public void baselineControl(ILocator baseline) throws DAVException {
        Assert.isNotNull(baseline);

        // Build the document body to describe the baseline control element.
        Document document = newDocument();
        Element root = ElementEditor.create(document, "baseline-control"); //$NON-NLS-1$
        ElementEditor.addChild(root, "baseline", //$NON-NLS-1$
                baseline.getResourceURL(), new String[] {"baseline"}, //$NON-NLS-1$
                true);

        // Send the baseline control method to the server and check the response.
        IResponse response = null;
        try {
            response = davClient.baselineControl(locator, newContext(), document);
            examineResponse(response);
        } catch (IOException e) {
            throw new SystemException(e);
        } finally {
            closeResponse(response);
        }
    }

Create a new version-controlled configuration on the given baseline.

@throws DAVException if the baseline control operation failed.
@see IServer#baselineControl(Locator, Context, Document)

Create a new version - controlled configuration on the given baseline .


public void bind(String member, ILocator source) throws DAVException {
        bind(member, source, false);
    }

public void bind ( String member , ILocator source ) throws DAVException { bind ( member , source , false ) ; }

Binds the given member in this collection to the resource identified
by the given source locator. If the member already exists, or is
already bound to a resource, it is not replaced.

@param member a member in this collection
@param source the location of a resource
@throws DAVException if the binding could not be created
@see #bind(String, Locator, boolean)
@see IServer#bind(Locator, Locator, Context)

Binds the given member in this collection to the resource identified by the given source locator . If the member already exists or is already bound to a resource it is not replaced .


public ILocator getMember(String memberName) {
        Assert.isTrue(locator.getLabel() == null);
        Assert.isTrue(!locator.isStable());
        String parentName = locator.getResourceURL();
        String childName;
        if (parentName.endsWith("/")) //$NON-NLS-1$
            childName = parentName + memberName;
        else
            childName = parentName + "/" + memberName; //$NON-NLS-1$
        return davClient.getDAVFactory().newLocator(childName);
    }

public ILocator getMember ( String memberName ) { Assert . isTrue ( locator . getLabel ( ) == null ) ; Assert . isTrue ( ! locator . isStable ( ) ) ; String parentName = locator . getResourceURL ( ) ; String childName ; if ( parentName . endsWith ( "/" ) ) //$NON-NLS-1$ childName = parentName + memberName ; else childName = parentName + "/" + memberName ; //$NON-NLS-1$ return davClient . getDAVFactory ( ) . newLocator ( childName ) ; }

Return the locator of the member of this collection, with the given
name.  Does NOT perform a call to the server to check the existence
of the member.

@param memberName the name of the receiver's internal member.
@return the Locator for the member.

Return the locator of the member of this collection with the given name . Does NOT perform a call to the server to check the existence of the member .


public void optimize() {
        final List<BaseVertex> sorted = new ArrayList<BaseVertex>( this.vertices );

        Collections.sort(sorted, new Comparator<BaseVertex>() {
            public int compare(final BaseVertex v1, final BaseVertex v2) {
                int v1OutDegree = v1.getSourceConnections().size();
                int v2OutDegree = v2.getSourceConnections().size();

                if (v1OutDegree < v2OutDegree) {
                    return 1;
                }

                if (v1OutDegree > v2OutDegree) {
                    return -1;
                }

                return 0;
            }
        });

        final LinkedList<BaseVertex> optimized = new LinkedList<BaseVertex>();

        boolean front = false;

        for ( final Iterator<BaseVertex> vertexIter = sorted.iterator(); vertexIter.hasNext(); ) {
            final BaseVertex vertex = vertexIter.next();

            if ( front ) {
                optimized.addFirst( vertex );
            } else {
                optimized.addLast( vertex );
            }

            front = !front;
        }

        this.vertices = optimized;
    }

public void optimize ( ) { final List < BaseVertex > sorted = new ArrayList < BaseVertex > ( this . vertices ) ; Collections . sort ( sorted , new Comparator < BaseVertex > ( ) { public int compare ( final BaseVertex v1 , final BaseVertex v2 ) { int v1OutDegree = v1 . getSourceConnections ( ) . size ( ) ; int v2OutDegree = v2 . getSourceConnections ( ) . size ( ) ; if ( v1OutDegree < v2OutDegree ) { return 1 ; } if ( v1OutDegree > v2OutDegree ) { return - 1 ; } return 0 ; } } ) ; final LinkedList < BaseVertex > optimized = new LinkedList < BaseVertex > ( ) ; boolean front = false ; for ( final Iterator < BaseVertex > vertexIter = sorted . iterator ( ) ; vertexIter . hasNext ( ) ; ) { final BaseVertex vertex = vertexIter . next ( ) ; if ( front ) { optimized . addFirst ( vertex ) ; } else { optimized . addLast ( vertex ) ; } front = ! front ; } this . vertices = optimized ; }

Optimizing vertices for optimal presentation


private void initializeControls() {
        if (originalFile != null) {
            resourceGroup.setContainerFullPath(originalFile.getParent()
                    .getFullPath());
            String fileName = originalFile.getName();
            int index = fileName.lastIndexOf(".");
            if (index != -1) {
                fileName = fileName.substring(0, index);
            }
            fileName += "-image.png";
            resourceGroup.setResource(fileName);
        } else if (originalName != null) {
            resourceGroup.setResource(originalName);
        }
        setDialogComplete(validatePage());
    }

private void initializeControls ( ) { if ( originalFile != null ) { resourceGroup . setContainerFullPath ( originalFile . getParent ( ) . getFullPath ( ) ) ; String fileName = originalFile . getName ( ) ; int index = fileName . lastIndexOf ( "." ) ; if ( index != - 1 ) { fileName = fileName . substring ( 0 , index ) ; } fileName += "-image.png" ; resourceGroup . setResource ( fileName ) ; } else if ( originalName != null ) { resourceGroup . setResource ( originalName ) ; } setDialogComplete ( validatePage ( ) ) ; }

Initializes the controls of this dialog.

Initializes the controls of this dialog .


private boolean validatePage() {
        if (!resourceGroup.areAllValuesValid()) {
            if (!resourceGroup.getResource().equals("")) { //$NON-NLS-1$
                setErrorMessage(resourceGroup.getProblemMessage());
            } else {
                setErrorMessage(null);
            }
            return false;
        }

        String resourceName = resourceGroup.getResource();
        IWorkspace workspace = ResourcesPlugin.getWorkspace();

        // Do not allow a closed project to be selected
        IPath fullPath = resourceGroup.getContainerFullPath();
        if (fullPath != null) {
            String projectName = fullPath.segment(0);
            IStatus isValidProjectName = workspace.validateName(projectName, IResource.PROJECT);
            if(isValidProjectName.isOK()) {
                IProject project = workspace.getRoot().getProject(projectName);
                if(!project.isOpen()) {
                    setErrorMessage(IDEWorkbenchMessages.SaveAsDialog_closedProjectMessage);
                    return false;
                }
            }
        }

        IStatus result = workspace.validateName(resourceName, IResource.FILE);
        if (!result.isOK()){
            setErrorMessage(result.getMessage());
            return false;
        }

        setErrorMessage(null);
        return true;
    }

Returns whether this page's visual components all contain valid values.

@return true if valid, and false otherwise

Returns whether this page s visual components all contain valid values .


public static EntityTag generateEntityTag() {
        String xx = basetime + ":" + Integer.toHexString(Thread.currentThread().hashCode()); //$NON-NLS-1$
        bcnt++;
        xx += ":" + bcnt; //$NON-NLS-1$
        return new EntityTag(xx);
    }

public static EntityTag generateEntityTag ( ) { String xx = basetime + ":" + Integer . toHexString ( Thread . currentThread ( ) . hashCode ( ) ) ; //$NON-NLS-1$ bcnt ++ ; xx += ":" + bcnt ; //$NON-NLS-1$ return new EntityTag ( xx ) ; }

Construct a unique EntityTag. The tag is constructed by concatening the
current time with the current thread's hash code.

@return a unique entity tag that servers may use for any purpose

Construct a unique EntityTag . The tag is constructed by concatening the current time with the current thread s hash code .


public BaseVertex getOpposite(BaseVertex vertex) {
        // If null or not part of this connection
        if ( vertex == null || (!vertex.equals( getSource() ) && !vertex.equals( getTarget() )) ) {
            return null;
        }
        if ( vertex.equals( getSource() ) ) {
            return getTarget();
        }
        return getSource();
    }

Gets opposite of specified vertex.

Returning null if specified not does not belong into this connection.

@param vertex
@return opposite of vertex


private boolean validate_otps(List<String> otps, NameCallback nameCb) throws LoginException {
		boolean validated = false;

		for (String otp : otps) {
			log.trace("Checking OTP {}", otp);

			VerificationResponse ykr;
			try {
				ykr = this.yc.verify(otp);
			} catch (YubicoVerificationException e) {
				log.warn("Errors during validation: ", e);
				throw new LoginException("Errors during validation: " + e.getMessage());
			} catch (YubicoValidationFailure e) {
				log.warn("Something went very wrong during authentication: ", e);
				throw new LoginException("Something went very wrong during authentication: " + e.getMessage());
			}
			if (ykr != null) {
				log.trace("OTP {} verify result : {}", otp, ykr.getStatus().toString());
				if (ykr.getStatus() == ResponseStatus.OK) {
					String publicId = YubicoClient.getPublicId(otp);
					log.info("OTP verified successfully (YubiKey id {})", publicId);
					if (is_right_user(nameCb.getName(), publicId)) {
						this.principals.add(new YubikeyPrincipal(publicId, this.idRealm));
						/* Don't just return here, we want to "consume" all OTPs if
						 * more than one is provided.
						 */
						validated = true;
					}
				} else {
					log.debug("OTP validation returned {}", ykr.getStatus().toString());
				}
			}
		}

		return validated;
	}

Try to validate all the OTPs provided.
@param otps  Possible YubiKey OTPs
@param nameCb  JAAS callback to get authenticating username
@return  true if one or more of the OTPs validated OK, otherwise false
@throws LoginException for exceptions during validation, logging real exception at warn level


private boolean is_right_user(String username, String publicId) {
		log.debug("Check if YubiKey {} belongs to user {}", publicId, username);
		return this.ykmap.is_right_user(username, publicId);
	}

After validation of an OTP, check that it came from a YubiKey that actually
belongs to the user trying to authenticate.

@param username  Username to match against YubiKey publicId.
@param publicId  The public ID of the authenticated YubiKey.
@return true if the username matched the YubiKey, false otherwise

After validation of an OTP check that it came from a YubiKey that actually belongs to the user trying to authenticate .


private String get_username_for_id(String publicId, String filename) throws FileNotFoundException {
		Scanner sc = null;
		File file = new File(filename);
		try {
			sc = new Scanner(file);
			while (sc.hasNextLine()) {
				String line = sc.nextLine();
				if (line.startsWith("yk." + publicId + ".user")) {
					String ykuser = line.split("=")[1].trim();

					return ykuser;
				}
			}
		} finally {
			if (sc != null) {
				sc.close();
			}
		}
		return null;
	}

private String get_username_for_id ( String publicId , String filename ) throws FileNotFoundException { Scanner sc = null ; File file = new File ( filename ) ; try { sc = new Scanner ( file ) ; while ( sc . hasNextLine ( ) ) { String line = sc . nextLine ( ) ; if ( line . startsWith ( "yk." + publicId + ".user" ) ) { String ykuser = line . split ( "=" ) [ 1 ] . trim ( ) ; return ykuser ; } } } finally { if ( sc != null ) { sc . close ( ) ; } } return null ; }

Given publicId "vvcccccfhc", scans filename for a line like "yk.vvcccccfhc.user = alice"
and returns "alice" if found. Null is returned in case there is no matching line in file.

@param publicId YubiKey public ID to scan for
@param filename name of the file to scan
@return String username
@throws FileNotFoundException if the filename does not match an existing file

Given publicId vvcccccfhc scans filename for a line like yk . vvcccccfhc . user = alice and returns alice if found . Null is returned in case there is no matching line in file .


private void add_yubikey_to_user(String publicId, String username, String filename) {
		try {
			File file = new File(filename);
			FileWriter writer = new FileWriter(file, true);
			writer.write("yk." + publicId + ".user = " + username
					+ System.getProperty("line.separator"));
			writer.close();
		} catch (IOException ex) {
			log.error("Failed appending entry to file {}", filename, ex);
		}
	}

private
void
add_yubikey_to_user
(
String
publicId
,
String
username
,
String
filename
)
{
try
{
File
file
=
new
File
(
filename
)
;
FileWriter
writer
=
new
FileWriter
(
file
,
true
)
;
writer
.
write
(
"yk."
+
publicId
+
".user = "
+
username
+
System
.
getProperty
(
"line.separator"
)
)
;
writer
.
close
(
)
;
}
catch
(
IOException
ex
)
{
log
.
error
(
"Failed appending entry to file {}"
,
filename
,
ex
)
;
}
}

Stores an association between username and YubiKey publicId in filename.

@param publicId YubiKey public ID to associate with user
@param username username to associate with a YubiKey public ID
@param filename name of the file to store to

Stores an association between username and YubiKey publicId in filename .


boolean verify_otp(String userName, String otp) {
		try {
			String authString = userName + ":" + otp;
			String authStringEnc = Base64.encodeBase64URLSafeString(authString.getBytes());

			BufferedReader in = attemptAuthentication(authStringEnc);

			String inputLine;
			while ((inputLine = in.readLine()) != null) {
				if (inputLine.contains(expectedOutput)) {
					return true;
				}
			}
		} catch (Exception ex) {
			log.error("Failed verifying OATH OTP :", ex);
		}
		return false;
	}

boolean
verify_otp
(
String
userName
,
String
otp
)
{
try
{
String
authString
=
userName
+
":"
+
otp
;
String
authStringEnc
=
Base64
.
encodeBase64URLSafeString
(
authString
.
getBytes
(
)
)
;
BufferedReader
in
=
attemptAuthentication
(
authStringEnc
)
;
String
inputLine
;
while
(
(
inputLine
=
in
.
readLine
(
)
)
!=
)
{
if
(
inputLine
.
contains
(
expectedOutput
)
)
{
return
true
;
}
}
}
catch
(
Exception
ex
)
{
log
.
error
(
"Failed verifying OATH OTP :"
,
ex
)
;
}
return
false
;
}

Access protectedUrl using userName and otp for basic auth.
Check if what we get back contains expectedOutput.
@param userName
@param otp
@return boolean

Access protectedUrl using userName and otp for basic auth . Check if what we get back contains expectedOutput .


public void clearPassword() {
		for (char pw[] : this.secrets) {
			for (int i = 0; i < pw.length; i++) {
				pw[i] = 0;
			}
		}

		/* Now discard the list. */
		this.secrets = new ArrayList<char []>();
	}

public
void
clearPassword
(
)
{
for
(
char
pw
[
]
:
this
.
secrets
)
{
for
(
int
i
=
0
;
i
<
pw
.
length
;
i
++
)
{
pw
[
i
]
=
0
;
}
}
/* Now discard the list. */
this
.
secrets
=
new
ArrayList
<
char
[
]
>
(
)
;
}

Tries to clear all the passwords from memory.

Tries to clear all the passwords from memory .


public static String getPublicId(String otp) {
		if ((otp == null) || (otp.length() < OTP_MIN_LEN)){
			//not a valid OTP format, throw an exception
			throw new IllegalArgumentException("The OTP is too short to be valid");
		}

		Integer len = otp.length();

		/* The OTP part is always the last 32 bytes of otp. Whatever is before that
		 * (if anything) is the public ID of the YubiKey. The ID can be set to ''
		 * through personalization.
		 */
		return otp.substring(0, len - 32).toLowerCase();
	}

Extract the public ID of a YubiKey from an OTP it generated.

@param otp	The OTP to extract ID from, in modhex format.

@return string	Public ID of YubiKey that generated otp. Between 0 and 12 lower-case characters.

@throws IllegalArgumentException for arguments that are null or too short to be valid OTP strings.

Extract the public ID of a YubiKey from an OTP it generated .


public static boolean isValidOTPFormat(String otp) {
		if (otp == null){
			return false;
		}
		int len = otp.length();
		for (char c : otp.toCharArray()) {
			if (c < 0x20 || c > 0x7E) {
				return false;
			}
		}
		return OTP_MIN_LEN <= len && len <= OTP_MAX_LEN;
	}

public static boolean isValidOTPFormat ( String otp ) { if ( otp == null ) { return false ; } int len = otp . length ( ) ; for ( char c : otp . toCharArray ( ) ) { if ( c < 0x20 || c > 0x7E ) { return false ; } } return OTP_MIN_LEN <= len && len <= OTP_MAX_LEN ; }

Determines whether a given OTP is of the correct length
and only contains printable characters, as per the recommendation.

@param otp The OTP to validate
@return boolean Returns true if it's valid; false otherwise

Determines whether a given OTP is of the correct length and only contains printable characters as per the recommendation .


public Evaluation create(SimpleNode node, Object source)
    {
        return create(node, source, false);
    }

public Evaluation create ( SimpleNode node , Object source ) { return create ( node , source , false ) ; }

Returns an Evaluation that contains the node, source and whether it
is a set operation.  If there are no Evaluation objects in the
pool one is created and returned.

Returns an Evaluation that contains the node source and whether it is a set operation . If there are no Evaluation objects in the pool one is created and returned .


public Evaluation create(SimpleNode node, Object source, boolean setOperation)
    {
        // synchronization is removed as we do not rely anymore on the in-house object pooling
        return new Evaluation(node, source, setOperation);
    }

Returns an Evaluation that contains the node, source and whether it
is a set operation.

Returns an Evaluation that contains the node source and whether it is a set operation .


public static void clearCache()
    {
        _methodParameterTypesCache.clear();
        _ctorParameterTypesCache.clear();
        _propertyDescriptorCache.clear();
        _constructorCache.clear();
        _staticMethodCache.clear();
        _instanceMethodCache.clear();
        _invokePermissionCache.clear();
        _fieldCache.clear();
        _superclasses.clear();
        _declaredMethods[0].clear();
        _declaredMethods[1].clear();
        _methodAccessCache.clear();
        _methodPermCache.clear();
    }

public static void clearCache ( ) { _methodParameterTypesCache . clear ( ) ; _ctorParameterTypesCache . clear ( ) ; _propertyDescriptorCache . clear ( ) ; _constructorCache . clear ( ) ; _staticMethodCache . clear ( ) ; _instanceMethodCache . clear ( ) ; _invokePermissionCache . clear ( ) ; _fieldCache . clear ( ) ; _superclasses . clear ( ) ; _declaredMethods [ 0 ] . clear ( ) ; _declaredMethods [ 1 ] . clear ( ) ; _methodAccessCache . clear ( ) ; _methodPermCache . clear ( ) ; }

Clears all of the cached reflection information normally used
to improve the speed of expressions that operate on the same classes
or are executed multiple times.

Warning: Calling this too often can be a huge performance
drain on your expressions - use with care.

Clears all of the cached reflection information normally used to improve the speed of expressions that operate on the same classes or are executed multiple times .


public static boolean isJdk15()
    {
        if (_jdkChecked)
            return _jdk15;

        try
        {
            Class.forName("java.lang.annotation.Annotation");
            _jdk15 = true;
        } catch (Exception e) { /* ignore */ }

        _jdkChecked = true;

        return _jdk15;
    }

public
static
boolean
isJdk15
(
)
{
if
(
_jdkChecked
)
return
_jdk15
;
try
{
Class
.
forName
(
"java.lang.annotation.Annotation"
)
;
_jdk15
=
true
;
}
catch
(
Exception
e
)
{
/* ignore */
}
_jdkChecked
=
true
;
return
_jdk15
;
}

Checks if the current jvm is java language >= 1.5 compatible.

@return True if jdk15 features are present.

Checks if the current jvm is java language > = 1 . 5 compatible .


public static String getPackageName(Object o)
    {
        return (o == null) ? null : getClassPackageName(o.getClass());
    }

public static String getPackageName ( Object o ) { return ( o == null ) ? null : getClassPackageName ( o . getClass ( ) ) ; }

Returns the package name of the object's class.

Returns the package name of the object s class .


public static String getClassPackageName(Class c)
    {
        String s = c.getName();
        int i = s.lastIndexOf('.');

        return (i < 0) ? null : s.substring(0, i);
    }

public static String getClassPackageName ( Class c ) { String s = c . getName ( ) ; int i = s . lastIndexOf ( ' ' ) ; return ( i < 0 ) ? null : s . substring ( 0 , i ) ; }

Returns the package name of the class given.

Returns the package name of the class given .


public static String getUniqueDescriptor(Object object, boolean fullyQualified)
    {
        StringBuffer result = new StringBuffer();

        if (object != null) {
            if (object instanceof Proxy) {
                Class interfaceClass = object.getClass().getInterfaces()[0];

                result.append(getClassName(interfaceClass, fullyQualified));
                result.append('^');
                object = Proxy.getInvocationHandler(object);
            }
            result.append(getClassName(object, fullyQualified));
            result.append('@');
            result.append(getPointerString(object));
        } else {
            result.append(NULL_OBJECT_STRING);
        }
        return new String(result);
    }

public static String getUniqueDescriptor ( Object object , boolean fullyQualified ) { StringBuffer result = new StringBuffer ( ) ; if ( object != null ) { if ( object instanceof Proxy ) { Class interfaceClass = object . getClass ( ) . getInterfaces ( ) [ 0 ] ; result . append ( getClassName ( interfaceClass , fullyQualified ) ) ; result . append ( ' ' ) ; object = Proxy . getInvocationHandler ( object ) ; } result . append ( getClassName ( object , fullyQualified ) ) ; result . append ( ' ' ) ; result . append ( getPointerString ( object ) ) ; } else { result . append ( NULL_OBJECT_STRING ) ; } return new String ( result ) ; }

Returns a unique descriptor string that includes the object's class and a unique integer
identifier. If fullyQualified is true then the class name will be fully qualified to include
the package name, else it will be just the class' base name.

Returns a unique descriptor string that includes the object s class and a unique integer identifier . If fullyQualified is true then the class name will be fully qualified to include the package name else it will be just the class base name .


public static final Class getArgClass(Object arg)
    {
        if (arg == null)
            return null;
        Class c = arg.getClass();
        if (c == Boolean.class)
            return Boolean.TYPE;
        else if (c.getSuperclass() == Number.class) {
            if (c == Integer.class)
                return Integer.TYPE;
            if (c == Double.class)
                return Double.TYPE;
            if (c == Byte.class)
                return Byte.TYPE;
            if (c == Long.class)
                return Long.TYPE;
            if (c == Float.class)
                return Float.TYPE;
            if (c == Short.class)
                return Short.TYPE;
        } else if (c == Character.class)
            return Character.TYPE;
        return c;
    }

public static final Class getArgClass ( Object arg ) { if ( arg == null ) return null ; Class c = arg . getClass ( ) ; if ( c == Boolean . class ) return Boolean . TYPE ; else if ( c . getSuperclass ( ) == Number . class ) { if ( c == Integer . class ) return Integer . TYPE ; if ( c == Double . class ) return Double . TYPE ; if ( c == Byte . class ) return Byte . TYPE ; if ( c == Long . class ) return Long . TYPE ; if ( c == Float . class ) return Float . TYPE ; if ( c == Short . class ) return Short . TYPE ; } else if ( c == Character . class ) return Character . TYPE ; return c ; }

Gets the class for a method argument that is appropriate for looking up methods by
reflection, by looking for the standard primitive wrapper classes and exchanging for them
their underlying primitive class objects. Other classes are passed through unchanged.

@param arg an object that is being passed to a method
@return the class to use to look up the method

Gets the class for a method argument that is appropriate for looking up methods by reflection by looking for the standard primitive wrapper classes and exchanging for them their underlying primitive class objects . Other classes are passed through unchanged .


public static final boolean isMoreSpecific(Class[] classes1, Class[] classes2)
    {
        for (int index = 0, count = classes1.length; index < count; ++index) {
            Class c1 = classes1[index], c2 = classes2[index];
            if (c1 == c2)
                continue;
            else if (c1.isPrimitive())
                return true;
            else if (c1.isAssignableFrom(c2))
                return false;
            else if (c2.isAssignableFrom(c1))
                return true;
        }

        // They are the same! So the first is not more specific than the second.
        return false;
    }

Tells whether the first array of classes is more specific than the second. Assumes that the
two arrays are of the same length.

Tells whether the first array of classes is more specific than the second . Assumes that the two arrays are of the same length .


public static Method getAppropriateMethod(OgnlContext context, Object source, Object target, String propertyName,
                                              String methodName, List methods, Object[] args, Object[] actualArgs)
    {
        Method result = null;

        if (methods != null)
        {
            Class typeClass = target != null ? target.getClass() : null;
            if (typeClass == null && source != null && Class.class.isInstance(source))
            {
                typeClass = (Class)source;
            }
            Class[] argClasses = getArgClasses(args);

            MatchingMethod mm = findBestMethod(methods, typeClass, methodName, argClasses);
            if (mm != null) {
                result = mm.mMethod;
                Class[] mParameterTypes = mm.mParameterTypes;
                System.arraycopy(args, 0, actualArgs, 0, args.length);

                for (int j = 0; j < mParameterTypes.length; j++)
                {
                    Class type = mParameterTypes[j];

                    if (mm.report.conversionNeeded[j] || (type.isPrimitive() && (actualArgs[j] == null)))
                    {
                        actualArgs[j] = getConvertedType(context, source, result, propertyName, args[j], type);
                    }
                }
            }
        }

        if (result == null)
        {
            result = getConvertedMethodAndArgs(context, target, propertyName, methods, args, actualArgs);
        }

        return result;
    }

public static Method getAppropriateMethod ( OgnlContext context , Object source , Object target , String propertyName , String methodName , List methods , Object [ ] args , Object [ ] actualArgs ) { Method result = null ; if ( methods != null ) { Class typeClass = target != null ? target . getClass ( ) : null ; if ( typeClass == null && source != null && Class . class . isInstance ( source ) ) { typeClass = ( Class ) source ; } Class [ ] argClasses = getArgClasses ( args ) ; MatchingMethod mm = findBestMethod ( methods , typeClass , methodName , argClasses ) ; if ( mm != null ) { result = mm . mMethod ; Class [ ] mParameterTypes = mm . mParameterTypes ; System . arraycopy ( args , 0 , actualArgs , 0 , args . length ) ; for ( int j = 0 ; j < mParameterTypes . length ; j ++ ) { Class type = mParameterTypes [ j ] ; if ( mm . report . conversionNeeded [ j ] || ( type . isPrimitive ( ) && ( actualArgs [ j ] == null ) ) ) { actualArgs [ j ] = getConvertedType ( context , source , result , propertyName , args [ j ] , type ) ; } } } } if ( result == null ) { result = getConvertedMethodAndArgs ( context , target , propertyName , methods , args , actualArgs ) ; } return result ; }

Gets the appropriate method to be called for the given target, method name and arguments. If
successful this method will return the Method within the target that can be called and the
converted arguments in actualArgs. If unsuccessful this method will return null and the
actualArgs will be empty.

@param context The current execution context.
@param source Target object to run against or method name.
@param target Instance of object to be run against.
@param propertyName Name of property to get method of.
@param methods List of current known methods.
@param args Arguments originally passed in.
@param actualArgs Converted arguments.

@return Best method match or null if none could be found.

Gets the appropriate method to be called for the given target method name and arguments . If successful this method will return the Method within the target that can be called and the converted arguments in actualArgs . If unsuccessful this method will return null and the actualArgs will be empty .


public static final Object getMethodValue(OgnlContext context, Object target, String propertyName,
                                              boolean checkAccessAndExistence)
            throws OgnlException, IllegalAccessException, NoSuchMethodException, IntrospectionException
    {
        Object result = null;
        Method m = getGetMethod(context, (target == null) ? null : target.getClass() , propertyName);
        if (m == null)
            m = getReadMethod((target == null) ? null : target.getClass(), propertyName, null);

        if (checkAccessAndExistence)
        {
            if ((m == null) || !context.getMemberAccess().isAccessible(context, target, m, propertyName))
            {
                result = NotFound;
            }
        }
        if (result == null) {
            if (m != null) {
                try {
                    result = invokeMethod(target, m, NoArguments);
                } catch (InvocationTargetException ex) {
                    throw new OgnlException(propertyName, ex.getTargetException());
                }
            } else {
                throw new NoSuchMethodException(propertyName);
            }
        }
        return result;
    }

public static final Object getMethodValue ( OgnlContext context , Object target , String propertyName , boolean checkAccessAndExistence ) throws OgnlException , IllegalAccessException , NoSuchMethodException , IntrospectionException { Object result = null ; Method m = getGetMethod ( context , ( target == null ) ? null : target . getClass ( ) , propertyName ) ; if ( m == null ) m = getReadMethod ( ( target == null ) ? null : target . getClass ( ) , propertyName , null ) ; if ( checkAccessAndExistence ) { if ( ( m == null ) || ! context . getMemberAccess ( ) . isAccessible ( context , target , m , propertyName ) ) { result = NotFound ; } } if ( result == null ) { if ( m != null ) { try { result = invokeMethod ( target , m , NoArguments ) ; } catch ( InvocationTargetException ex ) { throw new OgnlException ( propertyName , ex . getTargetException ( ) ) ; } } else { throw new NoSuchMethodException ( propertyName ) ; } } return result ; }

If the checkAccessAndExistence flag is true this method will check to see if the method
exists and if it is accessible according to the context's MemberAccess. If neither test
passes this will return NotFound.

If the checkAccessAndExistence flag is true this method will check to see if the method exists and if it is accessible according to the context s MemberAccess . If neither test passes this will return NotFound .


public static Map getPropertyDescriptors(Class targetClass)
            throws IntrospectionException, OgnlException
    {
        Map result;

        if ((result = (Map) _propertyDescriptorCache.get(targetClass)) == null)
        {
            synchronized (_propertyDescriptorCache) {
                if ((result = (Map) _propertyDescriptorCache.get(targetClass)) == null)
                {
                    PropertyDescriptor[] pda = Introspector.getBeanInfo(targetClass).getPropertyDescriptors();

                    result = new HashMap(101);
                    for (int i = 0, icount = pda.length; i < icount; i++)
                    {
                        // workaround for Introspector bug 6528714 (bugs.sun.com)
                        if (pda[i].getReadMethod() != null && !isMethodCallable(pda[i].getReadMethod()))
                        {
                            pda[i].setReadMethod(findClosestMatchingMethod(targetClass, pda[i].getReadMethod(), pda[i].getName(),
                                                                           pda[i].getPropertyType(), true));
                        }
                        if (pda[i].getWriteMethod() != null && !isMethodCallable(pda[i].getWriteMethod()))
                        {
                            pda[i].setWriteMethod(findClosestMatchingMethod(targetClass, pda[i].getWriteMethod(), pda[i].getName(),
                                                                            pda[i].getPropertyType(), false));
                        }

                        result.put(pda[i].getName(), pda[i]);
                    }

                    findObjectIndexedPropertyDescriptors(targetClass, result);
                    _propertyDescriptorCache.put(targetClass, result);
                }
            }
        }
        return result;
    }

This method returns the property descriptors for the given class as a Map.

@param targetClass The class to get the descriptors for.
@return Map map of property descriptors for class.

@throws IntrospectionException on errors using {@link Introspector}.
@throws OgnlException On general errors.

This method returns the property descriptors for the given class as a Map .


public static PropertyDescriptor getPropertyDescriptorFromArray(Class targetClass, String name)
            throws IntrospectionException
    {
        PropertyDescriptor result = null;
        PropertyDescriptor[] pda = getPropertyDescriptorsArray(targetClass);

        for (int i = 0, icount = pda.length; (result == null) && (i < icount); i++) {
            if (pda[i].getName().compareTo(name) == 0) {
                result = pda[i];
            }
        }
        return result;
    }

public static PropertyDescriptor getPropertyDescriptorFromArray ( Class targetClass , String name ) throws IntrospectionException { PropertyDescriptor result = null ; PropertyDescriptor [ ] pda = getPropertyDescriptorsArray ( targetClass ) ; for ( int i = 0 , icount = pda . length ; ( result == null ) && ( i < icount ) ; i ++ ) { if ( pda [ i ] . getName ( ) . compareTo ( name ) == 0 ) { result = pda [ i ] ; } } return result ; }

Gets the property descriptor with the given name for the target class given.

@param targetClass Class for which property descriptor is desired
@param name        Name of property
@return PropertyDescriptor of the named property or null if the class has no property with
the given name

Gets the property descriptor with the given name for the target class given .


public static Method getReadMethod(Class target, String name)
    {
        return getReadMethod(target, name, null);
    }

public static Method getReadMethod ( Class target , String name ) { return getReadMethod ( target , name , null ) ; }

Finds the best possible match for a method on the specified target class with a matching
name.

The name matched will also try different combinations like is + name, has + name, get + name, etc..

@param target
The class to find a matching method against.
@param name
The name of the method.
@return The most likely matching {@link Method}, or null if none could be found.

Finds the best possible match for a method on the specified target class with a matching name .


public char readChar() throws java.io.IOException
  {
     if (inBuf > 0)
     {
        --inBuf;

        if (++bufpos == bufsize)
           bufpos = 0;

        return buffer[bufpos];
     }

     char c;

     if (++bufpos == available)
        AdjustBuffSize();

     if ((buffer[bufpos] = c = ReadByte()) == '\\')
     {
        UpdateLineColumn(c);

        int backSlashCnt = 1;

        for (;;) // Read all the backslashes
        {
           if (++bufpos == available)
              AdjustBuffSize();

           try
           {
              if ((buffer[bufpos] = c = ReadByte()) != '\\')
              {
                 UpdateLineColumn(c);
                 // found a non-backslash char.
                 if ((c == 'u') && ((backSlashCnt & 1) == 1))
                 {
                    if (--bufpos < 0)
                       bufpos = bufsize - 1;

                    break;
                 }

                 backup(backSlashCnt);
                 return '\\';
              }
           }
           catch(java.io.IOException e)
           {
              if (backSlashCnt > 1)
                 backup(backSlashCnt-1);

              return '\\';
           }

           UpdateLineColumn(c);
           backSlashCnt++;
        }

        // Here, we have seen an odd number of backslash's followed by a 'u'
        try
        {
           while ((c = ReadByte()) == 'u')
              ++column;

           buffer[bufpos] = c = (char)(hexval(c) << 12 |
                                       hexval(ReadByte()) << 8 |
                                       hexval(ReadByte()) << 4 |
                                       hexval(ReadByte()));

           column += 4;
        }
        catch(java.io.IOException e)
        {
           throw new Error("Invalid escape character at line " + line +
                                         " column " + column + ".");
        }

        if (backSlashCnt == 1)
           return c;
        else
        {
           backup(backSlashCnt - 1);
           return '\\';
        }
     }
     else
     {
        UpdateLineColumn(c);
        return c;
     }
  }


final public void projection() throws ParseException {
                              /*@bgen(jjtree) Project */
  ASTProject jjtn000 = new ASTProject(JJTPROJECT);
  boolean jjtc000 = true;
  jjtree.openNodeScope(jjtn000);
    try {
      jj_consume_token(54);
      expression();
      jj_consume_token(55);
    } catch (Throwable jjte000) {
      if (jjtc000) {
        jjtree.clearNodeScope(jjtn000);
        jjtc000 = false;
      } else {
        jjtree.popNode();
      }
      if (jjte000 instanceof RuntimeException) {
        {if (true) throw (RuntimeException)jjte000;}
      }
      if (jjte000 instanceof ParseException) {
        {if (true) throw (ParseException)jjte000;}
      }
      {if (true) throw (Error)jjte000;}
    } finally {
      if (jjtc000) {
        jjtree.closeNodeScope(jjtn000, true);
      }
    }
  }

final
public
void
projection
(
)
throws
ParseException
{
/*@bgen(jjtree) Project */
ASTProject
jjtn000
=
new
ASTProject
(
JJTPROJECT
)
;
boolean
jjtc000
=
true
;
jjtree
.
openNodeScope
(
jjtn000
)
;
try
{
jj_consume_token
(
54
)
;
expression
(
)
;
jj_consume_token
(
55
)
;
}
catch
(
Throwable
jjte000
)
{
if
(
jjtc000
)
{
jjtree
.
clearNodeScope
(
jjtn000
)
;
jjtc000
=
false
;
}
else
{
jjtree
.
popNode
(
)
;
}
if
(
jjte000
instanceof
RuntimeException
)
{
{
if
(
true
)
throw
(
RuntimeException
)
jjte000
;
}
}
if
(
jjte000
instanceof
ParseException
)
{
{
if
(
true
)
throw
(
ParseException
)
jjte000
;
}
}
{
if
(
true
)
throw
(
Error
)
jjte000
;
}
}
finally
{
if
(
jjtc000
)
{
jjtree
.
closeNodeScope
(
jjtn000
,
true
)
;
}
}
}

Apply an expression to all elements of a collection, creating a new collection
as the result.

Apply an expression to all elements of a collection creating a new collection as the result .


final public void selectAll() throws ParseException {
                            /*@bgen(jjtree) Select */
  ASTSelect jjtn000 = new ASTSelect(JJTSELECT);
  boolean jjtc000 = true;
  jjtree.openNodeScope(jjtn000);
    try {
      jj_consume_token(54);
      jj_consume_token(3);
      expression();
      jj_consume_token(55);
    } catch (Throwable jjte000) {
      if (jjtc000) {
        jjtree.clearNodeScope(jjtn000);
        jjtc000 = false;
      } else {
        jjtree.popNode();
      }
      if (jjte000 instanceof RuntimeException) {
        {if (true) throw (RuntimeException)jjte000;}
      }
      if (jjte000 instanceof ParseException) {
        {if (true) throw (ParseException)jjte000;}
      }
      {if (true) throw (Error)jjte000;}
    } finally {
      if (jjtc000) {
        jjtree.closeNodeScope(jjtn000, true);
      }
    }
  }

final
public
void
selectAll
(
)
throws
ParseException
{
/*@bgen(jjtree) Select */
ASTSelect
jjtn000
=
new
ASTSelect
(
JJTSELECT
)
;
boolean
jjtc000
=
true
;
jjtree
.
openNodeScope
(
jjtn000
)
;
try
{
jj_consume_token
(
54
)
;
jj_consume_token
(
3
)
;
expression
(
)
;
jj_consume_token
(
55
)
;
}
catch
(
Throwable
jjte000
)
{
if
(
jjtc000
)
{
jjtree
.
clearNodeScope
(
jjtn000
)
;
jjtc000
=
false
;
}
else
{
jjtree
.
popNode
(
)
;
}
if
(
jjte000
instanceof
RuntimeException
)
{
{
if
(
true
)
throw
(
RuntimeException
)
jjte000
;
}
}
if
(
jjte000
instanceof
ParseException
)
{
{
if
(
true
)
throw
(
ParseException
)
jjte000
;
}
}
{
if
(
true
)
throw
(
Error
)
jjte000
;
}
}
finally
{
if
(
jjtc000
)
{
jjtree
.
closeNodeScope
(
jjtn000
,
true
)
;
}
}
}

Apply a boolean expression to all elements of a collection, creating a new collection
containing those elements for which the expression returned true.

Apply a boolean expression to all elements of a collection creating a new collection containing those elements for which the expression returned true .


public static long longValue(Object value)
        throws NumberFormatException
    {
        if (value == null) return 0L;
        Class c = value.getClass();
        if (c.getSuperclass() == Number.class) return ((Number) value).longValue();
        if (c == Boolean.class) return ((Boolean) value).booleanValue() ? 1 : 0;
        if (c == Character.class) return ((Character) value).charValue();
        return Long.parseLong(stringValue(value, true));
    }

public static long longValue ( Object value ) throws NumberFormatException { if ( value == null ) return 0L ; Class c = value . getClass ( ) ; if ( c . getSuperclass ( ) == Number . class ) return ( ( Number ) value ) . longValue ( ) ; if ( c == Boolean . class ) return ( ( Boolean ) value ) . booleanValue ( ) ? 1 : 0 ; if ( c == Character . class ) return ( ( Character ) value ) . charValue ( ) ; return Long . parseLong ( stringValue ( value , true ) ) ; }

Evaluates the given object as a long integer.

@param value
an object to interpret as a long integer
@return the long integer value implied by the given object
@throws NumberFormatException
if the given object can't be understood as a long integer

Evaluates the given object as a long integer .


public static double doubleValue(Object value)
        throws NumberFormatException
    {
        if (value == null) return 0.0;
        Class c = value.getClass();
        if (c.getSuperclass() == Number.class) return ((Number) value).doubleValue();
        if (c == Boolean.class) return ((Boolean) value).booleanValue() ? 1 : 0;
        if (c == Character.class) return ((Character) value).charValue();
        String s = stringValue(value, true);

        return (s.length() == 0) ? 0.0 : Double.parseDouble(s);
    }

public static double doubleValue ( Object value ) throws NumberFormatException { if ( value == null ) return 0.0 ; Class c = value . getClass ( ) ; if ( c . getSuperclass ( ) == Number . class ) return ( ( Number ) value ) . doubleValue ( ) ; if ( c == Boolean . class ) return ( ( Boolean ) value ) . booleanValue ( ) ? 1 : 0 ; if ( c == Character . class ) return ( ( Character ) value ) . charValue ( ) ; String s = stringValue ( value , true ) ; return ( s . length ( ) == 0 ) ? 0.0 : Double . parseDouble ( s ) ; }

Evaluates the given object as a double-precision floating-point number.

@param value
an object to interpret as a double
@return the double value implied by the given object
@throws NumberFormatException
if the given object can't be understood as a double

Evaluates the given object as a double - precision floating - point number .


public static BigInteger bigIntValue(Object value)
        throws NumberFormatException
    {
        if (value == null) return BigInteger.valueOf(0L);
        Class c = value.getClass();
        if (c == BigInteger.class) return (BigInteger) value;
        if (c == BigDecimal.class) return ((BigDecimal) value).toBigInteger();
        if (c.getSuperclass() == Number.class) return BigInteger.valueOf(((Number) value).longValue());
        if (c == Boolean.class) return BigInteger.valueOf(((Boolean) value).booleanValue() ? 1 : 0);
        if (c == Character.class) return BigInteger.valueOf(((Character) value).charValue());
        return new BigInteger(stringValue(value, true));
    }

public static BigInteger bigIntValue ( Object value ) throws NumberFormatException { if ( value == null ) return BigInteger . valueOf ( 0L ) ; Class c = value . getClass ( ) ; if ( c == BigInteger . class ) return ( BigInteger ) value ; if ( c == BigDecimal . class ) return ( ( BigDecimal ) value ) . toBigInteger ( ) ; if ( c . getSuperclass ( ) == Number . class ) return BigInteger . valueOf ( ( ( Number ) value ) . longValue ( ) ) ; if ( c == Boolean . class ) return BigInteger . valueOf ( ( ( Boolean ) value ) . booleanValue ( ) ? 1 : 0 ) ; if ( c == Character . class ) return BigInteger . valueOf ( ( ( Character ) value ) . charValue ( ) ) ; return new BigInteger ( stringValue ( value , true ) ) ; }

Evaluates the given object as a BigInteger.

@param value
an object to interpret as a BigInteger
@return the BigInteger value implied by the given object
@throws NumberFormatException
if the given object can't be understood as a BigInteger

Evaluates the given object as a BigInteger .


public static BigDecimal bigDecValue(Object value)
        throws NumberFormatException
    {
        if (value == null) return BigDecimal.valueOf(0L);
        Class c = value.getClass();
        if (c == BigDecimal.class) return (BigDecimal) value;
        if (c == BigInteger.class) return new BigDecimal((BigInteger) value);
        if (c == Boolean.class) return BigDecimal.valueOf(((Boolean) value).booleanValue() ? 1 : 0);
        if (c == Character.class) return BigDecimal.valueOf(((Character) value).charValue());
        return new BigDecimal(stringValue(value, true));
    }

public static BigDecimal bigDecValue ( Object value ) throws NumberFormatException { if ( value == null ) return BigDecimal . valueOf ( 0L ) ; Class c = value . getClass ( ) ; if ( c == BigDecimal . class ) return ( BigDecimal ) value ; if ( c == BigInteger . class ) return new BigDecimal ( ( BigInteger ) value ) ; if ( c == Boolean . class ) return BigDecimal . valueOf ( ( ( Boolean ) value ) . booleanValue ( ) ? 1 : 0 ) ; if ( c == Character . class ) return BigDecimal . valueOf ( ( ( Character ) value ) . charValue ( ) ) ; return new BigDecimal ( stringValue ( value , true ) ) ; }

Evaluates the given object as a BigDecimal.

@param value
an object to interpret as a BigDecimal
@return the BigDecimal value implied by the given object
@throws NumberFormatException
if the given object can't be understood as a BigDecimal

Evaluates the given object as a BigDecimal .


public static String stringValue(Object value, boolean trim)
    {
        String result;

        if (value == null) {
            result = OgnlRuntime.NULL_STRING;
        } else {
            result = value.toString();
            if (trim) {
                result = result.trim();
            }
        }
        return result;
    }

public static String stringValue ( Object value , boolean trim ) { String result ; if ( value == null ) { result = OgnlRuntime . NULL_STRING ; } else { result = value . toString ( ) ; if ( trim ) { result = result . trim ( ) ; } } return result ; }

Evaluates the given object as a String and trims it if the trim flag is true.

@param value
an object to interpret as a String
@return the String value implied by the given object as returned by the toString() method, or
"null" if the object is null.

Evaluates the given object as a String and trims it if the trim flag is true .


public static int getNumericType(Object value)
    {
        if (value != null) {
            Class c = value.getClass();
            if (c == Integer.class) return INT;
            if (c == Double.class) return DOUBLE;
            if (c == Boolean.class) return BOOL;
            if (c == Byte.class) return BYTE;
            if (c == Character.class) return CHAR;
            if (c == Short.class) return SHORT;
            if (c == Long.class) return LONG;
            if (c == Float.class) return FLOAT;
            if (c == BigInteger.class) return BIGINT;
            if (c == BigDecimal.class) return BIGDEC;
        }
        return NONNUMERIC;
    }

public static int getNumericType ( Object value ) { if ( value != null ) { Class c = value . getClass ( ) ; if ( c == Integer . class ) return INT ; if ( c == Double . class ) return DOUBLE ; if ( c == Boolean . class ) return BOOL ; if ( c == Byte . class ) return BYTE ; if ( c == Character . class ) return CHAR ; if ( c == Short . class ) return SHORT ; if ( c == Long . class ) return LONG ; if ( c == Float . class ) return FLOAT ; if ( c == BigInteger . class ) return BIGINT ; if ( c == BigDecimal . class ) return BIGDEC ; } return NONNUMERIC ; }

Returns a constant from the NumericTypes interface that represents the numeric type of the
given object.

@param value
an object that needs to be interpreted as a number
@return the appropriate constant from the NumericTypes interface

Returns a constant from the NumericTypes interface that represents the numeric type of the given object .


public static Object convertValue(Object value, Class toType)
    {
        return convertValue(value, toType, false);
    }

public static Object convertValue ( Object value , Class toType ) { return convertValue ( value , toType , false ) ; }

Returns the value converted numerically to the given class type This method also detects when
arrays are being converted and converts the components of one array to the type of the other.

@param value
an object to be converted to the given type
@param toType
class type to be converted to
@return converted value of the type given, or value if the value cannot be converted to the
given type.

Returns the value converted numerically to the given class type This method also detects when arrays are being converted and converts the components of one array to the type of the other .


public static int getIntValue(Object value)
    {
        try
        {
            if (value == null)
                return -1;

            if (Number.class.isInstance(value)) {

                return ((Number)value).intValue();
            }

            String str = String.class.isInstance(value) ? (String)value : value.toString();

            return Integer.parseInt(str);
        }
        catch (Throwable t)
        {
            throw new RuntimeException("Error converting " + value + " to integer:", t);
        }
    }

public
static
int
getIntValue
(
Object
value
)
{
try
{
if
(
value
==
)
return
1
;
if
(
Number
.
class
.
isInstance
(
value
)
)
{
return
(
(
Number
)
value
)
.
intValue
(
)
;
}
String
str
=
String
.
class
.
isInstance
(
value
)
(
String
)
value
:
value
.
toString
(
)
;
return
Integer
.
parseInt
(
str
)
;
}
catch
(
Throwable
t
)
{
throw
new
RuntimeException
(
"Error converting "
+
value
+
" to integer:"
,
t
)
;
}
}

Converts the specified value to a primitive integer value.

Null values will cause a -1 to be returned.

{@link Number} instances have their intValue() methods invoked.

All other types result in calling Integer.parseInt(value.toString());

@param value
The object to get the value of.
@return A valid integer.

Converts the specified value to a primitive integer value .


public static int getNumericType(int t1, int t2, boolean canBeNonNumeric)
    {
        if (t1 == t2) return t1;

        if (canBeNonNumeric && (t1 == NONNUMERIC || t2 == NONNUMERIC || t1 == CHAR || t2 == CHAR)) return NONNUMERIC;

        if (t1 == NONNUMERIC) t1 = DOUBLE; // Try to interpret strings as doubles...
        if (t2 == NONNUMERIC) t2 = DOUBLE; // Try to interpret strings as doubles...

        if (t1 >= MIN_REAL_TYPE) {
            if (t2 >= MIN_REAL_TYPE) return Math.max(t1, t2);
            if (t2 < INT) return t1;
            if (t2 == BIGINT) return BIGDEC;
            return Math.max(DOUBLE, t1);
        } else if (t2 >= MIN_REAL_TYPE) {
            if (t1 < INT) return t2;
            if (t1 == BIGINT) return BIGDEC;
            return Math.max(DOUBLE, t2);
        } else return Math.max(t1, t2);
    }

Returns the constant from the NumericTypes interface that best expresses the type of an
operation, which can be either numeric or not, on the two given types.

@param t1
type of one argument to an operator
@param t2
type of the other argument
@param canBeNonNumeric
whether the operator can be interpreted as non-numeric
@return the appropriate constant from the NumericTypes interface

Returns the constant from the NumericTypes interface that best expresses the type of an operation which can be either numeric or not on the two given types .


public static int getNumericType(Object v1, Object v2, boolean canBeNonNumeric)
    {
        return getNumericType(getNumericType(v1), getNumericType(v2), canBeNonNumeric);
    }

public static int getNumericType ( Object v1 , Object v2 , boolean canBeNonNumeric ) { return getNumericType ( getNumericType ( v1 ) , getNumericType ( v2 ) , canBeNonNumeric ) ; }

Returns the constant from the NumericTypes interface that best expresses the type of an
operation, which can be either numeric or not, on the two given objects.

@param v1
one argument to an operator
@param v2
the other argument
@param canBeNonNumeric
whether the operator can be interpreted as non-numeric
@return the appropriate constant from the NumericTypes interface

Returns the constant from the NumericTypes interface that best expresses the type of an operation which can be either numeric or not on the two given objects .


public static Number newInteger(int type, long value)
    {
        switch(type) {
        case BOOL:
        case CHAR:
        case INT:
            return new Integer((int) value);

        case FLOAT:
            if ((long) (float) value == value) { return new Float((float) value); }
            // else fall through:
        case DOUBLE:
            if ((long) (double) value == value) { return new Double((double) value); }
            // else fall through:
        case LONG:
            return new Long(value);

        case BYTE:
            return new Byte((byte) value);

        case SHORT:
            return new Short((short) value);

        default:
            return BigInteger.valueOf(value);
        }
    }

public
static
Number
newInteger
(
int
type
,
long
value
)
{
switch
(
type
)
{
case
BOOL
:
case
CHAR
:
case
INT
:
return
new
Integer
(
(
int
)
value
)
;
case
FLOAT
:
if
(
(
long
)
(
float
)
value
==
value
)
{
return
new
Float
(
(
float
)
value
)
;
}
// else fall through:
case
DOUBLE
:
if
(
(
long
)
(
double
)
value
==
value
)
{
return
new
Double
(
(
double
)
value
)
;
}
// else fall through:
case
LONG
:
return
new
Long
(
value
)
;
case
BYTE
:
return
new
Byte
(
(
byte
)
value
)
;
case
SHORT
:
return
new
Short
(
(
short
)
value
)
;
default
:
return
BigInteger
.
valueOf
(
value
)
;
}
}

Returns a new Number object of an appropriate type to hold the given integer value. The type
of the returned object is consistent with the given type argument, which is a constant from
the NumericTypes interface.

@param type
the nominal numeric type of the result, a constant from the NumericTypes interface
@param value
the integer value to convert to a Number object
@return a Number object with the given value, of type implied by the type argument

Returns a new Number object of an appropriate type to hold the given integer value . The type of the returned object is consistent with the given type argument which is a constant from the NumericTypes interface .


public Evaluation popEvaluation()
    {
        Evaluation result;

        result = _currentEvaluation;
        setCurrentEvaluation(result.getParent());
        if (_currentEvaluation == null) {
            setLastEvaluation(getKeepLastEvaluation() ? result : null);
            setRootEvaluation(null);
            setCurrentNode(null);
        }
        return result;
    }

public Evaluation popEvaluation ( ) { Evaluation result ; result = _currentEvaluation ; setCurrentEvaluation ( result . getParent ( ) ) ; if ( _currentEvaluation == null ) { setLastEvaluation ( getKeepLastEvaluation ( ) ? result : null ) ; setRootEvaluation ( null ) ; setCurrentNode ( null ) ; } return result ; }

Pops the current Evaluation off of the top of the stack. This is done after a node has
completed its evaluation.

Pops the current Evaluation off of the top of the stack . This is done after a node has completed its evaluation .


protected String generateOgnlGetter(CtClass clazz, CtMethod valueGetter, CtField node)
            throws Exception
    {
        String body = "return " + node.getName() + ".getValue($1, $2);";

        valueGetter.setBody(body);
        clazz.addMethod(valueGetter);

        return body;
    }

protected
String
generateOgnlGetter
(
CtClass
clazz
,
CtMethod
valueGetter
,
CtField
node
)
throws
Exception
{
String
body
=
"return "
+
node
.
getName
(
)
+
".getValue($1, $2);"
;
valueGetter
.
setBody
(
body
)
;
clazz
.
addMethod
(
valueGetter
)
;
return
body
;
}

Fail safe getter creation when normal compilation fails.

@param clazz
The javassist class the new method should be attached to.
@param valueGetter
The method definition the generated code will be contained within.
@param node
The root expression node.
@return The generated source string for this method, the method will still be
added via the javassist API either way so this is really a convenience
for exception reporting / debugging.
@throws Exception
If a javassist error occurs.

Fail safe getter creation when normal compilation fails .


protected String generateOgnlSetter(CtClass clazz, CtMethod valueSetter, CtField node)
            throws Exception
    {
        String body = node.getName() + ".setValue($1, $2, $3);";

        valueSetter.setBody(body);
        clazz.addMethod(valueSetter);

        return body;
    }

protected
String
generateOgnlSetter
(
CtClass
clazz
,
CtMethod
valueSetter
,
CtField
node
)
throws
Exception
{
String
body
=
node
.
getName
(
)
+
".setValue($1, $2, $3);"
;
valueSetter
.
setBody
(
body
)
;
clazz
.
addMethod
(
valueSetter
)
;
return
body
;
}

Fail safe setter creation when normal compilation fails.

@param clazz
The javassist class the new method should be attached to.
@param valueSetter
The method definition the generated code will be contained within.
@param node
The root expression node.
@return The generated source string for this method, the method will still be
added via the javassist API either way so this is really a convenience
for exception reporting / debugging.
@throws Exception
If a javassist error occurs.

Fail safe setter creation when normal compilation fails .


protected void flattenTree()
    {
        boolean shouldFlatten = false;
        int newSize = 0;

        for (int i = 0; i < _children.length; ++i)
            if (_children[i].getClass() == getClass())
            {
                shouldFlatten = true;
                newSize += _children[i].jjtGetNumChildren();
            } else
                ++newSize;

        if (shouldFlatten)
        {
            Node[] newChildren = new Node[newSize];
            int j = 0;

            for (int i = 0; i < _children.length; ++i)
            {
                Node c = _children[i];
                if (c.getClass() == getClass())
                {
                    for (int k = 0; k < c.jjtGetNumChildren(); ++k)
                        newChildren[j++] = c.jjtGetChild(k);

                } else
                    newChildren[j++] = c;
            }

            if (j != newSize)
                throw new Error("Assertion error: " + j + " != " + newSize);

            _children = newChildren;
        }
    }

protected
void
flattenTree
(
)
{
boolean
shouldFlatten
=
false
;
int
newSize
=
0
;
for
(
int
i
=
0
;
i
<
_children
.
length
;
++
i
)
if
(
_children
[
i
]
.
getClass
(
)
==
getClass
(
)
)
{
shouldFlatten
=
true
;
newSize
+=
_children
[
i
]
.
jjtGetNumChildren
(
)
;
}
else
++
newSize
;
if
(
shouldFlatten
)
{
Node
[
]
newChildren
=
new
Node
[
newSize
]
;
int
j
=
0
;
for
(
int
i
=
0
;
i
<
_children
.
length
;
++
i
)
{
Node
c
=
_children
[
i
]
;
if
(
c
.
getClass
(
)
==
getClass
(
)
)
{
for
(
int
k
=
0
;
k
<
c
.
jjtGetNumChildren
(
)
;
++
k
)
newChildren
[
j
++
]
=
.
jjtGetChild
(
k
)
;
}
else
newChildren
[
j
++
]
=
c
;
}
if
(
j
!=
newSize
)
throw
new
Error
(
"Assertion error: "
+
j
+
" != "
+
newSize
)
;
_children
=
newChildren
;
}
}

This method may be called from subclasses' jjtClose methods. It flattens the tree under this node by eliminating any children that are of the same class as this
node and copying their children to this node.

This method may be called from subclasses jjtClose methods . It flattens the tree under this node by eliminating any children that are of the same class as this node and copying their children to this node .


public void init(SimpleNode node, Object source, boolean setOperation)
    {
        this.node = node;
        this.source = source;
        this.setOperation = setOperation;
        result = null;
        exception = null;
        parent = null;
        next = null;
        previous = null;
        firstChild = null;
        lastChild = null;
    }

public void init ( SimpleNode node , Object source , boolean setOperation ) { this . node = node ; this . source = source ; this . setOperation = setOperation ; result = null ; exception = null ; parent = null ; next = null ; previous = null ; firstChild = null ; lastChild = null ; }

Reinitializes this Evaluation to the parameters specified.

Reinitializes this Evaluation to the parameters specified .


private char escapeChar()
    {
        int ofs = image.length() - 1;
        switch ( image.charAt(ofs) ) {
            case 'n':   return '\n';
            case 'r':   return '\r';
            case 't':   return '\t';
            case 'b':   return '\b';
            case 'f':   return '\f';
            case '\\':  return '\\';
            case '\'':  return '\'';
            case '\"':  return '\"';
        }

          // Otherwise, it's an octal number.  Find the backslash and convert.
        while ( image.charAt(--ofs) != '\\' )
          {}
        int value = 0;
        while ( ++ofs < image.length() )
            value = (value << 3) | (image.charAt(ofs) - '0');
        return (char) value;
    }

Converts an escape sequence into a character value.

Converts an escape sequence into a character value .


public static void setRoot(Map context, Object root)
    {
        context.put(OgnlContext.ROOT_CONTEXT_KEY, root);
    }

public static void setRoot ( Map context , Object root ) { context . put ( OgnlContext . ROOT_CONTEXT_KEY , root ) ; }

Sets the root object to use for all expressions in the given context - doesn't necessarily replace
root object instances explicitly passed in to other expression resolving methods on this class.

@param context
The context to store the root object in.
@param root
The root object.

Sets the root object to use for all expressions in the given context - doesn t necessarily replace root object instances explicitly passed in to other expression resolving methods on this class .


public static Object getValue(String expression, Map context, Object root)
            throws OgnlException
    {
        return getValue(expression, context, root, null);
    }

public static Object getValue ( String expression , Map context , Object root ) throws OgnlException { return getValue ( expression , context , root , null ) ; }

Evaluates the given OGNL expression to extract a value from the given root object in a given
context

@see #parseExpression(String)
@see #getValue(Object,Object)
@param expression
the OGNL expression to be parsed
@param context
the naming context for the evaluation
@param root
the root object for the OGNL expression
@return the result of evaluating the expression
@throws MethodFailedException
if the expression called a method which failed
@throws NoSuchPropertyException
if the expression referred to a nonexistent property
@throws InappropriateExpressionException
if the expression can't be used in this context
@throws OgnlException
if there is a pathological environmental problem


public static void setValue(ExpressionAccessor expression, OgnlContext context,
                                Object root, Object value)
    {
        expression.set(context, root, value);
    }

public static void setValue ( ExpressionAccessor expression , OgnlContext context , Object root , Object value ) { expression . set ( context , root , value ) ; }

Sets the value given using the pre-compiled expression on the specified root
object.

@param expression
The pre-compiled expression, as found in {@link Node#getAccessor()}.
@param context
The ognl context.
@param root
The object to set the expression value on.
@param value
The value to set.

Sets the value given using the pre - compiled expression on the specified root object .


public static void setValue(Object tree, Object root, Object value)
            throws OgnlException
    {
        setValue(tree, createDefaultContext(root), root, value);
    }

public static void setValue ( Object tree , Object root , Object value ) throws OgnlException { setValue ( tree , createDefaultContext ( root ) , root , value ) ; }

Evaluates the given OGNL expression tree to insert a value into the object graph rooted at
the given root object.

@param tree
the OGNL expression tree to evaluate, as returned by parseExpression()
@param root
the root object for the OGNL expression
@param value
the value to insert into the object graph
@throws MethodFailedException
if the expression called a method which failed
@throws NoSuchPropertyException
if the expression referred to a nonexistent property
@throws InappropriateExpressionException
if the expression can't be used in this context
@throws OgnlException
if there is a pathological environmental problem

Evaluates the given OGNL expression tree to insert a value into the object graph rooted at the given root object .


public static boolean isConstant(String expression, Map context)
            throws OgnlException
    {
        return isConstant(parseExpression(expression), context);
    }

public static boolean isConstant ( String expression , Map context ) throws OgnlException { return isConstant ( parseExpression ( expression ) , context ) ; }

Checks if the specified expression represents a constant expression.

@param expression
The expression to check.
@param context
The context to use.

@return True if the node is a constant - false otherwise.
@throws OgnlException  If an error occurs checking the expression.

Checks if the specified expression represents a constant expression .


public static String getDefaultWatchServiceId()
    {
        String result = "polling";
        String osName = System.getProperty( "os.name" );
        if ( osName != null )
        {
            osName = osName.toLowerCase( Locale.ENGLISH );
            if ( osName.contains( "windows" ) || osName.contains( "linux" ) )
            {
                result = isAtLeastJava7() ? "jdk7" : "jnotify";
            }
            else if ( osName.contains( "mac" ) )
            {
                result = "jnotify";
            }
        }
        return result;
    }

public static String getDefaultWatchServiceId ( ) { String result = "polling" ; String osName = System . getProperty ( "os.name" ) ; if ( osName != null ) { osName = osName . toLowerCase ( Locale . ENGLISH ) ; if ( osName . contains ( "windows" ) || osName . contains ( "linux" ) ) { result = isAtLeastJava7 ( ) ? "jdk7" : "jnotify" ; } else if ( osName . contains ( "mac" ) ) { result = "jnotify" ; } } return result ; }

Returns default watch service identifier based on operating system.

@return watch service id

Returns default watch service identifier based on operating system .


protected void waitForServerStarted( String rootUrl, JavaRunnable runner, int startTimeout, boolean spawned )
        throws MojoExecutionException, IOException
    {
        long endTimeMillis = startTimeout > 0  ? System.currentTimeMillis() + startTimeout : 0L;
        boolean started = false;

        URL connectUrl = new URL( rootUrl );
        int verifyWaitDelay = 1000;
        while ( !started )
        {
            if ( startTimeout > 0 && endTimeMillis - System.currentTimeMillis() < 0L )
            {
                if ( spawned )
                {
                    InternalPlay2StopMojo internalStop = new InternalPlay2StopMojo();
                    internalStop.project = project;
                    try
                    {
                        internalStop.execute();
                    }
                    catch ( MojoExecutionException e )
                    {
                        // just ignore
                    }
                    catch ( MojoFailureException e )
                    {
                        // just ignore
                    }
                }
                throw new MojoExecutionException( String.format( "Failed to start Play! server in %d ms",
                                                                 Integer.valueOf( startTimeout ) ) );
            }

            BuildException runnerException = runner.getException();
            if ( runnerException != null )
            {
                throw new MojoExecutionException( "Play! server start exception", runnerException );
            }

            try
            {
                URLConnection conn = connectUrl.openConnection();
                if ( startTimeout > 0 )
                {
                    int connectTimeOut =
                        Long.valueOf( Math.min( endTimeMillis - System.currentTimeMillis(),
                                                Integer.valueOf( Integer.MAX_VALUE ).longValue() ) ).intValue();
                    if ( connectTimeOut > 0 )
                    {
                        conn.setConnectTimeout( connectTimeOut );
                    }
                }
                connectUrl.openConnection().getContent();
                started = true;
            }
            catch ( Exception e )
            {
                // return false;
            }

            if ( !started )
            {
                long sleepTime = verifyWaitDelay;
                if ( startTimeout > 0 )
                {
                    sleepTime = Math.min( sleepTime, endTimeMillis - System.currentTimeMillis() );
                }
                if ( sleepTime > 0 )
                {
                    try
                    {
                        Thread.sleep( sleepTime );
                    }
                    catch ( InterruptedException e )
                    {
                        throw new MojoExecutionException( "?", e );
                    }
                }
            }
        }
    }

protected
void
waitForServerStarted
(
String
rootUrl
,
JavaRunnable
runner
,
int
startTimeout
,
boolean
spawned
)
throws
MojoExecutionException
,
IOException
{
long
endTimeMillis
=
startTimeout
>
0
System
.
currentTimeMillis
(
)
+
startTimeout
:
0L
;
boolean
started
=
false
;
URL
connectUrl
=
new
URL
(
rootUrl
)
;
int
verifyWaitDelay
=
1000
;
while
(
!
started
)
{
if
(
startTimeout
>
0
&&
endTimeMillis
System
.
currentTimeMillis
(
)
<
0L
)
{
if
(
spawned
)
{
InternalPlay2StopMojo
internalStop
=
new
InternalPlay2StopMojo
(
)
;
internalStop
.
project
=
project
;
try
{
internalStop
.
execute
(
)
;
}
catch
(
MojoExecutionException
e
)
{
// just ignore
}
catch
(
MojoFailureException
e
)
{
// just ignore
}
}
throw
new
MojoExecutionException
(
String
.
format
(
"Failed to start Play! server in %d ms"
,
Integer
.
valueOf
(
startTimeout
)
)
)
;
}
BuildException
runnerException
=
runner
.
getException
(
)
;
if
(
runnerException
!=
)
{
throw
new
MojoExecutionException
(
"Play! server start exception"
,
runnerException
)
;
}
try
{
URLConnection
conn
=
connectUrl
.
openConnection
(
)
;
if
(
startTimeout
>
0
)
{
int
connectTimeOut
=
Long
.
valueOf
(
Math
.
min
(
endTimeMillis
System
.
currentTimeMillis
(
)
,
Integer
.
valueOf
(
Integer
.
MAX_VALUE
)
.
longValue
(
)
)
)
.
intValue
(
)
;
if
(
connectTimeOut
>
0
)
{
conn
.
setConnectTimeout
(
connectTimeOut
)
;
}
}
connectUrl
.
openConnection
(
)
.
getContent
(
)
;
started
=
true
;
}
catch
(
Exception
e
)
{
// return false;
}
if
(
!
started
)
{
long
sleepTime
=
verifyWaitDelay
;
if
(
startTimeout
>
0
)
{
sleepTime
=
Math
.
min
(
sleepTime
,
endTimeMillis
System
.
currentTimeMillis
(
)
)
;
}
if
(
sleepTime
>
0
)
{
try
{
Thread
.
sleep
(
sleepTime
)
;
}
catch
(
InterruptedException
e
)
{
throw
new
MojoExecutionException
(
"?"
,
e
)
;
}
}
}
}
}


private String readFileAsString()
        throws IOException
    {
        FileInputStream is = new FileInputStream( e.source() );
        try
        {
            byte[] buffer = new byte[8192];
            int len = is.read( buffer );
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            while ( len != -1 )
            {
                out.write( buffer, 0, len );
                len = is.read( buffer );
            }
            return charsetName != null ? new String( out.toByteArray(), charsetName ) : new String( out.toByteArray() );
        }
        finally
        {
            is.close();
        }
    }

private String readFileAsString ( ) throws IOException { FileInputStream is = new FileInputStream ( e . source ( ) ) ; try { byte [ ] buffer = new byte [ 8192 ] ; int len = is . read ( buffer ) ; ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ; while ( len != - 1 ) { out . write ( buffer , 0 , len ) ; len = is . read ( buffer ) ; } return charsetName != null ? new String ( out . toByteArray ( ) , charsetName ) : new String ( out . toByteArray ( ) ) ; } finally { is . close ( ) ; } }

copied from AbstractPlay2SourcePositionMapper . java


@Override /* BuildLink interface */
    public synchronized Object reload()
    {
        Object result = null;
        try
        {
            boolean reloadRequired = buildLink.build();

            if ( reloadRequired )
            {
                int version = ++classLoaderVersion;
                String name = "ReloadableClassLoader(v" + version + ")";
                currentApplicationClassLoader =
                    new DelegatedResourcesClassLoader( name, toUrls( outputDirectories ), baseLoader );
                result = currentApplicationClassLoader;
            }
        }
        catch ( MalformedURLException e )
        {
            throw new UnexpectedException( "Unexpected reloader exception", e ); //??
        }
        catch ( Play2BuildFailure e )
        {
            result =
                new CompilationException( e.getMessage(), e.line(), e.position(),
                                          e.source() != null ? e.source().getAbsolutePath() : null, e.input() );
        }
        catch ( Play2BuildError e )
        {
            result = new UnexpectedException( e.getMessage(), e.getCause() ); //??
        }

        return result;
    }

@
Override
/* BuildLink interface */
public
synchronized
Object
reload
(
)
{
Object
result
=
;
try
{
boolean
reloadRequired
=
buildLink
.
build
(
)
;
if
(
reloadRequired
)
{
int
version
=
++
classLoaderVersion
;
String
name
=
"ReloadableClassLoader(v"
+
version
+
")"
;
currentApplicationClassLoader
=
new
DelegatedResourcesClassLoader
(
name
,
toUrls
(
outputDirectories
)
,
baseLoader
)
;
result
=
currentApplicationClassLoader
;
}
}
catch
(
MalformedURLException
e
)
{
throw
new
UnexpectedException
(
"Unexpected reloader exception"
,
e
)
;
//??
}
catch
(
Play2BuildFailure
e
)
{
result
=
new
CompilationException
(
e
.
getMessage
(
)
,
e
.
line
(
)
,
e
.
position
(
)
,
e
.
source
(
)
!=
e
.
source
(
)
.
getAbsolutePath
(
)
:
,
e
.
input
(
)
)
;
}
catch
(
Play2BuildError
e
)
{
result
=
new
UnexpectedException
(
e
.
getMessage
(
)
,
e
.
getCause
(
)
)
;
//??
}
return
result
;
}

Contrary to its name, this doesn't necessarily reload the app.  It is invoked on every request, and will only
trigger a reload of the app if something has changed.

Since this communicates across classloaders, it must return only simple objects.

@return Either
- Throwable - If something went wrong (eg, a compile error).
- ClassLoader - If the classloader has changed, and the application should be reloaded.
- null - If nothing changed.

Contrary to its name this doesn t necessarily reload the app . It is invoked on every request and will only trigger a reload of the app if something has changed .


protected Archiver getArchiver( String archiverName )
        throws NoSuchArchiverException
    {
        Archiver result = archiverManager.getArchiver( archiverName );
        result.setDuplicateBehavior( Archiver.DUPLICATES_FAIL ); // Just in case
        return result;
    }

protected
Archiver
getArchiver
(
String
archiverName
)
throws
NoSuchArchiverException
{
Archiver
result
=
archiverManager
.
getArchiver
(
archiverName
)
;
result
.
setDuplicateBehavior
(
Archiver
.
DUPLICATES_FAIL
)
;
// Just in case
return
result
;
}

Returns preconfigured archiver

@param archiverName archiver name
@return archiver
@throws NoSuchArchiverException for unsupported archiver name


protected void checkArchiverForProblems( Archiver archiver )
    {
        for ( ResourceIterator iter = archiver.getResources(); iter.hasNext(); )
        {
            iter.next();
        }
    }

protected void checkArchiverForProblems ( Archiver archiver ) { for ( ResourceIterator iter = archiver . getResources ( ) ; iter . hasNext ( ) ; ) { iter . next ( ) ; } }

Check for potential "Duplicate file" exception before archive processing starts

@param archiver archiver to check

Check for potential Duplicate file exception before archive processing starts


protected String readFileAsString( File file )
        throws IOException
    {
        FileInputStream is = new FileInputStream( file );
        try
        {
            byte[] buffer = new byte[8192];
            int len = is.read( buffer );
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            while ( len != -1 )
            {
                out.write( buffer, 0, len );
                len = is.read( buffer );
            }
            return charsetName != null ? new String( out.toByteArray(), charsetName ) : new String( out.toByteArray() );
        }
        finally
        {
            is.close();
        }
    }

protected String readFileAsString ( File file ) throws IOException { FileInputStream is = new FileInputStream ( file ) ; try { byte [ ] buffer = new byte [ 8192 ] ; int len = is . read ( buffer ) ; ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ; while ( len != - 1 ) { out . write ( buffer , 0 , len ) ; len = is . read ( buffer ) ; } return charsetName != null ? new String ( out . toByteArray ( ) , charsetName ) : new String ( out . toByteArray ( ) ) ; } finally { is . close ( ) ; } }

Reads the content of the file to a string.

@param file a file to read the content of
@return the content of the file
@throws IOException I/O exception when reading from the file

Reads the content of the file to a string .


protected Project createProject()
    {
        final Project antProject = new Project();

        final ProjectHelper helper = ProjectHelper.getProjectHelper();
        antProject.addReference( ProjectHelper.PROJECTHELPER_REFERENCE, helper );
        helper.getImportStack().addElement( "AntBuilder" ); // import checks that stack is not empty

        final BuildLogger logger = new NoBannerLogger();

        logger.setMessageOutputLevel( Project.MSG_INFO );
        logger.setOutputPrintStream( System.out );
        logger.setErrorPrintStream( System.err );

        antProject.addBuildListener( logger );

        antProject.init();
        antProject.getBaseDir();
        return antProject;
    }

Creates and configures Ant project for Java task.

@return Ant project for Java task

Creates and configures Ant project for Java task .


protected void addSystemProperty( Java java, String propertyName, String propertyValue )
    {
        Environment.Variable sysPropPlayHome = new Environment.Variable();
        sysPropPlayHome.setKey( propertyName );
        sysPropPlayHome.setValue( propertyValue );
        java.addSysproperty( sysPropPlayHome );
    }

protected void addSystemProperty ( Java java , String propertyName , String propertyValue ) { Environment . Variable sysPropPlayHome = new Environment . Variable ( ) ; sysPropPlayHome . setKey ( propertyName ) ; sysPropPlayHome . setValue ( propertyValue ) ; java . addSysproperty ( sysPropPlayHome ) ; }

Adds string type system property to Ant Java task.

@param java Ant Java task
@param propertyName system property name
@param propertyValue system property value

Adds string type system property to Ant Java task .


protected void addSystemProperty( Java java, String propertyName, File propertyValue )
    {
        Environment.Variable sysPropPlayHome = new Environment.Variable();
        sysPropPlayHome.setKey( propertyName );
        sysPropPlayHome.setFile( propertyValue );
        java.addSysproperty( sysPropPlayHome );
    }

protected void addSystemProperty ( Java java , String propertyName , File propertyValue ) { Environment . Variable sysPropPlayHome = new Environment . Variable ( ) ; sysPropPlayHome . setKey ( propertyName ) ; sysPropPlayHome . setFile ( propertyValue ) ; java . addSysproperty ( sysPropPlayHome ) ; }

Adds file type system property to Ant Java task.

@param java Ant Java task
@param propertyName system property name
@param propertyValue system property value

Adds file type system property to Ant Java task .


private void openNewFolderDialog() {
        @SuppressLint("InflateParams")
        final View dialogView = getActivity().getLayoutInflater().inflate(
                R.layout.dialog_new_folder, null);
        final TextView msgView = (TextView) dialogView.findViewById(R.id.msgText);
        final EditText editText = (EditText) dialogView.findViewById(R.id.editText);
        editText.setText(mNewDirectoryName);
        msgView.setText(getString(R.string.create_folder_msg, mNewDirectoryName));

        final AlertDialog alertDialog = new AlertDialog.Builder(getActivity())
                .setTitle(R.string.create_folder_label)
                .setView(dialogView)
                .setNegativeButton(R.string.cancel_label,
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(final DialogInterface dialog, final int which) {
                                dialog.dismiss();
                            }
                        })
                .setPositiveButton(R.string.confirm_label,
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(final DialogInterface dialog, final int which) {
                                dialog.dismiss();
                                mNewDirectoryName = editText.getText().toString();
                                final int msg = createFolder();
                                Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
                            }
                        })
                .show();

        alertDialog.getButton(DialogInterface.BUTTON_POSITIVE).setEnabled(editText.getText().length() != 0);

        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(final CharSequence charSequence, final int i, final int i2, final int i3) {

            }

            @Override
            public void onTextChanged(final CharSequence charSequence, final int i, final int i2, final int i3) {
                final boolean textNotEmpty = charSequence.length() != 0;
                alertDialog.getButton(DialogInterface.BUTTON_POSITIVE).setEnabled(textNotEmpty);
                msgView.setText(getString(R.string.create_folder_msg, charSequence.toString()));
            }

            @Override
            public void afterTextChanged(final Editable editable) {

            }
        });

        editText.setVisibility(mConfig.allowNewDirectoryNameModification()
                ? View.VISIBLE : View.GONE);
    }

private void openNewFolderDialog ( ) { @ SuppressLint ( "InflateParams" ) final View dialogView = getActivity ( ) . getLayoutInflater ( ) . inflate ( R . layout . dialog_new_folder , null ) ; final TextView msgView = ( TextView ) dialogView . findViewById ( R . id . msgText ) ; final EditText editText = ( EditText ) dialogView . findViewById ( R . id . editText ) ; editText . setText ( mNewDirectoryName ) ; msgView . setText ( getString ( R . string . create_folder_msg , mNewDirectoryName ) ) ; final AlertDialog alertDialog = new AlertDialog . Builder ( getActivity ( ) ) . setTitle ( R . string . create_folder_label ) . setView ( dialogView ) . setNegativeButton ( R . string . cancel_label , new DialogInterface . OnClickListener ( ) { @ Override public void onClick ( final DialogInterface dialog , final int which ) { dialog . dismiss ( ) ; } } ) . setPositiveButton ( R . string . confirm_label , new DialogInterface . OnClickListener ( ) { @ Override public void onClick ( final DialogInterface dialog , final int which ) { dialog . dismiss ( ) ; mNewDirectoryName = editText . getText ( ) . toString ( ) ; final int msg = createFolder ( ) ; Toast . makeText ( getActivity ( ) , msg , Toast . LENGTH_SHORT ) . show ( ) ; } } ) . show ( ) ; alertDialog . getButton ( DialogInterface . BUTTON_POSITIVE ) . setEnabled ( editText . getText ( ) . length ( ) != 0 ) ; editText . addTextChangedListener ( new TextWatcher ( ) { @ Override public void beforeTextChanged ( final CharSequence charSequence , final int i , final int i2 , final int i3 ) { } @ Override public void onTextChanged ( final CharSequence charSequence , final int i , final int i2 , final int i3 ) { final boolean textNotEmpty = charSequence . length ( ) != 0 ; alertDialog . getButton ( DialogInterface . BUTTON_POSITIVE ) . setEnabled ( textNotEmpty ) ; msgView . setText ( getString ( R . string . create_folder_msg , charSequence . toString ( ) ) ) ; } @ Override public void afterTextChanged ( final Editable editable ) { } } ) ; editText . setVisibility ( mConfig . allowNewDirectoryNameModification ( ) ? View . VISIBLE : View . GONE ) ; }

Shows a confirmation dialog that asks the user if he wants to create a
new folder. User can modify provided name, if it was not disallowed.

Shows a confirmation dialog that asks the user if he wants to create a new folder . User can modify provided name if it was not disallowed .


private void changeDirectory(final File dir) {
        if (dir == null) {
            debug("Could not change folder: dir was null");
        } else if (!dir.isDirectory()) {
            debug("Could not change folder: dir is no directory");
        } else {
            final File[] contents = dir.listFiles();
            if (contents != null) {
                int numDirectories = 0;
                for (final File f : contents) {
                    if (f.isDirectory()) {
                        numDirectories++;
                    }
                }
                mFilesInDir = new File[numDirectories];
                mFilenames.clear();
                for (int i = 0, counter = 0; i < numDirectories; counter++) {
                    if (contents[counter].isDirectory()) {
                        mFilesInDir[i] = contents[counter];
                        mFilenames.add(contents[counter].getName());
                        i++;
                    }
                }
                Arrays.sort(mFilesInDir);
                Collections.sort(mFilenames);
                mSelectedDir = dir;
                mTxtvSelectedFolder.setText(dir.getAbsolutePath());
                mListDirectoriesAdapter.notifyDataSetChanged();
                mFileObserver = createFileObserver(dir.getAbsolutePath());
                mFileObserver.startWatching();
                debug("Changed directory to %s", dir.getAbsolutePath());
            } else {
                debug("Could not change folder: contents of dir were null");
            }
        }
        refreshButtonState();
    }

Change the directory that is currently being displayed.

@param dir The file the activity should switch to. This File must be
non-null and a directory, otherwise the displayed directory
will not be changed

Change the directory that is currently being displayed .


private void refreshButtonState() {
        final Activity activity = getActivity();
        if (activity != null && mSelectedDir != null) {
            mBtnConfirm.setEnabled(isValidFile(mSelectedDir));
            getActivity().invalidateOptionsMenu();
        }
    }

private void refreshButtonState ( ) { final Activity activity = getActivity ( ) ; if ( activity != null && mSelectedDir != null ) { mBtnConfirm . setEnabled ( isValidFile ( mSelectedDir ) ) ; getActivity ( ) . invalidateOptionsMenu ( ) ; } }

Changes the state of the buttons depending on the currently selected file
or folder.

Changes the state of the buttons depending on the currently selected file or folder .


private FileObserver createFileObserver(final String path) {
        return new FileObserver(path, FileObserver.CREATE | FileObserver.DELETE
                | FileObserver.MOVED_FROM | FileObserver.MOVED_TO) {

            @Override
            public void onEvent(final int event, final String path) {
                debug("FileObserver received event %d", event);
                final Activity activity = getActivity();

                if (activity != null) {
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            refreshDirectory();
                        }
                    });
                }
            }
        };
    }

private
FileObserver
createFileObserver
(
final
String
path
)
{
return
new
FileObserver
(
path
,
FileObserver
.
CREATE
|
FileObserver
.
DELETE
|
FileObserver
.
MOVED_FROM
|
FileObserver
.
MOVED_TO
)
{
@
Override
public
void
onEvent
(
final
int
event
,
final
String
path
)
{
debug
(
"FileObserver received event %d"
,
event
)
;
final
Activity
activity
=
getActivity
(
)
;
if
(
activity
!=
)
{
activity
.
runOnUiThread
(
new
Runnable
(
)
{
@
Override
public
void
run
(
)
{
refreshDirectory
(
)
;
}
}
)
;
}
}
}
;
}

Sets up a FileObserver to watch the current directory.

Sets up a FileObserver to watch the current directory .


private void returnSelectedFolder() {
        if (mSelectedDir != null) {
            debug("Returning %s as result", mSelectedDir.getAbsolutePath());
            mListener.foreach(new UnitFunction<OnFragmentInteractionListener>() {
                @Override
                public void apply(final OnFragmentInteractionListener f) {
                    f.onSelectDirectory(mSelectedDir.getAbsolutePath());
                }
            });
        } else {
            mListener.foreach(new UnitFunction<OnFragmentInteractionListener>() {
                @Override
                public void apply(final OnFragmentInteractionListener f) {
                    f.onCancelChooser();
                }
            });
        }

    }

private
void
returnSelectedFolder
(
)
{
if
(
mSelectedDir
!=
)
{
debug
(
"Returning %s as result"
,
mSelectedDir
.
getAbsolutePath
(
)
)
;
mListener
.
foreach
(
new
UnitFunction
<
OnFragmentInteractionListener
>
(
)
{
@
Override
public
void
apply
(
final
OnFragmentInteractionListener
f
)
{
f
.
onSelectDirectory
(
mSelectedDir
.
getAbsolutePath
(
)
)
;
}
}
)
;
}
else
{
mListener
.
foreach
(
new
UnitFunction
<
OnFragmentInteractionListener
>
(
)
{
@
Override
public
void
apply
(
final
OnFragmentInteractionListener
f
)
{
f
.
onCancelChooser
(
)
;
}
}
)
;
}
}

Returns the selected folder as a result to the activity the fragment's attached to. The
selected folder can also be null.

Returns the selected folder as a result to the activity the fragment s attached to . The selected folder can also be null .


private int createFolder() {
        if (mNewDirectoryName != null && mSelectedDir != null
                && mSelectedDir.canWrite()) {
            final File newDir = new File(mSelectedDir, mNewDirectoryName);
            if (newDir.exists()) {
                return R.string.create_folder_error_already_exists;
            } else {
                final boolean result = newDir.mkdir();
                if (result) {
                    return R.string.create_folder_success;
                } else {
                    return R.string.create_folder_error;
                }
            }
        } else if (mSelectedDir != null && !mSelectedDir.canWrite()) {
            return R.string.create_folder_error_no_write_access;
        } else {
            return R.string.create_folder_error;
        }
    }

private int createFolder ( ) { if ( mNewDirectoryName != null && mSelectedDir != null && mSelectedDir . canWrite ( ) ) { final File newDir = new File ( mSelectedDir , mNewDirectoryName ) ; if ( newDir . exists ( ) ) { return R . string . create_folder_error_already_exists ; } else { final boolean result = newDir . mkdir ( ) ; if ( result ) { return R . string . create_folder_success ; } else { return R . string . create_folder_error ; } } } else if ( mSelectedDir != null && ! mSelectedDir . canWrite ( ) ) { return R . string . create_folder_error_no_write_access ; } else { return R . string . create_folder_error ; } }

Creates a new folder in the current directory with the name
CREATE_DIRECTORY_NAME.

Creates a new folder in the current directory with the name CREATE_DIRECTORY_NAME .


private boolean isValidFile(final File file) {
        return (file != null && file.isDirectory() && file.canRead() &&
                (mConfig.allowReadOnlyDirectory() || file.canWrite()));
    }

private boolean isValidFile ( final File file ) { return ( file != null && file . isDirectory ( ) && file . canRead ( ) && ( mConfig . allowReadOnlyDirectory ( ) || file . canWrite ( ) ) ) ; }

Returns true if the selected file or directory would be valid selection.

Returns true if the selected file or directory would be valid selection .


public void startBackgroundJob(int msgId, Runnable runnable) {
        // make the progress dialog uncancelable, so that we can guarantee
        // that the thread is done before the activity gets destroyed
        ProgressDialog dialog = ProgressDialog.show(this, null, getString(msgId), true, false);
        Job<Object> managedJob = new Job<Object>(runnable, dialog);
        managedJob.runBackgroundJob();
    }

Start a background job showing a progress bar as long as the job runs.
This seems contradictory but with background job we mean one that runs off
the ui thread to prevent an ANR.
We still have to wait for the processing to be done because we need the result.

Start a background job showing a progress bar as long as the job runs . This seems contradictory but with background job we mean one that runs off the ui thread to prevent an ANR . We still have to wait for the processing to be done because we need the result .


private void startList(boolean isOrderedList, Attributes attributes) {
        boolean isIndentation = isIndentation(attributes);

        ParagraphType newType = isIndentation && isOrderedList ? ParagraphType.INDENTATION_OL :
                isIndentation && !isOrderedList ? ParagraphType.INDENTATION_UL :
                        isOrderedList ? ParagraphType.NUMBERING :
                                ParagraphType.BULLET;

        AccumulatedParagraphStyle currentStyle = mParagraphStyles.isEmpty() ? null : mParagraphStyles.peek();

        if (currentStyle == null) {
            // no previous style found -> create new AccumulatedParagraphStyle with indentations of 1
            AccumulatedParagraphStyle newStyle = new AccumulatedParagraphStyle(newType, 1, 1);
            mParagraphStyles.push(newStyle);
        } else if (currentStyle.getType() == newType) {
            // same style found -> increase indentations by 1
            currentStyle.setAbsoluteIndent(currentStyle.getAbsoluteIndent() + 1);
            currentStyle.setRelativeIndent(currentStyle.getRelativeIndent() + 1);
        } else {
            // different style found -> create new AccumulatedParagraphStyle with incremented indentations
            AccumulatedParagraphStyle newStyle = new AccumulatedParagraphStyle(newType, currentStyle.getAbsoluteIndent() + 1, 1);
            mParagraphStyles.push(newStyle);
        }
    }


private void endList(boolean orderedList) {
        if (!mParagraphStyles.isEmpty()) {
            AccumulatedParagraphStyle style = mParagraphStyles.peek();
            ParagraphType type = style.getType();

            if ((orderedList && (type.isNumbering() || type == ParagraphType.INDENTATION_OL)) ||
                    (!orderedList && (type.isBullet() || type == ParagraphType.INDENTATION_UL))) {

                // the end tag matches the current style
                int indent = style.getRelativeIndent();
                if (indent > 1) {
                    style.setRelativeIndent(indent - 1);
                    style.setAbsoluteIndent(style.getAbsoluteIndent() - 1);
                } else {
                    mParagraphStyles.pop();
                }

            } else {

                // the end tag doesn't match the current style
                mParagraphStyles.pop();
                endList(orderedList);    // find the next matching style

            }
        }
    }