answer
stringlengths 17
10.2M
|
|---|
package liquibase.change;
import liquibase.database.Database;
import liquibase.database.sql.ComputedNumericValue;
import liquibase.database.sql.ComputedDateValue;
import liquibase.util.ISODateFormat;
import liquibase.util.StringUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Date;
/**
* This class is the representation of the column tag in the XMl file
* It has a reference to the Constraints object for getting information
* about the columns constraints.
*/
public class ColumnConfig {
private String name;
private String type;
private String value;
private Number valueNumeric;
private Date valueDate;
private Boolean valueBoolean;
private String defaultValue;
private Number defaultValueNumeric;
private Date defaultValueDate;
private Boolean defaultValueBoolean;
private ConstraintsConfig constraints;
private Boolean autoIncrement;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getValue() {
return value;
}
public void setValue(String value) {
// Since we have two rules for the value it can either be specifed as an attribute
// or as the tag body in case of long values then the check is necessary so that it
// should not override the value specifed as an attribute.
if (StringUtils.trimToNull(value) != null) {
this.value = value;
}
}
public Number getValueNumeric() {
return valueNumeric;
}
public void setValueNumeric(String valueNumeric) throws ParseException {
if (valueNumeric == null) {
this.valueNumeric = null;
} else {
if (valueNumeric.matches("\\d+\\.?\\d*")) {
this.valueNumeric = NumberFormat.getInstance().parse(valueNumeric);
} else {
this.valueNumeric = new ComputedNumericValue(valueNumeric);
}
}
}
public void setValueNumeric(Number valueNumeric) {
this.valueNumeric = valueNumeric;
}
public Boolean getValueBoolean() {
return valueBoolean;
}
public void setValueBoolean(Boolean valueBoolean) {
this.valueBoolean = valueBoolean;
}
public Date getValueDate() {
return valueDate;
}
public void setValueDate(Date valueDate) {
this.valueDate = valueDate;
}
public void setValueDate(String valueDate) throws ParseException {
try {
this.valueDate = new ISODateFormat().parse(valueDate);
} catch (ParseException e) {
//probably a function
this.valueDate = new ComputedDateValue(valueDate);
}
}
public Object getValueObject() {
if (getValue() != null) {
return getValue();
} else if (getValueBoolean() != null) {
return getValueBoolean();
} else if (getValueNumeric() != null) {
return getValueNumeric();
} else if (getValueDate() != null) {
return getValueDate();
}
return null;
}
public String getDefaultValue() {
return defaultValue;
}
public void setDefaultValue(String defaultValue) {
this.defaultValue = defaultValue;
}
public Number getDefaultValueNumeric() {
return defaultValueNumeric;
}
public void setDefaultValueNumeric(Number defaultValueNumeric) {
this.defaultValueNumeric = defaultValueNumeric;
}
public void setDefaultValueNumeric(String defaultValueNumeric) throws ParseException {
if (defaultValueNumeric == null) {
this.defaultValueNumeric = null;
} else {
if ("GENERATED_BY_DEFAULT".equals(defaultValueNumeric)) {
setAutoIncrement(true);
} else {
this.defaultValueNumeric = NumberFormat.getInstance().parse(defaultValueNumeric);
}
}
}
public Date getDefaultValueDate() {
return defaultValueDate;
}
public void setDefaultValueDate(String defaultValueDate) throws ParseException {
this.defaultValueDate = new ISODateFormat().parse(defaultValueDate);
}
public void setDefaultValueDate(Date defaultValueDate) {
this.defaultValueDate = defaultValueDate;
}
public Boolean getDefaultValueBoolean() {
return defaultValueBoolean;
}
public void setDefaultValueBoolean(Boolean defaultValueBoolean) {
this.defaultValueBoolean = defaultValueBoolean;
}
public Object getDefaultValueObject() {
if (getDefaultValue() != null) {
return getDefaultValue();
} else if (getDefaultValueBoolean() != null) {
return getDefaultValueBoolean();
} else if (getDefaultValueNumeric() != null) {
return getDefaultValueNumeric();
} else if (getDefaultValueDate() != null) {
return getDefaultValueDate();
}
return null;
}
public ConstraintsConfig getConstraints() {
return constraints;
}
public void setConstraints(ConstraintsConfig constraints) {
this.constraints = constraints;
}
public Boolean isAutoIncrement() {
return autoIncrement;
}
public void setAutoIncrement(Boolean autoIncrement) {
this.autoIncrement = autoIncrement;
}
public Element createNode(Document document) {
Element element = document.createElement("column");
element.setAttribute("name", getName());
if (getType() != null) {
element.setAttribute("type", getType());
}
if (getDefaultValue() != null) {
element.setAttribute("defaultValue", getDefaultValue());
}
if (getDefaultValueNumeric() != null) {
element.setAttribute("defaultValueNumeric", getDefaultValueNumeric().toString());
}
if (getDefaultValueDate() != null) {
element.setAttribute("defaultValueDate", new ISODateFormat().format(getDefaultValueDate()));
}
if (getDefaultValueBoolean() != null) {
element.setAttribute("defaultValueBoolean", getDefaultValueBoolean().toString());
}
if (getValue() != null) {
element.setAttribute("value", getValue());
}
if (getValueNumeric() != null) {
element.setAttribute("valueNumeric", getValueNumeric().toString());
}
if (getValueBoolean() != null) {
element.setAttribute("valueBoolean", getValueBoolean().toString());
}
if (getValueDate() != null) {
element.setAttribute("valueDate", new ISODateFormat().format(getValueDate()));
}
if (isAutoIncrement() != null && isAutoIncrement()) {
element.setAttribute("autoIncrement", "true");
}
ConstraintsConfig constraints = getConstraints();
if (constraints != null) {
Element constraintsElement = document.createElement("constraints");
if (constraints.getCheck() != null) {
constraintsElement.setAttribute("check", constraints.getCheck());
}
if (constraints.getForeignKeyName() != null) {
constraintsElement.setAttribute("foreignKeyName", constraints.getForeignKeyName());
}
if (constraints.getReferences() != null) {
constraintsElement.setAttribute("references", constraints.getReferences());
}
if (constraints.isDeferrable() != null) {
constraintsElement.setAttribute("deferrable", constraints.isDeferrable().toString());
}
if (constraints.isDeleteCascade() != null) {
constraintsElement.setAttribute("deleteCascade", constraints.isDeleteCascade().toString());
}
if (constraints.isInitiallyDeferred() != null) {
constraintsElement.setAttribute("initiallyDeferred", constraints.isInitiallyDeferred().toString());
}
if (constraints.isNullable() != null) {
constraintsElement.setAttribute("nullable", constraints.isNullable().toString());
}
if (constraints.isPrimaryKey() != null) {
constraintsElement.setAttribute("primaryKey", constraints.isPrimaryKey().toString());
}
if (constraints.isUnique() != null) {
constraintsElement.setAttribute("unique", constraints.isUnique().toString());
}
element.appendChild(constraintsElement);
}
return element;
}
public String getDefaultColumnValue(Database database) {
if (this.getDefaultValue() != null) {
if ("null".equalsIgnoreCase(this.getDefaultValue())) {
return "NULL";
}
if (!database.shouldQuoteValue(this.getDefaultValue())) {
return this.getDefaultValue();
} else {
return "'" + this.getDefaultValue().replaceAll("'", "''") + "'";
}
} else if (this.getDefaultValueNumeric() != null) {
return this.getDefaultValueNumeric().toString();
} else if (this.getDefaultValueBoolean() != null) {
String returnValue;
if (this.getDefaultValueBoolean()) {
returnValue = database.getTrueBooleanValue();
} else {
returnValue = database.getFalseBooleanValue();
}
if (returnValue.matches("\\d+")) {
return returnValue;
} else {
return "'" + returnValue + "'";
}
} else if (this.getDefaultValueDate() != null) {
Date defaultDateValue = this.getDefaultValueDate();
return database.getDateLiteral(defaultDateValue);
} else {
return "NULL";
}
}
public boolean hasDefaultValue() {
return this.getDefaultValue() != null
|| this.getDefaultValueBoolean() != null
|| this.getDefaultValueDate() != null
|| this.getDefaultValueNumeric() != null;
}
}
|
package com.novoda.merlin;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import com.novoda.merlin.registerable.Registerer;
import com.novoda.merlin.registerable.bind.Bindable;
import com.novoda.merlin.registerable.connection.Connectable;
import com.novoda.merlin.registerable.disconnection.Disconnectable;
import com.novoda.merlin.service.MerlinServiceBinder;
public class Merlin {
public static final String DEFAULT_ENDPOINT = "http:
private final MerlinServiceBinder merlinServiceBinder;
private final Registerer registerer;
Merlin(MerlinServiceBinder merlinServiceBinder, Registerer registerer) {
this.merlinServiceBinder = merlinServiceBinder;
this.registerer = registerer;
}
public void setEndpoint(String endpoint) {
merlinServiceBinder.setEndpoint(endpoint);
}
public void bind() {
merlinServiceBinder.bindService();
}
public void unbind() {
merlinServiceBinder.unbind();
}
public void registerConnectable(Connectable connectable) {
registerer.registerConnectable(connectable);
}
public void registerDisconnectable(Disconnectable disconnectable) {
registerer.registerDisconnectable(disconnectable);
}
public void registerBindable(Bindable bindable) {
registerer.registerBindable(bindable);
}
public static boolean isConnected(Context context) {
NetworkInfo activeNetworkInfo = getNetworkInfo(context);
return (activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting());
}
private static NetworkInfo getNetworkInfo(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
return connectivityManager.getActiveNetworkInfo();
}
public static class Builder extends MerlinBuilder {
}
}
|
package hudson.model;
import hudson.ExtensionPoint;
import hudson.Plugin;
/**
* Extensible property of {@link Job}.
*
* <p>
* {@link Plugin}s can extend this to define custom properties
* for {@link Job}s. {@link JobProperty}s show up in the user
* configuration screen, and they are persisted with the job object.
*
* <p>
* Configuration screen should be defined in <tt>config.jelly</tt>.
* Within this page, the {@link JobProperty} instance is available
* as <tt>instance</tt> variable (while <tt>it</tt> refers to {@link Job}.
*
*
* @author Kohsuke Kawaguchi
* @see JobPropertyDescriptor
* @since 1.72
*/
public abstract class JobProperty<J extends Job<?,?>> implements Describable<JobProperty<?>>, ExtensionPoint {
/**
* The {@link Job} object that owns this property.
* This value will be set by the Hudson code.
* Derived classes can expect this value to be always set.
*/
protected transient J owner;
protected void setOwner(J owner) {
this.owner = owner;
}
/**
* {@inheritDoc}
*/
public abstract JobPropertyDescriptor getDescriptor();
/**
* {@link Action} to be displayed in the job page.
*
* @return
* null if there's no such action.
* @since 1.102
*/
public Action getJobAction(J job) {
return null;
}
}
|
// Triple Play - utilities for use in PlayN-based games
package tripleplay.gesture;
import java.util.HashMap;
import java.util.Map;
import pythagoras.f.Point;
/**
* A simple swipe gesture in a given cardinal direction. Supports 1 to 4 fingers. If greedy, will
* indicate a continuous swipe. Completes if: one of the fingers stops moving or is removed from the
* display. Cancels if an additional finger is added to the display or one of the fingers switches
* directions.
*/
public class Swipe extends GestureBase<Swipe>
{
public Swipe (Direction direction) {
this(1, direction);
}
public Swipe (int touches, Direction direction) {
if (touches < 1 || touches > 4) {
Log.log.warning("How many fingers do you think people have?", "tapTouches", 4);
touches = Math.max(1, Math.min(4, touches));
}
if (direction == null) {
Log.log.warning("Swipe cannot operate with a null direction, assuming RIGHT");
direction = Direction.RIGHT;
}
_touches = touches;
_direction = direction;
_directionModifier = _direction == Direction.UP || _direction == Direction.LEFT ? -1 : 1;
}
/**
* If true (the default) a pause counts the same as a finger lifted from the display.
*/
public Swipe cancelOnPause (boolean value) {
_cancelOnPause = value;
return this;
}
/**
* A swipe is not qualified if the user moves outside of a region defined by lines that are
* parallel to the line that goes through the start touch point along the direction axis.
* offAxisTolerance is the distance away from that defining line that the parallel boundaries
* sit. The default is 10 pixels. If you want the user to have more freedom in how finely
* defined their swipes are, make the tolerance large.
*/
public Swipe offAxisTolerance (int pixels) {
_offAxisTolerance = pixels;
return this;
}
@Override protected void clearMemory () {
_movedEnough = false;
_startPoints.clear();
_lastPoints.clear();
}
@Override protected void updateState (GestureNode node) {
switch (node.type) {
case START:
_startPoints.put(node.touch.id(), node.location());
break;
case MOVE:
// always grounds for immediate dismissal
if (_startPoints.size() != _touches) setState(State.UNQUALIFIED);
evaluateMove(node);
break;
case PAUSE:
if (_cancelOnPause) {
setState(_movedEnough && _startPoints.size() == _touches ?
State.COMPLETE : State.UNQUALIFIED);
}
break;
case END:
setState(_movedEnough && _startPoints.size() == _touches ?
State.COMPLETE : State.UNQUALIFIED);
break;
case CANCEL:
setState(State.UNQUALIFIED);
break;
}
}
// TODO: any gesture that cares about swiping in a cardinal direction could make use of this
protected void evaluateMove (GestureNode node) {
Point start = _startPoints.get(node.touch.id());
if (start == null) {
Log.log.warning("No start point for a path check, invalid state",
"touchId", node.touch.id());
return;
}
Point last = _lastPoints.get(node.touch.id());
Point current = node.location();
_lastPoints.put(node.touch.id(), current);
// we haven't moved far enough yet, no further evaluation needed.
if (current.distance(start) < DIRECTION_THRESHOLD) return;
float offAxisDistance; // distance from our start position in the perpendicular axis
float lastAxisDistance = axisDistance(last, current);
if (_direction == Direction.UP || _direction == Direction.DOWN)
offAxisDistance = Math.abs(current.x() - start.x());
else
offAxisDistance = Math.abs(current.y() - start.y());
// if we've strayed outside of the safe zone, or we've backtracked from our last position,
// disqualify
if (offAxisDistance > _offAxisTolerance || lastAxisDistance < 0)
setState(State.UNQUALIFIED);
// Figure out if we've moved enough to meet minimum requirements with all touches
if (!_movedEnough) {
boolean allMovedEnough = true;
for (Map.Entry<Integer, Point> touchStart : _startPoints.entrySet()) {
Point touchLast = _lastPoints.get(touchStart.getKey());
if (axisDistance(touchStart.getValue(), touchLast) <= DIRECTION_THRESHOLD) {
allMovedEnough = false;
break;
}
}
if (allMovedEnough) {
_movedEnough = true;
if (_greedy) setState(State.GREEDY);
}
}
}
protected float axisDistance (Point start, Point end) {
if (start == null || end == null) return 0;
if (_direction == Direction.UP || _direction == Direction.DOWN)
return (end.y() - start.y()) * _directionModifier;
else
return (end.x() - start.x()) * _directionModifier;
}
// the furthest in a perpendicular direction a finger can go before being considered to not be
// moving the in the right direction. Also the distance that a finger must move to be considered
// a swipe.
protected static final int DIRECTION_THRESHOLD = 10;
protected final int _touches;
protected final Direction _direction;
protected final int _directionModifier;
protected boolean _movedEnough = false;
protected Map<Integer, Point> _startPoints = new HashMap<Integer, Point>();
protected Map<Integer, Point> _lastPoints = new HashMap<Integer, Point>();
protected boolean _cancelOnPause = true;
protected int _offAxisTolerance = 10;
}
|
// Triple Play - utilities for use in PlayN-based games
package tripleplay.syncdb;
import java.util.AbstractMap;
import java.util.AbstractSet;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import react.AbstractValue;
import react.RMap;
import react.RSet;
import react.Slot;
import react.Value;
import playn.core.Asserts;
import playn.core.Platform;
import playn.core.Storage;
import static tripleplay.syncdb.Log.log;
/**
* A database of key/value pairs that is synced (via a server) across multiple devices. The
* suggested usage pattern is to subclass {@code SyncDB} and define your properties like so:
* <pre>{@code
* public class FooDB extends SyncDB {
* public final Value<String> name = value("name", (String)null, Codec.STRING, Resolver.SERVER);
* public final Value<Integer> xp = value("xp", 0, Codec.INT, Resolver.INTMAX);
* public final Value<Integer> difficultyLevel = value("diff", 0, Codec.INT, Resolver.SERVER);
* public final RSet<String> badges = set("badges", Codec.STRING, SetResolver.UNION);
* public final RMap<String,Integer> items = map("it", Codec.STRING, Codec.INT, Resolver.INTMAX);
* // etc.
* }
* }</pre>
*/
public abstract class SyncDB
{
/**
* Returns the version at which this database was last synced.
*/
public int version () {
return _version;
}
/**
* Returns true if this database contains changes that have not been synced.
*/
public boolean hasUnsyncedChanges () {
return !_mods.isEmpty();
}
/**
* Returns a map of properties that have changed since our last sync. These can be sent to the
* server (along with our current version) to sync our state with the server.
*/
public Map<String,String> getDelta () {
Map<String,String> delta = new HashMap<String,String>();
for (String name : _mods) delta.put(name, _storage.getItem(name));
return delta;
}
/**
* Notes that we synced cleanly with the server. Updates our local version to the latest sync
* version and notes that we no longer have unsynced modifications.
*/
public void noteSync (int version) {
_mods.clear();
flushMods();
updateVersion(version);
}
/**
* Returns whether the supplied delta contains changes to any properties for which unsynced
* changes also exist.
*/
public boolean containsMerges (Map<String,String> delta) {
for (String key : delta.keySet()) if (_mods.contains(key)) return true;
return false;
}
/**
* Applies the supplied changes to this database. Any conflicts will be resolved according to
* the configured policies. If the resolved value differs from the supplied value, the property
* will remain marked as locally modified. Thus changes may need to be flushed again after
* calling this method. After applying the delta and resolving conflicts, the local version
* will be updated to the supplied version.
*
* @param version the latest version.
* @param delta the modifications from our local version to the latest version.
*/
public void applyDelta (int version, Map<String,String> delta) {
// resolve all of the subdbs that are needed to apply these properties
Set<String> subDBs = new HashSet<String>();
for (String key : delta.keySet()) {
String sdb = DBUtil.subDB(key);
if (sdb != null) subDBs.add(sdb);
}
if (!subDBs.isEmpty()) for (String subdb : subDBs) getSubDB(subdb);
// now apply the delta to the appropriate properties
for (Map.Entry<String,String> entry : delta.entrySet()) {
String name = entry.getKey();
Property prop;
int pidx = name.indexOf(DBUtil.MAP_KEY_SEP);
if (pidx == -1) prop = _props.get(name);
else prop = _props.get(name.substring(0, pidx));
if (prop == null) {
log.warning("No local property defined", "name", name);
} else if (_mods.contains(name)) {
if (prop.merge(name, entry.getValue())) _mods.remove(name);
} else {
prop.update(name, entry.getValue());
_mods.remove(name); // updating will cause the property to be marked as locally
// changed, but it's not really locally changed, it's been set
// to the latest synced value, so clear the mod flag
}
}
flushMods();
updateVersion(version);
}
/**
* Prepares this database to be melded into a pre-existing database. Resets this database's
* version to zero and marks all properties as modified. The database can then be synced with
* another database which will merge the other database into this one and then push remaining
* changes back up to the server. This is used to merge the database between two clients.
*/
public void prepareToMeld () {
updateVersion(0);
for (Property prop : _props.values()) prop.prepareToMeld();
}
protected SyncDB (Platform platform) {
_platform = platform;
_storage = platform.storage();
_version = get(SYNC_VERS_KEY, 0, Codec.INT);
// read the current unsynced key set
_mods = sget(SYNC_MODS_KEY, Codec.STRING);
}
/**
* Creates a synced value with the specified configuration.
*
* @param name the name to use for the persistent property, must not conflict with any other
* value, set or map name.
* @param defval the default value to use until a value has been configured.
* @param codec the codec to use when converting the value to and from a string for storage.
* @param resolver the conflict resolution policy to use when local modifications conflict with
* server modifications.
*/
protected <T> Value<T> value (final String name, final T defval, final Codec<T> codec,
final Resolver<? super T> resolver) {
Asserts.checkArgument(!SYNC_KEYS.contains(name), name + " is a reserved name.");
// create a value that reads/writes directly from/to the persistent store
final Value<T> value = new Value<T>(null) {
@Override public T get () {
return SyncDB.this.get(name, defval, codec);
}
@Override protected T updateLocal (T value) {
T oldValue = get();
SyncDB.this.set(name, value, codec);
return oldValue;
}
@Override protected void emitChange (T value, T ovalue) {
super.emitChange(value, ovalue);
noteModified(name);
}
};
_props.put(name, new Property() {
public boolean merge (String name, String data) {
T svalue = codec.decode(data), nvalue = resolver.resolve(value.get(), svalue);
value.update(nvalue);
return nvalue.equals(svalue);
}
public void update (String name, String data) {
value.update(codec.decode(data));
}
public void prepareToMeld () {
noteModified(name);
}
});
return value;
}
/**
* Creates a synced set with the specified configuration.
*
* @param name the name to use for the persistent property, must not conflict with any other
* value, set or map name.
* @param codec the codec to use when converting an element to and from a string for storage.
* @param resolver the conflict resolution policy to use when local modifications conflict with
* server modifications.
*/
protected <E> RSet<E> set (final String name, final Codec<E> codec, final SetResolver resolver) {
Asserts.checkArgument(!SYNC_KEYS.contains(name), name + " is a reserved name.");
final RSet<E> rset = new RSet<E>(sget(name, codec)) {
@Override protected void emitAdd (E elem) {
super.emitAdd(elem);
sset(name, _impl, codec);
noteModified(name);
}
@Override protected void emitRemove (E elem) {
super.emitRemove(elem);
sset(name, _impl, codec);
noteModified(name);
}
};
_props.put(name, new Property() {
public boolean merge (String name, String data) {
Set<E> sset = DBUtil.decodeSet(data, codec);
resolver.resolve(rset, sset);
return rset.equals(sset);
}
public void update (String name, String data) {
Set<E> sset = DBUtil.decodeSet(data, codec);
rset.retainAll(sset);
rset.addAll(sset);
}
public void prepareToMeld () {
noteModified(name);
}
});
return rset;
}
/**
* Creates a synced map with the specified configuration. Note that deletions take precedence
* over additions or modifications. If any client deletes a key, the deletion will be
* propagated to all clients, regardless of whether another client updates or reinstates the
* mapping in the meanwhile. Thus, you must avoid structuring your storage such that keys are
* deleted and later re-added. Instead use a "deleted" sentinal value for keys that may once
* again map to valid values.
*
* <em>Note:</em> the returned map <em>will not</em> tolerate ill-typed keys. Passing a key
* that is not an instance of {@code K} to any method that accepts a key will result in a
* ClassCastException. Also {@link Map#containsValue} is not supported by the returned map.
*
* @param prefix a string prefix prepended to the keys to create the storage key for each
* individual map entry. A '.' will be placed in between the prefix and the string value of the
* map key. For example: a prefix of {@code foo} and a map key of {@code 1} will result in a
* storage key of {@code foo.1}. Additionally, the {@code prefix_keys} storage cell will be used
* to track the current set of keys in the map.
* @param keyCodec the codec to use when converting a key to/from string.
* @param valCodec the codec to use when converting a value to/from string for storage.
* @param resolver the conflict resolution policy to use when conflicting changes have been
* made to a single mapping.
*/
protected <K,V> RMap<K,V> map (final String prefix, final Codec<K> keyCodec,
final Codec<V> valCodec, final Resolver<? super V> resolver) {
class StorageMap extends AbstractMap<K,V> {
@Override public int size () {
return _keys.size();
}
@Override public boolean containsKey (Object key) {
return _keys.contains(key);
}
@Override public V get (Object rawKey) {
String value = _storage.getItem(skey(rawKey));
return value == null ? null : valCodec.decode(value);
}
@Override public V put (K key, V value) {
_keys.add(key);
String skey = skey(key);
String valstr = valCodec.encode(value);
String ovalstr = _storage.getItem(skey);
_storage.setItem(skey, valstr);
if (!valstr.equals(ovalstr)) noteModified(skey);
return ovalstr == null ? null : valCodec.decode(ovalstr);
}
@Override public V remove (Object rawKey) {
String ovalue = _storage.getItem(skey(rawKey));
_keys.remove(rawKey); // this triggers a noteModified
return (ovalue == null) ? null : valCodec.decode(ovalue);
}
@Override public Set<K> keySet () {
return Collections.unmodifiableSet(_keys);
}
@Override public Set<Map.Entry<K,V>> entrySet () {
return new AbstractSet<Map.Entry<K,V>>() {
@Override public Iterator<Map.Entry<K,V>> iterator () {
return new Iterator<Map.Entry<K,V>>() {
public boolean hasNext () {
return _keysIter.hasNext();
}
public Map.Entry<K,V> next () {
final K key = _keysIter.next();
return new Map.Entry<K,V>() {
@Override public K getKey () { return key; }
@Override public V getValue () {
return StorageMap.this.get(key);
}
@Override public V setValue (V value) {
return StorageMap.this.put(key, value);
}
};
}
public void remove () {
_keysIter.remove();
}
protected Iterator<K> _keysIter = _keys.iterator();
};
}
@Override public int size () {
return _keys.size();
}
};
}
protected String skey (Object rawKey) {
@SuppressWarnings("unchecked") K key = (K)rawKey;
return DBUtil.mapKey(prefix, key, keyCodec);
}
protected final Set<K> _keys = new HashSet<K>(sget(mapKeysKey(prefix), keyCodec)) {
@Override public boolean add (K elem) {
if (!super.add(elem)) return false;
sset(mapKeysKey(prefix), this, keyCodec);
return true;
}
@Override public boolean remove (Object elem) {
if (!super.remove(elem)) return false;
@SuppressWarnings("unchecked") K key = (K)elem;
removeStorage(key);
sset(mapKeysKey(prefix), this, keyCodec);
return true;
}
@Override public Iterator<K> iterator () {
final Iterator<K> iter = super.iterator();
return new Iterator<K>() {
@Override public boolean hasNext () { return iter.hasNext(); }
@Override public K next () { return _current = iter.next(); }
@Override public void remove () {
iter.remove();
removeStorage(_current);
}
protected K _current;
};
}
protected void removeStorage (K key) {
String skey = skey(key);
_storage.removeItem(skey);
noteModified(skey);
}
};
}
final RMap<K,V> map = new RMap<K,V>(new StorageMap());
_props.put(prefix, new Property() {
public boolean merge (String name, String data) {
K skey = keyCodec.decode(name.substring(prefix.length()+1));
if (data == null) {
map.remove(skey);
return true;
}
V svalue = valCodec.decode(data), nvalue = resolver.resolve(map.get(skey), svalue);
map.put(skey, nvalue);
return nvalue.equals(svalue);
}
public void update (String name, String data) {
K skey = keyCodec.decode(name.substring(prefix.length()+1));
if (data == null) map.remove(skey);
else map.put(skey, valCodec.decode(data));
}
public void prepareToMeld () {
for (K key : map.keySet()) noteModified(DBUtil.mapKey(prefix, key, keyCodec));
}
});
return map;
}
/** Returns the subdb associated with the supplied prefix. The subdb will be created if it has
* not already been created, and will then be cached for the lifetime of the game. */
protected SubDB getSubDB (String prefix) {
SubDB db = _subdbs.get(prefix);
if (db == null) _subdbs.put(prefix, db = createSubDB(prefix));
return db;
}
protected SubDB createSubDB (String prefix) {
throw new IllegalArgumentException("Unknown subdb prefix: " + prefix);
}
protected <T> T get (String name, T defval, Codec<T> codec) {
String data = _storage.getItem(name);
return (data == null) ? defval : codec.decode(data);
}
protected <T> void set (String name, T value, Codec<T> codec) {
_storage.setItem(name, codec.encode(value));
}
protected <E> void sset (String name, Set<E> set, Codec<E> codec) {
_storage.setItem(name, DBUtil.encodeSet(set, codec));
}
protected <E> Set<E> sget (String name, Codec<E> codec) {
return DBUtil.decodeSet(_storage.getItem(name), codec);
}
protected void updateVersion (int version) {
set(SYNC_VERS_KEY, _version = version, Codec.INT);
}
protected void noteModified (String name) {
if (_mods.add(name)) queueFlushMods();
}
protected void flushMods () {
sset(SYNC_MODS_KEY, _mods, Codec.STRING);
}
protected void queueFlushMods () {
if (_flushQueued) return;
_flushQueued = true;
_platform.invokeLater(new Runnable() { public void run () {
flushMods();
_flushQueued = false;
}});
}
/** Manages merges and updates to database properties. */
protected interface Property {
boolean merge (String name, String data);
void update (String name, String data);
void prepareToMeld ();
}
/** Returns the key used to store the keys for a map with the specified prefix. */
protected static String mapKeysKey (String mapPrefix) {
return mapPrefix + "_keys";
}
/** Used to encapsulate a collection of properties associated with a particular prefix. For
* example a chess game could create a subdb for each active game using some generated game id
* as a prefix, and when the game was complete, the entire subdb could be removed.
* Additionally, conflict resolution could be adjusted for all elements in a subdb (e.g. using
* the server's values for an entire subdb, or the client's). */
protected abstract class SubDB {
protected SubDB (String prefix) {
_dbpre = prefix;
}
protected <T> Value<T> value (String name, T defval, Codec<T> codec,
Resolver<? super T> resolver) {
return SyncDB.this.value(key(name), defval, codec, resolver);
}
protected <E> RSet<E> set (String name, Codec<E> codec, SetResolver resolver) {
return SyncDB.this.set(key(name), codec, resolver);
}
protected <K,V> RMap<K,V> map (String prefix, Codec<K> keyCodec, Codec<V> valCodec,
Resolver<? super V> resolver) {
return SyncDB.this.map(key(prefix), keyCodec, valCodec, resolver);
}
protected String key (String name) {
return DBUtil.subDBKey(_dbpre, name);
}
/** Removes all of this subdb's properties from the client's persistent storage. Removes
* any pending sync requests for properties of this subdb. Clears the subdb object. */
protected void purge () {
String keyPrefix = DBUtil.subDBKey(_dbpre, "");
for (String key : _storage.keys()) {
if (!key.startsWith(keyPrefix)) continue;
_storage.removeItem(key);
_mods.remove(key);
}
flushMods();
_subdbs.remove(_dbpre);
}
protected String _dbpre;
}
protected final Platform _platform;
protected final Storage _storage;
protected final Map<String,Property> _props = new HashMap<String,Property>();
protected final Map<String,SubDB> _subdbs = new HashMap<String,SubDB>();
protected final Set<String> _mods;
protected int _version;
protected boolean _flushQueued;
protected static final String SYNC_VERS_KEY = "syncv";
protected static final String SYNC_MODS_KEY = "syncm";
protected static final Set<String> SYNC_KEYS = new HashSet<String>(); static {
SYNC_KEYS.add(SYNC_VERS_KEY);
SYNC_KEYS.add(SYNC_MODS_KEY);
}
}
|
package arez;
import arez.spy.SpyEventHandler;
import java.util.ArrayList;
import java.util.function.Consumer;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import static org.testng.Assert.*;
final class TestSpyEventHandler
implements SpyEventHandler
{
private final ArrayList<Object> _events = new ArrayList<>();
/**
* When using assertNextEvent this tracks the index that we are up to.
*/
private int _currentAssertIndex;
@Override
public void onSpyEvent( @Nonnull final Object event )
{
_events.add( event );
}
void assertEventCount( final int count )
{
assertEquals( _events.size(), count, "Actual events: " + _events );
}
/**
* Assert "next" Event is of specific type.
* Increment the next counter.
*/
<T> void assertNextEvent( @Nonnull final Class<T> type )
{
assertEvent( type, null );
}
/**
* Assert "next" Event is of specific type.
* Increment the next counter, run action.
*/
<T> void assertNextEvent( @Nonnull final Class<T> type, @Nonnull final Consumer<T> action )
{
assertEvent( type, action );
}
private <T> void assertEvent( @Nonnull final Class<T> type, @Nullable final Consumer<T> action )
{
assertTrue( _events.size() > _currentAssertIndex );
final Object e = _events.get( _currentAssertIndex );
assertTrue( type.isInstance( e ),
"Expected event at index " + _currentAssertIndex + " to be of type " + type + " but is " +
" of type " + e.getClass() + " with value " + e );
_currentAssertIndex++;
final T event = type.cast( e );
if ( null != action )
{
action.accept( event );
}
}
}
|
/*
* $Id: ParamDoclet.java,v 1.6 2005-06-23 05:26:18 tlipkis Exp $
*/
package org.lockss.doclet;
import org.lockss.util.StringUtil;
import java.util.*;
import java.io.*;
import java.lang.reflect.*;
import com.sun.javadoc.*;
/**
* A JavaDoc doclet that prints configuration parameter information.
*
*/
public class ParamDoclet {
private static PrintStream out = null;
private static boolean closeOut = false;
public static boolean start(RootDoc root) {
handleOptions(root);
if (out == null) {
out = System.out;
}
ClassDoc[] classDocs = root.classes();
HashMap params = new HashMap();
TreeMap sortedParams = new TreeMap();
for (int i = 0; i < classDocs.length; i++) {
ClassDoc classDoc = classDocs[i];
String className = classDoc.qualifiedName();
FieldDoc[] fields = classDoc.fields();
for (int j = 0; j < fields.length; j++) {
FieldDoc field = fields[j];
String name = field.name();
if (isParam(name)) {
String key = getParamKey(classDoc, name);
ParamInfo info = (ParamInfo)params.get(key);
if (info == null) {
info = new ParamInfo();
params.put(key, info);
}
if (name.startsWith("PARAM_")) {
// This is a PARAM, not a DEFAULT
if (info.usedIn.size() == 0) {
// This is the first occurance we've encountered.
Object value = field.constantValue();
if (value instanceof String) {
String paramName = escapeName((String)value);
String comment = field.getRawCommentText();
info.paramName = paramName;
info.comment = comment;
info.usedIn.add(className);
// Add to the sorted map we'll use for printing.
sortedParams.put(paramName, info);
}
} else {
// We've already visited this parameter before, this is
// just another use.
info.usedIn.add(className);
}
} else if (name.startsWith("DEFAULT_")) {
info.defaultValue = getDefaultValue(field, root);
}
}
}
}
printDocHeader();
out.println("<h3>" + sortedParams.size() + " total parameters</h3>");
for (Iterator iter = sortedParams.keySet().iterator(); iter.hasNext(); ) {
String key = (String)iter.next();
ParamInfo info = (ParamInfo)sortedParams.get(key);
printParamInfo(info);
}
printDocFooter();
if (closeOut) {
out.close();
}
return true;
}
// The simplest possible way to escape < and > in param names.
private static String escapeName(String name) {
String returnVal = StringUtil.replaceString(name, "<", "<");
return StringUtil.replaceString(returnVal, ">", ">");
}
private static void printDocHeader() {
out.println("<html>");
out.println("<head>");
out.println(" <title>Parameters</title>");
out.println(" <style type=\"text/css\">");
out.println(" .paramName { font-weight: bold; font-family: sans-serif;");
out.println(" font-size: 14pt; }");
out.println(" .defaultValue { font-family: monospace; font-size: 14pt; }");
out.println(" table { border-collapse: collapse; margin-left: 20px;");
out.println(" margin-right: 20px; padding: 0px; width: auto; }");
out.println(" tr { margin: 0px; padding: 0px; border: 0px; }");
out.println(" td { margin: 0px; padding-left: 6px; padding-right: 6px;");
out.println(" border: 0px; padding-left: 0px; padding-top: 0px; padding-right: 0px;}");
out.println(" td.paramHeader { padding-top: 5px; }");
out.println(" td.comment { }");
out.println(" td.usedIn { font-family: monospace; }");
out.println(" td.header { padding-left: 30px; padding-right: 10px; font-style: italic; text-align: right; }");
out.println(" </style>");
out.println("</head>");
out.println("<body>");
out.println("<div align=\"center\">");
out.println("<h1>LOCKSS Configuration Parameters</h1>");
out.println("<table>");
out.flush();
}
private static void printDocFooter() {
out.println("</table>");
out.println("</div>");
out.println("</body>");
out.println("</html>");
out.flush();
}
private static void printParamInfo(ParamInfo info) {
out.println("<tr>\n <td colspan=\"2\" class=\"paramHeader\">");
out.print(" <span class=\"paramName\">" +
info.paramName.trim() + "</span> ");
out.print("<span class=\"defaultValue\">[");
out.print(info.defaultValue == null ?
"" : info.defaultValue.toString());
out.println("]</span>\n </td>");
out.println("</tr>");
out.println("<tr>");
out.println(" <td class=\"header\" valign=\"top\">Comment:</td>");
out.print(" <td class=\"comment\">");
if (info.comment.trim().length() == 0) {
out.print("");
} else {
out.print(info.comment.trim());
}
out.println("</td>");
out.println("</tr>");
out.println("<tr>");
out.println(" <td class=\"header\" valign=\"top\">Used in:</td>");
out.println(" <td class=\"usedIn\">");
for (Iterator iter = info.usedIn.iterator(); iter.hasNext();) {
out.println( (String)iter.next() + "<br/>");
}
out.println(" </td>");
out.println("</tr>");
// out.println("<tr><td colspan=\"3\"> </td></tr>");
out.flush();
}
/**
* Return true if the specified string is a parameter name.
*/
private static boolean isParam(String s) {
return (s.startsWith("PARAM_") || s.startsWith("DEFAULT_"));
}
/**
* Given a parameter or default name, return the key used to look up
* its info object in the unsorted hashmap.
*/
private static String getParamKey(ClassDoc doc, String s) {
StringBuffer sb = new StringBuffer(doc.qualifiedName() + ".");
if (s.startsWith("DEFAULT_")) {
sb.append(s.replaceFirst("DEFAULT_", ""));
} else if (s.startsWith("PARAM_")) {
sb.append(s.replaceFirst("PARAM_", ""));
} else {
sb.append(s);
}
return sb.toString();
}
/**
* Cheesily use reflection to obtain the default value.
*/
public static String getDefaultValue(FieldDoc field, RootDoc root) {
String defaultVal = null;
try {
ClassDoc classDoc = field.containingClass();
Class c = Class.forName(classDoc.qualifiedName());
Field fld = c.getDeclaredField(field.name());
fld.setAccessible(true);
Class cls = fld.getType();
if (int.class == cls) {
defaultVal = (new Integer(fld.getInt(null))).toString();
} else if (long.class == cls) {
long timeVal = fld.getLong(null);
defaultVal = timeVal + " (" +
StringUtil.timeIntervalToString(timeVal) + ")";
} else if (boolean.class == cls) {
defaultVal = (new Boolean(fld.getBoolean(null))).toString();
} else {
try {
// This will throw NPE if the field isn't static; don't know how
// to get initial value in that case
Object dval = fld.get(null);
defaultVal = (dval != null) ? dval.toString() : "(null)";
} catch (NullPointerException e) {
defaultVal = "(unknown: non-static default)";
}
}
} catch (Exception e) {
root.printError(field.position(), field.name() + ": " + e);
root.printError(StringUtil.stackTraceString(e));
}
return defaultVal;
}
/**
* Required for Doclet options.
*/
public static int optionLength(String option) {
if (option.equals("-o")) {
return 2;
} else if (option.equals("-d")) {
return 2;
}
return 0;
}
public static boolean validOptions(String[][] options,
DocErrorReporter reporter) {
return true;
}
private static boolean handleOptions(RootDoc root) {
String outDir = null;
String[][] options = root.options();
for (int i = 0 ; i < options.length; i++) {
if (options[i][0].equals("-d")) {
outDir = options[i][1];
} else if (options[i][0].equals("-o")) {
String outFile = options[i][1];
try {
File f = null;
if (outDir != null) {
f = new File(outDir, outFile);
} else {
f = new File(outFile);
}
out = new PrintStream(new BufferedOutputStream(new FileOutputStream(f)));
closeOut = true;
return true;
} catch (IOException ex) {
root.printError("Unable to open output file: " + outFile);
}
}
}
return false;
}
/**
* Simple wrapper class to hold information about parameters.
*/
private static class ParamInfo {
public String paramName = "";
public Object defaultValue = null;
public String comment = "";
// Sorted list of uses.
public Set usedIn = new TreeSet();
}
}
|
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.QueueingConsumer;
import convertors.JobConverter;
import datamodel.Command;
import datamodel.Job;
import mongo.MongoManager;
import java.io.IOException;
public class Receiver {
private Channel channel;
private QueueingConsumer consumer;
private final String hostName;
private final String queueName;
private RabbitMqConfig rmqConf = new RabbitMqConfig();
/**
* set parameters for RabbitMQ receiver
*/
public Receiver() {
hostName = rmqConf.getHost();
queueName = rmqConf.getQueue();
ConnectionFactory factory = new ConnectionFactory();
factory.setHost(hostName);
Connection connection = null;
try {
connection = factory.newConnection();
channel = connection.createChannel();
/*
* a client can be assigned only 1 message, the next message will be
* assigned only after it finishes processing the first message
*/
int prefetchCount = 1;
channel.basicQos(prefetchCount);
boolean durable = true;
channel.queueDeclare(queueName, durable, false, false, null);
consumer = new QueueingConsumer(channel);
boolean autoAck = false;
channel.basicConsume(queueName, autoAck, consumer);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Listen for messages
*/
public void startReceiving() {
while (true) {
try {
QueueingConsumer.Delivery delivery = consumer.nextDelivery();
String message = new String(delivery.getBody());
Job job = JobConverter.jsonStringToJob(message);
MongoManager mm = new MongoManager();
mm.pullJsonById(job.getId());
//executeCommand(job.getCommand());
channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
System.out.println("[X] Done");
} catch (InterruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* Start a command with received message
*
* @param command terminal command that will be executed
* @throws InterruptedException
*/
private void executeCommand(String command) throws InterruptedException {
CommandExecutor cmd = new CommandExecutor();
cmd.execute(new Command(command));
}
}
|
package org.xnio;
import java.io.IOException;
import java.util.concurrent.CancellationException;
import java.util.concurrent.TimeUnit;
import static org.xnio.IoFuture.Status.DONE;
/**
* An implementation of {@link IoFuture} that represents an immediately-successful operation.
*
* @param <T> the type of result that this operation produces
*/
public class FinishedIoFuture<T> implements IoFuture<T> {
private final T result;
/**
* Create an instance.
*
* @param result the operation result
*/
public FinishedIoFuture(T result) {
this.result = result;
}
/**
* Cancel the operation. Since this operation is always complete, this is a no-op.
*
* @return this instance
*/
public IoFuture<T> cancel() {
return this;
}
@Override
public Status getStatus() {
return DONE;
}
@Override
public Status await() {
return DONE;
}
@Override
public Status await(final long time, final TimeUnit timeUnit) {
return DONE;
}
@Override
public Status awaitInterruptibly() throws InterruptedException {
return DONE;
}
@Override
public Status awaitInterruptibly(final long time, final TimeUnit timeUnit) throws InterruptedException {
return DONE;
}
@Override
public T get() throws IOException, CancellationException {
return result;
}
@Override
public T getInterruptibly() throws IOException, InterruptedException, CancellationException {
return result;
}
@Override
public IOException getException() throws IllegalStateException {
return null;
}
@Override
public <A> IoFuture<T> addNotifier(final Notifier<? super T, A> notifier, final A attachment) {
notifier.notify(this, attachment);
return this;
}
}
|
package cpw.mods.fml.client;
import java.util.BitSet;
import java.util.HashMap;
import java.util.logging.Level;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.FMLLog;
/**
* @author cpw
*
*/
public class SpriteHelper
{
private static HashMap<String, BitSet> spriteInfo = new HashMap<String, BitSet>();
private static void initMCSpriteMaps() {
BitSet slots =
SpriteHelper.toBitSet(
"0000000000000000" +
"0000000000110000" +
"0000000000100000" +
"0000000001100000" +
"0000000000000000" +
"0000000000000000" +
"0000000000000000" +
"0000000000000000" +
"0000000000000000" +
"0000000000000000" +
"0000000000000000" +
"0000000000011111" +
"0000000000000000" +
"0000000001111100" +
"0000000001111000" +
"0000000000000000");
spriteInfo.put("/terrain.png", slots);
slots = SpriteHelper.toBitSet(
"0000000000000000" +
"0000000000000000" +
"0000000000000000" +
"0000000000000000" +
"0000000000000000" +
"0000000000000000" +
"0000000000000000" +
"0000000000000000" +
"0000000000000000" +
"0111110000000000" +
"0111111010000000" +
"0111111110000000" +
"0111111110001000" +
"1111111111111111" +
"0000011111111111" +
"0000000000000000");
spriteInfo.put("/gui/items.png", slots);
}
/**
* Register a sprite map for ModTextureStatic, to allow for other mods to override
* your sprite page.
*
*
*/
public static void registerSpriteMapForFile(String file, String spriteMap) {
if (spriteInfo.size() == 0) {
initMCSpriteMaps();
}
if (spriteInfo.containsKey(file)) {
FMLLog.log("fml.TextureManager", Level.FINE, "Duplicate attempt to register a sprite file %s for overriding -- ignoring",file);
return;
}
spriteInfo.put(file, toBitSet(spriteMap));
}
public static int getUniqueSpriteIndex(String path)
{
if (!spriteInfo.containsKey("/terrain.png"))
{
initMCSpriteMaps();
}
BitSet slots = spriteInfo.get(path);
if (slots == null)
{
Exception ex = new Exception(String.format("Invalid getUniqueSpriteIndex call for texture: %s", path));
FMLLog.log("fml.TextureManager", Level.SEVERE, ex, "A critical error has been detected with sprite overrides");
FMLCommonHandler.instance().raiseException(ex,"Invalid request to getUniqueSpriteIndex",true);
}
int ret = getFreeSlot(slots);
if (ret == -1)
{
Exception ex = new Exception(String.format("No more sprite indicies left for: %s", path));
FMLLog.log("fml.TextureManager", Level.SEVERE, ex, "There are no sprite indicies left for %s", path);
FMLCommonHandler.instance().raiseException(ex,"No more sprite indicies left", true);
}
return ret;
}
public static BitSet toBitSet(String data)
{
BitSet ret = new BitSet(data.length());
for (int x = 0; x < data.length(); x++)
{
ret.set(x, data.charAt(x) == '1');
}
return ret;
}
public static int getFreeSlot(BitSet slots)
{
int next=slots.nextSetBit(0);
slots.clear(next);
return next;
}
public static int freeSlotCount(String textureToOverride)
{
return spriteInfo.get(textureToOverride).cardinality();
}
}
|
package luajava;
import java.io.BufferedReader;
import java.io.InputStreamReader;
/**
* LuaJava console
* @author Thiago Ponte
*/
public class Console
{
/**
* Creates a console for user interaction
* @param args - names of the lua files to be executed
*/
public static void main(String[] args)
{
try
{
LuaState L = LuaStateFactory.newLuaState();
L.openBasicLibraries();
L.openDebug();
L.openLoadLib();
if (args.length > 0)
{
for (int i = 0; i < args.length; i++)
{
int res = L.doFile(args[i]);
if (res != 0)
{
String str;
if (res == LuaState.LUA_ERRRUN.intValue())
{
str = "Runtime error. ";
}
else if (res == LuaState.LUA_ERRMEM.intValue())
{
str = "Memory allocation error. ";
}
else if (res == LuaState.LUA_ERRERR.intValue())
{
str = "Error while running the error handler function. ";
}
else
{
str = "Lua Error code " + res + ". ";
}
throw new LuaException(str + "Error on file " + args[i]);
}
}
return;
}
System.out.println("API Lua Java - console mode.");
BufferedReader inp =
new BufferedReader(new InputStreamReader(System.in));
String line;
System.out.print("> ");
while ((line = inp.readLine()) != null && !line.equals("exit"))
{
int ret = L.doString(line);
if (ret != 0)
{
String str;
if (ret == LuaState.LUA_ERRRUN.intValue())
{
str = "Runtime error. ";
}
else if (ret == LuaState.LUA_ERRMEM.intValue())
{
str = "Memory allocation error. ";
}
else if (ret == LuaState.LUA_ERRERR.intValue())
{
str = "Error while running the error handler function. ";
}
else
{
str = "Lua Error code " + ret + ". ";
}
System.out.println(str + line);
}
System.out.print("> ");
}
L.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
|
package net.fortuna.ical4j.model;
import java.io.IOException;
import java.io.Serializable;
import java.net.URISyntaxException;
import java.text.ParseException;
import java.util.Iterator;
import net.fortuna.ical4j.model.parameter.Value;
import net.fortuna.ical4j.model.property.DtEnd;
import net.fortuna.ical4j.model.property.DtStart;
import net.fortuna.ical4j.model.property.Duration;
import net.fortuna.ical4j.model.property.ExDate;
import net.fortuna.ical4j.model.property.ExRule;
import net.fortuna.ical4j.model.property.RDate;
import net.fortuna.ical4j.model.property.RRule;
import net.fortuna.ical4j.util.Strings;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
/**
* $Id$ [Apr 5, 2004]
*
* Defines an iCalendar component. Subclasses of this class provide additional validation and typed values for specific
* iCalendar components.
* @author Ben Fortuna
*/
public abstract class Component implements Serializable {
private static final long serialVersionUID = 4943193483665822201L;
public static final String BEGIN = "BEGIN";
public static final String END = "END";
public static final String VEVENT = "VEVENT";
public static final String VTODO = "VTODO";
public static final String VJOURNAL = "VJOURNAL";
public static final String VFREEBUSY = "VFREEBUSY";
public static final String VTIMEZONE = "VTIMEZONE";
public static final String VALARM = "VALARM";
public static final String VAVAILABILITY = "VAVAILABILITY";
public static final String VVENUE = "VVENUE";
public static final String AVAILABLE = "AVAILABLE";
public static final String EXPERIMENTAL_PREFIX = "X-";
private String name;
private PropertyList properties;
/**
* Constructs a new component containing no properties.
* @param s a component name
*/
protected Component(final String s) {
this(s, new PropertyList());
}
/**
* Constructor made protected to enforce the use of <code>ComponentFactory</code> for component instantiation.
* @param s component name
* @param p a list of properties
*/
protected Component(final String s, final PropertyList p) {
this.name = s;
this.properties = p;
}
/**
* @see java.lang.Object#toString()
*/
public String toString() {
final StringBuffer buffer = new StringBuffer();
buffer.append(BEGIN);
buffer.append(':');
buffer.append(getName());
buffer.append(Strings.LINE_SEPARATOR);
buffer.append(getProperties());
buffer.append(END);
buffer.append(':');
buffer.append(getName());
buffer.append(Strings.LINE_SEPARATOR);
return buffer.toString();
}
/**
* @return Returns the name.
*/
public final String getName() {
return name;
}
/**
* @return Returns the properties.
*/
public final PropertyList getProperties() {
return properties;
}
/**
* Convenience method for retrieving a list of named properties.
* @param name name of properties to retrieve
* @return a property list containing only properties with the specified name
*/
public final PropertyList getProperties(final String name) {
return getProperties().getProperties(name);
}
/**
* Convenience method for retrieving a named property.
* @param name name of the property to retrieve
* @return the first matching property in the property list with the specified name
*/
public final Property getProperty(final String name) {
return getProperties().getProperty(name);
}
/**
* Perform validation on a component and its properties.
* @throws ValidationException where the component is not in a valid state
*/
public final void validate() throws ValidationException {
validate(true);
}
/**
* Perform validation on a component.
* @param recurse indicates whether to validate the component's properties
* @throws ValidationException where the component is not in a valid state
*/
public abstract void validate(final boolean recurse)
throws ValidationException;
/**
* Invoke validation on the component properties in its current state.
* @throws ValidationException where any of the component properties is not in a valid state
*/
protected final void validateProperties() throws ValidationException {
for (final Iterator i = getProperties().iterator(); i.hasNext();) {
final Property property = (Property) i.next();
property.validate();
}
}
/**
* Uses {@link EqualsBuilder} to test equality. Two components are equal if and only if their name and property lists
* are equal.
*/
public boolean equals(final Object arg0) {
if (arg0 instanceof Component) {
final Component c = (Component) arg0;
return new EqualsBuilder().append(getName(), c.getName())
.append(getProperties(), c.getProperties()).isEquals();
}
return super.equals(arg0);
}
/**
* Uses {@link HashCodeBuilder} to build hashcode.
*/
public int hashCode() {
return new HashCodeBuilder().append(getName()).append(getProperties())
.toHashCode();
}
/**
* Create a (deep) copy of this component.
* @return the component copy
*/
public Component copy() throws ParseException, IOException,
URISyntaxException {
// Deep copy properties..
final PropertyList newprops = new PropertyList(getProperties());
return ComponentFactory.getInstance().createComponent(getName(),
newprops);
}
/**
* Calculates the recurrence set for this component using the specified period.
* The recurrence set is derived from a combination of the event start date,
* recurrence rules and dates, and exception rules and dates. Note that component
* transparency and anniversary-style dates do not affect the resulting
* intersection.
* @param period
* @return
*/
public final PeriodList calculateRecurrenceSet(final Period period) {
// validate();
final PeriodList recurrenceSet = new PeriodList();
final DtStart start = (DtStart) getProperty(Property.DTSTART);
final DtEnd end = (DtEnd) getProperty(Property.DTEND);
Duration duration = (Duration) getProperty(Property.DURATION);
// if no start date specified return empty list..
if (start == null) {
return recurrenceSet;
}
final Value startValue = (Value) start.getParameter(Parameter.VALUE);
// initialise timezone..
// if (startValue == null || Value.DATE_TIME.equals(startValue)) {
if (start.isUtc()) {
recurrenceSet.setUtc(true);
}
else if (start.getDate() instanceof DateTime) {
recurrenceSet.setTimeZone(((DateTime) start.getDate()).getTimeZone());
}
// if an explicit event duration is not specified, derive a value for recurring
// periods from the end date..
Dur rDuration;
// if no end or duration specified, end date equals start date..
if (end == null && duration == null) {
rDuration = new Dur(start.getDate(), start.getDate());
}
else if (duration == null) {
rDuration = new Dur(start.getDate(), end.getDate());
}
else {
rDuration = duration.getDuration();
}
// add recurrence dates..
for (final Iterator i = getProperties(Property.RDATE).iterator(); i.hasNext();) {
final RDate rdate = (RDate) i.next();
final Value rdateValue = (Value) rdate.getParameter(Parameter.VALUE);
if (Value.PERIOD.equals(rdateValue)) {
for (final Iterator j = rdate.getPeriods().iterator(); j.hasNext();) {
final Period rdatePeriod = (Period) j.next();
if (period.intersects(rdatePeriod)) {
recurrenceSet.add(rdatePeriod);
}
}
}
else if (Value.DATE_TIME.equals(rdateValue)) {
for (final Iterator j = rdate.getDates().iterator(); j.hasNext();) {
final DateTime rdateTime = (DateTime) j.next();
if (period.includes(rdateTime)) {
recurrenceSet.add(new Period(rdateTime, rDuration));
}
}
}
else {
for (final Iterator j = rdate.getDates().iterator(); j.hasNext();) {
final Date rdateDate = (DateTime) j.next();
if (period.includes(rdateDate)) {
recurrenceSet.add(new Period(new DateTime(rdateDate), rDuration));
}
}
}
}
// allow for recurrence rules that start prior to the specified period
// but still intersect with it..
final DateTime startMinusDuration = new DateTime(period.getStart());
startMinusDuration.setTime(rDuration.negate().getTime(
period.getStart()).getTime());
// add recurrence rules..
for (final Iterator i = getProperties(Property.RRULE).iterator(); i.hasNext();) {
final RRule rrule = (RRule) i.next();
final DateList rruleDates = rrule.getRecur().getDates(start.getDate(),
new Period(startMinusDuration, period.getEnd()), startValue);
for (final Iterator j = rruleDates.iterator(); j.hasNext();) {
final Date rruleDate = (Date) j.next();
recurrenceSet.add(new Period(new DateTime(rruleDate), rDuration));
}
}
// add initial instance if intersection with the specified period..
Period startPeriod = null;
if (end != null) {
startPeriod = new Period(new DateTime(start.getDate()),
new DateTime(end.getDate()));
}
else {
/*
* PeS: Anniversary type has no DTEND nor DUR, define DUR
* locally, otherwise we get NPE
*/
if (duration == null) {
duration = new Duration(rDuration);
}
startPeriod = new Period(new DateTime(start.getDate()),
duration.getDuration());
}
if (period.intersects(startPeriod)) {
recurrenceSet.add(startPeriod);
}
// subtract exception dates..
for (final Iterator i = getProperties(Property.EXDATE).iterator(); i.hasNext();) {
final ExDate exdate = (ExDate) i.next();
for (final Iterator j = recurrenceSet.iterator(); j.hasNext();) {
final Period recurrence = (Period) j.next();
// for DATE-TIME instances check for DATE-based exclusions also..
if (exdate.getDates().contains(recurrence.getStart())
|| exdate.getDates().contains(new Date(recurrence.getStart()))) {
j.remove();
}
}
}
// subtract exception rules..
for (final Iterator i = getProperties(Property.EXRULE).iterator(); i.hasNext();) {
final ExRule exrule = (ExRule) i.next();
final DateList exruleDates = exrule.getRecur().getDates(start.getDate(),
period, startValue);
for (final Iterator j = recurrenceSet.iterator(); j.hasNext();) {
final Period recurrence = (Period) j.next();
// for DATE-TIME instances check for DATE-based exclusions also..
if (exruleDates.contains(recurrence.getStart())
|| exruleDates.contains(new Date(recurrence.getStart()))) {
j.remove();
}
}
}
return recurrenceSet;
}
}
|
package net.fortuna.ical4j.model;
import java.io.IOException;
import java.io.Serializable;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import net.fortuna.ical4j.util.Dates;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Represents a timezone offset from UTC time.
*
* @author Ben Fortuna
*/
public class UtcOffset implements Serializable {
private static final long serialVersionUID = 5883111996721531728L;
private static final int HOUR_START_INDEX = 1;
private static final int HOUR_END_INDEX = 3;
private static final int MINUTE_START_INDEX = 3;
private static final int MINUTE_END_INDEX = 5;
private static final int SECOND_START_INDEX = 5;
private static final int SECOND_END_INDEX = 7;
private static final NumberFormat HOUR_FORMAT = new DecimalFormat("00");
private static final NumberFormat MINUTE_FORMAT = new DecimalFormat("00");
private static final NumberFormat SECOND_FORMAT = new DecimalFormat("00");
private transient Log log = LogFactory.getLog(UtcOffset.class);
private long offset;
/**
* @param value
*/
public UtcOffset(final String value) {
// debugging..
if (log.isDebugEnabled()) {
log.debug("Parsing string [" + value + "]");
}
if (value.length() < MINUTE_END_INDEX) {
throw new IllegalArgumentException("Invalid UTC offset [" + value
+ "] - must be of the form: (+/-)HHMM[SS]");
}
boolean negative = value.startsWith("-");
if (!negative && !value.startsWith("+")) {
throw new IllegalArgumentException("UTC offset value must be signed");
}
offset = 0;
offset += Integer.parseInt(value.substring(HOUR_START_INDEX,
HOUR_END_INDEX))
* Dates.MILLIS_PER_HOUR;
offset += Integer.parseInt(value.substring(MINUTE_START_INDEX,
MINUTE_END_INDEX))
* Dates.MILLIS_PER_MINUTE;
try {
offset += Integer.parseInt(value.substring(SECOND_START_INDEX,
SECOND_END_INDEX))
* Dates.MILLIS_PER_SECOND;
}
catch (Exception e) {
// seconds not supplied..
log.debug("Seconds not specified", e);
}
if (negative) {
offset = -offset;
}
}
/**
* @param offset
*/
public UtcOffset(final long offset) {
this.offset = (long) Math.floor(offset / (double) Dates.MILLIS_PER_SECOND) * Dates.MILLIS_PER_SECOND;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
public final String toString() {
StringBuffer b = new StringBuffer();
long remainder = Math.abs(offset);
if (offset < 0) {
b.append('-');
}
else {
b.append('+');
}
b.append(HOUR_FORMAT.format(remainder / Dates.MILLIS_PER_HOUR));
remainder = remainder % Dates.MILLIS_PER_HOUR;
b.append(MINUTE_FORMAT.format(remainder / Dates.MILLIS_PER_MINUTE));
remainder = remainder % Dates.MILLIS_PER_MINUTE;
if (remainder > 0) {
b.append(SECOND_FORMAT.format(remainder / Dates.MILLIS_PER_SECOND));
}
return b.toString();
}
/**
* @return Returns the offset.
*/
public final long getOffset() {
return offset;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
public final boolean equals(final Object arg0) {
if (arg0 instanceof UtcOffset) {
return getOffset() == ((UtcOffset) arg0).getOffset();
}
return super.equals(arg0);
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
public final int hashCode() {
return new HashCodeBuilder().append(getOffset()).toHashCode();
}
/**
* @param stream
* @throws IOException
* @throws ClassNotFoundException
*/
private void readObject(java.io.ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
log = LogFactory.getLog(UtcOffset.class);
}
}
|
package org.jivesoftware.smack;
import org.jivesoftware.smack.packet.RosterPacket;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.util.StringUtils;
import java.util.*;
/**
* A group of roster entries.
*
* @see Roster#getGroup(String)
* @author Matt Tucker
*/
public class RosterGroup {
private String name;
private XMPPConnection connection;
private List entries;
/**
* Creates a new roster group instance.
*
* @param name the name of the group.
* @param connection the connection the group belongs to.
*/
RosterGroup(String name, XMPPConnection connection) {
this.name = name;
this.connection = connection;
entries = new ArrayList();
}
/**
* Returns the name of the group.
*
* @return the name of the group.
*/
public String getName() {
return name;
}
/**
* Sets the name of the group. Changing the group's name is like moving all the group entries
* of the group to a new group specified by the new name. Since this group won't have entries
* it will be removed from the roster. This means that all the references to this object will
* be invalid and will need to be updated to the new group specified by the new name.
*
* @param name the name of the group.
*/
public void setName(String name) {
synchronized (entries) {
for (int i=0; i<entries.size(); i++) {
RosterPacket packet = new RosterPacket();
packet.setType(IQ.Type.SET);
RosterEntry entry = (RosterEntry)entries.get(i);
RosterPacket.Item item = RosterEntry.toRosterItem(entry);
item.removeGroupName(this.name);
item.addGroupName(name);
packet.addRosterItem(item);
connection.sendPacket(packet);
}
}
}
/**
* Returns the number of entries in the group.
*
* @return the number of entries in the group.
*/
public int getEntryCount() {
synchronized (entries) {
return entries.size();
}
}
/**
* Returns an iterator for the entries in the group.
*
* @return an iterator for the entries in the group.
*/
public Iterator getEntries() {
synchronized (entries) {
return Collections.unmodifiableList(new ArrayList(entries)).iterator();
}
}
/**
* Returns the roster entry associated with the given XMPP address or
* <tt>null</tt> if the user is not an entry in the group.
*
* @param user the XMPP address of the user (eg "jsmith@example.com").
* @return the roster entry or <tt>null</tt> if it does not exist in the group.
*/
public RosterEntry getEntry(String user) {
if (user == null) {
return null;
}
// Roster entries never include a resource so remove the resource
// if it's a part of the XMPP address.
user = StringUtils.parseBareAddress(user);
synchronized (entries) {
for (Iterator i=entries.iterator(); i.hasNext(); ) {
RosterEntry entry = (RosterEntry)i.next();
if (entry.getUser().equals(user)) {
return entry;
}
}
}
return null;
}
/**
* Returns true if the specified entry is part of this group.
*
* @param entry a roster entry.
* @return true if the entry is part of this group.
*/
public boolean contains(RosterEntry entry) {
synchronized (entries) {
return entries.contains(entry);
}
}
/**
* Returns true if the specified XMPP address is an entry in this group.
*
* @param user the XMPP address of the user.
* @return true if the XMPP address is an entry in this group.
*/
public boolean contains(String user) {
if (user == null) {
return false;
}
// Roster entries never include a resource so remove the resource
// if it's a part of the XMPP address.
user = StringUtils.parseBareAddress(user);
synchronized (entries) {
for (Iterator i=entries.iterator(); i.hasNext(); ) {
RosterEntry entry = (RosterEntry)i.next();
if (entry.getUser().equals(user)) {
return true;
}
}
}
return false;
}
/**
* Adds a roster entry to this group. If the entry was unfiled then it will be removed from
* the unfiled list and will be added to this group.
*
* @param entry a roster entry.
*/
public void addEntry(RosterEntry entry) {
// Only add the entry if it isn't already in the list.
synchronized (entries) {
if (!entries.contains(entry)) {
entries.add(entry);
RosterPacket packet = new RosterPacket();
packet.setType(IQ.Type.SET);
packet.addRosterItem(RosterEntry.toRosterItem(entry));
connection.sendPacket(packet);
}
}
}
/**
* Removes a roster entry from this group. If the entry does not belong to any other group
* then it will be considered as unfiled, therefore it will be added to the list of unfiled
* entries.
*
* @param entry a roster entry.
*/
public void removeEntry(RosterEntry entry) {
// Only remove the entry if it's in the entry list.
// The actual removal logic takes place in RosterPacketListenerprocess>>Packet(Packet)
synchronized (entries) {
if (entries.contains(entry)) {
RosterPacket packet = new RosterPacket();
packet.setType(IQ.Type.SET);
RosterPacket.Item item = RosterEntry.toRosterItem(entry);
item.removeGroupName(this.getName());
packet.addRosterItem(item);
connection.sendPacket(packet);
}
}
}
void addEntryLocal(RosterEntry entry) {
// Only add the entry if it isn't already in the list.
synchronized (entries) {
entries.remove(entry);
entries.add(entry);
}
}
void removeEntryLocal(RosterEntry entry) {
// Only remove the entry if it's in the entry list.
synchronized (entries) {
if (entries.contains(entry)) {
entries.remove(entry);
}
}
}
}
|
package tinycdxserver;
import org.rocksdb.RocksDB;
import org.rocksdb.RocksIterator;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.function.Predicate;
/**
* Wraps RocksDB with a higher-level query interface.
*/
public class Index {
final RocksDB db;
final Predicate<Capture> filter;
public Index(RocksDB db) {
this(db, null);
}
public Index(RocksDB db, Predicate<Capture> filter) {
this.db = db;
this.filter = filter;
}
/**
* Returns all resources (URLs) that match the given prefix.
*/
public Iterable<Resource> prefixQuery(String urlPrefix) {
return () -> new Resources(filteredCaptures(urlPrefix, record -> record.urlkey.startsWith(urlPrefix)));
}
/**
* Returns all captures for the given url.
*/
public Iterable<Capture> query(String url) {
return () -> filteredCaptures(url, record -> record.urlkey.equals(url));
}
private Iterator<Capture> filteredCaptures(String queryUrl, Predicate<Capture> scope) {
Iterator<Capture> captures = new Captures(db, queryUrl, scope);
if (filter != null) {
captures = new FilteringIterator<>(captures, filter);
}
return captures;
}
/**
* Iterates capture records in RocksDb, starting from queryUrl and continuing until scope returns false.
*/
private static class Captures implements Iterator<Capture> {
private final RocksIterator it;
private final Predicate<Capture> scope;
private Capture capture = null;
private boolean exhausted = false;
@Override
protected void finalize() throws Throwable {
it.dispose();
super.finalize();
}
public Captures(RocksDB db, String queryUrl, Predicate<Capture> scope) {
final RocksIterator it = db.newIterator();
it.seek(Capture.encodeKey(queryUrl, 0));
this.scope = scope;
this.it = it;
}
public boolean hasNext() {
if (exhausted) {
return false;
}
if (capture == null && it.isValid()) {
capture = new Capture(it.key(), it.value());
}
if (capture == null || !scope.test(capture)) {
capture = null;
exhausted = true;
it.dispose();
return false;
}
return true;
}
public Capture next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
Capture capture = this.capture;
this.capture = null;
it.next();
return capture;
}
}
/**
* Groups together all captures of the same URL.
*/
private static class Resources implements Iterator<Resource> {
private final Iterator<Capture> captures;
private Capture capture = null;
Resources(Iterator<Capture> captures) {
this.captures = captures;
}
public boolean hasNext() {
return capture != null || captures.hasNext();
}
public Resource next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
Resource result = new Resource();
String previousDigest = null;
if (capture == null) {
capture = captures.next();
}
result.firstCapture = capture;
result.lastCapture = capture;
while (capture.urlkey.equals(result.firstCapture.urlkey)) {
if (previousDigest == null || !previousDigest.equals(capture.digest)) {
result.versions++;
previousDigest = capture.digest;
}
result.captures++;
result.lastCapture = capture;
if (!captures.hasNext()) {
capture = null;
break;
}
capture = captures.next();
}
return result;
}
}
/**
* Wraps another iterator and only returns elements that match the given predicate.
*/
private static class FilteringIterator<T> implements Iterator<T> {
private final Iterator<T> iterator;
private final Predicate<T> predicate;
private T next;
private boolean holdingNext = false;
public FilteringIterator(Iterator<T> iterator, Predicate<T> predicate) {
this.iterator = iterator;
this.predicate = predicate;
}
@Override
public boolean hasNext() {
while (!holdingNext && iterator.hasNext()) {
T candidate = iterator.next();
if (predicate.test(candidate)) {
next = candidate;
holdingNext = true;
}
}
return holdingNext;
}
@Override
public T next() {
if (hasNext()) {
T result = next;
holdingNext = false;
next = null;
return result;
} else {
throw new NoSuchElementException();
}
}
}
}
|
// This source code implements specifications defined by the Java
// Community Process. In order to remain compliant with the specification
// DO NOT add / change / or delete method signatures!
package javax.mail;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import javax.mail.Flags.Flag;
import javax.mail.event.ConnectionEvent;
import javax.mail.event.ConnectionListener;
import javax.mail.event.FolderEvent;
import javax.mail.event.FolderListener;
import javax.mail.event.MessageChangedEvent;
import javax.mail.event.MessageChangedListener;
import javax.mail.event.MessageCountEvent;
import javax.mail.event.MessageCountListener;
import javax.mail.event.TransportListener;
import javax.mail.search.SearchTerm;
public abstract class Folder {
// Constants from J2SE 1.4 doc (Constant Values)
public static final int HOLDS_FOLDERS = 2;
public static final int HOLDS_MESSAGES = 1;
private static final Message[] MESSAGE_ARRAY = new Message[0];
public static final int READ_ONLY = 1;
public static final int READ_WRITE = 2;
private List _connectionListeners = new LinkedList();
private List _folderListeners = new LinkedList();
private List _messageChangedListeners = new LinkedList();
private List _messageCountListeners = new LinkedList();
private boolean _subscribed;
protected int mode;
protected Store store;
protected Folder(Store store) {
this.store = store;
}
public void addConnectionListener(ConnectionListener listener) {
_connectionListeners.add(listener);
}
public void addFolderListener(FolderListener listener) {
_folderListeners.add(listener);
}
public void addMessageChangedListener(MessageChangedListener listener) {
_messageChangedListeners.add(listener);
}
public void addMessageCountListener(MessageCountListener listener) {
_messageCountListeners.add(listener);
}
public abstract void appendMessages(Message[] messages)
throws MessagingException;
public abstract void close(boolean expunge) throws MessagingException;
public void copyMessages(Message[] messages, Folder folder)
throws MessagingException {
folder.appendMessages(messages);
}
public abstract boolean create(int type) throws MessagingException;
public abstract boolean delete(boolean recurse) throws MessagingException;
public abstract boolean exists() throws MessagingException;
public abstract Message[] expunge() throws MessagingException;
public void fetch(Message[] messages, FetchProfile profile)
throws MessagingException {
// default does not do anything
return;
}
protected void finalize() throws Throwable {
try {
super.finalize();
} finally {
}
}
private int getCount(Flag flag) throws MessagingException {
return getCount(flag, true);
}
private int getCount(Flag flag, boolean value) throws MessagingException {
if (isOpen()) {
Message[] messages = getMessages();
int total = 0;
for (int i = 0; i < messages.length; i++) {
if (messages[i].getFlags().contains(flag) == value) {
total++;
}
}
return total;
} else {
return -1;
}
}
public int getDeletedMessageCount() throws MessagingException {
return getCount(Flags.Flag.DELETED);
}
public abstract Folder getFolder(String name) throws MessagingException;
public abstract String getFullName();
public abstract Message getMessage(int id) throws MessagingException;
public abstract int getMessageCount() throws MessagingException;
public Message[] getMessages() throws MessagingException {
return getMessages(1, getMessageCount());
}
public Message[] getMessages(int from, int to) throws MessagingException {
if (to == -1 || to < from) {
throw new IndexOutOfBoundsException(
"Invalid message range: " + from + " to " + to);
}
Message[] result = new Message[to - from + 1];
for (int i = from; i <= to; i++) {
result[i] = getMessage(i);
}
return result;
}
public Message[] getMessages(int ids[]) throws MessagingException {
Message[] result = new Message[ids.length];
for (int i = 0; i < ids.length; i++) {
result[i] = getMessage(ids[i]);
}
return result;
}
public int getMode() {
return mode;
}
public abstract String getName();
public int getNewMessageCount() throws MessagingException {
return getCount(Flags.Flag.RECENT);
}
public abstract Folder getParent() throws MessagingException;
public abstract Flags getPermanentFlags();
public abstract char getSeparator() throws MessagingException;
public Store getStore() {
return store;
}
public abstract int getType() throws MessagingException;
public int getUnreadMessageCount() throws MessagingException {
return getCount(Flags.Flag.SEEN, false);
}
public URLName getURLName() throws MessagingException {
return store.getURLName();
}
public abstract boolean hasNewMessages() throws MessagingException;
public abstract boolean isOpen();
public boolean isSubscribed() {
return _subscribed;
}
public Folder[] list() throws MessagingException {
return list("%");
}
public abstract Folder[] list(String pattern) throws MessagingException;
public Folder[] listSubscribed() throws MessagingException {
return listSubscribed("%");
}
public Folder[] listSubscribed(String pattern) throws MessagingException {
return list(pattern);
}
protected void notifyConnectionListeners(int type) {
ConnectionEvent event = new ConnectionEvent(this, type);
Iterator it = _connectionListeners.iterator();
while (it.hasNext()) {
TransportListener listener = (TransportListener) it.next();
event.dispatch(listener);
}
}
protected void notifyFolderListeners(int type) {
Iterator it = _folderListeners.iterator();
FolderEvent event = new FolderEvent(this,this,type);
while (it.hasNext()) {
FolderListener listener = (FolderListener) it.next();
event.dispatch(listener);
}
}
protected void notifyFolderRenamedListeners(
Folder newFolder) {
Iterator it = _folderListeners.iterator();
FolderEvent event =
new FolderEvent(this, this, newFolder, FolderEvent.RENAMED);
while (it.hasNext()) {
FolderListener listener = (FolderListener) it.next();
event.dispatch(listener);
}
}
protected void notifyMessageAddedListeners(Message[] messages) {
Iterator it = _messageChangedListeners.iterator();
MessageCountEvent event =
new MessageCountEvent(
this,
MessageCountEvent.ADDED,
false,
messages);
while (it.hasNext()) {
MessageCountEvent listener = (MessageCountEvent) it.next();
event.dispatch(listener);
}
}
protected void notifyMessageChangedListeners(int type, Message message) {
Iterator it = _messageChangedListeners.iterator();
MessageChangedEvent event =
new MessageChangedEvent(this, type, message);
while (it.hasNext()) {
MessageCountEvent listener = (MessageCountEvent) it.next();
event.dispatch(listener);
}
}
protected void notifyMessageRemovedListeners(
boolean removed,
Message[] messages) {
Iterator it = _messageChangedListeners.iterator();
MessageCountEvent event =
new MessageCountEvent(
this,
MessageCountEvent.REMOVED,
removed,
messages);
while (it.hasNext()) {
MessageCountEvent listener = (MessageCountEvent) it.next();
event.dispatch(listener);
}
}
public abstract void open(int mode) throws MessagingException;
public void removeConnectionListener(ConnectionListener listener) {
_connectionListeners.remove(listener);
}
public void removeFolderListener(FolderListener listener) {
_folderListeners.remove(listener);
}
public void removeMessageChangedListener(MessageChangedListener listener) {
_messageChangedListeners.remove(listener);
}
public void removeMessageCountListener(MessageCountListener listener) {
_messageCountListeners.remove(listener);
}
public abstract boolean renameTo(Folder newName) throws MessagingException;
public Message[] search(SearchTerm term) throws MessagingException {
return search(term, getMessages());
}
public Message[] search(SearchTerm term, Message[] messages)
throws MessagingException {
List result = new LinkedList();
for (int i = 0; i < messages.length; i++) {
Message message = messages[i];
if (term.match(message)) {
result.add(message);
}
}
return (Message[]) result.toArray(MESSAGE_ARRAY);
}
public void setFlags(int from, int to, Flags flags, boolean value)
throws MessagingException {
setFlags(getMessages(from, to), flags, value);
}
public void setFlags(int ids[], Flags flags, boolean value)
throws MessagingException {
setFlags(getMessages(ids), flags, value);
}
public void setFlags(Message[] messages, Flags flags, boolean value)
throws MessagingException {
for (int i = 0; i < messages.length; i++) {
Message message = messages[i];
message.setFlags(flags, value);
}
}
public void setSubscribed(boolean subscribed) throws MessagingException {
_subscribed = subscribed;
}
public String toString() {
String name = getFullName();
if (name == null) {
return super.toString();
} else {
return name;
}
}
}
|
package ru.pinkponies.server;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.BufferOverflowException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import ru.pinkponies.protocol.LocationUpdatePacket;
import ru.pinkponies.protocol.LoginPacket;
import ru.pinkponies.protocol.Packet;
import ru.pinkponies.protocol.Protocol;
import ru.pinkponies.protocol.SayPacket;
public final class Server {
private static final int SERVER_PORT = 4264;
private static final int BUFFER_SIZE = 8192;
private ServerSocketChannel serverSocketChannel;
private Selector selector;
private Map<SocketChannel, ByteBuffer> incomingData = new HashMap<SocketChannel, ByteBuffer>();
private Map<SocketChannel, ByteBuffer> outgoingData = new HashMap<SocketChannel, ByteBuffer>();
private Protocol protocol;
private void initialize() {
try {
serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.configureBlocking(false);
InetSocketAddress address = new InetSocketAddress(SERVER_PORT);
serverSocketChannel.socket().bind(address);
selector = Selector.open();
SelectionKey key = serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
System.out.println("serverSocketChannel's registered key is " + key.channel().toString() + ".");
protocol = new Protocol();
} catch (Exception e) {
System.out.println("Exception: " + e.getMessage());
}
}
private void start() throws IOException {
System.out.println("Server is listening on port " + serverSocketChannel.socket().getLocalPort() + ".");
while(true) {
pumpEvents();
}
}
private void pumpEvents() throws IOException {
selector.select();
Set<SelectionKey> selectedKeys = selector.selectedKeys();
Iterator<SelectionKey> iterator = selectedKeys.iterator();
while (iterator.hasNext()) {
SelectionKey key = (SelectionKey) iterator.next();
iterator.remove();
if (!key.isValid()) {
continue;
}
if (key.isAcceptable()) {
accept(key);
} else if (key.isReadable()) {
read(key);
} else if (key.isWritable()) {
write(key);
}
}
}
public void accept(SelectionKey key) throws IOException {
SocketChannel channel = serverSocketChannel.accept();
channel.configureBlocking(false);
channel.register(selector, SelectionKey.OP_READ);
incomingData.put(channel, ByteBuffer.allocate(BUFFER_SIZE));
outgoingData.put(channel, ByteBuffer.allocate(BUFFER_SIZE));
onConnect(channel);
}
public void close(SelectionKey key) throws IOException {
SocketChannel channel = (SocketChannel) key.channel();
incomingData.remove(channel);
outgoingData.remove(channel);
channel.close();
key.cancel();
}
public void read(SelectionKey key) throws IOException {
SocketChannel channel = (SocketChannel) key.channel();
ByteBuffer buffer = incomingData.get(channel);
buffer.limit(buffer.capacity());
int numRead = -1;
try {
numRead = channel.read(buffer);
} catch (IOException e) {
close(key);
return;
}
if (numRead == -1) {
close(key);
return;
}
onMessage(channel, buffer);
}
public void write(SelectionKey key) throws IOException {
SocketChannel channel = (SocketChannel) key.channel();
synchronized (outgoingData) {
ByteBuffer buffer = outgoingData.get(channel);
buffer.flip();
channel.write(buffer);
buffer.compact();
if (buffer.remaining() == 0) {
key.interestOps(SelectionKey.OP_READ);
}
}
}
public void onConnect(SocketChannel channel) {
System.out.println("Client connected from " + channel.socket().getRemoteSocketAddress().toString() + ".");
}
public void onMessage(SocketChannel channel, ByteBuffer buffer) {
System.out.println("Message from " + channel.socket().getRemoteSocketAddress().toString() + ":");
Packet packet = null;
buffer.flip();
try {
packet = protocol.unpack(buffer);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
buffer.compact();
if (packet == null) {
return;
}
if (packet instanceof LoginPacket) {
LoginPacket loginPacket = (LoginPacket) packet;
System.out.println(loginPacket.toString());
} else if (packet instanceof SayPacket) {
SayPacket sayPacket = (SayPacket) packet;
System.out.println(sayPacket.toString());
} else if (packet instanceof LocationUpdatePacket) {
LocationUpdatePacket locUpdate = (LocationUpdatePacket) packet;
System.out.println(locUpdate.toString());
}
}
public void sendMessage(SocketChannel channel, byte[] data) {
synchronized (outgoingData) {
ByteBuffer buffer = outgoingData.get(channel);
try {
buffer.put(data);
} catch(BufferOverflowException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args) {
try {
Server server = new Server();
server.initialize();
server.start();
} catch (Exception e) {
System.out.println("Exception: " + e.getMessage());
}
}
}
|
package com.m2stice.graphics;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.util.LinkedList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import com.m2stice.controller.NavigationViewListener;
import com.m2stice.model.Competence;
import com.m2stice.model.Domaine;
import com.m2stice.model.Ec;
import com.m2stice.model.Evaluation;
import com.m2stice.model.Item;
import com.m2stice.model.SousItem;
public class CompetenceView extends JPanel {
private static final long serialVersionUID = 971L;
private JScrollPane blocInferrieure;
public JPanel bloc = new JPanel();
public JTableNotEditable tableauDomaine = new JTableNotEditable();
public JTableNotEditable tableauCompetence = new JTableNotEditable();
public JTableNotEditable tableauItem = new JTableNotEditable();
public JTableNotEditable tableauEC = new JTableNotEditable();
public JTableNotEditable tableauSousItem = new JTableNotEditable();
public JTableNotEditable tableauEvaluation = new JTableNotEditable();
private Object[][] donneesDomaine;
Object[][] donneesCompetence;
Object[][] donneesItem;
Object[][] donneesEC;
Object[][] donneesSousItem;
Object[][] donneesEvaluation;
ListSelectionModel cellSelectionDomaine = tableauDomaine.getSelectionModel();
ListSelectionModel cellSelectionCompetence = tableauCompetence.getSelectionModel();
ListSelectionModel cellSelectionItem = tableauItem.getSelectionModel();
ListSelectionModel cellSelectionEC = tableauEC.getSelectionModel();
ListSelectionModel cellSelectionSousItem = tableauSousItem.getSelectionModel();
ListSelectionModel cellSelectionEvaluation = tableauEvaluation.getSelectionModel();
private Interface interfaceUtilisateur; //Liaison avec l'interface
public boolean click_competence;
public boolean click_item;
public boolean click_ec;
public boolean click_sous_item;
public boolean click_evaluation;
public void init(){
click_competence=false;
click_item=false;
click_ec=false;
click_sous_item=false;
click_evaluation=false;
this.setLayout(new BorderLayout());
bloc.setLayout(new FlowLayout(FlowLayout.LEADING));
bloc.setBackground(Color.GRAY);
blocInferrieure = new JScrollPane(bloc);
//blocInferrieure.setBackground(Color.WHITE);
this.setOpaque(false);
this.add(blocInferrieure,BorderLayout.CENTER);
}
/**
* Contructeur de la vue
* @param interfaceUtilisateur
*/
public CompetenceView(Interface interfaceUtilisateur){
this.interfaceUtilisateur = interfaceUtilisateur;
init();
}
public void setDomaineJTable(LinkedList<Domaine> ld, NavigationViewListener nvl){
donneesDomaine = new Object[ld.size()][1];
int cpt = 0;
for(Domaine d:ld){
//System.out.println(d.getNom());
donneesDomaine[cpt][0] = d.getNom().toUpperCase();
cpt++;
}
String[] titre = {"Domaines de compétences"};
tableauDomaine = new JTableNotEditable(donneesDomaine,titre);
tableauDomaine.setToolTipText("Tableau des domaines");
cellSelectionDomaine = tableauDomaine.getSelectionModel();
cellSelectionDomaine.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
cellSelectionDomaine.addListSelectionListener(nvl.getDomaineTableListener(tableauDomaine));
//tableauDomaine.setPreferredSize(new Dimension(500,500));
JScrollPane blocTableau = new JScrollPane(tableauDomaine);
blocTableau.setBackground(Color.GRAY);
blocTableau.setPreferredSize(new Dimension(300,15+ld.size()*20));
this.bloc.add(blocTableau);
interfaceUtilisateur.repaint();
click_competence = false;
click_item = false;
click_ec = false;
click_sous_item = false;
click_evaluation = false;
}
public void setCompetenceJTable(LinkedList<Competence> lc, NavigationViewListener nvl){
if(click_evaluation == true)
{
this.bloc.remove(5);
click_evaluation = false;
}
if(click_sous_item == true)
{
this.bloc.remove(4);
click_sous_item = false;
}
if(click_ec == true)
{
this.bloc.remove(3);
click_ec = false;
}
if(click_item == true)
{
this.bloc.remove(2);
click_item = false;
}
if(click_competence == true)
{
this.bloc.remove(1);
}
donneesCompetence = new Object[lc.size()][1];
int cpt = 0;
for(Competence c:lc){
donneesCompetence[cpt][0] = c.getNom().toUpperCase();
cpt++;
}
String[] titre = {"Compétences"};
tableauCompetence = new JTableNotEditable(donneesCompetence,titre);
cellSelectionCompetence = tableauCompetence.getSelectionModel();
cellSelectionCompetence.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
cellSelectionCompetence.addListSelectionListener(nvl.getCompetenceTableListener(tableauCompetence));
//tableauCompetence.setPreferredSize(new Dimension(50,1000));
click_competence = true;
JScrollPane blocTableau = new JScrollPane(tableauCompetence);
blocTableau.setBackground(Color.GRAY);
blocTableau.setPreferredSize(new Dimension(300,20+lc.size()*18));
this.bloc.add(blocTableau);
interfaceUtilisateur.repaint();
}
public void setItemJTable(LinkedList<Item> li,NavigationViewListener nvl){
if(click_evaluation == true)
{
this.bloc.remove(5);
click_evaluation = false;
}
if(click_sous_item == true)
{
this.bloc.remove(4);
click_sous_item = false;
}
if(click_ec == true)
{
this.bloc.remove(3);
click_ec = false;
}
if(click_item == true)
{
this.bloc.remove(2);
}
donneesItem = new Object[li.size()][1];
int cpt = 0;
for(Item i:li){
donneesItem[cpt][0] = i.getNom().toUpperCase();
cpt++;
}
String[] titre = {"Items"};
tableauItem = new JTableNotEditable(donneesItem,titre);
cellSelectionItem = tableauItem.getSelectionModel();
cellSelectionItem.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
cellSelectionItem.addListSelectionListener(nvl.getItemTableListener(tableauItem));
//tableauItem.setPreferredSize(new Dimension(50,1000));
JScrollPane blocTableau = new JScrollPane(tableauItem);
blocTableau.setBackground(Color.GRAY);
blocTableau.setPreferredSize(new Dimension(300,20+li.size()*18));
this.bloc.add(blocTableau);
click_item = true;
interfaceUtilisateur.repaint();
}
public void setEcJTable(LinkedList<Ec> lec,NavigationViewListener nvl){
if(click_evaluation == true)
{
this.bloc.remove(5);
click_evaluation = false;
}
if(click_sous_item == true)
{
this.bloc.remove(4);
click_sous_item = false;
}
if(click_ec == true)
{
this.bloc.remove(3);
click_ec = false;
}
donneesEC = new Object[lec.size()][1];
int cpt = 0;
for(Ec ec:lec){
donneesEC[cpt][0] = ec.getNom().toUpperCase();
cpt++;
}
String[] titre = {"EC"};
tableauEC = new JTableNotEditable(donneesEC,titre);
cellSelectionEC = tableauEC.getSelectionModel();
cellSelectionEC.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
cellSelectionEC.addListSelectionListener(nvl.getECTableListener(tableauEC));
//tableauEC.setPreferredSize(new Dimension(50,1000));
JScrollPane blocTableau = new JScrollPane(tableauEC);
blocTableau.setBackground(Color.GRAY);
blocTableau.setPreferredSize(new Dimension(300,20+lec.size()*18));
this.bloc.add(blocTableau);
click_ec = true;
interfaceUtilisateur.repaint();
}
public void setSousItemJTable(LinkedList<SousItem> lsi,NavigationViewListener nvl){
if(click_evaluation == true)
{
this.bloc.remove(5);
click_evaluation = false;
}
if(click_sous_item == true)
{
this.bloc.remove(4);
}
donneesSousItem = new Object[lsi.size()][1];
int cpt = 0;
for(SousItem si:lsi){
//System.out.println(d.getNom());
donneesSousItem[cpt][0] = si.getNom().toUpperCase();
cpt++;
}
String[] titre = {"SousItem"};
tableauSousItem = new JTableNotEditable(donneesSousItem,titre);
cellSelectionSousItem = tableauSousItem.getSelectionModel();
cellSelectionSousItem.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
cellSelectionSousItem.addListSelectionListener(nvl.getSousItemTableListener(tableauSousItem));
//tableauSousItem.setPreferredSize(new Dimension(50,1000));
JScrollPane blocTableau = new JScrollPane(tableauSousItem);
blocTableau.setBackground(Color.GRAY);
blocTableau.setPreferredSize(new Dimension(300,20+lsi.size()*18));
this.bloc.add(blocTableau);
click_sous_item=true;
interfaceUtilisateur.repaint();
}
public void setEvaluationJTable(LinkedList<Evaluation> le,NavigationViewListener nvl){
if(click_evaluation == true)
{
this.bloc.remove(5);
}
donneesEvaluation = new Object[le.size()][1];
int cpt = 0;
for(Evaluation e:le){
//System.out.println(d.getNom());
donneesEvaluation[cpt][0] = e.getNom().toUpperCase();
cpt++;
}
String[] titre = {"Evaluations"};
tableauEvaluation = new JTableNotEditable(donneesEvaluation,titre);
cellSelectionEvaluation = tableauEvaluation.getSelectionModel();
cellSelectionEvaluation.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
cellSelectionEvaluation.addListSelectionListener(nvl.getEvaluationTableListener(tableauEvaluation));
//tableauEvaluation.setPreferredSize(new Dimension(50,1000));
JScrollPane blocTableau = new JScrollPane(tableauEvaluation);
blocTableau.setBackground(Color.GRAY);
blocTableau.setPreferredSize(new Dimension(300,20+le.size()*18));
this.bloc.add(blocTableau);
click_evaluation = true;
interfaceUtilisateur.repaint();
}
}
|
package net.acuttone.reddimg.core;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Comparator;
import java.util.TreeSet;
import net.acuttone.reddimg.prefs.PrefsActivity;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.os.StatFs;
import android.util.Log;
public class ImageCache {
private static final String NET_ACUTTONE_REDDIMG = "net.acuttone.reddimg";
private static final long MIN_FREE_SPACE = 5 * ReddimgApp.MEGABYTE;
private static final String FILE_PREFIX = "__RDIMG_";
private File reddimgDir;
private TreeSet<File> diskCacheFiles;
public ImageCache(Context context) {
initDiskCache(context);
}
private void initDiskCache(Context context) {
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
reddimgDir = new File(Environment.getExternalStorageDirectory() + File.separator + NET_ACUTTONE_REDDIMG);
if(reddimgDir.exists() == false) {
reddimgDir.mkdir();
}
} else {
reddimgDir = context.getCacheDir();
}
diskCacheFiles = new TreeSet<File>(new Comparator<File>() {
@Override
public int compare(File f1, File f2) {
return (int) (f1.lastModified() - f2.lastModified());
}
});
File[] listFiles = reddimgDir.listFiles();
for (File f : listFiles) {
if(f.isFile() && f.getName().startsWith(FILE_PREFIX)) {
diskCacheFiles.add(f);
}
}
Log.d(ReddimgApp.APP_NAME, "Cache dir : " + reddimgDir.getAbsolutePath());
}
public Bitmap getImage(String url) {
Log.d(ReddimgApp.APP_NAME, "Preparing " + url);
Bitmap result = getFromDisk(url);
if (result != null) {
Log.d(ReddimgApp.APP_NAME, url + " found on disk cache");
return result;
}
result = getFromWeb(url);
if(result != null) {
Log.d(ReddimgApp.APP_NAME, url + " dl from web");
return result;
}
Log.w(ReddimgApp.APP_NAME, url + " could not be dl from web");
return null;
}
private Bitmap getFromDisk(String url) {
Bitmap result = null;
File img = new File(getImageDiskPath(url));
if (img.exists()) {
try {
FileInputStream is = new FileInputStream(img);
// TODO: add downsampling for large imgs
try {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 1;
result = BitmapFactory.decodeStream(is, null, options);
} catch(OutOfMemoryError err) {
Log.w(ReddimgApp.APP_NAME, "ERROR WHILE DECODING " + url + " " + img.length() + " : " + err.toString());
}
is.close();
} catch (FileNotFoundException e) {
Log.e(ReddimgApp.APP_NAME, e.toString());
} catch (IOException e) {
Log.e(ReddimgApp.APP_NAME, e.toString());
}
}
return result;
}
private Bitmap getFromWeb(String url) {
HttpURLConnection connection = null;
InputStream is = null;
OutputStream out = null;
try {
connection = (HttpURLConnection) new URL(url).openConnection();
connection.setConnectTimeout(5000);
int contentLength = connection.getContentLength();
boolean enoughSpace = false;
synchronized (diskCacheFiles) {
enoughSpace = checkDiskCacheSize(contentLength);
}
if (!enoughSpace) {
Log.w(ReddimgApp.APP_NAME, "Insufficient space on disk to store " + url);
} else {
File img = new File(getImageDiskPath(url));
is = connection.getInputStream();
out = new FileOutputStream(img);
byte buf[] = new byte[1024];
int len;
while ((len = is.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.close();
is.close();
synchronized (diskCacheFiles) {
diskCacheFiles.add(img);
}
return getFromDisk(url);
}
} catch (MalformedURLException e) {
Log.e(ReddimgApp.APP_NAME, e.toString());
} catch (IOException e) {
Log.e(ReddimgApp.APP_NAME, e.toString());
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (is != null) {
is.close();
}
} catch (IOException e) {
Log.e(ReddimgApp.APP_NAME, e.toString());
}
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
Log.e(ReddimgApp.APP_NAME, e.toString());
}
}
return null;
}
private boolean checkDiskCacheSize(long contentLength) {
long totSize = contentLength;
long cacheSize = getMaxCacheSize();
synchronized (diskCacheFiles) {
for (File f : diskCacheFiles) {
totSize += f.length();
}
while (totSize > cacheSize && diskCacheFiles.size() > 0) {
File oldest = diskCacheFiles.first();
diskCacheFiles.remove(oldest);
totSize -= oldest.length();
if (oldest.exists()
&& oldest.getAbsolutePath().contains(NET_ACUTTONE_REDDIMG)
&& oldest.isFile()
&& oldest.getName().startsWith(FILE_PREFIX)) {
Log.d(ReddimgApp.APP_NAME, "Deleting from disk " + oldest.getName());
oldest.delete();
}
}
}
StatFs stat = new StatFs(reddimgDir.getPath());
double freeSpace = (double) stat.getAvailableBlocks() * (double) stat.getBlockSize();
return totSize < cacheSize && freeSpace > MIN_FREE_SPACE;
}
public double getCurrentCacheSize() {
double totSize = 0;
for(File f : diskCacheFiles) {
totSize += f.length();
}
return totSize / ReddimgApp.MEGABYTE;
}
private long getMaxCacheSize() {
SharedPreferences sp = ReddimgApp.instance().getPrefs();
int size = Integer.parseInt(sp.getString(PrefsActivity.CACHE_SIZE_KEY, PrefsActivity.DEFAULT_CACHE_SIZE));
return size * ReddimgApp.MEGABYTE;
}
public void clearCache() {
// little innocent hack to make checkDiskCacheSize delete all the cached files
checkDiskCacheSize(Long.MAX_VALUE / 2);
}
public String getImageDiskPath(String url) {
url = FILE_PREFIX + url;
if(url.length() > 256) {
url = url.substring(url.length() - 256);
}
url = url.replaceAll("\\W+", "_");
return reddimgDir.getAbsolutePath() + "/" + url;
}
}
|
package de.naoth.rc.dialogs;
import com.google.protobuf.InvalidProtocolBufferException;
import de.naoth.rc.core.dialog.AbstractDialog;
import de.naoth.rc.core.dialog.DialogPlugin;
import de.naoth.rc.RobotControl;
import de.naoth.rc.components.PNGExportFileType;
import de.naoth.rc.components.PlainPDFExportFileType;
import de.naoth.rc.core.dialog.RCDialog;
import de.naoth.rc.drawings.Drawable;
import de.naoth.rc.drawings.DrawingCollection;
import de.naoth.rc.drawings.DrawingOnField;
import de.naoth.rc.drawings.DrawingsContainer;
import de.naoth.rc.drawings.FieldDrawingS3D2011;
import de.naoth.rc.drawings.FieldDrawingSPL2012;
import de.naoth.rc.drawings.FieldDrawingSPL2013;
import de.naoth.rc.drawings.FieldDrawingNaoTHLabor;
import de.naoth.rc.drawings.FieldDrawingSPL2013BlackWhite;
import de.naoth.rc.drawings.LocalFieldDrawing;
import de.naoth.rc.drawings.RadarDrawing;
import de.naoth.rc.drawings.StrokePlot;
import de.naoth.rc.drawingmanager.DrawingEventManager;
import de.naoth.rc.manager.DebugDrawingManager;
import de.naoth.rc.manager.ImageManagerBottom;
import de.naoth.rc.core.manager.ObjectListener;
import de.naoth.rc.dataformats.SPLMessage;
import de.naoth.rc.drawings.Circle;
import de.naoth.rc.drawings.FieldDrawingSPL2020;
import de.naoth.rc.drawings.FieldDrawingSPL3x4;
import de.naoth.rc.drawings.FieldDrawingSPLAspen;
import de.naoth.rc.drawings.FillOval;
import de.naoth.rc.drawings.Line;
import de.naoth.rc.drawings.Pen;
import de.naoth.rc.drawings.Robot;
import de.naoth.rc.logmanager.BlackBoard;
import de.naoth.rc.logmanager.LogDataFrame;
import de.naoth.rc.logmanager.LogFileEventManager;
import de.naoth.rc.logmanager.LogFrameListener;
import de.naoth.rc.manager.DebugDrawingManagerMotion;
import de.naoth.rc.manager.PlotDataManager;
import de.naoth.rc.math.Matrix3D;
import de.naoth.rc.math.Pose2D;
import de.naoth.rc.math.Pose3D;
import de.naoth.rc.math.Vector2D;
import de.naoth.rc.math.Vector3D;
import de.naoth.rc.core.messages.CommonTypes;
import de.naoth.rc.core.messages.CommonTypes.DoubleVector3;
import de.naoth.rc.core.messages.CommonTypes.IntVector2;
import de.naoth.rc.core.messages.CommonTypes.LineSegment;
import de.naoth.rc.core.messages.FrameworkRepresentations.RobotInfo;
import de.naoth.rc.core.messages.Messages.PlotItem;
import de.naoth.rc.core.messages.Messages.Plots;
import de.naoth.rc.core.messages.Representations;
import de.naoth.rc.core.messages.Representations.MultiBallPercept;
import de.naoth.rc.core.messages.Representations.RansacCirclePercept2018;
import de.naoth.rc.core.messages.Representations.RansacLinePercept;
import de.naoth.rc.core.messages.Representations.ShortLinePercept;
import de.naoth.rc.core.messages.RobotPoseOuterClass.RobotPose;
import de.naoth.rc.core.messages.TeamMessageOuterClass;
import de.naoth.rc.core.messages.TeamMessageOuterClass.TeamMessage;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Point2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.SwingUtilities;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
import net.xeoh.plugins.base.annotations.PluginImplementation;
import net.xeoh.plugins.base.annotations.injections.InjectPlugin;
import org.freehep.graphicsio.emf.EMFExportFileType;
import org.freehep.graphicsio.java.JAVAExportFileType;
import org.freehep.graphicsio.ps.EPSExportFileType;
import org.freehep.graphicsio.svg.SVGExportFileType;
import org.freehep.util.export.ExportDialog;
/**
*
* @author Heinrich Mellmann
*/
public class FieldViewer extends AbstractDialog
{
@RCDialog(category = RCDialog.Category.View, name = "Field")
@PluginImplementation
public static class Plugin extends DialogPlugin<FieldViewer> {
@InjectPlugin
public static RobotControl parent;
@InjectPlugin
public static DebugDrawingManager debugDrawingManager;
@InjectPlugin
public static DebugDrawingManagerMotion debugDrawingManagerMotion;
@InjectPlugin
public static PlotDataManager plotDataManager;
@InjectPlugin
public static ImageManagerBottom imageManager;
@InjectPlugin
public static DrawingEventManager drawingEventManager;
@InjectPlugin
public static LogFileEventManager logFileEventManager;
}//end Plugin
// drawing buffer for concurrent access; every "source" gets its own "buffer"
private final MultiSourceDrawingCollection drawings = new MultiSourceDrawingCollection();
private final PlotDataListener plotDataListener;
private final StrokePlot strokePlot;
private final LogFrameListener logFrameListener;
// create new classes, so the received drawings are stored into different buffers
private class DrawingsListenerMotion extends DrawingsListener{}
private class DrawingsListenerCognition extends DrawingsListener{}
private final DrawingsListenerMotion drawingsListenerMotion = new DrawingsListenerMotion();
private final DrawingsListenerCognition drawingsListenerCognition = new DrawingsListenerCognition();
// this is ued as an exportbuffer when the field issaved as image
private BufferedImage exportBuffer = null;
// TODO: this is a hack
private static de.naoth.rc.components.DynamicCanvasPanel canvasExport = null;
public static de.naoth.rc.components.DynamicCanvasPanel getCanvas() {
return canvasExport;
}
public FieldViewer()
{
initComponents();
this.cbBackground.setModel(
new javax.swing.DefaultComboBoxModel(
new Drawable[]
{
new FieldDrawingSPL2020(),
new FieldDrawingSPL2013(),
new FieldDrawingSPL2012(),
new FieldDrawingS3D2011(),
new FieldDrawingNaoTHLabor(),
new FieldDrawingSPLAspen(),
new FieldDrawingSPL3x4(),
new LocalFieldDrawing(),
new RadarDrawing(),
new FieldDrawingSPL2013BlackWhite()
}
));
this.plotDataListener = new PlotDataListener();
this.logFrameListener = new LogFrameDrawer();
this.fieldCanvas.setBackgroundDrawing((Drawable)this.cbBackground.getSelectedItem());
this.fieldCanvas.setToolTipText("");
this.fieldCanvas.setFitToViewport(this.btFitToView.isSelected());
this.fieldCanvas.addDrawing(drawings);
canvasExport = this.fieldCanvas;
Plugin.drawingEventManager.addListener((Drawable drawing, Object src) -> {
// add drawing of the source to the drawing buffer
drawings.add(src.getClass(), drawing);
});
// intialize the field
resetView();
this.fieldCanvas.setAntializing(btAntializing.isSelected());
this.fieldCanvas.repaint();
this.fieldCanvas.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2 && !e.isConsumed()) {
e.consume();
fieldCanvas.fitToViewport();
}
}
});
this.strokePlot = new StrokePlot(300);
// schedules canvas drawing at a fixed rate, should prevent "flickering"
//this.drawingTimer = new Timer(300, this);
//this.drawingTimer.start();
// remember the location of the mouse
jPopupMenu.addPopupMenuListener(new PopupMenuListener() {
@Override
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
Point2D.Double p = convertToFieldCoordinates(fieldCanvas.getMousePosition());
jMenuItemCopyCoords.setToolTipText(String.format("%.1f; %.1f", p.x, p.y));
}
@Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {}
@Override
public void popupMenuCanceled(PopupMenuEvent e) {}
});
// middle click with the mouse on the field copies the field coordinates to the clipboard
fieldCanvas.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
if(e.getButton() == MouseEvent.BUTTON2) {
// "save" Coordinates to clipboard
Point2D.Double p = convertToFieldCoordinates(e.getPoint());
StringSelection ss = new StringSelection(String.format("%.1f; %.1f", p.x, p.y));
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, ss);
}
}
});
}
/**
* Convertes the given relative point of the field to "real" field coordinates.
*
* @param p the relative ui point
* @return "real" field coordinates.
*/
private Point2D.Double convertToFieldCoordinates(Point p) {
Point.Double o = new Point.Double(p.getX(), p.getY());
Point2D.Double r = fieldCanvas.canvasCoordinatesToInternal(o);
return r;
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPopupMenu = new javax.swing.JPopupMenu();
jMenuItemExport = new javax.swing.JMenuItem();
jMenuItemCopyCoords = new javax.swing.JMenuItem();
coordsPopup = new javax.swing.JDialog();
jToolBar1 = new javax.swing.JToolBar();
btReceiveDrawings = new javax.swing.JToggleButton();
btLog = new javax.swing.JToggleButton();
btClean = new javax.swing.JButton();
cbBackground = new javax.swing.JComboBox();
btRotate = new javax.swing.JButton();
btFitToView = new javax.swing.JToggleButton();
btAntializing = new javax.swing.JCheckBox();
btCollectDrawings = new javax.swing.JCheckBox();
cbExportOnDrawing = new javax.swing.JCheckBox();
btTrace = new javax.swing.JCheckBox();
jSlider1 = new javax.swing.JSlider();
drawingPanel = new javax.swing.JPanel();
fieldCanvas = new de.naoth.rc.components.DynamicCanvasPanel();
jMenuItemExport.setText("Export");
jMenuItemExport.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItemExportActionPerformed(evt);
}
});
jPopupMenu.add(jMenuItemExport);
jMenuItemCopyCoords.setText("Copy Coordinates");
jMenuItemCopyCoords.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItemCopyCoordsActionPerformed(evt);
}
});
jPopupMenu.add(jMenuItemCopyCoords);
javax.swing.GroupLayout coordsPopupLayout = new javax.swing.GroupLayout(coordsPopup.getContentPane());
coordsPopup.getContentPane().setLayout(coordsPopupLayout);
coordsPopupLayout.setHorizontalGroup(
coordsPopupLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 114, Short.MAX_VALUE)
);
coordsPopupLayout.setVerticalGroup(
coordsPopupLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 38, Short.MAX_VALUE)
);
jToolBar1.setFloatable(false);
jToolBar1.setRollover(true);
btReceiveDrawings.setText("Receive");
btReceiveDrawings.setFocusable(false);
btReceiveDrawings.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
btReceiveDrawings.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
btReceiveDrawings.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btReceiveDrawingsActionPerformed(evt);
}
});
jToolBar1.add(btReceiveDrawings);
btLog.setText("Log");
btLog.setFocusable(false);
btLog.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
btLog.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
btLog.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btLogActionPerformed(evt);
}
});
jToolBar1.add(btLog);
btClean.setText("Clean");
btClean.setFocusable(false);
btClean.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
btClean.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
btClean.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btCleanActionPerformed(evt);
}
});
jToolBar1.add(btClean);
cbBackground.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "SPL2013", "SPL2012", "S3D2011", "RADAR", "LOCAL" }));
cbBackground.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cbBackgroundActionPerformed(evt);
}
});
jToolBar1.add(cbBackground);
btRotate.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/naoth/rc/res/rotate_ccw.png"))); // NOI18N
btRotate.setToolTipText("Rotate the coordinates by 90°");
btRotate.setFocusable(false);
btRotate.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
btRotate.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
btRotate.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btRotateActionPerformed(evt);
}
});
jToolBar1.add(btRotate);
btFitToView.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/freehep/swing/images/0_MoveCursor.gif"))); // NOI18N
btFitToView.setSelected(true);
btFitToView.setToolTipText("auto-zoom canvas on resizing and rotation");
btFitToView.setFocusable(false);
btFitToView.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
btFitToView.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
btFitToView.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btFitToViewActionPerformed(evt);
}
});
jToolBar1.add(btFitToView);
btAntializing.setText("Antialiazing");
btAntializing.setFocusable(false);
btAntializing.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
btAntializing.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
btAntializing.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btAntializingActionPerformed(evt);
}
});
jToolBar1.add(btAntializing);
btCollectDrawings.setText("Collect");
btCollectDrawings.setFocusable(false);
btCollectDrawings.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
btCollectDrawings.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
btCollectDrawings.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btCollectDrawingsActionPerformed(evt);
}
});
jToolBar1.add(btCollectDrawings);
cbExportOnDrawing.setText("ExportOnDrawing");
cbExportOnDrawing.setFocusable(false);
jToolBar1.add(cbExportOnDrawing);
btTrace.setText("Trace");
btTrace.setFocusable(false);
btTrace.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
btTrace.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
jToolBar1.add(btTrace);
jSlider1.setMaximum(255);
jSlider1.setValue(247);
jSlider1.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
jSlider1StateChanged(evt);
}
});
jToolBar1.add(jSlider1);
drawingPanel.setBackground(new java.awt.Color(247, 247, 247));
drawingPanel.setLayout(new java.awt.BorderLayout());
fieldCanvas.setBackground(new java.awt.Color(247, 247, 247));
fieldCanvas.setComponentPopupMenu(jPopupMenu);
fieldCanvas.setOffsetX(350.0);
fieldCanvas.setOffsetY(200.0);
fieldCanvas.setScale(0.07);
javax.swing.GroupLayout fieldCanvasLayout = new javax.swing.GroupLayout(fieldCanvas);
fieldCanvas.setLayout(fieldCanvasLayout);
fieldCanvasLayout.setHorizontalGroup(
fieldCanvasLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 674, Short.MAX_VALUE)
);
fieldCanvasLayout.setVerticalGroup(
fieldCanvasLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 363, Short.MAX_VALUE)
);
drawingPanel.add(fieldCanvas, java.awt.BorderLayout.CENTER);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(drawingPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0)
.addComponent(drawingPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
}// </editor-fold>//GEN-END:initComponents
private void btReceiveDrawingsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btReceiveDrawingsActionPerformed
if(btReceiveDrawings.isSelected())
{
if(Plugin.parent.checkConnected())
{
Plugin.debugDrawingManager.addListener(drawingsListenerCognition);
Plugin.debugDrawingManagerMotion.addListener(drawingsListenerMotion);
Plugin.plotDataManager.addListener(plotDataListener);
}
else
{
btReceiveDrawings.setSelected(false);
}
}
else
{
Plugin.debugDrawingManager.removeListener(drawingsListenerCognition);
Plugin.debugDrawingManagerMotion.removeListener(drawingsListenerMotion);
Plugin.plotDataManager.removeListener(plotDataListener);
}
}//GEN-LAST:event_btReceiveDrawingsActionPerformed
private void jMenuItemExportActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemExportActionPerformed
ExportDialog export = new ExportDialog("FieldViewer", false);
// add the image types for export
export.addExportFileType(new SVGExportFileType());
export.addExportFileType(new PlainPDFExportFileType());
export.addExportFileType(new EPSExportFileType());
export.addExportFileType(new EMFExportFileType());
export.addExportFileType(new JAVAExportFileType());
export.addExportFileType(new PNGExportFileType());
export.showExportDialog(this, "Export view as ...", this.fieldCanvas, "export");
}//GEN-LAST:event_jMenuItemExportActionPerformed
private void btAntializingActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btAntializingActionPerformed
this.fieldCanvas.setAntializing(btAntializing.isSelected());
this.fieldCanvas.repaint();
}//GEN-LAST:event_btAntializingActionPerformed
private void btCollectDrawingsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btCollectDrawingsActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_btCollectDrawingsActionPerformed
private void jSlider1StateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_jSlider1StateChanged
int v = this.jSlider1.getValue();
this.fieldCanvas.setBackground(new Color(v,v,v));
this.drawingPanel.repaint();
}//GEN-LAST:event_jSlider1StateChanged
private void btCleanActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btCleanActionPerformed
this.strokePlot.clear();
resetView();
this.fieldCanvas.repaint();
}//GEN-LAST:event_btCleanActionPerformed
private void cbBackgroundActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_cbBackgroundActionPerformed
{//GEN-HEADEREND:event_cbBackgroundActionPerformed
this.fieldCanvas.setBackgroundDrawing((Drawable)this.cbBackground.getSelectedItem());
this.fieldCanvas.repaint();
// TODO: should this be inside the DynamicCanvasPanel?
if(this.fieldCanvas.isFitToViewport()) {
this.fieldCanvas.fitToViewport();
}
}//GEN-LAST:event_cbBackgroundActionPerformed
private void btRotateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btRotateActionPerformed
this.fieldCanvas.setRotation(this.fieldCanvas.getRotation() + Math.PI*0.5);
// TODO: should this be inside the DynamicCanvasPanel?
if(this.fieldCanvas.isFitToViewport()) {
this.fieldCanvas.fitToViewport();
}
this.fieldCanvas.repaint();
}//GEN-LAST:event_btRotateActionPerformed
private void btFitToViewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btFitToViewActionPerformed
fieldCanvas.setFitToViewport(this.btFitToView.isSelected());
}//GEN-LAST:event_btFitToViewActionPerformed
private void btLogActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btLogActionPerformed
if(btLog.isSelected())
{
Plugin.logFileEventManager.addListener(logFrameListener);
}
else
{
Plugin.logFileEventManager.removeListener(logFrameListener);
}
}//GEN-LAST:event_btLogActionPerformed
private void jMenuItemCopyCoordsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemCopyCoordsActionPerformed
// "save" Coordinates to clipboard
StringSelection ss = new StringSelection(jMenuItemCopyCoords.getToolTipText());
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, ss);
}//GEN-LAST:event_jMenuItemCopyCoordsActionPerformed
final void resetView()
{
this.fieldCanvas.getDrawingList().clear();
this.drawings.clear();
this.fieldCanvas.addDrawing(drawings);
if(btTrace.isSelected()) {
this.fieldCanvas.getDrawingList().add(this.strokePlot);
}
}//end resetView
private void exportCanvasToPNG() {
long l = java.lang.System.currentTimeMillis();
File file = new File("./fieldViewerExport-"+l+".png");
if(exportBuffer == null || exportBuffer.getWidth() != this.fieldCanvas.getWidth() || exportBuffer.getHeight() != this.fieldCanvas.getHeight()) {
exportBuffer = new BufferedImage(this.fieldCanvas.getWidth(), this.fieldCanvas.getHeight(), BufferedImage.TYPE_INT_ARGB);
}
Graphics2D g2d = exportBuffer.createGraphics();
this.fieldCanvas.paintAll(g2d);
try {
ImageIO.write(exportBuffer, "PNG", file);
} catch(IOException ex) {
ex.printStackTrace(System.err);
}
}
private class DrawingsListener implements ObjectListener<DrawingsContainer>
{
@Override
public void newObjectReceived(DrawingsContainer objectList)
{
if(objectList != null)
{
DrawingCollection drawingCollection = objectList.get(DrawingOnField.class);
if(drawingCollection == null || drawingCollection.isEmpty()) {
return;
}
// add received drawings to buffer
drawings.add(this.getClass(), drawingCollection);
if(cbExportOnDrawing.isSelected()) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
exportCanvasToPNG();
}
});
}
}
}
@Override
public void errorOccured(String cause)
{
btReceiveDrawings.setSelected(false);
Plugin.debugDrawingManager.removeListener(this);
Plugin.debugDrawingManagerMotion.removeListener(this);
}
}
class LogFrameDrawer implements LogFrameListener
{
Pose2D robotPose = null;
// camera matrix for top and bottom image
Pose3D cmBottom = null;
Pose3D cmTop = null;
// in some logfiles CM dowes not exist, this flag makes sure
// that the exception is thrown only once to notify about the absence
// of CMs.
boolean cmExceptionThrown = false;
// needed for projection
final double f = (0.5*640.0) / Math.tan(0.5 * 60.9/180.0*Math.PI);
private void readCameraMatrix(BlackBoard b)
{
cmBottom = null;
cmTop = null;
try {
Representations.CameraMatrix cm = Representations.CameraMatrix.parseFrom(b.get("CameraMatrix").getData());
Representations.CameraMatrix cmt = Representations.CameraMatrix.parseFrom(b.get("CameraMatrixTop").getData());
cmBottom = new Pose3D(
toVector(cm.getPose().getTranslation()),
new Matrix3D(
toVector(cm.getPose().getRotation(0)),
toVector(cm.getPose().getRotation(1)),
toVector(cm.getPose().getRotation(2)))
);
cmTop = new Pose3D(
toVector(cmt.getPose().getTranslation()),
new Matrix3D(
toVector(cmt.getPose().getRotation(0)),
toVector(cmt.getPose().getRotation(1)),
toVector(cmt.getPose().getRotation(2)))
);
// CMs exist, reset the error flag
cmExceptionThrown = false;
} catch(InvalidProtocolBufferException ex) {
ex.printStackTrace(System.err);
} catch(NullPointerException ex) {
// throw the exception only once to avoid spamming
if(!cmExceptionThrown) {
new Exception("No CameraMatrix or CameraMatrixTop.", ex).printStackTrace(System.err);
cmExceptionThrown = true;
}
}
}
private void drawTeamMessages(BlackBoard b, DrawingCollection dc)
{
Optional<String> ownBodyID = getOwnBodyID(b);
LogDataFrame teamMessageFrame = b.get("TeamMessage");
if(teamMessageFrame != null)
{
try {
TeamMessage teamMessage = TeamMessage.parseFrom(teamMessageFrame.getData());
for(int i=0; i < teamMessage.getDataCount(); i++)
{
TeamMessage.Data robotMsg = teamMessage.getData(i);
SPLMessage splMsg = SPLMessage.parseFrom(robotMsg);
splMsg.ballAge /= 1000.0; // the ballAge in the log files is in milliseconds
if((splMsg.user.hasIsPenalized() && !splMsg.user.getIsPenalized()) || (splMsg.user.hasRobotState() && splMsg.user.getRobotState() != TeamMessageOuterClass.RobotState.penalized)) {
boolean isOwnMsg = false;
if(ownBodyID.isPresent())
{
isOwnMsg = ownBodyID.get().equals(splMsg.user.getBodyID());
}
if(isOwnMsg) {
robotPose = new Pose2D(splMsg.pose_x, splMsg.pose_y, splMsg.pose_a);
}
splMsg.draw(dc, isOwnMsg ? Color.red : Color.black, false);
}
}
} catch (InvalidProtocolBufferException ex) {
Logger.getLogger(FieldViewer.class.getName()).log(Level.SEVERE, null, ex);
}
}
drawScanEdgelPercept(robotPose, b.get("GoalPercept"), b.get("ScanLineEdgelPercept"), cmBottom, dc, Color.red);
drawScanEdgelPercept(robotPose, b.get("GoalPerceptTop"), b.get("ScanLineEdgelPerceptTop"), cmTop, dc, Color.blue);
}
private void drawFieldPercept(BlackBoard b, DrawingCollection dc)
{
Color green = new Color(217, 255, 25);
if(b.has("FieldPercept")) { drawFieldPercept(robotPose, b.get("FieldPercept"), cmBottom, dc, green); }
if(b.has("FieldPerceptTop")) { drawFieldPercept(robotPose, b.get("FieldPerceptTop"), cmTop, dc, green); }
}
private void drawFieldPercept(Pose2D robotPose, LogDataFrame fieldPercept, Pose3D cameraMatrix, DrawingCollection dc, Color c) {
try {
Representations.FieldPercept fp = Representations.FieldPercept.parseFrom(fieldPercept.getData());
List<Vector2D> fieldPoly = new ArrayList<>(fp.getFieldPoly().getPointsCount());
for(IntVector2 polyPoint : fp.getFieldPoly().getPointsList()) {
Vector2D point = new Vector2D(polyPoint.getX(), polyPoint.getY());
Vector2D fieldPoint = project(cameraMatrix, f, point);
if(robotPose != null) {
fieldPoint = robotPose.multiply(fieldPoint);
}
fieldPoly.add(fieldPoint);
}
dc.add(new Pen(10, c));
Vector2D last = null;
for(Vector2D point: fieldPoly) {
dc.add(new Circle((int)point.x, (int)point.y, 10));
if(last != null) {
dc.add(new Line((int)last.x, (int)last.y, (int)point.x, (int)point.y));
}
last = point;
}
} catch (InvalidProtocolBufferException ex) {
Logger.getLogger(FieldViewer.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void drawScanEdgelPercept(Pose2D robotPose, LogDataFrame goalPerceptFrame, LogDataFrame scanLineFrame, Pose3D cameraMatrix, DrawingCollection dc, Color c)
{
if (scanLineFrame == null || cameraMatrix == null) {
return;
}
try {
Representations.ScanLineEdgelPercept data = Representations.ScanLineEdgelPercept.parseFrom(scanLineFrame.getData());
Representations.GoalPercept gp = Representations.GoalPercept.parseFrom(goalPerceptFrame.getData());
// draw prijected edgesl on the field
dc.add(new Pen(10, c));
for(Representations.Edgel e: data.getEdgelsList()) {
Vector2D p = new Vector2D(e.getPoint().getX(), e.getPoint().getY());
Vector2D p2 = p.add(new Vector2D(e.getDirection().getX(), e.getDirection().getY()));
Vector2D q = project(cameraMatrix,f,p);
Vector2D q2 = project(cameraMatrix,f,p2);
q2 = q.add(q2.subtract(q).normalize().multiply(50));
if(robotPose != null) {
q = robotPose.multiply(q);
q2 = robotPose.multiply(q2);
}
dc.add(new Circle((int)q.x, (int)q.y, 10));
dc.add(new Line((int)q.x, (int)q.y, (int)q2.x, (int)q2.y));
}
Vector2D last_p = null;
dc.add(new Pen(10, Color.black));
for(Representations.ScanLineEndPoint e: data.getEndPointsList()) {
Vector2D p = new Vector2D(e.getPosOnField().getX(), e.getPosOnField().getY());
if(robotPose != null) {
p = robotPose.multiply(p);
}
if (last_p != null) {
dc.add(new Line((int)last_p.x, (int)last_p.y, (int)p.x, (int)p.y));
}
dc.add(new Circle((int)p.x, (int)p.y, 10));
last_p = p;
}
// draw prijected goal posts on the field
for(Representations.GoalPercept.GoalPost g: gp.getPostList()) {
Vector2D q = new Vector2D(g.getPosition().getX(), g.getPosition().getY());
//Vector2D q = project(R,t,f,p);
if(robotPose != null) {
q = robotPose.multiply(q);
}
dc.add(new Pen(20, c));
dc.add(new FillOval((int)q.x, (int)q.y, 100, 100));
dc.add(new Pen(10, Color.black));
dc.add(new Circle((int)q.x, (int)q.y, 100));
}
} catch (InvalidProtocolBufferException ex) {
Logger.getLogger(FieldViewer.class.getName()).log(Level.SEVERE, null, ex);
}
}
private Vector2D project(Pose3D pose, double f, Vector2D p) {
Vector3D v = new Vector3D(f, 320 - p.x, 240 - p.y);
v = pose.rotation.multiply(v);
Vector2D q = new Vector2D(
pose.translation.x - v.x*(pose.translation.z/v.z),
pose.translation.y - v.y*(pose.translation.z/v.z));
return q;
}
private Vector3D toVector(DoubleVector3 v) {
return new Vector3D(v.getX(), v.getY(), v.getZ());
}
private Optional<String> getOwnBodyID(BlackBoard b)
{
LogDataFrame robotInfoFrame = b.get("RobotInfo");
if(robotInfoFrame != null)
{
try {
RobotInfo robotInfo = RobotInfo.parseFrom(robotInfoFrame.getData());
return Optional.of(robotInfo.getBodyID());
} catch (InvalidProtocolBufferException ex) {
Logger.getLogger(FieldViewer.class.getName()).log(Level.SEVERE, null, ex);
}
}
return Optional.empty();
}
private void drawCircle(BlackBoard b, DrawingCollection dc) {
// circle
LogDataFrame ransacCirclePercept2018 = b.get("RansacCirclePercept2018");
if(ransacCirclePercept2018 != null)
{
try {
RansacCirclePercept2018 circle = RansacCirclePercept2018.parseFrom(ransacCirclePercept2018.getData());
if(robotPose != null && circle.getWasSeen() && circle.hasMiddleCircleCenter())
{
Vector2D q = robotPose.multiply(new Vector2D(circle.getMiddleCircleCenter().getX(), circle.getMiddleCircleCenter().getY()));
dc.add(new Pen(50.0f, Color.yellow));
dc.add(new Circle((int)q.x, (int)q.y, 750));
}
} catch (InvalidProtocolBufferException ex) {
Logger.getLogger(FieldViewer.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
private void drawLines(BlackBoard b, DrawingCollection dc) {
LogDataFrame linesFrame = b.get("RansacLinePercept");
if(linesFrame != null)
{
try {
RansacLinePercept lines = RansacLinePercept.parseFrom(linesFrame.getData());
if(robotPose != null)
{
for(LineSegment l: lines.getFieldLineSegmentsList()) {
Vector2D begin = new Vector2D(l.getBase().getX(), l.getBase().getY());
Vector2D end = new Vector2D(begin.x + l.getDirection().getX()*l.getLength(), begin.y + l.getDirection().getY()*l.getLength());
begin = robotPose.multiply(begin);
end = robotPose.multiply(end);
dc.add(new Pen(50.0f, Color.yellow));
dc.add(new Line((int)begin.x, (int)begin.y, (int)end.x, (int)end.y));
}
}
} catch (InvalidProtocolBufferException ex) {
Logger.getLogger(FieldViewer.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
private void drawShortLines(BlackBoard b, DrawingCollection dc) {
LogDataFrame linesFrame = b.get("ShortLinePercept");
if(linesFrame != null)
{
try {
ShortLinePercept lines = ShortLinePercept.parseFrom(linesFrame.getData());
if(robotPose != null)
{
for(LineSegment l: lines.getFieldLineSegmentsList()) {
Vector2D begin = new Vector2D(l.getBase().getX(), l.getBase().getY());
Vector2D end = new Vector2D(begin.x + l.getDirection().getX()*l.getLength(), begin.y + l.getDirection().getY()*l.getLength());
begin = robotPose.multiply(begin);
end = robotPose.multiply(end);
dc.add(new Pen(50.0f, Color.cyan));
dc.add(new Line((int)begin.x, (int)begin.y, (int)end.x, (int)end.y));
}
}
} catch (InvalidProtocolBufferException ex) {
Logger.getLogger(FieldViewer.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
private void drawBallPercept(BlackBoard b, DrawingCollection dc) {
LogDataFrame data = b.get("MultiBallPercept");
if(data != null)
{
try {
MultiBallPercept ball = MultiBallPercept.parseFrom(data.getData());
if(robotPose != null && cmTop != null && cmBottom != null) {
for(MultiBallPercept.BallPercept p: ball.getPerceptsList()) {
Vector2D pi = new Vector2D(p.getCenterInImage().getX(), p.getCenterInImage().getY());
Vector2D q;
if(p.getCameraId() == CommonTypes.CameraID.bottom) {
q = project(cmBottom,f,pi);
} else {
q = project(cmTop,f,pi);
}
q = robotPose.multiply(q);
dc.add(new Pen(50.0f, Color.pink));
dc.add(new Circle((int)q.x, (int)q.y, 50));
}
}
} catch (InvalidProtocolBufferException ex) {
Logger.getLogger(FieldViewer.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
private void drawRobot(BlackBoard b, DrawingCollection dc) {
// parse the explicitely avaliable RobotPose if avaliable
LogDataFrame data = b.get("RobotPose");
if(data != null) {
try {
RobotPose pose = RobotPose.parseFrom(data.getData());
robotPose = new Pose2D(pose.getPose().getTranslation().getX(), pose.getPose().getTranslation().getY(), pose.getPose().getRotation());
} catch(InvalidProtocolBufferException ex) {
Logger.getLogger(FieldViewer.class.getName()).log(Level.SEVERE, null, ex);
}
}
if(robotPose != null) {
dc.add(new Pen(1.0f, Color.red));
dc.add(new Robot(robotPose.translation.x, robotPose.translation.y, robotPose.rotation, cmBottom.rotation.getZAngle()));
}
}
@Override
public void newFrame(BlackBoard b)
{
readCameraMatrix(b);
DrawingCollection dc = new DrawingCollection();
drawTeamMessages(b, dc);
drawCircle(b, dc);
drawLines(b, dc);
drawShortLines(b, dc);
drawBallPercept(b, dc);
drawRobot(b, dc);
drawFieldPercept(b, dc);
drawings.add(this.getClass(), dc);
}
}
class PlotDataListener implements ObjectListener<Plots>
{
@Override
public void errorOccured(String cause)
{
btReceiveDrawings.setSelected(false);
Plugin.plotDataManager.removeListener(this);
}
@Override
public void newObjectReceived(Plots data)
{
if (data == null) return;
for(PlotItem item : data.getPlotsList())
{
if(item.getType() == PlotItem.PlotType.Plot2D
&& item.hasX() && item.hasY())
{
strokePlot.addStroke(item.getName(), Color.blue);
strokePlot.setEnabled(item.getName(), true);
strokePlot.plot(item.getName(), new Vector2D(item.getX(), item.getY()));
}
else if(item.getType() == PlotItem.PlotType.Origin2D
&& item.hasX() && item.hasY() && item.hasRotation())
{
strokePlot.setRotation(item.getRotation());
}
} //end for
}//end newObjectReceived
}//end class PlotDataListener
@Override
public void dispose()
{
// remove all the registered listeners
Plugin.debugDrawingManager.removeListener(drawingsListenerCognition);
Plugin.debugDrawingManagerMotion.removeListener(drawingsListenerMotion);
Plugin.plotDataManager.removeListener(plotDataListener);
}
/*
// NOTE: can we use this again?
class DrawingCollectionLimited extends DrawingCollection
{
private final int maxNumberOfEnties;
public DrawingCollectionLimited(int maxNumberOfEnties) {
this.maxNumberOfEnties = maxNumberOfEnties;
}
@Override
public void add(Drawable d) {
if(maxNumberOfEnties > 0 && this.drawables.size() >= maxNumberOfEnties) {
this.drawables.remove(0);
}
super.add(d);
}
}
*/
class MultiSourceDrawingCollection implements Drawable
{
// drawing buffer for concurrent access; every "source" gets its own "buffer"
private final ConcurrentHashMap<Class<?>, DrawingCollection> drawingBuffers = new ConcurrentHashMap<>();
public void add(Class<?> owner, Drawable d)
{
// get the collection for the owner
DrawingCollection dc = drawingBuffers.get(owner);
if(dc == null) {
dc = new DrawingCollection();
drawingBuffers.put(owner, dc);
}
if(!btCollectDrawings.isSelected()) {
dc.clear();
}
dc.add(d);
// re-draw field
fieldCanvas.repaint();
}
public void clear() {
drawingBuffers.clear();
}
@Override
public void draw(Graphics2D g2d) {
drawingBuffers.forEach((s,b)->{b.draw(g2d);});
}
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JCheckBox btAntializing;
private javax.swing.JButton btClean;
private javax.swing.JCheckBox btCollectDrawings;
private javax.swing.JToggleButton btFitToView;
private javax.swing.JToggleButton btLog;
private javax.swing.JToggleButton btReceiveDrawings;
private javax.swing.JButton btRotate;
private javax.swing.JCheckBox btTrace;
private javax.swing.JComboBox cbBackground;
private javax.swing.JCheckBox cbExportOnDrawing;
private javax.swing.JDialog coordsPopup;
private javax.swing.JPanel drawingPanel;
private de.naoth.rc.components.DynamicCanvasPanel fieldCanvas;
private javax.swing.JMenuItem jMenuItemCopyCoords;
private javax.swing.JMenuItem jMenuItemExport;
private javax.swing.JPopupMenu jPopupMenu;
private javax.swing.JSlider jSlider1;
private javax.swing.JToolBar jToolBar1;
// End of variables declaration//GEN-END:variables
}
|
package example;
//-*- mode:java; encoding:utf8n; coding:utf-8 -*-
// vim:set fileencoding=utf-8:
//@homepage@
import java.awt.*;
import java.awt.event.*;
import java.util.EventObject;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.tree.*;
public class MainPanel extends JPanel {
public MainPanel() {
super(new BorderLayout());
UIManager.put("PopupMenu.consumeEventOnClose", Boolean.FALSE);
JTree tree = new JTree();
tree.setCellEditor(new DefaultTreeCellEditor(tree, (DefaultTreeCellRenderer)tree.getCellRenderer()) {
// @Override protected boolean shouldStartEditingTimer(EventObject e) {
// return false;
// @Override protected boolean canEditImmediately(EventObject e) {
// //((MouseEvent)e).getClickCount()>2
// return (e instanceof MouseEvent)?false:super.canEditImmediately(e);
@Override public boolean isCellEditable(EventObject e) {
return (e instanceof MouseEvent)?false:super.isCellEditable(e);
}
});
tree.setEditable(true);
tree.setComponentPopupMenu(new TreePopupMenu());
add(new JScrollPane(tree));
setPreferredSize(new Dimension(320, 200));
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
try{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}catch(Exception e) {
e.printStackTrace();
}
JFrame frame = new JFrame("@title@");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(new MainPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class TreePopupMenu extends JPopupMenu {
private TreePath path;
private final JTextField textField = new JTextField();
public TreePopupMenu() {
super();
add(new JMenuItem(new AbstractAction("Edit") {
@Override public void actionPerformed(ActionEvent e) {
JTree tree = (JTree)getInvoker();
if(path!=null) tree.startEditingAtPath(path);
}
}));
textField.addAncestorListener(new AncestorListener() {
@Override public void ancestorAdded(AncestorEvent e) {
textField.requestFocusInWindow();
}
@Override public void ancestorMoved(AncestorEvent event) {}
@Override public void ancestorRemoved(AncestorEvent e) {}
});
add(new JMenuItem(new AbstractAction("Edit Dialog") {
@Override public void actionPerformed(ActionEvent e) {
JTree tree = (JTree)getInvoker();
if(path==null) return;
Object node = path.getLastPathComponent();
if(node instanceof DefaultMutableTreeNode) {
DefaultMutableTreeNode leaf = (DefaultMutableTreeNode) node;
textField.setText(leaf.getUserObject().toString());
int result = JOptionPane.showConfirmDialog(tree, textField, "Rename", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
if(result==JOptionPane.OK_OPTION) {
String str = textField.getText();
if(!str.trim().isEmpty()) ((DefaultTreeModel)tree.getModel()).valueForPathChanged(path, str);
}
}
}
}));
}
@Override public void show(Component c, int x, int y) {
JTree tree = (JTree)c;
TreePath[] tsp = tree.getSelectionPaths();
if(tsp!=null && tsp.length>0) {
path = tree.getPathForLocation(x, y); //path = tree.getClosestPathForLocation(x, y);
if(tsp[tsp.length-1].equals(path)) { //Test: if(path!=null && java.util.Arrays.asList(tsp).contains(path)) {
super.show(c, x, y);
}
}
}
}
|
package main;
import io.IORobot;
import java.awt.Point;
import java.io.*;
import java.util.ArrayList;
import java.util.LinkedList;
import javax.swing.SwingUtilities;
import java.lang.InterruptedException;
import java.lang.Thread;
import java.util.zip.*;
import move.AttackTransferMove;
import move.MoveResult;
import move.PlaceArmiesMove;
import org.bson.types.ObjectId;
import com.mongodb.MongoClient;
import com.mongodb.MongoException;
import com.mongodb.WriteConcern;
import com.mongodb.DB;
import com.mongodb.DBObject;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCursor;
import com.mongodb.ServerAddress;
public class RunGame
{
LinkedList<MoveResult> fullPlayedGame;
LinkedList<MoveResult> player1PlayedGame;
LinkedList<MoveResult> player2PlayedGame;
int gameIndex = 1;
String playerName1, playerName2;
final String gameId,
bot1Id, bot2Id,
bot1Dir, bot2Dir;
Engine engine;
DB db;
public static void main(String args[]) throws Exception
{
RunGame run = new RunGame(args);
run.go();
}
public RunGame(String args[])
{
this.gameId = args[0];
this.bot1Id = args[1];
this.bot2Id = args[2];
this.bot1Dir = args[3];
this.bot2Dir = args[4];
this.playerName1 = "player1";
this.playerName2 = "player2";
}
private void go() throws IOException, InterruptedException
{
System.out.println("starting game " + gameId);
Map initMap, map;
Player player1, player2;
IORobot bot1, bot2;
int startingArmies;
db = new MongoClient("localhost", 27017).getDB("test");
// authentication
// boolean auth = db.authenticate(<username>,<password>);
//setup the bots
bot1 = new IORobot("/opt/aigames/scripts/run_bot.sh aiplayer1 " + bot1Dir);
bot2 = new IORobot("/opt/aigames/scripts/run_bot.sh aiplayer2 " + bot2Dir);
startingArmies = 5;
player1 = new Player(playerName1, bot1, startingArmies);
player2 = new Player(playerName2, bot2, startingArmies);
//setup the map
initMap = makeInitMap();
map = setupMap(initMap);
//start the engine
this.engine = new Engine(map, player1, player2);
//send the bots the info they need to start
bot1.writeInfo("settings your_bot " + player1.getName());
bot1.writeInfo("settings opponent_bot " + player2.getName());
bot2.writeInfo("settings your_bot " + player2.getName());
bot2.writeInfo("settings opponent_bot " + player1.getName());
sendSetupMapInfo(player1.getBot(), initMap);
sendSetupMapInfo(player2.getBot(), initMap);
this.engine.distributeStartingRegions(); //decide the player's starting regions
this.engine.recalculateStartingArmies(); //calculate how much armies the players get at the start of the round (depending on owned SuperRegions)
this.engine.sendAllInfo();
//play the game
while(this.engine.winningPlayer() == null && this.engine.getRoundNr() <= 100)
{
bot1.addToDump("Round " + this.engine.getRoundNr() + "\n");
bot2.addToDump("Round " + this.engine.getRoundNr() + "\n");
this.engine.playRound();
}
fullPlayedGame = this.engine.getFullPlayedGame();
player1PlayedGame = this.engine.getPlayer1PlayedGame();
player2PlayedGame = this.engine.getPlayer2PlayedGame();
// String outputFile = this.writeOutputFile(this.gameId, this.engine.winningPlayer());
// this.saveGame(engine.winningPlayer().getName(), engine.getRoundNr(), outputFile);
finish(bot1, bot2);
}
//aanpassen en een QPlayer class maken? met eigen finish
private void finish(IORobot bot1, IORobot bot2) throws InterruptedException
{
bot1.finish();
Thread.sleep(200);
bot2.finish();
Thread.sleep(200);
Thread.sleep(200);
// write everything
// String outputFile = this.writeOutputFile(this.gameId, this.engine.winningPlayer());
this.saveGame(bot1, bot2);
System.exit(0);
}
//tijdelijk handmatig invoeren
private Map makeInitMap()
{
Map map = new Map();
SuperRegion northAmerica = new SuperRegion(1, 5);
SuperRegion southAmerica = new SuperRegion(2, 2);
SuperRegion europe = new SuperRegion(3, 5);
SuperRegion afrika = new SuperRegion(4, 3);
SuperRegion azia = new SuperRegion(5, 7);
SuperRegion australia = new SuperRegion(6, 2);
Region region1 = new Region(1, northAmerica);
Region region2 = new Region(2, northAmerica);
Region region3 = new Region(3, northAmerica);
Region region4 = new Region(4, northAmerica);
Region region5 = new Region(5, northAmerica);
Region region6 = new Region(6, northAmerica);
Region region7 = new Region(7, northAmerica);
Region region8 = new Region(8, northAmerica);
Region region9 = new Region(9, northAmerica);
Region region10 = new Region(10, southAmerica);
Region region11 = new Region(11, southAmerica);
Region region12 = new Region(12, southAmerica);
Region region13 = new Region(13, southAmerica);
Region region14 = new Region(14, europe);
Region region15 = new Region(15, europe);
Region region16 = new Region(16, europe);
Region region17 = new Region(17, europe);
Region region18 = new Region(18, europe);
Region region19 = new Region(19, europe);
Region region20 = new Region(20, europe);
Region region21 = new Region(21, afrika);
Region region22 = new Region(22, afrika);
Region region23 = new Region(23, afrika);
Region region24 = new Region(24, afrika);
Region region25 = new Region(25, afrika);
Region region26 = new Region(26, afrika);
Region region27 = new Region(27, azia);
Region region28 = new Region(28, azia);
Region region29 = new Region(29, azia);
Region region30 = new Region(30, azia);
Region region31 = new Region(31, azia);
Region region32 = new Region(32, azia);
Region region33 = new Region(33, azia);
Region region34 = new Region(34, azia);
Region region35 = new Region(35, azia);
Region region36 = new Region(36, azia);
Region region37 = new Region(37, azia);
Region region38 = new Region(38, azia);
Region region39 = new Region(39, australia);
Region region40 = new Region(40, australia);
Region region41 = new Region(41, australia);
Region region42 = new Region(42, australia);
region1.addNeighbor(region2);
region1.addNeighbor(region4);
region1.addNeighbor(region30);
region2.addNeighbor(region4);
region2.addNeighbor(region3);
region2.addNeighbor(region5);
region3.addNeighbor(region5);
region3.addNeighbor(region6);
region3.addNeighbor(region14);
region4.addNeighbor(region5);
region4.addNeighbor(region7);
region5.addNeighbor(region6);
region5.addNeighbor(region7);
region5.addNeighbor(region8);
region6.addNeighbor(region8);
region7.addNeighbor(region8);
region7.addNeighbor(region9);
region8.addNeighbor(region9);
region9.addNeighbor(region10);
region10.addNeighbor(region11);
region10.addNeighbor(region12);
region11.addNeighbor(region12);
region11.addNeighbor(region13);
region12.addNeighbor(region13);
region12.addNeighbor(region21);
region14.addNeighbor(region15);
region14.addNeighbor(region16);
region15.addNeighbor(region16);
region15.addNeighbor(region18);
region15.addNeighbor(region19);
region16.addNeighbor(region17);
region17.addNeighbor(region19);
region17.addNeighbor(region20);
region17.addNeighbor(region27);
region17.addNeighbor(region32);
region17.addNeighbor(region36);
region18.addNeighbor(region19);
region18.addNeighbor(region20);
region18.addNeighbor(region21);
region19.addNeighbor(region20);
region20.addNeighbor(region21);
region20.addNeighbor(region22);
region20.addNeighbor(region36);
region21.addNeighbor(region22);
region21.addNeighbor(region23);
region21.addNeighbor(region24);
region22.addNeighbor(region23);
region22.addNeighbor(region36);
region23.addNeighbor(region24);
region23.addNeighbor(region25);
region23.addNeighbor(region26);
region23.addNeighbor(region36);
region24.addNeighbor(region25);
region25.addNeighbor(region26);
region27.addNeighbor(region28);
region27.addNeighbor(region32);
region27.addNeighbor(region33);
region28.addNeighbor(region29);
region28.addNeighbor(region31);
region28.addNeighbor(region33);
region28.addNeighbor(region34);
region29.addNeighbor(region30);
region29.addNeighbor(region31);
region30.addNeighbor(region31);
region30.addNeighbor(region34);
region30.addNeighbor(region35);
region31.addNeighbor(region34);
region32.addNeighbor(region33);
region32.addNeighbor(region36);
region32.addNeighbor(region37);
region33.addNeighbor(region34);
region33.addNeighbor(region37);
region33.addNeighbor(region38);
region34.addNeighbor(region35);
region36.addNeighbor(region37);
region37.addNeighbor(region38);
region38.addNeighbor(region39);
region39.addNeighbor(region40);
region39.addNeighbor(region41);
region40.addNeighbor(region41);
region40.addNeighbor(region42);
region41.addNeighbor(region42);
map.add(region1); map.add(region2); map.add(region3);
map.add(region4); map.add(region5); map.add(region6);
map.add(region7); map.add(region8); map.add(region9);
map.add(region10); map.add(region11); map.add(region12);
map.add(region13); map.add(region14); map.add(region15);
map.add(region16); map.add(region17); map.add(region18);
map.add(region19); map.add(region20); map.add(region21);
map.add(region22); map.add(region23); map.add(region24);
map.add(region25); map.add(region26); map.add(region27);
map.add(region28); map.add(region29); map.add(region30);
map.add(region31); map.add(region32); map.add(region33);
map.add(region34); map.add(region35); map.add(region36);
map.add(region37); map.add(region38); map.add(region39);
map.add(region40); map.add(region41); map.add(region42);
map.add(northAmerica);
map.add(southAmerica);
map.add(europe);
map.add(afrika);
map.add(azia);
map.add(australia);
return map;
}
//Make every region neutral with 2 armies to start with
private Map setupMap(Map initMap)
{
Map map = initMap;
for(Region region : map.regions)
{
region.setPlayerName("neutral");
region.setArmies(2);
}
return map;
}
private void sendSetupMapInfo(Robot bot, Map initMap)
{
String setupSuperRegionsString, setupRegionsString, setupNeighborsString;
setupSuperRegionsString = getSuperRegionsString(initMap);
setupRegionsString = getRegionsString(initMap);
setupNeighborsString = getNeighborsString(initMap);
bot.writeInfo(setupSuperRegionsString);
// System.out.println(setupSuperRegionsString);
bot.writeInfo(setupRegionsString);
// System.out.println(setupRegionsString);
bot.writeInfo(setupNeighborsString);
// System.out.println(setupNeighborsString);
}
private String getSuperRegionsString(Map map)
{
String superRegionsString = "setup_map super_regions";
for(SuperRegion superRegion : map.superRegions)
{
int id = superRegion.getId();
int reward = superRegion.getArmiesReward();
superRegionsString = superRegionsString.concat(" " + id + " " + reward);
}
return superRegionsString;
}
private String getRegionsString(Map map)
{
String regionsString = "setup_map regions";
for(Region region : map.regions)
{
int id = region.getId();
int superRegionId = region.getSuperRegion().getId();
regionsString = regionsString.concat(" " + id + " " + superRegionId);
}
return regionsString;
}
//beetje inefficiente methode, maar kan niet sneller wss
private String getNeighborsString(Map map)
{
String neighborsString = "setup_map neighbors";
ArrayList<Point> doneList = new ArrayList<Point>();
for(Region region : map.regions)
{
int id = region.getId();
String neighbors = "";
for(Region neighbor : region.getNeighbors())
{
if(checkDoneList(doneList, id, neighbor.getId()))
{
neighbors = neighbors.concat("," + neighbor.getId());
doneList.add(new Point(id,neighbor.getId()));
}
}
if(neighbors.length() != 0)
{
neighbors = neighbors.replaceFirst(","," ");
neighborsString = neighborsString.concat(" " + id + neighbors);
}
}
return neighborsString;
}
private Boolean checkDoneList(ArrayList<Point> doneList, int regionId, int neighborId)
{
for(Point p : doneList)
if((p.x == regionId && p.y == neighborId) || (p.x == neighborId && p.y == regionId))
return false;
return true;
}
// private String writeOutputFile(String gameId, Player winner)
// try {
// //temp
// String fileString = "/home/jim/development/the-ai-games-website/public/games/gameOutputFile" + gameId + ".txt";
// FileWriter fileStream = new FileWriter(fileString);
// BufferedWriter out = new BufferedWriter(fileStream);
// writePlayedGame(winner, out, "fullGame");
// writePlayedGame(winner, out, "player1");
// writePlayedGame(winner, out, "player2");
// out.close();
// return fileString;
// catch(Exception e) {
// System.err.println("Error on creating output file: " + e.getMessage());
// return null;
// private void writePlayedGame(Player winner, BufferedWriter out, String gameView) throws IOException
// LinkedList<MoveResult> playedGame;
// if(gameView.equals("player1"))
// playedGame = player1PlayedGame;
// else if(gameView.equals("player2"))
// playedGame = player2PlayedGame;
// else
// playedGame = fullPlayedGame;
// playedGame.removeLast();
// int roundNr = 2;
// out.write("map " + playedGame.getFirst().getMap().getMapString() + "\n");
// out.write("round 1" + "\n");
// for(MoveResult moveResult : playedGame)
// if(moveResult != null)
// if(moveResult.getMove() != null)
// try {
// PlaceArmiesMove plMove = (PlaceArmiesMove) moveResult.getMove();
// out.write(plMove.getString() + "\n");
// catch(Exception e) {
// AttackTransferMove atMove = (AttackTransferMove) moveResult.getMove();
// out.write(atMove.getString() + "\n");
// out.write("map " + moveResult.getMap().getMapString() + "\n");
// else
// out.write("round " + roundNr + "\n");
// roundNr++;
// if(winner != null)
// out.write(winner.getName() + " won\n");
// else
// out.write("Nobody won\n");
private String getPlayedGame(Player winner, String gameView)
{
StringBuffer out = new StringBuffer();
LinkedList<MoveResult> playedGame;
if(gameView.equals("player1"))
playedGame = player1PlayedGame;
else if(gameView.equals("player2"))
playedGame = player2PlayedGame;
else
playedGame = fullPlayedGame;
playedGame.removeLast();
int roundNr = 2;
out.append("map " + playedGame.getFirst().getMap().getMapString() + "\n");
out.append("round 1" + "\n");
for(MoveResult moveResult : playedGame)
{
if(moveResult != null)
{
if(moveResult.getMove() != null)
{
try {
PlaceArmiesMove plm = (PlaceArmiesMove) moveResult.getMove();
out.append(plm.getString() + "\n");
}
catch(Exception e) {
AttackTransferMove atm = (AttackTransferMove) moveResult.getMove();
out.append(atm.getString() + "\n");
}
out.append("map " + moveResult.getMap().getMapString() + "\n");
}
}
else
{
out.append("round " + roundNr + "\n");
roundNr++;
}
}
if(winner != null)
out.append(winner.getName() + " won\n");
else
out.append("Nobody won\n");
return out.toString();
}
private String compressGZip(String out)
{
System.out.println("number of newlines: " + countOccurrences(out, '\n'));
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
GZIPOutputStream gzos = new GZIPOutputStream(baos);
byte[] outBytes = out.getBytes();
gzos.write(outBytes, 0, outBytes.length);
gzos.close();
String encodedOut = baos.toByteArray();
encodedOut = encodedOut.replaceAll("\0", ""); //remove \0 chars
return new String(encodedOut);
}
catch(IOException e) {
System.out.println(e);
return "";
}
}
/*
* MongoDB connection functions
*/
public void saveGame(IORobot bot1, IORobot bot2) {
Player winner = this.engine.winningPlayer();
int score = this.engine.getRoundNr();
DBCollection coll = db.getCollection("games");
DBObject queryDoc = new BasicDBObject()
.append("_id", new ObjectId(gameId));
ObjectId bot1ObjectId = new ObjectId(bot1Id);
ObjectId bot2ObjectId = new ObjectId(bot2Id);
ObjectId winnerId = null;
if(winner != null) {
winnerId = winner.getName() == playerName1 ? bot1ObjectId : bot2ObjectId;
}
DBObject updateDoc = new BasicDBObject()
.append("$set", new BasicDBObject()
.append("winner", winnerId)
.append("score", score)
// .append("visualization", new BasicDBObject()
// .append("fullGame", getPlayedGame(winner, "fullGame"))
// .append("player1", getPlayedGame(winner, "player1"))
// .append("player2", getPlayedGame(winner, "player2"))
.append("visualization",
compressGZip( //compress visualisation
getPlayedGame(winner, "fullGame") +
getPlayedGame(winner, "player1") +
getPlayedGame(winner, "player2")
)
)
// .append("output", new BasicDBObject()
// .append(bot1Id, bot1.getStdout())
// .append(bot2Id, bot2.getStdout())
// .append("input", new BasicDBObject()
// .append(bot1Id, bot1.getStdin())
// .append(bot2Id, bot2.getStdin())
.append("errors", new BasicDBObject()
.append(bot1Id, bot1.getStderr())
.append(bot2Id, bot2.getStderr())
)
.append("dump", new BasicDBObject()
.append(bot1Id, bot1.getDump())
.append(bot2Id, bot2.getDump())
)
);
coll.findAndModify(queryDoc, updateDoc);
// System.out.print("Game done... winner: " + winner.getName() + ", score: " + score);
}
}
|
package water.fvec;
import org.junit.*;
import org.junit.rules.ExpectedException;
import water.*;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import static org.junit.Assert.*;
/**
* Tests for Frame.java
*/
public class FrameTest extends TestUtil {
@Rule
public transient ExpectedException ee = ExpectedException.none();
@BeforeClass
public static void setup() {
stall_till_cloudsize(1);
}
@Test
public void testNonEmptyChunks() {
try {
Scope.enter();
final Frame train1 = Scope.track(new TestFrameBuilder()
.withName("testFrame")
.withColNames("ColA", "Response")
.withVecTypes(Vec.T_NUM, Vec.T_CAT)
.withDataForCol(0, ard(1, 2, 3, 4, 0))
.withDataForCol(1, ar("A", "B", "C", "A", "B"))
.withChunkLayout(1, 0, 0, 2, 1, 0, 1)
.build());
assertEquals(4, train1.anyVec().nonEmptyChunks());
final Frame train2 = Scope.track(new TestFrameBuilder()
.withName("testFrame")
.withColNames("ColA", "Response")
.withVecTypes(Vec.T_NUM, Vec.T_CAT)
.withDataForCol(0, ard(1, 2, 3, 4, 0))
.withDataForCol(1, ar("A", "B", "C", "A", "B"))
.withChunkLayout(1, 2, 1, 1)
.build());
assertEquals(4, train2.anyVec().nonEmptyChunks());
} finally {
Scope.exit();
}
}
@Test
public void testRemoveColumn() {
Scope.enter();
Set<Vec> removedVecs = new HashSet<>();
try {
Frame testData = parse_test_file(Key.make("test_deep_select_1"), "smalldata/sparse/created_frame_binomial.svm.zip");
Scope.track(testData);
// dataset to split
int initialSize = testData.numCols();
removedVecs.add(testData.remove(-1));
assertEquals(initialSize, testData.numCols());
removedVecs.add(testData.remove(0));
assertEquals(initialSize - 1, testData.numCols());
assertEquals("C2", testData._names[0]);
removedVecs.add(testData.remove(initialSize - 2));
assertEquals(initialSize - 2, testData.numCols());
assertEquals("C" + (initialSize - 1), testData._names[initialSize - 3]);
removedVecs.add(testData.remove(42));
assertEquals(initialSize - 3, testData.numCols());
assertEquals("C43", testData._names[41]);
assertEquals("C45", testData._names[42]);
} finally {
Scope.exit();
for (Vec v : removedVecs) if (v != null) v.remove();
}
}
// _names=C1,... - C10001
@Ignore
@Test public void testDeepSelectSparse() {
Scope.enter();
// dataset to split
Frame testData = parse_test_file(Key.make("test_deep_select_1"), "smalldata/sparse/created_frame_binomial.svm.zip");
// premade splits from R
Frame subset1 = parse_test_file(Key.make("test_deep_select_2"), "smalldata/sparse/data_split_1.svm.zip");
// subset2 commented out to save time
// Frame subset2 = parse_test_file(Key.make("test_deep_select_3"),"smalldata/sparse/data_split_2.svm");
// predicates (0: runif 1:runif < .5 2: runif >= .5
Frame rnd = parse_test_file(Key.make("test_deep_select_4"), "smalldata/sparse/rnd_r.csv");
Frame x = null;
Frame y = null;
try {
x = testData.deepSlice(new Frame(rnd.vec(1)), null);
// y = testData.deepSlice(new Frame(rnd.vec(2)),null);
assertTrue(TestUtil.isBitIdentical(subset1, x));
// assertTrue(isBitIdentical(subset2,y));
} finally {
Scope.exit();
testData.delete();
rnd.delete();
subset1.delete();
// subset2.delete();
if (x != null) x.delete();
if (y != null) y.delete();
}
}
/**
* This test is testing deepSlice functionality and shows that we can use zero-based indexes for slicing
* // TODO if confirmed go and correct comments for Frame.deepSlice() method
*/
@Test
public void testRowDeepSlice() {
Scope.enter();
try {
long[] numericalCol = ar(1, 2, 3, 4);
Frame input = new TestFrameBuilder()
.withName("testFrame")
.withColNames("ColA", "ColB")
.withVecTypes(Vec.T_STR, Vec.T_NUM)
.withDataForCol(0, ar("a", "b", "c", "d"))
.withDataForCol(1, numericalCol)
.withChunkLayout(numericalCol.length)
.build();
// Single number row slice
Frame sliced = input.deepSlice(new long[]{1}, null);
assertEquals(1, sliced.numRows());
assertEquals("b", sliced.vec(0).stringAt(0));
assertEquals(2, sliced.vec(1).at(0), 1e-5);
//checking that 0-based indexing is allowed as well
// We are slicing here particular indexes of rows : 0 and 3
Frame slicedRange = input.deepSlice(new long[]{0, 3}, null);
assertEquals(2, slicedRange.numRows());
assertStringVecEquals(svec("a", "d"), slicedRange.vec(0));
assertVecEquals(vec(1,4), slicedRange.vec(1), 1e-5);
} finally {
Scope.exit();
}
}
@Test
public void testRowDeepSliceWithPredicateFrame() {
Scope.enter();
try {
long[] numericalCol = ar(1, 2, 3, 4);
Frame input = new TestFrameBuilder()
.withName("testFrame")
.withColNames("ColA", "ColB")
.withVecTypes(Vec.T_STR, Vec.T_NUM)
.withDataForCol(0, ar("a", "b", "c", "d"))
.withDataForCol(1, numericalCol)
.withChunkLayout(numericalCol.length)
.build();
// Single number row slice
Frame sliced = input.deepSlice(new Frame(vec(0, 1, 0, 0)), null);
assertEquals(1, sliced.numRows());
assertEquals("b", sliced.vec(0).stringAt(0));
assertEquals(2, sliced.vec(1).at(0), 1e-5);
//checking that 0-based indexing is allowed as well
Frame slicedRange = input.deepSlice(new Frame(vec(1, 0, 0, 1)), null);
assertEquals(2, slicedRange.numRows());
assertStringVecEquals(svec("a", "d"), slicedRange.vec(0));
assertVecEquals(vec(1,4), slicedRange.vec(1), 1e-5);
} finally {
Scope.exit();
}
}
@Test // deep select filters out all defined values of the chunk and the only left ones are NAs, eg.: c(1, NA, NA) -> c(NA, NA)
public void testDeepSelectNAs() {
Scope.enter();
try {
String[] data = new String[2 /*defined*/ + 17 /*undefined*/];
data[0] = "A";
data[data.length - 1] = "Z";
double[] pred = new double[data.length];
Arrays.fill(pred, 1.0);
pred[0] = 0;
pred[data.length - 1] = 0;
Frame input = new TestFrameBuilder()
.withName("testFrame")
.withColNames("ColA", "predicate")
.withVecTypes(Vec.T_STR, Vec.T_NUM)
.withDataForCol(0, data)
.withDataForCol(1, pred)
.withChunkLayout(data.length) // single chunk
.build();
Scope.track(input);
Frame result = new Frame.DeepSelect().doAll(Vec.T_STR, input).outputFrame();
Scope.track(result);
assertEquals(data.length - 2, result.numRows());
for (int i = 0; i < data.length - 2; i++)
assertTrue("Value in row " + i + " is NA", result.vec(0).isNA(i));
} finally {
Scope.exit();
}
}
@Test
public void testFinalizePartialFrameRemovesTrailingChunks() {
final String fName = "part_frame";
final long[] layout = new long[]{0, 1, 0, 3, 2, 0, 0, 0};
try {
Scope.enter();
Key<Frame> fKey = Key.make(fName);
Frame f = new Frame(fKey);
f.preparePartialFrame(new String[]{"C0"});
Scope.track(f);
f.update();
for (int i = 0; i < layout.length; i++) {
FrameTestUtil.createNC(fName, i, (int) layout[i], new byte[]{Vec.T_NUM});
}
f = DKV.get(fName).get();
f.finalizePartialFrame(layout, new String[][] {null}, new byte[]{Vec.T_NUM});
final long[] expectedESPC = new long[]{0, 0, 1, 1, 4, 6};
assertArrayEquals(expectedESPC, f.anyVec().espc());
Frame f2 = Scope.track(new MRTask(){
@Override
public void map(Chunk c, NewChunk nc) {
for (int i = 0; i < c._len; i++)
nc.addNum(c.atd(i));
}
}.doAll(Vec.T_NUM, f).outputFrame());
// the ESPC is the same
assertArrayEquals(expectedESPC, f2.anyVec().espc());
} finally {
Scope.exit();
}
}
@Test
public void deepCopyFrameTest() {
Scope.enter();
try {
Frame fr = new TestFrameBuilder()
.withName("testFrame")
.withColNames("ColA", "ColB")
.withVecTypes(Vec.T_CAT, Vec.T_CAT)
.withDataForCol(0, ar("a", "b"))
.withDataForCol(1, ar("c", "d"))
.build();
Frame newFrame = fr.deepCopy(Key.make().toString());
fr.delete();
assertStringVecEquals(newFrame.vec("ColB"), cvec("c", "d"));
} finally {
Scope.exit();
}
}
@Test
public void testToCategoricalColByIdx() {
Scope.enter();
try {
Frame fr = new TestFrameBuilder()
.withName("testFrame")
.withColNames("ColA")
.withVecTypes(Vec.T_STR)
.withDataForCol(0, new String[]{"A", "B", "C"})
.build();
assertFalse(fr.vec(0).isCategorical());
fr.toCategoricalCol(0);
assertTrue(fr.vec(0).isCategorical());
fr.delete();
} finally {
Scope.exit();
}
}
@Test
public void testToCategoricalColByName() {
Scope.enter();
try {
Frame fr = new TestFrameBuilder()
.withName("testFrame")
.withColNames("ColA")
.withVecTypes(Vec.T_STR)
.withDataForCol(0, new String[]{"A", "B", "C"})
.build();
assertFalse(fr.vec("ColA").isCategorical());
fr.toCategoricalCol("ColA");
assertTrue(fr.vec("ColA").isCategorical());
fr.delete();
} finally {
Scope.exit();
}
}
@Test
public void testMissingVecError() {
Assume.assumeTrue(Frame.class.desiredAssertionStatus());
Vec missingVec = Vec.makeCon(Math.PI, 4);
missingVec.remove();
assertNull(DKV.get(missingVec._key));
String msg1 = null;
try {
new Frame(null, new String[]{"testMissingVec"}, new Vec[]{missingVec});
} catch (AssertionError ae) {
msg1 = ae.getMessage();
}
assertEquals(" null vec: " + missingVec._key + "; name: testMissingVec", msg1);
String msg2 = null;
try {
new Frame(null, null, new Vec[]{missingVec});
} catch (AssertionError ae) {
msg2 = ae.getMessage();
}
assertEquals(" null vec: " + missingVec._key + "; index: 0", msg2);
}
@Test
public void testPubDev6673() {
checkToCSV(false, false);
checkToCSV(true, false);
checkToCSV(false, true);
checkToCSV(true, true);
}
private static void checkToCSV(final boolean headers, final boolean hex_string) {
final InputStream invoked = new ByteArrayInputStream(new byte[0]);
Frame f = new Frame() {
@Override
public InputStream toCSV(CSVStreamParams parms) {
assertEquals(headers, parms._headers);
assertEquals(hex_string, parms._hex_string);
return invoked;
}
};
InputStream wasInvoked = f.toCSV(headers, hex_string);
assertSame(invoked, wasInvoked); // just make sure the asserts were actually called
}
@Test
public void testSubframe() {
try {
Scope.enter();
String[] cols = new String[]{"col_1", "col_2"};
Frame f = TestFrameCatalog.oneChunkFewRows();
Frame sf = f.subframe(cols);
Frame expected = new Frame(cols, f.vecs(cols));
assertFrameEquals(expected, sf, 0);
} finally {
Scope.exit();
}
}
@Test
public void testSubframe_invalidCols() {
try {
Scope.enter();
String[] cols = new String[]{"col_5", "col_6", "col_7", "col_8", "col_9", "Omitted_1", "Omitted_2"};
Frame f = TestFrameCatalog.oneChunkFewRows();
ee.expectMessage("Frame `" + f._key + "` doesn't contain columns: " +
"'col_5', 'col_6', 'col_7', 'col_8', 'col_9' (and other 2).");
f.subframe(cols);
} finally {
Scope.exit();
}
}
}
|
package view;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import javax.swing.table.DefaultTableModel;
import controller.MainViewControllerC;
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import model.MTMainClient;
import model.UserClient;
public class MainViewClient extends JFrame{
private boolean isGuest = false;
private static JPanel jpMenu;
private static CardLayout cardLayout = new CardLayout();
private static JPanel jpLogInCard = new JPanel();
private static JPanel jpRegisterCard = new JPanel();
private static JPanel jpInitialMenuCard = new JPanel();
private static JPanel jpSelectGameCard = new JPanel();
private static JPanel jpGameCard = new JPanel();
private static JPanel jpRankingCard = new JPanel();
private JPanel jpButtonMenu;
private static JButton jbRegister = new JButton("Register");
private static JButton jbGuest = new JButton("Enter as a Guest");
private static JButton jbNewGame = new JButton("New Game");
private static JButton jbRanking = new JButton("Show Ranking");
private static JButton jbLogOut = new JButton("Log Out");
private static JButton jbBack = new JButton("Back");
private static JButton jbGoToMenu = new JButton("Log In");
private static JButton jbStartGame = new JButton("Start Game");
//atributs menu
//s'ha d'afegir la info tot en una label per que quedi tot seguit.
//important posar espai abans i despres del text (per que el borde no quedi tan enganxat)
private JLabel userinfo = new JLabel();
private JLabel comptime = new JLabel(" There is no competition running now. ");
private JLabel bestplayer = new JLabel(" Here will appear the best player of the competition. ");
//atributs de log in
private JTextField jtfnickname;
private JPasswordField jpfpassword;
//atributs de game card
private JLabel timecomp = new JLabel(" There is no competition running now. ");
private JLabel iadifficulty = new JLabel(" A.I. Difficulty ");
private JLabel mode = new JLabel(" Mode ");
private JLabel yourscore = new JLabel("Your Score", SwingConstants.CENTER);
private JLabel iascore = new JLabel("I.A. Score", SwingConstants.CENTER);
private JTable tableGame;
//atributs de register
private JTextField jtfnicknameR;
private JPasswordField jpfpasswordR;
private JTextField jtfname;
private JTextField jtflastname;
//atributs ranking
private JPanel panell;
private JTable table;
private String[] columnNames = {"NickName","Score",};
private JPanel title;
//atributs joc
private JPanel jpgame;
//atributs select game
private JRadioButton jrbmemoria;
private JRadioButton jrbconcentracio;
private JRadioButton jrbmachine;
private JRadioButton jrbtimetrial;
private JRadioButton jrbeasy;
private JRadioButton jrbmedium;
private JRadioButton jrbhard;
public MainViewClient(){
setTitle("Memory Torunament -Client-");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(1000,550);
setLocationRelativeTo(null);
createLogInCard();
createRegisterCard();
createInitialMenuCard();
createSelectGameCard();
createGameCard();
createRankingCard();
jpMenu = new JPanel();
jpMenu.setLayout(cardLayout);
jpMenu.add(jpLogInCard, "1");
jpMenu.add(jpRegisterCard, "2");
jpMenu.add(jpInitialMenuCard, "3");
jpMenu.add(jpSelectGameCard, "4");
jpMenu.add(jpGameCard, "5");
jpMenu.add(jpRankingCard, "6");
jpButtonMenu = new JPanel();
jpButtonMenu.add(jbGoToMenu);
jpButtonMenu.add(jbRegister);
jpButtonMenu.add(jbGuest);
jpButtonMenu.add(jbBack);
jpButtonMenu.add(jbNewGame);
jpButtonMenu.add(jbStartGame);
jpButtonMenu.add(jbRanking);
jpButtonMenu.add(jbLogOut);
jbBack.setVisible(false);
jbNewGame.setVisible(false);
jbStartGame.setVisible(false);
jbRanking.setVisible(false);
jbLogOut.setVisible(false);
jpButtonMenu.setVisible(true);
add(jpButtonMenu, BorderLayout.SOUTH);
add(jpMenu, BorderLayout.NORTH);
}
public void registerController(MainViewControllerC actionListener){
jbGoToMenu.addActionListener(actionListener);
jbRegister.addActionListener(actionListener);
jbGuest.addActionListener(actionListener);
jbBack.addActionListener(actionListener);
jbNewGame.addActionListener(actionListener);
jbStartGame.addActionListener(actionListener);
jbRanking.addActionListener(actionListener);
jbLogOut.addActionListener(actionListener);
}
public void setGuest(boolean guest){
this.isGuest = guest;
}
public void createRegisterCard(){
JPanel titol = new JPanel();
titol.setLayout(new BoxLayout(titol, BoxLayout.PAGE_AXIS));
JLabel nomtitol = new JLabel("Register");
nomtitol.setFont(new java.awt.Font("Geneva", 1, 40));
titol.add(Box.createVerticalStrut(15));
nomtitol.setAlignmentX(Component.CENTER_ALIGNMENT);
titol.add(nomtitol);
titol.add(Box.createVerticalStrut(65));
JPanel register = new JPanel();
register.setLayout(new BoxLayout(register, BoxLayout.PAGE_AXIS));
JLabel jlname = new JLabel("Name");
jlname.setFont(new java.awt.Font("Geneva", 1, 14));
jtfname = new JTextField();
JPanel jpname = new JPanel();
jpname.setLayout(new GridLayout(1,4));
jpname.add(new JPanel());
jpname.add(jlname);
jpname.add(jtfname);
jpname.add(new JPanel());
JLabel jllastname = new JLabel("Last Name");
jllastname.setFont(new java.awt.Font("Geneva", 1, 14));
jtflastname = new JTextField();
JPanel jplastname = new JPanel();
jplastname.setLayout(new GridLayout(1,4));
jplastname.add(new JPanel());
jplastname.add(jllastname);
jplastname.add(jtflastname);
jplastname.add(new JPanel());
JLabel jlnickname = new JLabel("Nickname");
jlnickname.setFont(new java.awt.Font("Geneva", 1, 14));
jtfnicknameR = new JTextField();
JPanel jpnickname = new JPanel();
jpnickname.setLayout(new GridLayout(1,4));
jpnickname.add(new JPanel());
jpnickname.add(jlnickname);
jpnickname.add(jtfnicknameR);
jpnickname.add(new JPanel());
JLabel jlpassword = new JLabel("Password");
jlpassword.setFont(new java.awt.Font("Geneva", 1, 14));
jpfpasswordR = new JPasswordField();
JPanel jppassword = new JPanel();
jppassword.setLayout(new GridLayout(1,4));
jppassword.add(new JPanel());
jppassword.add(jlpassword);
jppassword.add(jpfpasswordR);
jppassword.add(new JPanel());
JLabel jlage = new JLabel("Age");
String [] agestring = { "1-10", "11-20", "21-30", "31-40", "41-50", "51-60", "61-70", "71-80", "81-90", "91-99"};
JComboBox agelist = new JComboBox(agestring);
JPanel jpage = new JPanel();
jpage.setLayout(new GridLayout(1,4));
jpage.add(new JPanel());
jpage.add(jlage);
jpage.add(agelist);
jpage.add(new JPanel());
jpnickname.setAlignmentX(Component.CENTER_ALIGNMENT);
jpname.setAlignmentX(Component.CENTER_ALIGNMENT);
jplastname.setAlignmentX(Component.CENTER_ALIGNMENT);
jppassword.setAlignmentX(Component.CENTER_ALIGNMENT);
jpage.setAlignmentX(Component.CENTER_ALIGNMENT);
register.add(jpname);
register.add(jplastname);
register.add(jpnickname);
register.add(jppassword);
register.add(jpage);
register.setAlignmentX(Component.CENTER_ALIGNMENT);
titol.add(register);
jpRegisterCard.add(titol);
}
public String getRegNickname(){
return jtfnicknameR.getText();
}
@SuppressWarnings("deprecation")
public String getRegPasword(){
return jpfpasswordR.getText();
}
public void createLogInCard(){
//jpLogInCard.setBackground( Color.BLUE );
JPanel titol = new JPanel();
titol.setLayout(new BoxLayout(titol, BoxLayout.PAGE_AXIS));
JLabel nomtitol = new JLabel("MemoTournament");
nomtitol.setFont(new java.awt.Font("Geneva", 1, 50));
titol.add(Box.createVerticalStrut(15));
titol.add(nomtitol);
JLabel textinfo = new JLabel("Test your memory and see how quickly you can clear the board by matching up the pairs.");
textinfo.setFont(new java.awt.Font("Geneva", 3, 16));
textinfo.setAlignmentX(Component.CENTER_ALIGNMENT);
titol.add(Box.createVerticalStrut(25));
nomtitol.setAlignmentX(Component.CENTER_ALIGNMENT);
titol.add(textinfo);
titol.add(Box.createVerticalStrut(75));
JPanel login = new JPanel();
//login.setBorder(BorderFactory.createLineBorder(Color.BLACK, 1));
login.setLayout(new BoxLayout(login, BoxLayout.PAGE_AXIS));
JLabel jlnickname = new JLabel("Nickname");
jlnickname.setFont(new java.awt.Font("Geneva", 1, 14));
jtfnickname = new JTextField();
JPanel jpnickname = new JPanel();
jpnickname.setLayout(new GridLayout(1,6));
jpnickname.add(new JPanel());
jpnickname.add(new JPanel());
jpnickname.add(jlnickname);
jpnickname.add(jtfnickname);
jpnickname.add(new JPanel());
jpnickname.add(new JPanel());
JLabel jlpassword = new JLabel("Password");
jlpassword.setFont(new java.awt.Font("Geneva", 1, 14));
jpfpassword = new JPasswordField();
JPanel jppassword = new JPanel();
jppassword.setLayout(new GridLayout(1,6));
jppassword.add(new JPanel());
jppassword.add(new JPanel());
jppassword.add(jlpassword);
jppassword.add(jpfpassword);
jppassword.add(new JPanel());
jppassword.add(new JPanel());
jpnickname.setAlignmentX(Component.CENTER_ALIGNMENT);
jppassword.setAlignmentX(Component.CENTER_ALIGNMENT);
login.add(jpnickname);
login.add(jppassword);
login.setAlignmentX(Component.CENTER_ALIGNMENT);
titol.add(login);
jpLogInCard.add(titol);
}
public String getLogNickname(){
return jtfnickname.getText();
}
@SuppressWarnings("deprecation")
public String getLogPasword(){
return jpfpassword.getText();
}
public void createInitialMenuCard(){
JPanel titol = new JPanel();
titol.setLayout(new BoxLayout(titol, BoxLayout.PAGE_AXIS));
titol.add(Box.createVerticalStrut(15));
JLabel nomtitol = new JLabel("Menu");
nomtitol.setFont(new java.awt.Font("Geneva", 1, 40));
nomtitol.setAlignmentX(Component.CENTER_ALIGNMENT);
titol.add(nomtitol);
titol.add(Box.createVerticalStrut(15));
userinfo.setFont(new java.awt.Font("Geneva", 1, 16));
Border border = BorderFactory.createLineBorder(Color.ORANGE, 2);
userinfo.setBackground(Color.WHITE);
userinfo.setOpaque(true);
userinfo.setBorder(border);
userinfo.setAlignmentX(Component.CENTER_ALIGNMENT);
titol.add(userinfo);
titol.add(Box.createVerticalStrut(20));
comptime.setFont(new java.awt.Font("Geneva", 1, 16));
Border border2 = BorderFactory.createLineBorder(Color.CYAN, 2);
comptime.setBackground(Color.WHITE);
comptime.setOpaque(true);
comptime.setBorder(border2);
comptime.setAlignmentX(Component.CENTER_ALIGNMENT);
titol.add(comptime);
titol.add(Box.createVerticalStrut(20));
bestplayer.setFont(new java.awt.Font("Geneva", 1, 16));
Border border3 = BorderFactory.createLineBorder(Color.GREEN, 2);
bestplayer.setBackground(Color.WHITE);
bestplayer.setOpaque(true);
bestplayer.setBorder(border3);
bestplayer.setAlignmentX(Component.CENTER_ALIGNMENT);
titol.add(bestplayer);
jpInitialMenuCard.add(titol);
}
public void createSelectGameCard(){
JPanel titol = new JPanel();
titol.setLayout(new BoxLayout(titol, BoxLayout.PAGE_AXIS));
JLabel nomtitol = new JLabel("New Game");
nomtitol.setFont(new java.awt.Font("Geneva", 1, 40));
nomtitol.setAlignmentX(Component.CENTER_ALIGNMENT);
titol.add(Box.createVerticalStrut(25));
titol.add(nomtitol);
titol.add(Box.createVerticalStrut(55));
JPanel mode = new JPanel();
mode.setLayout(new BoxLayout(mode, BoxLayout.PAGE_AXIS));
JLabel jlselectmode = new JLabel("Select Mode");
jlselectmode.setFont(new java.awt.Font("Geneva", 1, 14));
jrbmemoria = new JRadioButton("Memory");
JPanel jpselectmode = new JPanel();
jpselectmode.setLayout(new GridLayout(1,4));
jpselectmode.add(new JPanel());
jpselectmode.add(jlselectmode);
jpselectmode.add(jrbmemoria);
jpselectmode.add(new JPanel());
jrbconcentracio = new JRadioButton("Concentration");
JPanel jpselect = new JPanel();
jpselect.setLayout(new GridLayout(1,4));
jpselect.add(new JPanel());
jpselect.add(new JPanel());
jpselect.add(jrbconcentracio);
jpselect.add(new JPanel());
ButtonGroup groupmode = new ButtonGroup();
groupmode.add(jrbmemoria);
groupmode.add(jrbconcentracio);
jpselectmode.setAlignmentX(Component.CENTER_ALIGNMENT);
jpselect.setAlignmentX(Component.CENTER_ALIGNMENT);
mode.add(jpselectmode);
mode.add(jpselect);
mode.setAlignmentX(Component.CENTER_ALIGNMENT);
titol.add(mode);
titol.add(Box.createVerticalStrut(25));
JPanel game = new JPanel();
game.setLayout(new BoxLayout(game, BoxLayout.PAGE_AXIS));
JLabel jlselectgame = new JLabel("Select Game(AI)");
jlselectgame.setFont(new java.awt.Font("Geneva", 1, 14));
jrbmachine = new JRadioButton("Machine");
JPanel jpselectgame = new JPanel();
jpselectgame.setLayout(new GridLayout(1,4));
jpselectgame.add(new JPanel());
jpselectgame.add(jlselectgame);
jpselectgame.add(jrbmachine);
jpselectgame.add(new JPanel());
jrbtimetrial = new JRadioButton("Time Trial");
JPanel jptimetrial = new JPanel();
jptimetrial.setLayout(new GridLayout(1,4));
jptimetrial.add(new JPanel());
jptimetrial.add(new JPanel());
jptimetrial.add(jrbtimetrial);
jptimetrial.add(new JPanel());
ButtonGroup groupgame2 = new ButtonGroup();
groupgame2.add(jrbmachine);
groupgame2.add(jrbtimetrial);
jpselectgame.setAlignmentX(Component.CENTER_ALIGNMENT);
jptimetrial.setAlignmentX(Component.CENTER_ALIGNMENT);
game.add(jpselectgame);
game.add(jptimetrial);
game.setAlignmentX(Component.CENTER_ALIGNMENT);
titol.add(game);
titol.add(Box.createVerticalStrut(25));
JPanel difficulty = new JPanel();
difficulty.setLayout(new BoxLayout(difficulty, BoxLayout.PAGE_AXIS));
JLabel jlselectdiff = new JLabel("Select Difficulty");
jlselectdiff.setFont(new java.awt.Font("Geneva", 1, 14));
jrbeasy = new JRadioButton("Easy");
JPanel jpeasy = new JPanel();
jpeasy.setLayout(new GridLayout(1,4));
jpeasy.add(new JPanel());
jpeasy.add(jlselectdiff);
jpeasy.add(jrbeasy);
jpeasy.add(new JPanel());
jrbmedium = new JRadioButton("Medium");
JPanel jpmedium = new JPanel();
jpmedium.setLayout(new GridLayout(1,4));
jpmedium.add(new JPanel());
jpmedium.add(new JPanel());
jpmedium.add(jrbmedium);
jpmedium.add(new JPanel());
jrbhard = new JRadioButton("Hard");
JPanel jphard = new JPanel();
jphard.setLayout(new GridLayout(1,4));
jphard.add(new JPanel());
jphard.add(new JPanel());
jphard.add(jrbhard);
jphard.add(new JPanel());
ButtonGroup groupdiff = new ButtonGroup();
groupdiff.add(jrbeasy);
groupdiff.add(jrbmedium);
groupdiff.add(jrbhard);
jpeasy.setAlignmentX(Component.CENTER_ALIGNMENT);
jpmedium.setAlignmentX(Component.CENTER_ALIGNMENT);
jphard.setAlignmentX(Component.CENTER_ALIGNMENT);
difficulty.add(jpeasy);
difficulty.add(jpmedium);
difficulty.add(jphard);
difficulty.setAlignmentX(Component.CENTER_ALIGNMENT);
titol.add(difficulty);
jpSelectGameCard.add(titol);
}
public boolean getmodeCon(){
if(jrbconcentracio.isSelected()){
return true;
}else{
return false;
}
}
public boolean getIA(){
if(jrbmachine.isSelected()){
return true;
}else{
return false;
}
}
public int getDifficulty(){
if(jrbeasy.isSelected()){
return 1;
}
if(jrbmedium.isSelected()){
return 2;
}
if(jrbhard.isSelected()){
return 3;
}
return -1;
}
public void createGameCard(){
title = new JPanel();
title.setLayout(new BoxLayout(title, BoxLayout.PAGE_AXIS));
JLabel nameTitle = new JLabel("Current Game");
nameTitle.setFont(new java.awt.Font("Geneva", 1, 34));
title.add(Box.createVerticalStrut(15));
nameTitle.setAlignmentX(Component.CENTER_ALIGNMENT);
title.add(nameTitle);
title.add(Box.createVerticalStrut(20));
timecomp.setFont(new java.awt.Font("Geneva", 1, 14));
Border border = BorderFactory.createLineBorder(Color.GREEN, 2);
timecomp.setBackground(Color.WHITE);
timecomp.setOpaque(true);
timecomp.setBorder(border);
timecomp.setAlignmentX(Component.CENTER_ALIGNMENT);
title.add(timecomp);
title.add(Box.createVerticalStrut(10));
iadifficulty.setFont(new java.awt.Font("Geneva", 1, 14));
Border border2 = BorderFactory.createLineBorder(Color.PINK, 2);
iadifficulty.setBackground(Color.WHITE);
iadifficulty.setOpaque(true);
iadifficulty.setBorder(border2);
iadifficulty.setAlignmentX(Component.CENTER_ALIGNMENT);
title.add(iadifficulty);
title.add(Box.createVerticalStrut(10));
mode.setFont(new java.awt.Font("Geneva", 1, 14));
Border border3 = BorderFactory.createLineBorder(Color.CYAN, 2);
mode.setBackground(Color.WHITE);
mode.setOpaque(true);
mode.setBorder(border3);
mode.setAlignmentX(Component.CENTER_ALIGNMENT);
title.add(mode);
title.add(Box.createVerticalStrut(30));
Border border4 = BorderFactory.createLineBorder(Color.DARK_GRAY, 1);
JLabel jlscore = new JLabel("Score:");
yourscore.setFont(new java.awt.Font("Geneva", 1, 14));
yourscore.setBorder(border4);
iascore.setFont(new java.awt.Font("Geneva", 1, 14));
iascore.setBorder(border4);
jlscore.setFont(new java.awt.Font("Geneva", 1, 14));
JPanel score = new JPanel();
score.setLayout(new GridLayout(1,5));
score.add(new JPanel());
score.add(jlscore);
score.add(new JPanel());
score.add(new JPanel());
score.add(new JPanel());
JPanel scorelabels = new JPanel();
scorelabels.setLayout(new GridLayout(1,5));
scorelabels.add(new JPanel());
scorelabels.add(yourscore);
scorelabels.add(new JPanel());
scorelabels.add(iascore);
scorelabels.add(new JPanel());
score.setAlignmentX(Component.CENTER_ALIGNMENT);
scorelabels.setAlignmentX(Component.CENTER_ALIGNMENT);
JLabel jltoprank = new JLabel("Top Ranking:");
jltoprank.setFont(new java.awt.Font("Geneva", 1, 14));
JPanel toprank = new JPanel();
toprank.setLayout(new GridLayout(1,5));
toprank.add(new JPanel());
toprank.add(jltoprank);
toprank.add(new JPanel());
toprank.add(new JPanel());
toprank.add(new JPanel());
toprank.setAlignmentX(Component.CENTER_ALIGNMENT);
panell = new JPanel();
String [][] mTopTen = new String [11][2];
tableGame = new JTable(mTopTen, columnNames);
tableGame.setPreferredSize(new Dimension(250, 125));
tableGame.setOpaque(false);
tableGame.setAlignmentX(Component.CENTER_ALIGNMENT);
panell.add(tableGame);
panell.setAlignmentX(Component.CENTER_ALIGNMENT);
title.add(score);
title.add(Box.createVerticalStrut(5));
title.add(scorelabels);
title.add(Box.createVerticalStrut(25));
title.add(toprank);
title.add(panell);
jpGameCard.add(title);
}
public void createRankingCard(){
title = new JPanel();
title.setLayout(new BoxLayout(title, BoxLayout.PAGE_AXIS));
JLabel nameTitle = new JLabel("Top 10 Ranking");
nameTitle.setFont(new java.awt.Font("Geneva", 1, 34));
title.add(Box.createVerticalStrut(15));
nameTitle.setAlignmentX(Component.CENTER_ALIGNMENT);
title.add(nameTitle);
title.add(Box.createVerticalStrut(15));
panell = new JPanel();
String [][] mTopTen = new String [11][2];
table = new JTable(mTopTen, columnNames);
table.setPreferredSize(new Dimension(500, 250));
table.setOpaque(false);
table.setAlignmentX(Component.CENTER_ALIGNMENT);
panell.add(table);
panell.setAlignmentX(Component.CENTER_ALIGNMENT);
title.add(panell);
jpRankingCard.add(title);
}
public void refreshRanking(String sTopTen){
String matrix[][] = new String [11][2];
String[] users = sTopTen.split("
int j = 0;
if (!sTopTen.equals(" ")){
for(int i=0;i<users.length;i++){
String[] aux = users[i].split("/");
matrix[j] = aux;
j++;
if(i==0 && !isGuest ){
refreshTop1("The best player of the competition is "+aux[0]+" with "+aux[1]+" points.");
}
}
DefaultTableModel model = new DefaultTableModel(matrix,columnNames);
table.setModel(model);
tableGame.setModel(model);
model.fireTableDataChanged();
}
}
public void refreshUser(UserClient actualUser){
if(isGuest){
userinfo.setText(" Hello, you're playing as a guest. ");
}else{
userinfo.setText(" Hello "+actualUser.getNickname()+", your actual score is: "+actualUser.getScore()+" ");
}
}
public void refreshTime(String time){
comptime.setText(" "+time+" ");
timecomp.setText(" "+time+" ");
}
public void refreshTop1(String top1){
bestplayer.setText(top1);
}
public void refreshMode(){
switch (getDifficulty()){
case 1:
if (getmodeCon()){
mode.setText(" Concentration mode : EASY ");
}else{
mode.setText(" Memory mode : EASY ");
}
break;
case 2:
if (getmodeCon()){
mode.setText(" Concentration mode : MEDIUM ");
}else{
mode.setText(" Memory mode : MEDIUM ");
}
break;
case 3:
if (getmodeCon()){
mode.setText(" Concentration mode : HARD ");
}else{
mode.setText(" Memory mode : HARD ");
}
break;
}
if (getIA()){
iadifficulty.setText(" Against A.I. ");
}
}
public void refreshScore(int score, int aiscore){
yourscore.setText(" Your score : "+score);
if (getIA()){
iascore.setVisible(true);
iascore.setText(" A.I. score : "+aiscore);
}else{
iascore.setVisible(false);
}
}
public void refreshGameTime(String time){
if (!getIA()){
iadifficulty.setText(" Time Trial : "+time);
}
}
public void showRegister(){
jtfnicknameR.setText("");
jpfpasswordR.setText("");
jtfname.setText("");
jtflastname.setText("");
cardLayout.show(jpMenu, "2");
jbBack.setVisible(true);
jbGoToMenu.setText("Register Profile");
jbGuest.setVisible(false);
jbRegister.setVisible(false);
}
public void showInitialMenu(){
cardLayout.show(jpMenu, "3");
jbBack.setVisible(false);
jbGoToMenu.setVisible(false);
jbGuest.setVisible(false);
jbRegister.setVisible(false);
jbStartGame.setVisible(false);
jbNewGame.setVisible(true);
jbRanking.setVisible(true);
jbLogOut.setVisible(true);
bestplayer.setVisible(true);
if(isGuest){
jbRanking.setVisible(false);
bestplayer.setVisible(false);
}
}
/**
* Fa visible la vista del ranking del client.
*/
public void showRanking(){
cardLayout.show(jpMenu, "6");
jbNewGame.setVisible(false);
jbRanking.setVisible(false);
jbLogOut.setVisible(false);
jbGoToMenu.setText("Menu");
jbGoToMenu.setVisible(true);
}
public void showLogIn(){
jtfnickname.setText("");
jpfpassword.setText("");
cardLayout.show(jpMenu, "1");
jbNewGame.setVisible(false);
jbRanking.setVisible(false);
jbLogOut.setVisible(false);
jbBack.setVisible(false);
jbGoToMenu.setText("Log In");
jbGoToMenu.setVisible(true);
jbRegister.setVisible(true);
jbGuest.setVisible(true);
}
public void showSelectGame(){
cardLayout.show(jpMenu, "4");
jbNewGame.setVisible(false);
jbRanking.setVisible(false);
jbLogOut.setVisible(false);
jbGoToMenu.setText("Back to Menu");
jbGoToMenu.setVisible(true);
jbStartGame.setVisible(true);
jrbmemoria.setSelected(false);
jrbconcentracio.setSelected(false);
jrbmachine.setSelected(false);
jrbtimetrial.setSelected(false);
jrbeasy.setSelected(false);
jrbmedium.setSelected(false);
jrbhard.setSelected(false);
}
public void showGame(){
cardLayout.show(jpMenu, "5");
jbStartGame.setVisible(false);
jbGoToMenu.setText("End Game");
jbGoToMenu.setVisible(true);
}
public void makeDialog(String message, boolean type){
if(type){
Dialog.DialogOK(message);
}else{
Dialog.DialogKO(message);
}
}
}
|
package apmon;
import apmon.host.HostPropertiesMonitor;
import apmon.host.Parser;
import apmon.host.cmdExec;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Separate thread which periodically checks the configuration file/URLs for changes and periodically sends datagrams
* with monitoring information.
*/
class BkThread extends Thread {
/* types of operations that this thread executes */
public static final int RECHECK_CONF = 0;
public static final int SYS_INFO_SEND = 1;
public static final int JOB_INFO_SEND = 2;
static String osName = System.getProperty("os.name");
private static Logger logger = Logger.getLogger("apmon");
ApMon apm;
boolean hasToRun = true;
/* LISA object used for obtaining system monitoring information */
HostPropertiesMonitor monitor = null;
public BkThread(ApMon apm) {
this.apm = apm;
this.monitor = new HostPropertiesMonitor();
this.setDaemon(true);
}
public static Hashtable getCpuInfo() throws IOException, ApMonException {
if (osName.indexOf("Linux") < 0)
return null;
Hashtable info = new Hashtable();
BufferedReader in = null;
FileReader fr = null;
try {
fr = new FileReader("/proc/cpuinfo");
in = new BufferedReader(fr);
String line = null;
while ((line = in.readLine()) != null) {
StringTokenizer st = new StringTokenizer(line, ":");
if (line.startsWith("cpu MHz")) {
st.nextToken();
String freq_s = st.nextToken();
if (freq_s == null)
throw new ApMonException("Error reading CPU frequency from /proc/cpuinfo");
info.put(ApMonMonitoringConstants.LGEN_CPU_MHZ, freq_s);
}
if (line.startsWith("vendor_id")) {
st.nextToken();
String vendor = st.nextToken();
if (vendor == null)
throw new ApMonException("Error reading CPU vendor_id from /proc/cpuinfo");
info.put(ApMonMonitoringConstants.LGEN_CPU_VENDOR_ID, vendor);
}
if (line.startsWith("model") && !line.startsWith("model name")) {
st.nextToken();
String model = st.nextToken();
if (model == null)
throw new ApMonException("Error reading CPU model from /proc/cpuinfo");
info.put(ApMonMonitoringConstants.LGEN_CPU_MODEL, model);
}
if (line.startsWith("cpu family")) {
st.nextToken();
String cpufam = st.nextToken();
if (cpufam == null)
throw new ApMonException("Error reading CPU family from /proc/cpuinfo");
info.put(ApMonMonitoringConstants.LGEN_CPU_FAMILY, cpufam);
}
if (line.startsWith("model name")) {
st.nextToken();
String modelname = st.nextToken();
if (modelname == null)
throw new ApMonException("Error reading CPU model name from /proc/cpuinfo");
info.put(ApMonMonitoringConstants.LGEN_CPU_MODEL_NAME, modelname);
}
if (line.startsWith("bogomips")) {
st.nextToken();
String bogomips = st.nextToken();
if (bogomips == null)
throw new ApMonException("Error reading CPU bogomips from /proc/cpuinfo");
info.put(ApMonMonitoringConstants.LGEN_BOGOMIPS, bogomips);
}
}
} finally {
if (fr != null) {
try {
fr.close();
} catch (Throwable ignore) {
}
}
if (in != null) {
try {
in.close();
} catch (Throwable ignore) {
}
}
}
return info;
}
/**
* Returns the system boot time in milliseconds since the Epoch. Works only on Linux systems.
*/
public static long getBootTime() throws IOException, ApMonException {
if (osName.indexOf("Linux") < 0)
return 0;
BufferedReader in = null;
FileReader fr = null;
try {
fr = new FileReader("/proc/stat");
in = new BufferedReader(fr);
String line = null;
while ((line = in.readLine()) != null) {
if (line.startsWith("btime"))
break;
}
if (line == null)
throw new ApMonException("Error reading boot time from /proc/stat");
StringTokenizer st = new StringTokenizer(line);
st.nextToken();
String btime_s = st.nextToken();
if (btime_s == null)
throw new ApMonException("Error reading boot time from /proc/stat");
return (Long.parseLong(btime_s) * 1000);
} finally {
if (fr != null) {
try {
fr.close();
} catch (Throwable ignore) {
}
}
if (in != null) {
try {
in.close();
} catch (Throwable ignore) {
}
}
}
}
/* in days */
public static double getUpTime() throws IOException, ApMonException {
if (osName.indexOf("Linux") < 0)
return 0;
FileReader fr = null;
BufferedReader in = null;
try {
fr = new FileReader("/proc/uptime");
in = new BufferedReader(fr);
String line = in.readLine();
if (line == null)
throw new ApMonException("Error reading boot time from /proc/uptime");
StringTokenizer st = new StringTokenizer(line);
String up_time = st.nextToken();
if (up_time == null)
throw new ApMonException("Error reading optime from /proc/uptime");
return (Double.parseDouble(up_time)) / (3600 * 24);
} finally {
if (fr != null) {
try {
fr.close();
} catch (Throwable ignore) {
}
}
if (in != null) {
try {
in.close();
} catch (Throwable ignore) {
}
}
}
}
/**
* Returns the number of CPUs in the system
*/
public static int getNumCPUs() throws IOException, ApMonException {
if (osName.indexOf("Linux") < 0)
return 0;
FileReader fr = null;
BufferedReader in = null;
try {
fr = new FileReader("/proc/stat");
in = new BufferedReader(fr);
String line = null;
int numCPUs = 0;
while ((line = in.readLine()) != null) {
if (line.startsWith("cpu") && Character.isDigit(line.charAt(3)))
numCPUs++;
}
if (numCPUs == 0)
throw new ApMonException("Error reading CPU frequency from /proc/stat");
return numCPUs;
} finally {
if (fr != null) {
try {
fr.close();
} catch (Throwable ignore) {
}
}
if (in != null) {
try {
in.close();
} catch (Throwable ignore) {
}
}
}
}
public static void getNetConfig(Vector netInterfaces, Vector ips) throws IOException, ApMonException {
String line;
Parser parser = new Parser();
cmdExec exec = new cmdExec();
String output = exec.executeCommandReality("/sbin/ifconfig -a", "");
if (exec.isError())
output = null;
exec.stopIt();
String crtIfaceName = null;
if (output != null && !output.equals("")) {
parser.parse(output);
line = parser.nextLine();
while (line != null) {
if (line == null)
break;
StringTokenizer lst = new StringTokenizer(line, " :\t");
if (line.startsWith(" ") || line.startsWith("\t")) {
if (line.indexOf("inet") < 0) {
line = parser.nextLine();
continue;
}
lst.nextToken();
lst.nextToken();
String addr_t = lst.nextToken();
if (!addr_t.equals("127.0.0.1")) {
ips.add(addr_t);
netInterfaces.add(crtIfaceName);
}
} else {
// get the name
String netName = lst.nextToken();
if (netName != null && !netName.startsWith("lo") && netName.indexOf("eth") != -1) {
crtIfaceName = new String(netName);
}
}
line = parser.nextLine();
}
}
}
void stopIt() {
hasToRun = false;
}
/**
* Returns true if the given parameter is set to be included in the system monitoring packet.
*/
boolean isActive_Sys(long param) {
return ((apm.sysMonitorParams & param) == param);
}
boolean isActive_Sys(Long param) {
return isActive_Sys(param.longValue());
}
/**
* Returns true if the given parameter is set to be included in the job monitoring packet.
*/
boolean isActive_Job(long param) {
return ((apm.jobMonitorParams & param) == param);
}
boolean isActive_Job(Long param) {
return isActive_Job(param.longValue());
}
/**
* Returns true if the given parameter is set to be included in the general system monitoring packet.
*/
boolean isActive_Gen(long param) {
return ((apm.genMonitorParams & param) == param);
}
boolean isActive_Gen(Long param) {
return isActive_Gen(param.longValue());
}
void sendJobInfo() {
int i;
synchronized (apm.mutexBack) {
if (apm.monJobs.size() == 0) {
logger.warning("There are not jobs to be monitored, not sending job monitoring information...");
return;
}
Date d = new Date();
logger.info("Sending job monitoring information...");
apm.lastJobInfoSend = d.getTime();
for (i = 0; i < apm.monJobs.size(); i++)
sendOneJobInfo(((MonitoredJob) apm.monJobs.get(i)));
}
}
/**
* Sends an UDP datagram with job monitoring information. Works only in Linux system; on other systems it takes no
* action.
*/
void sendOneJobInfo(MonitoredJob monJob) {
Vector paramNames, paramValues;
// , valueTypes;
long crtTime = System.currentTimeMillis();
apm.lastJobInfoSend = crtTime;
paramNames = new Vector();
paramValues = new Vector();
// valueTypes = new Vector();
HashMap hmJobInfo = null;
try {
hmJobInfo = monJob.readJobInfo();
} catch (IOException e) {
logger.warning("Unable to read job info for " + monJob.getPid());
hmJobInfo = null;
}
if (hmJobInfo == null) {
logger.warning("Job " + monJob.pid + " does not exist");
apm.removeJobToMonitor(monJob.pid);
return;
}
HashMap hmJobDisk = null;
try {
hmJobDisk = monJob.readJobDiskUsage();
} catch (Throwable t1) {
logger.warning("Unable to read job Disk Usage info for " + monJob.getPid());
hmJobDisk = null;
}
// hmJobInfo != null FOR SURE!
HashMap hm = hmJobInfo;
if (hmJobDisk != null) {
hm.putAll(hmJobDisk);
}
for (Iterator it = hm.keySet().iterator(); it.hasNext(); ) {
Long lParam = (Long) it.next();
try {
if (isActive_Job(lParam)) {
Double val = (Double) hm.get(lParam);
paramNames.add(ApMonMonitoringConstants.getJobMLParamName(lParam));
paramValues.add(val);
// valueTypes.add(new Integer(ApMon.XDR_REAL64));
}
} catch (Throwable t) {
logger.log(Level.WARNING, "", t);
if (apm.autoDisableMonitoring) {
logger.warning("parameter " + ApMonMonitoringConstants.getJobName(lParam) + " disabled");
apm.sysMonitorParams &= ~lParam.longValue();
}
}
}
try {
apm.sendParameters(monJob.clusterName, monJob.nodeName, paramNames.size(), paramNames, paramValues);
} catch (Exception e) {
logger.warning("Error while sending system information: " + e);
}
}
/**
* Sends an UDP datagram with system monitoring information
*/
void sendSysInfo() {
double value = 0.0;
Vector paramNames, paramValues;
// , valueTypes;
monitor.updateCall();
long crtTime = System.currentTimeMillis();
logger.log(Level.FINER,"Sending system monitoring information...");
// long intervalLength = crtTime - apm.lastSysInfoSend;
apm.lastSysInfoSend = crtTime;
paramNames = new Vector();
paramValues = new Vector();
// valueTypes = new Vector();
HashMap hms = monitor.getHashParams();
if (hms != null) {
for (Iterator it = hms.keySet().iterator(); it.hasNext(); ) {
Long lParam = (Long) it.next();
try {
if (isActive_Sys(lParam)) {
Double val = Double.valueOf((String) hms.get(lParam));
paramNames.add(ApMonMonitoringConstants.getSysMLParamName(lParam));
paramValues.add(val);
// valueTypes.add(new Integer(ApMon.XDR_REAL64));
}
} catch (Throwable t) {
if (apm.autoDisableMonitoring) {
logger.warning("parameter " + ApMonMonitoringConstants.getSysName(lParam) + " disabled");
apm.sysMonitorParams &= ~lParam.longValue();
}
}
}
}
if (apm.netInterfaces != null && apm.netInterfaces.size() != 0) {
for (int i = 0; i < apm.netInterfaces.size(); i++) {
String iName = (String) apm.netInterfaces.get(i);
if (iName == null)
continue;
try {
if (isActive_Sys(ApMonMonitoringConstants.SYS_NET_IN)) {
value = Double.parseDouble(monitor.getNetInCall(iName));
if (osName.indexOf("Mac") == -1)
// measure in KBps
value = value * 1024;
paramNames.add(iName + "_" + ApMonMonitoringConstants.getSysMLParamName(ApMonMonitoringConstants.SYS_NET_IN));
paramValues.add(new Double(value));
// valueTypes.add(new Integer(ApMon.XDR_REAL64));
}
} catch (Throwable t) {
logger.log(Level.WARNING, "", t);
// should not disable ... can work for the other interfaces
}
try {
if (isActive_Sys(ApMonMonitoringConstants.SYS_NET_OUT)) {
value = Double.parseDouble(monitor.getNetOutCall(iName));
if (osName.indexOf("Mac") == -1)
// measure in KBps
value = value * 1024;
paramNames.add(iName + "_" + ApMonMonitoringConstants.getSysMLParamName(ApMonMonitoringConstants.SYS_NET_OUT));
paramValues.add(new Double(value));
// valueTypes.add(new Integer(ApMon.XDR_REAL64));
}
} catch (Throwable t) {
logger.log(Level.WARNING, "", t);
;
// should not disable ... can work for the other interfaces
}
}
}
if (isActive_Sys(ApMonMonitoringConstants.SYS_UPTIME)) {
try {
value = getUpTime();
paramNames.add(ApMonMonitoringConstants.getSysMLParamName(ApMonMonitoringConstants.SYS_UPTIME));
paramValues.add(new Double(value));
// valueTypes.add(new Integer(ApMon.XDR_REAL64));
} catch (Exception e) {
logger.log(Level.WARNING, "", e);
;
if (apm.autoDisableMonitoring) {
logger.warning("parameter sys_uptime disabled");
apm.sysMonitorParams &= ~ApMonMonitoringConstants.SYS_UPTIME;
}
}
}
if (isActive_Sys(ApMonMonitoringConstants.SYS_PROCESSES)) {
try {
Hashtable vals = monitor.getPState();
Enumeration e = vals.keys();
while (e.hasMoreElements()) {
String name = (String) e.nextElement();
Integer val = (Integer) vals.get(name);
paramNames.add(ApMonMonitoringConstants.getSysMLParamName(ApMonMonitoringConstants.SYS_PROCESSES) + "_" + name);
paramValues.add(val);
// valueTypes.add(new Integer(ApMon.XDR_INT32));
}
} catch (Exception e) {
logger.log(Level.WARNING, "", e);
;
if (apm.autoDisableMonitoring) {
logger.warning("parameter processes disabled");
apm.sysMonitorParams &= ~ApMonMonitoringConstants.SYS_PROCESSES;
}
}
}
if (isActive_Sys(ApMonMonitoringConstants.SYS_NET_SOCKETS)) {
try {
Hashtable vals = monitor.getSockets();
Enumeration e = vals.keys();
while (e.hasMoreElements()) {
String name = (String) e.nextElement();
Integer val = (Integer) vals.get(name);
paramNames.add(ApMonMonitoringConstants.getSysMLParamName(ApMonMonitoringConstants.SYS_NET_SOCKETS) + "_" + name);
paramValues.add(val);
// valueTypes.add(new Integer(ApMon.XDR_INT32));
}
} catch (Exception e) {
logger.log(Level.WARNING, "", e);
;
if (apm.autoDisableMonitoring) {
logger.warning("parameter processes disabled");
apm.sysMonitorParams &= ~ApMonMonitoringConstants.SYS_NET_SOCKETS;
}
}
}
if (isActive_Sys(ApMonMonitoringConstants.SYS_NET_TCP_DETAILS)) {
try {
Hashtable vals = monitor.getTCPDetails();
Enumeration e = vals.keys();
while (e.hasMoreElements()) {
String name = (String) e.nextElement();
Integer val = (Integer) vals.get(name);
paramNames.add(ApMonMonitoringConstants.getSysMLParamName(ApMonMonitoringConstants.SYS_NET_TCP_DETAILS) + "_" + name);
paramValues.add(val);
// valueTypes.add(new Integer(ApMon.XDR_INT32));
}
} catch (Exception e) {
logger.log(Level.WARNING, "", e);
if (apm.autoDisableMonitoring) {
logger.warning("parameter processes disabled");
apm.sysMonitorParams &= ~ApMonMonitoringConstants.SYS_NET_TCP_DETAILS;
}
}
}
try {
apm.sendParameters(apm.sysClusterName, apm.sysNodeName, paramNames.size(), paramNames, paramValues);
} catch (Exception e) {
logger.warning("Error while sending system information: " + e);
}
}
/**
* Sends an UDP datagram with general system monitoring information. Only works with Linux systems; on other systems
* it is disabled.
*/
void sendGeneralInfo() {
Vector paramNames, paramValues;
// , valueTypes;
double cpu_MHz, bogomips;
int no_CPUs, i;
paramNames = new Vector();
paramValues = new Vector();
// valueTypes = new Vector();
paramNames.add("hostname");
paramValues.add(apm.myHostname);
// valueTypes.add(new Integer(ApMon.XDR_STRING));
for (i = 0; i < apm.netInterfaces.size(); i++) {
try {
paramNames.add("ip_" + apm.netInterfaces.get(i));
paramValues.add(apm.allMyIPs.get(i));
// valueTypes.add(new Integer(ApMon.XDR_STRING));
} catch (Exception e) {
logger.log(Level.FINE, "BkThread got exception, ignoring network interface: ", e);
}
}
Hashtable cpuInfo = new Hashtable();
try {
cpuInfo = getCpuInfo();
} catch (Exception e) {
e.printStackTrace();
}
if (isActive_Gen(ApMonMonitoringConstants.GEN_CPU_MHZ)) {
try {
cpu_MHz = Double.parseDouble((String) cpuInfo.get(ApMonMonitoringConstants.LGEN_CPU_MHZ));
paramNames.add(ApMonMonitoringConstants.getGenMLParamName(ApMonMonitoringConstants.LGEN_CPU_MHZ));
paramValues.add(new Double(cpu_MHz));
// valueTypes.add(new Integer(ApMon.XDR_REAL64));
} catch (Throwable t) {
logger.log(Level.WARNING, "", t);
if (apm.autoDisableMonitoring)
apm.genMonitorParams &= ~ApMonMonitoringConstants.GEN_CPU_MHZ;
}
}
String val;
if (isActive_Gen(ApMonMonitoringConstants.GEN_CPU_VENDOR_ID)) {
try {
val = ((String) cpuInfo.get(ApMonMonitoringConstants.LGEN_CPU_VENDOR_ID)).trim();
paramNames.add(ApMonMonitoringConstants.getGenMLParamName(ApMonMonitoringConstants.LGEN_CPU_VENDOR_ID));
paramValues.add(val);
// valueTypes.add(new Integer(ApMon.XDR_STRING));
} catch (Throwable t) {
logger.log(Level.WARNING, "", t);
if (apm.autoDisableMonitoring)
apm.genMonitorParams &= ~ApMonMonitoringConstants.GEN_CPU_VENDOR_ID;
}
}
if (isActive_Gen(ApMonMonitoringConstants.GEN_CPU_FAMILY)) {
try {
val = ((String) cpuInfo.get(ApMonMonitoringConstants.LGEN_CPU_FAMILY)).trim();
paramNames.add(ApMonMonitoringConstants.getGenMLParamName(ApMonMonitoringConstants.LGEN_CPU_FAMILY));
paramValues.add(val);
// valueTypes.add(new Integer(ApMon.XDR_STRING));
} catch (Throwable t) {
logger.log(Level.WARNING, "", t);
if (apm.autoDisableMonitoring)
apm.genMonitorParams &= ~ApMonMonitoringConstants.GEN_CPU_FAMILY;
}
}
if (isActive_Gen(ApMonMonitoringConstants.GEN_CPU_MODEL)) {
try {
val = ((String) cpuInfo.get(ApMonMonitoringConstants.LGEN_CPU_MODEL)).trim();
paramNames.add(ApMonMonitoringConstants.getGenMLParamName(ApMonMonitoringConstants.LGEN_CPU_MODEL));
paramValues.add(val);
// valueTypes.add(new Integer(ApMon.XDR_STRING));
} catch (Throwable t) {
logger.log(Level.WARNING, "", t);
if (apm.autoDisableMonitoring)
apm.genMonitorParams &= ~ApMonMonitoringConstants.GEN_CPU_MODEL;
}
}
if (isActive_Gen(ApMonMonitoringConstants.GEN_CPU_MODEL_NAME)) {
try {
val = ((String) cpuInfo.get(ApMonMonitoringConstants.LGEN_CPU_MODEL_NAME)).trim();
paramNames.add(ApMonMonitoringConstants.getGenMLParamName(ApMonMonitoringConstants.LGEN_CPU_MODEL_NAME));
paramValues.add(val);
// valueTypes.add(new Integer(ApMon.XDR_STRING));
} catch (Throwable t) {
logger.log(Level.WARNING, "", t);
if (apm.autoDisableMonitoring)
apm.genMonitorParams &= ~ApMonMonitoringConstants.GEN_CPU_MODEL_NAME;
}
}
if (isActive_Gen(ApMonMonitoringConstants.GEN_BOGOMIPS)) {
try {
bogomips = Double.parseDouble((String) cpuInfo.get(ApMonMonitoringConstants.LGEN_BOGOMIPS));
paramNames.add(ApMonMonitoringConstants.getGenMLParamName(ApMonMonitoringConstants.LGEN_BOGOMIPS));
paramValues.add(new Double(bogomips));
// valueTypes.add(new Integer(ApMon.XDR_REAL64));
} catch (Throwable t) {
logger.log(Level.WARNING, "", t);
if (apm.autoDisableMonitoring)
apm.genMonitorParams &= ~ApMonMonitoringConstants.GEN_BOGOMIPS;
}
}
if (isActive_Gen(ApMonMonitoringConstants.GEN_NO_CPUS)) {
try {
no_CPUs = getNumCPUs();
paramNames.add(ApMonMonitoringConstants.getGenMLParamName(ApMonMonitoringConstants.LGEN_NO_CPUS));
paramValues.add(new Integer(no_CPUs));
// valueTypes.add(new Integer(ApMon.XDR_INT32));
} catch (Throwable t) {
logger.log(Level.WARNING, "", t);
if (apm.autoDisableMonitoring)
apm.genMonitorParams &= ~ApMonMonitoringConstants.GEN_NO_CPUS;
}
}
if (isActive_Gen(ApMonMonitoringConstants.GEN_TOTAL_MEM)) {
try {
Double tm = Double.valueOf(monitor.getMemTotalCall());
paramNames.add(ApMonMonitoringConstants.getGenName(ApMonMonitoringConstants.LGEN_TOTAL_MEM));
paramValues.add(tm);
// valueTypes.add(new Integer(ApMon.XDR_REAL64));
} catch (Throwable t) {
logger.log(Level.WARNING, "", t);
;
if (apm.autoDisableMonitoring)
apm.genMonitorParams &= ~ApMonMonitoringConstants.GEN_TOTAL_MEM;
}
}
if (isActive_Gen(ApMonMonitoringConstants.GEN_TOTAL_SWAP)) {
try {
Double tm = Double.valueOf(monitor.getSwapTotalCall());
paramNames.add(ApMonMonitoringConstants.getGenName(ApMonMonitoringConstants.LGEN_TOTAL_SWAP));
paramValues.add(tm);
// valueTypes.add(new Integer(ApMon.XDR_REAL64));
} catch (Throwable t) {
logger.log(Level.WARNING, "", t);
;
if (apm.autoDisableMonitoring)
apm.genMonitorParams &= ~ApMonMonitoringConstants.GEN_TOTAL_SWAP;
}
}
try {
apm.sendParameters(apm.sysClusterName, apm.sysNodeName, paramNames.size(), paramNames, paramValues);
} catch (Exception e) {
logger.warning("Error while sending general system information: " + e);
}
}
public void run() {
long crtTime, timeRemained, nextOpTime;
long nextRecheck = 0, nextJobInfoSend = 0, nextSysInfoSend = 0;
int generalInfoCount;
int nextOp = 0;
boolean haveChange, haveTimeout;
logger.info("[Starting background thread...]");
crtTime = System.currentTimeMillis();
synchronized (apm.mutexBack) {
if (apm.confCheck) {
nextRecheck = crtTime + apm.crtRecheckInterval * 1000;
}
if (apm.jobMonitoring)
nextJobInfoSend = crtTime + apm.jobMonitorInterval * 1000;
if (apm.sysMonitoring)
nextSysInfoSend = crtTime + apm.sysMonitorInterval * 1000;
}
timeRemained = nextOpTime = -1;
generalInfoCount = 0;
while (hasToRun) {
crtTime = System.currentTimeMillis();
/* determine the next operation that must be performed */
if (nextRecheck > 0 && (nextJobInfoSend <= 0 || nextRecheck <= nextJobInfoSend)) {
if (nextSysInfoSend <= 0 || nextRecheck <= nextSysInfoSend) {
nextOp = RECHECK_CONF;
nextOpTime = nextRecheck;
} else {
nextOp = SYS_INFO_SEND;
nextOpTime = nextSysInfoSend;
}
} else {
if (nextJobInfoSend > 0 && (nextSysInfoSend <= 0 || nextJobInfoSend <= nextSysInfoSend)) {
nextOp = JOB_INFO_SEND;
nextOpTime = nextJobInfoSend;
} else if (nextSysInfoSend > 0) {
nextOp = SYS_INFO_SEND;
nextOpTime = nextSysInfoSend;
}
}
if (nextOpTime == -1)
nextOpTime = crtTime + ApMon.RECHECK_INTERVAL * 1000;
synchronized (apm.mutexCond) {
synchronized (apm.mutexBack) {
/* check for changes in the settings */
haveChange = false;
if (apm.jobMonChanged || apm.sysMonChanged || apm.recheckChanged)
haveChange = true;
if (apm.jobMonChanged) {
if (apm.jobMonitoring)
nextJobInfoSend = crtTime + apm.jobMonitorInterval * 1000;
else
nextJobInfoSend = -1;
apm.jobMonChanged = false;
}
if (apm.sysMonChanged) {
if (apm.sysMonitoring)
nextSysInfoSend = crtTime + apm.sysMonitorInterval * 1000;
else
nextSysInfoSend = -1;
apm.sysMonChanged = false;
}
if (apm.recheckChanged) {
if (apm.confCheck)
nextRecheck = crtTime + apm.crtRecheckInterval * 1000;
else
nextRecheck = -1;
apm.recheckChanged = false;
}
} // synchronized(apm.mutexBack)
if (haveChange)
continue;
timeRemained = nextOpTime - System.currentTimeMillis();
haveTimeout = true;
/*
* wait until the next operation should be performed or until a change in the settings occurs
*/
try {
if (timeRemained > 0)
apm.mutexCond.wait(timeRemained);
} catch (InterruptedException e) {
}
if (apm.condChanged) {
haveTimeout = false;
}
apm.condChanged = false;
}
// logger.info("### have timeout " + haveTimeout);
crtTime = System.currentTimeMillis();
// System.out.println("### 3 crtTime " + crtTime + " nextOpTime " + nextOpTime);
if (haveTimeout) { // the time interval until the next operation expired
/* now perform the operation */
if (nextOp == JOB_INFO_SEND) {
sendJobInfo();
nextJobInfoSend = crtTime + apm.getJobMonitorInterval() * 1000;
}
if (nextOp == SYS_INFO_SEND) {
sendSysInfo();
if (apm.getGenMonitoring()) {
/*
* send only 2 general monitoring packets in genMonitorIntervals intervals
*/
if (generalInfoCount <= 1)
sendGeneralInfo();
generalInfoCount = (generalInfoCount + 1) % apm.genMonitorIntervals;
}
nextSysInfoSend = crtTime + apm.getSysMonitorInterval() * 1000;
}
if (nextOp == RECHECK_CONF) {
/* check all the configuration resources (file, URLs) */
Enumeration e = apm.confResources.keys();
boolean resourceChanged = false;
try {
while (e.hasMoreElements()) {
Object obj = e.nextElement();
Long lastModified = (Long) apm.confResources.get(obj);
if (obj instanceof File) {
File f = (File) obj;
logger.info(" [Checking for modifications for " + f.getCanonicalPath() + "]");
long lmt = f.lastModified();
if (lmt > lastModified.longValue()) {
logger.info("[File " + f.getCanonicalPath() + " modified]");
resourceChanged = true;
break;
// confResources.put(f, new Long(lmt));
}
}
if (obj instanceof URL) {
URL u = (URL) obj;
long lmt = 0;
logger.info("[Checking for modifications for " + u + "]");
URLConnection urlConn = u.openConnection();
lmt = urlConn.getLastModified();
if (lmt > lastModified.longValue() || lmt == 0) {
logger.info("[Location " + u + " modified]");
resourceChanged = true;
break;
}
}
} // while
/*
* if any resource has changed we have to recheck all the others, otherwise some destinations
* might be ommitted
*/
if (resourceChanged) {
if (apm.initType == ApMon.FILE_INIT) {
apm.initialize((String) apm.initSource, false);
}
if (apm.initType == ApMon.LIST_INIT) {
apm.initialize((Vector) apm.initSource, false);
}
}
apm.setCrtRecheckInterval(apm.getRecheckInterval());
} catch (Throwable exc) {
apm.setCrtRecheckInterval(10 * apm.getRecheckInterval());
}
crtTime = System.currentTimeMillis();
nextRecheck = crtTime + apm.getRecheckInterval() * 1000;
} // while
}
}
}
}
|
package com.mychess.mychess;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.IBinder;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.mychess.mychess.Chess.Chess;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.ArrayList;
public class Juego extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, View.OnClickListener {
Servicio mService;
boolean mBound = false;
ImageView casillas[][] = new ImageView[8][8];
ImageView origen;
ImageView destino;
TextView tiempo;
Tiempo tiempoMovimiento;
int cOrigen;
int cDestino;
int fOrigen;
int fDestino;
boolean enroqueBlanco = true;
boolean enroqueNegro = true;
boolean jugadaLocal = true;// sirve para difenciar entre una jugada local y una remota
Chess chess;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_juego);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
inicializarCasillasBlanco();
setOnclickListener();
setDefaultColor();
tiempo = (TextView) findViewById(R.id.textView18);
tiempoMovimiento = new Tiempo();
tiempoMovimiento.iniciar();
/* inicializcion del nuevo juego*/
chess = new Chess();
chess.newGame();
new SocketServidor().conectar();
RecibirMovimientos recibirMovimientos = new RecibirMovimientos();
recibirMovimientos.execute();
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(jugadaLocal) {
SpeechRecognizer speechRecognizer = SpeechRecognizer.createSpeechRecognizer(Juego.this);
Speech speech = new Speech();
speechRecognizer.setRecognitionListener(speech);
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
speechRecognizer.startListening(intent);
}else
Toast.makeText(Juego.this, "No es su turno", Toast.LENGTH_SHORT).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
@Override
protected void onStart() {
super.onStart();
Intent intent = new Intent(this, Servicio.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
Servicio.LocalBinder binder = (Servicio.LocalBinder) service;
mService = binder.getService();
mBound = true;
}
@Override
public void onServiceDisconnected(ComponentName name) {
mBound = false;
}
};
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.juego, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.jugar) {
// Handle the camera action
} else if (id == R.id.amigos) {
Intent intent = new Intent(Juego.this, Amigos.class);
startActivity(intent);
} else if (id == R.id.logout) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private void inicializarCasillasBlanco() {
casillas[0][0] = (ImageView) findViewById(R.id.a8);
casillas[0][1] = (ImageView) findViewById(R.id.a7);
casillas[0][2] = (ImageView) findViewById(R.id.a6);
casillas[0][3] = (ImageView) findViewById(R.id.a5);
casillas[0][4] = (ImageView) findViewById(R.id.a4);
casillas[0][5] = (ImageView) findViewById(R.id.a3);
casillas[0][6] = (ImageView) findViewById(R.id.a2);
casillas[0][7] = (ImageView) findViewById(R.id.a1);
casillas[1][0] = (ImageView) findViewById(R.id.b8);
casillas[1][1] = (ImageView) findViewById(R.id.b7);
casillas[1][2] = (ImageView) findViewById(R.id.b6);
casillas[1][3] = (ImageView) findViewById(R.id.b5);
casillas[1][4] = (ImageView) findViewById(R.id.b4);
casillas[1][5] = (ImageView) findViewById(R.id.b3);
casillas[1][6] = (ImageView) findViewById(R.id.b2);
casillas[1][7] = (ImageView) findViewById(R.id.b1);
casillas[2][0] = (ImageView) findViewById(R.id.c8);
casillas[2][1] = (ImageView) findViewById(R.id.c7);
casillas[2][2] = (ImageView) findViewById(R.id.c6);
casillas[2][3] = (ImageView) findViewById(R.id.c5);
casillas[2][4] = (ImageView) findViewById(R.id.c4);
casillas[2][5] = (ImageView) findViewById(R.id.c3);
casillas[2][6] = (ImageView) findViewById(R.id.c2);
casillas[2][7] = (ImageView) findViewById(R.id.c1);
casillas[3][0] = (ImageView) findViewById(R.id.d8);
casillas[3][1] = (ImageView) findViewById(R.id.d7);
casillas[3][2] = (ImageView) findViewById(R.id.d6);
casillas[3][3] = (ImageView) findViewById(R.id.d5);
casillas[3][4] = (ImageView) findViewById(R.id.d4);
casillas[3][5] = (ImageView) findViewById(R.id.d3);
casillas[3][6] = (ImageView) findViewById(R.id.d2);
casillas[3][7] = (ImageView) findViewById(R.id.d1);
casillas[4][0] = (ImageView) findViewById(R.id.e8);
casillas[4][1] = (ImageView) findViewById(R.id.e7);
casillas[4][2] = (ImageView) findViewById(R.id.e6);
casillas[4][3] = (ImageView) findViewById(R.id.e5);
casillas[4][4] = (ImageView) findViewById(R.id.e4);
casillas[4][5] = (ImageView) findViewById(R.id.e3);
casillas[4][6] = (ImageView) findViewById(R.id.e2);
casillas[4][7] = (ImageView) findViewById(R.id.e1);
casillas[5][0] = (ImageView) findViewById(R.id.f8);
casillas[5][1] = (ImageView) findViewById(R.id.f7);
casillas[5][2] = (ImageView) findViewById(R.id.f6);
casillas[5][3] = (ImageView) findViewById(R.id.f5);
casillas[5][4] = (ImageView) findViewById(R.id.f4);
casillas[5][5] = (ImageView) findViewById(R.id.f3);
casillas[5][6] = (ImageView) findViewById(R.id.f2);
casillas[5][7] = (ImageView) findViewById(R.id.f1);
casillas[6][0] = (ImageView) findViewById(R.id.g8);
casillas[6][1] = (ImageView) findViewById(R.id.g7);
casillas[6][2] = (ImageView) findViewById(R.id.g6);
casillas[6][3] = (ImageView) findViewById(R.id.g5);
casillas[6][4] = (ImageView) findViewById(R.id.g4);
casillas[6][5] = (ImageView) findViewById(R.id.g3);
casillas[6][6] = (ImageView) findViewById(R.id.g2);
casillas[6][7] = (ImageView) findViewById(R.id.g1);
casillas[7][0] = (ImageView) findViewById(R.id.h8);
casillas[7][1] = (ImageView) findViewById(R.id.h7);
casillas[7][2] = (ImageView) findViewById(R.id.h6);
casillas[7][3] = (ImageView) findViewById(R.id.h5);
casillas[7][4] = (ImageView) findViewById(R.id.h4);
casillas[7][5] = (ImageView) findViewById(R.id.h3);
casillas[7][6] = (ImageView) findViewById(R.id.h2);
casillas[7][7] = (ImageView) findViewById(R.id.h1);
colocarPiezas(1);
}
private void inicializarCasillasNegro() {
casillas[0][0] = (ImageView) findViewById(R.id.h1);
casillas[0][1] = (ImageView) findViewById(R.id.h2);
casillas[0][2] = (ImageView) findViewById(R.id.h3);
casillas[0][3] = (ImageView) findViewById(R.id.h4);
casillas[0][4] = (ImageView) findViewById(R.id.h5);
casillas[0][5] = (ImageView) findViewById(R.id.h6);
casillas[0][6] = (ImageView) findViewById(R.id.h7);
casillas[0][7] = (ImageView) findViewById(R.id.h8);
casillas[1][0] = (ImageView) findViewById(R.id.g1);
casillas[1][1] = (ImageView) findViewById(R.id.g2);
casillas[1][2] = (ImageView) findViewById(R.id.g3);
casillas[1][3] = (ImageView) findViewById(R.id.g4);
casillas[1][4] = (ImageView) findViewById(R.id.g5);
casillas[1][5] = (ImageView) findViewById(R.id.g6);
casillas[1][6] = (ImageView) findViewById(R.id.g7);
casillas[1][7] = (ImageView) findViewById(R.id.g8);
casillas[2][0] = (ImageView) findViewById(R.id.f1);
casillas[2][1] = (ImageView) findViewById(R.id.f2);
casillas[2][2] = (ImageView) findViewById(R.id.f3);
casillas[2][3] = (ImageView) findViewById(R.id.f4);
casillas[2][4] = (ImageView) findViewById(R.id.f5);
casillas[2][5] = (ImageView) findViewById(R.id.f6);
casillas[2][6] = (ImageView) findViewById(R.id.f7);
casillas[2][7] = (ImageView) findViewById(R.id.f8);
casillas[3][0] = (ImageView) findViewById(R.id.e1);
casillas[3][1] = (ImageView) findViewById(R.id.e2);
casillas[3][2] = (ImageView) findViewById(R.id.e3);
casillas[3][3] = (ImageView) findViewById(R.id.e4);
casillas[3][4] = (ImageView) findViewById(R.id.e5);
casillas[3][5] = (ImageView) findViewById(R.id.e6);
casillas[3][6] = (ImageView) findViewById(R.id.e7);
casillas[3][7] = (ImageView) findViewById(R.id.e8);
casillas[4][0] = (ImageView) findViewById(R.id.d1);
casillas[4][1] = (ImageView) findViewById(R.id.d2);
casillas[4][2] = (ImageView) findViewById(R.id.d3);
casillas[4][3] = (ImageView) findViewById(R.id.d4);
casillas[4][4] = (ImageView) findViewById(R.id.d5);
casillas[4][5] = (ImageView) findViewById(R.id.d6);
casillas[4][6] = (ImageView) findViewById(R.id.d7);
casillas[4][7] = (ImageView) findViewById(R.id.d8);
casillas[5][0] = (ImageView) findViewById(R.id.c1);
casillas[5][1] = (ImageView) findViewById(R.id.c2);
casillas[5][2] = (ImageView) findViewById(R.id.c3);
casillas[5][3] = (ImageView) findViewById(R.id.c4);
casillas[5][4] = (ImageView) findViewById(R.id.c5);
casillas[5][5] = (ImageView) findViewById(R.id.c6);
casillas[5][6] = (ImageView) findViewById(R.id.c7);
casillas[5][7] = (ImageView) findViewById(R.id.c8);
casillas[6][0] = (ImageView) findViewById(R.id.b1);
casillas[6][1] = (ImageView) findViewById(R.id.b2);
casillas[6][2] = (ImageView) findViewById(R.id.b3);
casillas[6][3] = (ImageView) findViewById(R.id.b4);
casillas[6][4] = (ImageView) findViewById(R.id.b5);
casillas[6][5] = (ImageView) findViewById(R.id.b6);
casillas[6][6] = (ImageView) findViewById(R.id.b7);
casillas[6][7] = (ImageView) findViewById(R.id.b8);
casillas[7][0] = (ImageView) findViewById(R.id.a1);
casillas[7][1] = (ImageView) findViewById(R.id.a2);
casillas[7][2] = (ImageView) findViewById(R.id.a3);
casillas[7][3] = (ImageView) findViewById(R.id.a4);
casillas[7][4] = (ImageView) findViewById(R.id.a5);
casillas[7][5] = (ImageView) findViewById(R.id.a6);
casillas[7][6] = (ImageView) findViewById(R.id.a7);
casillas[7][7] = (ImageView) findViewById(R.id.a8);
}
private void setDefaultColor() {
boolean dark = true;
for (int i = 0; i < 8; ++i) {
for (int j = 0; j < 8; ++j) {
if (dark)
casillas[i][j].setBackgroundResource(R.color.casillablanca);
else
casillas[i][j].setBackgroundResource(R.color.casillnegra);
dark = !dark;
}
dark = !dark;
}
}
private void colocarPiezas(int bando){
casillas[0][7].setImageResource(bando == 1?R.mipmap.alpha_wr:R.mipmap.alpha_br);
casillas[7][7].setImageResource(bando == 1?R.mipmap.alpha_wr:R.mipmap.alpha_br);
casillas[0][6].setImageResource(bando == 1?R.mipmap.alpha_wp:R.mipmap.alpha_bp);
casillas[1][6].setImageResource(bando == 1?R.mipmap.alpha_wp:R.mipmap.alpha_bp);
casillas[1][6].setImageResource(bando == 1?R.mipmap.alpha_wp:R.mipmap.alpha_bp);
casillas[2][6].setImageResource(bando == 1?R.mipmap.alpha_wp:R.mipmap.alpha_bp);
casillas[4][6].setImageResource(bando == 1?R.mipmap.alpha_wp:R.mipmap.alpha_bp);
casillas[5][6].setImageResource(bando == 1?R.mipmap.alpha_wp:R.mipmap.alpha_bp);
casillas[6][6].setImageResource(bando == 1?R.mipmap.alpha_wp:R.mipmap.alpha_bp);
casillas[7][6].setImageResource(bando == 1?R.mipmap.alpha_wp:R.mipmap.alpha_bp);
casillas[1][7].setImageResource(bando == 1?R.mipmap.alpha_wn:R.mipmap.alpha_bn);
casillas[6][7].setImageResource(bando == 1?R.mipmap.alpha_wn:R.mipmap.alpha_bn);
casillas[2][7].setImageResource(bando == 1?R.mipmap.alpha_wb:R.mipmap.alpha_bb);
casillas[5][7].setImageResource(bando == 1?R.mipmap.alpha_wb:R.mipmap.alpha_bb);
casillas[3][7].setImageResource(bando == 1?R.mipmap.alpha_wq:R.mipmap.alpha_bq);
casillas[4][7].setImageResource(bando == 1?R.mipmap.alpha_wk:R.mipmap.alpha_bk);
casillas[7][0].setImageResource(bando == 2?R.mipmap.alpha_wr:R.mipmap.alpha_br);
casillas[0][0].setImageResource(bando == 2?R.mipmap.alpha_wr:R.mipmap.alpha_br);
casillas[0][1].setImageResource(bando == 2?R.mipmap.alpha_wp:R.mipmap.alpha_bp);
casillas[1][1].setImageResource(bando == 2?R.mipmap.alpha_wp:R.mipmap.alpha_bp);
casillas[2][1].setImageResource(bando == 2?R.mipmap.alpha_wp:R.mipmap.alpha_bp);
casillas[3][1].setImageResource(bando == 2?R.mipmap.alpha_wp:R.mipmap.alpha_bp);
casillas[4][1].setImageResource(bando == 2?R.mipmap.alpha_wp:R.mipmap.alpha_bp);
casillas[5][1].setImageResource(bando == 2?R.mipmap.alpha_wp:R.mipmap.alpha_bp);
casillas[6][1].setImageResource(bando == 2?R.mipmap.alpha_wp:R.mipmap.alpha_bp);
casillas[7][1].setImageResource(bando == 2?R.mipmap.alpha_wp:R.mipmap.alpha_bp);
casillas[1][0].setImageResource(bando == 2?R.mipmap.alpha_wn:R.mipmap.alpha_bn);
casillas[6][0].setImageResource(bando == 2?R.mipmap.alpha_wn:R.mipmap.alpha_bn);
casillas[2][0].setImageResource(bando == 2?R.mipmap.alpha_wb:R.mipmap.alpha_bb);
casillas[5][0].setImageResource(bando == 2?R.mipmap.alpha_wb:R.mipmap.alpha_bb);
casillas[3][0].setImageResource(bando == 2?R.mipmap.alpha_wq:R.mipmap.alpha_bq);
casillas[4][0].setImageResource(bando == 2?R.mipmap.alpha_wk:R.mipmap.alpha_bk);
}
private void setOnclickListener() {
for (int i = 0; i < 8; ++i) {
for (int j = 0; j < 8; ++j) {
casillas[i][j].setOnClickListener(this);
}
}
}
private int[] getPosition(int id) {
int position[] = {-1, -1};
for (int i = 0; i < 8; ++i) {
for (int j = 0; j < 8; ++j) {
if (id == casillas[i][j].getId()) {
position[0] = i;
position[1] = j;
return position;//si el click fue en una casilla se retorna la posicion
}
}
}
return position;//si el click no fue en una casilla se devuelven valores negativos en la posicion
}
private boolean validarCoordenadas(String coordenadas) {
final String columnas = "abcdefgh";
final String filas = "87654321";
cOrigen = columnas.indexOf(coordenadas.charAt(0));
cDestino = columnas.indexOf(coordenadas.charAt(2));
fOrigen = filas.indexOf(coordenadas.charAt(1));
fDestino = filas.indexOf(coordenadas.charAt(3));
if(cOrigen == -1 || cDestino == -1 || fOrigen == -1 || fDestino == -1)
return false;
return true;
}
private void procesarResultados(ArrayList<String> listaCoordenadas) {
String coordenadas;
for (int i = 0; i < listaCoordenadas.size(); ++i) {
coordenadas = listaCoordenadas.get(i).replace(" ", "").toLowerCase();
if (coordenadas.length() == 4) {
if (validarCoordenadas(coordenadas)) {
validarMovimiento(coordenadas);
break;
}
}
}
}
private void enviarMovimiento(String coordendas) {
DataOutputStream out = null;
try {
out = new DataOutputStream(SocketServidor.getSocket().getOutputStream());
out.writeUTF(coordendas);
tiempoMovimiento.reiniciar();
} catch (IOException e) {
e.printStackTrace();
}
}
private void validarMovimiento(String coordenadas){
switch (chess.mover(coordenadas.substring(0,2),coordenadas.substring(2,4)))
{
case 2:
Toast.makeText(Juego.this, "movimiento no valido", Toast.LENGTH_SHORT).show();
break;
case 3:
moverPieza(1,coordenadas);
break;
case 4:
Toast.makeText(Juego.this, "movimiento no valido", Toast.LENGTH_SHORT).show();
break;
case 0:
moverPieza(2,coordenadas);
break;
}
}
private void moverPieza(int n,String coordenada){
if(jugadaLocal){
enviarMovimiento(crearCoordenada());
if(!enroque()) {
casillas[cDestino][fDestino].setImageDrawable(casillas[cOrigen][fOrigen].getDrawable());
casillas[cOrigen][fOrigen].setImageDrawable(null);
}
}else{
validarCoordenadas(coordenada);
if(!enroque()) {
casillas[cDestino][fDestino].setImageDrawable(casillas[cOrigen][fOrigen].getDrawable());
casillas[cOrigen][fOrigen].setImageDrawable(null);
}
}
jugadaLocal = !jugadaLocal;
if(n == 1){
Toast.makeText(Juego.this, "Jaque Mate", Toast.LENGTH_SHORT).show();
}
}
private boolean enroque(){
if(enroqueBlanco)
if(cOrigen == 4 && fOrigen == 7 && cDestino == 6 && fDestino == 7)
{
casillas[cDestino][fDestino].setImageDrawable(casillas[cOrigen][fOrigen].getDrawable());
casillas[cOrigen][fOrigen].setImageDrawable(null);
casillas[5][7].setImageDrawable(casillas[7][7].getDrawable());
casillas[7][7].setImageDrawable(null);
enroqueBlanco = !enroqueBlanco;
return true;
}else if(cOrigen == 4 && fOrigen == 7 && cDestino == 2 && fDestino == 7)
{
casillas[cDestino][fDestino].setImageDrawable(casillas[cOrigen][fOrigen].getDrawable());
casillas[cOrigen][fOrigen].setImageDrawable(null);
casillas[3][7].setImageDrawable(casillas[0][7].getDrawable());
casillas[0][7].setImageDrawable(null);
enroqueBlanco = !enroqueBlanco;
return true;
}
if(enroqueNegro)
if(cOrigen == 4 && fOrigen == 0 && cDestino == 6 && fDestino == 0)
{
casillas[cDestino][fDestino].setImageDrawable(casillas[cOrigen][fOrigen].getDrawable());
casillas[cOrigen][fOrigen].setImageDrawable(null);
casillas[5][0].setImageDrawable(casillas[7][0].getDrawable());
casillas[7][0].setImageDrawable(null);
enroqueNegro = !enroqueNegro;
return true;
}else if(cOrigen == 4 && fOrigen == 0 && cDestino == 2 && fDestino == 0)
{
casillas[cDestino][fDestino].setImageDrawable(casillas[cOrigen][fOrigen].getDrawable());
casillas[cOrigen][fOrigen].setImageDrawable(null);
casillas[3][0].setImageDrawable(casillas[0][0].getDrawable());
casillas[0][0].setImageDrawable(null);
enroqueNegro = !enroqueNegro;
return true;
}
return false;
}
private String crearCoordenada() {
String coordenada = "";
final String columnas = "abcdefgh";
final String filas = "87654321";
coordenada += columnas.charAt(cOrigen);
coordenada += filas.charAt(fOrigen);
coordenada += columnas.charAt(cDestino);
coordenada += filas.charAt(fDestino);
return coordenada;
}
@Override
public void onClick(View v) {
if(jugadaLocal) {
int position[] = getPosition(v.getId());
if (position[0] != -1) {//si el valor es negativo indica que el click no se realizo en una casilla
if (origen == null) {
origen = casillas[position[0]][position[1]];
cOrigen = position[0];
fOrigen = position[1];
} else {
origen = null;
cDestino = position[0];
fDestino = position[1];
validarMovimiento(crearCoordenada());
}
}
}else{
Toast.makeText(Juego.this, "No es su turno", Toast.LENGTH_SHORT).show();
}
}
class Speech implements RecognitionListener {
@Override
public void onReadyForSpeech(Bundle params) {
}
@Override
public void onBeginningOfSpeech() {
}
@Override
public void onRmsChanged(float rmsdB) {
}
@Override
public void onBufferReceived(byte[] buffer) {
}
@Override
public void onEndOfSpeech() {
}
@Override
public void onError(int error) {
}
@Override
public void onResults(Bundle results) {
ArrayList<String> listaPalabras = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
procesarResultados(listaPalabras);
}
@Override
public void onPartialResults(Bundle partialResults) {
}
@Override
public void onEvent(int eventType, Bundle params) {
}
}
class Tiempo {
CountDown countDown;
public void iniciar() {
countDown = new CountDown(60000, 1000);
countDown.start();
}
public void detener() {
countDown.cancel();
}
public void reiniciar() {
tiempo.setText("60");
tiempo.setTextColor(Color.WHITE);
countDown.cancel();
}
class CountDown extends CountDownTimer {
public CountDown(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
@Override
public void onTick(long millisUntilFinished) {
long time = millisUntilFinished / 1000;
tiempo.setText(String.valueOf(time));
if (time == 15)
tiempo.setTextColor(Color.RED);
}
@Override
public void onFinish() {
}
}
}
class RecibirMovimientos extends AsyncTask<Void, String, Boolean> {
Socket socket;
protected Boolean doInBackground(Void... params) {
socket = SocketServidor.getSocket();
boolean continuar = true;
while (continuar) {
try {
Thread.sleep(250);
InputStream fromServer = SocketServidor.getSocket().getInputStream();
DataInputStream in = new DataInputStream(fromServer);
publishProgress(in.readUTF());
} catch (Exception ex) {
}
}
return null;
}
@Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
validarMovimiento(values[0]);
Toast.makeText(Juego.this, values[0], Toast.LENGTH_SHORT).show();
tiempoMovimiento.iniciar();
}
}
}
|
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.*;
import javafx.scene.paint.PhongMaterial;
import javafx.scene.shape.DrawMode;
import javafx.scene.shape.MeshView;
import javafx.scene.shape.TriangleMesh;
import javafx.scene.text.Text;
/**
* Represents one of the tiles containing an answer and it's value for the GUI's
*/
class AnswerTile extends BorderPane{
private Answer answer;
int rank;
int value;
private GameGUI gui;
Text answerText;
Text valueText;
Text rankText;
private BorderPane tile;
boolean hidden;
boolean isAnAnswer;
private double width;
private double height;
private double depth;
AnswerTile(GameGUI gui, int i){
super();
rank = i;
this.gui = gui;
gui.answerTiles.add(this);
rankText = new Text(Integer.toString(rank));
gui.styleText(rankText, gui.screen.getHeight()/11);
width = gui.screen.getWidth()/2.6225;
height = gui.screen.getHeight()/8.5714;
depth = height / 2;
setPrefSize(width, height);
clear();
}
void setAnswer(Answer a){
answer = a;
value = answer.points;
isAnAnswer = true;
hidden = true;
answerText = new Text(answer.answer);
double size = 12.0;
gui.styleText(answerText, gui.screen.getHeight()/size);
// Decreases the size of the text until it fits in it's section of the box
while(answerText.getBoundsInLocal().getWidth() > ((gui.screen.getWidth()/2.6225)*(11.0/14.0))){
size += 0.001; //increases because it's used to divide another number
gui.styleText(answerText, gui.screen.getHeight()/size);
}
value = answer.points;
valueText = new Text(Integer.toString(value));
gui.styleText(valueText, gui.screen.getHeight()/9);
tile = new BorderPane();
tile.setLeft(answerText);
BorderPane.setAlignment(answerText, Pos.CENTER_LEFT);
BorderPane.setMargin(answerText, new Insets(0, 0, 0, width/75));
tile.setRight(valueText);
BorderPane.setAlignment(valueText, Pos.CENTER_RIGHT);
if(valueText.getText().length() < 2){
BorderPane.setMargin(valueText, new Insets(0, width/19, 0, 0));
}else{
BorderPane.setMargin(valueText, new Insets(0, width/75, 0, 0));
}
// Create the 3D cuboid for the tile
TriangleMesh cuboid = new TriangleMesh(); //A simple 3D rectangle
float fheight = (float) height;
float fwidth = (float) width;
float fdepth = (float) depth;
cuboid.getPoints().addAll( //All points are referenced from the top, left, center
0f, 0f, fdepth/2, // Top, Left, Front
-fheight, 0f, fdepth/2, // Bottom, Left, Front
0f, fwidth, fdepth/2, // Top, Right, Front
-fheight, fwidth, fdepth/2, // Bottom, Right, Front
0f, 0f, -fdepth/2, // Top, Left, Back
-fheight, 0f, -fdepth/2, // Bottom, Left, Back
0f, fwidth, -fdepth/2, // Top, Right, Back
-fheight, fwidth, -fdepth/2 // Bottom, Right, Back
);
cuboid.getTexCoords().addAll(0,0); //todo - replace with percentages to 1.0 from top left corner
cuboid.getFaces().addAll(//The faces are listed as they move down, back, and counterclockwise
0,0, 2,0, 4,0, // Top Front
2,0, 4,0, 6,0, // Top Back
0,0, 1,0, 2,0, // Front Top
1,0, 2,0, 3,0, // Front Bottom
2,0, 3,0, 6,0, // Right Top
3,0, 6,0, 7,0, // Right Bottom
4,0, 6,0, 7,0, // Back Top
4,0, 5,0, 7,0, // Back Bottom
0,0, 1,0, 4,0, // Left Top
1,0, 4,0, 5,0, // Left Bottom
1,0, 3,0, 5,0, // Bottom Front
3,0, 5,0, 7,0 // Bottom Back
);
PhongMaterial material = new PhongMaterial();
material.setDiffuseMap(new Image("resources\\AnswerTile Texture.png"));
MeshView tile3D = new MeshView(cuboid);
tile3D.setDrawMode(DrawMode.FILL);
tile3D.setMaterial(material);
this.getChildren().clear();
this.setCenter(tile3D);
this.getChildren().clear();
ImageView front = new ImageView("resources\\numbered answer tile.png");
front.setFitHeight(height);
front.setFitWidth(width);
this.getChildren().add(front);
this.setCenter(rankText);
}
void reveal(boolean isVisible){
if(hidden && isAnAnswer){
if(isVisible) gui.caretaker.save();
if(isVisible) gui.playAudio("reveal.mp3");
this.getChildren().clear();
ImageView front = new ImageView("resources\\revealed answer tile.png");
front.setFitHeight(height);
front.setFitWidth(width);
this.getChildren().add(front);
this.setCenter(tile);
hidden = false;
gui.scoreAnswer(value);
if(isVisible){
//todo - animate the question revealing itself (flip while rotating in place && play sound)
}
}
}
void hide(){
this.getChildren().clear();
ImageView front = new ImageView("resources\\numbered answer tile.png");
front.setFitHeight(height);
front.setFitWidth(width);
this.getChildren().add(front);
this.setCenter(rankText);
hidden = true;
}
void clear(){
hidden = true;
isAnAnswer = false;
this.getChildren().clear();
ImageView front = new ImageView("resources\\blank answer tile.png");
front.setFitHeight(height);
front.setFitWidth(width);
this.getChildren().add(front);
}
}
|
public class ChessBoard {
ChessFactory factory = new ChessFactory();
private Chess ChessStatus[][] = new Chess[20][20];
private short nowPlayer;
private int step;
private Rule rule;
public ChessBoard(Rule rule) {
initializeGame();
// Clean Chess Board
initializeChessBoard();
this.rule = rule;
}
private void initializeGame() {
// First step = 0
this.step = 0;
// Black Chess First
this.nowPlayer = Const.BLACK_CHESS;
}
private void initializeChessBoard() {
for (int i = 0; i < 20; i++) {
for (int j = 0; j < 20; j++) {
this.ChessStatus[i][j] = null;
}
}
}
public short clickDot(Location loc) {
// Make Chess
this.ChessStatus[loc.getX()][loc.getY()] = factory.makeChess(this.nowPlayer, loc, this.step);
// Check Finish
short winner = this.checkFinish();
if (winner == Const.NO_WIN) {
//this.changePlayer();
step++;
}
return winner;
}
public short checkFinish() {
return this.rule.check(ChessStatus);
}
public short checkToLose() {
return this.rule.toLose(ChessStatus);
}
public void changePlayer() {
if (this.nowPlayer == Const.BLACK_CHESS) {
this.nowPlayer = Const.WHITE_CHESS;
} else {
this.nowPlayer = Const.BLACK_CHESS;
}
}
public short getNowPlayer() {
return nowPlayer;
}
public void Surrender() {
// TODO: Show Winner (UI)
System.out.println("Winner: " + (this.nowPlayer == Const.BLACK_CHESS ? "BLACK" : "WHITE"));
}
}
|
package bot;
import java.util.HashMap;
import com.stevebrecher.HandEval;
import com.stevebrecher.HandEval.HandCategory;
import be.stilkin.HandParser;
import be.stilkin.StartingHands;
import poker.Card;
import poker.HandHoldem;
import poker.PokerMove;
public class BotStarter implements Bot {
public static final String CALL_ACTION = "call";
public static final String RAISE_ACTION = "raise";
public static final String CHECK_ACTION = "check";
public static final String FOLD_ACTION = "fold";
public static final float CURIOSITY = 0.05f;
public static final float COCKYNESS = 0.025f;
private static final float ODD_LOWER_BOUND = 0.55f;
private final HashMap<String, Integer> roundMoneys = new HashMap<String, Integer>();
private final HandParser myHandParser = new HandParser();
private final HandParser tableHandParser = new HandParser();
private String botName = "stilkin";
private HandHoldem hand;
private int lastRound = -1;
private int minRaise;
/**
* Implement this method to return the best move you can. Currently it will return a raise the ordinal value of one of our cards is higher than 9, a call when one of the cards
* has a higher ordinal value than 5 and a check otherwise.
*
* @param state
* : The current state of your bot, with all the (parsed) information given by the engine
* @param timeOut
* : The time you have to return a move
* @return PokerMove : The move you will be doing
*/
@Override
public PokerMove getMove(BotState state, Long timeOut) {
// set some round variables
botName = state.getMyName();
hand = state.getHand();
minRaise = 2 * state.getBigBlind();
final Card[] table = state.getTable();
if (lastRound != state.getRound()) { // reset round counters
lastRound = state.getRound();
roundMoneys.clear();
}
if (table == null || table.length < 3) { // pre-flop
return preFlop(state);
} else { // post-flop
return postFlop(table, state);
}
}
private PokerMove postFlop(final Card[] table, final BotState state) {
// reset parsers
tableHandParser.clear();
myHandParser.clear();
// init parser with this rounds' cards
tableHandParser.addCards(table);
myHandParser.addCards(table);
myHandParser.addCards(state.getHand().getCards());
// if the table cards are stronger or equally strong, we bail
if (tableHandParser.getHandCategory().ordinal() >= myHandParser.getHandCategory().ordinal()) {
// TODO: check height of pairs and such on the table?
return preFlopCheck(state);
}
// TODO: check potential for flush or straight on the table
// if we get here we have at least one of the cards in our hand, otherwise the table would be as good as our hand (see higher)
final int callAmount = state.getAmountToCall();
final HandEval.HandCategory myHand = getHandCategory(hand, table);
// Get the ordinal values of the cards in your hand
final int height1 = hand.getCard(0).getHeight().ordinal();
final int height2 = hand.getCard(1).getHeight().ordinal();
final int sum = height1 + height2;
int odds = 1;
// calculate som odds as multipliers
switch (myHand) {
case STRAIGHT_FLUSH:
odds = 72192;
break;
case FOUR_OF_A_KIND:
odds = 4164;
break;
case FULL_HOUSE:
odds = 693;
break;
case FLUSH:
odds = 508;
break;
case STRAIGHT:
odds = 254;
break;
case THREE_OF_A_KIND:
odds = 46;
break;
case TWO_PAIR:
odds = 20;
break;
case PAIR:
odds = 2;
break;
case NO_PAIR:
odds = 1;
break;
default:
odds = 1;
break;
}
// determine right course of action
switch (myHand) {
case STRAIGHT_FLUSH:
case FOUR_OF_A_KIND:
case FULL_HOUSE:
case FLUSH:
case STRAIGHT:
final PokerMove oddRaise = raiseWithOdds(state, odds);
if (oddRaise != null) {
return oddRaise; // we raise
} else { // we are being re-raised
return loggedAction(botName, CALL_ACTION, 0);
}
case THREE_OF_A_KIND:
odds = 46;
boolean trips = hand.getCard(0).getHeight() == hand.getCard(1).getHeight();
if (trips) {
final PokerMove tripsOddRaise = raiseWithOdds(state, odds / 2);
if (tripsOddRaise != null) {
return tripsOddRaise; // we raise
} else { // we are being re-raised
return loggedAction(botName, CALL_ACTION, 0);
}
} else if (sum > 15) { // TODO: find out which card is in the THREE OF A KIND
return loggedAction(botName, CALL_ACTION, callAmount);
}
break;
case TWO_PAIR: // TODO: find out which card is in the TWO PAIR
odds = 20;
boolean pairOnTable = tableHandParser.getHandCategory().ordinal() >= HandCategory.PAIR.ordinal();
if (!pairOnTable && sum > 10) {
final PokerMove twoPairOddRaise = raiseWithOdds(state, odds / 2);
if (twoPairOddRaise != null) {
return twoPairOddRaise; // we raise
} else { // we are being re-raised
return loggedAction(botName, CALL_ACTION, 0);
}
} else if (sum > 15) {
return loggedAction(botName, CALL_ACTION, callAmount);
}
break;
case PAIR: // TODO: find out which card is in the PAIR
odds = 2;
if (sum > 20) {
return loggedAction(botName, CALL_ACTION, callAmount);
}
break;
case NO_PAIR:
odds = 1;
break;
}
return loggedAction(botName, CHECK_ACTION, 0);
}
/**
* We have a good hand, with how much do we raise?
*/
private PokerMove raiseWithOdds(final BotState state, int odds) {
final int multiplier = 2 + (odds / 120);
int raise = multiplier * state.getBigBlind();
final int stackDiff = state.getmyStack() - state.getOpponentStack();
if (stackDiff > 0) { // we are ahead
raise += (int) (0.15f * stackDiff);
}
final int raisedSoFar = roundMoneys.getOrDefault(RAISE_ACTION, 0);
final int calledSoFar = roundMoneys.getOrDefault(CALL_ACTION, 0);
final int bothSoFar = raisedSoFar + calledSoFar;
if (bothSoFar < raise) { // set to raise only once
return loggedAction(botName, RAISE_ACTION, raise);
} else {
final int callAmount = state.getAmountToCall();
return loggedAction(botName, CALL_ACTION, callAmount);
}
}
/**
* What do we do pre-flop? We get the odds and raise according to any odds over 50%
*/
private PokerMove preFlop(final BotState state) {
final float winOdds = StartingHands.getOdds(hand.getCard(0), hand.getCard(1));
final PokerMove oppAction = state.getOpponentAction();
boolean oppRaise = false;
if (oppAction != null) {
oppRaise = RAISE_ACTION.equals(oppAction.getAction());
}
final PokerMove oddRaise = raiseWithOdds(state, winOdds);
if (winOdds > ODD_LOWER_BOUND) { // over 55%
if (oddRaise != null) {
return oddRaise; // we raise
} else { // we are being re-raised
System.err.println("Pre-flop, BANZAII scenario.");
return loggedAction(botName, CALL_ACTION, 0);
}
} else if (winOdds > 0 && !oppRaise) { // between 50% and 55%
if (oddRaise != null) {
return oddRaise; // we raise
}
}
// poor starting hand, or average hand was re-raised
return preFlopCheck(state);
}
/**
* Raises up to a specific amount specified by the odds. Will return null if we cannot raise
*/
private PokerMove raiseWithOdds(final BotState state, final float winOdds) {
final int raisedSoFar = roundMoneys.getOrDefault(RAISE_ACTION, 0);
final int calledSoFar = roundMoneys.getOrDefault(CALL_ACTION, 0);
final int spentSoFar = raisedSoFar + calledSoFar;
final int maxRaise = (int) (winOdds * state.getmyStack());
if (spentSoFar < maxRaise || spentSoFar < minRaise) {
final int raisePart = maxRaise / 2; // we raise in 2 steps
final int raise = Math.max(minRaise, raisePart);
return loggedAction(botName, RAISE_ACTION, raise);
} else {
return null;
}
}
/**
* Calls up to big blind, otherwise checks (pre-flop)
*/
private PokerMove preFlopCheck(final BotState state) {
final int blindDiff = state.getBigBlind() - state.getSmallBlind();
final int callAmount = state.getAmountToCall();
final float costRatio = (float) blindDiff / state.getmyStack();
// when the blind is too big compared to our stack, we don't peek // TODO: is this smart?
if (costRatio < CURIOSITY && callAmount <= blindDiff) {
return loggedAction(botName, CALL_ACTION, callAmount);
} else {
return loggedAction(botName, CHECK_ACTION, 0);
}
}
/**
* TODO: add more logging to this method
*/
private PokerMove loggedAction(final String botName, final String action, final int amount) {
final int currentAmount = roundMoneys.getOrDefault(action, 0);
roundMoneys.put(action, currentAmount + amount);
return new PokerMove(botName, action, amount);
}
/**
* Calculates the hand strength, only works with 5 cards. This uses the com.stevebrecher package to get hand strength.
*
* @param cardSet
* : a set of five cards
* @return HandCategory with what the cardSet is worth
*/
public HandEval.HandCategory getCardsCategory(final Card[] cardSet) {
if (cardSet != null && cardSet.length == 5) {
long handCode = 0;
for (Card card : cardSet) {
handCode += card.getNumber();
}
return rankToCategory(HandEval.hand5Eval(handCode));
}
return null;
}
/**
* Calculates the bot's hand strength, with 0, 3, 4 or 5 cards on the table. This uses the com.stevebrecher package to get hand strength.
*
* @param hand
* : cards in hand
* @param table
* : cards on table
* @return HandCategory with what the bot has got, given the table and hand
*/
public HandEval.HandCategory getHandCategory(HandHoldem hand, Card[] table) {
if (table == null || table.length == 0) { // there are no cards on the table
return hand.getCard(0).getHeight() == hand.getCard(1).getHeight() // return a pair if our hand cards are the same
? HandEval.HandCategory.PAIR : HandEval.HandCategory.NO_PAIR;
}
long handCode = hand.getCard(0).getNumber() + hand.getCard(1).getNumber();
for (Card card : table) {
handCode += card.getNumber();
}
if (table.length == 3) { // three cards on the table
return rankToCategory(HandEval.hand5Eval(handCode));
}
if (table.length == 4) { // four cards on the table
return rankToCategory(HandEval.hand6Eval(handCode));
}
return rankToCategory(HandEval.hand7Eval(handCode)); // five cards on the table
}
/**
* small method to convert the int 'rank' to a readable enum called HandCategory
*/
public HandEval.HandCategory rankToCategory(int rank) {
return HandEval.HandCategory.values()[rank >> HandEval.VALUE_SHIFT];
}
/**
* @param args
*/
public static void main(String[] args) {
final BotParser parser = new BotParser(new BotStarter());
parser.run();
}
}
|
package cell;
import java.util.List;
import gui.CellSocietyGUI;
import location.Location;
import state.State;
import state.SugarState;
public class SugarCell extends Cell{
private static final int PATCH_STATE_0 = 0;
private static final int PATCH_STATE_1 = 1;
private static final int PATCH_STATE_2 = 2;
private static final int PATCH_STATE_3 = 3;
private static final int PATCH_STATE_4 = 4;
private static final int NUM_STATES = 5;
private static final int NO_AGENT_STATE = 0;
private static final int AGENT_STATE = 1;
private static final int MAX_SUGAR_CAPACITY = 4;
private static final int SUGAR_GROWBACK_RATE = 1;
//private static final int SUGAR_GROWBACK_INTERVAL = 1;
private SugarState mySugarState;
private int myAgentState;
private int myPatchAmntSugar;
private int myAgentAmntSugar; //arbitrary number
private int myAgentSugarMetabolism = 1;
//private int myAgentVision = 1;
SugarCell(State s, Location l, CellSocietyGUI CSGUI) {
super(s, NUM_STATES, l, CSGUI);
setPatchAmntSugar(s.getStateInt());
mySugarState = (SugarState) s;
myAgentState = mySugarState.getAgent();
if (myAgentState == AGENT_STATE){
setAgentAmntSugar(5);
}
}
private int getPatchAmntSugar(){
return myPatchAmntSugar;
}
private void setPatchAmntSugar(int sugar){
myPatchAmntSugar = sugar;
}
private int getAgentAmntSugar(){
return myAgentAmntSugar;
}
private void setAgentAmntSugar(int sugar){
myAgentAmntSugar = sugar;
}
@Override
public void determineNextState() {
if (myAgentState == AGENT_STATE) {
for(int i=MAX_SUGAR_CAPACITY; i>=0; i
List<Cell> neighborsInState = getNeighborsInStateInt(i);
if (!neighborsInState.isEmpty()){
SugarCell chosenCell = (SugarCell) findClosestCell(neighborsInState);
moveMyStateAndAgentToCell(chosenCell);
break;
}else{
continue;
}
}
}
if (myPatchAmntSugar != MAX_SUGAR_CAPACITY){
setPatchAmntSugar(getPatchAmntSugar() + SUGAR_GROWBACK_RATE);
}
}
@Override
public void remove() {
// TODO Auto-generated method stub
myCellGUI.remove();
}
private boolean moveMyStateAndAgentToCell(SugarCell chosenCell) {
if (chosenCell == null)
return false;
int prevSugar = chosenCell.getPatchAmntSugar();
SugarState prevState = (SugarState) chosenCell.getState();
int nextAgentAmntSugar = getAgentAmntSugar() + prevSugar - myAgentSugarMetabolism;
if (nextAgentAmntSugar <= 0){
chosenCell.setAgentAmntSugar(0);
prevState.setAgent(0);
}else{
chosenCell.setAgentAmntSugar(nextAgentAmntSugar);
chosenCell.setPatchAmntSugar(0); //agent takes sugar
prevState.setNextState(0); //state sugar=0
prevState.setAgent(1); //there is an agent in this cell now
}
this.mySugarState.setNextState(mySugarState.getStateInt());
this.mySugarState.setAgent(0);
this.setAgentAmntSugar(0);
return true;
}
private Cell findClosestCell(List<Cell> neighborCellList){
int currX = this.getLocation().getX();
int currY = this.getLocation().getY();
double minDistance = Integer.MAX_VALUE;
Cell minDistCell = this;
for(int i=0; i<neighborCellList.size(); i++){
int otherX = neighborCellList.get(i).getLocation().getX();
int otherY = neighborCellList.get(i).getLocation().getY();
double distance = Math.sqrt(Math.pow(currX-otherX, 2) + Math.pow(currY-otherY, 2));
if (distance < minDistance){
minDistance = distance;
minDistCell = neighborCellList.get(i);
}
}
return minDistCell;
}
}
|
package com.pty4j;
import com.pty4j.util.PtyUtil;
import com.sun.jna.Platform;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
/**
* @author traff
*/
public class TestUtil {
@NotNull
static String getTestDataPath() {
return Paths.get("test/testData").toAbsolutePath().normalize().toString();
}
@NotNull
public static String[] getJavaCommand(@NotNull Class<?> aClass, String... args) {
List<String> result = new ArrayList<>();
result.add(getJavaExecutablePath());
result.add("-cp");
result.add(getJarPathForClass(aClass));
result.add(aClass.getName());
result.addAll(Arrays.asList(args));
return result.toArray(new String[0]);
}
@NotNull
private static String getJavaExecutablePath() {
return System.getProperty("java.home") + File.separator + "bin"
+ File.separator + (Platform.isWindows() ? "java.exe" : "java");
}
/**
* Copied from com.intellij.openapi.application.PathManager#getJarPathForClass.
*/
@NotNull
private static String getJarPathForClass(@NotNull Class aClass) {
String resourceRoot = getResourceRoot(aClass, "/" + aClass.getName().replace('.', '/') + ".class");
return new File(Objects.requireNonNull(resourceRoot)).getAbsolutePath();
}
@Nullable
private static String getResourceRoot(@NotNull Class context, @NotNull String path) {
URL url = context.getResource(path);
if (url == null) {
url = ClassLoader.getSystemResource(path.substring(1));
}
return url != null ? extractRoot(url, path) : null;
}
@NotNull
private static String extractRoot(@NotNull URL resourceURL, @NotNull String resourcePath) {
if (!resourcePath.startsWith("/") && !resourcePath.startsWith("\\")) {
throw new IllegalStateException("precondition failed: " + resourcePath);
}
String resultPath = null;
String protocol = resourceURL.getProtocol();
if ("file".equals(protocol)) {
String path = urlToFile(resourceURL).getPath();
String testPath = path.replace('\\', '/');
String testResourcePath = resourcePath.replace('\\', '/');
if (testPath.endsWith(testResourcePath)) {
resultPath = path.substring(0, path.length() - resourcePath.length());
}
}
if (resultPath == null) {
throw new IllegalStateException("Cannot extract '" + resourcePath + "' from '" + resourceURL + "', " + protocol);
}
return resultPath;
}
@NotNull
private static File urlToFile(@NotNull URL url) {
try {
return new File(url.toURI().getSchemeSpecificPart());
}
catch (URISyntaxException e) {
throw new IllegalArgumentException("URL='" + url.toString() + "'", e);
}
}
@NotNull
public static Path getBuiltNativeFolder() {
return Paths.get("os").toAbsolutePath().normalize();
}
public static void setLocalPtyLib() {
if ("false".equals(System.getProperty(PtyUtil.PREFERRED_NATIVE_FOLDER_KEY))) {
System.clearProperty(PtyUtil.PREFERRED_NATIVE_FOLDER_KEY);
}
else {
System.setProperty(PtyUtil.PREFERRED_NATIVE_FOLDER_KEY, getBuiltNativeFolder().toString());
}
}
}
|
package org.intermine.util;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.SQLException;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.intermine.metadata.ClassDescriptor;
import org.intermine.metadata.FieldDescriptor;
import org.intermine.metadata.AttributeDescriptor;
import org.intermine.metadata.ReferenceDescriptor;
import org.intermine.metadata.CollectionDescriptor;
import org.intermine.sql.Database;
import org.intermine.sql.writebatch.BatchWriterPostgresCopyImpl;
import org.intermine.sql.writebatch.FlushJob;
import org.intermine.sql.writebatch.TableBatch;
import org.intermine.model.InterMineObject;
import org.apache.log4j.Logger;
/**
* Collection of commonly used Database utilities
*
* @author Andrew Varley
* @author Matthew Wakeling
*/
public class DatabaseUtil
{
private static final Logger LOG = Logger.getLogger(DatabaseUtil.class);
private static final String[] RESERVED_WORDS = new String[] {
"ABS",
"ABSOLUTE",
"ACTION",
"ADD",
"ADMIN",
"AFTER",
"AGGREGATE",
"ALIAS",
"ALL",
"ALLOCATE",
"ALTER",
"ANALYSE",
"ANALYZE",
"AND",
"ANY",
"ARE",
"ARRAY",
"AS",
"ASC",
"ASENSITIVE",
"ASSERTION",
"ASYMMETRIC",
"AT",
"ATOMIC",
"AUTHORIZATION",
"AVG",
"BEFORE",
"BEGIN",
"BETWEEN",
"BIGINT",
"BINARY",
"BIT",
"BIT_LENGTH",
"BLOB",
"BOOLEAN",
"BOTH",
"BREADTH",
"BY",
"CALL",
"CALLED",
"CARDINALITY",
"CASCADE",
"CASCADED",
"CASE",
"CAST",
"CATALOG",
"CEIL",
"CEILING",
"CHAR",
"CHARACTER",
"CHARACTER_LENGTH",
"CHAR_LENGTH",
"CHECK",
"CLASS",
"CLOB",
"CLOSE",
"COALESCE",
"COLLATE",
"COLLATION",
"COLLECT",
"COLUMN",
"COMMIT",
"COMPLETION",
"CONDITION",
"CONNECT",
"CONNECTION",
"CONSTRAINT",
"CONSTRAINTS",
"CONSTRUCTOR",
"CONTINUE",
"CONVERT",
"CORR",
"CORRESPONDING",
"COUNT",
"COVAR_POP",
"COVAR_SAMP",
"CREATE",
"CROSS",
"CUBE",
"CUME_DIST",
"CURRENT",
"CURRENT_DATE",
"CURRENT_DEFAULT_TRAN",
"CURRENT_PATH",
"CURRENT_ROLE",
"CURRENT_TIME",
"CURRENT_TIMESTAMP",
"CURRENT_TRANSFORM_GR",
"CURRENT_USER",
"CURSOR",
"CYCLE",
"DATA",
"DATABASE",
"DATE",
"DAY",
"DEALLOCATE",
"DEC",
"DECIMAL",
"DECLARE",
"DEFAULT",
"DEFERRABLE",
"DEFERRED",
"DELETE",
"DENSE_RANK",
"DEPTH",
"DEREF",
"DESC",
"DESCRIBE",
"DESCRIPTOR",
"DESTROY",
"DESTRUCTOR",
"DETERMINISTIC",
"DIAGNOSTICS",
"DICTIONARY",
"DISCONNECT",
"DISTINCT",
"DO",
"DOMAIN",
"DOUBLE",
"DROP",
"DYNAMIC",
"EACH",
"ELEMENT",
"ELSE",
"END",
"END-EXEC",
"EQUALS",
"ESCAPE",
"EVERY",
"EXCEPT",
"EXCEPTION",
"EXEC",
"EXECUTE",
"EXISTS",
"EXP",
"EXTERNAL",
"EXTRACT",
"FALSE",
"FETCH",
"FILTER",
"FIRST",
"FLOAT",
"FLOOR",
"FOR",
"FOREIGN",
"FOUND",
"FREE",
"FREEZE",
"FROM",
"FULL",
"FUNCTION",
"FUSION",
"GENERAL",
"GET",
"GLOBAL",
"GO",
"GOTO",
"GRANT",
"GROUP",
"GROUPING",
"HAVING",
"HOLD",
"HOST",
"HOUR",
"IDENTITY",
"IGNORE",
"ILIKE",
"IMMEDIATE",
"IN",
"INDICATOR",
"INITIALIZE",
"INITIALLY",
"INNER",
"INOUT",
"INPUT",
"INSENSITIVE",
"INSERT",
"INT",
"INTEGER",
"INTERSECT",
"INTERSECTION",
"INTERVAL",
"INTO",
"IS",
"ISNULL",
"ISOLATION",
"ITERATE",
"JOIN",
"KEY",
"LANGUAGE",
"LARGE",
"LAST",
"LATERAL",
"LEADING",
"LEFT",
"LESS",
"LEVEL",
"LIKE",
"LIMIT",
"LN",
"LOCAL",
"LOCALTIME",
"LOCALTIMESTAMP",
"LOCATOR",
"LOWER",
"MAP",
"MATCH",
"MAX",
"MEMBER",
"MERGE",
"METHOD",
"MIN",
"MINUTE",
"MOD",
"MODIFIES",
"MODIFY",
"MODULE",
"MONTH",
"MULTISET",
"NAMES",
"NATIONAL",
"NATURAL",
"NCHAR",
"NCLOB",
"NEW",
"NEXT",
"NO",
"NONE",
"NORMALIZE",
"NOT",
"NOTNULL",
"NULL",
"NULLIF",
"NUMERIC",
"OBJECT",
"OBJECTCLASS",
"OCTET_LENGTH",
"OF",
"OFF",
"OFFSET",
"OLD",
"ON",
"ONLY",
"OPEN",
"OPERATION",
"OPTION",
"OR",
"ORDER",
"ORDINALITY",
"OUT",
"OUTER",
"OUTPUT",
"OVER",
"OVERLAPS",
"OVERLAY",
"PAD",
"PARAMETER",
"PARAMETERS",
"PARTIAL",
"PARTITION",
"PATH",
"PERCENTILE_CONT",
"PERCENTILE_DISC",
"PERCENT_RANK",
"PLACING",
"POSITION",
"POSTFIX",
"POWER",
"PRECISION",
"PREFIX",
"PREORDER",
"PREPARE",
"PRESERVE",
"PRIMARY",
"PRIOR",
"PRIVILEGES",
"PROCEDURE",
"PUBLIC",
"RANGE",
"READ",
"READS",
"REAL",
"RECURSIVE",
"REF",
"REFERENCES",
"REFERENCING",
"REGR_AVGX",
"REGR_AVGY",
"REGR_COUNT",
"REGR_INTERCEPT",
"REGR_R2",
"REGR_SLOPE",
"REGR_SXX",
"REGR_SXY",
"REGR_SYY",
"RELATIVE",
"RELEASE",
"RESTRICT",
"RESULT",
"RETURN",
"RETURNS",
"REVOKE",
"RIGHT",
"ROLE",
"ROLLBACK",
"ROLLUP",
"ROUTINE",
"ROW",
"ROWS",
"ROW_NUMBER",
"SAVEPOINT",
"SCHEMA",
"SCOPE",
"SCROLL",
"SEARCH",
"SECOND",
"SECTION",
"SELECT",
"SENSITIVE",
"SEQUENCE",
"SESSION",
"SESSION_USER",
"SET",
"SETOF",
"SETS",
"SIMILAR",
"SIZE",
"SMALLINT",
"SOME",
"SPACE",
"SPECIFIC",
"SPECIFICTYPE",
"SQL",
"SQLCODE",
"SQLERROR",
"SQLEXCEPTION",
"SQLSTATE",
"SQLWARNING",
"SQRT",
"START",
"STATE",
"STATEMENT",
"STATIC",
"STDDEV_POP",
"STDDEV_SAMP",
"STRUCTURE",
"SUBMULTISET",
"SUBSTRING",
"SUM",
"SYMMETRIC",
"SYSTEM",
"SYSTEM_USER",
"TABLE",
"TABLESAMPLE",
"TEMPORARY",
"TERMINATE",
"THAN",
"THEN",
"TIME",
"TIMESTAMP",
"TIMEZONE_HOUR",
"TIMEZONE_MINUTE",
"TO",
"TRAILING",
"TRANSACTION",
"TRANSLATE",
"TRANSLATION",
"TREAT",
"TRIGGER",
"TRIM",
"TRUE",
"UESCAPE",
"UNDER",
"UNION",
"UNIQUE",
"UNKNOWN",
"UNNEST",
"UPDATE",
"UPPER",
"USAGE",
"USER",
"USING",
"VALUE",
"VALUES",
"VARCHAR",
"VARIABLE",
"VARYING",
"VAR_POP",
"VAR_SAMP",
"VERBOSE",
"VIEW",
"WHEN",
"WHENEVER",
"WHERE",
"WIDTH_BUCKET",
"WINDOW",
"WITH",
"WITHIN",
"WITHOUT",
"WORK",
"WRITE",
"YEAR",
"ZONE"};
private static Set reservedWords = new HashSet();
static {
for (int i = 0; i < RESERVED_WORDS.length; i++) {
reservedWords.add(RESERVED_WORDS[i]);
}
}
private DatabaseUtil() {
// empty
}
/**
* Tests if a table exists in the database
*
* @param con a connection to a database
* @param tableName the name of a table to test for
* @return true if the table exists, false otherwise
* @throws SQLException if an error occurs in the underlying database
* @throws NullPointerException if tableName is null
*/
public static boolean tableExists(Connection con, String tableName) throws SQLException {
if (tableName == null) {
throw new NullPointerException("tableName cannot be null");
}
ResultSet res = con.getMetaData().getTables(null, null, tableName, null);
while (res.next()) {
if (res.getString(3).equals(tableName) && "TABLE".equals(res.getString(4))) {
return true;
}
}
return false;
}
/**
* Removes every single table from the database given.
*
* @param con the Connection to the database
* @throws SQLException if an error occurs in the underlying database
*/
public static void removeAllTables(Connection con) throws SQLException {
ResultSet res = con.getMetaData().getTables(null, null, "%", null);
Set tablenames = new HashSet();
while (res.next()) {
String tablename = res.getString(3);
if ("TABLE".equals(res.getString(4))) {
tablenames.add(tablename);
}
}
Iterator tablenameIter = tablenames.iterator();
while (tablenameIter.hasNext()) {
String tablename = (String) tablenameIter.next();
LOG.info("Dropping table " + tablename);
con.createStatement().execute("DROP TABLE " + tablename);
}
}
/**
* Creates a table name for a class descriptor
*
* @param cld ClassDescriptor
* @return a valid table name
*/
public static String getTableName(ClassDescriptor cld) {
return generateSqlCompatibleName(cld.getUnqualifiedName());
}
/**
* Creates a column name for a field descriptor
*
* @param fd FieldDescriptor
* @return a valid column name
*/
public static String getColumnName(FieldDescriptor fd) {
if (fd instanceof AttributeDescriptor) {
return generateSqlCompatibleName(fd.getName());
}
if (fd instanceof CollectionDescriptor) {
return null;
}
if (fd instanceof ReferenceDescriptor) {
return fd.getName() + "Id";
}
return null;
}
/**
* Creates an indirection table name for a many-to-many collection descriptor
*
* @param col CollectionDescriptor
* @return a valid table name
*/
public static String getIndirectionTableName(CollectionDescriptor col) {
if (FieldDescriptor.M_N_RELATION != col.relationType()) {
throw new IllegalArgumentException("Argument must be a CollectionDescriptor for a "
+ "many-to-many relation");
}
String name1 = getInwardIndirectionColumnName(col);
String name2 = getOutwardIndirectionColumnName(col);
return name1.compareTo(name2) < 0 ? name1 + name2 : name2 + name1;
}
/**
* Creates a column name for the "inward" key of a many-to-many collection descriptor
*
* @param col CollectionDescriptor
* @return a valid column name
*/
public static String getInwardIndirectionColumnName(CollectionDescriptor col) {
if (FieldDescriptor.M_N_RELATION != col.relationType()) {
throw new IllegalArgumentException("Argument must be a CollectionDescriptor for a "
+ "many-to-many relation");
}
return StringUtil.capitalise(generateSqlCompatibleName(col.getName()));
}
/**
* Creates a column name for the "outward" key of a many-to-many collection descriptor
*
* @param col CollectionDescriptor
* @return a valid column name
*/
public static String getOutwardIndirectionColumnName(CollectionDescriptor col) {
if (FieldDescriptor.M_N_RELATION != col.relationType()) {
throw new IllegalArgumentException("Argument must be a CollectionDescriptor for a "
+ "many-to-many relation");
}
ReferenceDescriptor rd = col.getReverseReferenceDescriptor();
String colName = (rd == null
? TypeUtil.unqualifiedName(col.getClassDescriptor().getName())
: rd.getName());
return StringUtil.capitalise(generateSqlCompatibleName(colName));
}
/**
* Convert any sql keywords to valid names for tables/columns.
* @param n the string to convert
* @return a valid sql name
*/
public static String generateSqlCompatibleName(String n) {
String upper = n.toUpperCase();
if (upper.startsWith("INTERMINE_") || reservedWords.contains(upper)) {
return "intermine_" + n;
} else {
return n;
}
}
public static String objectToString(Object o) throws IllegalArgumentException {
if (o instanceof Float) {
return o.toString() + "::REAL";
} else if (o instanceof Number) {
return o.toString();
} else if (o instanceof String) {
return "'" + StringUtil.duplicateQuotes((String) o) + "'";
} else if (o instanceof Boolean) {
return ((Boolean) o).booleanValue() ? "'true'" : "'false'";
} else if (o == null) {
return "NULL";
} else {
throw new IllegalArgumentException("Can't convert " + o + " into an SQL String");
}
}
/**
* Analyse given database, perform vacuum full analyse if full parameter true.
* WARNING: currently PostgreSQL specific
* @param db the database to analyse
* @param full if true perform VACUUM FULL ANALYSE
* @throws SQLException if db problem
*/
public static void analyse(Database db, boolean full) throws SQLException {
Connection conn = db.getConnection();
boolean autoCommit = conn.getAutoCommit();
try {
conn.setAutoCommit(true);
Statement s = conn.createStatement();
if (full) {
s.execute("VACUUM FULL ANALYSE");
} else {
s.execute("ANALYSE");
}
conn.setAutoCommit(autoCommit);
} finally {
conn.setAutoCommit(autoCommit);
conn.close();
}
}
/**
* Analyse database table for a given class and all associated indirection tables.
* WARNING: currently PostgreSQL specific
* @param db the database to analyse
* @param cld description of class to analyse
* @param full if true perform VACUUM FULL ANALYSE
* @throws SQLException if db problem
*/
public static void analyse(Database db, ClassDescriptor cld, boolean full) throws SQLException {
Set tables = new HashSet();
tables.add(getTableName(cld));
tables.addAll(getIndirectionTableNames(cld));
Connection conn = db.getConnection();
boolean autoCommit = conn.getAutoCommit();
try {
conn.setAutoCommit(true);
Statement s = conn.createStatement();
Iterator tablesIter = tables.iterator();
while (tablesIter.hasNext()) {
if (full) {
String sql = "VACUUM FULL ANALYSE " + (String) tablesIter.next();
LOG.info(sql);
s.execute(sql);
} else {
String sql = "ANALYSE " + (String) tablesIter.next();
LOG.info(sql);
s.execute(sql);
}
}
conn.setAutoCommit(autoCommit);
} finally {
conn.setAutoCommit(autoCommit);
conn.close();
}
}
/**
* Given a ClassDescriptor find names of all related indirection tables.
* @param cld class to find tables for
* @return a set of all indirection table names
*/
public static Set getIndirectionTableNames(ClassDescriptor cld) {
Set tables = new HashSet();
Iterator iter = cld.getAllCollectionDescriptors().iterator();
while (iter.hasNext()) {
CollectionDescriptor col = (CollectionDescriptor) iter.next();
if (FieldDescriptor.M_N_RELATION == col.relationType()) {
tables.add(getIndirectionTableName(col));
}
}
return tables;
}
public static void grant(Database db, String user, String perm) throws SQLException {
Connection conn = db.getConnection();
boolean autoCommit = conn.getAutoCommit();
try {
conn.setAutoCommit(true);
Statement s = conn.createStatement();
ResultSet res = conn.getMetaData().getTables(null, null, null, null);
while (res.next()) {
if ("TABLE".equals(res.getString(4))) {
String sql = "GRANT " + perm + " ON " + res.getString(3) + " TO " + user;
LOG.debug(sql);
s.execute(sql);
}
}
conn.setAutoCommit(autoCommit);
} finally {
conn.setAutoCommit(autoCommit);
conn.close();
}
}
/**
* Create a new table the holds the contents of the given Collection (bag). The "Class c"
* parameter selects which objects from the bag are put in the new table. eg. if the bag
* contains Integers and Strings and the parameter is Integer.class then the table will contain
* only the Integers from the bag. A Class of InterMineObject is handled specially: the new
* table will contain the IDs of the objects, not the objects themselves. The table will have
* one column ("value").
* @param db the Database to access
* @param con the Connection to use
* @param tableName the name to use for the new table
* @param bag the Collection to create a table for
* @param c the type of objects to put int he new table
* @throws SQLException if there is a database problem
*/
public static void createBagTable(Database db, Connection con,
String tableName, Collection bag, Class c)
throws SQLException {
String typeString;
if (InterMineObject.class.isAssignableFrom(c)) {
typeString = db.getColumnTypeString(Integer.class);
} else {
typeString = db.getColumnTypeString(c);
if (typeString == null) {
throw new IllegalArgumentException("unknown Class passed to createBagTable(): "
+ c.getName());
}
}
String tableCreateSql = "CREATE TABLE " + tableName + " (value " + typeString + ")";
Statement s = con.createStatement();
s.execute(tableCreateSql);
Iterator bagIter = bag.iterator();
TableBatch tableBatch = new TableBatch();
String colNames[] = new String[] {"value"};
while (bagIter.hasNext()) {
Object o = bagIter.next();
if (c.isInstance(o)) {
if (o instanceof InterMineObject) {
o = ((InterMineObject) o).getId();
} else if (o instanceof Date) {
o = new Long(((Date) o).getTime());
}
tableBatch.addRow(null, colNames, new Object[] {o});
}
}
List flushJobs = (new BatchWriterPostgresCopyImpl()).write(con, Collections
.singletonMap(tableName, tableBatch), null);
Iterator flushJobIter = flushJobs.iterator();
while (flushJobIter.hasNext()) {
FlushJob fj = (FlushJob) flushJobIter.next();
fj.flush();
}
String indexCreateSql = "CREATE INDEX " + tableName + "_index ON " + tableName + "(value)";
s.execute(indexCreateSql);
s.execute("ANALYSE " + tableName);
}
}
|
package org.intermine.pathquery;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.TreeMap;
import java.util.regex.Pattern;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import org.intermine.metadata.ClassDescriptor;
import org.intermine.metadata.Model;
import org.intermine.objectstore.query.ConstraintOp;
import org.intermine.util.DynamicUtil;
import org.intermine.util.TypeUtil;
/**
* Class to represent a path-based query.
*
* @author Matthew Wakeling
*/
public class PathQuery implements Cloneable
{
/** A Pattern that finds spaces in a String. */
protected static final Pattern SPACE_SPLITTER = Pattern.compile(" ", Pattern.LITERAL);
/** Version number for the userprofile and PathQuery XML format. */
public static final int USERPROFILE_VERSION = 2;
private Model model;
private List<String> view = new ArrayList<String>();
private List<OrderElement> orderBy = new ArrayList<OrderElement>();
private Map<PathConstraint, String> constraints = new LinkedHashMap<PathConstraint, String>();
private LogicExpression logic = null;
private Map<String, OuterJoinStatus> outerJoinStatus
= new LinkedHashMap<String, OuterJoinStatus>();
private Map<String, String> descriptions = new LinkedHashMap<String, String>();
private String description = null;
// Verification variables:
private boolean isVerified = false;
/** The root path of this query */
private String rootClass = null;
/** A Map from path to class name for all PathConstraintSubclass objects in the query. */
private Map<String, String> subclasses = null;
/** A Map from path to outer join group for all main paths in the query. */
private Map<String, String> outerJoinGroups = null;
/** A Map from outer join group to the set of constraint codes in that group. */
private Map<String, Set<String>> constraintGroups = null;
/** A Set of Strings describing all the loop constraints in the query, in order to check for
* uniqueness */
private Set<String> existingLoops = null;
/** A boolean that determines if the constraints are broken enough to not bother validating the
* constraint logic */
private boolean doNotVerifyLogic = false;
/**
* Constructor. Takes a Model object, to enable verification later.
*
* @param model a Model object
*/
public PathQuery(Model model) {
this.model = model;
}
/**
* Constructor. Takes an existing PathQuery object, and copies all the data. Similar to the
* clone method.
*
* @param o a PathQuery to copy
*/
public PathQuery(PathQuery o) {
model = o.model;
view = new ArrayList<String>(o.view);
orderBy = new ArrayList<OrderElement>(o.orderBy);
constraints = new LinkedHashMap<PathConstraint, String>(o.constraints);
if (o.logic != null) {
logic = new LogicExpression(o.logic.toString());
}
outerJoinStatus = new LinkedHashMap<String, OuterJoinStatus>(o.outerJoinStatus);
descriptions = new LinkedHashMap<String, String>(o.descriptions);
description = o.description;
}
/**
* Returns the Model object stored in this object.
*
* @return a Model
*/
public Model getModel() {
return model;
}
public synchronized void addView(String viewPath) {
deVerify();
checkPathFormat(viewPath);
view.add(viewPath);
}
/**
* Removes a single element from the view list. The element should be a normal path expression,
* with dots separating the parts. Do not use colons to represent outer joins, and do not use
* square brackets to represent subclass constraints. If there are multiple copies of the path
* on the view list (which is an invalid query), then this method will remove all of them.
*
* @param viewPath the path String to remove from the view list
* @throws NullPointerException if the viewPath is null
* @throws NoSuchElementException if the viewPath is not already on the view list
*/
public synchronized void removeView(String viewPath) {
deVerify();
checkPathFormat(viewPath);
if (!view.contains(viewPath)) {
throw new NoSuchElementException("Path \"" + viewPath + "\" is not in the view list: \""
+ view + "\" - cannot remove it");
}
view.removeAll(Collections.singleton(viewPath));
}
/**
* Clears the entire view list.
*/
public synchronized void clearView() {
deVerify();
view.clear();
}
public synchronized void addViews(Collection<String> viewPaths) {
deVerify();
try {
for (String viewPath : viewPaths) {
checkPathFormat(viewPath);
}
for (String viewPath : viewPaths) {
addView(viewPath);
}
} catch (NullPointerException e) {
NullPointerException e2 = new NullPointerException("While adding list to view: "
+ viewPaths);
e2.initCause(e);
throw e2;
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("While adding list to view: " + viewPaths, e);
}
}
public synchronized void addViews(String ... viewPaths) {
deVerify();
try {
for (String viewPath : viewPaths) {
checkPathFormat(viewPath);
}
for (String viewPath : viewPaths) {
addView(viewPath);
}
} catch (NullPointerException e) {
NullPointerException e2 = new NullPointerException("While adding array to view: "
+ viewPaths);
e2.initCause(e);
throw e2;
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("While adding array to view: " + viewPaths, e);
}
}
public synchronized void addViewSpaceSeparated(String viewPaths) {
deVerify();
try {
String[] viewPathArray = SPACE_SPLITTER.split(viewPaths.trim());
for (String viewPath : viewPathArray) {
if (!"".equals(viewPath)) {
checkPathFormat(viewPath);
}
}
for (String viewPath : viewPathArray) {
if (!"".equals(viewPath)) {
addView(viewPath);
}
}
} catch (NullPointerException e) {
NullPointerException e2 = new NullPointerException("While adding space-separated list "
+ "to view: \"" + viewPaths + "\"");
e2.initCause(e);
throw e2;
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("While adding space-separated list to view: \""
+ viewPaths + "\"", e);
}
}
/**
* Returns the current view list. This is an unmodifiable copy of the view list as it is at the
* point of execution of this method. Changes in this query are not reflected in the result of
* this method. The paths listed are normal path expressions without colons or square brackets.
* The paths may not have been verified.
*
* @return a List of String paths
*/
public synchronized List<String> getView() {
return Collections.unmodifiableList(new ArrayList<String>(view));
}
public synchronized void addOrderBy(String orderPath, OrderDirection direction) {
deVerify();
addOrderBy(new OrderElement(orderPath, direction));
}
/**
* Removes an element from the order by list of this query. The element should be a normal path
* expression, with dots separating the parts. Do not use colons to represent outer joins, and
* do not use square brackets to represent subclass constraints. If there are multiple copies
* of the path on the order by list (which is an invalid query), then this method will remove
* all of them.
*
* @param orderPath the path String to remove from the order by list
* @throws NullPointerException if the orderPath is null
* @throws NoSuchElementException if the orderPath is not already in the order by list
*/
public synchronized void removeOrderBy(String orderPath) {
deVerify();
checkPathFormat(orderPath);
boolean found = false;
int i = 0;
while (i < orderBy.size()) {
if (orderPath.equals(orderBy.get(i).getOrderPath())) {
orderBy.remove(i);
found = true;
} else {
i++;
}
}
if (!found) {
throw new NoSuchElementException("Path \"" + orderPath + "\" is not in the order by "
+ "list: \"" + orderBy + "\" - cannot remove it");
}
}
/**
* Clears the entire order by list.
*/
public synchronized void clearOrderBy() {
deVerify();
orderBy.clear();
}
/**
* Adds an element to the order by list of this query. The OrderElement will have already
* checked the path for format, and the path will not be verified until the verifyQuery()
* method is called.
*
* @param orderElement an OrderElement to add to the order by list
* @throws NullPointerException if orderElement is null
*/
public synchronized void addOrderBy(OrderElement orderElement) {
deVerify();
if (orderElement == null) {
throw new NullPointerException("Cannot add a null OrderElement to the order by list");
}
orderBy.add(orderElement);
}
/**
* Adds a group of elements to the order by list of this query. The elements will have already
* checked the paths for format, but the paths will not be verified until the verifyQuery()
* method is called. If there is an error with any of the elements of the collection, then none
* of the elements will be added and the query will be unchanged.
*
* @param orderElements a Collection of OrderElement objects to add to the view list
* @throws NullPointerException if orderElements is null or contains a null element
*/
public synchronized void addOrderBys(Collection<OrderElement> orderElements) {
deVerify();
if (orderElements == null) {
throw new NullPointerException("Cannot add null collection of OrderElements to order by"
+ " list");
}
for (OrderElement orderElement : orderElements) {
if (orderElement == null) {
throw new NullPointerException("Cannot add null OrderElement (from collection \""
+ orderElements + "\") to the order by list");
}
}
for (OrderElement orderElement : orderElements) {
addOrderBy(orderElement);
}
}
/**
* Adds a group of elements to the order by list of this query. The elements will have already
* checked the paths for format, but the paths will not be verified until the verifyQuery()
* method is called. If there is an error with any of the elements in this array/varargs, then
* none of the elements will be added and the query will be unchanged.
*
* @param orderElements an array/varargs of OrderElement objects to add to the view list
* @throws NullPointerException if orderElements is null or contains a null element
*/
public synchronized void addOrderBys(OrderElement ... orderElements) {
deVerify();
if (orderElements == null) {
throw new NullPointerException("Cannot add null array of OrderElements to order by "
+ "list");
}
for (OrderElement orderElement : orderElements) {
if (orderElement == null) {
throw new NullPointerException("Cannot add null OrderElement (from array \""
+ orderElements + "\") to the order by list");
}
}
for (OrderElement orderElement : orderElements) {
addOrderBy(orderElement);
}
}
public synchronized void addOrderBySpaceSeparated(String orderString) {
deVerify();
try {
String[] orderPathArray = SPACE_SPLITTER.split(orderString.trim());
if (orderPathArray.length % 2 != 0) {
throw new IllegalArgumentException("Order String must contain alternating paths and"
+ " directions, so must have an even number of space-separated elements.");
}
List<OrderElement> toAdd = new ArrayList<OrderElement>();
for (int i = 0; i < orderPathArray.length - 1; i += 2) {
if ("asc".equals(orderPathArray[i + 1].toLowerCase())) {
toAdd.add(new OrderElement(orderPathArray[i], OrderDirection.ASC));
} else if ("desc".equals(orderPathArray[i + 1].toLowerCase())) {
toAdd.add(new OrderElement(orderPathArray[i], OrderDirection.DESC));
} else {
throw new IllegalArgumentException("Order direction \"" + orderPathArray[i + 1]
+ "\" must be either \"asc\" or \"desc\"");
}
}
addOrderBys(toAdd);
} catch (NullPointerException e) {
NullPointerException e2 = new NullPointerException("While adding space-separated list "
+ "to order by: \"" + orderString + "\"");
e2.initCause(e);
throw e2;
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("While adding space-separated list to order by: \""
+ orderString + "\"");
}
}
/**
* Returns the current order by list. This is an unmodifiable copy of the order by list as it is
* at the point of execution of this method. Changes in this query are not reflected in the
* result of this method. The returned value is a List containing OrderElement objects, which
* contain a String path expression without colons or square brackets, and an OrderDirection.
* The paths may not have been verified.
*
* @return a List of OrderElement objects
*/
public synchronized List<OrderElement> getOrderBy() {
return Collections.unmodifiableList(new ArrayList<OrderElement>(orderBy));
}
/**
* Adds a PathConstraint to this query. The PathConstraint will be attached to the path in the
* constraint, which will have already been checked for format (no colons or square brackets),
* but will not be verified until the verifyQuery() method is called. This method returns a
* String code which is a single character that can be used in the constraint logic to logically
* combine constraints. The constraint will be added to the existing constraint logic with the
* AND operator - for any other arrangement, set the logic after calling this method. If the
* constraint is already present in the query, then this method will do nothing.
*
* @param constraint the PathConstraint to add to this query
* @return a String constraint code for use in the constraint logic
* @throws NullPointerException if the constraint is null
*/
public synchronized String addConstraint(PathConstraint constraint) {
deVerify();
if (constraint == null) {
throw new NullPointerException("Cannot add a null constraint to this query");
}
if (constraints.containsKey(constraint)) {
return constraints.get(constraint);
}
if (constraint instanceof PathConstraintSubclass) {
// Subclass constraints don't get a code
constraints.put(constraint, null);
return null;
}
Set<String> usedCodes = new HashSet<String>(constraints.values());
char charCode = 'A';
String code = "A";
while (usedCodes.contains(code)) {
charCode++;
code = "" + charCode;
}
if (logic == null) {
logic = new LogicExpression(code);
} else {
logic = new LogicExpression("(" + logic.toString() + ") AND " + code);
}
constraints.put(constraint, code);
return code;
}
public synchronized void addConstraint(PathConstraint constraint, String code) {
deVerify();
if (constraint == null) {
throw new NullPointerException("Cannot add a null constraint to this query");
}
if (constraint instanceof PathConstraintSubclass) {
throw new IllegalArgumentException("Cannot associate a code with a subclass constraint."
+ " Use the addConstraint(PathConstraint) method instead");
}
if (code == null) {
throw new NullPointerException("Cannot use a null code for a constraint in this query");
}
if ((code.length() != 1) || (code.charAt(0) > 'Z') || (code.charAt(0) < 'A')) {
throw new IllegalArgumentException("The constraint code must be a single plain latin "
+ "uppercase character");
}
if (constraints.containsKey(constraint)) {
if (code.equals(constraints.get(constraint))) {
return;
} else {
throw new IllegalStateException("Given constraint is already associated with code "
+ constraints.get(constraint) + " - cannot associate with code " + code);
}
}
Set<String> usedCodes = new HashSet<String>(constraints.values());
if (usedCodes.contains(code)) {
throw new IllegalStateException("Given code " + code + " conflicts with an existing "
+ "constraint");
}
if (logic == null) {
logic = new LogicExpression(code);
} else {
logic = new LogicExpression("(" + logic.toString() + ") AND " + code);
}
constraints.put(constraint, code);
}
/**
* Removes a constraint from this query. The PathConstraint should be a constraint that already
* exists in this query. The constraint will also be removed from the constraint logic.
*
* @param constraint the PathConstraint to remove from this query
* @throws NullPointerException if the constraint is null
* @throws NoSuchElementException if the constraint is not present in the query
*/
public synchronized void removeConstraint(PathConstraint constraint) {
deVerify();
if (constraint == null) {
throw new NullPointerException("Cannot remove null constraint from this query");
}
if (constraints.containsKey(constraint)) {
String code = constraints.remove(constraint);
if (code != null) {
if (logic.getVariableNames().size() > 1) {
logic.removeVariable(code);
} else {
logic = null;
}
}
} else {
throw new NoSuchElementException("Constraint to remove is not present in query");
}
}
public synchronized void replaceConstraint(PathConstraint old, PathConstraint replacement) {
deVerify();
if (old == null) {
throw new NullPointerException("Cannot replace a null constraint");
}
if (replacement == null) {
throw new NullPointerException("Cannot replace a constraint with null");
}
if (!constraints.containsKey(old)) {
throw new NoSuchElementException("Old constraint is not in the query");
}
if (constraints.containsKey(replacement)) {
throw new IllegalStateException("Replacement constraint is already in the query");
}
String code = constraints.get(old);
// Read the next line very carefully!
if ((replacement instanceof PathConstraintSubclass) != (code == null)) {
throw new IllegalArgumentException("Cannot replace a "
+ old.getClass().getSimpleName() + " with a "
+ replacement.getClass().getSimpleName());
}
Map<PathConstraint, String> temp = new LinkedHashMap<PathConstraint, String>(constraints);
constraints.clear();
for (Map.Entry<PathConstraint, String> entry : temp.entrySet()) {
if (old.equals(entry.getKey())) {
constraints.put(replacement, code);
} else {
constraints.put(entry.getKey(), entry.getValue());
}
}
}
/**
* Clears the entire set of constraints from this query, and resets the constraint logic.
*/
public synchronized void clearConstraints() {
deVerify();
constraints.clear();
logic = null;
}
/**
* Adds a collection of constraints to this query. The PathConstraints will be attached to the
* paths in the constraints, which will have already been checked for format (no colons or
* square brackets), but will not be verified until the verifyQuery() method is called. The
* constraints will all be given codes, and added to the constraint logic with the default AND
* operator. To discover the codes, use the getConstraints() method. If there is an error with
* any of the elements in the collection, then none of the elements will be added and the
* query will be unchanged.
*
* @param constraints the PathConstraint objects to add to this query
* @throws NullPointerException if constraints is null, or if it contains a null element
*/
public synchronized void addConstraints(Collection<PathConstraint> constraints) {
deVerify();
if (constraints == null) {
throw new NullPointerException("Cannot add null collection of PathConstraints to this "
+ "query");
}
for (PathConstraint constraint : constraints) {
if (constraint == null) {
throw new NullPointerException("Cannot add null PathConstraint (from collection \""
+ constraints + "\" to this query");
}
}
for (PathConstraint constraint : constraints) {
addConstraint(constraint);
}
}
/**
* Adds a group of constraints to this query. The PathConstraints will be attached to the paths
* in the constraints, which will have already been checked for format (no colons or square
* brackets), but will not be verified until the verifyQuery() method is called. The constraints
* will all be given codes, and added to the constraint logic with the default AND operator. To
* discover the codes, use the getConstraints() method. If there is an error with any of the
* elements in the array/varargs, then none of the elements will be added and the query will be
* unchanged.
*
* @param constraints the PathConstraint objects to add to this query
* @throws NullPointerException if constraints is null, or if it contains a null element
*/
public synchronized void addConstraints(PathConstraint ... constraints) {
deVerify();
if (constraints == null) {
throw new NullPointerException("Cannot add null array of PathConstraints to this "
+ "query");
}
for (PathConstraint constraint : constraints) {
if (constraint == null) {
throw new NullPointerException("Cannot add null PathConstraint (from array \""
+ constraints + "\" to this query");
}
}
for (PathConstraint constraint : constraints) {
addConstraint(constraint);
}
}
/**
* Returns a Map of all the constraints in this query, from PathConstraint to the constraint
* code used in the constraint logic. This returns an unmodifiable copy of the data in the
* query at the moment this method is executed, so further changes to the query are not
* reflected in the returned value.
*
* @return a Map from PathConstraint to String constraint code (a single character)
*/
public synchronized Map<PathConstraint, String> getConstraints() {
Map<PathConstraint, String> retval = new LinkedHashMap<PathConstraint, String>(constraints);
return retval;
}
/**
* Returns the PathConstraint associated with a given code.
*
* @param code a single uppercase character
* @return a PathConstraint object
* @throws NullPointerException if code is null
* @throws NoSuchElementException if there is no PathConstraint for that code
*/
public synchronized PathConstraint getConstraintForCode(String code) {
for (Map.Entry<PathConstraint, String> entry : constraints.entrySet()) {
if (code.equals(entry.getValue())) {
return entry.getKey();
}
}
throw new NoSuchElementException("No constraint is associated with code " + code
+ ", valid codes are " + constraints.values());
}
/**
* Returns a list of PathConstraints applied to a given path or an empty list.
*
* @param path the path to fetch constraints for
* @return a List of PathConstraints or an empty list
*/
public synchronized List<PathConstraint> getConstraintsForPath(String path) {
List<PathConstraint> retval = new ArrayList<PathConstraint>();
for (PathConstraint con : constraints.keySet()) {
if (con.getPath().equals(path)) {
retval.add(con);
}
}
return Collections.unmodifiableList(retval);
}
/**
* Return the constraint codes used in the query, some constraint types (subclasses) don't
* get assigned a code, these are not included. This method returns all of the codes that
* should be involved in the logic expression of the query.
* @return the constraint codes used in this query
*/
public synchronized Set<String> getConstraintCodes() {
Set<String> codes = new HashSet<String>();
for (String code : constraints.values()) {
if (code != null) {
codes.add(code);
}
}
return codes;
}
/**
* Returns the current constraint logic. The logic is returned in groups, according to the outer
* join layout of the query. Two codes in separate groups can only be combined with an AND
* operation, not an OR operation.
*
* @return the current constraint logic
*/
public synchronized String getConstraintLogic() {
return (logic == null ? "" : logic.toString());
}
/**
* Sets the current constraint logic.
*
* @param logic the constraint logic
*/
public synchronized void setConstraintLogic(String logic) {
deVerify();
if (constraints.isEmpty()) {
this.logic = null;
} else {
this.logic = new LogicExpression(logic);
for (String code : constraints.values()) {
if (!this.logic.getVariableNames().contains(code)) {
this.logic = new LogicExpression("(" + this.logic.toString() + ") and " + code);
}
}
this.logic.removeAllVariablesExcept(constraints.values());
}
}
public synchronized OuterJoinStatus getOuterJoinStatus(String path) {
checkPathFormat(path);
return outerJoinStatus.get(path);
}
public synchronized void setOuterJoinStatus(String path, OuterJoinStatus status) {
deVerify();
checkPathFormat(path);
if (status == null) {
outerJoinStatus.remove(path);
} else {
outerJoinStatus.put(path, status);
}
}
/**
* Returns an unmodifiable Map which is a copy of the current outer join status of this query at
* the time of execution of this method. Further changes to this object will not be reflected in
* the object that was returned from this method.
*
* @return a Map from String path to OuterJoinStatus
*/
public synchronized Map<String, OuterJoinStatus> getOuterJoinStatus() {
return Collections.unmodifiableMap(
new LinkedHashMap<String, OuterJoinStatus>(outerJoinStatus));
}
/**
* Clears all outer join status data from this query.
*/
public synchronized void clearOuterJoinStatus() {
deVerify();
outerJoinStatus.clear();
}
/**
* Returns a Map from path to TRUE for all paths that are outer joined. That is, if the path is
* an outer join (not referring to its parents - use isCompletelyInner() for that), then it is
* present in this map mapped onto the value TRUE.
*
* @return a Map from String to Boolean TRUE
*/
public synchronized Map<String, Boolean> getOuterMap() {
Map<String, Boolean> retval = new HashMap<String, Boolean>();
for (Map.Entry<String, OuterJoinStatus> stat : outerJoinStatus.entrySet()) {
if (OuterJoinStatus.OUTER.equals(stat.getValue())) {
retval.put(stat.getKey(), Boolean.TRUE);
}
}
return retval;
}
public synchronized String getDescription(String path) {
checkPathFormat(path);
return descriptions.get(path);
}
public synchronized void setDescription(String path, String description) {
deVerify();
checkPathFormat(path);
if (description == null) {
descriptions.remove(path);
} else {
descriptions.put(path, description);
}
}
/**
* Returns an unmodifiable Map which is a copy of the current set of path descriptions of this
* query at the time of execution of this method. Further changes to this object will not
* be reflected in the object that was returned from this method.
*
* @return a Map from String path to description
*/
public synchronized Map<String, String> getDescriptions() {
return Collections.unmodifiableMap(new LinkedHashMap<String, String>(descriptions));
}
/**
* Removes all path descriptions from this query.
*/
public synchronized void clearDescriptions() {
deVerify();
descriptions.clear();
}
public synchronized String getGeneratedPathDescription(String path) {
checkPathFormat(path);
String retval = descriptions.get(path);
if (retval == null) {
int lastDot = path.lastIndexOf('.');
if (lastDot == -1) {
return path;
} else {
return getGeneratedPathDescription(path.substring(0, lastDot)) + " > "
+ path.substring(lastDot + 1);
}
} else {
return retval;
}
}
/**
* Sets the description for this PathQuery.
*
* @param description the new description, or null for none
*/
public synchronized void setDescription(String description) {
deVerify();
this.description = description;
}
/**
* Gets the description for this PathQuery.
*
* @return description
*/
public synchronized String getDescription() {
return description;
}
public synchronized void removeAllUnder(String path) {
checkPathFormat(path);
deVerify();
for (String v : getView()) {
if (isPathUnder(path, v)) {
removeView(v);
}
}
for (OrderElement order : getOrderBy()) {
if (isPathUnder(path, order.getOrderPath())) {
removeOrderBy(order.getOrderPath());
}
}
for (PathConstraint con : getConstraints().keySet()) {
if (isPathUnder(path, con.getPath())) {
removeConstraint(con);
}
}
for (String join : getOuterJoinStatus().keySet()) {
if (isPathUnder(path, join)) {
setOuterJoinStatus(join, null);
}
}
for (String desc : getDescriptions().keySet()) {
if (isPathUnder(path, desc)) {
setDescription(desc, null);
}
}
}
private static boolean isPathUnder(String parent, String child) {
if (parent.equals(child)) {
return true;
}
return child.startsWith(parent + ".");
}
/**
* Removes everything from this query that is irrelevant, and therefore making the query
* invalid. If the query is invalid for other reasons, then this method will either throw an
* exception or ignore that part of the query, depending on the error, however the query is
* unlikely to be made valid.
*
* @throws PathException if the query is invalid for a reason other than irrelevance
*/
public synchronized void removeAllIrrelevant() throws PathException {
deVerify();
List<String> problems = new ArrayList<String>();
// Validate subclass constraints and build subclass constraint map
buildSubclassMap(problems);
rootClass = null;
Set<String> validMainPaths = new LinkedHashSet<String>();
// Validate view paths
validateView(problems, validMainPaths);
// Validate constraints
validateConstraints(problems, validMainPaths);
// Now the validMainPaths set contains all the main (ie class) paths that are permitted in
// this query.
if (!problems.isEmpty()) {
throw new PathException(problems.toString(), null);
}
for (OrderElement order : getOrderBy()) {
Path path = new Path(model, order.getOrderPath(), subclasses);
if (path.endIsAttribute()) {
path = path.getPrefix();
}
if (!validMainPaths.contains(path.getNoConstraintsString())) {
removeOrderBy(order.getOrderPath());
}
}
for (String join : getOuterJoinStatus().keySet()) {
Path path = new Path(model, join, subclasses);
if (path.endIsAttribute()) {
path = path.getPrefix();
}
if (!validMainPaths.contains(path.getNoConstraintsString())) {
setOuterJoinStatus(join, null);
}
}
for (String desc : getDescriptions().keySet()) {
Path path = new Path(model, desc, subclasses);
if (path.endIsAttribute()) {
path = path.getPrefix();
}
if (!validMainPaths.contains(path.getNoConstraintsString())) {
setDescription(desc, null);
}
}
}
/**
* Fixes up the order by list and the constraint logic, given the arrangement of outer joins in
* the query.
*
* @return a List of messages about the changes that this method has made to the query
* @throws PathException if the query is invalid in any way other than that which this method
* will fix.
*/
public synchronized List<String> fixUpForJoinStyle() throws PathException {
deVerify();
List<String> problems = new ArrayList<String>();
// Validate subclass constraints and build subclass constraint map
buildSubclassMap(problems);
rootClass = null;
Set<String> validMainPaths = new LinkedHashSet<String>();
// Validate view paths
validateView(problems, validMainPaths);
// Validate constraints
validateConstraints(problems, validMainPaths);
// Now the validMainPaths set contains all the main (ie class) paths that are permitted in
// this query.
validateOuterJoins(problems, validMainPaths);
calculateConstraintGroups(problems);
if (!problems.isEmpty()) {
throw new PathException(problems.toString(), null);
}
List<String> messages = new ArrayList<String>();
for (OrderElement order : getOrderBy()) {
// We cannot rely on the query being valid, as we are trying to make it valid!
String orderString = order.getOrderPath();
boolean outer = false;
while (orderString.contains(".")) {
if (OuterJoinStatus.OUTER.equals(outerJoinStatus.get(orderString))) {
outer = true;
break;
}
orderString = orderString.substring(0, orderString.lastIndexOf('.'));
}
if (outer) {
removeOrderBy(order.getOrderPath());
messages.add("Removed path " + order.getOrderPath() + " from ORDER BY because of "
+ "outer joins");
}
}
if (logic != null) {
List<Set<String>> groups = new ArrayList<Set<String>>(constraintGroups.values());
try {
logic.split(groups);
} catch (IllegalArgumentException e) {
// The logic is invalid - we need to straighten it up.
String oldLogic = logic.toString();
logic = logic.validateForGroups(groups);
messages.add("Changed constraint logic from " + oldLogic + " to " + logic.toString()
+ " because of outer joins");
}
}
return messages;
}
public synchronized List<String> removeSubclassAndFixUp(String path) throws PathException {
checkPathFormat(path);
List<String> problems = verifyQuery();
if (!problems.isEmpty()) {
throw new PathException("Query does not verify: " + problems, null);
}
deVerify();
List<String> messages = new ArrayList<String>();
PathConstraint toRemove = null;
for (PathConstraint con : getConstraints().keySet()) {
if (con instanceof PathConstraintSubclass) {
if (con.getPath().equals(path)) {
toRemove = con;
break;
}
}
}
if (toRemove == null) {
return messages;
}
removeConstraint(toRemove);
buildSubclassMap(problems);
// Remove things from view
for (String viewPath : getView()) {
try {
@SuppressWarnings("unused")
Path viewPathObj = new Path(model, viewPath, subclasses);
} catch (PathException e) {
// This one is now invalid. Remove
removeView(viewPath);
messages.add("Removed path " + viewPath + " from view, because you removed the "
+ "subclass constraint that it depended on.");
}
}
for (PathConstraint con : getConstraints().keySet()) {
try {
@SuppressWarnings("unused")
Path constraintPath = new Path(model, con.getPath(), subclasses);
if (con instanceof PathConstraintLoop) {
try {
@SuppressWarnings("unused")
Path loopPath = new Path(model, ((PathConstraintLoop) con).getLoopPath(),
subclasses);
} catch (PathException e) {
removeConstraint(con);
messages.add("Removed constraint " + con + " because you removed the "
+ "subclass constraint it depended on.");
}
}
} catch (PathException e) {
removeConstraint(con);
messages.add("Removed constraint " + con + " because you removed the "
+ "subclass constraint it depended on.");
}
}
for (OrderElement order : getOrderBy()) {
try {
@SuppressWarnings("unused")
Path orderPath = new Path(model, order.getOrderPath(), subclasses);
} catch (PathException e) {
removeOrderBy(order.getOrderPath());
messages.add("Removed path " + order.getOrderPath() + " from ORDER BY, because you "
+ "removed the subclass constraint it depended on.");
}
}
for (String join : getOuterJoinStatus().keySet()) {
try {
@SuppressWarnings("unused")
Path joinPath = new Path(model, join, subclasses);
} catch (PathException e) {
setOuterJoinStatus(join, null);
}
}
for (String desc : getDescriptions().keySet()) {
try {
@SuppressWarnings("unused")
Path descPath = new Path(model, desc, subclasses);
} catch (PathException e) {
setDescription(desc, null);
messages.add("Removed description on path " + desc + ", because you removed the "
+ "subclass constraint it depended on.");
}
}
removeAllIrrelevant();
return messages;
}
/**
* Returns a deep copy of this object. The resulting object may be modified without impacting
* this object.
*
* @return a PathQuery
*/
@Override public PathQuery clone() {
try {
PathQuery retval = (PathQuery) super.clone();
retval.view = new ArrayList<String>(retval.view);
retval.orderBy = new ArrayList<OrderElement>(retval.orderBy);
retval.constraints = new LinkedHashMap<PathConstraint, String>(retval.constraints);
if (retval.logic != null) {
retval.logic = new LogicExpression(retval.logic.toString());
}
retval.outerJoinStatus = new LinkedHashMap<String, OuterJoinStatus>(retval
.outerJoinStatus);
retval.descriptions = new LinkedHashMap<String, String>(retval.descriptions);
return retval;
} catch (CloneNotSupportedException e) {
throw new Error("Should never happen", e);
}
}
/**
* Produces a Path object from the given path String, using subclass information from the query.
* Note that this method does not verify the query, but merely attempts to extract as much sane
* subclass information as possible to construct the Path.
*
* @param path the String path
* @return a Path object
* @throws PathException if something goes wrong, or if the path is in an invalid format
*/
public synchronized Path makePath(String path) throws PathException {
Map<String, String> lSubclasses = new HashMap<String, String>();
for (PathConstraint subclass : constraints.keySet()) {
if (subclass instanceof PathConstraintSubclass) {
lSubclasses.put(subclass.getPath(), ((PathConstraintSubclass) subclass).getType());
}
}
return new Path(model, path, lSubclasses);
}
private synchronized void deVerify() {
isVerified = false;
}
/**
* Returns true if the query verifies correctly.
*
* @return a boolean
*/
public boolean isValid() {
return verifyQuery().isEmpty();
}
/**
* Verifies the contents of this query against the model, and for internal integrity. Returns
* a list of String problems that would need to be rectified for this query to pass validation
* and be executed. If the return value is an empty List, then the query is valid.
* <BR>
* This method validates a few important characteristics about the query:
* <UL><LI>All subclass constraints must be subclasses of the class they would otherwise be</LI>
* <LI>All paths must validate against the model</LI>
* <LI>All paths need to extend from the same root class</LI>
* <LI>Paths in the order by list, the outer join status, and the descriptions, must all be
* attached to classes already defined by the view list and the constraints. Otherwise, it would
* be possible to change the number of rows by changing the order</LI>
* <LI>All elements of the view list and the order by list must be attributes, and all
* paths for outer join status and subclass constraints must not be attributes</LI>
* <LI>Subclass constraints cannot be on the root class of the query</LI>
* <LI>Loop constraints cannot cross an outer join</LI>
* <LI>Check constraint values against their types in the model and specific
* characteristics</LI>
* <LI>Check constraint logic for sanity and that it can be split into separate ANDed outer
* join sections</LI>
* </UL>
*
* @return a List of problems
*/
public synchronized List<String> verifyQuery() {
List<String> problems = new ArrayList<String>();
if (isVerified) {
// Query is already verified correctly. Return no problems
return problems;
}
// Validate subclass constraints and build subclass constraint map
buildSubclassMap(problems);
rootClass = null;
Set<String> validMainPaths = new LinkedHashSet<String>();
// Validate view paths
validateView(problems, validMainPaths);
// Validate constraints
validateConstraints(problems, validMainPaths);
// Now the validMainPaths set contains all the main (ie class) paths that are permitted in
// this query.
// Validate subclass constraints against validMainPaths
for (PathConstraint constraint : constraints.keySet()) {
if (constraint instanceof PathConstraintSubclass) {
try {
Path path = new Path(model, constraint.getPath(), subclasses);
if (path.endIsAttribute()) {
// Should have already caught this problem above. Ignore and suppress
continue;
}
} catch (PathException e) {
// Should have already been caught above. Ignore, and suppress further checking
continue;
}
if (!validMainPaths.contains(constraint.getPath())) {
problems.add("Subclass constraint on path " + constraint.getPath()
+ " is not relevant to the query");
}
}
}
// Validate outer join paths
validateOuterJoins(problems, validMainPaths);
// Validate description paths
for (String descPath : descriptions.keySet()) {
try {
Path path = new Path(model, descPath, subclasses);
if (path.endIsAttribute()) {
path = path.getPrefix();
}
if (!validMainPaths.contains(path.getNoConstraintsString())) {
problems.add("Description on path " + descPath
+ " is not relevant to the query");
continue;
}
} catch (PathException e) {
problems.add("Path " + descPath + " for description is not in the model");
continue;
}
}
// Validate order by paths
for (OrderElement orderPath : orderBy) {
try {
Path path = new Path(model, orderPath.getOrderPath(), subclasses);
if (!path.endIsAttribute()) {
problems.add("Path " + orderPath.getOrderPath() + " in order by list must be "
+ "an attribute");
continue;
}
if (!validMainPaths.contains(path.getPrefix().toStringNoConstraints())) {
problems.add("Order by element for path " + orderPath.getOrderPath()
+ " is not relevant to the query");
continue;
}
if (!rootClass.equals(outerJoinGroups.get(path.getPrefix()
.getNoConstraintsString()))) {
problems.add("Order by element " + orderPath
+ " is not in the root outer join group");
}
} catch (PathException e) {
problems.add("Path " + orderPath.getOrderPath()
+ " in order by list is not in the model");
continue;
}
}
calculateConstraintGroups(problems);
if (logic != null) {
if (!doNotVerifyLogic) {
try {
logic.split(new ArrayList<Set<String>>(constraintGroups.values()));
} catch (IllegalArgumentException e) {
problems.add("Logic expression is not compatible with outer join status: "
+ e.getMessage());
}
}
}
if (problems.isEmpty()) {
isVerified = true;
}
return problems;
}
private void calculateConstraintGroups(List<String> problems) {
doNotVerifyLogic = false;
// Put all constraints into groups
constraintGroups = new LinkedHashMap<String, Set<String>>();
for (Map.Entry<PathConstraint, String> constraintEntry : constraints.entrySet()) {
if (constraintEntry.getValue() != null) {
try {
Path path = new Path(model, constraintEntry.getKey().getPath(), subclasses);
if (path.getStartClassDescriptor().getUnqualifiedName().equals(rootClass)) {
if (path.endIsAttribute()) {
path = path.getPrefix();
}
String groupPath = outerJoinGroups.get(path.getNoConstraintsString());
if (groupPath != null) {
Set<String> group = constraintGroups.get(groupPath);
if (group == null) {
group = new HashSet<String>();
constraintGroups.put(groupPath, group);
}
group.add(constraintEntry.getValue());
}
} else {
doNotVerifyLogic = true;
}
} catch (PathException e) {
// If this happens, then we have already noted the problem. Ignore.
doNotVerifyLogic = true;
}
}
if (constraintEntry.getKey() instanceof PathConstraintLoop) {
PathConstraintLoop loop = (PathConstraintLoop) constraintEntry.getKey();
String aGroup = outerJoinGroups.get(loop.getPath());
String bGroup = outerJoinGroups.get(loop.getLoopPath());
// If one of these is null, then we must have recorded a problem above. Ignore.
if ((aGroup != null) && (bGroup != null)) {
if (!aGroup.equals(bGroup)) {
problems.add("Loop constraint " + loop + " crosses an outer join");
continue;
}
}
}
}
for (String group : new HashSet<String>(outerJoinGroups.values())) {
if (!constraintGroups.containsKey(group)) {
constraintGroups.put(group, new HashSet<String>());
}
}
}
private void validateOuterJoins(List<String> problems, Set<String> validMainPaths) {
for (String joinPath : outerJoinStatus.keySet()) {
try {
Path path = new Path(model, joinPath, subclasses);
if (path.endIsAttribute()) {
problems.add("Outer join status on path " + joinPath
+ " must not be on an attribute");
continue;
}
if (path.isRootPath()) {
problems.add("Outer join status cannot be set on root path " + joinPath);
continue;
}
} catch (PathException e) {
problems.add("Path " + joinPath + " for outer join status is not in the model");
continue;
}
if (!validMainPaths.contains(joinPath)) {
problems.add("Outer join status path " + joinPath + " is not relevant to the "
+ "query");
}
}
// Calculate outer join groups from the validMainPaths list of paths
outerJoinGroups = new LinkedHashMap<String, String>();
for (String validPath : validMainPaths) {
try {
Path path = new Path(model, validPath, subclasses);
while (isInner(path)) {
path = path.getPrefix();
}
outerJoinGroups.put(validPath, path.getNoConstraintsString());
} catch (PathException e) {
// Should never happen, as we have already checked in validateOuterJoins
throw new Error(e);
}
}
}
private void validateConstraints(List<String> problems,
Set<String> validMainPaths) {
existingLoops = new HashSet<String>();
// Validate constraint paths
for (PathConstraint constraint : constraints.keySet()) {
try {
Path path = new Path(model, constraint.getPath(), subclasses);
if (rootClass == null) {
rootClass = path.getStartClassDescriptor().getUnqualifiedName();
} else {
String newRootClass = path.getStartClassDescriptor().getUnqualifiedName();
if (!rootClass.equals(newRootClass)) {
problems.add("Multiple root classes in query: " + rootClass + " and "
+ newRootClass);
continue;
}
}
if (path.endIsAttribute()) {
addValidPaths(validMainPaths, path.getPrefix());
} else {
addValidPaths(validMainPaths, path);
}
if (constraint instanceof PathConstraintAttribute) {
if (!path.endIsAttribute()) {
problems.add("Constraint " + constraint + " must be on an attribute");
continue;
}
Class<?> valueType = path.getEndType();
try {
TypeUtil.stringToObject(valueType,
((PathConstraintAttribute) constraint).getValue());
} catch (Exception e) {
problems.add("Value in constraint " + constraint + " is not in correct "
+ "format for type of "
+ DynamicUtil.getFriendlyName(valueType));
continue;
}
} else if (constraint instanceof PathConstraintNull) {
if (path.isRootPath()) {
problems.add("Constraint " + constraint
+ " cannot be applied to the root path");
continue;
}
if (constraint.getOp().equals(ConstraintOp.IS_NULL)) {
if (!path.endIsAttribute()) {
problems.add("Constraint " + constraint
+ " is invalid - can only set IS NULL on an attribute");
continue;
}
}
} else if (constraint instanceof PathConstraintBag) {
// We do not check that the bag exists here. Call getBagNames() and check
// elsewhere.
if (path.endIsAttribute()) {
problems.add("Constraint " + constraint
+ " must not be on an attribute");
continue;
}
} else if (constraint instanceof PathConstraintIds) {
if (path.endIsAttribute()) {
problems.add("Constraint " + constraint
+ " must not be on an attribute");
continue;
}
} else if (constraint instanceof PathConstraintMultiValue) {
if (!path.endIsAttribute()) {
problems.add("Constraint " + constraint + " must be on an attribute");
continue;
}
Class<?> valueType = path.getEndType();
for (String value : ((PathConstraintMultiValue) constraint).getValues()) {
try {
TypeUtil.stringToObject(valueType, value);
} catch (Exception e) {
problems.add("Value (" + value + ") in list in constraint "
+ constraint + " is not in correct format for type of "
+ DynamicUtil.getFriendlyName(valueType));
continue;
}
}
} else if (constraint instanceof PathConstraintLoop) {
if (path.endIsAttribute()) {
problems.add("Constraint " + constraint
+ " must not be on an attribute");
continue;
}
String loopPathString = ((PathConstraintLoop) constraint).getLoopPath();
try {
Path loopPath = new Path(model, loopPathString, subclasses);
if (loopPath.endIsAttribute()) {
problems.add("Loop path in constraint " + constraint
+ " must not be an attribute");
continue;
}
String newRootClass = loopPath.getStartClassDescriptor()
.getUnqualifiedName();
if (!rootClass.equals(newRootClass)) {
problems.add("Multiple root classes in query: " + rootClass
+ " and " + newRootClass);
continue;
}
addValidPaths(validMainPaths, loopPath);
if (constraint.getPath().equals(loopPathString)) {
problems.add("Path " + constraint.getPath()
+ " may not be looped back on itself");
continue;
}
Class<?> aClass = path.getEndType();
Class<?> bClass = loopPath.getEndType();
if (!(aClass.isAssignableFrom(bClass)
|| bClass.isAssignableFrom(aClass))) {
problems.add("Loop constraint " + constraint
+ " must loop between similar types");
continue;
}
String loop = ((PathConstraintLoop) constraint).getDescriptiveString();
if (existingLoops.contains(loop)) {
problems.add("Cannot have two loop constraints between paths "
+ constraint.getPath() + " and " + loopPathString);
continue;
}
existingLoops.add(loop);
} catch (PathException e) {
problems.add("Path " + loopPathString + " in loop constraint from "
+ constraint.getPath() + " is not in the model");
continue;
}
} else if (constraint instanceof PathConstraintLookup) {
if (path.endIsAttribute()) {
problems.add("Constraint " + constraint
+ " must not be on an attribute");
}
} else if (constraint instanceof PathConstraintSubclass) {
// Do nothing
} else {
problems.add("Unrecognised constraint type "
+ constraint.getClass().getName());
continue;
}
} catch (PathException e) {
if (!(constraint instanceof PathConstraintSubclass)) {
problems.add("Path " + constraint.getPath()
+ " in constraint is not in the model");
}
}
}
}
private Set<String> validateView(List<String> problems, Set<String> validMainPaths) {
for (String viewPath : view) {
try {
Path path = new Path(model, viewPath, subclasses);
if (!path.endIsAttribute()) {
problems.add("Path " + viewPath + " in view list must be an attribute");
continue;
}
if (rootClass == null) {
rootClass = path.getStartClassDescriptor().getUnqualifiedName();
} else {
String newRootClass = path.getStartClassDescriptor().getUnqualifiedName();
if (!rootClass.equals(newRootClass)) {
problems.add("Multiple root classes in query: " + rootClass + " and "
+ newRootClass);
continue;
}
}
addValidPaths(validMainPaths, path.getPrefix());
} catch (PathException e) {
problems.add("Path " + viewPath + " in view list is not in the model");
}
}
return validMainPaths;
}
private void buildSubclassMap(List<String> problems) {
List<PathConstraintSubclass> subclassConstraints = new ArrayList<PathConstraintSubclass>();
for (PathConstraint constraint : constraints.keySet()) {
if (constraint instanceof PathConstraintSubclass) {
subclassConstraints.add((PathConstraintSubclass) constraint);
}
}
PathConstraintSubclass[] subclassConstraintArray = subclassConstraints.toArray(new
PathConstraintSubclass[0]);
Arrays.sort(subclassConstraintArray, new Comparator<PathConstraintSubclass>() {
public int compare(PathConstraintSubclass o1, PathConstraintSubclass o2) {
return o1.getPath().length() - o2.getPath().length();
}
});
// subclassConstraintArray should now be in order of increasing length of path string, so it
// should be fine to just build the subclass constraints map
subclasses = new LinkedHashMap<String, String>();
for (PathConstraintSubclass subclass : subclassConstraintArray) {
if (subclasses.containsKey(subclass.getPath())) {
problems.add("Cannot have multiple subclass constraints on path "
+ subclass.getPath());
continue;
}
Path subclassPath = null;
try {
subclassPath = new Path(model, subclass.getPath(), subclasses);
} catch (PathException e) {
problems.add("Path " + subclass.getPath() + " (from subclass constraint) is not in"
+ " the model");
continue;
}
if (subclassPath.isRootPath()) {
problems.add("Root node " + subclass.getPath()
+ " may not have a subclass constraint");
continue;
}
if (subclassPath.endIsAttribute()) {
problems.add("Path " + subclass.getPath() + " (from subclass constraint) must not "
+ "be an attribute");
continue;
}
Class<?> parentClassType = subclassPath.getEndClassDescriptor().getType();
ClassDescriptor subclassDesc = model.getClassDescriptorByName(subclass.getType());
Class<?> subclassType = (subclassDesc == null ? null : subclassDesc.getType());
if (subclassType == null) {
problems.add("Subclass " + subclass.getType() + " (for path " + subclass.getPath()
+ ") is not in the model");
continue;
}
if (!parentClassType.isAssignableFrom(subclassType)) {
problems.add("Subclass constraint on path " + subclass.getPath() + " (type "
+ DynamicUtil.getFriendlyName(parentClassType) + ") restricting to type "
+ DynamicUtil.getFriendlyName(subclassType) + " is not possible, as it is "
+ "not a subclass");
continue;
}
subclasses.put(subclass.getPath(), subclass.getType());
}
}
/**
* Returns the root path for this query, if the query verifies correctly.
*
* @return a String path which is the root class
* @throws PathException if the query does not verify
*/
public synchronized String getRootClass() throws PathException {
List<String> problems = verifyQuery();
if (problems.isEmpty()) {
return rootClass;
}
throw new PathException("Query does not verify: " + problems, null);
}
/**
* Returns the subclass Map for this query, if the query verifies correctly.
*
* @return a Map from path String to subclass name, for all PathConstraintSubclass objects
* @throws PathException if the query does not verify
*/
public synchronized Map<String, String> getSubclasses() throws PathException {
List<String> problems = verifyQuery();
if (problems.isEmpty()) {
return Collections.unmodifiableMap(new LinkedHashMap<String, String>(subclasses));
}
throw new PathException("Query does not verify: " + problems, null);
}
/**
* Returns all bag names used in constraints on this query.
*
* @return the bag names used in this query or an empty set
*/
public synchronized Set<String> getBagNames() {
Set<String> bagNames = new HashSet<String>();
for (PathConstraint constraint : constraints.keySet()) {
if (constraint instanceof PathConstraintBag) {
bagNames.add(((PathConstraintBag) constraint).getBag());
}
}
return bagNames;
}
/**
* Returns the outer join groups map for this query, if the query verifies correctly. This is a
* Map from all the class paths in the query to the outer join group, represented by the path of
* the root of the group.
*
* @return a Map from path String to the outer join group it is in
* @throws PathException if the query does not verify
*/
public synchronized Map<String, String> getOuterJoinGroups() throws PathException {
List<String> problems = verifyQuery();
if (problems.isEmpty()) {
return Collections.unmodifiableMap(new LinkedHashMap<String, String>(outerJoinGroups));
}
throw new PathException("Query does not verify: " + problems, null);
}
/**
* Returns the set of loop constraint descriptive strings, for the purpose of checking for
* uniqueness.
*
* @return a Set of Strings
* @throws PathException if the query does not verify
*/
public synchronized Set<String> getExistingLoops() throws PathException {
List<String> problems = verifyQuery();
if (problems.isEmpty()) {
return Collections.unmodifiableSet(new HashSet<String>(existingLoops));
}
throw new PathException("Query does not verify: " + problems, null);
}
/**
* Returns the outer join group that the given path is in.
*
* @param stringPath a pathString
* @return a String representing the outer join group that the path is in
* @throws NullPointerException if pathString is null
* @throws PathException if the query is invalid or the path is invalid
* @throws NoSuchElementException is the path is not in the query
*/
public String getOuterJoinGroup(String stringPath) throws PathException {
if (stringPath == null) {
throw new NullPointerException("stringPath is null");
}
Map<String, String> groups = getOuterJoinGroups();
Path path = makePath(stringPath);
if (path.endIsAttribute()) {
path = path.getPrefix();
}
if (!groups.containsKey(path.getNoConstraintsString())) {
throw new NoSuchElementException("Path " + stringPath + " is not in the query");
}
return groups.get(path.getNoConstraintsString());
}
/**
* Returns true if a path string is in the root outer join group of this query.
*
* @param stringPath a path String
* @return true if the given path is in the root outer join group, false if it contains outer
* joins
* @throws NullPointerException if pathString is null
* @throws PathException if the query is invalid or the path is invalid
* @throws NoSuchElementException if the path is not in the query
*/
public boolean isPathCompletelyInner(String stringPath) throws PathException {
String root = getRootClass();
return root.equals(getOuterJoinGroup(stringPath));
}
public synchronized Set<String> getCandidateLoops(String stringPath) throws PathException {
if (stringPath == null) {
throw new NullPointerException("stringPath is null");
}
Path path = makePath(stringPath);
if (path.endIsAttribute()) {
throw new IllegalArgumentException("stringPath \"" + stringPath
+ "\" is an attribute, not a class");
}
String lRootClass = getRootClass();
String rootOfStringPath = path.getStartClassDescriptor().getUnqualifiedName();
if ((lRootClass != null) && (!lRootClass.equals(rootOfStringPath))) {
throw new NoSuchElementException("Path " + stringPath + " is not in the query");
}
if (lRootClass == null) {
outerJoinGroups.put(rootOfStringPath, rootOfStringPath);
}
Map<String, String> groups = new HashMap<String, String>(getOuterJoinGroups());
Path groupPath = path;
Set<String> toAdd = new HashSet<String>();
while (!(groups.containsKey(groupPath.getNoConstraintsString()))) {
toAdd.add(groupPath.toStringNoConstraints());
groupPath = groupPath.getPrefix();
}
String group = groups.get(groupPath.getNoConstraintsString());
for (String toAddElement : toAdd) {
groups.put(toAddElement, group);
}
Class<?> type = path.getEndType();
Set<String> lExistingLoops = getExistingLoops();
Set<String> retval = new HashSet<String>();
for (Map.Entry<String, String> entry : groups.entrySet()) {
if (!entry.getKey().equals(stringPath)) {
Path entryPath = makePath(entry.getKey());
if (type.isAssignableFrom(entryPath.getEndType())
|| entryPath.getEndType().isAssignableFrom(type)) {
if (group.equals(entry.getValue())) {
String desc = stringPath.compareTo(entry.getKey()) > 0
? entry.getKey() + " -- " + stringPath
: stringPath + " -- " + entry.getKey();
if (!lExistingLoops.contains(desc)) {
retval.add(entry.getKey());
}
}
}
}
}
return retval;
}
/**
* Returns the outer join constraint codes groups map for this query, if the query verifies
* correctly.
*
* @return a Map from outer join group to the Set of constraint codes in the group
* @throws PathException if the query does not verify
*/
public synchronized Map<String, Set<String>> getConstraintGroups() throws PathException {
List<String> problems = verifyQuery();
if (problems.isEmpty()) {
return Collections.unmodifiableMap(new LinkedHashMap<String, Set<String>>(
constraintGroups));
}
throw new PathException("Query does not verify: " + problems, null);
}
/**
* Returns a List of logic Strings according to the different outer join sections of the query.
*
* @return a List of String
* @throws PathException if the query does not verify
*/
public synchronized List<String> getGroupedConstraintLogic() throws PathException {
if (logic == null) {
return Collections.emptyList();
}
Map<String, Set<String>> groups = getConstraintGroups();
List<LogicExpression> grouped = logic.split(new ArrayList<Set<String>>(groups.values()));
List<String> retval = new ArrayList<String>();
for (LogicExpression group : grouped) {
if (group != null) {
retval.add(group.toString());
}
}
return retval;
}
public synchronized LogicExpression getConstraintLogicForGroup(String group)
throws PathException {
List<String> problems = verifyQuery();
if (problems.isEmpty()) {
if (logic == null) {
return null;
} else {
Set<String> codes = constraintGroups.get(group);
if (codes == null) {
throw new IllegalArgumentException("Outer join group " + group
+ " does not seem to be in this query. Valid inputs are "
+ constraintGroups.keySet());
}
if (codes.isEmpty()) {
return null;
} else {
return logic.getSection(codes);
}
}
}
throw new PathException("Query does not verify: " + problems, null);
}
/**
* Adds all the parts of a Path to a Set. Call this with only a non-attribute Path.
*
* @param validMainPaths a Set of Strings to add to
* @param path a Path object
*/
private static void addValidPaths(Set<String> validMainPaths, Path path) {
while (!path.isRootPath()) {
validMainPaths.add(path.toStringNoConstraints());
path = path.getPrefix();
}
validMainPaths.add(path.toStringNoConstraints());
}
private boolean isInner(Path path) {
if (path.isRootPath()) {
return false;
}
if (path.endIsAttribute()) {
throw new IllegalArgumentException("Cannot call isInner() with a path that is an "
+ "attribute");
}
OuterJoinStatus status = getOuterJoinStatus(path.getNoConstraintsString());
if (OuterJoinStatus.INNER.equals(status)) {
return true;
} else if (OuterJoinStatus.OUTER.equals(status)) {
return false;
}
// Fall back on defaults
return true;
}
private static final Pattern PATH_MATCHER = Pattern.compile("([a-zA-Z0-9]+\\.)*[a-zA-Z0-9]+");
public static void checkPathFormat(String path) {
if (path == null) {
throw new NullPointerException("Path must not be null");
}
if (!PATH_MATCHER.matcher(path).matches()) {
throw new IllegalArgumentException("Path \"" + path + "\" does not match regular "
+ "expression \"([a-zA-Z0-9]+\\.)*[a-zA-Z0-9]+\"");
}
}
/**
* Get the PathQuery that should be executed. This should be called by code creating an
* ObjectStore query from a PathQuery. For PathQuery the method returns this, subclasses can
* override. TemplateQuery removes optional constraints that have been switched off in the
* returned query.
* @return a version of the query to execute
*/
public PathQuery getQueryToExecute() {
return this;
}
/**
* A method to sort constraints by a given lists, provided to allow TemplateQuery to set a
* specific sort order that will be preserved in a round-trip to XML. A list of constraints
* is provided, the constraints map is updated to reflect that order. The list does not need
* to contain all constraints in the query - TemplateQuery only needs to order the editable
* constraints.
* @param listToSortBy a list to define the new constraint order
*/
protected synchronized void sortConstraints(List<PathConstraint> listToSortBy) {
ConstraintComparator comparator = new ConstraintComparator(listToSortBy);
TreeMap<PathConstraint, String> orderedConstraints =
new TreeMap<PathConstraint, String>(comparator);
orderedConstraints.putAll(constraints);
constraints = new LinkedHashMap<PathConstraint, String>(orderedConstraints);
}
private class ConstraintComparator implements Comparator<PathConstraint>
{
private List<PathConstraint> listToSortBy;
public ConstraintComparator (List<PathConstraint> listToSortBy) {
this.listToSortBy = listToSortBy;
}
public int compare(PathConstraint c1, PathConstraint c2) {
if (listToSortBy.contains(c1) && listToSortBy.contains(c2)) {
return listToSortBy.indexOf(c1) - listToSortBy.indexOf(c2);
}
return 0;
}
}
/**
* Converts this object into a rudimentary String format, containing all the data.
*
* {@inheritDoc}
*/
@Override public synchronized String toString() {
return "PathQuery( view: " + view + ", orderBy: " + orderBy + ", constraints: "
+ constraints + ", logic: " + logic + ", outerJoinStatus: " + outerJoinStatus
+ ", descriptions: " + descriptions + ", description: " + description + ")";
}
/**
* Convert a PathQuery to XML.
*
* @param version the version number of the XML format
* @return this template query as XML.
*/
public synchronized String toXml(int version) {
StringWriter sw = new StringWriter();
XMLOutputFactory factory = XMLOutputFactory.newInstance();
try {
XMLStreamWriter writer = factory.createXMLStreamWriter(sw);
PathQueryBinding.marshal(this, "query", model.getName(), writer, version);
} catch (XMLStreamException e) {
throw new RuntimeException(e);
}
return sw.toString();
}
}
|
package org.flymine.modelproduction.uml;
// Most of this code originated in the ArgoUML project, which carries
// software and its documentation without fee, and without a written
// and this paragraph appear in all copies. This software program and
// California. The software program and documentation are supplied "AS
// IS", without any accompanying services from The Regents. The Regents
// does not warrant that the operation of the program will be
// uninterrupted or error-free. The end-user understands that the program
// was developed for research purposes and is advised not to rely
// exclusively on the program for any reason. IN NO EVENT SHALL THE
// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,
// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF
// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF
// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE
// PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF
// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,
// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
import ru.novosoft.uml.xmi.XMIReader;
import ru.novosoft.uml.foundation.core.*;
import ru.novosoft.uml.foundation.data_types.MMultiplicity;
import ru.novosoft.uml.model_management.MPackage;
import ru.novosoft.uml.foundation.extension_mechanisms.MTaggedValue;
import java.util.Iterator;
import java.util.Set;
import java.util.LinkedHashSet;
import java.util.Collection;
import java.io.InputStream;
import org.xml.sax.InputSource;
import org.apache.log4j.Logger;
import org.flymine.modelproduction.ModelParser;
import org.flymine.util.StringUtil;
import org.flymine.metadata.*;
/**
* Translates a model representation in XMI to FlyMine metadata (Java)
*
* @author Mark Woodbridge
*/
public class XmiParser implements ModelParser
{
protected static final Logger LOG = Logger.getLogger(XmiParser.class);
private Collection keys;
private Set attributes, references, collections;
private Set classes = new LinkedHashSet();
/**
* Read source model information in XMI format and
* construct a FlyMine Model object.
*
* @param is the source XMI file to parse
* @return the FlyMine Model created
* @throws Exception if Model not created successfully
*/
public Model process(InputStream is) throws Exception {
recurse(new XMIReader().parse(new InputSource(is)));
return new Model("testmodel", classes);
}
/**
* Adds a field (UML: attribute)
* @param attr the attribute
*/
protected void generateAttribute(MAttribute attr) {
String name = attr.getName();
String type = qualify(attr.getType().getName());
boolean primaryKey = keys.contains(attr.getName());
attributes.add(new AttributeDescriptor(name, primaryKey, type));
}
/**
* Adds a class or interface (UML: classifier)
* @param cls the classifier
*/
protected void generateClassifier(MClassifier cls) {
String name = qualified(cls);
String extend = generateGeneralization(cls.getGeneralizations());
String implement;
boolean isInterface;
if (cls instanceof MClass) {
isInterface = false;
implement = generateSpecification((MClass) cls);
} else {
isInterface = true;
implement = null;
}
keys = getKeys(cls);
attributes = new LinkedHashSet();
Iterator strIter = getAttributes(cls).iterator();
while (strIter.hasNext()) {
generateAttribute((MAttribute) strIter.next());
}
references = new LinkedHashSet();
collections = new LinkedHashSet();
Iterator endIter = cls.getAssociationEnds().iterator();
while (endIter.hasNext()) {
generateAssociationEnd(((MAssociationEnd) endIter.next()).getOppositeEnd());
}
classes.add(new ClassDescriptor(name, extend, implement, isInterface, attributes,
references, collections));
}
/**
* Adds a reference or collection of references to business objects (UML: association)
* @param ae the local end of the association
*/
protected void generateAssociationEnd(MAssociationEnd ae) {
if (ae.isNavigable()) {
String name = nameEnd(ae);
String referencedType = qualified(ae.getType());
MAssociationEnd ae2 = ae.getOppositeEnd();
String reverseReference = ae2.isNavigable() ? nameEnd(ae2) : null;
boolean primaryKey = keys.contains(name);
MMultiplicity m = ae.getMultiplicity();
if (MMultiplicity.M1_1.equals(m) || MMultiplicity.M0_1.equals(m)) {
references.add(new ReferenceDescriptor(name, primaryKey, referencedType,
reverseReference));
} else {
boolean ordered = ae.getOrdering() != null
&& !ae.getOrdering().getName().equals("unordered");
collections.add(new CollectionDescriptor(name, primaryKey, referencedType,
reverseReference, ordered));
}
}
}
private void recurse(MNamespace ns) {
Iterator ownedElements = ns.getOwnedElements().iterator();
while (ownedElements.hasNext()) {
MModelElement me = (MModelElement) ownedElements.next();
if (me instanceof MPackage) {
recurse((MNamespace) me);
}
if (me instanceof MClass && isBusinessObject((MClassifier) me)) {
generateClassifier((MClass) me);
}
if (me instanceof MInterface && isBusinessObject((MClassifier) me)) {
generateClassifier((MInterface) me);
}
}
}
private String generateSpecification(MClass cls) {
Collection realizations = getSpecifications(cls);
if (realizations == null || realizations.size() == 0) {
return null;
}
StringBuffer sb = new StringBuffer();
Iterator clsEnum = realizations.iterator();
while (clsEnum.hasNext()) {
MInterface i = (MInterface) clsEnum.next();
sb.append(qualified(i));
if (clsEnum.hasNext()) {
sb.append(" ");
}
}
return sb.toString();
}
private String generateGeneralization(Collection generalizations) {
if (generalizations == null || generalizations.size() == 0) {
return null;
}
Collection classes = new LinkedHashSet();
Iterator enum = generalizations.iterator();
while (enum.hasNext()) {
MGeneralization g = (MGeneralization) enum.next();
MGeneralizableElement ge = g.getParent();
if (ge != null) {
classes.add(ge);
}
}
return generateClassSet(classes);
}
private String generateClassSet(Collection classifiers) {
if (classifiers == null) {
return "";
}
StringBuffer sb = new StringBuffer();
Iterator clsEnum = classifiers.iterator();
while (clsEnum.hasNext()) {
MClassifier cls = (MClassifier) clsEnum.next();
sb.append(qualified(cls));
if (clsEnum.hasNext()) {
sb.append(" ");
}
}
return sb.toString();
}
private String qualified(MClassifier cls) {
return getPackagePath(cls) + "." + cls.getName();
}
private Collection getSpecifications(MClassifier cls) {
Collection result = new LinkedHashSet();
Iterator depIterator = cls.getClientDependencies().iterator();
while (depIterator.hasNext()) {
MDependency dep = (MDependency) depIterator.next();
if ((dep instanceof MAbstraction)
&& dep.getStereotype() != null
&& dep.getStereotype().getName() != null
&& dep.getStereotype().getName().equals("realize")) {
MInterface i = (MInterface) dep.getSuppliers().toArray()[0];
result.add(i);
}
}
return result;
}
private Collection getAttributes(MClassifier classifier) {
Collection result = new LinkedHashSet();
Iterator features = classifier.getFeatures().iterator();
while (features.hasNext()) {
MFeature feature = (MFeature) features.next();
if (feature instanceof MAttribute) {
result.add(feature);
}
}
return result;
}
private String getPackagePath(MClassifier cls) {
String packagePath = cls.getNamespace().getName();
MNamespace parent = cls.getNamespace().getNamespace();
while (parent != null) {
packagePath = parent.getName() + "." + packagePath;
parent = parent.getNamespace();
}
return packagePath;
}
private Collection getKeys(MClassifier cls) {
Set keyFields = new LinkedHashSet();
Collection tvs = cls.getTaggedValues();
if (tvs != null && tvs.size() > 0) {
Iterator iter = tvs.iterator();
while (iter.hasNext()) {
MTaggedValue tv = (MTaggedValue) iter.next();
if (tv.getTag().equals("key")) {
keyFields.addAll(StringUtil.tokenize(tv.getValue()));
}
}
}
Iterator parents = cls.getGeneralizations().iterator();
if (parents.hasNext()) {
keyFields.addAll(getKeys((MClassifier) ((MGeneralization) parents.next()).getParent()));
}
return keyFields;
}
private String nameEnd(MAssociationEnd ae) {
String name = ae.getName();
if (name == null || name.length() == 0) {
name = ae.getType().getName();
MMultiplicity m = ae.getMultiplicity();
if (!MMultiplicity.M1_1.equals(m) && !MMultiplicity.M0_1.equals(m)) {
name = StringUtil.pluralise(name);
}
}
return StringUtil.decapitalise(name);
}
private String qualify(String type) {
if (type.equals("String")) {
return "java.lang.String";
}
return type;
}
private boolean isBusinessObject(MClassifier cls) {
String name = cls.getName();
if (name == null || name.length() == 0
|| name.equals("void") || name.equals("char") || name.equals("byte")
|| name.equals("short") || name.equals("int") || name.equals("long")
|| name.equals("boolean") || name.equals("float") || name.equals("double")) {
return false;
}
String packagePath = getPackagePath(cls);
if (packagePath.endsWith("java.lang") || packagePath.endsWith("java.util")) {
return false;
}
return true;
}
}
|
package org.intermine.task;
import java.io.FileReader;
import java.io.Reader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.apache.log4j.Logger;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Task;
import org.intermine.objectstore.ObjectStore;
import org.intermine.objectstore.ObjectStoreFactory;
import org.intermine.web.Profile;
import org.intermine.web.ProfileManager;
import org.intermine.web.RequestPasswordAction;
import org.intermine.web.TemplateQuery;
import org.intermine.web.TemplateQueryBinding;
/**
* Load template queries form an XML file into a given user profile.
*
* @author Thomas Riley
*/
public class LoadDefaultTemplatesTask extends Task
{
private static final Logger LOG = Logger.getLogger(LoadDefaultTemplatesTask.class);
protected String xmlFile;
protected String username;
protected String alias;
/**
* Set the templates xml file.
* @param file to xml file
*/
public void setTemplatesXml(String file) {
xmlFile = file;
}
/**
* Set the account name to laod template to.
* @param user username to load templates into
*/
public void setUsername(String user) {
username = user;
}
/**
* Load templates from an xml file into a userprofile account.
*
* @see Task#execute
*/
public void execute() throws BuildException {
// Needed so that STAX can find it's implementation classes
ClassLoader cl = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
try {
ObjectStore os = ObjectStoreFactory.getObjectStore();
ProfileManager pm = new ProfileManager(os);
Reader templateQueriesReader = new FileReader(xmlFile);
Map templateQueries = new TemplateQueryBinding().unmarshal(templateQueriesReader);
Profile profile = null;
if (!pm.hasProfile(username)) {
LOG.info("Creating profile for " + username);
profile = new Profile(pm, username, new HashMap(), new HashMap(), new HashMap());
String password = RequestPasswordAction.generatePassword();
pm.saveProfile(profile);
pm.setPassword(username, password);
} else {
LOG.warn("Profile for " + username + ", clearing template queries");
profile = pm.getProfile(username, pm.getPassword(username));
Map tmpls = new HashMap(profile.getSavedTemplates());
Iterator iter = tmpls.keySet().iterator();
while (iter.hasNext()) {
profile.deleteTemplate((String) iter.next());
}
}
if (profile.getSavedTemplates().size() == 0) {
Iterator iter = templateQueries.values().iterator();
while (iter.hasNext()) {
TemplateQuery template = (TemplateQuery) iter.next();
String append = "";
if (!template.isValid()) {
append = " [invalid]";
}
log("Adding template \"" + template.getName() + "\"" + append);
profile.saveTemplate(template.getName(), template);
}
}
} catch (Exception e) {
throw new BuildException(e);
} finally {
Thread.currentThread().setContextClassLoader(cl);
}
}
}
|
package org.intermine.web.logic.query;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import org.intermine.objectstore.query.BagConstraint;
import org.intermine.objectstore.query.ResultsInfo;
import org.intermine.metadata.Model;
import org.intermine.path.Path;
import org.intermine.path.PathError;
import org.intermine.util.CollectionUtil;
import java.io.StringReader;
import javax.servlet.ServletContext;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
/**
* Class to represent a path-based query.
*
* @author Mark Woodbridge
* @author Thomas Riley
*/
public class PathQuery
{
private static final Logger LOG = Logger.getLogger(PathQuery.class);
private Model model;
protected LinkedHashMap<String, PathNode> nodes = new LinkedHashMap<String, PathNode>();
private List<Path> view = new ArrayList<Path>();
private List<OrderBy> sortOrder = new ArrayList<OrderBy>();
private ResultsInfo info;
ArrayList<Throwable> problems = new ArrayList<Throwable>();
protected LogicExpression constraintLogic = null;
private Map<Path, String> pathDescriptions = new HashMap<Path, String>();
/**
* Construct a new instance of PathQuery.
* @param model the Model on which to base this query
*/
public PathQuery(Model model) {
this.model = model;
}
/**
* Construct a new instance of PathQuery from an existing
* instance.
* @param query the existing query
*/
public PathQuery(PathQuery query) {
this.model = query.model;
this.nodes = new LinkedHashMap<String, PathNode>(query.nodes);
this.view = new ArrayList<Path>(query.view);
this.sortOrder = new ArrayList<OrderBy>(query.sortOrder);
this.info = query.info;
this.problems = new ArrayList<Throwable>(query.problems);
this.constraintLogic = query.constraintLogic;
this.pathDescriptions = new HashMap<Path, String>(query.pathDescriptions);
}
/**
* Get the constraint logic expression.
* @return the constraint logic expression
*/
public String getConstraintLogic() {
if (constraintLogic == null) {
return null;
} else {
return constraintLogic.toString();
}
}
/**
* Set the constraint logic expression. This expresses the AND and OR
* relation between constraints.
* @param constraintLogic the constraint logic expression
*/
public void setConstraintLogic(String constraintLogic) {
if (constraintLogic == null) {
this.constraintLogic = null;
return;
}
try {
this.constraintLogic = new LogicExpression(constraintLogic);
} catch (IllegalArgumentException err) {
LOG.error("Failed to parse constraintLogic: " + constraintLogic, err);
}
}
/**
* Make sure that the logic expression is valid for the current query. Remove
* any unknown constraint codes and add any constraints that aren't included
* (using the default operator).
* @param defaultOperator the default logical operator
*/
public void syncLogicExpression(String defaultOperator) {
if (getAllConstraints().size() <= 1) {
setConstraintLogic(null);
} else {
Set<String> codes = getConstraintCodes();
if (constraintLogic != null) {
// limit to the actual variables
constraintLogic.removeAllVariablesExcept(getConstraintCodes());
// add anything that isn't there
codes.removeAll(constraintLogic.getVariableNames());
}
addCodesToLogic(codes, defaultOperator);
}
}
/**
* Get all constraint codes.
* @return all present constraint codes
*/
private Set<String> getConstraintCodes() {
Set<String> codes = new HashSet<String>();
for (Iterator<Constraint> iter = getAllConstraints().iterator(); iter.hasNext(); ) {
codes.add(iter.next().getCode());
}
return codes;
}
/**
* Gets the value of model
* @return the value of model
*/
public Model getModel() {
return model;
}
/**
* Gets the value of nodes
* @return the value of nodes
*/
public Map<String, PathNode> getNodes() {
return nodes;
}
/**
* Get a PathNode by path.
* @param path a path
* @return the PathNode for path path
*/
public PathNode getNode(String path) {
return nodes.get(path);
}
/**
* Get all constraints.
* @return all constraints
*/
public List<Constraint> getAllConstraints() {
List<Constraint> list = new ArrayList<Constraint>();
for (Iterator<PathNode> iter = nodes.values().iterator(); iter.hasNext(); ) {
PathNode node = iter.next();
list.addAll(node.getConstraints());
}
return list;
}
/**
* Sets the value of view
* @param view a List of Path
*/
public void setView(List<Path> view) {
if (view == null) {
throw new RuntimeException("setView() was passed null");
}
this.view = view;
}
/**
* Gets the value of view
* @return a List of paths
*/
public List<Path> getView() {
return view;
}
/**
* Return the view as a List of Strings.
* @return the view as Strings
*/
public List<String> getViewStrings() {
List<String> retList = new ArrayList<String>();
for (Path path: view) {
retList.add(path.toStringNoConstraints());
}
return retList;
}
/**
* Sets the sort order
* @param sortOrder list of paths
*/
public void setSortOrder(List<OrderBy> sortOrder) {
this.sortOrder = sortOrder;
}
/**
* Gets the sort order
* @return a List of paths
*/
public List<OrderBy> getSortOrder() {
return sortOrder;
}
/**
* Add a path to the view
* @param viewString the String version of the path to add - should not include any class
* constraints (ie. use "Departement.employee.name" not "Departement.employee[Contractor].name")
*/
public void addPathStringToView(String viewString) {
try {
view.add(MainHelper.makePath(model, this, viewString));
} catch (PathError e) {
addProblem(e);
}
}
/**
* Remove the Path with the given String representation from the view. If the pathString
* refers to a path that appears in a PathError in the problems collection, remove that problem.
* @param pathString the path to remove
*/
public void removePathStringFromView(String pathString) {
Iterator<Path> iter = view.iterator();
while (iter.hasNext()) {
Path viewPath = iter.next();
if (viewPath.toStringNoConstraints().equals(pathString)
|| viewPath.toString().equals(pathString)) {
iter.remove();
}
}
Iterator<Throwable> throwIter = problems.iterator();
while (throwIter.hasNext()) {
Throwable thr = throwIter.next();
if (thr instanceof PathError) {
PathError pe = (PathError) thr;
if (pe.getPathString().equals(pathString)) {
throwIter.remove();
}
}
}
}
private Path getFirstPathFromView() {
Path viewPath = null;
if (!view.isEmpty()) {
Iterator<Path> iter = view.iterator();
viewPath = iter.next();
}
return viewPath;
}
// private void addPathToSortOrder(Path sortOrderPath, String direction) {
// try {
// sortOrder.clear(); // there can only be one sort column
// if (sortOrderPath != null) {
// OrderBy o = new OrderBy(sortOrderPath, direction);
// sortOrder.add(o);
// } catch (PathError e) {
// addProblem(e);
/**
* @param direction New sorting direction - asc or desc
*/
public void changeDirection(String direction) {
try {
sortOrder.get(0).setDirection(direction);
} catch (PathError e) {
addProblem(e);
}
}
/**
* Add a path to the sort order
* @param sortOrderString the String version of the path to add - should not include any class
* constraints (ie. use "Departement.employee.name" not "Departement.employee[Contractor].name")
* @param direction asc or desc
*/
public void addPathStringToSortOrder(String sortOrderString, String direction) {
try {
sortOrder.clear(); // there can only be one sort column
Path p = MainHelper.makePath(model, this, sortOrderString);
OrderBy o = new OrderBy(p, direction);
sortOrder.add(o);
} catch (PathError e) {
addProblem(e);
}
}
/**
* Remove a path from the sort order. Replace with first item on select list.
*/
public void removePathStringFromSortOrder() {
try {
sortOrder.clear(); // there can only be one sort column
Path p = getFirstPathFromView();
if (p != null) {
OrderBy o = new OrderBy(p, "asc");
sortOrder.add(o);
}
} catch (PathError e) {
addProblem(e);
}
}
/**
* Return true if and only if the view contains a Path that has pathString as its String
* representation.
* @param pathString the path to test
* @return true if found
*/
public boolean viewContains(String pathString) {
for (Path viewPath: getView()) {
if (viewPath.toStringNoConstraints().equals(pathString)
|| viewPath.toString().equals(pathString)) {
return true;
}
}
return false;
}
/**
* Get info regarding this query
* @return the info
*/
public ResultsInfo getInfo() {
return info;
}
/**
* Set info about this query
* @param info the info
*/
public void setInfo(ResultsInfo info) {
this.info = info;
}
/**
* Provide a list of the names of bags mentioned in the query
* @return the list of bag names
*/
public List<Object> getBagNames() {
List<Object> bagNames = new ArrayList<Object>();
for (Iterator<PathNode> i = nodes.values().iterator(); i.hasNext();) {
PathNode node = i.next();
for (Iterator j = node.getConstraints().iterator(); j.hasNext();) {
Constraint c = (Constraint) j.next();
if (BagConstraint.VALID_OPS.contains(c.getOp())) {
bagNames.add(c.getValue());
}
}
}
return bagNames;
}
/**
* Add a node to the query using a path, adding parent nodes if necessary
* @param path the path for the new Node
* @return the PathNode that was added to the nodes Map
*/
public PathNode addNode(String path) {
PathNode node;
// the new node will be inserted after this one or at the end if null
String previousNodePath = null;
if (path.indexOf(".") == -1) {
node = new PathNode(path);
// Check whether starting point exists
try {
MainHelper.getQualifiedTypeName(path, model);
} catch (ClassNotFoundException err) {
addProblem(err);
}
} else {
String prefix = path.substring(0, path.lastIndexOf("."));
if (nodes.containsKey(prefix)) {
Iterator<String> pathsIter = nodes.keySet().iterator();
while (pathsIter.hasNext()) {
String pathFromMap = pathsIter.next();
if (pathFromMap.startsWith(prefix)) {
previousNodePath = pathFromMap;
}
}
PathNode parent = nodes.get(prefix);
String fieldName = path.substring(path.lastIndexOf(".") + 1);
node = new PathNode(parent, fieldName);
try {
node.setModel(model);
} catch (Exception err) {
addProblem(err);
}
} else {
addNode(prefix);
return addNode(path);
}
}
nodes = CollectionUtil.linkedHashMapAdd(nodes, previousNodePath, path, node);
return node;
}
/**
* Get the exceptions generated while deserialising this path query query.
* @return exceptions relating to this path query
*/
public Throwable[] getProblems() {
return problems.toArray(new Throwable[0]);
}
/**
* Find out whether the path query is valid against the current model.
* @return true if query is valid, false if not
*/
public boolean isValid() {
return (problems.size() == 0);
}
/**
* Clone this PathQuery
* @return a PathQuery
*/
public PathQuery clone() {
PathQuery query = new PathQuery(model);
for (Iterator<Entry<String, PathNode>> i = nodes.entrySet().iterator(); i.hasNext();) {
Entry<String, PathNode> entry = i.next();
query.getNodes().put(entry.getKey(), clone(query, entry.getValue()));
}
query.getView().addAll(view);
query.getSortOrder().addAll(sortOrder);
if (problems != null) {
query.problems = new ArrayList<Throwable>(problems);
}
query.pathDescriptions = new HashMap<Path, String>(pathDescriptions);
query.setConstraintLogic(getConstraintLogic());
return query;
}
/**
* Clone a PathNode
* @param query PathQuery containing cloned PathNode
* @param node a PathNode
* @return a copy of the PathNode
*/
protected PathNode clone(PathQuery query, PathNode node) {
PathNode newNode;
PathNode parent = nodes.get(node.getPrefix());
if (parent == null) {
newNode = new PathNode(node.getType());
} else {
newNode = new PathNode(parent, node.getFieldName());
try {
newNode.setModel(model);
} catch (IllegalArgumentException err) {
query.addProblem(err);
}
newNode.setType(node.getType());
}
for (Iterator i = node.getConstraints().iterator(); i.hasNext();) {
Constraint constraint = (Constraint) i.next();
newNode.getConstraints().add(new Constraint(constraint.getOp(), constraint.getValue(),
constraint.isEditable(), constraint.getDescription(), constraint.getCode(),
constraint.getIdentifier()));
}
return newNode;
}
/**
* {@inheritDoc}
*/
public boolean equals(Object o) {
return (o instanceof PathQuery)
&& model.equals(((PathQuery) o).model)
&& nodes.equals(((PathQuery) o).nodes)
&& view.equals(((PathQuery) o).view)
&& sortOrder.equals(((PathQuery) o).sortOrder)
&& pathDescriptions.equals(((PathQuery) o).pathDescriptions);
}
/**
* {@inheritDoc}
*/
public int hashCode() {
return 2 * model.hashCode()
+ 3 * nodes.hashCode()
+ 5 * view.hashCode()
+ 7 * sortOrder.hashCode();
}
/**
* {@inheritDoc}
*/
public String toString() {
return "{PathQuery: model=" + model.getName() + ", nodes=" + nodes + ", view=" + view
+ ", sortOrder=" + sortOrder + ", pathDescriptions=" + pathDescriptions + "}";
}
/**
* Check validity of receiver by trying to create an objectstore Query. If
* conversion fails, the exception is recorded and isValid will return false.
* @param savedBags Map from bag name to bag
* @param servletContext global ServletContext object
*/
protected void checkValidity(Map savedBags, ServletContext servletContext) {
try {
MainHelper.makeQuery(this, savedBags, servletContext, null);
} catch (Exception err) {
addProblem(err);
}
}
private void addProblem(Throwable err) {
problems.add(err);
}
/**
* Get a constraint code that hasn't been used yet.
* @return a constraint code that hasn't been used yet
*/
public String getUnusedConstraintCode() {
char c = 'A';
while (getConstraintByCode("" + c) != null) {
c++;
}
return "" + c;
}
/**
* Get a Constraint involved in this query by code. Returns null if no
* constraint with the given code was found.
* @param string the constraint code
* @return the Constraint with matching code or null
*/
public Constraint getConstraintByCode(String string) {
Iterator<Constraint> iter = getAllConstraints().iterator();
while (iter.hasNext()) {
Constraint c = iter.next();
if (string.equals(c.getCode())) {
return c;
}
}
return null;
}
/**
* Add a set of codes to the logical expression using the given operator.
* @param codes Set of codes (Strings)
* @param operator operator to add with
*/
protected void addCodesToLogic(Set<String> codes, String operator) {
String logic = getConstraintLogic();
if (logic == null) {
logic = "";
} else {
logic = "(" + logic + ")";
}
for (Iterator<String> iter = codes.iterator(); iter.hasNext(); ) {
if (!StringUtils.isEmpty(logic)) {
logic += " " + operator + " ";
}
logic += iter.next();
}
setConstraintLogic(logic);
}
/**
* Remove some constraint code from the logic expression.
* @param code the code to remove
*/
public void removeCodeFromLogic(String code) {
if (constraintLogic != null) {
constraintLogic.removeVariable(code);
}
}
/**
* Get the LogicExpression. If there are one or zero constraints then
* this method will return null.
* @return the current LogicExpression or null
*/
public LogicExpression getLogic() {
return constraintLogic;
}
/**
* Serialise this query in XML format.
* @param name query name to put in xml
* @return PathQuery in XML format
*/
public String toXml(String name) {
return PathQueryBinding.marshal(this, name, model.getName());
}
/**
* Serialise to XML with no name.
* @return the XML
*/
public String toXml() {
return PathQueryBinding.marshal(this, "", model.getName());
}
/**
* Rematerialise single query from XML.
* @param xml PathQuery XML
* @return a PathQuery object
* @param savedBags Map from bag name to bag
* @param servletContext global ServletContext object
*/
public static PathQuery fromXml(String xml, Map savedBags, ServletContext servletContext) {
Map queries = PathQueryBinding.unmarshal(new StringReader(xml), savedBags, servletContext);
return (PathQuery) queries.values().iterator().next();
}
/**
* Return the map from Path objects (from the view) to their descriptions.
* @return the path descriptions map
*/
public Map<Path, String> getPathDescriptions() {
return pathDescriptions;
}
/**
* Return the description for the given path from the view.
* @param pathString the path as a string
* @return the description
*/
public String getPathDescription(String pathString) {
for (Map.Entry<Path, String> entry: pathDescriptions.entrySet()) {
if (entry.getKey().toStringNoConstraints().equals(pathString)
|| entry.getKey().toString().equals(pathString)) {
return entry.getValue();
}
}
return null;
}
/**
* Return the description for the given path from the view.
* @return the description Map
*/
public Map<String, String> getPathStringDescriptions() {
Map<String, String> retMap = new HashMap<String, String>();
for (Map.Entry<Path, String> entry: pathDescriptions.entrySet()) {
retMap.put(entry.getKey().toString(), entry.getValue());
retMap.put(entry.getKey().toStringNoConstraints(), entry.getValue());
}
return retMap;
}
/**
* Add a description to a path in the view. If the viewString isn't a valid view path, add an
* exception to the problems list.
* @param viewString the string form of a path in the view
* @param description the description
*/
public void addPathStringDescription(String viewString, String description) {
try {
Path path = MainHelper.makePath(model, this, viewString);
pathDescriptions.put(path, description);
} catch (PathError e) {
addProblem(e);
}
}
}
|
package com.iterable.iterableapi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import com.google.android.gms.ads.identifier.AdvertisingIdClient;
import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.common.GooglePlayServicesRepairableException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class IterableApi {
//region Variables
static final String TAG = "IterableApi";
static volatile IterableApi sharedInstance = new IterableApi();
private Context _applicationContext;
private String _apiKey;
private String _email;
private String _userId;
private boolean _debugMode;
private Bundle _payloadData;
private IterableNotificationData _notificationData;
private static Pattern deeplinkPattern = Pattern.compile(IterableConstants.ITBL_DEEPLINK_IDENTIFIER);
//endregion
//region Constructor
IterableApi(){
}
//endregion
//region Getters/Setters
/**
* Sets the icon to be displayed in notifications.
* The icon name should match the resource name stored in the /res/drawable directory.
* @param iconName
*/
public void setNotificationIcon(String iconName) {
setNotificationIcon(_applicationContext, iconName);
}
/**
* Retrieves the payload string for a given key.
* Used for deeplinking and retrieving extra data passed down along with a campaign.
* @param key
* @return Returns the requested payload data from the current push campaign if it exists.
*/
public String getPayloadData(String key) {
return (_payloadData != null) ? _payloadData.getString(key, null): null;
}
/**
* Returns the current context for the application.
* @return
*/
Context getMainActivityContext() {
return _applicationContext;
}
/**
* Sets debug mode.
* @param debugMode
*/
void setDebugMode(boolean debugMode) {
_debugMode = debugMode;
}
/**
* Gets the current state of the debug mode.
* @return
*/
boolean getDebugMode() {
return _debugMode;
}
/**
* Set the payload for a given intent if it is from Iterable.
* @param intent
*/
void setPayloadData(Intent intent) {
Bundle extras = intent.getExtras();
if (extras != null && extras.containsKey(IterableConstants.ITERABLE_DATA_KEY) && !IterableNotificationBuilder.isGhostPush(extras)) {
setPayloadData(extras);
}
}
/**
* Sets the payload bundle.
* @param bundle
*/
void setPayloadData(Bundle bundle) {
_payloadData = bundle;
}
/**
* Sets the IterableNotification data
* @param data
*/
void setNotificationData(IterableNotificationData data) {
_notificationData = data;
}
//endregion
//region Public Functions
/**
* Returns a shared instance of IterableApi. Updates the client data if an instance already exists.
* Should be called whenever the app is opened.
* @param currentActivity The current activity
* @param userId The current userId
* @return stored instance of IterableApi
*/
public static IterableApi sharedInstanceWithApiKeyWithUserId(Activity currentActivity, String apiKey,
String userId)
{
return sharedInstanceWithApiKeyWithUserId(currentActivity, apiKey, userId, false);
}
/**
* Returns a shared instance of IterableApi. Updates the client data if an instance already exists.
* Should be called whenever the app is opened.
* Allows the IterableApi to be intialized with debugging enabled
* @param currentActivity The current activity
* @param userId
* The current userId@return stored instance of IterableApi
*/
public static IterableApi sharedInstanceWithApiKeyWithUserId(Activity currentActivity, String apiKey,
String userId, boolean debugMode)
{
return sharedInstanceWithApiKeyWithUserId((Context) currentActivity, apiKey, userId, debugMode);
}
/**
* Returns a shared instance of IterableApi. Updates the client data if an instance already exists.
* Should be called whenever the app is opened.
* @param currentContext The current context
* @param userId The current userId
* @return stored instance of IterableApi
*/
public static IterableApi sharedInstanceWithApiKeyWithUserId(Context currentContext, String apiKey,
String userId)
{
return sharedInstanceWithApiKey(currentContext, apiKey, null, userId, false);
}
/**
* Returns a shared instance of IterableApi. Updates the client data if an instance already exists.
* Should be called whenever the app is opened.
* Allows the IterableApi to be intialized with debugging enabled
* @param currentContext The current context
* @return stored instance of IterableApi
*/
public static IterableApi sharedInstanceWithApiKeyWithUserId(Context currentContext, String apiKey,
String userId, boolean debugMode)
{
return sharedInstanceWithApiKey(currentContext, apiKey, null, userId, debugMode);
}
/**
* Returns a shared instance of IterableApi. Updates the client data if an instance already exists.
* Should be called whenever the app is opened.
* @param currentActivity The current activity
* @param email The current email
* @return stored instance of IterableApi
*/
public static IterableApi sharedInstanceWithApiKey(Activity currentActivity, String apiKey,
String email)
{
return sharedInstanceWithApiKey(currentActivity, apiKey, email, false);
}
/**
* Returns a shared instance of IterableApi. Updates the client data if an instance already exists.
* Should be called whenever the app is opened.
* Allows the IterableApi to be intialized with debugging enabled
* @param currentActivity The current activity
* @param email The current email
* @return stored instance of IterableApi
*/
public static IterableApi sharedInstanceWithApiKey(Activity currentActivity, String apiKey,
String email, boolean debugMode)
{
return sharedInstanceWithApiKey((Context) currentActivity, apiKey, email, debugMode);
}
/**
* Returns a shared instance of IterableApi. Updates the client data if an instance already exists.
* Should be called whenever the app is opened.
* @param currentContext The current context
* @param email The current email
* @return stored instance of IterableApi
*/
public static IterableApi sharedInstanceWithApiKey(Context currentContext, String apiKey,
String email)
{
return sharedInstanceWithApiKey(currentContext, apiKey, email, false);
}
/**
* Returns a shared instance of IterableApi. Updates the client data if an instance already exists.
* Should be called whenever the app is opened.
* Allows the IterableApi to be intialized with debugging enabled
* @param currentContext The current context
* @param email The current email
* @return stored instance of IterableApi
*/
public static IterableApi sharedInstanceWithApiKey(Context currentContext, String apiKey,
String email, boolean debugMode)
{
return sharedInstanceWithApiKey(currentContext, apiKey, email, null, debugMode);
}
private static IterableApi sharedInstanceWithApiKey(Context currentContext, String apiKey,
String email, String userId, boolean debugMode)
{
sharedInstance.updateData(currentContext.getApplicationContext(), apiKey, email, userId);
if (currentContext instanceof Activity) {
Activity currentActivity = (Activity) currentContext;
sharedInstance.onNewIntent(currentActivity.getIntent());
} else {
IterableLogger.w(TAG, "Notification Opens will not be tracked: "+
"sharedInstanceWithApiKey called with a Context that is not an instance of Activity. " +
"Pass in an Activity to IterableApi.sharedInstanceWithApiKey to enable open tracking" +
"or call onNewIntent when a new Intent is received.");
}
sharedInstance.setDebugMode(debugMode);
return sharedInstance;
}
/**
* Tracks a click on the uri if it is an iterable link.
* @param uri the
* @param onCallback Calls the callback handler with the destination location
* or the original url if it is not a interable link.
*/
public static void getAndTrackDeeplink(String uri, IterableHelper.IterableActionHandler onCallback) {
if (uri != null) {
Matcher m = deeplinkPattern.matcher(uri);
if (m.find( )) {
IterableApiRequest request = new IterableApiRequest(null, uri, null, IterableApiRequest.REDIRECT, onCallback);
new IterableRequest().execute(request);
} else {
onCallback.execute(uri);
}
} else {
onCallback.execute(null);
}
}
/**
* Debugging function to send API calls to different url endpoints.
* @param url
*/
public static void overrideURLEndpointPath(String url) {
IterableRequest.overrideUrl = url;
}
/**
* Call onNewIntent to set the payload data and track pushOpens directly if
* sharedInstanceWithApiKey was called with a Context rather than an Activity.
*/
public void onNewIntent(Intent intent) {
if (isIterableIntent(intent)) {
setPayloadData(intent);
tryTrackNotifOpen(intent);
} else {
IterableLogger.d(TAG, "onNewIntent not triggered by an Iterable notification");
}
}
/**
* Returns whether or not the intent was sent from Iterable.
*/
public boolean isIterableIntent(Intent intent) {
if (intent != null) {
Bundle extras = intent.getExtras();
return (extras != null && extras.containsKey(IterableConstants.ITERABLE_DATA_KEY));
}
return false;
}
/**
* Registers a device token with Iterable.
* @param applicationName
* @param token
*/
public void registerDeviceToken(String applicationName, String token) {
registerDeviceToken(applicationName, token, null);
}
/**
* Registers a device token with Iterable.
* @param applicationName
* @param token
* @param pushServicePlatform
*/
public void registerDeviceToken(final String applicationName, final String token, final String pushServicePlatform) {
if (token != null) {
new Thread(new Runnable() {
public void run() {
registerDeviceToken(applicationName, token, pushServicePlatform, null);
}
}).start();
}
}
/**
* Track an event.
* @param eventName
*/
public void track(String eventName) {
track(eventName, 0, 0, null);
}
/**
* Track an event.
* @param eventName
* @param dataFields
*/
public void track(String eventName, JSONObject dataFields) {
track(eventName, 0, 0, dataFields);
}
/**
* Track an event.
* @param eventName
* @param campaignId
* @param templateId
*/
public void track(String eventName, int campaignId, int templateId) {
track(eventName, campaignId, templateId, null);
}
/**
* Track an event.
* @param eventName
* @param campaignId
* @param templateId
* @param dataFields
*/
public void track(String eventName, int campaignId, int templateId, JSONObject dataFields) {
JSONObject requestJSON = new JSONObject();
try {
addEmailOrUserIdToJson(requestJSON);
requestJSON.put(IterableConstants.KEY_EVENT_NAME, eventName);
requestJSON.put(IterableConstants.KEY_CAMPAIGN_ID, campaignId);
requestJSON.put(IterableConstants.KEY_TEMPLATE_ID, templateId);
requestJSON.put(IterableConstants.KEY_DATA_FIELDS, dataFields);
sendPostRequest(IterableConstants.ENDPOINT_TRACK, requestJSON);
}
catch (JSONException e) {
e.printStackTrace();
}
}
public void sendPush(String email, int campaignId) {
sendPush(email, campaignId, null, null);
}
/**
* Sends a push campaign to an email address at the given time.
* @param sendAt Schedule the message for up to 365 days in the future.
* If set in the past, message is sent immediately.
* Format is YYYY-MM-DD HH:MM:SS in UTC
*/
public void sendPush(String email, int campaignId, Date sendAt) {
sendPush(email, campaignId, sendAt, null);
}
/**
* Sends a push campaign to an email address.
* @param email
* @param campaignId
* @param dataFields
*/
public void sendPush(String email, int campaignId, JSONObject dataFields) {
sendPush(email, campaignId, null, dataFields);
}
/**
* Sends a push campaign to an email address at the given time.
* @param sendAt Schedule the message for up to 365 days in the future.
* If set in the past, message is sent immediately.
* Format is YYYY-MM-DD HH:MM:SS in UTC
*/
public void sendPush(String email, int campaignId, Date sendAt, JSONObject dataFields) {
JSONObject requestJSON = new JSONObject();
try {
requestJSON.put(IterableConstants.KEY_RECIPIENT_EMAIL, email);
requestJSON.put(IterableConstants.KEY_CAMPAIGN_ID, campaignId);
if (sendAt != null){
SimpleDateFormat sdf = new SimpleDateFormat(IterableConstants.DATEFORMAT);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
String dateString = sdf.format(sendAt);
requestJSON.put(IterableConstants.KEY_SEND_AT, dateString);
}
sendPostRequest(IterableConstants.ENDPOINT_PUSH_TARGET, requestJSON);
}
catch (JSONException e) {
e.printStackTrace();
}
}
/**
* Updates the current user's email.
* @param newEmail
*/
public void updateEmail(String newEmail) {
if (_email != null) {
JSONObject requestJSON = new JSONObject();
try {
requestJSON.put(IterableConstants.KEY_CURRENT_EMAIL, _email);
requestJSON.put(IterableConstants.KEY_NEW_EMAIL, newEmail);
sendPostRequest(IterableConstants.ENDPOINT_UPDATE_EMAIL, requestJSON);
_email = newEmail;
}
catch (JSONException e) {
e.printStackTrace();
}
} else {
IterableLogger.w(TAG, "updateEmail should not be called with a userId. " +
"Init SDK with sharedInstanceWithApiKey instead of sharedInstanceWithApiKeyWithUserId");
}
}
/**
* Updates the current user.
* @param dataFields
*/
public void updateUser(JSONObject dataFields) {
JSONObject requestJSON = new JSONObject();
try {
addEmailOrUserIdToJson(requestJSON);
requestJSON.put(IterableConstants.KEY_DATA_FIELDS, dataFields);
sendPostRequest(IterableConstants.ENDPOINT_UPDATE_USER, requestJSON);
}
catch (JSONException e) {
e.printStackTrace();
}
}
/**
* Registers for push notifications.
* @param iterableAppId
* @param gcmProjectNumber
*/
public void registerForPush(String iterableAppId, String gcmProjectNumber) {
registerForPush(iterableAppId, gcmProjectNumber, IterableConstants.MESSAGING_PLATFORM_GOOGLE);
}
/**
* Registers for push notifications.
* @param iterableAppId
* @param projectNumber
* @param pushServicePlatform
*/
public void registerForPush(String iterableAppId, String projectNumber, String pushServicePlatform) {
IterablePushRegistrationData data = new IterablePushRegistrationData(iterableAppId, projectNumber, pushServicePlatform, IterablePushRegistrationData.PushRegistrationAction.ENABLE);
new IterablePushRegistration().execute(data);
}
/**
* Disables the device from push notifications
* @param iterableAppId
* @param gcmProjectNumber
*/
public void disablePush(String iterableAppId, String gcmProjectNumber) {
disablePush(iterableAppId, gcmProjectNumber, IterableConstants.MESSAGING_PLATFORM_GOOGLE);
}
/**
* Disables the device from push notifications
* @param iterableAppId
* @param projectNumber
* @param pushServicePlatform
*/
public void disablePush(String iterableAppId, String projectNumber, String pushServicePlatform) {
IterablePushRegistrationData data = new IterablePushRegistrationData(iterableAppId, projectNumber, pushServicePlatform, IterablePushRegistrationData.PushRegistrationAction.DISABLE);
new IterablePushRegistration().execute(data);
}
/**
* Updates the user subscription preferences. Passing in an empty array will clear the list, passing in null will not modify the list
* @param emailListIds
* @param unsubscribedChannelIds
* @param unsubscribedMessageTypeIds
*/
public void updateSubscriptions(Integer[] emailListIds, Integer[] unsubscribedChannelIds, Integer[] unsubscribedMessageTypeIds) {
JSONObject requestJSON = new JSONObject();
addEmailOrUserIdToJson(requestJSON);
tryAddArrayToJSON(requestJSON, IterableConstants.KEY_EMAIL_LIST_IDS, emailListIds);
tryAddArrayToJSON(requestJSON, IterableConstants.KEY_UNSUB_CHANNEL, unsubscribedChannelIds);
tryAddArrayToJSON(requestJSON, IterableConstants.KEY_UNSUB_MESSAGE, unsubscribedMessageTypeIds);
sendPostRequest(IterableConstants.ENDPOINT_UPDATE_USER_SUBS, requestJSON);
}
/**
* Attempts to add an array as a JSONArray to a JSONObject
* @param requestJSON
* @param key
* @param value
*/
void tryAddArrayToJSON(JSONObject requestJSON, String key, Object[] value) {
if (requestJSON != null && key != null && value != null)
try {
JSONArray mJSONArray = new JSONArray(Arrays.asList(value));
requestJSON.put(key, mJSONArray);
} catch (JSONException e) {
IterableLogger.e(TAG, e.toString());
}
}
/**
* Gets a notification from Iterable and displays it on device.
* @param context
* @param clickCallback
*/
public void spawnInAppNotification(final Context context, final IterableHelper.IterableActionHandler clickCallback) {
getInAppMessages(1, new IterableHelper.IterableActionHandler(){
@Override
public void execute(String payload) {
JSONObject dialogOptions = IterableInAppManager.getNextMessageFromPayload(payload);
if (dialogOptions != null) {
JSONObject message = dialogOptions.optJSONObject(IterableConstants.ITERABLE_IN_APP_CONTENT);
if (message != null) {
String messageId = dialogOptions.optString(IterableConstants.KEY_MESSAGE_ID);
String html = message.optString("html");
if (html.toLowerCase().contains("href")) {
JSONObject paddingOptions = message.optJSONObject("inAppDisplaySettings");
Rect padding = IterableInAppManager.getPaddingFromPayload(paddingOptions);
double backgroundAlpha = message.optDouble("backgroundAlpha", 0);
IterableInAppManager.showIterableNotificationHTML(context, html, messageId, clickCallback, backgroundAlpha, padding);
} else {
IterableLogger.w(TAG, "No href tag in found in the in-app html payload: "+ html);
}
IterableApi.sharedInstance.inAppConsume(messageId);
}
}
}
});
}
/**
* Gets a list of InAppNotifications from Iterable; passes the result to the callback.
* @param count the number of messages to fetch
* @param onCallback
*/
public void getInAppMessages(int count, IterableHelper.IterableActionHandler onCallback) {
JSONObject requestJSON = new JSONObject();
addEmailOrUserIdToJson(requestJSON);
try {
addEmailOrUserIdToJson(requestJSON);
requestJSON.put(IterableConstants.ITERABLE_IN_APP_COUNT, count);
requestJSON.put(IterableConstants.KEY_PLATFORM, IterableConstants.ITBL_PLATFORM_ANDROID);
requestJSON.put(IterableConstants.ITBL_KEY_SDK_VERSION, IterableConstants.ITBL_KEY_SDK_VERSION_NUMBER);
sendGetRequest(IterableConstants.ENDPOINT_GET_INAPP_MESSAGES, requestJSON, onCallback);
}
catch (JSONException e) {
e.printStackTrace();
}
}
/**
* Tracks an InApp open.
* @param messageId
*/
public void trackInAppOpen(String messageId) {
JSONObject requestJSON = new JSONObject();
try {
addEmailOrUserIdToJson(requestJSON);
requestJSON.put(IterableConstants.KEY_MESSAGE_ID, messageId);
sendPostRequest(IterableConstants.ENDPOINT_TRACK_INAPP_OPEN, requestJSON);
}
catch (JSONException e) {
e.printStackTrace();
}
}
/**
* Tracks an InApp click.
* @param messageId
* @param urlClick
*/
public void trackInAppClick(String messageId, String urlClick) {
JSONObject requestJSON = new JSONObject();
try {
addEmailOrUserIdToJson(requestJSON);
requestJSON.put(IterableConstants.KEY_MESSAGE_ID, messageId);
requestJSON.put(IterableConstants.ITERABLE_IN_APP_URL_CLICK, urlClick);
sendPostRequest(IterableConstants.ENDPOINT_TRACK_INAPP_CLICK, requestJSON);
}
catch (JSONException e) {
e.printStackTrace();
}
}
/**
* Consumes an InApp message.
* @param messageId
*/
public void inAppConsume(String messageId) {
JSONObject requestJSON = new JSONObject();
try {
addEmailOrUserIdToJson(requestJSON);
requestJSON.put(IterableConstants.KEY_MESSAGE_ID, messageId);
sendPostRequest(IterableConstants.ENDPOINT_INAPP_CONSUME, requestJSON);
}
catch (JSONException e) {
e.printStackTrace();
}
}
//endregion
//region Protected Fuctions
/**
* Set the notification icon with the given iconName.
* @param context
* @param iconName
*/
static void setNotificationIcon(Context context, String iconName) {
SharedPreferences sharedPref = context.getSharedPreferences(IterableConstants.NOTIFICATION_ICON_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString(IterableConstants.NOTIFICATION_ICON_NAME, iconName);
editor.commit();
}
/**
* Returns the stored notification icon.
* @param context
* @return
*/
static String getNotificationIcon(Context context) {
SharedPreferences sharedPref = context.getSharedPreferences(IterableConstants.NOTIFICATION_ICON_NAME, Context.MODE_PRIVATE);
String iconName = sharedPref.getString(IterableConstants.NOTIFICATION_ICON_NAME, "");
return iconName;
}
/**
* Tracks when a push notification is opened on device.
* @param campaignId
* @param templateId
*/
protected void trackPushOpen(int campaignId, int templateId, String messageId) {
JSONObject requestJSON = new JSONObject();
try {
addEmailOrUserIdToJson(requestJSON);
requestJSON.put(IterableConstants.KEY_CAMPAIGN_ID, campaignId);
requestJSON.put(IterableConstants.KEY_TEMPLATE_ID, templateId);
requestJSON.put(IterableConstants.KEY_MESSAGE_ID, messageId);
sendPostRequest(IterableConstants.ENDPOINT_TRACK_PUSH_OPEN, requestJSON);
}
catch (JSONException e) {
e.printStackTrace();
}
}
/**
* Internal api call made from IterablePushRegistration after a registrationToken is obtained.
* @param token
*/
protected void disablePush(String token) {
JSONObject requestJSON = new JSONObject();
try {
requestJSON.put(IterableConstants.KEY_TOKEN, token);
addEmailOrUserIdToJson(requestJSON);
sendPostRequest(IterableConstants.ENDPOINT_DISABLE_DEVICE, requestJSON);
}
catch (JSONException e) {
e.printStackTrace();
}
}
/**
* Registers the GCM registration ID with Iterable.
* @param applicationName
* @param token
* @param pushServicePlatform
* @param dataFields
*/
protected void registerDeviceToken(String applicationName, String token, String pushServicePlatform, JSONObject dataFields) {
String platform = IterableConstants.MESSAGING_PLATFORM_GOOGLE;
JSONObject requestJSON = new JSONObject();
try {
addEmailOrUserIdToJson(requestJSON);
if (dataFields == null) {
dataFields = new JSONObject();
}
if (pushServicePlatform != null) {
dataFields.put(IterableConstants.FIREBASE_COMPATIBLE, pushServicePlatform.equalsIgnoreCase(IterableConstants.MESSAGING_PLATFORM_FIREBASE));
}
dataFields.put(IterableConstants.DEVICE_BRAND, Build.BRAND); //brand: google
dataFields.put(IterableConstants.DEVICE_MANUFACTURER, Build.MANUFACTURER); //manufacturer: samsung
dataFields.putOpt(IterableConstants.DEVICE_ADID, getAdvertisingId()); //ADID: "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"
dataFields.put(IterableConstants.DEVICE_SYSTEM_NAME, Build.DEVICE); //device name: toro
dataFields.put(IterableConstants.DEVICE_SYSTEM_VERSION, Build.VERSION.RELEASE);
dataFields.put(IterableConstants.DEVICE_MODEL, Build.MODEL); //device model: Galaxy Nexus
dataFields.put(IterableConstants.DEVICE_SDK_VERSION, Build.VERSION.SDK_INT); //sdk version/api level: 15
JSONObject device = new JSONObject();
device.put(IterableConstants.KEY_TOKEN, token);
device.put(IterableConstants.KEY_PLATFORM, platform);
device.put(IterableConstants.KEY_APPLICATION_NAME, applicationName);
device.putOpt(IterableConstants.KEY_DATA_FIELDS, dataFields);
requestJSON.put(IterableConstants.KEY_DEVICE, device);
sendPostRequest(IterableConstants.ENDPOINT_REGISTER_DEVICE_TOKEN, requestJSON);
} catch (JSONException e) {
e.printStackTrace();
}
}
//endregion
//region Private Fuctions
/**
* Updates the data for the current user.
* @param context
* @param apiKey
* @param email
* @param userId
*/
private void updateData(Context context, String apiKey, String email, String userId) {
this._applicationContext = context;
this._apiKey = apiKey;
this._email = email;
this._userId = userId;
}
/**
* Attempts to track a notifOpened event from the called Intent.
* @param calledIntent
*/
private void tryTrackNotifOpen(Intent calledIntent) {
Bundle extras = calledIntent.getExtras();
if (extras != null) {
Intent intent = new Intent();
intent.setClass(_applicationContext, IterablePushOpenReceiver.class);
intent.setAction(IterableConstants.ACTION_NOTIF_OPENED);
intent.putExtras(extras);
_applicationContext.sendBroadcast(intent);
}
}
/**
* Sends the POST request to Iterable.
* Performs network operations on an async thread instead of the main thread.
* @param resourcePath
* @param json
*/
private void sendPostRequest(String resourcePath, JSONObject json) {
IterableApiRequest request = new IterableApiRequest(_apiKey, resourcePath, json, IterableApiRequest.POST, null);
new IterableRequest().execute(request);
}
/**
* Sends a GET request to Iterable.
* Performs network operations on an async thread instead of the main thread.
* @param resourcePath
* @param json
*/
private void sendGetRequest(String resourcePath, JSONObject json, IterableHelper.IterableActionHandler onCallback) {
IterableApiRequest request = new IterableApiRequest(_apiKey, resourcePath, json, IterableApiRequest.GET, onCallback);
new IterableRequest().execute(request);
}
/**
* Adds the current email or userID to the json request.
* @param requestJSON
*/
private void addEmailOrUserIdToJson(JSONObject requestJSON) {
try {
if (_email != null) {
requestJSON.put(IterableConstants.KEY_EMAIL, _email);
} else {
requestJSON.put(IterableConstants.KEY_USER_ID, _userId);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
/**
* Gets the advertisingId if available
* @return
*/
private String getAdvertisingId() {
String advertisingId = null;
try {
Class adClass = Class.forName("com.google.android.gms.ads.identifier.AdvertisingIdClient");
if (adClass != null) {
AdvertisingIdClient.Info advertisingIdInfo = AdvertisingIdClient.getAdvertisingIdInfo(_applicationContext);
if (advertisingIdInfo != null) {
advertisingId = advertisingIdInfo.getId();
}
}
} catch (IOException e) {
IterableLogger.w(TAG, e.getMessage());
} catch (GooglePlayServicesNotAvailableException e) {
IterableLogger.w(TAG, e.getMessage());
} catch (GooglePlayServicesRepairableException e) {
IterableLogger.w(TAG, e.getMessage());
} catch (ClassNotFoundException e) {
IterableLogger.d(TAG, "ClassNotFoundException: Can't track ADID. " +
"Check that play-services-ads is added to the dependencies.", e);
}
return advertisingId;
}
//endregion
}
|
package net.iaeste.iws.migrate.spring;
import net.iaeste.iws.api.constants.IWSErrors;
import net.iaeste.iws.api.exceptions.IWSException;
import org.postgresql.ds.PGSimpleDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;
import java.beans.Beans;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
@Configuration
@ComponentScan("net.iaeste.iws.migrate.spring")
@EnableTransactionManagement
public class Config {
private final Object lock = new Object();
private final Properties properties = new Properties();
private String readProperty(final String key, final String defaultValue) {
synchronized (lock) {
if (properties.isEmpty()) {
try (InputStream inputStream = Beans.class.getResourceAsStream("migration.properties")) {
if (inputStream != null) {
properties.load(inputStream);
}
} catch (final IOException e) {
throw new IWSException(IWSErrors.FATAL, "Cannot load the Properties.", e);
}
}
return properties.getProperty(key, defaultValue);
}
}
@Bean(name = "dataSourceIW3")
public DataSource dataSourceIW3() {
final PGSimpleDataSource dataSource = new PGSimpleDataSource();
dataSource.setServerName(readProperty("datasource.iw3.server", "192.38.77.85"));
dataSource.setPortNumber(Integer.valueOf(readProperty("datasource.iw3.port", "5432")));
dataSource.setDatabaseName(readProperty("datasource.iw3.database", "iw3_test"));
dataSource.setUser(readProperty("datasource.iw3.user", "readonly"));
final String pwd = readProperty("datasource.iw3.password", "af9v7aq6");
// this is the data source for the iw3 dump on the dev server
// dataSource.setServerName(readProperty("datasource.iw3.server", "localhost"));
// dataSource.setPortNumber(Integer.valueOf(readProperty("datasource.iw3.port", "5432")));
// dataSource.setDatabaseName(readProperty("datasource.iw3.database", "iw3_test"));
// dataSource.setUser(readProperty("datasource.iw3.user", "iw4_test_user"));
// final String pwd = readProperty("datasource.iw3.password", "jIf6rOAX92niHMFsQJjbuyf0");
if ((pwd != null) && !pwd.isEmpty()) {
dataSource.setPassword(pwd);
}
return dataSource;
}
@Bean(name = "dataSourceIWS")
public DataSource dataSourceIWS() {
final PGSimpleDataSource dataSource = new PGSimpleDataSource();
dataSource.setServerName(readProperty("datasource.iws.server", "localhost"));
dataSource.setPortNumber(Integer.valueOf(readProperty("datasource.iws.port", "5432")));
dataSource.setDatabaseName(readProperty("datasource.iws.database", "db_iw4_test"));
dataSource.setUser(readProperty("datasource.iws.user", "iw4_test_user"));
final String pwd = readProperty("datasource.iws.password", "jIf6rOAX92niHMFsQJjbuyf0");
if ((pwd != null) && !pwd.isEmpty()) {
dataSource.setPassword(pwd);
}
return dataSource;
}
@Bean(name = "dataSourceMail")
public DataSource dataSourceMail() {
final PGSimpleDataSource dataSource = new PGSimpleDataSource();
dataSource.setServerName(readProperty("datasource.mail.server", "localhost"));
dataSource.setPortNumber(Integer.valueOf(readProperty("datasource.mail.port", "5432")));
dataSource.setDatabaseName(readProperty("datasource.mail.database", "db_iw4_maillists_test"));
dataSource.setUser(readProperty("datasource.mail.user", "iw4_test_user"));
final String pwd = readProperty("datasource.mail.password", "jIf6rOAX92niHMFsQJjbuyf0");
if ((pwd != null) && !pwd.isEmpty()) {
dataSource.setPassword(pwd);
}
return dataSource;
}
@Bean(name = "entityManagerFactoryIW3Bean")
public LocalContainerEntityManagerFactoryBean entityManagerFactoryIW3Bean() {
final LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();
final JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
factoryBean.setPackagesToScan("net.iaeste.iws.migrate");
factoryBean.setDataSource(dataSourceIW3());
factoryBean.setJpaVendorAdapter(vendorAdapter);
factoryBean.setJpaProperties(jpaProperties());
factoryBean.setPersistenceUnitName("IW3PersistenceUnit");
return factoryBean;
}
@Bean(name = "entityManagerFactoryIWSBean")
public LocalContainerEntityManagerFactoryBean entityManagerFactoryIWSBean() {
final LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();
final JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
factoryBean.setPackagesToScan("net.iaeste.iws.persistence");
factoryBean.setDataSource(dataSourceIWS());
factoryBean.setJpaVendorAdapter(vendorAdapter);
factoryBean.setJpaProperties(jpaProperties());
factoryBean.setPersistenceUnitName("IWSPersistenceUnit");
return factoryBean;
}
@Bean(name = "entityManagerFactoryMailBean")
public LocalContainerEntityManagerFactoryBean entityManagerFactoryMailBean() {
final LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();
final JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
factoryBean.setPackagesToScan("net.iaeste.iws.persistence");
factoryBean.setDataSource(dataSourceMail());
factoryBean.setJpaVendorAdapter(vendorAdapter);
factoryBean.setJpaProperties(jpaProperties());
factoryBean.setPersistenceUnitName("MailPersistenceUnit");
return factoryBean;
}
@Bean(name = "transactionManagerIW3")
public PlatformTransactionManager transactionManagerIW3() {
final JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactoryIW3Bean().getObject());
return transactionManager;
}
@Bean(name = "transactionManagerIWS")
public PlatformTransactionManager transactionManagerIWS() {
final JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactoryIWSBean().getObject());
return transactionManager;
}
@Bean(name = "transactionManagerMail")
public PlatformTransactionManager transactionManagerMail() {
final JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactoryMailBean().getObject());
return transactionManager;
}
@Bean(name = "jpaProperties")
public Properties jpaProperties() {
final Properties jpaProperties = new Properties();
// For testing the result, it is helpful to be able to see the queries
// executed against the database, preferably formatted as well :-)
jpaProperties.setProperty("hibernate.show_sql", "false");
jpaProperties.setProperty("hibernate.format_sql", "false");
// For some braindead reason - someone thought it was a good idea to
// have the default behaviour being true for the autocommit setting!
jpaProperties.setProperty("hibernate.connection.autocommit", "false");
return jpaProperties;
}
}
|
package org.apache.derby.impl.sql;
import org.apache.derby.catalog.Dependable;
import org.apache.derby.catalog.DependableFinder;
import org.apache.derby.iapi.services.context.ContextService;
import org.apache.derby.iapi.services.context.ContextManager;
import org.apache.derby.iapi.services.monitor.Monitor;
import org.apache.derby.iapi.services.sanity.SanityManager;
import org.apache.derby.iapi.services.stream.HeaderPrintWriter;
import org.apache.derby.iapi.services.cache.Cacheable;
import org.apache.derby.catalog.UUID;
import org.apache.derby.iapi.services.uuid.UUIDFactory;
import org.apache.derby.iapi.util.ByteArray;
import org.apache.derby.iapi.sql.dictionary.DataDictionary;
import org.apache.derby.iapi.sql.dictionary.SchemaDescriptor;
import org.apache.derby.iapi.sql.dictionary.SPSDescriptor;
import org.apache.derby.iapi.sql.ParameterValueSet;
import org.apache.derby.iapi.sql.PreparedStatement;
import org.apache.derby.iapi.sql.Statement;
import org.apache.derby.iapi.types.DataTypeDescriptor;
import org.apache.derby.iapi.sql.ResultColumnDescriptor;
import org.apache.derby.iapi.sql.ResultDescription;
import org.apache.derby.iapi.sql.ResultSet;
import org.apache.derby.iapi.sql.Activation;
import org.apache.derby.iapi.sql.execute.ConstantAction;
import org.apache.derby.iapi.sql.execute.ExecCursorTableReference;
import org.apache.derby.iapi.sql.execute.ExecPreparedStatement;
import org.apache.derby.iapi.sql.depend.DependencyManager;
import org.apache.derby.iapi.sql.depend.Provider;
import org.apache.derby.iapi.sql.conn.LanguageConnectionContext;
import org.apache.derby.iapi.sql.conn.StatementContext;
import org.apache.derby.impl.sql.compile.CursorNode;
import org.apache.derby.impl.sql.compile.StatementNode;
import org.apache.derby.iapi.error.StandardException;
import org.apache.derby.iapi.reference.SQLState;
import org.apache.derby.iapi.services.loader.GeneratedClass;
import java.sql.Timestamp;
import java.sql.SQLWarning;
import java.util.List;
/**
* Basic implementation of prepared statement.
* relies on implementation of ResultDescription and Statement that
* are also in this package.
* <p>
* These are both dependents (of the schema objects and prepared statements
* they depend on) and providers. Prepared statements that are providers
* are cursors that end up being used in positioned delete and update
* statements (at present).
* <p>
* This is impl with the regular prepared statements; they will never
* have the cursor info fields set.
* <p>
* Stored prepared statements extend this implementation
*
*/
public class GenericPreparedStatement
implements ExecPreparedStatement
{
// WARNING: when adding members to this class, be
// sure to do the right thing in getClone(): if
// it is PreparedStatement specific like finished,
// then it shouldn't be copied, but stuff like parameters
// must be copied.
// STATE that is copied by getClone()
public Statement statement;
protected GeneratedClass activationClass; // satisfies Activation
protected ResultDescription resultDesc;
protected DataTypeDescriptor[] paramTypeDescriptors;
private String spsName;
private SQLWarning warnings;
//If the query node for this statement references SESSION schema tables, mark it so in the boolean below
//This information will be used by EXECUTE STATEMENT if it is executing a statement that was created with NOCOMPILE. Because
//of NOCOMPILE, we could not catch SESSION schema table reference by the statement at CREATE STATEMENT time. Need to catch
//such statements at EXECUTE STATEMENT time when the query is getting compiled.
//This information will also be used to decide if the statement should be cached or not. Any statement referencing SESSION
//schema tables will not be cached.
private boolean referencesSessionSchema;
// fields used for cursors
protected ExecCursorTableReference targetTable;
protected ResultColumnDescriptor[] targetColumns;
protected String[] updateColumns;
protected int updateMode;
protected ConstantAction executionConstants;
protected Object[] savedObjects;
protected List requiredPermissionsList;
// fields for dependency tracking
protected String UUIDString;
protected UUID UUIDValue;
private boolean needsSavepoint;
private String execStmtName;
private String execSchemaName;
protected boolean isAtomic;
protected String sourceTxt;
private int inUseCount;
// true if the statement is being compiled.
boolean compilingStatement;
/** True if the statement was invalidated while it was being compiled. */
boolean invalidatedWhileCompiling;
// STATE that is not copied by getClone()
// fields for run time stats
protected long parseTime;
protected long bindTime;
protected long optimizeTime;
protected long generateTime;
protected long compileTime;
protected Timestamp beginCompileTimestamp;
protected Timestamp endCompileTimestamp;
//private boolean finished;
protected boolean isValid;
protected boolean spsAction;
// state for caching.
/**
If non-null then this object is the cacheable
that holds us in the cache.
*/
private Cacheable cacheHolder;
/**
* Incremented for each (re)compile.
*/
private long versionCounter;
// constructors
GenericPreparedStatement() {
/* Get the UUID for this prepared statement */
UUIDFactory uuidFactory = Monitor.getMonitor().getUUIDFactory();
UUIDValue = uuidFactory.createUUID();
UUIDString = UUIDValue.toString();
spsAction = false;
}
public GenericPreparedStatement(Statement st) {
this();
statement = st;
}
// PreparedStatement interface
public synchronized boolean upToDate() throws StandardException {
return isUpToDate();
}
/**
* Check whether this statement is up to date and its generated class is
* identical to the supplied class object.
* @see ExecPreparedStatement#upToDate(GeneratedClass)
*/
public synchronized boolean upToDate(GeneratedClass gc) {
return (activationClass == gc) && isUpToDate();
}
/**
* Unsynchronized helper method for {@link #upToDate()} and {@link
* #upToDate(GeneratedClass)}. Checks whether this statement is up to date.
*
* @return {@code true} if this statement is up to date, {@code false}
* otherwise
*/
private boolean isUpToDate() {
return isValid && (activationClass != null) && !compilingStatement;
}
public void rePrepare(LanguageConnectionContext lcc)
throws StandardException {
if (!upToDate()) {
PreparedStatement ps = statement.prepare(lcc);
if (SanityManager.DEBUG)
SanityManager.ASSERT(ps == this, "ps != this");
}
}
/**
* Get a new activation instance.
*
* @exception StandardException thrown if finished.
*/
public Activation getActivation(LanguageConnectionContext lcc,
boolean scrollable)
throws StandardException
{
Activation ac;
synchronized (this) {
GeneratedClass gc = getActivationClass();
if (gc == null) {
rePrepare(lcc);
gc = getActivationClass();
}
ac = new GenericActivationHolder(lcc, gc, this, scrollable);
inUseCount++;
}
// DERBY-2689. Close unused activations-- this method should be called
// when I'm not holding a lock on a prepared statement to avoid
// deadlock.
lcc.closeUnusedActivations();
Activation parentAct = null;
StatementContext stmctx = lcc.getStatementContext();
if (stmctx != null) {
// If not null, parentAct represents one of 1) the activation of a
// calling statement and this activation corresponds to a statement
// inside a stored procedure or function, and 2) the activation of
// a statement that performs a substatement, e.g. trigger body
// execution.
parentAct = stmctx.getActivation();
}
ac.setParentActivation(parentAct);
return ac;
}
/**
* @see PreparedStatement#executeSubStatement(LanguageConnectionContext, boolean, long)
*/
public ResultSet executeSubStatement(LanguageConnectionContext lcc,
boolean rollbackParentContext,
long timeoutMillis)
throws StandardException
{
Activation parent = lcc.getLastActivation();
Activation a = getActivation(lcc, false);
a.setSingleExecution();
lcc.setupSubStatementSessionContext(parent);
return executeStmt(a, rollbackParentContext, timeoutMillis);
}
/**
* @see PreparedStatement#executeSubStatement(Activation, Activation, boolean, long)
*/
public ResultSet executeSubStatement(Activation parent,
Activation activation,
boolean rollbackParentContext,
long timeoutMillis)
throws StandardException
{
parent.getLanguageConnectionContext().
setupSubStatementSessionContext(parent);
return executeStmt(activation, rollbackParentContext, timeoutMillis);
}
/**
* @see PreparedStatement#execute
*/
public ResultSet execute(Activation activation,
long timeoutMillis)
throws StandardException
{
return executeStmt(activation, false, timeoutMillis);
}
/**
* The guts of execution.
*
* @param activation the activation to run.
* @param rollbackParentContext True if 1) the statement context is
* NOT a top-level context, AND 2) in the event of a statement-level
* exception, the parent context needs to be rolled back, too.
* @param timeoutMillis timeout value in milliseconds.
* @return the result set to be pawed through
*
* @exception StandardException thrown on error
*/
private ResultSet executeStmt(Activation activation,
boolean rollbackParentContext,
long timeoutMillis)
throws
StandardException
{
boolean needToClearSavePoint = false;
if (activation == null || activation.getPreparedStatement() != this)
{
throw StandardException.newException(SQLState.LANG_WRONG_ACTIVATION, "execute");
}
recompileOutOfDatePlan:
while (true) {
// verify the activation is for me--somehow. NOTE: This is
// different from the above check for whether the activation is
// associated with the right PreparedStatement - it's conceivable
// that someone could construct an activation of the wrong type
// that points to the right PreparedStatement.
//SanityManager.ASSERT(activation instanceof activationClass, "executing wrong activation");
/* This is where we set and clear savepoints around each individual
* statement which needs one. We don't set savepoints for cursors because
* they're not needed and they wouldn't work in a read only database.
* We can't set savepoints for commit/rollback because they'll get
* blown away before we try to clear them.
*/
LanguageConnectionContext lccToUse = activation.getLanguageConnectionContext();
if (lccToUse.getLogStatementText())
{
HeaderPrintWriter istream = Monitor.getStream();
String xactId = lccToUse.getTransactionExecute().getActiveStateTxIdString();
String pvsString = "";
ParameterValueSet pvs = activation.getParameterValueSet();
if (pvs != null && pvs.getParameterCount() > 0)
{
pvsString = " with " + pvs.getParameterCount() +
" parameters " + pvs.toString();
}
istream.printlnWithHeader(LanguageConnectionContext.xidStr +
xactId +
"), " +
LanguageConnectionContext.lccStr +
lccToUse.getInstanceNumber() +
"), " +
LanguageConnectionContext.dbnameStr +
lccToUse.getDbname() +
"), " +
LanguageConnectionContext.drdaStr +
lccToUse.getDrdaID() +
"), Executing prepared statement: " +
getSource() +
" :End prepared statement" +
pvsString);
}
ParameterValueSet pvs = activation.getParameterValueSet();
/* put it in try block to unlock the PS in any case
*/
if (!spsAction) {
// only re-prepare if this isn't an SPS for a trigger-action;
// if it _is_ an SPS for a trigger action, then we can't just
// do a regular prepare because the statement might contain
// internal SQL that isn't allowed in other statements (such as a
// static method call to get the trigger context for retrieval
// of "new row" or "old row" values). So in that case we
// skip the call to 'rePrepare' and if the statement is out
// of date, we'll get a NEEDS_COMPILE exception when we try
// to execute. That exception will be caught by the executeSPS()
// method of the GenericTriggerExecutor class, and at that time
// the SPS action will be recompiled correctly.
rePrepare(lccToUse);
}
StatementContext statementContext = lccToUse.pushStatementContext(
isAtomic, updateMode==CursorNode.READ_ONLY, getSource(), pvs, rollbackParentContext, timeoutMillis);
statementContext.setActivation(activation);
if (needsSavepoint())
{
/* Mark this position in the log so that a statement
* rollback will undo any changes.
*/
statementContext.setSavePoint();
needToClearSavePoint = true;
}
if (executionConstants != null)
{
lccToUse.validateStmtExecution(executionConstants);
}
ResultSet resultSet = null;
try {
resultSet = activation.execute();
resultSet.open();
} catch (StandardException se) {
/* Cann't handle recompiling SPS action recompile here */
if (!se.getMessageId().equals(SQLState.LANG_STATEMENT_NEEDS_RECOMPILE)
|| spsAction)
throw se;
statementContext.cleanupOnError(se);
continue recompileOutOfDatePlan;
}
if (needToClearSavePoint)
{
/* We're done with our updates */
statementContext.clearSavePoint();
}
lccToUse.popStatementContext(statementContext, null);
if (activation.isSingleExecution() && resultSet.isClosed())
{
// if the result set is 'done', i.e. not openable,
// then we can also release the activation.
// Note that a result set with output parameters
// or rows to return is explicitly finished
// by the user.
activation.close();
}
return resultSet;
}
}
public ResultDescription getResultDescription() {
return resultDesc;
}
public DataTypeDescriptor[] getParameterTypes() {
return paramTypeDescriptors;
}
public String getSource() {
return (sourceTxt != null) ?
sourceTxt :
(statement == null) ?
"null" :
statement.getSource();
}
public void setSource(String text)
{
sourceTxt = text;
}
public final void setSPSName(String name) {
spsName = name;
}
public String getSPSName() {
return spsName;
}
/**
* Get the total compile time for the associated query in milliseconds.
* Compile time can be divided into parse, bind, optimize and generate times.
*
* @return long The total compile time for the associated query in milliseconds.
*/
public long getCompileTimeInMillis()
{
return compileTime;
}
/**
* Get the parse time for the associated query in milliseconds.
*
* @return long The parse time for the associated query in milliseconds.
*/
public long getParseTimeInMillis()
{
return parseTime;
}
/**
* Get the bind time for the associated query in milliseconds.
*
* @return long The bind time for the associated query in milliseconds.
*/
public long getBindTimeInMillis()
{
return bindTime;
}
/**
* Get the optimize time for the associated query in milliseconds.
*
* @return long The optimize time for the associated query in milliseconds.
*/
public long getOptimizeTimeInMillis()
{
return optimizeTime;
}
/**
* Get the generate time for the associated query in milliseconds.
*
* @return long The generate time for the associated query in milliseconds.
*/
public long getGenerateTimeInMillis()
{
return generateTime;
}
/**
* Get the timestamp for the beginning of compilation
*
* @return Timestamp The timestamp for the beginning of compilation.
*/
public Timestamp getBeginCompileTimestamp()
{
return beginCompileTimestamp;
}
/**
* Get the timestamp for the end of compilation
*
* @return Timestamp The timestamp for the end of compilation.
*/
public Timestamp getEndCompileTimestamp()
{
return endCompileTimestamp;
}
void setCompileTimeWarnings(SQLWarning warnings) {
this.warnings = warnings;
}
public final SQLWarning getCompileTimeWarnings() {
return warnings;
}
/**
* Set the compile time for this prepared statement.
*
* @param compileTime The compile time
*/
protected void setCompileTimeMillis(long parseTime, long bindTime,
long optimizeTime,
long generateTime,
long compileTime,
Timestamp beginCompileTimestamp,
Timestamp endCompileTimestamp)
{
this.parseTime = parseTime;
this.bindTime = bindTime;
this.optimizeTime = optimizeTime;
this.generateTime = generateTime;
this.compileTime = compileTime;
this.beginCompileTimestamp = beginCompileTimestamp;
this.endCompileTimestamp = endCompileTimestamp;
}
/**
Finish marks a statement as totally unusable.
*/
public void finish(LanguageConnectionContext lcc) {
synchronized (this) {
inUseCount
if (cacheHolder != null)
return;
if (inUseCount != 0) {
//if (SanityManager.DEBUG) {
// if (inUseCount < 0)
// SanityManager.THROWASSERT("inUseCount is negative " + inUseCount + " for " + this);
return;
}
}
// invalidate any prepared statements that
// depended on this statement (including this one)
// prepareToInvalidate(this, DependencyManager.PREPARED_STATEMENT_INVALID);
try
{
/* NOTE: Since we are non-persistent, we "know" that no exception
* will be thrown under us.
*/
makeInvalid(DependencyManager.PREPARED_STATEMENT_RELEASE, lcc);
}
catch (StandardException se)
{
if (SanityManager.DEBUG)
{
SanityManager.THROWASSERT("Unexpected exception", se);
}
}
}
/**
* Set the Execution constants. This routine is called as we Prepare the
* statement.
*
* @param constantAction The big structure enclosing the Execution constants.
*/
final void setConstantAction( ConstantAction constantAction )
{
executionConstants = constantAction;
}
/**
* Get the Execution constants. This routine is called at Execution time.
*
* @return ConstantAction The big structure enclosing the Execution constants.
*/
public final ConstantAction getConstantAction()
{
return executionConstants;
}
/**
* Set the saved objects. Called when compilation completes.
*
* @param objects The objects to save from compilation
*/
final void setSavedObjects( Object[] objects )
{
savedObjects = objects;
}
/**
* Get the specified saved object.
*
* @param objectNum The object to get.
* @return the requested saved object.
*/
public final Object getSavedObject(int objectNum)
{
if (SanityManager.DEBUG) {
if (!(objectNum>=0 && objectNum<savedObjects.length))
SanityManager.THROWASSERT(
"request for savedObject entry "+objectNum+" invalid; "+
"savedObjects has "+savedObjects.length+" entries");
}
return savedObjects[objectNum];
}
/**
* Get the saved objects.
*
* @return all the saved objects
*/
public final Object[] getSavedObjects()
{
return savedObjects;
}
// Dependent interface
/**
Check that all of the dependent's dependencies are valid.
@return true if the dependent is currently valid
*/
public boolean isValid() {
return isValid;
}
/**
* set this prepared statement to be valid, currently used by
* GenericTriggerExecutor.
*/
public void setValid()
{
isValid = true;
}
/**
* Indicate this prepared statement is an SPS action, currently used
* by GenericTriggerExecutor.
*/
public void setSPSAction()
{
spsAction = true;
}
/**
Prepare to mark the dependent as invalid (due to at least one of
its dependencies being invalid).
@param action The action causing the invalidation
@param p the provider
@exception StandardException thrown if unable to make it invalid
*/
public void prepareToInvalidate(Provider p, int action,
LanguageConnectionContext lcc)
throws StandardException {
/*
this statement can have other open result sets
if another one is closing without any problems.
It is not a problem to create an index when there is an open
result set, since it doesn't invalidate the access path that was
chosen for the result set.
*/
switch (action) {
case DependencyManager.CHANGED_CURSOR:
case DependencyManager.CREATE_INDEX:
// Used by activations only:
case DependencyManager.RECHECK_PRIVILEGES:
return;
}
/* Verify that there are no activations with open result sets
* on this prepared statement.
*/
lcc.verifyNoOpenResultSets(this, p, action);
}
/**
Mark the dependent as invalid (due to at least one of
its dependencies being invalid).
@param action The action causing the invalidation
@exception StandardException Standard Derby error policy.
*/
public void makeInvalid(int action, LanguageConnectionContext lcc)
throws StandardException
{
boolean alreadyInvalid;
switch (action) {
case DependencyManager.RECHECK_PRIVILEGES:
return;
}
synchronized (this) {
if (compilingStatement)
{
// Since the statement is in the process of being compiled,
// and at the end of the compilation it will set isValid to
// true and overwrite whatever we set it to here, set another
// flag to indicate that an invalidation was requested. A
// re-compilation will be triggered if this flag is set, but
// not until the current compilation is done.
invalidatedWhileCompiling = true;
return;
}
alreadyInvalid = !isValid;
// make ourseleves invalid
isValid = false;
// block compiles while we are invalidating
compilingStatement = true;
}
try {
DependencyManager dm = lcc.getDataDictionary().getDependencyManager();
/* Clear out the old dependencies on this statement as we
* will build the new set during the reprepare in makeValid().
*/
dm.clearDependencies(lcc, this);
/*
** If we are invalidating an EXECUTE STATEMENT because of a stale
** plan, we also need to invalidate the stored prepared statement.
*/
if (execStmtName != null) {
switch (action) {
case DependencyManager.INTERNAL_RECOMPILE_REQUEST:
case DependencyManager.CHANGED_CURSOR:
{
/*
** Get the DataDictionary, so we can get the descriptor for
** the SPP to invalidate it.
*/
DataDictionary dd = lcc.getDataDictionary();
SchemaDescriptor sd = dd.getSchemaDescriptor(execSchemaName, lcc.getTransactionCompile(), true);
SPSDescriptor spsd = dd.getSPSDescriptor(execStmtName, sd);
spsd.makeInvalid(action, lcc);
break;
}
}
}
} finally {
synchronized (this) {
compilingStatement = false;
notifyAll();
}
}
}
/**
* Is this dependent persistent? A stored dependency will be required
* if both the dependent and provider are persistent.
*
* @return boolean Whether or not this dependent is persistent.
*/
public boolean isPersistent()
{
/* Non-stored prepared statements are not persistent */
return false;
}
// Dependable interface
/**
@return the stored form of this Dependable
@see Dependable#getDependableFinder
*/
public DependableFinder getDependableFinder()
{
return null;
}
/**
* Return the name of this Dependable. (Useful for errors.)
*
* @return String The name of this Dependable..
*/
public String getObjectName()
{
return UUIDString;
}
/**
* Get the Dependable's UUID String.
*
* @return String The Dependable's UUID String.
*/
public UUID getObjectID()
{
return UUIDValue;
}
/**
* Get the Dependable's class type.
*
* @return String Classname that this Dependable belongs to.
*/
public String getClassType()
{
return Dependable.PREPARED_STATEMENT;
}
/**
* Return true if the query node for this statement references SESSION schema
* tables/views.
* This method gets called at the very beginning of the compile phase of any statement.
* If the statement which needs to be compiled is already found in cache, then there is
* no need to compile it again except the case when the statement is referencing SESSION
* schema objects. There is a small window where such a statement might get cached
* temporarily (a statement referencing SESSION schema object will be removed from the
* cache after the bind phase is over because that is when we know for sure that the
* statement is referencing SESSION schema objects.)
*
* @return true if references SESSION schema tables, else false
*/
public boolean referencesSessionSchema()
{
return referencesSessionSchema;
}
/**
* Return true if the QueryTreeNode references SESSION schema tables/views.
* The return value is also saved in the local field because it will be
* used by referencesSessionSchema() method.
* This method gets called when the statement is not found in cache and
* hence it is getting compiled.
* At the beginning of compilation for any statement, first we check if
* the statement's plan already exist in the cache. If not, then we add
* the statement to the cache and continue with the parsing and binding.
* At the end of the binding, this method gets called to see if the
* QueryTreeNode references a SESSION schema object. If it does, then
* we want to remove it from the cache, since any statements referencing
* SESSION schema objects should never get cached.
*
* @return true if references SESSION schema tables/views, else false
*/
public boolean referencesSessionSchema(StatementNode qt)
throws StandardException {
//If the query references a SESSION schema table (temporary or permanent), then
// mark so in this statement
referencesSessionSchema = qt.referencesSessionSchema();
return(referencesSessionSchema);
}
// class interface
/**
Makes the prepared statement valid, assigning
values for its query tree, generated class,
and associated information.
@param qt the query tree for this statement
@exception StandardException thrown on failure.
*/
void completeCompile(StatementNode qt)
throws StandardException {
//if (finished)
// throw StandardException.newException(SQLState.LANG_STATEMENT_CLOSED, "completeCompile()");
paramTypeDescriptors = qt.getParameterTypes();
// erase cursor info in case statement text changed
if (targetTable!=null) {
targetTable = null;
updateMode = 0;
updateColumns = null;
targetColumns = null;
}
// get the result description (null for non-cursor statements)
// would we want to reuse an old resultDesc?
// or do we need to always replace in case this was select *?
resultDesc = qt.makeResultDescription();
// would look at resultDesc.getStatementType() but it
// doesn't call out cursors as such, so we check
// the root node type instead.
if (resultDesc != null)
{
/*
For cursors, we carry around some extra information.
*/
CursorInfo cursorInfo = (CursorInfo)qt.getCursorInfo();
if (cursorInfo != null)
{
targetTable = cursorInfo.targetTable;
targetColumns = cursorInfo.targetColumns;
updateColumns = cursorInfo.updateColumns;
updateMode = cursorInfo.updateMode;
}
}
isValid = true;
return;
}
public GeneratedClass getActivationClass()
throws StandardException
{
return activationClass;
}
void setActivationClass(GeneratedClass ac)
{
activationClass = ac;
}
// ExecPreparedStatement
/**
* the update mode of the cursor
*
* @return The update mode of the cursor
*/
public int getUpdateMode() {
return updateMode;
}
/**
* the target table of the cursor
*
* @return target table of the cursor
*/
public ExecCursorTableReference getTargetTable()
{
if (SanityManager.DEBUG)
{
SanityManager.ASSERT(targetTable!=null, "Not a cursor, no target table");
}
return targetTable;
}
/**
* the target columns of the cursor as a result column list
*
* @return target columns of the cursor as a result column list
*/
public ResultColumnDescriptor[] getTargetColumns() {
return targetColumns;
}
/**
* the update columns of the cursor as a update column list
*
* @return update columns of the cursor as a array of strings
*/
public String[] getUpdateColumns()
{
return updateColumns;
}
/**
* Return the cursor info in a single chunk. Used
* by StrorablePreparedStatement
*/
public Object getCursorInfo()
{
return new CursorInfo(
updateMode,
targetTable,
targetColumns,
updateColumns);
}
void setCursorInfo(CursorInfo cursorInfo)
{
if (cursorInfo != null)
{
updateMode = cursorInfo.updateMode;
targetTable = cursorInfo.targetTable;
targetColumns = cursorInfo.targetColumns;
updateColumns = cursorInfo.updateColumns;
}
}
// class implementation
/**
* Get the byte code saver for this statement.
* Overridden for StorablePreparedStatement. We
* don't want to save anything
*
* @return a byte code saver (null for us)
*/
ByteArray getByteCodeSaver()
{
return null;
}
/**
* Does this statement need a savepoint?
*
* @return true if this statement needs a savepoint.
*/
public boolean needsSavepoint()
{
return needsSavepoint;
}
/**
* Set the stmts 'needsSavepoint' state. Used
* by an SPS to convey whether the underlying stmt
* needs a savepoint or not.
*
* @param needsSavepoint true if this statement needs a savepoint.
*/
void setNeedsSavepoint(boolean needsSavepoint)
{
this.needsSavepoint = needsSavepoint;
}
/**
* Set the stmts 'isAtomic' state.
*
* @param isAtomic true if this statement must be atomic
* (i.e. it is not ok to do a commit/rollback in the middle)
*/
void setIsAtomic(boolean isAtomic)
{
this.isAtomic = isAtomic;
}
/**
* Returns whether or not this Statement requires should
* behave atomically -- i.e. whether a user is permitted
* to do a commit/rollback during the execution of this
* statement.
*
* @return boolean Whether or not this Statement is atomic
*/
public boolean isAtomic()
{
return isAtomic;
}
/**
* Set the name of the statement and schema for an "execute statement"
* command.
*/
void setExecuteStatementNameAndSchema(String execStmtName,
String execSchemaName)
{
this.execStmtName = execStmtName;
this.execSchemaName = execSchemaName;
}
/**
* Get a new prepared statement that is a shallow copy
* of the current one.
*
* @return a new prepared statement
*
* @exception StandardException on error
*/
public ExecPreparedStatement getClone() throws StandardException
{
GenericPreparedStatement clone = new GenericPreparedStatement(statement);
clone.activationClass = getActivationClass();
clone.resultDesc = resultDesc;
clone.paramTypeDescriptors = paramTypeDescriptors;
clone.executionConstants = executionConstants;
clone.UUIDString = UUIDString;
clone.UUIDValue = UUIDValue;
clone.savedObjects = savedObjects;
clone.execStmtName = execStmtName;
clone.execSchemaName = execSchemaName;
clone.isAtomic = isAtomic;
clone.sourceTxt = sourceTxt;
clone.targetTable = targetTable;
clone.targetColumns = targetColumns;
clone.updateColumns = updateColumns;
clone.updateMode = updateMode;
clone.needsSavepoint = needsSavepoint;
return clone;
}
// cache holder stuff.
public void setCacheHolder(Cacheable cacheHolder) {
this.cacheHolder = cacheHolder;
if (cacheHolder == null) {
// need to invalidate the statement
if (!isValid || (inUseCount != 0))
return;
ContextManager cm = ContextService.getFactory().getCurrentContextManager();
LanguageConnectionContext lcc =
(LanguageConnectionContext)
(cm.getContext(LanguageConnectionContext.CONTEXT_ID));
// invalidate any prepared statements that
// depended on this statement (including this one)
// prepareToInvalidate(this, DependencyManager.PREPARED_STATEMENT_INVALID);
try
{
/* NOTE: Since we are non-persistent, we "know" that no exception
* will be thrown under us.
*/
makeInvalid(DependencyManager.PREPARED_STATEMENT_RELEASE, lcc);
}
catch (StandardException se)
{
if (SanityManager.DEBUG)
{
SanityManager.THROWASSERT("Unexpected exception", se);
}
}
}
}
public String toString() {
return getObjectName();
}
public boolean isStorable() {
return false;
}
public void setRequiredPermissionsList( List requiredPermissionsList)
{
this.requiredPermissionsList = requiredPermissionsList;
}
public List getRequiredPermissionsList()
{
return requiredPermissionsList;
}
public final long getVersionCounter() {
return versionCounter;
}
public final void incrementVersionCounter() {
++versionCounter;
}
}
|
package com.jme3.audio.plugins;
import com.jme3.util.IntMap;
import de.jarnbjo.ogg.LogicalOggStream;
import de.jarnbjo.ogg.LogicalOggStreamImpl;
import de.jarnbjo.ogg.OggPage;
import de.jarnbjo.ogg.PhysicalOggStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Implementation of the <code>PhysicalOggStream</code> interface for reading
* and caching an Ogg stream from a URL. This class reads the data as fast as
* possible from the URL, caches it locally either in memory or on disk, and
* supports seeking within the available data.
*/
public class CachedOggStream implements PhysicalOggStream {
private boolean closed = false;
private boolean eos = false;
private boolean bos = false;
private InputStream sourceStream;
private HashMap<Integer, LogicalOggStream> logicalStreams
= new HashMap<Integer, LogicalOggStream>();
private IntMap<OggPage> oggPages = new IntMap<OggPage>();
private OggPage lastPage;
private int pageNumber;
private int serialno;
public CachedOggStream(InputStream in) throws IOException {
sourceStream = in;
// Read all OGG pages in file
long time = System.nanoTime();
while (!eos){
readOggNextPage();
}
long dt = System.nanoTime() - time;
Logger.getLogger(CachedOggStream.class.getName()).log(Level.FINE, "Took {0} ms to load OGG", dt/1000000);
}
public OggPage getLastOggPage() {
return lastPage;
}
private LogicalOggStream getLogicalStream(int serialNumber) {
return logicalStreams.get(Integer.valueOf(serialNumber));
}
public Collection<LogicalOggStream> getLogicalStreams() {
return logicalStreams.values();
}
public boolean isOpen() {
return !closed;
}
public void close() throws IOException {
closed = true;
sourceStream.close();
}
public OggPage getOggPage(int index) throws IOException {
return oggPages.get(index);
}
public void setTime(long granulePosition) throws IOException {
for (LogicalOggStream los : getLogicalStreams()){
los.setTime(granulePosition);
}
}
public LogicalOggStream reloadLogicalOggStream() {
logicalStreams.clear();
LogicalOggStreamImpl los = new LogicalOggStreamImpl(this, serialno);
logicalStreams.put(serialno, los);
for (IntMap.Entry<OggPage> entry : oggPages) {
los.addPageNumberMapping(entry.getKey());
los.addGranulePosition(entry.getValue().getAbsoluteGranulePosition());
}
return los;
}
private int readOggNextPage() throws IOException {
if (eos)
return -1;
OggPage op = OggPage.create(sourceStream);
if (!op.isBos()){
bos = true;
}
if (op.isEos()){
eos = true;
lastPage = op;
}
LogicalOggStreamImpl los = (LogicalOggStreamImpl) logicalStreams.get(op.getStreamSerialNumber());
if (los == null) {
serialno = op.getStreamSerialNumber();
los = new LogicalOggStreamImpl(this, op.getStreamSerialNumber());
logicalStreams.put(op.getStreamSerialNumber(), los);
los.checkFormat(op);
}
los.addPageNumberMapping(pageNumber);
los.addGranulePosition(op.getAbsoluteGranulePosition());
oggPages.put(pageNumber, op);
pageNumber++;
return pageNumber-1;
}
public boolean isSeekable() {
return true;
}
}
|
package com.jme3.renderer.lwjgl;
import com.jme3.light.LightList;
import com.jme3.material.RenderState;
import com.jme3.material.RenderState.StencilOperation;
import com.jme3.material.RenderState.TestFunction;
import com.jme3.math.*;
import com.jme3.renderer.*;
import com.jme3.scene.Mesh;
import com.jme3.scene.Mesh.Mode;
import com.jme3.scene.VertexBuffer;
import com.jme3.scene.VertexBuffer.Format;
import com.jme3.scene.VertexBuffer.Type;
import com.jme3.scene.VertexBuffer.Usage;
import com.jme3.shader.Attribute;
import com.jme3.shader.Shader;
import com.jme3.shader.Shader.ShaderSource;
import com.jme3.shader.Shader.ShaderType;
import com.jme3.shader.Uniform;
import com.jme3.texture.FrameBuffer;
import com.jme3.texture.FrameBuffer.RenderBuffer;
import com.jme3.texture.Image;
import com.jme3.texture.Texture;
import com.jme3.texture.Texture.WrapAxis;
import com.jme3.util.BufferUtils;
import com.jme3.util.ListMap;
import com.jme3.util.NativeObjectManager;
import java.nio.*;
import java.util.EnumSet;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import jme3tools.converters.MipMapGenerator;
import jme3tools.shader.ShaderDebug;
import static org.lwjgl.opengl.ARBDrawInstanced.*;
import static org.lwjgl.opengl.ARBInstancedArrays.*;
import static org.lwjgl.opengl.ARBMultisample.*;
import static org.lwjgl.opengl.ARBTextureMultisample.*;
import static org.lwjgl.opengl.ARBVertexArrayObject.*;
import org.lwjgl.opengl.ContextCapabilities;
import static org.lwjgl.opengl.EXTFramebufferBlit.*;
import static org.lwjgl.opengl.EXTFramebufferMultisample.*;
import static org.lwjgl.opengl.EXTFramebufferObject.*;
import static org.lwjgl.opengl.EXTFramebufferSRGB.*;
import static org.lwjgl.opengl.EXTGpuShader4.*;
import static org.lwjgl.opengl.EXTTextureArray.*;
import static org.lwjgl.opengl.EXTTextureFilterAnisotropic.*;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.opengl.GL12.*;
import static org.lwjgl.opengl.GL13.*;
import static org.lwjgl.opengl.GL14.*;
import static org.lwjgl.opengl.GL15.*;
import static org.lwjgl.opengl.GL20.*;
import org.lwjgl.opengl.GLContext;
//import static org.lwjgl.opengl.GL21.*;
//import static org.lwjgl.opengl.GL30.*;
public class LwjglRenderer implements Renderer {
private static final Logger logger = Logger.getLogger(LwjglRenderer.class.getName());
private static final boolean VALIDATE_SHADER = false;
private final ByteBuffer nameBuf = BufferUtils.createByteBuffer(250);
private final StringBuilder stringBuf = new StringBuilder(250);
private final IntBuffer intBuf1 = BufferUtils.createIntBuffer(1);
private final IntBuffer intBuf16 = BufferUtils.createIntBuffer(16);
private final FloatBuffer floatBuf16 = BufferUtils.createFloatBuffer(16);
private final RenderContext context = new RenderContext();
private final NativeObjectManager objManager = new NativeObjectManager();
private final EnumSet<Caps> caps = EnumSet.noneOf(Caps.class);
private int vertexTextureUnits;
private int fragTextureUnits;
private int vertexUniforms;
private int fragUniforms;
private int vertexAttribs;
private int maxFBOSamples;
private int maxFBOAttachs;
private int maxMRTFBOAttachs;
private int maxRBSize;
private int maxTexSize;
private int maxCubeTexSize;
private int maxVertCount;
private int maxTriCount;
private int maxColorTexSamples;
private int maxDepthTexSamples;
private FrameBuffer mainFbOverride = null;
private final Statistics statistics = new Statistics();
private int vpX, vpY, vpW, vpH;
private int clipX, clipY, clipW, clipH;
private boolean linearizeSrgbImages;
private ContextCapabilities ctxCaps;
public LwjglRenderer() {
}
protected void updateNameBuffer() {
int len = stringBuf.length();
nameBuf.position(0);
nameBuf.limit(len);
for (int i = 0; i < len; i++) {
nameBuf.put((byte) stringBuf.charAt(i));
}
nameBuf.rewind();
}
@Override
public Statistics getStatistics() {
return statistics;
}
@Override
public EnumSet<Caps> getCaps() {
return caps;
}
private static int extractVersion(String prefixStr, String versionStr) {
if (versionStr != null) {
int spaceIdx = versionStr.indexOf(" ", prefixStr.length());
if (spaceIdx >= 1) {
versionStr = versionStr.substring(prefixStr.length(), spaceIdx).trim();
} else {
versionStr = versionStr.substring(prefixStr.length()).trim();
}
// Some device have ":" at the end of the version.
versionStr = versionStr.replaceAll("\\:", "");
// Pivot on first point.
int firstPoint = versionStr.indexOf(".");
// Remove everything after second point.
int secondPoint = versionStr.indexOf(".", firstPoint + 1);
if (secondPoint != -1) {
versionStr = versionStr.substring(0, secondPoint);
}
String majorVerStr = versionStr.substring(0, firstPoint);
String minorVerStr = versionStr.substring(firstPoint + 1);
if (minorVerStr.endsWith("0") && minorVerStr.length() > 1) {
minorVerStr = minorVerStr.substring(0, minorVerStr.length() - 1);
}
int majorVer = Integer.parseInt(majorVerStr);
int minorVer = Integer.parseInt(minorVerStr);
return majorVer * 100 + minorVer * 10;
} else {
return -1;
}
}
@SuppressWarnings("fallthrough")
public void initialize() {
int oglVer = extractVersion("", glGetString(GL_VERSION));
if (oglVer >= 200) {
caps.add(Caps.OpenGL20);
if (oglVer >= 210) {
caps.add(Caps.OpenGL21);
if (oglVer >= 300) {
caps.add(Caps.OpenGL30);
if (oglVer >= 310) {
caps.add(Caps.OpenGL31);
if (oglVer >= 320) {
caps.add(Caps.OpenGL32);
}
}
}
}
}
// Fix issue in TestRenderToMemory when GL_FRONT is the main
// buffer being used.
context.initialDrawBuf = glGetInteger(GL_DRAW_BUFFER);
context.initialReadBuf = glGetInteger(GL_READ_BUFFER);
// XXX: This has to be GL_BACK for canvas on Mac
// Since initialDrawBuf is GL_FRONT for pbuffer, gotta
// change this value later on ...
// initialDrawBuf = GL_BACK;
// initialReadBuf = GL_BACK;
int glslVer = extractVersion("", glGetString(GL_SHADING_LANGUAGE_VERSION));
switch (glslVer) {
default:
if (glslVer < 400) {
break;
}
// so that future OpenGL revisions wont break jme3
// fall through intentional
case 400:
case 330:
case 150:
caps.add(Caps.GLSL150);
case 140:
caps.add(Caps.GLSL140);
case 130:
caps.add(Caps.GLSL130);
case 120:
caps.add(Caps.GLSL120);
case 110:
caps.add(Caps.GLSL110);
case 100:
caps.add(Caps.GLSL100);
break;
}
// Workaround, always assume we support GLSL100.
// Some cards just don't report this correctly.
caps.add(Caps.GLSL100);
ctxCaps = GLContext.getCapabilities();
glGetInteger(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS, intBuf16);
vertexTextureUnits = intBuf16.get(0);
logger.log(Level.FINER, "VTF Units: {0}", vertexTextureUnits);
if (vertexTextureUnits > 0) {
caps.add(Caps.VertexTextureFetch);
}
glGetInteger(GL_MAX_TEXTURE_IMAGE_UNITS, intBuf16);
fragTextureUnits = intBuf16.get(0);
logger.log(Level.FINER, "Texture Units: {0}", fragTextureUnits);
glGetInteger(GL_MAX_VERTEX_UNIFORM_COMPONENTS, intBuf16);
vertexUniforms = intBuf16.get(0);
logger.log(Level.FINER, "Vertex Uniforms: {0}", vertexUniforms);
glGetInteger(GL_MAX_FRAGMENT_UNIFORM_COMPONENTS, intBuf16);
fragUniforms = intBuf16.get(0);
logger.log(Level.FINER, "Fragment Uniforms: {0}", fragUniforms);
glGetInteger(GL_MAX_VERTEX_ATTRIBS, intBuf16);
vertexAttribs = intBuf16.get(0);
logger.log(Level.FINER, "Vertex Attributes: {0}", vertexAttribs);
glGetInteger(GL_SUBPIXEL_BITS, intBuf16);
int subpixelBits = intBuf16.get(0);
logger.log(Level.FINER, "Subpixel Bits: {0}", subpixelBits);
glGetInteger(GL_MAX_ELEMENTS_VERTICES, intBuf16);
maxVertCount = intBuf16.get(0);
logger.log(Level.FINER, "Preferred Batch Vertex Count: {0}", maxVertCount);
glGetInteger(GL_MAX_ELEMENTS_INDICES, intBuf16);
maxTriCount = intBuf16.get(0);
logger.log(Level.FINER, "Preferred Batch Index Count: {0}", maxTriCount);
glGetInteger(GL_MAX_TEXTURE_SIZE, intBuf16);
maxTexSize = intBuf16.get(0);
logger.log(Level.FINER, "Maximum Texture Resolution: {0}", maxTexSize);
glGetInteger(GL_MAX_CUBE_MAP_TEXTURE_SIZE, intBuf16);
maxCubeTexSize = intBuf16.get(0);
logger.log(Level.FINER, "Maximum CubeMap Resolution: {0}", maxCubeTexSize);
if (ctxCaps.GL_ARB_color_buffer_float) {
// XXX: Require both 16 and 32 bit float support for FloatColorBuffer.
if (ctxCaps.GL_ARB_half_float_pixel) {
caps.add(Caps.FloatColorBuffer);
}
}
if (ctxCaps.GL_ARB_depth_buffer_float) {
caps.add(Caps.FloatDepthBuffer);
}
if (ctxCaps.OpenGL30) {
caps.add(Caps.PackedDepthStencilBuffer);
}
if (ctxCaps.GL_ARB_draw_instanced && ctxCaps.GL_ARB_instanced_arrays) {
caps.add(Caps.MeshInstancing);
}
if (ctxCaps.GL_ARB_fragment_program) {
caps.add(Caps.ARBprogram);
}
if (ctxCaps.GL_ARB_texture_buffer_object) {
caps.add(Caps.TextureBuffer);
}
if (ctxCaps.GL_ARB_texture_float) {
if (ctxCaps.GL_ARB_half_float_pixel) {
caps.add(Caps.FloatTexture);
}
}
if (ctxCaps.GL_ARB_vertex_array_object) {
caps.add(Caps.VertexBufferArray);
}
if (ctxCaps.GL_ARB_texture_non_power_of_two) {
caps.add(Caps.NonPowerOfTwoTextures);
} else {
logger.log(Level.WARNING, "Your graphics card does not "
+ "support non-power-of-2 textures. "
+ "Some features might not work.");
}
boolean latc = ctxCaps.GL_EXT_texture_compression_latc;
if (latc) {
caps.add(Caps.TextureCompressionLATC);
}
if (ctxCaps.GL_EXT_packed_float || ctxCaps.OpenGL30) {
// This format is part of the OGL3 specification
caps.add(Caps.PackedFloatColorBuffer);
if (ctxCaps.GL_ARB_half_float_pixel) {
// because textures are usually uploaded as RGB16F
// need half-float pixel
caps.add(Caps.PackedFloatTexture);
}
}
if (ctxCaps.GL_EXT_texture_array || ctxCaps.OpenGL30) {
caps.add(Caps.TextureArray);
}
if (ctxCaps.GL_EXT_texture_shared_exponent || ctxCaps.OpenGL30) {
caps.add(Caps.SharedExponentTexture);
}
if (ctxCaps.GL_EXT_framebuffer_object) {
caps.add(Caps.FrameBuffer);
glGetInteger(GL_MAX_RENDERBUFFER_SIZE_EXT, intBuf16);
maxRBSize = intBuf16.get(0);
logger.log(Level.FINER, "FBO RB Max Size: {0}", maxRBSize);
glGetInteger(GL_MAX_COLOR_ATTACHMENTS_EXT, intBuf16);
maxFBOAttachs = intBuf16.get(0);
logger.log(Level.FINER, "FBO Max renderbuffers: {0}", maxFBOAttachs);
if (ctxCaps.GL_EXT_framebuffer_multisample) {
caps.add(Caps.FrameBufferMultisample);
glGetInteger(GL_MAX_SAMPLES_EXT, intBuf16);
maxFBOSamples = intBuf16.get(0);
logger.log(Level.FINER, "FBO Max Samples: {0}", maxFBOSamples);
}
if (ctxCaps.GL_ARB_texture_multisample) {
caps.add(Caps.TextureMultisample);
glGetInteger(GL_MAX_COLOR_TEXTURE_SAMPLES, intBuf16);
maxColorTexSamples = intBuf16.get(0);
logger.log(Level.FINER, "Texture Multisample Color Samples: {0}", maxColorTexSamples);
glGetInteger(GL_MAX_DEPTH_TEXTURE_SAMPLES, intBuf16);
maxDepthTexSamples = intBuf16.get(0);
logger.log(Level.FINER, "Texture Multisample Depth Samples: {0}", maxDepthTexSamples);
}
glGetInteger(GL_MAX_DRAW_BUFFERS, intBuf16);
maxMRTFBOAttachs = intBuf16.get(0);
if (maxMRTFBOAttachs > 1) {
caps.add(Caps.FrameBufferMRT);
logger.log(Level.FINER, "FBO Max MRT renderbuffers: {0}", maxMRTFBOAttachs);
}
}
if (ctxCaps.GL_ARB_multisample) {
glGetInteger(GL_SAMPLE_BUFFERS_ARB, intBuf16);
boolean available = intBuf16.get(0) != 0;
glGetInteger(GL_SAMPLES_ARB, intBuf16);
int samples = intBuf16.get(0);
logger.log(Level.FINER, "Samples: {0}", samples);
boolean enabled = glIsEnabled(GL_MULTISAMPLE_ARB);
if (samples > 0 && available && !enabled) {
glEnable(GL_MULTISAMPLE_ARB);
}
caps.add(Caps.Multisample);
}
// Supports sRGB pipeline.
if ( (ctxCaps.GL_ARB_framebuffer_sRGB && ctxCaps.GL_EXT_texture_sRGB ) || ctxCaps.OpenGL30 ) {
caps.add(Caps.Srgb);
}
logger.log(Level.FINE, "Caps: {0}", caps);
}
public void invalidateState() {
context.reset();
context.initialDrawBuf = glGetInteger(GL_DRAW_BUFFER);
context.initialReadBuf = glGetInteger(GL_READ_BUFFER);
}
public void resetGLObjects() {
logger.log(Level.FINE, "Reseting objects and invalidating state");
objManager.resetObjects();
statistics.clearMemory();
invalidateState();
}
public void cleanup() {
logger.log(Level.FINE, "Deleting objects and invalidating state");
objManager.deleteAllObjects(this);
statistics.clearMemory();
invalidateState();
}
private void checkCap(Caps cap) {
if (!caps.contains(cap)) {
throw new UnsupportedOperationException("Required capability missing: " + cap.name());
}
}
public void setDepthRange(float start, float end) {
glDepthRange(start, end);
}
public void clearBuffers(boolean color, boolean depth, boolean stencil) {
int bits = 0;
if (color) {
//See explanations of the depth below, we must enable color write to be able to clear the color buffer
if (context.colorWriteEnabled == false) {
glColorMask(true, true, true, true);
context.colorWriteEnabled = true;
}
bits = GL_COLOR_BUFFER_BIT;
}
if (depth) {
//glClear(GL_DEPTH_BUFFER_BIT) seems to not work when glDepthMask is false
//here s some link on openl board
//if depth clear is requested, we enable the depthMask
if (context.depthWriteEnabled == false) {
glDepthMask(true);
context.depthWriteEnabled = true;
}
bits |= GL_DEPTH_BUFFER_BIT;
}
if (stencil) {
bits |= GL_STENCIL_BUFFER_BIT;
}
if (bits != 0) {
glClear(bits);
}
}
public void setBackgroundColor(ColorRGBA color) {
glClearColor(color.r, color.g, color.b, color.a);
}
public void setAlphaToCoverage(boolean value) {
if (ctxCaps.GL_ARB_multisample) {
if (value) {
glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE_ARB);
} else {
glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE_ARB);
}
}
}
public void applyRenderState(RenderState state) {
if (state.isWireframe() && !context.wireframe) {
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
context.wireframe = true;
} else if (!state.isWireframe() && context.wireframe) {
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
context.wireframe = false;
}
if (state.isDepthTest() && !context.depthTestEnabled) {
glEnable(GL_DEPTH_TEST);
glDepthFunc(convertTestFunction(context.depthFunc));
context.depthTestEnabled = true;
} else if (!state.isDepthTest() && context.depthTestEnabled) {
glDisable(GL_DEPTH_TEST);
context.depthTestEnabled = false;
}
if (state.getDepthFunc() != context.depthFunc) {
glDepthFunc(convertTestFunction(state.getDepthFunc()));
context.depthFunc = state.getDepthFunc();
}
if (state.isAlphaTest() && !context.alphaTestEnabled) {
glEnable(GL_ALPHA_TEST);
glAlphaFunc(convertTestFunction(context.alphaFunc), context.alphaTestFallOff);
context.alphaTestEnabled = true;
} else if (!state.isAlphaTest() && context.alphaTestEnabled) {
glDisable(GL_ALPHA_TEST);
context.alphaTestEnabled = false;
}
if (state.getAlphaFallOff() != context.alphaTestFallOff) {
glAlphaFunc(convertTestFunction(context.alphaFunc), context.alphaTestFallOff);
context.alphaTestFallOff = state.getAlphaFallOff();
}
if (state.getAlphaFunc() != context.alphaFunc) {
glAlphaFunc(convertTestFunction(state.getAlphaFunc()), context.alphaTestFallOff);
context.alphaFunc = state.getAlphaFunc();
}
if (state.isDepthWrite() && !context.depthWriteEnabled) {
glDepthMask(true);
context.depthWriteEnabled = true;
} else if (!state.isDepthWrite() && context.depthWriteEnabled) {
glDepthMask(false);
context.depthWriteEnabled = false;
}
if (state.isColorWrite() && !context.colorWriteEnabled) {
glColorMask(true, true, true, true);
context.colorWriteEnabled = true;
} else if (!state.isColorWrite() && context.colorWriteEnabled) {
glColorMask(false, false, false, false);
context.colorWriteEnabled = false;
}
if (state.isPointSprite() && !context.pointSprite) {
// Only enable/disable sprite
if (context.boundTextures[0] != null) {
if (context.boundTextureUnit != 0) {
glActiveTexture(GL_TEXTURE0);
context.boundTextureUnit = 0;
}
glEnable(GL_POINT_SPRITE);
glEnable(GL_VERTEX_PROGRAM_POINT_SIZE);
}
context.pointSprite = true;
} else if (!state.isPointSprite() && context.pointSprite) {
if (context.boundTextures[0] != null) {
if (context.boundTextureUnit != 0) {
glActiveTexture(GL_TEXTURE0);
context.boundTextureUnit = 0;
}
glDisable(GL_POINT_SPRITE);
glDisable(GL_VERTEX_PROGRAM_POINT_SIZE);
context.pointSprite = false;
}
}
if (state.isPolyOffset()) {
if (!context.polyOffsetEnabled) {
glEnable(GL_POLYGON_OFFSET_FILL);
glPolygonOffset(state.getPolyOffsetFactor(),
state.getPolyOffsetUnits());
context.polyOffsetEnabled = true;
context.polyOffsetFactor = state.getPolyOffsetFactor();
context.polyOffsetUnits = state.getPolyOffsetUnits();
} else {
if (state.getPolyOffsetFactor() != context.polyOffsetFactor
|| state.getPolyOffsetUnits() != context.polyOffsetUnits) {
glPolygonOffset(state.getPolyOffsetFactor(),
state.getPolyOffsetUnits());
context.polyOffsetFactor = state.getPolyOffsetFactor();
context.polyOffsetUnits = state.getPolyOffsetUnits();
}
}
} else {
if (context.polyOffsetEnabled) {
glDisable(GL_POLYGON_OFFSET_FILL);
context.polyOffsetEnabled = false;
context.polyOffsetFactor = 0;
context.polyOffsetUnits = 0;
}
}
if (state.getFaceCullMode() != context.cullMode) {
if (state.getFaceCullMode() == RenderState.FaceCullMode.Off) {
glDisable(GL_CULL_FACE);
} else {
glEnable(GL_CULL_FACE);
}
switch (state.getFaceCullMode()) {
case Off:
break;
case Back:
glCullFace(GL_BACK);
break;
case Front:
glCullFace(GL_FRONT);
break;
case FrontAndBack:
glCullFace(GL_FRONT_AND_BACK);
break;
default:
throw new UnsupportedOperationException("Unrecognized face cull mode: "
+ state.getFaceCullMode());
}
context.cullMode = state.getFaceCullMode();
}
if (state.getBlendMode() != context.blendMode) {
if (state.getBlendMode() == RenderState.BlendMode.Off) {
glDisable(GL_BLEND);
} else {
glEnable(GL_BLEND);
switch (state.getBlendMode()) {
case Off:
break;
case Additive:
glBlendFunc(GL_ONE, GL_ONE);
break;
case AlphaAdditive:
glBlendFunc(GL_SRC_ALPHA, GL_ONE);
break;
case Color:
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_COLOR);
break;
case Alpha:
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
break;
case PremultAlpha:
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
break;
case Modulate:
glBlendFunc(GL_DST_COLOR, GL_ZERO);
break;
case ModulateX2:
glBlendFunc(GL_DST_COLOR, GL_SRC_COLOR);
break;
case Screen:
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_COLOR);
break;
case Exclusion:
glBlendFunc(GL_ONE_MINUS_DST_COLOR, GL_ONE_MINUS_SRC_COLOR);
break;
default:
throw new UnsupportedOperationException("Unrecognized blend mode: "
+ state.getBlendMode());
}
}
context.blendMode = state.getBlendMode();
}
if (context.stencilTest != state.isStencilTest()
|| context.frontStencilStencilFailOperation != state.getFrontStencilStencilFailOperation()
|| context.frontStencilDepthFailOperation != state.getFrontStencilDepthFailOperation()
|| context.frontStencilDepthPassOperation != state.getFrontStencilDepthPassOperation()
|| context.backStencilStencilFailOperation != state.getBackStencilStencilFailOperation()
|| context.backStencilDepthFailOperation != state.getBackStencilDepthFailOperation()
|| context.backStencilDepthPassOperation != state.getBackStencilDepthPassOperation()
|| context.frontStencilFunction != state.getFrontStencilFunction()
|| context.backStencilFunction != state.getBackStencilFunction()) {
context.frontStencilStencilFailOperation = state.getFrontStencilStencilFailOperation(); //terrible looking, I know
context.frontStencilDepthFailOperation = state.getFrontStencilDepthFailOperation();
context.frontStencilDepthPassOperation = state.getFrontStencilDepthPassOperation();
context.backStencilStencilFailOperation = state.getBackStencilStencilFailOperation();
context.backStencilDepthFailOperation = state.getBackStencilDepthFailOperation();
context.backStencilDepthPassOperation = state.getBackStencilDepthPassOperation();
context.frontStencilFunction = state.getFrontStencilFunction();
context.backStencilFunction = state.getBackStencilFunction();
if (state.isStencilTest()) {
glEnable(GL_STENCIL_TEST);
glStencilOpSeparate(GL_FRONT,
convertStencilOperation(state.getFrontStencilStencilFailOperation()),
convertStencilOperation(state.getFrontStencilDepthFailOperation()),
convertStencilOperation(state.getFrontStencilDepthPassOperation()));
glStencilOpSeparate(GL_BACK,
convertStencilOperation(state.getBackStencilStencilFailOperation()),
convertStencilOperation(state.getBackStencilDepthFailOperation()),
convertStencilOperation(state.getBackStencilDepthPassOperation()));
glStencilFuncSeparate(GL_FRONT,
convertTestFunction(state.getFrontStencilFunction()),
0, Integer.MAX_VALUE);
glStencilFuncSeparate(GL_BACK,
convertTestFunction(state.getBackStencilFunction()),
0, Integer.MAX_VALUE);
} else {
glDisable(GL_STENCIL_TEST);
}
}
}
private int convertStencilOperation(StencilOperation stencilOp) {
switch (stencilOp) {
case Keep:
return GL_KEEP;
case Zero:
return GL_ZERO;
case Replace:
return GL_REPLACE;
case Increment:
return GL_INCR;
case IncrementWrap:
return GL_INCR_WRAP;
case Decrement:
return GL_DECR;
case DecrementWrap:
return GL_DECR_WRAP;
case Invert:
return GL_INVERT;
default:
throw new UnsupportedOperationException("Unrecognized stencil operation: " + stencilOp);
}
}
private int convertTestFunction(TestFunction testFunc) {
switch (testFunc) {
case Never:
return GL_NEVER;
case Less:
return GL_LESS;
case LessOrEqual:
return GL_LEQUAL;
case Greater:
return GL_GREATER;
case GreaterOrEqual:
return GL_GEQUAL;
case Equal:
return GL_EQUAL;
case NotEqual:
return GL_NOTEQUAL;
case Always:
return GL_ALWAYS;
default:
throw new UnsupportedOperationException("Unrecognized test function: " + testFunc);
}
}
public void setViewPort(int x, int y, int w, int h) {
if (x != vpX || vpY != y || vpW != w || vpH != h) {
glViewport(x, y, w, h);
vpX = x;
vpY = y;
vpW = w;
vpH = h;
}
}
public void setClipRect(int x, int y, int width, int height) {
if (!context.clipRectEnabled) {
glEnable(GL_SCISSOR_TEST);
context.clipRectEnabled = true;
}
if (clipX != x || clipY != y || clipW != width || clipH != height) {
glScissor(x, y, width, height);
clipX = x;
clipY = y;
clipW = width;
clipH = height;
}
}
public void clearClipRect() {
if (context.clipRectEnabled) {
glDisable(GL_SCISSOR_TEST);
context.clipRectEnabled = false;
clipX = 0;
clipY = 0;
clipW = 0;
clipH = 0;
}
}
public void onFrame() {
objManager.deleteUnused(this);
// statistics.clearFrame();
}
public void setWorldMatrix(Matrix4f worldMatrix) {
}
public void setViewProjectionMatrices(Matrix4f viewMatrix, Matrix4f projMatrix) {
}
protected void updateUniformLocation(Shader shader, Uniform uniform) {
stringBuf.setLength(0);
stringBuf.append(uniform.getName()).append('\0');
updateNameBuffer();
int loc = glGetUniformLocation(shader.getId(), nameBuf);
if (loc < 0) {
uniform.setLocation(-1);
// uniform is not declared in shader
logger.log(Level.FINE, "Uniform {0} is not declared in shader {1}.", new Object[]{uniform.getName(), shader.getSources()});
} else {
uniform.setLocation(loc);
}
}
protected void bindProgram(Shader shader) {
int shaderId = shader.getId();
if (context.boundShaderProgram != shaderId) {
glUseProgram(shaderId);
statistics.onShaderUse(shader, true);
context.boundShader = shader;
context.boundShaderProgram = shaderId;
} else {
statistics.onShaderUse(shader, false);
}
}
protected void updateUniform(Shader shader, Uniform uniform) {
int shaderId = shader.getId();
assert uniform.getName() != null;
assert shader.getId() > 0;
bindProgram(shader);
int loc = uniform.getLocation();
if (loc == -1) {
return;
}
if (loc == -2) {
// get uniform location
updateUniformLocation(shader, uniform);
if (uniform.getLocation() == -1) {
// not declared, ignore
uniform.clearUpdateNeeded();
return;
}
loc = uniform.getLocation();
}
if (uniform.getVarType() == null) {
return; // value not set yet..
}
statistics.onUniformSet();
uniform.clearUpdateNeeded();
FloatBuffer fb;
IntBuffer ib;
switch (uniform.getVarType()) {
case Float:
Float f = (Float) uniform.getValue();
glUniform1f(loc, f.floatValue());
break;
case Vector2:
Vector2f v2 = (Vector2f) uniform.getValue();
glUniform2f(loc, v2.getX(), v2.getY());
break;
case Vector3:
Vector3f v3 = (Vector3f) uniform.getValue();
glUniform3f(loc, v3.getX(), v3.getY(), v3.getZ());
break;
case Vector4:
Object val = uniform.getValue();
if (val instanceof ColorRGBA) {
ColorRGBA c = (ColorRGBA) val;
glUniform4f(loc, c.r, c.g, c.b, c.a);
} else if (val instanceof Vector4f) {
Vector4f c = (Vector4f) val;
glUniform4f(loc, c.x, c.y, c.z, c.w);
} else {
Quaternion c = (Quaternion) uniform.getValue();
glUniform4f(loc, c.getX(), c.getY(), c.getZ(), c.getW());
}
break;
case Boolean:
Boolean b = (Boolean) uniform.getValue();
glUniform1i(loc, b.booleanValue() ? GL_TRUE : GL_FALSE);
break;
case Matrix3:
fb = (FloatBuffer) uniform.getValue();
assert fb.remaining() == 9;
glUniformMatrix3(loc, false, fb);
break;
case Matrix4:
fb = (FloatBuffer) uniform.getValue();
assert fb.remaining() == 16;
glUniformMatrix4(loc, false, fb);
break;
case IntArray:
ib = (IntBuffer) uniform.getValue();
glUniform1(loc, ib);
break;
case FloatArray:
fb = (FloatBuffer) uniform.getValue();
glUniform1(loc, fb);
break;
case Vector2Array:
fb = (FloatBuffer) uniform.getValue();
glUniform2(loc, fb);
break;
case Vector3Array:
fb = (FloatBuffer) uniform.getValue();
glUniform3(loc, fb);
break;
case Vector4Array:
fb = (FloatBuffer) uniform.getValue();
glUniform4(loc, fb);
break;
case Matrix4Array:
fb = (FloatBuffer) uniform.getValue();
glUniformMatrix4(loc, false, fb);
break;
case Int:
Integer i = (Integer) uniform.getValue();
glUniform1i(loc, i.intValue());
break;
default:
throw new UnsupportedOperationException("Unsupported uniform type: " + uniform.getVarType());
}
}
protected void updateShaderUniforms(Shader shader) {
ListMap<String, Uniform> uniforms = shader.getUniformMap();
for (int i = 0; i < uniforms.size(); i++) {
Uniform uniform = uniforms.getValue(i);
if (uniform.isUpdateNeeded()) {
updateUniform(shader, uniform);
}
}
}
protected void resetUniformLocations(Shader shader) {
ListMap<String, Uniform> uniforms = shader.getUniformMap();
for (int i = 0; i < uniforms.size(); i++) {
Uniform uniform = uniforms.getValue(i);
uniform.reset(); // e.g check location again
}
}
/*
* (Non-javadoc)
* Only used for fixed-function. Ignored.
*/
public void setLighting(LightList list) {
}
public int convertShaderType(ShaderType type) {
switch (type) {
case Fragment:
return GL_FRAGMENT_SHADER;
case Vertex:
return GL_VERTEX_SHADER;
// case Geometry:
// return ARBGeometryShader4.GL_GEOMETRY_SHADER_ARB;
default:
throw new UnsupportedOperationException("Unrecognized shader type.");
}
}
public void updateShaderSourceData(ShaderSource source) {
int id = source.getId();
if (id == -1) {
// Create id
id = glCreateShader(convertShaderType(source.getType()));
if (id <= 0) {
throw new RendererException("Invalid ID received when trying to create shader.");
}
source.setId(id);
} else {
throw new RendererException("Cannot recompile shader source");
}
// Upload shader source.
// Merge the defines and source code.
String language = source.getLanguage();
stringBuf.setLength(0);
if (language.startsWith("GLSL")) {
int version = Integer.parseInt(language.substring(4));
if (version > 100) {
stringBuf.append("#version ");
stringBuf.append(language.substring(4));
if (version >= 150) {
stringBuf.append(" core");
}
stringBuf.append("\n");
} else {
// version 100 does not exist in desktop GLSL.
// put version 110 in that case to enable strict checking
stringBuf.append("#version 110\n");
}
}
updateNameBuffer();
byte[] definesCodeData = source.getDefines().getBytes();
byte[] sourceCodeData = source.getSource().getBytes();
ByteBuffer codeBuf = BufferUtils.createByteBuffer(nameBuf.limit()
+ definesCodeData.length
+ sourceCodeData.length);
codeBuf.put(nameBuf);
codeBuf.put(definesCodeData);
codeBuf.put(sourceCodeData);
codeBuf.flip();
glShaderSource(id, codeBuf);
glCompileShader(id);
glGetShader(id, GL_COMPILE_STATUS, intBuf1);
boolean compiledOK = intBuf1.get(0) == GL_TRUE;
String infoLog = null;
if (VALIDATE_SHADER || !compiledOK) {
// even if compile succeeded, check
// log for warnings
glGetShader(id, GL_INFO_LOG_LENGTH, intBuf1);
int length = intBuf1.get(0);
if (length > 3) {
// get infos
ByteBuffer logBuf = BufferUtils.createByteBuffer(length);
glGetShaderInfoLog(id, null, logBuf);
byte[] logBytes = new byte[length];
logBuf.get(logBytes, 0, length);
// convert to string, etc
infoLog = new String(logBytes);
}
}
if (compiledOK) {
if (infoLog != null) {
logger.log(Level.WARNING, "{0} compiled successfully, compiler warnings: \n{1}",
new Object[]{source.getName(), infoLog});
} else {
logger.log(Level.FINE, "{0} compiled successfully.", source.getName());
}
source.clearUpdateNeeded();
} else {
logger.log(Level.WARNING, "Bad compile of:\n{0}",
new Object[]{ShaderDebug.formatShaderSource(source.getDefines(), source.getSource(), stringBuf.toString())});
if (infoLog != null) {
throw new RendererException("compile error in: " + source + "\n" + infoLog);
} else {
throw new RendererException("compile error in: " + source + "\nerror: <not provided>");
}
}
}
public void updateShaderData(Shader shader) {
int id = shader.getId();
boolean needRegister = false;
if (id == -1) {
// create program
id = glCreateProgram();
if (id == 0) {
throw new RendererException("Invalid ID (" + id + ") received when trying to create shader program.");
}
shader.setId(id);
needRegister = true;
}
for (ShaderSource source : shader.getSources()) {
if (source.isUpdateNeeded()) {
updateShaderSourceData(source);
}
glAttachShader(id, source.getId());
}
if (ctxCaps.GL_EXT_gpu_shader4) {
// Check if GLSL version is 1.5 for shader
glBindFragDataLocationEXT(id, 0, "outFragColor");
// For MRT
for (int i = 0; i < maxMRTFBOAttachs; i++) {
glBindFragDataLocationEXT(id, i, "outFragData[" + i + "]");
}
}
// Link shaders to program
glLinkProgram(id);
// Check link status
glGetProgram(id, GL_LINK_STATUS, intBuf1);
boolean linkOK = intBuf1.get(0) == GL_TRUE;
String infoLog = null;
if (VALIDATE_SHADER || !linkOK) {
glGetProgram(id, GL_INFO_LOG_LENGTH, intBuf1);
int length = intBuf1.get(0);
if (length > 3) {
// get infos
ByteBuffer logBuf = BufferUtils.createByteBuffer(length);
glGetProgramInfoLog(id, null, logBuf);
// convert to string, etc
byte[] logBytes = new byte[length];
logBuf.get(logBytes, 0, length);
infoLog = new String(logBytes);
}
}
if (linkOK) {
if (infoLog != null) {
logger.log(Level.WARNING, "Shader linked successfully. Linker warnings: \n{0}", infoLog);
} else {
logger.fine("Shader linked successfully.");
}
shader.clearUpdateNeeded();
if (needRegister) {
// Register shader for clean up if it was created in this method.
objManager.registerObject(shader);
statistics.onNewShader();
} else {
// OpenGL spec: uniform locations may change after re-link
resetUniformLocations(shader);
}
} else {
if (infoLog != null) {
throw new RendererException("Shader failed to link, shader:" + shader + "\n" + infoLog);
} else {
throw new RendererException("Shader failed to link, shader:" + shader + "\ninfo: <not provided>");
}
}
}
public void setShader(Shader shader) {
if (shader == null) {
throw new IllegalArgumentException("Shader cannot be null");
} else {
if (shader.isUpdateNeeded()) {
updateShaderData(shader);
}
// NOTE: might want to check if any of the
// sources need an update?
assert shader.getId() > 0;
updateShaderUniforms(shader);
bindProgram(shader);
}
}
public void deleteShaderSource(ShaderSource source) {
if (source.getId() < 0) {
logger.warning("Shader source is not uploaded to GPU, cannot delete.");
return;
}
source.clearUpdateNeeded();
glDeleteShader(source.getId());
source.resetObject();
}
public void deleteShader(Shader shader) {
if (shader.getId() == -1) {
logger.warning("Shader is not uploaded to GPU, cannot delete.");
return;
}
for (ShaderSource source : shader.getSources()) {
if (source.getId() != -1) {
glDetachShader(shader.getId(), source.getId());
deleteShaderSource(source);
}
}
glDeleteProgram(shader.getId());
statistics.onDeleteShader();
shader.resetObject();
}
public void copyFrameBuffer(FrameBuffer src, FrameBuffer dst) {
copyFrameBuffer(src, dst, true);
}
public void copyFrameBuffer(FrameBuffer src, FrameBuffer dst, boolean copyDepth) {
if (ctxCaps.GL_EXT_framebuffer_blit) {
int srcX0 = 0;
int srcY0 = 0;
int srcX1;
int srcY1;
int dstX0 = 0;
int dstY0 = 0;
int dstX1;
int dstY1;
int prevFBO = context.boundFBO;
if (mainFbOverride != null) {
if (src == null) {
src = mainFbOverride;
}
if (dst == null) {
dst = mainFbOverride;
}
}
if (src != null && src.isUpdateNeeded()) {
updateFrameBuffer(src);
}
if (dst != null && dst.isUpdateNeeded()) {
updateFrameBuffer(dst);
}
if (src == null) {
glBindFramebufferEXT(GL_READ_FRAMEBUFFER_EXT, 0);
srcX0 = vpX;
srcY0 = vpY;
srcX1 = vpX + vpW;
srcY1 = vpY + vpH;
} else {
glBindFramebufferEXT(GL_READ_FRAMEBUFFER_EXT, src.getId());
srcX1 = src.getWidth();
srcY1 = src.getHeight();
}
if (dst == null) {
glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER_EXT, 0);
dstX0 = vpX;
dstY0 = vpY;
dstX1 = vpX + vpW;
dstY1 = vpY + vpH;
} else {
glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER_EXT, dst.getId());
dstX1 = dst.getWidth();
dstY1 = dst.getHeight();
}
int mask = GL_COLOR_BUFFER_BIT;
if (copyDepth) {
mask |= GL_DEPTH_BUFFER_BIT;
}
glBlitFramebufferEXT(srcX0, srcY0, srcX1, srcY1,
dstX0, dstY0, dstX1, dstY1, mask,
GL_NEAREST);
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, prevFBO);
try {
checkFrameBufferError();
} catch (IllegalStateException ex) {
logger.log(Level.SEVERE, "Source FBO:\n{0}", src);
logger.log(Level.SEVERE, "Dest FBO:\n{0}", dst);
throw ex;
}
} else {
throw new RendererException("EXT_framebuffer_blit required.");
// TODO: support non-blit copies?
}
}
private String getTargetBufferName(int buffer) {
switch (buffer) {
case GL_NONE:
return "NONE";
case GL_FRONT:
return "GL_FRONT";
case GL_BACK:
return "GL_BACK";
default:
if (buffer >= GL_COLOR_ATTACHMENT0_EXT
&& buffer <= GL_COLOR_ATTACHMENT15_EXT) {
return "GL_COLOR_ATTACHMENT"
+ (buffer - GL_COLOR_ATTACHMENT0_EXT);
} else {
return "UNKNOWN? " + buffer;
}
}
}
private void printRealRenderBufferInfo(FrameBuffer fb, RenderBuffer rb, String name) {
System.out.println("== Renderbuffer " + name + " ==");
System.out.println("RB ID: " + rb.getId());
System.out.println("Is proper? " + glIsRenderbufferEXT(rb.getId()));
int attachment = convertAttachmentSlot(rb.getSlot());
int type = glGetFramebufferAttachmentParameterEXT(GL_DRAW_FRAMEBUFFER_EXT,
attachment,
GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE_EXT);
int rbName = glGetFramebufferAttachmentParameterEXT(GL_DRAW_FRAMEBUFFER_EXT,
attachment,
GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME_EXT);
switch (type) {
case GL_NONE:
System.out.println("Type: None");
break;
case GL_TEXTURE:
System.out.println("Type: Texture");
break;
case GL_RENDERBUFFER_EXT:
System.out.println("Type: Buffer");
System.out.println("RB ID: " + rbName);
break;
}
}
private void printRealFrameBufferInfo(FrameBuffer fb) {
boolean doubleBuffer = glGetBoolean(GL_DOUBLEBUFFER);
String drawBuf = getTargetBufferName(glGetInteger(GL_DRAW_BUFFER));
String readBuf = getTargetBufferName(glGetInteger(GL_READ_BUFFER));
int fbId = fb.getId();
int curDrawBinding = glGetInteger(GL_DRAW_FRAMEBUFFER_BINDING_EXT);
int curReadBinding = glGetInteger(GL_READ_FRAMEBUFFER_BINDING_EXT);
System.out.println("=== OpenGL FBO State ===");
System.out.println("Context doublebuffered? " + doubleBuffer);
System.out.println("FBO ID: " + fbId);
System.out.println("Is proper? " + glIsFramebufferEXT(fbId));
System.out.println("Is bound to draw? " + (fbId == curDrawBinding));
System.out.println("Is bound to read? " + (fbId == curReadBinding));
System.out.println("Draw buffer: " + drawBuf);
System.out.println("Read buffer: " + readBuf);
if (context.boundFBO != fbId) {
glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER_EXT, fbId);
context.boundFBO = fbId;
}
if (fb.getDepthBuffer() != null) {
printRealRenderBufferInfo(fb, fb.getDepthBuffer(), "Depth");
}
for (int i = 0; i < fb.getNumColorBuffers(); i++) {
printRealRenderBufferInfo(fb, fb.getColorBuffer(i), "Color" + i);
}
}
private void checkFrameBufferError() {
int status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
switch (status) {
case GL_FRAMEBUFFER_COMPLETE_EXT:
break;
case GL_FRAMEBUFFER_UNSUPPORTED_EXT:
//Choose different formats
throw new IllegalStateException("Framebuffer object format is "
+ "unsupported by the video hardware.");
case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_EXT:
throw new IllegalStateException("Framebuffer has erronous attachment.");
case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_EXT:
throw new IllegalStateException("Framebuffer doesn't have any renderbuffers attached.");
case GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_EXT:
throw new IllegalStateException("Framebuffer attachments must have same dimensions.");
case GL_FRAMEBUFFER_INCOMPLETE_FORMATS_EXT:
throw new IllegalStateException("Framebuffer attachments must have same formats.");
case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER_EXT:
throw new IllegalStateException("Incomplete draw buffer.");
case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER_EXT:
throw new IllegalStateException("Incomplete read buffer.");
case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_EXT:
throw new IllegalStateException("Incomplete multisample buffer.");
default:
//Programming error; will fail on all hardware
throw new IllegalStateException("Some video driver error "
+ "or programming error occured. "
+ "Framebuffer object status is invalid. ");
}
}
private void updateRenderBuffer(FrameBuffer fb, RenderBuffer rb) {
int id = rb.getId();
if (id == -1) {
glGenRenderbuffersEXT(intBuf1);
id = intBuf1.get(0);
rb.setId(id);
}
if (context.boundRB != id) {
glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, id);
context.boundRB = id;
}
if (fb.getWidth() > maxRBSize || fb.getHeight() > maxRBSize) {
throw new RendererException("Resolution " + fb.getWidth()
+ ":" + fb.getHeight() + " is not supported.");
}
TextureUtil.GLImageFormat glFmt = TextureUtil.getImageFormatWithError(ctxCaps, rb.getFormat(), fb.isSrgb());
if (fb.getSamples() > 1 && ctxCaps.GL_EXT_framebuffer_multisample) {
int samples = fb.getSamples();
if (maxFBOSamples < samples) {
samples = maxFBOSamples;
}
glRenderbufferStorageMultisampleEXT(GL_RENDERBUFFER_EXT,
samples,
glFmt.internalFormat,
fb.getWidth(),
fb.getHeight());
} else {
glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT,
glFmt.internalFormat,
fb.getWidth(),
fb.getHeight());
}
}
private int convertAttachmentSlot(int attachmentSlot) {
// can also add support for stencil here
if (attachmentSlot == -100) {
return GL_DEPTH_ATTACHMENT_EXT;
} else if (attachmentSlot < 0 || attachmentSlot >= 16) {
throw new UnsupportedOperationException("Invalid FBO attachment slot: " + attachmentSlot);
}
return GL_COLOR_ATTACHMENT0_EXT + attachmentSlot;
}
public void updateRenderTexture(FrameBuffer fb, RenderBuffer rb) {
Texture tex = rb.getTexture();
Image image = tex.getImage();
if (image.isUpdateNeeded()) {
updateTexImageData(image, tex.getType(), 0);
// NOTE: For depth textures, sets nearest/no-mips mode
// Required to fix "framebuffer unsupported"
// for old NVIDIA drivers!
setupTextureParams(tex);
}
glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT,
convertAttachmentSlot(rb.getSlot()),
convertTextureType(tex.getType(), image.getMultiSamples(), rb.getFace()),
image.getId(),
0);
}
public void updateFrameBufferAttachment(FrameBuffer fb, RenderBuffer rb) {
boolean needAttach;
if (rb.getTexture() == null) {
// if it hasn't been created yet, then attach is required.
needAttach = rb.getId() == -1;
updateRenderBuffer(fb, rb);
} else {
needAttach = false;
updateRenderTexture(fb, rb);
}
if (needAttach) {
glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT,
convertAttachmentSlot(rb.getSlot()),
GL_RENDERBUFFER_EXT,
rb.getId());
}
}
public void updateFrameBuffer(FrameBuffer fb) {
int id = fb.getId();
if (id == -1) {
// create FBO
glGenFramebuffersEXT(intBuf1);
id = intBuf1.get(0);
fb.setId(id);
objManager.registerObject(fb);
statistics.onNewFrameBuffer();
}
if (context.boundFBO != id) {
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, id);
// binding an FBO automatically sets draw buf to GL_COLOR_ATTACHMENT0
context.boundDrawBuf = 0;
context.boundFBO = id;
}
FrameBuffer.RenderBuffer depthBuf = fb.getDepthBuffer();
if (depthBuf != null) {
updateFrameBufferAttachment(fb, depthBuf);
}
for (int i = 0; i < fb.getNumColorBuffers(); i++) {
FrameBuffer.RenderBuffer colorBuf = fb.getColorBuffer(i);
updateFrameBufferAttachment(fb, colorBuf);
}
fb.clearUpdateNeeded();
}
public Vector2f[] getFrameBufferSamplePositions(FrameBuffer fb) {
if (fb.getSamples() <= 1) {
throw new IllegalArgumentException("Framebuffer must be multisampled");
}
if (!ctxCaps.GL_ARB_texture_multisample) {
throw new RendererException("Multisampled textures are not supported");
}
setFrameBuffer(fb);
Vector2f[] samplePositions = new Vector2f[fb.getSamples()];
FloatBuffer samplePos = BufferUtils.createFloatBuffer(2);
for (int i = 0; i < samplePositions.length; i++) {
glGetMultisample(GL_SAMPLE_POSITION, i, samplePos);
samplePos.clear();
samplePositions[i] = new Vector2f(samplePos.get(0) - 0.5f,
samplePos.get(1) - 0.5f);
}
return samplePositions;
}
public void setMainFrameBufferOverride(FrameBuffer fb) {
mainFbOverride = fb;
}
public void setFrameBuffer(FrameBuffer fb) {
if (!ctxCaps.GL_EXT_framebuffer_object) {
throw new RendererException("Framebuffer objects are not supported" +
" by the video hardware");
}
if (fb == null && mainFbOverride != null) {
fb = mainFbOverride;
}
if (context.boundFB == fb) {
if (fb == null || !fb.isUpdateNeeded()) {
return;
}
}
// generate mipmaps for last FB if needed
if (context.boundFB != null) {
for (int i = 0; i < context.boundFB.getNumColorBuffers(); i++) {
RenderBuffer rb = context.boundFB.getColorBuffer(i);
Texture tex = rb.getTexture();
if (tex != null
&& tex.getMinFilter().usesMipMapLevels()) {
setTexture(0, rb.getTexture());
int textureType = convertTextureType(tex.getType(), tex.getImage().getMultiSamples(), rb.getFace());
glEnable(textureType);
glGenerateMipmapEXT(textureType);
glDisable(textureType);
}
}
}
if (fb == null) {
// unbind any fbos
if (context.boundFBO != 0) {
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
statistics.onFrameBufferUse(null, true);
context.boundFBO = 0;
}
// select back buffer
if (context.boundDrawBuf != -1) {
glDrawBuffer(context.initialDrawBuf);
context.boundDrawBuf = -1;
}
if (context.boundReadBuf != -1) {
glReadBuffer(context.initialReadBuf);
context.boundReadBuf = -1;
}
context.boundFB = null;
} else {
if (fb.getNumColorBuffers() == 0 && fb.getDepthBuffer() == null) {
throw new IllegalArgumentException("The framebuffer: " + fb
+ "\nDoesn't have any color/depth buffers");
}
if (fb.isUpdateNeeded()) {
updateFrameBuffer(fb);
}
if (context.boundFBO != fb.getId()) {
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fb.getId());
statistics.onFrameBufferUse(fb, true);
// update viewport to reflect framebuffer's resolution
setViewPort(0, 0, fb.getWidth(), fb.getHeight());
context.boundFBO = fb.getId();
} else {
statistics.onFrameBufferUse(fb, false);
}
if (fb.getNumColorBuffers() == 0) {
// make sure to select NONE as draw buf
// no color buffer attached. select NONE
if (context.boundDrawBuf != -2) {
glDrawBuffer(GL_NONE);
context.boundDrawBuf = -2;
}
if (context.boundReadBuf != -2) {
glReadBuffer(GL_NONE);
context.boundReadBuf = -2;
}
} else {
if (fb.getNumColorBuffers() > maxFBOAttachs) {
throw new RendererException("Framebuffer has more color "
+ "attachments than are supported"
+ " by the video hardware!");
}
if (fb.isMultiTarget()) {
if (fb.getNumColorBuffers() > maxMRTFBOAttachs) {
throw new RendererException("Framebuffer has more"
+ " multi targets than are supported"
+ " by the video hardware!");
}
if (context.boundDrawBuf != 100 + fb.getNumColorBuffers()) {
intBuf16.clear();
for (int i = 0; i < fb.getNumColorBuffers(); i++) {
intBuf16.put(GL_COLOR_ATTACHMENT0_EXT + i);
}
intBuf16.flip();
glDrawBuffers(intBuf16);
context.boundDrawBuf = 100 + fb.getNumColorBuffers();
}
} else {
RenderBuffer rb = fb.getColorBuffer(fb.getTargetIndex());
// select this draw buffer
if (context.boundDrawBuf != rb.getSlot()) {
glDrawBuffer(GL_COLOR_ATTACHMENT0_EXT + rb.getSlot());
context.boundDrawBuf = rb.getSlot();
}
}
}
assert fb.getId() >= 0;
assert context.boundFBO == fb.getId();
context.boundFB = fb;
try {
checkFrameBufferError();
} catch (IllegalStateException ex) {
logger.log(Level.SEVERE, "=== jMonkeyEngine FBO State ===\n{0}", fb);
printRealFrameBufferInfo(fb);
throw ex;
}
}
}
public void readFrameBuffer(FrameBuffer fb, ByteBuffer byteBuf) {
if (fb != null) {
RenderBuffer rb = fb.getColorBuffer();
if (rb == null) {
throw new IllegalArgumentException("Specified framebuffer"
+ " does not have a colorbuffer");
}
setFrameBuffer(fb);
if (context.boundReadBuf != rb.getSlot()) {
glReadBuffer(GL_COLOR_ATTACHMENT0_EXT + rb.getSlot());
context.boundReadBuf = rb.getSlot();
}
} else {
setFrameBuffer(null);
}
glReadPixels(vpX, vpY, vpW, vpH, /*GL_RGBA*/ GL_BGRA, GL_UNSIGNED_BYTE, byteBuf);
}
private void deleteRenderBuffer(FrameBuffer fb, RenderBuffer rb) {
intBuf1.put(0, rb.getId());
glDeleteRenderbuffersEXT(intBuf1);
}
public void deleteFrameBuffer(FrameBuffer fb) {
if (fb.getId() != -1) {
if (context.boundFBO == fb.getId()) {
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
context.boundFBO = 0;
}
if (fb.getDepthBuffer() != null) {
deleteRenderBuffer(fb, fb.getDepthBuffer());
}
if (fb.getColorBuffer() != null) {
deleteRenderBuffer(fb, fb.getColorBuffer());
}
intBuf1.put(0, fb.getId());
glDeleteFramebuffersEXT(intBuf1);
fb.resetObject();
statistics.onDeleteFrameBuffer();
}
}
private int convertTextureType(Texture.Type type, int samples, int face) {
if (samples > 1 && !ctxCaps.GL_ARB_texture_multisample) {
throw new RendererException("Multisample textures are not supported" +
" by the video hardware.");
}
switch (type) {
case TwoDimensional:
if (samples > 1) {
return GL_TEXTURE_2D_MULTISAMPLE;
} else {
return GL_TEXTURE_2D;
}
case TwoDimensionalArray:
if (samples > 1) {
return GL_TEXTURE_2D_MULTISAMPLE_ARRAY;
} else {
return GL_TEXTURE_2D_ARRAY_EXT;
}
case ThreeDimensional:
return GL_TEXTURE_3D;
case CubeMap:
if (face < 0) {
return GL_TEXTURE_CUBE_MAP;
} else if (face < 6) {
return GL_TEXTURE_CUBE_MAP_POSITIVE_X + face;
} else {
throw new UnsupportedOperationException("Invalid cube map face index: " + face);
}
default:
throw new UnsupportedOperationException("Unknown texture type: " + type);
}
}
private int convertMagFilter(Texture.MagFilter filter) {
switch (filter) {
case Bilinear:
return GL_LINEAR;
case Nearest:
return GL_NEAREST;
default:
throw new UnsupportedOperationException("Unknown mag filter: " + filter);
}
}
private int convertMinFilter(Texture.MinFilter filter) {
switch (filter) {
case Trilinear:
return GL_LINEAR_MIPMAP_LINEAR;
case BilinearNearestMipMap:
return GL_LINEAR_MIPMAP_NEAREST;
case NearestLinearMipMap:
return GL_NEAREST_MIPMAP_LINEAR;
case NearestNearestMipMap:
return GL_NEAREST_MIPMAP_NEAREST;
case BilinearNoMipMaps:
return GL_LINEAR;
case NearestNoMipMaps:
return GL_NEAREST;
default:
throw new UnsupportedOperationException("Unknown min filter: " + filter);
}
}
private int convertWrapMode(Texture.WrapMode mode) {
switch (mode) {
case BorderClamp:
return GL_CLAMP_TO_BORDER;
case Clamp:
// Falldown intentional.
case EdgeClamp:
return GL_CLAMP_TO_EDGE;
case Repeat:
return GL_REPEAT;
case MirroredRepeat:
return GL_MIRRORED_REPEAT;
default:
throw new UnsupportedOperationException("Unknown wrap mode: " + mode);
}
}
@SuppressWarnings("fallthrough")
private void setupTextureParams(Texture tex) {
Image image = tex.getImage();
int target = convertTextureType(tex.getType(), image != null ? image.getMultiSamples() : 1, -1);
// filter things
int minFilter = convertMinFilter(tex.getMinFilter());
int magFilter = convertMagFilter(tex.getMagFilter());
glTexParameteri(target, GL_TEXTURE_MIN_FILTER, minFilter);
glTexParameteri(target, GL_TEXTURE_MAG_FILTER, magFilter);
if (tex.getAnisotropicFilter() > 1) {
if (ctxCaps.GL_EXT_texture_filter_anisotropic) {
glTexParameterf(target,
GL_TEXTURE_MAX_ANISOTROPY_EXT,
tex.getAnisotropicFilter());
}
}
if (context.pointSprite) {
return; // Attempt to fix glTexParameter crash for some ATI GPUs
}
// repeat modes
switch (tex.getType()) {
case ThreeDimensional:
case CubeMap: // cubemaps use 3D coords
glTexParameteri(target, GL_TEXTURE_WRAP_R, convertWrapMode(tex.getWrap(WrapAxis.R)));
//There is no break statement on purpose here
case TwoDimensional:
case TwoDimensionalArray:
glTexParameteri(target, GL_TEXTURE_WRAP_T, convertWrapMode(tex.getWrap(WrapAxis.T)));
// fall down here is intentional..
// case OneDimensional:
glTexParameteri(target, GL_TEXTURE_WRAP_S, convertWrapMode(tex.getWrap(WrapAxis.S)));
break;
default:
throw new UnsupportedOperationException("Unknown texture type: " + tex.getType());
}
if(tex.isNeedCompareModeUpdate()){
// R to Texture compare mode
if (tex.getShadowCompareMode() != Texture.ShadowCompareMode.Off) {
glTexParameteri(target, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_R_TO_TEXTURE);
glTexParameteri(target, GL_DEPTH_TEXTURE_MODE, GL_INTENSITY);
if (tex.getShadowCompareMode() == Texture.ShadowCompareMode.GreaterOrEqual) {
glTexParameteri(target, GL_TEXTURE_COMPARE_FUNC, GL_GEQUAL);
} else {
glTexParameteri(target, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL);
}
}else{
//restoring default value
glTexParameteri(target, GL_TEXTURE_COMPARE_MODE, GL_NONE);
}
tex.compareModeUpdated();
}
}
/**
* Uploads the given image to the GL driver.
*
* @param img The image to upload
* @param type How the data in the image argument should be interpreted.
* @param unit The texture slot to be used to upload the image, not important
*/
public void updateTexImageData(Image img, Texture.Type type, int unit) {
int texId = img.getId();
if (texId == -1) {
// create texture
glGenTextures(intBuf1);
texId = intBuf1.get(0);
img.setId(texId);
objManager.registerObject(img);
statistics.onNewTexture();
}
// bind texture
int target = convertTextureType(type, img.getMultiSamples(), -1);
if (context.boundTextureUnit != unit) {
glActiveTexture(GL_TEXTURE0 + unit);
context.boundTextureUnit = unit;
}
if (context.boundTextures[unit] != img) {
glBindTexture(target, texId);
context.boundTextures[unit] = img;
statistics.onTextureUse(img, true);
}
if (!img.hasMipmaps() && img.isGeneratedMipmapsRequired()) {
// Image does not have mipmaps, but they are required.
// Generate from base level.
if (!ctxCaps.OpenGL30) {
glTexParameteri(target, GL_GENERATE_MIPMAP, GL_TRUE);
img.setMipmapsGenerated(true);
} else {
// For OpenGL3 and up.
// We'll generate mipmaps via glGenerateMipmapEXT (see below)
}
} else if (img.hasMipmaps()) {
// Image already has mipmaps, set the max level based on the
// number of mipmaps we have.
glTexParameteri(target, GL_TEXTURE_MAX_LEVEL, img.getMipMapSizes().length - 1);
} else {
// Image does not have mipmaps and they are not required.
// Specify that that the texture has no mipmaps.
glTexParameteri(target, GL_TEXTURE_MAX_LEVEL, 0);
}
int imageSamples = img.getMultiSamples();
if (imageSamples > 1) {
if (img.getFormat().isDepthFormat()) {
img.setMultiSamples(Math.min(maxDepthTexSamples, imageSamples));
} else {
img.setMultiSamples(Math.min(maxColorTexSamples, imageSamples));
}
}
// Yes, some OpenGL2 cards (GeForce 5) still dont support NPOT.
if (!ctxCaps.GL_ARB_texture_non_power_of_two && img.isNPOT()) {
if (img.getData(0) == null) {
throw new RendererException("non-power-of-2 framebuffer textures are not supported by the video hardware");
} else {
MipMapGenerator.resizeToPowerOf2(img);
}
}
// Check if graphics card doesn't support multisample textures
if (!ctxCaps.GL_ARB_texture_multisample) {
if (img.getMultiSamples() > 1) {
throw new RendererException("Multisample textures not supported by graphics hardware");
}
}
if (target == GL_TEXTURE_CUBE_MAP) {
// Check max texture size before upload
if (img.getWidth() > maxCubeTexSize || img.getHeight() > maxCubeTexSize) {
throw new RendererException("Cannot upload cubemap " + img + ". The maximum supported cubemap resolution is " + maxCubeTexSize);
}
} else {
if (img.getWidth() > maxTexSize || img.getHeight() > maxTexSize) {
throw new RendererException("Cannot upload texture " + img + ". The maximum supported texture resolution is " + maxTexSize);
}
}
if (target == GL_TEXTURE_CUBE_MAP) {
List<ByteBuffer> data = img.getData();
if (data.size() != 6) {
logger.log(Level.WARNING, "Invalid texture: {0}\n"
+ "Cubemap textures must contain 6 data units.", img);
return;
}
for (int i = 0; i < 6; i++) {
TextureUtil.uploadTexture(ctxCaps, img, GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, i, 0, linearizeSrgbImages);
}
} else if (target == GL_TEXTURE_2D_ARRAY_EXT) {
if (!caps.contains(Caps.TextureArray)) {
throw new RendererException("Texture arrays not supported by graphics hardware");
}
List<ByteBuffer> data = img.getData();
// -1 index specifies prepare data for 2D Array
TextureUtil.uploadTexture(ctxCaps, img, target, -1, 0, linearizeSrgbImages);
for (int i = 0; i < data.size(); i++) {
// upload each slice of 2D array in turn
// this time with the appropriate index
TextureUtil.uploadTexture(ctxCaps, img, target, i, 0, linearizeSrgbImages);
}
} else {
TextureUtil.uploadTexture(ctxCaps, img, target, 0, 0, linearizeSrgbImages);
}
if (img.getMultiSamples() != imageSamples) {
img.setMultiSamples(imageSamples);
}
if (ctxCaps.OpenGL30) {
if (!img.hasMipmaps() && img.isGeneratedMipmapsRequired() && img.getData() != null) {
// XXX: Required for ATI
glEnable(target);
glGenerateMipmapEXT(target);
glDisable(target);
img.setMipmapsGenerated(true);
}
}
img.clearUpdateNeeded();
}
public void setTexture(int unit, Texture tex) {
Image image = tex.getImage();
if (image.isUpdateNeeded() || (image.isGeneratedMipmapsRequired() && !image.isMipmapsGenerated())) {
updateTexImageData(image, tex.getType(), unit);
}
int texId = image.getId();
assert texId != -1;
Image[] textures = context.boundTextures;
int type = convertTextureType(tex.getType(), image.getMultiSamples(), -1);
// if (!context.textureIndexList.moveToNew(unit)) {
// if (context.boundTextureUnit != unit){
// glActiveTexture(GL_TEXTURE0 + unit);
// context.boundTextureUnit = unit;
// glEnable(type);
if (context.boundTextureUnit != unit) {
glActiveTexture(GL_TEXTURE0 + unit);
context.boundTextureUnit = unit;
}
if (textures[unit] != image) {
glBindTexture(type, texId);
textures[unit] = image;
statistics.onTextureUse(image, true);
} else {
statistics.onTextureUse(image, false);
}
setupTextureParams(tex);
}
public void modifyTexture(Texture tex, Image pixels, int x, int y) {
setTexture(0, tex);
TextureUtil.uploadSubTexture(ctxCaps, pixels, convertTextureType(tex.getType(), pixels.getMultiSamples(), -1), 0, x, y, linearizeSrgbImages);
}
public void clearTextureUnits() {
// IDList textureList = context.textureIndexList;
// Image[] textures = context.boundTextures;
// for (int i = 0; i < textureList.oldLen; i++) {
// int idx = textureList.oldList[i];
// if (context.boundTextureUnit != idx){
// glActiveTexture(GL_TEXTURE0 + idx);
// context.boundTextureUnit = idx;
// glDisable(convertTextureType(textures[idx].getType()));
// textures[idx] = null;
// context.textureIndexList.copyNewToOld();
}
public void deleteImage(Image image) {
int texId = image.getId();
if (texId != -1) {
intBuf1.put(0, texId);
intBuf1.position(0).limit(1);
glDeleteTextures(intBuf1);
image.resetObject();
statistics.onDeleteTexture();
}
}
private int convertUsage(Usage usage) {
switch (usage) {
case Static:
return GL_STATIC_DRAW;
case Dynamic:
return GL_DYNAMIC_DRAW;
case Stream:
return GL_STREAM_DRAW;
default:
throw new UnsupportedOperationException("Unknown usage type.");
}
}
private int convertFormat(Format format) {
switch (format) {
case Byte:
return GL_BYTE;
case UnsignedByte:
return GL_UNSIGNED_BYTE;
case Short:
return GL_SHORT;
case UnsignedShort:
return GL_UNSIGNED_SHORT;
case Int:
return GL_INT;
case UnsignedInt:
return GL_UNSIGNED_INT;
case Float:
return GL_FLOAT;
case Double:
return GL_DOUBLE;
default:
throw new UnsupportedOperationException("Unknown buffer format.");
}
}
public void updateBufferData(VertexBuffer vb) {
int bufId = vb.getId();
boolean created = false;
if (bufId == -1) {
// create buffer
glGenBuffers(intBuf1);
bufId = intBuf1.get(0);
vb.setId(bufId);
objManager.registerObject(vb);
//statistics.onNewVertexBuffer();
created = true;
}
// bind buffer
int target;
if (vb.getBufferType() == VertexBuffer.Type.Index) {
target = GL_ELEMENT_ARRAY_BUFFER;
if (context.boundElementArrayVBO != bufId) {
glBindBuffer(target, bufId);
context.boundElementArrayVBO = bufId;
//statistics.onVertexBufferUse(vb, true);
} else {
//statistics.onVertexBufferUse(vb, false);
}
} else {
target = GL_ARRAY_BUFFER;
if (context.boundArrayVBO != bufId) {
glBindBuffer(target, bufId);
context.boundArrayVBO = bufId;
//statistics.onVertexBufferUse(vb, true);
} else {
//statistics.onVertexBufferUse(vb, false);
}
}
int usage = convertUsage(vb.getUsage());
vb.getData().rewind();
if (created || vb.hasDataSizeChanged()) {
// upload data based on format
switch (vb.getFormat()) {
case Byte:
case UnsignedByte:
glBufferData(target, (ByteBuffer) vb.getData(), usage);
break;
// case Half:
case Short:
case UnsignedShort:
glBufferData(target, (ShortBuffer) vb.getData(), usage);
break;
case Int:
case UnsignedInt:
glBufferData(target, (IntBuffer) vb.getData(), usage);
break;
case Float:
glBufferData(target, (FloatBuffer) vb.getData(), usage);
break;
case Double:
glBufferData(target, (DoubleBuffer) vb.getData(), usage);
break;
default:
throw new UnsupportedOperationException("Unknown buffer format.");
}
} else {
switch (vb.getFormat()) {
case Byte:
case UnsignedByte:
glBufferSubData(target, 0, (ByteBuffer) vb.getData());
break;
case Short:
case UnsignedShort:
glBufferSubData(target, 0, (ShortBuffer) vb.getData());
break;
case Int:
case UnsignedInt:
glBufferSubData(target, 0, (IntBuffer) vb.getData());
break;
case Float:
glBufferSubData(target, 0, (FloatBuffer) vb.getData());
break;
case Double:
glBufferSubData(target, 0, (DoubleBuffer) vb.getData());
break;
default:
throw new UnsupportedOperationException("Unknown buffer format.");
}
}
vb.clearUpdateNeeded();
}
public void deleteBuffer(VertexBuffer vb) {
int bufId = vb.getId();
if (bufId != -1) {
// delete buffer
intBuf1.put(0, bufId);
intBuf1.position(0).limit(1);
glDeleteBuffers(intBuf1);
vb.resetObject();
//statistics.onDeleteVertexBuffer();
}
}
public void clearVertexAttribs() {
IDList attribList = context.attribIndexList;
for (int i = 0; i < attribList.oldLen; i++) {
int idx = attribList.oldList[i];
glDisableVertexAttribArray(idx);
if (context.boundAttribs[idx].isInstanced()) {
glVertexAttribDivisorARB(idx, 0);
}
context.boundAttribs[idx] = null;
}
context.attribIndexList.copyNewToOld();
}
public void setVertexAttrib(VertexBuffer vb, VertexBuffer idb) {
if (vb.getBufferType() == VertexBuffer.Type.Index) {
throw new IllegalArgumentException("Index buffers not allowed to be set to vertex attrib");
}
int programId = context.boundShaderProgram;
if (programId > 0) {
Attribute attrib = context.boundShader.getAttribute(vb.getBufferType());
int loc = attrib.getLocation();
if (loc == -1) {
return; // not defined
}
if (loc == -2) {
stringBuf.setLength(0);
stringBuf.append("in").append(vb.getBufferType().name()).append('\0');
updateNameBuffer();
loc = glGetAttribLocation(programId, nameBuf);
// not really the name of it in the shader (inPosition\0) but
// the internal name of the enum (Position).
if (loc < 0) {
attrib.setLocation(-1);
return; // not available in shader.
} else {
attrib.setLocation(loc);
}
}
if (vb.isInstanced()) {
if (!ctxCaps.GL_ARB_instanced_arrays
|| !ctxCaps.GL_ARB_draw_instanced) {
throw new RendererException("Instancing is required, "
+ "but not supported by the "
+ "graphics hardware");
}
}
int slotsRequired = 1;
if (vb.getNumComponents() > 4) {
if (vb.getNumComponents() % 4 != 0) {
throw new RendererException("Number of components in multi-slot "
+ "buffers must be divisible by 4");
}
slotsRequired = vb.getNumComponents() / 4;
}
if (vb.isUpdateNeeded() && idb == null) {
updateBufferData(vb);
}
VertexBuffer[] attribs = context.boundAttribs;
for (int i = 0; i < slotsRequired; i++) {
if (!context.attribIndexList.moveToNew(loc + i)) {
glEnableVertexAttribArray(loc + i);
//System.out.println("Enabled ATTRIB IDX: "+loc);
}
}
if (attribs[loc] != vb) {
// NOTE: Use id from interleaved buffer if specified
int bufId = idb != null ? idb.getId() : vb.getId();
assert bufId != -1;
if (context.boundArrayVBO != bufId) {
glBindBuffer(GL_ARRAY_BUFFER, bufId);
context.boundArrayVBO = bufId;
//statistics.onVertexBufferUse(vb, true);
} else {
//statistics.onVertexBufferUse(vb, false);
}
if (slotsRequired == 1) {
glVertexAttribPointer(loc,
vb.getNumComponents(),
convertFormat(vb.getFormat()),
vb.isNormalized(),
vb.getStride(),
vb.getOffset());
} else {
for (int i = 0; i < slotsRequired; i++) {
// The pointer maps the next 4 floats in the slot.
// stride = 4 bytes in float * 4 floats in slot * num slots
// offset = 4 bytes in float * 4 floats in slot * slot index
glVertexAttribPointer(loc + i,
4,
convertFormat(vb.getFormat()),
vb.isNormalized(),
4 * 4 * slotsRequired,
4 * 4 * i);
}
}
for (int i = 0; i < slotsRequired; i++) {
int slot = loc + i;
if (vb.isInstanced() && (attribs[slot] == null || !attribs[slot].isInstanced())) {
// non-instanced -> instanced
glVertexAttribDivisorARB(slot, vb.getInstanceSpan());
} else if (!vb.isInstanced() && attribs[slot] != null && attribs[slot].isInstanced()) {
// instanced -> non-instanced
glVertexAttribDivisorARB(slot, 0);
}
attribs[slot] = vb;
}
}
} else {
throw new IllegalStateException("Cannot render mesh without shader bound");
}
}
public void setVertexAttrib(VertexBuffer vb) {
setVertexAttrib(vb, null);
}
public void drawTriangleArray(Mesh.Mode mode, int count, int vertCount) {
boolean useInstancing = count > 1 && caps.contains(Caps.MeshInstancing);
if (useInstancing) {
glDrawArraysInstancedARB(convertElementMode(mode), 0,
vertCount, count);
} else {
glDrawArrays(convertElementMode(mode), 0, vertCount);
}
}
public void drawTriangleList(VertexBuffer indexBuf, Mesh mesh, int count) {
if (indexBuf.getBufferType() != VertexBuffer.Type.Index) {
throw new IllegalArgumentException("Only index buffers are allowed as triangle lists.");
}
if (indexBuf.isUpdateNeeded()) {
updateBufferData(indexBuf);
}
int bufId = indexBuf.getId();
assert bufId != -1;
if (context.boundElementArrayVBO != bufId) {
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bufId);
context.boundElementArrayVBO = bufId;
//statistics.onVertexBufferUse(indexBuf, true);
} else {
//statistics.onVertexBufferUse(indexBuf, true);
}
int vertCount = mesh.getVertexCount();
boolean useInstancing = count > 1 && caps.contains(Caps.MeshInstancing);
if (mesh.getMode() == Mode.Hybrid) {
int[] modeStart = mesh.getModeStart();
int[] elementLengths = mesh.getElementLengths();
int elMode = convertElementMode(Mode.Triangles);
int fmt = convertFormat(indexBuf.getFormat());
int elSize = indexBuf.getFormat().getComponentSize();
int listStart = modeStart[0];
int stripStart = modeStart[1];
int fanStart = modeStart[2];
int curOffset = 0;
for (int i = 0; i < elementLengths.length; i++) {
if (i == stripStart) {
elMode = convertElementMode(Mode.TriangleStrip);
} else if (i == fanStart) {
elMode = convertElementMode(Mode.TriangleFan);
}
int elementLength = elementLengths[i];
if (useInstancing) {
glDrawElementsInstancedARB(elMode,
elementLength,
fmt,
curOffset,
count);
} else {
glDrawRangeElements(elMode,
0,
vertCount,
elementLength,
fmt,
curOffset);
}
curOffset += elementLength * elSize;
}
} else {
if (useInstancing) {
glDrawElementsInstancedARB(convertElementMode(mesh.getMode()),
indexBuf.getData().limit(),
convertFormat(indexBuf.getFormat()),
0,
count);
} else {
glDrawRangeElements(convertElementMode(mesh.getMode()),
0,
vertCount,
indexBuf.getData().limit(),
convertFormat(indexBuf.getFormat()),
0);
}
}
}
public int convertElementMode(Mesh.Mode mode) {
switch (mode) {
case Points:
return GL_POINTS;
case Lines:
return GL_LINES;
case LineLoop:
return GL_LINE_LOOP;
case LineStrip:
return GL_LINE_STRIP;
case Triangles:
return GL_TRIANGLES;
case TriangleFan:
return GL_TRIANGLE_FAN;
case TriangleStrip:
return GL_TRIANGLE_STRIP;
default:
throw new UnsupportedOperationException("Unrecognized mesh mode: " + mode);
}
}
public void updateVertexArray(Mesh mesh, VertexBuffer instanceData) {
int id = mesh.getId();
if (id == -1) {
IntBuffer temp = intBuf1;
glGenVertexArrays(temp);
id = temp.get(0);
mesh.setId(id);
}
if (context.boundVertexArray != id) {
glBindVertexArray(id);
context.boundVertexArray = id;
}
VertexBuffer interleavedData = mesh.getBuffer(Type.InterleavedData);
if (interleavedData != null && interleavedData.isUpdateNeeded()) {
updateBufferData(interleavedData);
}
if (instanceData != null) {
setVertexAttrib(instanceData, null);
}
for (VertexBuffer vb : mesh.getBufferList().getArray()) {
if (vb.getBufferType() == Type.InterleavedData
|| vb.getUsage() == Usage.CpuOnly // ignore cpu-only buffers
|| vb.getBufferType() == Type.Index) {
continue;
}
if (vb.getStride() == 0) {
// not interleaved
setVertexAttrib(vb);
} else {
// interleaved
setVertexAttrib(vb, interleavedData);
}
}
}
private void renderMeshVertexArray(Mesh mesh, int lod, int count, VertexBuffer instanceData) {
if (mesh.getId() == -1) {
updateVertexArray(mesh, instanceData);
} else {
// TODO: Check if it was updated
}
if (context.boundVertexArray != mesh.getId()) {
glBindVertexArray(mesh.getId());
context.boundVertexArray = mesh.getId();
}
// IntMap<VertexBuffer> buffers = mesh.getBuffers();
VertexBuffer indices;
if (mesh.getNumLodLevels() > 0) {
indices = mesh.getLodLevel(lod);
} else {
indices = mesh.getBuffer(Type.Index);
}
if (indices != null) {
drawTriangleList(indices, mesh, count);
} else {
drawTriangleArray(mesh.getMode(), count, mesh.getVertexCount());
}
clearVertexAttribs();
clearTextureUnits();
}
private void renderMeshDefault(Mesh mesh, int lod, int count, VertexBuffer[] instanceData) {
// Here while count is still passed in. Can be removed when/if
// the method is collapsed again. -pspeed
count = Math.max(mesh.getInstanceCount(), count);
VertexBuffer interleavedData = mesh.getBuffer(Type.InterleavedData);
if (interleavedData != null && interleavedData.isUpdateNeeded()) {
updateBufferData(interleavedData);
}
VertexBuffer indices;
if (mesh.getNumLodLevels() > 0) {
indices = mesh.getLodLevel(lod);
} else {
indices = mesh.getBuffer(Type.Index);
}
if (instanceData != null) {
for (VertexBuffer vb : instanceData) {
setVertexAttrib(vb, null);
}
}
for (VertexBuffer vb : mesh.getBufferList().getArray()) {
if (vb.getBufferType() == Type.InterleavedData
|| vb.getUsage() == Usage.CpuOnly // ignore cpu-only buffers
|| vb.getBufferType() == Type.Index) {
continue;
}
if (vb.getStride() == 0) {
// not interleaved
setVertexAttrib(vb);
} else {
// interleaved
setVertexAttrib(vb, interleavedData);
}
}
if (indices != null) {
drawTriangleList(indices, mesh, count);
} else {
drawTriangleArray(mesh.getMode(), count, mesh.getVertexCount());
}
clearVertexAttribs();
clearTextureUnits();
}
public void renderMesh(Mesh mesh, int lod, int count, VertexBuffer[] instanceData) {
if (mesh.getVertexCount() == 0) {
return;
}
if (context.pointSprite && mesh.getMode() != Mode.Points) {
// XXX: Hack, disable point sprite mode if mesh not in point mode
if (context.boundTextures[0] != null) {
if (context.boundTextureUnit != 0) {
glActiveTexture(GL_TEXTURE0);
context.boundTextureUnit = 0;
}
glDisable(GL_POINT_SPRITE);
glDisable(GL_VERTEX_PROGRAM_POINT_SIZE);
context.pointSprite = false;
}
}
if (context.pointSize != mesh.getPointSize()) {
glPointSize(mesh.getPointSize());
context.pointSize = mesh.getPointSize();
}
if (context.lineWidth != mesh.getLineWidth()) {
glLineWidth(mesh.getLineWidth());
context.lineWidth = mesh.getLineWidth();
}
statistics.onMeshDrawn(mesh, lod, count);
// if (ctxCaps.GL_ARB_vertex_array_object){
// renderMeshVertexArray(mesh, lod, count);
// }else{
renderMeshDefault(mesh, lod, count, instanceData);
}
public void setMainFrameBufferSrgb(boolean enableSrgb) {
// Gamma correction
if (!caps.contains(Caps.Srgb)) {
// Not supported, sorry.
logger.warning("sRGB framebuffer is not supported " +
"by video hardware, but was requested.");
return;
}
setFrameBuffer(null);
if (enableSrgb) {
if (!glGetBoolean(GL_FRAMEBUFFER_SRGB_CAPABLE_EXT)) {
logger.warning("Driver claims that default framebuffer "
+ "is not sRGB capable. Enabling anyway.");
}
glEnable(GL_FRAMEBUFFER_SRGB_EXT);
logger.log(Level.FINER, "SRGB FrameBuffer enabled (Gamma Correction)");
} else {
glDisable(GL_FRAMEBUFFER_SRGB_EXT);
}
}
public void setLinearizeSrgbImages(boolean linearize) {
if (caps.contains(Caps.Srgb)) {
linearizeSrgbImages = linearize;
}
}
}
|
package cz.zcu.kiv.jop.property;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import cz.zcu.kiv.jop.util.Preconditions;
import cz.zcu.kiv.jop.util.ReflectionUtils;
/**
* Abstract implementation of {@link Property} interface which provides an implementation of the
* common methods for all properties.
*
* @author Mr.FrAnTA
* @since 1.0.0
*
* @param <T> Declared class type of property.
*/
public abstract class AbstractProperty<T> implements Property<T> {
private static final long serialVersionUID = 20160228L;
/** Class type of a property owner. */
protected final Class<?> declaringClass;
/** Name of property. */
protected final String propertyName;
/**
* Field for property which can be lazy loaded (when is required) - use getter {@link #getField()}
* instead of direct access.
*/
transient Field field;
/** Created getter for property. */
protected transient Getter<T> getter;
/** Created setter for property. */
protected transient Setter<T> setter;
/**
* Constructs an abstract property.
*
* @param declaringClass the class type of a property owner.
* @param propertyName the name of property.
*/
public AbstractProperty(Class<?> declaringClass, String propertyName) {
this.declaringClass = Preconditions.checkArgumentNotNull(declaringClass, "Class type cannot be null");
this.propertyName = Preconditions.checkArgumentNotNull(propertyName, "Name of property cannot be null");
}
/**
* {@inheritDoc}
*/
public Class<?> getDeclaringClass() {
return declaringClass;
}
/**
* {@inheritDoc}
*/
public String getName() {
return propertyName;
}
/**
* {@inheritDoc}
*
* @throws PropertyRuntimeException If some error occurs during getting annotation for property.
*/
public boolean isAnnotationPresent(Class<? extends Annotation> annotationType) {
try {
return getField().isAnnotationPresent(annotationType);
}
catch (PropertyNotFoundException exc) {
throw new PropertyRuntimeException(exc, declaringClass, propertyName);
}
}
/**
* {@inheritDoc}
*
* @throws PropertyRuntimeException If some error occurs during getting annotation for property.
*/
public <A extends Annotation> A getAnnotation(Class<A> annotationType) {
try {
return getField().getAnnotation(annotationType);
}
catch (PropertyNotFoundException exc) {
throw new PropertyRuntimeException(exc, declaringClass, propertyName);
}
}
/**
* {@inheritDoc}
*
* @throws PropertyRuntimeException If some error occurs during getting annotation for property.
*/
public Annotation[] getAnnotations() {
try {
return getField().getAnnotations();
}
catch (PropertyNotFoundException exc) {
throw new PropertyRuntimeException(exc, declaringClass, propertyName);
}
}
/**
* {@inheritDoc}
*
* @throws PropertyRuntimeException If some error occurs during getting annotation for property.
*/
public Annotation[] getDeclaredAnnotations() {
try {
return getField().getDeclaredAnnotations();
}
catch (PropertyNotFoundException exc) {
throw new PropertyRuntimeException(exc, declaringClass, propertyName);
}
}
/**
* Returns field for property which is lazy loaded. Because of that is strongly suggested to use
* this getter instead of direct access.
*
* @return Declared field for property.
* @throws PropertyNotFoundException If the field with given name was not found in
* <code>declaringClass</code>.
*/
protected Field getField() throws PropertyNotFoundException {
return field == null ? field = getField(declaringClass, propertyName) : field;
}
/**
* {@inheritDoc}
*/
public Getter<T> getGetter() throws GetterNotFoundException {
if (getter == null) {
getter = createGetter();
}
return getter;
}
/**
* {@inheritDoc}
*/
public Setter<T> getSetter() throws SetterNotFoundException {
if (setter == null) {
setter = createSetter();
}
return setter;
}
/**
* Creates the instance of appropriate <em>getter</em> for the property.
*
* @return The <em>getter</em> for the property.
* @throws GetterNotFoundException If some error occurs during interpretation of the getter name
* (getter for property was not found).
*/
protected abstract Getter<T> createGetter() throws GetterNotFoundException;
/**
* Creates the instance of appropriate <em>setter</em> for the property.
*
* @return The <em>getter</em> for the property.
* @throws GetterNotFoundException If some error occurs during interpretation of the setter name
* (setter for property was not found).
*/
protected abstract Setter<T> createSetter() throws SetterNotFoundException;
/**
* Returns string value of property.
*
* @return String value of property.
*/
@Override
public String toString() {
return getClass().getName() + " [declaringClass=" + (declaringClass == null ? null : declaringClass.getName()) +
", propertyName=" + propertyName + "]";
}
/**
* Recursively searches for declared field with given name in given class and in all parent
* classes or implemented interfaces. If the field is not found, the exception is thrown.
*
* @param clazz the class type of a field owner.
* @param fieldName the name of field.
* @return Found declared field.
* @throws PropertyNotFoundException If the declared field with given name was not found.
*/
protected static Field getField(Class<?> clazz, String fieldName) throws PropertyNotFoundException {
return getField(clazz, clazz, fieldName);
}
/**
* Recursively searches for declared field with given name in given class and in all parent
* classes or implemented interfaces. If the field is not found, the exception is thrown.
*
* @param root the root class type of a field owner (the class from the recursion started).
* @param clazz the class type of a field owner.
* @param fieldName the name of field.
* @return Found declared field.
* @throws PropertyNotFoundException If the declared field with given name was not found.
*/
protected static Field getField(Class<?> root, Class<?> clazz, String fieldName) throws PropertyNotFoundException {
if (clazz == null || clazz == Object.class) {
throw new PropertyNotFoundException(root, fieldName);
}
// the declared field will be accessible, no additional setting is needed.
Field field = ReflectionUtils.getDeclaredField(clazz, fieldName);
if (field == null) {
field = getField(root, clazz.getSuperclass(), fieldName);
}
return field;
}
}
|
package jsettlers.common.landscape;
import java.util.EnumSet;
import java.util.Set;
import jsettlers.common.Color;
public enum ELandscapeType {
// DO NOT sort, order is important!
GRASS(0, new Color(0xff198219), false, false),
DRY_GRASS(1, new Color(0xff82601C), false, false),
DESERT(18, new Color(0xffA07038), false, false),
EARTH(2, new Color(0xffa2653e), false, false), // TODO: color
MOUNTAIN(21, new Color(0xff424142), false, false),
SNOW(25, new Color(0xffc7dee0), false, true),
SAND(3, new Color(0xff949200), false, false),
/**
* Flattened grass (for buildings, paths, ...). Must behave exactly like normal grass does!
*/
FLATTENED(35, new Color(0xff105910), false, false),
RIVER1(10, new Color(0xff000073), false, false),
RIVER2(10, new Color(0xff000073), false, false),
RIVER3(10, new Color(0xff000073), false, false),
RIVER4(10, new Color(0xff000073), false, false),
MOUNTAINBORDER(21, new Color(0xff424142), false, false),
MOUNTAINBORDEROUTER(21, new Color(0xff105910), false, false), // TODO: color
WATER1(17, new Color(0xff1863F0), true, true),
WATER2(16, new Color(0xff1562E0), true, true),
WATER3(15, new Color(0xff1260D0), true, true),
WATER4(14, new Color(0xff0E5CC8), true, true),
WATER5(13, new Color(0xff0C53C0), true, true),
WATER6(12, new Color(0xff084cB8), true, true),
WATER7(11, new Color(0xff0443B0), true, true),
WATER8(10, new Color(0xff003CAB), true, true),
MOOR(8, new Color(0xff003F1C), false, true),
MOORINNER(7, new Color(0xff003F1C), false, true),
MOORBORDER(9, new Color(0xff003F1C), false, false),
FLATTENED_DESERT(217, new Color(0xff949200), false, false),
SHARP_FLATTENED_DESERT(217, new Color(0xff949200), false, false),
GRAVEL(230, new Color(0xff000000), false, false), // TODO: color
DESERTBORDER(19, new Color(0xff949200), false, false),
DESERTBORDEROUTER(20, new Color(0xff949200), false, false),
SNOWINNER(24, new Color(0xffd7fffe), false, true),
SNOWBORDER(23, new Color(0xffd7fffe), false, false),
MUD(5, new Color(0xff0e87cc), false, true), // TODO: color
MUDINNER(4, new Color(0xff0e87cc), false, true), // TODO: color
MUDBORDER(6, new Color(0xff0e87cc), false, false); // TODO: color
public static final ELandscapeType[] values = ELandscapeType.values();
private static final Set<ELandscapeType> rivers = EnumSet.of(RIVER1, RIVER2, RIVER3, RIVER4);
public final int image;
public final Color color;
public final boolean isWater;
public final boolean isBlocking;
public final byte ordinal;
ELandscapeType(int image, Color color, boolean isWater, boolean isBlocking) {
this.image = image;
this.color = color;
this.isWater = isWater;
this.isBlocking = isBlocking;
this.ordinal = (byte) super.ordinal();
}
public final int getImageNumber() {
return image;
}
/**
* Gets the base color of the landscape
*
* @return The color the landscape has.
*/
public final Color getColor() {
return color;
}
/**
* Checks if this landscape type is water (not river, just water that ships can swim on.).
* <p>
* To check for unwalkable land, also test if it is MOOR or SNOW
*
* @return
*/
public final boolean isWater() {
return isWater;
}
public final boolean isGrass() {
return this == GRASS || this == FLATTENED;
}
public final boolean isRiver() {
return rivers.contains(this);
}
}
|
package jsettlers.graphics.ui;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import go.graphics.GLDrawContext;
import jsettlers.common.images.ImageLink;
import jsettlers.common.position.FloatRectangle;
import jsettlers.common.action.Action;
import jsettlers.graphics.image.Image;
import jsettlers.graphics.map.draw.ImageProvider;
/**
* This is a panel that holds UI elements and can have a background.
* <p>
* All elements are positioned relatively.
*
* @author michael
*/
public class UIPanel implements UIElement {
private final LinkedList<ChildLink> children = new LinkedList<>();
private FloatRectangle position = new FloatRectangle(0, 0, 1, 1);
private ImageLink background;
private boolean attached = false;
/**
* Sets the background. file=-1 means no background
*
*/
public void setBackground(ImageLink imageLink) {
this.background = imageLink;
}
/**
* Adds a child to the panel.
*
* @param child
* The child to add.
* @param left
* relative left border (0..1).
* @param bottom
* relative bottom border (0..1).
* @param right
* relative right border (0..1).
* @param top
* relative top border (0..1).
*/
public void addChild(UIElement child, float left, float bottom,
float right, float top) {
if (child == null) {
throw new NullPointerException();
}
this.children.add(new ChildLink(child, left, bottom, right, top));
if (attached) {
child.onAttach();
}
}
public void removeChild(UIElement child) {
for (Iterator<ChildLink> iterator = children.iterator(); iterator.hasNext();) {
ChildLink l = iterator.next();
if (l.child.equals(child)) {
if (attached) {
l.child.onDetach();
}
iterator.remove();
break;
}
}
}
public List<UIElement> getChildren() {
ArrayList<UIElement> list = new ArrayList<>();
for (ChildLink c : children) {
list.add(c.child);
}
return list;
}
@Override
public void drawAt(GLDrawContext gl) {
drawBackground(gl);
drawChildren(gl);
}
protected void drawChildren(GLDrawContext gl) {
if (children.size() > 0) {
for (ChildLink link : children) {
link.drawAt(gl, position);
}
}
}
protected void drawBackground(GLDrawContext gl) {
ImageLink link = getBackgroundImage();
if (link != null) {
FloatRectangle position = getPosition();
Image image = ImageProvider.getInstance().getImage(link, position.getWidth(), position.getHeight());
drawAtRect(gl, image, position);
}
}
/**
* Draws an image at a given rect
*
* @param gl
* The context to use
* @param image
* The image to draw
* @param position
* The position to draw the image at
*/
protected void drawAtRect(GLDrawContext gl, Image image, FloatRectangle position) {
gl.color(1, 1, 1, 1);
float minX = position.getMinX();
float minY = position.getMinY();
float maxX = position.getMaxX();
float maxY = position.getMaxY();
image.drawImageAtRect(gl, minX, minY, maxX, maxY);
}
protected ImageLink getBackgroundImage() {
return background;
}
private class ChildLink {
private final UIElement child;
private final float left;
private final float right;
private final float top;
private final float bottom;
public ChildLink(UIElement child, float left, float bottom, float right, float top) {
this.child = child;
this.left = left;
this.right = right;
this.top = top;
this.bottom = bottom;
}
public void drawAt(GLDrawContext gl, FloatRectangle pos) {
child.setPosition(new FloatRectangle((left * pos.getWidth())+pos.getMinX(), (bottom * pos.getHeight())+pos.getMinY(),
(right * pos.getWidth())+pos.getMinX(), (top * pos.getHeight())+pos.getMinY()));
child.drawAt(gl);
}
public Action getActionRelative(float parentx, float parenty) {
if (left <= parentx && parentx <= right && bottom <= parenty && parenty <= top) {
float relativex = (parentx - left) / (right - left);
float relativey = (parenty - bottom) / (top - bottom);
return child.getAction(relativex, relativey);
} else {
return null;
}
}
public String getDesctiptionRelative(float parentx, float parenty) {
if (left <= parentx && parentx <= right && bottom <= parenty && parenty <= top) {
float relativex = (parentx - left) / (right - left);
float relativey = (parenty - bottom) / (top - bottom);
return child.getDescription(relativex, relativey);
} else {
return null;
}
}
}
@Override
public void setPosition(FloatRectangle position) {
this.position = position;
}
public FloatRectangle getPosition() {
return position;
}
public void removeAll() {
if (attached) {
for (ChildLink link : children) {
link.child.onDetach();
}
}
this.children.clear();
}
@Override
public Action getAction(float relativex, float relativey) {
for (ChildLink link : children) {
Action action = link.getActionRelative(relativex, relativey);
if (action != null) {
return action;
}
}
return null;
}
@Override
public String getDescription(float relativex, float relativey) {
for (ChildLink link : children) {
String description = link.getDesctiptionRelative(relativex, relativey);
if (description != null) {
return description;
}
}
return null;
}
@Override
public void onAttach() {
if (!attached) {
for (ChildLink link : children) {
link.child.onAttach();
}
}
attached = true;
}
@Override
public void onDetach() {
if (attached) {
for (ChildLink link : children) {
link.child.onDetach();
}
}
attached = false;
}
}
|
package org.commcare.views;
import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Point;
import android.os.Build;
import android.support.v4.util.Pair;
import android.support.v4.widget.Space;
import android.support.v7.widget.GridLayout;
import android.text.Spannable;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.TextView;
import org.commcare.dalvik.R;
import org.commcare.models.AsyncEntity;
import org.commcare.models.Entity;
import org.commcare.suite.model.Detail;
import org.commcare.util.GridCoordinate;
import org.commcare.util.GridStyle;
import org.commcare.utils.CachingAsyncImageLoader;
import org.commcare.utils.MarkupUtil;
import org.commcare.utils.MediaUtil;
import org.commcare.views.media.AudioButton;
import org.commcare.views.media.ViewId;
import org.javarosa.core.services.Logger;
import org.javarosa.xpath.XPathUnhandledException;
import java.util.Arrays;
/**
* This class defines an individual panel that is shown either within an advanced case list
* or as a case tile. Each panel is defined by a Detail and an Entity.
*
* @author wspride
*/
public class EntityViewTile extends GridLayout {
private String[] searchTerms;
// All of the views that are being shown in this tile, one for each field of the entity's detail
private View[] mFieldViews;
private boolean mFuzzySearchEnabled = false;
private boolean mIsAsynchronous = false;
// load the screen-size-dependent font sizes
private final float SMALL_FONT = getResources().getDimension(R.dimen.font_size_small);
private final float MEDIUM_FONT = getResources().getDimension(R.dimen.font_size_medium);
private final float LARGE_FONT = getResources().getDimension(R.dimen.font_size_large);
private final float XLARGE_FONT = getResources().getDimension(R.dimen.font_size_xlarge);
private final float DENSITY = getResources().getDisplayMetrics().density;
private final int DEFAULT_TILE_PADDING_HORIZONTAL =
(int)getResources().getDimension(R.dimen.row_padding_horizontal);
private final int DEFAULT_TILE_PADDING_VERTICAL =
(int)getResources().getDimension(R.dimen.row_padding_vertical);
// Constants used to calibrate how many tiles should be shown on a screen at once -- This is
// saying that we expect a device with a density of 160 dpi and a height of 4 inches to look
// good in portrait mode with 4 tiles of 6 rows each being displayed at once.
private static final double DEFAULT_SCREEN_HEIGHT_IN_INCHES = 4.0;
private static final int DEFAULT_SCREEN_DENSITY = DisplayMetrics.DENSITY_MEDIUM;
private static final double DEFAULT_NUM_TILES_PER_SCREEN_PORTRAIT = 4;
private static final int DEFAULT_NUMBER_ROWS_PER_GRID = 6;
private static final double LANDSCAPE_TO_PORTRAIT_RATIO = .75;
// this is fixed for all tiles
private static final int NUMBER_COLUMNS_PER_GRID = 12;
private final int numRowsPerTile;
private final int numTilesPerRow;
private double cellWidth;
private double cellHeight;
private final CachingAsyncImageLoader mImageLoader;
private final boolean beingDisplayedInAwesomeMode;
public static EntityViewTile createTileForIndividualDisplay(Context context, Detail detail,
Entity entity) {
return new EntityViewTile(context, detail, entity, new String[0],
new CachingAsyncImageLoader(context), false, false);
}
public static EntityViewTile createTileForEntitySelectDisplay(Context context, Detail detail,
Entity entity,
String[] searchTerms,
CachingAsyncImageLoader loader,
boolean fuzzySearchEnabled,
boolean inAwesomeMode) {
return new EntityViewTile(context, detail, entity, searchTerms, loader,
fuzzySearchEnabled, inAwesomeMode);
}
private EntityViewTile(Context context, Detail detail, Entity entity, String[] searchTerms,
CachingAsyncImageLoader loader, boolean fuzzySearchEnabled,
boolean inAwesomeMode) {
super(context);
this.searchTerms = searchTerms;
this.mIsAsynchronous = entity instanceof AsyncEntity;
this.mImageLoader = loader;
this.mFuzzySearchEnabled = fuzzySearchEnabled;
this.numRowsPerTile = getMaxRows(detail);
this.numTilesPerRow = detail.getNumEntitiesToDisplayPerRow();
this.beingDisplayedInAwesomeMode = inAwesomeMode;
setEssentialGridLayoutValues();
setCellWidthAndHeight(context, detail);
addFieldViews(context, detail, entity);
}
/**
* @return the maximum height of the grid view for the given detail
*/
private static int getMaxRows(Detail detail) {
GridCoordinate[] coordinates = detail.getGridCoordinates();
int currentMaxHeight = 0;
for (GridCoordinate coordinate : coordinates) {
int yCoordinate = coordinate.getY();
int height = coordinate.getHeight();
int maxHeight = yCoordinate + height;
if (maxHeight > currentMaxHeight) {
currentMaxHeight = maxHeight;
}
}
return currentMaxHeight;
}
private void setEssentialGridLayoutValues() {
setColumnCount(NUMBER_COLUMNS_PER_GRID);
setRowCount(numRowsPerTile);
setPaddingIfNotInGridView();
}
private void setCellWidthAndHeight(Context context, Detail detail) {
Pair<Integer, Integer> tileWidthAndHeight = computeTileWidthAndHeight(context);
cellWidth = tileWidthAndHeight.first / (double)NUMBER_COLUMNS_PER_GRID;
if (detail.useUniformUnitsInCaseTile()) {
cellHeight = cellWidth;
} else {
cellHeight = tileWidthAndHeight.second / (double)numRowsPerTile;
}
}
/**
* Compute what the width and height of a single tile should be, based upon the available
* screen space, how many columns there should be, and how many rows we want to show at a time.
* Round up to the nearest integer since the GridView's width and height will ultimately be
* computed indirectly from these values, and those values need to be integers, and we don't
* want to end up cutting things off
*/
private Pair<Integer, Integer> computeTileWidthAndHeight(Context context) {
double screenWidth, screenHeight;
Display display = ((Activity)context).getWindowManager().getDefaultDisplay();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
Point size = new Point();
display.getSize(size);
screenWidth = size.x;
screenHeight = size.y;
} else {
screenWidth = display.getWidth();
screenHeight = display.getHeight();
}
if (!tileBeingShownInGridView()) {
// If we added padding, subtract that space since we can't use it
screenWidth = screenWidth - DEFAULT_TILE_PADDING_HORIZONTAL * 2;
}
int tileHeight;
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
if (beingDisplayedInAwesomeMode) {
// if in awesome mode, split available width in half
screenWidth = screenWidth / 2;
}
tileHeight = (int)Math.ceil(screenHeight / computeNumTilesPerScreen(false, screenHeight));
} else {
tileHeight = (int)Math.ceil(screenHeight / computeNumTilesPerScreen(true, screenHeight));
}
int tileWidth = (int)Math.ceil(screenWidth / numTilesPerRow);
return new Pair<>(tileWidth, tileHeight);
}
/**
* @return - The number of tiles that should be displayed on a single screen on this device,
* calibrated against our default values based upon both the screen density and the screen
* height in inches
*/
private double computeNumTilesPerScreen(boolean inPortrait, double screenHeightInPixels) {
double numTilesPerScreenPortrait = DEFAULT_NUM_TILES_PER_SCREEN_PORTRAIT *
(DEFAULT_NUMBER_ROWS_PER_GRID / (float)numRowsPerTile);
double baseNumberOfTiles;
if (inPortrait) {
baseNumberOfTiles = numTilesPerScreenPortrait;
} else {
baseNumberOfTiles = numTilesPerScreenPortrait * LANDSCAPE_TO_PORTRAIT_RATIO;
}
int screenDensity = getResources().getDisplayMetrics().densityDpi;
return (baseNumberOfTiles + getAdditionalTilesBasedOnScreenDensity(screenDensity))
* getScreenHeightMultiplier(screenDensity, screenHeightInPixels);
}
private static double getAdditionalTilesBasedOnScreenDensity(int screenDensity) {
// For every additional 160dpi from the default density, show one more tile on the screen
int defaultDensityDpi = DEFAULT_SCREEN_DENSITY;
return (screenDensity - defaultDensityDpi) / 160;
}
private static double getScreenHeightMultiplier(int screenDensity, double screenHeightInPixels) {
double screenHeightInInches = screenHeightInPixels / screenDensity;
return screenHeightInInches / DEFAULT_SCREEN_HEIGHT_IN_INCHES;
}
/**
* Add Spaces to this GridLayout to strictly enforce that Grid columns and rows stay the width/height we want
* Android GridLayout tries to be very "smart" about moving entries placed arbitrarily within the grid so that
* they look "ordered" even though this often ends up looking not how we want it. It will only make these adjustments
* to rows/columns that end up empty or near empty, so we solve this by adding spaces to every row and column.
* We just add a space of width cellWidth and height 1 to every column of the first row, and likewise a sapce of height
* cellHeight and width 1 to every row of the first column. These are then written on top of if need be.
*/
private void addBuffers(Context context) {
addBuffersToView(context, numRowsPerTile, true);
addBuffersToView(context, NUMBER_COLUMNS_PER_GRID, false);
}
private void addBuffersToView(Context context, int count, boolean isRow) {
for (int i = 0; i < count; i++) {
GridLayout.LayoutParams gridParams;
if (isRow) {
gridParams = new GridLayout.LayoutParams(GridLayout.spec(i), GridLayout.spec(0));
gridParams.width = 1;
gridParams.height = (int)cellHeight;
} else {
gridParams = new GridLayout.LayoutParams(GridLayout.spec(0), GridLayout.spec(i));
gridParams.width = (int)cellWidth;
gridParams.height = 1;
}
Space space = new Space(context);
space.setLayoutParams(gridParams);
this.addView(space, gridParams);
}
}
/**
* Add the view for each field in the detail
*
* @param detail - the Detail describing how to display each entry
* @param entity - the Entity describing the actual data of each entry
*/
public void addFieldViews(Context context, Detail detail, Entity entity) {
this.removeAllViews();
addBuffers(context); // add spacers to enforce regularized column and row size
GridCoordinate[] coordinatesOfEachField = detail.getGridCoordinates();
String[] typesOfEachField = detail.getTemplateForms();
GridStyle[] stylesOfEachField = detail.getGridStyles();
Log.v("TempForms", "Template: " + Arrays.toString(typesOfEachField) +
" | Coords: " + Arrays.toString(coordinatesOfEachField) +
" | Styles: " + Arrays.toString(stylesOfEachField));
setPaddingIfNotInGridView();
if (tileBeingShownInGridView()) {
// Fake dividers between each square in the grid view by using contrasting
// background colors for the grid view as a whole and each element in the grid view
setBackgroundColor(Color.WHITE);
}
mFieldViews = new View[coordinatesOfEachField.length];
for (int i = 0; i < mFieldViews.length; i++) {
addFieldView(context, typesOfEachField[i], stylesOfEachField[i],
coordinatesOfEachField[i], entity.getFieldString(i), entity.getSortField(i), i);
}
}
private void addFieldView(Context context, String form,
GridStyle style, GridCoordinate coordinateData, String fieldString,
String sortField, int index) {
if (coordinatesInvalid(coordinateData)) {
return;
}
ViewId uniqueId = new ViewId(coordinateData.getX(), coordinateData.getY(), false);
GridLayout.LayoutParams gridParams = getLayoutParamsForField(coordinateData);
View view = getView(context, style, form, fieldString, uniqueId, sortField,
gridParams.width, gridParams.height);
if (!(view instanceof ImageView)) {
gridParams.height = LayoutParams.WRAP_CONTENT;
}
view.setLayoutParams(gridParams);
mFieldViews[index] = view;
this.addView(view, gridParams);
}
private GridLayout.LayoutParams getLayoutParamsForField(GridCoordinate coordinateData) {
Spec columnSpec = GridLayout.spec(coordinateData.getX(), coordinateData.getWidth());
Spec rowSpec = GridLayout.spec(coordinateData.getY(), coordinateData.getHeight());
GridLayout.LayoutParams gridParams = new GridLayout.LayoutParams(rowSpec, columnSpec);
gridParams.width = (int)Math.ceil(cellWidth * coordinateData.getWidth());
gridParams.height = (int)Math.ceil(cellHeight * coordinateData.getHeight());
return gridParams;
}
private boolean coordinatesInvalid(GridCoordinate coordinate) {
if (coordinate.getX() + coordinate.getWidth() > NUMBER_COLUMNS_PER_GRID ||
coordinate.getY() + coordinate.getHeight() > numRowsPerTile) {
Logger.log("e", "Grid entry dimensions exceed allotted sizes");
throw new XPathUnhandledException("grid coordinates out of bounds: " +
coordinate.getX() + " " + coordinate.getWidth() + ", " +
coordinate.getY() + " " + coordinate.getHeight());
}
return (coordinate.getX() < 0 || coordinate.getY() < 0);
}
/**
* Get the correct View for this particular activity.
*
* @param fieldForm either "image", "audio", or default text. Describes how this XPath result should be displayed.
* @param rowData The actual data to display, either an XPath to media or a String to display.
*/
private View getView(Context context, GridStyle style, String fieldForm, String rowData,
ViewId uniqueId, String searchField, int maxWidth, int maxHeight) {
// How the text should be aligned horizontally - left, center, or right
String horzAlign = style.getHorzAlign();
// How the text should be aligned vertically - top, center, or bottom
String vertAlign = style.getVertAlign();
View retVal;
switch (fieldForm) {
case EntityView.FORM_IMAGE:
retVal = new ImageView(context);
setScaleType((ImageView)retVal, horzAlign);
// make the image's padding proportional to its size
retVal.setPadding(maxWidth / 6, maxHeight / 6, maxWidth / 6, maxHeight / 6);
if (rowData != null && !rowData.equals("")) {
if (mImageLoader != null) {
mImageLoader.display(rowData, ((ImageView)retVal), R.drawable.info_bubble,
maxWidth, maxHeight);
} else {
Bitmap b = MediaUtil.inflateDisplayImage(getContext(), rowData,
maxWidth, maxHeight, true);
((ImageView)retVal).setImageBitmap(b);
}
}
break;
case EntityView.FORM_AUDIO:
if (rowData != null && rowData.length() > 0) {
retVal = new AudioButton(context, rowData, uniqueId, true);
} else {
retVal = new AudioButton(context, rowData, uniqueId, false);
}
break;
default:
retVal = new TextView(context);
//the html spanner currently does weird stuff like converts "a a" into "a a"
//so we've gotta mirror that for the search text. Booooo. I dunno if there's any
//other other side effects (newlines? nbsp?)
String htmlIfiedSearchField = searchField == null ? null : MarkupUtil.getSpannable(searchField).toString();
String cssid = style.getCssID();
if (cssid != null && !cssid.equals("none")) {
// user defined a style we want to use
Spannable mSpannable = MarkupUtil.getCustomSpannable(cssid, rowData);
EntityView.highlightSearches(searchTerms, mSpannable, htmlIfiedSearchField, mFuzzySearchEnabled, mIsAsynchronous);
((TextView)retVal).setText(mSpannable);
} else {
// just process inline markup
Spannable mSpannable = MarkupUtil.returnCSS(rowData);
EntityView.highlightSearches(searchTerms, mSpannable, htmlIfiedSearchField, mFuzzySearchEnabled, mIsAsynchronous);
((TextView)retVal).setText(mSpannable);
}
int gravity = computeGravity(horzAlign, vertAlign);
if (gravity != 0) {
((TextView)retVal).setGravity(gravity);
}
// handle text resizing
switch (style.getFontSize()) {
case "large":
((TextView)retVal).setTextSize(LARGE_FONT / DENSITY);
break;
case "small":
((TextView)retVal).setTextSize(SMALL_FONT / DENSITY);
break;
case "medium":
((TextView)retVal).setTextSize(MEDIUM_FONT / DENSITY);
break;
case "xlarge":
((TextView)retVal).setTextSize(XLARGE_FONT / DENSITY);
break;
}
}
return retVal;
}
private static int computeGravity(String horzAlign, String vertAlign) {
int gravity = 0;
// handle horizontal alignments
switch (horzAlign) {
case "center":
gravity |= Gravity.CENTER_HORIZONTAL;
break;
case "left":
gravity |= Gravity.LEFT;
break;
case "right":
gravity |= Gravity.RIGHT;
break;
}
// handle vertical alignment
switch (vertAlign) {
case "center":
gravity |= Gravity.CENTER_VERTICAL;
break;
case "top":
gravity |= Gravity.TOP;
break;
case "bottom":
gravity |= Gravity.BOTTOM;
break;
}
return gravity;
}
private static void setScaleType(ImageView imageView, String horizontalAlignment) {
switch (horizontalAlignment) {
case "center":
imageView.setScaleType(ScaleType.CENTER_INSIDE);
break;
case "left":
imageView.setScaleType(ScaleType.FIT_START);
break;
case "right":
imageView.setScaleType(ScaleType.FIT_END);
break;
}
}
public void setSearchTerms(String[] currentSearchTerms) {
this.searchTerms = currentSearchTerms;
}
public void setTextColor(int color) {
for (View rowView : mFieldViews) {
if (rowView instanceof TextView) {
((TextView)rowView).setTextColor(color);
}
}
}
public void setTitleTextColor(int color) {
for (View rowView : mFieldViews) {
if (rowView instanceof TextView) {
((TextView)rowView).setTextColor(color);
return;
}
}
}
private boolean tileBeingShownInGridView() {
return numTilesPerRow > 1;
}
private void setPaddingIfNotInGridView() {
if (!tileBeingShownInGridView()) {
setPadding(DEFAULT_TILE_PADDING_HORIZONTAL, DEFAULT_TILE_PADDING_VERTICAL,
DEFAULT_TILE_PADDING_HORIZONTAL, DEFAULT_TILE_PADDING_VERTICAL);
}
}
}
|
package aptgraph.study;
import aptgraph.core.Domain;
import aptgraph.server.RequestHandler;
import aptgraph.server.Output;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.LinkedList;
import java.util.List;
import java.util.TreeMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.json.JSONException;
import org.json.JSONObject;
/**
*
* @author Thomas Gilon
*/
public final class Main {
private static final boolean DEFAULT_OVERWRITE_BOOL = false;
/**
* @param args the command line arguments
* @throws org.apache.commons.cli.ParseException If text can't be parsed
*/
public static void main(final String[] args) throws ParseException {
// Default value of arguments
boolean overwrite_bool = DEFAULT_OVERWRITE_BOOL;
// Parse command line arguments
Options options = new Options();
options.addOption("i", true, "Input config file (required)");
Option arg_overwrite = Option.builder("x")
.optionalArg(true)
.desc("Overwrite existing graphs (default : false)")
.hasArg(true)
.numberOfArgs(1)
.build();
options.addOption(arg_overwrite);
CommandLineParser parser = new DefaultParser();
CommandLine cmd = parser.parse(options, args);
if (cmd.hasOption("h")
|| !cmd.hasOption("i")) {
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("java -jar infection-<version>.jar", options);
return;
}
try {
if (cmd.hasOption("x")) {
overwrite_bool = Boolean.parseBoolean(cmd.getOptionValue("x"));
}
} catch (IllegalArgumentException ex) {
System.err.println(ex);
}
JSONObject obj;
List<String> config = null;
try {
config = Files.readAllLines(
Paths.get(cmd.getOptionValue("i")),
StandardCharsets.UTF_8);
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
String input_dir_store = "";
RequestHandler handler = null;
for (String config_line : config) {
try {
obj = new JSONObject(config_line);
} catch (JSONException ex) {
throw new JSONException(ex + "\nJSON did not match ");
}
if (!input_dir_store.equals(obj.getString("input_dir"))) {
input_dir_store = obj.getString("input_dir");
handler = new RequestHandler(
Paths.get(input_dir_store));
}
File file = new File(obj.getString("output_file"));
if (overwrite_bool || !file.exists()) {
Output output = handler.analyze(obj.getString("user"),
new double[]{obj.getDouble("feature_weights_time"),
obj.getDouble("feature_weights_domain"),
obj.getDouble("feature_weights_url")},
new double[]{obj.getDouble("feature_ordered_weights_1"),
obj.getDouble("feature_ordered_weights_2")},
obj.getDouble("prune_threshold"),
obj.getDouble("max_cluster_size"),
obj.getBoolean("prune_z"),
obj.getBoolean("cluster_z"),
obj.getBoolean("whitelist"),
obj.getString("white_ongo"),
obj.getInt("number_requests"),
new double[]{obj.getDouble("ranking_weights_parents"),
obj.getDouble("ranking_weights_children"),
obj.getDouble("ranking_weights_requests")},
obj.getBoolean("apt_search"));
TreeMap<Double, LinkedList<Domain>> ranking
= output.getRanking();
int n_apt_tot = obj.getInt("n_apt_tot");
ROC.makeROC(ranking, handler.getMemory().getAllDomains()
.get("all").values().size() - n_apt_tot, n_apt_tot,
obj.getString("output_file"));
}
}
}
private Main() {
}
}
|
package com.winterwell.web.ajax;
import java.util.Collections;
import java.util.Map;
import org.eclipse.jetty.util.ajax.JSON;
import com.winterwell.depot.IInit;
import com.winterwell.depot.INotSerializable;
import com.winterwell.gson.Gson;
import com.winterwell.utils.Dep;
import com.winterwell.utils.ReflectionUtils;
import com.winterwell.utils.StrUtils;
import com.winterwell.utils.Utils;
import com.winterwell.utils.WrappedException;
import com.winterwell.utils.web.IHasJson;
/**
* Wrapper for json objects
* @author daniel
*
*/
public class JThing<T>
implements INotSerializable, IHasJson // serialize the json not this wrapper
{
private String json;
private Map<String,Object> map;
private T java;
private Class<T> type;
/**
* Optionally used for ES version control
*/
public Object version;
/**
* Equivalent to new JThing().setJava(item)
* @param item the Java POJO
*/
public JThing(T item) {
setJava(item);
}
/**
* Usually needed (depending on the gson setup) for {@link #java()} to deserialise json.
* Note: Once set, you cannot change the type (repeated calls with the same type are fine).
* @param type
* @return this
*/
public JThing<T> setType(Class<T> type) {
// Once set, you cannot change the type (repeated calls with the same type are fine).
assert this.type==null || this.type.equals(type) : this.type+" != "+type;
this.type = type;
assert java==null || type==null || ReflectionUtils.isa(java.getClass(), type) : type+" vs "+java.getClass();
return this;
}
public Class<T> getType() {
return type;
}
public JThing() {
}
public JThing(String json) {
this.json = json;
}
/**
* @return The JSON string.
* <br>
* NB: This is NOT the same as {@link #toString()}, which returns a shorter snippet.
*/
public String string() {
if (json==null && map!=null) {
Gson gson = gson();
json = gson.toJson(map);
}
if (json==null && java!=null) {
Gson gson = gson();
json = gson.toJson(java);
}
return json;
}
private Gson gson() {
if (Dep.has(Gson.class)) {
return Dep.get(Gson.class);
}
// a default
return new Gson();
}
/**
* @return An unmodifiable map view.
* @see #put(String, Object)
*/
public Map<String, Object> map() {
if (map==null && string()!=null) {
map = (Map<String, Object>) JSON.parse(json);
}
if (map==null) {
return null;
}
return Collections.unmodifiableMap(map);
}
public JThing<T> setJava(T java) {
this.java = java;
if (java==null) return this;
map = null;
json = null;
if (type==null) type = (Class<T>) java.getClass();
assert ReflectionUtils.isa(java.getClass(), type) : type+" vs "+java.getClass();
return this;
}
public JThing<T> setJson(String json) {
this.json = json;
this.java = null;
this.map = null;
return this;
}
public T java() {
if (java!=null) return java;
// convert from json?
String sjson = string();
if (sjson == null) {
return null; // nope, its really null
}
assert type != null : "Call setType() first "+this;
Gson gson = gson();
T pojo = gson.fromJson(sjson, type);
// init?
if (pojo instanceof IInit) {
try {
((IInit) pojo).init();
} catch (Throwable ex) {
// add in extra info
throw new WrappedException("Cause POJO: "+pojo,ex);
}
}
// this will null out the json/map
// ...which is good, as extra json from the front-end can cause bugs with ES mappings.
setJava(pojo);
return java;
}
/**
* NOT the json - this is a short version for debug / logging.
* @see #string()
*/
@Override
public String toString() {
return "JThing"+StrUtils.ellipsize(string(), 100)+"";
}
/**
* Modify the map() view, and force an update of the string() view + null the java() view
* @param k
* @param v
*/
public void put(String k, Object v) {
map();
map.put(k, v);
java = null;
json = null;
}
public JThing<T> setMap(Map<String, Object> obj) {
this.map = obj;
java = null;
json = null;
return this;
}
public Object toJson2() {
// is it an object? (the normal case)
if (map!=null) return map();
if (json!=null && json.startsWith("{")) {
return map();
}
if (string()==null) return null;
return JSON.parse(string());
}
/**
* @param data A json object (from a parse). Normally a Map, but it could be an array/list or a primitive.
* @return this
*/
public JThing<T> setJsonObject(Object _data) {
// no unnecessary seialisation work for maps
if (_data instanceof Map) {
setMap((Map) _data);
return this;
}
// play it safe -- set as a json string
String djson = JSON.toString(_data);
setJson(djson);
return this;
}
}
|
package example;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.servlet.configuration.EnableWebMvcSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import example.xauth.XAuthTokenConfigurer;
@ComponentScan
@EnableAutoConfiguration
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@EnableWebMvcSecurity
@EnableWebSecurity(debug = false)
@Configuration
@Order
class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
String[] restEndpointsToSecure = { NewsController.NEWS_COLLECTION };
for (String endpoint : restEndpointsToSecure) {
|
package CodeQuizServer;
import java.io.Serializable;
import java.util.LinkedList;
import java.util.Random;
import codequiz.SortingQuestion;
public class SortingCeremonyGame implements Serializable {
private Database database;
private LinkedList<SortingQuestion> sortingQuestionList = new LinkedList<SortingQuestion>();
// private SortingQuestion sortingQuestion1;
public SortingCeremonyGame() {
System.out.println("SortingCeremonyGame: Konstruktor");
database = new Database();
database.getSortingQuestionDB();
setSortingQuestion();
// createSortingQuestions();
}
// public void createSortingQuestions() {
// System.out.println("SortingCeremonyGame: createSortingCeremonyQuestions()");
// sortingQuestion1 = new SortingQuestion(
// "Gul",
// "Gul"
// setSortingQuestion();
public void setSortingQuestion() {
LinkedList<SortingQuestion> sortingList = new LinkedList<SortingQuestion>(
database.returnSortingQuestions());
System.out.println(sortingList.size() + "storlek");
for (int i = 0; i < sortingList.size(); i++) {
sortingQuestionList.add(sortingList.get(i));
}
}
public SortingQuestion getSortingQuestion(int index) {
Random rand = new Random();
int random = rand.nextInt(sortingQuestionList.size());
return sortingQuestionList.get(random);
}
}
|
package ceylon.language;
import com.redhat.ceylon.compiler.java.Util;
import com.redhat.ceylon.compiler.java.metadata.Ceylon;
import com.redhat.ceylon.compiler.java.metadata.Class;
import com.redhat.ceylon.compiler.java.metadata.Ignore;
import com.redhat.ceylon.compiler.java.metadata.Name;
import com.redhat.ceylon.compiler.java.metadata.SatisfiedTypes;
import com.redhat.ceylon.compiler.java.metadata.Transient;
import com.redhat.ceylon.compiler.java.metadata.ValueType;
import com.redhat.ceylon.compiler.java.runtime.model.ReifiedType;
import com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor;
@Ceylon(major = 8)
@Class(extendsType="ceylon.language::Object", basic = false, identifiable = false)
@SatisfiedTypes({
"ceylon.language::Number<ceylon.language::Float>",
"ceylon.language::Exponentiable<ceylon.language::Float,ceylon.language::Float>"
})
@ValueType
public final class Float
implements Number<Float>, Exponentiable<Float,Float>, ReifiedType {
@Ignore
public final static TypeDescriptor $TypeDescriptor$ = TypeDescriptor.klass(Float.class);
@Ignore
final double value;
public Float(@Name("float") double f) {
value = f;
}
@Ignore
@Override
public Number$impl<Float> $ceylon$language$Number$impl(){
// drags Numeric<Float> Comparable<Float>
throw Util.makeUnimplementedMixinAccessException();
}
@Ignore
@Override
public Invertible$impl<Float> $ceylon$language$Invertible$impl(){
throw Util.makeUnimplementedMixinAccessException();
}
@Ignore
@Override
public Comparable$impl<Float> $ceylon$language$Comparable$impl(){
throw Util.makeUnimplementedMixinAccessException();
}
@Ignore
public static Float instance(double d) {
return new Float(d);
}
@Ignore
public double doubleValue() {
return value;
}
@Override
public Float plus(@Name("other") Float other) {
return instance(value + other.value);
}
@Ignore
public static double plus(double value, double otherValue) {
return value + otherValue;
}
@Override
public Float minus(@Name("other") Float other) {
return instance(value - other.value);
}
@Ignore
public static double minus(double value, double otherValue) {
return value - otherValue;
}
@Override
public Float times(@Name("other") Float other) {
return instance(value * other.value);
}
@Ignore
public static double times(double value, double otherValue) {
return value * otherValue;
}
@Override
public Float divided(@Name("other") Float other) {
return instance(value / other.value);
}
@Ignore
public static double divided(double value, double otherValue) {
return value / otherValue;
}
@Override
public Float power(@Name("other") Float other) {
return instance(power(value, other.value));
}
@Ignore
public static double power(double value, double otherValue) {
if (otherValue==0.0) {
return 1.0;
}
else if (otherValue==1.0) {
return value;
}
else if (otherValue==2.0) {
return value*value;
}
else if (otherValue==3.0) {
return value*value*value;
}
//TODO: other positive integer powers for which
// multiplying is faster than pow()
else if (otherValue==0.5) {
return Math.sqrt(value);
}
else if (otherValue==0.25) {
return Math.sqrt(Math.sqrt(value));
}
else if (otherValue==-1.0) {
return 1.0/value;
}
else if (otherValue==-2.0) {
return 1.0/value/value;
}
else if (otherValue==-3.0) {
return 1.0/value/value/value;
}
else if (otherValue==-0.5) {
return 1.0/Math.sqrt(value);
}
else if (otherValue==-0.25) {
return 1.0/Math.sqrt(Math.sqrt(value));
}
else {
//NOTE: this function is _really_ slow!
return Math.pow(value, otherValue);
}
}
@Ignore
public Float plus(Integer other) {
return instance(value + other.value);
}
@Ignore
public static double plus(double value, long otherValue) {
return value + otherValue;
}
@Ignore
public Float minus(Integer other) {
return instance(value - other.value);
}
@Ignore
public static double minus(double value, long otherValue) {
return value - otherValue;
}
@Ignore
public Float times(Integer other) {
return instance(value * other.value);
}
@Ignore
public static double times(double value, long otherValue) {
return value * otherValue;
}
@Ignore
public Float divided(Integer other) {
return instance(value / other.value);
}
@Ignore
public static double divided(double value, long otherValue) {
return value / otherValue;
}
@Ignore
public Float power(Integer other) {
return instance(powerOfInteger(value, other.value));
}
@Ignore
public static double power(double value, long otherValue) {
return powerOfInteger(value, otherValue);
}
@Override
public Float getMagnitude() {
return instance(Math.abs(value));
}
@Ignore
public static double getMagnitude(double value) {
return Math.abs(value);
}
@Override
public Float getFractionalPart() {
return instance(value > 0.0D ? value - (long)value : (long)value - value);
}
@Ignore
public static double getFractionalPart(double value) {
return value > 0.0D ? value - (long)value : (long)value - value;
}
@Override
public Float getWholePart() {
return instance(getInteger(value));
}
@Ignore
public static double getWholePart(double value) {
return getInteger(value);
}
@Override
public boolean getPositive() {
return value > 0;
}
@Ignore
public static boolean getPositive(double value) {
return value > 0;
}
@Override
public boolean getNegative() {
return value < 0;
}
@Ignore
public static boolean getNegative(double value) {
return value < 0;
}
public boolean getStrictlyPositive() {
return (Double.doubleToRawLongBits(value) >> 63)==0
&& !Double.isNaN(value);
}
@Ignore
public static boolean getStrictlyPositive(double value) {
return (Double.doubleToRawLongBits(value) >> 63)==0
&& !Double.isNaN(value);
}
public boolean getStrictlyNegative() {
return (Double.doubleToRawLongBits(value) >> 63)!=0
&& !Double.isNaN(value);
}
@Ignore
public static boolean getStrictlyNegative(double value) {
return (Double.doubleToRawLongBits(value) >> 63)!=0
&& !Double.isNaN(value);
}
@Override
public long getSign() {
if (value > 0)
return 1;
if (value < 0)
return -1;
return 0;
}
@Ignore
public static long getSign(double value) {
if (value > 0)
return 1;
if (value < 0)
return -1;
return 0;
}
@Override
public Float getNegated() {
return instance(-value);
}
@Ignore
public static double getNegated(double value) {
return -value;
}
@Override
public Comparison compare(@Name("other") Float other) {
double x = value;
double y = other.value;
return (x < y) ? smaller_.get_() :
((x == y) ? equal_.get_() : larger_.get_());
}
@Ignore
public static Comparison compare(double value, double otherValue) {
double x = value;
double y = otherValue;
return (x < y) ? smaller_.get_() :
((x == y) ? equal_.get_() : larger_.get_());
}
@Override
public java.lang.String toString() {
return java.lang.Double.toString(value);
}
@Ignore
public static java.lang.String toString(double value) {
return java.lang.Double.toString(value);
}
// Conversions between numeric types
public long getInteger() {
return getInteger(value);
}
@Ignore
public static long getInteger(double value) {
if (value >= Long.MIN_VALUE
&& value <= Long.MAX_VALUE) {
return (long)value;
}
else {
throw new OverflowException();
}
}
@Transient
public boolean getUndefined() {
return Double.isNaN(this.value);
}
@Ignore
public static boolean getUndefined(double value) {
return Double.isNaN(value);
}
@Transient
public boolean getFinite() {
return !Double.isInfinite(this.value) && !getUndefined();
}
@Ignore
public static boolean getFinite(double value) {
return !Double.isInfinite(value) && !getUndefined(value);
}
@Transient
public boolean getInfinite() {
return Double.isInfinite(value);
}
@Ignore
public static boolean getInfinite(double value) {
return Double.isInfinite(value);
}
@Override
public boolean equals(@Name("that") java.lang.Object that) {
return equals(value, that);
}
@Ignore
public static boolean equals(double value, java.lang.Object that) {
if (that instanceof Integer) {
return value == ((Integer)that).value;
}
else if (that instanceof Float) {
return value == ((Float)that).value;
}
else {
return false;
}
}
@Override
public int hashCode() {
return hashCode(value);
}
@Ignore
public static int hashCode(double value) {
long wholePart = (long) value;
if (value == wholePart) {// make integers and floats have consistent hashes
return Integer.hashCode(wholePart);
} else {
final long bits = Double.doubleToLongBits(value);
return (int)(bits ^ (bits >>> 32));
}
}
@Override
@Ignore
public TypeDescriptor $getType$() {
return $TypeDescriptor$;
}
public static boolean largerThan(double value, Float other) {
return value>other.value;
}
public static boolean largerThan(double value, double other) {
return value>other;
}
@Override
public boolean largerThan(@Name("other")Float other) {
return value>other.value;
}
public static boolean notSmallerThan(double value, Float other) {
return value>=other.value;
}
public static boolean notSmallerThan(double value, double other) {
return value>=other;
}
@Override
public boolean notSmallerThan(@Name("other") Float other) {
return value>=other.value;
}
public static boolean smallerThan(double value, Float other) {
return value<other.value;
}
public static boolean smallerThan(double value, double other) {
return value<other;
}
@Override
public boolean smallerThan(@Name("other") Float other) {
return value<other.value;
}
public static boolean notLargerThan(double value, Float other) {
return value<=other.value;
}
public static boolean notLargerThan(double value, double other) {
return value<=other;
}
@Override
public boolean notLargerThan(@Name("other") Float other) {
return value<=other.value;
}
@Override
public Float timesInteger(@Name("integer") long integer) {
return instance(value*integer);
}
public static double timesInteger(double value, long integer) {
return value*integer;
}
@Override
public Float plusInteger(@Name("integer") long integer) {
return instance(value+integer);
}
public static double plusInteger(double value, long integer) {
return value+integer;
}
@Override
public Float powerOfInteger(@Name("integer") long integer) {
return instance(powerOfInteger(value,integer));
}
public static double powerOfInteger(double value, long integer) {
if (integer == 0) {
return 1.0;
}
else if (integer == 1) {
return value;
}
else if (integer == 2) {
return value*value;
}
else if (integer == 3) {
return value*value*value;
}
//TODO: other positive integer powers for which
// multiplication is more efficient than pow()
else if (integer == -1) {
return 1/value;
}
else if (integer == -2) {
return 1/value/value;
}
else if (integer == -3) {
return 1/value/value/value;
}
else {
//NOTE: this function is _really_ slow!
return Math.pow(value,integer);
}
}
}
|
package kbasesearchengine.events.handler;
import java.io.IOException;
import java.net.ConnectException;
import java.nio.file.Path;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
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.NoSuchElementException;
import java.util.Set;
import java.util.stream.Collectors;
import com.google.common.base.Optional;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.DateTimeFormatterBuilder;
import com.fasterxml.jackson.core.type.TypeReference;
import kbasesearchengine.common.GUID;
import kbasesearchengine.events.ChildStatusEvent;
import kbasesearchengine.events.StatusEvent;
import kbasesearchengine.events.StatusEventType;
import kbasesearchengine.events.StoredStatusEvent;
import kbasesearchengine.events.exceptions.FatalIndexingException;
import kbasesearchengine.events.exceptions.FatalRetriableIndexingException;
import kbasesearchengine.events.exceptions.IndexingException;
import kbasesearchengine.events.exceptions.IndexingExceptionUncheckedWrapper;
import kbasesearchengine.events.exceptions.RetriableIndexingException;
import kbasesearchengine.events.exceptions.RetriableIndexingExceptionUncheckedWrapper;
import kbasesearchengine.events.exceptions.UnprocessableEventIndexingException;
import kbasesearchengine.system.StorageObjectType;
import kbasesearchengine.tools.Utils;
import us.kbase.common.service.JsonClientException;
import us.kbase.common.service.Tuple11;
import us.kbase.common.service.Tuple9;
import us.kbase.common.service.UObject;
import us.kbase.common.service.UnauthorizedException;
import us.kbase.workspace.GetObjectInfo3Params;
import us.kbase.workspace.GetObjectInfo3Results;
import us.kbase.workspace.GetObjects2Params;
import us.kbase.workspace.GetObjects2Results;
import us.kbase.workspace.ListObjectsParams;
import us.kbase.workspace.ObjectData;
import us.kbase.workspace.ObjectIdentity;
import us.kbase.workspace.ObjectSpecification;
import us.kbase.workspace.ProvenanceAction;
import us.kbase.workspace.SubAction;
import us.kbase.workspace.WorkspaceClient;
import us.kbase.workspace.WorkspaceIdentity;
/** A handler for events generated by the workspace service.
* @author gaprice@lbl.gov
*
*/
public class WorkspaceEventHandler implements EventHandler {
private final static DateTimeFormatter DATE_PARSER =
new DateTimeFormatterBuilder()
.append(DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss"))
.appendOptional(DateTimeFormat.forPattern(".SSS").getParser())
.append(DateTimeFormat.forPattern("Z"))
.toFormatter();
//TODO TEST
/** The storage code for workspace events. */
public static final String STORAGE_CODE = "WS";
private static final int WS_BATCH_SIZE = 10_000;
private static final String META_SEARCH_TAGS = "searchtags";
private static final TypeReference<List<Tuple11<Long, String, String, String,
Long, String, Long, String, String, Long, Map<String, String>>>> OBJ_TYPEREF =
new TypeReference<List<Tuple11<Long, String, String, String,
Long, String, Long, String, String, Long, Map<String, String>>>>() {};
private static final TypeReference<Tuple9<Long, String, String, String, Long, String,
String, String, Map<String, String>>> WS_INFO_TYPEREF =
new TypeReference<Tuple9<Long, String, String, String, Long, String, String,
String,Map<String,String>>>() {};
private final CloneableWorkspaceClient ws;
/** Create a handler.
* @param clonableWorkspaceClient a workspace client to use when contacting the workspace
* service.
*/
public WorkspaceEventHandler(final CloneableWorkspaceClient clonableWorkspaceClient) {
Utils.nonNull(clonableWorkspaceClient, "clonableWorkspaceClient");
ws = clonableWorkspaceClient;
}
@Override
public String getStorageCode() {
return STORAGE_CODE;
}
@Override
public SourceData load(final GUID guid, final Path file)
throws IndexingException, RetriableIndexingException {
Utils.nonNull(guid, "guid");
return load(Arrays.asList(guid), file);
}
@Override
public SourceData load(final List<GUID> guids, final Path file)
throws IndexingException, RetriableIndexingException {
Utils.nonNull(guids, "guids");
Utils.noNulls(guids, "null item in guids");
Utils.nonNull(file, "file");
final ObjectData ret = getObjectData(guids, file);
final List<String> tags = getTags(ret);
// we'll assume here that there's only one provenance action. This may need more thought
// if that's not true.
final ProvenanceAction pa = ret.getProvenance().isEmpty() ?
null : ret.getProvenance().get(0);
String copier = ret.getInfo().getE6();
if (ret.getCopied() == null && ret.getCopySourceInaccessible() == 0) {
copier = null;
}
final SourceData.Builder b = SourceData.getBuilder(
ret.getData(), ret.getInfo().getE2(), ret.getCreator())
.withNullableCopier(copier)
.withNullableMD5(ret.getInfo().getE9());
//TODO CODE get the timestamp from ret rather than using event timestamp
for (final String tag: tags) {
b.withSourceTag(tag);
}
if (pa != null) {
b.withNullableModule(pa.getService())
.withNullableMethod(pa.getMethod())
.withNullableVersion(pa.getServiceVer());
/* this is taking specific knowledge about how the KBase execution engine
* works into account, which I'm not sure is a good idea, but for now it'll do
*/
if (pa.getService() != null &&
pa.getMethod() != null &&
pa.getSubactions() != null &&
!pa.getSubactions().isEmpty()) {
final String modmeth = pa.getService() + "." + pa.getMethod();
for (final SubAction sa: pa.getSubactions()) {
if (modmeth.equals(sa.getName())) {
b.withNullableCommitHash(sa.getCommit());
}
}
}
}
return b.build();
}
private List<String> getTags(final ObjectData objectdata)
throws RetriableIndexingException, IndexingException {
final String tags = getWorkspaceInfoInternal(objectdata.getInfo().getE7()).getE9()
.get(META_SEARCH_TAGS);
final List<String> ret = new LinkedList<>();
if (tags != null) {
for (String tag: tags.split(",")) {
tag = tag.trim();
if (!tag.isEmpty()) {
ret.add(tag);
}
}
}
return ret;
}
/** Parse a date emitted from the workspace to epoch millis.
* @param workspaceFormattedDate a workspace timestamp.
* @return epoch millis.
*/
public static long parseDateToEpochMillis(final String workspaceFormattedDate) {
return DATE_PARSER.parseDateTime(workspaceFormattedDate).getMillis();
}
private Tuple9<Long, String, String, String, Long, String,
String, String, Map<String, String>> getWorkspaceInfoInternal(
final long workspaceID)
throws RetriableIndexingException, IndexingException {
try {
return getWorkspaceInfo(workspaceID);
} catch (IOException e) {
throw handleException(e);
} catch (JsonClientException e) {
throw handleException(e);
}
}
/** Get the workspace information for a workspace from the workspace service to which this
* handler is communicating.
* @param workspaceID the integer ID of the workspace.
* @return the workspace info as returned from the workspace.
* @throws IOException if an IO exception occurs.
* @throws JsonClientException if an error retrieving the data occurs.
*/
public Tuple9<Long, String, String, String, Long, String,
String, String, Map<String, String>> getWorkspaceInfo(
final long workspaceID)
throws IOException, JsonClientException {
final Map<String, Object> command = new HashMap<>();
command.put("command", "getWorkspaceInfo");
command.put("params", new WorkspaceIdentity().withId(workspaceID));
return ws.getClient().administer(new UObject(command))
.asClassInstance(WS_INFO_TYPEREF);
}
/** Get the workspace information for an object from the workspace service to which this
* handler is communicating.
* @param workspaceID the integer ID of the workspace.
* @param objectId the integer ID of the object.
* @return the object info as returned from the workspace.
* @throws IOException if an IO exception occurs.
* @throws JsonClientException if an error retrieving the data occurs.
*/
public GetObjectInfo3Results getObjectInfo(
final long workspaceID,
final long objectId)
throws IOException, JsonClientException {
final ObjectSpecification os = new ObjectSpecification().withRef(
Long.toString(workspaceID) + "/" + Long.toString(objectId));
final List<ObjectSpecification> getInfoInput = new ArrayList<>();
getInfoInput.add(os);
Map<String, Object> command = new HashMap<>();
command.put("command", "getObjectInfo");
command.put("params", new GetObjectInfo3Params().withObjects(getInfoInput));
return ws.getClient().administer(new UObject(command))
.asClassInstance(GetObjectInfo3Results.class);
}
private ObjectData getObjectData(final List<GUID> guids, final Path file)
throws RetriableIndexingException, IndexingException {
// create a new client since we're setting a file for the next response
// fixes race conditions
// a clone method would be handy
final WorkspaceClient wc = ws.getClientClone();
wc.setStreamingModeOn(true);
wc._setFileForNextRpcResponse(file.toFile());
final Map<String, Object> command = new HashMap<>();
command.put("command", "getObjects");
command.put("params", new GetObjects2Params().withObjects(
Arrays.asList(new ObjectSpecification().withRef(toWSRefPath(guids)))));
try {
return wc.administer(new UObject(command))
.asClassInstance(GetObjects2Results.class)
.getData().get(0);
} catch (IOException e) {
throw handleException(e);
} catch (JsonClientException e) {
throw handleException(e);
}
}
private static IndexingException handleException(final JsonClientException e) {
if (e instanceof UnauthorizedException) {
return new FatalIndexingException(e.getMessage(), e);
}
if (e.getMessage() == null) {
return new UnprocessableEventIndexingException(
"Null error message from workspace server", e);
} else if (e.getMessage().toLowerCase().contains("login")) {
return new FatalIndexingException(
"Workspace credentials are invalid: " + e.getMessage(), e);
} else if (e.getMessage().toLowerCase().contains("did not start up properly")) {
return new FatalIndexingException("Fatal error returned from workspace: " +
e.getMessage(), e);
} else {
// this may need to be expanded, some errors may require retries or total failures
return new UnprocessableEventIndexingException(
"Unrecoverable error from workspace on fetching object: " + e.getMessage(),
e);
}
}
private static RetriableIndexingException handleException(final IOException e) {
if (e instanceof ConnectException) {
return new FatalRetriableIndexingException(e.getMessage(), e);
}
return new RetriableIndexingException(e.getMessage(), e);
}
@Override
public Map<GUID, String> buildReferencePaths(
final List<GUID> refpath,
final Set<GUID> refs) {
final String refPrefix = buildRefPrefix(refpath);
return refs.stream().collect(Collectors.toMap(r -> r, r -> refPrefix + r.toRefString()));
}
@Override
public Set<ResolvedReference> resolveReferences(
final List<GUID> refpath,
final Set<GUID> refs)
throws RetriableIndexingException, IndexingException {
// may need to split into batches
final String refPrefix = buildRefPrefix(refpath);
final List<GUID> orderedRefs = new ArrayList<>(refs);
final List<ObjectSpecification> getInfoInput = orderedRefs.stream().map(
ref -> new ObjectSpecification().withRef(refPrefix + ref.toRefString())).collect(
Collectors.toList());
final Map<String, Object> command = new HashMap<>();
command.put("command", "getObjectInfo");
command.put("params", new GetObjectInfo3Params().withObjects(getInfoInput));
final GetObjectInfo3Results res;
try {
res = ws.getClient().administer(new UObject(command))
.asClassInstance(GetObjectInfo3Results.class);
} catch (IOException e) {
throw handleException(e);
} catch (JsonClientException e) {
throw handleException(e);
}
final Set<ResolvedReference> ret = new HashSet<>();
for (int i = 0; i < orderedRefs.size(); i++) {
ret.add(createResolvedReference(orderedRefs.get(i), res.getInfos().get(i)));
}
return ret;
}
private String buildRefPrefix(final List<GUID> refpath) {
//TODO CODE check storage code
return refpath == null || refpath.isEmpty() ? "" :
WorkspaceEventHandler.toWSRefPath(refpath) + ";";
}
private ResolvedReference createResolvedReference(
final GUID guid,
final Tuple11<Long, String, String, String, Long, String, Long, String, String,
Long, Map<String, String>> obj) {
return new ResolvedReference(
guid,
new GUID(STORAGE_CODE, Math.toIntExact(obj.getE7()), obj.getE1() + "",
Math.toIntExact(obj.getE5()), null, null),
new StorageObjectType(STORAGE_CODE, obj.getE3().split("-")[0],
Integer.parseInt(obj.getE3().split("-")[1].split("\\.")[0])),
Instant.ofEpochMilli(parseDateToEpochMillis(obj.getE4())));
}
@Override
public boolean isExpandable(final StoredStatusEvent parentEvent) {
checkStorageCode(parentEvent);
return EXPANDABLES.contains(parentEvent.getEvent().getEventType());
};
private static final Set<StatusEventType> EXPANDABLES = new HashSet<>(Arrays.asList(
StatusEventType.NEW_ALL_VERSIONS,
StatusEventType.COPY_ACCESS_GROUP,
StatusEventType.DELETE_ACCESS_GROUP,
StatusEventType.PUBLISH_ACCESS_GROUP,
StatusEventType.UNPUBLISH_ACCESS_GROUP));
@Override
public Iterable<ChildStatusEvent> expand(final StoredStatusEvent eventWID)
throws IndexingException, RetriableIndexingException {
checkStorageCode(eventWID);
final StatusEvent event = eventWID.getEvent();
if (StatusEventType.NEW_ALL_VERSIONS.equals(event.getEventType())) {
return handleNewAllVersions(eventWID);
} else if (StatusEventType.COPY_ACCESS_GROUP.equals(event.getEventType())) {
return handleNewAccessGroup(eventWID);
} else if (StatusEventType.DELETE_ACCESS_GROUP.equals(event.getEventType())) {
return handleDeletedAccessGroup(eventWID);
} else if (StatusEventType.PUBLISH_ACCESS_GROUP.equals(event.getEventType())) {
return handlePublishAccessGroup(eventWID, StatusEventType.PUBLISH_ALL_VERSIONS);
} else if (StatusEventType.UNPUBLISH_ACCESS_GROUP.equals(event.getEventType())) {
return handlePublishAccessGroup(eventWID, StatusEventType.UNPUBLISH_ALL_VERSIONS);
} else {
throw new IllegalArgumentException("Unexpandable event type: " + event.getEventType());
}
}
private void checkStorageCode(final StoredStatusEvent event) {
checkStorageCode(event.getEvent().getStorageCode());
}
private void checkStorageCode(final String storageCode) {
if (!STORAGE_CODE.equals(storageCode)) {
throw new IllegalArgumentException("This handler only accepts "
+ STORAGE_CODE + "events");
}
}
private Iterable<ChildStatusEvent> handlePublishAccessGroup(
final StoredStatusEvent event,
final StatusEventType newType)
throws RetriableIndexingException, IndexingException {
long workspaceId = (long) event.getEvent().getAccessGroupId().get();
final long objcount;
try {
objcount = getWorkspaceInfo(workspaceId).getE5();
} catch (IOException e) {
throw handleException(e);
} catch (JsonClientException e) {
throw handleException(e);
}
return new Iterable<ChildStatusEvent>() {
@Override
public Iterator<ChildStatusEvent> iterator() {
return new StupidWorkspaceObjectIterator(event, objcount, newType);
}
};
}
private Iterable<ChildStatusEvent> handleDeletedAccessGroup(final StoredStatusEvent event) {
return new Iterable<ChildStatusEvent>() {
@Override
public Iterator<ChildStatusEvent> iterator() {
return new StupidWorkspaceObjectIterator(
event, Long.parseLong(event.getEvent().getAccessGroupObjectId().get()),
StatusEventType.DELETE_ALL_VERSIONS);
}
};
}
/* This is not efficient, but allows parallelizing events by decomposing the event
* to per object events. That means the parallelization can run on a per object basis.
*/
private static class StupidWorkspaceObjectIterator implements Iterator<ChildStatusEvent> {
private final StoredStatusEvent event;
private final StatusEventType newType;
private final long maxObjectID;
private long counter = 0;
public StupidWorkspaceObjectIterator(
final StoredStatusEvent event,
final long maxObjectID,
final StatusEventType newType) {
this.event = event;
this.maxObjectID = maxObjectID;
this.newType = newType;
}
@Override
public boolean hasNext() {
return counter < maxObjectID;
}
@Override
public ChildStatusEvent next() {
if (counter >= maxObjectID) {
throw new NoSuchElementException();
}
return new ChildStatusEvent(
StatusEvent.getBuilder(STORAGE_CODE, event.getEvent().getTimestamp(), newType)
.withNullableAccessGroupID(event.getEvent().getAccessGroupId().get())
.withNullableObjectID(++counter + "")
.build(),
event.getId());
}
}
private Iterable<ChildStatusEvent> handleNewAccessGroup(final StoredStatusEvent event) {
return new Iterable<ChildStatusEvent>() {
@Override
public Iterator<ChildStatusEvent> iterator() {
return new WorkspaceIterator(ws.getClient(), event);
}
};
}
private static class WorkspaceIterator implements Iterator<ChildStatusEvent> {
private final WorkspaceClient ws;
private final StoredStatusEvent sourceEvent;
private final int accessGroupId;
private long processedObjs = 0;
private LinkedList<ChildStatusEvent> queue = new LinkedList<>();
public WorkspaceIterator(final WorkspaceClient ws, final StoredStatusEvent sourceEvent) {
this.ws = ws;
this.sourceEvent = sourceEvent;
this.accessGroupId = sourceEvent.getEvent().getAccessGroupId().get();
fillQueue();
}
@Override
public boolean hasNext() {
return !queue.isEmpty();
}
@Override
public ChildStatusEvent next() {
if (queue.isEmpty()) {
throw new NoSuchElementException();
}
final ChildStatusEvent event = queue.removeFirst();
if (queue.isEmpty()) {
fillQueue();
}
return event;
}
private void fillQueue() {
// as of 0.7.2 if only object id filters are used, workspace will sort by
// ws asc, obj id asc, ver dec
final ArrayList<ChildStatusEvent> events;
final Map<String, Object> command = new HashMap<>();
command.put("command", "listObjects");
command.put("params", new ListObjectsParams()
.withIds(Arrays.asList((long) accessGroupId))
.withMinObjectID((long) processedObjs + 1)
.withShowHidden(1L)
.withShowAllVersions(1L));
try {
events = buildEvents(sourceEvent, ws.administer(new UObject(command))
.asClassInstance(OBJ_TYPEREF));
} catch (IOException e) {
throw new RetriableIndexingExceptionUncheckedWrapper(handleException(e));
} catch (JsonClientException e) {
throw new IndexingExceptionUncheckedWrapper(handleException(e));
}
if (events.isEmpty()) {
return;
}
// might want to do something smarter about the extra parse at some point
final long first = Long.parseLong(events.get(0).getEvent()
.getAccessGroupObjectId().get());
final ChildStatusEvent lastEv = events.get(events.size() - 1);
long last = Long.parseLong(lastEv.getEvent().getAccessGroupObjectId().get());
// it cannot be true that there were <10K objects and the last object returned's
// version was != 1
if (first == last && events.size() == WS_BATCH_SIZE &&
lastEv.getEvent().getVersion().get() != 1) {
//holy poopsnacks, a > 10K version object
queue.addAll(events);
for (int i = lastEv.getEvent().getVersion().get(); i > 1; i =- WS_BATCH_SIZE) {
fillQueueWithVersions(first, i - WS_BATCH_SIZE, i);
}
} else {
// could be smarter about this later, rather than throwing away all the versions of
// the last object
// not too many objects will have enough versions to matter
if (lastEv.getEvent().getVersion().get() != 1) {
last
}
for (final ChildStatusEvent e: events) {
if (Long.parseLong(e.getEvent().getAccessGroupObjectId().get()) > last) { // *&@ parse
break;
}
queue.add(e);
}
}
processedObjs = last;
}
// startVersion = inclusive, endVersion = exclusive
private void fillQueueWithVersions(
final long objectID,
int startVersion,
final int endVersion) {
if (startVersion < 1) {
startVersion = 1;
}
final List<ObjectSpecification> objs = new LinkedList<>();
for (int ver = startVersion; ver < endVersion; ver++) {
objs.add(new ObjectSpecification()
.withWsid((long) accessGroupId)
.withObjid(objectID)
.withVer((long) ver));
}
final Map<String, Object> command = new HashMap<>();
command.put("command", "getObjectInfo");
command.put("params", new GetObjectInfo3Params().withObjects(objs));
try {
queue.addAll(buildEvents(sourceEvent, ws.administer(new UObject(command))
.asClassInstance(GetObjectInfo3Results.class).getInfos()));
} catch (IOException e) {
throw new RetriableIndexingExceptionUncheckedWrapper(handleException(e));
} catch (JsonClientException e) {
throw new IndexingExceptionUncheckedWrapper(handleException(e));
}
}
}
private ArrayList<ChildStatusEvent> handleNewAllVersions(final StoredStatusEvent eventWID)
throws IndexingException, RetriableIndexingException {
final StatusEvent event = eventWID.getEvent();
final long objid;
try {
objid = Long.parseLong(event.getAccessGroupObjectId().get());
} catch (NumberFormatException ne) {
throw new UnprocessableEventIndexingException("Illegal workspace object id: " +
event.getAccessGroupObjectId());
}
final Map<String, Object> command = new HashMap<>();
command.put("command", "getObjectHistory");
command.put("params", new ObjectIdentity()
.withWsid((long) event.getAccessGroupId().get())
.withObjid(objid));
try {
return buildEvents(eventWID, ws.getClient().administer(new UObject(command))
.asClassInstance(OBJ_TYPEREF));
} catch (IOException e) {
throw handleException(e);
} catch (JsonClientException e) {
throw handleException(e);
}
}
private static ArrayList<ChildStatusEvent> buildEvents(
final StoredStatusEvent originalEvent,
final List<Tuple11<Long, String, String, String, Long, String, Long, String,
String, Long, Map<String, String>>> objects) {
final ArrayList<ChildStatusEvent> events = new ArrayList<>();
for (final Tuple11<Long, String, String, String, Long, String, Long, String, String,
Long, Map<String, String>> obj: objects) {
events.add(buildEvent(originalEvent, obj));
}
return events;
}
private static ChildStatusEvent buildEvent(
final StoredStatusEvent origEvent,
final Tuple11<Long, String, String, String, Long, String, Long, String, String,
Long, Map<String, String>> obj) {
final StorageObjectType storageObjectType = new StorageObjectType(
STORAGE_CODE, obj.getE3().split("-")[0],
Integer.parseInt(obj.getE3().split("-")[1].split("\\.")[0]));
return new ChildStatusEvent(StatusEvent.getBuilder(
storageObjectType,
Instant.ofEpochMilli(parseDateToEpochMillis(obj.getE4())),
StatusEventType.NEW_VERSION)
.withNullableAccessGroupID(origEvent.getEvent().getAccessGroupId().get())
.withNullableObjectID(obj.getE1() + "")
.withNullableVersion(Math.toIntExact(obj.getE5()))
.withNullableisPublic(origEvent.getEvent().isPublic().get())
.build(),
origEvent.getId());
}
private static String toWSRefPath(final List<GUID> objectRefPath) {
final List<String> refpath = new LinkedList<>();
for (final GUID g: objectRefPath) {
if (!g.getStorageCode().equals("WS")) {
throw new IllegalArgumentException(String.format(
"GUID %s is not a workspace object", g));
}
refpath.add(g.getAccessGroupId() + "/" + g.getAccessGroupObjectId() + "/" +
g.getVersion());
}
return String.join(";", refpath);
}
@Override
public StatusEvent updateEvent(final StatusEvent ev)
throws IndexingException,
RetriableIndexingException {
// brute force get latest state and update event as events
// can be played out of order in the case of failed events being replayed.
StatusEventType eventType = ev.getEventType();
String accessGrpId = ev.getAccessGroupId().get().toString();
String objectId = ev.getAccessGroupObjectId().get();
// update a rename event
if (eventType.equals(StatusEventType.RENAME_ALL_VERSIONS)) {
// check if name has changed and update state of lastestName
try {
GetObjectInfo3Results objInfo =
getObjectInfo(Long.decode(accessGrpId), Long.decode(objectId));
String latestName = objInfo.getInfos().get(0).getE2();
if( ev.getNewName().equals(latestName) )
return ev;
else {
return StatusEvent.
getBuilder(ev.getStorageObjectType().get(), ev.getTimestamp(), eventType).
withNullableAccessGroupID(Integer.decode(accessGrpId)).
withNullableObjectID(objectId).
withNullableVersion(ev.getVersion().get()).
withNullableNewName(latestName).build();
}
} catch (IOException ex) {
throw handleException(ex);
} catch (JsonClientException ex) {
throw handleException(ex);
}
}
// update a (UN)PUBLISH_ALL_VERSIONS event
if (eventType.equals(StatusEventType.PUBLISH_ALL_VERSIONS) ||
eventType.equals(StatusEventType.UNPUBLISH_ALL_VERSIONS )) {
try {
final String isPublic = getWorkspaceInfo(Long.decode(accessGrpId)).getE7();
Boolean latestIsPublic = (isPublic == "n") ? true: false;
if (latestIsPublic) {
return StatusEvent.
getBuilder(ev.getStorageObjectType().get(), ev.getTimestamp(),
StatusEventType.PUBLISH_ALL_VERSIONS).
withNullableAccessGroupID(Integer.decode(accessGrpId)).
withNullableObjectID(objectId).
withNullableVersion(ev.getVersion().get()).
withNullableisPublic(latestIsPublic).build();
} else {
return StatusEvent.
getBuilder(ev.getStorageObjectType().get(), ev.getTimestamp(),
StatusEventType.UNPUBLISH_ALL_VERSIONS).
withNullableAccessGroupID(Integer.decode(accessGrpId)).
withNullableObjectID(objectId).
withNullableVersion(ev.getVersion().get()).
withNullableisPublic(latestIsPublic).build();
}
} catch (IOException ex) {
throw handleException(ex);
} catch (JsonClientException ex) {
throw handleException(ex);
}
}
// update a (UN)DELETE_ALL_VERSIONS event
if (eventType.equals(StatusEventType.DELETE_ALL_VERSIONS) ||
eventType.equals(StatusEventType.UNDELETE_ALL_VERSIONS )) {
Map<String, Object> command;
// if source data object does not exist then update event as a
// DELETE_ALL_VERSIONS event
command = new HashMap<>();
command.put("command", "listObjects");
command.put("params", new ListObjectsParams().
withIds(Arrays.asList(Long.decode(accessGrpId))));
try {
boolean objidExists = false;
final List<List> objList = ws.getClient().administer(new UObject(command))
.asClassInstance(List.class);
for (List obj: objList) {
long id = (long)((Integer)obj.get(0)).intValue();
if (id == Long.decode(objectId)) {
objidExists = true;
break;
}
}
if (!objidExists) {
return StatusEvent.
getBuilder(ev.getStorageObjectType().get(), ev.getTimestamp(),
StatusEventType.DELETE_ALL_VERSIONS).
withNullableAccessGroupID(Integer.decode(accessGrpId)).
withNullableObjectID(objectId).build();
}
} catch (IOException ex) {
throw handleException(ex);
} catch (JsonClientException ex) {
throw handleException(ex);
}
// if source data object is deleted then update event as a DELETE_ALL_VERSIONS event
command = new HashMap<>();
command.put("command", "listObjects");
command.put("params", new ListObjectsParams().
withShowOnlyDeleted(1L).
withIds(Arrays.asList(Long.decode(accessGrpId))));
final List<Tuple11<Long,String,String,String,Long,String,Long,String,String,Long,
Map<String,String>>> deletedObjList;
try {
deletedObjList = ws.getClient().administer(new UObject(command))
.asClassInstance(List.class);
for (Tuple11<Long,String,String,String,Long,String,Long,String,
String,Long,Map<String,String>> obj: deletedObjList) {
long deletedObjid = obj.getE1().longValue();
if (deletedObjid == Long.decode(objectId)) {
return StatusEvent.
getBuilder(ev.getStorageObjectType().get(), ev.getTimestamp(),
StatusEventType.DELETE_ALL_VERSIONS).
withNullableAccessGroupID(Integer.decode(accessGrpId)).
withNullableObjectID(objectId).build();
}
}
} catch (IOException ex) {
throw handleException(ex);
} catch (JsonClientException ex) {
throw handleException(ex);
}
// source data object exists so update event as UNDELETE_ALL_VERSIONS
return StatusEvent.
getBuilder(ev.getStorageObjectType().get(), ev.getTimestamp(),
StatusEventType.UNDELETE_ALL_VERSIONS).
withNullableAccessGroupID(Integer.decode(accessGrpId)).
withNullableObjectID(objectId).build();
}
// no update needed for other event types
return ev;
}
}
|
package org.jasig.portal.services;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jasig.portal.ChannelDefinition;
import org.jasig.portal.UserProfile;
import org.jasig.portal.layout.node.IUserLayoutChannelDescription;
import org.jasig.portal.layout.node.IUserLayoutFolderDescription;
import org.jasig.portal.security.IPerson;
import org.jasig.portal.services.stats.DoNothingStatsRecorder;
import org.jasig.portal.services.stats.IStatsRecorder;
import org.jasig.portal.services.stats.StatsRecorderLayoutEventListener;
import org.jasig.portal.services.stats.StatsRecorderSettings;
import org.jasig.portal.spring.PortalApplicationContextFacade;
import org.springframework.beans.BeansException;
/**
*
* Static cover for the primary instance of IStatsRecorder.
*
* This class makes the primary instance of IStatsRecorder defined as a
* Spring bean named "statsRecorder" available via static lookup.
*
* Various parts of the portal call
* the static methods in this service to record events such as
* when a user logs in, logs out, and subscribes to a channel.
* We forward those method calls to the configured instance of IStatsRecorder.
*
* Object instances configured via Spring and therefore ammenable to Dependency
* Injection can and probably should receive their IStatsRecorded instance via
* injection rather than statically accessing this class.
*
* @author Ken Weiner, kweiner@unicon.net
* @version $Revision$ $Date$
*/
public final class StatsRecorder {
/**
* The name of the Spring-configured IStatsRecorder instance to which we
* expect to delegate.
*/
public static final String BACKING_BEAN_NAME = "statsRecorder";
private static final Log log = LogFactory.getLog(StatsRecorder.class);
private static IStatsRecorder STATS_RECORDER;
/*
* Static block in which we discover our backing IStatsRecorder.
*/
static {
synchronized (StatsRecorder.class) {
try {
// our first preference is to get the stats recorder from the
// PortalApplicationContextFacade (which fronts Spring bean configuration)
STATS_RECORDER = (IStatsRecorder) PortalApplicationContextFacade.getPortalApplicationContext().getBean(BACKING_BEAN_NAME, IStatsRecorder.class);
} catch (BeansException be) {
// don't let exceptions about misconfiguration of the stats recorder propogate
// to the uPortal code that called StatsRecorder. Instead, fall back on
// failing to record anything, logging the configuration problem.
log.error("Unable to retrieve IStatsRecorder instance from Portal Application Context: is there a bean of name [" + BACKING_BEAN_NAME + "] ?", be);
STATS_RECORDER = new DoNothingStatsRecorder();
}
}
}
private StatsRecorder() {
// do nothing
// we're a static cover, no need to instantiate.
}
/**
* Creates an instance of a
* <code>StatsRecorderLayoutEventListener</code>.
*
* There is currently no difference between calling this method and using the
* StatsRecorderLayoutEventListener constructor directly.
*
* @return a new stats recorder layout event listener instance
*/
public final static StatsRecorderLayoutEventListener newLayoutEventListener(IPerson person, UserProfile profile) {
return new StatsRecorderLayoutEventListener(person, profile);
}
/**
* Record the successful login of a user.
* @param person the person who is logging in
*/
public static void recordLogin(IPerson person) {
STATS_RECORDER.recordLogin(person);
}
/**
* Record the logout of a user.
* @param person the person who is logging out
*/
public static void recordLogout(IPerson person) {
STATS_RECORDER.recordLogout(person);
}
/**
* Record that a new session is created for a user.
* @param person the person whose session is being created
*/
public static void recordSessionCreated(IPerson person) {
STATS_RECORDER.recordSessionCreated(person);
}
/**
* Record that a user's session is destroyed
* (when the user logs out or his/her session
* simply times out)
* @param person the person whose session is ending
*/
public static void recordSessionDestroyed(IPerson person) {
STATS_RECORDER.recordSessionDestroyed(person);
}
/**
* Record that a new channel is being published
* @param person the person publishing the channel
* @param channelDef the channel being published
*/
public static void recordChannelDefinitionPublished(IPerson person, ChannelDefinition channelDef) {
STATS_RECORDER.recordChannelDefinitionPublished(person, channelDef);
}
/**
* Record that an existing channel is being modified
* @param person the person modifying the channel
* @param channelDef the channel being modified
*/
public static void recordChannelDefinitionModified(IPerson person, ChannelDefinition channelDef) {
STATS_RECORDER.recordChannelDefinitionModified(person, channelDef);
}
/**
* Record that a channel is being removed
* @param person the person removing the channel
* @param channelDef the channel being modified
*/
public static void recordChannelDefinitionRemoved(IPerson person, ChannelDefinition channelDef) {
STATS_RECORDER.recordChannelDefinitionRemoved(person, channelDef);
}
/**
* Record that a channel is being added to a user layout
* @param person the person adding the channel
* @param profile the profile of the layout to which the channel is being added
* @param channelDesc the channel being subscribed to
*/
public static void recordChannelAddedToLayout(IPerson person, UserProfile profile, IUserLayoutChannelDescription channelDesc) {
STATS_RECORDER.recordChannelAddedToLayout(person, profile, channelDesc);
}
/**
* Record that a channel is being updated in a user layout
* @param person the person updating the channel
* @param profile the profile of the layout in which the channel is being updated
* @param channelDesc the channel being updated
*/
public static void recordChannelUpdatedInLayout(IPerson person, UserProfile profile, IUserLayoutChannelDescription channelDesc) {
STATS_RECORDER.recordChannelUpdatedInLayout(person, profile, channelDesc);
}
/**
* Record that a channel is being moved in a user layout
* @param person the person moving the channel
* @param profile the profile of the layout in which the channel is being moved
* @param channelDesc the channel being moved
*/
public static void recordChannelMovedInLayout(IPerson person, UserProfile profile, IUserLayoutChannelDescription channelDesc) {
STATS_RECORDER.recordChannelMovedInLayout(person, profile, channelDesc);
}
/**
* Record that a channel is being removed from a user layout
* @param person the person removing the channel
* @param profile the profile of the layout to which the channel is being added
* @param channelDesc the channel being removed from a user layout
*/
public static void recordChannelRemovedFromLayout(IPerson person, UserProfile profile, IUserLayoutChannelDescription channelDesc) {
STATS_RECORDER.recordChannelRemovedFromLayout(person, profile, channelDesc);
}
/**
* Record that a folder is being added to a user layout
* @param person the person adding the folder
* @param profile the profile of the layout to which the folder is being added
* @param folderDesc the folder being subscribed to
*/
public static void recordFolderAddedToLayout(IPerson person, UserProfile profile, IUserLayoutFolderDescription folderDesc) {
STATS_RECORDER.recordFolderAddedToLayout(person, profile, folderDesc);
}
/**
* Record that a folder is being updated in a user layout
* @param person the person updating the folder
* @param profile the profile of the layout in which the folder is being updated
* @param folderDesc the folder being updated
*/
public static void recordFolderUpdatedInLayout(IPerson person, UserProfile profile, IUserLayoutFolderDescription folderDesc) {
STATS_RECORDER.recordFolderUpdatedInLayout(person, profile, folderDesc);
}
/**
* Record that a folder is being moved in a user layout
* @param person the person moving the folder
* @param profile the profile of the layout in which the folder is being moved
* @param folderDesc the folder being moved
*/
public static void recordFolderMovedInLayout(IPerson person, UserProfile profile, IUserLayoutFolderDescription folderDesc) {
STATS_RECORDER.recordFolderMovedInLayout(person, profile, folderDesc);
}
/**
* Record that a folder is being removed from a user layout
* @param person the person removing the folder
* @param profile the profile of the layout to which the folder is being added
* @param folderDesc the folder being removed from a user layout
*/
public static void recordFolderRemovedFromLayout(IPerson person, UserProfile profile, IUserLayoutFolderDescription folderDesc) {
STATS_RECORDER.recordFolderRemovedFromLayout(person, profile, folderDesc);
}
/**
* Record that a channel is being instantiated
* @param person the person for whom the channel is instantiated
* @param profile the profile of the layout for whom the channel is instantiated
* @param channelDesc the channel being instantiated
*/
public static void recordChannelInstantiated(IPerson person, UserProfile profile, IUserLayoutChannelDescription channelDesc) {
STATS_RECORDER.recordChannelInstantiated(person, profile, channelDesc);
}
/**
* Record that a channel is being rendered
* @param person the person for whom the channel is rendered
* @param profile the profile of the layout for whom the channel is rendered
* @param channelDesc the channel being rendered
*/
public static void recordChannelRendered(IPerson person, UserProfile profile, IUserLayoutChannelDescription channelDesc) {
STATS_RECORDER.recordChannelRendered(person, profile, channelDesc);
}
/**
* Record that a channel is being targeted. In other words,
* the user is interacting with the channel via either a
* hyperlink or form submission.
* @param person the person interacting with the channel
* @param profile the profile of the layout in which the channel resides
* @param channelDesc the channel being targeted
*/
public static void recordChannelTargeted(IPerson person, UserProfile profile, IUserLayoutChannelDescription channelDesc) {
STATS_RECORDER.recordChannelTargeted(person, profile, channelDesc);
}
/**
* This method is deprecated. Stats recorder settings are no longer necessarily
* global. This method (continues to) access information about only one
* particular way in which StatsRecorder can be configured, that of portal.properties
* entries specifying booleans about which kinds of statistics should be recorded,
* fronting the StatsRecorderSettings static singleton.
*
* Instead of using the Static Singleton (anti-)pattern, you can instead wire
* together and configure your IStatsRecorder as a Spring-managed bean named
* "statsRecorder" and there apply, in a strongly typed and more flexible way,
* your desired statistics recording configuration.
*
* Specifically, the ConditionalStatsRecorder wrapper now provides a
* JavaBean-properties approach to querying the settings that were previously
* accessible via this method.
*
* Note that since StatsRecorderSettings is a Static Singleton, this implementation
* of this method continues to do what the 2.5.0 implementation did. The change
* since 2.5.0 is that StatsRecorderSettings is no longer necessarily
* controlling of StatsRecorder behavior.
*
* Gets the value of a particular stats recorder from StatsRecorderSettings.
* Possible settings are available from <code>StatsRecorderSettings</code>.
* For example: <code>StatsRecorder.get(StatsRecorderSettings.RECORD_LOGIN)</code>
* @param setting the setting
* @return the value for the setting
* @deprecated since uPortal 2.5.1, recorder settings are no longer global
*/
public static boolean get(int setting) {
return StatsRecorderSettings.instance().get(setting);
}
/**
* This method is deprecated. Stats recorder settings are no longer necessarily
* global. This method (continues to) provide a very thin layer in front of just
* one particular way in which StatsRecorder can be configured, that of
* portal.poperties specifying booleans about which kinds of statistics should be
* recorded, fronting the StatsRecorderSettings static singleton.
*
* Instead of using the Static Singleton (anti-)patterh, you can instead wire
* together and configure your IStatsRecorder as a Spring-managed bean named
* "statsRecorder" and there apply, in a strongly typed and more flexible way,
* your desired statistics recording configuration.
*
* Specifically, the ConditionalStatsRecorder wrapper now provides a
* JavaBean-properties approach to configuring the stats recorder even filtering
* that was previously configurable via this method.
*
* Note that since StatsRecorderSettings is a Static Singleton, this implementation
* of this method continues to do what the 2.5.0 implementation did. The change
* since 2.5.-0 is that StatsRecorderSettings is no longer necessarily controlling
* of StatsRecorderBehavior.
*
* CALLING THIS METHOD MAY HAVE NO EFFECT ON StatsRecorder BEHAVIOR.
* This method will only have effect if the IStatsRecorder implementation
* is actually using StatsRecorderSettings.
*
* Sets the value of a particular stats recorder setting.
* Possible settings are available from <code>StatsRecorderSettings</code>.
* For example: <code>StatsRecorder.set(StatsRecorderSettings.RECORD_LOGIN, true)</code>
* @param setting the setting to change
* @param newValue the new value for the setting
* @deprecated since uPortal 2.5.1, recorder settings are no longer necessarily global
*/
public static void set(int setting, boolean newValue) {
StatsRecorderSettings.instance().set(setting, newValue);
}
}
|
package org.wysaid.view;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.PixelFormat;
import android.graphics.SurfaceTexture;
import android.media.MediaPlayer;
import android.net.Uri;
import android.opengl.GLES20;
import android.opengl.GLSurfaceView;
import android.opengl.GLUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Surface;
import org.wysaid.myUtils.Common;
import org.wysaid.texUtils.TextureRenderer;
import org.wysaid.texUtils.TextureRendererDrawOrigin;
import org.wysaid.texUtils.TextureRendererMask;
import java.nio.IntBuffer;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
public class VideoPlayerGLSurfaceView extends GLSurfaceView implements GLSurfaceView.Renderer, SurfaceTexture.OnFrameAvailableListener {
public static final String LOG_TAG = Common.LOG_TAG;
public static boolean ENABLE_RESOLUTION_FIX = true;
public boolean mResolutionShouldFix = false;
private SurfaceTexture mSurfaceTexture;
private int mVideoTextureID;
private TextureRenderer mDrawer;
//setTextureRenderer OpenGL !
public void setTextureRenderer(TextureRenderer drawer) {
if(mDrawer == null) {
Log.e(LOG_TAG, "Invalid Drawer!");
return;
}
if(mDrawer != drawer) {
mDrawer.release();
mDrawer = drawer;
calcViewport();
}
}
private TextureRenderer.Viewport mRenderViewport = new TextureRenderer.Viewport();
private float[] mTransformMatrix = new float[16];
private boolean mIsUsingMask = false;
public boolean isUsingMask() {
return mIsUsingMask;
}
private float mMaskAspectRatio = 1.0f;
private float mDrawerFlipScaleX = 1.0f;
private float mDrawerFlipScaleY = 1.0f;
private int mViewWidth = 1000;
private int mViewHeight = 1000;
public int getViewWidth() {
return mViewWidth;
}
public int getViewheight() {
return mViewHeight;
}
private int mVideoWidth = 1000;
private int mVideoHeight = 1000;
private boolean mFitFullView = false;
public void setFitFullView(boolean fit) {
mFitFullView = fit;
if(mDrawer != null)
calcViewport();
}
private MediaPlayer mPlayer;
private Context mContext;
private Uri mVideoUri;
public interface PlayerInitializeCallback {
//player listener bufferupdateListener.
void initPlayer(MediaPlayer player);
}
public void setPlayerInitializeCallback(PlayerInitializeCallback callback) {
mPlayerInitCallback = callback;
}
PlayerInitializeCallback mPlayerInitCallback;
public interface PlayPreparedCallback {
void playPrepared(MediaPlayer player);
}
PlayPreparedCallback mPreparedCallback;
public interface PlayCompletionCallback {
void playComplete(MediaPlayer player);
/*
what : MEDIA_ERROR_UNKNOWN,
MEDIA_ERROR_SERVER_DIED
extra MEDIA_ERROR_IO
MEDIA_ERROR_MALFORMED
MEDIA_ERROR_UNSUPPORTED
MEDIA_ERROR_TIMED_OUT
returning false would cause the 'playComplete' to be called
*/
boolean playFailed(MediaPlayer mp, int what, int extra);
}
PlayCompletionCallback mPlayCompletionCallback;
public synchronized void setVideoUri(final Uri uri, final PlayPreparedCallback preparedCallback, final PlayCompletionCallback completionCallback) {
mVideoUri = uri;
mPreparedCallback = preparedCallback;
mPlayCompletionCallback = completionCallback;
if(mDrawer != null) {
queueEvent(new Runnable() {
@Override
public void run() {
Log.i(LOG_TAG, "setVideoUri...");
if (mSurfaceTexture == null || mVideoTextureID == 0) {
mVideoTextureID = Common.genSurfaceTextureID();
mSurfaceTexture = new SurfaceTexture(mVideoTextureID);
mSurfaceTexture.setOnFrameAvailableListener(VideoPlayerGLSurfaceView.this);
}
_useUri();
}
});
}
}
//bmp
//mask setMaskOK
// unsetMaskOK
public interface SetMaskBitmapCallback {
void setMaskOK(TextureRendererMask renderer);
void unsetMaskOK(TextureRenderer renderer);
}
public synchronized void setMaskBitmap(final Bitmap bmp, final boolean shouldRecycle) {
setMaskBitmap(bmp, shouldRecycle, null);
}
public synchronized void setMaskBitmap(final Bitmap bmp, final boolean shouldRecycle, final SetMaskBitmapCallback callback) {
queueEvent(new Runnable() {
@Override
public void run() {
if(bmp == null) {
Log.i(LOG_TAG, "Cancel Mask Bitmap!");
setMaskTexture(0, 1.0f);
if(callback != null) {
callback.unsetMaskOK(mDrawer);
}
return ;
}
Log.i(LOG_TAG, "Use Mask Bitmap!");
int texID[] = {0};
GLES20.glGenTextures(1, texID, 0);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, texID[0]);
GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, bmp, 0);
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_NEAREST);
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_NEAREST);
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE);
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE);
setMaskTexture(texID[0], bmp.getWidth() / (float) bmp.getHeight());
if(callback != null && mDrawer instanceof TextureRendererMask) {
callback.setMaskOK((TextureRendererMask)mDrawer);
}
if(shouldRecycle)
bmp.recycle();
}
});
}
public synchronized void setMaskTexture(int texID, float aspectRatio) {
Log.i(LOG_TAG, "setMaskTexture... ");
if(texID == 0) {
if(mDrawer instanceof TextureRendererMask) {
mDrawer.release();
mDrawer = TextureRendererDrawOrigin.create(true);
}
mIsUsingMask = false;
}
else {
if(!(mDrawer instanceof TextureRendererMask)) {
mDrawer.release();
TextureRendererMask drawer = TextureRendererMask.create(true);
assert drawer != null : "Drawer Create Failed!";
drawer.setMaskTexture(texID);
mDrawer = drawer;
}
mIsUsingMask = true;
}
mMaskAspectRatio = aspectRatio;
calcViewport();
}
public synchronized MediaPlayer getPlayer() {
if(mPlayer == null) {
Log.e(LOG_TAG, "Player is not initialized!");
}
return mPlayer;
}
public interface OnCreateCallback {
void createOK();
}
private OnCreateCallback mOnCreateCallback;
public void setOnCreateCallback(final OnCreateCallback callback) {
assert callback != null : "!";
if(mDrawer == null) {
mOnCreateCallback = callback;
}
else {
queueEvent(new Runnable() {
@Override
public void run() {
callback.createOK();
}
});
}
}
public VideoPlayerGLSurfaceView(Context context, AttributeSet attrs) {
super(context, attrs);
Log.i(LOG_TAG, "MyGLSurfaceView Construct...");
mContext = context;
setEGLContextClientVersion(2);
setEGLConfigChooser(8, 8, 8, 8, 8, 0);
getHolder().setFormat(PixelFormat.RGBA_8888);
setRenderer(this);
setRenderMode(RENDERMODE_WHEN_DIRTY);
setZOrderOnTop(true);
Log.i(LOG_TAG, "MyGLSurfaceView Construct OK...");
}
@Override
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
Log.i(LOG_TAG, "video player onSurfaceCreated...");
GLES20.glDisable(GLES20.GL_DEPTH_TEST);
GLES20.glDisable(GLES20.GL_STENCIL_TEST);
mDrawer = TextureRendererDrawOrigin.create(true);
if(mDrawer == null) {
Log.e(LOG_TAG, "Create Drawer Failed!");
return;
}
if(mOnCreateCallback != null) {
mOnCreateCallback.createOK();
}
if (mVideoUri != null && (mSurfaceTexture == null || mVideoTextureID == 0)) {
mVideoTextureID = Common.genSurfaceTextureID();
mSurfaceTexture = new SurfaceTexture(mVideoTextureID);
mSurfaceTexture.setOnFrameAvailableListener(VideoPlayerGLSurfaceView.this);
_useUri();
}
}
@Override
public void onSurfaceChanged(GL10 gl, int width, int height) {
GLES20.glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
mViewWidth = width;
mViewHeight = height;
calcViewport();
}
//must be in the OpenGL thread!
public void release() {
Log.i(LOG_TAG, "Video player view release...");
if(mPlayer != null) {
queueEvent(new Runnable() {
@Override
public void run() {
Log.i(LOG_TAG, "Video player view release run...");
if(mPlayer != null) {
mPlayer.setSurface(null);
if(mPlayer.isPlaying())
mPlayer.stop();
mPlayer.release();
mPlayer = null;
}
if(mDrawer != null) {
mDrawer.release();
mDrawer = null;
}
if(mSurfaceTexture != null) {
mSurfaceTexture.release();
mSurfaceTexture = null;
}
if(mVideoTextureID != 0) {
GLES20.glDeleteTextures(1, new int[]{mVideoTextureID}, 0);
mVideoTextureID = 0;
}
mIsUsingMask = false;
mPreparedCallback = null;
mPlayCompletionCallback = null;
Log.i(LOG_TAG, "Video player view release OK");
}
});
}
}
@Override
public void onPause() {
Log.i(LOG_TAG, "surfaceview onPause ...");
super.onPause();
}
@Override
public void onDrawFrame(GL10 gl) {
GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, 0);
GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
GLES20.glViewport(0, 0, mViewWidth, mViewHeight);
if(mSurfaceTexture == null) {
return;
}
mSurfaceTexture.updateTexImage();
mSurfaceTexture.getTransformMatrix(mTransformMatrix);
mDrawer.setTransform(mTransformMatrix);
mDrawer.renderTexture(mVideoTextureID, mRenderViewport);
}
private long mTimeCount2 = 0;
private long mFramesCount2 = 0;
private long mLastTimestamp2 = 0;
@Override
public void onFrameAvailable(SurfaceTexture surfaceTexture) {
requestRender();
if(mLastTimestamp2 == 0)
mLastTimestamp2 = System.currentTimeMillis();
long currentTimestamp = System.currentTimeMillis();
++mFramesCount2;
mTimeCount2 += currentTimestamp - mLastTimestamp2;
mLastTimestamp2 = currentTimestamp;
if(mTimeCount2 >= 1e3) {
Log.i(LOG_TAG, String.format(": %d", mFramesCount2));
mTimeCount2 -= 1e3;
mFramesCount2 = 0;
}
}
private void calcViewport() {
float scaling;
if(mIsUsingMask) {
flushMaskAspectRatio();
scaling = mMaskAspectRatio;
} else {
mDrawer.setFlipscale(mDrawerFlipScaleX, mDrawerFlipScaleY);
scaling = mVideoWidth / (float)mVideoHeight;
}
if(mResolutionShouldFix) {
mDrawer.setRotation((float) (-Math.PI * 0.5));
}
float viewRatio = mViewWidth / (float) mViewHeight;
float s = scaling / viewRatio;
int w, h;
if(mFitFullView) {
//view(view)
if(s > 1.0) {
w = (int)(mViewHeight * scaling);
h = mViewHeight;
} else {
w = mViewWidth;
h = (int)(mViewWidth / scaling);
}
} else {
//(view)
if(s > 1.0) {
w = mViewWidth;
h = (int)(mViewWidth / scaling);
} else {
h = mViewHeight;
w = (int)(mViewHeight * scaling);
}
}
mRenderViewport.width = w;
mRenderViewport.height = h;
mRenderViewport.x = (mViewWidth - mRenderViewport.width) / 2;
mRenderViewport.y = (mViewHeight - mRenderViewport.height) / 2;
Log.i(LOG_TAG, String.format("View port: %d, %d, %d, %d", mRenderViewport.x, mRenderViewport.y, mRenderViewport.width, mRenderViewport.height));
}
private void _useUri() {
if (mPlayer != null) {
mPlayer.stop();
mPlayer.reset();
} else {
mPlayer = new MediaPlayer();
}
try {
mPlayer.setDataSource(mContext, mVideoUri);
// mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mPlayer.setSurface(new Surface(mSurfaceTexture));
} catch (Exception e) {
e.printStackTrace();
Log.e(LOG_TAG, "useUri failed");
if(mPlayCompletionCallback != null) {
this.post(new Runnable() {
@Override
public void run() {
if(mPlayCompletionCallback != null) {
if(!mPlayCompletionCallback.playFailed(mPlayer, MediaPlayer.MEDIA_ERROR_UNKNOWN, MediaPlayer.MEDIA_ERROR_UNSUPPORTED))
mPlayCompletionCallback.playComplete(mPlayer);
}
}
});
}
return;
}
if(mPlayerInitCallback != null) {
mPlayerInitCallback.initPlayer(mPlayer);
}
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
if (mPlayCompletionCallback != null) {
mPlayCompletionCallback.playComplete(mPlayer);
}
Log.i(LOG_TAG, "Video Play Over");
}
});
mPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
mVideoWidth = mp.getVideoWidth();
mVideoHeight = mp.getVideoHeight();
//Mark: ios
if(ENABLE_RESOLUTION_FIX && mVideoWidth == 640 && mVideoHeight == 480) {
mVideoWidth = mp.getVideoHeight();
mVideoHeight = mp.getVideoWidth();
mResolutionShouldFix = true;
Log.w(LOG_TAG, "Forcing player rotation!! Be careful for this invalid video!");
} else {
mResolutionShouldFix = false;
}
queueEvent(new Runnable() {
@Override
public void run() {
calcViewport();
}
});
if (mPreparedCallback != null) {
mPreparedCallback.playPrepared(mPlayer);
} else {
mp.start();
}
// requestRender(); // (surface texture
Log.i(LOG_TAG, String.format("Video resolution 1: %d x %d", mVideoWidth, mVideoHeight));
}
});
mPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
if (mPlayCompletionCallback != null)
return mPlayCompletionCallback.playFailed(mp, what, extra);
return false;
}
});
try {
mPlayer.prepareAsync();
}catch (Exception e) {
Log.i(LOG_TAG, String.format("Error handled: %s, play failure handler would be called!", e.toString()));
if(mPlayCompletionCallback != null) {
this.post(new Runnable() {
@Override
public void run() {
if(mPlayCompletionCallback != null) {
if(!mPlayCompletionCallback.playFailed(mPlayer, MediaPlayer.MEDIA_ERROR_UNKNOWN, MediaPlayer.MEDIA_ERROR_UNSUPPORTED))
mPlayCompletionCallback.playComplete(mPlayer);
}
}
});
}
}
}
private void flushMaskAspectRatio() {
float dstRatio = mVideoWidth / (float)mVideoHeight;
if(mResolutionShouldFix) {
dstRatio = mVideoHeight / (float)mVideoWidth;
}
float s = dstRatio / mMaskAspectRatio;
if(s > 1.0f) {
mDrawer.setFlipscale(mDrawerFlipScaleX / s, mDrawerFlipScaleY);
} else {
mDrawer.setFlipscale(mDrawerFlipScaleX, s * mDrawerFlipScaleY);
}
}
public interface TakeShotCallback {
//bmprecycle
void takeShotOK(Bitmap bmp);
}
public synchronized void takeShot(final TakeShotCallback callback) {
assert callback != null : "callback must not be null!";
if(mDrawer == null) {
Log.e(LOG_TAG, "Drawer not initialized!");
callback.takeShotOK(null);
return;
}
queueEvent(new Runnable() {
@Override
public void run() {
IntBuffer buffer = IntBuffer.allocate(mRenderViewport.width * mRenderViewport.height);
GLES20.glReadPixels(mRenderViewport.x, mRenderViewport.y, mRenderViewport.width, mRenderViewport.height, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, buffer);
Bitmap bmp = Bitmap.createBitmap(mRenderViewport.width, mRenderViewport.height, Bitmap.Config.ARGB_8888);
bmp.copyPixelsFromBuffer(buffer);
Bitmap bmp2 = Bitmap.createBitmap(mRenderViewport.width, mRenderViewport.height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bmp2);
Matrix mat = new Matrix();
mat.setTranslate(0.0f, -mRenderViewport.height / 2.0f);
mat.postScale(1.0f, -1.0f);
mat.postTranslate(0.0f, mRenderViewport.height / 2.0f);
canvas.drawBitmap(bmp, mat, null);
bmp.recycle();
callback.takeShotOK(bmp2);
}
});
}
}
|
package liquibase.datatype.core;
import liquibase.database.Database;
import liquibase.database.core.HsqlDatabase;
import liquibase.database.core.OracleDatabase;
import liquibase.datatype.DataTypeInfo;
import liquibase.datatype.DatabaseDataType;
import liquibase.datatype.LiquibaseDataType;
@DataTypeInfo(name="nchar", aliases = { "java.sql.Types.NCHAR", "nchar2"}, minParameters = 0, maxParameters = 1, priority = LiquibaseDataType.PRIORITY_DEFAULT)
public class NCharType extends CharType {
@Override
public DatabaseDataType toDatabaseDataType(Database database) {
if (database instanceof HsqlDatabase) {
return new DatabaseDataType("CHAR", getParameters());
}
if (database instanceof OracleDatabase) {
return new DatabaseDataType("NCHAR", getParameters());
}
return super.toDatabaseDataType(database);
}
}
|
package org.pentaho.di.core.database;
import java.io.StringReader;
import java.sql.BatchUpdateException;
import java.sql.Blob;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Savepoint;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.sql.DataSource;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.Counter;
import org.pentaho.di.core.DBCache;
import org.pentaho.di.core.DBCacheEntry;
import org.pentaho.di.core.ProgressMonitorListener;
import org.pentaho.di.core.Result;
import org.pentaho.di.core.RowMetaAndData;
import org.pentaho.di.core.database.map.DatabaseConnectionMap;
import org.pentaho.di.core.database.util.DatabaseUtil;
import org.pentaho.di.core.encryption.Encr;
import org.pentaho.di.core.exception.KettleDatabaseBatchException;
import org.pentaho.di.core.exception.KettleDatabaseException;
import org.pentaho.di.core.exception.KettleValueException;
import org.pentaho.di.core.logging.LogWriter;
import org.pentaho.di.core.row.RowDataUtil;
import org.pentaho.di.core.row.RowMeta;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.core.row.ValueMeta;
import org.pentaho.di.core.row.ValueMetaInterface;
import org.pentaho.di.core.variables.VariableSpace;
import org.pentaho.di.core.variables.Variables;
/**
* Database handles the process of connecting to, reading from, writing to and updating databases.
* The database specific parameters are defined in DatabaseInfo.
*
* @author Matt
* @since 05-04-2003
*
*/
public class Database implements VariableSpace
{
private DatabaseMeta databaseMeta;
private int rowlimit;
private int commitsize;
private Connection connection;
private Statement sel_stmt;
private PreparedStatement pstmt;
private PreparedStatement prepStatementLookup;
private PreparedStatement prepStatementUpdate;
private PreparedStatement prepStatementInsert;
private PreparedStatement pstmt_seq;
private CallableStatement cstmt;
// private ResultSetMetaData rsmd;
private DatabaseMetaData dbmd;
private RowMetaInterface rowMeta;
private int written;
private LogWriter log;
/*
* Counts the number of rows written to a batch for a certain PreparedStatement.
*
private Map<PreparedStatement, Integer> batchCounterMap;
*/
/**
* Number of times a connection was opened using this object.
* Only used in the context of a database connection map
*/
private int opened;
/**
* The copy is equal to opened at the time of creation.
*/
private int copy;
private String connectionGroup;
private String partitionId;
private VariableSpace variables = new Variables();
/**
* Construct a new Database Connection
* @param inf The Database Connection Info to construct the connection with.
*/
public Database(DatabaseMeta inf)
{
log=LogWriter.getInstance();
databaseMeta = inf;
shareVariablesWith(inf);
pstmt = null;
rowMeta = null;
dbmd = null;
rowlimit=0;
written=0;
log.logDetailed(toString(), "New database connection defined");
}
public boolean equals(Object obj)
{
Database other = (Database) obj;
return other.databaseMeta.equals(other.databaseMeta);
}
/**
* Allows for the injection of a "life" connection, generated by a piece of software outside of Kettle.
* @param connection
*/
public void setConnection(Connection connection) {
this.connection = connection;
}
/**
* @return Returns the connection.
*/
public Connection getConnection()
{
return connection;
}
/**
* Set the maximum number of records to retrieve from a query.
* @param rows
*/
public void setQueryLimit(int rows)
{
rowlimit = rows;
}
/**
* @return Returns the prepStatementInsert.
*/
public PreparedStatement getPrepStatementInsert()
{
return prepStatementInsert;
}
/**
* @return Returns the prepStatementLookup.
*/
public PreparedStatement getPrepStatementLookup()
{
return prepStatementLookup;
}
/**
* @return Returns the prepStatementUpdate.
*/
public PreparedStatement getPrepStatementUpdate()
{
return prepStatementUpdate;
}
/**
* Open the database connection.
* @throws KettleDatabaseException if something went wrong.
*/
public void connect() throws KettleDatabaseException
{
connect(null);
}
/**
* Open the database connection.
* @param partitionId the partition ID in the cluster to connect to.
* @throws KettleDatabaseException if something went wrong.
*/
public void connect(String partitionId) throws KettleDatabaseException
{
connect(null, partitionId);
}
public synchronized void connect(String group, String partitionId) throws KettleDatabaseException
{
// Before anything else, let's see if we already have a connection defined for this group/partition!
// The group is called after the thread-name of the transformation or job that is running
// The name of that threadname is expected to be unique (it is in Kettle)
// So the deal is that if there is another thread using that, we go for it.
if (!Const.isEmpty(group))
{
this.connectionGroup = group;
this.partitionId = partitionId;
DatabaseConnectionMap map = DatabaseConnectionMap.getInstance();
// Try to find the conection for the group
Database lookup = map.getDatabase(group, partitionId, this);
if (lookup==null) // We already opened this connection for the partition & database in this group
{
// Do a normal connect and then store this database object for later re-use.
normalConnect(partitionId);
opened++;
copy = opened;
map.storeDatabase(group, partitionId, this);
}
else
{
connection = lookup.getConnection();
lookup.setOpened(lookup.getOpened()+1); // if this counter hits 0 again, close the connection.
copy = lookup.getOpened();
}
}
else
{
// Proceed with a normal connect
normalConnect(partitionId);
}
}
/**
* Open the database connection.
* @param partitionId the partition ID in the cluster to connect to.
* @throws KettleDatabaseException if something went wrong.
*/
public void normalConnect(String partitionId) throws KettleDatabaseException
{
if (databaseMeta==null)
{
throw new KettleDatabaseException("No valid database connection defined!");
}
try
{
// First see if we use connection pooling...
if ( databaseMeta.isUsingConnectionPool() && // default = false for backward compatibility
databaseMeta.getAccessType()!=DatabaseMeta.TYPE_ACCESS_JNDI // JNDI does pooling on it's own.
)
{
try
{
this.connection = ConnectionPoolUtil.getConnection(databaseMeta, partitionId);
}
catch (Exception e)
{
throw new KettleDatabaseException("Error occured while trying to connect to the database", e);
}
}
else
{
connectUsingClass(databaseMeta.getDriverClass(), partitionId );
log.logDetailed(toString(), "Connected to database.");
// See if we need to execute extra SQL statemtent...
String sql = environmentSubstitute( databaseMeta.getConnectSQL() );
// only execute if the SQL is not empty, null and is not just a bunch of spaces, tabs, CR etc.
if (!Const.isEmpty(sql) && !Const.onlySpaces(sql))
{
execStatements(sql);
log.logDetailed(toString(), "Executed connect time SQL statements:"+Const.CR+sql);
}
}
}
catch(Exception e)
{
throw new KettleDatabaseException("Error occured while trying to connect to the database", e);
}
}
private void initWithJNDI(String jndiName) throws KettleDatabaseException {
connection = null;
try {
DataSource dataSource = DatabaseUtil.getDataSourceFromJndi(jndiName);
if (dataSource != null) {
connection = dataSource.getConnection();
if (connection == null) {
throw new KettleDatabaseException( "Invalid JNDI connection "+ jndiName); //$NON-NLS-1$
}
} else {
throw new KettleDatabaseException( "Invalid JNDI connection "+ jndiName); //$NON-NLS-1$
}
} catch (Exception e) {
throw new KettleDatabaseException( "Invalid JNDI connection "+ jndiName + " : " + e.getMessage()); //$NON-NLS-1$
}
}
/**
* Connect using the correct classname
* @param classname for example "org.gjt.mm.mysql.Driver"
* @return true if the connect was succesfull, false if something went wrong.
*/
private void connectUsingClass(String classname, String partitionId) throws KettleDatabaseException
{
// Install and load the jdbc Driver
// first see if this is a JNDI connection
if( databaseMeta.getAccessType() == DatabaseMeta.TYPE_ACCESS_JNDI ) {
initWithJNDI( environmentSubstitute(databaseMeta.getDatabaseName()) );
return;
}
try
{
Class.forName(classname);
}
catch(NoClassDefFoundError e)
{
throw new KettleDatabaseException("Exception while loading class", e);
}
catch(ClassNotFoundException e)
{
throw new KettleDatabaseException("Exception while loading class", e);
}
catch(Exception e)
{
throw new KettleDatabaseException("Exception while loading class", e);
}
try
{
String url;
if (databaseMeta.isPartitioned() && !Const.isEmpty(partitionId))
{
url = environmentSubstitute(databaseMeta.getURL(partitionId));
}
else
{
url = environmentSubstitute(databaseMeta.getURL());
}
String clusterUsername=null;
String clusterPassword=null;
if (databaseMeta.isPartitioned() && !Const.isEmpty(partitionId))
{
// Get the cluster information...
PartitionDatabaseMeta partition = databaseMeta.getPartitionMeta(partitionId);
if (partition!=null)
{
clusterUsername = partition.getUsername();
clusterPassword = Encr.decryptPasswordOptionallyEncrypted(partition.getPassword());
}
}
String username;
String password;
if (!Const.isEmpty(clusterUsername))
{
username = clusterUsername;
password = clusterPassword;
}
else
{
username = environmentSubstitute(databaseMeta.getUsername());
password = Encr.decryptPasswordOptionallyEncrypted(environmentSubstitute(databaseMeta.getPassword()));
}
if (databaseMeta.supportsOptionsInURL())
{
if (!Const.isEmpty(username) || !Const.isEmpty(password))
{
// also allow for empty username with given password, in this case username must be given with one space
connection = DriverManager.getConnection(url, Const.NVL(username, " "), Const.NVL(password, ""));
}
else
{
// Perhaps the username is in the URL or no username is required...
connection = DriverManager.getConnection(url);
}
}
else
{
Properties properties = databaseMeta.getConnectionProperties();
if (!Const.isEmpty(username)) properties.put("user", username);
if (!Const.isEmpty(password)) properties.put("password", password);
connection = DriverManager.getConnection(url, properties);
}
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error connecting to database: (using class "+classname+")", e);
}
catch(Throwable e)
{
throw new KettleDatabaseException("Error connecting to database: (using class "+classname+")", e);
}
}
/**
* Disconnect from the database and close all open prepared statements.
*/
public synchronized void disconnect()
{
try
{
if (connection==null)
{
return ; // Nothing to do...
}
if (connection.isClosed())
{
return ; // Nothing to do...
}
if (pstmt !=null)
{
pstmt.close();
pstmt=null;
}
if (prepStatementLookup!=null)
{
prepStatementLookup.close();
prepStatementLookup=null;
}
if (prepStatementInsert!=null)
{
prepStatementInsert.close();
prepStatementInsert=null;
}
if (prepStatementUpdate!=null)
{
prepStatementUpdate.close();
prepStatementUpdate=null;
}
if (pstmt_seq!=null)
{
pstmt_seq.close();
pstmt_seq=null;
}
// See if there are other steps using this connection in a connection group.
// If so, we will hold commit & connection close until then.
if (!Const.isEmpty(connectionGroup))
{
return;
}
else
{
if (!isAutoCommit()) // Do we really still need this commit??
{
commit();
}
}
closeConnectionOnly();
}
catch(SQLException ex)
{
log.logError(toString(), "Error disconnecting from database:"+Const.CR+ex.getMessage());
log.logError(toString(), Const.getStackTracker(ex));
}
catch(KettleDatabaseException dbe)
{
log.logError(toString(), "Error disconnecting from database:"+Const.CR+dbe.getMessage());
log.logError(toString(), Const.getStackTracker(dbe));
}
}
/**
* Only for unique connections usage, typically you use disconnect() to disconnect() from the database.
* @throws KettleDatabaseException in case there is an error during connection close.
*/
public synchronized void closeConnectionOnly() throws KettleDatabaseException {
try
{
if (connection!=null)
{
connection.close();
if (!databaseMeta.isUsingConnectionPool())
{
connection=null;
}
}
log.logDetailed(toString(), "Connection to database closed!");
}
catch(SQLException e) {
throw new KettleDatabaseException("Error disconnecting from database '"+toString()+"'", e);
}
}
/**
* Cancel the open/running queries on the database connection
* @throws KettleDatabaseException
*/
public void cancelQuery() throws KettleDatabaseException
{
cancelStatement(pstmt);
cancelStatement(sel_stmt);
}
/**
* Cancel an open/running SQL statement
* @param statement the statement to cancel
* @throws KettleDatabaseException
*/
public void cancelStatement(Statement statement) throws KettleDatabaseException
{
try
{
if (statement!=null)
{
statement.cancel();
}
log.logDetailed(toString(), "Statement canceled!");
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Error cancelling statement", ex);
}
}
/**
* Specify after how many rows a commit needs to occur when inserting or updating values.
* @param commsize The number of rows to wait before doing a commit on the connection.
*/
public void setCommit(int commsize)
{
commitsize=commsize;
String onOff = (commitsize<=0?"on":"off");
try
{
connection.setAutoCommit(commitsize<=0);
log.logDetailed(toString(), "Auto commit "+onOff);
}
catch(Exception e)
{
log.logError(toString(), "Can't turn auto commit "+onOff);
}
}
public void setAutoCommit(boolean useAutoCommit) throws KettleDatabaseException {
try {
connection.setAutoCommit(useAutoCommit);
} catch (SQLException e) {
if (useAutoCommit) {
throw new KettleDatabaseException(Messages.getString("Database.Exception.UnableToEnableAutoCommit", toString()));
} else {
throw new KettleDatabaseException(Messages.getString("Database.Exception.UnableToDisableAutoCommit", toString()));
}
}
}
/**
* Perform a commit the connection if this is supported by the database
*/
public void commit() throws KettleDatabaseException
{
commit(false);
}
public void commit(boolean force) throws KettleDatabaseException
{
try
{
// Don't do the commit, wait until the end of the transformation.
// When the last database copy (opened counter) is about to be closed, we do a commit
// There is one catch, we need to catch the rollback
// The transformation will stop everything and then we'll do the rollback.
// The flag is in "performRollback", private only
if (!Const.isEmpty(connectionGroup) && !force)
{
return;
}
if (getDatabaseMetaData().supportsTransactions())
{
if (log.isDebug()) log.logDebug(toString(), "Commit on database connection ["+toString()+"]");
connection.commit();
}
else
{
log.logDetailed(toString(), "No commit possible on database connection ["+toString()+"]");
}
}
catch(Exception e)
{
if (databaseMeta.supportsEmptyTransactions())
throw new KettleDatabaseException("Error comitting connection", e);
}
}
public void rollback() throws KettleDatabaseException
{
rollback(false);
}
public void rollback(boolean force) throws KettleDatabaseException
{
try
{
if (!Const.isEmpty(connectionGroup) && !force)
{
return; // Will be handled by Trans --> endProcessing()
}
if (getDatabaseMetaData().supportsTransactions())
{
if (connection!=null) {
if (log.isDebug()) log.logDebug(toString(), "Rollback on database connection ["+toString()+"]");
connection.rollback();
}
}
else
{
log.logDetailed(toString(), "No rollback possible on database connection ["+toString()+"]");
}
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error performing rollback on connection", e);
}
}
/**
* Prepare inserting values into a table, using the fields & values in a Row
* @param rowMeta The row metadata to determine which values need to be inserted
* @param table The name of the table in which we want to insert rows
* @throws KettleDatabaseException if something went wrong.
*/
public void prepareInsert(RowMetaInterface rowMeta, String tableName) throws KettleDatabaseException
{
prepareInsert(rowMeta, null, tableName);
}
/**
* Prepare inserting values into a table, using the fields & values in a Row
* @param rowMeta The metadata row to determine which values need to be inserted
* @param schemaName The name of the schema in which we want to insert rows
* @param tableName The name of the table in which we want to insert rows
* @throws KettleDatabaseException if something went wrong.
*/
public void prepareInsert(RowMetaInterface rowMeta, String schemaName, String tableName) throws KettleDatabaseException
{
if (rowMeta.size()==0)
{
throw new KettleDatabaseException("No fields in row, can't insert!");
}
String ins = getInsertStatement(schemaName, tableName, rowMeta);
log.logDetailed(toString(),"Preparing statement: "+Const.CR+ins);
prepStatementInsert=prepareSQL(ins);
}
/**
* Prepare a statement to be executed on the database. (does not return generated keys)
* @param sql The SQL to be prepared
* @return The PreparedStatement object.
* @throws KettleDatabaseException
*/
public PreparedStatement prepareSQL(String sql)
throws KettleDatabaseException
{
return prepareSQL(sql, false);
}
/**
* Prepare a statement to be executed on the database.
* @param sql The SQL to be prepared
* @param returnKeys set to true if you want to return generated keys from an insert statement
* @return The PreparedStatement object.
* @throws KettleDatabaseException
*/
public PreparedStatement prepareSQL(String sql, boolean returnKeys) throws KettleDatabaseException
{
try
{
if (returnKeys)
{
return connection.prepareStatement(databaseMeta.stripCR(sql), Statement.RETURN_GENERATED_KEYS);
}
else
{
return connection.prepareStatement(databaseMeta.stripCR(sql));
}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Couldn't prepare statement:"+Const.CR+sql, ex);
}
}
public void closeLookup() throws KettleDatabaseException
{
closePreparedStatement(pstmt);
pstmt=null;
}
public void closePreparedStatement(PreparedStatement ps) throws KettleDatabaseException
{
if (ps!=null)
{
try
{
ps.close();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error closing prepared statement", e);
}
}
}
public void closeInsert() throws KettleDatabaseException
{
if (prepStatementInsert!=null)
{
try
{
prepStatementInsert.close();
prepStatementInsert = null;
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error closing insert prepared statement.", e);
}
}
}
public void closeUpdate() throws KettleDatabaseException
{
if (prepStatementUpdate!=null)
{
try
{
prepStatementUpdate.close();
prepStatementUpdate=null;
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error closing update prepared statement.", e);
}
}
}
public void setValues(RowMetaInterface rowMeta, Object[] data) throws KettleDatabaseException
{
setValues(rowMeta, data, pstmt);
}
public void setValues(RowMetaAndData row) throws KettleDatabaseException
{
setValues(row.getRowMeta(), row.getData());
}
public void setValuesInsert(RowMetaInterface rowMeta, Object[] data) throws KettleDatabaseException
{
setValues(rowMeta, data, prepStatementInsert);
}
public void setValuesInsert(RowMetaAndData row) throws KettleDatabaseException
{
setValues(row.getRowMeta(), row.getData(), prepStatementInsert);
}
public void setValuesUpdate(RowMetaInterface rowMeta, Object[] data) throws KettleDatabaseException
{
setValues(rowMeta, data, prepStatementUpdate);
}
public void setValuesLookup(RowMetaInterface rowMeta, Object[] data) throws KettleDatabaseException
{
setValues(rowMeta, data, prepStatementLookup);
}
public void setProcValues(RowMetaInterface rowMeta, Object[] data, int argnrs[], String argdir[], boolean result) throws KettleDatabaseException
{
int pos;
if (result) pos=2; else pos=1;
for (int i=0;i<argnrs.length;i++)
{
if (argdir[i].equalsIgnoreCase("IN") || argdir[i].equalsIgnoreCase("INOUT"))
{
ValueMetaInterface valueMeta = rowMeta.getValueMeta(argnrs[i]);
Object value = data[argnrs[i]];
setValue(cstmt, valueMeta, value, pos);
pos++;
} else {
pos++; //next parameter when OUT
}
}
}
public void setValue(PreparedStatement ps, ValueMetaInterface v, Object object, int pos) throws KettleDatabaseException
{
String debug = "";
try
{
switch(v.getType())
{
case ValueMetaInterface.TYPE_NUMBER :
if (object!=null)
{
debug="Number, not null, getting number from value";
double num = v.getNumber(object).doubleValue();
if (databaseMeta.supportsFloatRoundingOnUpdate() && v.getPrecision()>=0)
{
debug="Number, rounding to precision ["+v.getPrecision()+"]";
num = Const.round(num, v.getPrecision());
}
debug="Number, setting ["+num+"] on position #"+pos+" of the prepared statement";
ps.setDouble(pos, num);
}
else
{
ps.setNull(pos, java.sql.Types.DOUBLE);
}
break;
case ValueMetaInterface.TYPE_INTEGER:
debug="Integer";
if (object!=null)
{
if (databaseMeta.supportsSetLong())
{
ps.setLong(pos, v.getInteger(object).longValue() );
}
else
{
double d = v.getNumber(object).doubleValue();
if (databaseMeta.supportsFloatRoundingOnUpdate() && v.getPrecision()>=0)
{
ps.setDouble(pos, d );
}
else
{
ps.setDouble(pos, Const.round( d, v.getPrecision() ) );
}
}
}
else
{
ps.setNull(pos, java.sql.Types.INTEGER);
}
break;
case ValueMetaInterface.TYPE_STRING :
debug="String";
if (v.getLength()<DatabaseMeta.CLOB_LENGTH)
{
if (object!=null)
{
ps.setString(pos, v.getString(object));
}
else
{
ps.setNull(pos, java.sql.Types.VARCHAR);
}
}
else
{
if (object!=null)
{
String string = v.getString(object);
int maxlen = databaseMeta.getMaxTextFieldLength();
int len = string.length();
// Take the last maxlen characters of the string...
int begin = len - maxlen;
if (begin<0) begin=0;
// Get the substring!
String logging = string.substring(begin);
if (databaseMeta.supportsSetCharacterStream())
{
StringReader sr = new StringReader(logging);
ps.setCharacterStream(pos, sr, logging.length());
}
else
{
ps.setString(pos, logging);
}
}
else
{
ps.setNull(pos, java.sql.Types.VARCHAR);
}
}
break;
case ValueMetaInterface.TYPE_DATE :
debug="Date";
if (object!=null)
{
long dat = v.getInteger(object).longValue(); // converts using Date.getTime()
if(v.getPrecision()==1 || !databaseMeta.supportsTimeStampToDateConversion())
{
// Convert to DATE!
java.sql.Date ddate = new java.sql.Date(dat);
ps.setDate(pos, ddate);
}
else
{
java.sql.Timestamp sdate = new java.sql.Timestamp(dat);
ps.setTimestamp(pos, sdate);
}
}
else
{
if(v.getPrecision()==1 || !databaseMeta.supportsTimeStampToDateConversion())
{
ps.setNull(pos, java.sql.Types.DATE);
}
else
{
ps.setNull(pos, java.sql.Types.TIMESTAMP);
}
}
break;
case ValueMetaInterface.TYPE_BOOLEAN:
debug="Boolean";
if (databaseMeta.supportsBooleanDataType())
{
if (object!=null)
{
ps.setBoolean(pos, v.getBoolean(object).booleanValue());
}
else
{
ps.setNull(pos, java.sql.Types.BOOLEAN);
}
}
else
{
if (object!=null)
{
ps.setString(pos, v.getBoolean(object).booleanValue()?"Y":"N");
}
else
{
ps.setNull(pos, java.sql.Types.CHAR);
}
}
break;
case ValueMetaInterface.TYPE_BIGNUMBER:
debug="BigNumber";
if (object!=null)
{
ps.setBigDecimal(pos, v.getBigNumber(object));
}
else
{
ps.setNull(pos, java.sql.Types.DECIMAL);
}
break;
case ValueMetaInterface.TYPE_BINARY:
debug="Binary";
if (object!=null)
{
ps.setBytes(pos, v.getBinary(object));
}
else
{
ps.setNull(pos, java.sql.Types.BINARY);
}
break;
default:
debug="default";
// placeholder
ps.setNull(pos, java.sql.Types.VARCHAR);
break;
}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Error setting value #"+pos+" ["+v.toString()+"] on prepared statement ("+debug+")"+Const.CR+ex.toString(), ex);
}
catch(Exception e)
{
throw new KettleDatabaseException("Error setting value #"+pos+" ["+(v==null?"NULL":v.toString())+"] on prepared statement ("+debug+")"+Const.CR+e.toString(), e);
}
}
public void setValues(RowMetaAndData row, PreparedStatement ps) throws KettleDatabaseException
{
setValues(row.getRowMeta(), row.getData(), ps);
}
public void setValues(RowMetaInterface rowMeta, Object[] data, PreparedStatement ps) throws KettleDatabaseException
{
// now set the values in the row!
for (int i=0;i<rowMeta.size();i++)
{
ValueMetaInterface v = rowMeta.getValueMeta(i);
Object object = data[i];
try
{
setValue(ps, v, object, i+1);
}
catch(KettleDatabaseException e)
{
throw new KettleDatabaseException("offending row : "+rowMeta, e);
}
}
}
/**
* Sets the values of the preparedStatement pstmt.
* @param rowMeta
* @param data
*/
public void setValues(RowMetaInterface rowMeta, Object[] data, PreparedStatement ps, int ignoreThisValueIndex) throws KettleDatabaseException
{
// now set the values in the row!
int index=0;
for (int i=0;i<rowMeta.size();i++)
{
if (i!=ignoreThisValueIndex)
{
ValueMetaInterface v = rowMeta.getValueMeta(i);
Object object = data[i];
try
{
setValue(ps, v, object, index+1);
index++;
}
catch(KettleDatabaseException e)
{
throw new KettleDatabaseException("offending row : "+rowMeta, e);
}
}
}
}
/**
* @param ps The prepared insert statement to use
* @return The generated keys in auto-increment fields
* @throws KettleDatabaseException in case something goes wrong retrieving the keys.
*/
public RowMetaAndData getGeneratedKeys(PreparedStatement ps) throws KettleDatabaseException
{
ResultSet keys = null;
try
{
keys=ps.getGeneratedKeys(); // 1 row of keys
ResultSetMetaData resultSetMetaData = keys.getMetaData();
RowMetaInterface rowMeta = getRowInfo(resultSetMetaData, false, false);
return new RowMetaAndData(rowMeta, getRow(keys, resultSetMetaData, rowMeta));
}
catch(Exception ex)
{
throw new KettleDatabaseException("Unable to retrieve key(s) from auto-increment field(s)", ex);
}
finally
{
if (keys!=null)
{
try
{
keys.close();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to close resultset of auto-generated keys", e);
}
}
}
}
public Long getNextSequenceValue(String sequenceName, String keyfield) throws KettleDatabaseException
{
return getNextSequenceValue(null, sequenceName, keyfield);
}
public Long getNextSequenceValue(String schemaName, String sequenceName, String keyfield) throws KettleDatabaseException
{
Long retval=null;
String schemaSequence = databaseMeta.getQuotedSchemaTableCombination(schemaName, sequenceName);
try
{
if (pstmt_seq==null)
{
pstmt_seq=connection.prepareStatement(databaseMeta.getSeqNextvalSQL(databaseMeta.stripCR(schemaSequence)));
}
ResultSet rs=null;
try
{
rs = pstmt_seq.executeQuery();
if (rs.next())
{
retval = Long.valueOf( rs.getLong(1) );
}
}
finally
{
if ( rs != null ) rs.close();
}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to get next value for sequence : "+schemaSequence, ex);
}
return retval;
}
public void insertRow(String tableName, RowMetaInterface fields, Object[] data) throws KettleDatabaseException
{
prepareInsert(fields, tableName);
setValuesInsert(fields, data);
insertRow();
closeInsert();
}
public String getInsertStatement(String tableName, RowMetaInterface fields)
{
return getInsertStatement(null, tableName, fields);
}
public String getInsertStatement(String schemaName, String tableName, RowMetaInterface fields)
{
StringBuffer ins=new StringBuffer(128);
String schemaTable = databaseMeta.getQuotedSchemaTableCombination(schemaName, tableName);
ins.append("INSERT INTO ").append(schemaTable).append('(');
// now add the names in the row:
for (int i=0;i<fields.size();i++)
{
if (i>0) ins.append(", ");
String name = fields.getValueMeta(i).getName();
ins.append(databaseMeta.quoteField(name));
}
ins.append(") VALUES (");
// Add placeholders...
for (int i=0;i<fields.size();i++)
{
if (i>0) ins.append(", ");
ins.append(" ?");
}
ins.append(')');
return ins.toString();
}
public void insertRow()
throws KettleDatabaseException
{
insertRow(prepStatementInsert);
}
public void insertRow(boolean batch) throws KettleDatabaseException
{
insertRow(prepStatementInsert, batch);
}
public void updateRow()
throws KettleDatabaseException
{
insertRow(prepStatementUpdate);
}
public void insertRow(PreparedStatement ps)
throws KettleDatabaseException
{
insertRow(ps, false);
}
/**
* Insert a row into the database using a prepared statement that has all values set.
* @param ps The prepared statement
* @param batch True if you want to use batch inserts (size = commit size)
* @return true if the rows are safe: if batch of rows was sent to the database OR if a commit was done.
* @throws KettleDatabaseException
*/
public boolean insertRow(PreparedStatement ps, boolean batch) throws KettleDatabaseException
{
String debug="insertRow start";
boolean rowsAreSafe=false;
try
{
// Unique connections and Batch inserts don't mix when you want to roll back on certain databases.
// That's why we disable the batch insert in that case.
boolean useBatchInsert = batch && getDatabaseMetaData().supportsBatchUpdates() && databaseMeta.supportsBatchUpdates() && Const.isEmpty(connectionGroup);
// Add support for batch inserts...
if (!isAutoCommit())
{
if (useBatchInsert)
{
debug="insertRow add batch";
ps.addBatch(); // Add the batch, but don't forget to run the batch
}
else
{
debug="insertRow exec update";
ps.executeUpdate();
}
}
else
{
ps.executeUpdate();
}
written++;
/*
if (!isAutoCommit() && (written%commitsize)==0)
{
if (useBatchInsert)
{
debug="insertRow executeBatch commit";
ps.executeBatch();
commit();
ps.clearBatch();
batchCounterMap.put(ps, Integer.valueOf(0));
}
else
{
debug="insertRow normal commit";
commit();
}
rowsAreSafe=true;
}
*/
return rowsAreSafe;
}
catch(BatchUpdateException ex)
{
KettleDatabaseBatchException kdbe = new KettleDatabaseBatchException("Error updating batch", ex);
kdbe.setUpdateCounts(ex.getUpdateCounts());
List<Exception> exceptions = new ArrayList<Exception>();
// 'seed' the loop with the root exception
SQLException nextException = ex;
do
{
exceptions.add(nextException);
// while current exception has next exception, add to list
}
while ((nextException = nextException.getNextException())!=null);
kdbe.setExceptionsList(exceptions);
throw kdbe;
}
catch(SQLException ex)
{
// log.logError(toString(), Const.getStackTracker(ex));
throw new KettleDatabaseException("Error inserting row", ex);
}
catch(Exception e)
{
// System.out.println("Unexpected exception in ["+debug+"] : "+e.getMessage());
throw new KettleDatabaseException("Unexpected error inserting row in part ["+debug+"]", e);
}
}
/**
* Clears batch of insert prepared statement
* @deprecated
* @throws KettleDatabaseException
*/
public void clearInsertBatch() throws KettleDatabaseException
{
clearBatch(prepStatementInsert);
}
public void clearBatch(PreparedStatement preparedStatement) throws KettleDatabaseException
{
try
{
preparedStatement.clearBatch();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to clear batch for prepared statement", e);
}
}
public void insertFinished(boolean batch) throws KettleDatabaseException
{
insertFinished(prepStatementInsert, batch);
prepStatementInsert = null;
}
/**
* Close the prepared statement of the insert statement.
*
* @param ps The prepared statement to empty and close.
* @param batch true if you are using batch processing
* @param psBatchCounter The number of rows on the batch queue
* @throws KettleDatabaseException
*/
public void emptyAndCommit(PreparedStatement ps, boolean batch, int batchCounter) throws KettleDatabaseException {
try
{
if (ps!=null)
{
if (!isAutoCommit())
{
// Execute the batch or just perform a commit.
if (batch && getDatabaseMetaData().supportsBatchUpdates() && batchCounter>0)
{
// The problem with the batch counters is that you can't just execute the current batch.
// Certain databases have a problem if you execute the batch and if there are no statements in it.
// You can't just catch the exception either because you would have to roll back on certain databases before you can then continue to do anything.
// That leaves the task of keeping track of the number of rows up to our responsibility.
ps.executeBatch();
commit();
}
else
{
commit();
}
}
// Let's not forget to close the prepared statement.
ps.close();
}
}
catch(BatchUpdateException ex)
{
KettleDatabaseBatchException kdbe = new KettleDatabaseBatchException("Error updating batch", ex);
kdbe.setUpdateCounts(ex.getUpdateCounts());
List<Exception> exceptions = new ArrayList<Exception>();
SQLException nextException = ex.getNextException();
SQLException oldException = null;
// This construction is specifically done for some JDBC drivers, these drivers
// always return the same exception on getNextException() (and thus go into an infinite loop).
// So it's not "equals" but != (comments from Sven Boden).
while ( (nextException != null) && (oldException != nextException) )
{
exceptions.add(nextException);
oldException = nextException;
nextException = nextException.getNextException();
}
kdbe.setExceptionsList(exceptions);
throw kdbe;
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to empty ps and commit connection.", ex);
}
}
/**
* Close the prepared statement of the insert statement.
*
* @param ps The prepared statement to empty and close.
* @param batch true if you are using batch processing (typically true for this method)
* @param psBatchCounter The number of rows on the batch queue
* @throws KettleDatabaseException
*
* @deprecated use emptyAndCommit() instead (pass in the number of rows left in the batch)
*/
public void insertFinished(PreparedStatement ps, boolean batch) throws KettleDatabaseException
{
try
{
if (ps!=null)
{
if (!isAutoCommit())
{
// Execute the batch or just perform a commit.
if (batch && getDatabaseMetaData().supportsBatchUpdates())
{
// The problem with the batch counters is that you can't just execute the current batch.
// Certain databases have a problem if you execute the batch and if there are no statements in it.
// You can't just catch the exception either because you would have to roll back on certain databases before you can then continue to do anything.
// That leaves the task of keeping track of the number of rows up to our responsibility.
ps.executeBatch();
commit();
}
else
{
commit();
}
}
// Let's not forget to close the prepared statement.
ps.close();
}
}
catch(BatchUpdateException ex)
{
KettleDatabaseBatchException kdbe = new KettleDatabaseBatchException("Error updating batch", ex);
kdbe.setUpdateCounts(ex.getUpdateCounts());
List<Exception> exceptions = new ArrayList<Exception>();
SQLException nextException = ex.getNextException();
SQLException oldException = null;
// This construction is specifically done for some JDBC drivers, these drivers
// always return the same exception on getNextException() (and thus go into an infinite loop).
// So it's not "equals" but != (comments from Sven Boden).
while ( (nextException != null) && (oldException != nextException) )
{
exceptions.add(nextException);
oldException = nextException;
nextException = nextException.getNextException();
}
kdbe.setExceptionsList(exceptions);
throw kdbe;
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to commit connection after having inserted rows.", ex);
}
}
/**
* Execute an SQL statement on the database connection (has to be open)
* @param sql The SQL to execute
* @return a Result object indicating the number of lines read, deleted, inserted, updated, ...
* @throws KettleDatabaseException in case anything goes wrong.
*/
public Result execStatement(String sql) throws KettleDatabaseException
{
return execStatement(sql, null, null);
}
public Result execStatement(String sql, RowMetaInterface params, Object[] data) throws KettleDatabaseException
{
Result result = new Result();
try
{
boolean resultSet;
int count;
if (params!=null)
{
PreparedStatement prep_stmt = connection.prepareStatement(databaseMeta.stripCR(sql));
setValues(params, data, prep_stmt); // set the parameters!
resultSet = prep_stmt.execute();
count = prep_stmt.getUpdateCount();
prep_stmt.close();
}
else
{
String sqlStripped = databaseMeta.stripCR(sql);
// log.logDetailed(toString(), "Executing SQL Statement: ["+sqlStripped+"]");
Statement stmt = connection.createStatement();
resultSet = stmt.execute(sqlStripped);
count = stmt.getUpdateCount();
stmt.close();
}
if (resultSet)
{
// the result is a resultset, but we don't do anything with it!
// You should have called something else!
// log.logDetailed(toString(), "What to do with ResultSet??? (count="+count+")");
}
else
{
if (count > 0)
{
if (sql.toUpperCase().startsWith("INSERT")) result.setNrLinesOutput(count);
if (sql.toUpperCase().startsWith("UPDATE")) result.setNrLinesUpdated(count);
if (sql.toUpperCase().startsWith("DELETE")) result.setNrLinesDeleted(count);
}
}
// See if a cache needs to be cleared...
if (sql.toUpperCase().startsWith("ALTER TABLE") ||
sql.toUpperCase().startsWith("DROP TABLE") ||
sql.toUpperCase().startsWith("CREATE TABLE")
)
{
DBCache.getInstance().clear(databaseMeta.getName());
}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Couldn't execute SQL: "+sql+Const.CR, ex);
}
catch(Exception e)
{
throw new KettleDatabaseException("Unexpected error executing SQL: "+Const.CR, e);
}
return result;
}
/**
* Execute a series of SQL statements, separated by ;
*
* We are already connected...
* Multiple statements have to be split into parts
* We use the ";" to separate statements...
*
* We keep the results in Result object from Jobs
*
* @param script The SQL script to be execute
* @throws KettleDatabaseException In case an error occurs
* @return A result with counts of the number or records updates, inserted, deleted or read.
*/
public Result execStatements(String script) throws KettleDatabaseException
{
Result result = new Result();
String all = script;
int from=0;
int to=0;
int length = all.length();
int nrstats = 0;
while (to<length)
{
char c = all.charAt(to);
if (c=='"')
{
to++;
c=' ';
while (to<length && c!='"') { c=all.charAt(to); to++; }
}
else
if (c=='\'') // skip until next '
{
to++;
c=' ';
while (to<length && c!='\'') { c=all.charAt(to); to++; }
}
else
if (all.substring(to).startsWith("--")) // -- means: ignore comment until end of line...
{
to++;
while (to<length && c!='\n' && c!='\r') { c=all.charAt(to); to++; }
}
if (c==';' || to>=length-1) // end of statement
{
if (to>=length-1) to++; // grab last char also!
String stat;
if (to<=length) stat = all.substring(from, to);
else stat = all.substring(from);
// If it ends with a ; remove that ;
// Oracle for example can't stand it when this happens...
if (stat.length()>0 && stat.charAt(stat.length()-1)==';')
{
stat = stat.substring(0,stat.length()-1);
}
if (!Const.onlySpaces(stat))
{
String sql=Const.trim(stat);
if (sql.toUpperCase().startsWith("SELECT"))
{
// A Query
log.logDetailed(toString(), "launch SELECT statement: "+Const.CR+sql);
nrstats++;
ResultSet rs = null;
try
{
rs = openQuery(sql);
if (rs!=null)
{
Object[] row = getRow(rs);
while (row!=null)
{
result.setNrLinesRead(result.getNrLinesRead()+1);
if (log.isDetailed()) log.logDetailed(toString(), rowMeta.getString(row));
row = getRow(rs);
}
}
else
{
if (log.isDebug()) log.logDebug(toString(), "Error executing query: "+Const.CR+sql);
}
} catch (KettleValueException e) {
throw new KettleDatabaseException(e); // just pass the error upwards.
}
finally
{
try
{
if ( rs != null ) rs.close();
}
catch (SQLException ex )
{
if (log.isDebug()) log.logDebug(toString(), "Error closing query: "+Const.CR+sql);
}
}
}
else // any kind of statement
{
log.logDetailed(toString(), "launch DDL statement: "+Const.CR+sql);
// A DDL statement
nrstats++;
Result res = execStatement(sql);
result.add(res);
}
}
to++;
from=to;
}
else
{
to++;
}
}
log.logDetailed(toString(), nrstats+" statement"+(nrstats==1?"":"s")+" executed");
return result;
}
public ResultSet openQuery(String sql) throws KettleDatabaseException
{
return openQuery(sql, null, null);
}
/**
* Open a query on the database with a set of parameters stored in a Kettle Row
* @param sql The SQL to launch with question marks (?) as placeholders for the parameters
* @param params The parameters or null if no parameters are used.
* @data the parameter data to open the query with
* @return A JDBC ResultSet
* @throws KettleDatabaseException when something goes wrong with the query.
*/
public ResultSet openQuery(String sql, RowMetaInterface params, Object[] data) throws KettleDatabaseException
{
return openQuery(sql, params, data, ResultSet.FETCH_FORWARD);
}
public ResultSet openQuery(String sql, RowMetaInterface params, Object[] data, int fetch_mode) throws KettleDatabaseException
{
return openQuery(sql, params, data, fetch_mode, false);
}
public ResultSet openQuery(String sql, RowMetaInterface params, Object[] data, int fetch_mode, boolean lazyConversion) throws KettleDatabaseException
{
ResultSet res;
String debug = "Start";
// Create a Statement
try
{
if (params!=null)
{
debug = "P create prepared statement (con==null? "+(connection==null)+")";
pstmt = connection.prepareStatement(databaseMeta.stripCR(sql), ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
debug = "P Set values";
setValues(params, data); // set the dates etc!
if (canWeSetFetchSize(pstmt) )
{
debug = "P Set fetchsize";
int fs = Const.FETCH_SIZE<=pstmt.getMaxRows()?pstmt.getMaxRows():Const.FETCH_SIZE;
// System.out.println("Setting pstmt fetchsize to : "+fs);
{
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_MYSQL && databaseMeta.isStreamingResults())
{
pstmt.setFetchSize(Integer.MIN_VALUE);
}
else
pstmt.setFetchSize(fs);
}
debug = "P Set fetch direction";
pstmt.setFetchDirection(fetch_mode);
}
debug = "P Set max rows";
if (rowlimit>0 && databaseMeta.supportsSetMaxRows()) pstmt.setMaxRows(rowlimit);
debug = "exec query";
res = pstmt.executeQuery();
}
else
{
debug = "create statement";
sel_stmt = connection.createStatement();
if (canWeSetFetchSize(sel_stmt))
{
debug = "Set fetchsize";
int fs = Const.FETCH_SIZE<=sel_stmt.getMaxRows()?sel_stmt.getMaxRows():Const.FETCH_SIZE;
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_MYSQL && databaseMeta.isStreamingResults())
{
sel_stmt.setFetchSize(Integer.MIN_VALUE);
}
else
{
sel_stmt.setFetchSize(fs);
}
debug = "Set fetch direction";
sel_stmt.setFetchDirection(fetch_mode);
}
debug = "Set max rows";
if (rowlimit>0 && databaseMeta.supportsSetMaxRows()) sel_stmt.setMaxRows(rowlimit);
debug = "exec query";
res=sel_stmt.executeQuery(databaseMeta.stripCR(sql));
}
debug = "openQuery : get rowinfo";
// MySQL Hack only. It seems too much for the cursor type of operation on MySQL, to have another cursor opened
// to get the length of a String field. So, on MySQL, we ingore the length of Strings in result rows.
rowMeta = getRowInfo(res.getMetaData(), databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_MYSQL, lazyConversion);
}
catch(SQLException ex)
{
// log.logError(toString(), "ERROR executing ["+sql+"]");
// log.logError(toString(), "ERROR in part: ["+debug+"]");
// printSQLException(ex);
throw new KettleDatabaseException("An error occurred executing SQL: "+Const.CR+sql, ex);
}
catch(Exception e)
{
log.logError(toString(), "ERROR executing query: "+e.toString());
log.logError(toString(), "ERROR in part: "+debug);
throw new KettleDatabaseException("An error occurred executing SQL in part ["+debug+"]:"+Const.CR+sql, e);
}
return res;
}
private boolean canWeSetFetchSize(Statement statement) throws SQLException
{
return databaseMeta.isFetchSizeSupported() &&
( statement.getMaxRows()>0 ||
databaseMeta.getDatabaseType() == DatabaseMeta.TYPE_DATABASE_POSTGRES ||
( databaseMeta.getDatabaseType() == DatabaseMeta.TYPE_DATABASE_MYSQL && databaseMeta.isStreamingResults() )
);
}
public ResultSet openQuery(PreparedStatement ps, RowMetaInterface params, Object[] data) throws KettleDatabaseException
{
ResultSet res;
String debug = "Start";
// Create a Statement
try
{
debug = "OQ Set values";
setValues(params, data, ps); // set the parameters!
if (canWeSetFetchSize(ps))
{
debug = "OQ Set fetchsize";
int fs = Const.FETCH_SIZE<=ps.getMaxRows()?ps.getMaxRows():Const.FETCH_SIZE;
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_MYSQL && databaseMeta.isStreamingResults())
{
ps.setFetchSize(Integer.MIN_VALUE);
}
else
{
ps.setFetchSize(fs);
}
debug = "OQ Set fetch direction";
ps.setFetchDirection(ResultSet.FETCH_FORWARD);
}
debug = "OQ Set max rows";
if (rowlimit>0 && databaseMeta.supportsSetMaxRows()) ps.setMaxRows(rowlimit);
debug = "OQ exec query";
res = ps.executeQuery();
debug = "OQ getRowInfo()";
// rowinfo = getRowInfo(res.getMetaData());
// MySQL Hack only. It seems too much for the cursor type of operation on MySQL, to have another cursor opened
// to get the length of a String field. So, on MySQL, we ingore the length of Strings in result rows.
rowMeta = getRowInfo(res.getMetaData(), databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_MYSQL, false);
}
catch(SQLException ex)
{
throw new KettleDatabaseException("ERROR executing query in part["+debug+"]", ex);
}
catch(Exception e)
{
throw new KettleDatabaseException("ERROR executing query in part["+debug+"]", e);
}
return res;
}
public RowMetaInterface getTableFields(String tablename) throws KettleDatabaseException
{
return getQueryFields(databaseMeta.getSQLQueryFields(tablename), false);
}
public RowMetaInterface getQueryFields(String sql, boolean param) throws KettleDatabaseException
{
return getQueryFields(sql, param, null, null);
}
/**
* See if the table specified exists by reading
* @param tablename The name of the table to check.
* @return true if the table exists, false if it doesn't.
*/
public boolean checkTableExists(String tablename) throws KettleDatabaseException
{
try
{
log.logDebug(toString(), "Checking if table ["+tablename+"] exists!");
// Just try to read from the table.
String sql = databaseMeta.getSQLTableExists(tablename);
try
{
getOneRow(sql);
return true;
}
catch(KettleDatabaseException e)
{
return false;
}
/*
if (getDatabaseMetaData()!=null)
{
ResultSet alltables = getDatabaseMetaData().getTables(null, null, "%" , new String[] { "TABLE", "VIEW", "SYNONYM" } );
boolean found = false;
if (alltables!=null)
{
while (alltables.next() && !found)
{
String schemaName = alltables.getString("TABLE_SCHEM");
String name = alltables.getString("TABLE_NAME");
if ( tablename.equalsIgnoreCase(name) ||
( schemaName!=null && tablename.equalsIgnoreCase( databaseMeta.getSchemaTableCombination(schemaName, name)) )
)
{
log.logDebug(toString(), "table ["+tablename+"] was found!");
found=true;
}
}
alltables.close();
return found;
}
else
{
throw new KettleDatabaseException("Unable to read table-names from the database meta-data.");
}
}
else
{
throw new KettleDatabaseException("Unable to get database meta-data from the database.");
}
*/
}
catch(Exception e)
{
throw new KettleDatabaseException("Unable to check if table ["+tablename+"] exists on connection ["+databaseMeta.getName()+"]", e);
}
}
/**
* Check whether the sequence exists, Oracle only!
* @param sequenceName The name of the sequence
* @return true if the sequence exists.
*/
public boolean checkSequenceExists(String sequenceName) throws KettleDatabaseException
{
return checkSequenceExists(null, sequenceName);
}
/**
* Check whether the sequence exists, Oracle only!
* @param sequenceName The name of the sequence
* @return true if the sequence exists.
*/
public boolean checkSequenceExists(String schemaName, String sequenceName) throws KettleDatabaseException
{
boolean retval=false;
if (!databaseMeta.supportsSequences()) return retval;
String schemaSequence = databaseMeta.getQuotedSchemaTableCombination(schemaName, sequenceName);
try
{
// Get the info from the data dictionary...
String sql = databaseMeta.getSQLSequenceExists(schemaSequence);
ResultSet res = openQuery(sql);
if (res!=null)
{
Object[] row = getRow(res);
if (row!=null)
{
retval=true;
}
closeQuery(res);
}
}
catch(Exception e)
{
throw new KettleDatabaseException("Unexpected error checking whether or not sequence ["+schemaSequence+"] exists", e);
}
return retval;
}
/**
* Check if an index on certain fields in a table exists.
* @param tableName The table on which the index is checked
* @param idx_fields The fields on which the indexe is checked
* @return True if the index exists
*/
public boolean checkIndexExists(String tableName, String idx_fields[]) throws KettleDatabaseException
{
return checkIndexExists(null, tableName, idx_fields);
}
/**
* Check if an index on certain fields in a table exists.
* @param tablename The table on which the index is checked
* @param idx_fields The fields on which the indexe is checked
* @return True if the index exists
*/
public boolean checkIndexExists(String schemaName, String tableName, String idx_fields[]) throws KettleDatabaseException
{
String tablename = databaseMeta.getQuotedSchemaTableCombination(schemaName, tableName);
if (!checkTableExists(tablename)) return false;
log.logDebug(toString(), "CheckIndexExists() tablename = "+tablename+" type = "+databaseMeta.getDatabaseTypeDesc());
boolean exists[] = new boolean[idx_fields.length];
for (int i=0;i<exists.length;i++) exists[i]=false;
try
{
switch(databaseMeta.getDatabaseType())
{
case DatabaseMeta.TYPE_DATABASE_MSSQL:
{
// Get the info from the data dictionary...
StringBuffer sql = new StringBuffer(128);
sql.append("select i.name table_name, c.name column_name ");
sql.append("from sysindexes i, sysindexkeys k, syscolumns c ");
sql.append("where i.name = '"+tablename+"' ");
sql.append("AND i.id = k.id ");
sql.append("AND i.id = c.id ");
sql.append("AND k.colid = c.colid ");
ResultSet res = null;
try
{
res = openQuery(sql.toString());
if (res!=null)
{
Object[] row = getRow(res);
while (row!=null)
{
String column = rowMeta.getString(row, "column_name", "");
int idx = Const.indexOfString(column, idx_fields);
if (idx>=0) exists[idx]=true;
row = getRow(res);
}
}
else
{
return false;
}
}
finally
{
if ( res != null ) closeQuery(res);
}
}
break;
case DatabaseMeta.TYPE_DATABASE_ORACLE:
{
// Get the info from the data dictionary...
String sql = "SELECT * FROM USER_IND_COLUMNS WHERE TABLE_NAME = '"+tableName+"'";
ResultSet res = null;
try {
res = openQuery(sql);
if (res!=null)
{
Object[] row = getRow(res);
while (row!=null)
{
String column = rowMeta.getString(row, "COLUMN_NAME", "");
int idx = Const.indexOfString(column, idx_fields);
if (idx>=0)
{
exists[idx]=true;
}
row = getRow(res);
}
}
else
{
return false;
}
}
finally
{
if ( res != null ) closeQuery(res);
}
}
break;
case DatabaseMeta.TYPE_DATABASE_ACCESS:
{
// Get a list of all the indexes for this table
ResultSet indexList = null;
try
{
indexList = getDatabaseMetaData().getIndexInfo(null,null,tablename,false,true);
while (indexList.next())
{
// String tablen = indexList.getString("TABLE_NAME");
// String indexn = indexList.getString("INDEX_NAME");
String column = indexList.getString("COLUMN_NAME");
// int pos = indexList.getShort("ORDINAL_POSITION");
// int type = indexList.getShort("TYPE");
int idx = Const.indexOfString(column, idx_fields);
if (idx>=0)
{
exists[idx]=true;
}
}
}
finally
{
if ( indexList != null ) indexList.close();
}
}
break;
default:
{
// Get a list of all the indexes for this table
ResultSet indexList = null;
try
{
indexList = getDatabaseMetaData().getIndexInfo(null,null,tablename,false,true);
while (indexList.next())
{
// String tablen = indexList.getString("TABLE_NAME");
// String indexn = indexList.getString("INDEX_NAME");
String column = indexList.getString("COLUMN_NAME");
// int pos = indexList.getShort("ORDINAL_POSITION");
// int type = indexList.getShort("TYPE");
int idx = Const.indexOfString(column, idx_fields);
if (idx>=0)
{
exists[idx]=true;
}
}
}
finally
{
if ( indexList != null ) indexList.close();
}
}
break;
}
// See if all the fields are indexed...
boolean all=true;
for (int i=0;i<exists.length && all;i++) if (!exists[i]) all=false;
return all;
}
catch(Exception e)
{
log.logError(toString(), Const.getStackTracker(e));
throw new KettleDatabaseException("Unable to determine if indexes exists on table ["+tablename+"]", e);
}
}
public String getCreateIndexStatement(String tablename, String indexname, String idx_fields[], boolean tk, boolean unique, boolean bitmap, boolean semi_colon)
{
return getCreateIndexStatement(null, tablename, indexname, idx_fields, tk, unique, bitmap, semi_colon);
}
public String getCreateIndexStatement(String schemaname, String tablename, String indexname, String idx_fields[], boolean tk, boolean unique, boolean bitmap, boolean semi_colon)
{
String cr_index="";
cr_index += "CREATE ";
if (unique || ( tk && databaseMeta.getDatabaseType() == DatabaseMeta.TYPE_DATABASE_SYBASE))
cr_index += "UNIQUE ";
if (bitmap && databaseMeta.supportsBitmapIndex())
cr_index += "BITMAP ";
cr_index += "INDEX "+databaseMeta.quoteField(indexname)+Const.CR+" ";
cr_index += "ON ";
// assume table has already been quoted (and possibly includes schema)
cr_index += tablename;
cr_index += Const.CR + "( "+Const.CR;
for (int i=0;i<idx_fields.length;i++)
{
if (i>0) cr_index+=", "; else cr_index+=" ";
cr_index += databaseMeta.quoteField(idx_fields[i])+Const.CR;
}
cr_index+=")"+Const.CR;
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_ORACLE &&
databaseMeta.getIndexTablespace()!=null && databaseMeta.getIndexTablespace().length()>0)
{
cr_index+="TABLESPACE "+databaseMeta.quoteField(databaseMeta.getIndexTablespace());
}
if (semi_colon)
{
cr_index+=";"+Const.CR;
}
return cr_index;
}
public String getCreateSequenceStatement(String sequence, long start_at, long increment_by, long max_value, boolean semi_colon)
{
return getCreateSequenceStatement(null, sequence, Long.toString(start_at), Long.toString(increment_by), Long.toString(max_value), semi_colon);
}
public String getCreateSequenceStatement(String sequence, String start_at, String increment_by, String max_value, boolean semi_colon)
{
return getCreateSequenceStatement(null, sequence, start_at, increment_by, max_value, semi_colon);
}
public String getCreateSequenceStatement(String schemaName, String sequence, long start_at, long increment_by, long max_value, boolean semi_colon)
{
return getCreateSequenceStatement(schemaName, sequence, Long.toString(start_at), Long.toString(increment_by), Long.toString(max_value), semi_colon);
}
public String getCreateSequenceStatement(String schemaName, String sequenceName, String start_at, String increment_by, String max_value, boolean semi_colon)
{
String cr_seq="";
if (Const.isEmpty(sequenceName)) return cr_seq;
if (databaseMeta.supportsSequences())
{
String schemaSequence = databaseMeta.getQuotedSchemaTableCombination(schemaName, sequenceName);
cr_seq += "CREATE SEQUENCE "+schemaSequence+" "+Const.CR; // Works for both Oracle and PostgreSQL :-)
cr_seq += "START WITH "+start_at+" "+Const.CR;
cr_seq += "INCREMENT BY "+increment_by+" "+Const.CR;
if (max_value != null) cr_seq += "MAXVALUE "+max_value+Const.CR;
if (semi_colon) cr_seq+=";"+Const.CR;
}
return cr_seq;
}
public RowMetaInterface getQueryFields(String sql, boolean param, RowMetaInterface inform, Object[] data) throws KettleDatabaseException
{
RowMetaInterface fields;
DBCache dbcache = DBCache.getInstance();
DBCacheEntry entry=null;
// Check the cache first!
if (dbcache!=null)
{
entry = new DBCacheEntry(databaseMeta.getName(), sql);
fields = dbcache.get(entry);
if (fields!=null)
{
return fields;
}
}
if (connection==null) return null; // Cache test without connect.
// No cache entry found
// The new method of retrieving the query fields fails on Oracle because
// they failed to implement the getMetaData method on a prepared statement. (!!!)
// Even recent drivers like 10.2 fail because of it.
// There might be other databases that don't support it (we have no knowledge of this at the time of writing).
// If we discover other RDBMSs, we will create an interface for it.
// For now, we just try to get the field layout on the re-bound in the exception block below.
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_ORACLE ||
databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_H2 ||
databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_GENERIC)
{
fields=getQueryFieldsFallback(sql, param, inform, data);
}
else
{
// On with the regular program.
PreparedStatement preparedStatement = null;
try
{
preparedStatement = connection.prepareStatement(databaseMeta.stripCR(sql), ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
ResultSetMetaData rsmd = preparedStatement.getMetaData();
fields = getRowInfo(rsmd, false, false);
}
catch(Exception e)
{
fields = getQueryFieldsFallback(sql, param, inform, data);
}
finally
{
if (preparedStatement!=null)
{
try
{
preparedStatement.close();
}
catch (SQLException e)
{
throw new KettleDatabaseException("Unable to close prepared statement after determining SQL layout", e);
}
}
}
}
// Store in cache!!
if (dbcache!=null && entry!=null)
{
if (fields!=null)
{
dbcache.put(entry, fields);
}
}
return fields;
}
private RowMetaInterface getQueryFieldsFallback(String sql, boolean param, RowMetaInterface inform, Object[] data) throws KettleDatabaseException
{
RowMetaInterface fields;
try
{
if (inform==null
// Hack for MSSQL jtds 1.2 when using xxx NOT IN yyy we have to use a prepared statement (see BugID 3214)
&& databaseMeta.getDatabaseType()!=DatabaseMeta.TYPE_DATABASE_MSSQL
)
{
sel_stmt = connection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
if (databaseMeta.isFetchSizeSupported() && sel_stmt.getMaxRows()>=1)
{
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_MYSQL)
{
sel_stmt.setFetchSize(Integer.MIN_VALUE);
}
else
{
sel_stmt.setFetchSize(1);
}
}
if (databaseMeta.supportsSetMaxRows()) sel_stmt.setMaxRows(1);
ResultSet r=sel_stmt.executeQuery(databaseMeta.stripCR(sql));
fields = getRowInfo(r.getMetaData(), false, false);
r.close();
sel_stmt.close();
sel_stmt=null;
}
else
{
PreparedStatement ps = connection.prepareStatement(databaseMeta.stripCR(sql));
if (param)
{
RowMetaInterface par = inform;
if (par==null || par.isEmpty()) par = getParameterMetaData(ps);
if (par==null || par.isEmpty()) par = getParameterMetaData(sql, inform, data);
setValues(par, data, ps);
}
ResultSet r = ps.executeQuery();
fields=getRowInfo(ps.getMetaData(), false, false);
r.close();
ps.close();
}
}
catch(Exception ex)
{
throw new KettleDatabaseException("Couldn't get field info from ["+sql+"]"+Const.CR, ex);
}
return fields;
}
public void closeQuery(ResultSet res) throws KettleDatabaseException
{
// close everything involved in the query!
try
{
if (res!=null) res.close();
if (sel_stmt!=null) { sel_stmt.close(); sel_stmt=null; }
if (pstmt!=null) { pstmt.close(); pstmt=null;}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Couldn't close query: resultset or prepared statements", ex);
}
}
/**
* Build the row using ResultSetMetaData rsmd
* @param rm The resultset metadata to inquire
* @param ignoreLength true if you want to ignore the length (workaround for MySQL bug/problem)
* @param lazyConversion true if lazy conversion needs to be enabled where possible
*/
private RowMetaInterface getRowInfo(ResultSetMetaData rm, boolean ignoreLength, boolean lazyConversion) throws KettleDatabaseException
{
if (rm==null) return null;
rowMeta = new RowMeta();
try
{
// TODO If we do lazy conversion, we need to find out about the encoding
int fieldNr = 1;
int nrcols=rm.getColumnCount();
for (int i=1;i<=nrcols;i++)
{
String name=new String(rm.getColumnName(i));
// Check the name, sometimes it's empty.
if (Const.isEmpty(name) || Const.onlySpaces(name))
{
name = "Field"+fieldNr;
fieldNr++;
}
ValueMetaInterface v = getValueFromSQLType(name, rm, i, ignoreLength, lazyConversion);
rowMeta.addValueMeta(v);
}
return rowMeta;
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Error getting row information from database: ", ex);
}
}
private ValueMetaInterface getValueFromSQLType(String name, ResultSetMetaData rm, int index, boolean ignoreLength, boolean lazyConversion) throws SQLException
{
int length=-1;
int precision=-1;
int valtype=ValueMetaInterface.TYPE_NONE;
boolean isClob = false;
int type = rm.getColumnType(index);
switch(type)
{
case java.sql.Types.CHAR:
case java.sql.Types.VARCHAR:
case java.sql.Types.LONGVARCHAR: // Character Large Object
valtype=ValueMetaInterface.TYPE_STRING;
if (!ignoreLength) length=rm.getColumnDisplaySize(index);
break;
case java.sql.Types.CLOB:
valtype=ValueMetaInterface.TYPE_STRING;
length=DatabaseMeta.CLOB_LENGTH;
isClob=true;
break;
case java.sql.Types.BIGINT:
valtype=ValueMetaInterface.TYPE_INTEGER;
precision=0; // Max 9.223.372.036.854.775.807
length=15;
break;
case java.sql.Types.INTEGER:
valtype=ValueMetaInterface.TYPE_INTEGER;
precision=0; // Max 2.147.483.647
length=9;
break;
case java.sql.Types.SMALLINT:
valtype=ValueMetaInterface.TYPE_INTEGER;
precision=0; // Max 32.767
length=4;
break;
case java.sql.Types.TINYINT:
valtype=ValueMetaInterface.TYPE_INTEGER;
precision=0; // Max 127
length=2;
break;
case java.sql.Types.DECIMAL:
case java.sql.Types.DOUBLE:
case java.sql.Types.FLOAT:
case java.sql.Types.REAL:
case java.sql.Types.NUMERIC:
valtype=ValueMetaInterface.TYPE_NUMBER;
length=rm.getPrecision(index);
precision=rm.getScale(index);
if (length >=126) length=-1;
if (precision >=126) precision=-1;
if (type==java.sql.Types.DOUBLE || type==java.sql.Types.FLOAT || type==java.sql.Types.REAL)
{
if (precision==0)
{
precision=-1; // precision is obviously incorrect if the type if Double/Float/Real
}
// If we're dealing with PostgreSQL and double precision types
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_POSTGRES && type==java.sql.Types.DOUBLE && precision==16 && length==16)
{
precision=-1;
length=-1;
}
// MySQL: max resolution is double precision floating point (double)
// The (12,31) that is given back is not correct
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_MYSQL)
{
if (precision >= length) {
precision=-1;
length=-1;
}
}
}
else
{
if (precision==0 && length<18 && length>0) // Among others Oracle is affected here.
{
valtype=ValueMetaInterface.TYPE_INTEGER;
}
}
if (length>18 || precision>18) valtype=ValueMetaInterface.TYPE_BIGNUMBER;
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_ORACLE)
{
if (precision == 0 && length == 38 )
{
valtype=ValueMetaInterface.TYPE_INTEGER;
}
if (precision<=0 && length<=0) // undefined size: NUMBER
{
valtype=ValueMetaInterface.TYPE_NUMBER;
length=-1;
precision=-1;
}
}
break;
case java.sql.Types.DATE:
if (databaseMeta.getDatabaseType() == DatabaseMeta.TYPE_DATABASE_TERADATA) {
precision = 1;
}
case java.sql.Types.TIME:
case java.sql.Types.TIMESTAMP:
valtype=ValueMetaInterface.TYPE_DATE;
if (databaseMeta.getDatabaseType() == DatabaseMeta.TYPE_DATABASE_MYSQL) {
String property = databaseMeta.getConnectionProperties().getProperty("yearIsDateType");
if (property != null && property.equalsIgnoreCase("false")
&& rm.getColumnTypeName(index).equalsIgnoreCase("YEAR")) {
valtype = ValueMetaInterface.TYPE_INTEGER;
precision = 0;
length = 4;
break;
}
}
break;
case java.sql.Types.BOOLEAN:
case java.sql.Types.BIT:
valtype=ValueMetaInterface.TYPE_BOOLEAN;
break;
case java.sql.Types.BINARY:
case java.sql.Types.BLOB:
case java.sql.Types.VARBINARY:
case java.sql.Types.LONGVARBINARY:
valtype=ValueMetaInterface.TYPE_BINARY;
if (databaseMeta.getDatabaseType() == DatabaseMeta.TYPE_DATABASE_DB2 &&
(2 * rm.getPrecision(index)) == rm.getColumnDisplaySize(index))
{
// set the length for "CHAR(X) FOR BIT DATA"
length = rm.getPrecision(index);
}
else
if (databaseMeta.getDatabaseType() == DatabaseMeta.TYPE_DATABASE_ORACLE &&
( type==java.sql.Types.VARBINARY || type==java.sql.Types.LONGVARBINARY )
)
{
// set the length for Oracle "RAW" or "LONGRAW" data types
valtype = ValueMetaInterface.TYPE_STRING;
length = rm.getColumnDisplaySize(index);
}
else
{
length=-1;
}
precision=-1;
break;
default:
valtype=ValueMetaInterface.TYPE_STRING;
precision=rm.getScale(index);
break;
}
// Grab the comment as a description to the field as well.
String comments=rm.getColumnLabel(index);
// get & store more result set meta data for later use
int originalColumnType=rm.getColumnType(index);
String originalColumnTypeName=rm.getColumnTypeName(index);
int originalPrecision=-1;
if (!ignoreLength) rm.getPrecision(index); // Throws exception on MySQL
int originalScale=rm.getScale(index);
boolean originalAutoIncrement=rm.isAutoIncrement(index);
int originalNullable=rm.isNullable(index);
boolean originalSigned=rm.isSigned(index);
ValueMetaInterface v=new ValueMeta(name, valtype);
v.setLength(length);
v.setPrecision(precision);
v.setComments(comments);
v.setLargeTextField(isClob);
v.setOriginalColumnType(originalColumnType);
v.setOriginalColumnTypeName(originalColumnTypeName);
v.setOriginalPrecision(originalPrecision);
v.setOriginalScale(originalScale);
v.setOriginalAutoIncrement(originalAutoIncrement);
v.setOriginalNullable(originalNullable);
v.setOriginalSigned(originalSigned);
// See if we need to enable lazy conversion...
if (lazyConversion && valtype==ValueMetaInterface.TYPE_STRING) {
v.setStorageType(ValueMetaInterface.STORAGE_TYPE_BINARY_STRING);
// TODO set some encoding to go with this.
// Also set the storage metadata. a copy of the parent, set to String too.
ValueMetaInterface storageMetaData = v.clone();
storageMetaData.setType(ValueMetaInterface.TYPE_STRING);
storageMetaData.setStorageType(ValueMetaInterface.STORAGE_TYPE_NORMAL);
v.setStorageMetadata(storageMetaData);
}
return v;
}
public boolean absolute(ResultSet rs, int position) throws KettleDatabaseException
{
try
{
return rs.absolute(position);
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to move resultset to position "+position, e);
}
}
public boolean relative(ResultSet rs, int rows) throws KettleDatabaseException
{
try
{
return rs.relative(rows);
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to move the resultset forward "+rows+" rows", e);
}
}
public void afterLast(ResultSet rs)
throws KettleDatabaseException
{
try
{
rs.afterLast();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to move resultset to after the last position", e);
}
}
public void first(ResultSet rs) throws KettleDatabaseException
{
try
{
rs.first();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to move resultset to the first position", e);
}
}
/**
* Get a row from the resultset. Do not use lazy conversion
* @param rs The resultset to get the row from
* @return one row or null if no row was found on the resultset or if an error occurred.
*/
public Object[] getRow(ResultSet rs) throws KettleDatabaseException
{
return getRow(rs, false);
}
/**
* Get a row from the resultset.
* @param rs The resultset to get the row from
* @param lazyConversion set to true if strings need to have lazy conversion enabled
* @return one row or null if no row was found on the resultset or if an error occurred.
*/
public Object[] getRow(ResultSet rs, boolean lazyConversion) throws KettleDatabaseException
{
if (rowMeta==null)
{
ResultSetMetaData rsmd = null;
try
{
rsmd = rs.getMetaData();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to retrieve metadata from resultset", e);
}
rowMeta = getRowInfo(rsmd, false, lazyConversion);
}
return getRow(rs, null, rowMeta);
}
/**
* Get a row from the resultset.
* @param rs The resultset to get the row from
* @return one row or null if no row was found on the resultset or if an error occurred.
*/
public Object[] getRow(ResultSet rs, ResultSetMetaData dummy, RowMetaInterface rowInfo) throws KettleDatabaseException
{
try
{
int nrcols=rowInfo.size();
Object[] data = RowDataUtil.allocateRowData(nrcols);
if (rs.next())
{
for (int i=0;i<nrcols;i++)
{
ValueMetaInterface val = rowInfo.getValueMeta(i);
switch(val.getType())
{
case ValueMetaInterface.TYPE_BOOLEAN : data[i] = Boolean.valueOf( rs.getBoolean(i+1) ); break;
case ValueMetaInterface.TYPE_NUMBER : data[i] = new Double( rs.getDouble(i+1) ); break;
case ValueMetaInterface.TYPE_BIGNUMBER : data[i] = rs.getBigDecimal(i+1); break;
case ValueMetaInterface.TYPE_INTEGER : data[i] = Long.valueOf( rs.getLong(i+1) ); break;
case ValueMetaInterface.TYPE_STRING :
{
if (val.isStorageBinaryString()) {
data[i] = rs.getBytes(i+1);
}
else {
data[i] = rs.getString(i+1);
}
}
break;
case ValueMetaInterface.TYPE_BINARY :
{
if (databaseMeta.supportsGetBlob())
{
Blob blob = rs.getBlob(i+1);
if (blob!=null)
{
data[i] = blob.getBytes(1L, (int)blob.length());
}
else
{
data[i] = null;
}
}
else
{
data[i] = rs.getBytes(i+1);
}
}
break;
case ValueMetaInterface.TYPE_DATE :
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_NEOVIEW && val.getOriginalColumnType()==java.sql.Types.TIME)
{
// Neoview can not handle getDate / getTimestamp for a Time column
data[i] = rs.getTime(i+1); break; // Time is a subclass of java.util.Date, the default date will be 1970-01-01
}
else if (val.getPrecision()!=1 && databaseMeta.supportsTimeStampToDateConversion())
{
data[i] = rs.getTimestamp(i+1); break; // Timestamp extends java.util.Date
}
else
{
data[i] = rs.getDate(i+1); break;
}
default: break;
}
if (rs.wasNull()) data[i] = null; // null value, it's the default but we want it just to make sure we handle this case too.
}
}
else
{
data=null;
}
return data;
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Couldn't get row from result set", ex);
}
}
public void printSQLException(SQLException ex)
{
log.logError(toString(), "==> SQLException: ");
while (ex != null)
{
log.logError(toString(), "Message: " + ex.getMessage ());
log.logError(toString(), "SQLState: " + ex.getSQLState ());
log.logError(toString(), "ErrorCode: " + ex.getErrorCode ());
ex = ex.getNextException();
log.logError(toString(), "");
}
}
public void setLookup(String table, String codes[], String condition[],
String gets[], String rename[], String orderby
) throws KettleDatabaseException
{
setLookup(table, codes, condition, gets, rename, orderby, false);
}
public void setLookup(String schema, String table, String codes[], String condition[],
String gets[], String rename[], String orderby
) throws KettleDatabaseException
{
setLookup(schema, table, codes, condition, gets, rename, orderby, false);
}
public void setLookup(String tableName, String codes[], String condition[],
String gets[], String rename[], String orderby,
boolean checkForMultipleResults) throws KettleDatabaseException
{
setLookup(null, tableName, codes, condition, gets, rename, orderby, checkForMultipleResults);
}
// Lookup certain fields in a table
public void setLookup(String schemaName, String tableName, String codes[], String condition[],
String gets[], String rename[], String orderby,
boolean checkForMultipleResults) throws KettleDatabaseException
{
String table = databaseMeta.getQuotedSchemaTableCombination(schemaName, tableName);
String sql = "SELECT ";
for (int i=0;i<gets.length;i++)
{
if (i!=0) sql += ", ";
sql += databaseMeta.quoteField(gets[i]);
if (rename!=null && rename[i]!=null && !gets[i].equalsIgnoreCase(rename[i]))
{
sql+=" AS "+databaseMeta.quoteField(rename[i]);
}
}
sql += " FROM "+table+" WHERE ";
for (int i=0;i<codes.length;i++)
{
if (i!=0) sql += " AND ";
sql += databaseMeta.quoteField(codes[i]);
if ("BETWEEN".equalsIgnoreCase(condition[i]))
{
sql+=" BETWEEN ? AND ? ";
}
else
if ("IS NULL".equalsIgnoreCase(condition[i]) || "IS NOT NULL".equalsIgnoreCase(condition[i]))
{
sql+=" "+condition[i]+" ";
}
else
{
sql+=" "+condition[i]+" ? ";
}
}
if (orderby!=null && orderby.length()!=0)
{
sql += " ORDER BY "+orderby;
}
try
{
log.logDetailed(toString(), "Setting preparedStatement to ["+sql+"]");
prepStatementLookup=connection.prepareStatement(databaseMeta.stripCR(sql));
if (!checkForMultipleResults && databaseMeta.supportsSetMaxRows())
{
prepStatementLookup.setMaxRows(1); // alywas get only 1 line back!
}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to prepare statement for update ["+sql+"]", ex);
}
}
public boolean prepareUpdate(String table, String codes[], String condition[], String sets[])
{
return prepareUpdate(null, table, codes, condition, sets);
}
// Lookup certain fields in a table
public boolean prepareUpdate(String schemaName, String tableName, String codes[], String condition[], String sets[])
{
StringBuffer sql = new StringBuffer(128);
String schemaTable = databaseMeta.getQuotedSchemaTableCombination(schemaName, tableName);
sql.append("UPDATE ").append(schemaTable).append(Const.CR).append("SET ");
for (int i=0;i<sets.length;i++)
{
if (i!=0) sql.append(", ");
sql.append(databaseMeta.quoteField(sets[i]));
sql.append(" = ?").append(Const.CR);
}
sql.append("WHERE ");
for (int i=0;i<codes.length;i++)
{
if (i!=0) sql.append("AND ");
sql.append(databaseMeta.quoteField(codes[i]));
if ("BETWEEN".equalsIgnoreCase(condition[i]))
{
sql.append(" BETWEEN ? AND ? ");
}
else
if ("IS NULL".equalsIgnoreCase(condition[i]) || "IS NOT NULL".equalsIgnoreCase(condition[i]))
{
sql.append(' ').append(condition[i]).append(' ');
}
else
{
sql.append(' ').append(condition[i]).append(" ? ");
}
}
try
{
String s = sql.toString();
log.logDetailed(toString(), "Setting update preparedStatement to ["+s+"]");
prepStatementUpdate=connection.prepareStatement(databaseMeta.stripCR(s));
}
catch(SQLException ex)
{
printSQLException(ex);
return false;
}
return true;
}
/**
* Prepare a delete statement by giving it the tablename, fields and conditions to work with.
* @param table The table-name to delete in
* @param codes
* @param condition
* @return true when everything went OK, false when something went wrong.
*/
public boolean prepareDelete(String table, String codes[], String condition[])
{
return prepareDelete(null, table, codes, condition);
}
/**
* Prepare a delete statement by giving it the tablename, fields and conditions to work with.
* @param schemaName the schema-name to delete in
* @param tableName The table-name to delete in
* @param codes
* @param condition
* @return true when everything went OK, false when something went wrong.
*/
public boolean prepareDelete(String schemaName, String tableName, String codes[], String condition[])
{
String sql;
String table = databaseMeta.getQuotedSchemaTableCombination(schemaName, tableName);
sql = "DELETE FROM "+table+Const.CR;
sql+= "WHERE ";
for (int i=0;i<codes.length;i++)
{
if (i!=0) sql += "AND ";
sql += codes[i];
if ("BETWEEN".equalsIgnoreCase(condition[i]))
{
sql+=" BETWEEN ? AND ? ";
}
else
if ("IS NULL".equalsIgnoreCase(condition[i]) || "IS NOT NULL".equalsIgnoreCase(condition[i]))
{
sql+=" "+condition[i]+" ";
}
else
{
sql+=" "+condition[i]+" ? ";
}
}
try
{
log.logDetailed(toString(), "Setting update preparedStatement to ["+sql+"]");
prepStatementUpdate=connection.prepareStatement(databaseMeta.stripCR(sql));
}
catch(SQLException ex)
{
printSQLException(ex);
return false;
}
return true;
}
public void setProcLookup(String proc, String arg[], String argdir[], int argtype[], String returnvalue, int returntype)
throws KettleDatabaseException
{
String sql;
int pos=0;
sql = "{ ";
if (returnvalue!=null && returnvalue.length()!=0)
{
sql+="? = ";
}
sql+="call "+proc+" ";
if (arg.length>0) sql+="(";
for (int i=0;i<arg.length;i++)
{
if (i!=0) sql += ", ";
sql += " ?";
}
if (arg.length>0) sql+=")";
sql+="}";
try
{
log.logDetailed(toString(), "DBA setting callableStatement to ["+sql+"]");
cstmt=connection.prepareCall(sql);
pos=1;
if (!Const.isEmpty(returnvalue))
{
switch(returntype)
{
case ValueMetaInterface.TYPE_NUMBER : cstmt.registerOutParameter(pos, java.sql.Types.DOUBLE); break;
case ValueMetaInterface.TYPE_BIGNUMBER : cstmt.registerOutParameter(pos, java.sql.Types.DECIMAL); break;
case ValueMetaInterface.TYPE_INTEGER : cstmt.registerOutParameter(pos, java.sql.Types.BIGINT); break;
case ValueMetaInterface.TYPE_STRING : cstmt.registerOutParameter(pos, java.sql.Types.VARCHAR); break;
case ValueMetaInterface.TYPE_DATE : cstmt.registerOutParameter(pos, java.sql.Types.TIMESTAMP); break;
case ValueMetaInterface.TYPE_BOOLEAN : cstmt.registerOutParameter(pos, java.sql.Types.BOOLEAN); break;
default: break;
}
pos++;
}
for (int i=0;i<arg.length;i++)
{
if (argdir[i].equalsIgnoreCase("OUT") || argdir[i].equalsIgnoreCase("INOUT"))
{
switch(argtype[i])
{
case ValueMetaInterface.TYPE_NUMBER : cstmt.registerOutParameter(i+pos, java.sql.Types.DOUBLE); break;
case ValueMetaInterface.TYPE_BIGNUMBER : cstmt.registerOutParameter(i+pos, java.sql.Types.DECIMAL); break;
case ValueMetaInterface.TYPE_INTEGER : cstmt.registerOutParameter(i+pos, java.sql.Types.BIGINT); break;
case ValueMetaInterface.TYPE_STRING : cstmt.registerOutParameter(i+pos, java.sql.Types.VARCHAR); break;
case ValueMetaInterface.TYPE_DATE : cstmt.registerOutParameter(i+pos, java.sql.Types.TIMESTAMP); break;
case ValueMetaInterface.TYPE_BOOLEAN : cstmt.registerOutParameter(i+pos, java.sql.Types.BOOLEAN); break;
default: break;
}
}
}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to prepare database procedure call", ex);
}
}
public Object[] getLookup() throws KettleDatabaseException
{
return getLookup(prepStatementLookup);
}
public Object[] getLookup(boolean failOnMultipleResults) throws KettleDatabaseException
{
return getLookup(prepStatementLookup, failOnMultipleResults);
}
public Object[] getLookup(PreparedStatement ps) throws KettleDatabaseException
{
return getLookup(ps, false);
}
public Object[] getLookup(PreparedStatement ps, boolean failOnMultipleResults) throws KettleDatabaseException
{
String debug = "start";
ResultSet res = null;
try
{
debug = "pstmt.executeQuery()";
res = ps.executeQuery();
debug = "getRowInfo()";
rowMeta = getRowInfo(res.getMetaData(), false, false);
debug = "getRow(res)";
Object[] ret = getRow(res);
if (failOnMultipleResults)
{
if (ret != null && res.next())
{
// if the previous row was null, there's no reason to try res.next() again.
// on DB2 this will even cause an exception (because of the buggy DB2 JDBC driver).
throw new KettleDatabaseException("Only 1 row was expected as a result of a lookup, and at least 2 were found!");
}
}
return ret;
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Error looking up row in database ("+debug+")", ex);
}
finally
{
try
{
debug = "res.close()";
if (res!=null) res.close(); // close resultset!
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to close resultset after looking up data", e);
}
}
}
public DatabaseMetaData getDatabaseMetaData() throws KettleDatabaseException
{
try
{
if (dbmd==null) dbmd = connection.getMetaData(); // Only get the metadata once!
}
catch(Exception e)
{
throw new KettleDatabaseException("Unable to get database metadata from this database connection", e);
}
return dbmd;
}
public String getDDL(String tablename, RowMetaInterface fields) throws KettleDatabaseException
{
return getDDL(tablename, fields, null, false, null, true);
}
public String getDDL(String tablename, RowMetaInterface fields, String tk, boolean use_autoinc, String pk) throws KettleDatabaseException
{
return getDDL(tablename, fields, tk, use_autoinc, pk, true);
}
public String getDDL(String tableName, RowMetaInterface fields, String tk, boolean use_autoinc, String pk, boolean semicolon) throws KettleDatabaseException
{
String retval;
// First, check for reserved SQL in the input row r...
databaseMeta.quoteReservedWords(fields);
String quotedTk = tk != null ? databaseMeta.quoteField(tk) : null;
if (checkTableExists(tableName))
{
retval=getAlterTableStatement(tableName, fields, quotedTk, use_autoinc, pk, semicolon);
}
else
{
retval=getCreateTableStatement(tableName, fields, quotedTk, use_autoinc, pk, semicolon);
}
return retval;
}
/**
* Generates SQL
* @param tableName the table name or schema/table combination: this needs to be quoted properly in advance.
* @param fields the fields
* @param tk the name of the technical key field
* @param use_autoinc true if we need to use auto-increment fields for a primary key
* @param pk the name of the primary/technical key field
* @param semicolon append semicolon to the statement
* @return the SQL needed to create the specified table and fields.
*/
public String getCreateTableStatement(String tableName, RowMetaInterface fields, String tk, boolean use_autoinc, String pk, boolean semicolon)
{
String retval;
retval = "CREATE TABLE "+tableName+Const.CR;
retval+= "("+Const.CR;
for (int i=0;i<fields.size();i++)
{
if (i>0) retval+=", "; else retval+=" ";
ValueMetaInterface v=fields.getValueMeta(i);
retval+=databaseMeta.getFieldDefinition(v, tk, pk, use_autoinc);
}
// At the end, before the closing of the statement, we might need to add some constraints...
// Technical keys
if (tk!=null)
{
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_CACHE)
{
retval+=", PRIMARY KEY ("+tk+")"+Const.CR;
}
}
// Primary keys
if (pk!=null)
{
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_ORACLE)
{
retval+=", PRIMARY KEY ("+pk+")"+Const.CR;
}
}
retval+= ")"+Const.CR;
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_ORACLE &&
databaseMeta.getIndexTablespace()!=null && databaseMeta.getIndexTablespace().length()>0)
{
retval+="TABLESPACE "+databaseMeta.getDataTablespace();
}
if (pk==null && tk==null && databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_NEOVIEW)
{
retval+="NO PARTITION"; // use this as a default when no pk/tk is there, otherwise you get an error
}
if (semicolon) retval+=";";
retval+=Const.CR;
return retval;
}
public String getAlterTableStatement(String tableName, RowMetaInterface fields, String tk, boolean use_autoinc, String pk, boolean semicolon) throws KettleDatabaseException
{
String retval="";
// Get the fields that are in the table now:
RowMetaInterface tabFields = getTableFields(tableName);
// Don't forget to quote these as well...
databaseMeta.quoteReservedWords(tabFields);
// Find the missing fields
RowMetaInterface missing = new RowMeta();
for (int i=0;i<fields.size();i++)
{
ValueMetaInterface v = fields.getValueMeta(i);
// Not found?
if (tabFields.searchValueMeta( v.getName() )==null )
{
missing.addValueMeta(v); // nope --> Missing!
}
}
if (missing.size()!=0)
{
for (int i=0;i<missing.size();i++)
{
ValueMetaInterface v=missing.getValueMeta(i);
retval+=databaseMeta.getAddColumnStatement(tableName, v, tk, use_autoinc, pk, true);
}
}
// Find the surplus fields
RowMetaInterface surplus = new RowMeta();
for (int i=0;i<tabFields.size();i++)
{
ValueMetaInterface v = tabFields.getValueMeta(i);
// Found in table, not in input ?
if (fields.searchValueMeta( v.getName() )==null )
{
surplus.addValueMeta(v); // yes --> surplus!
}
}
if (surplus.size()!=0)
{
for (int i=0;i<surplus.size();i++)
{
ValueMetaInterface v=surplus.getValueMeta(i);
retval+=databaseMeta.getDropColumnStatement(tableName, v, tk, use_autoinc, pk, true);
}
}
// OK, see if there are fields for wich we need to modify the type... (length, precision)
RowMetaInterface modify = new RowMeta();
for (int i=0;i<fields.size();i++)
{
ValueMetaInterface desiredField = fields.getValueMeta(i);
ValueMetaInterface currentField = tabFields.searchValueMeta( desiredField.getName());
if (currentField!=null)
{
boolean mod = false;
mod |= ( currentField.getLength() < desiredField.getLength() ) && desiredField.getLength()>0;
mod |= ( currentField.getPrecision() < desiredField.getPrecision() ) && desiredField.getPrecision()>0;
// Numeric values...
mod |= ( currentField.getType() != desiredField.getType() ) && ( currentField.isNumber()^desiredField.isNumeric() );
// TODO: this is not an optimal way of finding out changes.
// Perhaps we should just generate the data types strings for existing and new data type and see if anything changed.
if (mod)
{
// System.out.println("Desired field: ["+desiredField.toStringMeta()+"], current field: ["+currentField.toStringMeta()+"]");
modify.addValueMeta(desiredField);
}
}
}
if (modify.size()>0)
{
for (int i=0;i<modify.size();i++)
{
ValueMetaInterface v=modify.getValueMeta(i);
retval+=databaseMeta.getModifyColumnStatement(tableName, v, tk, use_autoinc, pk, true);
}
}
return retval;
}
public void truncateTable(String tablename) throws KettleDatabaseException
{
if (Const.isEmpty(connectionGroup))
{
execStatement(databaseMeta.getTruncateTableStatement(null, tablename));
}
else
{
execStatement("DELETE FROM "+databaseMeta.quoteField(tablename));
}
}
public void truncateTable(String schema, String tablename) throws KettleDatabaseException
{
if (Const.isEmpty(connectionGroup))
{
execStatement(databaseMeta.getTruncateTableStatement(schema, tablename));
}
else
{
execStatement("DELETE FROM "+databaseMeta.getQuotedSchemaTableCombination(schema, tablename));
}
}
/**
* Execute a query and return at most one row from the resultset
* @param sql The SQL for the query
* @return one Row with data or null if nothing was found.
*/
public RowMetaAndData getOneRow(String sql) throws KettleDatabaseException
{
ResultSet rs = openQuery(sql);
if (rs!=null)
{
Object[] row = getRow(rs); // One row only;
try { rs.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close resultset", e); }
if (pstmt!=null)
{
try { pstmt.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close prepared statement pstmt", e); }
pstmt=null;
}
if (sel_stmt!=null)
{
try { sel_stmt.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close prepared statement sel_stmt", e); }
sel_stmt=null;
}
return new RowMetaAndData(rowMeta, row);
}
else
{
throw new KettleDatabaseException("error opening resultset for query: "+sql);
}
}
public RowMeta getMetaFromRow( Object[] row, ResultSetMetaData md ) throws SQLException {
RowMeta meta = new RowMeta();
for( int i=0; i<md.getColumnCount(); i++ ) {
String name = md.getColumnName(i+1);
ValueMetaInterface valueMeta = getValueFromSQLType( name, md, i+1, true, false );
meta.addValueMeta( valueMeta );
}
return meta;
}
public RowMetaAndData getOneRow(String sql, RowMetaInterface param, Object[] data) throws KettleDatabaseException
{
ResultSet rs = openQuery(sql, param, data);
if (rs!=null)
{
Object[] row = getRow(rs); // One value: a number;
rowMeta=null;
RowMeta tmpMeta = null;
try {
ResultSetMetaData md = rs.getMetaData();
tmpMeta = getMetaFromRow( row, md );
} catch (Exception e) {
e.printStackTrace();
} finally {
try { rs.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close resultset", e); }
if (pstmt!=null)
{
try { pstmt.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close prepared statement pstmt", e); }
pstmt=null;
}
if (sel_stmt!=null)
{
try { sel_stmt.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close prepared statement sel_stmt", e); }
sel_stmt=null;
}
}
return new RowMetaAndData(tmpMeta, row);
}
else
{
return null;
}
}
public RowMetaInterface getParameterMetaData(PreparedStatement ps)
{
RowMetaInterface par = new RowMeta();
try
{
ParameterMetaData pmd = ps.getParameterMetaData();
for (int i=1;i<=pmd.getParameterCount();i++)
{
String name = "par"+i;
int sqltype = pmd.getParameterType(i);
int length = pmd.getPrecision(i);
int precision = pmd.getScale(i);
ValueMeta val;
switch(sqltype)
{
case java.sql.Types.CHAR:
case java.sql.Types.VARCHAR:
val=new ValueMeta(name, ValueMetaInterface.TYPE_STRING);
break;
case java.sql.Types.BIGINT:
case java.sql.Types.INTEGER:
case java.sql.Types.NUMERIC:
case java.sql.Types.SMALLINT:
case java.sql.Types.TINYINT:
val=new ValueMeta(name, ValueMetaInterface.TYPE_INTEGER);
break;
case java.sql.Types.DECIMAL:
case java.sql.Types.DOUBLE:
case java.sql.Types.FLOAT:
case java.sql.Types.REAL:
val=new ValueMeta(name, ValueMetaInterface.TYPE_NUMBER);
break;
case java.sql.Types.DATE:
case java.sql.Types.TIME:
case java.sql.Types.TIMESTAMP:
val=new ValueMeta(name, ValueMetaInterface.TYPE_DATE);
break;
case java.sql.Types.BOOLEAN:
case java.sql.Types.BIT:
val=new ValueMeta(name, ValueMetaInterface.TYPE_BOOLEAN);
break;
default:
val=new ValueMeta(name, ValueMetaInterface.TYPE_NONE);
break;
}
if (val.isNumeric() && ( length>18 || precision>18) )
{
val = new ValueMeta(name, ValueMetaInterface.TYPE_BIGNUMBER);
}
par.addValueMeta(val);
}
}
// Oops: probably the database or JDBC doesn't support it.
catch(AbstractMethodError e) { return null; }
catch(SQLException e) { return null; }
catch(Exception e) { return null; }
return par;
}
public int countParameters(String sql)
{
int q=0;
boolean quote_opened=false;
boolean dquote_opened=false;
for (int x=0;x<sql.length();x++)
{
char c = sql.charAt(x);
switch(c)
{
case '\'': quote_opened= !quote_opened; break;
case '"' : dquote_opened=!dquote_opened; break;
case '?' : if (!quote_opened && !dquote_opened) q++; break;
}
}
return q;
}
// Get the fields back from an SQL query
public RowMetaInterface getParameterMetaData(String sql, RowMetaInterface inform, Object[] data)
{
// The database couldn't handle it: try manually!
int q=countParameters(sql);
RowMetaInterface par=new RowMeta();
if (inform!=null && q==inform.size())
{
for (int i=0;i<q;i++)
{
ValueMetaInterface inf=inform.getValueMeta(i);
ValueMetaInterface v = inf.clone();
par.addValueMeta(v);
}
}
else
{
for (int i=0;i<q;i++)
{
ValueMetaInterface v = new ValueMeta("name"+i, ValueMetaInterface.TYPE_NUMBER);
par.addValueMeta(v);
}
}
return par;
}
public static final RowMetaInterface getTransLogrecordFields(boolean update, boolean use_batchid, boolean use_logfield)
{
RowMetaInterface r = new RowMeta();
ValueMetaInterface v;
if (use_batchid && !update)
{
v=new ValueMeta("ID_BATCH", ValueMetaInterface.TYPE_INTEGER, 8, 0); r.addValueMeta(v);
}
if (!update)
{
v=new ValueMeta("TRANSNAME", ValueMetaInterface.TYPE_STRING, 255, 0); r.addValueMeta(v);
}
v=new ValueMeta("STATUS", ValueMetaInterface.TYPE_STRING , 15, 0); r.addValueMeta(v);
v=new ValueMeta("LINES_READ", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("LINES_WRITTEN", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("LINES_UPDATED", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("LINES_INPUT", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("LINES_OUTPUT", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("ERRORS", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("STARTDATE", ValueMetaInterface.TYPE_DATE ); r.addValueMeta(v);
v=new ValueMeta("ENDDATE", ValueMetaInterface.TYPE_DATE ); r.addValueMeta(v);
v=new ValueMeta("LOGDATE", ValueMetaInterface.TYPE_DATE ); r.addValueMeta(v);
v=new ValueMeta("DEPDATE", ValueMetaInterface.TYPE_DATE ); r.addValueMeta(v);
v=new ValueMeta("REPLAYDATE", ValueMetaInterface.TYPE_DATE ); r.addValueMeta(v);
if (use_logfield)
{
v=new ValueMeta("LOG_FIELD", ValueMetaInterface.TYPE_STRING, DatabaseMeta.CLOB_LENGTH, 0);
r.addValueMeta(v);
}
if (use_batchid && update)
{
v=new ValueMeta("ID_BATCH", ValueMetaInterface.TYPE_INTEGER, 8, 0); r.addValueMeta(v);
}
return r;
}
public static final RowMetaInterface getJobLogrecordFields(boolean update, boolean use_jobid, boolean use_logfield)
{
RowMetaInterface r = new RowMeta();
ValueMetaInterface v;
if (use_jobid && !update)
{
v=new ValueMeta("ID_JOB", ValueMetaInterface.TYPE_INTEGER, 8, 0); r.addValueMeta(v);
}
if (!update)
{
v=new ValueMeta("JOBNAME", ValueMetaInterface.TYPE_STRING,255, 0); r.addValueMeta(v);
}
v=new ValueMeta("STATUS", ValueMetaInterface.TYPE_STRING, 15, 0); r.addValueMeta(v);
v=new ValueMeta("LINES_READ", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("LINES_WRITTEN", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("LINES_UPDATED", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("LINES_INPUT", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("LINES_OUTPUT", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("ERRORS", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("STARTDATE", ValueMetaInterface.TYPE_DATE ); r.addValueMeta(v);
v=new ValueMeta("ENDDATE", ValueMetaInterface.TYPE_DATE ); r.addValueMeta(v);
v=new ValueMeta("LOGDATE", ValueMetaInterface.TYPE_DATE ); r.addValueMeta(v);
v=new ValueMeta("DEPDATE", ValueMetaInterface.TYPE_DATE ); r.addValueMeta(v);
v=new ValueMeta("REPLAYDATE", ValueMetaInterface.TYPE_DATE ); r.addValueMeta(v);
if (use_logfield)
{
v=new ValueMeta("LOG_FIELD", ValueMetaInterface.TYPE_STRING, DatabaseMeta.CLOB_LENGTH, 0);
r.addValueMeta(v);
}
if (use_jobid && update)
{
v=new ValueMeta("ID_JOB", ValueMetaInterface.TYPE_INTEGER, 8, 0); r.addValueMeta(v);
}
return r;
}
public void writeLogRecord(String logtable, boolean use_id, long id, boolean job, String name, String status, long read, long written, long updated, long input, long output, long errors, java.util.Date startdate, java.util.Date enddate, java.util.Date logdate, java.util.Date depdate, java.util.Date replayDate, String log_string) throws KettleDatabaseException {
boolean update = use_id && log_string != null && !status.equalsIgnoreCase("start");
RowMetaInterface rowMeta;
if (job) {
rowMeta = getJobLogrecordFields(update, use_id, !Const.isEmpty(log_string));
} else {
rowMeta = getTransLogrecordFields(update, use_id, !Const.isEmpty(log_string));
}
if (update) {
String sql = "UPDATE " + logtable + " SET ";
for (int i = 0; i < rowMeta.size() - 1; i++) // Without ID_JOB or ID_BATCH
{
ValueMetaInterface valueMeta = rowMeta.getValueMeta(i);
if (i > 0) {
sql += ", ";
}
sql += databaseMeta.quoteField(valueMeta.getName()) + "=? ";
}
sql += "WHERE ";
if (job) {
sql += databaseMeta.quoteField("ID_JOB") + "=? ";
} else {
sql += databaseMeta.quoteField("ID_BATCH") + "=? ";
}
Object[] data = new Object[] {
status,
Long.valueOf(read), Long.valueOf(written),
Long.valueOf(input), Long.valueOf(output),
Long.valueOf(updated), Long.valueOf(errors),
startdate, enddate, logdate, depdate, replayDate,
log_string,
Long.valueOf(id),
};
execStatement(sql, rowMeta, data);
} else {
String sql = "INSERT INTO " + logtable + " ( ";
for (int i = 0; i < rowMeta.size(); i++) {
ValueMetaInterface valueMeta = rowMeta.getValueMeta(i);
if (i > 0)
sql += ", ";
sql += databaseMeta.quoteField(valueMeta.getName());
}
sql += ") VALUES(";
for (int i = 0; i < rowMeta.size(); i++) {
if (i > 0)
sql += ", ";
sql += "?";
}
sql += ")";
try {
pstmt = connection.prepareStatement(databaseMeta.stripCR(sql));
List<Object> data = new ArrayList<Object>();
if (job) {
if (use_id) {
data.add(Long.valueOf(id));
}
data.add(name);
} else {
if (use_id) {
data.add(Long.valueOf(id));
}
data.add(name);
}
data.add(status);
data.add(Long.valueOf(read));
data.add(Long.valueOf(written));
data.add(Long.valueOf(updated));
data.add(Long.valueOf(input));
data.add(Long.valueOf(output));
data.add(Long.valueOf(errors));
data.add(startdate);
data.add(enddate);
data.add(logdate);
data.add(depdate);
data.add(replayDate);
if (!Const.isEmpty(log_string)) {
data.add(log_string);
}
setValues(rowMeta, data.toArray(new Object[data.size()]));
pstmt.executeUpdate();
pstmt.close();
pstmt = null;
} catch (SQLException ex) {
throw new KettleDatabaseException("Unable to write log record to log table " + logtable, ex);
}
}
}
public static final RowMetaInterface getStepPerformanceLogrecordFields()
{
RowMetaInterface r = new RowMeta();
ValueMetaInterface v;
v=new ValueMeta("ID_BATCH", ValueMetaInterface.TYPE_INTEGER, 8, 0); r.addValueMeta(v);
v=new ValueMeta("SEQ_NR", ValueMetaInterface.TYPE_INTEGER, 8, 0); r.addValueMeta(v);
v=new ValueMeta("LOGDATE", ValueMetaInterface.TYPE_DATE ); r.addValueMeta(v);
v=new ValueMeta("TRANSNAME", ValueMetaInterface.TYPE_STRING ,255, 0); r.addValueMeta(v);
v=new ValueMeta("STEPNAME", ValueMetaInterface.TYPE_STRING ,255, 0); r.addValueMeta(v);
v=new ValueMeta("STEP_COPY", ValueMetaInterface.TYPE_INTEGER, 3, 0); r.addValueMeta(v);
v=new ValueMeta("LINES_READ", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("LINES_WRITTEN", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("LINES_UPDATED", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("LINES_INPUT", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("LINES_OUTPUT", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("LINES_REJECTED", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("ERRORS", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("INPUT_BUFFER_ROWS", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("OUTPUT_BUFFER_ROWS", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
return r;
}
public Object[] getLastLogDate( String logtable, String name, boolean job, String status ) throws KettleDatabaseException
{
Object[] row = null;
String jobtrans = job?databaseMeta.quoteField("JOBNAME"):databaseMeta.quoteField("TRANSNAME");
String sql = "";
sql+=" SELECT "+databaseMeta.quoteField("ENDDATE")+", "+databaseMeta.quoteField("DEPDATE")+", "+databaseMeta.quoteField("STARTDATE");
sql+=" FROM "+logtable;
sql+=" WHERE "+databaseMeta.quoteField("ERRORS")+" = 0";
sql+=" AND "+databaseMeta.quoteField("STATUS")+" = 'end'";
sql+=" AND "+jobtrans+" = ?";
sql+=" ORDER BY "+databaseMeta.quoteField("LOGDATE")+" DESC, "+databaseMeta.quoteField("ENDDATE")+" DESC";
try
{
pstmt = connection.prepareStatement(databaseMeta.stripCR(sql));
RowMetaInterface r = new RowMeta();
r.addValueMeta( new ValueMeta("TRANSNAME", ValueMetaInterface.TYPE_STRING));
setValues(r, new Object[] { name });
ResultSet res = pstmt.executeQuery();
if (res!=null)
{
rowMeta = getRowInfo(res.getMetaData(), false, false);
row = getRow(res);
res.close();
}
pstmt.close(); pstmt=null;
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to obtain last logdate from table "+logtable, ex);
}
return row;
}
public synchronized Long getNextValue(Hashtable<String,Counter> counters, String tableName, String val_key) throws KettleDatabaseException
{
return getNextValue(counters, null, tableName, val_key);
}
public synchronized Long getNextValue(Hashtable<String,Counter> counters, String schemaName, String tableName, String val_key) throws KettleDatabaseException
{
Long nextValue = null;
String schemaTable = databaseMeta.getQuotedSchemaTableCombination(schemaName, tableName);
String lookup = schemaTable+"."+databaseMeta.quoteField(val_key);
// Try to find the previous sequence value...
Counter counter = null;
if (counters!=null) counter=counters.get(lookup);
if (counter==null)
{
RowMetaAndData rmad = getOneRow("SELECT MAX("+databaseMeta.quoteField(val_key)+") FROM "+schemaTable);
if (rmad!=null)
{
long previous;
try
{
Long tmp = rmad.getRowMeta().getInteger(rmad.getData(), 0);
// A "select max(x)" on a table with no matching rows will return null.
if ( tmp != null )
previous = tmp.longValue();
else
previous = 0L;
}
catch (KettleValueException e)
{
throw new KettleDatabaseException("Error getting the first long value from the max value returned from table : "+schemaTable);
}
counter = new Counter(previous+1, 1);
nextValue = Long.valueOf( counter.next() );
if (counters!=null) counters.put(lookup, counter);
}
else
{
throw new KettleDatabaseException("Couldn't find maximum key value from table "+schemaTable);
}
}
else
{
nextValue = Long.valueOf( counter.next() );
}
return nextValue;
}
public String toString()
{
if (databaseMeta!=null) return databaseMeta.getName();
else return "-";
}
public boolean isSystemTable(String table_name)
{
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_MSSQL)
{
if ( table_name.startsWith("sys")) return true;
if ( table_name.equals("dtproperties")) return true;
}
else
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_GUPTA)
{
if ( table_name.startsWith("SYS")) return true;
}
return false;
}
/** Reads the result of an SQL query into an ArrayList
*
* @param sql The SQL to launch
* @param limit <=0 means unlimited, otherwise this specifies the maximum number of rows read.
* @return An ArrayList of rows.
* @throws KettleDatabaseException if something goes wrong.
*/
public List<Object[]> getRows(String sql, int limit) throws KettleDatabaseException
{
return getRows(sql, limit, null);
}
/** Reads the result of an SQL query into an ArrayList
*
* @param sql The SQL to launch
* @param limit <=0 means unlimited, otherwise this specifies the maximum number of rows read.
* @param monitor The progress monitor to update while getting the rows.
* @return An ArrayList of rows.
* @throws KettleDatabaseException if something goes wrong.
*/
public List<Object[]> getRows(String sql, int limit, ProgressMonitorListener monitor) throws KettleDatabaseException
{
if (monitor!=null) monitor.setTaskName("Opening query...");
ResultSet rset = openQuery(sql);
return getRows(rset, limit, monitor);
}
/** Reads the result of a ResultSet into an ArrayList
*
* @param rset the ResultSet to read out
* @param limit <=0 means unlimited, otherwise this specifies the maximum number of rows read.
* @param monitor The progress monitor to update while getting the rows.
* @return An ArrayList of rows.
* @throws KettleDatabaseException if something goes wrong.
*/
public List<Object[]> getRows(ResultSet rset, int limit, ProgressMonitorListener monitor) throws KettleDatabaseException
{
try
{
List<Object[]> result = new ArrayList<Object[]>();
boolean stop=false;
int i=0;
if (rset!=null)
{
if (monitor!=null && limit>0) monitor.beginTask("Reading rows...", limit);
while ((limit<=0 || i<limit) && !stop)
{
Object[] row = getRow(rset);
if (row!=null)
{
result.add(row);
i++;
}
else
{
stop=true;
}
if (monitor!=null && limit>0) monitor.worked(1);
}
closeQuery(rset);
if (monitor!=null) monitor.done();
}
return result;
}
catch(Exception e)
{
throw new KettleDatabaseException("Unable to get list of rows from ResultSet : ", e);
}
}
public List<Object[]> getFirstRows(String table_name, int limit) throws KettleDatabaseException
{
return getFirstRows(table_name, limit, null);
}
/**
* Get the first rows from a table (for preview)
* @param table_name The table name (or schema/table combination): this needs to be quoted properly
* @param limit limit <=0 means unlimited, otherwise this specifies the maximum number of rows read.
* @param monitor The progress monitor to update while getting the rows.
* @return An ArrayList of rows.
* @throws KettleDatabaseException in case something goes wrong
*/
public List<Object[]> getFirstRows(String table_name, int limit, ProgressMonitorListener monitor) throws KettleDatabaseException
{
String sql = "SELECT";
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_NEOVIEW)
{
sql+=" [FIRST " + limit +"]";
}
sql += " * FROM "+table_name;
if (limit>0)
{
sql+=databaseMeta.getLimitClause(limit);
}
return getRows(sql, limit, monitor);
}
public RowMetaInterface getReturnRowMeta()
{
return rowMeta;
}
public String[] getTableTypes() throws KettleDatabaseException
{
try
{
ArrayList<String> types = new ArrayList<String>();
ResultSet rstt = getDatabaseMetaData().getTableTypes();
while(rstt.next())
{
String ttype = rstt.getString("TABLE_TYPE");
types.add(ttype);
}
return types.toArray(new String[types.size()]);
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to get table types from database!", e);
}
}
public String[] getTablenames() throws KettleDatabaseException
{
return getTablenames(false);
}
public String[] getTablenames(boolean includeSchema) throws KettleDatabaseException
{
String schemaname = null;
if (databaseMeta.useSchemaNameForTableList()) schemaname = databaseMeta.getUsername().toUpperCase();
List<String> names = new ArrayList<String>();
ResultSet alltables=null;
try
{
alltables = getDatabaseMetaData().getTables(null, schemaname, null, databaseMeta.getTableTypes() );
while (alltables.next())
{
String table = alltables.getString("TABLE_NAME");
String schema = alltables.getString("TABLE_SCHEM");
if (Const.isEmpty(schema)) schema = alltables.getString("TABLE_CAT"); // retry for the catalog.
String schemaTable;
if (includeSchema) schemaTable = databaseMeta.getQuotedSchemaTableCombination(schema, table);
else schemaTable = table;
if (log.isRowLevel()) log.logRowlevel(toString(), "got table from meta-data: "+schemaTable);
names.add(schemaTable);
}
}
catch(SQLException e)
{
log.logError(toString(), "Error getting tablenames from schema ["+schemaname+"]");
}
finally
{
try
{
if (alltables!=null) alltables.close();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error closing resultset after getting views from schema ["+schemaname+"]", e);
}
}
log.logDetailed(toString(), "read :"+names.size()+" table names from db meta-data.");
return names.toArray(new String[names.size()]);
}
public String[] getViews() throws KettleDatabaseException
{
return getViews(false);
}
public String[] getViews(boolean includeSchema) throws KettleDatabaseException
{
if (!databaseMeta.supportsViews()) return new String[] {};
String schemaname = null;
if (databaseMeta.useSchemaNameForTableList()) schemaname=databaseMeta.getUsername().toUpperCase();
ArrayList<String> names = new ArrayList<String>();
ResultSet alltables=null;
try
{
alltables = dbmd.getTables(null, schemaname, null, databaseMeta.getViewTypes() );
while (alltables.next())
{
String table = alltables.getString("TABLE_NAME");
String schema = alltables.getString("TABLE_SCHEM");
if (Const.isEmpty(schema)) schema = alltables.getString("TABLE_CAT"); // retry for the catalog.
String schemaTable;
if (includeSchema) schemaTable = databaseMeta.getQuotedSchemaTableCombination(schema, table);
else schemaTable = table;
if (log.isRowLevel()) log.logRowlevel(toString(), "got view from meta-data: "+schemaTable);
names.add(schemaTable);
}
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error getting views from schema ["+schemaname+"]", e);
}
finally
{
try
{
if (alltables!=null) alltables.close();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error closing resultset after getting views from schema ["+schemaname+"]", e);
}
}
log.logDetailed(toString(), "read :"+names.size()+" views from db meta-data.");
return names.toArray(new String[names.size()]);
}
public String[] getSynonyms() throws KettleDatabaseException
{
return getViews(false);
}
public String[] getSynonyms(boolean includeSchema) throws KettleDatabaseException
{
if (!databaseMeta.supportsSynonyms()) return new String[] {};
String schemaname = null;
if (databaseMeta.useSchemaNameForTableList()) schemaname=databaseMeta.getUsername().toUpperCase();
ArrayList<String> names = new ArrayList<String>();
ResultSet alltables=null;
try
{
alltables = dbmd.getTables(null, schemaname, null, databaseMeta.getSynonymTypes() );
while (alltables.next())
{
String table = alltables.getString("TABLE_NAME");
String schema = alltables.getString("TABLE_SCHEM");
if (Const.isEmpty(schema)) schema = alltables.getString("TABLE_CAT"); // retry for the catalog.
String schemaTable;
if (includeSchema) schemaTable = databaseMeta.getQuotedSchemaTableCombination(schema, table);
else schemaTable = table;
if (log.isRowLevel()) log.logRowlevel(toString(), "got view from meta-data: "+schemaTable);
names.add(schemaTable);
}
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error getting synonyms from schema ["+schemaname+"]", e);
}
finally
{
try
{
if (alltables!=null) alltables.close();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error closing resultset after getting synonyms from schema ["+schemaname+"]", e);
}
}
log.logDetailed(toString(), "read :"+names.size()+" views from db meta-data.");
return names.toArray(new String[names.size()]);
}
public String[] getProcedures() throws KettleDatabaseException
{
String sql = databaseMeta.getSQLListOfProcedures();
if (sql!=null)
{
//System.out.println("SQL= "+sql);
List<Object[]> procs = getRows(sql, 1000);
//System.out.println("Found "+procs.size()+" rows");
String[] str = new String[procs.size()];
for (int i=0;i<procs.size();i++)
{
str[i] = ((Object[])procs.get(i))[0].toString();
}
return str;
}
else
{
ResultSet rs = null;
try
{
DatabaseMetaData dbmd = getDatabaseMetaData();
rs = dbmd.getProcedures(null, null, null);
List<Object[]> rows = getRows(rs, 0, null);
String result[] = new String[rows.size()];
for (int i=0;i<rows.size();i++)
{
Object[] row = (Object[])rows.get(i);
String procCatalog = rowMeta.getString(row, "PROCEDURE_CAT", null);
String procSchema = rowMeta.getString(row, "PROCEDURE_SCHEMA", null);
String procName = rowMeta.getString(row, "PROCEDURE_NAME", "");
String name = "";
if (procCatalog!=null) name+=procCatalog+".";
else if (procSchema!=null) name+=procSchema+".";
name+=procName;
result[i] = name;
}
return result;
}
catch(Exception e)
{
throw new KettleDatabaseException("Unable to get list of procedures from database meta-data: ", e);
}
finally
{
if (rs!=null) try { rs.close(); } catch(Exception e) {}
}
}
}
public boolean isAutoCommit()
{
return commitsize<=0;
}
/**
* @return Returns the databaseMeta.
*/
public DatabaseMeta getDatabaseMeta()
{
return databaseMeta;
}
/**
* Lock a tables in the database for write operations
* @param tableNames The tables to lock
* @throws KettleDatabaseException
*/
public void lockTables(String tableNames[]) throws KettleDatabaseException
{
if (Const.isEmpty(tableNames)) return;
// Quote table names too...
String[] quotedTableNames = new String[tableNames.length];
for (int i=0;i<tableNames.length;i++) quotedTableNames[i] = databaseMeta.quoteField(tableNames[i]);
// Get the SQL to lock the (quoted) tables
String sql = databaseMeta.getSQLLockTables(quotedTableNames);
if (sql!=null)
{
execStatements(sql);
}
}
/**
* Unlock certain tables in the database for write operations
* @param tableNames The tables to unlock
* @throws KettleDatabaseException
*/
public void unlockTables(String tableNames[]) throws KettleDatabaseException
{
if (Const.isEmpty(tableNames)) return;
// Quote table names too...
String[] quotedTableNames = new String[tableNames.length];
for (int i=0;i<tableNames.length;i++) quotedTableNames[i] = databaseMeta.quoteField(tableNames[i]);
// Get the SQL to unlock the (quoted) tables
String sql = databaseMeta.getSQLUnlockTables(quotedTableNames);
if (sql!=null)
{
execStatement(sql);
}
}
/**
* @return the opened
*/
public int getOpened()
{
return opened;
}
/**
* @param opened the opened to set
*/
public void setOpened(int opened)
{
this.opened = opened;
}
/**
* @return the connectionGroup
*/
public String getConnectionGroup()
{
return connectionGroup;
}
/**
* @param connectionGroup the connectionGroup to set
*/
public void setConnectionGroup(String connectionGroup)
{
this.connectionGroup = connectionGroup;
}
/**
* @return the partitionId
*/
public String getPartitionId()
{
return partitionId;
}
/**
* @param partitionId the partitionId to set
*/
public void setPartitionId(String partitionId)
{
this.partitionId = partitionId;
}
/**
* @return the copy
*/
public int getCopy()
{
return copy;
}
/**
* @param copy the copy to set
*/
public void setCopy(int copy)
{
this.copy = copy;
}
public void copyVariablesFrom(VariableSpace space)
{
variables.copyVariablesFrom(space);
}
public String environmentSubstitute(String aString)
{
return variables.environmentSubstitute(aString);
}
public String[] environmentSubstitute(String aString[])
{
return variables.environmentSubstitute(aString);
}
public VariableSpace getParentVariableSpace()
{
return variables.getParentVariableSpace();
}
public void setParentVariableSpace(VariableSpace parent)
{
variables.setParentVariableSpace(parent);
}
public String getVariable(String variableName, String defaultValue)
{
return variables.getVariable(variableName, defaultValue);
}
public String getVariable(String variableName)
{
return variables.getVariable(variableName);
}
public boolean getBooleanValueOfVariable(String variableName, boolean defaultValue) {
if (!Const.isEmpty(variableName))
{
String value = environmentSubstitute(variableName);
if (!Const.isEmpty(value))
{
return ValueMeta.convertStringToBoolean(value);
}
}
return defaultValue;
}
public void initializeVariablesFrom(VariableSpace parent)
{
variables.initializeVariablesFrom(parent);
}
public String[] listVariables()
{
return variables.listVariables();
}
public void setVariable(String variableName, String variableValue)
{
variables.setVariable(variableName, variableValue);
}
public void shareVariablesWith(VariableSpace space)
{
variables = space;
// Also share the variables with the meta data object
// Make sure it's not the databaseMeta object itself. We would get an infinite loop in that case.
if (space!=databaseMeta) databaseMeta.shareVariablesWith(space);
}
public void injectVariables(Map<String,String> prop)
{
variables.injectVariables(prop);
}
public RowMetaAndData callProcedure(String arg[], String argdir[], int argtype[],
String resultname, int resulttype) throws KettleDatabaseException {
RowMetaAndData ret;
try {
cstmt.execute();
ret = new RowMetaAndData();
int pos = 1;
if (resultname != null && resultname.length() != 0) {
ValueMeta vMeta = new ValueMeta(resultname, resulttype);
Object v =null;
switch (resulttype) {
case ValueMetaInterface.TYPE_BOOLEAN:
v=Boolean.valueOf(cstmt.getBoolean(pos));
break;
case ValueMetaInterface.TYPE_NUMBER:
v=new Double(cstmt.getDouble(pos));
break;
case ValueMetaInterface.TYPE_BIGNUMBER:
v=cstmt.getBigDecimal(pos);
break;
case ValueMetaInterface.TYPE_INTEGER:
v=Long.valueOf(cstmt.getLong(pos));
break;
case ValueMetaInterface.TYPE_STRING:
v=cstmt.getString(pos);
break;
case ValueMetaInterface.TYPE_DATE:
v=cstmt.getDate(pos);
break;
}
ret.addValue(vMeta, v);
pos++;
}
for (int i = 0; i < arg.length; i++) {
if (argdir[i].equalsIgnoreCase("OUT")
|| argdir[i].equalsIgnoreCase("INOUT")) {
ValueMeta vMeta = new ValueMeta(arg[i], argtype[i]);
Object v=null;
switch (argtype[i]) {
case ValueMetaInterface.TYPE_BOOLEAN:
v=Boolean.valueOf(cstmt.getBoolean(pos + i));
break;
case ValueMetaInterface.TYPE_NUMBER:
v=new Double(cstmt.getDouble(pos + i));
break;
case ValueMetaInterface.TYPE_BIGNUMBER:
v=cstmt.getBigDecimal(pos + i);
break;
case ValueMetaInterface.TYPE_INTEGER:
v=Long.valueOf(cstmt.getLong(pos + i));
break;
case ValueMetaInterface.TYPE_STRING:
v=cstmt.getString(pos + i);
break;
case ValueMetaInterface.TYPE_DATE:
v=cstmt.getTimestamp(pos + i);
break;
}
ret.addValue(vMeta, v);
}
}
return ret;
} catch (SQLException ex) {
throw new KettleDatabaseException("Unable to call procedure", ex);
}
}
/**
* Return SQL CREATION statement for a Table
* @param tableName The table to create
* @throws KettleDatabaseException
*/
public String getDDLCreationTable(String tableName, RowMetaInterface fields) throws KettleDatabaseException
{
String retval;
// First, check for reserved SQL in the input row r...
databaseMeta.quoteReservedWords(fields);
String quotedTk=databaseMeta.quoteField(null);
retval=getCreateTableStatement(tableName, fields, quotedTk, false, null, true);
return retval;
}
/**
* Return SQL TRUNCATE statement for a Table
* @param schema The schema
* @param tableName The table to create
* @throws KettleDatabaseException
*/
public String getDDLTruncateTable(String schema, String tablename) throws KettleDatabaseException
{
if (Const.isEmpty(connectionGroup))
{
return(databaseMeta.getTruncateTableStatement(schema, tablename));
}
else
{
return("DELETE FROM "+databaseMeta.getQuotedSchemaTableCombination(schema, tablename));
}
}
/**
* Return SQL statement (INSERT INTO TableName ...
* @param schemaName tableName The schema
* @param tableName
* @param fields
* @param dateFormat date format of field
* @throws KettleDatabaseException
*/
public String getSQLOutput(String schemaName, String tableName, RowMetaInterface fields, Object[] r,String dateFormat) throws KettleDatabaseException
{
StringBuffer ins=new StringBuffer(128);
try{
String schemaTable = databaseMeta.getQuotedSchemaTableCombination(schemaName, tableName);
ins.append("INSERT INTO ").append(schemaTable).append('(');
// now add the names in the row:
for (int i=0;i<fields.size();i++)
{
if (i>0) ins.append(", ");
String name = fields.getValueMeta(i).getName();
ins.append(databaseMeta.quoteField(name));
}
ins.append(") VALUES (");
// new add values ...
for (int i=0;i<fields.size();i++)
{
if (i>0) ins.append(",");
{
if (fields.getValueMeta(i).getType()==ValueMeta.TYPE_STRING)
ins.append("'" + fields.getString(r,i) + "'") ;
else if (fields.getValueMeta(i).getType()==ValueMeta.TYPE_DATE)
{
if (Const.isEmpty(dateFormat))
ins.append("'" + fields.getString(r,i)+ "'") ;
else
{
try
{
java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat(dateFormat);
ins.append("'" + formatter.format(fields.getDate(r,i))+ "'") ;
}
catch(Exception e)
{
throw new KettleDatabaseException("Error : ", e);
}
}
}
else
{
ins.append( fields.getString(r,i)) ;
}
}
}
ins.append(')');
}catch (Exception e)
{
throw new KettleDatabaseException(e);
}
return ins.toString();
}
public Savepoint setSavepoint() throws KettleDatabaseException {
try {
return connection.setSavepoint();
} catch (SQLException e) {
throw new KettleDatabaseException(Messages.getString("Database.Exception.UnableToSetSavepoint"), e);
}
}
public Savepoint setSavepoint(String savePointName) throws KettleDatabaseException {
try {
return connection.setSavepoint(savePointName);
} catch (SQLException e) {
throw new KettleDatabaseException(Messages.getString("Database.Exception.UnableToSetSavepointName", savePointName), e);
}
}
public void releaseSavepoint(Savepoint savepoint) throws KettleDatabaseException {
try {
connection.releaseSavepoint(savepoint);
} catch (SQLException e) {
throw new KettleDatabaseException(Messages.getString("Database.Exception.UnableToReleaseSavepoint"), e);
}
}
public void rollback(Savepoint savepoint) throws KettleDatabaseException {
try {
connection.rollback(savepoint);
} catch (SQLException e) {
throw new KettleDatabaseException(Messages.getString("Database.Exception.UnableToRollbackToSavepoint"), e);
}
}
}
|
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.geom.AffineTransform;
import java.awt.geom.Point2D;
import java.awt.geom.Point2D.Double;
import java.awt.FlowLayout;
import java.awt.Rectangle;
import java.lang.Math;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JPanel;
import ij.*;
import ij.gui.*;
import ij.plugin.*;
import ij.plugin.frame.*;
import ij.measure.ResultsTable;
import ij.text.*;
import ij.ImagePlus;
import ij.process.ImageProcessor;
import ij.IJ;
import org.apache.commons.math.analysis.*;
import org.apache.commons.math.FunctionEvaluationException;
import org.apache.commons.math.linear.Array2DRowRealMatrix;
import org.apache.commons.math.linear.ArrayRealVector;
import org.apache.commons.math.linear.BlockRealMatrix;
import org.apache.commons.math.linear.SingularValueDecompositionImpl;
import org.apache.commons.math.linear.RealMatrix;
import org.apache.commons.math.linear.QRDecompositionImpl;
import org.apache.commons.math.optimization.direct.NelderMead;
import org.apache.commons.math.optimization.direct.MultiDirectional;
import org.apache.commons.math.optimization.fitting.ParametricRealFunction;
import org.apache.commons.math.optimization.fitting.CurveFitter;
import org.apache.commons.math.optimization.general.LevenbergMarquardtOptimizer;
import org.apache.commons.math.optimization.RealPointValuePair;
import org.apache.commons.math.optimization.GoalType;
import org.apache.commons.math.optimization.SimpleScalarValueChecker;
import org.apache.commons.math.stat.StatUtils;
// For plotting with JChart2
/*
import info.monitorenter.gui.chart.Chart2D;
import info.monitorenter.gui.chart.ZoomableChart;
import info.monitorenter.gui.chart.controls.LayoutFactory;
import info.monitorenter.gui.chart.IAxis.AxisTitle;
import info.monitorenter.gui.chart.ITrace2D;
import info.monitorenter.gui.chart.traces.Trace2DSimple;
import info.monitorenter.gui.chart.views.ChartPanel;
import info.monitorenter.gui.chart.traces.painters.TracePainterDisc;
import info.monitorenter.gui.chart.traces.painters.TracePainterLine;
*/
// For plotting with JFreeChart
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartFrame;
import org.jfree.chart.ChartPanel;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
public class GaussianTrack_ implements PlugIn {
double[] params0_ = {16000.0, 5.0, 5.0, 1.0, 850.0};
double[] steps_ = new double[5];
String [] paramNames_ = {"A", "x_c", "y_c", "sigma", "b"};
GaussianResidual gs_;
NelderMead nm_;
SimpleScalarValueChecker convergedChecker_;;
static final String XCOLNAME = "X";
static final String YCOLNAME = "Y";
private void print(String myText) {
ij.IJ.log(myText);
}
public class GaussianResidual implements MultivariateRealFunction {
short[] data_;
int nx_;
int ny_;
int count_ = 0;
public void setImage(short[] data, int width, int height) {
data_ = data;
nx_ = width;
ny_ = height;
}
public double value(double[] params) {
double residual = 0.0;
for (int i = 0; i < nx_; i++) {
for (int j = 0; j < ny_; j++) {
residual += sqr(gaussian(params, i, j) - data_[(j*nx_) + i]);
}
}
return residual;
}
public double sqr(double val) {
return val*val;
}
public double gaussian(double[] params, int x, int y) {
/* Gaussian function of the form:
* A * exp(-((x-xc)^2+(y-yc)^2)/(2 sigy^2))+b
* A = params[0] (total intensity)
* xc = params[1]
* yc = params[2]
* sig = params[3]
* b = params[4] (background)
*/
if (params.length < 5) {
// Problem, what do we do???
//MMScriptException e;
//e.message = "Params for Gaussian function has too few values"; //throw (e);
}
double exponent = (sqr(x - params[1]) + sqr(y - params[2])) / (2 * sqr(params[3]));
double res = params[0] * Math.exp(-exponent) + params[4];
return res;
}
}
/**
* Rotates a set of XY data points such that the direcion of largest
* variance is a line around the X-axis. Equivalent to total least square
* analysis - which finds the best fit line perpendicular to the data points
*/
public Vector<Point2D.Double> pcaRotate(Vector<Point2D.Double> xyPoints) {
double[][] data = new double[2][xyPoints.size()];
for (int i =0; i< xyPoints.size(); i++) {
data[0][i] = xyPoints.get(i).getX();
data[1][i] = xyPoints.get(i).getY();
}
double meanX = StatUtils.mean(data[0]);
double meanY = StatUtils.mean(data[1]);
for (int i = 0; i< data[0].length; i++) {
data[0][i] = data[0][i] - meanX;
data[1][i] = data[1][i] - meanY;
}
Array2DRowRealMatrix dataM = new Array2DRowRealMatrix(data);
SingularValueDecompositionImpl sVD = new SingularValueDecompositionImpl(dataM);
RealMatrix output = sVD.getUT().multiply(dataM);
Vector<Point2D.Double> result = new Vector<Point2D.Double>();
for (int i = 0; i < output.getColumnDimension(); i++) {
result.add(new Point2D.Double(output.getEntry(0,i), output.getEntry(1,i)));
}
return result;
}
/**
* Linear Regression to find the best line between a set of points
* returns an array where [0] = slope and [1] = offset
* Input: arrays with x and y data points
* Not used anymore
*
public double[] fitLine(Vector<Point2D.Double> xyPoints) {
double[][] xWithOne = new double[xyPoints.size()][2];
double[][] yWithOne = new double[xyPoints.size()][2];
for (int i =0; i< xyPoints.size(); i++) {
xWithOne[i][0] = xyPoints.get(i).getX();
xWithOne[i][1] = 1;
yWithOne[i][0] = xyPoints.get(i).getY();
yWithOne[i][1] = 1;
}
Array2DRowRealMatrix xM = new Array2DRowRealMatrix(xWithOne);
Array2DRowRealMatrix yM = new Array2DRowRealMatrix(yWithOne);
QRDecompositionImpl qX = new QRDecompositionImpl(xM);
BlockRealMatrix mX = (BlockRealMatrix) qX.getSolver().solve(yM);
RealMatrix theY = xM.multiply(mX);
double ansX = theY.subtract(yM).getColumnVector(0).getNorm();
print ("Answer X: " + ansX);
QRDecompositionImpl qY = new QRDecompositionImpl(yM);
BlockRealMatrix mY = (BlockRealMatrix) qY.getSolver().solve(xM);
RealMatrix theX = yM.multiply(mY);
double ansY = theX.subtract(xM).getColumnVector(0).getNorm();
print ("Answer Y: " + ansY);
double[][] res = mX.getData();
double[] ret = new double[2];
ret[0] = res[0][0];
ret[1] = res[1][0];
if (ansY < ansX) {
res = mY.getData();
ret[0] = 1 / res[0][0];
ret[1] = - res[1][0]/res[0][0];
}
return ret;
}
public AffineTransform computeAffineTransform(double a, double b) {
AffineTransform T = new AffineTransform();
T.rotate(-Math.atan(a));
T.translate(0, -b);
return T;
}
*/
/**
* KeyListener and MouseListenerclass for ResultsTable
* When user selected a line in the ResulsTable and presses a key,
* the corresponding image will move to the correct slice and draw the ROI
* that was used to calculate the Gaussian fit
* Works only in conjunction with appropriate column names
* Up and down keys also work as expected
*/
public class MyK implements KeyListener, MouseListener{
ImagePlus siPlus_;
ResultsTable res_;
TextWindow win_;
TextPanel tp_;
int hBS_;
public MyK(ImagePlus siPlus, ResultsTable res, TextWindow win, int halfBoxSize) {
siPlus_ = siPlus;
res_ = res;
win_ = win;
tp_ = win.getTextPanel();
hBS_ = halfBoxSize;
}
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
int row = tp_.getSelectionStart();
if (key == KeyEvent.VK_J) {
if (row > 0) {
row
tp_.setSelection(row, row);
}
} else if (key == KeyEvent.VK_K) {
if (row < tp_.getLineCount() - 1) {
row++;
tp_.setSelection(row, row);
}
}
update();
}
public void keyReleased(KeyEvent e) {}
public void keyTyped(KeyEvent e) {}
public void mouseReleased(MouseEvent e) {
update();
}
public void mousePressed(MouseEvent e) {}
public void mouseClicked(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {};
public void mouseExited(MouseEvent e) {};
private void update() {
int row = tp_.getSelectionStart();
if (row >= 0 && row < tp_.getLineCount()) {
if (siPlus_ != IJ.getImage()) {
siPlus_.getWindow().toFront();
win_.toFront();
}
int frame = (int) res_.getValue("Frame", row);
int x = (int)res_.getValue("XMax", row);
int y = (int) res_.getValue("YMax", row);
siPlus_.setSlice(frame);
siPlus_.setRoi(new Roi(x - hBS_ , y - hBS_, 2 * hBS_, 2 * hBS_));
}
}
}
/**
* Performs Gaussian Fit on a given ImageProcessor
* Estimates initial values for the fit and send of to Apache fitting code
*/
public double[] doGaussianFit (ImageProcessor siProc) {
short[] imagePixels = (short[])siProc.getPixels();
gs_.setImage((short[])siProc.getPixels(), siProc.getWidth(), siProc.getHeight());
// Hard code estimate for sigma:
params0_[3] = 1.115;
// estimate background by averaging pixels at the edge
double bg = 0.0;
int n = 0;
int lastRowOffset = (siProc.getHeight() - 1) * siProc.getWidth();
for (int i =0; i < siProc.getWidth(); i++) {
bg += imagePixels[i];
bg += imagePixels[i + lastRowOffset];
n += 2;
}
for (int i = 1; i < siProc.getHeight() - 1; i++) {
bg += imagePixels[i * siProc.getWidth()];
bg += imagePixels[(i + 1) *siProc.getWidth() - 1];
n += 2;
}
params0_[4] = bg / n;
// estimate signal by subtracting background from total intensity
double ti = 0.0;
double mt = 0.0;
for (int i = 0; i < siProc.getHeight() * siProc.getWidth(); i++) {
mt += imagePixels[i];
}
ti = mt - ( (bg / n) * siProc.getHeight() * siProc.getWidth());
params0_[0] = ti / (2 * Math.PI * params0_[3] * params0_[3]);
// print("Total signal: " + ti + "Estimate: " + params0_[0]);
// estimate center of mass
double mx = 0.0;
double my = 0.0;
for (int i = 0; i < siProc.getHeight() * siProc.getWidth(); i++) {
//mx += (imagePixels[i] - params0_[4]) * (i % siProc.getWidth() );
//my += (imagePixels[i] - params0_[4]) * (Math.floor (i / siProc.getWidth()));
mx += imagePixels[i] * (i % siProc.getWidth() );
my += imagePixels[i] * (Math.floor (i / siProc.getWidth()));
}
params0_[1] = mx/mt;
params0_[2] = my/mt;
print("Centroid: " + mx/mt + " " + my/mt);
// set step size during estimate
for (int i=0;i<params0_.length;++i)
steps_[i] = params0_[i]*0.3;
nm_.setStartConfiguration(steps_);
nm_.setConvergenceChecker(convergedChecker_);
nm_.setMaxIterations(200);
double[] paramsOut = {0.0};
try {
RealPointValuePair result = nm_.optimize(gs_, GoalType.MINIMIZE, params0_);
paramsOut = result.getPoint();
} catch (Exception e) {}
return paramsOut;
}
public void run(String arg) {
// objects used in Gaussian fitting
gs_ = new GaussianResidual();
nm_ = new NelderMead();
convergedChecker_ = new SimpleScalarValueChecker(1e-5,-1);
// Filters for results of Gaussian fit
double intMin = 100;
double intMax = 1E7;
double sigmaMin = 0.8;
double sigmaMax = 2.1;
// half the size of the box used for Gaussian fitting in pixels
int halfSize = 6;
// Needed to calculate # of photons and estimate error
double photonConversionFactor = 10.41;
double gain = 50;
double pixelSize = 107; // nm/pixel
// derived from above values:
double cPCF = photonConversionFactor / gain;
// initial setting for Maximum Finder
int noiseTolerance = 100;
// for now, take the active ImageJ image (this should be an image of a difraction limited spot
ImagePlus siPlus = IJ.getImage();
Roi originalRoi = siPlus.getRoi();
if (null == originalRoi) {
IJ.error("Please draw a Roi around the spot you want to track");
return;
}
int sliceN = siPlus.getSlice();
ResultsTable rt = new ResultsTable();
Rectangle rect = originalRoi.getBounds();
int xc = (int) (rect.getX() + 0.5 * rect.getWidth());
int yc = (int) (rect.getY() + 0.5 * rect.getHeight());
long startTime = System.nanoTime();
Vector<Point2D.Double> xyPoints = new Vector<Point2D.Double>();
for (int i = sliceN; i <= siPlus.getNSlices(); i++) {
// Search in next slice in same Roi for local maximum
Roi spotRoi = new Roi(xc - halfSize, yc - halfSize, 2 * halfSize, 2*halfSize);
siPlus.setSlice(i);
siPlus.setRoi(spotRoi);
// Find maximum in Roi
IJ.run("Find Maxima...", "noise=" + noiseTolerance + " output=List");
ResultsTable rtS = ResultsTable.getResultsTable();
if (rtS.getCounter() >=1) {
xc = (int) rtS.getValueAsDouble(0, 0);
yc = (int) rtS.getValueAsDouble(1, 0);
}
// Set Roi for fitting centered around maximum
spotRoi = new Roi(xc - halfSize, yc - halfSize, 2 * halfSize, 2*halfSize);
siPlus.setRoi(spotRoi);
ImageProcessor ip = siPlus.getProcessor().crop();
double[]paramsOut = doGaussianFit(ip);
if (paramsOut.length >= 4) {
double anormalized = paramsOut[0] * (2 * Math.PI * paramsOut[3] * paramsOut[3]);
double x = (paramsOut[1] - halfSize + xc) * pixelSize;
double y = (paramsOut[2] - halfSize + yc) * pixelSize;
xyPoints.add(new Point2D.Double(x, y));
// TOOD: quality control
boolean report = anormalized > intMin && anormalized < intMax &&
paramsOut[3] > sigmaMin && paramsOut[3] < sigmaMax;
rt.incrementCounter();
rt.addValue("Frame", i);
rt.addValue("Intensity (#p)", anormalized * cPCF);
rt.addValue("Background", paramsOut[4]);
rt.addValue(XCOLNAME, x);
rt.addValue(YCOLNAME, y);
rt.addValue("S (nm)", paramsOut[3] * pixelSize);
rt.addValue("XMax", xc);
rt.addValue("YMax", yc);
// rt.addValue("Residual", gs_.value(paramsOut));
if (report) {
// IJ.log (i + " " + xc + " " + paramsOut[1] + " " + halfSize);
// IJ.log (xc + " ");
}
}
}
long endTime = System.nanoTime();
double took = (endTime - startTime) / 1E6;
print("Calculation took: " + took + " milli seconds");
String rtTitle = "Gaussian Fit Tracking Result for " + siPlus.getWindow().getTitle();
rt.show(rtTitle);
// Attach listener to TextPanel
TextPanel tp;
Frame frame = WindowManager.getFrame(rtTitle);
TextWindow win;
if (frame!=null && frame instanceof TextWindow) {
win = (TextWindow)frame;
tp = win.getTextPanel();
MyK myk = new MyK(siPlus, rt, win, halfSize);
tp.addKeyListener(myk);
tp.addMouseListener(myk);
}
Vector<Point2D.Double> xyCorrPoints = pcaRotate(xyPoints);
/*
double[] line = fitLine(xyPoints);
print(line[0] + " " + line[1]);
AffineTransform T = computeAffineTransform(line[0], line[1]);
Vector<Point2D.Double> xyCorrPoints = new Vector<Point2D.Double>();
*/
XYSeries xData = new XYSeries("On Track");
XYSeries yData = new XYSeries("Off Track");
for (int i = 0; i < xyPoints.size(); i++) {
//Point2D.Double pt = new Point2D.Double();
//xyCorrPoints.add((Point2D.Double)T.transform(xyPoints.get(i), pt));
xData.add(i, xyCorrPoints.get(i).getX());
yData.add(i, xyCorrPoints.get(i).getY());
//print(pt.getX() + "\t" + pt.getY());
}
// JFreeChart code
// Create the graph
XYSeriesCollection dataset = new XYSeriesCollection();
dataset.addSeries(xData);
JFreeChart chart = ChartFactory.createScatterPlot("On axis movement", // Title
"Time (interval)", // x-axis Label
"Distance (pixels)", // y-axis Label
dataset, // Dataset
PlotOrientation.VERTICAL, // Plot Orientation
true, // Show Legend
true, // Use tooltips
false // Configure chart to generate URLs?
);
ChartFrame graphFrame = new ChartFrame("On Axis Movememt", chart);
/*
JFrame graphFrame = new JFrame();
ChartPanel cPanel = new ChartPanel(chart);
graphFrame.getContentPane().add(cPanel);
graphFrame.getContentPane().setLayout(new FlowLayout());
graphFrame.setSize(800, 1000);
*/
graphFrame.pack();
graphFrame.setVisible(true);
/*
* Chart On-Axis Movement with JChart2
*
ZoomableChart chart = new ZoomableChart();
chart.getAxisY().setPaintGrid(true);
chart.getAxisX().setAxisTitle(new AxisTitle("Time - #"));
chart.getAxisY().setAxisTitle(new AxisTitle("Movement (nm)"));
// Create an ITrace:
ITrace2D trace = new Trace2DSimple();
trace.setTracePainter(new TracePainterDisc());
ITrace2D traceLine = new Trace2DSimple();
traceLine.setTracePainter(new TracePainterLine());
chart.addTrace(trace);
chart.addTrace(traceLine);
LayoutFactory factory = LayoutFactory.getInstance();
ChartPanel chartpanel = new ChartPanel(chart);
for (int i = 0; i < xyPoints.size(); i++) {
trace.addPoint(i, xyCorrPoints.get(i).getX());
traceLine.addPoint(i, xyCorrPoints.get(i).getX());
}
// Make it visible:
final JFrame graphFrameX = new JFrame("On Axis Movement");
// add the chart to the frame:
graphFrameX.getContentPane().add(chart);
graphFrameX.setSize(400,300);
graphFrameX.setLocation(30, 30);
graphFrameX.setJMenuBar(factory.createChartMenuBar(chartpanel, false));
graphFrameX.addWindowListener(
new WindowAdapter(){
public void windowClosing(WindowEvent e){
graphFrameX.removeWindowListener(this);
graphFrameX.dispose();
}
}
);
graphFrameX.setVisible(true);
*
* Chart Off-Axis Movement with JChart2
*
ZoomableChart chartY = new ZoomableChart();
chartY.getAxisY().setPaintGrid(true);
chartY.getAxisX().setAxisTitle(new AxisTitle("Time - #"));
chartY.getAxisY().setAxisTitle(new AxisTitle("Movement (nm)"));
// Create an ITrace:
ITrace2D traceY = new Trace2DSimple();
traceY.setTracePainter(new TracePainterDisc());
ITrace2D traceYLine = new Trace2DSimple();
traceYLine.setTracePainter(new TracePainterLine());
chartY.addTrace(traceY);
chartY.addTrace(traceYLine);
ChartPanel chartpanelY = new ChartPanel(chartY);
for (int i = 0; i < xyPoints.size(); i++) {
traceY.addPoint(i, xyCorrPoints.get(i).getY());
traceYLine.addPoint(i, xyCorrPoints.get(i).getY());
}
// Make it visible:
final JFrame graphFrameY = new JFrame("Off Axis Movement");
// add the chart to the frame:
graphFrameY.getContentPane().add(chartY);
graphFrameY.setSize(400,300);
graphFrameY.setLocation(430, 30);
graphFrameY.setJMenuBar(factory.createChartMenuBar(chartpanelY, false));
graphFrameY.addWindowListener(
new WindowAdapter(){
public void windowClosing(WindowEvent e){
graphFrameY.removeWindowListener(this);
graphFrameY.dispose();
}
}
);
graphFrameY.setVisible(true);
*/
}
}
|
package pandemic.game.swing;
import j2a.java.BitmapImage;
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.KeyboardFocusManager;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Observable;
import java.util.Observer;
import javax.swing.JFrame;
import javax.swing.JPanel;
import pandemic.game.board.Board;
import pandemic.game.board.OtherActionsProvider;
import pandemic.game.board.parts.Deck;
import pandemic.game.roles.Roles;
public class Pandemic implements Observer {
private JFrame frame;
private Board board;
/**
* This method throws RuntimeException if no player goes to play.
*
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException {
new Pandemic().start(args);
}
private DrawingPanel drawPane;
private void start(String[] args) throws IOException {
if (args.length == 0) {
throw new RuntimeException("At least one player is expected!");
}
int ns = countNumbers(args);
int bs = countBooleans(args);
boolean randomize=false;
int epidemy=4;
String[] args2 = new String[args.length-ns-bs];
int i2=0;
for (int i = 0; i < args.length; i++) {
String arg = args[i];
if (isBool(arg)){
randomize=Boolean.valueOf(arg);
}else if (isInt(arg)){
epidemy=Integer.valueOf(arg);
}else{
args2[i]=arg;
i2++;
}
}
board = new Board(new Roles(args2), new OtherActionsProvider() {
@Override
public void provide(Roles r, Deck d) {
new OtherActions(r, d);
}
}, randomize, epidemy);
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
board.addObserver(Pandemic.this);
board.notifyObservers();
}
});
}
private void createAndShowGUI() {
KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(Manual.SHOW_MANUAL);
frame = new JFrame("Pandemic");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
drawPane = new DrawingPanel();
frame.add(drawPane);
frame.pack();
frame.setSize(300, 200);
frame.setVisible(true);
frame.setExtendedState(frame.getExtendedState() | JFrame.MAXIMIZED_BOTH);
}
@Override
public void update(Observable o, Object o1) {
if (drawPane != null) {
drawPane.setCurrentImage((BufferedImage) (((BitmapImage)o1).getOrigianl()));
frame.repaint();
}
}
private int countNumbers(String[] args) {
int r = 0;
for (String arg : args) {
if (isInt(arg)){
r++;
}
}
return r;
}
private int countBooleans(String[] args) {
int r = 0;
for (String arg : args) {
if (isBool(arg)){
r++;
}
}
return r;
}
public boolean isBool(String arg) {
return (arg.toLowerCase().equals("true") || arg.toLowerCase().equals("false"));
}
public boolean isInt(String arg) {
try{
Integer.valueOf(arg);
return true;
}catch(Exception ex){
}
return false;
}
private class DrawingPanel extends JPanel {
BufferedImage currentImage;
public DrawingPanel() {
this.addMouseMotionListener(new MouseAdapter() {
@Override
public void mouseMoved(MouseEvent e) {
try {
board.move(
real(e.getX(), DrawingPanel.this.getWidth(), board.getOrigWidth()),
real(e.getY(), DrawingPanel.this.getHeight(), board.getOrigHeight()));
} catch (NullPointerException ex) {
//here is happening NPE in init,and I dont know why
//silencing it to make etacher ahppy
}
}
});
this.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON1) {
board.mainClick(
real(e.getX(), DrawingPanel.this.getWidth(), board.getOrigWidth()),
real(e.getY(), DrawingPanel.this.getHeight(), board.getOrigHeight()));
}
if (e.getButton() == MouseEvent.BUTTON3) {
board.second(
real(e.getX(), DrawingPanel.this.getWidth(), board.getOrigWidth()),
real(e.getY(), DrawingPanel.this.getHeight(), board.getOrigHeight()));
}
}
});
}
//functions for recalculate coordinations
private int real(int coord, int current, int orig) {
return (int) real((double) coord, (double) current, (double) orig);
}
private double real(double coord, double current, double orig) {
return (orig / current) * coord;
}
public void setCurrentImage(BufferedImage currentImage) {
this.currentImage = currentImage;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(currentImage, 0, 0, this.getWidth(), this.getHeight(), null);
}
}
}
|
package bom;
import org.nakedobjects.application.BusinessObjectContainer;
import org.nakedobjects.application.Title;
import org.nakedobjects.application.control.FieldAbout;
import org.nakedobjects.application.value.IntegerNumber;
import org.nakedobjects.application.valueholder.Logical;
import org.nakedobjects.application.valueholder.TextString;
public class Telephone {
private final TextString number;
private final TextString knownAs;
private final Logical temporary;
private final Logical hide;
private transient BusinessObjectContainer container;
private IntegerNumber ringCount;
public Telephone() {
number = new TextString();
knownAs = new TextString();
temporary = new Logical();
hide = new Logical();
}
public void actionConvertToOffice() {
number.setValue(number.stringValue()+ " ext ");
knownAs.setValue("Office");
container.objectChanged(this);
}
public void aboutKnownAs(FieldAbout about, TextString entry) {
about.unmodifiableOnCondition(temporary.isSet(), "Flag set");
if(hide.isSet()) about.invisible();
}
public final TextString getKnownAs() {
return knownAs;
}
public void aboutNumber(FieldAbout about, TextString entry) {
about.unmodifiableOnCondition(temporary.isSet(), "Flag set");
if(hide.isSet()) about.invisible();
}
public final TextString getNumber() {
return number;
}
public final Logical getUnmodifiable() {
return temporary;
}
public final Logical getHideFields() {
return hide;
}
public Title title() {
if (knownAs.isEmpty()) {
return number.title();
} else {
return knownAs.title();
}
}
public IntegerNumber getRingCount() {
return ringCount;
}
public void setRingCount(IntegerNumber ringCount) {
this.ringCount = ringCount;
container.objectChanged(this);
}
public void setContainer(BusinessObjectContainer container) {
this.container = container;
}
}
|
package org.nutz.dao.test.normal;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({ FieldFilterTest.class,
SimpleDaoTest.class,
QueryTest.class,
UpdateTest.class,
BoneCP_Test.class,
SupportedFieldTypeTest.class,
AutoGenerateValueTest.class,
PkTest.class})
public class AllNormal {}
|
package to.etc.util;
import java.io.*;
public class ProcessTools {
private ProcessTools() {
}
/**
* This is used to async read strout and stderr streams from a process...
*/
static public class StreamReaderThread extends Thread {
/** The stream to read, */
private Reader m_reader;
/** The output writer thing. */
private final Writer m_w;
private final char[] m_buf;
public StreamReaderThread(final Appendable sb, String name, InputStream is) {
this(sb, name, is, System.getProperty("file.encoding"));
}
public StreamReaderThread(final Appendable sb, String name, InputStream is, String encoding) {
this(new Writer() {
@Override
public void write(char[] cbuf, int off, int len) throws IOException {
while(len
sb.append(cbuf[off++]);
}
@Override
public void flush() throws IOException {
}
@Override
public void close() throws IOException {
}
}, name, is, encoding);
}
public StreamReaderThread(Writer sb, String name, InputStream is) {
this(sb, name, is, System.getProperty("file.encoding"));
}
public StreamReaderThread(Writer w, String name, InputStream is, String encoding) {
m_w = w;
m_buf = new char[1024];
setName("StreamReader" + name);
try {
m_reader = new InputStreamReader(is, encoding);
} catch(UnsupportedEncodingException x) // Fuck James Gosling with his stupid checked exceptions crap
{
throw new IllegalStateException("Unsupported encoding " + encoding);
}
}
/**
* Read data from the stream until it closes line by line; add each line to
* the output channel.
*/
@Override
public void run() {
try {
int szrd;
while(0 < (szrd = m_reader.read(m_buf))) {
// System.out.println("dbg: writing "+szrd+" chars to the stream");
m_w.write(m_buf, 0, szrd);
}
m_w.flush();
} catch(Throwable x) {
x.printStackTrace();
} finally {
try {
if(m_reader != null)
m_reader.close();
} catch(Exception x) {}
}
// System.out.println("Reader "+m_name+" terminated.");
}
}
/**
* This is used to async read strout and stderr streams from a process into another output stream.
*/
static public class StreamCopyThread extends Thread {
/** The stream to read, */
private InputStream m_is;
private OutputStream m_os;
private final byte[] m_buf;
public StreamCopyThread(final OutputStream os, String name, InputStream is) {
m_os = os;
m_is = is;
m_buf = new byte[1024];
setName("StreamReader" + name);
}
/**
* Read data from the stream until it closes line by line; add each line to
* the output channel.
*/
@Override
public void run() {
try {
int szrd;
while(0 < (szrd = m_is.read(m_buf))) {
m_os.write(m_buf, 0, szrd);
}
m_os.flush();
} catch(Throwable x) {
x.printStackTrace();
} finally {
try {
if(m_is != null)
m_is.close();
} catch(Exception x) {}
}
}
}
/**
* Waits for completion of the command and collect data into the streams.
*/
static public int dumpStreams(Process pr, Appendable iosb) throws Exception {
//-- Create two reader classes,
StreamReaderThread outr = new StreamReaderThread(iosb, "stdout", pr.getInputStream());
StreamReaderThread errr = new StreamReaderThread(iosb, "stderr", pr.getErrorStream());
//-- Start both of 'm
outr.start();
errr.start();
int rc = pr.waitFor();
outr.join();
errr.join();
return rc;
}
/**
* Runs the process whose data is in the ProcessBuilder and captures the result with stdout and stderr merged.
* @param pb
* @param sb
* @return
* @throws Exception
*/
static public int runProcess(ProcessBuilder pb, Appendable sb) throws Exception {
pb.redirectErrorStream(true); // Merge stdout and stderr
Process pr = pb.start();
StreamReaderThread outr = new StreamReaderThread(sb, "stdout", pr.getInputStream());
outr.start();
int rc = pr.waitFor();
outr.join();
return rc;
}
/**
* Runs the process whose data is in the ProcessBuilder and captures the result.
* @param pb
* @param sb
* @return
* @throws Exception
*/
static public int runProcess(ProcessBuilder pb, OutputStream stdout, Appendable stderrsb) throws Exception {
Process pr = pb.start();
StreamReaderThread errr = new StreamReaderThread(stderrsb, "stderr", pr.getErrorStream());
StreamCopyThread outr = new StreamCopyThread(stdout, "stdout", pr.getInputStream());
outr.start();
errr.start();
int rc = pr.waitFor();
outr.join();
errr.join();
return rc;
}
/**
* Runs the process whose data is in the ProcessBuilder and captures the result with stdout and stderr merged.
* @param pb
* @param sb
* @return
* @throws Exception
*/
static public int runProcess(ProcessBuilder pb, Appendable outsb, Appendable errsb) throws Exception {
Process pr = pb.start();
StreamReaderThread outr = new StreamReaderThread(outsb, "stdout", pr.getInputStream());
StreamReaderThread errr = new StreamReaderThread(errsb, "stderr", pr.getErrorStream());
outr.start();
errr.start();
int rc = pr.waitFor();
outr.join();
errr.join();
return rc;
}
/**
* Runs the process whose data is in the ProcessBuilder and captures the
* result with stdout and stderr merged into a writer.
* @param pb
* @param sb
* @return
* @throws Exception
*/
static public int runProcess(ProcessBuilder pb, Writer out) throws Exception {
pb.redirectErrorStream(true); // Merge stdout and stderr
Process pr = pb.start();
StreamReaderThread outr = new StreamReaderThread(out, "stdout", pr.getInputStream());
outr.start();
int rc = pr.waitFor();
outr.join();
return rc;
}
}
|
package nitezh.ministock;
import android.app.Activity;
import android.app.backup.BackupManager;
import android.content.Context;
import android.content.Intent;
import android.os.Environment;
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import nitezh.ministock.domain.AndroidWidgetRepository;
import nitezh.ministock.domain.PortfolioStockRepository;
import nitezh.ministock.domain.Widget;
import nitezh.ministock.domain.WidgetRepository;
public class UserData {
// Object for intrinsic lock
public static final Object sFileBackupLock = new Object();
private boolean OVERWRITE_BACKUP = false;
public static void cleanupPreferenceFiles(Context context) {
ArrayList<String> preferencesPathsInUse = getPreferencesPathsInUse(context);
String sharedPrefsPath = context.getFilesDir().getParentFile().getPath() + "/shared_prefs";
removeFilesExceptWhitelist(sharedPrefsPath, preferencesPathsInUse);
}
private static void removeFilesExceptWhitelist(String sharedPrefsFolder, ArrayList<String> preferencesFilenames) {
File sharedPrefsDir = new File(sharedPrefsFolder);
if (sharedPrefsDir.exists()) {
for (File f : sharedPrefsDir.listFiles()) {
if (!preferencesFilenames.contains(f.getName())) {
f.delete();
}
}
}
}
private static ArrayList<String> getPreferencesPathsInUse(Context context) {
ArrayList<String> filenames = new ArrayList<>();
filenames.add(context.getString(R.string.prefs_name) + ".xml");
for (int id : new AndroidWidgetRepository(context).getIds()) {
filenames.add(context.getString(R.string.prefs_name) + id + ".xml");
}
return filenames;
}
public static void backupWidget(Context context, int appWidgetId, String backupName) {
try {
JSONObject jsonForAllWidgets = getJsonBackupsForAllWidgets(context);
JSONObject jsonForWidget = getJsonForWidget(context, appWidgetId);
jsonForAllWidgets.put(backupName, jsonForWidget);
setJsonForAllWidgets(context, jsonForAllWidgets);
} catch (JSONException ignored) {
}
}
private static void setJsonForAllWidgets(Context context, JSONObject jsonForAllWidgets) {
writeInternalStorage(context, jsonForAllWidgets.toString(), PortfolioStockRepository.WIDGET_JSON);
}
private static JSONObject getJsonForWidget(Context context, int appWidgetId) {
WidgetRepository widgetRepository = new AndroidWidgetRepository(context);
return widgetRepository.getWidget(appWidgetId).getWidgetPreferencesAsJson();
}
private static JSONObject getJsonBackupsForAllWidgets(Context context) throws JSONException {
JSONObject backupContainer = new JSONObject();
String rawJson = readInternalStorage(context, PortfolioStockRepository.WIDGET_JSON);
if (rawJson != null) {
backupContainer = new JSONObject(rawJson);
}
return backupContainer;
}
public static void restoreWidget(Context context, int appWidgetId, String backupName) {
try {
JSONObject jsonBackupsForAllWidgets = getJsonBackupsForAllWidgets(context);
Widget widget = new AndroidWidgetRepository(context).getWidget(appWidgetId);
widget.setWidgetPreferencesFromJson(
jsonBackupsForAllWidgets.getJSONObject(backupName));
InformUserWidgetBackupRestored(context);
ReloadPreferences((Activity) context);
} catch (JSONException ignored) {
}
}
private static void InformUserWidgetBackupRestored(Context context) {
DialogTools.showSimpleDialog(context, "AppWidgetProvider restored",
"The current widget preferences have been restored from your selected backup.");
}
private static void ReloadPreferences(Activity activity) {
Intent intent = activity.getIntent();
activity.finish();
activity.startActivity(intent);
}
public static CharSequence[] getWidgetBackupNames(Context context) {
try {
String rawJson = readInternalStorage(context, PortfolioStockRepository.WIDGET_JSON);
if (rawJson == null) {
return null;
}
JSONObject jsonBackupsForAllWidgets = getJsonBackupsForAllWidgets(context);
Iterator iterator = jsonBackupsForAllWidgets.keys();
ArrayList<String> backupList = new ArrayList<>();
while (iterator.hasNext()) {
backupList.add((String) iterator.next());
}
return backupList.toArray(new String[backupList.size()]);
} catch (JSONException ignored) {
}
return null;
}
public static CharSequence[] readFileNames(Context context, String internalDirectory) {
File root = Environment.getExternalStorageDirectory();
File dir = new File(root.getAbsolutePath() + "/ministocks/" + internalDirectory);
if (!dir.exists())
dir.mkdirs();
File[] files = dir.listFiles();
ArrayList<String> fileNames = new ArrayList<>();
for(int i = 0; i < files.length; i++) {
if(files[i].isFile())
fileNames.add(files[i].getName());
}
return fileNames.toArray(new String[fileNames.size()]);
}
public static void writeInternalStorage(Context context, String stringData, String filename) {
try {
synchronized (UserData.sFileBackupLock) {
FileOutputStream fos;
fos = context.openFileOutput(filename, Context.MODE_PRIVATE);
fos.write(stringData.getBytes());
fos.close();
}
new BackupManager(context).dataChanged();
} catch (IOException ignored) {
}
}
public static String readInternalStorage(Context context, String filename) {
try {
StringBuffer fileContent = new StringBuffer();
synchronized (UserData.sFileBackupLock) {
FileInputStream fis;
fis = context.openFileInput(filename);
byte[] buffer = new byte[1024];
while (fis.read(buffer) != -1) {
fileContent.append(new String(buffer));
}
}
return new String(fileContent);
} catch (IOException ignored) {
}
return null;
}
public static String readExternalStorage(Context context, String fileName, String internalDirectory) {
File root = Environment.getExternalStorageDirectory();
File dir = new File(root.getAbsolutePath() + "/ministocks/" + internalDirectory);
if (!dir.exists())
dir.mkdirs();
File file = new File(dir, fileName);
try {
StringBuffer fileContent = new StringBuffer();
String tmp;
synchronized (UserData.sFileBackupLock) {
FileInputStream fis = new FileInputStream(file);
InputStreamReader inputStreamReader = new InputStreamReader(fis);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
while ((tmp = bufferedReader.readLine())!= null) {
fileContent.append(tmp + "\n");
}
}
String res = new String(fileContent);
return res;
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
//DialogTools.showSimpleDialog(context, "Restore portfolio failed", "Backup file portfolioJson.txt not found");
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
// Write to external storage
public static boolean writeExternalStorage(Context context, String data, String fileName, String internalDirectory) {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
File root = Environment.getExternalStorageDirectory();
File dir = new File(root.getAbsolutePath() + "/ministocks/" + internalDirectory);
if(!dir.exists()) {
if (dir.mkdirs()) {
Log.d("Fcreate","Folder created" +"\n" + dir);
} else {
Log.d("Ffailed","Creating folder failed\n" + dir);
}
}else {
Log.d("Fexists",dir + " already exists");
}
if (new File(dir, fileName).exists()) {
DialogTools.showSimpleDialog(context, "Warning", "Choose a diffrent name for your backup. This one already exists");
return false;
}
new File(dir, fileName).delete();
File file = new File(dir, fileName);
try {
synchronized (UserData.sFileBackupLock) {
FileOutputStream fos = new FileOutputStream(file);
fos.write(data.getBytes());
fos.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return true;
} else {
DialogTools.showSimpleDialog(context, "External Storage not available",
"Your external Storage is nor available for this application ");
return false;
}
}
}
|
package io.noties.markwon.core;
import android.content.Context;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.text.TextPaint;
import androidx.annotation.ColorInt;
import androidx.annotation.IntRange;
import androidx.annotation.NonNull;
import androidx.annotation.Px;
import androidx.annotation.Size;
import java.util.Arrays;
import java.util.Locale;
import io.noties.markwon.MarkwonPlugin;
import io.noties.markwon.utils.ColorUtils;
import io.noties.markwon.utils.Dip;
/**
* Class to hold <i>theming</i> information for rending of markdown.
* <p>
* Since version 3.0.0 this class should be considered as <em>CoreTheme</em> as its
* information holds data for core features only. But based on this other components can still use it
* to display markdown consistently.
* <p>
* Since version 3.0.0 this class should not be instantiated manually. Instead a {@link MarkwonPlugin}
* should be used: {@link MarkwonPlugin#configureTheme(Builder)}
* <p>
* Since version 3.0.0 properties related to <em>strike-through</em>, <em>tables</em> and <em>HTML</em>
* are moved to specific plugins in independent artifacts
*
* @see CorePlugin
* @see MarkwonPlugin#configureTheme(Builder)
*/
@SuppressWarnings("WeakerAccess")
public class MarkwonTheme {
/**
* Factory method to obtain an instance of {@link MarkwonTheme} with all values as defaults
*
* @param context Context in order to resolve defaults
* @return {@link MarkwonTheme} instance
* @see #builderWithDefaults(Context)
* @since 1.0.0
*/
@NonNull
public static MarkwonTheme create(@NonNull Context context) {
return builderWithDefaults(context).build();
}
/**
* Create an <strong>empty</strong> instance of {@link Builder} with no default values applied
* <p>
* Since version 3.0.0 manual construction of {@link MarkwonTheme} is not required, instead a
* {@link MarkwonPlugin#configureTheme(Builder)} should be used in order
* to change certain theme properties
*
* @since 3.0.0
*/
@SuppressWarnings("unused")
@NonNull
public static Builder emptyBuilder() {
return new Builder();
}
/**
* Factory method to create a {@link Builder} instance and initialize it with values
* from supplied {@link MarkwonTheme}
*
* @param copyFrom {@link MarkwonTheme} to copy values from
* @return {@link Builder} instance
* @see #builderWithDefaults(Context)
* @since 1.0.0
*/
@NonNull
public static Builder builder(@NonNull MarkwonTheme copyFrom) {
return new Builder(copyFrom);
}
/**
* Factory method to obtain a {@link Builder} instance initialized with default values taken
* from current application theme.
*
* @param context Context to obtain default styling values (colors, etc)
* @return {@link Builder} instance
* @since 1.0.0
*/
@NonNull
public static Builder builderWithDefaults(@NonNull Context context) {
final Dip dip = Dip.create(context);
return new Builder()
.codeBlockMargin(dip.toPx(8))
.blockMargin(dip.toPx(24))
.blockQuoteWidth(dip.toPx(4))
.bulletListItemStrokeWidth(dip.toPx(1))
.headingBreakHeight(dip.toPx(1))
.thematicBreakHeight(dip.toPx(4));
}
protected static final int BLOCK_QUOTE_DEF_COLOR_ALPHA = 25;
protected static final int CODE_DEF_BACKGROUND_COLOR_ALPHA = 25;
protected static final float CODE_DEF_TEXT_SIZE_RATIO = .87F;
protected static final int HEADING_DEF_BREAK_COLOR_ALPHA = 75;
// taken from html spec (most browsers render headings like that)
// is not exposed via protected modifier in order to disallow modification
private static final float[] HEADING_SIZES = {
2.F, 1.5F, 1.17F, 1.F, .83F, .67F,
};
protected static final int THEMATIC_BREAK_DEF_ALPHA = 25;
protected final int linkColor;
// specifies whether we underline links, by default is true
// @since 4.4.1
protected final boolean isLinkedUnderlined;
// used in quote, lists
protected final int blockMargin;
// by default it's 1/4th of `blockMargin`
protected final int blockQuoteWidth;
// by default it's text color with `BLOCK_QUOTE_DEF_COLOR_ALPHA` applied alpha
protected final int blockQuoteColor;
// by default uses text color (applied for un-ordered lists & ordered (bullets & numbers)
protected final int listItemColor;
// by default the stroke color of a paint object
protected final int bulletListItemStrokeWidth;
// width of bullet, by default min(blockMargin, height) / 2
protected final int bulletWidth;
// by default - main text color
protected final int codeTextColor;
// by default - codeTextColor
protected final int codeBlockTextColor;
// by default 0.1 alpha of textColor/codeTextColor
protected final int codeBackgroundColor;
// by default codeBackgroundColor
protected final int codeBlockBackgroundColor;
// by default `width` of a space char... it's fun and games, but span doesn't have access to paint in `getLeadingMargin`
// so, we need to set this value explicitly (think of an utility method, that takes TextView/TextPaint and measures space char)
protected final int codeBlockMargin;
// by default Typeface.MONOSPACE
protected final Typeface codeTypeface;
protected final Typeface codeBlockTypeface;
// by default a bit (how much?!) smaller than normal text
// applied ONLY if default typeface was used, otherwise, not applied
protected final int codeTextSize;
protected final int codeBlockTextSize;
// by default paint.getStrokeWidth
protected final int headingBreakHeight;
// by default, text color with `HEADING_DEF_BREAK_COLOR_ALPHA` applied alpha
protected final int headingBreakColor;
// by default, whatever typeface is set on the TextView
// @since 1.1.0
protected final Typeface headingTypeface;
// by default, we use standard multipliers from the HTML spec (see HEADING_SIZES for values).
// this library supports 6 heading sizes, so make sure the array you pass here has 6 elements.
// @since 1.1.0
protected final float[] headingTextSizeMultipliers;
// by default textColor with `THEMATIC_BREAK_DEF_ALPHA` applied alpha
protected final int thematicBreakColor;
// by default paint.strokeWidth
protected final int thematicBreakHeight;
protected MarkwonTheme(@NonNull Builder builder) {
this.linkColor = builder.linkColor;
this.isLinkedUnderlined = builder.isLinkUnderlined;
this.blockMargin = builder.blockMargin;
this.blockQuoteWidth = builder.blockQuoteWidth;
this.blockQuoteColor = builder.blockQuoteColor;
this.listItemColor = builder.listItemColor;
this.bulletListItemStrokeWidth = builder.bulletListItemStrokeWidth;
this.bulletWidth = builder.bulletWidth;
this.codeTextColor = builder.codeTextColor;
this.codeBlockTextColor = builder.codeBlockTextColor;
this.codeBackgroundColor = builder.codeBackgroundColor;
this.codeBlockBackgroundColor = builder.codeBlockBackgroundColor;
this.codeBlockMargin = builder.codeBlockMargin;
this.codeTypeface = builder.codeTypeface;
this.codeBlockTypeface = builder.codeBlockTypeface;
this.codeTextSize = builder.codeTextSize;
this.codeBlockTextSize = builder.codeBlockTextSize;
this.headingBreakHeight = builder.headingBreakHeight;
this.headingBreakColor = builder.headingBreakColor;
this.headingTypeface = builder.headingTypeface;
this.headingTextSizeMultipliers = builder.headingTextSizeMultipliers;
this.thematicBreakColor = builder.thematicBreakColor;
this.thematicBreakHeight = builder.thematicBreakHeight;
}
/**
* @since 1.0.5
*/
public void applyLinkStyle(@NonNull TextPaint paint) {
paint.setUnderlineText(isLinkedUnderlined);
if (linkColor != 0) {
paint.setColor(linkColor);
} else {
// if linkColor is not specified during configuration -> use default one
paint.setColor(paint.linkColor);
}
}
public void applyLinkStyle(@NonNull Paint paint) {
paint.setUnderlineText(isLinkedUnderlined);
if (linkColor != 0) {
// by default we will be using text color
paint.setColor(linkColor);
} else {
// @since 1.0.5, if link color is specified during configuration, _try_ to use the
// default one (if provided paint is an instance of TextPaint)
if (paint instanceof TextPaint) {
paint.setColor(((TextPaint) paint).linkColor);
}
}
}
public void applyBlockQuoteStyle(@NonNull Paint paint) {
final int color;
if (blockQuoteColor == 0) {
color = ColorUtils.applyAlpha(paint.getColor(), BLOCK_QUOTE_DEF_COLOR_ALPHA);
} else {
color = blockQuoteColor;
}
paint.setStyle(Paint.Style.FILL);
paint.setColor(color);
}
public int getBlockMargin() {
return blockMargin;
}
public int getBlockQuoteWidth() {
final int out;
if (blockQuoteWidth == 0) {
out = (int) (blockMargin * .25F + .5F);
} else {
out = blockQuoteWidth;
}
return out;
}
public void applyListItemStyle(@NonNull Paint paint) {
final int color;
if (listItemColor != 0) {
color = listItemColor;
} else {
color = paint.getColor();
}
paint.setColor(color);
if (bulletListItemStrokeWidth != 0) {
paint.setStrokeWidth(bulletListItemStrokeWidth);
}
}
public int getBulletWidth(int height) {
final int min = Math.min(blockMargin, height) / 2;
final int width;
if (bulletWidth == 0
|| bulletWidth > min) {
width = min;
} else {
width = bulletWidth;
}
return width;
}
/**
* @since 3.0.0
*/
public void applyCodeTextStyle(@NonNull Paint paint) {
if (codeTextColor != 0) {
paint.setColor(codeTextColor);
}
if (codeTypeface != null) {
paint.setTypeface(codeTypeface);
if (codeTextSize > 0) {
paint.setTextSize(codeTextSize);
}
} else {
paint.setTypeface(Typeface.MONOSPACE);
if (codeTextSize > 0) {
paint.setTextSize(codeTextSize);
} else {
paint.setTextSize(paint.getTextSize() * CODE_DEF_TEXT_SIZE_RATIO);
}
}
}
/**
* @since 3.0.0
*/
public void applyCodeBlockTextStyle(@NonNull Paint paint) {
// apply text color, first check for block specific value,
// then check for code (inline), else do nothing (keep original color of text)
final int textColor = codeBlockTextColor != 0
? codeBlockTextColor
: codeTextColor;
if (textColor != 0) {
paint.setColor(textColor);
}
final Typeface typeface = codeBlockTypeface != null
? codeBlockTypeface
: codeTypeface;
if (typeface != null) {
paint.setTypeface(typeface);
// please note that we won't be calculating textSize
// (like we do when no Typeface is provided), if it's some specific typeface
// we would confuse users about textSize
final int textSize = codeBlockTextSize > 0
? codeBlockTextSize
: codeTextSize;
if (textSize > 0) {
paint.setTextSize(textSize);
}
} else {
// by default use monospace
paint.setTypeface(Typeface.MONOSPACE);
final int textSize = codeBlockTextSize > 0
? codeBlockTextSize
: codeTextSize;
if (textSize > 0) {
paint.setTextSize(textSize);
} else {
// calculate default value
paint.setTextSize(paint.getTextSize() * CODE_DEF_TEXT_SIZE_RATIO);
}
}
}
public int getCodeBlockMargin() {
return codeBlockMargin;
}
/**
* @since 3.0.0
*/
public int getCodeBackgroundColor(@NonNull Paint paint) {
final int color;
if (codeBackgroundColor != 0) {
color = codeBackgroundColor;
} else {
color = ColorUtils.applyAlpha(paint.getColor(), CODE_DEF_BACKGROUND_COLOR_ALPHA);
}
return color;
}
/**
* @since 3.0.0
*/
public int getCodeBlockBackgroundColor(@NonNull Paint paint) {
final int color = codeBlockBackgroundColor != 0
? codeBlockBackgroundColor
: codeBackgroundColor;
return color != 0
? color
: ColorUtils.applyAlpha(paint.getColor(), CODE_DEF_BACKGROUND_COLOR_ALPHA);
}
public void applyHeadingTextStyle(@NonNull Paint paint, @IntRange(from = 1, to = 6) int level) {
if (headingTypeface == null) {
paint.setFakeBoldText(true);
} else {
paint.setTypeface(headingTypeface);
}
final float[] textSizes = headingTextSizeMultipliers != null
? headingTextSizeMultipliers
: HEADING_SIZES;
if (textSizes != null && textSizes.length >= level) {
paint.setTextSize(paint.getTextSize() * textSizes[level - 1]);
} else {
throw new IllegalStateException(String.format(
Locale.US,
"Supplied heading level: %d is invalid, where configured heading sizes are: `%s`",
level, Arrays.toString(textSizes)));
}
}
public void applyHeadingBreakStyle(@NonNull Paint paint) {
final int color;
if (headingBreakColor != 0) {
color = headingBreakColor;
} else {
color = ColorUtils.applyAlpha(paint.getColor(), HEADING_DEF_BREAK_COLOR_ALPHA);
}
paint.setColor(color);
paint.setStyle(Paint.Style.FILL);
if (headingBreakHeight >= 0) {
//noinspection SuspiciousNameCombination
paint.setStrokeWidth(headingBreakHeight);
}
}
public void applyThematicBreakStyle(@NonNull Paint paint) {
final int color;
if (thematicBreakColor != 0) {
color = thematicBreakColor;
} else {
color = ColorUtils.applyAlpha(paint.getColor(), THEMATIC_BREAK_DEF_ALPHA);
}
paint.setColor(color);
paint.setStyle(Paint.Style.FILL);
if (thematicBreakHeight >= 0) {
//noinspection SuspiciousNameCombination
paint.setStrokeWidth(thematicBreakHeight);
}
}
@SuppressWarnings("unused")
public static class Builder {
private int linkColor;
private boolean isLinkUnderlined = true; // @since 4.4.1
private int blockMargin;
private int blockQuoteWidth;
private int blockQuoteColor;
private int listItemColor;
private int bulletListItemStrokeWidth;
private int bulletWidth;
private int codeTextColor;
private int codeBlockTextColor; // @since 1.0.5
private int codeBackgroundColor;
private int codeBlockBackgroundColor; // @since 1.0.5
private int codeBlockMargin;
private Typeface codeTypeface;
private Typeface codeBlockTypeface; // @since 3.0.0
private int codeTextSize;
private int codeBlockTextSize; // @since 3.0.0
private int headingBreakHeight = -1;
private int headingBreakColor;
private Typeface headingTypeface;
private float[] headingTextSizeMultipliers;
private int thematicBreakColor;
private int thematicBreakHeight = -1;
Builder() {
}
Builder(@NonNull MarkwonTheme theme) {
this.linkColor = theme.linkColor;
this.isLinkUnderlined = theme.isLinkedUnderlined;
this.blockMargin = theme.blockMargin;
this.blockQuoteWidth = theme.blockQuoteWidth;
this.blockQuoteColor = theme.blockQuoteColor;
this.listItemColor = theme.listItemColor;
this.bulletListItemStrokeWidth = theme.bulletListItemStrokeWidth;
this.bulletWidth = theme.bulletWidth;
this.codeTextColor = theme.codeTextColor;
this.codeBlockTextColor = theme.codeBlockTextColor;
this.codeBackgroundColor = theme.codeBackgroundColor;
this.codeBlockBackgroundColor = theme.codeBlockBackgroundColor;
this.codeBlockMargin = theme.codeBlockMargin;
this.codeTypeface = theme.codeTypeface;
this.codeTextSize = theme.codeTextSize;
this.headingBreakHeight = theme.headingBreakHeight;
this.headingBreakColor = theme.headingBreakColor;
this.headingTypeface = theme.headingTypeface;
this.headingTextSizeMultipliers = theme.headingTextSizeMultipliers;
this.thematicBreakColor = theme.thematicBreakColor;
this.thematicBreakHeight = theme.thematicBreakHeight;
}
@NonNull
public Builder linkColor(@ColorInt int linkColor) {
this.linkColor = linkColor;
return this;
}
@NonNull
public Builder isLinkUnderlined(boolean isLinkUnderlined) {
this.isLinkUnderlined = isLinkUnderlined;
return this;
}
@NonNull
public Builder blockMargin(@Px int blockMargin) {
this.blockMargin = blockMargin;
return this;
}
@NonNull
public Builder blockQuoteWidth(@Px int blockQuoteWidth) {
this.blockQuoteWidth = blockQuoteWidth;
return this;
}
@SuppressWarnings("SameParameterValue")
@NonNull
public Builder blockQuoteColor(@ColorInt int blockQuoteColor) {
this.blockQuoteColor = blockQuoteColor;
return this;
}
@NonNull
public Builder listItemColor(@ColorInt int listItemColor) {
this.listItemColor = listItemColor;
return this;
}
@NonNull
public Builder bulletListItemStrokeWidth(@Px int bulletListItemStrokeWidth) {
this.bulletListItemStrokeWidth = bulletListItemStrokeWidth;
return this;
}
@NonNull
public Builder bulletWidth(@Px int bulletWidth) {
this.bulletWidth = bulletWidth;
return this;
}
@NonNull
public Builder codeTextColor(@ColorInt int codeTextColor) {
this.codeTextColor = codeTextColor;
return this;
}
/**
* @since 1.0.5
*/
@NonNull
public Builder codeBlockTextColor(@ColorInt int codeBlockTextColor) {
this.codeBlockTextColor = codeBlockTextColor;
return this;
}
@SuppressWarnings({"SameParameterValue", "UnusedReturnValue"})
@NonNull
public Builder codeBackgroundColor(@ColorInt int codeBackgroundColor) {
this.codeBackgroundColor = codeBackgroundColor;
return this;
}
/**
* @since 1.0.5
*/
@NonNull
public Builder codeBlockBackgroundColor(@ColorInt int codeBlockBackgroundColor) {
this.codeBlockBackgroundColor = codeBlockBackgroundColor;
return this;
}
@NonNull
public Builder codeBlockMargin(@Px int codeBlockMargin) {
this.codeBlockMargin = codeBlockMargin;
return this;
}
@NonNull
public Builder codeTypeface(@NonNull Typeface codeTypeface) {
this.codeTypeface = codeTypeface;
return this;
}
/**
* @since 3.0.0
*/
@NonNull
public Builder codeBlockTypeface(@NonNull Typeface typeface) {
this.codeBlockTypeface = typeface;
return this;
}
@NonNull
public Builder codeTextSize(@Px int codeTextSize) {
this.codeTextSize = codeTextSize;
return this;
}
/**
* @since 3.0.0
*/
@NonNull
public Builder codeBlockTextSize(@Px int codeTextSize) {
this.codeBlockTextSize = codeTextSize;
return this;
}
@NonNull
public Builder headingBreakHeight(@Px int headingBreakHeight) {
this.headingBreakHeight = headingBreakHeight;
return this;
}
@NonNull
public Builder headingBreakColor(@ColorInt int headingBreakColor) {
this.headingBreakColor = headingBreakColor;
return this;
}
/**
* @param headingTypeface Typeface to use for heading elements
* @return self
* @since 1.1.0
*/
@NonNull
public Builder headingTypeface(@NonNull Typeface headingTypeface) {
this.headingTypeface = headingTypeface;
return this;
}
/**
* @param headingTextSizeMultipliers an array of multipliers values for heading elements.
* The base value for this multipliers is TextView\'s text size
* @return self
* @since 1.1.0
*/
@SuppressWarnings("UnusedReturnValue")
@NonNull
public Builder headingTextSizeMultipliers(@Size(6) @NonNull float[] headingTextSizeMultipliers) {
this.headingTextSizeMultipliers = headingTextSizeMultipliers;
return this;
}
@NonNull
public Builder thematicBreakColor(@ColorInt int thematicBreakColor) {
this.thematicBreakColor = thematicBreakColor;
return this;
}
@NonNull
public Builder thematicBreakHeight(@Px int thematicBreakHeight) {
this.thematicBreakHeight = thematicBreakHeight;
return this;
}
@NonNull
public MarkwonTheme build() {
return new MarkwonTheme(this);
}
}
}
|
package opendap.ppt;
import opendap.xml.Util;
import org.apache.commons.cli.*;
import org.jdom.Document;
import org.jdom.JDOMException;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
/**
* OpenDAPClient is an object that handles the connection to, sending requests
* to, and receiving response from a specified OpenDAP server running either
* on this machine or another machine.
* <p/>
* Requests to the OpenDAP server can be taken in different ways by the
* OpenDAPClient object.
* <UL>
* <LI>One request, ending with a semicolon.</LI>
* <LI>Multiple requests, each ending with a semicolon.</LI>
* <LI>Requests listed in a file, each request can span multiple lines in
* the file and there can be more than one request per line. Each request
* ends with a semicolon.</LI>
* <LI>Interactive mode where the user inputs requests on the command line,
* each ending with a semicolon, with multiple requests allowed per
* line.</LI>
* </UL>
* <p/>
* Response from the requests can sent to any File or OutputStream as
* specified by using the setOutput methods. If no output is specified using
* the setOutput methods thent he output is ignored.
* <p/>
* Thread safety of this object has not yet been determined.
*
* @author Patrick West <A * HREF="mailto:pwest@hao.ucar.edu">pwest@hao.ucar.edu</A>
*/
public class OPeNDAPClient {
private int commandCount;
private NewPPTClient _client = null;
private OutputStream _stream = null;
private boolean _isRunning;
private Logger log = null;
private String _id;
/**
* Creates a OpenDAPClient to handle OpenDAP requests.
* <p/>
* Sets the output of any responses from the OpenDAP server to null,
* meaning that all responses will be thrown out.
*/
public OPeNDAPClient() {
_stream = null;
_isRunning = false;
log = org.slf4j.LoggerFactory.getLogger(getClass());
commandCount = 0;
}
public String getID() {
return _id;
}
public void setID(String ID) {
_id = ID;
}
public int getCommandCount() {
return commandCount;
}
public boolean isRunning() {
return _isRunning;
}
public boolean isClosed() {
return _client.isClosed();
}
public boolean isConnected() {
return _client.isConnected();
}
public String showConnectionProperties() {
return _client.showConnectionProperties();
}
/**
* Connect the OpenDAP client to the OpenDAP server.
* <p/>
* Connects to the OpenDAP server on the specified machine listening on
* the specified port.
*
* @param hostStr The name of the host machine where the server is
* running.
* @param portVal The port on which the server on the host hostStr is
* listening for requests.
* @throws PPTException Thrown if unable to connect to the specified host
* machine given the specified port.
* @see String
* @see PPTException
*/
public void startClient(String hostStr, int portVal) throws PPTException {
_client = new NewPPTClient(hostStr, portVal);
_client.initConnection();
_isRunning = true;
}
/**
* Closes the connection to the OpeNDAP server and closes the output stream.
*
* @throws PPTException Thrown if unable to close the connection or close
* the output stream.
* machine given the specified port.
* @see OutputStream
* @see PPTException
*/
public void shutdownClient() throws PPTException {
if(_client!=null)
_client.closeConnection(true);
if (_stream != null) {
try {
_stream.close();
}
catch (IOException e) {
throw (new PPTException(e.getMessage()));
}
finally {
_isRunning = false;
}
}
_isRunning = false;
}
public int getChunkedReadBufferSize(){
return _client.getChunkReadBufferSize();
}
public void killClient() {
_client.dieNow();
}
/**
* Sends a single OpeNDAP request ending in a semicolon (;) to the
* OpeNDAP server.
* <p/>
* The response is written to the output stream if one is specified,
* otherwise the output is ignored.
*
* @param cmd The OpenDAP request, ending in a semicolon, that is sent to
* the OpenDAP server to handle.
*
* @param target The target OutputStream for the results of the command.
* @param error The error OutputStream for errors returned by the server.
*
* @return True if successful, false if the server returned an error.
* @throws PPTException Thrown if there is a problem sending the request
* to the server or a problem receiving the response
* from the server.
* @see String
* @see PPTException
*/
public boolean executeCommand(String cmd,
OutputStream target,
OutputStream error)
throws PPTException {
log.debug(cmd);
_client.sendRequest(cmd);
boolean success = _client.getResponse(target,error);
commandCount++;
return success;
}
/**
* Sends a single XML request document.
* <p/>
* The response is written to the output stream if one is specified,
* otherwise the output is ignored.
*
* @param request The XML request that is sent to
* the BES to handle.
*
*
* @return True if successful, false if the server returned an error.
* @throws PPTException Thrown if there is a problem sending the request
* to the server or a problem receiving the response
* from the server.
* @throws JDOMException if the response fails to parse.
* @see String
* @see PPTException
*/
/*
public Document sendRequest( Document request)
throws PPTException, JDOMException {
_client.sendXMLRequest(request);
Document doc = _client.getXMLResponse();
commandCount++;
return doc;
}
*/
/**
* Sends a single XML request document.
* <p/>
* The response is written to the output stream if one is specified,
* otherwise the output is ignored.
*
* @param request The XML request that is sent to
* the BES to handle.
*
* @param target The target OutputStream for the results of the command.
* @param error The error OutputStream for errors returned by the server.
*
* @return True if successful, false if the server returned an error.
* @throws PPTException Thrown if there is a problem sending the request
* to the server or a problem receiving the response
* from the server.
* @see String
* @see PPTException
*/
public boolean sendRequest( Document request,
OutputStream target,
OutputStream error)
throws PPTException {
_client.sendXMLRequest(request);
boolean val = _client.getResponse(target,error);
commandCount++;
return val;
}
/**
* Execute each of the commands in the cmd_list, separated by a * semicolon.
* <p/>
* The response is written to the output stream if one is specified,
* otherwise the output is ignored.
*
* @param cmd_list The list of OpenDAP requests, separated by semicolons
* and ending in a semicolon, that will be sent to the
* OpenDAP server to handle, one at a time.
* @param target The target OutputStream for the results of the command.
* @param error The error OutputStream for errors returned by the server.
*
* @return True if successful, false if the server returned an error.
* @throws PPTException Thrown if there is a problem sending any of the
* request to the server or a problem receiving any
* of the response
* s from the server.
* @see String
* @see PPTException
*/
public boolean executeCommands(String cmd_list,
OutputStream target,
OutputStream error)
throws PPTException {
boolean success = true;
String cmds[] = cmd_list.split(";");
for (String cmd : cmds) {
success = executeCommand(cmd + ";", target, error);
if(!success)
return success;
}
return success;
}
/**
* Sends the requests listed in the specified file to the OpenDAP server,
* each command ending with a semicolon.
* <p/>
* The requests do not have to be one per line but can span multiple
* lines and there can be more than one command per line.
* <p/>
* The response is written to the output stream if one is specified,
* otherwise the output is ignored.
*
* @param inputFile The file holding the list of OpenDAP requests, each
* ending with a semicolon, that will be sent to the
* OpenDAP server to handle.
* @param target The target OutputStream for the results of the command.
* @param error The error OutputStream for errors returned by the server.
*
* @return True if successful, false if the server returned an error.
* @throws PPTException Thrown if there is a problem opening the file to
* read, reading the requests from the file, sending
* any of the requests to the server or a problem
* receiving any of the responses from the server.
* @see File
* @see PPTException
*/
public boolean executeCommands(File inputFile,
OutputStream target,
OutputStream error) throws PPTException {
BufferedReader reader;
boolean success = true;
try {
reader = new BufferedReader(new FileReader(inputFile));
}
catch (FileNotFoundException e) {
throw (new PPTException(e.getMessage()));
}
try {
String cmd = null;
boolean done = false;
while (!done && success) {
String nextLine = reader.readLine();
if (nextLine == null) {
if (cmd != null) {
success = this.executeCommands(cmd,target,error);
}
done = true;
} else {
if (!nextLine.equals("")) {
int i = nextLine.lastIndexOf(';');
if (i == -1) {
if (cmd == null) {
cmd = nextLine;
} else {
cmd += " " + nextLine;
}
} else {
String sub = nextLine.substring(0, i);
if (cmd == null) {
cmd = sub;
} else {
cmd += " " + sub;
}
success = this.executeCommands(cmd,target,error);
if (i == nextLine.length() || i == nextLine.length() - 1) {
cmd = null;
} else {
cmd = nextLine.substring(i + 1, nextLine.length());
}
}
}
}
}
}
catch (IOException e) {
throw (new PPTException(e.getMessage()));
}
finally {
try {
reader.close();
} catch (IOException e) {
//Ignore the failure.
}
}
return success;
}
/**
* An interactive OpenDAP client that takes OpenDAP requests on the command
* line.
* <p/>
* There can be more than one command per line, but commands can NOT span
* multiple lines. The user will be prompted to enter a new OpenDAP request.
* <p/>
* OpenDAPClient:
* <p/>
* The response is written to the output stream if one is specified,
* otherwise the output is ignored.
*
* @param out The target OutputStream for the results of the command.
* @param err The error OutputStream for errors returned by the server.
*
* @throws PPTException Thrown if there is a problem sending any of the
* requests to the server or a problem receiving any
* of the responses from the server.
* @see PPTException
*/
public void interact(OutputStream out, OutputStream err) throws PPTException {
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
try {
boolean done = false;
while (!done) {
System.out.print("OPeNDAP> ");
String fromUser = stdIn.readLine();
if (fromUser != null) {
if (fromUser.compareTo("exit") == 0) {
done = true;
} else if (fromUser.compareTo("") == 0) {
//continue;
} else {
this.executeCommands(fromUser,out, err);
}
}
}
}
catch (Exception e) {
_client.closeConnection(true);
throw (new PPTException(e.getMessage(), e));
}
}
private static Options createCmdLineOptions(){
Options options = new Options();
options.addOption("r", "reps", true, "Number of times to send the command. default: 1");
options.addOption("c", "maxCmds", true, "Number of commands to send before closing the BES connection and opening a new one. default: 1");
options.addOption("i", "besCmd", true, "Name of file containing the BES command to use. default: \"bes.cmd\"");
options.addOption("p", "port", true, "Port number of BES. default: 10022");
options.addOption("n", "host", true, "Hostname of BES. default \"localhost\"");
options.addOption("o", "outFile", true, "File into which to log BES responses. default: stdout");
options.addOption("e", "errFile", true, "File into which to log BES errors. default: stderr");
options.addOption("h", "help", false, "Print this usage statement.");
return options;
}
private static void printUsage(PrintStream ps, Options options){
HelpFormatter formatter = new HelpFormatter();
formatter.setWidth(120);
formatter.printHelp( "OPeNDAPClient", options );
/*
ps.println("Usage: ");
ps.println("");
ps.println(" OPeNDAPClient [-i commandFileName] [-r #TimesToSendCommand] [-c numberOfCommandsPerConnection] ");
ps.println("");
ps.println("Summary:");
ps.println("");
ps.println("");
ps.println("Options:");
ps.println("");
ps.println(" --besCmd Filename for the BES command. default: \"bes.cmd\"");
ps.println(" --reps Number of times to send command. default: 1");
ps.println(" --maxCmds Number of commands to send before closing connection and making " +
"and opening a new one. default: 1");
ps.println(" --outFile File into which to log BES responses. default: stdout");
ps.println(" --errFile File into which to log BES errors. default: stderr");
ps.println(" --host BES hostname. default: \"localhost\"");
ps.println(" --port BES port number: default: 10022");
ps.println(" --help Prints this usage information.");
ps.println("");
*/
}
/**
*
* @param args Command line arguments as defined by createCmdLineOptions()
*/
public static void main(String[] args) {
Logger log = LoggerFactory.getLogger("OPeNDAPClient-MAIN");
String besCmdFileName = "bes.cmd";
String cmdString;
int reps = 1;
int maxCmds = 1;
OutputStream besOut = System.out;
OutputStream besErr = System.err;
String hostName = "localhost";
int portNum = 10022;
try {
Options options = createCmdLineOptions();
CommandLineParser parser = new PosixParser();
CommandLine cmd = parser.parse(options, args);
// Command File
if (cmd.hasOption("h")) {
printUsage(System.out,options);
return;
}
// Command File
if (cmd.hasOption("i")) {
besCmdFileName = cmd.getOptionValue("i");
}
log.info("BES Command Filename: "+besCmdFileName);
Document cmdDoc = Util.getDocument(besCmdFileName);
cmdString = new XMLOutputter(Format.getPrettyFormat()).outputString(cmdDoc);
log.info("BES command has been read and parsed.");
// Command reps
if (cmd.hasOption("r")) {
reps = Integer.parseInt(cmd.getOptionValue("r"));
}
log.info("BES command will sent "+reps+" time" + (reps>1?"s.":"."));
// Max commands per client
if (cmd.hasOption("c")) {
maxCmds = Integer.parseInt(cmd.getOptionValue("c"));
}
log.info("The connection to the BES will be dropped and a new one opened after every "
+ maxCmds+" command" + (maxCmds>1?"s.":"."));
// BES output file
if (cmd.hasOption("o")) {
File besOutFile = new File(cmd.getOptionValue("o"));
besOut = new FileOutputStream(besOutFile);
log.info("BES output will be written to "+besOutFile.getAbsolutePath());
}
else {
log.info("BES output will be written to stdout");
}
// BES error file
if (cmd.hasOption("e")) {
File besErrFile = new File(cmd.getOptionValue("e"));
besErr = new FileOutputStream(besErrFile);
log.info("BES errors will be written to "+besErrFile.getAbsolutePath());
}
else {
log.info("BES errors will be written to stderr");
}
// Hostname
if (cmd.hasOption("n")) {
hostName = cmd.getOptionValue("n");
}
// Port Number
if (cmd.hasOption("p")) {
portNum = Integer.parseInt(cmd.getOptionValue("p"));
}
log.info("Using BES at "+hostName+":"+portNum);
}
catch(Throwable t){
log.error("OUCH! Caught "+t.getClass().getName()+" Message: "+t.getMessage());
log.error("STACK TRACE: \n"+org.apache.commons.lang.exception.ExceptionUtils.getStackTrace(t));
return;
}
int cmdsSent = 0;
int connectionsMade = 0;
try {
log.info("
log.info("
log.info("Starting... \n\n\n");
OPeNDAPClient oc = new OPeNDAPClient();
oc.startClient(hostName,portNum);
connectionsMade++;
for(int r=0; r<reps ;r++){
if(r>0 && r%maxCmds==0){
oc.shutdownClient();
oc = new OPeNDAPClient();
oc.startClient(hostName,portNum);
connectionsMade++;
}
oc.executeCommand(cmdString,besOut,besErr);
cmdsSent++;
}
}
catch(Throwable t){
log.error("OUCH! Caught "+t.getClass().getName()+" Message: "+t.getMessage());
log.error("STACK TRACE: \n"+org.apache.commons.lang.exception.ExceptionUtils.getStackTrace(t));
}
finally {
log.info("BES Command Filename: "+besCmdFileName);
log.info("BES command will sent "+reps+" time" + (reps>1?"s.":"."));
log.info("The connection to the BES will be dropped and a new one opened after every "
+ maxCmds+" command" + (maxCmds>1?"s.":"."));
log.info("Using BES at "+hostName+":"+portNum);
log.info("Sent a total of "+cmdsSent+" commands.");
log.info("Made a total of " + connectionsMade + " connection"+(reps>1?"s":"")+" to the BES.");
}
}
}
|
package org.eatabrick.vecna;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.ClipboardManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.inputmethod.InputMethodManager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.Security;
import java.util.Iterator;
import org.spongycastle.jce.provider.BouncyCastleProvider;
import org.spongycastle.openpgp.PGPCompressedData;
import org.spongycastle.openpgp.PGPEncryptedDataList;
import org.spongycastle.openpgp.PGPException;
import org.spongycastle.openpgp.PGPLiteralData;
import org.spongycastle.openpgp.PGPObjectFactory;
import org.spongycastle.openpgp.PGPOnePassSignatureList;
import org.spongycastle.openpgp.PGPPrivateKey;
import org.spongycastle.openpgp.PGPPublicKeyEncryptedData;
import org.spongycastle.openpgp.PGPSecretKey;
import org.spongycastle.openpgp.PGPSecretKeyRingCollection;
import org.spongycastle.openpgp.PGPUtil;
public class Vecna extends ListActivity {
private final static String TAG = "Vecna";
private PasswordEntryAdapter adapter;
private SharedPreferences settings;
private String passphrase = "";
private class ReadEntriesTask extends AsyncTask<String, Integer, Integer> {
ProgressDialog progress;
protected void onPreExecute() {
adapter.clear();
adapter.notifyDataSetChanged();
adapter.setNotifyOnChange(false);
progress = new ProgressDialog(Vecna.this);
progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progress.setMessage(getString(R.string.progress_initial));
progress.setCancelable(false);
progress.setMax(6);
progress.show();
}
protected Integer doInBackground(String... string) {
PGPSecretKeyRingCollection keyring = null;
FileInputStream dataStream = null;
publishProgress(R.string.progress_keyfile);
try {
File keyFile = new File(settings.getString("key_file", ""));
FileInputStream keyStream = new FileInputStream(keyFile);
keyring = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(keyStream));
} catch (Exception e) {
return R.string.error_key_file_not_found;
}
publishProgress(R.string.progress_passfile);
try {
File dataFile = new File(settings.getString("passwords", ""));
dataStream = new FileInputStream(dataFile);
} catch (Exception e) {
return R.string.error_password_file_not_found;
}
try {
PGPObjectFactory factory;
publishProgress(R.string.progress_find_data);
factory = new PGPObjectFactory(PGPUtil.getDecoderStream(dataStream));
PGPEncryptedDataList dataList = null;
Object o;
while ((o = factory.nextObject()) != null) {
if (o instanceof PGPEncryptedDataList) {
dataList = (PGPEncryptedDataList) o;
break;
}
}
if (dataList == null) return R.string.error_no_data_in_file;
publishProgress(R.string.progress_find_key);
PGPSecretKey keySecret = null;
PGPPrivateKey keyPrivate = null;
PGPPublicKeyEncryptedData dataEncrypted = null;
Iterator it = dataList.getEncryptedDataObjects();
while (keyPrivate == null && it.hasNext()) {
dataEncrypted = (PGPPublicKeyEncryptedData) it.next();
keySecret = keyring.getSecretKey(dataEncrypted.getKeyID());
keyPrivate = keySecret.extractPrivateKey(string[0].toCharArray(), "BC");
}
if (keyPrivate == null) return R.string.error_secret_key_missing;
publishProgress(R.string.progress_decrypt);
factory = new PGPObjectFactory(dataEncrypted.getDataStream(keyPrivate, "BC"));
Object message = factory.nextObject();
if (message instanceof PGPCompressedData) {
PGPObjectFactory f = new PGPObjectFactory(((PGPCompressedData) message).getDataStream());
message = f.nextObject();
}
ByteArrayOutputStream dataFinal = new ByteArrayOutputStream();
if (message instanceof PGPLiteralData) {
InputStream s = ((PGPLiteralData) message).getInputStream();
int ch;
while ((ch = s.read()) >= 0) {
dataFinal.write(ch);
}
} else {
return R.string.error_encryption;
}
publishProgress(R.string.progress_parse);
String[] lines = dataFinal.toString().split("\n");
for (int i = 0; i < lines.length; ++i) {
adapter.add(new Entry(lines[i]));
}
} catch (PGPException e) {
e.printStackTrace();
return R.string.error_pgp_key;
} catch (Exception e) {
e.printStackTrace();
return R.string.error_unknown;
}
return 0;
}
protected void onProgressUpdate(Integer... messages) {
progress.setMessage(getString(messages[0]));
progress.incrementProgressBy(1);
}
protected void onPostExecute(Integer result) {
progress.dismiss();
adapter.setNotifyOnChange(true);
adapter.notifyDataSetChanged();
if (result > 0) {
AlertDialog.Builder builder = new AlertDialog.Builder(Vecna.this);
builder.setTitle(getString(R.string.error));
builder.setMessage(getString(result));
builder.setCancelable(false);
builder.setPositiveButton(android.R.string.ok, null);
builder.show();
}
// reset passphrase if they enter it incorrectly
if (result == R.string.error_pgp_key) {
passphrase = "";
setEmptyText(R.string.locked);
} else {
setEmptyText(R.string.empty);
}
findViewById(android.R.id.list).requestFocus();
}
}
@Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
settings = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
adapter = new PasswordEntryAdapter(this);
adapter.setNotifyOnChange(false);
setListAdapter(adapter);
Security.addProvider(new BouncyCastleProvider());
if (savedInstanceState != null) {
passphrase = savedInstanceState.getString("passphrase");
adapter.populate(savedInstanceState.getStringArray("entries"));
adapter.notifyDataSetChanged();
}
getListView().setLongClickable(true);
getListView().setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, View v, int pos, long id) {
onListItemLongClick(parent, v, pos, id);
return true;
}
});
}
@Override public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
@Override public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.search:
// just shows the soft keyboard and lets the list view deal with searching
InputMethodManager imm = (InputMethodManager) getSystemService(this.INPUT_METHOD_SERVICE);
imm.showSoftInput(getListView(), 0);
return true;
case R.id.lock:
// clear the passphrase and passwords from memory
passphrase = "";
setEmptyText(R.string.locked);
adapter.clear();
adapter.notifyDataSetChanged();
return true;
case R.id.refresh:
// reload the password file
updateEntries();
return true;
case R.id.settings:
Intent intent = new Intent(this, Preferences.class);
startActivityForResult(intent, 0);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override protected void onResume() {
super.onResume();
// Automatically show passwords on launch
if (adapter.getCount() == 0) updateEntries();
}
@Override protected void onListItemClick(ListView parent, View v, int pos, long id) {
// copy the password to the clipboard
Entry entry = (Entry) adapter.getItem(pos);
((ClipboardManager) getSystemService(CLIPBOARD_SERVICE)).setText(entry.password);
Toast.makeText(Vecna.this, getString(R.string.copied, entry.account), Toast.LENGTH_SHORT).show();
}
public void emptyClicked(View v) {
// get the passphrase if we don't know it
if (isLocked()) getPassphrase();
}
protected void onListItemLongClick(AdapterView parent, View v, int pos, long id) {
// show a crazy dialog for the entry
final Entry entry = (Entry) adapter.getItem(pos);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
final View layout = inflater.inflate(R.layout.entry, (ViewGroup) findViewById(R.id.layout_root));
((TextView) layout.findViewById(R.id.account )).setText(entry.account);
((TextView) layout.findViewById(R.id.user )).setText(entry.user);
((TextView) layout.findViewById(R.id.password)).setText(entry.password);
builder.setView(layout);
builder.setPositiveButton(R.string.show_entry_copy, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
((ClipboardManager) getSystemService(CLIPBOARD_SERVICE)).setText(entry.password);
Toast.makeText(Vecna.this, getString(R.string.copied, entry.account), Toast.LENGTH_SHORT).show();
}
});
builder.setNegativeButton(R.string.show_entry_close, null);
builder.setNeutralButton(R.string.show_entry_show, null);
final AlertDialog dialog = builder.create();
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
@Override public void onShow(DialogInterface dialogInterface) {
final Button show = dialog.getButton(AlertDialog.BUTTON_NEUTRAL);
show.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View view) {
EditText password = (EditText) layout.findViewById(R.id.password);
if (show.getText().equals(getString(R.string.show_entry_show))) {
Log.d(TAG, "Show clicked");
password.setTransformationMethod(null);
show.setText(R.string.show_entry_hide);
} else {
Log.d(TAG, "Hide clicked");
password.setTransformationMethod(new PasswordTransformationMethod());
show.setText(R.string.show_entry_show);
}
}
});
}
});
dialog.show();
}
@Override public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putString("passphrase", passphrase);
savedInstanceState.putStringArray("entries", adapter.toStringArray());
}
private void getPassphrase() {
final EditText pass = new EditText(this);
pass.setSingleLine();
pass.setTransformationMethod(new PasswordTransformationMethod());
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(getString(R.string.prompt));
builder.setView(pass);
builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
passphrase = pass.getText().toString();
if (!passphrase.isEmpty()) new ReadEntriesTask().execute(passphrase);
}
});
builder.show();
}
private void updateEntries() {
TextView empty = (TextView) findViewById(android.R.id.empty);
if (settings.getString("passwords", "").isEmpty() || settings.getString("key_file", "").isEmpty()) {
setEmptyText(R.string.settings);
} else {
setEmptyText(R.string.locked);
if (passphrase.isEmpty()) {
getPassphrase();
} else {
new ReadEntriesTask().execute(passphrase);
}
}
}
private void setEmptyText(int stringResource) {
((TextView) findViewById(android.R.id.empty)).setText(stringResource);
}
private boolean isLocked() {
return passphrase.isEmpty();
}
}
|
package org.mediterraneancoin.proxy;
import java.io.IOException;
import java.math.BigInteger;
import java.security.GeneralSecurityException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.node.ObjectNode;
import org.mediterraneancoin.miner.SuperHasher;
import static org.mediterraneancoin.proxy.net.RPCUtils.tohex;
import org.mediterraneancoin.proxy.net.WorkState;
/**
*
* @author dev2
*/
public class McproxyStratumServlet extends HttpServlet {
public static boolean DEBUG = true;
private static final String prefix = "SERVLET ";
static int localport;
static String hostname;
static int port;
final ObjectMapper mapper = new ObjectMapper();
static HashMap<String, McproxyHandler.SessionStorage> works = new HashMap<String, McproxyHandler.SessionStorage>();
private final static StratumConnection stratumConnection = StratumConnection.getInstance();
SuperHasher hasher;
@Override
public void init() throws ServletException {
super.init(); //To change body of generated methods, choose Tools | Templates.
try {
hasher = new SuperHasher();
} catch (GeneralSecurityException ex) {
Logger.getLogger(McproxyStratumServlet.class.getName()).log(Level.SEVERE, null, ex);
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if (DEBUG) {
System.out.println(prefix + "method: " + request.getMethod());
}
String type = request.getContentType();
//String authHeader = request.getHeader("authorization");
int contentLength = Integer.parseInt( request.getHeader("content-length") );
if (DEBUG) {
//System.out.println("auth: " + authHeader);
//System.out.println("content-type: " + type );
}
byte cbuf[] = new byte[contentLength];
request.getInputStream().read(cbuf);
String content = new String(cbuf);
if (DEBUG) {
//System.out.println("content-len: " + contentLength);
//System.out.println("content: " + content);
}
ObjectNode node = null;
try {
node = (ObjectNode) mapper.readTree(content);
} catch (IOException ex) {
Logger.getLogger(McproxyStratumServlet.class.getName()).log(Level.SEVERE, null, ex);
}
String jsonMethod = node.get("method").asText();
if (DEBUG) {
//System.out.println("jsonMethod: " + jsonMethod);
}
int paramSize = -1;
if (node.get("params").isArray()) {
paramSize = node.get("params").size();
}
String id = node.get("id").asText();
String answer = "";
if (type.toString().equals("application/json") && jsonMethod.equals("getwork") && paramSize == 0) {
System.out.println(prefix + "getwork request from miner...");
// data has already been byteswapped
McproxyHandler.SessionStorage sessionStorage = StratumThread.getSessionStorage();
System.out.println(prefix + "sending getwork: " + sessionStorage.answer);
works.put(sessionStorage.sentData.substring(0, 68*2) , sessionStorage);
answer = sessionStorage.answer;
} else if (type.toString().equals("application/json") && jsonMethod.equals("getwork") && paramSize != 0) {
System.out.println(prefix + "submitwork request from miner... works queue size: " + works.size());
String receivedDataStr = node.get("params").get(0).asText();
String receivedDataStr68 = receivedDataStr.substring(0, 68*2);
McproxyHandler.SessionStorage sessionStorage = works.get( receivedDataStr68 );
if (sessionStorage == null) {
System.out.println(prefix + "WORK NOT FOUND!!! " + receivedDataStr);
answer = "{\"result\":false,\"error\":null,\"id\":1}";
} else {
works.remove( receivedDataStr68 );
WorkState work = sessionStorage.work;
if (DEBUG) {
System.out.println(prefix + "RECEIVED WORK: " + receivedDataStr);
System.out.println(prefix + "dataFromWallet: " + sessionStorage.dataFromWallet);
System.out.println(prefix + "sentData TO MINER: " + sessionStorage.sentData);
}
// second part verification (STAGE2)
// 1 - byteswap all data received from miner
receivedDataStr = WorkState.byteSwap(receivedDataStr);
String nonceStr = receivedDataStr.substring(76*2, 76*2 + 8);
if (DEBUG) {
System.out.println(prefix + "byteswapped nonce: " + nonceStr);
}
// copy nonce from received work (and also nTime and nBits) to original work, a total of 12 bytes
byte [] data = work.getData1();
/*
for (int i = 0; i < 24; i += 2) {
String n = receivedDataStr.substring(i, i + 2);
data[68 + i / 2] = (byte) (0xFF & Integer.parseInt(n, 16)); //Byte.parseByte(n, 16);
}
*/
// 2 - calculate part2 of hybridhash
byte [] targetBits = new byte[4];
targetBits[0] = work.getData1()[72]; // LSB
targetBits[1] = work.getData1()[73];
targetBits[2] = work.getData1()[74];
targetBits[3] = work.getData1()[75]; // MSB
byte[] finalHash = null;
try {
finalHash = hasher.secondPartHash(data, targetBits);
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(McproxyStratumServlet.class.getName()).log(Level.SEVERE, null, ex);
} catch (GeneralSecurityException ex) {
Logger.getLogger(McproxyStratumServlet.class.getName()).log(Level.SEVERE, null, ex);
}
// 2.1 - verify hash
/*
byte [] header = work.getData1();
byte a, b, c, d;
a = targetBits[3]; //header[72]; // MSB
b = targetBits[2]; // header[73];
c = targetBits[1]; //header[74];
d = targetBits[0]; //header[75];
int nSize;
nSize = a & 0xFF;
boolean negative = (b & 0x80) != 0;
int nWord = ((b & 0x7F) << 16) + ((c & 0xFF) << 8) + (d & 0xFF);
if (DEBUG) {
System.out.println(prefix + "size=" + nSize);
System.out.println(prefix + "negative=" + negative);
System.out.println(prefix + "nWord=" + nWord);
}
BigInteger hashTarget = new BigInteger("" + nWord, 10);
hashTarget = hashTarget.shiftLeft( 8 * (nSize -3));
*/
String targetStr = WorkState.byteSwap( work.getTarget());
System.out.println(prefix + "hashTarget STR: " + targetStr);
BigInteger hashTarget = new BigInteger( targetStr ,16);
//System.out.println("hashTarget: " + hashTarget);
if (DEBUG)
System.out.println(prefix + "hashTarget: " + hashTarget.toString(16));
BigInteger hash = new BigInteger( 1 , SuperHasher.swap(finalHash) );
boolean checkHash = hash.compareTo(hashTarget) <= 0;
if (DEBUG)
System.out.println(prefix + "hash: " + hash.toString(16));
System.out.println(prefix + "is hash ok? " + checkHash);
if (!checkHash ) {
System.out.println(prefix + "returning FALSE to submit request");
answer = "{\"result\":false,\"error\":null,\"id\":1}";
} else {
// TODO: modify sessionStorage.serverWork with correct nonce
sessionStorage.serverWork.nonce = WorkState.byteSwap(nonceStr); // nonceStr;
// submit work to Stratum
// CHECK: need to byteswap?
boolean poolSubmitResult = stratumConnection.sendWorkSubmission(sessionStorage.serverWork);
if (DEBUG) {
System.out.println(prefix + "returning " + poolSubmitResult +" to submit request");
}
answer = "{\"result\":" + poolSubmitResult + ",\"error\":null,\"id\":1}";
}
//String workStr = WorkState.byteSwap(sessionStorage.dataFromWallet.substring(0, 68*2)) +
// receivedDataStr.substring(68*2);
try {
for (Iterator<String> i = works.keySet().iterator(); i.hasNext();) {
String key = i.next();
McproxyHandler.SessionStorage ss = works.get(key);
long delta = (System.currentTimeMillis() - ss.timestamp) / 1000;
if (delta > 120) {
ss.serverWork = null;
ss.work = null;
works.remove(ss);
}
}
} catch (Exception ex) {
System.out.println("Error: " + ex.toString());
}
}
}
response.setContentType("application/json");
response.setStatus(HttpServletResponse.SC_OK);
//baseRequest.setHandled(true);
response.getWriter().println(answer);
}
public static void main(String [] arg) throws GeneralSecurityException {
if (true) {
String START = "eecb92d5eefa3c91daed8b7a1ebc3093c15b4b459c05e54d92e78bf535d6c234a3e00426a7648f4ac8214fae1d9262427d2d7e6609f5323b4fd1f887a4aba6cf25eee7bf52fe29b01b01f9321dc38608" +
"000000800000000000000000000000000000000000000000000000000000000000000000000000000000000080020000";
WorkState work = new WorkState(null);
work.parseData(START);
System.out.println(work.getAllDataHex());
SuperHasher hasher = new SuperHasher();
String receivedDataStr = work.getAllDataHex();
//receivedDataStr = WorkState.byteSwap(receivedDataStr);
System.out.println(receivedDataStr);
String nonceStr = receivedDataStr.substring(76*2, 76*2 + 8);
if (DEBUG) {
System.out.println(prefix + "byteswapped nonce: " + nonceStr);
}
// copy nonce from received work (and also nTime and nBits) to original work, a total of 12 bytes
byte [] data = work.getData1();
for (int i = 0; i < 24; i += 2) {
String n = receivedDataStr.substring(68*2 + i, 68*2 + i + 2);
byte nv = (byte) (0xFF & Integer.parseInt(n, 16));
if (nv != data[68 + i / 2]) {
System.out.println("*** " + (8 + i / 2));
data[68 + i / 2] = nv;
}
//Byte.parseByte(n, 16);
}
// 2 - calculate part2 of hybridhash
byte [] targetBits = new byte[4];
targetBits[0] = work.getData1()[72]; // LSB
targetBits[1] = work.getData1()[73];
targetBits[2] = work.getData1()[74];
targetBits[3] = work.getData1()[75]; // MSB
byte[] finalHash = null;
try {
finalHash = hasher.secondPartHash(data, targetBits);
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(McproxyStratumServlet.class.getName()).log(Level.SEVERE, null, ex);
} catch (GeneralSecurityException ex) {
Logger.getLogger(McproxyStratumServlet.class.getName()).log(Level.SEVERE, null, ex);
}
work.setTarget("3fffc000000000000000000000000000000000000000000000000000000");
BigInteger hashTarget = new BigInteger( ( work.getTarget()) ,16);
//System.out.println("hashTarget: " + hashTarget);
if (DEBUG)
System.out.println(prefix + "hashTarget: " + hashTarget.toString(16));
BigInteger hash = new BigInteger( 1 , SuperHasher.swap(finalHash) );
boolean checkHash = hash.compareTo(hashTarget) <= 0;
if (DEBUG)
System.out.println(prefix + "hash: " + hash.toString(16));
System.out.println(prefix + "hash: " + hash.toString(10));
System.out.println(prefix + "is hash ok? " + checkHash);
return;
}
if (true) {
BigInteger bi = new BigInteger("15363741008652289555944905765563173368446543359880944893284847603");
System.out.println(bi.toString(16));
return;
}
// 52fdf7a6 1b01c274
//1b01c274
byte [] header = { 0x1b,
0x01,
(byte)0x9d,
(byte)0x93 };
header = new byte [] { 0x1b,
0x01,
(byte)0xc2,
(byte)74 };
SuperHasher.DEBUG = true;
BigInteger hashTarget = SuperHasher.readCompact(header[0], header[1], header[2],header[3]);
//System.out.println("hashTarget: " + hashTarget);
System.out.println(prefix + "hashTarget: " + hashTarget.toString(16));
//BigInteger hash = new BigInteger( 1 , SuperHasher.swap(finalHash) );
//boolean checkHash = hash.compareTo(hashTarget) <= 0;
BigInteger p = new BigInteger("421242738922051710830569942886312364625170292790221313845902704640");
System.out.println(prefix + "POOL target: " + p.toString(16));
}
}
|
// $Id: UDP.java,v 1.8 2004/01/07 00:29:21 belaban Exp $
package org.jgroups.protocols;
import java.io.*;
import java.net.*;
import java.util.HashMap;
import java.util.Properties;
import java.util.Vector;
import org.jgroups.*;
import org.jgroups.util.*;
import org.jgroups.stack.*;
import org.jgroups.log.Trace;
/**
* IP multicast transport based on UDP. Messages to the group (msg.dest == null) will
* be multicast (to all group members), whereas point-to-point messages
* (msg.dest != null) will be unicast to a single member. Uses a multicast and
* a unicast socket.<p>
* The following properties are being read by the UDP protocol<p>
* param mcast_addr - the multicast address to use default is 224.0.0.200<br>
* param mcast_port - (int) the port that the multicast is sent on default is 7500<br>
* param ip_mcast - (boolean) flag whether to use IP multicast - default is true<br>
* param ip_ttl - Set the default time-to-live for multicast packets sent out on this
* socket. default is 32<br>
* param use_packet_handler - If set, the mcast and ucast receiver threads just put
* the datagram's payload (a byte buffer) into a queue, from where a separate thread
* will dequeue and handle them (unmarshal and pass up). This frees the receiver
* threads from having to do message unmarshalling; this time can now be spent
* receiving packets. If you have lots of retransmissions because of network
* input buffer overflow, consider setting this property to true (default is false).
* @author Bela Ban
*/
public class UDP extends Protocol implements Runnable {
/** Socket used for
* <ol>
* <li>sending unicast packets
* <li>sending multicast packets and
* <li>receiving unicast packets
* </ol>
* The address of this socket will be our local address (<tt>local_addr</tt>) */
DatagramSocket sock=null;
/** IP multicast socket for <em>receiving</em> multicast packets */
MulticastSocket mcast_sock=null;
/** The address (host and port) of this member */
IpAddress local_addr=null;
/** The name of the group to which this member is connected */
String group_addr=null;
/** The multicast address (mcast address and port) this member uses */
IpAddress mcast_addr=null;
/** The interface (NIC) to which the unicast and multicast sockets bind */
InetAddress bind_addr=null;
/** The port to which the unicast receiver socket binds.
* 0 means to bind to any (ephemeral) port */
int bind_port=0;
int port_range=1; // 27-6-2003 bgooren, Only try one port by default
/** The multicast address used for sending and receiving packets */
String mcast_addr_name="228.8.8.8";
/** The multicast port used for sending and receiving packets */
int mcast_port=7600;
/** The multicast receiver thread */
Thread mcast_receiver=null;
/** The unicast receiver thread */
UcastReceiver ucast_receiver=null;
/** Whether to enable IP multicasting. If false, multiple unicast datagram
* packets are sent rather than one multicast packet */
boolean ip_mcast=true;
/** The time-to-live (TTL) for multicast datagram packets */
int ip_ttl=64;
/** The members of this group (updated when a member joins or leaves) */
Vector members=new Vector();
/** Pre-allocated byte stream. Used for serializing datagram packets. Will grow as needed */
ByteArrayOutputStream out_stream=new ByteArrayOutputStream(65535);
/** Header to be added to all messages sent via this protocol. It is
* preallocated for efficiency */
UdpHeader udp_hdr=null;
/** Send buffer size of the multicast datagram socket */
int mcast_send_buf_size=32000;
/** Receive buffer size of the multicast datagram socket */
int mcast_recv_buf_size=64000;
/** Send buffer size of the unicast datagram socket */
int ucast_send_buf_size=32000;
/** Receive buffer size of the unicast datagram socket */
int ucast_recv_buf_size=64000;
/** If true, messages sent to self are treated specially: unicast messages are
* looped back immediately, multicast messages get a local copy first and -
* when the real copy arrives - it will be discarded. Useful for Window
* media (non)sense */
boolean loopback=true;
/** Sometimes receivers are overloaded (they have to handle de-serialization etc).
* Packet handler is a separate thread taking care of de-serialization, receiver
* thread(s) simply put packet in queue and return immediately. Setting this to
* true adds one more thread */
boolean use_incoming_packet_handler=false;
/** Used by packet handler to store incoming DatagramPackets */
Queue incoming_queue=null;
/** Dequeues DatagramPackets from packet_queue, unmarshalls them and
* calls <tt>handleIncomingUdpPacket()</tt> */
IncomingPacketHandler incoming_packet_handler=null;
/** Packets to be sent are stored in outgoing_queue and sent by a separate thread. Enabling this
* value uses an additional thread */
boolean use_outgoing_packet_handler=false;
/** Used by packet handler to store outgoing DatagramPackets */
Queue outgoing_queue=null;
OutgoingPacketHandler outgoing_packet_handler=null;
/** If set it will be added to <tt>local_addr</tt>. Used to implement
* for example transport independent addresses */
byte[] additional_data=null;
/** The name of this protocol */
final String name="UDP";
final int VERSION_LENGTH=Version.getLength();
/**
* public constructor. creates the UDP protocol, and initializes the
* state variables, does however not start any sockets or threads
*/
public UDP() {
;
}
/**
* debug only
*/
public String toString() {
return "Protocol UDP(local address: " + local_addr + ")";
}
public void run() {
DatagramPacket packet;
byte receive_buf[]=new byte[65535];
int len;
byte[] tmp, data;
// moved out of loop to avoid excessive object creations (bela March 8 2001)
packet=new DatagramPacket(receive_buf, receive_buf.length);
while(mcast_receiver != null && mcast_sock != null) {
try {
packet.setData(receive_buf, 0, receive_buf.length);
mcast_sock.receive(packet);
len=packet.getLength();
data=packet.getData();
if(len == 1 && data[0] == 0) {
if(Trace.debug) Trace.info("UDP.run()", "received dummy packet");
continue;
}
if(len == 4) { // received a diagnostics probe
if(data[0] == 'd' && data[1] == 'i' && data[2] == 'a' && data[3] == 'g') {
handleDiagnosticProbe(packet.getAddress(), packet.getPort());
continue;
}
}
if(Trace.debug)
Trace.info("UDP.receive()", "received (mcast) " + packet.getLength() + " bytes from " +
packet.getAddress() + ":" + packet.getPort() + " (size=" + len + " bytes)");
if(len > receive_buf.length) {
Trace.error("UDP.run()", "size of the received packet (" + len + ") is bigger than " +
"allocated buffer (" + receive_buf.length + "): will not be able to handle packet. " +
"Use the FRAG protocol and make its frag_size lower than " + receive_buf.length);
}
if(Version.compareTo(data) == false) {
Trace.warn("UDP.run()",
"packet from " + packet.getAddress() + ":" + packet.getPort() +
" has different version (" +
Version.printVersionId(data, Version.version_id.length) +
") from ours (" + Version.printVersionId(Version.version_id) +
"). This may cause problems");
}
if(use_incoming_packet_handler) {
tmp=new byte[len];
System.arraycopy(data, 0, tmp, 0, len);
incoming_queue.add(tmp);
}
else
handleIncomingUdpPacket(data);
}
catch(SocketException sock_ex) {
if(Trace.trace) Trace.info("UDP.run()", "multicast socket is closed, exception=" + sock_ex);
break;
}
catch(InterruptedIOException io_ex) { // thread was interrupted
; // go back to top of loop, where we will terminate loop
}
catch(Throwable ex) {
Trace.error("UDP.run()", "exception=" + ex + ", stack trace=" + Util.printStackTrace(ex));
Util.sleep(300); // so we don't get into 100% cpu spinning (should NEVER happen !)
}
}
if(Trace.trace) Trace.info("UDP.run()", "multicast thread terminated");
}
void handleDiagnosticProbe(InetAddress sender, int port) {
try {
byte[] diag_rsp=getDiagResponse().getBytes();
DatagramPacket rsp=new DatagramPacket(diag_rsp, 0, diag_rsp.length, sender, port);
if(Trace.trace)
Trace.info("UDP.handleDiagnosticProbe()", "sending diag response to " + sender + ":" + port);
sock.send(rsp);
}
catch(Throwable t) {
Trace.error("UDP.handleDiagnosticProbe()", "failed sending diag rsp to " + sender + ":" + port +
", exception=" + t);
}
}
String getDiagResponse() {
StringBuffer sb=new StringBuffer();
sb.append(local_addr).append(" (").append(group_addr).append(")");
sb.append(" [").append(mcast_addr_name).append(":").append(mcast_port).append("]\n");
sb.append("Version=").append(Version.version).append(", cvs=\"").append(Version.cvs).append("\"\n");
sb.append("bound to ").append(bind_addr).append(":").append(bind_port).append("\n");
sb.append("members: ").append(members).append("\n");
return sb.toString();
}
public String getName() {
return name;
}
public void init() throws Exception {
if(use_incoming_packet_handler) {
incoming_queue=new Queue();
incoming_packet_handler=new IncomingPacketHandler();
}
if(use_outgoing_packet_handler) {
outgoing_queue=new Queue();
outgoing_packet_handler=new OutgoingPacketHandler();
}
}
/**
* Creates the unicast and multicast sockets and starts the unicast and multicast receiver threads
*/
public void start() throws Exception {
if(Trace.trace) Trace.info("UDP.start()", "creating sockets and starting threads");
createSockets();
passUp(new Event(Event.SET_LOCAL_ADDRESS, local_addr));
startThreads();
}
public void stop() {
if(Trace.trace) Trace.info("UDP.stop()", "closing sockets and stopping threads");
stopThreads(); // will close sockets, closeSockets() is not really needed anymore, but...
closeSockets(); // ... we'll leave it in there for now (doesn't do anything if already closed)
}
/**
* Setup the Protocol instance acording to the configuration string
* The following properties are being read by the UDP protocol
* param mcast_addr - the multicast address to use default is 224.0.0.200
* param mcast_port - (int) the port that the multicast is sent on default is 7500
* param ip_mcast - (boolean) flag whether to use IP multicast - default is true
* param ip_ttl - Set the default time-to-live for multicast packets sent out on this socket. default is 32
* @return true if no other properties are left.
* false if the properties still have data in them, ie ,
* properties are left over and not handled by the protocol stack
*
*/
public boolean setProperties(Properties props) {
String str, tmp;
tmp=System.getProperty("UDP.bind_addr");
if(tmp != null)
str=tmp;
else
str=props.getProperty("bind_addr");
if(str != null) {
try {
bind_addr=InetAddress.getByName(str);
}
catch(UnknownHostException unknown) {
Trace.fatal("UDP.setProperties()", "(bind_addr): host " + str + " not known");
return false;
}
props.remove("bind_addr");
}
str=props.getProperty("bind_port");
if(str != null) {
bind_port=new Integer(str).intValue();
props.remove("bind_port");
}
str=props.getProperty("start_port");
if(str != null) {
bind_port=new Integer(str).intValue();
props.remove("start_port");
}
str=props.getProperty("port_range");
if(str != null) {
port_range=new Integer(str).intValue();
props.remove("port_range");
}
str=props.getProperty("mcast_addr");
if(str != null) {
mcast_addr_name=new String(str);
props.remove("mcast_addr");
}
str=props.getProperty("mcast_port");
if(str != null) {
mcast_port=new Integer(str).intValue();
props.remove("mcast_port");
}
str=props.getProperty("ip_mcast");
if(str != null) {
ip_mcast=new Boolean(str).booleanValue();
props.remove("ip_mcast");
}
str=props.getProperty("ip_ttl");
if(str != null) {
ip_ttl=new Integer(str).intValue();
props.remove("ip_ttl");
}
str=props.getProperty("mcast_send_buf_size");
if(str != null) {
mcast_send_buf_size=Integer.parseInt(str);
props.remove("mcast_send_buf_size");
}
str=props.getProperty("mcast_recv_buf_size");
if(str != null) {
mcast_recv_buf_size=Integer.parseInt(str);
props.remove("mcast_recv_buf_size");
}
str=props.getProperty("ucast_send_buf_size");
if(str != null) {
ucast_send_buf_size=Integer.parseInt(str);
props.remove("ucast_send_buf_size");
}
str=props.getProperty("ucast_recv_buf_size");
if(str != null) {
ucast_recv_buf_size=Integer.parseInt(str);
props.remove("ucast_recv_buf_size");
}
str=props.getProperty("loopback");
if(str != null) {
loopback=new Boolean(str).booleanValue();
props.remove("loopback");
}
// this is deprecated, just left for compatibility (use use_incoming_packet_handler)
str=props.getProperty("use_packet_handler");
if(str != null) {
use_incoming_packet_handler=new Boolean(str).booleanValue();
props.remove("use_packet_handler");
Trace.warn("UDP.setProperties()",
"'use_packet_handler' is deprecated; use 'use_incoming_packet_handler' instead");
}
str=props.getProperty("use_incoming_packet_handler");
if(str != null) {
use_incoming_packet_handler=new Boolean(str).booleanValue();
props.remove("use_incoming_packet_handler");
}
str=props.getProperty("use_outgoing_packet_handler");
if(str != null) {
use_outgoing_packet_handler=new Boolean(str).booleanValue();
props.remove("use_outgoing_packet_handler");
}
if(props.size() > 0) {
System.err.println("UDP.setProperties(): the following properties are not recognized:");
props.list(System.out);
return false;
}
return true;
}
/**
* DON'T REMOVE ! This prevents the up-handler thread to be created, which essentially is superfluous:
* messages are received from the network rather than from a layer below.
*/
public void startUpHandler() {
;
}
/**
* handle the UP event.
* @param evt - the event being send from the stack
*/
public void up(Event evt) {
passUp(evt);
switch(evt.getType()) {
case Event.CONFIG:
passUp(evt);
if(Trace.trace) Trace.info("UDP.up()", "received CONFIG event: " + evt.getArg());
handleConfigEvent((HashMap)evt.getArg());
return;
}
passUp(evt);
}
/**
* Caller by the layer above this layer. Usually we just put this Message
* into the send queue and let one or more worker threads handle it. A worker thread
* then removes the Message from the send queue, performs a conversion and adds the
* modified Message to the send queue of the layer below it, by calling Down).
*/
public void down(Event evt) {
Message msg;
Object dest_addr;
if(evt.getType() != Event.MSG) { // unless it is a message handle it and respond
handleDownEvent(evt);
return;
}
msg=(Message)evt.getArg();
if(udp_hdr != null && udp_hdr.group_addr != null) {
// added patch by Roland Kurmann (March 20 2003)
msg.putHeader(name, udp_hdr);
}
dest_addr=msg.getDest();
// Because we don't call Protocol.passDown(), we notify the observer directly (e.g. PerfObserver).
// This way, we still have performance numbers for UDP
if(observer != null)
observer.passDown(evt);
if(dest_addr == null) { // 'null' means send to all group members
if(ip_mcast) {
if(mcast_addr == null) {
Trace.error("UDP.down()", "dest address of message is null, and " +
"sending to default address fails as mcast_addr is null, too !" +
" Discarding message " + Util.printEvent(evt));
return;
}
//if we want to use IP multicast, then set the destination of the message
msg.setDest(mcast_addr);
}
else {
//sends a separate UDP message to each address
sendMultipleUdpMessages(msg, members);
return;
}
}
try {
sendUdpMessage(msg);
}
catch(Exception e) {
Trace.error("UDP.down()", "exception=" + e + ", msg=" + msg + ", mcast_addr=" + mcast_addr);
}
}
/**
* If the sender is null, set our own address. We cannot just go ahead and set the address
* anyway, as we might be sending a message on behalf of someone else ! E.g. in case of
* retransmission, when the original sender has crashed, or in a FLUSH protocol when we
* have to return all unstable messages with the FLUSH_OK response.
*/
void setSourceAddress(Message msg) {
if(msg.getSrc() == null)
msg.setSrc(local_addr);
}
/**
* Processes a packet read from either the multicast or unicast socket. Needs to be synchronized because
* mcast or unicast socket reads can be concurrent
*/
void handleIncomingUdpPacket(byte[] data) {
ByteArrayInputStream inp_stream;
ObjectInputStream inp;
Message msg=null;
UdpHeader hdr=null;
Event evt;
try {
// skip the first n bytes (default: 4), this is the version info
inp_stream=new ByteArrayInputStream(data, VERSION_LENGTH, data.length - VERSION_LENGTH);
inp=new ObjectInputStream(inp_stream);
msg=new Message();
msg.readExternal(inp);
// discard my own multicast loopback copy
if(loopback) {
Address dst=msg.getDest();
Address src=msg.getSrc();
if(dst != null && dst.isMulticastAddress() && src != null && local_addr.equals(src)) {
if(Trace.debug)
Trace.info("UDP.handleIncomingUdpPacket()", "discarded own loopback multicast packet");
return;
}
}
evt=new Event(Event.MSG, msg);
if(Trace.debug)
Trace.info("UDP.handleIncomingUdpPacket()", "Message is " + msg + ", headers are " +
msg.getHeaders());
/* Because Protocol.up() is never called by this bottommost layer, we call up() directly in the observer.
* This allows e.g. PerfObserver to get the time of reception of a message */
if(observer != null)
observer.up(evt, up_queue.size());
hdr=(UdpHeader)msg.removeHeader(name);
}
catch(Throwable e) {
Trace.error("UDP.handleIncomingUdpPacket()", "exception=" + Trace.getStackTrace(e));
return;
}
if(hdr != null) {
/* Discard all messages destined for a channel with a different name */
String ch_name=null;
if(hdr.group_addr != null)
ch_name=hdr.group_addr;
// Discard if message's group name is not the same as our group name unless the
// message is a diagnosis message (special group name DIAG_GROUP)
if(ch_name != null && group_addr != null && !group_addr.equals(ch_name) &&
!ch_name.equals(Util.DIAG_GROUP)) {
if(Trace.trace)
Trace.warn("UDP.handleIncomingUdpPacket()", "discarded message from different group (" +
ch_name + "). Sender was " + msg.getSrc());
return;
}
}
passUp(evt);
}
/** Send a message to the address specified in dest */
void sendUdpMessage(Message msg) throws Exception {
IpAddress dest;
Message copy;
Event evt;
dest=(IpAddress)msg.getDest(); // guaranteed not to be null
setSourceAddress(msg);
if(Trace.debug)
Trace.debug("UDP.sendUdpMessage()",
"sending message to " + msg.getDest() +
" (src=" + msg.getSrc() + "), headers are " + msg.getHeaders());
// Don't send if destination is local address. Instead, switch dst and src and put in up_queue.
// If multicast message, loopback a copy directly to us (but still multicast). Once we receive this,
// we will discard our own multicast message
if(loopback && (dest.equals(local_addr) || dest.isMulticastAddress())) {
copy=msg.copy();
copy.removeHeader(name);
copy.setSrc(local_addr);
copy.setDest(dest);
evt=new Event(Event.MSG, copy);
/* Because Protocol.up() is never called by this bottommost layer, we call up() directly in the observer.
This allows e.g. PerfObserver to get the time of reception of a message */
if(observer != null)
observer.up(evt, up_queue.size());
if(Trace.debug) Trace.info("UDP.sendUdpMessage()", "looped back local message " + copy);
passUp(evt);
if(!dest.isMulticastAddress())
return;
}
if(use_outgoing_packet_handler) {
outgoing_queue.add(msg);
return;
}
send(msg);
}
/** Internal method to serialize and send a message. This method is not reentrant */
void send(Message msg) throws Exception {
DatagramPacket packet;
ObjectOutputStream out;
// BufferedOutputStream bos;
byte[] buf;
IpAddress dest=(IpAddress)msg.getDest();
out_stream.reset();
//bos=new BufferedOutputStream(out_stream);
out_stream.write(Version.version_id, 0, Version.version_id.length); // write the version
// bos.write(Version.version_id, 0, Version.version_id.length); // write the version
out=new ObjectOutputStream(out_stream);
// out=new ObjectOutputStream(bos);
msg.writeExternal(out);
out.flush(); // needed if out buffers its output to out_stream
buf=out_stream.toByteArray();
packet=new DatagramPacket(buf, buf.length, dest.getIpAddress(), dest.getPort());
sock.send(packet);
}
void sendMultipleUdpMessages(Message msg, Vector dests) {
Address dest;
for(int i=0; i < dests.size(); i++) {
dest=(Address)dests.elementAt(i);
msg.setDest(dest);
try {
sendUdpMessage(msg);
}
catch(Exception e) {
Trace.debug("UDP.sendMultipleUdpMessages()", "exception=" + e);
}
}
}
/**
* Create UDP sender and receiver sockets. Currently there are 2 sockets
* (sending and receiving). This is due to Linux's non-BSD compatibility
* in the JDK port (see DESIGN).
*/
void createSockets() throws Exception {
InetAddress tmp_addr=null;
// bind_addr not set, try to assign one by default. This is needed on Windows
// changed by bela Feb 12 2003: by default multicast sockets will be bound to all network interfaces
// CHANGED *BACK* by bela March 13 2003: binding to all interfaces did not result in a correct
// local_addr. As a matter of fact, comparison between e.g. 0.0.0.0:1234 (on hostA) and
// 0.0.0.0:1.2.3.4 (on hostB) would fail !
if(bind_addr == null) {
InetAddress[] interfaces=InetAddress.getAllByName(InetAddress.getLocalHost().getHostAddress());
if(interfaces != null && interfaces.length > 0)
bind_addr=interfaces[0];
}
if(bind_addr == null)
bind_addr=InetAddress.getLocalHost();
if(bind_addr != null && Trace.trace)
Trace.info("UDP.createSockets()", "unicast sockets will use interface " +
bind_addr.getHostAddress());
// 2. Create socket for receiving unicast UDP packets. The address and port
// of this socket will be our local address (local_addr)
// 27-6-2003 bgooren, find available port in range (start_port, start_port+port_range)
int rcv_port=bind_port, max_port=bind_port + port_range;
while(rcv_port <= max_port) {
try {
sock=new DatagramSocket(rcv_port, bind_addr);
break;
}
catch(SocketException bind_ex) { // Cannot listen on this port
rcv_port++;
}
catch(SecurityException sec_ex) { // Not allowed to list on this port
rcv_port++;
}
// Cannot listen at all, throw an Exception
if(rcv_port == max_port + 1) { // +1 due to the increment above
throw new Exception("UDP.createSockets(): cannot list on any port in range " +
bind_port + "-" + (bind_port + port_range));
}
}
//ucast_recv_sock=new DatagramSocket(bind_port, bind_addr);
if(sock == null)
throw new Exception("UDP.createSocket(): sock is null");
local_addr=new IpAddress(sock.getLocalAddress(), sock.getLocalPort());
if(additional_data != null)
local_addr.setAdditionalData(additional_data);
// 3. Create socket for receiving IP multicast packets
if(ip_mcast) {
mcast_sock=new MulticastSocket(mcast_port);
mcast_sock.setTimeToLive(ip_ttl);
if(bind_addr != null)
mcast_sock.setInterface(bind_addr);
tmp_addr=InetAddress.getByName(mcast_addr_name);
mcast_addr=new IpAddress(tmp_addr, mcast_port);
mcast_sock.joinGroup(tmp_addr);
}
setBufferSizes();
if(Trace.trace)
Trace.info("UDP.createSockets()", "socket information:\n" + dumpSocketInfo());
}
String dumpSocketInfo() throws Exception {
StringBuffer sb=new StringBuffer();
sb.append("local_addr=").append(local_addr);
sb.append(", mcast_addr=").append(mcast_addr);
sb.append(", bind_addr=").append(bind_addr);
sb.append(", ttl=").append(ip_ttl);
if(sock != null) {
sb.append("\nsocket: bound to ");
sb.append(sock.getLocalAddress().getHostAddress()).append(":").append(sock.getLocalPort());
sb.append(", receive buffer size=").append(sock.getReceiveBufferSize());
sb.append(", send buffer size=").append(sock.getSendBufferSize());
}
if(mcast_sock != null) {
sb.append("\nmulticast socket: bound to ");
sb.append(mcast_sock.getInterface().getHostAddress()).append(":").append(mcast_sock.getLocalPort());
sb.append(", send buffer size=").append(mcast_sock.getSendBufferSize());
sb.append(", receive buffer size=").append(mcast_sock.getReceiveBufferSize());
}
return sb.toString();
}
void setBufferSizes() {
if(sock != null) {
try {
sock.setSendBufferSize(ucast_send_buf_size);
}
catch(Throwable ex) {
Trace.warn("UDP.setBufferSizes()", "failed setting ucast_send_buf_size in sock: " + ex);
}
try {
sock.setReceiveBufferSize(ucast_recv_buf_size);
}
catch(Throwable ex) {
Trace.warn("UDP.setBufferSizes()", "failed setting ucast_recv_buf_size in sock: " + ex);
}
}
if(mcast_sock != null) {
try {
mcast_sock.setSendBufferSize(mcast_send_buf_size);
}
catch(Throwable ex) {
Trace.warn("UDP.setBufferSizes()", "failed setting mcast_send_buf_size in mcast_sock: " + ex);
}
try {
mcast_sock.setReceiveBufferSize(mcast_recv_buf_size);
}
catch(Throwable ex) {
Trace.warn("UDP.setBufferSizes()", "failed setting mcast_recv_buf_size in mcast_sock: " + ex);
}
}
}
/**
* Closed UDP unicast and multicast sockets
*/
void closeSockets() {
// 1. Close multicast socket
closeMulticastSocket();
// 2. Close socket
closeSocket();
}
void closeMulticastSocket() {
if(mcast_sock != null) {
try {
if(mcast_addr != null) {
// by sending a dummy packet the thread will be awakened
sendDummyPacket(mcast_addr.getIpAddress(), mcast_addr.getPort());
Util.sleep(300);
mcast_sock.leaveGroup(mcast_addr.getIpAddress());
}
mcast_sock.close(); // this will cause the mcast receiver thread to break out of its loop
mcast_sock=null;
if(Trace.trace) Trace.info("UDP.closeMulticastSocket()", "multicast socket closed");
}
catch(IOException ex) {
}
mcast_addr=null;
}
}
void closeSocket() {
if(sock != null) {
// by sending a dummy packet, the thread will terminate (if it was flagged as stopped before)
sendDummyPacket(sock.getLocalAddress(), sock.getLocalPort());
sock.close();
sock=null;
if(Trace.trace) Trace.info("UDP.closeSocket()", "socket closed");
}
}
/**
* Workaround for the problem encountered in certains JDKs that a thread listening on a socket
* cannot be interrupted. Therefore we just send a dummy datagram packet so that the thread 'wakes up'
* and realizes it has to terminate. Should be removed when all JDKs support Thread.interrupt() on
* reads. Uses sock t send dummy packet, so this socket has to be still alive.
* @param dest The destination host. Will be local host if null
* @param port The destination port
*/
void sendDummyPacket(InetAddress dest, int port) {
DatagramPacket packet;
byte[] buf={0};
if(dest == null) {
try {
dest=InetAddress.getLocalHost();
}
catch(Exception e) {
}
}
if(Trace.debug) Trace.info("UDP.sendDummyPacket()", "sending packet to " + dest + ":" + port);
if(sock == null || dest == null) {
Trace.warn("UDP.sendDummyPacket()", "sock was null or dest was null, cannot send dummy packet");
return;
}
packet=new DatagramPacket(buf, buf.length, dest, port);
try {
sock.send(packet);
}
catch(Throwable e) {
Trace.error("UDP.sendDummyPacket()", "exception sending dummy packet to " + dest + ":" + port + ": " + e);
}
}
/**
* Starts the unicast and multicast receiver threads
*/
void startThreads() throws Exception {
if(ucast_receiver == null) {
//start the listener thread of the ucast_recv_sock
ucast_receiver=new UcastReceiver();
ucast_receiver.start();
if(Trace.trace) Trace.info("UDP.startThreads()", "created unicast receiver thread");
}
if(ip_mcast) {
if(mcast_receiver != null) {
if(mcast_receiver.isAlive()) {
if(Trace.trace)
Trace.info("UDP.createThreads()",
"did not create new multicastreceiver thread as existing " +
"multicast receiver thread is still running");
}
else
mcast_receiver=null; // will be created just below...
}
if(mcast_receiver == null) {
mcast_receiver=new Thread(this, "UDP mcast receiver");
mcast_receiver.setPriority(Thread.MAX_PRIORITY); // needed ????
mcast_receiver.setDaemon(true);
mcast_receiver.start();
}
}
if(use_outgoing_packet_handler)
outgoing_packet_handler.start();
if(use_incoming_packet_handler)
incoming_packet_handler.start();
}
/**
* Stops unicast and multicast receiver threads
*/
void stopThreads() {
Thread tmp;
// 1. Stop the multicast receiver thread
if(mcast_receiver != null) {
if(mcast_receiver.isAlive()) {
tmp=mcast_receiver;
mcast_receiver=null;
closeMulticastSocket(); // will cause the multicast thread to terminate
tmp.interrupt();
try {
tmp.join(100);
}
catch(Exception e) {
}
tmp=null;
}
mcast_receiver=null;
}
// 2. Stop the unicast receiver thread
if(ucast_receiver != null) {
ucast_receiver.stop();
ucast_receiver=null;
}
// 3. Stop the in_packet_handler thread
if(incoming_packet_handler != null)
incoming_packet_handler.stop();
}
void handleDownEvent(Event evt) {
switch(evt.getType()) {
case Event.TMP_VIEW:
case Event.VIEW_CHANGE:
synchronized(members) {
members.removeAllElements();
Vector tmpvec=((View)evt.getArg()).getMembers();
for(int i=0; i < tmpvec.size(); i++)
members.addElement(tmpvec.elementAt(i));
}
break;
case Event.GET_LOCAL_ADDRESS: // return local address -> Event(SET_LOCAL_ADDRESS, local)
passUp(new Event(Event.SET_LOCAL_ADDRESS, local_addr));
break;
case Event.CONNECT:
group_addr=(String)evt.getArg();
udp_hdr=new UdpHeader(group_addr);
// removed March 18 2003 (bela), not needed (handled by GMS)
// changed July 2 2003 (bela): we discard CONNECT_OK at the GMS level anyway, this might
// be needed if we run without GMS though
passUp(new Event(Event.CONNECT_OK));
break;
case Event.DISCONNECT:
passUp(new Event(Event.DISCONNECT_OK));
break;
case Event.CONFIG:
if(Trace.trace) Trace.info("UDP.down()", "received CONFIG event: " + evt.getArg());
handleConfigEvent((HashMap)evt.getArg());
break;
}
}
void handleConfigEvent(HashMap map) {
if(map == null) return;
if(map.containsKey("additional_data"))
additional_data=(byte[])map.get("additional_data");
if(map.containsKey("send_buf_size")) {
mcast_send_buf_size=((Integer)map.get("send_buf_size")).intValue();
ucast_send_buf_size=mcast_send_buf_size;
}
if(map.containsKey("recv_buf_size")) {
mcast_recv_buf_size=((Integer)map.get("recv_buf_size")).intValue();
ucast_recv_buf_size=mcast_recv_buf_size;
}
setBufferSizes();
}
public class UcastReceiver implements Runnable {
boolean running=true;
Thread thread=null;
public void start() {
if(thread == null) {
thread=new Thread(this, "UDP.UcastReceiverThread");
thread.setDaemon(true);
running=true;
thread.start();
}
}
public void stop() {
Thread tmp;
if(thread != null && thread.isAlive()) {
running=false;
tmp=thread;
thread=null;
closeSocket(); // this will cause the thread to break out of its loop
tmp.interrupt();
tmp=null;
}
thread=null;
}
public void run() {
DatagramPacket packet;
byte receive_buf[]=new byte[65535];
int len;
byte[] data, tmp;
// moved out of loop to avoid excessive object creations (bela March 8 2001)
packet=new DatagramPacket(receive_buf, receive_buf.length);
while(running && thread != null && sock != null) {
try {
packet.setData(receive_buf, 0, receive_buf.length);
sock.receive(packet);
len=packet.getLength();
data=packet.getData();
if(len == 1 && data[0] == 0) {
if(Trace.debug) Trace.info("UDP.UcastReceiver.run()", "received dummy packet");
continue;
}
if(Trace.debug)
Trace.info("UDP.UcastReceiver.run()", "received (ucast) " + len + " bytes from " +
packet.getAddress() + ":" + packet.getPort());
if(len > receive_buf.length) {
Trace.error("UDP.UcastReceiver.run()", "size of the received packet (" + len + ") is bigger than " +
"allocated buffer (" + receive_buf.length + "): will not be able to handle packet. " +
"Use the FRAG protocol and make its frag_size lower than " + receive_buf.length);
}
if(Version.compareTo(data) == false) {
Trace.warn("UDP.UcastReceiver.run()",
"packet from " + packet.getAddress() + ":" + packet.getPort() +
" has different version (" +
Version.printVersionId(data, Version.version_id.length) +
") from ours (" + Version.printVersionId(Version.version_id) +
"). This may cause problems");
}
if(use_incoming_packet_handler) {
tmp=new byte[len];
System.arraycopy(data, 0, tmp, 0, len);
incoming_queue.add(tmp);
}
else
handleIncomingUdpPacket(data);
}
catch(SocketException sock_ex) {
if(Trace.trace)
Trace.info("UDP.UcastReceiver.run()",
"unicast receiver socket is closed, exception=" + sock_ex);
break;
}
catch(InterruptedIOException io_ex) { // thread was interrupted
; // go back to top of loop, where we will terminate loop
}
catch(Throwable ex) {
Trace.error("UDP.UcastReceiver.run()", "[" + local_addr + "] exception=" + ex +
", stack trace=" + Util.printStackTrace(ex));
Util.sleep(300); // so we don't get into 100% cpu spinning (should NEVER happen !)
}
}
if(Trace.trace) Trace.info("UDP.UcastReceiver.run()", "unicast receiver thread terminated");
}
}
/**
* This thread fetches byte buffers from the packet_queue, converts them into messages and passes them up
* to the higher layer (done in handleIncomingUdpPacket()).
*/
class IncomingPacketHandler implements Runnable {
Thread t=null;
public void run() {
byte[] data;
while(incoming_queue != null && incoming_packet_handler != null) {
try {
data=(byte[])incoming_queue.remove();
}
catch(QueueClosedException closed_ex) {
if(Trace.trace) Trace.info("UDP.IncomingPacketHandler.run()", "packet_handler thread terminating");
break;
}
handleIncomingUdpPacket(data);
data=null; // let's give the poor garbage collector a hand...
}
}
void start() {
if(t == null) {
t=new Thread(this, "UDP.IncomingPacketHandler thread");
t.setDaemon(true);
t.start();
}
}
void stop() {
if(incoming_queue != null)
incoming_queue.close(false); // should terminate the packet_handler thread too
t=null;
incoming_queue=null;
}
}
/**
* This thread fetches byte buffers from the outgoing_packet_queue, converts them into messages and sends them
* using the unicast or multicast socket
*/
class OutgoingPacketHandler implements Runnable {
Thread t=null;
ObjectOutputStream out;
byte[] buf;
DatagramPacket packet;
IpAddress dest;
public void run() {
Message msg;
while(outgoing_queue != null && outgoing_packet_handler != null) {
try {
msg=(Message)outgoing_queue.remove();
send(msg);
}
catch(QueueClosedException closed_ex) {
if(Trace.trace) Trace.info("UDP.OutgoingPacketHandler.run()", "packet_handler thread terminating");
break;
}
catch(Throwable t) {
Trace.error("UDP.OutgoingPacketHandler.run()", "exception sending packet: " + t);
}
msg=null; // let's give the poor garbage collector a hand...
}
}
void start() {
if(t == null) {
t=new Thread(this, "UDP.OutgoingPacketHandler thread");
t.setDaemon(true);
t.start();
}
}
void stop() {
if(outgoing_queue != null)
outgoing_queue.close(false); // should terminate the packet_handler thread too
t=null;
outgoing_queue=null;
}
}
}
|
// $Id: UDP.java,v 1.107 2005/10/03 13:31:33 belaban Exp $
package org.jgroups.protocols;
import org.jgroups.*;
import org.jgroups.stack.IpAddress;
import org.jgroups.util.BoundedList;
import org.jgroups.util.Util;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.*;
import java.util.*;
/**
* IP multicast transport based on UDP. Messages to the group (msg.dest == null) will
* be multicast (to all group members), whereas point-to-point messages
* (msg.dest != null) will be unicast to a single member. Uses a multicast and
* a unicast socket.<p>
* The following properties are read by the UDP protocol:
* <ul>
* <li> param mcast_addr - the multicast address to use; default is 228.8.8.8.
* <li> param mcast_port - (int) the port that the multicast is sent on; default is 7600
* <li> param ip_mcast - (boolean) flag whether to use IP multicast; default is true.
* <li> param ip_ttl - the default time-to-live for multicast packets sent out on this
* socket; default is 32.
* <li> param use_packet_handler - boolean, defaults to false.
* If set, the mcast and ucast receiver threads just put
* the datagram's payload (a byte buffer) into a queue, from where a separate thread
* will dequeue and handle them (unmarshal and pass up). This frees the receiver
* threads from having to do message unmarshalling; this time can now be spent
* receiving packets. If you have lots of retransmissions because of network
* input buffer overflow, consider setting this property to true.
* </ul>
* @author Bela Ban
*/
public class UDP extends TP implements Runnable {
/** Socket used for
* <ol>
* <li>sending unicast packets and
* <li>receiving unicast packets
* </ol>
* The address of this socket will be our local address (<tt>local_addr</tt>) */
DatagramSocket sock=null;
/**
* BoundedList<Integer> of the last 100 ports used. This is to avoid reusing a port for DatagramSocket
*/
private static BoundedList last_ports_used=null;
/** Maintain a list of local ports opened by DatagramSocket. If this is 0, this option is turned off.
* If bind_port is > 0, then this option will be ignored */
int num_last_ports=100;
/** IP multicast socket for <em>receiving</em> multicast packets */
MulticastSocket mcast_recv_sock=null;
/** IP multicast socket for <em>sending</em> multicast packets */
MulticastSocket mcast_send_sock=null;
/** If we have multiple mcast send sockets, e.g. send_interfaces or send_on_all_interfaces enabled */
MulticastSocket[] mcast_send_sockets=null;
/**
* Traffic class for sending unicast and multicast datagrams.
* Valid values are (check {@link #DatagramSocket.setTrafficClass(int)} for details):
* <UL>
* <LI><CODE>IPTOS_LOWCOST (0x02)</CODE>, <b>decimal 2</b></LI>
* <LI><CODE>IPTOS_RELIABILITY (0x04)</CODE><, <b>decimal 4</b>/LI>
* <LI><CODE>IPTOS_THROUGHPUT (0x08)</CODE>, <b>decimal 8</b></LI>
* <LI><CODE>IPTOS_LOWDELAY (0x10)</CODE>, <b>decimal</b> 16</LI>
* </UL>
*/
int tos=0; // valid values: 2, 4, 8, 16
/** The multicast address (mcast address and port) this member uses */
IpAddress mcast_addr=null;
/** The multicast address used for sending and receiving packets */
String mcast_addr_name="228.8.8.8";
/** The multicast port used for sending and receiving packets */
int mcast_port=7600;
/** The multicast receiver thread */
Thread mcast_receiver=null;
/** The unicast receiver thread */
UcastReceiver ucast_receiver=null;
/** Whether to enable IP multicasting. If false, multiple unicast datagram
* packets are sent rather than one multicast packet */
boolean ip_mcast=true;
/** The time-to-live (TTL) for multicast datagram packets */
int ip_ttl=64;
/** Send buffer size of the multicast datagram socket */
int mcast_send_buf_size=32000;
/** Receive buffer size of the multicast datagram socket */
int mcast_recv_buf_size=64000;
/** Send buffer size of the unicast datagram socket */
int ucast_send_buf_size=32000;
/** Receive buffer size of the unicast datagram socket */
int ucast_recv_buf_size=64000;
// private boolean null_src_addresses=true;
/**
* Creates the UDP protocol, and initializes the
* state variables, does however not start any sockets or threads.
*/
public UDP() {
}
/**
* Setup the Protocol instance acording to the configuration string.
* The following properties are read by the UDP protocol:
* <ul>
* <li> param mcast_addr - the multicast address to use default is 228.8.8.8
* <li> param mcast_port - (int) the port that the multicast is sent on default is 7600
* <li> param ip_mcast - (boolean) flag whether to use IP multicast - default is true
* <li> param ip_ttl - Set the default time-to-live for multicast packets sent out on this socket. default is 32
* </ul>
* @return true if no other properties are left.
* false if the properties still have data in them, ie ,
* properties are left over and not handled by the protocol stack
*/
public boolean setProperties(Properties props) {
String str;
super.setProperties(props);
str=props.getProperty("num_last_ports");
if(str != null) {
num_last_ports=Integer.parseInt(str);
props.remove("num_last_ports");
}
str=props.getProperty("mcast_addr");
if(str != null) {
mcast_addr_name=str;
props.remove("mcast_addr");
}
str=System.getProperty("jboss.partition.udpGroup");
if(str != null)
mcast_addr_name=str;
str=props.getProperty("mcast_port");
if(str != null) {
mcast_port=Integer.parseInt(str);
props.remove("mcast_port");
}
str=System.getProperty("jboss.partition.udpPort");
if(str != null)
mcast_port=Integer.parseInt(str);
str=props.getProperty("ip_mcast");
if(str != null) {
ip_mcast=Boolean.valueOf(str).booleanValue();
props.remove("ip_mcast");
}
str=props.getProperty("ip_ttl");
if(str != null) {
ip_ttl=Integer.parseInt(str);
props.remove("ip_ttl");
}
str=props.getProperty("tos");
if(str != null) {
tos=Integer.parseInt(str);
props.remove("tos");
}
str=props.getProperty("mcast_send_buf_size");
if(str != null) {
mcast_send_buf_size=Integer.parseInt(str);
props.remove("mcast_send_buf_size");
}
str=props.getProperty("mcast_recv_buf_size");
if(str != null) {
mcast_recv_buf_size=Integer.parseInt(str);
props.remove("mcast_recv_buf_size");
}
str=props.getProperty("ucast_send_buf_size");
if(str != null) {
ucast_send_buf_size=Integer.parseInt(str);
props.remove("ucast_send_buf_size");
}
str=props.getProperty("ucast_recv_buf_size");
if(str != null) {
ucast_recv_buf_size=Integer.parseInt(str);
props.remove("ucast_recv_buf_size");
}
str=props.getProperty("null_src_addresses");
if(str != null) {
// null_src_addresses=Boolean.valueOf(str).booleanValue();
props.remove("null_src_addresses");
log.error("null_src_addresses has been deprecated, property will be ignored");
}
if(props.size() > 0) {
log.error("the following properties are not recognized: " + props);
return false;
}
return true;
}
private BoundedList getLastPortsUsed() {
if(last_ports_used == null)
last_ports_used=new BoundedList(num_last_ports);
return last_ports_used;
}
public void run() {
DatagramPacket packet;
byte receive_buf[]=new byte[65535];
int offset, len, sender_port;
byte[] data;
InetAddress sender_addr;
Address sender;
// moved out of loop to avoid excessive object creations (bela March 8 2001)
packet=new DatagramPacket(receive_buf, receive_buf.length);
while(mcast_receiver != null && mcast_recv_sock != null) {
try {
packet.setData(receive_buf, 0, receive_buf.length);
mcast_recv_sock.receive(packet);
sender_addr=packet.getAddress();
sender_port=packet.getPort();
offset=packet.getOffset();
len=packet.getLength();
data=packet.getData();
sender=new IpAddress(sender_addr, sender_port);
if(len > receive_buf.length) {
if(log.isErrorEnabled())
log.error("size of the received packet (" + len + ") is bigger than " +
"allocated buffer (" + receive_buf.length + "): will not be able to handle packet. " +
"Use the FRAG protocol and make its frag_size lower than " + receive_buf.length);
}
receive(mcast_addr, sender, data, offset, len);
}
catch(SocketException sock_ex) {
if(trace) log.trace("multicast socket is closed, exception=" + sock_ex);
break;
}
catch(InterruptedIOException io_ex) { // thread was interrupted
}
catch(Throwable ex) {
if(log.isErrorEnabled())
log.error("failure in multicast receive()", ex);
Util.sleep(100); // so we don't get into 100% cpu spinning (should NEVER happen !)
}
}
if(log.isDebugEnabled()) log.debug("multicast thread terminated");
}
public String getInfo() {
StringBuffer sb=new StringBuffer();
sb.append("group_addr=").append(mcast_addr_name).append(':').append(mcast_port).append("\n");
return sb.toString();
}
public void sendToAllMembers(byte[] data, int offset, int length) throws Exception {
if(ip_mcast && mcast_addr != null) {
_send(mcast_addr.getIpAddress(), mcast_addr.getPort(), true, data, offset, length);
}
else {
ArrayList mbrs=new ArrayList(members);
IpAddress mbr;
for(Iterator it=mbrs.iterator(); it.hasNext();) {
mbr=(IpAddress)it.next();
_send(mbr.getIpAddress(), mbr.getPort(), false, data, offset, length);
}
}
}
public void sendToSingleMember(Address dest, byte[] data, int offset, int length) throws Exception {
_send(((IpAddress)dest).getIpAddress(), ((IpAddress)dest).getPort(), false, data, offset, length);
}
public void postUnmarshalling(Message msg, Address dest, Address src, boolean multicast) {
msg.setDest(dest);
}
public void postUnmarshallingList(Message msg, Address dest, boolean multicast) {
msg.setDest(dest);
}
private void _send(InetAddress dest, int port, boolean mcast, byte[] data, int offset, int length) throws Exception {
DatagramPacket packet=new DatagramPacket(data, offset, length, dest, port);
try {
if(mcast) {
if(mcast_send_sock != null) {
mcast_send_sock.send(packet);
}
else {
if(mcast_send_sockets != null) {
MulticastSocket s;
for(int i=0; i < mcast_send_sockets.length; i++) {
s=mcast_send_sockets[i];
try {
s.send(packet);
}
catch(Exception e) {
log.error("failed sending packet on socket " + s);
}
}
}
else {
throw new Exception("both mcast_send_sock and mcast_send_sockets are null");
}
}
}
else {
if(sock != null)
sock.send(packet);
}
}
catch(Exception ex) {
Exception new_ex=new Exception("dest=" + dest + ":" + port + " (" + length + " bytes)", ex);
throw new_ex;
}
}
public String getName() {
return "UDP";
}
/**
* Creates the unicast and multicast sockets and starts the unicast and multicast receiver threads
*/
public void start() throws Exception {
if(log.isDebugEnabled()) log.debug("creating sockets and starting threads");
createSockets();
super.start();
startThreads();
}
public void stop() {
if(log.isDebugEnabled()) log.debug("closing sockets and stopping threads");
stopThreads(); // will close sockets, closeSockets() is not really needed anymore, but...
closeSockets(); // ... we'll leave it in there for now (doesn't do anything if already closed)
super.stop();
}
/**
* Create UDP sender and receiver sockets. Currently there are 2 sockets
* (sending and receiving). This is due to Linux's non-BSD compatibility
* in the JDK port (see DESIGN).
*/
private void createSockets() throws Exception {
InetAddress tmp_addr;
// bind_addr not set, try to assign one by default. This is needed on Windows
// changed by bela Feb 12 2003: by default multicast sockets will be bound to all network interfaces
// CHANGED *BACK* by bela March 13 2003: binding to all interfaces did not result in a correct
// local_addr. As a matter of fact, comparison between e.g. 0.0.0.0:1234 (on hostA) and
// 0.0.0.0:1.2.3.4 (on hostB) would fail !
// if(bind_addr == null) {
// InetAddress[] interfaces=InetAddress.getAllByName(InetAddress.getLocalHost().getHostAddress());
// if(interfaces != null && interfaces.length > 0)
// bind_addr=interfaces[0];
if(bind_addr == null) {
bind_addr=Util.getFirstNonLoopbackAddress();
}
if(bind_addr == null)
bind_addr=InetAddress.getLocalHost();
if(bind_addr != null)
if(log.isInfoEnabled()) log.info("sockets will use interface " + bind_addr.getHostAddress());
// 2. Create socket for receiving unicast UDP packets. The address and port
// of this socket will be our local address (local_addr)
if(bind_port > 0) {
sock=createDatagramSocketWithBindPort();
}
else {
sock=createEphemeralDatagramSocket();
}
if(tos > 0) {
try {
sock.setTrafficClass(tos);
}
catch(SocketException e) {
log.warn("traffic class of " + tos + " could not be set, will be ignored", e);
}
}
if(sock == null)
throw new Exception("UDP.createSocket(): sock is null");
local_addr=new IpAddress(sock.getLocalAddress(), sock.getLocalPort());
if(additional_data != null)
((IpAddress)local_addr).setAdditionalData(additional_data);
// 3. Create socket for receiving IP multicast packets
if(ip_mcast) {
// 3a. Create mcast receiver socket
mcast_recv_sock=new MulticastSocket(mcast_port);
mcast_recv_sock.setTimeToLive(ip_ttl);
tmp_addr=InetAddress.getByName(mcast_addr_name);
mcast_addr=new IpAddress(tmp_addr, mcast_port);
if(receive_on_all_interfaces || (receive_interfaces != null && receive_interfaces.size() > 0)) {
List interfaces;
if(receive_interfaces != null)
interfaces=receive_interfaces;
else
interfaces=Util.getAllAvailableInterfaces();
bindToInterfaces(interfaces, mcast_recv_sock, mcast_addr.getIpAddress());
}
else {
if(bind_addr != null)
mcast_recv_sock.setInterface(bind_addr);
mcast_recv_sock.joinGroup(tmp_addr);
}
// 3b. Create mcast sender socket
if(send_on_all_interfaces || (send_interfaces != null && send_interfaces.size() > 0)) {
List interfaces;
NetworkInterface intf;
if(send_interfaces != null)
interfaces=send_interfaces;
else
interfaces=Util.getAllAvailableInterfaces();
mcast_send_sockets=new MulticastSocket[interfaces.size()];
int index=0;
for(Iterator it=interfaces.iterator(); it.hasNext();) {
intf=(NetworkInterface)it.next();
mcast_send_sockets[index]=new MulticastSocket();
mcast_send_sockets[index].setNetworkInterface(intf);
mcast_send_sockets[index].setTimeToLive(ip_ttl);
if(tos > 0) {
try {
mcast_send_sockets[index].setTrafficClass(tos);
}
catch(SocketException e) {
log.warn("traffic class of " + tos + " could not be set, will be ignored", e);
}
}
index++;
}
}
else {
mcast_send_sock=new MulticastSocket();
mcast_send_sock.setTimeToLive(ip_ttl);
if(bind_addr != null)
mcast_send_sock.setInterface(bind_addr);
if(tos > 0) {
try {
mcast_send_sock.setTrafficClass(tos); // high throughput
}
catch(SocketException e) {
log.warn("traffic class of " + tos + " could not be set, will be ignored", e);
}
}
}
}
setBufferSizes();
if(log.isInfoEnabled()) log.info("socket information:\n" + dumpSocketInfo());
}
// private void bindToAllInterfaces(MulticastSocket s, InetAddress mcastAddr) throws IOException {
// SocketAddress tmp_mcast_addr=new InetSocketAddress(mcastAddr, mcast_port);
// Enumeration en=NetworkInterface.getNetworkInterfaces();
// while(en.hasMoreElements()) {
// NetworkInterface i=(NetworkInterface)en.nextElement();
// for(Enumeration en2=i.getInetAddresses(); en2.hasMoreElements();) {
// InetAddress addr=(InetAddress)en2.nextElement();
// // if(addr.isLoopbackAddress())
// // continue;
// s.joinGroup(tmp_mcast_addr, i);
// if(trace)
// log.trace("joined " + tmp_mcast_addr + " on interface " + i.getName() + " (" + addr + ")");
// break;
/**
*
* @param interfaces List<NetworkInterface>. Guaranteed to have no duplicates
* @param s
* @param mcastAddr
* @throws IOException
*/
private void bindToInterfaces(List interfaces, MulticastSocket s, InetAddress mcastAddr) throws IOException {
SocketAddress tmp_mcast_addr=new InetSocketAddress(mcastAddr, mcast_port);
for(Iterator it=interfaces.iterator(); it.hasNext();) {
NetworkInterface i=(NetworkInterface)it.next();
for(Enumeration en2=i.getInetAddresses(); en2.hasMoreElements();) {
InetAddress addr=(InetAddress)en2.nextElement();
s.joinGroup(tmp_mcast_addr, i);
if(trace)
log.trace("joined " + tmp_mcast_addr + " on interface " + i.getName() + " (" + addr + ")");
break;
}
}
}
/** Creates a DatagramSocket with a random port. Because in certain operating systems, ports are reused,
* we keep a list of the n last used ports, and avoid port reuse */
private DatagramSocket createEphemeralDatagramSocket() throws SocketException {
DatagramSocket tmp;
int localPort=0;
while(true) {
tmp=new DatagramSocket(localPort, bind_addr); // first time localPort is 0
if(num_last_ports <= 0)
break;
localPort=tmp.getLocalPort();
if(getLastPortsUsed().contains(new Integer(localPort))) {
if(log.isDebugEnabled())
log.debug("local port " + localPort + " already seen in this session; will try to get other port");
try {tmp.close();} catch(Throwable e) {}
localPort++;
}
else {
getLastPortsUsed().add(new Integer(localPort));
break;
}
}
return tmp;
}
/**
* Creates a DatagramSocket when bind_port > 0. Attempts to allocate the socket with port == bind_port, and
* increments until it finds a valid port, or until port_range has been exceeded
* @return DatagramSocket The newly created socket
* @throws Exception
*/
private DatagramSocket createDatagramSocketWithBindPort() throws Exception {
DatagramSocket tmp=null;
// 27-6-2003 bgooren, find available port in range (start_port, start_port+port_range)
int rcv_port=bind_port, max_port=bind_port + port_range;
while(rcv_port <= max_port) {
try {
tmp=new DatagramSocket(rcv_port, bind_addr);
break;
}
catch(SocketException bind_ex) { // Cannot listen on this port
rcv_port++;
}
catch(SecurityException sec_ex) { // Not allowed to listen on this port
rcv_port++;
}
// Cannot listen at all, throw an Exception
if(rcv_port >= max_port + 1) { // +1 due to the increment above
throw new Exception("UDP.createSockets(): cannot create a socket on any port in range " +
bind_port + '-' + (bind_port + port_range));
}
}
return tmp;
}
private String dumpSocketInfo() throws Exception {
StringBuffer sb=new StringBuffer(128);
sb.append("local_addr=").append(local_addr);
sb.append(", mcast_addr=").append(mcast_addr);
sb.append(", bind_addr=").append(bind_addr);
sb.append(", ttl=").append(ip_ttl);
if(sock != null) {
sb.append("\nsock: bound to ");
sb.append(sock.getLocalAddress().getHostAddress()).append(':').append(sock.getLocalPort());
sb.append(", receive buffer size=").append(sock.getReceiveBufferSize());
sb.append(", send buffer size=").append(sock.getSendBufferSize());
}
if(mcast_recv_sock != null) {
sb.append("\nmcast_recv_sock: bound to ");
sb.append(mcast_recv_sock.getInterface().getHostAddress()).append(':').append(mcast_recv_sock.getLocalPort());
sb.append(", send buffer size=").append(mcast_recv_sock.getSendBufferSize());
sb.append(", receive buffer size=").append(mcast_recv_sock.getReceiveBufferSize());
}
if(mcast_send_sock != null) {
sb.append("\nmcast_send_sock: bound to ");
sb.append(mcast_send_sock.getInterface().getHostAddress()).append(':').append(mcast_send_sock.getLocalPort());
sb.append(", send buffer size=").append(mcast_send_sock.getSendBufferSize());
sb.append(", receive buffer size=").append(mcast_send_sock.getReceiveBufferSize());
}
if(mcast_send_sockets != null) {
sb.append("\n").append(mcast_send_sockets.length).append(" mcast send sockets:\n");
MulticastSocket s;
for(int i=0; i < mcast_send_sockets.length; i++) {
s=mcast_send_sockets[i];
sb.append(s.getInterface().getHostAddress()).append(':').append(s.getLocalPort());
sb.append(", send buffer size=").append(s.getSendBufferSize());
sb.append(", receive buffer size=").append(s.getReceiveBufferSize()).append("\n");
}
}
return sb.toString();
}
void setBufferSizes() {
if(sock != null)
setBufferSize(sock, ucast_send_buf_size, ucast_recv_buf_size);
if(mcast_recv_sock != null)
setBufferSize(mcast_recv_sock, mcast_send_buf_size, mcast_recv_buf_size);
if(mcast_send_sock != null)
setBufferSize(mcast_send_sock, mcast_send_buf_size, mcast_recv_buf_size);
if(mcast_send_sockets != null) {
for(int i=0; i < mcast_send_sockets.length; i++) {
setBufferSize(mcast_send_sockets[i], mcast_send_buf_size, mcast_recv_buf_size);
}
}
}
private void setBufferSize(DatagramSocket sock, int send_buf_size, int recv_buf_size) {
try {
sock.setSendBufferSize(send_buf_size);
}
catch(Throwable ex) {
if(warn) log.warn("failed setting send buffer size of " + send_buf_size + " in " + sock + ": " + ex);
}
try {
sock.setReceiveBufferSize(recv_buf_size);
}
catch(Throwable ex) {
if(warn) log.warn("failed setting receive buffer size of " + recv_buf_size + " in " + sock + ": " + ex);
}
}
/**
* Closed UDP unicast and multicast sockets
*/
void closeSockets() {
// 1. Close multicast socket
closeMulticastSocket();
// 2. Close socket
closeSocket();
}
void closeMulticastSocket() {
if(mcast_recv_sock != null) {
try {
if(mcast_addr != null) {
mcast_recv_sock.leaveGroup(mcast_addr.getIpAddress());
}
mcast_recv_sock.close(); // this will cause the mcast receiver thread to break out of its loop
mcast_recv_sock=null;
if(log.isDebugEnabled()) log.debug("multicast receive socket closed");
}
catch(IOException ex) {
}
mcast_addr=null;
}
if(mcast_send_sock != null) {
mcast_send_sock.close();
mcast_send_sock=null;
if(log.isDebugEnabled()) log.debug("multicast send socket closed");
}
if(mcast_send_sockets != null) {
MulticastSocket s;
for(int i=0; i < mcast_send_sockets.length; i++) {
s=mcast_send_sockets[i];
s.close();
if(log.isDebugEnabled()) log.debug("multicast send socket " + s + " closed");
}
mcast_send_sockets=null;
}
}
private void closeSocket() {
if(sock != null) {
sock.close();
sock=null;
if(log.isDebugEnabled()) log.debug("socket closed");
}
}
/**
* Starts the unicast and multicast receiver threads
*/
void startThreads() throws Exception {
if(ucast_receiver == null) {
//start the listener thread of the ucast_recv_sock
ucast_receiver=new UcastReceiver();
ucast_receiver.start();
if(log.isDebugEnabled()) log.debug("created unicast receiver thread");
}
if(ip_mcast) {
if(mcast_receiver != null) {
if(mcast_receiver.isAlive()) {
if(log.isDebugEnabled()) log.debug("did not create new multicastreceiver thread as existing " +
"multicast receiver thread is still running");
}
else
mcast_receiver=null; // will be created just below...
}
if(mcast_receiver == null) {
mcast_receiver=new Thread(this, "UDP mcast receiver");
mcast_receiver.setPriority(Thread.MAX_PRIORITY); // needed ????
mcast_receiver.setDaemon(true);
mcast_receiver.start();
}
}
}
/**
* Stops unicast and multicast receiver threads
*/
void stopThreads() {
Thread tmp;
// 1. Stop the multicast receiver thread
if(mcast_receiver != null) {
if(mcast_receiver.isAlive()) {
tmp=mcast_receiver;
mcast_receiver=null;
closeMulticastSocket(); // will cause the multicast thread to terminate
tmp.interrupt();
try {
tmp.join(100);
}
catch(Exception e) {
}
tmp=null;
}
mcast_receiver=null;
}
// 2. Stop the unicast receiver thread
if(ucast_receiver != null) {
ucast_receiver.stop();
ucast_receiver=null;
}
}
protected void handleConfigEvent(HashMap map) {
super.handleConfigEvent(map);
if(map == null) return;
if(map.containsKey("send_buf_size")) {
mcast_send_buf_size=((Integer)map.get("send_buf_size")).intValue();
ucast_send_buf_size=mcast_send_buf_size;
}
if(map.containsKey("recv_buf_size")) {
mcast_recv_buf_size=((Integer)map.get("recv_buf_size")).intValue();
ucast_recv_buf_size=mcast_recv_buf_size;
}
setBufferSizes();
}
// private void nullAddresses(Message msg, IpAddress dest, IpAddress src) {
// if(src != null) {
// if(null_src_addresses)
// msg.setSrc(new IpAddress(src.getPort(), false)); // null the host part, leave the port
// if(src.getAdditionalData() != null)
// ((IpAddress)msg.getSrc()).setAdditionalData(src.getAdditionalData());
// else if(dest != null && !dest.isMulticastAddress()) { // unicast
// msg.setSrc(null);
// private void setAddresses(Message msg, Address dest) {
// msg.setDest(dest);
// // set the source address if not set
// IpAddress src_addr=(IpAddress)msg.getSrc();
// if(src_addr == null) {
// msg.setSrc(sender);
// else {
// byte[] tmp_additional_data=src_addr.getAdditionalData();
// if(src_addr.getIpAddress() == null) {
// IpAddress tmp=new IpAddress(sender.getIpAddress(), src_addr.getPort());
// msg.setSrc(tmp);
// if(tmp_additional_data != null)
// ((IpAddress)msg.getSrc()).setAdditionalData(tmp_additional_data);
public class UcastReceiver implements Runnable {
boolean running=true;
Thread thread=null;
public void start() {
if(thread == null) {
thread=new Thread(this, "UDP.UcastReceiverThread");
thread.setDaemon(true);
running=true;
thread.start();
}
}
public void stop() {
Thread tmp;
if(thread != null && thread.isAlive()) {
running=false;
tmp=thread;
thread=null;
closeSocket(); // this will cause the thread to break out of its loop
tmp.interrupt();
tmp=null;
}
thread=null;
}
public void run() {
DatagramPacket packet;
byte receive_buf[]=new byte[65535];
int offset, len;
byte[] data;
InetAddress sender_addr;
int sender_port;
Address sender;
// moved out of loop to avoid excessive object creations (bela March 8 2001)
packet=new DatagramPacket(receive_buf, receive_buf.length);
while(running && thread != null && sock != null) {
try {
packet.setData(receive_buf, 0, receive_buf.length);
sock.receive(packet);
sender_addr=packet.getAddress();
sender_port=packet.getPort();
offset=packet.getOffset();
len=packet.getLength();
data=packet.getData();
sender=new IpAddress(sender_addr, sender_port);
if(len > receive_buf.length) {
if(log.isErrorEnabled())
log.error("size of the received packet (" + len + ") is bigger than allocated buffer (" +
receive_buf.length + "): will not be able to handle packet. " +
"Use the FRAG protocol and make its frag_size lower than " + receive_buf.length);
}
receive(local_addr, sender, data, offset, len);
}
catch(SocketException sock_ex) {
if(log.isDebugEnabled()) log.debug("unicast receiver socket is closed, exception=" + sock_ex);
break;
}
catch(InterruptedIOException io_ex) { // thread was interrupted
}
catch(Throwable ex) {
if(log.isErrorEnabled())
log.error("[" + local_addr + "] failed receiving unicast packet", ex);
Util.sleep(100); // so we don't get into 100% cpu spinning (should NEVER happen !)
}
}
if(log.isDebugEnabled()) log.debug("unicast receiver thread terminated");
}
}
}
|
package org.jgroups.protocols;
import org.jgroups.Global;
import org.jgroups.PhysicalAddress;
import org.jgroups.annotations.DeprecatedProperty;
import org.jgroups.annotations.Property;
import org.jgroups.annotations.ManagedAttribute;
import org.jgroups.stack.IpAddress;
import org.jgroups.util.Util;
import java.io.IOException;
import java.net.*;
import java.util.List;
import java.util.Map;
/**
* IP multicast transport based on UDP. Messages to the group (msg.dest == null)
* will be multicast (to all group members), whereas point-to-point messages
* (msg.dest != null) will be unicast to a single member. Uses a multicast and a
* unicast socket.
* <p>
* The following properties are read by the UDP protocol:
* <ul>
* <li> param mcast_addr - the multicast address to use; default is 228.8.8.8.
* <li> param mcast_port - (int) the port that the multicast is sent on; default
* is 7600
* <li> param ip_mcast - (boolean) flag whether to use IP multicast; default is
* true.
* <li> param ip_ttl - the default time-to-live for multicast packets sent out
* on this socket; default is 32.
* <li> param use_packet_handler - boolean, defaults to false. If set, the mcast
* and ucast receiver threads just put the datagram's payload (a byte buffer)
* into a queue, from where a separate thread will dequeue and handle them
* (unmarshal and pass up). This frees the receiver threads from having to do
* message unmarshalling; this time can now be spent receiving packets. If you
* have lots of retransmissions because of network input buffer overflow,
* consider setting this property to true.
* </ul>
*
* @author Bela Ban
* @version $Id: UDP.java,v 1.210 2009/12/10 13:02:11 belaban Exp $
*/
@DeprecatedProperty(names={"num_last_ports","null_src_addresses", "send_on_all_interfaces", "send_interfaces"})
public class UDP extends TP {
/**
* Traffic class for sending unicast and multicast datagrams. Valid values
* are (check {@link DatagramSocket#setTrafficClass(int)} ); for details):
* <UL>
* <LI><CODE>IPTOS_LOWCOST (0x02)</CODE>, <b>decimal 2</b></LI>
* <LI><CODE>IPTOS_RELIABILITY (0x04)</CODE><, <b>decimal 4</b>/LI>
* <LI><CODE>IPTOS_THROUGHPUT (0x08)</CODE>, <b>decimal 8</b></LI>
* <LI><CODE>IPTOS_LOWDELAY (0x10)</CODE>, <b>decimal</b> 16</LI>
* </UL>
*/
@ManagedAttribute(description="Traffic class for sending unicast and multicast datagrams. Default is 8")
@Property(description="Traffic class for sending unicast and multicast datagrams. Default is 8")
private int tos=8; // valid values: 2, 4, 8 (default), 16
@ManagedAttribute
@Property(name="mcast_addr", description="The multicast address used for sending and receiving packets. Default is 228.8.8.8",
defaultValueIPv4="228.8.8.8", defaultValueIPv6="ff0e::8:8:8",
systemProperty=Global.UDP_MCAST_ADDR)
private InetAddress mcast_group_addr=null;
@ManagedAttribute
@Property(description="The multicast port used for sending and receiving packets. Default is 7600",
systemProperty=Global.UDP_MCAST_PORT)
private int mcast_port=7600;
@ManagedAttribute
@Property(description="Multicast toggle. If false multiple unicast datagrams are sent instead of one multicast. Default is true")
private boolean ip_mcast=true;
@ManagedAttribute
@Property(description="The time-to-live (TTL) for multicast datagram packets. Default is 8",systemProperty=Global.UDP_IP_TTL)
private int ip_ttl=8;
@ManagedAttribute
@Property(description="Send buffer size of the multicast datagram socket. Default is 100'000 bytes")
private int mcast_send_buf_size=100000;
@ManagedAttribute
@Property(description="Receive buffer size of the multicast datagram socket. Default is 500'000 bytes")
private int mcast_recv_buf_size=500000;
@ManagedAttribute
@Property(description="Send buffer size of the unicast datagram socket. Default is 100'000 bytes")
private int ucast_send_buf_size=100000;
@ManagedAttribute
@Property(description="Receive buffer size of the unicast datagram socket. Default is 64'000 bytes")
private int ucast_recv_buf_size=64000;
/** The multicast address (mcast address and port) this member uses */
private IpAddress mcast_addr=null;
/**
* Socket used for
* <ol>
* <li>sending unicast and multicast packets and
* <li>receiving unicast packets
* </ol>
* The address of this socket will be our local address (<tt>local_addr</tt>)
*/
private DatagramSocket sock=null;
/** IP multicast socket for <em>receiving</em> multicast packets */
private MulticastSocket mcast_sock=null;
/** Runnable to receive multicast packets */
private PacketReceiver mcast_receiver=null;
/** Runnable to receive unicast packets */
private PacketReceiver ucast_receiver=null;
// private boolean null_src_addresses=true;
/**
* Creates the UDP protocol, and initializes the state variables, does however not start any sockets or threads.
*/
public UDP() {
}
public void setMulticastAddress(InetAddress addr) {this.mcast_group_addr=addr;}
public InetAddress getMulticastAddress() {return mcast_group_addr;}
public int getMulticastPort() {return mcast_port;}
public void setMulticastPort(int mcast_port) {this.mcast_port=mcast_port;}
public void setMcastPort(int mcast_port) {this.mcast_port=mcast_port;}
public String getInfo() {
StringBuilder sb=new StringBuilder();
sb.append("group_addr=").append(mcast_group_addr.getHostName()).append(':').append(mcast_port).append("\n");
return sb.toString();
}
public void sendMulticast(byte[] data, int offset, int length) throws Exception {
if(ip_mcast && mcast_addr != null) {
_send(mcast_addr.getIpAddress(), mcast_addr.getPort(), true, data, offset, length);
}
else {
sendToAllPhysicalAddresses(data, offset, length);
// List<Address> mbrs;
// synchronized(members) {
// mbrs=new ArrayList<Address>(members);
// for(Address mbr: mbrs) {
// Address physical_dest=getPhysicalAddressFromCache(mbr);
// if(physical_dest == null) {
// if(log.isWarnEnabled())
// log.warn("no physical address for " + mbr + ", dropping message");
// if(System.currentTimeMillis() - last_who_has_request >= 5000) { // send only every 5 secs max
// up_prot.up(new Event(Event.GET_PHYSICAL_ADDRESS, mbr));
// last_who_has_request=System.currentTimeMillis();
// return;
// _send(((IpAddress)physical_dest).getIpAddress(), ((IpAddress)physical_dest).getPort(),
// false, data, offset, length);
}
}
public void sendUnicast(PhysicalAddress dest, byte[] data, int offset, int length) throws Exception {
_send(((IpAddress)dest).getIpAddress(), ((IpAddress)dest).getPort(), false, data, offset, length);
}
private void _send(InetAddress dest, int port, boolean mcast, byte[] data, int offset, int length) throws Exception {
DatagramPacket packet=new DatagramPacket(data, offset, length, dest, port);
try {
if(mcast) {
if(mcast_sock != null && !mcast_sock.isClosed())
mcast_sock.send(packet);
}
else {
if(sock != null && !sock.isClosed())
sock.send(packet);
}
}
catch(Exception ex) {
throw new Exception("dest=" + dest + ":" + port + " (" + length + " bytes)", ex);
}
}
/**
* Creates the unicast and multicast sockets and starts the unicast and multicast receiver threads
*/
public void start() throws Exception {
if(log.isDebugEnabled()) log.debug("creating sockets");
try {
createSockets();
}
catch(Exception ex) {
String tmp="problem creating sockets (bind_addr=" + bind_addr + ", mcast_addr=" + mcast_addr + ")";
throw new Exception(tmp, ex);
}
super.start();
ucast_receiver=new PacketReceiver(sock,
"unicast receiver",
new Runnable() {
public void run() {
closeUnicastSocket();
}
});
if(ip_mcast)
mcast_receiver=new PacketReceiver(mcast_sock,
"multicast receiver",
new Runnable() {
public void run() {
closeMulticastSocket();
}
});
}
public void stop() {
if(log.isDebugEnabled()) log.debug("closing sockets and stopping threads");
stopThreads(); // will close sockets, closeSockets() is not really needed anymore, but...
super.stop();
}
public void destroy() {
super.destroy();
destroySockets();
}
protected void handleConnect() throws Exception {
if(isSingleton()) {
if(connect_count == 0) {
startThreads();
}
super.handleConnect();
}
else
startThreads();
}
protected void handleDisconnect() {
if(isSingleton()) {
super.handleDisconnect();
if(connect_count == 0) {
stopThreads();
}
}
else
stopThreads();
}
/**
* Create UDP sender and receiver sockets. Currently there are 2 sockets
* (sending and receiving). This is due to Linux's non-BSD compatibility
* in the JDK port (see DESIGN).
*/
private void createSockets() throws Exception {
// bind_addr not set, try to assign one by default. This is needed on Windows
// changed by bela Feb 12 2003: by default multicast sockets will be bound to all network interfaces
// CHANGED *BACK* by bela March 13 2003: binding to all interfaces did not result in a correct
// local_addr. As a matter of fact, comparison between e.g. 0.0.0.0:1234 (on hostA) and
// 0.0.0.0:1.2.3.4 (on hostB) would fail !
// if(bind_addr == null) {
// InetAddress[] interfaces=InetAddress.getAllByName(InetAddress.getLocalHost().getHostAddress());
// if(interfaces != null && interfaces.length > 0)
// bind_addr=interfaces[0];
// RA 14 Sep 09: These lines were never called as bind_addr always returned a non-null value
// if(bind_addr == null && !use_local_host) {
// bind_addr=Util.getFirstNonLoopbackAddress();
// if(bind_addr == null)
// bind_addr=InetAddress.getLocalHost();
if(bind_addr == null)
throw new IllegalArgumentException("bind_addr cannot be null") ;
// RA: 16 Sep 09: need to resolve the use of use_local_host
// if(bind_addr != null && !bind_addr.isLoopbackAddress() && use_local_host) {
if(log.isDebugEnabled()) log.debug("sockets will use interface " + bind_addr.getHostAddress());
// 2. Create socket for receiving unicast UDP packets. The address and port
// of this socket will be our local address (local_addr)
if(bind_port > 0) {
sock=createDatagramSocketWithBindPort();
}
else {
sock=createEphemeralDatagramSocket();
}
if(tos > 0) {
try {
sock.setTrafficClass(tos);
}
catch(SocketException e) {
log.warn("traffic class of " + tos + " could not be set, will be ignored: " + e);
}
}
if(sock == null)
throw new Exception("socket is null");
// 3. Create socket for receiving IP multicast packets
if(ip_mcast) {
// cross talking on Windows anyway, so we just do it for Linux. (How about Solaris ?)
if(can_bind_to_mcast_addr)
mcast_sock=Util.createMulticastSocket(mcast_group_addr, mcast_port, log);
else
mcast_sock=new MulticastSocket(mcast_port);
mcast_sock.setTimeToLive(ip_ttl);
mcast_addr=new IpAddress(mcast_group_addr, mcast_port);
// check that we're not using the same mcast address and port as the diagnostics socket
if(enable_diagnostics) {
if(diagnostics_addr != null && diagnostics_addr.equals(mcast_group_addr) ||
diagnostics_port == mcast_port)
throw new IllegalArgumentException("diagnostics_addr / diagnostics_port and mcast_addr / mcast_port " +
"have to be different");
}
if(tos > 0) {
try {
mcast_sock.setTrafficClass(tos);
}
catch(SocketException e) {
log.warn("traffic class of " + tos + " could not be set, will be ignored: " + e);
}
}
if(receive_on_all_interfaces || (receive_interfaces != null && !receive_interfaces.isEmpty())) {
List<NetworkInterface> interfaces;
if(receive_interfaces != null)
interfaces=receive_interfaces;
else
interfaces=Util.getAllAvailableInterfaces();
bindToInterfaces(interfaces, mcast_sock, mcast_addr.getIpAddress());
}
else {
if(bind_addr != null)
mcast_sock.setInterface(bind_addr);
mcast_sock.joinGroup(mcast_group_addr);
}
}
setBufferSizes();
if(log.isDebugEnabled()) log.debug("socket information:\n" + dumpSocketInfo());
}
protected void destroySockets() {
closeMulticastSocket();
closeUnicastSocket();
}
protected IpAddress createLocalAddress() {
return sock != null && !sock.isClosed()? new IpAddress(sock.getLocalAddress(), sock.getLocalPort()) : null;
}
protected PhysicalAddress getPhysicalAddress() {
return createLocalAddress();
}
/**
*
* @param interfaces List<NetworkInterface>. Guaranteed to have no duplicates
* @param s
* @param mcastAddr
* @throws IOException
*/
private void bindToInterfaces(List<NetworkInterface> interfaces,
MulticastSocket s,
InetAddress mcastAddr) {
SocketAddress tmp_mcast_addr=new InetSocketAddress(mcastAddr, mcast_port);
for(NetworkInterface intf:interfaces) {
//[ JGRP-680] - receive_on_all_interfaces requires every NIC to be configured
try {
s.joinGroup(tmp_mcast_addr, intf);
if(log.isTraceEnabled())
log.trace("joined " + tmp_mcast_addr + " on " + intf.getName());
}
catch(IOException e) {
if(log.isWarnEnabled())
log.warn("Could not join " + tmp_mcast_addr + " on interface " + intf.getName());
}
}
}
/** Creates a DatagramSocket with a random port. Because in certain operating systems, ports are reused,
* we keep a list of the n last used ports, and avoid port reuse */
protected DatagramSocket createEphemeralDatagramSocket() throws SocketException {
DatagramSocket tmp;
int localPort=0;
while(true) {
try {
tmp=new DatagramSocket(localPort, bind_addr); // first time localPort is 0
}
catch(SocketException socket_ex) {
// Vladimir May 30th 2007
// special handling for Linux 2.6 kernel which sometimes throws BindException while we probe for a random port
localPort++;
continue;
}
localPort=tmp.getLocalPort();
break;
}
return tmp;
}
/**
* Creates a DatagramSocket when bind_port > 0. Attempts to allocate the socket with port == bind_port, and
* increments until it finds a valid port, or until port_range has been exceeded
* @return DatagramSocket The newly created socket
* @throws Exception
*/
protected DatagramSocket createDatagramSocketWithBindPort() throws Exception {
DatagramSocket tmp=null;
// 27-6-2003 bgooren, find available port in range (start_port, start_port+port_range)
int rcv_port=bind_port, max_port=bind_port + port_range;
while(rcv_port <= max_port) {
try {
tmp=new DatagramSocket(rcv_port, bind_addr);
return tmp;
}
catch(SocketException bind_ex) { // Cannot listen on this port
rcv_port++;
}
catch(SecurityException sec_ex) { // Not allowed to listen on this port
rcv_port++;
}
}
// Cannot listen at all, throw an Exception
if(rcv_port >= max_port + 1) { // +1 due to the increment above
throw new Exception("failed to open a port in range " + bind_port + '-' + max_port);
}
return tmp;
}
private String dumpSocketInfo() throws Exception {
StringBuilder sb=new StringBuilder(128);
sb.append(", mcast_addr=").append(mcast_addr);
sb.append(", bind_addr=").append(bind_addr);
sb.append(", ttl=").append(ip_ttl);
if(sock != null) {
sb.append("\nsock: bound to ");
sb.append(sock.getLocalAddress().getHostAddress()).append(':').append(sock.getLocalPort());
sb.append(", receive buffer size=").append(sock.getReceiveBufferSize());
sb.append(", send buffer size=").append(sock.getSendBufferSize());
}
if(mcast_sock != null) {
sb.append("\nmcast_sock: bound to ");
sb.append(mcast_sock.getInterface().getHostAddress()).append(':').append(mcast_sock.getLocalPort());
sb.append(", send buffer size=").append(mcast_sock.getSendBufferSize());
sb.append(", receive buffer size=").append(mcast_sock.getReceiveBufferSize());
}
return sb.toString();
}
void setBufferSizes() {
if(sock != null)
setBufferSize(sock, ucast_send_buf_size, ucast_recv_buf_size);
if(mcast_sock != null)
setBufferSize(mcast_sock, mcast_send_buf_size, mcast_recv_buf_size);
}
private void setBufferSize(DatagramSocket sock, int send_buf_size, int recv_buf_size) {
try {
sock.setSendBufferSize(send_buf_size);
int actual_size=sock.getSendBufferSize();
if(actual_size < send_buf_size && log.isWarnEnabled()) {
log.warn("send buffer of socket " + sock + " was set to " +
Util.printBytes(send_buf_size) + ", but the OS only allocated " +
Util.printBytes(actual_size) + ". This might lead to performance problems. Please set your " +
"max send buffer in the OS correctly (e.g. net.core.wmem_max on Linux)");
}
}
catch(Throwable ex) {
if(log.isWarnEnabled()) log.warn("failed setting send buffer size of " + send_buf_size + " in " + sock + ": " + ex);
}
try {
sock.setReceiveBufferSize(recv_buf_size);
int actual_size=sock.getReceiveBufferSize();
if(actual_size < recv_buf_size && log.isWarnEnabled()) {
log.warn("receive buffer of socket " + sock + " was set to " +
Util.printBytes(recv_buf_size) + ", but the OS only allocated " +
Util.printBytes(actual_size) + ". This might lead to performance problems. Please set your " +
"max receive buffer in the OS correctly (e.g. net.core.rmem_max on Linux)");
}
}
catch(Throwable ex) {
if(log.isWarnEnabled()) log.warn("failed setting receive buffer size of " + recv_buf_size + " in " + sock + ": " + ex);
}
}
void closeMulticastSocket() {
if(mcast_sock != null) {
try {
if(mcast_addr != null) {
mcast_sock.leaveGroup(mcast_addr.getIpAddress());
}
mcast_sock.close(); // this will cause the mcast receiver thread to break out of its loop
mcast_sock=null;
if(log.isDebugEnabled()) log.debug("multicast socket closed");
}
catch(IOException ex) {
}
mcast_addr=null;
}
}
private void closeUnicastSocket() {
Util.close(sock);
}
/**
* Starts the unicast and multicast receiver threads
*/
void startThreads() throws Exception {
ucast_receiver.start();
if(mcast_receiver != null)
mcast_receiver.start();
}
/**
* Stops unicast and multicast receiver threads
*/
void stopThreads() {
if(mcast_receiver != null)
mcast_receiver.stop();
ucast_receiver.stop();
}
protected void handleConfigEvent(Map<String,Object> map) {
boolean set_buffers=false;
if(map == null) return;
if(map.containsKey("send_buf_size")) {
mcast_send_buf_size=((Integer)map.get("send_buf_size")).intValue();
ucast_send_buf_size=mcast_send_buf_size;
set_buffers=true;
}
if(map.containsKey("recv_buf_size")) {
mcast_recv_buf_size=((Integer)map.get("recv_buf_size")).intValue();
ucast_recv_buf_size=mcast_recv_buf_size;
set_buffers=true;
}
if(set_buffers)
setBufferSizes();
}
public class PacketReceiver implements Runnable {
private Thread thread=null;
private final DatagramSocket receiver_socket;
private final String name;
private final Runnable close_strategy;
public PacketReceiver(DatagramSocket socket, String name, Runnable close_strategy) {
this.receiver_socket=socket;
this.name=name;
this.close_strategy=close_strategy;
}
public synchronized void start() {
if(thread == null || !thread.isAlive()) {
thread=getThreadFactory().newThread(this, name);
thread.start();
if(log.isDebugEnabled())
log.debug("created " + name + " thread ");
}
}
public synchronized void stop() {
try {
close_strategy.run();
}
catch(Exception e1) {
}
finally {
Util.close(receiver_socket); // second line of defense
}
if(thread != null && thread.isAlive()) {
Thread tmp=thread;
thread=null;
tmp.interrupt();
try {
tmp.join(Global.THREAD_SHUTDOWN_WAIT_TIME);
}
catch(InterruptedException e) {
Thread.currentThread().interrupt(); // set interrupt flag again
}
}
thread=null;
}
public void run() {
final byte receive_buf[]=new byte[65535];
final DatagramPacket packet=new DatagramPacket(receive_buf, receive_buf.length);
while(thread != null && Thread.currentThread().equals(thread)) {
try {
receiver_socket.receive(packet);
int len=packet.getLength();
if(len > receive_buf.length) {
if(log.isErrorEnabled())
log.error("size of the received packet (" + len + ") is bigger than allocated buffer (" +
receive_buf.length + "): will not be able to handle packet. " +
"Use the FRAG2 protocol and make its frag_size lower than " + receive_buf.length);
}
receive(new IpAddress(packet.getAddress(), packet.getPort()),
receive_buf,
packet.getOffset(),
len);
}
catch(SocketException sock_ex) {
if(log.isDebugEnabled()) log.debug("receiver socket is closed, exception=" + sock_ex);
break;
}
catch(Throwable ex) {
if(log.isErrorEnabled())
log.error("failed receiving packet", ex);
}
}
if(log.isDebugEnabled()) log.debug(name + " thread terminated");
}
public String toString() {
return receiver_socket != null? receiver_socket.getLocalSocketAddress().toString() : "null";
}
}
}
|
package org.joval.scap.arf;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.util.JAXBSource;
import javax.xml.stream.FactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import jsaf.intf.util.ILoggable;
import org.slf4j.cal10n.LocLogger;
import org.gocil.diagnostics.ActionSequenceType;
import org.gocil.diagnostics.ActionType;
import org.gocil.diagnostics.OcilResultDiagnostics;
import org.gocil.diagnostics.QuestionnaireType;
import org.gocil.diagnostics.QuestionRef;
import org.gocil.diagnostics.QuestionnaireRef;
import org.oasis.catalog.Catalog;
import org.oasis.catalog.Uri;
import org.openscap.sce.results.SceResultsType;
import scap.ai.AssetType;
import scap.ai.ComputingDeviceType;
import scap.ai.Cpe;
import scap.ai.IpAddressType;
import scap.ai.NetworkInterfaceType;
import scap.arf.core.AssetReportCollection;
import scap.arf.core.ReportRequestType;
import scap.arf.core.ReportType;
import scap.arf.core.AssetReportCollection.ExtendedInfos.ExtendedInfo;
import scap.arf.reporting.RelationshipsContainerType;
import scap.arf.reporting.RelationshipType;
import scap.ocil.core.BooleanQuestionResultType;
import scap.ocil.core.ChoiceQuestionResultType;
import scap.ocil.core.ChoiceType;
import scap.ocil.core.ExtensionContainerType;
import scap.ocil.core.NumericQuestionResultType;
import scap.ocil.core.OCILType;
import scap.ocil.core.QuestionResultType;
import scap.ocil.core.QuestionnaireResultType;
import scap.ocil.core.QuestionTestActionType;
import scap.ocil.core.StringQuestionResultType;
import scap.oval.definitions.core.CriteriaType;
import scap.oval.definitions.core.CriterionType;
import scap.oval.definitions.core.DefinitionType;
import scap.oval.definitions.core.ExtendDefinitionType;
import scap.oval.definitions.core.ObjectRefType;
import scap.oval.definitions.core.ObjectType;
import scap.oval.definitions.core.StateRefType;
import scap.oval.definitions.core.StateType;
import scap.oval.definitions.core.TestType;
import scap.oval.results.OvalResults;
import scap.oval.results.SystemType;
import scap.oval.systemcharacteristics.core.InterfaceType;
import scap.oval.systemcharacteristics.core.ItemType;
import scap.oval.systemcharacteristics.core.SystemInfoType;
import scap.xccdf.CheckType;
import scap.xccdf.ComplexCheckType;
import scap.xccdf.RuleResultType;
import scap.xccdf.TestResultType;
import scap.xccdf.XccdfBenchmark;
import org.joval.intf.scap.arf.IReport;
import org.joval.intf.scap.ocil.IChecklist;
import org.joval.intf.scap.oval.IDefinitions;
import org.joval.intf.scap.oval.IResults;
import org.joval.intf.scap.oval.ISystemCharacteristics;
import org.joval.intf.scap.xccdf.SystemEnumeration;
import org.joval.intf.xml.ITransformable;
import org.joval.scap.ScapException;
import org.joval.scap.ScapFactory;
import org.joval.scap.diagnostics.CheckDiagnostics;
import org.joval.scap.diagnostics.RuleDiagnostics;
import org.joval.scap.oval.OvalFactory;
import org.joval.scap.oval.types.Ip4AddressType;
import org.joval.scap.oval.types.Ip6AddressType;
import org.joval.scap.xccdf.Benchmark;
import org.joval.util.JOVALMsg;
import org.joval.xml.DOMTools;
import org.joval.xml.SchemaRegistry;
/**
* A representation of an ARF report collection.
*
* @author David A. Solin
* @version %I% %G%
*/
public class Report implements IReport, ILoggable {
/**
* URI for the SCE results schema.
*/
public static final String SCERES = "http://open-scap.org/page/SCE_result_file";
/**
* URI for the OVAL results schema.
*/
public static final String OVALRES = "http://oval.mitre.org/XMLSchema/oval-results-5";
public static final AssetReportCollection getAssetReportCollection(File f) throws ArfException {
return getAssetReportCollection(new StreamSource(f));
}
public static final AssetReportCollection getAssetReportCollection(InputStream in) throws ArfException {
return getAssetReportCollection(new StreamSource(in));
}
public static final AssetReportCollection getAssetReportCollection(Source src) throws ArfException {
Object rootObj = parse(src);
if (rootObj instanceof AssetReportCollection) {
return (AssetReportCollection)rootObj;
} else {
throw new ArfException(JOVALMsg.getMessage(JOVALMsg.ERROR_ARF_BAD_SOURCE, src.getSystemId()));
}
}
private static final Object parse(InputStream in) throws ArfException {
return parse(new StreamSource(in));
}
private static final Object parse(Source src) throws ArfException {
try {
Unmarshaller unmarshaller = SchemaRegistry.ARF.getJAXBContext().createUnmarshaller();
return unmarshaller.unmarshal(src);
} catch (JAXBException e) {
throw new ArfException(e);
}
}
private static final String CATALOG_ID = "urn:joval:reports:catalog";
private LocLogger logger;
private AssetReportCollection arc;
private HashMap<String, XccdfBenchmark> requests;
private HashMap<String, AssetType> assets;
private HashMap<String, Object> reports;
/**
* Create a report based on an existing AssetReportCollection.
*/
public Report(AssetReportCollection arc) {
this.arc = arc;
logger = JOVALMsg.getLogger();
requests = new HashMap<String, XccdfBenchmark>();
for (ReportRequestType req : arc.getReportRequests().getReportRequest()) {
Object request = req.getContent().getAny();
if (request instanceof XccdfBenchmark) {
requests.put(req.getId(), (XccdfBenchmark)request);
} else {
String type = request == null ? "null" : request.getClass().getName();
logger.warn(JOVALMsg.WARNING_ARF_REQUEST, req.getId(), type);
}
}
assets = new HashMap<String, AssetType>();
for (AssetReportCollection.Assets.Asset asset : arc.getAssets().getAsset()) {
assets.put(asset.getId(), asset.getAsset().getValue());
}
reports = new HashMap<String, Object>();
for (ReportType report : arc.getReports().getReport()) {
reports.put(report.getId(), report.getContent().getAny());
}
}
/**
* Create an empty report.
*/
public Report() {
arc = Factories.core.createAssetReportCollection();
requests = new HashMap<String, XccdfBenchmark>();
assets = new HashMap<String, AssetType>();
reports = new HashMap<String, Object>();
logger = JOVALMsg.getLogger();
}
// Implement IReport
public Collection<String> getAssetIds() {
return assets.keySet();
}
public AssetType getAsset(String assetId) throws NoSuchElementException {
if (assets.containsKey(assetId)) {
return assets.get(assetId);
} else {
throw new NoSuchElementException(assetId);
}
}
public Collection<String> getBenchmarkIds() {
Collection<String> result = new ArrayList<String>();
for (XccdfBenchmark benchmark : requests.values()) {
result.add(benchmark.getBenchmarkId());
}
return result;
}
public XccdfBenchmark getBenchmark(String benchmarkId) throws NoSuchElementException {
for (XccdfBenchmark benchmark : requests.values()) {
if (benchmarkId.equals(benchmark.getBenchmarkId())) {
return benchmark;
}
}
throw new NoSuchElementException(benchmarkId);
}
public TestResultType getTestResult(String assetId, String benchmarkId, String profileId) throws NoSuchElementException {
for (RelationshipType rel : arc.getRelationships().getRelationship()) {
if (rel.getType().equals(Factories.IS_ABOUT)) {
for (String ref : rel.getRef()) {
if (assetId.equals(ref) && reports.containsKey(rel.getSubject())) {
Object report = reports.get(rel.getSubject());
if (report instanceof JAXBElement && ((JAXBElement)report).getValue() instanceof TestResultType) {
TestResultType tr = (TestResultType)((JAXBElement)report).getValue();
if (benchmarkId.equals(tr.getBenchmark().getId()) &&
profileId == null ? !tr.isSetProfile() : profileId.equals(tr.getProfile().getIdref())) {
return tr;
}
}
}
}
}
}
throw new NoSuchElementException(assetId + ":" + benchmarkId + ":" + profileId);
}
public Collection<RuleDiagnostics> getDiagnostics(String assetId, String benchmarkId, String profileId)
throws NoSuchElementException, ScapException {
Map<String, Object> reports = resolveCatalog(assetId);
ArrayList<RuleDiagnostics> results = new ArrayList<RuleDiagnostics>();
for (RuleResultType result : getTestResult(assetId, benchmarkId, profileId).getRuleResult()) {
switch(result.getResult()) {
case NOTAPPLICABLE:
case NOTSELECTED:
case NOTCHECKED:
break;
default:
results.add(getDiagnostics(result, reports));
break;
}
}
return results;
}
public RuleDiagnostics getDiagnostics(String assetId, String benchmarkId, String profileId, String ruleId)
throws NoSuchElementException, ScapException {
Catalog catalog = getCatalog(assetId);
RuleResultType rrt = null;
for (RuleResultType result : getTestResult(assetId, benchmarkId, profileId).getRuleResult()) {
if (result.getIdref().equals(ruleId)) {
return getDiagnostics(result, catalog);
}
}
throw new NoSuchElementException(ruleId);
}
public Catalog getCatalog() throws ArfException, NoSuchElementException {
if (arc.isSetExtendedInfos()) {
for (ExtendedInfo ext : arc.getExtendedInfos().getExtendedInfo()) {
if (CATALOG_ID.equals(ext.getId())) {
Object obj = ext.getAny();
if (obj instanceof JAXBElement) {
obj = ((JAXBElement)obj).getValue();
}
if (obj instanceof Catalog) {
return (Catalog)obj;
} else {
throw new ArfException(JOVALMsg.getMessage(JOVALMsg.ERROR_ARF_CATALOG, obj.getClass().getName()));
}
}
}
}
throw new NoSuchElementException();
}
public Catalog getCatalog(String assetId) throws ArfException, NoSuchElementException {
// Find the IDs of all the reports about the specified asset
HashSet<String> reports = new HashSet<String>();
for (RelationshipType rel : arc.getRelationships().getRelationship()) {
if (rel.getType().equals(Factories.IS_ABOUT)) {
if (rel.getRef().contains(assetId)) {
reports.add(rel.getSubject());
}
}
}
// Create a new catalog limited to the report subset.
Catalog result = Factories.catalog.createCatalog();
for (Object elt : getCatalog().getPublicOrSystemOrUri()) {
Object obj = ((JAXBElement)elt).getValue();
if (obj instanceof Uri) {
Uri uri = (Uri)obj;
if (reports.contains(uri.getName())) {
result.getPublicOrSystemOrUri().add(elt);
}
}
}
return result;
}
public synchronized String addRequest(XccdfBenchmark benchmark) {
String requestId = new StringBuffer("request_").append(Integer.toString(requests.size())).toString();
requests.put(requestId, benchmark);
if (!arc.isSetReportRequests()) {
arc.setReportRequests(Factories.core.createAssetReportCollectionReportRequests());
}
ReportRequestType requestType = Factories.core.createReportRequestType();
requestType.setId(requestId);
ReportRequestType.Content content = Factories.core.createReportRequestTypeContent();
content.setAny(benchmark);
requestType.setContent(content);
arc.getReportRequests().getReportRequest().add(requestType);
return requestId;
}
public synchronized String addAsset(SystemInfoType info, Collection<String> cpes) {
ComputingDeviceType cdt = Factories.asset.createComputingDeviceType();
if (cpes != null) {
for (String cpe : cpes) {
Cpe cpeType = Factories.asset.createCpe();
cpeType.setValue(cpe);
cdt.getCpe().add(cpeType);
}
}
ComputingDeviceType.Hostname hostname = Factories.asset.createComputingDeviceTypeHostname();
hostname.setValue(info.getPrimaryHostName());
cdt.setHostname(hostname);
if (info.isSetInterfaces() && info.getInterfaces().getInterface() != null) {
ComputingDeviceType.Connections connections = Factories.asset.createComputingDeviceTypeConnections();
HashMap<String, NetworkInterfaceType> interfaces = new HashMap<String, NetworkInterfaceType>();
for (InterfaceType intf : info.getInterfaces().getInterface()) {
if (intf.isSetMacAddress()) {
// For interfaces specifying a MAC address, keep iterating so that both IP4 and IP6 address
// information can be added to the same interface.
String macAddress = intf.getMacAddress();
NetworkInterfaceType nit = null;
if (interfaces.containsKey(macAddress)) {
nit = interfaces.get(macAddress);
} else {
nit = Factories.asset.createNetworkInterfaceType();
NetworkInterfaceType.MacAddress mac = Factories.asset.createNetworkInterfaceTypeMacAddress();
mac.setValue(macAddress);
nit.setMacAddress(mac);
interfaces.put(macAddress, nit);
}
if (intf.isSetIpAddress()) {
try {
setIpAddressInfo(nit, intf.getIpAddress());
} catch (IllegalArgumentException e) {
}
}
} else {
// Interfaces where the MAC address is unknown can be added immediately
NetworkInterfaceType nit = Factories.asset.createNetworkInterfaceType();
if (intf.isSetIpAddress()) {
try {
setIpAddressInfo(nit, intf.getIpAddress());
connections.getConnection().add(nit);
} catch (IllegalArgumentException e) {
}
}
}
}
// Add all the interfaces with MAC addresses that were stored in the map
for (NetworkInterfaceType nit : interfaces.values()) {
connections.getConnection().add(nit);
}
cdt.setConnections(connections);
}
String assetId = new StringBuffer("asset_").append(Integer.toString(assets.size())).toString();
assets.put(assetId, cdt);
if (!arc.isSetAssets()) {
arc.setAssets(Factories.core.createAssetReportCollectionAssets());
}
AssetReportCollection.Assets.Asset asset = Factories.core.createAssetReportCollectionAssetsAsset();
asset.setId(assetId);
asset.setAsset(Factories.asset.createComputingDevice(cdt));
arc.getAssets().getAsset().add(asset);
return assetId;
}
public synchronized String addReport(String requestId, String assetId, String ref, Object report)
throws NoSuchElementException, IllegalArgumentException, ArfException {
if (!requests.containsKey(requestId)) {
throw new NoSuchElementException(requestId);
}
if (!assets.containsKey(assetId)) {
throw new NoSuchElementException(assetId);
}
String reportId = new StringBuffer("report_").append(Integer.toString(reports.size())).toString();
reports.put(reportId, report);
if (ref != null && ref.length() > 0) {
Uri uri = Factories.catalog.createUri();
uri.setName(reportId);
if (ref.startsWith("
uri.setUri(ref);
} else {
uri.setUri(new StringBuffer("#").append(ref).toString());
}
getCreateCatalog().getPublicOrSystemOrUri().add(Factories.catalog.createUri(uri));
}
if (!arc.isSetRelationships()) {
arc.setRelationships(Factories.reporting.createRelationshipsContainerTypeRelationships());
}
// Relate to the request
RelationshipType relToRequest = Factories.reporting.createRelationshipType();
relToRequest.setSubject(reportId);
relToRequest.setType(Factories.CREATED_FOR);
relToRequest.getRef().add(requestId);
arc.getRelationships().getRelationship().add(relToRequest);
// Relate to the asset
RelationshipType relToAsset = Factories.reporting.createRelationshipType();
relToAsset.setSubject(reportId);
relToAsset.setType(Factories.IS_ABOUT);
relToAsset.getRef().add(assetId);
arc.getRelationships().getRelationship().add(relToAsset);
if (!arc.isSetReports()) {
arc.setReports(Factories.core.createAssetReportCollectionReports());
}
ReportType rt = Factories.core.createReportType();
rt.setId(reportId);
ReportType.Content content = Factories.core.createReportTypeContent();
content.setAny(report);
rt.setContent(content);
arc.getReports().getReport().add(rt);
return reportId;
}
public void writeXML(File f) throws IOException {
OutputStream out = null;
try {
Marshaller marshaller = SchemaRegistry.ARF.createMarshaller();
out = new FileOutputStream(f);
marshaller.marshal(arc, out);
} catch (JAXBException e) {
logger.warn(JOVALMsg.ERROR_FILE_GENERATE, f.toString());
logger.warn(JOVALMsg.getMessage(JOVALMsg.ERROR_EXCEPTION), e);
} catch (FactoryConfigurationError e) {
logger.warn(JOVALMsg.ERROR_FILE_GENERATE, f.toString());
logger.warn(JOVALMsg.getMessage(JOVALMsg.ERROR_EXCEPTION), e);
} catch (FileNotFoundException e) {
logger.warn(JOVALMsg.ERROR_FILE_GENERATE, f.toString());
logger.warn(JOVALMsg.getMessage(JOVALMsg.ERROR_EXCEPTION), e);
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
logger.warn(JOVALMsg.ERROR_FILE_CLOSE, f.toString());
}
}
}
}
public void writeTransform(Transformer transform, File output) {
try {
transform.transform(getSource(), new StreamResult(output));
} catch (JAXBException e) {
logger.warn(JOVALMsg.getMessage(JOVALMsg.ERROR_EXCEPTION), e);
} catch (TransformerException e) {
logger.warn(JOVALMsg.getMessage(JOVALMsg.ERROR_EXCEPTION), e);
}
}
// Implement ITransformable<AssetReportCollection>
public Source getSource() throws JAXBException {
return new JAXBSource(SchemaRegistry.ARF.getJAXBContext(), getRootObject());
}
public AssetReportCollection getRootObject() {
return arc;
}
public AssetReportCollection copyRootObject() throws Exception {
Unmarshaller unmarshaller = getJAXBContext().createUnmarshaller();
Object rootObj = unmarshaller.unmarshal(new DOMSource(DOMTools.toDocument(this).getDocumentElement()));
if (rootObj instanceof AssetReportCollection) {
return (AssetReportCollection)rootObj;
} else {
throw new ArfException(JOVALMsg.getMessage(JOVALMsg.ERROR_ARF_BAD_SOURCE, toString()));
}
}
public JAXBContext getJAXBContext() throws JAXBException {
return SchemaRegistry.ARF.getJAXBContext();
}
// Implement ILoggable
public void setLogger(LocLogger logger) {
this.logger = logger;
}
public LocLogger getLogger() {
return logger;
}
// Private
private void setIpAddressInfo(NetworkInterfaceType nit, String ipAddressString) {
IpAddressType ip = null;
if (nit.isSetIpAddress()) {
ip = nit.getIpAddress();
} else {
ip = Factories.asset.createIpAddressType();
nit.setIpAddress(ip);
}
IpAddressType subnet = null;
if (nit.isSetSubnetMask()) {
subnet = nit.getSubnetMask();
} else {
subnet = Factories.asset.createIpAddressType();
nit.setSubnetMask(subnet);
}
try {
Ip4AddressType addressType = new Ip4AddressType(ipAddressString);
IpAddressType.IpV4 ip4 = Factories.asset.createIpAddressTypeIpV4();
ip4.setValue(addressType.getIpAddressString());
ip.setIpV4(ip4);
IpAddressType.IpV4 ip4subnet = Factories.asset.createIpAddressTypeIpV4();
ip4subnet.setValue(addressType.getSubnetString());
subnet.setIpV4(ip4subnet);
} catch (IllegalArgumentException e) {
Ip6AddressType addressType = new Ip6AddressType(ipAddressString);
IpAddressType.IpV6 ip6 = Factories.asset.createIpAddressTypeIpV6();
ip6.setValue(addressType.getIpAddressString());
ip.setIpV6(ip6);
IpAddressType.IpV6 ip6subnet = Factories.asset.createIpAddressTypeIpV6();
ip6subnet.setValue(addressType.getSubnetString());
subnet.setIpV6(ip6subnet);
}
}
private Catalog getCreateCatalog() throws ArfException {
try {
return getCatalog();
} catch (NoSuchElementException e) {
// Catalog was not found, so generate it
if (!arc.isSetExtendedInfos()) {
arc.setExtendedInfos(Factories.core.createAssetReportCollectionExtendedInfos());
}
ExtendedInfo info = Factories.core.createAssetReportCollectionExtendedInfosExtendedInfo();
arc.getExtendedInfos().getExtendedInfo().add(info);
Catalog catalog = Factories.catalog.createCatalog();
info.setId(CATALOG_ID);
info.setAny(Factories.catalog.createCatalog(catalog));
return catalog;
}
}
/**
* Get a map, indexed by href, of unmarshalled JAXB elements.
*/
private Map<String, Object> resolveCatalog(String assetId) throws ScapException {
Map<String, Object> resolved = new HashMap<String, Object>();
for (Object obj : getCatalog(assetId).getPublicOrSystemOrUri()) {
obj = ((JAXBElement)obj).getValue();
if (obj instanceof Uri) {
Uri uri = (Uri)obj;
String report_id = uri.getName();
String href = uri.getUri().substring(1);
resolved.put(href, reports.get(report_id));
}
}
return resolved;
}
/**
* Get diagnostics for the specified rule, given a pre-resolved map of reports.
*/
private RuleDiagnostics getDiagnostics(RuleResultType rrt, Map<String, Object> resolved) throws ScapException {
RuleDiagnostics rd = new RuleDiagnostics();
rd.setRuleResult(rrt);
rd.setRuleId(rrt.getIdref());
// Create a collection of checks that apply to the selected rule
Collection<CheckType> checks = new ArrayList<CheckType>();
if (rrt.isSetCheck()) {
checks.add(rrt.getCheck().get(0));
} else if (rrt.isSetComplexCheck()) {
checks.addAll(getChecks(rrt.getComplexCheck()));
}
for (CheckType check : checks) {
CheckDiagnostics cd = new CheckDiagnostics();
String system = check.getSystem();
String href = check.getCheckContentRef().get(0).getHref();
String name = check.getCheckContentRef().get(0).getName();
cd.setCheck(check);
Object report = resolved.get(href);
if (SystemEnumeration.OCIL.namespace().equals(system) && report instanceof OCILType) {
OCILType ocil = (OCILType)report;
setDiagnosticInfo(cd, ScapFactory.createChecklist(ocil), name);
} else if (SystemEnumeration.OVAL.namespace().equals(system) && report instanceof OvalResults) {
OvalResults oval = (OvalResults)report;
if (name == null) {
cd.setDefinitions(oval.getOvalDefinitions().getDefinitions());
cd.setTests(oval.getOvalDefinitions().getTests());
cd.setObjects(oval.getOvalDefinitions().getObjects());
cd.setStates(oval.getOvalDefinitions().getStates());
SystemType st = oval.getResults().getSystem().get(0);
cd.setDefinitionResults(st.getDefinitions());
cd.setTestResults(st.getTests());
cd.setCollectedObjects(st.getOvalSystemCharacteristics().getCollectedObjects());
cd.setItems(st.getOvalSystemCharacteristics().getSystemData());
} else {
cd.setDefinitions(org.joval.scap.oval.Factories.definitions.core.createDefinitionsType());
cd.setDefinitionResults(org.joval.scap.oval.Factories.results.createDefinitionsType());
cd.setTests(org.joval.scap.oval.Factories.definitions.core.createTestsType());
cd.setTestResults(org.joval.scap.oval.Factories.results.createTestsType());
cd.setObjects(org.joval.scap.oval.Factories.definitions.core.createObjectsType());
cd.setCollectedObjects(org.joval.scap.oval.Factories.sc.core.createCollectedObjectsType());
cd.setStates(org.joval.scap.oval.Factories.definitions.core.createStatesType());
cd.setItems(org.joval.scap.oval.Factories.sc.core.createSystemDataType());
setDiagnosticInfo(cd, OvalFactory.createResults(oval), name);
}
} else if (SystemEnumeration.SCE.namespace().equals(system) && report instanceof SceResultsType) {
cd.setSceResults((SceResultsType)report);
}
rd.getCheckDiagnostics().add(cd);
}
return rd;
}
/**
* Get diagnostics for the specified rule, given a catalog.
*/
private RuleDiagnostics getDiagnostics(RuleResultType rrt, Catalog catalog) throws ScapException {
RuleDiagnostics rd = new RuleDiagnostics();
rd.setRuleResult(rrt);
rd.setRuleId(rrt.getIdref());
// Create a collection of checks that apply to the selected rule
Collection<CheckType> checks = new ArrayList<CheckType>();
if (rrt.isSetCheck()) {
checks.add(rrt.getCheck().get(0));
} else if (rrt.isSetComplexCheck()) {
checks.addAll(getChecks(rrt.getComplexCheck()));
}
for (CheckType check : checks) {
if (!check.isSetCheckContentRef()) {
// Skip checks with no content
continue;
}
CheckDiagnostics cd = new CheckDiagnostics();
cd.setCheck(check);
String system = check.getSystem();
String href = check.getCheckContentRef().get(0).getHref();
String name = check.getCheckContentRef().get(0).getName();
String report_id = null;
for (Object obj : catalog.getPublicOrSystemOrUri()) {
if (obj instanceof JAXBElement) {
obj = ((JAXBElement)obj).getValue();
}
if (obj instanceof Uri) {
Uri uri = (Uri)obj;
if (uri.getUri().substring(1).equals(href)) {
report_id = uri.getName();
break;
}
}
}
if (report_id != null && reports.containsKey(report_id)) {
Object subreport = reports.get(report_id);
try {
if (SystemEnumeration.OCIL.namespace().equals(system)) {
OCILType ocil = (OCILType)(((JAXBElement)subreport).getValue());
setDiagnosticInfo(cd, ScapFactory.createChecklist(ocil), name);
} else if (SystemEnumeration.OVAL.namespace().equals(system)) {
OvalResults oval = (OvalResults)subreport;
if (name == null) {
cd.setDefinitions(oval.getOvalDefinitions().getDefinitions());
cd.setTests(oval.getOvalDefinitions().getTests());
cd.setObjects(oval.getOvalDefinitions().getObjects());
cd.setStates(oval.getOvalDefinitions().getStates());
SystemType st = oval.getResults().getSystem().get(0);
cd.setDefinitionResults(st.getDefinitions());
cd.setTestResults(st.getTests());
cd.setCollectedObjects(st.getOvalSystemCharacteristics().getCollectedObjects());
cd.setItems(st.getOvalSystemCharacteristics().getSystemData());
} else {
cd.setDefinitions(org.joval.scap.oval.Factories.definitions.core.createDefinitionsType());
cd.setDefinitionResults(org.joval.scap.oval.Factories.results.createDefinitionsType());
cd.setTests(org.joval.scap.oval.Factories.definitions.core.createTestsType());
cd.setTestResults(org.joval.scap.oval.Factories.results.createTestsType());
cd.setObjects(org.joval.scap.oval.Factories.definitions.core.createObjectsType());
cd.setCollectedObjects(org.joval.scap.oval.Factories.sc.core.createCollectedObjectsType());
cd.setStates(org.joval.scap.oval.Factories.definitions.core.createStatesType());
cd.setItems(org.joval.scap.oval.Factories.sc.core.createSystemDataType());
setDiagnosticInfo(cd, OvalFactory.createResults(oval), name);
}
} else if (SystemEnumeration.SCE.namespace().equals(system)) {
JAXBElement elt = (JAXBElement)subreport;
cd.setSceResults((SceResultsType)elt.getValue());
}
} catch (NoSuchElementException e) {
logger.warn(e.getMessage());
} catch (ClassCastException e) {
logger.warn(JOVALMsg.getMessage(JOVALMsg.ERROR_EXCEPTION), e);
throw new ArfException(e);
}
rd.getCheckDiagnostics().add(cd);
}
}
return rd;
}
/**
* Find diagnostic information for the specified OCIL questionnaire in the checklist.
*/
private void setDiagnosticInfo(CheckDiagnostics cd, IChecklist checklist, String questionnaireId) {
OCILType ocil = checklist.getRootObject().getValue();
if (!ocil.isSetResults()) {
return;
}
cd.setTargets(ocil.getResults().getTargets());
OcilResultDiagnostics ord = null;
if (ocil.getGenerator().isSetAdditionalData()) {
for (Object obj : ocil.getGenerator().getAdditionalData().getAny()) {
if (obj instanceof OcilResultDiagnostics) {
ord = (OcilResultDiagnostics)obj;
break;
}
}
}
if (ord == null) return;
// Create maps of questionnaire results (indexed by questionnaire ID) and question answers (indexed by question ID)
// from the checklist results.
Map<String, String> questionnaireResults = new HashMap<String, String>();
for (QuestionnaireResultType qr :
checklist.getRootObject().getValue().getResults().getQuestionnaireResults().getQuestionnaireResult()) {
questionnaireResults.put(qr.getQuestionnaireRef(), qr.getResult());
}
Map<String, String> questionResults = new HashMap<String, String>();
for (JAXBElement<? extends QuestionResultType> elt : ocil.getResults().getQuestionResults().getQuestionResult()) {
QuestionResultType qrt = elt.getValue();
String id = qrt.getQuestionRef();
if (qrt instanceof BooleanQuestionResultType) {
questionResults.put(id, ((BooleanQuestionResultType)qrt).getAnswer().toString());
} else if (qrt instanceof ChoiceQuestionResultType) {
ChoiceType choice = checklist.getChoice(((ChoiceQuestionResultType)qrt).getAnswer().getChoiceRef());
if (choice.isSetValue()) {
questionResults.put(id, choice.getValue());
} else if (choice.isSetVarRef()) {
questionResults.put(id, choice.getVarRef()); // TBD: get value from somewhere?
}
} else if (qrt instanceof NumericQuestionResultType) {
questionResults.put(id, ((NumericQuestionResultType)qrt).getAnswer().toString());
} else if (qrt instanceof StringQuestionResultType) {
questionResults.put(id, ((StringQuestionResultType)qrt).getAnswer());
}
}
// Starting with the specified questionnaire ID, determine all the questionnaires required to determine
// its result. This is the scope of our diagnostic information.
Map<String, QuestionnaireType> questionnaires = new HashMap<String, QuestionnaireType>();
for (QuestionnaireType questionnaire : ord.getQuestionnaire()) {
questionnaires.put(questionnaire.getId(), questionnaire);
}
HashSet<String> scope = new HashSet<String>();
if (questionnaireId == null) {
// If no questionnaire is specified, then the scope is all questionnaires in the document
scope.addAll(questionnaires.keySet());
} else {
findDependencies(scope, questionnaireId, questionnaires);
}
// Create a diagnostic object, and add supplementary information
OcilResultDiagnostics diagnostics = new OcilResultDiagnostics();
for (String id : scope) {
QuestionnaireType questionnaire = questionnaires.get(id);
questionnaire.setResult(questionnaireResults.get(id));
questionnaire.setTitle(checklist.getQuestionnaire(id).getTitle());
for (ActionSequenceType sequence : questionnaire.getActions().getTestActionSequence()) {
for (JAXBElement<? extends ActionType> elt : sequence.getAction()) {
ActionType action = elt.getValue();
if (action instanceof QuestionRef) {
QuestionRef ref = (QuestionRef)action;
QuestionTestActionType qta = checklist.getQuestionTestAction(ref.getId());
String questionId = qta.getQuestionRef();
ref.setAnswer(questionResults.get(questionId));
ref.getQuestionText().addAll(checklist.getQuestion(questionId).getQuestionText());
}
}
}
diagnostics.getQuestionnaire().add(questionnaire);
}
cd.setOcilResultDiagnostics(diagnostics);
}
/**
* Find diagnostic information for the specified OVAL definition in the results.
*/
private void setDiagnosticInfo(CheckDiagnostics cd, IResults results, String definitionId) {
IDefinitions definitions = results.getDefinitions();
// Recursively find all the definitions and tests from the OVAL IDefinitions.
Map<String, DefinitionType> defMap = new HashMap<String, DefinitionType>();
DefinitionType rootDefinition = definitions.getDefinition(definitionId);
defMap.put(definitionId, rootDefinition);
Map<String, JAXBElement<? extends TestType>> testMap = new HashMap<String, JAXBElement<? extends TestType>>();
collectDefinitionsAndTests(rootDefinition.getCriteria(), definitions, defMap, testMap);
// Collect all the objects and states that are referenced by the referenced tests
Map<String, JAXBElement<? extends ObjectType>> objectMap = new HashMap<String, JAXBElement<? extends ObjectType>>();
Map<String, JAXBElement<? extends StateType>> stateMap = new HashMap<String, JAXBElement<? extends StateType>>();
collectObjectsAndStates(testMap.keySet(), definitions, objectMap, stateMap);
// Add all the test, object, state and def definitions and results to the diagnostic XML.
for (DefinitionType definition : defMap.values()) {
cd.getDefinitions().getDefinition().add(definition);
cd.getDefinitionResults().getDefinition().add(results.getDefinition(definition.getId()));
}
for (JAXBElement<? extends TestType> test : testMap.values()) {
TestType tt = test.getValue();
cd.getTests().getTest().add(test);
cd.getTestResults().getTest().add(results.getTest(tt.getId()));
}
// Add objects while collecting items in a map
Map<BigInteger, JAXBElement<? extends ItemType>> itemMap = new HashMap<BigInteger, JAXBElement<? extends ItemType>>();
for (Map.Entry<String, JAXBElement<? extends ObjectType>> entry : objectMap.entrySet()) {
String objectId = entry.getKey();
JAXBElement<? extends ObjectType> object = entry.getValue();
cd.getObjects().getObject().add(object);
ISystemCharacteristics sc = results.getSystemCharacteristics();
if (sc.containsObject(objectId)) {
cd.getCollectedObjects().getObject().add(sc.getObject(objectId));
for (JAXBElement<? extends ItemType> item : sc.getItemsByObjectId(objectId)) {
itemMap.put(item.getValue().getId(), item);
}
}
}
for (JAXBElement<? extends StateType> state : stateMap.values()) {
cd.getStates().getState().add(state);
}
for (JAXBElement<? extends ItemType> item : itemMap.values()) {
cd.getItems().getItem().add(item);
}
}
private void findDependencies(HashSet<String> scope, String id, Map<String, QuestionnaireType> questionnaires) {
scope.add(id);
for (ActionSequenceType seq : questionnaires.get(id).getActions().getTestActionSequence()) {
for (JAXBElement<? extends ActionType> elt : seq.getAction()) {
ActionType action = elt.getValue();
if (action instanceof QuestionnaireRef) {
findDependencies(scope, ((QuestionnaireRef)action).getId(), questionnaires);
}
}
}
}
private void collectDefinitionsAndTests(CriteriaType criteria, IDefinitions definitions,
Map<String, DefinitionType> defMap, Map<String, JAXBElement<? extends TestType>> testMap) {
for (Object obj : criteria.getCriteriaOrCriterionOrExtendDefinition()) {
if (obj instanceof CriterionType) {
CriterionType criterion = (CriterionType)obj;
String testId = criterion.getTestRef();
if (!testMap.containsKey(testId)) {
testMap.put(testId, definitions.getTest(testId));
}
} else if (obj instanceof CriteriaType) {
collectDefinitionsAndTests((CriteriaType)obj, definitions, defMap, testMap);
} else if (obj instanceof ExtendDefinitionType) {
String definitionId = ((ExtendDefinitionType)obj).getDefinitionRef();
DefinitionType definition = definitions.getDefinition(definitionId);
if (!defMap.containsKey(definitionId)) {
defMap.put(definitionId, definition);
collectDefinitionsAndTests(definition.getCriteria(), definitions, defMap, testMap);
}
}
}
}
private void collectObjectsAndStates(Collection<String> testIds, IDefinitions definitions,
Map<String, JAXBElement<? extends ObjectType>> objMap, Map<String, JAXBElement<? extends StateType>> stateMap) {
for (String testId : testIds) {
TestType test = definitions.getTest(testId).getValue();
String objectId = getObjectRef(test);
if (objectId != null) {
objMap.put(objectId, definitions.getObject(objectId));
}
for (String stateId : getStateRef(test)) {
stateMap.put(stateId, definitions.getState(stateId));
}
}
}
private String getObjectRef(TestType test) {
String result = null;
try {
Class<?> clazz = test.getClass();
Method method = clazz.getMethod("getObject");
Object obj = method.invoke(test);
if (obj instanceof ObjectRefType) {
result = ((ObjectRefType)obj).getObjectRef();
}
} catch (Exception e) {
}
return result;
}
private List<String> getStateRef(TestType test) {
List<String> result = new ArrayList<String>();
try {
Class<?> clazz = test.getClass();
Method method = clazz.getMethod("getState");
Object obj = method.invoke(test);
if (obj instanceof List) {
for (Object elt : (List)obj) {
if (elt instanceof StateRefType) {
result.add(((StateRefType)elt).getStateRef());
}
}
}
} catch (Exception e) {
}
return result;
}
private Collection<CheckType> getChecks(ComplexCheckType complex) {
Collection<CheckType> checks = new ArrayList<CheckType>();
for (Object obj : complex.getCheckOrComplexCheck()) {
if (obj instanceof CheckType) {
checks.add((CheckType)obj);
} else if (obj instanceof ComplexCheckType) {
checks.addAll(getChecks((ComplexCheckType)obj));
}
}
return checks;
}
}
|
// Contributors: Bjorn Aadland
package org.kxml2.wap;
import java.io.*;
import java.util.Vector;
import org.xmlpull.v1.*;
public class WbxmlParser implements XmlPullParser {
public static final int WAP_EXTENSION = 64;
static final private String UNEXPECTED_EOF =
"Unexpected EOF";
static final private String ILLEGAL_TYPE =
"Wrong event type";
private InputStream in;
private int TAG_TABLE = 0;
private int ATTR_START_TABLE = 1;
private int ATTR_VALUE_TABLE = 2;
private String[] attrStartTable;
private String[] attrValueTable;
private String[] tagTable;
private String stringTable;
private boolean processNsp;
private int depth;
private String[] elementStack = new String[16];
private String[] nspStack = new String[8];
private int[] nspCounts = new int[4];
private int attributeCount;
private String[] attributes = new String[16];
private int nextId = -2;
private Vector tables = new Vector();
int version;
int publicIdentifierId;
int charSet;
// StartTag current;
// ParseEvent next;
private String prefix;
private String namespace;
private String name;
private String text;
// private String encoding;
private Object wapExtensionData;
private int wapExtensionCode;
private int type;
private int codePage;
private boolean degenerated;
private boolean isWhitespace;
public boolean getFeature(String feature) {
if (XmlPullParser
.FEATURE_PROCESS_NAMESPACES
.equals(feature))
return processNsp;
else
return false;
}
public String getInputEncoding() {
// should return someting depending on charSet here!!!!!
return null;
}
public void defineEntityReplacementText(
String entity,
String value)
throws XmlPullParserException {
// just ignore, has no effect
}
public Object getProperty(String property) {
return null;
}
public int getNamespaceCount(int depth) {
if (depth > this.depth)
throw new IndexOutOfBoundsException();
return nspCounts[depth];
}
public String getNamespacePrefix(int pos) {
return nspStack[pos << 1];
}
public String getNamespaceUri(int pos) {
return nspStack[(pos << 1) + 1];
}
public String getNamespace(String prefix) {
if ("xml".equals(prefix))
return "http:
if ("xmlns".equals(prefix))
return "http:
for (int i = (getNamespaceCount(depth) << 1) - 2;
i >= 0;
i -= 2) {
if (prefix == null) {
if (nspStack[i] == null)
return nspStack[i + 1];
}
else if (prefix.equals(nspStack[i]))
return nspStack[i + 1];
}
return null;
}
public int getDepth() {
return depth;
}
public String getPositionDescription() {
StringBuffer buf =
new StringBuffer(
type < TYPES.length ? TYPES[type] : "unknown");
buf.append(' ');
if (type == START_TAG || type == END_TAG) {
if (degenerated)
buf.append("(empty) ");
buf.append('<');
if (type == END_TAG)
buf.append('/');
if (prefix != null)
buf.append("{" + namespace + "}" + prefix + ":");
buf.append(name);
int cnt = attributeCount << 2;
for (int i = 0; i < cnt; i += 4) {
buf.append(' ');
if (attributes[i + 1] != null)
buf.append(
"{"
+ attributes[i]
+ "}"
+ attributes[i
+ 1]
+ ":");
buf.append(
attributes[i
+ 2]
+ "='"
+ attributes[i
+ 3]
+ "'");
}
buf.append('>');
}
else if (type == IGNORABLE_WHITESPACE);
else if (type != TEXT)
buf.append(getText());
else if (isWhitespace)
buf.append("(whitespace)");
else {
String text = getText();
if (text.length() > 16)
text = text.substring(0, 16) + "...";
buf.append(text);
}
return buf.toString();
}
public int getLineNumber() {
return -1;
}
public int getColumnNumber() {
return -1;
}
public boolean isWhitespace()
throws XmlPullParserException {
if (type != TEXT
&& type != IGNORABLE_WHITESPACE
&& type != CDSECT)
exception(ILLEGAL_TYPE);
return isWhitespace;
}
public String getText() {
return text;
}
public char[] getTextCharacters(int[] poslen) {
if (type >= TEXT) {
poslen[0] = 0;
poslen[1] = text.length();
char[] buf = new char[text.length()];
text.getChars(0, text.length(), buf, 0);
return buf;
}
poslen[0] = -1;
poslen[1] = -1;
return null;
}
public String getNamespace() {
return namespace;
}
public String getName() {
return name;
}
public String getPrefix() {
return prefix;
}
public boolean isEmptyElementTag()
throws XmlPullParserException {
if (type != START_TAG)
exception(ILLEGAL_TYPE);
return degenerated;
}
public int getAttributeCount() {
return attributeCount;
}
public String getAttributeType(int index) {
return "CDATA";
}
public boolean isAttributeDefault(int index) {
return false;
}
public String getAttributeNamespace(int index) {
if (index >= attributeCount)
throw new IndexOutOfBoundsException();
return attributes[index << 2];
}
public String getAttributeName(int index) {
if (index >= attributeCount)
throw new IndexOutOfBoundsException();
return attributes[(index << 2) + 2];
}
public String getAttributePrefix(int index) {
if (index >= attributeCount)
throw new IndexOutOfBoundsException();
return attributes[(index << 2) + 1];
}
public String getAttributeValue(int index) {
if (index >= attributeCount)
throw new IndexOutOfBoundsException();
return attributes[(index << 2) + 3];
}
public String getAttributeValue(
String namespace,
String name) {
for (int i = (attributeCount << 2) - 4;
i >= 0;
i -= 4) {
if (attributes[i + 2].equals(name)
&& (namespace == null
|| attributes[i].equals(namespace)))
return attributes[i + 3];
}
return null;
}
public int getEventType() throws XmlPullParserException {
return type;
}
public int next() throws XmlPullParserException, IOException {
isWhitespace = true;
int minType = 9999;
while (true) {
String save = text;
nextImpl();
if (type < minType)
minType = type;
if (minType > CDSECT) continue; // no "real" event so far
if (minType >= TEXT) { // text, see if accumulate
if (save != null) text = text != null ? save : save + text;
switch(peekId()) {
case Wbxml.ENTITY:
case Wbxml.STR_I:
case Wbxml.LITERAL:
case Wbxml.LITERAL_C:
case Wbxml.LITERAL_A:
case Wbxml.LITERAL_AC: continue;
}
}
break;
}
type = minType;
if (type > TEXT)
type = TEXT;
return type;
}
public int nextToken() throws XmlPullParserException, IOException {
isWhitespace = true;
nextImpl();
return type;
}
public int nextTag() throws XmlPullParserException, IOException {
next();
if (type == TEXT && isWhitespace)
next();
if (type != END_TAG && type != START_TAG)
exception("unexpected type");
return type;
}
public String nextText() throws XmlPullParserException, IOException {
if (type != START_TAG)
exception("precondition: START_TAG");
next();
String result;
if (type == TEXT) {
result = getText();
next();
}
else
result = "";
if (type != END_TAG)
exception("END_TAG expected");
return result;
}
public void require(int type, String namespace, String name)
throws XmlPullParserException, IOException {
if (type != this.type
|| (namespace != null && !namespace.equals(getNamespace()))
|| (name != null && !name.equals(getName())))
exception(
"expected: " + TYPES[type] + " {" + namespace + "}" + name);
}
public void setInput(Reader reader) throws XmlPullParserException {
exception("InputStream required");
}
public void setInput(InputStream in, String enc)
throws XmlPullParserException {
this.in = in;
try {
version = readByte();
publicIdentifierId = readInt();
if (publicIdentifierId == 0)
readInt();
charSet = readInt(); // skip charset
int strTabSize = readInt();
StringBuffer buf = new StringBuffer(strTabSize);
for (int i = 0; i < strTabSize; i++)
buf.append((char) readByte());
stringTable = buf.toString();
// System.out.println("String table: "+stringTable);
// System.out.println("String table length: "+stringTable.length());
selectPage(0, true);
selectPage(0, false);
}
catch (IOException e) {
exception("Illegal input format");
}
}
public void setFeature(String feature, boolean value)
throws XmlPullParserException {
if (XmlPullParser.FEATURE_PROCESS_NAMESPACES.equals(feature))
processNsp = value;
else
exception("unsupported feature: " + feature);
}
public void setProperty(String property, Object value)
throws XmlPullParserException {
throw new XmlPullParserException("unsupported property: " + property);
}
private final boolean adjustNsp()
throws XmlPullParserException {
boolean any = false;
for (int i = 0; i < attributeCount << 2; i += 4) {
// * 4 - 4; i >= 0; i -= 4) {
String attrName = attributes[i + 2];
int cut = attrName.indexOf(':');
String prefix;
if (cut != -1) {
prefix = attrName.substring(0, cut);
attrName = attrName.substring(cut + 1);
}
else if (attrName.equals("xmlns")) {
prefix = attrName;
attrName = null;
}
else
continue;
if (!prefix.equals("xmlns")) {
any = true;
}
else {
int j = (nspCounts[depth]++) << 1;
nspStack = ensureCapacity(nspStack, j + 2);
nspStack[j] = attrName;
nspStack[j + 1] = attributes[i + 3];
if (attrName != null
&& attributes[i + 3].equals(""))
exception("illegal empty namespace");
// prefixMap = new PrefixMap (prefixMap, attrName, attr.getValue ());
//System.out.println (prefixMap);
System.arraycopy(
attributes,
i + 4,
attributes,
i,
((--attributeCount) << 2) - i);
i -= 4;
}
}
if (any) {
for (int i = (attributeCount << 2) - 4;
i >= 0;
i -= 4) {
String attrName = attributes[i + 2];
int cut = attrName.indexOf(':');
if (cut == 0)
throw new RuntimeException(
"illegal attribute name: "
+ attrName
+ " at "
+ this);
else if (cut != -1) {
String attrPrefix =
attrName.substring(0, cut);
attrName = attrName.substring(cut + 1);
String attrNs = getNamespace(attrPrefix);
if (attrNs == null)
throw new RuntimeException(
"Undefined Prefix: "
+ attrPrefix
+ " in "
+ this);
attributes[i] = attrNs;
attributes[i + 1] = attrPrefix;
attributes[i + 2] = attrName;
for (int j = (attributeCount << 2) - 4;
j > i;
j -= 4)
if (attrName.equals(attributes[j + 2])
&& attrNs.equals(attributes[j]))
exception(
"Duplicate Attribute: {"
+ attrNs
+ "}"
+ attrName);
}
}
}
int cut = name.indexOf(':');
if (cut == 0)
exception("illegal tag name: " + name);
else if (cut != -1) {
prefix = name.substring(0, cut);
name = name.substring(cut + 1);
}
this.namespace = getNamespace(prefix);
if (this.namespace == null) {
if (prefix != null)
exception("undefined prefix: " + prefix);
this.namespace = NO_NAMESPACE;
}
return any;
}
private final void setTable(int page, int type, String[] table) {
if(stringTable != null){
throw new RuntimeException("setXxxTable must be called before setInput!");
}
while(tables.size() < 3*page +3){
tables.addElement(null);
}
tables.setElementAt(table, page*3+type);
}
private final void exception(String desc)
throws XmlPullParserException {
throw new XmlPullParserException(desc, this, null);
}
private void selectPage(int nr, boolean tags) throws XmlPullParserException{
if(tables.size() == 0 && nr == 0) return;
if(nr*3 > tables.size())
exception("Code Page "+nr+" undefined!");
if(tags)
tagTable = (String[]) tables.elementAt(nr * 3 + TAG_TABLE);
else {
attrStartTable = (String[]) tables.elementAt(nr * 3 + ATTR_START_TABLE);
attrValueTable = (String[]) tables.elementAt(nr * 3 + ATTR_VALUE_TABLE);
}
}
private final void nextImpl()
throws IOException, XmlPullParserException {
String s;
if (type == END_TAG) {
depth
}
if (degenerated) {
type = XmlPullParser.END_TAG;
degenerated = false;
return;
}
text = null;
prefix = null;
name = null;
int id = peekId ();
nextId = -2;
switch (id) {
case -1 :
type = XmlPullParser.END_DOCUMENT;
break;
case Wbxml.SWITCH_PAGE :
selectPage(readByte(), true);
break;
case Wbxml.END :
{
int sp = (depth - 1) << 2;
type = END_TAG;
namespace = elementStack[sp];
prefix = elementStack[sp + 1];
name = elementStack[sp + 2];
}
break;
case Wbxml.ENTITY :
{
type = ENTITY_REF;
char c = (char) readInt();
text = "" + c;
name = "#" + ((int) c);
}
break;
case Wbxml.STR_I :
type = TEXT;
text = readStrI();
break;
case Wbxml.EXT_I_0 :
case Wbxml.EXT_I_1 :
case Wbxml.EXT_I_2 :
case Wbxml.EXT_T_0 :
case Wbxml.EXT_T_1 :
case Wbxml.EXT_T_2 :
case Wbxml.EXT_0 :
case Wbxml.EXT_1 :
case Wbxml.EXT_2 :
case Wbxml.OPAQUE :
parseWapExtension(id);
break;
case Wbxml.PI :
throw new RuntimeException("PI curr. not supp.");
// readPI;
// break;
case Wbxml.STR_T :
{
type = TEXT;
int pos = readInt();
int end = stringTable.indexOf('\0', pos);
text = stringTable.substring(pos, end);
}
break;
default :
parseElement(id);
}
// while (next == null);
// return next;
}
public void parseWapExtension(int id)
throws IOException, XmlPullParserException {
type = WAP_EXTENSION;
wapExtensionCode = id;
switch (id) {
case Wbxml.EXT_I_0 :
case Wbxml.EXT_I_1 :
case Wbxml.EXT_I_2 :
wapExtensionData = readStrI();
break;
case Wbxml.EXT_T_0 :
case Wbxml.EXT_T_1 :
case Wbxml.EXT_T_2 :
wapExtensionData = new Integer(readInt());
break;
case Wbxml.EXT_0 :
case Wbxml.EXT_1 :
case Wbxml.EXT_2 :
break;
case Wbxml.OPAQUE :
{
int len = readInt();
byte[] buf = new byte[len];
for (int i = 0;
i < len;
i++) // enhance with blockread!
buf[i] = (byte) readByte();
wapExtensionData = buf;
} // case OPAQUE
default:
exception("illegal id: "+id);
} // SWITCH
}
public void readAttr() throws IOException, XmlPullParserException {
int id = readByte();
int i = 0;
while (id != 1) {
String name = resolveId(attrStartTable, id);
StringBuffer value;
int cut = name.indexOf('=');
if (cut == -1)
value = new StringBuffer();
else {
value =
new StringBuffer(name.substring(cut + 1));
name = name.substring(0, cut);
}
id = readByte();
while (id > 128
|| id == Wbxml.SWITCH_PAGE
|| id == Wbxml.ENTITY
|| id == Wbxml.STR_I
|| id == Wbxml.STR_T
|| (id >= Wbxml.EXT_I_0 && id <= Wbxml.EXT_I_2)
|| (id >= Wbxml.EXT_T_0 && id <= Wbxml.EXT_T_2)) {
switch (id) {
case Wbxml.SWITCH_PAGE :
selectPage(readByte(), false);
break;
case Wbxml.ENTITY :
value.append((char) readInt());
break;
case Wbxml.STR_I :
value.append(readStrI());
break;
case Wbxml.EXT_I_0 :
case Wbxml.EXT_I_1 :
case Wbxml.EXT_I_2 :
case Wbxml.EXT_T_0 :
case Wbxml.EXT_T_1 :
case Wbxml.EXT_T_2 :
case Wbxml.EXT_0 :
case Wbxml.EXT_1 :
case Wbxml.EXT_2 :
case Wbxml.OPAQUE :
throw new RuntimeException("wap extension in attr not supported yet");
/*
ParseEvent e = parseWapExtension(id);
if (!(e.getType() != Xml.TEXT
&& e.getType() != Xml.WHITESPACE))
throw new RuntimeException("parse WapExtension must return Text Event in order to work inside Attributes!");
value.append(e.getText());
//value.append (handleExtension (id)); // skip EXT in ATTR
//break;
*/
case Wbxml.STR_T :
value.append(readStrT());
break;
default :
value.append(
resolveId(attrValueTable, id));
}
id = readByte();
}
attributes = ensureCapacity(attributes, i + 4);
attributes[i++] = "";
attributes[i++] = null;
attributes[i++] = name;
attributes[i++] = value.toString();
attributeCount++;
}
}
private int peekId () throws IOException {
if (nextId == -2) {
nextId = in.read ();
}
return nextId;
}
String resolveId(String[] tab, int id) throws IOException {
int idx = (id & 0x07f) - 5;
if (idx == -1)
return readStrT();
if (idx < 0
|| tab == null
|| idx >= tab.length
|| tab[idx] == null)
throw new IOException("id " + id + " undef.");
return tab[idx];
}
void parseElement(int id)
throws IOException, XmlPullParserException {
type = START_TAG;
name = resolveId(tagTable, id & 0x03f);
attributeCount = 0;
if ((id & 128) != 0) {
readAttr();
}
degenerated = (id & 64) == 0;
int sp = depth++ << 2;
// transfer to element stack
elementStack = ensureCapacity(elementStack, sp + 4);
elementStack[sp + 3] = name;
/* if (depth >= nspCounts.length) {
int[] bigger = new int[depth + 4];
System.arraycopy(nspCounts, 0, bigger, 0, nspCounts.length);
nspCounts = bigger;
}
nspCounts[depth] = nspCounts[depth - 1]; */
for (int i = attributeCount - 1; i > 0; i
for (int j = 0; j < i; j++) {
if (getAttributeName(i)
.equals(getAttributeName(j)))
exception(
"Duplicate Attribute: "
+ getAttributeName(i));
}
}
if (processNsp)
adjustNsp();
else
namespace = "";
elementStack[sp] = namespace;
elementStack[sp + 1] = prefix;
elementStack[sp + 2] = name;
}
private final String[] ensureCapacity(
String[] arr,
int required) {
if (arr.length >= required)
return arr;
String[] bigger = new String[required + 16];
System.arraycopy(arr, 0, bigger, 0, arr.length);
return bigger;
}
int readByte() throws IOException {
int i = in.read();
if (i == -1)
throw new IOException("Unexpected EOF");
return i;
}
int readInt() throws IOException {
int result = 0;
int i;
do {
i = readByte();
result = (result << 7) | (i & 0x7f);
}
while ((i & 0x80) != 0);
return result;
}
String readStrI() throws IOException {
StringBuffer buf = new StringBuffer();
boolean wsp = true;
while (true) {
int i = in.read();
if (i == -1)
throw new IOException("Unexpected EOF");
if (i == 0)
break;
if (i > 32)
wsp = false;
buf.append((char) i);
}
isWhitespace = wsp;
return buf.toString();
}
String readStrT() throws IOException {
int pos = readInt();
int end = stringTable.indexOf('\0', pos);
return stringTable.substring(pos, end);
}
/**
* Sets the tag table for a given page.
* The first string in the array defines tag 5, the second tag 6 etc.
*/
public void setTagTable(int page, String[] tagTable) {
setTable(page, TAG_TABLE, tagTable);
// this.tagTable = tagTable;
// if (page != 0)
// throw new RuntimeException("code pages curr. not supp.");
}
/** Sets the attribute start Table for a given page.
* The first string in the array defines attribute
* 5, the second attribute 6 etc.
* Currently, only page 0 is supported. Please use the
* character '=' (without quote!) as delimiter
* between the attribute name and the (start of the) value
*/
public void setAttrStartTable(
int page,
String[] attrStartTable) {
setTable(page, ATTR_START_TABLE, tagTable);
// this.attrStartTable = attrStartTable;
// if (page != 0)
// throw new RuntimeException("code pages curr. not supp.");
}
/** Sets the attribute value Table for a given page.
* The first string in the array defines attribute value 0x85,
* the second attribute value 0x86 etc.
* Currently, only page 0 is supported.
*/
public void setAttrValueTable(
int page,
String[] attrStartTable) {
setTable(page, ATTR_VALUE_TABLE, tagTable);
// this.attrValueTable = attrStartTable;
// if (page != 0)
// throw new RuntimeException("code pages curr. not supp.");
}
}
|
package org.mit.jstreamit;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* Channel represents a communication channel between two primitive workers in
* the stream graph, providing methods to push, pop and peek at elements in the
* channel.
*
* This class is not thread-safe.
* @param <E> the type of elements in this channel
* @author Jeffrey Bosboom <jeffreybosboom@gmail.com>
* @since 11/19/2012
*/
public final class Channel<E> implements Iterable<E> {
/**
* The default buffer capacity. Most Java collections choose 16, at least
* in the JRE I'm looking at, but we might want something different.
*/
private static final int DEFAULT_CAPACITY = 16;
/**
* The growth factor for reallocating the underlying array. Java
* collections vary between 1.5 and 2.
*/
private static final double GROWTH_FACTOR = 2;
/**
* The buffer holding elements in the channel. Elements [head, tail) are
* in the channel; other elements are null. Note that this buffer is
* managed circularly, and at least one element is empty before and after
* each method executes.
*/
private E[] buffer;
/**
* The index of the first element in this channel (the element returned by
* pop() or peek(0)), or an arbitrary number equal to tail if the channel
* is empty.
*/
private int head;
/**
* One greater than the index of the last element in this channel (that is,
* the index where an element would be added by push()), or an arbitrary
* number equal to head if the channel is empty.
*/
private int tail;
/**
* The number of calls to push() since the last call to resetStatistics().
*/
private int pushCount;
/**
* The number of calls to pop() since the last call to resetStatistics().
*/
private int popCount;
/**
* The maximum index passed to peek() since the last call to
* resetStatistics(), relative to the position of head at the time of that
* last call to resetStatistics(). That is, a number useful for checking
* peek rate declarations.
*/
private int maxPeekIndex;
/**
* Constructs an empty Channel with the default capacity.
*/
public Channel() {
this(DEFAULT_CAPACITY);
}
/**
* Constructs an empty Channel with the given initial capacity.
* @param capacity the new Channel's initial capacity
*/
@SuppressWarnings("unchecked")
public Channel(int capacity) {
if (capacity < 0)
throw new IllegalArgumentException();
capacity = Math.min(capacity, DEFAULT_CAPACITY);
buffer = (E[])new Object[capacity];
resetStatistics();
}
/**
* Constructs a Channel containing the given elements. The elements are
* copied into the channel; the given array is not modified.
* @param initialElements the initial elements
*/
public Channel(E[] initialElements) {
this(Arrays.asList(initialElements));
}
/**
* Constructs a Channel containing the given elements. The elements are
* copied into the channel; the given collection is not modified.
* @param initialElements the initial elements
*/
public Channel(Collection<? extends E> initialElements) {
this(initialElements.size() + 1);
for (E e : initialElements)
buffer[tail++] = e;
}
/* Basic operations */
/**
* Returns the element at the given index. Updates the maximum peek index.
* @param index the index to peek at
* @return the element at the given index
* @throws IndexOutOfBoundsException if index < 0 or index > size()
*/
public E peek(int index) {
if (index < 0 || index > size())
throw new IndexOutOfBoundsException(String.format("index %d, size %d", index, size()));
//Compute the physical index.
int physicalIndex = head + index;
if (physicalIndex >= buffer.length)
physicalIndex -= buffer.length;
maxPeekIndex = Math.max(maxPeekIndex, index + popCount);
return buffer[physicalIndex];
}
/**
* Adds the given element to the end of this channel. Updates the push
* count.
* @param element the element to add
*/
public void push(E element) {
buffer[tail] = element;
tail = increment(tail);
if (head == tail)
expandCapacity();
++pushCount;
}
/**
* Removes and returns the element at the front of this channel. Updates
* the pop count.
* @return the element at the front of this channel
* @throws NoSuchElementException if this channel is empty
*/
public E pop() {
if (isEmpty())
throw new NoSuchElementException("Channel is empty");
E retval = buffer[head];
//Help the garbage collector recognize this element as garbage.
buffer[head] = null;
head = increment(head);
++popCount;
return retval;
}
/**
* Returns this channel's logical size: the number of elements that can be
* popped.
* @return this channel's logical size
*/
public int size() {
int size = tail - head;
if (size < 0)
size += buffer.length;
return size;
}
/**
* Returns true iff this channel contains no elements.
* @return true iff this channel contains no elements.
*/
public boolean isEmpty() {
return head == tail;
}
/* Statistics-related operations */
/**
* Returns the maximum index passed to peek() since the last call to
* resetStatistics(), relative to the front of this channel at the time of
* that last call. If no peeking occurred, returns -1.
* @return the maximum peek index
*/
public int getMaxPeekIndex() {
return maxPeekIndex;
}
/**
* Returns the number of calls to push() since the last call to
* resetStatistics().
* @return the push count
*/
public int getPushCount() {
return pushCount;
}
/**
* Returns the number of calls to pop() since the last call to
* resetStatistics().
* @return the pop count
*/
public int getPopCount() {
return popCount;
}
/**
* Resets this channel's statistics (push count, pop count and max peek
* index).
*/
public void resetStatistics() {
popCount = 0;
pushCount = 0;
maxPeekIndex = -1;
}
/* Transitioning to other representations (compiler, debugging) */
/**
* Returns the current capacity of this channel (the number of elements it
* can hold without triggering a reallocation).
* @return the channel's capacity
*/
public int getCapacity() {
return buffer.length - 1;
}
/**
* Returns an iterator that iterates over the elements in this channel in
* first-to-last order. The returned iterator does not support remove().
* @return an iterator over this channel
*/
@Override
public Iterator<E> iterator() {
return new Iterator<E>() {
private int position = head;
@Override
public boolean hasNext() {
return position != tail;
}
@Override
public E next() {
if (!hasNext())
throw new NoSuchElementException();
E retval = buffer[position];
position = increment(position);
return retval;
}
@Override
public void remove() {
//We could support remove() for a prefix of the elements
//returned by next() (i.e., once you call next() twice in a row,
//you can't remove() anymore).
throw new UnsupportedOperationException("Not supported.");
}
};
}
@Override
public String toString() {
if (isEmpty())
return "[]";
Iterator<E> iterator = iterator();
StringBuilder sb = new StringBuilder("[");
sb.append(iterator.next());
while (iterator.hasNext())
sb.append(", ").append(iterator.next());
return sb.toString();
}
/* Helper methods */
/**
* Returns the index logically one greater than the given index, wrapping
* around the buffer size as required.
* @param index the index to increment
* @return the next index
*/
private int increment(int index) {
++index;
//TODO: we could trade the branch for a division by using % instead.
if (index >= buffer.length)
index -= buffer.length;
return index;
}
/**
* Expand the buffer, copying over the existing elements. We could take
* this opportunity to move all the elements to the front of the new buffer,
* but that would complicate the code merely to delay the next wraparound,
* so there's no real reason.
*/
private void expandCapacity() {
int newLength = (int)Math.ceil(buffer.length * GROWTH_FACTOR);
if (newLength <= 0)
newLength = Integer.MAX_VALUE; //Good luck allocating that much...
assert newLength >= buffer.length;
buffer = Arrays.copyOf(buffer, newLength);
}
}
|
package picoded.fileutil;
//java incldues
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.Path;
import java.nio.file.attribute.FileAttribute;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
//apache includes
import org.apache.commons.lang3.StringUtils;
/// Small extension of apache FileUtil, for some additional features that we needed.
/// Additionally several FilenameUtils is made avaliable here
public class FileUtil extends org.apache.commons.io.FileUtils {
// JavaCommons extensions
/// List only the folders inside a folder
/// @param folder to scan
/// @return Collection of folders within the current folder
public static Collection<File> listDirs(File inFile) {
List<File> ret = new ArrayList<File>();
for (File f : inFile.listFiles()) {
if (f.isDirectory()) {
ret.add(f);
}
}
return ret;
}
/// Overwrites null encoding with US-ASCII
public static String readFileToString(File inFile) throws IOException {
return picoded.fileutil.FileUtil.readFileToString(inFile, (String) null);
}
/// Overwrites null encoding with US-ASCII
public static String readFileToString(File inFile, String encoding) throws IOException {
if (encoding == null) {
encoding = "US-ASCII";
}
return org.apache.commons.io.FileUtils.readFileToString(inFile, encoding);
}
/// Overwrites null encoding with US-ASCII
public static void writeStringToFile(File inFile, String data) throws IOException {
picoded.fileutil.FileUtil.writeStringToFile(inFile, data, (String) null);
}
/// Overwrites null encoding with US-ASCII
public static void writeStringToFile(File inFile, String data, String encoding) throws IOException {
if (encoding == null) {
encoding = "US-ASCII";
}
org.apache.commons.io.FileUtils.writeStringToFile(inFile, data, encoding);
}
/// Extends the readFileToString to include a "fallback" default value,
/// which is used if the file does not exists / is not readable / is not a
/// file
/// @param file to read
/// @param fallback return value if file is invalid
/// @param encoding mode
/// @returns the file value if possible, else returns the fallback value
public static String readFileToString_withFallback(File inFile, String fallback) {
return picoded.fileutil.FileUtil.readFileToString_withFallback(inFile, fallback, null);
}
/// Extends the readFileToString to include a "fallback" default value,
/// which is used if the file does not exists / is not readable / is not a
/// file
/// @param file to read
/// @param fallback return value if file is invalid
/// @param encoding mode
/// @returns the file value if possible, else returns the fallback value
public static String readFileToString_withFallback(File inFile, String fallback, String encoding) {
if (inFile == null || !inFile.exists() || !inFile.isFile() || !inFile.canRead()) {
return fallback;
}
try {
return picoded.fileutil.FileUtil.readFileToString(inFile, encoding);
} catch (IOException e) {
return fallback;
}
}
/// Write to file only if it differs
/// @param file to write
/// @param value to write
/// @param encoding mode
/// @returns the boolean indicating true if file was written to
public static boolean writeStringToFile_ifDifferant(File inFile, String data, String encoding) throws IOException {
String original = readFileToString_withFallback(inFile, "", encoding);
if (original.equals(data)) {
return false;
}
writeStringToFile(inFile, data, encoding);
return true;
}
/// Write to file only if it differs
/// @param file to write
/// @param value to write
/// @returns the boolean indicating true if file was written to
public static boolean writeStringToFile_ifDifferant(File inFile, String data) throws IOException {
return picoded.fileutil.FileUtil.writeStringToFile_ifDifferant(inFile, data, null);
}
/// Recursively copy all directories, and files only if the file content is different
/// @param folder to scan and copy from
public static void copyDirectory_ifDifferent(File inDir, File outDir) throws IOException, IllegalArgumentException {
copyDirectory_ifDifferent(inDir, outDir, true);
}
/// Recursively copy all directories, and files only if the file content is different
/// @param folder to scan and copy from
public static void copyDirectory_ifDifferent(File inDir, File outDir, boolean preserveFileDate) throws IOException, IllegalArgumentException {
copyDirectory_ifDifferent(inDir, outDir, preserveFileDate, false); //default symlink is false : This is considered advance behaviour
}
/// Recursively copy all directories, and files only if the file content is different
/// @param folder to scan and copy from
public static void copyDirectory_ifDifferent(File inDir, File outDir, boolean preserveFileDate,
boolean tryToUseSymLink) throws IOException, IllegalArgumentException{
if (inDir == null || outDir == null) {
new IOException("Invalid directory");
}
File[] dir_inDir = inDir.listFiles();
for (int i = 0; i < dir_inDir.length; i++) {
File infile = dir_inDir[i];
if (infile.isFile()) {
File outfile = new File(outDir, infile.getName());
copyFile_ifDifferent(infile, outfile, preserveFileDate, tryToUseSymLink);
} else if (infile.isDirectory()) {
File newOutDir = new File(outDir.getAbsolutePath() + File.separator + infile.getName());
newOutDir.mkdir();
copyDirectory_ifDifferent(infile, newOutDir, preserveFileDate, tryToUseSymLink);
}
}
}
/// Recursively copy all directories, and files only if the file content is different
/// @param file to scan and copy from
public static void copyFile_ifDifferent(File inFile, File outFile) throws IOException {
copyFile_ifDifferent(inFile, outFile, true);
}
/// Recursively copy all directories, and files only if the file content is different
/// @param file to scan and copy from
public static void copyFile_ifDifferent(File inFile, File outFile, boolean preserveFileDate) throws IOException {
copyFile_ifDifferent(inFile, outFile, preserveFileDate, false); //default symlink is false : This is considered advance behaviour
}
/// Recursively copy all directories, and files only if the file content is different
/// @param file to scan and copy from
public static void copyFile_ifDifferent(File inFile, File outFile, boolean preserveFileDate, boolean tryToUseSymLink)
throws IOException {
try {
// Checks if the output file is already a symbolic link
// And if its valid. And since both is pratically the same
// final file when linked, the file is considered "not different"
if (Files.isSymbolicLink(outFile.toPath())) {
// Gets the symbolic link source file path, and checks if it points to source file.
// for why is `Files.isSameFile()` used
if (Files.isSameFile(Files.readSymbolicLink(outFile.toPath()), inFile.toPath())) {
// If it points to the same file, the symbolic link is valid
// No copy operations is required.
return;
}
}
// Tries to build symlink if possible, hopefully
if (tryToUseSymLink) {
// NOTE: You do not test source file for symbolic link
// Only the detination file should be a symbolic link.
//if(!Files.isSymbolicLink(inFile.toPath())){
// Files.createSymbolicLink(Paths.get(inFile.getAbsolutePath()), Paths.get(outFile.getAbsolutePath()), new FileAttribute<?>[0]);
// Assumes output file is either NOT a symbolic link
// or has the wrong symbolic link reference.
// Creates a symbolic link of the outfile,
// relative to the in file (if possible)
Files.createSymbolicLink(outFile.toPath().toAbsolutePath(), inFile.toPath().toAbsolutePath());
}
} catch (Exception e) {
// Silence the error
// Uses fallback behaviour of copying the file if it occurs
}
// Checks if file has not been modified, and has same data length, for skipping?
if (inFile.lastModified() == outFile.lastModified() && inFile.length() == outFile.length()) {
// returns and skip for optimization
return;
}
// Final fallback behaviour, copies file if content differs.
if (!FileUtil.contentEqualsIgnoreEOL(inFile, outFile, null)) {
copyFile(inFile, outFile, preserveFileDate);
}
}
// JavaCommons time utility functions
/// Recursively scan for the newest file
/// @param folder to scan
/// @param List of names to skip
/// @return The newest timestamp found, else 0 if failed
public static long newestFileTimestamp(File inFile, List<String> excludeNames) {
if(inFile.isDirectory()) {
long retTimestamp = 0L;
for (File f : inFile.listFiles()) {
if(excludeNames != null) {
String baseName = f.getName();
if( excludeNames.contains(baseName) ) {
continue;
}
}
long tmpTimestamp = 0L;
if (f.isDirectory()) {
tmpTimestamp = newestFileTimestamp(f, excludeNames);
} else if(f.isFile()) {
tmpTimestamp = f.lastModified();
}
if( tmpTimestamp > retTimestamp ) {
retTimestamp = tmpTimestamp;
}
}
return retTimestamp;
} else {
return inFile.lastModified();
}
}
/// Recursively scan for the newest file
/// @param folder to scan
/// @param List of names to skip
/// @return The newest timestamp found, else 0 if failed
public static long newestFileTimestamp(File inFile) {
return newestFileTimestamp(inFile, null);
}
// FilenameUtils functions
/// @see https://commons.apache.org/proper/commons-io/javadocs/api-2.5/org/apache/commons/io/FilenameUtils.html#getBaseName(java.lang.String)
/// @param raw file name/path
/// @return filename only without the the type extension
public static String getBaseName(String filename) {
return org.apache.commons.io.FilenameUtils.getBaseName(filename);
}
/// @see https://commons.apache.org/proper/commons-io/javadocs/api-2.5/org/apache/commons/io/FilenameUtils.html#getExtension(java.lang.String)
/// @param raw file name/path
/// @return filename type extension
public static String getExtension(String filename) {
return org.apache.commons.io.FilenameUtils.getExtension(filename);
}
/// @see https://commons.apache.org/proper/commons-io/javadocs/api-2.5/org/apache/commons/io/FilenameUtils.html#getFullPath(java.lang.String)
/// @param raw file name/path
/// @return full resolved path with ending / for directories
public static String getFullPath(String filename) {
return org.apache.commons.io.FilenameUtils.getFullPath(filename);
}
/// @see https://commons.apache.org/proper/commons-io/javadocs/api-2.5/org/apache/commons/io/FilenameUtils.html#getFullPathNoEndSeparator(java.lang.String)
/// @param raw file name/path
/// @return full resolved path without ending / for directories
public static String getFullPathNoEndSeparator(String filename) {
return org.apache.commons.io.FilenameUtils.getFullPathNoEndSeparator(filename);
}
/// @see https://commons.apache.org/proper/commons-io/javadocs/api-2.5/org/apache/commons/io/FilenameUtils.html#getName(java.lang.String)
/// @param raw file name/path
/// @return filename without the path
public static String getName(String filename) {
return org.apache.commons.io.FilenameUtils.getName(filename);
}
/// @see https://commons.apache.org/proper/commons-io/javadocs/api-2.5/org/apache/commons/io/FilenameUtils.html#getPath(java.lang.String)
/// @param raw file name/path
/// @return full resolved path with ending / for directories
public static String getPath(String filename) {
return org.apache.commons.io.FilenameUtils.getPath(filename);
}
/// @see https://commons.apache.org/proper/commons-io/javadocs/api-2.5/org/apache/commons/io/FilenameUtils.html#getPathNoEndSeparator(java.lang.String)
/// @param raw file name/path
/// @return full resolved path without ending / for directories
public static String getPathNoEndSeparator(String filename) {
return org.apache.commons.io.FilenameUtils.getPathNoEndSeparator(filename);
}
/// @see https://commons.apache.org/proper/commons-io/javadocs/api-2.5/org/apache/commons/io/FilenameUtils.html#normalize(java.lang.String)
/// @param raw file name/path
/// @return full resolved path with ending / for directories
public static String normalize(String filename) {
return org.apache.commons.io.FilenameUtils.normalize(filename);
}
// Items below here, requires cleanup : not considered stable
// @TODO: Documentation
public static Collection<String> getFilePaths(File inFile) {
return getFilePaths(inFile, null, null);
}
// @TODO: Documentation
public static Collection<String> getFilePaths(File inFile, String separator) {
return getFilePaths(inFile, separator, null);
}
// @TODO: Documentation
public static Collection<String> getFilePaths(File inFile, String separator, String folderPrefix) {
List<String> keyList = new ArrayList<String>();
if (StringUtils.isEmpty(folderPrefix)) {
folderPrefix = "";
}
if (StringUtils.isEmpty(separator)) {
separator = "/";
}
if (inFile.isDirectory()) {
File[] innerFiles = inFile.listFiles();
for (File innerFile : innerFiles) {
if (innerFile.isDirectory()) {
String parentFolderName = innerFile.getName();
if (!folderPrefix.isEmpty()) {
parentFolderName = folderPrefix + separator + parentFolderName;
}
keyList.addAll(getFilePaths(innerFile, parentFolderName, separator));
} else {
keyList.addAll(getFilePaths(innerFile, folderPrefix, separator));
}
}
} else {
String fileName = inFile.getName();
fileName = fileName.substring(0, fileName.lastIndexOf('.'));
String prefix = "";
if (!folderPrefix.isEmpty()) {
prefix += folderPrefix + separator;
}
keyList.add(prefix + fileName);
}
return keyList;
}
}
|
package org.usfirst.frc.team1719.robot;
import org.usfirst.frc.team1719.robot.commands.ExampleCommand;
import org.usfirst.frc.team1719.robot.commands.UseFlyWheel;
import org.usfirst.frc.team1719.robot.settings.PIDData;
import org.usfirst.frc.team1719.robot.subsystems.Arm;
import org.usfirst.frc.team1719.robot.subsystems.DriveSubsystem;
import org.usfirst.frc.team1719.robot.subsystems.DualShooter;
import org.usfirst.frc.team1719.robot.subsystems.ExampleSubsystem;
import org.usfirst.frc.team1719.robot.subsystems.FlyWheel;
import com.ni.vision.NIVision;
import com.ni.vision.NIVision.Image;
import edu.wpi.first.wpilibj.CameraServer;
import edu.wpi.first.wpilibj.IterativeRobot;
import edu.wpi.first.wpilibj.command.Command;
import edu.wpi.first.wpilibj.command.Scheduler;
import edu.wpi.first.wpilibj.livewindow.LiveWindow;
import edu.wpi.first.wpilibj.smartdashboard.SendableChooser;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
/**
* The VM is configured to automatically run this class, and to call the
* functions corresponding to each mode, as described in the IterativeRobot
* documentation. If you change the name of this class or the package after
* creating this project, you must also update the manifest file in the resource
* directory.
*/
public class Robot extends IterativeRobot {
final String CAMERA_NAME = "cam0";
public static final ExampleSubsystem exampleSubsystem = new ExampleSubsystem();
public static OI oi;
public static DriveSubsystem drive;
public static FlyWheel rightFlywheel;
public static FlyWheel leftFlywheel;
public static DualShooter shooter;
PIDData rightFlywheelPIDData;
PIDData leftFlywheelPIDData;
public static Arm arm;
Command autonomousCommand;
SendableChooser chooser;
Image frame;
int session;
NIVision.Rect crosshair;
public static boolean isAuton = false;
/**
* This function is run when the robot is first started up and should be
* used for any initialization code.
*/
public void robotInit() {
//Network Initialization
//Setup Camera Server
//Configure SmartDashboard Things
//Hardware Initialization
//Allocate Hardware
RobotMap.init();
//Initialize Subsystems
rightFlywheelPIDData = new PIDData(0,0,0);
leftFlywheelPIDData = new PIDData(0,0,0);
drive = new DriveSubsystem(RobotMap.leftDriveController, RobotMap.rightDriveController);
rightFlywheel = new FlyWheel(RobotMap.rightFlyWheelController, RobotMap.rightFlyWheelEncoder, rightFlywheelPIDData);
leftFlywheel = new FlyWheel(RobotMap.leftFlyWheelController, RobotMap.leftFlyWheelEncoder, leftFlywheelPIDData);
shooter = new DualShooter(leftFlywheel, rightFlywheel, RobotMap.innerShooterWheelController );
arm = new Arm(RobotMap.armController, RobotMap.armPot);
oi = new OI();
isAuton = false;
frame = NIVision.imaqCreateImage(NIVision.ImageType.IMAGE_RGB, 0);
session = NIVision.IMAQdxOpenCamera("cam0",
NIVision.IMAQdxCameraControlMode.CameraControlModeController);
NIVision.IMAQdxConfigureGrab(session);
crosshair = new NIVision.Rect(10, 10, 100, 100);
smartDashboardInit();
}
public void smartDashboardInit(){
//Setup Autonomous Sendable Chooser
chooser = new SendableChooser();
chooser.addDefault("Default Auto", new ExampleCommand());
SmartDashboard.putData("Auto mode", chooser);
//Setup network configurable constants
//puts right flywheel PID values on the smart Dashboard
SmartDashboard.putNumber("Right flywheel kP: ", 0);
SmartDashboard.putNumber("Right flywheel kI: ", 0);
SmartDashboard.putNumber("Right flywheel kD: ", 0);
// puts left flywheel PID values on the smart Dashboard
SmartDashboard.putNumber("Left flywheel kP: ", 0);
SmartDashboard.putNumber("Left flywheel kI: ", 0);
SmartDashboard.putNumber("Left flywheel kD: ", 0);
// puts Drive PID values on the smart Dashboard
SmartDashboard.putNumber("Drive kP", 0);
SmartDashboard.putNumber("Drive kI", 0.);
SmartDashboard.putNumber("Drive kD", 0.);
}
/**
* This function is called once each time the robot enters Disabled mode.
* You can use it to reset any subsystem information you want to clear when
* the robot is disabled.
*/
public void disabledInit(){
//Make sure everything gets disabled
isAuton = false;
rightFlywheel.spin(0);
leftFlywheel.spin(0);
NIVision.IMAQdxStopAcquisition(session);
}
public void disabledPeriodic() {
Scheduler.getInstance().run();
}
/**
* This autonomous (along with the chooser code above) shows how to select between different autonomous modes
* using the dashboard. The sendable chooser code works with the Java SmartDashboard. If you prefer the LabVIEW
* Dashboard, remove all of the chooser code and uncomment the getString code to get the auto name from the text box
* below the Gyro
*
* You can add additional auto modes by adding additional commands to the chooser code above (like the commented example)
* or additional comparisons to the switch structure below with additional strings & commands.
*/
public void autonomousInit() {
isAuton = true;
autonomousCommand = new UseFlyWheel(15, 15);
/* String autoSelected = SmartDashboard.getString("Auto Selector", "Default");
switch(autoSelected) {
case "My Auto":
autonomousCommand = new MyAutoCommand();
break;
case "Default Auto":
default:
autonomousCommand = new ExampleCommand();
break;
} */
// schedule the autonomous command (example)
if (autonomousCommand != null) autonomousCommand.start();
}
/**
* This function is called periodically during autonomous
*/
public void autonomousPeriodic() {
Scheduler.getInstance().run();
}
public void teleopInit() {
/* This makes sure that the autonomous stops running when
teleop starts running. If you want the autonomous to
continue until interrupted by another command, remove
this line or comment it out. */
isAuton = false;
if (autonomousCommand != null) autonomousCommand.cancel();
NIVision.IMAQdxStartAcquisition(session);
}
/**
* This function is called periodically during operator control
*/
public void teleopPeriodic() {
Scheduler.getInstance().run();
NIVision.IMAQdxGrab(session, frame, 1);
CameraServer.getInstance().setImage(frame);
}
/**
* This function is called periodically during test mode
*/
public void testPeriodic() {
isAuton = false;
LiveWindow.run();
}
}
|
package com.voxeo.moho.remote.impl;
import java.util.Map;
import java.util.Properties;
import javax.media.mscontrol.MediaObject;
import javax.media.mscontrol.join.Joinable.Direction;
import javax.media.mscontrol.join.JoinableStream;
import javax.media.mscontrol.join.JoinableStream.StreamType;
import com.rayo.core.JoinDestinationType;
import com.rayo.core.JoinedEvent;
import com.rayo.core.StartedSpeakingEvent;
import com.rayo.core.UnjoinedEvent;
import com.voxeo.moho.Call;
import com.voxeo.moho.Endpoint;
import com.voxeo.moho.Joint;
import com.voxeo.moho.MediaService;
import com.voxeo.moho.Mixer;
import com.voxeo.moho.Participant;
import com.voxeo.moho.Unjoint;
import com.voxeo.moho.common.event.MohoActiveSpeakerEvent;
import com.voxeo.moho.common.event.MohoJoinCompleteEvent;
import com.voxeo.moho.common.event.MohoUnjoinCompleteEvent;
import com.voxeo.moho.event.JoinCompleteEvent;
import com.voxeo.moho.event.UnjoinCompleteEvent;
import com.voxeo.moho.remote.MohoRemoteException;
import com.voxeo.rayo.client.xmpp.stanza.Presence;
public class MixerImpl extends MediaServiceSupport<Mixer> implements Mixer {
private MixerEndpointImpl _mixerEndpoint;
protected Map<Object, Object> _params;
protected String _name;
public MixerImpl(MixerEndpointImpl mixerEndpoint, String name, Map<Object, Object> params) {
super(mixerEndpoint.getMohoRemote());
_mixerEndpoint = mixerEndpoint;
_params = params;
_id = name;
_mohoRemote.addParticipant(this);
_name = name;
}
@Override
public JoinableStream getJoinableStream(StreamType value) {
throw new UnsupportedOperationException(Constants.unsupported_operation);
}
@Override
public JoinableStream[] getJoinableStreams() {
throw new UnsupportedOperationException(Constants.unsupported_operation);
}
@Override
public Endpoint getAddress() {
return _mixerEndpoint;
}
@Override
public Joint join(Participant other, JoinType type, Direction direction) {
return this.join(other, type, false, direction);
}
@Override
public Joint join(Participant other, JoinType type, boolean force, Direction direction) {
Joint joint = null;
if (other instanceof CallImpl) {
joint = other.join(this, type, reserve(direction));
return joint;
}
else {
// TODO mixer join mixer
}
return joint;
}
private Direction reserve(Direction direction) {
if (direction == Direction.RECV) {
return Direction.SEND;
}
else if (direction == Direction.SEND) {
return Direction.RECV;
}
return Direction.DUPLEX;
}
@Override
public Unjoint unjoin(Participant other) {
if (!_joinees.contains(other)) {
throw new IllegalStateException("Not joined.");
}
Unjoint unjoint = null;
if (other instanceof CallImpl) {
unjoint = other.unjoin(this);
}
return unjoint;
}
@Override
public Participant[] getParticipants() {
return _joinees.getJoinees();
}
@Override
public Participant[] getParticipants(Direction direction) {
return _joinees.getJoinees(direction);
}
@Override
public void disconnect() {
_joinees.clear();
}
@Override
public MediaObject getMediaObject() {
throw new UnsupportedOperationException(Constants.unsupported_operation);
}
@Override
public String getRemoteAddress() {
return _id;
}
@Override
public MediaService<Mixer> getMediaService() {
throw new UnsupportedOperationException(Constants.unsupported_operation);
}
@Override
public Joint join(Participant other, JoinType type, Direction direction, Properties props) {
return join(other, type, false, direction, props);
}
@Override
public Joint join(Participant other, JoinType type, boolean force, Direction direction, Properties props) {
return join(other, type, direction);
}
@Override
public JoinType getJoinType(Participant participant) {
return _joinees.getJoinType(participant);
}
@Override
public void onRayoEvent(JID from, Presence presence) {
Object object = presence.getExtension().getObject();
if (object instanceof JoinedEvent) {
MohoJoinCompleteEvent mohoEvent = null;
JoinedEvent event = (JoinedEvent) object;
String id = event.getTo();
JoinDestinationType type = event.getType();
JointImpl joint = _joints.remove(id);
if (type == JoinDestinationType.CALL) {
Call peer = (Call) _mohoRemote.getParticipant(id);
_joinees.add(peer, joint.getType(), joint.getDirection());
mohoEvent = new MohoJoinCompleteEvent(this, peer, JoinCompleteEvent.Cause.JOINED, true);
}
else {
// TODO support mixer join mixer
}
this.dispatch(mohoEvent);
}
else if (object instanceof UnjoinedEvent) {
UnjoinedEvent event = (UnjoinedEvent) object;
MohoUnjoinCompleteEvent mohoEvent = null;
String id = event.getFrom();
JoinDestinationType type = event.getType();
_unjoints.remove(id);
if (type == JoinDestinationType.CALL) {
Call peer = (Call) _mohoRemote.getParticipant(id);
_joinees.remove(peer);
mohoEvent = new MohoUnjoinCompleteEvent(this, peer, UnjoinCompleteEvent.Cause.SUCCESS_UNJOIN, true);
}
else {
// TODO mixer unjoin mixer
}
this.dispatch(mohoEvent);
}
else if (object instanceof StartedSpeakingEvent) {
StartedSpeakingEvent event = (StartedSpeakingEvent) object;
Call speaker = (Call) _mohoRemote.getParticipant(event.getSpeakerId());
MohoActiveSpeakerEvent mohoEvent = new MohoActiveSpeakerEvent(this, new Participant[] {speaker});
this.dispatch(mohoEvent);
}
}
@Override
public String startJoin() throws MohoRemoteException {
return _id;
}
@Override
public String getName() {
return _name;
}
}
|
package net.acomputerdog.BlazeLoader.api.recipe;
import net.minecraft.inventory.InventoryCrafting;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
public class ReversableShapedRecipe extends BShapedRecipe {
private boolean anyDirection = true;
public ReversableShapedRecipe(int par1, int par2, ItemStack[] par3ArrayOfItemStack, ItemStack par4ItemStack) {
super(par1, par2, par3ArrayOfItemStack, par4ItemStack);
}
public void setReverseOnly() {
anyDirection = false;
}
public boolean matches(InventoryCrafting grid, World w) {
if (anyDirection) {
return super.matches(grid, w);
}
return false;
}
public ItemStack[] getRecipeInput() {
return this.recipeItems.clone();
}
}
|
/**
* Customizable injection of bean properties.
* <p><p>
* For example:
*
* <pre>
* new AbstractModule() {
* @Override
* protected void configure() {
* bindListener( Matchers.any(), new BeanListener( new MyBeanBinder() ) );
* }
* }</pre>
* MyBeanBinder will be asked to supply a {@link org.eclipse.sisu.bean.PropertyBinder} per-bean type.
* <p><p>
* Each PropertyBinder will in turn be asked for a {@link org.eclipse.sisu.bean.PropertyBinding} per-property.
* <p><p>
* The PropertyBindings are used to set values in any injected instances of the bean.
*/
package org.eclipse.sisu.bean;
|
package org.aeonbits.owner.crypto;
import java.util.List;
import java.util.Arrays;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import org.aeonbits.owner.Config;
import org.aeonbits.owner.ConfigFactory;
import static org.aeonbits.owner.Config.*;
public class CryptoConfigTest {
public static final String SECRET_KEY = "ABCDEFGH12345678";
public static final String PASSWORD_EXPECTED = "This is my key.";
public static final String SALUTATION_EXPECTED = "Good Morning";
@DecryptorClass(Decryptor1.class)
public interface SampleConfig extends Config {
String hello(String param);
@DefaultValue("Bohemian Rapsody - Queen")
String favoriteSong();
String unspecifiedProperty();
@Key("server.http.port")
int httpPort();
@Key("salutation.text")
@DefaultValue("Good Morning")
String salutation();
@DefaultValue("foo")
void voidMethodWithValue();
void voidMethodWithoutValue();
@Key("crypto.password")
@EncryptedValue
@DefaultValue("tzH7IKLCVc0AC72fh5DiZA==")
String password();
@Key("crypto.list")
@EncryptedValue
@Separator(",")
@DefaultValue("Pfzoiet5E5zN2/7tfgrGLQ==")
List<String> cryptoList();
}
/**
* We test that the decrypt works as expected.
*/
@Test
public void passwordDecryptedTest() {
SampleConfig config = ConfigFactory.create( SampleConfig.class );
String decryptedPassword = config.password();
assertEquals( "Property password wasn't decrypted.", PASSWORD_EXPECTED, decryptedPassword );
}
/**
* This test checks that the decrypted value is not cached.
* So we recover it twice.
*/
@Test
public void passwordDecryptedTwiceTest() {
SampleConfig config = ConfigFactory.create( SampleConfig.class );
String decryptedPassword = config.password();
decryptedPassword = config.password();
assertEquals( "May be property password was decrypted twice.", PASSWORD_EXPECTED, decryptedPassword );
}
@Test
public void listDecryptedTest() {
SampleConfig config = ConfigFactory.create( SampleConfig.class );
List<String> decryptedList = config.cryptoList();
List<String> expectedList = Arrays.asList( "1", "2", "3", "4");
assertEquals( "KKKK", expectedList, decryptedList );
}
/**
* We test the value of non encripted properties.
*/
@Test
public void salutationNotDecryptedTest() {
SampleConfig config = ConfigFactory.create( SampleConfig.class );
String salutation = config.salutation();
assertEquals( "Salutation value is not expected", SALUTATION_EXPECTED, salutation );
}
public static class Decryptor1 extends SampleDecryptor {
public Decryptor1() {
super( "AES", SECRET_KEY );
}
}
public static class Decryptor2 extends SampleDecryptor {
public Decryptor2() {
super( "AES", SECRET_KEY + SECRET_KEY );
}
}
}
|
package Client;
import ChatBox.ChatClient;
import RMIInterfaces.ChatServerInterface;
import RMIInterfaces.ServerInterface;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.embed.swing.SwingFXUtils;
import javafx.fxml.FXML;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.image.WritableImage;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.stage.FileChooser;
import javax.imageio.ImageIO;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.rmi.registry.Registry;
import java.util.ArrayList;
import java.util.Optional;
public class WBController {
protected double startX;
protected double startY;
protected double endX;
protected double endY;
private int canvasCount = 0;
public Boolean close = false;
private File file = null;
public void setFile(File file) {
this.file = file;
}
private String message;
private String userName;
private String client1 = null;
private String client2 = null;
private String client3 = null;
private int clientCount = 0;
private Boolean isManager = false;
private Boolean testSignIn = true;
private Boolean isRegistered = false;
public void setMessage(String message) {
System.out.println("SetMessage" + message);
this.message = message;
}
@FXML
private TextField nameInput;
@FXML
private TextField passWordInput;
@FXML
private Pane signInPane;
@FXML
private BorderPane wbPane;
@FXML
private AnchorPane mainPane;
@FXML
private Canvas canvas;
@FXML
private ColorPicker colorPicker;
@FXML
private Slider slider;
@FXML
private Label sliderSize;
@FXML
private Pane canvasPane;
@FXML
private TextArea textMessage;
@FXML
private TextArea input;
@FXML
private Canvas pathCanvas;
@FXML
private RadioButton sketch;
@FXML
private RadioButton eraser;
@FXML
private RadioButton line;
@FXML
private RadioButton oval;
@FXML
private RadioButton circle;
@FXML
private RadioButton rect;
@FXML
private RadioButton text;
@FXML
private ImageView imageView;
@FXML
private Button clientOne;
@FXML
private Button clientTwo;
@FXML
private Button clientThree;
@FXML
private Label managerName;
protected ArrayList<Point> pointList = new ArrayList<Point>();
Registry registry;
ServerInterface gsonServant;
ChatServerInterface chatServant;
private final ToggleGroup group = new ToggleGroup();
private void setClient() throws Exception{
ArrayList<ChatClient> chatClients = chatServant.getChatClients();
client1 = chatClients.get(1).getUserName();
client2 = chatClients.get(2).getUserName();
client3 = chatClients.get(3).getUserName();
clientCount = chatClients.size();
}
// Initialize the canvas to make sure the default color of colorPicker is black.
public void setImage() {
sketch.setUserData("sketch");
eraser.setUserData("eraser");
line.setUserData("line");
oval.setUserData("oval");
circle.setUserData("circle");
text.setUserData("text");
rect.setUserData("rect");
sketch.setToggleGroup(group);
eraser.setToggleGroup(group);
line.setToggleGroup(group);
oval.setToggleGroup(group);
circle.setToggleGroup(group);
text.setToggleGroup(group);
rect.setToggleGroup(group);
sketch.setSelected(true);
imageView.setImage(new Image("sketch.png"));
group.selectedToggleProperty().addListener(new ChangeListener<Toggle>() {
public void changed(ObservableValue<? extends Toggle> ov,
Toggle old_toggle, Toggle new_toggle) {
if (group.getSelectedToggle() != null) {
final Image image = new Image(
group.getSelectedToggle().getUserData().toString() +
".png"
);
imageView.setImage(image);
}
}
});
}
public void initialize() {
colorPicker.setValue(Color.BLACK);
setImage();
sketch();
}
// It can change the size of font, which can be displayed while moving the slider.
public void setFont() {
GraphicsContext g = canvas.getGraphicsContext2D();
GraphicsContext newG = pathCanvas.getGraphicsContext2D();
slider.valueProperty().addListener(e -> {
double sliderValue = slider.getValue();
String str = String.format("%.1f", sliderValue);
sliderSize.setText(str);
g.setLineWidth(sliderValue);
newG.setLineWidth(sliderValue);
});
Color color = colorPicker.getValue();
g.setStroke(color);
newG.setStroke(color);
}
// when pressed the mouse, it starts to paint.
public void sketch() {
setFont();
GraphicsContext g = canvas.getGraphicsContext2D();
pathCanvas.setOnMousePressed(e -> {
g.beginPath();
g.lineTo(e.getX(), e.getY());
pointList.add(getPoint(e.getX(), e.getY()));
g.setStroke(colorPicker.getValue());
g.stroke();
});
pathCanvas.setOnMouseDragged(e -> {
g.lineTo(e.getX(), e.getY());
pointList.add(getPoint(e.getX(), e.getY()));
g.stroke();
});
pathCanvas.setOnMouseReleased(e -> {
canvasCount = 1;
jsonSendPaints("sketch", addPaintAttri(pointList, "null"));
pointList.clear();
g.closePath();
});
}
public void erase() {
setFont();
GraphicsContext g = canvas.getGraphicsContext2D();
ArrayList<Point> pointList = new ArrayList<>();
pathCanvas.setOnMousePressed(e -> {
g.beginPath();
double size = slider.getValue();
double x = e.getX() - size / 2;
double y = e.getY() - size / 2;
pointList.add(getPoint(e.getX(), e.getY()));
g.clearRect(x, y, size, size);
});
pathCanvas.setOnMouseDragged(e -> {
double size = slider.getValue();
double x = e.getX() - size / 2;
double y = e.getY() - size / 2;
pointList.add(getPoint(e.getX(), e.getY()));
g.clearRect(x, y, size, size);
g.closePath();
});
pathCanvas.setOnMouseReleased(e -> {
canvasCount = 1;
jsonSendPaints("erase", addPaintAttri(pointList, "null"));
pointList.clear();
});
}
public void lineDraw() {
setFont();
GraphicsContext g = canvas.getGraphicsContext2D();
GraphicsContext newG = pathCanvas.getGraphicsContext2D();
pathCanvas.setOnMousePressed(e -> {
g.beginPath();
g.setStroke(colorPicker.getValue());
newG.setStroke(colorPicker.getValue());
startX = e.getX();
startY = e.getY();
});
pathCanvas.setOnMouseDragged(e -> {
endX = e.getX();
endY = e.getY();
newG.clearRect(0, 0, pathCanvas.getWidth(), pathCanvas.getHeight());
newG.strokeLine(startX, startY, endX, endY);
});
pathCanvas.setOnMouseReleased(e -> {
canvasCount = 1;
endX = e.getX();
endY = e.getY();
newG.clearRect(0, 0, pathCanvas.getWidth(), pathCanvas.getHeight());
g.strokeLine(startX, startY, endX, endY);
pointList.add(getPoint(startX, startY));
pointList.add(getPoint(endX, endY));
jsonSendPaints("line", addPaintAttri(pointList, "null"));
pointList.clear();
g.closePath();
});
}
public void cirDraw() {
setFont();
GraphicsContext g = canvas.getGraphicsContext2D();
GraphicsContext newG = pathCanvas.getGraphicsContext2D();
pathCanvas.setOnMousePressed(e -> {
g.beginPath();
g.setStroke(colorPicker.getValue());
newG.setStroke(colorPicker.getValue());
startX = e.getX();
startY = e.getY();
});
pathCanvas.setOnMouseDragged(e -> {
endX = e.getX();
endY = e.getY();
double x = Math.min(startX, endX);
double y = Math.min(startY, endY);
double height = Math.abs(startY - endY);
newG.clearRect(0, 0, pathCanvas.getWidth(), pathCanvas.getHeight());
newG.strokeOval(x, y, height, height);
});
pathCanvas.setOnMouseReleased(e -> {
canvasCount = 1;
endX = e.getX();
endY = e.getY();
double x = Math.min(startX, endX);
double y = Math.min(startY, endY);
double height = Math.abs(startY - endY);
newG.clearRect(0, 0, pathCanvas.getWidth(), pathCanvas.getHeight());
g.strokeOval(x, y, height, height);
pointList.add(getPoint(startX, startY));
pointList.add(getPoint(endX, endY));
jsonSendPaints("cir", addPaintAttri(pointList, "null"));
pointList.clear();
g.closePath();
});
}
public void rectDraw() {
setFont();
GraphicsContext g = canvas.getGraphicsContext2D();
GraphicsContext newG = pathCanvas.getGraphicsContext2D();
pathCanvas.setOnMousePressed(e -> {
g.beginPath();
g.setStroke(colorPicker.getValue());
newG.setStroke(colorPicker.getValue());
startX = e.getX();
startY = e.getY();
});
pathCanvas.setOnMouseDragged(e -> {
endX = e.getX();
endY = e.getY();
double x = Math.min(startX, endX);
double y = Math.min(startY, endY);
double width = Math.abs(startX - endX);
double height = Math.abs(startY - endY);
newG.clearRect(0, 0, pathCanvas.getWidth(), pathCanvas.getHeight());
newG.strokeRect(x, y, width, height);
});
pathCanvas.setOnMouseReleased(e -> {
canvasCount = 1;
endX = e.getX();
endY = e.getY();
double x = Math.min(startX, endX);
double y = Math.min(startY, endY);
double width = Math.abs(startX - endX);
double height = Math.abs(startY - endY);
newG.clearRect(0, 0, pathCanvas.getWidth(), pathCanvas.getHeight());
g.strokeRect(x, y, width, height);
pointList.add(getPoint(startX, startY));
pointList.add(getPoint(endX, endY));
jsonSendPaints("rect", addPaintAttri(pointList, "null"));
pointList.clear();
g.closePath();
});
}
public void ovalDraw() {
setFont();
GraphicsContext g = canvas.getGraphicsContext2D();
GraphicsContext newG = pathCanvas.getGraphicsContext2D();
pathCanvas.setOnMousePressed(e -> {
g.beginPath();
g.setStroke(colorPicker.getValue());
newG.setStroke(colorPicker.getValue());
startX = e.getX();
startY = e.getY();
});
pathCanvas.setOnMouseDragged(e -> {
endX = e.getX();
endY = e.getY();
double x = Math.min(startX, endX);
double y = Math.min(startY, endY);
double width = Math.abs(startX - endX);
double height = Math.abs(startY - endY);
newG.clearRect(0, 0, pathCanvas.getWidth(), pathCanvas.getHeight());
newG.strokeOval(x, y, width, height);
});
pathCanvas.setOnMouseReleased(e -> {
canvasCount = 1;
endX = e.getX();
endY = e.getY();
double x = Math.min(startX, endX);
double y = Math.min(startY, endY);
double width = Math.abs(startX - endX);
double height = Math.abs(startY - endY);
newG.clearRect(0, 0, pathCanvas.getWidth(), pathCanvas.getHeight());
g.strokeOval(x, y, width, height);
pointList.add(getPoint(startX, startY));
pointList.add(getPoint(endX, endY));
jsonSendPaints("oval", addPaintAttri(pointList, "null"));
pointList.clear();
g.closePath();
});
}
public void textInput() {
setFont();
GraphicsContext g = canvas.getGraphicsContext2D();
pathCanvas.setOnMousePressed(e -> {
startX = e.getX();
startY = e.getY();
Font font = new Font(slider.getValue());
TextField textField = new TextField();
textField.setLayoutX(startX);
textField.setLayoutY(startY);
textField.setMinWidth(100);
textField.setMinHeight(50);
textField.setFont(font);
textField.setStyle("-fx-background-color: transparent");
canvasPane.getChildren().add(textField);
textField.requestFocus();
textField.setOnKeyPressed(keyEvent -> {
if (keyEvent.getCode() == KeyCode.ENTER) {
g.setFont(font);
g.setFill(colorPicker.getValue());
String text = textField.getText();
pointList.add(getPoint(startX, startY));
jsonSendPaints("text", addPaintAttri(pointList, text));
pointList.clear();
canvasPane.getChildren().remove(textField);
g.fillText(text, startX - 5, startY + 25);
}
});
});
pathCanvas.setOnMouseDragged(e -> {
});
pathCanvas.setOnMouseReleased(e -> {
canvasCount = 1;
});
}
private void newFile() throws IOException {
canvasPane.getChildren().remove(canvas);
canvas = new Canvas(canvasPane.getWidth(), canvasPane.getHeight());
pathCanvas = new Canvas(canvasPane.getWidth(), canvasPane.getHeight());
canvasPane.getChildren().add(canvas);
canvasPane.getChildren().add(pathCanvas);
slider.setValue(1);
colorPicker.setValue(Color.BLACK);
setFile(null);
canvasCount = 0;
}
public void onNew() throws IOException {
if (isManager) {
if (canvasCount == 1) {
infoBox("Your changes will be lost if you don't save them.",
"Do you want to save the changes?", "save");
} else {
newFile();
setFont();
}
}
}
private void save() throws IOException {
int width = (int) canvasPane.getWidth();
int height = (int) canvasPane.getHeight();
WritableImage writableImage = new WritableImage(width, height);
canvas.snapshot(null, writableImage);
RenderedImage renderedImage = SwingFXUtils.fromFXImage(writableImage, null);
ImageIO.write(renderedImage, "png", file);
canvasCount = 0;
}
public void onSave() throws IOException {
if (file != null) {
save();
} else {
onSaveAs();
}
}
public void onSaveAs() throws IOException {
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Save As");
fileChooser.getExtensionFilters().add(
new FileChooser.ExtensionFilter("Image Files", "*.png", "*.bmp", "*.jpg", "*.gif"));
File tempFile = fileChooser.showSaveDialog(null);
if (tempFile == null) {
} else {
setFile(tempFile);
}
if (file != null) {
save();
}
}
private void open() throws IOException {
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Open File");
fileChooser.getExtensionFilters().add(
new FileChooser.ExtensionFilter("Image Files", "*.png", "*.bmp", "*.jpg", "*.gif"));
File tempFile = fileChooser.showOpenDialog(null);
if (tempFile == null) {
} else {
setFile(tempFile);
}
if (file != null) {
Image image = new Image(new FileInputStream(file));
GraphicsContext g = canvas.getGraphicsContext2D();
g.drawImage(image, 0, 0, canvasPane.getWidth(), canvasPane.getHeight());
setFont();
}
}
public void onOpen() throws IOException {
if (isManager) {
if (canvasCount == 1) {
infoBox("Your changes will be lost if you don't save them.",
"Do you want to save the changes?", "open");
} else {
open();
}
}
}
public void onExit() throws IOException {
if (canvasCount == 1) {
infoBox("Your changes will be lost if you don't save them.",
"Do you want to save the changes?", "exit");
if (close == true) {
Platform.exit();
}
} else {
Platform.exit();
}
}
public void onClose() throws IOException {
if (isManager) {
confirmBox("Close", "Close the Whiteboard", "All Clients will lose the connections",0);
}
}
private void kick(String userName, int clientNum) throws IOException {
confirmBox("Kick", "Kick the " + userName + "!",
"Do you want to kick the " + userName + " ?", clientNum);
chatServant.kickClient(userName);
}
private void approve(String userName ,int clientNum) throws IOException {
if(isManager) {
confirmBox("Approve", "Approve the " + userName + "!",
"Do you want to approve the " + userName + " ?",clientNum);
}
}
public void kickUserOne() throws IOException {
if (isManager) {
String clientName = clientOne.getText();
kick(clientName,1);
}
}
public void kickUserTwo() throws IOException {
if (isManager) {
String clientName = clientTwo.getText();
kick(clientName,2);
}
}
public void kickUserThree() throws IOException {
if (isManager) {
String clientName = clientThree.getText();
kick(clientName,3);
}
}
private Point getPoint(double x, double y) {
Point p = new Point(x, y);
p.setPoint(x, y);
return p;
}
public void infoBox(String infoMessage, String headerMessage, String command) throws IOException {
Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
alert.setHeaderText(headerMessage);
alert.setContentText(infoMessage);
ButtonType buttonTypeOne = new ButtonType("Don't Save");
ButtonType buttonTypeTwo = new ButtonType("Cancel");
ButtonType buttonTypeThree = new ButtonType("Save");
alert.getButtonTypes().setAll(buttonTypeOne, buttonTypeTwo, buttonTypeThree);
Optional<ButtonType> result = alert.showAndWait();
switch (command) {
case "open":
if (result.get() == buttonTypeOne) {
open();
} else if (result.get() == buttonTypeTwo) {
alert.close();
} else if (result.get() == buttonTypeThree) {
onSave();
open();
}
break;
case "save":
if (result.get() == buttonTypeOne) {
newFile();
setFont();
} else if (result.get() == buttonTypeTwo) {
alert.close();
} else if (result.get() == buttonTypeThree) {
onSave();
}
break;
case "exit":
if (result.get() == buttonTypeOne) {
close = true;
} else if (result.get() == buttonTypeTwo) {
alert.close();
close = false;
} else if (result.get() == buttonTypeThree) {
onSave();
if (file != null) {
Platform.exit();
close = true;
} else {
alert.close();
}
}
break;
}
}
// this is for manager to control the client
private void confirmBox(String command, String header, String content, int clientNum) throws IOException {
Alert confirmAlert = new Alert(Alert.AlertType.CONFIRMATION);
confirmAlert.setTitle(command);
confirmAlert.setHeaderText(header);
confirmAlert.setContentText(content);
ButtonType buttonTypeOne = new ButtonType("Yes");
ButtonType buttonTypeTwo = new ButtonType("No");
confirmAlert.getButtonTypes().setAll(buttonTypeOne, buttonTypeTwo);
Optional<ButtonType> result = confirmAlert.showAndWait();
if (result.get() == buttonTypeOne) {
switch (command) {
case "Kick":
if (clientNum==2) {
clientOne.setText(null);
break;
}
if (clientNum==3) {
clientTwo.setText(null);
break;
}
if (clientNum==4) {
clientThree.setText(null);
break;
}
break;
case "Approve":
if (clientNum == 1) {
clientOne.setText(userName);
break;
}
if (clientNum == 2) {
clientTwo.setText(userName);
break;
}
if (clientNum == 3) {
clientThree.setText(userName);
break;
}
break;
case "Close":
infoBox("Your changes will be lost if you don't save them.",
"Do you want to save the changes?", "exit");
}
}
if (result.get() == buttonTypeTwo) {
confirmAlert.close();
}
}
private void jsonSendPaints(String shapeKey, PaintAttribute attribute) {
try {
String output = gsonServant.sendPaints(shapeKey, attribute);
// String output = sendPoints(shapeKey, list);
System.out.println("output = " + output);
} catch (Exception e) {
e.printStackTrace();
}
}
private PaintAttribute addPaintAttri(ArrayList<Point> pointList, String text) {
double lineWidth = slider.getValue();
double colorRed = colorPicker.getValue().getRed();
double colorGreen = colorPicker.getValue().getGreen();
double colorBlue = colorPicker.getValue().getBlue();
double[] color = {colorRed, colorGreen, colorBlue};
PaintAttribute paintAttribute = new PaintAttribute(pointList, lineWidth, color, text);
return paintAttribute;
}
public void setServant(ServerInterface gsonServant,ChatServerInterface chatServant) {
this.gsonServant = gsonServant;
this.chatServant = chatServant;
}
private void jsonSendUserData(String userName, String password) {
//test userSys
/*
try{
gsonServant.sendGson("username", userName);
gsonServant.sendGson("passward", password);
}catch (Exception e) {
e.printStackTrace();
}*/
}
public synchronized void autoPaint(String keyword, PaintAttribute attribute) {
// convert Json String back to PaintAttribute object.
// System.out.println(gson.fromJson(attribute, PaintAttribute.class));
switch (keyword) {
case "sketch":
autoSketch(attribute);
break;
case "erase":
autoErase(attribute);
break;
case "line":
autoLine(attribute);
break;
case "cir":
autoCir(attribute);
break;
case "rect":
autoRect(attribute);
break;
case "oval":
autoOval(attribute);
break;
case "text":
autoText(attribute);
break;
default:
System.out.println("Error shape keyword! Lao Ma Ni Za Hui SHier!!!");
break;
}
}
private void autoSketch(PaintAttribute attribute) {
GraphicsContext g = canvas.getGraphicsContext2D();
g.beginPath();
Color newColor = assembleColor(attribute);
g.setStroke(newColor);
g.setLineWidth(attribute.getLineWidth());
ArrayList<Point> nodeList = attribute.getPointList();
for (int i = 0; i < nodeList.size(); i++) {
g.lineTo(nodeList.get(i).getPointX(), nodeList.get(i).getPointY());
}
g.stroke();
canvasCount = 1;
g.closePath();
}
private void autoErase(PaintAttribute attribute) {
GraphicsContext g = canvas.getGraphicsContext2D();
g.beginPath();
double size = attribute.getLineWidth();
ArrayList<Point> nodeList = attribute.getPointList();
for (int i = 0; i < nodeList.size(); i++) {
double x = nodeList.get(i).getPointX() - size / 2;
double y = nodeList.get(i).getPointY() - size / 2;
g.clearRect(x, y, size, size);
}
canvasCount = 1;
g.closePath();
}
private void autoLine(PaintAttribute attribute) {
GraphicsContext g = canvas.getGraphicsContext2D();
Color newColor = assembleColor(attribute);
g.setStroke(newColor);
g.setLineWidth(attribute.getLineWidth());
g.beginPath();
ArrayList<Point> nodeList = attribute.getPointList();
startX = nodeList.get(0).getPointX();
startY = nodeList.get(0).getPointY();
endX = nodeList.get(1).getPointX();
endY = nodeList.get(1).getPointY();
g.strokeLine(startX, startY, endX, endY);
canvasCount = 1;
g.closePath();
}
private void autoCir(PaintAttribute attribute) {
GraphicsContext g = canvas.getGraphicsContext2D();
Color newColor = assembleColor(attribute);
g.setStroke(newColor);
g.setLineWidth(attribute.getLineWidth());
g.beginPath();
ArrayList<Point> nodeList = attribute.getPointList();
startX = nodeList.get(0).getPointX();
startY = nodeList.get(0).getPointY();
endX = nodeList.get(1).getPointX();
endY = nodeList.get(1).getPointY();
double x = Math.min(startX, endX);
double y = Math.min(startY, endY);
double height = Math.abs(startY - endY);
g.strokeOval(x, y, height, height);
canvasCount = 1;
g.closePath();
}
private void autoRect(PaintAttribute attribute) {
GraphicsContext g = canvas.getGraphicsContext2D();
Color newColor = assembleColor(attribute);
g.setStroke(newColor);
g.setLineWidth(attribute.getLineWidth());
g.beginPath();
ArrayList<Point> nodeList = attribute.getPointList();
startX = nodeList.get(0).getPointX();
startY = nodeList.get(0).getPointY();
endX = nodeList.get(1).getPointX();
endY = nodeList.get(1).getPointY();
double x = Math.min(startX, endX);
double y = Math.min(startY, endY);
double width = Math.abs(startX - endX);
double height = Math.abs(startY - endY);
g.strokeRect(x, y, width, height);
canvasCount = 1;
g.closePath();
}
private void autoOval(PaintAttribute attribute) {
GraphicsContext g = canvas.getGraphicsContext2D();
Color newColor = assembleColor(attribute);
g.setStroke(newColor);
g.setLineWidth(attribute.getLineWidth());
g.beginPath();
ArrayList<Point> nodeList = attribute.getPointList();
startX = nodeList.get(0).getPointX();
startY = nodeList.get(0).getPointY();
endX = nodeList.get(1).getPointX();
endY = nodeList.get(1).getPointY();
double x = Math.min(startX, endX);
double y = Math.min(startY, endY);
double width = Math.abs(startX - endX);
double height = Math.abs(startY - endY);
g.strokeOval(x, y, width, height);
canvasCount = 1;
g.closePath();
}
private void autoText(PaintAttribute attribute) {
GraphicsContext g = canvas.getGraphicsContext2D();
Color newColor = assembleColor(attribute);
ArrayList<Point> nodeList = attribute.getPointList();
startX = nodeList.get(0).getPointX();
startY = nodeList.get(0).getPointY();
Font font = new Font(attribute.getLineWidth());
g.setFont(font);
g.setFill(newColor);
String text = attribute.getText();
g.fillText(text, startX - 5, startY + 25);
}
private Color assembleColor(PaintAttribute attribute) {
double[] colorList = attribute.getColor();
Color newColor = Color.color(colorList[0], colorList[1], colorList[2]);
return newColor;
}
public synchronized void send() throws IOException {
String allMessages = ("userName: ");
String message = input.getText();
allMessages += message;
input.clear();
textMessage.appendText(allMessages + "\n");
gsonServant.sendMessage("userName", allMessages);
}
//print to GUI chat room
public void setText(String msgPrint) throws IOException {
message = msgPrint;
}
public void signIn() throws Exception {
String user = nameInput.getText();
String encrypt = passWordInput.getText();
gsonServant.checkPassword(user, encrypt);
if (testSignIn) {
// the number of client
if (true) {
isManager = true;
signInPane.setVisible(false);
wbPane.setVisible(true);
isManager = true;
managerName.setText(user);
//launch the whiteboard and turn off the signIn UI
} else if (clientCount < 4) {
isManager = false;
userName = user;
//launch the whiteboard and turn off the signIn UI
// launch the client
} else if (clientCount == 4) {
warningDialog("Fail to login In", "You can not join in this room!");
}
} else {
warningDialog(user + " is not existed!",
"You should confirm your username or register for " + user + " !");
}
}
public void signUp() throws Exception {
String userRegister = nameInput.getText();
String passwordRe = passWordInput.getText();
gsonServant.registerUser(userRegister, passwordRe);
if (isRegistered) {
warningDialog(userRegister + " is existed!", "Please change your username to register!");
} else {
inforDialog(userRegister);
}
}
private void inforDialog(String name) {
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("Registration");
alert.setHeaderText("Successful");
alert.setContentText("Congratulation! you can use " + name + " now!");
alert.showAndWait();
}
private void warningDialog(String header, String message) {
Alert alert = new Alert(Alert.AlertType.WARNING);
alert.setTitle("Warning");
alert.setHeaderText(header);
alert.setContentText(message);
alert.showAndWait();
}
private void errorDialog(String header, String message) {
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("Error");
alert.setHeaderText(header);
alert.setContentText(message);
alert.showAndWait();
}
}
|
package niagaraGUI;
import java.util.*;
public class QueryPlan {
private String filename;
static private Hashtable<String, OperatorTemplate> opTemplates;//Table of operator templates indexed by operator name
private List<Operator> opList;//List of operator Instances in the current query plan
private Operator top;//reference to the top operator
private String queryName;//name of the query
private DTDInterpreter dtdInterp;
public QueryPlan(String name, String filename) {
opTemplates = new Hashtable<String, OperatorTemplate>();
dtdInterp = new DTDInterpreter(filename);
opTemplates = dtdInterp.getTemplates();
opList = new ArrayList<Operator>();
}
static public Hashtable<String, OperatorTemplate> getOpTemplates() {
return opTemplates;
}
static public OperatorTemplate addTemplate(OperatorTemplate opTemplate) {
return opTemplates.put(opTemplate.getName(), opTemplate);
}
public void generateXML(String filename) {
}
public String[] getOperatorNames(){
if (opTemplates != null){
Set<String> opNameSet = opTemplates.keySet();
String[] opNameAry = new String[opNameSet.size()];
opNameAry = opNameSet.toArray(opNameAry);
return opNameAry;
}
else return null;
}
public void setName(String name) {
queryName = name;
}
public String getName() {
//returns the name of this query plan
return queryName;
}
public boolean addOperatorInstance(Operator newOp){
//Adds a new instansiated operator to this queryplan
if (opList.contains(newOp)){
return false;
}
else{
opList.add(newOp);
return true;
}
}
public boolean removeOperatorInstance(Operator toRemove){
//removes an instansiated from Operator from this query plan
if (opList.contains(toRemove)){
opList.remove(toRemove);
return true;
}
else{
return false;
}
}
// This design pattern is in place to ease future import if
// additional types are added
public Boolean parse(String filename) {
return parseDTD(filename);
}
public Boolean parse(String filename, String docType) {
if(docType == null) {
docType = "DTD";
}
if(docType == "DTD") {
return parseDTD(filename);
} else return false;
}
private Boolean parseDTD(String filename) {
return false;
}
public String toString() {
return null;
}
public void setTop(Operator newTop){
if (top != null){
top.isTop = false;
top = newTop;
top.isTop = true;
}
}
}
|
package com.intellij.openapi.vcs;
import com.intellij.ide.todo.TodoPanelSettings;
import com.intellij.openapi.components.*;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.progress.PerformInBackgroundOption;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.io.FileUtilRt;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vcs.versionBrowser.ChangeBrowserSettings;
import com.intellij.util.PlatformUtils;
import com.intellij.util.xmlb.XmlSerializerUtil;
import com.intellij.util.xmlb.annotations.OptionTag;
import com.intellij.util.xmlb.annotations.Property;
import com.intellij.util.xmlb.annotations.Transient;
import com.intellij.util.xmlb.annotations.XCollection;
import gnu.trove.THashMap;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
@State(
name = "VcsManagerConfiguration",
storages = @Storage(StoragePathMacros.WORKSPACE_FILE)
)
public final class VcsConfiguration implements PersistentStateComponent<VcsConfiguration> {
private static final Logger LOG = Logger.getInstance(VcsConfiguration.class);
public final static long ourMaximumFileForBaseRevisionSize = 500 * 1000;
@NonNls public static final String PATCH = "patch";
@NonNls public static final String DIFF = "diff";
public boolean OFFER_MOVE_TO_ANOTHER_CHANGELIST_ON_PARTIAL_COMMIT = false;
public boolean CHECK_CODE_SMELLS_BEFORE_PROJECT_COMMIT = !PlatformUtils.isPyCharm() && !PlatformUtils.isRubyMine();
public boolean CHECK_CODE_CLEANUP_BEFORE_PROJECT_COMMIT = false;
public boolean CHECK_NEW_TODO = true;
public TodoPanelSettings myTodoPanelSettings = new TodoPanelSettings();
public boolean PERFORM_UPDATE_IN_BACKGROUND = true;
public boolean PERFORM_COMMIT_IN_BACKGROUND = true;
public boolean PERFORM_EDIT_IN_BACKGROUND = true;
public boolean PERFORM_CHECKOUT_IN_BACKGROUND = true;
public boolean PERFORM_ADD_REMOVE_IN_BACKGROUND = true;
public boolean PERFORM_ROLLBACK_IN_BACKGROUND = false;
public volatile boolean CHECK_LOCALLY_CHANGED_CONFLICTS_IN_BACKGROUND = false;
@OptionTag(tag = "confirmMoveToFailedCommit", nameAttribute = "")
public VcsShowConfirmationOption.Value MOVE_TO_FAILED_COMMIT_CHANGELIST = VcsShowConfirmationOption.Value.DO_NOTHING_SILENTLY;
@OptionTag(tag = "confirmRemoveEmptyChangelist", nameAttribute = "")
public VcsShowConfirmationOption.Value REMOVE_EMPTY_INACTIVE_CHANGELISTS = VcsShowConfirmationOption.Value.SHOW_CONFIRMATION;
public int CHANGED_ON_SERVER_INTERVAL = 60;
public boolean SHOW_ONLY_CHANGED_IN_SELECTION_DIFF = true;
public String DEFAULT_PATCH_EXTENSION = PATCH;
public boolean USE_CUSTOM_SHELF_PATH = false;
public String CUSTOM_SHELF_PATH = null;
public boolean MOVE_SHELVES = false;
public boolean ADD_EXTERNAL_FILES_SILENTLY = false;
// asked only for non-DVCS
public boolean INCLUDE_TEXT_INTO_SHELF = true;
public Boolean SHOW_PATCH_IN_EXPLORER = null;
public boolean SHOW_FILE_HISTORY_DETAILS = true;
public boolean SHOW_DIRTY_RECURSIVELY = false;
public boolean LIMIT_HISTORY = true;
public int MAXIMUM_HISTORY_ROWS = 1000;
public String UPDATE_FILTER_SCOPE_NAME = null;
public boolean USE_COMMIT_MESSAGE_MARGIN = true;
public boolean WRAP_WHEN_TYPING_REACHES_RIGHT_MARGIN = false;
public boolean SHOW_UNVERSIONED_FILES_WHILE_COMMIT = true;
public boolean LOCAL_CHANGES_DETAILS_PREVIEW_SHOWN = true;
public boolean SHELVE_DETAILS_PREVIEW_SHOWN = false;
public boolean VCS_LOG_DETAILS_PREVIEW_SHOWN = false;
public boolean RELOAD_CONTEXT = true;
public boolean MARK_IGNORED_AS_EXCLUDED = false;
@XCollection(elementName = "path", propertyElementName = "ignored-roots")
public List<String> IGNORED_UNREGISTERED_ROOTS = new ArrayList<>();
public enum StandardOption {
ADD(VcsBundle.message("vcs.command.name.add")),
REMOVE(VcsBundle.message("vcs.command.name.remove")),
EDIT(VcsBundle.message("vcs.command.name.edit")),
CHECKOUT(VcsBundle.message("vcs.command.name.checkout")),
STATUS(VcsBundle.message("vcs.command.name.status")),
UPDATE(VcsBundle.message("vcs.command.name.update"));
StandardOption(final String id) {
myId = id;
}
private final String myId;
public String getId() {
return myId;
}
}
public enum StandardConfirmation {
ADD(VcsBundle.message("vcs.command.name.add")),
REMOVE(VcsBundle.message("vcs.command.name.remove"));
StandardConfirmation(@NotNull String id) {
myId = id;
}
@NotNull
private final String myId;
@NotNull
public String getId() {
return myId;
}
}
public boolean FORCE_NON_EMPTY_COMMENT = false;
public boolean CLEAR_INITIAL_COMMIT_MESSAGE = false;
@Property(surroundWithTag = false)
@XCollection(elementName = "MESSAGE")
public List<String> myLastCommitMessages = new ArrayList<>();
public String LAST_COMMIT_MESSAGE = null;
public boolean MAKE_NEW_CHANGELIST_ACTIVE = false;
public boolean PRESELECT_EXISTING_CHANGELIST = false;
public boolean OPTIMIZE_IMPORTS_BEFORE_PROJECT_COMMIT = false;
public boolean REFORMAT_BEFORE_PROJECT_COMMIT = false;
public boolean REARRANGE_BEFORE_PROJECT_COMMIT = false;
@Transient
public Map<String, ChangeBrowserSettings> changeBrowserSettings = new THashMap<>();
public boolean UPDATE_GROUP_BY_PACKAGES = false;
public boolean UPDATE_GROUP_BY_CHANGELIST = false;
public boolean UPDATE_FILTER_BY_SCOPE = false;
public boolean SHOW_FILE_HISTORY_AS_TREE = false;
public boolean GROUP_MULTIFILE_MERGE_BY_DIRECTORY = false;
private static final int MAX_STORED_MESSAGES = 25;
private final PerformInBackgroundOption myUpdateOption = new UpdateInBackgroundOption();
private final PerformInBackgroundOption myCommitOption = new CommitInBackgroundOption();
private final PerformInBackgroundOption myEditOption = new EditInBackgroundOption();
private final PerformInBackgroundOption myCheckoutOption = new CheckoutInBackgroundOption();
private final PerformInBackgroundOption myAddRemoveOption = new AddRemoveInBackgroundOption();
private final PerformInBackgroundOption myRollbackOption = new RollbackInBackgroundOption();
@Override
public VcsConfiguration getState() {
return this;
}
@Override
public void loadState(@NotNull VcsConfiguration state) {
XmlSerializerUtil.copyBean(state, this);
}
public static VcsConfiguration getInstance(@NotNull Project project) {
return ServiceManager.getService(project, VcsConfiguration.class);
}
public void saveCommitMessage(final String comment) {
LAST_COMMIT_MESSAGE = comment;
if (comment == null || comment.length() == 0) return;
myLastCommitMessages.remove(comment);
addCommitMessage(comment);
}
private void addCommitMessage(@NotNull String comment) {
if (myLastCommitMessages.size() >= MAX_STORED_MESSAGES) {
myLastCommitMessages.remove(0);
}
myLastCommitMessages.add(comment);
}
public String getLastNonEmptyCommitMessage() {
if (myLastCommitMessages.isEmpty()) {
return null;
}
else {
return myLastCommitMessages.get(myLastCommitMessages.size() - 1);
}
}
@NotNull
public ArrayList<String> getRecentMessages() {
return new ArrayList<>(myLastCommitMessages);
}
public void replaceMessage(@NotNull String oldMessage, @NotNull String newMessage) {
if (oldMessage.equals(LAST_COMMIT_MESSAGE)) {
LAST_COMMIT_MESSAGE = newMessage;
}
int index = myLastCommitMessages.indexOf(oldMessage);
if (index >= 0) {
myLastCommitMessages.remove(index);
myLastCommitMessages.add(index, newMessage);
}
else {
LOG.debug("Couldn't find message [" + oldMessage + "] in the messages history");
addCommitMessage(newMessage);
}
}
public PerformInBackgroundOption getUpdateOption() {
return myUpdateOption;
}
public PerformInBackgroundOption getCommitOption() {
return myCommitOption;
}
public PerformInBackgroundOption getEditOption() {
return myEditOption;
}
public PerformInBackgroundOption getCheckoutOption() {
return myCheckoutOption;
}
public PerformInBackgroundOption getAddRemoveOption() {
return myAddRemoveOption;
}
public PerformInBackgroundOption getRollbackOption() {
return myRollbackOption;
}
private class UpdateInBackgroundOption implements PerformInBackgroundOption {
@Override
public boolean shouldStartInBackground() {
return PERFORM_UPDATE_IN_BACKGROUND;
}
}
private class CommitInBackgroundOption implements PerformInBackgroundOption {
@Override
public boolean shouldStartInBackground() {
return PERFORM_COMMIT_IN_BACKGROUND;
}
}
private class EditInBackgroundOption implements PerformInBackgroundOption {
@Override
public boolean shouldStartInBackground() {
return PERFORM_EDIT_IN_BACKGROUND;
}
@Override
public void processSentToBackground() {
PERFORM_EDIT_IN_BACKGROUND = true;
}
}
private class CheckoutInBackgroundOption implements PerformInBackgroundOption {
@Override
public boolean shouldStartInBackground() {
return PERFORM_CHECKOUT_IN_BACKGROUND;
}
@Override
public void processSentToBackground() {
PERFORM_CHECKOUT_IN_BACKGROUND = true;
}
}
private class AddRemoveInBackgroundOption implements PerformInBackgroundOption {
@Override
public boolean shouldStartInBackground() {
return PERFORM_ADD_REMOVE_IN_BACKGROUND;
}
@Override
public void processSentToBackground() {
PERFORM_ADD_REMOVE_IN_BACKGROUND = true;
}
}
private class RollbackInBackgroundOption implements PerformInBackgroundOption {
@Override
public boolean shouldStartInBackground() {
return PERFORM_ROLLBACK_IN_BACKGROUND;
}
@Override
public void processSentToBackground() {
PERFORM_ROLLBACK_IN_BACKGROUND = true;
}
}
public String getPatchFileExtension() {
return DEFAULT_PATCH_EXTENSION;
}
public void acceptLastCreatedPatchName(final String string) {
if (StringUtil.isEmptyOrSpaces(string)) return;
if (FileUtilRt.extensionEquals(string, DIFF)) {
DEFAULT_PATCH_EXTENSION = DIFF;
}
else if (FileUtilRt.extensionEquals(string, PATCH)) {
DEFAULT_PATCH_EXTENSION = PATCH;
}
}
public boolean isChangedOnServerEnabled() {
return CHECK_LOCALLY_CHANGED_CONFLICTS_IN_BACKGROUND;
}
public void addIgnoredUnregisteredRoots(@NotNull Collection<String> roots) {
List<String> unregisteredRoots = new ArrayList<>(IGNORED_UNREGISTERED_ROOTS);
for (String root : roots) {
if (!unregisteredRoots.contains(root)) {
unregisteredRoots.add(root);
}
}
IGNORED_UNREGISTERED_ROOTS = unregisteredRoots;
}
public void removeFromIgnoredUnregisteredRoots(@NotNull Collection<String> roots) {
List<String> unregisteredRoots = new ArrayList<>(IGNORED_UNREGISTERED_ROOTS);
unregisteredRoots.removeAll(roots);
IGNORED_UNREGISTERED_ROOTS = unregisteredRoots;
}
public boolean isIgnoredUnregisteredRoot(@NotNull String root) {
return IGNORED_UNREGISTERED_ROOTS.contains(root);
}
}
|
package org.jetbrains.android.uipreview;
import com.android.SdkConstants;
import com.android.ide.common.rendering.api.RenderResources;
import com.android.ide.common.rendering.api.RenderSession;
import com.android.ide.common.rendering.api.Result;
import com.android.ide.common.resources.ResourceDeltaKind;
import com.android.ide.common.resources.ResourceFolder;
import com.android.ide.common.resources.ResourceRepository;
import com.android.ide.common.resources.ScanningContext;
import com.android.ide.common.resources.configuration.FolderConfiguration;
import com.android.ide.common.resources.configuration.VersionQualifier;
import com.android.io.IAbstractFile;
import com.android.io.IAbstractFolder;
import com.android.io.IAbstractResource;
import com.android.io.StreamException;
import com.android.sdklib.IAndroidTarget;
import com.intellij.compiler.impl.javaCompiler.javac.JavacConfiguration;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.compiler.CompilerManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.options.ShowSettingsUtil;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.projectRoots.JavaSdk;
import com.intellij.openapi.projectRoots.JavaSdkVersion;
import com.intellij.openapi.projectRoots.ProjectJdkTable;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.roots.ModuleRootManager;
import com.intellij.openapi.roots.ui.configuration.ClasspathEditor;
import com.intellij.openapi.roots.ui.configuration.ModulesConfigurator;
import com.intellij.openapi.roots.ui.configuration.ProjectStructureConfigurable;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.xml.XmlTag;
import com.intellij.util.containers.HashSet;
import org.jetbrains.android.dom.manifest.Application;
import org.jetbrains.android.dom.manifest.Manifest;
import org.jetbrains.android.facet.AndroidFacet;
import org.jetbrains.android.sdk.AndroidPlatform;
import org.jetbrains.android.sdk.AndroidSdkAdditionalData;
import org.jetbrains.android.sdk.AndroidSdkType;
import org.jetbrains.android.util.*;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.jps.model.java.compiler.JpsJavaCompilerOptions;
import org.xmlpull.v1.XmlPullParserException;
import javax.imageio.ImageIO;
import java.io.*;
import java.util.*;
/**
* @author Eugene.Kudelevsky
*/
public class RenderUtil {
private static final Logger LOG = Logger.getInstance("#org.jetbrains.android.uipreview.RenderUtil");
private static final String DEFAULT_APP_LABEL = "Android application";
private RenderUtil() {
}
@Nullable
public static RenderingResult renderLayout(@NotNull final Module module,
@NotNull String layoutXmlText,
@Nullable VirtualFile layoutXmlFile,
@Nullable String imgPath,
@NotNull IAndroidTarget target,
@NotNull AndroidFacet facet,
@NotNull FolderConfiguration config,
double xdpi,
double ydpi,
@NotNull ThemeData theme,
long timeout,
boolean checkTimeout)
throws RenderingException, IOException, AndroidSdkNotConfiguredException {
final Project project = module.getProject();
final Sdk sdk = ModuleRootManager.getInstance(facet.getModule()).getSdk();
if (sdk == null || !(sdk.getSdkType() instanceof AndroidSdkType)) {
throw new AndroidSdkNotConfiguredException();
}
final AndroidSdkAdditionalData data = (AndroidSdkAdditionalData)sdk.getSdkAdditionalData();
if (data == null) {
throw new AndroidSdkNotConfiguredException();
}
final AndroidPlatform platform = data.getAndroidPlatform();
if (platform == null) {
throw new AndroidSdkNotConfiguredException();
}
config.setVersionQualifier(new VersionQualifier(target.getVersion().getApiLevel()));
final RenderServiceFactory factory = platform.getSdkData().getTargetData(target).getRenderServiceFactory(project);
if (factory == null) {
throw new RenderingException(AndroidBundle.message("android.layout.preview.cannot.load.library.error"));
}
final List<AndroidFacet> allLibraries = AndroidUtils.getAllAndroidDependencies(module, true);
final List<ProjectResources> libResources = new ArrayList<ProjectResources>();
final List<ProjectResources> emptyResList = Collections.emptyList();
for (AndroidFacet libFacet : allLibraries) {
if (!libFacet.equals(facet)) {
libResources.add(loadProjectResources(libFacet, null, null, emptyResList));
}
}
final ProjectResources projectResources = loadProjectResources(facet, layoutXmlText, layoutXmlFile, libResources);
final int minSdkVersion = getMinSdkVersion(facet);
String missingRClassMessage = null;
boolean missingRClass = false;
boolean incorrectRClassFormat = false;
String rClassName = null;
final ProjectCallback callback = new ProjectCallback(factory.getLibrary(), facet.getModule(), projectResources);
try {
callback.loadAndParseRClass();
}
catch (ClassNotFoundException e) {
LOG.debug(e);
missingRClassMessage = e.getMessage();
missingRClass = true;
}
catch (IncompatibleClassFileFormatException e) {
LOG.debug(e);
incorrectRClassFormat = true;
rClassName = e.getClassName();
}
final Pair<RenderResources, RenderResources> pair =
factory.createResourceResolver(facet, config, projectResources, theme.getName(), theme.isProjectTheme());
final RenderService renderService = factory.createService(pair.getFirst(), pair.getSecond(), config, xdpi, ydpi, callback, minSdkVersion);
String appLabel = getAppLabelToShow(facet);
final List<FixableIssueMessage> warnMessages = new ArrayList<FixableIssueMessage>();
RenderSession session;
try {
while (true) {
final SimpleLogger logger = new SimpleLogger(project, LOG);
session = renderService
.createRenderSession(layoutXmlText, appLabel, timeout, logger);
if (checkTimeout && session.getResult().getStatus() == Result.Status.ERROR_TIMEOUT) {
continue;
}
warnMessages.addAll(logger.getMessages());
break;
}
}
catch (XmlPullParserException e) {
throw new RenderingException(e);
}
if (session == null) {
return null;
}
if (callback.hasUnsupportedClassVersionProblem() || (incorrectRClassFormat && callback.hasLoadedClasses())) {
reportIncorrectClassFormatWarning(callback, rClassName, incorrectRClassFormat, warnMessages);
}
if (missingRClass && callback.hasLoadedClasses()) {
final StringBuilder builder = new StringBuilder();
builder.append(missingRClassMessage != null && missingRClassMessage.length() > 0
? ("Class not found error: " + missingRClassMessage + ".")
: "R class not found.")
.append(" Try to build project");
warnMessages.add(new FixableIssueMessage(builder.toString()));
}
reportMissingClassesWarning(warnMessages, callback.getMissingClasses());
reportBrokenClassesWarning(project, warnMessages, callback.getBrokenClasses());
final Result result = session.getResult();
if (!result.isSuccess()) {
final Throwable exception = result.getException();
if (exception != null) {
final List<Throwable> exceptionsFromWarnings = getNonNullValues(callback.getBrokenClasses());
if (exception instanceof ClassCastException &&
(SdkConstants.CLASS_MOCK_VIEW + " cannot be cast to " + SdkConstants.CLASS_VIEWGROUP)
.equalsIgnoreCase(exception.getMessage())) {
throw new RenderingException(exceptionsFromWarnings.toArray(new Throwable[exceptionsFromWarnings.size()]))
.setWarnMessages(warnMessages);
}
throw new RenderingException(exception).setWarnMessages(warnMessages);
}
final String message = result.getErrorMessage();
if (message != null) {
LOG.info(message);
throw new RenderingException().setWarnMessages(warnMessages);
}
return null;
}
if (imgPath != null) {
final String format = FileUtil.getExtension(imgPath);
ImageIO.write(session.getImage(), format, new File(imgPath));
session.dispose();
session = null;
}
return new RenderingResult(warnMessages, session);
}
@NotNull
private static ProjectResources loadProjectResources(@NotNull AndroidFacet facet,
@Nullable String layoutXmlText,
@Nullable VirtualFile layoutXmlFile,
@NotNull List<ProjectResources> libResources)
throws IOException, RenderingException {
final VirtualFile resourceDir = facet.getLocalResourceManager().getResourceDir();
if (resourceDir != null) {
final IAbstractFolder resFolder = new BufferingFolderWrapper(new File(
FileUtil.toSystemDependentName(resourceDir.getPath())));
final ProjectResources projectResources = new ProjectResources(resFolder, libResources);
loadResources(projectResources, layoutXmlText, layoutXmlFile, resFolder);
return projectResources;
}
return new ProjectResources(new NullFolderWrapper(), libResources);
}
private static void reportBrokenClassesWarning(@NotNull final Project project,
@NotNull List<FixableIssueMessage> warnMessages,
@NotNull Map<String, Throwable> brokenClasses) {
if (brokenClasses.size() > 0) {
final List<Throwable> throwables = new ArrayList<Throwable>();
final List<String> brokenClassNames = new ArrayList<String>();
for (Map.Entry<String, Throwable> entry : brokenClasses.entrySet()) {
brokenClassNames.add(entry.getKey());
throwables.add(entry.getValue());
}
final Throwable[] throwableArray = throwables.toArray(new Throwable[throwables.size()]);
final StringBuilder builder = new StringBuilder();
builder.append("Unable to initialize:\n");
for (String className : brokenClassNames) {
builder.append(" ").append(className).append('\n');
}
removeLastNewLineChar(builder);
builder.append('\n');
warnMessages.add(new FixableIssueMessage(builder.toString(), Collections.singletonList(
Pair.<String, Runnable>create("Details", new Runnable() {
@Override
public void run() {
AndroidUtils.showStackStace(project, throwableArray);
}
}))));
}
}
private static void reportMissingClassesWarning(@NotNull List<FixableIssueMessage> warnMessages,
@NotNull Set<String> missingClasses) {
if (missingClasses.size() > 0) {
final StringBuilder builder = new StringBuilder();
builder.append("Missing classes:\n");
for (String missingClass : missingClasses) {
builder.append(" ").append(missingClass).append('\n');
}
builder.append("Try to build project");
warnMessages.add(new FixableIssueMessage(builder.toString()));
}
}
private static void reportIncorrectClassFormatWarning(@NotNull ProjectCallback callback,
@Nullable String rClassName,
boolean incorrectRClassFormat,
@NotNull List<FixableIssueMessage> warnMessages) {
final Module module = callback.getModule();
final Project project = module.getProject();
final List<Module> problemModules = getProblemModules(module);
final StringBuilder builder = new StringBuilder("Preview can be incorrect: unsupported classes version");
final List<Pair<String, Runnable>> quickFixes = new ArrayList<Pair<String, Runnable>>();
if (problemModules.size() > 0) {
quickFixes.add(new Pair<String, Runnable>("Rebuild project with '-target 1.6'", new Runnable() {
@Override
public void run() {
final JpsJavaCompilerOptions settings = JavacConfiguration.getOptions(project, JavacConfiguration.class);
if (settings.ADDITIONAL_OPTIONS_STRING.length() > 0) {
settings.ADDITIONAL_OPTIONS_STRING += ' ';
}
settings.ADDITIONAL_OPTIONS_STRING += "-target 1.6";
CompilerManager.getInstance(project).rebuild(null);
}
}));
quickFixes.add(new Pair<String, Runnable>("Change Java SDK to 1.5/1.6", new Runnable() {
@Override
public void run() {
final Set<String> sdkNames = getSdkNamesFromModules(problemModules);
if (sdkNames.size() == 1) {
final Sdk sdk = ProjectJdkTable.getInstance().findJdk(sdkNames.iterator().next());
if (sdk != null && sdk.getSdkType() instanceof AndroidSdkType) {
final ProjectStructureConfigurable config = ProjectStructureConfigurable.getInstance(project);
if (ShowSettingsUtil.getInstance().editConfigurable(project, config, new Runnable() {
public void run() {
config.select(sdk, true);
}
})) {
askAndRebuild(project);
}
return;
}
}
final String moduleToSelect = problemModules.size() > 0
? problemModules.iterator().next().getName()
: null;
if (ModulesConfigurator.showDialog(project, moduleToSelect, ClasspathEditor.NAME)) {
askAndRebuild(project);
}
}
}));
final Set<String> classesWithIncorrectFormat = new HashSet<String>(callback.getClassesWithIncorrectFormat());
if (incorrectRClassFormat && rClassName != null) {
classesWithIncorrectFormat.add(rClassName);
}
if (classesWithIncorrectFormat.size() > 0) {
quickFixes.add(new Pair<String, Runnable>("Details", new Runnable() {
@Override
public void run() {
showClassesWithIncorrectFormat(project, classesWithIncorrectFormat);
}
}));
}
builder.append("\nFollowing modules are built with incompatible JDK: ");
for (Iterator<Module> it = problemModules.iterator(); it.hasNext(); ) {
Module problemModule = it.next();
builder.append(problemModule.getName());
if (it.hasNext()) {
builder.append(", ");
}
}
}
warnMessages.add(new FixableIssueMessage(builder.toString(), quickFixes));
}
private static void showClassesWithIncorrectFormat(@NotNull Project project, @NotNull Set<String> classesWithIncorrectFormat) {
final StringBuilder builder = new StringBuilder("Classes with incompatible format:\n");
for (Iterator<String> it = classesWithIncorrectFormat.iterator(); it.hasNext(); ) {
builder.append(" ").append(it.next());
if (it.hasNext()) {
builder.append('\n');
}
}
Messages.showInfoMessage(project, builder.toString(), "Unsupported class version");
}
private static void askAndRebuild(Project project) {
final int r =
Messages.showYesNoDialog(project, "You have to rebuild project to see fixed preview. Would you like to do it?",
"Rebuild project", Messages.getQuestionIcon());
if (r == Messages.YES) {
CompilerManager.getInstance(project).rebuild(null);
}
}
@NotNull
private static Set<String> getSdkNamesFromModules(@NotNull Collection<Module> modules) {
final Set<String> result = new HashSet<String>();
for (Module module : modules) {
final Sdk sdk = ModuleRootManager.getInstance(module).getSdk();
if (sdk != null) {
result.add(sdk.getName());
}
}
return result;
}
@NotNull
private static List<Module> getProblemModules(@NotNull Module root) {
final List<Module> result = new ArrayList<Module>();
collectProblemModules(root, new HashSet<Module>(), result);
return result;
}
private static void collectProblemModules(@NotNull Module module, @NotNull Set<Module> visited, @NotNull Collection<Module> result) {
if (!visited.add(module)) {
return;
}
if (isBuiltByJdk7OrHigher(module)) {
result.add(module);
}
for (Module depModule : ModuleRootManager.getInstance(module).getDependencies(false)) {
collectProblemModules(depModule, visited, result);
}
}
private static boolean isBuiltByJdk7OrHigher(@NotNull Module module) {
Sdk sdk = ModuleRootManager.getInstance(module).getSdk();
if (sdk == null) {
return false;
}
if (sdk.getSdkType() instanceof AndroidSdkType) {
final AndroidSdkAdditionalData data = (AndroidSdkAdditionalData)sdk.getSdkAdditionalData();
if (data != null) {
final Sdk jdk = data.getJavaSdk();
if (jdk != null) {
sdk = jdk;
}
}
}
return sdk.getSdkType() instanceof JavaSdk &&
JavaSdk.getInstance().isOfVersionOrHigher(sdk, JavaSdkVersion.JDK_1_7);
}
private static void removeLastNewLineChar(StringBuilder builder) {
if (builder.length() > 0 && builder.charAt(builder.length() - 1) == '\n') {
builder.deleteCharAt(builder.length() - 1);
}
}
@NotNull
private static <T> List<T> getNonNullValues(@NotNull Map<?, T> map) {
final List<T> result = new ArrayList<T>();
for (Map.Entry<?, T> entry : map.entrySet()) {
final T value = entry.getValue();
if (value != null) {
result.add(value);
}
}
return result;
}
private static String getAppLabelToShow(final AndroidFacet facet) {
return ApplicationManager.getApplication().runReadAction(new Computable<String>() {
@Override
public String compute() {
final Manifest manifest = facet.getManifest();
if (manifest != null) {
final Application application = manifest.getApplication();
if (application != null) {
final String label = application.getLabel().getStringValue();
if (label != null) {
return label;
}
}
}
return DEFAULT_APP_LABEL;
}
});
}
private static int getMinSdkVersion(final AndroidFacet facet) {
final XmlTag manifestTag = ApplicationManager.getApplication().runReadAction(new Computable<XmlTag>() {
@Nullable
@Override
public XmlTag compute() {
final Manifest manifest = facet.getManifest();
return manifest != null ? manifest.getXmlTag() : null;
}
});
if (manifestTag != null) {
for (XmlTag usesSdkTag : manifestTag.findSubTags("uses-sdk")) {
final int candidate = AndroidUtils.getIntAttrValue(usesSdkTag, "minSdkVersion");
if (candidate >= 0) {
return candidate;
}
}
}
return -1;
}
public static void loadResources(@NotNull ResourceRepository repository,
@Nullable final String layoutXmlFileText,
@Nullable VirtualFile layoutXmlFile,
@NotNull IAbstractFolder... rootFolders) throws IOException, RenderingException {
final ScanningContext scanningContext = new ScanningContext(repository);
for (IAbstractFolder rootFolder : rootFolders) {
for (IAbstractResource file : rootFolder.listMembers()) {
if (!(file instanceof IAbstractFolder)) {
continue;
}
final IAbstractFolder folder = (IAbstractFolder)file;
final ResourceFolder resFolder = repository.processFolder(folder);
if (resFolder != null) {
for (final IAbstractResource childRes : folder.listMembers()) {
if (childRes instanceof IAbstractFile) {
final VirtualFile vFile;
if (childRes instanceof BufferingFileWrapper) {
final BufferingFileWrapper fileWrapper = (BufferingFileWrapper)childRes;
final String filePath = FileUtil.toSystemIndependentName(fileWrapper.getOsLocation());
vFile = LocalFileSystem.getInstance().findFileByPath(filePath);
if (vFile != null && Comparing.equal(vFile, layoutXmlFile) && layoutXmlFileText != null) {
resFolder.processFile(new MyFileWrapper(layoutXmlFileText, childRes), ResourceDeltaKind.ADDED, scanningContext);
}
else {
resFolder.processFile((IAbstractFile)childRes, ResourceDeltaKind.ADDED, scanningContext);
}
}
else {
LOG.error("childRes must be instance of " + BufferingFileWrapper.class.getName());
}
}
}
}
}
}
final List<String> errors = scanningContext.getErrors();
if (errors != null && errors.size() > 0) {
LOG.debug(new RenderingException(merge(errors)));
}
}
private static String merge(@NotNull Collection<String> strs) {
final StringBuilder result = new StringBuilder();
for (Iterator<String> it = strs.iterator(); it.hasNext(); ) {
String str = it.next();
result.append(str);
if (it.hasNext()) {
result.append('\n');
}
}
return result.toString();
}
@Nullable
public static String getRClassName(@NotNull final Module module) {
return ApplicationManager.getApplication().runReadAction(new Computable<String>() {
@Nullable
@Override
public String compute() {
final AndroidFacet facet = AndroidFacet.getInstance(module);
if (facet == null) {
return null;
}
final Manifest manifest = facet.getManifest();
if (manifest == null) {
return null;
}
final String aPackage = manifest.getPackage().getValue();
return aPackage == null ? null : aPackage + ".R";
}
});
}
private static class MyFileWrapper implements IAbstractFile {
private final String myLayoutXmlFileText;
private final IAbstractResource myChildRes;
public MyFileWrapper(String layoutXmlFileText, IAbstractResource childRes) {
myLayoutXmlFileText = layoutXmlFileText;
myChildRes = childRes;
}
@Override
public InputStream getContents() throws StreamException {
return new ByteArrayInputStream(myLayoutXmlFileText.getBytes());
}
@Override
public void setContents(InputStream source) throws StreamException {
throw new UnsupportedOperationException();
}
@Override
public OutputStream getOutputStream() throws StreamException {
throw new UnsupportedOperationException();
}
@Override
public PreferredWriteMode getPreferredWriteMode() {
throw new UnsupportedOperationException();
}
@Override
public long getModificationStamp() {
throw new UnsupportedOperationException();
}
@Override
public String getName() {
return myChildRes.getName();
}
@Override
public String getOsLocation() {
return myChildRes.getOsLocation();
}
@Override
public boolean exists() {
return true;
}
@Override
public IAbstractFolder getParentFolder() {
return myChildRes.getParentFolder();
}
@Override
public boolean delete() {
throw new UnsupportedOperationException();
}
}
}
|
package org.jgroups;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jgroups.conf.ConfiguratorFactory;
import org.jgroups.conf.ProtocolStackConfigurator;
import org.jgroups.stack.ProtocolStack;
import org.jgroups.stack.StateTransferInfo;
import org.jgroups.stack.IpAddress;
import org.jgroups.util.*;
import org.w3c.dom.Element;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;
/**
* JChannel is a pure Java implementation of Channel.
* When a JChannel object is instantiated it automatically sets up the
* protocol stack.
* <p>
* <B>Properties</B>
* <P>
* Properties are used to configure a channel, and are accepted in
* several forms; the String form is described here.
* A property string consists of a number of properties separated by
* colons. For example:
* <p>
* <pre>"<prop1>(arg1=val1):<prop2>(arg1=val1;arg2=val2):<prop3>:<propn>"</pre>
* <p>
* Each property relates directly to a protocol layer, which is
* implemented as a Java class. When a protocol stack is to be created
* based on the above property string, the first property becomes the
* bottom-most layer, the second one will be placed on the first, etc.:
* the stack is created from the bottom to the top, as the string is
* parsed from left to right. Each property has to be the name of a
* Java class that resides in the
* {@link org.jgroups.protocols} package.
* <p>
* Note that only the base name has to be given, not the fully specified
* class name (e.g., UDP instead of org.jgroups.protocols.UDP).
* <p>
* Each layer may have 0 or more arguments, which are specified as a
* list of name/value pairs in parentheses directly after the property.
* In the example above, the first protocol layer has 1 argument,
* the second 2, the third none. When a layer is created, these
* properties (if there are any) will be set in a layer by invoking
* the layer's setProperties() method
* <p>
* As an example the property string below instructs JGroups to create
* a JChannel with protocols UDP, PING, FD and GMS:<p>
* <pre>"UDP(mcast_addr=228.10.9.8;mcast_port=5678):PING:FD:GMS"</pre>
* <p>
* The UDP protocol layer is at the bottom of the stack, and it
* should use mcast address 228.10.9.8. and port 5678 rather than
* the default IP multicast address and port. The only other argument
* instructs FD to output debug information while executing.
* Property UDP refers to a class {@link org.jgroups.protocols.UDP},
* which is subsequently loaded and an instance of which is created as protocol layer.
* If any of these classes are not found, an exception will be thrown and
* the construction of the stack will be aborted.
*
* @author Bela Ban
* @version $Id: JChannel.java,v 1.93 2006/09/13 11:36:37 belaban Exp $
*/
public class JChannel extends Channel {
/**
* The default protocol stack used by the default constructor.
*/
public static final String DEFAULT_PROTOCOL_STACK=
"UDP(down_thread=false;mcast_send_buf_size=640000;mcast_port=45566;discard_incompatible_packets=true;" +
"ucast_recv_buf_size=20000000;mcast_addr=228.10.10.10;up_thread=false;loopback=false;" +
"mcast_recv_buf_size=25000000;max_bundle_size=64000;max_bundle_timeout=30;" +
"use_incoming_packet_handler=true;use_outgoing_packet_handler=false;" +
"ucast_send_buf_size=640000;tos=16;enable_bundling=true;ip_ttl=2):" +
"PING(timeout=2000;down_thread=false;num_initial_members=3;up_thread=false):" +
"MERGE2(max_interval=10000;down_thread=false;min_interval=5000;up_thread=false):" +
"FD(timeout=2000;max_tries=3;down_thread=false;up_thread=false):" +
"VERIFY_SUSPECT(timeout=1500;down_thread=false;up_thread=false):" +
"pbcast.NAKACK(max_xmit_size=60000;down_thread=false;use_mcast_xmit=false;gc_lag=0;" +
"discard_delivered_msgs=true;up_thread=false;retransmit_timeout=100,200,300,600,1200,2400,4800):" +
"UNICAST(timeout=300,600,1200,2400,3600;down_thread=false;up_thread=false):" +
"pbcast.STABLE(stability_delay=1000;desired_avg_gossip=50000;max_bytes=400000;down_thread=false;" +
"up_thread=false):" +
"VIEW_SYNC(down_thread=false;avg_send_interval=60000;up_thread=false):" +
"pbcast.GMS(print_local_addr=true;join_timeout=3000;down_thread=false;" +
"join_retry_timeout=2000;up_thread=false;shun=true):" +
"FC(max_credits=2000000;down_thread=false;up_thread=false;min_threshold=0.10):" +
"FRAG2(frag_size=60000;down_thread=false;up_thread=false):" +
"pbcast.STATE_TRANSFER(down_thread=false;up_thread=false)";
static final String FORCE_PROPS="force.properties";
/* the protocol stack configuration string */
private String props=null;
/*the address of this JChannel instance*/
private Address local_addr=null;
/*the channel (also know as group) name*/
private String cluster_name=null; // group name
/*the latest view of the group membership*/
private View my_view=null;
/*the queue that is used to receive messages (events) from the protocol stack*/
private final Queue mq=new Queue();
/*the protocol stack, used to send and receive messages from the protocol stack*/
private ProtocolStack prot_stack=null;
/** Thread responsible for closing a channel and potentially reconnecting to it (e.g., when shunned). */
protected CloserThread closer=null;
/** To wait until a local address has been assigned */
private final Promise local_addr_promise=new Promise();
/** To wait until we have connected successfully */
private final Promise connect_promise=new Promise();
/** To wait until we have been disconnected from the channel */
private final Promise disconnect_promise=new Promise();
private final Promise state_promise=new Promise();
private final Promise flush_promise=new Promise();
/** wait until we have a non-null local_addr */
private long LOCAL_ADDR_TIMEOUT=30000; //=Long.parseLong(System.getProperty("local_addr.timeout", "30000"));
/*if the states is fetched automatically, this is the default timeout, 5 secs*/
private static final long GET_STATE_DEFAULT_TIMEOUT=5000;
/*flag to indicate whether to receive blocks, if this is set to true, receive_views is set to true*/
private boolean receive_blocks=true;
/*flag to indicate whether to receive local messages
*if this is set to false, the JChannel will not receive messages sent by itself*/
private boolean receive_local_msgs=true;
/*flag to indicate whether the channel will reconnect (reopen) when the exit message is received*/
private boolean auto_reconnect=false;
/*flag t indicate whether the state is supposed to be retrieved after the channel is reconnected
*setting this to true, automatically forces auto_reconnect to true*/
private boolean auto_getstate=false;
/*channel connected flag*/
protected boolean connected=false;
/*channel closed flag*/
protected boolean closed=false; // close() has been called, channel is unusable
/** True if a state transfer protocol is available, false otherwise */
private boolean state_transfer_supported=false; // set by CONFIG event from STATE_TRANSFER protocol
/** True if a flush protocol is available, false otherwise */
private volatile boolean flush_supported=false; // set by CONFIG event from FLUSH protocol
/** Used to maintain additional data across channel disconnects/reconnects. This is a kludge and will be remove
* as soon as JGroups supports logical addresses
*/
private byte[] additional_data=null;
protected final Log log=LogFactory.getLog(getClass());
/** Collect statistics */
protected boolean stats=true;
protected long sent_msgs=0, received_msgs=0, sent_bytes=0, received_bytes=0;
/** Used by subclass to create a JChannel without a protocol stack, don't use as application programmer */
protected JChannel(boolean no_op) {
;
}
/**
* Constructs a <code>JChannel</code> instance with the protocol stack
* specified by the <code>DEFAULT_PROTOCOL_STACK</code> member.
*
* @throws ChannelException if problems occur during the initialization of
* the protocol stack.
*/
public JChannel() throws ChannelException {
this(DEFAULT_PROTOCOL_STACK);
}
/**
* Constructs a <code>JChannel</code> instance with the protocol stack
* configuration contained by the specified file.
*
* @param properties a file containing a JGroups XML protocol stack
* configuration.
*
* @throws ChannelException if problems occur during the configuration or
* initialization of the protocol stack.
*/
public JChannel(File properties) throws ChannelException {
this(ConfiguratorFactory.getStackConfigurator(properties));
}
/**
* Constructs a <code>JChannel</code> instance with the protocol stack
* configuration contained by the specified XML element.
*
* @param properties a XML element containing a JGroups XML protocol stack
* configuration.
*
* @throws ChannelException if problems occur during the configuration or
* initialization of the protocol stack.
*/
public JChannel(Element properties) throws ChannelException {
this(ConfiguratorFactory.getStackConfigurator(properties));
}
/**
* Constructs a <code>JChannel</code> instance with the protocol stack
* configuration indicated by the specified URL.
*
* @param properties a URL pointing to a JGroups XML protocol stack
* configuration.
*
* @throws ChannelException if problems occur during the configuration or
* initialization of the protocol stack.
*/
public JChannel(URL properties) throws ChannelException {
this(ConfiguratorFactory.getStackConfigurator(properties));
}
/**
* Constructs a <code>JChannel</code> instance with the protocol stack
* configuration based upon the specified properties parameter.
*
* @param properties an old style property string, a string representing a
* system resource containing a JGroups XML configuration,
* a string representing a URL pointing to a JGroups XML
* XML configuration, or a string representing a file name
* that contains a JGroups XML configuration.
*
* @throws ChannelException if problems occur during the configuration and
* initialization of the protocol stack.
*/
public JChannel(String properties) throws ChannelException {
this(ConfiguratorFactory.getStackConfigurator(properties));
}
/**
* Constructs a <code>JChannel</code> instance with the protocol stack
* configuration contained by the protocol stack configurator parameter.
* <p>
* All of the public constructors of this class eventually delegate to this
* method.
*
* @param configurator a protocol stack configurator containing a JGroups
* protocol stack configuration.
*
* @throws ChannelException if problems occur during the initialization of
* the protocol stack.
*/
protected JChannel(ProtocolStackConfigurator configurator) throws ChannelException {
init(configurator);
}
/**
* Creates a new JChannel with the protocol stack as defined in the properties
* parameter. an example of this parameter is<BR>
* "UDP:PING:FD:STABLE:NAKACK:UNICAST:FRAG:FLUSH:GMS:VIEW_ENFORCER:STATE_TRANSFER:QUEUE"<BR>
* Other examples can be found in the ./conf directory<BR>
* @param properties the protocol stack setup; if null, the default protocol stack will be used.
* The properties can also be a java.net.URL object or a string that is a URL spec.
* The JChannel will validate any URL object and String object to see if they are a URL.
* In case of the parameter being a url, the JChannel will try to load the xml from there.
* In case properties is a org.w3c.dom.Element, the ConfiguratorFactory will parse the
* DOM tree with the element as its root element.
* @deprecated Use the constructors with specific parameter types instead.
*/
public JChannel(Object properties) throws ChannelException {
if (properties == null)
properties = DEFAULT_PROTOCOL_STACK;
ProtocolStackConfigurator c=null;
try {
c=ConfiguratorFactory.getStackConfigurator(properties);
}
catch(Exception x) {
throw new ChannelException("unable to load protocol stack", x);
}
init(c);
}
/**
* Returns the protocol stack.
* Currently used by Debugger.
* Specific to JChannel, therefore
* not visible in Channel
*/
public ProtocolStack getProtocolStack() {
return prot_stack;
}
protected Log getLog() {
return log;
}
/**
* returns the protocol stack configuration in string format.
* an example of this property is<BR>
* "UDP:PING:FD:STABLE:NAKACK:UNICAST:FRAG:FLUSH:GMS:VIEW_ENFORCER:STATE_TRANSFER:QUEUE"
*/
public String getProperties() {
return props;
}
public boolean statsEnabled() {
return stats;
}
public void enableStats(boolean stats) {
this.stats=stats;
}
public void resetStats() {
sent_msgs=received_msgs=sent_bytes=received_bytes=0;
}
public long getSentMessages() {return sent_msgs;}
public long getSentBytes() {return sent_bytes;}
public long getReceivedMessages() {return received_msgs;}
public long getReceivedBytes() {return received_bytes;}
public int getNumberOfTasksInTimer() {return prot_stack != null ? prot_stack.timer.size() : -1;}
public String dumpTimerQueue() {
return prot_stack != null? prot_stack.dumpTimerQueue() : "<n/a";
}
/**
* Returns a pretty-printed form of all the protocols. If include_properties is set,
* the properties for each protocol will also be printed.
*/
public String printProtocolSpec(boolean include_properties) {
return prot_stack != null ? prot_stack.printProtocolSpec(include_properties) : null;
}
/**
* Connects the channel to a group.
* If the channel is already connected, an error message will be printed to the error log.
* If the channel is closed a ChannelClosed exception will be thrown.
* This method starts the protocol stack by calling ProtocolStack.start,
* then it sends an Event.CONNECT event down the stack and waits to receive a CONNECT_OK event.
* Once the CONNECT_OK event arrives from the protocol stack, any channel listeners are notified
* and the channel is considered connected.
*
* @param cluster_name A <code>String</code> denoting the group name. Cannot be null.
* @exception ChannelException The protocol stack cannot be started
* @exception ChannelClosedException The channel is closed and therefore cannot be used any longer.
* A new channel has to be created first.
*/
public synchronized void connect(String cluster_name) throws ChannelException, ChannelClosedException {
/*make sure the channel is not closed*/
checkClosed();
/*if we already are connected, then ignore this*/
if(connected) {
if(log.isTraceEnabled()) log.trace("already connected to " + cluster_name);
return;
}
/*make sure we have a valid channel name*/
if(cluster_name == null) {
if(log.isInfoEnabled()) log.info("cluster_name is null, assuming unicast channel");
}
else
this.cluster_name=cluster_name;
try {
prot_stack.startStack(); // calls start() in all protocols, from top to bottom
}
catch(Throwable e) {
throw new ChannelException("failed to start protocol stack", e);
}
String tmp=Util.getProperty(new String[]{Global.CHANNEL_LOCAL_ADDR_TIMEOUT, "local_addr.timeout"},
null, null, false, "30000");
LOCAL_ADDR_TIMEOUT=Long.parseLong(tmp);
/* Wait LOCAL_ADDR_TIMEOUT milliseconds for local_addr to have a non-null value (set by SET_LOCAL_ADDRESS) */
local_addr=(Address)local_addr_promise.getResult(LOCAL_ADDR_TIMEOUT);
if(local_addr == null) {
log.fatal("local_addr is null; cannot connect");
throw new ChannelException("local_addr is null");
}
/*create a temporary view, assume this channel is the only member and
*is the coordinator*/
Vector t=new Vector(1);
t.addElement(local_addr);
my_view=new View(local_addr, 0, t); // create a dummy view
// only connect if we are not a unicast channel
if(cluster_name != null) {
connect_promise.reset();
Event connect_event=new Event(Event.CONNECT, cluster_name);
down(connect_event);
Object res=connect_promise.getResult(); // waits forever until connected (or channel is closed)
if(res != null && res instanceof Exception) { // the JOIN was rejected by the coordinator
throw new ChannelException("connect() failed", (Throwable)res);
}
}
/*notify any channel listeners*/
connected=true;
notifyChannelConnected(this);
}
public synchronized boolean connect(String cluster_name, Address target, String state_id, long timeout) throws ChannelException {
throw new UnsupportedOperationException("not yet implemented");
}
/**
* Disconnects the channel if it is connected. If the channel is closed, this operation is ignored<BR>
* Otherwise the following actions happen in the listed order<BR>
* <ol>
* <li> The JChannel sends a DISCONNECT event down the protocol stack<BR>
* <li> Blocks until the channel to receives a DISCONNECT_OK event<BR>
* <li> Sends a STOP_QUEING event down the stack<BR>
* <li> Stops the protocol stack by calling ProtocolStack.stop()<BR>
* <li> Notifies the listener, if the listener is available<BR>
* </ol>
*/
public synchronized void disconnect() {
if(closed) return;
if(connected) {
if(cluster_name != null) {
/* Send down a DISCONNECT event. The DISCONNECT event travels down to the GMS, where a
* DISCONNECT_OK response is generated and sent up the stack. JChannel blocks until a
* DISCONNECT_OK has been received, or until timeout has elapsed.
*/
Event disconnect_event=new Event(Event.DISCONNECT, local_addr);
disconnect_promise.reset();
down(disconnect_event); // DISCONNECT is handled by each layer
disconnect_promise.getResult(); // wait for DISCONNECT_OK
}
// Just in case we use the QUEUE protocol and it is still blocked...
down(new Event(Event.STOP_QUEUEING));
connected=false;
try {
prot_stack.stopStack(); // calls stop() in all protocols, from top to bottom
}
catch(Exception e) {
if(log.isErrorEnabled()) log.error("exception: " + e);
}
notifyChannelDisconnected(this);
init(); // sets local_addr=null; changed March 18 2003 (bela) -- prevented successful rejoining
}
}
/**
* Destroys the channel.
* After this method has been called, the channel us unusable.<BR>
* This operation will disconnect the channel and close the channel receive queue immediately<BR>
*/
public synchronized void close() {
_close(true, true); // by default disconnect before closing channel and close mq
}
/** Shuts down the channel without disconnecting */
public synchronized void shutdown() {
_close(false, true); // by default disconnect before closing channel and close mq
}
/**
* Opens the channel.
* This does the following actions:
* <ol>
* <li> Resets the receiver queue by calling Queue.reset
* <li> Sets up the protocol stack by calling ProtocolStack.setup
* <li> Sets the closed flag to false
* </ol>
*/
public synchronized void open() throws ChannelException {
if(!closed)
throw new ChannelException("channel is already open");
try {
mq.reset();
prot_stack=new ProtocolStack(this, props);
prot_stack.setup();
closed=false;
}
catch(Exception e) {
throw new ChannelException("failed to open channel" , e);
}
}
/**
* returns true if the Open operation has been called successfully
*/
public boolean isOpen() {
return !closed;
}
/**
* returns true if the Connect operation has been called successfully
*/
public boolean isConnected() {
return connected;
}
public int getNumMessages() {
return mq != null? mq.size() : -1;
}
public String dumpQueue() {
return Util.dumpQueue(mq);
}
/**
* Returns a map of statistics of the various protocols and of the channel itself.
* @return Map<String,Map>. A map where the keys are the protocols ("channel" pseudo key is
* used for the channel itself") and the values are property maps.
*/
public Map dumpStats() {
Map retval=prot_stack.dumpStats();
if(retval != null) {
Map tmp=dumpChannelStats();
if(tmp != null)
retval.put("channel", tmp);
}
return retval;
}
private Map dumpChannelStats() {
Map retval=new HashMap();
retval.put("sent_msgs", new Long(sent_msgs));
retval.put("sent_bytes", new Long(sent_bytes));
retval.put("received_msgs", new Long(received_msgs));
retval.put("received_bytes", new Long(received_bytes));
return retval;
}
/**
* Sends a message through the protocol stack.
* Implements the Transport interface.
*
* @param msg the message to be sent through the protocol stack,
* the destination of the message is specified inside the message itself
* @exception ChannelNotConnectedException
* @exception ChannelClosedException
*/
public void send(Message msg) throws ChannelNotConnectedException, ChannelClosedException {
checkClosed();
checkNotConnected();
if(stats) {
sent_msgs++;
sent_bytes+=msg.getLength();
}
if(msg == null)
throw new NullPointerException("msg is null");
down(new Event(Event.MSG, msg));
}
/**
* creates a new message with the destination address, and the source address
* and the object as the message value
* @param dst - the destination address of the message, null for all members
* @param src - the source address of the message
* @param obj - the value of the message
* @exception ChannelNotConnectedException
* @exception ChannelClosedException
* @see JChannel#send
*/
public void send(Address dst, Address src, Serializable obj) throws ChannelNotConnectedException, ChannelClosedException {
send(new Message(dst, src, obj));
}
/**
* Blocking receive method.
* This method returns the object that was first received by this JChannel and that has not been
* received before. After the object is received, it is removed from the receive queue.<BR>
* If you only want to inspect the object received without removing it from the queue call
* JChannel.peek<BR>
* If no messages are in the receive queue, this method blocks until a message is added or the operation times out<BR>
* By specifying a timeout of 0, the operation blocks forever, or until a message has been received.
* @param timeout the number of milliseconds to wait if the receive queue is empty. 0 means wait forever
* @exception TimeoutException if a timeout occured prior to a new message was received
* @exception ChannelNotConnectedException
* @exception ChannelClosedException
* @see JChannel#peek
*/
public Object receive(long timeout) throws ChannelNotConnectedException, ChannelClosedException, TimeoutException {
checkClosed();
checkNotConnected();
try {
Event evt=(timeout <= 0)? (Event)mq.remove() : (Event)mq.remove(timeout);
Object retval=getEvent(evt);
evt=null;
if(stats) {
if(retval != null && retval instanceof Message) {
received_msgs++;
received_bytes+=((Message)retval).getLength();
}
}
return retval;
}
catch(QueueClosedException queue_closed) {
throw new ChannelClosedException();
}
catch(TimeoutException t) {
throw t;
}
catch(Exception e) {
if(log.isErrorEnabled()) log.error("exception: " + e);
return null;
}
}
/**
* Just peeks at the next message, view or block. Does <em>not</em> install
* new view if view is received<BR>
* Does the same thing as JChannel.receive but doesn't remove the object from the
* receiver queue
*/
public Object peek(long timeout) throws ChannelNotConnectedException, ChannelClosedException, TimeoutException {
checkClosed();
checkNotConnected();
try {
Event evt=(timeout <= 0)? (Event)mq.peek() : (Event)mq.peek(timeout);
Object retval=getEvent(evt);
evt=null;
return retval;
}
catch(QueueClosedException queue_closed) {
if(log.isErrorEnabled()) log.error("exception: " + queue_closed);
return null;
}
catch(TimeoutException t) {
return null;
}
catch(Exception e) {
if(log.isErrorEnabled()) log.error("exception: " + e);
return null;
}
}
/**
* Returns the current view.
* <BR>
* If the channel is not connected or if it is closed it will return null.
* <BR>
* @return returns the current group view, or null if the channel is closed or disconnected
*/
public View getView() {
return closed || !connected ? null : my_view;
}
/**
* returns the local address of the channel
* returns null if the channel is closed
*/
public Address getLocalAddress() {
return closed ? null : local_addr;
}
/**
* returns the name of the channel
* if the channel is not connected or if it is closed it will return null
* @deprecated Use {@link #getClusterName()} instead
*/
public String getChannelName() {
return closed ? null : !connected ? null : cluster_name;
}
public String getClusterName() {
return cluster_name;
}
/**
* Sets a channel option. The options can be one of the following:
* <UL>
* <LI> Channel.BLOCK
* <LI> Channel.LOCAL
* <LI> Channel.AUTO_RECONNECT
* <LI> Channel.AUTO_GETSTATE
* </UL>
* <P>
* There are certain dependencies between the options that you can set,
* I will try to describe them here.
* <P>
* Option: Channel.BLOCK<BR>
* Value: java.lang.Boolean<BR>
* Result: set to true will set setOpt(VIEW, true) and the JChannel will receive BLOCKS and VIEW events<BR>
*<BR>
* Option: LOCAL<BR>
* Value: java.lang.Boolean<BR>
* Result: set to true the JChannel will receive messages that it self sent out.<BR>
*<BR>
* Option: AUTO_RECONNECT<BR>
* Value: java.lang.Boolean<BR>
* Result: set to true and the JChannel will try to reconnect when it is being closed<BR>
*<BR>
* Option: AUTO_GETSTATE<BR>
* Value: java.lang.Boolean<BR>
* Result: set to true, the AUTO_RECONNECT will be set to true and the JChannel will try to get the state after a close and reconnect happens<BR>
* <BR>
*
* @param option the parameter option Channel.VIEW, Channel.SUSPECT, etc
* @param value the value to set for this option
*
*/
public void setOpt(int option, Object value) {
if(closed) {
if(log.isWarnEnabled()) log.warn("channel is closed; option not set !");
return;
}
switch(option) {
case VIEW:
if(log.isWarnEnabled())
log.warn("option VIEW has been deprecated (it is always true now); this option is ignored");
break;
case SUSPECT:
if(log.isWarnEnabled())
log.warn("option SUSPECT has been deprecated (it is always true now); this option is ignored");
break;
case BLOCK:
if(value instanceof Boolean)
receive_blocks=((Boolean)value).booleanValue();
else
if(log.isErrorEnabled()) log.error("option " + Channel.option2String(option) +
" (" + value + "): value has to be Boolean");
break;
case GET_STATE_EVENTS:
if(log.isWarnEnabled())
log.warn("option GET_STATE_EVENTS has been deprecated (it is always true now); this option is ignored");
break;
case LOCAL:
if(value instanceof Boolean)
receive_local_msgs=((Boolean)value).booleanValue();
else
if(log.isErrorEnabled()) log.error("option " + Channel.option2String(option) +
" (" + value + "): value has to be Boolean");
break;
case AUTO_RECONNECT:
if(value instanceof Boolean)
auto_reconnect=((Boolean)value).booleanValue();
else
if(log.isErrorEnabled()) log.error("option " + Channel.option2String(option) +
" (" + value + "): value has to be Boolean");
break;
case AUTO_GETSTATE:
if(value instanceof Boolean) {
auto_getstate=((Boolean)value).booleanValue();
if(auto_getstate)
auto_reconnect=true;
}
else
if(log.isErrorEnabled()) log.error("option " + Channel.option2String(option) +
" (" + value + "): value has to be Boolean");
break;
default:
if(log.isErrorEnabled()) log.error("option " + Channel.option2String(option) + " not known");
break;
}
}
/**
* returns the value of an option.
* @param option the option you want to see the value for
* @return the object value, in most cases java.lang.Boolean
* @see JChannel#setOpt
*/
public Object getOpt(int option) {
switch(option) {
case VIEW:
return Boolean.TRUE;
case BLOCK:
return receive_blocks ? Boolean.TRUE : Boolean.FALSE;
case SUSPECT:
return Boolean.TRUE;
case AUTO_RECONNECT:
return auto_reconnect ? Boolean.TRUE : Boolean.FALSE;
case AUTO_GETSTATE:
return auto_getstate ? Boolean.TRUE : Boolean.FALSE;
case GET_STATE_EVENTS:
return Boolean.TRUE;
case LOCAL:
return receive_local_msgs ? Boolean.TRUE : Boolean.FALSE;
default:
if(log.isErrorEnabled()) log.error("option " + Channel.option2String(option) + " not known");
return null;
}
}
/**
* Called to acknowledge a block() (callback in <code>MembershipListener</code> or
* <code>BlockEvent</code> received from call to <code>receive()</code>).
* After sending blockOk(), no messages should be sent until a new view has been received.
* Calling this method on a closed channel has no effect.
*/
public void blockOk() {
down(new Event(Event.BLOCK_OK));
down(new Event(Event.START_QUEUEING));
}
/**
* Retrieves the current group state. Sends GET_STATE event down to STATE_TRANSFER layer.
* Blocks until STATE_TRANSFER sends up a GET_STATE_OK event or until <code>timeout</code>
* milliseconds have elapsed. The argument of GET_STATE_OK should be a single object.
* @param target the target member to receive the state from. if null, state is retrieved from coordinator
* @param timeout the number of milliseconds to wait for the operation to complete successfully. 0 waits until
* the state has been received
* @return true of the state was received, false if the operation timed out
*/
public boolean getState(Address target, long timeout) throws ChannelNotConnectedException, ChannelClosedException {
return getState(target,null,timeout);
}
/**
* Retrieves a substate (or partial state) from the target.
* @param target State provider. If null, coordinator is used
* @param state_id The ID of the substate. If null, the entire state will be transferred
* @param timeout the number of milliseconds to wait for the operation to complete successfully. 0 waits until
* the state has been received
* @return
* @throws ChannelNotConnectedException
* @throws ChannelClosedException
*/
public boolean getState(Address target, String state_id, long timeout) throws ChannelNotConnectedException, ChannelClosedException {
if(target == null)
target=determineCoordinator();
if(target != null && local_addr != null && target.equals(local_addr)) {
if(log.isTraceEnabled())
log.trace("cannot get state from myself (" + target + "): probably the first member");
return false;
}
StateTransferInfo info=new StateTransferInfo(target, state_id, timeout);
boolean rc=_getState(new Event(Event.GET_STATE, info), info);
if(rc == false)
down(new Event(Event.RESUME_STABLE));
return rc;
}
/**
* Retrieves the current group state. Sends GET_STATE event down to STATE_TRANSFER layer.
* Blocks until STATE_TRANSFER sends up a GET_STATE_OK event or until <code>timeout</code>
* milliseconds have elapsed. The argument of GET_STATE_OK should be a vector of objects.
* @param targets - the target members to receive the state from ( an Address list )
* @param timeout - the number of milliseconds to wait for the operation to complete successfully
* @return true of the state was received, false if the operation timed out
* @deprecated Not really needed - we always want to get the state from a single member,
* use {@link #getState(org.jgroups.Address, long)} instead
*/
public boolean getAllStates(Vector targets, long timeout) throws ChannelNotConnectedException, ChannelClosedException {
throw new UnsupportedOperationException("use getState() instead");
}
/**
* Called by the application is response to receiving a <code>getState()</code> object when
* calling <code>receive()</code>.
* When the application receives a getState() message on the receive() method,
* it should call returnState() to reply with the state of the application
* @param state The state of the application as a byte buffer
* (to send over the network).
*/
public void returnState(byte[] state) {
StateTransferInfo info=new StateTransferInfo(null, null, 0L, state);
down(new Event(Event.GET_APPLSTATE_OK, info));
}
/**
* Returns a substate as indicated by state_id
* @param state
* @param state_id
*/
public void returnState(byte[] state, String state_id) {
StateTransferInfo info=new StateTransferInfo(null, state_id, 0L, state);
down(new Event(Event.GET_APPLSTATE_OK, info));
}
/**
* Callback method <BR>
* Called by the ProtocolStack when a message is received.
* It will be added to the message queue from which subsequent
* <code>Receive</code>s will dequeue it.
* @param evt the event carrying the message from the protocol stack
*/
public void up(Event evt) {
int type=evt.getType();
Message msg;
switch(type) {
case Event.MSG:
msg=(Message)evt.getArg();
if(!receive_local_msgs) { // discard local messages (sent by myself to me)
if(local_addr != null && msg.getSrc() != null)
if(local_addr.equals(msg.getSrc()))
return;
}
break;
case Event.VIEW_CHANGE:
View tmp=(View)evt.getArg();
if(tmp instanceof MergeView)
my_view=new View(tmp.getVid(), tmp.getMembers());
else
my_view=tmp;
// crude solution to bug #775120: if we get our first view *before* the CONNECT_OK,
// we simply set the state to connected
if(connected == false) {
connected=true;
connect_promise.setResult(null);
}
// unblock queueing of messages due to previous BLOCK event:
down(new Event(Event.STOP_QUEUEING));
break;
case Event.CONFIG:
HashMap config=(HashMap)evt.getArg();
if(config != null) {
if(config.containsKey("state_transfer")) {
state_transfer_supported=((Boolean)config.get("state_transfer")).booleanValue();
}
if(config.containsKey("flush_supported")) {
flush_supported=((Boolean)config.get("flush_supported")).booleanValue();
}
}
break;
case Event.BLOCK:
// If BLOCK is received by application, then we trust the application to not send
// any more messages until a VIEW_CHANGE is received. Otherwise (BLOCKs are disabled),
// we queue any messages sent until the next VIEW_CHANGE (they will be sent in the
// next view)
if(!receive_blocks) { // discard if client has not set 'receiving blocks' to 'on'
down(new Event(Event.BLOCK_OK));
down(new Event(Event.START_QUEUEING));
return;
}
break;
case Event.CONNECT_OK:
connect_promise.setResult(evt.getArg());
break;
case Event.SUSPEND_OK:
flush_promise.setResult(Boolean.TRUE);
break;
case Event.DISCONNECT_OK:
disconnect_promise.setResult(Boolean.TRUE);
break;
case Event.GET_STATE_OK:
StateTransferInfo info=(StateTransferInfo)evt.getArg();
byte[] state=info.state;
state_promise.setResult(state != null? Boolean.TRUE : Boolean.FALSE);
if(up_handler != null) {
up_handler.up(evt);
return;
}
if(state != null) {
String state_id=info.state_id;
if(receiver != null) {
if(receiver instanceof ExtendedReceiver && state_id!=null)
((ExtendedReceiver)receiver).setState(state_id, state);
else
receiver.setState(state);
}
else {
try {mq.add(new Event(Event.STATE_RECEIVED, info));} catch(Exception e) {}
}
}
break;
case Event.STATE_TRANSFER_INPUTSTREAM:
StateTransferInfo sti=(StateTransferInfo)evt.getArg();
InputStream is=sti.inputStream;
state_promise.setResult(is != null? Boolean.TRUE : Boolean.FALSE);
if(up_handler != null) {
up_handler.up(evt);
return;
}
if(is != null) {
if(receiver instanceof ExtendedReceiver) {
if(sti.state_id == null)
((ExtendedReceiver)receiver).setState(is);
else
((ExtendedReceiver)receiver).setState(sti.state_id, is);
}
else {
try {
mq.add(new Event(Event.STATE_TRANSFER_INPUTSTREAM, sti));
}
catch(Exception e) {
}
}
}
break;
case Event.SET_LOCAL_ADDRESS:
local_addr_promise.setResult(evt.getArg());
break;
case Event.EXIT:
handleExit(evt);
return; // no need to pass event up; already done in handleExit()
default:
break;
}
// If UpHandler is installed, pass all events to it and return (UpHandler is e.g. a building block)
if(up_handler != null) {
up_handler.up(evt);
return;
}
switch(type) {
case Event.MSG:
if(receiver != null) {
receiver.receive((Message)evt.getArg());
return;
}
break;
case Event.VIEW_CHANGE:
if(receiver != null) {
receiver.viewAccepted((View)evt.getArg());
return;
}
break;
case Event.SUSPECT:
if(receiver != null) {
receiver.suspect((Address)evt.getArg());
return;
}
break;
case Event.GET_APPLSTATE:
if(receiver != null) {
StateTransferInfo info=(StateTransferInfo)evt.getArg();
byte[] tmp_state;
String state_id=info.state_id;
if(receiver instanceof ExtendedReceiver && state_id!=null) {
tmp_state=((ExtendedReceiver)receiver).getState(state_id);
}
else {
tmp_state=receiver.getState();
}
returnState(tmp_state, state_id);
return;
}
break;
case Event.STATE_TRANSFER_OUTPUTSTREAM:
if(receiver != null) {
StateTransferInfo sti=(StateTransferInfo)evt.getArg();
OutputStream os=sti.outputStream;
if(os != null && receiver instanceof ExtendedReceiver) {
if(sti.state_id == null)
((ExtendedReceiver)receiver).getState(os);
else
((ExtendedReceiver)receiver).getState(sti.state_id, os);
}
return;
}
break;
case Event.BLOCK:
if(receiver != null) {
receiver.block();
return;
}
break;
default:
break;
}
if(type == Event.MSG || type == Event.VIEW_CHANGE || type == Event.SUSPECT ||
type == Event.GET_APPLSTATE || type== Event.STATE_TRANSFER_OUTPUTSTREAM
|| type == Event.BLOCK) {
try {
mq.add(evt);
}
catch(Exception e) {
if(log.isErrorEnabled()) log.error("exception adding event " + evt + " to message queue", e);
}
}
}
/**
* Sends a message through the protocol stack if the stack is available
* @param evt the message to send down, encapsulated in an event
*/
public void down(Event evt) {
if(evt == null) return;
// handle setting of additional data (kludge, will be removed soon)
if(evt.getType() == Event.CONFIG) {
try {
Map m=(Map)evt.getArg();
if(m != null && m.containsKey("additional_data")) {
additional_data=(byte[])m.get("additional_data");
if(local_addr instanceof IpAddress)
((IpAddress)local_addr).setAdditionalData(additional_data);
}
}
catch(Throwable t) {
if(log.isErrorEnabled()) log.error("CONFIG event did not contain a hashmap: " + t);
}
}
if(prot_stack != null)
prot_stack.down(evt);
else
if(log.isErrorEnabled()) log.error("no protocol stack available");
}
public String toString(boolean details) {
StringBuffer sb=new StringBuffer();
sb.append("local_addr=").append(local_addr).append('\n');
sb.append("cluster_name=").append(cluster_name).append('\n');
sb.append("my_view=").append(my_view).append('\n');
sb.append("connected=").append(connected).append('\n');
sb.append("closed=").append(closed).append('\n');
if(mq != null)
sb.append("incoming queue size=").append(mq.size()).append('\n');
if(details) {
sb.append("receive_blocks=").append(receive_blocks).append('\n');
sb.append("receive_local_msgs=").append(receive_local_msgs).append('\n');
sb.append("auto_reconnect=").append(auto_reconnect).append('\n');
sb.append("auto_getstate=").append(auto_getstate).append('\n');
sb.append("state_transfer_supported=").append(state_transfer_supported).append('\n');
sb.append("props=").append(props).append('\n');
}
return sb.toString();
}
protected final void init(ProtocolStackConfigurator configurator) throws ChannelException {
if(log.isInfoEnabled())
log.info("JGroups version: " + Version.description);
ConfiguratorFactory.substituteVariables(configurator); // replace vars with system props
props=configurator.getProtocolStackString();
prot_stack=new ProtocolStack(this, props);
try {
prot_stack.setup(); // Setup protocol stack (create layers, queues between them
}
catch(Throwable e) {
throw new ChannelException("unable to setup the protocol stack", e);
}
}
/**
* Initializes all variables. Used after <tt>close()</tt> or <tt>disconnect()</tt>,
* to be ready for new <tt>connect()</tt>
*/
private void init() {
local_addr=null;
cluster_name=null;
my_view=null;
// changed by Bela Sept 25 2003
//if(mq != null && mq.closed())
// mq.reset();
connect_promise.reset();
disconnect_promise.reset();
connected=false;
}
/**
* health check.<BR>
* throws a ChannelNotConnected exception if the channel is not connected
*/
protected void checkNotConnected() throws ChannelNotConnectedException {
if(!connected)
throw new ChannelNotConnectedException();
}
/**
* health check<BR>
* throws a ChannelClosed exception if the channel is closed
*/
protected void checkClosed() throws ChannelClosedException {
if(closed)
throw new ChannelClosedException();
}
/**
* returns the value of the event<BR>
* These objects will be returned<BR>
* <PRE>
* <B>Event Type - Return Type</B>
* Event.MSG - returns a Message object
* Event.VIEW_CHANGE - returns a View object
* Event.SUSPECT - returns a SuspectEvent object
* Event.BLOCK - returns a new BlockEvent object
* Event.GET_APPLSTATE - returns a GetStateEvent object
* Event.STATE_RECEIVED- returns a SetStateEvent object
* Event.Exit - returns an ExitEvent object
* All other - return the actual Event object
* </PRE>
* @param evt - the event of which you want to extract the value
* @return the event value if it matches the select list,
* returns null if the event is null
* returns the event itself if a match (See above) can not be made of the event type
*/
static Object getEvent(Event evt) {
if(evt == null)
return null; // correct ?
switch(evt.getType()) {
case Event.MSG:
return evt.getArg();
case Event.VIEW_CHANGE:
return evt.getArg();
case Event.SUSPECT:
return new SuspectEvent(evt.getArg());
case Event.BLOCK:
return new BlockEvent();
case Event.GET_APPLSTATE:
StateTransferInfo info=(StateTransferInfo)evt.getArg();
return new GetStateEvent(info.target, info.state_id);
case Event.STATE_RECEIVED:
info=(StateTransferInfo)evt.getArg();
return new SetStateEvent(info.state, info.state_id);
case Event.STATE_TRANSFER_OUTPUTSTREAM:
info = (StateTransferInfo)evt.getArg();
return new StreamingGetStateEvent(info.outputStream,info.state_id);
case Event.STATE_TRANSFER_INPUTSTREAM:
info = (StateTransferInfo)evt.getArg();
return new StreamingSetStateEvent(info.inputStream,info.state_id);
case Event.EXIT:
return new ExitEvent();
default:
return evt;
}
}
/**
* Receives the state from the group and modifies the JChannel.state object<br>
* This method initializes the local state variable to null, and then sends the state
* event down the stack. It waits for a GET_STATE_OK event to bounce back
* @param evt the get state event, has to be of type Event.GET_STATE
* @param info Information about the state transfer, e.g. target member and timeout
* @return true of the state was received, false if the operation timed out
*/
private boolean _getState(Event evt, StateTransferInfo info) throws ChannelNotConnectedException, ChannelClosedException {
checkClosed();
checkNotConnected();
if(!state_transfer_supported) {
throw new IllegalStateException("fetching state will fail as state transfer is not supported. "
+ "Add one of the STATE_TRANSFER protocols to your protocol configuration");
}
state_promise.reset();
down(evt);
Boolean state_transfer_successfull=(Boolean)state_promise.getResult(info.timeout);
return state_transfer_successfull != null && state_transfer_successfull.booleanValue();
}
/**
* Disconnects and closes the channel.
* This method does the folloing things
* <ol>
* <li>Calls <code>this.disconnect</code> if the disconnect parameter is true
* <li>Calls <code>Queue.close</code> on mq if the close_mq parameter is true
* <li>Calls <code>ProtocolStack.stop</code> on the protocol stack
* <li>Calls <code>ProtocolStack.destroy</code> on the protocol stack
* <li>Sets the channel closed and channel connected flags to true and false
* <li>Notifies any channel listener of the channel close operation
* </ol>
*/
protected void _close(boolean disconnect, boolean close_mq) {
if(closed)
return;
if(disconnect)
disconnect(); // leave group if connected
if(close_mq) {
try {
if(mq != null)
mq.close(false); // closes and removes all messages
}
catch(Exception e) {
if(log.isErrorEnabled()) log.error("exception: " + e);
}
}
if(prot_stack != null) {
try {
prot_stack.stopStack();
prot_stack.destroy();
}
catch(Exception e) {
if(log.isErrorEnabled()) log.error("failed destroying the protocol stack", e);
}
}
closed=true;
connected=false;
notifyChannelClosed(this);
init(); // sets local_addr=null; changed March 18 2003 (bela) -- prevented successful rejoining
}
public final void closeMessageQueue(boolean flush_entries) {
if(mq != null)
mq.close(flush_entries);
}
/**
* Creates a separate thread to close the protocol stack.
* This is needed because the thread that called JChannel.up() with the EXIT event would
* hang waiting for up() to return, while up() actually tries to kill that very thread.
* This way, we return immediately and allow the thread to terminate.
*/
private void handleExit(Event evt) {
notifyChannelShunned();
if(closer != null && !closer.isAlive())
closer=null;
if(closer == null) {
if(log.isInfoEnabled())
log.info("received an EXIT event, will leave the channel");
closer=new CloserThread(evt);
closer.start();
}
}
boolean startFlush(long timeout) {
if(!flush_supported) {
throw new IllegalStateException("Flush is not supported, add pbcast.FLUSH protocol to your configuration");
}
boolean successfulFlush=false;
down(new Event(Event.SUSPEND));
try {
flush_promise.reset();
flush_promise.getResultWithTimeout(timeout);
successfulFlush=true;
}
catch(TimeoutException e) {
}
return successfulFlush;
}
void stopFlush() {
if(!flush_supported) {
throw new IllegalStateException("Flush is not supported, add pbcast.FLUSH protocol to your configuration");
}
down(new Event(Event.RESUME));
}
Address determineCoordinator() {
Vector mbrs=my_view != null? my_view.getMembers() : null;
if(mbrs == null)
return null;
if(mbrs.size() > 0)
return (Address)mbrs.firstElement();
return null;
}
class CloserThread extends Thread {
final Event evt;
final Thread t=null;
CloserThread(Event evt) {
super(Util.getGlobalThreadGroup(), "CloserThread");
this.evt=evt;
setDaemon(true);
}
public void run() {
try {
String old_cluster_name=cluster_name; // remember because close() will null it
if(log.isInfoEnabled())
log.info("closing the channel");
_close(false, false); // do not disconnect before closing channel, do not close mq (yet !)
if(up_handler != null)
up_handler.up(this.evt);
else {
try {
if(receiver == null)
mq.add(this.evt);
}
catch(Exception ex) {
if(log.isErrorEnabled()) log.error("exception: " + ex);
}
}
if(mq != null) {
Util.sleep(500); // give the mq thread a bit of time to deliver EXIT to the application
try {
mq.close(false);
}
catch(Exception ex) {
}
}
if(auto_reconnect) {
try {
if(log.isInfoEnabled()) log.info("reconnecting to group " + old_cluster_name);
open();
}
catch(Exception ex) {
if(log.isErrorEnabled()) log.error("failure reopening channel: " + ex);
return;
}
try {
if(additional_data != null) {
// send previously set additional_data down the stack - other protocols (e.g. TP) use it
Map m=new HashMap(11);
m.put("additional_data", additional_data);
down(new Event(Event.CONFIG, m));
}
connect(old_cluster_name);
notifyChannelReconnected(local_addr);
}
catch(Exception ex) {
if(log.isErrorEnabled()) log.error("failure reconnecting to channel: " + ex);
return;
}
}
if(auto_getstate) {
if(log.isInfoEnabled())
log.info("fetching the state (auto_getstate=true)");
boolean rc=JChannel.this.getState(null, GET_STATE_DEFAULT_TIMEOUT);
if(log.isInfoEnabled()) {
if(rc)
log.info("state was retrieved successfully");
else
log.info("state transfer failed");
}
}
}
catch(Exception ex) {
if(log.isErrorEnabled()) log.error("exception: " + ex);
}
finally {
closer=null;
}
}
}
}
|
package org.ms2ms.math;
import com.google.common.collect.*;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.math.MathException;
import org.apache.commons.math.analysis.interpolation.LoessInterpolator;
import org.apache.commons.math.analysis.polynomials.PolynomialSplineFunction;
import org.ms2ms.data.AnnotatedPoint;
import org.ms2ms.utils.Strs;
import org.ms2ms.utils.Tools;
import org.uncommons.maths.combinatorics.PermutationGenerator;
import java.util.*;
public class Stats
{
public enum Aggregator { MEAN, MEDIAN, STDEV, COUNT }
static private Map<Long, Double> sLnFactorials = new HashMap<>();
static private Map<Double, Double> sLnDblFactorials = new HashMap<>();
static private Table<Integer, Integer, Collection<int[]>> sPermutationCache = HashBasedTable.create();
static
{
for (long i=0L; i<18L; i++) sLnFactorials.put( i, Math.log(factorial(i)));
for (Double i=0d; i<20d; i++) sLnDblFactorials.put(i, Math.log(factorial(i)));
}
public static Double lookup(Map<Double, Double> min_ppm, Double rt)
{
Double rt0 = (double )Math.round(rt);
if (rt0>Collections.max(min_ppm.keySet())) rt0=Collections.max(min_ppm.keySet());
else if (rt0<Collections.min(min_ppm.keySet())) rt0=Collections.min(min_ppm.keySet());
return min_ppm.get(rt0);
}
public static double geomean(Collection<Double> s)
{
if (!Tools.isSet(s)) return 0;
double avg = 0d, counts=0;
for (Double v : s) if (v!=null && v!=0) { avg += Math.log(v); counts++; }
return Math.exp(avg/counts);
}
public static double products(Collection<Double> s)
{
if (!Tools.isSet(s)) return 0;
double avg = 1d;
for (Double v : s) avg*=v;
return avg;
}
public static double ratio_products(Collection<Double> s)
{
if (!Tools.isSet(s)) return 0;
double avg = 1d;
for (Double v : s) avg*=(1-v);
return 1-avg;
}
// no bound checking
public static double mean0(double[] s)
{
double avg = 0d;
for (double v : s) avg+=v;
return avg/(double )s.length;
}
// no bound checking
public static double min(double[] s)
{
double m0 = Double.MAX_VALUE;
for (double v : s) if (v<m0) m0=v;
return m0;
}
public static double max(double[] s)
{
double m0 = Double.MAX_VALUE*-1d;
for (double v : s) if (v>m0) m0=v;
return m0;
}
public static double mean(Collection<Double> s)
{
if (!Tools.isSet(s)) return 0;
double avg = 0d;
for (Double v : s) avg+=v;
return avg/(double )s.size();
}
public static double mean(double[] s, int up_to)
{
if (!Tools.isSet(s)) return 0;
double avg = 0d;
for (int i=0; i<up_to; i++) avg+=s[i];
return avg/(double )s.length;
}
public static double stdev(Collection<Double> s) { return Math.sqrt(variance(s)); }
public static double stdev(double[] s, int up_to) { return Math.sqrt(variance(s, up_to)); }
public static double variance(Collection<Double> s)
{
if (!Tools.isSet(s) || s.size()==1) return 0;
double avg=mean(s), var=0d;
for (Double v : s) { var+= (v-avg)*(v-avg); }
return var/((double )s.size()-1d);
}
public static double variance(double[] s, int up_to)
{
if (!Tools.isSet(s) || s.length==1) return 0;
double avg=mean(s, up_to), var=0d;
for (int i=0; i<up_to; i++) { var+= (s[i]-avg)*(s[i]-avg); }
return var/((double )s.length-1d);
}
public static long factorial(long n)
{
long prod = 1L;
for (long k=1; k<=n; ++k)
prod *= k;
return prod;
}
public static double ln_permutation(double n, double k) { return ln_factorial(n)-ln_factorial(n-k); }
public static double ln_permutation(long n, long k) { return ln_factorial(n)-ln_factorial(n-k); }
public static double ln_combination(long n, long k) { return ln_factorial(n)-ln_factorial(k)-ln_factorial(n-k); }
public static double ln_factorial(long n)
{
if (n>17) return 0.5d*Math.log(2d*(double )n*3.14) + (double )n*Math.log((double )n) - (double )n;
// if (n<0)
// System.out.print("");
return sLnFactorials.get(n);
}
public static double ln_factorial(double n)
{
if (n>17) return 0.5d*Math.log(2d*n*3.14) + n*Math.log(n) - n;
return sLnDblFactorials.get((double )Math.round(n));
}
public static double hypergeometricPval1(long success, long trials, long success_population, long population)
{
long min_trial_pop = trials<success_population?trials:success_population;
double t1 = (double )trials-(double )population+(double )success_population;
if (success>min_trial_pop || (double )success<t1 || trials>population || success_population>population) return 1;
double ln_pop_trials =ln_combination(population, trials),
lnfac_suc_pop =ln_factorial(success_population),
lnfac_pop_sucpop=ln_factorial(population-success_population), prob=0d;
for (long suc=success; suc<=min_trial_pop; suc++)
{
double p=lnfac_suc_pop - ln_factorial(success) - ln_factorial(success_population-success) +
lnfac_pop_sucpop - ln_factorial(trials-success) - ln_factorial(population-success_population-trials+success) - ln_pop_trials;
prob += Math.exp(p);
}
return Math.log10(prob);
}
// calc the probability density
public static double hypergeom(long success, long trials, long success_population, long population)
{
return (ln_combination(success_population,success)+ln_combination(population-success_population,trials-success)-ln_combination(population,trials))/2.30258509;
}
public static Number aggregate(Collection data, Aggregator func)
{
if (!Tools.isSet(data)) return 0;
if (func.equals(Aggregator.COUNT)) return data.size();
Collection<Double> ns = new ArrayList<Double>();
for (Object d : data) ns.add(toDouble(d));
if (func.equals(Aggregator.MEAN)) return mean(ns);
//else if (func.equals(Dataframes.Func.MEAN)) return mean(ns);
return 0;
}
public static boolean isNumeric(Object s)
{
if (s==null) return false;
if (s instanceof Double || s instanceof Float || s instanceof Integer || s instanceof Long) return true;
return NumberUtils.isNumber(s.toString());
}
// convert the Object to Number if possible
public static Object toNumber(Object s)
{
if (s==null) return null;
try
{
// quotes? must remain a string if so
if (s instanceof String)
{
String val = Strs.trim((String) s);
if ((val.charAt(0)=='"' && val.charAt(val.length()-1)=='"') ||
(val.charAt(0)=='\'' && val.charAt(val.length()-1)=='\'')) return val.substring(1, val.length()-1);
boolean isNum = (val.charAt(0)>='0' && val.charAt(0)<='9');
return isNum && val.indexOf('.')>=0 ? NumberUtils.createDouble(val) : (isNum?NumberUtils.createLong(val):val);
}
}
catch (Exception e) {}
return s;
}
public static Double toDouble(Object s)
{
if (s==null) return null;
try
{
if (s instanceof String && "NA".equals((String )s)) return Double.NaN;
else if (s instanceof String) return NumberUtils.createDouble((String )s);
else if (s instanceof Double) return (Double )s;
else if (s instanceof Float ) return ((Float )s).doubleValue();
else if (s instanceof Long ) return ((Long )s).doubleValue();
else if (s instanceof Integer) return ((Integer)s).doubleValue();
}
catch (NumberFormatException e) {}
return null;
}
public static Float toFloat(Object s)
{
if (s==null) return null;
try
{
if (s instanceof String) return NumberUtils.createFloat((String )s);
else if (s instanceof Double) return ((Double )s).floatValue();
else if (s instanceof Float ) return ((Float )s);
else if (s instanceof Long ) return ((Long )s).floatValue();
else if (s instanceof Integer) return ((Integer)s).floatValue();
}
catch (NumberFormatException e) {}
return null;
}
public static Long[] toLongArray(Object s, char delim)
{
if (s==null) return null;
if (s instanceof String) return Stats.toLongArray(Strs.split((String) s, ';'));
Long i = Stats.toLong(s);
return i!=null?new Long[] {i}:null;
}
public static Long[] toLongArray(Object[] s)
{
try
{
Long[] out = new Long[s.length];
for (int i=0; i<s.length; i++) out[i]=toLong(s[i]);
return out;
}
catch (NumberFormatException e) {}
return null;
}
public static Long toLong(Object s)
{
if (s==null) return null;
if (s instanceof String) return NumberUtils.createLong((String) s);
else if (s instanceof Long ) return ((Long )s);
else if (s instanceof Integer) return ((Integer )s).longValue();
else if (s instanceof Double) return ((Double )s).longValue();
else if (s instanceof Float) return ((Float )s).longValue();
return null;
}
public static Integer toInt(Object s)
{
try
{
if (s instanceof String) return NumberUtils.createInteger((String) s);
else if (s instanceof Long ) return ((Long )s).intValue();
else if (s instanceof Integer) return ((Integer )s);
else if (s instanceof Double) return ((Double )s).intValue();
else if (s instanceof Float) return ((Float )s).intValue();
}
catch (Exception e) {}
return null;
}
public static Range<Double> closed(double[] s)
{
if (s==null) return null;
double lower=Double.MAX_VALUE, upper = Double.MAX_VALUE*-1;
for (double x : s)
{
if (x<lower) lower=x;
if (x>upper) upper=x;
}
return Range.closed(lower, upper);
}
/**
*
* @param Xs is the variable
* @param xs and ys represent the X-Y curve on which the interpolation will be based
* @param bandwidth is the fraction of source points closest to the current point is taken into account for computing
* a least-squares regression when computing the loess fit at a particular point. A sensible value is
* usually 0.25 to 0.5, the default value is 0.3.
* @return
*/
public static double[] interpolate(double[] xs, double[] ys, double bandwidth, double... Xs)
{
if (!Tools.isSet(xs) || !Tools.isSet(ys) || xs.length!=ys.length) return null;
try
{
// average the values with duplicated x
Multimap<Double, Double> xy = TreeMultimap.create();
for (int i=0; i<xs.length; i++) xy.put(xs[i], ys[i]);
int i=0; xs=new double[xy.keySet().size()]; ys=new double[xy.keySet().size()];
for (Double x : xy.keySet()) { xs[i]=x; ys[i]= mean(xy.get(x)); i++; }
xy=Tools.dispose(xy);
double[] Ys = new double[Xs.length];
Range<Double> bound = closed(xs);
PolynomialSplineFunction poly = new LoessInterpolator(bandwidth, 2).interpolate(xs, ys);
// compute the interpolated value
for (i=0; i<Xs.length; i++)
{
double x=Xs[i];
if (x<bound.lowerEndpoint()) x=bound.lowerEndpoint();
else if (x>bound.upperEndpoint()) x=bound.upperEndpoint();
Ys[i] = poly.value(x);
}
return Ys;
}
catch (MathException me)
{
throw new RuntimeException("Not able to interpolate: ", me);
}
}
public static double[] matrix_sum(double[]... ys)
{
if (!Tools.isSet(ys)) return null;
double[] out = new double[ys[0].length];
for (int i=0; i<ys.length; i++)
{
for (int j=0; j<out.length; j++)
{
out[j] += ys[i][j];
}
}
return out;
}
public static Double sum(Collection<Double> ys)
{
if (ys==null) return null;
Double sum=0d;
for (Double y : ys) sum+=y;
return sum;
}
public static Float sumFloats(Collection<Float> ys)
{
if (!Tools.isSet(ys)) return null;
Float sum=0f;
for (Float y : ys) sum+=y;
return sum;
}
public static Integer sumInts(Collection<Integer> ys)
{
if (!Tools.isSet(ys)) return null;
Integer sum=0;
for (Integer y : ys) sum+=y;
return sum;
}
public static Float sumFloats(Float... ys)
{
if (!Tools.isSet(ys)) return null;
Float sum=0f;
for (Float y : ys)
if (y!=null) sum+=y;
return sum;
}
public static double sum(double[] ys)
{
if (!Tools.isSet(ys)) return 0;
double sum=0d;
for (double y : ys) sum+=y;
return sum;
}
public static int sum(int[] ys)
{
if (!Tools.isSet(ys)) return 0;
int sum=0;
for (int y : ys) sum+=y;
return sum;
}
public static int sum(Integer[] ys)
{
if (!Tools.isSet(ys)) return 0;
int sum=0;
for (Integer y : ys) if (y!=null) sum+=y;
return sum;
}
public static Integer[] newIntArray(int start, int end)
{
Integer[] out = new Integer[end-start];
for (int i=start; i<end; i++) out[i-start]=i;
return out;
}
public static int[] fillIntArray(int[] s, int val)
{
Arrays.fill(s, val);
return s;
}
/** Estimates the mean and stdev of intensities after 'rounds' of outlier rejections.
* The outliers are defined as those outside of the 'stdevs' multiples of the calculated stdev
*
* @param intensities are the intensities of the points to be considered
* @param stdevs is the multiple of stdev that define the boundary for the outliers
* @param rounds is the number of times the outlier rejections will be attempted.
* @return a double array where mean is followed by stdev of the intensities excluding the outliers
*/
public static double[] outliers_rejected(Collection<Double> intensities, double stdevs, int rounds)
{
// deal with null or singleton first
if (intensities==null) return null;
if (intensities.size()<2) return new double[] { Tools.front(intensities), 0d};
double avg=0, bound=Double.MAX_VALUE;
for (int i = 0; i < rounds; i++)
{
Iterator<Double> itr = intensities.iterator();
while (itr.hasNext())
if (Math.abs(itr.next()-avg)>bound) itr.remove();
avg = mean(intensities);
bound = stdev(intensities) * stdevs;
}
return new double[] {avg, bound};
}
public static double median(double[] ys)
{
if (ys == null || ys.length == 0) return Double.NaN;
if (ys.length == 1) return ys[0];
Arrays.sort(ys);
if (ys.length % 2 == 0) return (ys[(int )(ys.length * 0.5) ] +
ys[(int )(ys.length * 0.5) - 1]) * 0.5;
return ys[(int )(ys.length * 0.5)];
}
public static double median(List<Double> ys)
{
if (ys.size() == 1) return Tools.front(ys);
Collections.sort(ys);
if (ys.size() % 2 == 0) return (ys.get((int )(ys.size() * 0.5) ) +
ys.get((int )(ys.size() * 0.5) - 1)) * 0.5;
return ys.get((int )(ys.size() * 0.5));
}
public static double filter(List<Double> A, int index_begin, double[] filters)
{
double Y = 0d;
for (int i = 0; i < filters.length; i++)
Y += A.get(i + index_begin) * filters[i];
return Y;
}
public static List<Double> smoothBySG5(List<Double> A)
{
// Do nothing if the set isn't big enough to smooth.
if (null==A || A.size()<6) return A;
// store the smoothed data separately
List<Double> smoothed = new ArrayList<>(A.size());
// special handling for the edge points
smoothed.add(filter(A, 0, new double[] {0.886,0.257,-0.086,-0.143,0.086}));
smoothed.add(filter(A, 0, new double[] {0.257,0.371,0.343,0.171,-0.143}));
// the mid section
for (int i=2; i < A.size()-2; i++)
smoothed.add(filter(A, i-2, new double[] {-0.086,0.343,0.486,0.343,-0.086}));
// special handling for the edge points
smoothed.add(filter(A, A.size()-6, new double[] {-0.143,0.171,0.343,0.371,0.257}));
smoothed.add(filter(A, A.size()-6, new double[] {0.086,-0.143,-0.086,0.257,0.886}));
return smoothed;
}
public static Histogram newHistogram(int steps, Collection<Double> data)
{
return newHistogram(steps, Tools.toDoubleArray(data));
}
public static Histogram newHistogram(int steps, double... data)
{
if (!Tools.isSet(data)) return null;
return Histogram.bestTransform(new Histogram(steps, data),
1, 6, Transformer.processor.log,Transformer.processor.sqrt);
}
/* Following Huber et al. Bioinformatics, 18, S96-S104, 2003 we apply the arcsinh transformation t,
t: intensity -> gamma*arcsinh(a + b*intensity), where arcsinh(x) = log(x + sqrt(x^2 + 1)),
which stabilizes the variance of the peak intensities, i.e. after this transformation all peak intensities
have the same variance independent of their height. This transformation is equal to the log transformation
for large intensities. According to Huber et al, this transformation is valid for error models of the form:
var(I) = (c1*I+c2)^2 + c3 i.e. the variance of the intensity I depend quadratically on the intensity itself.
The parameters gamma, a and b are related to the ci's as follows: gamma = 1/c1, a=c2/sqrt(c3), b=c1/sqrt(c3),
or may be estimated otherwise.
*/
public static double arcsinh(double s) { return Math.log(s + Math.sqrt(Math.pow(s, 2d) + 1d)); }
public static double transform(double s, Transformer.processor proc)
{
switch (proc)
{
case log: return Math.log(s);
case log2: return Math.log(s)/Math.log(2);
case inverse: return 1d/s;
case sqrt: return Math.sqrt(s);
case arcsinh: return arcsinh(s);
}
return s;
}
public static boolean isSet(double s) { return !Double.isNaN(s) && !Double.isInfinite(s); }
public static int compareTo(Object A, Object B)
{
if (A instanceof Comparable && B instanceof Comparable) return compareTo((Comparable )A, (Comparable )B);
return A.toString().compareTo(B.toString());
}
public static int compareTo(Comparable A, Comparable B)
{
if (A==null && B==null) return 0;
if (A==null) return -1;
if (B==null) return 1;
return A.compareTo(B);
}
public static double d2d(double x, int n)
{
double y=Math.round(x*Math.pow(10d,n))/Math.pow(10d,n);
return y;
}
public static Double max(Double A, Double B)
{
if (A==null && B!=null) return B;
if (A!=null && B==null) return A;
if (A==null && B==null) return null;
return Math.max(A,B);
}
public static Double percentile(Collection<Double> data, double pct)
{
if (data==null) return null;
List<Double> d = new ArrayList<>(data);
Collections.sort(d);
return d.get((int )Math.round(data.size()*pct*0.01));
}
public static double[] percentiles(List<Double> data, double... pct)
{
if (data==null) return null;
double[] pcts = new double[pct.length];
for (int i=0; i<pct.length; i++)
pcts[i] = data.get((int )Math.round((data.size()-1)*pct[i]*0.01));
return pcts;
}
public static Collection<int[]> permutations(int n, int r)
{
if (sPermutationCache.contains(n, r)) return sPermutationCache.get(n,r);
Multimap<String, List<Integer>> outcomes = HashMultimap.create();
Collection<int[]> permuted = new ArrayList<>();
// initiate a blank array of 0's
List<Integer> mods = new ArrayList<>(); for (int i=0; i<n; i++) mods.add(0);
// go thro the scenario
for (int i=1; i<=r; i++)
{
mods.set(i-1, 1); outcomes.clear();
PermutationGenerator perm = new PermutationGenerator(mods);
while (perm.hasMore())
{
List<Integer> row = perm.nextPermutationAsList();
// System.out.println(Strs.toString(row, ","));
outcomes.put(Strs.toString(row, ","), row);
}
for (List<Integer> row : outcomes.values())
{
int[] rr = new int[row.size()];
for (int j=0; j<row.size(); j++) rr[j]=row.get(j);
permuted.add(rr);
}
}
// deposit it in the cache
sPermutationCache.put(n, r, permuted);
return permuted;
}
public static boolean hasPositive(Collection<Double> s)
{
if (Tools.isSet(s))
for (Double d : s) if (d>0) return true;
return false;
}
public static double absSum(Collection<Double> s)
{
double sum=0;
if (Tools.isSet(s))
for (Double d : s) sum+=Math.abs(d);
return sum;
}
public static double ppm(double obs, double calc) { return 1E6*(obs-calc)/calc; }
public static double kai2(double[] pts)
{
if (pts==null) return 0d;
double kai=0d;
for (double s : pts) kai+=(s*s);
return kai;
}
public static double kai2(List<Double>... pts)
{
if (pts==null) return 0d;
double kai=0d;
for (List<Double> pt : pts)
if (pt!=null)
for (double s : pt) kai+=(s*s);
return kai;
}
public static Map<Double, Double> scaleQVal(SortedMap<Double, Boolean> scale)
{
if (scale==null) return null;
Map<Double, Double> qval = new HashMap<>(); double counts=0d, decoys=0d;
for (Double scr : scale.keySet())
{
counts++;
if (scale.get(scr)) decoys++;
qval.put(scr, 2d*decoys/counts);
}
return qval;
}
public static double factorial(double n)
{
if (n<2) return 1;
// compute the exact factorial. Could be costly!
double f=1d;
for (double i=1d; i<=n; i++) f*=i;
return f;
}
public static double binomial_exact(double s, double n, double p)
{
// >>> prob(20, 0.3, 100)
// 0.016462853241869437
// >>> 1-prob(40-1, 0.3, 100)
// 0.020988576003924564
double prob=0d, x=1.0-p, a=n-s, b=s+1, c=a+b-1;
for (double j=a; j<c+1; j++)
{
// double y2=Math.pow(x,j);
// double y3=Math.pow(1-x,c-j);
// prob += y1*y2*y3;
prob += factorial(c)/(factorial(j)*factorial(c-j)) * Math.pow(x,j) * Math.pow(1-x,c-j);
}
return prob;
}
// return cummulative binomial prob using log-transformed aprox of factorial fn.
public static double binomial(double s, double n, double p)
{
double prob=0d, x=1.0-p, a=n-s, b=s+1, c=a+b-1;
for (double j=a; j<c+1; j++)
prob += Math.exp(ln_factorial(c)-(ln_factorial(j)+ln_factorial(c-j)) + j*Math.log(x) + (c-j)*Math.log(1 - x));
return prob;
}
public static double erf_Horner(double z)
{
double t = 1d/(1d + 0.5 * Math.abs(z));
// use Horner's method
double ans = 1 - t * Math.exp( -z*z - 1.26551223 +
t * ( 1.00002368 +
t * ( 0.37409196 +
t * ( 0.09678418 +
t * (-0.18628806 +
t * ( 0.27886807 +
t * (-1.13520398 +
t * ( 1.48851587 +
t * (-0.82215223 +
t * ( 0.17087277))))))))));
return z>=0d?ans:(ans*-1d);
}
// Normal Estimate, good for large n
public static double binomial_normal_estimate(int s, int n, double p)
{
double u = n*p, o = Math.sqrt(u*(1-p));
return 0.5*(1 + erf_Horner((s-u)/(o*Math.sqrt(2))));
}
public static double binomial_poisson_estimate(double s, double n, double p)
{
double L = n*p, sum = 0d;
for (double i=0d; i<s+1d; i++)
sum += Math.exp(i*Math.log(L)-ln_factorial(i));
return sum*Math.exp(L*-1d);
}
public static int greaterEqualThan(Collection<Integer> vals, Double val)
{
int n=0;
if (Tools.isSet(vals))
for (Integer v : vals) if (v>=val) n++;
return n;
}
public static Double thresholdByFdr(SortedMap<Double, Boolean> scores, double maxFDR, int repeat)
{
double counts=0d, decoys=0d, last=0;
for (Double scr : scores.keySet())
{
counts++;
if (scores.get(scr)) decoys++;
if (decoys/counts>maxFDR) last=counts;
if (counts-last>=repeat) return scr;
}
return null;
}
public static Double thresholdByNorms(SortedMap<Double, Boolean> scores, int repeat)
{
double counts=0d, norms=0d;
for (Double scr : scores.keySet())
{
counts++;
if (!scores.get(scr)) norms++;
if (norms>repeat) return scr;
}
return null;
}
public static AnnotatedPoint aggregate(Collection<Double> pts)
{
if (Tools.isSet(pts))
{
AnnotatedPoint p = new AnnotatedPoint();
p.setX(mean(pts)).setY(stdev(pts));
p.addAnnotation("Data", pts);
return p;
}
return null;
}
}
|
package org.owasp.esapi;
import java.security.Principal;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.servlet.http.HttpSession;
import org.owasp.esapi.errors.AuthenticationException;
import org.owasp.esapi.errors.EncryptionException;
public interface User extends Principal {
/**
* Adds a role to an account.
*
* @param role
* the role to add
*
* @throws AuthenticationException
* the authentication exception
*/
void addRole(String role) throws AuthenticationException;
/**
* Adds a set of roles to an account.
*
* @param newRoles
* the new roles to add
*
* @throws AuthenticationException
* the authentication exception
*/
void addRoles(Set newRoles) throws AuthenticationException;
/**
* Sets the user's password, performing a verification of the user's old password, the equality of the two new
* passwords, and the strength of the new password.
*
* @param oldPassword
* the old password
* @param newPassword1
* the new password
* @param newPassword2
* the new password - used to verify that the new password was typed correctly
*
* @throws AuthenticationException
* if newPassword1 does not match newPassword2, if oldPassword does not match the stored old password, or if the new password does not meet complexity requirements
* @throws EncryptionException
*/
void changePassword(String oldPassword, String newPassword1, String newPassword2) throws AuthenticationException, EncryptionException;
/**
* Disable account.
*
*
*/
void disable();
/**
* Enable account.
*
*
*/
void enable();
/**
* Gets the account id.
*
* @return the account id
*/
long getAccountId();
/**
* Gets the account name.
*
* @return the account name
*/
String getAccountName();
/**
* Gets the CSRF token.
*
* @return the CSRF token
*/
String getCSRFToken();
/**
* Returns the date that the current user's account will expire, usually when the account will be disabled.
*
* @return Date representing the account expiration time.
*/
Date getExpirationTime();
/**
* Returns the number of failed login attempts since the last successful login for an account. This method is
* intended to be used as a part of the account lockout feature, to help protect against brute force attacks.
* However, the implementor should be aware that lockouts can be used to prevent access to an application by a
* legitimate user, and should consider the risk of denial of service.
*
* @return the number of failed login attempts since the last successful login
*/
int getFailedLoginCount();
/**
* Returns the last host address used by the user. This will be used in any log messages generated by the processing
* of this request.
*
* @return the last host address used by the user
*/
String getLastHostAddress();
/**
* Returns the date of the last failed login time for a user. This date should be used in a message to users after a
* successful login, to notify them of potential attack activity on their account.
*
* @return date of the last failed login
*
* @throws AuthenticationException
* the authentication exception
*/
Date getLastFailedLoginTime() throws AuthenticationException;
/**
* Returns the date of the last successful login time for a user. This date should be used in a message to users
* after a successful login, to notify them of potential attack activity on their account.
*
* @return date of the last successful login
*/
Date getLastLoginTime();
/**
* Gets the date of user's last password change.
*
* @return the date of last password change
*/
Date getLastPasswordChangeTime();
/**
* Gets the roles assigned to a particular account.
*
* @return an immutable set of roles
*/
Set getRoles();
/**
* Gets the screen name.
*
* @return the screen name
*/
String getScreenName();
/**
* Adds a session for this User.
* @param s
*/
void addSession( HttpSession s );
/**
* Removes a session for this User.
* @param s
*/
void removeSession( HttpSession s );
/**
* Returns the list of sessions associated with this User.
*/
Set getSessions();
/**
* Increment failed login count.
*/
void incrementFailedLoginCount();
/**
* Checks if user is anonymous.
*
* @return true, if user is anonymous
*/
boolean isAnonymous();
/**
* Checks if an account is currently enabled.
*
* @return true, if account is enabled
*/
boolean isEnabled();
/**
* Checks if an account is expired.
*
* @return true, if account is expired
*/
boolean isExpired();
/**
* Checks if an account has been assigned a particular role.
*
* @param role
* the role for which to check
*
* @return true, if role has been assigned to user
*/
boolean isInRole(String role);
/**
* Checks if an account is locked.
*
* @return true, if account is locked
*/
boolean isLocked();
/**
* Tests to see if the user is currently logged in.
*
* @return true, if the user is logged in
*/
boolean isLoggedIn();
/**
* Tests to see if the user's session has exceeded the absolute time out.
*
* @return true, if user's session has exceeded the absolute time out
*/
boolean isSessionAbsoluteTimeout();
/**
* Tests to see if the user's session has timed out from inactivity based
* on ESAPI configuration settings.
*
* A session may timeout prior to ESAPI's configuration setting due to the
* web.xml entry for session-timeout.
*
* <session-config>
* <session-timeout>60</session-timeout>
* </session-config>
*
* @return true, if user's session has timed out from inactivity based
* on ESAPI configuration
*/
boolean isSessionTimeout();
/**
* Lock the user's account.
*/
void lock();
/**
* Login with password.
*
* @param password
* the password
* @throws AuthenticationException
* if login fails
*/
void loginWithPassword(String password) throws AuthenticationException;
/**
* Logout this user.
*/
void logout();
/**
* Removes a role from an account.
*
* @param role
* the role to remove
* @throws AuthenticationException
* the authentication exception
*/
void removeRole(String role) throws AuthenticationException;
/**
* Returns a token to be used as a prevention against CSRF attacks. This token should be added to all links and
* forms. The application should verify that all requests contain the token, or they may have been generated by a
* CSRF attack. It is generally best to perform the check in a centralized location, either a filter or controller.
* See the verifyCSRFToken method.
*
* @return the new CSRF token
*
* @throws AuthenticationException
* the authentication exception
*/
String resetCSRFToken() throws AuthenticationException;
/**
* Sets the account name.
*
* @param accountName the new account name
*/
void setAccountName(String accountName);
/**
* Sets the time when this user's account will expire.
*
* @param expirationTime the new expiration time
*/
void setExpirationTime(Date expirationTime);
/**
* Sets the roles of this account.
*
* @param roles
* the new roles
*
* @throws AuthenticationException
* the authentication exception
*/
void setRoles(Set roles) throws AuthenticationException;
/**
* Sets the screen name.
*
* @param screenName the new screen name
*/
void setScreenName(String screenName);
/**
* Unlock account.
*/
void unlock();
/**
* Verify that the supplied password matches the password for this user. This method
* is typically used for "reauthentication" for the most sensitive functions, such
* as transactions, changing email address, and changing other account information.
*
* @param password
* the password that the user entered
*
* @return true, if the password passed in matches the account's password
*
* @throws EncryptionException
*/
public boolean verifyPassword(String password) throws EncryptionException;
/**
* Set the time of the last failed login for this user.
* @param lastFailedLoginTime
*/
void setLastFailedLoginTime(Date lastFailedLoginTime);
/**
* Set the last remote host address used by this user.
* @param remoteHost
*/
void setLastHostAddress(String remoteHost);
/**
* Set the time of the last successful login for this user.
* @param lastLoginTime
*/
void setLastLoginTime(Date lastLoginTime);
/**
* Set the time of the last password change for this user.
* @param lastPasswordChangeTime
*/
void setLastPasswordChangeTime(Date lastPasswordChangeTime);
/**
* The ANONYMOUS user is used to represent an unidentified user. Since there is
* always a real user, the ANONYMOUS user is better than using null to represent
* this.
*/
public final User ANONYMOUS = new User() {
private String csrfToken = "";
private Set sessions = new HashSet();
/* (non-Javadoc)
* @see org.owasp.esapi.User#addRole(java.lang.String)
*/
public void addRole(String role) throws AuthenticationException {
throw new RuntimeException("Invalid operation for the anonymous user");
}
/* (non-Javadoc)
* @see org.owasp.esapi.User#addRoles(java.util.Set)
*/
public void addRoles(Set newRoles) throws AuthenticationException {
throw new RuntimeException("Invalid operation for the anonymous user");
}
/* (non-Javadoc)
* @see org.owasp.esapi.User#changePassword(java.lang.String, java.lang.String, java.lang.String)
*/
public void changePassword(String oldPassword, String newPassword1,
String newPassword2) throws AuthenticationException,
EncryptionException {
throw new RuntimeException("Invalid operation for the anonymous user");
}
/* (non-Javadoc)
* @see org.owasp.esapi.User#disable()
*/
public void disable() {
throw new RuntimeException("Invalid operation for the anonymous user");
}
/* (non-Javadoc)
* @see org.owasp.esapi.User#enable()
*/
public void enable() {
throw new RuntimeException("Invalid operation for the anonymous user");
}
/* (non-Javadoc)
* @see org.owasp.esapi.User#getAccountId()
*/
public long getAccountId() {
return 0;
}
/* (non-Javadoc)
* @see org.owasp.esapi.User#getAccountName()
*/
public String getAccountName() {
return "Anonymous";
}
public String getName() {
return getAccountName();
}
/* (non-Javadoc)
* @see org.owasp.esapi.User#getCSRFToken()
*/
public String getCSRFToken() {
return csrfToken;
}
/* (non-Javadoc)
* @see org.owasp.esapi.User#getLastFailedLoginTime()
*/
public Date getExpirationTime() {
return null;
}
/* (non-Javadoc)
* @see org.owasp.esapi.User#getFailedLoginCount()
*/
public int getFailedLoginCount() {
return 0;
}
/* (non-Javadoc)
* @see org.owasp.esapi.User#getLastFailedLoginTime()
*/
public Date getLastFailedLoginTime() throws AuthenticationException {
return null;
}
/* (non-Javadoc)
* @see org.owasp.esapi.User#getLastHostAddress()
*/
public String getLastHostAddress() {
return "unknown";
}
/* (non-Javadoc)
* @see org.owasp.esapi.User#getLastLoginTime()
*/
public Date getLastLoginTime() {
return null;
}
/* (non-Javadoc)
* @see org.owasp.esapi.User#getLastPasswordChangeTime()
*/
public Date getLastPasswordChangeTime() {
return null;
}
/* (non-Javadoc)
* @see org.owasp.esapi.User#getRoles()
*/
public Set getRoles() {
return new HashSet();
}
/* (non-Javadoc)
* @see org.owasp.esapi.User#getScreenName()
*/
public String getScreenName() {
return "Anonymous";
}
/* (non-Javadoc)
*/
public void addSession(HttpSession s) {
}
/* (non-Javadoc)
*/
public void removeSession(HttpSession s) {
}
/* (non-Javadoc)
*/
public Set getSessions() {
return sessions;
}
/* (non-Javadoc)
* @see org.owasp.esapi.User#incrementFailedLoginCount()
*/
public void incrementFailedLoginCount() {
throw new RuntimeException("Invalid operation for the anonymous user");
}
/* (non-Javadoc)
* @see org.owasp.esapi.User#isAnonymous()
*/
public boolean isAnonymous() {
return true;
}
/* (non-Javadoc)
* @see org.owasp.esapi.User#isEnabled()
*/
public boolean isEnabled() {
return false;
}
/* (non-Javadoc)
* @see org.owasp.esapi.User#isExpired()
*/
public boolean isExpired() {
return false;
}
/* (non-Javadoc)
* @see org.owasp.esapi.User#isInRole(java.lang.String)
*/
public boolean isInRole(String role) {
return false;
}
/* (non-Javadoc)
* @see org.owasp.esapi.User#isLocked()
*/
public boolean isLocked() {
return false;
}
/* (non-Javadoc)
* @see org.owasp.esapi.User#isLoggedIn()
*/
public boolean isLoggedIn() {
return false;
}
/* (non-Javadoc)
* @see org.owasp.esapi.User#isSessionAbsoluteTimeout()
*/
public boolean isSessionAbsoluteTimeout() {
return false;
}
/* (non-Javadoc)
* @see org.owasp.esapi.User#isSessionTimeout()
*/
public boolean isSessionTimeout() {
return false;
}
/* (non-Javadoc)
* @see org.owasp.esapi.User#lock()
*/
public void lock() {
throw new RuntimeException("Invalid operation for the anonymous user");
}
/* (non-Javadoc)
* @see org.owasp.esapi.User#loginWithPassword(java.lang.String)
*/
public void loginWithPassword(String password)
throws AuthenticationException {
throw new RuntimeException("Invalid operation for the anonymous user");
}
/* (non-Javadoc)
* @see org.owasp.esapi.User#logout()
*/
public void logout() {
throw new RuntimeException("Invalid operation for the anonymous user");
}
/* (non-Javadoc)
* @see org.owasp.esapi.User#removeRole(java.lang.String)
*/
public void removeRole(String role) throws AuthenticationException {
throw new RuntimeException("Invalid operation for the anonymous user");
}
/* (non-Javadoc)
* @see org.owasp.esapi.User#resetCSRFToken()
*/
public String resetCSRFToken() throws AuthenticationException {
csrfToken = ESAPI.randomizer().getRandomString(8, Encoder.CHAR_ALPHANUMERICS);
return csrfToken;
}
/* (non-Javadoc)
* @see org.owasp.esapi.User#setAccountName(java.lang.String)
*/
public void setAccountName(String accountName) {
throw new RuntimeException("Invalid operation for the anonymous user");
}
/* (non-Javadoc)
* @see org.owasp.esapi.User#setAccountName(java.lang.String)
*/
public void setExpirationTime(Date expirationTime) {
throw new RuntimeException("Invalid operation for the anonymous user");
}
/* (non-Javadoc)
* @see org.owasp.esapi.User#setRoles(java.util.Set)
*/
public void setRoles(Set roles) throws AuthenticationException {
throw new RuntimeException("Invalid operation for the anonymous user");
}
/* (non-Javadoc)
* @see org.owasp.esapi.User#setScreenName(java.lang.String)
*/
public void setScreenName(String screenName) {
throw new RuntimeException("Invalid operation for the anonymous user");
}
/* (non-Javadoc)
* @see org.owasp.esapi.User#unlock()
*/
public void unlock() {
throw new RuntimeException("Invalid operation for the anonymous user");
}
/* (non-Javadoc)
* @see org.owasp.esapi.User#verifyPassword(java.lang.String)
*/
public boolean verifyPassword(String password) throws EncryptionException {
throw new RuntimeException("Invalid operation for the anonymous user");
}
public void setLastFailedLoginTime(Date lastFailedLoginTime) {
throw new RuntimeException("Invalid operation for the anonymous user");
}
public void setLastLoginTime(Date lastLoginTime) {
throw new RuntimeException("Invalid operation for the anonymous user");
}
public void setLastHostAddress(String remoteHost) {
throw new RuntimeException("Invalid operation for the anonymous user");
}
public void setLastPasswordChangeTime(Date lastPasswordChangeTime) {
throw new RuntimeException("Invalid operation for the anonymous user");
}
};
}
|
package org.twak.tweed;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.imageio.ImageIO;
import javax.swing.ButtonGroup;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JToggleButton;
import javax.vecmath.Matrix4d;
import javax.vecmath.Point3d;
import javax.vecmath.Tuple3d;
import javax.vecmath.Vector3d;
import org.apache.commons.io.FileUtils;
import org.geotools.referencing.CRS;
import org.geotools.referencing.crs.DefaultGeocentricCRS;
import org.opengis.referencing.FactoryException;
import org.opengis.referencing.NoSuchAuthorityCodeException;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.opengis.referencing.operation.MathTransform;
import org.opengis.referencing.operation.TransformException;
import org.twak.siteplan.jme.Jme3z;
import org.twak.tweed.gen.FeatureCache;
import org.twak.tweed.gen.GISGen;
import org.twak.tweed.handles.Handle;
import org.twak.tweed.handles.HandleMe;
import org.twak.tweed.tools.FacadeTool;
import org.twak.tweed.tools.HouseTool;
import org.twak.tweed.tools.MoveTool;
import org.twak.tweed.tools.PlaneTool;
import org.twak.tweed.tools.SelectTool;
import org.twak.tweed.tools.Tool;
import org.twak.utils.Cache;
import org.twak.utils.Mathz;
import org.twak.utils.ui.ListDownLayout;
import org.twak.utils.ui.WindowManager;
import com.google.common.io.Files;
import com.google.common.io.LineProcessor;
import com.jme3.app.DebugKeysAppState;
import com.jme3.app.FlyCamAppState;
import com.jme3.app.SimpleApplication;
import com.jme3.asset.AssetKey;
import com.jme3.asset.plugins.FileLocator;
import com.jme3.audio.AudioListenerState;
import com.jme3.collision.CollisionResult;
import com.jme3.collision.CollisionResults;
import com.jme3.input.KeyInput;
import com.jme3.input.MouseInput;
import com.jme3.input.controls.AnalogListener;
import com.jme3.input.controls.KeyTrigger;
import com.jme3.input.controls.MouseAxisTrigger;
import com.jme3.input.controls.MouseButtonTrigger;
import com.jme3.light.AmbientLight;
import com.jme3.light.DirectionalLight;
import com.jme3.light.PointLight;
import com.jme3.material.Material;
import com.jme3.material.TechniqueDef.LightMode;
import com.jme3.math.ColorRGBA;
import com.jme3.math.Plane;
import com.jme3.math.Quaternion;
import com.jme3.math.Ray;
import com.jme3.math.Vector2f;
import com.jme3.math.Vector3f;
import com.jme3.post.FilterPostProcessor;
import com.jme3.post.filters.FXAAFilter;
import com.jme3.post.ssao.SSAOFilter;
import com.jme3.renderer.ViewPort;
import com.jme3.renderer.queue.RenderQueue.ShadowMode;
import com.jme3.scene.Node;
import com.jme3.scene.Spatial;
import com.jme3.shadow.EdgeFilteringMode;
import com.jme3.shadow.PointLightShadowRenderer;
import com.jme3.ui.Picture;
public class Tweed extends SimpleApplication {
public static final String LAT_LONG = "EPSG:4326";
public final static String
CLICK = "Click",
MOUSE_MOVE = "MouseyMousey",
SPEED_UP = "SpeedUp", SPEED_DOWN = "SpeedDown",
AMBIENT_UP = "AmbientUp", AMBIENT_DOWN = "AmbientDown",
TOGGLE_ORTHO = "ToggleOrtho",
FOV_UP ="FovUp", FOV_DOWN = "FovDown";
public TweedFrame frame;
public FeatureCache features;
private Picture background;
public Vector3d cursorPosition;
Tool[] tools = new Tool[] {
new SelectTool(this),
new HouseTool(this),
new MoveTool(this),
// new AlignTool(this),
new FacadeTool(this),
// new PlaneTool(this)
// new TextureTool(this),
};
public Tool tool;
private AmbientLight ambient;
private DirectionalLight sun;
private PointLight point;
PointLightShadowRenderer plsr;
FilterPostProcessor fpp ;
public Node debug;
public Tweed(TweedFrame frame) {
super( new FlyCamAppState(), new AudioListenerState(), new DebugKeysAppState());
this.frame = frame;
}
@Override
public void reshape( int w, int h ) {
super.reshape( w, h );
}
public void simpleInitApp() {
point = new PointLight();
point.setEnabled( true );
point.setColor( ColorRGBA.White.mult(4) );
point.setRadius( 50 );
rootNode.addLight( point );
sun = new DirectionalLight();
// sun.setDirection(new Vector3f(-0.0f, -1f, -0f).normalizeLocal());
sun.setDirection(new Vector3f(-0.1f, -0.7f, -1.0f).normalizeLocal());
sun.setColor(new ColorRGBA(1f, 0.95f, 0.99f, 1f));
rootNode.addLight(sun);
renderManager.setPreferredLightMode(LightMode.SinglePass); // enable multiple lights
renderManager.setSinglePassLightBatchSize(16);
ambient = new AmbientLight();
rootNode.addLight(ambient);
// setAmbient( 0 );
setDisplayFps(false);
setDisplayStatView(false);
clearBackground();
buildBackground();
getFlyByCamera().setDragToRotate(true);
setTool(SelectTool.class);
debug = new Node( "dbg" );
rootNode.attachChild( debug );
// String folder = ; // data-source
// SpotLightShadowRenderer shadows = new SpotLightShadowRenderer(assetManager, 1024);
// shadows.setLight(sun);
// shadows.setShadowIntensity(0.3f);
// shadows.setEdgeFilteringMode(EdgeFilteringMode.PCF8);
// viewPort.addProcessor(shadows);
cam.setLocation(TweedSettings.settings.cameraLocation);
cam.setRotation(TweedSettings.settings.cameraOrientation);
setAmbient( 0 );
setFov(0);
setCameraSpeed( 0 );
TweedSettings.loadDefault();
inputManager.addMapping(MOUSE_MOVE, new MouseAxisTrigger( MouseInput.AXIS_X, false ) );
inputManager.addMapping(MOUSE_MOVE, new MouseAxisTrigger( MouseInput.AXIS_Y, false ) );
inputManager.addMapping(MOUSE_MOVE, new MouseAxisTrigger( MouseInput.AXIS_X, true ) );
inputManager.addMapping(MOUSE_MOVE, new MouseAxisTrigger( MouseInput.AXIS_Y, true ) );
inputManager.addListener( moveListener, MOUSE_MOVE );
inputManager.addMapping(CLICK, new MouseButtonTrigger(MouseInput.BUTTON_RIGHT));
inputManager.addListener(analogListener, CLICK);
inputManager.addMapping( SPEED_UP, new KeyTrigger( KeyInput.KEY_UP ) );
inputManager.addMapping( SPEED_DOWN, new KeyTrigger( KeyInput.KEY_DOWN ) );
inputManager.addMapping( AMBIENT_UP, new KeyTrigger( KeyInput.KEY_RIGHT ) );
inputManager.addMapping( AMBIENT_DOWN, new KeyTrigger( KeyInput.KEY_LEFT ) );
inputManager.addMapping( FOV_UP, new KeyTrigger( KeyInput.KEY_PGUP ) );
inputManager.addMapping( FOV_DOWN, new KeyTrigger( KeyInput.KEY_PGDN ) );
inputManager.addMapping( TOGGLE_ORTHO, new KeyTrigger( KeyInput.KEY_O ) );
inputManager.addListener( new com.jme3.input.controls.ActionListener() {
@Override
public void onAction( String name, boolean isPressed, float tpf ) {
if (name == SPEED_UP)
setCameraSpeed(+1);
else
setCameraSpeed(-1);
}
}, SPEED_UP, SPEED_DOWN );
inputManager.addListener( new com.jme3.input.controls.ActionListener() {
@Override
public void onAction( String name, boolean isPressed, float tpf ) {
if (!isPressed)
return;
if (name == AMBIENT_UP)
setAmbient(+1);
else
setAmbient(-1);
}
}, AMBIENT_UP, AMBIENT_DOWN );
inputManager.addListener( new com.jme3.input.controls.ActionListener() {
@Override
public void onAction( String name, boolean isPressed, float tpf ) {
if (!isPressed)
return;
if (name == FOV_UP)
setFov(+1);
else
setFov(-1);
}
}, FOV_UP, FOV_DOWN );
inputManager.addListener( new com.jme3.input.controls.ActionListener() {
@Override
public void onAction( String name, boolean isPressed, float tpf ) {
if ( isPressed ) {
TweedSettings.settings.ortho = !TweedSettings.settings.ortho;
setCameraPerspective();
}
}
}, TOGGLE_ORTHO );
}
private final static Pattern
SRS_EX = Pattern.compile( ".*srsName=\\\"([^\\\"]*).*" ),
OFFSET_EX = Pattern.compile(".*<gml:X>([\\-0-9\\\\.]*)</gml:X><gml:Y>([\\-0-9\\\\.]*).*");
public void addGML( File gmlFile, String guessCRS) throws Exception {
double[] lastOffset = new double[] { Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY };
if (guessCRS == null)
guessCRS = Files.readLines( gmlFile, Charset.forName( "UTF-8" ), new LineProcessor<String>() {
String crs;
@Override
public boolean processLine( String line ) throws IOException {
Matcher m = SRS_EX.matcher( line );
if (m.matches()) {
crs = m.group( 1 );
return false;
}
m = OFFSET_EX.matcher( line );
if (m.matches() && lastOffset[0] == Double.POSITIVE_INFINITY ) {// bounds def before we see a CRS...
lastOffset[0] = Double.parseDouble( m.group( 1 ) );
lastOffset[1] = Double.parseDouble( m.group( 2 ) );
}
return true;
}
@Override
public String getResult() {
return crs;
}
} );
if (guessCRS == null || lastOffset[0] == Double.POSITIVE_INFINITY) {
JOptionPane.showMessageDialog( frame.frame, "Failed to guess coordinate system for "+gmlFile.getName() );
return;
}
// if (TweedSettings.settings.trans != null) {
// lastOffset[0] = TweedSettings.settings.trans[0];
// lastOffset[1] = TweedSettings.settings.trans[1];
// else
TweedSettings.settings.trans = lastOffset;
TweedSettings.settings.gmlCoordSystem = guessCRS;
System.out.println( "Assuming CRS " + guessCRS + " for all of " + gmlFile.getName() );
MathTransform transform = CRS.findMathTransform( kludgeCMS.get( guessCRS ), DefaultGeocentricCRS.CARTESIAN, true );
System.out.println( "Using CRS --> World space offset of " + lastOffset[0] + ", " + lastOffset[1] );
TweedSettings.settings.toOrigin = buildOrigin ( lastOffset[0], lastOffset[1], transform );
TweedSettings.settings.fromOrigin = new Matrix4d( TweedSettings.settings.toOrigin );
TweedSettings.settings.fromOrigin.invert();
GISGen gg = new GISGen( makeWorkspaceRelative( gmlFile ).toString(), TweedSettings.settings.toOrigin, guessCRS, this );
frame.addGen ( gg, true );
}
public static Cache<String, CoordinateReferenceSystem> kludgeCMS = new Cache<String, CoordinateReferenceSystem>() {
@Override
public CoordinateReferenceSystem create( String crs ) {
try {
return CRS.decode( crs );
} catch ( NoSuchAuthorityCodeException e ) {
if (crs.equals( "EPSG:6312" ))
try {
return CRS.parseWKT("PROJCS[\"unnamed\",\n" +
" GEOGCS[\"WGS 84\",\n" +
" DATUM[\"unknown\",\n" +
" SPHEROID[\"WGS84\",6378137,298.257223563],\n" +
" TOWGS84[8.846,-4.394,-1.122,-0.00237,-0.146528,0.130428,0.783926]],\n" +
" PRIMEM[\"Greenwich\",0],\n" +
" UNIT[\"degree\",0.0174532925199433]],\n" +
" PROJECTION[\"Transverse_Mercator\"],\n" +
" PARAMETER[\"latitude_of_origin\",0],\n" +
" PARAMETER[\"central_meridian\",33],\n" +
" PARAMETER[\"scale_factor\",0.99995],\n" +
" PARAMETER[\"false_easting\",200000],\n" +
" PARAMETER[\"false_northing\",-3500000],\n" +
" UNIT[\"Meter\",1],\n" +
" AUTHORITY[\"epsg\",\"6312\"]]");
} catch ( FactoryException e1 ) {
e1.printStackTrace();
}
} catch ( Throwable th ) {
th.printStackTrace();
}
JOptionPane.showMessageDialog( TweedFrame.instance.frame, "failed to find CRS " + crs, "coordinate system error", JOptionPane.ERROR_MESSAGE );
return null;
}
};
public void setCameraPerspective() {
if (cam == null)
return;
if ( TweedSettings.settings.ortho ) {
cam.setParallelProjection( true );
float frustumSize = TweedSettings.settings.fov*10 +100;
float aspect = (float) cam.getWidth() / cam.getHeight();
cam.setFrustum( -1000, 1000, -aspect * frustumSize, aspect * frustumSize, frustumSize, -frustumSize );
} else {
cam.setFrustumPerspective( TweedSettings.settings.fov*10 +100, cam.getWidth() / (float) cam.getHeight(), 0.1f, 1e3f );
cam.setFrustumFar( 1e5f );
}
}
private void setFov( int i ) {
TweedSettings.settings.fov = Mathz.clamp( TweedSettings.settings.fov + i, -100, 100 );
System.out.println("fov now " + TweedSettings.settings.fov);
setCameraPerspective();
}
private void setCameraSpeed( int i ) {
TweedSettings.settings.cameraSpeed = Mathz.clamp( TweedSettings.settings.cameraSpeed+i, -25, 6 );
System.out.println("camera speed now " + TweedSettings.settings.cameraSpeed);
getFlyByCamera().setMoveSpeed( (float) Math.pow (2, (TweedSettings.settings.cameraSpeed /2 ) + 8) );
}
private void setAmbient( int i ) {
TweedSettings.settings.ambient = Mathz.clamp( TweedSettings.settings.ambient + i * 0.1, 0, 2 );
System.out.println("ambient now " + TweedSettings.settings.ambient);
ambient.setColor(ColorRGBA.White.mult( (float) TweedSettings.settings.ambient));
sun.setColor( new ColorRGBA(1f, 0.95f, 0.99f, 1f).mult( 2- (float)TweedSettings.settings.ambient) );
}
public void setTool( Class newTool ) {
for ( Tool t : tools )
if ( t.getClass() == newTool ) {
setTool( t );
return;
}
}
public void setTool( Tool newTool ) {
{
boolean seenBefore = false;
for ( Tool t : tools )
if ( t.getClass() == newTool.getClass() )
seenBefore = true;
if ( !seenBefore )
toolBG.clearSelection();
}
Tool oldTool = tool;
enqueue( new Runnable() {
@Override
public void run() {
if (oldTool != null)
oldTool.deactivate();
newTool.activate( Tweed.this );;
}
});
this.tool = newTool;
frame.genUI.removeAll();
this.tool.getUI(frame.genUI);
frame.genUI.revalidate();
frame.genUI.doLayout();
frame.genUI.repaint();
gainFocus();
}
/**
* Transform toCartesian (around x,y) to a renderable coordinate system with y-up.
*/
private Matrix4d buildOrigin( double x, double y, MathTransform toCartesian ) throws TransformException {
double delta = 1e-6;
double[] frame = new double[] {
x , y,
x+delta, y,
x , y+delta,
0 , 0 ,0 };
toCartesian.transform( frame, 0, frame, 0, 3 );
Vector3d o = new Vector3d(frame[0], frame[1], frame[2]),
a = new Vector3d(frame[3], frame[4], frame[5]),
b = new Vector3d(frame[6], frame[7], frame[8]),
c = new Vector3d();
a.sub( o );
b.sub( o );
a.normalize();
b.normalize();
c.cross( a, b );
Matrix4d out = new Matrix4d();
out.setRow( 0, -a.x, -a.y, -a.z, 0 );
out.setRow( 1, c.x, c.y, c.z, 0 );
out.setRow( 2, b.x, b.y, b.z, 0 );
out.setRow( 3, 0, 0, 0, 1 );
out.transform( o );
out.m03 = -o.x;
out.m13 = -o.y;
out.m23 = -o.z;
return out;
}
boolean checkForEnd = true;
int oldWidth, oldHeight;
public Vector3f oldCameraLoc = new Vector3f(575.0763f, 159.23715f, -580.0377f);
public Quaternion oldCameraRot = new Quaternion(0.029748844f, 0.9702514f, -0.16988836f, 0.16989778f);
public void simpleUpdate(float tpf) {
// cam.setFrustumFar( 1e4f );
if (oldWidth != cam.getWidth() || oldHeight != cam.getHeight()) {
buildBackground();
clearBackground();
oldWidth = cam.getWidth();
oldHeight = cam.getHeight();
}
// System.out.println(">>" + checkForEnd);
if (checkForEnd)
if (tool.isDragging()) {
tool.dragEnd();
}
checkForEnd = true;
oldCameraLoc = cam.getLocation();
oldCameraRot = cam.getRotation();
}
private AnalogListener moveListener = new AnalogListener() {
@Override
public void onAnalog( String name, float value, float tpf ) {
CollisionResult cr = getClicked();
Vector3f pos = null;
if (cr != null)
pos = cr.getContactPoint();
if (pos == null) {
Vector3f dir = cam.getWorldCoordinates( getInputManager().getCursorPosition(), -10 );
dir.subtractLocal( cam.getLocation() );
new Ray( cam.getLocation(), dir ).intersectsWherePlane( new Plane(Jme3z.UP, 0), pos = new Vector3f() );
}
cursorPosition = Jme3z.from( pos );
if (pos != null)
point.setPosition( pos.add ( cam.getDirection().mult( -0.3f ) ));
}
};
private Vector3f getSurfaceSelected(float dist) {
CollisionResult cr = getClicked();
Vector3f pos = null;
if (cr != null)
pos = cr.getContactPoint();
if (pos == null) {
Vector3f dir = cam.getWorldCoordinates( getInputManager().getCursorPosition(), -dist );
dir.subtractLocal( cam.getLocation() );
new Ray( cam.getLocation(), dir ).intersectsWherePlane( new Plane(Jme3z.UP, 0), pos = new Vector3f() );
}
return pos;
}
private AnalogListener analogListener = new AnalogListener() {
public void onAnalog( String name, float intensity, float tpf ) {
if ( name.equals( CLICK ) ) {
if ( tool.isDragging() ) {
tool.dragging( inputManager.getCursorPosition(), getSurfaceSelected( 0 ) );
checkForEnd = false;
} else {
CollisionResult cr = getClicked();
if ( cr == null )
tool.clear();
if ( tool instanceof PlaneTool || (cr != null && cr.getGeometry().getUserData( CLICK ) instanceof Handle ) ) {
tool.dragStart( cr == null ? null : cr.getGeometry(), inputManager.getCursorPosition(), getSurfaceSelected( 0 ) );
checkForEnd = false;
} else {
Spatial target = null;
Vector3f location;
if ( cr != null ) {
target = cr.getGeometry();
while ( target.getParent().getUserData( HandleMe.class.getSimpleName() ) != null )
target = target.getParent();
location = cr.getContactPoint();
} else {
location = point.getPosition();
}
tool.clickedOn( target, location, inputManager.getCursorPosition() );
}
}
}
}
};
public void clearBackground() {
if ( !TweedSettings.settings.SSAO ) {
if ( background == null ) {
background = new Picture( "background" );
}
Material mat1 = new Material( getAssetManager(), "Common/MatDefs/Misc/Unshaded.j3md" );
mat1.setColor( "Color", ColorRGBA.Black );
background.setMaterial( null );
background.setMaterial( mat1 );
}
}
final static String BG_LOC = "scratch/bg.jpg";
public void setBackground( BufferedImage bi ) {
if ( !TweedSettings.settings.SSAO ) {
try {
long hack = System.currentTimeMillis();
ImageIO.write( bi, "jpg", new File( JME + BG_LOC + hack + ".jpg" ) );
background.setMaterial( null );
getAssetManager().deleteFromCache( new AssetKey<>( BG_LOC ) ); //?! doesn't work
Material mat = new Material( getAssetManager(), "Common/MatDefs/Misc/Unshaded.j3md" );
mat.setTexture( "ColorMap", getAssetManager().loadTexture( BG_LOC + hack + ".jpg" ) );
// mat.setColor("Color", ColorRGBA.Red);
background.setMaterial( mat );
// background.setImage(assetManager, BG_LOC + hack + ".jpg" , false);
background.updateGeometricState();
gainFocus();
} catch ( IOException e ) {
e.printStackTrace();
}
}
}
protected void buildBackground() {
if ( !TweedSettings.settings.SSAO ) {
String bgKey = "background";
clearBackground();
background.setWidth( cam.getWidth() );
background.setHeight( cam.getHeight() );
background.setPosition( 0, 0 );
background.updateGeometricState();
ViewPort pv = renderManager.createPreView( bgKey, cam );
pv.setClearFlags( true, true, true );
viewPort.setClearFlags( false, true, true);
pv.attachScene( background );
background.updateGeometricState();
}
}
private CollisionResult getClicked() {
CollisionResults results = new CollisionResults();
Vector2f click2d = inputManager.getCursorPosition();
Vector3f click3d = cam.getWorldCoordinates(
new Vector2f(click2d.x, click2d.y), 0f).clone();
Vector3f dir = cam.getWorldCoordinates(
new Vector2f(click2d.x, click2d.y), 1f).subtractLocal(click3d).normalizeLocal();
Ray ray = new Ray(click3d, dir);
rootNode.collideWith(ray, results);
double dist = Double.MAX_VALUE;
CollisionResult bestDist = null;
for (CollisionResult c : results) {
if ( !Jme3z.isLine ( c.getGeometry().getMesh().getMode() ) ) {
float d = c.getDistance();
if (d < dist) {
dist = d;
bestDist = c;
}
}
}
if (bestDist != null)
return bestDist;
else
return null;
}
public void clearCurrentToolState() {
tool.clear();
}
private ButtonGroup toolBG = new ButtonGroup();
public void addUI( JPanel panel ) {
panel.setLayout( new ListDownLayout() );
panel.add( Fontz.setItalic( new JLabel("tools:")) );
for ( Tool t : tools ) {
JToggleButton tb = new JToggleButton( t.getName() );
toolBG.add( tb );
tb.addActionListener( new ActionListener() {
@Override
public void actionPerformed( ActionEvent e ) {
Tweed.this.setTool( t );
}
} );
panel.add( tb );
}
((JToggleButton)panel.getComponent( 1 ) ).setSelected( true );
}
public void resetCamera() {
cam.setLocation( new Vector3f() );
cam.setRotation( new Quaternion() );
setCameraSpeed( 0 );
TweedSettings.settings.ortho = false;
TweedSettings.settings.fov = 0;
setCameraPerspective();
}
public Component frame() {
return frame.frame;
}
public static String DATA; // we read the datafiles from here
public static String SCRATCH; // we read the datafiles from here
public static String JME; // root of asset resource-tree for jMonkey
public void initFrom( String dataDir ) {
if (JME != null) {
assetManager.unregisterLocator( JME, FileLocator.class );
deleteScratch();
}
frame.setGenUI( new JPanel() );
DATA = dataDir; // = System.getProperty("user.home")+"/data/regent"
SCRATCH = DATA + File.separator + "scratch" + File.separator;
deleteScratch();
new File (SCRATCH).mkdirs();
JME = DATA + File.separator;
cam.setLocation( TweedSettings.settings.cameraLocation );
cam.setRotation( TweedSettings.settings.cameraOrientation );
assetManager.registerLocator(Tweed.JME, FileLocator.class);
features = new FeatureCache( new File ( dataDir, FeatureCache.FEATURE_FOLDER ), this );
setFov( 0 );
setCameraSpeed( 0 );
setAmbient( 0 );
frame.setGens( TweedSettings.settings.genList );
if (plsr != null) {
rootNode.setShadowMode( ShadowMode.Off );
viewPort.removeProcessor( plsr );
}
if ( TweedSettings.settings.shadows ) {
plsr = new PointLightShadowRenderer( assetManager, 512 );
plsr.setLight( point );
plsr.setShadowZExtend( 50 );
plsr.setShadowIntensity( 0.5f );
plsr.setEdgeFilteringMode( EdgeFilteringMode.PCF4 );
rootNode.setShadowMode( ShadowMode.CastAndReceive );
viewPort.addProcessor( plsr );
}
if ( fpp != null ) {
viewPort.removeProcessor( fpp );
}
if ( TweedSettings.settings.SSAO ) {
fpp = new FilterPostProcessor( assetManager );
SSAOFilter filter = new SSAOFilter( 0.50997847f, 1.440001f, 1.39999998f, 0 );
// fpp.addFilter( new ColorOverlayFilter( ColorRGBA.Magenta ));
fpp.addFilter( filter );
fpp.addFilter( new FXAAFilter() );
viewPort.addProcessor( fpp );
}
WindowManager.setTitle( TweedFrame.APP_NAME +" " + new File( dataDir ).getName() );
}
public static void deleteScratch() {
try {
if ( Tweed.SCRATCH.contains( "scratch" ) )
try {
FileUtils.deleteDirectory( new File( Tweed.SCRATCH ) );
} catch ( IOException e ) {
e.printStackTrace();
}
} catch ( Throwable th ) {
th.printStackTrace();
}
}
public File makeWorkspaceRelative( File f ) {
return new File( DATA ).toPath().relativize( f.toPath() ).toFile();
}
public static File toWorkspace( String f ) {
return toWorkspace( new File (f) );
}
public static File toWorkspace( File f ) {
if (DATA == null)
return f;
if ( !f.isAbsolute() ) {
f = new File( new File( DATA ), f.toString() );
}
return f;
}
public double[] worldToLatLong( Tuple3d to3 ) {
double[] trans = new double[] { to3.x, 0, to3.z };
if ( TweedSettings.settings.gmlCoordSystem != null) try {
if ( TweedSettings.settings.gmlCoordSystem.equals( "EPSG:2062" ) ) { // oviedo :(
System.out.println( "******* dirty hack in place for CS" );
trans[ 2 ] += 258;
trans[ 0 ] -= 3;
trans[ 0 ] -= 3;
}
// two part transform to align heights - geoid for 4326 is different to 27700
{
Point3d tmp = new Point3d( trans );
TweedSettings.settings.fromOrigin.transform( tmp );
tmp.get( trans );
}
MathTransform cartesian2Country = CRS.findMathTransform(
DefaultGeocentricCRS.CARTESIAN,
kludgeCMS.get( TweedSettings.settings.gmlCoordSystem ),
true );
cartesian2Country.transform( trans, 0, trans, 0, 1 );
if ( TweedSettings.settings.gmlCoordSystem.equals( "EPSG:3042" ) ) { /* madrid?! */
double tmp = trans[ 0 ];
trans[ 0 ] = trans[ 1 ];
trans[ 1 ] = tmp;
}
MathTransform country2latlong;
country2latlong = CRS.findMathTransform(
kludgeCMS.get( TweedSettings.settings.gmlCoordSystem ),
CRS.decode( Tweed.LAT_LONG ),
true );
country2latlong.transform( trans, 0, trans, 0, 1 );
return new double[] {trans[0], trans[1]};
} catch ( Throwable e ) {
e.printStackTrace();
}
return new double[] {Double.NaN, Double.NaN };
}
}
|
package servidor;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import servidor.db.Conexion;
import interfacesComunes.Status;
import interfacesComunes.TwitterEvent;
import interfacesComunes.User;
public class TwitterEventImpl implements TwitterEvent{
private int id;
private User source;
private User target;
private Status status;
private Date createdAt;
private byte type;
private Conexion con;
/** Constructor para actualizacion de cuenta*/
public TwitterEventImpl(int id_source,byte type, Conexion con) throws SQLException{
TwitterEventImpl(id_source, 0, status, type, con);
}
/**Constructor para el follow*/
public TwitterEventImpl(int id_source, int id_target, byte type, Conexion con) throws SQLException{
TwitterEventImpl(id_source, id_target, null, type, con);
}
/**Tocho con todo, necesitamos este para favorite/unfavorite*/
public TwitterEventImpl(int id_source, int id_target,Status status, byte type, Conexion con) throws SQLException{
int id_status=0;
this.con=con;
this.createdAt=new Date();
this.type=type;
source= new UserImpl(id_source, this.con);
if (id_target==0)
target=null;
else
target= new UserImpl(id_target, this.con);
this.status=status;
if (this.status==null) //Si el id_status se guarda como 0 es que el Event no afecta a un tweet sino a un User
id_status=0;
else id_status=this.status.getId();
//Lo anadimos a la base de datos
this.con.updateQuery("INSERT INTO eventos (id_autor, id_destinatario, id_tweet,tipo, fecha)" +
"VALUES ("+id_source+","+id_target+","+id_status+","+type+","+createdAt+")");
ResultSet last_id = this.con.query("SELECT LAST_INSERT_ID()");
this.id=last_id.getInt(1);
}
public int getId() {
return id;
}
public Date getCreatedAt() {
return createdAt;
}
public User getSource() {
return source;
}
public User getTarget() {
return target;
}
public Object getTargetObject() {
if (status==null)
return getTarget();
else
return status;
}
public byte getType() {
return type;
}
public boolean is(byte type) {
if (this.type==type)
return true;
else
return false;
}
}
|
package be.ugent.service;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import be.ugent.Authentication;
import be.ugent.dao.PatientDao;
import be.ugent.entitity.Patient;
@Path("/PatientService")
public class PatientService {
PatientDao patientDao = new PatientDao();
@GET
@Path("/patients")
@Produces({ MediaType.APPLICATION_JSON })
public Response getUser(@QueryParam("firstName") String firstName, @QueryParam("lastName") String lastName, @HeaderParam("Authorization") String header) {
if(!Authentication.isAuthorized(header)){
return Response.status(403).build();
}
// System.out.println("Patient opgevraagd met naam: " + firstName + " " + lastName);
Patient retrieved = patientDao.getPatient(firstName, lastName);
retrieved.setPassword("");
return Response.ok(retrieved+"").build();
}
@GET
@Path("/advice")
@Produces({ MediaType.TEXT_PLAIN })
public Response getAdvice(@QueryParam("patientID") String patientID, @HeaderParam("Authorization") String header) {
if(!Authentication.isAuthorized(header)){
return Response.status(403).build();
}
// System.out.println("Patient opgevraagd met naam: " + firstName + " " + lastName);
Patient retrieved = patientDao.getPatienFromId(patientID);
return Response.ok().entity(retrieved.getAdvice()+"").build();
}
@GET
@Path("/login")
@Produces({ MediaType.APPLICATION_JSON })
public Response login(@HeaderParam("Authorization") String header) {
if(!Authentication.isAuthorized(header)){
return Response.status(403).build();
}
// System.out.println("User ingelogd met email:"+patientDao.getPatientFromHeader(header));
Patient retrieved = patientDao.getPatientFromHeader(header);
retrieved.setPassword("");
return Response.ok(retrieved+"").build();
}
@POST
@Path("/patients/hello")
@Consumes({MediaType.TEXT_PLAIN})
public Response hello(String user){
System.out.println("Hello "+user);
return Response.ok("Hello "+user).build();
}
@PUT
@Path("/patients")
@Consumes(MediaType.APPLICATION_JSON)
public Response addUser(String user){
System.out.println("pat: "+user);
System.out.println("Patient requested to add: "+user.toString());
Gson gson = new Gson();
Patient toAdd = gson.fromJson(user, Patient.class);
if(toAdd.getPatientID()==0){
PatientDao patientDao = new PatientDao();
toAdd.setPatientID(patientDao.getNewId());
}
JSONObject userJSON = null;
try {
userJSON = new JSONObject(user);
toAdd.setRelation(""+userJSON.get("relation"));
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return Response.status(417).build();
}
// System.out.println("Patient to add:"+toAdd);
if(patientDao.storePatient(toAdd)){
//return patient successfully created
return Response.status(201).entity(patientDao.getPatienFromId(toAdd.getPatientID()+"")).build();
}else{
//return record was already in database, or was wrong format
return Response.status(409).build();
}
}
@POST
@Path("/patients/update")
@Consumes(MediaType.APPLICATION_JSON)
public Response changeUser(String user){
System.out.println("Patient requested to change: "+user.toString());
Gson gson = new Gson();
Patient toAdd = gson.fromJson(user, Patient.class);
if(toAdd.getPatientID()<=0){
return Response.status(404).build();
}
JSONObject userJSON = null;
try {
userJSON = new JSONObject(user);
toAdd.setRelation(""+userJSON.get("relation"));
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// System.out.println("Patient to add:"+toAdd);
if(patientDao.updatePatient(toAdd)){
//return patient successfully created
return Response.status(202).entity(toAdd.getPatientID()).build();
}else{
//return record was already in database, or was wrong format
return Response.status(409).build();
}
}
@POST
@Path("/patients/diagnose")
@Consumes(MediaType.APPLICATION_JSON)
public Response diagnoseUser(String tupleID,@HeaderParam("Authorization") String header) {
if(!Authentication.isAuthorized(header)){
return Response.status(403).build();
}
System.out.println("Patient requested to diagnose: "+tupleID);
Gson gson = new Gson();
Patient toAdd = null;
try {
JSONObject tuple = gson.fromJson(tupleID, JsonObject.class);
toAdd = patientDao.getPatienFromId(""+Integer.parseInt(tuple.getString("patientID")));
if(toAdd.getPatientID()<=0){
return Response.status(404).build();
}
toAdd.setDiagnoseID(tuple.getInt("diagnoseID"));
} catch (NumberFormatException | JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(patientDao.updatePatient(toAdd)){
//return patient successfully created
return Response.status(202).entity(toAdd.getPatientID()).build();
}else{
//return record was already in database, or was wrong format
return Response.status(409).build();
}
}
}
|
package se.sics.cooja;
import java.util.Collection;
import javax.swing.JInternalFrame;
import org.jdom.Element;
/**
* COOJA plugin. For graphical plugins, extend abstract class VisPlugin.
* A plugin should also use ClassDecription and PluginType.
*
* @see se.sics.cooja.ClassDescription
* @see se.sics.cooja.PluginType
* @see se.sics.cooja.VisPlugin
*
* @author Fredrik Osterlind
*/
public interface Plugin {
/**
* Graphical component of plugin (if any)
*/
public JInternalFrame getGUI();
/**
* This method is called when an opened plugin is about to close.
* It should release any resources such as registered observers or
* opened interface visualizers.
*/
public void closePlugin();
/**
* This method is used by the simulator for book-keeping purposes, and should
* normally not be called by the plugin itself.
*
* @param tag
* Object
*/
public void tagWithObject(Object tag);
/**
* This method is used by the simulator for book-keeping purposes, and should
* normally not be called by the plugin itself.
*
* @return Object
*/
public Object getTag();
/**
* Returns XML elements representing the current config of this plugin. This
* is fetched by the simulator for example when saving a simulation
* configuration file. For example a plugin may return the current size and
* position. This method should however not return state specific information
* such as the value of a mote LED, or total number of motes. (All nodes are
* restarted when loading a simulation.)
*
* @see #setConfigXML(Collection, boolean)
* @return XML elements representing the current radio medium config
*/
public Collection<Element> getConfigXML();
/**
* Sets the current plugin config depending on the given XML elements.
*
* @see #getConfigXML()
* @param configXML
* Config XML elements
* @return True if config was set successfully, false otherwise
*/
public boolean setConfigXML(Collection<Element> configXML,
boolean visAvailable);
}
|
package jolie.doc;
import java.io.IOException;
import java.net.URI;
import jolie.CommandLineException;
import jolie.CommandLineParser;
import jolie.doc.impl.html.HtmlDocumentCreator;
import jolie.lang.parse.ParserException;
import jolie.lang.parse.SemanticVerifier;
import jolie.lang.parse.ast.Program;
import jolie.lang.parse.util.ParsingUtils;
import jolie.lang.parse.util.ProgramInspector;
public class JolieDoc
{
public static void main( String[] args )
{
try {
CommandLineParser cmdParser = new CommandLineParser( args, JolieDoc.class.getClassLoader() );
args = cmdParser.arguments();
SemanticVerifier.Configuration configuration = new SemanticVerifier.Configuration();
configuration.setCheckForMain( false );
Program program = ParsingUtils.parseProgram(
cmdParser.programStream(),
URI.create( "file:" + cmdParser.programFilepath() ),
cmdParser.includePaths(), JolieDoc.class.getClassLoader(), cmdParser.definedConstants(),
configuration
);
ProgramInspector inspector=ParsingUtils.createInspector( program );
HtmlDocumentCreator document = new HtmlDocumentCreator( inspector, program.context().source() );
document.ConvertDocument();
/*
HTMLDocumentCreator document = new HTMLDocumentCreator();
document.createDocument( program, cmdParser.programFilepath() );*/
} catch( CommandLineException e ) {
System.out.println( e.getMessage() );
System.out.println( "Syntax is: joliedoc [jolie options] <jolie filename> [interface name list]" );
} catch( IOException e ) {
e.printStackTrace();
} catch( ParserException e ) {
System.out.println( e.getMessage() );
/*} catch( DocumentCreationException e ) {
e.printStackTrace();*/
}
}
}
|
package Processes;
import Abstract.AbstractProcess;
import Abstract.AbstractVectorPuzzle;
import Main.PuzzleContainer;
import PuzzlePieces.Block;
import PuzzlePieces.Square;
import PuzzlePieces.Vector;
import SubPuzzles.BlockPuzzle;
import java.util.*;
public class NakedTwin extends AbstractProcess {
public NakedTwin(PuzzleContainer pc) { super(pc); }
/**
* Considers each block as an exposed pairing of candidates
* If there is an exposed pairing, remove that pair from the candidate sets
* in affected blocks (row, col, block)
* @return
*/
public boolean run_process()
{
boolean change_made = false;
List<Map<Set<Integer>, Integer>> row_candidate_counts = get_vector_set_counts(row_puzzle);
List<Map<Set<Integer>, Integer>> col_candidate_counts = get_vector_set_counts(col_puzzle);
List<Map<Set<Integer>, Integer>> block_candidate_counts = get_block_set_counts(block_puzzle);
change_made |= vector_detect_naked_twin(row_candidate_counts, row_puzzle);
change_made |= vector_detect_naked_twin(col_candidate_counts, col_puzzle);
change_made |= block_detect_naked_twin(block_candidate_counts, block_puzzle);
return false;
}
private boolean vector_detect_naked_twin(List<Map<Set<Integer>, Integer>> vector_candidate_counts,
AbstractVectorPuzzle puzzle)
{
boolean change_made = false;
for (int row = 0; row < vector_candidate_counts.size(); row++)
{
Map<Set<Integer>, Integer> current_map = vector_candidate_counts.get(row);
for (Set<Integer> pair : current_map.keySet())
{
if (current_map.get(pair) == 2)
{
vector_remove_naked_twin_candidates(pair, puzzle.get_vector(row));
change_made = true;
}
}
}
return change_made;
}
private boolean block_detect_naked_twin(List<Map<Set<Integer>, Integer>> block_candidate_counts,
BlockPuzzle puzzle)
{
boolean change_made = false;
for (int block = 0; block < block_candidate_counts.size(); block++)
{
Map<Set<Integer>, Integer> current_map = block_candidate_counts.get(block);
for (Set<Integer> pair : current_map.keySet())
{
if (current_map.get(pair) == 2)
{
block_remove_naked_twin_candidates(pair, puzzle.get_block(block/3, block%3));
change_made = true;
}
}
}
return change_made;
}
private void vector_remove_naked_twin_candidates(Set<Integer> pair, Vector vector)
{
Iterator<Square> vector_iterator = vector.iterator();
while (vector_iterator.hasNext())
{
Square current_square = vector_iterator.next();
if (current_square.is_assigned() || current_square.get_candidates().equals(pair))
{
continue;
}
current_square.remove_candidates(pair);
}
}
private void block_remove_naked_twin_candidates(Set<Integer> pair, Block block)
{
Iterator<Square> block_iterator = block.iterator();
while (block_iterator.hasNext())
{
Square current_square = block_iterator.next();
if (current_square.is_assigned() || current_square.get_candidates().equals(pair))
{
continue;
}
current_square.remove_candidates(pair);
}
}
private List<Map<Set<Integer>, Integer>> get_vector_set_counts(AbstractVectorPuzzle puzzle)
{
List<Map<Set<Integer>, Integer>> toReturn = new ArrayList<Map<Set<Integer>, Integer>>();
/* checking for exposed pairs on rows */
Iterator<Vector> row_iterator = puzzle.iterator();
while (row_iterator.hasNext())
{
Vector current_row = row_iterator.next();
Map<Set<Integer>, Integer> set_counts = new HashMap<Set<Integer>, Integer>();
/* Iterate through all Squares in current vector */
Iterator<Square> square_iterator = current_row.iterator();
while (square_iterator.hasNext())
{
Square current_square = square_iterator.next();
Set<Integer> current_candidates = new HashSet<Integer>(current_square.get_candidates());
/* If we're not considering a PAIR, move on */
if (current_square.is_assigned() || current_candidates.size() != 2)
{
continue;
}
if (!set_counts.containsKey(current_candidates))
{
set_counts.put(current_candidates, 1);
}
else
{
set_counts.put(current_candidates, set_counts.get(current_candidates) + 1);
}
}
toReturn.add(set_counts);
}
return toReturn;
}
private List<Map<Set<Integer>, Integer>> get_block_set_counts(BlockPuzzle puzzle)
{
List<Map<Set<Integer>, Integer>> toReturn = new ArrayList<Map<Set<Integer>, Integer>>();
/* checking for exposed pairs on rows */
Iterator<Block> block_iterator = puzzle.iterator();
while (block_iterator.hasNext())
{
Block current_block = block_iterator.next();
Map<Set<Integer>, Integer> set_counts = new HashMap<Set<Integer>, Integer>();
/* Iterate through all Squares in current vector */
Iterator<Square> square_iterator = current_block.iterator();
while (square_iterator.hasNext())
{
Square current_square = square_iterator.next();
Set<Integer> current_candidates = new HashSet<Integer>(current_square.get_candidates());
/* If we're not considering a PAIR, move on */
if (current_square.is_assigned() || current_candidates.size() != 2)
{
continue;
}
if (!set_counts.containsKey(current_candidates))
{
set_counts.put(current_candidates, 1);
}
else
{
set_counts.put(current_candidates, set_counts.get(current_candidates) + 1);
}
}
toReturn.add(set_counts);
}
return toReturn;
}
}
|
package org.lp20.aikuma.ui;
import android.media.AudioManager;
import android.content.Context;
import android.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.UUID;
import org.lp20.aikuma.model.Recording;
import org.lp20.aikuma.audio.Audio;
import org.lp20.aikuma.audio.Beeper;
import org.lp20.aikuma.audio.Player;
import org.lp20.aikuma.audio.record.PhoneRespeaker;
import org.lp20.aikuma.audio.SimplePlayer;
import org.lp20.aikuma.audio.InterleavedPlayer;
import org.lp20.aikuma.model.Segments;
import org.lp20.aikuma.model.Segments.Segment;
import org.lp20.aikuma.ui.sensors.ProximityDetector;
import org.lp20.aikuma.R;
/**
* @author Oliver Adams <oliver.adams@gmail.com>
* @author Florian Hanke <florian.hanke@gmail.com>
*/
public class PhoneRespeakFragment extends Fragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.phone_respeak_fragment, container, false);
seekBar = (InterleavedSeekBar) v.findViewById(R.id.InterleavedSeekBar);
seekBar.setOnSeekBarChangeListener(
new SeekBar.OnSeekBarChangeListener() {
int originalProgress;
public void onProgressChanged(SeekBar seekBar,
int progress, boolean fromUser) {
if (fromUser) {
seekBar.setProgress(originalProgress);
}
}
public void onStopTrackingTouch(SeekBar _seekBar) {};
public void onStartTrackingTouch(SeekBar _seekBar) {
originalProgress = seekBar.getProgress();
};
});
seekBar.invalidate();
return v;
}
@Override
public void onPause() {
super.onPause();
haltRespeaking();
this.proximityDetector.stop();
Audio.reset(getActivity());
}
@Override
public void onResume() {
super.onResume();
this.proximityDetector = new ProximityDetector(getActivity()) {
public void near(float distance) {
resumeRespeaking();
/*
if (!respeaker.getSimplePlayer().isPlaying()) {
play();
}
*/
}
public void far(float distance) {
haltRespeaking();
/*
if (respeaker.getSimplePlayer().isPlaying()) {
pause();
}
*/
}
};
this.proximityDetector.start();
Audio.playThroughEarpiece(getActivity(), false);
}
@Override
public void onStop() {
super.onStop();
}
@Override
public void onDestroy() {
super.onDestroy();
if (respeaker != null) {
//If you hit the stop button really quickly, the player may not
//have been initialized fully.
respeaker.release();
}
}
private void stopThread(Thread thread) {
if (thread != null) {
thread.interrupt();
}
}
private void haltRespeaking() {
respeaker.halt();
stopThread(seekBarThread);
}
private void resumeRespeaking() {
respeaker.resume();
seekBarThread = new Thread(new Runnable() {
public void run() {
int currentPosition;
while (true) {
currentPosition = respeaker.getSimplePlayer().getCurrentMsec();
seekBar.setProgress(
(int)(((float)currentPosition/(float)
respeaker.getSimplePlayer().getDurationMsec())*100));
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
return;
}
}
}
});
seekBarThread.start();
}
public void setRecording(Recording recording) {
this.recording = recording;
}
public void setSampleRate(int sampleRate) {
this.sampleRate = sampleRate;
}
public void setUUID(UUID uuid) {
this.uuid = uuid;
}
public void setPhoneRespeaker(PhoneRespeaker respeaker) {
this.respeaker = respeaker;
respeaker.getSimplePlayer().setOnCompletionListener(onCompletionListener);
}
private Player.OnCompletionListener onCompletionListener =
new Player.OnCompletionListener() {
public void onCompletion(Player _player) {
stopThread(seekBarThread);
seekBar.setProgress(seekBar.getMax());
Beeper.beep(getActivity(), null);
}
};
private PhoneRespeaker respeaker;
private ImageButton playPauseButton;
private InterleavedSeekBar seekBar;
private Thread seekBarThread;
private Recording recording;
private UUID uuid;
private int sampleRate;
private ProximityDetector proximityDetector;
}
|
package com.google.copybara.git;
import static com.google.copybara.git.GitOptions.GIT_FIRST_COMMIT_FLAG;
import com.google.common.base.MoreObjects;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.copybara.ChangeRejectedException;
import com.google.copybara.Destination;
import com.google.copybara.GeneralOptions;
import com.google.copybara.Options;
import com.google.copybara.RepoException;
import com.google.copybara.TransformResult;
import com.google.copybara.config.ConfigValidationException;
import com.google.copybara.doc.annotations.DocElement;
import com.google.copybara.doc.annotations.DocField;
import com.google.copybara.util.DiffUtil;
import com.google.copybara.util.PathMatcherBuilder;
import com.google.copybara.util.console.Console;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Nullable;
/**
* A Git repository destination.
*/
public final class GitDestination implements Destination {
interface CommitGenerator {
/**
* Generates a commit message based on the uncommitted index stored in the given repository.
*/
String message(TransformResult transformResult, GitRepository repo)
throws RepoException;
}
private static final class DefaultCommitGenerator implements CommitGenerator {
@Override
public String message(TransformResult transformResult, GitRepository repo) {
return String.format("%s\n%s: %s\n",
transformResult.getSummary(),
transformResult.getOriginRef().getLabelName(),
transformResult.getOriginRef().asString()
);
}
}
private static final Logger logger = Logger.getLogger(GitDestination.class.getName());
private final String repoUrl;
private final String fetch;
private final String push;
private final GitOptions gitOptions;
private final boolean verbose;
private final CommitGenerator commitGenerator;
private final ProcessPushOutput processPushOutput;
GitDestination(String repoUrl, String fetch, String push, GitOptions gitOptions, boolean verbose,
CommitGenerator commitGenerator, ProcessPushOutput processPushOutput) {
this.repoUrl = Preconditions.checkNotNull(repoUrl);
this.fetch = Preconditions.checkNotNull(fetch);
this.push = Preconditions.checkNotNull(push);
this.gitOptions = Preconditions.checkNotNull(gitOptions);
this.verbose = verbose;
this.commitGenerator = Preconditions.checkNotNull(commitGenerator);
this.processPushOutput = Preconditions.checkNotNull(processPushOutput);
}
/**
* Throws an exception if the user.email or user.name Git configuration settings are not set. This
* helps ensure that the committer field of generated commits is correct.
*/
private void verifyUserInfoConfigured(GitRepository repo) throws RepoException {
String output = repo.simpleCommand("config", "-l").getStdout();
boolean nameConfigured = false;
boolean emailConfigured = false;
for (String line : output.split("\n")) {
if (line.startsWith("user.name=")) {
nameConfigured = true;
} else if (line.startsWith("user.email=")) {
emailConfigured = true;
}
}
if (!nameConfigured || !emailConfigured) {
throw new RepoException("'user.name' and/or 'user.email' are not configured. Please run "
+ "`git config --global SETTING VALUE` to set them");
}
}
@Override
public Writer newWriter() {
return new WriterImpl();
}
private class WriterImpl implements Writer {
@Nullable private GitRepository scratchClone;
@Override
public WriterResult write(TransformResult transformResult, Console console) throws RepoException {
logger.log(Level.INFO, "Exporting from " + transformResult.getPath() + " to: " + this);
String baseline = transformResult.getBaseline();
if (scratchClone == null) {
console.progress("Git Destination: Fetching " + repoUrl);
scratchClone = cloneBaseline();
if (gitOptions.gitFirstCommit && baseline != null) {
throw new RepoException(
"Cannot use " + GIT_FIRST_COMMIT_FLAG + " and a previous baseline (" + baseline
+ "). Migrate some code to " + repoUrl + ":" + repoUrl + " first.");
}
if (!gitOptions.gitFirstCommit) {
console.progress("Git Destination: Checking out " + fetch);
// If baseline is not null we sync first to the baseline and apply the changes on top of
// that. Then we will rebase the new change to FETCH_HEAD.
scratchClone.simpleCommand("checkout", "-q", baseline != null ? baseline : "FETCH_HEAD");
}
if (!Strings.isNullOrEmpty(gitOptions.gitCommitterName)) {
scratchClone.simpleCommand("config", "user.name", gitOptions.gitCommitterName);
}
if (!Strings.isNullOrEmpty(gitOptions.gitCommitterEmail)) {
scratchClone.simpleCommand("config", "user.email", gitOptions.gitCommitterEmail);
}
verifyUserInfoConfigured(scratchClone);
}
console.progress("Git Destination: Adding files for push");
GitRepository alternate = scratchClone.withWorkTree(transformResult.getPath());
alternate.simpleCommand("add", "--all");
new AddMatchingFilesToIndexVisitor(scratchClone, transformResult.getExcludedDestinationPaths())
.walk();
if (transformResult.isAskForConfirmation()) {
// The git repo contains the staged changes at this point. Git diff writes to Stdout
console.info(DiffUtil.colorize(
console, alternate.simpleCommand("diff", "--staged").getStdout()));
if (!console.promptConfirmation(
String.format("Proceed with push to %s %s?", repoUrl, push))) {
console.warn("Migration aborted by user.");
throw new ChangeRejectedException(
"User aborted execution: did not confirm diff changes.");
}
}
alternate.simpleCommand("commit",
"--author", transformResult.getAuthor().toString(),
"--date", transformResult.getTimestamp() + " +0000",
"-m", commitGenerator.message(transformResult, alternate));
console.progress(String.format("Git Destination: Pushing to %s %s", repoUrl, push));
if (baseline != null) {
alternate.rebase("FETCH_HEAD");
}
// Git push writes to Stderr
processPushOutput.process(
alternate.simpleCommand("push", repoUrl, "HEAD:" + GitDestination.this.push).getStderr());
return WriterResult.OK;
}
}
private GitRepository cloneBaseline() throws RepoException {
GitRepository scratchClone = GitRepository.initScratchRepo(verbose);
try {
scratchClone.simpleCommand("fetch", repoUrl, fetch);
if (gitOptions.gitFirstCommit) {
throw new RepoException("'" + fetch + "' already exists in '" + repoUrl + "'.");
}
} catch (CannotFindReferenceException e) {
if (!gitOptions.gitFirstCommit) {
throw new RepoException("'" + fetch + "' doesn't exist in '" + repoUrl
+ "'. Use --git-first-commit flag if you want to push anyway");
}
}
return scratchClone;
}
/**
* A walker which adds all files matching a PathMatcher to the index of a Git repo using
* {@code git add}.
*/
private static final class AddMatchingFilesToIndexVisitor extends SimpleFileVisitor<Path> {
private final GitRepository repo;
private final PathMatcher matcher;
AddMatchingFilesToIndexVisitor(GitRepository repo, PathMatcherBuilder matcherBuilder) {
this.repo = repo;
this.matcher = matcherBuilder.relativeTo(repo.getWorkTree());
}
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
return dir.equals(repo.getGitDir())
? FileVisitResult.SKIP_SUBTREE
: FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if (matcher.matches(file)) {
try {
repo.simpleCommand("add", file.toString());
} catch (RepoException e) {
throw new IOException(e);
}
}
return FileVisitResult.CONTINUE;
}
void walk() throws RepoException {
try {
Files.walkFileTree(repo.getWorkTree(), this);
} catch (IOException e) {
throw new RepoException("Error when adding excludedDestinationPaths to destination.", e);
}
}
}
@Nullable
@Override
public String getPreviousRef(String labelName) throws RepoException {
if (gitOptions.gitFirstCommit) {
return null;
}
GitRepository gitRepository = cloneBaseline();
String commit = gitRepository.revParse("FETCH_HEAD");
String labelPrefix = labelName + ": ";
// Look at commits in reverse chronological order, starting from FETCH_HEAD.
while (!commit.isEmpty()) {
// Get commit message body.
String body = gitRepository.simpleCommand("log", "--no-color", "--format=%b", commit, "-1")
.getStdout();
for (String line : body.split("\n")) {
if (line.startsWith(labelPrefix)) {
return line.substring(labelPrefix.length());
}
}
// Get parent hash.
commit = gitRepository.simpleCommand("log", "--no-color", "--format=%P", commit, "-1")
.getStdout().trim();
if (commit.indexOf(' ') != -1) {
throw new RepoException(
"Found commit with multiple parents (merge commit) when looking for "
+ labelName + ". Please invoke Copybara with the --last-rev flag.");
}
}
return null;
}
@Override
public String getLabelNameWhenOrigin() {
return GitRepository.GIT_ORIGIN_REV_ID;
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("repoUrl", repoUrl)
.add("fetch", fetch)
.add("push", push)
.toString();
}
@DocElement(yamlName = "!GitDestination",
description = "Creates a commit in a git repository using the transformed worktree",
elementKind = Destination.class, flags = {GitOptions.class})
public static final class Yaml extends AbstractDestinationYaml {
private String push;
/**
* Indicates the ref to push to after the repository has been updated. For instance, to create a
* Gerrit review, this can be {@code refs/for/master}. This can also be set to the same value as
* {@code defaultTrackingRef}.
*/
@DocField(description = "Reference to use for pushing the change, for example 'master'")
public void setPush(String push) {
this.push = push;
}
@Override
public GitDestination withOptions(Options options, String configName)
throws ConfigValidationException {
ConfigValidationException.checkNotMissing(url, "url");
ConfigValidationException.checkNotMissing(fetch, "fetch");
ConfigValidationException.checkNotMissing(push, "push");
return newGitDestination(options, url, fetch, push);
}
}
/**
* Builds a new {@link GitDestination}.
*
* <p>This method is invoked both from Yaml and Skylark configurations.
*/
static GitDestination newGitDestination(Options options, String url, String fetch, String push) {
return new GitDestination(
url, fetch, push,
options.get(GitOptions.class),
options.get(GeneralOptions.class).isVerbose(),
new DefaultCommitGenerator(),
new ProcessPushOutput()
);
}
/**
* Process the server response from the push command
*/
static class ProcessPushOutput {
void process(String output) {
}
}
}
|
package net.somethingdreadful.MAL;
import android.app.DialogFragment;
import android.app.FragmentManager;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import android.widget.ViewFlipper;
import com.crashlytics.android.Crashlytics;
import net.somethingdreadful.MAL.adapters.DetailViewPagerAdapter;
import net.somethingdreadful.MAL.api.MALApi;
import net.somethingdreadful.MAL.api.MALApi.ListType;
import net.somethingdreadful.MAL.api.response.Anime;
import net.somethingdreadful.MAL.api.response.GenericRecord;
import net.somethingdreadful.MAL.api.response.Manga;
import net.somethingdreadful.MAL.dialog.RemoveConfirmationDialogFragment;
import net.somethingdreadful.MAL.dialog.UpdatePasswordDialogFragment;
import net.somethingdreadful.MAL.sql.DatabaseManager;
import net.somethingdreadful.MAL.tasks.APIAuthenticationErrorListener;
import net.somethingdreadful.MAL.tasks.NetworkTask;
import net.somethingdreadful.MAL.tasks.NetworkTaskCallbackListener;
import net.somethingdreadful.MAL.tasks.TaskJob;
import net.somethingdreadful.MAL.tasks.WriteDetailTask;
import java.io.Serializable;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Locale;
public class DetailView extends ActionBarActivity implements Serializable, NetworkTaskCallbackListener, APIAuthenticationErrorListener, SwipeRefreshLayout.OnRefreshListener {
public ListType type;
public Anime animeRecord;
public Manga mangaRecord;
public String username;
public PrefManager pref;
public DetailViewGeneral general;
public DetailViewDetails details;
DetailViewPagerAdapter PageAdapter;
int recordID;
private ActionBar actionBar;
private ViewPager viewPager;
private ViewFlipper viewFlipper;
private Menu menu;
private Context context;
private ArrayList<String> tabs = new ArrayList<String>();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detailview);
actionBar = getSupportActionBar();
context = getApplicationContext();
username = getIntent().getStringExtra("username");
pref = new PrefManager(this);
type = (ListType) getIntent().getSerializableExtra("recordType");
recordID = getIntent().getIntExtra("recordID", -1);
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
viewPager = (ViewPager) findViewById(R.id.pager);
viewFlipper = (ViewFlipper) findViewById(R.id.viewFlipper);
PageAdapter = new DetailViewPagerAdapter(getFragmentManager(), this);
viewPager.setAdapter(PageAdapter);
if (savedInstanceState != null) {
animeRecord = (Anime) savedInstanceState.getSerializable("anime");
mangaRecord = (Manga) savedInstanceState.getSerializable("manga");
}
}
/*
* Set text in all fragments
*/
public void setText() {
try {
actionBar.setTitle(type == ListType.ANIME ? animeRecord.getTitle() : mangaRecord.getTitle());
if (general != null) {
general.setText();
}
if (details != null && !isEmpty()) {
details.setText();
}
if (!isEmpty()) {
setupBeam();
}
} catch (Exception e) {
Crashlytics.log(Log.ERROR, "MALX", "DetailView.setText(): " + e.getMessage());
if (!(e instanceof IllegalStateException))
Crashlytics.logException(e);
}
setMenu();
}
/*
* Checks if the records are null to prevent nullpointerexceptions
*/
public boolean isEmpty() {
return animeRecord == null && mangaRecord == null;
}
/*
* Checks if this record is in our list
*/
public boolean isAdded() {
return !isEmpty() && (ListType.ANIME.equals(type) ? animeRecord.getWatchedStatus() != null : mangaRecord.getReadStatus() != null);
}
/*
* Set refreshing on all SwipeRefreshViews
*/
public void setRefreshing(Boolean show) {
if (general != null) {
general.swipeRefresh.setRefreshing(show);
general.swipeRefresh.setEnabled(!show);
}
if (details != null) {
details.swipeRefresh.setRefreshing(show);
details.swipeRefresh.setEnabled(!show);
}
}
/*
* Show the dialog with the tag
*/
public void showDialog(String tag, DialogFragment dialog) {
FragmentManager fm = getFragmentManager();
dialog.show(fm, "fragment_" + tag);
}
/*
* Episode picker dialog
*/
public void onDialogDismissed(int newValue) {
if (newValue != animeRecord.getWatchedEpisodes()) {
if (newValue == animeRecord.getEpisodes()) {
animeRecord.setWatchedStatus(GenericRecord.STATUS_COMPLETED);
}
if (newValue == 0) {
animeRecord.setWatchedStatus(Anime.STATUS_PLANTOWATCH);
}
animeRecord.setWatchedEpisodes(newValue);
animeRecord.setDirty(true);
setText();
}
}
/*
* Set the right menu items.
*/
public void setMenu() {
if (menu != null) {
if (isAdded()) {
menu.findItem(R.id.action_Remove).setVisible(!isEmpty() && MALApi.isNetworkAvailable(this));
menu.findItem(R.id.action_addToList).setVisible(false);
} else {
menu.findItem(R.id.action_Remove).setVisible(false);
menu.findItem(R.id.action_addToList).setVisible(!isEmpty());
}
menu.findItem(R.id.action_Share).setVisible(!isEmpty());
menu.findItem(R.id.action_ViewMALPage).setVisible(!isEmpty());
}
}
/*
* Add record to list
*/
public void addToList() {
if (!isEmpty()) {
if (type.equals(ListType.ANIME)) {
animeRecord.setCreateFlag(true);
animeRecord.setWatchedStatus(Anime.STATUS_WATCHING);
animeRecord.setDirty(true);
} else {
mangaRecord.setCreateFlag(true);
mangaRecord.setReadStatus(Manga.STATUS_READING);
mangaRecord.setDirty(true);
}
setText();
}
}
/*
* Open the share dialog
*/
public void Share() {
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
sharingIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
sharingIntent.putExtra(Intent.EXTRA_TEXT, makeShareText());
startActivity(Intent.createChooser(sharingIntent, "Share via"));
}
/*
* Make the share text for the share dialog
*/
public String makeShareText() {
String shareText = pref.getCustomShareText();
shareText = shareText.replace("$title;", actionBar.getTitle());
shareText = shareText.replace("$link;", "http://myanimelist.net/" + type.toString().toLowerCase(Locale.US) + "/" + Integer.toString(recordID));
shareText = shareText + getResources().getString(R.string.customShareText_fromAtarashii);
return shareText;
}
/*
* Check if the database contains the record.
*
* If it does contains the record it will set it.
*/
private boolean getRecordFromDB() {
DatabaseManager dbMan = new DatabaseManager(this);
if (type.equals(ListType.ANIME)) {
animeRecord = dbMan.getAnime(recordID, username);
return animeRecord != null;
} else {
mangaRecord = dbMan.getManga(recordID, username);
return mangaRecord != null;
}
}
/*
* Check if the record contains all the details.
*
* Without this function the fragments will call setText while it isn't loaded.
* This will cause a nullpointerexception.
*/
public boolean isDone() {
return (!isEmpty()) && (type.equals(ListType.ANIME) ? animeRecord.getSynopsis() != null : mangaRecord.getSynopsis() != null);
}
/*
* Get the translation from strings.xml
*/
private String getStringFromResourceArray(int resArrayId, int notFoundStringId, int index) {
Resources res = getResources();
try {
String[] types = res.getStringArray(resArrayId);
if (index < 0 || index >= types.length) // make sure to have a valid array index
return res.getString(notFoundStringId);
else
return types[index];
} catch (Resources.NotFoundException e) {
Crashlytics.logException(e);
return res.getString(notFoundStringId);
}
}
/*
* Get the anime or manga mediatype translations
*/
public String getTypeString(int typesInt) {
if (type.equals(ListType.ANIME))
return getStringFromResourceArray(R.array.mediaType_Anime, R.string.unknown, typesInt);
else
return getStringFromResourceArray(R.array.mediaType_Manga, R.string.unknown, typesInt);
}
/*
* Get the anime or manga status translations
*/
public String getStatusString(int statusInt) {
if (type.equals(ListType.ANIME))
return getStringFromResourceArray(R.array.mediaStatus_Anime, R.string.unknown, statusInt);
else
return getStringFromResourceArray(R.array.mediaStatus_Manga, R.string.unknown, statusInt);
}
/*
* Get the anime or manga genre translations
*/
public ArrayList<String> getGenresString(ArrayList<Integer> genresInt) {
ArrayList<String> genres = new ArrayList<String>();
for (Integer genreInt : genresInt) {
genres.add(getStringFromResourceArray(R.array.genresArray, R.string.unknown, genreInt));
}
return genres;
}
/*
* Get the anime or manga classification translations
*/
public String getClassificationString(Integer classificationInt) {
return getStringFromResourceArray(R.array.classificationArray, R.string.unknown, classificationInt);
}
public String getUserStatusString(int statusInt) {
return getStringFromResourceArray(R.array.mediaStatus_User, R.string.unknown, statusInt);
}
/*
* Get the records (Anime/Manga)
*
* Try to fetch them from the Database first to get reading/watching details.
* If the record doesn't contains a synopsis this method will get it.
*/
public void getRecord(boolean forceUpdate) {
setRefreshing(true);
toggleLoadingIndicator(isEmpty());
actionBar.setTitle(R.string.layout_card_loading);
boolean loaded = false;
if (!forceUpdate || !MALApi.isNetworkAvailable(this)) {
if (getRecordFromDB()) {
setText();
setRefreshing(false);
if (isDone()) {
loaded = true;
toggleLoadingIndicator(false);
}
}
}
if (MALApi.isNetworkAvailable(this)) {
if (!loaded || forceUpdate) {
Bundle data = new Bundle();
boolean saveDetails = username != null && !username.equals("") && isAdded();
if (saveDetails) {
data.putSerializable("record", type.equals(ListType.ANIME) ? animeRecord : mangaRecord);
} else {
data.putInt("recordID", recordID);
}
new NetworkTask(saveDetails ? TaskJob.GETDETAILS : TaskJob.GET, type, this, data, this, this).execute();
}
} else {
toggleLoadingIndicator(false);
setRefreshing(false);
if (isEmpty()) {
actionBar.setTitle("");
toggleNoNetworkCard(true);
}
}
}
public void onStatusDialogDismissed(String currentStatus) {
if (type.equals(ListType.ANIME)) {
animeRecord.setWatchedStatus(currentStatus);
if (GenericRecord.STATUS_COMPLETED.equals(currentStatus)) {
if (animeRecord.getEpisodes() != 0)
animeRecord.setWatchedEpisodes(animeRecord.getEpisodes());
}
animeRecord.setDirty(true);
} else {
mangaRecord.setReadStatus(currentStatus);
if (GenericRecord.STATUS_COMPLETED.equals(currentStatus)) {
if (mangaRecord.getChapters() != 0)
mangaRecord.setChaptersRead(mangaRecord.getChapters());
if (mangaRecord.getVolumes() != 0)
mangaRecord.setVolumesRead(mangaRecord.getVolumes());
}
mangaRecord.setDirty(true);
}
setText();
}
public void onMangaDialogDismissed(int value, int value2) {
if (value != mangaRecord.getChaptersRead()) {
if (value == mangaRecord.getChapters() && mangaRecord.getChapters() != 0) {
mangaRecord.setReadStatus(GenericRecord.STATUS_COMPLETED);
}
if (value == 0) {
mangaRecord.setReadStatus(Manga.STATUS_PLANTOREAD);
}
mangaRecord.setChaptersRead(value);
mangaRecord.setDirty(true);
}
if (value2 != mangaRecord.getVolumesRead()) {
if (value2 == mangaRecord.getVolumes()) {
mangaRecord.setReadStatus(GenericRecord.STATUS_COMPLETED);
}
if (value2 == 0) {
mangaRecord.setReadStatus(Manga.STATUS_PLANTOREAD);
}
mangaRecord.setVolumesRead(value2);
mangaRecord.setDirty(true);
}
setText();
setMenu();
}
public void onRemoveConfirmed() {
if (type.equals(ListType.ANIME)) {
animeRecord.setDirty(true);
animeRecord.setDeleteFlag(true);
} else {
mangaRecord.setDirty(true);
mangaRecord.setDeleteFlag(true);
}
finish();
}
@Override
protected void onSaveInstanceState(Bundle State) {
super.onSaveInstanceState(State);
State.putSerializable("anime", animeRecord);
State.putSerializable("manga", mangaRecord);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_detail_view, menu);
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
this.menu = menu;
setMenu();
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
break;
case R.id.action_Share:
Share();
break;
case R.id.action_Remove:
showDialog("removeConfirmation", new RemoveConfirmationDialogFragment());
break;
case R.id.action_addToList:
addToList();
break;
case R.id.action_ViewMALPage:
Uri malurl = Uri.parse("http://myanimelist.net/" + type.toString().toLowerCase(Locale.US) + "/" + recordID + "/");
startActivity(new Intent(Intent.ACTION_VIEW, malurl));
break;
case R.id.action_copy:
android.content.ClipboardManager clipBoard = (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
android.content.ClipData clipData = android.content.ClipData.newPlainText("Atarashii", type == ListType.ANIME ? animeRecord.getTitle() : mangaRecord.getTitle());
clipBoard.setPrimaryClip(clipData);
break;
}
return true;
}
@Override
public void onPause() {
super.onPause();
if (animeRecord == null && mangaRecord == null)
return; // nothing to do
try {
if (type.equals(ListType.ANIME)) {
if (animeRecord.getDirty() && !animeRecord.getDeleteFlag()) {
new WriteDetailTask(type, TaskJob.UPDATE, this, this).execute(animeRecord);
} else if (animeRecord.getDeleteFlag()) {
new WriteDetailTask(type, TaskJob.FORCESYNC, this, this).execute(animeRecord);
}
} else if (type.equals(ListType.MANGA)) {
if (mangaRecord.getDirty() && !mangaRecord.getDeleteFlag()) {
new WriteDetailTask(type, TaskJob.UPDATE, this, this).execute(mangaRecord);
} else if (mangaRecord.getDeleteFlag()) {
new WriteDetailTask(type, TaskJob.FORCESYNC, this, this).execute(mangaRecord);
}
}
} catch (Exception e) {
Crashlytics.log(Log.ERROR, "MALX", "DetailView.onPause(): " + e.getMessage());
Crashlytics.logException(e);
}
}
@Override
public void onResume() {
super.onResume();
// received Android Beam?
if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction()))
processIntent(getIntent());
}
private void processIntent(Intent intent) {
Parcelable[] rawMsgs = getIntent().getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
// only one message sent during the beam
NdefMessage msg = (NdefMessage) rawMsgs[0];
String message = new String(msg.getRecords()[0].getPayload());
String[] splitmessage = message.split(":", 2);
if (splitmessage.length == 2) {
try {
type = ListType.valueOf(splitmessage[0].toUpperCase(Locale.US));
recordID = Integer.parseInt(splitmessage[1]);
getRecord(false);
} catch (NumberFormatException e) {
Crashlytics.logException(e);
finish();
}
}
}
private void setupBeam() {
try {
// setup beam functionality (if NFC is available)
NfcAdapter mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
if (mNfcAdapter == null) {
Crashlytics.log(Log.INFO, "MALX", "DetailView.setupBeam(): NFC not available");
} else {
// Register NFC callback
String message_str = type.toString() + ":" + String.valueOf(recordID);
NdefMessage message = new NdefMessage(new NdefRecord[]{
new NdefRecord(
NdefRecord.TNF_MIME_MEDIA,
"application/net.somethingdreadful.MAL".getBytes(Charset.forName("US-ASCII")),
new byte[0], message_str.getBytes(Charset.forName("US-ASCII"))),
NdefRecord.createApplicationRecord(getPackageName())
});
mNfcAdapter.setNdefPushMessage(message, this);
}
} catch (Exception e) {
Crashlytics.log(Log.ERROR, "MALX", "DetailView.setupBeam(): " + e.getMessage());
Crashlytics.logException(e);
}
}
@SuppressWarnings("unchecked") // Don't panic, we handle possible class cast exceptions
@Override
public void onNetworkTaskFinished(Object result, TaskJob job, ListType type, Bundle data, boolean cancelled) {
try {
if (type == ListType.ANIME) {
animeRecord = (Anime) result;
if (isAdded())
animeRecord.setDirty(true);
} else {
mangaRecord = (Manga) result;
if (isAdded())
mangaRecord.setDirty(true);
}
setRefreshing(false);
toggleLoadingIndicator(false);
setText();
} catch (ClassCastException e) {
Crashlytics.log(Log.ERROR, "MALX", "DetailView.onNetworkTaskFinished(): " + result.getClass().toString());
Crashlytics.logException(e);
Toast.makeText(context, R.string.toast_error_DetailsError, Toast.LENGTH_SHORT).show();
}
}
@Override
public void onNetworkTaskError(TaskJob job, ListType type, Bundle data, boolean cancelled) {
Toast.makeText(context, R.string.toast_error_DetailsError, Toast.LENGTH_SHORT).show();
}
@Override
public void onAPIAuthenticationError(ListType type, TaskJob job) {
showDialog("updatePassword", new UpdatePasswordDialogFragment());
}
/*
* Set the fragment to future use
*/
public void setGeneral(DetailViewGeneral general) {
this.general = general;
if (isEmpty())
getRecord(false);
else
setText();
}
/*
* Set the fragment to future use
*/
public void setDetails(DetailViewDetails details) {
this.details = details;
}
/*
* handle the loading indicator
*/
private void toggleLoadingIndicator(boolean show) {
if (viewFlipper != null) {
viewFlipper.setDisplayedChild(show ? 1 : 0);
}
}
/*
* handle the offline card
*/
private void toggleNoNetworkCard(boolean show) {
if (viewFlipper != null) {
viewFlipper.setDisplayedChild(show ? 2 : 0);
}
}
@Override
public void onRefresh() {
getRecord(true);
}
}
|
package net.somethingdreadful.MAL;
import android.app.DialogFragment;
import android.app.FragmentManager;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import android.widget.ViewFlipper;
import com.crashlytics.android.Crashlytics;
import net.somethingdreadful.MAL.adapters.DetailViewPagerAdapter;
import net.somethingdreadful.MAL.api.MALApi;
import net.somethingdreadful.MAL.api.MALApi.ListType;
import net.somethingdreadful.MAL.api.response.Anime;
import net.somethingdreadful.MAL.api.response.GenericRecord;
import net.somethingdreadful.MAL.api.response.Manga;
import net.somethingdreadful.MAL.dialog.RemoveConfirmationDialogFragment;
import net.somethingdreadful.MAL.dialog.UpdatePasswordDialogFragment;
import net.somethingdreadful.MAL.sql.DatabaseManager;
import net.somethingdreadful.MAL.tasks.APIAuthenticationErrorListener;
import net.somethingdreadful.MAL.tasks.NetworkTask;
import net.somethingdreadful.MAL.tasks.NetworkTaskCallbackListener;
import net.somethingdreadful.MAL.tasks.TaskJob;
import net.somethingdreadful.MAL.tasks.WriteDetailTask;
import java.io.Serializable;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Locale;
public class DetailView extends ActionBarActivity implements Serializable, NetworkTaskCallbackListener, APIAuthenticationErrorListener, SwipeRefreshLayout.OnRefreshListener {
public ListType type;
public Anime animeRecord;
public Manga mangaRecord;
public String username;
public PrefManager pref;
public DetailViewGeneral general;
public DetailViewDetails details;
DetailViewPagerAdapter PageAdapter;
int recordID;
private ActionBar actionBar;
private ViewPager viewPager;
private ViewFlipper viewFlipper;
private Menu menu;
private Context context;
private ArrayList<String> tabs = new ArrayList<String>();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detailview);
actionBar = getSupportActionBar();
context = getApplicationContext();
username = getIntent().getStringExtra("username");
pref = new PrefManager(this);
type = (ListType) getIntent().getSerializableExtra("recordType");
recordID = getIntent().getIntExtra("recordID", -1);
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
viewPager = (ViewPager) findViewById(R.id.pager);
viewFlipper = (ViewFlipper) findViewById(R.id.viewFlipper);
PageAdapter = new DetailViewPagerAdapter(getFragmentManager(), this);
viewPager.setAdapter(PageAdapter);
if (savedInstanceState != null) {
animeRecord = (Anime) savedInstanceState.getSerializable("anime");
mangaRecord = (Manga) savedInstanceState.getSerializable("manga");
}
}
/*
* Set text in all fragments
*/
public void setText() {
try {
actionBar.setTitle(type == ListType.ANIME ? animeRecord.getTitle() : mangaRecord.getTitle());
if (general != null) {
general.setText();
}
if (details != null && !isEmpty()) {
details.setText();
}
if (!isEmpty()) {
setupBeam();
}
} catch (Exception e) {
Crashlytics.log(Log.ERROR, "MALX", "DetailView.setText(): " + e.getMessage());
if (!(e instanceof IllegalStateException))
Crashlytics.logException(e);
}
setMenu();
}
/*
* Checks if the records are null to prevent nullpointerexceptions
*/
public boolean isEmpty() {
return animeRecord == null && mangaRecord == null;
}
/*
* Checks if this record is in our list
*/
public boolean isAdded() {
return !isEmpty() && (ListType.ANIME.equals(type) ? animeRecord.getWatchedStatus() != null : mangaRecord.getReadStatus() != null);
}
/*
* Set refreshing on all SwipeRefreshViews
*/
public void setRefreshing(Boolean show) {
if (general != null) {
general.swipeRefresh.setRefreshing(show);
general.swipeRefresh.setEnabled(!show);
}
if (details != null) {
details.swipeRefresh.setRefreshing(show);
details.swipeRefresh.setEnabled(!show);
}
}
/*
* Show the dialog with the tag
*/
public void showDialog(String tag, DialogFragment dialog) {
FragmentManager fm = getFragmentManager();
dialog.show(fm, "fragment_" + tag);
}
/*
* Episode picker dialog
*/
public void onDialogDismissed(int newValue) {
if (newValue != animeRecord.getWatchedEpisodes()) {
if (newValue == animeRecord.getEpisodes()) {
animeRecord.setWatchedStatus(GenericRecord.STATUS_COMPLETED);
}
if (newValue == 0) {
animeRecord.setWatchedStatus(Anime.STATUS_PLANTOWATCH);
}
animeRecord.setWatchedEpisodes(newValue);
animeRecord.setDirty(true);
setText();
}
}
/*
* Set the right menu items.
*/
public void setMenu() {
if (menu != null) {
if (isAdded()) {
menu.findItem(R.id.action_Remove).setVisible(!isEmpty() && MALApi.isNetworkAvailable(this));
menu.findItem(R.id.action_addToList).setVisible(false);
} else {
menu.findItem(R.id.action_Remove).setVisible(false);
menu.findItem(R.id.action_addToList).setVisible(!isEmpty());
}
menu.findItem(R.id.action_Share).setVisible(!isEmpty());
menu.findItem(R.id.action_ViewMALPage).setVisible(!isEmpty());
}
}
/*
* Add record to list
*/
public void addToList() {
if (!isEmpty()) {
if (type.equals(ListType.ANIME)) {
animeRecord.setCreateFlag(true);
animeRecord.setWatchedStatus(Anime.STATUS_WATCHING);
animeRecord.setDirty(true);
} else {
mangaRecord.setCreateFlag(true);
mangaRecord.setReadStatus(Manga.STATUS_READING);
mangaRecord.setDirty(true);
}
setText();
}
}
/*
* Open the share dialog
*/
public void Share() {
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
sharingIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
sharingIntent.putExtra(Intent.EXTRA_TEXT, makeShareText());
startActivity(Intent.createChooser(sharingIntent, "Share via"));
}
/*
* Make the share text for the share dialog
*/
public String makeShareText() {
String shareText = pref.getCustomShareText();
shareText = shareText.replace("$title;", actionBar.getTitle());
shareText = shareText.replace("$link;", "http://myanimelist.net/" + type.toString().toLowerCase(Locale.US) + "/" + Integer.toString(recordID));
shareText = shareText + getResources().getString(R.string.customShareText_fromAtarashii);
return shareText;
}
/*
* Check if the database contains the record.
*
* If it does contains the record it will set it.
*/
private boolean getRecordFromDB() {
DatabaseManager dbMan = new DatabaseManager(this);
if (type.equals(ListType.ANIME)) {
animeRecord = dbMan.getAnime(recordID, username);
return animeRecord != null;
} else {
mangaRecord = dbMan.getManga(recordID, username);
return mangaRecord != null;
}
}
/*
* Check if the record contains all the details.
*
* Without this function the fragments will call setText while it isn't loaded.
* This will cause a nullpointerexception.
*/
public boolean isDone() {
return (!isEmpty()) && (type.equals(ListType.ANIME) ? animeRecord.getSynopsis() != null : mangaRecord.getSynopsis() != null);
}
/*
* Get the translation from strings.xml
*/
private String getStringFromResourceArray(int resArrayId, int notFoundStringId, int index) {
Resources res = getResources();
try {
String[] types = res.getStringArray(resArrayId);
if (index < 0 || index >= types.length) // make sure to have a valid array index
return res.getString(notFoundStringId);
else
return types[index];
} catch (Resources.NotFoundException e) {
Crashlytics.logException(e);
return res.getString(notFoundStringId);
}
}
/*
* Get the anime or manga mediatype translations
*/
public String getTypeString(int typesInt) {
if (type.equals(ListType.ANIME))
return getStringFromResourceArray(R.array.mediaType_Anime, R.string.unknown, typesInt);
else
return getStringFromResourceArray(R.array.mediaType_Manga, R.string.unknown, typesInt);
}
/*
* Get the anime or manga status translations
*/
public String getStatusString(int statusInt) {
if (type.equals(ListType.ANIME))
return getStringFromResourceArray(R.array.mediaStatus_Anime, R.string.unknown, statusInt);
else
return getStringFromResourceArray(R.array.mediaStatus_Manga, R.string.unknown, statusInt);
}
/*
* Get the anime or manga genre translations
*/
public ArrayList<String> getGenresString(ArrayList<Integer> genresInt) {
ArrayList<String> genres = new ArrayList<String>();
for (Integer genreInt : genresInt) {
genres.add(getStringFromResourceArray(R.array.genresArray, R.string.unknown, genreInt));
}
return genres;
}
/*
* Get the anime or manga classification translations
*/
public String getClassificationString(Integer classificationInt) {
return getStringFromResourceArray(R.array.classificationArray, R.string.unknown, classificationInt);
}
public String getUserStatusString(int statusInt) {
return getStringFromResourceArray(R.array.mediaStatus_User, R.string.unknown, statusInt);
}
/*
* Get the records (Anime/Manga)
*
* Try to fetch them from the Database first to get reading/watching details.
* If the record doesn't contains a synopsis this method will get it.
*/
public void getRecord(boolean forceUpdate) {
setRefreshing(true);
toggleLoadingIndicator(isEmpty());
actionBar.setTitle(R.string.layout_card_loading);
boolean loaded = false;
if (!forceUpdate || !MALApi.isNetworkAvailable(this)) {
if (getRecordFromDB()) {
setText();
setRefreshing(false);
if (isDone()) {
loaded = true;
toggleLoadingIndicator(false);
}
}
}
if (MALApi.isNetworkAvailable(this)) {
if (!loaded || forceUpdate) {
Bundle data = new Bundle();
boolean saveDetails = username != null && !username.equals("") && isAdded();
if (saveDetails) {
data.putSerializable("record", type.equals(ListType.ANIME) ? animeRecord : mangaRecord);
} else {
data.putInt("recordID", recordID);
}
new NetworkTask(saveDetails ? TaskJob.GETDETAILS : TaskJob.GET, type, this, data, this, this).execute();
}
} else {
toggleLoadingIndicator(false);
setRefreshing(false);
if (isEmpty()) {
actionBar.setTitle("");
toggleNoNetworkCard(true);
}
}
}
public void onStatusDialogDismissed(String currentStatus) {
if (type.equals(ListType.ANIME)) {
animeRecord.setWatchedStatus(currentStatus);
if (GenericRecord.STATUS_COMPLETED.equals(currentStatus)) {
if (animeRecord.getEpisodes() != 0)
animeRecord.setWatchedEpisodes(animeRecord.getEpisodes());
}
animeRecord.setDirty(true);
} else {
mangaRecord.setReadStatus(currentStatus);
if (GenericRecord.STATUS_COMPLETED.equals(currentStatus)) {
if (mangaRecord.getChapters() != 0)
mangaRecord.setChaptersRead(mangaRecord.getChapters());
if (mangaRecord.getVolumes() != 0)
mangaRecord.setVolumesRead(mangaRecord.getVolumes());
}
mangaRecord.setDirty(true);
}
setText();
}
public void onMangaDialogDismissed(int value, int value2) {
if (value != mangaRecord.getChaptersRead()) {
if (value == mangaRecord.getChapters() && mangaRecord.getChapters() != 0) {
mangaRecord.setReadStatus(GenericRecord.STATUS_COMPLETED);
}
if (value == 0) {
mangaRecord.setReadStatus(Manga.STATUS_PLANTOREAD);
}
mangaRecord.setChaptersRead(value);
mangaRecord.setDirty(true);
}
if (value2 != mangaRecord.getVolumesRead()) {
if (value2 == mangaRecord.getVolumes()) {
mangaRecord.setReadStatus(GenericRecord.STATUS_COMPLETED);
}
if (value2 == 0) {
mangaRecord.setReadStatus(Manga.STATUS_PLANTOREAD);
}
mangaRecord.setVolumesRead(value2);
mangaRecord.setDirty(true);
}
setText();
setMenu();
}
public void onRemoveConfirmed() {
if (type.equals(ListType.ANIME)) {
animeRecord.setDirty(true);
animeRecord.setDeleteFlag(true);
} else {
mangaRecord.setDirty(true);
mangaRecord.setDeleteFlag(true);
}
finish();
}
@Override
protected void onSaveInstanceState(Bundle State) {
super.onSaveInstanceState(State);
State.putSerializable("anime", animeRecord);
State.putSerializable("manga", mangaRecord);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_detail_view, menu);
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
this.menu = menu;
setMenu();
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
break;
case R.id.action_Share:
Share();
break;
case R.id.action_Remove:
showDialog("removeConfirmation", new RemoveConfirmationDialogFragment());
break;
case R.id.action_addToList:
addToList();
break;
case R.id.action_ViewMALPage:
Uri malurl = Uri.parse("http://myanimelist.net/" + type.toString().toLowerCase(Locale.US) + "/" + recordID + "/");
startActivity(new Intent(Intent.ACTION_VIEW, malurl));
break;
case R.id.action_copy:
if (animeRecord != null || mangaRecord != null) {
android.content.ClipboardManager clipBoard = (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
android.content.ClipData clipData = android.content.ClipData.newPlainText("Atarashii", type == ListType.ANIME ? animeRecord.getTitle() : mangaRecord.getTitle());
clipBoard.setPrimaryClip(clipData);
} else {
Toast.makeText(context, R.string.toast_info_hold_on, Toast.LENGTH_SHORT).show();
}
break;
}
return true;
}
@Override
public void onPause() {
super.onPause();
if (animeRecord == null && mangaRecord == null)
return; // nothing to do
try {
if (type.equals(ListType.ANIME)) {
if (animeRecord.getDirty() && !animeRecord.getDeleteFlag()) {
new WriteDetailTask(type, TaskJob.UPDATE, this, this).execute(animeRecord);
} else if (animeRecord.getDeleteFlag()) {
new WriteDetailTask(type, TaskJob.FORCESYNC, this, this).execute(animeRecord);
}
} else if (type.equals(ListType.MANGA)) {
if (mangaRecord.getDirty() && !mangaRecord.getDeleteFlag()) {
new WriteDetailTask(type, TaskJob.UPDATE, this, this).execute(mangaRecord);
} else if (mangaRecord.getDeleteFlag()) {
new WriteDetailTask(type, TaskJob.FORCESYNC, this, this).execute(mangaRecord);
}
}
} catch (Exception e) {
Crashlytics.log(Log.ERROR, "MALX", "DetailView.onPause(): " + e.getMessage());
Crashlytics.logException(e);
}
}
@Override
public void onResume() {
super.onResume();
// received Android Beam?
if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction()))
processIntent(getIntent());
}
private void processIntent(Intent intent) {
Parcelable[] rawMsgs = getIntent().getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
// only one message sent during the beam
NdefMessage msg = (NdefMessage) rawMsgs[0];
String message = new String(msg.getRecords()[0].getPayload());
String[] splitmessage = message.split(":", 2);
if (splitmessage.length == 2) {
try {
type = ListType.valueOf(splitmessage[0].toUpperCase(Locale.US));
recordID = Integer.parseInt(splitmessage[1]);
getRecord(false);
} catch (NumberFormatException e) {
Crashlytics.logException(e);
finish();
}
}
}
private void setupBeam() {
try {
// setup beam functionality (if NFC is available)
NfcAdapter mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
if (mNfcAdapter == null) {
Crashlytics.log(Log.INFO, "MALX", "DetailView.setupBeam(): NFC not available");
} else {
// Register NFC callback
String message_str = type.toString() + ":" + String.valueOf(recordID);
NdefMessage message = new NdefMessage(new NdefRecord[]{
new NdefRecord(
NdefRecord.TNF_MIME_MEDIA,
"application/net.somethingdreadful.MAL".getBytes(Charset.forName("US-ASCII")),
new byte[0], message_str.getBytes(Charset.forName("US-ASCII"))),
NdefRecord.createApplicationRecord(getPackageName())
});
mNfcAdapter.setNdefPushMessage(message, this);
}
} catch (Exception e) {
Crashlytics.log(Log.ERROR, "MALX", "DetailView.setupBeam(): " + e.getMessage());
Crashlytics.logException(e);
}
}
@SuppressWarnings("unchecked") // Don't panic, we handle possible class cast exceptions
@Override
public void onNetworkTaskFinished(Object result, TaskJob job, ListType type, Bundle data, boolean cancelled) {
try {
if (type == ListType.ANIME) {
animeRecord = (Anime) result;
if (isAdded())
animeRecord.setDirty(true);
} else {
mangaRecord = (Manga) result;
if (isAdded())
mangaRecord.setDirty(true);
}
setRefreshing(false);
toggleLoadingIndicator(false);
setText();
} catch (ClassCastException e) {
Crashlytics.log(Log.ERROR, "MALX", "DetailView.onNetworkTaskFinished(): " + result.getClass().toString());
Crashlytics.logException(e);
Toast.makeText(context, R.string.toast_error_DetailsError, Toast.LENGTH_SHORT).show();
}
}
@Override
public void onNetworkTaskError(TaskJob job, ListType type, Bundle data, boolean cancelled) {
Toast.makeText(context, R.string.toast_error_DetailsError, Toast.LENGTH_SHORT).show();
}
@Override
public void onAPIAuthenticationError(ListType type, TaskJob job) {
showDialog("updatePassword", new UpdatePasswordDialogFragment());
}
/*
* Set the fragment to future use
*/
public void setGeneral(DetailViewGeneral general) {
this.general = general;
if (isEmpty())
getRecord(false);
else
setText();
}
/*
* Set the fragment to future use
*/
public void setDetails(DetailViewDetails details) {
this.details = details;
}
/*
* handle the loading indicator
*/
private void toggleLoadingIndicator(boolean show) {
if (viewFlipper != null) {
viewFlipper.setDisplayedChild(show ? 1 : 0);
}
}
/*
* handle the offline card
*/
private void toggleNoNetworkCard(boolean show) {
if (viewFlipper != null) {
viewFlipper.setDisplayedChild(show ? 2 : 0);
}
}
@Override
public void onRefresh() {
getRecord(true);
}
}
|
package br.com.biblioteca.basic;
import br.com.biblioteca.repositorios.RepositorioFornecedorArray;
import br.com.biblioteca.repositorios.RepositorioFornecedorLista;
import br.com.biblioteca.repositorios.RepositorioLivroArray;
import br.com.biblioteca.repositorios.RepositorioLivrosLista;
import br.com.biblioteca.repositorios.RepositorioPessoasArray;
import br.com.biblioteca.repositorios.RepositorioPessoasLista;
public class Funcionario extends Pessoa {
RepositorioPessoasArray arrayAlunos = new RepositorioPessoasArray(100);
RepositorioPessoasLista listaAlunos = new RepositorioPessoasLista();
RepositorioFornecedorArray arrayFornecedor = new RepositorioFornecedorArray(100);
RepositorioFornecedorLista listaFornecedor = new RepositorioFornecedorLista();
RepositorioLivroArray arrayLivros = new RepositorioLivroArray(100);
RepositorioLivrosLista listaLivros = new RepositorioLivrosLista();
void cadastrarLivroArray(Livro livro) {
arrayLivros.inserir(livro);
}
void cadastrarAlunoArray(Aluno aluno) {
arrayAlunos.inserir(aluno);
}
void descadastrarAlunoArray(Aluno aluno) {
arrayAlunos.remover(aluno);
}
void cadastrarFornecedorArray(Fornecedor forn) {
arrayFornecedor.inserir(forn);
}
void descadastrarFornecedorArray(Fornecedor forn) {
arrayFornecedor.remover(forn);
}
void cadastrarLivroLista(Livro livro) {
listaLivros.inserir(livro);
}
void cadastrarAlunoLista(Aluno aluno) {
listaAlunos.inserir(aluno);
}
void descadastrarAlunoLista(Aluno aluno) {
listaAlunos.remover(aluno);
}
void cadastrarFornecedorLista(Fornecedor forn) {
listaFornecedor.inserir(forn);
}
void descadastrarFornecedor(Fornecedor forn) {
listaFornecedor.remover(forn);
}
void retiraMulta(Aluno a) {
a.setValorMulta(0);
}
}
|
package ru.taximaxim.treeviewer.filter;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerFilter;
import ru.taximaxim.treeviewer.models.IColumn;
import ru.taximaxim.treeviewer.models.IObject;
import ru.taximaxim.treeviewer.models.DataSource;
import ru.taximaxim.treeviewer.tree.ExtendedTreeViewerComponent;
import ru.taximaxim.treeviewer.utils.ColumnType;
import java.util.*;
public class FilterChangeHandler {
private DataSource<? extends IObject> dataSource;
private ExtendedTreeViewerComponent tree;
private Map<IColumn, ViewerFilter> columnFilters = new HashMap<>();
private ViewerFilter allTextFilter;
public FilterChangeHandler(DataSource<? extends IObject> dataSource) {
this.dataSource = dataSource;
}
public void setTree(ExtendedTreeViewerComponent tree) {
this.tree = tree;
}
void filterAllColumns(String searchText) {
if (searchText.isEmpty()) {
allTextFilter = null;
} else {
allTextFilter = new ViewerFilter() {
@Override
public boolean select(Viewer viewer, Object parentElement, Object element) {
if (parentElement instanceof ArrayList) {
return dataSource.getColumnsToFilter().stream()
.anyMatch(column -> match(column, element, searchText,
FilterOperation.CONTAINS, ColumnType.STRING));
}
return true;
}
};
}
updateFilters();
}
void filter(String searchText, FilterOperation value, IColumn column) {
if (searchText.isEmpty() || value == FilterOperation.NONE) {
columnFilters.remove(column);
} else {
ViewerFilter columnFilter = new ViewerFilter() {
@Override
public boolean select(Viewer viewer, Object parentElement, Object element) {
if (parentElement instanceof ArrayList) {
return match(column, element, searchText, value, column.getColumnType());
}
return true;
}
};
columnFilters.put(column, columnFilter);
}
updateFilters();
}
private boolean match(IColumn column, Object element, String searchText,
FilterOperation value, ColumnType columnType) {
IObject parentObject = (IObject) element;
if (parentObject.hasChildren()) {
for (Object child : parentObject.getChildren()) {
if (match(column, child, searchText, value, columnType)) {
return true;
}
}
}
String textFromObject = dataSource.getRowText(element, column);
return value.matchesForType(textFromObject, searchText, columnType);
}
private void updateFilters() {
List<ViewerFilter> filters = new ArrayList<>(columnFilters.values());
if (allTextFilter != null) {
filters.add(allTextFilter);
}
tree.setFilters(filters.toArray(new ViewerFilter[0]));
}
}
|
package org.apache.bcel;
/* Actually, this is the BCEL Repository, with an added facility to
* let an application know which classes are actually in the Repository.
* A class that wants this, should implement the interface "RepositoryObserver"
* (which contains one method: void notify(String classname); ).
* In addition, it should register itself with the Repository through the
* void registerObserver(RepositoryObserver n); method.
*
* Another fix: the ClassQueue object in BCEL is buggy. Don't use it.
* (Don't know about BCEL 5.1. It was so in BCEL 5.0).
*/
import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.util.*;
import java.io.*;
import java.util.Vector;
/**
* The repository maintains informations about class interdependencies, e.g.,
* whether a class is a sub-class of another. Delegates actual class loading
* to SyntheticRepository with current class path by default.
*
* @see org.apache.bcel.util.Repository
* @see org.apache.bcel.util.SyntheticRepository
*
* @version $Id$
* @author <A HREF="mailto:markus.dahm@berlin.de">M. Dahm</A>
*/
public abstract class Repository {
private static org.apache.bcel.util.Repository _repository =
SyntheticRepository.getInstance();
private static Vector observers = new Vector();
/** Register a RepositoryObserver.
*/
public static void registerObserver(RepositoryObserver n) {
for (int i = 0; i < observers.size(); i++) {
if ((RepositoryObserver) (observers.elementAt(i)) == n) return;
}
observers.addElement(n);
}
/** Unregister a RepositoryObserver.
*/
public static void unregisterObserver(RepositoryObserver n) {
observers.removeElement(n);
}
private static void notifyObserver(String n) {
for (int i = 0; i < observers.size(); i++) {
RepositoryObserver w = (RepositoryObserver) (observers.elementAt(i));
w.notify(n);
}
}
/** @return currently used repository instance
*/
public static org.apache.bcel.util.Repository getRepository() {
return _repository;
}
/** Set repository instance to be used for class loading
*/
public static void setRepository(org.apache.bcel.util.Repository rep) {
_repository = rep;
}
/** Lookup class somewhere found on your CLASSPATH, or whereever the
* repository instance looks for it.
*
* @return class object for given fully qualified class name, or null
* if the class could not be found or parsed correctly
*/
public static JavaClass lookupClass(String class_name) {
try {
JavaClass clazz = _repository.findClass(class_name);
if(clazz == null) {
clazz = _repository.loadClass(class_name);
notifyObserver(class_name);
}
return clazz;
} catch(ClassNotFoundException ex) {
return null;
}
}
/**
* Try to find class source via getResourceAsStream().
* @see Class
* @return JavaClass object for given runtime class
*/
public static JavaClass lookupClass(Class clazz) {
try {
JavaClass cl = _repository.loadClass(clazz);
notifyObserver(cl.getClassName());
return cl;
} catch(ClassNotFoundException ex) { return null; }
}
/** @return class file object for given Java class.
*/
public static ClassPath.ClassFile lookupClassFile(String class_name) {
try {
return ClassPath.SYSTEM_CLASS_PATH.getClassFile(class_name);
} catch(IOException e) { return null; }
}
/** Clear the repository.
*/
public static void clearCache() {
_repository.clear();
}
/**
* Add clazz to repository if there isn't an equally named class already in there.
*
* @return old entry in repository
*/
public static JavaClass addClass(JavaClass clazz) {
JavaClass old = _repository.findClass(clazz.getClassName());
_repository.storeClass(clazz);
return old;
}
/**
* Remove class with given (fully qualified) name from repository.
*/
public static void removeClass(String clazz) {
_repository.removeClass(_repository.findClass(clazz));
}
/**
* Remove given class from repository.
*/
public static void removeClass(JavaClass clazz) {
_repository.removeClass(clazz);
}
/**
* @return list of super classes of clazz in ascending order, i.e.,
* Object is always the last element
*/
public static JavaClass[] getSuperClasses(JavaClass clazz) {
return clazz.getSuperClasses();
}
/**
* @return list of super classes of clazz in ascending order, i.e.,
* Object is always the last element. return "null", if class
* cannot be found.
*/
public static JavaClass[] getSuperClasses(String class_name) {
JavaClass jc = lookupClass(class_name);
return (jc == null? null : getSuperClasses(jc));
}
/**
* @return all interfaces implemented by class and its super
* classes and the interfaces that those interfaces extend, and so on.
* (Some people call this a transitive hull).
*/
public static JavaClass[] getInterfaces(JavaClass clazz) {
return clazz.getAllInterfaces();
}
/**
* @return all interfaces implemented by class and its super
* classes and the interfaces that extend those interfaces, and so on
*/
public static JavaClass[] getInterfaces(String class_name) {
return getInterfaces(lookupClass(class_name));
}
/**
* Equivalent to runtime "instanceof" operator.
* @return true, if clazz is an instance of super_class
*/
public static boolean instanceOf(JavaClass clazz, JavaClass super_class) {
return clazz.instanceOf(super_class);
}
/**
* @return true, if clazz is an instance of super_class
*/
public static boolean instanceOf(String clazz, String super_class) {
return instanceOf(lookupClass(clazz), lookupClass(super_class));
}
/**
* @return true, if clazz is an instance of super_class
*/
public static boolean instanceOf(JavaClass clazz, String super_class) {
return instanceOf(clazz, lookupClass(super_class));
}
/**
* @return true, if clazz is an instance of super_class
*/
public static boolean instanceOf(String clazz, JavaClass super_class) {
return instanceOf(lookupClass(clazz), super_class);
}
/**
* @return true, if clazz is an implementation of interface inter
*/
public static boolean implementationOf(JavaClass clazz, JavaClass inter) {
if (clazz == null || inter == null) return false;
return clazz.implementationOf(inter);
}
/**
* @return true, if clazz is an implementation of interface inter
*/
public static boolean implementationOf(String clazz, String inter) {
return implementationOf(lookupClass(clazz), lookupClass(inter));
}
/**
* @return true, if clazz is an implementation of interface inter
*/
public static boolean implementationOf(JavaClass clazz, String inter) {
return implementationOf(clazz, lookupClass(inter));
}
/**
* @return true, if clazz is an implementation of interface inter
*/
public static boolean implementationOf(String clazz, JavaClass inter) {
return implementationOf(lookupClass(clazz), inter);
}
}
|
package blog.controller;
import auth.AuthHelper;
import beans.BeanManager;
import blog.auth.AuthHelperExt;
import blog.data.EIComment;
import blog.service.IBlogCommentService;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.protocol.HttpContext;
import rest.RestHelper;
import rest.WithMatcher;
import java.io.IOException;
public class SetBlogCommentCtrl extends WithMatcher {
private IBlogCommentService blogCommentService = BeanManager.getInstance().getService(IBlogCommentService.class);
@Override
public int auth() {
return AuthHelperExt.BLOG_LOGIN | AuthHelper.ADMIN;
}
@Override
public String name() {
return "blog set post's comment";
}
@Override
public String urlPattern() {
return "/blog/comment/set";
}
@Override
public void handle(HttpRequest httpRequest, HttpResponse httpResponse, HttpContext httpContext) throws HttpException, IOException {
if (!RestHelper.isPost(httpRequest, httpResponse)) {
return;
}
EIComment comment = RestHelper.getBodyAsObject(httpRequest, EIComment.class);
RestHelper.oneCallAndRet(httpResponse, this.blogCommentService, "save", comment);
}
}
|
package pp.block1.cc.dfa;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class AwesomeGenerator implements Generator {
public List<String> scan(State dfa, String text) {
List<String> result = new ArrayList<>();
while (text.length() > 0) {
String token = nextWord(dfa, text);
result.add(token);
text = text.substring(token.length());
}
return result;
}
private String nextWord(State dfa, String text) {
State state = dfa;
String token = "";
Stack<State> stack = new Stack<>();
int i = 0;
while (state != null && i < text.length()) {
char c = text.charAt(i);
token = token + c;
if (state.isAccepting()) {
stack.clear();
}
stack.push(state);
state = state.getNext(c);
i++;
}
while ((state == null || !state.isAccepting()) && stack.size() > 0) {
state = stack.pop();
token = text.substring(0, token.length() - 1);
}
return token;
}
}
|
package be.ibridge.kettle.core.value;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.math.BigDecimal;
import java.text.DateFormatSymbols;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import org.w3c.dom.Node;
import be.ibridge.kettle.core.Const;
import be.ibridge.kettle.core.Row;
import be.ibridge.kettle.core.XMLHandler;
import be.ibridge.kettle.core.XMLInterface;
import be.ibridge.kettle.core.exception.KettleDatabaseException;
import be.ibridge.kettle.core.exception.KettleEOFException;
import be.ibridge.kettle.core.exception.KettleException;
import be.ibridge.kettle.core.exception.KettleFileException;
import be.ibridge.kettle.core.exception.KettleValueException;
import be.ibridge.kettle.repository.Repository;
/**
* This class is one of the core classes of the Kettle framework.
* It contains everything you need to manipulate atomic data (Values/Fields/...)
* and to describe it in the form of meta-data. (name, length, precision, etc.)
*
* @author Matt
* @since Beginning 2003
*/
public class Value implements Cloneable, XMLInterface, Serializable
{
private static final long serialVersionUID = -6310073485210258622L;
/**
* Value type indicating that the value has no type set.
*/
public static final int VALUE_TYPE_NONE = 0;
/**
* Value type indicating that the value contains a floating point double precision number.
*/
public static final int VALUE_TYPE_NUMBER = 1;
/**
* Value type indicating that the value contains a text String.
*/
public static final int VALUE_TYPE_STRING = 2;
/**
* Value type indicating that the value contains a Date.
*/
public static final int VALUE_TYPE_DATE = 3;
/**
* Value type indicating that the value contains a boolean.
*/
public static final int VALUE_TYPE_BOOLEAN = 4;
/**
* Value type indicating that the value contains a long integer.
*/
public static final int VALUE_TYPE_INTEGER = 5;
/**
* Value type indicating that the value contains a floating point precision number with arbitrary precision.
*/
public static final int VALUE_TYPE_BIGNUMBER = 6;
/**
* Value type indicating that the value contains an Object.
*/
public static final int VALUE_TYPE_SERIALIZABLE = 7;
/**
* The descriptions of the value types.
*/
private static final String valueTypeCode[]=
{
"-", // $NON-NLS-1$
"Number", "String", "Date", "Boolean", "Integer", "BigNumber", "Serializable" // $NON-NLS-1$ $NON-NLS-2$ $NON-NLS-3$ $NON-NLS-4$ $NON-NLS-5$ $NON-NLS-6$
};
private ValueInterface value;
private String name;
private String origin;
private boolean NULL;
/**
* Constructs a new Value of type EMPTY
*
*/
public Value()
{
clearValue();
}
/**
* Constructs a new Value with a name.
*
* @param name Sets the name of the Value
*/
public Value(String name)
{
clearValue();
setName(name);
}
/**
* Constructs a new Value with a name and a type.
*
* @param name Sets the name of the Value
* @param val_type Sets the type of the Value (Value.VALUE_TYPE_*)
*/
public Value(String name, int val_type)
{
clearValue();
newValue(val_type);
setName(name);
}
/**
* This method allocates a new value of the appropriate type..
* @param val_type The new type of value
*/
private void newValue(int val_type)
{
switch(val_type)
{
case VALUE_TYPE_NUMBER : value = new ValueNumber(); break;
case VALUE_TYPE_STRING : value = new ValueString(); break;
case VALUE_TYPE_DATE : value = new ValueDate(); break;
case VALUE_TYPE_BOOLEAN : value = new ValueBoolean(); break;
case VALUE_TYPE_INTEGER : value = new ValueInteger(); break;
case VALUE_TYPE_BIGNUMBER: value = new ValueBigNumber(); break;
default: value = null;
}
}
/**
* Convert the value to another type. This only works if a value has been set previously.
* That is the reason this method is private. Rather, use the public method setType(int type).
*
* @param valType The type to convert to.
*/
private void convertTo(int valType)
{
if (value!=null)
{
switch(valType)
{
case VALUE_TYPE_NUMBER : value = new ValueNumber(value.getNumber()); break;
case VALUE_TYPE_STRING : value = new ValueString(value.getString()); break;
case VALUE_TYPE_DATE : value = new ValueDate(value.getDate()); break;
case VALUE_TYPE_BOOLEAN : value = new ValueBoolean(value.getBoolean()); break;
case VALUE_TYPE_INTEGER : value = new ValueInteger(value.getInteger()); break;
case VALUE_TYPE_BIGNUMBER : value = new ValueBigNumber(value.getBigNumber()); break;
default: value = null;
}
}
}
/**
* Constructs a new Value with a name, a type, length and precision.
*
* @param name Sets the name of the Value
* @param valType Sets the type of the Value (Value.VALUE_TYPE_*)
* @param length The length of the value
* @param precision The precision of the value
*/
public Value(String name, int valType, int length, int precision)
{
this(name, valType);
setLength(length, precision);
}
/**
* Constructs a new Value of Type VALUE_TYPE_BIGNUMBER, with a name, containing a BigDecimal number
*
* @param name Sets the name of the Value
* @param bignum The number to store in this Value
*/
public Value(String name, BigDecimal bignum)
{
clearValue();
setValue(bignum);
setName(name);
}
/**
* Constructs a new Value of Type VALUE_TYPE_NUMBER, with a name, containing a number
*
* @param name Sets the name of the Value
* @param num The number to store in this Value
*/
public Value(String name, double num)
{
clearValue();
setValue(num);
setName(name);
}
/**
* Constructs a new Value of Type VALUE_TYPE_STRING, with a name, containing a String
*
* @param name Sets the name of the Value
* @param str The text to store in this Value
*/
public Value(String name, StringBuffer str)
{
this(name, str.toString());
}
/**
* Constructs a new Value of Type VALUE_TYPE_STRING, with a name, containing a String
*
* @param name Sets the name of the Value
* @param str The text to store in this Value
*/
public Value(String name, String str)
{
clearValue();
setValue(str);
setName(name);
}
/**
* Constructs a new Value of Type VALUE_TYPE_DATE, with a name, containing a Date
*
* @param name Sets the name of the Value
* @param dat The date to store in this Value
*/
public Value(String name, Date dat)
{
clearValue();
setValue(dat);
setName(name);
}
/**
* Constructs a new Value of Type VALUE_TYPE_BOOLEAN, with a name, containing a boolean value
*
* @param name Sets the name of the Value
* @param bool The boolean to store in this Value
*/
public Value(String name, boolean bool)
{
clearValue();
setValue(bool);
setName(name);
}
/**
* Constructs a new Value of Type VALUE_TYPE_INTEGER, with a name, containing an integer number
*
* @param name Sets the name of the Value
* @param l The integer to store in this Value
*/
public Value(String name, long l)
{
clearValue();
setValue(l);
setName(name);
}
/**
* Constructs a new Value as a copy of another value and renames it...
*
* @param name The new name of the copied Value
* @param v The value to be copied
*/
public Value(String name, Value v)
{
this(v);
setName(name);
}
/**
* Constructs a new Value as a copy of another value
*
* @param v The Value to be copied
*/
public Value(Value v)
{
if (v!=null)
{
setType(v.getType());
value = v.getValueCopy();
setName(v.getName());
setLength(v.getLength(), v.getPrecision());
setNull(v.isNull());
setOrigin(v.origin);
}
else
{
clearValue();
setNull(true);
}
}
public Object clone()
{
Value retval = null;
try
{
retval = (Value)super.clone();
}
catch(CloneNotSupportedException e)
{
retval=null;
}
return retval;
}
/**
* Build a copy of this Value
* @return a copy of another value
*
*/
public Value Clone()
{
Value v = new Value(this);
return v;
}
/**
* Clears the content and name of a Value
*/
public void clearValue()
{
value = null;
name = null;
NULL = false;
origin = null;
}
private ValueInterface getValueCopy()
{
if (value==null) return null;
return (ValueInterface)value.clone();
}
/**
* Sets the name of a Value
*
* @param name The new name of the value
*/
public void setName(String name)
{
this.name = name;
}
/**
* Obtain the name of a Value
*
* @return The name of the Value
*/
public String getName()
{
return name;
}
/**
* This method allows you to set the origin of the Value by means of the name of the originating step.
*
* @param step_of_origin The step of origin.
*/
public void setOrigin(String step_of_origin)
{
origin = step_of_origin;
}
/**
* Obtain the origin of the step.
*
* @return The name of the originating step
*/
public String getOrigin()
{
return origin;
}
/**
* Sets the value to a BigDecimal number value.
* @param num The number value to set the value to
*/
public void setValue(BigDecimal num)
{
if (value==null || value.getType()!=VALUE_TYPE_BIGNUMBER) value = new ValueBigNumber(num);
else value.setBigNumber(num);
setNull(false);
}
/**
* Sets the value to a double Number value.
* @param num The number value to set the value to
*/
public void setValue(double num)
{
if (value==null || value.getType()!=VALUE_TYPE_NUMBER) value = new ValueNumber(num);
else value.setNumber(num);
setNull(false);
}
/**
* Sets the Value to a String text
* @param str The StringBuffer to get the text from
*/
public void setValue(StringBuffer str)
{
if (value==null || value.getType()!=VALUE_TYPE_STRING) value = new ValueString(str.toString());
else value.setString(str.toString());
setNull(str==null);
}
/**
* Sets the Value to a String text
* @param str The String to get the text from
*/
public void setValue(String str)
{
if (value==null || value.getType()!=VALUE_TYPE_STRING) value = new ValueString(str);
else value.setString(str);
setNull(str==null);
}
public void setSerializedValue(Serializable ser) {
if (value==null || value.getType()!=VALUE_TYPE_SERIALIZABLE) value = new ValueSerializable(ser);
else value.setSerializable(ser);
setNull(ser==null);
}
/**
* Sets the Value to a Date
* @param dat The Date to set the Value to
*/
public void setValue(Date dat)
{
if (value==null || value.getType()!=VALUE_TYPE_DATE) value = new ValueDate(dat);
else value.setDate(dat);
setNull(dat==null);
}
/**
* Sets the Value to a boolean
* @param bool The boolean to set the Value to
*/
public void setValue(boolean bool)
{
if (value==null || value.getType()!=VALUE_TYPE_BOOLEAN) value = new ValueBoolean(bool);
else value.setBoolean(bool);
setNull(false);
}
/**
* Sets the Value to a long integer
* @param b The byte to convert to a long integer to which the Value is set.
*/
public void setValue(byte b)
{
setValue((long)b);
}
/**
* Sets the Value to a long integer
* @param i The integer to convert to a long integer to which the Value is set.
*/
public void setValue(int i)
{
setValue((long)i);
}
/**
* Sets the Value to a long integer
* @param l The long integer to which the Value is set.
*/
public void setValue(long l)
{
if (value==null || value.getType()!=VALUE_TYPE_INTEGER) value = new ValueInteger(l);
else value.setInteger(l);
setNull(false);
}
/**
* Copy the Value from another Value.
* It doesn't copy the name.
* @param v The Value to copy the settings and value from
*/
public void setValue(Value v)
{
if (v!=null)
{
value = v.getValueCopy();
setNull(v.isNull());
setOrigin(v.origin);
}
else
{
clearValue();
}
}
/**
* Get the BigDecimal number of this Value.
* If the value is not of type BIG_NUMBER, a conversion is done first.
* @return the double precision floating point number of this Value.
*/
public BigDecimal getBigNumber()
{
if (value==null || isNull()) return null;
return value.getBigNumber();
}
/**
* Get the double precision floating point number of this Value.
* If the value is not of type NUMBER, a conversion is done first.
* @return the double precision floating point number of this Value.
*/
public double getNumber()
{
if (value==null || isNull()) return 0.0;
return value.getNumber();
}
/**
* Get the String text representing this value.
* If the value is not of type STRING, a conversion if done first.
* @return the String text representing this value.
*/
public String getString()
{
if (value==null || isNull()) return null;
return value.getString();
}
/**
* Get the length of the String representing this value.
* @return the length of the String representing this value.
*/
public int getStringLength()
{
String s = getString();
if (s==null) return 0;
return s.length();
}
/**
* Get the Date of this Value.
* If the Value is not of type DATE, a conversion is done first.
* @return the Date of this Value.
*/
public Date getDate()
{
if (value==null || isNull()) return null;
return value.getDate();
}
/**
* Get the Serializable of this Value.
* If the Value is not of type Serializable, it returns null.
* @return the Serializable of this Value.
*/
public Serializable getSerializable()
{
if (value==null || isNull() || value.getType() != VALUE_TYPE_SERIALIZABLE) return null;
return value.getSerializable();
}
public boolean getBoolean()
{
if (value==null || isNull()) return false;
return value.getBoolean();
}
public long getInteger()
{
if (value==null || isNull()) return 0L;
return value.getInteger();
}
/**
* Set the type of this Value
* @param val_type The type to which the Value will be set.
*/
public void setType(int val_type)
{
if (value==null) newValue(val_type);
else // Convert the value to the appropriate type...
{
convertTo(val_type);
}
}
/**
* Returns the type of this Value
* @return the type of this Value
*/
public int getType()
{
if (value==null) return VALUE_TYPE_NONE;
return value.getType();
}
/**
* Checks whether or not this Value is empty.
* A value is empty if it has the type VALUE_TYPE_EMPTY
* @return true if the value is empty.
*/
public boolean isEmpty()
{
if (value==null) return true;
return false;
}
/**
* Checks wheter or not the value is a String.
* @return true if the value is a String.
*/
public boolean isString()
{
if (value==null) return false;
return value.getType()==VALUE_TYPE_STRING;
}
/**
* Checks whether or not this value is a Date
* @return true if the value is a Date
*/
public boolean isDate()
{
if (value==null) return false;
return value.getType()==VALUE_TYPE_DATE;
}
/**
* Checks whether or not the value is a Big Number
* @return true is this value is a big number
*/
public boolean isBigNumber()
{
if (value==null) return false;
return value.getType()==VALUE_TYPE_BIGNUMBER;
}
/**
* Checks whether or not the value is a Number
* @return true is this value is a number
*/
public boolean isNumber()
{
if (value==null) return false;
return value.getType()==VALUE_TYPE_NUMBER;
}
/**
* Checks whether or not this value is a boolean
* @return true if this value has type boolean.
*/
public boolean isBoolean()
{
if (value==null) return false;
return value.getType()==VALUE_TYPE_BOOLEAN;
}
/**
* Checks whether or not this value is of type Serializable
* @retur true if this value has type Serializable
*/
public boolean isSerializableType() {
if(value == null) {
return false;
}
return value.getType() == VALUE_TYPE_SERIALIZABLE;
}
/**
* Checks whether or not this value is an Integer
* @return true if this value is an integer
*/
public boolean isInteger()
{
if (value==null) return false;
return value.getType()==VALUE_TYPE_INTEGER;
}
/**
* Checks whether or not this Value is Numeric
* A Value is numeric if it is either of type Number or Integer
* @return true if the value is either of type Number or Integer
*/
public boolean isNumeric()
{
return isInteger() || isNumber() || isBigNumber();
}
/**
* Checks whether or not the specified type is either Integer or Number
* @param t the type to check
* @return true if the type is Integer or Number
*/
public static final boolean isNumeric(int t)
{
return t==VALUE_TYPE_INTEGER || t==VALUE_TYPE_NUMBER || t==VALUE_TYPE_BIGNUMBER;
}
/**
* Returns a padded to length String text representation of this Value
* @return a padded to length String text representation of this Value
*/
public String toString()
{
return toString(true);
}
/**
* a String text representation of this Value, optionally padded to the specified length
* @param pad true if you want to pad the resulting String
* @return a String text representation of this Value, optionally padded to the specified length
*/
public String toString(boolean pad)
{
String retval;
switch(getType())
{
case VALUE_TYPE_STRING : retval=toStringString(pad); break;
case VALUE_TYPE_NUMBER : retval=toStringNumber(pad); break;
case VALUE_TYPE_DATE : retval=toStringDate(); break;
case VALUE_TYPE_BOOLEAN: retval=toStringBoolean(); break;
case VALUE_TYPE_INTEGER: retval=toStringInteger(pad); break;
case VALUE_TYPE_BIGNUMBER: retval=toStringBigNumber(pad); break;
default: retval=""; break;
}
return retval;
}
/**
* a String text representation of this Value, optionally padded to the specified length
* @param pad true if you want to pad the resulting String
* @return a String text representation of this Value, optionally padded to the specified length
*/
public String toStringMeta()
{
// We (Sven Boden) did explicit performance testing for this
// part. The original version used Strings instead of StringBuffers,
// performance between the 2 does not differ that much. A few milliseconds
// on 100000 iterations in the advantage of StringBuffers. The
// lessened creation of objects may be worth it in the long run.
StringBuffer retval=new StringBuffer(getTypeDesc());
switch(getType())
{
case VALUE_TYPE_STRING :
if (getLength()>0) retval.append('(').append(getLength()).append(')');
break;
case VALUE_TYPE_NUMBER :
case VALUE_TYPE_BIGNUMBER :
if (getLength()>0)
{
retval.append('(').append(getLength());
if (getPrecision()>0)
{
retval.append(", ").append(getPrecision());
}
retval.append(')');
}
break;
case VALUE_TYPE_INTEGER:
if (getLength()>0)
{
retval.append('(').append(getLength()).append(')');
}
break;
default: break;
}
return retval.toString();
}
/**
* Converts a String Value to String optionally padded to the specified length.
* @param pad true if you want to pad the resulting string to length.
* @return a String optionally padded to the specified length.
*/
private String toStringString(boolean pad)
{
String retval=null;
if (value==null) return null;
if (value.getLength()<=0) // No length specified!
{
if (isNull() || value.getString()==null)
retval = Const.NULL_STRING;
else
retval = value.getString();
}
else
{
StringBuffer ret;
if (isNull() || value.getString()==null) ret=new StringBuffer(Const.NULL_STRING);
else ret=new StringBuffer(value.getString());
if (pad)
{
int length = value.getLength();
if (length>16384) length=16384; // otherwise we get OUT OF MEMORY errors for CLOBS.
Const.rightPad(ret, length);
}
retval=ret.toString();
}
return retval;
}
/**
* Converts a Number value to a String, optionally padding the result to the specified length.
* @param pad true if you want to pad the resulting string to length.
* @return a String optionally padded to the specified length.
*/
private String toStringNumber(boolean pad)
{
String retval;
if (value==null) return null;
if (pad)
{
if (value.getLength()<1)
{
if (isNull()) retval=Const.NULL_NUMBER;
else
{
DecimalFormat form= new DecimalFormat();
form.applyPattern("
// System.out.println("local.pattern = ["+form.toLocalizedPattern()+"]");
retval=form.format(value.getNumber());
}
}
else
{
if (isNull())
{
StringBuffer ret=new StringBuffer(Const.NULL_NUMBER);
Const.rightPad(ret, value.getLength());
retval=ret.toString();
}
else
{
StringBuffer fmt=new StringBuffer();
int i;
DecimalFormat form;
if (value.getNumber()>=0) fmt.append(' '); // to compensate for minus sign.
if (value.getPrecision()<0) // Default: two decimals
{
for (i=0;i<value.getLength();i++) fmt.append('0');
fmt.append(".00"); // for the .00
}
else // Floating point format 00001234,56 --> (12,2)
{
for (i=0;i<=value.getLength();i++) fmt.append('0'); // all zeroes.
int pos = value.getLength()-value.getPrecision()+1-(value.getNumber()<0?1:0);
if (pos>=0 && pos <fmt.length())
{
fmt.setCharAt(value.getLength()-value.getPrecision()+1-(value.getNumber()<0?1:0), '.'); // one 'comma'
}
}
form= new DecimalFormat(fmt.toString());
retval=form.format(value.getNumber());
}
}
}
else
{
if (isNull()) retval=Const.NULL_NUMBER;
else retval=""+value.getNumber();
}
return retval;
}
/**
* Converts a Date value to a String.
* The date has format: <code>yyyy/MM/dd HH:mm:ss.SSS</code>
* @return a String representing the Date Value.
*/
private String toStringDate()
{
String retval;
if (value==null) return null;
SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS", Locale.US);
if (isNull() || value.getDate()==null) retval=Const.NULL_DATE;
else
{
retval=df.format(value.getDate()).toString();
}
/*
This code was removed as TYPE_VALUE_DATE does not know "length", so this
could never be called anyway
else
{
StringBuffer ret;
if (isNull() || value.getDate()==null)
ret=new StringBuffer(Const.NULL_DATE);
else ret=new StringBuffer(df.format(value.getDate()).toString());
Const.rightPad(ret, getLength()<=10?10:getLength());
retval=ret.toString();
}
*/
return retval;
}
/**
* Returns a String representing the boolean value.
* It will be either "true" or "false".
*
* @return a String representing the boolean value.
*/
private String toStringBoolean()
{
// Code was removed from this method as ValueBoolean
// did not store length, so some parts could never be
// called.
String retval;
if (value==null) return null;
if (isNull())
{
retval=Const.NULL_BOOLEAN;
}
else
{
retval=value.getBoolean()?"true":"false";
}
return retval;
}
/**
* Converts an Integer value to a String, optionally padding the result to the specified length.
* @param pad true if you want to pad the resulting string to length.
* @return a String optionally padded to the specified length.
*/
private String toStringInteger(boolean pad)
{
String retval;
if (value==null) return null;
if (getLength()<1)
{
if (isNull()) retval=Const.NULL_INTEGER;
else
{
DecimalFormat form= new DecimalFormat("
retval=form.format(value.getInteger());
}
}
else
{
if (isNull())
{
StringBuffer ret=new StringBuffer(Const.NULL_INTEGER);
Const.rightPad(ret, getLength());
retval=ret.toString();
}
else
{
StringBuffer fmt=new StringBuffer();
int i;
DecimalFormat form;
if (value.getInteger()>=0) fmt.append(' '); // to compensate for minus sign.
int len = getLength();
for (i=0;i<len;i++) fmt.append('0'); // all zeroes.
form= new DecimalFormat(fmt.toString());
retval=form.format(value.getInteger());
}
}
return retval;
}
/**
* Converts a BigNumber value to a String, optionally padding the result to the specified length. // TODO: BigNumber padding
* @param pad true if you want to pad the resulting string to length.
* @return a String optionally padded to the specified length.
*/
private String toStringBigNumber(boolean pad)
{
if (value.getBigNumber()==null) return null;
String retval = value.getString();
// Localise . to ,
if (Const.DEFAULT_DECIMAL_SEPARATOR!='.')
{
retval = retval.replace('.', Const.DEFAULT_DECIMAL_SEPARATOR);
}
return retval;
}
/**
* Sets the length of the Number, Integer or String to the specified length
* Note: no truncation of the value takes place, this is meta-data only!
* @param l the length to which you want to set the Value.
*/
public void setLength(int l)
{
if (value==null) return;
value.setLength(l);
}
/**
* Sets the length and the precision of the Number, Integer or String to the specified length & precision
* Note: no truncation of the value takes place, this is meta-data only!
* @param l the length to which you want to set the Value.
* @param p the precision to which you want to set this Value
*/
public void setLength(int l, int p)
{
if (value==null) return;
value.setLength(l,p);
}
/**
* Get the length of this Value.
* @return the length of this Value.
*/
public int getLength()
{
if (value==null) return -1;
return value.getLength();
}
/**
* get the precision of this Value
* @return the precision of this Value.
*/
public int getPrecision()
{
if (value==null) return -1;
return value.getPrecision();
}
/**
* Sets the precision of this Value
* Note: no rounding or truncation takes place, this is meta-data only!
* @param p the precision to which you want to set this Value.
*/
public void setPrecision(int p)
{
if (value==null) return;
value.setPrecision(p);
}
/**
* Return the type of a value in a textual form: "String", "Number", "Integer", "Boolean", "Date", ...
* @return A String describing the type of value.
*/
public String getTypeDesc()
{
if (value==null) return "Unknown";
return value.getTypeDesc();
}
/**
* Return the type of a value in a textual form: "String", "Number", "Integer", "Boolean", "Date", ... given a certain integer type
* @param t the type to convert to text.
* @return A String describing the type of a certain value.
*/
public static final String getTypeDesc(int t)
{
return valueTypeCode[t];
}
/**
* Convert the String description of a type to an integer type.
* @param desc The description of the type to convert
* @return The integer type of the given String. (Value.VALUE_TYPE_...)
*/
public static final int getType(String desc)
{
int i;
for (i=1;i<valueTypeCode.length;i++)
{
if (valueTypeCode[i].equalsIgnoreCase(desc))
{
return i;
}
}
return VALUE_TYPE_NONE;
}
/**
* get an array of String describing the possible types a Value can have.
* @return an array of String describing the possible types a Value can have.
*/
public static final String[] getTypes()
{
String retval[] = new String[valueTypeCode.length-1];
System.arraycopy(valueTypeCode, 1, retval, 0, valueTypeCode.length-1);
return retval;
}
/**
* Get an array of String describing the possible types a Value can have.
* @return an array of String describing the possible types a Value can have.
*/
public static final String[] getAllTypes()
{
String retval[] = new String[valueTypeCode.length];
System.arraycopy(valueTypeCode, 0, retval, 0, valueTypeCode.length);
return retval;
}
/**
* Sets the Value to null, no type is being changed.
*
*/
public void setNull()
{
setNull(true);
}
/**
* Sets or unsets a value to null, no type is being changed.
* @param n true if you want the value to be null, false if you don't want this to be the case.
*/
public void setNull(boolean n)
{
NULL=n;
}
/**
* Checks wheter or not a value is null.
* @return true if the Value is null.
*/
public boolean isNull()
{
return NULL;
}
/**
* Write the object to an ObjectOutputStream
* @param out
* @throws IOException
*/
private void writeObject(java.io.ObjectOutputStream out) throws IOException
{
writeObj(new DataOutputStream(out));
}
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException
{
readObj(new DataInputStream(in));
}
public void writeObj(DataOutputStream dos) throws IOException
{
int type=getType();
// Handle type
dos.writeInt(getType());
// Handle name-length
dos.writeInt(name.length());
// Write name
dos.writeChars(name);
// length & precision
dos.writeInt(getLength());
dos.writeInt(getPrecision());
// NULL?
dos.writeBoolean(isNull());
// Handle Content -- only when not NULL
if (!isNull())
{
switch(type)
{
case VALUE_TYPE_STRING :
case VALUE_TYPE_BIGNUMBER:
if (getString()!=null && getString().getBytes().length>0)
{
dos.writeInt(getString().getBytes("UTF-8").length);
dos.writeUTF(getString());
}
else
{
dos.writeInt(0);
}
break;
case VALUE_TYPE_DATE :
dos.writeBoolean(getDate()!=null);
if (getDate()!=null)
{
dos.writeLong(getDate().getTime());
}
break;
case VALUE_TYPE_NUMBER :
dos.writeDouble(getNumber());
break;
case VALUE_TYPE_BOOLEAN:
dos.writeBoolean(getBoolean());
break;
case VALUE_TYPE_INTEGER:
dos.writeLong(getInteger());
break;
default: break; // nothing
}
}
}
/**
* Write the value, including the meta-data to a DataOutputStream
* @param outputStream the OutputStream to write to .
* @throws KettleFileException if something goes wrong.
*/
public void write(OutputStream outputStream) throws KettleFileException
{
try
{
writeObj(new DataOutputStream(outputStream));
}
catch(Exception e)
{
throw new KettleFileException("Unable to write value to output stream", e);
}
}
public void readObj(DataInputStream dis) throws IOException
{
// type
int theType = dis.readInt();
newValue(theType);
// name-length
int nameLength=dis.readInt();
// name
StringBuffer nameBuffer=new StringBuffer();
for (int i=0;i<nameLength;i++) nameBuffer.append(dis.readChar());
setName(new String(nameBuffer));
// length & precision
setLength(dis.readInt(), dis.readInt());
// Null?
setNull(dis.readBoolean());
// Read the values
if (!isNull())
{
switch(getType())
{
case VALUE_TYPE_STRING:
case VALUE_TYPE_BIGNUMBER:
// Handle lengths
int dataLength=dis.readInt();
if (dataLength>0)
{
String string = dis.readUTF();
setValue(string);
}
if (theType==VALUE_TYPE_BIGNUMBER)
{
try
{
convertString(theType);
}
catch(KettleValueException e)
{
throw new IOException("Unable to convert String to BigNumber while reading from data input stream ["+getString()+"]");
}
}
break;
case VALUE_TYPE_DATE:
if (dis.readBoolean())
{
setValue(new Date(dis.readLong()));
}
break;
case VALUE_TYPE_NUMBER:
setValue(dis.readDouble());
break;
case VALUE_TYPE_INTEGER:
setValue(dis.readLong());
break;
case VALUE_TYPE_BOOLEAN:
setValue(dis.readBoolean());
break;
default: break;
}
}
}
public Value(InputStream is) throws KettleFileException
{
try
{
readObj(new DataInputStream(is));
}
catch(EOFException e)
{
throw new KettleEOFException("End of file reached", e);
}
catch(Exception e)
{
throw new KettleFileException("Error reading from data input stream", e);
}
}
/**
* Write the data of this Value, without the meta-data to a DataOutputStream
* @param dos The DataOutputStream to write the data to
* @return true if all went well, false if something went wrong.
*/
public boolean writeData(DataOutputStream dos) throws KettleFileException
{
try
{
// Is the value NULL?
dos.writeBoolean(isNull());
// Handle Content -- only when not NULL
if (!isNull())
{
switch(getType())
{
case VALUE_TYPE_STRING :
case VALUE_TYPE_BIGNUMBER:
if (getString()!=null && getString().getBytes().length>0)
{
dos.writeInt(getString().getBytes().length);
dos.writeUTF(getString());
}
else
{
dos.writeInt(0);
}
break;
case VALUE_TYPE_DATE :
dos.writeBoolean(getDate()!=null);
if (getDate()!=null)
{
dos.writeLong(getDate().getTime());
}
break;
case VALUE_TYPE_NUMBER :
dos.writeDouble(getNumber());
break;
case VALUE_TYPE_BOOLEAN:
dos.writeBoolean(getBoolean());
break;
case VALUE_TYPE_INTEGER:
dos.writeLong(getInteger());
break;
default: break; // nothing
}
}
}
catch(IOException e)
{
throw new KettleFileException("Unable to write value data to output stream", e);
}
return true;
}
/**
* Read the data of a Value from a DataInputStream, the meta-data of the value has to be set before calling this method!
* @param dis the DataInputStream to read from
* @throws KettleFileException when the value couldn't be read from the DataInputStream
*/
public Value(Value metaData, DataInputStream dis) throws KettleFileException
{
setValue(metaData);
setName(metaData.getName());
try
{
// Is the value NULL?
setNull(dis.readBoolean());
// Read the values
if (!isNull())
{
switch(getType())
{
case VALUE_TYPE_STRING:
case VALUE_TYPE_BIGNUMBER:
// Handle lengths
int dataLength=dis.readInt();
if (dataLength>0)
{
String string = dis.readUTF();
setValue(string);
if (metaData.isBigNumber()) convertString(metaData.getType());
}
break;
case VALUE_TYPE_DATE:
if (dis.readBoolean())
{
setValue(new Date(dis.readLong()));
}
break;
case VALUE_TYPE_NUMBER:
setValue(dis.readDouble());
break;
case VALUE_TYPE_INTEGER:
setValue(dis.readLong());
break;
case VALUE_TYPE_BOOLEAN:
setValue(dis.readBoolean());
break;
default: break;
}
}
}
catch(EOFException e)
{
throw new KettleEOFException("End of file reached", e);
}
catch(Exception e)
{
throw new KettleEOFException("Error reading value data from stream", e);
}
}
/**
* Compare 2 values of the same or different type!
* The comparison of Strings is case insensitive
* @param v the value to compare with.
* @return -1 if The value was smaller, 1 bigger and 0 if both values are equal.
*/
public int compare(Value v)
{
return compare(v, true);
}
/**
* Compare 2 values of the same or different type!
* @param v the value to compare with.
* @param caseInsensitive True if you want the comparison to be case insensitive
* @return -1 if The value was smaller, 1 bigger and 0 if both values are equal.
*/
public int compare(Value v, boolean caseInsensitive)
{
boolean n1 = isNull() || (isString() && (getString()==null || getString().length()==0)) || (isDate() && getDate()==null) || (isBigNumber() && getBigNumber()==null);
boolean n2 = v.isNull() || (v.isString() && (v.getString()==null || v.getString().length()==0)) || (v.isDate() && v.getDate()==null) || (v.isBigNumber() && v.getBigNumber()==null);
// null is always smaller!
if ( n1 && !n2) return -1;
if (!n1 && n2) return 1;
if ( n1 && n2) return 0;
switch(getType())
{
case VALUE_TYPE_STRING:
{
String one = Const.rtrim(getString());
String two = Const.rtrim(v.getString());
int cmp=0;
if (caseInsensitive)
{
cmp = one.compareToIgnoreCase(two);
}
else
{
cmp = one.compareTo(two);
}
return cmp;
}
case VALUE_TYPE_INTEGER:
{
return Double.compare(getNumber(), v.getNumber());
}
case VALUE_TYPE_DATE :
{
return Double.compare(getNumber(), v.getNumber());
}
case VALUE_TYPE_BOOLEAN:
{
if (getBoolean() && v.getBoolean() ||
!getBoolean() && !v.getBoolean()) return 0; // true == true, false == false
if (getBoolean() && !v.getBoolean()) return 1; // true > false
return -1; // false < true
}
case VALUE_TYPE_NUMBER :
{
return Double.compare(getNumber(), v.getNumber());
}
case VALUE_TYPE_BIGNUMBER:
{
return getBigNumber().compareTo(v.getBigNumber());
}
}
// Still here? Not possible! But hey, give back 0, mkay?
return 0;
}
public boolean equals(Object v)
{
if (compare((Value)v)==0)
return true;
else
return false;
}
/**
* Check whether this value is equal to the String supplied.
* @param string The string to check for equality
* @return true if the String representation of the value is equal to string. (ignoring case)
*/
public boolean isEqualTo(String string)
{
return getString().equalsIgnoreCase(string);
}
/**
* Check whether this value is equal to the BigDecimal supplied.
* @param number The BigDecimal to check for equality
* @return true if the BigDecimal representation of the value is equal to number.
*/
public boolean isEqualTo(BigDecimal number)
{
return getBigNumber().equals(number);
}
/**
* Check whether this value is equal to the Number supplied.
* @param number The Number to check for equality
* @return true if the Number representation of the value is equal to number.
*/
public boolean isEqualTo(double number)
{
return getNumber() == number;
}
/**
* Check whether this value is equal to the Integer supplied.
* @param number The Integer to check for equality
* @return true if the Integer representation of the value is equal to number.
*/
public boolean isEqualTo(long number)
{
return getInteger() == number;
}
/**
* Check whether this value is equal to the Integer supplied.
* @param number The Integer to check for equality
* @return true if the Integer representation of the value is equal to number.
*/
public boolean isEqualTo(int number)
{
return getInteger() == number;
}
/**
* Check whether this value is equal to the Integer supplied.
* @param number The Integer to check for equality
* @return true if the Integer representation of the value is equal to number.
*/
public boolean isEqualTo(byte number)
{
return getInteger() == number;
}
/**
* Check whether this value is equal to the Date supplied.
* @param date The Date to check for equality
* @return true if the Date representation of the value is equal to date.
*/
public boolean isEqualTo(Date date)
{
return getDate() == date;
}
public int hashCode()
{
int hash=0; // name.hashCode(); -> Name shouldn't be part of hashCode()!
if (isNull())
{
switch(getType())
{
case VALUE_TYPE_BOOLEAN : hash^= 1; break;
case VALUE_TYPE_DATE : hash^= 2; break;
case VALUE_TYPE_NUMBER : hash^= 4; break;
case VALUE_TYPE_STRING : hash^= 8; break;
case VALUE_TYPE_INTEGER : hash^=16; break;
case VALUE_TYPE_BIGNUMBER : hash^=32; break;
case VALUE_TYPE_NONE : break;
default: break;
}
}
else
{
switch(getType())
{
case VALUE_TYPE_BOOLEAN : hash^=Boolean.valueOf(getBoolean()).hashCode(); break;
case VALUE_TYPE_DATE : if (getDate()!=null) hash^=getDate().hashCode(); break;
case VALUE_TYPE_INTEGER :
case VALUE_TYPE_NUMBER : hash^=(new Double(getNumber())).hashCode(); break;
case VALUE_TYPE_STRING : if (getString()!=null) hash^=getString().hashCode(); break;
case VALUE_TYPE_BIGNUMBER : if (getBigNumber()!=null) hash^=getBigNumber().hashCode(); break;
case VALUE_TYPE_NONE : break;
default: break;
}
}
return hash;
}
// OPERATORS & COMPARATORS
public Value and(Value v)
{
long n1 = getInteger();
long n2 = v.getInteger();
long res = n1 & n2;
setValue(res);
return this;
}
public Value xor(Value v)
{
long n1 = getInteger();
long n2 = v.getInteger();
long res = n1 ^ n2;
setValue(res);
return this;
}
public Value or(Value v)
{
long n1 = getInteger();
long n2 = v.getInteger();
long res = n1 | n2;
setValue(res);
return this;
}
public Value bool_and(Value v)
{
boolean b1 = getBoolean();
boolean b2 = v.getBoolean();
boolean res = b1 && b2;
setValue(res);
return this;
}
public Value bool_or(Value v)
{
boolean b1 = getBoolean();
boolean b2 = v.getBoolean();
boolean res = b1 || b2;
setValue(res);
return this;
}
public Value bool_xor(Value v)
{
boolean b1 = getBoolean();
boolean b2 = v.getBoolean();
boolean res = b1&&b2 ? false : !b1&&!b2 ? false : true;
setValue(res);
return this;
}
public Value bool_not()
{
value.setBoolean(!getBoolean());
return this;
}
public Value greater_equal(Value v)
{
if (compare(v)>=0) setValue(true); else setValue(false);
return this;
}
public Value smaller_equal(Value v)
{
if (compare(v)<=0) setValue(true); else setValue(false);
return this;
}
public Value different(Value v)
{
if (compare(v)!=0) setValue(true); else setValue(false);
return this;
}
public Value equal(Value v)
{
if (compare(v)==0) setValue(true); else setValue(false);
return this;
}
public Value like(Value v)
{
String cmp=v.getString();
// Is cmp part of look?
int idx=getString().indexOf(cmp);
if (idx<0) setValue(false); else setValue(true);
return this;
}
public Value greater(Value v)
{
if (compare(v)>0) setValue(true); else setValue(false);
return this;
}
public Value smaller(Value v)
{
if (compare(v)<0) setValue(true); else setValue(false);
return this;
}
public Value minus(BigDecimal v) throws KettleValueException { return minus(new Value("tmp", v)); }
public Value minus(double v) throws KettleValueException { return minus(new Value("tmp", v)); }
public Value minus(long v) throws KettleValueException { return minus(new Value("tmp", v)); }
public Value minus(int v) throws KettleValueException { return minus(new Value("tmp", (long)v)); }
public Value minus(byte v) throws KettleValueException { return minus(new Value("tmp", (long)v)); }
public Value minus(Value v) throws KettleValueException
{
switch(getType())
{
case VALUE_TYPE_BIGNUMBER : value.setBigNumber(getBigNumber().subtract(v.getBigNumber())); break;
case VALUE_TYPE_NUMBER : value.setNumber(getNumber()-v.getNumber()); break;
case VALUE_TYPE_INTEGER : value.setInteger(getInteger()-v.getInteger()); break;
case VALUE_TYPE_BOOLEAN :
case VALUE_TYPE_STRING :
default:
throw new KettleValueException("Subtraction can only be done with numbers!");
}
return this;
}
public Value plus(BigDecimal v) { return plus(new Value("tmp", v)); }
public Value plus(double v) { return plus(new Value("tmp", v)); }
public Value plus(long v) { return plus(new Value("tmp", v)); }
public Value plus(int v) { return plus(new Value("tmp", (long)v)); }
public Value plus(byte v) { return plus(new Value("tmp", (long)v)); }
public Value plus(Value v)
{
switch(getType())
{
case VALUE_TYPE_BIGNUMBER : setValue(getBigNumber().add(v.getBigNumber())); break;
case VALUE_TYPE_NUMBER : setValue(getNumber()+v.getNumber()); break;
case VALUE_TYPE_INTEGER : setValue(getInteger()+v.getInteger()); break;
case VALUE_TYPE_BOOLEAN : setValue(getBoolean()|v.getBoolean()); break;
case VALUE_TYPE_STRING : setValue(getString()+v.getString()); break;
default: break;
}
return this;
}
public Value divide(BigDecimal v) throws KettleValueException { return divide(new Value("tmp", v)); }
public Value divide(double v) throws KettleValueException { return divide(new Value("tmp", v)); }
public Value divide(long v) throws KettleValueException { return divide(new Value("tmp", v)); }
public Value divide(int v) throws KettleValueException { return divide(new Value("tmp", (long)v)); }
public Value divide(byte v) throws KettleValueException { return divide(new Value("tmp", (long)v)); }
public Value divide(Value v) throws KettleValueException
{
if (isNull() || v.isNull())
{
setNull();
}
else
{
switch(getType())
{
case VALUE_TYPE_BIGNUMBER : setValue(getBigNumber().divide(v.getBigNumber(), BigDecimal.ROUND_UP)); break;
case VALUE_TYPE_NUMBER : setValue(getNumber()/v.getNumber()); break;
case VALUE_TYPE_INTEGER : setValue(getInteger()/v.getInteger()); break;
case VALUE_TYPE_BOOLEAN :
case VALUE_TYPE_STRING :
default:
throw new KettleValueException("Division can only be done with numeric data!");
}
}
return this;
}
public Value multiply(BigDecimal v) throws KettleValueException { return multiply(new Value("tmp", v)); }
public Value multiply(double v) throws KettleValueException { return multiply(new Value("tmp", v)); }
public Value multiply(long v) throws KettleValueException { return multiply(new Value("tmp", v)); }
public Value multiply(int v) throws KettleValueException { return multiply(new Value("tmp", (long)v)); }
public Value multiply(byte v) throws KettleValueException { return multiply(new Value("tmp", (long)v)); }
public Value multiply(Value v) throws KettleValueException
{
// a number and a string!
if (isNull() || v.isNull())
{
setNull();
return this;
}
if ((v.isString() && isNumeric()) || (v.isNumeric() && isString()))
{
StringBuffer s;
String append="";
int n;
if (v.isString())
{
s=new StringBuffer(v.getString());
append=v.getString();
n=(int)getInteger();
}
else
{
s=new StringBuffer(getString());
append=getString();
n=(int)v.getInteger();
}
if (n==0) s.setLength(0);
else
for (int i=1;i<n;i++) s.append(append);
setValue(s);
}
else
// big numbers
if (isBigNumber() || v.isBigNumber())
{
setValue(getBigNumber().multiply(v.getBigNumber()));
}
else
// numbers
if (isNumber() || v.isNumber())
{
setValue(getNumber()*v.getNumber());
}
else
// integers
if (isInteger() || v.isInteger())
{
setValue(getInteger()*v.getInteger());
}
else
{
throw new KettleValueException("Multiplication can only be done with numbers or a number and a string!");
}
return this;
}
// FUNCTIONS!!
// implement the ABS function, arguments in args[]
public Value abs() throws KettleValueException
{
if (isNull()) return this;
if (isBigNumber())
{
setValue(getBigNumber().abs());
}
else
if (isNumber())
{
setValue(Math.abs(getNumber()));
}
else
if (isInteger())
{
setValue(Math.abs(getInteger()));
}
else
{
throw new KettleValueException("Function ABS only works with a number");
}
return this;
}
// implement the ACOS function, arguments in args[]
public Value acos() throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
setValue(Math.acos(getNumber()));
}
else
{
throw new KettleValueException("Function ACOS only works with numeric data");
}
return this;
}
// implement the ASIN function, arguments in args[]
public Value asin() throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
setValue(Math.asin(getNumber()));
}
else
{
throw new KettleValueException("Function ASIN only works with numeric data");
}
return this;
}
// implement the ATAN function, arguments in args[]
public Value atan() throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
setValue(Math.atan(getNumber()));
}
else
{
throw new KettleValueException("Function ATAN only works with numeric data");
}
return this;
}
// implement the ATAN2 function, arguments in args[]
public Value atan2(Value arg0) throws KettleValueException { return atan2(arg0.getNumber()); }
public Value atan2(double arg0) throws KettleValueException
{
if (isNull())
{
return this;
}
if (isNumeric())
{
setValue(Math.atan2(getNumber(), arg0));
}
else
{
throw new
KettleValueException("Function ATAN2 only works with numbers");
}
return this;
}
// implement the CEIL function, arguments in args[]
public Value ceil() throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
setValue(Math.ceil(getNumber()));
}
else
{
throw new KettleValueException("Function CEIL only works with a number");
}
return this;
}
// implement the COS function, arguments in args[]
public Value cos() throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
setValue(Math.cos(getNumber()));
}
else
{
throw new KettleValueException("Function COS only works with a number");
}
return this;
}
// implement the EXP function, arguments in args[]
public Value exp() throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
setValue(Math.exp(getNumber()));
}
else
{
throw new KettleValueException("Function EXP only works with a number");
}
return this;
}
// implement the FLOOR function, arguments in args[]
public Value floor() throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
setValue(Math.floor(getNumber()));
}
else
{
throw new KettleValueException("Function FLOOR only works with a number");
}
return this;
}
// implement the INITCAP function, arguments in args[]
public Value initcap() throws KettleValueException
{
if (isNull()) return this;
if (getType()==VALUE_TYPE_STRING)
{
if (getString()==null)
{
setNull();
}
else
{
StringBuffer change=new StringBuffer(getString());
boolean new_word;
int i;
char lower, upper, ch;
new_word=true;
for (i=0 ; i<getString().length() ; i++)
{
lower=change.substring(i,i+1).toLowerCase().charAt(0); // Lowercase is default.
upper=change.substring(i,i+1).toUpperCase().charAt(0); // Uppercase for new words.
ch=upper;
if (new_word)
{
change.setCharAt(i, upper);
}
else
{
change.setCharAt(i, lower);
}
new_word = false;
if ( !(ch>='A' && ch<='Z') &&
!(ch>='0' && ch<='9') &&
ch!='_'
) new_word = true;
}
setValue( change.toString() );
}
}
else
{
throw new KettleValueException("Function INITCAP only works with a string");
}
return this;
}
// implement the LENGTH function, arguments in args[]
public Value length() throws KettleValueException
{
if (isNull())
{
setType(VALUE_TYPE_INTEGER);
setValue(0L);
return this;
}
if (getType()==VALUE_TYPE_STRING)
{
setValue((double)getString().length());
}
else
{
throw new KettleValueException("Function LENGTH only works with a string");
}
return this;
}
// implement the LOG function, arguments in args[]
public Value log() throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
setValue(Math.log(getNumber()));
}
else
{
throw new KettleValueException("Function LOG only works with a number");
}
return this;
}
// implement the LOWER function, arguments in args[]
public Value lower()
{
if (isNull())
{
setType(VALUE_TYPE_STRING);
}
else
{
setValue( getString().toLowerCase() );
}
return this;
}
// implement the LPAD function: left pad strings or numbers...
public Value lpad(Value len) { return lpad((int)len.getNumber(), " "); }
public Value lpad(Value len, Value padstr) { return lpad((int)len.getNumber(), padstr.getString()); }
public Value lpad(int len) { return lpad(len, " "); }
public Value lpad(int len, String padstr)
{
if (isNull())
{
setType(VALUE_TYPE_STRING);
}
else
{
if (getType()!=VALUE_TYPE_STRING) // also lpad other types!
{
setValue(getString());
}
if (getString()!=null)
{
StringBuffer result = new StringBuffer(getString());
int pad=len;
int l= ( pad-result.length() ) / padstr.length() + 1;
int i;
for (i=0;i<l;i++) result.insert(0, padstr);
// Maybe we added one or two too many!
i=result.length();
while (i>pad && pad>0)
{
result.deleteCharAt(0);
i
}
setValue(result.toString());
}
else
{
setNull();
}
}
setLength(len);
return this;
}
// implement the LTRIM function
public Value ltrim()
{
if (isNull())
{
setType(VALUE_TYPE_STRING);
}
else
{
if (getString()!=null)
{
StringBuffer s;
if (getType()==VALUE_TYPE_STRING)
{
s = new StringBuffer(getString());
}
else
{
s = new StringBuffer(toString());
}
// Left trim
while (s.length()>0 && s.charAt(0)==' ') s.deleteCharAt(0);
setValue(s);
}
else
{
setNull();
}
}
return this;
}
// implement the MOD function, arguments in args[]
public Value mod(Value arg) throws KettleValueException { return mod(arg.getNumber()); }
public Value mod(BigDecimal arg) throws KettleValueException { return mod(arg.doubleValue()); }
public Value mod(long arg) throws KettleValueException { return mod((double)arg); }
public Value mod(int arg) throws KettleValueException { return mod((double)arg); }
public Value mod(byte arg) throws KettleValueException { return mod((double)arg); }
public Value mod(double arg0) throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
double n1=getNumber();
double n2=arg0;
setValue( n1 - (n2 * Math.floor(n1 /n2 )) );
}
else
{
throw new KettleValueException("Function MOD only works with numeric data");
}
return this;
}
// implement the NVL function, arguments in args[]
public Value nvl(Value alt)
{
if (isNull()) setValue(alt);
return this;
}
// implement the POWER function, arguments in args[]
public Value power(BigDecimal arg) throws KettleValueException{ return power(new Value("tmp", arg)); }
public Value power(double arg) throws KettleValueException{ return power(new Value("tmp", arg)); }
public Value power(Value v) throws KettleValueException
{
if (isNull()) return this;
else if (isNumeric())
{
setValue( Math.pow(getNumber(), v.getNumber()) );
}
else
{
throw new KettleValueException("Function POWER only works with numeric data");
}
return this;
}
// implement the REPLACE function, arguments in args[]
public Value replace(Value repl, Value with) { return replace(repl.getString(), with.getString()); }
public Value replace(String repl, String with)
{
if (isNull()) return this;
if (getString()==null)
{
setNull();
}
else
{
setValue( Const.replace(getString(), repl, with) );
}
return this;
}
/**
* Rounds off to the nearest integer.<p>
* See also: java.lang.Math.round()
*
* @return The rounded Number value.
*/
public Value round() throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
setValue( (double)Math.round(getNumber()) );
}
else
{
throw new KettleValueException("Function ROUND only works with a number");
}
return this;
}
/**
* Rounds the Number value to a certain number decimal places.
* @param decimalPlaces
* @return The rounded Number Value
* @throws KettleValueException in case it's not a number (or other problem).
*/
public Value round(int decimalPlaces) throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
if (isBigNumber())
{
// Multiply by 10^decimalPlaces
// For example 123.458343938437, Decimalplaces = 2
BigDecimal bigDec = getBigNumber();
// System.out.println("ROUND decimalPlaces : "+decimalPlaces+", bigNumber = "+bigDec);
bigDec = bigDec.setScale(decimalPlaces, BigDecimal.ROUND_HALF_EVEN);
// System.out.println("ROUND finished result : "+bigDec);
setValue( bigDec );
}
else
{
setValue( (double)Const.round(getNumber(), decimalPlaces) );
}
}
else
{
throw new KettleValueException("Function ROUND only works with a number");
}
return this;
}
// implement the RPAD function, arguments in args[]
public Value rpad(Value len) { return rpad((int)len.getNumber(), " "); }
public Value rpad(Value len, Value padstr) { return rpad((int)len.getNumber(), padstr.getString()); }
public Value rpad(int len) { return rpad(len, " "); }
public Value rpad(int len, String padstr)
{
if (isNull())
{
setType(VALUE_TYPE_STRING);
}
else
{
if (getType()!=VALUE_TYPE_STRING) // also rpad other types!
{
setValue(getString());
}
if (getString()!=null)
{
StringBuffer result = new StringBuffer(getString());
int pad=len;
int l= ( pad-result.length() ) / padstr.length() + 1;
int i;
for (i=0;i<l;i++) result.append(padstr);
// Maybe we added one or two too many!
i=result.length();
while (i>pad && pad>0)
{
result.deleteCharAt(i-1);
i
}
setValue(result.toString());
}
else
{
setNull();
}
}
setLength(len);
return this;
}
// implement the RTRIM function, arguments in args[]
public Value rtrim()
{
if (isNull())
{
setType(VALUE_TYPE_STRING);
}
else
{
StringBuffer s;
if (getType()==VALUE_TYPE_STRING)
{
s = new StringBuffer(getString());
}
else
{
s = new StringBuffer(toString());
}
// Right trim
while (s.length()>0 && s.charAt(s.length()-1)==' ') s.deleteCharAt(s.length()-1);
setValue(s);
}
return this;
}
// implement the SIGN function, arguments in args[]
public Value sign() throws KettleValueException
{
if (isNull()) return this;
if (isNumber())
{
int cmp = getBigNumber().compareTo(new BigDecimal(0L));
if (cmp>0) value.setBigNumber(new BigDecimal(1L));
else if (cmp<0) value.setBigNumber(new BigDecimal(-1L));
else value.setBigNumber(new BigDecimal(0L));
}
else
if (isNumber())
{
if (getNumber()>0) value.setNumber(1.0);
else if (getNumber()<0) value.setNumber(-1.0);
else value.setNumber(0.0);
}
else
if (isInteger())
{
if (getInteger()>0) value.setInteger(1);
else if (getInteger()<0) value.setInteger(-1);
else value.setInteger(0);
}
else
{
throw new KettleValueException("Function SIGN only works with a number");
}
return this;
}
// implement the SIN function, arguments in args[]
public Value sin() throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
setValue( Math.sin(getNumber()) );
}
else
{
throw new KettleValueException("Function SIN only works with a number");
}
return this;
}
// implement the SQRT function, arguments in args[]
public Value sqrt() throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
setValue( Math.sqrt(getNumber()) );
}
else
{
throw new KettleValueException("Function SQRT only works with a number");
}
return this;
}
// implement the SUBSTR function, arguments in args[]
public Value substr(Value from, Value to) { return substr((int)from.getNumber(), (int)to.getNumber()); }
public Value substr(Value from) { return substr((int)from.getNumber(), -1); }
public Value substr(int from) { return substr(from, -1); }
public Value substr(int from, int to)
{
if (isNull())
{
setType(VALUE_TYPE_STRING);
return this;
}
setValue( getString() );
if (getString()!=null)
{
if (to<0 && from>=0)
{
setValue( getString().substring(from) );
}
else if (to>=0 && from>=0)
{
setValue( getString().substring(from, to) );
}
}
else
{
setNull();
}
if (!isString()) setType(VALUE_TYPE_STRING);
return this;
}
// implement the RIGHTSTR function, arguments in args[]
public Value rightstr(Value len) { return rightstr((int)len.getNumber()); }
public Value rightstr(int len)
{
if (isNull())
{
setType(VALUE_TYPE_STRING);
return this;
}
setValue( getString() );
int tot_len = getString()!=null?getString().length():0;
if (tot_len>0)
{
int totlen = getString().length();
int f = totlen-len;
if (f<0) f=0;
setValue( getString().substring(f) );
}
else
{
setNull();
}
if (!isString()) setType(VALUE_TYPE_STRING);
return this;
}
// implement the LEFTSTR function, arguments in args[]
public Value leftstr(Value len)
{
return leftstr((int)len.getNumber());
}
public Value leftstr(int len)
{
if (isNull())
{
setType(VALUE_TYPE_STRING);
return this;
}
setValue( getString() );
int tot_len = getString()!=null?getString().length():0;
if (tot_len>0)
{
int totlen = getString().length();
int f = totlen-len;
if (f>0)
{
setValue( getString().substring(0,len) );
}
}
else
{
setNull();
}
if (!isString()) setType(VALUE_TYPE_STRING);
return this;
}
public Value startsWith(Value string)
{
return startsWith(string.getString());
}
public Value startsWith(String string)
{
if (isNull())
{
setType(VALUE_TYPE_BOOLEAN);
return this;
}
if (string==null)
{
setValue(false);
setNull();
return this;
}
setValue( getString().startsWith(string) );
return this;
}
// implement the SYSDATE function, arguments in args[]
public Value sysdate()
{
setValue( Calendar.getInstance().getTime() );
return this;
}
// implement the TAN function, arguments in args[]
public Value tan() throws KettleValueException
{
if (isNull()) return this;
if (isNumeric())
{
setValue( Math.tan(getNumber()) );
}
else
{
throw new KettleValueException("Function TAN only works on a number");
}
return this;
}
// implement the TO_CHAR function, arguments in args[]
// number: NUM2STR( 123.456 ) : default format
// number: NUM2STR( 123.456, '###,##0.000') : format
// number: NUM2STR( 123.456, '###,##0.000', '.') : grouping
// number: NUM2STR( 123.456, '###,##0.000', '.', ',') : decimal
// number: NUM2STR( 123.456, '###,##0.000', '.', ',', '?') : currency
public Value num2str() throws KettleValueException { return num2str(null, null, null, null); }
public Value num2str(String format) throws KettleValueException { return num2str(format, null, null, null); }
public Value num2str(String format, String decimalSymbol) throws KettleValueException { return num2str(format, decimalSymbol, null, null); }
public Value num2str(String format, String decimalSymbol, String groupingSymbol) throws KettleValueException { return num2str(format, decimalSymbol, groupingSymbol, null); }
public Value num2str(String format, String decimalSymbol, String groupingSymbol, String currencySymbol) throws KettleValueException
{
if (isNull())
{
setType(VALUE_TYPE_STRING);
}
else
{
// Number to String conversion...
if (getType()==VALUE_TYPE_NUMBER || getType()==VALUE_TYPE_INTEGER)
{
NumberFormat nf = NumberFormat.getInstance();
DecimalFormat df = (DecimalFormat)nf;
DecimalFormatSymbols dfs =new DecimalFormatSymbols();
if (currencySymbol!=null && currencySymbol.length()>0) dfs.setCurrencySymbol( currencySymbol );
if (groupingSymbol!=null && groupingSymbol.length()>0) dfs.setGroupingSeparator( groupingSymbol.charAt(0) );
if (decimalSymbol!=null && decimalSymbol.length()>0) dfs.setDecimalSeparator( decimalSymbol.charAt(0) );
df.setDecimalFormatSymbols(dfs); // in case of 4, 3 or 2
if (format!=null && format.length()>0) df.applyPattern(format);
try
{
setValue( nf.format(getNumber()) );
}
catch(Exception e)
{
setType(VALUE_TYPE_STRING);
setNull();
throw new KettleValueException("Couldn't convert Number to String "+e.toString());
}
}
else
{
throw new KettleValueException("Function NUM2STR only works on Numbers and Integers");
}
}
return this;
}
public Value dat2str() throws KettleValueException { return dat2str(null, null); }
public Value dat2str(String arg0) throws KettleValueException { return dat2str(arg0, null); }
public Value dat2str(String arg0, String arg1) throws KettleValueException
{
if (isNull())
{
setType(VALUE_TYPE_STRING);
}
else
{
if (getType()==VALUE_TYPE_DATE)
{
SimpleDateFormat df = new SimpleDateFormat();
DateFormatSymbols dfs = new DateFormatSymbols();
if (arg1!=null) dfs.setLocalPatternChars(arg1);
if (arg0!=null) df.applyPattern(arg0);
try
{
setValue( df.format(getDate()) );
}
catch(Exception e)
{
setType(VALUE_TYPE_STRING);
setNull();
throw new KettleValueException("TO_CHAR Couldn't convert Date to String "+e.toString());
}
}
else
{
throw new KettleValueException("Function DAT2STR only works on a date");
}
}
return this;
}
// implement the TO_DATE function, arguments in args[]
public Value num2dat() throws KettleValueException
{
if (isNull())
{
setType(VALUE_TYPE_DATE);
}
else
{
if (isNumeric())
{
value = new ValueDate();
value.setInteger(getInteger());
setType(VALUE_TYPE_DATE);
setLength(-1,-1);
}
else
{
throw new KettleValueException("Function NUM2DAT only works on a number");
}
}
return this;
}
public Value str2dat(String arg0) throws KettleValueException { return str2dat(arg0, null); }
public Value str2dat(String arg0, String arg1) throws KettleValueException
{
if (isNull())
{
setType(VALUE_TYPE_DATE);
}
else
{
// System.out.println("Convert string ["+string+"] to date using pattern '"+arg0+"'");
SimpleDateFormat df = new SimpleDateFormat();
DateFormatSymbols dfs = new DateFormatSymbols();
if (arg1!=null) dfs.setLocalPatternChars(arg1);
if (arg0!=null) df.applyPattern(arg0);
try
{
value.setDate( df.parse(getString()) );
setType(VALUE_TYPE_DATE);
setLength(-1,-1);
}
catch(Exception e)
{
setType(VALUE_TYPE_DATE);
setNull();
throw new KettleValueException("TO_DATE Couldn't convert String to Date"+e.toString());
}
}
return this;
}
// implement the TO_NUMBER function, arguments in args[]
public Value str2num() throws KettleValueException { return str2num(null, null, null, null); }
public Value str2num(String pattern) throws KettleValueException { return str2num(pattern, null, null, null); }
public Value str2num(String pattern, String decimal) throws KettleValueException { return str2num(pattern, decimal, null, null); }
public Value str2num(String pattern, String decimal, String grouping) throws KettleValueException { return str2num(pattern, decimal, grouping, null); }
public Value str2num(String pattern, String decimal, String grouping, String currency) throws KettleValueException
{
// 0 : pattern
// 1 : Decimal separator
// 2 : Grouping separator
// 3 : Currency symbol
if (isNull())
{
setType(VALUE_TYPE_STRING);
}
else
{
if (getType()==VALUE_TYPE_STRING)
{
if (getString()==null)
{
setNull();
setValue(0.0);
}
else
{
NumberFormat nf = NumberFormat.getInstance();
DecimalFormat df = (DecimalFormat)nf;
DecimalFormatSymbols dfs =new DecimalFormatSymbols();
if ( pattern !=null && pattern .length()>0 ) df.applyPattern( pattern );
if ( decimal !=null && decimal .length()>0 ) dfs.setDecimalSeparator( decimal.charAt(0) );
if ( grouping!=null && grouping.length()>0 ) dfs.setGroupingSeparator( grouping.charAt(0) );
if ( currency!=null && currency.length()>0 ) dfs.setCurrencySymbol( currency );
try
{
df.setDecimalFormatSymbols(dfs);
setValue( nf.parse(getString()).doubleValue() );
}
catch(Exception e)
{
String message = "Couldn't convert string to number "+e.toString();
if ( pattern !=null && pattern .length()>0 ) message+=" pattern="+pattern;
if ( decimal !=null && decimal .length()>0 ) message+=" decimal="+decimal;
if ( grouping!=null && grouping.length()>0 ) message+=" grouping="+grouping.charAt(0);
if ( currency!=null && currency.length()>0 ) message+=" currency="+currency;
throw new KettleValueException(message);
}
}
}
else
{
throw new KettleValueException("Function STR2NUM works only on strings");
}
}
return this;
}
public Value dat2num() throws KettleValueException
{
if (isNull())
{
setType(VALUE_TYPE_INTEGER);
return this;
}
if (getType()==VALUE_TYPE_DATE)
{
if (getString()==null)
{
setNull();
setValue(0L);
}
else
{
setValue(getInteger());
}
}
else
{
throw new KettleValueException("Function DAT2NUM works only on dates");
}
return this;
}
/**
* Performs a right and left trim of spaces in the string.
* If the value is not a string a conversion to String is performed first.
*
* @return The trimmed string value.
*/
public Value trim()
{
if (isNull())
{
setType(VALUE_TYPE_STRING);
return this;
}
String str = Const.trim(getString());
setValue(str);
return this;
}
// implement the UPPER function, arguments in args[]
public Value upper()
{
if (isNull())
{
setType(VALUE_TYPE_STRING);
return this;
}
setValue( getString().toUpperCase() );
return this;
}
// implement the E function, arguments in args[]
public Value e()
{
setValue(Math.E);
return this;
}
// implement the PI function, arguments in args[]
public Value pi()
{
setValue(Math.PI);
return this;
}
// implement the DECODE function, arguments in args[]
public Value v_decode(Value args[]) throws KettleValueException
{
int i;
boolean found;
// Decode takes as input the first argument...
// The next pair
// Limit to 3, 5, 7, 9, ... arguments
if (args.length>=3 && (args.length%2)==1)
{
i=0;
found=false;
while (i<args.length-1 && !found)
{
if (this.equals(args[i]))
{
setValue(args[i+1]);
found=true;
}
i+=2;
}
if (!found) setValue(args[args.length-1]);
}
else
{
// ERROR with nr of arguments
throw new KettleValueException("Function DECODE can't have "+args.length+" arguments!");
}
return this;
}
// implement the IF function, arguments in args[]
// IF( <condition>, <then value>, <else value>)
public Value v_if(Value args[]) throws KettleValueException
{
if (getType()==VALUE_TYPE_BOOLEAN)
{
if (args.length==1)
{
if (getBoolean()) setValue(args[0]); else setNull();
}
else
if (args.length==2)
{
if (getBoolean()) setValue(args[0]); else setValue(args[1]);
}
}
else
{
throw new KettleValueException("Function DECODE can't have "+args.length+" arguments!");
}
return this;
}
// implement the ADD_MONTHS function, one argument
public Value add_months(int months) throws KettleValueException
{
if (getType()==VALUE_TYPE_DATE)
{
if (!isNull() && getDate()!=null)
{
Calendar cal = Calendar.getInstance();
cal.setTime(getDate());
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
month+=months;
int newyear = year+(int)Math.floor(month/12);
int newmonth = month%12;
cal.set(newyear, newmonth, 1);
int newday = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
if (newday<day) cal.set(Calendar.DAY_OF_MONTH, newday);
else cal.set(Calendar.DAY_OF_MONTH, day);
setValue( cal.getTime() );
}
}
else
{
throw new KettleValueException("Function add_months only works on a date!");
}
return this;
}
/**
* Add a number of days to a Date value.
*
* @param days The number of days to add to the current date value
* @return The resulting value
* @throws KettleValueException
*/
public Value add_days(long days) throws KettleValueException
{
if (getType()==VALUE_TYPE_DATE)
{
if (!isNull() && getDate()!=null)
{
Calendar cal = Calendar.getInstance();
cal.setTime(getDate());
cal.add(Calendar.DAY_OF_YEAR, (int)days);
setValue( cal.getTime() );
}
}
else
{
throw new KettleValueException("Function add_days only works on a date!");
}
return this;
}
// implement the LAST_DAY function, arguments in args[]
public Value last_day() throws KettleValueException
{
if (getType()==VALUE_TYPE_DATE)
{
Calendar cal=Calendar.getInstance();
cal.setTime(getDate());
int last_day = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
cal.set(Calendar.DAY_OF_MONTH, last_day);
setValue( cal.getTime() );
}
else
{
throw new KettleValueException("Function last_day only works on a date");
}
return this;
}
public Value first_day() throws KettleValueException
{
if (getType()==VALUE_TYPE_DATE)
{
Calendar cal=Calendar.getInstance();
cal.setTime(getDate());
cal.set(Calendar.DAY_OF_MONTH, 1);
setValue( cal.getTime() );
}
else
{
throw new KettleValueException("Function first_day only works on a date");
}
return this;
}
// implement the TRUNC function, version without arguments
public Value trunc() throws KettleValueException
{
if (isNull()) return this; // don't do anything, leave it at NULL!
if (isBigNumber())
{
getBigNumber().setScale(0, BigDecimal.ROUND_FLOOR);
}
else
if (isNumber())
{
setValue( Math.floor(getNumber()) );
}
else
if (isInteger())
{
// Nothing
}
else
if (isDate())
{
Calendar cal=Calendar.getInstance();
cal.setTime(getDate());
cal.set(Calendar.MILLISECOND, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.HOUR_OF_DAY, 0);
setValue( cal.getTime() );
}
else
{
throw new KettleValueException("Function TRUNC only works on numbers and dates");
}
return this;
}
// implement the TRUNC function, arguments in args[]
public Value trunc(double level) throws KettleValueException { return trunc((int)level); }
public Value trunc(int level) throws KettleValueException
{
if (isNull()) return this; // don't do anything, leave it at NULL!
if (isBigNumber())
{
getBigNumber().setScale(level, BigDecimal.ROUND_FLOOR);
}
else
if (isNumber())
{
double pow=Math.pow(10, level);
setValue( Math.floor( getNumber() * pow ) / pow );
}
else
if (isInteger())
{
// Nothing!
}
else
if (isDate())
{
Calendar cal=Calendar.getInstance();
cal.setTime(getDate());
switch((int)level)
{
// MONTHS
case 5: cal.set(Calendar.MONTH, 1);
// DAYS
case 4: cal.set(Calendar.DAY_OF_MONTH, 1);
// HOURS
case 3: cal.set(Calendar.HOUR_OF_DAY, 0);
// MINUTES
case 2: cal.set(Calendar.MINUTE, 0);
// SECONDS
case 1: cal.set(Calendar.SECOND, 0); break;
default:
throw new KettleValueException("Argument of TRUNC of date has to be between 1 and 5");
}
}
else
{
throw new KettleValueException("Function TRUNC only works with numbers and dates");
}
return this;
}
/* Some javascript extensions...
*
*/
public static final Value getInstance() { return new Value(); }
public String getClassName() { return "Value"; }
public void jsConstructor()
{
}
public void jsConstructor(String name)
{
setName(name);
}
public void jsConstructor(String name, String value)
{
setName(name);
setValue(value);
}
/**
* Produce the XML representation of this value.
* @return a String containing the XML to represent this Value.
*/
public String getXML()
{
StringBuffer retval = new StringBuffer(128);
retval.append(XMLHandler.addTagValue("name", getName(), false));
retval.append(XMLHandler.addTagValue("type", getTypeDesc(), false));
retval.append(XMLHandler.addTagValue("text", toString(false), false));
retval.append(XMLHandler.addTagValue("length", getLength(), false));
retval.append(XMLHandler.addTagValue("precision", getPrecision(), false));
retval.append(XMLHandler.addTagValue("isnull", isNull(), false));
return retval.toString();
}
/**
* Construct a new Value and read the data from XML
* @param valnode The XML Node to read from.
*/
public Value(Node valnode)
{
this();
loadXML(valnode);
}
/**
* Read the data for this Value from an XML Node
* @param valnode The XML Node to read from
* @return true if all went well, false if something went wrong.
*/
public boolean loadXML(Node valnode)
{
try
{
String valname = XMLHandler.getTagValue(valnode, "name");
int valtype = getType( XMLHandler.getTagValue(valnode, "type") );
String text = XMLHandler.getTagValue(valnode, "text");
boolean isnull = "Y".equalsIgnoreCase(XMLHandler.getTagValue(valnode, "isnull"));
int len = Const.toInt(XMLHandler.getTagValue(valnode, "length"), -1);
int prec = Const.toInt(XMLHandler.getTagValue(valnode, "precision"), -1);
setName(valname);
setValue(text);
setLength(len, prec);
if (valtype!=VALUE_TYPE_STRING)
{
trim();
convertString(valtype);
}
if (isnull) setNull();
}
catch(Exception e)
{
setNull();
return false;
}
return true;
}
/**
* Convert this Value from type String to another type
* @param newtype The Value type to convert to.
*/
public void convertString(int newtype) throws KettleValueException
{
switch(newtype)
{
case VALUE_TYPE_STRING : break;
case VALUE_TYPE_NUMBER : setValue( getNumber() ); break;
case VALUE_TYPE_DATE : setValue( getDate() ); break;
case VALUE_TYPE_BOOLEAN : setValue( getBoolean() ); break;
case VALUE_TYPE_INTEGER : setValue( getInteger() ); break;
case VALUE_TYPE_BIGNUMBER : setValue( getBigNumber() ); break;
default:
throw new KettleValueException("Please specify the type to convert to from String type.");
}
}
public Value(Repository rep, long id_value)
throws KettleException
{
try
{
Row r = rep.getValue(id_value);
if (r!=null)
{
name = r.getString("NAME", null);
String valstr = r.getString("VALUE_STR", null);
setValue( valstr );
int valtype = getType( r.getString("VALUE_TYPE", null) );
setType(valtype);
setNull( r.getBoolean("IS_NULL", false) );
}
}
catch(KettleDatabaseException dbe)
{
throw new KettleException("Unable to load Value from repository with id_value="+id_value, dbe);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.