private boolean queryPreferPublic () {
    String prefer = System.getProperty(pPrefer);

    if (prefer == null) {
      if (resources==null) readProperties();
      if (resources==null) return defaultPreferPublic;
      try {
	prefer = resources.getString("prefer");
      } catch (MissingResourceException e) {
	return defaultPreferPublic;
      }
    }

    if (prefer == null) {
      return defaultPreferPublic;
    }

    return (prefer.equalsIgnoreCase("public"));
  }

private boolean queryPreferPublic ( ) { String prefer = System . getProperty ( pPrefer ) ; if ( prefer == null ) { if ( resources == null ) readProperties ( ) ; if ( resources == null ) return defaultPreferPublic ; try { prefer = resources . getString ( "prefer" ) ; } catch ( MissingResourceException e ) { return defaultPreferPublic ; } } if ( prefer == null ) { return defaultPreferPublic ; } return ( prefer . equalsIgnoreCase ( "public" ) ) ; }

Obtain the preferPublic setting from the properties.

In the properties, a value of 'public' is true,
anything else is false.

@return True if prefer is public or the
defaultPreferSetting.

Obtain the preferPublic setting from the properties .


private boolean queryUseStaticCatalog () {
    String staticCatalog = System.getProperty(pStatic);

    if (useStaticCatalog == null) {
      if (resources==null) readProperties();
      if (resources==null) return defaultUseStaticCatalog;
      try {
	staticCatalog = resources.getString("static-catalog");
      } catch (MissingResourceException e) {
	return defaultUseStaticCatalog;
      }
    }

    if (staticCatalog == null) {
      return defaultUseStaticCatalog;
    }

    return (staticCatalog.equalsIgnoreCase("true")
	    || staticCatalog.equalsIgnoreCase("yes")
	    || staticCatalog.equalsIgnoreCase("1"));
  }

private boolean queryUseStaticCatalog ( ) { String staticCatalog = System . getProperty ( pStatic ) ; if ( useStaticCatalog == null ) { if ( resources == null ) readProperties ( ) ; if ( resources == null ) return defaultUseStaticCatalog ; try { staticCatalog = resources . getString ( "static-catalog" ) ; } catch ( MissingResourceException e ) { return defaultUseStaticCatalog ; } } if ( staticCatalog == null ) { return defaultUseStaticCatalog ; } return ( staticCatalog . equalsIgnoreCase ( "true" ) || staticCatalog . equalsIgnoreCase ( "yes" ) || staticCatalog . equalsIgnoreCase ( "1" ) ) ; }

Obtain the static-catalog setting from the properties.

In the properties, a value of 'yes', 'true', or '1' is considered
true, anything else is false.

@return The static-catalog setting from the propertyFile or the
defaultUseStaticCatalog.

Obtain the static - catalog setting from the properties .


public InputSource resolveEntity (String publicId, String systemId) {
    String resolved = null;

    if (systemId != null && systemMap.containsKey(systemId)) {
      resolved = (String) systemMap.get(systemId);
    } else if (publicId != null && publicMap.containsKey(publicId)) {
      resolved = (String) publicMap.get(publicId);
    }

    if (resolved != null) {
      try {
	InputSource iSource = new InputSource(resolved);
	iSource.setPublicId(publicId);

	// Ideally this method would not attempt to open the
	// InputStream, but there is a bug (in Xerces, at least)
	// that causes the parser to mistakenly open the wrong
	// system identifier if the returned InputSource does
	// not have a byteStream.
	//
	// It could be argued that we still shouldn't do this here,
	// but since the purpose of calling the entityResolver is
	// almost certainly to open the input stream, it seems to
	// do little harm.
	//
	URL url = new URL(resolved);
	InputStream iStream = url.openStream();
	iSource.setByteStream(iStream);

	return iSource;
      } catch (Exception e) {
	// FIXME: silently fail?
	return null;
      }
    }

    return null;
  }


public Source resolve(String href, String base)
    throws TransformerException {

    String uri = href;
    int hashPos = href.indexOf("#");
    if (hashPos >= 0) {
      uri = href.substring(0, hashPos);
    }

    String result = null;
    if (href != null && uriMap.containsKey(href)) {
      result = (String) uriMap.get(href);
    }

    if (result == null) {
      try {
	URL url = null;

	if (base==null) {
	  url = new URL(uri);
	  result = url.toString();
	} else {
	  URL baseURL = new URL(base);
	  url = (href.length()==0 ? baseURL : new URL(baseURL, uri));
	  result = url.toString();
	}
      } catch (java.net.MalformedURLException mue) {
	// try to make an absolute URI from the current base
	String absBase = makeAbsolute(base);
	if (!absBase.equals(base)) {
	  // don't bother if the absBase isn't different!
	  return resolve(href, absBase);
	} else {
	  throw new TransformerException("Malformed URL "
					 + href + "(base " + base + ")",
					 mue);
	}
      }
    }

    SAXSource source = new SAXSource();
    source.setInputSource(new InputSource(result));
    return source;
  }


private String makeAbsolute(String uri) {
    if (uri == null) {
      uri = "";
    }

    try {
      URL url = new URL(uri);
      return url.toString();
    } catch (MalformedURLException mue) {
      String dir = System.getProperty("user.dir");
      String file = "";

      if (dir.endsWith("/")) {
	file = "file://" + dir + uri;
      } else {
	file = "file://" + dir + "/" + uri;
      }

      try {
	URL fileURL = new URL(file);
	return fileURL.toString();
      } catch (MalformedURLException mue2) {
	// bail
	return uri;
      }
    }
  }

private
String
makeAbsolute
(
String
uri
)
{
if
(
uri
==
)
{
uri
=
""
;
}
try
{
URL
url
=
new
URL
(
uri
)
;
return
url
.
toString
(
)
;
}
catch
(
MalformedURLException
mue
)
{
String
dir
=
System
.
getProperty
(
"user.dir"
)
;
String
file
=
""
;
if
(
dir
.
endsWith
(
"/"
)
)
{
file
=
"file://"
+
dir
+
uri
;
}
else
{
file
=
"file://"
+
dir
+
"/"
+
uri
;
}
try
{
URL
fileURL
=
new
URL
(
file
)
;
return
fileURL
.
toString
(
)
;
}
catch
(
MalformedURLException
mue2
)
{
// bail
return
uri
;
}
}
}


protected Class<?> resolveClass(ObjectStreamClass v)
         throws IOException, ClassNotFoundException
   {
      ClassLoader loader = Thread.currentThread().getContextClassLoader();
      String className = v.getName();
      try
      {
         // JDK 6, by default, only supports array types (ex. [[B)  using Class.forName()
         return Class.forName(className, false, loader);
      }
      catch (ClassNotFoundException cnfe)
      {
         Class cl = primClasses.get(className);
         if (cl == null)
            throw cnfe;
         else
            return cl;
      }
   }

Use the thread context class loader to resolve the class

@throws java.io.IOException Any exception thrown by the underlying OutputStream.


protected void invokeSetter(String value) {
      try {
         // coerce value to field type
         Class<?> type = descriptor.getPropertyType();
         PropertyEditor editor = PropertyEditors.findEditor(type);
         editor.setAsText(value);
         Object coerced = editor.getValue();
         // System.out.println("type: " + type);
         // System.out.println("coerced: " + coerced);

         // invoke the setter method
         setter.invoke(instance, new Object[] { coerced });
      }
      catch (InvocationTargetException e) {
         Throwable target = e.getTargetException();
         if (target instanceof PropertyException) {
            throw (PropertyException)target;
         }
         else {
            throw new PropertyException(target);
         }
      }
      catch (Exception e) {
         throw new PropertyException(e);
      }
   }

Coerce and invoke the property setter method on the instance.

@param value   Method value.

@throws PropertyException     Failed to invoke setter method.

Coerce and invoke the property setter method on the instance .


public static String getLocalName(Element element) {
	String name = element.getTagName();

	if (name.indexOf(':') > 0) {
	    name = name.substring(name.indexOf(':')+1);
	}

	return name;
    }

public static String getLocalName ( Element element ) { String name = element . getTagName ( ) ; if ( name . indexOf ( ' ' ) > 0 ) { name = name . substring ( name . indexOf ( ' ' ) + 1 ) ; } return name ; }

Returns the "localname" part of a QName, which is the whole
name if it has no prefix.

@param element The QName of an element.
@return The local part of a QName.

Returns the localname part of a QName which is the whole name if it has no prefix .


public static String getNamespaceURI(Node node, String prefix) {
	if (node == null || node.getNodeType() != Node.ELEMENT_NODE) {
	    return null;
	}

	if (prefix.equals("")) {
	    if (((Element) node).hasAttribute("xmlns")) {
		return ((Element) node).getAttribute("xmlns");
	    }
	} else {
	    String nsattr = "xmlns:" + prefix;
	    if (((Element) node).hasAttribute(nsattr)) {
		return ((Element) node).getAttribute(nsattr);
	    }
	}

	return getNamespaceURI(node.getParentNode(), prefix);
    }

public static String getNamespaceURI ( Node node , String prefix ) { if ( node == null || node . getNodeType ( ) != Node . ELEMENT_NODE ) { return null ; } if ( prefix . equals ( "" ) ) { if ( ( ( Element ) node ) . hasAttribute ( "xmlns" ) ) { return ( ( Element ) node ) . getAttribute ( "xmlns" ) ; } } else { String nsattr = "xmlns:" + prefix ; if ( ( ( Element ) node ) . hasAttribute ( nsattr ) ) { return ( ( Element ) node ) . getAttribute ( nsattr ) ; } } return getNamespaceURI ( node . getParentNode ( ) , prefix ) ; }

Returns the namespace URI for the specified prefix at the
specified context node.

@param node The context node.
@param prefix The prefix.
@return The namespace URI associated with the prefix, or
null if no namespace declaration exists for the prefix.

Returns the namespace URI for the specified prefix at the specified context node .


public static String getNamespaceURI(Element element) {
	String prefix = getPrefix(element);
	return getNamespaceURI(element, prefix);
    }

public static String getNamespaceURI ( Element element ) { String prefix = getPrefix ( element ) ; return getNamespaceURI ( element , prefix ) ; }

Returns the namespace URI for the namespace to which the
element belongs.

@param element The element.
@return The namespace URI associated with the namespace of the
element, or null if no namespace declaration exists for it.

Returns the namespace URI for the namespace to which the element belongs .


public static List list(Enumeration e)
   {
      ArrayList result = new ArrayList();
      while (e.hasMoreElements())
         result.add(e.nextElement());
      return result;
   }

public static List list ( Enumeration e ) { ArrayList result = new ArrayList ( ) ; while ( e . hasMoreElements ( ) ) result . add ( e . nextElement ( ) ) ; return result ; }

Create a list from an enumeration

@param e the enumeration
@return the list


protected InputStream getInputStream(String filename) throws IOException {
      File file = new File(filename);
      return new FileInputStream(file);
   }

protected InputStream getInputStream ( String filename ) throws IOException { File file = new File ( filename ) ; return new FileInputStream ( file ) ; }

Get an input stream for the given filename.

@param filename   File name to get input stream for.
@return           Input stream for file.

@throws IOException  Failed to get input stream for file.

Get an input stream for the given filename .


protected void loadProperties(Properties props, String filename)
      throws IOException
   {
      if (filename == null)
         throw new NullArgumentException("filename");
      if (filename.equals(""))
         throw new IllegalArgumentException("filename");

      InputStream in = new BufferedInputStream(getInputStream(filename));
      props.load(in);
      in.close();
   }

protected void loadProperties ( Properties props , String filename ) throws IOException { if ( filename == null ) throw new NullArgumentException ( "filename" ) ; if ( filename . equals ( "" ) ) throw new IllegalArgumentException ( "filename" ) ; InputStream in = new BufferedInputStream ( getInputStream ( filename ) ) ; props . load ( in ) ; in . close ( ) ; }

Load properties from a file into a properties map.

@param props      Properties map to load properties into.
@param filename   Filename to read properties from.

@throws IOException              Failed to load properties from filename.
@throws IllegalArgumentException Filename is invalid.

Load properties from a file into a properties map .


public Map readProperties()
      throws PropertyException, IOException
   {
      Properties props = new Properties();

      // load each specified property file
      for (int i=0; i<filenames.length; i++) {
         loadProperties(props, filenames[i]);
      }

      return props;
   }

public
Map
readProperties
(
)
throws
PropertyException
,
IOException
{
Properties
props
=
new
Properties
(
)
;
// load each specified property file
for
(
int
i
=
0
;
i
<
filenames
.
length
;
i
++
)
{
loadProperties
(
props
,
filenames
[
i
]
)
;
}
return
props
;
}

Read properties from each specified filename

@return  Read properties

@throws PropertyException    Failed to read properties.
@throws IOException          I/O error while reading properties.


public boolean addEdge(Edge<T> e)
   {
      if (e.getFrom() == this)
         outgoingEdges.add(e);
      else if (e.getTo() == this)
         incomingEdges.add(e);
      else
         return false;
      return true;
   }

public boolean addEdge ( Edge < T > e ) { if ( e . getFrom ( ) == this ) outgoingEdges . add ( e ) ; else if ( e . getTo ( ) == this ) incomingEdges . add ( e ) ; else return false ; return true ; }

Add an edge to the vertex. If edge.from is this vertex, its an
outgoing edge. If edge.to is this vertex, its an incoming
edge. If neither from or to is this vertex, the edge is
not added.

@param e - the edge to add
@return true if the edge was added, false otherwise

Add an edge to the vertex . If edge . from is this vertex its an outgoing edge . If edge . to is this vertex its an incoming edge . If neither from or to is this vertex the edge is not added .


public void addOutgoingEdge(Vertex<T> to, int cost)
   {
      Edge<T> out = new Edge<T>(this, to, cost);
      outgoingEdges.add(out);
   }

public void addOutgoingEdge ( Vertex < T > to , int cost ) { Edge < T > out = new Edge < T > ( this , to , cost ) ; outgoingEdges . add ( out ) ; }

Add an outgoing edge ending at to.

@param to - the destination vertex
@param cost the edge cost


public void addIncomingEdge(Vertex<T> from, int cost)
   {
      Edge<T> out = new Edge<T>(this, from, cost);
      incomingEdges.add(out);
   }

public void addIncomingEdge ( Vertex < T > from , int cost ) { Edge < T > out = new Edge < T > ( this , from , cost ) ; incomingEdges . add ( out ) ; }

Add an incoming edge starting at from

@param from - the starting vertex
@param cost the edge cost


public boolean hasEdge(Edge<T> e)
   {
      if (e.getFrom() == this)
         return outgoingEdges.contains(e);
      else if (e.getTo() == this)
         return incomingEdges.contains(e);
      else
         return false;
   }

public boolean hasEdge ( Edge < T > e ) { if ( e . getFrom ( ) == this ) return outgoingEdges . contains ( e ) ; else if ( e . getTo ( ) == this ) return incomingEdges . contains ( e ) ; else return false ; }

Check the vertex for either an incoming or outgoing edge
mathcing e.

@param e the edge to check
@return true it has an edge

Check the vertex for either an incoming or outgoing edge mathcing e .


public boolean remove(Edge<T> e)
   {
      if (e.getFrom() == this)
         outgoingEdges.remove(e);
      else if (e.getTo() == this)
         incomingEdges.remove(e);
      else
         return false;
      return true;
   }

public boolean remove ( Edge < T > e ) { if ( e . getFrom ( ) == this ) outgoingEdges . remove ( e ) ; else if ( e . getTo ( ) == this ) incomingEdges . remove ( e ) ; else return false ; return true ; }

Remove an edge from this vertex

@param e - the edge to remove
@return true if the edge was removed, false if the
edge was not connected to this vertex


public Edge<T> findEdge(Vertex<T> dest)
   {
      for (Edge<T> e : outgoingEdges)
      {
         if (e.getTo() == dest)
            return e;
      }
      return null;
   }

public Edge < T > findEdge ( Vertex < T > dest ) { for ( Edge < T > e : outgoingEdges ) { if ( e . getTo ( ) == dest ) return e ; } return null ; }

Search the outgoing edges looking for an edge whose's
edge.to == dest.
@param dest the destination
@return the outgoing edge going to dest if one exists,
null otherwise.

Search the outgoing edges looking for an edge whose s edge . to == dest .


public Edge<T> findEdge(Edge<T> e)
   {
      if (outgoingEdges.contains(e))
         return e;
      else
         return null;
   }

public Edge < T > findEdge ( Edge < T > e ) { if ( outgoingEdges . contains ( e ) ) return e ; else return null ; }

Search the outgoing edges for a match to e.

@param e - the edge to check
@return e if its a member of the outgoing edges, null
otherwise.

Search the outgoing edges for a match to e .


public int cost(Vertex<T> dest)
   {
      if (dest == this)
         return 0;

      Edge<T> e = findEdge(dest);
      int cost = Integer.MAX_VALUE;
      if (e != null)
         cost = e.getCost();
      return cost;
   }

public int cost ( Vertex < T > dest ) { if ( dest == this ) return 0 ; Edge < T > e = findEdge ( dest ) ; int cost = Integer . MAX_VALUE ; if ( e != null ) cost = e . getCost ( ) ; return cost ; }

What is the cost from this vertext to the dest vertex.

@param dest - the destination vertex.
@return Return Integer.MAX_VALUE if we have no edge to dest,
0 if dest is this vertex, the cost of the outgoing edge
otherwise.

What is the cost from this vertext to the dest vertex .


private static void jar(File src, String prefix, JarInfo info)
      throws IOException
   {

      JarOutputStream jout = info.out;
      if (src.isDirectory())
      {
         // create / init the zip entry
         prefix = prefix + src.getName() + "/";
         ZipEntry entry = new ZipEntry(prefix);
         entry.setTime(src.lastModified());
         entry.setMethod(JarOutputStream.STORED);
         entry.setSize(0L);
         entry.setCrc(0L);
         jout.putNextEntry(entry);
         jout.closeEntry();

         // process the sub-directories
         File[] files = src.listFiles(info.filter);
         for (int i = 0; i < files.length; i++)
         {
            jar(files[i], prefix, info);
         }
      }
      else if (src.isFile())
      {
         // get the required info objects
         byte[] buffer = info.buffer;

         // create / init the zip entry
         ZipEntry entry = new ZipEntry(prefix + src.getName());
         entry.setTime(src.lastModified());
         jout.putNextEntry(entry);

         // dump the file
         FileInputStream in = new FileInputStream(src);
         int len;
         while ((len = in.read(buffer, 0, buffer.length)) != -1)
         {
            jout.write(buffer, 0, len);
         }
         in.close();
         jout.closeEntry();
      }
   }

private
static
void
jar
(
File
src
,
String
prefix
,
JarInfo
info
)
throws
IOException
{
JarOutputStream
jout
=
info
.
out
;
if
(
src
.
isDirectory
(
)
)
{
// create / init the zip entry
prefix
=
prefix
+
src
.
getName
(
)
+
"/"
;
ZipEntry
entry
=
new
ZipEntry
(
prefix
)
;
entry
.
setTime
(
src
.
lastModified
(
)
)
;
entry
.
setMethod
(
JarOutputStream
.
STORED
)
;
entry
.
setSize
(
0L
)
;
entry
.
setCrc
(
0L
)
;
jout
.
putNextEntry
(
entry
)
;
jout
.
closeEntry
(
)
;
// process the sub-directories
File
[
]
files
=
src
.
listFiles
(
info
.
filter
)
;
for
(
int
i
=
0
;
i
<
files
.
length
;
i
++
)
{
jar
(
files
[
i
]
,
prefix
,
info
)
;
}
}
else
if
(
src
.
isFile
(
)
)
{
// get the required info objects
byte
[
]
buffer
=
info
.
buffer
;
// create / init the zip entry
ZipEntry
entry
=
new
ZipEntry
(
prefix
+
src
.
getName
(
)
)
;
entry
.
setTime
(
src
.
lastModified
(
)
)
;
jout
.
putNextEntry
(
entry
)
;
// dump the file
FileInputStream
in
=
new
FileInputStream
(
src
)
;
int
len
;
while
(
(
len
=
in
.
read
(
buffer
,
0
,
buffer
.
length
)
)
!=
1
)
{
jout
.
write
(
buffer
,
0
,
len
)
;
}
in
.
close
(
)
;
jout
.
closeEntry
(
)
;
}
}

This recursive method writes all matching files and directories to
the jar output stream.

This recursive method writes all matching files and directories to the jar output stream .


public boolean hasNext() {
      for (; index < iters.length; index++) {
         if (iters[index] != null && iters[index].hasNext()) {
            return true;
         }
      }

      return false;
   }

public boolean hasNext ( ) { for ( ; index < iters . length ; index ++ ) { if ( iters [ index ] != null && iters [ index ] . hasNext ( ) ) { return true ; } } return false ; }

Check if there are more elements.

@return  True if there are more elements.


public void fireEvent(Object event) {
        if (event == null) {
            throw new IllegalArgumentException("Event must not be null.");
        }
        mTaskQueue.offer(Task.obtainTask(Task.CODE_FIRE_EVENT, event, -1));
        if (!mQueueProcessed) processTaskQueue();
    }

public
void
fireEvent
(
Object
event
)
{
if
(
event
==
)
{
throw
new
IllegalArgumentException
(
"Event must not be null."
)
;
}
mTaskQueue
.
offer
(
Task
.
obtainTask
(
Task
.
CODE_FIRE_EVENT
,
event
,
1
)
)
;
if
(
!
mQueueProcessed
)
processTaskQueue
(
)
;
}

Forwards an event into state machine. State machine will deliver the event to a
handler methods responsible for its processing. If there is no handler method found,
then event gets silently ignored and this call has no effect.

@param event event to be delivered to a handler method

Forwards an event into state machine . State machine will deliver the event to a handler methods responsible for its processing . If there is no handler method found then event gets silently ignored and this call has no effect .


private void internalInstallJvmTypeProvider(XtextResourceSet resourceSet, File tmpClassDirectory,
			boolean skipIndexLookup) {
		Iterable<String> classPathEntries = concat(getClassPathEntries(), getSourcePathDirectories(),
				asList(tmpClassDirectory.toString()));
		classPathEntries = filter(classPathEntries, new Predicate<String>() {
			public boolean apply(String input) {
				return !Strings.isEmpty(input.trim());
			}
		});
		Function<String, URL> toUrl = new Function<String, URL>() {
			public URL apply(String from) {
				try {
					return new File(from).toURI().toURL();
				} catch (MalformedURLException e) {
					throw new RuntimeException(e);
				}
			}
		};
		Iterable<URL> classPathUrls = Iterables.transform(classPathEntries, toUrl);
		log.debug("classpath used for Struct compilation : " + classPathUrls);
		ClassLoader parentClassLoader;
		if (useCurrentClassLoaderAsParent) {
			parentClassLoader = currentClassLoader;
		} else {
			if (isEmpty(bootClassPath)) {
				parentClassLoader = ClassLoader.getSystemClassLoader().getParent();
			} else {
				Iterable<URL> bootClassPathUrls = Iterables.transform(getBootClassPathEntries(), toUrl);
				parentClassLoader = new BootClassLoader(toArray(bootClassPathUrls, URL.class));
			}
		}
		ClassLoader urlClassLoader = new URLClassLoader(toArray(classPathUrls, URL.class), parentClassLoader);
		new ClasspathTypeProvider(urlClassLoader, resourceSet, skipIndexLookup ? null : indexedJvmTypeAccess);
		resourceSet.setClasspathURIContext(urlClassLoader);

		// for annotation processing we need to have the compiler's classpath as
		// a parent.
		URLClassLoader urlClassLoaderForAnnotationProcessing = new URLClassLoader(toArray(classPathUrls, URL.class),
				currentClassLoader);
		resourceSet.eAdapters().add(new ProcessorClassloaderAdapter(urlClassLoaderForAnnotationProcessing));
	}

Performs the actual installation of the JvmTypeProvider.

Performs the actual installation of the JvmTypeProvider .


protected static boolean cleanFolder(File parentFolder, FileFilter filter, boolean continueOnError,
			boolean deleteParentFolder) {
		if (!parentFolder.exists()) {
			return true;
		}
		if (filter == null)
			filter = ACCEPT_ALL_FILTER;
		log.debug("Cleaning folder " + parentFolder.toString());
		final File[] contents = parentFolder.listFiles(filter);
		for (int j = 0; j < contents.length; j++) {
			final File file = contents[j];
			if (file.isDirectory()) {
				if (!cleanFolder(file, filter, continueOnError, true) && !continueOnError)
					return false;
			} else {
				if (!file.delete()) {
					log.warn("Couldn't delete " + file.getAbsolutePath());
					if (!continueOnError)
						return false;
				}
			}
		}
		if (deleteParentFolder) {
			if (parentFolder.list().length == 0 && !parentFolder.delete()) {
				log.warn("Couldn't delete " + parentFolder.getAbsolutePath());
				return false;
			}
		}
		return true;
	}

protected
static
boolean
cleanFolder
(
File
parentFolder
,
FileFilter
filter
,
boolean
continueOnError
,
boolean
deleteParentFolder
)
{
if
(
!
parentFolder
.
exists
(
)
)
{
return
true
;
}
if
(
filter
==
)
filter
=
ACCEPT_ALL_FILTER
;
log
.
debug
(
"Cleaning folder "
+
parentFolder
.
toString
(
)
)
;
final
File
[
]
contents
=
parentFolder
.
listFiles
(
filter
)
;
for
(
int
j
=
0
;
j
<
contents
.
length
;
j
++
)
{
final
File
file
=
contents
[
j
]
;
if
(
file
.
isDirectory
(
)
)
{
if
(
!
cleanFolder
(
file
,
filter
,
continueOnError
,
true
)
&&
!
continueOnError
)
return
false
;
}
else
{
if
(
!
file
.
delete
(
)
)
{
log
.
warn
(
"Couldn't delete "
+
file
.
getAbsolutePath
(
)
)
;
if
(
!
continueOnError
)
return
false
;
}
}
}
if
(
deleteParentFolder
)
{
if
(
parentFolder
.
list
(
)
.
length
==
0
&&
!
parentFolder
.
delete
(
)
)
{
log
.
warn
(
"Couldn't delete "
+
parentFolder
.
getAbsolutePath
(
)
)
;
return
false
;
}
}
return
true
;
}


public void dispatchOnFxThread(Action action) {
        if(Platform.isFxApplicationThread()) {
            actionStream.push(action);
        } else {
            Platform.runLater(() -> actionStream.push(action));
        }
    }

public void dispatchOnFxThread ( Action action ) { if ( Platform . isFxApplicationThread ( ) ) { actionStream . push ( action ) ; } else { Platform . runLater ( ( ) -> actionStream . push ( action ) ) ; } }

Dispatch the given action. Dispatching is always done on the JavaFX application
thread, even if this method is called from another thread.

@param action the action that will be dispatched to the stores.

Dispatch the given action . Dispatching is always done on the JavaFX application thread even if this method is called from another thread .


@SuppressWarnings("unchecked")
    <T extends Action> EventStream<T> getActionStream(Class<T> actionType) {
        return Dispatcher.getInstance()
                .getActionStream()
                .filter(action -> action.getClass().equals(actionType))
                .map(action -> (T) action);
    }

@ SuppressWarnings ( "unchecked" ) < T extends Action > EventStream < T > getActionStream ( Class < T > actionType ) { return Dispatcher . getInstance ( ) . getActionStream ( ) . filter ( action -> action . getClass ( ) . equals ( actionType ) ) . map ( action -> ( T ) action ) ; }

A filtered event-stream of actions of the given type.

@param actionType the class type of the action.
@param <T> the generic type of the action.
@return an event-stream of all actions of the given type.

A filtered event - stream of actions of the given type .


private static String createFxmlPath(Class<?> viewType) {
        final StringBuilder pathBuilder = new StringBuilder();

        pathBuilder.append("/");

        if (viewType.getPackage() != null) {
            pathBuilder.append(viewType.getPackage().getName().replaceAll("\\.", "/"));
            pathBuilder.append("/");
        }

        pathBuilder.append(viewType.getSimpleName());
        pathBuilder.append(".fxml");

        return pathBuilder.toString();
    }

private static String createFxmlPath ( Class < ? > viewType ) { final StringBuilder pathBuilder = new StringBuilder ( ) ; pathBuilder . append ( "/" ) ; if ( viewType . getPackage ( ) != null ) { pathBuilder . append ( viewType . getPackage ( ) . getName ( ) . replaceAll ( "\\." , "/" ) ) ; pathBuilder . append ( "/" ) ; } pathBuilder . append ( viewType . getSimpleName ( ) ) ; pathBuilder . append ( ".fxml" ) ; return pathBuilder . toString ( ) ; }


public Stream<Record> oneToMany(Collection<? extends Record> rights, ListKey<Record> manyKey) {
        return oneToMany(rights.stream(), manyKey);
    }

public Stream < Record > oneToMany ( Collection < ? extends Record > rights , ListKey < Record > manyKey ) { return oneToMany ( rights . stream ( ) , manyKey ) ; }


public Stream<T2<L, R>> manyToOne(Collection<? extends R> rights) {
        return manyToOne(rights.stream());
    }

public Stream < T2 < L , R > > manyToOne ( Collection < ? extends R > rights ) { return manyToOne ( rights . stream ( ) ) ; }


public Stream<T2<L, R>> strictManyToOne(Collection<? extends R> rights) {
        return strictManyToOne(rights.stream());
    }

public Stream < T2 < L , R > > strictManyToOne ( Collection < ? extends R > rights ) { return strictManyToOne ( rights . stream ( ) ) ; }


public Stream<T2<L, R>> strictOneToOne(Collection<? extends R> rights) {
        return strictOneToOne(rights.stream());
    }

public Stream < T2 < L , R > > strictOneToOne ( Collection < ? extends R > rights ) { return strictOneToOne ( rights . stream ( ) ) ; }


@Override
	public boolean getAllowRobots(ServletContext servletContext, HttpServletRequest request, HttpServletResponse response, Page page) throws ServletException, IOException {
		return PageUtils.findAllowRobots(servletContext, request, response, page);
	}

@ Override public boolean getAllowRobots ( ServletContext servletContext , HttpServletRequest request , HttpServletResponse response , Page page ) throws ServletException , IOException { return PageUtils . findAllowRobots ( servletContext , request , response , page ) ; }

Uses the page settings.

@see  PageUtils#findAllowRobots(javax.servlet.ServletContext, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, com.semanticcms.core.model.Page)


@Then("^the instruction generated should be \"([^\"]*)\"$")
    public void the_instruction_generated_should_be(String command) throws Throwable {
        verify(context.getDrinkMaker()).executeCommand(eq(command));
    }

Assert that the generated command matches the specified command.
@param command expected command
@throws Throwable

Assert that the generated command matches the specified command .


public static void main(String[] args) throws Exception {
		int n = 1;
		if(args.length < 1) {
			usage();
			return;
		}
		Properties analyzers = new Properties();
		analyzers.load(new FileInputStream(new File("analyzer.properties")));
		String mode = System.getProperty("mode", "complex");
		String a = System.getProperty("analyzer", "mmseg4j");
		Analyzer analyzer = null;
		String an = (String) analyzers.get(a);
		if(an != null) {
			analyzer = (Analyzer)Class.forName(an).newInstance();
			mode = a;
		} else {
			usage();
			return;
		}
		if(args.length > 1) {
			try {
				n = Integer.parseInt(args[1]);
			} catch (NumberFormatException e) {

			}
		}
		File path = new File(args[0]);
		System.out.println("analyzer="+analyzer.getClass().getName());
		Effect ef = new Effect(path, analyzer);
		ef.run(mode, n);
	}

public static void main ( String [ ] args ) throws Exception { int n = 1 ; if ( args . length < 1 ) { usage ( ) ; return ; } Properties analyzers = new Properties ( ) ; analyzers . load ( new FileInputStream ( new File ( "analyzer.properties" ) ) ) ; String mode = System . getProperty ( "mode" , "complex" ) ; String a = System . getProperty ( "analyzer" , "mmseg4j" ) ; Analyzer analyzer = null ; String an = ( String ) analyzers . get ( a ) ; if ( an != null ) { analyzer = ( Analyzer ) Class . forName ( an ) . newInstance ( ) ; mode = a ; } else { usage ( ) ; return ; } if ( args . length > 1 ) { try { n = Integer . parseInt ( args [ 1 ] ) ; } catch ( NumberFormatException e ) { } } File path = new File ( args [ 0 ] ) ; System . out . println ( "analyzer=" + analyzer . getClass ( ) . getName ( ) ) ; Effect ef = new Effect ( path , analyzer ) ; ef . run ( mode , n ) ; }

-Dmode=simple, default is complex
@param args args[0] txt path
@author chenlb 2009-3-28 下午02:19:52
@throws Exception


public static void main(String[] args) throws IOException {
		if(args.length < 1) {
			System.out.println("Usage:");
			System.out.println("\t-Dmode=simple, defalut is complex");
			System.out.println("\tPerformance <txt path> - is a directory that contain *.txt");
			return;
		}
		String mode = System.getProperty("mode", "complex");
		Seg seg = null;
		Dictionary dic = Dictionary.getInstance();
		if("simple".equals(mode)) {
			seg = new SimpleSeg(dic);
		} else {
			seg = new ComplexSeg(dic);
		}
		File path = new File(args[0]);
		File[] txts = path.listFiles(new FilenameFilter() {

			public boolean accept(File dir, String name) {

				return name.endsWith(".txt");
			}

		});
		long time = 0;
		for(File txt : txts) {
			MMSeg mmSeg = new MMSeg(new InputStreamReader(new FileInputStream(txt)), seg);
			Word word = null;
			OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(new File(txt.getAbsoluteFile()+"."+mode+".word")));
			BufferedWriter bw = new BufferedWriter(osw);
			long start = System.currentTimeMillis();
			while((word=mmSeg.next())!=null) {

				bw.append(new String(word.getString())).append("\r\n");
			}
			time += System.currentTimeMillis() - start;
			bw.close();
		}
		System.out.println("use "+time+"ms");
	}

-Dmode=simple, default is complex
-Dfile.encode=utf-8 or other
@param args args[0] txt path
@author chenlb 2009-3-28 下午02:19:52
@throws IOException

- Dmode = simple default is complex - Dfile . encode = utf - 8 or other


public int getSumDegree() {
		if(sumDegree < 0) {
			int sum = 0;
			for(Word word : words) {
				if(word != null && word.getDegree() > -1) {
					sum += word.getDegree();
				}
			}
			sumDegree = sum;
		}
		return sumDegree;
	}

public int getSumDegree ( ) { if ( sumDegree < 0 ) { int sum = 0 ; for ( Word word : words ) { if ( word != null && word . getDegree ( ) > - 1 ) { sum += word . getDegree ( ) ; } } sumDegree = sum ; } return sumDegree ; }

Sum of Degree of Morphemic Freedom of One-Character

Sum of Degree of Morphemic Freedom of One - Character


private static Map<String, String> superclassArgs(Map<String, String> args) {
      Map<String, String> result = new HashMap<>();

      // resource loading does not take place if no file has been configured.
      if (!result.containsKey("dictionary")) {
         result.put("dictionary", JdbcResourceLoader.DATABASE);
      }
      for (String arg : ImmutableList.of("dictionary", "ignoreCase")) {
         String value = args.get(arg);
         if (value != null) {
            result.put(arg, value);
         }
      }
      return result;
   }

Returns a map which contains only those arguments that the superclass understands.

Returns a map which contains only those arguments that the superclass understands .


@Override
   public void inform(ResourceLoader loader) throws IOException {
      super.inform(new JdbcResourceLoader(loader, reader, StandardCharsets.UTF_8));
   }

@ Override public void inform ( ResourceLoader loader ) throws IOException { super . inform ( new JdbcResourceLoader ( loader , reader , StandardCharsets . UTF_8 ) ) ; }


protected final void checkDatasource() {
      // Check database connection information of data source
      if (dataSource != null) {
         //noinspection unused,EmptyTryBlock
         try (Connection connection = dataSource.getConnection()) {
            // Just get the connection to check if data source parameters are configured correctly.
         } catch (SQLException e) {
            dataSource = null;
            logger.error("Failed to connect to database of data source: {}.", e.getMessage());
            if (!ignore) {
               throw new IllegalArgumentException("Failed to connect to the database.", e);
            }
         }
      }
   }

Check if the datasource is able to provide connections.

Check if the datasource is able to provide connections .


@NonNull
  public static <T> Iterable<T> iterableOf(final InstanceOf<T> type) {
    return PrivateGenerate.FIXTURE.createMany(type);
  }

@ NonNull public static < T > Iterable < T > iterableOf ( final InstanceOf < T > type ) { return PrivateGenerate . FIXTURE . createMany ( type ) ; }


@NonNull
  public static <T> T[] arrayOf(final Class<T> clazz) {
    assertIsNotParameterized(clazz, ErrorMessages.msg("arrayOf"));
    return PrivateGenerate.manyAsArrayOf(TypeToken.of(clazz));
  }

@ NonNull public static < T > T [ ] arrayOf ( final Class < T > clazz ) { assertIsNotParameterized ( clazz , ErrorMessages . msg ( "arrayOf" ) ) ; return PrivateGenerate . manyAsArrayOf ( TypeToken . of ( clazz ) ) ; }


@NonNull
  public static <T> List<T> listOf(final Class<T> clazz) {
    assertIsNotParameterized(clazz, ErrorMessages.msg("listOf"));
    return PrivateGenerate.manyAsListOf(TypeToken.of(clazz));
  }

@ NonNull public static < T > List < T > listOf ( final Class < T > clazz ) { assertIsNotParameterized ( clazz , ErrorMessages . msg ( "listOf" ) ) ; return PrivateGenerate . manyAsListOf ( TypeToken . of ( clazz ) ) ; }


@NonNull
  public static <T> Collection<T> collectionOf(final InstanceOf<T> typeToken, final InlineConstrainedGenerator<T> omittedValues) {
    return PrivateGenerate.manyAsListOf(typeToken, omittedValues);
  }

@ NonNull public static < T > Collection < T > collectionOf ( final InstanceOf < T > typeToken , final InlineConstrainedGenerator < T > omittedValues ) { return PrivateGenerate . manyAsListOf ( typeToken , omittedValues ) ; }


@NonNull
  public static <T> List<T> listOf(Class<T> clazz) {
    assertIsNotParameterized(clazz, msg("listOf"));
    return io.vavr.collection.List.ofAll(Any.listOf(clazz));
  }

@ NonNull public static < T > List < T > listOf ( Class < T > clazz ) { assertIsNotParameterized ( clazz , msg ( "listOf" ) ) ; return io . vavr . collection . List . ofAll ( Any . listOf ( clazz ) ) ; }


@NonNull
  public static <T,U> Either<T, U> left(final Class<T> leftType) {
    assertIsNotParameterized(leftType, msgInline("left"));
    return Either.left(Any.instanceOf(leftType));
  }

@ NonNull public static < T , U > Either < T , U > left ( final Class < T > leftType ) { assertIsNotParameterized ( leftType , msgInline ( "left" ) ) ; return Either . left ( Any . instanceOf ( leftType ) ) ; }


@NonNull
  public static <T,U> Either<T, U> right(final Class<U> rightType) {
    assertIsNotParameterized(rightType, msgInline("right"));
    return Either.right(Any.instanceOf(rightType));
  }

@ NonNull public static < T , U > Either < T , U > right ( final Class < U > rightType ) { assertIsNotParameterized ( rightType , msgInline ( "right" ) ) ; return Either . right ( Any . instanceOf ( rightType ) ) ; }


@NonNull
  public static <T,U> Validation<T, U> validationFailed(final Class<T> type) {
    assertIsNotParameterized(type, msgInline("validationFailed"));
    return Validation.invalid(Any.instanceOf(type));
  }

@ NonNull public static < T , U > Validation < T , U > validationFailed ( final Class < T > type ) { assertIsNotParameterized ( type , msgInline ( "validationFailed" ) ) ; return Validation . invalid ( Any . instanceOf ( type ) ) ; }


@NonNull
  public static <T,U> Validation<T, U> validationSuccess(final Class<U> type) {
    assertIsNotParameterized(type, msgInline("validationSuccess"));
    return Validation.valid(Any.instanceOf(type));
  }

@ NonNull public static < T , U > Validation < T , U > validationSuccess ( final Class < U > type ) { assertIsNotParameterized ( type , msgInline ( "validationSuccess" ) ) ; return Validation . valid ( Any . instanceOf ( type ) ) ; }


@NonNull
  public static <T> Try<T> trySuccess(final Class<T> type) {
    assertIsNotParameterized(type, msgInline("trySuccess"));
    return Try.success(Any.instanceOf(type));
  }

@ NonNull public static < T > Try < T > trySuccess ( final Class < T > type ) { assertIsNotParameterized ( type , msgInline ( "trySuccess" ) ) ; return Try . success ( Any . instanceOf ( type ) ) ; }


@SuppressWarnings("unchecked")
	public boolean connectJdbcOnWithUrlAndDriverAndUsernameAndPassword(String dataBaseId, String url, String driverClassName, String username, String password) throws ReflectiveOperationException {
		SimpleDriverDataSource dataSource = new SimpleDriverDataSource();
		dataSource.setUrl(url);
		dataSource.setDriverClass((Class<Driver>) Class.forName(driverClassName));
		dataSource.setUsername(username);
		dataSource.setPassword(password);
		this.templateMap.put(dataBaseId, new JdbcTemplate(dataSource));
		return true;
	}

Registers a database to further execute SQL commands

| connect jdbc on | database | with url | url | and driver | driver | and username | username | and | password |

@param url


public boolean runInTheSql(String database, final String sql) {
		getDatabaseJdbcTemplate(database).update(sql);
		return true;
	}

public boolean runInTheSql ( String database , final String sql ) { getDatabaseJdbcTemplate ( database ) . update ( sql ) ; return true ; }

Simply runs a SQL command, used for udpates, inserts which the result doesn't matter.

| run in | database | the sql | sql |

@param database registered database to run the SQL
@param sql to run

Simply runs a SQL command used for udpates inserts which the result doesn t matter .


public String queryInWithSql(String database, String sql) {
		JdbcTemplate template = getDatabaseJdbcTemplate(database);
		if (sql != null && !sql.trim().toUpperCase().startsWith(JdbcFixture.SELECT_COMMAND_PREFIX)) {
			return Objects.toString(template.update(sql));
		}
		List<String> results = template.queryForList(sql, String.class);
		if(results == null || results.isEmpty()) {
			return null;
		}
		return results.get(0);
	}

public String queryInWithSql ( String database , String sql ) { JdbcTemplate template = getDatabaseJdbcTemplate ( database ) ; if ( sql != null && ! sql . trim ( ) . toUpperCase ( ) . startsWith ( JdbcFixture . SELECT_COMMAND_PREFIX ) ) { return Objects . toString ( template . update ( sql ) ) ; } List < String > results = template . queryForList ( sql , String . class ) ; if ( results == null || results . isEmpty ( ) ) { return null ; } return results . get ( 0 ) ; }

Used generally when the result is assigned to a variable

| $variable= | query in | database | with sql | sql |

@param database registered database to run the SQL
@param sql to run


public boolean[] asBoolArray() {
        boolean[] retval;
        UBArray array = asArray();
        switch(array.getStrongType()){
            case Int8: {
                byte[] data = ((UBInt8Array) array).getValues();
                retval = new boolean[data.length];
                for (int i = 0; i < data.length; i++) {
                    retval[i] = data[i] > 0;
                }
                break;
            }

            case Int16: {
                short[] data = ((UBInt16Array) array).getValues();
                retval = new boolean[data.length];
                for (int i = 0; i < data.length; i++) {
                    retval[i] = data[i] > 0;
                }
                break;
            }

            case Int32: {
                int[] data = ((UBInt32Array)array).getValues();
                retval = new boolean[data.length];
                for (int i = 0; i < data.length; i++) {
                    retval[i] = data[i] > 0;
                }
                break;
            }

            case Int64: {
                long[] data = ((UBInt64Array)array).getValues();
                retval = new boolean[data.length];
                for (int i = 0; i < data.length; i++) {
                    retval[i] = data[i] > 0;
                }
                break;
            }

            case Float32: {
                float[] data = ((UBFloat32Array) array).getValues();
                retval = new boolean[data.length];
                for (int i = 0; i < data.length; i++) {
                    retval[i] = data[i] > 0;
                }
                break;
            }

            case Float64: {
                double[] data = ((UBFloat64Array) array).getValues();
                retval = new boolean[data.length];
                for (int i = 0; i < data.length; i++) {
                    retval[i] = data[i] > 0;
                }
                break;
            }

            default:
                throw new RuntimeException("not an int32[] type");
        }

        return retval;
    }

public
boolean
[
]
asBoolArray
(
)
{
boolean
[
]
retval
;
UBArray
array
=
asArray
(
)
;
switch
(
array
.
getStrongType
(
)
)
{
case
Int8
:
{
byte
[
]
data
=
(
(
UBInt8Array
)
array
)
.
getValues
(
)
;
retval
=
new
boolean
[
data
.
length
]
;
for
(
int
i
=
0
;
i
<
data
.
length
;
i
++
)
{
retval
[
i
]
=
data
[
i
]
>
0
;
}
break
;
}
case
Int16
:
{
short
[
]
data
=
(
(
UBInt16Array
)
array
)
.
getValues
(
)
;
retval
=
new
boolean
[
data
.
length
]
;
for
(
int
i
=
0
;
i
<
data
.
length
;
i
++
)
{
retval
[
i
]
=
data
[
i
]
>
0
;
}
break
;
}
case
Int32
:
{
int
[
]
data
=
(
(
UBInt32Array
)
array
)
.
getValues
(
)
;
retval
=
new
boolean
[
data
.
length
]
;
for
(
int
i
=
0
;
i
<
data
.
length
;
i
++
)
{
retval
[
i
]
=
data
[
i
]
>
0
;
}
break
;
}
case
Int64
:
{
long
[
]
data
=
(
(
UBInt64Array
)
array
)
.
getValues
(
)
;
retval
=
new
boolean
[
data
.
length
]
;
for
(
int
i
=
0
;
i
<
data
.
length
;
i
++
)
{
retval
[
i
]
=
data
[
i
]
>
0
;
}
break
;
}
case
Float32
:
{
float
[
]
data
=
(
(
UBFloat32Array
)
array
)
.
getValues
(
)
;
retval
=
new
boolean
[
data
.
length
]
;
for
(
int
i
=
0
;
i
<
data
.
length
;
i
++
)
{
retval
[
i
]
=
data
[
i
]
>
0
;
}
break
;
}
case
Float64
:
{
double
[
]
data
=
(
(
UBFloat64Array
)
array
)
.
getValues
(
)
;
retval
=
new
boolean
[
data
.
length
]
;
for
(
int
i
=
0
;
i
<
data
.
length
;
i
++
)
{
retval
[
i
]
=
data
[
i
]
>
0
;
}
break
;
}
default
:
throw
new
RuntimeException
(
"not an int32[] type"
)
;
}
return
retval
;
}

Interprets a strongly-typed number array to array of booleans.
If a value found in the array is greater than 0 return true, false otherwise.
@return booleans

Interprets a strongly - typed number array to array of booleans . If a value found in the array is greater than 0 return true false otherwise .


public Query<T> byExample(T obj) {
		if (obj != null) {
			return dao.getTableHelper().buildFilter(this, obj);
		}
		return this;
	}

public Query < T > byExample ( T obj ) { if ( obj != null ) { return dao . getTableHelper ( ) . buildFilter ( this , obj ) ; } return this ; }

Executes a query which returns all rows in the entity table
that match the fields of the example object having values other
than the defaults.

Calling method MUST close the {@link Cursor}!

@return Cursor

Executes a query which returns all rows in the entity table that match the fields of the example object having values other than the defaults .


protected void onUpgrade(final SQLiteDatabase db, final int oldVersion,
			final int newVersion) {
		db.execSQL(upgradeSql(oldVersion, newVersion));
	}

protected void onUpgrade ( final SQLiteDatabase db , final int oldVersion , final int newVersion ) { db . execSQL ( upgradeSql ( oldVersion , newVersion ) ) ; }

Upgrades the table that represents the associated entity. This will
typically be an ALTER TABLE statement.

@param db
@param oldVersion
@param newVersion

Upgrades the table that represents the associated entity . This will typically be an ALTER TABLE statement .


public boolean backup(SQLiteDatabase db, Context ctx, String suffix) {
		try {
			new CsvTableWriter(this).dumpToCsv(ctx, db, suffix);
		} catch (SQLException e) {
			if (e.getMessage().contains("no such table")) {
				Log.w(TAG, "Table " + this.getTableName() + " doesn't exist. This is expected if the table is new in this db version.");
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

Backs up the current table to a CSV file.

@param db
@param ctx
@param suffix

@return true on success

Backs up the current table to a CSV file .


public void restore(SQLiteDatabase db, Context ctx, String suffix) {
		new CsvTableReader(this).importFromCsv(ctx, db, suffix);
	}

public void restore ( SQLiteDatabase db , Context ctx , String suffix ) { new CsvTableReader ( this ) . importFromCsv ( ctx , db , suffix ) ; }

Restores a table from a text file.

@param db
@param ctx
@param suffix


public void setEmptyText(CharSequence emptyText) {
		if (mListView != null){
			View emptyView = mListView.getEmptyView();

			if (emptyText instanceof TextView) {
				((TextView) emptyView).setText(emptyText);
			}
		}
    }

public void setEmptyText ( CharSequence emptyText ) { if ( mListView != null ) { View emptyView = mListView . getEmptyView ( ) ; if ( emptyText instanceof TextView ) { ( ( TextView ) emptyView ) . setText ( emptyText ) ; } } }

The default content for this Activity has a TextView that is shown when
the list is empty. If you would like to change the text, call this method
to supply the text it should use.

The default content for this Activity has a TextView that is shown when the list is empty . If you would like to change the text call this method to supply the text it should use .


public int dumpToCsv(Context ctx, SQLiteDatabase db, String suffix) throws FileNotFoundException {
		int numRowsWritten = 0;
		Cursor c;
		String filename = getCsvFilename(db.getPath(), db.getVersion(), suffix);
		c = db.query(th.getTableName(), null, null, null, null, null, null);
		FileOutputStream fos;
		fos = ctx.openFileOutput(filename, 0);
		PrintWriter printWriter = new PrintWriter(fos);
		String headerRow = buildHeaderRow();
		printWriter.println(headerRow);
		for (boolean hasItem = c.moveToFirst(); hasItem; hasItem = c
				.moveToNext()) {
			String csv = buildCsvRow(c);
			printWriter.println(csv);
			numRowsWritten++;
		}
		printWriter.flush();
		printWriter.close();
		return numRowsWritten;
	}

public int dumpToCsv ( Context ctx , SQLiteDatabase db , String suffix ) throws FileNotFoundException { int numRowsWritten = 0 ; Cursor c ; String filename = getCsvFilename ( db . getPath ( ) , db . getVersion ( ) , suffix ) ; c = db . query ( th . getTableName ( ) , null , null , null , null , null , null ) ; FileOutputStream fos ; fos = ctx . openFileOutput ( filename , 0 ) ; PrintWriter printWriter = new PrintWriter ( fos ) ; String headerRow = buildHeaderRow ( ) ; printWriter . println ( headerRow ) ; for ( boolean hasItem = c . moveToFirst ( ) ; hasItem ; hasItem = c . moveToNext ( ) ) { String csv = buildCsvRow ( c ) ; printWriter . println ( csv ) ; numRowsWritten ++ ; } printWriter . flush ( ) ; printWriter . close ( ) ; return numRowsWritten ; }

Dumps a database table to a CSV file in the default location.
Returns the number of rows written to the file.

@param ctx
@param db
@param suffix

@return count of rows in the exported file

Dumps a database table to a CSV file in the default location . Returns the number of rows written to the file .


public static String unescapeCsv(String str) {
		if (str == null)
			return null;
		if (!(str.charAt(0) == QUOTE && str.charAt(str.length() - 1) == QUOTE))
			return str;
		String quoteless = str.substring(1, str.length() - 1);
		return quoteless.replace(QUOTE_STR + QUOTE_STR, QUOTE_STR);
	}

public static String unescapeCsv ( String str ) { if ( str == null ) return null ; if ( ! ( str . charAt ( 0 ) == QUOTE && str . charAt ( str . length ( ) - 1 ) == QUOTE ) ) return str ; String quoteless = str . substring ( 1 , str . length ( ) - 1 ) ; return quoteless . replace ( QUOTE_STR + QUOTE_STR , QUOTE_STR ) ; }

Removes enclosing quotes and unescapes double quotes

@param str An escaped CSV value
@return the original value


public static List<String> getValues(String csvRow) {
		List<String> values = new ArrayList<String>();
		StringReader in = new StringReader(csvRow);
		String value;
		try {
			value = nextValue(in);
			while (true) {
				values.add(value);
				value = nextValue(in);
			}
		} catch (IOException e) {
			// TODO handle case of final null value better?
			if (csvRow.lastIndexOf(',') == csvRow.length() - 1)
				values.add(null);
			return values;
		}
	}

Returns values from a CSV String.

@param csvRow
@return


public static Map<String,String> getAsMap(String csvPairs) {
		Map<String,String> map = new HashMap<String,String>();
		String[] pairs = csvPairs.split(",");
		for (String pair : pairs) {
			String[] split = pair.split("=");
			map.put(split[0], split[1]);
		}
		return map;
	}

public static Map < String , String > getAsMap ( String csvPairs ) { Map < String , String > map = new HashMap < String , String > ( ) ; String [ ] pairs = csvPairs . split ( "," ) ; for ( String pair : pairs ) { String [ ] split = pair . split ( "=" ) ; map . put ( split [ 0 ] , split [ 1 ] ) ; } return map ; }

Parses a CSV row containing name=value pairs.

@param csvPairs
@return Map<name,value>

Parses a CSV row containing name = value pairs .


public static String mapToCsv(Map<String,String> map) {
		StringBuilder sb = new StringBuilder();
		for (String key : map.keySet()) {
			sb.append(",");
			String val = map.get(key);
			sb.append(key + "=" + val);
		}
		return sb.toString().substring(1);
	}

public static String mapToCsv ( Map < String , String > map ) { StringBuilder sb = new StringBuilder ( ) ; for ( String key : map . keySet ( ) ) { sb . append ( "," ) ; String val = map . get ( key ) ; sb . append ( key + "=" + val ) ; } return sb . toString ( ) . substring ( 1 ) ; }

Returns a String containing a comma-separated list
of name=value pairs from a map.

@param map
@return String csv

Returns a String containing a comma - separated list of name = value pairs from a map .


public static String join(final List<String> list) {

		// zero, empty or one element
		if (list == null) {
			return null;
		} else if (list.size() == 0) {
			return "";
		} else if (list.size() == 1) {
			return list.get(0);
		}

		// two or more elements
		final StringBuilder builder = new StringBuilder();
		for (String item : list) {
			if (builder.length() > 0) {
				builder.append(", ");
			}
			builder.append(item);
		}
		return builder.toString();

	}

public
static
String
join
(
final
List
<
String
>
list
)
{
// zero, empty or one element
if
(
list
==
)
{
return
;
}
else
if
(
list
.
size
(
)
==
0
)
{
return
""
;
}
else
if
(
list
.
size
(
)
==
1
)
{
return
list
.
get
(
0
)
;
}
// two or more elements
final
StringBuilder
builder
=
new
StringBuilder
(
)
;
for
(
String
item
:
list
)
{
if
(
builder
.
length
(
)
>
0
)
{
builder
.
append
(
", "
)
;
}
builder
.
append
(
item
)
;
}
return
builder
.
toString
(
)
;
}

Joins items of a text list, separating items by comma.

@param list
list of text items
@return joined list

Joins items of a text list separating items by comma .


public static String join(final String[] list) {

		// zero, empty or one element
		if (list == null) {
			return null;
		} else if (list.length == 0) {
			return "";
		} else if (list.length == 1) {
			return list[0];
		}

		// two or more elements
		final StringBuilder builder = new StringBuilder();
		for (String item : list) {
			if (builder.length() > 0) {
				builder.append(", ");
			}
			builder.append(item);
		}
		return builder.toString();

	}

public
static
String
join
(
final
String
[
]
list
)
{
// zero, empty or one element
if
(
list
==
)
{
return
;
}
else
if
(
list
.
length
==
0
)
{
return
""
;
}
else
if
(
list
.
length
==
1
)
{
return
list
[
0
]
;
}
// two or more elements
final
StringBuilder
builder
=
new
StringBuilder
(
)
;
for
(
String
item
:
list
)
{
if
(
builder
.
length
(
)
>
0
)
{
builder
.
append
(
", "
)
;
}
builder
.
append
(
item
)
;
}
return
builder
.
toString
(
)
;
}

Joins items of a text array, separating items by comma.

@param list
list of text items
@return joined list

Joins items of a text array separating items by comma .


public static DatabaseModel readFromIndex(BufferedReader reader, ProcessorLogger logger) throws IOException {
		String dbInfo = reader.readLine();
		logger.info(dbInfo);
		Map<String, String> props = CsvUtils.getAsMap(dbInfo);
		String dbName = props.get("dbName");
		int dbVersion = Integer.parseInt(props.get("dbVersion"));
		String helperClass = props.get("helperClass");
		DatabaseModel dbModel = new DatabaseModel(dbName, dbVersion, helperClass);
		// read TableHelpers
		List<String> tables = new ArrayList<String>();
		String th = reader.readLine();
		while (th != null && !th.equals(StormEnvironment.END_DATABASE)) {
			tables.add(th);
			th = reader.readLine();
		}
		dbModel.tableHelpers = tables;
		return dbModel;
	}

public
static
DatabaseModel
readFromIndex
(
BufferedReader
reader
,
ProcessorLogger
logger
)
throws
IOException
{
String
dbInfo
=
reader
.
readLine
(
)
;
logger
.
info
(
dbInfo
)
;
Map
<
String
,
String
>
props
=
CsvUtils
.
getAsMap
(
dbInfo
)
;
String
dbName
=
props
.
get
(
"dbName"
)
;
int
dbVersion
=
Integer
.
parseInt
(
props
.
get
(
"dbVersion"
)
)
;
String
helperClass
=
props
.
get
(
"helperClass"
)
;
DatabaseModel
dbModel
=
new
DatabaseModel
(
dbName
,
dbVersion
,
helperClass
)
;
// read TableHelpers
List
<
String
>
tables
=
new
ArrayList
<
String
>
(
)
;
String
th
=
reader
.
readLine
(
)
;
while
(
th
!=
&&
!
th
.
equals
(
StormEnvironment
.
END_DATABASE
)
)
{
tables
.
add
(
th
)
;
th
=
reader
.
readLine
(
)
;
}
dbModel
.
tableHelpers
=
tables
;
return
dbModel
;
}

Populate the model of a database and its associated tables from
a file in support of incremental compilation.

@param reader
@param logger
@return DatabaseModel
@throws IOException

Populate the model of a database and its associated tables from a file in support of incremental compilation .


public void writeToIndex(PrintWriter out) {
		out.println(StormEnvironment.BEGIN_DATABASE);
		Map<String,String> dbMap = new HashMap<String,String>();
		dbMap.put("dbName", this.getDbName());
		dbMap.put("dbVersion", String.valueOf(this.getDbVersion()));
		dbMap.put("helperClass", this.getQualifiedClassName());
		String dbInfo = CsvUtils	.mapToCsv(dbMap);
		out.println(dbInfo);
		// write TableHelpers
		for (String th: this.tableHelpers) {
			out.println(th);
		}
		out.println(StormEnvironment.END_DATABASE);
	}

public
void
writeToIndex
(
PrintWriter
out
)
{
out
.
println
(
StormEnvironment
.
BEGIN_DATABASE
)
;
Map
<
String
,
String
>
dbMap
=
new
HashMap
<
String
,
String
>
(
)
;
dbMap
.
put
(
"dbName"
,
this
.
getDbName
(
)
)
;
dbMap
.
put
(
"dbVersion"
,
String
.
valueOf
(
this
.
getDbVersion
(
)
)
)
;
dbMap
.
put
(
"helperClass"
,
this
.
getQualifiedClassName
(
)
)
;
String
dbInfo
=
CsvUtils
.
mapToCsv
(
dbMap
)
;
out
.
println
(
dbInfo
)
;
// write TableHelpers
for
(
String
th
:
this
.
tableHelpers
)
{
out
.
println
(
th
)
;
}
out
.
println
(
StormEnvironment
.
END_DATABASE
)
;
}

Write the database info and associated tables to a file
in support of incremental compilation.

@param out PrintWriter

Write the database info and associated tables to a file in support of incremental compilation .


private void inspectId() {
        if (entityModel.getIdField() == null) {
            // Default to field named "id"
            List<FieldModel> fields = entityModel.getFields();
            for (FieldModel f : fields) {
                if (EntityModel.DEFAULT_ID_FIELD.equals(f.getFieldName())) {
                    entityModel.setIdField(f);
                }
            }
        }
        FieldModel idField = entityModel.getIdField();
        if (idField != null && "long".equals(idField.getJavaType())) {
            return;
        } else {
            abort("Entity must contain a field named id or annotated with @Id of type long");
        }
    }

Verifies that the entity has exactly one id field of type long.

Verifies that the entity has exactly one id field of type long .


private static BaseDaoModel getBaseDaoClass(Entity entity) {
        String qualifiedName = SQLiteDao.class.getName();
        TypeMirror typeMirror = getBaseDaoTypeMirror(entity);
        if(typeMirror != null) qualifiedName = typeMirror.toString();
        return new BaseDaoModel(qualifiedName);
    }

private static BaseDaoModel getBaseDaoClass ( Entity entity ) { String qualifiedName = SQLiteDao . class . getName ( ) ; TypeMirror typeMirror = getBaseDaoTypeMirror ( entity ) ; if ( typeMirror != null ) qualifiedName = typeMirror . toString ( ) ; return new BaseDaoModel ( qualifiedName ) ; }

Builds a BaseDaoModel from the class passed as attribute baseDaoClass of the annotation Entity
@param entity
@return BaseDaoModel containing the package name + Class name


public String getBindType() {
		String bindType = getConverter().getBindType().name();
		return bindType.charAt(0) + bindType.toLowerCase().substring(1);
	}

public String getBindType ( ) { String bindType = getConverter ( ) . getBindType ( ) . name ( ) ; return bindType . charAt ( 0 ) + bindType . toLowerCase ( ) . substring ( 1 ) ; }

Morph bind type like INT ==> Int so it can be used in a Cursor getXxx
method name. Never called at runtime.

@return

Morph bind type like INT == > Int so it can be used in a Cursor getXxx method name . Never called at runtime .


public int importFromCsv(Context ctx, SQLiteDatabase db, String suffix) {
		String filename = getCsvFilename(db.getPath(), db.getVersion(), suffix);
		FileInputStream fileInputStream;
		try {
			fileInputStream = ctx.openFileInput(filename);
			return importFromCsv(db, fileInputStream);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return -1;
		}
	}

public int importFromCsv ( Context ctx , SQLiteDatabase db , String suffix ) { String filename = getCsvFilename ( db . getPath ( ) , db . getVersion ( ) , suffix ) ; FileInputStream fileInputStream ; try { fileInputStream = ctx . openFileInput ( filename ) ; return importFromCsv ( db , fileInputStream ) ; } catch ( FileNotFoundException e ) { e . printStackTrace ( ) ; return - 1 ; } }

Attempts to import a database table from a CSV file in the default
location.

@param ctx
@param db
@param suffix

@return count of rows imported or -1 if error

Attempts to import a database table from a CSV file in the default location .


public boolean backupAllTablesToCsv(Context ctx, SQLiteDatabase db, String suffix) {
		boolean allSucceeded = true;
		for (TableHelper table : getTableHelpers()) {
			allSucceeded &= table.backup(db, ctx, suffix);
		}
		return allSucceeded;
	}

public boolean backupAllTablesToCsv ( Context ctx , SQLiteDatabase db , String suffix ) { boolean allSucceeded = true ; for ( TableHelper table : getTableHelpers ( ) ) { allSucceeded &= table . backup ( db , ctx , suffix ) ; } return allSucceeded ; }

Backup all tables to CSV files, one per table

@param ctx
@param db
@param suffix Optional filename suffix, none if null

@return True if all tables completed without errors

Backup all tables to CSV files one per table


public void restoreAllTablesFromCsv(Context ctx, SQLiteDatabase db, String suffix) {
		for (TableHelper table : getTableHelpers()) {
			table.restore(db, ctx, suffix);
		}
	}

public void restoreAllTablesFromCsv ( Context ctx , SQLiteDatabase db , String suffix ) { for ( TableHelper table : getTableHelpers ( ) ) { table . restore ( db , ctx , suffix ) ; } }

Restore all tables from CSV files, one per table

@param ctx
@param db
@param suffix Optional filename suffix, none if null

Restore all tables from CSV files one per table


void writeIndex(Filer filer) {
		StandardLocation location = StandardLocation.SOURCE_OUTPUT;
		FileObject indexFile;
		try {
			indexFile = filer.createResource(location, "com.turbomanage.storm",
					ENV_FILE);
			OutputStream fos = indexFile.openOutputStream();
			PrintWriter out = new PrintWriter(fos);
			// Dump converters
			out.println(BEGIN_CONVERTERS);
			for (ConverterModel converter : converters) {
				converter.writeToIndex(out);
			}
			out.println(END_CONVERTERS);
			// Dump databases
			for (DatabaseModel dbModel : dbModels.values()) {
				dbModel.writeToIndex(out);
			}
			out.close();
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

void
writeIndex
(
Filer
filer
)
{
StandardLocation
location
=
StandardLocation
.
SOURCE_OUTPUT
;
FileObject
indexFile
;
try
{
indexFile
=
filer
.
createResource
(
location
,
"com.turbomanage.storm"
,
ENV_FILE
)
;
OutputStream
fos
=
indexFile
.
openOutputStream
(
)
;
PrintWriter
out
=
new
PrintWriter
(
fos
)
;
// Dump converters
out
.
println
(
BEGIN_CONVERTERS
)
;
for
(
ConverterModel
converter
:
converters
)
{
converter
.
writeToIndex
(
out
)
;
}
out
.
println
(
END_CONVERTERS
)
;
// Dump databases
for
(
DatabaseModel
dbModel
:
dbModels
.
values
(
)
)
{
dbModel
.
writeToIndex
(
out
)
;
}
out
.
close
(
)
;
}
catch
(
IOException
e
)
{
throw
new
RuntimeException
(
e
)
;
}
}

Write the current model state to a file in support of incremental
compilation.

@see StormEnvironment#readIndex(Filer)

@param Filer
used by the annotation processor

Write the current model state to a file in support of incremental compilation .


public Query createQuery(final EntityManager manager) {
		if (manager == null) {
			throw new NullPointerException("Entity Manager required");
		}

		final Query query = manager.createQuery(render());

		for (Parameter<?> parameter : parameters) {
			parameter.apply(query);
		}

		return query;
	}

public
Query
createQuery
(
final
EntityManager
manager
)
{
if
(
manager
==
)
{
throw
new
NullPointerException
(
"Entity Manager required"
)
;
}
final
Query
query
=
manager
.
createQuery
(
render
(
)
)
;
for
(
Parameter
<
>
parameter
:
parameters
)
{
parameter
.
apply
(
query
)
;
}
return
query
;
}

Returns a JPA Query with all previously specified parameters added.

@param manager
JPA EntityManager
@return JPA Query

Returns a JPA Query with all previously specified parameters added .


public <T> TypedQuery<T> createQuery(final EntityManager manager,
			Class<T> type) {
		if (manager == null) {
			throw new NullPointerException("Entity Manager required");
		}

		TypedQuery<T> result = manager.createQuery(render(), type);

		for (Parameter<?> parameter : parameters) {
			parameter.apply(result);
		}

		return result;
	}

public
<
T
>
TypedQuery
<
T
>
createQuery
(
final
EntityManager
manager
,
Class
<
T
>
type
)
{
if
(
manager
==
)
{
throw
new
NullPointerException
(
"Entity Manager required"
)
;
}
TypedQuery
<
T
>
result
=
manager
.
createQuery
(
render
(
)
,
type
)
;
for
(
Parameter
<
>
parameter
:
parameters
)
{
parameter
.
apply
(
result
)
;
}
return
result
;
}

Returns a JPA TypedQuery with all previously specified parameters added.

@param manager
JPA EntityManager
@param type
the type of the query result
@return JPA Query

Returns a JPA TypedQuery with all previously specified parameters added .


public String render() {

		StringBuilder query = new StringBuilder();

		if (!select.isEmpty()) {
			query.append("SELECT ");
			query.append(StringUtils.join(select.items));
		}

		if (!deleteFrom.isEmpty()) {
			query.append("DELETE FROM ");
			query.append(deleteFrom.item);
		}

		if (!update.isEmpty()) {
			query.append("UPDATE ");
			query.append(update.item);

			if (!set.isEmpty()) {
				query.append(" SET ");
				query.append(StringUtils.join(set.items));
			}
		}

		if (!from.isEmpty()) {
			query.append(" FROM ");
			query.append(StringUtils.join(from.items));
		}

		if (!where.isEmpty()) {
			query.append(" WHERE ");
			query.append(where.render());
		}

		if (!group.isEmpty()) {
			query.append(" GROUP BY ");
			query.append(StringUtils.join(group.items));
		}

		if (order.isEmpty() == false) {
			query.append(" ORDER BY ");
			query.append(StringUtils.join(order.items));
		}

		return query.toString();

	}

public
String
render
(
)
{
StringBuilder
query
=
new
StringBuilder
(
)
;
if
(
!
select
.
isEmpty
(
)
)
{
query
.
append
(
"SELECT "
)
;
query
.
append
(
StringUtils
.
join
(
select
.
items
)
)
;
}
if
(
!
deleteFrom
.
isEmpty
(
)
)
{
query
.
append
(
"DELETE FROM "
)
;
query
.
append
(
deleteFrom
.
item
)
;
}
if
(
!
update
.
isEmpty
(
)
)
{
query
.
append
(
"UPDATE "
)
;
query
.
append
(
update
.
item
)
;
if
(
!
set
.
isEmpty
(
)
)
{
query
.
append
(
" SET "
)
;
query
.
append
(
StringUtils
.
join
(
set
.
items
)
)
;
}
}
if
(
!
from
.
isEmpty
(
)
)
{
query
.
append
(
" FROM "
)
;
query
.
append
(
StringUtils
.
join
(
from
.
items
)
)
;
}
if
(
!
where
.
isEmpty
(
)
)
{
query
.
append
(
" WHERE "
)
;
query
.
append
(
where
.
render
(
)
)
;
}
if
(
!
group
.
isEmpty
(
)
)
{
query
.
append
(
" GROUP BY "
)
;
query
.
append
(
StringUtils
.
join
(
group
.
items
)
)
;
}
if
(
order
.
isEmpty
(
)
==
false
)
{
query
.
append
(
" ORDER BY "
)
;
query
.
append
(
StringUtils
.
join
(
order
.
items
)
)
;
}
return
query
.
toString
(
)
;
}

Renders this object as JPQL query string.

@return the query as string

Renders this object as JPQL query string .


public int delete(Long id) {
		if (id != null) {
			return getWritableDb().delete(th.getTableName(), th.getIdCol() + "=?", new String[]{id.toString()});
		}
		return 0;
	}

public int delete ( Long id ) { if ( id != null ) { return getWritableDb ( ) . delete ( th . getTableName ( ) , th . getIdCol ( ) + "=?" , new String [ ] { id . toString ( ) } ) ; } return 0 ; }

Deletes a single row by ID. Returns the number of rows deleted
or 0 if unsuccessful.

@param id
@return count of rows deleted

Deletes a single row by ID . Returns the number of rows deleted or 0 if unsuccessful .


public long save(T obj) {
		if (th.getId(obj) == 0) {
			return insert(obj);
		}
		long updated = update(obj);
		if (updated == 1) {
			return 0;
		}
		return -1;
	}

public long save ( T obj ) { if ( th . getId ( obj ) == 0 ) { return insert ( obj ) ; } long updated = update ( obj ) ; if ( updated == 1 ) { return 0 ; } return - 1 ; }

Insert or update.

@param obj An entity
@return 0 if updated, -1 if err, else new ID


public long update(T obj) {
		ContentValues cv = th.getEditableValues(obj);
		Long id = th.getId(obj);
		int numRowsUpdated = getWritableDb().update(th.getTableName(), cv, th.getIdCol()
				+ "=?", new String[] { id.toString() });
		return numRowsUpdated;
	}

public long update ( T obj ) { ContentValues cv = th . getEditableValues ( obj ) ; Long id = th . getId ( obj ) ; int numRowsUpdated = getWritableDb ( ) . update ( th . getTableName ( ) , cv , th . getIdCol ( ) + "=?" , new String [ ] { id . toString ( ) } ) ; return numRowsUpdated ; }

Update all columns for the row having the ID matching
the provided entity's ID.

@param obj An entity
@return count of updated rows

Update all columns for the row having the ID matching the provided entity s ID .


public <V extends Object> WhereItems notIn(final String expression,
			final V... array) {
		items.add(new WhereIn(builder(), expression, true, array));
		return this;
	}

public < V extends Object > WhereItems notIn ( final String expression , final V ... array ) { items . add ( new WhereIn ( builder ( ) , expression , true , array ) ) ; return this ; }

Adds a "NOT IN" predicate.

@param expression
SQL expression, e.g. "expression" of
"expression NOT IN (...)", actually the left part of the
predicate
@param array
array of literal values
@return this object


public QueryBuilder subquery(final String lhsPredicate) {
		final WhereSubquery subquery = new WhereSubquery(builder(),
				lhsPredicate);
		items.add(subquery);
		return subquery.getQueryBuilder();
	}

public QueryBuilder subquery ( final String lhsPredicate ) { final WhereSubquery subquery = new WhereSubquery ( builder ( ) , lhsPredicate ) ; items . add ( subquery ) ; return subquery . getQueryBuilder ( ) ; }

Adds a sub-query predicate.

@param lhsPredicate
left hand side of the predicate, i.e. expression and operator,
e.g. "field IN" or "EXISTS"
@return the added subquery builder


Stack255 nextActiveStack() {
    activeStack = (activeStack + 1) % stacks.size();
    return (Stack255) stacks.get(activeStack);
  }

Stack255 nextActiveStack ( ) { activeStack = ( activeStack + 1 ) % stacks . size ( ) ; return ( Stack255 ) stacks . get ( activeStack ) ; }

Makes the next intentions stack active using a round robin scheme.
@return the newly active stack.

Makes the next intentions stack active using a round robin scheme .


Stack255 getEmptyIntentionStack() {
    // If the active stack is empty then return it (don't check other stacks)
    if (!stacks.isEmpty() && getActiveStack().isEmpty()) {
      return getActiveStack();
    }
    // else create an empty stack, add it to the list ot stacks, and return it
    Stack255 stack = new Stack255((byte) 8, (byte) 2);
    stacks.push(stack);
    return stack;
  }

Returns an empty intentions stack.
Creates a new intentions stack and adds it to the list of stacks if needed.
@return the newly created stack

Returns an empty intentions stack . Creates a new intentions stack and adds it to the list of stacks if needed .


public void add(Plan plan, Set<Belief> planBindings) {
    if (plan == null) {
      return;
    }
    // remove any old bindings, making sure to decrement the cached size
    if (this.bindings.containsKey(plan)) {
      Set<Belief> oldBindings = this.bindings.remove(plan);
      if (oldBindings == null || oldBindings.isEmpty()) {
        cachedsize--;
      } else {
        cachedsize -= oldBindings.size();
      }
    }
    // add this binding and update the cached size
    this.bindings.put(plan, planBindings);
    if (planBindings == null || planBindings.isEmpty()) {
      cachedsize++;
    } else {
      cachedsize += planBindings.size();
    }
  }

Add the set of bindings for a given plan to this store. Any previously stored bindings for this
plan will be replaced.

@param plan the plan type
@param planBindings the available bindings

Add the set of bindings for a given plan to this store . Any previously stored bindings for this plan will be replaced .


public Plan selectPlan(PlanSelectionPolicy policy) {
    Plan plan = null;
    int index = 0;
    switch (policy) {
      case FIRST:
      case LAST:
        Plan[] plans = bindings.keySet().toArray(new Plan[0]);
        plan = (policy == PlanSelectionPolicy.FIRST) ? plans[0] : plans[plans.length - 1];
        index = (policy == PlanSelectionPolicy.FIRST) ? 0 : plans.length - 1;
        setPlanVariables(plan.getAgent(), plan, bindings.get(plan), index);
        break;
      case RANDOM:
        plan = selectPlanAtRandom();
        break;
      default:
        // TODO: ignore remaining polic
        break;
    }
    return plan;
  }

public
Plan
selectPlan
(
PlanSelectionPolicy
policy
)
{
Plan
plan
=
;
int
index
=
0
;
switch
(
policy
)
{
case
FIRST
:
case
LAST
:
Plan
[
]
plans
=
bindings
.
keySet
(
)
.
toArray
(
new
Plan
[
0
]
)
;
plan
=
(
policy
==
PlanSelectionPolicy
.
FIRST
)
plans
[
0
]
:
plans
[
plans
.
length
1
]
;
index
=
(
policy
==
PlanSelectionPolicy
.
FIRST
)
0
:
plans
.
length
1
;
setPlanVariables
(
plan
.
getAgent
(
)
,
plan
,
bindings
.
get
(
plan
)
,
index
)
;
break
;
case
RANDOM
:
plan
=
selectPlanAtRandom
(
)
;
break
;
default
:
// TODO: ignore remaining polic
break
;
}
return
plan
;
}

Selects a plan instance from the set of plan bindings, using the given policy.

@param policy the policy to use for plan selection
@return the selected plan, or {@code null} if something went wrong

Selects a plan instance from the set of plan bindings using the given policy .


private Plan selectPlanAtRandom() {
    Plan plan = null;
    Set<Belief> vars = null;
    int index = rand.nextInt(size());
    int idx = 0;
    boolean bindingsExist = false;
    for (Plan p : bindings.keySet()) {
      vars = bindings.get(p);
      bindingsExist = (vars != null && !vars.isEmpty());
      idx += bindingsExist ? vars.size() : 1;
      if (idx > index) {
        plan = p;
        if (bindingsExist) {
          index = index - (idx - vars.size());
          setPlanVariables(plan.getAgent(), plan, vars, index);
        }
        break;
      }
    }
    return plan;
  }

private Plan selectPlanAtRandom ( ) { Plan plan = null ; Set < Belief > vars = null ; int index = rand . nextInt ( size ( ) ) ; int idx = 0 ; boolean bindingsExist = false ; for ( Plan p : bindings . keySet ( ) ) { vars = bindings . get ( p ) ; bindingsExist = ( vars != null && ! vars . isEmpty ( ) ) ; idx += bindingsExist ? vars . size ( ) : 1 ; if ( idx > index ) { plan = p ; if ( bindingsExist ) { index = index - ( idx - vars . size ( ) ) ; setPlanVariables ( plan . getAgent ( ) , plan , vars , index ) ; } break ; } } return plan ; }

Selects a plan instance at random from the set of plan bindings.

@return a randomly selected plan instance, or null if ther are no bindings to choose from

Selects a plan instance at random from the set of plan bindings .


private final void setPlanVariables(Agent agent, Plan planInstance, Set<Belief> results,
      int choice) {
    if (agent == null || planInstance == null) {
      return;
    }
    Belief belief = getResultAtIndex(results, choice);
    if (belief == null) {
      return;
    }
    Object[] tuple = belief.getTuple();
    if (tuple == null) {
      return;
    }
    int index = 0;
    HashMap<String, Object> vars = new HashMap<String, Object>();
    for (Object o : belief.getTuple()) {
      try {
        String fieldname = ABeliefStore.getFieldName(agent.getId(), belief.getBeliefset(), index);
        vars.put(fieldname, o);
      } catch (BeliefBaseException e) {
        Log.error(
            "Agent " + agent.getId() + " could not retrive belief set field: " + e.getMessage());
      }
      index++;
    }
    planInstance.setPlanVariables(vars);
  }

private
final
void
setPlanVariables
(
Agent
agent
,
Plan
planInstance
,
Set
<
Belief
>
results
,
int
choice
)
{
if
(
agent
==
||
planInstance
==
)
{
return
;
}
Belief
belief
=
getResultAtIndex
(
results
,
choice
)
;
if
(
belief
==
)
{
return
;
}
Object
[
]
tuple
=
belief
.
getTuple
(
)
;
if
(
tuple
==
)
{
return
;
}
int
index
=
0
;
HashMap
<
String
,
Object
>
vars
=
new
HashMap
<
String
,
Object
>
(
)
;
for
(
Object
o
:
belief
.
getTuple
(
)
)
{
try
{
String
fieldname
=
ABeliefStore
.
getFieldName
(
agent
.
getId
(
)
,
belief
.
getBeliefset
(
)
,
index
)
;
vars
.
put
(
fieldname
,
o
)
;
}
catch
(
BeliefBaseException
e
)
{
Log
.
error
(
"Agent "
+
agent
.
getId
(
)
+
" could not retrive belief set field: "
+
e
.
getMessage
(
)
)
;
}
index
++
;
}
planInstance
.
setPlanVariables
(
vars
)
;
}

Sets the plan instance variables using the given results set.

@param agent the agent for which this operation applies
@param planInstance the plan instance that is to be populated
@param results the beliefs set representing all plan bindings
@param choice index of the belief that is to be used to populate the plan instance variables

Sets the plan instance variables using the given results set .


private Belief getResultAtIndex(Set<Belief> results, int index) {
    Belief belief = null;
    if (!(results == null || index < 0 || index >= results.size())) {
      int idx = 0;
      for (Belief b : results) {
        if (idx == index) {
          belief = b;
          break;
        }
        idx++;
      }
    }
    return belief;
  }

private Belief getResultAtIndex ( Set < Belief > results , int index ) { Belief belief = null ; if ( ! ( results == null || index < 0 || index >= results . size ( ) ) ) { int idx = 0 ; for ( Belief b : results ) { if ( idx == index ) { belief = b ; break ; } idx ++ ; } } return belief ; }

Gets the result at the given index from the results set.

@param results results set (implementation must support predictable iteration order)
@param index the index within the set {@code (0 < index < results.size())} to retrieve
@return the result at the given index, or null if there was an error

Gets the result at the given index from the results set .


public byte[] getParents() {
    if (parents == null) {
      return null;
    }
    byte[] arr = new byte[parents.length];
    System.arraycopy(parents, 0, arr, 0, arr.length);
    return arr;
  }

public byte [ ] getParents ( ) { if ( parents == null ) { return null ; } byte [ ] arr = new byte [ parents . length ] ; System . arraycopy ( parents , 0 , arr , 0 , arr . length ) ; return arr ; }

Gets the parents of this object in the Goal-Plan tree.

@return array of parent IDs, or null if this object has no parents

Gets the parents of this object in the Goal - Plan tree .


public byte[] getChildren() {
    if (children == null) {
      return null;
    }
    byte[] arr = new byte[children.length];
    System.arraycopy(children, 0, arr, 0, arr.length);
    return arr;
  }

public byte [ ] getChildren ( ) { if ( children == null ) { return null ; } byte [ ] arr = new byte [ children . length ] ; System . arraycopy ( children , 0 , arr , 0 , arr . length ) ; return arr ; }

Gets all the children of this object in the Goal-Plan tree.

@return array of children IDs, or null if this object has no children

Gets all the children of this object in the Goal - Plan tree .


public static byte[] grow(byte[] bytes, int increment) {
    if (bytes == null) {
      return new byte[1];
    }
    byte[] temp = new byte[bytes.length + increment];
    System.arraycopy(bytes, 0, temp, 0, bytes.length);
    return temp;
  }

public static byte [ ] grow ( byte [ ] bytes , int increment ) { if ( bytes == null ) { return new byte [ 1 ] ; } byte [ ] temp = new byte [ bytes . length + increment ] ; System . arraycopy ( bytes , 0 , temp , 0 , bytes . length ) ; return temp ; }

Grows the given array by the given size.

@param bytes the array to grow
@param increment the size by which to grow it
@return the new extended array with all the contents of the old array copied over

Grows the given array by the given size .


public static Logger createLogger(String name, Level level, String file) {
    LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
    PatternLayoutEncoder ple = new PatternLayoutEncoder();
    ple.setPattern("%date %level [%thread] %logger{10} [%file:%line]%n%msg%n%n");
    ple.setContext(lc);
    ple.start();
    FileAppender<ILoggingEvent> fileAppender = new FileAppender<ILoggingEvent>();
    fileAppender.setFile(file);
    fileAppender.setEncoder(ple);
    fileAppender.setAppend(false);
    fileAppender.setContext(lc);
    fileAppender.start();
    logger = (Logger) LoggerFactory.getLogger(name);
    logger.detachAndStopAllAppenders(); // detach console (doesn't seem to work)
    logger.addAppender(fileAppender); // attach file appender
    logger.setLevel(level);
    logger.setAdditive(true); // set to true if root should log too

    return logger;
  }

Creates a new logger.

@param name a name for the logger
@param level the logging level for the logger
@param file the file to output all logging to
@return the created logger


public void step() {
    if (body == null || body.length == 0 || index < 0 || index >= body.length) {
      return;
    }
    body[index++].step();
  }

public void step ( ) { if ( body == null || body . length == 0 || index < 0 || index >= body . length ) { return ; } body [ index ++ ] . step ( ) ; }

Performs a single step of this plan, i.e., progresses this intention.

Performs a single step of this plan i . e . progresses this intention .


public void setGoals(byte[] arr) {
    if (arr == null) {
      goals = null;
      return;
    }
    goals = new byte[arr.length];
    System.arraycopy(arr, 0, goals, 0, goals.length);
  }

public void setGoals ( byte [ ] arr ) { if ( arr == null ) { goals = null ; return ; } goals = new byte [ arr . length ] ; System . arraycopy ( arr , 0 , goals , 0 , goals . length ) ; }

Sets the list of goals for this agent.

@param arr array of goal IDs


static void pauseForUserInput() {
    System.out.println("Press the Enter/Return key to continue..");
    Scanner in = new Scanner(System.in);
    in.nextLine();
    in.close();
  }

Waits for user to press a key before continuing. Useful for connecting to a profiler

Waits for user to press a key before continuing . Useful for connecting to a profiler


public static void initIntentionSelectionPools(int nagents, int ncores) {
    Main.poolsize = (nagents > ncores) ? (nagents / ncores) : 1;
    Main.npools = (nagents > ncores) ? ncores : nagents;
  }

public static void initIntentionSelectionPools ( int nagents , int ncores ) { Main . poolsize = ( nagents > ncores ) ? ( nagents / ncores ) : 1 ; Main . npools = ( nagents > ncores ) ? ncores : nagents ; }

Initialises the intention selection pools.

@param nagents total number of agents to distribution between the intention selection pools
@param ncores total number of cores

Initialises the intention selection pools .


static void initIntentionSelectionThreads(Config config) {
    int ncores = config.getNumThreads();
    Main.intentionSelectors = new IntentionSelector[ncores];
    for (int i = 0; i < Main.npools; i++) {
      Main.intentionSelectors[i] = new IntentionSelector(i, config.getRandomSeed());
    }
  }

static void initIntentionSelectionThreads ( Config config ) { int ncores = config . getNumThreads ( ) ; Main . intentionSelectors = new IntentionSelector [ ncores ] ; for ( int i = 0 ; i < Main . npools ; i ++ ) { Main . intentionSelectors [ i ] = new IntentionSelector ( i , config . getRandomSeed ( ) ) ; } }

Starts the intention selection threads that each handle a pool of agents.

@param config the global configuration object

Starts the intention selection threads that each handle a pool of agents .


static void startIntentionSelectionThreads() {
    for (int i = 0; i < Main.npools; i++) {
      Thread thread = new Thread(Main.intentionSelectors[i]);
      thread.setName("jill-" + i);
      thread.start(); // start and wait at the entry barrier
    }
  }

static
void
startIntentionSelectionThreads
(
)
{
for
(
int
i
=
0
;
i
<
Main
.
npools
;
i
++
)
{
Thread
thread
=
new
Thread
(
Main
.
intentionSelectors
[
i
]
)
;
thread
.
setName
(
"jill-"
+
i
)
;
thread
.
start
(
)
;
// start and wait at the entry barrier
}
}

Starts the intention selection threads .


static void shutdownIntentionSelectionThreads() {
    for (int i = 0; i < Main.npools; i++) {
      Main.intentionSelectors[i].shutdown();
    }
  }

static void shutdownIntentionSelectionThreads ( ) { for ( int i = 0 ; i < Main . npools ; i ++ ) { Main . intentionSelectors [ i ] . shutdown ( ) ; } }


public static void registerExtension(JillExtension extension) {
    if (extension != null) {
      GlobalState.eventHandlers.add(extension);
      Main.logger.info("Registered Jill extension: " + extension);
    } else {
      Main.logger.warn("Cannot register null extension; will ignore.");
    }
  }

Registers a new Jill extension.

@param extension the extension to register


public static void reset() {
    agentTypes = new AObjectCatalog("agentTypes", 5, 5);
    goalTypes = new AObjectCatalog("goalTypes", 10, 5);
    planTypes = new AObjectCatalog("planTypes", 20, 5);
    agents = null;
    beliefbase = null;
    eventHandlers = new HashSet<JillExtension>();
  }

public static void reset ( ) { agentTypes = new AObjectCatalog ( "agentTypes" , 5 , 5 ) ; goalTypes = new AObjectCatalog ( "goalTypes" , 10 , 5 ) ; planTypes = new AObjectCatalog ( "planTypes" , 20 , 5 ) ; agents = null ; beliefbase = null ; eventHandlers = new HashSet < JillExtension > ( ) ; }


public static boolean loadAgent(String className, int num, AObjectCatalog agents) {

    // Load the Agent class
    Class<?> aclass = loadClass(className, Agent.class);
    if (aclass == null) {
      return false;
    }

    // Save this agent type to the catalog of known agent types
    AgentType atype = new AgentType(className);
    atype.setAgentClass(aclass);
    GlobalState.agentTypes.push(atype);

    // Find the goals that this agent has
    String[] goals = getGoalsFromAgentInfoAnnotation(aclass);
    if (goals.length == 0) {
      return false;
    }

    // First pass: get the goals and their plans (flat goal-plan list)
    loadGoalPlanNodes(atype, goals);

    // Second pass: complete the goal-plan hierarchy
    completeGoalPlanHierarchy();

    // Now create the specified number of instances of this agent type
    createAgentsInCatalog(agents, atype, aclass, num);

    // return success
    return true;
  }

Creates a given number of agents of a given Class, and adds the newly created agents to the
given store.

@param className the fully qualified Java classname for the agents begin created
@param num the number of agents (class instances) to create
@param agents the store to which these agents should be added
@return true if agents were successfully created and added, false otherwise

Creates a given number of agents of a given Class and adds the newly created agents to the given store .


private static boolean processPlansForGoal(GoalType gtype, String[] plans) {
    for (int j = 0; j < plans.length; j++) {
      // Load the Plan class
      Class<?> pclass = loadClass(plans[j], Plan.class);
      if (pclass == null) {
        return false;
      }
      // Found the plan class, so add this plan to the catalog of known plan types
      logger.info("Found Plan " + pclass.getName() + " that handles Goal " + gtype.getName());
      PlanType ptype = new PlanType(pclass.getName());
      ptype.setPlanClass(pclass);
      GlobalState.planTypes.push(ptype);
      // Set up the parent/child links between them (makings of a goal-plan tree)
      ptype.addParent((byte) gtype.getId());
      gtype.addChild((byte) ptype.getId());
    }
    return true;
  }

Loads the given plan classes and sets up parent-child links with the given goal type.

@param gtype the goal for which the list of plans is provided
@param plans list of plans to be loaded
@return true if successful, false otherwise

Loads the given plan classes and sets up parent - child links with the given goal type .


private static void createAgentsInCatalog(AObjectCatalog agents, AgentType atype, Class<?> aclass,
      int num) {
    int added = 0;
    try {
      for (int i = 0; i < num; i++) {
        // Create a new instance (name prefix 'a' for agents)
        Agent agent =
            (Agent) (aclass.getConstructor(String.class).newInstance("a" + Integer.toString(i)));
        // Assign the static goal plan tree hierarchy to this instance
        agent.setGoals(atype.getGoals());
        // Add this instance to the catalog of agent instances
        agents.push(agent);
        added++;
      }
      logger.info("Finished loading {} agents", added);

    } catch (NoSuchMethodException | SecurityException | InstantiationException
        | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
      logger.error("Could not create instance of class " + aclass.getName());
    }

  }

Creates the specified number of agent instances of the given type and adds them to the catalog.

@param agents the catalog to add agents to
@param atype the type of agents to create
@param aclass the class of that agent type
@param num the number of instances of that agent (class) to create

Creates the specified number of agent instances of the given type and adds them to the catalog .


private static Class<?> loadClass(String className, Class<?> classType) {
    Class<?> aclass = null;
    try {
      aclass = Class.forName(className);
    } catch (ClassNotFoundException e) {
      logger.error("Class not found: " + className, e);
      return null;
    }
    if (!classType.isAssignableFrom(aclass)) {
      logger.error("Class '" + className + "' is not of type " + classType.getName());
      return null;
    }
    logger.info("Found class " + className + " of type " + classType.getName());
    return aclass;
  }

private
static
Class
<
>
loadClass
(
String
className
,
Class
<
>
classType
)
{
Class
<
>
aclass
=
;
try
{
aclass
=
Class
.
forName
(
className
)
;
}
catch
(
ClassNotFoundException
e
)
{
logger
.
error
(
"Class not found: "
+
className
,
e
)
;
return
;
}
if
(
!
classType
.
isAssignableFrom
(
aclass
)
)
{
logger
.
error
(
"Class '"
+
className
+
"' is not of type "
+
classType
.
getName
(
)
)
;
return
;
}
logger
.
info
(
"Found class "
+
className
+
" of type "
+
classType
.
getName
(
)
)
;
return
aclass
;
}

Loads the class of given name and type.

@param className the fully qualified class name
@param classType the class type to check against
@return the loaded class, or null if unsuccessful

Loads the class of given name and type .


public static JillExtension loadExtension(String className) {
    JillExtension extension = null;
    Class<?> eclass;
    try {
      // Check that we have the extension class, else abort
      eclass = Class.forName(className);
      if (!JillExtension.class.isAssignableFrom(eclass)) {
        logger
            .error("Class '" + className + "' does not implement " + JillExtension.class.getName());
        return null;
      }
      logger.info("Loading extension " + className);
      extension = (JillExtension) (eclass.newInstance());
    } catch (ClassNotFoundException | SecurityException | InstantiationException
        | IllegalAccessException | IllegalArgumentException e) {
      logger.error("Could not load extension " + className, e);
    }
    return extension;
  }

Loads a Jill extension.

@param className the fully qalified Java classname of the extension
@return an instance of the Jill extension class


public static boolean isNameEqual(AObject obj1, AObject obj2) {
    // Not equal if the names are null, or empty, or not the same size
    if (obj1.name == null || obj2.name == null || obj1.name.length != obj2.name.length
        || obj1.name.length == 0) {
      return false;
    }
    // Not equal if any name character is different
    for (int i = 0; i < obj1.name.length; i++) {
      if (obj1.name[i] != obj2.name[i]) {
        return false;
      }
    }
    // Else equal
    return true;
  }

Checks if two objects have the same name. The check is case sensitive.

@param obj1 the first object
@param obj2 the second object
@return true if the objects have the same non-null non-empty name, and false otherwise

Checks if two objects have the same name . The check is case sensitive .


public static String usage() {
    return GlobalConstant.APP_HEADER + "\n\n" + "usage: " + Main.class.getName()
        + "  [options] --agent-class <agentclass> --num-agents <numagents>" + "\n"
        + "   --config <string>                 load configuration from string" + "\n"
        + "   --configfile <file>               load configuration from file" + "\n"
        + "   --exit-on-idle <boolean>          forces system exit when all agents are "
        + "idle (default is '" + GlobalConstant.EXIT_ON_IDLE + "')\n"
        + "   --help                            print this usage message and exit \n"
        + "   --plan-selection-policy <policy>  policy for selecting from plan instances "
        + "(FIRST, RANDOM, or LAST (default is '" + GlobalConstant.PLAN_SELECTION_POLICY + "')\n"
        + "   --plan-instances-limit <number>   maximum number of applicable plan instances "
        + "to consider (default is '" + GlobalConstant.PLAN_INSTANCES_LIMIT + "')\n";
  }

Returns a usage string for the Jill command line arguments.

@return the usage string

Returns a usage string for the Jill command line arguments .


public static void parse(String[] args) {
    for (int i = 0; args != null && i < args.length; i++) {
      // First parse args that don't require an option
      if ("--help".equals(args[i])) {
        abort(null);
      }
      // Now parse args that must be accompanied by an option
      if (i + 1 < args.length) {
        parseArgumentWithOption(args[i], args[++i]); // force increment the counter
      }
    }
    // Abort if required args were not given
    if (config == null) {
      abort("Configuration file or string was not given");
    } else if (config.getAgents() == null || config.getAgents().isEmpty()) {
      abort("Configuration is missing agents specification");
    }
  }

Parses the given command line arguments.

@param args the command line arguments

Parses the given command line arguments .


private static void parseArgumentWithOption(String arg, String opt) {
    switch (arg) {
      case "--config":
        config = loadConfigFromString(opt);
        break;
      case "--configfile":
        config = loadConfigFromFile(opt);
        break;
      case "--exit-on-idle":
        GlobalConstant.EXIT_ON_IDLE = Boolean.parseBoolean(opt);
        break;
      case "--plan-selection-policy":
        try {
          GlobalConstant.PLAN_SELECTION_POLICY = GlobalConstant.PlanSelectionPolicy.valueOf(opt);
        } catch (IllegalArgumentException e) {
          abort("Unknown plan selection policy '" + opt + "'");
        }
        break;
      case "--plan-instances-limit":
        try {
          GlobalConstant.PLAN_INSTANCES_LIMIT = Integer.parseInt(opt);
        } catch (NumberFormatException e) {
          abort("Option value '" + opt + "' is not a number");
        }
        break;
      default:
        // Ignore any other arguments (which may be used by components external to Jill)
        break;
    }
  }

Parses the given command line argument and associated option. Will abort if an unrecoverable
error occurs.

@param arg the argument to parse
@param opt the options to parse for that argument

Parses the given command line argument and associated option . Will abort if an unrecoverable error occurs .


public static void doEval(BeliefBase bb, int agentId, String query) throws BeliefBaseException {
    final long t0 = System.currentTimeMillis();
    bb.eval(agentId, query);
    final long t1 = System.currentTimeMillis();
    Log.info("Agent " + agentId + " searched for '" + query + "' " + Log.formattedDuration(t0, t1));
  }

public
static
void
doEval
(
BeliefBase
bb
,
int
agentId
,
String
query
)
throws
BeliefBaseException
{
final
long
t0
=
System
.
currentTimeMillis
(
)
;
bb
.
eval
(
agentId
,
query
)
;
final
long
t1
=
System
.
currentTimeMillis
(
)
;
Log
.
info
(
"Agent "
+
agentId
+
" searched for '"
+
query
+
"' "
+
Log
.
formattedDuration
(
t0
,
t1
)
)
;
}

Evaluates the given query on the given belief base for the agent.

@param bb the belief base to query
@param agentId the agent for which the query applies
@param query the belief query
@throws BeliefBaseException on query evaluation error
@since 0.3.4

Evaluates the given query on the given belief base for the agent .


public AObject get(int index) {
    if (index >= 0 && index < objects.length) {
      return objects[index];
    }
    return null;
  }

public AObject get ( int index ) { if ( index >= 0 && index < objects . length ) { return objects [ index ] ; } return null ; }

Gets the object at the given index of the catalog.

@param index the index of the object
@return the object at that index

Gets the object at the given index of the catalog .