answer
stringlengths 17
10.2M
|
|---|
package org.ohmage.domain.campaign.prompt;
import java.io.IOException;
import java.util.UUID;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonGenerator;
import org.json.JSONException;
import org.json.JSONObject;
import org.ohmage.config.grammar.custom.ConditionValuePair;
import org.ohmage.domain.campaign.Prompt;
import org.ohmage.domain.campaign.PromptResponse;
import org.ohmage.domain.campaign.Response.NoResponse;
import org.ohmage.domain.campaign.response.AudioPromptResponse;
import org.ohmage.exception.DomainException;
/**
* <p>
* This class represents an audio prompt.
* </p>
*
* @author John Jenkins
*/
public class AudioPrompt extends Prompt {
/**
* The JSON key for the maximum duration.
*/
public static final String JSON_KEY_MAX_DURATION = "max_duration";
/**
* The JSON key for the maximum duration.
*/
public static final String XML_KEY_MAX_DURATION = "maxDuration";
/**
* The maximum number of milliseconds that the recording may last.
*/
private final Long maxDuration;
/**
* Creates an audio prompt.
*
* @param id
* The unique identifier for the prompt within its survey item
* group.
*
* @param condition
* The condition determining if this prompt should be displayed.
*
* @param unit
* The unit value for this prompt.
*
* @param text
* The text to be displayed to the user for this prompt.
*
* @param explanationText
* A more-verbose version of the text to be displayed to the user
* for this prompt.
*
* @param skippable
* Whether or not this prompt may be skipped.
*
* @param skipLabel
* The text to show to the user indicating that the prompt may be
* skipped.
*
* @param displayLabel
* The display label for this prompt.
*
* @param index
* This prompt's index in its container's list of survey items.
*
* @param maxDuration
*
* @throws DomainException
* Thrown if the maximum duration is negative.
*/
public AudioPrompt(
final String id,
final String condition,
final String unit,
final String text,
final String explanationText,
final boolean skippable,
final String skipLabel,
final String displayLabel,
final int index,
final Long maxDuration)
throws DomainException {
super(
id,
condition,
unit,
text,
explanationText,
skippable,
skipLabel,
displayLabel,
Type.AUDIO,
index);
// Validate the maximum duration.
if(maxDuration <= 0) {
throw
new DomainException("The maximum duration must be positive.");
}
this.maxDuration = maxDuration;
}
/**
* Returns the maximum allowed duration for a recording from this prompt.
*
* @return The maximum allowed duration for a recording from this prompt.
*/
public long getMaxDuration() {
return maxDuration;
}
/**
* Conditions are not allowed for audio prompts unless they are
* {@link NoResponse} values.
*
* @param pair The pair to validate.
*
* @throws DomainException Always thrown because conditions are not allowed
* for photo prompts.
*/
@Override
public void validateConditionValuePair(
final ConditionValuePair pair)
throws DomainException {
throw
new DomainException(
"Conditions are not allowed for audio prompts.");
}
/*
* (non-Javadoc)
* @see org.ohmage.domain.campaign.Prompt#validateValue(java.lang.Object)
*/
@Override
public Object validateValue(final Object value) throws DomainException {
// If it's already a NoResponse value, then return make sure that if it
// was skipped that it as skippable.
if(value instanceof NoResponse) {
if(NoResponse.SKIPPED.equals(value) && (! skippable())) {
throw new DomainException(
"The prompt, '" +
getId() +
"', was skipped, but it is not skippable.");
}
return value;
}
// If it is already a UUID value, then return it.
else if(value instanceof UUID) {
return value;
}
// If it is a String value then attempt to decode it into a NoResponse
// value or a UUID value.
else if(value instanceof String) {
String valueString = (String) value;
try {
return NoResponse.valueOf(valueString);
}
catch(IllegalArgumentException notNoResponse) {
try {
return UUID.fromString(valueString);
}
catch(IllegalArgumentException notUuid) {
throw new DomainException(
"The string response value was not decodable into a UUID for prompt '" +
getId() +
"': " +
valueString);
}
}
}
else {
throw new DomainException(
"The value is not decodable as a reponse value for prompt '" +
getId() +
"'.");
}
}
/*
* (non-Javadoc)
* @see org.ohmage.domain.campaign.Prompt#createResponse(java.lang.Integer, java.lang.Object)
*/
@Override
public AudioPromptResponse createResponse(
final Integer repeatableSetIteration,
final Object response)
throws DomainException {
return
new AudioPromptResponse(
this,
repeatableSetIteration,
response);
}
/**
* Creates a JSONObject that represents this photo prompt.
*
* @return A JSONObject that represents this photo prompt.
*
* @throws JSONException There was a problem creating the JSONObject.
*/
@Override
public JSONObject toJson() throws JSONException {
JSONObject result = super.toJson();
if(maxDuration != null) {
result.put(JSON_KEY_MAX_DURATION, maxDuration);
}
return result;
}
/*
* (non-Javadoc)
* @see org.ohmage.domain.campaign.SurveyItem#toConcordia(org.codehaus.jackson.JsonGenerator)
*/
@Override
public void toConcordia(JsonGenerator generator)
throws JsonGenerationException,
IOException {
// The response is always an object.
generator.writeStartObject();
generator.writeStringField("type", "object");
// The fields array.
generator.writeArrayFieldStart("schema");
// The first field in the object is the prompt's ID.
generator.writeStartObject();
generator.writeStringField("name", PromptResponse.JSON_KEY_PROMPT_ID);
generator.writeStringField("type", "string");
generator.writeEndObject();
// The second field in the object is the response's value.
generator.writeStartObject();
generator.writeStringField("name", PromptResponse.JSON_KEY_RESPONSE);
generator.writeStringField("type", "string");
generator.writeEndObject();
// End the array of fields.
generator.writeEndArray();
// End the object.
generator.writeEndObject();
}
}
|
package org.pathwayeditor.figure.geometry;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
public class LineSegment {
private static final double LINE_WIDTH_TOL = 0.1;
private final Logger logger = Logger.getLogger(this.getClass());
private final Point origin;
private final Point terminus;
public LineSegment(Point origin, Point terminus){
this.origin = origin;
this.terminus = terminus;
}
public LineSegment(double startX, double startY, double endX, double endY){
this.origin = new Point(startX, startY);
this.terminus = new Point(endX, endY);
}
/**
* Create a new line segment starting at the current line's origin and with the same unit vector,
* but with a different magnitude.
* @param length the length of the new line segment, which must be <code>> 0</code>.
* @return the new line segment, which cannot be null
*/
public LineSegment newLineSegment(double length){
if(length <= 0.0) throw new IllegalArgumentException("length must be a positive non-zero value");
double theta = this.angle();
double y = length * Math.sin(theta);
double x = length * Math.cos(theta);
return new LineSegment(this.origin, this.origin.translate(x, y));
}
/**
* The inverted line segment.
* @return return the reverse line segment to this one, with the origin and terminus swapped.
*/
public LineSegment invert(){
return new LineSegment(this.terminus, this.origin);
}
/**
* Determines the intersect point between this line and the line passed
* in as a parameter. If they intersect, then true is returned and the
* point reference passed in will be set to the intersect point.
* If they don't intersect, then the method returns <code>false</code>.
*
* @param line <code>MyLine</code> to test the intersection against.
* @param nTolerance int tolerance value for detecting the intersection.
* @return <code>Point</code> that represents the intersection with this line,
* or <code>null</code> if the calculation is not possible.
*/
public Point intersect(final LineSegment line, final double nTolerance) {
if(logger.isDebugEnabled()){
logger.debug("Looking for intersection between line this=" + this + ",other=" + line);
}
List<Point> intersections = getLinesIntersections(line);
if (intersections.size()>1) {
intersections.add(getOrigin());
intersections.add(getTerminus());
}
Point retVal = null;
for (int i=0; i<intersections.size() && retVal == null; i++) {
Point result = intersections.get(i);
if(logger.isTraceEnabled()){
logger.trace("Found intersection at:" + result);
}
if (containsPoint(result, nTolerance)
&& line.containsPoint(result, nTolerance)) {
logger.trace("Intersection point accepted: within line limits");
retVal = result;
}
}
if(logger.isDebugEnabled()){
logger.debug("Intersection point found=" + retVal);
}
return retVal;
}
/**
* Checks if this line segment contains the given point within a tolerance value.
*
* @param aPoint <code>Point</code> to test if contained in this line.
* @param lineWidth the width of the line to be tested. The thickness of the line is
* considered as part of the line for the pusposes of containment.
* @return <code>boolean</code> <code>true</code> if the given point lies on this
* segment, <code>false</code> otherwise.
*/
public final boolean containsPoint(final Point aPoint, final double lineWidth) {
Point theOrigin = getOrigin();
Point theTerminus = getTerminus();
double x1 = theTerminus.getX() - theOrigin.getX();
double y1 = theTerminus.getY()-theOrigin.getY();
double x2 = aPoint.getX() - theOrigin.getX();
double y2 = aPoint.getY() - theOrigin.getY();
// Calc if on the line by getting the cross-product of the vector of the line and the vector
// from the origin to the point.
double v_xy_cross_v_xp = (x1 * y2) - (y1 * x2);
double v1 = theOrigin.getDistance(theTerminus);
double v2 = theOrigin.getDistance(aPoint);
// sine theta from cross-product
double sinTheta = v_xy_cross_v_xp / (v1 * v2);
// cos theta from scalar product
double cosTheta = (x1 * x2 + y1 * y2) / (v1 * v2);
// if both +ve then in 1st quadrant and so we should check tolerane
// otherwise there cannot be an intersection
boolean retVal = false;
if(sinTheta >= 0.0 && cosTheta >= 0.0){
// now check the length of the opposite side of the RHT and see if it is within the tolerance length
double adj = v2 * cosTheta;
// check adj length is less than length of line - i.e. is the point on the line
if(adj <= v1){
double opp = v2 * sinTheta;
double halfLineHeight = (lineWidth/2);
halfLineHeight += halfLineHeight * LINE_WIDTH_TOL;
retVal = opp < halfLineHeight;
}
}
if(logger.isTraceEnabled()){
logger.trace("containsPoint=" + retVal + ",point=" + aPoint + ",start=" + theOrigin + ",end=" + theTerminus + ",sinTheta=" + sinTheta + ",cosTheta=" + cosTheta
+ "lineWidth=" + lineWidth);
}
return retVal;
}
/**
* Calculate the length of the line segment.
*
* @return the <code>double</code> length of the line segment.
*/
public final double length() {
return getOrigin().getDistance(getTerminus());
}
/**
* Returns intersection points of two lines that contain this line segment and
* the argumet line segment.
* The list of intersection points may contain at most two points and will contain
* 2 points if and only if the lines are equal. The 2 points will be the end points
* of the parameter line segment
*
* @param line - the line segment
* @return intersection points of two lines that contain this line segment and
* the argumet line segment.
*/
public List<Point> getLinesIntersections (LineSegment line) {
List<Point> intersections = new ArrayList<Point>();
double temp[] = getEquation();
double a1 = temp[0];
double b1 = temp[1];
double c1 = temp[2];
temp = line.getEquation();
double a2 = temp[0];
double b2 = temp[1];
double c2 = temp[2];
// Cramer's rule for the system of linear equations
double det = a1*b2 - b1*a2;
if (det == 0) {
if (a1==a2 && b1==b2 && c1==c2) {
// if lines are the same, then instead of infinite number of intersections
// we will put the end points of the line segment passed as an argument
intersections.add(line.getOrigin());
intersections.add(line.getTerminus());
}
}
else {
intersections.add(new Point((c1*b2-b1*c2)/det, (a1*c2-c1*a2)/det));
}
return intersections;
}
public LineSegment translate(Point p){
return new LineSegment(this.origin.translate(p), this.terminus.translate(p));
}
/**
* Get the angle of the vector of this line. Effectively the theta component of
* the polar coordinate of the end point of this line using the start point
* as the origin.
* @return the angle in radians which is in the range -pi to pi.
*/
public double angle(){
return Math.atan2(this.getYDisplacement(), this.getXDisplacement());
}
/**
* Returns the coefficients of the generalized equation of the line passing through
* points (x1,y1) and (x2,y2)
* Generalized line equation: ax+by=c => a==result[0], b==result[1], c==result[2]
*
* @param x1 - x coordinate of the 1st point
* @param y1 - y coordinate of the 1st point
* @param x2 - x coordinate of the 2nd point
* @param y2 - y coordinate of the 2nd point
* @return the coefficients of the generalized equation of the line passing through
* points (x1,y1) and (x2,y2)
*/
private static double [] getLineEquation(double x1, double y1, double x2, double y2) {
double equation[] = new double[3];
for (int i=0; i<3; i++)
equation[i]=0;
if (x1 == x2 && y1 == y2)
return equation;
if (x1 == x2) {
equation[0]=1;
equation[1]=0;
equation[2]=x1;
return equation;
}
equation[0]=(y1-y2)/(x2-x1);
equation[1]=1.0;
equation[2]=y2+equation[0]*x2;
return equation;
}
public Point getMidPoint(){
return new Point(this.origin.getX() + getXDisplacement()/2, this.origin.getY() + this.getYDisplacement()/2);
}
public double getXDisplacement(){
return terminus.getX() - origin.getX();
}
public double getYDisplacement(){
return terminus.getY() - origin.getY();
}
public double getLength(){
double i = terminus.getX() - origin.getX();
double j = terminus.getY() - origin.getY();
return Math.sqrt(i * i + j * j);
}
public Vector getVector(){
return new Vector(terminus.getX() - origin.getX(), terminus.getY() - origin.getY(), 0.0);
}
/**
* Gets the normal to this line on the left-hand-side of the line. This
* has the same magnitude as the line segment.
* @return the left hand normal of this line as a vector originating at the line's origin.
*/
public Vector getLeftHandNormal(){
double i = terminus.getX() - origin.getX();
double j = terminus.getY() - origin.getY();
return new Vector(-j, i, 0);
}
/**
* Gets the normal to this line on the right-hand-side of the line. This
* has the same magnitude as the line segment.
* @return the right hand normal of this line as a vector originating at the line's origin.
*/
public Vector getRightHandNormal(){
double i = terminus.getX() - origin.getX();
double j = terminus.getY() - origin.getY();
return new Vector(j, -i, 0);
}
/**
* Returns array with 3 numbers in it, which are the coefficients of the
* generalized line equation of the line corresponding to this line segment
* a*x+b*y=c is the equation => result[0]=a, result[1]=b, result[2]=c
*
* @return an array with 3 numbers in it, which are the coefficients of the
* generalized line equation
*/
public double [] getEquation() {
return getLineEquation(origin.getX(), origin.getY(), terminus.getX(), terminus.getY());
}
public Point getOrigin() {
return origin;
}
public Point getTerminus() {
return terminus;
}
@Override
public String toString(){
StringBuilder builder = new StringBuilder(this.getClass().getSimpleName());
builder.append("(origin=");
builder.append(this.origin);
builder.append("terminus=");
builder.append(this.terminus);
builder.append(")");
return builder.toString();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((origin == null) ? 0 : origin.hashCode());
result = prime * result
+ ((terminus == null) ? 0 : terminus.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof LineSegment))
return false;
LineSegment other = (LineSegment) obj;
if (origin == null) {
if (other.origin != null)
return false;
} else if (!origin.equals(other.origin))
return false;
if (terminus == null) {
if (other.terminus != null)
return false;
} else if (!terminus.equals(other.terminus))
return false;
return true;
}
}
|
package org.springframework.web.context;
import javax.servlet.ServletContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextException;
import org.springframework.context.config.ConfigurableApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.context.support.XmlWebApplicationContext;
/**
* Performs the actual initialization work for the root application context.
* Called by ContextLoaderListener and ContextLoaderServlet.
*
* <p>Regards a "contextClass" parameter at the web.xml context-param level,
* falling back to the default context class (XmlWebApplicationContext) if not found.
* With the default ContextLoader, a context class needs to implement
* ConfigurableWebApplicationContext.
*
* <p>Passes a "contextConfigLocation" context-param to the context instance,
* parsing it into potentially multiple file paths which can be separated by any
* number of commas and spaces, like "applicationContext1.xml, applicationContext2.xml".
* If not explicitly specified, the context implementation is supposed to use a
* default location (with XmlWebApplicationContext: "/WEB-INF/applicationContext.xml").
*
* @author Juergen Hoeller
* @author Colin Sampaleanu
* @since 17.02.2003
* @see ContextLoaderListener
* @see ContextLoaderServlet
* @see ConfigurableWebApplicationContext
* @see org.springframework.web.context.support.XmlWebApplicationContext
*/
public class ContextLoader {
/**
* Config param for the root WebApplicationContext implementation class to use:
* "contextClass"
*/
public static final String CONTEXT_CLASS_PARAM = "contextClass";
/**
* Default context class for ContextLoader.
* @see org.springframework.web.context.support.XmlWebApplicationContext
*/
public static final Class DEFAULT_CONTEXT_CLASS = XmlWebApplicationContext.class;
/**
* Name of servlet context parameter that can specify the config location
* for the root context, falling back to DEFAULT_CONFIG_LOCATION.
*/
public static final String CONFIG_LOCATION_PARAM = "contextConfigLocation";
private final Log logger = LogFactory.getLog(ContextLoader.class);
/**
* Initialize Spring's web application context for the given servlet context,
* regarding the "contextClass" and "contextConfigLocation" context-params.
* @param servletContext current servlet context
* @return the new WebApplicationContext
* @throws BeansException if the context couldn't be initialized
* @see #CONTEXT_CLASS_PARAM
* @see #CONFIG_LOCATION_PARAM
*/
public WebApplicationContext initWebApplicationContext(ServletContext servletContext) throws BeansException {
servletContext.log("Loading root WebApplicationContext");
ApplicationContext parent = loadParentContext(servletContext);
WebApplicationContext wac = createWebApplicationContext(servletContext, parent);
logger.info("Using context class [" + wac.getClass().getName() + "] for root WebApplicationContext");
WebApplicationContextUtils.publishWebApplicationContext(wac);
return wac;
}
/**
* Instantiate the root WebApplicationContext for this loader, either a default
* XmlWebApplicationContext or a custom context class if specified.
* This implementation expects custom contexts to implement ConfigurableWebApplicationContext.
* Can be overridden in subclasses.
* @throws BeansException if the context couldn't be initialized
* @see #CONTEXT_CLASS_PARAM
* @see #DEFAULT_CONTEXT_CLASS
* @see ConfigurableWebApplicationContext
* @see org.springframework.web.context.support.XmlWebApplicationContext
*/
protected WebApplicationContext createWebApplicationContext(ServletContext servletContext,
ApplicationContext parent) throws BeansException {
String contextClassName = servletContext.getInitParameter(CONTEXT_CLASS_PARAM);
Class contextClass = DEFAULT_CONTEXT_CLASS;
if (contextClassName != null) {
try {
contextClass = Class.forName(contextClassName, true, Thread.currentThread().getContextClassLoader());
}
catch (ClassNotFoundException ex) {
throw new ApplicationContextException("Failed to load context class [" + contextClassName + "]", ex);
}
if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {
throw new ApplicationContextException("Custom context class [" + contextClassName +
"] is not of type ConfigurableWebApplicationContext");
}
}
ConfigurableWebApplicationContext wac = (ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);
wac.setParent(parent);
wac.setServletContext(servletContext);
String configLocation = servletContext.getInitParameter(CONFIG_LOCATION_PARAM);
if (configLocation != null) {
wac.setConfigLocations(WebApplicationContextUtils.parseContextConfigLocation(configLocation));
}
wac.refresh();
return wac;
}
/**
* Template method which may be overridden by a subclass to load or obtain
* an ApplicationContext instance which will be used as the parent context
* of the root WebApplicationContext if it is not null.
* @param servletContext
* @return the parent application context, or null if none
* @throws BeansException if the context couldn't be initialized
*/
protected ApplicationContext loadParentContext(ServletContext servletContext) throws BeansException {
return null;
}
/**
* Close Spring's web application context for the given servlet context.
* @param servletContext current servlet context
*/
public void closeContext(ServletContext servletContext) throws ApplicationContextException {
servletContext.log("Closing root WebApplicationContext");
WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
if (wac instanceof ConfigurableApplicationContext) {
((ConfigurableApplicationContext) wac).close();
}
}
}
|
package com.cradle.iitc_mobile;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.AssetManager;
import android.net.Uri;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.util.Base64;
import android.util.Base64OutputStream;
import android.webkit.WebResourceResponse;
import android.widget.Toast;
import com.cradle.iitc_mobile.IITC_Mobile.ResponseHandler;
import org.json.JSONObject;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.net.URLEncoder;
import java.util.HashMap;
public class IITC_FileManager {
private static final WebResourceResponse EMPTY =
new WebResourceResponse("text/plain", "UTF-8", new ByteArrayInputStream("".getBytes()));
private static final String WRAPPER_NEW = "wrapper(info);";
private static final String WRAPPER_OLD =
"script.appendChild(document.createTextNode('('+ wrapper +')('+JSON.stringify(info)+');'));\n"
+ "(document.body || document.head || document.documentElement).appendChild(script);";
public static final String DOMAIN = ".iitcm.localhost";
/**
* copies the contents of a stream into another stream and (optionally) closes the output stream afterwards
*
* @param inStream
* the stream to read from
* @param outStream
* the stream to write to
* @param closeOutput
* whether to close the output stream when finished
*
* @throws IOException
*/
public static void copyStream(final InputStream inStream, final OutputStream outStream, final boolean closeOutput)
throws IOException
{
// in case Android includes Apache commons IO in the future, this function should be replaced by IOUtils.copy
final int bufferSize = 4096;
final byte[] buffer = new byte[bufferSize];
int len = 0;
try {
while ((len = inStream.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
} finally {
if (outStream != null && closeOutput)
outStream.close();
}
}
public static HashMap<String, String> getScriptInfo(final String js) {
final HashMap<String, String> map = new HashMap<String, String>();
String header = "";
if (js != null && js.contains("==UserScript==") && js.contains("==/UserScript==")) {
header = js.substring(js.indexOf("==UserScript=="),
js.indexOf("==/UserScript=="));
}
// remove new line comments
header = header.replace("\n
// get a list of key-value
final String[] attributes = header.split(" +");
// add default values
map.put("version", "not found");
map.put("name", "unknown");
map.put("description", "");
map.put("category", "Misc");
// add parsed values
for (int i = 0; i < attributes.length; i++) {
// search for attributes and use the value
if (attributes[i].equals("@version")) {
map.put("version", attributes[i + 1]);
}
if (attributes[i].equals("@name")) {
map.put("name", attributes[i + 1]);
}
if (attributes[i].equals("@description")) {
map.put("description", attributes[i + 1]);
}
if (attributes[i].equals("@category")) {
map.put("category", attributes[i + 1]);
}
}
return map;
}
public static String readStream(final InputStream stream) {
final ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
copyStream(stream, os, true);
} catch (final IOException e) {
Log.w(e);
return "";
}
return os.toString();
}
private final AssetManager mAssetManager;
private final IITC_Mobile mIitc;
private final String mIitcPath;
private final SharedPreferences mPrefs;
public IITC_FileManager(final IITC_Mobile iitc) {
mIitc = iitc;
mIitcPath = Environment.getExternalStorageDirectory().getPath() + "/IITC_Mobile/";
mPrefs = PreferenceManager.getDefaultSharedPreferences(iitc);
mAssetManager = mIitc.getAssets();
}
private InputStream getAssetFile(final String filename) throws IOException {
if (mPrefs.getBoolean("pref_dev_checkbox", false)) {
final File file = new File(mIitcPath + "dev/" + filename);
try {
return new FileInputStream(file);
} catch (final FileNotFoundException e) {
mIitc.runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(mIitc, "File " + mIitcPath +
"dev/" + filename + " not found. " +
"Disable developer mode or add iitc files to the dev folder.",
Toast.LENGTH_SHORT).show();
}
});
Log.w(e);
}
}
// load plugins from asset folder
return mAssetManager.open(filename);
}
private WebResourceResponse getFileRequest(final Uri uri) {
return new FileRequest(uri);
}
private WebResourceResponse getScript(final Uri uri) {
InputStream stream;
try {
stream = getAssetFile(uri.getPath().substring(1));
} catch (final IOException e) {
Log.w(e);
return EMPTY;
}
final InputStream data = prepareUserScript(stream);
return new WebResourceResponse("application/x-javascript", "UTF-8", data);
}
private HashMap<String, String> getScriptInfo(final InputStream stream) {
return getScriptInfo(readStream(stream));
}
private WebResourceResponse getUserPlugin(final Uri uri) {
if (!mPrefs.getBoolean(uri.getPath(), false)) {
Log.e("Attempted to inject user script that is not enabled by user: " + uri.getPath());
return EMPTY;
}
InputStream stream;
try {
stream = new FileInputStream(new File(uri.getPath()));
} catch (final IOException e) {
Log.w(e);
return EMPTY;
}
final InputStream data = prepareUserScript(stream);
return new WebResourceResponse("application/x-javascript", "UTF-8", data);
}
private InputStream prepareUserScript(final InputStream stream) {
String content = readStream(stream);
final HashMap<String, String> info = getScriptInfo(content);
final JSONObject jObject = new JSONObject(info);
final String gmInfo = "var GM_info={\"script\":" + jObject.toString() + "}";
content = content.replace(WRAPPER_OLD, WRAPPER_NEW);
return new ByteArrayInputStream((gmInfo + content).getBytes());
}
public String getFileRequestPrefix() {
return "//file-request" + DOMAIN + "/";
}
public String getIITCVersion() throws IOException {
final InputStream stream = getAssetFile("total-conversion-build.user.js");
return getScriptInfo(stream).get("version");
}
public WebResourceResponse getResponse(final Uri uri) {
String host = uri.getHost();
if (!host.endsWith(DOMAIN))
return EMPTY;
host = host.substring(0, host.length() - DOMAIN.length());
if ("script".equals(host))
return getScript(uri);
if ("user-plugin".equals(host))
return getUserPlugin(uri);
if ("file-request".equals(host))
return getFileRequest(uri);
Log.e("could not generate response for url: " + uri);
return EMPTY;
}
private class FileRequest extends WebResourceResponse implements ResponseHandler, Runnable {
private Intent mData;
private final String mFunctionName;
private int mResultCode;
private PipedOutputStream mStreamOut;
private FileRequest(final Uri uri) {
// create two connected streams we can write to after the file has been read
super("application/x-javascript", "UTF-8", new PipedInputStream());
try {
mStreamOut = new PipedOutputStream((PipedInputStream) getData());
} catch (final IOException e) {
Log.w(e);
}
// the function to call
mFunctionName = uri.getPathSegments().get(0);
// create the chooser Intent
final Intent target = new Intent(Intent.ACTION_GET_CONTENT);
|
package org.apache.jmeter.util;
/**
* Utility class to define the JMeter Version string
*
* @author sebb AT apache.org
* @version $revision$ $date$
*/
public class JMeterVersion
{
/*
* The VERSION string is updated by the Ant build file, which looks for the
* pattern: VERSION = <quote>.*<quote>
*
*/
static final String VERSION = "1.9.20031125";
private JMeterVersion() // Not instantiable
{
super();
}
}
|
package com.github.dreamhead.moco;
import com.github.dreamhead.moco.internal.*;
import static com.google.common.base.Preconditions.checkNotNull;
public abstract class Runner {
public static void running(final HttpServer httpServer, final Runnable runnable) throws Exception {
doRunning(runner(checkNotNull(httpServer)), checkNotNull(runnable));
}
public static void running(final HttpsServer httpServer, final Runnable runnable) throws Exception {
doRunning(runner(checkNotNull(httpServer)), checkNotNull(runnable));
}
public static void running(final SocketServer server, final Runnable runnable) throws Exception {
doRunning(runner(checkNotNull(server)), checkNotNull(runnable));
}
private static void doRunning(final Runner server, final Runnable runnable) throws Exception {
try {
server.start();
runnable.run();
} finally {
server.stop();
}
}
public static Runner runner(final HttpServer server) {
return new MocoHttpServer((ActualHttpServer) checkNotNull(server));
}
public static Runner runner(final SocketServer server) {
return new MocoSocketServer((ActualSocketServer)checkNotNull(server));
}
public abstract void start();
public abstract void stop();
}
|
package hex.rulefit;
import hex.ConfusionMatrix;
import hex.ScoringInfo;
import hex.genmodel.utils.DistributionFamily;
import hex.glm.GLM;
import hex.glm.GLMModel;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import water.DKV;
import water.Scope;
import water.TestUtil;
import water.fvec.Frame;
import water.fvec.Vec;
import water.runner.CloudSize;
import water.runner.H2ORunner;
import water.test.util.ConfusionMatrixUtils;
import static org.junit.Assert.*;
@RunWith(H2ORunner.class)
@CloudSize(1)
public class RuleFitTest extends TestUtil {
@Test
public void testBestPracticeExample() {
try {
Scope.enter();
final Frame fr = Scope.track(parse_test_file("./smalldata/gbm_test/titanic.csv"));
Scope.track(fr);
String responseColumnName = "survived";
asFactor(fr, responseColumnName);
asFactor(fr, "pclass");
fr.remove("name").remove();
fr.remove("ticket").remove();
fr.remove("cabin").remove();
fr.remove("embarked").remove();
fr.remove("boat").remove();
fr.remove("body").remove();
fr.remove("home.dest").remove();
RuleFitModel.RuleFitParameters params = new RuleFitModel.RuleFitParameters();
params._seed = 1234;
params._train = fr._key;
params._response_column = responseColumnName;
params._max_num_rules = 100;
params._model_type = RuleFitModel.ModelType.RULES;
params._distribution = DistributionFamily.bernoulli;
final RuleFitModel rfModel = new RuleFit(params).trainModel().get();
Scope.track_generic(rfModel);
System.out.println("Intercept: \n" + rfModel._output._intercept[0]);
System.out.println(rfModel._output._rule_importance);
final Frame fr2 = Scope.track(rfModel.score(fr));
Assert.assertTrue(rfModel.testJavaScoring(fr,fr2,1e-4));
Vec predictions = fr2.vec("predict");
Vec data = fr.vec("survived");
ConfusionMatrix ruleFitConfusionMatrix = ConfusionMatrixUtils.buildCM(data, predictions);
// GLM to compare:
GLMModel.GLMParameters glmParameters = rfModel.glmModel._parms;
glmParameters._train = fr._key;
final GLMModel glmModel = new GLM(glmParameters).trainModel().get();
Scope.track_generic(glmModel);
final Frame fr3 = Scope.track(glmModel.score(fr));
predictions = fr3.vec("predict");
ConfusionMatrix glmConfusionMatrix = ConfusionMatrixUtils.buildCM(data, predictions);
System.out.println("RuleFit ACC: \n" + ruleFitConfusionMatrix.accuracy());
System.out.println("RuleFit specificity: \n" + ruleFitConfusionMatrix.specificity());
System.out.println("RuleFit sensitivity: \n" + ruleFitConfusionMatrix.recall());
assertEquals(ruleFitConfusionMatrix.accuracy(),0.7868601986249045,1e-4);
assertEquals(ruleFitConfusionMatrix.specificity(),0.8207663782447466,1e-4);
assertEquals(ruleFitConfusionMatrix.recall(),0.732,1e-4);
System.out.println("pure GLM ACC: \n" + glmConfusionMatrix.accuracy());
System.out.println("pure GLM specificity: \n" + glmConfusionMatrix.specificity());
System.out.println("pure GLM sensitivity: \n" + glmConfusionMatrix.recall());
assertEquals(glmConfusionMatrix.accuracy(),0.7815126050420168,1e-4);
assertEquals(glmConfusionMatrix.specificity(),0.8145859085290482,1e-4);
assertEquals(glmConfusionMatrix.recall(),0.728,1e-4);
ScoringInfo RuleFitScoringInfo = rfModel.glmModel.getScoringInfo()[0];
ScoringInfo GLMScoringInfo = glmModel.getScoringInfo()[0];
System.out.println("RuleFit MSE: " + RuleFitScoringInfo.scored_train._mse);
System.out.println("GLM MSE: " + GLMScoringInfo.scored_train._mse);
System.out.println("RuleFit r2: " + RuleFitScoringInfo.scored_train._r2);
System.out.println("GLM r2: " + GLMScoringInfo.scored_train._r2);
} finally {
Scope.exit();
}
}
@Test
public void testBestPracticeExampleWithLinearVariables() {
// the same as above but uses rules + linear terms
try {
Scope.enter();
final Frame fr = Scope.track(parse_test_file("./smalldata/gbm_test/titanic.csv"));
String responseColumnName = "survived";
asFactor(fr, responseColumnName);
asFactor(fr, "pclass");
fr.remove("name").remove();
fr.remove("ticket").remove();
fr.remove("cabin").remove();
fr.remove("embarked").remove();
fr.remove("boat").remove();
fr.remove("body").remove();
fr.remove("home.dest").remove();
final Vec weightsVector = Vec.makeOne(fr.numRows());
final String weightsColumnName = "weights";
fr.add(weightsColumnName, weightsVector);
DKV.put(fr);
RuleFitModel.RuleFitParameters params = new RuleFitModel.RuleFitParameters();
params._seed = 1234;
params._train = fr._key;
params._response_column = responseColumnName;
params._max_num_rules = 100;
params._model_type = RuleFitModel.ModelType.RULES_AND_LINEAR;
params._weights_column = "weights";
final RuleFitModel rfModel = new RuleFit(params).trainModel().get();
Scope.track_generic(rfModel);
System.out.println("Intercept: \n" + rfModel._output._intercept[0]);
System.out.println(rfModel._output._rule_importance);
final Frame fr2 = Scope.track(rfModel.score(fr));
Assert.assertTrue(rfModel.testJavaScoring(fr,fr2,1e-4));
Vec predictions = fr2.vec("predict");
Vec data = fr.vec("survived");
ConfusionMatrix ruleFitConfusionMatrix = ConfusionMatrixUtils.buildCM(data, predictions);
// GLM to compare:
GLMModel.GLMParameters glmParameters = rfModel.glmModel._parms;
glmParameters._train = fr._key;
final GLMModel glmModel = new GLM(glmParameters).trainModel().get();
Scope.track_generic(glmModel);
final Frame fr3 = Scope.track(glmModel.score(fr));
predictions = fr3.vec("predict");
ConfusionMatrix glmConfusionMatrix = ConfusionMatrixUtils.buildCM(data, predictions);
System.out.println("RuleFit ACC: \n" + ruleFitConfusionMatrix.accuracy());
System.out.println("RuleFit specificity: \n" + ruleFitConfusionMatrix.specificity());
System.out.println("RuleFit sensitivity: \n" + ruleFitConfusionMatrix.recall());
assertEquals(ruleFitConfusionMatrix.accuracy(),0.7685255920550038,1e-4);
assertEquals(ruleFitConfusionMatrix.specificity(),0.761433868974042,1e-4);
assertEquals(ruleFitConfusionMatrix.recall(),0.78,1e-4);
System.out.println("pure GLM ACC: \n" + glmConfusionMatrix.accuracy());
System.out.println("pure GLM specificity: \n" + glmConfusionMatrix.specificity());
System.out.println("pure GLM sensitivity: \n" + glmConfusionMatrix.recall());
assertEquals(glmConfusionMatrix.accuracy(),0.7815126050420168,1e-4);
assertEquals(glmConfusionMatrix.specificity(),0.8145859085290482,1e-4);
assertEquals(glmConfusionMatrix.recall(),0.728,1e-4);
ScoringInfo RuleFitScoringInfo = rfModel.glmModel.getScoringInfo()[0];
ScoringInfo GLMScoringInfo = glmModel.getScoringInfo()[0];
System.out.println("RuleFit MSE: " + RuleFitScoringInfo.scored_train._mse);
System.out.println("GLM MSE: " + GLMScoringInfo.scored_train._mse);
System.out.println("RuleFit r2: " + RuleFitScoringInfo.scored_train._r2);
System.out.println("GLM r2: " + GLMScoringInfo.scored_train._r2);
} finally {
Scope.exit();
}
}
@Test
public void testCarsRules() {
try {
Scope.enter();
final Frame fr = Scope.track(parse_test_file("./smalldata/junit/cars.csv"));
RuleFitModel.RuleFitParameters params = new RuleFitModel.RuleFitParameters();
params._seed = 1234;
params._response_column = "power (hp)";
params._ignored_columns = new String[]{"name"};
params._train = fr._key;
params._max_num_rules = 200;
params._max_rule_length = 5;
params._model_type = RuleFitModel.ModelType.RULES;
RuleFitModel model = new RuleFit( params).trainModel().get();
Scope.track_generic(model);
System.out.println("Intercept: \n" + model._output._intercept[0]);
System.out.println(model._output._rule_importance);
final Frame fr2 = Scope.track(model.score(fr));
double[] expectedCoeffs = new double[] {13.54857, 8.37943, 8.33535, 7.78235, 7.62020, -7.57865, -5.59529, 5.54992, -4.04620, -3.73222, -3.66495,
-3.42013, -3.15808, -2.35471, -2.18179, 1.37956, -1.21565, -1.14398, -0.72780, -0.65794, -0.60032, -0.51938, -0.24730, -0.21409, 0.16232,
0.15663, 0.11327, 0.09523, -0.02568, -0.02156, 0.00606, 0.00080, -0.00059, 0.00000, 0.00000, -0.00000, -0.00000};
String[] expectedVars = new String[] {"tree_0.T1.R", "tree_1.T26.RL", "tree_1.T49.LR", "tree_1.T29.RL", "tree_1.T19.LR", "tree_1.T14.LR",
"tree_1.T7.LR", "tree_1.T27.LR", "tree_1.T5.RR", "tree_2.T31.LLL", "tree_1.T1.LL", "tree_2.T37.LLL", "tree_1.T37.LL", "tree_1.T15.LL", "tree_1.T2.RL",
"tree_0.T2.L", "tree_1.T3.RR", "tree_3.T14.LRRR", "tree_1.T27.RL", "tree_1.T21.RL", "tree_1.T34.RL", "tree_2.T39.LRL", "tree_1.T6.LL", "tree_0.T1.L",
"tree_0.T12.R", "tree_0.T19.L", "tree_0.T27.L", "tree_0.T23.R", "tree_0.T2.R", "tree_1.T8.LL", "tree_1.T4.RL", "tree_0.T28.R", "tree_0.T12.L",
"tree_1.T38.RL", "tree_0.T15.R", "tree_0.T5.R", "tree_1.T10.LL"};
for (int i = 0; i < model._output._rule_importance.getRowDim(); i++) {
assertEquals(expectedCoeffs[i], (double) model._output._rule_importance.get(i,1),1e-4);
assertEquals(expectedVars[i], model._output._rule_importance.get(i,0));
}
GLMModel.GLMParameters glmParameters = model.glmModel._parms;
glmParameters._train = fr._key;
final GLMModel glmModel = new GLM(glmParameters).trainModel().get();
Scope.track_generic(glmModel);
Scope.track(glmModel.score(fr));
Assert.assertTrue(model.testJavaScoring(fr,fr2,1e-4));
ScoringInfo RuleFitScoringInfo = model.glmModel.getScoringInfo()[0];
ScoringInfo GLMScoringInfo = glmModel.getScoringInfo()[0];
System.out.println("RuleFit MSE: " + RuleFitScoringInfo.scored_train._mse);
System.out.println("GLM MSE: " + GLMScoringInfo.scored_train._mse);
System.out.println("RuleFit r2: " + RuleFitScoringInfo.scored_train._r2);
System.out.println("GLM r2: " + GLMScoringInfo.scored_train._r2);
} finally {
Scope.exit();
}
}
@Test
public void testCarsRulesAndLinear() {
// only linear variables are important in this case
try {
Scope.enter();
final Frame fr = Scope.track(parse_test_file( "./smalldata/junit/cars.csv"));
RuleFitModel.RuleFitParameters params = new RuleFitModel.RuleFitParameters();
params._seed = 1234;
params._response_column = "power (hp)";
params._ignored_columns = new String[]{"name"};
params._train = fr._key;
params._max_num_rules = 200;
params._max_rule_length = 5;
params._model_type = RuleFitModel.ModelType.RULES_AND_LINEAR;
params._distribution = DistributionFamily.gaussian;
final RuleFitModel model = new RuleFit(params).trainModel().get();
Scope.track_generic(model);
System.out.println("Intercept: \n" + model._output._intercept[0]);
System.out.println(model._output._rule_importance);
double[] expectedCoeffs = new double[] {-3.76823, -0.12718, 0.11265, -0.08923, 0.01601};
String[] expectedVars = new String[] {"linear.0-60 mph (s)", "linear.economy (mpg)", "linear.displacement (cc)", "linear.year", "linear.weight (lb)"};
for (int i = 0; i < model._output._rule_importance.getRowDim(); i++) {
assertEquals(expectedCoeffs[i], (double) model._output._rule_importance.get(i,1),1e-4);
assertEquals(expectedVars[i], model._output._rule_importance.get(i,0));
}
final Frame scoredByRF = Scope.track(model.score(fr));
Vec RFpredictions = scoredByRF.vec("predict");
GLMModel.GLMParameters glmParameters = model.glmModel._parms;
glmParameters._train = fr._key;
final GLMModel glmModel = new GLM(glmParameters).trainModel().get();
Scope.track_generic(glmModel);
final Frame scoredByGLM = Scope.track(glmModel.score(fr));
Vec GLMpredictions = scoredByGLM.vec("predict");
Assert.assertTrue(model.testJavaScoring(fr,scoredByRF,1e-4));
// should be equal because only linear terms were important during RF training
assertVecEquals(GLMpredictions, RFpredictions, 1e-4);
ScoringInfo RuleFitScoringInfo = model.glmModel.getScoringInfo()[0];
ScoringInfo GLMScoringInfo = glmModel.getScoringInfo()[0];
System.out.println("RuleFit MSE: " + RuleFitScoringInfo.scored_train._mse);
System.out.println("GLM MSE: " + GLMScoringInfo.scored_train._mse);
System.out.println("RuleFit r2: " + RuleFitScoringInfo.scored_train._r2);
System.out.println("GLM r2: " + GLMScoringInfo.scored_train._r2);
} finally {
Scope.exit();
}
}
@Test
public void testCarsLongRules() {
try {
Scope.enter();
final Frame fr = Scope.track(parse_test_file("./smalldata/junit/cars.csv"));
RuleFitModel.RuleFitParameters params = new RuleFitModel.RuleFitParameters();
params._seed = 1234;
params._response_column = "power (hp)";
params._ignored_columns = new String[]{"name"};
params._train = fr._key;
params._max_num_rules = 200;
params._max_rule_length = 500;
params._model_type = RuleFitModel.ModelType.RULES_AND_LINEAR;
final RuleFitModel model = new RuleFit(params).trainModel().get();
Scope.track_generic(model);
System.out.println("Intercept: \n" + model._output._intercept[0]);
System.out.println(model._output._rule_importance);
final Frame fr2 = Scope.track(model.score(fr));
double[] expectedCoeffs = new double[] {-3.76824, -0.12718, 0.11265, -0.08923, 0.01601};
String[] expectedVars = new String[] {"linear.0-60 mph (s)", "linear.economy (mpg)", "linear.displacement (cc)", "linear.year", "linear.weight (lb)"};
for (int i = 0; i < model._output._rule_importance.getRowDim(); i++) {
assertEquals(expectedCoeffs[i], (double) model._output._rule_importance.get(i,1),1e-4);
assertEquals(expectedVars[i], model._output._rule_importance.get(i,0));
}
Assert.assertTrue(model.testJavaScoring(fr, fr2,1e-4));
GLMModel.GLMParameters glmParameters = model.glmModel._parms;
glmParameters._train = fr._key;
final GLMModel glmModel = new GLM(glmParameters).trainModel().get();
Scope.track_generic(glmModel);
Scope.track(glmModel.score(fr));
ScoringInfo RuleFitScoringInfo = model.glmModel.getScoringInfo()[0];
ScoringInfo GLMScoringInfo = glmModel.getScoringInfo()[0];
System.out.println("RuleFit MSE: " + RuleFitScoringInfo.scored_train._mse);
System.out.println("GLM MSE: " + GLMScoringInfo.scored_train._mse);
System.out.println("RuleFit r2: " + RuleFitScoringInfo.scored_train._r2);
System.out.println("GLM r2: " + GLMScoringInfo.scored_train._r2);
} finally {
Scope.exit();
}
}
@Test
public void testBostonHousing() {
try {
Scope.enter();
final Frame fr = parse_test_file("./smalldata/gbm_test/BostonHousing.csv");
Scope.track(fr);
String responseColumnName = fr.lastVecName();
RuleFitModel.RuleFitParameters params = new RuleFitModel.RuleFitParameters();
params._seed = 12345;
params._train = fr._key;
params._model_type = RuleFitModel.ModelType.RULES;
params._response_column = responseColumnName;
final RuleFitModel rfModel = new RuleFit(params).trainModel().get();
Scope.track_generic(rfModel);
System.out.println("Intercept: \n" + rfModel._output._intercept[0]);
System.out.println(rfModel._output._rule_importance);
final Frame fr2 = Scope.track(rfModel.score(fr));
Assert.assertTrue(rfModel.testJavaScoring(fr,fr2,1e-4));
// GLM to compare:
GLMModel.GLMParameters glmParameters = rfModel.glmModel._parms;
glmParameters._train = fr._key;
final GLMModel glmModel = new GLM(glmParameters).trainModel().get();
Scope.track_generic(glmModel);
glmModel.score(fr);
ScoringInfo RuleFitScoringInfo = rfModel.glmModel.getScoringInfo()[0];
ScoringInfo GLMScoringInfo = glmModel.getScoringInfo()[0];
System.out.println("RuleFit MSE: " + RuleFitScoringInfo.scored_train._mse);
System.out.println("GLM MSE: " + GLMScoringInfo.scored_train._mse);
System.out.println("RuleFit r2: " + RuleFitScoringInfo.scored_train._r2);
System.out.println("GLM r2: " + GLMScoringInfo.scored_train._r2);
} finally {
Scope.exit();
}
}
@Test
public void testDiabetesWithWeights() {
try {
Scope.enter();
final Frame fr = parse_test_file("./smalldata/diabetes/diabetes_text_train.csv");
Scope.track(fr);
final Vec weightsVector = createRandomBinaryWeightsVec(fr.numRows(), 10);
final String weightsColumnName = "weights";
fr.add(weightsColumnName, weightsVector);
DKV.put(fr);
RuleFitModel.RuleFitParameters params = new RuleFitModel.RuleFitParameters();
params._seed = 12345;
params._train = fr._key;
params._model_type = RuleFitModel.ModelType.RULES_AND_LINEAR;
params._response_column = "diabetesMed";
params._weights_column = "weights";
final RuleFitModel rfModel = new RuleFit(params).trainModel().get();
Scope.track_generic(rfModel);
System.out.println("Intercept: \n" + rfModel._output._intercept[0]);
System.out.println(rfModel._output._rule_importance);
final Frame fr2 = Scope.track(rfModel.score(fr));
Assert.assertTrue(rfModel.testJavaScoring(fr,fr2,1e-4));
// GLM to compare:
GLMModel.GLMParameters glmParameters = rfModel.glmModel._parms;
glmParameters._train = fr._key;
final GLMModel glmModel = new GLM(glmParameters).trainModel().get();
Scope.track_generic(glmModel);
final Frame fr3 = Scope.track(glmModel.score(fr));
ScoringInfo RuleFitScoringInfo = rfModel.glmModel.getScoringInfo()[0];
ScoringInfo GLMScoringInfo = glmModel.getScoringInfo()[0];
System.out.println("RuleFit MSE: " + RuleFitScoringInfo.scored_train._mse);
System.out.println("GLM MSE: " + GLMScoringInfo.scored_train._mse);
System.out.println("RuleFit r2: " + RuleFitScoringInfo.scored_train._r2);
System.out.println("GLM r2: " + GLMScoringInfo.scored_train._r2);
} finally {
Scope.exit();
}
}
// h2o-3/smalldata/diabetes
}
|
package de.LittleRolf.MazeOverkill.rats;
import java.awt.Color;
import java.awt.Point;
import de.LittleRolf.MazeOverkill.data.Maze;
import de.LittleRolf.MazeOverkill.data.MazeField;
import de.LittleRolf.MazeOverkill.data.MazeRat;
/**
* A sample implementation of the wall follower method for solving simple mazes
*
* @author ole
*
*/
public class SimpleRat extends MazeRat {
public SimpleRat(Point p, Maze m) {
super(p, m);
}
@Override
public void performStep() {
if(checkIfTargetNearby())
return;
turnRight();
if (!goForward()) { // can go right?
turnLeft();
if (!goForward()) { // can go straight?
turnLeft();
if (!goForward()) { // what about left?
turnLeft();
goForward(); // OK, dead end
}
}
}
}
private boolean checkIfTargetNearby() {
try {
if (getRatSurrounding().get(Direction.NORTH).isTarget()) {
dir = Direction.NORTH;
goForward();
return true;
} else if (getRatSurrounding().get(Direction.EAST).isTarget()) {
dir = Direction.EAST;
goForward();
return true;
} else if (getRatSurrounding().get(Direction.SOUTH).isTarget()) {
dir = Direction.SOUTH;
goForward();
return true;
} else if (getRatSurrounding().get(Direction.WEST).isTarget()) {
dir = Direction.WEST;
goForward();
return true;
}
} catch (NullPointerException e) {
//Shit happens, on start or target field or maze border not there
}
return false;
}
@Override
public Color getColor() {
return Color.CYAN;
}
}
|
package de.bitdroid.flooding.news;
import java.text.SimpleDateFormat;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import de.bitdroid.flooding.R;
final class NewsListAdapter extends ArrayAdapter<NewsItem> {
private final static SimpleDateFormat dateFormatter
= new SimpleDateFormat("dd/M/yyyy hh:mm a");
private final Context context;
public NewsListAdapter(Context context) {
super(context, R.layout.news_item, NewsManager.getInstance(context).getAllItems());
this.context = context;
setNotifyOnChange(false);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater
= (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.news_item, parent, false);
NewsItem item = getItem(position);
TextView title = (TextView) view.findViewById(R.id.news_title);
TextView date = (TextView) view.findViewById(R.id.news_timestamp);
TextView content = (TextView) view.findViewById(R.id.news_content);
title.setText(item.getTitle());
date.setText(dateFormatter.format(item.getTimestamp()));
content.setText(item.getContent());
return view;
}
@Override
public void notifyDataSetChanged() {
clear();
addAll(NewsManager.getInstance(context).getAllItems());
super.notifyDataSetChanged();
setNotifyOnChange(false);
}
}
|
package de.jungblut.classification.eval;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import com.google.common.base.Preconditions;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import de.jungblut.classification.Classifier;
import de.jungblut.classification.ClassifierFactory;
import de.jungblut.datastructure.ArrayUtils;
import de.jungblut.math.DoubleVector;
import de.jungblut.partition.BlockPartitioner;
import de.jungblut.partition.Boundaries.Range;
/**
* Binary-/Multi-class classification evaluator utility that takes care of
* test/train splitting and its evaluation with various metrics.
*
* @author thomas.jungblut
*
*/
public final class Evaluator {
private Evaluator() {
throw new IllegalAccessError();
}
public static class EvaluationResult {
int numLabels, correct, trainSize, testSize, truePositive, falsePositive,
trueNegative, falseNegative;
int[][] confusionMatrix;
public double getPrecision() {
return ((double) truePositive) / (truePositive + falsePositive);
}
public double getRecall() {
return ((double) truePositive) / (truePositive + falseNegative);
}
public double getAccuracy() {
if (isBinary()) {
return ((double) truePositive + trueNegative)
/ (truePositive + trueNegative + falsePositive + falseNegative);
} else {
return correct / (double) testSize;
}
}
public double getF1Score() {
return 2d * (getPrecision() * getRecall())
/ (getPrecision() + getRecall());
}
public int getCorrect() {
if (!isBinary()) {
return correct;
} else {
return truePositive + trueNegative;
}
}
public int getNumLabels() {
return numLabels;
}
public int getTrainSize() {
return trainSize;
}
public int getTestSize() {
return testSize;
}
public int[][] getConfusionMatrix() {
return this.confusionMatrix;
}
public boolean isBinary() {
return numLabels == 2;
}
public void add(EvaluationResult res) {
numLabels += res.numLabels;
correct += res.correct;
trainSize += res.trainSize;
testSize += res.testSize;
truePositive += res.truePositive;
falsePositive += res.falsePositive;
trueNegative += res.trueNegative;
falseNegative += res.falseNegative;
if (this.confusionMatrix != null && res.confusionMatrix != null) {
for (int i = 0; i < numLabels; i++) {
for (int j = 0; j < numLabels; j++) {
this.confusionMatrix[i][j] += res.confusionMatrix[i][j];
}
}
}
}
public void average(int pn) {
final double n = pn;
numLabels /= n;
correct /= n;
trainSize /= n;
testSize /= n;
truePositive /= n;
falsePositive /= n;
trueNegative /= n;
falseNegative /= n;
if (this.confusionMatrix != null) {
for (int i = 0; i < numLabels; i++) {
for (int j = 0; j < numLabels; j++) {
this.confusionMatrix[i][j] /= n;
}
}
}
}
public int getTruePositive() {
return this.truePositive;
}
public int getFalsePositive() {
return this.falsePositive;
}
public int getTrueNegative() {
return this.trueNegative;
}
public int getFalseNegative() {
return this.falseNegative;
}
public void print() {
System.out.println("Number of labels: " + getNumLabels());
System.out.println("Trainingset size: " + getTrainSize());
System.out.println("Testset size: " + getTestSize());
System.out.println("Correctly classified: " + getCorrect());
System.out.println("Accuracy: " + getAccuracy());
if (isBinary()) {
System.out.println("TP: " + truePositive);
System.out.println("FP: " + falsePositive);
System.out.println("TN: " + trueNegative);
System.out.println("FN: " + falseNegative);
System.out.println("Precision: " + getPrecision());
System.out.println("Recall: " + getRecall());
System.out.println("F1 Score: " + getF1Score());
} else {
printConfusionMatrix();
}
}
public void printConfusionMatrix() {
printConfusionMatrix(null);
}
public void printConfusionMatrix(String[] classNames) {
Preconditions.checkNotNull(this.confusionMatrix,
"No confusion matrix found.");
System.out
.println("\nConfusion matrix (real outcome on rows, prediction in columns)\n");
for (int i = 0; i < getNumLabels(); i++) {
System.out.format("%5d", i);
}
System.out.format(" <- %5s %5s\t%s\n", "sum", "perc", "class");
for (int i = 0; i < getNumLabels(); i++) {
int sum = 0;
for (int j = 0; j < getNumLabels(); j++) {
if (i != j) {
sum += confusionMatrix[i][j];
}
System.out.format("%5d", confusionMatrix[i][j]);
}
float falsePercentage = sum / (float) (sum + confusionMatrix[i][i]);
String clz = classNames != null ? " " + i + " (" + classNames[i] + ")"
: " " + i;
System.out.format(" <- %5s %5s\t%s\n", sum, NumberFormat
.getPercentInstance().format(falsePercentage), clz);
}
}
}
/**
* Trains and evaluates the given classifier with a test split.
*
* @param classifier the classifier to train and evaluate.
* @param features the features to split.
* @param outcome the outcome to split.
* @param numLabels the number of labels that are used. (e.G. 2 in binary
* classification).
* @param splitFraction a value between 0f and 1f that sets the size of the
* trainingset. With 1k items, a splitFraction of 0.9f will result in
* 900 items to train and 100 to evaluate.
* @param random true if you want to perform shuffling on the data beforehand.
* @return a new {@link EvaluationResult}.
*/
public static EvaluationResult evaluateClassifier(Classifier classifier,
DoubleVector[] features, DoubleVector[] outcome, int numLabels,
float splitFraction, boolean random) {
return evaluateClassifier(classifier, features, outcome, numLabels,
splitFraction, random, null);
}
/**
* Trains and evaluates the given classifier with a test split.
*
* @param classifier the classifier to train and evaluate.
* @param features the features to split.
* @param outcome the outcome to split.
* @param numLabels the number of labels that are used. (e.G. 2 in binary
* classification).
* @param splitFraction a value between 0f and 1f that sets the size of the
* trainingset. With 1k items, a splitFraction of 0.9f will result in
* 900 items to train and 100 to evaluate.
* @param random true if you want to perform shuffling on the data beforehand.
* @param threshold in case of binary predictions, threshold is used to call
* in {@link Classifier#getPredictedClass(DoubleVector, double)}. Can
* be null, then no thresholding will be used.
* @return a new {@link EvaluationResult}.
*/
public static EvaluationResult evaluateClassifier(Classifier classifier,
DoubleVector[] features, DoubleVector[] outcome, int numLabels,
float splitFraction, boolean random, Double threshold) {
Preconditions.checkArgument(numLabels > 1,
"The number of labels should be greater than 1!");
EvaluationSplit split = EvaluationSplit.create(features, outcome,
splitFraction, random);
return evaluateSplit(classifier, numLabels, threshold, split);
}
/**
* Evaluates a given train/test split with the given classifier.
*
* @param classifier the classifier to train on the train split.
* @param numLabels the number of labels that can be classified.
* @param threshold the threshold for predicting a specific class by
* probability (if not provided = null).
* @param split the {@link EvaluationSplit} that contains the test and train
* data.
* @return a fresh evalation result filled with the evaluated metrics.
*/
public static EvaluationResult evaluateSplit(Classifier classifier,
int numLabels, Double threshold, EvaluationSplit split) {
return evaluateSplit(classifier, numLabels, threshold,
split.getTrainFeatures(), split.getTrainOutcome(),
split.getTestFeatures(), split.getTestOutcome());
}
/**
* Evaluates a given train/test split with the given classifier.
*
* @param classifier the classifier to train on the train split.
* @param numLabels the number of labels that can be classified.
* @param threshold the threshold for predicting a specific class by
* probability (if not provided = null).
* @param trainFeatures the features to train with.
* @param trainOutcome the outcomes to train with.
* @param testFeatures the features to test with.
* @param testOutcome the outcome to test with.
* @return a fresh evalation result filled with the evaluated metrics.
*/
public static EvaluationResult evaluateSplit(Classifier classifier,
int numLabels, Double threshold, DoubleVector[] trainFeatures,
DoubleVector[] trainOutcome, DoubleVector[] testFeatures,
DoubleVector[] testOutcome) {
classifier.train(trainFeatures, trainOutcome);
return testClassifier(classifier, numLabels, threshold,
trainOutcome.length, testFeatures, testOutcome);
}
/**
* Tests the given classifier without actually training it.
*
* @param classifier the classifier to evaluate on the test split.
* @param numLabels the number of labels that can be classified.
* @param threshold the threshold for predicting a specific class by
* probability (if not provided = null).
* @param trainingSetSize the size of the training set (just for reference).
* @param testFeatures the features to test with.
* @param testOutcome the outcome to test with.
* @return a fresh evalation result filled with the evaluated metrics.
*/
public static EvaluationResult testClassifier(Classifier classifier,
int numLabels, Double threshold, int trainingSetSize,
DoubleVector[] testFeatures, DoubleVector[] testOutcome) {
EvaluationResult result = new EvaluationResult();
result.numLabels = numLabels;
result.testSize = testOutcome.length;
result.trainSize = trainingSetSize;
// check the binary case to calculate special metrics
if (numLabels == 2) {
for (int i = 0; i < testFeatures.length; i++) {
int outcomeClass = ((int) testOutcome[i].get(0));
DoubleVector predictedVector = classifier.predict(testFeatures[i]);
int prediction = 0;
if (threshold == null) {
prediction = classifier.predictClassInternal(predictedVector);
} else {
prediction = classifier.predictClassInternal(predictedVector,
threshold);
}
if (outcomeClass == 1) {
if (prediction == 1) {
result.truePositive++; // "Correct result"
} else {
result.falseNegative++; // "Missing the correct result"
}
} else if (outcomeClass == 0) {
if (prediction == 0) {
result.trueNegative++; // "Correct absence of result"
} else {
result.falsePositive++; // "Unexpected result"
}
}
}
} else {
int[][] confusionMatrix = new int[numLabels][numLabels];
for (int i = 0; i < testFeatures.length; i++) {
int outcomeClass = testOutcome[i].maxIndex();
int prediction = classifier.getPredictedClass(testFeatures[i]);
confusionMatrix[outcomeClass][prediction]++;
if (outcomeClass == prediction) {
result.correct++;
}
}
result.confusionMatrix = confusionMatrix;
}
return result;
}
/**
* Does a k-fold crossvalidation on the given classifiers with features and
* outcomes. The folds will be calculated on a new thread.
*
* @param classifierFactory the classifiers to train and test.
* @param features the features to train/test with.
* @param outcome the outcomes to train/test with.
* @param numLabels the total number of labels that are possible. e.G. 2 in
* the binary case.
* @param folds the number of folds to fold, usually 10.
* @param threshold the threshold for predicting a specific class by
* probability (if not provided = null).
* @param verbose true if partial fold results should be printed.
* @return a averaged evaluation result over all k folds.
*/
public static <A extends Classifier> EvaluationResult crossValidateClassifier(
ClassifierFactory<A> classifierFactory, DoubleVector[] features,
DoubleVector[] outcome, int numLabels, int folds, Double threshold,
boolean verbose) {
return crossValidateClassifier(classifierFactory, features, outcome,
numLabels, folds, threshold, 1, verbose);
}
/**
* Does a k-fold crossvalidation on the given classifiers with features and
* outcomes.
*
* @param classifierFactory the classifiers to train and test.
* @param features the features to train/test with.
* @param outcome the outcomes to train/test with.
* @param numLabels the total number of labels that are possible. e.G. 2 in
* the binary case.
* @param folds the number of folds to fold, usually 10.
* @param threshold the threshold for predicting a specific class by
* probability (if not provided = null).
* @param numThreads how many threads to use to evaluate the folds.
* @param verbose true if partial fold results should be printed.
* @return a averaged evaluation result over all k folds.
*/
public static <A extends Classifier> EvaluationResult crossValidateClassifier(
ClassifierFactory<A> classifierFactory, DoubleVector[] features,
DoubleVector[] outcome, int numLabels, int folds, Double threshold,
int numThreads, boolean verbose) {
// train on k-1 folds, test on 1 fold, results are averaged
final int numFolds = folds + 1;
// multi shuffle the arrays first, note that this is not stratified.
ArrayUtils.multiShuffle(features, outcome);
EvaluationResult averagedModel = new EvaluationResult();
final int m = features.length;
// compute the split ranges by blocks, so we have range from 0 to the next
// partition index end that will be our testset, and so on.
List<Range> partition = new ArrayList<>(new BlockPartitioner().partition(
numFolds, m).getBoundaries());
int[] splitRanges = new int[numFolds];
for (int i = 1; i < numFolds; i++) {
splitRanges[i] = partition.get(i).getEnd();
}
// because we are dealing with indices, we have to subtract 1 from the end
splitRanges[numFolds - 1] = splitRanges[numFolds - 1] - 1;
if (verbose) {
System.out.println("Computed split ranges: "
+ Arrays.toString(splitRanges) + "\n");
}
final ExecutorService pool = Executors.newFixedThreadPool(numThreads,
new ThreadFactoryBuilder().setDaemon(true).build());
final ExecutorCompletionService<EvaluationResult> completionService = new ExecutorCompletionService<>(
pool);
// build the models fold for fold
for (int fold = 0; fold < folds; fold++) {
completionService.submit(new CallableEvaluation<>(fold, splitRanges, m,
classifierFactory, features, outcome, numLabels, folds, threshold));
}
// retrieve the results
for (int fold = 0; fold < folds; fold++) {
Future<EvaluationResult> take;
try {
take = completionService.take();
EvaluationResult foldSplit = take.get();
if (verbose) {
System.out.println("Fold: " + (fold + 1));
foldSplit.print();
System.out.println();
}
averagedModel.add(foldSplit);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
// average the sums in the model
averagedModel.average(folds);
return averagedModel;
}
/**
* Does a 10 fold crossvalidation.
*
* @param classifierFactory the classifiers to train and test.
* @param features the features to train/test with.
* @param outcome the outcomes to train/test with.
* @param numLabels the total number of labels that are possible. e.G. 2 in
* the binary case.
* @param threshold the threshold for predicting a specific class by
* probability (if not provided = null).
* @param numThreads how many threads to use to evaluate the folds.
* @param verbose true if partial fold results should be printed.
* @return a averaged evaluation result over all 10 folds.
*/
public static <A extends Classifier> EvaluationResult tenFoldCrossValidation(
ClassifierFactory<A> classifierFactory, DoubleVector[] features,
DoubleVector[] outcome, int numLabels, Double threshold, boolean verbose) {
return crossValidateClassifier(classifierFactory, features, outcome,
numLabels, 10, threshold, verbose);
}
/**
* Does a 10 fold crossvalidation.
*
* @param classifierFactory the classifiers to train and test.
* @param features the features to train/test with.
* @param outcome the outcomes to train/test with.
* @param numLabels the total number of labels that are possible. e.G. 2 in
* the binary case.
* @param threshold the threshold for predicting a specific class by
* probability (if not provided = null).
* @param verbose true if partial fold results should be printed.
* @return a averaged evaluation result over all 10 folds.
*/
public static <A extends Classifier> EvaluationResult tenFoldCrossValidation(
ClassifierFactory<A> classifierFactory, DoubleVector[] features,
DoubleVector[] outcome, int numLabels, Double threshold, int numThreads,
boolean verbose) {
return crossValidateClassifier(classifierFactory, features, outcome,
numLabels, 10, threshold, numThreads, verbose);
}
private static class CallableEvaluation<A extends Classifier> implements
Callable<EvaluationResult> {
private final int fold;
private final int[] splitRanges;
private final int m;
private final DoubleVector[] features;
private final DoubleVector[] outcome;
private final ClassifierFactory<A> classifierFactory;
private final int numLabels;
private final Double threshold;
public CallableEvaluation(int fold, int[] splitRanges, int m,
ClassifierFactory<A> classifierFactory, DoubleVector[] features,
DoubleVector[] outcome, int numLabels, int folds, Double threshold) {
this.fold = fold;
this.splitRanges = splitRanges;
this.m = m;
this.classifierFactory = classifierFactory;
this.features = features;
this.outcome = outcome;
this.numLabels = numLabels;
this.threshold = threshold;
}
@Override
public EvaluationResult call() throws Exception {
DoubleVector[] featureTest = ArrayUtils.subArray(features,
splitRanges[fold], splitRanges[fold + 1]);
DoubleVector[] outcomeTest = ArrayUtils.subArray(outcome,
splitRanges[fold], splitRanges[fold + 1]);
DoubleVector[] featureTrain = new DoubleVector[m - featureTest.length];
DoubleVector[] outcomeTrain = new DoubleVector[m - featureTest.length];
int index = 0;
for (int i = 0; i < m; i++) {
if (i < splitRanges[fold] || i > splitRanges[fold + 1]) {
featureTrain[index] = features[i];
outcomeTrain[index] = outcome[i];
index++;
}
}
return evaluateSplit(classifierFactory.newInstance(), numLabels,
threshold, featureTrain, outcomeTrain, featureTest, outcomeTest);
}
}
}
|
package de.littlerolf.sav;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLConnection;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import de.littlerolf.sav.gui.ProgressFrame;
import de.littlerolf.sav.gui.SAVFrame;
public class SortAlgorithmVisualizer {
private static final String SERVER = "github.io";
private static final String SERVER_URL = "http://littlerolf.github.io/SortAlgorithmVisualizer/";
private static final File DOWNLOADED_FILE = new File(
System.getProperty("user.home") + File.separator + ".sav"
+ File.separator + "SAV.jar");
public static void main(String[] args) throws UnknownHostException,
IOException {
int localVersion = getLocalVersion();
if (localVersion == -1
|| !InetAddress.getByName(SERVER).isReachable(5000)
|| (args.length > 1 && args[1].equals("ultraulf"))) {
System.out.println("Starting local version.");
startLocal();
return;
}
int remoteVersion = getRemoteVersion();
int downloadedVersion = getDownloadedJarVersion();
if (remoteVersion > downloadedVersion) {
System.out.println("Starting remote version.");
downloadAndStartRemoteJar();
} else {
System.out.println("Starting cached version.");
startJar(DOWNLOADED_FILE.getAbsolutePath());
}
}
private static void downloadAndStartRemoteJar() {
final ProgressFrame frame = new ProgressFrame();
frame.setVisible(true);
new Thread(new Runnable() {
@Override
public void run() {
downloadRemoteJar(new DownloadListener() {
@Override
public void onDownloadProgress(int value, int max) {
frame.setMaximum(100);
frame.setMinimum(0);
frame.setValue(value);
}
@Override
public void onDownloadFinished(File f) {
frame.setVisible(false);
startJar(f.getAbsolutePath());
}
});
}
}).start();
}
private static int getLocalVersion() {
URLClassLoader cl = (URLClassLoader) SortAlgorithmVisualizer.class
.getClassLoader();
try {
URL url = cl.findResource("META-INF/MANIFEST.MF");
Manifest manifest = new Manifest(url.openStream());
int version = Integer.valueOf(manifest.getMainAttributes()
.getValue("Build-Number"));
System.out.println("Local version is " + version + ".");
return version;
} catch (IOException e) {
e.printStackTrace();
} catch (NullPointerException e) {
} catch (NumberFormatException e) {
e.printStackTrace();
}
return -1;
}
private static int getDownloadedJarVersion() {
if (!DOWNLOADED_FILE.exists())
return -1;
try {
JarFile f = new JarFile(DOWNLOADED_FILE);
int version = Integer.valueOf(f.getManifest().getMainAttributes()
.getValue("Build-Number"));
f.close();
System.out.println("Downloaded version is " + version + ".");
return version;
} catch (IOException e) {
e.printStackTrace();
} catch (NullPointerException e) {
}
return -1;
}
private static int getRemoteVersion() {
URL url = null;
try {
url = new URL(SERVER_URL + "version.txt");
} catch (MalformedURLException e2) {
e2.printStackTrace();
}
try {
URLConnection urlConnection = url.openConnection();
urlConnection.setAllowUserInteraction(false);
InputStream urlStream = url.openStream();
byte buffer[] = new byte[1000];
int numRead = urlStream.read(buffer);
String content = new String(buffer, 0, numRead);
while ((numRead != -1) && (content.length() < 1024)) {
numRead = urlStream.read(buffer);
if (numRead != -1) {
String newContent = new String(buffer, 0, numRead);
content += newContent;
}
}
content = content.trim();
System.out.println("Remote version is " + content + ".");
return Integer.valueOf(content);
} catch (IOException e) {
e.printStackTrace();
} catch (IndexOutOfBoundsException e1) {
e1.printStackTrace();
}
return -1;
}
interface DownloadListener {
public void onDownloadProgress(int value, int max);
public void onDownloadFinished(File f);
}
private static File downloadRemoteJar(DownloadListener l) {
System.out.println("Downloading remote jar.");
File f = DOWNLOADED_FILE;
f.getParentFile().mkdirs();
URL website;
try {
website = new URL(SERVER_URL + "jar/SAV.jar");
ReadableByteChannel rbc = new RBCWrapper(
Channels.newChannel(website.openStream()),
getContentLength(website), l);
FileOutputStream fos = new FileOutputStream(f);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
l.onDownloadFinished(f);
return f;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private static int getContentLength(URL url) {
HttpURLConnection connection;
int contentLength = -1;
try {
HttpURLConnection.setFollowRedirects(false);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("HEAD");
contentLength = connection.getContentLength();
} catch (Exception e) {
}
return contentLength;
}
private static void startJar(String path) {
System.out.println("Starting jar " + path + ".");
ProcessBuilder pb = new ProcessBuilder("java", "-classpath", path,
SortAlgorithmVisualizer.class.getName(), "ultraulf");
try {
Process p = pb.start();
new StreamGobbler(p.getErrorStream()).start();
new StreamGobbler(p.getInputStream()).start();
p.waitFor();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static void startLocal() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (UnsupportedLookAndFeelException e) {
} catch (ClassNotFoundException e) {
} catch (InstantiationException e) {
} catch (IllegalAccessException e) {
}
new SAVFrame().setVisible(true);
}
private static class StreamGobbler extends Thread {
InputStream is;
// reads everything from is until empty.
StreamGobbler(InputStream is) {
this.is = is;
}
public void run() {
try {
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line = null;
while ((line = br.readLine()) != null)
System.out.println(line);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
private static final class RBCWrapper implements ReadableByteChannel {
private DownloadListener delegate;
private long expectedSize;
private ReadableByteChannel rbc;
private long readSoFar;
RBCWrapper(ReadableByteChannel rbc, long expectedSize,
DownloadListener delegate) {
this.delegate = delegate;
this.expectedSize = expectedSize;
this.rbc = rbc;
}
public void close() throws IOException {
rbc.close();
}
public boolean isOpen() {
return rbc.isOpen();
}
public int read(ByteBuffer bb) throws IOException {
int n;
double progress;
if ((n = rbc.read(bb)) > 0) {
readSoFar += n;
progress = expectedSize > 0 ? (double) readSoFar
/ (double) expectedSize * 100.0 : -1.0;
delegate.onDownloadProgress((int) progress, (int) expectedSize);
}
return n;
}
}
}
|
package de.podfetcher.adapter;
import java.text.DateFormat;
import java.util.List;
import de.podfetcher.feed.FeedItem;
import de.podfetcher.util.Converter;
import de.podfetcher.R;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.content.Context;
import android.graphics.Typeface;
public class FeedItemlistAdapter extends ArrayAdapter<FeedItem> {
private OnClickListener onButActionClicked;
public FeedItemlistAdapter(Context context, int textViewResourceId,
List<FeedItem> objects, OnClickListener onButActionClicked) {
super(context, textViewResourceId, objects);
this.onButActionClicked = onButActionClicked;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Holder holder;
FeedItem item = getItem(position);
if (convertView == null) {
holder = new Holder();
LayoutInflater inflater = (LayoutInflater) getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.feeditemlist_item, null);
holder.title = (TextView) convertView
.findViewById(R.id.txtvItemname);
holder.lenSize = (TextView) convertView
.findViewById(R.id.txtvLenSize);
holder.butAction = (ImageButton) convertView
.findViewById(R.id.butAction);
holder.published = (TextView) convertView
.findViewById(R.id.txtvPublished);
holder.downloaded = (ImageView) convertView
.findViewById(R.id.imgvDownloaded);
holder.type = (ImageView) convertView.findViewById(R.id.imgvType);
holder.downloading = (ImageView) convertView
.findViewById(R.id.imgvDownloading);
holder.encInfo = (RelativeLayout) convertView
.findViewById(R.id.enc_info);
convertView.setTag(holder);
} else {
holder = (Holder) convertView.getTag();
}
holder.title.setText(item.getTitle());
if (!item.isRead()) {
holder.title.setTypeface(Typeface.DEFAULT_BOLD);
} else {
holder.title.setTypeface(Typeface.DEFAULT);
}
holder.published.setText("Published: "
+ DateUtils.formatSameDayTime(item.getPubDate().getTime(),
System.currentTimeMillis(), DateFormat.SHORT,
DateFormat.SHORT));
if (item.getMedia() == null) {
holder.encInfo.setVisibility(View.GONE);
} else {
holder.encInfo.setVisibility(View.VISIBLE);
if (item.getMedia().isDownloaded()) {
holder.lenSize.setText(Converter.getDurationStringShort(item
.getMedia().getDuration()));
holder.downloaded.setVisibility(View.VISIBLE);
} else {
holder.lenSize.setText(Converter.byteToString(item.getMedia()
.getSize()));
holder.downloaded.setVisibility(View.GONE);
}
if (item.getMedia().isDownloading()) {
holder.downloading.setVisibility(View.VISIBLE);
} else {
holder.downloading.setVisibility(View.GONE);
}
String type = item.getMedia().getMime_type();
if (type.startsWith("audio")) {
holder.type.setImageResource(R.drawable.type_audio);
} else if (type.startsWith("video")) {
holder.type.setImageResource(R.drawable.type_video);
} else {
holder.type.setImageBitmap(null);
}
}
holder.butAction.setFocusable(false);
holder.butAction.setOnClickListener(onButActionClicked);
return convertView;
}
static class Holder {
TextView title;
TextView published;
TextView lenSize;
ImageView downloaded;
ImageView type;
ImageView downloading;
ImageButton butAction;
RelativeLayout encInfo;
}
}
|
package de.unitrier.st.soposthistory;
import de.unitrier.st.soposthistory.comments.CommentsIterator;
import de.unitrier.st.soposthistory.history.PostHistoryIterator;
import org.apache.commons.cli.*;
import java.nio.file.Path;
import java.nio.file.Paths;
class MainIterator {
// TODO : Also store n-grams of code blocks in database? -> would result in a very large database
// TODO: Evolution of question title (PostHistoryTypeId 1)?
public static void main (String[] args) {
System.out.println("SOPostHistory (Iterator Mode)");
Options options = new Options();
Option dataDirOption = new Option("d", "data-dir", true,
"path to data directory (used to store post id lists");
dataDirOption.setRequired(true);
options.addOption(dataDirOption);
Option hibernateConfigFileOption = new Option("h", "hibernate-config", true,
"path to hibernate config file");
hibernateConfigFileOption.setRequired(true);
options.addOption(hibernateConfigFileOption);
Option partitionCountOption = new Option("p", "partition-count", true,
"number of partitions created from post id lists (one worker thread per partition, default value: 4)");
partitionCountOption.setRequired(false);
options.addOption(partitionCountOption);
Option tagsOption = new Option("t", "tags", true,
"tags for filtering questions and answers (separated by a space)");
tagsOption.setRequired(false);
options.addOption(tagsOption);
CommandLineParser commandLineParser = new DefaultParser();
HelpFormatter commandLineFormatter = new HelpFormatter();
CommandLine commandLine;
try {
commandLine = commandLineParser.parse(options, args);
} catch (ParseException e) {
System.out.println(e.getMessage());
commandLineFormatter.printHelp("SOPostHistory (Iterator Mode)", options);
System.exit(1);
return;
}
Path dataDirPath = Paths.get(commandLine.getOptionValue("data-dir"));
Path hibernateConfigFilePath = Paths.get(commandLine.getOptionValue("hibernate-config"));
String[] tags = {}; // no tags provided -> all posts
int partitionCount = 4;
if (commandLine.hasOption("tags")) {
tags = commandLine.getOptionValue("tags").split(" ");
}
if (commandLine.hasOption("partition-count")) {
partitionCount = Integer.parseInt(commandLine.getOptionValue("partition-count"));
}
// process version history
PostHistoryIterator.createSessionFactory(hibernateConfigFilePath);
PostHistoryIterator postHistoryIterator = new PostHistoryIterator(
dataDirPath, "all", partitionCount, tags
);
postHistoryIterator.extractSaveAndSplitPostIds(); // including split
postHistoryIterator.extractDataFromPostHistory("questions");
postHistoryIterator.extractDataFromPostHistory("answers");
PostHistoryIterator.sessionFactory.close();
// extract URLs from comments
CommentsIterator.createSessionFactory(hibernateConfigFilePath);
CommentsIterator commentsIterator = new CommentsIterator(partitionCount);
commentsIterator.extractUrlsFromComments();
CommentsIterator.sessionFactory.close();
}
}
|
package dr.evomodel.antigenic;
import dr.evolution.util.*;
import dr.inference.model.*;
import dr.math.MathUtils;
import dr.math.distributions.NormalDistribution;
import dr.util.*;
import dr.xml.*;
import java.io.*;
import java.util.*;
import java.util.logging.Logger;
/**
* @author Andrew Rambaut
* @author Trevor Bedford
* @author Marc Suchard
* @version $Id$
*/
public class AntigenicLikelihood extends AbstractModelLikelihood implements Citable {
private static final boolean CHECK_INFINITE = false;
private static final boolean USE_THRESHOLDS = true;
private static final boolean USE_INTERVALS = true;
public final static String ANTIGENIC_LIKELIHOOD = "antigenicLikelihood";
// column indices in table
private static final int COLUMN_LABEL = 0;
private static final int SERUM_STRAIN = 2;
private static final int ROW_LABEL = 1;
private static final int VIRUS_STRAIN = 3;
private static final int SERUM_DATE = 4;
private static final int VIRUS_DATE = 5;
private static final int TITRE = 6;
public enum MeasurementType {
INTERVAL,
POINT,
THRESHOLD,
MISSING
}
public AntigenicLikelihood(
int mdsDimension,
Parameter mdsPrecisionParameter,
TaxonList strainTaxa,
MatrixParameter locationsParameter,
CompoundParameter tipTraitsParameter,
Parameter datesParameter,
Parameter columnParameter,
Parameter rowParameter,
DataTable<String[]> dataTable,
double intervalWidth,
List<String> virusLocationStatisticList) {
super(ANTIGENIC_LIKELIHOOD);
List<String> strainNames = new ArrayList<String>();
Map<String, Double> strainDateMap = new HashMap<String, Double>();
this.intervalWidth = intervalWidth;
boolean useIntervals = USE_INTERVALS && intervalWidth > 0.0;
int thresholdCount = 0;
for (int i = 0; i < dataTable.getRowCount(); i++) {
String[] values = dataTable.getRow(i);
int column = columnLabels.indexOf(values[COLUMN_LABEL]);
if (column == -1) {
columnLabels.add(values[0]);
column = columnLabels.size() - 1;
}
int columnStrain = -1;
if (strainTaxa != null) {
columnStrain = strainTaxa.getTaxonIndex(values[SERUM_STRAIN]);
} else {
columnStrain = strainNames.indexOf(values[SERUM_STRAIN]);
if (columnStrain == -1) {
strainNames.add(values[SERUM_STRAIN]);
Double date = Double.parseDouble(values[SERUM_DATE]);
strainDateMap.put(values[SERUM_STRAIN], date);
columnStrain = strainNames.size() - 1;
}
}
if (columnStrain == -1) {
throw new IllegalArgumentException("Error reading data table: Unrecognized serum strain name, " + values[SERUM_STRAIN] + ", in row " + (i+1));
}
int row = rowLabels.indexOf(values[ROW_LABEL]);
if (row == -1) {
rowLabels.add(values[ROW_LABEL]);
row = rowLabels.size() - 1;
}
int rowStrain = -1;
if (strainTaxa != null) {
rowStrain = strainTaxa.getTaxonIndex(values[VIRUS_STRAIN]);
} else {
rowStrain = strainNames.indexOf(values[VIRUS_STRAIN]);
if (rowStrain == -1) {
strainNames.add(values[VIRUS_STRAIN]);
Double date = Double.parseDouble(values[VIRUS_DATE]);
strainDateMap.put(values[VIRUS_STRAIN], date);
rowStrain = strainNames.size() - 1;
}
}
if (rowStrain == -1) {
throw new IllegalArgumentException("Error reading data table: Unrecognized virus strain name, " + values[VIRUS_STRAIN] + ", in row " + (i+1));
}
boolean isThreshold = false;
double rawTitre = Double.NaN;
if (values[TITRE].length() > 0) {
try {
rawTitre = Double.parseDouble(values[TITRE]);
} catch (NumberFormatException nfe) {
// check if threshold below
if (values[TITRE].contains("<")) {
rawTitre = Double.parseDouble(values[TITRE].replace("<",""));
isThreshold = true;
thresholdCount++;
}
// check if threshold above
if (values[TITRE].contains(">")) {
throw new IllegalArgumentException("Error in measurement: unsupported greater than threshold at row " + (i+1));
}
}
}
MeasurementType type = (isThreshold ? MeasurementType.THRESHOLD : (useIntervals ? MeasurementType.INTERVAL : MeasurementType.POINT));
Measurement measurement = new Measurement(column, columnStrain, row, rowStrain, type, rawTitre);
if (USE_THRESHOLDS || !isThreshold) {
measurements.add(measurement);
}
}
double[] maxColumnTitre = new double[columnLabels.size()];
double[] maxRowTitre = new double[rowLabels.size()];
for (Measurement measurement : measurements) {
double titre = measurement.log2Titre;
if (Double.isNaN(titre)) {
titre = measurement.log2Titre;
}
if (titre > maxColumnTitre[measurement.column]) {
maxColumnTitre[measurement.column] = titre;
}
if (titre > maxRowTitre[measurement.row]) {
maxRowTitre[measurement.row] = titre;
}
}
if (strainTaxa != null) {
this.strains = strainTaxa;
// fill in the strain name array for local use
for (int i = 0; i < strains.getTaxonCount(); i++) {
strainNames.add(strains.getTaxon(i).getId());
}
} else {
Taxa taxa = new Taxa();
for (String strain : strainNames) {
taxa.addTaxon(new Taxon(strain));
}
this.strains = taxa;
}
this.mdsDimension = mdsDimension;
this.mdsPrecisionParameter = mdsPrecisionParameter;
addVariable(mdsPrecisionParameter);
this.locationsParameter = locationsParameter;
setupLocationsParameter(this.locationsParameter, strainNames);
this.tipTraitsParameter = tipTraitsParameter;
if (tipTraitsParameter != null) {
setupTipTraitsParameter(this.tipTraitsParameter, strainNames);
}
if (datesParameter != null) {
// this parameter is not used in this class but is setup to be used in other classes
setupDatesParameter(datesParameter, strainNames, strainDateMap);
}
this.columnEffectsParameter = setupColumnEffectsParameter(columnParameter, maxColumnTitre);
this.rowEffectsParameter = setupRowEffectsParameter(rowParameter, maxRowTitre);
StringBuilder sb = new StringBuilder();
sb.append("\tAntigenicLikelihood:\n");
sb.append("\t\t" + this.strains.getTaxonCount() + " strains\n");
sb.append("\t\t" + columnLabels.size() + " unique columns\n");
sb.append("\t\t" + rowLabels.size() + " unique rows\n");
sb.append("\t\t" + measurements.size() + " assay measurements\n");
if (USE_THRESHOLDS) {
sb.append("\t\t" + thresholdCount + " thresholded measurements\n");
}
if (useIntervals) {
sb.append("\n\t\tAssuming a log 2 measurement interval width of " + intervalWidth + "\n");
}
Logger.getLogger("dr.evomodel").info(sb.toString());
locationChanged = new boolean[this.locationsParameter.getParameterCount()];
logLikelihoods = new double[measurements.size()];
storedLogLikelihoods = new double[measurements.size()];
setupInitialLocations(strainNames, strainDateMap);
makeDirty();
}
private Parameter setupRowEffectsParameter(Parameter rowParameter, double[] maxRowTitre) {
// If no row parameter is given, then we will only use the column effects
if (rowParameter != null) {
rowParameter.addBounds(new Parameter.DefaultBounds(Double.MAX_VALUE, 0.0, 1));
rowParameter.setDimension(rowLabels.size());
addVariable(rowParameter);
String[] labelArray = new String[rowLabels.size()];
rowLabels.toArray(labelArray);
rowParameter.setDimensionNames(labelArray);
for (int i = 0; i < maxRowTitre.length; i++) {
rowParameter.setParameterValueQuietly(i, maxRowTitre[i]);
}
}
return rowParameter;
}
private Parameter setupColumnEffectsParameter(Parameter columnParameter, double[] maxColumnTitre) {
// If no column parameter is given, make one to hold maximum values for scaling titres...
if (columnParameter == null) {
columnParameter = new Parameter.Default("columnEffects");
} else {
columnParameter.addBounds(new Parameter.DefaultBounds(Double.MAX_VALUE, 0.0, 1));
addVariable(columnParameter);
}
columnParameter.setDimension(columnLabels.size());
String[] labelArray = new String[columnLabels.size()];
columnLabels.toArray(labelArray);
columnParameter.setDimensionNames(labelArray);
for (int i = 0; i < maxColumnTitre.length; i++) {
columnParameter.setParameterValueQuietly(i, maxColumnTitre[i]);
}
return columnParameter;
}
protected void setupLocationsParameter(MatrixParameter locationsParameter, List<String> strains) {
locationsParameter.setColumnDimension(mdsDimension);
locationsParameter.setRowDimension(strains.size());
for (int i = 0; i < strains.size(); i++) {
locationsParameter.getParameter(i).setId(strains.get(i));
}
addVariable(this.locationsParameter);
}
private void setupDatesParameter(Parameter datesParameter, List<String> strainNames, Map<String, Double> strainDateMap) {
datesParameter.setDimension(strainNames.size());
String[] labelArray = new String[strainNames.size()];
strainNames.toArray(labelArray);
datesParameter.setDimensionNames(labelArray);
for (int i = 0; i < strainNames.size(); i++) {
Double date = strainDateMap.get(strainNames.get(i));
if (date == null) {
throw new IllegalArgumentException("Date missing for strain: " + strainNames.get(i));
}
datesParameter.setParameterValue(i, date);
}
}
private void setupTipTraitsParameter(CompoundParameter tipTraitsParameter, List<String> strainNames) {
tipIndices = new int[strainNames.size()];
for (int i = 0; i < strainNames.size(); i++) {
tipIndices[i] = -1;
}
for (int i = 0; i < tipTraitsParameter.getParameterCount(); i++) {
Parameter tip = tipTraitsParameter.getParameter(i);
String label = tip.getParameterName();
int index = findStrain(label, strainNames);
if (index != -1) {
if (tipIndices[index] != -1) {
throw new IllegalArgumentException("Duplicated tip name: " + label);
}
tipIndices[index] = i;
// rather than setting these here, we set them when the locations are set so the changes propagate
// through to the diffusion model.
// Parameter location = locationsParameter.getParameter(index);
// for (int dim = 0; dim < mdsDimension; dim++) {
// tip.setParameterValue(dim, location.getParameterValue(dim));
} else {
throw new IllegalArgumentException("Unmatched tip name in assay data: " + label);
}
}
// we are only setting this parameter not listening to it:
// addVariable(this.tipTraitsParameter);
}
private final int findStrain(String label, List<String> strainNames) {
int index = 0;
for (String strainName : strainNames) {
if (label.startsWith(strainName)) {
return index;
}
index ++;
}
return -1;
}
private void setupInitialLocations(List<String> strainNames, Map<String,Double> strainDateMap) {
double earliestDate = Double.POSITIVE_INFINITY;
for (double date : strainDateMap.values()) {
if (earliestDate > date) {
earliestDate = date;
}
}
for (int i = 0; i < locationsParameter.getParameterCount(); i++) {
double date = (double) strainDateMap.get(strainNames.get(i));
double diff = (date-earliestDate);
locationsParameter.getParameter(i).setParameterValue(0, diff + MathUtils.nextGaussian());
for (int j = 1; j < mdsDimension; j++) {
double r = MathUtils.nextGaussian();
locationsParameter.getParameter(i).setParameterValue(j, r);
}
}
}
@Override
protected void handleModelChangedEvent(Model model, Object object, int index) {
}
@Override
protected void handleVariableChangedEvent(Variable variable, int index, Variable.ChangeType type) {
if (variable == locationsParameter) {
int loc = index / mdsDimension;
locationChanged[loc] = true;
if (tipTraitsParameter != null && tipIndices[loc] != -1) {
Parameter location = locationsParameter.getParameter(loc);
Parameter tip = tipTraitsParameter.getParameter(tipIndices[loc]);
int dim = index % mdsDimension;
tip.setParameterValue(dim, location.getParameterValue(dim));
}
} else if (variable == mdsPrecisionParameter) {
setLocationChangedFlags(true);
} else if (variable == columnEffectsParameter) {
setLocationChangedFlags(true);
} else if (variable == rowEffectsParameter) {
setLocationChangedFlags(true);
} else {
// could be a derived class's parameter
}
likelihoodKnown = false;
}
@Override
protected void storeState() {
System.arraycopy(logLikelihoods, 0, storedLogLikelihoods, 0, logLikelihoods.length);
}
@Override
protected void restoreState() {
double[] tmp = logLikelihoods;
logLikelihoods = storedLogLikelihoods;
storedLogLikelihoods = tmp;
likelihoodKnown = false;
}
@Override
protected void acceptState() {
}
public Model getModel() {
return this;
}
public double getLogLikelihood() {
if (!likelihoodKnown) {
logLikelihood = computeLogLikelihood();
}
return logLikelihood;
}
// This function can be overwritten to implement other sampling densities, i.e. discrete ranks
private double computeLogLikelihood() {
double precision = mdsPrecisionParameter.getParameterValue(0);
double sd = 1.0 / Math.sqrt(precision);
logLikelihood = 0.0;
int i = 0;
for (Measurement measurement : measurements) {
if (locationChanged[measurement.rowStrain] || locationChanged[measurement.columnStrain]) {
double mapDistance = computeDistance(measurement.rowStrain, measurement.columnStrain);
double logNormalization = calculateTruncationNormalization(mapDistance, sd);
logLikelihoods[i] = computeMeasurementLikelihood(measurement.titre, mapDistance, sd) - logNormalization;
// switch (measurement.type) {
// case INTERVAL: {
// // once transformed the lower titre becomes the higher distance
// double minHiDistance = transformTitre(measurement.log2Titre + 1.0, measurement.column, measurement.row);
// double maxHiDistance = transformTitre(measurement.log2Titre, measurement.column, measurement.row);
// logLikelihoods[i] = computeMeasurementIntervalLikelihood(minHiDistance, maxHiDistance, mapDistance, sd) - logNormalization;
// } break;
// case POINT: {
// double hiDistance = transformTitre(measurement.log2Titre, measurement.column, measurement.row);
// logLikelihoods[i] = computeMeasurementLikelihood(hiDistance, mapDistance, sd) - logNormalization;
// } break;
// case THRESHOLD: {
// double hiDistance = transformTitre(measurement.log2Titre, measurement.column, measurement.row);
// logLikelihoods[i] = computeMeasurementThresholdLikelihood(hiDistance, mapDistance, sd) - logNormalization;
// } break;
// case MISSING:
// break;
}
logLikelihood += logLikelihoods[i];
i++;
}
likelihoodKnown = true;
setLocationChangedFlags(false);
return logLikelihood;
}
private void setLocationChangedFlags(boolean flag) {
for (int i = 0; i < locationChanged.length; i++) {
locationChanged[i] = flag;
}
}
protected double computeDistance(int rowStrain, int columnStrain) {
if (rowStrain == columnStrain) {
return 0.0;
}
Parameter X = locationsParameter.getParameter(rowStrain);
Parameter Y = locationsParameter.getParameter(columnStrain);
double sum = 0.0;
for (int i = 0; i < mdsDimension; i++) {
double difference = X.getParameterValue(i) - Y.getParameterValue(i);
sum += difference * difference;
}
return Math.sqrt(sum);
}
/**
* Transforms a titre into log2 space and normalizes it with respect to a unit normal
* @param titre
* @param column
* @param row
* @return
*/
private double transformTitre(double titre, int column, int row) {
double t;
double columnEffect = columnEffectsParameter.getParameterValue(column);
if (rowEffectsParameter != null) {
double rowEffect = rowEffectsParameter.getParameterValue(row);
t = ((rowEffect + columnEffect) * 0.5) - titre;
} else {
t = columnEffect - titre;
}
return t;
}
private static double computeMeasurementIntervalLikelihood(double minDistance, double maxDistance, double mean, double sd) {
double cdf1 = NormalDistribution.cdf(minDistance, mean, sd, false);
double cdf2 = NormalDistribution.cdf(maxDistance, mean, sd, false);
double lnL = Math.log(cdf2 - cdf1);
if (cdf1 == cdf2) {
lnL = Math.log(cdf1);
}
if (CHECK_INFINITE && Double.isNaN(lnL) || Double.isInfinite(lnL)) {
throw new RuntimeException("infinite");
}
return lnL;
}
private static double computeMeasurementIntervalLikelihood_CDF(double minDistance, double maxDistance, double mean, double sd) {
double cdf1 = NormalDistribution.cdf(minDistance, mean, sd, false);
double cdf2 = NormalDistribution.cdf(maxDistance, mean, sd, false);
double lnL = Math.log(cdf1 - cdf2);
if (cdf1 == cdf2) {
lnL = Math.log(cdf1);
}
if (CHECK_INFINITE && Double.isNaN(lnL) || Double.isInfinite(lnL)) {
throw new RuntimeException("infinite");
}
return lnL;
}
private static double computeMeasurementLikelihood(double distance, double mean, double sd) {
double lnL = NormalDistribution.logPdf(distance, mean, sd);
if (CHECK_INFINITE && Double.isNaN(lnL) || Double.isInfinite(lnL)) {
throw new RuntimeException("infinite");
}
return lnL;
}
// private static double computeMeasurementLowerBoundLikelihood(double transformedMinTitre) {
// // a lower bound in non-transformed titre so the bottom tail of the distribution
// double cdf = NormalDistribution.standardTail(transformedMinTitre, false);
// double lnL = Math.log(cdf);
// if (CHECK_INFINITE && Double.isNaN(lnL) || Double.isInfinite(lnL)) {
// throw new RuntimeException("infinite");
// return lnL;
private static double computeMeasurementThresholdLikelihood(double distance, double mean, double sd) {
// a upper bound in non-transformed titre so the upper tail of the distribution
// using special tail function of NormalDistribution (see main() in NormalDistribution for test)
double tail = NormalDistribution.tailCDF(distance, mean, sd);
double lnL = Math.log(tail);
if (CHECK_INFINITE && Double.isNaN(lnL) || Double.isInfinite(lnL)) {
throw new RuntimeException("infinite");
}
return lnL;
}
private static double calculateTruncationNormalization(double distance, double sd) {
return NormalDistribution.cdf(distance, 0.0, sd, true);
}
public void makeDirty() {
likelihoodKnown = false;
setLocationChangedFlags(true);
}
private class Measurement {
private Measurement(final int column, final int columnStrain, final int row, final int rowStrain, final MeasurementType type, final double titre) {
this.column = column;
this.columnStrain = columnStrain;
this.row = row;
this.rowStrain = rowStrain;
this.type = type;
this.titre = titre;
this.log2Titre = Math.log(titre) / Math.log(2);
}
final int column;
final int row;
final int columnStrain;
final int rowStrain;
final MeasurementType type;
final double titre;
final double log2Titre;
};
private final List<Measurement> measurements = new ArrayList<Measurement>();
private final List<String> columnLabels = new ArrayList<String>();
private final List<String> rowLabels = new ArrayList<String>();
private final int mdsDimension;
private final double intervalWidth;
private final Parameter mdsPrecisionParameter;
private final MatrixParameter locationsParameter;
private final CompoundParameter tipTraitsParameter;
private final TaxonList strains;
private int[] tipIndices;
private final Parameter columnEffectsParameter;
private final Parameter rowEffectsParameter;
private double logLikelihood = 0.0;
private boolean likelihoodKnown = false;
private final boolean[] locationChanged;
private double[] logLikelihoods;
private double[] storedLogLikelihoods;
// XMLObjectParser
public static XMLObjectParser PARSER = new AbstractXMLObjectParser() {
public final static String FILE_NAME = "fileName";
public final static String TIP_TRAIT = "tipTrait";
public final static String LOCATIONS = "locations";
public final static String DATES = "dates";
public static final String MDS_DIMENSION = "mdsDimension";
public static final String INTERVAL_WIDTH = "intervalWidth";
public static final String MDS_PRECISION = "mdsPrecision";
public static final String COLUMN_EFFECTS = "columnEffects";
public static final String ROW_EFFECTS = "rowEffects";
public static final String STRAINS = "strains";
public String getParserName() {
return ANTIGENIC_LIKELIHOOD;
}
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
String fileName = xo.getStringAttribute(FILE_NAME);
DataTable<String[]> assayTable;
try {
assayTable = DataTable.Text.parse(new FileReader(fileName), true, false);
} catch (IOException e) {
throw new XMLParseException("Unable to read assay data from file: " + e.getMessage());
}
System.out.println("Loaded HI table file: " + fileName);
int mdsDimension = xo.getIntegerAttribute(MDS_DIMENSION);
double intervalWidth = 0.0;
if (xo.hasAttribute(INTERVAL_WIDTH)) {
intervalWidth = xo.getDoubleAttribute(INTERVAL_WIDTH);
}
CompoundParameter tipTraitParameter = null;
if (xo.hasChildNamed(TIP_TRAIT)) {
tipTraitParameter = (CompoundParameter) xo.getElementFirstChild(TIP_TRAIT);
}
TaxonList strains = null;
if (xo.hasChildNamed(STRAINS)) {
strains = (TaxonList) xo.getElementFirstChild(STRAINS);
}
MatrixParameter locationsParameter = (MatrixParameter) xo.getElementFirstChild(LOCATIONS);
Parameter datesParameter = null;
if (xo.hasChildNamed(DATES)) {
datesParameter = (Parameter) xo.getElementFirstChild(DATES);
}
Parameter mdsPrecision = (Parameter) xo.getElementFirstChild(MDS_PRECISION);
Parameter columnEffectsParameter = null;
if (xo.hasChildNamed(COLUMN_EFFECTS)) {
columnEffectsParameter = (Parameter) xo.getElementFirstChild(COLUMN_EFFECTS);
}
Parameter rowEffectsParameter = null;
if (xo.hasChildNamed(ROW_EFFECTS)) {
rowEffectsParameter = (Parameter) xo.getElementFirstChild(ROW_EFFECTS);
}
AntigenicLikelihood AGL = new AntigenicLikelihood(
mdsDimension,
mdsPrecision,
strains,
locationsParameter,
tipTraitParameter,
datesParameter,
columnEffectsParameter,
rowEffectsParameter,
assayTable,
intervalWidth,
null);
Logger.getLogger("dr.evomodel").info("Using EvolutionaryCartography model. Please cite:\n" + Utils.getCitationString(AGL));
return AGL;
}
|
/*
* LogisticGrowthN0.java
*
* Daniel Wilson 4th October 2011
*
*/
package dr.evomodel.epidemiology;
import dr.evolution.coalescent.*;
/**
* This class models logistic growth.
*
* @author Daniel Wilson
* @author Alexei Drummond
* @author Andrew Rambaut
* @version $Id: LogisticGrowth.java,v 1.15 2008/03/21 20:25:56 rambaut Exp $
*/
public class LogisticGrowthN0 extends ExponentialGrowth {
/**
* Construct demographic model with default settings
*/
public LogisticGrowthN0(Type units) {
super(units);
}
public void setT50(double value) {
t50 = value;
}
public double getT50() {
return t50;
}
// Implementation of abstract methods
/**
* Gets the value of the demographic function N(t) at time t.
*
* @param t the time
* @return the value of the demographic function N(t) at time t.
*/
public double getDemographic(double t) {
double N0 = getN0();
double r = getGrowthRate();
double T50 = getT50();
return N0 * (1 + Math.exp(-r * T50)) / (1 + Math.exp(r * (t-T50)));
}
public double getLogDemographic(double t) {
return Math.log(getDemographic(t));
}
/**
* Returns value of demographic intensity function at time t
* (= integral 1/N(x) dx from 0 to t).
*/
public double getIntensity(double t) {
double N0 = getN0();
double r = getGrowthRate();
double T50 = getT50();
double exp_rT50 = Math.exp(-r*T50);
return (t + exp_rT50 * (Math.exp(r * t) - 1)/r) / (N0 * (1 + exp_rT50));
}
/**
* Returns the inverse function of getIntensity
*
* If exp(-qt) = a(x-k) then t = k + (1/q) * W(q*exp(-q*k)/a) where W(x) is the Lambert W function.
*
* for our purposes:
*
* q = -r
* a = (q/exp(q*T50))
* k = N0*(1+exp(q*T50))*x - (1/q)exp(q*T50)
*
* For large x, W0(x) is approximately equal to ln(x) - ln(ln(x)); if q*exp(-q*k)/a rounds to infinity, we log it
* and use this instead
*/
public double getInverseIntensity(double x) {
double q = -getGrowthRate();
double T50 = getT50();
double N0 = getN0();
double a = (q/Math.exp(q*T50));
double k = N0*(1+Math.exp(q*T50))*x - (1/q)*Math.exp(q*T50);
double lambertInput = q*Math.exp(-q*k)/a;
double lambertResult;
if(lambertInput==Double.POSITIVE_INFINITY){
//use the asymptote
double logInput = Math.log(-q)-Math.log(-a)-q*k;
lambertResult = logInput - Math.log(logInput);
} else {
lambertResult = LambertW.branch0(lambertInput);
}
return k + (1/q)*lambertResult;
}
public double getIntegral(double start, double finish) {
return getIntensity(finish) - getIntensity(start);
}
public int getNumArguments() {
return 3;
}
public String getArgumentName(int n) {
switch (n) {
case 0:
return "N0";
case 1:
return "r";
case 2:
return "t50";
}
throw new IllegalArgumentException("Argument " + n + " does not exist");
}
public double getArgument(int n) {
switch (n) {
case 0:
return getN0();
case 1:
return getGrowthRate();
case 2:
return getT50();
}
throw new IllegalArgumentException("Argument " + n + " does not exist");
}
public void setArgument(int n, double value) {
switch (n) {
case 0:
setN0(value);
break;
case 1:
setGrowthRate(value);
break;
case 2:
setT50(value);
break;
default:
throw new IllegalArgumentException("Argument " + n + " does not exist");
}
}
public double getLowerBound(int n) {
return 0.0;
}
public double getUpperBound(int n) {
return Double.POSITIVE_INFINITY;
}
public DemographicFunction getCopy() {
LogisticGrowthN0 df = new LogisticGrowthN0(getUnits());
df.setN0(getN0());
df.setGrowthRate(getGrowthRate());
df.setT50(getT50());
return df;
}
// private stuff
private double t50;
}
|
package edu.caravane.guitare.gitobejct;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.file.Paths;
import java.nio.file.Files;
import java.util.zip.DataFormatException;
import java.util.zip.Inflater;
//13h55 -> 14h05
//16h00 -> 16h18
/**
*
* @author VieVie31
*
*/
public class BinaryFile {
/**
* Return the content of the file specified by the path argument as
* a byte array.
*
* @param path the path of the binary file to read
* @return the content of the file
* @throws IOException
* @author VieVie31
*/
public static byte[] read(String path) throws IOException {
return Files.readAllBytes(Paths.get(path)); //java7 way
}
/**
* Return the decompressed version of the input array using the zlib
* algorithm.
*
* @param data an input byte array to decompress using zlib
* @return the data array decompressed
* @throws IOException
* @throws DataFormatException
* @author VieVie31
*/
public static byte[] decompress(byte[] data)
throws IOException, DataFormatException {
Inflater inflater = new Inflater();
inflater.setInput(data);
ByteArrayOutputStream outputStream;
outputStream = new ByteArrayOutputStream(data.length);
byte[] buffer = new byte[1024];
while (!inflater.finished())
outputStream.write(buffer, 0, inflater.inflate(buffer));
outputStream.close();
return outputStream.toByteArray();
}
/**
* Return a decompressed file content, using the zlib algorithm ,
* as byte array.
*
* @param path of the binary file to decompress
* @return the content of the file decompressed
* @throws IOException
* @throws DataFormatException
* @author VieVie31
*/
public static byte[] decompress(String path)
throws IOException, DataFormatException {
return decompress(read(path));
}
}
|
package edu.drexel.tm.cs338.textacular;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
/**
* The class TeXHandler.
*
* Handles validation, generation, and compilation of TeX files
*
* @author Trevor Maglione <tm@cs.drexel.edu>
*/
public class TeXHandler {
/**
* The temp file prefix.
*/
private static final String PREFIX = "textacular";
/**
* The output directory.
*/
private static final String OUTDIR = "res/output";
/**
* The job name for latexmk.
*/
private static final String JOBNAME = "output";
/**
* The directory.
*/
private String directory;
/**
* The source filename.
*/
private String filename;
/**
* The template file contents.
*/
private String templateContents;
/**
* The temporary TeX file.
*/
private File texFile;
/**
* Instantiate a new TeXHandler.
*
* @param directory the directory
* @param filename the source filename
*/
public TeXHandler(String directory, String filename) {
this.directory = directory;
this.filename = filename;
templateContents = checkTemplateFile() ? readTemplateFile() : "";
texFile = null;
}
/**
* Determine if the source file exists and is readable.
*
* @return if the file exists and is not a directory
*/
protected boolean checkTemplateFile() {
File sourceFile = new File(String.format("%s/%s", directory, filename));
return sourceFile.exists() && !sourceFile.isDirectory();
}
/**
* Get the template contents.
*
* @return the template contents
*/
protected String getTemplateContents() {
return templateContents;
}
/**
* Prepare the new TeX file.
*
* @param newContents the contents with input variables
* @throws IOException
*/
protected void prepareContents(String newContents) throws IOException {
if (texFile == null) {
texFile = File.createTempFile(PREFIX, ".tex");
texFile.deleteOnExit();
}
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(texFile)));
bw.write(newContents);
bw.close();
}
/**
* Compile the TeX file.
* @throws IOException
* @throws InterruptedException
*/
protected void compile() throws IOException, InterruptedException {
System.out.println(texFile.getAbsolutePath());
Process p = Runtime.getRuntime().exec(String.format("latexmk -gg -pdf -jobname=%s/%s %s", OUTDIR, JOBNAME, texFile.getAbsolutePath()));
p.waitFor();
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
/**
* Remove compiled and intermediate files.
*/
protected void cleanup() {
}
/**
* Read the source file.
*
* @return the contents of the source file, null on error
*/
protected String readTemplateFile() {
BufferedReader br;
try {
br = new BufferedReader(new FileReader(String.format("%s/%s", directory, filename)));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(String.format("%s%n", line));
}
br.close();
return sb.toString();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
|
package edu.mit.streamjit.impl.compiler2;
import static com.google.common.base.Preconditions.checkArgument;
import static edu.mit.streamjit.util.LookupUtils.findStatic;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import static edu.mit.streamjit.util.LookupUtils.findVirtual;
import edu.mit.streamjit.util.NIOBufferUtils;
import edu.mit.streamjit.util.PrimitiveUtils;
import java.lang.invoke.MethodType;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.nio.Buffer;
import java.util.Locale;
import sun.misc.Unsafe;
/**
* An array-ish object; that is, storage for items of a given type (and its
* subtypes) in slots from 0 to size-1.
* @author Jeffrey Bosboom <jeffreybosboom@gmail.com>
* @since 2/28/2014
*/
public interface Arrayish {
public static final MethodHandle GET = findVirtual(MethodHandles.publicLookup(), Arrayish.class, "get", Object.class, int.class);
public static final MethodHandle SET = findVirtual(MethodHandles.publicLookup(), Arrayish.class, "set", void.class, int.class, Object.class);
public Class<?> type();
public int size();
/**
* Returns a MethodHandle of type int -> T.
* @return a read handle
*/
public MethodHandle get();
/**
* Returns a MethodHandle of type int, T -> void.
* @return a write handle
*/
public MethodHandle set();
/**
* An Arrayish backed by an actual Java array.
*/
public static final class ArrayArrayish implements Arrayish {
private final Object array;
private final MethodHandle get, set;
public ArrayArrayish(Class<?> type, int size) {
this.array = Array.newInstance(type, size);
this.get = MethodHandles.arrayElementGetter(array.getClass()).bindTo(array);
this.set = MethodHandles.arrayElementSetter(array.getClass()).bindTo(array);
}
@Override
public Class<?> type() {
return array.getClass().getComponentType();
}
@Override
public int size() {
return Array.getLength(array);
}
@Override
public MethodHandle get() {
return get;
}
@Override
public MethodHandle set() {
return set;
}
}
/**
* An Arrayish of primitives backed by a direct NIO buffer. (Non-direct NIO
* buffers are just arrays -- use ArrayArrayish instead.)
*/
public static final class NIOArrayish implements Arrayish {
private final Buffer buffer;
private final int size;
private final MethodHandle get, set;
public NIOArrayish(Class<?> type, int size) {
checkArgument(type.isPrimitive() && !type.equals(void.class), "%s can't be stored in an NIO buffer", type);
Class<?> dataType = type.equals(boolean.class) ? byte.class : type;
Class<? extends Buffer> bufferType = NIOBufferUtils.bufferForPrimitive(dataType);
this.buffer = NIOBufferUtils.allocateDirect(bufferType, size);
this.size = size;
//explicitCastArguments converts byte to boolean and back; otherwise
//the types exactly match and the target is returned immediately.
this.get = MethodHandles.explicitCastArguments(
findVirtual(MethodHandles.publicLookup(), bufferType, "get", dataType, int.class)
.bindTo(buffer),
MethodType.methodType(type, int.class));
this.set = MethodHandles.explicitCastArguments(
findVirtual(MethodHandles.publicLookup(), bufferType, "put", bufferType, int.class, dataType)
.bindTo(buffer),
MethodType.methodType(void.class, int.class, type));
}
@Override
public Class<?> type() {
return get.type().returnType();
}
@Override
public int size() {
return size;
}
@Override
public MethodHandle get() {
return get;
}
@Override
public MethodHandle set() {
return set;
}
}
/**
* An Arrayish of primitives backed by native memory. The returned handles
* do not keep a strong reference to this object, so something else must do
* so to prevent the native memory from being freed while it's still used.
* (In Compiler2, Read/Write/DrainInstructions that reference
* ConcreteStorage serve this function.)
*/
public static final class UnsafeArrayish implements Arrayish {
private static final sun.misc.Unsafe UNSAFE;
static {
try {
Field f = sun.misc.Unsafe.class.getDeclaredField("theUnsafe");
f.setAccessible(true);
UNSAFE = (Unsafe)f.get(null);
} catch (NoSuchFieldException | IllegalAccessException ex) {
throw new AssertionError(ex);
}
}
private static final MethodHandle INDEX = findStatic(MethodHandles.lookup(), UnsafeArrayish.class, "index", long.class, long.class, int.class, int.class);
private final long memory;
private final int size;
private final MethodHandle get, set;
public UnsafeArrayish(Class<?> type, int size) {
//We can't store object references for lack of GC roots.
checkArgument(type.isPrimitive() && !type.equals(void.class), "%s can't be stored in native memory", type);
checkArgument(size >= 0, "bad size: %s", size);
this.memory = UNSAFE.allocateMemory(size * PrimitiveUtils.sizeof(type));
this.size = size;
Class<?> dataType = type.equals(boolean.class) ? byte.class : type;
String dataTypeNameCap = dataType.getSimpleName().substring(0, 1).toUpperCase(Locale.ROOT)
+ dataType.getSimpleName().substring(1);
MethodHandle index = MethodHandles.insertArguments(INDEX, 0, memory, PrimitiveUtils.sizeof(dataType));
//explicitCastArguments converts byte to boolean and back; otherwise
//the types exactly match and the target is returned immediately.
this.get = MethodHandles.explicitCastArguments(
MethodHandles.filterArguments(
findVirtual(MethodHandles.publicLookup(), sun.misc.Unsafe.class, "get" + dataTypeNameCap, dataType, long.class)
.bindTo(UNSAFE),
0, index),
MethodType.methodType(type, int.class));
this.set = MethodHandles.explicitCastArguments(
MethodHandles.filterArguments(
findVirtual(MethodHandles.publicLookup(), sun.misc.Unsafe.class, "put" + dataTypeNameCap, void.class, long.class, dataType)
.bindTo(UNSAFE),
0, index),
MethodType.methodType(void.class, int.class, type));
}
@Override
public Class<?> type() {
return get.type().returnType();
}
@Override
public int size() {
return size;
}
@Override
public MethodHandle get() {
return get;
}
@Override
public MethodHandle set() {
return set;
}
private static long index(long base, int stride, int index) {
return base + stride * index;
}
@Override
protected void finalize() throws Throwable {
super.finalize();
UNSAFE.freeMemory(memory);
}
}
}
|
package edu.wpi.first.wpilibj.templates;
import com.sun.squawk.io.BufferedReader;
import com.sun.squawk.microedition.io.FileConnection;
import edu.wpi.first.wpilibj.Compressor;
import edu.wpi.first.wpilibj.DriverStation;
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.RobotDrive;
import edu.wpi.first.wpilibj.Servo;
import edu.wpi.first.wpilibj.SimpleRobot;
import edu.wpi.first.wpilibj.Talon;
import edu.wpi.first.wpilibj.Timer;
import edu.wpi.first.wpilibj.camera.AxisCamera;
import edu.wpi.first.wpilibj.camera.AxisCameraException;
import edu.wpi.first.wpilibj.image.BinaryImage;
import edu.wpi.first.wpilibj.image.NIVisionException;
import edu.wpi.first.wpilibj.smartdashboard.*;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.io.Reader;
import javax.microedition.io.Connector;
public class RobotMain extends SimpleRobot {
Compressor compressor = new Compressor(1, 1);
RobotDrive chassis;
Joystick leftStick = new Joystick(1);
Joystick rightStick = new Joystick(2);
AxisCamera camera;
Servo servoTest;
DriverStation driverStation;
final int frontLeft = 0;
final int backLeft = 1;
final int backRight = 2;
final int frontRight = 3;
double[] motorValues = new double[4];
double[] offsetTrim = new double[4];
double[] scaleTrim = new double[4];
Talon fl;
Talon bl;
Talon fr;
Talon br;
private VisionProcessing visionProcessing;
public RobotMain() {
}
public void robotInit() {
camera = AxisCamera.getInstance("10.14.92.11");
visionProcessing = new VisionProcessing();
visionProcessing.init(camera);
driverStation = DriverStation.getInstance();
servoTest = new Servo(5);
fl = new Talon(1); //create the talons for each of the four wheels
bl = new Talon(2);
br = new Talon(3);
fr = new Talon(4);
compressor.start();
chassis = new RobotDrive(fl, bl, fr, br); //create the chassis with the motor drivers
chassis.setExpiration(2); // since this is a double it's probrably seconds not miliseconds
chassis.setInvertedMotor(RobotDrive.MotorType.kFrontRight, true); //invert the two motors so the robot drives correctly
chassis.setInvertedMotor(RobotDrive.MotorType.kRearRight, true);
}
public void autonomous() { //this method is called once when the robot is autonomous mode
visionProcessing.autonomousInit();
BinaryImage filteredImage;
while (this.isAutonomous() && this.isEnabled()) {
driveNowhere();
try {
filteredImage = visionProcessing.filterImage(camera.getImage()); //get an image and filter for vision targets
visionProcessing.autonomousUpdate(filteredImage); //process the filtered image and look for any potential targets
} catch (Exception e) {
}
SmartDashboard.putBoolean("Target Hot", visionProcessing.target.Hot);
Timer.delay(0.01);
}
}
public void operatorControl() { //this method is called once when the robot is teleoperated mode
chassis.setSafetyEnabled(true);
SmartDashboard.putString("Alliance", driverStation.getAlliance().name);
while (this.isOperatorControl() && this.isEnabled()) {
SmartDashboard.putNumber("Mecanum X", getMecX()); //put the different motor and joystick values on the dashboard for debugging
SmartDashboard.putNumber("Mecanum Y", getMecY());
SmartDashboard.putNumber("Mecanum Rotation", getMecRot());
SmartDashboard.putNumber("Front Left", fl.getSpeed());
SmartDashboard.putNumber("Front Right", fr.getSpeed());
SmartDashboard.putNumber("Back Left", bl.getSpeed());
SmartDashboard.putNumber("Back Right", br.getSpeed());
motorValues = mecanumDrive(getMecX(), getMecY(), getMecRot());
//chassis.mecanumDrive_Cartesian(getMecX(), getMecY(), getMecRot(), 0);
offsetTrim[frontLeft] = SmartDashboard.getNumber("Front Left Offset"); //get the offsets for the motors
offsetTrim[frontRight] = SmartDashboard.getNumber("Front Right Offset");
offsetTrim[backLeft] = SmartDashboard.getNumber("Back Left Offset");
offsetTrim[backRight] = SmartDashboard.getNumber("Back Right Offset");
scaleTrim[frontLeft] = SmartDashboard.getNumber("Front Left Scale"); //get the scaling for the motors
scaleTrim[frontRight] = SmartDashboard.getNumber("Front Right Scale");
scaleTrim[backLeft] = SmartDashboard.getNumber("Back Left Scale");
scaleTrim[backRight] = SmartDashboard.getNumber("Back Right Scale");
motorValues = trimValues(motorValues, scaleTrim, offsetTrim); //scale and offset the motors
driveMotors(motorValues); //set the motors to the scaled and offset values
if(SmartDashboard.getBoolean("Test file output", false)) { //test writing to a file
DataOutputStream file;
FileConnection fc;
try {
fc = (FileConnection)Connector.open("file:///test.txt", Connector.WRITE);
fc.create();
file = fc.openDataOutputStream();
file.writeUTF(SmartDashboard.getString("Data to write to file"));
file.flush();
file.close();
fc.close();
} catch (IOException ex) {
}
}
if(SmartDashboard.getBoolean("Test file input", false)) { //test reaing from a file
FileConnection fc;
BufferedReader reader;
try {
fc = (FileConnection)Connector.open("file:///test.txt", Connector.READ);
fc.create();
reader = new BufferedReader((Reader) fc);
String firstLine = reader.readLine();
SmartDashboard.putString("First line of the file", firstLine); //put the first line of the file on the SmartDashboard
fc.close();
} catch (IOException ex) {
}
}
if (rightStick.getRawButton(3)) {
servoTest.setAngle(-360);
} else if (rightStick.getRawButton(2)) { //down
servoTest.setAngle(360);
}
Timer.delay(0.01); //do not run the loop to fast
}
}
public void disabled() {
}
public void test() { //this method is called once when the robot is test mode
visionProcessing.autonomousInit();
BinaryImage filteredImage;
try {
filteredImage = visionProcessing.filterImageTest(camera.getImage());
visionProcessing.autonomousUpdate(filteredImage);
} catch (AxisCameraException ex) {
} catch (NIVisionException ex) {
}
SmartDashboard.putBoolean("Target Hot", visionProcessing.target.Hot);
while (this.isTest() && this.isEnabled()) { //keep the robot from returning errors
driveNowhere();
Timer.delay(0.1);
}
}
private double getMecX() { //get joystick values
return deadZone(rightStick.getAxis(Joystick.AxisType.kX));
}
private double getMecY() { //get joystick values
return deadZone(rightStick.getAxis(Joystick.AxisType.kY));
}
private double getMecRot() { //get joystick values
return deadZone(leftStick.getAxis(Joystick.AxisType.kX));
}
private double deadZone(double value) { //apply a dead zone to a value
return (abs(value) < .1) ? 0 : value;
}
private double abs(double value) { //absoulte value
return value < 0 ? -value : value;
}
private double[] mecanumDrive(double x, double y, double r) { // find the values for the motors based on x, y and rotation values
y = -y;
double frn = 0;
double fln = 0;
double brn = 0;
double bln = 0;
fln = y + x + r;
frn = y - x - r;
bln = y - x + r;
brn = y + x - r;
double[] values = new double[4];
values[frontRight] = frn;
values[frontLeft] = fln;
values[backRight] = brn;
values[backLeft] = bln;
return values;
}
private double[] trimValues(double[] orignalValues, double[] scale, double[] offset) { //apply offset and scaling to the values
double[] trimedValues = new double[4];
for (int i = 0; i < 4; i++) {
trimedValues[i] = orignalValues[i] * scale[i];
}
for (int i = 0; i < 4; i++) {
trimedValues[i] = orignalValues[i] + offset[i];
}
return trimedValues;
}
private void driveMotors(double[] motorValues) { //assign the values to the motors
fl.set(maxAt1(motorValues[frontLeft]));
bl.set(maxAt1(motorValues[backLeft]));
br.set(maxAt1(motorValues[backRight]));
fr.set(maxAt1(motorValues[frontRight]));
}
private double maxAt1(double n) { //make the input value between 1 and -1
return n < -1 ? -1 : (n > 1 ? 1 : n);
}
private void driveNowhere() {
chassis.tankDrive(0, 0);
}
}
|
package task.z04.sql;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import javax.sql.DataSource;
import task.z04.entity.AppUser;
import task.z04.entity.UserMessage;
import task.z04.exception.NotSupportedArgumentTypeException;
public class SQLUtils {
public interface QueryTemplate {
String UPD_LAST_LOGON_DATE_BY_ACCOUNT_ID = "update account set last_logon_date = current_timestamp where id = ?";
String GET_ACCOUNT_ID_AND_USER_ID_BY_LOGIN = "select id, user_id from account where login = ?";
String GET_NAME_AND_LAST_NAME_BY_USER_ID = "select name, last_name from appuser where id = ?";
String GET_LAST_LOGON_DATE_BY_ACCOUNT_ID = "select last_logon_date from account where id = ?";
String GET_ALL_MESSAGES_BY_USER_ID =
"select m.id, m.creation_date, m.text from account a inner join appuser u on (u.id = a.user_id) inner join message m on (m.user_id = u.id) where u.id = ?";
String GET_ALL_USERS = "select u.id, u.name, u.last_name, a.last_logon_date from account a inner join appuser u on (a.user_id = u.id)";
String INS_NEW_MESSAGE_BY_USER_ID = "insert into message (id, user_id, creation_date, text) values (nextval('seq_message_id'), ?, current_timestamp, ?)";
}
public static void insertNewMessage(DataSource dataSource, AppUser user, String message) throws SQLException {
try {
SQLUtils.executeUpdate(
dataSource,
SQLUtils.QueryTemplate.INS_NEW_MESSAGE_BY_USER_ID,
new Object[]{ user.getId(), message }
);
} catch (NotSupportedArgumentTypeException e) {
throw new RuntimeException(e);
}
}
public static List<AppUser> getAllUsers(DataSource dataSource) {
List<AppUser> users = new ArrayList<AppUser>();
List <String[]> usersInfo = new ArrayList<String[]>();
try {
SQLUtils.executeQuery(
dataSource,
SQLUtils.QueryTemplate.GET_ALL_USERS,
new Object[0],
usersInfo
);
} catch (NotSupportedArgumentTypeException | SQLException e) {
throw new RuntimeException(e);
}
for (String[] tuple : usersInfo) {
Calendar calendar = null;
try {
calendar = parseDateFromPostgresFormat(tuple[3]);
} catch (ParseException e) {}
AppUser user = new AppUser(Integer.parseInt(tuple[0]), tuple[1], tuple[2], calendar);
users.add(user);
}
return users;
}
public static List<AppUser> getLastLoginUsers(DataSource dataSource, int usersLimit) {
List<AppUser> allUsers = getAllUsers(dataSource);
TreeSet<AppUser> users = new TreeSet<AppUser>(Collections.reverseOrder());
users.addAll(allUsers);
List<AppUser> selected = new ArrayList<AppUser>();
Iterator<AppUser> iterator = users.iterator();
for (int i = 1; i <= usersLimit && iterator.hasNext(); i++)
selected.add(iterator.next());
return selected;
}
public static List<AppUser> getLateLoginUsers(DataSource dataSource, int usersLimit) {
List<AppUser> allUsers = getAllUsers(dataSource);
Set<AppUser> users = new TreeSet<AppUser>(allUsers);
List<AppUser> selected = new ArrayList<AppUser>();
Iterator<AppUser> iterator = users.iterator();
for (int i = 1; i <= usersLimit && iterator.hasNext(); i++)
selected.add(iterator.next());
return selected;
}
public static List<UserMessage> getAllMessages(DataSource dataSource, AppUser user) {
List<UserMessage> list = new ArrayList<UserMessage>();
List<String[]> messages = new ArrayList<String[]>();
try {
SQLUtils.executeQuery(
dataSource,
SQLUtils.QueryTemplate.GET_ALL_MESSAGES_BY_USER_ID,
new Object[]{ user.getId() },
messages
);
} catch (NotSupportedArgumentTypeException | SQLException e) {
throw new RuntimeException(e);
}
for (String[] tuple : messages) {
Calendar calendar = null;
try {
calendar = parseDateFromPostgresFormat(tuple[1]);
} catch (ParseException e) {}
UserMessage msg = new UserMessage(Integer.parseInt(tuple[0]), user.getId(), calendar, tuple[2]);
list.add(msg);
}
return list;
}
public static final SimpleDateFormat POSTGRES_DATEFORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public static final SimpleDateFormat USER_DATEFORMAT = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
public static Calendar parseDateFromPostgresFormat(String potentilaDate) throws ParseException {
String potentialTime = potentilaDate.substring(0, potentilaDate.indexOf('.'));
Date date = POSTGRES_DATEFORMAT.parse(potentialTime);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar;
}
public static void executeUpdate(DataSource ds, String preparedQueryTemplate, Object[] args)
throws SQLException, NotSupportedArgumentTypeException {
try (Connection connection = ds.getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(preparedQueryTemplate)) {
setArgs(statement, args);
statement.executeUpdate();
}
}
}
public static void executeQuery(DataSource ds, String preparedQueryTemplate, Object[] args, List<String[]> result)
throws SQLException, NotSupportedArgumentTypeException {
try (Connection connection = ds.getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(preparedQueryTemplate)) {
setArgs(statement, args);
try (ResultSet rs = statement.executeQuery()) {
ResultSetMetaData metadata = rs.getMetaData();
int columnsNumber = metadata.getColumnCount();
while (rs.next()) {
String[] tuple = new String[columnsNumber];
for (int i = 1; i <= columnsNumber; i++)
tuple[i - 1] = rs.getString(i);
result.add(tuple);
}
}
}
}
}
private static void setArgs(PreparedStatement statement, Object[] args)
throws NotSupportedArgumentTypeException, SQLException {
for (int i = 0; i < args.length; i++) {
if (args[i] instanceof Integer) {
statement.setInt(i + 1, (Integer) args[i]);
} else if (args[i] instanceof Long) {
statement.setLong(i + 1, (Long) args[i]);
} else if (args[i] instanceof Double) {
statement.setDouble(i + 1, (Double) args[i]);
} else if (args[i] instanceof Float) {
statement.setFloat(i + 1, (Float) args[i]);
} else if (args[i] instanceof Boolean) {
statement.setBoolean(i + 1, (Boolean) args[i]);
} else if (args[i] instanceof String) {
statement.setString(i + 1, (String) args[i]);
} else
throw new NotSupportedArgumentTypeException();
}
}
}
|
package Main.Groceries;
public abstract class Grocery {
private final double TAX = 0.13;
private String name;
private double mass;
private String color;
private double price;
private static int amount;
/**
* A grocery item.
*/
public Grocery() {
this.name = "empty";
this.mass = 0;
}
/**
* A grocery item
*
* @param name Item's name.
*/
public Grocery(String name) {
this();
this.name = name;
}
/**
* A grocery item.
*
* @param name The item's name.
* @param mass The item's mass.
*/
public Grocery(String name, double mass) {
this(name);
this.mass = mass;
}
/**
* A grocery item.
*
* @param name The item's name.
* @param mass The item's mass.
* @param color The item's color.
*/
public Grocery(String name, double mass, String color) {
this(name, mass);
this.color = color;
}
/**
* A grocery item.
*
* @param name The item's name.
* @param mass The item's mass.
* @param color The item's color.
* @param price The item's price
*/
public Grocery(String name, double mass, String color, double price) {
this(name, mass, color);
this.price = price;
}
/**
* A grocery item.
*
* @param name The item's name.
* @param mass The item's mass.
* @param color The item's color.
* @param price The item's price
* @param amount The amount of the item.
*/
public Grocery(String name, double mass, String color, double price, int amount) {
this(name, mass, color, price);
this.amount = amount;
}
/**
* Gets the name of the item
*
* @return
*/
public String getName() {
return name;
}
/**
* Sets the name of the item
*
* @param name
*/
public void setName(String name) {
this.name = name;
}
/**
* Gets the mass of the item
*
* @return
*/
public double getMass() {
return mass;
}
/**
* Sets the mass of the item
*
* @param mass
*/
public void setMass(double mass) {
this.mass = mass;
}
/**
* Gets the price of the item
*
* @return
*/
public double getPrice() {
return price + (price * TAX);
}
/**
* Sets the price of the item
*
* @param price
*/
public void setPrice(double price) {
this.price = price;
}
/**
* Gets the color of the item
*
* @return
*/
public String getColor() {
return color;
}
/**
* Sets the color of the item
*
* @param color
*/
public void setColor(String color) {
this.color = color;
}
public static int getAmount() {
return amount;
}
public static void setAmount(int amount) {
Grocery.amount = amount;
}
public double getTAX() {
return TAX * price;
}
/**
* Eating the item
*/
public abstract void eat();
/**
* Buy an item
*
* @param money The amount of money the user will pay for the item.
* @return Weather the item was bought or not
*/
public abstract boolean buy(double money);
/**
* Returns a string representation of the item
*
* @return
*/
public abstract String toString();
}
|
package org.opencv.imgproc;
import java.lang.Math;
//javadoc:Moments
public class Moments {
public double m00;
public double m10;
public double m01;
public double m20;
public double m11;
public double m02;
public double m30;
public double m21;
public double m12;
public double m03;
public double mu20;
public double mu11;
public double mu02;
public double mu30;
public double mu21;
public double mu12;
public double mu03;
public double nu20;
public double nu11;
public double nu02;
public double nu30;
public double nu21;
public double nu12;
public double nu03;
public Moments(
double m00,
double m10,
double m01,
double m20,
double m11,
double m02,
double m30,
double m21,
double m12,
double m03)
{
this.m00 = m00;
this.m10 = m10;
this.m01 = m01;
this.m20 = m20;
this.m11 = m11;
this.m02 = m02;
this.m30 = m30;
this.m21 = m21;
this.m12 = m12;
this.m03 = m03;
this.completeState();
}
public Moments() {
this(0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
}
public Moments(double[] vals) {
set(vals);
}
public void set(double[] vals) {
if (vals != null) {
m00 = vals.length > 0 ? vals[0] : 0;
m10 = vals.length > 1 ? vals[1] : 0;
m01 = vals.length > 2 ? vals[2] : 0;
m20 = vals.length > 3 ? vals[3] : 0;
m11 = vals.length > 4 ? vals[4] : 0;
m02 = vals.length > 5 ? vals[5] : 0;
m30 = vals.length > 6 ? vals[6] : 0;
m21 = vals.length > 7 ? vals[7] : 0;
m12 = vals.length > 8 ? vals[8] : 0;
m03 = vals.length > 9 ? vals[9] : 0;
this.completeState();
} else {
m00 = 0;
m10 = 0;
m01 = 0;
m20 = 0;
m11 = 0;
m02 = 0;
m30 = 0;
m21 = 0;
m12 = 0;
m03 = 0;
mu20 = 0;
mu11 = 0;
mu02 = 0;
mu30 = 0;
mu21 = 0;
mu12 = 0;
mu03 = 0;
nu20 = 0;
nu11 = 0;
nu02 = 0;
nu30 = 0;
nu21 = 0;
nu12 = 0;
nu03 = 0;
}
}
@Override
public String toString() {
return "Moments [ " +
"\n" +
"m00=" + m00 + ", " +
"\n" +
"m10=" + m10 + ", " +
"m01=" + m01 + ", " +
"\n" +
"m20=" + m20 + ", " +
"m11=" + m11 + ", " +
"m02=" + m02 + ", " +
"\n" +
"m30=" + m30 + ", " +
"m21=" + m21 + ", " +
"m12=" + m12 + ", " +
"m03=" + m03 + ", " +
"\n" +
"mu20=" + mu20 + ", " +
"mu11=" + mu11 + ", " +
"mu02=" + mu02 + ", " +
"\n" +
"mu30=" + mu30 + ", " +
"mu21=" + mu21 + ", " +
"mu12=" + mu12 + ", " +
"mu03=" + mu03 + ", " +
"\n" +
"nu20=" + nu20 + ", " +
"nu11=" + nu11 + ", " +
"nu02=" + nu02 + ", " +
"\n" +
"nu30=" + nu30 + ", " +
"nu21=" + nu21 + ", " +
"nu12=" + nu12 + ", " +
"nu03=" + nu03 + ", " +
"\n]";
}
protected void completeState()
{
double cx = 0, cy = 0;
double mu20, mu11, mu02;
double inv_m00 = 0.0;
if( Math.abs(this.m00) > 0.00000001 )
{
inv_m00 = 1. / this.m00;
cx = this.m10 * inv_m00;
cy = this.m01 * inv_m00;
}
// mu20 = m20 - m10*cx
mu20 = this.m20 - this.m10 * cx;
// mu11 = m11 - m10*cy
mu11 = this.m11 - this.m10 * cy;
// mu02 = m02 - m01*cy
mu02 = this.m02 - this.m01 * cy;
this.mu20 = mu20;
this.mu11 = mu11;
this.mu02 = mu02;
// mu30 = m30 - cx*(3*mu20 + cx*m10)
this.mu30 = this.m30 - cx * (3 * mu20 + cx * this.m10);
mu11 += mu11;
// mu21 = m21 - cx*(2*mu11 + cx*m01) - cy*mu20
this.mu21 = this.m21 - cx * (mu11 + cx * this.m01) - cy * mu20;
// mu12 = m12 - cy*(2*mu11 + cy*m10) - cx*mu02
this.mu12 = this.m12 - cy * (mu11 + cy * this.m10) - cx * mu02;
// mu03 = m03 - cy*(3*mu02 + cy*m01)
this.mu03 = this.m03 - cy * (3 * mu02 + cy * this.m01);
double inv_sqrt_m00 = Math.sqrt(Math.abs(inv_m00));
double s2 = inv_m00*inv_m00, s3 = s2*inv_sqrt_m00;
this.nu20 = this.mu20*s2;
this.nu11 = this.mu11*s2;
this.nu02 = this.mu02*s2;
this.nu30 = this.mu30*s3;
this.nu21 = this.mu21*s3;
this.nu12 = this.mu12*s3;
this.nu03 = this.mu03*s3;
}
public double get_m00() { return this.m00; }
public double get_m10() { return this.m10; }
public double get_m01() { return this.m01; }
public double get_m20() { return this.m20; }
public double get_m11() { return this.m11; }
public double get_m02() { return this.m02; }
public double get_m30() { return this.m30; }
public double get_m21() { return this.m21; }
public double get_m12() { return this.m12; }
public double get_m03() { return this.m03; }
public double get_mu20() { return this.mu20; }
public double get_mu11() { return this.mu11; }
public double get_mu02() { return this.mu02; }
public double get_mu30() { return this.mu30; }
public double get_mu21() { return this.mu21; }
public double get_mu12() { return this.mu12; }
public double get_mu03() { return this.mu03; }
public double get_nu20() { return this.nu20; }
public double get_nu11() { return this.nu11; }
public double get_nu02() { return this.nu02; }
public double get_nu30() { return this.nu30; }
public double get_nu21() { return this.nu21; }
public double get_nu12() { return this.nu12; }
public double get_nu03() { return this.nu03; }
public void set_m00(double m00) { this.m00 = m00; }
public void set_m10(double m10) { this.m10 = m10; }
public void set_m01(double m01) { this.m01 = m01; }
public void set_m20(double m20) { this.m20 = m20; }
public void set_m11(double m11) { this.m11 = m11; }
public void set_m02(double m02) { this.m02 = m02; }
public void set_m30(double m30) { this.m30 = m30; }
public void set_m21(double m21) { this.m21 = m21; }
public void set_m12(double m12) { this.m12 = m12; }
public void set_m03(double m03) { this.m03 = m03; }
public void set_mu20(double mu20) { this.mu20 = mu20; }
public void set_mu11(double mu11) { this.mu11 = mu11; }
public void set_mu02(double mu02) { this.mu02 = mu02; }
public void set_mu30(double mu30) { this.mu30 = mu30; }
public void set_mu21(double mu21) { this.mu21 = mu21; }
public void set_mu12(double mu12) { this.mu12 = mu12; }
public void set_mu03(double mu03) { this.mu03 = mu03; }
public void set_nu20(double nu20) { this.nu20 = nu20; }
public void set_nu11(double nu11) { this.nu11 = nu11; }
public void set_nu02(double nu02) { this.nu02 = nu02; }
public void set_nu30(double nu30) { this.nu30 = nu30; }
public void set_nu21(double nu21) { this.nu21 = nu21; }
public void set_nu12(double nu12) { this.nu12 = nu12; }
public void set_nu03(double nu03) { this.nu03 = nu03; }
}
|
package natlab.Static.builtin;
import java.util.HashMap;
import natlab.toolkits.path.BuiltinQuery;
public abstract class Builtin {
private static HashMap<String, Builtin> builtinMap = new HashMap<String, Builtin>();
public static void main(String[] args) {
java.lang.System.out.println(getInstance("i"));
Builtin b = builtinMap.get("i");
java.lang.System.out.println(b);
java.lang.System.out.println("number of builtins "+builtinMap.size());
java.lang.System.out.println(builtinMap);
}
/**
* returns the builtin from the given name (case sensitive)
* if there is no builtin, returns null.
*/
public static final Builtin getInstance(String name){
if (builtinMap.containsKey(name)){
return builtinMap.get(name);
} else {
return null;
}
}
/**
* returns a builtin query object returning true for all builtings in this class hierarchy
*/
public static BuiltinQuery getBuiltinQuery() {
return new BuiltinQuery(){
public boolean isBuiltin(String functionname)
{ return builtinMap.containsKey(functionname); }
};
}
/**
* calls the BuiltinVisitor method associated with this Builtin, using the given argument,
* and returns the value returned by the visitor.
* (e.g. if this is a Builtin.Plus, calls visitor.casePlus)
*/
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseBuiltin(this,arg);
}
/**
* allows the instantiation of Builtins - used to create more builtins using the builtinMap
*/
//todo should all builtins of a given type be the same, so that this is not required?
protected Builtin create(){return null;}
/**
* Returns the name of the builtin function that this object is referring to
*/
public abstract String getName();
public String toString() {
return getName();
}
public int hashCode() {
return getName().hashCode();
}
//static initializer fills in builtinMap
static {
builtinMap.put("pi",Pi.getInstance());
builtinMap.put("i",I.getInstance());
builtinMap.put("j",J.getInstance());
builtinMap.put("tril",Tril.getInstance());
builtinMap.put("triu",Triu.getInstance());
builtinMap.put("diag",Diag.getInstance());
builtinMap.put("real",Real.getInstance());
builtinMap.put("imag",Imag.getInstance());
builtinMap.put("abs",Abs.getInstance());
builtinMap.put("conj",Conj.getInstance());
builtinMap.put("sign",Sign.getInstance());
builtinMap.put("uplus",Uplus.getInstance());
builtinMap.put("uminus",Uminus.getInstance());
builtinMap.put("fix",Fix.getInstance());
builtinMap.put("round",Round.getInstance());
builtinMap.put("floor",Floor.getInstance());
builtinMap.put("ceil",Ceil.getInstance());
builtinMap.put("complex",Complex.getInstance());
builtinMap.put("plus",Plus.getInstance());
builtinMap.put("minus",Minus.getInstance());
builtinMap.put("times",Times.getInstance());
builtinMap.put("power",Power.getInstance());
builtinMap.put("ldivide",Ldivide.getInstance());
builtinMap.put("rdivide",Rdivide.getInstance());
builtinMap.put("mod",Mod.getInstance());
builtinMap.put("rem",Rem.getInstance());
builtinMap.put("dot",Dot.getInstance());
builtinMap.put("cross",Cross.getInstance());
builtinMap.put("mtimes",Mtimes.getInstance());
builtinMap.put("mpower",Mpower.getInstance());
builtinMap.put("mldivide",Mldivide.getInstance());
builtinMap.put("mrdivide",Mrdivide.getInstance());
builtinMap.put("min",Min.getInstance());
builtinMap.put("max",Max.getInstance());
builtinMap.put("median",Median.getInstance());
builtinMap.put("sqrt",Sqrt.getInstance());
builtinMap.put("realsqrt",Realsqrt.getInstance());
builtinMap.put("erf",Erf.getInstance());
builtinMap.put("erfinv",Erfinv.getInstance());
builtinMap.put("erfc",Erfc.getInstance());
builtinMap.put("erfcinv",Erfcinv.getInstance());
builtinMap.put("gamma",Gamma.getInstance());
builtinMap.put("gammainc",Gammainc.getInstance());
builtinMap.put("betainc",Betainc.getInstance());
builtinMap.put("gammaln",Gammaln.getInstance());
builtinMap.put("exp",Exp.getInstance());
builtinMap.put("log",Log.getInstance());
builtinMap.put("log2",Log2.getInstance());
builtinMap.put("log10",Log10.getInstance());
builtinMap.put("sin",Sin.getInstance());
builtinMap.put("cos",Cos.getInstance());
builtinMap.put("tan",Tan.getInstance());
builtinMap.put("cot",Cot.getInstance());
builtinMap.put("sec",Sec.getInstance());
builtinMap.put("csc",Csc.getInstance());
builtinMap.put("sind",Sind.getInstance());
builtinMap.put("cosd",Cosd.getInstance());
builtinMap.put("tand",Tand.getInstance());
builtinMap.put("cotd",Cotd.getInstance());
builtinMap.put("secd",Secd.getInstance());
builtinMap.put("cscd",Cscd.getInstance());
builtinMap.put("sinh",Sinh.getInstance());
builtinMap.put("cosh",Cosh.getInstance());
builtinMap.put("tanh",Tanh.getInstance());
builtinMap.put("coth",Coth.getInstance());
builtinMap.put("sech",Sech.getInstance());
builtinMap.put("csch",Csch.getInstance());
builtinMap.put("asin",Asin.getInstance());
builtinMap.put("acos",Acos.getInstance());
builtinMap.put("atan",Atan.getInstance());
builtinMap.put("atan2",Atan2.getInstance());
builtinMap.put("acot",Acot.getInstance());
builtinMap.put("asec",Asec.getInstance());
builtinMap.put("acsc",Acsc.getInstance());
builtinMap.put("asind",Asind.getInstance());
builtinMap.put("acosd",Acosd.getInstance());
builtinMap.put("atand",Atand.getInstance());
builtinMap.put("acotd",Acotd.getInstance());
builtinMap.put("asecd",Asecd.getInstance());
builtinMap.put("acscd",Acscd.getInstance());
builtinMap.put("asinh",Asinh.getInstance());
builtinMap.put("acosh",Acosh.getInstance());
builtinMap.put("atanh",Atanh.getInstance());
builtinMap.put("acoth",Acoth.getInstance());
builtinMap.put("asech",Asech.getInstance());
builtinMap.put("acsch",Acsch.getInstance());
builtinMap.put("logm",Logm.getInstance());
builtinMap.put("sqrtm",Sqrtm.getInstance());
builtinMap.put("expm",Expm.getInstance());
builtinMap.put("inv",Inv.getInstance());
builtinMap.put("hypot",Hypot.getInstance());
builtinMap.put("eps",Eps.getInstance());
builtinMap.put("cumsum",Cumsum.getInstance());
builtinMap.put("cumprod",Cumprod.getInstance());
builtinMap.put("mode",Mode.getInstance());
builtinMap.put("prod",Prod.getInstance());
builtinMap.put("sum",Sum.getInstance());
builtinMap.put("mean",Mean.getInstance());
builtinMap.put("eig",Eig.getInstance());
builtinMap.put("norm",Norm.getInstance());
builtinMap.put("rank",Rank.getInstance());
builtinMap.put("cond",Cond.getInstance());
builtinMap.put("det",Det.getInstance());
builtinMap.put("rcond",Rcond.getInstance());
builtinMap.put("linsolve",Linsolve.getInstance());
builtinMap.put("schur",Schur.getInstance());
builtinMap.put("ordschur",Ordschur.getInstance());
builtinMap.put("lu",Lu.getInstance());
builtinMap.put("chol",Chol.getInstance());
builtinMap.put("svd",Svd.getInstance());
builtinMap.put("qr",Qr.getInstance());
builtinMap.put("bitand",Bitand.getInstance());
builtinMap.put("bitor",Bitor.getInstance());
builtinMap.put("bitxor",Bitxor.getInstance());
builtinMap.put("bitcmp",Bitcmp.getInstance());
builtinMap.put("bitset",Bitset.getInstance());
builtinMap.put("bitget",Bitget.getInstance());
builtinMap.put("bitshift",Bitshift.getInstance());
builtinMap.put("find",Find.getInstance());
builtinMap.put("nnz",Nnz.getInstance());
builtinMap.put("not",Not.getInstance());
builtinMap.put("any",Any.getInstance());
builtinMap.put("all",All.getInstance());
builtinMap.put("isreal",Isreal.getInstance());
builtinMap.put("isinf",Isinf.getInstance());
builtinMap.put("isfinite",Isfinite.getInstance());
builtinMap.put("isnan",Isnan.getInstance());
builtinMap.put("eq",Eq.getInstance());
builtinMap.put("ne",Ne.getInstance());
builtinMap.put("lt",Lt.getInstance());
builtinMap.put("gt",Gt.getInstance());
builtinMap.put("le",Le.getInstance());
builtinMap.put("ge",Ge.getInstance());
builtinMap.put("and",And.getInstance());
builtinMap.put("or",Or.getInstance());
builtinMap.put("xor",Xor.getInstance());
builtinMap.put("colon",Colon.getInstance());
builtinMap.put("ones",Ones.getInstance());
builtinMap.put("zeros",Zeros.getInstance());
builtinMap.put("eye",Eye.getInstance());
builtinMap.put("inf",Inf.getInstance());
builtinMap.put("nan",Nan.getInstance());
builtinMap.put("true",True.getInstance());
builtinMap.put("false",False.getInstance());
builtinMap.put("double",Double.getInstance());
builtinMap.put("single",Single.getInstance());
builtinMap.put("char",Char.getInstance());
builtinMap.put("logical",Logical.getInstance());
builtinMap.put("int8",Int8.getInstance());
builtinMap.put("int16",Int16.getInstance());
builtinMap.put("int32",Int32.getInstance());
builtinMap.put("int64",Int64.getInstance());
builtinMap.put("uint8",Uint8.getInstance());
builtinMap.put("uint16",Uint16.getInstance());
builtinMap.put("uint32",Uint32.getInstance());
builtinMap.put("uint64",Uint64.getInstance());
builtinMap.put("cellFunction",CellFunction.getInstance());
builtinMap.put("isfield",Isfield.getInstance());
builtinMap.put("objectFunction",ObjectFunction.getInstance());
builtinMap.put("sort",Sort.getInstance());
builtinMap.put("unique",Unique.getInstance());
builtinMap.put("upper",Upper.getInstance());
builtinMap.put("lower",Lower.getInstance());
builtinMap.put("deblank",Deblank.getInstance());
builtinMap.put("strtrim",Strtrim.getInstance());
builtinMap.put("strfind",Strfind.getInstance());
builtinMap.put("findstr",Findstr.getInstance());
builtinMap.put("strrep",Strrep.getInstance());
builtinMap.put("strcmp",Strcmp.getInstance());
builtinMap.put("strcmpi",Strcmpi.getInstance());
builtinMap.put("strncmpi",Strncmpi.getInstance());
builtinMap.put("strncmp",Strncmp.getInstance());
builtinMap.put("regexptranslate",Regexptranslate.getInstance());
builtinMap.put("regexp",Regexp.getInstance());
builtinMap.put("regexpi",Regexpi.getInstance());
builtinMap.put("regexprep",Regexprep.getInstance());
builtinMap.put("class",Class.getInstance());
builtinMap.put("size",Size.getInstance());
builtinMap.put("length",Length.getInstance());
builtinMap.put("ndims",Ndims.getInstance());
builtinMap.put("numel",Numel.getInstance());
builtinMap.put("end",End.getInstance());
builtinMap.put("isempty",Isempty.getInstance());
builtinMap.put("isobject",Isobject.getInstance());
builtinMap.put("isfloat",Isfloat.getInstance());
builtinMap.put("isinteger",Isinteger.getInstance());
builtinMap.put("islogical",Islogical.getInstance());
builtinMap.put("isstruct",Isstruct.getInstance());
builtinMap.put("ischar",Ischar.getInstance());
builtinMap.put("iscell",Iscell.getInstance());
builtinMap.put("isnumeric",Isnumeric.getInstance());
builtinMap.put("isa",Isa.getInstance());
builtinMap.put("isemtpy",Isemtpy.getInstance());
builtinMap.put("isvector",Isvector.getInstance());
builtinMap.put("isscalar",Isscalar.getInstance());
builtinMap.put("isequalwithequalnans",Isequalwithequalnans.getInstance());
builtinMap.put("isequal",Isequal.getInstance());
builtinMap.put("reshape",Reshape.getInstance());
builtinMap.put("permute",Permute.getInstance());
builtinMap.put("squeeze",Squeeze.getInstance());
builtinMap.put("transpose",Transpose.getInstance());
builtinMap.put("ctranspose",Ctranspose.getInstance());
builtinMap.put("horzcat",Horzcat.getInstance());
builtinMap.put("vertcat",Vertcat.getInstance());
builtinMap.put("cat",Cat.getInstance());
builtinMap.put("subsasgn",Subsasgn.getInstance());
builtinMap.put("subsref",Subsref.getInstance());
builtinMap.put("structfun",Structfun.getInstance());
builtinMap.put("arrayfun",Arrayfun.getInstance());
builtinMap.put("cellfun",Cellfun.getInstance());
builtinMap.put("superiorto",Superiorto.getInstance());
builtinMap.put("superiorfloat",Superiorfloat.getInstance());
builtinMap.put("exit",Exit.getInstance());
builtinMap.put("quit",Quit.getInstance());
builtinMap.put("clock",Clock.getInstance());
builtinMap.put("tic",Tic.getInstance());
builtinMap.put("toc",Toc.getInstance());
builtinMap.put("cputime",Cputime.getInstance());
builtinMap.put("assert",Assert.getInstance());
builtinMap.put("nargoutchk",Nargoutchk.getInstance());
builtinMap.put("nargchk",Nargchk.getInstance());
builtinMap.put("str2func",Str2func.getInstance());
builtinMap.put("pause",Pause.getInstance());
builtinMap.put("eval",Eval.getInstance());
builtinMap.put("evalin",Evalin.getInstance());
builtinMap.put("feval",Feval.getInstance());
builtinMap.put("assignin",Assignin.getInstance());
builtinMap.put("inputname",Inputname.getInstance());
builtinMap.put("import",Import.getInstance());
builtinMap.put("cd",Cd.getInstance());
builtinMap.put("exist",Exist.getInstance());
builtinMap.put("matlabroot",Matlabroot.getInstance());
builtinMap.put("whos",Whos.getInstance());
builtinMap.put("which",Which.getInstance());
builtinMap.put("version",Version.getInstance());
builtinMap.put("clear",Clear.getInstance());
builtinMap.put("nargin",Nargin.getInstance());
builtinMap.put("nargout",Nargout.getInstance());
builtinMap.put("methods",Methods.getInstance());
builtinMap.put("fieldnames",Fieldnames.getInstance());
builtinMap.put("disp",Disp.getInstance());
builtinMap.put("display",Display.getInstance());
builtinMap.put("clc",Clc.getInstance());
builtinMap.put("error",Error.getInstance());
builtinMap.put("warning",Warning.getInstance());
builtinMap.put("echo",Echo.getInstance());
builtinMap.put("diary",Diary.getInstance());
builtinMap.put("message",Message.getInstance());
builtinMap.put("lastwarn",Lastwarn.getInstance());
builtinMap.put("lasterror",Lasterror.getInstance());
builtinMap.put("format",Format.getInstance());
builtinMap.put("rand",Rand.getInstance());
builtinMap.put("randi",Randi.getInstance());
builtinMap.put("randn",Randn.getInstance());
builtinMap.put("computer",Computer.getInstance());
builtinMap.put("beep",Beep.getInstance());
builtinMap.put("dir",Dir.getInstance());
builtinMap.put("unix",Unix.getInstance());
builtinMap.put("dos",Dos.getInstance());
builtinMap.put("system",System.getInstance());
builtinMap.put("load",Load.getInstance());
builtinMap.put("save",Save.getInstance());
builtinMap.put("input",Input.getInstance());
builtinMap.put("textscan",Textscan.getInstance());
builtinMap.put("sprintf",Sprintf.getInstance());
builtinMap.put("sscanf",Sscanf.getInstance());
builtinMap.put("fprintf",Fprintf.getInstance());
builtinMap.put("ftell",Ftell.getInstance());
builtinMap.put("ferror",Ferror.getInstance());
builtinMap.put("fopen",Fopen.getInstance());
builtinMap.put("fread",Fread.getInstance());
builtinMap.put("frewind",Frewind.getInstance());
builtinMap.put("fscanf",Fscanf.getInstance());
builtinMap.put("fseek",Fseek.getInstance());
builtinMap.put("fwrite",Fwrite.getInstance());
builtinMap.put("fgetl",Fgetl.getInstance());
builtinMap.put("fgets",Fgets.getInstance());
builtinMap.put("fclose",Fclose.getInstance());
builtinMap.put("imwrite",Imwrite.getInstance());
builtinMap.put("sparse",Sparse.getInstance());
builtinMap.put("var",Var.getInstance());
builtinMap.put("std",Std.getInstance());
builtinMap.put("realmax",Realmax.getInstance());
builtinMap.put("histc",Histc.getInstance());
}
//the actual Builtin Classes:
public static abstract class AbstractRoot extends Builtin {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractRoot(this,arg);
}
}
public static abstract class AbstractPureFunction extends AbstractRoot {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractPureFunction(this,arg);
}
}
public static abstract class AbstractMatrixFunction extends AbstractPureFunction {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractMatrixFunction(this,arg);
}
}
public static abstract class AbstractConstant extends AbstractMatrixFunction {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractConstant(this,arg);
}
}
public static abstract class AbstractDoubleConstant extends AbstractConstant implements ClassPropagationDefined {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractDoubleConstant(this,arg);
}
public ClassPropTools.MC getMatlabClassPropagationInfo(){{
return getClassPropagationInfo();
}}
private ClassPropTools.MC classPropInfo = null; //new ClassPropTools.MCMap(new ClassPropTools.MCNone(),new ClassPropTools.MCBuiltin("double"));
public ClassPropTools.MC getClassPropagationInfo(){
//set classPropInfo if not defined
if (classPropInfo == null){
ClassPropTools.MC parentClassPropInfo = new ClassPropTools.MCNone();
classPropInfo = new ClassPropTools.MCMap(new ClassPropTools.MCNone(),new ClassPropTools.MCBuiltin("double"));
}
return classPropInfo;
}
}
public static class Pi extends AbstractDoubleConstant {
//returns the singleton instance of this class
private static Pi singleton = null;
public static Pi getInstance(){
if (singleton == null) singleton = new Pi();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.casePi(this,arg);
}
//return name of builtin
public String getName(){
return "pi";
}
}
public static class I extends AbstractDoubleConstant {
//returns the singleton instance of this class
private static I singleton = null;
public static I getInstance(){
if (singleton == null) singleton = new I();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseI(this,arg);
}
//return name of builtin
public String getName(){
return "i";
}
}
public static class J extends AbstractDoubleConstant {
//returns the singleton instance of this class
private static J singleton = null;
public static J getInstance(){
if (singleton == null) singleton = new J();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseJ(this,arg);
}
//return name of builtin
public String getName(){
return "j";
}
}
public static abstract class AbstractAnyMatrixFunction extends AbstractMatrixFunction {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractAnyMatrixFunction(this,arg);
}
}
public static abstract class AbstractProperAnyMatrixFunction extends AbstractAnyMatrixFunction {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractProperAnyMatrixFunction(this,arg);
}
}
public static abstract class AbstractUnaryAnyMatrixFunction extends AbstractProperAnyMatrixFunction {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractUnaryAnyMatrixFunction(this,arg);
}
}
public static abstract class ElementalUnaryAnyMatrixFunction extends AbstractUnaryAnyMatrixFunction {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseElementalUnaryAnyMatrixFunction(this,arg);
}
}
public static abstract class ArrayUnaryAnyMatrixFunction extends AbstractUnaryAnyMatrixFunction {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseArrayUnaryAnyMatrixFunction(this,arg);
}
}
public static abstract class AbstractBinaryAnyMatrixFunction extends AbstractProperAnyMatrixFunction {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractBinaryAnyMatrixFunction(this,arg);
}
}
public static abstract class ElementalBinaryAnyMatrixFunction extends AbstractBinaryAnyMatrixFunction {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseElementalBinaryAnyMatrixFunction(this,arg);
}
}
public static abstract class ArrayBinaryAnyMatrixFunction extends AbstractBinaryAnyMatrixFunction {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseArrayBinaryAnyMatrixFunction(this,arg);
}
}
public static abstract class AbstractImproperAnyMatrixFunction extends AbstractAnyMatrixFunction {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractImproperAnyMatrixFunction(this,arg);
}
}
public static abstract class AbstractDiagonalSensitive extends AbstractImproperAnyMatrixFunction implements ClassPropagationDefined {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractDiagonalSensitive(this,arg);
}
public ClassPropTools.MC getMatlabClassPropagationInfo(){{
return getClassPropagationInfo();
}}
private ClassPropTools.MC classPropInfo = null; //new ClassPropTools.MCMap(new ClassPropTools.MCChain(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("single"),new ClassPropTools.MCBuiltin("double")),new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("int8"),new ClassPropTools.MCBuiltin("uint16")),new ClassPropTools.MCBuiltin("uint32")),new ClassPropTools.MCBuiltin("uint64")),new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("int8"),new ClassPropTools.MCBuiltin("uint16")),new ClassPropTools.MCBuiltin("uint32")),new ClassPropTools.MCBuiltin("uint64")))),new ClassPropTools.MCBuiltin("char")),new ClassPropTools.MCBuiltin("logical")),new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("single"),new ClassPropTools.MCBuiltin("double")),new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("int8"),new ClassPropTools.MCBuiltin("uint16")),new ClassPropTools.MCBuiltin("uint32")),new ClassPropTools.MCBuiltin("uint64")),new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("int8"),new ClassPropTools.MCBuiltin("uint16")),new ClassPropTools.MCBuiltin("uint32")),new ClassPropTools.MCBuiltin("uint64")))),new ClassPropTools.MCBuiltin("char")),new ClassPropTools.MCBuiltin("logical")),new ClassPropTools.MCNone())),new ClassPropTools.MCNum(0));
public ClassPropTools.MC getClassPropagationInfo(){
//set classPropInfo if not defined
if (classPropInfo == null){
ClassPropTools.MC parentClassPropInfo = new ClassPropTools.MCNone();
classPropInfo = new ClassPropTools.MCMap(new ClassPropTools.MCChain(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("single"),new ClassPropTools.MCBuiltin("double")),new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("int8"),new ClassPropTools.MCBuiltin("uint16")),new ClassPropTools.MCBuiltin("uint32")),new ClassPropTools.MCBuiltin("uint64")),new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("int8"),new ClassPropTools.MCBuiltin("uint16")),new ClassPropTools.MCBuiltin("uint32")),new ClassPropTools.MCBuiltin("uint64")))),new ClassPropTools.MCBuiltin("char")),new ClassPropTools.MCBuiltin("logical")),new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("single"),new ClassPropTools.MCBuiltin("double")),new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("int8"),new ClassPropTools.MCBuiltin("uint16")),new ClassPropTools.MCBuiltin("uint32")),new ClassPropTools.MCBuiltin("uint64")),new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("int8"),new ClassPropTools.MCBuiltin("uint16")),new ClassPropTools.MCBuiltin("uint32")),new ClassPropTools.MCBuiltin("uint64")))),new ClassPropTools.MCBuiltin("char")),new ClassPropTools.MCBuiltin("logical")),new ClassPropTools.MCNone())),new ClassPropTools.MCNum(0));
}
return classPropInfo;
}
}
public static class Tril extends AbstractDiagonalSensitive {
//returns the singleton instance of this class
private static Tril singleton = null;
public static Tril getInstance(){
if (singleton == null) singleton = new Tril();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseTril(this,arg);
}
//return name of builtin
public String getName(){
return "tril";
}
}
public static class Triu extends AbstractDiagonalSensitive {
//returns the singleton instance of this class
private static Triu singleton = null;
public static Triu getInstance(){
if (singleton == null) singleton = new Triu();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseTriu(this,arg);
}
//return name of builtin
public String getName(){
return "triu";
}
}
public static class Diag extends AbstractDiagonalSensitive {
//returns the singleton instance of this class
private static Diag singleton = null;
public static Diag getInstance(){
if (singleton == null) singleton = new Diag();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseDiag(this,arg);
}
//return name of builtin
public String getName(){
return "diag";
}
}
public static abstract class AbstractDimensionSensitiveAnyMatrixFunction extends AbstractImproperAnyMatrixFunction {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractDimensionSensitiveAnyMatrixFunction(this,arg);
}
}
public static abstract class DimensionCollapsingAnyMatrixFunction extends AbstractDimensionSensitiveAnyMatrixFunction {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseDimensionCollapsingAnyMatrixFunction(this,arg);
}
}
public static abstract class AbstractNumericFunction extends AbstractMatrixFunction {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractNumericFunction(this,arg);
}
}
public static abstract class AbstractProperNumericFunction extends AbstractNumericFunction {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractProperNumericFunction(this,arg);
}
}
public static abstract class AbstractUnaryNumericFunction extends AbstractProperNumericFunction implements ClassPropagationDefined {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractUnaryNumericFunction(this,arg);
}
public ClassPropTools.MC getMatlabClassPropagationInfo(){{
return getClassPropagationInfo();
}}
private ClassPropTools.MC classPropInfo = null; //new ClassPropTools.MCUnion(new ClassPropTools.MCMap(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("single"),new ClassPropTools.MCBuiltin("double")),new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("int8"),new ClassPropTools.MCBuiltin("uint16")),new ClassPropTools.MCBuiltin("uint32")),new ClassPropTools.MCBuiltin("uint64")),new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("int8"),new ClassPropTools.MCBuiltin("uint16")),new ClassPropTools.MCBuiltin("uint32")),new ClassPropTools.MCBuiltin("uint64")))),new ClassPropTools.MCNum(0)),new ClassPropTools.MCMap(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("char"),new ClassPropTools.MCBuiltin("logical")),new ClassPropTools.MCBuiltin("double")));
public ClassPropTools.MC getClassPropagationInfo(){
//set classPropInfo if not defined
if (classPropInfo == null){
ClassPropTools.MC parentClassPropInfo = new ClassPropTools.MCNone();
classPropInfo = new ClassPropTools.MCUnion(new ClassPropTools.MCMap(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("single"),new ClassPropTools.MCBuiltin("double")),new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("int8"),new ClassPropTools.MCBuiltin("uint16")),new ClassPropTools.MCBuiltin("uint32")),new ClassPropTools.MCBuiltin("uint64")),new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("int8"),new ClassPropTools.MCBuiltin("uint16")),new ClassPropTools.MCBuiltin("uint32")),new ClassPropTools.MCBuiltin("uint64")))),new ClassPropTools.MCNum(0)),new ClassPropTools.MCMap(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("char"),new ClassPropTools.MCBuiltin("logical")),new ClassPropTools.MCBuiltin("double")));
}
return classPropInfo;
}
}
public static abstract class AbstractElementalUnaryNumericFunction extends AbstractUnaryNumericFunction {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractElementalUnaryNumericFunction(this,arg);
}
}
public static class Real extends AbstractElementalUnaryNumericFunction {
//returns the singleton instance of this class
private static Real singleton = null;
public static Real getInstance(){
if (singleton == null) singleton = new Real();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseReal(this,arg);
}
//return name of builtin
public String getName(){
return "real";
}
}
public static class Imag extends AbstractElementalUnaryNumericFunction {
//returns the singleton instance of this class
private static Imag singleton = null;
public static Imag getInstance(){
if (singleton == null) singleton = new Imag();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseImag(this,arg);
}
//return name of builtin
public String getName(){
return "imag";
}
}
public static class Abs extends AbstractElementalUnaryNumericFunction {
//returns the singleton instance of this class
private static Abs singleton = null;
public static Abs getInstance(){
if (singleton == null) singleton = new Abs();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbs(this,arg);
}
//return name of builtin
public String getName(){
return "abs";
}
}
public static class Conj extends AbstractElementalUnaryNumericFunction {
//returns the singleton instance of this class
private static Conj singleton = null;
public static Conj getInstance(){
if (singleton == null) singleton = new Conj();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseConj(this,arg);
}
//return name of builtin
public String getName(){
return "conj";
}
private ClassPropTools.MC matlabClassPropInfo = null; //new ClassPropTools.MCMap(new ClassPropTools.MCBuiltin("logical"),new ClassPropTools.MCError());
public ClassPropTools.MC getMatlabClassPropagationInfo(){
//set classPropInfo if not defined
if (matlabClassPropInfo == null){
ClassPropTools.MC parentClassPropInfo = super.getMatlabClassPropagationInfo();
matlabClassPropInfo = new ClassPropTools.MCMap(new ClassPropTools.MCBuiltin("logical"),new ClassPropTools.MCError());
}
return matlabClassPropInfo;
}
}
public static class Sign extends AbstractElementalUnaryNumericFunction {
//returns the singleton instance of this class
private static Sign singleton = null;
public static Sign getInstance(){
if (singleton == null) singleton = new Sign();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseSign(this,arg);
}
//return name of builtin
public String getName(){
return "sign";
}
private ClassPropTools.MC matlabClassPropInfo = null; //new ClassPropTools.MCMap(new ClassPropTools.MCBuiltin("logical"),new ClassPropTools.MCError());
public ClassPropTools.MC getMatlabClassPropagationInfo(){
//set classPropInfo if not defined
if (matlabClassPropInfo == null){
ClassPropTools.MC parentClassPropInfo = super.getMatlabClassPropagationInfo();
matlabClassPropInfo = new ClassPropTools.MCMap(new ClassPropTools.MCBuiltin("logical"),new ClassPropTools.MCError());
}
return matlabClassPropInfo;
}
}
public static abstract class AbstractElementalUnaryArithmetic extends AbstractElementalUnaryNumericFunction {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractElementalUnaryArithmetic(this,arg);
}
}
public static class Uplus extends AbstractElementalUnaryArithmetic {
//returns the singleton instance of this class
private static Uplus singleton = null;
public static Uplus getInstance(){
if (singleton == null) singleton = new Uplus();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseUplus(this,arg);
}
//return name of builtin
public String getName(){
return "uplus";
}
}
public static class Uminus extends AbstractElementalUnaryArithmetic {
//returns the singleton instance of this class
private static Uminus singleton = null;
public static Uminus getInstance(){
if (singleton == null) singleton = new Uminus();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseUminus(this,arg);
}
//return name of builtin
public String getName(){
return "uminus";
}
}
public static abstract class AbstractRoundingOperation extends AbstractElementalUnaryNumericFunction {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractRoundingOperation(this,arg);
}
private ClassPropTools.MC matlabClassPropInfo = null; //new ClassPropTools.MCUnion(new ClassPropTools.MCMap(new ClassPropTools.MCBuiltin("logical"),new ClassPropTools.MCError()),getClassPropagationInfo());
public ClassPropTools.MC getMatlabClassPropagationInfo(){
//set classPropInfo if not defined
if (matlabClassPropInfo == null){
ClassPropTools.MC parentClassPropInfo = super.getMatlabClassPropagationInfo();
matlabClassPropInfo = new ClassPropTools.MCUnion(new ClassPropTools.MCMap(new ClassPropTools.MCBuiltin("logical"),new ClassPropTools.MCError()),getClassPropagationInfo());
}
return matlabClassPropInfo;
}
}
public static class Fix extends AbstractRoundingOperation {
//returns the singleton instance of this class
private static Fix singleton = null;
public static Fix getInstance(){
if (singleton == null) singleton = new Fix();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseFix(this,arg);
}
//return name of builtin
public String getName(){
return "fix";
}
private ClassPropTools.MC matlabClassPropInfo = null; //new ClassPropTools.MCUnion(new ClassPropTools.MCMap(new ClassPropTools.MCBuiltin("logical"),new ClassPropTools.MCBuiltin("double")),getClassPropagationInfo());
public ClassPropTools.MC getMatlabClassPropagationInfo(){
//set classPropInfo if not defined
if (matlabClassPropInfo == null){
ClassPropTools.MC parentClassPropInfo = super.getMatlabClassPropagationInfo();
matlabClassPropInfo = new ClassPropTools.MCUnion(new ClassPropTools.MCMap(new ClassPropTools.MCBuiltin("logical"),new ClassPropTools.MCBuiltin("double")),getClassPropagationInfo());
}
return matlabClassPropInfo;
}
}
public static class Round extends AbstractRoundingOperation {
//returns the singleton instance of this class
private static Round singleton = null;
public static Round getInstance(){
if (singleton == null) singleton = new Round();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseRound(this,arg);
}
//return name of builtin
public String getName(){
return "round";
}
}
public static class Floor extends AbstractRoundingOperation {
//returns the singleton instance of this class
private static Floor singleton = null;
public static Floor getInstance(){
if (singleton == null) singleton = new Floor();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseFloor(this,arg);
}
//return name of builtin
public String getName(){
return "floor";
}
}
public static class Ceil extends AbstractRoundingOperation {
//returns the singleton instance of this class
private static Ceil singleton = null;
public static Ceil getInstance(){
if (singleton == null) singleton = new Ceil();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseCeil(this,arg);
}
//return name of builtin
public String getName(){
return "ceil";
}
}
public static abstract class AbstractArrayUnaryNumericFunction extends AbstractUnaryNumericFunction {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractArrayUnaryNumericFunction(this,arg);
}
}
public static abstract class ArrayUnaryArithmetic extends AbstractArrayUnaryNumericFunction {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseArrayUnaryArithmetic(this,arg);
}
}
public static abstract class AbstractBinaryNumericFunction extends AbstractProperNumericFunction implements ClassPropagationDefined {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractBinaryNumericFunction(this,arg);
}
private ClassPropTools.MC matlabClassPropInfo = null; //new ClassPropTools.MCUnion(new ClassPropTools.MCMap(new ClassPropTools.MCChain(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("logical"),new ClassPropTools.MCBuiltin("char")),new ClassPropTools.MCNum(0)),new ClassPropTools.MCError()),new ClassPropTools.MCUnion(new ClassPropTools.MCMap(new ClassPropTools.MCUnion(new ClassPropTools.MCChain(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("int8"),new ClassPropTools.MCBuiltin("uint16")),new ClassPropTools.MCBuiltin("uint32")),new ClassPropTools.MCBuiltin("uint64")),new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("int8"),new ClassPropTools.MCBuiltin("uint16")),new ClassPropTools.MCBuiltin("uint32")),new ClassPropTools.MCBuiltin("uint64"))),new ClassPropTools.MCBuiltin("logical")),new ClassPropTools.MCChain(new ClassPropTools.MCBuiltin("logical"),new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("int8"),new ClassPropTools.MCBuiltin("uint16")),new ClassPropTools.MCBuiltin("uint32")),new ClassPropTools.MCBuiltin("uint64")),new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("int8"),new ClassPropTools.MCBuiltin("uint16")),new ClassPropTools.MCBuiltin("uint32")),new ClassPropTools.MCBuiltin("uint64"))))),new ClassPropTools.MCError()),getClassPropagationInfo()));
public ClassPropTools.MC getMatlabClassPropagationInfo(){
//set classPropInfo if not defined
if (matlabClassPropInfo == null){
ClassPropTools.MC parentClassPropInfo = new ClassPropTools.MCNone();
matlabClassPropInfo = new ClassPropTools.MCUnion(new ClassPropTools.MCMap(new ClassPropTools.MCChain(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("logical"),new ClassPropTools.MCBuiltin("char")),new ClassPropTools.MCNum(0)),new ClassPropTools.MCError()),new ClassPropTools.MCUnion(new ClassPropTools.MCMap(new ClassPropTools.MCUnion(new ClassPropTools.MCChain(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("int8"),new ClassPropTools.MCBuiltin("uint16")),new ClassPropTools.MCBuiltin("uint32")),new ClassPropTools.MCBuiltin("uint64")),new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("int8"),new ClassPropTools.MCBuiltin("uint16")),new ClassPropTools.MCBuiltin("uint32")),new ClassPropTools.MCBuiltin("uint64"))),new ClassPropTools.MCBuiltin("logical")),new ClassPropTools.MCChain(new ClassPropTools.MCBuiltin("logical"),new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("int8"),new ClassPropTools.MCBuiltin("uint16")),new ClassPropTools.MCBuiltin("uint32")),new ClassPropTools.MCBuiltin("uint64")),new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("int8"),new ClassPropTools.MCBuiltin("uint16")),new ClassPropTools.MCBuiltin("uint32")),new ClassPropTools.MCBuiltin("uint64"))))),new ClassPropTools.MCError()),getClassPropagationInfo()));
}
return matlabClassPropInfo;
}
private ClassPropTools.MC classPropInfo = null; //new ClassPropTools.MCCoerce(new ClassPropTools.MCMap(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("logical"),new ClassPropTools.MCBuiltin("char")),new ClassPropTools.MCBuiltin("double")),new ClassPropTools.MCUnion(new ClassPropTools.MCMap(new ClassPropTools.MCChain(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("single"),new ClassPropTools.MCBuiltin("double")),new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("int8"),new ClassPropTools.MCBuiltin("uint16")),new ClassPropTools.MCBuiltin("uint32")),new ClassPropTools.MCBuiltin("uint64")),new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("int8"),new ClassPropTools.MCBuiltin("uint16")),new ClassPropTools.MCBuiltin("uint32")),new ClassPropTools.MCBuiltin("uint64")))),new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("double"),new ClassPropTools.MCNum(0))),new ClassPropTools.MCNum(0)),new ClassPropTools.MCMap(new ClassPropTools.MCChain(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("double"),new ClassPropTools.MCNum(1)),new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("single"),new ClassPropTools.MCBuiltin("double")),new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("int8"),new ClassPropTools.MCBuiltin("uint16")),new ClassPropTools.MCBuiltin("uint32")),new ClassPropTools.MCBuiltin("uint64")),new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("int8"),new ClassPropTools.MCBuiltin("uint16")),new ClassPropTools.MCBuiltin("uint32")),new ClassPropTools.MCBuiltin("uint64"))))),new ClassPropTools.MCNum(1))));
public ClassPropTools.MC getClassPropagationInfo(){
//set classPropInfo if not defined
if (classPropInfo == null){
ClassPropTools.MC parentClassPropInfo = new ClassPropTools.MCNone();
classPropInfo = new ClassPropTools.MCCoerce(new ClassPropTools.MCMap(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("logical"),new ClassPropTools.MCBuiltin("char")),new ClassPropTools.MCBuiltin("double")),new ClassPropTools.MCUnion(new ClassPropTools.MCMap(new ClassPropTools.MCChain(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("single"),new ClassPropTools.MCBuiltin("double")),new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("int8"),new ClassPropTools.MCBuiltin("uint16")),new ClassPropTools.MCBuiltin("uint32")),new ClassPropTools.MCBuiltin("uint64")),new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("int8"),new ClassPropTools.MCBuiltin("uint16")),new ClassPropTools.MCBuiltin("uint32")),new ClassPropTools.MCBuiltin("uint64")))),new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("double"),new ClassPropTools.MCNum(0))),new ClassPropTools.MCNum(0)),new ClassPropTools.MCMap(new ClassPropTools.MCChain(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("double"),new ClassPropTools.MCNum(1)),new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("single"),new ClassPropTools.MCBuiltin("double")),new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("int8"),new ClassPropTools.MCBuiltin("uint16")),new ClassPropTools.MCBuiltin("uint32")),new ClassPropTools.MCBuiltin("uint64")),new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("int8"),new ClassPropTools.MCBuiltin("uint16")),new ClassPropTools.MCBuiltin("uint32")),new ClassPropTools.MCBuiltin("uint64"))))),new ClassPropTools.MCNum(1))));
}
return classPropInfo;
}
}
public static abstract class AbstractElementalBinaryNumericFunction extends AbstractBinaryNumericFunction {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractElementalBinaryNumericFunction(this,arg);
}
}
public static class Complex extends AbstractElementalBinaryNumericFunction {
//returns the singleton instance of this class
private static Complex singleton = null;
public static Complex getInstance(){
if (singleton == null) singleton = new Complex();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseComplex(this,arg);
}
//return name of builtin
public String getName(){
return "complex";
}
private ClassPropTools.MC matlabClassPropInfo = null; //new ClassPropTools.MCUnion(new ClassPropTools.MCMap(new ClassPropTools.MCChain(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("char"),new ClassPropTools.MCBuiltin("logical")),new ClassPropTools.MCAny()),new ClassPropTools.MCError()),new ClassPropTools.MCUnion(new ClassPropTools.MCMap(new ClassPropTools.MCChain(new ClassPropTools.MCAny(),new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("char"),new ClassPropTools.MCBuiltin("logical"))),new ClassPropTools.MCError()),getClassPropagationInfo()));
public ClassPropTools.MC getMatlabClassPropagationInfo(){
//set classPropInfo if not defined
if (matlabClassPropInfo == null){
ClassPropTools.MC parentClassPropInfo = super.getMatlabClassPropagationInfo();
matlabClassPropInfo = new ClassPropTools.MCUnion(new ClassPropTools.MCMap(new ClassPropTools.MCChain(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("char"),new ClassPropTools.MCBuiltin("logical")),new ClassPropTools.MCAny()),new ClassPropTools.MCError()),new ClassPropTools.MCUnion(new ClassPropTools.MCMap(new ClassPropTools.MCChain(new ClassPropTools.MCAny(),new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("char"),new ClassPropTools.MCBuiltin("logical"))),new ClassPropTools.MCError()),getClassPropagationInfo()));
}
return matlabClassPropInfo;
}
}
public static abstract class AbstractElementalBinaryArithmetic extends AbstractElementalBinaryNumericFunction {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractElementalBinaryArithmetic(this,arg);
}
private ClassPropTools.MC matlabClassPropInfo = null; //new ClassPropTools.MCUnion(new ClassPropTools.MCMap(new ClassPropTools.MCChain(new ClassPropTools.MCBuiltin("logical"),new ClassPropTools.MCBuiltin("logical")),new ClassPropTools.MCBuiltin("double")),parentClassPropInfo);
public ClassPropTools.MC getMatlabClassPropagationInfo(){
//set classPropInfo if not defined
if (matlabClassPropInfo == null){
ClassPropTools.MC parentClassPropInfo = super.getMatlabClassPropagationInfo();
matlabClassPropInfo = new ClassPropTools.MCUnion(new ClassPropTools.MCMap(new ClassPropTools.MCChain(new ClassPropTools.MCBuiltin("logical"),new ClassPropTools.MCBuiltin("logical")),new ClassPropTools.MCBuiltin("double")),parentClassPropInfo);
}
return matlabClassPropInfo;
}
}
public static class Plus extends AbstractElementalBinaryArithmetic {
//returns the singleton instance of this class
private static Plus singleton = null;
public static Plus getInstance(){
if (singleton == null) singleton = new Plus();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.casePlus(this,arg);
}
//return name of builtin
public String getName(){
return "plus";
}
}
public static class Minus extends AbstractElementalBinaryArithmetic {
//returns the singleton instance of this class
private static Minus singleton = null;
public static Minus getInstance(){
if (singleton == null) singleton = new Minus();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseMinus(this,arg);
}
//return name of builtin
public String getName(){
return "minus";
}
}
public static class Times extends AbstractElementalBinaryArithmetic {
//returns the singleton instance of this class
private static Times singleton = null;
public static Times getInstance(){
if (singleton == null) singleton = new Times();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseTimes(this,arg);
}
//return name of builtin
public String getName(){
return "times";
}
}
public static class Power extends AbstractElementalBinaryArithmetic {
//returns the singleton instance of this class
private static Power singleton = null;
public static Power getInstance(){
if (singleton == null) singleton = new Power();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.casePower(this,arg);
}
//return name of builtin
public String getName(){
return "power";
}
}
public static abstract class AbstractDividingElementalArithmetic extends AbstractElementalBinaryArithmetic {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractDividingElementalArithmetic(this,arg);
}
private ClassPropTools.MC matlabClassPropInfo = null; //new ClassPropTools.MCUnion(new ClassPropTools.MCMap(new ClassPropTools.MCChain(new ClassPropTools.MCBuiltin("logical"),new ClassPropTools.MCBuiltin("logical")),new ClassPropTools.MCError()),parentClassPropInfo);
public ClassPropTools.MC getMatlabClassPropagationInfo(){
//set classPropInfo if not defined
if (matlabClassPropInfo == null){
ClassPropTools.MC parentClassPropInfo = super.getMatlabClassPropagationInfo();
matlabClassPropInfo = new ClassPropTools.MCUnion(new ClassPropTools.MCMap(new ClassPropTools.MCChain(new ClassPropTools.MCBuiltin("logical"),new ClassPropTools.MCBuiltin("logical")),new ClassPropTools.MCError()),parentClassPropInfo);
}
return matlabClassPropInfo;
}
}
public static class Ldivide extends AbstractDividingElementalArithmetic {
//returns the singleton instance of this class
private static Ldivide singleton = null;
public static Ldivide getInstance(){
if (singleton == null) singleton = new Ldivide();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseLdivide(this,arg);
}
//return name of builtin
public String getName(){
return "ldivide";
}
}
public static class Rdivide extends AbstractDividingElementalArithmetic {
//returns the singleton instance of this class
private static Rdivide singleton = null;
public static Rdivide getInstance(){
if (singleton == null) singleton = new Rdivide();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseRdivide(this,arg);
}
//return name of builtin
public String getName(){
return "rdivide";
}
}
public static class Mod extends AbstractDividingElementalArithmetic {
//returns the singleton instance of this class
private static Mod singleton = null;
public static Mod getInstance(){
if (singleton == null) singleton = new Mod();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseMod(this,arg);
}
//return name of builtin
public String getName(){
return "mod";
}
}
public static class Rem extends AbstractDividingElementalArithmetic {
//returns the singleton instance of this class
private static Rem singleton = null;
public static Rem getInstance(){
if (singleton == null) singleton = new Rem();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseRem(this,arg);
}
//return name of builtin
public String getName(){
return "rem";
}
}
public static abstract class AbstractArrayBinaryNumericFunction extends AbstractBinaryNumericFunction {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractArrayBinaryNumericFunction(this,arg);
}
}
public static class Dot extends AbstractArrayBinaryNumericFunction {
//returns the singleton instance of this class
private static Dot singleton = null;
public static Dot getInstance(){
if (singleton == null) singleton = new Dot();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseDot(this,arg);
}
//return name of builtin
public String getName(){
return "dot";
}
private ClassPropTools.MC matlabClassPropInfo = null; //new ClassPropTools.MCUnion(new ClassPropTools.MCMap(new ClassPropTools.MCChain(new ClassPropTools.MCBuiltin("logical"),new ClassPropTools.MCAny()),new ClassPropTools.MCError()),getClassPropagationInfo());
public ClassPropTools.MC getMatlabClassPropagationInfo(){
//set classPropInfo if not defined
if (matlabClassPropInfo == null){
ClassPropTools.MC parentClassPropInfo = super.getMatlabClassPropagationInfo();
matlabClassPropInfo = new ClassPropTools.MCUnion(new ClassPropTools.MCMap(new ClassPropTools.MCChain(new ClassPropTools.MCBuiltin("logical"),new ClassPropTools.MCAny()),new ClassPropTools.MCError()),getClassPropagationInfo());
}
return matlabClassPropInfo;
}
}
public static class Cross extends AbstractArrayBinaryNumericFunction {
//returns the singleton instance of this class
private static Cross singleton = null;
public static Cross getInstance(){
if (singleton == null) singleton = new Cross();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseCross(this,arg);
}
//return name of builtin
public String getName(){
return "cross";
}
}
public static abstract class AbstractArrayBinaryArithmetic extends AbstractArrayBinaryNumericFunction {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractArrayBinaryArithmetic(this,arg);
}
}
public static class Mtimes extends AbstractArrayBinaryArithmetic {
//returns the singleton instance of this class
private static Mtimes singleton = null;
public static Mtimes getInstance(){
if (singleton == null) singleton = new Mtimes();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseMtimes(this,arg);
}
//return name of builtin
public String getName(){
return "mtimes";
}
private ClassPropTools.MC matlabClassPropInfo = null; //new ClassPropTools.MCUnion(new ClassPropTools.MCMap(new ClassPropTools.MCChain(new ClassPropTools.MCBuiltin("logical"),new ClassPropTools.MCBuiltin("logical")),new ClassPropTools.MCBuiltin("double")),parentClassPropInfo);
public ClassPropTools.MC getMatlabClassPropagationInfo(){
//set classPropInfo if not defined
if (matlabClassPropInfo == null){
ClassPropTools.MC parentClassPropInfo = super.getMatlabClassPropagationInfo();
matlabClassPropInfo = new ClassPropTools.MCUnion(new ClassPropTools.MCMap(new ClassPropTools.MCChain(new ClassPropTools.MCBuiltin("logical"),new ClassPropTools.MCBuiltin("logical")),new ClassPropTools.MCBuiltin("double")),parentClassPropInfo);
}
return matlabClassPropInfo;
}
}
public static class Mpower extends AbstractArrayBinaryArithmetic {
//returns the singleton instance of this class
private static Mpower singleton = null;
public static Mpower getInstance(){
if (singleton == null) singleton = new Mpower();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseMpower(this,arg);
}
//return name of builtin
public String getName(){
return "mpower";
}
}
public static abstract class AbstractDividingArrayArithmetic extends AbstractArrayBinaryArithmetic {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractDividingArrayArithmetic(this,arg);
}
}
public static class Mldivide extends AbstractDividingArrayArithmetic {
//returns the singleton instance of this class
private static Mldivide singleton = null;
public static Mldivide getInstance(){
if (singleton == null) singleton = new Mldivide();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseMldivide(this,arg);
}
//return name of builtin
public String getName(){
return "mldivide";
}
}
public static class Mrdivide extends AbstractDividingArrayArithmetic {
//returns the singleton instance of this class
private static Mrdivide singleton = null;
public static Mrdivide getInstance(){
if (singleton == null) singleton = new Mrdivide();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseMrdivide(this,arg);
}
//return name of builtin
public String getName(){
return "mrdivide";
}
}
public static abstract class AbstractImproperNumericFunction extends AbstractNumericFunction {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractImproperNumericFunction(this,arg);
}
}
public static abstract class AbstractDimensionSensitiveNumericFunction extends AbstractImproperNumericFunction {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractDimensionSensitiveNumericFunction(this,arg);
}
}
public static abstract class AbstractDimensionCollapsingNumericFunction extends AbstractDimensionSensitiveNumericFunction {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractDimensionCollapsingNumericFunction(this,arg);
}
}
public static class Min extends AbstractDimensionCollapsingNumericFunction {
//returns the singleton instance of this class
private static Min singleton = null;
public static Min getInstance(){
if (singleton == null) singleton = new Min();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseMin(this,arg);
}
//return name of builtin
public String getName(){
return "min";
}
}
public static class Max extends AbstractDimensionCollapsingNumericFunction {
//returns the singleton instance of this class
private static Max singleton = null;
public static Max getInstance(){
if (singleton == null) singleton = new Max();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseMax(this,arg);
}
//return name of builtin
public String getName(){
return "max";
}
}
public static class Median extends AbstractDimensionCollapsingNumericFunction {
//returns the singleton instance of this class
private static Median singleton = null;
public static Median getInstance(){
if (singleton == null) singleton = new Median();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseMedian(this,arg);
}
//return name of builtin
public String getName(){
return "median";
}
}
public static abstract class AbstractFloatFunction extends AbstractMatrixFunction {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractFloatFunction(this,arg);
}
}
public static abstract class AbstractProperFloatFunction extends AbstractFloatFunction {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractProperFloatFunction(this,arg);
}
}
public static abstract class AbstractUnaryFloatFunction extends AbstractProperFloatFunction implements ClassPropagationDefined {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractUnaryFloatFunction(this,arg);
}
public ClassPropTools.MC getMatlabClassPropagationInfo(){{
return getClassPropagationInfo();
}}
private ClassPropTools.MC classPropInfo = null; //new ClassPropTools.MCMap(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("single"),new ClassPropTools.MCBuiltin("double")),new ClassPropTools.MCNum(0));
public ClassPropTools.MC getClassPropagationInfo(){
//set classPropInfo if not defined
if (classPropInfo == null){
ClassPropTools.MC parentClassPropInfo = new ClassPropTools.MCNone();
classPropInfo = new ClassPropTools.MCMap(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("single"),new ClassPropTools.MCBuiltin("double")),new ClassPropTools.MCNum(0));
}
return classPropInfo;
}
}
public static abstract class AbstractElementalUnaryFloatFunction extends AbstractUnaryFloatFunction {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractElementalUnaryFloatFunction(this,arg);
}
}
public static class Sqrt extends AbstractElementalUnaryFloatFunction {
//returns the singleton instance of this class
private static Sqrt singleton = null;
public static Sqrt getInstance(){
if (singleton == null) singleton = new Sqrt();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseSqrt(this,arg);
}
//return name of builtin
public String getName(){
return "sqrt";
}
}
public static class Realsqrt extends AbstractElementalUnaryFloatFunction {
//returns the singleton instance of this class
private static Realsqrt singleton = null;
public static Realsqrt getInstance(){
if (singleton == null) singleton = new Realsqrt();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseRealsqrt(this,arg);
}
//return name of builtin
public String getName(){
return "realsqrt";
}
}
public static class Erf extends AbstractElementalUnaryFloatFunction {
//returns the singleton instance of this class
private static Erf singleton = null;
public static Erf getInstance(){
if (singleton == null) singleton = new Erf();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseErf(this,arg);
}
//return name of builtin
public String getName(){
return "erf";
}
}
public static class Erfinv extends AbstractElementalUnaryFloatFunction {
//returns the singleton instance of this class
private static Erfinv singleton = null;
public static Erfinv getInstance(){
if (singleton == null) singleton = new Erfinv();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseErfinv(this,arg);
}
//return name of builtin
public String getName(){
return "erfinv";
}
}
public static class Erfc extends AbstractElementalUnaryFloatFunction {
//returns the singleton instance of this class
private static Erfc singleton = null;
public static Erfc getInstance(){
if (singleton == null) singleton = new Erfc();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseErfc(this,arg);
}
//return name of builtin
public String getName(){
return "erfc";
}
}
public static class Erfcinv extends AbstractElementalUnaryFloatFunction {
//returns the singleton instance of this class
private static Erfcinv singleton = null;
public static Erfcinv getInstance(){
if (singleton == null) singleton = new Erfcinv();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseErfcinv(this,arg);
}
//return name of builtin
public String getName(){
return "erfcinv";
}
}
public static class Gamma extends AbstractElementalUnaryFloatFunction {
//returns the singleton instance of this class
private static Gamma singleton = null;
public static Gamma getInstance(){
if (singleton == null) singleton = new Gamma();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseGamma(this,arg);
}
//return name of builtin
public String getName(){
return "gamma";
}
}
public static class Gammainc extends AbstractElementalUnaryFloatFunction {
//returns the singleton instance of this class
private static Gammainc singleton = null;
public static Gammainc getInstance(){
if (singleton == null) singleton = new Gammainc();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseGammainc(this,arg);
}
//return name of builtin
public String getName(){
return "gammainc";
}
}
public static class Betainc extends AbstractElementalUnaryFloatFunction {
//returns the singleton instance of this class
private static Betainc singleton = null;
public static Betainc getInstance(){
if (singleton == null) singleton = new Betainc();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseBetainc(this,arg);
}
//return name of builtin
public String getName(){
return "betainc";
}
}
public static class Gammaln extends AbstractElementalUnaryFloatFunction {
//returns the singleton instance of this class
private static Gammaln singleton = null;
public static Gammaln getInstance(){
if (singleton == null) singleton = new Gammaln();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseGammaln(this,arg);
}
//return name of builtin
public String getName(){
return "gammaln";
}
}
public static class Exp extends AbstractElementalUnaryFloatFunction {
//returns the singleton instance of this class
private static Exp singleton = null;
public static Exp getInstance(){
if (singleton == null) singleton = new Exp();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseExp(this,arg);
}
//return name of builtin
public String getName(){
return "exp";
}
}
public static class Log extends AbstractElementalUnaryFloatFunction {
//returns the singleton instance of this class
private static Log singleton = null;
public static Log getInstance(){
if (singleton == null) singleton = new Log();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseLog(this,arg);
}
//return name of builtin
public String getName(){
return "log";
}
}
public static class Log2 extends AbstractElementalUnaryFloatFunction {
//returns the singleton instance of this class
private static Log2 singleton = null;
public static Log2 getInstance(){
if (singleton == null) singleton = new Log2();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseLog2(this,arg);
}
//return name of builtin
public String getName(){
return "log2";
}
}
public static class Log10 extends AbstractElementalUnaryFloatFunction {
//returns the singleton instance of this class
private static Log10 singleton = null;
public static Log10 getInstance(){
if (singleton == null) singleton = new Log10();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseLog10(this,arg);
}
//return name of builtin
public String getName(){
return "log10";
}
}
public static abstract class AbstractForwardTrigonometricFunction extends AbstractElementalUnaryFloatFunction {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractForwardTrigonometricFunction(this,arg);
}
}
public static abstract class AbstractRadianTrigonometricFunction extends AbstractForwardTrigonometricFunction {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractRadianTrigonometricFunction(this,arg);
}
}
public static class Sin extends AbstractRadianTrigonometricFunction {
//returns the singleton instance of this class
private static Sin singleton = null;
public static Sin getInstance(){
if (singleton == null) singleton = new Sin();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseSin(this,arg);
}
//return name of builtin
public String getName(){
return "sin";
}
}
public static class Cos extends AbstractRadianTrigonometricFunction {
//returns the singleton instance of this class
private static Cos singleton = null;
public static Cos getInstance(){
if (singleton == null) singleton = new Cos();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseCos(this,arg);
}
//return name of builtin
public String getName(){
return "cos";
}
}
public static class Tan extends AbstractRadianTrigonometricFunction {
//returns the singleton instance of this class
private static Tan singleton = null;
public static Tan getInstance(){
if (singleton == null) singleton = new Tan();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseTan(this,arg);
}
//return name of builtin
public String getName(){
return "tan";
}
}
public static class Cot extends AbstractRadianTrigonometricFunction {
//returns the singleton instance of this class
private static Cot singleton = null;
public static Cot getInstance(){
if (singleton == null) singleton = new Cot();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseCot(this,arg);
}
//return name of builtin
public String getName(){
return "cot";
}
}
public static class Sec extends AbstractRadianTrigonometricFunction {
//returns the singleton instance of this class
private static Sec singleton = null;
public static Sec getInstance(){
if (singleton == null) singleton = new Sec();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseSec(this,arg);
}
//return name of builtin
public String getName(){
return "sec";
}
}
public static class Csc extends AbstractRadianTrigonometricFunction {
//returns the singleton instance of this class
private static Csc singleton = null;
public static Csc getInstance(){
if (singleton == null) singleton = new Csc();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseCsc(this,arg);
}
//return name of builtin
public String getName(){
return "csc";
}
}
public static abstract class AbstractDegreeTrigonometricFunction extends AbstractForwardTrigonometricFunction {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractDegreeTrigonometricFunction(this,arg);
}
}
public static class Sind extends AbstractDegreeTrigonometricFunction {
//returns the singleton instance of this class
private static Sind singleton = null;
public static Sind getInstance(){
if (singleton == null) singleton = new Sind();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseSind(this,arg);
}
//return name of builtin
public String getName(){
return "sind";
}
}
public static class Cosd extends AbstractDegreeTrigonometricFunction {
//returns the singleton instance of this class
private static Cosd singleton = null;
public static Cosd getInstance(){
if (singleton == null) singleton = new Cosd();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseCosd(this,arg);
}
//return name of builtin
public String getName(){
return "cosd";
}
}
public static class Tand extends AbstractDegreeTrigonometricFunction {
//returns the singleton instance of this class
private static Tand singleton = null;
public static Tand getInstance(){
if (singleton == null) singleton = new Tand();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseTand(this,arg);
}
//return name of builtin
public String getName(){
return "tand";
}
}
public static class Cotd extends AbstractDegreeTrigonometricFunction {
//returns the singleton instance of this class
private static Cotd singleton = null;
public static Cotd getInstance(){
if (singleton == null) singleton = new Cotd();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseCotd(this,arg);
}
//return name of builtin
public String getName(){
return "cotd";
}
}
public static class Secd extends AbstractDegreeTrigonometricFunction {
//returns the singleton instance of this class
private static Secd singleton = null;
public static Secd getInstance(){
if (singleton == null) singleton = new Secd();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseSecd(this,arg);
}
//return name of builtin
public String getName(){
return "secd";
}
}
public static class Cscd extends AbstractDegreeTrigonometricFunction {
//returns the singleton instance of this class
private static Cscd singleton = null;
public static Cscd getInstance(){
if (singleton == null) singleton = new Cscd();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseCscd(this,arg);
}
//return name of builtin
public String getName(){
return "cscd";
}
}
public static abstract class AbstractHyperbolicTrigonometricFunction extends AbstractForwardTrigonometricFunction {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractHyperbolicTrigonometricFunction(this,arg);
}
}
public static class Sinh extends AbstractHyperbolicTrigonometricFunction {
//returns the singleton instance of this class
private static Sinh singleton = null;
public static Sinh getInstance(){
if (singleton == null) singleton = new Sinh();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseSinh(this,arg);
}
//return name of builtin
public String getName(){
return "sinh";
}
}
public static class Cosh extends AbstractHyperbolicTrigonometricFunction {
//returns the singleton instance of this class
private static Cosh singleton = null;
public static Cosh getInstance(){
if (singleton == null) singleton = new Cosh();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseCosh(this,arg);
}
//return name of builtin
public String getName(){
return "cosh";
}
}
public static class Tanh extends AbstractHyperbolicTrigonometricFunction {
//returns the singleton instance of this class
private static Tanh singleton = null;
public static Tanh getInstance(){
if (singleton == null) singleton = new Tanh();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseTanh(this,arg);
}
//return name of builtin
public String getName(){
return "tanh";
}
}
public static class Coth extends AbstractHyperbolicTrigonometricFunction {
//returns the singleton instance of this class
private static Coth singleton = null;
public static Coth getInstance(){
if (singleton == null) singleton = new Coth();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseCoth(this,arg);
}
//return name of builtin
public String getName(){
return "coth";
}
}
public static class Sech extends AbstractHyperbolicTrigonometricFunction {
//returns the singleton instance of this class
private static Sech singleton = null;
public static Sech getInstance(){
if (singleton == null) singleton = new Sech();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseSech(this,arg);
}
//return name of builtin
public String getName(){
return "sech";
}
}
public static class Csch extends AbstractHyperbolicTrigonometricFunction {
//returns the singleton instance of this class
private static Csch singleton = null;
public static Csch getInstance(){
if (singleton == null) singleton = new Csch();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseCsch(this,arg);
}
//return name of builtin
public String getName(){
return "csch";
}
}
public static abstract class AbstractInverseTrigonmetricFunction extends AbstractElementalUnaryFloatFunction {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractInverseTrigonmetricFunction(this,arg);
}
}
public static abstract class AbstractRadianInverseTrigonmetricFunction extends AbstractInverseTrigonmetricFunction {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractRadianInverseTrigonmetricFunction(this,arg);
}
}
public static class Asin extends AbstractRadianInverseTrigonmetricFunction {
//returns the singleton instance of this class
private static Asin singleton = null;
public static Asin getInstance(){
if (singleton == null) singleton = new Asin();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAsin(this,arg);
}
//return name of builtin
public String getName(){
return "asin";
}
}
public static class Acos extends AbstractRadianInverseTrigonmetricFunction {
//returns the singleton instance of this class
private static Acos singleton = null;
public static Acos getInstance(){
if (singleton == null) singleton = new Acos();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAcos(this,arg);
}
//return name of builtin
public String getName(){
return "acos";
}
}
public static class Atan extends AbstractRadianInverseTrigonmetricFunction {
//returns the singleton instance of this class
private static Atan singleton = null;
public static Atan getInstance(){
if (singleton == null) singleton = new Atan();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAtan(this,arg);
}
//return name of builtin
public String getName(){
return "atan";
}
}
public static class Atan2 extends AbstractRadianInverseTrigonmetricFunction {
//returns the singleton instance of this class
private static Atan2 singleton = null;
public static Atan2 getInstance(){
if (singleton == null) singleton = new Atan2();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAtan2(this,arg);
}
//return name of builtin
public String getName(){
return "atan2";
}
}
public static class Acot extends AbstractRadianInverseTrigonmetricFunction {
//returns the singleton instance of this class
private static Acot singleton = null;
public static Acot getInstance(){
if (singleton == null) singleton = new Acot();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAcot(this,arg);
}
//return name of builtin
public String getName(){
return "acot";
}
}
public static class Asec extends AbstractRadianInverseTrigonmetricFunction {
//returns the singleton instance of this class
private static Asec singleton = null;
public static Asec getInstance(){
if (singleton == null) singleton = new Asec();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAsec(this,arg);
}
//return name of builtin
public String getName(){
return "asec";
}
}
public static class Acsc extends AbstractRadianInverseTrigonmetricFunction {
//returns the singleton instance of this class
private static Acsc singleton = null;
public static Acsc getInstance(){
if (singleton == null) singleton = new Acsc();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAcsc(this,arg);
}
//return name of builtin
public String getName(){
return "acsc";
}
}
public static abstract class AbstractDegreeInverseTrigonmetricFunction extends AbstractInverseTrigonmetricFunction {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractDegreeInverseTrigonmetricFunction(this,arg);
}
}
public static class Asind extends AbstractDegreeInverseTrigonmetricFunction {
//returns the singleton instance of this class
private static Asind singleton = null;
public static Asind getInstance(){
if (singleton == null) singleton = new Asind();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAsind(this,arg);
}
//return name of builtin
public String getName(){
return "asind";
}
}
public static class Acosd extends AbstractDegreeInverseTrigonmetricFunction {
//returns the singleton instance of this class
private static Acosd singleton = null;
public static Acosd getInstance(){
if (singleton == null) singleton = new Acosd();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAcosd(this,arg);
}
//return name of builtin
public String getName(){
return "acosd";
}
}
public static class Atand extends AbstractDegreeInverseTrigonmetricFunction {
//returns the singleton instance of this class
private static Atand singleton = null;
public static Atand getInstance(){
if (singleton == null) singleton = new Atand();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAtand(this,arg);
}
//return name of builtin
public String getName(){
return "atand";
}
}
public static class Acotd extends AbstractDegreeInverseTrigonmetricFunction {
//returns the singleton instance of this class
private static Acotd singleton = null;
public static Acotd getInstance(){
if (singleton == null) singleton = new Acotd();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAcotd(this,arg);
}
//return name of builtin
public String getName(){
return "acotd";
}
}
public static class Asecd extends AbstractDegreeInverseTrigonmetricFunction {
//returns the singleton instance of this class
private static Asecd singleton = null;
public static Asecd getInstance(){
if (singleton == null) singleton = new Asecd();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAsecd(this,arg);
}
//return name of builtin
public String getName(){
return "asecd";
}
}
public static class Acscd extends AbstractDegreeInverseTrigonmetricFunction {
//returns the singleton instance of this class
private static Acscd singleton = null;
public static Acscd getInstance(){
if (singleton == null) singleton = new Acscd();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAcscd(this,arg);
}
//return name of builtin
public String getName(){
return "acscd";
}
}
public static abstract class AbstractHyperbolicInverseTrigonmetricFunction extends AbstractInverseTrigonmetricFunction {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractHyperbolicInverseTrigonmetricFunction(this,arg);
}
}
public static class Asinh extends AbstractHyperbolicInverseTrigonmetricFunction {
//returns the singleton instance of this class
private static Asinh singleton = null;
public static Asinh getInstance(){
if (singleton == null) singleton = new Asinh();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAsinh(this,arg);
}
//return name of builtin
public String getName(){
return "asinh";
}
}
public static class Acosh extends AbstractHyperbolicInverseTrigonmetricFunction {
//returns the singleton instance of this class
private static Acosh singleton = null;
public static Acosh getInstance(){
if (singleton == null) singleton = new Acosh();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAcosh(this,arg);
}
//return name of builtin
public String getName(){
return "acosh";
}
}
public static class Atanh extends AbstractHyperbolicInverseTrigonmetricFunction {
//returns the singleton instance of this class
private static Atanh singleton = null;
public static Atanh getInstance(){
if (singleton == null) singleton = new Atanh();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAtanh(this,arg);
}
//return name of builtin
public String getName(){
return "atanh";
}
}
public static class Acoth extends AbstractHyperbolicInverseTrigonmetricFunction {
//returns the singleton instance of this class
private static Acoth singleton = null;
public static Acoth getInstance(){
if (singleton == null) singleton = new Acoth();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAcoth(this,arg);
}
//return name of builtin
public String getName(){
return "acoth";
}
}
public static class Asech extends AbstractHyperbolicInverseTrigonmetricFunction {
//returns the singleton instance of this class
private static Asech singleton = null;
public static Asech getInstance(){
if (singleton == null) singleton = new Asech();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAsech(this,arg);
}
//return name of builtin
public String getName(){
return "asech";
}
}
public static class Acsch extends AbstractHyperbolicInverseTrigonmetricFunction {
//returns the singleton instance of this class
private static Acsch singleton = null;
public static Acsch getInstance(){
if (singleton == null) singleton = new Acsch();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAcsch(this,arg);
}
//return name of builtin
public String getName(){
return "acsch";
}
}
public static abstract class AbstractArrayUnaryFloatFunction extends AbstractUnaryFloatFunction {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractArrayUnaryFloatFunction(this,arg);
}
}
public static abstract class AbstractSquareArrayUnaryFloatFunction extends AbstractArrayUnaryFloatFunction {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractSquareArrayUnaryFloatFunction(this,arg);
}
}
public static class Logm extends AbstractSquareArrayUnaryFloatFunction {
//returns the singleton instance of this class
private static Logm singleton = null;
public static Logm getInstance(){
if (singleton == null) singleton = new Logm();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseLogm(this,arg);
}
//return name of builtin
public String getName(){
return "logm";
}
}
public static class Sqrtm extends AbstractSquareArrayUnaryFloatFunction {
//returns the singleton instance of this class
private static Sqrtm singleton = null;
public static Sqrtm getInstance(){
if (singleton == null) singleton = new Sqrtm();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseSqrtm(this,arg);
}
//return name of builtin
public String getName(){
return "sqrtm";
}
}
public static class Expm extends AbstractSquareArrayUnaryFloatFunction {
//returns the singleton instance of this class
private static Expm singleton = null;
public static Expm getInstance(){
if (singleton == null) singleton = new Expm();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseExpm(this,arg);
}
//return name of builtin
public String getName(){
return "expm";
}
}
public static class Inv extends AbstractSquareArrayUnaryFloatFunction {
//returns the singleton instance of this class
private static Inv singleton = null;
public static Inv getInstance(){
if (singleton == null) singleton = new Inv();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseInv(this,arg);
}
//return name of builtin
public String getName(){
return "inv";
}
}
public static abstract class AbstractBinaryFloatFunction extends AbstractProperFloatFunction {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractBinaryFloatFunction(this,arg);
}
}
public static abstract class AbstractArrayBinaryFloatFunction extends AbstractBinaryFloatFunction implements ClassPropagationDefined {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractArrayBinaryFloatFunction(this,arg);
}
public ClassPropTools.MC getMatlabClassPropagationInfo(){{
return getClassPropagationInfo();
}}
private ClassPropTools.MC classPropInfo = null; //new ClassPropTools.MCUnion(new ClassPropTools.MCMap(new ClassPropTools.MCChain(new ClassPropTools.MCBuiltin("single"),new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("single"),new ClassPropTools.MCBuiltin("double"))),new ClassPropTools.MCNum(0)),new ClassPropTools.MCMap(new ClassPropTools.MCChain(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("single"),new ClassPropTools.MCBuiltin("double")),new ClassPropTools.MCBuiltin("single")),new ClassPropTools.MCNum(1)));
public ClassPropTools.MC getClassPropagationInfo(){
//set classPropInfo if not defined
if (classPropInfo == null){
ClassPropTools.MC parentClassPropInfo = new ClassPropTools.MCNone();
classPropInfo = new ClassPropTools.MCUnion(new ClassPropTools.MCMap(new ClassPropTools.MCChain(new ClassPropTools.MCBuiltin("single"),new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("single"),new ClassPropTools.MCBuiltin("double"))),new ClassPropTools.MCNum(0)),new ClassPropTools.MCMap(new ClassPropTools.MCChain(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("single"),new ClassPropTools.MCBuiltin("double")),new ClassPropTools.MCBuiltin("single")),new ClassPropTools.MCNum(1)));
}
return classPropInfo;
}
}
public static class Hypot extends AbstractArrayBinaryFloatFunction {
//returns the singleton instance of this class
private static Hypot singleton = null;
public static Hypot getInstance(){
if (singleton == null) singleton = new Hypot();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseHypot(this,arg);
}
//return name of builtin
public String getName(){
return "hypot";
}
}
public static abstract class AbstractImproperFloatFunction extends AbstractFloatFunction {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractImproperFloatFunction(this,arg);
}
}
public static class Eps extends AbstractImproperFloatFunction {
//returns the singleton instance of this class
private static Eps singleton = null;
public static Eps getInstance(){
if (singleton == null) singleton = new Eps();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseEps(this,arg);
}
//return name of builtin
public String getName(){
return "eps";
}
}
public static abstract class AbstractDimensionSensitiveFloatFunction extends AbstractImproperFloatFunction {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractDimensionSensitiveFloatFunction(this,arg);
}
}
public static class Cumsum extends AbstractDimensionSensitiveFloatFunction {
//returns the singleton instance of this class
private static Cumsum singleton = null;
public static Cumsum getInstance(){
if (singleton == null) singleton = new Cumsum();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseCumsum(this,arg);
}
//return name of builtin
public String getName(){
return "cumsum";
}
}
public static class Cumprod extends AbstractDimensionSensitiveFloatFunction {
//returns the singleton instance of this class
private static Cumprod singleton = null;
public static Cumprod getInstance(){
if (singleton == null) singleton = new Cumprod();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseCumprod(this,arg);
}
//return name of builtin
public String getName(){
return "cumprod";
}
}
public static abstract class AbstractDimensionCollapsingFloatFunction extends AbstractDimensionSensitiveFloatFunction {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractDimensionCollapsingFloatFunction(this,arg);
}
}
public static class Mode extends AbstractDimensionCollapsingFloatFunction {
//returns the singleton instance of this class
private static Mode singleton = null;
public static Mode getInstance(){
if (singleton == null) singleton = new Mode();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseMode(this,arg);
}
//return name of builtin
public String getName(){
return "mode";
}
}
public static class Prod extends AbstractDimensionCollapsingFloatFunction {
//returns the singleton instance of this class
private static Prod singleton = null;
public static Prod getInstance(){
if (singleton == null) singleton = new Prod();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseProd(this,arg);
}
//return name of builtin
public String getName(){
return "prod";
}
}
public static class Sum extends AbstractDimensionCollapsingFloatFunction {
//returns the singleton instance of this class
private static Sum singleton = null;
public static Sum getInstance(){
if (singleton == null) singleton = new Sum();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseSum(this,arg);
}
//return name of builtin
public String getName(){
return "sum";
}
}
public static class Mean extends AbstractDimensionCollapsingFloatFunction {
//returns the singleton instance of this class
private static Mean singleton = null;
public static Mean getInstance(){
if (singleton == null) singleton = new Mean();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseMean(this,arg);
}
//return name of builtin
public String getName(){
return "mean";
}
}
public static abstract class AbstractMatrixLibaryFunction extends AbstractImproperFloatFunction {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractMatrixLibaryFunction(this,arg);
}
}
public static class Eig extends AbstractMatrixLibaryFunction {
//returns the singleton instance of this class
private static Eig singleton = null;
public static Eig getInstance(){
if (singleton == null) singleton = new Eig();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseEig(this,arg);
}
//return name of builtin
public String getName(){
return "eig";
}
}
public static class Norm extends AbstractMatrixLibaryFunction {
//returns the singleton instance of this class
private static Norm singleton = null;
public static Norm getInstance(){
if (singleton == null) singleton = new Norm();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseNorm(this,arg);
}
//return name of builtin
public String getName(){
return "norm";
}
}
public static class Rank extends AbstractMatrixLibaryFunction {
//returns the singleton instance of this class
private static Rank singleton = null;
public static Rank getInstance(){
if (singleton == null) singleton = new Rank();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseRank(this,arg);
}
//return name of builtin
public String getName(){
return "rank";
}
}
public static class Cond extends AbstractMatrixLibaryFunction {
//returns the singleton instance of this class
private static Cond singleton = null;
public static Cond getInstance(){
if (singleton == null) singleton = new Cond();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseCond(this,arg);
}
//return name of builtin
public String getName(){
return "cond";
}
}
public static class Det extends AbstractMatrixLibaryFunction {
//returns the singleton instance of this class
private static Det singleton = null;
public static Det getInstance(){
if (singleton == null) singleton = new Det();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseDet(this,arg);
}
//return name of builtin
public String getName(){
return "det";
}
}
public static class Rcond extends AbstractMatrixLibaryFunction {
//returns the singleton instance of this class
private static Rcond singleton = null;
public static Rcond getInstance(){
if (singleton == null) singleton = new Rcond();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseRcond(this,arg);
}
//return name of builtin
public String getName(){
return "rcond";
}
}
public static class Linsolve extends AbstractMatrixLibaryFunction {
//returns the singleton instance of this class
private static Linsolve singleton = null;
public static Linsolve getInstance(){
if (singleton == null) singleton = new Linsolve();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseLinsolve(this,arg);
}
//return name of builtin
public String getName(){
return "linsolve";
}
}
public static abstract class AbstractFacotorizationFunction extends AbstractImproperFloatFunction {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractFacotorizationFunction(this,arg);
}
}
public static class Schur extends AbstractFacotorizationFunction {
//returns the singleton instance of this class
private static Schur singleton = null;
public static Schur getInstance(){
if (singleton == null) singleton = new Schur();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseSchur(this,arg);
}
//return name of builtin
public String getName(){
return "schur";
}
}
public static class Ordschur extends AbstractFacotorizationFunction {
//returns the singleton instance of this class
private static Ordschur singleton = null;
public static Ordschur getInstance(){
if (singleton == null) singleton = new Ordschur();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseOrdschur(this,arg);
}
//return name of builtin
public String getName(){
return "ordschur";
}
}
public static class Lu extends AbstractFacotorizationFunction {
//returns the singleton instance of this class
private static Lu singleton = null;
public static Lu getInstance(){
if (singleton == null) singleton = new Lu();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseLu(this,arg);
}
//return name of builtin
public String getName(){
return "lu";
}
}
public static class Chol extends AbstractFacotorizationFunction {
//returns the singleton instance of this class
private static Chol singleton = null;
public static Chol getInstance(){
if (singleton == null) singleton = new Chol();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseChol(this,arg);
}
//return name of builtin
public String getName(){
return "chol";
}
}
public static class Svd extends AbstractFacotorizationFunction {
//returns the singleton instance of this class
private static Svd singleton = null;
public static Svd getInstance(){
if (singleton == null) singleton = new Svd();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseSvd(this,arg);
}
//return name of builtin
public String getName(){
return "svd";
}
}
public static class Qr extends AbstractFacotorizationFunction {
//returns the singleton instance of this class
private static Qr singleton = null;
public static Qr getInstance(){
if (singleton == null) singleton = new Qr();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseQr(this,arg);
}
//return name of builtin
public String getName(){
return "qr";
}
}
public static abstract class AbstractBitFunction extends AbstractMatrixFunction {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractBitFunction(this,arg);
}
}
public static abstract class AbstractProperBitFunction extends AbstractBitFunction {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractProperBitFunction(this,arg);
}
}
public static class Bitand extends AbstractProperBitFunction {
//returns the singleton instance of this class
private static Bitand singleton = null;
public static Bitand getInstance(){
if (singleton == null) singleton = new Bitand();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseBitand(this,arg);
}
//return name of builtin
public String getName(){
return "bitand";
}
}
public static class Bitor extends AbstractProperBitFunction {
//returns the singleton instance of this class
private static Bitor singleton = null;
public static Bitor getInstance(){
if (singleton == null) singleton = new Bitor();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseBitor(this,arg);
}
//return name of builtin
public String getName(){
return "bitor";
}
}
public static class Bitxor extends AbstractProperBitFunction {
//returns the singleton instance of this class
private static Bitxor singleton = null;
public static Bitxor getInstance(){
if (singleton == null) singleton = new Bitxor();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseBitxor(this,arg);
}
//return name of builtin
public String getName(){
return "bitxor";
}
}
public static abstract class AbstractImproperBitFunciton extends AbstractBitFunction {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractImproperBitFunciton(this,arg);
}
}
public static class Bitcmp extends AbstractImproperBitFunciton {
//returns the singleton instance of this class
private static Bitcmp singleton = null;
public static Bitcmp getInstance(){
if (singleton == null) singleton = new Bitcmp();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseBitcmp(this,arg);
}
//return name of builtin
public String getName(){
return "bitcmp";
}
}
public static class Bitset extends AbstractImproperBitFunciton {
//returns the singleton instance of this class
private static Bitset singleton = null;
public static Bitset getInstance(){
if (singleton == null) singleton = new Bitset();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseBitset(this,arg);
}
//return name of builtin
public String getName(){
return "bitset";
}
}
public static class Bitget extends AbstractImproperBitFunciton {
//returns the singleton instance of this class
private static Bitget singleton = null;
public static Bitget getInstance(){
if (singleton == null) singleton = new Bitget();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseBitget(this,arg);
}
//return name of builtin
public String getName(){
return "bitget";
}
}
public static class Bitshift extends AbstractImproperBitFunciton {
//returns the singleton instance of this class
private static Bitshift singleton = null;
public static Bitshift getInstance(){
if (singleton == null) singleton = new Bitshift();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseBitshift(this,arg);
}
//return name of builtin
public String getName(){
return "bitshift";
}
}
public static abstract class AbstractMatrixQuery extends AbstractMatrixFunction {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractMatrixQuery(this,arg);
}
}
public static abstract class AbstractToDoubleMatrixQuery extends AbstractMatrixQuery {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractToDoubleMatrixQuery(this,arg);
}
}
public static class Find extends AbstractToDoubleMatrixQuery {
//returns the singleton instance of this class
private static Find singleton = null;
public static Find getInstance(){
if (singleton == null) singleton = new Find();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseFind(this,arg);
}
//return name of builtin
public String getName(){
return "find";
}
}
public static abstract class AbstractToScalarDoubleMatrixQuery extends AbstractToDoubleMatrixQuery {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractToScalarDoubleMatrixQuery(this,arg);
}
}
public static class Nnz extends AbstractToScalarDoubleMatrixQuery {
//returns the singleton instance of this class
private static Nnz singleton = null;
public static Nnz getInstance(){
if (singleton == null) singleton = new Nnz();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseNnz(this,arg);
}
//return name of builtin
public String getName(){
return "nnz";
}
}
public static abstract class AbstractToLogicalMatrixQuery extends AbstractMatrixQuery {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractToLogicalMatrixQuery(this,arg);
}
}
public static abstract class AbstractUnaryToLogicalMatrixQuery extends AbstractToLogicalMatrixQuery implements ClassPropagationDefined {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractUnaryToLogicalMatrixQuery(this,arg);
}
public ClassPropTools.MC getMatlabClassPropagationInfo(){{
return getClassPropagationInfo();
}}
private ClassPropTools.MC classPropInfo = null; //new ClassPropTools.MCMap(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("single"),new ClassPropTools.MCBuiltin("double")),new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("int8"),new ClassPropTools.MCBuiltin("uint16")),new ClassPropTools.MCBuiltin("uint32")),new ClassPropTools.MCBuiltin("uint64")),new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("int8"),new ClassPropTools.MCBuiltin("uint16")),new ClassPropTools.MCBuiltin("uint32")),new ClassPropTools.MCBuiltin("uint64")))),new ClassPropTools.MCBuiltin("char")),new ClassPropTools.MCBuiltin("logical")),new ClassPropTools.MCBuiltin("logical"));
public ClassPropTools.MC getClassPropagationInfo(){
//set classPropInfo if not defined
if (classPropInfo == null){
ClassPropTools.MC parentClassPropInfo = new ClassPropTools.MCNone();
classPropInfo = new ClassPropTools.MCMap(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("single"),new ClassPropTools.MCBuiltin("double")),new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("int8"),new ClassPropTools.MCBuiltin("uint16")),new ClassPropTools.MCBuiltin("uint32")),new ClassPropTools.MCBuiltin("uint64")),new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("int8"),new ClassPropTools.MCBuiltin("uint16")),new ClassPropTools.MCBuiltin("uint32")),new ClassPropTools.MCBuiltin("uint64")))),new ClassPropTools.MCBuiltin("char")),new ClassPropTools.MCBuiltin("logical")),new ClassPropTools.MCBuiltin("logical"));
}
return classPropInfo;
}
}
public static abstract class AbstractScalarUnaryToLogicalMatrixQuery extends AbstractUnaryToLogicalMatrixQuery {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractScalarUnaryToLogicalMatrixQuery(this,arg);
}
}
public static class Not extends AbstractScalarUnaryToLogicalMatrixQuery {
//returns the singleton instance of this class
private static Not singleton = null;
public static Not getInstance(){
if (singleton == null) singleton = new Not();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseNot(this,arg);
}
//return name of builtin
public String getName(){
return "not";
}
}
public static class Any extends AbstractScalarUnaryToLogicalMatrixQuery {
//returns the singleton instance of this class
private static Any singleton = null;
public static Any getInstance(){
if (singleton == null) singleton = new Any();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAny(this,arg);
}
//return name of builtin
public String getName(){
return "any";
}
}
public static class All extends AbstractScalarUnaryToLogicalMatrixQuery {
//returns the singleton instance of this class
private static All singleton = null;
public static All getInstance(){
if (singleton == null) singleton = new All();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAll(this,arg);
}
//return name of builtin
public String getName(){
return "all";
}
}
public static class Isreal extends AbstractScalarUnaryToLogicalMatrixQuery {
//returns the singleton instance of this class
private static Isreal singleton = null;
public static Isreal getInstance(){
if (singleton == null) singleton = new Isreal();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseIsreal(this,arg);
}
//return name of builtin
public String getName(){
return "isreal";
}
}
public static abstract class AbstractElementalUnaryToLogicalMatrixQuery extends AbstractUnaryToLogicalMatrixQuery {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractElementalUnaryToLogicalMatrixQuery(this,arg);
}
}
public static class Isinf extends AbstractElementalUnaryToLogicalMatrixQuery {
//returns the singleton instance of this class
private static Isinf singleton = null;
public static Isinf getInstance(){
if (singleton == null) singleton = new Isinf();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseIsinf(this,arg);
}
//return name of builtin
public String getName(){
return "isinf";
}
}
public static class Isfinite extends AbstractElementalUnaryToLogicalMatrixQuery {
//returns the singleton instance of this class
private static Isfinite singleton = null;
public static Isfinite getInstance(){
if (singleton == null) singleton = new Isfinite();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseIsfinite(this,arg);
}
//return name of builtin
public String getName(){
return "isfinite";
}
}
public static class Isnan extends AbstractElementalUnaryToLogicalMatrixQuery {
//returns the singleton instance of this class
private static Isnan singleton = null;
public static Isnan getInstance(){
if (singleton == null) singleton = new Isnan();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseIsnan(this,arg);
}
//return name of builtin
public String getName(){
return "isnan";
}
}
public static abstract class AbstractBinaryToLogicalMatrixQuery extends AbstractToLogicalMatrixQuery implements ClassPropagationDefined {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractBinaryToLogicalMatrixQuery(this,arg);
}
public ClassPropTools.MC getMatlabClassPropagationInfo(){{
return getClassPropagationInfo();
}}
private ClassPropTools.MC classPropInfo = null; //new ClassPropTools.MCMap(new ClassPropTools.MCChain(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("single"),new ClassPropTools.MCBuiltin("double")),new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("int8"),new ClassPropTools.MCBuiltin("uint16")),new ClassPropTools.MCBuiltin("uint32")),new ClassPropTools.MCBuiltin("uint64")),new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("int8"),new ClassPropTools.MCBuiltin("uint16")),new ClassPropTools.MCBuiltin("uint32")),new ClassPropTools.MCBuiltin("uint64")))),new ClassPropTools.MCBuiltin("char")),new ClassPropTools.MCBuiltin("logical")),new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("single"),new ClassPropTools.MCBuiltin("double")),new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("int8"),new ClassPropTools.MCBuiltin("uint16")),new ClassPropTools.MCBuiltin("uint32")),new ClassPropTools.MCBuiltin("uint64")),new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("int8"),new ClassPropTools.MCBuiltin("uint16")),new ClassPropTools.MCBuiltin("uint32")),new ClassPropTools.MCBuiltin("uint64")))),new ClassPropTools.MCBuiltin("char")),new ClassPropTools.MCBuiltin("logical"))),new ClassPropTools.MCBuiltin("logical"));
public ClassPropTools.MC getClassPropagationInfo(){
//set classPropInfo if not defined
if (classPropInfo == null){
ClassPropTools.MC parentClassPropInfo = new ClassPropTools.MCNone();
classPropInfo = new ClassPropTools.MCMap(new ClassPropTools.MCChain(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("single"),new ClassPropTools.MCBuiltin("double")),new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("int8"),new ClassPropTools.MCBuiltin("uint16")),new ClassPropTools.MCBuiltin("uint32")),new ClassPropTools.MCBuiltin("uint64")),new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("int8"),new ClassPropTools.MCBuiltin("uint16")),new ClassPropTools.MCBuiltin("uint32")),new ClassPropTools.MCBuiltin("uint64")))),new ClassPropTools.MCBuiltin("char")),new ClassPropTools.MCBuiltin("logical")),new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("single"),new ClassPropTools.MCBuiltin("double")),new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("int8"),new ClassPropTools.MCBuiltin("uint16")),new ClassPropTools.MCBuiltin("uint32")),new ClassPropTools.MCBuiltin("uint64")),new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("int8"),new ClassPropTools.MCBuiltin("uint16")),new ClassPropTools.MCBuiltin("uint32")),new ClassPropTools.MCBuiltin("uint64")))),new ClassPropTools.MCBuiltin("char")),new ClassPropTools.MCBuiltin("logical"))),new ClassPropTools.MCBuiltin("logical"));
}
return classPropInfo;
}
}
public static abstract class AbstractElementalBinaryToLogicalMatrixQuery extends AbstractBinaryToLogicalMatrixQuery {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractElementalBinaryToLogicalMatrixQuery(this,arg);
}
}
public static abstract class AbstractRelationalOperator extends AbstractElementalBinaryToLogicalMatrixQuery {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractRelationalOperator(this,arg);
}
}
public static class Eq extends AbstractRelationalOperator {
//returns the singleton instance of this class
private static Eq singleton = null;
public static Eq getInstance(){
if (singleton == null) singleton = new Eq();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseEq(this,arg);
}
//return name of builtin
public String getName(){
return "eq";
}
}
public static class Ne extends AbstractRelationalOperator {
//returns the singleton instance of this class
private static Ne singleton = null;
public static Ne getInstance(){
if (singleton == null) singleton = new Ne();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseNe(this,arg);
}
//return name of builtin
public String getName(){
return "ne";
}
}
public static class Lt extends AbstractRelationalOperator {
//returns the singleton instance of this class
private static Lt singleton = null;
public static Lt getInstance(){
if (singleton == null) singleton = new Lt();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseLt(this,arg);
}
//return name of builtin
public String getName(){
return "lt";
}
}
public static class Gt extends AbstractRelationalOperator {
//returns the singleton instance of this class
private static Gt singleton = null;
public static Gt getInstance(){
if (singleton == null) singleton = new Gt();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseGt(this,arg);
}
//return name of builtin
public String getName(){
return "gt";
}
}
public static class Le extends AbstractRelationalOperator {
//returns the singleton instance of this class
private static Le singleton = null;
public static Le getInstance(){
if (singleton == null) singleton = new Le();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseLe(this,arg);
}
//return name of builtin
public String getName(){
return "le";
}
}
public static class Ge extends AbstractRelationalOperator {
//returns the singleton instance of this class
private static Ge singleton = null;
public static Ge getInstance(){
if (singleton == null) singleton = new Ge();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseGe(this,arg);
}
//return name of builtin
public String getName(){
return "ge";
}
}
public static abstract class AbstractLogicalOperator extends AbstractElementalBinaryToLogicalMatrixQuery {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractLogicalOperator(this,arg);
}
}
public static class And extends AbstractLogicalOperator {
//returns the singleton instance of this class
private static And singleton = null;
public static And getInstance(){
if (singleton == null) singleton = new And();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAnd(this,arg);
}
//return name of builtin
public String getName(){
return "and";
}
}
public static class Or extends AbstractLogicalOperator {
//returns the singleton instance of this class
private static Or singleton = null;
public static Or getInstance(){
if (singleton == null) singleton = new Or();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseOr(this,arg);
}
//return name of builtin
public String getName(){
return "or";
}
}
public static class Xor extends AbstractLogicalOperator {
//returns the singleton instance of this class
private static Xor singleton = null;
public static Xor getInstance(){
if (singleton == null) singleton = new Xor();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseXor(this,arg);
}
//return name of builtin
public String getName(){
return "xor";
}
}
public static abstract class AbstractMatrixCreation extends AbstractMatrixFunction {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractMatrixCreation(this,arg);
}
}
public static class Colon extends AbstractMatrixCreation implements ClassPropagationDefined {
//returns the singleton instance of this class
private static Colon singleton = null;
public static Colon getInstance(){
if (singleton == null) singleton = new Colon();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseColon(this,arg);
}
//return name of builtin
public String getName(){
return "colon";
}
private ClassPropTools.MC matlabClassPropInfo = null; //new ClassPropTools.MCUnion(new ClassPropTools.MCMap(new ClassPropTools.MCChain(new ClassPropTools.MCChain(new ClassPropTools.MCBuiltin("logical"),new ClassPropTools.MCBuiltin("logical")),new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("logical"),new ClassPropTools.MCNone())),new ClassPropTools.MCError()),new ClassPropTools.MCUnion(new ClassPropTools.MCMap(new ClassPropTools.MCChain(new ClassPropTools.MCChain(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("logical"),new ClassPropTools.MCBuiltin("double")),new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("double"),new ClassPropTools.MCBuiltin("logical"))),new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("double"),new ClassPropTools.MCBuiltin("logical")),new ClassPropTools.MCNone())),new ClassPropTools.MCBuiltin("double")),new ClassPropTools.MCUnion(new ClassPropTools.MCMap(new ClassPropTools.MCChain(new ClassPropTools.MCChain(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("double"),new ClassPropTools.MCNum(-1)),new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("double"),new ClassPropTools.MCNum(-1))),new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("single"),new ClassPropTools.MCBuiltin("double")),new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("int8"),new ClassPropTools.MCBuiltin("uint16")),new ClassPropTools.MCBuiltin("uint32")),new ClassPropTools.MCBuiltin("uint64")),new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("int8"),new ClassPropTools.MCBuiltin("uint16")),new ClassPropTools.MCBuiltin("uint32")),new ClassPropTools.MCBuiltin("uint64")))),new ClassPropTools.MCNone())),new ClassPropTools.MCNum(-1)),new ClassPropTools.MCUnion(new ClassPropTools.MCMap(new ClassPropTools.MCChain(new ClassPropTools.MCChain(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("double"),new ClassPropTools.MCNum(1)),new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("single"),new ClassPropTools.MCBuiltin("double")),new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("int8"),new ClassPropTools.MCBuiltin("uint16")),new ClassPropTools.MCBuiltin("uint32")),new ClassPropTools.MCBuiltin("uint64")),new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("int8"),new ClassPropTools.MCBuiltin("uint16")),new ClassPropTools.MCBuiltin("uint32")),new ClassPropTools.MCBuiltin("uint64"))))),new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("double"),new ClassPropTools.MCNum(1))),new ClassPropTools.MCNum(1)),new ClassPropTools.MCMap(new ClassPropTools.MCChain(new ClassPropTools.MCBuiltin("char"),new ClassPropTools.MCUnion(new ClassPropTools.MCChain(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("char"),new ClassPropTools.MCBuiltin("double")),new ClassPropTools.MCBuiltin("char")),new ClassPropTools.MCBuiltin("char"))),new ClassPropTools.MCBuiltin("char"))))));
public ClassPropTools.MC getMatlabClassPropagationInfo(){
//set classPropInfo if not defined
if (matlabClassPropInfo == null){
ClassPropTools.MC parentClassPropInfo = new ClassPropTools.MCNone();
matlabClassPropInfo = new ClassPropTools.MCUnion(new ClassPropTools.MCMap(new ClassPropTools.MCChain(new ClassPropTools.MCChain(new ClassPropTools.MCBuiltin("logical"),new ClassPropTools.MCBuiltin("logical")),new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("logical"),new ClassPropTools.MCNone())),new ClassPropTools.MCError()),new ClassPropTools.MCUnion(new ClassPropTools.MCMap(new ClassPropTools.MCChain(new ClassPropTools.MCChain(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("logical"),new ClassPropTools.MCBuiltin("double")),new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("double"),new ClassPropTools.MCBuiltin("logical"))),new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("double"),new ClassPropTools.MCBuiltin("logical")),new ClassPropTools.MCNone())),new ClassPropTools.MCBuiltin("double")),new ClassPropTools.MCUnion(new ClassPropTools.MCMap(new ClassPropTools.MCChain(new ClassPropTools.MCChain(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("double"),new ClassPropTools.MCNum(-1)),new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("double"),new ClassPropTools.MCNum(-1))),new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("single"),new ClassPropTools.MCBuiltin("double")),new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("int8"),new ClassPropTools.MCBuiltin("uint16")),new ClassPropTools.MCBuiltin("uint32")),new ClassPropTools.MCBuiltin("uint64")),new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("int8"),new ClassPropTools.MCBuiltin("uint16")),new ClassPropTools.MCBuiltin("uint32")),new ClassPropTools.MCBuiltin("uint64")))),new ClassPropTools.MCNone())),new ClassPropTools.MCNum(-1)),new ClassPropTools.MCUnion(new ClassPropTools.MCMap(new ClassPropTools.MCChain(new ClassPropTools.MCChain(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("double"),new ClassPropTools.MCNum(1)),new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("single"),new ClassPropTools.MCBuiltin("double")),new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("int8"),new ClassPropTools.MCBuiltin("uint16")),new ClassPropTools.MCBuiltin("uint32")),new ClassPropTools.MCBuiltin("uint64")),new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("int8"),new ClassPropTools.MCBuiltin("uint16")),new ClassPropTools.MCBuiltin("uint32")),new ClassPropTools.MCBuiltin("uint64"))))),new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("double"),new ClassPropTools.MCNum(1))),new ClassPropTools.MCNum(1)),new ClassPropTools.MCMap(new ClassPropTools.MCChain(new ClassPropTools.MCBuiltin("char"),new ClassPropTools.MCUnion(new ClassPropTools.MCChain(new ClassPropTools.MCUnion(new ClassPropTools.MCBuiltin("char"),new ClassPropTools.MCBuiltin("double")),new ClassPropTools.MCBuiltin("char")),new ClassPropTools.MCBuiltin("char"))),new ClassPropTools.MCBuiltin("char"))))));
}
return matlabClassPropInfo;
}
private ClassPropTools.MC classPropInfo = null; //new ClassPropTools.MCCoerce(new ClassPropTools.MCMap(new ClassPropTools.MCBuiltin("logical"),new ClassPropTools.MCBuiltin("double")),getMatlabClassPropagationInfo());
public ClassPropTools.MC getClassPropagationInfo(){
//set classPropInfo if not defined
if (classPropInfo == null){
ClassPropTools.MC parentClassPropInfo = new ClassPropTools.MCNone();
classPropInfo = new ClassPropTools.MCCoerce(new ClassPropTools.MCMap(new ClassPropTools.MCBuiltin("logical"),new ClassPropTools.MCBuiltin("double")),getMatlabClassPropagationInfo());
}
return classPropInfo;
}
}
public static abstract class AbstractByShapeAndTypeMatrixCreation extends AbstractMatrixCreation {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractByShapeAndTypeMatrixCreation(this,arg);
}
}
public static abstract class AbstractNumericalByShapeAndTypeMatrixCreation extends AbstractByShapeAndTypeMatrixCreation {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractNumericalByShapeAndTypeMatrixCreation(this,arg);
}
}
public static class Ones extends AbstractNumericalByShapeAndTypeMatrixCreation {
//returns the singleton instance of this class
private static Ones singleton = null;
public static Ones getInstance(){
if (singleton == null) singleton = new Ones();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseOnes(this,arg);
}
//return name of builtin
public String getName(){
return "ones";
}
}
public static class Zeros extends AbstractNumericalByShapeAndTypeMatrixCreation {
//returns the singleton instance of this class
private static Zeros singleton = null;
public static Zeros getInstance(){
if (singleton == null) singleton = new Zeros();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseZeros(this,arg);
}
//return name of builtin
public String getName(){
return "zeros";
}
}
public static class Eye extends AbstractNumericalByShapeAndTypeMatrixCreation {
//returns the singleton instance of this class
private static Eye singleton = null;
public static Eye getInstance(){
if (singleton == null) singleton = new Eye();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseEye(this,arg);
}
//return name of builtin
public String getName(){
return "eye";
}
}
public static abstract class AbstractFloatByShapeAndTypeMatrixCreation extends AbstractNumericalByShapeAndTypeMatrixCreation {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractFloatByShapeAndTypeMatrixCreation(this,arg);
}
}
public static class Inf extends AbstractFloatByShapeAndTypeMatrixCreation {
//returns the singleton instance of this class
private static Inf singleton = null;
public static Inf getInstance(){
if (singleton == null) singleton = new Inf();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseInf(this,arg);
}
//return name of builtin
public String getName(){
return "inf";
}
}
public static class Nan extends AbstractFloatByShapeAndTypeMatrixCreation {
//returns the singleton instance of this class
private static Nan singleton = null;
public static Nan getInstance(){
if (singleton == null) singleton = new Nan();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseNan(this,arg);
}
//return name of builtin
public String getName(){
return "nan";
}
}
public static abstract class AbstractLogicalByShapeAndTypeMatrixCreation extends AbstractByShapeAndTypeMatrixCreation {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractLogicalByShapeAndTypeMatrixCreation(this,arg);
}
}
public static class True extends AbstractLogicalByShapeAndTypeMatrixCreation {
//returns the singleton instance of this class
private static True singleton = null;
public static True getInstance(){
if (singleton == null) singleton = new True();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseTrue(this,arg);
}
//return name of builtin
public String getName(){
return "true";
}
}
public static class False extends AbstractLogicalByShapeAndTypeMatrixCreation {
//returns the singleton instance of this class
private static False singleton = null;
public static False getInstance(){
if (singleton == null) singleton = new False();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseFalse(this,arg);
}
//return name of builtin
public String getName(){
return "false";
}
}
public static abstract class AbstractMatrixConstructor extends AbstractMatrixFunction {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractMatrixConstructor(this,arg);
}
}
public static class Double extends AbstractMatrixConstructor implements ClassPropagationDefined {
//returns the singleton instance of this class
private static Double singleton = null;
public static Double getInstance(){
if (singleton == null) singleton = new Double();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseDouble(this,arg);
}
//return name of builtin
public String getName(){
return "double";
}
public ClassPropTools.MC getMatlabClassPropagationInfo(){{
return getClassPropagationInfo();
}}
private ClassPropTools.MC classPropInfo = null; //new ClassPropTools.MCMap(new ClassPropTools.MCAny(),new ClassPropTools.MCBuiltin("double"));
public ClassPropTools.MC getClassPropagationInfo(){
//set classPropInfo if not defined
if (classPropInfo == null){
ClassPropTools.MC parentClassPropInfo = new ClassPropTools.MCNone();
classPropInfo = new ClassPropTools.MCMap(new ClassPropTools.MCAny(),new ClassPropTools.MCBuiltin("double"));
}
return classPropInfo;
}
}
public static class Single extends AbstractMatrixConstructor implements ClassPropagationDefined {
//returns the singleton instance of this class
private static Single singleton = null;
public static Single getInstance(){
if (singleton == null) singleton = new Single();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseSingle(this,arg);
}
//return name of builtin
public String getName(){
return "single";
}
public ClassPropTools.MC getMatlabClassPropagationInfo(){{
return getClassPropagationInfo();
}}
private ClassPropTools.MC classPropInfo = null; //new ClassPropTools.MCMap(new ClassPropTools.MCAny(),new ClassPropTools.MCBuiltin("single"));
public ClassPropTools.MC getClassPropagationInfo(){
//set classPropInfo if not defined
if (classPropInfo == null){
ClassPropTools.MC parentClassPropInfo = new ClassPropTools.MCNone();
classPropInfo = new ClassPropTools.MCMap(new ClassPropTools.MCAny(),new ClassPropTools.MCBuiltin("single"));
}
return classPropInfo;
}
}
public static class Char extends AbstractMatrixConstructor implements ClassPropagationDefined {
//returns the singleton instance of this class
private static Char singleton = null;
public static Char getInstance(){
if (singleton == null) singleton = new Char();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseChar(this,arg);
}
//return name of builtin
public String getName(){
return "char";
}
public ClassPropTools.MC getMatlabClassPropagationInfo(){{
return getClassPropagationInfo();
}}
private ClassPropTools.MC classPropInfo = null; //new ClassPropTools.MCMap(new ClassPropTools.MCAny(),new ClassPropTools.MCBuiltin("char"));
public ClassPropTools.MC getClassPropagationInfo(){
//set classPropInfo if not defined
if (classPropInfo == null){
ClassPropTools.MC parentClassPropInfo = new ClassPropTools.MCNone();
classPropInfo = new ClassPropTools.MCMap(new ClassPropTools.MCAny(),new ClassPropTools.MCBuiltin("char"));
}
return classPropInfo;
}
}
public static class Logical extends AbstractMatrixConstructor implements ClassPropagationDefined {
//returns the singleton instance of this class
private static Logical singleton = null;
public static Logical getInstance(){
if (singleton == null) singleton = new Logical();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseLogical(this,arg);
}
//return name of builtin
public String getName(){
return "logical";
}
public ClassPropTools.MC getMatlabClassPropagationInfo(){{
return getClassPropagationInfo();
}}
private ClassPropTools.MC classPropInfo = null; //new ClassPropTools.MCMap(new ClassPropTools.MCAny(),new ClassPropTools.MCBuiltin("logical"));
public ClassPropTools.MC getClassPropagationInfo(){
//set classPropInfo if not defined
if (classPropInfo == null){
ClassPropTools.MC parentClassPropInfo = new ClassPropTools.MCNone();
classPropInfo = new ClassPropTools.MCMap(new ClassPropTools.MCAny(),new ClassPropTools.MCBuiltin("logical"));
}
return classPropInfo;
}
}
public static class Int8 extends AbstractMatrixConstructor implements ClassPropagationDefined {
//returns the singleton instance of this class
private static Int8 singleton = null;
public static Int8 getInstance(){
if (singleton == null) singleton = new Int8();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseInt8(this,arg);
}
//return name of builtin
public String getName(){
return "int8";
}
public ClassPropTools.MC getMatlabClassPropagationInfo(){{
return getClassPropagationInfo();
}}
private ClassPropTools.MC classPropInfo = null; //new ClassPropTools.MCMap(new ClassPropTools.MCAny(),new ClassPropTools.MCBuiltin("int8"));
public ClassPropTools.MC getClassPropagationInfo(){
//set classPropInfo if not defined
if (classPropInfo == null){
ClassPropTools.MC parentClassPropInfo = new ClassPropTools.MCNone();
classPropInfo = new ClassPropTools.MCMap(new ClassPropTools.MCAny(),new ClassPropTools.MCBuiltin("int8"));
}
return classPropInfo;
}
}
public static class Int16 extends AbstractMatrixConstructor implements ClassPropagationDefined {
//returns the singleton instance of this class
private static Int16 singleton = null;
public static Int16 getInstance(){
if (singleton == null) singleton = new Int16();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseInt16(this,arg);
}
//return name of builtin
public String getName(){
return "int16";
}
public ClassPropTools.MC getMatlabClassPropagationInfo(){{
return getClassPropagationInfo();
}}
private ClassPropTools.MC classPropInfo = null; //new ClassPropTools.MCMap(new ClassPropTools.MCAny(),new ClassPropTools.MCBuiltin("uint16"));
public ClassPropTools.MC getClassPropagationInfo(){
//set classPropInfo if not defined
if (classPropInfo == null){
ClassPropTools.MC parentClassPropInfo = new ClassPropTools.MCNone();
classPropInfo = new ClassPropTools.MCMap(new ClassPropTools.MCAny(),new ClassPropTools.MCBuiltin("uint16"));
}
return classPropInfo;
}
}
public static class Int32 extends AbstractMatrixConstructor implements ClassPropagationDefined {
//returns the singleton instance of this class
private static Int32 singleton = null;
public static Int32 getInstance(){
if (singleton == null) singleton = new Int32();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseInt32(this,arg);
}
//return name of builtin
public String getName(){
return "int32";
}
public ClassPropTools.MC getMatlabClassPropagationInfo(){{
return getClassPropagationInfo();
}}
private ClassPropTools.MC classPropInfo = null; //new ClassPropTools.MCMap(new ClassPropTools.MCAny(),new ClassPropTools.MCBuiltin("uint32"));
public ClassPropTools.MC getClassPropagationInfo(){
//set classPropInfo if not defined
if (classPropInfo == null){
ClassPropTools.MC parentClassPropInfo = new ClassPropTools.MCNone();
classPropInfo = new ClassPropTools.MCMap(new ClassPropTools.MCAny(),new ClassPropTools.MCBuiltin("uint32"));
}
return classPropInfo;
}
}
public static class Int64 extends AbstractMatrixConstructor implements ClassPropagationDefined {
//returns the singleton instance of this class
private static Int64 singleton = null;
public static Int64 getInstance(){
if (singleton == null) singleton = new Int64();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseInt64(this,arg);
}
//return name of builtin
public String getName(){
return "int64";
}
public ClassPropTools.MC getMatlabClassPropagationInfo(){{
return getClassPropagationInfo();
}}
private ClassPropTools.MC classPropInfo = null; //new ClassPropTools.MCMap(new ClassPropTools.MCAny(),new ClassPropTools.MCBuiltin("uint64"));
public ClassPropTools.MC getClassPropagationInfo(){
//set classPropInfo if not defined
if (classPropInfo == null){
ClassPropTools.MC parentClassPropInfo = new ClassPropTools.MCNone();
classPropInfo = new ClassPropTools.MCMap(new ClassPropTools.MCAny(),new ClassPropTools.MCBuiltin("uint64"));
}
return classPropInfo;
}
}
public static class Uint8 extends AbstractMatrixConstructor implements ClassPropagationDefined {
//returns the singleton instance of this class
private static Uint8 singleton = null;
public static Uint8 getInstance(){
if (singleton == null) singleton = new Uint8();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseUint8(this,arg);
}
//return name of builtin
public String getName(){
return "uint8";
}
public ClassPropTools.MC getMatlabClassPropagationInfo(){{
return getClassPropagationInfo();
}}
private ClassPropTools.MC classPropInfo = null; //new ClassPropTools.MCMap(new ClassPropTools.MCAny(),new ClassPropTools.MCBuiltin("int8"));
public ClassPropTools.MC getClassPropagationInfo(){
//set classPropInfo if not defined
if (classPropInfo == null){
ClassPropTools.MC parentClassPropInfo = new ClassPropTools.MCNone();
classPropInfo = new ClassPropTools.MCMap(new ClassPropTools.MCAny(),new ClassPropTools.MCBuiltin("int8"));
}
return classPropInfo;
}
}
public static class Uint16 extends AbstractMatrixConstructor implements ClassPropagationDefined {
//returns the singleton instance of this class
private static Uint16 singleton = null;
public static Uint16 getInstance(){
if (singleton == null) singleton = new Uint16();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseUint16(this,arg);
}
//return name of builtin
public String getName(){
return "uint16";
}
public ClassPropTools.MC getMatlabClassPropagationInfo(){{
return getClassPropagationInfo();
}}
private ClassPropTools.MC classPropInfo = null; //new ClassPropTools.MCMap(new ClassPropTools.MCAny(),new ClassPropTools.MCBuiltin("uint16"));
public ClassPropTools.MC getClassPropagationInfo(){
//set classPropInfo if not defined
if (classPropInfo == null){
ClassPropTools.MC parentClassPropInfo = new ClassPropTools.MCNone();
classPropInfo = new ClassPropTools.MCMap(new ClassPropTools.MCAny(),new ClassPropTools.MCBuiltin("uint16"));
}
return classPropInfo;
}
}
public static class Uint32 extends AbstractMatrixConstructor implements ClassPropagationDefined {
//returns the singleton instance of this class
private static Uint32 singleton = null;
public static Uint32 getInstance(){
if (singleton == null) singleton = new Uint32();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseUint32(this,arg);
}
//return name of builtin
public String getName(){
return "uint32";
}
public ClassPropTools.MC getMatlabClassPropagationInfo(){{
return getClassPropagationInfo();
}}
private ClassPropTools.MC classPropInfo = null; //new ClassPropTools.MCMap(new ClassPropTools.MCAny(),new ClassPropTools.MCBuiltin("uint32"));
public ClassPropTools.MC getClassPropagationInfo(){
//set classPropInfo if not defined
if (classPropInfo == null){
ClassPropTools.MC parentClassPropInfo = new ClassPropTools.MCNone();
classPropInfo = new ClassPropTools.MCMap(new ClassPropTools.MCAny(),new ClassPropTools.MCBuiltin("uint32"));
}
return classPropInfo;
}
}
public static class Uint64 extends AbstractMatrixConstructor implements ClassPropagationDefined {
//returns the singleton instance of this class
private static Uint64 singleton = null;
public static Uint64 getInstance(){
if (singleton == null) singleton = new Uint64();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseUint64(this,arg);
}
//return name of builtin
public String getName(){
return "uint64";
}
public ClassPropTools.MC getMatlabClassPropagationInfo(){{
return getClassPropagationInfo();
}}
private ClassPropTools.MC classPropInfo = null; //new ClassPropTools.MCMap(new ClassPropTools.MCAny(),new ClassPropTools.MCBuiltin("uint64"));
public ClassPropTools.MC getClassPropagationInfo(){
//set classPropInfo if not defined
if (classPropInfo == null){
ClassPropTools.MC parentClassPropInfo = new ClassPropTools.MCNone();
classPropInfo = new ClassPropTools.MCMap(new ClassPropTools.MCAny(),new ClassPropTools.MCBuiltin("uint64"));
}
return classPropInfo;
}
}
public static class CellFunction extends AbstractPureFunction {
//returns the singleton instance of this class
private static CellFunction singleton = null;
public static CellFunction getInstance(){
if (singleton == null) singleton = new CellFunction();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseCellFunction(this,arg);
}
//return name of builtin
public String getName(){
return "cellFunction";
}
}
public static abstract class AbstractStructFunction extends AbstractPureFunction {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractStructFunction(this,arg);
}
}
public static class Isfield extends AbstractStructFunction {
//returns the singleton instance of this class
private static Isfield singleton = null;
public static Isfield getInstance(){
if (singleton == null) singleton = new Isfield();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseIsfield(this,arg);
}
//return name of builtin
public String getName(){
return "isfield";
}
}
public static class ObjectFunction extends AbstractPureFunction {
//returns the singleton instance of this class
private static ObjectFunction singleton = null;
public static ObjectFunction getInstance(){
if (singleton == null) singleton = new ObjectFunction();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseObjectFunction(this,arg);
}
//return name of builtin
public String getName(){
return "objectFunction";
}
}
public static abstract class AbstractVersatileFunction extends AbstractPureFunction {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractVersatileFunction(this,arg);
}
}
public static abstract class AbstractMatrixOrCellOfCharFunction extends AbstractVersatileFunction {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractMatrixOrCellOfCharFunction(this,arg);
}
}
public static class Sort extends AbstractMatrixOrCellOfCharFunction {
//returns the singleton instance of this class
private static Sort singleton = null;
public static Sort getInstance(){
if (singleton == null) singleton = new Sort();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseSort(this,arg);
}
//return name of builtin
public String getName(){
return "sort";
}
}
public static class Unique extends AbstractMatrixOrCellOfCharFunction {
//returns the singleton instance of this class
private static Unique singleton = null;
public static Unique getInstance(){
if (singleton == null) singleton = new Unique();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseUnique(this,arg);
}
//return name of builtin
public String getName(){
return "unique";
}
}
public static abstract class AbstractCharFunction extends AbstractMatrixOrCellOfCharFunction {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractCharFunction(this,arg);
}
}
public static abstract class AbstractProperCharFunction extends AbstractCharFunction {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractProperCharFunction(this,arg);
}
}
public static abstract class AbstractUnaryProperCharFunction extends AbstractProperCharFunction {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractUnaryProperCharFunction(this,arg);
}
}
public static class Upper extends AbstractUnaryProperCharFunction {
//returns the singleton instance of this class
private static Upper singleton = null;
public static Upper getInstance(){
if (singleton == null) singleton = new Upper();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseUpper(this,arg);
}
//return name of builtin
public String getName(){
return "upper";
}
}
public static class Lower extends AbstractUnaryProperCharFunction {
//returns the singleton instance of this class
private static Lower singleton = null;
public static Lower getInstance(){
if (singleton == null) singleton = new Lower();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseLower(this,arg);
}
//return name of builtin
public String getName(){
return "lower";
}
}
public static class Deblank extends AbstractUnaryProperCharFunction {
//returns the singleton instance of this class
private static Deblank singleton = null;
public static Deblank getInstance(){
if (singleton == null) singleton = new Deblank();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseDeblank(this,arg);
}
//return name of builtin
public String getName(){
return "deblank";
}
}
public static class Strtrim extends AbstractUnaryProperCharFunction {
//returns the singleton instance of this class
private static Strtrim singleton = null;
public static Strtrim getInstance(){
if (singleton == null) singleton = new Strtrim();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseStrtrim(this,arg);
}
//return name of builtin
public String getName(){
return "strtrim";
}
}
public static abstract class AbstractImproperCharFunction extends AbstractCharFunction {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractImproperCharFunction(this,arg);
}
}
public static class Strfind extends AbstractImproperCharFunction {
//returns the singleton instance of this class
private static Strfind singleton = null;
public static Strfind getInstance(){
if (singleton == null) singleton = new Strfind();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseStrfind(this,arg);
}
//return name of builtin
public String getName(){
return "strfind";
}
}
public static class Findstr extends AbstractImproperCharFunction {
//returns the singleton instance of this class
private static Findstr singleton = null;
public static Findstr getInstance(){
if (singleton == null) singleton = new Findstr();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseFindstr(this,arg);
}
//return name of builtin
public String getName(){
return "findstr";
}
}
public static class Strrep extends AbstractImproperCharFunction {
//returns the singleton instance of this class
private static Strrep singleton = null;
public static Strrep getInstance(){
if (singleton == null) singleton = new Strrep();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseStrrep(this,arg);
}
//return name of builtin
public String getName(){
return "strrep";
}
}
public static abstract class AbstractStringCompare extends AbstractImproperCharFunction {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractStringCompare(this,arg);
}
}
public static class Strcmp extends AbstractStringCompare {
//returns the singleton instance of this class
private static Strcmp singleton = null;
public static Strcmp getInstance(){
if (singleton == null) singleton = new Strcmp();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseStrcmp(this,arg);
}
//return name of builtin
public String getName(){
return "strcmp";
}
}
public static class Strcmpi extends AbstractStringCompare {
//returns the singleton instance of this class
private static Strcmpi singleton = null;
public static Strcmpi getInstance(){
if (singleton == null) singleton = new Strcmpi();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseStrcmpi(this,arg);
}
//return name of builtin
public String getName(){
return "strcmpi";
}
}
public static class Strncmpi extends AbstractStringCompare {
//returns the singleton instance of this class
private static Strncmpi singleton = null;
public static Strncmpi getInstance(){
if (singleton == null) singleton = new Strncmpi();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseStrncmpi(this,arg);
}
//return name of builtin
public String getName(){
return "strncmpi";
}
}
public static class Strncmp extends AbstractStringCompare {
//returns the singleton instance of this class
private static Strncmp singleton = null;
public static Strncmp getInstance(){
if (singleton == null) singleton = new Strncmp();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseStrncmp(this,arg);
}
//return name of builtin
public String getName(){
return "strncmp";
}
}
public static abstract class AbstractRegexpFunction extends AbstractImproperCharFunction {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractRegexpFunction(this,arg);
}
}
public static class Regexptranslate extends AbstractRegexpFunction {
//returns the singleton instance of this class
private static Regexptranslate singleton = null;
public static Regexptranslate getInstance(){
if (singleton == null) singleton = new Regexptranslate();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseRegexptranslate(this,arg);
}
//return name of builtin
public String getName(){
return "regexptranslate";
}
}
public static class Regexp extends AbstractRegexpFunction {
//returns the singleton instance of this class
private static Regexp singleton = null;
public static Regexp getInstance(){
if (singleton == null) singleton = new Regexp();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseRegexp(this,arg);
}
//return name of builtin
public String getName(){
return "regexp";
}
}
public static class Regexpi extends AbstractRegexpFunction {
//returns the singleton instance of this class
private static Regexpi singleton = null;
public static Regexpi getInstance(){
if (singleton == null) singleton = new Regexpi();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseRegexpi(this,arg);
}
//return name of builtin
public String getName(){
return "regexpi";
}
}
public static class Regexprep extends AbstractRegexpFunction {
//returns the singleton instance of this class
private static Regexprep singleton = null;
public static Regexprep getInstance(){
if (singleton == null) singleton = new Regexprep();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseRegexprep(this,arg);
}
//return name of builtin
public String getName(){
return "regexprep";
}
}
public static abstract class AbstractVersatileQuery extends AbstractVersatileFunction {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractVersatileQuery(this,arg);
}
}
public static class Class extends AbstractVersatileQuery {
//returns the singleton instance of this class
private static Class singleton = null;
public static Class getInstance(){
if (singleton == null) singleton = new Class();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseClass(this,arg);
}
//return name of builtin
public String getName(){
return "class";
}
}
public static abstract class AbstractDoubleResultVersatileQuery extends AbstractVersatileQuery {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractDoubleResultVersatileQuery(this,arg);
}
}
public static class Size extends AbstractDoubleResultVersatileQuery {
//returns the singleton instance of this class
private static Size singleton = null;
public static Size getInstance(){
if (singleton == null) singleton = new Size();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseSize(this,arg);
}
//return name of builtin
public String getName(){
return "size";
}
}
public static abstract class AbstractScalarDoubleResultVersatileQuery extends AbstractDoubleResultVersatileQuery {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractScalarDoubleResultVersatileQuery(this,arg);
}
}
public static class Length extends AbstractScalarDoubleResultVersatileQuery {
//returns the singleton instance of this class
private static Length singleton = null;
public static Length getInstance(){
if (singleton == null) singleton = new Length();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseLength(this,arg);
}
//return name of builtin
public String getName(){
return "length";
}
}
public static class Ndims extends AbstractScalarDoubleResultVersatileQuery {
//returns the singleton instance of this class
private static Ndims singleton = null;
public static Ndims getInstance(){
if (singleton == null) singleton = new Ndims();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseNdims(this,arg);
}
//return name of builtin
public String getName(){
return "ndims";
}
}
public static class Numel extends AbstractScalarDoubleResultVersatileQuery {
//returns the singleton instance of this class
private static Numel singleton = null;
public static Numel getInstance(){
if (singleton == null) singleton = new Numel();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseNumel(this,arg);
}
//return name of builtin
public String getName(){
return "numel";
}
}
public static class End extends AbstractScalarDoubleResultVersatileQuery {
//returns the singleton instance of this class
private static End singleton = null;
public static End getInstance(){
if (singleton == null) singleton = new End();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseEnd(this,arg);
}
//return name of builtin
public String getName(){
return "end";
}
}
public static abstract class AbstractLogicalResultVersatileQuery extends AbstractVersatileQuery {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractLogicalResultVersatileQuery(this,arg);
}
}
public static abstract class AbstractScalarLogicalResultVersatileQuery extends AbstractLogicalResultVersatileQuery {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractScalarLogicalResultVersatileQuery(this,arg);
}
}
public static abstract class AbstractClassQuery extends AbstractScalarLogicalResultVersatileQuery {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractClassQuery(this,arg);
}
}
public static class Isempty extends AbstractClassQuery {
//returns the singleton instance of this class
private static Isempty singleton = null;
public static Isempty getInstance(){
if (singleton == null) singleton = new Isempty();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseIsempty(this,arg);
}
//return name of builtin
public String getName(){
return "isempty";
}
}
public static class Isobject extends AbstractClassQuery {
//returns the singleton instance of this class
private static Isobject singleton = null;
public static Isobject getInstance(){
if (singleton == null) singleton = new Isobject();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseIsobject(this,arg);
}
//return name of builtin
public String getName(){
return "isobject";
}
}
public static class Isfloat extends AbstractClassQuery {
//returns the singleton instance of this class
private static Isfloat singleton = null;
public static Isfloat getInstance(){
if (singleton == null) singleton = new Isfloat();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseIsfloat(this,arg);
}
//return name of builtin
public String getName(){
return "isfloat";
}
}
public static class Isinteger extends AbstractClassQuery {
//returns the singleton instance of this class
private static Isinteger singleton = null;
public static Isinteger getInstance(){
if (singleton == null) singleton = new Isinteger();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseIsinteger(this,arg);
}
//return name of builtin
public String getName(){
return "isinteger";
}
}
public static class Islogical extends AbstractClassQuery {
//returns the singleton instance of this class
private static Islogical singleton = null;
public static Islogical getInstance(){
if (singleton == null) singleton = new Islogical();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseIslogical(this,arg);
}
//return name of builtin
public String getName(){
return "islogical";
}
}
public static class Isstruct extends AbstractClassQuery {
//returns the singleton instance of this class
private static Isstruct singleton = null;
public static Isstruct getInstance(){
if (singleton == null) singleton = new Isstruct();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseIsstruct(this,arg);
}
//return name of builtin
public String getName(){
return "isstruct";
}
}
public static class Ischar extends AbstractClassQuery {
//returns the singleton instance of this class
private static Ischar singleton = null;
public static Ischar getInstance(){
if (singleton == null) singleton = new Ischar();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseIschar(this,arg);
}
//return name of builtin
public String getName(){
return "ischar";
}
}
public static class Iscell extends AbstractClassQuery {
//returns the singleton instance of this class
private static Iscell singleton = null;
public static Iscell getInstance(){
if (singleton == null) singleton = new Iscell();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseIscell(this,arg);
}
//return name of builtin
public String getName(){
return "iscell";
}
}
public static class Isnumeric extends AbstractClassQuery {
//returns the singleton instance of this class
private static Isnumeric singleton = null;
public static Isnumeric getInstance(){
if (singleton == null) singleton = new Isnumeric();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseIsnumeric(this,arg);
}
//return name of builtin
public String getName(){
return "isnumeric";
}
}
public static class Isa extends AbstractClassQuery {
//returns the singleton instance of this class
private static Isa singleton = null;
public static Isa getInstance(){
if (singleton == null) singleton = new Isa();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseIsa(this,arg);
}
//return name of builtin
public String getName(){
return "isa";
}
}
public static abstract class AbstractScalarLogicalShapeQuery extends AbstractScalarLogicalResultVersatileQuery {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractScalarLogicalShapeQuery(this,arg);
}
}
public static class Isemtpy extends AbstractScalarLogicalShapeQuery {
//returns the singleton instance of this class
private static Isemtpy singleton = null;
public static Isemtpy getInstance(){
if (singleton == null) singleton = new Isemtpy();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseIsemtpy(this,arg);
}
//return name of builtin
public String getName(){
return "isemtpy";
}
}
public static class Isvector extends AbstractScalarLogicalShapeQuery {
//returns the singleton instance of this class
private static Isvector singleton = null;
public static Isvector getInstance(){
if (singleton == null) singleton = new Isvector();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseIsvector(this,arg);
}
//return name of builtin
public String getName(){
return "isvector";
}
}
public static class Isscalar extends AbstractScalarLogicalShapeQuery {
//returns the singleton instance of this class
private static Isscalar singleton = null;
public static Isscalar getInstance(){
if (singleton == null) singleton = new Isscalar();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseIsscalar(this,arg);
}
//return name of builtin
public String getName(){
return "isscalar";
}
}
public static abstract class AbstractBinaryToScalarLogicalVersatileQuery extends AbstractVersatileQuery {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractBinaryToScalarLogicalVersatileQuery(this,arg);
}
}
public static class Isequalwithequalnans extends AbstractBinaryToScalarLogicalVersatileQuery {
//returns the singleton instance of this class
private static Isequalwithequalnans singleton = null;
public static Isequalwithequalnans getInstance(){
if (singleton == null) singleton = new Isequalwithequalnans();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseIsequalwithequalnans(this,arg);
}
//return name of builtin
public String getName(){
return "isequalwithequalnans";
}
}
public static class Isequal extends AbstractBinaryToScalarLogicalVersatileQuery {
//returns the singleton instance of this class
private static Isequal singleton = null;
public static Isequal getInstance(){
if (singleton == null) singleton = new Isequal();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseIsequal(this,arg);
}
//return name of builtin
public String getName(){
return "isequal";
}
}
public static abstract class AbstractVersatileConversion extends AbstractVersatileFunction {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractVersatileConversion(this,arg);
}
}
public static abstract class AbstractShapeTransformation extends AbstractVersatileConversion {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractShapeTransformation(this,arg);
}
}
public static class Reshape extends AbstractShapeTransformation {
//returns the singleton instance of this class
private static Reshape singleton = null;
public static Reshape getInstance(){
if (singleton == null) singleton = new Reshape();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseReshape(this,arg);
}
//return name of builtin
public String getName(){
return "reshape";
}
}
public static class Permute extends AbstractShapeTransformation {
//returns the singleton instance of this class
private static Permute singleton = null;
public static Permute getInstance(){
if (singleton == null) singleton = new Permute();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.casePermute(this,arg);
}
//return name of builtin
public String getName(){
return "permute";
}
}
public static class Squeeze extends AbstractShapeTransformation {
//returns the singleton instance of this class
private static Squeeze singleton = null;
public static Squeeze getInstance(){
if (singleton == null) singleton = new Squeeze();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseSqueeze(this,arg);
}
//return name of builtin
public String getName(){
return "squeeze";
}
}
public static class Transpose extends AbstractShapeTransformation {
//returns the singleton instance of this class
private static Transpose singleton = null;
public static Transpose getInstance(){
if (singleton == null) singleton = new Transpose();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseTranspose(this,arg);
}
//return name of builtin
public String getName(){
return "transpose";
}
}
public static class Ctranspose extends AbstractShapeTransformation {
//returns the singleton instance of this class
private static Ctranspose singleton = null;
public static Ctranspose getInstance(){
if (singleton == null) singleton = new Ctranspose();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseCtranspose(this,arg);
}
//return name of builtin
public String getName(){
return "ctranspose";
}
}
public static abstract class AbstractConcatenation extends AbstractVersatileFunction {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractConcatenation(this,arg);
}
}
public static class Horzcat extends AbstractConcatenation {
//returns the singleton instance of this class
private static Horzcat singleton = null;
public static Horzcat getInstance(){
if (singleton == null) singleton = new Horzcat();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseHorzcat(this,arg);
}
//return name of builtin
public String getName(){
return "horzcat";
}
}
public static class Vertcat extends AbstractConcatenation {
//returns the singleton instance of this class
private static Vertcat singleton = null;
public static Vertcat getInstance(){
if (singleton == null) singleton = new Vertcat();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseVertcat(this,arg);
}
//return name of builtin
public String getName(){
return "vertcat";
}
}
public static class Cat extends AbstractConcatenation {
//returns the singleton instance of this class
private static Cat singleton = null;
public static Cat getInstance(){
if (singleton == null) singleton = new Cat();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseCat(this,arg);
}
//return name of builtin
public String getName(){
return "cat";
}
}
public static abstract class AbstractIndexing extends AbstractVersatileFunction {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractIndexing(this,arg);
}
}
public static class Subsasgn extends AbstractIndexing {
//returns the singleton instance of this class
private static Subsasgn singleton = null;
public static Subsasgn getInstance(){
if (singleton == null) singleton = new Subsasgn();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseSubsasgn(this,arg);
}
//return name of builtin
public String getName(){
return "subsasgn";
}
}
public static class Subsref extends AbstractIndexing {
//returns the singleton instance of this class
private static Subsref singleton = null;
public static Subsref getInstance(){
if (singleton == null) singleton = new Subsref();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseSubsref(this,arg);
}
//return name of builtin
public String getName(){
return "subsref";
}
}
public static abstract class AbstractMapOperator extends AbstractVersatileFunction {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractMapOperator(this,arg);
}
}
public static class Structfun extends AbstractMapOperator {
//returns the singleton instance of this class
private static Structfun singleton = null;
public static Structfun getInstance(){
if (singleton == null) singleton = new Structfun();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseStructfun(this,arg);
}
//return name of builtin
public String getName(){
return "structfun";
}
}
public static class Arrayfun extends AbstractMapOperator {
//returns the singleton instance of this class
private static Arrayfun singleton = null;
public static Arrayfun getInstance(){
if (singleton == null) singleton = new Arrayfun();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseArrayfun(this,arg);
}
//return name of builtin
public String getName(){
return "arrayfun";
}
}
public static class Cellfun extends AbstractMapOperator {
//returns the singleton instance of this class
private static Cellfun singleton = null;
public static Cellfun getInstance(){
if (singleton == null) singleton = new Cellfun();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseCellfun(this,arg);
}
//return name of builtin
public String getName(){
return "cellfun";
}
}
public static abstract class AbstractImpureFunction extends AbstractRoot {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractImpureFunction(this,arg);
}
}
public static class Superiorto extends AbstractImpureFunction {
//returns the singleton instance of this class
private static Superiorto singleton = null;
public static Superiorto getInstance(){
if (singleton == null) singleton = new Superiorto();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseSuperiorto(this,arg);
}
//return name of builtin
public String getName(){
return "superiorto";
}
}
public static class Superiorfloat extends AbstractImpureFunction {
//returns the singleton instance of this class
private static Superiorfloat singleton = null;
public static Superiorfloat getInstance(){
if (singleton == null) singleton = new Superiorfloat();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseSuperiorfloat(this,arg);
}
//return name of builtin
public String getName(){
return "superiorfloat";
}
}
public static class Exit extends AbstractImpureFunction {
//returns the singleton instance of this class
private static Exit singleton = null;
public static Exit getInstance(){
if (singleton == null) singleton = new Exit();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseExit(this,arg);
}
//return name of builtin
public String getName(){
return "exit";
}
}
public static class Quit extends AbstractImpureFunction {
//returns the singleton instance of this class
private static Quit singleton = null;
public static Quit getInstance(){
if (singleton == null) singleton = new Quit();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseQuit(this,arg);
}
//return name of builtin
public String getName(){
return "quit";
}
}
public static abstract class AbstractBuiltin extends AbstractImpureFunction {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractBuiltin(this,arg);
}
}
public static abstract class AbstractTimeFunction extends AbstractImpureFunction {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractTimeFunction(this,arg);
}
}
public static class Clock extends AbstractTimeFunction {
//returns the singleton instance of this class
private static Clock singleton = null;
public static Clock getInstance(){
if (singleton == null) singleton = new Clock();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseClock(this,arg);
}
//return name of builtin
public String getName(){
return "clock";
}
}
public static class Tic extends AbstractTimeFunction {
//returns the singleton instance of this class
private static Tic singleton = null;
public static Tic getInstance(){
if (singleton == null) singleton = new Tic();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseTic(this,arg);
}
//return name of builtin
public String getName(){
return "tic";
}
}
public static class Toc extends AbstractTimeFunction {
//returns the singleton instance of this class
private static Toc singleton = null;
public static Toc getInstance(){
if (singleton == null) singleton = new Toc();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseToc(this,arg);
}
//return name of builtin
public String getName(){
return "toc";
}
}
public static class Cputime extends AbstractTimeFunction {
//returns the singleton instance of this class
private static Cputime singleton = null;
public static Cputime getInstance(){
if (singleton == null) singleton = new Cputime();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseCputime(this,arg);
}
//return name of builtin
public String getName(){
return "cputime";
}
}
public static abstract class AbstractMatlabSystemFunction extends AbstractImpureFunction {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractMatlabSystemFunction(this,arg);
}
}
public static class Assert extends AbstractMatlabSystemFunction {
//returns the singleton instance of this class
private static Assert singleton = null;
public static Assert getInstance(){
if (singleton == null) singleton = new Assert();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAssert(this,arg);
}
//return name of builtin
public String getName(){
return "assert";
}
}
public static class Nargoutchk extends AbstractMatlabSystemFunction {
//returns the singleton instance of this class
private static Nargoutchk singleton = null;
public static Nargoutchk getInstance(){
if (singleton == null) singleton = new Nargoutchk();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseNargoutchk(this,arg);
}
//return name of builtin
public String getName(){
return "nargoutchk";
}
}
public static class Nargchk extends AbstractMatlabSystemFunction {
//returns the singleton instance of this class
private static Nargchk singleton = null;
public static Nargchk getInstance(){
if (singleton == null) singleton = new Nargchk();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseNargchk(this,arg);
}
//return name of builtin
public String getName(){
return "nargchk";
}
}
public static class Str2func extends AbstractMatlabSystemFunction {
//returns the singleton instance of this class
private static Str2func singleton = null;
public static Str2func getInstance(){
if (singleton == null) singleton = new Str2func();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseStr2func(this,arg);
}
//return name of builtin
public String getName(){
return "str2func";
}
}
public static class Pause extends AbstractMatlabSystemFunction {
//returns the singleton instance of this class
private static Pause singleton = null;
public static Pause getInstance(){
if (singleton == null) singleton = new Pause();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.casePause(this,arg);
}
//return name of builtin
public String getName(){
return "pause";
}
}
public static abstract class AbstractDynamicMatlabFunction extends AbstractMatlabSystemFunction {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractDynamicMatlabFunction(this,arg);
}
}
public static class Eval extends AbstractDynamicMatlabFunction {
//returns the singleton instance of this class
private static Eval singleton = null;
public static Eval getInstance(){
if (singleton == null) singleton = new Eval();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseEval(this,arg);
}
//return name of builtin
public String getName(){
return "eval";
}
}
public static class Evalin extends AbstractDynamicMatlabFunction {
//returns the singleton instance of this class
private static Evalin singleton = null;
public static Evalin getInstance(){
if (singleton == null) singleton = new Evalin();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseEvalin(this,arg);
}
//return name of builtin
public String getName(){
return "evalin";
}
}
public static class Feval extends AbstractDynamicMatlabFunction {
//returns the singleton instance of this class
private static Feval singleton = null;
public static Feval getInstance(){
if (singleton == null) singleton = new Feval();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseFeval(this,arg);
}
//return name of builtin
public String getName(){
return "feval";
}
}
public static class Assignin extends AbstractDynamicMatlabFunction {
//returns the singleton instance of this class
private static Assignin singleton = null;
public static Assignin getInstance(){
if (singleton == null) singleton = new Assignin();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAssignin(this,arg);
}
//return name of builtin
public String getName(){
return "assignin";
}
}
public static class Inputname extends AbstractDynamicMatlabFunction {
//returns the singleton instance of this class
private static Inputname singleton = null;
public static Inputname getInstance(){
if (singleton == null) singleton = new Inputname();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseInputname(this,arg);
}
//return name of builtin
public String getName(){
return "inputname";
}
}
public static abstract class AbstractMatlabEnvironmentFunction extends AbstractMatlabSystemFunction {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractMatlabEnvironmentFunction(this,arg);
}
}
public static class Import extends AbstractMatlabEnvironmentFunction {
//returns the singleton instance of this class
private static Import singleton = null;
public static Import getInstance(){
if (singleton == null) singleton = new Import();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseImport(this,arg);
}
//return name of builtin
public String getName(){
return "import";
}
}
public static class Cd extends AbstractMatlabEnvironmentFunction {
//returns the singleton instance of this class
private static Cd singleton = null;
public static Cd getInstance(){
if (singleton == null) singleton = new Cd();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseCd(this,arg);
}
//return name of builtin
public String getName(){
return "cd";
}
}
public static class Exist extends AbstractMatlabEnvironmentFunction {
//returns the singleton instance of this class
private static Exist singleton = null;
public static Exist getInstance(){
if (singleton == null) singleton = new Exist();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseExist(this,arg);
}
//return name of builtin
public String getName(){
return "exist";
}
}
public static class Matlabroot extends AbstractMatlabEnvironmentFunction {
//returns the singleton instance of this class
private static Matlabroot singleton = null;
public static Matlabroot getInstance(){
if (singleton == null) singleton = new Matlabroot();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseMatlabroot(this,arg);
}
//return name of builtin
public String getName(){
return "matlabroot";
}
}
public static class Whos extends AbstractMatlabEnvironmentFunction {
//returns the singleton instance of this class
private static Whos singleton = null;
public static Whos getInstance(){
if (singleton == null) singleton = new Whos();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseWhos(this,arg);
}
//return name of builtin
public String getName(){
return "whos";
}
}
public static class Which extends AbstractMatlabEnvironmentFunction {
//returns the singleton instance of this class
private static Which singleton = null;
public static Which getInstance(){
if (singleton == null) singleton = new Which();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseWhich(this,arg);
}
//return name of builtin
public String getName(){
return "which";
}
}
public static class Version extends AbstractMatlabEnvironmentFunction {
//returns the singleton instance of this class
private static Version singleton = null;
public static Version getInstance(){
if (singleton == null) singleton = new Version();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseVersion(this,arg);
}
//return name of builtin
public String getName(){
return "version";
}
}
public static class Clear extends AbstractMatlabEnvironmentFunction {
//returns the singleton instance of this class
private static Clear singleton = null;
public static Clear getInstance(){
if (singleton == null) singleton = new Clear();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseClear(this,arg);
}
//return name of builtin
public String getName(){
return "clear";
}
}
public static class Nargin extends AbstractMatlabEnvironmentFunction {
//returns the singleton instance of this class
private static Nargin singleton = null;
public static Nargin getInstance(){
if (singleton == null) singleton = new Nargin();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseNargin(this,arg);
}
//return name of builtin
public String getName(){
return "nargin";
}
}
public static class Nargout extends AbstractMatlabEnvironmentFunction {
//returns the singleton instance of this class
private static Nargout singleton = null;
public static Nargout getInstance(){
if (singleton == null) singleton = new Nargout();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseNargout(this,arg);
}
//return name of builtin
public String getName(){
return "nargout";
}
}
public static class Methods extends AbstractMatlabEnvironmentFunction {
//returns the singleton instance of this class
private static Methods singleton = null;
public static Methods getInstance(){
if (singleton == null) singleton = new Methods();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseMethods(this,arg);
}
//return name of builtin
public String getName(){
return "methods";
}
}
public static class Fieldnames extends AbstractMatlabEnvironmentFunction {
//returns the singleton instance of this class
private static Fieldnames singleton = null;
public static Fieldnames getInstance(){
if (singleton == null) singleton = new Fieldnames();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseFieldnames(this,arg);
}
//return name of builtin
public String getName(){
return "fieldnames";
}
}
public static abstract class AbstractReportFunction extends AbstractImpureFunction {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractReportFunction(this,arg);
}
}
public static class Disp extends AbstractReportFunction {
//returns the singleton instance of this class
private static Disp singleton = null;
public static Disp getInstance(){
if (singleton == null) singleton = new Disp();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseDisp(this,arg);
}
//return name of builtin
public String getName(){
return "disp";
}
}
public static class Display extends AbstractReportFunction {
//returns the singleton instance of this class
private static Display singleton = null;
public static Display getInstance(){
if (singleton == null) singleton = new Display();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseDisplay(this,arg);
}
//return name of builtin
public String getName(){
return "display";
}
}
public static class Clc extends AbstractReportFunction {
//returns the singleton instance of this class
private static Clc singleton = null;
public static Clc getInstance(){
if (singleton == null) singleton = new Clc();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseClc(this,arg);
}
//return name of builtin
public String getName(){
return "clc";
}
}
public static class Error extends AbstractReportFunction {
//returns the singleton instance of this class
private static Error singleton = null;
public static Error getInstance(){
if (singleton == null) singleton = new Error();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseError(this,arg);
}
//return name of builtin
public String getName(){
return "error";
}
}
public static class Warning extends AbstractReportFunction {
//returns the singleton instance of this class
private static Warning singleton = null;
public static Warning getInstance(){
if (singleton == null) singleton = new Warning();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseWarning(this,arg);
}
//return name of builtin
public String getName(){
return "warning";
}
}
public static class Echo extends AbstractReportFunction {
//returns the singleton instance of this class
private static Echo singleton = null;
public static Echo getInstance(){
if (singleton == null) singleton = new Echo();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseEcho(this,arg);
}
//return name of builtin
public String getName(){
return "echo";
}
}
public static class Diary extends AbstractReportFunction {
//returns the singleton instance of this class
private static Diary singleton = null;
public static Diary getInstance(){
if (singleton == null) singleton = new Diary();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseDiary(this,arg);
}
//return name of builtin
public String getName(){
return "diary";
}
}
public static class Message extends AbstractReportFunction {
//returns the singleton instance of this class
private static Message singleton = null;
public static Message getInstance(){
if (singleton == null) singleton = new Message();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseMessage(this,arg);
}
//return name of builtin
public String getName(){
return "message";
}
}
public static class Lastwarn extends AbstractReportFunction {
//returns the singleton instance of this class
private static Lastwarn singleton = null;
public static Lastwarn getInstance(){
if (singleton == null) singleton = new Lastwarn();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseLastwarn(this,arg);
}
//return name of builtin
public String getName(){
return "lastwarn";
}
}
public static class Lasterror extends AbstractReportFunction {
//returns the singleton instance of this class
private static Lasterror singleton = null;
public static Lasterror getInstance(){
if (singleton == null) singleton = new Lasterror();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseLasterror(this,arg);
}
//return name of builtin
public String getName(){
return "lasterror";
}
}
public static class Format extends AbstractReportFunction {
//returns the singleton instance of this class
private static Format singleton = null;
public static Format getInstance(){
if (singleton == null) singleton = new Format();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseFormat(this,arg);
}
//return name of builtin
public String getName(){
return "format";
}
}
public static abstract class AbstractRandomFunction extends AbstractImpureFunction {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractRandomFunction(this,arg);
}
}
public static class Rand extends AbstractRandomFunction {
//returns the singleton instance of this class
private static Rand singleton = null;
public static Rand getInstance(){
if (singleton == null) singleton = new Rand();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseRand(this,arg);
}
//return name of builtin
public String getName(){
return "rand";
}
}
public static class Randi extends AbstractRandomFunction {
//returns the singleton instance of this class
private static Randi singleton = null;
public static Randi getInstance(){
if (singleton == null) singleton = new Randi();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseRandi(this,arg);
}
//return name of builtin
public String getName(){
return "randi";
}
}
public static class Randn extends AbstractRandomFunction {
//returns the singleton instance of this class
private static Randn singleton = null;
public static Randn getInstance(){
if (singleton == null) singleton = new Randn();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseRandn(this,arg);
}
//return name of builtin
public String getName(){
return "randn";
}
}
public static abstract class AbstractSystemFunction extends AbstractImpureFunction {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractSystemFunction(this,arg);
}
}
public static class Computer extends AbstractSystemFunction {
//returns the singleton instance of this class
private static Computer singleton = null;
public static Computer getInstance(){
if (singleton == null) singleton = new Computer();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseComputer(this,arg);
}
//return name of builtin
public String getName(){
return "computer";
}
}
public static class Beep extends AbstractSystemFunction {
//returns the singleton instance of this class
private static Beep singleton = null;
public static Beep getInstance(){
if (singleton == null) singleton = new Beep();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseBeep(this,arg);
}
//return name of builtin
public String getName(){
return "beep";
}
}
public static class Dir extends AbstractSystemFunction {
//returns the singleton instance of this class
private static Dir singleton = null;
public static Dir getInstance(){
if (singleton == null) singleton = new Dir();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseDir(this,arg);
}
//return name of builtin
public String getName(){
return "dir";
}
}
public static abstract class AbstractOperatingSystemCallFunction extends AbstractSystemFunction {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractOperatingSystemCallFunction(this,arg);
}
}
public static class Unix extends AbstractOperatingSystemCallFunction {
//returns the singleton instance of this class
private static Unix singleton = null;
public static Unix getInstance(){
if (singleton == null) singleton = new Unix();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseUnix(this,arg);
}
//return name of builtin
public String getName(){
return "unix";
}
}
public static class Dos extends AbstractOperatingSystemCallFunction {
//returns the singleton instance of this class
private static Dos singleton = null;
public static Dos getInstance(){
if (singleton == null) singleton = new Dos();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseDos(this,arg);
}
//return name of builtin
public String getName(){
return "dos";
}
}
public static class System extends AbstractOperatingSystemCallFunction {
//returns the singleton instance of this class
private static System singleton = null;
public static System getInstance(){
if (singleton == null) singleton = new System();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseSystem(this,arg);
}
//return name of builtin
public String getName(){
return "system";
}
}
public static abstract class AbstractIoFunction extends AbstractSystemFunction {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractIoFunction(this,arg);
}
}
public static class Load extends AbstractIoFunction {
//returns the singleton instance of this class
private static Load singleton = null;
public static Load getInstance(){
if (singleton == null) singleton = new Load();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseLoad(this,arg);
}
//return name of builtin
public String getName(){
return "load";
}
}
public static class Save extends AbstractIoFunction {
//returns the singleton instance of this class
private static Save singleton = null;
public static Save getInstance(){
if (singleton == null) singleton = new Save();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseSave(this,arg);
}
//return name of builtin
public String getName(){
return "save";
}
}
public static class Input extends AbstractIoFunction {
//returns the singleton instance of this class
private static Input singleton = null;
public static Input getInstance(){
if (singleton == null) singleton = new Input();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseInput(this,arg);
}
//return name of builtin
public String getName(){
return "input";
}
}
public static class Textscan extends AbstractIoFunction {
//returns the singleton instance of this class
private static Textscan singleton = null;
public static Textscan getInstance(){
if (singleton == null) singleton = new Textscan();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseTextscan(this,arg);
}
//return name of builtin
public String getName(){
return "textscan";
}
}
public static abstract class AbstractPosixIoFunction extends AbstractIoFunction {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractPosixIoFunction(this,arg);
}
}
public static class Sprintf extends AbstractPosixIoFunction {
//returns the singleton instance of this class
private static Sprintf singleton = null;
public static Sprintf getInstance(){
if (singleton == null) singleton = new Sprintf();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseSprintf(this,arg);
}
//return name of builtin
public String getName(){
return "sprintf";
}
}
public static class Sscanf extends AbstractPosixIoFunction {
//returns the singleton instance of this class
private static Sscanf singleton = null;
public static Sscanf getInstance(){
if (singleton == null) singleton = new Sscanf();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseSscanf(this,arg);
}
//return name of builtin
public String getName(){
return "sscanf";
}
}
public static class Fprintf extends AbstractPosixIoFunction {
//returns the singleton instance of this class
private static Fprintf singleton = null;
public static Fprintf getInstance(){
if (singleton == null) singleton = new Fprintf();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseFprintf(this,arg);
}
//return name of builtin
public String getName(){
return "fprintf";
}
}
public static class Ftell extends AbstractPosixIoFunction {
//returns the singleton instance of this class
private static Ftell singleton = null;
public static Ftell getInstance(){
if (singleton == null) singleton = new Ftell();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseFtell(this,arg);
}
//return name of builtin
public String getName(){
return "ftell";
}
}
public static class Ferror extends AbstractPosixIoFunction {
//returns the singleton instance of this class
private static Ferror singleton = null;
public static Ferror getInstance(){
if (singleton == null) singleton = new Ferror();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseFerror(this,arg);
}
//return name of builtin
public String getName(){
return "ferror";
}
}
public static class Fopen extends AbstractPosixIoFunction {
//returns the singleton instance of this class
private static Fopen singleton = null;
public static Fopen getInstance(){
if (singleton == null) singleton = new Fopen();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseFopen(this,arg);
}
//return name of builtin
public String getName(){
return "fopen";
}
}
public static class Fread extends AbstractPosixIoFunction {
//returns the singleton instance of this class
private static Fread singleton = null;
public static Fread getInstance(){
if (singleton == null) singleton = new Fread();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseFread(this,arg);
}
//return name of builtin
public String getName(){
return "fread";
}
}
public static class Frewind extends AbstractPosixIoFunction {
//returns the singleton instance of this class
private static Frewind singleton = null;
public static Frewind getInstance(){
if (singleton == null) singleton = new Frewind();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseFrewind(this,arg);
}
//return name of builtin
public String getName(){
return "frewind";
}
}
public static class Fscanf extends AbstractPosixIoFunction {
//returns the singleton instance of this class
private static Fscanf singleton = null;
public static Fscanf getInstance(){
if (singleton == null) singleton = new Fscanf();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseFscanf(this,arg);
}
//return name of builtin
public String getName(){
return "fscanf";
}
}
public static class Fseek extends AbstractPosixIoFunction {
//returns the singleton instance of this class
private static Fseek singleton = null;
public static Fseek getInstance(){
if (singleton == null) singleton = new Fseek();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseFseek(this,arg);
}
//return name of builtin
public String getName(){
return "fseek";
}
}
public static class Fwrite extends AbstractPosixIoFunction {
//returns the singleton instance of this class
private static Fwrite singleton = null;
public static Fwrite getInstance(){
if (singleton == null) singleton = new Fwrite();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseFwrite(this,arg);
}
//return name of builtin
public String getName(){
return "fwrite";
}
}
public static class Fgetl extends AbstractPosixIoFunction {
//returns the singleton instance of this class
private static Fgetl singleton = null;
public static Fgetl getInstance(){
if (singleton == null) singleton = new Fgetl();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseFgetl(this,arg);
}
//return name of builtin
public String getName(){
return "fgetl";
}
}
public static class Fgets extends AbstractPosixIoFunction {
//returns the singleton instance of this class
private static Fgets singleton = null;
public static Fgets getInstance(){
if (singleton == null) singleton = new Fgets();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseFgets(this,arg);
}
//return name of builtin
public String getName(){
return "fgets";
}
}
public static class Fclose extends AbstractPosixIoFunction {
//returns the singleton instance of this class
private static Fclose singleton = null;
public static Fclose getInstance(){
if (singleton == null) singleton = new Fclose();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseFclose(this,arg);
}
//return name of builtin
public String getName(){
return "fclose";
}
}
public static abstract class AbstractNotABuiltin extends AbstractRoot {
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseAbstractNotABuiltin(this,arg);
}
}
public static class Imwrite extends AbstractNotABuiltin {
//returns the singleton instance of this class
private static Imwrite singleton = null;
public static Imwrite getInstance(){
if (singleton == null) singleton = new Imwrite();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseImwrite(this,arg);
}
//return name of builtin
public String getName(){
return "imwrite";
}
}
public static class Sparse extends AbstractNotABuiltin {
//returns the singleton instance of this class
private static Sparse singleton = null;
public static Sparse getInstance(){
if (singleton == null) singleton = new Sparse();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseSparse(this,arg);
}
//return name of builtin
public String getName(){
return "sparse";
}
}
public static class Var extends AbstractNotABuiltin {
//returns the singleton instance of this class
private static Var singleton = null;
public static Var getInstance(){
if (singleton == null) singleton = new Var();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseVar(this,arg);
}
//return name of builtin
public String getName(){
return "var";
}
}
public static class Std extends AbstractNotABuiltin {
//returns the singleton instance of this class
private static Std singleton = null;
public static Std getInstance(){
if (singleton == null) singleton = new Std();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseStd(this,arg);
}
//return name of builtin
public String getName(){
return "std";
}
}
public static class Realmax extends AbstractNotABuiltin {
//returns the singleton instance of this class
private static Realmax singleton = null;
public static Realmax getInstance(){
if (singleton == null) singleton = new Realmax();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseRealmax(this,arg);
}
//return name of builtin
public String getName(){
return "realmax";
}
}
public static class Histc extends AbstractNotABuiltin {
//returns the singleton instance of this class
private static Histc singleton = null;
public static Histc getInstance(){
if (singleton == null) singleton = new Histc();
return singleton;
}
//visit visitor
public <Arg,Ret> Ret visit(BuiltinVisitor<Arg,Ret> visitor, Arg arg){
return visitor.caseHistc(this,arg);
}
//return name of builtin
public String getName(){
return "histc";
}
}
}
|
package asciiPanel;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.awt.image.LookupOp;
import java.awt.image.ShortLookupTable;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
/**
* This simulates a code page 437 ASCII terminal display.
* @author Trystan Spangler
*/
public class AsciiPanel extends JPanel {
private static final long serialVersionUID = -4167851861147593092L;
/**
* The color black (pure black).
*/
public static Color black = new Color(0, 0, 0);
/**
* The color red.
*/
public static Color red = new Color(128, 0, 0);
/**
* The color green.
*/
public static Color green = new Color(0, 128, 0);
/**
* The color yellow.
*/
public static Color yellow = new Color(128, 128, 0);
/**
* The color blue.
*/
public static Color blue = new Color(0, 0, 128);
/**
* The color magenta.
*/
public static Color magenta = new Color(128, 0, 128);
/**
* The color cyan.
*/
public static Color cyan = new Color(0, 128, 128);
/**
* The color white (light gray).
*/
public static Color white = new Color(192, 192, 192);
/**
* A brighter black (dark gray).
*/
public static Color brightBlack = new Color(128, 128, 128);
/**
* A brighter red.
*/
public static Color brightRed = new Color(255, 0, 0);
/**
* A brighter green.
*/
public static Color brightGreen = new Color(0, 255, 0);
/**
* A brighter yellow.
*/
public static Color brightYellow = new Color(255, 255, 0);
/**
* A brighter blue.
*/
public static Color brightBlue = new Color(0, 0, 255);
/**
* A brighter magenta.
*/
public static Color brightMagenta = new Color(255, 0, 255);
/**
* A brighter cyan.
*/
public static Color brightCyan = new Color(0, 255, 255);
/**
* A brighter white (pure white).
*/
public static Color brightWhite = new Color(255, 255, 255);
private Image offscreenBuffer;
private Graphics offscreenGraphics;
private int widthInCharacters;
private int heightInCharacters;
private int charWidth = 9;
private int charHeight = 16;
private Color defaultBackgroundColor;
private Color defaultForegroundColor;
private int cursorX;
private int cursorY;
private BufferedImage glyphSprite;
private BufferedImage[] glyphs;
private char[][] chars;
private Color[][] backgroundColors;
private Color[][] foregroundColors;
private char[][] oldChars;
private Color[][] oldBackgroundColors;
private Color[][] oldForegroundColors;
/**
* Gets the height, in pixels, of a character.
* @return
*/
public int getCharHeight() {
return charHeight;
}
/**
* Gets the width, in pixels, of a character.
* @return
*/
public int getCharWidth() {
return charWidth;
}
/**
* Gets the height in characters.
* A standard terminal is 24 characters high.
* @return
*/
public int getHeightInCharacters() {
return heightInCharacters;
}
/**
* Gets the width in characters.
* A standard terminal is 80 characters wide.
* @return
*/
public int getWidthInCharacters() {
return widthInCharacters;
}
/**
* Gets the distance from the left new text will be written to.
* @return
*/
public int getCursorX() {
return cursorX;
}
/**
* Sets the distance from the left new text will be written to.
* This should be equal to or greater than 0 and less than the the width in characters.
* @param cursorX the distance from the left new text should be written to
*/
public void setCursorX(int cursorX) {
if (cursorX < 0 || cursorX >= widthInCharacters)
throw new IllegalArgumentException("cursorX " + cursorX + " must be within range [0," + widthInCharacters + ")." );
this.cursorX = cursorX;
}
/**
* Gets the distance from the top new text will be written to.
* @return
*/
public int getCursorY() {
return cursorY;
}
/**
* Sets the distance from the top new text will be written to.
* This should be equal to or greater than 0 and less than the the height in characters.
* @param cursorY the distance from the top new text should be written to
*/
public void setCursorY(int cursorY) {
if (cursorY < 0 || cursorY >= heightInCharacters)
throw new IllegalArgumentException("cursorY " + cursorY + " must be within range [0," + heightInCharacters + ")." );
this.cursorY = cursorY;
}
/**
* Sets the x and y position of where new text will be written to. The origin (0,0) is the upper left corner.
* The x should be equal to or greater than 0 and less than the the width in characters.
* The y should be equal to or greater than 0 and less than the the height in characters.
* @param x the distance from the left new text should be written to
* @param y the distance from the top new text should be written to
*/
public void setCursorPosition(int x, int y) {
setCursorX(x);
setCursorY(y);
}
/**
* Gets the default background color that is used when writing new text.
* @return
*/
public Color getDefaultBackgroundColor() {
return defaultBackgroundColor;
}
/**
* Sets the default background color that is used when writing new text.
* @param defaultBackgroundColor
*/
public void setDefaultBackgroundColor(Color defaultBackgroundColor) {
if (defaultBackgroundColor == null)
throw new NullPointerException("defaultBackgroundColor must not be null.");
this.defaultBackgroundColor = defaultBackgroundColor;
}
/**
* Gets the default foreground color that is used when writing new text.
* @return
*/
public Color getDefaultForegroundColor() {
return defaultForegroundColor;
}
/**
* Sets the default foreground color that is used when writing new text.
* @param defaultForegroundColor
*/
public void setDefaultForegroundColor(Color defaultForegroundColor) {
if (defaultForegroundColor == null)
throw new NullPointerException("defaultForegroundColor must not be null.");
this.defaultForegroundColor = defaultForegroundColor;
}
/**
* Class constructor.
* Default size is 80x24.
*/
public AsciiPanel() {
this(80, 24);
}
/**
* Class constructor specifying the width and height in characters.
* @param width
* @param height
*/
public AsciiPanel(int width, int height) {
super();
if (width < 1)
throw new IllegalArgumentException("width " + width + " must be greater than 0." );
if (height < 1)
throw new IllegalArgumentException("height " + height + " must be greater than 0." );
widthInCharacters = width;
heightInCharacters = height;
setPreferredSize(new Dimension(charWidth * widthInCharacters, charHeight * heightInCharacters));
defaultBackgroundColor = black;
defaultForegroundColor = white;
chars = new char[widthInCharacters][heightInCharacters];
backgroundColors = new Color[widthInCharacters][heightInCharacters];
foregroundColors = new Color[widthInCharacters][heightInCharacters];
oldChars = new char[widthInCharacters][heightInCharacters];
oldBackgroundColors = new Color[widthInCharacters][heightInCharacters];
oldForegroundColors = new Color[widthInCharacters][heightInCharacters];
glyphs = new BufferedImage[256];
loadGlyphs();
AsciiPanel.this.clear();
}
@Override
public void update(Graphics g) {
paint(g);
}
@Override
public void paint(Graphics g) {
if (g == null)
throw new NullPointerException();
if (offscreenBuffer == null){
offscreenBuffer = createImage(this.getWidth(), this.getHeight());
offscreenGraphics = offscreenBuffer.getGraphics();
}
for (int x = 0; x < widthInCharacters; x++) {
for (int y = 0; y < heightInCharacters; y++) {
if (oldBackgroundColors[x][y] == backgroundColors[x][y]
&& oldForegroundColors[x][y] == foregroundColors[x][y]
&& oldChars[x][y] == chars[x][y])
continue;
Color bg = backgroundColors[x][y];
Color fg = foregroundColors[x][y];
LookupOp op = setColors(bg, fg);
BufferedImage img = op.filter(glyphs[chars[x][y]], null);
offscreenGraphics.drawImage(img, x * charWidth, y * charHeight, null);
oldBackgroundColors[x][y] = backgroundColors[x][y];
oldForegroundColors[x][y] = foregroundColors[x][y];
oldChars[x][y] = chars[x][y];
}
}
g.drawImage(offscreenBuffer,0,0,this);
}
private void loadGlyphs() {
try {
glyphSprite = ImageIO.read(AsciiPanel.class.getResource("cp437.png"));
} catch (IOException e) {
System.err.println("loadGlyphs(): " + e.getMessage());
}
for (int i = 0; i < 256; i++) {
int sx = (i % 32) * charWidth + 8;
int sy = (i / 32) * charHeight + 8;
glyphs[i] = new BufferedImage(charWidth, charHeight, BufferedImage.TYPE_INT_ARGB);
glyphs[i].getGraphics().drawImage(glyphSprite, 0, 0, charWidth, charHeight, sx, sy, sx + charWidth, sy + charHeight, null);
}
}
/**
* Create a <code>LookupOp</code> object (lookup table) mapping the original
* pixels to the background and foreground colors, respectively.
* @param bgColor the background color
* @param fgColor the foreground color
* @return the <code>LookupOp</code> object (lookup table)
*/
private LookupOp setColors(Color bgColor, Color fgColor) {
short[] a = new short[256];
short[] r = new short[256];
short[] g = new short[256];
short[] b = new short[256];
byte bgr = (byte) (bgColor.getRed());
byte bgg = (byte) (bgColor.getGreen());
byte bgb = (byte) (bgColor.getBlue());
byte fgr = (byte) (fgColor.getRed());
byte fgg = (byte) (fgColor.getGreen());
byte fgb = (byte) (fgColor.getBlue());
for (int i = 0; i < 256; i++) {
if (i == 0) {
a[i] = (byte) 255;
r[i] = bgr;
g[i] = bgg;
b[i] = bgb;
} else {
a[i] = (byte) 255;
r[i] = fgr;
g[i] = fgg;
b[i] = fgb;
}
}
short[][] table = {r, g, b, a};
return new LookupOp(new ShortLookupTable(0, table), null);
}
/**
* Clear the entire screen to whatever the default background color is.
* @return this for convenient chaining of method calls
*/
public AsciiPanel clear() {
return clear(' ', 0, 0, widthInCharacters, heightInCharacters, defaultForegroundColor, defaultBackgroundColor);
}
/**
* Clear the entire screen with the specified character and whatever the default foreground and background colors are.
* @param character the character to write
* @return this for convenient chaining of method calls
*/
public AsciiPanel clear(char character) {
if (character < 0 || character >= glyphs.length)
throw new IllegalArgumentException("character " + character + " must be within range [0," + glyphs.length + "]." );
return clear(character, 0, 0, widthInCharacters, heightInCharacters, defaultForegroundColor, defaultBackgroundColor);
}
/**
* Clear the entire screen with the specified character and whatever the specified foreground and background colors are.
* @param character the character to write
* @param foreground the foreground color or null to use the default
* @param background the background color or null to use the default
* @return this for convenient chaining of method calls
*/
public AsciiPanel clear(char character, Color foreground, Color background) {
if (character < 0 || character >= glyphs.length)
throw new IllegalArgumentException("character " + character + " must be within range [0," + glyphs.length + "]." );
return clear(character, 0, 0, widthInCharacters, heightInCharacters, foreground, background);
}
/**
* Clear the section of the screen with the specified character and whatever the default foreground and background colors are.
* @param character the character to write
* @param x the distance from the left to begin writing from
* @param y the distance from the top to begin writing from
* @param width the height of the section to clear
* @param height the width of the section to clear
* @return this for convenient chaining of method calls
*/
public AsciiPanel clear(char character, int x, int y, int width, int height) {
if (character < 0 || character >= glyphs.length)
throw new IllegalArgumentException("character " + character + " must be within range [0," + glyphs.length + "]." );
if (x < 0 || x >= widthInCharacters)
throw new IllegalArgumentException("x " + x + " must be within range [0," + widthInCharacters + ")." );
if (y < 0 || y >= heightInCharacters)
throw new IllegalArgumentException("y " + y + " must be within range [0," + heightInCharacters + ")." );
if (width < 1)
throw new IllegalArgumentException("width " + width + " must be greater than 0." );
if (height < 1)
throw new IllegalArgumentException("height " + height + " must be greater than 0." );
if (x + width > widthInCharacters)
throw new IllegalArgumentException("x + width " + (x + width) + " must be less than " + (widthInCharacters + 1) + "." );
if (y + height > heightInCharacters)
throw new IllegalArgumentException("y + height " + (y + height) + " must be less than " + (heightInCharacters + 1) + "." );
return clear(character, x, y, width, height, defaultForegroundColor, defaultBackgroundColor);
}
/**
* Clear the section of the screen with the specified character and whatever the specified foreground and background colors are.
* @param character the character to write
* @param x the distance from the left to begin writing from
* @param y the distance from the top to begin writing from
* @param width the height of the section to clear
* @param height the width of the section to clear
* @param foreground the foreground color or null to use the default
* @param background the background color or null to use the default
* @return this for convenient chaining of method calls
*/
public AsciiPanel clear(char character, int x, int y, int width, int height, Color foreground, Color background) {
if (character < 0 || character >= glyphs.length)
throw new IllegalArgumentException("character " + character + " must be within range [0," + glyphs.length + "]." );
if (x < 0 || x >= widthInCharacters)
throw new IllegalArgumentException("x " + x + " must be within range [0," + widthInCharacters + ")" );
if (y < 0 || y >= heightInCharacters)
throw new IllegalArgumentException("y " + y + " must be within range [0," + heightInCharacters + ")" );
if (width < 1)
throw new IllegalArgumentException("width " + width + " must be greater than 0." );
if (height < 1)
throw new IllegalArgumentException("height " + height + " must be greater than 0." );
if (x + width > widthInCharacters)
throw new IllegalArgumentException("x + width " + (x + width) + " must be less than " + (widthInCharacters + 1) + "." );
if (y + height > heightInCharacters)
throw new IllegalArgumentException("y + height " + (y + height) + " must be less than " + (heightInCharacters + 1) + "." );
for (int xo = x; xo < x + width; xo++) {
for (int yo = y; yo < y + height; yo++) {
write(character, xo, yo, foreground, background);
}
}
return this;
}
/**
* Write a character to the cursor's position.
* This updates the cursor's position.
* @param character the character to write
* @return this for convenient chaining of method calls
*/
public AsciiPanel write(char character) {
if (character < 0 || character >= glyphs.length)
throw new IllegalArgumentException("character " + character + " must be within range [0," + glyphs.length + "]." );
return write(character, cursorX, cursorY, defaultForegroundColor, defaultBackgroundColor);
}
/**
* Write a character to the cursor's position with the specified foreground color.
* This updates the cursor's position but not the default foreground color.
* @param character the character to write
* @param foreground the foreground color or null to use the default
* @return this for convenient chaining of method calls
*/
public AsciiPanel write(char character, Color foreground) {
if (character < 0 || character >= glyphs.length)
throw new IllegalArgumentException("character " + character + " must be within range [0," + glyphs.length + "]." );
return write(character, cursorX, cursorY, foreground, defaultBackgroundColor);
}
/**
* Write a character to the cursor's position with the specified foreground and background colors.
* This updates the cursor's position but not the default foreground or background colors.
* @param character the character to write
* @param foreground the foreground color or null to use the default
* @param background the background color or null to use the default
* @return this for convenient chaining of method calls
*/
public AsciiPanel write(char character, Color foreground, Color background) {
if (character < 0 || character >= glyphs.length)
throw new IllegalArgumentException("character " + character + " must be within range [0," + glyphs.length + "]." );
return write(character, cursorX, cursorY, foreground, background);
}
/**
* Write a character to the specified position.
* This updates the cursor's position.
* @param character the character to write
* @param x the distance from the left to begin writing from
* @param y the distance from the top to begin writing from
* @return this for convenient chaining of method calls
*/
public AsciiPanel write(char character, int x, int y) {
if (character < 0 || character >= glyphs.length)
throw new IllegalArgumentException("character " + character + " must be within range [0," + glyphs.length + "]." );
if (x < 0 || x >= widthInCharacters)
throw new IllegalArgumentException("x " + x + " must be within range [0," + widthInCharacters + ")" );
if (y < 0 || y >= heightInCharacters)
throw new IllegalArgumentException("y " + y + " must be within range [0," + heightInCharacters + ")" );
return write(character, x, y, defaultForegroundColor, defaultBackgroundColor);
}
/**
* Write a character to the specified position with the specified foreground color.
* This updates the cursor's position but not the default foreground color.
* @param character the character to write
* @param x the distance from the left to begin writing from
* @param y the distance from the top to begin writing from
* @param foreground the foreground color or null to use the default
* @return this for convenient chaining of method calls
*/
public AsciiPanel write(char character, int x, int y, Color foreground) {
if (character < 0 || character >= glyphs.length)
throw new IllegalArgumentException("character " + character + " must be within range [0," + glyphs.length + "]." );
if (x < 0 || x >= widthInCharacters)
throw new IllegalArgumentException("x " + x + " must be within range [0," + widthInCharacters + ")" );
if (y < 0 || y >= heightInCharacters)
throw new IllegalArgumentException("y " + y + " must be within range [0," + heightInCharacters + ")" );
return write(character, x, y, foreground, defaultBackgroundColor);
}
/**
* Write a character to the specified position with the specified foreground and background colors.
* This updates the cursor's position but not the default foreground or background colors.
* @param character the character to write
* @param x the distance from the left to begin writing from
* @param y the distance from the top to begin writing from
* @param foreground the foreground color or null to use the default
* @param background the background color or null to use the default
* @return this for convenient chaining of method calls
*/
public AsciiPanel write(char character, int x, int y, Color foreground, Color background) {
if (character < 0 || character >= glyphs.length)
throw new IllegalArgumentException("character " + character + " must be within range [0," + glyphs.length + "]." );
if (x < 0 || x >= widthInCharacters)
throw new IllegalArgumentException("x " + x + " must be within range [0," + widthInCharacters + ")" );
if (y < 0 || y >= heightInCharacters)
throw new IllegalArgumentException("y " + y + " must be within range [0," + heightInCharacters + ")" );
if (foreground == null) foreground = defaultForegroundColor;
if (background == null) background = defaultBackgroundColor;
chars[x][y] = character;
foregroundColors[x][y] = foreground;
backgroundColors[x][y] = background;
cursorX = x + 1;
cursorY = y;
return this;
}
/**
* Write a string to the cursor's position.
* This updates the cursor's position.
* @param string the string to write
* @return this for convenient chaining of method calls
*/
public AsciiPanel write(String string) {
if (string == null)
throw new NullPointerException("string must not be null" );
if (cursorX + string.length() >= widthInCharacters)
throw new IllegalArgumentException("cursorX + string.length() " + (cursorX + string.length()) + " must be less than " + widthInCharacters + "." );
return write(string, cursorX, cursorY, defaultForegroundColor, defaultBackgroundColor);
}
/**
* Write a string to the cursor's position with the specified foreground color.
* This updates the cursor's position but not the default foreground color.
* @param string the string to write
* @param foreground the foreground color or null to use the default
* @return this for convenient chaining of method calls
*/
public AsciiPanel write(String string, Color foreground) {
if (string == null)
throw new NullPointerException("string must not be null" );
if (cursorX + string.length() >= widthInCharacters)
throw new IllegalArgumentException("cursorX + string.length() " + (cursorX + string.length()) + " must be less than " + widthInCharacters + "." );
return write(string, cursorX, cursorY, foreground, defaultBackgroundColor);
}
/**
* Write a string to the cursor's position with the specified foreground and background colors.
* This updates the cursor's position but not the default foreground or background colors.
* @param string the string to write
* @param foreground the foreground color or null to use the default
* @param background the background color or null to use the default
* @return this for convenient chaining of method calls
*/
public AsciiPanel write(String string, Color foreground, Color background) {
if (string == null)
throw new NullPointerException("string must not be null" );
if (cursorX + string.length() >= widthInCharacters)
throw new IllegalArgumentException("cursorX + string.length() " + (cursorX + string.length()) + " must be less than " + widthInCharacters + "." );
return write(string, cursorX, cursorY, foreground, background);
}
/**
* Write a string to the specified position.
* This updates the cursor's position.
* @param string the string to write
* @param x the distance from the left to begin writing from
* @param y the distance from the top to begin writing from
* @return this for convenient chaining of method calls
*/
public AsciiPanel write(String string, int x, int y) {
if (string == null)
throw new NullPointerException("string must not be null" );
if (x + string.length() >= widthInCharacters)
throw new IllegalArgumentException("x + string.length() " + (x + string.length()) + " must be less than " + widthInCharacters + "." );
if (x < 0 || x >= widthInCharacters)
throw new IllegalArgumentException("x " + x + " must be within range [0," + widthInCharacters + ")" );
if (y < 0 || y >= heightInCharacters)
throw new IllegalArgumentException("y " + y + " must be within range [0," + heightInCharacters + ")" );
return write(string, x, y, defaultForegroundColor, defaultBackgroundColor);
}
/**
* Write a string to the specified position with the specified foreground color.
* This updates the cursor's position but not the default foreground color.
* @param string the string to write
* @param x the distance from the left to begin writing from
* @param y the distance from the top to begin writing from
* @param foreground the foreground color or null to use the default
* @return this for convenient chaining of method calls
*/
public AsciiPanel write(String string, int x, int y, Color foreground) {
if (string == null)
throw new NullPointerException("string must not be null" );
if (x + string.length() >= widthInCharacters)
throw new IllegalArgumentException("x + string.length() " + (x + string.length()) + " must be less than " + widthInCharacters + "." );
if (x < 0 || x >= widthInCharacters)
throw new IllegalArgumentException("x " + x + " must be within range [0," + widthInCharacters + ")" );
if (y < 0 || y >= heightInCharacters)
throw new IllegalArgumentException("y " + y + " must be within range [0," + heightInCharacters + ")" );
return write(string, x, y, foreground, defaultBackgroundColor);
}
/**
* Write a string to the specified position with the specified foreground and background colors.
* This updates the cursor's position but not the default foreground or background colors.
* @param string the string to write
* @param x the distance from the left to begin writing from
* @param y the distance from the top to begin writing from
* @param foreground the foreground color or null to use the default
* @param background the background color or null to use the default
* @return this for convenient chaining of method calls
*/
public AsciiPanel write(String string, int x, int y, Color foreground, Color background) {
if (string == null)
throw new NullPointerException("string must not be null." );
if (x + string.length() >= widthInCharacters)
throw new IllegalArgumentException("x + string.length() " + (x + string.length()) + " must be less than " + widthInCharacters + "." );
if (x < 0 || x >= widthInCharacters)
throw new IllegalArgumentException("x " + x + " must be within range [0," + widthInCharacters + ")." );
if (y < 0 || y >= heightInCharacters)
throw new IllegalArgumentException("y " + y + " must be within range [0," + heightInCharacters + ")." );
if (foreground == null)
foreground = defaultForegroundColor;
if (background == null)
background = defaultBackgroundColor;
for (int i = 0; i < string.length(); i++) {
write(string.charAt(i), x + i, y, foreground, background);
}
return this;
}
/**
* Write a string to the center of the panel at the specified y position.
* This updates the cursor's position.
* @param string the string to write
* @param y the distance from the top to begin writing from
* @return this for convenient chaining of method calls
*/
public AsciiPanel writeCenter(String string, int y) {
if (string == null)
throw new NullPointerException("string must not be null" );
if (string.length() >= widthInCharacters)
throw new IllegalArgumentException("string.length() " + string.length() + " must be less than " + widthInCharacters + "." );
int x = (widthInCharacters - string.length()) / 2;
if (y < 0 || y >= heightInCharacters)
throw new IllegalArgumentException("y " + y + " must be within range [0," + heightInCharacters + ")" );
return write(string, x, y, defaultForegroundColor, defaultBackgroundColor);
}
/**
* Write a string to the center of the panel at the specified y position with the specified foreground color.
* This updates the cursor's position but not the default foreground color.
* @param string the string to write
* @param y the distance from the top to begin writing from
* @param foreground the foreground color or null to use the default
* @return this for convenient chaining of method calls
*/
public AsciiPanel writeCenter(String string, int y, Color foreground) {
if (string == null)
throw new NullPointerException("string must not be null" );
if (string.length() >= widthInCharacters)
throw new IllegalArgumentException("string.length() " + string.length() + " must be less than " + widthInCharacters + "." );
int x = (widthInCharacters - string.length()) / 2;
if (y < 0 || y >= heightInCharacters)
throw new IllegalArgumentException("y " + y + " must be within range [0," + heightInCharacters + ")" );
return write(string, x, y, foreground, defaultBackgroundColor);
}
/**
* Write a string to the center of the panel at the specified y position with the specified foreground and background colors.
* This updates the cursor's position but not the default foreground or background colors.
* @param string the string to write
* @param y the distance from the top to begin writing from
* @param foreground the foreground color or null to use the default
* @param background the background color or null to use the default
* @return this for convenient chaining of method calls
*/
public AsciiPanel writeCenter(String string, int y, Color foreground, Color background) {
if (string == null)
throw new NullPointerException("string must not be null." );
if (string.length() >= widthInCharacters)
throw new IllegalArgumentException("string.length() " + string.length() + " must be less than " + widthInCharacters + "." );
int x = (widthInCharacters - string.length()) / 2;
if (y < 0 || y >= heightInCharacters)
throw new IllegalArgumentException("y " + y + " must be within range [0," + heightInCharacters + ")." );
if (foreground == null)
foreground = defaultForegroundColor;
if (background == null)
background = defaultBackgroundColor;
for (int i = 0; i < string.length(); i++) {
write(string.charAt(i), x + i, y, foreground, background);
}
return this;
}
}
|
package org.voltdb.utils;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
import java.util.jar.JarEntry;
import java.util.jar.JarInputStream;
import java.util.jar.JarOutputStream;
import org.apache.hadoop_voltpatches.util.PureJavaCrc32;
/**
* Given a jarfile, construct a map of entry name => byte array representing
* the contents. Allow it to be modified and written out in flexible ways.
*
*/
public class InMemoryJarfile extends TreeMap<String, byte[]> {
private static final long serialVersionUID = 1L;
protected final JarLoader m_loader = new JarLoader();;
// CONSTRUCTION
public InMemoryJarfile() {}
public InMemoryJarfile(String pathOrURL) throws IOException {
InputStream fin = null;
try {
URL url = new URL(pathOrURL);
fin = url.openStream();
} catch (MalformedURLException ex) {
// Invalid URL. Try as a file.
fin = new FileInputStream(pathOrURL);
}
loadFromStream(fin);
}
public InMemoryJarfile(URL url) throws IOException {
loadFromStream(url.openStream());
}
public InMemoryJarfile(File file) throws IOException {
loadFromStream(new FileInputStream(file));
}
public InMemoryJarfile(byte[] bytes) throws IOException {
loadFromStream(new ByteArrayInputStream(bytes));
}
private void loadFromStream(InputStream in) throws IOException {
JarInputStream jarIn = new JarInputStream(in);
JarEntry catEntry = null;
while ((catEntry = jarIn.getNextJarEntry()) != null) {
byte[] value = readFromJarEntry(jarIn, catEntry);
String key = catEntry.getName();
put(key, value);
}
}
public static byte[] readFromJarEntry(JarInputStream jarIn, JarEntry entry) throws IOException {
int totalRead = 0;
int maxToRead = 4096 << 10;
byte[] buffer = new byte[maxToRead];
byte[] bytes = new byte[maxToRead * 2];
// Keep reading until we run out of bytes for this entry
// We will resize our return value byte array if we run out of space
while (jarIn.available() == 1) {
int readSize = jarIn.read(buffer, 0, buffer.length);
if (readSize > 0) {
totalRead += readSize;
if (totalRead > bytes.length) {
byte[] temp = new byte[bytes.length * 2];
System.arraycopy(bytes, 0, temp, 0, bytes.length);
bytes = temp;
}
System.arraycopy(buffer, 0, bytes, totalRead - readSize, readSize);
}
}
// Trim bytes to proper size
byte retval[] = new byte[totalRead];
System.arraycopy(bytes, 0, retval, 0, totalRead);
return retval;
}
// OUTPUT
public Runnable writeToFile(File file) throws IOException {
final FileOutputStream output = new FileOutputStream(file);
writeToOutputStream(output);
return new Runnable() {
@Override
public void run() {
try {
output.getFD().sync();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
try {
output.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
};
}
public byte[] getFullJarBytes() throws IOException {
ByteArrayOutputStream output = new ByteArrayOutputStream();
writeToOutputStream(output);
output.close();
return output.toByteArray();
}
protected void writeToOutputStream(OutputStream output) throws IOException {
JarOutputStream jarOut = new JarOutputStream(output);
for (Entry<String, byte[]> e : super.entrySet()) {
assert(e.getValue() != null);
JarEntry entry = new JarEntry(e.getKey());
entry.setSize(e.getValue().length);
entry.setTime(System.currentTimeMillis());
jarOut.putNextEntry(entry);
jarOut.write(e.getValue());
jarOut.flush();
jarOut.closeEntry();
}
jarOut.finish();
}
// UTILITY
public long getCRC() throws IOException {
PureJavaCrc32 crc = new PureJavaCrc32();
for (Entry<String, byte[]> e : super.entrySet()) {
if (e.getKey().equals("buildinfo.txt") || e.getKey().equals("catalog-report.html")) {
continue;
}
crc.update(e.getKey().getBytes("UTF-8"));
crc.update(e.getValue());
}
return crc.getValue();
}
public byte[] put(String key, File value) throws IOException {
byte[] bytes = null;
bytes = new byte[(int) value.length()];
BufferedInputStream in = new BufferedInputStream(new FileInputStream(value));
int bytesRead = in.read(bytes);
assert(bytesRead != -1);
return put(key, bytes);
}
// CLASSLOADING
public class JarLoader extends ClassLoader {
final Map<String, Class<?>> m_cache = new HashMap<String, Class<?>>();
final Set<String> m_classNames = new HashSet<String>();
void noteUpdated(String key) {
if (!key.endsWith(".class"))
return;
String javaClassName = key.replace(File.separatorChar, '.');
javaClassName = javaClassName.substring(0, javaClassName.length() - 6);
m_classNames.add(javaClassName);
}
void noteRemoved(String key) {
if (!key.endsWith(".class"))
return;
String javaClassName = key.replace(File.separatorChar, '.');
javaClassName = javaClassName.substring(0, javaClassName.length() - 6);
m_classNames.remove(javaClassName);
m_cache.remove(javaClassName);
}
// prevent this from being publicly called
JarLoader() {}
@Override
public synchronized Class<?> loadClass(String className) throws ClassNotFoundException {
// try the fast cache first
Class<?> result;
if (m_cache.containsKey(className)) {
//System.out.println("found in cache.");
return m_cache.get(className);
}
// now look through the list
if (m_classNames.contains(className)) {
String classPath = className.replace('.', File.separatorChar) + ".class";
byte bytes[] = get(classPath);
if (bytes == null)
throw new ClassNotFoundException(className);
result = this.defineClass(className, bytes, 0, bytes.length);
resolveClass(result);
m_cache.put(className, result);
return result;
}
// default to parent
//System.out.println("deferring to parent.");
return getParent().loadClass(className);
}
}
public JarLoader getLoader() {
return m_loader;
}
// OVERRIDDEN TREEMAP OPERATIONS
@Override
public byte[] put(String key, byte[] value) {
if (value == null)
throw new RuntimeException("InMemoryJarFile cannon contain null entries.");
byte[] retval = super.put(key, value);
m_loader.noteUpdated(key);
return retval;
}
@Override
public void putAll(Map<? extends String, ? extends byte[]> m) {
for (Entry<? extends String, ? extends byte[]> e : m.entrySet()) {
put(e.getKey(), e.getValue());
}
}
@Override
public byte[] remove(Object key) {
String realKey = null;
try {
realKey = (String) key;
}
catch (Exception e) {
return null;
}
m_loader.noteRemoved(realKey);
return super.remove(key);
}
@Override
public void clear() {
for (String key : keySet())
m_loader.noteRemoved(key);
super.clear();
}
@Override
public Object clone() {
throw new UnsupportedOperationException();
}
@Override
public java.util.Map.Entry<String, byte[]> pollFirstEntry() {
throw new UnsupportedOperationException();
}
@Override
public java.util.Map.Entry<String, byte[]> pollLastEntry() {
throw new UnsupportedOperationException();
}
}
|
package org.voltdb.iv2;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.voltcore.logging.VoltLogger;
import org.voltcore.utils.CoreUtils;
import org.voltdb.CatalogContext;
import org.voltdb.exceptions.TransactionRestartException;
import org.voltdb.messaging.FragmentResponseMessage;
import org.voltdb.messaging.FragmentTaskMessage;
/**
* Provide an implementation of the TransactionTaskQueue specifically for the MPI.
* This class will manage separating the stream of reads and writes to different
* Sites and block appropriately so that reads and writes never execute concurrently.
*/
public class MpTransactionTaskQueue extends TransactionTaskQueue
{
protected static final VoltLogger tmLog = new VoltLogger("TM");
// Track the current writes and reads in progress. If writes contains anything, reads must be empty,
// and vice versa
private final Map<Long, TransactionTask> m_currentWrites = new HashMap<Long, TransactionTask>();
private final Map<Long, TransactionTask> m_currentReads = new HashMap<Long, TransactionTask>();
private Deque<TransactionTask> m_backlog = new ArrayDeque<TransactionTask>();
private MpRoSitePool m_sitePool = null;
MpTransactionTaskQueue(SiteTaskerQueue queue)
{
super(queue, false);
}
void setMpRoSitePool(MpRoSitePool sitePool)
{
m_sitePool = sitePool;
}
synchronized void updateCatalog(String diffCmds, CatalogContext context)
{
m_sitePool.updateCatalog(diffCmds, context);
}
synchronized void updateSettings(CatalogContext context)
{
m_sitePool.updateSettings(context);
}
void shutdown()
{
if (m_sitePool != null) {
m_sitePool.shutdown();
}
}
/**
* Stick this task in the backlog.
* Many network threads may be racing to reach here, synchronize to
* serialize queue order.
* Always returns true in this case, side effect of extending
* TransactionTaskQueue.
*/
@Override
synchronized void offer(TransactionTask task)
{
Iv2Trace.logTransactionTaskQueueOffer(task);
m_backlog.addLast(task);
taskQueueOffer();
}
// repair is used by MPI repair to inject a repair task into the
// SiteTaskerQueue. Before it does this, it unblocks the MP transaction
// that may be running in the Site thread and causes it to rollback by
// faking an unsuccessful FragmentResponseMessage.
synchronized void repair(SiteTasker task, List<Long> masters, Map<Integer, Long> partitionMasters, boolean balanceSPI)
{
// We know that every Site assigned to the MPI (either the main writer or
// any of the MP read pool) will only have one active transaction at a time,
// and that we either have active reads or active writes, but never both.
// Figure out which we're doing, and then poison all of the appropriate sites.
Map<Long, TransactionTask> currentSet;
boolean readonly = true;
if (!m_currentReads.isEmpty()) {
assert(m_currentWrites.isEmpty());
if (tmLog.isDebugEnabled()) {
tmLog.debug("MpTTQ: repairing reads. MigratePartitionLeader:" + balanceSPI);
}
for (Long txnId : m_currentReads.keySet()) {
m_sitePool.repair(txnId, task);
}
currentSet = m_currentReads;
}
else {
if (tmLog.isDebugEnabled()) {
tmLog.debug("MpTTQ: repairing writes. MigratePartitionLeader:" + balanceSPI);
}
m_taskQueue.offer(task);
currentSet = m_currentWrites;
readonly = false;
}
for (Entry<Long, TransactionTask> e : currentSet.entrySet()) {
if (e.getValue() instanceof MpProcedureTask) {
MpProcedureTask next = (MpProcedureTask)e.getValue();
if (tmLog.isDebugEnabled()) {
tmLog.debug("MpTTQ: poisoning task: " + next);
}
next.doRestart(masters, partitionMasters);
if (!balanceSPI) {
MpTransactionState txn = (MpTransactionState)next.getTransactionState();
// inject poison pill
FragmentTaskMessage dummy = new FragmentTaskMessage(0L, 0L, 0L, 0L,
false, false, false, txn.isNPartTxn(), txn.getTimetamp());
FragmentResponseMessage poison =
new FragmentResponseMessage(dummy, 0L); // Don't care about source HSID here
// Provide a TransactionRestartException which will be converted
// into a ClientResponse.RESTART, so that the MpProcedureTask can
// detect the restart and take the appropriate actions.
TransactionRestartException restart = new TransactionRestartException(
"Transaction being restarted due to fault recovery or shutdown.", next.getTxnId());
restart.setMisrouted(false);
poison.setStatus(FragmentResponseMessage.UNEXPECTED_ERROR, restart);
txn.offerReceivedFragmentResponse(poison);
if (tmLog.isDebugEnabled()) {
tmLog.debug("MpTTQ: restarting:" + next);
}
}
}
}
// Now, iterate through the backlog and update the partition masters
// for all ProcedureTasks
Iterator<TransactionTask> iter = m_backlog.iterator();
while (iter.hasNext()) {
TransactionTask tt = iter.next();
if (tt instanceof MpProcedureTask) {
MpProcedureTask next = (MpProcedureTask)tt;
if (tmLog.isDebugEnabled()) {
tmLog.debug("Repair updating task: " + next + " with masters: " + CoreUtils.hsIdCollectionToString(masters));
}
next.updateMasters(masters, partitionMasters);
}
else if (tt instanceof EveryPartitionTask) {
EveryPartitionTask next = (EveryPartitionTask)tt;
if (tmLog.isDebugEnabled()) {
tmLog.debug("Repair updating EPT task: " + next + " with masters: " + CoreUtils.hsIdCollectionToString(masters));
}
next.updateMasters(masters);
}
}
}
private void taskQueueOffer(TransactionTask task)
{
Iv2Trace.logSiteTaskerQueueOffer(task);
if (task.getTransactionState().isReadOnly()) {
m_sitePool.doWork(task.getTxnId(), task);
}
else {
m_taskQueue.offer(task);
}
}
private boolean taskQueueOffer()
{
// Do we have something to do?
// - If so, is it a write?
// - If so, are there reads or writes outstanding?
// - if not, pull it from the backlog, add it to current write set, and queue it
// - if so, bail for now
// - If not, are there writes outstanding?
// - if not, while there are reads on the backlog and the pool has capacity:
// - pull the read from the backlog, add it to the current read set, and queue it.
// - bail when done
// - if so, bail for now
boolean retval = false;
if (!m_backlog.isEmpty()) {
// We may not queue the next task, just peek to get the read-only state
TransactionTask task = m_backlog.peekFirst();
if (!task.getTransactionState().isReadOnly()) {
if (m_currentReads.isEmpty() && m_currentWrites.isEmpty()) {
task = m_backlog.pollFirst();
m_currentWrites.put(task.getTxnId(), task);
taskQueueOffer(task);
retval = true;
}
}
else if (m_currentWrites.isEmpty()) {
while (task != null && task.getTransactionState().isReadOnly() &&
m_sitePool.canAcceptWork())
{
task = m_backlog.pollFirst();
assert(task.getTransactionState().isReadOnly());
m_currentReads.put(task.getTxnId(), task);
taskQueueOffer(task);
retval = true;
// Prime the pump with the head task, if any. If empty,
// task will be null
task = m_backlog.peekFirst();
}
}
}
return retval;
}
/**
* Indicate that the transaction associated with txnId is complete. Perform
* management of reads/writes in progress then call taskQueueOffer() to
* submit additional tasks to be done, determined by whatever the current state is.
* See giant comment at top of taskQueueOffer() for what happens.
*/
@Override
synchronized int flush(long txnId)
{
int offered = 0;
if (m_currentReads.containsKey(txnId)) {
m_currentReads.remove(txnId);
m_sitePool.completeWork(txnId);
}
else {
assert(m_currentWrites.containsKey(txnId));
m_currentWrites.remove(txnId);
assert(m_currentWrites.isEmpty());
}
if (taskQueueOffer()) {
++offered;
}
return offered;
}
/**
* Restart the current task at the head of the queue. This will be called
* instead of flush by the currently blocking MP transaction in the event a
* restart is necessary.
*/
@Override
synchronized void restart()
{
if (!m_currentReads.isEmpty()) {
// re-submit all the tasks in the current read set to the pool.
// the pool will ensure that things submitted with the same
// txnID will go to the the MpRoSite which is currently running it
for (TransactionTask task : m_currentReads.values()) {
taskQueueOffer(task);
}
}
else {
assert(!m_currentWrites.isEmpty());
TransactionTask task;
// There currently should only ever be one current write. This
// is the awkward way to get a single value out of a Map
task = m_currentWrites.entrySet().iterator().next().getValue();
taskQueueOffer(task);
}
}
/**
* How many Tasks are un-runnable?
* @return
*/
@Override
synchronized int size()
{
return m_backlog.size();
}
synchronized public void toString(StringBuilder sb)
{
sb.append("MpTransactionTaskQueue:").append("\n");
sb.append("\tSIZE: ").append(m_backlog.size());
if (!m_backlog.isEmpty()) {
// Print deduped list of backlog
Iterator<TransactionTask> it = m_backlog.iterator();
Set<String> pendingInvocations = new HashSet<>(m_backlog.size()*2);
if (it.hasNext()) {
String procName = it.next().m_txnState.getInvocation().getProcName();
pendingInvocations.add(procName);
sb.append("\n\tPENDING: ").append(procName);
}
while(it.hasNext()) {
String procName = it.next().m_txnState.getInvocation().getProcName();
if (pendingInvocations.add(procName)) {
sb.append(", ").append(procName);
}
}
}
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
toString(sb);
return sb.toString();
}
}
|
package gov.nih.nci.calab.service.common;
import gov.nih.nci.calab.db.DataAccessProxy;
import gov.nih.nci.calab.db.IDataAccess;
import gov.nih.nci.calab.domain.MeasureUnit;
import gov.nih.nci.calab.domain.StorageElement;
import gov.nih.nci.calab.dto.administration.AliquotBean;
import gov.nih.nci.calab.dto.administration.ContainerInfoBean;
import gov.nih.nci.calab.dto.administration.SampleBean;
import gov.nih.nci.calab.dto.workflow.AssayBean;
import gov.nih.nci.calab.service.util.CalabConstants;
import gov.nih.nci.calab.service.util.StringUtils;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
/**
* The service to return prepopulated data that are shared across different
* views.
*
* @author zengje
*
*/
/* CVS $Id: LookupService.java,v 1.23 2006-04-27 18:19:58 pansu Exp $ */
public class LookupService {
private static Logger logger = Logger.getLogger(LookupService.class);
/**
* Retriving all aliquot in the system, for views view aliquot, create run,
* search sample.
*
* @return a list of AliquotBeans containing aliquot ID and aliquot name
*/
public List<AliquotBean> getAliquots() throws Exception {
List<AliquotBean> aliquots = new ArrayList<AliquotBean>();
IDataAccess ida = (new DataAccessProxy()).getInstance(IDataAccess.HIBERNATE);
try {
ida.open();
String hqlString = "select aliquot.id, aliquot.name, status.status from Aliquot aliquot left join aliquot.dataStatus status order by aliquot.name";
List results = ida.search(hqlString);
for (Object obj : results) {
Object[] aliquotInfo = (Object[]) obj;
aliquots.add(new AliquotBean(StringUtils.convertToString(aliquotInfo[0]),
StringUtils.convertToString(aliquotInfo[1]),
StringUtils.convertToString(aliquotInfo[2])));
}
} catch (Exception e) {
logger.error("Error in retrieving all aliquot Ids and names", e);
throw new RuntimeException(
"Error in retrieving all aliquot Ids and names");
} finally {
ida.close();
}
return aliquots;
}
/**
* Retrieving all unmasked aliquots for views use aliquot and create
* aliquot.
*
* @return a list of AliquotBeans containing unmasked aliquot IDs and names.
*
*/
public List<AliquotBean> getUnmaskedAliquots() throws Exception {
List<AliquotBean> aliquots = new ArrayList<AliquotBean>();
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
try {
ida.open();
String hqlString = "select aliquot.id, aliquot.name from Aliquot aliquot where aliquot.dataStatus is null order by aliquot.name";
List results = ida.search(hqlString);
for (Object obj : results) {
Object[] aliquotInfo = (Object[]) obj;
aliquots.add(new AliquotBean(StringUtils
.convertToString(aliquotInfo[0]), StringUtils
.convertToString(aliquotInfo[1]), CalabConstants.ACTIVE_STATUS));
}
} catch (Exception e) {
logger.error("Error in retrieving all aliquot Ids and names", e);
throw new RuntimeException(
"Error in retrieving all aliquot Ids and names");
} finally {
ida.close();
}
return aliquots;
}
/**
* Retrieving all sample types.
*
* @return a list of all sample types
*/
public List<String> getAllSampleTypes() throws Exception {
// Detail here
// Retrieve data from Sample_Type table
List<String> sampleTypes = new ArrayList<String>();
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
try {
ida.open();
String hqlString = "select sampleType.name from SampleType sampleType order by sampleType.name";
List results = ida.search(hqlString);
for (Object obj : results) {
sampleTypes.add((String) obj);
}
} catch (Exception e) {
logger.error("Error in retrieving all sample types", e);
throw new RuntimeException("Error in retrieving all sample types");
} finally {
ida.close();
}
return sampleTypes;
}
/**
*
* @return the default sample container information in a form of
* ContainerInfoBean
*/
public ContainerInfoBean getSampleContainerInfo() throws Exception {
// tmp code to be replaced
List<String> containerTypes = getAllContainerTypes();
List<MeasureUnit> units = getAllMeasureUnits();
List<StorageElement> storageElements = getAllRoomAndFreezers();
List<String> quantityUnits = new ArrayList<String>();
List<String> concentrationUnits = new ArrayList<String>();
List<String> volumeUnits = new ArrayList<String>();
List<String> rooms = new ArrayList<String>();
List<String> freezers = new ArrayList<String>();
for (MeasureUnit unit : units) {
if (unit.getType().equalsIgnoreCase("Quantity")) {
quantityUnits.add(unit.getName());
} else if (unit.getType().equalsIgnoreCase("Volume")) {
volumeUnits.add(unit.getName());
} else if (unit.getType().equalsIgnoreCase("Concentration")) {
concentrationUnits.add(unit.getName());
}
}
for (StorageElement storageElement : storageElements) {
if (storageElement.getType().equalsIgnoreCase("Room")) {
rooms.add((storageElement.getLocation()));
} else if (storageElement.getType().equalsIgnoreCase("Freezer")) {
freezers.add((storageElement.getLocation()));
}
}
// set labs and racks to null for now
ContainerInfoBean containerInfo = new ContainerInfoBean(containerTypes,
quantityUnits, concentrationUnits, volumeUnits, null, rooms,
freezers);
return containerInfo;
}
private List<String> getAllContainerTypes() throws Exception {
List<String> containerTypes = new ArrayList<String>();
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
try {
ida.open();
String hqlString = "select distinct container.containerType from SampleContainer container order by container.containerType";
List results = ida.search(hqlString);
for (Object obj : results) {
containerTypes.add((String) obj);
}
} catch (Exception e) {
logger.error("Error in retrieving all container types", e);
throw new RuntimeException(
"Error in retrieving all container types.");
} finally {
ida.close();
}
return containerTypes;
}
private List<MeasureUnit> getAllMeasureUnits() throws Exception {
List<MeasureUnit> units = new ArrayList<MeasureUnit>();
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
try {
ida.open();
String hqlString = "from MeasureUnit";
List results = ida.search(hqlString);
for (Object obj : results) {
units.add((MeasureUnit) obj);
}
} catch (Exception e) {
logger.error("Error in retrieving all measure units", e);
throw new RuntimeException("Error in retrieving all measure units.");
} finally {
ida.close();
}
return units;
}
private List<StorageElement> getAllRoomAndFreezers() throws Exception {
List<StorageElement> storageElements = new ArrayList<StorageElement>();
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
try {
ida.open();
String hqlString = "from StorageElement where type in ('Room', 'Freezer')";
List results = ida.search(hqlString);
for (Object obj : results) {
storageElements.add((StorageElement) obj);
}
} catch (Exception e) {
logger.error("Error in retrieving all rooms and freezers", e);
throw new RuntimeException(
"Error in retrieving all rooms and freezers.");
} finally {
ida.close();
}
return storageElements;
}
/**
*
* @return the default sample container information in a form of
* ContainerInfoBean
*/
public ContainerInfoBean getAliquotContainerInfo() throws Exception {
return getSampleContainerInfo();
}
/**
* Get all samples in the database
*
* @return a list of SampleBean containing sample Ids and names
*/
public List<SampleBean> getAllSamples() throws Exception {
List<SampleBean> samples = new ArrayList<SampleBean>();
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
try {
ida.open();
String hqlString = "select sample.id, sample.name from Sample sample order by sample.name";
List results = ida.search(hqlString);
for (Object obj : results) {
Object[] sampleInfo = (Object[]) obj;
samples.add(new SampleBean(StringUtils
.convertToString(sampleInfo[0]), StringUtils
.convertToString(sampleInfo[1])));
}
} catch (Exception e) {
logger.error("Error in retrieving all sample IDs and names", e);
throw new RuntimeException(
"Error in retrieving all sample IDs and names");
} finally {
ida.close();
}
return samples;
}
/**
* Retrieve all Assay Types from the system
*
* @return A list of all assay type
*/
public List getAllAssayTypes() throws Exception {
List<String> assayTypes = new ArrayList<String>();
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
try {
ida.open();
String hqlString = "select assayType.name from AssayType assayType order by assayType.executeOrder";
List results = ida.search(hqlString);
for (Object obj : results) {
assayTypes.add((String) obj);
}
} catch (Exception e) {
logger.error("Error in retrieving all assay types", e);
throw new RuntimeException("Error in retrieving all assay types");
} finally {
ida.close();
}
return assayTypes;
}
/**
* Retrieve all assays
*
* @return a list of all assays in certain type
*/
public List<String> getAllAssignedAliquots() {
// Detail here
List<String> aliquots = new ArrayList<String>();
return aliquots;
}
public List<AssayBean> getAllAssayBeans() throws Exception {
List<AssayBean> assayBeans = new ArrayList<AssayBean>();
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
try {
ida.open();
String hqlString = "select assay.id, assay.name, assay.assayType from Assay assay";
List results = ida.search(hqlString);
for (Object obj : results) {
Object[] objArray = (Object[]) obj;
AssayBean assay = new AssayBean(
((Long) objArray[0]).toString(), (String) objArray[1],
(String) objArray[2]);
assayBeans.add(assay);
}
} catch (Exception e) {
logger.error("Error in retrieving all assay beans. ", e);
throw new RuntimeException("Error in retrieving all assays beans. ");
} finally {
ida.close();
}
return assayBeans;
}
public List<String> getAllUsernames() throws Exception {
List<String> usernames = new ArrayList<String>();
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
try {
ida.open();
String hqlString = "select user.loginName from User user order by user.loginName";
List results = ida.search(hqlString);
for (Object obj : results) {
usernames.add((String) obj);
}
} catch (Exception e) {
logger.error("Error in retrieving all aliquot Ids and names", e);
throw new RuntimeException(
"Error in retrieving all aliquot Ids and names");
} finally {
ida.close();
}
return usernames;
}
}
|
package gov.nih.nci.calab.ui.workflow;
import gov.nih.nci.calab.dto.workflow.FileBean;
import gov.nih.nci.calab.dto.workflow.RunBean;
import gov.nih.nci.calab.service.util.CaNanoLabConstants;
import gov.nih.nci.calab.service.util.PropertyReader;
import gov.nih.nci.calab.service.util.SpecialCharReplacer;
import gov.nih.nci.calab.service.util.file.FileNameConvertor;
import gov.nih.nci.calab.service.util.file.FilePacker;
import gov.nih.nci.calab.service.util.file.HttpFileUploadSessionData;
import gov.nih.nci.calab.service.util.file.HttpUploadedFileData;
import gov.nih.nci.calab.service.workflow.ExecuteWorkflowService;
import gov.nih.nci.calab.ui.core.AbstractDispatchAction;
import gov.nih.nci.calab.ui.core.InitSessionSetup;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.DynaActionForm;
/**
* This class handle workflow upload process.
*
* @author zhoujim, pansu
*
*/
public class FileUploadAction extends AbstractDispatchAction {
private static org.apache.log4j.Logger logger_ = org.apache.log4j.Logger
.getLogger(FileUploadAction.class);
/**
* This method is setting up the parameters for the workflow input upload
* files or output upload files.
*
* @param mapping
* @param form
* @param request
* @param response
* @return mapping forward
*/
public ActionForward setup(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception {
String inout = (String) request.getParameter("inout");
String menuType = (String) request.getParameter("menuType");
InitSessionSetup.getInstance().setCurrentRun(request);
HttpSession session = request.getSession();
RunBean currentRun = (RunBean) session.getAttribute("currentRun");
if (inout == null) {
inout = (String) session.getAttribute("inout");
}
if (menuType == null) {
menuType = (String) session.getAttribute("menuType");
}
SpecialCharReplacer specialCharReplacer = new SpecialCharReplacer();
String assayType = specialCharReplacer.getReplacedString(currentRun
.getAssayBean().getAssayType());
String assayName = specialCharReplacer.getReplacedString(currentRun
.getAssayBean().getAssayName());
String runName = specialCharReplacer.getReplacedString(currentRun
.getName());
DynaActionForm fileForm = (DynaActionForm) form;
fileForm.set("archiveValue", PropertyReader.getProperty(
CaNanoLabConstants.FILEUPLOAD_PROPERTY, "archiveValue"));
fileForm.set("servletURL", PropertyReader.getProperty(
CaNanoLabConstants.FILEUPLOAD_PROPERTY, "servletURL"));
fileForm.set("notifyURL", PropertyReader.getProperty(
CaNanoLabConstants.FILEUPLOAD_PROPERTY, "notifyURL"));
fileForm.set("defaultURL", PropertyReader.getProperty(
CaNanoLabConstants.FILEUPLOAD_PROPERTY, "defaultURL"));
fileForm.set("sid", session.getId());
fileForm.set("module", "calab");
fileForm.set("permissibleFileExtension", "*");
HttpFileUploadSessionData hFileUploadData = new HttpFileUploadSessionData();
hFileUploadData.setInout(inout);
hFileUploadData.setRunId(currentRun.getId());
hFileUploadData.setAssay(assayName);
hFileUploadData.setAssayType(assayType);
hFileUploadData.setRun(runName);
// set where this upload from
hFileUploadData.setFromType(menuType);
session.setAttribute("httpFileUploadSessionData", hFileUploadData);
InitSessionSetup.getInstance().clearSearchSession(session);
InitSessionSetup.getInstance().clearInventorySession(session);
return mapping.findForward("success");
}
public ActionForward persistFileUploadData(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
ActionForward forward = null;
HttpFileUploadSessionData mySessionData = (HttpFileUploadSessionData) request
.getSession().getAttribute("httpFileUploadSessionData");
String path = PropertyReader.getProperty(
CaNanoLabConstants.FILEUPLOAD_PROPERTY, "fileRepositoryDir");
String relativePathName = mySessionData.getAssayType() + File.separator
+ mySessionData.getAssay() + File.separator
+ mySessionData.getRun() + File.separator
+ mySessionData.getInout();
String fullPathName = path + relativePathName;
String mode = (String) request.getParameter("mode");
HttpSession session = request.getSession();
if ("stop".equals(mode)) {
if (mySessionData != null) {
mySessionData.setIsStopped(true);
List list = mySessionData.getFileList();
for (Iterator it = list.iterator(); it.hasNext();) {
HttpUploadedFileData data = (HttpUploadedFileData) it
.next();
try {
File file = new File(fullPathName, data.getFileName());
if (file.exists()) {
file.delete();
}
// delete uncompressed files
String fileName = null;
FileNameConvertor fnConvertor = new FileNameConvertor();
fileName = fnConvertor.getConvertedFileName(data
.getFileName());
File uncompressedFile = new File(fullPathName, fileName);
if (uncompressedFile.exists()) {
uncompressedFile.delete();
}
} catch (Exception e) {
logger_.info("Mode " + mode + ": File "
+ data.getFileName()
+ " can't be deleted due to io error");
}
}
// clear the cache
mySessionData.clearList();
}
forward = null;
} // end of if "stop".equals(mode)
// Right after uploaded all the files, parsing service will be called
// to start process these files. This allows multiple uploads from
// the same applet. After each upload, the file parsing process is
// put into a queue for one by one processing.
else if ("success".equals(mode)) {
// Should not occur, but in case.
if (mySessionData == null) {
logger_.debug("Session data not found");
return mapping.findForward("expiredSession");
}
List fileList = mySessionData.getFileList();
String inout = mySessionData.getInout();
String runId = mySessionData.getRunId();
logger_.info("Persist file upload data to database ");
// use CaNanoLabConstants.URI_SEPERATOR to save in the database, which
// might be different from physical file structure/seperator
String uriPathName = mySessionData.getAssayType()
+ CaNanoLabConstants.URI_SEPERATOR + mySessionData.getAssay()
+ CaNanoLabConstants.URI_SEPERATOR + mySessionData.getRun()
+ CaNanoLabConstants.URI_SEPERATOR + mySessionData.getInout();
String unzipFilePath = CaNanoLabConstants.URI_SEPERATOR + uriPathName
+ CaNanoLabConstants.URI_SEPERATOR
+ CaNanoLabConstants.UNCOMPRESSED_FILE_DIRECTORY;
ExecuteWorkflowService workflowService = new ExecuteWorkflowService();
workflowService.saveFile(fileList, unzipFilePath, runId, inout,
(String) session.getAttribute("creator"));
session.setAttribute("newFileLoaded", "true");
session.setAttribute("newRunCreated", "true");
// After data persistence, we need to create all.zip for all upload
// files,
// which includes previous uploaded file and uploaded files
// currently.
List<FileBean> fileBeans = workflowService.getLastestFileListByRun(
runId, inout);
FilePacker fPacker = new FilePacker();
String uncompressedFileDirecory = fullPathName + File.separator
+ CaNanoLabConstants.UNCOMPRESSED_FILE_DIRECTORY;
fPacker.removeOldZipFile(uncompressedFileDirecory);
List<String> fileNameHolder = new ArrayList<String>();
for (FileBean fileBean : fileBeans) {
fileNameHolder.add(fileBean.getFilename());
}
String[] needToPackFiles = new String[fileNameHolder.size()];
for (int i = 0; i < needToPackFiles.length; i++) {
needToPackFiles[i] = (String) fileNameHolder.get(i);
}
boolean isCreated = fPacker.packFiles(needToPackFiles,
uncompressedFileDirecory);
logger_.info("Creating ALL_FILES.zip is " + isCreated);
mySessionData.clearList();
forward = null;
}
// If user says it's done, then move to our defaut page for this action.
else if ("done".equals(mode)) {
// The page will be forwarded to the DefaultURl defined in
// fileupload.properties
forward = null;
}
return forward;
}
public boolean loginRequired() {
return true;
}
}
|
/**
* @author dgeorge
*
* $Id: UserManagerImpl.java,v 1.19 2006-04-20 19:09:26 georgeda Exp $
*
* $Log: not supported by cvs2svn $
* Revision 1.18 2006/04/19 15:08:44 georgeda
* Uncomment login checking
*
* Revision 1.17 2006/04/17 19:11:05 pandyas
* caMod 2.1 OM changes
*
* Revision 1.16 2005/12/06 22:00:04 georgeda
* Defect #253, only check roles when there is a username
*
* Revision 1.15 2005/12/06 14:50:45 georgeda
* Defect #253, change the lowecase to the login action so that roles match
*
* Revision 1.14 2005/12/05 19:35:17 schroedn
* Defect #253 - Covert username to all lowercase before validating
*
* Revision 1.13 2005/11/29 16:13:04 georgeda
* Check for null password in login
*
* Revision 1.12 2005/11/18 21:05:37 georgeda
* Defect #130, added superuser
*
* Revision 1.11 2005/11/08 22:32:44 georgeda
* LDAP changes
*
* Revision 1.10 2005/11/07 13:58:29 georgeda
* Dynamically update roles
*
* Revision 1.9 2005/10/24 13:28:06 georgeda
* Cleanup changes
*
* Revision 1.8 2005/10/17 13:10:16 georgeda
* Get contact information
*
* Revision 1.7 2005/10/13 17:00:06 georgeda
* Cleanup
*
* Revision 1.6 2005/09/30 19:49:58 georgeda
* Make sure user is in db
*
* Revision 1.5 2005/09/22 18:55:49 georgeda
* Get coordinator from user in properties file
*
* Revision 1.4 2005/09/22 15:15:17 georgeda
* More changes
*
* Revision 1.3 2005/09/16 15:52:57 georgeda
* Changes due to manager re-write
*
*
*/
package gov.nih.nci.camod.service.impl;
import gov.nih.nci.camod.Constants;
import gov.nih.nci.camod.domain.*;
import gov.nih.nci.camod.service.UserManager;
import gov.nih.nci.camod.util.LDAPUtil;
import gov.nih.nci.common.persistence.Search;
import gov.nih.nci.security.AuthenticationManager;
import gov.nih.nci.security.SecurityServiceProvider;
import gov.nih.nci.security.exceptions.CSException;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
/**
* Implementation of class used to wrap the CSM implementation
*/
public class UserManagerImpl extends BaseManager implements UserManager {
private AuthenticationManager theAuthenticationMgr = null;
/**
* Constructor gets reference to authorization manager
*/
UserManagerImpl() {
log.trace("Entering UserManagerImpl");
try {
theAuthenticationMgr = SecurityServiceProvider.getAuthenticationManager(Constants.UPT_CONTEXT_NAME);
} catch (CSException ex) {
log.error("Error getting authentication managers", ex);
} catch (Throwable e) {
log.error("Error getting authentication managers", e);
}
log.trace("Exiting UserManagerImpl");
}
/**
* Get a list of roles for a user
*
* @param inUsername
* the login name of the user
*
* @return the list of roles associated with the user
* @throws Exception
*/
public List getRolesForUser(String inUsername) throws Exception {
log.trace("Entering getRolesForUser");
List theRoles = new ArrayList();
try {
Person thePerson = new Person();
thePerson.setUsername(inUsername);
List thePeople = Search.query(thePerson);
if (thePeople.size() > 0) {
thePerson = (Person) thePeople.get(0);
Set theRoleSet = thePerson.getRoleCollection();
Iterator it = theRoleSet.iterator();
while (it.hasNext()) {
Role theRole = (Role) it.next();
theRoles.add(theRole.getName());
}
// Check for superuser priv
try {
// Get from default bundle
ResourceBundle theBundle = ResourceBundle.getBundle(Constants.CAMOD_BUNDLE);
String theSuperusers = theBundle.getString(Constants.BundleKeys.SUPERUSER_USERNAMES_KEY);
StringTokenizer theTokenizer = new StringTokenizer(theSuperusers, ",");
while (theTokenizer.hasMoreTokens()) {
if (theTokenizer.nextToken().equals(inUsername)) {
theRoles.add(Constants.Admin.Roles.SUPER_USER);
break;
}
}
} catch (Exception e) {
log.error("Cannot get superuser information from bundle", e);
}
} else {
throw new IllegalArgumentException("User: " + inUsername + " not in caMOD database");
}
} catch (Exception e) {
log.error("Unable to get roles for user (" + inUsername + ": ", e);
throw e;
}
log.info("User: " + inUsername + " and roles: " + theRoles);
log.trace("Exiting getRolesForUser");
return theRoles;
}
/**
* Get a list of users for a particular role
*
* @param inRoleName
* is the name of the role
*
* @return the list of users associated with the role
* @throws Exception
*/
public List getUsersForRole(String inRoleName) throws Exception {
log.trace("Entering getUsersForRole");
List theUsersForRole = new ArrayList();
Role theRole = new Role();
theRole.setName(inRoleName);
try {
List theRoles = Search.query(theRole);
if (theRoles.size() > 0) {
theRole = (Role) theRoles.get(0);
// Get the users for the role
Set theUsers = theRole.getPartyCollection();
Iterator theIterator = theUsers.iterator();
// Go through the list of returned Party objects
while (theIterator.hasNext()) {
Object theObject = theIterator.next();
// Only add when it's actually a person
if (theObject instanceof Person) {
Person thePerson = (Person) theObject;
theUsersForRole.add(thePerson.getUsername());
}
}
} else {
log.warn("Role not found in database: " + inRoleName);
}
} catch (Exception e) {
log.error("Unable to get roles for user: ", e);
throw e;
}
log.info("Role: " + inRoleName + " and users: " + theUsersForRole);
log.trace("Exiting getUsersForRole");
return theUsersForRole;
}
/**
* Get an e-mail address for a user
*
* @param inUsername
* is the login name of the user
*
* @return the list of users associated with the role
*/
public String getEmailForUser(String inUsername) {
log.trace("Entering getEmailForUser");
log.debug("Username: " + inUsername);
String theEmail = "";
try {
theEmail = LDAPUtil.getEmailAddressForUser(inUsername);
} catch (Exception e) {
log.warn("Could not fetch user from LDAP", e);
}
log.trace("Exiting getEmailForUser");
return theEmail;
}
/**
* Update the roles for the current user
*/
public void updateCurrentUserRoles(HttpServletRequest inRequest) {
String theCurrentUser = (String) inRequest.getSession().getAttribute(Constants.CURRENTUSER);
try {
List theRoles = getRolesForUser(theCurrentUser);
inRequest.getSession().setAttribute(Constants.CURRENTUSERROLES, theRoles);
} catch (Exception e) {
log.info("Unable to update user roles for " + theCurrentUser, e);
}
}
/**
* Get an e-mail address for a user
*
* @param inUsername
* is the login name of the user
*
* @return the list of users associated with the role
*/
public ContactInfo getContactInformationForUser(String inUsername) {
log.trace("Entering getContactInformationForUser");
log.debug("Username: " + inUsername);
ContactInfo theContactInfo = new ContactInfo();
try {
theContactInfo.setInstitute("");
theContactInfo.setEmail(LDAPUtil.getEmailAddressForUser(inUsername));
theContactInfo.setPhone("");
} catch (Exception e) {
log.warn("Could not fetch user from LDAP", e);
}
log.trace("Exiting getEmailForUser");
return theContactInfo;
}
/**
* Get an e-mail address for the coordinator
*
* @return the list of users associated with the role
*/
public String getEmailForCoordinator() {
log.trace("Entering getEmailForCoordinator");
String theEmail = "";
try {
// Get from default bundle
ResourceBundle theBundle = ResourceBundle.getBundle(Constants.CAMOD_BUNDLE);
String theCoordinator = theBundle.getString(Constants.BundleKeys.COORDINATOR_USERNAME_KEY);
theEmail = getEmailForUser(theCoordinator);
} catch (Exception e) {
log.warn("Unable to get coordinator email: ", e);
}
log.trace("Exiting getEmailForCoordinator");
return theEmail;
}
/**
* Log in a user and get roles.
*
* @param inUsername
* is the login name of the user
* @param inPassword
* password
* @param inRequest
* Used to store the roles
*
* @return the list of users associated with the role
*/
public boolean login(String inUsername, String inPassword, HttpServletRequest inRequest) {
boolean loginOk = false;
try {
// Work around bug in CSM. Empty passwords pass
if (inPassword.trim().length() != 0) {
loginOk = theAuthenticationMgr.login(inUsername, inPassword);
// Does the user exist? Must also be in our database to login
List theRoles = getRolesForUser(inUsername);
inRequest.getSession().setAttribute(Constants.CURRENTUSERROLES, theRoles);
}
} catch (Exception e) {
log.error("Error logging in user: ", e);
loginOk = false;
}
return loginOk;
}
}
|
package org.apollo.net.codec.game;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import org.apollo.net.meta.PacketType;
import org.apollo.util.BufferUtil;
import com.google.common.base.Preconditions;
/**
* A class which assists in creating a {@link GamePacket}.
*
* @author Graham
*/
public final class GamePacketBuilder {
/**
* The current bit index.
*/
private int bitIndex;
/**
* The buffer.
*/
private final ByteBuf buffer = Unpooled.buffer();
/**
* The current mode.
*/
private AccessMode mode = AccessMode.BYTE_ACCESS;
/**
* The opcode.
*/
private final int opcode;
/**
* The {@link PacketType}.
*/
private final PacketType type;
/**
* Creates a raw {@link GamePacketBuilder}.
*/
public GamePacketBuilder() {
opcode = -1;
type = PacketType.RAW;
}
/**
* Creates the {@link GamePacketBuilder} for a {@link PacketType#FIXED} packet with the specified opcode.
*
* @param opcode The opcode.
*/
public GamePacketBuilder(int opcode) {
this(opcode, PacketType.FIXED);
}
/**
* Creates the {@link GamePacketBuilder} for the specified packet type and opcode.
*
* @param opcode The opcode.
* @param type The packet type.
*/
public GamePacketBuilder(int opcode, PacketType type) {
this.opcode = opcode;
this.type = type;
}
private void checkBitAccess() {
Preconditions.checkState(mode == AccessMode.BIT_ACCESS, "For bit-based calls to work, the mode must be bit access.");
}
private void checkByteAccess() {
Preconditions.checkState(mode == AccessMode.BYTE_ACCESS, "For byte-based calls to work, the mode must be byte access.");
}
/**
* Gets the current length of the builder's buffer.
*
* @return The length of the buffer.
*/
public int getLength() {
checkByteAccess();
return buffer.writerIndex();
}
public void put(DataType type, DataOrder order, DataTransformation transformation, Number value) {
checkByteAccess();
long longValue = value.longValue();
int length = type.getBytes();
if (order == DataOrder.BIG) {
for (int i = length - 1; i >= 0; i
if (i == 0 && transformation != DataTransformation.NONE) {
if (transformation == DataTransformation.ADD) {
buffer.writeByte((byte) (longValue + 128));
} else if (transformation == DataTransformation.NEGATE) {
buffer.writeByte((byte) -longValue);
} else if (transformation == DataTransformation.SUBTRACT) {
buffer.writeByte((byte) (128 - longValue));
} else {
throw new IllegalArgumentException("Unknown transformation.");
}
} else {
buffer.writeByte((byte) (longValue >> i * 8));
}
}
} else if (order == DataOrder.LITTLE) {
for (int i = 0; i < length; i++) {
if (i == 0 && transformation != DataTransformation.NONE) {
if (transformation == DataTransformation.ADD) {
buffer.writeByte((byte) (longValue + 128));
} else if (transformation == DataTransformation.NEGATE) {
buffer.writeByte((byte) -longValue);
} else if (transformation == DataTransformation.SUBTRACT) {
buffer.writeByte((byte) (128 - longValue));
} else {
throw new IllegalArgumentException("Unknown transformation.");
}
} else {
buffer.writeByte((byte) (longValue >> i * 8));
}
}
} else if (order == DataOrder.MIDDLE) {
Preconditions.checkArgument(transformation == DataTransformation.NONE, "Middle endian cannot be transformed.");
Preconditions.checkArgument(type == DataType.INT, "Middle endian can only be used with an integer.");
buffer.writeByte((byte) (longValue >> 8));
buffer.writeByte((byte) longValue);
buffer.writeByte((byte) (longValue >> 24));
buffer.writeByte((byte) (longValue >> 16));
} else if (order == DataOrder.INVERSED_MIDDLE) {
Preconditions.checkArgument(transformation == DataTransformation.NONE, "Inversed middle endian cannot be transformed.");
Preconditions.checkArgument(type == DataType.INT, "Inversed middle endian can only be used with an integer.");
buffer.writeByte((byte) (longValue >> 16));
buffer.writeByte((byte) (longValue >> 24));
buffer.writeByte((byte) longValue);
buffer.writeByte((byte) (longValue >> 8));
} else {
throw new IllegalArgumentException("Unknown order.");
}
}
/**
* Puts a standard data type with the specified value and byte order.
*
* @param type The data type.
* @param order The byte order.
* @param value The value.
*/
public void put(DataType type, DataOrder order, Number value) {
put(type, order, DataTransformation.NONE, value);
}
/**
* Puts a standard data type with the specified value and transformation.
*
* @param type The type.
* @param transformation The transformation.
* @param value The value.
*/
public void put(DataType type, DataTransformation transformation, Number value) {
put(type, DataOrder.BIG, transformation, value);
}
/**
* Puts a standard data type with the specified value.
*
* @param type The data type.
* @param value The value.
*/
public void put(DataType type, Number value) {
put(type, DataOrder.BIG, DataTransformation.NONE, value);
}
/**
* Puts a single bit into the buffer. If {@code flag} is {@code true}, the value of the bit is {@code 1}. If
* {@code flag} is {@code false}, the value of the bit is {@code 0}.
*
* @param flag The flag.
*/
public void putBit(boolean flag) {
putBit(flag ? 1 : 0);
}
/**
* Puts a single bit into the buffer with the value {@code value}.
*
* @param value The value.
*/
public void putBit(int value) {
putBits(1, value);
}
public void putBits(int numBits, int value) {
Preconditions.checkArgument(numBits >= 1 && numBits <= 32, "Number of bits must be between 1 and 32 inclusive.");
checkBitAccess();
int bytePos = bitIndex >> 3;
int bitOffset = 8 - (bitIndex & 7);
bitIndex += numBits;
int requiredSpace = bytePos - buffer.writerIndex() + 1;
requiredSpace += (numBits + 7) / 8;
buffer.ensureWritable(requiredSpace);
for (; numBits > bitOffset; bitOffset = 8) {
int tmp = buffer.getByte(bytePos);
tmp &= ~DataConstants.BIT_MASK[bitOffset];
tmp |= value >> numBits - bitOffset & DataConstants.BIT_MASK[bitOffset];
buffer.setByte(bytePos++, tmp);
numBits -= bitOffset;
}
if (numBits == bitOffset) {
int tmp = buffer.getByte(bytePos);
tmp &= ~DataConstants.BIT_MASK[bitOffset];
tmp |= value & DataConstants.BIT_MASK[bitOffset];
buffer.setByte(bytePos, tmp);
} else {
int tmp = buffer.getByte(bytePos);
tmp &= ~(DataConstants.BIT_MASK[numBits] << bitOffset - numBits);
tmp |= (value & DataConstants.BIT_MASK[numBits]) << bitOffset - numBits;
buffer.setByte(bytePos, tmp);
}
}
/**
* Puts the specified byte array into the buffer.
*
* @param bytes The byte array.
*/
public void putBytes(byte[] bytes) {
buffer.writeBytes(bytes);
}
/**
* Puts the bytes from the specified buffer into this packet's buffer.
*
* @param buffer The source {@link ByteBuf}.
*/
public void putBytes(ByteBuf buffer) {
byte[] bytes = new byte[buffer.readableBytes()];
buffer.markReaderIndex();
try {
buffer.readBytes(bytes);
} finally {
buffer.resetReaderIndex();
}
putBytes(bytes);
}
/**
* Puts the bytes into the buffer with the specified transformation.
*
* @param transformation The transformation.
* @param bytes The byte array.
*/
public void putBytes(DataTransformation transformation, byte[] bytes) {
if (transformation == DataTransformation.NONE) {
putBytes(bytes);
} else {
for (byte b : bytes) {
put(DataType.BYTE, transformation, b);
}
}
}
/**
* Puts the specified byte array into the buffer in reverse.
*
* @param bytes The byte array.
*/
public void putBytesReverse(byte[] bytes) {
checkByteAccess();
for (int i = bytes.length - 1; i >= 0; i
buffer.writeByte(bytes[i]);
}
}
/**
* Puts the bytes from the specified buffer into this packet's buffer, in reverse.
*
* @param buffer The source {@link ByteBuf}.
*/
public void putBytesReverse(ByteBuf buffer) {
byte[] bytes = new byte[buffer.readableBytes()];
buffer.markReaderIndex();
try {
buffer.readBytes(bytes);
} finally {
buffer.resetReaderIndex();
}
putBytesReverse(bytes);
}
/**
* Puts the specified byte array into the buffer in reverse with the specified transformation.
*
* @param transformation The transformation.
* @param bytes The byte array.
*/
public void putBytesReverse(DataTransformation transformation, byte[] bytes) {
if (transformation == DataTransformation.NONE) {
putBytesReverse(bytes);
} else {
for (int i = bytes.length - 1; i >= 0; i
put(DataType.BYTE, transformation, bytes[i]);
}
}
}
public void putRawBuilder(GamePacketBuilder builder) {
checkByteAccess();
if (builder.type != PacketType.RAW) {
throw new IllegalArgumentException("Builder must be raw.");
}
builder.checkByteAccess();
putBytes(builder.buffer);
}
public void putRawBuilderReverse(GamePacketBuilder builder) {
checkByteAccess();
Preconditions.checkArgument(builder.type == PacketType.RAW, "Builder must be raw.");
builder.checkByteAccess();
putBytesReverse(builder.buffer);
}
/**
* Puts a smart into the buffer.
*
* @param value The value.
*/
public void putSmart(int value) {
checkByteAccess();
if (value < 128) {
buffer.writeByte(value);
} else {
buffer.writeShort(value);
}
}
/**
* Puts a string into the buffer.
*
* @param str The string.
*/
public void putString(String str) {
checkByteAccess();
char[] chars = str.toCharArray();
for (char c : chars) {
buffer.writeByte((byte) c);
}
buffer.writeByte(BufferUtil.STRING_TERMINATOR);
}
public void switchToBitAccess() {
Preconditions.checkState(mode != AccessMode.BIT_ACCESS, "Already in bit access mode.");
mode = AccessMode.BIT_ACCESS;
bitIndex = buffer.writerIndex() * 8;
}
public void switchToByteAccess() {
Preconditions.checkState(mode != AccessMode.BYTE_ACCESS, "Already in bit access mode.");
mode = AccessMode.BYTE_ACCESS;
buffer.writerIndex((bitIndex + 7) / 8);
}
public GamePacket toGamePacket() {
Preconditions.checkState(type != PacketType.RAW, "Raw packets cannot be converted to a game packet.");
Preconditions.checkState(mode == AccessMode.BYTE_ACCESS, "Must be in byte access mode to convert to a packet.");
return new GamePacket(opcode, type, buffer);
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package it.ferogrammer.ui;
import org.jfree.chart.labels.XYItemLabelGenerator;
import org.jfree.data.xy.XYDataset;
/**
*
* @author enea
*/
public class NucleotideItemLabelGenerator implements XYItemLabelGenerator {
@Override
public String generateLabel(XYDataset dataset, int series, int item) {
//This can be improved by including a dependency on the Nucleotide Enum.values()
//see setColorsAndLabels() in ElectropherogramChartPanel for an example of the approach
//TODO fix here because now only N label appears
String label = "";
if ((dataset.getXValue(series, item) % 1 == 0) && dataset.getYValue(series, item) >= 1500) {
if (onlyOnePeak(dataset, series, item)) {
switch (series) {
case 0:
label = "A";
break;
case 1:
label = "C";
break;
case 2:
label = "T";
break;
case 3:
label = "G";
break;
}
} else {
//means there are 2 peaks
//set the label of only 'N' series to N, leave others blank
if(series==4){
label = "N";
}
}
}
return label;
}
private boolean onlyOnePeak(XYDataset dataset, int series, int item) {
boolean only1 = true;
//NOTE: used dataset.getSeriesCount()-1 to exclude last series which is the accessory 'N' series
for (int i = 0; i < dataset.getSeriesCount()-1; i++) {
if(i==series) continue; //do not consider the current series
if(dataset.getYValue(i, item)>=1500) only1=false;
}
return only1;
}
}
|
package jade.tools.introspector.gui;
import java.awt.event.*;
import javax.swing.*;
import jade.core.AID;
import jade.tools.introspector.Introspector;
class TreeAgentPopupMenu extends JPopupMenu{
Introspector debugger;
String agentName;
public TreeAgentPopupMenu(Introspector d){
debugger = d;
build();
}
void build (){
JMenuItem debugOn = new JMenuItem("Debug On");
JMenuItem debugOff = new JMenuItem("Debug Off");
TreeAgentPopupMenuListener listener = new TreeAgentPopupMenuListener();
debugOn.addActionListener(listener);
debugOn.setName("on");
debugOff.addActionListener(listener);
debugOff.setName("off");
this.add(debugOn);
this.addSeparator();
this.add(debugOff);
}
public void setSelectedAgent(String agentname) {
this.agentName = agentname;
}
class TreeAgentPopupMenuListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
JMenuItem source=(JMenuItem) e.getSource();
if(source.getName().equals("on")) {
debugger.addAgent(new AID(agentName, AID.ISGUID));
}
else if(source.getName().equals("off")) {
debugger.removeAgent(new AID(agentName, AID.ISGUID));
}
}
}
}
|
package com.healthmarketscience.jackcess;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* An Access database.
*
* @author Tim McCune
*/
public class Database {
private static final Log LOG = LogFactory.getLog(Database.class);
private static final byte[] SID = new byte[2];
static {
SID[0] = (byte) 0xA6;
SID[1] = (byte) 0x33;
}
/** Batch commit size for copying other result sets into this database */
private static final int COPY_TABLE_BATCH_SIZE = 200;
/** System catalog always lives on page 2 */
private static final int PAGE_SYSTEM_CATALOG = 2;
private static final int ACM = 1048319;
/** Free space left in page for new usage map definition pages */
private static final short USAGE_MAP_DEF_FREE_SPACE = 3940;
private static final String COL_ACM = "ACM";
/** System catalog column name of the date a system object was created */
private static final String COL_DATE_CREATE = "DateCreate";
/** System catalog column name of the date a system object was updated */
private static final String COL_DATE_UPDATE = "DateUpdate";
private static final String COL_F_INHERITABLE = "FInheritable";
private static final String COL_FLAGS = "Flags";
/**
* System catalog column name of the page on which system object definitions
* are stored
*/
private static final String COL_ID = "Id";
/** System catalog column name of the name of a system object */
private static final String COL_NAME = "Name";
private static final String COL_OBJECT_ID = "ObjectId";
private static final String COL_OWNER = "Owner";
/** System catalog column name of a system object's parent's id */
private static final String COL_PARENT_ID = "ParentId";
private static final String COL_SID = "SID";
/** System catalog column name of the type of a system object */
private static final String COL_TYPE = "Type";
/** Empty database template for creating new databases */
private static final String EMPTY_MDB = "com/healthmarketscience/jackcess/empty.mdb";
/** Prefix for column or table names that are reserved words */
private static final String ESCAPE_PREFIX = "x";
/** Prefix that flags system tables */
private static final String PREFIX_SYSTEM = "MSys";
/** Name of the system object that is the parent of all tables */
private static final String SYSTEM_OBJECT_NAME_TABLES = "Tables";
/** Name of the table that contains system access control entries */
private static final String TABLE_SYSTEM_ACES = "MSysACEs";
/** System object type for table definitions */
private static final Short TYPE_TABLE = (short) 1;
/**
* All of the reserved words in Access that should be escaped when creating
* table or column names
*/
private static final Set<String> RESERVED_WORDS = new HashSet<String>();
static {
//Yup, there's a lot.
RESERVED_WORDS.addAll(Arrays.asList(
"add", "all", "alphanumeric", "alter", "and", "any", "application", "as",
"asc", "assistant", "autoincrement", "avg", "between", "binary", "bit",
"boolean", "by", "byte", "char", "character", "column", "compactdatabase",
"constraint", "container", "count", "counter", "create", "createdatabase",
"createfield", "creategroup", "createindex", "createobject", "createproperty",
"createrelation", "createtabledef", "createuser", "createworkspace",
"currency", "currentuser", "database", "date", "datetime", "delete",
"desc", "description", "disallow", "distinct", "distinctrow", "document",
"double", "drop", "echo", "else", "end", "eqv", "error", "exists", "exit",
"false", "field", "fields", "fillcache", "float", "float4", "float8",
"foreign", "form", "forms", "from", "full", "function", "general",
"getobject", "getoption", "gotopage", "group", "group by", "guid", "having",
"idle", "ieeedouble", "ieeesingle", "if", "ignore", "imp", "in", "index",
"indexes", "inner", "insert", "inserttext", "int", "integer", "integer1",
"integer2", "integer4", "into", "is", "join", "key", "lastmodified", "left",
"level", "like", "logical", "logical1", "long", "longbinary", "longtext",
"macro", "match", "max", "min", "mod", "memo", "module", "money", "move",
"name", "newpassword", "no", "not", "null", "number", "numeric", "object",
"oleobject", "off", "on", "openrecordset", "option", "or", "order", "outer",
"owneraccess", "parameter", "parameters", "partial", "percent", "pivot",
"primary", "procedure", "property", "queries", "query", "quit", "real",
"recalc", "recordset", "references", "refresh", "refreshlink",
"registerdatabase", "relation", "repaint", "repairdatabase", "report",
"reports", "requery", "right", "screen", "section", "select", "set",
"setfocus", "setoption", "short", "single", "smallint", "some", "sql",
"stdev", "stdevp", "string", "sum", "table", "tabledef", "tabledefs",
"tableid", "text", "time", "timestamp", "top", "transform", "true", "type",
"union", "unique", "update", "user", "value", "values", "var", "varp",
"varbinary", "varchar", "where", "with", "workspace", "xor", "year", "yes",
"yesno"
));
}
/** Buffer to hold database pages */
private ByteBuffer _buffer;
/** ID of the Tables system object */
private Integer _tableParentId;
/** Format that the containing database is in */
private JetFormat _format;
/**
* Map of table names to page numbers containing their definition
*/
private Map<String, Integer> _tables = new HashMap<String, Integer>();
/** Reads and writes database pages */
private PageChannel _pageChannel;
/** System catalog table */
private Table _systemCatalog;
/** System access control entries table */
private Table _accessControlEntries;
/**
* Open an existing Database
* @param mdbFile File containing the database
*/
public static Database open(File mdbFile) throws IOException, SQLException {
return new Database(openChannel(mdbFile));
}
/**
* Create a new Database
* @param mdbFile Location to write the new database to. <b>If this file
* already exists, it will be overwritten.</b>
*/
public static Database create(File mdbFile) throws IOException, SQLException {
FileChannel channel = openChannel(mdbFile);
channel.transferFrom(Channels.newChannel(
Thread.currentThread().getContextClassLoader().getResourceAsStream(
EMPTY_MDB)), 0, (long) Integer.MAX_VALUE);
return new Database(channel);
}
private static FileChannel openChannel(File mdbFile) throws FileNotFoundException {
return new RandomAccessFile(mdbFile, "rw").getChannel();
}
/**
* Create a new database by reading it in from a FileChannel.
* @param channel File channel of the database. This needs to be a
* FileChannel instead of a ReadableByteChannel because we need to
* randomly jump around to various points in the file.
*/
protected Database(FileChannel channel) throws IOException, SQLException {
_format = JetFormat.getFormat(channel);
_pageChannel = new PageChannel(channel, _format);
_buffer = _pageChannel.createPageBuffer();
readSystemCatalog();
}
public PageChannel getPageChannel() {
return _pageChannel;
}
/**
* @return The system catalog table
*/
public Table getSystemCatalog() {
return _systemCatalog;
}
public Table getAccessControlEntries() {
return _accessControlEntries;
}
/**
* Read the system catalog
*/
private void readSystemCatalog() throws IOException, SQLException {
_pageChannel.readPage(_buffer, PAGE_SYSTEM_CATALOG);
byte pageType = _buffer.get();
if (pageType != PageTypes.TABLE_DEF) {
throw new IOException("Looking for system catalog at page " +
PAGE_SYSTEM_CATALOG + ", but page type is " + pageType);
}
_systemCatalog = new Table(_buffer, _pageChannel, _format, PAGE_SYSTEM_CATALOG);
Map row;
while ( (row = _systemCatalog.getNextRow(Arrays.asList(
COL_NAME, COL_TYPE, COL_ID))) != null)
{
String name = (String) row.get(COL_NAME);
if (name != null && TYPE_TABLE.equals(row.get(COL_TYPE))) {
if (!name.startsWith(PREFIX_SYSTEM)) {
_tables.put((String) row.get(COL_NAME), (Integer) row.get(COL_ID));
} else if (TABLE_SYSTEM_ACES.equals(name)) {
readAccessControlEntries(((Integer) row.get(COL_ID)).intValue());
}
} else if (SYSTEM_OBJECT_NAME_TABLES.equals(name)) {
_tableParentId = (Integer) row.get(COL_ID);
}
}
if (LOG.isDebugEnabled()) {
LOG.debug("Finished reading system catalog. Tables: " + _tables);
}
}
/**
* Read the system access control entries table
* @param pageNum Page number of the table def
*/
private void readAccessControlEntries(int pageNum) throws IOException, SQLException {
ByteBuffer buffer = _pageChannel.createPageBuffer();
_pageChannel.readPage(buffer, pageNum);
byte pageType = buffer.get();
if (pageType != PageTypes.TABLE_DEF) {
throw new IOException("Looking for MSysACEs at page " + pageNum +
", but page type is " + pageType);
}
_accessControlEntries = new Table(buffer, _pageChannel, _format, pageNum);
}
/**
* @return The names of all of the user tables (String)
*/
public Set<String> getTableNames() {
return _tables.keySet();
}
/**
* @param name Table name
* @return The table, or null if it doesn't exist
*/
public Table getTable(String name) throws IOException, SQLException {
Integer pageNumber = (Integer) _tables.get(name);
if (pageNumber == null) {
// Bug workaround:
pageNumber = (Integer) _tables.get(Character.toUpperCase(name.charAt(0)) +
name.substring(1));
}
if (pageNumber == null) {
return null;
} else {
_pageChannel.readPage(_buffer, pageNumber.intValue());
return new Table(_buffer, _pageChannel, _format, pageNumber.intValue());
}
}
/**
* Create a new table in this database
* @param name Name of the table to create
* @param columns List of Columns in the table
*/
//XXX Set up 1-page rollback buffer?
public void createTable(String name, List<Column> columns) throws IOException {
//There is some really bizarre bug in here where tables that start with
//the letters a-m (only lower case) won't open in Access. :)
name = Character.toUpperCase(name.charAt(0)) + name.substring(1);
//We are creating a new page at the end of the db for the tdef.
int pageNumber = _pageChannel.getPageCount();
ByteBuffer buffer = _pageChannel.createPageBuffer();
writeTableDefinition(buffer, columns, pageNumber);
writeColumnDefinitions(buffer, columns);
//End of tabledef
buffer.put((byte) 0xff);
buffer.put((byte) 0xff);
buffer.putInt(8, buffer.position()); //Overwrite length of data for this page
//Write the tdef and usage map pages to disk.
_pageChannel.writeNewPage(buffer);
_pageChannel.writeNewPage(createUsageMapDefinitionBuffer(pageNumber));
_pageChannel.writeNewPage(createUsageMapDataBuffer()); //Usage map
//Add this table to our internal list.
_tables.put(name, new Integer(pageNumber));
//Add this table to system tables
addToSystemCatalog(name, pageNumber);
addToAccessControlEntries(pageNumber);
}
/**
* @param buffer Buffer to write to
* @param columns List of Columns in the table
* @param pageNumber Page number that this table definition will be written to
*/
private void writeTableDefinition(ByteBuffer buffer, List<Column> columns,
int pageNumber)
throws IOException {
//Start writing the tdef
buffer.put(PageTypes.TABLE_DEF); //Page type
buffer.put((byte) 0x01); //Unknown
buffer.put((byte) 0); //Unknown
buffer.put((byte) 0); //Unknown
buffer.putInt(0); //Next TDEF page pointer
buffer.putInt(0); //Length of data for this page
buffer.put((byte) 0x59); //Unknown
buffer.put((byte) 0x06); //Unknown
buffer.putShort((short) 0); //Unknown
buffer.putInt(0); //Number of rows
buffer.putInt(0); //Autonumber
for (int i = 0; i < 16; i++) { //Unknown
buffer.put((byte) 0);
}
buffer.put(Table.TYPE_USER); //Table type
buffer.putShort((short) columns.size()); //Max columns a row will have
buffer.putShort(Column.countVariableLength(columns)); //Number of variable columns in table
buffer.putShort((short) columns.size()); //Number of columns in table
buffer.putInt(0); //Number of indexes in table
buffer.putInt(0); //Number of indexes in table
buffer.put((byte) 0); //Usage map row number
int usageMapPage = pageNumber + 1;
buffer.put(ByteUtil.to3ByteInt(usageMapPage)); //Usage map page number
buffer.put((byte) 1); //Free map row number
buffer.put(ByteUtil.to3ByteInt(usageMapPage)); //Free map page number
if (LOG.isDebugEnabled()) {
int position = buffer.position();
buffer.rewind();
LOG.debug("Creating new table def block:\n" + ByteUtil.toHexString(
buffer, _format.SIZE_TDEF_BLOCK));
buffer.position(position);
}
}
/**
* @param buffer Buffer to write to
* @param columns List of Columns to write definitions for
*/
private void writeColumnDefinitions(ByteBuffer buffer, List columns)
throws IOException {
Iterator iter;
short columnNumber = (short) 0;
short fixedOffset = (short) 0;
short variableOffset = (short) 0;
for (iter = columns.iterator(); iter.hasNext(); columnNumber++) {
Column col = (Column) iter.next();
int position = buffer.position();
buffer.put(col.getType().getValue());
buffer.put((byte) 0x59); //Unknown
buffer.put((byte) 0x06); //Unknown
buffer.putShort((short) 0); //Unknown
buffer.putShort(columnNumber); //Column Number
if (col.getType().isVariableLength()) {
buffer.putShort(variableOffset++);
} else {
buffer.putShort((short) 0);
}
buffer.putShort(columnNumber); //Column Number again
buffer.put((byte) 0x09); //Unknown
buffer.put((byte) 0x04); //Unknown
buffer.putShort((short) 0); //Unknown
if (col.getType().isVariableLength()) { //Variable length
buffer.put((byte) 0x2);
} else {
buffer.put((byte) 0x3);
}
if (col.isCompressedUnicode()) { //Compressed
buffer.put((byte) 1);
} else {
buffer.put((byte) 0);
}
buffer.putInt(0); //Unknown, but always 0.
//Offset for fixed length columns
if (col.getType().isVariableLength()) {
buffer.putShort((short) 0);
} else {
buffer.putShort(fixedOffset);
fixedOffset += col.getType().getSize();
}
buffer.putShort(col.getLength()); //Column length
if (LOG.isDebugEnabled()) {
LOG.debug("Creating new column def block\n" + ByteUtil.toHexString(
buffer, position, _format.SIZE_COLUMN_DEF_BLOCK));
}
}
iter = columns.iterator();
while (iter.hasNext()) {
Column col = (Column) iter.next();
ByteBuffer colName = _format.CHARSET.encode(col.getName());
buffer.putShort((short) colName.remaining());
buffer.put(colName);
}
}
/**
* Create the usage map definition page buffer. It will be stored on the page
* immediately after the tdef page.
* @param pageNumber Page number that the corresponding table definition will
* be written to
*/
private ByteBuffer createUsageMapDefinitionBuffer(int pageNumber) throws IOException {
ByteBuffer rtn = _pageChannel.createPageBuffer();
rtn.put(PageTypes.DATA);
rtn.put((byte) 0x1); //Unknown
rtn.putShort(USAGE_MAP_DEF_FREE_SPACE); //Free space in page
rtn.putInt(0); //Table definition
rtn.putInt(0); //Unknown
rtn.putShort((short) 2); //Number of records on this page
rtn.putShort((short) _format.OFFSET_USED_PAGES_USAGE_MAP_DEF); //First location
rtn.putShort((short) _format.OFFSET_FREE_PAGES_USAGE_MAP_DEF); //Second location
rtn.position(_format.OFFSET_USED_PAGES_USAGE_MAP_DEF);
rtn.put((byte) UsageMap.MAP_TYPE_REFERENCE);
rtn.putInt(pageNumber + 2); //First referenced page number
rtn.position(_format.OFFSET_FREE_PAGES_USAGE_MAP_DEF);
rtn.put((byte) UsageMap.MAP_TYPE_INLINE);
return rtn;
}
/**
* Create a usage map data page buffer.
*/
private ByteBuffer createUsageMapDataBuffer() throws IOException {
ByteBuffer rtn = _pageChannel.createPageBuffer();
rtn.put(PageTypes.USAGE_MAP);
rtn.put((byte) 0x01); //Unknown
rtn.putShort((short) 0); //Unknown
return rtn;
}
/**
* Add a new table to the system catalog
* @param name Table name
* @param pageNumber Page number that contains the table definition
*/
private void addToSystemCatalog(String name, int pageNumber) throws IOException {
Object[] catalogRow = new Object[_systemCatalog.getColumns().size()];
int idx = 0;
Iterator iter;
for (iter = _systemCatalog.getColumns().iterator(); iter.hasNext(); idx++) {
Column col = (Column) iter.next();
if (COL_ID.equals(col.getName())) {
catalogRow[idx] = new Integer(pageNumber);
} else if (COL_NAME.equals(col.getName())) {
catalogRow[idx] = name;
} else if (COL_TYPE.equals(col.getName())) {
catalogRow[idx] = TYPE_TABLE;
} else if (COL_DATE_CREATE.equals(col.getName()) ||
COL_DATE_UPDATE.equals(col.getName()))
{
catalogRow[idx] = new Date();
} else if (COL_PARENT_ID.equals(col.getName())) {
catalogRow[idx] = _tableParentId;
} else if (COL_FLAGS.equals(col.getName())) {
catalogRow[idx] = new Integer(0);
} else if (COL_OWNER.equals(col.getName())) {
byte[] owner = new byte[2];
catalogRow[idx] = owner;
owner[0] = (byte) 0xcf;
owner[1] = (byte) 0x5f;
}
}
_systemCatalog.addRow(catalogRow);
}
/**
* Add a new table to the system's access control entries
* @param pageNumber Page number that contains the table definition
*/
private void addToAccessControlEntries(int pageNumber) throws IOException {
Object[] aceRow = new Object[_accessControlEntries.getColumns().size()];
int idx = 0;
Iterator iter;
for (iter = _accessControlEntries.getColumns().iterator(); iter.hasNext(); idx++) {
Column col = (Column) iter.next();
if (col.getName().equals(COL_ACM)) {
aceRow[idx] = ACM;
} else if (col.getName().equals(COL_F_INHERITABLE)) {
aceRow[idx] = Boolean.FALSE;
} else if (col.getName().equals(COL_OBJECT_ID)) {
aceRow[idx] = new Integer(pageNumber);
} else if (col.getName().equals(COL_SID)) {
aceRow[idx] = SID;
}
}
_accessControlEntries.addRow(aceRow);
}
/**
* Copy an existing JDBC ResultSet into a new table in this database
* @param name Name of the new table to create
* @param source ResultSet to copy from
*/
public void copyTable(String name, ResultSet source) throws SQLException, IOException {
ResultSetMetaData md = source.getMetaData();
List<Column> columns = new LinkedList<Column>();
int textCount = 0;
int totalSize = 0;
for (int i = 1; i <= md.getColumnCount(); i++) {
DataType accessColumnType = DataType.fromSQLType(md.getColumnType(i));
switch (accessColumnType) {
case BYTE:
case INT:
case LONG:
case MONEY:
case FLOAT:
case NUMERIC:
totalSize += 4;
break;
case DOUBLE:
case SHORT_DATE_TIME:
totalSize += 8;
break;
case BINARY:
case TEXT:
case OLE:
case MEMO:
textCount++;
break;
}
}
short textSize = 0;
if (textCount > 0) {
textSize = (short) ((JetFormat.MAX_RECORD_SIZE - totalSize) / textCount);
if (textSize > JetFormat.TEXT_FIELD_MAX_LENGTH) {
textSize = JetFormat.TEXT_FIELD_MAX_LENGTH;
}
}
for (int i = 1; i <= md.getColumnCount(); i++) {
Column column = new Column();
column.setName(escape(md.getColumnName(i)));
column.setType(DataType.fromSQLType(md.getColumnType(i)));
if (column.getType() == DataType.TEXT) {
column.setLength(textSize);
}
columns.add(column);
}
createTable(escape(name), columns);
Table table = getTable(escape(name));
List<Object[]> rows = new ArrayList<Object[]>();
while (source.next()) {
Object[] row = new Object[md.getColumnCount()];
for (int i = 0; i < row.length; i++) {
row[i] = source.getObject(i + 1);
}
rows.add(row);
if (rows.size() == COPY_TABLE_BATCH_SIZE) {
table.addRows(rows);
rows.clear();
}
}
if (rows.size() > 0) {
table.addRows(rows);
}
}
/**
* Copy a delimited text file into a new table in this database
* @param name Name of the new table to create
* @param f Source file to import
* @param delim Regular expression representing the delimiter string.
*/
public void importFile(String name, File f, String delim)
throws IOException, SQLException
{
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader(f));
importReader(name, in, delim);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException ex) {
LOG.warn("Could not close file " + f.getAbsolutePath(), ex);
}
}
}
}
/**
* Copy a delimited text file into a new table in this database
* @param name Name of the new table to create
* @param in Source reader to import
* @param delim Regular expression representing the delimiter string.
*/
public void importReader(String name, BufferedReader in, String delim)
throws IOException, SQLException
{
String line = in.readLine();
if (line == null || line.trim().length() == 0) {
return;
}
String tableName = escape(name);
int counter = 0;
while(getTable(tableName) != null) {
tableName = escape(name + (counter++));
}
List<Column> columns = new LinkedList<Column>();
String[] columnNames = line.split(delim);
short textSize = (short) ((JetFormat.MAX_RECORD_SIZE) / columnNames.length);
if (textSize > JetFormat.TEXT_FIELD_MAX_LENGTH) {
textSize = JetFormat.TEXT_FIELD_MAX_LENGTH;
}
for (int i = 0; i < columnNames.length; i++) {
Column column = new Column();
column.setName(escape(columnNames[i]));
column.setType(DataType.TEXT);
column.setLength(textSize);
columns.add(column);
}
createTable(tableName, columns);
Table table = getTable(tableName);
List<String[]> rows = new ArrayList<String[]>();
while ((line = in.readLine()) != null)
{
// Handle the situation where the end of the line
// may have null fields. We always want to add the
// same number of columns to the table each time.
String[] data = new String[columnNames.length];
String[] splitData = line.split(delim);
System.arraycopy(splitData, 0, data, 0, splitData.length);
rows.add(data);
if (rows.size() == COPY_TABLE_BATCH_SIZE) {
table.addRows(rows);
rows.clear();
}
}
if (rows.size() > 0) {
table.addRows(rows);
}
}
/**
* Close the database file
*/
public void close() throws IOException {
_pageChannel.close();
}
/**
* @return A table or column name escaped for Access
*/
private String escape(String s) {
if (RESERVED_WORDS.contains(s.toLowerCase())) {
return ESCAPE_PREFIX + s;
} else {
return s;
}
}
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
|
// samskivert library - useful routines for java programs
// This library is free software; you can redistribute it and/or modify it
// (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// You should have received a copy of the GNU Lesser General Public
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.samskivert.velocity;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Properties;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.velocity.Template;
import org.apache.velocity.context.Context;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.io.VelocityWriter;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.RuntimeSingleton;
import org.apache.velocity.util.SimplePool;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.event.EventCartridge;
import org.apache.velocity.app.event.MethodExceptionEventHandler;
import com.samskivert.servlet.HttpErrorException;
import com.samskivert.servlet.MessageManager;
import com.samskivert.servlet.RedirectException;
import com.samskivert.servlet.SiteIdentifier;
import com.samskivert.servlet.SiteResourceLoader;
import com.samskivert.servlet.util.FriendlyException;
import com.samskivert.util.ConfigUtil;
import com.samskivert.util.StringUtil;
import static com.samskivert.Log.log;
/**
* The dispatcher servlet builds upon Velocity's architecture. It does so in the following ways:
*
* <ul> <li> It defines the notion of a logic object which populates the context with data to be
* used to satisfy a particular request. The logic is not a servlet and is therefore limited in
* what it can do while populating data. Experience dictates that ultimate flexibility leads to bad
* design decisions and that this is a place where that sort of thing can be comfortably nipped in
* the bud. <br><br>
*
* <li> It allows template files to be referenced directly in the URL while maintaining the ability
* to choose a cobranded template based on information in the request. The URI is mapped to a
* servlet based on some simple mapping rules. This provides template designers with a clearer
* understanding of the structure of a web application as well as with an easy way to test their
* templates in the absence of an associated servlet. <br><br>
*
* <li> It provides a common error handling paradigm that simplifies the task of authoring web
* applications.
* </ul>
*
* <p><b>URI to servlet mapping</b><br> The mapping process allows the Velocity framework to be
* invoked for all requests ending in a particular file extension (usually <code>.wm</code>). It is
* necessary to instruct your servlet engine of choice to invoke the <code>DispatcherServlet</code>
* for all requests ending in that extension. For Apache/JServ this looks something like this:
*
* <pre>
* ApJServAction .wm /servlets/com.samskivert.velocity.Dispatcher
* </pre>
*
* The request URI then defines the path of the template that will be used to satisfy the
* request. To understand how code is selected to go along with the request, let's look at an
* example. Consider the following configuration:
*
* <pre>
* applications=whowhere
* whowhere.base_uri=/whowhere
* whowhere.base_pkg=whowhere.logic
* </pre>
*
* This defines an application identified as <code>whowhere</code>. An application is defined by
* three parameters, the application identifier, the <code>base_uri</code>, and the
* <code>base_pkg</code>. The <code>base_uri</code> defines the prefix shared by all pages served
* by the application and which serves to identify which application to invoke when processing a
* request. The <code>base_pkg</code> is used to construct the logic classname based on the URI and
* the <code>base_uri</code> parameter.
*
* <p> Now let's look at a sample request to determine how the logic classname is
* resolved. Consider the following request URI:
*
* <pre>
* /whowhere/view/trips.wm
* </pre>
*
* It begins with <code>/whowhere</code> which tells the dispatcher that it's part of the
* <code>whowhere</code> application. That application's <code>base_uri</code> is then stripped
* from the URI leaving <code>/view/trips.wm</code>. The slashes are converted into periods to map
* directories to packages, giving us <code>view.trips.wm</code>. Finally, the
* <code>base_pkg</code> is prepended and the trailing <code>.wm</code> extension removed.
*
* <p> Thus the class invoked to populate the context for this request is
* <code>whowhere.servlets.view.trips</code> (note that the classname <em>is</em> lowercase which
* is an intentional choice in resolving conflicting recommendations that classnames should always
* start with a capital letter and URLs should always be lowercase).
*
* <p> The template used to generate the result is loaded based on the full URI, essentially with a
* call to <code>getTemplate("/whowhere/view/trips.wm")</code> in this example. This is the place
* where more sophisticated cobranding support could be inserted in the future (ie. if I ever want
* to use this to develop a cobranded web site).
*
* @see Logic
*/
public class DispatcherServlet extends HttpServlet
implements MethodExceptionEventHandler
{
/** The HTTP content type context key. */
public static final String CONTENT_TYPE = "default.contentType";
@Override
public void init (ServletConfig config)
throws ServletException
{
super.init(config);
// load up our application configuration
try {
String appcl = config.getInitParameter(APP_CLASS_KEY);
if (StringUtil.isBlank(appcl)) {
_app = new Application();
} else {
Class<?> appclass = Class.forName(appcl);
_app = (Application)appclass.newInstance();
}
// now initialize the applicaiton
String logicPkg = config.getInitParameter(LOGIC_PKG_KEY);
_app.init(config, getServletContext(),
StringUtil.isBlank(logicPkg) ? "" : logicPkg);
} catch (Throwable t) {
throw new ServletException("Error instantiating Application: " + t, t);
}
try {
Velocity.init(loadConfiguration(config));
} catch (Exception e) {
throw new ServletException("Error initializing Velocity: " + e, e);
}
_defaultContentType = RuntimeSingleton.getString(CONTENT_TYPE, DEFAULT_CONTENT_TYPE);
// determine the character set we'll use
_charset = config.getInitParameter(CHARSET_KEY);
if (_charset == null) {
_charset = "UTF-8";
}
}
/**
* Handles HTTP <code>GET</code> requests by calling {@link #doRequest}.
*/
@Override
public void doGet (HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
doRequest(request, response);
}
/**
* Handles HTTP <code>POST</code> requests by calling {@link #doRequest}.
*/
@Override
public void doPost (HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
doRequest(request, response);
}
/**
* Clean up after ourselves and our application.
*/
@Override
public void destroy ()
{
super.destroy();
// shutdown our application
_app.shutdown();
}
/**
* We load our velocity properties from the classpath rather than from a file.
*/
protected Properties loadConfiguration (ServletConfig config)
throws IOException
{
String propsPath = config.getInitParameter(INIT_PROPS_KEY);
if (propsPath == null) {
throw new IOException(INIT_PROPS_KEY + " must point to the velocity properties file " +
"in the servlet configuration.");
}
// config util loads properties files from the classpath
Properties props = ConfigUtil.loadProperties(propsPath);
if (props == null) {
throw new IOException("Unable to load velocity properties " +
"from file '" + INIT_PROPS_KEY + "'.");
}
// if we failed to create our application for whatever reason; bail
if (_app == null) {
return props;
}
// let the application set up velocity properties
_app.configureVelocity(config, props);
// if no file resource loader path has been set and a
// site-specific jar file path was provided, wire up our site
// resource manager
if (props.getProperty("file.resource.loader.path") == null) {
SiteResourceLoader siteLoader = _app.getSiteResourceLoader();
if (siteLoader != null) {
log.info("Velocity loading templates from site loader.");
props.setProperty(RuntimeSingleton.RESOURCE_MANAGER_CLASS,
SiteResourceManager.class.getName());
_usingSiteLoading = true;
} else {
// otherwise use a servlet context resource loader
log.info("Velocity loading templates from servlet context.");
props.setProperty(RuntimeSingleton.RESOURCE_MANAGER_CLASS,
ServletContextResourceManager.class.getName());
}
}
// wire up our #import directive
props.setProperty("userdirective", ImportDirective.class.getName());
// configure the servlet context logger
props.put(RuntimeSingleton.RUNTIME_LOG_LOGSYSTEM_CLASS,
ServletContextLogger.class.getName());
// now return our augmented properties
return props;
}
/**
* Loads up the template appropriate for this request, locates and invokes any associated logic
* class and finally returns the prepared template which will be merged with the prepared
* context.
*/
public Template handleRequest (HttpServletRequest req, HttpServletResponse rsp, Context ctx)
throws Exception
{
InvocationContext ictx = (InvocationContext)ctx;
Logic logic = null;
// listen for exceptions so that we can report them
EventCartridge ec = ictx.getEventCartridge();
if (ec == null) {
ec = new EventCartridge();
ec.attachToContext(ictx);
ec.addEventHandler(this);
}
// if our application failed to initialize, fail with a 500 response
if (_app == null) {
rsp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return null;
}
// obtain the siteid for this request and stuff that into the context
int siteId = SiteIdentifier.DEFAULT_SITE_ID;
SiteIdentifier ident = _app.getSiteIdentifier();
if (ident != null) {
siteId = ident.identifySite(req);
}
if (_usingSiteLoading) {
ctx.put("__siteid__", Integer.valueOf(siteId));
}
// put the context path in the context as well to make it easier to
// construct full paths
ctx.put("context_path", req.getContextPath());
// then select the template
Template tmpl = null;
try {
tmpl = selectTemplate(siteId, ictx);
} catch (ResourceNotFoundException rnfe) {
// send up a 404. For some annoying reason, Jetty tells Apache
// that all is okay (200) when sending its own custom error pages,
// forcing us to use Jetty's custom error page handling code rather
// than passing it up the chain to be dealt with appropriately.
rsp.sendError(HttpServletResponse.SC_NOT_FOUND);
return null;
}
// assume the request is in the default character set unless it has
// actually been sensibly supplied by the browser
if (req.getCharacterEncoding() == null) {
req.setCharacterEncoding(_charset);
}
// assume an HTML response in the default character set unless
// otherwise massaged by the logic
rsp.setContentType("text/html; charset=" + _charset);
Exception error = null;
try {
// insert the application into the context in case the logic or a
// tool wishes to make use of it
ictx.put(APPLICATION_KEY, _app);
// if the application provides a message manager, we want create a
// translation tool and stuff that into the context
MessageManager msgmgr = _app.getMessageManager();
if (msgmgr != null) {
I18nTool i18n = new I18nTool(req, msgmgr);
ictx.put(I18NTOOL_KEY, i18n);
}
// create a form tool for use by the template
FormTool form = new FormTool(req);
ictx.put(FORMTOOL_KEY, form);
// create a new string tool for use by the template
StringTool string = new StringTool();
ictx.put(STRINGTOOL_KEY, string);
// create a new data tool for use by the tempate
DataTool datatool = new DataTool();
ictx.put(DATATOOL_KEY, datatool);
// create a curreny tool set up to use the correct locale
CurrencyTool ctool = new CurrencyTool(req.getLocale());
ictx.put(CURRENCYTOOL_KEY, ctool);
// allow the application to prepare the context
_app.prepareContext(ictx);
// allow the application to do global access control
_app.checkAccess(ictx);
// resolve the appropriate logic class for this URI and execute it
// if it exists
String path = req.getServletPath();
logic = resolveLogic(path);
if (logic != null) {
logic.invoke(_app, ictx);
}
} catch (Exception e) {
error = e;
}
// if an error occurred processing the template, allow the application
// to convert it to something more appropriate and then handle it
String errmsg = null;
try {
if (error != null) {
throw _app.translateException(error);
}
} catch (RedirectException re) {
rsp.sendRedirect(re.getRedirectURL());
return null;
} catch (HttpErrorException hee) {
String msg = hee.getErrorMessage();
if (msg != null) {
rsp.sendError(hee.getErrorCode(), msg);
} else {
rsp.sendError(hee.getErrorCode());
}
return null;
} catch (FriendlyException fe) {
// grab the error message, we'll deal with it shortly
errmsg = fe.getMessage();
} catch (Exception e) {
errmsg = _app.handleException(req, logic, e);
}
// if we have an error message, insert it into the template
if (errmsg != null) {
// try using the application to localize the error message
// before we insert it
MessageManager msgmgr = _app.getMessageManager();
if (msgmgr != null) {
errmsg = msgmgr.getMessage(req, errmsg);
}
ictx.put(ERROR_KEY, errmsg);
}
return tmpl;
}
/**
* Called when a method throws an exception during template evaluation.
*/
@SuppressWarnings("rawtypes") // our super class declares a bare Class
public Object methodException (Class clazz, String method, Exception e)
throws Exception
{
log.warning("Exception", "class", clazz.getName(), "method", method, e);
return "";
}
/**
* Returns the reference to the application that is handling this
* request.
*
* @return The application in effect for this request or null if no
* application was selected to handle the request.
*/
public static Application getApplication (InvocationContext context)
{
return (Application)context.get(APPLICATION_KEY);
}
/**
* Handles all requests (by default).
*
* @param request HttpServletRequest object containing client request.
* @param response HttpServletResponse object for the response.
*/
protected void doRequest (HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
InvocationContext context = null;
try {
context = new InvocationContext(request, response);
setContentType(request, response);
Template template = handleRequest(request, response, context);
if (template != null) {
mergeTemplate(template, context);
}
} catch (Exception e) {
log.warning("doRequest failed", "uri", request.getRequestURI(), e);
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
}
}
/**
* Sets the content type of the response, defaulting to {@link #_defaultContentType} if not
* overriden. Delegates to {@link #chooseCharacterEncoding(HttpServletRequest)} to select the
* appropriate character encoding.
*/
protected void setContentType (HttpServletRequest request, HttpServletResponse response)
{
String contentType = _defaultContentType;
int index = contentType.lastIndexOf(';') + 1;
if (index <= 0 || (index < contentType.length() &&
contentType.indexOf("charset", index) == -1)) {
// append the character encoding which we'd like to use
String encoding = chooseCharacterEncoding(request);
if (!DEFAULT_OUTPUT_ENCODING.equalsIgnoreCase(encoding)) {
contentType += "; charset=" + encoding;
}
}
response.setContentType(contentType);
}
/**
* Chooses the output character encoding to be used as the value for the "charset=" portion of
* the HTTP Content-Type header (and thus returned by
* <code>response.getCharacterEncoding()</code>). Called by {@link #setContentType} if an
* encoding isn't already specified by Content-Type. By default, chooses the value of
* RuntimeSingleton's <code>output.encoding</code> property.
*/
protected String chooseCharacterEncoding (HttpServletRequest request)
{
return RuntimeSingleton.getString(
RuntimeConstants.OUTPUT_ENCODING, DEFAULT_OUTPUT_ENCODING);
}
/**
* This method is called to select the appropriate template for this request. The default
* implementation simply loads the template using Velocity's default template loading services
* based on the URI provided in the request.
*
* @param ctx The context of this request.
*
* @return The template to be used in generating the response.
*/
protected Template selectTemplate (int siteId, InvocationContext ctx)
throws ResourceNotFoundException, ParseErrorException, Exception
{
String path = ctx.getRequest().getServletPath();
if (_usingSiteLoading) {
// if we're using site resource loading, we need to prefix the path with the site
// identifier
path = siteId + ":" + path;
}
// log.info("Loading template", "path", path);
return RuntimeSingleton.getTemplate(path);
}
/**
* Merges the template with the context.
*
* @param template template object returned by the {@link #handleRequest} method.
* @param context the context for this request.
*/
protected void mergeTemplate (Template template, InvocationContext context)
throws ResourceNotFoundException, ParseErrorException, MethodInvocationException,
UnsupportedEncodingException, IOException, Exception
{
HttpServletResponse response = context.getResponse();
ServletOutputStream output = response.getOutputStream();
// ASSUMPTION: response.setContentType() has been called.
String encoding = response.getCharacterEncoding();
VelocityWriter vw = null;
try {
vw = (VelocityWriter)_writerPool.get();
if (vw == null) {
vw = new VelocityWriter(new OutputStreamWriter(output, encoding), 4 * 1024, true);
} else {
vw.recycle(new OutputStreamWriter(output, encoding));
}
template.merge(context, vw);
} catch (IOException ioe) {
// the client probably crashed or aborted the connection ungracefully, so use log.info
log.info("Failed to write response", "uri", context.getRequest().getRequestURI(),
"error", ioe);
} finally {
if (vw != null) {
try {
// flush and put back into the pool don't close to allow us to play nicely with
// others.
vw.flush();
} catch (IOException e) {
// do nothing
}
// Clear the VelocityWriter's reference to its internal OutputStreamWriter to allow
// the latter to be GC'd while vw is pooled.
vw.recycle(null);
_writerPool.put(vw);
}
}
}
/**
* This method is called to select the appropriate logic for this request URI.
*
* @return The logic to be used in generating the response or null if no logic could be
* matched.
*/
protected Logic resolveLogic (String path)
{
// look for a cached logic instance
String lclass = _app.generateClass(path);
Logic logic = _logic.get(lclass);
if (logic == null) {
try {
Class<?> pcl = Class.forName(lclass);
logic = (Logic)pcl.newInstance();
} catch (ClassNotFoundException cnfe) {
// nothing interesting to report
} catch (Throwable t) {
log.warning("Unable to instantiate logic for application", "path", path,
"lclass", lclass, t);
}
// if something failed, use a dummy in it's place so that we don't sit around all day
// freaking out about our inability to instantiate the proper logic class
if (logic == null) {
logic = new DummyLogic();
}
// cache the resolved logic instance
_logic.put(lclass, logic);
}
return logic;
}
/** The application being served by this dispatcher servlet. */
protected Application _app;
/** A table of resolved logic instances. */
protected HashMap<String,Logic> _logic = new HashMap<String,Logic>();
/** The character set in which serve our responses. */
protected String _charset;
/** Set to true if we're using the {@link SiteResourceLoader}. */
protected boolean _usingSiteLoading;
/** Our default content type. */
protected String _defaultContentType;
/** A pool of VelocityWriter instances. */
protected static SimplePool _writerPool = new SimplePool(40);
/** Describes the location of our properties. */
protected static final String INIT_PROPS_KEY = "org.apache.velocity.properties";
/** This is the key used in the context for error messages. */
protected static final String ERROR_KEY = "error";
/** This is the key used to store a reference back to the dispatcher servlet in our invocation
* context. */
protected static final String APPLICATION_KEY = "%_app_%";
/** The key used to store the translation tool in the context. */
protected static final String I18NTOOL_KEY = "i18n";
/** The key used to store the form tool in the context. */
protected static final String FORMTOOL_KEY = "form";
/** The key used to store the string tool in the context. */
protected static final String STRINGTOOL_KEY = "string";
/** The key used to store the data tool in the context. */
protected static final String DATATOOL_KEY = "data";
/** The key used to store the currency tool in the context. */
protected static final String CURRENCYTOOL_KEY = "cash";
/** The servlet parameter key specifying the application class. */
protected static final String APP_CLASS_KEY = "app_class";
/** The servlet parameter key specifying the base logic package. */
protected static final String LOGIC_PKG_KEY = "logic_package";
/** The servlet parameter key specifying the default character set. */
protected static final String CHARSET_KEY = "charset";
/** The default content type for responses. */
protected static final String DEFAULT_CONTENT_TYPE = "text/html";
/** The default encoding for the output stream. */
protected static final String DEFAULT_OUTPUT_ENCODING = "ISO-8859-1";
}
|
// $Id: SceneObjectTip.java,v 1.2 2003/04/26 00:48:47 mdb Exp $
package com.threerings.miso.client;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Composite;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.util.Collection;
import javax.swing.Icon;
import javax.swing.UIManager;
import com.samskivert.swing.Label;
import com.samskivert.swing.LabelSausage;
import com.samskivert.swing.LabelStyleConstants;
import com.samskivert.swing.util.SwingUtil;
import com.samskivert.util.StringUtil;
/**
* A lightweight tooltip used by the {@link MisoScenePanel}. The tip
* foreground and background are controlled by the following {@link
* UIManager} properties:
*
* <pre>
* SceneObjectTip.background
* SceneObjectTip.foreground
* SceneObjectTip.font (falls back to Label.font)
* </pre>
*/
public class SceneObjectTip extends LabelSausage
{
/** The bounding box of this tip, or null prior to layout(). */
public Rectangle bounds;
/**
* Construct a SceneObjectTip.
*/
public SceneObjectTip (String text, Icon icon)
{
super(new Label(text, _foreground, _font), icon);
}
/**
* Called to initialize the tip so that it can be painted.
*
* @param tipFor the bounding rectangle for the object we tip for.
* @param boundary the boundary of all displayable space.
* @param othertips other tip boundaries that we should avoid.
*/
public void layout (Graphics2D gfx, Rectangle tipFor, Rectangle boundary,
Collection othertips)
{
layout(gfx, PAD);
bounds = new Rectangle(_size);
boundary = MAX_RECT;
// center in the on-screen portion of the bounding box of the
// object we're tipping for, but don't go above MAX_HEIGHT from
// the bottom...
Rectangle anchor = boundary.intersection(tipFor);
bounds.setLocation(
anchor.x + (anchor.width - bounds.width) / 2,
anchor.y + Math.max(
(anchor.height - bounds.height) / 2,
anchor.height - MAX_HEIGHT));
// and jiggle it to not overlap any other tips
SwingUtil.positionRect(bounds, boundary, othertips);
}
/**
* Paint this tip at it's location.
*/
public void paint (Graphics2D gfx)
{
paint(gfx, bounds.x, bounds.y, _background, null);
}
/**
* Generates a string representation of this instance.
*/
public String toString ()
{
return _label.getText() + "[" + StringUtil.toString(bounds) + "]";
}
// documentation inherited
protected void drawBase (Graphics2D gfx, int x, int y)
{
Composite ocomp = gfx.getComposite();
gfx.setComposite(ALPHA);
super.drawBase(gfx, x, y);
gfx.setComposite(ocomp);
}
/** The alpha we use for our base. */
protected static final Composite ALPHA = AlphaComposite.getInstance(
AlphaComposite.SRC_OVER, .75f);
/** Colors to use when rendering the tip. */
protected static Color _background, _foreground;
/** The font to use when rendering the tip. */
protected static Font _font;
// initialize resources shared by all tips
static {
_background = UIManager.getColor("SceneObjectTip.background");
_foreground = UIManager.getColor("SceneObjectTip.foreground");
_font = UIManager.getFont("SceneObjectTip.font");
if (_font == null) {
_font = UIManager.getFont("Label.font");
}
}
/** The number of pixels to reserve between elements of the tip. */
protected static final int PAD = 3;
/** The maximum height above the bottom of the object bounds that we are
* to center ourselves. */
protected static final int MAX_HEIGHT = 80;
/** Since we don't bound our tooltips into the view, we provide this
* generous region in which they may lay themselves out. */
protected static final Rectangle MAX_RECT = new Rectangle(
Integer.MIN_VALUE/2, Integer.MIN_VALUE/2,
Integer.MAX_VALUE, Integer.MAX_VALUE);
}
|
package net.sf.plugfy.verifier;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;
/**
* results of a verification run
*
* @author hendrik
*/
public class VerificationResult implements Iterable<String> {
private final Set<String> results = new TreeSet<String>();
/**
* adds a result
*
* @param result result to add
*/
public void add(String result) {
results.add(result);
}
@Override
public String toString() {
return results.toString();
}
@Override
public Iterator<String> iterator() {
return results.iterator();
}
}
|
//This library is free software; you can redistribute it and/or
//modify it under the terms of the GNU Lesser General Public
//This library is distributed in the hope that it will be useful,
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//You should have received a copy of the GNU Lesser General Public
//Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
package opennlp.tools.lang.english;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;
import java.util.regex.Pattern;
import opennlp.maxent.io.SuffixSensitiveGISModelReader;
import opennlp.tools.parser.AbstractBottomUpParser;
import opennlp.tools.parser.Parse;
import opennlp.tools.parser.Parser;
import opennlp.tools.util.Span;
/**
* Class for performing full parsing on English text.
*/
public class TreebankParser {
private static Pattern untokenizedParenPattern1 = Pattern.compile("([^ ])([({)}])");
private static Pattern untokenizedParenPattern2 = Pattern.compile("([({)}])([^ ])");
public static Parser getParser(String dataDir, boolean useTagDictionary, boolean useCaseSensitiveTagDictionary, int beamSize, double advancePercentage) throws IOException {
if (useTagDictionary) {
return new opennlp.tools.parser.chunking.Parser(
new SuffixSensitiveGISModelReader(new File(dataDir + "/build.bin.gz")).getModel(),
new SuffixSensitiveGISModelReader(new File(dataDir + "/check.bin.gz")).getModel(),
new ParserTagger(dataDir + "/tag.bin.gz", dataDir + "/tagdict", useCaseSensitiveTagDictionary ),//, new Dictionary(dataDir+"/dict.bin.gz")),
new ParserChunker(dataDir + "/chunk.bin.gz"),
new HeadRules(dataDir + "/head_rules"),beamSize,advancePercentage);
}
else {
return new opennlp.tools.parser.chunking.Parser(
new SuffixSensitiveGISModelReader(new File(dataDir + "/build.bin.gz")).getModel(),
new SuffixSensitiveGISModelReader(new File(dataDir + "/check.bin.gz")).getModel(),
new ParserTagger(dataDir + "/tag.bin.gz",null), //new Dictionary(dataDir+"/dict.bin.gz")),
new ParserChunker(dataDir + "/chunk.bin.gz"),
new HeadRules(dataDir + "/head_rules"),beamSize,advancePercentage);
}
}
public static Parser getParser(String dataDir) throws IOException {
return getParser(dataDir,true,true,AbstractBottomUpParser.defaultBeamSize,AbstractBottomUpParser.defaultAdvancePercentage);
}
public static Parser getInsertionParser(String dataDir) throws IOException {
return getInsertionParser(dataDir,true,true,AbstractBottomUpParser.defaultBeamSize,AbstractBottomUpParser.defaultAdvancePercentage);
}
public static Parser getInsertionParser(String dataDir, boolean useTagDictionary, boolean useCaseSensitiveTagDictionary, int beamSize, double advancePercentage) throws IOException {
return new opennlp.tools.parser.treeinsert.Parser(
new SuffixSensitiveGISModelReader(new File(dataDir + "/build.bin.gz")).getModel(),
new SuffixSensitiveGISModelReader(new File(dataDir + "/attach.bin.gz")).getModel(),
new SuffixSensitiveGISModelReader(new File(dataDir + "/check.bin.gz")).getModel(),
new ParserTagger(dataDir + "/tag.bin.gz", dataDir + "/tagdict", useCaseSensitiveTagDictionary ),//, new Dictionary(dataDir+"/dict.bin.gz")),
new ParserChunker(dataDir + "/chunk.bin.gz"),
new HeadRules(dataDir + "/head_rules"),beamSize,advancePercentage);
}
private static String convertToken(String token) {
if (token.equals("(")) {
return "-LRB-";
}
else if (token.equals(")")) {
return "-RRB-";
}
else if (token.equals("{")) {
return "-LCB-";
}
else if (token.equals("}")) {
return "-RCB-";
}
return token;
}
public static Parse[] parseLine(String line, Parser parser, int numParses) {
line = untokenizedParenPattern1.matcher(line).replaceAll("$1 $2");
line = untokenizedParenPattern2.matcher(line).replaceAll("$1 $2");
StringTokenizer str = new StringTokenizer(line);
StringBuffer sb = new StringBuffer();
List tokens = new ArrayList();
while (str.hasMoreTokens()) {
String tok = convertToken(str.nextToken());
tokens.add(tok);
sb.append(tok).append(" ");
}
String text = sb.substring(0, sb.length() - 1);
Parse p = new Parse(text, new Span(0, text.length()), AbstractBottomUpParser.INC_NODE, 1, 0);
int start = 0;
int i=0;
for (Iterator ti = tokens.iterator(); ti.hasNext();i++) {
String tok = (String) ti.next();
p.insert(new Parse(text, new Span(start, start + tok.length()), AbstractBottomUpParser.TOK_NODE, 0,i));
start += tok.length() + 1;
}
Parse[] parses;
if (numParses == 1) {
parses = new Parse[] { parser.parse(p)};
}
else {
parses = parser.parse(p,numParses);
}
return parses;
}
private static void usage() {
System.err.println("Usage: TreebankParser [-d -i -bs n -ap f -type t] dataDirectory < tokenized_sentences");
System.err.println("dataDirectory: Directory containing parser models.");
System.err.println("-type [chunking|insertion]: Type of parser to use.");
System.err.println("-d: Use tag dictionary.");
System.err.println("-i: Case insensitive tag dictionary.");
System.err.println("-bs 20: Use a beam size of 20.");
System.err.println("-ap 0.95: Advance outcomes in with at least 95% of the probability mass.");
System.err.println("-k 5: Show the top 5 parses. This will also display their log-probablities.");
System.exit(1);
}
public static void main(String[] args) throws IOException {
if (args.length == 0) {
usage();
}
boolean useTagDictionary = false;
boolean caseSensitiveTagDictionary = true;
boolean showTopK = false;
String parserType = "chunking";
int numParses = 1;
int ai = 0;
int beamSize = AbstractBottomUpParser.defaultBeamSize;
double advancePercentage = AbstractBottomUpParser.defaultAdvancePercentage;
while (args[ai].startsWith("-")) {
if (args[ai].equals("-d")) {
useTagDictionary = true;
}
else if (args[ai].equals("-i")) {
caseSensitiveTagDictionary = false;
}
else if (args[ai].equals("-di") || args[ai].equals("-id")) {
useTagDictionary = true;
caseSensitiveTagDictionary = false;
}
else if (args[ai].equals("-bs")) {
if (args.length > ai+1) {
try {
beamSize=Integer.parseInt(args[ai+1]);
ai++;
}
catch(NumberFormatException nfe) {
System.err.println(nfe);
usage();
}
}
else {
usage();
}
}
else if (args[ai].equals("-ap")) {
if (args.length > ai+1) {
try {
advancePercentage=Double.parseDouble(args[ai+1]);
ai++;
}
catch(NumberFormatException nfe) {
System.err.println(nfe);
usage();
}
}
else {
usage();
}
}
else if (args[ai].equals("-k")) {
showTopK = true;
if (args.length > ai+1) {
try {
numParses=Integer.parseInt(args[ai+1]);
ai++;
}
catch(NumberFormatException nfe) {
System.err.println(nfe);
usage();
}
}
else {
usage();
}
}
else if (args[ai].equals("-type")) {
if (args.length > ai+1) {
parserType = args[ai+1];
ai++;
if (!parserType.equals("chunking") && !parserType.equals("insertion")) {
usage();
}
}
else {
usage();
}
}
else if (args[ai].equals("
ai++;
break;
}
else {
System.err.println("Unknown option "+args[ai]);
usage();
}
ai++;
}
Parser parser = null;
if (parserType.equals("chunking")) {
if (!caseSensitiveTagDictionary) {
parser = TreebankParser.getParser(args[ai++], true, false,beamSize,advancePercentage);
}
else if (useTagDictionary) {
parser = TreebankParser.getParser(args[ai++], true, true,beamSize,advancePercentage);
}
else {
parser = TreebankParser.getParser(args[ai++], false, false,beamSize,advancePercentage);
}
}
else if (parserType.equals("insertion")) {
parser = TreebankParser.getInsertionParser(args[ai++], false, false,beamSize,advancePercentage);
}
BufferedReader in;
if (ai == args.length) {
in = new BufferedReader(new InputStreamReader(System.in));
}
else {
in = new BufferedReader(new FileReader(args[ai]));
}
String line;
try {
while (null != (line = in.readLine())) {
if (line.length() == 0) {
System.out.println();
}
else {
Parse[] parses = parseLine(line, parser, numParses);
for (int pi=0,pn=parses.length;pi<pn;pi++) {
if (showTopK) {
System.out.print(pi+" "+parses[pi].getProb()+" ");
}
parses[pi].show();
}
}
}
}
catch (IOException e) {
System.err.println(e);
}
}
}
|
package org.jsimpledb.kv.fdb;
import com.foundationdb.Database;
import com.foundationdb.FDB;
import com.foundationdb.FDBException;
import com.foundationdb.NetworkOptions;
import java.util.concurrent.Executor;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import org.jsimpledb.kv.KVDatabase;
import org.jsimpledb.kv.KVDatabaseException;
/**
* FoundationDB {@link KVDatabase} implementation.
*
* <p>
* Allows specifying a {@linkplain #setKeyPrefix key prefix} for all keys, allowing multiple independent databases.
* </p>
*/
public class FoundationKVDatabase implements KVDatabase {
/**
* The API version used by this class.
*/
public static final int API_VERSION = 200;
private final FDB fdb = FDB.selectAPIVersion(API_VERSION);
private final NetworkOptions options = this.fdb.options();
private String clusterFilePath;
private byte[] databaseName = new byte[] { (byte)'D', (byte)'B' };
private byte[] keyPrefix;
private Executor executor;
private Database database;
/**
* Constructor.
*
* @throws FDBException if {@link #API_VERSION} is not supported
*/
public FoundationKVDatabase() {
}
/**
* Get the {@link NetworkOptions} associated with this instance.
* Options must be configured prior to {@link #start}.
*/
public NetworkOptions getNetworkOptions() {
return this.options;
}
/**
* Configure the {@link Executor} used for the FoundationDB networking event loop.
*/
public void setExecutor(Executor executor) {
this.executor = executor;
}
/**
* Configure the cluster file path. Default is null, which results in the default fdb.cluster file being used.
*/
public void setClusterFilePath(String clusterFilePath) {
this.clusterFilePath = clusterFilePath;
}
/**
* Configure the database name. Currently the default value ({@code "DB".getBytes()}) is the only valid value.
*/
public void setDatabaseName(byte[] databaseName) {
this.databaseName = databaseName;
}
/**
* Get the key prefix for all keys.
*
* @return key prefix, or null if there is none configured
*/
public byte[] getKeyPrefix() {
return this.keyPrefix.clone();
}
public void setKeyPrefix(byte[] keyPrefix) {
if (this.database != null)
throw new IllegalStateException("already started");
this.keyPrefix = keyPrefix != null && keyPrefix.length > 0 ? keyPrefix.clone() : null;
}
public Database getDatabase() {
if (this.database == null)
throw new IllegalStateException("not started");
return this.database;
}
@PostConstruct
public synchronized void start() {
if (this.database != null)
throw new IllegalStateException("already started");
this.database = this.fdb.open(this.clusterFilePath, this.databaseName);
if (this.executor != null)
this.fdb.startNetwork(this.executor);
else
this.fdb.startNetwork();
}
/**
* Stop this instance. Invokes {@link FDB#stopNetwork}. Does nothing if not {@linkplain #start started}.
*
* @throws FDBException if an error occurs
*/
@PreDestroy
public synchronized void stop() {
if (this.database == null)
return;
this.fdb.stopNetwork();
}
@Override
public FoundationKVTransaction createTransaction() {
if (this.database == null)
throw new IllegalStateException("not started");
try {
return new FoundationKVTransaction(this, this.keyPrefix);
} catch (FDBException e) {
throw new KVDatabaseException(this, e);
}
}
}
|
package org.neo4j.impl.cache;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.logging.Logger;
public class AdaptiveCacheManager
{
private static Logger log =
Logger.getLogger( AdaptiveCacheManager.class.getName() );
// private static final AdaptiveCacheManager instance =
// new AdaptiveCacheManager();
// public static AdaptiveCacheManager getManager()
// return instance;
public AdaptiveCacheManager()
{
}
private final List<AdaptiveCacheElement> caches =
new CopyOnWriteArrayList<AdaptiveCacheElement>();
private AdaptiveCacheWorker workerThread;
public synchronized void registerCache( Cache<?,?> cache,
float ratio, int minSize )
{
if ( cache == null || ratio >= 1 || ratio <= 0 ||
minSize < 0 )
{
throw new IllegalArgumentException(
" cache=" + cache + " ratio =" + ratio + " minSize=" +
minSize );
}
AdaptiveCacheElement element = new AdaptiveCacheElement(
cache, ratio, minSize );
int elementIndex = getAdaptiveCacheElementIndex( cache );
if ( elementIndex == -1 )
{
caches.add( element );
}
cache.setAdaptiveStatus( true );
log.fine( "Cache[" + cache.getName() + "] threshold=" + ratio +
"minSize=" + minSize + " registered." );
}
public synchronized void unregisterCache( Cache<?,?> cache )
{
if ( cache == null )
{
throw new IllegalArgumentException( "Null cache" );
}
int elementIndex = getAdaptiveCacheElementIndex( cache );
if ( elementIndex != -1 )
{
caches.remove( elementIndex );
}
cache.setAdaptiveStatus( false );
log.fine( "Cache[" + cache.getName() + "] removed." );
}
int getAdaptiveCacheElementIndex( Cache<?,?> cache )
{
int i = 0;
for ( AdaptiveCacheElement element : caches )
{
if ( element.getCache() == cache )
{
return i;
}
i++;
}
return -1;
}
public void start()
{
workerThread = new AdaptiveCacheWorker();
workerThread.start();
}
public void stop()
{
workerThread.markDone();
workerThread = null;
}
Collection<AdaptiveCacheElement> getCaches()
{
return caches;
}
private class AdaptiveCacheWorker extends Thread
{
private boolean done = false;
AdaptiveCacheWorker()
{
super( "AdaptiveCacheWorker" );
}
public void run()
{
while ( !done )
{
try
{
adaptCaches();
Thread.sleep( 3000 );
}
catch (InterruptedException e)
{
}
}
}
private void adaptCaches()
{
for ( AdaptiveCacheElement element : getCaches() )
{
adaptCache( element.getCache() );
}
}
void markDone()
{
done = true;
}
}
public void adaptCache( Cache<?,?> cache )
{
if ( cache == null )
{
throw new IllegalArgumentException( "Null cache" );
}
int elementIndex = getAdaptiveCacheElementIndex( cache );
if ( elementIndex != -1 )
{
adaptCache( caches.get( elementIndex ) );
}
}
private void adaptCache( AdaptiveCacheElement element )
{
long max = Runtime.getRuntime().maxMemory();
long total = Runtime.getRuntime().totalMemory();
long free = Runtime.getRuntime().freeMemory();
float ratio = (float) (max - free) / max;
float allocationRatio = (float) total / max;
if ( allocationRatio < element.getRatio() )
{
// allocation ratio < 1 means JVM can still increase heap size
// we won't decrease caches until element ratio is less
// then allocationRatio
ratio = 0;
}
// System.out.println( "max= " + max + " total=" + total +
// " ratio= " + ratio + " ... free=" + free );
if ( ratio > element.getRatio() )
{
// decrease cache size
// after decrease we resize again with +1000 to avoid
// spam of this method
Cache<?,?> cache = element.getCache();
int newCacheSize = (int) ( cache.maxSize() / 1.15 /
(1 + (ratio - element.getRatio())));
int minSize = element.minSize();
if ( newCacheSize < minSize )
{
log.fine( "Cache[" + cache.getName() +
"] cannot decrease under " +
minSize + " (allocation ratio=" + allocationRatio +
" threshold status=" + ratio + ")" );
cache.resize( minSize );
cache.resize( minSize + 1000 );
return;
}
if ( newCacheSize + 1200 > cache.size() )
{
if ( cache.size() - 1200 >= minSize )
{
newCacheSize = cache.size() - 1200;
}
else
{
newCacheSize = minSize;
}
}
log.fine( "Cache[" + cache.getName() + "] decreasing from " +
cache.size() + " to " + newCacheSize +
" (allocation ratio=" + allocationRatio +
" threshold status=" + ratio + ")" );
if ( newCacheSize <= 1000 )
{
cache.clear();
}
else
{
cache.resize( newCacheSize );
}
cache.resize( newCacheSize + 1000 );
}
else
{
// increase cache size
Cache<?,?> cache = element.getCache();
if ( cache.size() /
(float) cache.maxSize() < 0.9f )
{
return;
}
int newCacheSize = (int) (cache.maxSize() * 1.1);
log.fine( "Cache[" + cache.getName() + "] increasing from " +
cache.size() + " to " + newCacheSize +
" (allocation ratio=" + allocationRatio +
" threshold status=" + ratio + ")" );
cache.resize( newCacheSize );
}
}
private static class AdaptiveCacheElement
{
private final Cache<?,?> cache;
private final float ratio;
private final int minSize;
AdaptiveCacheElement( Cache<?,?> cache, float ratio,
int minSize )
{
this.cache = cache;
this.ratio = ratio;
this.minSize = minSize;
}
String getName()
{
return cache.getName();
}
Cache<?,?> getCache()
{
return cache;
}
float getRatio()
{
return ratio;
}
int minSize()
{
return minSize;
}
}
}
|
package gens.rft.standard;
import general.GenModel;
import gens.rft.Function;
import gens.rft.TreeNode;
import java.util.Random;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.StringProperty;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.image.PixelWriter;
import javafx.scene.paint.Color;
/**
*
* @author Moritz Rieger
*/
public class RandomFunctionTreeModel extends GenModel {
private static final int UNARY = 1;
private static final int BINARY = 2;
private final int R;
private final int G;
private final int B;
private final IntegerProperty widthProperty = new SimpleIntegerProperty(250);
private final IntegerProperty heightProperty = new SimpleIntegerProperty(250);
private final IntegerProperty minDepthProperty = new SimpleIntegerProperty(2);
private final IntegerProperty maxDepthProperty = new SimpleIntegerProperty(6);
private final IntegerProperty seedProperty = new SimpleIntegerProperty(10);
private Function[] functions;
private Random random;
public RandomFunctionTreeModel(){
createFunctions();
random = new Random(seedProperty.getValue());
R = random.nextInt(255);
G = random.nextInt(255);
B = random.nextInt(255);
}
public void validate() {
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public String getGenName() {
return "Standard Random Function Tree Generator";
}
@Override
public void generate() {
Function rootNode = createTree(minDepthProperty.getValue());
canvas = new Canvas(widthProperty.getValue(), heightProperty.getValue());
GraphicsContext gc = canvas.getGraphicsContext2D();
PixelWriter pw = gc.getPixelWriter();
//loop through every pixel
for(int x = 0; x < widthProperty.getValue(); x++){
for(int y = 0; y < heightProperty.getValue(); y++){
int rnd = random.nextInt(functions.length);
//System.out.println("function no. " + rnd);
double[] nCoords = normalize(x,y);
//double result = functions[rnd].getResult(nCoords[0], nCoords[1]);
double result = evalRFT(rootNode, nCoords[0], nCoords[1]);
//System.out.println("Result "+result+" for x"+ x+ " y " + y);
int percentage =(int) ((double)(x*heightProperty.getValue())/(double)(widthProperty.getValue()*heightProperty.getValue())*100);
setGenState("Calculating Randomized Function Tree Image " + percentage + " %");
pw.setColor(x, y, getColor(result));
//gc.setFill(Color.WHITE);
//gc.fillRect(0, 0, 500, 500);
waitForCanvasIterationDisplayedInApp();
}
}
}
public IntegerProperty getWidthProperty() {
return widthProperty;
}
public IntegerProperty getHeightProperty() {
return heightProperty;
}
public IntegerProperty getMinDepthProperty() {
return minDepthProperty;
}
public IntegerProperty getMaxDepthProperty() {
return maxDepthProperty;
}
private void createFunctions(){
functions = new Function[6];
//unary functions
functions[0] = new Function(UNARY){
@Override
public double getResult(double x, double y){
return Math.sin(2*Math.PI*x);
}
};
functions[1] = new Function(UNARY){
@Override
public double getResult(double x, double y){
return Math.cos(2*Math.PI*x);
}
};
functions[2] = new Function(BINARY){
@Override
public double getResult(double x, double y){
return Math.pow(x, y);
}
};
//binary functions
functions[3] = new Function(BINARY){
@Override
public double getResult(double x, double y){
return (x+y)/2;
}
};
functions[4] = new Function(BINARY){
@Override
public double getResult(double x, double y){
return x*y;
}
};
functions[5] = new Function(BINARY){
@Override
public double getResult(double x, double y){
return x-y;
}
};
}
private double[] normalize(int x,int y){
double[] result = {x/widthProperty.doubleValue(), y/heightProperty.doubleValue()};
return result;
}
/**
* creates recursively a directional Tree in the given depth
* @param depth
* @return
*/
private Function createTree(int depth){
Function node;
//take random function from pool
node = functions[random.nextInt(functions.length-1)];
//create one children for unary, two for binary ...
if(depth > 0){
Function[] children = new Function[node.getType()];
for(int i=0; i < children.length; i++){
children[i] = createTree(depth-1);
}
node.setChildren(children);
}
System.out.println("childrencount"+node.getChildrenCount());
return node;
}
/**
* recursively evaluate a random function tree
* @param node
* @param x
* @param y
* @return
*/
private double evalRFT(Function node, double x, double y){
System.out.println("count" + node.getChildrenCount());
if(node.getChildrenCount() > 0){
Function[] children = (Function[]) node.getChildren();
//save results from each children
double[] values = new double[children.length];
for(int i=0; i<children.length; i++){
values[i] = evalRFT(children[i], x, y);
}
//when all childrens are evaluated we can set the values of the children in this nodes function
switch (node.getType()){
case UNARY: return node.getResult(values[0], values[0]);
case BINARY: return node.getResult(values[0], values[1]);
default: return node.getResult(values[0], values[0]); //this should never be reached, just to satisfy javacompiler
}
}else{
System.out.println("Coords for x"+ x+ " y " + y);
return node.getResult(x, y);
}
}
private Color getColor(double val){
int r = (int) (R * val);
int g = (int) (G * val);
int b = (int) (B * val);
return Color.rgb(r,g,b);
}
}
|
package gscrot.processor.watermark;
import javax.swing.JDialog;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JRadioButton;
import javax.swing.JLabel;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.ScrollPaneConstants;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
@SuppressWarnings("serial")
public class DialogSettings extends JDialog {
private JTextField textField;
private JButton btnFont;
private JButton btnColor;
private JTextPane textPane;
public DialogSettings() {
setTitle("Watermark Settings");
JRadioButton rdbtnImage = new JRadioButton("Image");
JLabel lblFile = new JLabel("File:");
textField = new JTextField();
textField.setEditable(false);
textField.setColumns(10);
JButton btnBrowse = new JButton("Browse");
JRadioButton rdbtnLabel = new JRadioButton("Label");
rdbtnLabel.setSelected(true);
JLabel lblText = new JLabel("Text:");
JScrollPane scrollPane = new JScrollPane();
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
btnFont = new JButton("Font");
btnFont.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JFontChooser j = new JFontChooser();
j.showDialog(DialogSettings.this);
textPane.setFont(j.getSelectedFont());
}
});
btnColor = new JButton("Color");
GroupLayout groupLayout = new GroupLayout(getContentPane());
groupLayout.setHorizontalGroup(
groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addContainerGap()
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addComponent(rdbtnImage)
.addPreferredGap(ComponentPlacement.UNRELATED)
.addComponent(lblFile)
.addGap(12)
.addComponent(textField, GroupLayout.PREFERRED_SIZE, 240, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(btnBrowse))
.addGroup(groupLayout.createSequentialGroup()
.addComponent(rdbtnLabel)
.addPreferredGap(ComponentPlacement.UNRELATED)
.addComponent(lblText)
.addPreferredGap(ComponentPlacement.UNRELATED)
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addComponent(btnFont)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(btnColor))
.addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 239, GroupLayout.PREFERRED_SIZE))))
.addContainerGap(152, Short.MAX_VALUE))
);
groupLayout.setVerticalGroup(
groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addContainerGap()
.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(rdbtnImage)
.addComponent(lblFile)))
.addGroup(groupLayout.createSequentialGroup()
.addGap(8)
.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(textField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(btnBrowse))))
.addPreferredGap(ComponentPlacement.UNRELATED)
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(rdbtnLabel)
.addComponent(lblText))
.addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 81, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(btnFont)
.addComponent(btnColor))
.addContainerGap(209, Short.MAX_VALUE))
);
textPane = new JTextPane();
scrollPane.setViewportView(textPane);
getContentPane().setLayout(groupLayout);
}
}
|
package ibis.impl.nameServer.tcp;
import ibis.impl.nameServer.NameServer;
import ibis.ipl.ConnectionRefusedException;
import ibis.ipl.ConnectionTimedOutException;
import ibis.ipl.Ibis;
import ibis.ipl.IbisConfigurationException;
import ibis.ipl.IbisIdentifier;
import ibis.ipl.ReceivePortIdentifier;
import ibis.ipl.StaticProperties;
import ibis.util.DummyInputStream;
import ibis.util.DummyOutputStream;
import ibis.util.IbisSocketFactory;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StreamCorruptedException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Properties;
public class NameServerClient extends NameServer implements Runnable, Protocol {
static final boolean DEBUG = false;
private PortTypeNameServerClient portTypeNameServerClient;
private ReceivePortNameServerClient receivePortNameServerClient;
private ElectionClient electionClient;
private ServerSocket serverSocket;
private Ibis ibisImpl;
private IbisIdentifier id;
private volatile boolean stop = false;
private InetAddress serverAddress;
private String server;
private int port;
private String poolName;
private InetAddress myAddress;
public NameServerClient() {
}
protected void init(Ibis ibisImpl) throws IOException, IbisConfigurationException {
this.ibisImpl = ibisImpl;
this.id = ibisImpl.identifier();
Properties p = System.getProperties();
String myIp = p.getProperty("ip_address");
if (myIp == null) {
myAddress = InetAddress.getLocalHost();
} else {
myAddress = InetAddress.getByName(myIp);
}
server = p.getProperty("ibis.name_server.host");
if (server == null) {
throw new IbisConfigurationException("property ibis.name_server.host is not specified");
}
poolName = p.getProperty("ibis.name_server.key");
if (poolName == null) {
throw new IbisConfigurationException("property ibis.name_server.key is not specified");
}
String nameServerPortString = p.getProperty("ibis.name_server.port");
if (nameServerPortString == null) {
port = ibis.impl.nameServer.tcp.NameServer.TCP_IBIS_NAME_SERVER_PORT_NR;
} else {
try {
port = Integer.parseInt(nameServerPortString);
if(DEBUG) {
System.err.println("Using nameserver port: " + port);
}
} catch (Exception e) {
System.err.println("illegal nameserver port: " + nameServerPortString + ", using default");
}
}
serverAddress = InetAddress.getByName(server);
if(DEBUG) {
System.err.println("Found nameServerInet " + serverAddress);
}
serverSocket = IbisSocketFactory.createServerSocket(0, myAddress, true);
boolean retry = false;
String retryStr = p.getProperty("ibis.name_server.retry");
if (retryStr != null) {
if(retryStr.equals("true")) {
retry = true;
} else if (retryStr.equals("false")) {
retry = false;
} else {
throw new IbisConfigurationException("property ibis.name_server.retry has non-boolean value");
}
}
Socket s = null;
boolean failed_once = false;
while(s == null) {
try {
s = IbisSocketFactory.createSocket(serverAddress,
port, myAddress, -1);
} catch (ConnectionTimedOutException e) {
if(!retry) {
throw new ConnectionTimedOutException("Could not connect to name server "+server);
}
if(!failed_once) {
System.err.println("Nameserver client failed"
+ " to connect to nameserver\n at "
+ serverAddress + ":" + port
+ ", will keep trying");
failed_once = true;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e2) {
// don't care
}
}
}
DummyOutputStream dos = new DummyOutputStream(s.getOutputStream());
ObjectOutputStream out =
new ObjectOutputStream(new BufferedOutputStream(dos));
if (DEBUG) {
System.out.println("NameServerClient: contacting nameserver");
}
out.writeByte(IBIS_JOIN);
out.writeUTF(poolName);
out.writeObject(id);
out.writeObject(myAddress);
out.writeInt(serverSocket.getLocalPort());
out.flush();
DummyInputStream di = new DummyInputStream(s.getInputStream());
ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(di));
int opcode = in.readByte();
if (DEBUG) {
System.out.println("NameServerClient: nameserver reply, opcode " + opcode);
}
switch (opcode) {
case IBIS_REFUSED:
IbisSocketFactory.close(in, out, s);
throw new ConnectionRefusedException("NameServerClient: " + id.name() + " is not unique!");
case IBIS_ACCEPTED:
// read the ports for the other name servers and start the receiver thread...
int temp = in.readInt(); /* Port for the PortTypeNameServer */
portTypeNameServerClient = new PortTypeNameServerClient(myAddress, serverAddress, temp);
temp = in.readInt(); /* Port for the ReceivePortNameServer */
receivePortNameServerClient = new ReceivePortNameServerClient(myAddress, serverAddress, temp);
temp = in.readInt(); /* Port for the ElectionServer */
electionClient = new ElectionClient(myAddress, serverAddress, temp);
int poolSize = in.readInt();
if (DEBUG) {
System.out.println("NameServerClient: accepted by nameserver, poolsize " + poolSize);
}
for(int i=0; i<poolSize; i++) {
IbisIdentifier newid;
try {
newid = (IbisIdentifier) in.readObject();
} catch (ClassNotFoundException e) {
throw new IOException("Receive IbisIdent of unknown class " + e);
}
if(DEBUG) {
System.out.println("NameServerClient: join of " + newid);
}
ibisImpl.join(newid);
if(DEBUG) {
System.out.println("NameServerClient: join of " + newid + " DONE");
}
}
IbisSocketFactory.close(in, out, s);
new Thread(this, "NameServerClient accept thread").start();
break;
default:
IbisSocketFactory.close(in, out, s);
throw new StreamCorruptedException("NameServerClient: got illegal opcode " + opcode);
}
}
public boolean newPortType(String name, StaticProperties p) throws IOException {
return portTypeNameServerClient.newPortType(name, p);
}
public void leave() throws IOException {
if(DEBUG) {
System.err.println("NS client: leave");
}
Socket s = IbisSocketFactory.createSocket(serverAddress, port, myAddress, 0 /* retry */);
DummyOutputStream dos = new DummyOutputStream(s.getOutputStream());
ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(dos));
out.writeByte(IBIS_LEAVE);
out.writeUTF(poolName);
out.writeObject(id);
out.flush();
if(DEBUG) {
System.err.println("NS client: leave sent");
}
DummyInputStream di = new DummyInputStream(s.getInputStream());
ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(di));
int temp = in.readByte();
if(DEBUG) {
System.err.println("NS client: leave ack received");
}
IbisSocketFactory.close(null, out, s);
// stop = true;
// this.interrupt();
if(DEBUG) {
System.err.println("NS client: leave DONE");
}
}
public void run() {
if (DEBUG) {
System.out.println("NameServerClient: stread started");
}
while (true) { // !stop
Socket s;
IbisIdentifier id;
try {
s = IbisSocketFactory.accept(serverSocket);
if (DEBUG) {
System.out.println("NameServerClient: incoming connection from " + s.toString());
}
} catch (Exception e) {
if (stop) {
if (DEBUG) {
System.out.println("NameServerClient: thread dying");
}
try {
serverSocket.close();
} catch (IOException e1) {
}
return;
}
throw new RuntimeException("NameServerClient: got an error " + e.getMessage());
}
int opcode = 666;
try {
DummyInputStream di = new DummyInputStream(s.getInputStream());
ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(di));
opcode = in.readByte();
switch (opcode) {
case (IBIS_JOIN):
id = (IbisIdentifier) in.readObject();
IbisSocketFactory.close(in, null, s);
ibisImpl.join(id);
break;
case (IBIS_LEAVE):
id = (IbisIdentifier) in.readObject();
IbisSocketFactory.close(in, null, s);
if(id.equals(this.id)) {
// received an ack from the nameserver that I left.
if (DEBUG) {
System.out.println("NameServerClient: thread dying");
}
return;
} else {
ibisImpl.leave(id);
}
break;
default:
System.out.println("NameServerClient: got an illegal opcode " + opcode);
}
} catch (Exception e1) {
System.out.println("Got an exception in NameServerClient.run (opcode = " + opcode + ") " + e1.toString());
if(stop) return;
e1.printStackTrace();
if (s != null) {
IbisSocketFactory.close(null, null, s);
}
}
}
}
public ReceivePortIdentifier lookup(String name) throws IOException {
return lookup(name, 0);
}
public ReceivePortIdentifier lookup(String name, long timeout) throws IOException {
return receivePortNameServerClient.lookup(name, timeout);
}
public IbisIdentifier locate(String name) throws IOException {
return locate(name, 0);
}
public IbisIdentifier locate(String name, long timeout) throws IOException {
/* not implemented yet */
return null;
}
public ReceivePortIdentifier [] query(IbisIdentifier ident) throws IOException, ClassNotFoundException {
/* not implemented yet */
return new ReceivePortIdentifier[0];
}
public Object elect(String election, Object candidate) throws IOException, ClassNotFoundException {
return electionClient.elect(election, candidate);
}
//gosia
public void bind(String name, ReceivePortIdentifier rpi) throws IOException {
receivePortNameServerClient.bind(name, rpi);
}
public void rebind(String name, ReceivePortIdentifier rpi) throws IOException {
receivePortNameServerClient.rebind(name, rpi);
}
public void unbind(String name) throws IOException {
receivePortNameServerClient.unbind(name);
}
public String[] list(String pattern) throws IOException {
return receivePortNameServerClient.list(pattern);
}
//end gosia
}
|
package org.xins.util.threads;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.Set;
/**
* Monitor that acts like a doorman. It implements a variation of the
* <em>Alternating Reader Writer</em> algorithm.
*
* @version $Revision$ $Date$
* @author Ernst de Haan (<a href="mailto:znerd@FreeBSD.org">znerd@FreeBSD.org</a>)
*
* @since XINS 0.66
*/
public final class Doorman extends Object {
// Class fields
/**
* The type for readers in the queue.
*/
private static final Queue.EntryType READ_QUEUE_ENTRY_TYPE = new Queue.EntryType();
/**
* The type for writers in the queue.
*/
private static final Queue.EntryType WRITE_QUEUE_ENTRY_TYPE = new Queue.EntryType();
// Class functions
// Constructors
public Doorman(int queueSize)
throws IllegalArgumentException {
// Check preconditions
if (queueSize < 0) {
throw new IllegalArgumentException("queueSize (" + queueSize + ") < 0");
}
// Initialize fields
_currentActorLock = new Object();
_currentReaders = new HashSet();
_queue = new Queue(queueSize);
_readAccess = new Object();
_writeAccess = new Object();
}
// Fields
/**
* Lock object for reading and writing the set of current readers and the
* current writer.
*/
private final Object _currentActorLock;
/**
* The set of currently active readers. All elements in the set are
* {@link Thread} instances.
*/
private final Set _currentReaders;
/**
* The currently active writer, if any.
*/
private Thread _currentWriter;
/**
* The queue that contains the waiting readers and writers.
*/
private final Queue _queue;
/**
* Object used for waiting for read access.
*/
private final Object _readAccess;
/**
* Object used for waiting for write access.
*/
private final Object _writeAccess;
// Methods
/**
* Enters the 'protected area' as a reader. If necessary, this method will
* wait until the area can be entered.
*
* @throws InterruptedException
* if a {@link Object#wait()} call was interrupted.
*/
public void enterAsReader()
throws InterruptedException {
Thread reader = Thread.currentThread();
boolean enterQueue;
synchronized (_currentActorLock) {
// Short-circuit if this thread is already entered
if (_currentReaders.contains(reader)) {
return;
}
// If there is an existing queue, or if a writer is busy, line up.
enterQueue = !_queue.isEmpty() || _currentWriter != null;
// If we don't have to join the queue, join the set of current
// readers and go ahead
if (!enterQueue) {
_currentReaders.add(reader);
return;
// Otherwise we must join the queue
} else {
synchronized (_queue) {
_queue.add(reader, READ_QUEUE_ENTRY_TYPE);
}
}
}
// Wait for read access
boolean mayEnter;
do {
synchronized (_currentActorLock) {
mayEnter = _currentReaders.contains(reader);
}
if (! mayEnter) {
boolean exceptionThrown = true;
try {
_readAccess.wait();
exceptionThrown = false;
} finally {
if (exceptionThrown) {
synchronized (_currentActorLock) {
_queue.remove(reader);
}
}
}
}
} while (! mayEnter);
}
/**
* Notifies all appropriate waiting threads in the queue.
*/
private void leave() {
Queue.EntryType type;
synchronized (_queue) {
type = _queue.getTypeOfFirst();
}
if (type == READ_QUEUE_ENTRY_TYPE) {
_readAccess.notifyAll();
} else if (type == WRITE_QUEUE_ENTRY_TYPE) {
_writeAccess.notifyAll();
}
}
/**
* Leaves the 'protected area' as a reader.
*/
public void leaveAsReader() {
Thread reader = Thread.currentThread();
synchronized (_currentActorLock) {
_currentReaders.remove(reader);
}
leave();
}
/**
* Leaves the 'protected area' as a writer.
*/
public void leaveAsWriter() {
// XXX: Thread writer = Thread.currentThread();
synchronized (_currentActorLock) {
// TODO: What if _currentWriter != writer ?
_currentWriter = null;
}
leave();
}
/**
* Enters the 'protected area' as a writer. If necessary, this method will
* wait until the area can be entered.
*
* @throws InterruptedException
* if a {@link Object#wait()} call was interrupted.
*/
public void enterAsWriter()
throws InterruptedException {
Thread writer = Thread.currentThread();
boolean enterQueue;
synchronized (_currentActorLock) {
// Short-circuit if this thread is already entered
if (_currentWriter == writer) {
return;
}
// If there is an existing queue, or if any thread is busy, line up.
enterQueue = !_queue.isEmpty() || !_currentReaders.isEmpty() || _currentWriter != null;
// If we don't have to join the queue, join the set of current
// readers and go ahead
if (!enterQueue) {
_currentWriter = writer;
return;
// Otherwise we must join the queue
} else {
synchronized (_queue) {
_queue.add(writer, WRITE_QUEUE_ENTRY_TYPE);
}
}
}
// Wait for write access
boolean mayEnter;
do {
synchronized (_currentActorLock) {
mayEnter = _currentWriter == writer;
}
if (! mayEnter) {
boolean exceptionThrown = true;
try {
_writeAccess.wait();
exceptionThrown = false;
} finally {
if (exceptionThrown) {
synchronized (_currentActorLock) {
_queue.remove(writer);
}
}
}
}
} while (! mayEnter);
}
// Inner class
/**
* Queue of waiting reader and writer threads.
*
* @version $Revision$ $Date$
* @author Ernst de Haan (<a href="mailto:znerd@FreeBSD.org">znerd@FreeBSD.org</a>)
*
* @since XINS 0.66
*/
private static final class Queue
extends Object {
// Constructors
public Queue(int capacity) {
if (capacity < 0) {
throw new IllegalArgumentException("capacity (" + capacity + ") < 0");
}
_entries = new LinkedList();
_entryTypes = new HashMap(capacity);
}
// Fields
/**
* The list of entries.
*/
private final LinkedList _entries;
/**
* The entry types, by entry. This map has the {@link Thread threads} as
* keys and their {@link EntryType types} as values.
*/
private final Map _entryTypes;
/**
* Cached link to the first entry. This field is either
* <code>null</code> or an instance of class {@link Thread}.
*/
private Thread _first;
/**
* Cached type of the first entry. This field is either
* <code>null</code> (if {@link #_entries} is empty), or
* <code>(EntryType) </code>{@link #_entries}<code>.</code>{@link List#get() get}<code>(0)</code>
* (if {@link #_entries} is not empty).
*/
private EntryType _typeOfFirst;
// Methods
public boolean isEmpty() {
return (_first == null);
}
public EntryType getTypeOfFirst() {
return _typeOfFirst;
}
public void add(Thread thread, EntryType type) {
if (_first == null) {
_first = thread;
_typeOfFirst = type;
}
_entryTypes.put(thread, type);
_entries.addLast(thread);
}
public void remove(Thread thread) {
_entryTypes.remove(thread);
if (thread == _first) {
_entries.removeFirst();
_first = (Thread) _entries.getFirst();
_typeOfFirst = _first == null ? null : (EntryType) _entryTypes.get(_first);
} else {
_entries.remove(thread);
}
}
// Inner classes
public static final class EntryType
extends Object {
// Constructors
// Fields
// Methods
}
}
}
|
package org.xins.util.threads;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.Set;
import org.apache.log4j.Logger;
/**
* Monitor that acts like a doorman. It implements a variation of the
* <em>Alternating Reader Writer</em> algorithm.
*
* @version $Revision$ $Date$
* @author Ernst de Haan (<a href="mailto:znerd@FreeBSD.org">znerd@FreeBSD.org</a>)
*
* @since XINS 0.66
*/
public final class Doorman extends Object {
// Class fields
/**
* The logging category used by this class. This class field is never
* <code>null</code>.
*/
private final static Logger LOG = Logger.getLogger(Doorman.class.getName());
/**
* The type for readers in the queue.
*/
private static final Queue.EntryType READ_QUEUE_ENTRY_TYPE = new Queue.EntryType();
/**
* The type for writers in the queue.
*/
private static final Queue.EntryType WRITE_QUEUE_ENTRY_TYPE = new Queue.EntryType();
/**
* The maximum time an entry can be in the queue. This is currently set to
* 30 seconds.
*/
private static final long MAX_QUEUE_WAIT_TIME = 10000L;
/**
* The number of instances of this class.
*/
private static int INSTANCE_COUNT;
/**
* The lock object for <code>INSTANCE_COUNT</code>.
*/
private static final Object INSTANCE_COUNT_LOCK = new Object();
// Class functions
// Constructors
public Doorman(int queueSize)
throws IllegalArgumentException {
// Check preconditions
if (queueSize < 0) {
throw new IllegalArgumentException("queueSize (" + queueSize + ") < 0");
}
// Initialize fields
synchronized (INSTANCE_COUNT_LOCK) {
_instanceID = INSTANCE_COUNT++;
}
_currentActorLock = new Object();
_currentReaders = new HashSet();
_queue = new Queue(queueSize);
if (LOG.isDebugEnabled()) {
LOG.debug("Constructed Doorman #" + _instanceID + '.');
}
}
// Fields
/**
* Lock object for reading and writing the set of current readers and the
* current writer.
*/
private final Object _currentActorLock;
/**
* The set of currently active readers. All elements in the set are
* {@link Thread} instances.
*/
private final Set _currentReaders;
/**
* The currently active writer, if any.
*/
private Thread _currentWriter;
/**
* The queue that contains the waiting readers and/or writers.
*/
private final Queue _queue;
/**
* Unique numeric identifier for this instance.
*/
private final int _instanceID;
// Methods
/**
* Enters the 'protected area' as a reader. If necessary, this method will
* wait until the area can be entered.
*
* @throws QueueTimeOutException
* if this thread was waiting in the queue for too long.
*/
public void enterAsReader()
throws QueueTimeOutException {
Thread reader = Thread.currentThread();
if (LOG.isDebugEnabled()) {
LOG.debug("Doorman #" + _instanceID + ", enterAsReader() called for thread " + reader + '.');
}
synchronized (_currentActorLock) {
// Check preconditions
if (_currentWriter == reader) {
throw new IllegalStateException("Thread cannot enter as a reader if it is already the active writer.");
} else if (_currentReaders.contains(reader)) {
throw new IllegalStateException("Thread cannot enter as a reader if it is already an active reader.");
}
// If there is a current writer, then we need to wait in the queue
boolean enterQueue = _currentWriter != null;
synchronized (_queue) {
// If there is no current writer, but there is already a queue,
// then we also need to join it
enterQueue = enterQueue ? true : !_queue.isEmpty();
// Join the queue if necessary
if (enterQueue) {
_queue.add(reader, READ_QUEUE_ENTRY_TYPE);
}
}
// If we don't have to join the queue, join the set of current
// readers and go ahead
if (!enterQueue) {
_currentReaders.add(reader);
return;
}
}
// Wait for read access
try {
Thread.sleep(MAX_QUEUE_WAIT_TIME);
throw new QueueTimeOutException();
} catch (InterruptedException exception) {
// fall through
}
synchronized (_currentActorLock) {
if (! _currentReaders.contains(reader)) {
throw new IllegalStateException("Thread was interrupted in enterAsReader(), but not in the set of current readers.");
}
}
}
/**
* Enters the 'protected area' as a writer. If necessary, this method will
* wait until the area can be entered.
*
* @throws QueueTimeOutException
* if this thread was waiting in the queue for too long.
*/
public void enterAsWriter()
throws QueueTimeOutException {
Thread writer = Thread.currentThread();
if (LOG.isDebugEnabled()) {
LOG.debug("Doorman #" + _instanceID + ", enterAsWriter() called for thread " + writer + '.');
}
synchronized (_currentActorLock) {
// Check preconditions
if (_currentWriter == writer) {
throw new IllegalStateException("Thread cannot enter as a writer if it is already the active writer.");
} else if (_currentReaders.contains(writer)) {
throw new IllegalStateException("Thread cannot enter as a writer if it is already an active reader.");
}
// If there is a current writer or one or more current readers, then
// we need to wait in the queue
boolean enterQueue = ! (_currentWriter == null && _currentReaders.isEmpty());
// Join the queue if necessary
if (enterQueue) {
synchronized (_queue) {
_queue.add(writer, WRITE_QUEUE_ENTRY_TYPE);
}
// If we don't have to join the queue, become the current writer and
// return
} else {
_currentWriter = writer;
return;
}
}
// Wait for write access
try {
Thread.sleep(MAX_QUEUE_WAIT_TIME);
throw new QueueTimeOutException();
} catch (InterruptedException exception) {
// fall through
}
synchronized (_currentActorLock) {
if (_currentWriter != writer) {
throw new IllegalStateException("Thread was interrupted in enterAsWriter(), but is not set as the current writer.");
}
}
}
/**
* Leaves the 'protected area' as a reader.
*/
public void leaveAsReader() {
Thread reader = Thread.currentThread();
if (LOG.isDebugEnabled()) {
LOG.debug("Doorman #" + _instanceID + ", leaveAsReader() called for thread " + reader + '.');
}
synchronized (_currentActorLock) {
boolean readerRemoved = _currentReaders.remove(reader);
if (!readerRemoved) {
throw new IllegalStateException("Cannot leave protected area as reader, because it has not entered as a reader.");
}
if (_currentReaders.isEmpty()) {
synchronized (_queue) {
// Determine if the queue has a writer atop, a reader atop or is
// empty
Queue.EntryType type = _queue.getTypeOfFirst();
if (type == WRITE_QUEUE_ENTRY_TYPE) {
// If a writer is waiting, activate it
_currentWriter = _queue.pop();
_currentWriter.interrupt();
} else if (type == READ_QUEUE_ENTRY_TYPE) {
// If a reader leaves, the queue cannot contain a reader at the
// top, it must be either empty or have a writer at the top
throw new IllegalStateException("Found writer at top of queue while a reader is leaving the protected area.");
}
}
}
}
}
/**
* Leaves the 'protected area' as a writer.
*/
public void leaveAsWriter() {
Thread writer = Thread.currentThread();
if (LOG.isDebugEnabled()) {
LOG.debug("Doorman #" + _instanceID + ", leaveAsWriter() called for thread " + writer + '.');
}
synchronized (_currentActorLock) {
if (_currentWriter != writer) {
throw new IllegalStateException("Cannot leave protected area as writer, because it has not entered as a writer.");
}
synchronized (_queue) {
// Determine if the queue has a writer atop, a reader atop or is
// empty
Queue.EntryType type = _queue.getTypeOfFirst();
// If a writer is waiting, activate it alone
if (type == WRITE_QUEUE_ENTRY_TYPE) {
_currentWriter = _queue.pop();
_currentWriter.interrupt();
// If readers are on top, active all readers atop
} else if (type == READ_QUEUE_ENTRY_TYPE) {
do {
Thread reader = _queue.pop();
_currentReaders.add(reader);
reader.interrupt();
} while (_queue.getTypeOfFirst() == READ_QUEUE_ENTRY_TYPE);
// Otherwise there is no active thread, make sure to reset the
// current writer
} else {
_currentWriter = null;
}
}
}
}
// Inner class
/**
* Queue of waiting reader and writer threads.
*
* @version $Revision$ $Date$
* @author Ernst de Haan (<a href="mailto:znerd@FreeBSD.org">znerd@FreeBSD.org</a>)
*
* @since XINS 0.66
*/
private static final class Queue
extends Object {
// Constructors
public Queue(int capacity) {
if (capacity < 0) {
throw new IllegalArgumentException("capacity (" + capacity + ") < 0");
}
_entries = new LinkedList();
_entryTypes = new HashMap(capacity);
}
// Fields
/**
* The list of entries.
*/
private final LinkedList _entries;
/**
* The entry types, by entry. This map has the {@link Thread threads} as
* keys and their {@link EntryType types} as values.
*/
private final Map _entryTypes;
/**
* Cached link to the first entry. This field is either
* <code>null</code> or an instance of class {@link Thread}.
*/
private Thread _first;
/**
* Cached type of the first entry. This field is either
* <code>null</code> (if {@link #_entries} is empty), or
* <code>(EntryType) </code>{@link #_entries}<code>.</code>{@link List#get() get}<code>(0)</code>
* (if {@link #_entries} is not empty).
*/
private EntryType _typeOfFirst;
// Methods
/**
* Determines if this queue is empty.
*
* @return
* <code>true</code> if this queue is empty, <code>false</code> if it
* is not.
*/
public boolean isEmpty() {
return (_first == null);
}
/**
* Gets the type of the first waiting thread in this queue. If this
* queue is empty, then <code>null</code> is returned.
*
* @return
* <code>null</code> if this queue is empty;
* {@link #READ_QUEUE_ENTRY_TYPE} is the first thread in this queue
* is waiting for read access;
* {@link #WRITE_QUEUE_ENTRY_TYPE} is the first thread in this queue
* is waiting for write access;
*/
public EntryType getTypeOfFirst() {
return _typeOfFirst;
}
public void add(Thread thread, EntryType type)
throws IllegalStateException {
// Check preconditions
if (_entryTypes.containsKey(thread)) {
throw new IllegalStateException("The specified thread is already in this queue.");
}
// If the queue is empty, then store the new waiter as the first
if (_first == null) {
_first = thread;
_typeOfFirst = type;
}
// Store the waiter thread and its type
_entryTypes.put(thread, type);
_entries.addLast(thread);
}
public Thread pop() throws IllegalStateException {
// Check preconditions
if (_first == null) {
throw new IllegalStateException("This queue is empty.");
}
Thread oldFirst = _first;
// Remove the current first
_entries.removeFirst();
_entryTypes.remove(oldFirst);
// Get the new first, now that the other one is removed
Object newFirst = _entries.getFirst();
_first = newFirst == null ? null : (Thread) _entries.getFirst();
_typeOfFirst = newFirst == null ? null : (EntryType) _entryTypes.get(_first);
return oldFirst;
}
public void remove(Thread thread)
throws IllegalStateException {
if (thread == _first) {
// Remove the current first
_entries.removeFirst();
// Get the new first, now that the other one is removed
Object newFirst = _entries.getFirst();
_first = newFirst == null ? null : (Thread) _entries.getFirst();
_typeOfFirst = newFirst == null ? null : (EntryType) _entryTypes.get(_first);
} else {
// Remove the thread from the list
if (! _entries.remove(thread)) {
throw new IllegalStateException("The specified thread is not in this queue.");
}
}
_entryTypes.remove(thread);
}
// Inner classes
/**
* Type of an entry in a queue for a doorman.
*
* @version $Revision$ $Date$
* @author Ernst de Haan (<a href="mailto:znerd@FreeBSD.org">znerd@FreeBSD.org</a>)
*
* @since XINS 0.66
*/
public static final class EntryType
extends Object {
// empty
}
}
}
|
package afc.ant.modular;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.taskdefs.CallTarget;
import org.apache.tools.ant.taskdefs.Property;
import org.apache.tools.ant.taskdefs.Ant.Reference;
import org.apache.tools.ant.types.PropertySet;
public class CallTargetForModules extends Task
{
private ArrayList<ModuleElement> moduleElements;
private ModuleLoader moduleLoader;
// If defined then the correspondent Module object is set to this property for each module being processed.
private String moduleProperty;
private String target;
private boolean targetSet;
private final ArrayList<ParamElement> params = new ArrayList<ParamElement>();
private final ArrayList<Reference> references = new ArrayList<Reference>();
private final PropertySet propertySet = new PropertySet();
// Default values match antcall's defaults.
private boolean inheritAll = true;
private boolean inheritRefs = false;
private int threadCount = 1;
@Override
public void init() throws BuildException
{
moduleProperty = null;
targetSet = false;
moduleElements = new ArrayList<ModuleElement>();
}
@Override
public void execute() throws BuildException
{
if (!targetSet) {
throw new BuildException("Target is not set.");
}
if (moduleLoader == null) {
throw new BuildException("The module loader element is required.");
}
final ModuleRegistry registry = new ModuleRegistry(moduleLoader);
try {
final ArrayList<Module> modules = new ArrayList<Module>(moduleElements.size());
for (final ModuleElement moduleParam : moduleElements) {
if (moduleParam.path == null) {
throw new BuildException("Module path is undefined.");
}
modules.add(registry.resolveModule(moduleParam.path));
}
if (threadCount == 1) {
processModulesSerial(modules);
} else {
processModulesParallel(modules);
}
}
catch (ModuleNotLoadedException ex) {
throw new BuildException(ex.getMessage(), ex);
}
catch (CyclicDependenciesDetectedException ex) {
throw new BuildException(ex.getMessage(), ex);
}
}
private void callTarget(final Module module)
{
final CallTarget antcall = (CallTarget) getProject().createTask("antcall");
antcall.init();
if (moduleProperty != null) {
final Property moduleParam = antcall.createParam();
moduleParam.setName(moduleProperty);
moduleParam.setValue(module);
}
for (int i = 0, n = params.size(); i < n; ++i) {
final ParamElement param = params.get(i);
param.populate(antcall.createParam());
}
for (int i = 0, n = references.size(); i < n; ++i) {
antcall.addReference(references.get(i));
}
antcall.addPropertyset(propertySet);
antcall.setInheritAll(inheritAll);
antcall.setInheritRefs(inheritRefs);
antcall.setTarget(target);
antcall.perform();
}
private void processModulesSerial(final ArrayList<Module> modules) throws CyclicDependenciesDetectedException
{
final SerialDependencyResolver dependencyResolver = new SerialDependencyResolver();
dependencyResolver.init(modules);
Module module;
while ((module = dependencyResolver.getFreeModule()) != null) {
callTarget(module);
dependencyResolver.moduleProcessed(module);
}
}
private void processModulesParallel(final ArrayList<Module> modules) throws CyclicDependenciesDetectedException
{
final ParallelDependencyResolver dependencyResolver = new ParallelDependencyResolver();
dependencyResolver.init(modules);
final AtomicBoolean buildFailed = new AtomicBoolean(false);
final AtomicReference buildFailureException = new AtomicReference();
final Thread[] threads = new Thread[threadCount];
for (int i = 0; i < threadCount; ++i) {
final Thread t = new Thread()
{
@Override
public void run()
{
try {
while (!buildFailed.get()) {
if (Thread.interrupted()) {
return;
}
final Module module = dependencyResolver.getFreeModule();
if (module == null) {
return;
}
callTarget(module);
dependencyResolver.moduleProcessed(module);
}
}
catch (Throwable ex) {
buildFailed.set(true);
buildFailureException.set(ex);
}
}
};
threads[i] = t;
t.start();
}
try {
for (final Thread t : threads) {
t.join();
}
}
catch (InterruptedException ex) {
Thread.currentThread().interrupt();
throw new BuildException("The build thread was interrupted.", ex);
}
if (buildFailed.get()) {
final Throwable ex = (Throwable) buildFailureException.get();
if (ex instanceof BuildException) {
throw (BuildException) ex;
}
throw new BuildException(MessageFormat.format("Build failed. Cause: ''{0}''.", ex.getMessage()), ex);
}
}
public ModuleElement createModule()
{
final ModuleElement module = new ModuleElement();
moduleElements.add(module);
return module;
}
public void addConfigured(final ModuleLoader loader)
{
if (moduleLoader != null) {
throw new BuildException("Only a single module loader element is allowed.");
}
moduleLoader = loader;
}
public void setThreadCount(final int threadCount)
{
if (threadCount <= 0) {
throw new BuildException(MessageFormat.format(
"Invalid thread count: ''{0}''. It must be a positive value.",
String.valueOf(threadCount)));
}
this.threadCount = threadCount;
}
public void setModuleProperty(final String propertyName)
{
moduleProperty = propertyName;
}
public void setTarget(final String target)
{
this.target = target;
targetSet = true;
}
public void setInheritAll(final boolean inheritAll)
{
this.inheritAll = inheritAll;
}
public void setInheritRefs(final boolean inheritRefs)
{
this.inheritRefs = inheritRefs;
}
public ParamElement createParam()
{
final ParamElement param = new ParamElement();
params.add(param);
return param;
}
public void addReference(final Reference reference)
{
references.add(reference);
}
public void addPropertyset(final PropertySet propertySet)
{
this.propertySet.addPropertyset(propertySet);
}
// TODO support defining modules using regular expressions
public static class ModuleElement
{
private String path;
public void setPath(final String path)
{
if (path == null) {
throw new BuildException("Module path is undefined.");
}
this.path = path;
}
}
// TODO add all configuration that is supported by the Ant Property type.
public static class ParamElement
{
private String name;
private String value;
private boolean nameSet;
private boolean valueSet;
public void setName(final String name)
{
this.name = name;
nameSet = true;
}
public void setValue(final String value)
{
this.value = value;
valueSet = true;
}
public void populate(final Property property)
{
if (nameSet) {
property.setName(name);
}
if (valueSet) {
property.setValue(value);
}
}
}
}
|
package afc.ant.modular;
import java.io.File;
import java.net.URL;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.IdentityHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Location;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.ProjectComponent;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.taskdefs.CallTarget;
import org.apache.tools.ant.taskdefs.Property;
import org.apache.tools.ant.taskdefs.Ant;
import org.apache.tools.ant.types.Path;
import org.apache.tools.ant.types.PropertySet;
/**
* <p>An Ant task that executes a target for each module specified and all their dependee modules.
* An order in which the modules' targets are executed is such that for each module all
* the dependee modules are processed before this module is processed. An order in which
* independent modules are executed is undefined.</p>
*
* <p>To provide isolation, the target invoked to process the module is executed in its own
* Ant {@link Project project}. However, there is a way to pass data from the parent Ant project to
* the module-specific project. The attributes {@link #setInheritAll(boolean) inheritAll},
* {@link #setInheritRefs(boolean) inheritRefs}, and the nested elements {@link #createParam()
* <createParam>}, {@link #addPropertyset(PropertySet) <propertyset>},
* {@link #addReference(org.apache.tools.ant.taskdefs.Ant.Reference) <reference>} can be used
* for this. If the attribute {@link #setModuleProperty(String) moduleProperty} is defined
* then a {@link Module} instance that contains module metadata is passed to the module-specific
* project with the given property. In addition, all user-defined properties (i.e. the properties
* defined by the command line) are passed to each module-specific project. Note that there is no
* explicit way to pass data between module-specific Ant projects.</p>
*
* <p>Module metadata are loaded by a {@link ModuleLoader} specified by the nested element
* whose type is a descendant of {@code ModuleLoader}. One and only one such element must
* be specified.</p>
*
* <p>For the sake of performance, modules could be processed in parallel. That is, independent
* modules could be processed simultaneously, each within its own thread. There is no way to
* perform parallel processing of modules that are dependent, directly or indirectly, one upon
* another. The number of threads to be used is defined by the attribute
* {@link #setThreadCount(int) threadCount}.</p>
*
* <h3>Task input</h3>
* <h4>Attributes</h4>
* <table border="1">
* <thead>
* <tr><th>Attribute</th>
* <th>Required?</th>
* <th>Description</th>
* <th>Default value</th></tr>
* </thead>
* <tbody>
* <tr><td>{@link #setTarget(String) target}</td>
* <td>yes</td>
* <td>The name of the target to be invoked by this {@code <callTargetForModules>} for modules
* involved in the build process by default. The target is expected to be defined in
* the current Ant project. If at least one module uses this target and the target itself
* is undefined in the current Ant project then the build fails.</td>
* <td>N/A</td></tr>
* <tr><td>{@link #setModuleProperty(String) moduleProperty}</td>
* <td>no</td>
* <td>The name of the property that holds the {@link Module} object within
* the module-specific project. No {@code Module} is passed if <em>moduleProperty</em>
* is undefined.</td>
* <td>N/A</td></tr>
* <tr><td>{@link #setThreadCount(int) threadCount}</td>
* <td>no</td>
* <td>The number of threads to be used by this {@code <callTargetForModules>} task to build
* independent modules in parallel. If <em>1</em> is passed then modules are built
* sequentally. It must be a positive value.</td>
* <td>{@code 1}</td></tr>
* <tr><td>{@link #setInheritAll(boolean) inheritAll}</td>
* <td>no</td>
* <td>Indicates whether or not the properties of the current Ant project are to be passed
* to the module-specific Ant projects. If {@code true} is set then all the properties
* from the current project are passed to each module-specific Ant project. If
* {@code false} is set then only the user properties and the properties defined by
* the elements {@link #createParam() <param>} and
* {@link #addPropertyset(PropertySet) <propertyset>} are passed.</td>
* <td>{@code true}</td></tr>
* <tr><td>{@link #setInheritRefs(boolean) inheritRefs}</td>
* <td>no</td>
* <td>Indicates whether or not the references of the current Ant {@link Project project} are
* to be passed to the module-specific Ant projects. If {@code true} is set then all
* the references are passed to each module-specific Ant project. If {@code false} is set
* then the references are not passed.</td>
* <td>{@code false}</td></tr>
* </tbody>
* </table>
* <h4>Elements</h4>
* <h5>{@link #createModule() module}</h5>
* <p>The module this element refers to will be built by this {@code <callTargetForModules>} along
* with all modules it depends upon (directly or indirectly). At least one {@code <module>} element
* must be specified. Multiple nested elements are allowed.</p>
* <p>Refer to {@link ModuleElement} for the attribute/element description.</p>
*
* <h5>{@link #addConfigured(ModuleLoader) moduleLoaderElement}</h5>
* <p>Defines a {@link ModuleLoader} that is to be used by this task. One and only one module
* loader must be defined. The name of the nested element is defined by the name of the Ant type
* used to pass this instance of {@code ModuleLoader}.</p>
*
* <h5>{@link #createParam() param}</h5>
* <p>Represents a property set that is passed to the Ant project created for each module or any
* project created in that project regardless of what is set to {@link #setInheritAll(boolean)
* inheritAll}. This property set overrides the properties with the same name defined in
* the project it is passed to. However, it does not override the user-defined properties with
* the same name. Nor it overrides the property defined by the attribute
* {@link #setModuleProperty(String) moduleProperty}. It is an optional element. Multiple nested
* elements are allowed.</p>
* <p>Refer to {@link ParamElement} for the attribute/element description.</p>
*
* <h5>{@link #addPropertyset(PropertySet) propertyset}</h5>
* <p>Defines a set of Ant project properties that are to be passed to the module-specific Ant
* projects. Each of these properties overrides the property with the same name defined in
* a module-specific project. However, these properties are overridden by the user-defined
* properties and {@link #createParam() params}. It is an optional element. Multiple nested
* elements are allowed.</p>
* <p>Refer to the Ant task {@link PropertySet <propertyset>} for the attribute/element
* description.</p>
*
* <h5>{@link #addReference(org.apache.tools.ant.taskdefs.Ant.Reference) reference}</h5>
* <p>Defines a reference to be inherited by the module-specific Ant projects. If there is
* a reference with the ID requested defined in the module-specific Ant project then it is
* overridden by this reference. However, a reference with the ID requested defined within
* a target is not overridden. It is an optional element. Multiple nested elements are allowed.</p>
* <p>Refer to the Ant task {@link org.apache.tools.ant.taskdefs.Ant.Reference <reference>}
* for the attribute/element description.</p>
*
* @author Dźmitry Laŭčuk
*/
// TODO document usage example.
public class CallTargetForModules extends Task
{
private ArrayList<ModuleElement> moduleElements = new ArrayList<ModuleElement>();
private ModuleLoader moduleLoader;
// If defined then the correspondent Module object is set to this property for each module being processed.
private String moduleProperty;
private String target;
private final ArrayList<ParamElement> params = new ArrayList<ParamElement>();
private final ArrayList<Ant.Reference> references = new ArrayList<Ant.Reference>();
private final PropertySet propertySet = new PropertySet();
// Default values match antcall's defaults.
private boolean inheritAll = true;
private boolean inheritRefs = false;
// The number of threads used to build modules.
private int threadCount = 1;
/**
* <p>Executes this {@code <callTargetForModules>} task. See the
* {@link CallTargetForModules class description} for the details.</p>
*
* @throws BuildException if this task is configured incorrectly or
* if the build of some module involved fails.
*/
@Override
public void execute() throws BuildException
{
if (target == null) {
throw new BuildException("The attribute 'target' is undefined.");
}
if (moduleLoader == null) {
throw new BuildException("No module loader is defined.");
}
final int moduleCount = moduleElements.size();
if (moduleCount == 0) {
throw new BuildException("At least one <module> element is required.");
}
for (int i = 0; i < moduleCount; ++i) {
final ModuleElement moduleParam = moduleElements.get(i);
if (moduleParam.path == null) {
throw new BuildException("There is a <module> element with the attribute 'path' undefined.");
}
}
final ModuleRegistry registry = new ModuleRegistry(moduleLoader);
try {
final ArrayList<Module> modules = new ArrayList<Module>(moduleCount);
// These targets will be invoked for these modules despite of the default target name.
final IdentityHashMap<Module, String> overriddenTargets =
new IdentityHashMap<Module, String>(modules.size());
for (int i = 0, n = moduleCount; i < n; ++i) {
final ModuleElement moduleParam = moduleElements.get(i);
final Module module = registry.resolveModule(moduleParam.path);
modules.add(module);
/* Resolving the name of the target to be invoked for this module. If the choice
* if ambiguous (i.e. there are multiple <module> elements that define the same
* module whose target name configured is different) then a BuildException
* is thrown to terminate the build.
*/
String moduleTarget = moduleParam.target == null ? target : moduleParam.target;
final String oldTarget = overriddenTargets.put(module, moduleTarget);
if (oldTarget != null && !oldTarget.equals(moduleTarget)) {
throw new BuildException(MessageFormat.format(
"Ambiguous choice of the target to be invoked for the module ''{0}''. " +
"At least the targets ''{1}'' and ''{2}'' are configured.",
module.getPath(), oldTarget, moduleTarget));
}
}
/* Params that define the property with the name equal to the moduleProperty value
* (if the latter is set) must be removed so that moduleProperty overrides them
* in module-specific projects.
*/
deleteModulePropertyParams();
if (threadCount == 1) {
processModulesSerial(modules, overriddenTargets);
} else {
processModulesParallel(modules, overriddenTargets);
}
}
catch (ModuleNotLoadedException ex) {
throw new BuildException(ex.getMessage(), ex);
}
catch (CyclicDependenciesDetectedException ex) {
throw new BuildException(ex.getMessage(), ex);
}
}
private void callTarget(final Module module, final String target)
{
final CallTarget antcall = (CallTarget) getProject().createTask("antcall");
antcall.init();
/* moduleProperty is expected to override properties with the same name
* defined in params. That's why it goes first.
*/
if (moduleProperty != null) {
final Property moduleParam = antcall.createParam();
moduleParam.setName(moduleProperty);
moduleParam.setValue(module);
}
for (int i = 0, n = params.size(); i < n; ++i) {
final ParamElement param = params.get(i);
param.populate(antcall.createParam());
}
for (int i = 0, n = references.size(); i < n; ++i) {
antcall.addReference(references.get(i));
}
antcall.addPropertyset(propertySet);
antcall.setInheritAll(inheritAll);
antcall.setInheritRefs(inheritRefs);
antcall.setTarget(target);
try {
antcall.perform();
}
catch (RuntimeException ex) {
throw buildExceptionForModule(ex, module);
}
}
private BuildException buildExceptionForModule(final Throwable cause, final Module module)
{
final BuildException ex = new BuildException(MessageFormat.format(
"Module ''{0}'': {1}", module.getPath(), cause.getMessage()), cause);
// Gathering all information available from the original build exception.
if (cause instanceof BuildException) {
/* The thread that generated this exception is either the current thread or
a dead thread so synchronisation is not needed to read location. */
final Location location = ((BuildException) cause).getLocation();
ex.setLocation(location == null ? Location.UNKNOWN_LOCATION : location);
ex.setStackTrace(cause.getStackTrace());
}
return ex;
}
// Removes all params which define a property with the name equal to what is set to moduleProperty.
private void deleteModulePropertyParams()
{
if (moduleProperty == null) {
return;
}
for (int i = params.size() - 1; i >= 0; --i) {
final String paramName = params.get(i).name;
if (paramName != null && moduleProperty.equals(paramName)) {
params.remove(i);
}
}
}
private void processModulesSerial(final ArrayList<Module> modules,
final IdentityHashMap<Module, String> overriddenTargets) throws CyclicDependenciesDetectedException
{
final SerialDependencyResolver dependencyResolver = new SerialDependencyResolver();
dependencyResolver.init(modules);
Module module;
while ((module = dependencyResolver.getFreeModule()) != null) {
String target = overriddenTargets.get(module);
if (target == null) {
target = this.target;
}
callTarget(module, target);
dependencyResolver.moduleProcessed(module);
}
}
private void processModulesParallel(final ArrayList<Module> modules,
final IdentityHashMap<Module, String> overriddenTargets) throws CyclicDependenciesDetectedException
{
final ParallelDependencyResolver dependencyResolver = new ParallelDependencyResolver();
dependencyResolver.init(modules);
final AtomicBoolean buildFailed = new AtomicBoolean(false);
final AtomicReference<Throwable> buildFailureException = new AtomicReference<Throwable>();
/* A stateless worker to process modules using ParallelDependencyResolver.
* This instance can be used by multiple threads simultaneously.
*
* It does not throw an exception outside run() and preserves the
* interrupted status of the thread it is executed in.
*/
final Runnable parallelBuildWorker = new Runnable()
{
public void run()
{
try {
do {
final Module module = dependencyResolver.getFreeModule();
if (module == null) {
/* Either all modules are processed or the build has failed and
* the resolver was aborted. Finishing execution.
*/
return;
}
String target = overriddenTargets.get(module);
if (target == null) {
target = CallTargetForModules.this.target;
}
/* Do not call dependencyResolver#moduleProcessed in case of exception!
* This could make the modules that depend upon this module
* (whose processing has failed!) free for acquisition, despite of
* their dependee module did not succeed.
*
* Instead, dependencyResolver#abort() is called.
*/
callTarget(module, target);
// Reporting this module as processed if no error is encountered.
dependencyResolver.moduleProcessed(module);
} while (!Thread.currentThread().isInterrupted());
}
catch (Throwable ex) {
buildFailed.set(true);
buildFailureException.set(ex);
/* Ensure that other threads will stop module processing right after
their current module is processed. */
dependencyResolver.abort();
}
}
};
// The current thread will be the last thread to process modules.
final int threadsToCreate = threadCount-1;
final Thread[] threads = new Thread[threadsToCreate];
for (int i = 0; i < threadsToCreate; ++i) {
final Thread t = new Thread(parallelBuildWorker);
threads[i] = t;
t.start();
}
try {
// The current thread is one of the threads that process the modules.
parallelBuildWorker.run();
}
finally {
/* Waiting for all worker threads to finish even if the build fails on
* a module that was being processed by this thread. This will allow the
* 'build failed' message to be the last one.
*/
joinThreads(threads);
}
if (buildFailed.get()) {
/* buildFailureException could contain either RuntimeException or Error
because this is what could be thrown in thread#run(). */
final Throwable ex = buildFailureException.get();
if (ex instanceof RuntimeException) {
throw (RuntimeException) ex; // includes properly initialised BuildException
} else {
throw (Error) ex;
}
}
}
private static void joinThreads(final Thread[] threads)
{
/* parallelBuildWorker preserves the interrupted status of the current thread
* so an InterruptedException is thrown if this thread starts waiting
* for a helper thread to join. This leads to all helper threads interrupted
* so that the build finished rapidly and gracefully.
*/
try {
for (final Thread t : threads) {
t.join();
}
}
catch (InterruptedException ex) {
/* Interrupting all the activities so that the build finishes as quick as possible.
* This is fine if an already finished thread is interrupted.
*/
for (final Thread t : threads) {
t.interrupt();
}
Thread.currentThread().interrupt();
throw new BuildException("The build thread was interrupted.");
}
}
/**
* <p>Creates a new {@link ModuleElement ModuleElement} container that backs the
* nested element {@code <module>} of this {@code <callTargetForModules>} task.
* The module it refers to will be built by this {@code <callTargetForModules>} along
* with all modules it depends upon (directly or indirectly).</p>
*
* <p>At least one {@code <module>} element must be specified. Otherwise the build
* process fails.</p>
*
* @return the {@code ModuleElement} created. It is never {@code null}.
*
* @see #setTarget(String)
*/
public ModuleElement createModule()
{
final ModuleElement module = new ModuleElement();
moduleElements.add(module);
return module;
}
/**
* <p>Sets a {@link ModuleLoader} that is to be used by this {@code <callTargetForModules>}
* task. One and only one module loader must be defined for a {@code <callTargetForModules>}
* task. The name of the nested element is defined by the name of the Ant type used to pass
* this instance of {@code ModuleLoader}.</p>
*
* @param moduleLoader the {@code ModuleLoader} instance to be used by this
* {@code <callTargetForModules>} task. {@code null} value is not allowed.
*
* @throws BuildException if more than one {@code ModuleLoader} is defined for this
* {@code <callTargetForModules>} task.
* @throws NullPointerException if <em>moduleLoader</em> is {@code null}.
*/
public void addConfigured(final ModuleLoader moduleLoader)
{
if (moduleLoader == null) {
throw new NullPointerException("moduleLoader");
}
if (this.moduleLoader != null) {
throw new BuildException("Only a single module loader element is allowed.");
}
this.moduleLoader = moduleLoader;
}
/**
* <p>Sets the number of threads to be used by this {@code <callTargetForModules>}
* task to build independent modules in parallel. If <em>1</em> is passed then
* modules are built sequentally. By default, the number of threads used is
* <em>1</em>.</p>
*
* <p>This setter is accessible via the attribute {@code threadCount} of this
* {@code <callTargetForModules>} task.</p>
*
* @param threadCount the number of threads to be set. It must be a positive value.
*
* @throws BuildException if <em>threadCount</em> is non-positive.
*
* @see SerialDependencyResolver
* @see ParallelDependencyResolver
*/
public void setThreadCount(final int threadCount)
{
if (threadCount <= 0) {
throw new BuildException(MessageFormat.format(
"Invalid thread count: ''{0}''. It must be a positive value.",
String.valueOf(threadCount)));
}
this.threadCount = threadCount;
}
/**
* <p>Sets the name of the Ant property in a module-specific project that is assigned
* with the {@link Module} instance that is associated with this module. If it is not
* set then the {@code Module} is not passed to that project. This property value overrides
* the property with the same name passed with {@link #createParam() <param>} elements.
* If the property with the same name is defined in the caller project or in the module
* project then it is overridden regardless of what is set to the
* {@link #setInheritAll(boolean) inheritAll} attribute. However, the user-defined property
* with the same name is not overridden.</p>
*
* <p>It is used to extract module metadata in module-specific Ant projects. In addition,
* it could be used to pass information between module-specific projects via module
* attributes (which is possible if two modules are linked one to the other).</p>
*
* @param propertyName the name of the property to set {@code Module} instances to.
* An empty string is considered a defined property.
*
* @see Module
* @see GetModuleAttribute
* @see GetModulePath
* @see GetModuleClasspath
*/
public void setModuleProperty(final String propertyName)
{
moduleProperty = propertyName;
}
/**
* <p>Sets the name of the target to be invoked by this {@code <callTargetForModules>}
* for modules involved in the build process by default. The target is expected to be
* defined in the current Ant project. If at least one module uses this target and the
* target itself is undefined in the current Ant project then the build fails.</p>
*
* <p>A non-default target could be defined for a module by means of the attribute
* {@link ModuleElement#setTarget(String) target} of the nested element
* {@link #createModule() <module>}. </p>
*
* <p>The attribute {@code target} is required. It must be defined even if all modules
* involved have custom targets.</p>
*
* @param target the name of the target to invoke for modules by default.
*/
public void setTarget(final String target)
{
this.target = target;
}
/**
* <p>Sets the flag whether or not the properties of the current Ant {@link Project project}
* are to be passed to the Ant projects created to process {@link Module modules}.
* If {@code true} is set then all the properties from the current project are passed to
* each module-specific Ant project. If {@code false} is set then only the user properties
* (i.e. the properties defined in the command line) and the properties defined by the elements
* {@link #createParam() <param>} and {@link #addPropertyset(PropertySet) <propertyset>}
* are passed. {@code true} is the default value.</p>
*
* <p>In either case the properties defined within the module-specific project are overridden
* by the correspondent properties passed from the current project.</p>
*
* @param inheritAll the flag value to be set.
*/
public void setInheritAll(final boolean inheritAll)
{
this.inheritAll = inheritAll;
}
/**
* <p>Sets the flag whether or not the references of the current Ant {@link Project project}
* are to be passed to the Ant projects created to process {@link Module modules}. If
* {@code true} is set then all the references are passed to each module-specific Ant project.
* If {@code false} is set then the references are not passed. {@code false} is the default
* value.</p>
*
* <p>The references defined in the module-specific Ant project are not overridden by
* the current project's references even if <em>inheritRefs</em> is set to {@code true}.
* Use the {@link #addReference(Ant.Reference) <reference>} nested element for this.</p>
*
* @param inheritRefs the flag value to be set.
*/
public void setInheritRefs(final boolean inheritRefs)
{
this.inheritRefs = inheritRefs;
}
/**
* <p>Creates a new {@link ParamElement ParamElement} container that backs the nested
* element {@code <param>} of this {@code <callTargetForModules>} task. Multiple
* nested {@code <param>} elements are allowed.</p>
*
* <p>This element represents a property set that is passed to the Ant project
* created for each module or any project created in that project regardless of what
* is set to {@link #setInheritAll(boolean) inheritAll}. This property set overrides the
* properties with the same name defined in the project it is passed to. However, it does
* not override the user-defined properties with the same name. Nor it overrides the
* property defined by the attribute {@link #setModuleProperty(String) moduleProperty}.</p>
*
* <p>This allows you to parameterise targets that are invoked for modules.</p>
*
* @return the {@code ParamElement} created. It is never {@code null}.
*/
public ParamElement createParam()
{
final ParamElement param = new ParamElement();
param.setProject(getProject());
params.add(param);
return param;
}
/**
* <p>Adds a new {@link org.apache.tools.ant.taskdefs.Ant.Reference org.apache.tools.ant.taskdefs.Ant.Reference}
* container that backs the nested element {@code <reference>} of this
* {@code <callTargetForModules>} task. Multiple nested {@code <reference>} elements are
* allowed.</p>
*
* <p>This element defines a reference to be inherited by the Ant {@link Project projects}
* created to process {@link Module modules}. If there is a reference with the ID requested
* defined in the module-specific Ant project then it is overridden by this reference.
* However, a reference with the ID requested defined within a target is not overridden.</p>
*
* <p>Use the task attribute {@link #setInheritRefs(boolean) inheritRefs} set to {@code true}
* to pass all references defined within the Ant project of this {@code <callTargetForModules>}
* to the module-specific projects. Note that no references are overridden in this case except
* those that are specified by the {@code <reference>} elements.</p>
*
* @param reference the {@code <reference>} element to be added. It must be not {@code null}.
*/
public void addReference(final Ant.Reference reference)
{
references.add(reference);
}
/**
* <p>Adds a new {@link PropertySet org.apache.tools.ant.types.PropertySet}
* container that backs the nested element {@code <propertyset>} of this
* {@code <callTargetForModules>} task. Multiple nested {@code <propertyset>} elements are
* allowed.</p>
*
* <p>This element defines a set of Ant project properties that are to be passed to the Ant
* {@link Project projects} created to process {@link Module modules}. Each of these properties
* overrides the property with the same name defined in a module-specific project. However,
* these properties are overridden by the user-defined properties (i.e. those passed with
* the command line) and {@link #createParam() params}.</p>
*
* <p>Use the task attribute {@link #setInheritAll(boolean) inheritAll} set to {@code true}
* to pass all properties defined within the current Ant project to the module-specific
* projects.</p>
*
* @param propertySet the {@code <propertyset>} element to be added. It must be
* not {@code null}.
*/
public void addPropertyset(final PropertySet propertySet)
{
this.propertySet.addPropertyset(propertySet);
}
/**
* <p>Serves as the nested element {@code <module>} of the task
* {@link CallTargetForModules <callTargetForModules>} and defines the root modules
* to start build with. All modules this module depend upon (directly or indirectly)
* are included into the build process.</p>
*
* <h3>Attributes</h3>
* <table border="1">
* <thead>
* <tr><th>Attribute</th>
* <th>Required?</th>
* <th>Description</th></tr>
* </thead>
* <tbody>
* <tr><td>path</td>
* <td>yes</td>
* <td>The path of the module to be included. Non-normalised paths are allowed.</td></tr>
* <tr><td>target</td>
* <td>no</td>
* <td>Specifies the name of the target that must be invoked for this module by
* {@code <callTargetForModules>}. If this attribute is undefined then the
* target defined in {@code <callTargetForModules>} is used.
* This target name is not propagated to the dependee modules.</td></tr>
* </tbody>
* </table>
*/
public static class ModuleElement
{
private String path;
private String target;
/**
* <p>Sets the path of the module to be included into the build process.</p>
*
* @param path the module path. Non-normalised paths are allowed.
* {@code null} should not be set because this leads to build failure.
*/
public void setPath(final String path)
{
this.path = path;
}
/**
* <p>Sets the target to be invoked for the module defined by this
* {@code <module>} element. If the module-specific target is undefined then
* the target defined in {@code <callTargetForModules>} is used.</p>
*
* @param target the name of the target to be invoked.
*/
public void setTarget(final String target)
{
this.target = target;
}
}
/**
* <p>Serves as the nested element {@code <param>} of the task
* {@link CallTargetForModules <callTargetForModules>} and defines the parameters to be
* passed to the module-specific Ant projects. Refer to
* {@link CallTargetForModules#createParam()} for more details.</p>
*
* <h3>Attributes</h3>
* <p>The attributes and nested elements defined by {@code ParamElement} have the same
* semantics as the correspondent attributes and nested elements of the task
* {@link org.apache.tools.ant.taskdefs.Property <property>} have.</p>
*
* @see Property org.apache.tools.ant.taskdefs.Property
*/
public static class ParamElement extends ProjectComponent
{
private String name;
private String value;
private File location;
private File file;
private URL url;
private String resource;
private Path classpathAttribute;
private Path classpath;
private Ant.Reference classpathRef;
private String environment;
private Ant.Reference reference;
private String prefix;
// relative and basedir introduced in Ant 1.8.0 are not available because Ant 1.6+ is supported.
// prefixValues introduced in Ant 1.8.2 is not available because Ant 1.6+ is supported.
private boolean nameSet;
private boolean valueSet;
private boolean locationSet;
private boolean fileSet;
private boolean urlSet;
private boolean resourceSet;
private boolean classpathAttributeSet;
private boolean classpathRefSet;
private boolean environmentSet;
private boolean referenceSet;
private boolean prefixSet;
/**
* <p>Has the same semantics as
* {@link org.apache.tools.ant.taskdefs.Property#setName(String)} have.</p>
*
* @param name the value to be set.
*/
public void setName(final String name)
{
this.name = name;
nameSet = true;
}
/**
* <p>Has the same semantics as
* {@link org.apache.tools.ant.taskdefs.Property#setValue(String)} have.</p>
*
* @param value the value to be set.
*/
public void setValue(final String value)
{
this.value = value;
valueSet = true;
}
/**
* <p>Has the same semantics as
* {@link org.apache.tools.ant.taskdefs.Property#setLocation(File)} have.</p>
*
* @param location the value to be set.
*/
public void setLocation(final File location)
{
this.location = location;
locationSet = true;
}
/**
* <p>Has the same semantics as
* {@link org.apache.tools.ant.taskdefs.Property#setFile(File)} have.</p>
*
* @param file the value to be set.
*/
public void setFile(final File file)
{
this.file = file;
fileSet = true;
}
/**
* <p>Has the same semantics as
* {@link org.apache.tools.ant.taskdefs.Property#setUrl(URL)} have.</p>
*
* @param url the value to be set.
*/
public void setUrl(final URL url)
{
this.url = url;
urlSet = true;
}
/**
* <p>Has the same semantics as
* {@link org.apache.tools.ant.taskdefs.Property#setResource(String)} have.</p>
*
* @param resource the value to be set.
*/
public void setResource(final String resource)
{
this.resource = resource;
resourceSet = true;
}
/**
* <p>Has the same semantics as
* {@link org.apache.tools.ant.taskdefs.Property#setClasspath(Path)} have.</p>
*
* @param classpath the value to be set.
*/
public void setClasspath(final Path classpath)
{
classpathAttribute = classpath;
classpathAttributeSet = true;
}
/**
* <p>Has the same semantics as
* {@link org.apache.tools.ant.taskdefs.Property#createClasspath()} have.</p>
*
* @return the element created. It is never {@code null}.
*/
public Path createClasspath()
{
if (classpath == null) {
return classpath = new Path(getProject());
} else {
return classpath.createPath();
}
}
/**
* <p>Has the same semantics as
* {@link org.apache.tools.ant.taskdefs.Property#setClasspathRef(
* org.apache.tools.ant.types.Reference)} have.</p>
*
* @param reference the value to be set.
*/
public void setClasspathRef(final Ant.Reference reference)
{
classpathRef = reference;
classpathRefSet = true;
}
/**
* <p>Has the same semantics as
* {@link org.apache.tools.ant.taskdefs.Property#setEnvironment(String)} have.</p>
*
* @param environment the value to be set.
*/
public void setEnvironment(final String environment)
{
this.environment = environment;
environmentSet = true;
}
/**
* <p>Has the same semantics as
* {@link org.apache.tools.ant.taskdefs.Property#setRefid(
* org.apache.tools.ant.types.Reference)} have.</p>
*
* @param reference the value to be set.
*/
public void setRefid(final Ant.Reference reference)
{
this.reference = reference;
referenceSet = true;
}
/**
* <p>Has the same semantics as
* {@link org.apache.tools.ant.taskdefs.Property#setPrefix(String)} have.</p>
*
* @param prefix the value to be set.
*/
public void setPrefix(final String prefix)
{
this.prefix = prefix;
prefixSet = true;
}
private void populate(final Property property)
{
if (nameSet) {
property.setName(name);
}
if (valueSet) {
property.setValue(value);
}
if (locationSet) {
property.setLocation(location);
}
if (fileSet) {
property.setFile(file);
}
if (urlSet) {
property.setUrl(url);
}
if (resourceSet) {
property.setResource(resource);
}
if (classpathAttributeSet) {
property.setClasspath(classpathAttribute);
}
if (classpath != null) {
property.createClasspath().add(classpath);
}
if (classpathRefSet) {
property.setClasspathRef(classpathRef);
}
if (environmentSet) {
property.setEnvironment(environment);
}
if (referenceSet) {
property.setRefid(reference);
}
if (prefixSet) {
property.setPrefix(prefix);
}
}
}
}
|
// $Id: ImageUtil.java,v 1.30 2003/04/09 22:02:20 mdb Exp $
package com.threerings.media.image;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Graphics;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.DataBuffer;
import java.awt.image.IndexColorModel;
import java.awt.image.Raster;
import java.awt.image.WritableRaster;
import java.awt.geom.Area;
import java.util.Arrays;
import java.util.Iterator;
import com.samskivert.swing.Label;
import com.samskivert.util.ArrayUtil;
import com.samskivert.util.StringUtil;
import com.threerings.media.Log;
/**
* Image related utility functions.
*/
public class ImageUtil
{
/**
* Creates a new buffered image with the same sample model and color
* model as the source image but with the new width and height.
*/
public static BufferedImage createCompatibleImage (
BufferedImage source, int width, int height)
{
WritableRaster raster =
source.getRaster().createCompatibleWritableRaster(width, height);
return new BufferedImage(source.getColorModel(), raster, false, null);
}
/**
* Creates an image with the word "Error" written in it.
*/
public static BufferedImage createErrorImage (int width, int height)
{
BufferedImage img = new BufferedImage(
width, height, BufferedImage.TYPE_BYTE_INDEXED);
Graphics2D g = (Graphics2D)img.getGraphics();
g.setColor(Color.red);
Label l = new Label("Error");
l.layout(g);
Dimension d = l.getSize();
// fill that sucker with errors
for (int yy = 0; yy < height; yy += d.height) {
for (int xx = 0; xx < width; xx += (d.width+5)) {
l.render(g, xx, yy);
}
}
g.dispose();
return img;
}
/**
* Used to recolor images by shifting bands of color (in HSV color
* space) to a new hue. The source images must be 8-bit color mapped
* images, as the recoloring process works by analysing the color map
* and modifying it.
*/
public static BufferedImage recolorImage (
BufferedImage image, Color rootColor, float[] dists, float[] offsets)
{
return recolorImage(image, new Colorization[] {
new Colorization(-1, rootColor, dists, offsets) });
}
/**
* Recolors the supplied image as in {@link
* #recolorImage(BufferedImage,Color,float[],float[])} obtaining the
* recoloring parameters from the supplied {@link Colorization}
* instance.
*/
public static BufferedImage recolorImage (
BufferedImage image, Colorization cz)
{
return recolorImage(image, new Colorization[] { cz });
}
/**
* Recolors the supplied image using the supplied colorizations.
*/
public static BufferedImage recolorImage (
BufferedImage image, Colorization[] zations)
{
ColorModel cm = image.getColorModel();
if (!(cm instanceof IndexColorModel)) {
String errmsg = "Unable to recolor images with non-index color " +
"model [cm=" + cm.getClass() + "]";
throw new RuntimeException(errmsg);
}
// now process the image
IndexColorModel icm = (IndexColorModel)cm;
int size = icm.getMapSize();
int zcount = zations.length;
int[] rgbs = new int[size];
// fetch the color data
icm.getRGBs(rgbs);
// convert the colors to HSV
float[] hsv = new float[3];
int[] fhsv = new int[3];
int tpixel = -1;
for (int i = 0; i < size; i++) {
int value = rgbs[i];
// don't fiddle with alpha pixels
if ((value & 0xFF000000) == 0) {
tpixel = i;
continue;
}
// convert the color to HSV
int red = (value >> 16) & 0xFF;
int green = (value >> 8) & 0xFF;
int blue = (value >> 0) & 0xFF;
Color.RGBtoHSB(red, green, blue, hsv);
Colorization.toFixedHSV(hsv, fhsv);
// see if this color matches and of our colorizations and
// recolor it if it does
for (int z = 0; z < zcount; z++) {
Colorization cz = zations[z];
if (cz != null && cz.matches(hsv, fhsv)) {
// massage the HSV bands and update the RGBs array
rgbs[i] = cz.recolorColor(hsv);
break;
}
}
}
// create a new image with the adjusted color palette
IndexColorModel nicm = new IndexColorModel(
icm.getPixelSize(), size, rgbs, 0, icm.hasAlpha(),
icm.getTransparentPixel(), icm.getTransferType());
return new BufferedImage(nicm, image.getRaster(), false, null);
}
/**
* Paints multiple copies of the supplied image using the supplied
* graphics context such that the requested width is filled with the
* image.
*/
public static void tileImageAcross (Graphics g, Image image,
int x, int y, int width)
{
int iwidth = image.getWidth(null), iheight = image.getHeight(null);
int tcount = width/iwidth, extra = width % iwidth;
// draw the full copies of the image
for (int ii = 0; ii < tcount; ii++) {
g.drawImage(image, x, y, null);
x += iwidth;
}
// clip the final blit
if (extra > 0) {
Shape oclip = g.getClip();
g.clipRect(x, y, extra, iheight);
g.drawImage(image, x, y, null);
g.setClip(oclip);
}
}
/**
* Paints multiple copies of the supplied image using the supplied
* graphics context such that the requested height is filled with the
* image.
*/
public static void tileImageDown (Graphics g, Image image,
int x, int y, int height)
{
int iwidth = image.getWidth(null), iheight = image.getHeight(null);
int tcount = height/iheight, extra = height % iheight;
// draw the full copies of the image
for (int ii = 0; ii < tcount; ii++) {
g.drawImage(image, x, y, null);
y += iheight;
}
// clip the final blit
if (extra > 0) {
Shape oclip = g.getClip();
g.clipRect(x, y, iwidth, extra);
g.drawImage(image, x, y, null);
g.setClip(oclip);
}
}
// Not fully added because we're not using it anywhere, plus
// it's probably a little sketchy to create Area objects with all
// this pixely data.
// Also, the Area was getting zeroed out when it was translated. Something
// to look into someday if anyone wants to use this method.
// /**
// * Creates a mask that is opaque in the non-transparent areas of the
// * source image.
// */
// public static Area createImageMask (BufferedImage src)
// Raster srcdata = src.getData();
// int wid = src.getWidth(), hei = src.getHeight();
// Log.info("creating area of (" + wid + ", " + hei + ")");
// Area a = new Area(new Rectangle(wid, hei));
// Rectangle r = new Rectangle(1, 1);
// for (int yy=0; yy < hei; yy++) {
// for (int xx=0; xx < wid; xx++) {
// if (srcdata.getSample(xx, yy, 0) == 0) {
// r.setLocation(xx, yy);
// a.subtract(new Area(r));
// return a;
/**
* Creates and returns a new image consisting of the supplied image
* traced with the given color and thickness.
*/
public static BufferedImage createTracedImage (
ImageManager imgr, BufferedImage src, Color tcolor, int thickness)
{
return createTracedImage(imgr, src, tcolor, thickness, 1.0f, 1.0f);
}
/**
* Creates and returns a new image consisting of the supplied image
* traced with the given color, thickness and alpha transparency.
*/
public static BufferedImage createTracedImage (
ImageManager imgr, BufferedImage src, Color tcolor, int thickness,
float startAlpha, float endAlpha)
{
// create the destination image
int wid = src.getWidth(), hei = src.getHeight();
BufferedImage dest = imgr.createImage(
wid, hei, Transparency.TRANSLUCENT);
// prepare various bits of working data
int spixel = (tcolor.getRGB() & RGB_MASK);
int salpha = (int)(startAlpha * 255);
int tpixel = (spixel | (salpha << 24));
boolean[] traced = new boolean[wid * hei];
int stepAlpha = (thickness <= 1) ? 0 :
(int)(((startAlpha - endAlpha) * 255) / (thickness - 1));
// TODO: this could be made more efficient, e.g., if we made four
// passes through the image in a vertical scan, horizontal scan,
// and opposing diagonal scans, making sure each non-transparent
// pixel found during each scan is traced on both sides of the
// respective scan direction. for now, we just naively check all
// eight pixels surrounding each pixel in the image and fill the
// center pixel with the tracing color if it's transparent but has
// a non-transparent pixel around it.
for (int tt = 0; tt < thickness; tt++) {
if (tt > 0) {
// clear out the array of pixels traced this go-around
Arrays.fill(traced, false);
// use the destination image as our new source
src = dest;
// decrement the trace pixel alpha-level
salpha -= Math.max(0, stepAlpha);
tpixel = (spixel | (salpha << 24));
}
for (int yy = 0; yy < hei; yy++) {
for (int xx = 0; xx < wid; xx++) {
// get the pixel we're checking
int argb = src.getRGB(xx, yy);
if ((argb & TRANS_MASK) != 0) {
// copy any pixel that isn't transparent
dest.setRGB(xx, yy, argb);
} else if (bordersNonTransparentPixel(
src, wid, hei, traced, xx, yy)) {
dest.setRGB(xx, yy, tpixel);
// note that we traced this pixel this pass so
// that it doesn't impact other-pixel borderedness
traced[(yy*wid)+xx] = true;
}
}
}
}
return dest;
}
/**
* Returns whether the given pixel is bordered by any non-transparent
* pixel.
*/
protected static boolean bordersNonTransparentPixel (
BufferedImage data, int wid, int hei, boolean[] traced, int x, int y)
{
// check the three-pixel row above the pixel
if (y > 0) {
for (int rxx = x - 1; rxx <= x + 1; rxx++) {
if (rxx < 0 || rxx >= wid || traced[((y-1)*wid)+rxx]) {
continue;
}
if ((data.getRGB(rxx, y - 1) & TRANS_MASK) != 0) {
return true;
}
}
}
// check the pixel to the left
if (x > 0 && !traced[(y*wid)+(x-1)]) {
if ((data.getRGB(x - 1, y) & TRANS_MASK) != 0) {
return true;
}
}
// check the pixel to the right
if (x < wid - 1 && !traced[(y*wid)+(x+1)]) {
if ((data.getRGB(x + 1, y) & TRANS_MASK) != 0) {
return true;
}
}
// check the three-pixel row below the pixel
if (y < hei - 1) {
for (int rxx = x - 1; rxx <= x + 1; rxx++) {
if (rxx < 0 || rxx >= wid || traced[((y+1)*wid)+rxx]) {
continue;
}
if ((data.getRGB(rxx, y + 1) & TRANS_MASK) != 0) {
return true;
}
}
}
return false;
}
/**
* Create an image using the alpha channel from the first and the RGB
* values from the second.
*/
public static BufferedImage composeMaskedImage (
ImageManager imgr, BufferedImage mask, BufferedImage base)
{
int wid = base.getWidth();
int hei = base.getHeight();
Raster maskdata = mask.getData();
Raster basedata = base.getData();
// create a new image using the rasters if possible
if (maskdata.getNumBands() == 4 && basedata.getNumBands() >= 3) {
WritableRaster target =
basedata.createCompatibleWritableRaster(wid, hei);
// copy the alpha from the mask image
int[] adata = maskdata.getSamples(0, 0, wid, hei, 3, (int[]) null);
target.setSamples(0, 0, wid, hei, 3, adata);
// copy the RGB from the base image
for (int ii=0; ii < 3; ii++) {
int[] cdata = basedata.getSamples(
0, 0, wid, hei, ii, (int[]) null);
target.setSamples(0, 0, wid, hei, ii, cdata);
}
return new BufferedImage(mask.getColorModel(), target, true, null);
} else {
// otherwise composite them by rendering them with an alpha
// rule
BufferedImage target = imgr.createImage(
wid, hei, Transparency.TRANSLUCENT);
Graphics2D g2 = target.createGraphics();
try {
g2.drawImage(mask, 0, 0, null);
g2.setComposite(AlphaComposite.SrcIn);
g2.drawImage(base, 0, 0, null);
} finally {
g2.dispose();
}
return target;
}
}
/**
* Create a new image using the supplied shape as a mask from which to
* cut out pixels from the supplied image. Pixels inside the shape
* will be added to the final image, pixels outside the shape will be
* clear.
*/
public static BufferedImage composeMaskedImage (
ImageManager imgr, Shape mask, BufferedImage base)
{
int wid = base.getWidth();
int hei = base.getHeight();
// alternate method for composition:
// 1. create WriteableRaster with base data
// 2. test each pixel with mask.contains() and set the alpha
// channel to fully-alpha if false
// 3. create buffered image from raster
// (I didn't use this method because it depends on the colormodel
// of the source image, and was booching when the souce image was
// a cut-up from a tileset, and it seems like it would take
// longer than the method we are using.
// But it's something to consider)
// composite them by rendering them with an alpha rule
BufferedImage target = imgr.createImage(
wid, hei, Transparency.TRANSLUCENT);
Graphics2D g2 = target.createGraphics();
try {
g2.setColor(Color.BLACK); // whatever, really
g2.fill(mask);
g2.setComposite(AlphaComposite.SrcIn);
g2.drawImage(base, 0, 0, null);
} finally {
g2.dispose();
}
return target;
}
/**
* Returns true if the supplied image contains a non-transparent pixel
* at the specified coordinates, false otherwise.
*/
public static boolean hitTest (BufferedImage image, int x, int y)
{
// it's only a hit if the pixel is non-transparent
int argb = image.getRGB(x, y);
return (argb >> 24) != 0;
}
/**
* Computes the bounds of the smallest rectangle that contains all
* non-transparent pixels of this image. This isn't extremely
* efficient, so you shouldn't be doing this anywhere exciting.
*/
public static void computeTrimmedBounds (
BufferedImage image, Rectangle tbounds)
{
// this could be more efficient, but it's run as a batch process
// and doesn't really take that long anyway
int width = image.getWidth(), height = image.getHeight();
int firstrow = -1, lastrow = -1, minx = width, maxx = 0;
for (int yy = 0; yy < height; yy++) {
int firstidx = -1, lastidx = -1;
for (int xx = 0; xx < width; xx++) {
// if this pixel is transparent, do nothing
int argb = image.getRGB(xx, yy);
if ((argb >> 24) == 0) {
continue;
}
// otherwise, if we've not seen a non-transparent pixel,
// make a note that this is the first non-transparent
// pixel in the row
if (firstidx == -1) {
firstidx = xx;
}
// keep track of the last non-transparent pixel we saw
lastidx = xx;
}
// if we saw no pixels on this row, we can bail now
if (firstidx == -1) {
continue;
}
// update our min and maxx
minx = Math.min(firstidx, minx);
maxx = Math.max(lastidx, maxx);
// otherwise keep track of the first row on which we see
// pixels and the last row on which we see pixels
if (firstrow == -1) {
firstrow = yy;
}
lastrow = yy;
}
// fill in the dimensions
tbounds.x = minx;
tbounds.y = firstrow;
tbounds.width = maxx - minx + 1;
tbounds.height = lastrow - firstrow + 1;
}
/**
* Returns the estimated memory usage in bytes for the specified
* image.
*/
public static long getEstimatedMemoryUsage (BufferedImage image)
{
if (image != null) {
return getEstimatedMemoryUsage(image.getRaster());
} else {
return 0;
}
}
/**
* Returns the estimated memory usage in bytes for the specified
* raster.
*/
public static long getEstimatedMemoryUsage (Raster raster)
{
// we assume that the data buffer stores each element in a
// byte-rounded memory element; maybe the buffer is smarter about
// things than this, but we're better to err on the safe side
DataBuffer db = raster.getDataBuffer();
int bpe = (int)Math.ceil(
DataBuffer.getDataTypeSize(db.getDataType()) / 8f);
return bpe * db.getSize();
}
/**
* Returns the estimated memory usage in bytes for all buffered images
* in the supplied iterator.
*/
public static long getEstimatedMemoryUsage (Iterator iter)
{
long size = 0;
while (iter.hasNext()) {
BufferedImage image = (BufferedImage)iter.next();
size += getEstimatedMemoryUsage(image);
}
return size;
}
/**
* Obtains the default graphics configuration for this VM.
*/
protected static GraphicsConfiguration getDefGC ()
{
if (_gc == null) {
// obtain information on our graphics environment
GraphicsEnvironment env =
GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = env.getDefaultScreenDevice();
_gc = gd.getDefaultConfiguration();
}
return _gc;
}
/** The graphics configuration for the default screen device. */
protected static GraphicsConfiguration _gc;
/** Used when seeking fully transparent pixels for outlining. */
protected static final int TRANS_MASK = (0xFF << 24);
/** Used when outlining. */
protected static final int RGB_MASK = 0x00FFFFFF;
}
|
package org.openlca.ilcd.io;
import static org.junit.Assert.assertEquals;
import java.io.InputStream;
import java.util.function.Consumer;
import javax.xml.bind.JAXB;
import org.junit.Test;
import org.openlca.ilcd.commons.DataSetType;
import org.openlca.ilcd.commons.IDataSet;
import org.openlca.ilcd.contacts.Contact;
import org.openlca.ilcd.flowproperties.FlowProperty;
import org.openlca.ilcd.flows.Flow;
import org.openlca.ilcd.sources.Source;
import org.openlca.ilcd.units.UnitGroup;
public class IDataSetTest {
@Test
public void testSource() throws Exception {
with("sdk_sample_source.xml", Source.class, ds -> {
assertEquals("00000000-0000-0000-0000-000000000000", ds.getUUID());
assertEquals("00.00", ds.getVersion());
assertEquals(DataSetType.SOURCE, ds.getDataSetType());
assertEquals("http:
ds.getURI().trim());
});
}
@Test
public void testContact() throws Exception {
with("sdk_sample_contact.xml", Contact.class, ds -> {
assertEquals("00000000-0000-0000-0000-000000000000", ds.getUUID());
assertEquals("00.00", ds.getVersion());
assertEquals(DataSetType.CONTACT, ds.getDataSetType());
assertEquals("http:
ds.getURI().trim());
});
}
@Test
public void testUnitGroup() throws Exception {
with("sdk_sample_unitgroup.xml", UnitGroup.class, ds -> {
assertEquals("00000000-0000-0000-0000-000000000000", ds.getUUID());
assertEquals("00.00", ds.getVersion());
assertEquals(DataSetType.UNIT_GROUP, ds.getDataSetType());
assertEquals("http:
ds.getURI().trim());
});
}
@Test
public void testFlowProperty() throws Exception {
with("sdk_sample_flowproperty.xml", FlowProperty.class, ds -> {
assertEquals("00000000-0000-0000-0000-000000000000", ds.getUUID());
assertEquals("00.00", ds.getVersion());
assertEquals(DataSetType.FLOW_PROPERTY, ds.getDataSetType());
assertEquals("http:
ds.getURI().trim());
});
}
@Test
public void testFlow() throws Exception {
with("sdk_sample_flow.xml", Flow.class, ds -> {
assertEquals("00000000-0000-0000-0000-000000000000", ds.getUUID());
assertEquals("00.00", ds.getVersion());
assertEquals(DataSetType.FLOW, ds.getDataSetType());
assertEquals("http:
ds.getURI().trim());
});
}
@Test
public void testProcess() throws Exception {
with("sdk_sample_process.xml", org.openlca.ilcd.processes.Process.class, ds -> {
assertEquals("00000000-0000-0000-0000-000000000000", ds.getUUID());
assertEquals("00.00", ds.getVersion());
assertEquals(DataSetType.PROCESS, ds.getDataSetType());
assertEquals("http:
ds.getURI().trim());
});
}
private void with(String xml, Class<?> type, Consumer<IDataSet> fn)
throws Exception {
try (InputStream is = getClass().getResourceAsStream(xml)) {
Object o = JAXB.unmarshal(is, type);
IDataSet ds = (IDataSet) o;
fn.accept(ds);
}
}
}
|
package io.compgen.ngsutils.cli.vcf;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import htsjdk.samtools.util.CloseableIterator;
import io.compgen.cmdline.annotation.Command;
import io.compgen.cmdline.annotation.Exec;
import io.compgen.cmdline.annotation.Option;
import io.compgen.cmdline.annotation.UnnamedArg;
import io.compgen.cmdline.exceptions.CommandArgumentException;
import io.compgen.cmdline.impl.AbstractOutputCommand;
import io.compgen.common.IterUtils;
import io.compgen.common.StringUtils;
import io.compgen.common.TabWriter;
import io.compgen.common.TallyValues;
import io.compgen.common.progress.ProgressMessage;
import io.compgen.common.progress.ProgressStats;
import io.compgen.common.progress.ProgressUtils;
import io.compgen.ngsutils.NGSUtils;
import io.compgen.ngsutils.annotation.GenomeSpan;
import io.compgen.ngsutils.bam.support.ReadUtils;
import io.compgen.ngsutils.pileup.BAMPileup;
import io.compgen.ngsutils.pileup.PileupRecord;
import io.compgen.ngsutils.pileup.PileupRecord.PileupBaseCall;
import io.compgen.ngsutils.pileup.PileupRecord.PileupBaseCallOp;
import io.compgen.ngsutils.vcf.VCFAttributeException;
import io.compgen.ngsutils.vcf.VCFHeader;
import io.compgen.ngsutils.vcf.VCFReader;
import io.compgen.ngsutils.vcf.VCFRecord;
@Command(name="vcf-count", desc="For each variant in a VCF file, count the number of ref and alt alleles in a BAM file", category="vcf")
public class VCFCount extends AbstractOutputCommand {
private String refFilename=null;
private String vcfFilename=null;
private String bamFilename=null;
private String sampleName=null;
private int maxDepth = -1;
private int minMappingQual = 0;
private int minBaseQual = 13;
private boolean disableBAQ = true;
private boolean extendedBAQ = false;
private boolean onlyOutputPass = false;
private boolean outputVCFAF = false;
private boolean outputAF = false;
private int filterFlags = 0;
private int requiredFlags = 0;
private int maxBatchLen = -1;
private boolean hetOnly = false;
@Option(desc = "Only keep properly paired reads", name = "proper-pairs")
public void setProperPairs(boolean val) {
if (val) {
requiredFlags |= ReadUtils.PROPER_PAIR_FLAG;
filterFlags |= ReadUtils.MATE_UNMAPPED_FLAG;
}
}
@Option(desc = "Batch variants into blocks of size {val} for mpileup (limits mpileup calls)", name = "batchlen")
public void setBatchLen(int maxBatchLen) {
this.maxBatchLen = maxBatchLen;
}
@Option(desc = "Only count heterozygous variants (requires GT FORMAT field)", name = "het")
public void setHeterozygous(boolean hetOnly) {
this.hetOnly = hetOnly;
}
@Option(desc = "Filtering flags", name = "filter-flags", defaultValue = "3844")
public void setFilterFlags(int flag) {
filterFlags = flag;
}
@Option(desc = "Required flags", name = "required-flags", defaultValue = "0")
public void setRequiredFlags(int flag) {
requiredFlags = flag;
}
@Option(desc="Output variant allele frequency from the VCF file (requires AD FORMAT field)", name="vcf-af")
public void setVCFAF(boolean val) {
this.outputVCFAF = val;
}
@Option(desc="Output alternative allele frequency (from BAM file)", name="af")
public void setAF(boolean val) {
this.outputAF = val;
}
@Option(desc="BAQ re-calculation (default:false)", name="baq")
public void setDisableBAQ(boolean val) {
this.disableBAQ = !val;
}
@Option(desc="Perform extended BAQ re-calculation (default:false)", name="extended-baq")
public void setExtendedBAQ(boolean val) {
this.extendedBAQ = val;
}
@Option(desc="Minimum base quality (indels always returned regardless of base quality)", name="min-basequal", defaultValue="13")
public void setMinBaseQual(int minBaseQual) {
this.minBaseQual = minBaseQual;
}
@Option(desc="Minimum read mapping quality (MAPQ)", name="min-mapq", defaultValue="0")
public void setMinMapQual(int minMappingQual) {
this.minMappingQual = minMappingQual;
}
@Option(desc="Maximum depth", name="max-depth", defaultValue="0")
public void setMaxDepth(int maxDepth) {
this.maxDepth = maxDepth;
}
@Option(desc="Only output passing variants", name="passing")
public void setOnlyOutputPass(boolean onlyOutputPass) {
this.onlyOutputPass = onlyOutputPass;
}
@Option(desc="Sample to use for vcf-counts (if VCF file has more than one sample)", name="sample")
public void setSampleName(String sampleName) {
this.sampleName = sampleName;
}
@Option(desc="Reference FASTA file (optional, used to validate variant positions)", name="ref")
public void setRefFilename(String refFilename) {
this.refFilename = refFilename;
}
@UnnamedArg(name = "input.vcf input.bam", required=true)
public void setFilename(String[] filenames) throws CommandArgumentException {
if (filenames.length!=2) {
throw new CommandArgumentException("You must include a VCF file and a BAM file.");
}
vcfFilename = filenames[0];
bamFilename = filenames[1];
}
@Exec
public void exec() throws Exception {
VCFReader reader;
if (vcfFilename.equals("-")) {
reader = new VCFReader(System.in);
} else {
reader = new VCFReader(vcfFilename);
}
if (outputVCFAF && !reader.getHeader().getFormatIDs().contains("AD")) {
throw new CommandArgumentException("The VCF file must contain the \"AD\" format annotation to output allele frequencies from the VCF file.");
}
int sampleIdx = 0;
if (sampleName != null) {
sampleIdx = reader.getHeader().getSamplePosByName(sampleName);
}
TabWriter writer = new TabWriter();
writer.write_line("## program: " + NGSUtils.getVersion());
writer.write_line("## cmd: " + NGSUtils.getArgs());
writer.write_line("## vcf-input: " + vcfFilename);
writer.write_line("## bam-input: " + bamFilename);
BAMPileup pileup = new BAMPileup(bamFilename);
pileup.setFlagFilter(filterFlags);
pileup.setFlagRequired(requiredFlags);
pileup.setMinBaseQual(minBaseQual);
pileup.setMaxDepth(maxDepth);
pileup.setMinMappingQual(minMappingQual);
pileup.setDisableBAQ(disableBAQ);
pileup.setExtendedBAQ(extendedBAQ);
pileup.setNoGaps(true);
if (refFilename != null) {
pileup.setRefFilename(refFilename);
}
writer.write_line("## pileup-cmd: " + StringUtils.join(" ", pileup.getCommand()));
writer.write("chrom");
writer.write("pos");
writer.write("ref");
writer.write("alt");
if (outputVCFAF) {
writer.write("vcf_ref_count");
writer.write("vcf_alt_count");
}
writer.write("ref_count");
writer.write("alt_count");
if (outputAF) {
writer.write("alt_freq");
}
writer.eol();
long total = 0;
final long[] offset = new long[]{0,0}; // offset, curpos
for (String chr: reader.getHeader().getContigNames()) {
total += reader.getHeader().getContigLength(chr);
}
final List<VCFRecord> recordBlock = new ArrayList<VCFRecord>();
final VCFHeader header = reader.getHeader();
final long totalF = total;
for (VCFRecord record: IterUtils.wrap(ProgressUtils.getIterator(vcfFilename.equals("-") ? "variants <stdin>": vcfFilename, reader.iterator(), new ProgressStats(){
@Override
public long size() {
return totalF;
}
@Override
public long position() {
return offset[0] + offset[1];
}}, new ProgressMessage<VCFRecord>(){
String curChrom = "";
@Override
public String msg(VCFRecord current) {
if (!current.getChrom().equals(curChrom)) {
if (!curChrom.equals("")) {
offset[0] += header.getContigLength(curChrom);
}
curChrom = current.getChrom();
}
offset[1] = current.getPos();
return current.getChrom()+":"+current.getPos();
}}))) {
if (onlyOutputPass && record.isFiltered()) {
continue;
}
if (hetOnly) {
if (!record.getSampleAttributes().get(sampleIdx).contains("GT")) {
throw new CommandArgumentException("Missing GT field");
}
String val = record.getSampleAttributes().get(sampleIdx).get("GT").asString(null);
// if 0/0 or 1/1, etc -- skip
if (val.indexOf('/')>-1) {
String[] v2 = val.split("/");
if (v2.length == 2 && v2[0].equals(v2[1])) {
continue;
}
} else if (val.indexOf('|')>-1) {
String[] v2 = val.split("\\|");
if (v2.length == 2 && v2[0].equals(v2[1])) {
continue;
}
}
}
if (maxBatchLen > 0) {
if (recordBlock.size() > 0) {
if (!recordBlock.get(0).getChrom().equals(record.getChrom())) {
processVariants(recordBlock, pileup, writer, sampleIdx);
recordBlock.clear();
} else if (record.getPos() - recordBlock.get(0).getPos() > maxBatchLen) {
processVariants(recordBlock, pileup, writer, sampleIdx);
recordBlock.clear();
}
}
recordBlock.add(record);
} else {
processVariant(record, pileup, writer, sampleIdx);
}
// if (indel) {
// System.out.print("INDEL: " + record.getChrom()+":"+record.getPos()+" Tally counts: ");
// for (String t: tally.keySet()) {
// System.out.print(t+"="+tally.getCount(t)+" ");
// System.out.println();
}
if (recordBlock.size() > 0) {
processVariants(recordBlock, pileup, writer, sampleIdx);
}
reader.close();
writer.close();
}
private void processVariant(VCFRecord record, BAMPileup pileup, TabWriter writer, int sampleIdx) throws IOException {
int pos = record.getPos() - 1; // switch to 0-based
CloseableIterator<PileupRecord> it2 = pileup.pileup(new GenomeSpan(record.getChrom(), pos));
for (PileupRecord pileupRecord: IterUtils.wrap(it2)) {
if (pileupRecord.ref.equals(record.getChrom()) && pileupRecord.pos == pos) {
if (refFilename != null && !pileupRecord.refBase.equals(record.getRef().subSequence(0, 1))) {
throw new IOException("Reference bases don't match! "+record.getChrom()+":"+record.getPos());
}
processVariantRecord(record, pileupRecord, writer, sampleIdx);
}
}
it2.close();
}
private void processVariantRecord(VCFRecord record, PileupRecord pileupRecord, TabWriter writer, int sampleIdx) throws IOException {
// TODO: HANDLE multi-base references?
if (refFilename != null && !pileupRecord.refBase.equals(record.getRef().substring(0, 1))) {
throw new IOException("Reference bases don't match! "+record.getChrom()+":"+record.getPos());
}
TallyValues<String> tally = new TallyValues<String>();
for (PileupBaseCall call: pileupRecord.getSampleRecords(0).calls) {
if (call.op == PileupBaseCallOp.Match) {
tally.incr(call.call);
} else if (call.op == PileupBaseCallOp.Ins) {
// NOTE: Indels are always reported out by BAMPileup/samtools mpileup
// Ex: C->CA is a +1A in the pileup but C/CA in VCF
// chr8 109080640 C 4 ..-1A,, oJA<
tally.incr("ins"+record.getRef()+call.call);
// indel = true;
} else if (call.op == PileupBaseCallOp.Del) {
// Ex: CA->C is a -1A in the pileup but CA/C in VCF
// chr8 109080640 C 4 ..-1A,, oJA<
tally.incr("del"+call.call.length());
// indel = true;
}
}
// for each alt-allele...
for (int i=0; i< record.getAlt().size(); i++) {
writer.write(record.getChrom());
writer.write(record.getPos());
writer.write(record.getRef());
writer.write(record.getAlt().get(i));
if (outputVCFAF) {
try {
String ad = record.getSampleAttributes().get(sampleIdx).get("AD").asString(null);
String spl[] = ad.split(",");
writer.write(spl[0]);
writer.write(spl[i]);
} catch (VCFAttributeException e) {
throw new IOException(e);
}
}
long ref;
long alt;
if (record.getRef().length()>1) {
// is a del
// assumes a properly anchored variant call in VCF (ex: CA/C)
ref = tally.getCount(record.getAlt().get(i));
alt = tally.getCount("del"+(record.getRef().length()-1));
} else if (record.getAlt().get(i).length()>1) {
// is an insert
ref = tally.getCount(record.getRef());
alt = tally.getCount("ins"+record.getAlt().get(i));
} else {
// match
ref = tally.getCount(record.getRef());
alt = tally.getCount(record.getAlt().get(i));
}
writer.write(ref);
writer.write(alt);
if (outputAF) {
if (tally.getTotal() > 0) {
// need the total allele count here (if we have two non-ref alleles in het, then we can skew the AF unless we do this...)
// in those cases, the AF will not equal alt / (alt+ref); rather alt / (alt1+alt2)
writer.write(""+((double)alt) / tally.getTotal());
} else {
writer.write("");
}
}
writer.eol();
}
}
private void processVariants(List<VCFRecord> records, BAMPileup pileup, TabWriter writer, int sampleIdx) throws IOException {
// records must have the same chrom.
int start = records.get(0).getPos() - 1;
int end = records.get(records.size()-1).getPos(); // minus 1?
GenomeSpan span = new GenomeSpan(records.get(0).getChrom(), start, end);
CloseableIterator<PileupRecord> it2 = pileup.pileup(span);
VCFRecord curRecord = records.get(0);
int idx = 1;
for (PileupRecord pileupRecord: IterUtils.wrap(it2)) {
if (pileupRecord.ref.equals(curRecord.getChrom()) && pileupRecord.pos == curRecord.getPos()-1) {
processVariantRecord(curRecord, pileupRecord, writer, sampleIdx);
if (idx < records.size()) {
curRecord = records.get(idx++);
} else {
break;
}
}
}
it2.close();
}
}
|
package com.olmatix.service;
import android.Manifest;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.app.TaskStackBuilder;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.RingtoneManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.preference.PreferenceManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.NotificationManagerCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.NotificationCompat;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.androidadvance.topsnackbar.TSnackbar;
import com.olmatix.database.dbNode;
import com.olmatix.database.dbNodeRepo;
import com.olmatix.helper.PreferenceHelper;
import com.olmatix.helper.SnackbarWrapper;
import com.olmatix.lesjaw.olmatix.R;
import com.olmatix.model.DetailNodeModel;
import com.olmatix.model.DurationModel;
import com.olmatix.model.InstalledNodeModel;
import com.olmatix.ui.activity.MainActivity;
import com.olmatix.ui.activity.SplashActivity;
import com.olmatix.ui.fragment.DetailNode;
import com.olmatix.utils.Connection;
import com.olmatix.utils.OlmatixUtils;
import org.eclipse.paho.android.service.MqttAndroidClient;
import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttAsyncClient;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import static com.olmatix.lesjaw.olmatix.R.drawable;
import static com.olmatix.lesjaw.olmatix.R.string;
public class OlmatixService extends Service {
//public final static String MY_ACTION = "MY_ACTION";
public static dbNodeRepo mDbNodeRepo;
private static String TAG = OlmatixService.class.getSimpleName();
private static boolean hasWifi = false;
private static boolean hasMmobile = false;
private static ArrayList<InstalledNodeModel> data;
public volatile MqttAndroidClient mqttClient;
HashMap<String, String> messageReceive = new HashMap<>();
HashMap<String, String> message_topic = new HashMap<>();
CharSequence text, textNode, titleNode;
ArrayList<DetailNodeModel> data1;
ArrayList<InstalledNodeModel> data2;
String add_NodeID;
boolean flagSub = true;
boolean flagNode = false;
boolean flagConn = false;
boolean flagStart = false;
boolean flagOnForeground = true;
int notifyID = 0;
String topic, topic1;
private ConnectivityManager mConnMan;
private String deviceId;
private InstalledNodeModel installedNodeModel;
private DetailNodeModel detailNodeModel;
private DurationModel durationModel;
private String NodeID, Channel, mMessage;
private String mNodeID, mNiceName, mNiceNameN, NodeIDSensor, TopicID, mChange = "", connectionResult;
private ArrayList<String> notifications;
private static final int TWO_MINUTES = 1000 * 60 * 5;
public LocationManager locationManager;
public MyLocationListener listener;
public Location previousBestLocation = null;
private String Distance;
String adString = "";
String loc = null;
double lat;
double lng;
IntentFilter filter;
int numMessages = 0;
int count = 0;
boolean hasConnectivity = false;
boolean hasChanged = false;
SharedPreferences sharedPref;
Boolean mStatusServer, doCon, noNotif=true;
dbNode dbnode;
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
add_NodeID = intent.getStringExtra("NodeID");
String alarmService = intent.getStringExtra("Conn");
Log.d("DEBUG", "onReceive1: " + add_NodeID);
Log.d("DEBUG", "onReceive2: " + alarmService);
NetworkInfo nInfo = mConnMan.getActiveNetworkInfo();
if (nInfo != null) {
if (nInfo.getType() == ConnectivityManager.TYPE_WIFI) {
hasWifi = nInfo.isConnected();
} else if (nInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
hasMmobile = nInfo.isConnected();
}
}
hasConnectivity = hasWifi||hasMmobile;
if (alarmService==null){
if (!hasConnectivity) {
final SnackbarWrapper snackbarWrapper = SnackbarWrapper.make(getApplicationContext(),
"Internet connection avalaible",TSnackbar.LENGTH_LONG);
snackbarWrapper.setAction("Olmatix",
new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Action",
Toast.LENGTH_SHORT).show();
}
});
snackbarWrapper.show();
} else {
if (add_NodeID == null) {
final SnackbarWrapper snackbarWrapper = SnackbarWrapper.make(getApplicationContext(),
"Your device Offline",TSnackbar.LENGTH_LONG);
snackbarWrapper.setAction("Olmatix",
new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Action",
Toast.LENGTH_SHORT).show();
}
});
snackbarWrapper.show(); doCon = false;
sharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
mStatusServer = sharedPref.getBoolean("conStatus", false);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean("conStatus", false);
editor.apply();
doConnect();
}
}
}
if (alarmService != null) {
if (alarmService.equals("login")) {
doCon=false;
sharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
mStatusServer = sharedPref.getBoolean("conStatus", false);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean("conStatus", false);
editor.apply();
doConnect();
}
if (alarmService.equals("con")) {
doCon = false;
sharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
mStatusServer = sharedPref.getBoolean("conStatus", false);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean("conStatus", false);
editor.apply();
doConnect();
}
if (alarmService.equals("stop")) {
stopSelf();
}
}
if (add_NodeID != null) {
doAddNodeSub();
}
}
};
class OlmatixBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
NetworkInfo nInfo = mConnMan.getActiveNetworkInfo();
if (nInfo != null) {
if (nInfo.getType() == ConnectivityManager.TYPE_WIFI) {
hasChanged = true;
hasWifi = nInfo.isConnected();
} else if (nInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
hasChanged = true;
hasMmobile = nInfo.isConnected();
}
} else {
//Not Connected info
final SnackbarWrapper snackbarWrapper = SnackbarWrapper.make(getApplicationContext(),
"No Internet connection",TSnackbar.LENGTH_LONG);
snackbarWrapper.setAction("Olmatix",
new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Action",
Toast.LENGTH_SHORT).show();
}
});
snackbarWrapper.show();
text = "Disconnected";
flagConn = false;
doCon=false;
hasMmobile = false;
hasWifi = false;
sharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean("conStatus", false);
editor.apply();
sendMessage();
showNotification();
}
hasConnectivity = hasMmobile || hasWifi;
Log.d(TAG, "hasConn: " + hasConnectivity + " hasChange: " + hasChanged );
if (hasConnectivity && hasChanged) {
if (mqttClient != null) {
Log.d(TAG, "Pref Status con at receive: "+mStatusServer);
sharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
mStatusServer = sharedPref.getBoolean("conStatus", false);
if (!mStatusServer) {
Log.d(TAG, "doCon at receive: " + doCon);
if (!doCon) {
doConnect();
}
}
}
}
}
}
/*private void stopService (){
stopSelf();
}*/
private void doConnect() {
final SimpleDateFormat timeformat = new SimpleDateFormat("d MMM | hh:mm");
sharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String mServerURL = sharedPref.getString("server_address", "cloud.olmatix.com");
String mServerPort = sharedPref.getString("server_port", "1883");
String mUserName = sharedPref.getString("user_name", "olmatix1");
String mPassword = sharedPref.getString("password", "olmatix");
mStatusServer = sharedPref.getBoolean("conStatus", false);
Log.d(TAG, "login: " + mUserName + " : " + mPassword);
final Boolean mSwitch_conn = sharedPref.getBoolean("switch_conn", true);
Log.d(TAG, "doConnect status connection: "+mStatusServer);
doCon=true;
if (!mStatusServer) {
final MqttConnectOptions options = new MqttConnectOptions();
options.setUserName(mUserName);
options.setPassword(mPassword.toCharArray());
mqttClient = new MqttAndroidClient(getApplicationContext(), "tcp://" + mServerURL + ":" + mServerPort, deviceId);
if (mSwitch_conn) {
options.setCleanSession(false);
} else {
options.setCleanSession(true);
}
Log.d(TAG, "doConnect: " + count);
dbnode.setTopic("Connecting to server");
dbnode.setMessage("at "+timeformat.format(System.currentTimeMillis()));
mDbNodeRepo.insertDbMqtt(dbnode);
String topic = "status/" + deviceId + "/$online";
byte[] payload = "false".getBytes();
options.setWill(topic, payload, 1, true);
options.setKeepAliveInterval(300);
Connection.setClient(mqttClient);
text = "Connecting to server..";
showNotification();
Log.d(TAG, "doConnect: " + deviceId);
try {
IMqttToken token = mqttClient.connect(options);
token.setActionCallback(new IMqttActionListener() {
@Override
public void onSuccess(IMqttToken asyncActionToken) {
mqttClient.setCallback(new MqttEventCallback());
text = "Connected";
showNotification();
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean("conStatus", true);
editor.apply();
connectionResult = "AuthOK";
flagConn = true;
sendMessage();
if (!mSwitch_conn) {
Log.d(TAG, "Doing subscribe nodes");
doSubAll();
//new OlmatixService.load().execute();
}
dbnode.setTopic("Connected to server");
dbnode.setMessage("at "+timeformat.format(System.currentTimeMillis()));
mDbNodeRepo.insertDbMqtt(dbnode);
try {
String topic = "status/" + deviceId + "/$online";
String payload = "true";
byte[] encodedPayload = new byte[0];
try {
if (mqttClient!=null) {
encodedPayload = payload.getBytes("UTF-8");
MqttMessage message = new MqttMessage(encodedPayload);
message.setQos(1);
message.setRetained(true);
Connection.getClient().publish(topic, message);
}
} catch (UnsupportedEncodingException | MqttException e) {
e.printStackTrace();
}
Connection.getClient().subscribe("test", 0, getApplicationContext(), new IMqttActionListener() {
@Override
public void onSuccess(IMqttToken asyncActionToken) {
text = "Connected";
showNotification();
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean("conStatus", true);
editor.apply();
flagConn = true;
sendMessage();
}
@Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
//Toast.makeText(getApplicationContext(), R.string.sub_fail, Toast.LENGTH_SHORT).show();
Log.e("error", exception.toString());
}
});
} catch (MqttException e) {
e.printStackTrace();
text = "Failed to subscribe";
showNotification();
editor.putBoolean("conStatus", false);
editor.apply();
flagConn = false;
sendMessage();
dbnode.setTopic("Failed to subscribe");
dbnode.setMessage("at "+timeformat.format(System.currentTimeMillis()));
mDbNodeRepo.insertDbMqtt(dbnode);
}
}
@Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
text = "Not Connected";
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean("conStatus", false);
editor.apply();
String me = exception.toString();
if (me.equals("Not authorized to connect (5)")){
connectionResult = "NotAuth";
text = "Not Connected - Bad login";
}
flagConn = false;
sendMessage();
showNotification();
dbnode.setTopic((String) text);
dbnode.setMessage("at "+timeformat.format(System.currentTimeMillis()));
mDbNodeRepo.insertDbMqtt(dbnode);
}
});
} catch (MqttException e) {
e.printStackTrace();
}
}
sendMessage();
showNotification();
noNotif=true;
setFlagSub();
}
private void doDisconnect() {
Log.d(TAG, "doDisconnect, flagConn = " + flagConn);
if (flagConn) {
try {
mqttClient.disconnect();
flagConn = false;
Log.d(TAG, "doDisconnect done");
} catch (MqttException e) {
e.printStackTrace();
Log.d(TAG, "onReceive: " + String.valueOf(e.getMessage()));
}
}
}
private void setFlagSub() {
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
@Override
public void run() {
flagSub = true;
checkActivityForeground();
unSubIfnotForeground();
noNotif=false;
}
}, 10000);
}
@Override
public void onCreate() {
IntentFilter intent = new IntentFilter();
setClientID();
intent.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(new OlmatixBroadcastReceiver(), new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
mConnMan = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
data = new ArrayList<>();
data1 = new ArrayList<>();
data2 = new ArrayList<>();
notifications = new ArrayList<>();
dbnode = new dbNode();
Connection.setClient(mqttClient);
mDbNodeRepo = new dbNodeRepo(getApplicationContext());
installedNodeModel = new InstalledNodeModel();
detailNodeModel = new DetailNodeModel();
durationModel = new DurationModel();
// Display a notification about us starting. We put an icon in the status bar.
showNotification();
LocalBroadcastManager.getInstance(this).registerReceiver(
mMessageReceiver, new IntentFilter("addNode"));
notifications.clear();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
String mProvider = locationManager.getBestProvider(OlmatixUtils.getGeoCriteria(), true);
noNotif=true;
if (!flagStart) {
flagStart = true;
sharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
mStatusServer = sharedPref.getBoolean("conStatus", false);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean("conStatus", false);
editor.apply();
Log.d(TAG, "onStartCommand status connection: " + mStatusServer);
doConnect();
OlmatixAlarmReceiver alarmCheckConn = new OlmatixAlarmReceiver();
if (alarmCheckConn==null) {
alarmCheckConn.setAlarm(this);
Log.d("DEBUG", "Alarm set ");
}
}
sendMessage();
listener = new MyLocationListener();
if (ActivityCompat.checkSelfPermission(getApplication(), Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getApplicationContext(),
Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, OlmatixUtils.POSITION_UPDATE_INTERVAL,
OlmatixUtils.POSITION_UPDATE_MIN_DIST, listener);
}
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, OlmatixUtils.POSITION_UPDATE_INTERVAL,
OlmatixUtils.POSITION_UPDATE_MIN_DIST, listener);
Location mLocation = locationManager.getLastKnownLocation(mProvider);
if (mLocation == null) {
mLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
} else if (mLocation == null) {
mLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
} else {
mLocation = locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
}
if (mLocation!=null) {
lat = mLocation.getLatitude();
lng = mLocation.getLongitude();
locationDistance();
PreferenceHelper mPrefHelper = new PreferenceHelper(this.getApplicationContext());
double homeLat = mPrefHelper.getHomeLatitude();
double homelng = mPrefHelper.getHomeLongitude();
long thres = mPrefHelper.getHomeThresholdDistance();
Log.d("DEBUG", "proximity: " + homeLat + " | " + homelng + ":" + thres);
String proximityIntentAction = "com.olmatix.lesjaw.olmatix.ProximityAlert";
Intent i = new Intent(proximityIntentAction);
PendingIntent pi = PendingIntent.getBroadcast(getApplicationContext(), 0, i, 0);
locationManager.addProximityAlert(homeLat, homelng, thres, -1, pi);
filter = new IntentFilter(proximityIntentAction);
registerReceiver(new OlmatixReceiver(), filter);
} else {
}
}
return START_STICKY;
}
private void unSubIfnotForeground() {
Log.d("Unsubscribe", " uptime and signal");
if (!flagOnForeground||!noNotif) {
int countDB = mDbNodeRepo.getNodeList().size();
Log.d("DEBUG", "Count list Node: " + countDB);
data.addAll(mDbNodeRepo.getNodeList());
if (countDB != 0) {
for (int i = 0; i < countDB; i++) {
final String mNodeID1 = data.get(i).getNodesID();
//Log.d("DEBUG", "Count list: " + mNodeID1);
for (int a = 0; a < 2; a++) {
if (a == 0) {
topic = "devices/" + mNodeID1 + "/$signal";
}
if (a == 1) {
topic = "devices/" + mNodeID1 + "/$uptime";
}
try {
if (mqttClient!=null) {
Connection.getClient().unsubscribe(topic);
}
} catch (MqttException e) {
e.printStackTrace();
}
}
//Log.d("Unsubscribe", " device = " + mNodeID1);
}
}
data.clear();
}
}
private void showNotification() {
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, SplashActivity.class), 0);
// Set the info for the views that show in the notification panel.
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
mBuilder.setSmallIcon(R.drawable.olmatixsmall) // the status icon
.setTicker(text) // the status text
.setWhen(System.currentTimeMillis()) // the time stamp
.setContentTitle(getText(R.string.local_service_label)) // the label of the entry
.setContentText(text) // the contents of the entry
.setContentIntent(contentIntent) // The intent to send when the entry is clicked
.setOngoing(true)
.setPriority(Notification.FLAG_FOREGROUND_SERVICE)
//.setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 })
.build();
// Send the notification.
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
int NOTIFICATION = string.local_service_label;
notificationManager.notify(NOTIFICATION, mBuilder.build());
}
private void showNotificationNode() {
numMessages++;
SimpleDateFormat timeformat = new SimpleDateFormat("d MMM | hh:mm");
notifications.add(numMessages +". "+String.valueOf(titleNode) + " : "+String.valueOf(textNode)+ " at " +timeformat.format(System.currentTimeMillis()));
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
mBuilder.setContentTitle("New Olmatix status");
mBuilder.setContentText("You've received new status..");
mBuilder.setTicker("Olmatix status alert!");
mBuilder.setAutoCancel(true);
mBuilder.setWhen(System.currentTimeMillis());
mBuilder.setNumber(numMessages);
//mBuilder.setGroup(GROUP_KEY_NOTIF);
//mBuilder.setGroupSummary(true);
mBuilder.setSound(defaultSoundUri);
mBuilder.setSmallIcon(R.drawable.ic_lightbulb);
mBuilder.setPriority(Notification.PRIORITY_MAX);
NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
inboxStyle.setBigContentTitle("Olmatix status");
Collections.sort(notifications,Collections.reverseOrder());
for (int i=0; i < notifications.size(); i++) {
inboxStyle.addLine(notifications.get(i));
}
mBuilder.setStyle(inboxStyle);
Intent resultIntent = new Intent(this, MainActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(15,mBuilder.build());
}
private void setClientID() {
// Context mContext;
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo wInfo = wifiManager.getConnectionInfo();
deviceId = "OlmatixApp-" + wInfo.getMacAddress();
if (deviceId == null) {
deviceId = MqttAsyncClient.generateClientId();
}
}
private void sTopService() {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
stopSelf();
}
}, 20000);
}
private void sendMessage() {
Intent intent = new Intent("MQTTStatus");
intent.putExtra("MqttStatus", flagConn);
intent.putExtra("ConnectionStatus", connectionResult);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
private void sendMessageDetail() {
Intent intent = new Intent("MQTTStatusDetail");
intent.putExtra("NotifyChangeNode", mChange);
intent.putExtra("NotifyChangeDetail", mChange);
intent.putExtra("distance", Distance);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
@Override
public void onDestroy() {
// Cancel the persistent notification.
// Tell the user we stopped.
doDisconnect();
Log.d(TAG, "Service stop!! ");
messageReceive.clear();
message_topic.clear();
data.clear();
super.onDestroy();
}
@Override
public IBinder onBind(Intent intent) {
Log.i(TAG, "onBind called");
return null;
}
private void addNode() {
String[] outputDevices = TopicID.split("/");
NodeID = outputDevices[1];
String mNodeIdSplit = mNodeID;
mNodeIdSplit = mNodeIdSplit.substring(mNodeIdSplit.indexOf("$") + 1, mNodeIdSplit.length());
messageReceive.put(mNodeIdSplit, mMessage);
checkValidation();
}
private void checkValidation() {
if (flagNode) {
if (messageReceive.containsKey("online")) {
Log.d("CheckValid online", "Passed");
if (mMessage.equals("true")) {
Log.d("CheckValid online", " true Passed");
saveFirst();
} else {
final SnackbarWrapper snackbarWrapper = SnackbarWrapper.make(getApplicationContext(),
"Your device Offline",TSnackbar.LENGTH_LONG);
snackbarWrapper.setAction("Olmatix",
new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Action",
Toast.LENGTH_SHORT).show();
}
});
snackbarWrapper.show();
}
}
flagNode = false;
} else {
saveDatabase();
}
}
private void saveFirst() {
if (mDbNodeRepo.getNodeList().isEmpty()) {
installedNodeModel.setNodesID(NodeID);
installedNodeModel.setNodes(messageReceive.get("online"));
Calendar now = Calendar.getInstance();
now.setTime(new Date());
now.getTimeInMillis();
installedNodeModel.setAdding(now.getTimeInMillis());
mDbNodeRepo.insertDb(installedNodeModel);
final SnackbarWrapper snackbarWrapper = SnackbarWrapper.make(getApplicationContext(),
"Add "+NodeID +" success",TSnackbar.LENGTH_LONG);
snackbarWrapper.setAction("Olmatix",
new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Action",
Toast.LENGTH_SHORT).show();
}
});
snackbarWrapper.show();
doSub();
} else {
installedNodeModel.setNodesID(NodeID);
if (mDbNodeRepo.hasObject(installedNodeModel)) {
final SnackbarWrapper snackbarWrapper = SnackbarWrapper.make(getApplicationContext(),
"Checking this Node ID : " + NodeID + ", its exist, we are updating Node status",TSnackbar.LENGTH_LONG);
snackbarWrapper.setAction("Olmatix",
new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Action",
Toast.LENGTH_SHORT).show();
}
});
snackbarWrapper.show();
saveDatabase();
} else {
installedNodeModel.setNodesID(NodeID);
installedNodeModel.setNodes(messageReceive.get("online"));
Calendar now = Calendar.getInstance();
now.setTime(new Date());
now.getTimeInMillis();
installedNodeModel.setAdding(now.getTimeInMillis());
mDbNodeRepo.insertDb(installedNodeModel);
final SnackbarWrapper snackbarWrapper = SnackbarWrapper.make(getApplicationContext(),
"Add "+NodeID +" success",TSnackbar.LENGTH_LONG);
snackbarWrapper.setAction("Olmatix",
new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Action",
Toast.LENGTH_SHORT).show();
}
});
snackbarWrapper.show();
doSub();
}
}
}
private void doSub() {
for (int a = 0; a < 4; a++) {
if (a == 0) {
topic = "devices/" + NodeID + "/$fwname";
}
if (a == 1) {
topic = "devices/" + NodeID + "/$signal";
}
if (a == 2) {
topic = "devices/" + NodeID + "/$uptime";
}
if (a == 3) {
topic = "devices/" + NodeID + "/$localip";
}
int qos = 2;
try {
IMqttToken subToken = Connection.getClient().subscribe(topic, qos);
subToken.setActionCallback(new IMqttActionListener() {
@Override
public void onSuccess(IMqttToken asyncActionToken) {
Log.d("SubscribeNode", " device = " + mNodeID);
}
@Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
}
});
} catch (MqttException e) {
e.printStackTrace();
}
}
messageReceive.clear();
}
private void toastAndNotif() {
checkActivityForeground();
String state = "";
detailNodeModel.setNode_id(NodeID);
detailNodeModel.setChannel(Channel);
data1.addAll(mDbNodeRepo.getNodeDetail(NodeID, Channel));
int countDB = mDbNodeRepo.getNodeDetail(NodeID, Channel).size();
if (countDB != 0) {
for (int i = 0; i < countDB; i++) {
if (data1.get(i).getNice_name_d() != null) {
mNiceName = data1.get(i).getNice_name_d();
} else {
mNiceName = data1.get(i).getName();
}
state = data1.get(i).getStatus();
}
}
if (state.equals("true") || state.equals("ON")) {
state = "ON";
}
if (state.equals("false") || state.equals("OFF")) {
state = "OFF";
}
if (mNiceName != null) {
if (!state.equals("")) {
titleNode = mNiceName;
textNode = state;
//notifyID = notid;
notifyID = 0;
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
final Boolean mSwitch_NotifStatus = sharedPref.getBoolean("switch_notif", true);
if (mSwitch_NotifStatus) {
if (!flagOnForeground) {
if (!noNotif) {
showNotificationNode();
}
}
}
}
}
SimpleDateFormat timeformat = new SimpleDateFormat("d MMM | hh:mm");
dbnode.setTopic(mNiceName+" is "+textNode);
dbnode.setMessage("at "+timeformat.format(System.currentTimeMillis()));
mDbNodeRepo.insertDbMqtt(dbnode);
messageReceive.clear();
message_topic.clear();
data1.clear();
textNode="";
titleNode="";
}
protected void checkActivityForeground() {
//Log.d(TAG, "start checking for Activity in foreground");
Intent intent = new Intent();
intent.setAction(DetailNode.UE_ACTION);
sendOrderedBroadcast(intent, null, new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
int result = getResultCode();
if (result != Activity.RESULT_CANCELED) { // Activity caught it
//Log.d(TAG, "An activity caught the broadcast, result " + result);
activityInForeground();
return;
}
//Log.d(TAG, "No activity did catch the broadcast.");
noActivityInForeground();
}
}, null, Activity.RESULT_CANCELED, null, null);
}
protected void activityInForeground() {
// TODO something you want to happen when an Activity is in the foreground
flagOnForeground = true;
notifications.clear();
}
protected void noActivityInForeground() {
// TODO something you want to happen when no Activity is in the foreground
flagOnForeground = false;
//stopSelf(); // quit
}
private void updateSensorDoor() {
if (!mNodeID.contains("light")) {
detailNodeModel.setNode_id(NodeIDSensor);
detailNodeModel.setChannel("0");
detailNodeModel.setStatus_sensor(mMessage);
mDbNodeRepo.update_detailSensor(detailNodeModel);
mChange = "2";
sendMessageDetail();
}
}
private void updateSensorTheft() {
if (!mNodeID.contains("light")) {
detailNodeModel.setNode_id(NodeIDSensor);
detailNodeModel.setChannel("0");
detailNodeModel.setStatus_theft(mMessage);
mDbNodeRepo.update_detailSensor(detailNodeModel);
mChange = "2";
sendMessageDetail();
data1.addAll(mDbNodeRepo.getNodeDetail(NodeIDSensor, "0"));
int countDB = mDbNodeRepo.getNodeDetail(NodeIDSensor, "0").size();
if (countDB != 0) {
for (int i = 0; i < countDB; i++) {
if (data1.get(i).getNice_name_d() != null) {
mNiceName = data1.get(i).getNice_name_d();
} else {
mNiceName = data1.get(i).getName();
}
}
}
if (mMessage.equals("true")) {
titleNode = mNiceName;
textNode = "ALARM!!";
showNotificationNode();
}
data1.clear();
}
}
private void updateDetail() {
String[] outputDevices = TopicID.split("/");
NodeID = outputDevices[1];
Channel = outputDevices[3];
message_topic.put(Channel, mMessage);
saveDatabase_Detail();
toastAndNotif();
}
private void addNodeDetail() {
if (installedNodeModel.getFwName() != null) {
if (installedNodeModel.getFwName().equals("smartfitting")||installedNodeModel.getFwName().equals("smartadapter1ch")) {
detailNodeModel.setNode_id(NodeID);
detailNodeModel.setChannel("0");
if (mDbNodeRepo.hasDetailObject(detailNodeModel)) {
saveDatabase_Detail();
} else {
detailNodeModel.setNode_id(NodeID);
detailNodeModel.setChannel("0");
detailNodeModel.setStatus("false");
detailNodeModel.setNice_name_d(NodeID);
detailNodeModel.setSensor("light");
mDbNodeRepo.insertInstalledNode(detailNodeModel);
durationModel.setNodeId(NodeID);
durationModel.setChannel("0");
durationModel.setStatus("false");
durationModel.setTimeStampOn((long) 0);
durationModel.setDuration((long) 0);
mDbNodeRepo.insertDurationNode(durationModel);
topic1 = "devices/" + NodeID + "/light/0";
int qos = 2;
try {
IMqttToken subToken = Connection.getClient().subscribe(topic1, qos);
subToken.setActionCallback(new IMqttActionListener() {
@Override
public void onSuccess(IMqttToken asyncActionToken) {
Log.d("SubscribeButton", " device = " + NodeID);
}
@Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
}
});
} catch (MqttException e) {
e.printStackTrace();
}
}
} else if (installedNodeModel.getFwName().equals("smartadapter4ch")) {
detailNodeModel.setNode_id(NodeID);
detailNodeModel.setChannel("0");
if (mDbNodeRepo.hasDetailObject(detailNodeModel)) {
saveDatabase_Detail();
} else {
for (int i = 0; i < 4; i++) {
String a = String.valueOf(i);
detailNodeModel.setNode_id(NodeID);
detailNodeModel.setChannel(String.valueOf(i));
detailNodeModel.setStatus("false");
detailNodeModel.setNice_name_d(NodeID + " Ch " + String.valueOf(i + 1));
detailNodeModel.setSensor("light");
mDbNodeRepo.insertInstalledNode(detailNodeModel);
durationModel.setNodeId(NodeID);
durationModel.setChannel(String.valueOf(i));
durationModel.setStatus("false");
durationModel.setTimeStampOn((long) 0);
//durationModel.setTimeStampOff((long) 0);
durationModel.setDuration((long) 0);
mDbNodeRepo.insertDurationNode(durationModel);
topic1 = "devices/" + NodeID + "/light/" + i;
int qos = 2;
try {
IMqttToken subToken = Connection.getClient().subscribe(topic1, qos);
subToken.setActionCallback(new IMqttActionListener() {
@Override
public void onSuccess(IMqttToken asyncActionToken) {
Log.d("SubscribeButton", " device = " + NodeID);
}
@Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
}
});
} catch (MqttException e) {
e.printStackTrace();
}
}
}
} else if (installedNodeModel.getFwName().equals("smartsensordoor")) {
detailNodeModel.setNode_id(NodeID);
detailNodeModel.setChannel("0");
if (mDbNodeRepo.hasDetailObject(detailNodeModel)) {
} else {
detailNodeModel.setNode_id(NodeID);
detailNodeModel.setChannel("0");
detailNodeModel.setSensor("close");
detailNodeModel.setStatus("false");
detailNodeModel.setStatus_sensor("false");
detailNodeModel.setStatus_theft("false");
detailNodeModel.setNice_name_d(NodeID);
mDbNodeRepo.insertInstalledNode(detailNodeModel);
durationModel.setNodeId(NodeID);
durationModel.setChannel("0");
durationModel.setTimeStampOn((long) 0);
durationModel.setTimeStampOff((long) 0);
durationModel.setDuration((long) 0);
mDbNodeRepo.insertDurationNode(durationModel);
for (int a = 0; a < 3; a++) {
if (a == 0) {
topic1 = "devices/" + NodeID + "/light/0";
}
if (a == 1) {
topic1 = "devices/" + NodeID + "/door/close";
}
if (a == 2) {
topic1 = "devices/" + NodeID + "/door/theft";
}
int qos = 2;
try {
IMqttToken subToken = Connection.getClient().subscribe(topic1, qos);
subToken.setActionCallback(new IMqttActionListener() {
@Override
public void onSuccess(IMqttToken asyncActionToken) {
Log.d("SubscribeSensor", " device = " + mNodeID);
}
@Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
}
});
} catch (MqttException e) {
e.printStackTrace();
}
}
}
}
}
}
private void saveDatabase() {
/* new Thread(new Runnable() {
@Override
public void run() {
*/
installedNodeModel.setNodesID(NodeID);
installedNodeModel.setNodes(messageReceive.get("nodes"));
installedNodeModel.setName(messageReceive.get("name"));
installedNodeModel.setLocalip(messageReceive.get("localip"));
installedNodeModel.setFwName(messageReceive.get("fwname"));
installedNodeModel.setFwVersion(messageReceive.get("fwversion"));
if (installedNodeModel.getFwName() != null) {
addNodeDetail();
}
installedNodeModel.setOnline(messageReceive.get("online"));
if (messageReceive.containsKey("online")) {
checkActivityForeground();
installedNodeModel.setNodesID(NodeID);
data2.addAll(mDbNodeRepo.getNodeListbyNode(NodeID));
int countDB = mDbNodeRepo.getNodeListbyNode(NodeID).size();
Log.d(TAG, "saveDatabase: "+NodeID);
if (countDB != 0) {
for (int i = 0; i < countDB; i++) {
if (data2.get(i).getNice_name_n() != null) {
mNiceNameN = data2.get(i).getNice_name_n();
Log.d(TAG, "saveDatabase1: "+mNiceNameN);
} else {
mNiceNameN = data2.get(i).getFwName();
Log.d(TAG, "saveDatabase2: "+mNiceNameN);
}
int id = Integer.parseInt(NodeID.replaceAll("[\\D]", ""));
notifyID = id + 2;
if (mMessage.equals("true")) {
titleNode = mNiceNameN;
textNode = "ONLINE";
Log.d(TAG, "saveDatabase3: "+mNiceNameN);
} else {
titleNode = mNiceNameN;
textNode = "OFFLINE";
Log.d(TAG, "saveDatabase4: "+mNiceNameN);
}
if (!flagOnForeground) {
if (!noNotif) {
showNotificationNode();
}
}
}
}
SimpleDateFormat timeformat = new SimpleDateFormat("d MMM | hh:mm");
dbnode.setTopic(mNiceNameN+" is "+textNode);
dbnode.setMessage("at "+timeformat.format(System.currentTimeMillis()));
mDbNodeRepo.insertDbMqtt(dbnode);
data2.clear();
}
installedNodeModel.setSignal(messageReceive.get("signal"));
installedNodeModel.setUptime(messageReceive.get("uptime"));
if (messageReceive.containsKey("uptime")) {
if (mMessage != null) {
installedNodeModel.setOnline("true");
}
}
Calendar now = Calendar.getInstance();
now.setTime(new Date());
now.getTimeInMillis();
installedNodeModel.setAdding(now.getTimeInMillis());
mDbNodeRepo.update(installedNodeModel);
messageReceive.clear();
data.clear();
mChange = "2";
sendMessageDetail();
textNode="";
titleNode="";
/* }
}).start();*/
}
private void saveDatabase_Detail() {
/*new Thread(new Runnable() {
@Override
public void run() {*/
if (!mNodeID.contains("door")) {
detailNodeModel.setNode_id(NodeID);
detailNodeModel.setChannel(Channel);
if (mMessage.equals("true")) {
detailNodeModel.setStatus(mMessage);
saveOnTime();
} else if (mMessage.equals("false")) {
detailNodeModel.setStatus(mMessage);
saveOffTime();
}
mDbNodeRepo.update_detail(detailNodeModel);
mChange = "2";
sendMessageDetail();
data1.clear();
}
/* }
}).start();*/
}
private void saveOnTime() {
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
//Log.d(TAG, "run ON: "+Channel);
durationModel.setNodeId(NodeID);
durationModel.setChannel(Channel);
durationModel.setStatus(mMessage);
Calendar now = Calendar.getInstance();
now.setTime(new Date());
now.getTimeInMillis();
durationModel.setTimeStampOn(now.getTimeInMillis());
durationModel.setTimeStampOff(Long.valueOf("0"));
mDbNodeRepo.insertDurationNode(durationModel);
}
});
}
private void saveOffTime() {
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
//Log.d(TAG, "run OFF: "+Channel);
durationModel.setNodeId(NodeID);
durationModel.setChannel(Channel);
durationModel.setStatus(mMessage);
Calendar now = Calendar.getInstance();
now.setTime(new Date());
now.getTimeInMillis();
durationModel.setTimeStampOff(now.getTimeInMillis());
if(durationModel.getTimeStampOn()!=null) {
//Log.d(TAG, "run: " + Long.valueOf(durationModel.getTimeStampOn()));
durationModel.setDuration((now.getTimeInMillis() - durationModel.getTimeStampOn())/1000);
}
mDbNodeRepo.updateOff(durationModel);
}
});
}
private void doAddNodeSub() {
String topic = "devices/" + add_NodeID + "/$online";
int qos = 2;
try {
if (mqttClient!=null) {
IMqttToken subToken = Connection.getClient().subscribe(topic, qos);
subToken.setActionCallback(new IMqttActionListener() {
@Override
public void onSuccess(IMqttToken asyncActionToken) {
Log.d("Subscribe", " device = " + NodeID);
}
@Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
}
});
}
} catch (MqttException e) {
e.printStackTrace();
}
flagNode = true;
}
/*private void doUnsubscribe() {
String topic = "devices/" + NodeID + "/$online";
try {
Connection.getClient().unsubscribe(topic);
//Log.d("Unsubscribe", " device = " + NodeID);
} catch (MqttException e) {
e.printStackTrace();
}
}*/
private void doSubAll() {
int countDB = mDbNodeRepo.getNodeList().size();
Log.d("DEBUG", "Count list Node: " + countDB);
data.addAll(mDbNodeRepo.getNodeList());
if (countDB != 0) {
for (int i = 0; i < countDB; i++) {
final String mNodeID = data.get(i).getNodesID();
//Log.d("DEBUG", "Count list: " + mNodeID);
for (int a = 0; a < 5; a++) {
if (a == 0) {
topic = "devices/" + mNodeID + "/$online";
}
if (a == 1) {
topic = "devices/" + mNodeID + "/$fwname";
}
if (a == 2) {
topic = "devices/" + mNodeID + "/$signal";
}
if (a == 3) {
topic = "devices/" + mNodeID + "/$uptime";
}
if (a == 4) {
topic = "devices/" + mNodeID + "/$localip";
}
int qos = 2;
try {
if (mqttClient!=null) {
IMqttToken subToken = Connection.getClient().subscribe(topic, qos);
subToken.setActionCallback(new IMqttActionListener() {
@Override
public void onSuccess(IMqttToken asyncActionToken) {
//Log.d("SubscribeNode", " device = " + mNodeID);
}
@Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
}
});
}
} catch (MqttException e) {
e.printStackTrace();
}
}
}
data.clear();
doSubAllDetail();
}
}
/*class load extends AsyncTask<Void, Integer, String> {
protected void onPreExecute (){
}
protected String doInBackground(Void...arg0) {
mStatusServer = sharedPref.getBoolean("conStatus", false);
if (mStatusServer){
int countDB = mDbNodeRepo.getNodeList().size();
Log.d("DEBUG", "Count list Node: " + countDB);
data.addAll(mDbNodeRepo.getNodeList());
if (countDB != 0) {
for (int i = 0; i < countDB; i++) {
final String mNodeID = data.get(i).getNodesID();
//Log.d("DEBUG", "Count list: " + mNodeID);
for (int a = 0; a < 5; a++) {
if (a == 0) {
topic = "devices/" + mNodeID + "/$online";
}
if (a == 1) {
topic = "devices/" + mNodeID + "/$fwname";
}
if (a == 2) {
topic = "devices/" + mNodeID + "/$signal";
}
if (a == 3) {
topic = "devices/" + mNodeID + "/$uptime";
}
if (a == 4) {
topic = "devices/" + mNodeID + "/$localip";
}
int qos = 2;
try {
if (mqttClient != null) {
IMqttToken subToken = Connection.getClient().subscribe(topic, qos);
subToken.setActionCallback(new IMqttActionListener() {
@Override
public void onSuccess(IMqttToken asyncActionToken) {
//Log.d("SubscribeNode", " device = " + mNodeID);
}
@Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
}
});
}
} catch (MqttException e) {
e.printStackTrace();
}
}
}
int countDB1 = mDbNodeRepo.getNodeDetailList().size();
Log.d("DEBUG", "Count list Detail: " + countDB1);
data1.addAll(mDbNodeRepo.getNodeDetailList());
countDB1 = mDbNodeRepo.getNodeDetailList().size();
if (countDB1 != 0) {
for (int i = 0; i < countDB1; i++) {
final String mNodeID = data1.get(i).getNode_id();
final String mChannel = data1.get(i).getChannel();
topic1 = "devices/" + mNodeID + "/light/" + mChannel;
int qos = 2;
try {
IMqttToken subToken = Connection.getClient().subscribe(topic1, qos);
subToken.setActionCallback(new IMqttActionListener() {
@Override
public void onSuccess(IMqttToken asyncActionToken) {
//Log.d("SubscribeButton", " device = " + mNodeID);
}
@Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
}
});
} catch (MqttException e) {
e.printStackTrace();
}
}
for (int i = 0; i < countDB1; i++) {
final String mNodeID1 = data1.get(i).getNode_id();
final String mSensorT = data1.get(i).getSensor();
//Log.d("DEBUG", "Count list Sensor: " + mSensorT);
if (mSensorT != null && mSensorT.equals("close")) {
for (int a = 0; a < 2; a++) {
if (a == 0) {
topic1 = "devices/" + mNodeID1 + "/door/close";
}
if (a == 1) {
topic1 = "devices/" + mNodeID1 + "/door/theft";
}
int qos = 2;
try {
IMqttToken subToken = Connection.getClient().subscribe(topic1, qos);
subToken.setActionCallback(new IMqttActionListener() {
@Override
public void onSuccess(IMqttToken asyncActionToken) {
//Log.d("SubscribeSensor", " device = " + mNodeID);
}
@Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
}
});
} catch (MqttException e) {
e.printStackTrace();
}
}
}
}
}
}
}
return "You are at PostExecute";
}
protected void onProgressUpdate(Integer...a){
//Log.d(TAG + " onProgressUpdate", "You are in progress update ... " + a[0]);
}
protected void onPostExecute(String result) {
data.clear();
flagSub = false;
data1.clear();
}
}*/
private void doSubAllDetail() {
int countDB = mDbNodeRepo.getNodeDetailList().size();
Log.d("DEBUG", "Count list Detail: " + countDB);
data1.addAll(mDbNodeRepo.getNodeDetailList());
countDB = mDbNodeRepo.getNodeDetailList().size();
if (countDB != 0) {
for (int i = 0; i < countDB; i++) {
final String mNodeID = data1.get(i).getNode_id();
final String mChannel = data1.get(i).getChannel();
topic1 = "devices/" + mNodeID + "/light/" + mChannel;
int qos = 2;
try {
IMqttToken subToken = Connection.getClient().subscribe(topic1, qos);
subToken.setActionCallback(new IMqttActionListener() {
@Override
public void onSuccess(IMqttToken asyncActionToken) {
//Log.d("SubscribeButton", " device = " + mNodeID);
}
@Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
}
});
} catch (MqttException e) {
e.printStackTrace();
}
}
doAllsubDetailSensor();
}
data1.clear();
}
private void doAllsubDetailSensor() {
int countDB = mDbNodeRepo.getNodeDetailList().size();
Log.d("DEBUG", "Count list Sensor: " + countDB);
data1.addAll(mDbNodeRepo.getNodeDetailList());
countDB = mDbNodeRepo.getNodeDetailList().size();
if (countDB != 0) {
for (int i = 0; i < countDB; i++) {
final String mNodeID1 = data1.get(i).getNode_id();
final String mSensorT = data1.get(i).getSensor();
//Log.d("DEBUG", "Count list Sensor: " + mSensorT);
if (mSensorT != null && mSensorT.equals("close")) {
for (int a = 0; a < 2; a++) {
if (a == 0) {
topic1 = "devices/" + mNodeID1 + "/door/close";
}
if (a == 1) {
topic1 = "devices/" + mNodeID1 + "/door/theft";
}
int qos = 2;
try {
IMqttToken subToken = Connection.getClient().subscribe(topic1, qos);
subToken.setActionCallback(new IMqttActionListener() {
@Override
public void onSuccess(IMqttToken asyncActionToken) {
//Log.d("SubscribeSensor", " device = " + mNodeID);
}
@Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
}
});
} catch (MqttException e) {
e.printStackTrace();
}
}
}
}
flagSub = false;
data1.clear();
}
setFlagSub();
}
/*public class OlmatixBinder extends Binder {
public OlmatixService getService() {
return OlmatixService.this;
}
}*/
private class MqttEventCallback implements MqttCallback {
@Override
public void connectionLost(Throwable cause) {
Log.d(TAG, "connectionLost: "+cause);
sendMessage();
if (cause!=null) {
doDisconnect();
}
sharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
mStatusServer = sharedPref.getBoolean("conStatus", false);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean("conStatus", false);
editor.apply();
flagConn = false;
doCon=false;
sendMessage();
}
@Override
public void messageArrived(String topic, final MqttMessage message) throws Exception {
Log.d("Receive MQTTMessage", " = " + topic + " message = " + message.toString());
TopicID = topic;
mNodeID = topic;
mMessage = message.toString();
String[] outputDevices = TopicID.split("/");
NodeIDSensor = outputDevices[1];
if (mNodeID.contains("$")) {
addNode();
} else if (mNodeID.contains("close")) {
updateSensorDoor();
} else if (mNodeID.contains("theft")) {
updateSensorTheft();
} else {
updateDetail();
}
}
@Override
public void deliveryComplete(IMqttDeliveryToken token) {
//Log.d(TAG, "deliveryComplete: ");
}
}
public class MyLocationListener implements LocationListener {
public void onLocationChanged(final Location mLocation) {
Log.i("*****************", "Location changed");
if(isBetterLocation(mLocation, previousBestLocation)) {
lat = (mLocation.getLatitude());
lng = (mLocation.getLongitude());
locationDistance();
}
}
public void onProviderDisabled(String provider) {
/*final SnackbarWrapper snackbarWrapper = SnackbarWrapper.make(getApplicationContext(),
"Your GPS is disable.. We'll use Network for location",TSnackbar.LENGTH_LONG);
snackbarWrapper.setAction("Olmatix",
new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Action",
Toast.LENGTH_SHORT).show();
}
});
snackbarWrapper.show(); */
}
public void onProviderEnabled(String provider) {
/*final SnackbarWrapper snackbarWrapper = SnackbarWrapper.make(getApplicationContext(),
"GPS Enable.. Nice, it will be much more accurate",TSnackbar.LENGTH_LONG);
snackbarWrapper.setAction("Olmatix",
new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Action",
Toast.LENGTH_SHORT).show();
}
});
snackbarWrapper.show();*/
}
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
}
public void locationDistance(){
if (lat!=0 && lng!=0) {
new Thread(new Runnable() {
@Override
public void run() {
final Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
try {
List<Address> list;
list = geocoder.getFromLocation(lat, lng, 1);
if (list != null && list.size() > 0) {
Address address = list.get(0);
loc = address.getLocality();
if (address.getAddressLine(0) != null)
adString = ", " + address.getAddressLine(0);
}
} catch (final IOException e) {
new Thread(new Runnable() {
@Override
public void run() {
Log.e("DEBUG", "Geocoder ERROR", e);
}
}).start();
loc = OlmatixUtils.gpsDecimalFormat.format(lat) + " : " + OlmatixUtils.gpsDecimalFormat.format(lng);
}
final float[] res = new float[3];
final PreferenceHelper mPrefHelper = new PreferenceHelper(getApplicationContext());
Location.distanceBetween(lat, lng, mPrefHelper.getHomeLatitude(), mPrefHelper.getHomeLongitude(), res);
if (mPrefHelper.getHomeLatitude() != 0) {
String unit = " m";
if (res[0] > 2000) {// uuse km
unit = " km";
res[0] = res[0] / 1000;
}
Distance = loc +", it's "+ (int) res[0] + unit ;
Log.d("DEBUG", "Distance SERVICE 1: " + Distance);
titleNode = "Current Location is ";
textNode = Distance + " from home";
notifyID = 5;
sendMessageDetail();
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
final Boolean mSwitch_Notif = sharedPref.getBoolean("switch_loc", true);
if (mSwitch_Notif){
showNotificationLoc();
}
}
}
}).start();
}
}
protected boolean isBetterLocation(Location location, Location currentBestLocation) {
if (currentBestLocation == null) {
// A new location is always better than no location
return true;
}
// Check whether the new location fix is newer or older
long timeDelta = location.getTime() - currentBestLocation.getTime();
boolean isSignificantlyNewer = timeDelta > TWO_MINUTES;
boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES;
boolean isNewer = timeDelta > 0;
// If it's been more than two minutes since the current location, use the new location
// because the user has likely moved
if (isSignificantlyNewer) {
return true;
// If the new location is more than two minutes older, it must be worse
} else if (isSignificantlyOlder) {
return false;
}
// Check whether the new location fix is more or less accurate
int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation.getAccuracy());
boolean isLessAccurate = accuracyDelta > 0;
boolean isMoreAccurate = accuracyDelta < 0;
boolean isSignificantlyLessAccurate = accuracyDelta > 200;
// Check if the old and new location are from the same provider
boolean isFromSameProvider = isSameProvider(location.getProvider(),
currentBestLocation.getProvider());
// Determine location quality using a combination of timeliness and accuracy
if (isMoreAccurate) {
return true;
} else if (isNewer && !isLessAccurate) {
return true;
} else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) {
return true;
}
return false;
}
/** Checks whether two providers are the same */
private boolean isSameProvider(String provider1, String provider2) {
if (provider1 == null) {
return provider2 == null;
}
return provider1.equals(provider2);
}
private void showNotificationLoc(){
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class), 0);
// Set the info for the views that show in the notification panel.
Notification notification = new Notification.Builder(this)
.setSmallIcon(drawable.ic_location_red) // the status icon
.setTicker(textNode) // the status text
.setWhen(System.currentTimeMillis()) // the time stamp
.setContentTitle(getText(string.local_service_label_loc)) // the label of the entry
.setContentText(textNode) // the contents of the entry
.setContentIntent(contentIntent) // The intent to send when the entry is clicked
.setAutoCancel(true)
.build();
// Add as notification
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(5, notification);
}
}
|
package io.compgen.ngsutils.cli.vcf;
import java.util.Iterator;
import io.compgen.cmdline.annotation.Command;
import io.compgen.cmdline.annotation.Exec;
import io.compgen.cmdline.annotation.Option;
import io.compgen.cmdline.annotation.UnnamedArg;
import io.compgen.cmdline.exceptions.CommandArgumentException;
import io.compgen.cmdline.impl.AbstractOutputCommand;
import io.compgen.common.IterUtils;
import io.compgen.common.TabWriter;
import io.compgen.ngsutils.NGSUtils;
import io.compgen.ngsutils.vcf.VCFReader;
import io.compgen.ngsutils.vcf.VCFRecord;
@Command(name="vcf-tobed", desc="Export allele positions from a VCF file to BED format", category="vcf")
public class VCFToBED extends AbstractOutputCommand {
private String filename = "-";
private boolean onlyOutputPass = false;
private boolean includePos = false;
private int padding = 0;
private String altChrom = null;
private String altPos = null;
@Option(desc="Use an alternate INFO field for the chromosome (ex: SV). If missing, skip annotation.", name="alt-chrom")
public void setAltChrom(String key) throws CommandArgumentException {
this.altChrom = key;
}
@Option(desc="Use an alternate INFO field for the position (ex: SV). If missing, skip annotation.", name="alt-pos")
public void setAltPos(String key) throws CommandArgumentException {
this.altPos = key;
}
@Option(desc="Include the position as the name field (w/o padding)", name="include-pos")
public void setIncludePos(boolean includePos) {
this.includePos = includePos;
}
@Option(desc="Only output passing variants", name="passing")
public void setOnlyOutputPass(boolean onlyOutputPass) {
this.onlyOutputPass = onlyOutputPass;
}
@Option(desc="Add extra padding on either side", name="padding")
public void setPadding(int padding) {
this.padding = padding;
}
@UnnamedArg(name = "input.vcf", required=true)
public void setFilename(String filename) throws CommandArgumentException {
this.filename = filename;
}
@Exec
public void exec() throws Exception {
VCFReader reader;
if (filename.equals("-")) {
reader = new VCFReader(System.in);
} else {
reader = new VCFReader(filename);
}
TabWriter writer = new TabWriter();
writer.write_line("##ngsutilsj_vcf_tobedCommand="+NGSUtils.getArgs());
writer.write_line("##ngsutilsj_vcf_tobedVersion="+NGSUtils.getVersion());
Iterator<VCFRecord> it = reader.iterator();
for (VCFRecord rec: IterUtils.wrap(it)) {
if (onlyOutputPass && rec.isFiltered()) {
continue;
}
String chrom = rec.getChrom();
int pos = rec.getPos();
if (altChrom != null) {
chrom = rec.getInfo().get(altChrom).toString();
}
if (altPos != null) {
pos = rec.getInfo().get(altPos).asInt();
}
writer.write(chrom);
writer.write(((pos-1)-padding));
writer.write((pos+padding));
if (includePos) {
writer.write(rec.getChrom()+"_"+rec.getPos());
}
writer.eol();
}
reader.close();
writer.close();
}
}
|
package org.apache.commons.digester;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.InputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Reader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.EmptyStackException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.apache.commons.collections.ArrayStack;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.EntityResolver;
import org.xml.sax.ErrorHandler;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.InputSource;
import org.xml.sax.Locator;
import org.xml.sax.EntityResolver;
import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;
public class Digester extends DefaultHandler {
/**
* Construct a new Digester with default properties.
*/
public Digester() {
super();
}
/**
* Construct a new Digester, allowing a SAXParser to be passed in. This
* allows Digester to be used in environments which are unfriendly to
* JAXP1.1 (such as WebLogic 6.0). Thanks for the request to change go to
* James House (james@interobjective.com). This may help in places where
* you are able to load JAXP 1.1 classes yourself.
*/
public Digester(SAXParser parser) {
super();
this.parser = parser;
}
/**
* Construct a new Digester, allowing an XMLReader to be passed in. This
* allows Digester to be used in environments which are unfriendly to
* JAXP1.1 (such as WebLogic 6.0). Note that if you use this option you
* have to configure namespace and validation support yourself, as these
* properties only affect the SAXParser and emtpy constructor.
*/
public Digester(XMLReader reader) {
super();
this.reader = reader;
}
/**
* The body text of the current element.
*/
protected StringBuffer bodyText = new StringBuffer();
/**
* The stack of body text string buffers for surrounding elements.
*/
protected ArrayStack bodyTexts = new ArrayStack();
/**
* The class loader to use for instantiating application objects.
* If not specified, the context class loader, or the class loader
* used to load Digester itself, is used, based on the value of the
* <code>useContextClassLoader</code> variable.
*/
protected ClassLoader classLoader = null;
/**
* Has this Digester been configured yet.
*/
protected boolean configured = false;
/**
* The EntityResolver used by the SAX parser. By default it use this class
*/
protected EntityResolver entityResolver;
/**
* The URLs of entityValidator that have been registered, keyed by the public
* identifier that corresponds.
*/
protected HashMap entityValidator = new HashMap();
/**
* The application-supplied error handler that is notified when parsing
* warnings, errors, or fatal errors occur.
*/
protected ErrorHandler errorHandler = null;
/**
* The SAXParserFactory that is created the first time we need it.
*/
protected SAXParserFactory factory = null;
/**
* The JAXP 1.2 property required to set up the schema location.
*/
private static final String JAXP_SCHEMA_SOURCE =
"http://java.sun.com/xml/jaxp/properties/schemaSource";
/**
* The JAXP 1.2 property to set up the schemaLanguage used.
*/
protected String JAXP_SCHEMA_LANGUAGE =
"http://java.sun.com/xml/jaxp/properties/schemaLanguage";
/**
* The Locator associated with our parser.
*/
protected Locator locator = null;
/**
* The current match pattern for nested element processing.
*/
protected String match = "";
/**
* Do we want a "namespace aware" parser.
*/
protected boolean namespaceAware = false;
/**
* Registered namespaces we are currently processing. The key is the
* namespace prefix that was declared in the document. The value is an
* ArrayStack of the namespace URIs this prefix has been mapped to --
* the top Stack element is the most current one. (This architecture
* is required because documents can declare nested uses of the same
* prefix for different Namespace URIs).
*/
protected HashMap namespaces = new HashMap();
/**
* The parameters stack being utilized by CallMethodRule and
* CallParamRule rules.
*/
protected ArrayStack params = new ArrayStack();
/**
* The SAXParser we will use to parse the input stream.
*/
protected SAXParser parser = null;
/**
* The public identifier of the DTD we are currently parsing under
* (if any).
*/
protected String publicId = null;
/**
* The XMLReader used to parse digester rules.
*/
protected XMLReader reader = null;
/**
* The "root" element of the stack (in other words, the last object
* that was popped.
*/
protected Object root = null;
/**
* The <code>Rules</code> implementation containing our collection of
* <code>Rule</code> instances and associated matching policy. If not
* established before the first rule is added, a default implementation
* will be provided.
*/
protected Rules rules = null;
/**
* The XML schema language to use for validating an XML instance. By
* default this value is set to <code>W3C_XML_SCHEMA</code>
*/
protected String schemaLanguage = W3C_XML_SCHEMA;
/**
* The XML schema to use for validating an XML instance.
*/
protected String schemaLocation = null;
/**
* The object stack being constructed.
*/
protected ArrayStack stack = new ArrayStack();
/**
* Do we want to use the Context ClassLoader when loading classes
* for instantiating new objects. Default is <code>false</code>.
*/
protected boolean useContextClassLoader = false;
/**
* Do we want to use a validating parser.
*/
protected boolean validating = false;
/**
* The Log to which most logging calls will be made.
*/
protected Log log =
LogFactory.getLog("org.apache.commons.digester.Digester");
/**
* The Log to which all SAX event related logging calls will be made.
*/
protected Log saxLog =
LogFactory.getLog("org.apache.commons.digester.Digester.sax");
/**
* The schema language supported. By default, we use this one.
*/
protected static final String W3C_XML_SCHEMA =
"http:
/**
* Return the currently mapped namespace URI for the specified prefix,
* if any; otherwise return <code>null</code>. These mappings come and
* go dynamically as the document is parsed.
*
* @param prefix Prefix to look up
*/
public String findNamespaceURI(String prefix) {
ArrayStack stack = (ArrayStack) namespaces.get(prefix);
if (stack == null) {
return (null);
}
try {
return ((String) stack.peek());
} catch (EmptyStackException e) {
return (null);
}
}
/**
* Return the class loader to be used for instantiating application objects
* when required. This is determined based upon the following rules:
* <ul>
* <li>The class loader set by <code>setClassLoader()</code>, if any</li>
* <li>The thread context class loader, if it exists and the
* <code>useContextClassLoader</code> property is set to true</li>
* <li>The class loader used to load the Digester class itself.
* </ul>
*/
public ClassLoader getClassLoader() {
if (this.classLoader != null) {
return (this.classLoader);
}
if (this.useContextClassLoader) {
ClassLoader classLoader =
Thread.currentThread().getContextClassLoader();
if (classLoader != null) {
return (classLoader);
}
}
return (this.getClass().getClassLoader());
}
/**
* Set the class loader to be used for instantiating application objects
* when required.
*
* @param classLoader The new class loader to use, or <code>null</code>
* to revert to the standard rules
*/
public void setClassLoader(ClassLoader classLoader) {
this.classLoader = classLoader;
}
/**
* Return the current depth of the element stack.
*/
public int getCount() {
return (stack.size());
}
/**
* Return the name of the XML element that is currently being processed.
*/
public String getCurrentElementName() {
String elementName = match;
int lastSlash = elementName.lastIndexOf('/');
if (lastSlash >= 0) {
elementName = elementName.substring(lastSlash + 1);
}
return (elementName);
}
/**
* Return the debugging detail level of our currently enabled logger.
*
* @deprecated Configure the logger using standard mechanisms
* for your implementation
*/
public int getDebug() {
return (0);
}
/**
* Set the debugging detail level of our currently enabled logger.
*
* @param debug New debugging detail level (0=off, increasing integers
* for more detail)
*
* @deprecated Configure the logger using standard mechanisms
* for your implementation
*/
public void setDebug(int debug) {
; // No action is taken
}
/**
* Return the error handler for this Digester.
*/
public ErrorHandler getErrorHandler() {
return (this.errorHandler);
}
/**
* Set the error handler for this Digester.
*
* @param errorHandler The new error handler
*/
public void setErrorHandler(ErrorHandler errorHandler) {
this.errorHandler = errorHandler;
}
/**
* Return the SAXParserFactory we will use, creating one if necessary.
*/
public SAXParserFactory getFactory() {
if (factory == null) {
factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(namespaceAware);
factory.setValidating(validating);
}
return (factory);
}
public boolean getFeature(String feature)
throws ParserConfigurationException, SAXNotRecognizedException,
SAXNotSupportedException {
return (getFactory().getFeature(feature));
}
public void setFeature(String feature, boolean value)
throws ParserConfigurationException, SAXNotRecognizedException,
SAXNotSupportedException {
getFactory().setFeature(feature, value);
}
/**
* Return the current Logger associated with this instance of the Digester
*/
public Log getLogger() {
return log;
}
/**
* Set the current logger for this Digester.
*/
public void setLogger(Log log) {
this.log = log;
}
/**
* Return the current rule match path
*/
public String getMatch() {
return match;
}
/**
* Return the "namespace aware" flag for parsers we create.
*/
public boolean getNamespaceAware() {
return (this.namespaceAware);
}
/**
* Set the "namespace aware" flag for parsers we create.
*
* @param namespaceAware The new "namespace aware" flag
*/
public void setNamespaceAware(boolean namespaceAware) {
this.namespaceAware = namespaceAware;
}
/**
* Return the public identifier of the DTD we are currently
* parsing under, if any.
*/
public String getPublicId() {
return (this.publicId);
}
/**
* Return the namespace URI that will be applied to all subsequently
* added <code>Rule</code> objects.
*/
public String getRuleNamespaceURI() {
return (getRules().getNamespaceURI());
}
/**
* Set the namespace URI that will be applied to all subsequently
* added <code>Rule</code> objects.
*
* @param ruleNamespaceURI Namespace URI that must match on all
* subsequently added rules, or <code>null</code> for matching
* regardless of the current namespace URI
*/
public void setRuleNamespaceURI(String ruleNamespaceURI) {
getRules().setNamespaceURI(ruleNamespaceURI);
}
/**
* Return the SAXParser we will use to parse the input stream. If there
* is a problem creating the parser, return <code>null</code>.
*/
public SAXParser getParser() {
// Return the parser we already created (if any)
if (parser != null) {
return (parser);
}
// Create a new parser
try {
parser = getFactory().newSAXParser();
} catch (Exception e) {
log.error("Digester.getParser: ", e);
return (null);
}
// Configure standard properties and return the new instance
try {
if (schemaLocation != null) {
setProperty(JAXP_SCHEMA_LANGUAGE, schemaLanguage);
setProperty(JAXP_SCHEMA_SOURCE, schemaLocation);
}
} catch (Exception e) {
log.warn("" + e);
}
return (parser);
}
public Object getProperty(String property)
throws SAXNotRecognizedException, SAXNotSupportedException {
return (getParser().getProperty(property));
}
public void setProperty(String property, Object value)
throws SAXNotRecognizedException, SAXNotSupportedException {
getParser().setProperty(property, value);
}
/**
* By setting the reader in the constructor, you can bypass JAXP and
* be able to use digester in Weblogic 6.0.
*
* @deprecated Use getXMLReader() instead, which can throw a
* SAXException if the reader cannot be instantiated
*/
public XMLReader getReader() {
try {
return (getXMLReader());
} catch (SAXException e) {
log.error("Cannot get XMLReader", e);
return (null);
}
}
/**
* Return the <code>Rules</code> implementation object containing our
* rules collection and associated matching policy. If none has been
* established, a default implementation will be created and returned.
*/
public Rules getRules() {
if (this.rules == null) {
this.rules = new RulesBase();
this.rules.setDigester(this);
}
return (this.rules);
}
/**
* Set the <code>Rules</code> implementation object containing our
* rules collection and associated matching policy.
*
* @param rules New Rules implementation
*/
public void setRules(Rules rules) {
this.rules = rules;
this.rules.setDigester(this);
}
/**
* Return the XML Schema URI used for validating an XML instance.
*/
public String getSchema() {
return (this.schemaLocation);
}
/**
* Set the XML Schema URI used for validating a XML Instance.
*
* @param schemaLocation a URI to the schema.
*/
public void setSchema(String schemaLocation){
this.schemaLocation = schemaLocation;
}
/**
* Return the XML Schema language used when parsing.
*/
public String getSchemaLanguage() {
return (this.schemaLanguage);
}
/**
* Set the XML Schema language used when parsing. By default, we use W3C.
*
* @param schemaLanguage a URI to the schema language.
*/
public void setSchemaLanguage(String schemaLanguage){
this.schemaLanguage = schemaLanguage;
}
/**
* Return the boolean as to whether the context classloader should be used.
*/
public boolean getUseContextClassLoader() {
return useContextClassLoader;
}
/**
* Determine whether to use the Context ClassLoader (the one found by
* calling <code>Thread.currentThread().getContextClassLoader()</code>)
* to resolve/load classes that are defined in various rules. If not
* using Context ClassLoader, then the class-loading defaults to
* using the calling-class' ClassLoader.
*
* @param boolean determines whether to use Context ClassLoader.
*/
public void setUseContextClassLoader(boolean use) {
useContextClassLoader = use;
}
/**
* Return the validating parser flag.
*/
public boolean getValidating() {
return (this.validating);
}
/**
* Set the validating parser flag. This must be called before
* <code>parse()</code> is called the first time.
*
* @param validating The new validating parser flag.
*/
public void setValidating(boolean validating) {
this.validating = validating;
}
/**
* Return the XMLReader to be used for parsing the input document.
*
* FIX ME: there is a bug in JAXP/XERCES that prevent the use of a
* parser that contains a schema with a DTD.
* @exception SAXException if no XMLReader can be instantiated
*/
public XMLReader getXMLReader() throws SAXException {
if (reader == null){
reader = getParser().getXMLReader();
}
reader.setDTDHandler(this);
reader.setContentHandler(this);
if (entityResolver == null){
reader.setEntityResolver(this);
} else {
reader.setEntityResolver(entityResolver);
}
reader.setErrorHandler(this);
return reader;
}
/**
* Process notification of character data received from the body of
* an XML element.
*
* @param buffer The characters from the XML document
* @param start Starting offset into the buffer
* @param length Number of characters from the buffer
*
* @exception SAXException if a parsing error is to be reported
*/
public void characters(char buffer[], int start, int length)
throws SAXException {
if (saxLog.isDebugEnabled()) {
saxLog.debug("characters(" + new String(buffer, start, length) + ")");
}
bodyText.append(buffer, start, length);
}
/**
* Process notification of the end of the document being reached.
*
* @exception SAXException if a parsing error is to be reported
*/
public void endDocument() throws SAXException {
if (saxLog.isDebugEnabled()) {
if (getCount() > 1) {
saxLog.debug("endDocument(): " + getCount() +
" elements left");
} else {
saxLog.debug("endDocument()");
}
}
while (getCount() > 1) {
pop();
}
// Fire "finish" events for all defined rules
Iterator rules = getRules().rules().iterator();
while (rules.hasNext()) {
Rule rule = (Rule) rules.next();
try {
rule.finish();
} catch (Exception e) {
log.error("Finish event threw exception", e);
throw createSAXException(e);
} catch (Error e) {
log.error("Finish event threw error", e);
throw e;
}
}
// Perform final cleanup
clear();
}
/**
* Process notification of the end of an XML element being reached.
*
* @param uri - The Namespace URI, or the empty string if the
* element has no Namespace URI or if Namespace processing is not
* being performed.
* @param localName - The local name (without prefix), or the empty
* string if Namespace processing is not being performed.
* @param qName - The qualified XML 1.0 name (with prefix), or the
* empty string if qualified names are not available.
* @exception SAXException if a parsing error is to be reported
*/
public void endElement(String namespaceURI, String localName,
String qName) throws SAXException {
boolean debug = log.isDebugEnabled();
if (debug) {
if (saxLog.isDebugEnabled()) {
saxLog.debug("endElement(" + namespaceURI + "," + localName +
"," + qName + ")");
}
log.debug(" match='" + match + "'");
log.debug(" bodyText='" + bodyText + "'");
}
// Fire "body" events for all relevant rules
List rules = getRules().match(namespaceURI, match);
if ((rules != null) && (rules.size() > 0)) {
String bodyText = this.bodyText.toString();
for (int i = 0; i < rules.size(); i++) {
try {
Rule rule = (Rule) rules.get(i);
if (debug) {
log.debug(" Fire body() for " + rule);
}
rule.body(bodyText);
} catch (Exception e) {
log.error("Body event threw exception", e);
throw createSAXException(e);
} catch (Error e) {
log.error("Body event threw error", e);
throw e;
}
}
} else {
if (debug) {
log.debug(" No rules found matching '" + match + "'.");
}
}
// Recover the body text from the surrounding element
bodyText = (StringBuffer) bodyTexts.pop();
if (debug) {
log.debug(" Popping body text '" + bodyText.toString() + "'");
}
// Fire "end" events for all relevant rules in reverse order
if (rules != null) {
for (int i = 0; i < rules.size(); i++) {
int j = (rules.size() - i) - 1;
try {
Rule rule = (Rule) rules.get(j);
if (debug) {
log.debug(" Fire end() for " + rule);
}
rule.end();
} catch (Exception e) {
log.error("End event threw exception", e);
throw createSAXException(e);
} catch (Error e) {
log.error("End event threw error", e);
throw e;
}
}
}
// Recover the previous match expression
int slash = match.lastIndexOf('/');
if (slash >= 0) {
match = match.substring(0, slash);
} else {
match = "";
}
}
/**
* Process notification that a namespace prefix is going out of scope.
*
* @param prefix Prefix that is going out of scope
*
* @exception SAXException if a parsing error is to be reported
*/
public void endPrefixMapping(String prefix) throws SAXException {
if (saxLog.isDebugEnabled()) {
saxLog.debug("endPrefixMapping(" + prefix + ")");
}
// Deregister this prefix mapping
ArrayStack stack = (ArrayStack) namespaces.get(prefix);
if (stack == null) {
return;
}
try {
stack.pop();
if (stack.empty())
namespaces.remove(prefix);
} catch (EmptyStackException e) {
throw createSAXException("endPrefixMapping popped too many times");
}
}
/**
* Process notification of ignorable whitespace received from the body of
* an XML element.
*
* @param buffer The characters from the XML document
* @param start Starting offset into the buffer
* @param length Number of characters from the buffer
*
* @exception SAXException if a parsing error is to be reported
*/
public void ignorableWhitespace(char buffer[], int start, int len)
throws SAXException {
if (saxLog.isDebugEnabled()) {
saxLog.debug("ignorableWhitespace(" +
new String(buffer, start, len) + ")");
}
; // No processing required
}
/**
* Process notification of a processing instruction that was encountered.
*
* @param target The processing instruction target
* @param data The processing instruction data (if any)
*
* @exception SAXException if a parsing error is to be reported
*/
public void processingInstruction(String target, String data)
throws SAXException {
if (saxLog.isDebugEnabled()) {
saxLog.debug("processingInstruction('" + target + "','" + data + "')");
}
; // No processing is required
}
/**
* Set the document locator associated with our parser.
*
* @param locator The new locator
*/
public void setDocumentLocator(Locator locator) {
if (saxLog.isDebugEnabled()) {
saxLog.debug("setDocumentLocator(" + locator + ")");
}
this.locator = locator;
}
/**
* Process notification of a skipped entity.
*
* @param name Name of the skipped entity
*
* @exception SAXException if a parsing error is to be reported
*/
public void skippedEntity(String name) throws SAXException {
if (saxLog.isDebugEnabled()) {
saxLog.debug("skippedEntity(" + name + ")");
}
; // No processing required
}
/**
* Process notification of the beginning of the document being reached.
*
* @exception SAXException if a parsing error is to be reported
*/
public void startDocument() throws SAXException {
if (saxLog.isDebugEnabled()) {
saxLog.debug("startDocument()");
}
// ensure that the digester is properly configured, as
// the digester could be used as a SAX ContentHandler
// rather than via the parse() methods.
configure();
}
/**
* Process notification of the start of an XML element being reached.
*
* @param uri The Namespace URI, or the empty string if the element
* has no Namespace URI or if Namespace processing is not being performed.
* @param localName The local name (without prefix), or the empty
* string if Namespace processing is not being performed.
* @param qName The qualified name (with prefix), or the empty
* string if qualified names are not available.\
* @param list The attributes attached to the element. If there are
* no attributes, it shall be an empty Attributes object.
* @exception SAXException if a parsing error is to be reported
*/
public void startElement(String namespaceURI, String localName,
String qName, Attributes list)
throws SAXException {
boolean debug = log.isDebugEnabled();
if (saxLog.isDebugEnabled()) {
saxLog.debug("startElement(" + namespaceURI + "," + localName + "," +
qName + ")");
}
// Save the body text accumulated for our surrounding element
bodyTexts.push(bodyText);
if (debug) {
log.debug(" Pushing body text '" + bodyText.toString() + "'");
}
bodyText = new StringBuffer();
// Compute the current matching rule
StringBuffer sb = new StringBuffer(match);
if (match.length() > 0) {
sb.append('/');
}
if ((localName == null) || (localName.length() < 1)) {
sb.append(qName);
} else {
sb.append(localName);
}
match = sb.toString();
if (debug) {
log.debug(" New match='" + match + "'");
}
// Fire "begin" events for all relevant rules
List rules = getRules().match(namespaceURI, match);
if ((rules != null) && (rules.size() > 0)) {
String bodyText = this.bodyText.toString();
for (int i = 0; i < rules.size(); i++) {
try {
Rule rule = (Rule) rules.get(i);
if (debug) {
log.debug(" Fire begin() for " + rule);
}
rule.begin(list);
} catch (Exception e) {
log.error("Begin event threw exception", e);
throw createSAXException(e);
} catch (Error e) {
log.error("Begin event threw error", e);
throw e;
}
}
} else {
if (debug) {
log.debug(" No rules found matching '" + match + "'.");
}
}
}
/**
* Process notification that a namespace prefix is coming in to scope.
*
* @param prefix Prefix that is being declared
* @param namespaceURI Corresponding namespace URI being mapped to
*
* @exception SAXException if a parsing error is to be reported
*/
public void startPrefixMapping(String prefix, String namespaceURI)
throws SAXException {
if (saxLog.isDebugEnabled()) {
saxLog.debug("startPrefixMapping(" + prefix + "," + namespaceURI + ")");
}
// Register this prefix mapping
ArrayStack stack = (ArrayStack) namespaces.get(prefix);
if (stack == null) {
stack = new ArrayStack();
namespaces.put(prefix, stack);
}
stack.push(namespaceURI);
}
/**
* Receive notification of a notation declaration event.
*
* @param name The notation name
* @param publicId The public identifier (if any)
* @param systemId The system identifier (if any)
*/
public void notationDecl(String name, String publicId, String systemId) {
if (saxLog.isDebugEnabled()) {
saxLog.debug("notationDecl(" + name + "," + publicId + "," +
systemId + ")");
}
}
/**
* Receive notification of an unparsed entity declaration event.
*
* @param name The unparsed entity name
* @param publicId The public identifier (if any)
* @param systemId The system identifier (if any)
* @param notation The name of the associated notation
*/
public void unparsedEntityDecl(String name, String publicId,
String systemId, String notation) {
if (saxLog.isDebugEnabled()) {
saxLog.debug("unparsedEntityDecl(" + name + "," + publicId + "," +
systemId + "," + notation + ")");
}
}
/**
* Set the <code>EntityResolver</code> used by SAX when resolving
* public id and system id.
* This must be called before the first call to <code>parse()</code>.
* @param entityResolver a class that implement the <code>EntityResolver</code> interface.
*/
public void setEntityResolver(EntityResolver entityResolver){
this.entityResolver = entityResolver;
}
/**
* Return the Entity Resolver used by the SAX parser.
* @return Return the Entity Resolver used by the SAX parser.
*/
public EntityResolver getEntityResolver(){
return entityResolver;
}
/**
* Resolve the requested external entity.
*
* @param publicId The public identifier of the entity being referenced
* @param systemId The system identifier of the entity being referenced
*
* @exception SAXException if a parsing exception occurs
* <
*/
public InputSource resolveEntity(String publicId, String systemId)
throws SAXException {
boolean debug = log.isDebugEnabled();
if (saxLog.isDebugEnabled()) {
saxLog.debug("resolveEntity('" + publicId + "', '" + systemId + "')");
}
if (publicId != null)
this.publicId = publicId;
// Has this system identifier been registered?
String entityURL = null;
if (publicId != null) {
entityURL = (String) entityValidator.get(publicId);
}
// Redirect the schema location to a local destination
if (schemaLocation != null && entityURL == null && systemId != null){
entityURL = (String)entityValidator.get(systemId);
}
if (entityURL == null){
return (null);
}
// Return an input source to our alternative URL
if (debug) {
log.debug(" Resolving to alternate DTD '" + entityURL + "'");
}
try {
return (new InputSource(entityURL));
} catch (Exception e) {
throw createSAXException(e);
}
}
/**
* Forward notification of a parsing error to the application supplied
* error handler (if any).
*
* @param exception The error information
*
* @exception SAXException if a parsing exception occurs
*/
public void error(SAXParseException exception) throws SAXException {
log.error("Parse Error at line " + exception.getLineNumber() +
" column " + exception.getColumnNumber() + ": " +
exception.getMessage(), exception);
if (errorHandler != null) {
errorHandler.error(exception);
}
}
/**
* Forward notification of a fatal parsing error to the application
* supplied error handler (if any).
*
* @param exception The fatal error information
*
* @exception SAXException if a parsing exception occurs
*/
public void fatalError(SAXParseException exception) throws SAXException {
log.error("Parse Fatal Error at line " + exception.getLineNumber() +
" column " + exception.getColumnNumber() + ": " +
exception.getMessage(), exception);
if (errorHandler != null) {
errorHandler.fatalError(exception);
}
}
/**
* Forward notification of a parse warning to the application supplied
* error handler (if any).
*
* @param exception The warning information
*
* @exception SAXException if a parsing exception occurs
*/
public void warning(SAXParseException exception) throws SAXException {
if (errorHandler != null) {
log.warn("Parse Warning Error at line " + exception.getLineNumber() +
" column " + exception.getColumnNumber() + ": " +
exception.getMessage(), exception);
errorHandler.warning(exception);
}
}
/**
* Log a message to our associated logger.
*
* @param message The message to be logged
* @deprecated Call getLogger() and use it's logging methods
*/
public void log(String message) {
log.info(message);
}
/**
* Log a message and exception to our associated logger.
*
* @param message The message to be logged
* @deprecated Call getLogger() and use it's logging methods
*/
public void log(String message, Throwable exception) {
log.error(message, exception);
}
/**
* Parse the content of the specified file using this Digester. Returns
* the root element from the object stack (if any).
*
* @param file File containing the XML data to be parsed
*
* @exception IOException if an input/output error occurs
* @exception SAXException if a parsing exception occurs
*/
public Object parse(File file) throws IOException, SAXException {
configure();
InputSource input = new InputSource(new FileInputStream(file));
input.setSystemId("file://" + file.getAbsolutePath());
getXMLReader().parse(input);
return (root);
}
/**
* Parse the content of the specified input source using this Digester.
* Returns the root element from the object stack (if any).
*
* @param input Input source containing the XML data to be parsed
*
* @exception IOException if an input/output error occurs
* @exception SAXException if a parsing exception occurs
*/
public Object parse(InputSource input) throws IOException, SAXException {
configure();
getXMLReader().parse(input);
return (root);
}
/**
* Parse the content of the specified input stream using this Digester.
* Returns the root element from the object stack (if any).
*
* @param input Input stream containing the XML data to be parsed
*
* @exception IOException if an input/output error occurs
* @exception SAXException if a parsing exception occurs
*/
public Object parse(InputStream input) throws IOException, SAXException {
configure();
InputSource is = new InputSource(input);
getXMLReader().parse(is);
return (root);
}
/**
* Parse the content of the specified reader using this Digester.
* Returns the root element from the object stack (if any).
*
* @param reader Reader containing the XML data to be parsed
*
* @exception IOException if an input/output error occurs
* @exception SAXException if a parsing exception occurs
*/
public Object parse(Reader reader) throws IOException, SAXException {
configure();
InputSource is = new InputSource(reader);
getXMLReader().parse(is);
return (root);
}
/**
* Parse the content of the specified URI using this Digester.
* Returns the root element from the object stack (if any).
*
* @param uri URI containing the XML data to be parsed
*
* @exception IOException if an input/output error occurs
* @exception SAXException if a parsing exception occurs
*/
public Object parse(String uri) throws IOException, SAXException {
configure();
InputSource is = new InputSource(uri);
getXMLReader().parse(is);
return (root);
}
/**
* Register the specified DTD URL for the specified public identifier.
* This must be called before the first call to <code>parse()</code>.
*
* @param publicId Public identifier of the DTD to be resolved
* @param entityURL The URL to use for reading this DTD
*/
public void register(String publicId, String entityURL) {
if (log.isDebugEnabled()) {
log.debug("register('" + publicId + "', '" + entityURL + "'");
}
entityValidator.put(publicId, entityURL);
}
/**
* <p>Register a new Rule matching the specified pattern.
* This method sets the <code>Digester</code> property on the rule.</p>
*
* @param pattern Element matching pattern
* @param rule Rule to be registered
*/
public void addRule(String pattern, Rule rule) {
rule.setDigester(this);
getRules().add(pattern, rule);
}
/**
* Register a set of Rule instances defined in a RuleSet.
*
* @param ruleSet The RuleSet instance to configure from
*/
public void addRuleSet(RuleSet ruleSet) {
String oldNamespaceURI = getRuleNamespaceURI();
String newNamespaceURI = ruleSet.getNamespaceURI();
if (log.isDebugEnabled()) {
if (newNamespaceURI == null) {
log.debug("addRuleSet() with no namespace URI");
} else {
log.debug("addRuleSet() with namespace URI " + newNamespaceURI);
}
}
setRuleNamespaceURI(newNamespaceURI);
ruleSet.addRuleInstances(this);
setRuleNamespaceURI(oldNamespaceURI);
}
/**
* Add a "bean property setter" rule for the specified parameters.
*
* @param pattern Element matching pattern
*/
public void addBeanPropertySetter(String pattern) {
addRule(pattern,
new BeanPropertySetterRule());
}
/**
* Add a "bean property setter" rule for the specified parameters.
*
* @param pattern Element matching pattern
* @param propertyName Name of property to set
*/
public void addBeanPropertySetter(String pattern,
String propertyName) {
addRule(pattern,
new BeanPropertySetterRule(propertyName));
}
/**
* Add an "call method" rule for a method which accepts no arguments.
*
* @param pattern Element matching pattern
* @param methodName Method name to be called
*/
public void addCallMethod(String pattern, String methodName) {
addRule(
pattern,
new CallMethodRule(methodName));
}
/**
* Add an "call method" rule for the specified parameters.
*
* @param pattern Element matching pattern
* @param methodName Method name to be called
* @param paramCount Number of expected parameters (or zero
* for a single parameter from the body of this element)
*/
public void addCallMethod(String pattern, String methodName,
int paramCount) {
addRule(pattern,
new CallMethodRule(methodName, paramCount));
}
/**
* Add an "call method" rule for the specified parameters.
* If <code>paramCount</code> is set to zero the rule will use
* the body of the matched element as the single argument of the
* method, unless <code>paramTypes</code> is null or empty, in this
* case the rule will call the specified method with no arguments.
*
* @param pattern Element matching pattern
* @param methodName Method name to be called
* @param paramCount Number of expected parameters (or zero
* for a single parameter from the body of this element)
* @param paramTypes Set of Java class names for the types
* of the expected parameters
* (if you wish to use a primitive type, specify the corresonding
* Java wrapper class instead, such as <code>java.lang.Boolean</code>
* for a <code>boolean</code> parameter)
*/
public void addCallMethod(String pattern, String methodName,
int paramCount, String paramTypes[]) {
addRule(pattern,
new CallMethodRule(
methodName,
paramCount,
paramTypes));
}
/**
* Add an "call method" rule for the specified parameters.
* If <code>paramCount</code> is set to zero the rule will use
* the body of the matched element as the single argument of the
* method, unless <code>paramTypes</code> is null or empty, in this
* case the rule will call the specified method with no arguments.
*
* @param pattern Element matching pattern
* @param methodName Method name to be called
* @param paramCount Number of expected parameters (or zero
* for a single parameter from the body of this element)
* @param paramTypes The Java class names of the arguments
* (if you wish to use a primitive type, specify the corresonding
* Java wrapper class instead, such as <code>java.lang.Boolean</code>
* for a <code>boolean</code> parameter)
*/
public void addCallMethod(String pattern, String methodName,
int paramCount, Class paramTypes[]) {
addRule(pattern,
new CallMethodRule(
methodName,
paramCount,
paramTypes));
}
/**
* Add a "call parameter" rule for the specified parameters.
*
* @param pattern Element matching pattern
* @param paramIndex Zero-relative parameter index to set
* (from the body of this element)
*/
public void addCallParam(String pattern, int paramIndex) {
addRule(pattern,
new CallParamRule(paramIndex));
}
/**
* Add a "call parameter" rule for the specified parameters.
*
* @param pattern Element matching pattern
* @param paramIndex Zero-relative parameter index to set
* (from the specified attribute)
* @param attributeName Attribute whose value is used as the
* parameter value
*/
public void addCallParam(String pattern, int paramIndex,
String attributeName) {
addRule(pattern,
new CallParamRule(paramIndex, attributeName));
}
/**
* Add a "factory create" rule for the specified parameters.
*
* @param pattern Element matching pattern
* @param className Java class name of the object creation factory class
*/
public void addFactoryCreate(String pattern, String className) {
addRule(pattern,
new FactoryCreateRule(className));
}
/**
* Add a "factory create" rule for the specified parameters.
*
* @param pattern Element matching pattern
* @param clazz Java class of the object creation factory class
*/
public void addFactoryCreate(String pattern, Class clazz) {
addRule(pattern,
new FactoryCreateRule(clazz));
}
/**
* Add a "factory create" rule for the specified parameters.
*
* @param pattern Element matching pattern
* @param className Java class name of the object creation factory class
* @param attributeName Attribute name which, if present, overrides the
* value specified by <code>className</code>
*/
public void addFactoryCreate(String pattern, String className,
String attributeName) {
addRule(pattern,
new FactoryCreateRule(className, attributeName));
}
/**
* Add a "factory create" rule for the specified parameters.
*
* @param pattern Element matching pattern
* @param clazz Java class of the object creation factory class
* @param attributeName Attribute name which, if present, overrides the
* value specified by <code>className</code>
*/
public void addFactoryCreate(String pattern, Class clazz,
String attributeName) {
addRule(pattern,
new FactoryCreateRule(clazz, attributeName));
}
/**
* Add a "factory create" rule for the specified parameters.
*
* @param pattern Element matching pattern
* @param creationFactory Previously instantiated ObjectCreationFactory
* to be utilized
*/
public void addFactoryCreate(String pattern,
ObjectCreationFactory creationFactory) {
creationFactory.setDigester(this);
addRule(pattern,
new FactoryCreateRule(creationFactory));
}
/**
* Add an "object create" rule for the specified parameters.
*
* @param pattern Element matching pattern
* @param className Java class name to be created
*/
public void addObjectCreate(String pattern, String className) {
addRule(pattern,
new ObjectCreateRule(className));
}
/**
* Add an "object create" rule for the specified parameters.
*
* @param pattern Element matching pattern
* @param clazz Java class to be created
*/
public void addObjectCreate(String pattern, Class clazz) {
addRule(pattern,
new ObjectCreateRule(clazz));
}
/**
* Add an "object create" rule for the specified parameters.
*
* @param pattern Element matching pattern
* @param className Default Java class name to be created
* @param attributeName Attribute name that optionally overrides
* the default Java class name to be created
*/
public void addObjectCreate(String pattern, String className,
String attributeName) {
addRule(pattern,
new ObjectCreateRule(className, attributeName));
}
/**
* Add an "object create" rule for the specified parameters.
*
* @param pattern Element matching pattern
* @param attributeName Attribute name that optionally overrides
* @param clazz Default Java class to be created
* the default Java class name to be created
*/
public void addObjectCreate(String pattern,
String attributeName,
Class clazz) {
addRule(pattern,
new ObjectCreateRule(attributeName, clazz));
}
/**
* Add a "set next" rule for the specified parameters.
*
* @param pattern Element matching pattern
* @param methodName Method name to call on the parent element
*/
public void addSetNext(String pattern, String methodName) {
addRule(pattern,
new SetNextRule(methodName));
}
/**
* Add a "set next" rule for the specified parameters.
*
* @param pattern Element matching pattern
* @param methodName Method name to call on the parent element
* @param paramType Java class name of the expected parameter type
* (if you wish to use a primitive type, specify the corresonding
* Java wrapper class instead, such as <code>java.lang.Boolean</code>
* for a <code>boolean</code> parameter)
*/
public void addSetNext(String pattern, String methodName,
String paramType) {
addRule(pattern,
new SetNextRule(methodName, paramType));
}
/**
* Add {@link SetRootRule} with the specified parameters.
*
* @param pattern Element matching pattern
* @param methodName Method name to call on the root object
*/
public void addSetRoot(String pattern, String methodName) {
addRule(pattern,
new SetRootRule(methodName));
}
/**
* Add {@link SetRootRule} with the specified parameters.
*
* @param pattern Element matching pattern
* @param methodName Method name to call on the root object
* @param paramType Java class name of the expected parameter type
*/
public void addSetRoot(String pattern, String methodName,
String paramType) {
addRule(pattern,
new SetRootRule(methodName, paramType));
}
/**
* Add a "set properties" rule for the specified parameters.
*
* @param pattern Element matching pattern
*/
public void addSetProperties(String pattern) {
addRule(pattern,
new SetPropertiesRule());
}
/**
* Add a "set properties" rule with a single overridden parameter.
* See {@link SetPropertiesRule#SetPropertiesRule(String attributeName, String propertyName)}
*
* @param pattern Element matching pattern
* @param attributeName map this attribute
* @param propertyNames to this property
*/
public void addSetProperties(
String pattern,
String attributeName,
String propertyName) {
addRule(pattern,
new SetPropertiesRule(attributeName, propertyName));
}
/**
* Add a "set properties" rule with overridden parameters.
* See {@link SetPropertiesRule#SetPropertiesRule(String [] attributeNames, String [] propertyNames)}
*
* @param pattern Element matching pattern
* @param attributeNames names of attributes with custom mappings
* @param propertyNames property names these attributes map to
*/
public void addSetProperties(
String pattern,
String [] attributeNames,
String [] propertyNames) {
addRule(pattern,
new SetPropertiesRule(attributeNames, propertyNames));
}
/**
* Add a "set property" rule for the specified parameters.
*
* @param pattern Element matching pattern
* @param name Attribute name containing the property name to be set
* @param value Attribute name containing the property value to set
*/
public void addSetProperty(String pattern, String name, String value) {
addRule(pattern,
new SetPropertyRule(name, value));
}
/**
* Add a "set top" rule for the specified parameters.
*
* @param pattern Element matching pattern
* @param methodName Method name to call on the parent element
*/
public void addSetTop(String pattern, String methodName) {
addRule(pattern,
new SetTopRule(methodName));
}
/**
* Add a "set top" rule for the specified parameters.
*
* @param pattern Element matching pattern
* @param methodName Method name to call on the parent element
* @param paramType Java class name of the expected parameter type
* (if you wish to use a primitive type, specify the corresonding
* Java wrapper class instead, such as <code>java.lang.Boolean</code>
* for a <code>boolean</code> parameter)
*/
public void addSetTop(String pattern, String methodName,
String paramType) {
addRule(pattern,
new SetTopRule(methodName, paramType));
}
/**
* Clear the current contents of the object stack.
*/
public void clear() {
match = "";
bodyTexts.clear();
params.clear();
publicId = null;
stack.clear();
}
/**
* Return the top object on the stack without removing it. If there are
* no objects on the stack, return <code>null</code>.
*/
public Object peek() {
try {
return (stack.peek());
} catch (EmptyStackException e) {
log.warn("Empty stack (returning null)");
return (null);
}
}
/**
* Return the n'th object down the stack, where 0 is the top element
* and [getCount()-1] is the bottom element. If the specified index
* is out of range, return <code>null</code>.
*
* @param n Index of the desired element, where 0 is the top of the stack,
* 1 is the next element down, and so on.
*/
public Object peek(int n) {
try {
return (stack.peek(n));
} catch (EmptyStackException e) {
log.warn("Empty stack (returning null)");
return (null);
}
}
/**
* Pop the top object off of the stack, and return it. If there are
* no objects on the stack, return <code>null</code>.
*/
public Object pop() {
try {
return (stack.pop());
} catch (EmptyStackException e) {
log.warn("Empty stack (returning null)");
return (null);
}
}
/**
* Push a new object onto the top of the object stack.
*
* @param object The new object
*/
public void push(Object object) {
if (stack.size() == 0) {
root = object;
}
stack.push(object);
}
/**
* When the Digester is being used as a SAXContentHandler,
* this method allows you to access the root object that has been
* created after parsing.
*
* @return the root object that has been created after parsing
* or null if the digester has not parsed any XML yet.
*/
public Object getRoot() {
return root;
}
/**
* Provide a hook for lazy configuration of this <code>Digester</code>
* instance. The default implementation does nothing, but subclasses
* can override as needed.
*/
protected void configure() {
// Do not configure more than once
if (configured) {
return;
}
// Perform lazy configuration as needed
; // Nothing required by default
// Set the configuration flag to avoid repeating
configured = true;
}
/**
* Return the set of DTD URL registrations, keyed by public identifier.
*/
Map getRegistrations() {
return (entityValidator);
}
/**
* Return the set of rules that apply to the specified match position.
* The selected rules are those that match exactly, or those rules
* that specify a suffix match and the tail of the rule matches the
* current match position. Exact matches have precedence over
* suffix matches, then (among suffix matches) the longest match
* is preferred.
*
* @param match The current match position
*
* @deprecated Call <code>match()</code> on the <code>Rules</code>
* implementation returned by <code>getRules()</code>
*/
List getRules(String match) {
return (getRules().match(match));
}
/**
* <p>Return the top object on the parameters stack without removing it. If there are
* no objects on the stack, return <code>null</code>.</p>
*
* <p>The parameters stack is used to store <code>CallMethodRule</code> parameters.
* See {@link #params}.</p>
*/
Object peekParams() {
try {
return (params.peek());
} catch (EmptyStackException e) {
log.warn("Empty stack (returning null)");
return (null);
}
}
/**
* <p>Return the n'th object down the parameters stack, where 0 is the top element
* and [getCount()-1] is the bottom element. If the specified index
* is out of range, return <code>null</code>.</p>
*
* <p>The parameters stack is used to store <code>CallMethodRule</code> parameters.
* See {@link #params}.</p>
*
* @param n Index of the desired element, where 0 is the top of the stack,
* 1 is the next element down, and so on.
*/
Object peekParams(int n) {
try {
return (params.peek(n));
} catch (EmptyStackException e) {
log.warn("Empty stack (returning null)");
return (null);
}
}
/**
* <p>Pop the top object off of the parameters stack, and return it. If there are
* no objects on the stack, return <code>null</code>.</p>
*
* <p>The parameters stack is used to store <code>CallMethodRule</code> parameters.
* See {@link #params}.</p>
*/
Object popParams() {
try {
if (log.isTraceEnabled()) {
log.trace("Popping params");
}
return (params.pop());
} catch (EmptyStackException e) {
log.warn("Empty stack (returning null)");
return (null);
}
}
/**
* <p>Push a new object onto the top of the parameters stack.</p>
*
* <p>The parameters stack is used to store <code>CallMethodRule</code> parameters.
* See {@link #params}.</p>
*
* @param object The new object
*/
void pushParams(Object object) {
if (log.isTraceEnabled()) {
log.trace("Pushing params");
}
params.push(object);
}
/**
* Create a SAX exception which also understands about the location in
* the digester file where the exception occurs
*
* @return the new exception
*/
protected SAXException createSAXException(String message, Exception e) {
if (locator != null) {
String error = "Error at (" + locator.getLineNumber() + ", "
+ locator.getColumnNumber() + ": " + message;
if (e != null) {
return new SAXParseException(error, locator, e);
} else {
return new SAXParseException(error, locator);
}
}
log.error("No Locator!");
if (e != null) {
return new SAXException(message, e);
} else {
return new SAXException(message);
}
}
/**
* Create a SAX exception which also understands about the location in
* the digester file where the exception occurs
*
* @return the new exception
*/
protected SAXException createSAXException(Exception e) {
return createSAXException(e.getMessage(), e);
}
/**
* Create a SAX exception which also understands about the location in
* the digester file where the exception occurs
*
* @return the new exception
*/
protected SAXException createSAXException(String message) {
return createSAXException(message, null);
}
}
|
package org.apache.commons.digester;
import java.io.File;
import java.io.FileReader;
import java.io.InputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.EmptyStackException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.apache.commons.collections.ArrayStack;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.EntityResolver;
import org.xml.sax.ErrorHandler;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.InputSource;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;
public class Digester extends DefaultHandler {
/**
* Construct a new Digester with default properties.
*/
public Digester() {
super();
}
/**
* Construct a new Digester, allowing a SAXParser to be passed in. This
* allows Digester to be used in environments which are unfriendly to
* JAXP1.1 (such as WebLogic 6.0). Thanks for the request to change go to
* James House (james@interobjective.com). This may help in places where
* you are able to load JAXP 1.1 classes yourself.
*/
public Digester(SAXParser parser) {
super();
this.parser = parser;
}
/**
* Construct a new Digester, allowing an XMLReader to be passed in. This
* allows Digester to be used in environments which are unfriendly to
* JAXP1.1 (such as WebLogic 6.0). Note that if you use this option you
* have to configure namespace and validation support yourself, as these
* properties only affect the SAXParser and emtpy constructor.
*/
public Digester(XMLReader reader) {
super();
this.reader = reader;
}
/**
* The body text of the current element.
*/
protected StringBuffer bodyText = new StringBuffer();
/**
* The stack of body text string buffers for surrounding elements.
*/
protected ArrayStack bodyTexts = new ArrayStack();
/**
* The class loader to use for instantiating application objects.
* If not specified, the context class loader, or the class loader
* used to load Digester itself, is used, based on the value of the
* <code>useContextClassLoader</code> variable.
*/
protected ClassLoader classLoader = null;
/**
* Has this Digester been configured yet?
*/
protected boolean configured = false;
/**
* The debugging detail level of this component.
*/
protected int debug = 0;
/**
* The URLs of DTDs that have been registered, keyed by the public
* identifier that corresponds.
*/
protected HashMap dtds = new HashMap();
/**
* The application-supplied error handler that is notified when parsing
* warnings, errors, or fatal errors occur.
*/
protected ErrorHandler errorHandler = null;
/**
* The SAXParserFactory that is created the first time we need it.
*/
protected static SAXParserFactory factory = null;
/**
* The Locator associated with our parser.
*/
protected Locator locator = null;
/**
* The current match pattern for nested element processing.
*/
protected String match = "";
/**
* Do we want a "namespace aware" parser?
*/
protected boolean namespaceAware = false;
/**
* Registered namespaces we are currently processing. The key is the
* namespace prefix that was declared in the document. The value is an
* ArrayStack of the namespace URIs this prefix has been mapped to --
* the top Stack element is the most current one. (This architecture
* is required because documents can declare nested uses of the same
* prefix for different Namespace URIs).
*/
protected HashMap namespaces = new HashMap();
/**
* The parameters stack being utilized by CallMethodRule and
* CallParamRule rules.
*/
protected ArrayStack params = new ArrayStack();
/**
* The SAXParser we will use to parse the input stream.
*/
protected SAXParser parser = null;
/**
* The public identifier of the DTD we are currently parsing under
* (if any).
*/
protected String publicId = null;
/**
* The XMLReader used to parse digester rules.
*/
protected XMLReader reader = null;
/**
* The "root" element of the stack (in other words, the last object
* that was popped.
*/
protected Object root = null;
/**
* The <code>Rules</code> implementation containing our collection of
* <code>Rule</code> instances and associated matching policy. If not
* established before the first rule is added, a default implementation
* will be provided.
*/
protected Rules rules = null;
/**
* The object stack being constructed.
*/
protected ArrayStack stack = new ArrayStack();
/**
* Do we want to use the Context ClassLoader when loading classes
* for instantiating new objects? Default is <code>false</code>.
*/
protected boolean useContextClassLoader = false;
/**
* Do we want to use a validating parser?
*/
protected boolean validating = false;
/**
* The PrintWriter to which we should send log output, or
* <code>null</code> to write to <code>System.out</code>.
*/
protected PrintWriter writer = null;
/**
* Return the currently mapped namespace URI for the specified prefix,
* if any; otherwise return <code>null</code>. These mappings come and
* go dynamically as the document is parsed.
*
* @param prefix Prefix to look up
*/
public String findNamespaceURI(String prefix) {
ArrayStack stack = (ArrayStack) namespaces.get(prefix);
if (stack == null)
return (null);
try {
return ((String) stack.peek());
} catch (EmptyStackException e) {
return (null);
}
}
/**
* Return the class loader to be used for instantiating application objects
* when required. This is determined based upon the following rules:
* <ul>
* <li>The class loader set by <code>setClassLoader()</code>, if any</li>
* <li>The thread context class loader, if it exists and the
* <code>useContextClassLoader</code> property is set to true</li>
* <li>The class loader used to load the Digester class itself.
* </ul>
*/
public ClassLoader getClassLoader() {
if (this.classLoader != null)
return (this.classLoader);
if (this.useContextClassLoader) {
ClassLoader classLoader =
Thread.currentThread().getContextClassLoader();
if (classLoader != null)
return (classLoader);
}
return (this.getClass().getClassLoader());
}
/**
* Set the class loader to be used for instantiating application objects
* when required.
*
* @param classLoader The new class loader to use, or <code>null</code>
* to revert to the standard rules
*/
public void setClassLoader(ClassLoader classLoader) {
this.classLoader = classLoader;
}
/**
* Return the current depth of the element stack.
*/
public int getCount() {
return (stack.size());
}
/**
* Return the debugging detail level of this Digester.
*/
public int getDebug() {
return (this.debug);
}
/**
* Set the debugging detail level of this Digester.
*
* @param debug The new debugging detail level
*/
public void setDebug(int debug) {
this.debug = debug;
}
/**
* Return the error handler for this Digester.
*/
public ErrorHandler getErrorHandler() {
return (this.errorHandler);
}
/**
* Set the error handler for this Digester.
*
* @param errorHandler The new error handler
*/
public void setErrorHandler(ErrorHandler errorHandler) {
this.errorHandler = errorHandler;
}
/**
* Return the "namespace aware" flag for parsers we create.
*/
public boolean getNamespaceAware() {
return (this.namespaceAware);
}
/**
* Set the "namespace aware" flag for parsers we create.
*
* @param namespaceAware The new "namespace aware" flag
*/
public void setNamespaceAware(boolean namespaceAware) {
this.namespaceAware = namespaceAware;
}
/**
* Return the public identifier of the DTD we are currently
* parsing under, if any.
*/
public String getPublicId() {
return (this.publicId);
}
/**
* Return the namespace URI that will be applied to all subsequently
* added <code>Rule</code> objects.
*/
public String getRuleNamespaceURI() {
return (getRules().getNamespaceURI());
}
/**
* Set the namespace URI that will be applied to all subsequently
* added <code>Rule</code> objects.
*
* @param ruleNamespaceURI Namespace URI that must match on all
* subsequently added rules, or <code>null</code> for matching
* regardless of the current namespace URI
*/
public void setRuleNamespaceURI(String ruleNamespaceURI) {
getRules().setNamespaceURI(ruleNamespaceURI);
}
/**
* Return the SAXParser we will use to parse the input stream. If there
* is a problem creating the parser, return <code>null</code>.
*/
public SAXParser getParser() {
// Return the parser we already created (if any)
if (parser != null)
return (parser);
// Create and return a new parser
synchronized (this) {
try {
if (factory == null)
factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(namespaceAware);
factory.setValidating(validating);
parser = factory.newSAXParser();
return (parser);
} catch (Exception e) {
log("Digester.getParser: ", e);
return (null);
}
}
}
/**
* By setting the reader in the constructor, you can bypass JAXP and be able
* to use digester in Weblogic 6.0.
*/
public synchronized XMLReader getReader() {
if (reader == null) {
try {
reader = getParser().getXMLReader();
} catch (SAXException se) {
return null;
}
}
//set up the parse
reader.setContentHandler(this);
reader.setDTDHandler(this);
reader.setEntityResolver(this);
reader.setErrorHandler(this);
return reader;
}
/**
* Return the <code>Rules</code> implementation object containing our
* rules collection and associated matching policy. If none has been
* established, a default implementation will be created and returned.
*/
public Rules getRules() {
if (this.rules == null) {
this.rules = new RulesBase();
this.rules.setDigester(this);
}
return (this.rules);
}
/**
* Set the <code>Rules</code> implementation object containing our
* rules collection and associated matching policy.
*
* @param rules New Rules implementation
*/
public void setRules(Rules rules) {
this.rules = rules;
this.rules.setDigester(this);
}
/**
* Return the validating parser flag.
*/
public boolean getValidating() {
return (this.validating);
}
/**
* Set the validating parser flag. This must be called before
* <code>parse()</code> is called the first time.
*
* @param validating The new validating parser flag.
*/
public void setValidating(boolean validating) {
this.validating = validating;
}
/**
* Return the logging writer for this Digester.
*/
public PrintWriter getWriter() {
return (this.writer);
}
/**
* Set the logging writer for this Digester.
*
* @param writer The new PrintWriter, or <code>null</code> for
* <code>System.out</code>.
*/
public void setWriter(PrintWriter writer) {
this.writer = writer;
}
/**
* Return the boolean as to whether the context classloader should be used.
*/
public boolean getUseContextClassLoader() {
return useContextClassLoader;
}
/**
* Determine whether to use the Context ClassLoader (the one found by
* calling <code>Thread.currentThread().getContextClassLoader()</code>)
* to resolve/load classes that are defined in various rules. If not
* using Context ClassLoader, then the class-loading defaults to
* using the calling-class' ClassLoader.
*
* @param boolean determines whether to use Context ClassLoader.
*/
public void setUseContextClassLoader(boolean use) {
useContextClassLoader = use;
}
/**
* Process notification of character data received from the body of
* an XML element.
*
* @param buffer The characters from the XML document
* @param start Starting offset into the buffer
* @param length Number of characters from the buffer
*
* @exception SAXException if a parsing error is to be reported
*/
public void characters(char buffer[], int start, int length)
throws SAXException {
if (debug >= 3)
log("characters(" + new String(buffer, start, length) + ")");
bodyText.append(buffer, start, length);
}
/**
* Process notification of the end of the document being reached.
*
* @exception SAXException if a parsing error is to be reported
*/
public void endDocument() throws SAXException {
if (debug >= 3)
log("endDocument()");
if (getCount() > 1)
log("endDocument(): " + getCount() + " elements left");
while (getCount() > 1)
pop();
// Fire "finish" events for all defined rules
Iterator rules = getRules().rules().iterator();
while (rules.hasNext()) {
Rule rule = (Rule) rules.next();
try {
rule.finish();
} catch (Exception e) {
log("Finish event threw exception", e);
throw createSAXException(e);
} catch (Throwable t) {
log("Finish event threw exception", t);
throw createSAXException(t.getMessage());
}
}
// Perform final cleanup
clear();
}
/**
* Process notification of the end of an XML element being reached.
*
* @param uri - The Namespace URI, or the empty string if the
* element has no Namespace URI or if Namespace processing is not
* being performed.
* @param localName - The local name (without prefix), or the empty
* string if Namespace processing is not being performed.
* @param qName - The qualified XML 1.0 name (with prefix), or the
* empty string if qualified names are not available.
* @exception SAXException if a parsing error is to be reported
*/
public void endElement(String namespaceURI, String localName,
String qName) throws SAXException {
if (debug >= 3) {
log("endElement(" + namespaceURI + "," + localName +
"," + qName + ")");
log(" match='" + match + "'");
log(" bodyText='" + bodyText + "'");
}
// Fire "body" events for all relevant rules
List rules = getRules().match(namespaceURI, match);
if ((rules != null) && (rules.size() > 0)) {
String bodyText = this.bodyText.toString().trim();
for (int i = 0; i < rules.size(); i++) {
try {
Rule rule = (Rule) rules.get(i);
if (debug >= 4)
log(" Fire body() for " + rule);
rule.body(bodyText);
} catch (Exception e) {
log("Body event threw exception", e);
throw createSAXException(e);
} catch (Throwable t) {
log("Body event threw exception", t);
throw createSAXException(t.getMessage());
}
}
} else {
if (debug >= 3)
log(" No rules found matching '" + match + "'.");
}
// Recover the body text from the surrounding element
bodyText = new StringBuffer((String) bodyTexts.pop());
if (debug >= 4)
log(" Popping body text '" + bodyText.toString() + "'");
// Fire "end" events for all relevant rules in reverse order
if (rules != null) {
for (int i = 0; i < rules.size(); i++) {
int j = (rules.size() - i) - 1;
try {
Rule rule = (Rule) rules.get(j);
if (debug >= 4)
log(" Fire end() for " + rule);
rule.end();
} catch (Exception e) {
log("End event threw exception", e);
throw createSAXException(e);
} catch (Throwable t) {
log("End event threw exception", t);
throw createSAXException(t.getMessage());
}
}
}
// Recover the previous match expression
int slash = match.lastIndexOf('/');
if (slash >= 0)
match = match.substring(0, slash);
else
match = "";
}
/**
* Process notification that a namespace prefix is going out of scope.
*
* @param prefix Prefix that is going out of scope
*
* @exception SAXException if a parsing error is to be reported
*/
public void endPrefixMapping(String prefix) throws SAXException {
if (debug >= 3)
log("endPrefixMapping(" + prefix + ")");
// Deregister this prefix mapping
ArrayStack stack = (ArrayStack) namespaces.get(prefix);
if (stack == null)
return;
try {
stack.pop();
if (stack.empty())
namespaces.remove(prefix);
} catch (EmptyStackException e) {
throw createSAXException("endPrefixMapping popped too many times");
}
}
/**
* Process notification of ignorable whitespace received from the body of
* an XML element.
*
* @param buffer The characters from the XML document
* @param start Starting offset into the buffer
* @param length Number of characters from the buffer
*
* @exception SAXException if a parsing error is to be reported
*/
public void ignorableWhitespace(char buffer[], int start, int len)
throws SAXException {
if (debug >= 3)
log("ignorableWhitespace(" +
new String(buffer, start, len) + ")");
; // No processing required
}
/**
* Process notification of a processing instruction that was encountered.
*
* @param target The processing instruction target
* @param data The processing instruction data (if any)
*
* @exception SAXException if a parsing error is to be reported
*/
public void processingInstruction(String target, String data)
throws SAXException {
if (debug >= 3)
log("processingInstruction('" + target + "','" + data + "')");
; // No processing is required
}
/**
* Set the document locator associated with our parser.
*
* @param locator The new locator
*/
public void setDocumentLocator(Locator locator) {
if (debug >= 3)
log("setDocumentLocator(" + locator + ")");
this.locator = locator;
}
/**
* Process notification of a skipped entity.
*
* @param name Name of the skipped entity
*
* @exception SAXException if a parsing error is to be reported
*/
public void skippedEntity(String name) throws SAXException {
if (debug >= 3)
log("skippedEntity(" + name + ")");
; // No processing required
}
/**
* Process notification of the beginning of the document being reached.
*
* @exception SAXException if a parsing error is to be reported
*/
public void startDocument() throws SAXException {
if (debug >= 3)
log("startDocument()");
; // No processing required
}
/**
* Process notification of the start of an XML element being reached.
*
* @param uri The Namespace URI, or the empty string if the element
* has no Namespace URI or if Namespace processing is not being performed.
* @param localName The local name (without prefix), or the empty
* string if Namespace processing is not being performed.
* @param qName The qualified name (with prefix), or the empty
* string if qualified names are not available.\
* @param list The attributes attached to the element. If there are
* no attributes, it shall be an empty Attributes object.
* @exception SAXException if a parsing error is to be reported
*/
public void startElement(String namespaceURI, String localName,
String qName, Attributes list)
throws SAXException {
if (debug >= 3)
log("startElement(" + namespaceURI + "," + localName + "," +
qName + ")");
// Save the body text accumulated for our surrounding element
bodyTexts.push(bodyText.toString());
if (debug >= 4)
log(" Pushing body text '" + bodyText.toString() + "'");
bodyText.setLength(0);
// Compute the current matching rule
StringBuffer sb = new StringBuffer(match);
if (match.length() > 0)
sb.append('/');
if ((localName == null) || (localName.length() < 1))
sb.append(qName);
else
sb.append(localName);
match = sb.toString();
if (debug >= 3)
log(" New match='" + match + "'");
// Fire "begin" events for all relevant rules
List rules = getRules().match(namespaceURI, match);
if ((rules != null) && (rules.size() > 0)) {
String bodyText = this.bodyText.toString();
for (int i = 0; i < rules.size(); i++) {
try {
Rule rule = (Rule) rules.get(i);
if (debug >= 4)
log(" Fire begin() for " + rule);
rule.begin(list);
} catch (Exception e) {
log("Begin event threw exception", e);
throw createSAXException(e);
} catch (Throwable t) {
log("Begin event threw exception", t);
throw createSAXException(t.getMessage());
}
}
} else {
if (debug >= 3)
log(" No rules found matching '" + match + "'.");
}
}
/**
* Process notification that a namespace prefix is coming in to scope.
*
* @param prefix Prefix that is being declared
* @param namespaceURI Corresponding namespace URI being mapped to
*
* @exception SAXException if a parsing error is to be reported
*/
public void startPrefixMapping(String prefix, String namespaceURI)
throws SAXException {
if (debug >= 3)
log("startPrefixMapping(" + prefix + "," + namespaceURI + ")");
// Register this prefix mapping
ArrayStack stack = (ArrayStack) namespaces.get(prefix);
if (stack == null) {
stack = new ArrayStack();
namespaces.put(prefix, stack);
}
stack.push(namespaceURI);
}
/**
* Receive notification of a notation declaration event.
*
* @param name The notation name
* @param publicId The public identifier (if any)
* @param systemId The system identifier (if any)
*/
public void notationDecl(String name, String publicId, String systemId) {
if (debug >= 3)
log("notationDecl(" + name + "," + publicId + "," +
systemId + ")");
}
/**
* Receive notification of an unparsed entity declaration event.
*
* @param name The unparsed entity name
* @param publicId The public identifier (if any)
* @param systemId The system identifier (if any)
* @param notation The name of the associated notation
*/
public void unparsedEntityDecl(String name, String publicId,
String systemId, String notation) {
if (debug >= 3)
log("unparsedEntityDecl(" + name + "," + publicId + "," +
systemId + "," + notation + ")");
}
/**
* Resolve the requested external entity.
*
* @param publicId The public identifier of the entity being referenced
* @param systemId The system identifier of the entity being referenced
*
* @exception SAXException if a parsing exception occurs
*/
public InputSource resolveEntity(String publicId, String systemId)
throws SAXException {
if (debug >= 1)
log("resolveEntity('" + publicId + "', '" + systemId + "')");
this.publicId = publicId;
// Has this system identifier been registered?
String dtdURL = null;
if (publicId != null)
dtdURL = (String) dtds.get(publicId);
if (dtdURL == null) {
if (debug >= 1)
log(" Not registered, use system identifier");
return (null);
}
// Return an input source to our alternative URL
if (debug >= 1)
log(" Resolving to alternate DTD '" + dtdURL + "'");
try {
URL url = new URL(dtdURL);
InputStream stream = url.openStream();
return (new InputSource(stream));
} catch (Exception e) {
throw createSAXException(e);
}
}
/**
* Forward notification of a parsing error to the application supplied
* error handler (if any).
*
* @param exception The error information
*
* @exception SAXException if a parsing exception occurs
*/
public void error(SAXParseException exception) throws SAXException {
log("Parse Error at line " + exception.getLineNumber() +
" column " + exception.getColumnNumber() + ": " +
exception.getMessage(), exception);
if (errorHandler != null)
errorHandler.error(exception);
}
/**
* Forward notification of a fatal parsing error to the application
* supplied error handler (if any).
*
* @param exception The fatal error information
*
* @exception SAXException if a parsing exception occurs
*/
public void fatalError(SAXParseException exception) throws SAXException {
log("Parse Fatal Error at line " + exception.getLineNumber() +
" column " + exception.getColumnNumber() + ": " +
exception.getMessage(), exception);
if (errorHandler != null)
errorHandler.fatalError(exception);
}
/**
* Forward notification of a parse warning to the application supplied
* error handler (if any).
*
* @param exception The warning information
*
* @exception SAXException if a parsing exception occurs
*/
public void warning(SAXParseException exception) throws SAXException {
log("Parse Warning at line " + exception.getLineNumber() +
" column " + exception.getColumnNumber() + ": " +
exception.getMessage(), exception);
if (errorHandler != null)
errorHandler.warning(exception);
}
/**
* Log a message to the log writer associated with this context.
*
* @param message The message to be logged
*/
public void log(String message) {
if (writer == null)
System.out.println(message);
else
writer.println(message);
}
/**
* Log a message and associated exception to the log writer
* associated with this context.
*
* @param message The message to be logged
* @param exception The associated exception to be logged
*/
public void log(String message, Throwable exception) {
if (writer == null) {
System.out.println(message);
exception.printStackTrace(System.out);
} else {
writer.println(message);
exception.printStackTrace(writer);
}
}
/**
* Parse the content of the specified file using this Digester. Returns
* the root element from the object stack (if any).
*
* @param file File containing the XML data to be parsed
*
* @exception IOException if an input/output error occurs
* @exception SAXException if a parsing exception occurs
*/
public Object parse(File file) throws IOException, SAXException {
configure();
getReader().parse(new InputSource(new FileReader(file)));
return (root);
}
/**
* Parse the content of the specified input source using this Digester.
* Returns the root element from the object stack (if any).
*
* @param input Input source containing the XML data to be parsed
*
* @exception IOException if an input/output error occurs
* @exception SAXException if a parsing exception occurs
*/
public Object parse(InputSource input) throws IOException, SAXException {
configure();
getReader().parse(input);
return (root);
}
/**
* Parse the content of the specified input stream using this Digester.
* Returns the root element from the object stack (if any).
*
* @param input Input stream containing the XML data to be parsed
*
* @exception IOException if an input/output error occurs
* @exception SAXException if a parsing exception occurs
*/
public Object parse(InputStream input) throws IOException, SAXException {
configure();
getReader().parse(new InputSource(input));
return (root);
}
/**
* Parse the content of the specified URI using this Digester.
* Returns the root element from the object stack (if any).
*
* @param uri URI containing the XML data to be parsed
*
* @exception IOException if an input/output error occurs
* @exception SAXException if a parsing exception occurs
*/
public Object parse(String uri) throws IOException, SAXException {
configure();
getReader().parse(uri);
return (root);
}
/**
* Register the specified DTD URL for the specified public identifier.
* This must be called before the first call to <code>parse()</code>.
*
* @param publicId Public identifier of the DTD to be resolved
* @param dtdURL The URL to use for reading this DTD
*/
public void register(String publicId, String dtdURL) {
if (debug >= 1)
log("register('" + publicId + "', '" + dtdURL + "'");
dtds.put(publicId, dtdURL);
}
/**
* Register a new Rule matching the specified pattern.
*
* @param pattern Element matching pattern
* @param rule Rule to be registered
*/
public void addRule(String pattern, Rule rule) {
getRules().add(pattern, rule);
}
/**
* Register a set of Rule instances defined in a RuleSet.
*
* @param ruleSet The RuleSet instance to configure from
*/
public void addRuleSet(RuleSet ruleSet) {
String oldNamespaceURI = getRuleNamespaceURI();
String newNamespaceURI = ruleSet.getNamespaceURI();
if (debug >= 3) {
if (newNamespaceURI == null)
log("addRuleSet() with no namespace URI");
else
log("addRuleSet() with namespace URI " + newNamespaceURI);
}
setRuleNamespaceURI(newNamespaceURI);
ruleSet.addRuleInstances(this);
setRuleNamespaceURI(oldNamespaceURI);
}
/**
* Add a "bean property setter" rule for the specified parameters.
*
* @param pattern Element matching pattern
*/
public void addBeanPropertySetter(String pattern) {
addRule(pattern,
new BeanPropertySetterRule(this));
}
/**
* Add a "bean property setter" rule for the specified parameters.
*
* @param pattern Element matching pattern
* @param propertyName Name of property to set
*/
public void addBeanPropertySetter(String pattern,
String propertyName) {
addRule(pattern,
new BeanPropertySetterRule(this, propertyName));
}
/**
* Add an "call method" rule for the specified parameters.
*
* @param pattern Element matching pattern
* @param methodName Method name to be called
* @param paramCount Number of expected parameters (or zero
* for a single parameter from the body of this element)
*/
public void addCallMethod(String pattern, String methodName,
int paramCount) {
addRule(pattern,
new CallMethodRule(this, methodName, paramCount));
}
/**
* Add an "call method" rule for the specified parameters.
*
* @param pattern Element matching pattern
* @param methodName Method name to be called
* @param paramCount Number of expected parameters (or zero
* for a single parameter from the body of this element)
* @param paramTypes Set of Java class names for the types
* of the expected parameters
* (if you wish to use a primitive type, specify the corresonding
* Java wrapper class instead, such as <code>java.lang.Boolean</code>
* for a <code>boolean</code> parameter)
*/
public void addCallMethod(String pattern, String methodName,
int paramCount, String paramTypes[]) {
addRule(pattern,
new CallMethodRule(this, methodName,
paramCount, paramTypes));
}
/**
* Add an "call method" rule for the specified parameters.
*
* @param pattern Element matching pattern
* @param methodName Method name to be called
* @param paramCount Number of expected parameters (or zero
* for a single parameter from the body of this element)
* @param paramTypes The Java class names of the arguments
* (if you wish to use a primitive type, specify the corresonding
* Java wrapper class instead, such as <code>java.lang.Boolean</code>
* for a <code>boolean</code> parameter)
*/
public void addCallMethod(String pattern, String methodName,
int paramCount, Class paramTypes[]) {
addRule(pattern,
new CallMethodRule(this, methodName,
paramCount, paramTypes));
}
/**
* Add a "call parameter" rule for the specified parameters.
*
* @param pattern Element matching pattern
* @param paramIndex Zero-relative parameter index to set
* (from the body of this element)
*/
public void addCallParam(String pattern, int paramIndex) {
addRule(pattern,
new CallParamRule(this, paramIndex));
}
/**
* Add a "call parameter" rule for the specified parameters.
*
* @param pattern Element matching pattern
* @param paramIndex Zero-relative parameter index to set
* (from the specified attribute)
* @param attributeName Attribute whose value is used as the
* parameter value
*/
public void addCallParam(String pattern, int paramIndex,
String attributeName) {
addRule(pattern,
new CallParamRule(this, paramIndex, attributeName));
}
/**
* Add a "factory create" rule for the specified parameters.
*
* @param pattern Element matching pattern
* @param className Java class name of the object creation factory class
*/
public void addFactoryCreate(String pattern, String className) {
addRule(pattern,
new FactoryCreateRule(this, className));
}
/**
* Add a "factory create" rule for the specified parameters.
*
* @param pattern Element matching pattern
* @param className Java class name of the object creation factory class
* @param attributeName Attribute name which, if present, overrides the
* value specified by <code>className</code>
*/
public void addFactoryCreate(String pattern, String className,
String attributeName) {
addRule(pattern,
new FactoryCreateRule(this, className, attributeName));
}
/**
* Add a "factory create" rule for the specified parameters.
*
* @param pattern Element matching pattern
* @param creationFactory Previously instantiated ObjectCreationFactory
* to be utilized
*/
public void addFactoryCreate(String pattern,
ObjectCreationFactory creationFactory) {
addRule(pattern,
new FactoryCreateRule(this, creationFactory));
}
/**
* Add an "object create" rule for the specified parameters.
*
* @param pattern Element matching pattern
* @param className Java class name to be created
*/
public void addObjectCreate(String pattern, String className) {
addRule(pattern,
new ObjectCreateRule(this, className));
}
/**
* Add an "object create" rule for the specified parameters.
*
* @param pattern Element matching pattern
* @param className Default Java class name to be created
* @param attributeName Attribute name that optionally overrides
* the default Java class name to be created
*/
public void addObjectCreate(String pattern, String className,
String attributeName) {
addRule(pattern,
new ObjectCreateRule(this, className, attributeName));
}
/**
* Add a "set next" rule for the specified parameters.
*
* @param pattern Element matching pattern
* @param methodName Method name to call on the parent element
*/
public void addSetNext(String pattern, String methodName) {
addRule(pattern,
new SetNextRule(this, methodName));
}
/**
* Add a "set next" rule for the specified parameters.
*
* @param pattern Element matching pattern
* @param methodName Method name to call on the parent element
* @param paramType Java class name of the expected parameter type
* (if you wish to use a primitive type, specify the corresonding
* Java wrapper class instead, such as <code>java.lang.Boolean</code>
* for a <code>boolean</code> parameter)
*/
public void addSetNext(String pattern, String methodName,
String paramType) {
addRule(pattern,
new SetNextRule(this, methodName, paramType));
}
/**
* Add a "set properties" rule for the specified parameters.
*
* @param pattern Element matching pattern
*/
public void addSetProperties(String pattern) {
addRule(pattern,
new SetPropertiesRule(this));
}
/**
* Add a "set property" rule for the specified parameters.
*
* @param pattern Element matching pattern
* @param name Attribute name containing the property name to be set
* @param value Attribute name containing the property value to set
*/
public void addSetProperty(String pattern, String name, String value) {
addRule(pattern,
new SetPropertyRule(this, name, value));
}
/**
* Add a "set top" rule for the specified parameters.
*
* @param pattern Element matching pattern
* @param methodName Method name to call on the parent element
*/
public void addSetTop(String pattern, String methodName) {
addRule(pattern,
new SetTopRule(this, methodName));
}
/**
* Add a "set top" rule for the specified parameters.
*
* @param pattern Element matching pattern
* @param methodName Method name to call on the parent element
* @param paramType Java class name of the expected parameter type
* (if you wish to use a primitive type, specify the corresonding
* Java wrapper class instead, such as <code>java.lang.Boolean</code>
* for a <code>boolean</code> parameter)
*/
public void addSetTop(String pattern, String methodName,
String paramType) {
addRule(pattern,
new SetTopRule(this, methodName, paramType));
}
/**
* Clear the current contents of the object stack.
*/
public void clear() {
match = "";
bodyTexts.clear();
params.clear();
publicId = null;
stack.clear();
}
/**
* Return the top object on the stack without removing it. If there are
* no objects on the stack, return <code>null</code>.
*/
public Object peek() {
try {
return (stack.peek());
} catch (EmptyStackException e) {
if (debug >= 1)
log("Empty stack (returning null)");
return (null);
}
}
/**
* Return the n'th object down the stack, where 0 is the top element
* and [getCount()-1] is the bottom element. If the specified index
* is out of range, return <code>null</code>.
*
* @param n Index of the desired element, where 0 is the top of the stack,
* 1 is the next element down, and so on.
*/
public Object peek(int n) {
try {
return (stack.peek(n));
} catch (EmptyStackException e) {
if (debug >= 1)
log("Empty stack (returning null)");
return (null);
}
}
/**
* Pop the top object off of the stack, and return it. If there are
* no objects on the stack, return <code>null</code>.
*/
public Object pop() {
try {
return (stack.pop());
} catch (EmptyStackException e) {
if (debug >= 1)
log("Empty stack (returning null)");
return (null);
}
}
/**
* Push a new object onto the top of the object stack.
*
* @param object The new object
*/
public void push(Object object) {
if (stack.size() == 0)
root = object;
stack.push(object);
}
/**
* Provide a hook for lazy configuration of this <code>Digester</code>
* instance. The default implementation does nothing, but subclasses
* can override as needed.
*/
protected void configure() {
// Do not configure more than once
if (configured)
return;
// Perform lazy configuration as needed
; // Nothing required by default
// Set the configuration flag to avoid repeating
configured = true;
}
/**
* Return the set of DTD URL registrations, keyed by public identifier.
*/
Map getRegistrations() {
return (dtds);
}
/**
* Return the set of rules that apply to the specified match position.
* The selected rules are those that match exactly, or those rules
* that specify a suffix match and the tail of the rule matches the
* current match position. Exact matches have precedence over
* suffix matches, then (among suffix matches) the longest match
* is preferred.
*
* @param match The current match position
*
* @deprecated Call <code>match()</code> on the <code>Rules</code>
* implementation returned by <code>getRules()</code>
*/
List getRules(String match) {
return (getRules().match(match));
}
/**
* Return the top object on the stack without removing it. If there are
* no objects on the stack, return <code>null</code>.
*/
Object peekParams() {
try {
return (params.peek());
} catch (EmptyStackException e) {
return (null);
}
}
/**
* Return the n'th object down the stack, where 0 is the top element
* and [getCount()-1] is the bottom element. If the specified index
* is out of range, return <code>null</code>.
*
* @param n Index of the desired element, where 0 is the top of the stack,
* 1 is the next element down, and so on.
*/
Object peekParams(int n) {
try {
return (params.peek(n));
} catch (EmptyStackException e) {
return (null);
}
}
/**
* Pop the top object off of the stack, and return it. If there are
* no objects on the stack, return <code>null</code>.
*/
Object popParams() {
try {
return (params.pop());
} catch (EmptyStackException e) {
return (null);
}
}
/**
* Push a new object onto the top of the object stack.
*
* @param object The new object
*/
void pushParams(Object object) {
params.push(object);
}
/**
* Create a SAX exception which also understands about the location in
* the digester file where the exception occurs
*
* @return the new exception
*/
protected SAXException createSAXException(String message, Exception e) {
if ( locator != null ) {
String error = "Error at (" + locator.getLineNumber() + ", "
+ locator.getColumnNumber() + ": " + message;
if ( e != null ) {
return new SAXParseException( error, locator, e );
}
else {
return new SAXParseException( error, locator );
}
}
System.out.println( "No Locator!" );
if ( e != null ) {
return new SAXException(message, e);
}
else {
return new SAXException(message);
}
}
/**
* Create a SAX exception which also understands about the location in
* the digester file where the exception occurs
*
* @return the new exception
*/
protected SAXException createSAXException(Exception e) {
return createSAXException(e.getMessage(), e);
}
/**
* Create a SAX exception which also understands about the location in
* the digester file where the exception occurs
*
* @return the new exception
*/
protected SAXException createSAXException(String message) {
return createSAXException(message, null);
}
}
|
package org.apache.commons.digester;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.lang.reflect.InvocationTargetException;
import java.util.EmptyStackException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.apache.commons.collections.ArrayStack;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.xml.sax.Attributes;
import org.xml.sax.EntityResolver;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
public class Digester extends DefaultHandler {
/**
* Construct a new Digester with default properties.
*/
public Digester() {
super();
}
/**
* Construct a new Digester, allowing a SAXParser to be passed in. This
* allows Digester to be used in environments which are unfriendly to
* JAXP1.1 (such as WebLogic 6.0). Thanks for the request to change go to
* James House (james@interobjective.com). This may help in places where
* you are able to load JAXP 1.1 classes yourself.
*/
public Digester(SAXParser parser) {
super();
this.parser = parser;
}
/**
* Construct a new Digester, allowing an XMLReader to be passed in. This
* allows Digester to be used in environments which are unfriendly to
* JAXP1.1 (such as WebLogic 6.0). Note that if you use this option you
* have to configure namespace and validation support yourself, as these
* properties only affect the SAXParser and emtpy constructor.
*/
public Digester(XMLReader reader) {
super();
this.reader = reader;
}
/**
* The body text of the current element.
*/
protected StringBuffer bodyText = new StringBuffer();
/**
* The stack of body text string buffers for surrounding elements.
*/
protected ArrayStack bodyTexts = new ArrayStack();
/**
* The class loader to use for instantiating application objects.
* If not specified, the context class loader, or the class loader
* used to load Digester itself, is used, based on the value of the
* <code>useContextClassLoader</code> variable.
*/
protected ClassLoader classLoader = null;
/**
* Has this Digester been configured yet.
*/
protected boolean configured = false;
/**
* The EntityResolver used by the SAX parser. By default it use this class
*/
protected EntityResolver entityResolver;
/**
* The URLs of entityValidator that have been registered, keyed by the public
* identifier that corresponds.
*/
protected HashMap entityValidator = new HashMap();
/**
* The application-supplied error handler that is notified when parsing
* warnings, errors, or fatal errors occur.
*/
protected ErrorHandler errorHandler = null;
/**
* The SAXParserFactory that is created the first time we need it.
*/
protected SAXParserFactory factory = null;
/**
* The JAXP 1.2 property required to set up the schema location.
*/
private static final String JAXP_SCHEMA_SOURCE =
"http://java.sun.com/xml/jaxp/properties/schemaSource";
/**
* The JAXP 1.2 property to set up the schemaLanguage used.
*/
protected String JAXP_SCHEMA_LANGUAGE =
"http://java.sun.com/xml/jaxp/properties/schemaLanguage";
/**
* The Locator associated with our parser.
*/
protected Locator locator = null;
/**
* The current match pattern for nested element processing.
*/
protected String match = "";
/**
* Do we want a "namespace aware" parser.
*/
protected boolean namespaceAware = false;
/**
* Registered namespaces we are currently processing. The key is the
* namespace prefix that was declared in the document. The value is an
* ArrayStack of the namespace URIs this prefix has been mapped to --
* the top Stack element is the most current one. (This architecture
* is required because documents can declare nested uses of the same
* prefix for different Namespace URIs).
*/
protected HashMap namespaces = new HashMap();
/**
* The parameters stack being utilized by CallMethodRule and
* CallParamRule rules.
*/
protected ArrayStack params = new ArrayStack();
/**
* The SAXParser we will use to parse the input stream.
*/
protected SAXParser parser = null;
/**
* The public identifier of the DTD we are currently parsing under
* (if any).
*/
protected String publicId = null;
/**
* The XMLReader used to parse digester rules.
*/
protected XMLReader reader = null;
/**
* The "root" element of the stack (in other words, the last object
* that was popped.
*/
protected Object root = null;
/**
* The <code>Rules</code> implementation containing our collection of
* <code>Rule</code> instances and associated matching policy. If not
* established before the first rule is added, a default implementation
* will be provided.
*/
protected Rules rules = null;
/**
* The XML schema language to use for validating an XML instance. By
* default this value is set to <code>W3C_XML_SCHEMA</code>
*/
protected String schemaLanguage = W3C_XML_SCHEMA;
/**
* The XML schema to use for validating an XML instance.
*/
protected String schemaLocation = null;
/**
* The object stack being constructed.
*/
protected ArrayStack stack = new ArrayStack();
/**
* Do we want to use the Context ClassLoader when loading classes
* for instantiating new objects. Default is <code>false</code>.
*/
protected boolean useContextClassLoader = false;
/**
* Do we want to use a validating parser.
*/
protected boolean validating = false;
/**
* The Log to which most logging calls will be made.
*/
protected Log log =
LogFactory.getLog("org.apache.commons.digester.Digester");
/**
* The Log to which all SAX event related logging calls will be made.
*/
protected Log saxLog =
LogFactory.getLog("org.apache.commons.digester.Digester.sax");
/**
* The schema language supported. By default, we use this one.
*/
protected static final String W3C_XML_SCHEMA =
"http:
/**
* Return the currently mapped namespace URI for the specified prefix,
* if any; otherwise return <code>null</code>. These mappings come and
* go dynamically as the document is parsed.
*
* @param prefix Prefix to look up
*/
public String findNamespaceURI(String prefix) {
ArrayStack stack = (ArrayStack) namespaces.get(prefix);
if (stack == null) {
return (null);
}
try {
return ((String) stack.peek());
} catch (EmptyStackException e) {
return (null);
}
}
/**
* Return the class loader to be used for instantiating application objects
* when required. This is determined based upon the following rules:
* <ul>
* <li>The class loader set by <code>setClassLoader()</code>, if any</li>
* <li>The thread context class loader, if it exists and the
* <code>useContextClassLoader</code> property is set to true</li>
* <li>The class loader used to load the Digester class itself.
* </ul>
*/
public ClassLoader getClassLoader() {
if (this.classLoader != null) {
return (this.classLoader);
}
if (this.useContextClassLoader) {
ClassLoader classLoader =
Thread.currentThread().getContextClassLoader();
if (classLoader != null) {
return (classLoader);
}
}
return (this.getClass().getClassLoader());
}
/**
* Set the class loader to be used for instantiating application objects
* when required.
*
* @param classLoader The new class loader to use, or <code>null</code>
* to revert to the standard rules
*/
public void setClassLoader(ClassLoader classLoader) {
this.classLoader = classLoader;
}
/**
* Return the current depth of the element stack.
*/
public int getCount() {
return (stack.size());
}
/**
* Return the name of the XML element that is currently being processed.
*/
public String getCurrentElementName() {
String elementName = match;
int lastSlash = elementName.lastIndexOf('/');
if (lastSlash >= 0) {
elementName = elementName.substring(lastSlash + 1);
}
return (elementName);
}
/**
* Return the debugging detail level of our currently enabled logger.
*
* @deprecated Configure the logger using standard mechanisms
* for your implementation
*/
public int getDebug() {
return (0);
}
/**
* Set the debugging detail level of our currently enabled logger.
*
* @param debug New debugging detail level (0=off, increasing integers
* for more detail)
*
* @deprecated Configure the logger using standard mechanisms
* for your implementation
*/
public void setDebug(int debug) {
; // No action is taken
}
/**
* Return the error handler for this Digester.
*/
public ErrorHandler getErrorHandler() {
return (this.errorHandler);
}
/**
* Set the error handler for this Digester.
*
* @param errorHandler The new error handler
*/
public void setErrorHandler(ErrorHandler errorHandler) {
this.errorHandler = errorHandler;
}
/**
* Return the SAXParserFactory we will use, creating one if necessary.
*/
public SAXParserFactory getFactory() {
if (factory == null) {
factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(namespaceAware);
factory.setValidating(validating);
}
return (factory);
}
public boolean getFeature(String feature)
throws ParserConfigurationException, SAXNotRecognizedException,
SAXNotSupportedException {
return (getFactory().getFeature(feature));
}
public void setFeature(String feature, boolean value)
throws ParserConfigurationException, SAXNotRecognizedException,
SAXNotSupportedException {
getFactory().setFeature(feature, value);
}
/**
* Return the current Logger associated with this instance of the Digester
*/
public Log getLogger() {
return log;
}
/**
* Set the current logger for this Digester.
*/
public void setLogger(Log log) {
this.log = log;
}
/**
* Gets the logger used for logging SAX-related information.
* <strong>Note</strong> the output is finely grained.
*/
public Log getSAXLogger() {
return saxLog;
}
/**
* Sets the logger used for logging SAX-related information.
* <strong>Note</strong> the output is finely grained.
* @param log Log, not null
*/
public void setSAXLogger(Log saxLog) {
this.saxLog = saxLog;
}
/**
* Return the current rule match path
*/
public String getMatch() {
return match;
}
/**
* Return the "namespace aware" flag for parsers we create.
*/
public boolean getNamespaceAware() {
return (this.namespaceAware);
}
/**
* Set the "namespace aware" flag for parsers we create.
*
* @param namespaceAware The new "namespace aware" flag
*/
public void setNamespaceAware(boolean namespaceAware) {
this.namespaceAware = namespaceAware;
}
/**
* Set the publid id of the current file being parse.
* @param publicId the DTD/Schema public's id.
*/
public void setPublicId(String publicId){
this.publicId = publicId;
}
/**
* Return the public identifier of the DTD we are currently
* parsing under, if any.
*/
public String getPublicId() {
return (this.publicId);
}
/**
* Return the namespace URI that will be applied to all subsequently
* added <code>Rule</code> objects.
*/
public String getRuleNamespaceURI() {
return (getRules().getNamespaceURI());
}
/**
* Set the namespace URI that will be applied to all subsequently
* added <code>Rule</code> objects.
*
* @param ruleNamespaceURI Namespace URI that must match on all
* subsequently added rules, or <code>null</code> for matching
* regardless of the current namespace URI
*/
public void setRuleNamespaceURI(String ruleNamespaceURI) {
getRules().setNamespaceURI(ruleNamespaceURI);
}
/**
* Return the SAXParser we will use to parse the input stream. If there
* is a problem creating the parser, return <code>null</code>.
*/
public SAXParser getParser() {
// Return the parser we already created (if any)
if (parser != null) {
return (parser);
}
// Create a new parser
try {
parser = getFactory().newSAXParser();
} catch (Exception e) {
log.error("Digester.getParser: ", e);
return (null);
}
// Configure standard properties and return the new instance
try {
if (schemaLocation != null) {
setProperty(JAXP_SCHEMA_LANGUAGE, schemaLanguage);
setProperty(JAXP_SCHEMA_SOURCE, schemaLocation);
}
} catch (Exception e) {
log.warn("" + e);
}
return (parser);
}
public Object getProperty(String property)
throws SAXNotRecognizedException, SAXNotSupportedException {
return (getParser().getProperty(property));
}
public void setProperty(String property, Object value)
throws SAXNotRecognizedException, SAXNotSupportedException {
getParser().setProperty(property, value);
}
/**
* By setting the reader in the constructor, you can bypass JAXP and
* be able to use digester in Weblogic 6.0.
*
* @deprecated Use getXMLReader() instead, which can throw a
* SAXException if the reader cannot be instantiated
*/
public XMLReader getReader() {
try {
return (getXMLReader());
} catch (SAXException e) {
log.error("Cannot get XMLReader", e);
return (null);
}
}
/**
* Return the <code>Rules</code> implementation object containing our
* rules collection and associated matching policy. If none has been
* established, a default implementation will be created and returned.
*/
public Rules getRules() {
if (this.rules == null) {
this.rules = new RulesBase();
this.rules.setDigester(this);
}
return (this.rules);
}
/**
* Set the <code>Rules</code> implementation object containing our
* rules collection and associated matching policy.
*
* @param rules New Rules implementation
*/
public void setRules(Rules rules) {
this.rules = rules;
this.rules.setDigester(this);
}
/**
* Return the XML Schema URI used for validating an XML instance.
*/
public String getSchema() {
return (this.schemaLocation);
}
/**
* Set the XML Schema URI used for validating a XML Instance.
*
* @param schemaLocation a URI to the schema.
*/
public void setSchema(String schemaLocation){
this.schemaLocation = schemaLocation;
}
/**
* Return the XML Schema language used when parsing.
*/
public String getSchemaLanguage() {
return (this.schemaLanguage);
}
/**
* Set the XML Schema language used when parsing. By default, we use W3C.
*
* @param schemaLanguage a URI to the schema language.
*/
public void setSchemaLanguage(String schemaLanguage){
this.schemaLanguage = schemaLanguage;
}
/**
* Return the boolean as to whether the context classloader should be used.
*/
public boolean getUseContextClassLoader() {
return useContextClassLoader;
}
/**
* Determine whether to use the Context ClassLoader (the one found by
* calling <code>Thread.currentThread().getContextClassLoader()</code>)
* to resolve/load classes that are defined in various rules. If not
* using Context ClassLoader, then the class-loading defaults to
* using the calling-class' ClassLoader.
*
* @param use determines whether to use Context ClassLoader.
*/
public void setUseContextClassLoader(boolean use) {
useContextClassLoader = use;
}
/**
* Return the validating parser flag.
*/
public boolean getValidating() {
return (this.validating);
}
/**
* Set the validating parser flag. This must be called before
* <code>parse()</code> is called the first time.
*
* @param validating The new validating parser flag.
*/
public void setValidating(boolean validating) {
this.validating = validating;
}
/**
* Return the XMLReader to be used for parsing the input document.
*
* FIX ME: there is a bug in JAXP/XERCES that prevent the use of a
* parser that contains a schema with a DTD.
* @exception SAXException if no XMLReader can be instantiated
*/
public XMLReader getXMLReader() throws SAXException {
if (reader == null){
reader = getParser().getXMLReader();
}
reader.setDTDHandler(this);
reader.setContentHandler(this);
if (entityResolver == null){
reader.setEntityResolver(this);
} else {
reader.setEntityResolver(entityResolver);
}
reader.setErrorHandler(this);
return reader;
}
/**
* Process notification of character data received from the body of
* an XML element.
*
* @param buffer The characters from the XML document
* @param start Starting offset into the buffer
* @param length Number of characters from the buffer
*
* @exception SAXException if a parsing error is to be reported
*/
public void characters(char buffer[], int start, int length)
throws SAXException {
if (saxLog.isDebugEnabled()) {
saxLog.debug("characters(" + new String(buffer, start, length) + ")");
}
bodyText.append(buffer, start, length);
}
/**
* Process notification of the end of the document being reached.
*
* @exception SAXException if a parsing error is to be reported
*/
public void endDocument() throws SAXException {
if (saxLog.isDebugEnabled()) {
if (getCount() > 1) {
saxLog.debug("endDocument(): " + getCount() +
" elements left");
} else {
saxLog.debug("endDocument()");
}
}
while (getCount() > 1) {
pop();
}
// Fire "finish" events for all defined rules
Iterator rules = getRules().rules().iterator();
while (rules.hasNext()) {
Rule rule = (Rule) rules.next();
try {
rule.finish();
} catch (Exception e) {
log.error("Finish event threw exception", e);
throw createSAXException(e);
} catch (Error e) {
log.error("Finish event threw error", e);
throw e;
}
}
// Perform final cleanup
clear();
}
/**
* Process notification of the end of an XML element being reached.
*
* @param namespaceURI - The Namespace URI, or the empty string if the
* element has no Namespace URI or if Namespace processing is not
* being performed.
* @param localName - The local name (without prefix), or the empty
* string if Namespace processing is not being performed.
* @param qName - The qualified XML 1.0 name (with prefix), or the
* empty string if qualified names are not available.
* @exception SAXException if a parsing error is to be reported
*/
public void endElement(String namespaceURI, String localName,
String qName) throws SAXException {
boolean debug = log.isDebugEnabled();
if (debug) {
if (saxLog.isDebugEnabled()) {
saxLog.debug("endElement(" + namespaceURI + "," + localName +
"," + qName + ")");
}
log.debug(" match='" + match + "'");
log.debug(" bodyText='" + bodyText + "'");
}
// the actual element name is either in localName or qName, depending
// on whether the parser is namespace aware
String name = localName;
if ((name == null) || (name.length() < 1)) {
name = qName;
}
// Fire "body" events for all relevant rules
List rules = getRules().match(namespaceURI, match);
if ((rules != null) && (rules.size() > 0)) {
String bodyText = this.bodyText.toString();
for (int i = 0; i < rules.size(); i++) {
try {
Rule rule = (Rule) rules.get(i);
if (debug) {
log.debug(" Fire body() for " + rule);
}
rule.body(namespaceURI, name, bodyText);
} catch (Exception e) {
log.error("Body event threw exception", e);
throw createSAXException(e);
} catch (Error e) {
log.error("Body event threw error", e);
throw e;
}
}
} else {
if (debug) {
log.debug(" No rules found matching '" + match + "'.");
}
}
// Recover the body text from the surrounding element
bodyText = (StringBuffer) bodyTexts.pop();
if (debug) {
log.debug(" Popping body text '" + bodyText.toString() + "'");
}
// Fire "end" events for all relevant rules in reverse order
if (rules != null) {
for (int i = 0; i < rules.size(); i++) {
int j = (rules.size() - i) - 1;
try {
Rule rule = (Rule) rules.get(j);
if (debug) {
log.debug(" Fire end() for " + rule);
}
rule.end(namespaceURI, name);
} catch (Exception e) {
log.error("End event threw exception", e);
throw createSAXException(e);
} catch (Error e) {
log.error("End event threw error", e);
throw e;
}
}
}
// Recover the previous match expression
int slash = match.lastIndexOf('/');
if (slash >= 0) {
match = match.substring(0, slash);
} else {
match = "";
}
}
/**
* Process notification that a namespace prefix is going out of scope.
*
* @param prefix Prefix that is going out of scope
*
* @exception SAXException if a parsing error is to be reported
*/
public void endPrefixMapping(String prefix) throws SAXException {
if (saxLog.isDebugEnabled()) {
saxLog.debug("endPrefixMapping(" + prefix + ")");
}
// Deregister this prefix mapping
ArrayStack stack = (ArrayStack) namespaces.get(prefix);
if (stack == null) {
return;
}
try {
stack.pop();
if (stack.empty())
namespaces.remove(prefix);
} catch (EmptyStackException e) {
throw createSAXException("endPrefixMapping popped too many times");
}
}
/**
* Process notification of ignorable whitespace received from the body of
* an XML element.
*
* @param buffer The characters from the XML document
* @param start Starting offset into the buffer
* @param len Number of characters from the buffer
*
* @exception SAXException if a parsing error is to be reported
*/
public void ignorableWhitespace(char buffer[], int start, int len)
throws SAXException {
if (saxLog.isDebugEnabled()) {
saxLog.debug("ignorableWhitespace(" +
new String(buffer, start, len) + ")");
}
; // No processing required
}
/**
* Process notification of a processing instruction that was encountered.
*
* @param target The processing instruction target
* @param data The processing instruction data (if any)
*
* @exception SAXException if a parsing error is to be reported
*/
public void processingInstruction(String target, String data)
throws SAXException {
if (saxLog.isDebugEnabled()) {
saxLog.debug("processingInstruction('" + target + "','" + data + "')");
}
; // No processing is required
}
/**
* Gets the document locator associated with our parser.
*
* @return the Locator supplied by the document parser
*/
public Locator getDocumentLocator() {
return locator;
}
/**
* Sets the document locator associated with our parser.
*
* @param locator The new locator
*/
public void setDocumentLocator(Locator locator) {
if (saxLog.isDebugEnabled()) {
saxLog.debug("setDocumentLocator(" + locator + ")");
}
this.locator = locator;
}
/**
* Process notification of a skipped entity.
*
* @param name Name of the skipped entity
*
* @exception SAXException if a parsing error is to be reported
*/
public void skippedEntity(String name) throws SAXException {
if (saxLog.isDebugEnabled()) {
saxLog.debug("skippedEntity(" + name + ")");
}
; // No processing required
}
/**
* Process notification of the beginning of the document being reached.
*
* @exception SAXException if a parsing error is to be reported
*/
public void startDocument() throws SAXException {
if (saxLog.isDebugEnabled()) {
saxLog.debug("startDocument()");
}
// ensure that the digester is properly configured, as
// the digester could be used as a SAX ContentHandler
// rather than via the parse() methods.
configure();
}
/**
* Process notification of the start of an XML element being reached.
*
* @param namespaceURI The Namespace URI, or the empty string if the element
* has no Namespace URI or if Namespace processing is not being performed.
* @param localName The local name (without prefix), or the empty
* string if Namespace processing is not being performed.
* @param qName The qualified name (with prefix), or the empty
* string if qualified names are not available.\
* @param list The attributes attached to the element. If there are
* no attributes, it shall be an empty Attributes object.
* @exception SAXException if a parsing error is to be reported
*/
public void startElement(String namespaceURI, String localName,
String qName, Attributes list)
throws SAXException {
boolean debug = log.isDebugEnabled();
if (saxLog.isDebugEnabled()) {
saxLog.debug("startElement(" + namespaceURI + "," + localName + "," +
qName + ")");
}
// Save the body text accumulated for our surrounding element
bodyTexts.push(bodyText);
if (debug) {
log.debug(" Pushing body text '" + bodyText.toString() + "'");
}
bodyText = new StringBuffer();
// the actual element name is either in localName or qName, depending
// on whether the parser is namespace aware
String name = localName;
if ((name == null) || (name.length() < 1)) {
name = qName;
}
// Compute the current matching rule
StringBuffer sb = new StringBuffer(match);
if (match.length() > 0) {
sb.append('/');
}
sb.append(name);
match = sb.toString();
if (debug) {
log.debug(" New match='" + match + "'");
}
// Fire "begin" events for all relevant rules
List rules = getRules().match(namespaceURI, match);
if ((rules != null) && (rules.size() > 0)) {
String bodyText = this.bodyText.toString();
for (int i = 0; i < rules.size(); i++) {
try {
Rule rule = (Rule) rules.get(i);
if (debug) {
log.debug(" Fire begin() for " + rule);
}
rule.begin(namespaceURI, name, list);
} catch (Exception e) {
log.error("Begin event threw exception", e);
throw createSAXException(e);
} catch (Error e) {
log.error("Begin event threw error", e);
throw e;
}
}
} else {
if (debug) {
log.debug(" No rules found matching '" + match + "'.");
}
}
}
/**
* Process notification that a namespace prefix is coming in to scope.
*
* @param prefix Prefix that is being declared
* @param namespaceURI Corresponding namespace URI being mapped to
*
* @exception SAXException if a parsing error is to be reported
*/
public void startPrefixMapping(String prefix, String namespaceURI)
throws SAXException {
if (saxLog.isDebugEnabled()) {
saxLog.debug("startPrefixMapping(" + prefix + "," + namespaceURI + ")");
}
// Register this prefix mapping
ArrayStack stack = (ArrayStack) namespaces.get(prefix);
if (stack == null) {
stack = new ArrayStack();
namespaces.put(prefix, stack);
}
stack.push(namespaceURI);
}
/**
* Receive notification of a notation declaration event.
*
* @param name The notation name
* @param publicId The public identifier (if any)
* @param systemId The system identifier (if any)
*/
public void notationDecl(String name, String publicId, String systemId) {
if (saxLog.isDebugEnabled()) {
saxLog.debug("notationDecl(" + name + "," + publicId + "," +
systemId + ")");
}
}
/**
* Receive notification of an unparsed entity declaration event.
*
* @param name The unparsed entity name
* @param publicId The public identifier (if any)
* @param systemId The system identifier (if any)
* @param notation The name of the associated notation
*/
public void unparsedEntityDecl(String name, String publicId,
String systemId, String notation) {
if (saxLog.isDebugEnabled()) {
saxLog.debug("unparsedEntityDecl(" + name + "," + publicId + "," +
systemId + "," + notation + ")");
}
}
/**
* Set the <code>EntityResolver</code> used by SAX when resolving
* public id and system id.
* This must be called before the first call to <code>parse()</code>.
* @param entityResolver a class that implement the <code>EntityResolver</code> interface.
*/
public void setEntityResolver(EntityResolver entityResolver){
this.entityResolver = entityResolver;
}
/**
* Return the Entity Resolver used by the SAX parser.
* @return Return the Entity Resolver used by the SAX parser.
*/
public EntityResolver getEntityResolver(){
return entityResolver;
}
/**
* Resolve the requested external entity.
*
* @param publicId The public identifier of the entity being referenced
* @param systemId The system identifier of the entity being referenced
*
* @exception SAXException if a parsing exception occurs
*
*/
public InputSource resolveEntity(String publicId, String systemId)
throws SAXException {
if (saxLog.isDebugEnabled()) {
saxLog.debug("resolveEntity('" + publicId + "', '" + systemId + "')");
}
if (publicId != null)
this.publicId = publicId;
// Has this system identifier been registered?
String entityURL = null;
if (publicId != null) {
entityURL = (String) entityValidator.get(publicId);
}
// Redirect the schema location to a local destination
if (schemaLocation != null && entityURL == null && systemId != null){
entityURL = (String)entityValidator.get(systemId);
}
if (entityURL == null) {
if (systemId == null) {
// cannot resolve
if (log.isDebugEnabled()) {
log.debug(" Cannot resolve entity: '" + entityURL + "'");
}
return (null);
} else {
// try to resolve using system ID
if (log.isDebugEnabled()) {
log.debug(" Trying to resolve using system ID '" + systemId + "'");
}
entityURL = systemId;
}
}
// Return an input source to our alternative URL
if (log.isDebugEnabled()) {
log.debug(" Resolving to alternate DTD '" + entityURL + "'");
}
try {
return (new InputSource(entityURL));
} catch (Exception e) {
throw createSAXException(e);
}
}
/**
* Forward notification of a parsing error to the application supplied
* error handler (if any).
*
* @param exception The error information
*
* @exception SAXException if a parsing exception occurs
*/
public void error(SAXParseException exception) throws SAXException {
log.error("Parse Error at line " + exception.getLineNumber() +
" column " + exception.getColumnNumber() + ": " +
exception.getMessage(), exception);
if (errorHandler != null) {
errorHandler.error(exception);
}
}
/**
* Forward notification of a fatal parsing error to the application
* supplied error handler (if any).
*
* @param exception The fatal error information
*
* @exception SAXException if a parsing exception occurs
*/
public void fatalError(SAXParseException exception) throws SAXException {
log.error("Parse Fatal Error at line " + exception.getLineNumber() +
" column " + exception.getColumnNumber() + ": " +
exception.getMessage(), exception);
if (errorHandler != null) {
errorHandler.fatalError(exception);
}
}
/**
* Forward notification of a parse warning to the application supplied
* error handler (if any).
*
* @param exception The warning information
*
* @exception SAXException if a parsing exception occurs
*/
public void warning(SAXParseException exception) throws SAXException {
if (errorHandler != null) {
log.warn("Parse Warning Error at line " + exception.getLineNumber() +
" column " + exception.getColumnNumber() + ": " +
exception.getMessage(), exception);
errorHandler.warning(exception);
}
}
/**
* Log a message to our associated logger.
*
* @param message The message to be logged
* @deprecated Call getLogger() and use it's logging methods
*/
public void log(String message) {
log.info(message);
}
/**
* Log a message and exception to our associated logger.
*
* @param message The message to be logged
* @deprecated Call getLogger() and use it's logging methods
*/
public void log(String message, Throwable exception) {
log.error(message, exception);
}
/**
* Parse the content of the specified file using this Digester. Returns
* the root element from the object stack (if any).
*
* @param file File containing the XML data to be parsed
*
* @exception IOException if an input/output error occurs
* @exception SAXException if a parsing exception occurs
*/
public Object parse(File file) throws IOException, SAXException {
configure();
InputSource input = new InputSource(new FileInputStream(file));
input.setSystemId("file://" + file.getAbsolutePath());
getXMLReader().parse(input);
return (root);
}
/**
* Parse the content of the specified input source using this Digester.
* Returns the root element from the object stack (if any).
*
* @param input Input source containing the XML data to be parsed
*
* @exception IOException if an input/output error occurs
* @exception SAXException if a parsing exception occurs
*/
public Object parse(InputSource input) throws IOException, SAXException {
configure();
getXMLReader().parse(input);
return (root);
}
/**
* Parse the content of the specified input stream using this Digester.
* Returns the root element from the object stack (if any).
*
* @param input Input stream containing the XML data to be parsed
*
* @exception IOException if an input/output error occurs
* @exception SAXException if a parsing exception occurs
*/
public Object parse(InputStream input) throws IOException, SAXException {
configure();
InputSource is = new InputSource(input);
getXMLReader().parse(is);
return (root);
}
/**
* Parse the content of the specified reader using this Digester.
* Returns the root element from the object stack (if any).
*
* @param reader Reader containing the XML data to be parsed
*
* @exception IOException if an input/output error occurs
* @exception SAXException if a parsing exception occurs
*/
public Object parse(Reader reader) throws IOException, SAXException {
configure();
InputSource is = new InputSource(reader);
getXMLReader().parse(is);
return (root);
}
/**
* Parse the content of the specified URI using this Digester.
* Returns the root element from the object stack (if any).
*
* @param uri URI containing the XML data to be parsed
*
* @exception IOException if an input/output error occurs
* @exception SAXException if a parsing exception occurs
*/
public Object parse(String uri) throws IOException, SAXException {
configure();
InputSource is = new InputSource(uri);
getXMLReader().parse(is);
return (root);
}
/**
* Register the specified DTD URL for the specified public identifier.
* This must be called before the first call to <code>parse()</code>.
*
* @param publicId Public identifier of the DTD to be resolved
* @param entityURL The URL to use for reading this DTD
*/
public void register(String publicId, String entityURL) {
if (log.isDebugEnabled()) {
log.debug("register('" + publicId + "', '" + entityURL + "'");
}
entityValidator.put(publicId, entityURL);
}
/**
* <p>Register a new Rule matching the specified pattern.
* This method sets the <code>Digester</code> property on the rule.</p>
*
* @param pattern Element matching pattern
* @param rule Rule to be registered
*/
public void addRule(String pattern, Rule rule) {
rule.setDigester(this);
getRules().add(pattern, rule);
}
/**
* Register a set of Rule instances defined in a RuleSet.
*
* @param ruleSet The RuleSet instance to configure from
*/
public void addRuleSet(RuleSet ruleSet) {
String oldNamespaceURI = getRuleNamespaceURI();
String newNamespaceURI = ruleSet.getNamespaceURI();
if (log.isDebugEnabled()) {
if (newNamespaceURI == null) {
log.debug("addRuleSet() with no namespace URI");
} else {
log.debug("addRuleSet() with namespace URI " + newNamespaceURI);
}
}
setRuleNamespaceURI(newNamespaceURI);
ruleSet.addRuleInstances(this);
setRuleNamespaceURI(oldNamespaceURI);
}
/**
* Add a "bean property setter" rule for the specified parameters.
*
* @param pattern Element matching pattern
* @see BeanPropertySetterRule
*/
public void addBeanPropertySetter(String pattern) {
addRule(pattern,
new BeanPropertySetterRule());
}
/**
* Add a "bean property setter" rule for the specified parameters.
*
* @param pattern Element matching pattern
* @param propertyName Name of property to set
* @see BeanPropertySetterRule
*/
public void addBeanPropertySetter(String pattern,
String propertyName) {
addRule(pattern,
new BeanPropertySetterRule(propertyName));
}
/**
* Add an "call method" rule for a method which accepts no arguments.
*
* @param pattern Element matching pattern
* @param methodName Method name to be called
* @see CallMethodRule
*/
public void addCallMethod(String pattern, String methodName) {
addRule(
pattern,
new CallMethodRule(methodName));
}
/**
* Add an "call method" rule for the specified parameters.
*
* @param pattern Element matching pattern
* @param methodName Method name to be called
* @param paramCount Number of expected parameters (or zero
* for a single parameter from the body of this element)
* @see CallMethodRule
*/
public void addCallMethod(String pattern, String methodName,
int paramCount) {
addRule(pattern,
new CallMethodRule(methodName, paramCount));
}
/**
* Add an "call method" rule for the specified parameters.
* If <code>paramCount</code> is set to zero the rule will use
* the body of the matched element as the single argument of the
* method, unless <code>paramTypes</code> is null or empty, in this
* case the rule will call the specified method with no arguments.
*
* @param pattern Element matching pattern
* @param methodName Method name to be called
* @param paramCount Number of expected parameters (or zero
* for a single parameter from the body of this element)
* @param paramTypes Set of Java class names for the types
* of the expected parameters
* (if you wish to use a primitive type, specify the corresonding
* Java wrapper class instead, such as <code>java.lang.Boolean</code>
* for a <code>boolean</code> parameter)
* @see CallMethodRule
*/
public void addCallMethod(String pattern, String methodName,
int paramCount, String paramTypes[]) {
addRule(pattern,
new CallMethodRule(
methodName,
paramCount,
paramTypes));
}
/**
* Add an "call method" rule for the specified parameters.
* If <code>paramCount</code> is set to zero the rule will use
* the body of the matched element as the single argument of the
* method, unless <code>paramTypes</code> is null or empty, in this
* case the rule will call the specified method with no arguments.
*
* @param pattern Element matching pattern
* @param methodName Method name to be called
* @param paramCount Number of expected parameters (or zero
* for a single parameter from the body of this element)
* @param paramTypes The Java class names of the arguments
* (if you wish to use a primitive type, specify the corresonding
* Java wrapper class instead, such as <code>java.lang.Boolean</code>
* for a <code>boolean</code> parameter)
* @see CallMethodRule
*/
public void addCallMethod(String pattern, String methodName,
int paramCount, Class paramTypes[]) {
addRule(pattern,
new CallMethodRule(
methodName,
paramCount,
paramTypes));
}
/**
* Add a "call parameter" rule for the specified parameters.
*
* @param pattern Element matching pattern
* @param paramIndex Zero-relative parameter index to set
* (from the body of this element)
* @see CallParamRule
*/
public void addCallParam(String pattern, int paramIndex) {
addRule(pattern,
new CallParamRule(paramIndex));
}
/**
* Add a "call parameter" rule for the specified parameters.
*
* @param pattern Element matching pattern
* @param paramIndex Zero-relative parameter index to set
* (from the specified attribute)
* @param attributeName Attribute whose value is used as the
* parameter value
* @see CallParamRule
*/
public void addCallParam(String pattern, int paramIndex,
String attributeName) {
addRule(pattern,
new CallParamRule(paramIndex, attributeName));
}
/**
* Add a "call parameter" rule.
* This will either take a parameter from the stack
* or from the current element body text.
*
* @param paramIndex The zero-relative parameter number
* @param fromStack Should the call parameter be taken from the top of the stack?
* @see CallParamRule
*/
public void addCallParam(String pattern, int paramIndex, boolean fromStack) {
addRule(pattern,
new CallParamRule(paramIndex, fromStack));
}
/**
* Add a "call parameter" rule that sets a parameter from the stack.
* This takes a parameter from the given position on the stack.
*
* @param paramIndex The zero-relative parameter number
* @param stackIndex set the call parameter to the stackIndex'th object down the stack,
* where 0 is the top of the stack, 1 the next element down and so on
* @see CallMethodRule
*/
public void addCallParam(String pattern, int paramIndex, int stackIndex) {
addRule(pattern,
new CallParamRule(paramIndex, stackIndex));
}
/**
* Add a "call parameter" rule that sets a parameter from the current
* <code>Digester</code> matching path.
* This is sometimes useful when using rules that support wildcards.
*
* @param pattern the pattern that this rule should match
* @param paramIndex The zero-relative parameter number
* @see CallMethodRule
*/
public void addCallParamPath(String pattern,int paramIndex) {
addRule(pattern, new PathCallParamRule(paramIndex));
}
/**
* Add a "call parameter" rule that sets a parameter from a
* caller-provided object. This can be used to pass constants such as
* strings to methods; it can also be used to pass mutable objects,
* providing ways for objects to do things like "register" themselves
* with some shared object.
* <p>
* Note that when attempting to locate a matching method to invoke,
* the true type of the paramObj is used, so that despite the paramObj
* being passed in here as type Object, the target method can declare
* its parameters as being the true type of the object (or some ancestor
* type, according to the usual type-conversion rules).
*
* @param paramIndex The zero-relative parameter number
* @param paramObj Any arbitrary object to be passed to the target
* method.
* @see CallMethodRule
*/
public void addObjectParam(String pattern, int paramIndex,
Object paramObj) {
addRule(pattern,
new ObjectParamRule(paramIndex, paramObj));
}
/**
* Add a "factory create" rule for the specified parameters.
* Exceptions thrown during the object creation process will be propagated.
*
* @param pattern Element matching pattern
* @param className Java class name of the object creation factory class
* @see FactoryCreateRule
*/
public void addFactoryCreate(String pattern, String className) {
addFactoryCreate(pattern, className, false);
}
/**
* Add a "factory create" rule for the specified parameters.
* Exceptions thrown during the object creation process will be propagated.
*
* @param pattern Element matching pattern
* @param clazz Java class of the object creation factory class
* @see FactoryCreateRule
*/
public void addFactoryCreate(String pattern, Class clazz) {
addFactoryCreate(pattern, clazz, false);
}
/**
* Add a "factory create" rule for the specified parameters.
* Exceptions thrown during the object creation process will be propagated.
*
* @param pattern Element matching pattern
* @param className Java class name of the object creation factory class
* @param attributeName Attribute name which, if present, overrides the
* value specified by <code>className</code>
* @see FactoryCreateRule
*/
public void addFactoryCreate(String pattern, String className,
String attributeName) {
addFactoryCreate(pattern, className, attributeName, false);
}
/**
* Add a "factory create" rule for the specified parameters.
* Exceptions thrown during the object creation process will be propagated.
*
* @param pattern Element matching pattern
* @param clazz Java class of the object creation factory class
* @param attributeName Attribute name which, if present, overrides the
* value specified by <code>className</code>
* @see FactoryCreateRule
*/
public void addFactoryCreate(String pattern, Class clazz,
String attributeName) {
addFactoryCreate(pattern, clazz, attributeName, false);
}
/**
* Add a "factory create" rule for the specified parameters.
* Exceptions thrown during the object creation process will be propagated.
*
* @param pattern Element matching pattern
* @param creationFactory Previously instantiated ObjectCreationFactory
* to be utilized
* @see FactoryCreateRule
*/
public void addFactoryCreate(String pattern,
ObjectCreationFactory creationFactory) {
addFactoryCreate(pattern, creationFactory, false);
}
/**
* Add a "factory create" rule for the specified parameters.
*
* @param pattern Element matching pattern
* @param className Java class name of the object creation factory class
* @param ignoreCreateExceptions when <code>true</code> any exceptions thrown during
* object creation will be ignored.
* @see FactoryCreateRule
*/
public void addFactoryCreate(
String pattern,
String className,
boolean ignoreCreateExceptions) {
addRule(
pattern,
new FactoryCreateRule(className, ignoreCreateExceptions));
}
/**
* Add a "factory create" rule for the specified parameters.
*
* @param pattern Element matching pattern
* @param clazz Java class of the object creation factory class
* @param ignoreCreateExceptions when <code>true</code> any exceptions thrown during
* object creation will be ignored.
* @see FactoryCreateRule
*/
public void addFactoryCreate(
String pattern,
Class clazz,
boolean ignoreCreateExceptions) {
addRule(
pattern,
new FactoryCreateRule(clazz, ignoreCreateExceptions));
}
/**
* Add a "factory create" rule for the specified parameters.
*
* @param pattern Element matching pattern
* @param className Java class name of the object creation factory class
* @param attributeName Attribute name which, if present, overrides the
* value specified by <code>className</code>
* @param ignoreCreateExceptions when <code>true</code> any exceptions thrown during
* object creation will be ignored.
* @see FactoryCreateRule
*/
public void addFactoryCreate(
String pattern,
String className,
String attributeName,
boolean ignoreCreateExceptions) {
addRule(
pattern,
new FactoryCreateRule(className, attributeName, ignoreCreateExceptions));
}
/**
* Add a "factory create" rule for the specified parameters.
*
* @param pattern Element matching pattern
* @param clazz Java class of the object creation factory class
* @param attributeName Attribute name which, if present, overrides the
* value specified by <code>className</code>
* @param ignoreCreateExceptions when <code>true</code> any exceptions thrown during
* object creation will be ignored.
* @see FactoryCreateRule
*/
public void addFactoryCreate(
String pattern,
Class clazz,
String attributeName,
boolean ignoreCreateExceptions) {
addRule(
pattern,
new FactoryCreateRule(clazz, attributeName, ignoreCreateExceptions));
}
/**
* Add a "factory create" rule for the specified parameters.
*
* @param pattern Element matching pattern
* @param creationFactory Previously instantiated ObjectCreationFactory
* to be utilized
* @param ignoreCreateExceptions when <code>true</code> any exceptions thrown during
* object creation will be ignored.
* @see FactoryCreateRule
*/
public void addFactoryCreate(String pattern,
ObjectCreationFactory creationFactory,
boolean ignoreCreateExceptions) {
creationFactory.setDigester(this);
addRule(pattern,
new FactoryCreateRule(creationFactory, ignoreCreateExceptions));
}
/**
* Add an "object create" rule for the specified parameters.
*
* @param pattern Element matching pattern
* @param className Java class name to be created
* @see ObjectCreateRule
*/
public void addObjectCreate(String pattern, String className) {
addRule(pattern,
new ObjectCreateRule(className));
}
/**
* Add an "object create" rule for the specified parameters.
*
* @param pattern Element matching pattern
* @param clazz Java class to be created
* @see ObjectCreateRule
*/
public void addObjectCreate(String pattern, Class clazz) {
addRule(pattern,
new ObjectCreateRule(clazz));
}
/**
* Add an "object create" rule for the specified parameters.
*
* @param pattern Element matching pattern
* @param className Default Java class name to be created
* @param attributeName Attribute name that optionally overrides
* the default Java class name to be created
* @see ObjectCreateRule
*/
public void addObjectCreate(String pattern, String className,
String attributeName) {
addRule(pattern,
new ObjectCreateRule(className, attributeName));
}
/**
* Add an "object create" rule for the specified parameters.
*
* @param pattern Element matching pattern
* @param attributeName Attribute name that optionally overrides
* @param clazz Default Java class to be created
* the default Java class name to be created
* @see ObjectCreateRule
*/
public void addObjectCreate(String pattern,
String attributeName,
Class clazz) {
addRule(pattern,
new ObjectCreateRule(attributeName, clazz));
}
/**
* Add a "set next" rule for the specified parameters.
*
* @param pattern Element matching pattern
* @param methodName Method name to call on the parent element
* @see SetNextRule
*/
public void addSetNext(String pattern, String methodName) {
addRule(pattern,
new SetNextRule(methodName));
}
/**
* Add a "set next" rule for the specified parameters.
*
* @param pattern Element matching pattern
* @param methodName Method name to call on the parent element
* @param paramType Java class name of the expected parameter type
* (if you wish to use a primitive type, specify the corresonding
* Java wrapper class instead, such as <code>java.lang.Boolean</code>
* for a <code>boolean</code> parameter)
* @see SetNextRule
*/
public void addSetNext(String pattern, String methodName,
String paramType) {
addRule(pattern,
new SetNextRule(methodName, paramType));
}
/**
* Add {@link SetRootRule} with the specified parameters.
*
* @param pattern Element matching pattern
* @param methodName Method name to call on the root object
* @see SetRootRule
*/
public void addSetRoot(String pattern, String methodName) {
addRule(pattern,
new SetRootRule(methodName));
}
/**
* Add {@link SetRootRule} with the specified parameters.
*
* @param pattern Element matching pattern
* @param methodName Method name to call on the root object
* @param paramType Java class name of the expected parameter type
* @see SetRootRule
*/
public void addSetRoot(String pattern, String methodName,
String paramType) {
addRule(pattern,
new SetRootRule(methodName, paramType));
}
/**
* Add a "set properties" rule for the specified parameters.
*
* @param pattern Element matching pattern
* @see SetPropertiesRule
*/
public void addSetProperties(String pattern) {
addRule(pattern,
new SetPropertiesRule());
}
/**
* Add a "set properties" rule with a single overridden parameter.
* See {@link SetPropertiesRule#SetPropertiesRule(String attributeName, String propertyName)}
*
* @param pattern Element matching pattern
* @param attributeName map this attribute
* @param propertyName to this property
* @see SetPropertiesRule
*/
public void addSetProperties(
String pattern,
String attributeName,
String propertyName) {
addRule(pattern,
new SetPropertiesRule(attributeName, propertyName));
}
/**
* Add a "set properties" rule with overridden parameters.
* See {@link SetPropertiesRule#SetPropertiesRule(String [] attributeNames, String [] propertyNames)}
*
* @param pattern Element matching pattern
* @param attributeNames names of attributes with custom mappings
* @param propertyNames property names these attributes map to
* @see SetPropertiesRule
*/
public void addSetProperties(
String pattern,
String [] attributeNames,
String [] propertyNames) {
addRule(pattern,
new SetPropertiesRule(attributeNames, propertyNames));
}
/**
* Add a "set property" rule for the specified parameters.
*
* @param pattern Element matching pattern
* @param name Attribute name containing the property name to be set
* @param value Attribute name containing the property value to set
* @see SetPropertyRule
*/
public void addSetProperty(String pattern, String name, String value) {
addRule(pattern,
new SetPropertyRule(name, value));
}
/**
* Add a "set top" rule for the specified parameters.
*
* @param pattern Element matching pattern
* @param methodName Method name to call on the parent element
* @see SetTopRule
*/
public void addSetTop(String pattern, String methodName) {
addRule(pattern,
new SetTopRule(methodName));
}
/**
* Add a "set top" rule for the specified parameters.
*
* @param pattern Element matching pattern
* @param methodName Method name to call on the parent element
* @param paramType Java class name of the expected parameter type
* (if you wish to use a primitive type, specify the corresonding
* Java wrapper class instead, such as <code>java.lang.Boolean</code>
* for a <code>boolean</code> parameter)
* @see SetTopRule
*/
public void addSetTop(String pattern, String methodName,
String paramType) {
addRule(pattern,
new SetTopRule(methodName, paramType));
}
/**
* Clear the current contents of the object stack.
*/
public void clear() {
match = "";
bodyTexts.clear();
params.clear();
publicId = null;
stack.clear();
}
/**
* Return the top object on the stack without removing it. If there are
* no objects on the stack, return <code>null</code>.
*/
public Object peek() {
try {
return (stack.peek());
} catch (EmptyStackException e) {
log.warn("Empty stack (returning null)");
return (null);
}
}
/**
* Return the n'th object down the stack, where 0 is the top element
* and [getCount()-1] is the bottom element. If the specified index
* is out of range, return <code>null</code>.
*
* @param n Index of the desired element, where 0 is the top of the stack,
* 1 is the next element down, and so on.
*/
public Object peek(int n) {
try {
return (stack.peek(n));
} catch (EmptyStackException e) {
log.warn("Empty stack (returning null)");
return (null);
}
}
/**
* Pop the top object off of the stack, and return it. If there are
* no objects on the stack, return <code>null</code>.
*/
public Object pop() {
try {
return (stack.pop());
} catch (EmptyStackException e) {
log.warn("Empty stack (returning null)");
return (null);
}
}
/**
* Push a new object onto the top of the object stack.
*
* @param object The new object
*/
public void push(Object object) {
if (stack.size() == 0) {
root = object;
}
stack.push(object);
}
/**
* When the Digester is being used as a SAXContentHandler,
* this method allows you to access the root object that has been
* created after parsing.
*
* @return the root object that has been created after parsing
* or null if the digester has not parsed any XML yet.
*/
public Object getRoot() {
return root;
}
/**
* <p>
* Provide a hook for lazy configuration of this <code>Digester</code>
* instance. The default implementation does nothing, but subclasses
* can override as needed.
* </p>
*
* <p>
* <strong>Note</strong> This method may be called more than once.
* Once only initialization code should be placed in {@link #initialize}
* or the code should take responsibility by checking and setting the
* {@link #configured} flag.
* </p>
*/
protected void configure() {
// Do not configure more than once
if (configured) {
return;
}
// Perform lazy configuration as needed
initialize(); // call hook method for subclasses that want to be initialized once only
// Nothing else required by default
// Set the configuration flag to avoid repeating
configured = true;
}
/**
* <p>
* Provides a hook for lazy initialization of this <code>Digester</code>
* instance.
* The default implementation does nothing, but subclasses
* can override as needed.
* Digester (by default) only calls this method once.
* </p>
*
* <p>
* <strong>Note</strong> This method will be called by {@link #configure}
* only when the {@link #configured} flag is false.
* Subclasses that override <code>configure</code> or who set <code>configured</code>
* may find that this method may be called more than once.
* </p>
*/
protected void initialize() {
// Perform lazy initialization as needed
; // Nothing required by default
}
/**
* Return the set of DTD URL registrations, keyed by public identifier.
*/
Map getRegistrations() {
return (entityValidator);
}
/**
* Return the set of rules that apply to the specified match position.
* The selected rules are those that match exactly, or those rules
* that specify a suffix match and the tail of the rule matches the
* current match position. Exact matches have precedence over
* suffix matches, then (among suffix matches) the longest match
* is preferred.
*
* @param match The current match position
*
* @deprecated Call <code>match()</code> on the <code>Rules</code>
* implementation returned by <code>getRules()</code>
*/
List getRules(String match) {
return (getRules().match(match));
}
/**
* <p>Return the top object on the parameters stack without removing it. If there are
* no objects on the stack, return <code>null</code>.</p>
*
* <p>The parameters stack is used to store <code>CallMethodRule</code> parameters.
* See {@link #params}.</p>
*/
public Object peekParams() {
try {
return (params.peek());
} catch (EmptyStackException e) {
log.warn("Empty stack (returning null)");
return (null);
}
}
/**
* <p>Return the n'th object down the parameters stack, where 0 is the top element
* and [getCount()-1] is the bottom element. If the specified index
* is out of range, return <code>null</code>.</p>
*
* <p>The parameters stack is used to store <code>CallMethodRule</code> parameters.
* See {@link #params}.</p>
*
* @param n Index of the desired element, where 0 is the top of the stack,
* 1 is the next element down, and so on.
*/
public Object peekParams(int n) {
try {
return (params.peek(n));
} catch (EmptyStackException e) {
log.warn("Empty stack (returning null)");
return (null);
}
}
/**
* <p>Pop the top object off of the parameters stack, and return it. If there are
* no objects on the stack, return <code>null</code>.</p>
*
* <p>The parameters stack is used to store <code>CallMethodRule</code> parameters.
* See {@link #params}.</p>
*/
public Object popParams() {
try {
if (log.isTraceEnabled()) {
log.trace("Popping params");
}
return (params.pop());
} catch (EmptyStackException e) {
log.warn("Empty stack (returning null)");
return (null);
}
}
/**
* <p>Push a new object onto the top of the parameters stack.</p>
*
* <p>The parameters stack is used to store <code>CallMethodRule</code> parameters.
* See {@link #params}.</p>
*
* @param object The new object
*/
public void pushParams(Object object) {
if (log.isTraceEnabled()) {
log.trace("Pushing params");
}
params.push(object);
}
/**
* Create a SAX exception which also understands about the location in
* the digester file where the exception occurs
*
* @return the new exception
*/
protected SAXException createSAXException(String message, Exception e) {
if ((e != null) &&
(e instanceof InvocationTargetException)) {
Throwable t = ((InvocationTargetException) e).getTargetException();
if ((t != null) && (t instanceof Exception)) {
e = (Exception) t;
}
}
if (locator != null) {
String error = "Error at (" + locator.getLineNumber() + ", "
+ locator.getColumnNumber() + ": " + message;
if (e != null) {
return new SAXParseException(error, locator, e);
} else {
return new SAXParseException(error, locator);
}
}
log.error("No Locator!");
if (e != null) {
return new SAXException(message, e);
} else {
return new SAXException(message);
}
}
/**
* Create a SAX exception which also understands about the location in
* the digester file where the exception occurs
*
* @return the new exception
*/
protected SAXException createSAXException(Exception e) {
if (e instanceof InvocationTargetException) {
Throwable t = ((InvocationTargetException) e).getTargetException();
if ((t != null) && (t instanceof Exception)) {
e = (Exception) t;
}
}
return createSAXException(e.getMessage(), e);
}
/**
* Create a SAX exception which also understands about the location in
* the digester file where the exception occurs
*
* @return the new exception
*/
protected SAXException createSAXException(String message) {
return createSAXException(message, null);
}
}
|
package org.apache.velocity.util;
import java.io.File;
import java.io.FileReader;
import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.StringTokenizer;
/**
* This class provides some methods for dynamically
* invoking methods in objects, and some string
* manipulation methods used by torque. The string
* methods will soon be moved into the turbine
* string utilities class.
*
* @author <a href="mailto:jvanzyl@periapt.com">Jason van Zyl</a>
* @author <a href="mailto:dlr@finemaltcoding.com">Daniel Rall</a>
* @version $Id: StringUtils.java,v 1.13 2001/07/02 03:16:01 geirm Exp $
*/
public class StringUtils
{
/**
* Line separator for the OS we are operating on.
*/
private static final String EOL = System.getProperty("line.separator");
/**
* Length of the line separator.
*/
private static final int EOL_LENGTH = EOL.length();
/**
* Concatenates a list of objects as a String.
*
* @param list The list of objects to concatenate.
* @return A text representation of the concatenated objects.
*/
public String concat(List list)
{
StringBuffer sb = new StringBuffer();
int size = list.size();
for (int i = 0; i < size; i++)
{
sb.append(list.get(i).toString());
}
return sb.toString();
}
/**
* Return a package name as a relative path name
*
* @param String package name to convert to a directory.
* @return String directory path.
*/
static public String getPackageAsPath(String pckge)
{
return pckge.replace( '.', File.separator.charAt(0) ) + File.separator;
}
/**
* <p>
* Remove underscores from a string and replaces first
* letters with capitals. Other letters are changed to lower case.
* </p>
*
* <p>
* For example <code>foo_bar</code> becomes <code>FooBar</code>
* but <code>foo_barBar</code> becomes <code>FooBarbar</code>.
* </p>
*
* @param data string to remove underscores from.
* @return String
*/
static public String removeUnderScores (String data)
{
String temp = null;
StringBuffer out = new StringBuffer();
temp = data;
StringTokenizer st = new StringTokenizer(temp, "_");
while (st.hasMoreTokens())
{
String element = (String) st.nextElement();
out.append ( firstLetterCaps(element));
}//while
return out.toString();
}
/**
* <p>
* 'Camels Hump' replacement of underscores.
* </p>
*
* <p>
* Remove underscores from a string but leave the capitalization of the
* other letters unchanged.
* </p>
*
* <p>
* For example <code>foo_barBar</code> becomes <code>FooBarBar</code>.
* </p>
*
* @param data string to hump
* @return String
*/
static public String removeAndHump (String data)
{
return removeAndHump(data,"_");
}
/**
* <p>
* 'Camels Hump' replacement.
* </p>
*
* <p>
* Remove one string from another string but leave the capitalization of the
* other letters unchanged.
* </p>
*
* <p>
* For example, removing "_" from <code>foo_barBar</code> becomes <code>FooBarBar</code>.
* </p>
*
* @param data string to hump
* @param replaceThis string to be replaced
* @return String
*/
static public String removeAndHump (String data,String replaceThis)
{
String temp = null;
StringBuffer out = new StringBuffer();
temp = data;
StringTokenizer st = new StringTokenizer(temp, replaceThis);
while (st.hasMoreTokens())
{
String element = (String) st.nextElement();
out.append ( capitalizeFirstLetter(element));
}//while
return out.toString();
}
/**
* <p>
* Makes the first letter caps and the rest lowercase.
* </p>
*
* <p>
* For example <code>fooBar</code> becomes <code>Foobar</code>.
* </p>
*
* @param data capitalize this
* @return String
*/
static public String firstLetterCaps ( String data )
{
String firstLetter = data.substring(0,1).toUpperCase();
String restLetters = data.substring(1).toLowerCase();
return firstLetter + restLetters;
}
/**
* <p>
* Capitalize the first letter but leave the rest as they are.
* </p>
*
* <p>
* For example <code>fooBar</code> becomes <code>FooBar</code>.
* </p>
*
* @param data capitalize this
* @return String
*/
static public String capitalizeFirstLetter ( String data )
{
String firstLetter = data.substring(0,1).toUpperCase();
String restLetters = data.substring(1);
return firstLetter + restLetters;
}
/**
* Create a string array from a string separated by delim
*
* @param line the line to split
* @param delim the delimter to split by
* @return a string array of the split fields
*/
public static String [] split(String line, String delim)
{
List list = new ArrayList();
StringTokenizer t = new StringTokenizer(line, delim);
while (t.hasMoreTokens())
{
list.add(t.nextToken());
}
return (String []) list.toArray(new String[list.size()]);
}
/**
* Chop i characters off the end of a string.
* This method assumes that any EOL characters in String s
* and the platform EOL will be the same.
* A 2 character EOL will count as 1 character.
*
* @param string String to chop.
* @param i Number of characters to chop.
* @return String with processed answer.
*/
public static String chop(String s, int i)
{
return chop(s, i, EOL);
}
/**
* Chop i characters off the end of a string.
* A 2 character EOL will count as 1 character.
*
* @param string String to chop.
* @param i Number of characters to chop.
* @param eol A String representing the EOL (end of line).
* @return String with processed answer.
*/
public static String chop(String s, int i, String eol)
{
char[] sa = s.toCharArray();
int length = sa.length;
if ( eol.length() == 2 )
{
char eol1 = eol.charAt(0);
char eol2 = eol.charAt(1);
for (; i>0; i
{
if ( sa[length-1] == eol2 && sa[length-2] == eol1 )
{
length -= 2;
}
else
{
length
}
}
}
else
{
length -= i;
}
return new String(sa, 0, length);
}
/**
* Perform a series of substitutions. The substitions
* are performed by replacing $variable in the target
* string with the value of provided by the key "variable"
* in the provided hashtable.
*
* @param String target string
* @param Hashtable name/value pairs used for substitution
* @return String target string with replacements.
*/
public static StringBuffer stringSubstitution(String argStr,
Hashtable vars)
{
StringBuffer argBuf = new StringBuffer();
for (int cIdx = 0 ; cIdx < argStr.length();)
{
char ch = argStr.charAt(cIdx);
switch (ch)
{
case '$':
StringBuffer nameBuf = new StringBuffer();
for (++cIdx ; cIdx < argStr.length(); ++cIdx)
{
ch = argStr.charAt(cIdx);
if (ch == '_' || Character.isLetterOrDigit(ch))
nameBuf.append(ch);
else
break;
}
if (nameBuf.length() > 0)
{
String value =
(String) vars.get(nameBuf.toString());
if (value != null)
{
argBuf.append(value);
}
}
break;
default:
argBuf.append(ch);
++cIdx;
break;
}
}
return argBuf;
}
/**
* Read the contents of a file and place them in
* a string object.
*
* @param String path to file.
* @return String contents of the file.
*/
public static String fileContentsToString(String file)
{
String contents = "";
File f = new File(file);
if (f.exists())
{
try
{
FileReader fr = new FileReader(f);
char[] template = new char[(int) f.length()];
fr.read(template);
contents = new String(template);
}
catch (Exception e)
{
System.out.println(e);
e.printStackTrace();
}
}
return contents;
}
/**
* Remove/collapse multiple newline characters.
*
* @param String string to collapse newlines in.
* @return String
*/
public static String collapseNewlines(String argStr)
{
char last = argStr.charAt(0);
StringBuffer argBuf = new StringBuffer();
for (int cIdx = 0 ; cIdx < argStr.length(); cIdx++)
{
char ch = argStr.charAt(cIdx);
if (ch != '\n' || last != '\n')
{
argBuf.append(ch);
last = ch;
}
}
return argBuf.toString();
}
/**
* Remove/collapse multiple spaces.
*
* @param String string to remove multiple spaces from.
* @return String
*/
public static String collapseSpaces(String argStr)
{
char last = argStr.charAt(0);
StringBuffer argBuf = new StringBuffer();
for (int cIdx = 0 ; cIdx < argStr.length(); cIdx++)
{
char ch = argStr.charAt(cIdx);
if (ch != ' ' || last != ' ')
{
argBuf.append(ch);
last = ch;
}
}
return argBuf.toString();
}
/**
* Replaces all instances of oldString with newString in line.
* Taken from the Jive forum package.
*
* @param String original string.
* @param String string in line to replace.
* @param String replace oldString with this.
* @return String string with replacements.
*/
public static final String sub(String line, String oldString,
String newString)
{
int i = 0;
if ((i = line.indexOf(oldString, i)) >= 0)
{
char [] line2 = line.toCharArray();
char [] newString2 = newString.toCharArray();
int oLength = oldString.length();
StringBuffer buf = new StringBuffer(line2.length);
buf.append(line2, 0, i).append(newString2);
i += oLength;
int j = i;
while ((i = line.indexOf(oldString, i)) > 0)
{
buf.append(line2, j, i - j).append(newString2);
i += oLength;
j = i;
}
buf.append(line2, j, line2.length - j);
return buf.toString();
}
return line;
}
/**
* Returns the output of printStackTrace as a String.
*
* @param e A Throwable.
* @return A String.
*/
public static final String stackTrace(Throwable e)
{
String foo = null;
try
{
// And show the Error Screen.
ByteArrayOutputStream ostr = new ByteArrayOutputStream();
e.printStackTrace( new PrintWriter(ostr,true) );
foo = ostr.toString();
}
catch (Exception f)
{
// Do nothing.
}
return foo;
}
/**
* Return a context-relative path, beginning with a "/", that represents
* the canonical version of the specified path after ".." and "." elements
* are resolved out. If the specified path attempts to go outside the
* boundaries of the current context (i.e. too many ".." path elements
* are present), return <code>null</code> instead.
*
* @param path Path to be normalized
* @return String normalized path
*/
public static final String normalizePath(String path)
{
// Normalize the slashes and add leading slash if necessary
String normalized = path;
if (normalized.indexOf('\\') >= 0)
{
normalized = normalized.replace('\\', '/');
}
if (!normalized.startsWith("/"))
{
normalized = "/" + normalized;
}
// Resolve occurrences of "//" in the normalized path
while (true)
{
int index = normalized.indexOf("
if (index < 0)
break;
normalized = normalized.substring(0, index) +
normalized.substring(index + 1);
}
// Resolve occurrences of "%20" in the normalized path
while (true)
{
int index = normalized.indexOf("%20");
if (index < 0)
break;
normalized = normalized.substring(0, index) + " " +
normalized.substring(index + 3);
}
// Resolve occurrences of "/./" in the normalized path
while (true)
{
int index = normalized.indexOf("/./");
if (index < 0)
break;
normalized = normalized.substring(0, index) +
normalized.substring(index + 2);
}
// Resolve occurrences of "/../" in the normalized path
while (true)
{
int index = normalized.indexOf("/../");
if (index < 0)
break;
if (index == 0)
return (null); // Trying to go outside our context
int index2 = normalized.lastIndexOf('/', index - 1);
normalized = normalized.substring(0, index2) +
normalized.substring(index + 3);
}
// Return the normalized path that we have completed
return (normalized);
}
/**
* If state is true then return the trueString, else
* return the falseString.
*
* @param boolean
* @param String trueString
* @param String falseString
*/
public String select(boolean state, String trueString, String falseString)
{
if (state)
{
return trueString;
}
else
{
return falseString;
}
}
/**
* Check to see if all the string objects passed
* in are empty.
*
* @param list A list of {@link java.lang.String} objects.
* @return Whether all strings are empty.
*/
public boolean allEmpty(List list)
{
int size = list.size();
for (int i = 0; i < size; i++)
{
if (list.get(i) != null && list.get(i).toString().length() > 0)
{
return false;
}
}
return true;
}
}
|
package dyvil.tools.repl.command;
import dyvil.collection.Set;
import dyvil.collection.mutable.IdentityHashSet;
import dyvil.collection.mutable.TreeSet;
import dyvil.reflect.Modifiers;
import dyvil.tools.compiler.ast.classes.IClass;
import dyvil.tools.compiler.ast.classes.IClassBody;
import dyvil.tools.compiler.ast.consumer.IValueConsumer;
import dyvil.tools.compiler.ast.expression.IValue;
import dyvil.tools.compiler.ast.field.IField;
import dyvil.tools.compiler.ast.field.IProperty;
import dyvil.tools.compiler.ast.member.IMember;
import dyvil.tools.compiler.ast.method.IMethod;
import dyvil.tools.compiler.ast.parameter.IParameter;
import dyvil.tools.compiler.ast.type.IType;
import dyvil.tools.compiler.ast.type.Types;
import dyvil.tools.compiler.parser.ParserManager;
import dyvil.tools.compiler.parser.expression.ExpressionParser;
import dyvil.tools.compiler.transform.DyvilSymbols;
import dyvil.tools.parsing.TokenIterator;
import dyvil.tools.parsing.lexer.BaseSymbols;
import dyvil.tools.parsing.lexer.DyvilLexer;
import dyvil.tools.parsing.marker.MarkerList;
import dyvil.tools.repl.DyvilREPL;
import dyvil.tools.repl.context.REPLContext;
public class CompleteCommand implements ICommand
{
@Override
public String getName()
{
return "complete";
}
@Override
public String[] getAliases()
{
return new String[] { "c" };
}
@Override
public String getDescription()
{
return "Prints a list of possible completions";
}
@Override
public String getUsage()
{
return ":c[omplete] <identifier>[.]";
}
@Override
public void execute(DyvilREPL repl, String argument)
{
final REPLContext context = repl.getContext();
if (argument == null)
{
// REPL Variables
this.printREPLMembers(repl, context, "");
return;
}
final int dotIndex = argument.lastIndexOf('.');
if (dotIndex <= 0)
{
// REPL Variable Completions
this.printREPLMembers(repl, context, BaseSymbols.qualify(argument));
return;
}
final String expression = argument.substring(0, dotIndex);
final String memberStart = BaseSymbols.qualify(argument.substring(dotIndex + 1));
final MarkerList markers = new MarkerList();
final TokenIterator tokenIterator = new DyvilLexer(markers, DyvilSymbols.INSTANCE).tokenize(expression);
final IValueConsumer valueConsumer = value -> {
value.resolveTypes(markers, context);
value = value.resolve(markers, context);
value.checkTypes(markers, context);
final IType type = value.getType();
repl.getOutput().println("Available completions for '" + value + "' of type '" + type + "':");
this.printCompletions(repl, memberStart, type, value.valueTag() == IValue.CLASS_ACCESS);
};
new ParserManager(new ExpressionParser(valueConsumer), markers, context).parse(tokenIterator);
}
private void printREPLMembers(DyvilREPL repl, REPLContext context, String start)
{
final Set<String> fields = new TreeSet<>();
final Set<String> methods = new TreeSet<>();
for (IField variable : context.getFields().values())
{
if (variable.getName().startWith(start))
{
fields.add(getSignature(Types.UNKNOWN, variable));
}
}
for (IMethod method : context.getMethods())
{
if (method.getName().startWith(start))
{
methods.add(getSignature(Types.UNKNOWN, method));
}
}
boolean output = false;
if (!fields.isEmpty())
{
output = true;
repl.getOutput().println("Fields:");
for (String field : fields)
{
repl.getOutput().print('\t');
repl.getOutput().println(field);
}
}
if (!methods.isEmpty())
{
output = true;
repl.getOutput().println("Methods:");
for (String method : methods)
{
repl.getOutput().print('\t');
repl.getOutput().println(method);
}
}
if (!output)
{
repl.getOutput().println("No completions available");
}
}
private void printCompletions(DyvilREPL repl, String memberStart, IType type, boolean statics)
{
final Set<String> fields = new TreeSet<>();
final Set<String> properties = new TreeSet<>();
final Set<String> methods = new TreeSet<>();
this.findCompletions(type, fields, properties, methods, memberStart, statics, new IdentityHashSet<>());
boolean output = false;
if (!fields.isEmpty())
{
output = true;
repl.getOutput().println("Fields:");
for (String field : fields)
{
repl.getOutput().print('\t');
repl.getOutput().println(field);
}
}
if (!properties.isEmpty())
{
output = true;
repl.getOutput().println("Properties:");
for (String property : properties)
{
repl.getOutput().print('\t');
repl.getOutput().println(property);
}
}
if (!methods.isEmpty())
{
output = true;
repl.getOutput().println("Methods:");
for (String method : methods)
{
repl.getOutput().print('\t');
repl.getOutput().println(method);
}
}
if (!output)
{
if (statics)
{
repl.getOutput().println("No static completions available for type " + type);
}
else
{
repl.getOutput().println("No completions available for type " + type);
}
}
}
private void findCompletions(IType type, Set<String> fields, Set<String> properties, Set<String> methods, String start, boolean statics, Set<IClass> dejaVu)
{
IClass iclass = type.getTheClass();
if (dejaVu.contains(iclass))
{
return;
}
dejaVu.add(iclass);
// Add members
for (int i = 0, count = iclass.parameterCount(); i < count; i++)
{
final IParameter parameter = iclass.getParameter(i);
if (matches(start, parameter, statics))
{
fields.add(getSignature(type, parameter));
}
}
final IClassBody body = iclass.getBody();
if (body != null)
{
for (int i = 0, count = body.fieldCount(); i < count; i++)
{
final IField field = body.getField(i);
if (matches(start, field, statics))
{
fields.add(getSignature(type, field));
}
}
for (int i = 0, count = body.propertyCount(); i < count; i++)
{
final IProperty property = body.getProperty(i);
if (matches(start, property, statics))
{
properties.add(getSignature(type, property));
}
}
for (int i = 0, count = body.methodCount(); i < count; i++)
{
final IMethod method = body.getMethod(i);
if (matches(start, method, statics))
{
methods.add(getSignature(type, method));
}
}
}
if (statics)
{
return;
}
// Recursively scan super types
final IType superType = iclass.getSuperType();
if (superType != null)
{
this.findCompletions(superType.getConcreteType(type), fields, properties, methods, start, false, dejaVu);
}
for (int i = 0, count = iclass.interfaceCount(); i < count; i++)
{
final IType superInterface = iclass.getInterface(i);
if (superInterface != null)
{
this.findCompletions(superInterface.getConcreteType(type), fields, properties, methods, start, false,
dejaVu);
}
}
}
private static boolean matches(String start, IMember member, boolean statics)
{
if (!member.getName().startWith(start))
{
return false;
}
int modifiers = member.getModifiers().toFlags();
return (modifiers & Modifiers.PUBLIC) != 0 && statics == ((modifiers & Modifiers.STATIC) != 0);
}
private static String getSignature(IType type, IMember member)
{
StringBuilder sb = new StringBuilder();
sb.append(member.getName());
sb.append(" : ");
member.getType().getConcreteType(type).toString("", sb);
return sb.toString();
}
private static String getSignature(IType type, IMethod method)
{
StringBuilder sb = new StringBuilder();
sb.append(method.getName());
sb.append('(');
int paramCount = method.parameterCount();
if (paramCount > 0)
{
method.getParameter(0).getType().getConcreteType(type).toString("", sb);
for (int i = 1; i < paramCount; i++)
{
sb.append(", ");
method.getParameter(i).getType().getConcreteType(type).toString("", sb);
}
}
sb.append(") : ");
method.getType().getConcreteType(type).toString("", sb);
return sb.toString();
}
}
|
package com.helger.as4lib.util;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.cert.Certificate;
import java.security.cert.CertificateEncodingException;
import javax.annotation.Nonnegative;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.annotation.WillClose;
import javax.annotation.WillNotClose;
import javax.annotation.concurrent.Immutable;
import com.helger.commons.CGlobal;
import com.helger.commons.ValueEnforcer;
import com.helger.commons.annotation.Nonempty;
import com.helger.commons.base64.Base64;
import com.helger.commons.io.file.FileIOError;
import com.helger.commons.io.file.FileOperationManager;
import com.helger.commons.io.file.FilenameHelper;
import com.helger.commons.io.file.LoggingFileOperationCallback;
import com.helger.commons.io.stream.StreamHelper;
import com.helger.commons.mutable.MutableLong;
import com.helger.commons.string.StringHelper;
import com.helger.commons.timing.StopWatch;
import com.helger.security.certificate.CertificateHelper;
@Immutable
public final class IOHelper
{
private static final FileOperationManager s_aFOM = new FileOperationManager (new LoggingFileOperationCallback ());
private IOHelper ()
{}
@Nonnull
public static FileOperationManager getFileOperationManager ()
{
return s_aFOM;
}
@Nonnegative
public static long copy (@Nonnull @WillClose final InputStream aIS, @Nonnull @WillNotClose final OutputStream aOS)
{
final MutableLong aML = new MutableLong ();
StreamHelper.copyInputStreamToOutputStream (aIS, aOS, aML);
return aML.longValue ();
}
@Nonnull
public static File getDirectoryFile (@Nonnull final String sDirectory)
{
final File aDir = new File (sDirectory);
s_aFOM.createDirRecursiveIfNotExisting (aDir);
return aDir;
}
@Nonnull
@Nonempty
public static String getTransferRate (final long nBytes, @Nonnull final StopWatch aSW)
{
final StringBuilder aSB = new StringBuilder ();
aSB.append (nBytes).append (" bytes in ").append (aSW.getMillis () / 1000.0).append (" seconds at ");
final long nMillis = aSW.getMillis ();
if (nMillis != 0)
{
final double dSeconds = nMillis / 1000.0;
final long nBytesPerSecond = Math.round (nBytes / dSeconds);
aSB.append (_getTransferRate (nBytesPerSecond));
}
else
{
aSB.append (_getTransferRate (nBytes));
}
return aSB.toString ();
}
@Nonnull
@Nonempty
private static String _getTransferRate (final long nBytesPerSecond)
{
final StringBuilder aSB = new StringBuilder ();
if (nBytesPerSecond < CGlobal.BYTES_PER_KILOBYTE)
{
// < 1024
aSB.append (nBytesPerSecond).append (" Bps");
}
else
{
final long nKBytesPerSecond = nBytesPerSecond / CGlobal.BYTES_PER_KILOBYTE;
if (nKBytesPerSecond < CGlobal.BYTES_PER_KILOBYTE)
{
// < 1048576
aSB.append (nKBytesPerSecond)
.append ('.')
.append (nBytesPerSecond % CGlobal.BYTES_PER_KILOBYTE)
.append (" KBps");
}
else
{
// >= 1048576
aSB.append (nKBytesPerSecond / CGlobal.BYTES_PER_KILOBYTE)
.append ('.')
.append (nKBytesPerSecond % CGlobal.BYTES_PER_KILOBYTE)
.append (" MBps");
}
}
return aSB.toString ();
}
@Nonnull
public static File getUniqueFile (@Nonnull final File aDir, @Nullable final String sFilename)
{
final String sBaseFilename = FilenameHelper.getAsSecureValidFilename (sFilename);
int nCounter = -1;
while (true)
{
final File aTest = new File (aDir,
nCounter == -1 ? sBaseFilename : sBaseFilename + "." + Integer.toString (nCounter));
if (!aTest.exists ())
return aTest;
nCounter++;
}
}
@Nonnull
public static File moveFile (@Nonnull final File aSrc,
@Nonnull final File aDestFile,
final boolean bOverwrite,
final boolean bRename) throws IOException
{
File aRealDestFile = aDestFile;
if (!bOverwrite && aRealDestFile.exists ())
{
if (!bRename)
throw new IOException ("File already exists: " + aRealDestFile);
aRealDestFile = getUniqueFile (aRealDestFile.getAbsoluteFile ().getParentFile (), aRealDestFile.getName ());
}
// Copy
FileIOError aIOErr = s_aFOM.copyFile (aSrc, aRealDestFile);
if (aIOErr.isFailure ())
throw new IOException ("Copy failed: " + aIOErr.toString ());
// Delete old
aIOErr = s_aFOM.deleteFile (aSrc);
if (aIOErr.isFailure ())
{
s_aFOM.deleteFile (aRealDestFile);
throw new IOException ("Move failed, unable to delete " + aSrc + ": " + aIOErr.toString ());
}
return aRealDestFile;
}
@Nonnull
public static String getFilenameFromMessageID (@Nonnull final String sMessageID)
{
// Remove angle brackets manually
String s = StringHelper.removeAll (sMessageID, '<');
s = StringHelper.removeAll (s, '>');
return FilenameHelper.getAsSecureValidASCIIFilename (s);
}
// TODO Replace with CertificateHelper method in ph-security > 8.5.4
@Nonnull
@Nonempty
public static String getPEMEncodedCertificate (@Nonnull final Certificate aCert)
{
ValueEnforcer.notNull (aCert, "Cert");
try
{
return CertificateHelper.BEGIN_CERTIFICATE +
"\n" +
Base64.encodeBytes (aCert.getEncoded ()) +
"\n" +
CertificateHelper.END_CERTIFICATE;
}
catch (final CertificateEncodingException ex)
{
throw new IllegalArgumentException ("Failed to encode certificate " + aCert, ex);
}
}
}
|
package ch03._excercise;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
/**
A house that can be positioned anywhere on the screen.
*/
public class House {
private int xPos;
private int yPos;
public House(int x, int y) {
xPos = x;
yPos = y;
}
public void draw(Graphics2D g2) {
Rectangle front = new Rectangle(xPos, yPos, 100, 100);
Rectangle door = new Rectangle(xPos+10, yPos+60, 20, 40);
Rectangle window = new Rectangle(xPos+60, yPos+30, 20, 20);
Point2D.Double roofLeftPoint = new Point2D.Double(xPos, yPos);
Point2D.Double roofRightPoint = new Point2D.Double(xPos+100, yPos);
Point2D.Double roofTopPoint = new Point2D.Double(xPos+50, yPos-50);
Line2D.Double roofLeftLine = new Line2D.Double(roofLeftPoint,
roofTopPoint);
Line2D.Double roofRightLine = new Line2D.Double(roofRightPoint,
roofTopPoint);
g2.draw(front);
g2.draw(door);
g2.draw(window);
g2.draw(roofLeftLine);
g2.draw(roofRightLine);
}
public int[] setPos(int x, int y) {
xPos = x;
yPos = y;
return new int[]{xPos, yPos};
}
public int[] getPos() {
return new int[]{xPos, yPos};
}
public int getxPos() {
return xPos;
}
public int getyPos() {
return yPos;
}
}
|
package se.chalmers.watchme.activity;
import se.chalmers.watchme.R;
import se.chalmers.watchme.R.id;
import se.chalmers.watchme.R.layout;
import se.chalmers.watchme.R.menu;
import se.chalmers.watchme.database.DatabaseHandler;
import se.chalmers.watchme.model.Movie;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.support.v4.app.NavUtils;
import android.view.View.OnClickListener;
public class AddMovieActivity extends Activity {
private TextView titleField;
private TextView noteField;
private Button addButton;
private final Context context = this;
private DatabaseHandler db;
@SuppressLint("NewApi")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_movie);
getActionBar().setDisplayHomeAsUpEnabled(true);
this.addButton = (Button) findViewById(R.id.add_movie_button);
this.titleField = (TextView) findViewById(R.id.movie_name_field);
this.noteField = (TextView) findViewById(R.id.movie_note_field);
db = new DatabaseHandler(this);
/**
* Click callback. Create a new Movie object and set it on
* the Intent, and then finish this Activity.
*/
this.addButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String movieTitle = titleField.getText().toString();
String movieNote = noteField.getText().toString();
Movie movie = new Movie(movieTitle);
movie.setNote(movieNote);
db.addMovie(movie);
Intent home = new Intent(context, MainActivity.class);
setResult(RESULT_OK, home);
home.putExtra("movie", movie);
finish();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_add_movie, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
|
package org.xtreemfs.mrc.client;
import java.net.InetSocketAddress;
import java.util.List;
import org.xtreemfs.common.buffer.ReusableBuffer;
import org.xtreemfs.foundation.oncrpc.client.ONCRPCClient;
import org.xtreemfs.foundation.oncrpc.client.RPCNIOSocketClient;
import org.xtreemfs.foundation.oncrpc.client.RPCResponse;
import org.xtreemfs.foundation.oncrpc.client.RPCResponseDecoder;
import org.xtreemfs.interfaces.AccessControlPolicyType;
import org.xtreemfs.interfaces.DirectoryEntrySet;
import org.xtreemfs.interfaces.FileCredentials;
import org.xtreemfs.interfaces.FileCredentialsSet;
import org.xtreemfs.interfaces.OSDSelectionPolicyType;
import org.xtreemfs.interfaces.OSDWriteResponse;
import org.xtreemfs.interfaces.Replica;
import org.xtreemfs.interfaces.Stat;
import org.xtreemfs.interfaces.StatVFS;
import org.xtreemfs.interfaces.StringSet;
import org.xtreemfs.interfaces.StripingPolicy;
import org.xtreemfs.interfaces.UserCredentials;
import org.xtreemfs.interfaces.Volume;
import org.xtreemfs.interfaces.VolumeSet;
import org.xtreemfs.interfaces.XCap;
import org.xtreemfs.interfaces.MRCInterface.MRCInterface;
import org.xtreemfs.interfaces.MRCInterface.accessRequest;
import org.xtreemfs.interfaces.MRCInterface.accessResponse;
import org.xtreemfs.interfaces.MRCInterface.chmodRequest;
import org.xtreemfs.interfaces.MRCInterface.chmodResponse;
import org.xtreemfs.interfaces.MRCInterface.chownRequest;
import org.xtreemfs.interfaces.MRCInterface.chownResponse;
import org.xtreemfs.interfaces.MRCInterface.creatRequest;
import org.xtreemfs.interfaces.MRCInterface.creatResponse;
import org.xtreemfs.interfaces.MRCInterface.ftruncateRequest;
import org.xtreemfs.interfaces.MRCInterface.ftruncateResponse;
import org.xtreemfs.interfaces.MRCInterface.getattrRequest;
import org.xtreemfs.interfaces.MRCInterface.getattrResponse;
import org.xtreemfs.interfaces.MRCInterface.getxattrRequest;
import org.xtreemfs.interfaces.MRCInterface.getxattrResponse;
import org.xtreemfs.interfaces.MRCInterface.linkRequest;
import org.xtreemfs.interfaces.MRCInterface.linkResponse;
import org.xtreemfs.interfaces.MRCInterface.listxattrRequest;
import org.xtreemfs.interfaces.MRCInterface.listxattrResponse;
import org.xtreemfs.interfaces.MRCInterface.mkdirRequest;
import org.xtreemfs.interfaces.MRCInterface.mkdirResponse;
import org.xtreemfs.interfaces.MRCInterface.openRequest;
import org.xtreemfs.interfaces.MRCInterface.openResponse;
import org.xtreemfs.interfaces.MRCInterface.readdirRequest;
import org.xtreemfs.interfaces.MRCInterface.readdirResponse;
import org.xtreemfs.interfaces.MRCInterface.removexattrRequest;
import org.xtreemfs.interfaces.MRCInterface.removexattrResponse;
import org.xtreemfs.interfaces.MRCInterface.renameRequest;
import org.xtreemfs.interfaces.MRCInterface.renameResponse;
import org.xtreemfs.interfaces.MRCInterface.rmdirRequest;
import org.xtreemfs.interfaces.MRCInterface.rmdirResponse;
import org.xtreemfs.interfaces.MRCInterface.setattrRequest;
import org.xtreemfs.interfaces.MRCInterface.setattrResponse;
import org.xtreemfs.interfaces.MRCInterface.setxattrRequest;
import org.xtreemfs.interfaces.MRCInterface.setxattrResponse;
import org.xtreemfs.interfaces.MRCInterface.statvfsRequest;
import org.xtreemfs.interfaces.MRCInterface.statvfsResponse;
import org.xtreemfs.interfaces.MRCInterface.symlinkRequest;
import org.xtreemfs.interfaces.MRCInterface.symlinkResponse;
import org.xtreemfs.interfaces.MRCInterface.unlinkRequest;
import org.xtreemfs.interfaces.MRCInterface.unlinkResponse;
import org.xtreemfs.interfaces.MRCInterface.utimensRequest;
import org.xtreemfs.interfaces.MRCInterface.utimensResponse;
import org.xtreemfs.interfaces.MRCInterface.xtreemfs_check_file_existsRequest;
import org.xtreemfs.interfaces.MRCInterface.xtreemfs_check_file_existsResponse;
import org.xtreemfs.interfaces.MRCInterface.xtreemfs_checkpointRequest;
import org.xtreemfs.interfaces.MRCInterface.xtreemfs_checkpointResponse;
import org.xtreemfs.interfaces.MRCInterface.xtreemfs_dump_databaseRequest;
import org.xtreemfs.interfaces.MRCInterface.xtreemfs_dump_databaseResponse;
import org.xtreemfs.interfaces.MRCInterface.xtreemfs_get_suitable_osdsRequest;
import org.xtreemfs.interfaces.MRCInterface.xtreemfs_get_suitable_osdsResponse;
import org.xtreemfs.interfaces.MRCInterface.xtreemfs_internal_debugRequest;
import org.xtreemfs.interfaces.MRCInterface.xtreemfs_internal_debugResponse;
import org.xtreemfs.interfaces.MRCInterface.xtreemfs_lsvolRequest;
import org.xtreemfs.interfaces.MRCInterface.xtreemfs_lsvolResponse;
import org.xtreemfs.interfaces.MRCInterface.xtreemfs_mkvolRequest;
import org.xtreemfs.interfaces.MRCInterface.xtreemfs_mkvolResponse;
import org.xtreemfs.interfaces.MRCInterface.xtreemfs_renew_capabilityRequest;
import org.xtreemfs.interfaces.MRCInterface.xtreemfs_renew_capabilityResponse;
import org.xtreemfs.interfaces.MRCInterface.xtreemfs_replica_addRequest;
import org.xtreemfs.interfaces.MRCInterface.xtreemfs_replica_addResponse;
import org.xtreemfs.interfaces.MRCInterface.xtreemfs_replica_removeRequest;
import org.xtreemfs.interfaces.MRCInterface.xtreemfs_replica_removeResponse;
import org.xtreemfs.interfaces.MRCInterface.xtreemfs_restore_databaseRequest;
import org.xtreemfs.interfaces.MRCInterface.xtreemfs_restore_databaseResponse;
import org.xtreemfs.interfaces.MRCInterface.xtreemfs_restore_fileRequest;
import org.xtreemfs.interfaces.MRCInterface.xtreemfs_restore_fileResponse;
import org.xtreemfs.interfaces.MRCInterface.xtreemfs_rmvolRequest;
import org.xtreemfs.interfaces.MRCInterface.xtreemfs_rmvolResponse;
import org.xtreemfs.interfaces.MRCInterface.xtreemfs_shutdownRequest;
import org.xtreemfs.interfaces.MRCInterface.xtreemfs_shutdownResponse;
import org.xtreemfs.interfaces.MRCInterface.xtreemfs_update_file_sizeRequest;
import org.xtreemfs.interfaces.MRCInterface.xtreemfs_update_file_sizeResponse;
/**
*
* @author bjko
*/
public class MRCClient extends ONCRPCClient {
public MRCClient(RPCNIOSocketClient client, InetSocketAddress defaultServer) {
super(client, defaultServer, 1, MRCInterface.getVersion());
}
/* admin calls */
public RPCResponse xtreemfs_shutdown(InetSocketAddress server, UserCredentials credentials) {
xtreemfs_shutdownRequest rq = new xtreemfs_shutdownRequest();
RPCResponse r = sendRequest(server, rq.getTag(), rq, new RPCResponseDecoder() {
@Override
public Object getResult(ReusableBuffer data) {
final xtreemfs_shutdownResponse resp = new xtreemfs_shutdownResponse();
resp.deserialize(data);
return null;
}
}, credentials);
return r;
}
public RPCResponse xtreemfs_checkpoint(InetSocketAddress server, UserCredentials credentials) {
xtreemfs_checkpointRequest rq = new xtreemfs_checkpointRequest();
RPCResponse r = sendRequest(server, rq.getTag(), rq, new RPCResponseDecoder() {
@Override
public Object getResult(ReusableBuffer data) {
final xtreemfs_checkpointResponse resp = new xtreemfs_checkpointResponse();
resp.deserialize(data);
return null;
}
}, credentials);
return r;
}
public RPCResponse xtreemfs_dump_database(InetSocketAddress server, UserCredentials credentials,
String dumpFile) {
xtreemfs_dump_databaseRequest rq = new xtreemfs_dump_databaseRequest(dumpFile);
RPCResponse r = sendRequest(server, rq.getTag(), rq, new RPCResponseDecoder() {
@Override
public Object getResult(ReusableBuffer data) {
final xtreemfs_dump_databaseResponse resp = new xtreemfs_dump_databaseResponse();
resp.deserialize(data);
return null;
}
}, credentials);
return r;
}
public RPCResponse xtreemfs_restore_database(InetSocketAddress server, UserCredentials credentials,
String dumpFile) {
xtreemfs_restore_databaseRequest rq = new xtreemfs_restore_databaseRequest(dumpFile);
RPCResponse r = sendRequest(server, rq.getTag(), rq, new RPCResponseDecoder() {
@Override
public Object getResult(ReusableBuffer data) {
final xtreemfs_restore_databaseResponse resp = new xtreemfs_restore_databaseResponse();
resp.deserialize(data);
return null;
}
}, credentials);
return r;
}
/* POSIX metadata calls */
public RPCResponse<Boolean> access(InetSocketAddress server, UserCredentials credentials, String path,
int mode) {
accessRequest rq = new accessRequest(path, mode);
RPCResponse<Boolean> r = sendRequest(server, rq.getTag(), rq, new RPCResponseDecoder<Boolean>() {
@Override
public Boolean getResult(ReusableBuffer data) {
final accessResponse resp = new accessResponse();
resp.deserialize(data);
return resp.getReturnValue();
}
}, credentials);
return r;
}
public RPCResponse chmod(InetSocketAddress server, UserCredentials credentials, String path, int mode) {
chmodRequest rq = new chmodRequest(path, mode);
RPCResponse r = sendRequest(server, rq.getTag(), rq, new RPCResponseDecoder() {
@Override
public Object getResult(ReusableBuffer data) {
final chmodResponse resp = new chmodResponse();
resp.deserialize(data);
return null;
}
}, credentials);
return r;
}
public RPCResponse chown(InetSocketAddress server, UserCredentials credentials, String path,
String newUID, String newGID) {
chownRequest rq = new chownRequest(path, newUID, newGID);
RPCResponse r = sendRequest(server, rq.getTag(), rq, new RPCResponseDecoder() {
@Override
public Object getResult(ReusableBuffer data) {
final chownResponse resp = new chownResponse();
resp.deserialize(data);
return null;
}
}, credentials);
return r;
}
public RPCResponse create(InetSocketAddress server, UserCredentials credentials, String path, int mode) {
creatRequest rq = new creatRequest(path, mode);
RPCResponse r = sendRequest(server, rq.getTag(), rq, new RPCResponseDecoder() {
@Override
public Object getResult(ReusableBuffer data) {
final creatResponse resp = new creatResponse();
resp.deserialize(data);
return null;
}
}, credentials);
return r;
}
public RPCResponse<XCap> ftruncate(InetSocketAddress server, XCap writeCap) {
ftruncateRequest rq = new ftruncateRequest(writeCap);
RPCResponse<XCap> r = sendRequest(server, rq.getTag(), rq, new RPCResponseDecoder<XCap>() {
@Override
public XCap getResult(ReusableBuffer data) {
final ftruncateResponse resp = new ftruncateResponse();
resp.deserialize(data);
return resp.getTruncate_xcap();
}
});
return r;
}
public RPCResponse<Stat> getattr(InetSocketAddress server, UserCredentials credentials, String path) {
getattrRequest rq = new getattrRequest(path);
RPCResponse<Stat> r = sendRequest(server, rq.getTag(), rq, new RPCResponseDecoder<Stat>() {
@Override
public Stat getResult(ReusableBuffer data) {
final getattrResponse resp = new getattrResponse();
resp.deserialize(data);
return resp.getStbuf();
}
}, credentials);
return r;
}
public RPCResponse<String> getxattr(InetSocketAddress server, UserCredentials credentials, String path,
String name) {
getxattrRequest rq = new getxattrRequest(path, name);
RPCResponse<String> r = sendRequest(server, rq.getTag(), rq, new RPCResponseDecoder<String>() {
@Override
public String getResult(ReusableBuffer data) {
final getxattrResponse resp = new getxattrResponse();
resp.deserialize(data);
return resp.getValue();
}
}, credentials);
return r;
}
public RPCResponse link(InetSocketAddress server, UserCredentials credentials, String targetPath,
String linkPath) {
linkRequest rq = new linkRequest(targetPath, linkPath);
RPCResponse r = sendRequest(server, rq.getTag(), rq, new RPCResponseDecoder() {
@Override
public Object getResult(ReusableBuffer data) {
final linkResponse resp = new linkResponse();
resp.deserialize(data);
return null;
}
}, credentials);
return r;
}
public RPCResponse<StringSet> listxattr(InetSocketAddress server, UserCredentials credentials, String path) {
listxattrRequest rq = new listxattrRequest(path);
RPCResponse<StringSet> r = sendRequest(server, rq.getTag(), rq, new RPCResponseDecoder<StringSet>() {
@Override
public StringSet getResult(ReusableBuffer data) {
final listxattrResponse resp = new listxattrResponse();
resp.deserialize(data);
return resp.getNames();
}
}, credentials);
return r;
}
public RPCResponse<VolumeSet> lsvol(InetSocketAddress server, UserCredentials credentials) {
xtreemfs_lsvolRequest rq = new xtreemfs_lsvolRequest();
RPCResponse<VolumeSet> r = sendRequest(server, rq.getTag(), rq, new RPCResponseDecoder<VolumeSet>() {
@Override
public VolumeSet getResult(ReusableBuffer data) {
final xtreemfs_lsvolResponse resp = new xtreemfs_lsvolResponse();
resp.deserialize(data);
return resp.getVolumes();
}
}, credentials);
return r;
}
public RPCResponse mkdir(InetSocketAddress server, UserCredentials credentials, String path, int mode) {
mkdirRequest rq = new mkdirRequest(path, mode);
RPCResponse r = sendRequest(server, rq.getTag(), rq, new RPCResponseDecoder() {
@Override
public Object getResult(ReusableBuffer data) {
final mkdirResponse resp = new mkdirResponse();
resp.deserialize(data);
return null;
}
}, credentials);
return r;
}
public RPCResponse mkvol(InetSocketAddress server, UserCredentials credentials, String volumeName,
int osdSelectionPolicy, StripingPolicy defaultStripingPolicy, int accessControlPolicy, int accessMode) {
xtreemfs_mkvolRequest rq = new xtreemfs_mkvolRequest(new Volume(volumeName, accessMode,
OSDSelectionPolicyType.parseInt(osdSelectionPolicy), defaultStripingPolicy,
AccessControlPolicyType.parseInt(accessControlPolicy), "", "", ""));
RPCResponse r = sendRequest(server, rq.getTag(), rq, new RPCResponseDecoder() {
@Override
public Object getResult(ReusableBuffer data) {
final xtreemfs_mkvolResponse resp = new xtreemfs_mkvolResponse();
resp.deserialize(data);
return null;
}
}, credentials);
return r;
}
public RPCResponse<FileCredentials> open(InetSocketAddress server, UserCredentials credentials,
String path, int flags, int mode, int w32attrs) {
openRequest rq = new openRequest(path, flags, mode, w32attrs);
RPCResponse<FileCredentials> r = sendRequest(server, rq.getTag(), rq,
new RPCResponseDecoder<FileCredentials>() {
@Override
public FileCredentials getResult(ReusableBuffer data) {
final openResponse resp = new openResponse();
resp.deserialize(data);
return resp.getFile_credentials();
}
}, credentials);
return r;
}
public RPCResponse<DirectoryEntrySet> readdir(InetSocketAddress server, UserCredentials credentials,
String path) {
readdirRequest rq = new readdirRequest(path);
RPCResponse<DirectoryEntrySet> r = sendRequest(server, rq.getTag(), rq,
new RPCResponseDecoder<DirectoryEntrySet>() {
@Override
public DirectoryEntrySet getResult(ReusableBuffer data) {
final readdirResponse resp = new readdirResponse();
resp.deserialize(data);
return resp.getDirectory_entries();
}
}, credentials);
return r;
}
public RPCResponse removexattr(InetSocketAddress server, UserCredentials credentials, String path,
String name) {
removexattrRequest rq = new removexattrRequest(path, name);
RPCResponse r = sendRequest(server, rq.getTag(), rq, new RPCResponseDecoder() {
@Override
public Object getResult(ReusableBuffer data) {
final removexattrResponse resp = new removexattrResponse();
resp.deserialize(data);
return null;
}
}, credentials);
return r;
}
public RPCResponse<FileCredentialsSet> rename(InetSocketAddress server, UserCredentials credentials,
String sourcePath, String targetPath) {
renameRequest rq = new renameRequest(sourcePath, targetPath);
RPCResponse<FileCredentialsSet> r = sendRequest(server, rq.getTag(), rq,
new RPCResponseDecoder<FileCredentialsSet>() {
@Override
public FileCredentialsSet getResult(ReusableBuffer data) {
final renameResponse resp = new renameResponse();
resp.deserialize(data);
return resp.getFile_credentials();
}
}, credentials);
return r;
}
public RPCResponse rmdir(InetSocketAddress server, UserCredentials credentials, String path) {
rmdirRequest rq = new rmdirRequest(path);
RPCResponse r = sendRequest(server, rq.getTag(), rq, new RPCResponseDecoder() {
@Override
public Object getResult(ReusableBuffer data) {
final rmdirResponse resp = new rmdirResponse();
resp.deserialize(data);
return null;
}
}, credentials);
return r;
}
public RPCResponse rmvol(InetSocketAddress server, UserCredentials credentials, String volumeName) {
xtreemfs_rmvolRequest rq = new xtreemfs_rmvolRequest(volumeName);
RPCResponse r = sendRequest(server, rq.getTag(), rq, new RPCResponseDecoder() {
@Override
public Object getResult(ReusableBuffer data) {
final xtreemfs_rmvolResponse resp = new xtreemfs_rmvolResponse();
resp.deserialize(data);
return null;
}
}, credentials);
return r;
}
public RPCResponse setattr(InetSocketAddress server, UserCredentials credentials, String path,
Stat statInfo) {
setattrRequest rq = new setattrRequest(path, statInfo);
RPCResponse r = sendRequest(server, rq.getTag(), rq, new RPCResponseDecoder() {
@Override
public Object getResult(ReusableBuffer data) {
final setattrResponse resp = new setattrResponse();
resp.deserialize(data);
return null;
}
}, credentials);
return r;
}
public RPCResponse setxattr(InetSocketAddress server, UserCredentials credentials, String path,
String name, String value, int flags) {
setxattrRequest rq = new setxattrRequest(path, name, value, flags);
RPCResponse r = sendRequest(server, rq.getTag(), rq, new RPCResponseDecoder() {
@Override
public Object getResult(ReusableBuffer data) {
final setxattrResponse resp = new setxattrResponse();
resp.deserialize(data);
return null;
}
}, credentials);
return r;
}
public RPCResponse<StatVFS> statfs(InetSocketAddress server, UserCredentials credentials,
String volumeName) {
statvfsRequest rq = new statvfsRequest(volumeName);
RPCResponse<StatVFS> r = sendRequest(server, rq.getTag(), rq, new RPCResponseDecoder<StatVFS>() {
@Override
public StatVFS getResult(ReusableBuffer data) {
final statvfsResponse resp = new statvfsResponse();
resp.deserialize(data);
return resp.getStbuf();
}
}, credentials);
return r;
}
public RPCResponse symlink(InetSocketAddress server, UserCredentials credentials, String targetPath,
String linkPath) {
symlinkRequest rq = new symlinkRequest(targetPath, linkPath);
RPCResponse r = sendRequest(server, rq.getTag(), rq, new RPCResponseDecoder() {
@Override
public Object getResult(ReusableBuffer data) {
final symlinkResponse resp = new symlinkResponse();
resp.deserialize(data);
return null;
}
}, credentials);
return r;
}
public RPCResponse<FileCredentialsSet> unlink(InetSocketAddress server, UserCredentials credentials,
String path) {
unlinkRequest rq = new unlinkRequest(path);
RPCResponse<FileCredentialsSet> r = sendRequest(server, rq.getTag(), rq,
new RPCResponseDecoder<FileCredentialsSet>() {
@Override
public FileCredentialsSet getResult(ReusableBuffer data) {
final unlinkResponse resp = new unlinkResponse();
resp.deserialize(data);
return resp.getFile_credentials();
}
}, credentials);
return r;
}
public RPCResponse utime(InetSocketAddress server, UserCredentials credentials, String path, long atime,
long ctime, long mtime) {
utimensRequest rq = new utimensRequest(path, atime, ctime, mtime);
RPCResponse r = sendRequest(server, rq.getTag(), rq, new RPCResponseDecoder() {
@Override
public Object getResult(ReusableBuffer data) {
final utimensResponse resp = new utimensResponse();
resp.deserialize(data);
return null;
}
}, credentials);
return r;
}
/* xtreemfs-specific calls */
public RPCResponse<String> xtreemfs_checkFileExists(InetSocketAddress server, String volumeId,
StringSet fileIds) {
xtreemfs_check_file_existsRequest rq = new xtreemfs_check_file_existsRequest(volumeId, fileIds);
RPCResponse<String> r = sendRequest(server, rq.getTag(), rq, new RPCResponseDecoder<String>() {
@Override
public String getResult(ReusableBuffer data) {
final xtreemfs_check_file_existsResponse resp = new xtreemfs_check_file_existsResponse();
resp.deserialize(data);
return resp.getBitmap();
}
});
return r;
}
public RPCResponse<String> xtreemfs_internal_debug(InetSocketAddress server, UserCredentials creds, String cmd) {
xtreemfs_internal_debugRequest rq = new xtreemfs_internal_debugRequest(cmd);
RPCResponse<String> r = sendRequest(server, rq.getTag(), rq,
new RPCResponseDecoder<String>() {
@Override
public String getResult(ReusableBuffer data) {
final xtreemfs_internal_debugResponse resp = new xtreemfs_internal_debugResponse();
resp.deserialize(data);
return resp.getResult();
}
},creds);
return r;
}
public RPCResponse<StringSet> xtreemfs_get_suitable_osds(InetSocketAddress server, String fileId) {
xtreemfs_get_suitable_osdsRequest rq = new xtreemfs_get_suitable_osdsRequest(fileId);
RPCResponse<StringSet> r = sendRequest(server, rq.getTag(), rq, new RPCResponseDecoder<StringSet>() {
@Override
public StringSet getResult(ReusableBuffer data) {
final xtreemfs_get_suitable_osdsResponse resp = new xtreemfs_get_suitable_osdsResponse();
resp.deserialize(data);
return resp.getOsd_uuids();
}
});
return r;
}
public RPCResponse<XCap> xtreemfs_renew_capability(InetSocketAddress server, XCap capability) {
xtreemfs_renew_capabilityRequest rq = new xtreemfs_renew_capabilityRequest(capability);
RPCResponse<XCap> r = sendRequest(server, rq.getTag(), rq, new RPCResponseDecoder<XCap>() {
@Override
public XCap getResult(ReusableBuffer data) {
final xtreemfs_renew_capabilityResponse resp = new xtreemfs_renew_capabilityResponse();
resp.deserialize(data);
return resp.getRenewed_xcap();
}
});
return r;
}
public RPCResponse xtreemfs_replica_add(InetSocketAddress server, UserCredentials credentials,
String fileId, Replica newReplica) {
xtreemfs_replica_addRequest rq = new xtreemfs_replica_addRequest(fileId, newReplica);
RPCResponse r = sendRequest(server, rq.getTag(), rq, new RPCResponseDecoder() {
@Override
public Object getResult(ReusableBuffer data) {
final xtreemfs_replica_addResponse resp = new xtreemfs_replica_addResponse();
resp.deserialize(data);
return null;
}
}, credentials);
return r;
}
public RPCResponse<XCap> xtreemfs_replica_remove(InetSocketAddress server, UserCredentials credentials,
String fileId, String osdUUID) {
xtreemfs_replica_removeRequest rq = new xtreemfs_replica_removeRequest(fileId, osdUUID);
RPCResponse<XCap> r = sendRequest(server, rq.getTag(), rq, new RPCResponseDecoder() {
@Override
public Object getResult(ReusableBuffer data) {
final xtreemfs_replica_removeResponse resp = new xtreemfs_replica_removeResponse();
resp.deserialize(data);
return resp.getDelete_xcap();
}
}, credentials);
return r;
}
public RPCResponse xtreemfs_restore_file(InetSocketAddress server, String filePath, String fileId,
long fileSizeInBytes, String osdUUID, int stripeSizeInKB, UserCredentials credentials) {
xtreemfs_restore_fileRequest rq = new xtreemfs_restore_fileRequest(filePath, fileId, fileSizeInBytes,
osdUUID, stripeSizeInKB);
RPCResponse r = sendRequest(server, rq.getTag(), rq, new RPCResponseDecoder() {
@Override
public Object getResult(ReusableBuffer data) {
final xtreemfs_restore_fileResponse resp = new xtreemfs_restore_fileResponse();
resp.deserialize(data);
return null;
}
}, credentials);
return r;
}
public RPCResponse xtreemfs_update_file_size(InetSocketAddress server, XCap xcap,
OSDWriteResponse newFileSize) {
xtreemfs_update_file_sizeRequest rq = new xtreemfs_update_file_sizeRequest(xcap, newFileSize);
RPCResponse r = sendRequest(server, rq.getTag(), rq, new RPCResponseDecoder() {
@Override
public Object getResult(ReusableBuffer data) {
final xtreemfs_update_file_sizeResponse resp = new xtreemfs_update_file_sizeResponse();
resp.deserialize(data);
return null;
}
});
return r;
}
public static UserCredentials getCredentials(String uid, List<String> gids) {
StringSet gidsAsSet = new StringSet();
for (String gid : gids)
gidsAsSet.add(gid);
return new UserCredentials(uid, gidsAsSet, "");
}
}
|
// This file is part of the OpenNMS(R) Application.
// OpenNMS(R) is a derivative work, containing both original code, included code and modified
// and included code are below.
// OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
// Modifications:
// 2003 Jan 31: Cleaned up some unused imports.
// 2003 Jan 08: Added code to associate the IP address in traps with nodes
// and added the option to discover nodes based on traps.
// This program is free software; you can redistribute it and/or modify
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
// For more information contact:
package org.opennms.netmgt.trapd;
import java.lang.reflect.UndeclaredThrowableException;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Map;
import org.apache.log4j.Category;
import org.opennms.core.fiber.PausableFiber;
import org.opennms.core.queue.FifoQueue;
import org.opennms.core.queue.FifoQueueException;
import org.opennms.core.queue.FifoQueueImpl;
import org.opennms.core.utils.ThreadCategory;
import org.opennms.netmgt.config.TrapdConfig;
import org.opennms.netmgt.eventd.EventIpcManager;
import org.opennms.protocols.snmp.SnmpOctetString;
import org.opennms.protocols.snmp.SnmpPduPacket;
import org.opennms.protocols.snmp.SnmpPduTrap;
import org.opennms.protocols.snmp.SnmpTrapHandler;
import org.opennms.protocols.snmp.SnmpTrapSession;
public class TrapHandler implements SnmpTrapHandler, PausableFiber {
/**
* The name of the logging category for Trapd.
*/
private static final String LOG4J_CATEGORY = "OpenNMS.TrapHandler";
/**
* The singlton instance.
*/
private static final TrapHandler m_singleton = new TrapHandler();
/**
* Set the Trapd configuration
*/
private TrapdConfig m_trapdConfig;
/**
* Event manager
*/
private EventIpcManager m_eventMgr;
/**
* The trap session used by Trapd to receive traps
*/
private SnmpTrapSession m_trapSession;
/**
* The name of this service.
*/
private String m_name = LOG4J_CATEGORY;
/**
* The last status sent to the service control manager.
*/
private int m_status = START_PENDING;
/**
* The communication queue
*/
private FifoQueue m_backlogQ;
/**
* The list of known IPs
*/
private Map m_knownIps;
/**
* The queue processing thread
*/
private TrapQueueProcessor m_processor;
/**
* The class instance used to recieve new events from for the system.
*/
private BroadcastEventProcessor m_eventReader;
/**
* <P>
* Constructs a new Trapd object that receives and forwards trap messages
* via JSDT. The session is initialized with the default client name of <EM>
* OpenNMS.trapd</EM>. The trap session is started on the default port, as
* defined by the SNMP libarary.
* </P>
*
* @see org.opennms.protocols.snmp.SnmpTrapSession
*/
public TrapHandler() {
}
public void setTrapdConfig(TrapdConfig trapdConfig) {
m_trapdConfig = trapdConfig;
}
/**
* <P>
* Process the recieved SNMP v2c trap that was received by the underlying
* trap session.
* </P>
*
* @param session
* The trap session that received the datagram.
* @param agent
* The remote agent that sent the datagram.
* @param port
* The remmote port the trap was sent from.
* @param community
* The community string contained in the message.
* @param pdu
* The protocol data unit containing the data
*
*/
public void snmpReceivedTrap(SnmpTrapSession session, InetAddress agent,
int port, SnmpOctetString community, SnmpPduPacket pdu) {
addTrap(new V2TrapInformation(agent, community, pdu));
}
/**
* <P>
* Process the recieved SNMP v1 trap that was received by the underlying
* trap session.
* </P>
*
* @param session
* The trap session that received the datagram.
* @param agent
* The remote agent that sent the datagram.
* @param port
* The remmote port the trap was sent from.
* @param community
* The community string contained in the message.
* @param pdu
* The protocol data unit containing the data
*
*/
public void snmpReceivedTrap(SnmpTrapSession session, InetAddress agent,
int port, SnmpOctetString community, SnmpPduTrap pdu) {
addTrap(new V1TrapInformation(agent, community, pdu));
}
private void addTrap(Object o) {
try {
m_backlogQ.add(o);
} catch (InterruptedException ie) {
Category log = ThreadCategory.getInstance(getClass());
log.warn("snmpReceivedTrap: Error adding trap to queue, it was interrupted", ie);
} catch (FifoQueueException qe) {
Category log = ThreadCategory.getInstance(getClass());
log.warn("snmpReceivedTrap: Error adding trap to queue", qe);
}
}
/**
* <P>
* Processes an error condition that occurs in the SnmpTrapSession. The
* errors are logged and ignored by the trapd class.
* </P>
*/
public void snmpTrapSessionError(SnmpTrapSession session, int error,
Object ref) {
Category log = ThreadCategory.getInstance(getClass());
log.warn("Error Processing Received Trap: error = " + error
+ (ref != null ? ", ref = " + ref.toString() : ""));
}
public synchronized void init() {
ThreadCategory.setPrefix(LOG4J_CATEGORY);
Category log = ThreadCategory.getInstance();
try {
// Get the newSuspectOnTrap flag
boolean m_newSuspect = m_trapdConfig.getNewSuspectOnTrap();
// set up the trap processor
m_backlogQ = new FifoQueueImpl();
m_processor = new TrapQueueProcessor(m_backlogQ, m_newSuspect, m_eventMgr);
log.debug("start: Creating the trap queue processor");
// Initialize the trapd session
m_trapSession = new SnmpTrapSession(this, m_trapdConfig
.getSnmpTrapPort());
log.debug("start: Creating the trap session");
} catch (SocketException e) {
log.error("Failed to setup SNMP trap port", e);
throw new UndeclaredThrowableException(e);
}
// Is this ever used?
/*
try {
m_eventReader = new BroadcastEventProcessor();
} catch (Exception ex) {
ThreadCategory.getInstance().error("Failed to create event reader",
ex);
throw new UndeclaredThrowableException(ex);
}
*/
}
/**
* Create the SNMP trap session and create the JSDT communication channel to
* communicate with eventd.
*
* @exception java.lang.reflect.UndeclaredThrowableException
* if an unexpected database, or IO exception occurs.
*
* @see org.opennms.protocols.snmp.SnmpTrapSession
* @see org.opennms.protocols.snmp.SnmpTrapHandler
*/
public synchronized void start() {
m_status = STARTING;
ThreadCategory.setPrefix(LOG4J_CATEGORY);
Category log = ThreadCategory.getInstance();
log.debug("start: Initializing the trapd config factory");
m_processor.start();
m_status = RUNNING;
log.debug("start: Trapd ready to receive traps");
}
/**
* Pauses Trapd
*/
public void pause() {
if (m_status != RUNNING) {
return;
}
m_status = PAUSE_PENDING;
Category log = ThreadCategory.getInstance(getClass());
log.debug("Calling pause on processor");
m_processor.pause();
log.debug("Processor paused");
m_status = PAUSED;
log.debug("Trapd paused");
}
/**
* Resumes Trapd
*/
public void resume() {
if (m_status != PAUSED) {
return;
}
m_status = RESUME_PENDING;
Category log = ThreadCategory.getInstance(getClass());
log.debug("Calling resume on processor");
m_processor.resume();
log.debug("Processor resumed");
m_status = RUNNING;
log.debug("Trapd resumed");
}
/**
* Stops the currently running service. If the service is not running then
* the command is silently discarded.
*/
public synchronized void stop() {
Category log = ThreadCategory.getInstance(getClass());
m_status = STOP_PENDING;
// shutdown and wait on the background processing thread to exit.
log.debug("exit: closing communication paths.");
try {
log.debug("stop: Closing SNMP trap session.");
m_trapSession.close();
log.debug("stop: SNMP trap session closed.");
} catch (IllegalStateException e) {
log.debug("stop: The SNMP session was already closed");
}
log.debug("stop: Stopping queue processor.");
// interrupt the processor daemon thread
m_processor.stop();
m_status = STOPPED;
log.debug("stop: Trapd stopped");
}
/**
* Returns the current status of the service.
*
* @return The service's status.
*/
public synchronized int getStatus() {
return m_status;
}
/**
* Returns the singular instance of the trapd daemon. There can be only one
* instance of this service per virtual machine.
*/
public static TrapHandler getInstance() {
return m_singleton;
}
/**
* Returns the name of the service.
*
* @return The service's name.
*/
public String getName() {
return m_name;
}
public EventIpcManager getEventManager() {
return m_eventMgr;
}
public void setEventManager(EventIpcManager eventMgr) {
m_eventMgr = eventMgr;
}
}
|
package sofia.graphics.internal;
import java.util.HashMap;
import sofia.graphics.Shape;
import sofia.graphics.ShapeView;
import java.util.Iterator;
import java.util.concurrent.ConcurrentLinkedQueue;
/**
* Manages animations for all shapes system-wide.
*
* @author Tony Allevato
* @version 2011.12.04
*/
public class ShapeAnimationManager
{
public static final String TESTING_MODE_PROPERTY =
"sofia.graphics.testingMode";
private ShapeView view;
private boolean running;
private Object animatorToken = new Object();
private ConcurrentLinkedQueue<Shape.Animator<?>> animators =
new ConcurrentLinkedQueue<Shape.Animator<?>>();
private HashMap<Shape, Shape.Animator<?>> currentAnimators =
new HashMap<Shape, Shape.Animator<?>>();
/**
* Not intended for public use.
*/
public ShapeAnimationManager(ShapeView view)
{
this.view = view;
running = true;
}
public synchronized void setRunning(boolean value)
{
running = value;
}
public synchronized boolean isRunning()
{
return running;
}
public void enqueue(Shape.Animator<?> animator)
{
if (isTestingMode())
{
// Just run the animator instantaneously.
long endTime = System.currentTimeMillis()
+ animator.getDelay() + animator.getDuration();
animator.advanceTo(endTime);
}
else
{
Shape shape = animator.getShape();
if (currentAnimators.containsKey(shape))
{
currentAnimators.get(shape).stop();
}
currentAnimators.put(shape, animator);
animators.offer(animator);
synchronized (animatorToken)
{
animatorToken.notify();
}
}
}
public void stop(Shape shape)
{
Shape.Animator<?> animator = currentAnimators.get(shape);
if (animator != null)
{
animator.stop();
}
}
public void start()
{
if (!isTestingMode())
{
new ProductionThread().start();
}
}
private boolean isTestingMode()
{
String testingProp = System.getProperty(
TESTING_MODE_PROPERTY, "false");
return Boolean.parseBoolean(testingProp);
}
private class ProductionThread extends Thread
{
@Override
public void run()
{
while (running)
{
waitForSignal();
view.internalSetAutoRepaintForThread(false);
while (!animators.isEmpty())
{
long start = System.currentTimeMillis();
Iterator<Shape.Animator<?>> it = animators.iterator();
while (it.hasNext())
{
Shape.Animator<?> animator = it.next();
Shape shape = animator.getShape();
boolean ended =
animator.advanceTo(start);
if (ended)
{
it.remove();
if (currentAnimators.get(shape) == animator)
{
currentAnimators.remove(shape);
}
}
}
view.repaint();
long end = System.currentTimeMillis();
long length = end - start;
long FRAME_TIME = 20;
if (length < FRAME_TIME)
{
try
{
Thread.sleep(FRAME_TIME - length);
}
catch (InterruptedException e)
{
// Do nothing.
}
}
end = System.currentTimeMillis();
}
view.internalSetAutoRepaintForThread(true);
}
}
}
private void waitForSignal()
{
synchronized (animatorToken)
{
while (animators.isEmpty())
{
try
{
animatorToken.wait();
}
catch (InterruptedException e)
{
// Do nothing.
}
}
}
}
}
|
package soot.jimple.infoflow.problems;
import heros.FlowFunction;
import heros.FlowFunctions;
import heros.TwoElementSet;
import heros.flowfunc.Identity;
import heros.flowfunc.KillAll;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import soot.ArrayType;
import soot.BooleanType;
import soot.IntType;
import soot.Local;
import soot.NullType;
import soot.PrimType;
import soot.RefType;
import soot.SootField;
import soot.SootMethod;
import soot.Type;
import soot.Unit;
import soot.Value;
import soot.ValueBox;
import soot.jimple.ArrayRef;
import soot.jimple.AssignStmt;
import soot.jimple.CastExpr;
import soot.jimple.CaughtExceptionRef;
import soot.jimple.Constant;
import soot.jimple.DefinitionStmt;
import soot.jimple.FieldRef;
import soot.jimple.IdentityStmt;
import soot.jimple.IfStmt;
import soot.jimple.InstanceFieldRef;
import soot.jimple.InstanceInvokeExpr;
import soot.jimple.InstanceOfExpr;
import soot.jimple.InvokeExpr;
import soot.jimple.LengthExpr;
import soot.jimple.LookupSwitchStmt;
import soot.jimple.NewArrayExpr;
import soot.jimple.ReturnStmt;
import soot.jimple.StaticFieldRef;
import soot.jimple.Stmt;
import soot.jimple.TableSwitchStmt;
import soot.jimple.ThrowStmt;
import soot.jimple.infoflow.InfoflowConfiguration;
import soot.jimple.infoflow.aliasing.Aliasing;
import soot.jimple.infoflow.aliasing.IAliasingStrategy;
import soot.jimple.infoflow.aliasing.ImplicitFlowAliasStrategy;
import soot.jimple.infoflow.collect.ConcurrentHashSet;
import soot.jimple.infoflow.collect.MyConcurrentHashMap;
import soot.jimple.infoflow.data.Abstraction;
import soot.jimple.infoflow.data.AbstractionAtSink;
import soot.jimple.infoflow.data.AccessPath;
import soot.jimple.infoflow.handlers.TaintPropagationHandler;
import soot.jimple.infoflow.handlers.TaintPropagationHandler.FlowFunctionType;
import soot.jimple.infoflow.solver.cfg.IInfoflowCFG;
import soot.jimple.infoflow.solver.cfg.IInfoflowCFG.UnitContainer;
import soot.jimple.infoflow.solver.cfg.InfoflowCFG;
import soot.jimple.infoflow.solver.functions.SolverCallFlowFunction;
import soot.jimple.infoflow.solver.functions.SolverCallToReturnFlowFunction;
import soot.jimple.infoflow.solver.functions.SolverNormalFlowFunction;
import soot.jimple.infoflow.solver.functions.SolverReturnFlowFunction;
import soot.jimple.infoflow.source.ISourceSinkManager;
import soot.jimple.infoflow.source.SourceInfo;
import soot.jimple.infoflow.util.BaseSelector;
import soot.jimple.infoflow.util.SystemClassHandler;
public class InfoflowProblem extends AbstractInfoflowProblem {
private final Aliasing aliasing;
private final IAliasingStrategy aliasingStrategy;
private final IAliasingStrategy implicitFlowAliasingStrategy;
private final MyConcurrentHashMap<Unit, Set<Abstraction>> implicitTargets =
new MyConcurrentHashMap<Unit, Set<Abstraction>>();
protected final MyConcurrentHashMap<AbstractionAtSink, Abstraction> results =
new MyConcurrentHashMap<AbstractionAtSink, Abstraction>();
public InfoflowProblem(InfoflowConfiguration config,
ISourceSinkManager sourceSinkManager,
IAliasingStrategy aliasingStrategy) {
this(config, new InfoflowCFG(), sourceSinkManager, aliasingStrategy);
}
public InfoflowProblem(InfoflowConfiguration config,
ISourceSinkManager mySourceSinkManager,
Set<Unit> analysisSeeds,
IAliasingStrategy aliasingStrategy) {
this(config, new InfoflowCFG(), mySourceSinkManager, aliasingStrategy);
for (Unit u : analysisSeeds)
this.initialSeeds.put(u, Collections.singleton(getZeroValue()));
}
public InfoflowProblem(InfoflowConfiguration config,
IInfoflowCFG icfg,
ISourceSinkManager sourceSinkManager,
IAliasingStrategy aliasingStrategy) {
super(config, icfg, sourceSinkManager);
this.aliasingStrategy = aliasingStrategy;
this.implicitFlowAliasingStrategy = new ImplicitFlowAliasStrategy(icfg);
this.aliasing = new Aliasing(aliasingStrategy, icfg);
}
/**
* Computes the taints produced by a taint wrapper object
* @param d1 The context (abstraction at the method's start node)
* @param iStmt The call statement the taint wrapper shall check for well-
* known methods that introduce black-box taint propagation
* @param source The taint source
* @return The taints computed by the wrapper
*/
private Set<Abstraction> computeWrapperTaints
(Abstraction d1,
final Stmt iStmt,
Abstraction source) {
assert config.getInspectSources() || source != getZeroValue();
// If we don't have a taint wrapper, there's nothing we can do here
if(taintWrapper == null)
return Collections.emptySet();
// Do not check taints that are not mentioned anywhere in the call
if (!source.getAccessPath().isStaticFieldRef()
&& !source.getAccessPath().isEmpty()) {
boolean found = false;
// The base object must be tainted
if (iStmt.getInvokeExpr() instanceof InstanceInvokeExpr) {
InstanceInvokeExpr iiExpr = (InstanceInvokeExpr) iStmt.getInvokeExpr();
found = aliasing.mayAlias(iiExpr.getBase(), source.getAccessPath().getPlainValue());
}
// or one of the parameters must be tainted
if (!found)
for (int paramIdx = 0; paramIdx < iStmt.getInvokeExpr().getArgCount(); paramIdx++)
if (aliasing.mayAlias(source.getAccessPath().getPlainValue(),
iStmt.getInvokeExpr().getArg(paramIdx))) {
found = true;
break;
}
// If nothing is tainted, we don't have any taints to propagate
if (!found)
return Collections.emptySet();
}
Set<Abstraction> res = taintWrapper.getTaintsForMethod(iStmt, d1, source);
if(res != null) {
Set<Abstraction> resWithAliases = new HashSet<>(res);
for (Abstraction abs : res) {
// The new abstraction gets activated where it was generated
if (!abs.equals(source)) {
// If the taint wrapper creates a new taint, this must be propagated
// backwards as there might be aliases for the base object
// Note that we don't only need to check for heap writes such as a.x = y,
// but also for base object taints ("a" in this case).
final AccessPath val = abs.getAccessPath();
boolean taintsObjectValue = val.getBaseType() instanceof RefType
&& abs.getAccessPath().getBaseType() instanceof RefType
&& !isStringType(val.getBaseType());
boolean taintsStaticField = config.getEnableStaticFieldTracking()
&& abs.getAccessPath().isStaticFieldRef();
// If the tainted value gets overwritten, it cannot have aliases afterwards
boolean taintedValueOverwritten = (iStmt instanceof DefinitionStmt)
? baseMatches(((DefinitionStmt) iStmt).getLeftOp(), abs) : false;
if (!taintedValueOverwritten)
if (taintsStaticField
|| (taintsObjectValue && abs.getAccessPath().getTaintSubFields())
|| triggerInaktiveTaintOrReverseFlow(iStmt, val.getPlainValue(), abs))
computeAliasTaints(d1, iStmt, val.getPlainValue(), resWithAliases,
interproceduralCFG().getMethodOf(iStmt), abs);
}
}
res = resWithAliases;
}
return res;
}
/**
* Computes the taints for the aliases of a given tainted variable
* @param d1 The context in which the variable has been tainted
* @param src The statement that tainted the variable
* @param targetValue The target value which has been tainted
* @param taintSet The set to which all generated alias taints shall be
* added
* @param method The method containing src
* @param newAbs The newly generated abstraction for the variable taint
* @return The set of immediately available alias abstractions. If no such
* abstractions exist, null is returned
*/
private void computeAliasTaints
(final Abstraction d1, final Stmt src,
final Value targetValue, Set<Abstraction> taintSet,
SootMethod method, Abstraction newAbs) {
// We never ever handle primitives as they can never have aliases
if (newAbs.getAccessPath().getLastFieldType() instanceof PrimType)
return;
// If we are not in a conditionally-called method, we run the
// full alias analysis algorithm. Otherwise, we use a global
// non-flow-sensitive approximation.
if (!d1.getAccessPath().isEmpty()) {
aliasingStrategy.computeAliasTaints(d1,
src, targetValue, taintSet, method, newAbs);
}
else if (targetValue instanceof InstanceFieldRef) {
assert config.getEnableImplicitFlows();
implicitFlowAliasingStrategy.computeAliasTaints(d1, src,
targetValue, taintSet, method, newAbs);
}
}
/**
* we cannot rely just on "real" heap objects, but must also inspect locals because of Jimple's representation ($r0 =... )
* @param val the value which gets tainted
* @param source the source from which the taints comes from. Important if not the value, but a field is tainted
* @return true if a reverseFlow should be triggered or an inactive taint should be propagated (= resulting object is stored in heap = alias)
*/
private boolean triggerInaktiveTaintOrReverseFlow(Stmt stmt, Value val, Abstraction source){
if (stmt instanceof DefinitionStmt) {
DefinitionStmt defStmt = (DefinitionStmt) stmt;
// If the left side is overwritten completely, we do not need to
// look for aliases. This also covers strings.
if (defStmt.getLeftOp() instanceof Local
&& defStmt.getLeftOp() == source.getAccessPath().getPlainValue())
return false;
// Arrays are heap objects
if (val instanceof ArrayRef)
return true;
if (val instanceof FieldRef)
return true;
}
// Primitive types or constants do not have aliases
if (val.getType() instanceof PrimType)
return false;
if (val instanceof Constant)
return false;
// String cannot have aliases
if (isStringType(val.getType()))
return false;
return val instanceof FieldRef
|| (val instanceof Local && ((Local)val).getType() instanceof ArrayType);
}
@Override
public FlowFunctions<Unit, Abstraction, SootMethod> createFlowFunctionsFactory() {
return new FlowFunctions<Unit, Abstraction, SootMethod>() {
/**
* Abstract base class for all normal flow functions. This is to
* share code that e.g. notifies the taint handlers between the
* various functions.
*
* @author Steven Arzt
*/
abstract class NotifyingNormalFlowFunction extends SolverNormalFlowFunction {
private final Stmt stmt;
public NotifyingNormalFlowFunction(Stmt stmt) {
this.stmt = stmt;
}
@Override
public Set<Abstraction> computeTargets(Abstraction d1, Abstraction source) {
if (config.getStopAfterFirstFlow() && !results.isEmpty())
return Collections.emptySet();
// Notify the handler if we have one
if (taintPropagationHandlers != null)
for (TaintPropagationHandler tp : taintPropagationHandlers)
tp.notifyFlowIn(stmt, source, interproceduralCFG(),
FlowFunctionType.NormalFlowFunction);
// Compute the new abstractions
Set<Abstraction> res = computeTargetsInternal(d1, source);
return notifyOutFlowHandlers(stmt, d1, source, res,
FlowFunctionType.NormalFlowFunction);
}
public abstract Set<Abstraction> computeTargetsInternal(Abstraction d1, Abstraction source);
}
/**
* Notifies the outbound flow handlers, if any, about the computed
* result abstractions for the current flow function
* @param d1 The abstraction at the beginning of the method
* @param stmt The statement that has just been processed
* @param incoming The incoming abstraction from which the outbound
* ones were computed
* @param outgoing The outbound abstractions to be propagated on
* @param functionType The type of flow function that was computed
* @return The outbound flow abstracions, potentially changed by the
* flow handlers
*/
private Set<Abstraction> notifyOutFlowHandlers(Unit stmt,
Abstraction d1,
Abstraction incoming,
Set<Abstraction> outgoing,
FlowFunctionType functionType) {
if (taintPropagationHandlers != null
&& outgoing != null
&& !outgoing.isEmpty())
for (TaintPropagationHandler tp : taintPropagationHandlers)
outgoing = tp.notifyFlowOut(stmt, d1, incoming, outgoing,
interproceduralCFG(), functionType);
return outgoing;
}
/**
* Taints the left side of the given assignment
* @param assignStmt The source statement from which the taint originated
* @param targetValue The target value that shall now be tainted
* @param source The incoming taint abstraction from the source
* @param taintSet The taint set to which to add all newly produced
* taints
*/
private void addTaintViaStmt
(final Abstraction d1,
final AssignStmt assignStmt,
Abstraction source,
Set<Abstraction> taintSet,
boolean cutFirstField,
SootMethod method,
Type targetType) {
final Value leftValue = assignStmt.getLeftOp();
final Value rightValue = assignStmt.getRightOp();
// Do not taint static fields unless the option is enabled
if (!config.getEnableStaticFieldTracking()
&& leftValue instanceof StaticFieldRef)
return;
Abstraction newAbs = null;
boolean isArrayLength = false;
if (!source.getAccessPath().isEmpty()) {
// Special handling for array (de)construction
if (leftValue instanceof ArrayRef && targetType != null)
targetType = buildArrayOrAddDimension(targetType);
else if (assignStmt.getRightOp() instanceof ArrayRef && targetType != null)
targetType = ((ArrayType) targetType).getElementType();
// If this is an unrealizable typecast, drop the abstraction
if (rightValue instanceof CastExpr) {
// If we cast java.lang.Object to an array type,
// we must update our typing information
CastExpr cast = (CastExpr) assignStmt.getRightOp();
if (cast.getType() instanceof ArrayType && !(targetType instanceof ArrayType)) {
assert canCastType(targetType, cast.getType());
// If the cast was realizable, we can assume that we had the
// type to which we cast.
targetType = cast.getType();
}
}
// Special type handling for certain operations
else if (rightValue instanceof InstanceOfExpr)
newAbs = source.deriveNewAbstraction(new AccessPath(leftValue, null,
BooleanType.v(), (Type[]) null, true), assignStmt);
else if (rightValue instanceof NewArrayExpr) {
isArrayLength = true;
targetType = null;
}
}
else
// For implicit taints, we have no type information
assert targetType == null;
// also taint the target of the assignment
if (newAbs == null)
if (source.getAccessPath().isEmpty())
newAbs = source.deriveNewAbstraction(new AccessPath(leftValue, true), assignStmt, true);
else
newAbs = source.deriveNewAbstraction(leftValue, cutFirstField, assignStmt, targetType,
isArrayLength);
taintSet.add(newAbs);
if (triggerInaktiveTaintOrReverseFlow(assignStmt, leftValue, newAbs))
computeAliasTaints(d1, assignStmt, leftValue, taintSet,
method, newAbs);
}
/**
* Checks whether the given call has at least one valid target,
* i.e. a callee with a body.
* @param call The call site to check
* @return True if there is at least one callee implementation
* for the given call, otherwise false
*/
private boolean hasValidCallees(Unit call) {
Collection<SootMethod> callees = interproceduralCFG().getCalleesOfCallAt(call);
for (SootMethod callee : callees)
if (callee.isConcrete())
return true;
return false;
}
@Override
public FlowFunction<Abstraction> getNormalFlowFunction(final Unit src, final Unit dest) {
// Get the call site
if (!(src instanceof Stmt))
return KillAll.v();
final Stmt stmt = (Stmt) src;
final SourceInfo sourceInfo = sourceSinkManager != null
? sourceSinkManager.getSourceInfo(stmt, interproceduralCFG()) : null;
// If we compute flows on parameters, we create the initial
// flow fact here
if (src instanceof IdentityStmt) {
final IdentityStmt is = (IdentityStmt) src;
return new NotifyingNormalFlowFunction(is) {
@Override
public Set<Abstraction> computeTargetsInternal(Abstraction d1, Abstraction source) {
// Check whether we must leave a conditional branch
if (source.isTopPostdominator(is)) {
source = source.dropTopPostdominator();
// Have we dropped the last postdominator for an empty taint?
if (source.getAccessPath().isEmpty() && source.getTopPostdominator() == null)
return Collections.emptySet();
}
// This may also be a parameter access we regard as a source
Set<Abstraction> res = new HashSet<Abstraction>();
if (source == getZeroValue()
&& sourceInfo != null
&& !sourceInfo.getAccessPaths().isEmpty()) {
for (AccessPath ap : sourceInfo.getAccessPaths()) {
Abstraction abs = new Abstraction(ap,
is,
sourceInfo.getUserData(),
false,
false);
res.add(abs);
// Compute the aliases
if (triggerInaktiveTaintOrReverseFlow(is, is.getLeftOp(), abs))
computeAliasTaints(d1, is, is.getLeftOp(),
res, interproceduralCFG().getMethodOf(is), abs);
}
return res;
}
boolean addOriginal = true;
if (is.getRightOp() instanceof CaughtExceptionRef) {
if (source.getExceptionThrown()) {
res.add(source.deriveNewAbstractionOnCatch(is.getLeftOp()));
addOriginal = false;
}
}
if (addOriginal)
if (source != getZeroValue())
res.add(source);
return res;
}
};
}
// taint is propagated with assignStmt
else if (src instanceof AssignStmt) {
final AssignStmt assignStmt = (AssignStmt) src;
final Value right = assignStmt.getRightOp();
final Value leftValue = assignStmt.getLeftOp();
final Value[] rightVals = BaseSelector.selectBaseList(right, true);
return new NotifyingNormalFlowFunction(assignStmt) {
@Override
public Set<Abstraction> computeTargetsInternal(Abstraction d1, Abstraction source) {
// Make sure nothing all wonky is going on here
assert source.getAccessPath().isEmpty()
|| source.getTopPostdominator() == null;
assert source.getTopPostdominator() == null
|| interproceduralCFG().getMethodOf(src) == source.getTopPostdominator().getMethod()
|| interproceduralCFG().getMethodOf(src).getActiveBody().getUnits().contains
(source.getTopPostdominator().getUnit());
// Fields can be sources in some cases
if (source == getZeroValue()
&& sourceInfo != null
&& !sourceInfo.getAccessPaths().isEmpty()) {
Set<Abstraction> res = new HashSet<Abstraction>();
for (AccessPath ap : sourceInfo.getAccessPaths()) {
final Abstraction abs = new Abstraction(ap,
assignStmt,
sourceInfo.getUserData(),
false,
false);
res.add(abs);
// Compute the aliases
if (triggerInaktiveTaintOrReverseFlow(assignStmt, leftValue, abs))
computeAliasTaints(d1, assignStmt, leftValue, res,
interproceduralCFG().getMethodOf(assignStmt), abs);
}
return res;
}
// on NormalFlow taint cannot be created
if (source == getZeroValue())
return Collections.emptySet();
// Check whether we must leave a conditional branch
if (source.isTopPostdominator(assignStmt)) {
source = source.dropTopPostdominator();
// Have we dropped the last postdominator for an empty taint?
if (source.getAccessPath().isEmpty() && source.getTopPostdominator() == null)
return Collections.emptySet();
}
// Check whether we must activate a taint
final Abstraction newSource;
if (!source.isAbstractionActive() && src == source.getActivationUnit())
newSource = source.getActiveCopy();
else
newSource = source;
Set<Abstraction> res = createNewTaintOnAssignment(src, assignStmt,
rightVals, d1, newSource);
if (res != null)
return res;
// If we have propagated taint, we have returned from this method by now
//if leftvalue contains the tainted value -> it is overwritten - remove taint:
//but not for arrayRefs:
// x[i] = y --> taint is preserved since we do not distinguish between elements of collections
//because we do not use a MUST-Alias analysis, we cannot delete aliases of taints
if (assignStmt.getLeftOp() instanceof ArrayRef)
return Collections.singleton(newSource);
if(newSource.getAccessPath().isInstanceFieldRef()) {
// Data Propagation: x.f = y && x.f tainted --> no taint propagated
// Alias Propagation: Only kill the alias if we directly overwrite it,
// otherwise it might just be the creation of yet another alias
if (leftValue instanceof InstanceFieldRef) {
InstanceFieldRef leftRef = (InstanceFieldRef) leftValue;
boolean baseAliases = source.isAbstractionActive()
&& aliasing.mustAlias((Local) leftRef.getBase(),
newSource.getAccessPath().getPlainValue(), assignStmt);
if (baseAliases
|| leftRef.getBase() == newSource.getAccessPath().getPlainValue()) {
if (aliasing.mustAlias(leftRef.getField(), newSource.getAccessPath().getFirstField())) {
return Collections.emptySet();
}
}
}
// x = y && x.f tainted -> no taint propagated. This must only check the precise
// variable which gets replaced, but not any potential strong aliases
else if (leftValue instanceof Local){
if (leftValue == newSource.getAccessPath().getPlainValue()) {
return Collections.emptySet();
}
}
}
//X.f = y && X.f tainted -> no taint propagated. Kills are allowed even if
// static field tracking is disabled
else if (newSource.getAccessPath().isStaticFieldRef()){
if(leftValue instanceof StaticFieldRef
&& aliasing.mustAlias(((StaticFieldRef)leftValue).getField(),
newSource.getAccessPath().getFirstField())){
return Collections.emptySet();
}
}
//when the fields of an object are tainted, but the base object is overwritten
// then the fields should not be tainted any more
//x = y && x.f tainted -> no taint propagated
else if (newSource.getAccessPath().isLocal()
&& leftValue instanceof Local
&& leftValue == newSource.getAccessPath().getPlainValue()){
return Collections.emptySet();
}
//nothing applies: z = y && x tainted -> taint is preserved
return Collections.singleton(newSource);
}
private Set<Abstraction> createNewTaintOnAssignment(final Unit src,
final AssignStmt assignStmt,
final Value[] rightVals,
Abstraction d1,
final Abstraction newSource) {
final Value leftValue = assignStmt.getLeftOp();
final Value rightValue = assignStmt.getRightOp();
boolean addLeftValue = false;
// If we have an implicit flow, but the assigned
// local is never read outside the condition, we do
// not need to taint it.
boolean implicitTaint = newSource.getTopPostdominator() != null
&& newSource.getTopPostdominator().getUnit() != null;
implicitTaint |= newSource.getAccessPath().isEmpty();
// If we have a non-empty postdominator stack, we taint
// every assignment target
if (implicitTaint) {
assert config.getEnableImplicitFlows();
// We can skip over all local assignments inside conditionally-
// called functions since they are not visible in the caller
// anyway
if ((d1 == null || d1.getAccessPath().isEmpty())
&& !(leftValue instanceof FieldRef))
return Collections.singleton(newSource);
if (newSource.getAccessPath().isEmpty())
addLeftValue = true;
}
// If we have a = x with the taint "x" being inactive,
// we must not taint the left side. We can only taint
// the left side if the tainted value is some "x.y".
boolean aliasOverwritten = !addLeftValue
&& !newSource.isAbstractionActive()
&& baseMatchesStrict(rightValue, newSource)
&& rightValue.getType() instanceof RefType
&& !newSource.dependsOnCutAP();
boolean cutFirstField = false;
AccessPath mappedAP = newSource.getAccessPath();
Type targetType = null;
if (!addLeftValue && !aliasOverwritten) {
for (Value rightVal : rightVals) {
if (rightVal instanceof FieldRef) {
// Get the field reference
FieldRef rightRef = (FieldRef) rightVal;
// If the right side references a NULL field, we kill the taint
if (rightRef instanceof InstanceFieldRef
&& ((InstanceFieldRef) rightRef).getBase().getType() instanceof NullType)
return null;
// Check for aliasing
mappedAP = aliasing.mayAlias(newSource.getAccessPath(), rightRef);
// check if static variable is tainted (same name, same class)
//y = X.f && X.f tainted --> y, X.f tainted
if (rightVal instanceof StaticFieldRef) {
if (config.getEnableStaticFieldTracking() && mappedAP != null) {
addLeftValue = true;
cutFirstField = true;
}
}
// check for field references
//y = x.f && x tainted --> y, x tainted
//y = x.f && x.f tainted --> y, x tainted
else if (rightVal instanceof InstanceFieldRef) {
Local rightBase = (Local) ((InstanceFieldRef) rightRef).getBase();
Local sourceBase = newSource.getAccessPath().getPlainValue();
final SootField rightField = rightRef.getField();
// We need to compare the access path on the right side
// with the start of the given one
if (mappedAP != null) {
addLeftValue = true;
cutFirstField = (mappedAP.getFieldCount() > 0
&& mappedAP.getFirstField() == rightField);
}
else if (aliasing.mayAlias(rightBase, sourceBase)
&& newSource.getAccessPath().getFieldCount() == 0
&& newSource.getAccessPath().getTaintSubFields()) {
addLeftValue = true;
targetType = rightField.getType();
}
}
}
// indirect taint propagation:
// if rightvalue is local and source is instancefield of this local:
// y = x && x.f tainted --> y.f, x.f tainted
// y.g = x && x.f tainted --> y.g.f, x.f tainted
else if (rightVal instanceof Local && newSource.getAccessPath().isInstanceFieldRef()) {
Local base = newSource.getAccessPath().getPlainValue();
if (aliasing.mayAlias(rightVal, base)) {
addLeftValue = true;
targetType = newSource.getAccessPath().getBaseType();
}
}
//y = x[i] && x tainted -> x, y tainted
else if (rightVal instanceof ArrayRef) {
Local rightBase = (Local) ((ArrayRef) rightVal).getBase();
if (aliasing.mayAlias(rightBase, newSource.getAccessPath().getPlainValue())) {
addLeftValue = true;
targetType = newSource.getAccessPath().getBaseType();
assert targetType instanceof ArrayType;
}
}
// generic case, is true for Locals, ArrayRefs that are equal etc..
//y = x && x tainted --> y, x tainted
else if (aliasing.mayAlias(rightVal, newSource.getAccessPath().getPlainValue())) {
addLeftValue = true;
targetType = newSource.getAccessPath().getBaseType();
}
// One reason to taint the left side is enough
if (addLeftValue)
break;
}
}
// If we have nothing to add, we quit
if (!addLeftValue)
return null;
// If the right side is a typecast, it must be compatible,
// or this path is not realizable
if (rightValue instanceof CastExpr) {
CastExpr ce = (CastExpr) rightValue;
if (!checkCast(newSource.getAccessPath(), ce.getCastType()))
return Collections.emptySet();
}
// Special handling for certain operations
else if (rightValue instanceof LengthExpr) {
assert newSource.getAccessPath().isEmpty()
|| newSource.getAccessPath().getBaseType() instanceof ArrayType;
assert leftValue instanceof Local;
AccessPath ap = new AccessPath(leftValue, null, IntType.v(),
(Type[]) null, true, false, true, true);
Abstraction lenAbs = newSource.deriveNewAbstraction(ap, assignStmt);
return new TwoElementSet<Abstraction>(newSource, lenAbs);
}
if (mappedAP == null)
for (Value val : rightVals)
aliasing.mayAlias(newSource.getAccessPath(), val);
// If this is a sink, we need to report the finding
if (sourceSinkManager != null
&& sourceSinkManager.isSink(stmt, interproceduralCFG(),
newSource.getAccessPath())
&& newSource.isAbstractionActive()
&& newSource.getAccessPath().isEmpty())
addResult(new AbstractionAtSink(newSource, assignStmt));
Set<Abstraction> res = new HashSet<Abstraction>();
Abstraction targetAB = mappedAP.equals(newSource.getAccessPath())
? newSource : newSource.deriveNewAbstraction(mappedAP, null);
addTaintViaStmt(d1, assignStmt, targetAB, res, cutFirstField,
interproceduralCFG().getMethodOf(src), targetType);
res.add(newSource);
return res;
}
};
}
// for unbalanced problems, return statements correspond to
// normal flows, not return flows, because there is no return
// site we could jump to
else if (src instanceof ReturnStmt) {
final ReturnStmt returnStmt = (ReturnStmt) src;
return new NotifyingNormalFlowFunction(returnStmt) {
@Override
public Set<Abstraction> computeTargetsInternal(Abstraction d1, Abstraction source) {
// Check whether we must leave a conditional branch
if (source.isTopPostdominator(returnStmt)) {
source = source.dropTopPostdominator();
// Have we dropped the last postdominator for an empty taint?
if (source.getAccessPath().isEmpty() && source.getTopPostdominator() == null)
return Collections.emptySet();
}
// Check whether we have reached a sink
if (sourceSinkManager != null
&& source.isAbstractionActive()
&& aliasing.mayAlias(returnStmt.getOp(), source.getAccessPath().getPlainValue())
&& sourceSinkManager.isSink(returnStmt, interproceduralCFG(),
source.getAccessPath()))
addResult(new AbstractionAtSink(source, returnStmt));
return Collections.singleton(source);
}
};
}
else if (config.getEnableExceptionTracking() && src instanceof ThrowStmt) {
final ThrowStmt throwStmt = (ThrowStmt) src;
return new NotifyingNormalFlowFunction(throwStmt) {
@Override
public Set<Abstraction> computeTargetsInternal(Abstraction d1, Abstraction source) {
// Check whether we must leave a conditional branch
if (source.isTopPostdominator(throwStmt)) {
source = source.dropTopPostdominator();
// Have we dropped the last postdominator for an empty taint?
if (source.getAccessPath().isEmpty() && source.getTopPostdominator() == null)
return Collections.emptySet();
}
if (aliasing.mayAlias(throwStmt.getOp(), source.getAccessPath().getPlainValue()))
return Collections.singleton(source.deriveNewAbstractionOnThrow(throwStmt));
return Collections.singleton(source);
}
};
}
// IF statements can lead to implicit flows or sinks
else if (src instanceof IfStmt
|| src instanceof LookupSwitchStmt
|| src instanceof TableSwitchStmt) {
final Value condition = src instanceof IfStmt ? ((IfStmt) src).getCondition()
: src instanceof LookupSwitchStmt ? ((LookupSwitchStmt) src).getKey()
: ((TableSwitchStmt) src).getKey();
// If implicit flow tracking is not enabled, we only need to
// check for sinks
if (!config.getEnableImplicitFlows())
return new NotifyingNormalFlowFunction(stmt) {
@Override
public Set<Abstraction> computeTargetsInternal(Abstraction d1, Abstraction source) {
// Check for a sink
if (source.isAbstractionActive()
&& sourceSinkManager != null
&& sourceSinkManager.isSink(stmt, interproceduralCFG(),
source.getAccessPath()))
for (Value v : BaseSelector.selectBaseList(condition, false))
if (aliasing.mayAlias(v, source.getAccessPath().getPlainValue())) {
addResult(new AbstractionAtSink(source, stmt));
break;
}
return Collections.singleton(source);
}
};
// Check for implicit flows
return new NotifyingNormalFlowFunction(stmt) {
@Override
public Set<Abstraction> computeTargetsInternal(Abstraction d1, Abstraction source) {
if (!source.isAbstractionActive())
return Collections.singleton(source);
// Check for a sink
if (sourceSinkManager != null
&& sourceSinkManager.isSink(stmt, interproceduralCFG(),
source.getAccessPath()))
for (Value v : BaseSelector.selectBaseList(condition, false))
if (aliasing.mayAlias(v, source.getAccessPath().getPlainValue())) {
addResult(new AbstractionAtSink(source, stmt));
break;
}
// Check whether we must leave a conditional branch
if (source.isTopPostdominator(src)) {
source = source.dropTopPostdominator();
// Have we dropped the last postdominator for an empty taint?
if (source.getAccessPath().isEmpty() && source.getTopPostdominator() == null)
return Collections.emptySet();
}
// If we are in a conditionally-called method, there is no
// need to care about further conditionals, since all
// assignment targets will be tainted anyway
if (source.getAccessPath().isEmpty())
return Collections.singleton(source);
Set<Abstraction> res = new HashSet<Abstraction>();
res.add(source);
Set<Value> values = new HashSet<Value>();
if (condition instanceof Local)
values.add(condition);
else
for (ValueBox box : condition.getUseBoxes())
values.add(box.getValue());
for (Value val : values)
if (aliasing.mayAlias(val, source.getAccessPath().getPlainValue())) {
// ok, we are now in a branch that depends on a secret value.
// We now need the postdominator to know when we leave the
// branch again.
UnitContainer postdom = interproceduralCFG().getPostdominatorOf(src);
if (!(postdom.getMethod() == null
&& source.getTopPostdominator() != null
&& interproceduralCFG().getMethodOf(postdom.getUnit()) == source.getTopPostdominator().getMethod())) {
Abstraction newAbs = source.deriveConditionalAbstractionEnter(postdom, stmt);
res.add(newAbs);
break;
}
}
return res;
}
};
}
return Identity.v();
}
@Override
public FlowFunction<Abstraction> getCallFlowFunction(final Unit src, final SootMethod dest) {
if (!dest.isConcrete()){
logger.debug("Call skipped because target has no body: {} -> {}", src, dest);
return KillAll.v();
}
final Stmt stmt = (Stmt) src;
final InvokeExpr ie = (stmt != null && stmt.containsInvokeExpr())
? stmt.getInvokeExpr() : null;
final Local[] paramLocals = dest.getActiveBody().getParameterLocals().toArray(
new Local[0]);
final SourceInfo sourceInfo = sourceSinkManager != null
? sourceSinkManager.getSourceInfo(stmt, interproceduralCFG()) : null;
final boolean isSink = sourceSinkManager != null
? sourceSinkManager.isSink(stmt, interproceduralCFG(), null) : false;
// This is not cached by Soot, so accesses are more expensive
// than one might think
final Local thisLocal = dest.isStatic() ? null : dest.getActiveBody().getThisLocal();
return new SolverCallFlowFunction() {
@Override
public Set<Abstraction> computeTargets(Abstraction d1, Abstraction source) {
Set<Abstraction> res = computeTargetsInternal(d1, source);
if (!res.isEmpty())
for (Abstraction abs : res)
aliasingStrategy.injectCallingContext(abs, solver, dest, src, source, d1);
return notifyOutFlowHandlers(stmt, d1, source, res,
FlowFunctionType.CallFlowFunction);
}
private Set<Abstraction> computeTargetsInternal(Abstraction d1, Abstraction source) {
if (config.getStopAfterFirstFlow() && !results.isEmpty())
return Collections.emptySet();
//if we do not have to look into sources or sinks:
if (!config.getInspectSources() && sourceInfo != null)
return Collections.emptySet();
if (!config.getInspectSinks() && isSink)
return Collections.emptySet();
if (source == getZeroValue()) {
assert sourceInfo != null;
return Collections.singleton(source);
}
// Notify the handler if we have one
if (taintPropagationHandlers != null)
for (TaintPropagationHandler tp : taintPropagationHandlers)
tp.notifyFlowIn(stmt, source, interproceduralCFG(),
FlowFunctionType.CallFlowFunction);
// If we have an exclusive taint wrapper for the target
// method, we do not perform an own taint propagation.
if(taintWrapper != null && taintWrapper.isExclusive(stmt, source)) {
//taint is propagated in CallToReturnFunction, so we do not need any taint here:
return Collections.emptySet();
}
// Check whether we must leave a conditional branch
if (source.isTopPostdominator(stmt)) {
source = source.dropTopPostdominator();
// Have we dropped the last postdominator for an empty taint?
if (source.getAccessPath().isEmpty() && source.getTopPostdominator() == null)
return Collections.emptySet();
}
// If no parameter is tainted, but we are in a conditional, we create a
// pseudo abstraction. We do not map parameters if we are handling an
// implicit flow anyway.
if (source.getAccessPath().isEmpty()) {
assert config.getEnableImplicitFlows();
// Block the call site for further explicit tracking
if (d1 != null) {
Set<Abstraction> callSites = implicitTargets.putIfAbsentElseGet
(src, new ConcurrentHashSet<Abstraction>());
callSites.add(d1);
}
Abstraction abs = source.deriveConditionalAbstractionCall(src);
return Collections.singleton(abs);
}
else if (source.getTopPostdominator() != null)
return Collections.emptySet();
// If we have already tracked implicit flows through this method,
// there is no point in tracking explicit ones afterwards as well.
if (implicitTargets.containsKey(src) && (d1 == null || implicitTargets.get(src).contains(d1)))
return Collections.emptySet();
// Only propagate the taint if the target field is actually read
if (source.getAccessPath().isStaticFieldRef()
&& !config.getEnableStaticFieldTracking())
return Collections.emptySet();
// Map the source access path into the callee
Set<AccessPath> res = mapAccessPathToCallee(dest, ie, paramLocals,
thisLocal, source.getAccessPath());
if (res == null)
return Collections.emptySet();
// Translate the access paths into abstractions
Set<Abstraction> resAbs = new HashSet<Abstraction>(res.size());
for (AccessPath ap : res)
if (ap.isStaticFieldRef()) {
// Do not propagate static fields that are not read inside the callee
if (interproceduralCFG().isStaticFieldRead(dest, ap.getFirstField()))
resAbs.add(source.deriveNewAbstraction(ap, stmt));
}
// If the variable is never read in the callee, there is no
// need to propagate it through
else if (source.isImplicit() || interproceduralCFG().methodReadsValue(dest, ap.getPlainValue()))
resAbs.add(source.deriveNewAbstraction(ap, stmt));
return resAbs;
}
};
}
@Override
public FlowFunction<Abstraction> getReturnFlowFunction(final Unit callSite,
final SootMethod callee, final Unit exitStmt, final Unit retSite) {
// Get the call site
if (callSite != null && !(callSite instanceof Stmt))
return KillAll.v();
final Stmt iCallStmt = (Stmt) callSite;
final ThrowStmt throwStmt = (exitStmt instanceof ThrowStmt) ? (ThrowStmt) exitStmt : null;
final ReturnStmt returnStmt = (exitStmt instanceof ReturnStmt) ? (ReturnStmt) exitStmt : null;
final Local[] paramLocals = callee.getActiveBody().getParameterLocals().toArray(
new Local[0]);
// This is not cached by Soot, so accesses are more expensive
// than one might think
final Local thisLocal = callee.isStatic() ? null : callee.getActiveBody().getThisLocal();
return new SolverReturnFlowFunction() {
@Override
public Set<Abstraction> computeTargets(Abstraction source, Abstraction d1,
Collection<Abstraction> callerD1s) {
Set<Abstraction> res = computeTargetsInternal(source, callerD1s);
return notifyOutFlowHandlers(exitStmt, d1, source, res,
FlowFunctionType.ReturnFlowFunction);
}
private Set<Abstraction> computeTargetsInternal(Abstraction source,
Collection<Abstraction> callerD1s) {
if (config.getStopAfterFirstFlow() && !results.isEmpty())
return Collections.emptySet();
if (source == getZeroValue())
return Collections.emptySet();
// Notify the handler if we have one
if (taintPropagationHandlers != null)
for (TaintPropagationHandler tp : taintPropagationHandlers)
tp.notifyFlowIn(exitStmt, source, interproceduralCFG(),
FlowFunctionType.ReturnFlowFunction);
boolean callerD1sConditional = false;
for (Abstraction d1 : callerD1s)
if (d1.getAccessPath().isEmpty()) {
callerD1sConditional = true;
break;
}
// Activate taint if necessary
Abstraction newSource = source;
if(!source.isAbstractionActive())
if(callSite != null)
if (callSite == source.getActivationUnit()
|| isCallSiteActivatingTaint(callSite, source.getActivationUnit()))
newSource = source.getActiveCopy();
// Empty access paths are never propagated over return edges
if (source.getAccessPath().isEmpty()) {
// If we return a constant, we must taint it
if (returnStmt != null && returnStmt.getOp() instanceof Constant)
if (callSite instanceof DefinitionStmt) {
DefinitionStmt def = (DefinitionStmt) callSite;
Abstraction abs = newSource.deriveNewAbstraction
(newSource.getAccessPath().copyWithNewValue(def.getLeftOp()), (Stmt) exitStmt);
Set<Abstraction> res = new HashSet<Abstraction>();
res.add(abs);
// If we taint a return value because it is implicit,
// we must trigger an alias analysis
if(triggerInaktiveTaintOrReverseFlow(def, def.getLeftOp(), abs) && !callerD1sConditional)
for (Abstraction d1 : callerD1s)
computeAliasTaints(d1, iCallStmt, def.getLeftOp(), res,
interproceduralCFG().getMethodOf(callSite), abs);
return res;
}
// Kill the empty abstraction
return Collections.emptySet();
}
// Are we still inside a conditional? We check this before we
// leave the method since the return value is still assigned
// inside the method.
boolean insideConditional = newSource.getTopPostdominator() != null
|| newSource.getAccessPath().isEmpty();
// Check whether we must leave a conditional branch
if (newSource.isTopPostdominator(exitStmt) || newSource.isTopPostdominator(callee)) {
newSource = newSource.dropTopPostdominator();
// Have we dropped the last postdominator for an empty taint?
if (!insideConditional
&& newSource.getAccessPath().isEmpty()
&& newSource.getTopPostdominator() == null)
return Collections.emptySet();
}
//if abstraction is not active and activeStmt was in this method, it will not get activated = it can be removed:
if(!newSource.isAbstractionActive() && newSource.getActivationUnit() != null)
if (interproceduralCFG().getMethodOf(newSource.getActivationUnit()) == callee)
return Collections.emptySet();
// Static field tracking can be disabled
if (!config.getEnableStaticFieldTracking()
&& newSource.getAccessPath().isStaticFieldRef())
return Collections.emptySet();
// Check whether this return is treated as a sink
if (returnStmt != null) {
assert returnStmt.getOp() == null
|| returnStmt.getOp() instanceof Local
|| returnStmt.getOp() instanceof Constant;
boolean mustTaintSink = insideConditional;
mustTaintSink |= returnStmt.getOp() != null
&& newSource.getAccessPath().isLocal()
&& aliasing.mayAlias(newSource.getAccessPath().getPlainValue(), returnStmt.getOp());
if (mustTaintSink
&& sourceSinkManager != null
&& sourceSinkManager.isSink(returnStmt, interproceduralCFG(),
newSource.getAccessPath())
&& newSource.isAbstractionActive())
addResult(new AbstractionAtSink(newSource, returnStmt));
}
// If we have no caller, we have nowhere to propagate. This
// can happen when leaving the main method.
if (callSite == null)
return Collections.emptySet();
// If we throw an exception with a tainted operand, we need to
// handle this specially
if (throwStmt != null && config.getEnableExceptionTracking())
if (aliasing.mayAlias(throwStmt.getOp(), source.getAccessPath().getPlainValue()))
return Collections.singleton(source.deriveNewAbstractionOnThrow(throwStmt));
Set<Abstraction> res = new HashSet<Abstraction>();
// if we have a returnStmt we have to look at the returned value:
if (returnStmt != null && callSite instanceof DefinitionStmt) {
Value retLocal = returnStmt.getOp();
DefinitionStmt defnStmt = (DefinitionStmt) callSite;
Value leftOp = defnStmt.getLeftOp();
if ((insideConditional && leftOp instanceof FieldRef)
|| aliasing.mayAlias(retLocal, newSource.getAccessPath().getPlainValue())) {
Abstraction abs = newSource.deriveNewAbstraction
(newSource.getAccessPath().copyWithNewValue(leftOp), (Stmt) exitStmt);
res.add(abs);
// Aliases of implicitly tainted variables must be mapped back
// into the caller's context on return when we leave the last
// implicitly-called method
if ((abs.isImplicit()
&& (abs.getAccessPath().isInstanceFieldRef() || abs.getAccessPath().isStaticFieldRef())
&& !callerD1sConditional) || aliasingStrategy.requiresAnalysisOnReturn())
for (Abstraction d1 : callerD1s)
computeAliasTaints(d1, iCallStmt, leftOp, res,
interproceduralCFG().getMethodOf(callSite), abs);
}
}
// easy: static
if (newSource.getAccessPath().isStaticFieldRef()) {
// Simply pass on the taint
Abstraction abs = newSource;
res.add(abs);
// Aliases of implicitly tainted variables must be mapped back
// into the caller's context on return when we leave the last
// implicitly-called method
if ((abs.isImplicit() && !callerD1sConditional)
|| aliasingStrategy.requiresAnalysisOnReturn())
for (Abstraction d1 : callerD1s)
computeAliasTaints(d1, iCallStmt, null, res,
interproceduralCFG().getMethodOf(callSite), abs);
}
// checks: this/params/fields
// check one of the call params are tainted (not if simple type)
Value sourceBase = newSource.getAccessPath().getPlainValue();
boolean parameterAliases = false;
{
Value originalCallArg = null;
for (int i = 0; i < callee.getParameterCount(); i++) {
// If this parameter is overwritten, we cannot propagate
// the "old" taint over. Return value propagation must
// always happen explicitly.
if (callSite instanceof DefinitionStmt) {
DefinitionStmt defnStmt = (DefinitionStmt) callSite;
Value leftOp = defnStmt.getLeftOp();
originalCallArg = defnStmt.getInvokeExpr().getArg(i);
if (originalCallArg == leftOp)
continue;
}
// Propagate over the parameter taint
if (aliasing.mayAlias(paramLocals[i], sourceBase)) {
parameterAliases = true;
originalCallArg = iCallStmt.getInvokeExpr().getArg(i);
// If this is a constant parameter, we can safely ignore it
if (!AccessPath.canContainValue(originalCallArg))
continue;
if (!checkCast(source.getAccessPath(), originalCallArg.getType()))
continue;
// Primitive types and strings cannot have aliases and thus
// never need to be propagated back
if (source.getAccessPath().getBaseType() instanceof PrimType)
continue;
if (isStringType(source.getAccessPath().getBaseType()))
continue;
Abstraction abs = newSource.deriveNewAbstraction
(newSource.getAccessPath().copyWithNewValue(originalCallArg), (Stmt) exitStmt);
res.add(abs);
// Aliases of implicitly tainted variables must be mapped back
// into the caller's context on return when we leave the last
// implicitly-called method
if ((abs.isImplicit()
&& implicitFlowAliasingStrategy.hasProcessedMethod(callee)
&& !callerD1sConditional) || aliasingStrategy.requiresAnalysisOnReturn()) {
assert originalCallArg.getType() instanceof ArrayType
|| originalCallArg.getType() instanceof RefType;
for (Abstraction d1 : callerD1s)
computeAliasTaints(d1, iCallStmt, originalCallArg, res,
interproceduralCFG().getMethodOf(callSite), abs);
}
}
}
}
{
if (!callee.isStatic()) {
if (aliasing.mayAlias(thisLocal, sourceBase)) {
// check if it is not one of the params (then we have already fixed it)
if (!parameterAliases) {
if (iCallStmt.getInvokeExpr() instanceof InstanceInvokeExpr) {
InstanceInvokeExpr iIExpr = (InstanceInvokeExpr) iCallStmt.getInvokeExpr();
Abstraction abs = newSource.deriveNewAbstraction
(newSource.getAccessPath().copyWithNewValue(iIExpr.getBase()), (Stmt) exitStmt);
res.add(abs);
// Aliases of implicitly tainted variables must be mapped back
// into the caller's context on return when we leave the last
// implicitly-called method
if ((abs.isImplicit()
&& triggerInaktiveTaintOrReverseFlow(iCallStmt, iIExpr.getBase(), abs)
&& implicitFlowAliasingStrategy.hasProcessedMethod(callee)
&& !callerD1sConditional) || aliasingStrategy.requiresAnalysisOnReturn())
for (Abstraction d1 : callerD1s)
computeAliasTaints(d1, iCallStmt, iIExpr.getBase(), res,
interproceduralCFG().getMethodOf(callSite), abs);
}
}
}
}
}
for (Abstraction abs : res)
if (abs != newSource)
abs.setCorrespondingCallSite(iCallStmt);
return res;
}
};
}
@Override
public FlowFunction<Abstraction> getCallToReturnFlowFunction(final Unit call, final Unit returnSite) {
// special treatment for native methods:
if (!(call instanceof Stmt))
return KillAll.v();
final Stmt iCallStmt = (Stmt) call;
final InvokeExpr invExpr = iCallStmt.getInvokeExpr();
final Value[] callArgs = new Value[invExpr.getArgCount()];
for (int i = 0; i < invExpr.getArgCount(); i++)
callArgs[i] = invExpr.getArg(i);
final SourceInfo sourceInfo = sourceSinkManager != null
? sourceSinkManager.getSourceInfo(iCallStmt, interproceduralCFG()) : null;
final boolean isSink = (sourceSinkManager != null)
? sourceSinkManager.isSink(iCallStmt, interproceduralCFG(), null) : false;
final SootMethod callee = invExpr.getMethod();
final boolean hasValidCallees = hasValidCallees(call);
return new SolverCallToReturnFlowFunction() {
@Override
public Set<Abstraction> computeTargets(Abstraction d1, Abstraction source) {
Set<Abstraction> res = computeTargetsInternal(d1, source);
return notifyOutFlowHandlers(call, d1, source, res,
FlowFunctionType.CallToReturnFlowFunction);
}
private Set<Abstraction> computeTargetsInternal(Abstraction d1, Abstraction source) {
if (config.getStopAfterFirstFlow() && !results.isEmpty())
return Collections.emptySet();
// Notify the handler if we have one
if (taintPropagationHandlers != null)
for (TaintPropagationHandler tp : taintPropagationHandlers)
tp.notifyFlowIn(call, source, interproceduralCFG(),
FlowFunctionType.CallToReturnFlowFunction);
// Check whether we must leave a conditional branch
if (source.isTopPostdominator(call)) {
source = source.dropTopPostdominator();
// Have we dropped the last postdominator for an empty taint?
if (source.getAccessPath().isEmpty() && source.getTopPostdominator() == null)
return Collections.emptySet();
}
// Static field tracking can be disabled
if (!config.getEnableStaticFieldTracking()
&& source.getAccessPath().isStaticFieldRef())
return Collections.emptySet();
Set<Abstraction> res = new HashSet<Abstraction>();
// Sources can either be assignments like x = getSecret() or
// instance method calls like constructor invocations
if (source == getZeroValue()
&& sourceInfo != null
&& !sourceInfo.getAccessPaths().isEmpty()) {
for (AccessPath ap : sourceInfo.getAccessPaths()) {
final Abstraction abs = new Abstraction(ap,
iCallStmt,
sourceInfo.getUserData(),
false,
false);
res.add(abs);
// Compute the aliases
if (triggerInaktiveTaintOrReverseFlow(iCallStmt, ap.getPlainValue(), abs))
computeAliasTaints(d1, iCallStmt, ap.getPlainValue(), res,
interproceduralCFG().getMethodOf(call), abs);
// Set the corresponding call site
for (Abstraction absRet : res)
if (absRet != source)
absRet.setCorrespondingCallSite(iCallStmt);
}
return res;
}
//check inactive elements:
final Abstraction newSource;
if (!source.isAbstractionActive() && (call == source.getActivationUnit()
|| isCallSiteActivatingTaint(call, source.getActivationUnit())))
newSource = source.getActiveCopy();
else
newSource = source;
// Compute the taint wrapper taints
boolean passOn = true;
Collection<Abstraction> wrapperTaints = computeWrapperTaints(d1, iCallStmt, newSource);
if (wrapperTaints != null) {
res.addAll(wrapperTaints);
// If the taint wrapper generated an abstraction for
// the incoming access path, we assume it to be handled
// and do not pass on the incoming abstraction on our own
for (Abstraction wrapperAbs : wrapperTaints)
if (wrapperAbs.getAccessPath().equals(newSource.getAccessPath())) {
passOn = false;
break;
}
}
// if we have called a sink we have to store the path from the source - in case one of the params is tainted!
if (sourceSinkManager != null
&& sourceSinkManager.isSink(iCallStmt, interproceduralCFG(),
newSource.getAccessPath())) {
// If we are inside a conditional branch, we consider every sink call a leak
boolean conditionalCall = config.getEnableImplicitFlows()
&& !interproceduralCFG().getMethodOf(call).isStatic()
&& aliasing.mayAlias(interproceduralCFG().getMethodOf(call).getActiveBody().getThisLocal(),
newSource.getAccessPath().getPlainValue())
&& newSource.getAccessPath().getFirstField() == null;
boolean taintedParam = (conditionalCall
|| newSource.getTopPostdominator() != null
|| newSource.getAccessPath().isEmpty())
&& newSource.isAbstractionActive();
// If the base object is tainted, we also consider the "code" associated
// with the object's class as tainted.
if (!taintedParam) {
for (int i = 0; i < callArgs.length; i++) {
if (aliasing.mayAlias(callArgs[i], newSource.getAccessPath().getPlainValue())) {
taintedParam = true;
break;
}
}
}
if (taintedParam && newSource.isAbstractionActive())
addResult(new AbstractionAtSink(newSource, iCallStmt));
// if the base object which executes the method is tainted the sink is reached, too.
if (invExpr instanceof InstanceInvokeExpr) {
InstanceInvokeExpr vie = (InstanceInvokeExpr) iCallStmt.getInvokeExpr();
if (newSource.isAbstractionActive()
&& aliasing.mayAlias(vie.getBase(), newSource.getAccessPath().getPlainValue()))
addResult(new AbstractionAtSink(newSource, iCallStmt));
}
}
if (newSource.getTopPostdominator() != null
&& newSource.getTopPostdominator().getUnit() == null)
return Collections.singleton(newSource);
// Implicit flows: taint return value
if (call instanceof DefinitionStmt) {
// If we have an implicit flow, but the assigned
// local is never read outside the condition, we do
// not need to taint it.
boolean implicitTaint = newSource.getTopPostdominator() != null
&& newSource.getTopPostdominator().getUnit() != null;
implicitTaint |= newSource.getAccessPath().isEmpty();
if (implicitTaint) {
Value leftVal = ((DefinitionStmt) call).getLeftOp();
// We can skip over all local assignments inside conditionally-
// called functions since they are not visible in the caller
// anyway
if ((d1 == null || d1.getAccessPath().isEmpty())
&& !(leftVal instanceof FieldRef))
return Collections.singleton(newSource);
Abstraction abs = newSource.deriveNewAbstraction(new AccessPath(leftVal, true),
iCallStmt);
return new TwoElementSet<Abstraction>(newSource, abs);
}
}
// If this call overwrites the left side, the taint is never passed on.
if (passOn) {
if (newSource.getAccessPath().isStaticFieldRef())
passOn = false;
else if (call instanceof DefinitionStmt
&& aliasing.mayAlias(((DefinitionStmt) call).getLeftOp(),
newSource.getAccessPath().getPlainValue()))
passOn = false;
}
//we only can remove the taint if we step into the call/return edges
//otherwise we will loose taint - see ArrayTests/arrayCopyTest
if (passOn
&& invExpr instanceof InstanceInvokeExpr
&& newSource.getAccessPath().isInstanceFieldRef()
&& (config.getInspectSinks() || !isSink)
&& (hasValidCallees
|| (taintWrapper != null && taintWrapper.isExclusive(
iCallStmt, newSource)))) {
// If one of the callers does not read the value, we must pass it on
// in any case
boolean allCalleesRead = true;
outer : for (SootMethod callee : interproceduralCFG().getCalleesOfCallAt(call)) {
if (callee.isConcrete() && callee.hasActiveBody()) {
Set<AccessPath> calleeAPs = mapAccessPathToCallee(callee,
invExpr, null, null, source.getAccessPath());
if (calleeAPs != null)
for (AccessPath ap : calleeAPs)
if (!interproceduralCFG().methodReadsValue(callee, ap.getPlainValue())) {
allCalleesRead = false;
break outer;
}
}
}
if (allCalleesRead) {
if (aliasing.mayAlias(((InstanceInvokeExpr) invExpr).getBase(),
newSource.getAccessPath().getPlainValue())) {
passOn = false;
}
if (passOn)
for (int i = 0; i < callArgs.length; i++)
if (aliasing.mayAlias(callArgs[i], newSource.getAccessPath().getPlainValue())) {
passOn = false;
break;
}
//static variables are always propagated if they are not overwritten. So if we have at least one call/return edge pair,
//we can be sure that the value does not get "lost" if we do not pass it on:
if(newSource.getAccessPath().isStaticFieldRef())
passOn = false;
}
}
// If the callee does not read the given value, we also need to pass it on
// since we do not propagate it into the callee.
if (source.getAccessPath().isStaticFieldRef()) {
if (!interproceduralCFG().isStaticFieldUsed(callee,
source.getAccessPath().getFirstField()))
passOn = true;
}
// Implicit taints are always passed over conditionally called methods
passOn |= source.getTopPostdominator() != null || source.getAccessPath().isEmpty();
if (passOn)
if (newSource != getZeroValue())
res.add(newSource);
if (callee.isNative())
for (Value callVal : callArgs)
if (callVal == newSource.getAccessPath().getPlainValue()) {
// java uses call by value, but fields of complex objects can be changed (and tainted), so use this conservative approach:
Set<Abstraction> nativeAbs = ncHandler.getTaintedValues(iCallStmt, newSource, callArgs);
if (nativeAbs != null) {
res.addAll(nativeAbs);
// Compute the aliases
for (Abstraction abs : nativeAbs)
if (abs.getAccessPath().isStaticFieldRef()
|| triggerInaktiveTaintOrReverseFlow(iCallStmt,
abs.getAccessPath().getPlainValue(), abs))
computeAliasTaints(d1, iCallStmt,
abs.getAccessPath().getPlainValue(), res,
interproceduralCFG().getMethodOf(call), abs);
}
// We only call the native code handler once per statement
break;
}
for (Abstraction abs : res)
if (abs != newSource)
abs.setCorrespondingCallSite(iCallStmt);
return res;
}
};
}
/**
* Maps the given access path into the scope of the callee
* @param callee The method that is being called
* @param ie The invocation expression for the call
* @param paramLocals The list of parameter locals in the callee
* @param thisLocal The "this" local in the callee
* @param ap The caller-side access path to map
* @return The set of callee-side access paths corresponding to the
* given caller-side access path
*/
private Set<AccessPath> mapAccessPathToCallee(final SootMethod callee, final InvokeExpr ie,
Value[] paramLocals, Local thisLocal, AccessPath ap) {
// We do not transfer empty access paths
if (ap.isEmpty())
return Collections.emptySet();
// Android executor methods are handled specially. getSubSignature()
// is slow, so we try to avoid it whenever we can
final boolean isExecutorExecute = isExecutorExecute(ie, callee);
Set<AccessPath> res = null;
// check if whole object is tainted (happens with strings, for example:)
if (!isExecutorExecute
&& !ap.isStaticFieldRef()
&& !callee.isStatic()) {
assert ie instanceof InstanceInvokeExpr;
InstanceInvokeExpr vie = (InstanceInvokeExpr) ie;
// this might be enough because every call must happen with a local variable which is tainted itself:
if (aliasing.mayAlias(vie.getBase(), ap.getPlainValue()))
if (hasCompatibleTypesForCall(ap, callee.getDeclaringClass())) {
if (res == null) res = new HashSet<AccessPath>();
// Get the "this" local if we don't have it yet
if (thisLocal == null)
thisLocal = callee.isStatic() ? null : callee.getActiveBody().getThisLocal();
res.add(ap.copyWithNewValue(thisLocal));
}
}
// staticfieldRefs must be analyzed even if they are not part of the params:
else if (ap.isStaticFieldRef()) {
if (res == null) res = new HashSet<AccessPath>();
res.add(ap);
}
//special treatment for clinit methods - no param mapping possible
if (isExecutorExecute) {
if (aliasing.mayAlias(ie.getArg(0), ap.getPlainValue())) {
if (res == null) res = new HashSet<AccessPath>();
res.add(ap.copyWithNewValue(callee.getActiveBody().getThisLocal()));
}
}
else if (callee.getParameterCount() > 0) {
assert callee.getParameterCount() == ie.getArgCount();
// check if param is tainted:
for (int i = 0; i < ie.getArgCount(); i++) {
if (aliasing.mayAlias(ie.getArg(i), ap.getPlainValue())) {
if (res == null) res = new HashSet<AccessPath>();
// Get the parameter locals if we don't have them yet
if (paramLocals == null)
paramLocals = callee.getActiveBody().getParameterLocals().toArray(
new Local[callee.getParameterCount()]);
res.add(ap.copyWithNewValue(paramLocals[i]));
}
}
}
return res;
}
};
}
@Override
public boolean autoAddZero() {
return false;
}
/**
* Adds a new result of the data flow analysis to the collection
* @param resultAbs The abstraction at the sink instruction
*/
private void addResult(AbstractionAtSink resultAbs) {
// Check whether we need to filter a result in a system package
if (config.getIgnoreFlowsInSystemPackages() && SystemClassHandler.isClassInSystemPackage
(interproceduralCFG().getMethodOf(resultAbs.getSinkStmt()).getDeclaringClass().getName()))
return;
// Make sure that the sink statement also appears inside the
// abstraction
resultAbs = new AbstractionAtSink
(resultAbs.getAbstraction().deriveNewAbstraction
(resultAbs.getAbstraction().getAccessPath(), resultAbs.getSinkStmt()),
resultAbs.getSinkStmt());
resultAbs.getAbstraction().setCorrespondingCallSite(resultAbs.getSinkStmt());
Abstraction newAbs = this.results.putIfAbsentElseGet
(resultAbs, resultAbs.getAbstraction());
if (newAbs != resultAbs.getAbstraction())
newAbs.addNeighbor(resultAbs.getAbstraction());
}
/**
* Gets the results of the data flow analysis
*/
public Set<AbstractionAtSink> getResults(){
return this.results.keySet();
}
}
|
package com.ffxivcensus.gatherer;
import com.ffxivcensus.gatherer.Player;
import static org.junit.Assert.*;
/**
* JUnit test class to test the methods of the Player class.
*
* @author Peter Reid
* @see Player
* @since 1.0
*/
public class PlayerTest {
/**
* Perform a test of the getPlayer method, using character #2356533 (Aelia Sokoto, Cerberus) as the test character.
*
* @throws Exception excception thrown when reading non-existant character.
*/
@org.junit.Test
public void testGetPlayer() throws Exception {
//Fetch object to test against (Aelia Sokoto, Cerberus)
Player playerOne = Player.getPlayer(2356533);
//NOTE: All of the following tests assume various pieces of information
//Testing information that is very unlikely to change
assertEquals(playerOne.getId(), 2356533);
assertEquals(playerOne.getPlayerName(), "Aelia Sokoto");
assertEquals(playerOne.getRealm(), "Cerberus");
//Following can only be assumed to be true based on info at time of test creation
assertEquals(playerOne.getRace(), "Miqo'te");
assertEquals(playerOne.getGender(), "female");
assertEquals(playerOne.getGrandCompany(), "Maelstrom");
//Test classes - levels based on those at time of test creation
//Disciples of War
assertTrue(playerOne.getLvlGladiator() >= 60);
assertTrue(playerOne.getLvlPugilist() >= 60);
assertTrue(playerOne.getLvlMarauder() >= 60);
assertTrue(playerOne.getLvlLancer() >= 60);
assertTrue(playerOne.getLvlArcher() >= 52);
assertTrue(playerOne.getLvlRogue() >= 56);
//Disciples of Magic
assertTrue(playerOne.getLvlConjurer() >= 60);
assertTrue(playerOne.getLvlThaumaturge() >= 60);
assertTrue(playerOne.getLvlArcanist() >= 60);
//Extra Jobs
assertTrue(playerOne.getLvlDarkKnight() >= 60);
assertTrue(playerOne.getLvlMachinist() >= 60);
assertTrue(playerOne.getLvlAstrologian() >= 60);
//Disciples of the hand
assertTrue(playerOne.getLvlCarpenter() >= 53);
assertTrue(playerOne.getLvlBlacksmith() >= 53);
assertTrue(playerOne.getLvlArmorer() >= 58);
assertTrue(playerOne.getLvlGoldsmith() >= 58);
assertTrue(playerOne.getLvlLeatherworker() >= 53);
assertTrue(playerOne.getLvlWeaver() >= 56);
assertTrue(playerOne.getLvlAlchemist() >= 60);
assertTrue(playerOne.getLvlCulinarian() >= 55);
//Disciples of the land
assertTrue(playerOne.getLvlMiner() >= 60);
assertTrue(playerOne.getLvlBotanist() >= 60);
assertTrue(playerOne.getLvlFisher() >= 60);
//Test boolean values
//Subscription periods
assertTrue(playerOne.isHas30DaysSub());
assertTrue(playerOne.isHas60DaysSub());
assertTrue(playerOne.isHas90DaysSub());
assertTrue(playerOne.isHas180DaysSub());
assertTrue(playerOne.isHas270DaysSub());
assertTrue(playerOne.isHas360DaysSub());
assertTrue(playerOne.isHas450DaysSub());
assertTrue(playerOne.isHas630DaysSub());
assertTrue(playerOne.isHas630DaysSub());
//Collectibles
assertTrue(playerOne.isHasPreOrderArr());
assertTrue(playerOne.isHasPreOrderHW());
assertTrue(playerOne.isHasPS4Collectors());
assertTrue(playerOne.isHasARRCollectors());
//Assuming the below don't change
assertFalse(playerOne.isHasArtbook());
assertFalse(playerOne.isHasBeforeMeteor());
assertFalse(playerOne.isHasBeforeTheFall());
assertFalse(playerOne.isHasSoundtrack());
assertFalse(playerOne.isHasMooglePlush());
//Achievements
assertTrue(playerOne.isHasAttendedEternalBond());
assertFalse(playerOne.isHasCompletedHWSightseeing());
assertTrue(playerOne.isHasCompleted2pt5());
assertTrue(playerOne.isHasFiftyComms());
assertTrue(playerOne.isHasCompletedHildibrand());
assertTrue(playerOne.isHasEternalBond());
assertTrue(playerOne.isHasKobold());
assertTrue(playerOne.isHasSahagin());
assertTrue(playerOne.isHasAmaljaa());
assertTrue(playerOne.isHasSylph());
assertTrue(playerOne.isHasCompletedHW());
assertFalse(playerOne.getIsLegacyPlayer());
}
/**
* Perform a test of the getPlayer method, using character #2356539, which should not exist.
*/
@org.junit.Test
public void testGetPlayerInvalid() {
try {
//Try to get a character that doesn't exist
Player player = Player.getPlayer(2356539);
//If no exception thrown fail
fail("Character should not exist");
} catch (Exception e) {
}
}
}
|
package ch.unizh.ini.jaer.projects.minliu;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.font.FontRenderContext;
import java.awt.geom.Rectangle2D;
import java.beans.PropertyChangeEvent;
import java.util.Arrays;
import java.util.Observable;
import java.util.Observer;
import java.util.logging.Level;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import com.jogamp.opengl.GL;
import com.jogamp.opengl.GL2;
import com.jogamp.opengl.GL2ES3;
import com.jogamp.opengl.GLAutoDrawable;
import com.jogamp.opengl.util.awt.TextRenderer;
import ch.unizh.ini.jaer.projects.rbodo.opticalflow.AbstractMotionFlow;
import com.jogamp.opengl.GLException;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Logger;
import java.util.stream.IntStream;
import javax.swing.SwingUtilities;
import net.sf.jaer.Description;
import net.sf.jaer.DevelopmentStatus;
import net.sf.jaer.chip.AEChip;
import net.sf.jaer.event.ApsDvsEvent;
import net.sf.jaer.event.ApsDvsEventPacket;
import net.sf.jaer.event.EventPacket;
import net.sf.jaer.event.PolarityEvent;
import net.sf.jaer.eventio.AEInputStream;
import net.sf.jaer.eventprocessing.FilterChain;
import net.sf.jaer.eventprocessing.TimeLimiter;
import net.sf.jaer.eventprocessing.filter.SpatioTemporalCorrelationFilter;
import net.sf.jaer.graphics.AEViewer;
import net.sf.jaer.graphics.FrameAnnotater;
import net.sf.jaer.graphics.ImageDisplay;
import net.sf.jaer.graphics.ImageDisplay.Legend;
import net.sf.jaer.util.DrawGL;
import net.sf.jaer.util.EngineeringFormat;
import net.sf.jaer.util.TobiLogger;
import net.sf.jaer.util.filter.LowpassFilter;
import org.apache.commons.lang3.ArrayUtils;
/**
* Uses patch matching to measureTT local optical flow. <b>Not</b> gradient
* based, but rather matches local features backwards in time.
*
* @author Tobi and Min, Jan 2016
*/
@Description("<html>Computes optical flow with vector direction using adaptive time slice block matching (ABMOF) as published in<br>"
+ "Liu, M., and Delbruck, T. (2018). <a href=\"http://bmvc2018.org/contents/papers/0280.pdf\">Adaptive Time-Slice Block-Matching Optical Flow Algorithm for Dynamic Vision Sensors</a>.<br> in BMVC 2018 (Nescatle upon Tyne)")
@DevelopmentStatus(DevelopmentStatus.Status.Experimental)
public class PatchMatchFlow extends AbstractMotionFlow implements Observer, FrameAnnotater {
/* LDSP is Large Diamond Search Pattern, and SDSP mens Small Diamond Search Pattern.
LDSP has 9 points and SDSP consists of 5 points.
*/
private static final int LDSP[][] = {{0, -2}, {-1, -1}, {1, -1}, {-2, 0}, {0, 0},
{2, 0}, {-1, 1}, {1, 1}, {0, 2}};
private static final int SDSP[][] = {{0, -1}, {-1, 0}, {0, 0}, {1, 0}, {0, 1}};
// private int[][][] histograms = null;
private int numSlices = 3; //getInt("numSlices", 3); // fix to 4 slices to compute error sign from min SAD result from t-2d to t-3d
volatile private int numScales = getInt("numScales", 3); //getInt("numSlices", 3); // fix to 4 slices to compute error sign from min SAD result from t-2d to t-3d
private String scalesToCompute = getString("scalesToCompute", ""); //getInt("numSlices", 3); // fix to 4 slices to compute error sign from min SAD result from t-2d to t-3d
private Integer[] scalesToComputeArray = null; // holds array of scales to actually compute, for debugging
private int[] scaleResultCounts = new int[numScales]; // holds counts at each scale for min SAD results
/**
* The computed average possible match distance from 0 motion
*/
protected float avgPossibleMatchDistance;
private static final int MIN_SLICE_EVENT_COUNT_FULL_FRAME = 1000;
private static final int MAX_SLICE_EVENT_COUNT_FULL_FRAME = 1000000;
// private int sx, sy;
private int currentSliceIdx = 0; // the slice we are currently filling with events
/**
* time slice 2d histograms of (maybe signed) event counts slices = new
* byte[numSlices][numScales][subSizeX][subSizeY] [slice][scale][x][y]
*/
private byte[][][][] slices = null;
private float[] sliceSummedSADValues = null; // tracks the total summed SAD differences between reference and past slices, to adjust the slice duration
private int[] sliceSummedSADCounts = null; // tracks the total summed SAD differences between reference and past slices, to adjust the slice duration
private int[] sliceStartTimeUs; // holds the time interval between reference slice and this slice
private int[] sliceEndTimeUs; // holds the time interval between reference slice and this slice
private byte[][][] currentSlice;
private SADResult lastGoodSadResult = new SADResult(0, 0, 0, 0); // used for consistency check
private int blockDimension = getInt("blockDimension", 23);
// private float cost = getFloat("cost", 0.001f);
private float maxAllowedSadDistance = getFloat("maxAllowedSadDistance", .5f);
private float validPixOccupancy = getFloat("validPixOccupancy", 0.01f); // threshold for valid pixel percent for one block
private float weightDistance = getFloat("weightDistance", 0.95f); // confidence value consists of the distance and the dispersion, this value set the distance value
private static final int MAX_SKIP_COUNT = 1000;
private int skipProcessingEventsCount = getInt("skipProcessingEventsCount", 0); // skip this many events for processing (but not for accumulating to bitmaps)
private int skipCounter = 0;
private boolean adaptiveEventSkipping = getBoolean("adaptiveEventSkipping", true);
private float skipChangeFactor = (float) Math.sqrt(2); // by what factor to change the skip count if too slow or too fast
private boolean outputSearchErrorInfo = false; // make user choose this slow down every time
private boolean adaptiveSliceDuration = getBoolean("adaptiveSliceDuration", true);
private boolean adaptiveSliceDurationLogging = false; // for debugging and analyzing control of slice event number/duration
private TobiLogger adaptiveSliceDurationLogger = null;
private int adaptiveSliceDurationPacketCount = 0;
private boolean useSubsampling = getBoolean("useSubsampling", false);
private int adaptiveSliceDurationMinVectorsToControl = getInt("adaptiveSliceDurationMinVectorsToControl", 10);
private boolean showBlockMatches = getBoolean("showBlockMatches", false); // Display the bitmaps
private boolean showSlices = false; // Display the bitmaps
private int showSlicesScale = 0; // Display the bitmaps
private float adapativeSliceDurationProportionalErrorGain = getFloat("adapativeSliceDurationProportionalErrorGain", 0.05f); // factor by which an error signal on match distance changes slice duration
private boolean adapativeSliceDurationUseProportionalControl = getBoolean("adapativeSliceDurationUseProportionalControl", false);
private int processingTimeLimitMs = getInt("processingTimeLimitMs", 100); // time limit for processing packet in ms to process OF events (events still accumulate). Overrides the system EventPacket timelimiter, which cannot be used here because we still need to accumulate and render the events.
private int sliceMaxValue = getInt("sliceMaxValue", 7);
private boolean rectifyPolarties = getBoolean("rectifyPolarties", false);
private TimeLimiter timeLimiter = new TimeLimiter(); // private instance used to accumulate events to slices even if packet has timed out
// results histogram for each packet
// private int ANGLE_HISTOGRAM_COUNT = 16;
// private int[] resultAngleHistogram = new int[ANGLE_HISTOGRAM_COUNT + 1];
private int[][] resultHistogram = null;
// private int resultAngleHistogramCount = 0, resultAngleHistogramMax = 0;
private int resultHistogramCount;
private volatile float avgMatchDistance = 0; // stores average match distance for rendering it
private float histStdDev = 0, lastHistStdDev = 0;
private float FSCnt = 0, DSCorrectCnt = 0;
float DSAverageNum = 0, DSAveError[] = {0, 0}; // Evaluate DS cost average number and the error.
// private float lastErrSign = Math.signum(1);
// private final String outputFilename;
private int sliceDeltaT; // The time difference between two slices used for velocity caluction. For constantDuration, this one is equal to the duration. For constantEventNumber, this value will change.
private int MIN_SLICE_DURATION_US = 100;
private int MAX_SLICE_DURATION_US = 300000;
private boolean enableImuTimesliceLogging = false;
private TobiLogger imuTimesliceLogger = null;
private volatile boolean resetOFHistogramFlag; // signals to reset the OF histogram after it is rendered
public enum PatchCompareMethod {
/*JaccardDistance,*/ /*HammingDistance*/
SAD/*, EventSqeDistance*/
};
private PatchCompareMethod patchCompareMethod = null;
public enum SearchMethod {
FullSearch, DiamondSearch, CrossDiamondSearch
};
private SearchMethod searchMethod = SearchMethod.valueOf(getString("searchMethod", SearchMethod.DiamondSearch.toString()));
private int sliceDurationUs = getInt("sliceDurationUs", 20000);
private int sliceEventCount = getInt("sliceEventCount", 1000);
private boolean rewindFlg = false; // The flag to indicate the rewind event.
private boolean displayResultHistogram = getBoolean("displayResultHistogram", true);
public enum SliceMethod {
ConstantDuration, ConstantEventNumber, AreaEventNumber, ConstantIntegratedFlow
};
private SliceMethod sliceMethod = SliceMethod.valueOf(getString("sliceMethod", SliceMethod.AreaEventNumber.toString()));
// counting events into subsampled areas, when count exceeds the threshold in any area, the slices are rotated
private int areaEventNumberSubsampling = getInt("areaEventNumberSubsampling", 5);
private int[][] areaCounts = null;
private int numAreas = 1;
private boolean areaCountExceeded = false;
// nongreedy flow evaluation
// the entire scene is subdivided into regions, and a bitmap of these regions distributed flow computation more fairly
// by only servicing a region when sufficient fraction of other regions have been serviced first
private boolean nonGreedyFlowComputingEnabled = getBoolean("nonGreedyFlowComputingEnabled", false);
private boolean[][] nonGreedyRegions = null;
private int nonGreedyRegionsNumberOfRegions, nonGreedyRegionsCount;
/**
* This fraction of the regions must be serviced for computing flow before
* we reset the nonGreedyRegions map
*/
private float nonGreedyFractionToBeServiced = getFloat("nonGreedyFractionToBeServiced", .5f);
// Print scale count's statics
private boolean printScaleCntStatEnabled = getBoolean("printScaleCntStatEnabled", false);
// timers and flags for showing filter properties temporarily
private final int SHOW_STUFF_DURATION_MS = 4000;
private volatile TimerTask stopShowingStuffTask = null;
private boolean showBlockSizeAndSearchAreaTemporarily = false;
private volatile boolean showAreaCountAreasTemporarily = false;
private int eventCounter = 0;
private int sliceLastTs = Integer.MAX_VALUE;
private JFrame blockMatchingFrame[] = new JFrame[numScales];
private JFrame blockMatchingFrameTarget[] = new JFrame[numScales];
private ImageDisplay blockMatchingImageDisplay[] = new ImageDisplay[numScales];
private ImageDisplay blockMatchingImageDisplayTarget[] = new ImageDisplay[numScales]; // makde a new ImageDisplay GLCanvas with default OpenGL capabilities
private Legend blockMatchingDisplayLegend[] = new Legend[numScales];
private Legend blockMatchingDisplayLegendTarget[] = new Legend[numScales];
private static final String LEGEND_G_SEARCH_AREA_R_REF_BLOCK_AREA_B_BEST_MATCH = "G: search area\nR: ref block area\nB: best match";
private JFrame sliceBitMapFrame = null;
private ImageDisplay sliceBitmapImageDisplay; // makde a new ImageDisplay GLCanvas with default OpenGL capabilities
private Legend sliceBitmapImageDisplayLegend;
private static final String LEGEND_SLICES = "G: Slice t-d\nR: Slice t-2d";
private JFrame timeStampBlockFrame = null;
private ImageDisplay timeStampBlockImageDisplay; // makde a new ImageDisplay GLCanvas with default OpenGL capabilities
private Legend timeStampBlockImageDisplayLegend;
private static final String TIME_STAMP_BLOCK_LEGEND_SLICES = "R: Inner Circle\nB: Outer Circle\nG: Current event";
private static final int innerCircle[][] = {{0, 3}, {1, 3}, {2, 2}, {3, 1},
{3, 0}, {3, -1}, {2, -2}, {1, -3},
{0, -3}, {-1, -3}, {-2, -2}, {-3, -1},
{-3, 0}, {-3, 1}, {-2, 2}, {-1, 3}};
private static final int outerCircle[][] = {{0, 4}, {1, 4}, {2, 3}, {3, 2},
{4, 1}, {4, 0}, {4, -1}, {3, -2},
{2, -3}, {1, -4}, {0, -4}, {-1, -4},
{-2, -3}, {-3, -2}, {-4, -1}, {-4, 0},
{-4, 1}, {-3, 2}, {-2, 3}, {-1, 4}};
int innerTsValue[] = new int[16];
int outerTsValue[] = new int[20];
private HWCornerPointRenderer keypointFilter = null;
/**
* A PropertyChangeEvent with this value is fired when the slices has been
* rotated. The oldValue is t-2d slice. The newValue is the t-d slice.
*/
public static final String EVENT_NEW_SLICES = "eventNewSlices";
TobiLogger sadValueLogger = new TobiLogger("sadvalues", "sadvalue,scale"); // TODO debug
private boolean calcOFonCornersEnabled = getBoolean("calcOFonCornersEnabled", false);
public PatchMatchFlow(AEChip chip) {
super(chip);
getEnclosedFilterChain().clear();
// getEnclosedFilterChain().add(new SpatioTemporalCorrelationFilter(chip));
keypointFilter = new HWCornerPointRenderer(chip);
getEnclosedFilterChain().add(keypointFilter);
setSliceDurationUs(getSliceDurationUs()); // 40ms is good for the start of the slice duration adatative since 4ms is too fast and 500ms is too slow.
setDefaultScalesToCompute();
// // Save the result to the file
// Format formatter = new SimpleDateFormat("YYYY-MM-dd_hh-mm-ss");
// // Instantiate a Date object
// Date date = new Date();
// Log file for the OF distribution's statistics
// outputFilename = "PMF_HistStdDev" + formatter.format(date) + ".txt";
String patchTT = "0a: Block matching";
// String eventSqeMatching = "Event squence matching";
// String preProcess = "Denoise";
String metricConfid = "Confidence of current metric";
try {
patchCompareMethod = PatchCompareMethod.valueOf(getString("patchCompareMethod", PatchCompareMethod.SAD.toString()));
} catch (IllegalArgumentException e) {
patchCompareMethod = PatchCompareMethod.SAD;
}
chip.addObserver(this); // to allocate memory once chip size is known
setPropertyTooltip(metricConfid, "maxAllowedSadDistance", "<html>SAD distance threshold for rejecting unresonable block matching result; <br> events with SAD distance larger than this value are rejected. <p>Lower value means it is harder to accept the event.");
setPropertyTooltip(metricConfid, "validPixOccupancy", "<html>Threshold for valid pixel percent for each block; Range from 0 to 1. <p>If either matching block is less occupied than this fraction, no motion vector will be calculated.");
setPropertyTooltip(metricConfid, "weightDistance", "<html>The confidence value consists of the distance and the dispersion; <br>weightDistance sets the weighting of the distance value compared with the dispersion value; Range from 0 to 1. <p>To count only e.g. hamming distance, set weighting to 1. <p> To count only dispersion, set to 0.");
setPropertyTooltip(patchTT, "blockDimension", "linear dimenion of patches to match, in pixels");
setPropertyTooltip(patchTT, "searchDistance", "search distance for matching patches, in pixels");
setPropertyTooltip(patchTT, "patchCompareMethod", "method to compare two patches; SAD=sum of absolute differences, HammingDistance is same as SAD for binary bitmaps");
setPropertyTooltip(patchTT, "searchMethod", "method to search patches");
setPropertyTooltip(patchTT, "sliceDurationUs", "duration of bitmaps in us, also called sample interval, when ConstantDuration method is used");
setPropertyTooltip(patchTT, "sliceEventCount", "number of events collected to fill a slice, when ConstantEventNumber method is used");
setPropertyTooltip(patchTT, "sliceMethod", "<html>Method for determining time slice duration for block matching<ul>"
+ "<li>ConstantDuration: slices are fixed time duration"
+ "<li>ConstantEventNumber: slices are fixed event number"
+ "<li>AreaEventNumber: slices are fixed event number in any subsampled area defined by areaEventNumberSubsampling"
+ "<li>ConstantIntegratedFlow: slices are rotated when average speeds times delta time exceeds half the search distance");
setPropertyTooltip(patchTT, "areaEventNumberSubsampling", "<html>how to subsample total area to count events per unit subsampling blocks for AreaEventNumber method. <p>For example, if areaEventNumberSubsampling=5, <br> then events falling into 32x32 blocks of pixels are counted <br>to determine when they exceed sliceEventCount to make new slice");
setPropertyTooltip(patchTT, "adapativeSliceDurationProportionalErrorGain", "gain for proporportional change of duration or slice event number. typically 0.05f for bang-bang, and 0.5f for proportional control");
setPropertyTooltip(patchTT, "adapativeSliceDurationUseProportionalControl", "If true, then use proportional error control. If false, use bang-bang control with sign of match distance error");
setPropertyTooltip(patchTT, "skipProcessingEventsCount", "skip this many events for processing (but not for accumulating to bitmaps)");
setPropertyTooltip(patchTT, "adaptiveEventSkipping", "enables adaptive event skipping depending on free time left in AEViewer animation loop");
setPropertyTooltip(patchTT, "adaptiveSliceDuration", "<html>Enables adaptive slice duration using feedback control, <br> based on average match search distance compared with total search distance. <p>If the match distance is too small, increaes duration or event count, and if too far, decreases duration or event count.<p>If using <i>AreaEventNumber</i> slice rotation method, don't increase count if actual duration is already longer than <i>sliceDurationUs</i>");
setPropertyTooltip(patchTT, "nonGreedyFlowComputingEnabled", "<html>Enables fairer distribution of computing flow by areas; an area is only serviced after " + nonGreedyFractionToBeServiced + " fraction of areas have been serviced. <p> Areas are defined by the the area subsubsampling bit shift.<p>Enabling this option ignores event skipping, so use <i>processingTimeLimitMs</i> to ensure minimum frame rate");
setPropertyTooltip(patchTT, "nonGreedyFractionToBeServiced", "An area is only serviced after " + nonGreedyFractionToBeServiced + " fraction of areas have been serviced. <p> Areas are defined by the the area subsubsampling bit shift.<p>Enabling this option ignores event skipping, so use the timeLimiter to ensure minimum frame rate");
setPropertyTooltip(patchTT, "useSubsampling", "<html>Enables using both full and subsampled block matching; <p>when using adaptiveSliceDuration, enables adaptive slice duration using feedback controlusing difference between full and subsampled resolution slice matching");
setPropertyTooltip(patchTT, "adaptiveSliceDurationMinVectorsToControl", "<html>Min flow vectors computed in packet to control slice duration, increase to reject control during idle periods");
setPropertyTooltip(patchTT, "processingTimeLimitMs", "<html>time limit for processing packet in ms to process OF events (events still accumulate). <br> Set to 0 to disable. <p>Alternative to the system EventPacket timelimiter, which cannot be used here because we still need to accumulate and render the events");
setPropertyTooltip(patchTT, "outputSearchErrorInfo", "enables displaying the search method error information");
setPropertyTooltip(patchTT, "outlierMotionFilteringEnabled", "(Currently has no effect) discards first optical flow event that points in opposite direction as previous one (dot product is negative)");
setPropertyTooltip(patchTT, "numSlices", "<html>Number of bitmaps to use. <p>At least 3: 1 to collect on, and two more to match on. <br>If >3, then best match is found between last slice reference block and all previous slices.");
setPropertyTooltip(patchTT, "numScales", "<html>Number of scales to search over for minimum SAD value; 1 for single full resolution scale, 2 for full + 2x2 subsampling, etc.");
setPropertyTooltip(patchTT, "sliceMaxValue", "<html> the maximum value used to represent each pixel in the time slice:<br>1 for binary or signed binary slice, (in conjunction with rectifyEventPolarities==true), etc, <br>up to 127 by these byte values");
setPropertyTooltip(patchTT, "rectifyPolarties", "<html> whether to rectify ON and OFF polarities to unsigned counts; true ignores polarity for block matching, false uses polarity with sliceNumBits>1");
setPropertyTooltip(patchTT, "scalesToCompute", "Scales to compute, e.g. 1,2; blank for all scales. 0 is full resolution, 1 is subsampled 2x2, etc");
setPropertyTooltip(patchTT, "defaults", "Sets reasonable defaults");
setPropertyTooltip(patchTT, "enableImuTimesliceLogging", "Logs IMU and rate gyro");
setPropertyTooltip(patchTT, "calcOFonCornersEnabled", "Calculate OF based on corners or not");
String patchDispTT = "0b: Block matching display";
setPropertyTooltip(patchDispTT, "showSlices", "enables displaying the entire bitmaps slices (the current slices)");
setPropertyTooltip(patchDispTT, "showSlicesScale", "sets which scale of the slices to display");
setPropertyTooltip(patchDispTT, "showBlockMatches", "enables displaying the individual block matches");
setPropertyTooltip(patchDispTT, "ppsScale", "scale of pixels per second to draw local motion vectors; global vectors are scaled up by an additional factor of " + GLOBAL_MOTION_DRAWING_SCALE);
setPropertyTooltip(patchDispTT, "displayOutputVectors", "display the output motion vectors or not");
setPropertyTooltip(patchDispTT, "displayResultHistogram", "display the output motion vectors histogram to show disribution of results for each packet. Only implemented for HammingDistance");
setPropertyTooltip(patchDispTT, "printScaleCntStatEnabled", "enables printing the statics of scale counts");
getSupport().addPropertyChangeListener(AEViewer.EVENT_TIMESTAMPS_RESET, this);
getSupport().addPropertyChangeListener(AEViewer.EVENT_FILEOPEN, this);
getSupport().addPropertyChangeListener(AEInputStream.EVENT_REWOUND, this);
getSupport().addPropertyChangeListener(AEInputStream.EVENT_NON_MONOTONIC_TIMESTAMP, this);
computeAveragePossibleMatchDistance();
numInputTypes = 2; // allocate timestamp map
}
// TODO debug
public void doStartLogSadValues() {
sadValueLogger.setEnabled(true);
}
// TODO debug
public void doStopLogSadValues() {
sadValueLogger.setEnabled(false);
}
@Override
synchronized public EventPacket filterPacket(EventPacket in) {
setupFilter(in);
checkArrays();
if (processingTimeLimitMs > 0) {
timeLimiter.setTimeLimitMs(processingTimeLimitMs);
timeLimiter.restart();
} else {
timeLimiter.setEnabled(false);
}
int minDistScale = 0;
// following awkward block needed to deal with DVS/DAVIS and IMU/APS events
// block STARTS
Iterator i = null;
if (in instanceof ApsDvsEventPacket) {
i = ((ApsDvsEventPacket) in).fullIterator();
} else {
i = ((EventPacket) in).inputIterator();
}
nSkipped = 0;
nProcessed = 0;
while (i.hasNext()) {
Object o = i.next();
if (o == null) {
log.warning("null event passed in, returning input packet");
return in;
}
if ((o instanceof ApsDvsEvent) && ((ApsDvsEvent) o).isApsData()) {
continue;
}
PolarityEvent ein = (PolarityEvent) o;
if (!extractEventInfo(o)) {
continue;
}
if (measureAccuracy || discardOutliersForStatisticalMeasurementEnabled) {
if (imuFlowEstimator.calculateImuFlow(o)) {
continue;
}
}
// block ENDS
if (isInvalidTimestamp()) {
continue;
}
if (xyFilter()) {
continue;
}
countIn++;
// compute flow
SADResult result = null;
float[] sadVals = new float[numScales]; // TODO debug
int[] dxInitVals = new int[numScales];
int[] dyInitVals = new int[numScales];
switch (patchCompareMethod) {
case SAD:
boolean rotated = maybeRotateSlices();
if (rotated) {
adaptSliceDuration();
setResetOFHistogramFlag();
}
// if (ein.x >= subSizeX || ein.y > subSizeY) {
// log.warning("event out of range");
// continue;
if (!accumulateEvent(ein)) { // maybe skip events here
break;
}
if(ein.timestamp == 296004143)
{
int tmp = 1;
}
SADResult sliceResult = new SADResult();
minDistScale = 0;
// Sorts scalesToComputeArray[] in descending order
Arrays.sort(scalesToComputeArray, Collections.reverseOrder());
for (int scale : scalesToComputeArray) {
if (scale >= numScales) {
// log.warning("scale " + scale + " is out of range of " + numScales + "; fix scalesToCompute for example by clearing it");
// break;
}
int dx_init = ((result != null) && !isNotSufficientlyAccurate(sliceResult)) ? (sliceResult.dx >> scale) : 0;
int dy_init = ((result != null) && !isNotSufficientlyAccurate(sliceResult)) ? (sliceResult.dy >> scale) : 0;
// dx_init = 0;
// dy_init = 0;
// The reason why we inverse dx_init, dy_init i is the offset is pointing from previous slice to current slice.
// The dx_init, dy_init are from the corse scale's result, and it is used as the finer scale's initial guess.
sliceResult = minSADDistance(ein.x, ein.y, -dx_init, -dy_init, slices[sliceIndex(1)], slices[sliceIndex(2)], scale); // from ref slice to past slice k+1, using scale 0,1,....
// sliceSummedSADValues[sliceIndex(scale + 2)] += sliceResult.sadValue; // accumulate SAD for this past slice
// sliceSummedSADCounts[sliceIndex(scale + 2)]++; // accumulate SAD count for this past slice
// sliceSummedSADValues should end up filling 2 values for 4 slices
sadVals[scale] = sliceResult.sadValue; // TODO debug
dxInitVals[scale] = dx_init;
dyInitVals[scale] = dy_init;
if(sliceResult.sadValue >= this.maxAllowedSadDistance)
{
break;
}
else
{
if ((result == null) || (sliceResult.sadValue < result.sadValue)) {
result = sliceResult; // result holds the overall min sad result
minDistScale = scale;
}
}
// result=sliceResult; // TODO tobi: override the absolute minimum to always use the finest scale result, which has been guided by coarser scales
}
result = sliceResult;
minDistScale = 0;
float dt = (sliceDeltaTimeUs(2) * 1e-6f);
if (result != null) {
result.vx = result.dx / dt; // hack, convert to pix/second
result.vy = result.dy / dt; // TODO clean up, make time for each slice, since could be different when const num events
}
break;
// case JaccardDistance:
// maybeRotateSlices();
// if (!accumulateEvent(in)) {
// break;
// result = minJaccardDistance(x, y, bitmaps[sliceIndex(2)], bitmaps[sliceIndex(1)]);
// float dtj=(sliceDeltaTimeUs(2) * 1e-6f);
// result.dx = result.dx / dtj;
// result.dy = result.dy / dtj;
// break;
}
if (result == null || result.sadValue == Float.MAX_VALUE) {
continue; // maybe some property change caused this
}
// reject values that are unreasonable
if (isNotSufficientlyAccurate(result)) {
continue;
}
scaleResultCounts[minDistScale]++;
vx = result.vx;
vy = result.vy;
v = (float) Math.sqrt((vx * vx) + (vy * vy));
// TODO debug
StringBuilder sadValsString = new StringBuilder();
for (int k = 0; k < sadVals.length - 1; k++) {
sadValsString.append(String.format("%f,", sadVals[k]));
}
sadValsString.append(String.format("%f", sadVals[sadVals.length - 1])); // very awkward to prevent trailing ,
if (sadValueLogger.isEnabled()) { // TODO debug
sadValueLogger.log(sadValsString.toString());
}
if (showBlockMatches) {
// TODO danger, drawing outside AWT thread
final SADResult thisResult = result;
final PolarityEvent thisEvent = ein;
final byte[][][][] thisSlices = slices;
// SwingUtilities.invokeLater(new Runnable() {
// @Override
// public void run() {
drawMatching(thisResult, thisEvent, thisSlices, sadVals, dxInitVals, dyInitVals); // ein.x >> result.scale, ein.y >> result.scale, (int) result.dx >> result.scale, (int) result.dy >> result.scale, slices[sliceIndex(1)][result.scale], slices[sliceIndex(2)][result.scale], result.scale);
drawTimeStampBlock(thisEvent);
}
if(Math.abs(result.dy) >= 3)
{
int tmp = 0;
}
if(ein.timestamp == 295914282)
{
int tmp = 1;
}
if (resultHistogram != null) {
resultHistogram[result.xidx][result.yidx]++;
resultHistogramCount++;
}
// if (result.dx != 0 || result.dy != 0) {
// final int bin = (int) Math.round(ANGLE_HISTOGRAM_COUNT * (Math.atan2(result.dy, result.dx) + Math.PI) / (2 * Math.PI));
// int v = ++resultAngleHistogram[bin];
// resultAngleHistogramCount++;
// if (v > resultAngleHistogramMax) {
// resultAngleHistogramMax = v;
processGoodEvent();
lastGoodSadResult.set(result);
}
motionFlowStatistics.updatePacket(countIn, countOut, ts);
adaptEventSkipping();
if (rewindFlg) {
rewindFlg = false;
for (byte[][][] b : slices) {
clearSlice(b);
}
currentSliceIdx = 0; // start by filling slice 0
currentSlice = slices[currentSliceIdx];
sliceLastTs = Integer.MAX_VALUE;
}
return isDisplayRawInput() ? in : dirPacket;
}
public void doDefaults() {
setSearchMethod(SearchMethod.DiamondSearch);
setBlockDimension(21);
setNumScales(2);
setSearchDistance(4);
setAdaptiveEventSkipping(true);
setAdaptiveSliceDuration(true);
setMaxAllowedSadDistance(.5f);
setDisplayVectorsEnabled(true);
setPpsScaleDisplayRelativeOFLength(true);
setDisplayGlobalMotion(true);
setPpsScale(.1f);
setSliceMaxValue(7);
setRectifyPolarties(true); // rectify to better handle cases of steadicam where pan/tilt flips event polarities
setValidPixOccupancy(.01f); // at least this fraction of pixels from each block must both have nonzero values
setSliceMethod(SliceMethod.AreaEventNumber);
// compute nearest power of two over block dimension
int ss = (int) (Math.log(blockDimension - 1) / Math.log(2));
setAreaEventNumberSubsampling(ss);
// set event count so that count=block area * sliceMaxValue/4;
// i.e. set count to roll over when slice pixels from most subsampled scale are half full if they are half stimulated
final int eventCount = (((blockDimension * blockDimension) * sliceMaxValue) / 2) >> (numScales - 1);
setSliceEventCount(eventCount);
setSliceDurationUs(50000); // set a bit smaller max duration in us to avoid instability where count gets too high with sparse input
}
private void adaptSliceDuration() {
// measure last hist to get control signal on slice duration
// measures avg match distance. weights the average so that long distances with more pixels in hist are not overcounted, simply
// by having more pixels.
if (rewindFlg) {
return; // don't adapt during rewind or delay before playing again
}
float radiusSum = 0;
int countSum = 0;
// int maxRadius = (int) Math.ceil(Math.sqrt(2 * searchDistance * searchDistance));
// int countSum = 0;
final int totSD = searchDistance << (numScales - 1);
for (int xx = -totSD; xx <= totSD; xx++) {
for (int yy = -totSD; yy <= totSD; yy++) {
int count = resultHistogram[xx + totSD][yy + totSD];
if (count > 0) {
final float radius = (float) Math.sqrt((xx * xx) + (yy * yy));
countSum += count;
radiusSum += radius * count;
}
}
}
if (countSum > 0) {
avgMatchDistance = radiusSum / (countSum); // compute average match distance from reference block
}
if (adaptiveSliceDuration && (countSum > adaptiveSliceDurationMinVectorsToControl)) {
// if (resultHistogramCount > 0) {
// following stats not currently used
// double[] rstHist1D = new double[resultHistogram.length * resultHistogram.length];
// int index = 0;
//// int rstHistMax = 0;
// for (int[] resultHistogram1 : resultHistogram) {
// for (int element : resultHistogram1) {
// rstHist1D[index++] = element;
// Statistics histStats = new Statistics(rstHist1D);
// // double histMax = Collections.max(Arrays.asList(ArrayUtils.toObject(rstHist1D)));
// double histMax = histStats.getMax();
// for (int m = 0; m < rstHist1D.length; m++) {
// rstHist1D[m] = rstHist1D[m] / histMax;
// lastHistStdDev = histStdDev;
// histStdDev = (float) histStats.getStdDev();
// try (FileWriter outFile = new FileWriter(outputFilename,true)) {
// outFile.write(String.format(in.getFirstEvent().getTimestamp() + " " + histStdDev + "\r\n"));
// outFile.close();
// } catch (IOException ex) {
// Logger.getLogger(PatchMatchFlow.class.getName()).log(Level.SEVERE, null, ex);
// } catch (Exception e) {
// log.warning("Caught " + e + ". See following stack trace.");
// e.printStackTrace();
// float histMean = (float) histStats.getMean();
// compute error signal.
// If err<0 it means the average match distance is larger than target avg match distance, so we need to reduce slice duration
// If err>0, it means the avg match distance is too short, so increse time slice
final float err = avgMatchDistance / (avgPossibleMatchDistance); // use target that is smaller than average possible to bound excursions to large slices better
// final float err = avgPossibleMatchDistance / 2 - avgMatchDistance; // use target that is smaller than average possible to bound excursions to large slices better
// final float err = ((searchDistance << (numScales - 1)) / 2) - avgMatchDistance;
// final float lastErr = searchDistance / 2 - lastHistStdDev;
// final double err = histMean - 1/ (rstHist1D.length * rstHist1D.length);
float errSign = Math.signum(err - 1);
// float avgSad2 = sliceSummedSADValues[sliceIndex(4)] / sliceSummedSADCounts[sliceIndex(4)];
// float avgSad3 = sliceSummedSADValues[sliceIndex(3)] / sliceSummedSADCounts[sliceIndex(3)];
// float errSign = avgSad2 <= avgSad3 ? 1 : -1;
// if(Math.abs(err) > Math.abs(lastErr)) {
// errSign = -errSign;
// if(histStdDev >= 0.14) {
// if(lastHistStdDev > histStdDev) {
// errSign = -lastErrSign;
// } else {
// errSign = lastErrSign;
// errSign = 1;
// } else {
// errSign = (float) Math.signum(err);
// lastErrSign = errSign;
// problem with following is that if sliceDurationUs gets really big, then of course the avgMatchDistance becomes small because
// of the biased-towards-zero search policy that selects the closest match
switch (sliceMethod) {
case ConstantDuration:
if (adapativeSliceDurationUseProportionalControl) { // proportional
setSliceDurationUs(Math.round((1 / (1 + (err - 1) * adapativeSliceDurationProportionalErrorGain)) * sliceDurationUs));
} else { // bang bang
int durChange = (int) (-errSign * adapativeSliceDurationProportionalErrorGain * sliceDurationUs);
setSliceDurationUs(sliceDurationUs + durChange);
}
break;
case ConstantEventNumber:
case AreaEventNumber:
if (adapativeSliceDurationUseProportionalControl) { // proportional
setSliceEventCount(Math.round((1 / (1 + (err - 1) * adapativeSliceDurationProportionalErrorGain)) * sliceEventCount));
} else {
if (errSign < 0) { // match distance too short, increase duration
// match too short, increase count
setSliceEventCount(Math.round(sliceEventCount * (1 + adapativeSliceDurationProportionalErrorGain)));
} else if (errSign > 0) { // match too long, decrease duration
setSliceEventCount(Math.round(sliceEventCount * (1 - adapativeSliceDurationProportionalErrorGain)));
}
}
break;
case ConstantIntegratedFlow:
setSliceEventCount(eventCounter);
}
if (adaptiveSliceDurationLogger != null && adaptiveSliceDurationLogger.isEnabled()) {
if (!isDisplayGlobalMotion()) {
setDisplayGlobalMotion(true);
}
adaptiveSliceDurationLogger.log(String.format("%d\t%f\t%f\t%f\t%d\t%d", adaptiveSliceDurationPacketCount++, avgMatchDistance, err, motionFlowStatistics.getGlobalMotion().getGlobalSpeed().getMean(), sliceDurationUs, sliceEventCount));
}
}
}
private void setResetOFHistogramFlag() {
resetOFHistogramFlag = true;
}
private void clearResetOFHistogramFlag() {
resetOFHistogramFlag = false;
}
private void resetOFHistogram() {
if (!resetOFHistogramFlag || resultHistogram == null) {
return;
}
for (int[] h : resultHistogram) {
Arrays.fill(h, 0);
}
resultHistogramCount = 0;
// Arrays.fill(resultAngleHistogram, 0);
// resultAngleHistogramCount = 0;
// resultAngleHistogramMax = Integer.MIN_VALUE;
// Print statics of scale count, only for debuuging.
if (printScaleCntStatEnabled) {
float sumScaleCounts = 0;
for (int scale : scalesToComputeArray) {
sumScaleCounts += scaleResultCounts[scale];
}
for (int scale : scalesToComputeArray) {
System.out.println("Scale " + scale + " count percentage is: " + scaleResultCounts[scale] / sumScaleCounts);
}
}
Arrays.fill(scaleResultCounts, 0);
clearResetOFHistogramFlag();
}
private EngineeringFormat engFmt = new EngineeringFormat();
private TextRenderer textRenderer = null;
@Override
synchronized public void annotate(GLAutoDrawable drawable) {
super.annotate(drawable);
GL2 gl = drawable.getGL().getGL2();
try {
gl.glEnable(GL.GL_BLEND);
gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA);
gl.glBlendEquation(GL.GL_FUNC_ADD);
} catch (GLException e) {
e.printStackTrace();
}
if (displayResultHistogram && (resultHistogram != null)) {
// draw histogram as shaded in 2d hist above color wheel
// normalize hist
int rhDim = resultHistogram.length; // 2*(searchDistance<<numScales)+1
gl.glPushMatrix();
final float scale = 30f / rhDim; // size same as the color wheel
gl.glTranslatef(-35, .65f * chip.getSizeY(), 0); // center above color wheel
gl.glScalef(scale, scale, 1);
gl.glColor3f(0, 0, 1);
gl.glLineWidth(2f);
gl.glBegin(GL.GL_LINE_LOOP);
gl.glVertex2f(0, 0);
gl.glVertex2f(rhDim, 0);
gl.glVertex2f(rhDim, rhDim);
gl.glVertex2f(0, rhDim);
gl.glEnd();
if (textRenderer == null) {
textRenderer = new TextRenderer(new Font("SansSerif", Font.PLAIN, 64));
}
int max = 0;
for (int[] h : resultHistogram) {
for (int vv : h) {
if (vv > max) {
max = vv;
}
}
}
if (max == 0) {
gl.glTranslatef(0, rhDim / 2, 0); // translate to UL corner of histogram
textRenderer.begin3DRendering();
textRenderer.draw3D("No data", 0, 0, 0, .07f);
textRenderer.end3DRendering();
gl.glPopMatrix();
} else {
final float maxRecip = 2f / max;
gl.glPushMatrix();
// draw hist values
for (int xx = 0; xx < rhDim; xx++) {
for (int yy = 0; yy < rhDim; yy++) {
float g = maxRecip * resultHistogram[xx][yy];
gl.glColor3f(g, g, g);
gl.glBegin(GL2ES3.GL_QUADS);
gl.glVertex2f(xx, yy);
gl.glVertex2f(xx + 1, yy);
gl.glVertex2f(xx + 1, yy + 1);
gl.glVertex2f(xx, yy + 1);
gl.glEnd();
}
}
final int tsd = searchDistance << (numScales - 1);
if (avgMatchDistance > 0) {
gl.glPushMatrix();
gl.glColor4f(1f, 0, 0, .5f);
gl.glLineWidth(5f);
DrawGL.drawCircle(gl, tsd + .5f, tsd + .5f, avgMatchDistance, 16);
gl.glPopMatrix();
}
if (avgPossibleMatchDistance > 0) {
gl.glPushMatrix();
gl.glColor4f(0, 1f, 0, .5f);
gl.glLineWidth(5f);
DrawGL.drawCircle(gl, tsd + .5f, tsd + .5f, avgPossibleMatchDistance / 2, 16); // draw circle at target match distance
gl.glPopMatrix();
}
// a bunch of cryptic crap to draw a string the same width as the histogram...
gl.glPopMatrix();
gl.glPopMatrix(); // back to original chip coordinates
gl.glPushMatrix();
textRenderer.begin3DRendering();
String s = String.format("d=%.1f ms", 1e-3f * sliceDeltaT);
// final float sc = TextRendererScale.draw3dScale(textRenderer, s, chip.getCanvas().getScale(), chip.getWidth(), .1f);
// determine width of string in pixels and scale accordingly
FontRenderContext frc = textRenderer.getFontRenderContext();
Rectangle2D r = textRenderer.getBounds(s); // bounds in java2d coordinates, downwards more positive
Rectangle2D rt = frc.getTransform().createTransformedShape(r).getBounds2D(); // get bounds in textrenderer coordinates
// float ps = chip.getCanvas().getScale();
float w = (float) rt.getWidth(); // width of text in textrenderer, i.e. histogram cell coordinates (1 unit = 1 histogram cell)
float sc = subSizeX / w / 6; // scale to histogram width
gl.glTranslatef(0, .65f * subSizeY, 0); // translate to UL corner of histogram
textRenderer.draw3D(s, 0, 0, 0, sc);
String s2 = String.format("Skip: %d", skipProcessingEventsCount);
textRenderer.draw3D(s2, 0, (float) (rt.getHeight()) * sc, 0, sc);
String s3 = String.format("Slice events: %d", sliceEventCount);
textRenderer.draw3D(s3, 0, 2 * (float) (rt.getHeight()) * sc, 0, sc);
StringBuilder sb = new StringBuilder("Scale counts: ");
for (int c : scaleResultCounts) {
sb.append(String.format("%d ", c));
}
textRenderer.draw3D(sb.toString(), 0, (float) (3 * rt.getHeight()) * sc, 0, sc);
if (timeLimiter.isTimedOut()) {
String s4 = String.format("Timed out: skipped %d events", nSkipped);
textRenderer.draw3D(s4, 0, 4 * (float) (rt.getHeight()) * sc, 0, sc);
}
textRenderer.end3DRendering();
gl.glPopMatrix(); // back to original chip coordinates
// log.info(String.format("processed %.1f%% (%d/%d)", 100 * (float) nProcessed / (nSkipped + nProcessed), nProcessed, (nProcessed + nSkipped)));
// // draw histogram of angles around center of image
// if (resultAngleHistogramCount > 0) {
// gl.glPushMatrix();
// gl.glTranslatef(subSizeX / 2, subSizeY / 2, 0);
// gl.glLineWidth(getMotionVectorLineWidthPixels());
// gl.glColor3f(1, 1, 1);
// gl.glBegin(GL.GL_LINES);
// for (int i = 0; i < ANGLE_HISTOGRAM_COUNT; i++) {
// float l = ((float) resultAngleHistogram[i] / resultAngleHistogramMax) * chip.getMinSize() / 2; // bin 0 is angle -PI
// double angle = ((2 * Math.PI * i) / ANGLE_HISTOGRAM_COUNT) - Math.PI;
// float dx = (float) Math.cos(angle) * l, dy = (float) Math.sin(angle) * l;
// gl.glVertex2f(0, 0);
// gl.glVertex2f(dx, dy);
// gl.glEnd();
// gl.glPopMatrix();
resetOFHistogram(); // clears OF histogram if slices have been rotated
}
} else {
resetOFHistogram(); // clears OF histogram if slices have been rotated and we are not displaying the histogram
}
if (sliceMethod == SliceMethod.AreaEventNumber && showAreaCountAreasTemporarily) {
int d = 1 << areaEventNumberSubsampling;
gl.glLineWidth(2f);
gl.glColor3f(1, 1, 1);
gl.glBegin(GL.GL_LINES);
for (int x = 0; x <= subSizeX; x += d) {
gl.glVertex2f(x, 0);
gl.glVertex2f(x, subSizeY);
}
for (int y = 0; y <= subSizeY; y += d) {
gl.glVertex2f(0, y);
gl.glVertex2f(subSizeX, y);
}
gl.glEnd();
}
if (sliceMethod == SliceMethod.ConstantIntegratedFlow && showAreaCountAreasTemporarily) {
// TODO fill in what to draw
}
if (showBlockSizeAndSearchAreaTemporarily) {
gl.glLineWidth(2f);
gl.glColor3f(1, 0, 0);
// show block size
final int xx = subSizeX / 2, yy = subSizeY / 2, d = blockDimension / 2;
gl.glBegin(GL.GL_LINE_LOOP);
gl.glVertex2f(xx - d, yy - d);
gl.glVertex2f(xx + d, yy - d);
gl.glVertex2f(xx + d, yy + d);
gl.glVertex2f(xx - d, yy + d);
gl.glEnd();
// show search area
gl.glColor3f(0, 1, 0);
final int sd = d + (searchDistance << (numScales - 1));
gl.glBegin(GL.GL_LINE_LOOP);
gl.glVertex2f(xx - sd, yy - sd);
gl.glVertex2f(xx + sd, yy - sd);
gl.glVertex2f(xx + sd, yy + sd);
gl.glVertex2f(xx - sd, yy + sd);
gl.glEnd();
}
}
@Override
public synchronized void resetFilter() {
setSubSampleShift(0); // filter breaks with super's bit shift subsampling
super.resetFilter();
eventCounter = 0;
// lastTs = Integer.MIN_VALUE;
checkArrays();
if (slices == null) {
return; // on reset maybe chip is not set yet
}
// for (byte[][][] b : slices) {
// clearSlice(b);
// currentSliceIdx = 0; // start by filling slice 0
// currentSlice = slices[currentSliceIdx];
// sliceLastTs = Integer.MAX_VALUE;
rewindFlg = true;
if (adaptiveEventSkippingUpdateCounterLPFilter != null) {
adaptiveEventSkippingUpdateCounterLPFilter.reset();
}
clearAreaCounts();
clearNonGreedyRegions();
}
@Override
public void update(Observable o, Object arg) {
if (!isFilterEnabled()) {
return;
}
super.update(o, arg);
if ((o instanceof AEChip) && (chip.getNumPixels() > 0)) {
resetFilter();
}
}
private LowpassFilter speedFilter = new LowpassFilter();
/**
* uses the current event to maybe rotate the slices
*
* @return true if slices were rotated
*/
private boolean maybeRotateSlices() {
int dt = ts - sliceLastTs;
if (dt < 0) { // handle timestamp wrapping
// System.out.println("rotated slices at ");
// System.out.println("rotated slices with dt= "+dt);
rotateSlices();
eventCounter = 0;
sliceDeltaT = dt;
sliceLastTs = ts;
return true;
}
switch (sliceMethod) {
case ConstantDuration:
if ((dt < sliceDurationUs)) {
return false;
}
break;
case ConstantEventNumber:
if (eventCounter < sliceEventCount) {
return false;
}
break;
case AreaEventNumber:
if (!areaCountExceeded && dt < MAX_SLICE_DURATION_US) {
return false;
}
break;
case ConstantIntegratedFlow:
speedFilter.setTauMs(sliceDeltaTimeUs(2) >> 10);
final float meanGlobalSpeed = motionFlowStatistics.getGlobalMotion().meanGlobalSpeed;
if (!Float.isNaN(meanGlobalSpeed)) {
speedFilter.filter(meanGlobalSpeed, ts);
}
final float filteredMeanGlobalSpeed = speedFilter.getValue();
final float totalMovement = filteredMeanGlobalSpeed * dt * 1e-6f;
if (Float.isNaN(meanGlobalSpeed)) { // we need to rotate slices somwhow even if there is no motion computed yet
if (eventCounter < sliceEventCount) {
return false;
}
if ((dt < sliceDurationUs)) {
return false;
}
break;
}
if (totalMovement < searchDistance / 2 && dt < sliceDurationUs) {
return false;
}
break;
}
rotateSlices();
/* Slices have been rotated */
getSupport().firePropertyChange(PatchMatchFlow.EVENT_NEW_SLICES, slices[sliceIndex(1)], slices[sliceIndex(2)]);
return true;
}
/**
* Rotates slices by incrementing the slice pointer with rollover back to
* zero, and sets currentSliceIdx and currentBitmap. Clears the new
* currentBitmap. Thus the slice pointer increments. 0,1,2,0,1,2
*
*/
private void rotateSlices() {
if (e != null) {
sliceEndTimeUs[currentSliceIdx] = e.timestamp;
}
/*Thus if 0 is current index for current filling slice, then sliceIndex returns 1,2 for pointer =1,2.
* Then if NUM_SLICES=3, after rotateSlices(),
currentSliceIdx=NUM_SLICES-1=2, and sliceIndex(0)=2, sliceIndex(1)=0, sliceIndex(2)=1.
*/
sliceSummedSADValues[currentSliceIdx] = 0; // clear out current collecting slice which becomes the oldest slice after rotation
sliceSummedSADCounts[currentSliceIdx] = 0; // clear out current collecting slice which becomes the oldest slice after rotation
currentSliceIdx
if (currentSliceIdx < 0) {
currentSliceIdx = numSlices - 1;
}
currentSlice = slices[currentSliceIdx];
//sliceStartTimeUs[currentSliceIdx] = ts; // current event timestamp; set on first event to slice
clearSlice(currentSlice);
clearAreaCounts();
eventCounter = 0;
sliceDeltaT = ts - sliceLastTs;
sliceLastTs = ts;
if (imuTimesliceLogger != null && imuTimesliceLogger.isEnabled()) {
imuTimesliceLogger.log(String.format("%d %d %.3f", ts, sliceDeltaT, imuFlowEstimator.getPanRateDps()));
}
if (showSlices && !rewindFlg) {
// TODO danger, drawing outside AWT thread
final byte[][][][] thisSlices = slices;
// log.info("making runnable to draw slices in EDT");
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
// will grab this instance. if called from AWT via e.g. slider, then can deadlock if we also invokeAndWait to draw something in ViewLoop
drawSlices(thisSlices);
}
});
}
}
/**
* Returns index to slice given pointer, with zero as current filling slice
* pointer.
*
*
* @param pointer how many slices in the past to index for. I.e.. 0 for
* current slice (one being currently filled), 1 for next oldest, 2 for
* oldest (when using NUM_SLICES=3).
* @return index into bitmaps[]
*/
private int sliceIndex(int pointer) {
return (currentSliceIdx + pointer) % numSlices;
}
/**
* returns slice delta time in us from reference slice
*
* @param pointer how many slices in the past to index for. I.e.. 0 for
* current slice (one being currently filled), 1 for next oldest, 2 for
* oldest (when using NUM_SLICES=3). Only meaningful for pointer>=2,
* currently exactly only pointer==2 since we are using only 3 slices.
*
* Modified to compute the delta time using the average of start and end
* timestamps of each slices, i.e. the slice time "midpoint" where midpoint
* is defined by average of first and last timestamp.
*
*/
protected int sliceDeltaTimeUs(int pointer) {
// System.out.println("dt(" + pointer + ")=" + (sliceStartTimeUs[sliceIndex(1)] - sliceStartTimeUs[sliceIndex(pointer)]));
int idxOlder = sliceIndex(pointer), idxYounger = sliceIndex(1);
int tOlder = (sliceStartTimeUs[idxOlder] + sliceEndTimeUs[idxOlder]) / 2;
int tYounger = (sliceStartTimeUs[idxYounger] + sliceEndTimeUs[idxYounger]) / 2;
int dt = tYounger - tOlder;
return dt;
}
private int nSkipped = 0, nProcessed = 0;
/**
* Accumulates the current event to the current slice
*
* @return true if subsequent processing should done, false if it should be
* skipped for efficiency
*/
synchronized private boolean accumulateEvent(PolarityEvent e) {
if (eventCounter++ == 0) {
sliceStartTimeUs[currentSliceIdx] = e.timestamp; // current event timestamp
}
for (int s = 0; s < numScales; s++) {
final int xx = e.x >> s;
final int yy = e.y >> s;
// if (xx >= currentSlice[s].length || yy > currentSlice[s][xx].length) {
// log.warning("event out of range");
// return false;
int cv = currentSlice[s][xx][yy];
cv += rectifyPolarties ? 1 : (e.polarity == PolarityEvent.Polarity.On ? 1 : -1);
if (cv > sliceMaxValue) {
cv = sliceMaxValue;
} else if (cv < -sliceMaxValue) {
cv = -sliceMaxValue;
}
currentSlice[s][xx][yy] = (byte) cv;
}
if (sliceMethod == SliceMethod.AreaEventNumber) {
if (areaCounts == null) {
clearAreaCounts();
}
int c = ++areaCounts[e.x >> areaEventNumberSubsampling][e.y >> areaEventNumberSubsampling];
if (c >= sliceEventCount) {
areaCountExceeded = true;
// int count=0, sum=0, sum2=0;
// StringBuilder sb=new StringBuilder("Area counts:\n");
// for(int[] i:areaCounts){
// for(int j:i){
// count++;
// sum+=j;
// sum2+=j*j;
// sb.append(String.format("%6d ",j));
// sb.append("\n");
// float m=(float)sum/count;
// float s=(float)Math.sqrt((float)sum2/count-m*m);
// sb.append(String.format("mean=%.1f, std=%.1f",m,s));
// log.info("area count stats "+sb.toString());
}
}
// detect if keypoint here
boolean isCorner = ((e.getAddress() & 1) == 1);
if (calcOFonCornersEnabled && !isCorner) {
return false;
}
if (timeLimiter.isTimedOut()) {
nSkipped++;
return false;
}
if (nonGreedyFlowComputingEnabled) {
// only process the event for flow if most of the other regions have already been processed
int xx = e.x >> areaEventNumberSubsampling, yy = e.y >> areaEventNumberSubsampling;
boolean didArea = nonGreedyRegions[xx][yy];
if (!didArea) {
nonGreedyRegions[xx][yy] = true;
nonGreedyRegionsCount++;
if (nonGreedyRegionsCount >= (int) (nonGreedyFractionToBeServiced * nonGreedyRegionsNumberOfRegions)) {
clearNonGreedyRegions();
}
nProcessed++;
return true; // skip counter is ignored
} else {
nSkipped++;
return false;
}
}
if (skipProcessingEventsCount == 0) {
nProcessed++;
return true;
}
if (skipCounter++ < skipProcessingEventsCount) {
nSkipped++;
return false;
}
nProcessed++;
skipCounter = 0;
return true;
}
// private void clearSlice(int idx) {
// for (int[] a : histograms[idx]) {
// Arrays.fill(a, 0);
private float sumArray[][] = null;
/**
* Computes block matching image difference best match around point x,y
* using blockDimension and searchDistance and scale
*
* @param x coordinate in subsampled space
* @param y
* @param dx_init initial offset
* @param dy_init
* @param prevSlice the slice over which we search for best match
* @param curSlice the slice from which we get the reference block
* @param subSampleBy the scale to compute this SAD on, 0 for full
* resolution, 1 for 2x2 subsampled block bitmap, etc
* @return SADResult that provides the shift and SAD value
*/
// private SADResult minHammingDistance(int x, int y, BitSet prevSlice, BitSet curSlice) {
private SADResult minSADDistance(int x, int y, int dx_init, int dy_init, byte[][][] curSlice, byte[][][] prevSlice, int subSampleBy) {
SADResult result = new SADResult();
float minSum = Float.MAX_VALUE, sum;
float FSDx = 0, FSDy = 0, DSDx = 0, DSDy = 0; // This is for testing the DS search accuracy.
final int searchRange = (2 * searchDistance) + 1; // The maximum search distance in this subSampleBy slice
if ((sumArray == null) || (sumArray.length != searchRange)) {
sumArray = new float[searchRange][searchRange];
} else {
for (float[] row : sumArray) {
Arrays.fill(row, Float.MAX_VALUE);
}
}
if (outputSearchErrorInfo) {
searchMethod = SearchMethod.FullSearch;
} else {
searchMethod = getSearchMethod();
}
final int xsub = (x >> subSampleBy) + dx_init;
final int ysub = (y >> subSampleBy) + dy_init;
final int r = ((blockDimension) / 2) << (numScales - 1 - subSampleBy);
int w = subSizeX >> subSampleBy, h = subSizeY >> subSampleBy;
// Make sure both ref block and past slice block are in bounds on all sides or there'll be arrayIndexOutOfBoundary exception.
// Also we don't want to match ref block only on inner sides or there will be a bias towards motion towards middle
if (xsub - r - searchDistance < 0 || xsub + r + searchDistance >= 1 * w
|| ysub - r - searchDistance < 0 || ysub + r + searchDistance >= 1 * h) {
result.sadValue = Float.MAX_VALUE; // return very large distance for this match so it is not selected
result.scale = subSampleBy;
return result;
}
switch (searchMethod) {
case DiamondSearch:
// SD = small diamond, LD=large diamond SP=search process
/* The center of the LDSP or SDSP could change in the iteration process,
so we need to use a variable to represent it.
In the first interation, it's the Zero Motion Potion (ZMP).
*/
int xCenter = x,
yCenter = y;
/* x offset of center point relative to ZMP, y offset of center point to ZMP.
x offset of center pointin positive number to ZMP, y offset of center point in positive number to ZMP.
*/
int dx,
dy,
xidx,
yidx; // x and y best match offsets in pixels, indices of these in 2d hist
int minPointIdx = 0; // Store the minimum point index.
boolean SDSPFlg = false; // If this flag is set true, then it means LDSP search is finished and SDSP search could start.
/* If one block has been already calculated, the computedFlg will be set so we don't to do
the calculation again.
*/
boolean computedFlg[][] = new boolean[searchRange][searchRange];
for (boolean[] row : computedFlg) {
Arrays.fill(row, false);
}
if (searchDistance == 1) { // LDSP search can only be applied for search distance >= 2.
SDSPFlg = true;
}
int iterationsLeft = searchRange * searchRange;
while (!SDSPFlg) {
/* 1. LDSP search */
for (int pointIdx = 0; pointIdx < LDSP.length; pointIdx++) {
dx = (LDSP[pointIdx][0] + xCenter) - x;
dy = (LDSP[pointIdx][1] + yCenter) - y;
xidx = dx + searchDistance;
yidx = dy + searchDistance;
// Point to be searched is out of search area, skip it.
if ((xidx >= searchRange) || (yidx >= searchRange) || (xidx < 0) || (yidx < 0)) {
continue;
}
/* We just calculate the blocks that haven't been calculated before */
if (computedFlg[xidx][yidx] == false) {
sumArray[xidx][yidx] = sadDistance(x, y, dx_init + dx, dy_init + dy, curSlice, prevSlice, subSampleBy);
computedFlg[xidx][yidx] = true;
if (outputSearchErrorInfo) {
DSAverageNum++;
}
if (outputSearchErrorInfo) {
if (sumArray[xidx][yidx] != sumArray[xidx][yidx]) { // TODO huh? this is never true, compares to itself
log.warning("It seems that there're some bugs in the DS algorithm.");
}
}
}
if (sumArray[xidx][yidx] <= minSum) {
minSum = sumArray[xidx][yidx];
minPointIdx = pointIdx;
}
}
/* 2. Check the minimum value position is in the center or not. */
xCenter = xCenter + LDSP[minPointIdx][0];
yCenter = yCenter + LDSP[minPointIdx][1];
if (minPointIdx == 4) { // It means it's in the center, so we should break the loop and go to SDSP search.
SDSPFlg = true;
}
if (--iterationsLeft < 0) {
log.warning("something is wrong with diamond search; did not find min in SDSP search");
SDSPFlg = true;
}
}
/* 3. SDSP Search */
for (int[] element : SDSP) {
dx = (element[0] + xCenter) - x;
dy = (element[1] + yCenter) - y;
xidx = dx + searchDistance;
yidx = dy + searchDistance;
// Point to be searched is out of search area, skip it.
if ((xidx >= searchRange) || (yidx >= searchRange) || (xidx < 0) || (yidx < 0)) {
continue;
}
/* We just calculate the blocks that haven't been calculated before */
if (computedFlg[xidx][yidx] == false) {
sumArray[xidx][yidx] = sadDistance(x, y, dx_init + dx, dy_init + dy, curSlice, prevSlice, subSampleBy);
computedFlg[xidx][yidx] = true;
if (outputSearchErrorInfo) {
DSAverageNum++;
}
if (outputSearchErrorInfo) {
if (sumArray[xidx][yidx] != sumArray[xidx][yidx]) {
log.warning("It seems that there're some bugs in the DS algorithm.");
}
}
}
if (sumArray[xidx][yidx] <= minSum) {
minSum = sumArray[xidx][yidx];
result.dx = -dx - dx_init; // minus is because result points to the past slice and motion is in the other direction
result.dy = -dy - dy_init;
result.sadValue = minSum;
}
// // debug
// if(result.dx==-searchDistance && result.dy==-searchDistance){
// System.out.println(result);
}
if (outputSearchErrorInfo) {
DSDx = result.dx;
DSDy = result.dy;
}
break;
case FullSearch:
for (dx = -searchDistance; dx <= searchDistance; dx++) {
for (dy = -searchDistance; dy <= searchDistance; dy++) {
sum = sadDistance(x, y, dx_init + dx, dy_init + dy, curSlice, prevSlice, subSampleBy);
sumArray[dx + searchDistance][dy + searchDistance] = sum;
if (sum < minSum) {
minSum = sum;
result.dx = -dx - dx_init; // minus is because result points to the past slice and motion is in the other direction
result.dy = -dy - dy_init;
result.sadValue = minSum;
}
}
}
if((e.getAddress() & 1) == 1)
{
System.out.printf("Scale %d with Refblock is: \n", subSampleBy);
int xscale = (x >> subSampleBy);
int yscale = (y >> subSampleBy);
for (int xx = xscale - r; xx <= (xscale + r); xx++) {
for (int yy = yscale - r; yy <= (yscale + r); yy++) {
System.out.printf("%d\t", curSlice[subSampleBy][xx][yy]);
}
System.out.printf("\n");
}
System.out.printf("\n");
System.out.printf("Tagblock is: \n");
for (int xx = xscale + dx_init - r - searchDistance; xx <= (xscale + dx_init + r + searchDistance); xx++) {
for (int yy = yscale + dy_init - r - searchDistance; yy <= (yscale + dy_init + r + searchDistance); yy++) {
System.out.printf("%d\t", prevSlice[subSampleBy][xx][yy]);
}
System.out.printf("\n");
}
System.out.printf("result is %s: ", result.toString());
System.out.printf("\n");
}
if (outputSearchErrorInfo) {
FSCnt += 1;
FSDx = result.dx;
FSDy = result.dy;
} else {
break;
}
case CrossDiamondSearch:
break;
}
// compute the indices into 2d histogram of all motion vector results.
// It's a bit complicated because of multiple scales.
// Also, we want the indexes to be centered in the histogram array so that searches at full scale appear at the middle
// of the array and not at 0,0 corner.
// Suppose searchDistance=1 and numScales=2. Then the histogram has size 2*2+1=5.
// Therefore the scale 0 results need to have offset added to them to center results in histogram that
// shows results over all scales.
result.scale = subSampleBy;
// convert dx in search steps to dx in pixels including subsampling
// compute index assuming no subsampling or centering
result.xidx = (result.dx + dx_init) + searchDistance;
result.yidx = (result.dy + dy_init) + searchDistance;
// compute final dx and dy including subsampling
result.dx = (result.dx) << subSampleBy;
result.dy = (result.dy) << subSampleBy;
// compute final index including subsampling and centering
// idxCentering is shift needed to be applyed to store this result finally into the hist,
final int idxCentering = (searchDistance << (numScales - 1)) - ((searchDistance) << subSampleBy); // i.e. for subSampleBy=0 and numScales=2, shift=1 so that full scale search is centered in 5x5 hist
result.xidx = (result.xidx << subSampleBy) + idxCentering;
result.yidx = (result.yidx << subSampleBy) + idxCentering;
// if (result.xidx < 0 || result.yidx < 0 || result.xidx > maxIdx || result.yidx > maxIdx) {
// log.warning("something wrong with result=" + result);
// return null;
if (outputSearchErrorInfo) {
if ((DSDx == FSDx) && (DSDy == FSDy)) {
DSCorrectCnt += 1;
} else {
DSAveError[0] += Math.abs(DSDx - FSDx);
DSAveError[1] += Math.abs(DSDy - FSDy);
}
if (0 == (FSCnt % 10000)) {
log.log(Level.INFO, "Correct Diamond Search times are {0}, Full Search times are {1}, accuracy is {2}, averageNumberPercent is {3}, averageError is ({4}, {5})",
new Object[]{DSCorrectCnt, FSCnt, DSCorrectCnt / FSCnt, DSAverageNum / (searchRange * searchRange * FSCnt), DSAveError[0] / FSCnt, DSAveError[1] / (FSCnt - DSCorrectCnt)});
}
}
// if (tmpSadResult.xidx == searchRange-1 && tmpSadResult.yidx == searchRange-1) {
// tmpSadResult.sadValue = 1; // reject results to top right that are likely result of ambiguous search
return result;
}
/**
* computes Hamming distance centered on x,y with patch of patchSize for
* prevSliceIdx relative to curSliceIdx patch.
*
* @param xfull coordinate x in full resolution
* @param yfull coordinate y in full resolution
* @param dx the offset in pixels in the subsampled space of the past slice.
* The motion vector is then *from* this position *to* the current slice.
* @param dy
* @param prevSlice
* @param curSlice
* @param subsampleBy the scale to search over
* @return Distance value, max 1 when all pixels differ, min 0 when all the
* same
*/
private float sadDistance(final int xfull, final int yfull,
final int dx, final int dy,
final byte[][][] curSlice,
final byte[][][] prevSlice,
final int subsampleBy) {
final int x = xfull >> subsampleBy;
final int y = yfull >> subsampleBy;
final int r = ((blockDimension) / 2) << (numScales - 1 - subsampleBy);
// int w = subSizeX >> subsampleBy, h = subSizeY >> subsampleBy;
// int adx = dx > 0 ? dx : -dx; // abs val of dx and dy, to compute limits
// int ady = dy > 0 ? dy : -dy;
// // Make sure both ref block and past slice block are in bounds on all sides or there'll be arrayIndexOutOfBoundary exception.
// // Also we don't want to match ref block only on inner sides or there will be a bias towards motion towards middle
// if (x - r - adx < 0 || x + r + adx >= w
// || y - r - ady < 0 || y + r + ady >= h) {
// return 1; // tobi changed to 1 again // Float.MAX_VALUE; // return very large distance for this match so it is not selected
int validPixNumCurSlice = 0, validPixNumPrevSlice = 0; // The valid pixel number in the current block
int nonZeroMatchCount = 0;
// int saturatedPixNumCurSlice = 0, saturatedPixNumPrevSlice = 0; // The valid pixel number in the current block
int sumDist = 0;
// try {
for (int xx = x - r; xx <= (x + r); xx++) {
for (int yy = y - r; yy <= (y + r); yy++) {
// if (xx < 0 || yy < 0 || xx >= w || yy >= h
// || xx + dx < 0 || yy + dy < 0 || xx + dx >= w || yy + dy >= h) {
//// log.warning("out of bounds slice access; something wrong"); // TODO fix this check above
// continue;
int currSliceVal = curSlice[subsampleBy][xx][yy]; // binary value on (xx, yy) for current slice
int prevSliceVal = prevSlice[subsampleBy][xx + dx][yy + dy]; // binary value on (xx, yy) for previous slice at offset dx,dy in (possibly subsampled) slice
int dist = (currSliceVal - prevSliceVal);
if (dist < 0) {
dist = (-dist);
}
sumDist += dist;
// if (currSlicePol != prevSlicePol) {
// hd += 1;
// if (currSliceVal == sliceMaxValue || currSliceVal == -sliceMaxValue) {
// saturatedPixNumCurSlice++; // pixels that are not saturated
// if (prevSliceVal == sliceMaxValue || prevSliceVal == -sliceMaxValue) {
// saturatedPixNumPrevSlice++;
if (currSliceVal != 0) {
validPixNumCurSlice++; // pixels that are not saturated
}
if (prevSliceVal != 0) {
validPixNumPrevSlice++;
}
if (currSliceVal != 0 && prevSliceVal != 0) {
nonZeroMatchCount++; // pixels that both have events in them
}
}
}
// } catch (ArrayIndexOutOfBoundsException ex) {
// log.warning(ex.toString());
// debug
// if(dx==-1 && dy==-1) return 0; else return Float.MAX_VALUE;
// normalize by dimesion of subsampling, with idea that subsampling increases SAD
//by sqrt(area) because of Gaussian distribution of SAD values
sumDist = sumDist >> (subsampleBy << 1);
final int blockDim = (2 * r) + 1;
final int blockArea = (blockDim) * (blockDim); // TODO check math here for fraction correct with subsampling
// TODD: NEXT WORK IS TO DO THE RESEARCH ON WEIGHTED HAMMING DISTANCE
// Calculate the metric confidence value
final int minValidPixNum = (int) (this.validPixOccupancy * blockArea);
// final int maxSaturatedPixNum = (int) ((1 - this.validPixOccupancy) * blockArea);
final float sadNormalizer = 1f / (blockArea * (rectifyPolarties ? 2 : 1) * sliceMaxValue);
// if current or previous block has insufficient pixels with values or if all the pixels are filled up, then reject match
if ((validPixNumCurSlice < minValidPixNum)
|| (validPixNumPrevSlice < minValidPixNum)
|| (nonZeroMatchCount < minValidPixNum) // || (saturatedPixNumCurSlice >= maxSaturatedPixNum) || (saturatedPixNumPrevSlice >= maxSaturatedPixNum)
) { // If valid pixel number of any slice is 0, then we set the distance to very big value so we can exclude it.
return 1; // tobi changed to 1 to represent max distance // Float.MAX_VALUE;
} else {
/*
retVal consists of the distance and the dispersion. dispersion is used to describe the spatial relationship within one block.
Here we use the difference between validPixNumCurrSli and validPixNumPrevSli to calculate the dispersion.
Inspired by paper "Measuring the spatial dispersion of evolutionist search process: application to Walksat" by Alain Sidaner.
*/
final float finalDistance = sadNormalizer * ((sumDist * weightDistance) + (Math.abs(validPixNumCurSlice - validPixNumPrevSlice) * (1 - weightDistance)));
return finalDistance;
}
}
/**
* Computes hamming weight around point x,y using blockDimension and
* searchDistance
*
* @param x coordinate in subsampled space
* @param y
* @param prevSlice
* @param curSlice
* @return SADResult that provides the shift and SAD value
*/
// private SADResult minJaccardDistance(int x, int y, BitSet prevSlice, BitSet curSlice) {
// private SADResult minJaccardDistance(int x, int y, byte[][] prevSlice, byte[][] curSlice) {
// float minSum = Integer.MAX_VALUE, sum = 0;
// SADResult sadResult = new SADResult(0, 0, 0);
// for (int dx = -searchDistance; dx <= searchDistance; dx++) {
// for (int dy = -searchDistance; dy <= searchDistance; dy++) {
// sum = jaccardDistance(x, y, dx, dy, prevSlice, curSlice);
// if (sum <= minSum) {
// minSum = sum;
// sadResult.dx = dx;
// sadResult.dy = dy;
// sadResult.sadValue = minSum;
// return sadResult;
/**
* computes Hamming distance centered on x,y with patch of patchSize for
* prevSliceIdx relative to curSliceIdx patch.
*
* @param x coordinate in subSampled space
* @param y
* @param patchSize
* @param prevSlice
* @param curSlice
* @return SAD value
*/
// private float jaccardDistance(int x, int y, int dx, int dy, BitSet prevSlice, BitSet curSlice) {
private float jaccardDistance(int x, int y, int dx, int dy, boolean[][] prevSlice, boolean[][] curSlice) {
float M01 = 0, M10 = 0, M11 = 0;
int blockRadius = blockDimension / 2;
// Make sure 0<=xx+dx<subSizeX, 0<=xx<subSizeX and 0<=yy+dy<subSizeY, 0<=yy<subSizeY, or there'll be arrayIndexOutOfBoundary exception.
if ((x < (blockRadius + dx)) || (x >= ((subSizeX - blockRadius) + dx)) || (x < blockRadius) || (x >= (subSizeX - blockRadius))
|| (y < (blockRadius + dy)) || (y >= ((subSizeY - blockRadius) + dy)) || (y < blockRadius) || (y >= (subSizeY - blockRadius))) {
return 1; // changed back to 1 // Float.MAX_VALUE;
}
for (int xx = x - blockRadius; xx <= (x + blockRadius); xx++) {
for (int yy = y - blockRadius; yy <= (y + blockRadius); yy++) {
final boolean c = curSlice[xx][yy], p = prevSlice[xx - dx][yy - dy];
if ((c == true) && (p == true)) {
M11 += 1;
}
if ((c == true) && (p == false)) {
M01 += 1;
}
if ((c == false) && (p == true)) {
M10 += 1;
}
// if ((curSlice.get((xx + 1) + ((yy) * subSizeX)) == true) && (prevSlice.get(((xx + 1) - dx) + ((yy - dy) * subSizeX)) == true)) {
// M11 += 1;
// if ((curSlice.get((xx + 1) + ((yy) * subSizeX)) == true) && (prevSlice.get(((xx + 1) - dx) + ((yy - dy) * subSizeX)) == false)) {
// M01 += 1;
// if ((curSlice.get((xx + 1) + ((yy) * subSizeX)) == false) && (prevSlice.get(((xx + 1) - dx) + ((yy - dy) * subSizeX)) == true)) {
// M10 += 1;
}
}
float retVal;
if (0 == (M01 + M10 + M11)) {
retVal = 0;
} else {
retVal = M11 / (M01 + M10 + M11);
}
retVal = 1 - retVal;
return retVal;
}
// private SADResult minVicPurDistance(int blockX, int blockY) {
// ArrayList<Integer[]> seq1 = new ArrayList(1);
// SADResult sadResult = new SADResult(0, 0, 0);
// int size = spikeTrains[blockX][blockY].size();
// int lastTs = spikeTrains[blockX][blockY].get(size - forwardEventNum)[0];
// for (int i = size - forwardEventNum; i < size; i++) {
// seq1.appendCopy(spikeTrains[blockX][blockY].get(i));
//// if(seq1.get(2)[0] - seq1.get(0)[0] > thresholdTime) {
//// return sadResult;
// double minium = Integer.MAX_VALUE;
// for (int i = -1; i < 2; i++) {
// for (int j = -1; j < 2; j++) {
// // Remove the seq1 itself
// if ((0 == i) && (0 == j)) {
// continue;
// ArrayList<Integer[]> seq2 = new ArrayList(1);
// if ((blockX >= 2) && (blockY >= 2)) {
// ArrayList<Integer[]> tmpSpikes = spikeTrains[blockX + i][blockY + j];
// if (tmpSpikes != null) {
// for (int index = 0; index < tmpSpikes.size(); index++) {
// if (tmpSpikes.get(index)[0] >= lastTs) {
// seq2.appendCopy(tmpSpikes.get(index));
// double dis = vicPurDistance(seq1, seq2);
// if (dis < minium) {
// minium = dis;
// sadResult.dx = -i;
// sadResult.dy = -j;
// lastFireIndex[blockX][blockY] = spikeTrains[blockX][blockY].size() - 1;
// if ((sadResult.dx != 1) || (sadResult.dy != 0)) {
// // sadResult = new SADResult(0, 0, 0);
// return sadResult;
// private double vicPurDistance(ArrayList<Integer[]> seq1, ArrayList<Integer[]> seq2) {
// int sum1Plus = 0, sum1Minus = 0, sum2Plus = 0, sum2Minus = 0;
// Iterator itr1 = seq1.iterator();
// Iterator itr2 = seq2.iterator();
// int length1 = seq1.size();
// int length2 = seq2.size();
// double[][] distanceMatrix = new double[length1 + 1][length2 + 1];
// for (int h = 0; h <= length1; h++) {
// for (int k = 0; k <= length2; k++) {
// if (h == 0) {
// distanceMatrix[h][k] = k;
// continue;
// if (k == 0) {
// distanceMatrix[h][k] = h;
// continue;
// double tmpMin = Math.min(distanceMatrix[h][k - 1] + 1, distanceMatrix[h - 1][k] + 1);
// double event1 = seq1.get(h - 1)[0] - seq1.get(0)[0];
// double event2 = seq2.get(k - 1)[0] - seq2.get(0)[0];
// distanceMatrix[h][k] = Math.min(tmpMin, distanceMatrix[h - 1][k - 1] + (cost * Math.abs(event1 - event2)));
// while (itr1.hasNext()) {
// Integer[] ii = (Integer[]) itr1.next();
// if (ii[1] == 1) {
// sum1Plus += 1;
// } else {
// sum1Minus += 1;
// while (itr2.hasNext()) {
// Integer[] ii = (Integer[]) itr2.next();
// if (ii[1] == 1) {
// sum2Plus += 1;
// } else {
// sum2Minus += 1;
// // return Math.abs(sum1Plus - sum2Plus) + Math.abs(sum1Minus - sum2Minus);
// return distanceMatrix[length1][length2];
// /**
// * Computes min SAD shift around point x,y using blockDimension and
// * searchDistance
// *
// * @param x coordinate in subsampled space
// * @param y
// * @param prevSlice
// * @param curSlice
// * @return SADResult that provides the shift and SAD value
// */
// private SADResult minSad(int x, int y, BitSet prevSlice, BitSet curSlice) {
// // for now just do exhaustive search over all shifts up to +/-searchDistance
// SADResult sadResult = new SADResult(0, 0, 0);
// float minSad = 1;
// for (int dx = -searchDistance; dx <= searchDistance; dx++) {
// for (int dy = -searchDistance; dy <= searchDistance; dy++) {
// float sad = sad(x, y, dx, dy, prevSlice, curSlice);
// if (sad <= minSad) {
// minSad = sad;
// sadResult.dx = dx;
// sadResult.dy = dy;
// sadResult.sadValue = minSad;
// return sadResult;
// /**
// * computes SAD centered on x,y with shift of dx,dy for prevSliceIdx
// * relative to curSliceIdx patch.
// *
// * @param x coordinate x in subSampled space
// * @param y coordinate y in subSampled space
// * @param dx block shift of x
// * @param dy block shift of y
// * @param prevSliceIdx
// * @param curSliceIdx
// * @return SAD value
// */
// private float sad(int x, int y, int dx, int dy, BitSet prevSlice, BitSet curSlice) {
// int blockRadius = blockDimension / 2;
// // Make sure 0<=xx+dx<subSizeX, 0<=xx<subSizeX and 0<=yy+dy<subSizeY, 0<=yy<subSizeY, or there'll be arrayIndexOutOfBoundary exception.
// if ((x < (blockRadius + dx)) || (x >= ((subSizeX - blockRadius) + dx)) || (x < blockRadius) || (x >= (subSizeX - blockRadius))
// || (y < (blockRadius + dy)) || (y >= ((subSizeY - blockRadius) + dy)) || (y < blockRadius) || (y >= (subSizeY - blockRadius))) {
// return Float.MAX_VALUE;
// float sad = 0, retVal = 0;
// float validPixNumCurrSli = 0, validPixNumPrevSli = 0; // The valid pixel number in the current block
// for (int xx = x - blockRadius; xx <= (x + blockRadius); xx++) {
// for (int yy = y - blockRadius; yy <= (y + blockRadius); yy++) {
// boolean currSlicePol = curSlice.get((xx + 1) + ((yy) * subSizeX)); // binary value on (xx, yy) for current slice
// boolean prevSlicePol = prevSlice.get(((xx + 1) - dx) + ((yy - dy) * subSizeX)); // binary value on (xx, yy) for previous slice
// int imuWarningDialog = (currSlicePol ? 1 : 0) - (prevSlicePol ? 1 : 0);
// if (currSlicePol == true) {
// validPixNumCurrSli += 1;
// if (prevSlicePol == true) {
// validPixNumPrevSli += 1;
// if (imuWarningDialog <= 0) {
// imuWarningDialog = -imuWarningDialog;
// sad += imuWarningDialog;
// // Calculate the metric confidence value
// float validPixNum = this.validPixOccupancy * (((2 * blockRadius) + 1) * ((2 * blockRadius) + 1));
// if ((validPixNumCurrSli <= validPixNum) || (validPixNumPrevSli <= validPixNum)) { // If valid pixel number of any slice is 0, then we set the distance to very big value so we can exclude it.
// retVal = 1;
// } else {
// /*
// retVal is consisted of the distance and the dispersion, dispersion is used to describe the spatial relationship within one block.
// Here we use the difference between validPixNumCurrSli and validPixNumPrevSli to calculate the dispersion.
// Inspired by paper "Measuring the spatial dispersion of evolutionist search process: application to Walksat" by Alain Sidaner.
// */
// retVal = ((sad * weightDistance) + (Math.abs(validPixNumCurrSli - validPixNumPrevSli) * (1 - weightDistance))) / (((2 * blockRadius) + 1) * ((2 * blockRadius) + 1));
// return retVal;
private class SADResult {
int dx, dy; // best match offset in pixels to reference block from past slice block, i.e. motion vector points in this direction
float vx, vy; // optical flow in pixels/second corresponding to this match
float sadValue; // sum of absolute differences for this best match normalized by number of pixels in reference area
int xidx, yidx; // x and y indices into 2d matrix of result. 0,0 corresponds to motion SW. dx, dy may be negative, like (-1, -1) represents SW.
// However, for histgram index, it's not possible to use negative number. That's the reason for intrducing xidx and yidx.
// boolean minSearchedFlg = false; // The flag indicates that this minimum have been already searched before.
int scale;
/**
* Allocates new results initialized to zero
*/
public SADResult() {
this(0, 0, 0, 0);
}
public SADResult(int dx, int dy, float sadValue, int scale) {
this.dx = dx;
this.dy = dy;
this.sadValue = sadValue;
}
public void set(SADResult s) {
this.dx = s.dx;
this.dy = s.dy;
this.sadValue = s.sadValue;
this.xidx = s.xidx;
this.yidx = s.yidx;
this.scale = s.scale;
}
@Override
public String toString() {
return String.format("(dx,dy=%5d,%5d), (vx,vy=%.1f,%.1f pps), SAD=%f, scale=%d", dx, dy, vx, vy, sadValue, scale);
}
}
private class Statistics {
double[] data;
int size;
public Statistics(double[] data) {
this.data = data;
size = data.length;
}
double getMean() {
double sum = 0.0;
for (double a : data) {
sum += a;
}
return sum / size;
}
double getVariance() {
double mean = getMean();
double temp = 0;
for (double a : data) {
temp += (a - mean) * (a - mean);
}
return temp / size;
}
double getStdDev() {
return Math.sqrt(getVariance());
}
public double median() {
Arrays.sort(data);
if ((data.length % 2) == 0) {
return (data[(data.length / 2) - 1] + data[data.length / 2]) / 2.0;
}
return data[data.length / 2];
}
public double getMin() {
Arrays.sort(data);
return data[0];
}
public double getMax() {
Arrays.sort(data);
return data[data.length - 1];
}
}
/**
* @return the blockDimension
*/
public int getBlockDimension() {
return blockDimension;
}
/**
* @param blockDimension the blockDimension to set
*/
synchronized public void setBlockDimension(int blockDimension) {
int old = this.blockDimension;
// enforce odd value
if ((blockDimension & 1) == 0) { // even
if (blockDimension > old) {
blockDimension++;
} else {
blockDimension
}
}
// clip final value
if (blockDimension < 1) {
blockDimension = 1;
} else if (blockDimension > 63) {
blockDimension = 63;
}
this.blockDimension = blockDimension;
getSupport().firePropertyChange("blockDimension", old, blockDimension);
putInt("blockDimension", blockDimension);
showBlockSizeAndSearchAreaTemporarily();
}
/**
* @return the sliceMethod
*/
public SliceMethod getSliceMethod() {
return sliceMethod;
}
/**
* @param sliceMethod the sliceMethod to set
*/
synchronized public void setSliceMethod(SliceMethod sliceMethod) {
SliceMethod old = this.sliceMethod;
this.sliceMethod = sliceMethod;
putString("sliceMethod", sliceMethod.toString());
if (sliceMethod == SliceMethod.AreaEventNumber || sliceMethod == SliceMethod.ConstantIntegratedFlow) {
showAreasForAreaCountsTemporarily();
}
// if(sliceMethod==SliceMethod.ConstantIntegratedFlow){
// setDisplayGlobalMotion(true);
getSupport().firePropertyChange("sliceMethod", old, this.sliceMethod);
}
public PatchCompareMethod getPatchCompareMethod() {
return patchCompareMethod;
}
synchronized public void setPatchCompareMethod(PatchCompareMethod patchCompareMethod) {
this.patchCompareMethod = patchCompareMethod;
putString("patchCompareMethod", patchCompareMethod.toString());
}
/**
*
* @return the search method
*/
public SearchMethod getSearchMethod() {
return searchMethod;
}
/**
*
* @param searchMethod the method to be used for searching
*/
synchronized public void setSearchMethod(SearchMethod searchMethod) {
SearchMethod old = this.searchMethod;
this.searchMethod = searchMethod;
putString("searchMethod", searchMethod.toString());
getSupport().firePropertyChange("searchMethod", old, this.searchMethod);
}
private void computeAveragePossibleMatchDistance() {
int n = 0;
double s = 0;
for (int xx = -searchDistance; xx <= searchDistance; xx++) {
for (int yy = -searchDistance; yy <= searchDistance; yy++) {
n++;
s += Math.sqrt((xx * xx) + (yy * yy));
}
}
double d = s / n; // avg for one scale
double s2 = 0;
for (int i = 0; i < numScales; i++) {
s2 += d * (1 << i);
}
double d2 = s2 / numScales;
log.info(String.format("searchDistance=%d numScales=%d: avgPossibleMatchDistance=%.1f", searchDistance, numScales, avgPossibleMatchDistance));
avgPossibleMatchDistance = (float) d2;
}
@Override
synchronized public void setSearchDistance(int searchDistance) {
int old = this.searchDistance;
if (searchDistance > 12) {
searchDistance = 12;
} else if (searchDistance < 1) {
searchDistance = 1; // limit size
}
this.searchDistance = searchDistance;
putInt("searchDistance", searchDistance);
getSupport().firePropertyChange("searchDistance", old, searchDistance);
resetFilter();
showBlockSizeAndSearchAreaTemporarily();
computeAveragePossibleMatchDistance();
}
/**
* @return the sliceDurationUs
*/
public int getSliceDurationUs() {
return sliceDurationUs;
}
/**
* @param sliceDurationUs the sliceDurationUs to set
*/
public void setSliceDurationUs(int sliceDurationUs) {
int old = this.sliceDurationUs;
if (sliceDurationUs < MIN_SLICE_DURATION_US) {
sliceDurationUs = MIN_SLICE_DURATION_US;
} else if (sliceDurationUs > MAX_SLICE_DURATION_US) {
sliceDurationUs = MAX_SLICE_DURATION_US; // limit it to one second
}
this.sliceDurationUs = sliceDurationUs;
/* If the slice duration is changed, reset FSCnt and DScorrect so we can get more accurate evaluation result */
FSCnt = 0;
DSCorrectCnt = 0;
putInt("sliceDurationUs", sliceDurationUs);
getSupport().firePropertyChange("sliceDurationUs", old, this.sliceDurationUs);
}
/**
* @return the sliceEventCount
*/
public int getSliceEventCount() {
return sliceEventCount;
}
/**
* @param sliceEventCount the sliceEventCount to set
*/
public void setSliceEventCount(int sliceEventCount) {
final int div = sliceMethod == SliceMethod.AreaEventNumber ? numAreas : 1;
final int old = this.sliceEventCount;
if (sliceEventCount < MIN_SLICE_EVENT_COUNT_FULL_FRAME / div) {
sliceEventCount = MIN_SLICE_EVENT_COUNT_FULL_FRAME / div;
} else if (sliceEventCount > MAX_SLICE_EVENT_COUNT_FULL_FRAME / div) {
sliceEventCount = MAX_SLICE_EVENT_COUNT_FULL_FRAME / div;
}
this.sliceEventCount = sliceEventCount;
putInt("sliceEventCount", sliceEventCount);
getSupport().firePropertyChange("sliceEventCount", old, this.sliceEventCount);
}
public float getMaxAllowedSadDistance() {
return maxAllowedSadDistance;
}
public void setMaxAllowedSadDistance(float maxAllowedSadDistance) {
float old = this.maxAllowedSadDistance;
if (maxAllowedSadDistance < 0) {
maxAllowedSadDistance = 0;
} else if (maxAllowedSadDistance > 1) {
maxAllowedSadDistance = 1;
}
this.maxAllowedSadDistance = maxAllowedSadDistance;
putFloat("maxAllowedSadDistance", maxAllowedSadDistance);
getSupport().firePropertyChange("maxAllowedSadDistance", old, this.maxAllowedSadDistance);
}
public float getValidPixOccupancy() {
return validPixOccupancy;
}
public void setValidPixOccupancy(float validPixOccupancy) {
float old = this.validPixOccupancy;
if (validPixOccupancy < 0) {
validPixOccupancy = 0;
} else if (validPixOccupancy > 1) {
validPixOccupancy = 1;
}
this.validPixOccupancy = validPixOccupancy;
putFloat("validPixOccupancy", validPixOccupancy);
getSupport().firePropertyChange("validPixOccupancy", old, this.validPixOccupancy);
}
public float getWeightDistance() {
return weightDistance;
}
public void setWeightDistance(float weightDistance) {
if (weightDistance < 0) {
weightDistance = 0;
} else if (weightDistance > 1) {
weightDistance = 1;
}
this.weightDistance = weightDistance;
putFloat("weightDistance", weightDistance);
}
// private int totalFlowEvents=0, filteredOutFlowEvents=0;
// private boolean filterOutInconsistentEvent(SADResult result) {
// if (!isOutlierMotionFilteringEnabled()) {
// return false;
// totalFlowEvents++;
// if (lastGoodSadResult == null) {
// return false;
// if (result.dx * lastGoodSadResult.dx + result.dy * lastGoodSadResult.dy >= 0) {
// return false;
// filteredOutFlowEvents++;
// return true;
synchronized private void checkArrays() {
if (subSizeX == 0 || subSizeY == 0) {
return; // don't do on init when chip is not known yet
}
// numSlices = getInt("numSlices", 3); // since resetFilter is called in super before numSlices is even initialized
if (slices == null || slices.length != numSlices
|| slices[0] == null || slices[0].length != numScales) {
if (numScales > 0 && numSlices > 0) { // deal with filter reconstruction where these fields are not set
slices = new byte[numSlices][numScales][][];
for (int n = 0; n < numSlices; n++) {
for (int s = 0; s < numScales; s++) {
int nx = (subSizeX >> s) + 1 + blockDimension, ny = (subSizeY >> s) + 1 + blockDimension;
if (slices[n][s] == null || slices[n][s].length != nx
|| slices[n][s][0] == null || slices[n][s][0].length != ny) {
slices[n][s] = new byte[nx][ny];
}
}
}
currentSliceIdx = 0; // start by filling slice 0
currentSlice = slices[currentSliceIdx];
sliceLastTs = Integer.MAX_VALUE;
sliceStartTimeUs = new int[numSlices];
sliceEndTimeUs = new int[numSlices];
sliceSummedSADValues = new float[numSlices];
sliceSummedSADCounts = new int[numSlices];
}
// log.info("allocated slice memory");
}
// if (lastTimesMap != null) {
// lastTimesMap = null; // save memory
int rhDim = (2 * (searchDistance << (numScales - 1))) + 1; // e.g. search distance 1, dim=3, 3x3 possibilties (including zero motion)
if ((resultHistogram == null) || (resultHistogram.length != rhDim)) {
resultHistogram = new int[rhDim][rhDim];
resultHistogramCount = 0;
}
checkNonGreedyRegionsAllocated();
}
/**
*
* @param distResult
* @return the confidence of the result. True means it's not good and should
* be rejected, false means we should accept it.
*/
private synchronized boolean isNotSufficientlyAccurate(SADResult distResult) {
boolean retVal = super.accuracyTests(); // check accuracy in super, if reject returns true
// additional test, normalized blaock distance must be small enough
// distance has max value 1
if (distResult.sadValue >= maxAllowedSadDistance) {
retVal = true;
}
return retVal;
}
/**
* @return the skipProcessingEventsCount
*/
public int getSkipProcessingEventsCount() {
return skipProcessingEventsCount;
}
/**
* @param skipProcessingEventsCount the skipProcessingEventsCount to set
*/
public void setSkipProcessingEventsCount(int skipProcessingEventsCount) {
int old = this.skipProcessingEventsCount;
if (skipProcessingEventsCount < 0) {
skipProcessingEventsCount = 0;
}
if (skipProcessingEventsCount > MAX_SKIP_COUNT) {
skipProcessingEventsCount = MAX_SKIP_COUNT;
}
this.skipProcessingEventsCount = skipProcessingEventsCount;
getSupport().firePropertyChange("skipProcessingEventsCount", old, this.skipProcessingEventsCount);
putInt("skipProcessingEventsCount", skipProcessingEventsCount);
}
/**
* @return the displayResultHistogram
*/
public boolean isDisplayResultHistogram() {
return displayResultHistogram;
}
/**
* @param displayResultHistogram the displayResultHistogram to set
*/
public void setDisplayResultHistogram(boolean displayResultHistogram) {
this.displayResultHistogram = displayResultHistogram;
putBoolean("displayResultHistogram", displayResultHistogram);
}
/**
* @return the adaptiveEventSkipping
*/
public boolean isAdaptiveEventSkipping() {
return adaptiveEventSkipping;
}
/**
* @param adaptiveEventSkipping the adaptiveEventSkipping to set
*/
synchronized public void setAdaptiveEventSkipping(boolean adaptiveEventSkipping) {
boolean old = this.adaptiveEventSkipping;
this.adaptiveEventSkipping = adaptiveEventSkipping;
putBoolean("adaptiveEventSkipping", adaptiveEventSkipping);
if (adaptiveEventSkipping && adaptiveEventSkippingUpdateCounterLPFilter != null) {
adaptiveEventSkippingUpdateCounterLPFilter.reset();
}
getSupport().firePropertyChange("adaptiveEventSkipping", old, this.adaptiveEventSkipping);
}
public boolean isOutputSearchErrorInfo() {
return outputSearchErrorInfo;
}
public boolean isShowBlockMatches() {
return showBlockMatches;
}
/**
* @param showBlockMatches
* @param showBlockMatches the option of displaying bitmap
*/
synchronized public void setShowBlockMatches(boolean showBlockMatches) {
boolean old = this.showBlockMatches;
this.showBlockMatches = showBlockMatches;
putBoolean("showBlockMatches", showBlockMatches);
getSupport().firePropertyChange("showBlockMatches", old, this.showBlockMatches);
}
public boolean isShowSlices() {
return showSlices;
}
/**
* @param showSlices
* @param showSlices the option of displaying bitmap
*/
synchronized public void setShowSlices(boolean showSlices) {
boolean old = this.showSlices;
this.showSlices = showSlices;
getSupport().firePropertyChange("showSlices", old, this.showBlockMatches);
}
synchronized public void setOutputSearchErrorInfo(boolean outputSearchErrorInfo) {
this.outputSearchErrorInfo = outputSearchErrorInfo;
if (!outputSearchErrorInfo) {
searchMethod = SearchMethod.valueOf(getString("searchMethod", SearchMethod.FullSearch.toString())); // make sure method is reset
}
}
private LowpassFilter adaptiveEventSkippingUpdateCounterLPFilter = null;
private int adaptiveEventSkippingUpdateCounter = 0;
private void adaptEventSkipping() {
if (!adaptiveEventSkipping) {
return;
}
if (chip.getAeViewer() == null) {
return;
}
int old = skipProcessingEventsCount;
if (chip.getAeViewer().isPaused() || chip.getAeViewer().isSingleStep()) {
skipProcessingEventsCount = 0;
getSupport().firePropertyChange("skipProcessingEventsCount", old, this.skipProcessingEventsCount);
}
if (adaptiveEventSkippingUpdateCounterLPFilter == null) {
adaptiveEventSkippingUpdateCounterLPFilter = new LowpassFilter(chip.getAeViewer().getFrameRater().FPS_LOWPASS_FILTER_TIMECONSTANT_MS);
}
final float averageFPS = chip.getAeViewer().getFrameRater().getAverageFPS();
final int frameRate = chip.getAeViewer().getDesiredFrameRate();
boolean skipMore = averageFPS < (int) (0.75f * frameRate);
boolean skipLess = averageFPS > (int) (0.25f * frameRate);
float newSkipCount = skipProcessingEventsCount;
if (skipMore) {
newSkipCount = adaptiveEventSkippingUpdateCounterLPFilter.filter(1 + (skipChangeFactor * skipProcessingEventsCount), 1000 * (int) System.currentTimeMillis());
} else if (skipLess) {
newSkipCount = adaptiveEventSkippingUpdateCounterLPFilter.filter((skipProcessingEventsCount / skipChangeFactor) - 1, 1000 * (int) System.currentTimeMillis());
}
skipProcessingEventsCount = Math.round(newSkipCount);
if (skipProcessingEventsCount > MAX_SKIP_COUNT) {
skipProcessingEventsCount = MAX_SKIP_COUNT;
} else if (skipProcessingEventsCount < 0) {
skipProcessingEventsCount = 0;
}
getSupport().firePropertyChange("skipProcessingEventsCount", old, this.skipProcessingEventsCount);
}
/**
* @return the adaptiveSliceDuration
*/
public boolean isAdaptiveSliceDuration() {
return adaptiveSliceDuration;
}
/**
* @param adaptiveSliceDuration the adaptiveSliceDuration to set
*/
synchronized public void setAdaptiveSliceDuration(boolean adaptiveSliceDuration) {
boolean old = this.adaptiveSliceDuration;
this.adaptiveSliceDuration = adaptiveSliceDuration;
putBoolean("adaptiveSliceDuration", adaptiveSliceDuration);
if (adaptiveSliceDurationLogging) {
if (adaptiveSliceDurationLogger == null) {
adaptiveSliceDurationLogger = new TobiLogger("PatchMatchFlow-SliceDurationControl", "slice duration or event count control logging");
adaptiveSliceDurationLogger.setHeaderLine("systemTimeMs\tpacketNumber\tavgMatchDistance\tmatchRadiusError\tglobalTranslationSpeedPPS\tsliceDurationUs\tsliceEventCount");
}
adaptiveSliceDurationLogger.setEnabled(adaptiveSliceDuration);
}
getSupport().firePropertyChange("adaptiveSliceDuration", old, this.adaptiveSliceDuration);
}
/**
* @return the processingTimeLimitMs
*/
public int getProcessingTimeLimitMs() {
return processingTimeLimitMs;
}
/**
* @param processingTimeLimitMs the processingTimeLimitMs to set
*/
public void setProcessingTimeLimitMs(int processingTimeLimitMs) {
this.processingTimeLimitMs = processingTimeLimitMs;
putInt("processingTimeLimitMs", processingTimeLimitMs);
}
/**
* clears all scales for a particular time slice
*
* @param slice [scale][x][y]
*/
private void clearSlice(byte[][][] slice) {
for (byte[][] scale : slice) { // for each scale
for (byte[] row : scale) { // for each col
Arrays.fill(row, (byte) 0); // fill col
}
}
}
private int dim = blockDimension + (2 * searchDistance);
/**
* Draws the block matching bitmap
*
* @param x
* @param y
* @param dx
* @param dy
* @param refBlock
* @param searchBlock
* @param subSampleBy
*/
synchronized private void drawMatching(SADResult result, PolarityEvent ein, byte[][][][] slices, float[] sadVals, int[] dxInitVals, int[] dyInitVals) {
// synchronized private void drawMatching(int x, int y, int dx, int dy, byte[][] refBlock, byte[][] searchBlock, int subSampleBy) {
for(int dispIdx = 0; dispIdx < numScales; dispIdx++)
{
int x = ein.x >> dispIdx, y = ein.y >> dispIdx;
int dx = (int) result.dx >> dispIdx, dy = (int) result.dy >> dispIdx;
byte[][] refBlock = slices[sliceIndex(0)][dispIdx], searchBlock = slices[sliceIndex(1)][dispIdx];
int subSampleBy = dispIdx;
Legend sadLegend = null;
final int refRadius = (blockDimension / 2) << (numScales - 1 - dispIdx);
int dimNew = refRadius * 2 + 1 + (2 * (searchDistance));
if (blockMatchingFrame[dispIdx] == null) {
String windowName = "Ref Block " + dispIdx;
blockMatchingFrame[dispIdx] = new JFrame(windowName);
blockMatchingFrame[dispIdx].setLayout(new BoxLayout(blockMatchingFrame[dispIdx].getContentPane(), BoxLayout.Y_AXIS));
blockMatchingFrame[dispIdx].setPreferredSize(new Dimension(600, 600));
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
blockMatchingImageDisplay[dispIdx] = ImageDisplay.createOpenGLCanvas();
blockMatchingImageDisplay[dispIdx].setBorderSpacePixels(10);
blockMatchingImageDisplay[dispIdx].setImageSize(dimNew, dimNew);
blockMatchingImageDisplay[dispIdx].setSize(200, 200);
blockMatchingImageDisplay[dispIdx].setGrayValue(0);
blockMatchingDisplayLegend[dispIdx] = blockMatchingImageDisplay[dispIdx].addLegend(LEGEND_G_SEARCH_AREA_R_REF_BLOCK_AREA_B_BEST_MATCH, 0, dim);
panel.add(blockMatchingImageDisplay[dispIdx]);
blockMatchingFrame[dispIdx].getContentPane().add(panel);
blockMatchingFrame[dispIdx].pack();
blockMatchingFrame[dispIdx].addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
setShowBlockMatches(false);
}
});
}
if (!blockMatchingFrame[dispIdx].isVisible()) {
blockMatchingFrame[dispIdx].setVisible(true);
}
if (blockMatchingFrameTarget[dispIdx] == null) {
String windowName = "Target Block " + dispIdx;
blockMatchingFrameTarget[dispIdx] = new JFrame(windowName);
blockMatchingFrameTarget[dispIdx].setLayout(new BoxLayout(blockMatchingFrameTarget[dispIdx].getContentPane(), BoxLayout.Y_AXIS));
blockMatchingFrameTarget[dispIdx].setPreferredSize(new Dimension(600, 600));
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
blockMatchingImageDisplayTarget[dispIdx] = ImageDisplay.createOpenGLCanvas();
blockMatchingImageDisplayTarget[dispIdx].setBorderSpacePixels(10);
blockMatchingImageDisplayTarget[dispIdx].setImageSize(dimNew, dimNew);
blockMatchingImageDisplayTarget[dispIdx].setSize(200, 200);
blockMatchingImageDisplayTarget[dispIdx].setGrayValue(0);
blockMatchingDisplayLegendTarget[dispIdx] = blockMatchingImageDisplayTarget[dispIdx].addLegend(LEGEND_G_SEARCH_AREA_R_REF_BLOCK_AREA_B_BEST_MATCH, 0, dim);
panel.add(blockMatchingImageDisplayTarget[dispIdx]);
blockMatchingFrameTarget[dispIdx].getContentPane().add(panel);
blockMatchingFrameTarget[dispIdx].pack();
blockMatchingFrameTarget[dispIdx].addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
setShowBlockMatches(false);
}
});
}
if (!blockMatchingFrameTarget[dispIdx].isVisible()) {
blockMatchingFrameTarget[dispIdx].setVisible(true);
}
final int radius = (refRadius) + searchDistance;
float scale = 1f / getSliceMaxValue();
try {
// if ((x >= radius) && ((x + radius) < subSizeX)
// && (y >= radius) && ((y + radius) < subSizeY))
{
if (dimNew != blockMatchingImageDisplay[dispIdx].getWidth()) {
dim = dimNew;
blockMatchingImageDisplay[dispIdx].setImageSize(dimNew, dimNew);
blockMatchingImageDisplay[dispIdx].clearLegends();
blockMatchingDisplayLegend[dispIdx] = blockMatchingImageDisplay[dispIdx].addLegend(LEGEND_G_SEARCH_AREA_R_REF_BLOCK_AREA_B_BEST_MATCH, 0, dim);
}
if (dimNew != blockMatchingImageDisplayTarget[dispIdx].getWidth()) {
dim = dimNew;
blockMatchingImageDisplayTarget[dispIdx].setImageSize(dimNew, dimNew);
blockMatchingImageDisplayTarget[dispIdx].clearLegends();
blockMatchingDisplayLegendTarget[dispIdx] = blockMatchingImageDisplayTarget[dispIdx].addLegend(LEGEND_G_SEARCH_AREA_R_REF_BLOCK_AREA_B_BEST_MATCH, 0, dim);
}
// TextRenderer textRenderer = new TextRenderer(new Font("SansSerif", Font.PLAIN, 12));
if (blockMatchingDisplayLegend[dispIdx] != null) {
blockMatchingDisplayLegend[dispIdx].s
= "R: ref block area"
+ "\nScale: "
+ subSampleBy
+ "\nSAD: "
+ engFmt.format(sadVals[dispIdx])
+ "\nTimestamp: " + ein.timestamp;
}
if (blockMatchingDisplayLegendTarget[dispIdx] != null) {
blockMatchingDisplayLegendTarget[dispIdx].s
= "G: search area"
+ "\nx: " + ein.x
+ "\ny: " + ein.y
+ "\ndx_init: " + dxInitVals[dispIdx]
+ "\ndy_init: " + dyInitVals[dispIdx];
}
/* Reset the image first */
blockMatchingImageDisplay[dispIdx].clearImage();
blockMatchingImageDisplayTarget[dispIdx].clearImage();
/* Rendering the reference patch in t-imuWarningDialog slice, it's on the center with color red */
for (int i = searchDistance; i < (refRadius *2 + 1 + searchDistance); i++) {
for (int j = searchDistance; j < (refRadius * 2 + 1 + searchDistance); j++) {
float[] f = blockMatchingImageDisplay[dispIdx].getPixmapRGB(i, j);
f[0] = scale * Math.abs(refBlock[((x - (refRadius)) + i) - searchDistance][((y - (refRadius)) + j) - searchDistance]);
blockMatchingImageDisplay[dispIdx].setPixmapRGB(i, j, f);
}
}
/* Rendering the area within search distance in t-2d slice, it's full of the whole search area with color green */
for (int i = 0; i < ((2 * radius) + 1); i++) {
for (int j = 0; j < ((2 * radius) + 1); j++) {
float[] f = blockMatchingImageDisplayTarget[dispIdx].getPixmapRGB(i, j);
f[1] = scale * Math.abs(searchBlock[(x - dxInitVals[dispIdx] - radius) + i][(y - dyInitVals[dispIdx] - radius) + j]);
blockMatchingImageDisplayTarget[dispIdx].setPixmapRGB(i, j, f);
}
}
/* Rendering the best matching patch in t-2d slice, it's on the shifted position related to the center location with color blue */
// for (int i = searchDistance + dx; i < (blockDimension + searchDistance + dx); i++) {
// for (int j = searchDistance + dy; j < (blockDimension + searchDistance + dy); j++) {
// float[] f = blockMatchingImageDisplayTarget[dispIdx].getPixmapRGB(i, j);
// f[2] = scale * Math.abs(searchBlock[((x - (blockDimension / 2)) + i) - searchDistance][((y - (blockDimension / 2)) + j) - searchDistance]);
// blockMatchingImageDisplayTarget[dispIdx].setPixmapRGB(i, j, f);
}
} catch (ArrayIndexOutOfBoundsException e) {
}
blockMatchingImageDisplay[dispIdx].repaint();
blockMatchingImageDisplayTarget[dispIdx].repaint();
}
}
synchronized private void drawTimeStampBlock(PolarityEvent ein)
{
int dim = 11;
int eX = ein.x, eY = ein.y, eType = ein.type;
if (timeStampBlockFrame == null) {
String windowName = "TSBlock";
timeStampBlockFrame = new JFrame(windowName);
timeStampBlockFrame.setLayout(new BoxLayout(timeStampBlockFrame.getContentPane(), BoxLayout.Y_AXIS));
timeStampBlockFrame.setPreferredSize(new Dimension(600, 600));
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
timeStampBlockImageDisplay = ImageDisplay.createOpenGLCanvas();
timeStampBlockImageDisplay.setBorderSpacePixels(10);
timeStampBlockImageDisplay.setImageSize(dim, dim);
timeStampBlockImageDisplay.setSize(200, 200);
timeStampBlockImageDisplay.setGrayValue(0);
timeStampBlockImageDisplayLegend = timeStampBlockImageDisplay.addLegend(LEGEND_G_SEARCH_AREA_R_REF_BLOCK_AREA_B_BEST_MATCH, 0, dim);
panel.add(timeStampBlockImageDisplay);
timeStampBlockFrame.getContentPane().add(panel);
timeStampBlockFrame.pack();
timeStampBlockFrame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
setShowSlices(false);
}
});
}
if (!timeStampBlockFrame.isVisible()) {
timeStampBlockFrame.setVisible(true);
}
timeStampBlockImageDisplay.clearImage();
int xInnerOffset[] = new int[16];
int yInnerOffset[] = new int[16];
for(int i = 0; i < 16; i++)
{
xInnerOffset[i] = innerCircle[i][0];
yInnerOffset[i] = innerCircle[i][1];
innerTsValue[i] = lastTimesMap[eX + xInnerOffset[i]][eY + yInnerOffset[i]][type];
if(innerTsValue[i] == 0x80000000) innerTsValue[i] = 0;
}
int xOuterOffset[] = new int[20];
int yOuterOffset[] = new int[20];
for(int i = 0; i < 20; i++)
{
xOuterOffset[i] = outerCircle[i][0];
yOuterOffset[i] = outerCircle[i][1];
outerTsValue[i] = lastTimesMap[eX + xOuterOffset[i]][eY + yOuterOffset[i]][type];
if(outerTsValue[i] == 0x80000000) outerTsValue[i] = 0;
}
List innerList = Arrays.asList(ArrayUtils.toObject(innerTsValue));
int innerMax = (int) Collections.max(innerList);
int innerMin = (int) Collections.min(innerList);
float innerScale = 1f / (innerMax - innerMin);
List outerList = Arrays.asList(ArrayUtils.toObject(outerTsValue));
int outerMax = (int) Collections.max(outerList);
int outerMin = (int) Collections.min(outerList);
float outerScale = 1f / (outerMax - outerMin);
timeStampBlockImageDisplay.setPixmapRGB(dim/2, dim/2, 0, 1, 0);
for(int i = 0; i < 16; i++)
{
timeStampBlockImageDisplay.setPixmapRGB(xInnerOffset[i] + dim/2, yInnerOffset[i] + dim/2, innerScale * (innerTsValue[i] - innerMin), 0, 0);
}
for(int i = 0; i < 20; i++)
{
timeStampBlockImageDisplay.setPixmapRGB(xOuterOffset[i] + dim/2, yOuterOffset[i] + dim/2, 0, 0, outerScale * (outerTsValue[i] - outerMin));
}
if (timeStampBlockImageDisplayLegend != null) {
timeStampBlockImageDisplayLegend.s
= TIME_STAMP_BLOCK_LEGEND_SLICES;
}
timeStampBlockImageDisplay.repaint();
}
private void drawSlices(byte[][][][] slices) {
// log.info("drawing slices");
if (sliceBitMapFrame == null) {
String windowName = "Slices";
sliceBitMapFrame = new JFrame(windowName);
sliceBitMapFrame.setLayout(new BoxLayout(sliceBitMapFrame.getContentPane(), BoxLayout.Y_AXIS));
sliceBitMapFrame.setPreferredSize(new Dimension(600, 600));
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
sliceBitmapImageDisplay = ImageDisplay.createOpenGLCanvas();
sliceBitmapImageDisplay.setBorderSpacePixels(10);
sliceBitmapImageDisplay.setImageSize(sizex, sizey);
sliceBitmapImageDisplay.setSize(200, 200);
sliceBitmapImageDisplay.setGrayValue(0);
sliceBitmapImageDisplayLegend = sliceBitmapImageDisplay.addLegend(LEGEND_G_SEARCH_AREA_R_REF_BLOCK_AREA_B_BEST_MATCH, 0, dim);
panel.add(sliceBitmapImageDisplay);
sliceBitMapFrame.getContentPane().add(panel);
sliceBitMapFrame.pack();
sliceBitMapFrame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
setShowSlices(false);
}
});
}
if (!sliceBitMapFrame.isVisible()) {
sliceBitMapFrame.setVisible(true);
}
float scale = 1f / getSliceMaxValue();
sliceBitmapImageDisplay.clearImage();
int d1 = sliceIndex(1), d2 = sliceIndex(2);
if (showSlicesScale >= numScales) {
showSlicesScale = numScales - 1;
}
for (int x = 0; x < sizex >> showSlicesScale; x++) {
for (int y = 0; y < sizey >> showSlicesScale; y++) {
// TODO only draw scale 0 (no subsampling) for now
sliceBitmapImageDisplay.setPixmapRGB(x, y, scale * slices[d2][showSlicesScale][x][y], scale * slices[d1][showSlicesScale][x][y], 0);
}
}
if (sliceBitmapImageDisplayLegend != null) {
sliceBitmapImageDisplayLegend.s
= LEGEND_SLICES;
}
sliceBitmapImageDisplay.repaint();
}
// /**
// * @return the numSlices
// */
// public int getNumSlices() {
// return numSlices;
// /**
// * @param numSlices the numSlices to set
// */
// synchronized public void setNumSlices(int numSlices) {
// if (numSlices < 3) {
// numSlices = 3;
// } else if (numSlices > 8) {
// numSlices = 8;
// this.numSlices = numSlices;
// putInt("numSlices", numSlices);
/**
* @return the sliceNumBits
*/
public int getSliceMaxValue() {
return sliceMaxValue;
}
/**
* @param sliceMaxValue the sliceMaxValue to set
*/
public void setSliceMaxValue(int sliceMaxValue) {
int old = this.sliceMaxValue;
if (sliceMaxValue < 1) {
sliceMaxValue = 1;
} else if (sliceMaxValue > 127) {
sliceMaxValue = 127;
}
this.sliceMaxValue = sliceMaxValue;
putInt("sliceMaxValue", sliceMaxValue);
getSupport().firePropertyChange("sliceMaxValue", old, this.sliceMaxValue);
}
/**
* @return the rectifyPolarties
*/
public boolean isRectifyPolarties() {
return rectifyPolarties;
}
/**
* @param rectifyPolarties the rectifyPolarties to set
*/
public void setRectifyPolarties(boolean rectifyPolarties) {
boolean old = this.rectifyPolarties;
this.rectifyPolarties = rectifyPolarties;
putBoolean("rectifyPolarties", rectifyPolarties);
getSupport().firePropertyChange("rectifyPolarties", old, this.rectifyPolarties);
}
/**
* @return the useSubsampling
*/
public boolean isUseSubsampling() {
return useSubsampling;
}
/**
* @param useSubsampling the useSubsampling to set
*/
public void setUseSubsampling(boolean useSubsampling) {
this.useSubsampling = useSubsampling;
}
/**
* @return the numScales
*/
public int getNumScales() {
return numScales;
}
/**
* @param numScales the numScales to set
*/
synchronized public void setNumScales(int numScales) {
int old = this.numScales;
if (numScales < 1) {
numScales = 1;
} else if (numScales > 4) {
numScales = 4;
}
this.numScales = numScales;
putInt("numScales", numScales);
setDefaultScalesToCompute();
scaleResultCounts = new int[numScales];
showBlockSizeAndSearchAreaTemporarily();
computeAveragePossibleMatchDistance();
getSupport().firePropertyChange("numScales", old, this.numScales);
}
/**
* Computes pooled (summed) value of slice at location xx, yy, in subsampled
* region around this point
*
* @param slice
* @param x
* @param y
* @param subsampleBy pool over 1<<subsampleBy by 1<<subsampleBy area to sum
* up the slice values @return
*/
private int pool(byte[][] slice, int x, int y, int subsampleBy) {
if (subsampleBy == 0) {
return slice[x][y];
} else {
int n = 1 << subsampleBy;
int sum = 0;
for (int xx = x; xx < x + n + n; xx++) {
for (int yy = y; yy < y + n + n; yy++) {
if (xx >= subSizeX || yy >= subSizeY) {
// log.warning("should not happen that xx="+xx+" or yy="+yy);
continue; // TODO remove this check when iteration avoids this sum explictly
}
sum += slice[xx][yy];
}
}
return sum;
}
}
/**
* @return the scalesToCompute
*/
public String getScalesToCompute() {
return scalesToCompute;
}
/**
* @param scalesToCompute the scalesToCompute to set
*/
synchronized public void setScalesToCompute(String scalesToCompute) {
this.scalesToCompute = scalesToCompute;
if (scalesToCompute == null || scalesToCompute.isEmpty()) {
setDefaultScalesToCompute();
} else {
StringTokenizer st = new StringTokenizer(scalesToCompute, ", ", false);
int n = st.countTokens();
if (n == 0) {
setDefaultScalesToCompute();
} else {
scalesToComputeArray = new Integer[n];
int i = 0;
while (st.hasMoreTokens()) {
try {
int scale = Integer.parseInt(st.nextToken());
scalesToComputeArray[i++] = scale;
} catch (NumberFormatException e) {
log.warning("bad string in scalesToCompute field, use blank or 0,2 for example");
setDefaultScalesToCompute();
}
}
}
}
}
private void setDefaultScalesToCompute() {
scalesToComputeArray = new Integer[numScales];
for (int i = 0; i < numScales; i++) {
scalesToComputeArray[i] = i;
}
}
/**
* @return the areaEventNumberSubsampling
*/
public int getAreaEventNumberSubsampling() {
return areaEventNumberSubsampling;
}
/**
* @param areaEventNumberSubsampling the areaEventNumberSubsampling to set
*/
synchronized public void setAreaEventNumberSubsampling(int areaEventNumberSubsampling) {
int old = this.areaEventNumberSubsampling;
if (areaEventNumberSubsampling < 3) {
areaEventNumberSubsampling = 3;
} else if (areaEventNumberSubsampling > 7) {
areaEventNumberSubsampling = 7;
}
this.areaEventNumberSubsampling = areaEventNumberSubsampling;
putInt("areaEventNumberSubsampling", areaEventNumberSubsampling);
showAreasForAreaCountsTemporarily();
clearAreaCounts();
if (sliceMethod != SliceMethod.AreaEventNumber) {
log.warning("AreaEventNumber method is not currently selected as sliceMethod");
}
getSupport().firePropertyChange("areaEventNumberSubsampling", old, this.areaEventNumberSubsampling);
}
private void showAreasForAreaCountsTemporarily() {
if (stopShowingStuffTask != null) {
stopShowingStuffTask.cancel();
}
stopShowingStuffTask = new TimerTask() {
@Override
public void run() {
showBlockSizeAndSearchAreaTemporarily = false; // in case we are canceling a task that would clear this
showAreaCountAreasTemporarily = false;
}
};
Timer showAreaCountsAreasTimer = new Timer();
showAreaCountAreasTemporarily = true;
showAreaCountsAreasTimer.schedule(stopShowingStuffTask, SHOW_STUFF_DURATION_MS);
}
private void showBlockSizeAndSearchAreaTemporarily() {
if (stopShowingStuffTask != null) {
stopShowingStuffTask.cancel();
}
stopShowingStuffTask = new TimerTask() {
@Override
public void run() {
showAreaCountAreasTemporarily = false; // in case we are canceling a task that would clear this
showBlockSizeAndSearchAreaTemporarily = false;
}
};
Timer showBlockSizeAndSearchAreaTimer = new Timer();
showBlockSizeAndSearchAreaTemporarily = true;
showBlockSizeAndSearchAreaTimer.schedule(stopShowingStuffTask, SHOW_STUFF_DURATION_MS);
}
private void clearAreaCounts() {
if (sliceMethod != SliceMethod.AreaEventNumber) {
return;
}
if (areaCounts == null || areaCounts.length != 1 + (subSizeX >> areaEventNumberSubsampling)) {
int nax = 1 + (subSizeX >> areaEventNumberSubsampling), nay = 1 + (subSizeY >> areaEventNumberSubsampling);
numAreas = nax * nay;
areaCounts = new int[nax][nay];
} else {
for (int[] i : areaCounts) {
Arrays.fill(i, 0);
}
}
areaCountExceeded = false;
}
private void clearNonGreedyRegions() {
if (!nonGreedyFlowComputingEnabled) {
return;
}
checkNonGreedyRegionsAllocated();
nonGreedyRegionsCount = 0;
for (boolean[] i : nonGreedyRegions) {
Arrays.fill(i, false);
}
}
private void checkNonGreedyRegionsAllocated() {
if (nonGreedyRegions == null || nonGreedyRegions.length != 1 + (subSizeX >> areaEventNumberSubsampling)) {
nonGreedyRegionsNumberOfRegions = (1 + (subSizeX >> areaEventNumberSubsampling)) * (1 + (subSizeY >> areaEventNumberSubsampling));
nonGreedyRegions = new boolean[1 + (subSizeX >> areaEventNumberSubsampling)][1 + (subSizeY >> areaEventNumberSubsampling)];
nonGreedyRegionsNumberOfRegions = (1 + (subSizeX >> areaEventNumberSubsampling)) * (1 + (subSizeY >> areaEventNumberSubsampling));
}
}
public int getSliceDeltaT() {
return sliceDeltaT;
}
/**
* @return the enableImuTimesliceLogging
*/
public boolean isEnableImuTimesliceLogging() {
return enableImuTimesliceLogging;
}
/**
* @param enableImuTimesliceLogging the enableImuTimesliceLogging to set
*/
public void setEnableImuTimesliceLogging(boolean enableImuTimesliceLogging) {
this.enableImuTimesliceLogging = enableImuTimesliceLogging;
if (enableImuTimesliceLogging) {
if (imuTimesliceLogger == null) {
imuTimesliceLogger = new TobiLogger("imuTimeslice.txt", "IMU rate gyro deg/s and patchmatch timeslice duration in ms");
imuTimesliceLogger.setHeaderLine("systemtime(ms) timestamp(us) timeslice(us) rate(deg/s)");
}
}
imuTimesliceLogger.setEnabled(enableImuTimesliceLogging);
}
/**
* @return the nonGreedyFlowComputingEnabled
*/
public boolean isNonGreedyFlowComputingEnabled() {
return nonGreedyFlowComputingEnabled;
}
/**
* @param nonGreedyFlowComputingEnabled the nonGreedyFlowComputingEnabled to
* set
*/
synchronized public void setNonGreedyFlowComputingEnabled(boolean nonGreedyFlowComputingEnabled) {
boolean old = this.nonGreedyFlowComputingEnabled;
this.nonGreedyFlowComputingEnabled = nonGreedyFlowComputingEnabled;
putBoolean("nonGreedyFlowComputingEnabled", nonGreedyFlowComputingEnabled);
if (nonGreedyFlowComputingEnabled) {
clearNonGreedyRegions();
}
getSupport().firePropertyChange("nonGreedyFlowComputingEnabled", old, nonGreedyFlowComputingEnabled);
}
/**
* @return the nonGreedyFractionToBeServiced
*/
public float getNonGreedyFractionToBeServiced() {
return nonGreedyFractionToBeServiced;
}
/**
* @param nonGreedyFractionToBeServiced the nonGreedyFractionToBeServiced to
* set
*/
public void setNonGreedyFractionToBeServiced(float nonGreedyFractionToBeServiced) {
this.nonGreedyFractionToBeServiced = nonGreedyFractionToBeServiced;
putFloat("nonGreedyFractionToBeServiced", nonGreedyFractionToBeServiced);
}
/**
* @return the adapativeSliceDurationProportionalErrorGain
*/
public float getAdapativeSliceDurationProportionalErrorGain() {
return adapativeSliceDurationProportionalErrorGain;
}
/**
* @param adapativeSliceDurationProportionalErrorGain the
* adapativeSliceDurationProportionalErrorGain to set
*/
public void setAdapativeSliceDurationProportionalErrorGain(float adapativeSliceDurationProportionalErrorGain) {
this.adapativeSliceDurationProportionalErrorGain = adapativeSliceDurationProportionalErrorGain;
putFloat("adapativeSliceDurationProportionalErrorGain", adapativeSliceDurationProportionalErrorGain);
}
/**
* @return the adapativeSliceDurationUseProportionalControl
*/
public boolean isAdapativeSliceDurationUseProportionalControl() {
return adapativeSliceDurationUseProportionalControl;
}
/**
* @param adapativeSliceDurationUseProportionalControl the
* adapativeSliceDurationUseProportionalControl to set
*/
public void setAdapativeSliceDurationUseProportionalControl(boolean adapativeSliceDurationUseProportionalControl) {
this.adapativeSliceDurationUseProportionalControl = adapativeSliceDurationUseProportionalControl;
putBoolean("adapativeSliceDurationUseProportionalControl", adapativeSliceDurationUseProportionalControl);
}
public boolean isPrintScaleCntStatEnabled() {
return printScaleCntStatEnabled;
}
public void setPrintScaleCntStatEnabled(boolean printScaleCntStatEnabled) {
this.printScaleCntStatEnabled = printScaleCntStatEnabled;
putBoolean("printScaleCntStatEnabled", printScaleCntStatEnabled);
}
/**
* @return the showSlicesScale
*/
public int getShowSlicesScale() {
return showSlicesScale;
}
/**
* @param showSlicesScale the showSlicesScale to set
*/
public void setShowSlicesScale(int showSlicesScale) {
if (showSlicesScale < 0) {
showSlicesScale = 0;
} else if (showSlicesScale > numScales - 1) {
showSlicesScale = numScales - 1;
}
this.showSlicesScale = showSlicesScale;
}
public boolean isCalcOFonCornersEnabled() {
return calcOFonCornersEnabled;
}
public void setCalcOFonCornersEnabled(boolean calcOFonCornersEnabled) {
this.calcOFonCornersEnabled = calcOFonCornersEnabled;
putBoolean("calcOFonCornersEnabled", calcOFonCornersEnabled);
}
}
|
package org.intermine.web;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.Collection;
import java.util.LinkedHashMap;
import org.intermine.metadata.AttributeDescriptor;
import org.intermine.metadata.ClassDescriptor;
import org.intermine.metadata.FieldDescriptor;
import org.intermine.metadata.Model;
import org.intermine.metadata.ReferenceDescriptor;
import org.intermine.objectstore.query.ConstraintOp;
import org.intermine.objectstore.query.ConstraintSet;
import org.intermine.objectstore.query.ContainsConstraint;
import org.intermine.objectstore.query.Query;
import org.intermine.objectstore.query.QueryClass;
import org.intermine.objectstore.query.QueryCollectionReference;
import org.intermine.objectstore.query.QueryField;
import org.intermine.objectstore.query.QueryNode;
import org.intermine.objectstore.query.QueryObjectReference;
import org.intermine.objectstore.query.QueryReference;
import org.intermine.objectstore.query.QueryValue;
import org.intermine.objectstore.query.SimpleConstraint;
import org.intermine.objectstore.query.BagConstraint;
import org.intermine.util.TypeUtil;
/**
* Helper methods for main controller and main action
* @author Mark Woodbridge
*/
public class MainHelper
{
/**
* Given a path, render a set of metadata Nodes to the relevant depth
* @param path of form Gene.organism.name
* @param model the model used to resolve class names
* @return an ordered Set of nodes
*/
public static Collection makeNodes(String path, Model model) {
String className, subPath;
if (path.indexOf(".") == -1) {
className = path;
subPath = "";
} else {
className = path.substring(0, path.indexOf("."));
subPath = path.substring(path.indexOf(".") + 1);
}
Map nodes = new TreeMap();
nodes.put(className, new LeftNode(className));
makeNodes(getClassDescriptor(className, model), subPath, className, nodes);
return nodes.values();
}
/**
* Recursive method used to add nodes to a set representing a path from a given ClassDescriptor
* @param cld the root ClassDescriptor
* @param path current path prefix (eg Gene)
* @param currentPath current path suffix (eg organism.name)
* @param nodes the current Node set
*/
public static void makeNodes(ClassDescriptor cld, String path, String currentPath, Map nodes) {
for (Iterator i = cld.getAllFieldDescriptors().iterator(); i.hasNext();) {
FieldDescriptor fd = (FieldDescriptor) i.next();
String fieldName = fd.getName();
if (fieldName.equals("id")) {
return;
}
String head, tail;
if (path.indexOf(".") != -1) {
head = path.substring(0, path.indexOf("."));
tail = path.substring(path.indexOf(".") + 1);
} else {
head = path;
tail = "";
}
String button;
if (fieldName.equals(head)) {
button = "-";
} else if (fd.isReference() || fd.isCollection()) {
button = "+";
} else {
button = " ";
}
LeftNode parent = (LeftNode) nodes.get(currentPath);
LeftNode node = new LeftNode(parent, fieldName, cld.getModel(), button);
nodes.put(node.getPath(), node);
if (fieldName.equals(head)) {
ClassDescriptor refCld = ((ReferenceDescriptor) fd).getReferencedClassDescriptor();
makeNodes(refCld, tail, currentPath + "." + head, nodes);
}
}
}
/**
* Method to return a String representing the unqualified type of the item referenced by a path
* @param path the path
* @param model the metadata used to resolve the types of fields in the path
* @return the type
*/
public static String getType(String path, Model model) {
if (path.indexOf(".") == -1) {
return path;
}
FieldDescriptor fd = getFieldDescriptor(path, model);
if (fd.isAttribute()) {
return TypeUtil.unqualifiedName(((AttributeDescriptor) fd).getType());
} else {
return TypeUtil.unqualifiedName(((ReferenceDescriptor) fd).
getReferencedClassDescriptor().getType().getName());
}
}
/**
* Return the metadata for a field identified by a path into a model (eg Gene.organism.name)
* @param path the path
* @param model the model
* @return the metadata for the field
*
*/
public static FieldDescriptor getFieldDescriptor(String path, Model model) {
if (path.indexOf(".") == -1) {
return null;
}
String className = path.substring(0, path.indexOf("."));
path = path.substring(path.indexOf(".") + 1);
ClassDescriptor cld = getClassDescriptor(className, model);
FieldDescriptor fd;
for (;;) {
if (path.indexOf(".") == -1) {
fd = cld.getFieldDescriptorByName(path);
break;
} else {
fd = cld.getFieldDescriptorByName(path.substring(0, path.indexOf(".")));
cld = ((ReferenceDescriptor) fd).getReferencedClassDescriptor();
path = path.substring(path.indexOf(".") + 1);
}
}
return fd;
}
/**
* Add a node to the query using a path, adding parent nodes if necessary
* @param qNodes the current Node map (from path to Node)
* @param path the path for the new Node
* @param model the model
*/
public static void addNode(Map qNodes, String path, Model model) {
String prefix = path.substring(0, path.lastIndexOf("."));
if (qNodes.containsKey(prefix)) {
RightNode parent = (RightNode) qNodes.get(prefix);
String fieldName = path.substring(path.lastIndexOf(".") + 1);
qNodes.put(path, new RightNode(parent, fieldName, model));
} else {
addNode(qNodes, prefix, model);
addNode(qNodes, path, model);
}
}
/**
* Make an InterMine query from a query represented as a Node map (from path to Node)
* @param qNodes the Node map
* @param view a list of paths (that may not appear in the query) to use as the results view
* @param model the relevant metadata
* @param savedBags the current saved bags map
* @return an InterMine Query
*/
public static Query makeQuery(Map qNodes, List view, Model model, Map savedBags) {
Map qNodes2 = new TreeMap(qNodes);
for (Iterator i = view.iterator(); i.hasNext();) {
String path = (String) i.next();
if (path.indexOf(".") != -1 && !qNodes.containsKey(path)) {
addNode(qNodes2, path, model);
}
}
ConstraintSet cs = new ConstraintSet(ConstraintOp.AND);
Query q = new Query();
q.setConstraint(cs);
Map queryBits = new HashMap();
for (Iterator i = qNodes2.values().iterator(); i.hasNext();) {
RightNode node = (RightNode) i.next();
String path = node.getPath();
if (path.indexOf(".") == -1) {
QueryClass qc = new QueryClass(getClass(node.getType(), model));
q.addFrom(qc);
queryBits.put(path, qc);
for (Iterator j = node.getConstraints().iterator(); j.hasNext();) {
Constraint c = (Constraint) j.next();
cs.addConstraint(new BagConstraint(qc,
c.getOp(),
(Collection) savedBags.get(c.getValue())));
}
continue;
}
String fieldName = path.substring(path.lastIndexOf(".") + 1);
String prefix = path.substring(0, path.lastIndexOf("."));
QueryClass parentQc = (QueryClass) queryBits.get(prefix);
FieldDescriptor fd = getFieldDescriptor(path, model);
if (fd.isAttribute()) {
QueryField qf = new QueryField(parentQc, fieldName);
queryBits.put(path, qf);
for (Iterator j = node.getConstraints().iterator(); j.hasNext();) {
Constraint c = (Constraint) j.next();
cs.addConstraint(new SimpleConstraint(qf,
c.getOp(),
new QueryValue(c.getValue())));
}
} else {
QueryReference qr = null;
if (fd.isReference()) {
qr = new QueryObjectReference(parentQc, fieldName);
} else {
qr = new QueryCollectionReference(parentQc, fieldName);
}
QueryClass qc = new QueryClass(getClass(node.getType(), model));
cs.addConstraint(new ContainsConstraint(qr, ConstraintOp.CONTAINS, qc));
q.addFrom(qc);
queryBits.put(path, qc);
for (Iterator j = node.getConstraints().iterator(); j.hasNext();) {
Constraint c = (Constraint) j.next();
cs.addConstraint(new BagConstraint(qc,
c.getOp(),
(Collection) savedBags.get(c.getValue())));
}
}
}
for (Iterator i = view.iterator(); i.hasNext();) {
String path = (String) i.next();
q.addToSelect((QueryNode) queryBits.get(path));
}
return q;
}
/**
* Instantiate a class by unqualified name
* The name should be "InterMineObject" or the name of class in the model provided
* @param className the name of the class
* @param model the Model used to resolve class names
* @return the relevant Class
*/
public static Class getClass(String className, Model model) {
if ("InterMineObject".equals(className)) {
className = "org.intermine.model.InterMineObject";
} else {
className = model.getPackageName() + "." + className;
}
try {
return Class.forName(className);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Get the metadata for a class by unqualified name
* The name is looked up in the provided model
* @param className the name of the class
* @param model the Model used to resolve class names
* @return the relevant ClassDescriptor
*/
public static ClassDescriptor getClassDescriptor(String className, Model model) {
return model.getClassDescriptorByName(getClass(className, model).getName());
}
/**
* Take a Collection of ConstraintOps and builds a map from ConstraintOp.getIndex() to
* ConstraintOp.toString() for each
* @param ops a Collection of ConstraintOps
* @return the Map from index to string
*/
protected static Map mapOps(Collection ops) {
Map opString = new LinkedHashMap();
for (Iterator iter = ops.iterator(); iter.hasNext();) {
ConstraintOp op = (ConstraintOp) iter.next();
opString.put(op.getIndex(), op.toString());
}
return opString;
}
}
|
package Taquilla.Views;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
public class RegisterPlayView extends javax.swing.JFrame {
private javax.swing.JLabel scheduleDateLabel;
private javax.swing.JLabel scheduleHourLabel;
private javax.swing.JSpinner scheduleHours;
private javax.swing.JSpinner scheduleMinutes;
private javax.swing.JLabel scheduleSelectedLabel;
private javax.swing.JTable showsTable;
private javax.swing.JButton cancelButton;
private javax.swing.JButton disponibilityButton;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JScrollPane jScrollPane3;
private javax.swing.JScrollPane jScrollPane4;
private javax.swing.JPanel panelPlay;
private javax.swing.JPanel panelResponsible;
private javax.swing.JPanel panelSchedule;
private javax.swing.JTextArea playActors;
private javax.swing.JLabel playActorsLabel;
private javax.swing.JTextArea playComments;
private javax.swing.JLabel playCommentsLabel;
private javax.swing.JTextArea playDescription;
private javax.swing.JLabel playDescriptionLabel;
private javax.swing.JTextField playName;
private javax.swing.JLabel playNameLabel;
private javax.swing.JTextField responsibleEmail;
private javax.swing.JLabel responsibleEmailLabel;
private javax.swing.JTextField responsibleLastName;
private javax.swing.JLabel responsibleLastNameLabel;
private javax.swing.JTextField responsibleName;
private javax.swing.JLabel responsibleNameLabel;
private javax.swing.JTextField responsibleTelephone;
private javax.swing.JTextField responsibleTelephoneAlt;
private javax.swing.JLabel responsibleTelephoneAltLabel;
private javax.swing.JLabel responsibleTelephoneLabel;
private javax.swing.JButton saveButton;
private javax.swing.JTextField scheduleDate;
private DefaultTableModel showsTableModel;
public RegisterPlayView() {
initComponents();
}
@SuppressWarnings("unchecked")
private void initComponents() {
panelResponsible = new javax.swing.JPanel();
responsibleNameLabel = new javax.swing.JLabel();
responsibleName = new javax.swing.JTextField();
responsibleLastNameLabel = new javax.swing.JLabel();
responsibleLastName = new javax.swing.JTextField();
responsibleTelephoneLabel = new javax.swing.JLabel();
responsibleTelephone = new javax.swing.JTextField();
responsibleTelephoneAltLabel = new javax.swing.JLabel();
responsibleTelephoneAlt = new javax.swing.JTextField();
responsibleEmailLabel = new javax.swing.JLabel();
responsibleEmail = new javax.swing.JTextField();
panelPlay = new javax.swing.JPanel();
playNameLabel = new javax.swing.JLabel();
playName = new javax.swing.JTextField();
playDescriptionLabel = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
playDescription = new javax.swing.JTextArea();
playActorsLabel = new javax.swing.JLabel();
jScrollPane2 = new javax.swing.JScrollPane();
playActors = new javax.swing.JTextArea();
playCommentsLabel = new javax.swing.JLabel();
jScrollPane3 = new javax.swing.JScrollPane();
playComments = new javax.swing.JTextArea();
panelSchedule = new javax.swing.JPanel();
scheduleSelectedLabel = new javax.swing.JLabel();
scheduleHourLabel = new javax.swing.JLabel();
scheduleHours = new javax.swing.JSpinner();
scheduleMinutes = new javax.swing.JSpinner();
jScrollPane4 = new javax.swing.JScrollPane();
showsTable = new javax.swing.JTable();
scheduleDateLabel = new javax.swing.JLabel();
scheduleDate = new javax.swing.JTextField();
disponibilityButton = new javax.swing.JButton();
saveButton = new javax.swing.JButton();
cancelButton = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Registrar obra - Taco Taquilla (TM)");
setResizable(false);
setLocation(new Point(300, 200));
setVisible(true);
panelResponsible.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos del responsable:"));
responsibleNameLabel.setText("Nombre:");
responsibleLastNameLabel.setText("Apellido:");
responsibleTelephoneLabel.setText("Número de teléfono:");
responsibleTelephoneAltLabel.setText("Número de teléfono alternativo:");
responsibleEmailLabel.setText("E-mail:");
javax.swing.GroupLayout panelResponsibleLayout = new javax.swing.GroupLayout(panelResponsible);
panelResponsible.setLayout(panelResponsibleLayout);
panelResponsibleLayout.setHorizontalGroup(
panelResponsibleLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelResponsibleLayout.createSequentialGroup()
.addContainerGap()
.addGroup(panelResponsibleLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(responsibleNameLabel)
.addComponent(responsibleName, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(responsibleLastNameLabel)
.addComponent(responsibleLastName, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(responsibleTelephoneLabel)
.addComponent(responsibleTelephone, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(responsibleTelephoneAltLabel)
.addComponent(responsibleTelephoneAlt, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(responsibleEmailLabel)
.addComponent(responsibleEmail, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(20, Short.MAX_VALUE))
);
panelResponsibleLayout.setVerticalGroup(
panelResponsibleLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelResponsibleLayout.createSequentialGroup()
.addContainerGap()
.addComponent(responsibleNameLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(responsibleName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(responsibleLastNameLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(responsibleLastName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(responsibleTelephoneLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(responsibleTelephone, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(responsibleTelephoneAltLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(responsibleTelephoneAlt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(responsibleEmailLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(responsibleEmail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
panelPlay.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos de la obra:"));
playNameLabel.setText("Nombre:");
playDescriptionLabel.setText("Descripción:");
playDescription.setColumns(20);
playDescription.setRows(5);
jScrollPane1.setViewportView(playDescription);
playActorsLabel.setText("Actores principales (uno por línea):");
playActors.setColumns(20);
playActors.setRows(5);
jScrollPane2.setViewportView(playActors);
playCommentsLabel.setText("Otros datos relevantes:");
playComments.setColumns(20);
playComments.setRows(5);
jScrollPane3.setViewportView(playComments);
javax.swing.GroupLayout panelPlayLayout = new javax.swing.GroupLayout(panelPlay);
panelPlay.setLayout(panelPlayLayout);
panelPlayLayout.setHorizontalGroup(
panelPlayLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelPlayLayout.createSequentialGroup()
.addContainerGap()
.addGroup(panelPlayLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 202, Short.MAX_VALUE)
.addGroup(panelPlayLayout.createSequentialGroup()
.addGroup(panelPlayLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(playNameLabel)
.addComponent(playDescriptionLabel)
.addComponent(playActorsLabel)
.addComponent(playCommentsLabel))
.addGap(0, 0, Short.MAX_VALUE))
.addComponent(jScrollPane2)
.addComponent(jScrollPane3)
.addComponent(playName))
.addContainerGap())
);
panelPlayLayout.setVerticalGroup(
panelPlayLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelPlayLayout.createSequentialGroup()
.addContainerGap()
.addComponent(playNameLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(playName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(playDescriptionLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(playActorsLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(playCommentsLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
panelSchedule.setBorder(javax.swing.BorderFactory.createTitledBorder("Fechas y horarios:"));
scheduleSelectedLabel.setText("Fechas seleccionadas disponibles:");
scheduleHourLabel.setText("Horario (24 horas):");
scheduleHours.setModel(new javax.swing.SpinnerNumberModel(23, 0, 23, 1));
scheduleMinutes.setModel(new javax.swing.SpinnerNumberModel(59, 0, 59, 1));
String header[] = {"Fecha", "Hora"};
String data[][] = {};
showsTableModel = new DefaultTableModel(data, header);
showsTable.setModel(showsTableModel);
jScrollPane4.setViewportView(showsTable);
scheduleDateLabel.setText("Selecciones fecha (dd-MM-yyyy):");
disponibilityButton.setText("Comprobar disponibilidad...");
javax.swing.GroupLayout panelScheduleLayout = new javax.swing.GroupLayout(panelSchedule);
panelSchedule.setLayout(panelScheduleLayout);
panelScheduleLayout.setHorizontalGroup(
panelScheduleLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelScheduleLayout.createSequentialGroup()
.addContainerGap()
.addGroup(panelScheduleLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelScheduleLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(scheduleSelectedLabel)
.addComponent(scheduleHourLabel)
.addGroup(panelScheduleLayout.createSequentialGroup()
.addComponent(scheduleHours, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(scheduleMinutes, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 355, Short.MAX_VALUE)
.addComponent(scheduleDateLabel)
.addComponent(scheduleDate))
.addComponent(disponibilityButton))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
panelScheduleLayout.setVerticalGroup(
panelScheduleLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panelScheduleLayout.createSequentialGroup()
.addContainerGap()
.addComponent(scheduleDateLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(scheduleDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(scheduleHourLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(panelScheduleLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(scheduleHours, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(scheduleMinutes, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(disponibilityButton)
.addGap(18, 18, 18)
.addComponent(scheduleSelectedLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
saveButton.setText("Guardar");
cancelButton.setText("Cancelar");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(panelResponsible, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(panelPlay, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(panelSchedule, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGap(80, 80, 80)
.addComponent(saveButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(cancelButton)
.addGap(93, 93, 93))))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(panelResponsible, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(panelPlay, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addComponent(panelSchedule, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(cancelButton)
.addComponent(saveButton))))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}
public static void main(String args[]) {
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(RegisterPlayView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(RegisterPlayView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(RegisterPlayView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(RegisterPlayView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new RegisterPlayView().setVisible(true);
}
});
}
public JSpinner getScheduleHours() {
return scheduleHours;
}
public JSpinner getScheduleMinutes() {
return scheduleMinutes;
}
public JButton getCancelButton() {
return cancelButton;
}
public JButton getDisponibilityButton() {
return disponibilityButton;
}
public JTextArea getPlayActors() {
return playActors;
}
public JTextArea getPlayComments() {
return playComments;
}
public JTextArea getPlayDescription() {
return playDescription;
}
public JTextField getPlayName() {
return playName;
}
public JTextField getResponsibleEmail() {
return responsibleEmail;
}
public JTextField getResponsibleLastName() {
return responsibleLastName;
}
public JTextField getResponsibleName() {
return responsibleName;
}
public JTextField getResponsibleTelephone() {
return responsibleTelephone;
}
public JTextField getResponsibleTelephoneAlt() {
return responsibleTelephoneAlt;
}
public JButton getSaveButton() {
return saveButton;
}
public JTextField getScheduleDate() {
return scheduleDate;
}
public DefaultTableModel getTableModel() {
return showsTableModel;
}
}
|
package ch.unizh.ini.jaer.projects.minliu;
import ch.unizh.ini.jaer.projects.rbodo.opticalflow.AbstractMotionFlow;
import com.jogamp.opengl.util.awt.TextRenderer;
import eu.seebetter.ini.chips.davis.imu.IMUSample;
import java.awt.geom.Point2D;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Iterator;
import java.util.Observable;
import java.util.Observer;
import net.sf.jaer.Description;
import net.sf.jaer.DevelopmentStatus;
import net.sf.jaer.chip.AEChip;
import net.sf.jaer.event.ApsDvsEvent;
import net.sf.jaer.event.ApsDvsEventPacket;
import net.sf.jaer.event.EventPacket;
import net.sf.jaer.eventprocessing.FilterChain;
import net.sf.jaer.eventprocessing.filter.Steadicam;
import net.sf.jaer.eventprocessing.filter.TransformAtTime;
import net.sf.jaer.util.filter.HighpassFilter;
/**
* Uses patch matching to measure local optical flow. <b>Not</b> gradient based,
* but rather matches local features backwards in time.
*
* @author Tobi, Jan 2016
*/
@Description("Computes true flow events with speed and vector direction using binary feature patch matching.")
@DevelopmentStatus(DevelopmentStatus.Status.Experimental)
public class PatchMatchFlow extends AbstractMotionFlow implements Observer {
// These const values are for the fast implementation of the hamming weight calculation
private final long m1 = 0x5555555555555555L; //binary: 0101...
private final long m2 = 0x3333333333333333L; //binary: 00110011..
private final long m4 = 0x0f0f0f0f0f0f0f0fL; //binary: 4 zeros, 4 ones ...
private final long m8 = 0x00ff00ff00ff00ffL; //binary: 8 zeros, 8 ones ...
private final long m16 = 0x0000ffff0000ffffL; //binary: 16 zeros, 16 ones ...
private final long m32 = 0x00000000ffffffffL; //binary: 32 zeros, 32 ones
private final long hff = 0xffffffffffffffffL; //binary: all ones
private final long h01 = 0x0101010101010101L; //the sum of 256 to the power of 0,1,2,3...
private int[][][] histograms = null;
private int numSlices = 3;
private int sx, sy;
private int tMinus2SliceIdx = 0, tMinus1SliceIdx = 1, currentSliceIdx = 2;
private int[][] currentSlice = null, tMinus1Slice = null, tMinus2Slice = null;
private BitSet[] histogramsBitSet = null;
private BitSet currentSli = null, tMinus1Sli = null, tMinus2Sli = null;
private int patchDimension = getInt("patchDimension", 8);
protected boolean measurePerformance = getBoolean("measurePerformance", false);
private boolean displayOutputVectors = getBoolean("displayOutputVectors", true);
public enum PatchCompareMethod {
JaccardDistance, HammingDistance, SAD
};
private PatchCompareMethod patchCompareMethod = PatchCompareMethod.valueOf(getString("patchCompareMethod", PatchCompareMethod.HammingDistance.toString()));
private int sliceDurationUs = getInt("sliceDurationUs", 1000);
private int sliceEventCount = getInt("sliceEventCount", 1000);
private String patchTT = "Patch matching";
private float sadSum = 0;
private boolean rewindFlg = false; // The flag to indicate the rewind event.
private TransformAtTime lastTransform = null, imageTransform = null;
private FilterChain filterChain;
private Steadicam cameraMotion;
private int packetNum;
private int sx2;
private int sy2;
private double panTranslationDeg;
private double tiltTranslationDeg;
private float rollDeg;
private int lastImuTimestamp = 0;
private float panRate = 0, tiltRate = 0, rollRate = 0; // in deg/sec
private float panOffset = getFloat("panOffset", 0), tiltOffset = getFloat("tiltOffset", 0), rollOffset = getFloat("rollOffset", 0);
private float panDC = 0, tiltDC = 0, rollDC = 0;
private boolean showTransformRectangle = getBoolean("showTransformRectangle", true);
private boolean removeCameraMotion = getBoolean("removeCameraMotion", true);
// calibration
private boolean calibrating = false; // used to flag calibration state
private int calibrationSampleCount = 0;
private int NUM_CALIBRATION_SAMPLES_DEFAULT = 800; // 400 samples /sec
protected int numCalibrationSamples = getInt("numCalibrationSamples", NUM_CALIBRATION_SAMPLES_DEFAULT);
private CalibrationFilter panCalibrator, tiltCalibrator, rollCalibrator;
TextRenderer imuTextRenderer = null;
private boolean showGrid = getBoolean("showGrid", true);
private int flushCounter = 0;
public enum SliceMethod {
ConstantDuration, ConstantEventNumber
};
private SliceMethod sliceMethod = SliceMethod.valueOf(getString("sliceMethod", SliceMethod.ConstantDuration.toString()));
private int eventCounter = 0;
// private int sliceLastTs = Integer.MIN_VALUE;
private int sliceLastTs = 0;
HighpassFilter panTranslationFilter = new HighpassFilter();
HighpassFilter tiltTranslationFilter = new HighpassFilter();
HighpassFilter rollFilter = new HighpassFilter();
private float highpassTauMsTranslation = getFloat("highpassTauMsTranslation", 1000);
private float highpassTauMsRotation = getFloat("highpassTauMsRotation", 1000);
private boolean highPassFilterEn = getBoolean("highPassFilterEn", false);
public PatchMatchFlow(AEChip chip) {
super(chip);
filterChain = new FilterChain(chip);
cameraMotion = new Steadicam(chip);
cameraMotion.setFilterEnabled(true);
cameraMotion.setDisableRotation(true);
cameraMotion.setDisableTranslation(true);
// filterChain.add(cameraMotion);
setEnclosedFilterChain(filterChain);
String imu = "IMU";
chip.addObserver(this); // to allocate memory once chip size is known
setPropertyTooltip(patchTT, "patchDimension", "linear dimenion of patches to match, in pixels");
setPropertyTooltip(patchTT, "searchDistance", "search distance for matching patches, in pixels");
setPropertyTooltip(patchTT, "patchCompareMethod", "method to compare two patches");
setPropertyTooltip(patchTT, "sliceDurationUs", "duration of patches in us");
setPropertyTooltip(patchTT, "sliceEventCount", "number of collected events in each bitmap");
setPropertyTooltip(dispTT, "highpassTauMsTranslation", "highpass filter time constant in ms to relax transform back to zero for translation (pan, tilt) components");
setPropertyTooltip(dispTT, "highpassTauMsRotation", "highpass filter time constant in ms to relax transform back to zero for rotation (roll) component");
setPropertyTooltip(dispTT, "highPassFilterEn", "enable the high pass filter or not");
setPropertyTooltip(dispTT, "showTransformRectangle", "Disable to not show the red transform square and red cross hairs");
setPropertyTooltip(dispTT, "displayOutputVectors", "display the output motion vectors or not");
setPropertyTooltip(imu, "removeCameraMotion", "Remove the camera motion");
setPropertyTooltip(imu, "zeroGyro", "zeros the gyro output. Sensor should be stationary for period of 1-2 seconds during zeroing");
setPropertyTooltip(imu, "eraseGyroZero", "Erases the gyro zero values");
panCalibrator = new CalibrationFilter();
tiltCalibrator = new CalibrationFilter();
rollCalibrator = new CalibrationFilter();
rollFilter.setTauMs(highpassTauMsRotation);
panTranslationFilter.setTauMs(highpassTauMsTranslation);
tiltTranslationFilter.setTauMs(highpassTauMsTranslation);
lastTransform = new TransformAtTime(ts,
new Point2D.Float(
(float)(0),
(float)(0)),
(float) (0));
}
@Override
public EventPacket filterPacket(EventPacket in) {
setupFilter(in);
sadSum = 0;
packetNum++;
ApsDvsEventPacket in2 = (ApsDvsEventPacket) in;
Iterator itr = in2.fullIterator(); // We also need IMU data, so here we use the full iterator.
while (itr.hasNext()) {
Object ein = itr.next();
if (ein == null) {
log.warning("null event passed in, returning input packet");
return in;
}
extractEventInfo(ein);
ApsDvsEvent apsDvsEvent = (ApsDvsEvent) ein;
if (apsDvsEvent.isImuSample()) {
IMUSample s = apsDvsEvent.getImuSample();
lastTransform = updateTransform(s);
}
// inItr = in.inputIterator;
if (measureAccuracy || discardOutliersForStatisticalMeasurementEnabled) {
imuFlowEstimator.calculateImuFlow((ApsDvsEvent) inItr.next());
setGroundTruth();
}
if (xyFilter()) {
continue;
}
countIn++;
if(!removeCameraMotion) {
showTransformRectangle = true;
int nx = e.x - 120, ny = e.y - 90;
e.x = (short) ((((lastTransform.cosAngle * nx) - (lastTransform.sinAngle * ny)) + lastTransform.translationPixels.x) + 120);
e.y = (short) (((lastTransform.sinAngle * nx) + (lastTransform.cosAngle * ny) + lastTransform.translationPixels.y) + 90);
e.address = chip.getEventExtractor().getAddressFromCell(e.x, e.y, e.getType()); // so event is logged properly to disk
if ((e.x > 239) || (e.x < 0) || (e.y > 179) || (e.y < 0)) {
e.setFilteredOut(true); // TODO this gradually fills the packet with filteredOut events, which are never seen afterwards because the iterator filters them outputPacket in the reused packet.
continue; // discard events outside chip limits for now, because we can't render them presently, although they are valid events
} else {
e.setFilteredOut(false);
}
extractEventInfo(e); // Update x, y, ts and type
} else {
showTransformRectangle = false;
}
long startTime = 0;
if (measurePerformance) {
startTime = System.nanoTime();
}
// compute flow
maybeRotateSlices();
accumulateEvent();
SADResult result = new SADResult(0,0,0);
switch(patchCompareMethod) {
case HammingDistance:
result = minHammingDistance(x, y, tMinus2Sli, tMinus1Sli);
break;
case SAD:
result = minSad(x, y, tMinus2Slice, tMinus1Slice);
break;
case JaccardDistance:
result = minJaccardDistance(x, y, tMinus2Sli, tMinus1Sli);
break;
}
vx = result.dx * 5;
vy = result.dy * 5;
v = (float) Math.sqrt(vx * vx + vy * vy);
if (measurePerformance) {
long dt = System.nanoTime() - startTime;
float us = 1e-3f * dt;
log.info(String.format("Per event processing time: %.1fus", us));
}
// long[] testByteArray1 = tMinus1Sli.toLongArray();
// long[] testByteArray2 = tMinus2Sli.toLongArray();
// tMinus1Sli.andNot(tMinus2Sli);
// long test1 = popcount_3((long) sadSum);
// DavisChip apsDvsChip = (DavisChip) chip;
// int frameStartTimestamp = apsDvsChip.getFrameExposureStartTimestampUs();
// int frameEndTimestamp = apsDvsChip.getFrameExposureEndTimestampUs();
// int frameCounter = apsDvsChip.getFrameCount();
// // if a frame has been read outputPacket, then save the last transform to apply to rendering this frame
// imageTransform = lastTransform;
// ChipRendererDisplayMethodRGBA displayMethod = (ChipRendererDisplayMethodRGBA) chip.getCanvas().getDisplayMethod(); // TODO not ideal (tobi)
// displayMethod.setImageTransform(lastTransform.translationPixels, lastTransform.rotationRad);
// reject values that are unreasonable
if (accuracyTests()) {
continue;
}
if(displayOutputVectors) {
writeOutputEvent();
}
if (measureAccuracy) {
motionFlowStatistics.update(vx, vy, v, vxGT, vyGT, vGT);
}
}
// if(cameraMotion.getLastTransform() != null) {
// lastTransform = cameraMotion.getLastTransform();
// ChipRendererDisplayMethodRGBA displayMethod = (ChipRendererDisplayMethodRGBA) chip.getCanvas().getDisplayMethod(); // After the rewind event, restore sliceLastTs to 0 and rewindFlg to false.
// displayMethod.getImageTransform();
// displayMethod.setImageTransform(lastTransform.translationPixels, lastTransform.rotationRad);
if(rewindFlg) {
rewindFlg = false;
sliceLastTs = 0;
flushCounter = 10;
panDC = 0;
tiltDC = 0;
rollDC = 0;
}
motionFlowStatistics.updatePacket(countIn, countOut);
return isShowRawInputEnabled() ? in : dirPacket;
}
@Override
public synchronized void resetFilter() {
super.resetFilter();
eventCounter = 0;
lastTs = Integer.MIN_VALUE;
if (histograms == null || histograms.length != subSizeX || histograms[0].length != subSizeY) {
histograms = new int[numSlices][subSizeX][subSizeY];
}
for (int[][] a : histograms) {
for (int[] b : a) {
Arrays.fill(b, 0);
}
}
if (histogramsBitSet == null) {
histogramsBitSet = new BitSet[numSlices];
}
for(int ii = 0; ii < numSlices; ii ++) {
histogramsBitSet[ii] = new BitSet(subSizeX*subSizeY);
}
tMinus2SliceIdx = 0;
tMinus1SliceIdx = 1;
currentSliceIdx = 2;
assignSliceReferences();
sliceLastTs = 0;
packetNum = 0;
rewindFlg = true;
}
// @Override
// public void annotate(GLAutoDrawable drawable) {
// GL2 gl = null;
// if (showTransformRectangle) {
// gl = drawable.getGL().getGL2();
// if (gl == null) {
// return;
// // draw transform
// gl.glPushMatrix();
// // Use this blur rectangle to indicate where is the zero point position.
// gl.glColor4f(.1f, .1f, 1f, .25f);
// gl.glRectf(0, 0, 10, 10);
// gl.glLineWidth(1f);
// gl.glColor3f(1, 0, 0);
// if(chip != null) {
// sx2 = chip.getSizeX() / 2;
// sy2 = chip.getSizeY() / 2;
// } else {
// sx2 = 0;
// sy2 = 0;
// // translate and rotate
// if(lastTransform != null) {
// gl.glTranslatef(lastTransform.translationPixels.x + sx2, lastTransform.translationPixels.y + sy2, 0);
// gl.glRotatef((float) ((lastTransform.rotationRad * 180) / Math.PI), 0, 0, 1);
// // draw xhairs on frame to help show locations of objects and if they have moved.
// gl.glBegin(GL.GL_LINES); // sequence of individual segments, in pairs of vertices
// gl.glVertex2f(0, 0); // start at origin
// gl.glVertex2f(sx2, 0); // outputPacket to right
// gl.glVertex2f(0, 0); // origin
// gl.glVertex2f(-sx2, 0); // outputPacket to left
// gl.glVertex2f(0, 0); // origin
// gl.glVertex2f(0, sy2); // up
// gl.glVertex2f(0, 0); // origin
// gl.glVertex2f(0, -sy2); // down
// gl.glEnd();
// // rectangle around transform
// gl.glTranslatef(-sx2, -sy2, 0); // lower left corner
// gl.glBegin(GL.GL_LINE_LOOP); // loop of vertices
// gl.glVertex2f(0, 0); // lower left corner
// gl.glVertex2f(sx2 * 2, 0); // lower right
// gl.glVertex2f(2 * sx2, 2 * sy2); // upper right
// gl.glVertex2f(0, 2 * sy2); // upper left
// gl.glVertex2f(0, 0); // back of lower left
// gl.glEnd();
// gl.glPopMatrix();
@Override
public void update(Observable o, Object arg) {
super.update(o, arg);
if (!isFilterEnabled()) {
return;
}
if (o instanceof AEChip && chip.getNumPixels() > 0) {
resetFilter();
}
}
/**
* Computes transform using current gyro outputs based on timestamp supplied
* and returns a TransformAtTime object.
*
* @param timestamp the timestamp in us.
* @return the transform object representing the camera rotationRad
*/
synchronized public TransformAtTime updateTransform(IMUSample imuSample) {
int timestamp = imuSample.getTimestampUs();
float dtS = (timestamp - lastImuTimestamp) * 1e-6f;
lastImuTimestamp = timestamp;
if (flushCounter
return new TransformAtTime(ts,
new Point2D.Float( (float)(0),(float)(0)),
(float) (0)); // flush some samples if the timestamps have been reset and we need to discard some samples here
}
panRate = imuSample.getGyroYawY();
tiltRate = imuSample.getGyroTiltX();
rollRate = imuSample.getGyroRollZ();
if (calibrating) {
calibrationSampleCount++;
if (calibrationSampleCount > numCalibrationSamples) {
calibrating = false;
panOffset = panCalibrator.computeAverage();
tiltOffset = tiltCalibrator.computeAverage();
rollOffset = rollCalibrator.computeAverage();
panDC = 0;
tiltDC = 0;
rollDC = 0;
putFloat("panOffset", panOffset);
putFloat("tiltOffset", tiltOffset);
putFloat("rollOffset", rollOffset);
log.info(String.format("calibration finished. %d samples averaged to (pan,tilt,roll)=(%.3f,%.3f,%.3f)", numCalibrationSamples, panOffset, tiltOffset, rollOffset));
} else {
panCalibrator.addSample(panRate);
tiltCalibrator.addSample(tiltRate);
rollCalibrator.addSample(rollRate);
}
return new TransformAtTime(ts,
new Point2D.Float( (float)(0),(float)(0)),
(float) (0));
}
panDC += getPanRate() * dtS;
tiltDC += getTiltRate() * dtS;
rollDC += getRollRate() * dtS;
if(highPassFilterEn) {
panTranslationDeg = panTranslationFilter.filter(panDC, timestamp);
tiltTranslationDeg = tiltTranslationFilter.filter(tiltDC, timestamp);
rollDeg = rollFilter.filter(rollDC, timestamp);
} else {
panTranslationDeg = panDC;
tiltTranslationDeg = tiltDC;
rollDeg = rollDC;
}
float radValPerPixel = (float) Math.atan(chip.getPixelWidthUm() / (1000 * getLensFocalLengthMm()));
// Use the lens focal length and camera resolution.
TransformAtTime tr = new TransformAtTime(timestamp,
new Point2D.Float(
(float) ((Math.PI / 180) * panTranslationDeg/radValPerPixel),
(float) ((Math.PI / 180) * tiltTranslationDeg/radValPerPixel)),
(-rollDeg * (float) Math.PI) / 180);
return tr;
}
private class CalibrationFilter {
int count = 0;
float sum = 0;
void reset() {
count = 0;
sum = 0;
}
void addSample(float sample) {
sum += sample;
count++;
}
float computeAverage() {
return sum / count;
}
}
/**
* @return the panRate
*/
public float getPanRate() {
return panRate - panOffset;
}
/**
* @return the tiltRate
*/
public float getTiltRate() {
return tiltRate - tiltOffset;
}
/**
* @return the rollRate
*/
public float getRollRate() {
return rollRate - rollOffset;
}
/**
* uses the current event to maybe rotate the slices
*/
private void maybeRotateSlices() {
switch (sliceMethod) {
case ConstantDuration:
int dt = ts - sliceLastTs;
if(rewindFlg) {
return;
}
if (dt < sliceDurationUs || dt < 0) {
return;
}
break;
case ConstantEventNumber:
if (eventCounter++ < sliceEventCount) {
return;
}
}
/* The index cycle is " current idx -> t1 idx -> t2 idx -> current idx".
Change the index, the change should like this:
next t2 = previous t1 = histogram(previous t2 idx + 1);
next t1 = previous current = histogram(previous t1 idx + 1);
*/
currentSliceIdx = (currentSliceIdx + 1) % numSlices;
tMinus1SliceIdx = (tMinus1SliceIdx + 1) % numSlices;
tMinus2SliceIdx = (tMinus2SliceIdx + 1) % numSlices;
sliceEventCount = 0;
sliceLastTs = ts;
assignSliceReferences();
}
private void assignSliceReferences() {
currentSlice = histograms[currentSliceIdx];
tMinus1Slice = histograms[tMinus1SliceIdx];
tMinus2Slice = histograms[tMinus2SliceIdx];
currentSli = histogramsBitSet[currentSliceIdx];
tMinus1Sli = histogramsBitSet[tMinus1SliceIdx];
tMinus2Sli = histogramsBitSet[tMinus2SliceIdx];
currentSli.clear();
}
/**
* Accumulates the current event to the current slice
*/
private void accumulateEvent() {
currentSlice[x][y] += e.getPolaritySignum();
currentSli.set((x + 1) + y * subSizeX); // All evnets wheather 0 or 1 will be set in the BitSet Slice.
}
private void clearSlice(int idx) {
for (int[] a : histograms[idx]) {
Arrays.fill(a, 0);
}
}
synchronized public void doEraseGyroZero() {
panOffset = 0;
tiltOffset = 0;
rollOffset = 0;
putFloat("panOffset", 0);
putFloat("tiltOffset", 0);
putFloat("rollOffset", 0);
log.info("calibration erased");
}
synchronized public void doZeroGyro() {
calibrating = true;
calibrationSampleCount = 0;
panCalibrator.reset();
tiltCalibrator.reset();
rollCalibrator.reset();
log.info("calibration started");
// panOffset = panRate; // TODO offsets should really be some average over some samples
// tiltOffset = tiltRate;
// rollOffset = rollRate;
}
/**
* Computes hamming eight around point x,y using patchDimension and
* searchDistance
*
* @param x coordinate in subsampled space
* @param y
* @param prevSlice
* @param curSlice
* @return SADResult that provides the shift and SAD value
*/
private SADResult minHammingDistance(int x, int y, BitSet prevSlice, BitSet curSlice) {
int minSum = Integer.MAX_VALUE, sum = 0;
SADResult sadResult = new SADResult(0, 0, 0);
for (int dx = -searchDistance; dx <= searchDistance; dx++) {
for (int dy = -searchDistance; dy <= searchDistance; dy++) {
sum = hammingDistance(x, y, dx, dy, prevSlice, curSlice);
if(sum <= minSum) {
minSum = sum;
sadResult.dx = dx;
sadResult.dy = dy;
sadResult.sadValue = minSum;
}
}
}
return sadResult;
}
/**
* computes Hamming distance centered on x,y with patch of patchSize for prevSliceIdx
* relative to curSliceIdx patch.
*
* @param x coordinate in subSampled space
* @param y
* @param patchSize
* @param prevSliceIdx
* @param curSliceIdx
* @return SAD value
*/
private int hammingDistance(int x, int y, int dx, int dy, BitSet prevSlice, BitSet curSlice) {
int retVal = 0;
// Make sure 0<=xx+dx<subSizeX, 0<=xx<subSizeX and 0<=yy+dy<subSizeY, 0<=yy<subSizeY, or there'll be arrayIndexOutOfBoundary exception.
if (x < patchDimension + dx || x >= subSizeX - patchDimension + dx || x < patchDimension || x >= subSizeX - patchDimension
|| y < patchDimension + dy || y >= subSizeY - patchDimension + dy || y < patchDimension || y >= subSizeY - patchDimension) {
return 0;
}
for (int xx = x - patchDimension; xx <= x + patchDimension; xx++) {
for (int yy = y - patchDimension; yy <= y + patchDimension; yy++) {
if(curSlice.get((xx + 1) + (yy) * subSizeX) != prevSlice.get((xx + 1 - dx) + (yy - dy) * subSizeX)) {
retVal += 1;
}
}
}
return retVal;
}
/**
* Computes hamming eight around point x,y using patchDimension and
* searchDistance
*
* @param x coordinate in subsampled space
* @param y
* @param prevSlice
* @param curSlice
* @return SADResult that provides the shift and SAD value
*/
private SADResult minJaccardDistance(int x, int y, BitSet prevSlice, BitSet curSlice) {
float minSum = Integer.MAX_VALUE, sum = 0;
SADResult sadResult = new SADResult(0, 0, 0);
for (int dx = -searchDistance; dx <= searchDistance; dx++) {
for (int dy = -searchDistance; dy <= searchDistance; dy++) {
sum = jaccardDistance(x, y, dx, dy, prevSlice, curSlice);
if(sum <= minSum) {
minSum = sum;
sadResult.dx = dx;
sadResult.dy = dy;
sadResult.sadValue = minSum;
}
}
}
return sadResult;
}
/**
* computes Hamming distance centered on x,y with patch of patchSize for prevSliceIdx
* relative to curSliceIdx patch.
*
* @param x coordinate in subSampled space
* @param y
* @param patchSize
* @param prevSliceIdx
* @param curSliceIdx
* @return SAD value
*/
private float jaccardDistance(int x, int y, int dx, int dy, BitSet prevSlice, BitSet curSlice) {
float retVal = 0;
float M01 = 0, M10 = 0, M11 = 0;
// Make sure 0<=xx+dx<subSizeX, 0<=xx<subSizeX and 0<=yy+dy<subSizeY, 0<=yy<subSizeY, or there'll be arrayIndexOutOfBoundary exception.
if (x < patchDimension + dx || x >= subSizeX - patchDimension + dx || x < patchDimension || x >= subSizeX - patchDimension
|| y < patchDimension + dy || y >= subSizeY - patchDimension + dy || y < patchDimension || y >= subSizeY - patchDimension) {
return 0;
}
for (int xx = x - patchDimension; xx <= x + patchDimension; xx++) {
for (int yy = y - patchDimension; yy <= y + patchDimension; yy++) {
if(curSlice.get((xx + 1) + (yy) * subSizeX) == true && prevSlice.get((xx + 1 - dx) + (yy - dy) * subSizeX) == true) {
M11 += 1;
}
if(curSlice.get((xx + 1) + (yy) * subSizeX) == true && prevSlice.get((xx + 1 - dx) + (yy - dy) * subSizeX) == false) {
M01 += 1;
}
if(curSlice.get((xx + 1) + (yy) * subSizeX) == false && prevSlice.get((xx + 1 - dx) + (yy - dy) * subSizeX) == true) {
M10 += 1;
}
}
}
if(0 == M01 + M10 + M11) {
retVal = 0;
} else {
retVal = M11/(M01 + M10 + M11);
}
retVal = 1 - retVal;
return retVal;
}
/**
* Computes min SAD shift around point x,y using patchDimension and
* searchDistance
*
* @param x coordinate in subsampled space
* @param y
* @param prevSlice
* @param curSlice
* @return SADResult that provides the shift and SAD value
*/
private SADResult minSad(int x, int y, int[][] prevSlice, int[][] curSlice) {
// for now just do exhaustive search over all shifts up to +/-searchDistance
SADResult sadResult = new SADResult(0, 0, 0);
int minSad = Integer.MAX_VALUE, minDx = 0, minDy = 0;
for (int dx = -searchDistance; dx <= searchDistance; dx++) {
for (int dy = -searchDistance; dy <= searchDistance; dy++) {
int sad = sad(x, y, dx, dy, prevSlice, curSlice);
if (sad <= minSad) {
minSad = sad;
sadResult.dx = dx;
sadResult.dy = dy;
sadResult.sadValue = minSad;
}
}
}
return sadResult;
}
/**
* computes SAD centered on x,y with shift of dx,dy for prevSliceIdx
* relative to curSliceIdx patch.
*
* @param x coordinate in subSampled space
* @param y
* @param dx
* @param dy
* @param prevSliceIdx
* @param curSliceIdx
* @return SAD value
*/
private int sad(int x, int y, int dx, int dy, int[][] prevSlice, int[][] curSlice) {
// Make sure 0<=xx+dx<subSizeX, 0<=xx<subSizeX and 0<=yy+dy<subSizeY, 0<=yy<subSizeY, or there'll be arrayIndexOutOfBoundary exception.
if (x < patchDimension + dx || x >= subSizeX - patchDimension + dx || x < patchDimension || x >= subSizeX - patchDimension
|| y < patchDimension + dy || y >= subSizeY - patchDimension + dy || y < patchDimension || y >= subSizeY - patchDimension) {
return 0;
}
int sad = 0;
for (int xx = x - patchDimension; xx <= x + patchDimension; xx++) {
for (int yy = y - patchDimension; yy <= y + patchDimension; yy++) {
int d = prevSlice[xx][yy] - curSlice[xx + dx][yy + dy];
if (d <= 0) {
d = -d;
}
sad += d;
}
}
return sad;
}
//This uses fewer arithmetic operations than any other known
//implementation on machines with fast multiplication.
//It uses 12 arithmetic operations, one of which is a multiply.
public long popcount_3(long x) {
x -= (x >> 1) & m1; //put count of each 2 bits into those 2 bits
x = (x & m2) + ((x >> 2) & m2); //put count of each 4 bits into those 4 bits
x = (x + (x >> 4)) & m4; //put count of each 8 bits into those 8 bits
return (x * h01)>>56; //returns left 8 bits of x + (x<<8) + (x<<16) + (x<<24) + ...
}
private class SADResult {
float dx, dy;
float sadValue;
public SADResult(float dx, float dy, float sadValue) {
this.dx = dx;
this.dy = dy;
this.sadValue = sadValue;
}
@Override
public String toString() {
return String.format("dx,dy=%d,%5 SAD=%d",dx,dy,sadValue);
}
}
/**
* @return the patchDimension
*/
public int getPatchDimension() {
return patchDimension;
}
/**
* @param patchDimension the patchDimension to set
*/
public void setPatchDimension(int patchDimension) {
this.patchDimension = patchDimension;
putInt("patchDimension", patchDimension);
}
/**
* @return the sliceMethod
*/
public SliceMethod getSliceMethod() {
return sliceMethod;
}
/**
* @param sliceMethod the sliceMethod to set
*/
public void setSliceMethod(SliceMethod sliceMethod) {
this.sliceMethod = sliceMethod;
putString("sliceMethod", sliceMethod.toString());
}
public PatchCompareMethod getPatchCompareMethod() {
return patchCompareMethod;
}
public void setPatchCompareMethod(PatchCompareMethod patchCompareMethod) {
this.patchCompareMethod = patchCompareMethod;
putString("patchCompareMethod", patchCompareMethod.toString());
}
/**
* @return the sliceDurationUs
*/
public int getSliceDurationUs() {
return sliceDurationUs;
}
/**
* @param sliceDurationUs the sliceDurationUs to set
*/
public void setSliceDurationUs(int sliceDurationUs) {
this.sliceDurationUs = sliceDurationUs;
putInt("sliceDurationUs", sliceDurationUs);
}
public boolean isShowTransformRectangle() {
return showTransformRectangle;
}
public void setShowTransformRectangle(boolean showTransformRectangle) {
this.showTransformRectangle = showTransformRectangle;
}
public boolean isRemoveCameraMotion() {
return removeCameraMotion;
}
public void setRemoveCameraMotion(boolean removeCameraMotion) {
this.removeCameraMotion = removeCameraMotion;
}
/**
* @return the sliceEventCount
*/
public int getSliceEventCount() {
return sliceEventCount;
}
/**
* @param sliceEventCount the sliceEventCount to set
*/
public void setSliceEventCount(int sliceEventCount) {
this.sliceEventCount = sliceEventCount;
putInt("sliceEventCount", sliceEventCount);
}
public float getHighpassTauMsTranslation() {
return highpassTauMsTranslation;
}
public void setHighpassTauMsTranslation(float highpassTauMs) {
this.highpassTauMsTranslation = highpassTauMs;
putFloat("highpassTauMsTranslation", highpassTauMs);
panTranslationFilter.setTauMs(highpassTauMs);
tiltTranslationFilter.setTauMs(highpassTauMs);
}
public float getHighpassTauMsRotation() {
return highpassTauMsRotation;
}
public void setHighpassTauMsRotation(float highpassTauMs) {
this.highpassTauMsRotation = highpassTauMs;
putFloat("highpassTauMsRotation", highpassTauMs);
rollFilter.setTauMs(highpassTauMs);
}
public boolean isHighPassFilterEn() {
return highPassFilterEn;
}
public void setHighPassFilterEn(boolean highPassFilterEn) {
this.highPassFilterEn = highPassFilterEn;
putBoolean("highPassFilterEn", highPassFilterEn);
}
public boolean isMeasurePerformance() {
return measurePerformance;
}
public void setMeasurePerformance(boolean measurePerformance) {
this.measurePerformance = measurePerformance;
putBoolean("measurePerformance", measurePerformance);
}
public boolean isDisplayOutputVectors() {
return displayOutputVectors;
}
public void setDisplayOutputVectors(boolean displayOutputVectors) {
this.displayOutputVectors = displayOutputVectors;
putBoolean("displayOutputVectors", measurePerformance);
}
}
|
package com.anthavio.sink;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.rmi.RemoteException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.sql.DataSource;
/**
*
* @author martin.vanek
*
*/
public class GenericThrows {
public static void main(String[] args) {
StrategyContext context = new StrategyContext();
ReaderLoader readerLoader = new ReaderLoader(new StringReader("Blah! Blah! Blah!"));
try {
context.perform(readerLoader);
} catch (IOException iox) {
//ReaderLoader thrown IOException is propagated through StrategyContext and delivered here
} catch (ContextException cx) {
//StrategyContext thrown exception wrapper - All sorts of non ReaderLoader originated Exceptions
}
DataSource dataSource = null; //get it from somewhere
JdbcLoader jdbcLoader = new JdbcLoader(dataSource, "SELECT something FROM somewhere WHERE column = ?");
try {
context.perform(jdbcLoader);
} catch (InvalidRecordCountException ircx) {
//JdbcLoader thrown InvalidRecordCountException is propagated through StrategyContext and delivered here
long badRecordId = ircx.getRecordId(); //we can take some action when knowing failing record id
} catch (ContextException cx) {
//StrategyContext thrown exception wrapper - SQLException will be cause propably...
Throwable cause = cx.getCause();
}
}
}
/**
* Strategy interface - To be implemented by client
*/
interface LoaderStrategy<X extends Exception> {
public String load(long id) throws X;
}
/**
* Lazy but nice client can pick this LoaderStrategy subtype
*/
interface NiceLoaderStrategy extends LoaderStrategy<RuntimeException> {
@Override
public String load(long id);
}
/**
* Lazy and nasty client can pick this LoaderStrategy subtype
*/
interface NastyLoaderStrategy extends LoaderStrategy<Exception> {
@Override
public String load(long id) throws Exception;
}
/**
* Context exception wrapper - delivers other then LoaderStrategy exceptions to client
*/
class ContextException extends RuntimeException {
public ContextException(String string, Exception cause) {
super(string, cause);
}
}
/**
* Context using LoaderStrategy, passing selected exceptions (X)
*/
class StrategyContext {
public <X extends Exception> void perform(LoaderStrategy<X> loader) throws X {
long resourceId = getIdFromSomewhere();
String data = loader.load(resourceId); //throws X - don't have to hadle exception here
try {
sendDataToRemoteSystem(data);
} catch (RemoteException rx) {
//Other checked Exception must be wrapped inside ContextException
throw new ContextException("Failed to send data for resourceId " + resourceId, rx);
}
}
private long getIdFromSomewhere() {
return System.currentTimeMillis(); //CurrentTimeMillis is best id ever!
}
private void sendDataToRemoteSystem(String data) throws RemoteException {
//invoke some remoting operation here...
}
}
/**
* Client provided LoaderStrategy implementation throwing IOException
*/
class ReaderLoader implements LoaderStrategy<IOException> {
private Reader reader;
public ReaderLoader(Reader reader) {
this.reader = reader;
}
public String load(long id) throws IOException {
String sid = String.valueOf(id);
BufferedReader br = new BufferedReader(reader);
String line = null;
while ((line = br.readLine()) != null) {
if (line.startsWith(sid)) {
return line;
}
}
return null;
}
}
/**
* Client provided custom Exception
*/
class InvalidRecordCountException extends Exception {
private long recordId;
public InvalidRecordCountException(long recordId, String message) {
super(message);
this.recordId = recordId;
}
public InvalidRecordCountException(long recordId, SQLException exception) {
super(exception);
this.recordId = recordId;
}
public long getRecordId() {
return recordId;
}
}
/**
* Client provided LoaderStrategy implementation throwing custom InvalidRecordCountException
*/
class JdbcLoader implements LoaderStrategy<InvalidRecordCountException> {
private DataSource dataSource;
private String select;
public JdbcLoader(DataSource dataSource, String select) {
this.dataSource = dataSource;
this.select = select;
}
@Override
public String load(long id) throws InvalidRecordCountException {
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
try {
connection = dataSource.getConnection();
statement = connection.prepareStatement(select);
statement.setLong(1, id);
resultSet = statement.executeQuery();
if (resultSet.next()) {
String string = resultSet.getString(1);
if (resultSet.next()) {
//here we go...
throw new InvalidRecordCountException(id, "Too many somethings in somewhere!");
}
return string;
} else {
//here we go...
throw new InvalidRecordCountException(id, "Not a single something in somewhere!");
}
} catch (SQLException sqlx) {
//here we go...
throw new InvalidRecordCountException(id, sqlx);
} finally {
//TODO close resultSet, statement, connection
}
}
}
|
package com.forgeessentials.chat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.util.DamageSource;
import net.minecraftforge.common.config.Configuration;
import com.forgeessentials.core.ForgeEssentials;
import com.forgeessentials.core.moduleLauncher.config.ConfigLoader.ConfigLoaderBase;
import com.forgeessentials.util.OutputHandler;
import com.google.common.base.Strings;
public class Censor extends ConfigLoaderBase
{
private static final String CONFIG_CATEGORY = "Chat.Censor";
private static final String[] DEFAULT_WORDS = new String[] { "fuck", "ass", "bitch", "shit" };
public static List<String> bannedWords = new ArrayList<>();
public static Map<String, Pattern> bannedPatterns = new HashMap<>();
public boolean enabled;
public String censorSymbol;
public int censorSlap;
public Censor()
{
ForgeEssentials.getConfigManager().registerLoader(ModuleChat.CONFIG_FILE, this);
}
@Override
public void load(Configuration config, boolean isReload)
{
enabled = config.get(CONFIG_CATEGORY, "enable", true).getBoolean(true);
bannedWords = new ArrayList<>(Arrays.asList(config.get(CONFIG_CATEGORY, "words", DEFAULT_WORDS, "Words to be censored").getStringList()));
censorSlap = config.get(CONFIG_CATEGORY, "slapDamage", 1, "Damage to a player when he uses a censored word").getInt();
censorSymbol = config.get(CONFIG_CATEGORY, "censorSymbol", "#", "Replace censored words with this character").getString();
if (censorSymbol.length() > 1)
{
OutputHandler.felog.warning("Censor symbol is too long!");
censorSymbol = censorSymbol.substring(1);
}
else if (censorSymbol.isEmpty())
{
OutputHandler.felog.warning("Censor symbol is empty!");
censorSymbol = "
}
buildPatterns();
}
public void buildPatterns()
{
bannedPatterns.clear();
for (String word : bannedWords)
{
if (word.startsWith("!"))
word = word.substring(1);
else
word = "\\b" + word + "\\b";
bannedPatterns.put(Strings.repeat(censorSymbol, word.length()),
Pattern.compile(word, Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE | Pattern.MULTILINE));
}
}
public String filter(EntityPlayerMP player, String message)
{
if (!enabled)
return message;
for (Entry<String, Pattern> word : bannedPatterns.entrySet())
{
Matcher m = word.getValue().matcher(message);
if (m.find())
{
m.replaceAll(word.getKey());
if (censorSlap != 0)
player.attackEntityFrom(DamageSource.generic, censorSlap);
}
}
return message;
}
}
|
package com.intellij.openapi.diagnostic;
import com.intellij.util.ArrayUtil;
import com.intellij.util.ExceptionUtil;
import com.intellij.util.Function;
import com.intellij.util.containers.ContainerUtil;
import org.apache.log4j.Level;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.lang.reflect.Constructor;
public abstract class Logger {
public interface Factory {
@NotNull
Logger getLoggerInstance(@NotNull String category);
}
private static class DefaultFactory implements Factory {
@NotNull
@Override
public Logger getLoggerInstance(@NotNull String category) {
return new DefaultLogger(category);
}
}
private static Factory ourFactory = new DefaultFactory();
public static void setFactory(@NotNull Class<? extends Factory> factory) {
if (isInitialized()) {
if (factory.isInstance(ourFactory)) {
return;
}
//noinspection UseOfSystemOutOrSystemErr
System.out.println("Changing log factory\n" + ExceptionUtil.getThrowableText(new Throwable()));
}
try {
Constructor<? extends Factory> constructor = factory.getDeclaredConstructor();
constructor.setAccessible(true);
ourFactory = constructor.newInstance();
}
catch (Exception e) {
//noinspection CallToPrintStackTrace
e.printStackTrace();
throw new RuntimeException(e);
}
}
public static void setFactory(Factory factory) {
if (isInitialized()) {
//noinspection UseOfSystemOutOrSystemErr
System.out.println("Changing log factory\n" + ExceptionUtil.getThrowableText(new Throwable()));
}
ourFactory = factory;
}
public static Factory getFactory() {
return ourFactory;
}
public static boolean isInitialized() {
return !(ourFactory instanceof DefaultFactory);
}
@NotNull
public static Logger getInstance(@NotNull String category) {
return ourFactory.getLoggerInstance(category);
}
@NotNull
public static Logger getInstance(@NotNull Class cl) {
return getInstance("#" + cl.getName());
}
public abstract boolean isDebugEnabled();
public abstract void debug(String message);
public abstract void debug(@Nullable Throwable t);
public abstract void debug(String message, @Nullable Throwable t);
public void debug(@NotNull String message, @NotNull Object... details) {
if (isDebugEnabled()) {
StringBuilder sb = new StringBuilder();
sb.append(message);
for (Object detail : details) {
sb.append(detail);
}
debug(sb.toString());
}
}
public boolean isTraceEnabled() {
return isDebugEnabled();
}
/**
* Log a message with 'trace' level which finer-grained than 'debug' level. Use this method instead of {@link #debug(String)} for internal
* events of a subsystem to avoid overwhelming the log if 'debug' level is enabled.
*/
public void trace(String message) {
debug(message);
}
public void trace(@Nullable Throwable t) {
debug(t);
}
public void info(@NotNull Throwable t) {
info(t.getMessage(), t);
}
public abstract void info(String message);
public abstract void info(String message, @Nullable Throwable t);
public void warn(String message) {
warn(message, null);
}
public void warn(@NotNull Throwable t) {
warn(t.getMessage(), t);
}
public abstract void warn(String message, @Nullable Throwable t);
public void error(String message) {
error(message, new Throwable(message), ArrayUtil.EMPTY_STRING_ARRAY);
}
public void error(Object message) {
error(String.valueOf(message));
}
static final Function<Attachment, String> ATTACHMENT_TO_STRING = new Function<Attachment, String>() {
@Override
public String fun(Attachment attachment) {
return attachment.getPath() + "\n" + attachment.getDisplayText();
}
};
public void error(String message, @NotNull Attachment... attachments) {
error(message, null, attachments);
}
public void error(String message, @Nullable Throwable t, @NotNull Attachment... attachments) {
error(message, t, ContainerUtil.map2Array(attachments, String.class, ATTACHMENT_TO_STRING));
}
public void error(String message, @NotNull String... details) {
error(message, new Throwable(message), details);
}
public void error(String message, @Nullable Throwable t) {
error(message, t, ArrayUtil.EMPTY_STRING_ARRAY);
}
public void error(@NotNull Throwable t) {
error(t.getMessage(), t, ArrayUtil.EMPTY_STRING_ARRAY);
}
public abstract void error(String message, @Nullable Throwable t, @NotNull String... details);
@Contract("false,_->fail") // wrong, but avoid quite a few warnings in the code
public boolean assertTrue(boolean value, @Nullable Object message) {
if (!value) {
String resultMessage = "Assertion failed";
if (message != null) resultMessage += ": " + message;
error(resultMessage, new Throwable(resultMessage));
}
return value;
}
@Contract("false->fail") // wrong, but avoid quite a few warnings in the code
public boolean assertTrue(boolean value) {
//noinspection ConstantConditions
return value || assertTrue(false, null);
}
public abstract void setLevel(Level level);
protected static Throwable checkException(@Nullable Throwable t) {
return t instanceof ControlFlowException ? new Throwable("Control-flow exceptions should never be logged", t) : t;
}
}
|
package com.growthbeat.model;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.codehaus.jackson.type.TypeReference;
public class Credential extends Model {
private String id;
private Date created;
private Account account;
public static List<Credential> getByConnectionIdAndSecretService(String connectionId, String secretService) {
Map<String, Object> params = new HashMap<String, Object>();
params.put("connectionId", connectionId);
params.put("secretService", secretService);
List<Credential> credentials = get(1, "credentials", params, new TypeReference<List<Credential>>() {
});
return credentials;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public Account getAccount() {
return account;
}
public void setAccount(Account account) {
this.account = account;
}
}
|
package com.jaamsim.Graphics;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import com.jaamsim.DisplayModels.TextModel;
import com.jaamsim.controllers.RenderManager;
import com.jaamsim.input.InputAgent;
import com.jaamsim.input.Keyword;
import com.jaamsim.input.ValueInput;
import com.jaamsim.math.Transform;
import com.jaamsim.math.Vec3d;
import com.jaamsim.units.DistanceUnit;
import com.jogamp.newt.event.KeyEvent;
/**
* The "TextBasics" object displays text within the 3D model universe.
* @author Harry King
*
*/
public abstract class TextBasics extends DisplayEntity {
@Keyword(description = "The height of the font as displayed in the view window.",
exampleList = {"15 m"})
protected final ValueInput textHeight;
private boolean editMode = false; // true if the entity is being edited
private String savedText = ""; // saved text after editing is finished
private String editText = ""; // modified text as edited by the user
private int insertPos = 0; // position in the string where new text will be inserted
private int numSelected = 0; // number of characters selected (positive to the right of the insertion position)
{
textHeight = new ValueInput("TextHeight", "Key Inputs", 0.3d);
textHeight.setValidRange(0.0d, Double.POSITIVE_INFINITY);
textHeight.setUnitType(DistanceUnit.class);
this.addInput(textHeight);
}
public TextBasics() {}
public void setSavedText(String str) {
savedText = str;
editText = str;
}
public String getEditText() {
return editText;
}
private void deleteSelection() {
if (numSelected == 0)
return;
int start = Math.min(insertPos, insertPos+numSelected);
int end = Math.max(insertPos, insertPos+numSelected);
StringBuilder sb = new StringBuilder(editText);
editText = sb.delete(start, end).toString();
insertPos = start;
numSelected = 0;
}
private void setInsertPosition(int pos, boolean shift) {
if (shift)
numSelected -= pos - insertPos;
else
numSelected = 0;
insertPos = pos;
}
protected void acceptEdits() {
savedText = editText;
editMode = false;
insertPos = editText.length();
numSelected = 0;
}
protected void cancelEdits() {
editMode = false;
editText = savedText;
insertPos = editText.length();
numSelected = 0;
}
private void selectPresentWord() {
// Find the end of the present word
int end = editText.length();
for (int i=insertPos; i<editText.length(); i++) {
if (editText.charAt(i) == ' ') {
end = i + 1;
break;
}
}
// Find the start of the present word
int start = 0;
for (int i=insertPos-1; i>=0; i
if (editText.charAt(i) == ' ') {
start = i + 1;
break;
}
}
// Set the insert position and selection
insertPos = end;
numSelected = start - end;
}
private void copyToClipboard() {
Clipboard clpbrd = Toolkit.getDefaultToolkit().getSystemClipboard();
int start = Math.min(insertPos, insertPos+numSelected);
int end = Math.max(insertPos, insertPos+numSelected);
StringBuilder sb = new StringBuilder(editText);
String copiedText = sb.substring(start, end).toString();
clpbrd.setContents(new StringSelection(copiedText), null);
}
private void pasteFromClipboard() {
Clipboard clpbrd = Toolkit.getDefaultToolkit().getSystemClipboard();
try {
String newText = (String)clpbrd.getData(DataFlavor.stringFlavor);
StringBuilder sb = new StringBuilder(editText);
editText = sb.insert(insertPos, newText).toString();
insertPos += newText.length();
}
catch (Throwable err) {}
}
@Override
public void handleKeyPressed(int keyCode, char keyChar, boolean shift, boolean control, boolean alt) {
if (keyCode == KeyEvent.VK_F2) {
editMode = true;
insertPos = editText.length();
numSelected = 0;
RenderManager.redraw();
return;
}
if (!editMode) {
super.handleKeyPressed(keyCode, keyChar, shift, control, alt);
return;
}
switch (keyCode) {
case KeyEvent.VK_DELETE:
if (numSelected == 0) {
if (insertPos == editText.length())
break;
StringBuilder sb = new StringBuilder(editText);
editText = sb.deleteCharAt(insertPos).toString();
break;
}
deleteSelection();
break;
case KeyEvent.VK_BACK_SPACE:
if (numSelected == 0) {
if (insertPos == 0)
break;
StringBuilder sb = new StringBuilder(editText);
editText = sb.deleteCharAt(insertPos-1).toString();
insertPos
break;
}
deleteSelection();
break;
case KeyEvent.VK_LEFT:
if (!shift && !(numSelected == 0)) {
if (numSelected < 0)
setInsertPosition(insertPos + numSelected, shift);
else
setInsertPosition(insertPos, shift);
break;
}
setInsertPosition(Math.max(0, insertPos-1), shift);
break;
case KeyEvent.VK_RIGHT:
if (!shift && !(numSelected == 0)) {
if (numSelected > 0)
setInsertPosition(insertPos + numSelected, shift);
else
setInsertPosition(insertPos, shift);
break;
}
setInsertPosition(Math.min(editText.length(), insertPos+1), shift);
break;
case KeyEvent.VK_HOME:
setInsertPosition(0, shift);
break;
case KeyEvent.VK_END:
setInsertPosition(editText.length(), shift);
break;
case KeyEvent.VK_ENTER:
acceptEdits();
break;
case KeyEvent.VK_ESCAPE:
cancelEdits();
break;
case KeyEvent.VK_C:
if (control) {
copyToClipboard();
break;
}
case KeyEvent.VK_V:
if (control) {
deleteSelection();
pasteFromClipboard();
break;
}
case KeyEvent.VK_X:
if (control) {
copyToClipboard();
deleteSelection();
break;
}
default:
if (keyChar == KeyEvent.VK_UNDEFINED || control)
break;
deleteSelection();
StringBuilder sb = new StringBuilder(editText);
editText = sb.insert(insertPos, keyChar).toString();
insertPos++;
break;
}
RenderManager.redraw();
}
@Override
public void handleKeyReleased(int keyCode, char keyChar, boolean shift, boolean control, boolean alt) {
if (editMode)
return;
super.handleKeyReleased(keyCode, keyChar, shift, control, alt);
}
@Override
public void handleMouseClicked(short count, Vec3d globalCoord) {
if (count > 2)
return;
// Double click starts edit mode
if (count == 2)
editMode = true;
// Set up the transformation from global coordinates to the entity's coordinates
double height = textHeight.getValue();
TextModel tm = (TextModel) displayModelListInput.getValue().get(0);
Vec3d textsize = RenderManager.inst().getRenderedStringSize(tm.getTessFontKey(), height, editText);
Transform trans = getEntityTransForSize(textsize);
// Calculate the entity's coordinates for the mouse click
Vec3d entityCoord = new Vec3d();
trans.multAndTrans(globalCoord, entityCoord);
// Position the insertion point where the text was clicked
double insert = entityCoord.x + 0.5d*textsize.x;
insertPos = RenderManager.inst().getRenderedStringPosition(tm.getTessFontKey(), height, editText, insert);
numSelected = 0;
// Double click selects a whole word
if (count == 2)
selectPresentWord();
}
@Override
public boolean handleDrag(Vec3d currentPt, Vec3d firstPt) {
if (!editMode)
return false;
// Set up the transformation from global coordinates to the entity's coordinates
double height = textHeight.getValue();
TextModel tm = (TextModel) displayModelListInput.getValue().get(0);
Vec3d textsize = RenderManager.inst().getRenderedStringSize(tm.getTessFontKey(), height, editText);
Transform trans = getEntityTransForSize(textsize);
// Calculate the entity's coordinates for the mouse click
Vec3d currentCoord = new Vec3d();
trans.multAndTrans(currentPt, currentCoord);
Vec3d firstCoord = new Vec3d();
trans.multAndTrans(firstPt, firstCoord);
// Set the start and end of highlighting
double insert = currentCoord.x + 0.5d*textsize.x;
double first = firstCoord.x + 0.5d*textsize.x;
insertPos = RenderManager.inst().getRenderedStringPosition(tm.getTessFontKey(), height, editText, insert);
int firstPos = RenderManager.inst().getRenderedStringPosition(tm.getTessFontKey(), height, editText, first);
numSelected = firstPos - insertPos;
return true;
}
@Override
public void handleSelectionLost() {
if (editMode)
acceptEdits();
}
public String getCachedText() {
if (editMode)
return editText;
return savedText;
}
public double getTextHeight() {
return textHeight.getValue().doubleValue();
}
public Vec3d getTextSize() {
double height = textHeight.getValue();
TextModel tm = (TextModel) displayModelListInput.getValue().get(0);
return RenderManager.inst().getRenderedStringSize(tm.getTessFontKey(), height, savedText);
}
public void resizeForText() {
Vec3d textSize = getTextSize();
double length = textSize.x + textSize.y;
double height = 2.0 * textSize.y;
Vec3d newSize = new Vec3d(length, height, 0.0);
InputAgent.apply(this, InputAgent.formatPointInputs("Size", newSize, "m"));
}
public boolean isEditMode() {
return editMode;
}
public int getInsertPosition() {
return insertPos;
}
public int getNumberSelected() {
return numSelected;
}
}
|
package com.lfkdsk.justel.repl;
import com.lfkdsk.justel.ast.base.AstNode;
import com.lfkdsk.justel.compile.compiler.JustCompiler;
import com.lfkdsk.justel.compile.compiler.JustCompilerImpl;
import com.lfkdsk.justel.compile.generate.Generator;
import com.lfkdsk.justel.compile.generate.JavaCodeGenerator;
import com.lfkdsk.justel.compile.generate.JavaSource;
import com.lfkdsk.justel.context.JustContext;
import com.lfkdsk.justel.context.JustMapContext;
import com.lfkdsk.justel.eval.Expression;
import com.lfkdsk.justel.lexer.Lexer;
import com.lfkdsk.justel.parser.JustParser;
import jline.console.ConsoleReader;
import org.fusesource.jansi.Ansi;
import org.fusesource.jansi.AnsiConsole;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import static com.lfkdsk.justel.utils.FormatUtils.beautifulPrint;
import static com.lfkdsk.justel.utils.FormatUtils.insertNewLine;
import static com.lfkdsk.justel.utils.FormatUtils.reformatAstPrint;
import static org.fusesource.jansi.Ansi.ansi;
public class JustRepl {
static String logoStr =
"\n" +
" \n" +
" \n" +
" \n" +
" \n" +
" \n" +
" \n" +
" \n";
static final String help =
"-a show ast structure of this expr \n" +
"-e eval this expr \n" +
"-g generate java source code \n" +
"-c compile java source code [need -g] \n" +
"Just-REPL support assign(=) operator to set id-token's value, this grammar \n " +
"won't support in JustEL";
private static final String ANSI_RESET = "\u001B[0m";
private static final String ANSI_PURPLE = "\u001B[35m";
private static final String ANSI_CYAN = "\u001B[36m";
private static final String JUST_EL = "JustEL > ";
/**
* just-lexer
*/
private static Lexer lexer = new MockLexer(new BufferedReader(new InputStreamReader(System.in)));
private static JustParser parser = new MockParser();
/**
* just-compiler
*/
private static JustCompiler compiler = new JustCompilerImpl();
/**
* code-generator
*/
private static Generator generator = new JavaCodeGenerator();
private static boolean openAst = false;
private static boolean openMockEval = false;
private static boolean openMockCompile = false;
private static boolean openMockGenerate = false;
private static String cyanPrint(String msg) {
return ANSI_CYAN + msg + ANSI_RESET;
}
private static void resolveCommandFlag(String command, boolean flag) {
if (command.contains("a")) openAst = flag;
if (command.contains("e")) openMockEval = flag;
if (command.contains("c")) openMockCompile = flag;
if (command.contains("g")) openMockGenerate = flag;
}
private static boolean resolveCommandLine(String command) {
String trimCommand = command.trim();
if (trimCommand.startsWith("+")) {
resolveCommandFlag(trimCommand, true);
} else if (trimCommand.startsWith("-")) {
resolveCommandFlag(trimCommand, false);
} else {
return false;
}
return true;
}
private static void run() throws IOException {
ConsoleReader reader = new ConsoleReader();
reader.setHistoryEnabled(true);
String command;
JustContext env = new JustMapContext();
while ((command = reader.readLine(cyanPrint(JUST_EL))) != null) {
if (command.equals("")) continue;
else if (command.trim().equals("-q")) return;
else if (resolveCommandLine(command)) continue;
try {
lexer.reset(command);
lexer.hasMore();
AstNode node = parser.parser(lexer);
if (openAst) {
String reformat = reformatAstPrint(node.toString());
String[] args = {
"AST ---- Lisp Style",
insertNewLine(new StringBuilder(reformat), "\n", "").toString()
};
System.out.println(cyanPrint(beautifulPrint(args)));
}
if (openMockEval) {
String reformat = node.eval(env).toString();
String[] args = {
"Value ---- Eval",
insertNewLine(new StringBuilder(reformat), "\n", "\r\n").toString()
};
System.out.println(cyanPrint(beautifulPrint(args)));
}
if (openMockGenerate) {
generator.reset(env, node);
JavaSource javaSource = generator.generate();
System.out.println(cyanPrint(javaSource.toString()));
if (openMockCompile) {
long start = System.currentTimeMillis();
// save
Expression expr = compiler.compile(javaSource);
env.put(javaSource.className.toLowerCase(), expr);
AnsiConsole.out.println("Compile Time :" + (System.currentTimeMillis() - start + " ms"));
}
}
} catch (Throwable e) {
AnsiConsole.out.println(ansi().fgRed().a(JUST_EL + e.getMessage()).reset().toString());
}
}
}
public static void main(String[] args) throws Exception {
AnsiConsole.systemInstall();
// print logo & welcome ~
logoStr = logoStr.replace("", ansi().fg(Ansi.Color.GREEN).a("").reset().toString());
System.out.println(ansi().eraseScreen().render(logoStr));
System.out.println(ANSI_PURPLE + "Welcome to JustEL Debug Tools~~" + ANSI_RESET);
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
System.out.println("");
System.out.println(ANSI_PURPLE + "Have a nice Day~~" + ANSI_RESET);
}));
if (args.length < 1) {
System.out.println(ansi().fgBrightGreen().render(help).reset().toString());
return;
}
String type = args[0];
resolveCommandFlag(type, true);
run();
}
}
|
package maven_webapp_sample;
import java.util.ArrayList;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import javax.swing.plaf.synth.SynthSeparatorUI;
import org.joda.time.DateTime;
import org.junit.Test;
import com.kkdm.worker.service.WorkService;
import com.kkdm.worker.service.workers.GetInfoWorker;
import com.quya.core.utils.DateTimeUtils;
import com.quya.core.utils.MysqlUtils;
public class WorkServiceTest {
@Test
public void checkWorkTest(){
WorkService workService = new WorkService();
workService.checkWork();
}
@Test
public void getInfoWorkerTest(){
GetInfoWorker.getInstance().getInfo(null);
}
@Test
public void timerTest(){
System.out.println(DateTimeUtils.getYestoday());
// MysqlUtils.truncate("tbTopicTags");
}
@Test
public void brunchTest(){
System.out.println("dev brunch");
}
}
|
package com.maestrano.account;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import com.google.gson.Gson;
import com.maestrano.net.MnoApiAccountClient;
class MnoObject {
public Map<String,Object> changedAttributes;
public Map<String,Object> orginalAttributes;
public MnoObject() {
changedAttributes = new HashMap<String,Object>();
orginalAttributes = new HashMap<String,Object>();
}
public String toString() {
return MnoApiAccountClient.GSON.toJson(this);
}
protected void changeAttribute(String attrName, Object value) {
try {
Field f = this.getClass().getDeclaredField(attrName);
Object currentVal = f.get(this);
f.set(this,value);
if (this.orginalAttributes.get(attrName) == null) {
this.orginalAttributes.put(attrName, currentVal);
}
if (this.orginalAttributes.get(attrName) != null
&& this.orginalAttributes.get(attrName).equals(value)) {
this.changedAttributes.remove(attrName);
this.orginalAttributes.remove(attrName);
} else {
this.changedAttributes.put(attrName, value);
}
} catch (Exception e) {}
}
protected void merge(Object obj) {
Field[] fs = this.getClass().getDeclaredFields();
for (Field f : fs) {
try {
f.set(this,f.get(obj));
} catch (Exception e) {}
}
}
}
|
package mho.qbar.objects;
import mho.wheels.iterables.ExhaustiveProvider;
import mho.wheels.iterables.RandomProvider;
import mho.wheels.math.Combinatorics;
import mho.wheels.math.MathUtils;
import mho.wheels.misc.FloatingPointUtils;
import mho.wheels.misc.Readers;
import mho.wheels.ordering.Ordering;
import mho.wheels.structures.Pair;
import mho.wheels.structures.Triple;
import mho.qbar.iterableProviders.QBarExhaustiveProvider;
import mho.qbar.iterableProviders.QBarIterableProvider;
import mho.qbar.iterableProviders.QBarRandomProvider;
import org.jetbrains.annotations.NotNull;
import org.junit.Test;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.util.*;
import static mho.wheels.iterables.IterableUtils.*;
import static mho.wheels.ordering.Ordering.*;
import static mho.qbar.objects.Rational.*;
import static org.junit.Assert.*;
@SuppressWarnings("ConstantConditions")
public class RationalProperties {
private static boolean USE_RANDOM;
private static final String RATIONAL_CHARS = "-/0123456789";
private static final int SMALL_LIMIT = 1000;
private static final int MEDIUM_LIMIT = 3000;
private static int LIMIT;
private static QBarIterableProvider P;
private static void initialize() {
if (USE_RANDOM) {
P = new QBarRandomProvider(new Random(0x6af477d9a7e54fcaL));
LIMIT = 1000;
} else {
P = QBarExhaustiveProvider.INSTANCE;
LIMIT = 10000;
}
}
@Test
public void testAllProperties() {
System.out.println("Rational properties");
propertiesConstants();
for (boolean useRandom : Arrays.asList(false, true)) {
System.out.println("\ttesting " + (useRandom ? "randomly" : "exhaustively"));
USE_RANDOM = useRandom;
propertiesGetNumerator();
propertiesGetDenominator();
propertiesOf_BigInteger_BigInteger();
propertiesOf_long_long();
propertiesOf_int_int();
propertiesOf_BigInteger();
propertiesOf_long();
propertiesOf_int();
propertiesOf_float();
propertiesOf_double();
propertiesOfExact_float();
propertiesOfExact_double();
propertiesOf_BigDecimal();
propertiesIsInteger();
propertiesBigIntegerValue_RoundingMode();
propertiesBigIntegerValue();
propertiesBigIntegerValueExact();
propertiesByteValueExact();
propertiesShortValueExact();
propertiesIntValueExact();
propertiesLongValueExact();
propertiesHasTerminatingBaseExpansion();
propertiesBigDecimalValue_int_RoundingMode();
propertiesBigDecimalValue_int();
propertiesBigDecimalValueExact();
propertiesBinaryExponent();
propertiesFloatValue_RoundingMode();
propertiesFloatValue();
propertiesFloatValueExact();
propertiesDoubleValue_RoundingMode();
propertiesDoubleValue();
propertiesDoubleValueExact();
propertiesAdd();
propertiesNegate();
propertiesAbs();
propertiesSignum();
compareImplementationsAdd();
propertiesSubtract();
propertiesMultiply_Rational();
compareImplementationsMultiply_Rational();
propertiesMultiply_BigInteger();
compareImplementationsMultiply_BigInteger();
propertiesMultiply_int();
compareImplementationsMultiply_int();
propertiesInvert();
compareImplementationsInvert();
propertiesDivide_Rational();
compareImplementationsDivide_Rational();
propertiesDivide_BigInteger();
compareImplementationsDivide_BigInteger();
propertiesDivide_int();
compareImplementationsDivide_int();
propertiesSum();
compareImplementationsSum();
propertiesProduct();
compareImplementationsProduct();
propertiesDelta();
propertiesHarmonicNumber();
propertiesPow();
compareImplementationsPow();
propertiesFloor();
propertiesCeiling();
propertiesFractionalPart();
propertiesRoundToDenominator();
propertiesShiftLeft();
compareImplementationsShiftLeft();
propertiesShiftRight();
compareImplementationsShiftRight();
propertiesContinuedFraction();
propertiesFromContinuedFraction();
propertiesConvergents();
propertiesPositionalNotation();
propertiesFromPositionalNotation();
propertiesDigits();
compareImplementationsDigits();
propertiesToStringBase_BigInteger();
propertiesToStringBase_BigInteger_int();
propertiesFromStringBase();
propertiesCancelDenominators();
propertiesEquals();
propertiesHashCode();
propertiesCompareTo();
compareImplementationsCompareTo();
propertiesRead();
propertiesFindIn();
propertiesToString();
}
System.out.println("Done");
}
private static void propertiesConstants() {
initialize();
System.out.println("\ttesting constant properties...");
List<Rational> sample = toList(take(SMALL_LIMIT, HARMONIC_NUMBERS));
sample.forEach(mho.qbar.objects.RationalProperties::validate);
assertTrue(unique(sample));
assertTrue(increasing(sample));
assertTrue(all(r -> !r.isInteger(), tail(sample)));
try {
HARMONIC_NUMBERS.iterator().remove();
fail();
} catch (UnsupportedOperationException ignored) {}
}
private static void propertiesGetNumerator() {
initialize();
System.out.println("\t\ttesting getNumerator() properties...");
for (Rational r : take(LIMIT, P.rationals())) {
assertEquals(r.toString(), of(r.getNumerator(), r.getDenominator()), r);
}
}
private static void propertiesGetDenominator() {
initialize();
System.out.println("\t\ttesting getDenominator() properties...");
for (Rational r : take(LIMIT, P.rationals())) {
assertEquals(r.toString(), r.getDenominator().signum(), 1);
}
}
private static void propertiesOf_BigInteger_BigInteger() {
initialize();
System.out.println("\t\ttesting of(BigInteger, BigInteger) properties...");
Iterable<Pair<BigInteger, BigInteger>> ps = filter(
p -> !p.b.equals(BigInteger.ZERO),
P.pairs(P.bigIntegers())
);
for (Pair<BigInteger, BigInteger> p : take(LIMIT, ps)) {
Rational r = of(p.a, p.b);
validate(r);
assertEquals(p.toString(), of(p.a).divide(p.b), r);
}
for (BigInteger i : take(LIMIT, P.bigIntegers())) {
try {
of(i, BigInteger.ZERO);
fail(i.toString());
} catch (ArithmeticException ignored) {}
}
}
private static void propertiesOf_long_long() {
initialize();
System.out.println("\t\ttesting of(long, long) properties...");
BigInteger minLong = BigInteger.valueOf(Long.MIN_VALUE);
BigInteger maxLong = BigInteger.valueOf(Long.MAX_VALUE);
Iterable<Pair<Long, Long>> ps = filter(p -> p.b != 0, P.pairs(P.longs()));
for (Pair<Long, Long> p : take(LIMIT, ps)) {
Rational r = of(p.a, p.b);
validate(r);
assertEquals(p.toString(), of(p.a).divide(BigInteger.valueOf(p.b)), r);
assertTrue(p.toString(), ge(r.getNumerator(), minLong));
assertTrue(p.toString(), le(r.getNumerator(), maxLong));
assertTrue(p.toString(), ge(r.getDenominator(), minLong));
assertTrue(p.toString(), le(r.getDenominator(), maxLong));
}
for (long l : take(LIMIT, P.longs())) {
try {
of(l, 0L);
fail(Long.toString(l));
} catch (ArithmeticException ignored) {}
}
}
private static void propertiesOf_int_int() {
initialize();
System.out.println("\t\ttesting of(int, int) properties...");
BigInteger minInt = BigInteger.valueOf(Integer.MIN_VALUE);
BigInteger maxInt = BigInteger.valueOf(Integer.MAX_VALUE);
Iterable<Pair<Integer, Integer>> ps = filter(p -> p.b != 0, P.pairs(P.integers()));
for (Pair<Integer, Integer> p : take(LIMIT, ps)) {
Rational r = of(p.a, p.b);
validate(r);
assertEquals(p.toString(), of(p.a).divide(p.b), r);
assertTrue(p.toString(), ge(r.getNumerator(), minInt));
assertTrue(p.toString(), le(r.getNumerator(), maxInt));
assertTrue(p.toString(), ge(r.getDenominator(), minInt));
assertTrue(p.toString(), le(r.getDenominator(), maxInt));
}
for (int i : take(LIMIT, P.integers())) {
try {
of(i, 0);
fail(Integer.toString(i));
} catch (ArithmeticException ignored) {}
}
}
private static void propertiesOf_BigInteger() {
initialize();
System.out.println("\t\ttesting of(BigInteger) properties...");
for (BigInteger i : take(LIMIT, P.bigIntegers())) {
Rational r = of(i);
validate(r);
assertEquals(i.toString(), r.getDenominator(), BigInteger.ONE);
}
}
private static void propertiesOf_long() {
initialize();
System.out.println("\t\ttesting of(long) properties...");
BigInteger minLong = BigInteger.valueOf(Long.MIN_VALUE);
BigInteger maxLong = BigInteger.valueOf(Long.MAX_VALUE);
for (long l : take(LIMIT, P.longs())) {
Rational r = of(l);
validate(r);
assertEquals(Long.toString(l), r.getDenominator(), BigInteger.ONE);
assertTrue(Long.toString(l), ge(r.getNumerator(), minLong));
assertTrue(Long.toString(l), le(r.getNumerator(), maxLong));
}
}
private static void propertiesOf_int() {
initialize();
System.out.println("\t\ttesting of(int) properties...");
BigInteger minInt = BigInteger.valueOf(Integer.MIN_VALUE);
BigInteger maxInt = BigInteger.valueOf(Integer.MAX_VALUE);
for (int i : take(LIMIT, P.integers())) {
Rational r = of(i);
validate(r);
assertEquals(Integer.toString(i), r.getDenominator(), BigInteger.ONE);
assertTrue(Integer.toString(i), ge(r.getNumerator(), minInt));
assertTrue(Integer.toString(i), le(r.getNumerator(), maxInt));
}
}
private static void propertiesOf_float() {
initialize();
System.out.println("\t\ttesting of(float) properties...");
Iterable<Float> fs = filter(f -> Float.isFinite(f) && !Float.isNaN(f), P.floats());
for (float f : take(LIMIT, fs)) {
Rational r = of(f);
validate(r);
assertTrue(Float.toString(f), r.hasTerminatingBaseExpansion(BigInteger.valueOf(10)));
}
for (float f : take(LIMIT, P.ordinaryFloats())) {
Rational r = of(f);
aeq(Float.toString(f), f, r.floatValue());
aeq(Float.toString(f), new BigDecimal(Float.toString(f)), r.bigDecimalValueExact());
}
}
private static void propertiesOf_double() {
initialize();
System.out.println("\t\ttesting of(double) properties...");
Iterable<Double> ds = filter(d -> Double.isFinite(d) && !Double.isNaN(d), P.doubles());
for (double d : take(LIMIT, ds)) {
Rational r = of(d);
validate(r);
assertTrue(Double.toString(d), r.hasTerminatingBaseExpansion(BigInteger.valueOf(10)));
}
for (double d : take(LIMIT, P.ordinaryDoubles())) {
Rational r = of(d);
aeq(Double.toString(d), d, r.doubleValue());
aeq(Double.toString(d), new BigDecimal(Double.toString(d)), r.bigDecimalValueExact());
}
}
private static void propertiesOfExact_float() {
initialize();
System.out.println("\t\ttesting ofExact(float) properties...");
BigInteger denominatorLimit = BigInteger.ONE.shiftLeft(149);
BigInteger numeratorLimit = BigInteger.ONE.shiftLeft(128).subtract(BigInteger.ONE.shiftLeft(104));
Iterable<Float> fs = filter(f -> Float.isFinite(f) && !Float.isNaN(f), P.floats());
for (float f : take(LIMIT, fs)) {
Rational r = ofExact(f);
validate(r);
assertTrue(Float.toString(f), MathUtils.isAPowerOfTwo(r.getDenominator()));
assertTrue(Float.toString(f), le(r.getDenominator(), denominatorLimit));
assertTrue(Float.toString(f), le(r.getNumerator(), numeratorLimit));
}
for (float f : take(LIMIT, P.ordinaryFloats())) {
Rational r = ofExact(f);
aeq(Float.toString(f), f, r.floatValue());
}
}
private static void propertiesOfExact_double() {
initialize();
System.out.println("\t\ttesting ofExact(double) properties...");
BigInteger denominatorLimit = BigInteger.ONE.shiftLeft(1074);
BigInteger numeratorLimit = BigInteger.ONE.shiftLeft(1024).subtract(BigInteger.ONE.shiftLeft(971));
Iterable<Double> ds = filter(d -> Double.isFinite(d) && !Double.isNaN(d), P.doubles());
for (double d : take(LIMIT, ds)) {
Rational r = ofExact(d);
validate(r);
assertTrue(Double.toString(d), MathUtils.isAPowerOfTwo(r.getDenominator()));
assertTrue(Double.toString(d), le(r.getDenominator(), denominatorLimit));
assertTrue(Double.toString(d), le(r.getNumerator(), numeratorLimit));
}
for (double d : take(LIMIT, P.ordinaryDoubles())) {
Rational r = ofExact(d);
aeq(Double.toString(d), d, r.doubleValue());
}
}
private static void propertiesOf_BigDecimal() {
initialize();
System.out.println("\t\ttesting of(BigDecimal) properties...");
for (BigDecimal bd : take(LIMIT, P.bigDecimals())) {
Rational r = of(bd);
validate(r);
aeq(bd.toString(), bd, r.bigDecimalValueExact());
assertTrue(bd.toString(), r.hasTerminatingBaseExpansion(BigInteger.valueOf(10)));
}
}
private static void propertiesIsInteger() {
initialize();
System.out.println("\t\ttesting isInteger() properties...");
for (Rational r : take(LIMIT, P.rationals())) {
assertEquals(r.toString(), r.isInteger(), of(r.floor()).equals(r));
}
for (BigInteger i : take(LIMIT, P.bigIntegers())) {
assertTrue(of(i).isInteger());
}
}
private static void propertiesBigIntegerValue_RoundingMode() {
initialize();
System.out.println("\t\ttesting bigIntegerValue(RoundingMode) properties...");
Iterable<Pair<Rational, RoundingMode>> ps = filter(
p -> p.b != RoundingMode.UNNECESSARY || p.a.isInteger(),
P.pairs(P.rationals(), P.roundingModes())
);
for (Pair<Rational, RoundingMode> p : take(LIMIT, ps)) {
BigInteger rounded = p.a.bigIntegerValue(p.b);
assertTrue(p.toString(), rounded.equals(BigInteger.ZERO) || rounded.signum() == p.a.signum());
assertTrue(p.toString(), lt(p.a.subtract(of(rounded)).abs(), ONE));
}
for (BigInteger i : take(LIMIT, P.bigIntegers())) {
assertEquals(i.toString(), of(i).bigIntegerValue(RoundingMode.UNNECESSARY), i);
}
for (Rational r : take(LIMIT, P.rationals())) {
assertEquals(r.toString(), r.bigIntegerValue(RoundingMode.FLOOR), r.floor());
assertEquals(r.toString(), r.bigIntegerValue(RoundingMode.CEILING), r.ceiling());
assertTrue(r.toString(), le(of(r.bigIntegerValue(RoundingMode.DOWN)).abs(), r.abs()));
assertTrue(r.toString(), ge(of(r.bigIntegerValue(RoundingMode.UP)).abs(), r.abs()));
assertTrue(r.toString(), le(r.subtract(of(r.bigIntegerValue(RoundingMode.HALF_DOWN))).abs(), of(1, 2)));
assertTrue(r.toString(), le(r.subtract(of(r.bigIntegerValue(RoundingMode.HALF_UP))).abs(), of(1, 2)));
assertTrue(r.toString(), le(r.subtract(of(r.bigIntegerValue(RoundingMode.HALF_EVEN))).abs(), of(1, 2)));
}
Iterable<Rational> rs = filter(r -> lt(r.abs().fractionalPart(), of(1, 2)), P.rationals());
for (Rational r : take(LIMIT, rs)) {
assertEquals(r.toString(), r.bigIntegerValue(RoundingMode.HALF_DOWN), r.bigIntegerValue(RoundingMode.DOWN));
assertEquals(r.toString(), r.bigIntegerValue(RoundingMode.HALF_UP), r.bigIntegerValue(RoundingMode.DOWN));
assertEquals(r.toString(), r.bigIntegerValue(RoundingMode.HALF_EVEN), r.bigIntegerValue(RoundingMode.DOWN));
}
rs = filter(r -> gt(r.abs().fractionalPart(), of(1, 2)), P.rationals());
for (Rational r : take(LIMIT, rs)) {
assertEquals(r.toString(), r.bigIntegerValue(RoundingMode.HALF_DOWN), r.bigIntegerValue(RoundingMode.UP));
assertEquals(r.toString(), r.bigIntegerValue(RoundingMode.HALF_UP), r.bigIntegerValue(RoundingMode.UP));
assertEquals(r.toString(), r.bigIntegerValue(RoundingMode.HALF_EVEN), r.bigIntegerValue(RoundingMode.UP));
}
//odd multiples of 1/2
rs = map(i -> of(i.shiftLeft(1).add(BigInteger.ONE), BigInteger.valueOf(2)), P.bigIntegers());
for (Rational r : take(LIMIT, rs)) {
assertEquals(
r.toString(),
r.bigIntegerValue(RoundingMode.HALF_DOWN),
r.bigIntegerValue(RoundingMode.DOWN))
;
assertEquals(r.toString(), r.bigIntegerValue(RoundingMode.HALF_UP), r.bigIntegerValue(RoundingMode.UP));
assertFalse(r.toString(), r.bigIntegerValue(RoundingMode.HALF_EVEN).testBit(0));
}
for (Rational r : take(LIMIT, filter(s -> !s.isInteger(), P.rationals()))) {
try {
r.bigIntegerValue(RoundingMode.UNNECESSARY);
fail(r.toString());
} catch (ArithmeticException ignored) {}
}
}
private static void propertiesBigIntegerValue() {
initialize();
System.out.println("\t\ttesting bigIntegerValue() properties...");
for (Rational r : take(LIMIT, P.rationals())) {
BigInteger rounded = r.bigIntegerValue();
assertTrue(r.toString(), rounded.equals(BigInteger.ZERO) || rounded.signum() == r.signum());
assertTrue(r.toString(), le(r.subtract(of(r.bigIntegerValue())).abs(), of(1, 2)));
}
Iterable<Rational> rs = filter(r -> lt(r.abs().fractionalPart(), of(1, 2)), P.rationals());
for (Rational r : take(LIMIT, rs)) {
assertEquals(r.toString(), r.bigIntegerValue(), r.bigIntegerValue(RoundingMode.DOWN));
}
rs = filter(r -> gt(r.abs().fractionalPart(), of(1, 2)), P.rationals());
for (Rational r : take(LIMIT, rs)) {
assertEquals(r.toString(), r.bigIntegerValue(), r.bigIntegerValue(RoundingMode.UP));
}
//odd multiples of 1/2
rs = map(i -> of(i.shiftLeft(1).add(BigInteger.ONE), BigInteger.valueOf(2)), P.bigIntegers());
for (Rational r : take(LIMIT, rs)) {
assertFalse(r.toString(), r.bigIntegerValue().testBit(0));
}
}
private static void propertiesBigIntegerValueExact() {
initialize();
System.out.println("\t\ttesting bigIntegerValueExact() properties...");
for (BigInteger i : take(LIMIT, P.bigIntegers())) {
assertEquals(i.toString(), of(i).bigIntegerValueExact(), i);
}
for (Rational r : take(LIMIT, filter(s -> !s.isInteger(), P.rationals()))) {
try {
r.bigIntegerValueExact();
fail(r.toString());
} catch (ArithmeticException ignored) {}
}
}
private static void propertiesByteValueExact() {
initialize();
System.out.println("\t\ttesting byteValueExact() properties...");
for (byte b : take(LIMIT, P.bytes())) {
assertEquals(Byte.toString(b), of(b).byteValueExact(), b);
}
for (Rational r : take(LIMIT, filter(s -> !s.isInteger(), P.rationals()))) {
try {
r.byteValueExact();
fail(r.toString());
} catch (ArithmeticException ignored) {}
}
for (BigInteger i : take(LIMIT, P.rangeUp(BigInteger.valueOf(Byte.MAX_VALUE).add(BigInteger.ONE)))) {
try {
of(i).byteValueExact();
fail(i.toString());
} catch (ArithmeticException ignored) {}
}
Iterable<BigInteger> below = rangeBy(
BigInteger.valueOf(Byte.MIN_VALUE).subtract(BigInteger.ONE),
BigInteger.valueOf(-1)
);
for (BigInteger i : take(LIMIT, below)) {
try {
of(i).byteValueExact();
fail(i.toString());
} catch (ArithmeticException ignored) {}
}
}
private static void propertiesShortValueExact() {
initialize();
System.out.println("\t\ttesting shortValueExact() properties...");
for (short s : take(LIMIT, P.shorts())) {
assertEquals(Short.toString(s), of(s).shortValueExact(), s);
}
for (Rational r : take(LIMIT, filter(s -> !s.isInteger(), P.rationals()))) {
try {
r.shortValueExact();
fail(r.toString());
} catch (ArithmeticException ignored) {}
}
for (BigInteger i : take(LIMIT, P.rangeUp(BigInteger.valueOf(Short.MAX_VALUE).add(BigInteger.ONE)))) {
try {
of(i).shortValueExact();
fail(i.toString());
} catch (ArithmeticException ignored) {}
}
Iterable<BigInteger> below = rangeBy(
BigInteger.valueOf(Short.MIN_VALUE).subtract(BigInteger.ONE),
BigInteger.valueOf(-1)
);
for (BigInteger i : take(LIMIT, below)) {
try {
of(i).shortValueExact();
fail(i.toString());
} catch (ArithmeticException ignored) {}
}
}
private static void propertiesIntValueExact() {
initialize();
System.out.println("\t\ttesting intValueExact() properties...");
for (int i : take(LIMIT, P.integers())) {
assertEquals(Integer.toString(i), of(i).intValueExact(), i);
}
for (Rational r : take(LIMIT, filter(s -> !s.isInteger(), P.rationals()))) {
try {
r.intValueExact();
fail(r.toString());
} catch (ArithmeticException ignored) {}
}
for (BigInteger i : take(LIMIT, P.rangeUp(BigInteger.valueOf(Integer.MAX_VALUE).add(BigInteger.ONE)))) {
try {
of(i).intValueExact();
fail(i.toString());
} catch (ArithmeticException ignored) {}
}
Iterable<BigInteger> below = rangeBy(
BigInteger.valueOf(Integer.MIN_VALUE).subtract(BigInteger.ONE),
BigInteger.valueOf(-1)
);
for (BigInteger i : take(LIMIT, below)) {
try {
of(i).intValueExact();
fail(i.toString());
} catch (ArithmeticException ignored) {}
}
}
private static void propertiesLongValueExact() {
initialize();
System.out.println("\t\ttesting longValueExact() properties...");
for (long l : take(LIMIT, P.longs())) {
assertEquals(Long.toString(l), of(l).longValueExact(), l);
}
for (Rational r : take(LIMIT, filter(s -> !s.isInteger(), P.rationals()))) {
try {
r.longValueExact();
fail(r.toString());
} catch (ArithmeticException ignored) {}
}
for (BigInteger i : take(LIMIT, P.rangeUp(BigInteger.valueOf(Long.MAX_VALUE).add(BigInteger.ONE)))) {
try {
of(i).longValueExact();
fail(i.toString());
} catch (ArithmeticException ignored) {}
}
Iterable<BigInteger> below = rangeBy(
BigInteger.valueOf(Long.MIN_VALUE).subtract(BigInteger.ONE),
BigInteger.valueOf(-1)
);
for (BigInteger i : take(LIMIT, below)) {
try {
of(i).longValueExact();
fail(i.toString());
} catch (ArithmeticException ignored) {}
}
}
private static void propertiesHasTerminatingBaseExpansion() {
initialize();
System.out.println("\t\ttesting hasTerminatingBaseExpansion(BigInteger) properties...");
Iterable<Pair<Rational, BigInteger>> ps;
if (P instanceof ExhaustiveProvider) {
ps = ((ExhaustiveProvider) P).pairsSquareRootOrder(
cons(ZERO, P.positiveRationals()),
P.rangeUp(BigInteger.valueOf(2))
);
} else {
ps = P.pairs(
cons(ZERO, ((QBarRandomProvider) P).positiveRationals(20)),
map(i -> BigInteger.valueOf(i + 2), ((RandomProvider) P).naturalIntegersGeometric(20))
);
}
for (Pair<Rational, BigInteger> p : take(LIMIT, ps)) {
boolean result = p.a.hasTerminatingBaseExpansion(p.b);
Iterable<BigInteger> dPrimeFactors = nub(MathUtils.primeFactors(p.a.getDenominator()));
Iterable<BigInteger> bPrimeFactors = nub(MathUtils.primeFactors(p.b));
assertEquals(p.toString(), result, isSubsetOf(dPrimeFactors, bPrimeFactors));
}
if (!(P instanceof ExhaustiveProvider)) {
ps = P.pairs(
cons(ZERO, ((QBarRandomProvider) P).positiveRationals(8)),
map(i -> BigInteger.valueOf(i + 2), ((RandomProvider) P).naturalIntegersGeometric(20))
);
}
for (Pair<Rational, BigInteger> p : take(LIMIT, ps)) {
boolean result = p.a.hasTerminatingBaseExpansion(p.b);
Triple<List<BigInteger>, List<BigInteger>, List<BigInteger>> pn = p.a.positionalNotation(p.b);
assertEquals(p.toString(), result, pn.c.equals(Arrays.asList(BigInteger.ZERO)));
}
for (Pair<Rational, BigInteger> p : take(LIMIT, P.pairs(P.rationals(), P.rangeDown(BigInteger.ONE)))) {
try {
p.a.hasTerminatingBaseExpansion(p.b);
fail(p.toString());
} catch (IllegalArgumentException ignored) {}
}
}
private static void propertiesBigDecimalValue_int_RoundingMode() {
initialize();
System.out.println("\t\ttesting bigDecimalValue(int, RoundingMode)...");
Iterable<Pair<Rational, Pair<Integer, RoundingMode>>> ps;
if (P instanceof ExhaustiveProvider) {
ps = P.pairs(
P.rationals(),
(Iterable<Pair<Integer, RoundingMode>>) P.pairs(P.naturalIntegers(), P.roundingModes())
);
} else {
ps = P.pairs(
P.rationals(),
(Iterable<Pair<Integer, RoundingMode>>) P.pairs(
((RandomProvider) P).naturalIntegersGeometric(20),
P.roundingModes()
)
);
}
ps = filter(
p -> {
try {
p.a.bigDecimalValue(p.b.a, p.b.b);
return true;
} catch (ArithmeticException e) {
return false;
}
},
ps
);
for (Pair<Rational, Pair<Integer, RoundingMode>> p : take(LIMIT, ps)) {
BigDecimal bd = p.a.bigDecimalValue(p.b.a, p.b.b);
assertTrue(p.toString(), eq(bd, BigDecimal.ZERO) || bd.signum() == p.a.signum());
}
for (Pair<Rational, Pair<Integer, RoundingMode>> p : take(LIMIT, filter(q -> q.b.a != 0 && q.a != ZERO, ps))) {
BigDecimal bd = p.a.bigDecimalValue(p.b.a, p.b.b);
assertTrue(p.toString(), bd.precision() == p.b.a);
}
Iterable<Pair<Rational, Integer>> pris;
if (P instanceof ExhaustiveProvider) {
pris = ((ExhaustiveProvider) P).pairsSquareRootOrder(P.rationals(), P.naturalIntegers());
} else {
pris = P.pairs(P.rationals(), ((RandomProvider) P).naturalIntegersGeometric(20));
}
pris = filter(
p -> {
try {
p.a.bigDecimalValue(p.b);
return true;
} catch (ArithmeticException e) {
return false;
}
},
pris
);
Iterable<Pair<Rational, Integer>> priExact = filter(p -> of(p.a.bigDecimalValue(p.b)).equals(p.a), pris);
for (Pair<Rational, Integer> pri : take(LIMIT, priExact)) {
BigDecimal bd = pri.a.bigDecimalValue(pri.b, RoundingMode.UNNECESSARY);
assertEquals(pri.toString(), bd, pri.a.bigDecimalValue(pri.b, RoundingMode.FLOOR));
assertEquals(pri.toString(), bd, pri.a.bigDecimalValue(pri.b, RoundingMode.CEILING));
assertEquals(pri.toString(), bd, pri.a.bigDecimalValue(pri.b, RoundingMode.DOWN));
assertEquals(pri.toString(), bd, pri.a.bigDecimalValue(pri.b, RoundingMode.UP));
assertEquals(pri.toString(), bd, pri.a.bigDecimalValue(pri.b, RoundingMode.HALF_DOWN));
assertEquals(pri.toString(), bd, pri.a.bigDecimalValue(pri.b, RoundingMode.HALF_UP));
assertEquals(pri.toString(), bd, pri.a.bigDecimalValue(pri.b, RoundingMode.HALF_EVEN));
}
Iterable<Pair<Rational, Integer>> priInexact = filter(p -> !of(p.a.bigDecimalValue(p.b)).equals(p.a), pris);
for (Pair<Rational, Integer> pri : take(LIMIT, priInexact)) {
BigDecimal low = pri.a.bigDecimalValue(pri.b, RoundingMode.FLOOR);
BigDecimal high = pri.a.bigDecimalValue(pri.b, RoundingMode.CEILING);
assertTrue(pri.toString(), lt(low, high));
}
for (Pair<Rational, Integer> pri : take(LIMIT, filter(p -> p.a.signum() == 1, priInexact))) {
BigDecimal floor = pri.a.bigDecimalValue(pri.b, RoundingMode.FLOOR);
BigDecimal down = pri.a.bigDecimalValue(pri.b, RoundingMode.DOWN);
BigDecimal ceiling = pri.a.bigDecimalValue(pri.b, RoundingMode.CEILING);
BigDecimal up = pri.a.bigDecimalValue(pri.b, RoundingMode.UP);
assertEquals(pri.toString(), floor, down);
assertEquals(pri.toString(), ceiling, up);
}
for (Pair<Rational, Integer> pri : take(LIMIT, filter(p -> p.a.signum() == -1, priInexact))) {
BigDecimal floor = pri.a.bigDecimalValue(pri.b, RoundingMode.FLOOR);
BigDecimal down = pri.a.bigDecimalValue(pri.b, RoundingMode.DOWN);
BigDecimal ceiling = pri.a.bigDecimalValue(pri.b, RoundingMode.CEILING);
BigDecimal up = pri.a.bigDecimalValue(pri.b, RoundingMode.UP);
assertEquals(pri.toString(), floor, up);
assertEquals(pri.toString(), ceiling, down);
}
Iterable<Pair<BigDecimal, Integer>> notMidpoints;
if (P instanceof ExhaustiveProvider) {
notMidpoints = ((ExhaustiveProvider) P).pairsSquareRootOrder(P.bigDecimals(), P.naturalIntegers());
} else {
notMidpoints = P.pairs(P.bigDecimals(), ((RandomProvider) P).naturalIntegersGeometric(20));
}
notMidpoints = filter(
p -> {
//noinspection SimplifiableIfStatement
if (p.a.precision() <= 1 || p.b != p.a.precision() - 1) return false;
return !p.a.abs().unscaledValue().mod(BigInteger.valueOf(10)).equals(BigInteger.valueOf(5));
},
notMidpoints
);
for (Pair<BigDecimal, Integer> p : take(LIMIT, notMidpoints)) {
Rational r = of(p.a);
BigDecimal down = r.bigDecimalValue(p.b, RoundingMode.DOWN);
BigDecimal up = r.bigDecimalValue(p.b, RoundingMode.UP);
BigDecimal halfDown = r.bigDecimalValue(p.b, RoundingMode.HALF_DOWN);
BigDecimal halfUp = r.bigDecimalValue(p.b, RoundingMode.HALF_UP);
BigDecimal halfEven = r.bigDecimalValue(p.b, RoundingMode.HALF_EVEN);
boolean closerToDown = lt(r.subtract(of(down)).abs(), r.subtract(of(up)).abs());
assertEquals(p.toString(), halfDown, closerToDown ? down : up);
assertEquals(p.toString(), halfUp, closerToDown ? down : up);
assertEquals(p.toString(), halfEven, closerToDown ? down : up);
}
Iterable<BigDecimal> midpoints = filter(
x -> x.precision() > 1,
map(
x -> new BigDecimal(
x.unscaledValue().multiply(BigInteger.TEN).add(BigInteger.valueOf(5)),
x.scale()
),
P.bigDecimals()
)
);
for (BigDecimal bd : take(LIMIT, midpoints)) {
Rational r = of(bd);
int precision = bd.precision() - 1;
BigDecimal down = r.bigDecimalValue(precision, RoundingMode.DOWN);
BigDecimal up = r.bigDecimalValue(precision, RoundingMode.UP);
BigDecimal halfDown = r.bigDecimalValue(precision, RoundingMode.HALF_DOWN);
BigDecimal halfUp = r.bigDecimalValue(precision, RoundingMode.HALF_UP);
BigDecimal halfEven = r.bigDecimalValue(precision, RoundingMode.HALF_EVEN);
assertEquals(bd.toString(), down, halfDown);
assertEquals(bd.toString(), up, halfUp);
assertTrue(bd.toString(), bd.scale() != halfEven.scale() + 1 || !halfEven.unscaledValue().testBit(0));
}
Iterable<Pair<Rational, Pair<Integer, RoundingMode>>> psFail = P.pairs(
P.rationals(),
(Iterable<Pair<Integer, RoundingMode>>) P.pairs(P.negativeIntegers(), P.roundingModes())
);
for (Pair<Rational, Pair<Integer, RoundingMode>> p : take(LIMIT, psFail)) {
try {
p.a.bigDecimalValue(p.b.a, p.b.b);
fail(p.toString());
} catch (IllegalArgumentException ignored) {}
}
Iterable<Rational> rs = filter(r -> !r.hasTerminatingBaseExpansion(BigInteger.valueOf(10)), P.rationals());
Iterable<Pair<Rational, Integer>> prisFail;
if (P instanceof ExhaustiveProvider) {
prisFail = ((ExhaustiveProvider) P).pairsSquareRootOrder(rs, P.naturalIntegers());
} else {
prisFail = P.pairs(rs, ((RandomProvider) P).naturalIntegersGeometric(20));
}
for (Pair<Rational, Integer> p : take(LIMIT, prisFail)) {
try {
p.a.bigDecimalValue(p.b, RoundingMode.UNNECESSARY);
fail(p.toString());
} catch (ArithmeticException ignored) {}
}
}
private static void propertiesBigDecimalValue_int() {
initialize();
System.out.println("\t\ttesting bigDecimalValue(int)...");
Iterable<Pair<Rational, Integer>> ps;
if (P instanceof ExhaustiveProvider) {
ps = ((ExhaustiveProvider) P).pairsSquareRootOrder(P.rationals(), P.naturalIntegers());
} else {
ps = P.pairs(P.rationals(), ((RandomProvider) P).naturalIntegersGeometric(20));
}
ps = filter(
p -> {
try {
p.a.bigDecimalValue(p.b);
return true;
} catch (ArithmeticException e) {
return false;
}
},
ps
);
for (Pair<Rational, Integer> p : take(LIMIT, ps)) {
BigDecimal bd = p.a.bigDecimalValue(p.b);
assertEquals(p.toString(), bd, p.a.bigDecimalValue(p.b, RoundingMode.HALF_EVEN));
assertTrue(p.toString(), eq(bd, BigDecimal.ZERO) || bd.signum() == p.a.signum());
}
for (Pair<Rational, Integer> p : take(LIMIT, filter(q -> q.b != 0 && q.a != ZERO, ps))) {
BigDecimal bd = p.a.bigDecimalValue(p.b);
assertTrue(p.toString(), bd.precision() == p.b);
}
Iterable<Pair<BigDecimal, Integer>> notMidpoints;
if (P instanceof ExhaustiveProvider) {
notMidpoints = ((ExhaustiveProvider) P).pairsSquareRootOrder(P.bigDecimals(), P.naturalIntegers());
} else {
notMidpoints = P.pairs(P.bigDecimals(), ((RandomProvider) P).naturalIntegersGeometric(20));
}
notMidpoints = filter(
p -> {
//noinspection SimplifiableIfStatement
if (p.a.precision() <= 1 || p.b != p.a.precision() - 1) return false;
return !p.a.abs().unscaledValue().mod(BigInteger.valueOf(10)).equals(BigInteger.valueOf(5));
},
notMidpoints
);
for (Pair<BigDecimal, Integer> p : take(LIMIT, notMidpoints)) {
Rational r = of(p.a);
BigDecimal down = r.bigDecimalValue(p.b, RoundingMode.DOWN);
BigDecimal up = r.bigDecimalValue(p.b, RoundingMode.UP);
BigDecimal halfEven = r.bigDecimalValue(p.b);
boolean closerToDown = lt(r.subtract(of(down)).abs(), r.subtract(of(up)).abs());
assertEquals(p.toString(), halfEven, closerToDown ? down : up);
}
Iterable<BigDecimal> midpoints = filter(
x -> x.precision() > 1,
map(
x -> new BigDecimal(
x.unscaledValue().multiply(BigInteger.TEN).add(BigInteger.valueOf(5)),
x.scale()
),
P.bigDecimals()
)
);
for (BigDecimal bd : take(LIMIT, midpoints)) {
Rational r = of(bd);
int precision = bd.precision() - 1;
BigDecimal halfEven = r.bigDecimalValue(precision);
assertTrue(bd.toString(), bd.scale() != halfEven.scale() + 1 || !halfEven.unscaledValue().testBit(0));
}
for (Pair<Rational, Integer> p : take(LIMIT, P.pairs(P.rationals(), P.negativeIntegers()))) {
try {
p.a.bigDecimalValue(p.b);
fail(p.toString());
} catch (IllegalArgumentException ignored) {}
}
}
private static void propertiesBigDecimalValueExact() {
initialize();
System.out.println("\t\ttesting bigDecimalValueExact()...");
Iterable<Rational> rs = filter(r -> r.hasTerminatingBaseExpansion(BigInteger.valueOf(10)), P.rationals());
for (Rational r : take(LIMIT, rs)) {
BigDecimal bd = r.bigDecimalValueExact();
assertEquals(r.toString(), bd, r.bigDecimalValue(0, RoundingMode.UNNECESSARY));
assertTrue(r.toString(), eq(bd, BigDecimal.ZERO) || bd.signum() == r.signum());
assertEquals(r.toString(), of(bd), r);
}
for (Pair<Rational, Integer> p : take(LIMIT, P.pairs(P.rationals(), P.negativeIntegers()))) {
try {
p.a.bigDecimalValue(p.b);
fail(p.toString());
} catch (IllegalArgumentException ignored) {}
}
Iterable<Rational> rsFail = filter(r -> !r.hasTerminatingBaseExpansion(BigInteger.valueOf(10)), P.rationals());
for (Rational r : take(LIMIT, rsFail)) {
try {
r.bigDecimalValueExact();
fail(r.toString());
} catch (ArithmeticException ignored) {}
}
}
private static void propertiesBinaryExponent() {
initialize();
System.out.println("\t\ttesting binaryExponent() properties...");
for (Rational r : take(LIMIT, P.positiveRationals())) {
int exponent = r.binaryExponent();
Rational power = ONE.shiftLeft(exponent);
assertTrue(r.toString(), le(power, r));
assertTrue(r.toString(), le(r, power.shiftLeft(1)));
}
for (Rational r : take(LIMIT, P.rationals(Interval.lessThanOrEqualTo(ZERO)))) {
try {
r.binaryExponent();
fail(r.toString());
} catch (IllegalArgumentException ignored) {}
}
}
private static boolean floatEquidistant(@NotNull Rational r) {
float below = r.floatValue(RoundingMode.FLOOR);
float above = r.floatValue(RoundingMode.CEILING);
if (below == above || Float.isInfinite(below) || Float.isInfinite(above)) return false;
Rational belowDistance = r.subtract(ofExact(below));
Rational aboveDistance = ofExact(above).subtract(r);
return belowDistance.equals(aboveDistance);
}
private static void propertiesFloatValue_RoundingMode() {
initialize();
System.out.println("\t\ttesting floatValue(RoundingMode) properties...");
Iterable<Pair<Rational, RoundingMode>> ps = filter(
p -> p.b != RoundingMode.UNNECESSARY || p.a.equals(ofExact(p.a.floatValue(RoundingMode.FLOOR))),
P.pairs(P.rationals(), P.roundingModes())
);
for (Pair<Rational, RoundingMode> p : take(LIMIT, ps)) {
float rounded = p.a.floatValue(p.b);
assertTrue(p.toString(), !Float.isNaN(rounded));
assertTrue(p.toString(), rounded == 0.0f || Math.signum(rounded) == p.a.signum());
}
Iterable<Rational> rs = map(
Rational::ofExact,
filter(f -> !Float.isNaN(f) && Float.isFinite(f) && !f.equals(-0.0f), P.floats())
);
for (Rational r : take(LIMIT, rs)) {
float rounded = r.floatValue(RoundingMode.UNNECESSARY);
assertEquals(r.toString(), r, ofExact(rounded));
assertTrue(r.toString(), Float.isFinite(rounded));
assertTrue(r.toString(), !new Float(rounded).equals(-0.0f));
}
rs = filter(r -> !r.equals(LARGEST_FLOAT), P.rationals(Interval.of(LARGEST_FLOAT.negate(), LARGEST_FLOAT)));
for (Rational r : take(LIMIT, rs)) {
float rounded = r.floatValue(RoundingMode.FLOOR);
float successor = FloatingPointUtils.successor(rounded);
assertTrue(r.toString(), le(ofExact(rounded), r));
assertTrue(r.toString(), gt(ofExact(successor), r));
assertTrue(r.toString(), rounded < 0 || Float.isFinite(rounded));
assertTrue(r.toString(), !new Float(rounded).equals(-0.0f));
}
rs = filter(
r -> !r.equals(LARGEST_FLOAT.negate()),
P.rationals(Interval.of(LARGEST_FLOAT.negate(), LARGEST_FLOAT))
);
for (Rational r : take(LIMIT, rs)) {
float rounded = r.floatValue(RoundingMode.CEILING);
float predecessor = FloatingPointUtils.predecessor(rounded);
assertTrue(r.toString(), ge(ofExact(rounded), r));
assertTrue(r.toString(), lt(ofExact(predecessor), r));
assertTrue(r.toString(), rounded > 0 || Float.isFinite(rounded));
}
rs = P.rationals(Interval.of(LARGEST_FLOAT.negate(), LARGEST_FLOAT));
for (Rational r : take(LIMIT, rs)) {
float rounded = r.floatValue(RoundingMode.DOWN);
assertTrue(r.toString(), le(ofExact(rounded).abs(), r.abs()));
assertTrue(r.toString(), Float.isFinite(rounded));
}
rs = filter(r -> r != ZERO, P.rationals(Interval.of(LARGEST_FLOAT.negate(), LARGEST_FLOAT)));
for (Rational r : take(LIMIT, rs)) {
float rounded = r.floatValue(RoundingMode.DOWN);
float successor = FloatingPointUtils.successor(rounded);
float predecessor = FloatingPointUtils.predecessor(rounded);
float down = r.signum() == -1 ? successor : predecessor;
assertTrue(r.toString(), lt(ofExact(down).abs(), r.abs()));
}
rs = filter(
r -> !r.abs().equals(LARGEST_FLOAT),
P.rationals(Interval.of(LARGEST_FLOAT.negate(), LARGEST_FLOAT))
);
for (Rational r : take(LIMIT, rs)) {
assertTrue(r.toString(), !new Float(r.floatValue(RoundingMode.UP)).equals(-0.0f));
}
rs = filter(r -> !r.equals(SMALLEST_FLOAT), P.rationals(Interval.of(ZERO, SMALLEST_FLOAT)));
for (Rational r : take(LIMIT, rs)) {
aeq(r.toString(), r.floatValue(RoundingMode.FLOOR), 0.0f);
aeq(r.toString(), r.floatValue(RoundingMode.DOWN), 0.0f);
float rounded = r.floatValue(RoundingMode.UP);
float successor = FloatingPointUtils.successor(rounded);
float predecessor = FloatingPointUtils.predecessor(rounded);
float up = r.signum() == -1 ? predecessor : successor;
assertTrue(r.toString(), gt(ofExact(up).abs(), r.abs()));
}
rs = filter(
r -> !r.equals(LARGEST_FLOAT.negate()),
P.rationals(Interval.lessThanOrEqualTo(LARGEST_FLOAT.negate()))
);
for (Rational r : take(LIMIT, rs)) {
float floor = r.floatValue(RoundingMode.FLOOR);
aeq(r.toString(), floor, Float.NEGATIVE_INFINITY);
float up = r.floatValue(RoundingMode.UP);
aeq(r.toString(), up, Float.NEGATIVE_INFINITY);
float halfUp = r.floatValue(RoundingMode.HALF_UP);
aeq(r.toString(), halfUp, Float.NEGATIVE_INFINITY);
float halfEven = r.floatValue(RoundingMode.HALF_EVEN);
aeq(r.toString(), halfEven, Float.NEGATIVE_INFINITY);
}
rs = P.rationals(Interval.greaterThanOrEqualTo(LARGEST_FLOAT));
for (Rational r : take(LIMIT, rs)) {
aeq(r.toString(), r.floatValue(RoundingMode.FLOOR), Float.MAX_VALUE);
aeq(r.toString(), r.floatValue(RoundingMode.DOWN), Float.MAX_VALUE);
aeq(r.toString(), r.floatValue(RoundingMode.HALF_DOWN), Float.MAX_VALUE);
}
rs = filter(
r -> r != ZERO && !r.equals(SMALLEST_FLOAT.negate()),
P.rationals(Interval.of(SMALLEST_FLOAT.negate(), ZERO))
);
for (Rational r : take(LIMIT, rs)) {
aeq(r.toString(), r.floatValue(RoundingMode.CEILING), -0.0f);
aeq(r.toString(), r.floatValue(RoundingMode.DOWN), -0.0f);
}
rs = filter(r -> !r.equals(LARGEST_FLOAT), P.rationals(Interval.greaterThanOrEqualTo(LARGEST_FLOAT)));
for (Rational r : take(LIMIT, rs)) {
float ceiling = r.floatValue(RoundingMode.CEILING);
aeq(r.toString(), ceiling, Float.POSITIVE_INFINITY);
float up = r.floatValue(RoundingMode.UP);
aeq(r.toString(), up, Float.POSITIVE_INFINITY);
float halfUp = r.floatValue(RoundingMode.HALF_UP);
aeq(r.toString(), halfUp, Float.POSITIVE_INFINITY);
float halfEven = r.floatValue(RoundingMode.HALF_EVEN);
aeq(r.toString(), halfEven, Float.POSITIVE_INFINITY);
}
rs = P.rationals(Interval.lessThanOrEqualTo(LARGEST_FLOAT.negate()));
for (Rational r : take(LIMIT, rs)) {
aeq(r.toString(), r.floatValue(RoundingMode.CEILING), -Float.MAX_VALUE);
aeq(r.toString(), r.floatValue(RoundingMode.DOWN), -Float.MAX_VALUE);
aeq(r.toString(), r.floatValue(RoundingMode.HALF_DOWN), -Float.MAX_VALUE);
}
Iterable<Rational> midpoints = map(
f -> {
Rational lo = ofExact(f);
Rational hi = ofExact(FloatingPointUtils.successor(f));
return lo.add(hi).shiftRight(1);
},
filter(f -> !f.equals(-0.0f) && f != Float.MAX_VALUE, P.ordinaryFloats())
);
for (Rational r : take(LIMIT, midpoints)) {
float down = r.floatValue(RoundingMode.DOWN);
float up = r.floatValue(RoundingMode.UP);
aeq(r.toString(), r.floatValue(RoundingMode.HALF_DOWN), down);
aeq(r.toString(), r.floatValue(RoundingMode.HALF_UP), up);
float halfEven = r.floatValue(RoundingMode.HALF_EVEN);
assertTrue(r.toString(), ((Float.floatToIntBits(down) & 1) == 0 ? down : up) == halfEven);
}
Iterable<Rational> notMidpoints = filter(
r -> ge(r, LARGEST_FLOAT.negate()) && le(r, LARGEST_FLOAT) && !floatEquidistant(r),
P.rationals()
);
for (Rational r : take(LIMIT, notMidpoints)) {
float below = r.floatValue(RoundingMode.FLOOR);
float above = r.floatValue(RoundingMode.CEILING);
Rational belowDistance = r.subtract(ofExact(below));
Rational aboveDistance = ofExact(above).subtract(r);
float closest = lt(belowDistance, aboveDistance) ? below : above;
aeq(r.toString(), r.floatValue(RoundingMode.HALF_DOWN), closest);
aeq(r.toString(), r.floatValue(RoundingMode.HALF_UP), closest);
aeq(r.toString(), r.floatValue(RoundingMode.HALF_EVEN), closest);
}
rs = P.rationals(Interval.of(ZERO, SMALLEST_FLOAT.shiftRight(1)));
for (Rational r : take(LIMIT, rs)) {
aeq(r.toString(), r.floatValue(RoundingMode.HALF_DOWN), 0.0f);
aeq(r.toString(), r.floatValue(RoundingMode.HALF_EVEN), 0.0f);
}
rs = filter(r -> r != ZERO, P.rationals(Interval.of(SMALLEST_FLOAT.shiftRight(1).negate(), ZERO)));
for (Rational r : take(LIMIT, rs)) {
aeq(r.toString(), r.floatValue(RoundingMode.HALF_DOWN), -0.0f);
aeq(r.toString(), r.floatValue(RoundingMode.HALF_EVEN), -0.0f);
}
rs = filter(
r -> !r.equals(SMALLEST_FLOAT.shiftRight(1)),
P.rationals(Interval.of(ZERO, SMALLEST_FLOAT.shiftRight(1)))
);
for (Rational r : take(LIMIT, rs)) {
aeq(r.toString(), r.floatValue(RoundingMode.HALF_UP), 0.0f);
}
rs = filter(
r -> r != ZERO && !r.equals(SMALLEST_FLOAT.shiftRight(1).negate()),
P.rationals(Interval.of(SMALLEST_FLOAT.shiftRight(1).negate(), ZERO))
);
for (Rational r : take(LIMIT, rs)) {
aeq(r.toString(), r.floatValue(RoundingMode.HALF_UP), -0.0f);
}
for (Rational r : take(LIMIT, P.rationals())) {
float floor = r.floatValue(RoundingMode.FLOOR);
assertFalse(r.toString(), Float.valueOf(floor).equals(-0.0f));
assertFalse(r.toString(), floor == Float.POSITIVE_INFINITY);
float ceiling = r.floatValue(RoundingMode.CEILING);
assertFalse(r.toString(), ceiling == Float.NEGATIVE_INFINITY);
float down = r.floatValue(RoundingMode.DOWN);
assertFalse(r.toString(), down == Float.NEGATIVE_INFINITY);
assertFalse(r.toString(), down == Float.POSITIVE_INFINITY);
float up = r.floatValue(RoundingMode.UP);
assertFalse(r.toString(), Float.valueOf(up).equals(-0.0f));
float halfDown = r.floatValue(RoundingMode.HALF_DOWN);
assertFalse(r.toString(), halfDown == Float.NEGATIVE_INFINITY);
assertFalse(r.toString(), halfDown == Float.POSITIVE_INFINITY);
}
Iterable<Rational> rsFail = filter(
r -> !ofExact(r.floatValue(RoundingMode.FLOOR)).equals(r),
P.rationals(Interval.of(LARGEST_FLOAT.negate(), LARGEST_FLOAT))
);
for (Rational r : take(LIMIT, rsFail)) {
try {
r.floatValue(RoundingMode.UNNECESSARY);
fail(r.toString());
} catch (ArithmeticException ignored) {}
}
}
private static void propertiesFloatValue() {
initialize();
System.out.println("\t\ttesting floatValue() properties...");
for (Rational r : take(LIMIT, P.rationals())) {
float rounded = r.floatValue();
aeq(r.toString(), rounded, r.floatValue(RoundingMode.HALF_EVEN));
assertTrue(r.toString(), !Float.isNaN(rounded));
assertTrue(r.toString(), rounded == 0.0f || Math.signum(rounded) == r.signum());
}
Iterable<Rational> rs = filter(
r -> !r.equals(LARGEST_FLOAT.negate()),
P.rationals(Interval.lessThanOrEqualTo(LARGEST_FLOAT.negate()))
);
for (Rational r : take(LIMIT, rs)) {
float rounded = r.floatValue();
aeq(r.toString(), rounded, Float.NEGATIVE_INFINITY);
}
rs = filter(r -> !r.equals(LARGEST_FLOAT), P.rationals(Interval.greaterThanOrEqualTo(LARGEST_FLOAT)));
for (Rational r : take(LIMIT, rs)) {
float rounded = r.floatValue();
aeq(r.toString(), rounded, Float.POSITIVE_INFINITY);
}
Iterable<Rational> midpoints = map(
f -> {
Rational lo = ofExact(f);
Rational hi = ofExact(FloatingPointUtils.successor(f));
return lo.add(hi).shiftRight(1);
},
filter(f -> !f.equals(-0.0f) && f != Float.MAX_VALUE, P.ordinaryFloats())
);
for (Rational r : take(LIMIT, midpoints)) {
float down = r.floatValue(RoundingMode.DOWN);
float up = r.floatValue(RoundingMode.UP);
float rounded = r.floatValue();
assertTrue(r.toString(), ((Float.floatToIntBits(down) & 1) == 0 ? down : up) == rounded);
}
Iterable<Rational> notMidpoints = filter(
r -> ge(r, LARGEST_FLOAT.negate()) && le(r, LARGEST_FLOAT) && !floatEquidistant(r),
P.rationals()
);
for (Rational r : take(LIMIT, notMidpoints)) {
float below = r.floatValue(RoundingMode.FLOOR);
float above = r.floatValue(RoundingMode.CEILING);
Rational belowDistance = r.subtract(ofExact(below));
Rational aboveDistance = ofExact(above).subtract(r);
float closest = lt(belowDistance, aboveDistance) ? below : above;
aeq(r.toString(), r.floatValue(), closest);
}
rs = P.rationals(Interval.of(ZERO, SMALLEST_FLOAT.shiftRight(1)));
for (Rational r : take(LIMIT, rs)) {
aeq(r.toString(), r.floatValue(), 0.0f);
}
rs = filter(r -> r != ZERO, P.rationals(Interval.of(SMALLEST_FLOAT.shiftRight(1).negate(), ZERO)));
for (Rational r : take(LIMIT, rs)) {
aeq(r.toString(), r.floatValue(), -0.0f);
}
}
private static void propertiesFloatValueExact() {
initialize();
System.out.println("\t\ttesting floatValueExact() properties...");
Iterable<Rational> rs = filter(r -> r.equals(ofExact(r.floatValue(RoundingMode.FLOOR))), P.rationals());
for (Rational r : take(LIMIT, rs)) {
float f = r.floatValueExact();
assertTrue(r.toString(), !Float.isNaN(f));
assertTrue(r.toString(), f == 0.0f || Math.signum(f) == r.signum());
}
rs = map(
Rational::ofExact,
filter(f -> !Float.isNaN(f) && Float.isFinite(f) && !f.equals(-0.0f), P.floats())
);
for (Rational r : take(LIMIT, rs)) {
float f = r.floatValueExact();
assertEquals(r.toString(), r, ofExact(f));
assertTrue(r.toString(), Float.isFinite(f));
assertTrue(r.toString(), !new Float(f).equals(-0.0f));
}
Iterable<Rational> rsFail = filter(
r -> !ofExact(r.floatValue(RoundingMode.FLOOR)).equals(r),
P.rationals(Interval.of(LARGEST_FLOAT.negate(), LARGEST_FLOAT))
);
for (Rational r : take(LIMIT, rsFail)) {
try {
r.floatValueExact();
fail(r.toString());
} catch (ArithmeticException ignored) {}
}
}
private static boolean doubleEquidistant(@NotNull Rational r) {
double below = r.doubleValue(RoundingMode.FLOOR);
double above = r.doubleValue(RoundingMode.CEILING);
if (below == above || Double.isInfinite(below) || Double.isInfinite(above)) return false;
Rational belowDistance = r.subtract(ofExact(below));
Rational aboveDistance = ofExact(above).subtract(r);
return belowDistance.equals(aboveDistance);
}
private static void propertiesDoubleValue_RoundingMode() {
initialize();
System.out.println("\t\ttesting doubleValue(RoundingMode) properties...");
Iterable<Pair<Rational, RoundingMode>> ps = filter(
p -> p.b != RoundingMode.UNNECESSARY || p.a.equals(ofExact(p.a.doubleValue(RoundingMode.FLOOR))),
P.pairs(P.rationals(), P.roundingModes())
);
for (Pair<Rational, RoundingMode> p : take(LIMIT, ps)) {
double rounded = p.a.doubleValue(p.b);
assertTrue(p.toString(), !Double.isNaN(rounded));
assertTrue(p.toString(), rounded == 0.0 || Math.signum(rounded) == p.a.signum());
}
Iterable<Rational> rs = map(
Rational::ofExact,
filter(f -> !Double.isNaN(f) && Double.isFinite(f) && !f.equals(-0.0), P.doubles())
);
for (Rational r : take(LIMIT, rs)) {
double rounded = r.doubleValue(RoundingMode.UNNECESSARY);
assertEquals(r.toString(), r, ofExact(rounded));
assertTrue(r.toString(), Double.isFinite(rounded));
assertTrue(r.toString(), !new Double(rounded).equals(-0.0));
}
rs = filter(r -> !r.equals(LARGEST_DOUBLE), P.rationals(Interval.of(LARGEST_DOUBLE.negate(), LARGEST_DOUBLE)));
for (Rational r : take(LIMIT, rs)) {
double rounded = r.doubleValue(RoundingMode.FLOOR);
double successor = FloatingPointUtils.successor(rounded);
assertTrue(r.toString(), le(ofExact(rounded), r));
assertTrue(r.toString(), gt(ofExact(successor), r));
assertTrue(r.toString(), rounded < 0 || Double.isFinite(rounded));
assertTrue(r.toString(), !new Double(rounded).equals(-0.0));
}
rs = filter(
r -> !r.equals(LARGEST_DOUBLE.negate()),
P.rationals(Interval.of(LARGEST_DOUBLE.negate(), LARGEST_DOUBLE))
);
for (Rational r : take(LIMIT, rs)) {
double rounded = r.doubleValue(RoundingMode.CEILING);
double predecessor = FloatingPointUtils.predecessor(rounded);
assertTrue(r.toString(), ge(ofExact(rounded), r));
assertTrue(r.toString(), lt(ofExact(predecessor), r));
assertTrue(r.toString(), rounded > 0 || Double.isFinite(rounded));
}
rs = P.rationals(Interval.of(LARGEST_DOUBLE.negate(), LARGEST_DOUBLE));
for (Rational r : take(LIMIT, rs)) {
double rounded = r.doubleValue(RoundingMode.DOWN);
assertTrue(r.toString(), le(ofExact(rounded).abs(), r.abs()));
assertTrue(r.toString(), Double.isFinite(rounded));
}
rs = filter(r -> r != ZERO, P.rationals(Interval.of(LARGEST_DOUBLE.negate(), LARGEST_DOUBLE)));
for (Rational r : take(LIMIT, rs)) {
double rounded = r.doubleValue(RoundingMode.DOWN);
double successor = FloatingPointUtils.successor(rounded);
double predecessor = FloatingPointUtils.predecessor(rounded);
double down = r.signum() == -1 ? successor : predecessor;
assertTrue(r.toString(), lt(ofExact(down).abs(), r.abs()));
}
rs = filter(
r -> !r.abs().equals(LARGEST_DOUBLE),
P.rationals(Interval.of(LARGEST_DOUBLE.negate(), LARGEST_DOUBLE))
);
for (Rational r : take(LIMIT, rs)) {
assertTrue(r.toString(), !new Double(r.doubleValue(RoundingMode.UP)).equals(-0.0));
}
rs = filter(r -> !r.equals(SMALLEST_DOUBLE), P.rationals(Interval.of(ZERO, SMALLEST_DOUBLE)));
for (Rational r : take(LIMIT, rs)) {
aeq(r.toString(), r.doubleValue(RoundingMode.FLOOR), 0.0);
aeq(r.toString(), r.doubleValue(RoundingMode.DOWN), 0.0);
double rounded = r.doubleValue(RoundingMode.UP);
double successor = FloatingPointUtils.successor(rounded);
double predecessor = FloatingPointUtils.predecessor(rounded);
double up = r.signum() == -1 ? predecessor : successor;
assertTrue(r.toString(), gt(ofExact(up).abs(), r.abs()));
}
rs = filter(
r -> !r.equals(LARGEST_DOUBLE.negate()),
P.rationals(Interval.lessThanOrEqualTo(LARGEST_DOUBLE.negate()))
);
for (Rational r : take(LIMIT, rs)) {
double floor = r.doubleValue(RoundingMode.FLOOR);
aeq(r.toString(), floor, Double.NEGATIVE_INFINITY);
double up = r.doubleValue(RoundingMode.UP);
aeq(r.toString(), up, Double.NEGATIVE_INFINITY);
double halfUp = r.doubleValue(RoundingMode.HALF_UP);
aeq(r.toString(), halfUp, Double.NEGATIVE_INFINITY);
double halfEven = r.doubleValue(RoundingMode.HALF_EVEN);
aeq(r.toString(), halfEven, Double.NEGATIVE_INFINITY);
}
rs = P.rationals(Interval.greaterThanOrEqualTo(LARGEST_DOUBLE));
for (Rational r : take(LIMIT, rs)) {
aeq(r.toString(), r.doubleValue(RoundingMode.FLOOR), Double.MAX_VALUE);
aeq(r.toString(), r.doubleValue(RoundingMode.DOWN), Double.MAX_VALUE);
aeq(r.toString(), r.doubleValue(RoundingMode.HALF_DOWN), Double.MAX_VALUE);
}
rs = filter(
r -> r != ZERO && !r.equals(SMALLEST_DOUBLE.negate()),
P.rationals(Interval.of(SMALLEST_DOUBLE.negate(), ZERO))
);
for (Rational r : take(LIMIT, rs)) {
aeq(r.toString(), r.doubleValue(RoundingMode.CEILING), -0.0);
aeq(r.toString(), r.doubleValue(RoundingMode.DOWN), -0.0);
}
rs = filter(r -> !r.equals(LARGEST_DOUBLE), P.rationals(Interval.greaterThanOrEqualTo(LARGEST_DOUBLE)));
for (Rational r : take(LIMIT, rs)) {
double ceiling = r.doubleValue(RoundingMode.CEILING);
aeq(r.toString(), ceiling, Double.POSITIVE_INFINITY);
double up = r.doubleValue(RoundingMode.UP);
aeq(r.toString(), up, Double.POSITIVE_INFINITY);
double halfUp = r.doubleValue(RoundingMode.HALF_UP);
aeq(r.toString(), halfUp, Double.POSITIVE_INFINITY);
double halfEven = r.doubleValue(RoundingMode.HALF_EVEN);
aeq(r.toString(), halfEven, Double.POSITIVE_INFINITY);
}
rs = P.rationals(Interval.lessThanOrEqualTo(LARGEST_DOUBLE.negate()));
for (Rational r : take(LIMIT, rs)) {
aeq(r.toString(), r.doubleValue(RoundingMode.CEILING), -Double.MAX_VALUE);
aeq(r.toString(), r.doubleValue(RoundingMode.DOWN), -Double.MAX_VALUE);
aeq(r.toString(), r.doubleValue(RoundingMode.HALF_DOWN), -Double.MAX_VALUE);
}
Iterable<Rational> midpoints = map(
f -> {
Rational lo = ofExact(f);
Rational hi = ofExact(FloatingPointUtils.successor(f));
return lo.add(hi).shiftRight(1);
},
filter(f -> !f.equals(-0.0) && f != Double.MAX_VALUE, P.ordinaryDoubles())
);
for (Rational r : take(LIMIT, midpoints)) {
double down = r.doubleValue(RoundingMode.DOWN);
double up = r.doubleValue(RoundingMode.UP);
aeq(r.toString(), r.doubleValue(RoundingMode.HALF_DOWN), down);
aeq(r.toString(), r.doubleValue(RoundingMode.HALF_UP), up);
double halfEven = r.doubleValue(RoundingMode.HALF_EVEN);
assertTrue(r.toString(), ((Double.doubleToLongBits(down) & 1) == 0 ? down : up) == halfEven);
}
Iterable<Rational> notMidpoints = filter(
r -> ge(r, LARGEST_DOUBLE.negate()) && le(r, LARGEST_DOUBLE) && !doubleEquidistant(r),
P.rationals()
);
for (Rational r : take(LIMIT, notMidpoints)) {
double below = r.doubleValue(RoundingMode.FLOOR);
double above = r.doubleValue(RoundingMode.CEILING);
Rational belowDistance = r.subtract(ofExact(below));
Rational aboveDistance = ofExact(above).subtract(r);
double closest = lt(belowDistance, aboveDistance) ? below : above;
aeq(r.toString(), r.doubleValue(RoundingMode.HALF_DOWN), closest);
aeq(r.toString(), r.doubleValue(RoundingMode.HALF_UP), closest);
aeq(r.toString(), r.doubleValue(RoundingMode.HALF_EVEN), closest);
}
rs = P.rationals(Interval.of(ZERO, SMALLEST_DOUBLE.shiftRight(1)));
for (Rational r : take(LIMIT, rs)) {
aeq(r.toString(), r.doubleValue(RoundingMode.HALF_DOWN), 0.0);
aeq(r.toString(), r.doubleValue(RoundingMode.HALF_EVEN), 0.0);
}
rs = filter(r -> r != ZERO, P.rationals(Interval.of(SMALLEST_DOUBLE.shiftRight(1).negate(), ZERO)));
for (Rational r : take(LIMIT, rs)) {
aeq(r.toString(), r.doubleValue(RoundingMode.HALF_DOWN), -0.0);
aeq(r.toString(), r.doubleValue(RoundingMode.HALF_EVEN), -0.0);
}
rs = filter(
r -> !r.equals(SMALLEST_DOUBLE.shiftRight(1)),
P.rationals(Interval.of(ZERO, SMALLEST_DOUBLE.shiftRight(1)))
);
for (Rational r : take(LIMIT, rs)) {
aeq(r.toString(), r.doubleValue(RoundingMode.HALF_UP), 0.0);
}
rs = filter(
r -> r != ZERO && !r.equals(SMALLEST_DOUBLE.shiftRight(1).negate()),
P.rationals(Interval.of(SMALLEST_DOUBLE.shiftRight(1).negate(), ZERO))
);
for (Rational r : take(LIMIT, rs)) {
aeq(r.toString(), r.doubleValue(RoundingMode.HALF_UP), -0.0);
}
for (Rational r : take(LIMIT, P.rationals())) {
double floor = r.doubleValue(RoundingMode.FLOOR);
assertFalse(r.toString(), Double.valueOf(floor).equals(-0.0));
assertFalse(r.toString(), floor == Double.POSITIVE_INFINITY);
double ceiling = r.doubleValue(RoundingMode.CEILING);
assertFalse(r.toString(), ceiling == Double.NEGATIVE_INFINITY);
double down = r.doubleValue(RoundingMode.DOWN);
assertFalse(r.toString(), down == Double.NEGATIVE_INFINITY);
assertFalse(r.toString(), down == Double.POSITIVE_INFINITY);
double up = r.doubleValue(RoundingMode.UP);
assertFalse(r.toString(), Double.valueOf(up).equals(-0.0));
double halfDown = r.doubleValue(RoundingMode.HALF_DOWN);
assertFalse(r.toString(), halfDown == Double.NEGATIVE_INFINITY);
assertFalse(r.toString(), halfDown == Double.POSITIVE_INFINITY);
}
Iterable<Rational> rsFail = filter(
r -> !ofExact(r.doubleValue(RoundingMode.FLOOR)).equals(r),
P.rationals(Interval.of(LARGEST_DOUBLE.negate(), LARGEST_DOUBLE))
);
for (Rational r : take(LIMIT, rsFail)) {
try {
r.doubleValue(RoundingMode.UNNECESSARY);
fail(r.toString());
} catch (ArithmeticException ignored) {}
}
}
private static void propertiesDoubleValue() {
initialize();
System.out.println("\t\ttesting doubleValue() properties...");
for (Rational r : take(LIMIT, P.rationals())) {
double rounded = r.doubleValue();
aeq(r.toString(), rounded, r.doubleValue(RoundingMode.HALF_EVEN));
assertTrue(r.toString(), !Double.isNaN(rounded));
assertTrue(r.toString(), rounded == 0.0 || Math.signum(rounded) == r.signum());
}
Iterable<Rational> rs = filter(
r -> !r.equals(LARGEST_DOUBLE.negate()),
P.rationals(Interval.lessThanOrEqualTo(LARGEST_DOUBLE.negate()))
);
for (Rational r : take(LIMIT, rs)) {
double rounded = r.doubleValue();
aeq(r.toString(), rounded, Double.NEGATIVE_INFINITY);
}
rs = filter(r -> !r.equals(LARGEST_DOUBLE), P.rationals(Interval.greaterThanOrEqualTo(LARGEST_DOUBLE)));
for (Rational r : take(LIMIT, rs)) {
double rounded = r.doubleValue();
aeq(r.toString(), rounded, Double.POSITIVE_INFINITY);
}
Iterable<Rational> midpoints = map(
f -> {
Rational lo = ofExact(f);
Rational hi = ofExact(FloatingPointUtils.successor(f));
return lo.add(hi).shiftRight(1);
},
filter(f -> !f.equals(-0.0) && f != Double.MAX_VALUE, P.ordinaryDoubles())
);
for (Rational r : take(LIMIT, midpoints)) {
double down = r.doubleValue(RoundingMode.DOWN);
double up = r.doubleValue(RoundingMode.UP);
double rounded = r.doubleValue();
assertTrue(r.toString(), ((Double.doubleToLongBits(down) & 1) == 0 ? down : up) == rounded);
}
Iterable<Rational> notMidpoints = filter(
r -> ge(r, LARGEST_DOUBLE.negate()) && le(r, LARGEST_DOUBLE) && !doubleEquidistant(r),
P.rationals()
);
for (Rational r : take(LIMIT, notMidpoints)) {
double below = r.doubleValue(RoundingMode.FLOOR);
double above = r.doubleValue(RoundingMode.CEILING);
Rational belowDistance = r.subtract(ofExact(below));
Rational aboveDistance = ofExact(above).subtract(r);
double closest = lt(belowDistance, aboveDistance) ? below : above;
aeq(r.toString(), r.doubleValue(), closest);
}
rs = P.rationals(Interval.of(ZERO, SMALLEST_DOUBLE.shiftRight(1)));
for (Rational r : take(LIMIT, rs)) {
aeq(r.toString(), r.doubleValue(), 0.0);
}
rs = filter(r -> r != ZERO, P.rationals(Interval.of(SMALLEST_DOUBLE.shiftRight(1).negate(), ZERO)));
for (Rational r : take(LIMIT, rs)) {
aeq(r.toString(), r.doubleValue(), -0.0);
}
}
private static void propertiesDoubleValueExact() {
initialize();
System.out.println("\t\ttesting doubleValueExact() properties...");
Iterable<Rational> rs = filter(r -> r.equals(ofExact(r.doubleValue(RoundingMode.FLOOR))), P.rationals());
for (Rational r : take(LIMIT, rs)) {
double f = r.doubleValueExact();
assertTrue(r.toString(), !Double.isNaN(f));
assertTrue(r.toString(), f == 0.0 || Math.signum(f) == r.signum());
}
rs = map(
Rational::ofExact,
filter(f -> !Double.isNaN(f) && Double.isFinite(f) && !f.equals(-0.0), P.doubles())
);
for (Rational r : take(LIMIT, rs)) {
double f = r.doubleValueExact();
assertEquals(r.toString(), r, ofExact(f));
assertTrue(r.toString(), Double.isFinite(f));
assertTrue(r.toString(), !new Double(f).equals(-0.0));
}
Iterable<Rational> rsFail = filter(
r -> !ofExact(r.doubleValue(RoundingMode.FLOOR)).equals(r),
P.rationals(Interval.of(LARGEST_DOUBLE.negate(), LARGEST_DOUBLE))
);
for (Rational r : take(LIMIT, rsFail)) {
try {
r.doubleValueExact();
fail(r.toString());
} catch (ArithmeticException ignored) {}
}
}
private static @NotNull Rational add_simplest(@NotNull Rational a, @NotNull Rational b) {
return of(
a.getNumerator().multiply(b.getDenominator()).add(a.getDenominator().multiply(b.getNumerator())),
a.getDenominator().multiply(b.getDenominator())
);
}
private static void propertiesAdd() {
initialize();
System.out.println("\t\ttesting add(Rational) properties...");
for (Pair<Rational, Rational> p : take(LIMIT, P.pairs(P.rationals()))) {
Rational sum = p.a.add(p.b);
validate(sum);
assertEquals(p.toString(), sum, add_simplest(p.a, p.b));
assertEquals(p.toString(), sum, p.b.add(p.a));
assertEquals(p.toString(), sum.subtract(p.b), p.a);
}
for (Rational r : take(LIMIT, P.rationals())) {
assertEquals(r.toString(), ZERO.add(r), r);
assertEquals(r.toString(), r.add(ZERO), r);
assertTrue(r.toString(), r.add(r.negate()) == ZERO);
}
for (Triple<Rational, Rational, Rational> t : take(LIMIT, P.triples(P.rationals()))) {
Rational sum1 = t.a.add(t.b).add(t.c);
Rational sum2 = t.a.add(t.b.add(t.c));
assertEquals(t.toString(), sum1, sum2);
}
}
private static void compareImplementationsAdd() {
initialize();
System.out.println("\t\tcomparing add(Rational) implementations...");
long totalTime = 0;
for (Pair<Rational, Rational> p : take(LIMIT, P.pairs(P.rationals()))) {
long time = System.nanoTime();
add_simplest(p.a, p.b);
totalTime += (System.nanoTime() - time);
}
System.out.println("\t\t\tsimplest: " + ((double) totalTime) / 1e9 + " s");
totalTime = 0;
for (Pair<Rational, Rational> p : take(LIMIT, P.pairs(P.rationals()))) {
long time = System.nanoTime();
p.a.add(p.b);
totalTime += (System.nanoTime() - time);
}
System.out.println("\t\t\tstandard: " + ((double) totalTime) / 1e9 + " s");
}
private static void propertiesNegate() {
initialize();
System.out.println("\t\ttesting negate() properties...");
for (Rational r : take(LIMIT, P.rationals())) {
Rational negativeR = r.negate();
validate(negativeR);
assertEquals(r.toString(), r, negativeR.negate());
assertTrue(r.add(negativeR) == ZERO);
}
Iterable<Rational> rs = filter(r -> r != ZERO, P.rationals());
for (Rational r : take(LIMIT, rs)) {
Rational negativeR = r.negate();
assertNotEquals(r.toString(), r, negativeR);
}
}
private static void propertiesAbs() {
initialize();
System.out.println("\t\ttesting abs() properties...");
for (Rational r : take(LIMIT, P.rationals())) {
Rational absR = r.abs();
validate(absR);
assertEquals(r.toString(), absR, absR.abs());
assertTrue(r.toString(), ge(absR, ZERO));
}
}
private static void propertiesSignum() {
initialize();
System.out.println("\t\ttesting signum() properties...");
for (Rational r : take(LIMIT, P.rationals())) {
int signumR = r.signum();
assertEquals(r.toString(), signumR, Ordering.compare(r, ZERO).toInt());
assertTrue(r.toString(), signumR == -1 || signumR == 0 || signumR == 1);
}
}
private static void propertiesSubtract() {
initialize();
System.out.println("\t\ttesting subtract(Rational) properties...");
for (Pair<Rational, Rational> p : take(LIMIT, P.pairs(P.rationals()))) {
Rational difference = p.a.subtract(p.b);
validate(difference);
assertEquals(p.toString(), difference, p.b.subtract(p.a).negate());
assertEquals(p.toString(), p.a, difference.add(p.b));
}
for (Rational r : take(LIMIT, P.rationals())) {
assertEquals(r.toString(), ZERO.subtract(r), r.negate());
assertEquals(r.toString(), r.subtract(ZERO), r);
assertTrue(r.toString(), r.subtract(r) == ZERO);
}
}
private static @NotNull Pair<BigInteger, BigInteger> multiply_Rational_Knuth(
@NotNull Rational a,
@NotNull Rational b
) {
if (a == ZERO || b == ZERO) return new Pair<>(BigInteger.ZERO, BigInteger.ONE);
if (a == ONE) return new Pair<>(b.getNumerator(), b.getDenominator());
if (b == ONE) return new Pair<>(a.getNumerator(), a.getDenominator());
BigInteger g1 = a.getNumerator().gcd(b.getDenominator());
BigInteger g2 = b.getNumerator().gcd(a.getDenominator());
BigInteger mn = a.getNumerator().divide(g1).multiply(b.getNumerator().divide(g2));
BigInteger md = a.getDenominator().divide(g2).multiply(b.getDenominator().divide(g1));
if (mn.equals(md)) return new Pair<>(BigInteger.ONE, BigInteger.ONE);
return new Pair<>(mn, md);
}
private static void propertiesMultiply_Rational() {
initialize();
System.out.println("\t\ttesting multiply(Rational) properties...");
for (Pair<Rational, Rational> p : take(LIMIT, P.pairs(P.rationals()))) {
Rational product = p.a.multiply(p.b);
validate(product);
assertEquals(
p.toString(),
new Pair<>(product.getNumerator(), product.getDenominator()),
multiply_Rational_Knuth(p.a, p.b)
);
assertEquals(p.toString(), product, p.b.multiply(p.a));
}
for (Pair<Rational, Rational> p : take(LIMIT, P.pairs(P.rationals(), filter(r -> r != ZERO, P.rationals())))) {
assertEquals(p.toString(), p.a.multiply(p.b).divide(p.b), p.a);
}
Iterable<Pair<Rational, Rational>> ps = P.pairs(P.rationals(), filter(r -> r != Rational.ZERO, P.rationals()));
for (Pair<Rational, Rational> p : take(LIMIT, ps)) {
assertEquals(p.toString(), p.a.multiply(p.b), p.a.divide(p.b.invert()));
}
for (Rational r : take(LIMIT, P.rationals())) {
assertEquals(r.toString(), ONE.multiply(r), r);
assertEquals(r.toString(), r.multiply(ONE), r);
assertTrue(r.toString(), ZERO.multiply(r) == ZERO);
assertTrue(r.toString(), r.multiply(ZERO) == ZERO);
}
Iterable<Rational> rs = filter(r -> r != ZERO, P.rationals());
for (Rational r : take(LIMIT, rs)) {
assertTrue(r.toString(), r.multiply(r.invert()) == ONE);
}
for (Triple<Rational, Rational, Rational> t : take(LIMIT, P.triples(P.rationals()))) {
Rational product1 = t.a.multiply(t.b).multiply(t.c);
Rational product2 = t.a.multiply(t.b.multiply(t.c));
assertEquals(t.toString(), product1, product2);
Rational expression1 = t.a.add(t.b).multiply(t.c);
Rational expression2 = t.a.multiply(t.c).add(t.b.multiply(t.c));
assertEquals(t.toString(), expression1, expression2);
}
}
private static void compareImplementationsMultiply_Rational() {
initialize();
System.out.println("\t\tcomparing multiply(Rational) implementations...");
long totalTime = 0;
for (Pair<Rational, Rational> p : take(LIMIT, P.pairs(P.rationals()))) {
long time = System.nanoTime();
multiply_Rational_Knuth(p.a, p.b);
totalTime += (System.nanoTime() - time);
}
System.out.println("\t\t\tKnuth: " + ((double) totalTime) / 1e9 + " s");
totalTime = 0;
for (Pair<Rational, Rational> p : take(LIMIT, P.pairs(P.rationals()))) {
long time = System.nanoTime();
p.a.multiply(p.b);
totalTime += (System.nanoTime() - time);
}
System.out.println("\t\t\tstandard: " + ((double) totalTime) / 1e9 + " s");
}
private static @NotNull Rational multiply_BigInteger_simplest(@NotNull Rational a, @NotNull BigInteger b) {
return of(a.getNumerator().multiply(b), a.getDenominator());
}
private static void propertiesMultiply_BigInteger() {
initialize();
System.out.println("\t\ttesting multiply(BigInteger) properties...");
Iterable<Pair<Rational, BigInteger>> ps = P.pairs(P.rationals(), P.bigIntegers());
for (Pair<Rational, BigInteger> p : take(LIMIT, ps)) {
Rational product = p.a.multiply(p.b);
validate(product);
assertEquals(p.toString(), product, multiply_BigInteger_simplest(p.a, p.b));
assertEquals(p.toString(), product, p.a.multiply(of(p.b)));
assertEquals(p.toString(), product, of(p.b).multiply(p.a));
}
ps = P.pairs(P.rationals(), filter(i -> !i.equals(BigInteger.ZERO), P.bigIntegers()));
for (Pair<Rational, BigInteger> p : take(LIMIT, ps)) {
assertEquals(p.toString(), p.a.multiply(p.b).divide(p.b), p.a);
}
for (BigInteger i : take(LIMIT, P.bigIntegers())) {
assertEquals(i.toString(), ONE.multiply(i), of(i));
assertTrue(i.toString(), ZERO.multiply(i) == ZERO);
}
for (Rational r : take(LIMIT, P.rationals())) {
assertEquals(r.toString(), r.multiply(BigInteger.ONE), r);
assertTrue(r.toString(), r.multiply(BigInteger.ZERO) == ZERO);
}
Iterable<BigInteger> bis = filter(i -> !i.equals(BigInteger.ZERO), P.bigIntegers());
for (BigInteger i : take(LIMIT, bis)) {
assertTrue(i.toString(), of(i).invert().multiply(i) == ONE);
}
Iterable<Rational> rs = P.rationals();
for (Triple<Rational, Rational, BigInteger> t : take(LIMIT, P.triples(rs, rs, P.bigIntegers()))) {
Rational expression1 = t.a.add(t.b).multiply(t.c);
Rational expression2 = t.a.multiply(t.c).add(t.b.multiply(t.c));
assertEquals(t.toString(), expression1, expression2);
}
}
private static void compareImplementationsMultiply_BigInteger() {
initialize();
System.out.println("\t\tcomparing multiply(BigInteger) implementations...");
long totalTime = 0;
Iterable<Pair<Rational, BigInteger>> ps = P.pairs(P.rationals(), P.bigIntegers());
for (Pair<Rational, BigInteger> p : take(LIMIT, ps)) {
long time = System.nanoTime();
multiply_BigInteger_simplest(p.a, p.b);
totalTime += (System.nanoTime() - time);
}
System.out.println("\t\t\tsimplest: " + ((double) totalTime) / 1e9 + " s");
totalTime = 0;
for (Pair<Rational, BigInteger> p : take(LIMIT, ps)) {
long time = System.nanoTime();
p.a.multiply(p.b);
totalTime += (System.nanoTime() - time);
}
System.out.println("\t\t\tstandard: " + ((double) totalTime) / 1e9 + " s");
}
private static @NotNull Rational multiply_int_simplest(@NotNull Rational a, int b) {
return of(a.getNumerator().multiply(BigInteger.valueOf(b)), a.getDenominator());
}
private static void propertiesMultiply_int() {
initialize();
System.out.println("\t\ttesting multiply(int) properties...");
for (Pair<Rational, Integer> p :take(LIMIT, P.pairs(P.rationals(), P.integers()))) {
Rational product = p.a.multiply(p.b);
validate(product);
assertEquals(p.toString(), product, multiply_int_simplest(p.a, p.b));
assertEquals(p.toString(), product, p.a.multiply(p.b));
assertEquals(p.toString(), product, p.a.multiply(of(p.b)));
assertEquals(p.toString(), product, of(p.b).multiply(p.a));
}
for (Pair<Rational, Integer> p : take(LIMIT, P.pairs(P.rationals(), filter(i -> i != 0, P.integers())))) {
assertEquals(p.toString(), p.a.multiply(p.b).divide(p.b), p.a);
}
for (int i : take(LIMIT, P.integers())) {
assertEquals(Integer.toString(i), ONE.multiply(i), of(i));
assertTrue(Integer.toString(i), ZERO.multiply(i) == ZERO);
}
for (Rational r : take(LIMIT, P.rationals())) {
assertEquals(r.toString(), r.multiply(1), r);
assertTrue(r.toString(), r.multiply(0) == ZERO);
}
Iterable<Integer> is = filter(i -> i != 0, P.integers());
for (int i : take(LIMIT, is)) {
assertTrue(Integer.toString(i), of(i).invert().multiply(i) == ONE);
}
Iterable<Rational> rs = P.rationals();
for (Triple<Rational, Rational, Integer> t : take(LIMIT, P.triples(rs, rs, P.integers()))) {
Rational expression1 = t.a.add(t.b).multiply(t.c);
Rational expression2 = t.a.multiply(t.c).add(t.b.multiply(t.c));
assertEquals(t.toString(), expression1, expression2);
}
}
private static void compareImplementationsMultiply_int() {
initialize();
System.out.println("\t\tcomparing multiply(int) implementations...");
long totalTime = 0;
Iterable<Pair<Rational, Integer>> ps = P.pairs(P.rationals(), P.integers());
for (Pair<Rational, Integer> p : take(LIMIT, ps)) {
long time = System.nanoTime();
multiply_int_simplest(p.a, p.b);
totalTime += (System.nanoTime() - time);
}
System.out.println("\t\t\tsimplest: " + ((double) totalTime) / 1e9 + " s");
totalTime = 0;
for (Pair<Rational, Integer> p : take(LIMIT, ps)) {
long time = System.nanoTime();
p.a.multiply(p.b);
totalTime += (System.nanoTime() - time);
}
System.out.println("\t\t\tstandard: " + ((double) totalTime) / 1e9 + " s");
}
private static @NotNull Rational invert_simplest(@NotNull Rational r) {
return of(r.getDenominator(), r.getNumerator());
}
private static void propertiesInvert() {
initialize();
System.out.println("\t\ttesting invert() properties...");
Iterable<Rational> rs = filter(r -> r != ZERO, P.rationals());
for (Rational r : take(LIMIT, rs)) {
Rational inverseR = r.invert();
validate(inverseR);
assertEquals(r.toString(), inverseR, invert_simplest(r));
assertEquals(r.toString(), r, inverseR.invert());
assertTrue(r.multiply(inverseR) == ONE);
assertTrue(inverseR != ZERO);
}
rs = filter(r -> r != ZERO && r.abs() != ONE, P.rationals());
for (Rational r : take(LIMIT, rs)) {
Rational inverseR = r.invert();
assertTrue(r.toString(), !r.equals(inverseR));
}
}
private static void compareImplementationsInvert() {
initialize();
System.out.println("\t\tcomparing invert() implementations...");
long totalTime = 0;
Iterable<Rational> rs = filter(r -> r != ZERO, P.rationals());
for (Rational r : take(LIMIT, rs)) {
long time = System.nanoTime();
invert_simplest(r);
totalTime += (System.nanoTime() - time);
}
System.out.println("\t\t\tsimplest: " + ((double) totalTime) / 1e9 + " s");
totalTime = 0;
for (Rational r : take(LIMIT, rs)) {
long time = System.nanoTime();
r.invert();
totalTime += (System.nanoTime() - time);
}
System.out.println("\t\t\tstandard: " + ((double) totalTime) / 1e9 + " s");
}
private static @NotNull Rational divide_Rational_simplest(@NotNull Rational a, @NotNull Rational b) {
return of(a.getNumerator().multiply(b.getDenominator()), a.getDenominator().multiply(b.getNumerator()));
}
private static void propertiesDivide_Rational() {
initialize();
System.out.println("\t\ttesting divide(Rational) properties...");
Iterable<Pair<Rational, Rational>> ps = filter(p -> p.b != ZERO, P.pairs(P.rationals()));
for (Pair<Rational, Rational> p : take(LIMIT, ps)) {
Rational quotient = p.a.divide(p.b);
validate(quotient);
assertEquals(p.toString(), quotient, divide_Rational_simplest(p.a, p.b));
assertEquals(p.toString(), p.a, quotient.multiply(p.b));
assertEquals(p.toString(), quotient, p.a.multiply(p.b.invert()));
}
ps = filter(p -> p.a != ZERO && p.b != ZERO, P.pairs(P.rationals()));
for (Pair<Rational, Rational> p : take(LIMIT, ps)) {
assertEquals(p.toString(), p.a.divide(p.b), p.b.divide(p.a).invert());
}
for (Rational r : take(LIMIT, P.rationals())) {
assertEquals(r.toString(), r.divide(ONE), r);
}
Iterable<Rational> rs = filter(r -> r != ZERO, P.rationals());
for (Rational r : take(LIMIT, rs)) {
assertEquals(r.toString(), ONE.divide(r), r.invert());
assertTrue(r.toString(), r.divide(r) == ONE);
}
for (Rational r : take(LIMIT, P.rationals())) {
try {
r.divide(ZERO);
fail(r.toString());
} catch (ArithmeticException ignored) {}
}
}
private static void compareImplementationsDivide_Rational() {
initialize();
System.out.println("\t\tcomparing divide(Rational) implementations...");
long totalTime = 0;
Iterable<Pair<Rational, Rational>> ps = filter(p -> p.b != ZERO, P.pairs(P.rationals()));
for (Pair<Rational, Rational> p : take(LIMIT, ps)) {
long time = System.nanoTime();
divide_Rational_simplest(p.a, p.b);
totalTime += (System.nanoTime() - time);
}
System.out.println("\t\t\tsimplest: " + ((double) totalTime) / 1e9 + " s");
totalTime = 0;
for (Pair<Rational, Rational> p : take(LIMIT, ps)) {
long time = System.nanoTime();
p.a.divide(p.b);
totalTime += (System.nanoTime() - time);
}
System.out.println("\t\t\tstandard: " + ((double) totalTime) / 1e9 + " s");
}
private static @NotNull Rational divide_BigInteger_simplest(@NotNull Rational a, @NotNull BigInteger b) {
return of(a.getNumerator(), a.getDenominator().multiply(b));
}
private static void propertiesDivide_BigInteger() {
initialize();
System.out.println("\t\ttesting divide(BigInteger) properties...");
Iterable<Pair<Rational, BigInteger>> ps = P.pairs(
P.rationals(),
filter(i -> !i.equals(BigInteger.ZERO), P.bigIntegers())
);
for (Pair<Rational, BigInteger> p : take(LIMIT, ps)) {
Rational quotient = p.a.divide(p.b);
validate(quotient);
assertEquals(p.toString(), quotient, divide_BigInteger_simplest(p.a, p.b));
assertEquals(p.toString(), p.a, quotient.multiply(p.b));
}
ps = P.pairs(
filter(r -> r != ZERO, P.rationals()),
filter(i -> !i.equals(BigInteger.ZERO), P.bigIntegers())
);
for (Pair<Rational, BigInteger> p : take(LIMIT, ps)) {
assertEquals(p.toString(), p.a.divide(p.b), of(p.b).divide(p.a).invert());
}
Iterable<BigInteger> bis = filter(i -> !i.equals(BigInteger.ZERO), P.bigIntegers());
for (BigInteger i : take(LIMIT, bis)) {
assertEquals(i.toString(), ONE.divide(i), of(i).invert());
assertEquals(i.toString(), of(i).divide(i), ONE);
}
for (Rational r : take(LIMIT, P.rationals())) {
assertEquals(r.toString(), r.divide(BigInteger.ONE), r);
}
for (Rational r : take(LIMIT, P.rationals())) {
try {
r.divide(BigInteger.ZERO);
fail(r.toString());
} catch (ArithmeticException ignored) {}
}
}
private static void compareImplementationsDivide_BigInteger() {
initialize();
System.out.println("\t\tcomparing divide(BigInteger) implementations...");
long totalTime = 0;
Iterable<Pair<Rational, BigInteger>> ps = P.pairs(
P.rationals(),
filter(i -> !i.equals(BigInteger.ZERO), P.bigIntegers())
);
for (Pair<Rational, BigInteger> p : take(LIMIT, ps)) {
long time = System.nanoTime();
divide_BigInteger_simplest(p.a, p.b);
totalTime += (System.nanoTime() - time);
}
System.out.println("\t\t\tsimplest: " + ((double) totalTime) / 1e9 + " s");
totalTime = 0;
for (Pair<Rational, BigInteger> p : take(LIMIT, ps)) {
long time = System.nanoTime();
p.a.divide(p.b);
totalTime += (System.nanoTime() - time);
}
System.out.println("\t\t\tstandard: " + ((double) totalTime) / 1e9 + " s");
}
private static @NotNull Rational divide_int_simplest(@NotNull Rational a, int b) {
return of(a.getNumerator(), a.getDenominator().multiply(BigInteger.valueOf(b)));
}
private static void propertiesDivide_int() {
initialize();
System.out.println("\t\ttesting divide(int) properties...");
Iterable<Pair<Rational, Integer>> ps = P.pairs(P.rationals(), filter(i -> i != 0, P.integers()));
for (Pair<Rational, Integer> p : take(LIMIT, ps)) {
Rational quotient = p.a.divide(p.b);
validate(quotient);
assertEquals(p.toString(), quotient, divide_int_simplest(p.a, p.b));
assertEquals(p.toString(), p.a, quotient.multiply(p.b));
}
ps = P.pairs(filter(r -> r != ZERO, P.rationals()), filter(i -> i != 0, P.integers()));
for (Pair<Rational, Integer> p : take(LIMIT, ps)) {
assertEquals(p.toString(), p.a.divide(p.b), of(p.b).divide(p.a).invert());
}
Iterable<Integer> is = filter(i -> i != 0, P.integers());
for (int i : take(LIMIT, is)) {
assertEquals(Integer.toString(i), ONE.divide(i), of(i).invert());
assertEquals(Integer.toString(i), of(i).divide(i), ONE);
}
for (Rational r : take(LIMIT, P.rationals())) {
assertEquals(r.toString(), r.divide(1), r);
}
for (Rational r : take(LIMIT, P.rationals())) {
try {
r.divide(0);
fail(r.toString());
} catch (ArithmeticException ignored) {}
}
}
private static void compareImplementationsDivide_int() {
initialize();
System.out.println("\t\tcomparing divide(int) implementations...");
long totalTime = 0;
Iterable<Pair<Rational, Integer>> ps = P.pairs(P.rationals(), filter(i -> i != 0, P.integers()));
for (Pair<Rational, Integer> p : take(LIMIT, ps)) {
long time = System.nanoTime();
divide_int_simplest(p.a, p.b);
totalTime += (System.nanoTime() - time);
}
System.out.println("\t\t\tsimplest: " + ((double) totalTime) / 1e9 + " s");
totalTime = 0;
for (Pair<Rational, Integer> p : take(LIMIT, ps)) {
long time = System.nanoTime();
p.a.divide(p.b);
totalTime += (System.nanoTime() - time);
}
System.out.println("\t\t\tstandard: " + ((double) totalTime) / 1e9 + " s");
}
private static @NotNull Rational shiftLeft_simplest(@NotNull Rational r, int bits) {
if (bits < 0) {
return r.divide(BigInteger.ONE.shiftLeft(-bits));
} else {
return r.multiply(BigInteger.ONE.shiftLeft(bits));
}
}
private static void propertiesShiftLeft() {
initialize();
System.out.println("\t\ttesting shiftLeft(int) properties...");
Iterable<Integer> is;
if (P instanceof QBarExhaustiveProvider) {
is = P.integers();
} else {
is = ((QBarRandomProvider) P).integersGeometric(50);
}
for (Pair<Rational, Integer> p : take(LIMIT, P.pairs(P.rationals(), is))) {
Rational shifted = p.a.shiftLeft(p.b);
validate(shifted);
assertEquals(p.toString(), shifted, shiftLeft_simplest(p.a, p.b));
assertEquals(p.toString(), p.a.signum(), shifted.signum());
assertEquals(p.toString(), p.a.negate().shiftLeft(p.b), shifted.negate());
assertEquals(p.toString(), shifted, p.a.shiftRight(-p.b));
}
if (P instanceof QBarExhaustiveProvider) {
is = P.naturalIntegers();
} else {
is = ((QBarRandomProvider) P).naturalIntegersGeometric(50);
}
for (Pair<Rational, Integer> p : take(LIMIT, P.pairs(P.rationals(), is))) {
Rational shifted = p.a.shiftLeft(p.b);
assertEquals(p.toString(), shifted, p.a.multiply(BigInteger.ONE.shiftLeft(p.b)));
}
}
private static void compareImplementationsShiftLeft() {
initialize();
System.out.println("\t\tcomparing shiftLeft(int) implementations...");
long totalTime = 0;
Iterable<Integer> is;
if (P instanceof QBarExhaustiveProvider) {
is = P.integers();
} else {
is = ((QBarRandomProvider) P).integersGeometric(50);
}
for (Pair<Rational, Integer> p : take(LIMIT, P.pairs(P.rationals(), is))) {
long time = System.nanoTime();
shiftLeft_simplest(p.a, p.b);
totalTime += (System.nanoTime() - time);
}
System.out.println("\t\t\tsimplest: " + ((double) totalTime) / 1e9 + " s");
totalTime = 0;
for (Pair<Rational, Integer> p : take(LIMIT, P.pairs(P.rationals(), is))) {
long time = System.nanoTime();
p.a.shiftLeft(p.b);
totalTime += (System.nanoTime() - time);
}
System.out.println("\t\t\tstandard: " + ((double) totalTime) / 1e9 + " s");
}
private static @NotNull Rational shiftRight_simplest(@NotNull Rational r, int bits) {
if (bits < 0) {
return r.multiply(BigInteger.ONE.shiftLeft(-bits));
} else {
return r.divide(BigInteger.ONE.shiftLeft(bits));
}
}
private static void propertiesShiftRight() {
initialize();
System.out.println("\t\ttesting shiftRight(int) properties...");
Iterable<Integer> is;
if (P instanceof QBarExhaustiveProvider) {
is = P.integers();
} else {
is = ((QBarRandomProvider) P).integersGeometric(50);
}
for (Pair<Rational, Integer> p : take(LIMIT, P.pairs(P.rationals(), is))) {
Rational shifted = p.a.shiftRight(p.b);
validate(shifted);
assertEquals(p.toString(), shifted, shiftRight_simplest(p.a, p.b));
assertEquals(p.toString(), p.a.signum(), shifted.signum());
assertEquals(p.toString(), p.a.negate().shiftRight(p.b), shifted.negate());
assertEquals(p.toString(), shifted, p.a.shiftLeft(-p.b));
}
if (P instanceof QBarExhaustiveProvider) {
is = P.naturalIntegers();
} else {
is = ((QBarRandomProvider) P).naturalIntegersGeometric(50);
}
for (Pair<Rational, Integer> p : take(LIMIT, P.pairs(P.rationals(), is))) {
Rational shifted = p.a.shiftRight(p.b);
assertEquals(p.toString(), shifted, p.a.divide(BigInteger.ONE.shiftLeft(p.b)));
}
}
private static void compareImplementationsShiftRight() {
initialize();
System.out.println("\t\tcomparing shiftRight(int) implementations...");
long totalTime = 0;
Iterable<Integer> is;
if (P instanceof QBarExhaustiveProvider) {
is = P.integers();
} else {
is = ((QBarRandomProvider) P).integersGeometric(50);
}
for (Pair<Rational, Integer> p : take(LIMIT, P.pairs(P.rationals(), is))) {
long time = System.nanoTime();
shiftRight_simplest(p.a, p.b);
totalTime += (System.nanoTime() - time);
}
System.out.println("\t\t\tsimplest: " + ((double) totalTime) / 1e9 + " s");
totalTime = 0;
for (Pair<Rational, Integer> p : take(LIMIT, P.pairs(P.rationals(), is))) {
long time = System.nanoTime();
p.a.shiftRight(p.b);
totalTime += (System.nanoTime() - time);
}
System.out.println("\t\t\tstandard: " + ((double) totalTime) / 1e9 + " s");
}
private static @NotNull Rational sum_alt(@NotNull Iterable<Rational> xs) {
List<Rational> denominatorSorted = sort(
(x, y) -> {
Ordering o = compare(x.getDenominator(), y.getDenominator());
if (o == EQ) {
o = compare(x.getNumerator().abs(), y.getNumerator().abs());
}
if (o == EQ) {
o = compare(x.getNumerator().signum(), y.getNumerator().signum());
}
return o.toInt();
},
xs
);
Iterable<List<Rational>> denominatorGrouped = group(
p -> p.a.getDenominator().equals(p.b.getDenominator()),
denominatorSorted
);
Rational sum = ZERO;
for (List<Rational> group : denominatorGrouped) {
BigInteger numeratorSum = sumBigInteger(map(Rational::getNumerator, group));
sum = sum.add(of(numeratorSum, head(group).getDenominator()));
}
return sum;
}
private static void propertiesSum() {
initialize();
System.out.println("\t\ttesting sum(Iterable<Rational>) properties...");
for (List<Rational> rs : take(LIMIT, P.lists(P.rationals()))) {
Rational sum = sum(rs);
validate(sum);
assertEquals(rs.toString(), sum, sum_alt(rs));
}
Iterable<Pair<List<Rational>, List<Rational>>> ps = filter(
q -> !q.a.equals(q.b),
P.dependentPairsLogarithmic(P.lists(P.rationals()), Combinatorics::permutationsIncreasing)
);
for (Pair<List<Rational>, List<Rational>> p : take(LIMIT, ps)) {
assertEquals(p.toString(), sum(p.a), sum(p.b));
}
for (Rational r : take(LIMIT, P.rationals())) {
assertEquals(r.toString(), sum(Arrays.asList(r)), r);
}
for (Pair<Rational, Rational> p : take(LIMIT, P.pairs(P.rationals()))) {
assertEquals(p.toString(), sum(Arrays.asList(p.a, p.b)), p.a.add(p.b));
}
Iterable<List<Rational>> failRss = map(
p -> toList(insert(p.a, p.b, null)),
(Iterable<Pair<List<Rational>, Integer>>) P.dependentPairsLogarithmic(
P.lists(P.rationals()),
rs -> range(0, rs.size())
)
);
for (List<Rational> rs : take(LIMIT, failRss)) {
try {
sum(rs);
fail(rs.toString());
} catch (IllegalArgumentException ignored) {}
}
}
private static void compareImplementationsSum() {
initialize();
System.out.println("\t\tcomparing sum(Iterable<Rational>) implementations...");
long totalTime = 0;
for (List<Rational> rs : take(LIMIT, P.lists(P.rationals()))) {
long time = System.nanoTime();
sum_alt(rs);
totalTime += (System.nanoTime() - time);
}
System.out.println("\t\t\talt: " + ((double) totalTime) / 1e9 + " s");
totalTime = 0;
for (List<Rational> rs : take(LIMIT, P.lists(P.rationals()))) {
long time = System.nanoTime();
sum(rs);
totalTime += (System.nanoTime() - time);
}
System.out.println("\t\t\tstandard: " + ((double) totalTime) / 1e9 + " s");
}
private static @NotNull Rational product_simplest(@NotNull Iterable<Rational> xs) {
return foldl(p -> p.a.multiply(p.b), ONE, xs);
}
private static void propertiesProduct() {
initialize();
System.out.println("\t\ttesting product(Iterable<Rational>) properties...");
for (List<Rational> rs : take(LIMIT, P.lists(P.rationals()))) {
Rational product = product(rs);
validate(product);
assertEquals(rs.toString(), product, product_simplest(rs));
}
Iterable<Pair<List<Rational>, List<Rational>>> ps = filter(
q -> !q.a.equals(q.b),
P.dependentPairsLogarithmic(P.lists(P.rationals()), Combinatorics::permutationsIncreasing)
);
for (Pair<List<Rational>, List<Rational>> p : take(LIMIT, ps)) {
assertEquals(p.toString(), product(p.a), product(p.b));
}
for (Rational r : take(LIMIT, P.rationals())) {
assertEquals(r.toString(), product(Arrays.asList(r)), r);
}
for (Pair<Rational, Rational> p : take(LIMIT, P.pairs(P.rationals()))) {
assertEquals(p.toString(), product(Arrays.asList(p.a, p.b)), p.a.multiply(p.b));
}
Iterable<List<Rational>> failRss = map(
p -> toList(insert(p.a, p.b, null)),
P.dependentPairsLogarithmic(P.lists(P.rationals()), rs -> range(0, rs.size()))
);
for (List<Rational> rs : take(LIMIT, failRss)) {
try {
product(rs);
fail(rs.toString());
} catch (NullPointerException | IllegalArgumentException ignored) {}
}
}
private static void compareImplementationsProduct() {
initialize();
System.out.println("\t\tcomparing product(Iterable<Rational>) implementations...");
long totalTime = 0;
for (List<Rational> rs : take(LIMIT, P.lists(P.rationals()))) {
long time = System.nanoTime();
product_simplest(rs);
totalTime += (System.nanoTime() - time);
}
System.out.println("\t\t\tsimplest: " + ((double) totalTime) / 1e9 + " s");
totalTime = 0;
for (List<Rational> rs : take(LIMIT, P.lists(P.rationals()))) {
long time = System.nanoTime();
product(rs);
totalTime += (System.nanoTime() - time);
}
System.out.println("\t\t\tstandard: " + ((double) totalTime) / 1e9 + " s");
}
private static void propertiesDelta() {
initialize();
System.out.println("\t\ttesting delta(Iterable<Rational>) properties...");
for (List<Rational> rs : take(LIMIT, P.listsAtLeast(1, P.rationals()))) {
Iterable<Rational> deltas = delta(rs);
deltas.forEach(mho.qbar.objects.RationalProperties::validate);
assertEquals(rs.toString(), length(deltas), length(rs) - 1);
List<Rational> reversed = reverse(map(Rational::negate, delta(reverse(rs))));
aeq(rs.toString(), deltas, reversed);
try {
deltas.iterator().remove();
} catch (UnsupportedOperationException ignored) {}
}
for (Rational r : take(LIMIT, P.rationals())) {
assertTrue(r.toString(), isEmpty(delta(Arrays.asList(r))));
}
for (Pair<Rational, Rational> p : take(LIMIT, P.pairs(P.rationals()))) {
aeq(p.toString(), delta(Arrays.asList(p.a, p.b)), Arrays.asList(p.b.subtract(p.a)));
}
Iterable<List<Rational>> failRss = map(
p -> toList(insert(p.a, p.b, null)),
(Iterable<Pair<List<Rational>, Integer>>) P.dependentPairsLogarithmic(
P.lists(P.rationals()),
rs -> range(0, rs.size())
)
);
for (List<Rational> rs : take(LIMIT, failRss)) {
try {
toList(delta(rs));
fail(rs.toString());
} catch (AssertionError | NullPointerException ignored) {}
}
}
private static void propertiesHarmonicNumber() {
initialize();
System.out.println("\t\ttesting harmonicNumber(int) properties...");
Iterable<Integer> is;
if (P instanceof ExhaustiveProvider) {
is = P.positiveIntegers();
} else {
is = ((RandomProvider) P).positiveIntegersGeometric(100);
}
for (int i : take(SMALL_LIMIT, is)) {
Rational h = harmonicNumber(i);
validate(h);
assertTrue(Integer.toString(i), ge(h, ONE));
}
is = map(i -> i + 1, is);
for (int i : take(SMALL_LIMIT, is)) {
Rational h = harmonicNumber(i);
assertTrue(Integer.toString(i), gt(h, harmonicNumber(i - 1)));
assertFalse(Integer.toString(i), h.isInteger());
}
for (int i : take(LIMIT, P.rangeDown(0))) {
try {
harmonicNumber(i);
fail(Integer.toString(i));
} catch (ArithmeticException ignored) {}
}
}
private static @NotNull Rational pow_simplest(@NotNull Rational a, int p) {
Rational result = product(replicate(Math.abs(p), a));
return p < 0 ? result.invert() : result;
}
private static void propertiesPow() {
initialize();
System.out.println("\t\ttesting pow(int) properties...");
Iterable<Integer> exps;
if (P instanceof QBarExhaustiveProvider) {
exps = P.integers();
} else {
exps = ((RandomProvider) P).integersGeometric(20);
}
Iterable<Pair<Rational, Integer>> ps = filter(p -> p.b >= 0 || p.a != ZERO, P.pairs(P.rationals(), exps));
for (Pair<Rational, Integer> p : take(LIMIT, ps)) {
Rational r = p.a.pow(p.b);
validate(r);
assertEquals(p.toString(), r, pow_simplest(p.a, p.b));
}
ps = P.pairs(filter(r -> r != ZERO, P.rationals()), exps);
for (Pair<Rational, Integer> p : take(LIMIT, ps)) {
Rational r
= p.a.pow(p.b);
assertEquals(p.toString(), r, p.a.pow(-p.b).invert());
assertEquals(p.toString(), r, p.a.invert().pow(-p.b));
}
Iterable<Integer> pexps;
if (P instanceof QBarExhaustiveProvider) {
pexps = P.positiveIntegers();
} else {
pexps = ((RandomProvider) P).positiveIntegersGeometric(20);
}
for (int i : take(LIMIT, pexps)) {
assertTrue(Integer.toString(i), ZERO.pow(i) == ZERO);
}
for (Rational r : take(LIMIT, P.rationals())) {
assertTrue(r.toString(), r.pow(0) == ONE);
assertEquals(r.toString(), r.pow(1), r);
assertEquals(r.toString(), r.pow(2), r.multiply(r));
}
Iterable<Rational> rs = filter(r -> r != ZERO, P.rationals());
for (Rational r : take(LIMIT, rs)) {
assertEquals(r.toString(), r.pow(-1), r.invert());
}
Iterable<Triple<Rational, Integer, Integer>> ts1 = filter(
p -> p.b >= 0 && p.c >= 0 || p.a != ZERO,
P.triples(P.rationals(), exps, exps)
);
for (Triple<Rational, Integer, Integer> t : take(LIMIT, ts1)) {
Rational expression1 = t.a.pow(t.b).multiply(t.a.pow(t.c));
Rational expression2 = t.a.pow(t.b + t.c);
assertEquals(t.toString(), expression1, expression2);
}
ts1 = filter(
t -> t.a != ZERO || t.c == 0 && t.b >= 0,
P.triples(P.rationals(), exps, exps)
);
for (Triple<Rational, Integer, Integer> t : take(LIMIT, ts1)) {
Rational expression1 = t.a.pow(t.b).divide(t.a.pow(t.c));
Rational expression2 = t.a.pow(t.b - t.c);
assertEquals(t.toString(), expression1, expression2);
}
ts1 = filter(
t -> t.a != ZERO || t.b >= 0 && t.c >= 0,
P.triples(P.rationals(), exps, exps)
);
for (Triple<Rational, Integer, Integer> t : take(LIMIT, ts1)) {
Rational expression5 = t.a.pow(t.b).pow(t.c);
Rational expression6 = t.a.pow(t.b * t.c);
assertEquals(t.toString(), expression5, expression6);
}
Iterable<Triple<Rational, Rational, Integer>> ts2 = filter(
t -> t.a != ZERO && t.b != ZERO || t.c >= 0,
P.triples(P.rationals(), P.rationals(), exps)
);
for (Triple<Rational, Rational, Integer> t : take(LIMIT, ts2)) {
Rational expression1 = t.a.multiply(t.b).pow(t.c);
Rational expression2 = t.a.pow(t.c).multiply(t.b.pow(t.c));
assertEquals(t.toString(), expression1, expression2);
}
ts2 = filter(
t -> t.a != ZERO || t.c >= 0,
P.triples(P.rationals(), filter(r -> r != ZERO, P.rationals()), exps)
);
for (Triple<Rational, Rational, Integer> t : take(LIMIT, ts2)) {
Rational expression1 = t.a.divide(t.b).pow(t.c);
Rational expression2 = t.a.pow(t.c).divide(t.b.pow(t.c));
assertEquals(t.toString(), expression1, expression2);
}
for (int i : take(LIMIT, P.negativeIntegers())) {
try {
ZERO.pow(i);
fail(Integer.toString(i));
} catch (ArithmeticException ignored) {}
}
}
private static void compareImplementationsPow() {
initialize();
System.out.println("\t\tcomparing pow(int) implementations...");
long totalTime = 0;
Iterable<Integer> exps;
if (P instanceof QBarExhaustiveProvider) {
exps = P.integers();
} else {
exps = ((RandomProvider) P).integersGeometric(20);
}
Iterable<Pair<Rational, Integer>> ps = filter(p -> p.b >= 0 || p.a != ZERO, P.pairs(P.rationals(), exps));
for (Pair<Rational, Integer> p : take(LIMIT, ps)) {
long time = System.nanoTime();
pow_simplest(p.a, p.b);
totalTime += (System.nanoTime() - time);
}
System.out.println("\t\t\tsimplest: " + ((double) totalTime) / 1e9 + " s");
totalTime = 0;
for (Pair<Rational, Integer> p : take(LIMIT, ps)) {
long time = System.nanoTime();
p.a.pow(p.b);
totalTime += (System.nanoTime() - time);
}
System.out.println("\t\t\tstandard: " + ((double) totalTime) / 1e9 + " s");
}
private static void propertiesFloor() {
initialize();
System.out.println("\t\ttesting floor() properties...");
for (Rational r : take(LIMIT, P.rationals())) {
BigInteger floor = r.floor();
assertTrue(r.toString(), le(of(floor), r));
assertTrue(r.toString(), le(r.subtract(of(floor)), ONE));
}
for (BigInteger i : take(LIMIT, P.bigIntegers())) {
assertEquals(i.toString(), of(i).floor(), i);
}
}
private static void propertiesCeiling() {
initialize();
System.out.println("\t\ttesting ceiling() properties...");
for (Rational r : take(LIMIT, P.rationals())) {
BigInteger ceiling = r.ceiling();
assertTrue(r.toString(), ge(of(ceiling), r));
assertTrue(r.toString(), le(of(ceiling).subtract(r), ONE));
}
for (BigInteger i : take(LIMIT, P.bigIntegers())) {
assertEquals(i.toString(), of(i).ceiling(), i);
}
}
private static void propertiesFractionalPart() {
initialize();
System.out.println("\t\ttesting fractionalPart() properties...");
for (Rational r : take(LIMIT, P.rationals())) {
Rational fractionalPart = r.fractionalPart();
validate(fractionalPart);
assertTrue(r.toString(), ge(fractionalPart, ZERO));
assertTrue(r.toString(), lt(fractionalPart, ONE));
assertEquals(r.toString(), of(r.floor()).add(fractionalPart), r);
}
for (BigInteger i : take(LIMIT, P.bigIntegers())) {
assertEquals(i.toString(), of(i).fractionalPart(), ZERO);
}
}
private static void propertiesRoundToDenominator() {
initialize();
System.out.println("\t\ttesting roundToDenominator(BigInteger, RoundingMode) properties...");
Iterable<Triple<Rational, BigInteger, RoundingMode>> ts = filter(
p -> p.c != RoundingMode.UNNECESSARY || p.b.mod(p.a.getDenominator()).equals(BigInteger.ZERO),
P.triples(P.rationals(), P.positiveBigIntegers(), P.roundingModes())
);
for (Triple<Rational, BigInteger, RoundingMode> t : take(LIMIT, ts)) {
Rational rounded = t.a.roundToDenominator(t.b, t.c);
validate(rounded);
assertEquals(t.toString(), t.b.mod(rounded.getDenominator()), BigInteger.ZERO);
assertTrue(t.toString(), rounded == ZERO || rounded.signum() == t.a.signum());
assertTrue(t.toString(), lt(t.a.subtract(rounded).abs(), of(BigInteger.ONE, t.b)));
}
Iterable<Pair<Rational, RoundingMode>> ps1 = filter(
p -> p.b != RoundingMode.UNNECESSARY || p.a.isInteger(),
P.pairs(P.rationals(), P.roundingModes())
);
for (Pair<Rational, RoundingMode> p : take(LIMIT, ps1)) {
Rational rounded = p.a.roundToDenominator(BigInteger.ONE, p.b);
assertEquals(p.toString(), rounded.getNumerator(), p.a.bigIntegerValue(p.b));
assertEquals(p.toString(), rounded.getDenominator(), BigInteger.ONE);
}
Iterable<Pair<Rational, BigInteger>> ps2 = filter(
p -> p.b.mod(p.a.getDenominator()).equals(BigInteger.ZERO),
P.pairs(P.rationals(), P.positiveBigIntegers())
);
for (Pair<Rational, BigInteger> p : take(LIMIT, ps2)) {
assertTrue(p.toString(), p.a.roundToDenominator(p.b, RoundingMode.UNNECESSARY).equals(p.a));
}
ps2 = P.pairs(P.rationals(), P.positiveBigIntegers());
for (Pair<Rational, BigInteger> p : take(LIMIT, ps2)) {
assertTrue(p.toString(), le(p.a.roundToDenominator(p.b, RoundingMode.FLOOR), p.a));
assertTrue(p.toString(), ge(p.a.roundToDenominator(p.b, RoundingMode.CEILING), p.a));
assertTrue(p.toString(), le(p.a.roundToDenominator(p.b, RoundingMode.DOWN).abs(), p.a.abs()));
assertTrue(p.toString(), ge(p.a.roundToDenominator(p.b, RoundingMode.UP).abs(), p.a.abs()));
assertTrue(
p.toString(),
le(
p.a.subtract(p.a.roundToDenominator(p.b, RoundingMode.HALF_DOWN)).abs(),
of(p.b).shiftLeft(1).invert()
)
);
assertTrue(
p.toString(),
le(
p.a.subtract(p.a.roundToDenominator(p.b, RoundingMode.HALF_UP)).abs(),
of(p.b).shiftLeft(1).invert()
)
);
assertTrue(
p.toString(),
le(
p.a.subtract(p.a.roundToDenominator(p.b, RoundingMode.HALF_EVEN)).abs(),
of(p.b).shiftLeft(1).invert()
)
);
}
ps2 = filter(
p -> lt(p.a.abs().multiply(p.b).fractionalPart(), of(1, 2)),
P.pairs(P.rationals(), P.positiveBigIntegers())
);
for (Pair<Rational, BigInteger> p : take(LIMIT, ps2)) {
assertEquals(
p.toString(),
p.a.roundToDenominator(p.b, RoundingMode.HALF_DOWN),
p.a.roundToDenominator(p.b, RoundingMode.DOWN)
);
assertEquals(
p.toString(),
p.a.roundToDenominator(p.b, RoundingMode.HALF_UP),
p.a.roundToDenominator(p.b, RoundingMode.DOWN)
);
assertEquals(
p.toString(),
p.a.roundToDenominator(p.b, RoundingMode.HALF_EVEN),
p.a.roundToDenominator(p.b, RoundingMode.DOWN)
);
}
ps2 = filter(
p -> gt(p.a.abs().multiply(p.b).fractionalPart(), of(1, 2)),
P.pairs(P.rationals(), P.positiveBigIntegers())
);
for (Pair<Rational, BigInteger> p : take(LIMIT, ps2)) {
assertEquals(
p.toString(),
p.a.roundToDenominator(p.b, RoundingMode.HALF_DOWN),
p.a.roundToDenominator(p.b, RoundingMode.UP)
);
assertEquals(
p.toString(),
p.a.roundToDenominator(p.b, RoundingMode.HALF_UP),
p.a.roundToDenominator(p.b, RoundingMode.UP)
);
assertEquals(
p.toString(),
p.a.roundToDenominator(p.b, RoundingMode.HALF_EVEN),
p.a.roundToDenominator(p.b, RoundingMode.UP)
);
}
Iterable<Rational> rs = filter(r -> !r.getDenominator().testBit(0), P.rationals());
for (Rational r : take(LIMIT, rs)) {
BigInteger denominator = r.getDenominator().shiftRight(1);
assertEquals(r.toString(), r.abs().multiply(denominator).fractionalPart(), of(1, 2));
Rational hd = r.roundToDenominator(denominator, RoundingMode.HALF_DOWN);
assertEquals(r.toString(), hd, r.roundToDenominator(denominator, RoundingMode.DOWN));
Rational hu = r.roundToDenominator(denominator, RoundingMode.HALF_UP);
assertEquals(r.toString(), hu, r.roundToDenominator(denominator, RoundingMode.UP));
Rational he = r.roundToDenominator(denominator, RoundingMode.HALF_EVEN);
assertEquals(r.toString(), he.multiply(denominator).getNumerator().testBit(0), false);
}
Iterable<Triple<Rational, BigInteger, RoundingMode>> failTs = P.triples(
P.rationals(),
map(BigInteger::negate, P.naturalBigIntegers()),
P.roundingModes()
);
for (Triple<Rational, BigInteger, RoundingMode> t : take(LIMIT, failTs)) {
try {
t.a.roundToDenominator(t.b, t.c);
fail(t.toString());
} catch (ArithmeticException ignored) {}
}
Iterable<Pair<Rational, BigInteger>> failPs = filter(
p -> !p.b.mod(p.a.getDenominator()).equals(BigInteger.ZERO),
P.pairs(P.rationals(), P.positiveBigIntegers())
);
for (Pair<Rational, BigInteger> p : take(LIMIT, failPs)) {
try {
p.a.roundToDenominator(p.b, RoundingMode.UNNECESSARY);
fail(p.toString());
} catch (ArithmeticException ignored) {}
}
}
private static void propertiesContinuedFraction() {
initialize();
System.out.println("\t\ttesting continuedFraction() properties...");
for (Rational r : take(LIMIT, P.rationals())) {
List<BigInteger> continuedFraction = r.continuedFraction();
assertFalse(r.toString(), continuedFraction.isEmpty());
assertTrue(r.toString(), all(i -> i != null, continuedFraction));
assertTrue(r.toString(), all(i -> i.signum() == 1, tail(continuedFraction)));
assertEquals(r.toString(), r, fromContinuedFraction(continuedFraction));
}
for (Rational r : take(LIMIT, filter(s -> !s.isInteger(), P.rationals()))) {
List<BigInteger> continuedFraction = r.continuedFraction();
assertTrue(r.toString(), gt(last(continuedFraction), BigInteger.ONE));
}
}
private static void propertiesFromContinuedFraction() {
initialize();
System.out.println("\t\ttesting fromContinuedFraction(List<BigInteger>) properties...");
Iterable<List<BigInteger>> iss = map(
p -> toList(cons(p.a, p.b)),
(Iterable<Pair<BigInteger, List<BigInteger>>>) P.pairs(
P.bigIntegers(),
P.lists(P.positiveBigIntegers())
)
);
for (List<BigInteger> is : take(LIMIT, iss)) {
Rational r = fromContinuedFraction(is);
validate(r);
}
for (List<BigInteger> is : take(LIMIT, filter(js -> !last(js).equals(BigInteger.ONE), iss))) {
Rational r = fromContinuedFraction(is);
assertEquals(is.toString(), r.continuedFraction(), is);
}
Iterable<List<BigInteger>> failIss = filter(
is -> any(i -> i.signum() != 1, tail(is)),
P.listsAtLeast(1, P.bigIntegers())
);
for (List<BigInteger> is : take(LIMIT, failIss)) {
try {
fromContinuedFraction(is);
fail(is.toString());
} catch (IllegalArgumentException ignored) {}
}
}
private static void propertiesConvergents() {
initialize();
System.out.println("\t\ttesting convergents() properties...");
for (Rational r : take(LIMIT, P.rationals())) {
List<Rational> convergents = toList(r.convergents());
convergents.forEach(mho.qbar.objects.RationalProperties::validate);
assertFalse(r.toString(), convergents.isEmpty());
assertTrue(r.toString(), all(s -> s != null, convergents));
assertEquals(r.toString(), head(convergents), of(r.floor()));
assertEquals(r.toString(), last(convergents), r);
assertTrue(r.toString(), zigzagging(convergents));
}
}
private static @NotNull <T> Pair<List<T>, List<T>> minimize(@NotNull List<T> a, @NotNull List<T> b) {
List<T> oldA = new ArrayList<>();
List<T> oldB = new ArrayList<>();
while (!a.equals(oldA) || !b.equals(oldB)) {
int longestCommonSuffixLength = 0;
for (int i = 0; i < Math.min(a.size(), b.size()); i++) {
if (!a.get(a.size() - i - 1).equals(b.get(b.size() - i - 1))) break;
longestCommonSuffixLength++;
}
oldA = a;
oldB = b;
a = toList(take(a.size() - longestCommonSuffixLength, a));
b = unrepeat(rotateRight(longestCommonSuffixLength, b));
}
return new Pair<>(a, b);
}
private static void propertiesPositionalNotation() {
initialize();
System.out.println("\t\ttesting positionalNotation(BigInteger) properties...");
Iterable<Pair<Rational, BigInteger>> ps;
if (P instanceof ExhaustiveProvider) {
ps = ((ExhaustiveProvider) P).pairsSquareRootOrder(
cons(ZERO, P.positiveRationals()),
P.rangeUp(BigInteger.valueOf(2))
);
} else {
ps = P.pairs(
cons(ZERO, ((QBarRandomProvider) P).positiveRationals(8)),
map(i -> BigInteger.valueOf(i + 2), ((RandomProvider) P).naturalIntegersGeometric(20))
);
}
for (Pair<Rational, BigInteger> p : take(LIMIT, ps)) {
Triple<List<BigInteger>, List<BigInteger>, List<BigInteger>> pn = p.a.positionalNotation(p.b);
for (List<BigInteger> is : Arrays.asList(pn.a, pn.b, pn.c)) {
assertTrue(p.toString(), all(i -> i != null && i.signum() != -1 && lt(i, p.b), is));
}
assertTrue(p.toString(), pn.a.isEmpty() || !head(pn.a).equals(BigInteger.ZERO));
assertFalse(p.toString(), pn.c.isEmpty());
assertNotEquals(p.toString(), pn.c, Arrays.asList(p.b.subtract(BigInteger.ONE)));
Pair<List<BigInteger>, List<BigInteger>> minimized = minimize(pn.b, pn.c);
assertEquals(p.toString(), minimized.a, pn.b);
assertEquals(p.toString(), minimized.b, pn.c);
assertEquals(p.toString(), fromPositionalNotation(p.b, pn.a, pn.b, pn.c), p.a);
assertEquals(
p.toString(),
pn.c.equals(Arrays.asList(BigInteger.ZERO)),
p.a.hasTerminatingBaseExpansion(p.b)
);
}
Iterable<Pair<Rational, BigInteger>> psFail = P.pairs(P.negativeRationals(), P.rangeUp(BigInteger.valueOf(2)));
for (Pair<Rational, BigInteger> p : take(LIMIT, psFail)) {
try {
p.a.positionalNotation(p.b);
fail(p.toString());
} catch (IllegalArgumentException ignored) {}
}
for (Pair<Rational, BigInteger> p : take(LIMIT, P.pairs(P.rationals(), P.rangeDown(BigInteger.ONE)))) {
try {
p.a.positionalNotation(p.b);
fail(p.toString());
} catch (IllegalArgumentException ignored) {}
}
}
private static void propertiesFromPositionalNotation() {
initialize();
System.out.println(
"\t\ttesting fromPositionalNotation(BigInteger, List<BigInteger>, List<BigInteger>," +
" List<BigInteger>) properties...");
Iterable<BigInteger> bases;
if (P instanceof ExhaustiveProvider) {
bases = P.rangeUp(BigInteger.valueOf(2));
} else {
bases = map(i -> BigInteger.valueOf(i + 2), ((RandomProvider) P).naturalIntegersGeometric(20));
}
Iterable<Pair<BigInteger, Triple<List<BigInteger>, List<BigInteger>, List<BigInteger>>>> ps = P.dependentPairs(
bases,
b -> filter(
t -> !t.c.isEmpty(),
P.triples(P.lists(P.range(BigInteger.ZERO, b.subtract(BigInteger.ONE))))
)
);
for (Pair<BigInteger, Triple<List<BigInteger>, List<BigInteger>, List<BigInteger>>> p : take(LIMIT, ps)) {
Rational r = fromPositionalNotation(p.a, p.b.a, p.b.b, p.b.c);
validate(r);
assertNotEquals(p.toString(), r.signum(), -1);
}
ps = filter(
p -> {
if (!p.b.a.isEmpty() && head(p.b.a).equals(BigInteger.ZERO)) return false;
Pair<List<BigInteger>, List<BigInteger>> minimized = minimize(p.b.b, p.b.c);
//noinspection SimplifiableIfStatement
if (!minimized.a.equals(p.b.b) || !minimized.b.equals(p.b.c)) return false;
return !p.b.c.equals(Arrays.asList(p.a.subtract(BigInteger.ONE)));
},
ps
);
for (Pair<BigInteger, Triple<List<BigInteger>, List<BigInteger>, List<BigInteger>>> p : take(LIMIT, ps)) {
Rational r = fromPositionalNotation(p.a, p.b.a, p.b.b, p.b.c);
assertEquals(p.toString(), r.positionalNotation(p.a), p.b);
}
Iterable<Pair<BigInteger, Triple<List<BigInteger>, List<BigInteger>, List<BigInteger>>>> psFail = P.pairs(
P.rangeDown(BigInteger.ONE),
filter(t -> !t.c.isEmpty(), P.triples(P.lists(P.bigIntegers())))
);
for (Pair<BigInteger, Triple<List<BigInteger>, List<BigInteger>, List<BigInteger>>> p : take(LIMIT, psFail)) {
try {
fromPositionalNotation(p.a, p.b.a, p.b.b, p.b.c);
fail(p.toString());
} catch (IllegalArgumentException ignored) {}
}
psFail = P.dependentPairs(
P.rangeUp(BigInteger.valueOf(2)),
b -> filter(
t -> !t.c.isEmpty() && any(x -> x.signum() == -1 || ge(x, b), t.a),
P.triples(P.lists(P.bigIntegers()))
)
);
for (Pair<BigInteger, Triple<List<BigInteger>, List<BigInteger>, List<BigInteger>>> p : take(LIMIT, psFail)) {
try {
fromPositionalNotation(p.a, p.b.a, p.b.b, p.b.c);
fail(p.toString());
} catch (IllegalArgumentException ignored) {}
}
psFail = P.dependentPairs(
P.rangeUp(BigInteger.valueOf(2)),
b -> filter(
t -> !t.c.isEmpty() && any(x -> x.signum() == -1 || ge(x, b), t.b),
P.triples(P.lists(P.bigIntegers()))
)
);
for (Pair<BigInteger, Triple<List<BigInteger>, List<BigInteger>, List<BigInteger>>> p : take(LIMIT, psFail)) {
try {
fromPositionalNotation(p.a, p.b.a, p.b.b, p.b.c);
fail(p.toString());
} catch (IllegalArgumentException ignored) {}
}
psFail = P.dependentPairs(
P.rangeUp(BigInteger.valueOf(2)),
b -> filter(
t -> !t.c.isEmpty() && any(x -> x.signum() == -1 || ge(x, b), t.c),
P.triples(P.lists(P.bigIntegers()))
)
);
for (Pair<BigInteger, Triple<List<BigInteger>, List<BigInteger>, List<BigInteger>>> p : take(LIMIT, psFail)) {
try {
fromPositionalNotation(p.a, p.b.a, p.b.b, p.b.c);
fail(p.toString());
} catch (IllegalArgumentException ignored) {}
}
Iterable<Pair<BigInteger, Pair<List<BigInteger>, List<BigInteger>>>> psFail2 = P.pairs(
P.rangeDown(BigInteger.ONE),
P.pairs(P.lists(P.bigIntegers()))
);
for (Pair<BigInteger, Pair<List<BigInteger>, List<BigInteger>>> p : take(LIMIT, psFail2)) {
try {
fromPositionalNotation(p.a, p.b.a, p.b.b, new ArrayList<>());
fail(p.toString());
} catch (IllegalArgumentException ignored) {}
}
}
private static @NotNull Pair<List<BigInteger>, Iterable<BigInteger>> digits_alt(
@NotNull Rational r,
@NotNull BigInteger base
) {
Triple<List<BigInteger>, List<BigInteger>, List<BigInteger>> positionalNotation = r.positionalNotation(base);
Iterable<BigInteger> afterDecimal;
if (positionalNotation.c.equals(Arrays.asList(BigInteger.ZERO))) {
afterDecimal = positionalNotation.b;
} else {
afterDecimal = concat(positionalNotation.b, cycle(positionalNotation.c));
}
return new Pair<>(positionalNotation.a, afterDecimal);
}
private static void propertiesDigits() {
initialize();
System.out.println("\t\ttesting digits(BigInteger) properties...");
Iterable<Pair<Rational, BigInteger>> ps;
if (P instanceof ExhaustiveProvider) {
ps = ((ExhaustiveProvider) P).pairsSquareRootOrder(
cons(ZERO, P.positiveRationals()),
P.rangeUp(BigInteger.valueOf(2))
);
} else {
ps = P.pairs(
cons(ZERO, P.positiveRationals()),
map(i -> BigInteger.valueOf(i + 2), ((RandomProvider) P).naturalIntegersGeometric(20))
);
}
for (Pair<Rational, BigInteger> p : take(LIMIT, ps)) {
Pair<List<BigInteger>, Iterable<BigInteger>> digits = p.a.digits(p.b);
assertTrue(p.toString(), digits.a.isEmpty() || !head(digits.a).equals(BigInteger.ZERO));
assertTrue(p.toString(), all(x -> x.signum() != -1 && lt(x, p.b), digits.a));
assertEquals(p.toString(), MathUtils.fromBigEndianDigits(p.b, digits.a), p.a.floor());
}
for (Pair<Rational, BigInteger> p : take(LIMIT, filter(q -> q.a.hasTerminatingBaseExpansion(q.b), ps))) {
Pair<List<BigInteger>, Iterable<BigInteger>> digits = p.a.digits(p.b);
toList(digits.b);
}
if (!(P instanceof ExhaustiveProvider)) {
ps = P.pairs(
cons(ZERO, ((QBarRandomProvider) P).positiveRationals(8)),
map(i -> BigInteger.valueOf(i + 2), ((RandomProvider) P).naturalIntegersGeometric(20))
);
}
for (Pair<Rational, BigInteger> p : take(LIMIT, ps)) {
Pair<List<BigInteger>, Iterable<BigInteger>> digits = p.a.digits(p.b);
Pair<List<BigInteger>, Iterable<BigInteger>> alt = digits_alt(p.a, p.b);
assertEquals(p.toString(), digits.a, alt.a);
aeq(p.toString(), take(100, digits.b), take(100, alt.b));
}
Iterable<Pair<Rational, BigInteger>> psFail = P.pairs(P.negativeRationals(), P.rangeUp(BigInteger.valueOf(2)));
for (Pair<Rational, BigInteger> p : take(LIMIT, psFail)) {
try {
p.a.digits(p.b);
fail(p.toString());
} catch (IllegalArgumentException ignored) {}
}
for (Pair<Rational, BigInteger> p : take(LIMIT, P.pairs(P.rationals(), P.rangeDown(BigInteger.ONE)))) {
try {
p.a.digits(p.b);
fail(p.toString());
} catch (IllegalArgumentException ignored) {}
}
}
private static void compareImplementationsDigits() {
initialize();
System.out.println("\t\tcomparing digits(BigInteger) implementations...");
long totalTime = 0;
Iterable<Pair<Rational, BigInteger>> ps;
if (P instanceof ExhaustiveProvider) {
ps = ((ExhaustiveProvider) P).pairsSquareRootOrder(
cons(ZERO, P.positiveRationals()),
P.rangeUp(BigInteger.valueOf(2))
);
} else {
ps = P.pairs(
cons(ZERO, ((QBarRandomProvider) P).positiveRationals(8)),
map(i -> BigInteger.valueOf(i + 2), ((RandomProvider) P).naturalIntegersGeometric(20))
);
}
for (Pair<Rational, BigInteger> p : take(LIMIT, ps)) {
long time = System.nanoTime();
toList(take(20, digits_alt(p.a, p.b).b));
totalTime += (System.nanoTime() - time);
}
System.out.println("\t\t\tsimplest: " + ((double) totalTime) / 1e9 + " s");
totalTime = 0;
for (Pair<Rational, BigInteger> p : take(LIMIT, ps)) {
long time = System.nanoTime();
toList(take(20, p.a.digits(p.b).b));
totalTime += (System.nanoTime() - time);
}
System.out.println("\t\t\tstandard: " + ((double) totalTime) / 1e9 + " s");
}
private static void propertiesToStringBase_BigInteger() {
initialize();
System.out.println("\t\ttesting toStringBase(BigInteger) properties...");
Iterable<Pair<Rational, BigInteger>> ps;
if (P instanceof ExhaustiveProvider) {
ps = ((ExhaustiveProvider) P).pairsSquareRootOrder(P.rationals(), P.rangeUp(BigInteger.valueOf(2)));
} else {
ps = P.pairs(
P.rationals(),
map(i -> BigInteger.valueOf(i + 2), ((RandomProvider) P).naturalIntegersGeometric(20))
);
}
for (Pair<Rational, BigInteger> p : take(LIMIT, filter(q -> q.a.hasTerminatingBaseExpansion(q.b), ps))) {
String s = p.a.toStringBase(p.b);
assertEquals(p.toString(), fromStringBase(p.b, s), p.a);
}
String chars = charsToString(concat(Arrays.asList(fromString("-."), range('0', '9'), range('A', 'Z'))));
if (P instanceof ExhaustiveProvider) {
ps = ((ExhaustiveProvider) P).pairsSquareRootOrder(
P.rationals(),
P.range(BigInteger.valueOf(2), BigInteger.valueOf(36))
);
} else {
ps = P.pairs(P.rationals(), P.range(BigInteger.valueOf(2), BigInteger.valueOf(36)));
}
for (Pair<Rational, BigInteger> p : take(LIMIT, filter(q -> q.a.hasTerminatingBaseExpansion(q.b), ps))) {
String s = p.a.toStringBase(p.b);
assertTrue(p.toString(), all(c -> elem(c, chars), s));
}
String chars2 = charsToString(concat(fromString("-.()"), range('0', '9')));
if (P instanceof ExhaustiveProvider) {
ps = ((ExhaustiveProvider) P).pairsSquareRootOrder(P.rationals(), P.rangeUp(BigInteger.valueOf(37)));
} else {
ps = P.pairs(
P.rationals(),
map(i -> BigInteger.valueOf(i + 37), ((RandomProvider) P).naturalIntegersGeometric(20))
);
}
for (Pair<Rational, BigInteger> p : take(LIMIT, filter(q -> q.a.hasTerminatingBaseExpansion(q.b), ps))) {
String s = p.a.toStringBase(p.b);
assertTrue(p.toString(), all(c -> elem(c, chars2), s));
}
for (Pair<Rational, BigInteger> p : take(LIMIT, P.pairs(P.rationals(), P.rangeDown(BigInteger.ONE)))) {
try {
p.a.toStringBase(p.b);
fail(p.toString());
} catch (IllegalArgumentException ignored) {}
}
Iterable<Pair<Rational, BigInteger>> psFail;
if (P instanceof ExhaustiveProvider) {
psFail = P.pairs(P.rationals(), P.rangeUp(BigInteger.valueOf(2)));
} else {
psFail = P.pairs(
P.rationals(),
map(i -> BigInteger.valueOf(i + 2), ((RandomProvider) P).naturalIntegersGeometric(20))
);
}
for (Pair<Rational, BigInteger> p : take(LIMIT, filter(q -> !q.a.hasTerminatingBaseExpansion(q.b), psFail))) {
try {
p.a.toStringBase(p.b);
fail(p.toString());
} catch (ArithmeticException ignored) {}
}
}
private static void propertiesToStringBase_BigInteger_int() {
initialize();
System.out.println("\t\ttesting toStringBase(BigInteger, int) properties...");
Iterable<Pair<Rational, Pair<BigInteger, Integer>>> ps;
if (P instanceof ExhaustiveProvider) {
ps = P.pairs(
P.rationals(),
(Iterable<Pair<BigInteger, Integer>>) P.pairs(P.rangeUp(BigInteger.valueOf(2)), P.integers())
);
} else {
ps = P.pairs(
P.rationals(),
(Iterable<Pair<BigInteger, Integer>>) P.pairs(
map(i -> BigInteger.valueOf(i + 2), ((RandomProvider) P).naturalIntegersGeometric(20)),
((RandomProvider) P).integersGeometric(20)
)
);
}
for (Pair<Rational, Pair<BigInteger, Integer>> p : take(LIMIT, ps)) {
String s = p.a.toStringBase(p.b.a, p.b.b);
boolean ellipsis = s.endsWith("...");
if (ellipsis) s = take(s.length() - 3, s);
Rational error = fromStringBase(p.b.a, s).subtract(p.a).abs();
assertTrue(p.toString(), lt(error, of(p.b.a).pow(-p.b.b)));
if (ellipsis) {
assertTrue(p.toString(), error != ZERO);
}
}
String chars = charsToString(concat(Arrays.asList(fromString("-."), range('0', '9'), range('A', 'Z'))));
if (P instanceof ExhaustiveProvider) {
ps = P.pairs(
P.rationals(),
(Iterable<Pair<BigInteger, Integer>>) P.pairs(
P.range(BigInteger.valueOf(2), BigInteger.valueOf(36)),
P.integers()
)
);
} else {
ps = P.pairs(
P.rationals(),
(Iterable<Pair<BigInteger, Integer>>) P.pairs(
P.range(BigInteger.valueOf(2), BigInteger.valueOf(36)),
((RandomProvider) P).integersGeometric(20)
)
);
}
for (Pair<Rational, Pair<BigInteger, Integer>> p : take(LIMIT, ps)) {
String s = p.a.toStringBase(p.b.a, p.b.b);
assertTrue(p.toString(), all(c -> elem(c, chars), s));
}
String chars2 = charsToString(concat(fromString("-.()"), range('0', '9')));
if (P instanceof ExhaustiveProvider) {
ps = P.pairs(
P.rationals(),
(Iterable<Pair<BigInteger, Integer>>) P.pairs(P.rangeUp(BigInteger.valueOf(37)), P.integers())
);
} else {
ps = P.pairs(
P.rationals(),
(Iterable<Pair<BigInteger, Integer>>) P.pairs(
map(i -> BigInteger.valueOf(i + 37), ((RandomProvider) P).naturalIntegersGeometric(20)),
((RandomProvider) P).integersGeometric(20)
)
);
}
for (Pair<Rational, Pair<BigInteger, Integer>> p : take(LIMIT, ps)) {
String s = p.a.toStringBase(p.b.a, p.b.b);
assertTrue(p.toString(), all(c -> elem(c, chars2), s));
}
Iterable<Triple<Rational, BigInteger, Integer>> tsFail = P.triples(
P.rationals(),
P.rangeDown(BigInteger.ONE),
P.integers()
);
for (Triple<Rational, BigInteger, Integer> t : take(LIMIT, tsFail)) {
try {
t.a.toStringBase(t.b, t.c);
fail(t.toString());
} catch (IllegalArgumentException ignored) {}
}
}
private static void propertiesFromStringBase() {
initialize();
System.out.println("\t\ttesting fromStringBase(BigInteger, String) properties...");
Iterable<BigInteger> bases;
if (P instanceof ExhaustiveProvider) {
bases = P.rangeUp(BigInteger.valueOf(2));
} else {
bases = map(i -> BigInteger.valueOf(i + 2), ((RandomProvider) P).naturalIntegersGeometric(20));
}
Iterable<Pair<BigInteger, String>> ps = P.dependentPairs(
bases,
b -> {
String chars = ".-";
if (Ordering.le(b, BigInteger.valueOf(36))) {
chars += charsToString(range('0', MathUtils.toDigit(b.intValueExact() - 1)));
} else {
chars += "()0123456789";
}
Iterable<Character> unfiltered;
if (P instanceof ExhaustiveProvider) {
unfiltered = fromString(chars);
} else {
unfiltered = ((RandomProvider) P).uniformSample(chars);
}
return filter(
s -> {
try {
fromStringBase(b, s);
return true;
} catch (IllegalArgumentException e) {
return false;
}
},
P.strings(unfiltered)
);
}
);
for (Pair<BigInteger, String> p : take(MEDIUM_LIMIT, ps)) {
Rational r = fromStringBase(p.a, p.b);
validate(r);
}
ps = filter(
p -> {
if (p.b.isEmpty()) return false;
if (head(p.b) == '.' || last(p.b) == '.') return false;
if (p.b.startsWith("-.")) return false;
if (p.b.equals("0") || p.b.equals("(0)")) return true;
if (head(p.b) == '0' && !p.b.startsWith("0.")) return false;
if (p.b.startsWith("(0)") && !p.b.startsWith("(0).")) return false;
if (p.b.startsWith("-0") || p.b.startsWith("-(0)")) return false;
int decimalIndex = p.b.indexOf('.');
if (decimalIndex != -1) {
if (last(p.b) == '0' || p.b.endsWith("(0)")) return false;
}
return true;
},
ps
);
for (Pair<BigInteger, String> p : take(MEDIUM_LIMIT, ps)) {
Rational r = fromStringBase(p.a, p.b);
assertEquals(p.toString(), r.toStringBase(p.a), p.b);
}
for (BigInteger i : take(LIMIT, P.rangeUp(BigInteger.valueOf(2)))) {
assertTrue(i.toString(), fromStringBase(i, "") == ZERO);
}
for (Pair<BigInteger, String> p : take(SMALL_LIMIT, P.pairs(P.rangeDown(BigInteger.ONE), P.strings()))) {
try {
fromStringBase(p.a, p.b);
fail(p.toString());
} catch (IllegalArgumentException ignored) {}
}
//improper String left untested
}
private static void propertiesCancelDenominators() {
initialize();
System.out.println("\t\ttesting cancelDenominators(List<Rational>) properties...");
for (List<Rational> rs : take(LIMIT, P.lists(P.rationals()))) {
List<BigInteger> canceled = cancelDenominators(rs);
BigInteger gcd = foldl(p -> p.a.gcd(p.b), BigInteger.ZERO, canceled);
assertTrue(rs.toString(), gcd.equals(BigInteger.ZERO) || gcd.equals(BigInteger.ONE));
assertTrue(rs.toString(), equal(map(Rational::signum, rs), map(BigInteger::signum, canceled)));
assertTrue(
rs.toString(),
same(
zipWith(
p -> p.a.divide(p.b),
filter(r -> r != ZERO, rs),
filter(i -> !i.equals(BigInteger.ZERO), canceled)
)
)
);
}
for (Pair<List<Rational>, Rational> p : take(LIMIT, P.pairs(P.lists(P.rationals()), P.positiveRationals()))) {
assertEquals(
p.toString(),
cancelDenominators(p.a),
cancelDenominators(toList(map(r -> r.multiply(p.b), p.a)))
);
}
for (Rational r : take(LIMIT, P.rationals())) {
BigInteger canceled = head(cancelDenominators(Arrays.asList(r)));
assertTrue(r.toString(), le(canceled.abs(), BigInteger.ONE));
}
Iterable<List<Rational>> failRss = map(
p -> toList(insert(p.a, p.b, null)),
(Iterable<Pair<List<Rational>, Integer>>) P.dependentPairsLogarithmic(
P.lists(P.rationals()),
rs -> range(0, rs.size())
)
);
for (List<Rational> rs : take(LIMIT, failRss)) {
try {
cancelDenominators(rs);
fail(rs.toString());
} catch (NullPointerException ignored) {}
}
}
private static void propertiesEquals() {
initialize();
System.out.println("\t\ttesting equals(Object) properties...");
for (Rational r : take(LIMIT, P.rationals())) {
//noinspection EqualsWithItself
assertTrue(r.toString(), r.equals(r));
//noinspection ObjectEqualsNull
assertFalse(r.toString(), r.equals(null));
}
}
private static void propertiesHashCode() {
initialize();
System.out.println("\t\ttesting hashCode() properties...");
for (Rational r : take(LIMIT, P.rationals())) {
assertEquals(r.toString(), r.hashCode(), r.hashCode());
}
}
private static int compareTo_simplest(@NotNull Rational x, @NotNull Rational y) {
return x.getNumerator().multiply(y.getDenominator()).compareTo(y.getNumerator().multiply(x.getDenominator()));
}
private static void propertiesCompareTo() {
initialize();
System.out.println("\t\ttesting compareTo(Rational) properties...");
for (Pair<Rational, Rational> p : take(LIMIT, P.pairs(P.rationals()))) {
int compare = p.a.compareTo(p.b);
assertEquals(p.toString(), compare, compareTo_simplest(p.a, p.b));
assertTrue(p.toString(), compare == -1 || compare == 0 || compare == 1);
assertEquals(p.toString(), p.b.compareTo(p.a), -compare);
assertEquals(p.toString(), p.a.subtract(p.b).signum(), compare);
}
for (Rational r : take(LIMIT, P.rationals())) {
assertEquals(r.toString(), r.compareTo(r), 0);
}
Iterable<Triple<Rational, Rational, Rational>> ts = filter(
t -> lt(t.a, t.b) && lt(t.b, t.c),
P.triples(P.rationals())
);
for (Triple<Rational, Rational, Rational> t : take(LIMIT, ts)) {
assertEquals(t.toString(), t.a.compareTo(t.c), -1);
}
}
private static void compareImplementationsCompareTo() {
initialize();
System.out.println("\t\tcomparing compareTo(Rational) implementations...");
long totalTime = 0;
for (Pair<Rational, Rational> p : take(LIMIT, P.pairs(P.rationals()))) {
long time = System.nanoTime();
compareTo_simplest(p.a, p.b);
totalTime += (System.nanoTime() - time);
}
System.out.println("\t\t\tsimplest: " + ((double) totalTime) / 1e9 + " s");
totalTime = 0;
for (Pair<Rational, Rational> p : take(LIMIT, P.pairs(P.rationals()))) {
long time = System.nanoTime();
p.a.compareTo(p.b);
totalTime += (System.nanoTime() - time);
}
System.out.println("\t\t\tstandard: " + ((double) totalTime) / 1e9 + " s");
}
private static void propertiesRead() {
initialize();
System.out.println("\t\ttesting read(String) properties...");
for (String s : take(LIMIT, P.strings())) {
read(s);
}
for (Rational r : take(LIMIT, P.rationals())) {
Optional<Rational> or = read(r.toString());
assertEquals(r.toString(), or.get(), r);
}
Iterable<Character> cs;
if (P instanceof QBarExhaustiveProvider) {
cs = fromString(RATIONAL_CHARS);
} else {
cs = ((QBarRandomProvider) P).uniformSample(RATIONAL_CHARS);
}
Iterable<String> ss = filter(s -> read(s).isPresent(), P.strings(cs));
for (String s : take(LIMIT, ss)) {
Optional<Rational> or = read(s);
validate(or.get());
}
Pair<Iterable<String>, Iterable<String>> slashPartition = partition(s -> s.contains("/"), ss);
for (String s : take(LIMIT, slashPartition.a)) {
int slashIndex = s.indexOf('/');
String left = s.substring(0, slashIndex);
String right = s.substring(slashIndex + 1);
assertTrue(s, Readers.readBigInteger(left).isPresent());
assertTrue(s, Readers.readBigInteger(right).isPresent());
}
for (String s : take(LIMIT, slashPartition.b)) {
assertTrue(s, Readers.readBigInteger(s).isPresent());
}
}
private static void propertiesFindIn() {
initialize();
System.out.println("\t\ttesting findIn(String) properties...");
for (String s : take(LIMIT, P.strings())) {
findIn(s);
}
Iterable<Pair<String, Integer>> ps = P.dependentPairsLogarithmic(P.strings(), s -> range(0, s.length()));
Iterable<String> ss = map(p -> take(p.a.b, p.a.a) + p.b + drop(p.a.b, p.a.a), P.pairs(ps, P.rationals()));
for (String s : take(LIMIT, ss)) {
Optional<Pair<Rational, Integer>> op = findIn(s);
Pair<Rational, Integer> p = op.get();
assertNotNull(s, p.a);
assertNotNull(s, p.b);
assertTrue(s, p.b >= 0 && p.b < s.length());
String before = take(p.b, s);
assertFalse(s, findIn(before).isPresent());
String during = p.a.toString();
assertTrue(s, s.substring(p.b).startsWith(during));
String after = drop(p.b + during.length(), s);
assertTrue(s, after.isEmpty() || !read(during + head(after)).isPresent());
}
}
private static void propertiesToString() {
initialize();
System.out.println("\t\ttesting toString() properties...");
for (Rational r : take(LIMIT, P.rationals())) {
String s = r.toString();
assertTrue(isSubsetOf(s, RATIONAL_CHARS));
Optional<Rational> readR = read(s);
assertTrue(r.toString(), readR.isPresent());
assertEquals(r.toString(), readR.get(), r);
}
}
private static void validate(@NotNull Rational r) {
assertEquals(r.toString(), r.getNumerator().gcd(r.getDenominator()), BigInteger.ONE);
assertEquals(r.toString(), r.getDenominator().signum(), 1);
if (r.equals(ZERO)) assertTrue(r.toString(), r == ZERO);
if (r.equals(ONE)) assertTrue(r.toString(), r == ONE);
}
private static <T> void aeq(String message, Iterable<T> xs, Iterable<T> ys) {
assertTrue(message, equal(xs, ys));
}
private static void aeq(String message, float x, float y) {
assertEquals(message, Float.toString(x), Float.toString(y));
}
private static void aeq(String message, double x, double y) {
assertEquals(message, Double.toString(x), Double.toString(y));
}
private static void aeq(String message, BigDecimal x, BigDecimal y) {
assertEquals(message, x.stripTrailingZeros(), y.stripTrailingZeros());
}
}
|
package com.mangopay.entities;
import com.google.gson.annotations.SerializedName;
import com.mangopay.core.Address;
import com.mangopay.core.enumerations.*;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Map;
import static com.mangopay.core.enumerations.PersonType.LEGAL;
public class UserLegal extends User {
/**
* Name of this user.
*/
@SerializedName("Name")
private String name;
@SerializedName("LegalPersonType")
private LegalPersonType legalPersonType;
/**
* Headquarters address.
*/
@SerializedName("HeadquartersAddress")
private Address headquartersAddress;
@SerializedName("LegalRepresentativeFirstName")
private String legalRepresentativeFirstName;
@SerializedName("LegalRepresentativeLastName")
private String legalRepresentativeLastName;
@SerializedName("LegalRepresentativeAddress")
private Address legalRepresentativeAddress;
@SerializedName("LegalRepresentativeEmail")
private String legalRepresentativeEmail;
@SerializedName("LegalRepresentativeBirthday")
private Long legalRepresentativeBirthday;
@SerializedName("LegalRepresentativeNationality")
private CountryIso legalRepresentativeNationality;
@SerializedName("LegalRepresentativeCountryOfResidence")
private CountryIso legalRepresentativeCountryOfResidence;
/**
* Statute.
*/
@SerializedName("Statute")
private String statute;
/**
* Proof of registration.
*/
@SerializedName("ProofOfRegistration")
private String proofOfRegistration;
/**
* Shareholder declaration.
*/
@SerializedName("ShareholderDeclaration")
private String shareholderDeclaration;
/**
* Company number.
*/
@SerializedName("CompanyNumber")
private String companyNumber;
public UserLegal() {
this.personType = LEGAL;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public LegalPersonType getLegalPersonType() {
return legalPersonType;
}
public void setLegalPersonType(LegalPersonType legalPersonType) {
this.legalPersonType = legalPersonType;
}
public Address getHeadquartersAddress() {
return headquartersAddress;
}
public void setHeadquartersAddress(Address headquartersAddress) {
this.headquartersAddress = headquartersAddress;
}
public String getLegalRepresentativeFirstName() {
return legalRepresentativeFirstName;
}
public void setLegalRepresentativeFirstName(String legalRepresentativeFirstName) {
this.legalRepresentativeFirstName = legalRepresentativeFirstName;
}
public String getLegalRepresentativeLastName() {
return legalRepresentativeLastName;
}
public void setLegalRepresentativeLastName(String legalRepresentativeLastName) {
this.legalRepresentativeLastName = legalRepresentativeLastName;
}
public Address getLegalRepresentativeAddress() {
return legalRepresentativeAddress;
}
public void setLegalRepresentativeAddress(Address legalRepresentativeAddress) {
this.legalRepresentativeAddress = legalRepresentativeAddress;
}
public String getLegalRepresentativeEmail() {
return legalRepresentativeEmail;
}
public void setLegalRepresentativeEmail(String legalRepresentativeEmail) {
this.legalRepresentativeEmail = legalRepresentativeEmail;
}
public Long getLegalRepresentativeBirthday() {
return legalRepresentativeBirthday;
}
public void setLegalRepresentativeBirthday(Long legalRepresentativeBirthday) {
this.legalRepresentativeBirthday = legalRepresentativeBirthday;
}
public CountryIso getLegalRepresentativeNationality() {
return legalRepresentativeNationality;
}
public void setLegalRepresentativeNationality(CountryIso legalRepresentativeNationality) {
this.legalRepresentativeNationality = legalRepresentativeNationality;
}
public CountryIso getLegalRepresentativeCountryOfResidence() {
return legalRepresentativeCountryOfResidence;
}
public void setLegalRepresentativeCountryOfResidence(CountryIso legalRepresentativeCountryOfResidence) {
this.legalRepresentativeCountryOfResidence = legalRepresentativeCountryOfResidence;
}
public String getStatute() {
return statute;
}
public void setStatute(String statute) {
this.statute = statute;
}
public String getProofOfRegistration() {
return proofOfRegistration;
}
public void setProofOfRegistration(String proofOfRegistration) {
this.proofOfRegistration = proofOfRegistration;
}
public String getShareholderDeclaration() {
return shareholderDeclaration;
}
public void setShareholderDeclaration(String shareholderDeclaration) {
this.shareholderDeclaration = shareholderDeclaration;
}
public String getCompanyNumber() {
return companyNumber;
}
public void setCompanyNumber(String companyNumber) {
this.companyNumber = companyNumber;
}
/**
* Gets map which property is an object and what type of object.
* @return Collection of field name-field type pairs.
*/
@Override
public Map<String, Type> getSubObjects() {
Map<String, Type> result = super.getSubObjects();
result.put("HeadquartersAddress", Address.class);
result.put("LegalRepresentativeAddress", Address.class);
return result;
}
/**
* Gets the collection of read-only fields names.
* @return List of field names.
*/
@Override
public ArrayList<String> getReadOnlyProperties() {
ArrayList<String> result = super.getReadOnlyProperties();
result.add("Statute");
result.add("ProofOfRegistration");
result.add("ShareholderDeclaration");
return result;
}
}
|
package org.adridadou;
import org.adridadou.ethereum.*;
import org.adridadou.ethereum.provider.*;
import org.adridadou.ethereum.values.EthAccount;
import org.adridadou.ethereum.values.EthAddress;
import org.adridadou.ethereum.values.SoliditySource;
import org.junit.Test;
import java.io.File;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class TestnetConnectionTest {
private final StandaloneEthereumFacadeProvider standalone = new StandaloneEthereumFacadeProvider();
private final TestnetEthereumFacadeProvider testnet = new TestnetEthereumFacadeProvider();
private final MordenEthereumFacadeProvider morden = new MordenEthereumFacadeProvider();
private final MainEthereumFacadeProvider main = new MainEthereumFacadeProvider();
@Test
public void run() throws Exception {
run(testnet, "cow", "");
}
private void run(EthereumFacadeProvider ethereumFacadeProvider, final String id, final String password) throws Exception {
EthAccount sender = ethereumFacadeProvider.getKey(id).decode(password);
EthereumFacade ethereum = ethereumFacadeProvider.create();
System.out.println(ethereum.getBalance(sender).inEth() + " ETH");
SoliditySource contract = SoliditySource.from(new File(this.getClass().getResource("/contract.sol").toURI()));
CompletableFuture<EthAddress> futureAddress = ethereum.publishContract(contract, "myContract2", sender);
EthAddress address = futureAddress.get();
MyContract2 myContract = ethereum.createContractProxy(contract, "myContract2", address, sender, MyContract2.class);
assertEquals("", myContract.getI1());
System.out.println("*** calling contract myMethod");
Future<Integer> future = myContract.myMethod("this is a test");
Future<Integer> future2 = myContract.myMethod("this is a test2");
Integer result = future2.get();
assertEquals(12, result.intValue());
assertEquals("this is a test2", myContract.getI1());
assertTrue(myContract.getT());
Integer[] expected = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
assertArrayEquals(expected, myContract.getArray().toArray(new Integer[0]));
assertEquals(new MyReturnType(true, "hello", 34), myContract.getM());
assertEquals("", myContract.getI2());
System.out.println("*** calling contract myMethod2 async");
myContract.myMethod2("async call").get();
assertEquals("async call", myContract.getI2());
assertEquals(EnumTest.VAL2, myContract.getEnumValue());
}
public static class MyReturnType {
private Boolean val1;
private String val2;
private Integer val3;
public MyReturnType(Boolean val1, String val2, Integer val3) {
this.val1 = val1;
this.val2 = val2;
this.val3 = val3;
}
@Override
public String toString() {
return "MyReturnType{" +
"val1=" + val1 +
", val2='" + val2 + '\'' +
", val3=" + val3 +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MyReturnType that = (MyReturnType) o;
if (val1 != null ? !val1.equals(that.val1) : that.val1 != null) return false;
if (val2 != null ? !val2.equals(that.val2) : that.val2 != null) return false;
return val3 != null ? val3.equals(that.val3) : that.val3 == null;
}
@Override
public int hashCode() {
int result = val1 != null ? val1.hashCode() : 0;
result = 31 * result + (val2 != null ? val2.hashCode() : 0);
result = 31 * result + (val3 != null ? val3.hashCode() : 0);
return result;
}
}
private enum EnumTest {
VAL1, VAL2, VAL3
}
private interface MyContract2 {
CompletableFuture<Integer> myMethod(String value);
CompletableFuture<Void> myMethod2(String value);
EnumTest getEnumValue();
String getI1();
String getI2();
boolean getT();
MyReturnType getM();
List<Integer> getArray();
}
}
|
package com.nfl.glitr.relay;
import com.nfl.glitr.registry.TypeRegistry;
import graphql.relay.*;
import graphql.schema.*;
import javax.xml.bind.DatatypeConverter;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import static graphql.Assert.assertNotNull;
public class RelayHelper {
private Relay relay;
private static final String DUMMY_CURSOR_PREFIX = "simple-cursor";
private final TypeRegistry typeRegistry;
public RelayHelper(Relay relay, TypeRegistry typeRegistry) {
assertNotNull(typeRegistry, "TypeRegistry can't be null");
assertNotNull(typeRegistry.getNodeInterface(), "NodeInterface can't be null");
this.relay = relay;
this.typeRegistry = typeRegistry;
}
public GraphQLInterfaceType getNodeInterface() {
return typeRegistry.getNodeInterface();
}
public List<GraphQLArgument> getConnectionFieldArguments() {
return relay.getConnectionFieldArguments();
}
public GraphQLObjectType edgeType(String simpleName, GraphQLOutputType edgeGraphQLOutputType,
GraphQLInterfaceType nodeInterface, List<GraphQLFieldDefinition> graphQLFieldDefinitions) {
return relay.edgeType(simpleName, edgeGraphQLOutputType, nodeInterface, graphQLFieldDefinitions);
}
public GraphQLObjectType connectionType(String simpleName, GraphQLObjectType edgeType, List<GraphQLFieldDefinition> graphQLFieldDefinitions) {
return relay.connectionType(simpleName, edgeType, graphQLFieldDefinitions);
}
public static graphql.relay.Connection buildConnection(Iterable<?> col, int skipItems, int totalCount) {
List<Edge<Object>> edges = new ArrayList<>();
int ix = skipItems;
for (Object object : col) {
edges.add(new DefaultEdge<>(object, new DefaultConnectionCursor(createCursor(ix++))));
}
ConnectionCursor startCursor = null;
ConnectionCursor endCursor = null ;
boolean hasPreviousPage = skipItems > 0 && totalCount > 0;
boolean hasNextPage = skipItems + edges.size() + 1 < totalCount;
if (!edges.isEmpty()) {
Edge firstEdge = edges.get(0);
Edge lastEdge = edges.get(edges.size() - 1);
startCursor = firstEdge.getCursor();
endCursor = lastEdge.getCursor();
}
PageInfoWithTotal pageInfoWithTotal = new PageInfoWithTotal(startCursor, endCursor,
hasPreviousPage, hasNextPage);
pageInfoWithTotal.setTotal(totalCount);
return new DefaultConnection<>(edges, pageInfoWithTotal);
}
public static String createCursor(int offset) {
return Base64.toBase64(DUMMY_CURSOR_PREFIX + Integer.toString(offset));
}
public static int getOffsetFromCursor(String cursor, int defaultValue) {
if (cursor == null) return defaultValue;
String string = Base64.fromBase64(cursor);
return Integer.parseInt(string.substring(DUMMY_CURSOR_PREFIX.length()));
}
static public class Base64 {
private Base64() {
}
public static String toBase64(String string) {
return DatatypeConverter.printBase64Binary(string.getBytes(StandardCharsets.UTF_8));
}
public static String fromBase64(String string) {
return new String(DatatypeConverter.parseBase64Binary(string), Charset.forName("UTF-8"));
}
}
}
|
package org.cubeengine.butler;
import org.cubeengine.butler.Tokenizer.Token;
import org.cubeengine.butler.Tokenizer.TokenType;
import org.junit.Test;
import static java.util.Arrays.asList;
import static org.cubeengine.butler.Tokenizer.tokenize;
import static org.junit.Assert.assertEquals;
public class TokenizerTest
{
private static Token plain(String in)
{
return new Token(TokenType.PLAIN, in);
}
private static Token quoted(String in)
{
return new Token(TokenType.QUOTED, in);
}
@Test
public void testTokenize()
{
assertEquals(asList(plain("a"), plain("b"), plain("c")), tokenize("a b c"));
assertEquals(asList(plain("\\\"\\a"), plain("b\""), plain("\\\"c")), tokenize("\\\"\\a b\" \\\"c"));
assertEquals(asList(quoted("a b "), plain("c")), tokenize("\"a b \"c"));
assertEquals(asList(plain("a"), plain("b"), plain("c")), tokenize("a b c "));
}
}
|
package org.jactiveresource.test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.Date;
import org.jactiveresource.ResourceConnection;
import org.jactiveresource.ResourceFormat;
import org.junit.Before;
import org.junit.Test;
/**
* @version $LastChangedRevision$ <br>
* $LastChangedDate$
* @author $LastChangedBy$
*/
public class TestPerson {
private ResourceConnection c;
private PersonFactory xf, jf;
private Person p;
@Before
public void setUp() throws Exception {
c = new ResourceConnection("http://localhost:3000");
c.setUsername("Ace");
c.setPassword("newenglandclamchowder");
xf = new PersonFactory(c, ResourceFormat.XML);
jf = new PersonFactory(c, ResourceFormat.JSON);
}
@Test
public void basicOperationsXML() throws Exception {
basicOperations(xf);
}
@Test
public void basicOperationsJSON() throws Exception {
basicOperations(jf);
}
private void basicOperations(PersonFactory f) throws Exception {
p = f.instantiate();
assertNull(p.getId());
p.setName("King Tut");
Date old = new Date(new Long("-99999999999999"));
p.setBirthdate(old);
p.save();
String id = p.getId();
assertEquals(p.getName(), "King Tut");
assertNotNull("No id present", p.getId());
p = f.find(id);
assertEquals(p.getName(), "King Tut");
p.setName("Alexander the Great");
p.update();
p = f.find(id);
assertEquals(p.getName(), "Alexander the Great");
assertTrue(f.exists(id));
p.delete();
assertFalse(f.exists(id));
}
@Test
public void reloadXML() throws Exception {
reload(xf);
}
@Test
public void reloadJSON() throws Exception {
reload(jf);
}
private void reload(PersonFactory f) throws Exception {
p = f.instantiate();
p.setName("George Burns");
p.setBirthdate(new Date());
p.save();
p.setName("Fred Flintstone");
p.reload();
assertEquals("George Burns", p.getName());
p.delete();
}
@Test
public void findAllXML() throws Exception {
findAll(xf);
}
//@Test
//public void findAllJSON() throws Exception {
// findAll(jf);
private void findAll(PersonFactory f) throws Exception {
Person pp;
ArrayList<Person> people, otherpeople;
people = f.findAll();
p = f.instantiate();
p.setName("George Lopez");
p.setBirthdate(new Date());
p.save();
pp = f.instantiate();
pp.setName("George Foreman");
pp.setBirthdate(new Date());
pp.save();
otherpeople = f.findAll();
assertEquals(otherpeople.size(), people.size() + 2);
p.delete();
pp.delete();
otherpeople = f.findAll();
assertEquals(otherpeople.size(), people.size());
}
@Test
public void validationXML() throws Exception {
validation(xf);
}
@Test
public void validationJSON() throws Exception {
validation(jf);
}
public void validation(PersonFactory f) throws Exception {
p = f.instantiate();
p.setBirthdate(new Date());
assertFalse(p.save());
assertNull(p.getId());
p.setName("Shoeless Joe");
assertTrue(p.save());
assertNotNull(p.getId());
p.delete();
}
@Test
public void findXML() throws Exception {
find(xf);
}
@Test
public void findJSON() throws Exception {
find(jf);
}
public void find(PersonFactory f) throws Exception {
p = f.instantiate();
assertNull(p.getId());
p.setName("Ty Cobb");
p.setBirthdate(new Date());
p.save();
String id = p.getId();
Person p = f.find(id);
assertEquals("Ty Cobb", p.getName());
p.delete();
}
@Test
public void existsXML() throws Exception {
exists(xf);
}
@Test
public void existsJSON() throws Exception {
exists(jf);
}
public void exists(PersonFactory f) throws Exception {
p = f.instantiate();
assertNull(p.getId());
p.setName("Nolan Ryan");
p.setBirthdate(new Date());
p.save();
String id = p.getId();
assertEquals(true, f.exists(id));
p.delete();
assertEquals(false, f.exists(id));
}
}
|
package com.qiniu.storage;
import com.qiniu.common.Config;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Client;
import com.qiniu.http.Response;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.storage.model.FileInfo;
import com.qiniu.storage.model.FileListing;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import com.qiniu.util.StringUtils;
import com.qiniu.util.UrlSafeBase64;
import java.util.ArrayList;
import java.util.Iterator;
public final class BucketManager {
private final Auth auth;
private final Client client;
public BucketManager(Auth auth) {
this.auth = auth;
client = new Client();
}
/**
* EncodedEntryURI
*
* @param bucket
* @param key
* @return urlsafe_base64_encode(Bucket:Key)
*/
public static String entry(String bucket, String key) {
return entry(bucket, key, true);
}
/**
* EncodedEntryURI
* mustHaveKey false key null urlsafe_base64_encode(Bucket);
* urlsafe_base64_encode(Bucket:Key)
*
* @param bucket
* @param key
* @param mustHaveKey
* @return urlsafe_base64_encode(entry)
*/
public static String entry(String bucket, String key, boolean mustHaveKey) {
String en = bucket + ":" + key;
if (!mustHaveKey && (key == null)) {
en = bucket;
}
return UrlSafeBase64.encodeToString(en);
}
/**
*
*
* @return bucket
*/
public String[] buckets() throws QiniuException {
Response r = rsGet("/buckets");
return r.jsonToObject(String[].class);
}
/**
*
*
* @param bucket
* @param prefix
* @return FileInfo
*/
public FileListIterator createFileListIterator(String bucket, String prefix) {
return new FileListIterator(bucket, prefix, 100, null);
}
/**
*
*
* @param bucket
* @param prefix
* @param limit 1000 100
* @param delimiter
* @return FileInfo
*/
public FileListIterator createFileListIterator(String bucket, String prefix, int limit, String delimiter) {
return new FileListIterator(bucket, prefix, limit, delimiter);
}
/**
*
*
* @param bucket
* @param prefix
* @param marker marker
* @param limit 1000 100
* @param delimiter
* @return
* @throws QiniuException
*/
public FileListing listFiles(String bucket, String prefix, String marker, int limit, String delimiter)
throws QiniuException {
StringMap map = new StringMap().put("bucket", bucket).putNotEmpty("marker", marker)
.putNotEmpty("prefix", prefix).putNotEmpty("delimiter", delimiter).putWhen("limit", limit, limit > 0);
String url = Config.RSF_HOST + "/list?" + map.formString();
Response r = get(url);
return r.jsonToObject(FileListing.class);
}
/**
*
*
* @param bucket
* @param key
* @return
* @throws QiniuException
*/
public FileInfo stat(String bucket, String key) throws QiniuException {
Response r = rsGet("/stat/" + entry(bucket, key));
return r.jsonToObject(FileInfo.class);
}
/**
*
*
* @param bucket
* @param key
* @throws QiniuException
*/
public void delete(String bucket, String key) throws QiniuException {
rsPost("/delete/" + entry(bucket, key));
}
/**
*
*
* @param bucket
* @param oldname
* @param newname
* @throws QiniuException
*/
public void rename(String bucket, String oldname, String newname) throws QiniuException {
move(bucket, oldname, bucket, newname);
}
/**
*
*
* @param from_bucket
* @param from_key
* @param to_bucket
* @param to_key
* @throws QiniuException
*/
public void copy(String from_bucket, String from_key, String to_bucket, String to_key) throws QiniuException {
String from = entry(from_bucket, from_key);
String to = entry(to_bucket, to_key);
String path = "/copy/" + from + "/" + to;
rsPost(path);
}
/**
*
*
* @param from_bucket
* @param from_key
* @param to_bucket
* @param to_key
* @throws QiniuException
*/
public void move(String from_bucket, String from_key, String to_bucket, String to_key) throws QiniuException {
String from = entry(from_bucket, from_key);
String to = entry(to_bucket, to_key);
String path = "/move/" + from + "/" + to;
rsPost(path);
}
/**
* mimeTYpe
*
* @param bucket
* @param key
* @param mime
* @throws QiniuException
*/
public void changeMime(String bucket, String key, String mime) throws QiniuException {
String resource = entry(bucket, key);
String encode_mime = UrlSafeBase64.encodeToString(mime);
String path = "/chgm/" + resource + "/mime/" + encode_mime;
rsPost(path);
}
/**
*
* url
*
*
* @param url
* @param bucket
* @throws QiniuException
*/
public DefaultPutRet fetch(String url, String bucket) throws QiniuException {
return fetch(url, bucket, null);
}
/**
*
* url
*
*
* @param url
* @param bucket
* @param key
* @throws QiniuException
*/
public DefaultPutRet fetch(String url, String bucket, String key) throws QiniuException {
String resource = UrlSafeBase64.encodeToString(url);
String to = entry(bucket, key, false);
String path = "/fetch/" + resource + "/to/" + to;
Response r = ioPost(path);
return r.jsonToObject(DefaultPutRet.class);
}
/**
*
*
*
* @param bucket
* @param key
* @throws QiniuException
*/
public void prefetch(String bucket, String key) throws QiniuException {
String resource = entry(bucket, key);
String path = "/prefetch/" + resource;
ioPost(path);
}
/**
*
*
* @param operations
* @return
* @throws QiniuException
* @see Batch
*/
public Response batch(Batch operations) throws QiniuException {
return rsPost("/batch", operations.toBody());
}
private Response rsPost(String path, byte[] body) throws QiniuException {
String url = Config.RS_HOST + path;
return post(url, body);
}
private Response rsPost(String path) throws QiniuException {
return rsPost(path, null);
}
private Response rsGet(String path) throws QiniuException {
String url = Config.RS_HOST + path;
return get(url);
}
private Response ioPost(String path) throws QiniuException {
String url = Config.IO_HOST + path;
return post(url, null);
}
private Response get(String url) throws QiniuException {
StringMap headers = auth.authorization(url);
return client.get(url, headers);
}
private Response post(String url, byte[] body) throws QiniuException {
StringMap headers = auth.authorization(url, body, Client.FormMime);
return client.post(url, body, headers, Client.FormMime);
}
public static class Batch {
private ArrayList<String> ops;
public Batch() {
this.ops = new ArrayList<String>();
}
public Batch copy(String from_bucket, String from_key, String to_bucket, String to_key) {
String from = entry(from_bucket, from_key);
String to = entry(to_bucket, to_key);
ops.add("copy" + "/" + from + "/" + to);
return this;
}
public Batch rename(String from_bucket, String from_key, String to_key) {
return move(from_bucket, from_key, from_bucket, to_key);
}
public Batch move(String from_bucket, String from_key, String to_bucket, String to_key) {
String from = entry(from_bucket, from_key);
String to = entry(to_bucket, to_key);
ops.add("move" + "/" + from + "/" + to);
return this;
}
public Batch delete(String bucket, String... keys) {
for (String key : keys) {
ops.add("delete" + "/" + entry(bucket, key));
}
return this;
}
public Batch stat(String bucket, String... keys) {
for (String key : keys) {
ops.add("stat" + "/" + entry(bucket, key));
}
return this;
}
public byte[] toBody() {
String body = StringUtils.join(ops, "&op=", "op=");
return StringUtils.utf8Bytes(body);
}
public Batch merge(Batch batch) {
this.ops.addAll(batch.ops);
return this;
}
}
public class FileListIterator implements Iterator<FileInfo[]> {
private String marker = null;
private String bucket;
private String delimiter;
private int limit;
private String prefix;
private QiniuException exception = null;
public FileListIterator(String bucket, String prefix, int limit, String delimiter) {
if (limit <= 0) {
throw new IllegalArgumentException("limit must great than 0");
}
this.bucket = bucket;
this.prefix = prefix;
this.limit = limit;
this.delimiter = delimiter;
}
public QiniuException error() {
return exception;
}
@Override
public boolean hasNext() {
return exception == null && !"".equals(marker);
}
@Override
public FileInfo[] next() {
try {
FileListing f = listFiles(bucket, prefix, marker, limit, delimiter);
this.marker = f.marker == null ? "" : f.marker;
return f.items;
} catch (QiniuException e) {
this.exception = e;
return null;
}
}
@Override
public void remove() {
throw new UnsupportedOperationException("remove");
}
}
}
|
package de.bornemisza.rest;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.javalite.http.HttpException;
public class Json {
public static String toJson(Object obj) throws HttpException {
try {
return new ObjectMapper().writeValueAsString(obj);
}
catch (JsonProcessingException ex) {
throw new HttpException("Problem marshalling JSON!", ex);
}
}
public static <T extends Object> T fromJson(String json, Class<T> type) throws HttpException {
try {
return new ObjectMapper().readValue(json, type);
}
catch (IOException ex) {
throw new HttpException("Problem unmarshalling JSON: " + json, ex);
}
}
}
|
package com.sdl.selenium.web;
/**
* Contains all Search types :
* see details for all in :
* <p>{@link SearchType#EQUALS}</p>
* <p>{@link SearchType#CONTAINS}</p>
* <p>{@link SearchType#STARTS_WITH}</p>
* <p>{@link SearchType#TRIM}</p>
* <p>{@link SearchType#CHILD_NODE}</p>
* <p>{@link SearchType#DEEP_CHILD_NODE}</p>
* <p>{@link SearchType#HTML_NODE}</p>
* <p>{@link SearchType#CONTAINS_ALL}</p>
* <p>{@link SearchType#CONTAINS_ANY}</p>
*/
public enum SearchType {
EQUALS,
CONTAINS,
STARTS_WITH,
/**
* will use : normalize-spaces on text()
*/
TRIM,
/**
* For finding elements that contain text (and text is not first node in that element).
* eg. next button has the span.icon as first childNode in html:
* <pre>
<div class="btn">
<span class="icon"></span>
Cancel
</div></pre>
* <p>so must be used like:</p>
* <pre>WebLocator cancelBtn = new WebLocator().setClasses("btn").setText("Cancel", SearchType.CHILD_NODE);</pre>
*/
CHILD_NODE,
/**
* For finding elements that contain text (and text is not in any of direct childNodes in that element, but inside of them).
* eg. next button has the span.icon as first childNode in html, and text is inside span.btn-text childNode:
* <pre>
<div class="btn">
<span class="icon"></span>
<span class="btn-text">Cancel</span>
</div></pre>
* <p>so must be used like:</p>
* <pre>WebLocator cancelBtn = new WebLocator().setClasses("btn").setText("Cancel", SearchType.DEEP_CHILD_NODE);</pre>
*/
DEEP_CHILD_NODE,
/**
* TODO add better documentation and working example
* For finding elements that contain text composed by html nodes
* eg. "Get an instant Quote" button contains text containing html node <span>instant </span>
* <pre>
<div class="btn">
Get an <span class="bold">instant</span> Quote
</div>
</pre>
* <p>so must be used like:</p>
* <pre>WebLocator cancelBtn = new WebLocator().setClasses("btn").setText("Get an instant Quote", SearchType.HTML_NODE);</pre>
*/
HTML_NODE,
/**
* <p>For finding elements that contain all text segments.</p>
* <p>Segments will be made by splitting text into elements with first char of input text</p>
* <pre>
<div class="btn">
<span class="btn-text">Cancel is a Button</span>
</div></pre>
* <p>so must be used like:</p>
* <pre>
* WebLocator cancelBtn = new WebLocator().setClasses("btn")
* .setText("&Cancel&Button", SearchType.CONTAINS_ALL);
* </pre>
*/
CONTAINS_ALL,
/**
* <p>For finding elements that contain any text segments.</p>
* <p>Segments will be made by splitting text into elements with first char of input text</p>
* <pre>
<div class="btn">
<span class="btn-text">Cancel is a Button</span>
</div></pre>
* <p>so must be used like:</p>
* <pre>
WebLocator cancelBtn = new WebLocator().setClasses("btn")
.setText("|Cancel|Button", SearchType.CONTAINS_ANY);</pre>
*/
CONTAINS_ANY
}
|
package com.renjipanicker;
import java.util.ArrayList;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.lang.Thread;
import android.provider.Settings.Secure;
import android.graphics.Bitmap;
import android.content.res.AssetManager;
import android.content.Intent;
import android.net.Uri;
import android.webkit.WebView;
import android.os.Handler;
import android.os.Looper;
import android.webkit.JavascriptInterface;
import android.webkit.WebViewClient;
import android.webkit.ConsoleMessage;
import android.webkit.WebSettings;
import android.webkit.WebSettings.RenderPriority;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebChromeClient;
import android.webkit.JsResult;
import android.webkit.JavascriptInterface;
import android.util.Log;
public class wui {
private class nproxy {
public String name;
public nproxy(String n) {
this.name = n;
}
@JavascriptInterface
public String invoke(String fn, String[] params) {
return invokeNative(name, fn, params);
}
};
private final String TAG;
private WebView webView;
private Handler mainHandler;
private nproxy consoleobj = null;
private native void initNative(String tag, String[] params, AssetManager assetManager);
private native void exitNative();
private native void initWindow();
private native void initPage(String url);
private native String invokeNative(String obj, String fn, String[] params);
private native Object[] getPageData(String url);
class JsObject {
public String name;
public String nname;
public String body;
public JsObject(String n, String nn, String b) {
this.name = n;
this.nname = nn;
this.body = b;
}
};
private ArrayList<JsObject> jsoList = new ArrayList<JsObject>();
public void connect(WebView wv, Handler mh) {
this.webView = wv;
this.mainHandler = mh;
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setRenderPriority(RenderPriority.HIGH);
webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
webView.setWebChromeClient(new WebChromeClient() {
@Override
public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
return super.onJsAlert(view, url, message, result);
}
@Override
public boolean onConsoleMessage(ConsoleMessage cm) {
if(consoleobj != null){
String[] params = new String[3];
params[0] = cm.message();
consoleobj.invoke("log", params);
}else{
//Log.d(TAG, cm.message() + ":--:yFrom line " + cm.lineNumber() + " of " + cm.sourceId());
}
return true;
}
});
webView.setWebViewClient(new WebViewClient() {
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
//Log.d(TAG, "pstart:" + url);
}
@Override
public void onPageFinished(WebView view, String url) {
//Log.d(TAG, "pfinish:" + url);
}
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
//Log.d(TAG, "shouldInterceptRequest:" + url);
final Uri uri = Uri.parse(url);
final String scheme = uri.getScheme();
if (scheme.equals("embedded")) {
String path = uri.getHost();
Object data[] = getPageData(path);
if(data != null){
String mim = (String)data[0];
byte[] dat = (byte[])data[1];
ByteArrayInputStream is = new ByteArrayInputStream(dat);
String enc = "UTF-8";
if(mim.equals("image/png")){
enc = "binary";
}
return new WebResourceResponse(mim, enc, is);
}
}
return null;
}
});
initWindow();
//Log.d(TAG, "connected");
}
public void disconnect() {
this.webView = null;
this.mainHandler = null;
}
public wui(String tg, String[] params, AssetManager assetManager) {
this.TAG = tg;
initNative(TAG, params, assetManager);
}
public void onDestroy() {
exitNative();
}
private void insertObjects() {
for(JsObject jso : jsoList){
nproxy np = new nproxy(jso.name);
if(jso.name == "console"){
consoleobj = np;
}else{
webView.addJavascriptInterface(np, jso.nname);
}
}
}
private void insertObjectBody() {
for(JsObject jso : jsoList){
webView.loadUrl(jso.body);
}
jsoList.clear();
}
public void setObject(final String name, final String nname, final String body) {
jsoList.add(new JsObject(name, nname, body));
}
public void go_embedded(final String url, final String data, final String mimetype) {
if(mainHandler == null){
Log.d(TAG, "mainHandler is empty in go_embedded:" + url);
return;
}
mainHandler.post(new Runnable() {
public void run() {
insertObjects();
// Log.d(TAG, data);
webView.loadDataWithBaseURL("embedded://", data, mimetype, "utf-8", null);
insertObjectBody();
initPage(url);
}
});
}
public void go_standard(final String url) {
if(mainHandler == null){
Log.d(TAG, "mainHandler is empty in go_standard:" + url);
return;
}
mainHandler.post(new Runnable() {
public void run() {
insertObjects();
webView.loadUrl(url);
insertObjectBody();
initPage(url);
}
});
}
};
|
package com.ktl.moment.android.activity;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.ktl.moment.R;
import com.ktl.moment.android.base.BaseActivity;
import com.ktl.moment.android.component.CircleImageView;
import com.ktl.moment.android.component.wheel.HoloWheelActivity;
import com.ktl.moment.common.Account;
import com.ktl.moment.common.constant.C;
import com.ktl.moment.entity.User;
import com.ktl.moment.infrastructure.HttpCallBack;
import com.ktl.moment.qiniu.QiniuManager;
import com.ktl.moment.qiniu.QiniuManager.QiniuRequestCallbBack;
import com.ktl.moment.utils.EditTextUtil;
import com.ktl.moment.utils.ToastUtil;
import com.ktl.moment.utils.net.ApiManager;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.lidroid.xutils.view.annotation.event.OnTouch;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.ImageLoader;
public class EditInfoActivity extends BaseActivity {
@ViewInject(R.id.edit_avatar)
private CircleImageView editAvatar;
@ViewInject(R.id.edit_nickname)
private EditText editNickname;
@ViewInject(R.id.edit_sex)
private EditText editSex;
@ViewInject(R.id.edit_area)
private TextView editArea;
@ViewInject(R.id.edit_birthday)
private TextView editBirthday;
@ViewInject(R.id.edit_signature)
private EditText editSignature;
@ViewInject(R.id.edit_base_layout)
private LinearLayout editBaseLayout;
private String avatar;
private String imgPath = "";
@Override
protected void onCreate(Bundle arg0) {
// TODO Auto-generated method stub
super.onCreate(arg0);
getLayoutInflater().inflate(R.layout.activity_edit_info, contentLayout,
true);
ViewUtils.inject(this);
initUser();
initView();
}
private void initView() {
setTitleBackImgVisible(true);
setTitleBackImg(R.drawable.title_return_white);
setMiddleTitleVisible(true);
setMiddleTitleName("");
setTitleRightTvVisible(true);
setTitleRightTv("");
setBaseActivityBgColor(getResources()
.getColor(R.color.main_title_color));
EditTextUtil.setEditable(editNickname, false);
EditTextUtil.setEditable(editSex, false);
EditTextUtil.setEditable(editSignature, false);
}
private void initUser() {
User spUser = Account.getUserInfo();
ImageLoader.getInstance().displayImage(spUser.getUserAvatar(),
editAvatar, getDisplayImageOptions());
editNickname.setText(spUser.getNickName());
if (spUser.getSex() == 0) {
editSex.setText("");
} else {
editSex.setText("");
}
if (spUser.getUserArea().equals("") || spUser.getUserArea() == null) {
editArea.setText(" ");
} else {
editArea.setText(spUser.getUserArea());
}
if (spUser.getBirthday().equals("") || spUser.getBirthday() == null) {
editBirthday.setText("2000-01-01");
} else {
editBirthday.setText(spUser.getBirthday());
}
if (!spUser.getSignature().equals("") && spUser.getSignature() != null) {
editSignature.setText(spUser.getSignature());
}
}
@OnClick({ R.id.title_back_img, R.id.title_right_tv, R.id.edit_area,
R.id.edit_avatar, R.id.edit_nickname, R.id.edit_sex,
R.id.edit_signature, R.id.edit_birthday })
public void click(View v) {
switch (v.getId()) {
case R.id.title_back_img:
finish();
break;
case R.id.title_right_tv:
complete();
break;
case R.id.edit_avatar:
editAvatar();
break;
case R.id.edit_nickname:
editNickname();
break;
case R.id.edit_sex:
editSex();
break;
case R.id.edit_area:
editArea();
break;
case R.id.edit_signature:
editSignature();
break;
case R.id.edit_birthday:
editBirthday();
break;
default:
break;
}
}
@OnTouch({ R.id.edit_base_layout })
public boolean onTouch(View v, MotionEvent e) {
EditTextUtil.setEditable(editNickname, false);
EditTextUtil.setEditable(editSex, false);
EditTextUtil.setEditable(editSignature, false);
try {
InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
return imm.hideSoftInputFromWindow(getCurrentFocus()
.getWindowToken(), 0);
} catch (NullPointerException error) {
// TODO: handle exception
return false;
}
}
private void editAvatar() {
Intent cameraIntent = new Intent(this, CameraSelectActivity.class);
startActivityForResult(cameraIntent,
C.ActivityRequest.REQUEST_SELECT_CAMERA_ACTIVITY);
}
private void editNickname() {
EditTextUtil.setEditable(editNickname, true);
}
private void editSex() {
EditTextUtil.setEditable(editSex, true);
}
private void editSignature() {
EditTextUtil.setEditable(editSignature, true);
}
private void editArea() {
Intent intent = new Intent(this, HoloWheelActivity.class);
startActivityForResult(intent,
C.ActivityRequest.REQUEST_SELECT_CITY_ACTIVITY);
}
private void editBirthday() {
String birthday = editBirthday.getText().toString().trim();
if (birthday.equals("") || birthday == null) {
birthday = "2000-01-01";
}
String[] dateArray = birthday.split("-");
int year = Integer.parseInt(dateArray[0]);
int month = Integer.parseInt(dateArray[1]);
int day = Integer.parseInt(dateArray[2]);
Log.i("date", year + "-" + month + "-" + day);
Intent intent = new Intent(this, CustomDatePicker.class);
intent.putExtra("year", year);
intent.putExtra("month", month);
intent.putExtra("day", day);
startActivityForResult(intent,
C.ActivityRequest.REQUEST_DATE_PICKER_ACTIVITY);
}
private void submit() {
String nickname = editNickname.getText().toString().trim();
String tmpSex = editSex.getText().toString().trim();
String area = editArea.getText().toString().trim();
String birthday = editBirthday.getText().toString().trim();
String signature = editSignature.getText().toString().trim();
int sex = 0;
if (tmpSex.equals("")) {
sex = 1;
} else {
sex = 0;
}
RequestParams params = new RequestParams();
params.put("userId", Account.getUserInfo().getUserId());
params.put("nickName", nickname);
params.put("userAvatar", avatar);
params.put("sex", sex);
params.put("userArea", area);
params.put("birthday", birthday);
params.put("signature", signature);
ApiManager.getInstance().post(this, C.API.UPDATE_USER_INFO, params,
new HttpCallBack() {
@Override
public void onSuccess(Object res) {
// TODO Auto-generated method stub
@SuppressWarnings("unchecked")
List<User> list = (List<User>) res;
User user = list.get(0);
Account.saveUserInfo(user);
setResult(RESULT_OK);
finish();
}
@Override
public void onFailure(Object res) {
// TODO Auto-generated method stub
ToastUtil.show(EditInfoActivity.this, (String) res);
}
}, "User");
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if (resultCode == Activity.RESULT_OK) {
switch (requestCode) {
case C.ActivityRequest.REQUEST_SELECT_CITY_ACTIVITY:
String province = data.getStringExtra("provinceText");
String city = data.getStringExtra("cityText");
editArea.setText(province + " " + city);
break;
case C.ActivityRequest.REQUEST_SELECT_CAMERA_ACTIVITY:
Uri cropUri = data.getParcelableExtra("cropPicUri");
imgPath = cropUri.getPath();
try {
Bitmap bmp = MediaStore.Images.Media.getBitmap(
this.getContentResolver(), cropUri);
editAvatar.setImageBitmap(bmp);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
case C.ActivityRequest.REQUEST_DATE_PICKER_ACTIVITY:
String birthday = data.getStringExtra("birthday");
editBirthday.setText(birthday);
break;
}
}
}
private void complete() {
if (imgPath.equals("") || imgPath == null) {
avatar = Account.getUserInfo().getUserAvatar();
submit();
} else {
QiniuManager.getInstance().uploadFile(this, imgPath, "img_",
new QiniuRequestCallbBack() {
@Override
public void OnFailed(String msg) {
// TODO Auto-generated method stub
ToastUtil.show(EditInfoActivity.this, msg);
}
@Override
public void OnComplate(String key) {
// TODO Auto-generated method stub
avatar = C.API.QINIU_BASE_URL + key;
submit();
}
});
}
}
@Override
public void OnDbTaskComplete(Message res) {
// TODO Auto-generated method stub
}
}
|
package com.wisdom.easy;
/**
* 415-
*
* "A man, a plan, a canal: Panama"
* "race a car"
*/
public class ValidPalindrome {
public static void main(String[] args) {
ValidPalindrome validPalindrome = new ValidPalindrome();
String s = "ahdpgaghapsdguaweytpoaudifanvlkczxhjiougpq paoidugpawet pa";
boolean b = validPalindrome.isPalindrome(s);
System.out.println(b);
}
private boolean isPalindrome(String s) {
StringBuilder stringBuilder = new StringBuilder();
char[] ch = s.toCharArray();
for(char c : ch) {
if (Character.isLetterOrDigit(c)) {
stringBuilder.append(c);
}
}
if (0 == stringBuilder.length()) {
return true;
}
char[] chars = stringBuilder.toString().toLowerCase().toCharArray();
for (int i = 0; i < chars.length / 2; i++) {
if (chars[i] != chars[chars.length - 1 - i]) {
return false;
}
}
return true;
}
}
|
package com.mararok.epiccore.database;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
/**
* Intarface for connection to sql database
*/
public interface DatabaseConnection {
public int exec(String sql) throws SQLException;
public Statement query() throws SQLException;
public PreparedStatement prepareQuery(String sql) throws SQLException;
public CachedQuery prepareCachedQuery(String sql) throws SQLException;
public CachedQuery getCachedQuery(int index) throws SQLException;
public void clearCache() throws SQLException;
public void beginTransaction() throws SQLException;
public void endTransaction() throws SQLException;
public void commit() throws SQLException;
public void rollback() throws SQLException;
DatabaseConnectionConfig getConfig();
}
|
package com.xhub.pdflego.core;
import com.xhub.pdflego.exception.ComponentOverflowException;
import org.apache.log4j.Logger;
/**
* Component has the attributes of a rectangle
* @author Amine Hakkou
*/
public abstract class Component {
protected Integer x = 0;
protected Integer y = 0;
protected Integer width;
protected Integer height;
protected Component parent;
private Logger logger = Logger.getLogger(Component.class);
public Component(Component parent){
this.parent = parent;
}
public Integer getX() {
if(this.parent != null){
return this.parent.getX() + this.x;
}else{
return this.x;
}
}
public void setX(Integer x) {
if((this.parent != null) && (x + this.width > parent.getX() + parent.getWidth())){
ComponentOverflowException e = new ComponentOverflowException();
this.logger.error(e.getMessage(), e);
}
this.x = x;
}
public Integer getY() {
if(this.parent != null){
return this.parent.getY() + this.y;
}else{
return this.y;
}
}
public void setY(Integer y) {
if((this.parent != null) &&
(y + this.height > parent.getY() + parent.getHeight())){
ComponentOverflowException e = new ComponentOverflowException();
this.logger.error(e.getMessage(), e);
}
this.y = y;
}
public Integer getWidth() {
return width;
}
public void setWidth(Integer width) {
this.width = width;
}
public Integer getHeight() {
return height;
}
public void setHeight(Integer height) {
this.height = height;
}
public Component getParent() {
return parent;
}
public void setParent(Component parent) {
this.parent = parent;
}
}
|
package org.helioviewer.jhv.layers;
import java.awt.EventQueue;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Vector;
import javax.swing.JOptionPane;
import org.helioviewer.base.logging.Log;
import org.helioviewer.base.math.Interval;
import org.helioviewer.base.message.Message;
import org.helioviewer.jhv.Settings;
import org.helioviewer.jhv.display.Displayer;
import org.helioviewer.jhv.gui.ImageViewerGui;
import org.helioviewer.jhv.gui.UIViewListener;
import org.helioviewer.jhv.gui.UIViewListenerDistributor;
import org.helioviewer.jhv.gui.components.MoviePanel;
import org.helioviewer.jhv.gui.components.layerTable.LayerTableModel;
import org.helioviewer.jhv.gui.dialogs.MetaDataDialog;
import org.helioviewer.jhv.io.APIRequestManager;
import org.helioviewer.jhv.io.FileDownloader;
import org.helioviewer.viewmodel.changeevent.ChangeEvent;
import org.helioviewer.viewmodel.changeevent.LayerChangedReason;
import org.helioviewer.viewmodel.changeevent.LayerChangedReason.LayerChangeType;
import org.helioviewer.viewmodel.changeevent.TimestampChangedReason;
import org.helioviewer.viewmodel.changeevent.ViewChainChangedReason;
import org.helioviewer.viewmodel.io.APIResponse;
import org.helioviewer.viewmodel.io.APIResponseDump;
import org.helioviewer.viewmodel.region.Region;
import org.helioviewer.viewmodel.region.StaticRegion;
import org.helioviewer.viewmodel.view.GL3DLayeredView;
import org.helioviewer.viewmodel.view.ImageInfoView;
import org.helioviewer.viewmodel.view.LayeredView;
import org.helioviewer.viewmodel.view.LinkedMovieManager;
import org.helioviewer.viewmodel.view.MetaDataView;
import org.helioviewer.viewmodel.view.MovieView;
import org.helioviewer.viewmodel.view.RegionView;
import org.helioviewer.viewmodel.view.TimedMovieView;
import org.helioviewer.viewmodel.view.View;
import org.helioviewer.viewmodel.view.jp2view.JHVJP2View;
import org.helioviewer.viewmodel.view.jp2view.datetime.ImmutableDateTime;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLReaderFactory;
/**
* This class is a (redundant) representation of the LayeredView + ViewChain
* state, and, in addition to this, introduces the concept of an "activeLayer",
* which is the Layer that is currently operated on by the user/GUI.
*
* This class is mainly used by the LayerTable(Model) as an abstraction to the
* ViewChain.
*
* Future development plans still have to show if it is worth to keep this
* class, or if the abstraction should be avoided and direct access to the
* viewChain/layeredView should be used in all GUI classes.
*
* @author Malte Nuhn
*/
public class LayersModel implements UIViewListener {
private static final LayersModel layersModel = new LayersModel();
private int activeLayer = -1;
private final ArrayList<LayersListener> layerListeners = new ArrayList<LayersListener>();
private Date lastTimestamp;
private final GL3DLayeredView layeredView;
/**
* Method returns the sole instance of this class.
*
* @return the only instance of this class.
* */
public static LayersModel getSingletonInstance() {
if (!EventQueue.isDispatchThread()) {
System.out.println(">>> You have been naughty: " + Thread.currentThread().getName());
Thread.dumpStack();
System.exit(1);
}
return layersModel;
}
private LayersModel() {
layeredView = new GL3DLayeredView();
UIViewListenerDistributor.getSingletonInstance().addViewListener(this);
}
public LayeredView getLayeredView() {
return layeredView;
}
/**
* Return the view associated with the active Layer
*
* @return View associated with the active Layer
*/
public View getActiveView() {
return getLayer(activeLayer);
}
/**
* @return Index of the currently active Layer
*/
public int getActiveLayer() {
return activeLayer;
}
/**
* @param idx
* - Index of the layer to be retrieved
* @return View associated with the given index
*/
public View getLayer(int idx) {
idx = invertIndex(idx);
if (idx >= 0 && idx < getNumLayers()) {
return layeredView.getLayer(idx);
}
return null;
}
/**
* Set the activeLayer to the Layer that can be associated to the given
* view, do nothing if the view cannot be associated with any layer
*
* @param view
*/
public void setActiveLayer(View view) {
int i = this.findView(view);
setActiveLayer(i);
}
/**
* Set the activeLayer to the Layer associated with the given index
*
* @param idx
* - index of the layer to be set as active Layer
*/
public void setActiveLayer(int idx) {
View view = getLayer(idx);
if (view == null && idx != -1) {
return;
}
activeLayer = idx;
fireActiveLayerChanged(idx);
}
/**
* Return a String containing the current timestamp of the given layer,
* return an empty string if no timing information is available
*
* @param idx
* - Index of the layer in question
* @return String representation of the timestamp, empty String if no timing
* information is available
*/
public String getCurrentFrameTimestampString(int idx) {
View view = this.getLayer(idx);
return getCurrentFrameTimestampString(view);
}
/**
* Return a String containing the current timestamp of the given layer,
* return an empty string if no timing information is available
*
* @param view
* - View that can be associated with the layer in question
* @return String representation of the timestamp, empty String if no timing
* information is available
*/
public String getCurrentFrameTimestampString(View view) {
ImmutableDateTime dt = getCurrentFrameTimestamp(view);
if (dt != null) {
return dt.getCachedDate();
}
return "N/A";
}
/**
* Return the current timestamp of the given layer, return an empty string
* if no timing information is available
*
* @param idx
* - Index of the layer in question
* @return timestamp, null if no timing information is available
*/
public ImmutableDateTime getCurrentFrameTimestamp(int idx) {
View view = this.getLayer(idx);
return getCurrentFrameTimestamp(view);
}
/**
* Return the current timestamp of the given layer, return an empty string
* if no timing information is available
*
* @param view
* - View that can be associated with the layer in question
* @return timestamp, null if no timing information is available
*/
public ImmutableDateTime getCurrentFrameTimestamp(View view) {
if (view != null) {
// null for PixelBasedMetaData
return view.getAdapter(MetaDataView.class).getMetaData().getDateTime();
}
return null;
}
/**
* Return the timestamp of the first available image data of the layer in
* question
*
* @param view
* - View that can be associated with the layer in question
* @return timestamp of the first available image data, null if no
* information available
*/
public ImmutableDateTime getStartDate(View view) {
ImmutableDateTime result = null;
if (view == null) {
return result;
}
TimedMovieView tmv = view.getAdapter(TimedMovieView.class);
if (tmv != null) {
result = tmv.getFrameDateTime(0);
} else {
// else try to acces a timestamp by assuming it is a plain image
result = getCurrentFrameTimestamp(view);
}
return result;
}
/**
* Return the timestamp of the first available image data of the layer in
* question
*
* @param idx
* - index of the layer in question
* @return timestamp of the first available image data, null if no
* information available
*/
public ImmutableDateTime getStartDate(int idx) {
View view = this.getLayer(idx);
return this.getStartDate(view);
}
public Interval<Date> getFrameInterval() {
return new Interval<Date>(getFirstDate(), getLastDate());
}
/**
* Return the timestamp of the first available image data
*
* @return timestamp of the first available image data, null if no
* information available
*/
public Date getFirstDate() {
ImmutableDateTime earliest = null;
for (int idx = 0; idx < getNumLayers(); idx++) {
ImmutableDateTime start = getStartDate(idx);
if (start == null) {
continue;
}
if (earliest == null || start.compareTo(earliest) < 0) {
earliest = start;
}
}
return earliest == null ? null : earliest.getTime();
}
/**
* Return the timestamp of the last available image data of the layer in
* question
*
* @param view
* - View that can be associated with the layer in question
* @return timestamp of the last available image data, null if no
* information available
*/
public ImmutableDateTime getEndDate(View view) {
ImmutableDateTime result = null;
if (view == null) {
return result;
}
TimedMovieView tmv = view.getAdapter(TimedMovieView.class);
if (tmv != null) {
int lastFrame = tmv.getMaximumFrameNumber();
// the following call will block if the meta is not yet available -
// and will cause deadlocks if called form the wrong thread
result = tmv.getFrameDateTime(lastFrame);
} else {
// else try to acces a timestamp by assuming it is a plain image
result = getCurrentFrameTimestamp(view);
}
return result;
}
/**
* Return the timestamp of the last available image data
*
* @return timestamp of the last available image data, null if no
* information available
*/
public Date getLastDate() {
ImmutableDateTime latest = null;
for (int idx = 0; idx < getNumLayers(); idx++) {
ImmutableDateTime end = getEndDate(idx);
if (end == null) {
continue;
}
if (latest == null || end.compareTo(latest) > 0) {
latest = end;
}
}
return latest == null ? null : latest.getTime();
}
/**
* Return the timestamp of the last available image data of the layer in
* question
*
* @param idx
* - index of the layer in question
* @return timestamp of the last available image data, null if no
* information available
*/
public ImmutableDateTime getEndDate(int idx) {
View view = this.getLayer(idx);
return this.getEndDate(view);
}
/**
* Find the index of the layer that can be associated with the given view
*
* @param view
* - View that can be associated with the layer in question
* @return index of the layer that can be associated with the given view
*/
public int findView(View view) {
int idx = -1;
if (view != null) {
idx = layeredView.getLayerLevel(view);
}
return invertIndex(idx);
}
/**
* Important internal method to convert between LayersModel indexing and
* LayeredView indexing. Calling it twice should form the identity
* operation.
*
* LayersModel indices go from 0 .. (LayerCount - 1), with 0 being the
* uppermost layer
*
* whereas
*
* LayeredView indies go from (LayerCount - 1) .. 0, with 0 being the layer
* at the bottom.
*
* @param idx
* to be converted from LayersModel to LayeredView or the other
* direction.
* @return the inverted index
*/
private int invertIndex(int idx) {
int num = this.getNumLayers();
// invert indices
if (idx >= 0 && num > 0) {
idx = num - 1 - idx;
}
return idx;
}
/**
* Important internal method to convert between LayersModel indexing and
* LayeredView indexing.
*
* Since this index transformation involves the number of layers, this
* transformation has to pay respect to situation where the number of layers
* has changed.
*
* @param idx
* to be converted from LayersModel to LayeredView or the other
* direction after a layer has been deleted
* @return inverted index
*/
private int invertIndexDeleted(int idx) {
int num = this.getNumLayers();
if (idx >= 0) {
idx = num - idx;
}
return idx;
}
/**
* Return the number of layers currently available
*
* @return number of layers
*/
public int getNumLayers() {
return layeredView.getNumLayers();
}
/**
* Change the visibility of the layer in question, and automatically
* (un)link + play/pause the layer
*
* @param view
* - View that can be associated with the layer in question
* @param visible
* - the new visibility state
*/
public void setVisibleLink(View view, boolean visible) {
this.setVisible(view, visible);
this.setLink(view, visible);
if (!visible) {
this.setPlaying(view, false);
}
}
/**
* Change the visibility of the layer in question, and automatically
* (un)link + play/pause the layer
*
* @param idx
* - index of the layer in question
* @param visible
* - the new visibility state
*/
public void setVisibleLink(int idx, boolean visible) {
View view = this.getLayer(idx);
this.setVisibleLink(view, visible);
}
/**
* Change the visibility of the layer in question
*
* @param view
* - View that can be associated with the layer in question
* @param visible
* - the new visibility state
*/
public void setVisible(View view, boolean visible) {
LayeredView lv = getLayeredView();
if (lv != null) {
if (lv.isVisible(view) != visible) {
lv.toggleVisibility(view);
}
}
}
/**
* Change the visibility of the layer in question
*
* @param idx
* - index of the layer in question
* @param visible
* - the new visibility state
*/
public void setVisible(int idx, boolean visible) {
LayeredView lv = getLayeredView();
if (lv != null) {
if (lv.isVisible(getLayer(idx)) != visible) {
lv.toggleVisibility(getLayer(idx));
}
}
}
/**
* Get the visibility of the layer in question
*
* @param view
* - View that can be associated with the layer in question
*
* @return true if the layer is visible
*/
public boolean isVisible(View view) {
LayeredView lv = getLayeredView();
if (lv != null) {
return lv.isVisible(view);
} else {
return false;
}
}
/**
* Get the visibility of the layer in question
*
* @param idx
* - index of the layer in question
* @return true if the layer is visible
*/
public boolean isVisible(int idx) {
LayeredView lv = getLayeredView();
if (lv != null) {
return lv.isVisible(getLayer(idx));
} else {
return false;
}
}
/**
* Get the name of the layer in question
*
* @param view
* - View that can be associated with the layer in question
* @return name of the layer, the views default String representation if no
* name is available
*/
public String getName(View view) {
if (view == null) {
return null;
}
ImageInfoView imageInfoView = view.getAdapter(ImageInfoView.class);
if (imageInfoView != null) {
return imageInfoView.getName();
} else {
return view.toString();
}
}
/**
* Get the name of the layer in question
*
* @param idx
* - index of the layer in question
* @return name of the layer, the views default String representation if no
* name is available
*/
public String getName(int idx) {
View view = this.getLayer(idx);
return this.getName(view);
}
private void handleLayerChanges(View sender, ChangeEvent aEvent) {
LayerChangedReason layerReason = aEvent.getLastChangedReasonByType(LayerChangedReason.class);
// if layers were changed, perform same operations on GUI
if (layerReason != null && !layerReason.getProcessed()) {
LayerChangeType type = layerReason.getLayerChangeType();
// If layer was deleted, delete corresponding panel
if (type == LayerChangedReason.LayerChangeType.LAYER_ADDED) {
layerReason.setProcessed(true);
View view = layerReason.getSubView();
int newIndex = findView(view);
if (newIndex != -1) {
this.setActiveLayer(newIndex);
this.fireLayerAdded(newIndex);
}
} else if (type == LayerChangedReason.LayerChangeType.LAYER_REMOVED) {
layerReason.setProcessed(true);
int oldIndex = this.invertIndexDeleted(layerReason.getLayerIndex());
this.fireLayerRemoved(layerReason.getView(), oldIndex);
int newIndex = determineNewActiveLayer(oldIndex);
this.setActiveLayer(newIndex);
} else if (type == LayerChangedReason.LayerChangeType.LAYER_VISIBILITY) {
layerReason.setProcessed(true);
View view = layerReason.getSubView();
int idx = findView(view);
if (idx != -1) {
this.fireLayerChanged(idx);
}
}
}
}
private void handleTimestampChanges(View sender, ChangeEvent aEvent) {
List<TimestampChangedReason> timestampReasons = aEvent.getAllChangedReasonsByType(TimestampChangedReason.class);
// if meta data has changed, update label
for (TimestampChangedReason timestampReason : timestampReasons) {
View timestampView = timestampReason.getView();
if (timestampView != null) {
int idx = findView(timestampView);
if (isValidIndex(idx)) {
// update LayerTableModel (timestamp labels)
LayerTableModel.getSingletonInstance().fireTableRowsUpdated(idx, idx);
// store last timestamp displayed and fire TimeChanged
ImmutableDateTime currentFrameTimestamp = getCurrentFrameTimestamp(idx);
if (currentFrameTimestamp != null) {
lastTimestamp = currentFrameTimestamp.getTime();
if (idx == activeLayer) {
Displayer.fireTimeChanged(lastTimestamp);
}
}
}
}
}
}
private void handleViewChainChanges(View sender, ChangeEvent aEvent) {
if (aEvent.getLastChangedReasonByType(ViewChainChangedReason.class) != null) {
this.fireAllLayersChanged();
}
}
/**
* View changed handler.
*
* Internally forwards (an abstraction) of the events to the LayersListener
*
*/
@Override
public void UIviewChanged(View sender, ChangeEvent aEvent) {
handleTimestampChanges(sender, aEvent);
handleLayerChanges(sender, aEvent);
handleViewChainChanges(sender, aEvent);
}
/**
* Check if the given index is valid, given the current state of the
* LayeredView/ViewChain
*
* @param idx
* - index of the layer in question
* @return true if the index is valid
*/
public boolean isValidIndex(int idx) {
if (idx >= 0 && idx < this.getNumLayers()) {
return true;
}
return false;
}
/**
* Calulate a new activeLayer after the old Layer has been deleted
*
* @param oldActiveLayerIdx
* - index of old active, but deleted, layer
* @return the index of the new active layer to choose, or -1 if no suitable
* new layer can be found
*/
private int determineNewActiveLayer(int oldActiveLayerIdx) {
int candidate = oldActiveLayerIdx;
if (!isValidIndex(candidate)) {
candidate = this.getNumLayers() - 1;
}
return candidate;
}
/**
* Trigger downloading the layer in question
*
* @param idx
* - index of the layer in question
*/
public void downloadLayer(int idx) {
View view = getLayeredView().getLayer(idx);
downloadLayer(view);
}
/**
* Trigger downloading the layer in question
*
* @param view
* - View that can be associated with the layer in question
*/
public void downloadLayer(View view) {
ImageInfoView infoView;
if (view == null || (infoView = view.getAdapter(ImageInfoView.class)) == null) {
return;
}
Thread downloadThread = new Thread(new Runnable() {
private ImageInfoView theInfoView;
@Override
public void run() {
downloadFromJPIP(theInfoView);
}
public Runnable init(ImageInfoView theInfoView) {
this.theInfoView = theInfoView;
return this;
}
}.init(infoView), "DownloadFromJPIPThread");
downloadThread.start();
}
/**
* Downloads the complete image from the JPIP server.
*
* Changes the source of the ImageInfoView afterwards, since a local file is
* always faster.
*/
private void downloadFromJPIP(ImageInfoView infoView) {
FileDownloader fileDownloader = new FileDownloader();
URI downloadUri = infoView.getDownloadURI();
URI uri = infoView.getUri();
// the http server to download the file from is unknown
if (downloadUri.equals(uri) && !downloadUri.toString().contains("delphi.nascom.nasa.gov")) {
String inputValue = JOptionPane.showInputDialog("To download this file, please specify a concurrent HTTP server address to the JPIP server: ", uri);
if (inputValue != null) {
try {
downloadUri = new URI(inputValue);
} catch (URISyntaxException e) {
}
}
}
File downloadDestination = fileDownloader.getDefaultDownloadLocation(uri);
try {
if (!fileDownloader.get(downloadUri, downloadDestination, "Downloading " + infoView.getName())) {
return;
}
} catch (IOException e) {
e.printStackTrace();
return;
}
}
/**
* Trigger showing a dialog displaying the meta data of the layer in
* question.
*
* @param idx
* - index of the layer in question
*/
public void showMetaInfo(int idx) {
View view = getLayer(idx);
showMetaInfo(view);
}
/**
* Trigger showing a dialog displaying the meta data of the layer in
* question.
*
* @param view
* - View that can be associated with the layer in question
*
* @see org.helioviewer.jhv.gui.dialogs.MetaDataDialog
*/
public void showMetaInfo(View view) {
if (view == null) {
return;
}
MetaDataDialog dialog = new MetaDataDialog();
dialog.setMetaData(view.getAdapter(MetaDataView.class));
dialog.showDialog();
}
/**
* Remove the layer in question
*
* @param idx
* - index of the layer in question
*/
public void removeLayer(int idx) {
idx = invertIndex(idx);
LayeredView lv = getLayeredView();
lv.removeLayer(idx);
}
/**
* Remove the layer in question
*
* @param view
* - View that can be associated with the layer in question
*/
public void removeLayer(View view) {
int index = this.findView(view);
removeLayer(index);
}
/**
* Set the link-state of the layer in question
*
* @param view
* - View that can be associated with the layer in question
* @param link
* - true if the layer in question should be linked
*/
public void setLink(View view, boolean link) {
if (view == null) {
return;
}
if (!this.isTimed(view)) {
return;
}
MovieView view2 = view.getAdapter(MovieView.class);
if (view2 != null) {
MoviePanel moviePanel = MoviePanel.getMoviePanel(view2);
if (moviePanel != null) {
moviePanel.setMovieLink(link);
}
}
this.fireAllLayersChanged();
}
/**
* Set the link-state of the layer in question
*
* @param idx
* - index of the layer in question
* @param link
* - true if the layer in question should be linked
*/
public void setLink(int idx, boolean link) {
View view = this.getLayer(idx);
this.setLink(view, link);
}
/**
* Set the play-state of the layer in question
*
* @param idx
* - index of the layer in question
* @param play
* - true if the layer in question should play
*/
public void setPlaying(int idx, boolean play) {
View view = this.getLayer(idx);
this.setPlaying(view, play);
}
/**
* Set the play-state of the layer in question
*
* @param view
* - View that can be associated with the layer in question
* @param play
* - true if the layer in question should play
*/
public void setPlaying(View view, boolean play) {
if (view == null) {
return;
}
TimedMovieView timedMovieView = view.getAdapter(TimedMovieView.class);
if (timedMovieView != null) {
if (play) {
timedMovieView.playMovie();
} else {
timedMovieView.pauseMovie();
}
}
}
/**
* Check whether the layer in question is a movie
*
* @param idx
* - index of the layer in question
* @return true if the layer in question is a movie
*/
public boolean isMovie(int idx) {
View view = this.getLayer(idx);
return isMovie(view);
}
/**
* Check whether the layer in question is a movie
*
* @param view
* - View that can be associated with the layer in question
* @return true if the layer in question is a movie
*/
public boolean isMovie(View view) {
if (view == null) {
return false;
}
MovieView view2 = view.getAdapter(MovieView.class);
return (view2 != null);
}
/**
* Check whether the layer in question has timing information
*
* @param idx
* - index of the layer in question
* @return true if the layer in question has timing information
*/
public boolean isTimed(int idx) {
return isTimed(this.getLayer(idx));
}
/**
* Check whether the layer in question has timing information
*
* @param view
* - View that can be associated with the layer in question
* @return true if the layer in question has timing information
*/
public boolean isTimed(View view) {
if (getCurrentFrameTimestamp(view) != null) {
return true;
}
return false;
}
/**
* Move the layer in question up
*
* @param view
* - View that can be associated with the layer in question
*/
public void moveLayerUp(View view) {
if (view == null) {
return;
}
// Operates on the (inverted) LayeredView indices
LayeredView lv = this.getLayeredView();
int level = lv.getLayerLevel(view);
if (level < lv.getNumLayers() - 1) {
level++;
}
lv.moveView(view, level);
this.setActiveLayer(invertIndex(level));
}
/**
* Move the layer in question down
*
* @param view
* - View that can be associated with the layer in question
*/
public void moveLayerDown(View view) {
if (view == null) {
return;
}
// Operates on the (inverted) LayeredView indices
LayeredView lv = this.getLayeredView();
int level = lv.getLayerLevel(view);
if (level > 0) {
level
}
lv.moveView(view, level);
this.setActiveLayer(invertIndex(level));
}
/**
* Check whether the layer in question is currently playing
*
* @param idx
* - index of the layer in question
* @return true if the layer in question is currently playing
*/
public boolean isPlaying(int idx) {
View view = getLayer(idx);
return isPlaying(view);
}
/**
* Check whether the layer in question is currently playing
*
* @param view
* - View that can be associated with the layer in question
* @return true if the layer in question is currently playing
*/
public boolean isPlaying(View view) {
if (view == null) {
return false;
}
if (isMovie(view)) {
MovieView movieView = view.getAdapter(MovieView.class);
return movieView.isMoviePlaying();
} else {
return false;
}
}
/**
* Return the current framerate for the layer in question
*
* @param idx
* - index of the layer in question
* @return the current framerate or 0.0 if the movie is not playing, or if
* an error occurs
*/
public double getFPS(int idx) {
View view = getLayer(idx);
return getFPS(view);
}
/**
* Return the current framerate for the layer in question
*
* @param view
* - View that can be associated with the layer in question
* @return the current framerate or 0.0 if the movie is not playing, or if
* an error occurs
*/
public double getFPS(View view) {
double result = 0.0;
if (view == null) {
return result;
}
if (isMovie(view)) {
MovieView movieView = view.getAdapter(MovieView.class);
if (isPlaying(view)) {
result = Math.round(movieView.getActualFramerate() * 100) / 100;
}
}
return result;
}
/**
* Check whether the layer in question is a Master in the list of linked
* movies
*
* @param idx
* - index of the layer in question
* @return true if the layer in question is a master
*/
public boolean isMaster(int idx) {
View view = getLayer(idx);
return isMaster(view);
}
/**
* Check whether the layer in question is a Master in the list of linked
* movies
*
* @param view
* - View that can be associated with the layer in question
* @return true if the layer in question is a master
*/
public boolean isMaster(View view) {
if (view == null) {
return false;
}
TimedMovieView timedMovieView = view.getAdapter(TimedMovieView.class);
return LinkedMovieManager.getActiveInstance().isMaster(timedMovieView);
}
/**
* Check whether the layer in question is a Remote View
*
* @param view
* - View that can be associated with the layer in question
* @return true if the layer in question is a remote view
*/
public boolean isRemote(View view) {
if (view == null) {
return false;
}
JHVJP2View jp2View = view.getAdapter(JHVJP2View.class);
if (jp2View != null) {
return jp2View.isRemote();
} else {
return false;
}
}
/**
* Check whether the layer in question is a Remote View
*
* @param idx
* - index of the layer in question
* @return true if the layer in question is a remote view
*/
public boolean isRemote(int idx) {
View view = getLayer(idx);
return isRemote(view);
}
/**
* Check whether the layer in question is connected to a JPIP server
*
* @param idx
* - index of the layer in question
* @return true if the layer is connected to a JPIP server
*/
public boolean isConnectedToJPIP(int idx) {
View view = getLayer(idx);
return isConnectedToJPIP(view);
}
/**
* Check whether the layer in question is connected to a JPIP server
*
* @param view
* - View that can be associated with the layer in question
* @return true if the layer is connected to a JPIP server
*/
public boolean isConnectedToJPIP(View view) {
if (view == null) {
return false;
}
JHVJP2View jp2View = view.getAdapter(JHVJP2View.class);
if (jp2View != null) {
return jp2View.isConnectedToJPIP();
} else {
return false;
}
}
/**
* Return a representation of the layer in question
*
* @param idx
* - index of the layer in question
* @return LayerDescriptor of the current state of the layer in question
*/
public LayerDescriptor getDescriptor(int idx) {
View view = this.getLayer(idx);
return getDescriptor(view);
}
/**
* Return a representation of the layer in question
*
* @param view
* - View that can be associated with the layer in question
* @return LayerDescriptor of the current state of the layer in question
*/
public LayerDescriptor getDescriptor(View view) {
LayerDescriptor ld = new LayerDescriptor("sd", "sdf");
ld.isMovie = layersModel.isMovie(view);
ld.isMaster = layersModel.isMaster(view);
ld.isVisible = layersModel.isVisible(view);
ld.isTimed = layersModel.isTimed(view);
ld.title = layersModel.getName(view);
ld.timestamp = layersModel.getCurrentFrameTimestampString(view);
return ld;
}
/**
* Notify all LayersListeners
*/
private void fireLayerRemoved(final View oldView, final int oldIndex) {
for (LayersListener ll : layerListeners) {
ll.layerRemoved(oldView, oldIndex);
}
}
/**
* Notify all LayersListeners
*/
private void fireLayerAdded(final int newIndex) {
for (LayersListener ll : layerListeners) {
ll.layerAdded(newIndex);
}
}
/**
* Notify all LayersListeners
*/
private void fireLayerChanged(final int index) {
for (LayersListener ll : layerListeners) {
ll.layerChanged(index);
}
}
/**
* Notify all LayersListeners
*/
private void fireAllLayersChanged() {
for (LayersListener ll : layerListeners) {
for (int index = 0; index < getNumLayers(); index++) {
ll.layerChanged(index);
}
}
}
/**
* Notify all LayersListeners
*/
private void fireActiveLayerChanged(final int index) {
for (LayersListener ll : layerListeners) {
ll.activeLayerChanged(index);
}
}
/**
* Notify all LayersListeners
*/
public void addLayersListener(LayersListener layerListener) {
layerListeners.add(layerListener);
}
/**
* Remove LayersListener
*
* * @author Carlos Martin
*/
public void removeLayersListener(LayersListener layerListener) {
layerListeners.remove(layerListener);
}
/**
* Get last Frame
*
* @return
*/
public Date getLastUpdatedTimestamp() {
if (lastTimestamp == null) {
Date lastDate = this.getLastDate();
if (lastDate != null) {
lastTimestamp = this.getLastDate();
return lastTimestamp;
}
return null;
} else {
return lastTimestamp;
}
}
/**
* Return a XML representation of the current layers. This also includes the
* filter state for each layer.
*
* @see org.helioviewer.viewmodel.filter.Filter#getState
* @param tab
* - String to be prepended to each line of the xml
* representation
* @return the layers' xml representation as string
*/
public String getXMLRepresentation(String tab) {
int layers = getNumLayers();
if (layers == 0) {
return "";
}
StringBuffer xml = new StringBuffer();
xml.append(tab).append("<layers>\n");
// add tab
tab = tab + "\t";
// store region
RegionView regionView = ImageViewerGui.getSingletonInstance().getMainView().getAdapter(RegionView.class);
Region region = regionView.getRegion();
String regionStr = String.format(Locale.ENGLISH, "<region x=\"%.4f\" y=\"%.4f\" width=\"%.4f\" height=\"%.4f\"/>\n", region.getCornerX(), region.getCornerY(), region.getWidth(), region.getHeight());
xml.append(tab).append(regionStr);
// store layers
for (int i = 0; i < layers; i++) {
View currentView = LayersModel.getSingletonInstance().getLayer(i);
if (currentView != null) {
xml.append(tab).append("<layer id=\"").append(i).append("\">\n");
ImageInfoView currentImageInfoView = currentView.getAdapter(ImageInfoView.class);
// add tab
tab = tab + "\t";
// TODO Use a proper encoding function - not "replace X->Y"
xml.append(tab).append("<uri>").append(currentImageInfoView.getUri().toString().replaceAll("&", "&")).append("</uri>\n");
xml.append(tab).append("<downloaduri>").append(currentImageInfoView.getDownloadURI().toString().replaceAll("&", "&")).append("</downloaduri>\n");
// check if we got any api response
APIResponse apiResponse = APIResponseDump.getSingletonInstance().getResponse(currentImageInfoView.getUri(), true);
if (apiResponse != null) {
String xmlApiResponse = apiResponse.getXMLRepresentation();
xml.append(tab).append("<apiresponse>\n").append(tab).append("\t").append(xmlApiResponse).append("\n").append(tab).append("</apiresponse>\n");
}
// remove last tab
tab = tab.substring(0, tab.length() - 1);
xml.append(tab).append("</layer>\n");
}
}
// remove last tab
tab = tab.substring(0, tab.length() - 1);
xml.append(tab).append("</layers>");
return xml.toString();
}
/**
* Restore the JHV state from the given file. This will overwrite the
* current JHV state without further notice!
*
* @param stateURL
* - URL to read the JHV state from
*/
public void loadState(URL stateURL) {
try {
InputSource stateInputSource = new InputSource(new InputStreamReader(stateURL.openStream()));
// create new parser for this inputsource
StateParser stateParser = new StateParser(stateInputSource);
// finally tell the parser to setup the viewchain
stateParser.setupLayers();
} catch (IOException e) {
e.printStackTrace();
}
}
public class StateParser extends DefaultHandler {
/**
* Buffer needed for reading data in-between XML tags
*/
private StringBuffer stringBuffer = new StringBuffer("");
/**
* Temporary variable storing all information about the filter currently
* being parsed
*/
private FilterState tmpFilterSetting = null;
/**
* Temporary variable storing all information about the layer currently
* being parsed
*/
private LayerState tmpLayerSetting = null;
/**
* Variable storing all information about the state currently being
* parsed
*/
private final FullState fullSetting = new FullState();
/**
* Flag showing, if the parser should "copy" the raw XML data currently
* being read in order to feed it to the json parser later on
*/
private boolean apiResponseMode = false;
/**
* Default Constructor
*
* @param xmlSource
*/
public StateParser(InputSource xmlSource) {
try {
XMLReader parser = XMLReaderFactory.createXMLReader("com.sun.org.apache.xerces.internal.parsers.SAXParser");
parser.setContentHandler(this);
parser.parse(xmlSource);
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* {@inheritDoc}
*/
@Override
public void characters(char ch[], int start, int length) throws SAXException {
stringBuffer.append(new String(ch, start, length));
}
/**
* {@inheritDoc}
*/
@Override
public void startElement(String namespaceURI, String localName, String qualifiedName, Attributes atts) throws SAXException {
String tagName = localName.toLowerCase();
if (tagName.equals("apiresponse")) {
apiResponseMode = true;
// if this is enclosed in apiresponse-tags, store the "raw XML"
// in the stringBuffer
} else if (apiResponseMode == true) {
stringBuffer.append("<" + localName);
for (int i = 0; i < atts.getLength(); i++) {
stringBuffer.append(" ");
stringBuffer.append(atts.getLocalName(i));
stringBuffer.append("=\"");
stringBuffer.append(atts.getValue(i));
stringBuffer.append("\"");
}
stringBuffer.append(">");
// skip all other tags
return;
}
stringBuffer = new StringBuffer("");
if (tagName.equals("region")) {
try {
// the attribute names are all case sensitive!
fullSetting.regionViewState.regionX = Double.parseDouble(atts.getValue("x"));
fullSetting.regionViewState.regionY = Double.parseDouble(atts.getValue("y"));
fullSetting.regionViewState.regionWidth = Double.parseDouble(atts.getValue("width"));
fullSetting.regionViewState.regionHeight = Double.parseDouble(atts.getValue("height"));
} catch (Exception e) {
Log.fatal(">> LayersModel.StateParser.startElement() > Error parsing region data");
fullSetting.regionViewState = null;
}
} else if (tagName.equals("layer")) {
tmpLayerSetting = new LayerState();
Log.info("new layer setting ");
// try to read the "id" attribute
int idx_layer_id = atts.getIndex("id");
if (idx_layer_id != -1) {
String str_layer_id = atts.getValue(idx_layer_id);
tmpLayerSetting.id = Integer.parseInt(str_layer_id);
}
} else if (tagName.equals("filter")) {
tmpFilterSetting = new FilterState();
int idx_filter_name = atts.getIndex("name");
if (idx_filter_name != -1) {
tmpFilterSetting.name = atts.getValue(idx_filter_name);
}
}
}
/**
* {@inheritDoc}
*/
@Override
public void endElement(String namespaceURI, String localName, String qualifiedName) throws SAXException {
String tagName = localName.toLowerCase();
if (tagName.equals("apiresponse")) {
if (tmpLayerSetting != null) {
tmpLayerSetting.apiResponse = stringBuffer.toString();
}
apiResponseMode = false;
}
// if this is enclosed in apiresponse-tags, store the "raw XML" in
// the stringBuffer
if (apiResponseMode) {
stringBuffer.append("</" + localName + ">");
return;
}
if (tagName.equals("filter")) {
if (tmpFilterSetting != null) {
tmpFilterSetting.stateString.append(stringBuffer);
// add to list
if (tmpLayerSetting != null) {
tmpLayerSetting.filterSettings.add(tmpFilterSetting);
}
}
} else if (tagName.equals("uri")) {
if (tmpLayerSetting != null) {
tmpLayerSetting.directURI += stringBuffer.toString();
}
} else if (tagName.equals("downloaduri")) {
if (tmpLayerSetting != null) {
tmpLayerSetting.downloadURI += stringBuffer.toString();
}
} else if (tagName.equals("layer")) {
fullSetting.layerSettings.add(tmpLayerSetting);
}
stringBuffer = new StringBuffer();
}
/**
* Add a new Layer and initialize it according to the given LayerSetting
* object, including filters
*
* @param layerSetting
* - LayerSetting describing the new layer to be set-up
* @see LayerState
*/
private void setupLayer(LayerState layerSetting, Interval<Date> range) {
View newView = null;
try {
URI directURI = new URI(layerSetting.directURI);
// first setup the cached API response, if available
if (layerSetting.apiResponse != null) {
APIResponse apiResponse = new APIResponse(layerSetting.apiResponse, true);
APIResponseDump.getSingletonInstance().putResponse(apiResponse);
}
// If scheme is jpip, check if source was API call and file
// still exists
if (directURI.getScheme().equalsIgnoreCase("jpip") && (layerSetting.downloadURI.contains(Settings.getSingletonInstance().getProperty("API.jp2series.path")) || layerSetting.downloadURI.contains(Settings.getSingletonInstance().getProperty("API.jp2images.path")))) {
Log.info(">> LayersModel.StateParser.setupLayer() > Check if API-generated file \"" + layerSetting.directURI + "\" still exists... ");
URL testURL = new URL(layerSetting.directURI.replaceFirst("jpip", "http").replaceFirst(":8090", "/jp2"));
HttpURLConnection testConnection = (HttpURLConnection) testURL.openConnection();
int responseCode;
try {
testConnection.connect();
responseCode = testConnection.getResponseCode();
} catch (IOException e) {
responseCode = 400;
}
// If file does not exist any more -> use downloadURI to
// reconstruct API-call
if (responseCode != 200) {
String jpipRequest = layerSetting.downloadURI + "&jpip=true&verbose=true&linked=true";
Log.info(">> LayersModel.StateParser.setupLayer() > \"" + layerSetting.directURI + "\" does not exist any more.");
Log.info(">> LayersModel.StateParser.setupLayer() > Requesting \"" + jpipRequest + "\" instead.");
newView = APIRequestManager.requestData(true, new URL(jpipRequest), new URI(layerSetting.downloadURI), range, true);
} else { // If file exists -> Open file
Log.info(">> LayersModel.StateParser.setupLayer() > \"" + layerSetting.directURI + "\" still exists, load it.");
newView = APIRequestManager.newLoad(directURI, new URI(layerSetting.downloadURI), true, range);
}
} else { // If no API file -> Open file
Log.info(">> LayersModel.StateParser.setupLayer() > Load file \"" + layerSetting.directURI + "\"");
newView = APIRequestManager.newLoad(directURI, true, range);
}
} catch (IOException e) {
Message.err("An error occured while opening the file!", e.getMessage(), false);
} catch (URISyntaxException e) {
// This should never happen
e.printStackTrace();
} finally {
// go through all sub view chains of the layered
// view and try to find the
// view chain of the corresponding image info view
// TODO Markus Langenberg Can't we change the
// APIRequestManager.newLoad to return the topmost View, instead
// of searching it here?
// TODO Malte Nuhn this is soo ugly!
// check if we could load add a new layer/view
if (newView != null) {
LayeredView layeredView = LayersModel.getSingletonInstance().getLayeredView();
for (int i = 0; i < layeredView.getNumLayers(); i++) {
View subView = layeredView.getLayer(i);
// if view has been found
if (subView != null && newView.equals(subView.getAdapter(ImageInfoView.class))) {
newView = subView;
break;
}
}
} else {
// this case is executed, if an error occured while adding
// the layer
}
}
}
/**
* Finally setup the viewchain, filters, ... according to the internal
* FullSetting representation
*
* @see FullState
*/
public void setupLayers() {
// First clear all Layers
Log.info(">> LayersModel.StateParser.setupLayers() > Removing previously existing layers");
int removedLayers = 0;
while (LayersModel.getSingletonInstance().getNumLayers() > 0 || removedLayers > 1000) {
LayersModel.getSingletonInstance().removeLayer(0);
removedLayers++;
}
// Sort the list of layers by id
Collections.sort(fullSetting.layerSettings);
// reverse the list, since the layers get stacked up
Collections.reverse(fullSetting.layerSettings);
boolean regionIsInitialized = false;
for (LayerState currentLayerSetting : fullSetting.layerSettings) {
setupLayer(currentLayerSetting, null);
// setup the region as soon as the first layer has been added
if (!regionIsInitialized) {
setupRegion();
regionIsInitialized = false;
}
}
}
/**
* Setup the RegionView
*/
private void setupRegion() {
if (fullSetting.regionViewState != null) {
Log.info(">> LayersModel.StateParser.setupLayers() > Setting up RegionView");
RegionViewState regionViewState = fullSetting.regionViewState;
RegionView regionView = LayersModel.getSingletonInstance().getLayeredView().getAdapter(RegionView.class);
Region region = StaticRegion.createAdaptedRegion(regionViewState.regionX, regionViewState.regionY, regionViewState.regionWidth, regionViewState.regionHeight);
regionView.setRegion(region, new ChangeEvent());
} else {
Log.info(">> LayersModel.StateParser.setupLayers() > Skipping RegionView setup.");
}
}
// private classes
/**
* Class representing the full JHV state
*/
private class FullState {
/**
* Vector of LayerStates contained in the state file
*/
Vector<LayerState> layerSettings = new Vector<LayerState>();
/**
* Representation of the RegionView's region
*/
RegionViewState regionViewState = new RegionViewState();
}
/**
* Class representing the RegionView's region
*/
private class RegionViewState {
/**
* Variables describing the RegionView's region
*/
double regionX, regionY, regionWidth, regionHeight = 0;
}
/**
* Class representing the state of a filter
*/
private class FilterState {
/**
* Identifier of the Filter (e.g. class name)
*/
String name = "";
/**
* String representing the filter's state
*/
StringBuffer stateString = new StringBuffer("");
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return "FilterSetting{ name: " + name + " state: " + stateString + "}";
}
}
/**
* Class representing the state of a layer
*/
private class LayerState implements Comparable<LayerState> {
/**
* The layer's id
*/
int id = -1;
/**
* Direct URI
*/
String directURI = "";
/**
* Downloadable URI
*/
String downloadURI = "";
/**
* API response XML
*/
String apiResponse = null;
/**
* Store settings for all of this layer's filters
*/
Vector<FilterState> filterSettings = new Vector<FilterState>();
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return "LayerSetting{ id: " + id + ", URI: " + directURI + ", downloadURI: " + downloadURI + " FilterSettings: " + filterSettings + "}";
}
/**
* Sort Layers by their ids.
* <p>
* {@inheritDoc}
*/
@Override
public int compareTo(LayerState other) {
if (other != null) {
LayerState otherLayerSetting = other;
return new Integer(id).compareTo(otherLayerSetting.id);
} else {
return 0;
}
}
}
}
}
|
package com.xpn.xwiki.doc;
import com.xpn.xwiki.XWiki;
import com.xpn.xwiki.XWikiConstant;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.XWikiException;
import com.xpn.xwiki.content.parsers.LinkParser;
import com.xpn.xwiki.content.parsers.DocumentParser;
import com.xpn.xwiki.content.parsers.ReplacementResultCollection;
import com.xpn.xwiki.content.parsers.RenamePageReplaceLinkHandler;
import com.xpn.xwiki.content.Link;
import com.xpn.xwiki.api.DocumentSection;
import com.xpn.xwiki.notify.XWikiNotificationRule;
import com.xpn.xwiki.objects.BaseCollection;
import com.xpn.xwiki.objects.BaseObject;
import com.xpn.xwiki.objects.BaseProperty;
import com.xpn.xwiki.objects.ListProperty;
import com.xpn.xwiki.objects.classes.BaseClass;
import com.xpn.xwiki.objects.classes.ListClass;
import com.xpn.xwiki.objects.classes.PropertyClass;
import com.xpn.xwiki.objects.classes.StaticListClass;
import com.xpn.xwiki.plugin.query.XWikiCriteria;
import com.xpn.xwiki.render.XWikiVelocityRenderer;
import com.xpn.xwiki.store.XWikiAttachmentStoreInterface;
import com.xpn.xwiki.store.XWikiStoreInterface;
import com.xpn.xwiki.store.XWikiVersioningStoreInterface;
import com.xpn.xwiki.util.Util;
import com.xpn.xwiki.validation.XWikiValidationInterface;
import com.xpn.xwiki.validation.XWikiValidationStatus;
import com.xpn.xwiki.web.EditForm;
import com.xpn.xwiki.web.ObjectAddForm;
import com.xpn.xwiki.web.XWikiMessageTool;
import com.xpn.xwiki.web.XWikiRequest;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ecs.filter.CharacterFilter;
import org.apache.oro.text.regex.MalformedPatternException;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.tools.VelocityFormatter;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.dom.DOMDocument;
import org.dom4j.dom.DOMElement;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.suigeneris.jrcs.diff.Diff;
import org.suigeneris.jrcs.diff.DifferentiationFailedException;
import org.suigeneris.jrcs.diff.Revision;
import org.suigeneris.jrcs.rcs.Version;
import org.suigeneris.jrcs.util.ToString;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.lang.ref.SoftReference;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class XWikiDocument
{
private static final Log log = LogFactory.getLog(XWikiDocument.class);
private String title;
private String parent;
private String web;
private String name;
private String content;
private String meta;
private String format;
private String creator;
private String author;
private String contentAuthor;
private String customClass;
private Date contentUpdateDate;
private Date updateDate;
private Date creationDate;
private Version version;
private long id = 0;
private boolean mostRecent = false;
private boolean isNew = true;
private String template;
private String language;
private String defaultLanguage;
private int translation;
private String database;
private BaseObject tags;
// Comment on the latest modification
private String comment;
// Used to make sure the MetaData String is regenerated
private boolean isContentDirty = true;
// Used to make sure the MetaData String is regenerated
private boolean isMetaDataDirty = true;
public static final int HAS_ATTACHMENTS = 1;
public static final int HAS_OBJECTS = 2;
public static final int HAS_CLASS = 4;
private int elements = HAS_OBJECTS | HAS_ATTACHMENTS;
// Meta Data
private BaseClass xWikiClass;
private String xWikiClassXML;
private Map xWikiObjects = new HashMap();
private List attachmentList;
// Caching
private boolean fromCache = false;
private ArrayList objectsToRemove = new ArrayList();
// Template by default assign to a view
private String defaultTemplate;
private String validationScript;
private Object wikiNode;
// We are using a SoftReference which will allow the archive to be
// discarded by the Garbage collector as long as the context is closed (usually during the request)
private SoftReference archive;
private XWikiStoreInterface store;
public XWikiStoreInterface getStore(XWikiContext context)
{
return context.getWiki().getStore();
}
public XWikiAttachmentStoreInterface getAttachmentStore(XWikiContext context)
{
return context.getWiki().getAttachmentStore();
}
public XWikiVersioningStoreInterface getVersioningStore(XWikiContext context)
{
return context.getWiki().getVersioningStore();
}
public XWikiStoreInterface getStore()
{
return store;
}
public void setStore(XWikiStoreInterface store)
{
this.store = store;
}
public long getId()
{
if ((language == null) || language.trim().equals("")) {
id = getFullName().hashCode();
} else {
id = (getFullName() + ":" + language).hashCode();
}
//if (log.isDebugEnabled())
// log.debug("ID: " + getFullName() + " " + language + ": " + id);
return id;
}
public void setId(long id)
{
this.id = id;
}
/**
* @return the name of the space of the document
*/
public String getSpace()
{
return web;
}
public void setSpace(String space)
{
this.web = space;
}
/**
* @deprecated use {@link #getSpace()} instead
*/
public String getWeb()
{
return getSpace();
}
/**
* @deprecated use {@link #setSpace(String)} instead
*/
public void setWeb(String web)
{
setSpace(web);
}
public String getVersion()
{
return getRCSVersion().toString();
}
public void setVersion(String version)
{
this.version = new Version(version);
}
public Version getRCSVersion()
{
if (version == null) {
version = new Version("1.1");
}
return version;
}
public void setRCSVersion(Version version)
{
this.version = version;
}
public XWikiDocument()
{
this("Main", "WebHome");
}
public XWikiDocument(String web, String name)
{
setSpace(web);
int i1 = name.indexOf(".");
if (i1 == -1) {
setName(name);
} else {
setSpace(name.substring(0, i1));
setName(name.substring(i1 + 1));
}
this.updateDate = new Date();
updateDate.setTime((updateDate.getTime() / 1000) * 1000);
this.contentUpdateDate = new Date();
contentUpdateDate.setTime((contentUpdateDate.getTime() / 1000) * 1000);
this.creationDate = new Date();
creationDate.setTime((creationDate.getTime() / 1000) * 1000);
this.parent = "";
this.content = "\n";
this.format = "";
this.author = "";
this.language = "";
this.defaultLanguage = "";
this.attachmentList = new ArrayList();
this.customClass = "";
this.comment = "";
}
public XWikiDocument getParentDoc()
{
return new XWikiDocument(getSpace(), getParent());
}
public String getParent()
{
return parent != null ? parent : "";
}
public void setParent(String parent)
{
if (parent != null && !parent.equals(this.parent)) {
setMetaDataDirty(true);
}
this.parent = parent;
}
public String getContent()
{
return content;
}
public void setContent(String content)
{
if (!content.equals(this.content)) {
setContentDirty(true);
setWikiNode(null);
}
this.content = content;
}
public String getRenderedContent(XWikiContext context) throws XWikiException
{
return context.getWiki().getRenderingEngine().renderDocument(this, context);
}
public String getRenderedContent(String text, XWikiContext context)
{
String result;
HashMap backup = new HashMap();
try {
backupContext(backup, context);
setAsContextDoc(context);
result = context.getWiki().getRenderingEngine().renderText(text, this, context);
} finally {
restoreContext(backup, context);
}
return result;
}
public String getEscapedContent(XWikiContext context) throws XWikiException
{
CharacterFilter filter = new CharacterFilter();
return filter.process(getTranslatedContent(context));
}
public String getName()
{
return this.name;
}
public void setName(String name)
{
this.name = name;
}
public String getFullName()
{
StringBuffer buf = new StringBuffer();
buf.append(getSpace());
buf.append(".");
buf.append(getName());
return buf.toString();
}
public void setFullName(String name)
{
setFullName(name, null);
}
public String getTitle()
{
return (title != null) ? title : "";
}
/**
* @param context the XWiki context used to get acces to the XWikiRenderingEngine object
* @return the document title. If a title has not been provided, look for a section title in
* the document's content and if not found return the page name. The returned title
* is also interpreted which means it's allowed to use Velocity, Groovy, etc syntax
* within a title.
*/
public String getDisplayTitle(XWikiContext context)
{
// 1) Check if the user has provided a title
String title = getTitle();
// 2) If not, then try to extract the title from the first document section title
if (title.length() == 0) {
title = extractTitle();
}
// 3) Last if a title has been found renders it as it can contain macros, velocity code,
// groovy, etc.
if (title.length() > 0) {
// This will not completely work for scriting code in title referencing variables
// defined elsewhere. In that case it'll only work if those variables have been
// parsed and put in the corresponding scripting context. This will not work for
// breadcrumbs for example.
title = context.getWiki().getRenderingEngine().interpretText(title, this, context);
} else {
// 4) No title has been found, return the page name as the title
title = getName();
}
return title;
}
/**
* @return the first level 1 or level 1.1 title text in the document's content or "" if none
* are found
* @todo this method has nothing to do in this class and should be moved elsewhere
*/
public String extractTitle()
{
try {
String content = getContent();
int i1 = 0;
int i2;
while (true) {
i2 = content.indexOf("\n", i1);
String title = "";
if (i2 != -1) {
title = content.substring(i1, i2).trim();
} else {
title = content.substring(i1).trim();
}
if ((!title.equals("")) && (title.matches("1(\\.1)?\\s+.+"))) {
return title.substring(title.indexOf(" ")).trim();
}
if (i2 == -1) {
break;
}
i1 = i2 + 1;
}
} catch (Exception e) {
}
return "";
}
public void setTitle(String title)
{
if (title != null && !title.equals(this.title)) {
setContentDirty(true);
}
this.title = title;
}
public String getFormat()
{
return format != null ? format : "";
}
public void setFormat(String format)
{
this.format = format;
if (!format.equals(this.format)) {
setMetaDataDirty(true);
}
}
public String getAuthor()
{
return author != null ? author.trim() : "";
}
public String getContentAuthor()
{
return contentAuthor != null ? contentAuthor.trim() : "";
}
public void setAuthor(String author)
{
if (!getAuthor().equals(author)) {
setMetaDataDirty(true);
}
this.author = author;
}
public void setContentAuthor(String contentAuthor)
{
if (!getContentAuthor().equals(contentAuthor)) {
setMetaDataDirty(true);
}
this.contentAuthor = contentAuthor;
}
public String getCreator()
{
return creator != null ? creator.trim() : "";
}
public void setCreator(String creator)
{
if (!getCreator().equals(creator)) {
setMetaDataDirty(true);
}
this.creator = creator;
}
public Date getDate()
{
if (updateDate == null) {
return new Date();
} else {
return updateDate;
}
}
public void setDate(Date date)
{
if ((date != null) && (!date.equals(this.updateDate))) {
setMetaDataDirty(true);
}
// Make sure we drop milliseconds for consistency with the database
if (date != null) {
date.setTime((date.getTime() / 1000) * 1000);
}
this.updateDate = date;
}
public Date getCreationDate()
{
if (creationDate == null) {
return new Date();
} else {
return creationDate;
}
}
public void setCreationDate(Date date)
{
if ((date != null) && (!date.equals(creationDate))) {
setMetaDataDirty(true);
}
// Make sure we drop milliseconds for consistency with the database
if (date != null) {
date.setTime((date.getTime() / 1000) * 1000);
}
this.creationDate = date;
}
public Date getContentUpdateDate()
{
if (contentUpdateDate == null) {
return new Date();
} else {
return contentUpdateDate;
}
}
public void setContentUpdateDate(Date date)
{
if ((date != null) && (!date.equals(this.contentUpdateDate))) {
setMetaDataDirty(true);
}
// Make sure we drop milliseconds for consistency with the database
if (date != null) {
date.setTime((date.getTime() / 1000) * 1000);
}
this.contentUpdateDate = date;
}
public String getMeta()
{
return meta;
}
public void setMeta(String meta)
{
if (meta == null) {
if (this.meta != null) {
setMetaDataDirty(true);
}
} else if (!meta.equals(this.meta)) {
setMetaDataDirty(true);
}
this.meta = meta;
}
public void appendMeta(String meta)
{
StringBuffer buf = new StringBuffer(this.meta);
buf.append(meta);
buf.append("\n");
this.meta = buf.toString();
setMetaDataDirty(true);
}
public boolean isContentDirty()
{
return isContentDirty;
}
public void incrementVersion()
{
if (version == null) {
version = new Version("1.1");
} else {
version = version.next();
}
}
public void setContentDirty(boolean contentDirty)
{
isContentDirty = contentDirty;
}
public boolean isMetaDataDirty()
{
return isMetaDataDirty;
}
public void setMetaDataDirty(boolean metaDataDirty)
{
isMetaDataDirty = metaDataDirty;
}
public String getAttachmentURL(String filename, XWikiContext context)
{
return getAttachmentURL(filename, "download", context);
}
public String getAttachmentURL(String filename, String action, XWikiContext context)
{
URL url = context.getURLFactory().createAttachmentURL(filename, getSpace(), getName(),
action, null, getDatabase(), context);
return context.getURLFactory().getURL(url, context);
}
public String getExternalAttachmentURL(String filename, String action, XWikiContext context) {
URL url = context.getURLFactory().createAttachmentURL(filename, getSpace(), getName(), action, null, getDatabase(), context);
return url.toString();
}
public String getAttachmentURL(String filename, String action, String querystring,
XWikiContext context)
{
URL url = context.getURLFactory().createAttachmentURL(filename, getSpace(), getName(),
action, querystring, getDatabase(), context);
return context.getURLFactory().getURL(url, context);
}
public String getAttachmentRevisionURL(String filename, String revision, XWikiContext context)
{
URL url = context.getURLFactory().createAttachmentRevisionURL(filename, getSpace(),
getName(), revision, null, getDatabase(), context);
return context.getURLFactory().getURL(url, context);
}
public String getAttachmentRevisionURL(String filename, String revision, String querystring,
XWikiContext context)
{
URL url = context.getURLFactory().createAttachmentRevisionURL(filename, getSpace(),
getName(), revision, querystring, getDatabase(), context);
return context.getURLFactory().getURL(url, context);
}
public String getURL(String action, boolean redirect, XWikiContext context)
{
URL url = context.getURLFactory()
.createURL(getSpace(), getName(), action, null, null, getDatabase(), context);
if (redirect) {
if (url == null) {
return null;
} else {
return url.toString();
}
} else {
return context.getURLFactory().getURL(url, context);
}
}
public String getURL(String action, XWikiContext context)
{
return getURL(action, false, context);
}
public String getURL(String action, String querystring, XWikiContext context)
{
URL url = context.getURLFactory().createURL(getSpace(), getName(), action,
querystring, null, getDatabase(), context);
return context.getURLFactory().getURL(url, context);
}
public String getExternalURL(String action, XWikiContext context)
{
URL url = context.getURLFactory().createExternalURL(getSpace(), getName(), action,
null, null, getDatabase(), context);
return url.toString();
}
public String getExternalURL(String action, String querystring, XWikiContext context)
{
URL url = context.getURLFactory().createExternalURL(getSpace(), getName(), action,
querystring, null, getDatabase(), context);
return url.toString();
}
public String getParentURL(XWikiContext context) throws XWikiException
{
XWikiDocument doc = new XWikiDocument();
doc.setFullName(getParent(), context);
URL url = context.getURLFactory()
.createURL(doc.getSpace(), doc.getName(), "view", null, null, getDatabase(), context);
return context.getURLFactory().getURL(url, context);
}
public XWikiDocumentArchive getDocumentArchive(XWikiContext context) throws XWikiException
{
loadArchive(context);
return getDocumentArchive();
}
/**
* return a wrapped version of an XWikiDocument. Prefer this function instead of new
* Document(XWikiDocument, XWikiContext)
*/
public com.xpn.xwiki.api.Document newDocument(String customClassName, XWikiContext context)
{
if (!((customClassName == null) || (customClassName.equals("")))) {
try {
Class[] classes = new Class[]{XWikiDocument.class, XWikiContext.class};
Object[] args = new Object[]{this, context};
return (com.xpn.xwiki.api.Document) Class.forName(customClassName)
.getConstructor(classes).newInstance(args);
} catch (InstantiationException e) {
e.printStackTrace(); // To change body of catch statement use File | Settings | File Templates.
} catch (IllegalAccessException e) {
e.printStackTrace(); // To change body of catch statement use File | Settings | File Templates.
} catch (ClassNotFoundException e) {
e.printStackTrace(); // To change body of catch statement use File | Settings | File Templates.
} catch (NoSuchMethodException e) {
e.printStackTrace(); // To change body of catch statement use File | Settings | File Templates.
} catch (InvocationTargetException e) {
e.printStackTrace(); // To change body of catch statement use File | Settings | File Templates.
}
}
return new com.xpn.xwiki.api.Document(this, context);
}
public com.xpn.xwiki.api.Document newDocument(XWikiContext context)
{
String customClass = getCustomClass();
return newDocument(customClass, context);
}
public void loadArchive(XWikiContext context) throws XWikiException
{
if (archive == null) {
XWikiDocumentArchive arch =
getVersioningStore(context).getXWikiDocumentArchive(this, context);
// We are using a SoftReference which will allow the archive to be
// discarded by the Garbage collector as long as the context is closed (usually during the request)
archive = new SoftReference(arch);
}
}
public XWikiDocumentArchive getDocumentArchive()
{
// We are using a SoftReference which will allow the archive to be
// discarded by the Garbage collector as long as the context is closed (usually during the request)
if (archive == null) {
return null;
} else {
return (XWikiDocumentArchive) archive.get();
}
}
public void setDocumentArchive(XWikiDocumentArchive arch)
{
// We are using a SoftReference which will allow the archive to be
// discarded by the Garbage collector as long as the context is closed (usually during the request)
if (arch != null) {
this.archive = new SoftReference(arch);
}
}
public void setDocumentArchive(String sarch) throws XWikiException
{
XWikiDocumentArchive xda = new XWikiDocumentArchive(getId());
xda.setArchive(sarch);
setDocumentArchive(xda);
}
public Version[] getRevisions(XWikiContext context) throws XWikiException
{
return getVersioningStore(context).getXWikiDocVersions(this, context);
}
public String[] getRecentRevisions(int nb, XWikiContext context) throws XWikiException
{
try {
Version[] revisions = getVersioningStore(context).getXWikiDocVersions(this, context);
int length = nb;
// 0 means all revisions
if (nb == 0) {
length = revisions.length;
}
if (revisions.length < length) {
length = revisions.length;
}
String[] recentrevs = new String[length];
for (int i = 1; i <= length; i++) {
recentrevs[i - 1
] = revisions[revisions.length - i].toString();
}
return recentrevs;
} catch (Exception e) {
return new String[0];
}
}
public boolean isMostRecent()
{
return mostRecent;
}
public void setMostRecent(boolean mostRecent)
{
this.mostRecent = mostRecent;
}
public BaseClass getxWikiClass()
{
if (xWikiClass == null) {
xWikiClass = new BaseClass();
xWikiClass.setName(getFullName());
}
return xWikiClass;
}
public void setxWikiClass(BaseClass xWikiClass)
{
this.xWikiClass = xWikiClass;
}
public Map getxWikiObjects()
{
return xWikiObjects;
}
public void setxWikiObjects(Map xWikiObjects)
{
this.xWikiObjects = xWikiObjects;
}
public BaseObject getxWikiObject()
{
return getObject(getFullName());
}
public List getxWikiClasses(XWikiContext context)
{
List list = new ArrayList();
for (Iterator it = getxWikiObjects().keySet().iterator(); it.hasNext();) {
String classname = (String) it.next();
BaseClass bclass = null;
Vector objects = getObjects(classname);
for (int i = 0; i < objects.size(); i++) {
BaseObject obj = (BaseObject) objects.get(i);
if (obj != null) {
bclass = obj.getxWikiClass(context);
if (bclass != null) {
break;
}
}
}
if (bclass != null) {
list.add(bclass);
}
}
return list;
}
public int createNewObject(String classname, XWikiContext context) throws XWikiException
{
BaseObject object = BaseClass.newCustomClassInstance(classname, context);
object.setName(getFullName());
object.setClassName(classname);
Vector objects = getObjects(classname);
if (objects == null) {
objects = new Vector();
setObjects(classname, objects);
}
objects.add(object);
int nb = objects.size() - 1;
object.setNumber(nb);
setContentDirty(true);
return nb;
}
public int getObjectNumbers(String classname)
{
try {
return ((Vector) getxWikiObjects().get(classname)).size();
} catch (Exception e) {
return 0;
}
}
public Vector getObjects(String classname)
{
if (classname == null) {
return new Vector();
}
if (classname.indexOf(".") == -1) {
classname = "XWiki." + classname;
}
return (Vector) getxWikiObjects().get(classname);
}
public void setObjects(String classname, Vector objects)
{
if (classname.indexOf(".") == -1) {
classname = "XWiki." + classname;
}
getxWikiObjects().put(classname, objects);
}
public BaseObject getObject(String classname)
{
if (classname.indexOf(".") == -1) {
classname = "XWiki." + classname;
}
Vector objects = (Vector) getxWikiObjects().get(classname);
if (objects == null) {
return null;
}
for (int i = 0; i < objects.size(); i++) {
BaseObject obj = (BaseObject) objects.get(i);
if (obj != null) {
return obj;
}
}
return null;
}
public BaseObject getObject(String classname, int nb)
{
try {
if (classname.indexOf(".") == -1) {
classname = "XWiki." + classname;
}
return (BaseObject) ((Vector) getxWikiObjects().get(classname)).get(nb);
} catch (Exception e) {
return null;
}
}
public BaseObject getObject(String classname, String key, String value)
{
return getObject(classname, key, value, false);
}
public BaseObject getObject(String classname, String key, String value, boolean failover)
{
if (classname.indexOf(".") == -1) {
classname = "XWiki." + classname;
}
try {
if (value == null) {
if (failover) {
return getObject(classname);
} else {
return null;
}
}
Vector objects = (Vector) getxWikiObjects().get(classname);
if ((objects == null) || (objects.size() == 0)) {
return null;
}
for (int i = 0; i < objects.size(); i++) {
BaseObject obj = (BaseObject) objects.get(i);
if (obj != null) {
if (value.equals(obj.getStringValue(key))) {
return obj;
}
}
}
if (failover) {
return getObject(classname);
} else {
return null;
}
} catch (Exception e) {
if (failover) {
return getObject(classname);
}
e.printStackTrace();
return null;
}
}
public void addObject(String classname, BaseObject object)
{
Vector vobj = getObjects(classname);
if (vobj == null) {
setObject(classname, 0, object);
} else {
setObject(classname, vobj.size(), object);
}
setContentDirty(true);
}
public void setObject(String classname, int nb, BaseObject object)
{
Vector objects = getObjects(classname);
if (objects == null) {
objects = new Vector();
setObjects(classname, objects);
}
if (nb >= objects.size()) {
objects.setSize(nb + 1);
}
objects.set(nb, object);
object.setNumber(nb);
setContentDirty(true);
}
/**
* @return true if the document is a new one (ie it has never been saved) or false otherwise
*/
public boolean isNew()
{
return isNew;
}
public void setNew(boolean aNew)
{
isNew = aNew;
}
public void mergexWikiClass(XWikiDocument templatedoc)
{
BaseClass bclass = getxWikiClass();
BaseClass tbclass = templatedoc.getxWikiClass();
if (tbclass != null) {
if (bclass == null) {
setxWikiClass((BaseClass) tbclass.clone());
} else {
getxWikiClass().merge((BaseClass) tbclass.clone());
}
}
setContentDirty(true);
}
public void mergexWikiObjects(XWikiDocument templatedoc)
{
// TODO: look for each object if it already exist and add it if it doesn't
Iterator itobjects = templatedoc.getxWikiObjects().keySet().iterator();
while (itobjects.hasNext()) {
String name = (String) itobjects.next();
Vector objects = (Vector) getxWikiObjects().get(name);
if (objects != null) {
Vector tobjects = (Vector) templatedoc.getxWikiObjects().get(name);
for (int i = 0; i < tobjects.size(); i++) {
BaseObject bobj = (BaseObject) ((BaseObject) tobjects.get(i)).clone();
objects.add(bobj);
bobj.setNumber(objects.size() - 1);
}
} else {
Vector tobjects = templatedoc.getObjects(name);
objects = new Vector();
for (int i = 0; i < tobjects.size(); i++) {
BaseObject bobj1 = (BaseObject) tobjects.get(i);
if (bobj1 != null) {
BaseObject bobj = (BaseObject) bobj1.clone();
objects.add(bobj);
bobj.setNumber(objects.size() - 1);
}
}
getxWikiObjects().put(name, objects);
}
}
setContentDirty(true);
}
public void clonexWikiObjects(XWikiDocument templatedoc)
{
// TODO: look for each object if it already exist and add it if it doesn't
Iterator itobjects = templatedoc.getxWikiObjects().keySet().iterator();
while (itobjects.hasNext()) {
String name = (String) itobjects.next();
Vector tobjects = templatedoc.getObjects(name);
Vector objects = new Vector();
objects.setSize(tobjects.size());
for (int i = 0; i < tobjects.size(); i++) {
BaseObject bobj1 = (BaseObject) tobjects.get(i);
if (bobj1 != null) {
BaseObject bobj = (BaseObject) bobj1.clone();
objects.set(i, bobj);
}
}
getxWikiObjects().put(name, objects);
}
}
public String getTemplate()
{
if (template == null) {
return "";
} else {
return template;
}
}
public void setTemplate(String template)
{
this.template = template;
setMetaDataDirty(true);
}
public String displayPrettyName(String fieldname, XWikiContext context)
{
return displayPrettyName(fieldname, false, true, context);
}
public String displayPrettyName(String fieldname, boolean showMandatory, XWikiContext context)
{
return displayPrettyName(fieldname, false, true, context);
}
public String displayPrettyName(String fieldname, boolean showMandatory, boolean before,
XWikiContext context)
{
try {
BaseObject object = getxWikiObject();
if (object == null) {
object = getFirstObject(fieldname, context);
}
return displayPrettyName(fieldname, showMandatory, before, object, context);
} catch (Exception e) {
return "";
}
}
public String displayPrettyName(String fieldname, BaseObject obj, XWikiContext context)
{
return displayPrettyName(fieldname, false, true, obj, context);
}
public String displayPrettyName(String fieldname, boolean showMandatory, BaseObject obj,
XWikiContext context)
{
return displayPrettyName(fieldname, showMandatory, true, obj, context);
}
public String displayPrettyName(String fieldname, boolean showMandatory, boolean before,
BaseObject obj, XWikiContext context)
{
try {
PropertyClass pclass = (PropertyClass) obj.getxWikiClass(context).get(fieldname);
String dprettyName = "";
if ((showMandatory) && (pclass.getValidationRegExp() != null) &&
(!pclass.getValidationRegExp().equals("")))
{
dprettyName = context.getWiki().addMandatory(context);
}
if (before) {
return dprettyName + pclass.getPrettyName();
} else {
return pclass.getPrettyName() + dprettyName;
}
}
catch (Exception e) {
return "";
}
}
public String displayTooltip(String fieldname, XWikiContext context)
{
try {
BaseObject object = getxWikiObject();
if (object == null) {
object = getFirstObject(fieldname, context);
}
return displayTooltip(fieldname, object, context);
} catch (Exception e) {
return "";
}
}
public String displayTooltip(String fieldname, BaseObject obj, XWikiContext context)
{
try {
PropertyClass pclass = (PropertyClass) obj.getxWikiClass(context).get(fieldname);
String tooltip = pclass.getTooltip();
if ((tooltip != null) && (!tooltip.trim().equals(""))) {
String img = "<img src=\"" + context.getWiki().getSkinFile("info.gif", context) +
"\" class=\"tooltip_image\" align=\"middle\" />";
return context.getWiki().addTooltip(img, tooltip, context);
} else {
return "";
}
}
catch (Exception e) {
return "";
}
}
public String display(String fieldname, String type, BaseObject obj, XWikiContext context)
{
return display(fieldname, type, "", obj, context);
}
public String display(String fieldname, String type, String pref, BaseObject obj,
XWikiContext context)
{
HashMap backup = new HashMap();
try {
backupContext(backup, context);
setAsContextDoc(context);
type = type.toLowerCase();
StringBuffer result = new StringBuffer();
PropertyClass pclass = (PropertyClass) obj.getxWikiClass(context).get(fieldname);
String prefix =
pref + obj.getxWikiClass(context).getName() + "_" + obj.getNumber() + "_";
if (pclass.isCustomDisplayed(context)) {
pclass.displayCustom(result, fieldname, prefix, type, obj, context);
} else if (type.equals("view")) {
pclass.displayView(result, fieldname, prefix, obj, context);
} else if (type.equals("rendered")) {
String fcontent = pclass.displayView(fieldname, prefix, obj, context);
result.append(getRenderedContent(fcontent, context));
} else if (type.equals("edit")) {
context.addDisplayedField(fieldname);
result.append("{pre}");
pclass.displayEdit(result, fieldname, prefix, obj, context);
result.append("{/pre}");
} else if (type.equals("hidden")) {
result.append("{pre}");
pclass.displayHidden(result, fieldname, prefix, obj, context);
result.append("{/pre}");
} else if (type.equals("search")) {
result.append("{pre}");
prefix = obj.getxWikiClass(context).getName() + "_";
pclass.displaySearch(result, fieldname, prefix,
(XWikiCriteria) context.get("query"), context);
result.append("{/pre}");
} else {
pclass.displayView(result, fieldname, prefix, obj, context);
}
return result.toString();
}
catch (Exception ex) {
// TODO: It would better to check if the field exists rather than catching an exception
// raised by a NPE as this is currently the case here...
log.warn("Failed to display field [" + fieldname + "] in [" + type
+ "] mode for Object [" + (obj == null ? "NULL" : obj.getName()) + "]");
return "";
}
finally {
restoreContext(backup, context);
}
}
public String display(String fieldname, BaseObject obj, XWikiContext context)
{
String type = null;
try {
type = (String) context.get("display");
}
catch (Exception e) {
}
if (type == null) {
type = "view";
}
return display(fieldname, type, obj, context);
}
public String display(String fieldname, XWikiContext context)
{
try {
BaseObject object = getxWikiObject();
if (object == null) {
object = getFirstObject(fieldname, context);
}
return display(fieldname, object, context);
} catch (Exception e) {
return "";
}
}
public String display(String fieldname, String mode, XWikiContext context)
{
return display(fieldname, mode, "", context);
}
public String display(String fieldname, String mode, String prefix, XWikiContext context)
{
try {
BaseObject object = getxWikiObject();
if (object == null) {
object = getFirstObject(fieldname, context);
}
if (object == null) {
return "";
} else {
return display(fieldname, mode, object, context);
}
} catch (Exception e) {
return "";
}
}
public String displayForm(String className, String header, String format, XWikiContext context)
{
return displayForm(className, header, format, true, context);
}
public String displayForm(String className, String header, String format, boolean linebreak,
XWikiContext context)
{
Vector objects = getObjects(className);
if (format.endsWith("\\n")) {
linebreak = true;
}
BaseObject firstobject = null;
Iterator foit = objects.iterator();
while ((firstobject == null) && foit.hasNext()) {
firstobject = (BaseObject) foit.next();
}
if (firstobject == null) {
return "";
}
BaseClass bclass = firstobject.getxWikiClass(context);
Collection fields = bclass.getFieldList();
if (fields.size() == 0) {
return "";
}
StringBuffer result = new StringBuffer();
VelocityContext vcontext = new VelocityContext();
vcontext.put("formatter", new VelocityFormatter(vcontext));
for (Iterator it = fields.iterator(); it.hasNext();) {
PropertyClass pclass = (PropertyClass) it.next();
vcontext.put(pclass.getName(), pclass.getPrettyName());
}
result.append(XWikiVelocityRenderer.evaluate(header, context.getDoc().getFullName(),
vcontext, context));
if (linebreak) {
result.append("\n");
}
// display each line
for (int i = 0; i < objects.size(); i++) {
vcontext.put("id", new Integer(i + 1));
BaseObject object = (BaseObject) objects.get(i);
if (object != null) {
for (Iterator it = bclass.getPropertyList().iterator(); it.hasNext();) {
String name = (String) it.next();
vcontext.put(name, display(name, object, context));
}
result.append(XWikiVelocityRenderer.evaluate(format, context.getDoc().getFullName(),
vcontext, context));
if (linebreak) {
result.append("\n");
}
}
}
return result.toString();
}
public String displayForm(String className, XWikiContext context)
{
Vector objects = getObjects(className);
if (objects == null) {
return "";
}
BaseObject firstobject = null;
Iterator foit = objects.iterator();
while ((firstobject == null) && foit.hasNext()) {
firstobject = (BaseObject) foit.next();
}
if (firstobject == null) {
return "";
}
BaseClass bclass = firstobject.getxWikiClass(context);
Collection fields = bclass.getFieldList();
if (fields.size() == 0) {
return "";
}
StringBuffer result = new StringBuffer();
result.append("{table}\n");
boolean first = true;
for (Iterator it = fields.iterator(); it.hasNext();) {
if (first == true) {
first = false;
} else {
result.append("|");
}
PropertyClass pclass = (PropertyClass) it.next();
result.append(pclass.getPrettyName());
}
result.append("\n");
for (int i = 0; i < objects.size(); i++) {
BaseObject object = (BaseObject) objects.get(i);
if (object != null) {
first = true;
for (Iterator it = bclass.getPropertyList().iterator(); it.hasNext();) {
if (first == true) {
first = false;
} else {
result.append("|");
}
String data = display((String) it.next(), object, context);
data = data.trim();
data = data.replaceAll("\n", " ");
if (data.length() == 0) {
result.append(" ");
} else {
result.append(data);
}
}
result.append("\n");
}
}
result.append("{table}\n");
return result.toString();
}
public boolean isFromCache()
{
return fromCache;
}
public void setFromCache(boolean fromCache)
{
this.fromCache = fromCache;
}
public void readDocMetaFromForm(EditForm eform, XWikiContext context) throws XWikiException
{
String defaultLanguage = eform.getDefaultLanguage();
if (defaultLanguage != null) {
setDefaultLanguage(defaultLanguage);
}
String defaultTemplate = eform.getDefaultTemplate();
if (defaultTemplate != null) {
setDefaultTemplate(defaultTemplate);
}
String creator = eform.getCreator();
if ((creator != null) && (!creator.equals(getCreator()))) {
if ((getCreator().equals(context.getUser()))
|| (context.getWiki().getRightService().hasAdminRights(context)))
{
setCreator(creator);
}
}
String parent = eform.getParent();
if (parent != null) {
setParent(parent);
}
// Read the comment from the form
String comment = eform.getComment();
if (comment != null) {
setComment(comment);
}
String tags = eform.getTags();
if (tags != null) {
setTags(tags, context);
}
}
/**
* add tags to the document.
*/
public void setTags(String tags, XWikiContext context) throws XWikiException
{
loadTags(context);
StaticListClass tagProp = (StaticListClass) this.tags.getxWikiClass(context)
.getField(XWikiConstant.TAG_CLASS_PROP_TAGS);
tagProp.fromString(tags);
this.tags.safeput(XWikiConstant.TAG_CLASS_PROP_TAGS, tagProp.fromString(tags));
setMetaDataDirty(true);
}
public String getTags(XWikiContext context)
{
ListProperty prop = (ListProperty) getTagProperty(context);
if (prop != null) {
return prop.getTextValue();
}
return null;
}
public List getTagsList(XWikiContext context)
{
List tagList = null;
BaseProperty prop = getTagProperty(context);
if (prop != null) {
tagList = (List) prop.getValue();
}
return tagList;
}
private BaseProperty getTagProperty(XWikiContext context)
{
loadTags(context);
return ((BaseProperty) this.tags.safeget(XWikiConstant.TAG_CLASS_PROP_TAGS));
}
private void loadTags(XWikiContext context)
{
if (this.tags == null) {
this.tags = getObject(XWikiConstant.TAG_CLASS, true, context);
}
}
public List getTagsPossibleValues(XWikiContext context)
{
loadTags(context);
String possibleValues = ((StaticListClass) this.tags.getxWikiClass(context)
.getField(XWikiConstant.TAG_CLASS_PROP_TAGS)).getValues();
return ListClass.getListFromString(possibleValues);
//((BaseProperty) this.tags.safeget(XWikiConstant.TAG_CLASS_PROP_TAGS)).toString();
}
public void readTranslationMetaFromForm(EditForm eform, XWikiContext context)
throws XWikiException
{
String content = eform.getContent();
if ((content != null) && (!content.equals(""))) {
// Cleanup in case we use HTMLAREA
// content = context.getUtil().substitute("s/<br class=\\\"htmlarea\\\"\\/>/\\r\\n/g", content);
content = context.getUtil().substitute("s/<br class=\"htmlarea\" \\/>/\r\n/g", content);
setContent(content);
}
String title = eform.getTitle();
if (title != null) {
setTitle(title);
}
}
public void readObjectsFromForm(EditForm eform, XWikiContext context) throws XWikiException
{
Iterator itobj = getxWikiObjects().keySet().iterator();
while (itobj.hasNext()) {
String name = (String) itobj.next();
Vector bobjects = getObjects(name);
Vector newobjects = new Vector();
newobjects.setSize(bobjects.size());
for (int i = 0; i < bobjects.size(); i++) {
BaseObject oldobject = getObject(name, i);
if (oldobject != null) {
BaseClass baseclass = oldobject.getxWikiClass(context);
BaseObject newobject = (BaseObject) baseclass
.fromMap(eform.getObject(baseclass.getName() + "_" + i), oldobject);
newobject.setNumber(oldobject.getNumber());
newobject.setName(getFullName());
newobjects.set(newobject.getNumber(), newobject);
}
}
getxWikiObjects().put(name, newobjects);
}
setContentDirty(true);
}
public void readFromForm(EditForm eform, XWikiContext context) throws XWikiException
{
readDocMetaFromForm(eform, context);
readTranslationMetaFromForm(eform, context);
readObjectsFromForm(eform, context);
}
/*
public void readFromTemplate(EditForm eform, XWikiContext context) throws XWikiException {
// Get the class from the template
String template = eform.getTemplate();
if ((template!=null)&&(!template.equals(""))) {
if (template.indexOf('.')==-1) {
template = getSpace() + "." + template;
}
XWiki xwiki = context.getWiki();
XWikiDocument templatedoc = xwiki.getDocument(template, context);
if (templatedoc.isNew()) {
Object[] args = { template, getFullName() };
throw new XWikiException( XWikiException.MODULE_XWIKI_STORE, XWikiException.ERROR_XWIKI_APP_TEMPLATE_DOES_NOT_EXIST,
"Template document {0} does not exist when adding to document {1}", null, args);
} else {
setTemplate(template);
mergexWikiObjects(templatedoc);
}
}
}
*/
public void readFromTemplate(EditForm eform, XWikiContext context) throws XWikiException
{
String template = eform.getTemplate();
readFromTemplate(template, context);
}
public void readFromTemplate(String template, XWikiContext context) throws XWikiException
{
if ((template != null) && (!template.equals(""))) {
String content = getContent();
if ((!content.equals("\n")) && (!content.equals("")) && !isNew()) {
Object[] args = {getFullName()};
throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
XWikiException.ERROR_XWIKI_APP_DOCUMENT_NOT_EMPTY,
"Cannot add a template to document {0} because it already has content", null,
args);
} else {
if (template.indexOf('.') == -1) {
template = getSpace() + "." + template;
}
XWiki xwiki = context.getWiki();
XWikiDocument templatedoc = xwiki.getDocument(template, context);
if (templatedoc.isNew()) {
Object[] args = {template, getFullName()};
throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
XWikiException.ERROR_XWIKI_APP_TEMPLATE_DOES_NOT_EXIST,
"Template document {0} does not exist when adding to document {1}", null,
args);
} else {
setTemplate(template);
setContent(templatedoc.getContent());
if ((getParent() == null) || (getParent().equals(""))) {
String tparent = templatedoc.getParent();
if (tparent != null) {
setParent(tparent);
}
}
if (isNew()) {
// We might have received the object from the cache
// and the templace objects might have been copied already
// we need to remove them
setxWikiObjects(new HashMap());
}
// Merge the external objects
// Currently the choice is not to merge the base class and object because it is not
// the prefered way of using external classes and objects.
mergexWikiObjects(templatedoc);
}
}
}
setContentDirty(true);
}
public void notify(XWikiNotificationRule rule, XWikiDocument newdoc, XWikiDocument olddoc,
int event, XWikiContext context)
{
// Do nothing for the moment..
// A usefull thing here would be to look at any instances of a Notification Object
// with email addresses and send an email to warn that the document has been modified..
}
/**
* Use the document passsed as parameter as the new identity for the current document.
*
* @param document the document containing the new identity
* @throws XWikiException in case of error
*/
private void clone(XWikiDocument document) throws XWikiException
{
setDatabase(document.getDatabase());
setRCSVersion(document.getRCSVersion());
setDocumentArchive(document.getDocumentArchive());
setAuthor(document.getAuthor());
setContentAuthor(document.getContentAuthor());
setContent(document.getContent());
setContentDirty(document.isContentDirty());
setCreationDate(document.getCreationDate());
setDate(document.getDate());
setCustomClass(document.getCustomClass());
setContentUpdateDate(document.getContentUpdateDate());
setTitle(document.getTitle());
setFormat(document.getFormat());
setFromCache(document.isFromCache());
setElements(document.getElements());
setId(document.getId());
setMeta(document.getMeta());
setMetaDataDirty(document.isMetaDataDirty());
setMostRecent(document.isMostRecent());
setName(document.getName());
setNew(document.isNew());
setStore(document.getStore());
setTemplate(document.getTemplate());
setSpace(document.getSpace());
setParent(document.getParent());
setCreator(document.getCreator());
setDefaultLanguage(document.getDefaultLanguage());
setDefaultTemplate(document.getDefaultTemplate());
setValidationScript(document.getValidationScript());
setLanguage(document.getLanguage());
setTranslation(document.getTranslation());
setxWikiClass((BaseClass) document.getxWikiClass().clone());
setxWikiClassXML(document.getxWikiClassXML());
setComment(document.getComment());
clonexWikiObjects(document);
copyAttachments(document);
elements = document.elements;
}
public Object clone()
{
XWikiDocument doc = null;
try {
doc = (XWikiDocument) getClass().newInstance();
doc.setDatabase(getDatabase());
doc.setRCSVersion(getRCSVersion());
doc.setDocumentArchive(getDocumentArchive());
doc.setAuthor(getAuthor());
doc.setContentAuthor(getContentAuthor());
doc.setContent(getContent());
doc.setContentDirty(isContentDirty());
doc.setCreationDate(getCreationDate());
doc.setDate(getDate());
doc.setCustomClass(getCustomClass());
doc.setContentUpdateDate(getContentUpdateDate());
doc.setTitle(getTitle());
doc.setFormat(getFormat());
doc.setFromCache(isFromCache());
doc.setElements(getElements());
doc.setId(getId());
doc.setMeta(getMeta());
doc.setMetaDataDirty(isMetaDataDirty());
doc.setMostRecent(isMostRecent());
doc.setName(getName());
doc.setNew(isNew());
doc.setStore(getStore());
doc.setTemplate(getTemplate());
doc.setSpace(getSpace());
doc.setParent(getParent());
doc.setCreator(getCreator());
doc.setDefaultLanguage(getDefaultLanguage());
doc.setDefaultTemplate(getDefaultTemplate());
doc.setValidationScript(getValidationScript());
doc.setLanguage(getLanguage());
doc.setTranslation(getTranslation());
doc.setxWikiClass((BaseClass) getxWikiClass().clone());
doc.setxWikiClassXML(getxWikiClassXML());
doc.setComment(getComment());
doc.clonexWikiObjects(this);
doc.copyAttachments(this);
doc.elements = elements;
} catch (Exception e) {
// This should not happen
}
return doc;
}
public void copyAttachments(XWikiDocument xWikiSourceDocument)
{
getAttachmentList().clear();
Iterator attit = xWikiSourceDocument.getAttachmentList().iterator();
while (attit.hasNext()) {
XWikiAttachment attachment = (XWikiAttachment) attit.next();
XWikiAttachment newattachment = (XWikiAttachment) attachment.clone();
newattachment.setDoc(this);
if (newattachment.getAttachment_archive() != null) {
newattachment.getAttachment_archive().setAttachment(newattachment);
}
if (newattachment.getAttachment_content() != null) {
newattachment.getAttachment_content().setContentDirty(true);
}
getAttachmentList().add(newattachment);
}
setContentDirty(true);
}
public void loadAttachments(XWikiContext context) throws XWikiException
{
Iterator attit = getAttachmentList().iterator();
while (attit.hasNext()) {
XWikiAttachment attachment = (XWikiAttachment) attit.next();
attachment.loadContent(context);
attachment.loadArchive(context);
}
}
public boolean equals(Object object)
{
XWikiDocument doc = (XWikiDocument) object;
if (!getName().equals(doc.getName())) {
return false;
}
if (!getSpace().equals(doc.getSpace())) {
return false;
}
if (!getAuthor().equals(doc.getAuthor())) {
return false;
}
if (!getContentAuthor().equals(doc.getContentAuthor())) {
return false;
}
if (!getParent().equals(doc.getParent())) {
return false;
}
if (!getCreator().equals(doc.getCreator())) {
return false;
}
if (!getDefaultLanguage().equals(doc.getDefaultLanguage())) {
return false;
}
if (!getLanguage().equals(doc.getLanguage())) {
return false;
}
if (getTranslation() != doc.getTranslation()) {
return false;
}
if (getDate().getTime() != doc.getDate().getTime()) {
return false;
}
if (getContentUpdateDate().getTime() != doc.getContentUpdateDate().getTime()) {
return false;
}
if (getCreationDate().getTime() != doc.getCreationDate().getTime()) {
return false;
}
if (!getFormat().equals(doc.getFormat())) {
return false;
}
if (!getTitle().equals(doc.getTitle())) {
return false;
}
if (!getContent().equals(doc.getContent())) {
return false;
}
if (!getVersion().equals(doc.getVersion())) {
return false;
}
if (!getTemplate().equals(doc.getTemplate())) {
return false;
}
if (!getDefaultTemplate().equals(doc.getDefaultTemplate())) {
return false;
}
if (!getValidationScript().equals(doc.getValidationScript())) {
return false;
}
if (!getComment().equals(doc.getComment())) {
return false;
}
if (!getxWikiClass().equals(doc.getxWikiClass())) {
return false;
}
Set list1 = getxWikiObjects().keySet();
Set list2 = doc.getxWikiObjects().keySet();
if (!list1.equals(list2)) {
return false;
}
for (Iterator it = list1.iterator(); it.hasNext();) {
String name = (String) it.next();
Vector v1 = getObjects(name);
Vector v2 = doc.getObjects(name);
if (v1.size() != v2.size()) {
return false;
}
for (int i = 0; i < v1.size(); i++) {
if ((v1.get(i) == null) && (v2.get(i) != null)) {
return false;
}
if (!v1.get(i).equals(v2.get(i))) {
return false;
}
}
}
return true;
}
public String toXML(Document doc, XWikiContext context)
{
OutputFormat outputFormat = new OutputFormat("", true);
if ((context == null) || (context.getWiki() == null)) {
outputFormat.setEncoding("UTF-8");
} else {
outputFormat.setEncoding(context.getWiki().getEncoding());
}
StringWriter out = new StringWriter();
XMLWriter writer = new XMLWriter(out, outputFormat);
try {
writer.write(doc);
return out.toString();
} catch (IOException e) {
e.printStackTrace();
return "";
}
}
public String getXMLContent(XWikiContext context) throws XWikiException
{
XWikiDocument tdoc = getTranslatedDocument(context);
Document doc = tdoc.toXMLDocument(true, true, false, false, context);
return toXML(doc, context);
}
public String toXML(XWikiContext context) throws XWikiException
{
Document doc = toXMLDocument(context);
return toXML(doc, context);
}
public String toFullXML(XWikiContext context) throws XWikiException
{
return toXML(true, false, true, true, context);
}
public void addToZip(ZipOutputStream zos, boolean withVersions, XWikiContext context)
throws IOException
{
try {
String zipname = getSpace() + "/" + getName();
String language = getLanguage();
if ((language != null) && (!language.equals(""))) {
zipname += "." + language;
}
ZipEntry zipentry = new ZipEntry(zipname);
zos.putNextEntry(zipentry);
zos.write(toXML(true, false, true, withVersions, context).getBytes());
zos.closeEntry();
} catch (Exception e) {
e.printStackTrace();
}
}
public void addToZip(ZipOutputStream zos, XWikiContext context) throws IOException
{
addToZip(zos, true, context);
}
public String toXML(boolean bWithObjects, boolean bWithRendering,
boolean bWithAttachmentContent,
boolean bWithVersions,
XWikiContext context) throws XWikiException
{
Document doc = toXMLDocument(bWithObjects, bWithRendering,
bWithAttachmentContent, bWithVersions, context);
return toXML(doc, context);
}
public Document toXMLDocument(XWikiContext context) throws XWikiException
{
return toXMLDocument(true, false, false, false, context);
}
public Document toXMLDocument(boolean bWithObjects, boolean bWithRendering,
boolean bWithAttachmentContent,
boolean bWithVersions,
XWikiContext context) throws XWikiException
{
Document doc = new DOMDocument();
Element docel = new DOMElement("xwikidoc");
doc.setRootElement(docel);
Element el = new DOMElement("web");
el.addText(getSpace());
docel.add(el);
el = new DOMElement("name");
el.addText(getName());
docel.add(el);
el = new DOMElement("language");
el.addText(getLanguage());
docel.add(el);
el = new DOMElement("defaultLanguage");
el.addText(getDefaultLanguage());
docel.add(el);
el = new DOMElement("translation");
el.addText("" + getTranslation());
docel.add(el);
el = new DOMElement("parent");
el.addText(getParent());
docel.add(el);
el = new DOMElement("creator");
el.addText(getCreator());
docel.add(el);
el = new DOMElement("author");
el.addText(getAuthor());
docel.add(el);
el = new DOMElement("customClass");
el.addText(getCustomClass());
docel.add(el);
el = new DOMElement("contentAuthor");
el.addText(getContentAuthor());
docel.add(el);
long d = getCreationDate().getTime();
el = new DOMElement("creationDate");
el.addText("" + d);
docel.add(el);
d = getDate().getTime();
el = new DOMElement("date");
el.addText("" + d);
docel.add(el);
d = getContentUpdateDate().getTime();
el = new DOMElement("contentUpdateDate");
el.addText("" + d);
docel.add(el);
el = new DOMElement("version");
el.addText(getVersion());
docel.add(el);
el = new DOMElement("title");
el.addText(getTitle());
docel.add(el);
el = new DOMElement("template");
el.addText(getTemplate());
docel.add(el);
el = new DOMElement("defaultTemplate");
el.addText(getDefaultTemplate());
docel.add(el);
el = new DOMElement("validationScript");
el.addText(getValidationScript());
docel.add(el);
el = new DOMElement("comment");
el.addText(getComment());
docel.add(el);
List alist = getAttachmentList();
for (int ai = 0; ai < alist.size(); ai++) {
XWikiAttachment attach = (XWikiAttachment) alist.get(ai);
docel.add(attach.toXML(bWithAttachmentContent, bWithVersions, context));
}
if (bWithObjects) {
// Add Class
BaseClass bclass = getxWikiClass();
if (bclass.getFieldList().size() > 0) {
docel.add(bclass.toXML(null));
}
// Add Objects
Iterator it = getxWikiObjects().values().iterator();
while (it.hasNext()) {
Vector objects = (Vector) it.next();
for (int i = 0; i < objects.size(); i++) {
BaseObject obj = (BaseObject) objects.get(i);
if (obj != null) {
BaseClass objclass = null;
if (obj.getName().equals(obj.getClassName())) {
objclass = bclass;
} else {
objclass = obj.getxWikiClass(context);
}
docel.add(obj.toXML(objclass));
}
}
}
}
// Add Content
el = new DOMElement("content");
//Filter filter = new CharacterFilter();
//String newcontent = filter.process(getContent());
//String newcontent = encodedXMLStringAsUTF8(getContent());
String newcontent = content;
el.addText(newcontent);
docel.add(el);
if (bWithRendering) {
el = new DOMElement("renderedcontent");
try {
el.addText(getRenderedContent(context));
} catch (XWikiException e) {
el.addText("Exception with rendering content: " + e.getFullMessage());
}
docel.add(el);
}
if (bWithVersions) {
el = new DOMElement("versions");
try {
el.addText(getDocumentArchive(context).getArchive());
} catch (XWikiException e) {
return null;
}
docel.add(el);
}
return doc;
}
protected String encodedXMLStringAsUTF8(String xmlString)
{
if (xmlString == null) {
return "";
}
int length = xmlString.length();
char character;
StringBuffer result = new StringBuffer();
for (int i = 0; i < length; i++) {
character = xmlString.charAt(i);
switch (character) {
case '&':
result.append("&");
break;
case '"':
result.append(""");
break;
case '<':
result.append("<");
break;
case '>':
result.append(">");
break;
case '\n':
result.append("\n");
break;
case '\r':
result.append("\r");
break;
case '\t':
result.append("\t");
break;
default:
if (character < 0x20) {
} else if (character > 0x7F) {
result.append("&
result.append(Integer.toHexString(character).toUpperCase());
result.append(";");
} else {
result.append(character);
}
break;
}
}
return result.toString();
}
protected String getElement(Element docel, String name)
{
Element el = docel.element(name);
if (el == null) {
return "";
} else {
return el.getText();
}
}
public void fromXML(String xml) throws XWikiException
{
fromXML(xml, false);
}
public void fromXML(InputStream is) throws XWikiException
{
fromXML(is, false);
}
public void fromXML(String xml, boolean withArchive) throws XWikiException
{
SAXReader reader = new SAXReader();
Document domdoc;
try {
StringReader in = new StringReader(xml);
domdoc = reader.read(in);
} catch (DocumentException e) {
throw new XWikiException(XWikiException.MODULE_XWIKI_DOC,
XWikiException.ERROR_DOC_XML_PARSING, "Error parsing xml", e, null);
}
fromXML(domdoc, withArchive);
}
public void fromXML(InputStream in, boolean withArchive) throws XWikiException
{
SAXReader reader = new SAXReader();
Document domdoc;
try {
domdoc = reader.read(in);
} catch (DocumentException e) {
throw new XWikiException(XWikiException.MODULE_XWIKI_DOC,
XWikiException.ERROR_DOC_XML_PARSING, "Error parsing xml", e, null);
}
fromXML(domdoc, withArchive);
}
public void fromXML(Document domdoc, boolean withArchive) throws XWikiException
{
Element docel = domdoc.getRootElement();
setName(getElement(docel, "name"));
setSpace(getElement(docel, "web"));
setParent(getElement(docel, "parent"));
setCreator(getElement(docel, "creator"));
setAuthor(getElement(docel, "author"));
setCustomClass(getElement(docel, "customClass"));
setContentAuthor(getElement(docel, "contentAuthor"));
setVersion(getElement(docel, "version"));
setContent(getElement(docel, "content"));
setLanguage(getElement(docel, "language"));
setDefaultLanguage(getElement(docel, "defaultLanguage"));
setTitle(getElement(docel, "title"));
setDefaultTemplate(getElement(docel, "defaultTemplate"));
setValidationScript(getElement(docel, "validationScript"));
setComment(getElement(docel, "comment"));
String strans = getElement(docel, "translation");
if ((strans == null) || strans.equals("")) {
setTranslation(0);
} else {
setTranslation(Integer.parseInt(strans));
}
String archive = getElement(docel, "versions");
if (withArchive && archive != null && archive.length() > 0) {
setDocumentArchive(archive);
}
String sdate = getElement(docel, "date");
if (!sdate.equals("")) {
Date date = new Date(Long.parseLong(sdate));
setDate(date);
}
String scdate = getElement(docel, "creationDate");
if (!scdate.equals("")) {
Date cdate = new Date(Long.parseLong(scdate));
setCreationDate(cdate);
}
List atels = docel.elements("attachment");
for (int i = 0; i < atels.size(); i++) {
Element atel = (Element) atels.get(i);
XWikiAttachment attach = new XWikiAttachment();
attach.setDoc(this);
attach.fromXML(atel);
getAttachmentList().add(attach);
}
Element cel = docel.element("class");
BaseClass bclass = new BaseClass();
if (cel != null) {
bclass.fromXML(cel);
setxWikiClass(bclass);
}
List objels = docel.elements("object");
for (int i = 0; i < objels.size(); i++) {
Element objel = (Element) objels.get(i);
BaseObject bobject = new BaseObject();
bobject.fromXML(objel);
addObject(bobject.getClassName(), bobject);
}
// We have been reading from XML so the document does not need a new version when saved
setMetaDataDirty(false);
setContentDirty(false);
}
public void setAttachmentList(List list)
{
attachmentList = list;
}
public List getAttachmentList()
{
return attachmentList;
}
public void saveAllAttachments(XWikiContext context) throws XWikiException
{
for (int i = 0; i < attachmentList.size(); i++) {
saveAttachmentContent((XWikiAttachment) attachmentList.get(i), context);
}
}
public void saveAttachmentsContent(List attachments, XWikiContext context) throws XWikiException
{
String database = context.getDatabase();
try {
// We might need to switch database to
// get the translated content
if (getDatabase() != null) {
context.setDatabase(getDatabase());
}
context.getWiki().getAttachmentStore()
.saveAttachmentsContent(attachments, this, true, context, true);
} catch (java.lang.OutOfMemoryError e) {
throw new XWikiException(XWikiException.MODULE_XWIKI_APP,
XWikiException.ERROR_XWIKI_APP_JAVA_HEAP_SPACE,
"Out Of Memory Exception");
}
finally {
if (database != null) {
context.setDatabase(database);
}
}
}
public void saveAttachmentContent(XWikiAttachment attachment, XWikiContext context)
throws XWikiException
{
saveAttachmentContent(attachment, true, true, context);
}
protected void saveAttachmentContent(XWikiAttachment attachment, boolean bParentUpdate,
boolean bTransaction, XWikiContext context) throws XWikiException
{
String database = context.getDatabase();
try {
// We might need to switch database to
// get the translated content
if (getDatabase() != null) {
context.setDatabase(getDatabase());
}
context.getWiki().getAttachmentStore()
.saveAttachmentContent(attachment, bParentUpdate, context, bTransaction);
} catch (java.lang.OutOfMemoryError e) {
throw new XWikiException(XWikiException.MODULE_XWIKI_APP,
XWikiException.ERROR_XWIKI_APP_JAVA_HEAP_SPACE,
"Out Of Memory Exception");
}
finally {
if (database != null) {
context.setDatabase(database);
}
}
}
public void loadAttachmentContent(XWikiAttachment attachment, XWikiContext context)
throws XWikiException
{
String database = context.getDatabase();
try {
// We might need to switch database to
// get the translated content
if (getDatabase() != null) {
context.setDatabase(getDatabase());
}
context.getWiki().getAttachmentStore().loadAttachmentContent(attachment, context, true);
} finally {
if (database != null) {
context.setDatabase(database);
}
}
}
public void deleteAttachment(XWikiAttachment attachment, XWikiContext context)
throws XWikiException
{
String database = context.getDatabase();
try {
// We might need to switch database to
// get the translated content
if (getDatabase() != null) {
context.setDatabase(getDatabase());
}
try {
context.getWiki().getAttachmentStore()
.deleteXWikiAttachment(attachment, context, true);
} catch (java.lang.OutOfMemoryError e) {
throw new XWikiException(XWikiException.MODULE_XWIKI_APP,
XWikiException.ERROR_XWIKI_APP_JAVA_HEAP_SPACE,
"Out Of Memory Exception");
}
} finally {
if (database != null) {
context.setDatabase(database);
}
}
}
public List getBacklinks(XWikiContext context) throws XWikiException
{
return getStore(context).loadBacklinks(getFullName(), context, true);
}
public List getLinks(XWikiContext context) throws XWikiException
{
return getStore(context).loadLinks(getId(), context, true);
}
public void renameProperties(String className, Map fieldsToRename)
{
Vector objects = getObjects(className);
if (objects == null) {
return;
}
for (int j = 0; j < objects.size(); j++) {
BaseObject bobject = (BaseObject) objects.get(j);
if (bobject == null) {
continue;
}
for (Iterator renameit = fieldsToRename.keySet().iterator(); renameit.hasNext();) {
String origname = (String) renameit.next();
String newname = (String) fieldsToRename.get(origname);
BaseProperty origprop = (BaseProperty) bobject.safeget(origname);
if (origprop != null) {
BaseProperty prop = (BaseProperty) origprop.clone();
bobject.removeField(origname);
prop.setName(newname);
bobject.addField(newname, prop);
}
}
}
setContentDirty(true);
}
public void addObjectsToRemove(BaseObject object)
{
getObjectsToRemove().add(object);
setContentDirty(true);
}
public ArrayList getObjectsToRemove()
{
return objectsToRemove;
}
public void setObjectsToRemove(ArrayList objectsToRemove)
{
this.objectsToRemove = objectsToRemove;
setContentDirty(true);
}
public List getIncludedPages(XWikiContext context)
{
try {
String pattern =
"#include(Topic|InContext|Form|Macros|parseGroovyFromPage)\\([\"'](.*?)[\"']\\)";
List list = context.getUtil().getUniqueMatches(getContent(), pattern, 2);
for (int i = 0; i < list.size(); i++) {
try {
String name = (String) list.get(i);
if (name.indexOf(".") == -1) {
list.set(i, getSpace() + "." + name);
}
} catch (Exception e) {
// This should never happen
e.printStackTrace();
return null;
}
}
return list;
} catch (Exception e) {
// This should never happen
e.printStackTrace();
return null;
}
}
public List getIncludedMacros(XWikiContext context)
{
return context.getWiki().getIncludedMacros(getSpace(), getContent(), context);
}
public List getLinkedPages(XWikiContext context)
{
try {
String pattern = "\\[(.*?)\\]";
List newlist = new ArrayList();
List list = context.getUtil().getUniqueMatches(getContent(), pattern, 1);
for (int i = 0; i < list.size(); i++) {
try {
String name = (String) list.get(i);
int i1 = name.indexOf(">");
if (i1 != -1) {
name = name.substring(i1 + 1);
}
i1 = name.indexOf(">");
if (i1 != -1) {
name = name.substring(i1 + 4);
}
i1 = name.indexOf("
if (i1 != -1) {
name = name.substring(0, i1);
}
i1 = name.indexOf("?");
if (i1 != -1) {
name = name.substring(0, i1);
}
// Let's get rid of anything that's not a real link
if (name.trim().equals("") || (name.indexOf("$") != -1) ||
(name.indexOf(":
|| (name.indexOf("\"") != -1) || (name.indexOf("\'") != -1)
|| (name.indexOf("..") != -1) || (name.indexOf(":") != -1) ||
(name.indexOf("=") != -1))
{
continue;
}
// generate the link
String newname = StringUtils.replace(Util.noaccents(name), " ", "");
// If it is a local link let's add the space
if (newname.indexOf(".") == -1) {
newname = getSpace() + "." + name;
}
if (context.getWiki().exists(newname, context)) {
name = newname;
} else {
// If it is a local link let's add the space
if (name.indexOf(".") == -1) {
name = getSpace() + "." + name;
}
}
// Let's finally ignore the autolinks
if (!name.equals(getFullName())) {
newlist.add(name);
}
} catch (Exception e) {
// This should never happen
e.printStackTrace();
return null;
}
}
return newlist;
} catch (Exception e) {
// This should never happen
e.printStackTrace();
return null;
}
}
public String displayRendered(PropertyClass pclass, String prefix, BaseCollection object,
XWikiContext context) throws XWikiException
{
String result = pclass.displayView(pclass.getName(), prefix, object, context);
return getRenderedContent(result, context);
}
public String displayView(PropertyClass pclass, String prefix, BaseCollection object,
XWikiContext context)
{
return (pclass == null) ? "" :
pclass.displayView(pclass.getName(), prefix, object, context);
}
public String displayEdit(PropertyClass pclass, String prefix, BaseCollection object,
XWikiContext context)
{
return (pclass == null) ? "" :
pclass.displayEdit(pclass.getName(), prefix, object, context);
}
public String displayHidden(PropertyClass pclass, String prefix, BaseCollection object,
XWikiContext context)
{
return (pclass == null) ? "" :
pclass.displayHidden(pclass.getName(), prefix, object, context);
}
public String displaySearch(PropertyClass pclass, String prefix, XWikiCriteria criteria,
XWikiContext context)
{
return (pclass == null) ? "" :
pclass.displaySearch(pclass.getName(), prefix, criteria, context);
}
public XWikiAttachment getAttachment(String filename)
{
List list = getAttachmentList();
for (int i = 0; i < list.size(); i++) {
XWikiAttachment attach = (XWikiAttachment) list.get(i);
if (attach.getFilename().equals(filename)) {
return attach;
}
}
for (int i = 0; i < list.size(); i++) {
XWikiAttachment attach = (XWikiAttachment) list.get(i);
if (attach.getFilename().startsWith(filename + ".")) {
return attach;
}
}
return null;
}
public BaseObject getFirstObject(String fieldname)
{
// Keeping this function with context null for compatibilit reasons
// It should not be used, since it would miss properties which are only defined in the class
// and not present in the object because the object was not updated
return getFirstObject(fieldname, null);
}
public BaseObject getFirstObject(String fieldname, XWikiContext context)
{
Collection objectscoll = getxWikiObjects().values();
if (objectscoll == null) {
return null;
}
for (Iterator itobjs = objectscoll.iterator(); itobjs.hasNext();) {
Vector objects = (Vector) itobjs.next();
for (Iterator itobjs2 = objects.iterator(); itobjs2.hasNext();) {
BaseObject obj = (BaseObject) itobjs2.next();
if (obj != null) {
BaseClass bclass = obj.getxWikiClass(context);
if (bclass != null) {
Set set = bclass.getPropertyList();
if ((set != null) && set.contains(fieldname)) {
return obj;
}
}
Set set = obj.getPropertyList();
if ((set != null) && set.contains(fieldname)) {
return obj;
}
}
}
}
return null;
}
public void setProperty(String className, String fieldName, BaseProperty value)
{
BaseObject bobject = getObject(className);
if (bobject == null) {
bobject = new BaseObject();
addObject(className, bobject);
}
bobject.setName(getFullName());
bobject.setClassName(className);
bobject.safeput(fieldName, value);
setContentDirty(true);
}
public int getIntValue(String className, String fieldName)
{
BaseObject obj = getObject(className, 0);
if (obj == null) {
return 0;
}
return obj.getIntValue(fieldName);
}
public long getLongValue(String className, String fieldName)
{
BaseObject obj = getObject(className, 0);
if (obj == null) {
return 0;
}
return obj.getLongValue(fieldName);
}
public String getStringValue(String className, String fieldName)
{
BaseObject obj = getObject(className);
if (obj == null) {
return "";
}
String result = obj.getStringValue(fieldName);
if (result.equals(" ")) {
return "";
} else {
return result;
}
}
public int getIntValue(String fieldName)
{
BaseObject object = getFirstObject(fieldName, null);
if (object == null) {
return 0;
} else {
return object.getIntValue(fieldName);
}
}
public long getLongValue(String fieldName)
{
BaseObject object = getFirstObject(fieldName, null);
if (object == null) {
return 0;
} else {
return object.getLongValue(fieldName);
}
}
public String getStringValue(String fieldName)
{
BaseObject object = getFirstObject(fieldName, null);
if (object == null) {
return "";
}
String result = object.getStringValue(fieldName);
if (result.equals(" ")) {
return "";
} else {
return result;
}
}
public void setStringValue(String className, String fieldName, String value)
{
BaseObject bobject = getObject(className);
if (bobject == null) {
bobject = new BaseObject();
addObject(className, bobject);
}
bobject.setName(getFullName());
bobject.setClassName(className);
bobject.setStringValue(fieldName, value);
setContentDirty(true);
}
public List getListValue(String className, String fieldName)
{
BaseObject obj = getObject(className);
if (obj == null) {
return new ArrayList();
}
return obj.getListValue(fieldName);
}
public List getListValue(String fieldName)
{
BaseObject object = getFirstObject(fieldName, null);
if (object == null) {
return new ArrayList();
}
return object.getListValue(fieldName);
}
/**
* @deprecated use setStringListValue or setDBStringListProperty
*/
public void setListValue(String className, String fieldName, List value)
{
BaseObject bobject = getObject(className);
if (bobject == null) {
bobject = new BaseObject();
addObject(className, bobject);
}
bobject.setName(getFullName());
bobject.setClassName(className);
bobject.setListValue(fieldName, value);
setContentDirty(true);
}
public void setStringListValue(String className, String fieldName, List value)
{
BaseObject bobject = getObject(className);
if (bobject == null) {
bobject = new BaseObject();
addObject(className, bobject);
}
bobject.setName(getFullName());
bobject.setClassName(className);
bobject.setStringListValue(fieldName, value);
setContentDirty(true);
}
public void setDBStringListValue(String className, String fieldName, List value)
{
BaseObject bobject = getObject(className);
if (bobject == null) {
bobject = new BaseObject();
addObject(className, bobject);
}
bobject.setName(getFullName());
bobject.setClassName(className);
bobject.setDBStringListValue(fieldName, value);
setContentDirty(true);
}
public void setLargeStringValue(String className, String fieldName, String value)
{
BaseObject bobject = getObject(className);
if (bobject == null) {
bobject = new BaseObject();
addObject(className, bobject);
}
bobject.setName(getFullName());
bobject.setClassName(className);
bobject.setLargeStringValue(fieldName, value);
setContentDirty(true);
}
public void setIntValue(String className, String fieldName, int value)
{
BaseObject bobject = getObject(className);
if (bobject == null) {
bobject = new BaseObject();
addObject(className, bobject);
}
bobject.setName(getFullName());
bobject.setClassName(className);
bobject.setIntValue(fieldName, value);
setContentDirty(true);
}
public String getDatabase()
{
return this.database;
}
public void setDatabase(String database)
{
this.database = database;
}
public void setFullName(String fullname, XWikiContext context)
{
if (fullname == null) {
return;
}
int i0 = fullname.lastIndexOf(":");
int i1 = fullname.lastIndexOf(".");
if (i0 != -1) {
setDatabase(fullname.substring(0, i0));
setSpace(fullname.substring(i0 + 1, i1));
setName(fullname.substring(i1 + 1));
} else {
if (i1 == -1) {
try {
setSpace(context.getDoc().getSpace());
} catch (Exception e) {
setSpace("XWiki");
}
setName(fullname);
} else {
setSpace(fullname.substring(0, i1));
setName(fullname.substring(i1 + 1));
}
}
if (getName().equals("")) {
setName("WebHome");
}
setContentDirty(true);
}
public String getLanguage()
{
if (language == null) {
return "";
} else {
return language.trim();
}
}
public void setLanguage(String language)
{
this.language = language;
}
public String getDefaultLanguage()
{
if (defaultLanguage == null) {
return "";
} else {
return defaultLanguage.trim();
}
}
public void setDefaultLanguage(String defaultLanguage)
{
this.defaultLanguage = defaultLanguage;
setMetaDataDirty(true);
}
public int getTranslation()
{
return translation;
}
public void setTranslation(int translation)
{
this.translation = translation;
setMetaDataDirty(true);
}
public String getTranslatedContent(XWikiContext context) throws XWikiException
{
String language = context.getWiki().getLanguagePreference(context);
return getTranslatedContent(language, context);
}
public String getTranslatedContent(String language, XWikiContext context) throws XWikiException
{
XWikiDocument tdoc = getTranslatedDocument(language, context);
String rev = (String) context.get("rev");
if ((rev == null) || (rev.length() == 0)) {
return tdoc.getContent();
}
XWikiDocument cdoc = context.getWiki().getDocument(tdoc, rev, context);
return cdoc.getContent();
}
public XWikiDocument getTranslatedDocument(XWikiContext context) throws XWikiException
{
String language = context.getWiki().getLanguagePreference(context);
return getTranslatedDocument(language, context);
}
public XWikiDocument getTranslatedDocument(String language, XWikiContext context)
throws XWikiException
{
XWikiDocument tdoc = this;
if (!((language == null) || (language.equals("")) || language.equals(defaultLanguage))) {
tdoc = new XWikiDocument(getSpace(), getName());
tdoc.setLanguage(language);
String database = context.getDatabase();
try {
// We might need to switch database to
// get the translated content
if (getDatabase() != null) {
context.setDatabase(getDatabase());
}
tdoc = getStore(context).loadXWikiDoc(tdoc, context);
if (tdoc.isNew()) {
tdoc = this;
}
} catch (Exception e) {
tdoc = this;
} finally {
context.setDatabase(database);
}
}
return tdoc;
}
public String getRealLanguage(XWikiContext context) throws XWikiException
{
String lang = getLanguage();
if ((lang.equals("") || lang.equals("default"))) {
return getDefaultLanguage();
} else {
return lang;
}
}
public String getRealLanguage()
{
String lang = getLanguage();
if ((lang.equals("") || lang.equals("default"))) {
return getDefaultLanguage();
} else {
return lang;
}
}
public List getTranslationList(XWikiContext context) throws XWikiException
{
return getStore().getTranslationList(this, context);
}
public List getXMLDiff(XWikiDocument origdoc, XWikiDocument newdoc, XWikiContext context)
throws XWikiException, DifferentiationFailedException
{
return getDeltas(Diff.diff(ToString.stringToArray(origdoc.toXML(context)),
ToString.stringToArray(newdoc.toXML(context))));
}
public List getContentDiff(XWikiDocument origdoc, XWikiDocument newdoc, XWikiContext context)
throws XWikiException, DifferentiationFailedException
{
return getDeltas(Diff.diff(ToString.stringToArray(origdoc.getContent()),
ToString.stringToArray(newdoc.getContent())));
}
public List getContentDiff(String origrev, String newrev, XWikiContext context)
throws XWikiException, DifferentiationFailedException
{
XWikiDocument origdoc = context.getWiki().getDocument(this, origrev, context);
XWikiDocument newdoc = context.getWiki().getDocument(this, newrev, context);
return getContentDiff(origdoc, newdoc, context);
}
public List getContentDiff(String rev, XWikiContext context)
throws XWikiException, DifferentiationFailedException
{
XWikiDocument revdoc = context.getWiki().getDocument(this, rev, context);
return getContentDiff(this, revdoc, context);
}
public List getLastChanges(XWikiContext context)
throws XWikiException, DifferentiationFailedException
{
Version version = getRCSVersion();
String prev = "1." + (version.last() - 1);
XWikiDocument prevdoc = context.getWiki().getDocument(this, prev, context);
return getDeltas(Diff.diff(ToString.stringToArray(getContent()),
ToString.stringToArray(prevdoc.getContent())));
}
public List getRenderedContentDiff(XWikiDocument origdoc, XWikiDocument newdoc,
XWikiContext context) throws XWikiException, DifferentiationFailedException
{
String content1, content2;
content1 = context.getWiki().getRenderingEngine()
.renderText(origdoc.getContent(), origdoc, context);
content2 =
context.getWiki().getRenderingEngine().renderText(newdoc.getContent(), newdoc, context);
return getDeltas(Diff.diff(ToString.stringToArray(content1),
ToString.stringToArray(content2)));
}
public List getRenderedContentDiff(String origrev, String newrev, XWikiContext context)
throws XWikiException, DifferentiationFailedException
{
XWikiDocument origdoc = context.getWiki().getDocument(this, origrev, context);
XWikiDocument newdoc = context.getWiki().getDocument(this, newrev, context);
return getRenderedContentDiff(origdoc, newdoc, context);
}
public List getRenderedContentDiff(String rev, XWikiContext context)
throws XWikiException, DifferentiationFailedException
{
XWikiDocument revdoc = context.getWiki().getDocument(this, rev, context);
return getRenderedContentDiff(this, revdoc, context);
}
protected List getDeltas(Revision rev)
{
ArrayList list = new ArrayList();
for (int i = 0; i < rev.size(); i++) {
list.add(rev.getDelta(i));
}
return list;
}
public List getMetaDataDiff(String origrev, String newrev, XWikiContext context)
throws XWikiException
{
XWikiDocument origdoc = context.getWiki().getDocument(this, origrev, context);
XWikiDocument newdoc = context.getWiki().getDocument(this, newrev, context);
return getMetaDataDiff(origdoc, newdoc, context);
}
public List getMetaDataDiff(String rev, XWikiContext context) throws XWikiException
{
XWikiDocument revdoc = context.getWiki().getDocument(this, rev, context);
return getMetaDataDiff(this, revdoc, context);
}
public List getMetaDataDiff(XWikiDocument origdoc, XWikiDocument newdoc, XWikiContext context)
throws XWikiException
{
List list = new ArrayList();
if ((origdoc == null) || (newdoc == null)) {
return list;
}
if (!origdoc.getParent().equals(newdoc.getParent())) {
list.add(new MetaDataDiff("parent", origdoc.getParent(), newdoc.getParent()));
}
if (!origdoc.getAuthor().equals(newdoc.getAuthor())) {
list.add(new MetaDataDiff("author", origdoc.getAuthor(), newdoc.getAuthor()));
}
if (!origdoc.getSpace().equals(newdoc.getSpace())) {
list.add(new MetaDataDiff("web", origdoc.getSpace(), newdoc.getSpace()));
}
if (!origdoc.getName().equals(newdoc.getName())) {
list.add(new MetaDataDiff("name", origdoc.getName(), newdoc.getName()));
}
if (!origdoc.getLanguage().equals(newdoc.getLanguage())) {
list.add(new MetaDataDiff("language", origdoc.getLanguage(), newdoc.getLanguage()));
}
if (!origdoc.getDefaultLanguage().equals(newdoc.getDefaultLanguage())) {
list.add(new MetaDataDiff("defaultLanguage", origdoc.getDefaultLanguage(),
newdoc.getDefaultLanguage()));
}
return list;
}
public List getObjectDiff(String origrev, String newrev, XWikiContext context)
throws XWikiException
{
XWikiDocument origdoc = context.getWiki().getDocument(this, origrev, context);
XWikiDocument newdoc = context.getWiki().getDocument(this, newrev, context);
return getObjectDiff(origdoc, newdoc, context);
}
public List getObjectDiff(String rev, XWikiContext context) throws XWikiException
{
XWikiDocument revdoc = context.getWiki().getDocument(this, rev, context);
return getObjectDiff(this, revdoc, context);
}
public List getObjectDiff(XWikiDocument origdoc, XWikiDocument newdoc, XWikiContext context)
throws XWikiException
{
ArrayList difflist = new ArrayList();
for (Iterator itobjs = origdoc.getxWikiObjects().values().iterator(); itobjs.hasNext();) {
Vector objects = (Vector) itobjs.next();
for (Iterator itobjs2 = objects.iterator(); itobjs2.hasNext();) {
BaseObject origobj = (BaseObject) itobjs2.next();
BaseObject newobj = newdoc.getObject(origobj.getClassName(), origobj.getNumber());
List dlist;
if (newobj == null) {
dlist = origobj.getDiff(new BaseObject(), context);
} else {
dlist = origobj.getDiff(newobj, context);
}
if (dlist.size() > 0) {
difflist.add(dlist);
}
}
}
for (Iterator itobjs = newdoc.getxWikiObjects().values().iterator(); itobjs.hasNext();) {
Vector objects = (Vector) itobjs.next();
for (Iterator itobjs2 = objects.iterator(); itobjs2.hasNext();) {
BaseObject newobj = (BaseObject) itobjs2.next();
BaseObject origobj = origdoc.getObject(newobj.getClassName(), newobj.getNumber());
if (origobj == null) {
origobj = new BaseObject();
origobj.setClassName(newobj.getClassName());
origobj.setNumber(newobj.getNumber());
List dlist = origobj.getDiff(newobj, context);
if (dlist.size() > 0) {
difflist.add(dlist);
}
}
}
}
return difflist;
}
public List getClassDiff(XWikiDocument origdoc, XWikiDocument newdoc, XWikiContext context)
throws XWikiException
{
ArrayList difflist = new ArrayList();
BaseClass origclass = origdoc.getxWikiClass();
BaseClass newclass = newdoc.getxWikiClass();
if ((newclass == null) && (origclass == null)) {
return difflist;
}
List dlist = origclass.getDiff(newclass, context);
if (dlist.size() > 0) {
difflist.add(dlist);
}
return difflist;
}
/**
* Rename the current document and all the backlinks leading to it. See
* {@link #rename(String, java.util.List, com.xpn.xwiki.XWikiContext)} for more details.
*
* @param newDocumentName the new document name. If the space is not specified then defaults
* to the current space.
* @param context the ubiquitous XWiki Context
* @throws XWikiException in case of an error
*/
public void rename(String newDocumentName, XWikiContext context)
throws XWikiException
{
rename(newDocumentName, getBacklinks(context), context);
}
/**
* Rename the current document and all the links pointing to it in the list of passed backlink
* documents. The renaming algorithm takes into account the fact that there are several ways to
* write a link to a given page and all those forms need to be renamed. For example the
* following links all point to the same page:
* <ul>
* <li>[Page]</li>
* <li>[Page?param=1]</li>
* <li>[currentwiki:Page]</li>
* <li>[CurrentSpace.Page]</li>
* </ul>
* <p>Note: links without a space are renamed with the space added.</p>
*
* @param newDocumentName the new document name. If the space is not specified then defaults
* to the current space.
* @param backlinkDocumentNames the list of documents to parse and for which links will be
* modified to point to the new renamed document.
* @param context the ubiquitous XWiki Context
* @throws XWikiException in case of an error
*/
public void rename(String newDocumentName, List backlinkDocumentNames,
XWikiContext context) throws XWikiException
{
// TODO: Do all this in a single DB transaction as otherwise the state will be unknown if
// something fails in the middle...
if (isNew()) {
return;
}
// This link handler recognizes that 2 links are the same when they point to the same
// document (regardless of query string, target or alias). It keeps the query string,
// target and alias from the link being replaced.
RenamePageReplaceLinkHandler linkHandler = new RenamePageReplaceLinkHandler();
// Transform string representation of old and new links so that they can be manipulated.
Link oldLink = new LinkParser().parse(getFullName());
Link newLink = new LinkParser().parse(newDocumentName);
// Verify if the user is trying to rename to the same name... In that case, simply exits
// for efficiency.
if (linkHandler.compare(newLink, oldLink)) {
return;
}
// Step 1: Copy the document under a new name
context.getWiki().copyDocument(getFullName(), newDocumentName, context);
// Step 2: For each backlink to rename, parse the backlink document and replace the links
// with the new name.
// Note: we ignore invalid links here. Invalid links should be shown to the user so
// that they fix them but the rename feature ignores them.
DocumentParser documentParser = new DocumentParser();
for (Iterator it = backlinkDocumentNames.iterator(); it.hasNext();) {
String backlinkDocumentName = (String) it.next();
XWikiDocument backlinkDocument =
context.getWiki().getDocument(backlinkDocumentName, context);
// Note: Here we cannot do a simple search/replace as there are several ways to point
// to the same document. For example [Page], [Page?param=1], [currentwiki:Page],
// [CurrentSpace.Page] all point to the same document. Thus we have to parse the links
// to recognize them and do the replace.
ReplacementResultCollection result = documentParser.parseLinksAndReplace(
backlinkDocument.getContent(), oldLink, newLink, linkHandler, getSpace());
backlinkDocument.setContent((String) result.getModifiedContent());
context.getWiki().saveDocument(backlinkDocument, context);
}
// Step 3: Delete the old document
context.getWiki().deleteDocument(this, context);
// Step 4: The current document needs to point to the renamed document as otherwise it's
// pointing to an invalid XWikiDocument object as it's been deleted...
clone(context.getWiki().getDocument(newDocumentName, context));
}
public XWikiDocument copyDocument(String newDocumentName, XWikiContext context) throws XWikiException
{
String oldname = getFullName();
loadAttachments(context);
loadArchive(context);
/* if (oldname.equals(docname))
return this; */
XWikiDocument newdoc = (XWikiDocument) clone();
newdoc.setFullName(newDocumentName, context);
newdoc.setContentDirty(true);
newdoc.getxWikiClass().setName(newDocumentName);
Vector objects = newdoc.getObjects(oldname);
if (objects != null) {
Iterator it = objects.iterator();
while (it.hasNext()) {
BaseObject object = (BaseObject) it.next();
object.setName(newDocumentName);
}
}
return newdoc;
}
public XWikiLock getLock(XWikiContext context) throws XWikiException
{
XWikiLock theLock = getStore(context).loadLock(getId(), context, true);
if (theLock != null) {
int timeout =
context.getWiki().getXWikiPreferenceAsInt("lock_Timeout", 30 * 60, context);
if (theLock.getDate().getTime() + timeout * 1000 < new Date().getTime()) {
getStore(context).deleteLock(theLock, context, true);
theLock = null;
}
}
return theLock;
}
public void setLock(String userName, XWikiContext context) throws XWikiException
{
XWikiLock lock = new XWikiLock(getId(), userName);
getStore(context).saveLock(lock, context, true);
}
public void removeLock(XWikiContext context) throws XWikiException
{
XWikiLock lock = getStore(context).loadLock(getId(), context, true);
if (lock != null) {
getStore(context).deleteLock(lock, context, true);
}
}
public void insertText(String text, String marker, XWikiContext context) throws XWikiException
{
setContent(StringUtils.replaceOnce(getContent(), marker, text + marker));
context.getWiki().saveDocument(this, context);
}
public Object getWikiNode()
{
return wikiNode;
}
public void setWikiNode(Object wikiNode)
{
this.wikiNode = wikiNode;
}
public String getxWikiClassXML()
{
return xWikiClassXML;
}
public void setxWikiClassXML(String xWikiClassXML)
{
this.xWikiClassXML = xWikiClassXML;
}
public int getElements()
{
return elements;
}
public void setElements(int elements)
{
this.elements = elements;
}
public void setElement(int element, boolean toggle)
{
if (toggle) {
elements = elements | element;
} else {
elements = elements & (~element);
}
}
public boolean hasElement(int element)
{
return ((elements & element) == element);
}
public String getDefaultEditURL(XWikiContext context) throws XWikiException
{
com.xpn.xwiki.XWiki xwiki = context.getWiki();
if (getContent().indexOf("includeForm(") != -1) {
return getEditURL("inline", "", context);
} else {
String editor = xwiki.getEditorPreference(context);
return getEditURL("edit", editor, context);
}
}
public String getEditURL(String action, String mode, XWikiContext context) throws XWikiException
{
com.xpn.xwiki.XWiki xwiki = context.getWiki();
String language = "";
XWikiDocument tdoc = (XWikiDocument) context.get("tdoc");
String realLang = tdoc.getRealLanguage(context);
if ((xwiki.isMultiLingual(context) == true) && (!realLang.equals(""))) {
language = realLang;
}
return getEditURL(action, mode, language, context);
}
public String getEditURL(String action, String mode, String language, XWikiContext context)
{
StringBuffer editparams = new StringBuffer();
if (!mode.equals("")) {
editparams.append("xpage=");
editparams.append(mode);
}
if (!language.equals("")) {
if (!mode.equals("")) {
editparams.append("&");
}
editparams.append("language=");
editparams.append(language);
}
return getURL(action, editparams.toString(), context);
}
public String getDefaultTemplate()
{
if (defaultTemplate == null) {
return "";
} else {
return defaultTemplate;
}
}
public void setDefaultTemplate(String defaultTemplate)
{
this.defaultTemplate = defaultTemplate;
setMetaDataDirty(true);
}
public Vector getComments()
{
return getComments(true);
}
public Vector getComments(boolean asc)
{
if (asc) {
return getObjects("XWiki.XWikiComments");
} else {
Vector list = getObjects("XWiki.XWikiComments");
if (list == null) {
return list;
}
Vector newlist = new Vector();
for (int i = list.size() - 1; i >= 0; i
newlist.add(list.get(i));
}
return newlist;
}
}
public boolean isCurrentUserCreator(XWikiContext context)
{
return isCreator(context.getUser());
}
public boolean isCreator(String username)
{
if (username.equals("XWiki.XWikiGuest")) {
return false;
}
return username.equals(getCreator());
}
public boolean isCurrentUserPage(XWikiContext context)
{
String username = context.getUser();
if (username.equals("XWiki.XWikiGuest")) {
return false;
}
return context.getUser().equals(getFullName());
}
public boolean isCurrentLocalUserPage(XWikiContext context)
{
String username = context.getLocalUser();
if (username.equals("XWiki.XWikiGuest")) {
return false;
}
return context.getUser().equals(getFullName());
}
public void resetArchive(XWikiContext context) throws XWikiException
{
getVersioningStore(context).resetRCSArchive(this, true, context);
}
// This functions adds an object from an new object creation form
public BaseObject addObjectFromRequest(XWikiContext context) throws XWikiException
{
// Read info in object
ObjectAddForm form = new ObjectAddForm();
form.setRequest((HttpServletRequest) context.getRequest());
form.readRequest();
String className = form.getClassName();
int nb = createNewObject(className, context);
BaseObject oldobject = getObject(className, nb);
BaseClass baseclass = oldobject.getxWikiClass(context);
BaseObject newobject = (BaseObject) baseclass.fromMap(form.getObject(className), oldobject);
newobject.setNumber(oldobject.getNumber());
newobject.setName(getFullName());
setObject(className, nb, newobject);
return newobject;
}
// This functions adds an object from an new object creation form
public BaseObject addObjectFromRequest(String className, XWikiContext context)
throws XWikiException
{
return addObjectFromRequest(className, "", 0, context);
}
// This functions adds an object from an new object creation form
public BaseObject addObjectFromRequest(String className, String prefix, XWikiContext context)
throws XWikiException
{
return addObjectFromRequest(className, prefix, 0, context);
}
// This functions adds multiple objects from an new objects creation form
public List addObjectsFromRequest(String className, XWikiContext context) throws XWikiException
{
return addObjectsFromRequest(className, "", context);
}
// This functions adds multiple objects from an new objects creation form
public List addObjectsFromRequest(String className, String pref, XWikiContext context)
throws XWikiException
{
Map map = context.getRequest().getParameterMap();
List objectsNumberDone = new ArrayList();
List objects = new ArrayList();
Iterator it = map.keySet().iterator();
String start = pref + className + "_";
while (it.hasNext()) {
String name = (String) it.next();
if (name.startsWith(start)) {
int pos = name.indexOf("_", start.length() + 1);
String prefix = name.substring(0, pos);
int num = Integer.decode(prefix.substring(prefix.lastIndexOf("_") + 1)).intValue();
if (!objectsNumberDone.contains(new Integer(num))) {
objectsNumberDone.add(new Integer(num));
objects.add(addObjectFromRequest(className, pref, num, context));
}
}
}
return objects;
}
// This functions adds object from an new object creation form
public BaseObject addObjectFromRequest(String className, int num, XWikiContext context)
throws XWikiException
{
return addObjectFromRequest(className, "", num, context);
}
// This functions adds object from an new object creation form
public BaseObject addObjectFromRequest(String className, String prefix, int num,
XWikiContext context) throws XWikiException
{
int nb = createNewObject(className, context);
BaseObject oldobject = getObject(className, nb);
BaseClass baseclass = oldobject.getxWikiClass(context);
BaseObject newobject = (BaseObject) baseclass.fromMap(
Util.getObject(context.getRequest(), prefix + className + "_" + num), oldobject);
newobject.setNumber(oldobject.getNumber());
newobject.setName(getFullName());
setObject(className, nb, newobject);
return newobject;
}
// This functions adds an object from an new object creation form
public BaseObject updateObjectFromRequest(String className, XWikiContext context)
throws XWikiException
{
return updateObjectFromRequest(className, "", context);
}
// This functions adds an object from an new object creation form
public BaseObject updateObjectFromRequest(String className, String prefix, XWikiContext context)
throws XWikiException
{
return updateObjectFromRequest(className, prefix, 0, context);
}
// This functions adds an object from an new object creation form
public BaseObject updateObjectFromRequest(String className, String prefix, int num,
XWikiContext context) throws XWikiException
{
int nb;
BaseObject oldobject = getObject(className, num);
if (oldobject == null) {
nb = createNewObject(className, context);
oldobject = getObject(className, nb);
} else {
nb = oldobject.getNumber();
}
BaseClass baseclass = oldobject.getxWikiClass(context);
BaseObject newobject = (BaseObject) baseclass.fromMap(
Util.getObject(context.getRequest(), prefix + className + "_" + nb), oldobject);
newobject.setNumber(oldobject.getNumber());
newobject.setName(getFullName());
setObject(className, nb, newobject);
return newobject;
}
// This functions adds an object from an new object creation form
public List updateObjectsFromRequest(String className, XWikiContext context)
throws XWikiException
{
return updateObjectsFromRequest(className, "", context);
}
// This functions adds multiple objects from an new objects creation form
public List updateObjectsFromRequest(String className, String pref, XWikiContext context)
throws XWikiException
{
Map map = context.getRequest().getParameterMap();
List objectsNumberDone = new ArrayList();
List objects = new ArrayList();
Iterator it = map.keySet().iterator();
String start = pref + className + "_";
while (it.hasNext()) {
String name = (String) it.next();
if (name.startsWith(start)) {
int pos = name.indexOf("_", start.length() + 1);
String prefix = name.substring(0, pos);
int num = Integer.decode(prefix.substring(prefix.lastIndexOf("_") + 1)).intValue();
if (!objectsNumberDone.contains(new Integer(num))) {
objectsNumberDone.add(new Integer(num));
objects.add(updateObjectFromRequest(className, pref, num, context));
}
}
}
return objects;
}
public boolean isAdvancedContent()
{
String[] matches = {"<%", "#set", "#include", "#if", "public class",
"/* Advanced content */", "## Advanced content", "/* Programmatic content */",
"## Programmatic content"};
String content2 = content.toLowerCase();
for (int i = 0; i < matches.length; i++) {
if (content2.indexOf(matches[i].toLowerCase()) != -1) {
return true;
}
}
String htmlregexp =
"</?(html|body|img|a|i|b|embed|script|form|input|textarea|object|font|li|ul|ol|table|center|hr|br|p) ?([^>]*)>";
try {
Util util = new Util();
List list = util.getUniqueMatches(content2, htmlregexp, 1);
if (list.size() > 0) {
return true;
}
} catch (MalformedPatternException e) {
}
return false;
}
public boolean isProgrammaticContent()
{
String[] matches = {"<%", "\\$xwiki.xWiki", "$context.context", "$doc.document",
"$xwiki.getXWiki()", "$context.getContext()",
"$doc.getDocument()", "WithProgrammingRights(", "/* Programmatic content */",
"## Programmatic content",
"$xwiki.search(", "$xwiki.createUser", "$xwiki.createNewWiki", "$xwiki.addToAllGroup",
"$xwiki.sendMessage",
"$xwiki.copyDocument", "$xwiki.copyWikiWeb", "$xwiki.parseGroovyFromString",
"$doc.toXML()", "$doc.toXMLDocument()",
};
String content2 = content.toLowerCase();
for (int i = 0; i < matches.length; i++) {
if (content2.indexOf(matches[i].toLowerCase()) != -1) {
return true;
}
}
return false;
}
public boolean removeObject(BaseObject bobj)
{
Vector objects = getObjects(bobj.getClassName());
if (objects == null) {
return false;
}
if (objects.elementAt(bobj.getNumber()) == null) {
return false;
}
objects.set(bobj.getNumber(), null);
addObjectsToRemove(bobj);
return true;
}
/**
* Remove all the object of the class in parameter
*
* @param className the class name of the objects to be removed
*/
public boolean removeObjects(String className)
{
Vector objects = getObjects(className);
if (objects == null) {
return false;
}
Iterator it = objects.iterator();
while (it.hasNext()) {
BaseObject bobj = (BaseObject) it.next();
if (bobj != null) {
objects.set(bobj.getNumber(), null);
addObjectsToRemove(bobj);
}
}
return true;
}
// This method to split section according to title .
public List getSplitSectionsAccordingToTitle() throws XWikiException
{
// pattern to match the title
Pattern pattern =
Pattern.compile("^[\\p{Space}]*(1(\\.1)*)[\\p{Space}]+(.*?)$", Pattern.MULTILINE);
Matcher matcher = pattern.matcher(getContent());
List splitSections = new ArrayList();
int sectionNumber = 0;
String contentTemp = getContent();
int beforeIndex = 0;
while (matcher.find()) { // find title to split
String sectionLevel = matcher.group(1);
if (sectionLevel.equals("1") || sectionLevel.equals("1.1")) {
// only set editting for the title that is 1 or 1.1
sectionNumber++;
String sectionTitle = matcher.group(3);
int sectionIndex = contentTemp.indexOf(matcher.group(0), beforeIndex);
beforeIndex = sectionIndex + matcher.group(0).length();
// initialize a documentSection object
DocumentSection docSection =
new DocumentSection(sectionNumber, sectionIndex, sectionLevel, sectionTitle);
// add the document section to list
splitSections.add(docSection);
}
}
return splitSections;
}
// This function to return a Document section with parameter is sectionNumber
public DocumentSection getDocumentSection(int sectionNumber) throws XWikiException
{
// return a document section according to section number
return (DocumentSection) getSplitSectionsAccordingToTitle().get(sectionNumber - 1);
}
// This method to return the content of a section
public String getContentOfSection(int sectionNumber) throws XWikiException
{
List splitSections = getSplitSectionsAccordingToTitle();
int indexEnd = 0;
// get current section
DocumentSection section = getDocumentSection(sectionNumber);
int indexStart = section.getSectionIndex();
String sectionLevel = section.getSectionLevel();
for (int i = sectionNumber; i < splitSections.size(); i++) {
// get next section
DocumentSection nextSection = getDocumentSection(i + 1);
String nextLevel = nextSection.getSectionLevel();
if (sectionLevel.equals(nextLevel)) {
// if section level is next section level
indexEnd = nextSection.getSectionIndex();
break;
}
if (sectionLevel.length() > nextLevel.length()) {
// section level length is greater than next section level length (1.1 and 1)
indexEnd = nextSection.getSectionIndex();
break;
}
}
String sectionContent = null;
if (indexStart < 0) {
indexStart = 0;
}
if (indexEnd == 0) {
sectionContent = getContent().substring(indexStart);
} else {
sectionContent = getContent().substring(indexStart, indexEnd); // get section content
}
return sectionContent;
}
// This function to update a section content in document
public String updateDocumentSection(int sectionNumber, String newSectionContent)
throws XWikiException
{
StringBuffer newContent = new StringBuffer();
// get document section that will be edited
DocumentSection docSection = getDocumentSection(sectionNumber);
int numberOfSection = getSplitSectionsAccordingToTitle().size();
int indexSection = docSection.getSectionIndex();
if (numberOfSection == 1) {
// there is only a sections in document
String contentBegin = getContent().substring(0, indexSection);
newContent = newContent.append(contentBegin).append(newSectionContent);
return newContent.toString();
} else if (sectionNumber == numberOfSection) {
// edit lastest section that doesn't contain subtitle
String contentBegin = getContent().substring(0, indexSection);
newContent = newContent.append(contentBegin).append(newSectionContent);
return newContent.toString();
} else {
String sectionLevel = docSection.getSectionLevel();
int nextSectionIndex = 0;
// get index of next section
for (int i = sectionNumber; i < numberOfSection; i++) {
DocumentSection nextSection = getDocumentSection(i + 1); // get next section
String nextSectionLevel = nextSection.getSectionLevel();
if (sectionLevel.equals(nextSectionLevel)) {
nextSectionIndex = nextSection.getSectionIndex();
break;
} else if (sectionLevel.length() > nextSectionLevel.length()) {
nextSectionIndex = nextSection.getSectionIndex();
break;
}
}
if (nextSectionIndex == 0) {// edit the last section
newContent = newContent.append(getContent().substring(0, indexSection))
.append(newSectionContent);
return newContent.toString();
} else {
String contentAfter = getContent().substring(nextSectionIndex);
String contentBegin = getContent().substring(0, indexSection);
newContent =
newContent.append(contentBegin).append(newSectionContent).append(contentAfter);
}
return newContent.toString();
}
}
/**
* Computes a document hash, taking into account all document data: content, objects,
* attachments, metadata... TODO: cache the hash value, update only on modification.
*/
public String getVersionHashCode(XWikiContext context)
{
MessageDigest md5 = null;
try {
md5 = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException ex) {
log.error("Cannot create MD5 object", ex);
return this.hashCode() + "";
}
try {
String valueBeforeMD5 = toXML(true, false, true, false, context);
md5.update(valueBeforeMD5.getBytes());
byte[] array = md5.digest();
StringBuffer sb = new StringBuffer();
for (int j = 0; j < array.length; ++j) {
int b = array[j] & 0xFF;
if (b < 0x10) {
sb.append('0');
}
sb.append(Integer.toHexString(b));
}
return sb.toString();
} catch (Exception ex) {
log.error("Exception while computing document hash", ex);
}
return this.hashCode() + "";
}
public static String getInternalPropertyName(String propname, XWikiContext context)
{
XWikiMessageTool msg = context.getMessageTool();
String cpropname = StringUtils.capitalize(propname);
return (msg == null) ? cpropname : msg.get(cpropname);
}
public String getInternalProperty(String propname)
{
String methodName = "get" + StringUtils.capitalize(propname);
try {
Method method = getClass().getDeclaredMethod(methodName, null);
return (String) method.invoke(this, null);
} catch (Exception e) {
return null;
}
}
public String getCustomClass()
{
if (customClass == null) {
return "";
}
return customClass;
}
public void setCustomClass(String customClass)
{
this.customClass = customClass;
setMetaDataDirty(true);
}
public void setValidationScript(String validationScript)
{
this.validationScript = validationScript;
setMetaDataDirty(true);
}
public String getValidationScript()
{
if (validationScript == null) {
return "";
} else {
return validationScript;
}
}
public String getComment()
{
if (comment == null) {
return "";
}
return comment;
}
public void setComment(String comment)
{
this.comment = comment;
setMetaDataDirty(true);
}
public BaseObject newObject(String classname, XWikiContext context) throws XWikiException
{
int nb = createNewObject(classname, context);
return getObject(classname, nb);
}
public BaseObject getObject(String classname, boolean create, XWikiContext context)
{
try {
BaseObject obj = getObject(classname);
if ((obj == null) && create) {
return newObject(classname, context);
}
if (obj == null) {
return null;
} else {
return obj;
}
} catch (Exception e) {
return null;
}
}
public boolean validate(XWikiContext context) throws XWikiException
{
return validate(null, context);
}
public boolean validate(String[] classNames, XWikiContext context) throws XWikiException
{
boolean isValid = true;
if ((classNames == null) || (classNames.length == 0)) {
for (Iterator it = getxWikiObjects().keySet().iterator(); it.hasNext();) {
String classname = (String) it.next();
BaseClass bclass = context.getWiki().getClass(classname, context);
Vector objects = getObjects(classname);
for (int i = 0; i < objects.size(); i++) {
BaseObject obj = (BaseObject) objects.get(i);
if (obj != null) {
isValid &= bclass.validateObject(obj, context);
}
}
}
} else {
for (int i = 0; i < classNames.length; i++) {
Vector objects = getObjects(classNames[i]);
if (objects != null) {
for (int j = 0; j < objects.size(); j++) {
BaseObject obj = (BaseObject) objects.get(j);
if (obj != null) {
BaseClass bclass = obj.getxWikiClass(context);
isValid &= bclass.validateObject(obj, context);
}
}
}
}
}
String validationScript = "";
XWikiRequest req = context.getRequest();
if (req != null) {
validationScript = req.get("xvalidation");
}
if ((validationScript == null) || (validationScript.trim().equals(""))) {
validationScript = getValidationScript();
}
if ((validationScript != null) && (!validationScript.trim().equals(""))) {
isValid &= executeValidationScript(context, validationScript);
}
return isValid;
}
private boolean executeValidationScript(XWikiContext context, String validationScript)
throws XWikiException
{
try {
XWikiValidationInterface validObject = (XWikiValidationInterface) context.getWiki()
.parseGroovyFromPage(validationScript, context);
return validObject.validateDocument(this, context);
} catch (Throwable e) {
XWikiValidationStatus.addExceptionToContext(getFullName(), "", e, context);
return false;
}
}
public static void backupContext(HashMap backup, XWikiContext context)
{
backup.put("doc", context.getDoc());
VelocityContext vcontext = (VelocityContext) context.get("vcontext");
if (vcontext != null) {
backup.put("vdoc", vcontext.get("doc"));
backup.put("vcdoc", vcontext.get("cdoc"));
backup.put("vtdoc", vcontext.get("tdoc"));
}
Map gcontext = (Map) context.get("gcontext");
if (gcontext != null) {
backup.put("gdoc", gcontext.get("doc"));
backup.put("gcdoc", gcontext.get("cdoc"));
backup.put("gtdoc", gcontext.get("tdoc"));
}
}
public static void restoreContext(HashMap backup, XWikiContext context)
{
context.setDoc((XWikiDocument) backup.get("doc"));
VelocityContext vcontext = (VelocityContext) context.get("vcontext");
Map gcontext = (Map) context.get("gcontext");
if (vcontext != null) {
if (backup.get("vdoc") != null) {
vcontext.put("doc", backup.get("vdoc"));
}
if (backup.get("vcdoc") != null) {
vcontext.put("cdoc", backup.get("vcdoc"));
}
if (backup.get("vtdoc") != null) {
vcontext.put("tdoc", backup.get("vtdoc"));
}
}
if (gcontext != null) {
if (backup.get("gdoc") != null) {
gcontext.put("doc", backup.get("gdoc"));
}
if (backup.get("gcdoc") != null) {
gcontext.put("cdoc", backup.get("gcdoc"));
}
if (backup.get("gtdoc") != null) {
gcontext.put("tdoc", backup.get("gtdoc"));
}
}
}
public void setAsContextDoc(XWikiContext context)
{
try {
context.setDoc(this);
com.xpn.xwiki.api.Document apidoc = this.newDocument(context);
com.xpn.xwiki.api.Document tdoc = apidoc.getTranslatedDocument();
VelocityContext vcontext = (VelocityContext) context.get("vcontext");
Map gcontext = (Map) context.get("gcontext");
if (vcontext != null) {
vcontext.put("doc", apidoc);
vcontext.put("tdoc", tdoc);
}
if (gcontext != null) {
gcontext.put("doc", apidoc);
gcontext.put("tdoc", tdoc);
}
} catch (XWikiException ex) {
log.warn("Unhandled exception setting context", ex);
}
}
}
|
package com.syncleus.tests.dann.genetics;
import com.syncleus.dann.genetics.*;
import java.util.*;
import org.junit.*;
public class TestGeneticCube
{
private class VolumeAreaCubeFitness extends GeneticAlgorithmFitnessFunction
{
private double IDEAL_AREA = 2200d;
private double IDEAL_VOLUME = 6000d;
public VolumeAreaCubeFitness(GeneticAlgorithmChromosome chromosome)
{
super(chromosome);
if(chromosome.getGenes().size() < 3)
throw new IllegalArgumentException("Chromosome must have atleast 3 genes");
}
public double getError()
{
List<ValueGene> genes = this.getChromosome().getGenes();
double side1 = genes.get(0).expressionActivity();
double side2 = genes.get(1).expressionActivity();
double side3 = genes.get(2).expressionActivity();
double volume = side1 * side2 * side3;
double area = (side1*side2*2d)+(side1*side3*2d)+(side2*side3*2d);
double volumeError = Math.abs(IDEAL_VOLUME - volume);
double areaError = Math.abs(IDEAL_AREA - area);
return volumeError + areaError;
}
public int compareTo(GeneticAlgorithmFitnessFunction baseCompareWith)
{
if(!(baseCompareWith instanceof VolumeAreaCubeFitness))
throw new ClassCastException("Can only compare with VolumeAreaCubeFitness");
VolumeAreaCubeFitness compareWith = (VolumeAreaCubeFitness) baseCompareWith;
if(this.getError() < compareWith.getError())
return 1;
else if(this.getError() == compareWith.getError())
return 0;
else
return -1;
}
}
private class VolumeAreaCubePopulation extends GeneticAlgorithmPopulation
{
public VolumeAreaCubePopulation(Set<GeneticAlgorithmChromosome> initialChromosomes)
{
super(initialChromosomes);
}
protected GeneticAlgorithmFitnessFunction packageChromosome(GeneticAlgorithmChromosome chromosome)
{
return new VolumeAreaCubeFitness(chromosome);
}
}
@Test
public void testVolumeArea()
{
HashSet<GeneticAlgorithmChromosome> cubeChromosomes = new HashSet<GeneticAlgorithmChromosome>();
while(cubeChromosomes.size() < 1000)
{
cubeChromosomes.add(new GeneticAlgorithmChromosome(3, 10d));
}
VolumeAreaCubePopulation population = new VolumeAreaCubePopulation(cubeChromosomes);
VolumeAreaCubeFitness fitness = new VolumeAreaCubeFitness(population.getWinner());
while((population.getGenerations() < 10000)&&(fitness.getError() > 0.1d))
{
population.nextGeneration();
fitness = new VolumeAreaCubeFitness(population.getWinner());
}
Assert.assertTrue("Volume/Area Cube failed (error was too great)" + fitness.getError(), fitness.getError() < 0.1d);
}
}
|
package views.formdata;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import play.data.validation.ValidationError;
import models.Offer;
import models.Student;
import models.Textbook;
public class BuyOfferFormData {
public Student student = null;
public Textbook textbook = null;
public int price = 0;
public Date expiration = null;
/** The id. */
public int id;
/**
* Default constructor
*/
public BuyOfferFormData() {
}
public BuyOfferFormData(Offer formData) {
this.student = formData.getStudent();
this.textbook = formData.getTextbook();
this.price = formData.getPrice();
this.expiration = formData.getExpiration();
this.id = formData.getId();
}
public BuyOfferFormData(Student student, Textbook textbook, int price, Date date, int id) {
this.student = student;
this.textbook = textbook;
this.price = price;
this.expiration = date;
this.id = id;
}
public BuyOfferFormData(Student student, Textbook textbook, int price, Date date) {
this.student = student;
this.textbook = textbook;
this.price = price;
this.expiration = date;
}
/**
* Checks that form fields are valid. Called by bindFormRequest().
* @return null if valid, a list of ValidationError if problem is found.
*/
public List<ValidationError> validate() {
List<ValidationError> errors = new ArrayList<>();
if (student == null) {
errors.add(new ValidationError("student", "Student is required."));
}
if (textbook == null) {
errors.add(new ValidationError("textbook", "Textbook is required."));
}
if (price == 0) {
errors.add(new ValidationError("price", "Price is required."));
}
if (expiration == null) {
errors.add(new ValidationError("expiration", "Expiration is required."));
}
return errors.isEmpty() ? null : errors;
}
}
|
// This file is part of the OpenNMS(R) Application.
// OpenNMS(R) is a derivative work, containing both original code, included code and modified
// and included code are below.
// OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
// Modifications:
// 2003 Mar 20: Added code to allow the joeSNMP library to answer SNMP requests
// to be used in creating SNMP agents.
// This program is free software; you can redistribute it and/or modify
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
// For more information contact:
// Tab Size = 8
// SnmpSession.java,v 1.1.1.1 2001/11/11 17:27:22 ben Exp
// History:
// 3/29/00 Weave
// Made some minor changes here and there, but the biggest change
// is from ArrayList to LinkedList for the outstanding request. I
// realized that the session was mostly adding/deleting request
// and linked list was faster. When the ArrayList was being used
// the search was O(N), just like a linked list (actually N/2 on average).
// So the performance gains from the faster add/remove should help
// until a better structure for searching, adding, and deleteing
// can be used.
// 5/25/00 Sowmya
// Added the SnmpPortal member to abstract the communication related
// data out of this class. Added SnmpSessionPacketHandler to
// handle callbacks from the SnmpPortal
package org.opennms.protocols.snmp;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.LinkedList;
import java.util.ListIterator;
import org.opennms.protocols.snmp.asn1.ASN1;
import org.opennms.protocols.snmp.asn1.AsnEncoder;
import org.opennms.protocols.snmp.asn1.AsnEncodingException;
public class SnmpSession extends Object {
/**
* This is the command passed to the SnmpHandler if a timeout occurs. All
* errors are less than zero.
*
* @see SnmpHandler
*/
public static final int ERROR_TIMEOUT = -1;
/**
* This is the command passed to the SnmpHandler if an IOException occurs
* while attempting to transmit the request
*
* @see SnmpHandler
*/
public static final int ERROR_IOEXCEPTION = -2;
/**
* This is the command passed to the SnmpHandler if an encoding exception is
* generated when attempting to send an SnmpPduRequest message
*
* @see SnmpHandler
*/
public static final int ERROR_ENCODING = -3;
/**
* Used to contain a list of outstanding request for the session. The list
* should only contain SnmpRequest objects!
*/
private LinkedList m_requests;
/**
* The SNMP peer to whom this session will communicate with. The peer
* contains the parameters also.
*
* @see SnmpParameters
*/
private SnmpPeer m_peer;
/**
* The timer object used to schedule the SnmpRequest timeouts. It is also
* used to schedule the cleanup of the m_requests list.
*
* @see org.opennms.protocols.snmp.SnmpSession.CleanupRequest
* @see SnmpRequest
*/
private SnmpTimer m_timer;
/**
* The default SNMP callback handler. If this is not set and it is needed
* then an SnmpHandlerNotDefinedException is thrown.
*/
private SnmpHandler m_defHandler;
/**
* ASN encoder
*/
AsnEncoder m_encoder;
// thread related stuff
/**
* Provides a synchronization point
*/
private Object m_sync;
/**
* If the boolean variable is set then the destroy() method must have been
* called
*/
private boolean m_stopRun;
/**
* the receiver thread
*/
private SnmpPortal m_portal;
/**
* If this boolean value is set then the receiver thread is terminated due
* to an exception that was generated in either a handler or a socket error.
* This is considered a fatal exception.
*/
private boolean m_threadException;
/**
* This is the saved fatal excetion that can be rethrown by the application
*/
private Throwable m_why;
/**
* Inner class SessionHandler implements the interface SnmpPacketHandler to
* handle callbacks from the SnmpPortal
*/
private class SessionHandler implements SnmpPacketHandler {
public void processSnmpMessage(InetAddress agent, int port, SnmpInt32 version, SnmpOctetString community, int pduType, SnmpPduPacket pdu) throws SnmpPduEncodingException {
// now find the request and
// inform
boolean isExpired = false;
SnmpRequest req = null;
synchronized (m_requests) {
// ensures that we get the proper
// state information
req = findRequest(pdu);
if (req != null)
isExpired = req.m_expired;
}
if (isExpired == false) {
int cmd = -1;
if (req != null && req.m_pdu instanceof SnmpPduPacket)
cmd = ((SnmpPduPacket) req.m_pdu).getCommand();
else {
cmd = pdu.getCommand();
pdu.setPeer(new SnmpPeer(agent, port));
}
switch (cmd) {
case SnmpPduPacket.SET: {
String tst = new String(community.getString());
String wr = m_peer.getParameters().getWriteCommunity();
if (!tst.equals(wr)) {
throw new SnmpPduEncodingException("Invalid community string");
}
}
break;
case SnmpPduPacket.GET:
case SnmpPduPacket.GETNEXT:
case SnmpPduPacket.RESPONSE:
case SnmpPduPacket.INFORM:
case SnmpPduPacket.GETBULK:
case SnmpPduPacket.REPORT: {
String tst = new String(community.getString());
String rd = m_peer.getParameters().getReadCommunity();
if (!tst.equals(rd)) {
throw new SnmpPduEncodingException("Invalid community string");
}
}
break;
default:
throw new SnmpPduEncodingException("Invalid PDU Type for session received");
}
if (req != null) {
req.m_expired = true; // mark it as expired
req.m_handler.snmpReceivedPdu(req.m_session, ((SnmpPduRequest) pdu).getCommand(), (SnmpPduRequest) pdu);
} else {
if (m_defHandler != null)
m_defHandler.snmpReceivedPdu(null, cmd, pdu);
else
}
}
}
public void processSnmpTrap(InetAddress agent, int port, SnmpOctetString community, SnmpPduTrap pdu) throws SnmpPduEncodingException {
throw new SnmpPduEncodingException("Invalid PDU Type for session");
}
public void processBadDatagram(DatagramPacket p) {
// do nothing - discard?
}
public void processException(Exception e) {
// do nothing - discard?
}
}
/**
* This class is used to periodically cleanup the outstanding request that
* have expired. The cleanup interval is nominally once every 5 to 10
* seconds. It's used like the garbage collector for the m_requests list.
* This is used in hopes of minimizing the contention for the request array
*
*/
private class CleanupRequest implements Runnable {
/**
* Preforms the actual removal of the expired SnmpRequest elements.
*
* @see SnmpRequest
*
*/
public void run() {
synchronized (m_requests) {
if (m_requests.size() > 0) {
ListIterator iter = m_requests.listIterator(0);
while (iter.hasNext()) {
SnmpRequest req = (SnmpRequest) iter.next();
if (req.m_expired)
iter.remove();
}
}
}
// reschedule
if (!m_stopRun && !m_threadException)
m_timer.schedule(this, 1000);
}
}
/**
* <P>
* Encapsulates a byte array and the number of bytes of valid data in the
* array. The length passed to the constructor is normally less then the
* length of the encapsulated array.
* </P>
*
*/
private static class ByteArrayInfo {
/**
* The buffer
*/
private byte[] m_buf;
/**
* The valid length of the buffer
*/
private int m_length;
/**
* Builds an encapuslated array with the passed buffer and its <EM>
* valid</EM> length set to <EM>length</EM>.
*
* @param buf
* The buffer.
* @param length
* The valid length of the buffer.
*/
public ByteArrayInfo(byte[] buf, int length) {
m_buf = buf;
m_length = length;
}
/**
* returns the encapsulated array
*/
public byte[] array() {
return m_buf;
}
/**
* Returns the valid length of the encapsulate array
*/
public int size() {
return m_length;
}
}
/**
* <P>
* This method is used to encode the passed protocol data unit and return
* the encoding. The encoding is performed using the default encoder for the
* session and limits the size to a 16K buffer.
* </P>
*
* @param pdu
* The pdu to encode
*
* @return The encoded pdu request
*
* @exception SnmpPduEncodingException
* Thrown if an encoding exception occurs at the session
* level
* @exception org.opennms.protocols.snmp.asn1.AsnEncodingException
* Thrown if an encoding exception occurs in the AsnEncoder
* object.
*/
private ByteArrayInfo encode(SnmpPduPacket pdu) throws SnmpPduEncodingException, AsnEncodingException {
SnmpPeer peer = m_peer;
SnmpParameters parms = peer.getParameters();
// Get the encoder and start
// the encoding process
// get a suitable buffer (16k)
int begin = 0;
int offset = 0;
byte[] buf = new byte[16 * 1024];
// encode the snmp version
SnmpInt32 version = new SnmpInt32(parms.getVersion());
offset = version.encodeASN(buf, offset, m_encoder);
// get the correct community string. The
// SET command uses the write community, all
// others use the read community
SnmpOctetString community;
if (pdu.getCommand() == SnmpPduPacket.SET) {
String wrComm = parms.getWriteCommunity();
if (wrComm == null)
throw new SnmpPduEncodingException("Requested SET but there is no write community");
community = new SnmpOctetString(wrComm.getBytes());
} else {
community = new SnmpOctetString(parms.getReadCommunity().getBytes());
}
// encode the community strings
offset = community.encodeASN(buf, offset, m_encoder);
offset = pdu.encodeASN(buf, offset, m_encoder);
// build the header, don't forget to mark the
// pivot point
int pivot = offset;
offset = m_encoder.buildHeader(buf, offset, (byte) (ASN1.SEQUENCE | ASN1.CONSTRUCTOR), pivot);
// rotate the buffer around the pivot point
SnmpUtil.rotate(buf, 0, pivot, offset);
return new ByteArrayInfo(buf, offset);
}
/**
* <P>
* This method is used to encode the passed protocol data unit and return
* the encoding. The encoding is performed using the default encoder for the
* session and limits the size to a 16K buffer.
* </P>
*
* @param pdu
* The pdu to encode
*
* @return The encoded pdu request
*
* @exception SnmpPduEncodingException
* Thrown if an encoding exception occurs at the session
* level
* @exception org.opennms.protocols.snmp.asn1.AsnEncodingException
* Thrown if an encoding exception occurs in the AsnEncoder
* object.
*/
private ByteArrayInfo encode(SnmpPduTrap pdu) throws SnmpPduEncodingException, AsnEncodingException {
SnmpPeer peer = m_peer;
SnmpParameters parms = peer.getParameters();
// get a suitable buffer (16k)
int begin = 0;
int offset = 0;
byte[] buf = new byte[16 * 1024];
// encode the snmp version
SnmpInt32 version = new SnmpInt32(parms.getVersion());
offset = version.encodeASN(buf, offset, m_encoder);
// get the correct community string. The
// SET command uses the write community, all
// others use the read community
SnmpOctetString community = new SnmpOctetString(parms.getReadCommunity().getBytes());
// encode the community strings
offset = community.encodeASN(buf, offset, m_encoder);
offset = pdu.encodeASN(buf, offset, m_encoder);
// build the header, don't forget to mark the
// pivot point
int pivot = offset;
offset = m_encoder.buildHeader(buf, offset, (byte) (ASN1.SEQUENCE | ASN1.CONSTRUCTOR), pivot);
// rotate the buffer around the pivot point
SnmpUtil.rotate(buf, 0, pivot, offset);
return new ByteArrayInfo(buf, offset);
}
/**
* Adds an outstanding request to the session. The access to the list is
* synchronized on the actual list of request. This is done to allow
* synchronization between addRequest(), removeRequest(), and findRequest()
*
* @param req
* The request reference to add (not cloned)
*/
void addRequest(SnmpRequest req) {
synchronized (m_requests) {
m_requests.addLast(req);
}
}
/**
* Removes an outstanding request from the session. The method uses the
* Object.equals() to find a matching request. If the SnmpRequest object
* does not override the equals() method the a "by reference" equality is
* used.
*
* @param req
* The request to remove. All matching request are removed.
*/
void removeRequest(SnmpRequest req) {
synchronized (m_requests) {
if (m_requests.size() > 0) {
ListIterator iter = m_requests.listIterator(0);
while (iter.hasNext()) {
SnmpRequest cmp = (SnmpRequest) iter.next();
if (req.equals(cmp)) {
req.m_expired = true;
iter.remove();
}
}
}
}
}
/**
* Finds the first matching request in the list of outstanding request and
* returns it to the caller. The matching is done by means using the SNMP
* Protocol Data Unit's request id. If no match is found then a null is
* returned
*
* @param pdu
* The source pdu for the search.
*
* @return Returns a SnmpRequest if a match is found. Otherwise a null is
* returned.
*
*/
SnmpRequest findRequest(SnmpPduPacket pdu) {
synchronized (m_requests) {
if (m_requests.size() > 0) {
ListIterator iter = m_requests.listIterator(0);
while (iter.hasNext()) {
SnmpRequest req = (SnmpRequest) iter.next();
if (!req.m_expired && req.m_pdu instanceof SnmpPduPacket && ((SnmpPduPacket) req.m_pdu).getRequestId() == pdu.getRequestId()) {
return req;
}
}
}
}
return null;
}
/**
* Returns the internal timer object for the SNMP Session.
*
* @return The internal timer object
*
*/
SnmpTimer getTimer() {
return m_timer;
}
/**
* Transmits the specified SnmpRequest to the SnmpPeer defined by the
* session. First the SnmpPdu contained within the request is encoded using
* the session AsnEncoder, as defined by the SnmpParameters. Once the packet
* is encoded it is transmitted to the agent defined by SnmpPeer. If an
* error occurs an appropiate exception is generated.
*
* @param req
* The SnmpRequest to transmit
*
* @exception SnmpPduEncodingException
* Thrown if an encoding exception occurs at the session
* level
* @exception org.opennms.protocols.snmp.asn1.AsnEncodingException
* Thrown if an encoding exception occurs in the AsnEncoder
* object.
* @exception java.io.IOException
* Thrown if an error occurs sending the encoded datagram
*
* @see SnmpRequest
* @see SnmpParameters
* @see SnmpPeer
*
*/
void transmit(SnmpRequest req) throws SnmpPduEncodingException, AsnEncodingException, java.io.IOException {
// break down the pieces into usable variables
SnmpPduPacket pdu = null;
SnmpPduTrap trap = null;
SnmpPeer peer = m_peer;
SnmpParameters parms = peer.getParameters();
if (req.m_pdu instanceof SnmpPduPacket)
pdu = (SnmpPduPacket) req.m_pdu;
if (req.m_pdu instanceof SnmpPduTrap)
trap = (SnmpPduTrap) req.m_pdu;
// verify that for a SNMPV1 session that no
// SNMPV2 packets are transmitted!
if (pdu != null) {
switch (pdu.getCommand()) {
case SnmpPduPacket.INFORM:
case SnmpPduPacket.V2TRAP:
case SnmpPduPacket.REPORT:
case SnmpPduPacket.GETBULK:
if (parms.getVersion() < SnmpSMI.SNMPV2) {
throw new SnmpPduEncodingException("Cannot send pdu, invalid SNMP version");
}
}
// transmit the datagram
ByteArrayInfo msg = encode(pdu);
if (pdu.getPeer() == null)
m_portal.send(m_peer, msg.array(), msg.size());
else
m_portal.send(pdu.getPeer(), msg.array(), msg.size());
} else if (trap != null) {
ByteArrayInfo msg = encode(trap);
m_portal.send(m_peer, msg.array(), msg.size());
} else {
throw new SnmpPduEncodingException("Invalid PDU type passed to method");
}
}
/**
* The default SnmpSession constructor. The object is constructed with a
* default SnmpPeer object.
*
* @param peer
* The peer agent
*
* @see SnmpPeer
*
* @exception java.net.SocketException
* If thrown it is from the creation of a DatagramSocket.
*
*/
public SnmpSession(InetAddress peer) throws SocketException {
m_sync = new Object();
m_requests = new LinkedList();
m_peer = new SnmpPeer(peer);
m_timer = new SnmpTimer();
m_defHandler = null;
m_stopRun = false;
m_encoder = (new SnmpParameters()).getEncoder();
m_portal = new SnmpPortal(new SessionHandler(), m_encoder, 0);
m_threadException = false;
m_why = null;
m_timer.schedule(new CleanupRequest(), 1000);
}
/**
* Constructs the SnmpSession with the specific SnmpPeer.
*
* @param peer
* The SnmpPeer used to configure this session
*
* @see SnmpPeer
*
* @exception java.net.SocketException
* If thrown it is from the creation of a DatagramSocket.
*
*/
public SnmpSession(SnmpPeer peer) throws SocketException {
m_requests = new LinkedList();
m_timer = new SnmpTimer();
m_defHandler = null;
m_sync = new Object();
m_stopRun = false;
m_encoder = peer.getParameters().getEncoder();
m_portal = new SnmpPortal(new SessionHandler(), m_encoder, peer.getServerPort());
m_threadException = false;
m_why = null;
m_peer = peer;
m_timer.schedule(new CleanupRequest(), 5000);
}
/**
* Constructs the SnmpSession with the specific parameters. The parameters
* are associated with the default SnmpPeer object.
*
* @param peer
* The peer address for agent
* @param params
* The SnmpParameters to configure with this session
*
* @see SnmpPeer
* @see SnmpParameters
*
* @exception java.net.SocketException
* If thrown it is from the creation of a DatagramSocket.
*
*/
public SnmpSession(InetAddress peer, SnmpParameters params) throws SocketException {
this(peer);
m_peer.setParameters(params);
}
/**
* Gets the default SnmpHandler for the session. If the handler has never
* been set via the setDefaultHandler() method then a null will be returned.
*
* @return The default SnmpHandler, a null if one has never been registered.
*
*/
public SnmpHandler getDefaultHandler() {
return m_defHandler;
}
/**
* Sets the default SnmpHandler.
*
* @param hdl
* The new default handler
*
*/
public void setDefaultHandler(SnmpHandler hdl) {
m_defHandler = hdl;
}
/**
* Gets the current peer object.
*
* @return The current SnmpPeer object
*
*/
public SnmpPeer getPeer() {
return m_peer;
}
/**
* Sets the passed SnmpPeer object to the one used for all new SNMP
* communications. This includes any outstanding retries.
*
* @param peer
* The SnmpPeer object for the sesison
*
*/
public void setPeer(SnmpPeer peer) {
m_peer = peer;
setAsnEncoder(peer.getParameters().getEncoder());
}
public int getOutstandingCount() {
// check to ensure that the session is still open
synchronized (m_sync) {
if (m_stopRun) // session has been closed!
throw new IllegalStateException("illegal operation, the session has been closed");
}
synchronized (m_requests) {
// need to do cleanup in order
// to make this happen!
if (m_requests.size() > 0) {
ListIterator iter = m_requests.listIterator();
while (iter.hasNext()) {
SnmpRequest req = (SnmpRequest) iter.next();
if (req.m_expired)
iter.remove();
}
}
return m_requests.size();
}
}
public void cancel(int requestId) {
// check to ensure that the session is still open
synchronized (m_sync) {
if (m_stopRun) // session has been closed!
throw new IllegalStateException("illegal operation, the session has been closed");
}
synchronized (m_requests) {
if (m_requests.size() > 0) {
ListIterator iter = m_requests.listIterator();
while (iter.hasNext()) {
// While the method owns the lock remove any expired
// request and any request with a matching request id
SnmpRequest req = (SnmpRequest) iter.next();
if (req.m_expired || (req.m_pdu instanceof SnmpPduPacket && ((SnmpPduPacket) req.m_pdu).getRequestId() == requestId)) {
req.m_expired = true;
iter.remove();
}
}
}
}
}
public int send(SnmpPduPacket pdu, SnmpHandler handler) {
if (handler == null)
throw new SnmpHandlerNotDefinedException("No Handler Defined");
// check to ensure that the session is still open
synchronized (m_sync) {
if (m_stopRun) // session has been closed!
throw new IllegalStateException("illegal operation, the session has been closed");
}
SnmpRequest req = new SnmpRequest(this, pdu, handler);
if (pdu.getCommand() != SnmpPduPacket.V2TRAP || pdu.getPeer() == null) // traps
// and
// responses
// don't
// get
// answers!
addRequest(req);
req.run();
if (req.m_expired == true) {
return 0;
}
return ((SnmpPduPacket) req.m_pdu).getRequestId();
}
public int send(SnmpPduPacket pdu) {
if (m_defHandler == null)
throw new SnmpHandlerNotDefinedException("No Handler Defined");
return send(pdu, m_defHandler);
}
public int send(SnmpPduTrap pdu, SnmpHandler handler) {
if (handler == null)
throw new SnmpHandlerNotDefinedException("No Handler Defined");
// check to ensure that the session is still open
synchronized (m_sync) {
if (m_stopRun) // session has been closed!
throw new IllegalStateException("illegal operation, the session has been closed");
}
SnmpRequest req = new SnmpRequest(this, pdu, handler);
req.run();
return 0;
}
public int send(SnmpPduTrap pdu) {
if (m_defHandler == null)
throw new SnmpHandlerNotDefinedException("No Handler Defined");
return send(pdu, m_defHandler);
}
/**
* Returns true if the <CODE>close</CODE> method has been called. The
* session cannot be used to send request after <CODE>close</CODE> has
* been executed.
*
*/
public boolean isClosed() {
synchronized (m_sync) {
return m_stopRun;
}
}
public void close() {
synchronized (m_sync) {
// only allow close to be called once
if (m_stopRun)
throw new IllegalStateException("The session is already closed");
m_stopRun = true;
m_timer.cancel();
m_portal.close();
}
// remove all items from the list
synchronized (m_requests) {
m_requests.clear();
}
}
/**
* If an exception occurs in the SNMP receiver thread then raise() will
* rethrow the exception.
*
* @exception java.lang.Throwable
* The base for thrown exceptions.
*/
public void raise() throws Throwable {
synchronized (m_sync) {
if (m_threadException)
throw m_why;
}
}
/**
* Sets the default encoder.
*
* @param encoder
* The new encoder
*
*/
public void setAsnEncoder(AsnEncoder encoder) {
m_encoder = encoder;
m_portal.setAsnEncoder(encoder);
}
/**
* Gets the AsnEncoder for the session.
*
* @return the AsnEncoder
*/
public AsnEncoder getAsnEncoder() {
return m_encoder;
}
/**
* Allows library users to register new ASN.1 types with the SNMP library.
* The object must support all methods of the SnmpSyntax interface. The
* object is registered globally with the library and is visible to all
* session after it is registered.
*
* @param object
* The new SnmpSyntax object to register
*/
public static void registerSyntaxObject(SnmpSyntax object) {
SnmpUtil.registerSyntax(object);
}
} // end of SnmpSession class
|
package ca.dmoj.java;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Scanner;
import java.util.Arrays;
@SuppressWarnings("deprecation")
public class JavaSafeExecutor {
/**
* We use our own instance of ThreadDeath for killing submissions.
* This is just so that a `throw new ThreadDeath()` directive in a user's submission will not be
* incorrectly marked as TLE. But who throws ThreadDeaths randomly, anyways?
*/
public static ThreadDeath TLE = new ThreadDeath();
/**
* Used to kill the submission thread when the user calls System.exit.
*/
public static ThreadDeath EXIT_REQUESTED = new ThreadDeath();
public static int ACCESS_ERROR_CODE = -1001;
/**
* The user did not declare a `public static void main(String[] argv)` in their code.
* How are we supposed to run it?
*/
public static int NO_ENTRY_POINT_ERROR_CODE = -1002;
/**
* User's submission threw a Throwable, which we caught.
*/
public static int PROGRAM_ERROR_CODE = 1;
/**
* Class.forName failed; internal error.
*/
public static int CLASS_NOT_FOUND_ERROR_CODE = -1003;
/**
* Class.forName failed; internal error.
*/
public static int NO_CLASS_DEF_ERROR_CODE = -1004;
/**
* Thread to kill the user's submission after their time limit is exceeded.
*/
static ShockerThread shockerThread;
/**
* The thread the user's submission runs on.
*/
static SubmissionThread submissionThread;
static Thread selfThread;
/**
* Flag to indicate that the security manager should be deactivated.
* Should be set to false before running the user's submission, and false after it has finished running.
* If this flag somehow is set to false while a user's submission is running, the judging server may be
* compromised: the submission gains the same access level as the user the judge is running under.
*/
static boolean _safeBlock = false;
/**
* The current working directory of the submission, used for classpath adding.
*/
static String cwd;
static File statefile;
static boolean isUnicode = false;
static long startupTime = 0;
static {
/*
Scanner needs to load some locale files before it can be used. Since "files" implies IO which is blocked by
our security manager, we force Scanner to load the files here, before our security manager is activated.
*/
new Scanner(new ByteArrayInputStream(new byte[128])).close();
}
static void writeState(String state, Object... format) throws IOException {
FileOutputStream fos = new FileOutputStream(statefile);
PrintStream out = new PrintStream(fos);
out.format(state, format);
fos.close();
}
static void printStateAndExit() throws IOException {
// UnsafePrintStream buffers
System.out.flush();
long totalProgramTime = (System.nanoTime() - startupTime) / 1000000;
boolean tle = submissionThread.isTle();
/*
Fetch the memory usage for the submission. This is a Linux-specific task, and will obviously
fail on any other OS.
We could periodically poll MemoryMXBean for heap usage etc, but that would require a third thread and would
not be as accurate.
*/
long mem = 0;
try {
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream("/proc/self/status")));
for (String line; (line = in.readLine()) != null; ) {
if (line.startsWith("VmHWM:")) {
String[] data = line.split("\\s+");
mem = Integer.parseInt(data[1]);
}
}
} catch (Exception ignored) {
}
boolean mle = submissionThread.isMle();
int error = submissionThread.getError();
Throwable exc = submissionThread.getException();
writeState("%d %d %d %d %d %s\n", totalProgramTime, tle ? 1 : 0, mem, mle ? 1 : 0, error, exc != null ? exc.getClass().getName() : "OK");
System.exit(0);
}
public static void main(String[] argv) throws MalformedURLException, ClassNotFoundException, UnsupportedEncodingException, IOException {
cwd = new File(argv[0]).toString(); // Resolve relative paths
String classname = argv[1];
int TL = Integer.parseInt(argv[2]);
selfThread = Thread.currentThread();
statefile = new File(new File(cwd), argv[3]);
isUnicode = Arrays.asList(argv).contains("-unicode");
System.setOut(new UnsafePrintStream(new FileOutputStream(FileDescriptor.out), isUnicode));
URLClassLoader classLoader = new URLClassLoader(new URL[]{new File(cwd).toURI().toURL()}) {
private void askShouldFail(String name) throws ClassNotFoundException {
if (name.startsWith("ca.dmoj.")) throw new ClassNotFoundException("Nope");
}
@Override
public Class<?> loadClass(String name, boolean init) throws ClassNotFoundException {
askShouldFail(name);
return super.loadClass(name, init);
}
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
askShouldFail(name);
return super.findClass(name);
}
};
startupTime = System.nanoTime();
Class program;
try {
program = classLoader.loadClass(classname);
} catch (ClassNotFoundException e) {
e.printStackTrace();
writeState("\n%d %d %d %d %d CNF\n", 0, 0, 0, 0, CLASS_NOT_FOUND_ERROR_CODE);
return;
} catch (NoClassDefFoundError ex) {
ex.printStackTrace();
writeState("\n%d %d %d %d %d CNF\n", 0, 0, 0, 0, NO_CLASS_DEF_ERROR_CODE);
return;
}
submissionThread = new SubmissionThread(program);
shockerThread = new ShockerThread(TL, submissionThread);
System.setSecurityManager(new SubmissionSecurityManager());
shockerThread.start();
submissionThread.start();
try {
submissionThread.join();
} catch (InterruptedException ignored) {
}
shockerThread.stop();
printStateAndExit();
}
}
|
package com.yammer.metrics.core;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
/**
* A set of factory methods for creating centrally registered metric instances.
*
* @author coda
*/
public class Metrics {
private static final ConcurrentMap<MetricName, Metric> METRICS = new ConcurrentHashMap<MetricName, Metric>();
private Metrics() { /* unused */ }
/**
* Given a new {@link GaugeMetric}, registers it under the given class and
* name.
*
* @param klass the class which owns the metric
* @param name the name of the metric
* @param metric the metric
* @param <T> the type of the value returned by the metric
* @return {@code metric}
*/
public static <T> GaugeMetric<T> newGauge(Class<?> klass, String name, GaugeMetric<T> metric) {
return getOrAdd(new MetricName(klass, name), metric);
}
/**
* Creates a new {@link CounterMetric} and registers it under the given
* class and name.
*
* @param klass the class which owns the metric
* @param name the name of the metric
* @return a new {@link CounterMetric}
*/
public static CounterMetric newCounter(Class<?> klass, String name) {
return getOrAdd(new MetricName(klass, name), new CounterMetric());
}
/**
* Creates a new {@link MeterMetric} and registers it under the given
* class and name.
*
* @param klass the class which owns the metric
* @param name the name of the metric
* @param eventType the plural name of the type of events the meter is
* measuring (e.g., {@code "requests"})
* @param unit the scale unit of the new meter
* @return a new {@link MeterMetric}
*/
public static MeterMetric newMeter(Class<?> klass, String name, String eventType, TimeUnit unit) {
MetricName metricName = new MetricName(klass, name);
final Metric existingMetric = METRICS.get(metricName);
if (existingMetric == null) {
final MeterMetric metric = MeterMetric.newMeter(eventType, unit);
final Metric justAddedMetric = METRICS.putIfAbsent(metricName, metric);
if (justAddedMetric == null) {
return metric;
}
return (MeterMetric) justAddedMetric;
}
return (MeterMetric) existingMetric;
}
/**
* Creates a new {@link TimerMetric} and registers it under the given
* class and name.
*
* @param klass the class which owns the metric
* @param name the name of the metric
* @param durationUnit the duration scale unit of the new timer
* @param rateUnit the rate scale unit of the new timer
* @return a new {@link TimerMetric}
*/
public static TimerMetric newTimer(Class<?> klass, String name, TimeUnit durationUnit, TimeUnit rateUnit) {
MetricName metricName = new MetricName(klass, name);
final Metric existingMetric = METRICS.get(metricName);
if (existingMetric == null) {
final TimerMetric metric = new TimerMetric(durationUnit, rateUnit);
final Metric justAddedMetric = METRICS.putIfAbsent(metricName, metric);
if (justAddedMetric == null) {
return metric;
}
return (TimerMetric) justAddedMetric;
}
return (TimerMetric) existingMetric;
}
/**
* Enables the HTTP/JSON reporter on the given port.
*
* @param port the port on which the HTTP server will listen
* @throws IOException if there is a problem listening on the given port
* @see HttpReporter
*/
public static void enableHttpReporting(int port) throws IOException {
final HttpReporter reporter = new HttpReporter(METRICS, port);
reporter.start();
}
/**
* Enables the console reporter and causes it to print to STDOUT with the
* specified period.
*
* @param period the period between successive outputs
* @param unit the time unit of {@code period}
*/
public static void enableConsoleReporting(long period, TimeUnit unit) {
final ConsoleReporter reporter = new ConsoleReporter(METRICS, System.out);
reporter.start(period, unit);
}
@SuppressWarnings("unchecked")
private static <T extends Metric> T getOrAdd(MetricName name, T metric) {
final Metric existingMetric = METRICS.get(name);
if (existingMetric == null) {
final Metric justAddedMetric = METRICS.putIfAbsent(name, metric);
if (justAddedMetric == null) {
return metric;
}
return (T) justAddedMetric;
}
return (T) existingMetric;
}
public static void enableJmxReporting() {
final JmxReporter reporter = new JmxReporter(METRICS);
reporter.start();
}
}
|
package com.uwflow.flow_android.fragment;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;
import com.uwflow.flow_android.FlowApplication;
import com.uwflow.flow_android.R;
import com.uwflow.flow_android.adapters.SearchResultAdapter;
import com.uwflow.flow_android.db_object.Course;
import com.uwflow.flow_android.db_object.SearchResults;
import com.uwflow.flow_android.network.FlowApiRequestCallbackAdapter;
import com.uwflow.flow_android.network.FlowApiRequests;
import java.util.*;
public class ExploreFragment extends Fragment implements AdapterView.OnItemClickListener {
private static final String TAG = "ExploreFragment";
private static final int ITEMS_PER_PAGE = 20;
// TODO(david): Convert all the search stuff to use a SearchView, which gets us things like suggestions
private EditText mSearchBox;
private Spinner mSortSpinner;
private CheckBox mExcludeTakenCheckBox;
private ListView mResultsListView;
private View mFooterView;
private boolean mSortSpinnerFired = false;
private int mSortSpinnerPosition = -1;
private boolean mExcludeTakenCheckBoxChecked = false;
private List<Course> mSearchResultList = new ArrayList<Course>();
private SearchResultAdapter mSearchResultAdapter;
private static final Map<String, String> mSortModesMap;
static {
Map<String, String> map = new LinkedHashMap<String, String>();
map.put("Popular", "popular");
map.put("Friends taken", "friends_taken");
map.put("Interesting", "interesting");
map.put("Easy", "easy");
map.put("Hard", "hard");
map.put("Course code", "course code");
mSortModesMap = Collections.unmodifiableMap(map);
}
private ArrayAdapter<CharSequence> mSortModesAdapter;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.explore_layout, container, false);
mSearchBox = (EditText)rootView.findViewById(R.id.search_box);
mSortSpinner = (Spinner)rootView.findViewById(R.id.sort_spinner);
mExcludeTakenCheckBox = (CheckBox)rootView.findViewById(R.id.checkbox_exclude_taken);
mResultsListView = (ListView)rootView.findViewById(R.id.results_list);
mFooterView = inflater.inflate(R.layout.search_results_footer, null, false);
mResultsListView.addFooterView(mFooterView);
mSearchResultAdapter = new SearchResultAdapter(mSearchResultList, getActivity());
mResultsListView.setAdapter(mSearchResultAdapter);
mResultsListView.setOnItemClickListener(this);
Set<String> sortModes = new LinkedHashSet<String>(mSortModesMap.keySet());
// Hide various controls for logged out users
boolean isUserLoggedIn = ((FlowApplication)getActivity().getApplication()).isUserLoggedIn();
if (!isUserLoggedIn) {
sortModes.remove("Friends taken");
mExcludeTakenCheckBox.setVisibility(View.GONE);
}
// Populate the sort spinner
mSortModesAdapter = new ArrayAdapter <CharSequence>(getActivity(), android.R.layout.simple_spinner_item,
sortModes.toArray(new CharSequence[0]));
mSortModesAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSortSpinner.setAdapter(mSortModesAdapter);
setUpListeners();
return rootView;
}
private void setUpListeners() {
mSortSpinnerFired = false;
// Do search on sort mode change
mSortSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// Android stupidly fires this listener on create of the spinner. This is used to ignore that.
if (!mSortSpinnerFired) {
mSortSpinnerFired = true;
return;
}
// Item selection didn't actually change. This could happen when back button is pressed to return to
// this fragment.
if (mSortSpinnerPosition == position) {
return;
}
mSortSpinnerPosition = position;
doSearch(0);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
Log.e(TAG, "No sort mode selected. This should never happen.");
}
});
// Do search on checkbox include/exclude courses taken change
mExcludeTakenCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// Checkbox selection didn't actually change. This may happen when back button pressed to return to
// this fragment.
if (isChecked == mExcludeTakenCheckBoxChecked) {
return;
}
mExcludeTakenCheckBoxChecked = isChecked;
doSearch(0);
}
});
// Do search on edit text submit
mSearchBox.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
doSearch(0);
v.clearFocus();
InputMethodManager imm = (InputMethodManager)getActivity().getSystemService(
Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
return true;
}
return false;
}
});
// Infinite scroll: load next page of results when scrolled towards the end of the list.
mResultsListView.setOnScrollListener(new InfiniteScrollListener() {
@Override
public void onLoadMore(int page) {
doSearch(page);
}
});
}
@Override
public void onActivityCreated(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
if (mSearchResultList.isEmpty()) {
doSearch(0);
}
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Course course = (Course)parent.getItemAtPosition(position);
getFragmentManager().beginTransaction()
.replace(R.id.content_frame, CourseFragment.newInstance(course.getId()))
.addToBackStack(null)
.commit();
}
/**
* Performs a search with parameters set on the UI.
* @param page The page to load. Pass 0 if loading search results for a different query/filters.
*/
private void doSearch(final int page) {
mFooterView.setVisibility(View.VISIBLE);
if (page == 0) {
mResultsListView.setAlpha((float)0.4);
}
// Get keywords
Editable searchBoxText = mSearchBox.getText();
String keywords = "";
if (searchBoxText != null) {
keywords = searchBoxText.toString();
}
// Get sort mode
Object sortItem = mSortSpinner.getSelectedItem();
String sortMode = sortItem == null ? "" : mSortModesMap.get(sortItem.toString());
// Get whether we should exclude taken courses
boolean excludeTakenCourses = mExcludeTakenCheckBox.isChecked();
FlowApiRequests.searchCourses(keywords, sortMode, excludeTakenCourses, ITEMS_PER_PAGE, page * ITEMS_PER_PAGE,
new FlowApiRequestCallbackAdapter() {
@Override
public void searchCoursesCallback(SearchResults searchResults) {
if (page == 0) {
mSearchResultList.clear();
}
mSearchResultList.addAll(searchResults.getCourses());
mSearchResultAdapter.notifyDataSetChanged();
if (page == 0) {
mResultsListView.setSelectionAfterHeaderView();
}
mResultsListView.setAlpha((float)1.0);
mFooterView.setVisibility(View.GONE);
}
});
}
private abstract class InfiniteScrollListener implements AbsListView.OnScrollListener {
private final int remainingThreshold = 5;
private int currentPage = 0;
private int currentTotalItems = 0;
private boolean loading = true;
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
int totalItemsLessFooter = totalItemCount - 1;
// If total items has somehow gone down, then search results were probably refreshed.
if (totalItemsLessFooter< currentTotalItems) {
currentPage = 0;
currentTotalItems = totalItemsLessFooter;
if (totalItemsLessFooter == 0) {
loading = true;
}
}
// See if loading has just completed.
if (loading && totalItemsLessFooter > currentTotalItems) {
currentTotalItems = totalItemsLessFooter;
currentPage++;
loading = false;
}
// If we're not already loading, see if the remaining items below the fold is about to exceed the threshold.
if (!loading && totalItemsLessFooter - (firstVisibleItem + visibleItemCount) <= remainingThreshold) {
onLoadMore(currentPage + 1);
loading = true;
}
}
public abstract void onLoadMore(int page);
}
}
|
package org.jdesktop.swingx.decorator;
import java.awt.event.ActionEvent;
import java.text.Collator;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import org.jdesktop.swingx.InteractiveTestCase;
import org.jdesktop.swingx.JXFrame;
import org.jdesktop.swingx.JXTable;
import org.jdesktop.swingx.test.PipelineReport;
import org.jdesktop.test.AncientSwingTeam;
public class FilterTest extends InteractiveTestCase {
public FilterTest() {
super("FilterTest");
}
private TableModel tableModel;
protected ComponentAdapter directModelAdapter;
private PipelineReport pipelineReport;
/**
* test notification from sorter after setSortkey.
* Guarantee refresh notification with same direction, columnIndex
* but different Comparator.
*/
public void testSorterSortKeyComparatorRefresh() {
FilterPipeline pipeline = new FilterPipeline();
pipeline.assign(directModelAdapter);
// create a sorter for column 0, ascending,
// without explicit comparator
Sorter sorter = new ShuttleSorter();
pipeline.setSorter(sorter);
pipeline.addPipelineListener(pipelineReport);
// create sortKey with other sort direction on column
SortKey sortKey = new SortKey(SortOrder.ASCENDING,
sorter.getColumnIndex(), Collator.getInstance());
sorter.setSortKey(sortKey);
// sanity: sorter and sortKey synched
SorterTest.assertSorterSortKeySynched(sortKey, sorter);
assertEquals(1, pipelineReport.getEventCount(PipelineEvent.CONTENTS_CHANGED));
}
/**
* test notification from sorter after setSortkey.
* Guarantee refresh notification with same columnIndex.
*/
public void testSorterSortKeyRefresh() {
FilterPipeline pipeline = new FilterPipeline();
pipeline.assign(directModelAdapter);
// create a sorter for column 0, ascending,
// without explicit comparator
Sorter sorter = new ShuttleSorter();
pipeline.setSorter(sorter);
pipeline.addPipelineListener(pipelineReport);
// create sortKey with other sort direction on column
SortKey sortKey = new SortKey(SortOrder.DESCENDING, sorter.getColumnIndex());
sorter.setSortKey(sortKey);
// sanity: sorter and sortKey synched
SorterTest.assertSorterSortKeySynched(sortKey, sorter);
assertEquals(1, pipelineReport.getEventCount(PipelineEvent.CONTENTS_CHANGED));
}
/**
* test notification from sorter after setSortkey.
* Guarantee exactly one refresh notification.
*/
public void testSorterSortKeyOneRefresh() {
FilterPipeline pipeline = new FilterPipeline();
pipeline.assign(directModelAdapter);
// create a sorter for column 0, ascending,
// without explicit comparator
Sorter sorter = new ShuttleSorter();
pipeline.setSorter(sorter);
pipeline.addPipelineListener(pipelineReport);
// create sortKey with other sort direction on column
SortKey sortKey = new SortKey(SortOrder.DESCENDING, sorter.getColumnIndex() +1);
sorter.setSortKey(sortKey);
// sanity: sorter and sortKey synched
SorterTest.assertSorterSortKeySynched(sortKey, sorter);
assertEquals(1, pipelineReport.getEventCount(PipelineEvent.CONTENTS_CHANGED));
}
/**
* test notification from sorter after setSortkey.
* Guarantee no refresh notification on same.
*/
public void testSorterSortKeyNoRefresh() {
FilterPipeline pipeline = new FilterPipeline();
pipeline.assign(directModelAdapter);
// create a sorter for column 0, ascending,
// without explicit comparator
Comparator comparator = Collator.getInstance();
Sorter sorter = new ShuttleSorter(0, true, comparator);
pipeline.setSorter(sorter);
pipeline.addPipelineListener(pipelineReport);
// create sortKey with other sort direction on column
SortKey sortKey = new SortKey(SortOrder.ASCENDING,
sorter.getColumnIndex(), sorter.getComparator());
sorter.setSortKey(sortKey);
// sanity: sorter and sortKey synched
SorterTest.assertSorterSortKeySynched(sortKey, sorter);
assertFalse("sorter must not refresh without state change", pipelineReport.hasEvents());
}
public void testSortControllerToggleWithComparator() {
FilterPipeline pipeline = createAssignedPipeline(true);
SortController controller = pipeline.getSortController();
// controller.toggleSortOrder(0, Collator.getInstance());
}
/**
* creates and returns a FilterPipeline assigned to directModelAdapter.
* Registers pipelineReport if withReport.
*
* @param withReport flag to indicate if pipelineReport should be registered.
* @return FilterPipeline
*/
private FilterPipeline createAssignedPipeline(boolean withReport) {
FilterPipeline pipeline = new FilterPipeline();
pipeline.assign(directModelAdapter);
if (withReport) {
pipeline.addPipelineListener(pipelineReport);
}
return pipeline;
}
/**
* Guarantee that Pipeline's Sorter and SortController are in synch
* after setting properties of SortController.
*
*/
public void testSortControllerToggleUpdatesSameSorter() {
FilterPipeline pipeline = createAssignedPipeline(false);
int column = 2;
pipeline.setSorter(new ShuttleSorter(column, false));
Sorter sorter = pipeline.getSorter();
pipeline.addPipelineListener(pipelineReport);
SortController controller = pipeline.getSortController();
controller.toggleSortOrder(column);
assertFalse("toggleSortOrder must have initialized sortKey", controller.getSortKeys().isEmpty());
// we assume that there's exactly one sortkey created!
SortKey sortKey = controller.getSortKeys().get(0);
assertTrue(pipeline.getSorter().isAscending());
assertEquals(column, sortKey.getColumn());
assertSame(sorter, pipeline.getSorter());
SorterTest.assertSorterSortKeySynched(sortKey, pipeline.getSorter());
assertEquals(1, pipelineReport.getEventCount(PipelineEvent.CONTENTS_CHANGED));
}
/**
* Guarantee that Pipeline's Sorter and SortController are in synch
* after setting properties of SortController.
*
*/
public void testSortControllerToggleUpdatesSorter() {
FilterPipeline pipeline = createAssignedPipeline(false);
int column = 2;
pipeline.setSorter(new ShuttleSorter(column, false));
pipeline.addPipelineListener(pipelineReport);
SortController controller = pipeline.getSortController();
int newColumn = column - 1;
controller.toggleSortOrder(newColumn);
assertFalse("toggleSortOrder must have initialized sortKey", controller.getSortKeys().isEmpty());
// we assume that there's exactly one sortkey created!
SortKey sortKey = controller.getSortKeys().get(0);
assertTrue(pipeline.getSorter().isAscending());
SorterTest.assertSorterSortKeySynched(sortKey, pipeline.getSorter());
assertEquals(1, pipelineReport.getEventCount(PipelineEvent.CONTENTS_CHANGED));
}
/**
* Guarantee that Pipeline's Sorter is correctly initialized
* after setting properties of SortController.
*
*/
public void testSortControllerToggleInitSorter() {
FilterPipeline pipeline = createAssignedPipeline(true);
int column = 2;
SortController controller = pipeline.getSortController();
controller.toggleSortOrder(column);
assertFalse("toggleSortOrder must have initialized sortKey", controller.getSortKeys().isEmpty());
// we assume that there's exactly one sortkey created!
SortKey sortKey = controller.getSortKeys().get(0);
SorterTest.assertSorterSortKeySynched(sortKey, pipeline.getSorter());
assertEquals(1, pipelineReport.getEventCount(PipelineEvent.CONTENTS_CHANGED));
}
/**
* Guarantee that Pipeline's Sorter and SortController are in synch
* after setting properties of SortController.
*
*/
public void testSortControllerResetRemovesSorter() {
FilterPipeline pipeline = createAssignedPipeline(false);
int column = 2;
pipeline.setSorter(new ShuttleSorter(column, true));
SortController controller = pipeline.getSortController();
controller.setSortKeys(Collections.EMPTY_LIST);
assertNull(pipeline.getSorter());
}
/**
* Guarantee that Pipeline's Sorter and SortController are in synch
* after setting properties of SortController.
*
*/
public void testSortControllerSortKeysUpdatesSameSorter() {
FilterPipeline pipeline = createAssignedPipeline(false);
pipeline.setSorter(new ShuttleSorter());
Sorter sorter = pipeline.getSorter();
pipeline.addPipelineListener(pipelineReport);
SortController controller = pipeline.getSortController();
SortKey sortKey = new SortKey(SortOrder.DESCENDING, sorter.getColumnIndex());
controller.setSortKeys(Collections.singletonList(sortKey));
assertSame(sorter, pipeline.getSorter());
SorterTest.assertSorterSortKeySynched(sortKey, pipeline.getSorter());
assertEquals(1, pipelineReport.getEventCount(PipelineEvent.CONTENTS_CHANGED));
}
/**
* Guarantee that Pipeline's Sorter and SortController are in synch
* after setting properties of SortController.
*
*/
public void testSortControllerSortKeysUpdatesSorter() {
FilterPipeline pipeline = createAssignedPipeline(false);
int column = 2;
pipeline.setSorter(new ShuttleSorter(column, true));
pipeline.addPipelineListener(pipelineReport);
SortController controller = pipeline.getSortController();
int newColumn = column - 1;
SortKey sortKey = new SortKey(SortOrder.DESCENDING, newColumn);
controller.setSortKeys(Collections.singletonList(sortKey));
SorterTest.assertSorterSortKeySynched(sortKey, pipeline.getSorter());
assertEquals(1, pipelineReport.getEventCount(PipelineEvent.CONTENTS_CHANGED));
}
/**
* Guarantee that Pipeline's Sorter is correctly initialized
* after setting properties of SortController.
*
*/
public void testSortControllerSortKeysInitSorter() {
FilterPipeline pipeline = createAssignedPipeline(true);
int column = 1;
SortController controller = pipeline.getSortController();
SortKey sortKey = new SortKey(SortOrder.DESCENDING, column, Collator.getInstance());
controller.setSortKeys(Collections.singletonList(sortKey));
SorterTest.assertSorterSortKeySynched(sortKey, pipeline.getSorter());
SortKey createdKey = SortKey.getFirstSortKeyForColumn(controller.getSortKeys(), column);
SorterTest.assertSorterSortKeySynched(createdKey, pipeline.getSorter());
assertEquals(1, pipelineReport.getEventCount(PipelineEvent.CONTENTS_CHANGED));
}
/**
* initial addition of SortController
* (== basically renamed Jesse's RowSorter).
* no active sorter.
*/
public void testSortControllerWithoutSorter() {
FilterPipeline pipeline = createAssignedPipeline(false);
SortController controller = pipeline.getSortController();
assertNotNull(controller);
// test all method if nothing is sorted
assertEquals(SortOrder.UNSORTED, controller.getSortOrder(0));
assertNotNull(controller.getSortKeys());
}
/**
* initial addition of SortController
* Guarantee that SortController getters are in synch with Sorter.
*/
public void testSortControllerWithSorter() {
FilterPipeline pipeline = createAssignedPipeline(false);
int column = 2;
pipeline.setSorter(new ShuttleSorter(column, true));
SortController controller = pipeline.getSortController();
assertNotNull(controller);
// test all method if sorter ascending sorter on column
assertEquals(SortOrder.ASCENDING, controller.getSortOrder(column));
List<? extends SortKey> sortKeys = controller.getSortKeys();
assertNotNull(sortKeys);
assertEquals(1, sortKeys.size());
SortKey sortKey = sortKeys.get(0);
assertEquals(SortOrder.ASCENDING, sortKey.getSortOrder());
assertEquals(column, sortKey.getColumn());
// sanity: doesn't effect unsorted column
assertEquals(SortOrder.UNSORTED, controller.getSortOrder(column - 1));
}
public void testSortOrderChangedEvent() {
FilterPipeline pipeline = createAssignedPipeline(true);
pipeline.setSorter(new ShuttleSorter());
assertEquals(1, pipelineReport.getEventCount(PipelineEvent.CONTENTS_CHANGED));
// expect 2 events: one for sortOrderChanged, one for contentsChanged
// not yet implemented - has implications on other tests, so go for
// one type of events only ...
// assertEquals(1, pipelineReport.getEventCount(PipelineEvent.SORT_ORDER_CHANGED));
// PipelineEvent event = pipelineReport.getLastEvent(PipelineEvent.SORT_ORDER_CHANGED);
// assertEquals(PipelineEvent.SORT_ORDER_CHANGED, event.getType());
}
/**
* reported on swingx-dev mailing list:
* chained filters must AND - as they did.
* Currently (10/2005) they OR ?.
*
* Hmm, can't reproduce - JW.
*/
public void testAndFilter() {
PatternFilter first = new PatternFilter("a", 0, 0);
PatternFilter second = new PatternFilter("b", 0, 1);
// FilterPipeline pipeline = new FilterPipeline(new Filter[] {first, second});
FilterPipeline pipeline = new FilterPipeline(first, second);
pipeline.assign(directModelAdapter);
assertTrue(pipeline.getOutputSize() > 0);
for (int i = 0; i < pipeline.getOutputSize(); i++) {
boolean firstMatch = first.getPattern().matcher(pipeline.getValueAt(i, 0).toString()).find();
boolean secondMatch = second.getPattern().matcher(pipeline.getValueAt(i, 1).toString()).find();
assertTrue(firstMatch);
assertEquals("both matchers must find", firstMatch, secondMatch);
}
}
/**
* Issue ??-swingx
* pipeline should auto-flush on assigning adapter.
*
*/
public void testFlushOnAssign() {
Filter filter = new PatternFilter(".*", 0, 0);
FilterPipeline pipeline = new FilterPipeline(new Filter[] { filter });
pipeline.assign(directModelAdapter);
assertEquals("pipeline output size must be model count",
directModelAdapter.getRowCount(), pipeline.getOutputSize());
// JW PENDING: remove necessity to explicitly flush...
Object value = pipeline.getValueAt(0, 0);
assertEquals("value access via sorter must return the same as via pipeline",
value, pipeline.getValueAt(0, 0));
}
/**
* test notification on setSorter: must fire on change only.
*
*/
public void testPipelineEventOnSameSorter() {
FilterPipeline pipeline = new FilterPipeline();
pipeline.assign(directModelAdapter);
pipeline.addPipelineListener(pipelineReport);
Sorter sorter = new ShuttleSorter();
pipeline.setSorter(sorter);
assertEquals("pipeline must have fired on setSorter", 1, pipelineReport.getEventCount());
pipelineReport.clear();
pipeline.setSorter(sorter);
assertEquals("pipeline must not have fired on same setSorter", 0, pipelineReport.getEventCount());
}
/**
* test notification on setSorter.
*
*/
public void testPipelineEventOnSetSorter() {
FilterPipeline pipeline = new FilterPipeline();
pipeline.assign(directModelAdapter);
pipeline.addPipelineListener(pipelineReport);
pipeline.setSorter(new ShuttleSorter());
assertEquals("pipeline must have fired on setSorter", 1, pipelineReport.getEventCount());
pipelineReport.clear();
pipeline.setSorter(null);
assertEquals("pipeline must have fired on setSorter null", 1, pipelineReport.getEventCount());
}
/**
* test notification on setSorter: must fire if assigned only.
*
*/
public void testPipelineEventOnSetSorterUnassigned() {
FilterPipeline pipeline = new FilterPipeline();
pipeline.addPipelineListener(pipelineReport);
pipeline.setSorter(new ShuttleSorter());
assertEquals("pipeline must not fire if unassigned", 0, pipelineReport.getEventCount());
pipelineReport.clear();
pipeline.setSorter(null);
assertEquals("pipeline must not fire if unassigned", 0, pipelineReport.getEventCount());
}
/**
* Issue #45-swingx:
* interpose should throw if trying to interpose to a pipeline
* with a differnt ComponentAdapter.
*
*/
public void testSetSorterDiffComponentAdapter() {
FilterPipeline pipeline = new FilterPipeline();
pipeline.assign(directModelAdapter);
Sorter sorter = new ShuttleSorter();
sorter.assign(new DirectModelAdapter(new DefaultTableModel(10, 5)));
try {
pipeline.setSorter(sorter);
fail("interposing with a different adapter must throw an IllegalStateException");
} catch (IllegalStateException ex) {
} catch (Exception e) {
fail("interposing with a different adapter must throw an " +
"IllegalStatetException instead of " + e);
}
}
/**
*
* Issue #46-swingx:
*
* need to clarify the behaviour of an empty pipeline.
* I would expect 0 filters to result in an open pipeline
* (nothing filtered). The implementation treats this case as a
* closed pipeline (everything filtered).
*
* Arguably it could be decided either way, but returning a
* outputsize > 0 and null instead of the adapter value for
* all rows is a bug.
*
* Fixed by adding an pass-all filter internally.
*
*/
public void testEmptyPipeline() {
int sortColumn = 0;
FilterPipeline pipeline = new FilterPipeline();
pipeline.assign(directModelAdapter);
assertEquals("size must be number of rows in adapter",
directModelAdapter.getRowCount(), pipeline.getOutputSize());
Object value = pipeline.getValueAt(0, sortColumn);
assertEquals(directModelAdapter.getValueAt(0, sortColumn), value);
}
/**
* sorter in empty pipeline must behave in the same way as
* an identical sorter in the pipeline's filter chain.
*
*/
public void testSorterInEmptyPipeline() {
int sortColumn = 0;
// prepare the reference pipeline
Filter[] sorters = new Filter[] {new ShuttleSorter()};
FilterPipeline sortedPipeline = new FilterPipeline(sorters);
sortedPipeline.assign(directModelAdapter);
Object sortedValue = sortedPipeline.getValueAt(0, sortColumn);
// prepare the empty pipeline with associated sorter
FilterPipeline pipeline = new FilterPipeline();
pipeline.assign(directModelAdapter);
Sorter sorter = new ShuttleSorter();
pipeline.setSorter(sorter);
assertEquals("sorted values must be equal", sortedValue, pipeline.getValueAt(0, sortColumn));
}
/**
* sorter.getValueAt must be same as pipeline.getValueAt.
*
*/
public void testSorterInPipeline() {
Filter filter = createDefaultPatternFilter(0);
FilterPipeline pipeline = new FilterPipeline(new Filter[] { filter });
pipeline.assign(directModelAdapter);
Sorter sorter = new ShuttleSorter();
pipeline.setSorter(sorter);
assertEquals("value access via sorter must return the same as via pipeline",
pipeline.getValueAt(0, 0), sorter.getValueAt(0,0));
}
/**
* unassigned filter/-pipeline must have size 0.
*
*/
public void testUnassignedFilter() {
Filter filter = createDefaultPatternFilter(0);
assertEquals(0, filter.getSize());
Filter[] filters = new Filter[] {filter};
FilterPipeline pipeline = new FilterPipeline(filters);
assertEquals(0, pipeline.getOutputSize());
}
public void testUnassignedEmptyFilter() {
FilterPipeline filters = new FilterPipeline();
assertEquals(0, filters.getOutputSize());
}
/**
* JW: test paranoia?
*
*/
public void testDirectComponentAdapterAccess() {
FilterPipeline pipeline = createPipeline();
pipeline.assign(directModelAdapter);
assertTrue("pipeline must have filtered values", pipeline.getOutputSize() < directModelAdapter.getRowCount());
}
/**
* order of filters must be retained.
*
*/
public void testFilterOrder() {
Filter filterZero = createDefaultPatternFilter(0);
Filter filterTwo = createDefaultPatternFilter(2);
Sorter sorter = new ShuttleSorter();
assertEquals("order < 0", -1, sorter.order);
Filter[] filters = new Filter[] {filterZero, filterTwo, sorter};
new FilterPipeline(filters);
assertOrder(filterZero, filters);
}
/**
* FilterPipeline allows maximal one sorter per column.
*
*/
public void testDuplicatedSortColumnException() {
Filter[] filters = new Filter[] {new ShuttleSorter(), new ShuttleSorter()};
try {
new FilterPipeline(filters);
fail("trying to sort one column more than once must throw IllegalArgumentException");
} catch (IllegalArgumentException e) {
// that's what we expect
} catch (Exception e) {
fail("trying to sort one column more than once must throw IllegalArgumentException" +
"instead of " + e);
}
}
/**
* A filter can be bound to maximally one pipeline.
*/
public void testAssignFilterPipelineBoundFilterException() {
Filter filter = createDefaultPatternFilter(0);
assertEquals("order < 0", -1, filter.order);
Filter[] filters = new Filter[] {filter};
new FilterPipeline(filters);
try {
new FilterPipeline(filters);
fail("sharing filters are not allowed - must throw IllegalArgumentException");
} catch (IllegalArgumentException e) {
// that's what we expect
} catch (Exception e) {
fail("exception must be illegalArgument instead of " + e);
}
}
/**
* early binding of pipeline to filters.
*
*/
public void testAssignFilterPipeline() {
Filter filter = createDefaultPatternFilter(0);
Filter[] filters = new Filter[] {filter};
FilterPipeline pipeline = new FilterPipeline(filters);
assertEquals("assigned to pipeline", pipeline, filter.getPipeline());
JXTable table = new JXTable(tableModel);
table.setFilters(pipeline);
assertEquals("assigned to table's componentadapter", table, filter.adapter.getComponent());
}
private void assertOrder(Filter filter, Filter[] filters) {
int position = getFilterPosition(filter, filters);
assertEquals("order equals position in array", position, filter.order);
}
protected void assertOrders(Filter[] filters) {
for (int i = 0; i < filters.length; i++) {
assertEquals("order must be equal to filter position", i, filters[i].order);
}
}
private int getFilterPosition(Filter filter, Filter[] filters) {
for (int i = 0; i < filters.length; i++) {
if (filters[i].equals(filter)) {
return i;
}
}
return -1;
}
/**
* returns a pipeline with two default patternfilters on
* column 0, 2 and an ascending sorter on column 0.
*/
protected FilterPipeline createPipeline() {
Filter filterZero = createDefaultPatternFilter(0);
Filter filterTwo = createDefaultPatternFilter(2);
Sorter sorter = new ShuttleSorter();
Filter[] filters = new Filter[] {filterZero, filterTwo, sorter};
FilterPipeline pipeline = new FilterPipeline(filters);
return pipeline;
}
/** returns a PatternFilter for occurences of "e" in column.
*
* @param column
* @return a PatternFilter for occurences of "e" in column
*/
protected Filter createDefaultPatternFilter(int column) {
Filter filterZero = new PatternFilter("e", 0, column);
return filterZero;
}
/**
* This is a test to ensure that the example in the javadoc actually works.
* if the javadoc example changes, then those changes should be pasted here.
*/
public void testJavaDocExample() {
Filter[] filters = new Filter[] {
new PatternFilter("^S", 0, 1), // regex, matchflags, column
new ShuttleSorter(1, false), // column 1, descending
new ShuttleSorter(0, true), // column 0, ascending
};
FilterPipeline pipeline = new FilterPipeline(filters);
JXTable table = new JXTable();
table.setFilters(pipeline);
}
protected void setUp() throws Exception {
super.setUp();
tableModel = new AncientSwingTeam();
directModelAdapter = new DirectModelAdapter(tableModel);
pipelineReport = new PipelineReport();
}
/**
* ComponentAdapter directly on top of a TableModel.
*/
public static class DirectModelAdapter extends ComponentAdapter {
private TableModel tableModel;
public DirectModelAdapter(TableModel tableModel) {
super(null);
this.tableModel = tableModel;
}
public int getColumnCount() {
return tableModel.getColumnCount();
}
public int getRowCount() {
return tableModel.getRowCount();
}
public String getColumnName(int columnIndex) {
return tableModel.getColumnName(columnIndex);
}
public String getColumnIdentifier(int columnIndex) {
return getColumnName(columnIndex);
}
public Object getValueAt(int row, int column) {
return tableModel.getValueAt(row, column);
}
public Object getFilteredValueAt(int row, int column) {
return null;
}
public void setValueAt(Object aValue, int row, int column) {
tableModel.setValueAt(aValue, row, column);
}
public boolean isCellEditable(int row, int column) {
return tableModel.isCellEditable(row, column);
}
public boolean hasFocus() {
return false;
}
public boolean isSelected() {
return false;
}
public void refresh() {
// do nothing
}
}
/**
* just to see the filtering effects...
*
*/
public void interactiveTestColumnControlAndFilters() {
final JXTable table = new JXTable(tableModel);
table.setColumnControlVisible(true);
Action toggleFilter = new AbstractAction("Toggle Filters") {
boolean hasFilters;
public void actionPerformed(ActionEvent e) {
if (hasFilters) {
table.setFilters(null);
} else {
table.setFilters(createPipeline());
}
hasFilters = !hasFilters;
}
};
toggleFilter.putValue(Action.SHORT_DESCRIPTION, "filtering first column - problem if invisible ");
JXFrame frame = wrapWithScrollingInFrame(table, "JXTable ColumnControl and Filters");
addAction(frame, toggleFilter);
frame.setVisible(true);
}
/**
* just to see the filtering effects...
*
*/
public void interactiveTestAndFilter() {
final JXTable table = new JXTable(tableModel);
table.setColumnControlVisible(true);
Action toggleFilter = new AbstractAction("Toggle Filters") {
boolean hasFilters;
public void actionPerformed(ActionEvent e) {
if (hasFilters) {
table.setFilters(null);
} else {
PatternFilter first = new PatternFilter("a", 0, 0);
PatternFilter second = new PatternFilter("b", 0, 1);
FilterPipeline pipeline = new FilterPipeline(new Filter[] {first, second});
table.setFilters(pipeline);
}
hasFilters = !hasFilters;
}
};
toggleFilter.putValue(Action.SHORT_DESCRIPTION,
"Filtered rows: col(0) contains 'a' AND col(1) contains 'b'");
JXFrame frame = wrapWithScrollingInFrame(table, "JXTable ColumnControl and Filters");
addAction(frame, toggleFilter);
frame.setVisible(true);
}
public static void main(String args[]) {
setSystemLF(true);
FilterTest test = new FilterTest();
try {
test.runInteractiveTests();
} catch (Exception e) {
System.err.println("exception when executing interactive tests:");
e.printStackTrace();
}
}
}
|
package de.dhbw.humbuch.util;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
/**
* @author davherrmann
*
* Util class for looking up a book by its isbn
* <ul>
* <li>Standard ISBN API is isbndb.com</li>
* <li>Document retrieval, validation and parsing can be overridden in subclass</li>
* </ul>
*/
public class BookLookup {
private final static String KEY = "CONBNUOZ";
private final static String LOOKUP_URL = "http://isbndb.com/api/v2/xml/"
+ KEY + "/book/";
/**
* Look up a book by its ISBN
*
* @param isbn
* {@link String} containing the ISBN - all non-numerical
* characters are ignored
* @return {@link Book} containing the book data
* @throws BookNotFoundException
* when a book is not found
*/
public static Book lookup(String isbn) throws BookNotFoundException {
Document document = retrieveDocument(buildLookupURL(processISBN(isbn)));
validateDocument(document);
return parseDocument(document);
}
/**
* Removes all non-numerical characters from the isbn
*
* @param isbn
* {@link String} containing the ISBN
* @return {@link String} without all non-numerical characters
*/
protected static String processISBN(String isbn) {
return isbn.replaceAll("[^\\d]", "");
}
/**
* Builds the URI for the ISBN API
*
* @param isbn
* {@link String} containing the ISBN
* @return {@link String} containing the ISBN API URL
*/
protected static String buildLookupURL(String isbn) {
return LOOKUP_URL + isbn;
}
/**
* Retrieve an document from a given URI
*
* @param uri
* {@link String} containing the URI
* @return {@link Document} retrieved from the URI
* @throws BookNotFoundException
* thrown when an error occurs while retrieving the document
*/
protected static Document retrieveDocument(String uri)
throws BookNotFoundException {
try {
DocumentBuilder documentBuilder = DocumentBuilderFactory
.newInstance().newDocumentBuilder();
Document document = documentBuilder.parse(uri);
document.getDocumentElement().normalize();
return document;
} catch (ParserConfigurationException | SAXException | IOException e) {
throw new BookNotFoundException(
"Error during retrieving the XML document...", e);
}
}
/**
* Checks if the document contains valid data for a book
*
* @param document
* {@link Document} to be validated
* @throws BookNotFoundException
* thrown when the document contains no valid book data
*/
protected static void validateDocument(Document document)
throws BookNotFoundException {
Object error = getNodeValue(document, "error");
if (error != null) {
throw new BookNotFoundException("No book found...");
}
}
/**
* Parse a document and extract the book data
*
* @param document
* {@link Document} containing the book data
* @return {@link Book} with the extracted data
*/
protected static Book parseDocument(Document document) {
return new Book.Builder(getNodeValue(document, "title"))
.author(getNodeValue(document, "name"))
.isbn10(getNodeValue(document, "isbn10"))
.isbn13(getNodeValue(document, "isbn13"))
.publisher(getNodeValue(document, "publisher_name")).build();
}
/**
* Extract the value of the first node of an element
*
* @param document
* the {@link Document}
* @param elementName
* name of the element of which the value should be extracted
* @return {@link String} containing the content of the element if it
* exists, otherwise <code>null</code>
*/
private static String getNodeValue(Document document, String elementName) {
NodeList data = document.getElementsByTagName(elementName);
Element element = (Element) data.item(0);
if (element != null) {
Node node = element.getChildNodes().item(0);
return node.getNodeValue();
}
return null;
}
/**
* Exception indicating a book was not found
*/
public static class BookNotFoundException extends Exception {
private static final long serialVersionUID = -644882332116172763L;
public BookNotFoundException() {
super();
}
public BookNotFoundException(String message, Throwable cause,
boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
public BookNotFoundException(String message, Throwable cause) {
super(message, cause);
}
public BookNotFoundException(String message) {
super(message);
}
public BookNotFoundException(Throwable cause) {
super(cause);
}
}
/**
* POJO holding information about the book
*/
public static class Book {
public final String author;
public final String isbn10;
public final String isbn13;
public final String publisher;
public final String title;
private Book(Builder builder) {
this.author = builder.author;
this.isbn10 = builder.isbn10;
this.isbn13 = builder.isbn13;
this.publisher = builder.publisher;
this.title = builder.title;
}
public static class Builder {
private String author;
private String isbn10;
private String isbn13;
private String publisher;
private String title;
public Builder(String title) {
this.title = title;
}
public Builder author(String author) {
this.author = author;
return this;
}
public Builder isbn10(String isbn10) {
this.isbn10 = isbn10;
return this;
}
public Builder isbn13(String isbn13) {
this.isbn13 = isbn13;
return this;
}
public Builder publisher(String publisher) {
this.publisher = publisher;
return this;
}
public Book build() {
return new Book(this);
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.