diff
stringlengths 262
553k
| is_single_chunk
bool 2
classes | is_single_function
bool 1
class | buggy_function
stringlengths 20
391k
| fixed_function
stringlengths 0
392k
|
---|---|---|---|---|
diff --git a/src/org/gavrog/joss/tilings/FaceList.java b/src/org/gavrog/joss/tilings/FaceList.java
index 0e16558..18944e3 100644
--- a/src/org/gavrog/joss/tilings/FaceList.java
+++ b/src/org/gavrog/joss/tilings/FaceList.java
@@ -1,618 +1,618 @@
/*
Copyright 2012 Olaf Delgado-Friedrichs
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.gavrog.joss.tilings;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.gavrog.box.collections.Pair;
import org.gavrog.jane.compounds.Matrix;
import org.gavrog.jane.numbers.Real;
import org.gavrog.joss.dsyms.basic.DSymbol;
import org.gavrog.joss.dsyms.basic.DelaneySymbol;
import org.gavrog.joss.dsyms.basic.DynamicDSymbol;
import org.gavrog.joss.dsyms.basic.IndexList;
import org.gavrog.joss.dsyms.derived.DSCover;
import org.gavrog.joss.geometry.Point;
import org.gavrog.joss.geometry.Vector;
import org.gavrog.joss.pgraphs.basic.INode;
import org.gavrog.joss.pgraphs.io.GenericParser;
import org.gavrog.joss.pgraphs.io.NetParser;
import org.gavrog.joss.pgraphs.io.NetParser.Face;
/**
* Implements a periodic face set meant to define a tiling.
*
* TODO Remove ? and Object as type parameters.
*/
public class FaceList {
final private static boolean DEBUG = false;
/**
* Hashable class for edges in the tiling to be constructed.
*/
private static class Edge implements Comparable<Edge> {
final public int source;
final public int target;
final public Vector shift;
public Edge(final int source, final int target, final Vector shift) {
if (source < target || (source == target && shift.isNonNegative())) {
this.source = source;
this.target = target;
this.shift = shift;
} else {
this.source = target;
this.target = source;
this.shift = (Vector) shift.negative();
}
}
public int hashCode() {
return ((source * 37) + target * 127) + shift.hashCode();
}
public boolean equals(final Object other) {
final Edge e = (Edge) other;
return source == e.source && target == e.target
&& shift.equals(e.shift);
}
public int compareTo(final Edge other) {
if (this.source != other.source) {
return this.source - other.source;
}
if (this.target != other.target) {
return this.target - other.target;
}
return this.shift.compareTo(other.shift);
}
public String toString() {
return "(" + source + "," + target + "," + shift + ")";
}
}
private static class Incidence implements Comparable<Incidence> {
final public int faceIndex;
final public int edgeIndex;
final public boolean reverse;
final public double angle;
public Incidence(
final int faceIndex, final int edgeIndex, final boolean rev,
final double angle) {
this.faceIndex = faceIndex;
this.edgeIndex = edgeIndex;
this.reverse = rev;
this.angle = angle;
}
public Incidence(
final int faceIndex, final int edgeIndex, final boolean rev) {
this(faceIndex, edgeIndex, rev, 0.0);
}
public Incidence(final Incidence source, final double angle) {
this(source.faceIndex, source.edgeIndex, source.reverse, angle);
}
public int compareTo(final Incidence other) {
if (this.angle < other.angle) {
return -1;
} else if (this.angle > other.angle) {
return 1;
}
if (this.faceIndex != other.faceIndex) {
return this.faceIndex - other.faceIndex;
}
if (this.edgeIndex != other.edgeIndex) {
return this.edgeIndex - other.edgeIndex;
}
if (!this.reverse && other.reverse) {
return -1;
} else if (this.reverse && !other.reverse) {
return 1;
} else {
return 0;
}
}
public String toString() {
return "(" + faceIndex + "," + edgeIndex + "," + reverse + ","
+ angle + ")";
}
}
final private List<Face> faces;
final private List<List<Pair<Face, Vector>>> tiles;
final private Map<Face, List<Pair<Integer, Vector>>> tilesAtFace;
final private Map<Integer, Point> indexToPos;
final private int dim;
final private DSymbol ds;
final private DSCover<Integer> cover;
final private Map<Integer, Point> positions;
public FaceList(
final List<Object> input,
final Map<Integer, Point> indexToPosition)
{
if (DEBUG) {
System.err.println("\nStarting FaceList constructor");
}
if (input == null || input.size() < 1) {
throw new IllegalArgumentException("no data given");
}
if (input.get(0) instanceof List) {
this.tiles = new ArrayList<List<Pair<Face, Vector>>>();
this.tilesAtFace = new HashMap<Face, List<Pair<Integer, Vector>>>();
for (int i = 0; i < input.size(); ++i) {
@SuppressWarnings("unchecked")
final List<Pair<Face, Vector>> tile =
(List<Pair<Face, Vector>>) input.get(i);
final List<Pair<Face, Vector>> newTile =
new ArrayList<Pair<Face, Vector>>();
for (final Pair<Face, Vector> entry: tile) {
final Face face = entry.getFirst();
final Pair<Face, Vector> normal =
NetParser.normalizedFace(face);
final Vector shift =
(Vector) entry.getSecond().plus(normal.getSecond());
if (!this.tilesAtFace.containsKey(face)) {
this.tilesAtFace.put(face,
new ArrayList<Pair<Integer, Vector>>());
}
this.tilesAtFace.get(face).add(
new Pair<Integer, Vector>(i, shift));
newTile.add(new Pair<Face, Vector>(face, shift));
}
this.tiles.add(newTile);
}
// --- make sure each face is in exactly two tiles
for (final List<Pair<Integer, Vector>> tlist:
this.tilesAtFace.values())
{
final int n = tlist.size();
if (n != 2) {
throw new IllegalArgumentException("Face incident to " + n
+ " tile" + (n == 1 ? "" : "s") + ".");
}
}
this.faces = new ArrayList<Face>();
this.faces.addAll(this.tilesAtFace.keySet());
} else {
this.tiles = null;
this.tilesAtFace = null;
this.faces = new ArrayList<Face>();
for (final Object x: input)
this.faces.add((Face) x);
}
final Face f0 = this.faces.get(0);
if (f0.size() < 3) {
throw new IllegalArgumentException("minimal face-size is 3");
}
this.dim = f0.shift(0).getDimension();
if (this.dim != 3) {
throw new UnsupportedOperationException("dimension must be 3");
}
this.indexToPos = indexToPosition;
// --- initialize the intermediate symbol
final Map<Face, List<Integer>> faceElements =
new HashMap<Face, List<Integer>>();
final DynamicDSymbol ds = new DynamicDSymbol(this.dim);
for (final Face f: this.faces) {
final int n = f.size();
final int _2n = 2 * n;
final List<Integer> elms = ds.grow(4 * n);
faceElements.put(f, elms);
for (int i = 0; i < 4 * n; i += 2) {
ds.redefineOp(0, elms.get(i), elms.get(i + 1));
}
for (int i = 1; i < _2n; i += 2) {
final int i1 = (i + 1) % _2n;
ds.redefineOp(1, elms.get(i), elms.get(i1));
ds.redefineOp(1, elms.get(i + _2n), elms.get(i1 + _2n));
}
for (int i = 0; i < _2n; ++i) {
ds.redefineOp(3, elms.get(i), elms.get(i + _2n));
}
}
if (DEBUG) {
System.err.println("Symbol without 2-ops: " + new DSymbol(ds));
}
if (this.tiles == null) {
set2opPlainMode(ds, faceElements);
} else {
set2opTileMode(ds, faceElements);
}
if (DEBUG) {
System.err.println("Symbol with 2-ops: " + new DSymbol(ds));
}
// --- set all v values to 1
for (int i = 0; i < dim; ++i) {
for (final int D: ds.elements()) {
if (!ds.definesV(i, i + 1, D)) {
ds.redefineV(i, i + 1, D, 1);
}
}
}
if (DEBUG) {
System.err.println("Completed symbol: " + new DSymbol(ds));
}
// --- do some checks
assertCompleteness(ds);
if (!ds.isConnected()) {
throw new RuntimeException("Built non-connected symbol.");
} else if (!ds.isLocallyEuclidean3D()) {
throw new RuntimeException("Built non-manifold symbol.");
} else if (!ds.isLocallyEuclidean3D()) {
throw new RuntimeException("Built non-manifold symbol.");
}
// --- freeze the symbol, make a tiling object, and extract the cover
this.ds = new DSymbol(ds);
final Tiling tiling = new Tiling(this.ds);
this.cover = tiling.getCover();
// --- map skeleton nodes for the tiling to appropriate positions
final Tiling.Skeleton skel = tiling.getSkeleton();
this.positions = new HashMap<Integer, Point>();
for (final Face f: this.faces)
{
final int n = f.size();
final List<Integer> chambers = faceElements.get(f);
- for (int i = 0; i < 2 * n; ++i)
+ for (int i = 0; i < 4 * n; ++i)
{
- final int k = (i + 1) / 2 % n;
+ final int k = (i % (2 * n) + 1) / 2 % n;
final int D = chambers.get(i);
assert(this.cover.image(D) == D);
final INode v = skel.nodeForChamber(D);
if (D == skel.chamberAtNode(v))
{
final Point p = indexToPosition.get(f.vertex(k));
final Vector s = f.shift(k);
final Vector t = tiling.cornerShift(0, D);
this.positions.put(D, (Point) p.plus(s).minus(t));
}
}
}
}
private FaceList(final Pair<List<Object>, Map<Integer, Point>> p) {
this(p.getFirst(), p.getSecond());
}
public FaceList(final GenericParser.Block data) {
this(NetParser.parseFaceList(data));
}
/**
* Computes normals for the sectors of a face.
*
* @param f the input face.
* @param indexToPos maps symbolic corners to positions.
* @return the array of sector normals.
*/
private static Vector[] sectorNormals(
final Face f,
final Map<Integer, Point> indexToPos)
{
final int n = f.size();
if (DEBUG) {
System.err.println("Computing normals for face " + f);
}
// --- compute corners and center of this face
Matrix sum = null;
final Point corners[] = new Point[n];
for (int i = 0; i < n; ++i) {
final int v = f.vertex(i);
final Vector s = f.shift(i);
final Point p = (Point) s.plus(indexToPos.get(v));
corners[i] = p;
if (sum == null) {
sum = p.getCoordinates();
} else {
sum = (Matrix) sum.plus(p.getCoordinates());
}
}
final Point center = new Point((Matrix) sum.dividedBy(n));
// --- use that to compute the normals
final Vector normals[] = new Vector[n];
for (int i = 0; i < n; ++i) {
final int i1 = (i + 1) % n;
final Vector a = (Vector) corners[i].minus(center);
final Vector b = (Vector) corners[i1].minus(corners[i]);
normals[i] = Vector.unit(Vector.crossProduct3D(a, b));
if (DEBUG) {
System.err.println(" " + normals[i]);
}
}
return normals;
}
private static Map<?, List<Incidence>> collectEdges(
final List<?> faces,
final boolean useShifts)
{
final Map<Object, List<Incidence>> facesAtEdge =
new HashMap<Object, List<Incidence>>();
for (int i = 0; i < faces.size(); ++i) {
final Face f;
final Vector fShift;
if (useShifts) {
@SuppressWarnings("unchecked")
final Pair<Face, Vector> entry =
(Pair<Face, Vector>) faces.get(i);
f = entry.getFirst();
fShift = entry.getSecond();
} else {
f = (Face) faces.get(i);
fShift = null;
}
final int n = f.size();
for (int j = 0; j < n; ++j) {
final int j1 = (j + 1) % n;
final int v = f.vertex(j);
final int w = f.vertex(j1);
final Vector s = (Vector) f.shift(j1).minus(f.shift(j));
final Edge e = new Edge(v, w, s);
final boolean rev = (e.source != v || !e.shift.equals(s));
final Object key;
if (useShifts) {
final Vector vShift = rev ? f.shift(j1) : f.shift(j);
key = new Pair<Edge, Vector>(e,
(Vector) fShift.plus(vShift));
} else {
key = e;
}
if (!facesAtEdge.containsKey(key)) {
facesAtEdge.put(key, new ArrayList<Incidence>());
}
facesAtEdge.get(key).add(new Incidence(i, j, rev));
}
}
if (DEBUG) {
System.err.println("Edge to incident faces mapping:");
final List<Object> edges = new ArrayList<Object>();
edges.addAll(facesAtEdge.keySet());
Collections.sort(edges, new Comparator<Object>() {
public int compare(final Object arg0, final Object arg1) {
if (useShifts) {
@SuppressWarnings("unchecked")
final Pair<Edge, Vector> p0 = (Pair<Edge, Vector>) arg0;
@SuppressWarnings("unchecked")
final Pair<Edge, Vector> p1 = (Pair<Edge, Vector>) arg1;
if (p0.getFirst().equals(p1.getFirst()))
return p0.getSecond().compareTo(p1.getSecond());
else
return p0.getFirst().compareTo(p1.getFirst());
} else
return ((Edge) arg0).compareTo((Edge) arg1);
}});
for (final Object e: edges) {
final List<Incidence> inc = facesAtEdge.get(e);
System.err.println(" " + inc.size() + " at edge " + e + ":");
for (int i = 0; i < inc.size(); ++i) {
System.err.println(" " + inc.get(i));
}
}
}
return facesAtEdge;
}
private void set2opPlainMode(
final DynamicDSymbol ds,
final Map<Face, List<Integer>> faceElms)
{
// --- determine sector normals for each face
final Map<Face, Vector[]> normals = new HashMap<Face, Vector[]>();
for (final Face f: this.faces) {
normals.put(f, sectorNormals(f, this.indexToPos));
}
// --- set 2 operator according to cyclic orders of faces around edges
final Map<?, List<Incidence>> facesAtEdge =
collectEdges(this.faces, false);
for (final Object obj: facesAtEdge.keySet()) {
final Edge e = (Edge) obj;
final Point p = this.indexToPos.get(e.source);
final Point q = this.indexToPos.get(e.target);
final Vector a = Vector.unit((Vector) q.plus(e.shift).minus(p));
// --- augment all incidences at this edge with their angles
final List<Incidence> incidences = facesAtEdge.get(e);
Vector n0 = null;
for (int i = 0; i < incidences.size(); ++i) {
final Incidence inc = incidences.get(i);
Vector normal =
(normals.get(faces.get(inc.faceIndex)))[inc.edgeIndex];
if (inc.reverse) {
normal = (Vector) normal.negative();
}
double angle;
if (i == 0) {
n0 = normal;
angle = 0.0;
} else {
double x = ((Real) Vector.dot(n0, normal)).doubleValue();
x = Math.max(Math.min(x, 1.0), -1.0);
angle = Math.acos(x);
if (Vector.volume3D(a, n0, normal).isNegative()) {
angle = 2 * Math.PI - angle;
}
}
incidences.set(i, new Incidence(inc, angle));
}
if (DEBUG) {
System.err.println("Augmented incidences at edge " + e + ":");
for (int i = 0; i < incidences.size(); ++i) {
System.err.println(" " + incidences.get(i));
}
}
// --- sort by angle
Collections.sort(incidences);
// --- top off with a copy of the first incidences
final Incidence inc = incidences.get(0);
incidences.add(new Incidence(inc, inc.angle + 2 * Math.PI));
if (DEBUG) {
System.err.println("Sorted incidences at edge " + e + ":");
for (int i = 0; i < incidences.size(); ++i) {
System.err.println(" " + incidences.get(i));
}
}
// --- now set all the connections around this edge
for (int i = 0; i < incidences.size() - 1; ++i) {
final Incidence inc1 = incidences.get(i);
final Incidence inc2 = incidences.get(i + 1);
if (inc2.angle - inc1.angle < 1e-3) {
throw new RuntimeException("tiny dihedral angle");
}
final List<Integer> elms1 =
faceElms.get(faces.get(inc1.faceIndex));
final List<Integer> elms2 =
faceElms.get(faces.get(inc2.faceIndex));
final int A, B, C, D;
if (inc1.reverse) {
final int k =
2 * (inc1.edgeIndex + faces.get(inc1.faceIndex).size());
A = elms1.get(k + 1);
B = elms1.get(k);
} else {
final int k = 2 * inc1.edgeIndex;
A = elms1.get(k);
B = elms1.get(k + 1);
}
if (inc2.reverse) {
final int k = 2 * inc2.edgeIndex;
C = elms2.get(k + 1);
D = elms2.get(k);
} else {
final int k =
2 * (inc2.edgeIndex + faces.get(inc2.faceIndex).size());
C = elms2.get(k);
D = elms2.get(k + 1);
}
ds.redefineOp(2, A, C);
ds.redefineOp(2, B, D);
}
}
}
private void set2opTileMode(
final DynamicDSymbol ds,
final Map<Face, List<Integer>> faceElms)
{
for (int i = 0; i < this.tiles.size(); ++i) {
final List<Pair<Face, Vector>> tile = this.tiles.get(i);
final Map<?, List<Incidence>> facesAtEdge =
collectEdges(tile, true);
for (final List<Incidence> flist: facesAtEdge.values()) {
if (flist.size() != 2) {
final String msg = flist.size() + " faces at an edge";
throw new UnsupportedOperationException(msg);
}
final int D[] = new int[2];
final int E[] = new int[2];
boolean reverse = false;
for (int k = 0; k <= 1; ++k) {
final Incidence inc = flist.get(k);
final Pair<Face, Vector> p = tile.get(inc.faceIndex);
final Face face = p.getFirst();
final Vector shift = p.getSecond();
final List<Pair<Integer, Vector>> taf =
this.tilesAtFace.get(face);
final int t =
taf.indexOf(new Pair<Integer, Vector>(i, shift));
final int x = 2 * (t * face.size() + inc.edgeIndex);
D[k] = faceElms.get(face).get(x);
E[k] = faceElms.get(face).get(x + 1);
if (inc.reverse) {
reverse = !reverse;
}
}
if (reverse) {
ds.redefineOp(2, D[0], E[1]);
ds.redefineOp(2, D[1], E[0]);
} else {
ds.redefineOp(2, D[0], D[1]);
ds.redefineOp(2, E[0], E[1]);
}
}
}
}
private void assertCompleteness(final DelaneySymbol<Integer> ds)
{
final IndexList idcs = new IndexList(ds);
for (final int D: ds.elements()) {
for (int i = 0; i < idcs.size()-1; ++i) {
final int ii = idcs.get(i);
if (!ds.definesOp(ii, D)) {
throw new AssertionError(
"op(" + ii + ", " + D + ") undefined");
}
for (int j = i+1; j < idcs.size(); ++j) {
final int jj = idcs.get(j);
if (!ds.definesV(ii, jj, D)) {
throw new AssertionError(
"v(" + ii + ", " + jj + ", " + D +
") undefined");
}
}
}
}
}
public DSymbol getSymbol() {
return ds;
}
public DSCover<Integer> getCover() {
return cover;
}
public Map<Integer, Point> getPositions() {
return positions;
}
}
| false | true | public FaceList(
final List<Object> input,
final Map<Integer, Point> indexToPosition)
{
if (DEBUG) {
System.err.println("\nStarting FaceList constructor");
}
if (input == null || input.size() < 1) {
throw new IllegalArgumentException("no data given");
}
if (input.get(0) instanceof List) {
this.tiles = new ArrayList<List<Pair<Face, Vector>>>();
this.tilesAtFace = new HashMap<Face, List<Pair<Integer, Vector>>>();
for (int i = 0; i < input.size(); ++i) {
@SuppressWarnings("unchecked")
final List<Pair<Face, Vector>> tile =
(List<Pair<Face, Vector>>) input.get(i);
final List<Pair<Face, Vector>> newTile =
new ArrayList<Pair<Face, Vector>>();
for (final Pair<Face, Vector> entry: tile) {
final Face face = entry.getFirst();
final Pair<Face, Vector> normal =
NetParser.normalizedFace(face);
final Vector shift =
(Vector) entry.getSecond().plus(normal.getSecond());
if (!this.tilesAtFace.containsKey(face)) {
this.tilesAtFace.put(face,
new ArrayList<Pair<Integer, Vector>>());
}
this.tilesAtFace.get(face).add(
new Pair<Integer, Vector>(i, shift));
newTile.add(new Pair<Face, Vector>(face, shift));
}
this.tiles.add(newTile);
}
// --- make sure each face is in exactly two tiles
for (final List<Pair<Integer, Vector>> tlist:
this.tilesAtFace.values())
{
final int n = tlist.size();
if (n != 2) {
throw new IllegalArgumentException("Face incident to " + n
+ " tile" + (n == 1 ? "" : "s") + ".");
}
}
this.faces = new ArrayList<Face>();
this.faces.addAll(this.tilesAtFace.keySet());
} else {
this.tiles = null;
this.tilesAtFace = null;
this.faces = new ArrayList<Face>();
for (final Object x: input)
this.faces.add((Face) x);
}
final Face f0 = this.faces.get(0);
if (f0.size() < 3) {
throw new IllegalArgumentException("minimal face-size is 3");
}
this.dim = f0.shift(0).getDimension();
if (this.dim != 3) {
throw new UnsupportedOperationException("dimension must be 3");
}
this.indexToPos = indexToPosition;
// --- initialize the intermediate symbol
final Map<Face, List<Integer>> faceElements =
new HashMap<Face, List<Integer>>();
final DynamicDSymbol ds = new DynamicDSymbol(this.dim);
for (final Face f: this.faces) {
final int n = f.size();
final int _2n = 2 * n;
final List<Integer> elms = ds.grow(4 * n);
faceElements.put(f, elms);
for (int i = 0; i < 4 * n; i += 2) {
ds.redefineOp(0, elms.get(i), elms.get(i + 1));
}
for (int i = 1; i < _2n; i += 2) {
final int i1 = (i + 1) % _2n;
ds.redefineOp(1, elms.get(i), elms.get(i1));
ds.redefineOp(1, elms.get(i + _2n), elms.get(i1 + _2n));
}
for (int i = 0; i < _2n; ++i) {
ds.redefineOp(3, elms.get(i), elms.get(i + _2n));
}
}
if (DEBUG) {
System.err.println("Symbol without 2-ops: " + new DSymbol(ds));
}
if (this.tiles == null) {
set2opPlainMode(ds, faceElements);
} else {
set2opTileMode(ds, faceElements);
}
if (DEBUG) {
System.err.println("Symbol with 2-ops: " + new DSymbol(ds));
}
// --- set all v values to 1
for (int i = 0; i < dim; ++i) {
for (final int D: ds.elements()) {
if (!ds.definesV(i, i + 1, D)) {
ds.redefineV(i, i + 1, D, 1);
}
}
}
if (DEBUG) {
System.err.println("Completed symbol: " + new DSymbol(ds));
}
// --- do some checks
assertCompleteness(ds);
if (!ds.isConnected()) {
throw new RuntimeException("Built non-connected symbol.");
} else if (!ds.isLocallyEuclidean3D()) {
throw new RuntimeException("Built non-manifold symbol.");
} else if (!ds.isLocallyEuclidean3D()) {
throw new RuntimeException("Built non-manifold symbol.");
}
// --- freeze the symbol, make a tiling object, and extract the cover
this.ds = new DSymbol(ds);
final Tiling tiling = new Tiling(this.ds);
this.cover = tiling.getCover();
// --- map skeleton nodes for the tiling to appropriate positions
final Tiling.Skeleton skel = tiling.getSkeleton();
this.positions = new HashMap<Integer, Point>();
for (final Face f: this.faces)
{
final int n = f.size();
final List<Integer> chambers = faceElements.get(f);
for (int i = 0; i < 2 * n; ++i)
{
final int k = (i + 1) / 2 % n;
final int D = chambers.get(i);
assert(this.cover.image(D) == D);
final INode v = skel.nodeForChamber(D);
if (D == skel.chamberAtNode(v))
{
final Point p = indexToPosition.get(f.vertex(k));
final Vector s = f.shift(k);
final Vector t = tiling.cornerShift(0, D);
this.positions.put(D, (Point) p.plus(s).minus(t));
}
}
}
}
| public FaceList(
final List<Object> input,
final Map<Integer, Point> indexToPosition)
{
if (DEBUG) {
System.err.println("\nStarting FaceList constructor");
}
if (input == null || input.size() < 1) {
throw new IllegalArgumentException("no data given");
}
if (input.get(0) instanceof List) {
this.tiles = new ArrayList<List<Pair<Face, Vector>>>();
this.tilesAtFace = new HashMap<Face, List<Pair<Integer, Vector>>>();
for (int i = 0; i < input.size(); ++i) {
@SuppressWarnings("unchecked")
final List<Pair<Face, Vector>> tile =
(List<Pair<Face, Vector>>) input.get(i);
final List<Pair<Face, Vector>> newTile =
new ArrayList<Pair<Face, Vector>>();
for (final Pair<Face, Vector> entry: tile) {
final Face face = entry.getFirst();
final Pair<Face, Vector> normal =
NetParser.normalizedFace(face);
final Vector shift =
(Vector) entry.getSecond().plus(normal.getSecond());
if (!this.tilesAtFace.containsKey(face)) {
this.tilesAtFace.put(face,
new ArrayList<Pair<Integer, Vector>>());
}
this.tilesAtFace.get(face).add(
new Pair<Integer, Vector>(i, shift));
newTile.add(new Pair<Face, Vector>(face, shift));
}
this.tiles.add(newTile);
}
// --- make sure each face is in exactly two tiles
for (final List<Pair<Integer, Vector>> tlist:
this.tilesAtFace.values())
{
final int n = tlist.size();
if (n != 2) {
throw new IllegalArgumentException("Face incident to " + n
+ " tile" + (n == 1 ? "" : "s") + ".");
}
}
this.faces = new ArrayList<Face>();
this.faces.addAll(this.tilesAtFace.keySet());
} else {
this.tiles = null;
this.tilesAtFace = null;
this.faces = new ArrayList<Face>();
for (final Object x: input)
this.faces.add((Face) x);
}
final Face f0 = this.faces.get(0);
if (f0.size() < 3) {
throw new IllegalArgumentException("minimal face-size is 3");
}
this.dim = f0.shift(0).getDimension();
if (this.dim != 3) {
throw new UnsupportedOperationException("dimension must be 3");
}
this.indexToPos = indexToPosition;
// --- initialize the intermediate symbol
final Map<Face, List<Integer>> faceElements =
new HashMap<Face, List<Integer>>();
final DynamicDSymbol ds = new DynamicDSymbol(this.dim);
for (final Face f: this.faces) {
final int n = f.size();
final int _2n = 2 * n;
final List<Integer> elms = ds.grow(4 * n);
faceElements.put(f, elms);
for (int i = 0; i < 4 * n; i += 2) {
ds.redefineOp(0, elms.get(i), elms.get(i + 1));
}
for (int i = 1; i < _2n; i += 2) {
final int i1 = (i + 1) % _2n;
ds.redefineOp(1, elms.get(i), elms.get(i1));
ds.redefineOp(1, elms.get(i + _2n), elms.get(i1 + _2n));
}
for (int i = 0; i < _2n; ++i) {
ds.redefineOp(3, elms.get(i), elms.get(i + _2n));
}
}
if (DEBUG) {
System.err.println("Symbol without 2-ops: " + new DSymbol(ds));
}
if (this.tiles == null) {
set2opPlainMode(ds, faceElements);
} else {
set2opTileMode(ds, faceElements);
}
if (DEBUG) {
System.err.println("Symbol with 2-ops: " + new DSymbol(ds));
}
// --- set all v values to 1
for (int i = 0; i < dim; ++i) {
for (final int D: ds.elements()) {
if (!ds.definesV(i, i + 1, D)) {
ds.redefineV(i, i + 1, D, 1);
}
}
}
if (DEBUG) {
System.err.println("Completed symbol: " + new DSymbol(ds));
}
// --- do some checks
assertCompleteness(ds);
if (!ds.isConnected()) {
throw new RuntimeException("Built non-connected symbol.");
} else if (!ds.isLocallyEuclidean3D()) {
throw new RuntimeException("Built non-manifold symbol.");
} else if (!ds.isLocallyEuclidean3D()) {
throw new RuntimeException("Built non-manifold symbol.");
}
// --- freeze the symbol, make a tiling object, and extract the cover
this.ds = new DSymbol(ds);
final Tiling tiling = new Tiling(this.ds);
this.cover = tiling.getCover();
// --- map skeleton nodes for the tiling to appropriate positions
final Tiling.Skeleton skel = tiling.getSkeleton();
this.positions = new HashMap<Integer, Point>();
for (final Face f: this.faces)
{
final int n = f.size();
final List<Integer> chambers = faceElements.get(f);
for (int i = 0; i < 4 * n; ++i)
{
final int k = (i % (2 * n) + 1) / 2 % n;
final int D = chambers.get(i);
assert(this.cover.image(D) == D);
final INode v = skel.nodeForChamber(D);
if (D == skel.chamberAtNode(v))
{
final Point p = indexToPosition.get(f.vertex(k));
final Vector s = f.shift(k);
final Vector t = tiling.cornerShift(0, D);
this.positions.put(D, (Point) p.plus(s).minus(t));
}
}
}
}
|
diff --git a/Source/summative2013/lifeform/Animal.java b/Source/summative2013/lifeform/Animal.java
index c1757a3..9dd189f 100644
--- a/Source/summative2013/lifeform/Animal.java
+++ b/Source/summative2013/lifeform/Animal.java
@@ -1,476 +1,476 @@
package summative2013.lifeform;
import java.awt.Point;
import java.util.ArrayList;
import summative2013.Summative;
import summative2013.Summative.TERRAIN;
import static summative2013.lifeform.Lifeform.summative;
import summative2013.memory.Memory;
import summative2013.phenomena.Weather.WEATHER;
import java.util.LinkedList;
/**
* Parent class of all animal moving lifeform living creatures
*
* @author 322303413
*/
public abstract class Animal extends Lifeform {
/**
* Stores hunger level, from 0-99
*/
protected int hunger;
/**
* @return the inGroup
*/
/*public LinkedList<Animal> getInGroup() {
return inGroup;
}*/
/**
* @return the outGroup
*/
/*public LinkedList<Animal> getOutGroup() {
return outGroup;
}*/
/**
* Creates the gender enum thing
*/
public enum GENDER {
MALE, FEMALE
};
/**
* Some kind of direction variable
*/
public enum DIRECTION {
NORTH, SOUTH, EAST, WEST, CENTER
};
/**
* Stores gender
*/
protected GENDER gender;
/**
* Store the friends happy no fighting membership club
*/
//protected LinkedList inGroup;
/**
* Stores the angry enemies murder hatred villain gang
*/
//protected LinkedList outGroup;
/**
* Stores the location the animal is currently moving to
*/
protected Point destination;
/**
* Stores how messed up that animal losing its mind crazies asylum bar level
*/
protected int depravity;
/**
* Stores nearest prey
*/
protected Point food;
/**
* stores the nearest mate
*/
protected Point mate;
/**
* The closest potential victim
*/
protected Point murder;
/**
* Stores past memories and regrets and nostalgic moments in the sun of
* childhood glorious
*/
protected ArrayList<Memory> knowledge;
/**
* Stores eating food delicious untermensch inferior prey animals
*/
protected ArrayList<Class> preyList;
/**
* Works at night
*/
protected boolean nocturnal;
/**
* Constructor
*/
public Animal() {
super();
setDestination();
hunger = 50;
gender = Math.random() < 0.5 ? GENDER.MALE : GENDER.FEMALE;
depravity = 0;
preyList = new ArrayList<>();
}
/**
* Finds the closest prey
*/
public void findFood(ArrayList<Lifeform> list) {
ArrayList<Point> foodList = new ArrayList<>();
food = null;
for (Lifeform l : list) {
for (Class m : preyList) {
if (l.getClass().equals(m)) {
if (l instanceof Tree || l instanceof Grass) {
Vegetable temp = (Vegetable) l;
if (temp.getCurrent() > 0) {
foodList.add(l.getLocation());
}
}
}
}
}
if (foodList.size() > 0) {
food = foodList.get(0);
final Point location = summative.getLocation(this);
for (Point p : foodList) {
if (Math.abs(p.x - location.x) + Math.abs(p.y - location.y) < Math.abs(food.x - location.x) + Math.abs(food.y - location.y)) {
food = p;
}
}
} else {
for (Lifeform l : list) {
for (Class m : preyList) {
if (l.getClass().equals(m)) {
if (l instanceof Tree || l instanceof Grass) {
foodList.add(l.getLocation());
}
}
}
}
}
}
/**
* Finds the nearest mate
*
* @param list
*/
public void findMate(ArrayList<Lifeform> list) {
ArrayList<Point> mateList = new ArrayList<>();
mate = null;
for (Lifeform l : list) {
if (l.getMobile()) {
if (canMate((Animal) l)) {
mateList.add(l.getLocation());
}
}
}
if (mateList.size() > 0) {
mate = mateList.get(0);
final Point location = summative.getLocation(this);
for (Point p : mateList) {
if (Math.abs(p.x - location.x) + Math.abs(p.y - location.y) < Math.abs(mate.x - location.x) + Math.abs(mate.y - location.y)) {
mate = p;
}
}
}
}
public void findVictim(ArrayList<Lifeform> list) {
ArrayList<Point> hitList = new ArrayList<>();
murder = null;
for (Lifeform l : list) {
if (l.getClass().equals(this.getClass())) {
hitList.add(l.getLocation());
}
}
if (hitList.size() > 0) {
murder = hitList.get(0);
for (Point p : hitList) {
final Point location = summative.getLocation(this);
if (Math.abs(p.x - location.x) + Math.abs(p.y - location.y) < Math.abs(mate.x - location.x) + Math.abs(mate.y - location.y)) {
murder = p;
}
}
}
}
/**
* Checks if the lifeform is prey
*
* @param l
* @return
*/
public boolean isPrey(Lifeform l) {
for (Class m : preyList) {
if (m.equals(l.getClass())) {
return true;
}
}
return false;
}
/**
* Sets the destination of the animal
*/
public void setDestination() {
if (thirst < 50 && hunger < 50 && mate != null) {
if (Math.random() < 1) {
destination = mate;
} else if (murder != null) {
destination = murder;
}
} else if (thirst >= hunger && water != null) {
destination = water;
} else {
destination = food;
}
if (destination == null) {
if (water != null) {
destination = water;
} else if (food != null) {
destination = food;
} else if (mate != null) {
destination = mate;
} else if (murder != null) {
destination = murder;
}
}
}
/**
* Gives the direction in which the point is located relative to the animal
*
* @param p
* @return
*/
public DIRECTION getDirection(Point p) {
final Point location = summative.getLocation(this);
if (p.x == location.x && p.y == location.y) {
return DIRECTION.CENTER;
} else if (Math.abs(p.x - location.x) > Math.abs(p.y - location.y)) {
if (p.x > location.x) {
return DIRECTION.EAST;
} else {
return DIRECTION.WEST;
}
} else if (p.y > location.y) {
return DIRECTION.SOUTH;
} else {
return DIRECTION.NORTH;
}
}
/**
* Returns the animal's gender
*
* @return
*/
public GENDER getGender() {
return gender;
}
/**
* Returns whether the animal can mate with the specified lifeform
*
* @param l
* @return
*/
public boolean canMate(Animal l) {
if (l.getClass() == this.getClass() && l.getGender() != this.getGender()) {
return true;
}
return false;
}
/**
* Can this animal walk there? That is, is it empty?
*/
public boolean canWalk(Point p) {
if (summative.lifeGet(p) == null && summative.terrainGet(p) != TERRAIN.SEA) {
return true;
} else {
return false;
}
}
/**
* Returns whether or not the animal is drowning
*
* @return
*/
public boolean drowning() {
if (summative.terrainGet(summative.getLocation(this)) == TERRAIN.SEA) {
return true;
} else {
return false;
}
}
/**
* The acting method
*
* @param Weather
*/
@Override
public void act(WEATHER Weather) {
boolean walked = false;
if (diseased) {
int temp = sight;
sight = 4;
findNearbyLife();
for (Lifeform l : nearbyLife) {
l.disease();
}
sight = temp;
hunger = hunger + 20;
thirst = thirst + 20;
} else {
if (Math.random() < 0.01) {
disease();
}
}
findNearbyLife();
findWater();
findFood(nearbyLife);
findMate(nearbyLife);
hunger = hunger + 1;
thirst = thirst + 1;
if (hunger > 70 || thirst > 70) {
setDestination();
}
if (Weather == WEATHER.NIGHT && !nocturnal) {
} else {
final Point location = summative.getLocation(this);
if (destination == null || getDirection(destination) == DIRECTION.SOUTH) {
Point temp = new Point(location.x, location.y + 1);
if (canWalk(temp)) {
walked = true;
summative.move(temp, this);
}
} else if (getDirection(destination) == DIRECTION.NORTH) {
Point temp = new Point(location.x, location.y - 1);
if (canWalk(temp)) {
walked = true;
summative.move(temp, this);
}
} else if (getDirection(destination) == DIRECTION.WEST) {
Point temp = new Point(location.x - 1, location.y);
if (canWalk(temp)) {
walked = true;
summative.move(temp, this);
}
} else if (getDirection(destination) == DIRECTION.EAST) {
Point temp = new Point(location.x + 1, location.y);
if (canWalk(temp)) {
walked = true;
summative.move(temp, this);
}
}
if (walked == false) {
Point tempS = new Point(location.x, location.y + 1);
Point tempN = new Point(location.x, location.y - 1);
Point tempW = new Point(location.x - 1, location.y);
Point tempE = new Point(location.x + 1, location.y);
boolean S = true;
boolean W = true;
boolean N = true;
boolean E = true;
int counter = 0;
while (!walked) {
double x = Math.random();
if (x < 0.25 && canWalk(tempS)) {
summative.move(tempS, this);
walked = true;
} else if (S && !canWalk(tempS)) {
S = false;
counter = counter + 1;
} else if (x < 0.5 && canWalk(tempN)) {
summative.move(tempN, this);
walked = true;
} else if (N && !canWalk(tempN)) {
S = false;
counter = counter + 1;
} else if (x < 0.75 && canWalk(tempW)) {
summative.move(tempW, this);
walked = true;
} else if (W && !canWalk(tempW)) {
W = false;
counter = counter + 1;
} else if (canWalk(tempE)) {
summative.move(tempE, this);
walked = true;
} else if (E && !canWalk(tempE)) {
E = false;
counter = counter + 1;
}
if (counter == 4) {
walked = true;
}
}
}
if (destination != null
&& Math.abs(destination.x - location.x) <= 1 && Math.abs(destination.y - location.y) <= 1
&& Math.abs(destination.x - location.x) + Math.abs(destination.y - location.y) < 2) {
{
if (destination == water) {
thirst = 0;
setDestination();
} else if (destination == food) {
hunger = hunger - 30;
setDestination();
if (summative.lifeGet(destination) instanceof Tree) {
Tree temp = (Tree) (summative.lifeGet(destination));
if (temp.getCurrent() <= 0) {
temp.changeHealth(-50);
} else {
temp.changeCurrent(-1);
}
- } else if (isPrey(summative.grassGet(destination))) {
+ } else if (preyList.contains(Grass.class) && summative.lifeGet(destination) instanceof Grass) {
Grass tempg = summative.grassGet(destination);
if (tempg.getCurrent() <= 0) {
tempg.changeHealth(-50);
} else {
tempg.changeCurrent(-1);
}
} else {
summative.kill(destination);
}
} else if (destination == mate) {
hunger = hunger + 30;
reproduce();
setDestination();
} else if (destination == murder) {
summative.lifeGet(destination).suicide();
setDestination();
}
}
}
}
if (hunger > 100 || thirst > 100) {
suicide();
} else if (drowning()) {
suicide();
}
}
/**
* Prints some info about the animal
*
* @return
*/
@Override
public String toString() {
return super.toString()
+ "\nGender: " + gender
+ "\nDestination: " + ((destination != null)
? destination.x + "," + destination.y : "")
+ "\nHunger: " + hunger + "%";
}
}
| true | true | public void act(WEATHER Weather) {
boolean walked = false;
if (diseased) {
int temp = sight;
sight = 4;
findNearbyLife();
for (Lifeform l : nearbyLife) {
l.disease();
}
sight = temp;
hunger = hunger + 20;
thirst = thirst + 20;
} else {
if (Math.random() < 0.01) {
disease();
}
}
findNearbyLife();
findWater();
findFood(nearbyLife);
findMate(nearbyLife);
hunger = hunger + 1;
thirst = thirst + 1;
if (hunger > 70 || thirst > 70) {
setDestination();
}
if (Weather == WEATHER.NIGHT && !nocturnal) {
} else {
final Point location = summative.getLocation(this);
if (destination == null || getDirection(destination) == DIRECTION.SOUTH) {
Point temp = new Point(location.x, location.y + 1);
if (canWalk(temp)) {
walked = true;
summative.move(temp, this);
}
} else if (getDirection(destination) == DIRECTION.NORTH) {
Point temp = new Point(location.x, location.y - 1);
if (canWalk(temp)) {
walked = true;
summative.move(temp, this);
}
} else if (getDirection(destination) == DIRECTION.WEST) {
Point temp = new Point(location.x - 1, location.y);
if (canWalk(temp)) {
walked = true;
summative.move(temp, this);
}
} else if (getDirection(destination) == DIRECTION.EAST) {
Point temp = new Point(location.x + 1, location.y);
if (canWalk(temp)) {
walked = true;
summative.move(temp, this);
}
}
if (walked == false) {
Point tempS = new Point(location.x, location.y + 1);
Point tempN = new Point(location.x, location.y - 1);
Point tempW = new Point(location.x - 1, location.y);
Point tempE = new Point(location.x + 1, location.y);
boolean S = true;
boolean W = true;
boolean N = true;
boolean E = true;
int counter = 0;
while (!walked) {
double x = Math.random();
if (x < 0.25 && canWalk(tempS)) {
summative.move(tempS, this);
walked = true;
} else if (S && !canWalk(tempS)) {
S = false;
counter = counter + 1;
} else if (x < 0.5 && canWalk(tempN)) {
summative.move(tempN, this);
walked = true;
} else if (N && !canWalk(tempN)) {
S = false;
counter = counter + 1;
} else if (x < 0.75 && canWalk(tempW)) {
summative.move(tempW, this);
walked = true;
} else if (W && !canWalk(tempW)) {
W = false;
counter = counter + 1;
} else if (canWalk(tempE)) {
summative.move(tempE, this);
walked = true;
} else if (E && !canWalk(tempE)) {
E = false;
counter = counter + 1;
}
if (counter == 4) {
walked = true;
}
}
}
if (destination != null
&& Math.abs(destination.x - location.x) <= 1 && Math.abs(destination.y - location.y) <= 1
&& Math.abs(destination.x - location.x) + Math.abs(destination.y - location.y) < 2) {
{
if (destination == water) {
thirst = 0;
setDestination();
} else if (destination == food) {
hunger = hunger - 30;
setDestination();
if (summative.lifeGet(destination) instanceof Tree) {
Tree temp = (Tree) (summative.lifeGet(destination));
if (temp.getCurrent() <= 0) {
temp.changeHealth(-50);
} else {
temp.changeCurrent(-1);
}
} else if (isPrey(summative.grassGet(destination))) {
Grass tempg = summative.grassGet(destination);
if (tempg.getCurrent() <= 0) {
tempg.changeHealth(-50);
} else {
tempg.changeCurrent(-1);
}
} else {
summative.kill(destination);
}
} else if (destination == mate) {
hunger = hunger + 30;
reproduce();
setDestination();
} else if (destination == murder) {
summative.lifeGet(destination).suicide();
setDestination();
}
}
}
}
if (hunger > 100 || thirst > 100) {
suicide();
} else if (drowning()) {
suicide();
}
}
| public void act(WEATHER Weather) {
boolean walked = false;
if (diseased) {
int temp = sight;
sight = 4;
findNearbyLife();
for (Lifeform l : nearbyLife) {
l.disease();
}
sight = temp;
hunger = hunger + 20;
thirst = thirst + 20;
} else {
if (Math.random() < 0.01) {
disease();
}
}
findNearbyLife();
findWater();
findFood(nearbyLife);
findMate(nearbyLife);
hunger = hunger + 1;
thirst = thirst + 1;
if (hunger > 70 || thirst > 70) {
setDestination();
}
if (Weather == WEATHER.NIGHT && !nocturnal) {
} else {
final Point location = summative.getLocation(this);
if (destination == null || getDirection(destination) == DIRECTION.SOUTH) {
Point temp = new Point(location.x, location.y + 1);
if (canWalk(temp)) {
walked = true;
summative.move(temp, this);
}
} else if (getDirection(destination) == DIRECTION.NORTH) {
Point temp = new Point(location.x, location.y - 1);
if (canWalk(temp)) {
walked = true;
summative.move(temp, this);
}
} else if (getDirection(destination) == DIRECTION.WEST) {
Point temp = new Point(location.x - 1, location.y);
if (canWalk(temp)) {
walked = true;
summative.move(temp, this);
}
} else if (getDirection(destination) == DIRECTION.EAST) {
Point temp = new Point(location.x + 1, location.y);
if (canWalk(temp)) {
walked = true;
summative.move(temp, this);
}
}
if (walked == false) {
Point tempS = new Point(location.x, location.y + 1);
Point tempN = new Point(location.x, location.y - 1);
Point tempW = new Point(location.x - 1, location.y);
Point tempE = new Point(location.x + 1, location.y);
boolean S = true;
boolean W = true;
boolean N = true;
boolean E = true;
int counter = 0;
while (!walked) {
double x = Math.random();
if (x < 0.25 && canWalk(tempS)) {
summative.move(tempS, this);
walked = true;
} else if (S && !canWalk(tempS)) {
S = false;
counter = counter + 1;
} else if (x < 0.5 && canWalk(tempN)) {
summative.move(tempN, this);
walked = true;
} else if (N && !canWalk(tempN)) {
S = false;
counter = counter + 1;
} else if (x < 0.75 && canWalk(tempW)) {
summative.move(tempW, this);
walked = true;
} else if (W && !canWalk(tempW)) {
W = false;
counter = counter + 1;
} else if (canWalk(tempE)) {
summative.move(tempE, this);
walked = true;
} else if (E && !canWalk(tempE)) {
E = false;
counter = counter + 1;
}
if (counter == 4) {
walked = true;
}
}
}
if (destination != null
&& Math.abs(destination.x - location.x) <= 1 && Math.abs(destination.y - location.y) <= 1
&& Math.abs(destination.x - location.x) + Math.abs(destination.y - location.y) < 2) {
{
if (destination == water) {
thirst = 0;
setDestination();
} else if (destination == food) {
hunger = hunger - 30;
setDestination();
if (summative.lifeGet(destination) instanceof Tree) {
Tree temp = (Tree) (summative.lifeGet(destination));
if (temp.getCurrent() <= 0) {
temp.changeHealth(-50);
} else {
temp.changeCurrent(-1);
}
} else if (preyList.contains(Grass.class) && summative.lifeGet(destination) instanceof Grass) {
Grass tempg = summative.grassGet(destination);
if (tempg.getCurrent() <= 0) {
tempg.changeHealth(-50);
} else {
tempg.changeCurrent(-1);
}
} else {
summative.kill(destination);
}
} else if (destination == mate) {
hunger = hunger + 30;
reproduce();
setDestination();
} else if (destination == murder) {
summative.lifeGet(destination).suicide();
setDestination();
}
}
}
}
if (hunger > 100 || thirst > 100) {
suicide();
} else if (drowning()) {
suicide();
}
}
|
diff --git a/src/main/java/com/google/gerrit/server/mail/NewChangeSender.java b/src/main/java/com/google/gerrit/server/mail/NewChangeSender.java
index a99fa5720..557833970 100644
--- a/src/main/java/com/google/gerrit/server/mail/NewChangeSender.java
+++ b/src/main/java/com/google/gerrit/server/mail/NewChangeSender.java
@@ -1,133 +1,134 @@
// Copyright (C) 2009 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.server.mail;
import com.google.gerrit.client.reviewdb.Account;
import com.google.gerrit.client.reviewdb.Change;
import com.google.gerrit.server.ssh.SshInfo;
import com.google.inject.Inject;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/** Sends an email alerting a user to a new change for them to review. */
public abstract class NewChangeSender extends OutgoingEmail {
@Inject
private SshInfo sshInfo;
private final Set<Account.Id> reviewers = new HashSet<Account.Id>();
private final Set<Account.Id> extraCC = new HashSet<Account.Id>();
protected NewChangeSender(Change c) {
super(c, "newchange");
}
public void addReviewers(final Collection<Account.Id> cc) {
reviewers.addAll(cc);
}
public void addExtraCC(final Collection<Account.Id> cc) {
extraCC.addAll(cc);
}
@Override
protected void init() {
super.init();
setHeader("Message-ID", getChangeMessageThreadId());
add(RecipientType.TO, reviewers);
add(RecipientType.CC, extraCC);
rcptToAuthors(RecipientType.CC);
}
@Override
protected void format() {
formatSalutation();
formatChangeDetail();
}
private void formatSalutation() {
final String changeUrl = getChangeUrl();
final String pullUrl = getPullUrl();
if (reviewers.isEmpty()) {
formatDest();
if (changeUrl != null) {
appendText("\n");
appendText(" " + changeUrl + "\n");
+ appendText(" " + pullUrl + "\n");
appendText("\n");
}
appendText("\n");
} else {
appendText("Hello");
for (final Iterator<Account.Id> i = reviewers.iterator(); i.hasNext();) {
appendText(" ");
appendText(getNameFor(i.next()));
appendText(",");
}
appendText("\n");
appendText("\n");
appendText("I'd like you to do a code review.");
if (changeUrl != null) {
appendText(" Please visit\n");
appendText("\n");
appendText(" " + changeUrl + "\n");
appendText(" " + pullUrl + "\n");
appendText("\n");
appendText("to review the following change:\n");
} else {
appendText(" Please execute\n");
appendText("\n");
appendText(" " + pullUrl + "\n");
appendText("\n");
appendText("to review the following change:\n");
}
appendText("\n");
formatDest();
appendText("\n");
}
}
private void formatDest() {
appendText("Change " + change.getKey().abbreviate());
appendText(" for ");
appendText(change.getDest().getShortName());
appendText(" in ");
appendText(projectName);
appendText(":\n");
}
private String getPullUrl() {
final StringBuilder r = new StringBuilder();
r.append("git pull ssh://");
String sshAddress = sshInfo.getSshdAddress();
if (sshAddress.startsWith(":") || "".equals(sshAddress)) {
r.append(getGerritHost());
}
r.append(sshAddress);
r.append("/");
r.append(projectName);
r.append(" ");
r.append(patchSet.getRefName());
return r.toString();
}
}
| true | true | private void formatSalutation() {
final String changeUrl = getChangeUrl();
final String pullUrl = getPullUrl();
if (reviewers.isEmpty()) {
formatDest();
if (changeUrl != null) {
appendText("\n");
appendText(" " + changeUrl + "\n");
appendText("\n");
}
appendText("\n");
} else {
appendText("Hello");
for (final Iterator<Account.Id> i = reviewers.iterator(); i.hasNext();) {
appendText(" ");
appendText(getNameFor(i.next()));
appendText(",");
}
appendText("\n");
appendText("\n");
appendText("I'd like you to do a code review.");
if (changeUrl != null) {
appendText(" Please visit\n");
appendText("\n");
appendText(" " + changeUrl + "\n");
appendText(" " + pullUrl + "\n");
appendText("\n");
appendText("to review the following change:\n");
} else {
appendText(" Please execute\n");
appendText("\n");
appendText(" " + pullUrl + "\n");
appendText("\n");
appendText("to review the following change:\n");
}
appendText("\n");
formatDest();
appendText("\n");
}
}
| private void formatSalutation() {
final String changeUrl = getChangeUrl();
final String pullUrl = getPullUrl();
if (reviewers.isEmpty()) {
formatDest();
if (changeUrl != null) {
appendText("\n");
appendText(" " + changeUrl + "\n");
appendText(" " + pullUrl + "\n");
appendText("\n");
}
appendText("\n");
} else {
appendText("Hello");
for (final Iterator<Account.Id> i = reviewers.iterator(); i.hasNext();) {
appendText(" ");
appendText(getNameFor(i.next()));
appendText(",");
}
appendText("\n");
appendText("\n");
appendText("I'd like you to do a code review.");
if (changeUrl != null) {
appendText(" Please visit\n");
appendText("\n");
appendText(" " + changeUrl + "\n");
appendText(" " + pullUrl + "\n");
appendText("\n");
appendText("to review the following change:\n");
} else {
appendText(" Please execute\n");
appendText("\n");
appendText(" " + pullUrl + "\n");
appendText("\n");
appendText("to review the following change:\n");
}
appendText("\n");
formatDest();
appendText("\n");
}
}
|
diff --git a/src/org/bh/platform/PlatformActionListener.java b/src/org/bh/platform/PlatformActionListener.java
index e88c0c07..cc577763 100644
--- a/src/org/bh/platform/PlatformActionListener.java
+++ b/src/org/bh/platform/PlatformActionListener.java
@@ -1,780 +1,782 @@
package org.bh.platform;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Calendar;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.WindowConstants;
import javax.swing.tree.TreePath;
import org.apache.log4j.Logger;
import org.bh.controller.IDataExchangeController;
import org.bh.data.DTOPeriod;
import org.bh.data.DTOProject;
import org.bh.data.DTOScenario;
import org.bh.data.IDTO;
import org.bh.data.types.StringValue;
import org.bh.gui.swing.BHComboBox;
import org.bh.gui.swing.BHContent;
import org.bh.gui.swing.BHDataExchangeDialog;
import org.bh.gui.swing.BHHelpDebugDialog;
import org.bh.gui.swing.BHMainFrame;
import org.bh.gui.swing.BHOptionDialog;
import org.bh.gui.swing.BHStatusBar;
import org.bh.gui.swing.BHTreeNode;
import org.bh.gui.swing.IBHAction;
import org.bh.platform.PlatformController.BHTreeModel;
import org.bh.platform.i18n.BHTranslator;
import org.bh.platform.i18n.ITranslator;
/**
* The PlatformActionListener handles all actions that are fired by a button
* etc. of the platform.
*/
class PlatformActionListener implements ActionListener {
private static final Logger log = Logger
.getLogger(PlatformActionListener.class);
BHMainFrame bhmf;
ProjectRepositoryManager projectRepoManager;
PlatformController pC;
IDataExchangeController dataExchangeCntrl;
public PlatformActionListener(BHMainFrame bhmf,
ProjectRepositoryManager projectRepoManager,
PlatformController platformController) {
this.bhmf = bhmf;
this.projectRepoManager = projectRepoManager;
this.pC = platformController;
}
@Override
public void actionPerformed(ActionEvent aEvent) {
// get actionKey of fired action
PlatformKey actionKey = ((IBHAction) aEvent.getSource())
.getPlatformKey();
// do right action...
switch (actionKey) {
/*
* Clear current workspace
*
* @author Michael Löckelt
*/
case FILENEW:
log.debug("handling FILENEW event");
this.fileNew();
break;
/*
* Open a workspace
*
* @author Michael Löckelt
*/
case FILEOPEN:
log.debug("handling FILEOPEN event");
this.fileOpen();
break;
/*
* Save the whole workspace using the already defined filepath or ask
* for new path
*
* @author Michael Löckelt
*/
case FILESAVE:
log.debug("handling FILESAVE event");
Services.firePlatformEvent(new PlatformEvent(
PlatformActionListener.class, PlatformEvent.Type.SAVE));
break;
/*
* Save the whole workspace - incl. filepath save dialog
*
* @author Michael Löckelt
*/
case FILESAVEAS:
log.debug("handling FILESAVEAS event");
Services.firePlatformEvent(new PlatformEvent(
PlatformActionListener.class, PlatformEvent.Type.SAVEAS));
break;
/*
* Clear workspace - same like filenew
*
* @author Michael Löckelt
*/
case FILECLOSE:
log.debug("handling FILECLOSE event");
this.fileNew();
break;
case FILEQUIT:
log.debug("handling FILEQUIT event");
bhmf.dispose();
break;
case PROJECTCREATE:
this.createProject();
break;
case PROJECTDUPLICATE:
this.duplicateProject();
break;
// TODO Katzor.Marcus
case PROJECTIMPORT:
BHDataExchangeDialog importDialog = new BHDataExchangeDialog(bhmf,
true);
importDialog.setAction(IImportExport.IMP_PROJECT);
importDialog.setDescription(BHTranslator.getInstance().translate(
"DXMLImportDescription"));
importDialog.setVisible(true);
break;
// TODO Katzor.Marcus
case PROJECTEXPORT:
// Get selected node
if (bhmf.getBHTree().getSelectionPath() != null) {
BHTreeNode selectedNode = (BHTreeNode) bhmf.getBHTree()
.getSelectionPath().getLastPathComponent();
// Get DTOProject
if (selectedNode.getUserObject() instanceof DTOProject) {
// Create data exchange dialog
BHDataExchangeDialog dialog = new BHDataExchangeDialog(
bhmf, true);
dialog.setAction(IImportExport.EXP_PROJECT);
dialog.setModel((IDTO<?>) selectedNode.getUserObject());
dialog.setDescription(BHTranslator.getInstance().translate(
"DExpFileFormatSel"));
dialog.setVisible(true);
} else {
// TODO Katzor.Marcus Show Message
}
} else {
// TODO Katzor.Marcus Show Message
}
break;
case PROJECTREMOVE:
int pr_choice = JOptionPane.showConfirmDialog(bhmf, Services
.getTranslator().translate("Pproject_delete"), Services
.getTranslator().translate("Pdelete"),
JOptionPane.YES_NO_OPTION);
if (pr_choice == JOptionPane.YES_OPTION) {
TreePath currentRemoveProjectSelection = bhmf.getBHTree()
.getSelectionPath();
if (currentRemoveProjectSelection != null) {
BHTreeNode removeProjectNode = (BHTreeNode) bhmf
.getBHTree().getSelectionPath()
.getLastPathComponent();
if (removeProjectNode.getUserObject() instanceof DTOProject) {
((BHTreeModel) bhmf.getBHTree().getModel())
.removeNodeFromParent(removeProjectNode);
projectRepoManager
.removeProject((DTOProject) removeProjectNode
.getUserObject());
} else {
BHStatusBar.getInstance().setHint(
BHTranslator.getInstance().translate(
"EisSelectProject"), true);
}
}
}
break;
case SCENARIOCREATE:
this.createScenario();
break;
case SCENARIODUPLICATE:
this.duplicateScenario();
break;
case SCENARIOMOVE:
// TODO Drag&Drop
break;
case SCENARIOREMOVE:
int sc_choice = JOptionPane.showConfirmDialog(bhmf, Services
.getTranslator().translate("Pscenario_delete"), Services
.getTranslator().translate("Pdelete"),
JOptionPane.YES_NO_OPTION);
if (sc_choice == JOptionPane.YES_OPTION) {
TreePath currentRemoveScenarioSelection = bhmf.getBHTree()
.getSelectionPath();
if (currentRemoveScenarioSelection != null) {
BHTreeNode removeScenarioNode = (BHTreeNode) bhmf
.getBHTree().getSelectionPath()
.getLastPathComponent();
if (removeScenarioNode.getUserObject() instanceof DTOScenario) {
((BHTreeModel) bhmf.getBHTree().getModel())
.removeNodeFromParent(removeScenarioNode);
((DTOScenario) ((BHTreeNode) removeScenarioNode
.getParent()).getUserObject())
.removeChild((DTOPeriod) removeScenarioNode
.getUserObject());
} else {
BHStatusBar.getInstance().setHint(
BHTranslator.getInstance().translate(
"EisSelectScenario"), true);
}
}
}
break;
case PERIODCREATE:
this.createPeriod();
break;
case PERIODDUPLICATE:
this.duplicatePeriod();
break;
case PERIODREMOVE:
int pe_choice = JOptionPane.showConfirmDialog(bhmf, Services
.getTranslator().translate("Pperiod_delete"), Services
.getTranslator().translate("Pdelete"),
JOptionPane.YES_NO_OPTION);
if (pe_choice == JOptionPane.YES_OPTION) {
TreePath currentRemovePeriodSelection = bhmf.getBHTree()
.getSelectionPath();
if (currentRemovePeriodSelection != null) {
BHTreeNode removeNode = (BHTreeNode) bhmf.getBHTree()
.getSelectionPath().getLastPathComponent();
if (removeNode.getUserObject() instanceof DTOPeriod) {
((BHTreeModel) bhmf.getBHTree().getModel())
.removeNodeFromParent(removeNode);
((DTOPeriod) ((BHTreeNode) removeNode.getParent())
.getUserObject()).remove((DTOPeriod) removeNode
.getUserObject());
} else {
BHStatusBar.getInstance().setHint(
BHTranslator.getInstance().translate(
"EisSelectPeriod"), true);
}
}
}
break;
case BILANZGUVSHOW:
// TODO Prüfen und ggf. implementieren!
break;
case BILANZGUVCREATE:
// TODO Prüfen und ggf. implementieren!
break;
case BILANZGUVIMPORT:
// TODO Prüfen und ggf. implementieren!
break;
case BILANZGUVREMOVE:
// TODO Prüfen und ggf. implementieren!
break;
case OPTIONSCHANGE:
new BHOptionDialog();
break;
case HELPUSERHELP:
openUserHelp("userhelp");
+ break;
case HELPMATHHELP:
openUserHelp("mathhelp");
+ break;
case HELPINFO:
// TODO Prüfen und ggf. implementieren!
break;
case HELPDEBUG:
new BHHelpDebugDialog();
break;
case TOOLBARNEW:
log.debug("handling FILENEW event");
this.fileNew();
break;
case TOOLBAROPEN:
log.debug("handling TOOLBAROPEN event");
this.fileOpen();
break;
case TOOLBARSAVE:
log.debug("handling TOOLBARSAVE event");
Services.firePlatformEvent(new PlatformEvent(
PlatformActionListener.class, PlatformEvent.Type.SAVE));
break;
case TOOLBARADDPRO:
this.createProject();
break;
case TOOLBARADDS:
this.createScenario();
break;
case TOOLBARADDPER:
this.createPeriod();
break;
case TOOLBARREMOVE:
this.toolbarRemove();
break;
case POPUPREMOVE:
this.toolbarRemove();
break;
case POPUPADD:
this.popupAdd();
break;
case POPUPDUPLICATE:
this.popupDuplicate();
break;
default:
// TODO implementieren?
break;
}
}
/*
* new file
*
* @author Loeckelt.Michael
*/
private void fileNew() {
if (ProjectRepositoryManager.isChanged()) {
int i = JOptionPane.showConfirmDialog(bhmf, Services
.getTranslator().translate("Psave", ITranslator.LONG),
Services.getTranslator().translate("Psave"),
JOptionPane.YES_NO_CANCEL_OPTION);
if (i == JOptionPane.YES_OPTION || i == JOptionPane.NO_OPTION) {
if (i == JOptionPane.YES_OPTION)
Services.firePlatformEvent(new PlatformEvent(
BHMainFrame.class, PlatformEvent.Type.SAVE));
if (i == JOptionPane.NO_OPTION)
Logger
.getLogger(getClass())
.debug(
"Existing changes but no save wish - clear project list");
projectRepoManager.clearProjectList();
pC.setupTree(bhmf, projectRepoManager);
PlatformController.preferences.remove("path");
ProjectRepositoryManager.setChanged(false);
bhmf.resetTitle();
} else if (i == JOptionPane.CANCEL_OPTION) {
}
} else {
Logger.getLogger(getClass()).debug(
"No changes - clear project list");
projectRepoManager.clearProjectList();
pC.setupTree(bhmf, projectRepoManager);
PlatformController.preferences.remove("path");
ProjectRepositoryManager.setChanged(false);
bhmf.resetTitle();
}
}
/*
* new file
*
* @author Loeckelt.Michael
*/
protected void fileOpen() {
// create a open-dialog
int returnVal = bhmf.getChooser().showOpenDialog(bhmf);
if (returnVal == JFileChooser.APPROVE_OPTION) {
log.debug("You chose to open this file: "
+ bhmf.getChooser().getSelectedFile().getName());
// open already provided file
PlatformController.platformPersistenceManager.openFile(bhmf
.getChooser().getSelectedFile());
// rebuild Tree
pC.setupTree(bhmf, projectRepoManager);
bhmf.getBHTree().expandAll();
}
}
protected void popupDuplicate(){
TreePath currentSelection = bhmf.getBHTree().getSelectionPath();
//is a node selected?
if(currentSelection != null){
BHTreeNode currentNode = (BHTreeNode) bhmf.getBHTree()
.getSelectionPath().getLastPathComponent();
//add a new node to data model...
if(currentNode.getUserObject() instanceof DTOProject){
this.duplicateProject();
}else if(currentNode.getUserObject() instanceof DTOScenario){
this.duplicateScenario();
}else if(currentNode.getUserObject() instanceof DTOPeriod){
this.duplicatePeriod();
}
}
}
protected void popupAdd(){
TreePath currentSelection = bhmf.getBHTree().getSelectionPath();
//is a node selected?
if(currentSelection != null){
BHTreeNode currentNode = (BHTreeNode) bhmf.getBHTree()
.getSelectionPath().getLastPathComponent();
//add a new node to data model...
if(currentNode.getUserObject() instanceof DTOProject){
this.createScenario();
}else if(currentNode.getUserObject() instanceof DTOScenario){
this.createPeriod();
}
}else {
this.createProject();
}
}
protected void toolbarRemove() {
TreePath currentSelection = bhmf.getBHTree().getSelectionPath();
// is a node selected?
if (currentSelection != null) {
int choice = JOptionPane.showConfirmDialog(bhmf, Services
.getTranslator().translate("Pelement_delete"), Services
.getTranslator().translate("Pdelete"),
JOptionPane.YES_NO_OPTION);
if (choice == JOptionPane.YES_OPTION) {
// find out current selected node
BHTreeNode currentNode = (BHTreeNode) bhmf.getBHTree()
.getSelectionPath().getLastPathComponent();
// remove node from data model...
if (currentNode.getUserObject() instanceof DTOProject) {
projectRepoManager.removeProject((DTOProject) currentNode
.getUserObject());
} else if (currentNode.getUserObject() instanceof DTOScenario) {
((DTOProject) ((BHTreeNode) currentNode.getParent())
.getUserObject())
.removeChild((DTOScenario) currentNode
.getUserObject());
} else if (currentNode.getUserObject() instanceof DTOPeriod) {
((DTOScenario) ((BHTreeNode) currentNode.getParent())
.getUserObject())
.removeChild((DTOPeriod) currentNode
.getUserObject());
}
// ... and from GUI and select other node or empty screen
TreePath tp = new TreePath(currentNode.getPreviousNode()
.getPath());
bhmf.getBHTree().setSelectionPath(tp);
if (bhmf.getBHTree().getSelectionPath().getPathCount() == 1)
bhmf.setContentForm(new BHContent());
((BHTreeModel) bhmf.getBHTree().getModel())
.removeNodeFromParent(currentNode);
}
}
}
protected void createProject() {
// Create new project
DTOProject newProject = new DTOProject();
// TODO hardgecodeder String raus! AS
newProject.put(DTOProject.Key.NAME, new StringValue("neues Projekt"));
// add it to DTO-Repository and Tree
PlatformController.getInstance().addProject(newProject);
}
protected void createScenario() {
// If a path is selected...
if (bhmf.getBHTree().getSelectionPath() != null) {
// check kind of scenario: deterministic or stochastic?
// TODO Schmalzhaf.Alexander: String raus!
ArrayList<BHComboBox.Item> itemsList = new ArrayList<BHComboBox.Item>();
itemsList.add(new BHComboBox.Item("deterministic", new StringValue(
"deterministisch")));
itemsList.add(new BHComboBox.Item("stochastic", new StringValue(
"stochastisch")));
BHComboBox.Item res = (BHComboBox.Item) JOptionPane
.showInputDialog(bhmf,
"Bitte gewünschten Szenariotyp auswählen:",
"Szenariotyp auswählen",
JOptionPane.QUESTION_MESSAGE, null, itemsList
.toArray(), null);
if (res == null)
return;
// ...create new scenario
DTOScenario newScenario = new DTOScenario(res.getKey()
.equalsIgnoreCase("deterministic"));
// TODO hardgecodeder String raus! AS
newScenario.put(DTOScenario.Key.NAME, new StringValue(
"neues Szenario"));
// ...set Basis (IDENTIFIER) of scenario -> naming of periods
newScenario.put(DTOScenario.Key.IDENTIFIER, new StringValue(""
+ Calendar.getInstance().get(Calendar.YEAR)));
// ...add it to DTO-Repository
((DTOProject) ((BHTreeNode) bhmf.getBHTree().getSelectionPath()
.getPathComponent(1)).getUserObject())
.addChild(newScenario);
// ...and insert it into GUI-Tree
BHTreeNode newScenarioNode = bhmf.getBHTree()
.addScenarioAtCurrentPos(newScenario);
// last steps: unfold tree to new element, set focus and start
// editing
bhmf.getBHTree().scrollPathToVisible(
new TreePath(newScenarioNode.getPath()));
bhmf.getBHTree().startEditingAtPath(
new TreePath(newScenarioNode.getPath()));
} else {
BHStatusBar.getInstance().setHint(
BHTranslator.getInstance().translate("EisSelectProject"),
true);
}
}
protected void createPeriod() {
// If a scenario or a period is selected...
if (bhmf.getBHTree().getSelectionPath() != null
&& bhmf.getBHTree().getSelectionPath().getPathCount() > 2) {
DTOScenario scenario = ((DTOScenario) ((BHTreeNode) bhmf
.getBHTree().getSelectionPath().getPathComponent(2))
.getUserObject());
// ...create new period
DTOPeriod newPeriod = new DTOPeriod();
// TODO hardgecodeder String raus! AS
// ...set name of period
String periodName = "";
if (scenario.getChildren().isEmpty()) {
try {
periodName = BHTranslator.getInstance().translate("period")
+ " "
+ scenario.get(DTOScenario.Key.IDENTIFIER)
.toString();
} catch (Exception e) {
// Do nothing;
}
} else {
//get reference period to orient index
//-> depends on sort of scenario
DTOPeriod refPeriod;
int periodDifference;
if(scenario.isDeterministic()){
refPeriod = scenario.getLastChild();
periodDifference = 1;
}else{
refPeriod = scenario.getFirstChild();
periodDifference = -1;
}
try {
// get number of last Period and add 1.
periodName = ""
+ (Integer.parseInt(((StringValue) refPeriod
.get(DTOPeriod.Key.NAME)).getString()) + periodDifference);
} catch (Exception e) {
try {
// get number and Text of last Period and add 1.
String lastPeriodName = ((StringValue) refPeriod
.get(DTOPeriod.Key.NAME)).getString();
int tempNum = Integer.parseInt(lastPeriodName
.substring(getNumPos(lastPeriodName)));
periodName = lastPeriodName.substring(0,
getNumPos(lastPeriodName))
+ (tempNum + periodDifference);
} catch (Exception e1) {
// TODO Schmalzhaf.Alexander harter String raus!
periodName = "neue Periode";
}
}
}
newPeriod.put(DTOPeriod.Key.NAME, new StringValue(periodName));
// ...add it to DTO-Repository
((DTOScenario) ((BHTreeNode) bhmf.getBHTree().getSelectionPath()
.getPathComponent(2)).getUserObject()).addChild(newPeriod);
// ...and insert it into GUI-Tree
BHTreeNode newPeriodNode = bhmf.getBHTree().addPeriodAtCurrentPos(
newPeriod);
// last steps: unfold tree to new element, set focus and start
// editing
bhmf.getBHTree().scrollPathToVisible(
new TreePath(newPeriodNode.getPath()));
bhmf.getBHTree().startEditingAtPath(
new TreePath(newPeriodNode.getPath()));
Services.startPeriodEditing(newPeriod);
}
}
private void duplicateProject() {
TreePath currentDuplicateProjectSelection = bhmf.getBHTree()
.getSelectionPath();
if (currentDuplicateProjectSelection != null) {
// Access to selected project
BHTreeNode duplicateProjectNode = (BHTreeNode) bhmf.getBHTree()
.getSelectionPath().getLastPathComponent();
// zu kopierendes Project in eigene Variable
DTOProject duplicateProject = (DTOProject) duplicateProjectNode
.getUserObject();
// neues DTOProject mit Referenz auf den Klon
DTOProject newProject = (DTOProject) duplicateProject.clone();
// new name after duplication
String duplicateProjectName = bhmf.getBHTree().getSelectionPath()
.getPathComponent(1).toString();
newProject.put(DTOProject.Key.NAME, new StringValue(
duplicateProjectName + " (2)"));
bhmf.getBHTree().addProject(newProject);
} else {
BHStatusBar.getInstance().setHint(
BHTranslator.getInstance().translate("EisSelectProject"),
true);
}
}
private void duplicateScenario() {
TreePath currentDuplicateScenarioSelection = bhmf.getBHTree()
.getSelectionPath();
if (currentDuplicateScenarioSelection != null) {
// Access to selected scenario
BHTreeNode duplicateScenarioNode = (BHTreeNode) bhmf.getBHTree()
.getSelectionPath().getLastPathComponent();
// zu kopierendes Project in eigene Variable
DTOScenario duplicateScenario = (DTOScenario) duplicateScenarioNode
.getUserObject();
// neues DTOProject mit Referenz auf den Klon
DTOScenario newScenario = (DTOScenario) duplicateScenario.clone();
// new name after duplication
String duplicateScenarioName = bhmf.getBHTree().getSelectionPath()
.getPathComponent(2).toString();
newScenario.put(DTOScenario.Key.NAME, new StringValue(
duplicateScenarioName + " (2)"));
bhmf.getBHTree().addScenarioAtCurrentPos(newScenario);
} else {
BHStatusBar.getInstance().setHint(
BHTranslator.getInstance().translate("EisSelectScenario"),
true);
}
}
private void duplicatePeriod() {
// implement the 'duplicate period' method
TreePath currentDuplicatePeriodSelection = bhmf.getBHTree()
.getSelectionPath();
if (currentDuplicatePeriodSelection != null) {
// Access to selected period
BHTreeNode duplicatePeriodNode = (BHTreeNode) bhmf.getBHTree()
.getSelectionPath().getLastPathComponent();
// copy the period to a temp period
DTOPeriod duplicatePeriod = (DTOPeriod) duplicatePeriodNode
.getUserObject();
String duplicatePeriodName = bhmf.getBHTree().getSelectionPath()
.getPathComponent(3).toString();
// new DTOPeriod object with reference to the clone
DTOPeriod newPeriod = (DTOPeriod) duplicatePeriod.clone();
newPeriod.put(DTOPeriod.Key.NAME, new StringValue(
duplicatePeriodName + " (2)"));
bhmf.getBHTree().addPeriodAtCurrentPos(newPeriod);
} else {
BHStatusBar.getInstance().setHint(
BHTranslator.getInstance().translate("EisSelectScenario"),
true);
}
}
protected void openUserHelp(String help) {
log.debug("HELPUSERHELP gefeuert");
JDialog frame = new JDialog();
frame.setTitle(BHTranslator.getInstance().translate("MuserHelpDialog"));
frame.setSize(610, 600);
frame.getContentPane().add(new BHHelpSystem(help));
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
/**
* Method to get Position on numeric value in a string Necessary for naming
* of Periods
*
* @param s
* @return
*/
private int getNumPos(String s) {
int[] numbers = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int start = s.length();
for (int i : numbers) {
if (s.indexOf("" + i) < start && s.indexOf("" + i) > -1)
start = s.indexOf("" + i);
}
System.out.println("start " + start);
return start;
}
}
| false | true | public void actionPerformed(ActionEvent aEvent) {
// get actionKey of fired action
PlatformKey actionKey = ((IBHAction) aEvent.getSource())
.getPlatformKey();
// do right action...
switch (actionKey) {
/*
* Clear current workspace
*
* @author Michael Löckelt
*/
case FILENEW:
log.debug("handling FILENEW event");
this.fileNew();
break;
/*
* Open a workspace
*
* @author Michael Löckelt
*/
case FILEOPEN:
log.debug("handling FILEOPEN event");
this.fileOpen();
break;
/*
* Save the whole workspace using the already defined filepath or ask
* for new path
*
* @author Michael Löckelt
*/
case FILESAVE:
log.debug("handling FILESAVE event");
Services.firePlatformEvent(new PlatformEvent(
PlatformActionListener.class, PlatformEvent.Type.SAVE));
break;
/*
* Save the whole workspace - incl. filepath save dialog
*
* @author Michael Löckelt
*/
case FILESAVEAS:
log.debug("handling FILESAVEAS event");
Services.firePlatformEvent(new PlatformEvent(
PlatformActionListener.class, PlatformEvent.Type.SAVEAS));
break;
/*
* Clear workspace - same like filenew
*
* @author Michael Löckelt
*/
case FILECLOSE:
log.debug("handling FILECLOSE event");
this.fileNew();
break;
case FILEQUIT:
log.debug("handling FILEQUIT event");
bhmf.dispose();
break;
case PROJECTCREATE:
this.createProject();
break;
case PROJECTDUPLICATE:
this.duplicateProject();
break;
// TODO Katzor.Marcus
case PROJECTIMPORT:
BHDataExchangeDialog importDialog = new BHDataExchangeDialog(bhmf,
true);
importDialog.setAction(IImportExport.IMP_PROJECT);
importDialog.setDescription(BHTranslator.getInstance().translate(
"DXMLImportDescription"));
importDialog.setVisible(true);
break;
// TODO Katzor.Marcus
case PROJECTEXPORT:
// Get selected node
if (bhmf.getBHTree().getSelectionPath() != null) {
BHTreeNode selectedNode = (BHTreeNode) bhmf.getBHTree()
.getSelectionPath().getLastPathComponent();
// Get DTOProject
if (selectedNode.getUserObject() instanceof DTOProject) {
// Create data exchange dialog
BHDataExchangeDialog dialog = new BHDataExchangeDialog(
bhmf, true);
dialog.setAction(IImportExport.EXP_PROJECT);
dialog.setModel((IDTO<?>) selectedNode.getUserObject());
dialog.setDescription(BHTranslator.getInstance().translate(
"DExpFileFormatSel"));
dialog.setVisible(true);
} else {
// TODO Katzor.Marcus Show Message
}
} else {
// TODO Katzor.Marcus Show Message
}
break;
case PROJECTREMOVE:
int pr_choice = JOptionPane.showConfirmDialog(bhmf, Services
.getTranslator().translate("Pproject_delete"), Services
.getTranslator().translate("Pdelete"),
JOptionPane.YES_NO_OPTION);
if (pr_choice == JOptionPane.YES_OPTION) {
TreePath currentRemoveProjectSelection = bhmf.getBHTree()
.getSelectionPath();
if (currentRemoveProjectSelection != null) {
BHTreeNode removeProjectNode = (BHTreeNode) bhmf
.getBHTree().getSelectionPath()
.getLastPathComponent();
if (removeProjectNode.getUserObject() instanceof DTOProject) {
((BHTreeModel) bhmf.getBHTree().getModel())
.removeNodeFromParent(removeProjectNode);
projectRepoManager
.removeProject((DTOProject) removeProjectNode
.getUserObject());
} else {
BHStatusBar.getInstance().setHint(
BHTranslator.getInstance().translate(
"EisSelectProject"), true);
}
}
}
break;
case SCENARIOCREATE:
this.createScenario();
break;
case SCENARIODUPLICATE:
this.duplicateScenario();
break;
case SCENARIOMOVE:
// TODO Drag&Drop
break;
case SCENARIOREMOVE:
int sc_choice = JOptionPane.showConfirmDialog(bhmf, Services
.getTranslator().translate("Pscenario_delete"), Services
.getTranslator().translate("Pdelete"),
JOptionPane.YES_NO_OPTION);
if (sc_choice == JOptionPane.YES_OPTION) {
TreePath currentRemoveScenarioSelection = bhmf.getBHTree()
.getSelectionPath();
if (currentRemoveScenarioSelection != null) {
BHTreeNode removeScenarioNode = (BHTreeNode) bhmf
.getBHTree().getSelectionPath()
.getLastPathComponent();
if (removeScenarioNode.getUserObject() instanceof DTOScenario) {
((BHTreeModel) bhmf.getBHTree().getModel())
.removeNodeFromParent(removeScenarioNode);
((DTOScenario) ((BHTreeNode) removeScenarioNode
.getParent()).getUserObject())
.removeChild((DTOPeriod) removeScenarioNode
.getUserObject());
} else {
BHStatusBar.getInstance().setHint(
BHTranslator.getInstance().translate(
"EisSelectScenario"), true);
}
}
}
break;
case PERIODCREATE:
this.createPeriod();
break;
case PERIODDUPLICATE:
this.duplicatePeriod();
break;
case PERIODREMOVE:
int pe_choice = JOptionPane.showConfirmDialog(bhmf, Services
.getTranslator().translate("Pperiod_delete"), Services
.getTranslator().translate("Pdelete"),
JOptionPane.YES_NO_OPTION);
if (pe_choice == JOptionPane.YES_OPTION) {
TreePath currentRemovePeriodSelection = bhmf.getBHTree()
.getSelectionPath();
if (currentRemovePeriodSelection != null) {
BHTreeNode removeNode = (BHTreeNode) bhmf.getBHTree()
.getSelectionPath().getLastPathComponent();
if (removeNode.getUserObject() instanceof DTOPeriod) {
((BHTreeModel) bhmf.getBHTree().getModel())
.removeNodeFromParent(removeNode);
((DTOPeriod) ((BHTreeNode) removeNode.getParent())
.getUserObject()).remove((DTOPeriod) removeNode
.getUserObject());
} else {
BHStatusBar.getInstance().setHint(
BHTranslator.getInstance().translate(
"EisSelectPeriod"), true);
}
}
}
break;
case BILANZGUVSHOW:
// TODO Prüfen und ggf. implementieren!
break;
case BILANZGUVCREATE:
// TODO Prüfen und ggf. implementieren!
break;
case BILANZGUVIMPORT:
// TODO Prüfen und ggf. implementieren!
break;
case BILANZGUVREMOVE:
// TODO Prüfen und ggf. implementieren!
break;
case OPTIONSCHANGE:
new BHOptionDialog();
break;
case HELPUSERHELP:
openUserHelp("userhelp");
case HELPMATHHELP:
openUserHelp("mathhelp");
case HELPINFO:
// TODO Prüfen und ggf. implementieren!
break;
case HELPDEBUG:
new BHHelpDebugDialog();
break;
case TOOLBARNEW:
log.debug("handling FILENEW event");
this.fileNew();
break;
case TOOLBAROPEN:
log.debug("handling TOOLBAROPEN event");
this.fileOpen();
break;
case TOOLBARSAVE:
log.debug("handling TOOLBARSAVE event");
Services.firePlatformEvent(new PlatformEvent(
PlatformActionListener.class, PlatformEvent.Type.SAVE));
break;
case TOOLBARADDPRO:
this.createProject();
break;
case TOOLBARADDS:
this.createScenario();
break;
case TOOLBARADDPER:
this.createPeriod();
break;
case TOOLBARREMOVE:
this.toolbarRemove();
break;
case POPUPREMOVE:
this.toolbarRemove();
break;
case POPUPADD:
this.popupAdd();
break;
case POPUPDUPLICATE:
this.popupDuplicate();
break;
default:
// TODO implementieren?
break;
}
}
| public void actionPerformed(ActionEvent aEvent) {
// get actionKey of fired action
PlatformKey actionKey = ((IBHAction) aEvent.getSource())
.getPlatformKey();
// do right action...
switch (actionKey) {
/*
* Clear current workspace
*
* @author Michael Löckelt
*/
case FILENEW:
log.debug("handling FILENEW event");
this.fileNew();
break;
/*
* Open a workspace
*
* @author Michael Löckelt
*/
case FILEOPEN:
log.debug("handling FILEOPEN event");
this.fileOpen();
break;
/*
* Save the whole workspace using the already defined filepath or ask
* for new path
*
* @author Michael Löckelt
*/
case FILESAVE:
log.debug("handling FILESAVE event");
Services.firePlatformEvent(new PlatformEvent(
PlatformActionListener.class, PlatformEvent.Type.SAVE));
break;
/*
* Save the whole workspace - incl. filepath save dialog
*
* @author Michael Löckelt
*/
case FILESAVEAS:
log.debug("handling FILESAVEAS event");
Services.firePlatformEvent(new PlatformEvent(
PlatformActionListener.class, PlatformEvent.Type.SAVEAS));
break;
/*
* Clear workspace - same like filenew
*
* @author Michael Löckelt
*/
case FILECLOSE:
log.debug("handling FILECLOSE event");
this.fileNew();
break;
case FILEQUIT:
log.debug("handling FILEQUIT event");
bhmf.dispose();
break;
case PROJECTCREATE:
this.createProject();
break;
case PROJECTDUPLICATE:
this.duplicateProject();
break;
// TODO Katzor.Marcus
case PROJECTIMPORT:
BHDataExchangeDialog importDialog = new BHDataExchangeDialog(bhmf,
true);
importDialog.setAction(IImportExport.IMP_PROJECT);
importDialog.setDescription(BHTranslator.getInstance().translate(
"DXMLImportDescription"));
importDialog.setVisible(true);
break;
// TODO Katzor.Marcus
case PROJECTEXPORT:
// Get selected node
if (bhmf.getBHTree().getSelectionPath() != null) {
BHTreeNode selectedNode = (BHTreeNode) bhmf.getBHTree()
.getSelectionPath().getLastPathComponent();
// Get DTOProject
if (selectedNode.getUserObject() instanceof DTOProject) {
// Create data exchange dialog
BHDataExchangeDialog dialog = new BHDataExchangeDialog(
bhmf, true);
dialog.setAction(IImportExport.EXP_PROJECT);
dialog.setModel((IDTO<?>) selectedNode.getUserObject());
dialog.setDescription(BHTranslator.getInstance().translate(
"DExpFileFormatSel"));
dialog.setVisible(true);
} else {
// TODO Katzor.Marcus Show Message
}
} else {
// TODO Katzor.Marcus Show Message
}
break;
case PROJECTREMOVE:
int pr_choice = JOptionPane.showConfirmDialog(bhmf, Services
.getTranslator().translate("Pproject_delete"), Services
.getTranslator().translate("Pdelete"),
JOptionPane.YES_NO_OPTION);
if (pr_choice == JOptionPane.YES_OPTION) {
TreePath currentRemoveProjectSelection = bhmf.getBHTree()
.getSelectionPath();
if (currentRemoveProjectSelection != null) {
BHTreeNode removeProjectNode = (BHTreeNode) bhmf
.getBHTree().getSelectionPath()
.getLastPathComponent();
if (removeProjectNode.getUserObject() instanceof DTOProject) {
((BHTreeModel) bhmf.getBHTree().getModel())
.removeNodeFromParent(removeProjectNode);
projectRepoManager
.removeProject((DTOProject) removeProjectNode
.getUserObject());
} else {
BHStatusBar.getInstance().setHint(
BHTranslator.getInstance().translate(
"EisSelectProject"), true);
}
}
}
break;
case SCENARIOCREATE:
this.createScenario();
break;
case SCENARIODUPLICATE:
this.duplicateScenario();
break;
case SCENARIOMOVE:
// TODO Drag&Drop
break;
case SCENARIOREMOVE:
int sc_choice = JOptionPane.showConfirmDialog(bhmf, Services
.getTranslator().translate("Pscenario_delete"), Services
.getTranslator().translate("Pdelete"),
JOptionPane.YES_NO_OPTION);
if (sc_choice == JOptionPane.YES_OPTION) {
TreePath currentRemoveScenarioSelection = bhmf.getBHTree()
.getSelectionPath();
if (currentRemoveScenarioSelection != null) {
BHTreeNode removeScenarioNode = (BHTreeNode) bhmf
.getBHTree().getSelectionPath()
.getLastPathComponent();
if (removeScenarioNode.getUserObject() instanceof DTOScenario) {
((BHTreeModel) bhmf.getBHTree().getModel())
.removeNodeFromParent(removeScenarioNode);
((DTOScenario) ((BHTreeNode) removeScenarioNode
.getParent()).getUserObject())
.removeChild((DTOPeriod) removeScenarioNode
.getUserObject());
} else {
BHStatusBar.getInstance().setHint(
BHTranslator.getInstance().translate(
"EisSelectScenario"), true);
}
}
}
break;
case PERIODCREATE:
this.createPeriod();
break;
case PERIODDUPLICATE:
this.duplicatePeriod();
break;
case PERIODREMOVE:
int pe_choice = JOptionPane.showConfirmDialog(bhmf, Services
.getTranslator().translate("Pperiod_delete"), Services
.getTranslator().translate("Pdelete"),
JOptionPane.YES_NO_OPTION);
if (pe_choice == JOptionPane.YES_OPTION) {
TreePath currentRemovePeriodSelection = bhmf.getBHTree()
.getSelectionPath();
if (currentRemovePeriodSelection != null) {
BHTreeNode removeNode = (BHTreeNode) bhmf.getBHTree()
.getSelectionPath().getLastPathComponent();
if (removeNode.getUserObject() instanceof DTOPeriod) {
((BHTreeModel) bhmf.getBHTree().getModel())
.removeNodeFromParent(removeNode);
((DTOPeriod) ((BHTreeNode) removeNode.getParent())
.getUserObject()).remove((DTOPeriod) removeNode
.getUserObject());
} else {
BHStatusBar.getInstance().setHint(
BHTranslator.getInstance().translate(
"EisSelectPeriod"), true);
}
}
}
break;
case BILANZGUVSHOW:
// TODO Prüfen und ggf. implementieren!
break;
case BILANZGUVCREATE:
// TODO Prüfen und ggf. implementieren!
break;
case BILANZGUVIMPORT:
// TODO Prüfen und ggf. implementieren!
break;
case BILANZGUVREMOVE:
// TODO Prüfen und ggf. implementieren!
break;
case OPTIONSCHANGE:
new BHOptionDialog();
break;
case HELPUSERHELP:
openUserHelp("userhelp");
break;
case HELPMATHHELP:
openUserHelp("mathhelp");
break;
case HELPINFO:
// TODO Prüfen und ggf. implementieren!
break;
case HELPDEBUG:
new BHHelpDebugDialog();
break;
case TOOLBARNEW:
log.debug("handling FILENEW event");
this.fileNew();
break;
case TOOLBAROPEN:
log.debug("handling TOOLBAROPEN event");
this.fileOpen();
break;
case TOOLBARSAVE:
log.debug("handling TOOLBARSAVE event");
Services.firePlatformEvent(new PlatformEvent(
PlatformActionListener.class, PlatformEvent.Type.SAVE));
break;
case TOOLBARADDPRO:
this.createProject();
break;
case TOOLBARADDS:
this.createScenario();
break;
case TOOLBARADDPER:
this.createPeriod();
break;
case TOOLBARREMOVE:
this.toolbarRemove();
break;
case POPUPREMOVE:
this.toolbarRemove();
break;
case POPUPADD:
this.popupAdd();
break;
case POPUPDUPLICATE:
this.popupDuplicate();
break;
default:
// TODO implementieren?
break;
}
}
|
diff --git a/src/cmu/arktweetnlp/io/JsonTweetReader.java b/src/cmu/arktweetnlp/io/JsonTweetReader.java
index c0b5382..7ef0e2c 100644
--- a/src/cmu/arktweetnlp/io/JsonTweetReader.java
+++ b/src/cmu/arktweetnlp/io/JsonTweetReader.java
@@ -1,51 +1,50 @@
package cmu.arktweetnlp.io;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Iterator;
import cmu.arktweetnlp.util.BasicFileIO;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
*
*/
public class JsonTweetReader {
ObjectMapper mapper;
public JsonTweetReader() {
mapper = new ObjectMapper();
}
/**
* Get the text from a raw Tweet JSON string.
*
* @param tweetJson
* @return null if there is no text field, or invalid JSON.
*/
public String getText(String tweetJson) {
JsonNode rootNode;
- // wtf, we have to allocate a new parser for every line?
try {
rootNode = mapper.readValue(tweetJson, JsonNode.class);
} catch (JsonParseException e) {
return null;
} catch (IOException e) {
return null;
}
if (! rootNode.isObject())
return null;
JsonNode textValue = rootNode.get("text");
if (textValue==null)
return null;
return textValue.asText();
}
}
| true | true | public String getText(String tweetJson) {
JsonNode rootNode;
// wtf, we have to allocate a new parser for every line?
try {
rootNode = mapper.readValue(tweetJson, JsonNode.class);
} catch (JsonParseException e) {
return null;
} catch (IOException e) {
return null;
}
if (! rootNode.isObject())
return null;
JsonNode textValue = rootNode.get("text");
if (textValue==null)
return null;
return textValue.asText();
}
| public String getText(String tweetJson) {
JsonNode rootNode;
try {
rootNode = mapper.readValue(tweetJson, JsonNode.class);
} catch (JsonParseException e) {
return null;
} catch (IOException e) {
return null;
}
if (! rootNode.isObject())
return null;
JsonNode textValue = rootNode.get("text");
if (textValue==null)
return null;
return textValue.asText();
}
|
diff --git a/src/java/org/infoglue/cms/util/graphics/ThumbnailGenerator.java b/src/java/org/infoglue/cms/util/graphics/ThumbnailGenerator.java
index 755312b80..3c7c36e6b 100755
--- a/src/java/org/infoglue/cms/util/graphics/ThumbnailGenerator.java
+++ b/src/java/org/infoglue/cms/util/graphics/ThumbnailGenerator.java
@@ -1,117 +1,117 @@
/* ===============================================================================
*
* Part of the InfoGlue Content Management Platform (www.infoglue.org)
*
* ===============================================================================
*
* Copyright (C)
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 2, as published by the
* Free Software Foundation. See the file LICENSE.html for more information.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY, including the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc. / 59 Temple
* Place, Suite 330 / Boston, MA 02111-1307 / USA.
*
* ===============================================================================
*/
package org.infoglue.cms.util.graphics;
import java.awt.*;
import java.awt.image.*;
import java.io.*;
import org.infoglue.cms.util.CmsLogger;
import org.infoglue.cms.util.CmsPropertyHandler;
public class ThumbnailGenerator
{
public ThumbnailGenerator()
{
}
private void execCmd(String command) throws Exception
{
CmsLogger.logSevere(command);
String line;
Process p = Runtime.getRuntime().exec(command);
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = input.readLine()) != null)
{
CmsLogger.logSevere(line);
}
input.close();
}
public void transform(String originalFile, String thumbnailFile, int thumbWidth, int thumbHeight, int quality) throws Exception
{
Image image = javax.imageio.ImageIO.read(new File(originalFile));
double thumbRatio = (double)thumbWidth / (double)thumbHeight;
int imageWidth = image.getWidth(null);
int imageHeight = image.getHeight(null);
double imageRatio = (double)imageWidth / (double)imageHeight;
if (thumbRatio < imageRatio)
{
thumbHeight = (int)(thumbWidth / imageRatio);
}
else
{
thumbWidth = (int)(thumbHeight * imageRatio);
}
if(imageWidth < thumbWidth && imageHeight < thumbHeight)
{
thumbWidth = imageWidth;
thumbHeight = imageHeight;
}
else if(imageWidth < thumbWidth)
thumbWidth = imageWidth;
else if(imageHeight < thumbHeight)
thumbHeight = imageHeight;
if(thumbWidth < 1)
thumbWidth = 1;
if(thumbHeight < 1)
thumbHeight = 1;
- if(CmsPropertyHandler.getProperty("externalThumbnailGeneration") != null)
+ if(CmsPropertyHandler.getProperty("externalThumbnailGeneration") != null && CmsPropertyHandler.getProperty("externalThumbnailGeneration").equalsIgnoreCase(""))
{
String[] args = new String[5];
args[0] = CmsPropertyHandler.getProperty("externalThumbnailGeneration");
args[1] = "-resize";
args[2] = String.valueOf(thumbWidth) + "x" + String.valueOf(thumbHeight);
args[3] = originalFile;
args[4] = thumbnailFile;
try
{
Process p = Runtime.getRuntime().exec(args);
p.waitFor();
}
catch(InterruptedException e)
{
new Exception("Error resizing image for thumbnail", e);
}
}
else
{
BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics2D = thumbImage.createGraphics();
graphics2D.setBackground(Color.WHITE);
graphics2D.setPaint(Color.WHITE);
graphics2D.fillRect(0, 0, thumbWidth, thumbHeight);
graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null);
javax.imageio.ImageIO.write(thumbImage, "JPG", new File(thumbnailFile));
}
}
}
| true | true | public void transform(String originalFile, String thumbnailFile, int thumbWidth, int thumbHeight, int quality) throws Exception
{
Image image = javax.imageio.ImageIO.read(new File(originalFile));
double thumbRatio = (double)thumbWidth / (double)thumbHeight;
int imageWidth = image.getWidth(null);
int imageHeight = image.getHeight(null);
double imageRatio = (double)imageWidth / (double)imageHeight;
if (thumbRatio < imageRatio)
{
thumbHeight = (int)(thumbWidth / imageRatio);
}
else
{
thumbWidth = (int)(thumbHeight * imageRatio);
}
if(imageWidth < thumbWidth && imageHeight < thumbHeight)
{
thumbWidth = imageWidth;
thumbHeight = imageHeight;
}
else if(imageWidth < thumbWidth)
thumbWidth = imageWidth;
else if(imageHeight < thumbHeight)
thumbHeight = imageHeight;
if(thumbWidth < 1)
thumbWidth = 1;
if(thumbHeight < 1)
thumbHeight = 1;
if(CmsPropertyHandler.getProperty("externalThumbnailGeneration") != null)
{
String[] args = new String[5];
args[0] = CmsPropertyHandler.getProperty("externalThumbnailGeneration");
args[1] = "-resize";
args[2] = String.valueOf(thumbWidth) + "x" + String.valueOf(thumbHeight);
args[3] = originalFile;
args[4] = thumbnailFile;
try
{
Process p = Runtime.getRuntime().exec(args);
p.waitFor();
}
catch(InterruptedException e)
{
new Exception("Error resizing image for thumbnail", e);
}
}
else
{
BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics2D = thumbImage.createGraphics();
graphics2D.setBackground(Color.WHITE);
graphics2D.setPaint(Color.WHITE);
graphics2D.fillRect(0, 0, thumbWidth, thumbHeight);
graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null);
javax.imageio.ImageIO.write(thumbImage, "JPG", new File(thumbnailFile));
}
}
| public void transform(String originalFile, String thumbnailFile, int thumbWidth, int thumbHeight, int quality) throws Exception
{
Image image = javax.imageio.ImageIO.read(new File(originalFile));
double thumbRatio = (double)thumbWidth / (double)thumbHeight;
int imageWidth = image.getWidth(null);
int imageHeight = image.getHeight(null);
double imageRatio = (double)imageWidth / (double)imageHeight;
if (thumbRatio < imageRatio)
{
thumbHeight = (int)(thumbWidth / imageRatio);
}
else
{
thumbWidth = (int)(thumbHeight * imageRatio);
}
if(imageWidth < thumbWidth && imageHeight < thumbHeight)
{
thumbWidth = imageWidth;
thumbHeight = imageHeight;
}
else if(imageWidth < thumbWidth)
thumbWidth = imageWidth;
else if(imageHeight < thumbHeight)
thumbHeight = imageHeight;
if(thumbWidth < 1)
thumbWidth = 1;
if(thumbHeight < 1)
thumbHeight = 1;
if(CmsPropertyHandler.getProperty("externalThumbnailGeneration") != null && CmsPropertyHandler.getProperty("externalThumbnailGeneration").equalsIgnoreCase(""))
{
String[] args = new String[5];
args[0] = CmsPropertyHandler.getProperty("externalThumbnailGeneration");
args[1] = "-resize";
args[2] = String.valueOf(thumbWidth) + "x" + String.valueOf(thumbHeight);
args[3] = originalFile;
args[4] = thumbnailFile;
try
{
Process p = Runtime.getRuntime().exec(args);
p.waitFor();
}
catch(InterruptedException e)
{
new Exception("Error resizing image for thumbnail", e);
}
}
else
{
BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics2D = thumbImage.createGraphics();
graphics2D.setBackground(Color.WHITE);
graphics2D.setPaint(Color.WHITE);
graphics2D.fillRect(0, 0, thumbWidth, thumbHeight);
graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null);
javax.imageio.ImageIO.write(thumbImage, "JPG", new File(thumbnailFile));
}
}
|
diff --git a/portsensor.core/com/portsensor/main/Main.java b/portsensor.core/com/portsensor/main/Main.java
index 79a9215..628d398 100644
--- a/portsensor.core/com/portsensor/main/Main.java
+++ b/portsensor.core/com/portsensor/main/Main.java
@@ -1,381 +1,379 @@
/**
* @author Jeff Standen <[email protected]>
*/
package com.portsensor.main;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.math.BigInteger;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.TreeMap;
import org.hyperic.sigar.CpuPerc;
import org.hyperic.sigar.FileSystemUsage;
import org.hyperic.sigar.ProcCpu;
import org.hyperic.sigar.ProcCredName;
import org.hyperic.sigar.ProcMem;
import org.hyperic.sigar.ProcState;
import org.hyperic.sigar.ProcTime;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;
import org.hyperic.sigar.Who;
import org.hyperic.sigar.cmd.Ps;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import com.portsensor.command.CommandFactory;
import com.portsensor.sensor.ConsoleSensor;
import com.portsensor.sensor.SensorCheck;
import com.portsensor.testers.PortTester;
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
if(1 == args.length && args[0].equalsIgnoreCase("--config")) {
ConfigurationBuilder.autoConfigure();
} else if(0 == args.length || 1 == args.length && args[0].equalsIgnoreCase("--help")) {
Main.printHelp();
} else {
Configuration cfg = Configuration.getInstance();
if(!cfg.load(args[0])) {
System.exit(1);
}
// if(2 == args.length && args[1].equalsIgnoreCase("--list-devices")) {
// cfg.printDevices();
// } else if(3 == args.length && args[1].equalsIgnoreCase("--list-sensors")) {
// cfg.printSensors(args[0], args[2]);
// } else if(6 == args.length && args[1].equalsIgnoreCase("--add-sensor")) {
// cfg.addPort(args[0], args[2], args[3], args[4], args[5]);
// } else if(4 == args.length && args[1].equalsIgnoreCase("--remove-sensor")) {
// cfg.removeSensor(args[0], args[2], args[3]);
if(2 == args.length && args[1].equalsIgnoreCase("--test")) {
String xml = Main.getXML();
System.out.println(xml);
} else if(1==args.length) {
String xml = Main.getXML();
Main.postXML(xml);
} else {
Main.printHelp();
}
}
System.exit(0);
}
private static void printHelp() {
System.out.println("Syntax:");
System.out.println("<config file>");
System.out.println("<config file> --test");
// System.out.println("<config file> --list-devices");
// System.out.println("<config file> --list-sensors <device>");
// System.out.println("<config file> --add-sensor <device> <host> <service> <port>");
// System.out.println("<config file> --remove-sensor <device> <sensor>");
// System.out.println("--config");
System.out.println("--help");
}
private static String getXML() {
Configuration cfg = Configuration.getInstance();
Sigar sigar = new Sigar();
// Formatters
NumberFormat loadFormatter = DecimalFormat.getNumberInstance();
loadFormatter.setMaximumFractionDigits(2);
SimpleDateFormat dateFormatter = new SimpleDateFormat("MMM dd HH:mm");
// Output XML
Element eRoot = new Element("sensors");
Document doc = new Document(eRoot);
Iterator<ConsoleSensor> iCommands = cfg.getSensors().iterator();
while(iCommands.hasNext()) {
ConsoleSensor sensor = iCommands.next();
String cmd = sensor.getCommand();
char cStatus = SensorCheck.STATUS_OK;
String sSensorOut = "";
String sOut = "";
// [TODO] Move commands into their own classes
// Built-in commands
if(cmd.startsWith("#PORT")) {
String[] parts = cmd.split(" ");
String sHost = parts[1];
Integer iPort = Integer.parseInt(parts[2]);
sSensorOut = (PortTester.testPort(sHost, iPort)) ? "UP" : "DOWN";
} else if(cmd.startsWith("#WHO")) {
StringBuilder str = new StringBuilder();
try {
Who[] whos = sigar.getWhoList();
for (Who who : whos) {
String host = who.getHost();
str.append(String.format("%s\t%s\t%s%s\n",
new Object[] {
who.getUser(),
who.getDevice(),
dateFormatter.format(new Date(who.getTime()*1000)),
((0 == host.length()) ? "" : String.format("\t(%s)", host))
}));
}
sSensorOut = str.toString();
} catch (SigarException e) {
e.printStackTrace();
}
} else if(cmd.startsWith("#DF")) {
String[] parts = cmd.split(" ");
String sFileSystem = parts[1];
try {
FileSystemUsage usage = sigar.getFileSystemUsage(sFileSystem);
sSensorOut = Double.toString(usage.getUsePercent());
} catch (SigarException e) {
e.printStackTrace();
}
} else if(cmd.startsWith("#LOAD")) {
try {
double loads[] = sigar.getLoadAverage();
sSensorOut = String.valueOf(loadFormatter.format(loads[0])); // 1 min avg
} catch (SigarException e) {
e.printStackTrace();
}
} else if(cmd.startsWith("#PS")) {
String[] parts = cmd.split(" ");
String sSortBy = (2==parts.length) ? parts[1] : "mem";
try {
StringBuilder str = new StringBuilder();
String sProcUser = "";
// Sort by the desired criteria
TreeMap<Long, String> pidTree = new TreeMap<Long, String>(Collections.reverseOrder());
long[] pids = sigar.getProcList();
// Do we need to prime the CPU measurements?
if(sSortBy.equals("cpu")) {
for(long pid : pids) {
try {
ProcCpu procCpu = sigar.getProcCpu(pid);
procCpu.getPercent();
} catch(Exception e) {
// ignore things we can't measure
}
}
}
try {
Thread.sleep(1000L);
} catch(Exception e) {}
// [TODO] Ignore our own pid?
for(long pid : pids) {
try {
ProcCredName procUser = sigar.getProcCredName(pid);
sProcUser = procUser.getUser();
ProcState procState = sigar.getProcState(pid);
if(sSortBy.equals("cpu")) { // [TODO] Format CPU time
ProcCpu procCpu = sigar.getProcCpu(pid);
Double perc = procCpu.getPercent();
String out = String.format("%s\t[%d]\t%s\t(%s)\n", new Object[] {
CpuPerc.format(perc),
pid,
//ProcUtil.getDescription(sigar, pid),
procState.getName(),
sProcUser
});
Long hash = new Double(perc * 100 * 1000000).longValue();
while(pidTree.containsKey(hash)) {
hash++;
}
pidTree.put(hash, out);
} else if(sSortBy.equals("time")) { // [TODO] Format run time
ProcTime procTime = sigar.getProcTime(pid);
String out = String.format("%s\t[%d]\t%s\t(%s)\n", new Object[] {
Ps.getCpuTime(procTime.getTotal()),
pid,
procState.getName(),
//ProcUtil.getDescription(sigar, pid),
sProcUser
});
pidTree.put(procTime.getTotal(), out);
} else { // "mem"
ProcMem procMem = sigar.getProcMem(pid);
String out = String.format("%s\t[%d]\t%s\t(%s)\n", new Object[] {
Sigar.formatSize(procMem.getResident()),
pid,
procState.getName(),
//ProcUtil.getDescription(sigar, pid),
sProcUser
});
pidTree.put(procMem.getResident(), out);
}
} catch(Exception e) { /* ignore partial processes */ }
}
// Make sure we have 5 max items
while(pidTree.size() > 5) {
pidTree.remove(pidTree.lastKey());
}
// Lazy load the remaining items
for(String process : pidTree.values()) {
str.append(process);
}
sSensorOut = str.toString();
} catch (SigarException e) {
e.printStackTrace();
}
} else { // command wrapper
sSensorOut = CommandFactory.quickRun(cmd).trim();
}
try {
// Typecast as requested
if(sensor.getType().equals(ConsoleSensor.TYPE_NUMBER)) {
sSensorOut = String.valueOf(DecimalFormat.getNumberInstance().parse(sSensorOut).longValue());
} else if(sensor.getType().equals(ConsoleSensor.TYPE_PERCENT)) {
if(sSensorOut.endsWith("%")) {
} else {
double percent = DecimalFormat.getNumberInstance().parse(sSensorOut).doubleValue();
sSensorOut = String.valueOf(Math.round(100*percent)) + "%";
}
} else if (sensor.getType().equals(ConsoleSensor.TYPE_DECIMAL)) {
sSensorOut = String.valueOf(DecimalFormat.getNumberInstance().parse(sSensorOut).doubleValue());
} else if (sensor.getType().equals(ConsoleSensor.TYPE_UPDOWN)) {
sSensorOut = String.valueOf(sSensorOut);
}
if(sOut.equals(""))
sOut = sSensorOut;
// Rule check
Iterator<SensorCheck> i = sensor.getChecks().iterator();
while(i.hasNext()) {
SensorCheck rule = i.next();
if(rule.check(sSensorOut)) {
cStatus = rule.getStatus();
sOut = rule.getMessage() + ": " + sSensorOut;
}
}
} catch(ParseException pe) {
pe.printStackTrace();
cStatus = SensorCheck.STATUS_CRITICAL;
sOut = "Sensor result was not a valid "+sensor.getType();
}
- if(0 != sSensorOut.length()) {
- Element e = new Element("sensor");
- e.setAttribute("id", sensor.getId());
- e.addContent(new Element("name").setText(sensor.getName()));
- e.addContent(new Element("status").setText(String.valueOf(cStatus)));
- e.addContent(new Element("metric").setText(sSensorOut));
- e.addContent(new Element("metric_type").setText(sensor.getType()));
- e.addContent(new Element("output").setText(sOut));
- eRoot.addContent(e);
- }
+ Element e = new Element("sensor");
+ e.setAttribute("id", sensor.getId());
+ e.addContent(new Element("name").setText(sensor.getName()));
+ e.addContent(new Element("status").setText(String.valueOf(cStatus)));
+ e.addContent(new Element("metric").setText(sSensorOut));
+ e.addContent(new Element("metric_type").setText(sensor.getType()));
+ e.addContent(new Element("output").setText(sOut));
+ eRoot.addContent(e);
}
XMLOutputter outputter = new XMLOutputter();
outputter.setFormat(Format.getPrettyFormat());
return outputter.outputString(doc);
}
private static void postXML(String xml) {
Configuration cfg = Configuration.getInstance();
URL url = null;
MessageDigest mdMD5 = null;
String username = cfg.getSetting(Configuration.SETTING_USERNAME, "");
String secret_key = cfg.getSetting(Configuration.SETTING_SECRET_KEY, "");
String post_url = cfg.getSetting(Configuration.SETTING_POST_URL, "");
try {
mdMD5 = MessageDigest.getInstance("MD5");
url = new URL(post_url);
} catch(Exception e) {
System.out.println("Error: " + e.getMessage());
System.exit(1);
}
String httpDate = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z").format(new Date()).toString();
String url_query = (null==url.getQuery()) ? "" : url.getQuery();
System.out.println("Posting to " + post_url);
try {
// Password MD5
mdMD5.update(secret_key.getBytes("iso-8859-1"));
String password_hash = new BigInteger(1,mdMD5.digest()).toString(16);
while(password_hash.length() < 32) // pad
password_hash = "0"+password_hash;
// Construct data
String stringToSign = "POST\n"+httpDate+"\n"+url.getPath()+"\n"+url_query+"\n"+xml+"\n"+password_hash+"\n";
mdMD5.update(stringToSign.getBytes("iso-8859-1"));
String signedString = String.valueOf(new BigInteger(1,mdMD5.digest()).toString(16));
// Send data
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.addRequestProperty("Cerb5-Auth", username+":"+signedString);
conn.addRequestProperty("Date", httpDate);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(xml);
wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
// Process line...
System.out.println(line);
}
wr.close();
rd.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
| true | true | private static String getXML() {
Configuration cfg = Configuration.getInstance();
Sigar sigar = new Sigar();
// Formatters
NumberFormat loadFormatter = DecimalFormat.getNumberInstance();
loadFormatter.setMaximumFractionDigits(2);
SimpleDateFormat dateFormatter = new SimpleDateFormat("MMM dd HH:mm");
// Output XML
Element eRoot = new Element("sensors");
Document doc = new Document(eRoot);
Iterator<ConsoleSensor> iCommands = cfg.getSensors().iterator();
while(iCommands.hasNext()) {
ConsoleSensor sensor = iCommands.next();
String cmd = sensor.getCommand();
char cStatus = SensorCheck.STATUS_OK;
String sSensorOut = "";
String sOut = "";
// [TODO] Move commands into their own classes
// Built-in commands
if(cmd.startsWith("#PORT")) {
String[] parts = cmd.split(" ");
String sHost = parts[1];
Integer iPort = Integer.parseInt(parts[2]);
sSensorOut = (PortTester.testPort(sHost, iPort)) ? "UP" : "DOWN";
} else if(cmd.startsWith("#WHO")) {
StringBuilder str = new StringBuilder();
try {
Who[] whos = sigar.getWhoList();
for (Who who : whos) {
String host = who.getHost();
str.append(String.format("%s\t%s\t%s%s\n",
new Object[] {
who.getUser(),
who.getDevice(),
dateFormatter.format(new Date(who.getTime()*1000)),
((0 == host.length()) ? "" : String.format("\t(%s)", host))
}));
}
sSensorOut = str.toString();
} catch (SigarException e) {
e.printStackTrace();
}
} else if(cmd.startsWith("#DF")) {
String[] parts = cmd.split(" ");
String sFileSystem = parts[1];
try {
FileSystemUsage usage = sigar.getFileSystemUsage(sFileSystem);
sSensorOut = Double.toString(usage.getUsePercent());
} catch (SigarException e) {
e.printStackTrace();
}
} else if(cmd.startsWith("#LOAD")) {
try {
double loads[] = sigar.getLoadAverage();
sSensorOut = String.valueOf(loadFormatter.format(loads[0])); // 1 min avg
} catch (SigarException e) {
e.printStackTrace();
}
} else if(cmd.startsWith("#PS")) {
String[] parts = cmd.split(" ");
String sSortBy = (2==parts.length) ? parts[1] : "mem";
try {
StringBuilder str = new StringBuilder();
String sProcUser = "";
// Sort by the desired criteria
TreeMap<Long, String> pidTree = new TreeMap<Long, String>(Collections.reverseOrder());
long[] pids = sigar.getProcList();
// Do we need to prime the CPU measurements?
if(sSortBy.equals("cpu")) {
for(long pid : pids) {
try {
ProcCpu procCpu = sigar.getProcCpu(pid);
procCpu.getPercent();
} catch(Exception e) {
// ignore things we can't measure
}
}
}
try {
Thread.sleep(1000L);
} catch(Exception e) {}
// [TODO] Ignore our own pid?
for(long pid : pids) {
try {
ProcCredName procUser = sigar.getProcCredName(pid);
sProcUser = procUser.getUser();
ProcState procState = sigar.getProcState(pid);
if(sSortBy.equals("cpu")) { // [TODO] Format CPU time
ProcCpu procCpu = sigar.getProcCpu(pid);
Double perc = procCpu.getPercent();
String out = String.format("%s\t[%d]\t%s\t(%s)\n", new Object[] {
CpuPerc.format(perc),
pid,
//ProcUtil.getDescription(sigar, pid),
procState.getName(),
sProcUser
});
Long hash = new Double(perc * 100 * 1000000).longValue();
while(pidTree.containsKey(hash)) {
hash++;
}
pidTree.put(hash, out);
} else if(sSortBy.equals("time")) { // [TODO] Format run time
ProcTime procTime = sigar.getProcTime(pid);
String out = String.format("%s\t[%d]\t%s\t(%s)\n", new Object[] {
Ps.getCpuTime(procTime.getTotal()),
pid,
procState.getName(),
//ProcUtil.getDescription(sigar, pid),
sProcUser
});
pidTree.put(procTime.getTotal(), out);
} else { // "mem"
ProcMem procMem = sigar.getProcMem(pid);
String out = String.format("%s\t[%d]\t%s\t(%s)\n", new Object[] {
Sigar.formatSize(procMem.getResident()),
pid,
procState.getName(),
//ProcUtil.getDescription(sigar, pid),
sProcUser
});
pidTree.put(procMem.getResident(), out);
}
} catch(Exception e) { /* ignore partial processes */ }
}
// Make sure we have 5 max items
while(pidTree.size() > 5) {
pidTree.remove(pidTree.lastKey());
}
// Lazy load the remaining items
for(String process : pidTree.values()) {
str.append(process);
}
sSensorOut = str.toString();
} catch (SigarException e) {
e.printStackTrace();
}
} else { // command wrapper
sSensorOut = CommandFactory.quickRun(cmd).trim();
}
try {
// Typecast as requested
if(sensor.getType().equals(ConsoleSensor.TYPE_NUMBER)) {
sSensorOut = String.valueOf(DecimalFormat.getNumberInstance().parse(sSensorOut).longValue());
} else if(sensor.getType().equals(ConsoleSensor.TYPE_PERCENT)) {
if(sSensorOut.endsWith("%")) {
} else {
double percent = DecimalFormat.getNumberInstance().parse(sSensorOut).doubleValue();
sSensorOut = String.valueOf(Math.round(100*percent)) + "%";
}
} else if (sensor.getType().equals(ConsoleSensor.TYPE_DECIMAL)) {
sSensorOut = String.valueOf(DecimalFormat.getNumberInstance().parse(sSensorOut).doubleValue());
} else if (sensor.getType().equals(ConsoleSensor.TYPE_UPDOWN)) {
sSensorOut = String.valueOf(sSensorOut);
}
if(sOut.equals(""))
sOut = sSensorOut;
// Rule check
Iterator<SensorCheck> i = sensor.getChecks().iterator();
while(i.hasNext()) {
SensorCheck rule = i.next();
if(rule.check(sSensorOut)) {
cStatus = rule.getStatus();
sOut = rule.getMessage() + ": " + sSensorOut;
}
}
} catch(ParseException pe) {
pe.printStackTrace();
cStatus = SensorCheck.STATUS_CRITICAL;
sOut = "Sensor result was not a valid "+sensor.getType();
}
if(0 != sSensorOut.length()) {
Element e = new Element("sensor");
e.setAttribute("id", sensor.getId());
e.addContent(new Element("name").setText(sensor.getName()));
e.addContent(new Element("status").setText(String.valueOf(cStatus)));
e.addContent(new Element("metric").setText(sSensorOut));
e.addContent(new Element("metric_type").setText(sensor.getType()));
e.addContent(new Element("output").setText(sOut));
eRoot.addContent(e);
}
}
XMLOutputter outputter = new XMLOutputter();
outputter.setFormat(Format.getPrettyFormat());
return outputter.outputString(doc);
}
| private static String getXML() {
Configuration cfg = Configuration.getInstance();
Sigar sigar = new Sigar();
// Formatters
NumberFormat loadFormatter = DecimalFormat.getNumberInstance();
loadFormatter.setMaximumFractionDigits(2);
SimpleDateFormat dateFormatter = new SimpleDateFormat("MMM dd HH:mm");
// Output XML
Element eRoot = new Element("sensors");
Document doc = new Document(eRoot);
Iterator<ConsoleSensor> iCommands = cfg.getSensors().iterator();
while(iCommands.hasNext()) {
ConsoleSensor sensor = iCommands.next();
String cmd = sensor.getCommand();
char cStatus = SensorCheck.STATUS_OK;
String sSensorOut = "";
String sOut = "";
// [TODO] Move commands into their own classes
// Built-in commands
if(cmd.startsWith("#PORT")) {
String[] parts = cmd.split(" ");
String sHost = parts[1];
Integer iPort = Integer.parseInt(parts[2]);
sSensorOut = (PortTester.testPort(sHost, iPort)) ? "UP" : "DOWN";
} else if(cmd.startsWith("#WHO")) {
StringBuilder str = new StringBuilder();
try {
Who[] whos = sigar.getWhoList();
for (Who who : whos) {
String host = who.getHost();
str.append(String.format("%s\t%s\t%s%s\n",
new Object[] {
who.getUser(),
who.getDevice(),
dateFormatter.format(new Date(who.getTime()*1000)),
((0 == host.length()) ? "" : String.format("\t(%s)", host))
}));
}
sSensorOut = str.toString();
} catch (SigarException e) {
e.printStackTrace();
}
} else if(cmd.startsWith("#DF")) {
String[] parts = cmd.split(" ");
String sFileSystem = parts[1];
try {
FileSystemUsage usage = sigar.getFileSystemUsage(sFileSystem);
sSensorOut = Double.toString(usage.getUsePercent());
} catch (SigarException e) {
e.printStackTrace();
}
} else if(cmd.startsWith("#LOAD")) {
try {
double loads[] = sigar.getLoadAverage();
sSensorOut = String.valueOf(loadFormatter.format(loads[0])); // 1 min avg
} catch (SigarException e) {
e.printStackTrace();
}
} else if(cmd.startsWith("#PS")) {
String[] parts = cmd.split(" ");
String sSortBy = (2==parts.length) ? parts[1] : "mem";
try {
StringBuilder str = new StringBuilder();
String sProcUser = "";
// Sort by the desired criteria
TreeMap<Long, String> pidTree = new TreeMap<Long, String>(Collections.reverseOrder());
long[] pids = sigar.getProcList();
// Do we need to prime the CPU measurements?
if(sSortBy.equals("cpu")) {
for(long pid : pids) {
try {
ProcCpu procCpu = sigar.getProcCpu(pid);
procCpu.getPercent();
} catch(Exception e) {
// ignore things we can't measure
}
}
}
try {
Thread.sleep(1000L);
} catch(Exception e) {}
// [TODO] Ignore our own pid?
for(long pid : pids) {
try {
ProcCredName procUser = sigar.getProcCredName(pid);
sProcUser = procUser.getUser();
ProcState procState = sigar.getProcState(pid);
if(sSortBy.equals("cpu")) { // [TODO] Format CPU time
ProcCpu procCpu = sigar.getProcCpu(pid);
Double perc = procCpu.getPercent();
String out = String.format("%s\t[%d]\t%s\t(%s)\n", new Object[] {
CpuPerc.format(perc),
pid,
//ProcUtil.getDescription(sigar, pid),
procState.getName(),
sProcUser
});
Long hash = new Double(perc * 100 * 1000000).longValue();
while(pidTree.containsKey(hash)) {
hash++;
}
pidTree.put(hash, out);
} else if(sSortBy.equals("time")) { // [TODO] Format run time
ProcTime procTime = sigar.getProcTime(pid);
String out = String.format("%s\t[%d]\t%s\t(%s)\n", new Object[] {
Ps.getCpuTime(procTime.getTotal()),
pid,
procState.getName(),
//ProcUtil.getDescription(sigar, pid),
sProcUser
});
pidTree.put(procTime.getTotal(), out);
} else { // "mem"
ProcMem procMem = sigar.getProcMem(pid);
String out = String.format("%s\t[%d]\t%s\t(%s)\n", new Object[] {
Sigar.formatSize(procMem.getResident()),
pid,
procState.getName(),
//ProcUtil.getDescription(sigar, pid),
sProcUser
});
pidTree.put(procMem.getResident(), out);
}
} catch(Exception e) { /* ignore partial processes */ }
}
// Make sure we have 5 max items
while(pidTree.size() > 5) {
pidTree.remove(pidTree.lastKey());
}
// Lazy load the remaining items
for(String process : pidTree.values()) {
str.append(process);
}
sSensorOut = str.toString();
} catch (SigarException e) {
e.printStackTrace();
}
} else { // command wrapper
sSensorOut = CommandFactory.quickRun(cmd).trim();
}
try {
// Typecast as requested
if(sensor.getType().equals(ConsoleSensor.TYPE_NUMBER)) {
sSensorOut = String.valueOf(DecimalFormat.getNumberInstance().parse(sSensorOut).longValue());
} else if(sensor.getType().equals(ConsoleSensor.TYPE_PERCENT)) {
if(sSensorOut.endsWith("%")) {
} else {
double percent = DecimalFormat.getNumberInstance().parse(sSensorOut).doubleValue();
sSensorOut = String.valueOf(Math.round(100*percent)) + "%";
}
} else if (sensor.getType().equals(ConsoleSensor.TYPE_DECIMAL)) {
sSensorOut = String.valueOf(DecimalFormat.getNumberInstance().parse(sSensorOut).doubleValue());
} else if (sensor.getType().equals(ConsoleSensor.TYPE_UPDOWN)) {
sSensorOut = String.valueOf(sSensorOut);
}
if(sOut.equals(""))
sOut = sSensorOut;
// Rule check
Iterator<SensorCheck> i = sensor.getChecks().iterator();
while(i.hasNext()) {
SensorCheck rule = i.next();
if(rule.check(sSensorOut)) {
cStatus = rule.getStatus();
sOut = rule.getMessage() + ": " + sSensorOut;
}
}
} catch(ParseException pe) {
pe.printStackTrace();
cStatus = SensorCheck.STATUS_CRITICAL;
sOut = "Sensor result was not a valid "+sensor.getType();
}
Element e = new Element("sensor");
e.setAttribute("id", sensor.getId());
e.addContent(new Element("name").setText(sensor.getName()));
e.addContent(new Element("status").setText(String.valueOf(cStatus)));
e.addContent(new Element("metric").setText(sSensorOut));
e.addContent(new Element("metric_type").setText(sensor.getType()));
e.addContent(new Element("output").setText(sOut));
eRoot.addContent(e);
}
XMLOutputter outputter = new XMLOutputter();
outputter.setFormat(Format.getPrettyFormat());
return outputter.outputString(doc);
}
|
diff --git a/app/controllers/PageViewer.java b/app/controllers/PageViewer.java
index 517d2f6..68a1998 100644
--- a/app/controllers/PageViewer.java
+++ b/app/controllers/PageViewer.java
@@ -1,106 +1,106 @@
package controllers;
import elasticsearch.SearchJob;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.logging.Level;
import java.util.logging.Logger;
import models.Page;
import models.PageRef;
import models.Tag;
import play.Play;
import play.mvc.Controller;
/**
*
* @author keruspe
*/
@SuppressWarnings("unchecked")
public class PageViewer extends Controller {
public static Page getGoodPage(List<Page> pages) {
- if(pages == null)
+ if(pages == null || pages.isEmpty())
return null;
Page page = null;
switch (pages.size()) {
case 0:
return null;
case 1:
page = pages.get(0);
if (!page.published)
return null;
return page;
default:
List<Locale> locales = I18nController.getLanguages();
for (Locale locale : locales) {
// Try exact Locale or exact language no matter the country
for (Page candidat : pages) {
if ((candidat.language.equals(locale) || (!locale.getCountry().equals("") && candidat.language.getLanguage().equals(locale.getLanguage()))) && candidat.published)
return candidat;
}
}
if (page == null || !page.published) {
for (Page candidat : pages) {
if (candidat.published)
return candidat; // pick up first published for now
}
}
return null;
}
}
public static Page getGoodPageByUrlId(String urlId) {
return PageViewer.getGoodPage(Page.getPagesByUrlId(urlId));
}
public static void index() {
PageViewer.page(Play.configuration.getProperty("fmkcms.index", "index"));
}
public static void page(String urlId) {
List<Page> pages = Page.getPagesByUrlId(urlId);
Page page = PageViewer.getGoodPage(pages);
if (page == null)
notFound(urlId);
if (request.headers.get("accept").value().contains("json"))
renderJSON(page);
Boolean isConnected = session.contains("username");
render(page, isConnected);
}
public static void pagesTag(String tagName) {
Tag tag = Tag.findOrCreateByName(tagName); /* avoid NPE in view ... */
List<PageRef> pageRefs = PageRef.findTaggedWith(tag);
List<Page> pages = new ArrayList<Page>();
Page page = null;
for (PageRef pageRef : pageRefs) {
page = PageViewer.getGoodPage(Page.getPagesByPageRef(pageRef));
if (page != null)
pages.add(page);
}
render(pages, tag);
}
public static void searchPage(String q) {
if (request.isNew) {
Future<String> task = new SearchJob(q).now();
request.args.put("task", task);
waitFor(task);
}
try {
renderText(((Future<String>) request.args.get("task")).get());
} catch (InterruptedException ex) {
Logger.getLogger(PageController.class.getName()).log(Level.SEVERE, null, ex);
} catch (ExecutionException ex) {
Logger.getLogger(PageController.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
| true | true | public static Page getGoodPage(List<Page> pages) {
if(pages == null)
return null;
Page page = null;
switch (pages.size()) {
case 0:
return null;
case 1:
page = pages.get(0);
if (!page.published)
return null;
return page;
default:
List<Locale> locales = I18nController.getLanguages();
for (Locale locale : locales) {
// Try exact Locale or exact language no matter the country
for (Page candidat : pages) {
if ((candidat.language.equals(locale) || (!locale.getCountry().equals("") && candidat.language.getLanguage().equals(locale.getLanguage()))) && candidat.published)
return candidat;
}
}
if (page == null || !page.published) {
for (Page candidat : pages) {
if (candidat.published)
return candidat; // pick up first published for now
}
}
return null;
}
}
| public static Page getGoodPage(List<Page> pages) {
if(pages == null || pages.isEmpty())
return null;
Page page = null;
switch (pages.size()) {
case 0:
return null;
case 1:
page = pages.get(0);
if (!page.published)
return null;
return page;
default:
List<Locale> locales = I18nController.getLanguages();
for (Locale locale : locales) {
// Try exact Locale or exact language no matter the country
for (Page candidat : pages) {
if ((candidat.language.equals(locale) || (!locale.getCountry().equals("") && candidat.language.getLanguage().equals(locale.getLanguage()))) && candidat.published)
return candidat;
}
}
if (page == null || !page.published) {
for (Page candidat : pages) {
if (candidat.published)
return candidat; // pick up first published for now
}
}
return null;
}
}
|
diff --git a/src/main/java/cn/beihangsoft/parkingsystem/model/ParkingArea.java b/src/main/java/cn/beihangsoft/parkingsystem/model/ParkingArea.java
index 5e85427..194b8fd 100644
--- a/src/main/java/cn/beihangsoft/parkingsystem/model/ParkingArea.java
+++ b/src/main/java/cn/beihangsoft/parkingsystem/model/ParkingArea.java
@@ -1,26 +1,27 @@
package cn.beihangsoft.parkingsystem.model;
public class ParkingArea {
private int freeSlots;
private int totalSlots;
public ParkingArea(int totalSlots) {
this.totalSlots = totalSlots;
+ this.freeSlots = totalSlots;
}
public int getSlotsNum() {
return freeSlots;
}
public void setSlotsNum(int slotsNum) {
this.freeSlots = slotsNum;
}
public int getTotalSlots() {
return totalSlots;
}
public void setTotalSlots(int totalSlots) {
this.totalSlots = totalSlots;
}
}
| true | true | public ParkingArea(int totalSlots) {
this.totalSlots = totalSlots;
}
| public ParkingArea(int totalSlots) {
this.totalSlots = totalSlots;
this.freeSlots = totalSlots;
}
|
diff --git a/src/main/java/org/mybatis/spring/SqlSessionFactoryBean.java b/src/main/java/org/mybatis/spring/SqlSessionFactoryBean.java
index 8a92f736..a7b26ee1 100644
--- a/src/main/java/org/mybatis/spring/SqlSessionFactoryBean.java
+++ b/src/main/java/org/mybatis/spring/SqlSessionFactoryBean.java
@@ -1,360 +1,360 @@
/*
* Copyright 2010 The myBatis Team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mybatis.spring;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.ibatis.builder.xml.XMLConfigBuilder;
import org.apache.ibatis.builder.xml.XMLMapperBuilder;
import org.apache.ibatis.logging.Log;
import org.apache.ibatis.logging.LogFactory;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.parsing.XNode;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.mybatis.spring.transaction.SpringManagedTransactionFactory;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.NestedIOException;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
/**
* {@link org.springframework.beans.factory.FactoryBean} that creates an MyBatis
* {@link org.apache.ibatis.session.SqlSessionFactory}. This is the usual way to set up a shared
* MyBatis SqlSessionFactory in a Spring application context; the SqlSessionFactory can then be
* passed to MyBatis-based DAOs via dependency injection.
*
* Either {@link org.springframework.jdbc.datasource.DataSourceTransactionManager} or
* {@link org.springframework.transaction.jta.JtaTransactionManager} can be used for transaction
* demarcation in combination with a SqlSessionFactory. JTA should be used for transactions
* which span multiple databases or when container managed transactions (CMT) are being used.
*
* Allows for specifying a DataSource at the SqlSessionFactory level. This is preferable to per-DAO
* DataSource references, as it allows for lazy loading and avoids repeated DataSource references in
* every DAO.
*
* @see #setConfigLocation
* @see #setDataSource
* @see org.mybatis.spring.SqlSessionTemplate#setSqlSessionFactory
* @see org.mybatis.spring.SqlSessionTemplate#setDataSource
* @version $Id$
*/
public class SqlSessionFactoryBean implements FactoryBean<SqlSessionFactory>, InitializingBean {
private final Log logger = LogFactory.getLog(getClass());
private Resource configLocation;
private Resource[] mapperLocations;
private DataSource dataSource;
private Class<? extends TransactionFactory> transactionFactoryClass = SpringManagedTransactionFactory.class;
private Properties transactionFactoryProperties;
private Properties configurationProperties;
private SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
private SqlSessionFactory sqlSessionFactory;
private String environment = SqlSessionFactoryBean.class.getSimpleName();
public SqlSessionFactoryBean() {}
/**
* Set the location of the MyBatis SqlSessionFactory config file. A typical value is
* "WEB-INF/mybatis-configuration.xml".
*/
public void setConfigLocation(Resource configLocation) {
this.configLocation = configLocation;
}
/**
* Set locations of MyBatis mapper files that are going to be merged into the SqlSessionFactory
* configuration at runtime.
*
* This is an alternative to specifying "<sqlmapper>" entries in an MyBatis config file.
* This property being based on Spring's resource abstraction also allows for specifying
* resource patterns here: e.g. "classpath*:sqlmap/*-mapper.xml".
*/
public void setMapperLocations(Resource[] mapperLocations) {
this.mapperLocations = mapperLocations;
}
/**
* Set optional properties to be passed into the SqlSession configuration, as alternative to a
* <code><properties></code> tag in the configuration xml file. This will be used to
* resolve placeholders in the config file.
*
* @see org.apache.ibatis.session.Configuration#getVariables
*/
public void setConfigurationProperties(Properties sqlSessionFactoryProperties) {
this.configurationProperties = sqlSessionFactoryProperties;
}
/**
* Set the JDBC DataSource that this instance should manage transactions for. The DataSource
* should match the one used by the SqlSessionFactory: for example, you could specify the same
* JNDI DataSource for both.
*
* A transactional JDBC Connection for this DataSource will be provided to application code
* accessing this DataSource directly via DataSourceUtils or DataSourceTransactionManager.
*
* The DataSource specified here should be the target DataSource to manage transactions for, not
* a TransactionAwareDataSourceProxy. Only data access code may work with
* TransactionAwareDataSourceProxy, while the transaction manager needs to work on the
* underlying target DataSource. If there's nevertheless a TransactionAwareDataSourceProxy
* passed in, it will be unwrapped to extract its target DataSource.
*
* @see org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy
* @see org.springframework.jdbc.datasource.DataSourceUtils
* @see org.springframework.jdbc.datasource.DataSourceTransactionManager
*/
public void setDataSource(DataSource dataSource) {
if (dataSource instanceof TransactionAwareDataSourceProxy) {
// If we got a TransactionAwareDataSourceProxy, we need to perform
// transactions for its underlying target DataSource, else data
// access code won't see properly exposed transactions (i.e.
// transactions for the target DataSource).
this.dataSource = ((TransactionAwareDataSourceProxy) dataSource).getTargetDataSource();
} else {
this.dataSource = dataSource;
}
}
/**
* Sets the SqlSessionFactoryBuilder to use when creating the SqlSessionFactory.
*
* This is mainly meant for testing so that mock SqlSessionFactory classes can be injected. By
* default, SqlSessionFactoryBuilder creates <code>DefaultSqlSessionFactory<code> instances.
*
* @see org.apache.ibatis.session.SqlSessionFactoryBuilder
*/
public void setSqlSessionFactoryBuilder(SqlSessionFactoryBuilder sqlSessionFactoryBuilder) {
this.sqlSessionFactoryBuilder = sqlSessionFactoryBuilder;
}
/**
* Set the MyBatis TransactionFactory class to use. Default is
* <code>SpringManagedTransactionFactory</code>.
*
* The default SpringManagedTransactionFactory should be appropriate for all cases: be it Spring
* transaction management, EJB CMT or plain JTA. If there is no active transaction, SqlSession
* operations will execute SQL statements non-transactionally.
*
* <b>It is strongly recommended to use the default TransactionFactory.</b> If not used, any
* attempt at getting an SqlSession through Spring's MyBatis framework will throw an exception if
* a transaction is active.
*
* @see #setDataSource
* @see #setTransactionFactoryProperties(java.util.Properties)
* @see org.apache.ibatis.transaction.TransactionFactory
* @see org.mybatis.spring.transaction.SpringManagedTransactionFactory
* @see org.apache.ibatis.transaction.Transaction
* @see org.mybatis.spring.SqlSessionUtils#getSqlSession(SqlSessionFactory,
* DataSource, org.apache.ibatis.session.ExecutorType)
* @param <TF> the MyBatis TransactionFactory type
* @param transactionFactoryClass the MyBatis TransactionFactory class to use
*/
public <TF extends TransactionFactory> void setTransactionFactoryClass(Class<TF> transactionFactoryClass) {
this.transactionFactoryClass = transactionFactoryClass;
}
/**
* Set properties to be passed to the TransactionFactory instance used by this
* SqlSessionFactory.
*
* The default SpringManagedTransactionFactory does not have any user configurable properties.
*
* @see org.apache.ibatis.transaction.TransactionFactory#setProperties(java.util.Properties)
* @see org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory
* @see org.apache.ibatis.transaction.managed.ManagedTransactionFactory
*/
public void setTransactionFactoryProperties(Properties transactionFactoryProperties) {
this.transactionFactoryProperties = transactionFactoryProperties;
}
/**
* <b>NOTE:</b> This class <em>overrides</em> any Environment you have set in the MyBatis config
* file. This is used only as a placeholder name. The default value is
* <code>SqlSessionFactoryBean.class.getSimpleName()</code>.
*
* @param environment the environment name
*/
public void setEnvironment(String environment) {
this.environment = environment;
}
public void afterPropertiesSet() throws Exception {
Assert.notNull(dataSource, "Property 'dataSource' is required");
Assert.notNull(sqlSessionFactoryBuilder, "Property 'sqlSessionFactoryBuilder' is required");
Assert.notNull(transactionFactoryClass, "Property 'transactionFactoryClass' is required");
sqlSessionFactory = buildSqlSessionFactory();
}
/**
* Build a SqlSessionFactory instance.
*
* The default implementation uses the standard MyBatis {@link XMLConfigBuilder} API to build a
* SqlSessionFactory instance based on an Reader.
*
* @see org.apache.ibatis.builder.xml.XMLConfigBuilder#parse()
*
* @return SqlSessionFactory
*
* @throws IOException if loading the config file failed
* @throws IllegalAccessException
* @throws InstantiationException
*/
protected SqlSessionFactory buildSqlSessionFactory() throws IOException, IllegalAccessException,
InstantiationException {
XMLConfigBuilder xmlConfigBuilder;
Configuration configuration;
if (configLocation != null) {
Reader reader = null;
try {
reader = new InputStreamReader(configLocation.getInputStream());
// Null environment causes the configuration to use the default.
// This will be overwritten below regardless.
xmlConfigBuilder = new XMLConfigBuilder(reader, null, configurationProperties);
configuration = xmlConfigBuilder.parse();
} catch (IOException ex) {
throw new NestedIOException("Failed to parse config resource: " + configLocation, ex);
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException ignored) {
}
}
}
if (logger.isDebugEnabled()) {
logger.debug("Parsed configuration file: '" + configLocation + "'");
}
} else {
if (logger.isDebugEnabled()) {
logger.debug("Property 'configLocation' not specified, using default MyBatis Configuration");
}
configuration = new Configuration();
}
TransactionFactory transactionFactory = this.transactionFactoryClass.newInstance(); // expose IllegalAccessException, InstantiationException
transactionFactory.setProperties(transactionFactoryProperties);
Environment environment = new Environment(this.environment, transactionFactory, this.dataSource);
configuration.setEnvironment(environment);
if (!ObjectUtils.isEmpty(mapperLocations)) {
Map<String, XNode> sqlFragments = new HashMap<String, XNode>();
for (Resource mapperLocation : mapperLocations) {
if (mapperLocation == null) {
continue;
}
// MyBatis holds a Map using "resource" name as a key.
// If a mapper file is loaded, it searches for a mapper interface type.
// If the type is found then it tries to load the mapper file again looking for this:
//
// String xmlResource = type.getName().replace('.', '/') + ".xml";
//
// So if a mapper interface exists, resource cannot be an absolute path.
// Otherwise MyBatis will throw an exception because
// it will load both a mapper interface and the mapper xml file,
// and throw an exception telling that a mapperStatement cannot be loaded twice.
String path;
if (mapperLocation instanceof ClassPathResource) {
path = ClassPathResource.class.cast(mapperLocation).getPath();
} else {
// this won't work if there is also a mapper interface in classpath
- path = mapperLocation.getURI().getPath();
+ path = mapperLocation.toString();
}
Reader reader = null;
try {
reader = new InputStreamReader(mapperLocation.getInputStream());
XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(reader, configuration, path, sqlFragments);
xmlMapperBuilder.parse();
} catch (Exception e) {
throw new NestedIOException("Failed to parse mapping resource: '" + mapperLocation + "'", e);
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException ignored) {
}
}
}
if (logger.isDebugEnabled()) {
logger.debug("Parsed mapper file: '" + mapperLocation + "'");
}
}
} else {
if (logger.isDebugEnabled()) {
logger.debug("Property 'mapperLocations' was not specified, only MyBatis mapper files specified in the config xml were loaded");
}
}
return sqlSessionFactoryBuilder.build(configuration);
}
/**
* {@inheritDoc}
*/
public SqlSessionFactory getObject() throws Exception {
if (sqlSessionFactory == null) {
afterPropertiesSet();
}
return sqlSessionFactory;
}
/**
* {@inheritDoc}
*/
public Class<? extends SqlSessionFactory> getObjectType() {
return sqlSessionFactory == null ? SqlSessionFactory.class : sqlSessionFactory.getClass();
}
/**
* {@inheritDoc}
*/
public boolean isSingleton() {
return true;
}
}
| true | true | protected SqlSessionFactory buildSqlSessionFactory() throws IOException, IllegalAccessException,
InstantiationException {
XMLConfigBuilder xmlConfigBuilder;
Configuration configuration;
if (configLocation != null) {
Reader reader = null;
try {
reader = new InputStreamReader(configLocation.getInputStream());
// Null environment causes the configuration to use the default.
// This will be overwritten below regardless.
xmlConfigBuilder = new XMLConfigBuilder(reader, null, configurationProperties);
configuration = xmlConfigBuilder.parse();
} catch (IOException ex) {
throw new NestedIOException("Failed to parse config resource: " + configLocation, ex);
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException ignored) {
}
}
}
if (logger.isDebugEnabled()) {
logger.debug("Parsed configuration file: '" + configLocation + "'");
}
} else {
if (logger.isDebugEnabled()) {
logger.debug("Property 'configLocation' not specified, using default MyBatis Configuration");
}
configuration = new Configuration();
}
TransactionFactory transactionFactory = this.transactionFactoryClass.newInstance(); // expose IllegalAccessException, InstantiationException
transactionFactory.setProperties(transactionFactoryProperties);
Environment environment = new Environment(this.environment, transactionFactory, this.dataSource);
configuration.setEnvironment(environment);
if (!ObjectUtils.isEmpty(mapperLocations)) {
Map<String, XNode> sqlFragments = new HashMap<String, XNode>();
for (Resource mapperLocation : mapperLocations) {
if (mapperLocation == null) {
continue;
}
// MyBatis holds a Map using "resource" name as a key.
// If a mapper file is loaded, it searches for a mapper interface type.
// If the type is found then it tries to load the mapper file again looking for this:
//
// String xmlResource = type.getName().replace('.', '/') + ".xml";
//
// So if a mapper interface exists, resource cannot be an absolute path.
// Otherwise MyBatis will throw an exception because
// it will load both a mapper interface and the mapper xml file,
// and throw an exception telling that a mapperStatement cannot be loaded twice.
String path;
if (mapperLocation instanceof ClassPathResource) {
path = ClassPathResource.class.cast(mapperLocation).getPath();
} else {
// this won't work if there is also a mapper interface in classpath
path = mapperLocation.getURI().getPath();
}
Reader reader = null;
try {
reader = new InputStreamReader(mapperLocation.getInputStream());
XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(reader, configuration, path, sqlFragments);
xmlMapperBuilder.parse();
} catch (Exception e) {
throw new NestedIOException("Failed to parse mapping resource: '" + mapperLocation + "'", e);
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException ignored) {
}
}
}
if (logger.isDebugEnabled()) {
logger.debug("Parsed mapper file: '" + mapperLocation + "'");
}
}
} else {
if (logger.isDebugEnabled()) {
logger.debug("Property 'mapperLocations' was not specified, only MyBatis mapper files specified in the config xml were loaded");
}
}
return sqlSessionFactoryBuilder.build(configuration);
}
| protected SqlSessionFactory buildSqlSessionFactory() throws IOException, IllegalAccessException,
InstantiationException {
XMLConfigBuilder xmlConfigBuilder;
Configuration configuration;
if (configLocation != null) {
Reader reader = null;
try {
reader = new InputStreamReader(configLocation.getInputStream());
// Null environment causes the configuration to use the default.
// This will be overwritten below regardless.
xmlConfigBuilder = new XMLConfigBuilder(reader, null, configurationProperties);
configuration = xmlConfigBuilder.parse();
} catch (IOException ex) {
throw new NestedIOException("Failed to parse config resource: " + configLocation, ex);
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException ignored) {
}
}
}
if (logger.isDebugEnabled()) {
logger.debug("Parsed configuration file: '" + configLocation + "'");
}
} else {
if (logger.isDebugEnabled()) {
logger.debug("Property 'configLocation' not specified, using default MyBatis Configuration");
}
configuration = new Configuration();
}
TransactionFactory transactionFactory = this.transactionFactoryClass.newInstance(); // expose IllegalAccessException, InstantiationException
transactionFactory.setProperties(transactionFactoryProperties);
Environment environment = new Environment(this.environment, transactionFactory, this.dataSource);
configuration.setEnvironment(environment);
if (!ObjectUtils.isEmpty(mapperLocations)) {
Map<String, XNode> sqlFragments = new HashMap<String, XNode>();
for (Resource mapperLocation : mapperLocations) {
if (mapperLocation == null) {
continue;
}
// MyBatis holds a Map using "resource" name as a key.
// If a mapper file is loaded, it searches for a mapper interface type.
// If the type is found then it tries to load the mapper file again looking for this:
//
// String xmlResource = type.getName().replace('.', '/') + ".xml";
//
// So if a mapper interface exists, resource cannot be an absolute path.
// Otherwise MyBatis will throw an exception because
// it will load both a mapper interface and the mapper xml file,
// and throw an exception telling that a mapperStatement cannot be loaded twice.
String path;
if (mapperLocation instanceof ClassPathResource) {
path = ClassPathResource.class.cast(mapperLocation).getPath();
} else {
// this won't work if there is also a mapper interface in classpath
path = mapperLocation.toString();
}
Reader reader = null;
try {
reader = new InputStreamReader(mapperLocation.getInputStream());
XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(reader, configuration, path, sqlFragments);
xmlMapperBuilder.parse();
} catch (Exception e) {
throw new NestedIOException("Failed to parse mapping resource: '" + mapperLocation + "'", e);
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException ignored) {
}
}
}
if (logger.isDebugEnabled()) {
logger.debug("Parsed mapper file: '" + mapperLocation + "'");
}
}
} else {
if (logger.isDebugEnabled()) {
logger.debug("Property 'mapperLocations' was not specified, only MyBatis mapper files specified in the config xml were loaded");
}
}
return sqlSessionFactoryBuilder.build(configuration);
}
|
diff --git a/org/jruby/parser/DefaultRubyParser.java b/org/jruby/parser/DefaultRubyParser.java
index 4df8b0c32..91802c1ac 100644
--- a/org/jruby/parser/DefaultRubyParser.java
+++ b/org/jruby/parser/DefaultRubyParser.java
@@ -1,2934 +1,2934 @@
// line 2 "parse.y"
/*
* DefaultRubyParser.java - JRuby - Parser constructed from parse.y
* Created on 07. Oktober 2001, 01:28
*
* Copyright (C) 2001 Jan Arne Petersen, Stefan Matthias Aust
* Jan Arne Petersen <[email protected]>
* Stefan Matthias Aust <[email protected]>
*
* JRuby - http://jruby.sourceforge.net
*
* This file is part of JRuby
*
* JRuby is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* JRuby is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with JRuby; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
package org.jruby.parser;
import java.util.*;
import java.io.*;
import org.jruby.*;
import org.jruby.nodes.*;
import org.jruby.runtime.*;
import org.jruby.util.*;
public class DefaultRubyParser implements RubyParser {
private Ruby ruby;
private ParserHelper ph;
private NodeFactory nf;
private DefaultRubyScanner rs;
public DefaultRubyParser(Ruby ruby) {
this.ruby = ruby;
this.ph = ruby.getParserHelper();
this.nf = new NodeFactory(ruby);
this.rs = new DefaultRubyScanner(ruby);
}
/*
%union {
Node *node;
VALUE val;
ID id;
int num;
struct RVarmap *vars;
}
*/
// line 62 "-"
// %token constants
public static final int kCLASS = 257;
public static final int kMODULE = 258;
public static final int kDEF = 259;
public static final int kUNDEF = 260;
public static final int kBEGIN = 261;
public static final int kRESCUE = 262;
public static final int kENSURE = 263;
public static final int kEND = 264;
public static final int kIF = 265;
public static final int kUNLESS = 266;
public static final int kTHEN = 267;
public static final int kELSIF = 268;
public static final int kELSE = 269;
public static final int kCASE = 270;
public static final int kWHEN = 271;
public static final int kWHILE = 272;
public static final int kUNTIL = 273;
public static final int kFOR = 274;
public static final int kBREAK = 275;
public static final int kNEXT = 276;
public static final int kREDO = 277;
public static final int kRETRY = 278;
public static final int kIN = 279;
public static final int kDO = 280;
public static final int kDO_COND = 281;
public static final int kDO_BLOCK = 282;
public static final int kRETURN = 283;
public static final int kYIELD = 284;
public static final int kSUPER = 285;
public static final int kSELF = 286;
public static final int kNIL = 287;
public static final int kTRUE = 288;
public static final int kFALSE = 289;
public static final int kAND = 290;
public static final int kOR = 291;
public static final int kNOT = 292;
public static final int kIF_MOD = 293;
public static final int kUNLESS_MOD = 294;
public static final int kWHILE_MOD = 295;
public static final int kUNTIL_MOD = 296;
public static final int kRESCUE_MOD = 297;
public static final int kALIAS = 298;
public static final int kDEFINED = 299;
public static final int klBEGIN = 300;
public static final int klEND = 301;
public static final int k__LINE__ = 302;
public static final int k__FILE__ = 303;
public static final int tIDENTIFIER = 304;
public static final int tFID = 305;
public static final int tGVAR = 306;
public static final int tIVAR = 307;
public static final int tCONSTANT = 308;
public static final int tCVAR = 309;
public static final int tINTEGER = 310;
public static final int tFLOAT = 311;
public static final int tSTRING = 312;
public static final int tXSTRING = 313;
public static final int tREGEXP = 314;
public static final int tDSTRING = 315;
public static final int tDXSTRING = 316;
public static final int tDREGEXP = 317;
public static final int tNTH_REF = 318;
public static final int tBACK_REF = 319;
public static final int tUPLUS = 320;
public static final int tUMINUS = 321;
public static final int tPOW = 322;
public static final int tCMP = 323;
public static final int tEQ = 324;
public static final int tEQQ = 325;
public static final int tNEQ = 326;
public static final int tGEQ = 327;
public static final int tLEQ = 328;
public static final int tANDOP = 329;
public static final int tOROP = 330;
public static final int tMATCH = 331;
public static final int tNMATCH = 332;
public static final int tDOT2 = 333;
public static final int tDOT3 = 334;
public static final int tAREF = 335;
public static final int tASET = 336;
public static final int tLSHFT = 337;
public static final int tRSHFT = 338;
public static final int tCOLON2 = 339;
public static final int tCOLON3 = 340;
public static final int tOP_ASGN = 341;
public static final int tASSOC = 342;
public static final int tLPAREN = 343;
public static final int tLBRACK = 344;
public static final int tLBRACE = 345;
public static final int tSTAR = 346;
public static final int tAMPER = 347;
public static final int tSYMBEG = 348;
public static final int LAST_TOKEN = 349;
public static final int yyErrorCode = 256;
/** thrown for irrecoverable syntax errors and stack overflow.
*/
public static class yyException extends java.lang.Exception {
public yyException (String message) {
super(message);
}
}
/** must be implemented by a scanner object to supply input to the parser.
*/
public interface yyInput {
/** move on to next token.
@return false if positioned beyond tokens.
@throws IOException on input error.
*/
boolean advance () throws java.io.IOException;
/** classifies current token.
Should not be called if advance() returned false.
@return current %token or single character.
*/
int token ();
/** associated with current token.
Should not be called if advance() returned false.
@return value for token().
*/
Object value ();
}
/** simplified error message.
@see <a href="#yyerror(java.lang.String, java.lang.String[])">yyerror</a>
*/
public void yyerror (String message) {
yyerror(message, null);
}
/** (syntax) error message.
Can be overwritten to control message format.
@param message text to be displayed.
@param expected vector of acceptable tokens, if available.
*/
public void yyerror (String message, String[] expected) {
if (expected != null && expected.length > 0) {
System.err.print(message+", expecting");
for (int n = 0; n < expected.length; ++ n)
System.err.print(" "+expected[n]);
System.err.println();
} else
System.err.println(message);
}
/** debugging support, requires the package jay.yydebug.
Set to null to suppress debugging messages.
*/
protected static final int yyFinal = 1;
/** index-checked interface to yyName[].
@param token single character or %token value.
@return token name or [illegal] or [unknown].
*/
/** computes list of expected tokens on error by tracing the tables.
@param state for which to compute the list.
@return list of token names.
*/
protected String[] yyExpecting (int state) {
int token, n, len = 0;
boolean[] ok = new boolean[YyNameClass.yyName.length];
if ((n = YySindexClass.yySindex[state]) != 0)
for (token = n < 0 ? -n : 0;
token < YyNameClass.yyName.length && n+token < YyTableClass.yyTable.length; ++ token)
if (YyCheckClass.yyCheck[n+token] == token && !ok[token] && YyNameClass.yyName[token] != null) {
++ len;
ok[token] = true;
}
if ((n = YyRindexClass.yyRindex[state]) != 0)
for (token = n < 0 ? -n : 0;
token < YyNameClass.yyName.length && n+token < YyTableClass.yyTable.length; ++ token)
if (YyCheckClass.yyCheck[n+token] == token && !ok[token] && YyNameClass.yyName[token] != null) {
++ len;
ok[token] = true;
}
String result[] = new String[len];
for (n = token = 0; n < len; ++ token)
if (ok[token]) result[n++] = YyNameClass.yyName[token];
return result;
}
/** the generated parser, with debugging messages.
Maintains a state and a value stack, currently with fixed maximum size.
@param yyLex scanner.
@param yydebug debug message writer implementing yyDebug, or null.
@return result of the last reduction, if any.
@throws yyException on irrecoverable parse error.
*/
public Object yyparse (yyInput yyLex, Object yydebug)
throws java.io.IOException, yyException {
return yyparse(yyLex);
}
/** initial size and increment of the state/value stack [default 256].
This is not final so that it can be overwritten outside of invocations
of yyparse().
*/
protected int yyMax;
/** executed at the beginning of a reduce action.
Used as $$ = yyDefault($1), prior to the user-specified action, if any.
Can be overwritten to provide deep copy, etc.
@param first value for $1, or null.
@return first.
*/
protected Object yyDefault (Object first) {
return first;
}
/** the generated parser.
Maintains a state and a value stack, currently with fixed maximum size.
@param yyLex scanner.
@return result of the last reduction, if any.
@throws yyException on irrecoverable parse error.
*/
public Object yyparse (yyInput yyLex)
throws java.io.IOException, yyException {
if (yyMax <= 0) yyMax = 256; // initial size
int yyState = 0, yyStates[] = new int[yyMax]; // state stack
Object yyVal = null, yyVals[] = new Object[yyMax]; // value stack
int yyToken = -1; // current input
int yyErrorFlag = 0; // #tks to shift
yyLoop: for (int yyTop = 0;; ++ yyTop) {
if (yyTop >= yyStates.length) { // dynamically increase
int[] i = new int[yyStates.length+yyMax];
System.arraycopy(yyStates, 0, i, 0, yyStates.length);
yyStates = i;
Object[] o = new Object[yyVals.length+yyMax];
System.arraycopy(yyVals, 0, o, 0, yyVals.length);
yyVals = o;
}
yyStates[yyTop] = yyState;
yyVals[yyTop] = yyVal;
yyDiscarded: for (;;) { // discarding a token does not change stack
int yyN;
if ((yyN = YyDefRedClass.yyDefRed[yyState]) == 0) { // else [default] reduce (yyN)
if (yyToken < 0) {
yyToken = yyLex.advance() ? yyLex.token() : 0;
}
if ((yyN = YySindexClass.yySindex[yyState]) != 0 && (yyN += yyToken) >= 0
&& yyN < YyTableClass.yyTable.length && YyCheckClass.yyCheck[yyN] == yyToken) {
yyState = YyTableClass.yyTable[yyN]; // shift to yyN
yyVal = yyLex.value();
yyToken = -1;
if (yyErrorFlag > 0) -- yyErrorFlag;
continue yyLoop;
}
if ((yyN = YyRindexClass.yyRindex[yyState]) != 0 && (yyN += yyToken) >= 0
&& yyN < YyTableClass.yyTable.length && YyCheckClass.yyCheck[yyN] == yyToken)
yyN = YyTableClass.yyTable[yyN]; // reduce (yyN)
else
switch (yyErrorFlag) {
case 0:
yyerror("syntax error", yyExpecting(yyState));
case 1: case 2:
yyErrorFlag = 3;
do {
if ((yyN = YySindexClass.yySindex[yyStates[yyTop]]) != 0
&& (yyN += yyErrorCode) >= 0 && yyN < YyTableClass.yyTable.length
&& YyCheckClass.yyCheck[yyN] == yyErrorCode) {
yyState = YyTableClass.yyTable[yyN];
yyVal = yyLex.value();
continue yyLoop;
}
} while (-- yyTop >= 0);
throw new yyException("irrecoverable syntax error");
case 3:
if (yyToken == 0) {
throw new yyException("irrecoverable syntax error at end-of-file");
}
yyToken = -1;
continue yyDiscarded; // leave stack alone
}
}
int yyV = yyTop + 1-YyLenClass.yyLen[yyN];
yyVal = yyDefault(yyV > yyTop ? null : yyVals[yyV]);
switch (yyN) {
case 1:
// line 181 "parse.y"
{
yyVal = ruby.getDynamicVars();
ph.setLexState(LexState.EXPR_BEG);
ph.top_local_init();
if (ruby.getRubyClass() == ruby.getClasses().getObjectClass())
ph.setClassNest(0);
else
ph.setClassNest(1);
}
break;
case 2:
// line 191 "parse.y"
{
if (((Node)yyVals[0+yyTop]) != null && !ph.isCompileForEval()) {
/* last expression should not be void */
if (((Node)yyVals[0+yyTop]).getType() != Constants.NODE_BLOCK)
ph.void_expr(((Node)yyVals[0+yyTop]));
else {
Node node = ((Node)yyVals[0+yyTop]);
while (node.getNextNode() != null) {
node = node.getNextNode();
}
ph.void_expr(node.getHeadNode());
}
}
ph.setEvalTree(ph.block_append(ph.getEvalTree(), ((Node)yyVals[0+yyTop])));
ph.top_local_setup();
ph.setClassNest(0);
ruby.setDynamicVars(((RubyVarmap)yyVals[-1+yyTop]));
}
break;
case 3:
// line 211 "parse.y"
{
ph.void_stmts(((Node)yyVals[-1+yyTop]));
yyVal = ((Node)yyVals[-1+yyTop]);
}
break;
case 5:
// line 218 "parse.y"
{
yyVal = ph.newline_node(((Node)yyVals[0+yyTop]));
}
break;
case 6:
// line 222 "parse.y"
{
yyVal = ph.block_append(((Node)yyVals[-2+yyTop]), ph.newline_node(((Node)yyVals[0+yyTop])));
}
break;
case 7:
// line 226 "parse.y"
{
yyVal = ((Node)yyVals[0+yyTop]);
}
break;
case 8:
// line 230 "parse.y"
{ph.setLexState(LexState.EXPR_FNAME);}
break;
case 9:
// line 231 "parse.y"
{
if (ph.isInDef() || ph.isInSingle())
yyerror("alias within method");
yyVal = nf.newAlias(((RubyId)yyVals[-2+yyTop]), ((RubyId)yyVals[0+yyTop]));
}
break;
case 10:
// line 237 "parse.y"
{
if (ph.isInDef() || ph.isInSingle())
yyerror("alias within method");
yyVal = nf.newVAlias(((RubyId)yyVals[-1+yyTop]), ((RubyId)yyVals[0+yyTop]));
}
break;
case 11:
// line 243 "parse.y"
{
if (ph.isInDef() || ph.isInSingle())
yyerror("alias within method");
String buf = "$" + (char)((Node)yyVals[0+yyTop]).getNth();
yyVal = nf.newVAlias(((RubyId)yyVals[-1+yyTop]), ruby.intern(buf));
}
break;
case 12:
// line 250 "parse.y"
{
yyerror("can't make alias for the number variables");
yyVal = null; /*XXX 0*/
}
break;
case 13:
// line 255 "parse.y"
{
if (ph.isInDef() || ph.isInSingle())
yyerror("undef within method");
yyVal = ((Node)yyVals[0+yyTop]);
}
break;
case 14:
// line 261 "parse.y"
{
ph.value_expr(((Node)yyVals[0+yyTop]));
yyVal = nf.newIf(ph.cond(((Node)yyVals[0+yyTop])), ((Node)yyVals[-2+yyTop]), null);
ph.fixpos(yyVal, ((Node)yyVals[0+yyTop]));
}
break;
case 15:
// line 267 "parse.y"
{
ph.value_expr(((Node)yyVals[0+yyTop]));
yyVal = nf.newUnless(ph.cond(((Node)yyVals[0+yyTop])), ((Node)yyVals[-2+yyTop]), null);
ph.fixpos(yyVal, ((Node)yyVals[0+yyTop]));
}
break;
case 16:
// line 273 "parse.y"
{
ph.value_expr(((Node)yyVals[0+yyTop]));
if (((Node)yyVals[-2+yyTop]) != null && ((Node)yyVals[-2+yyTop]) instanceof BeginNode) {
yyVal = nf.newWhile(ph.cond(((Node)yyVals[0+yyTop])), ((Node)yyVals[-2+yyTop]).getBodyNode()); /* , 0*/
} else {
yyVal = nf.newWhile(ph.cond(((Node)yyVals[0+yyTop])), ((Node)yyVals[-2+yyTop])); /* , 1*/
}
}
break;
case 17:
// line 282 "parse.y"
{
ph.value_expr(((Node)yyVals[0+yyTop]));
if (((Node)yyVals[-2+yyTop]) != null && ((Node)yyVals[-2+yyTop]) instanceof BeginNode) {
yyVal = nf.newUntil(ph.cond(((Node)yyVals[0+yyTop])), ((Node)yyVals[-2+yyTop]).getBodyNode()); /* , 0*/
} else {
yyVal = nf.newUntil(ph.cond(((Node)yyVals[0+yyTop])), ((Node)yyVals[-2+yyTop])); /* , 1*/
}
}
break;
case 18:
// line 291 "parse.y"
{
yyVal = nf.newRescue(((Node)yyVals[-2+yyTop]), nf.newResBody(null,((Node)yyVals[0+yyTop]),null), null);
}
break;
case 19:
// line 295 "parse.y"
{
if (ph.isInDef() || ph.isInSingle()) {
yyerror("BEGIN in method");
}
ph.local_push();
}
break;
case 20:
// line 302 "parse.y"
{
ph.setEvalTreeBegin(ph.block_append(ph.getEvalTree(), nf.newPreExe(((Node)yyVals[-1+yyTop]))));
ph.local_pop();
yyVal = null; /*XXX 0;*/
}
break;
case 21:
// line 308 "parse.y"
{
if (ph.isCompileForEval() && (ph.isInDef() || ph.isInSingle())) {
yyerror("END in method; use at_exit");
}
yyVal = nf.newIter(null, nf.newPostExe(), ((Node)yyVals[-1+yyTop]));
}
break;
case 22:
// line 316 "parse.y"
{
ph.value_expr(((Node)yyVals[0+yyTop]));
yyVal = ph.node_assign(((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 23:
// line 321 "parse.y"
{
ph.value_expr(((Node)yyVals[0+yyTop]));
((Node)yyVals[-2+yyTop]).setValueNode(((Node)yyVals[0+yyTop]));
yyVal = ((Node)yyVals[-2+yyTop]);
}
break;
case 24:
// line 327 "parse.y"
{
yyVal = ph.node_assign(((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 26:
// line 333 "parse.y"
{
ph.value_expr(((Node)yyVals[0+yyTop]));
((Node)yyVals[-2+yyTop]).setValueNode(((Node)yyVals[0+yyTop]));
yyVal = ((Node)yyVals[-2+yyTop]);
}
break;
case 27:
// line 339 "parse.y"
{
if (!ph.isCompileForEval() && !ph.isInDef() && !ph.isInSingle())
yyerror("return appeared outside of method");
yyVal = nf.newReturn(ph.ret_args(((Node)yyVals[0+yyTop])));
}
break;
case 29:
// line 346 "parse.y"
{
yyVal = ph.logop(Constants.NODE_AND, ((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 30:
// line 350 "parse.y"
{
yyVal = ph.logop(Constants.NODE_OR, ((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 31:
// line 354 "parse.y"
{
ph.value_expr(((Node)yyVals[0+yyTop]));
yyVal = nf.newNot(ph.cond(((Node)yyVals[0+yyTop])));
}
break;
case 32:
// line 359 "parse.y"
{
yyVal = nf.newNot(ph.cond(((Node)yyVals[0+yyTop])));
}
break;
case 37:
// line 369 "parse.y"
{
ph.value_expr(((Node)yyVals[-3+yyTop]));
yyVal = ph.new_call(((Node)yyVals[-3+yyTop]), ((RubyId)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 38:
// line 374 "parse.y"
{
ph.value_expr(((Node)yyVals[-3+yyTop]));
yyVal = ph.new_call(((Node)yyVals[-3+yyTop]), ((RubyId)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 39:
// line 380 "parse.y"
{
yyVal = ph.new_fcall(((RubyId)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
ph.fixpos(yyVal, ((Node)yyVals[0+yyTop]));
}
break;
case 40:
// line 385 "parse.y"
{
ph.value_expr(((Node)yyVals[-3+yyTop]));
yyVal = ph.new_call(((Node)yyVals[-3+yyTop]), ((RubyId)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
ph.fixpos(yyVal, ((Node)yyVals[-3+yyTop]));
}
break;
case 41:
// line 391 "parse.y"
{
ph.value_expr(((Node)yyVals[-3+yyTop]));
yyVal = ph.new_call(((Node)yyVals[-3+yyTop]), ((RubyId)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
ph.fixpos(yyVal, ((Node)yyVals[-3+yyTop]));
}
break;
case 42:
// line 397 "parse.y"
{
if (!ph.isCompileForEval() && ph.isInDef() && ph.isInSingle())
yyerror("super called outside of method");
yyVal = ph.new_super(((Node)yyVals[0+yyTop]));
ph.fixpos(yyVal, ((Node)yyVals[0+yyTop]));
}
break;
case 43:
// line 404 "parse.y"
{
yyVal = nf.newYield(ph.ret_args(((Node)yyVals[0+yyTop])));
ph.fixpos(yyVal, ((Node)yyVals[0+yyTop]));
}
break;
case 45:
// line 411 "parse.y"
{
yyVal = ((Node)yyVals[-1+yyTop]);
}
break;
case 47:
// line 417 "parse.y"
{
yyVal = nf.newMAsgn(nf.newList(((Node)yyVals[-1+yyTop])), null);
}
break;
case 48:
// line 422 "parse.y"
{
yyVal = nf.newMAsgn(((Node)yyVals[0+yyTop]), null);
}
break;
case 49:
// line 426 "parse.y"
{
yyVal = nf.newMAsgn(ph.list_append(((Node)yyVals[-1+yyTop]),((Node)yyVals[0+yyTop])), null);
}
break;
case 50:
// line 430 "parse.y"
{
yyVal = nf.newMAsgn(((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 51:
// line 434 "parse.y"
{
yyVal = nf.newMAsgn(((Node)yyVals[-1+yyTop]), Node.MINUS_ONE);
}
break;
case 52:
// line 438 "parse.y"
{
yyVal = nf.newMAsgn(null, ((Node)yyVals[0+yyTop]));
}
break;
case 53:
// line 442 "parse.y"
{
yyVal = nf.newMAsgn(null, Node.MINUS_ONE);
}
break;
case 55:
// line 448 "parse.y"
{
yyVal = ((Node)yyVals[-1+yyTop]);
}
break;
case 56:
// line 453 "parse.y"
{
yyVal = nf.newList(((Node)yyVals[-1+yyTop]));
}
break;
case 57:
// line 457 "parse.y"
{
yyVal = ph.list_append(((Node)yyVals[-2+yyTop]), ((Node)yyVals[-1+yyTop]));
}
break;
case 58:
// line 462 "parse.y"
{
yyVal = ph.assignable(((RubyId)yyVals[0+yyTop]), null);
}
break;
case 59:
// line 466 "parse.y"
{
yyVal = ph.aryset(((Node)yyVals[-3+yyTop]), ((Node)yyVals[-1+yyTop]));
}
break;
case 60:
// line 470 "parse.y"
{
yyVal = ph.attrset(((Node)yyVals[-2+yyTop]), ((RubyId)yyVals[0+yyTop]));
}
break;
case 61:
// line 474 "parse.y"
{
yyVal = ph.attrset(((Node)yyVals[-2+yyTop]), ((RubyId)yyVals[0+yyTop]));
}
break;
case 62:
// line 478 "parse.y"
{
yyVal = ph.attrset(((Node)yyVals[-2+yyTop]), ((RubyId)yyVals[0+yyTop]));
}
break;
case 63:
// line 482 "parse.y"
{
ph.rb_backref_error(((Node)yyVals[0+yyTop]));
yyVal = null; /*XXX 0;*/
}
break;
case 64:
// line 488 "parse.y"
{
yyVal = ph.assignable(((RubyId)yyVals[0+yyTop]), null);
}
break;
case 65:
// line 492 "parse.y"
{
yyVal = ph.aryset(((Node)yyVals[-3+yyTop]), ((Node)yyVals[-1+yyTop]));
}
break;
case 66:
// line 496 "parse.y"
{
yyVal = ph.attrset(((Node)yyVals[-2+yyTop]), ((RubyId)yyVals[0+yyTop]));
}
break;
case 67:
// line 500 "parse.y"
{
yyVal = ph.attrset(((Node)yyVals[-2+yyTop]), ((RubyId)yyVals[0+yyTop]));
}
break;
case 68:
// line 504 "parse.y"
{
yyVal = ph.attrset(((Node)yyVals[-2+yyTop]), ((RubyId)yyVals[0+yyTop]));
}
break;
case 69:
// line 508 "parse.y"
{
ph.rb_backref_error(((Node)yyVals[0+yyTop]));
yyVal = null; /*XXX 0;*/
}
break;
case 70:
// line 514 "parse.y"
{
yyerror("class/module name must be CONSTANT");
}
break;
case 75:
// line 523 "parse.y"
{
ph.setLexState(LexState.EXPR_END);
yyVal = ((RubyId)yyVals[0+yyTop]);
}
break;
case 76:
// line 528 "parse.y"
{
ph.setLexState(LexState.EXPR_END);
yyVal = yyVals[0+yyTop];
}
break;
case 79:
// line 537 "parse.y"
{
yyVal = nf.newUndef(((RubyId)yyVals[0+yyTop]));
}
break;
case 80:
// line 540 "parse.y"
{ph.setLexState(LexState.EXPR_FNAME);}
break;
case 81:
// line 541 "parse.y"
{
yyVal = ph.block_append(((Node)yyVals[-3+yyTop]), nf.newUndef(((RubyId)yyVals[0+yyTop])));
}
break;
case 82:
// line 545 "parse.y"
{ yyVal = RubyId.newId(ruby, '|'); }
break;
case 83:
// line 546 "parse.y"
{ yyVal = RubyId.newId(ruby, '^'); }
break;
case 84:
// line 547 "parse.y"
{ yyVal = RubyId.newId(ruby, '&'); }
break;
case 85:
// line 548 "parse.y"
{ yyVal = RubyId.newId(ruby, tCMP); }
break;
case 86:
// line 549 "parse.y"
{ yyVal = RubyId.newId(ruby, tEQ); }
break;
case 87:
// line 550 "parse.y"
{ yyVal = RubyId.newId(ruby, tEQQ); }
break;
case 88:
// line 551 "parse.y"
{ yyVal = RubyId.newId(ruby, tMATCH); }
break;
case 89:
// line 552 "parse.y"
{ yyVal = RubyId.newId(ruby, '>'); }
break;
case 90:
// line 553 "parse.y"
{ yyVal = RubyId.newId(ruby, tGEQ); }
break;
case 91:
// line 554 "parse.y"
{ yyVal = RubyId.newId(ruby, '<'); }
break;
case 92:
// line 555 "parse.y"
{ yyVal = RubyId.newId(ruby, tLEQ); }
break;
case 93:
// line 556 "parse.y"
{ yyVal = RubyId.newId(ruby, tLSHFT); }
break;
case 94:
// line 557 "parse.y"
{ yyVal = RubyId.newId(ruby, tRSHFT); }
break;
case 95:
// line 558 "parse.y"
{ yyVal = RubyId.newId(ruby, '+'); }
break;
case 96:
// line 559 "parse.y"
{ yyVal = RubyId.newId(ruby, '-'); }
break;
case 97:
// line 560 "parse.y"
{ yyVal = RubyId.newId(ruby, '*'); }
break;
case 98:
// line 561 "parse.y"
{ yyVal = RubyId.newId(ruby, '*'); }
break;
case 99:
// line 562 "parse.y"
{ yyVal = RubyId.newId(ruby, '/'); }
break;
case 100:
// line 563 "parse.y"
{ yyVal = RubyId.newId(ruby, '%'); }
break;
case 101:
// line 564 "parse.y"
{ yyVal = RubyId.newId(ruby, tPOW); }
break;
case 102:
// line 565 "parse.y"
{ yyVal = RubyId.newId(ruby, '~'); }
break;
case 103:
// line 566 "parse.y"
{ yyVal = RubyId.newId(ruby, tUPLUS); }
break;
case 104:
// line 567 "parse.y"
{ yyVal = RubyId.newId(ruby, tUMINUS); }
break;
case 105:
// line 568 "parse.y"
{ yyVal = RubyId.newId(ruby, tAREF); }
break;
case 106:
// line 569 "parse.y"
{ yyVal = RubyId.newId(ruby, tASET); }
break;
case 107:
// line 570 "parse.y"
{ yyVal = RubyId.newId(ruby, '`'); }
break;
case 149:
// line 581 "parse.y"
{
ph.value_expr(((Node)yyVals[0+yyTop]));
yyVal = ph.node_assign(((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 150:
// line 585 "parse.y"
{yyVal = ph.assignable(((RubyId)yyVals[-1+yyTop]), null);}
break;
case 151:
// line 586 "parse.y"
{
if (((RubyId)yyVals[-2+yyTop]).intValue() == tOROP) {
((Node)yyVals[-1+yyTop]).setValueNode(((Node)yyVals[0+yyTop]));
yyVal = nf.newOpAsgnOr(ph.gettable(((RubyId)yyVals[-3+yyTop])), ((Node)yyVals[-1+yyTop]));
if (((RubyId)yyVals[-3+yyTop]).isInstanceId()) {
((Node)yyVal).setAId(((RubyId)yyVals[-3+yyTop]));
}
} else if (((RubyId)yyVals[-2+yyTop]).intValue() == tANDOP) {
((Node)yyVals[-1+yyTop]).setValueNode(((Node)yyVals[0+yyTop]));
yyVal = nf.newOpAsgnAnd(ph.gettable(((RubyId)yyVals[-3+yyTop])), ((Node)yyVals[-1+yyTop]));
} else {
yyVal = ((Node)yyVals[-1+yyTop]);
if (yyVal != null) {
((Node)yyVal).setValueNode(ph.call_op(ph.gettable(((RubyId)yyVals[-3+yyTop])),((RubyId)yyVals[-2+yyTop]).intValue(),1,((Node)yyVals[0+yyTop])));
}
}
ph.fixpos(yyVal, ((Node)yyVals[0+yyTop]));
}
break;
case 152:
// line 605 "parse.y"
{
ArrayNode args = nf.newList(((Node)yyVals[0+yyTop]));
ph.list_append(((Node)yyVals[-3+yyTop]), nf.newNil());
ph.list_concat(args, ((Node)yyVals[-3+yyTop]));
if (((RubyId)yyVals[-1+yyTop]).intValue() == Token.tOROP) {
yyVals[-1+yyTop] = RubyId.newId(ruby, 0);
} else if (((RubyId)yyVals[-1+yyTop]).intValue() == Token.tANDOP) {
yyVals[-1+yyTop] = RubyId.newId(ruby, 1);
}
yyVal = nf.newOpAsgn1(((Node)yyVals[-5+yyTop]), ((RubyId)yyVals[-1+yyTop]), args);
ph.fixpos(yyVal, ((Node)yyVals[-5+yyTop]));
}
break;
case 153:
// line 619 "parse.y"
{
if (((RubyId)yyVals[-1+yyTop]).intValue() == Token.tOROP) {
yyVals[-1+yyTop] = RubyId.newId(ruby, 0);
} else if (((RubyId)yyVals[-1+yyTop]).intValue() == Token.tANDOP) {
yyVals[-1+yyTop] = RubyId.newId(ruby, 1);
}
yyVal = nf.newOpAsgn2(((Node)yyVals[-4+yyTop]), ((RubyId)yyVals[-2+yyTop]), ((RubyId)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
ph.fixpos(yyVal, ((Node)yyVals[-4+yyTop]));
}
break;
case 154:
// line 629 "parse.y"
{
if (((RubyId)yyVals[-1+yyTop]).intValue() == Token.tOROP) {
yyVals[-1+yyTop] = RubyId.newId(ruby, 0);
} else if (((RubyId)yyVals[-1+yyTop]).intValue() == Token.tANDOP) {
yyVals[-1+yyTop] = RubyId.newId(ruby, 1);
}
yyVal = nf.newOpAsgn2(((Node)yyVals[-4+yyTop]), ((RubyId)yyVals[-2+yyTop]), ((RubyId)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
ph.fixpos(yyVal, ((Node)yyVals[-4+yyTop]));
}
break;
case 155:
// line 639 "parse.y"
{
if (((RubyId)yyVals[-1+yyTop]).intValue() == Token.tOROP) {
yyVals[-1+yyTop] = RubyId.newId(ruby, 0);
} else if (((RubyId)yyVals[-1+yyTop]).intValue() == Token.tANDOP) {
yyVals[-1+yyTop] = RubyId.newId(ruby, 1);
}
yyVal = nf.newOpAsgn2(((Node)yyVals[-4+yyTop]), ((RubyId)yyVals[-2+yyTop]), ((RubyId)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
ph.fixpos(yyVal, ((Node)yyVals[-4+yyTop]));
}
break;
case 156:
// line 649 "parse.y"
{
ph.rb_backref_error(((Node)yyVals[-2+yyTop]));
yyVal = null; /*XXX 0*/
}
break;
case 157:
// line 654 "parse.y"
{
yyVal = nf.newDot2(((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 158:
// line 658 "parse.y"
{
yyVal = nf.newDot3(((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 159:
// line 662 "parse.y"
{
yyVal = ph.call_op(((Node)yyVals[-2+yyTop]), '+', 1, ((Node)yyVals[0+yyTop]));
}
break;
case 160:
// line 666 "parse.y"
{
yyVal = ph.call_op(((Node)yyVals[-2+yyTop]), '-', 1, ((Node)yyVals[0+yyTop]));
}
break;
case 161:
// line 670 "parse.y"
{
yyVal = ph.call_op(((Node)yyVals[-2+yyTop]), '*', 1, ((Node)yyVals[0+yyTop]));
}
break;
case 162:
// line 674 "parse.y"
{
yyVal = ph.call_op(((Node)yyVals[-2+yyTop]), '/', 1, ((Node)yyVals[0+yyTop]));
}
break;
case 163:
// line 678 "parse.y"
{
yyVal = ph.call_op(((Node)yyVals[-2+yyTop]), '%', 1, ((Node)yyVals[0+yyTop]));
}
break;
case 164:
// line 682 "parse.y"
{
boolean need_negate = false;
if (((Node)yyVals[-2+yyTop]) instanceof LitNode) {
if (((Node)yyVals[-2+yyTop]).getLiteral() instanceof RubyFixnum ||
((Node)yyVals[-2+yyTop]).getLiteral() instanceof RubyFloat ||
((Node)yyVals[-2+yyTop]).getLiteral() instanceof RubyBignum) {
if (((Node)yyVals[-2+yyTop]).getLiteral().funcall(ruby.intern("<"), RubyFixnum.zero(ruby)).isTrue()) {
((Node)yyVals[-2+yyTop]).setLiteral(((Node)yyVals[-2+yyTop]).getLiteral().funcall(ruby.intern("-@")));
need_negate = true;
}
}
}
yyVal = ph.call_op(((Node)yyVals[-2+yyTop]), tPOW, 1, ((Node)yyVals[0+yyTop]));
if (need_negate) {
yyVal = ph.call_op(((Node)yyVal), tUMINUS, 0, null);
}
}
break;
case 165:
// line 701 "parse.y"
{
if (((Node)yyVals[0+yyTop]) != null && ((Node)yyVals[0+yyTop]) instanceof LitNode) {
yyVal = ((Node)yyVals[0+yyTop]);
} else {
yyVal = ph.call_op(((Node)yyVals[0+yyTop]), tUPLUS, 0, null);
}
}
break;
case 166:
// line 709 "parse.y"
{
if (((Node)yyVals[0+yyTop]) != null && ((Node)yyVals[0+yyTop]) instanceof LitNode && ((Node)yyVals[0+yyTop]).getLiteral() instanceof RubyFixnum) {
long i = ((RubyFixnum)((Node)yyVals[0+yyTop]).getLiteral()).getValue();
((Node)yyVals[0+yyTop]).setLiteral(RubyFixnum.m_newFixnum(ruby, -i));
yyVal = ((Node)yyVals[0+yyTop]);
} else {
yyVal = ph.call_op(((Node)yyVals[0+yyTop]), tUMINUS, 0, null);
}
}
break;
case 167:
// line 720 "parse.y"
{
yyVal = ph.call_op(((Node)yyVals[-2+yyTop]), '|', 1, ((Node)yyVals[0+yyTop]));
}
break;
case 168:
// line 724 "parse.y"
{
yyVal = ph.call_op(((Node)yyVals[-2+yyTop]), '^', 1, ((Node)yyVals[0+yyTop]));
}
break;
case 169:
// line 728 "parse.y"
{
yyVal = ph.call_op(((Node)yyVals[-2+yyTop]), '&', 1, ((Node)yyVals[0+yyTop]));
}
break;
case 170:
// line 732 "parse.y"
{
yyVal = ph.call_op(((Node)yyVals[-2+yyTop]), tCMP, 1, ((Node)yyVals[0+yyTop]));
}
break;
case 171:
// line 736 "parse.y"
{
yyVal = ph.call_op(((Node)yyVals[-2+yyTop]), '>', 1, ((Node)yyVals[0+yyTop]));
}
break;
case 172:
// line 740 "parse.y"
{
yyVal = ph.call_op(((Node)yyVals[-2+yyTop]), tGEQ, 1, ((Node)yyVals[0+yyTop]));
}
break;
case 173:
// line 744 "parse.y"
{
yyVal = ph.call_op(((Node)yyVals[-2+yyTop]), '<', 1, ((Node)yyVals[0+yyTop]));
}
break;
case 174:
// line 748 "parse.y"
{
yyVal = ph.call_op(((Node)yyVals[-2+yyTop]), tLEQ, 1, ((Node)yyVals[0+yyTop]));
}
break;
case 175:
// line 752 "parse.y"
{
yyVal = ph.call_op(((Node)yyVals[-2+yyTop]), tEQ, 1, ((Node)yyVals[0+yyTop]));
}
break;
case 176:
// line 756 "parse.y"
{
yyVal = ph.call_op(((Node)yyVals[-2+yyTop]), tEQQ, 1, ((Node)yyVals[0+yyTop]));
}
break;
case 177:
// line 760 "parse.y"
{
yyVal = nf.newNot(ph.call_op(((Node)yyVals[-2+yyTop]), tEQ, 1, ((Node)yyVals[0+yyTop])));
}
break;
case 178:
// line 764 "parse.y"
{
yyVal = ph.match_gen(((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 179:
// line 768 "parse.y"
{
yyVal = nf.newNot(ph.match_gen(((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop])));
}
break;
case 180:
// line 772 "parse.y"
{
ph.value_expr(((Node)yyVals[0+yyTop]));
yyVal = nf.newNot(ph.cond(((Node)yyVals[0+yyTop])));
}
break;
case 181:
// line 777 "parse.y"
{
yyVal = ph.call_op(((Node)yyVals[0+yyTop]), '~', 0, null);
}
break;
case 182:
// line 781 "parse.y"
{
yyVal = ph.call_op(((Node)yyVals[-2+yyTop]), tLSHFT, 1, ((Node)yyVals[0+yyTop]));
}
break;
case 183:
// line 785 "parse.y"
{
yyVal = ph.call_op(((Node)yyVals[-2+yyTop]), tRSHFT, 1, ((Node)yyVals[0+yyTop]));
}
break;
case 184:
// line 789 "parse.y"
{
yyVal = ph.logop(Constants.NODE_AND, ((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 185:
// line 793 "parse.y"
{
yyVal = ph.logop(Constants.NODE_OR, ((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 186:
// line 796 "parse.y"
{ ph.setInDefined(true);}
break;
case 187:
// line 797 "parse.y"
{
ph.setInDefined(false);
yyVal = nf.newDefined(((Node)yyVals[0+yyTop]));
}
break;
case 188:
// line 802 "parse.y"
{
ph.value_expr(((Node)yyVals[-4+yyTop]));
yyVal = nf.newIf(ph.cond(((Node)yyVals[-4+yyTop])), ((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
ph.fixpos(yyVal, ((Node)yyVals[-4+yyTop]));
}
break;
case 189:
// line 808 "parse.y"
{
yyVal = ((Node)yyVals[0+yyTop]);
}
break;
case 191:
// line 814 "parse.y"
{
yyVal = nf.newList(((Node)yyVals[-1+yyTop]));
}
break;
case 192:
// line 818 "parse.y"
{
yyVal = ph.list_append(((Node)yyVals[-3+yyTop]), ((Node)yyVals[-1+yyTop]));
}
break;
case 193:
// line 822 "parse.y"
{
yyVal = ((Node)yyVals[-1+yyTop]);
}
break;
case 194:
// line 826 "parse.y"
{
ph.value_expr(((Node)yyVals[-1+yyTop]));
yyVal = ph.arg_concat(((Node)yyVals[-4+yyTop]), ((Node)yyVals[-1+yyTop]));
}
break;
case 195:
// line 831 "parse.y"
{
yyVal = nf.newList(nf.newHash(((Node)yyVals[-1+yyTop])));
}
break;
case 196:
// line 835 "parse.y"
{
ph.value_expr(((Node)yyVals[-1+yyTop]));
yyVal = nf.newRestArgs(((Node)yyVals[-1+yyTop]));
}
break;
case 197:
// line 841 "parse.y"
{
yyVal = ((Node)yyVals[-1+yyTop]);
}
break;
case 198:
// line 845 "parse.y"
{
yyVal = ((Node)yyVals[-2+yyTop]);
}
break;
case 199:
// line 849 "parse.y"
{
yyVal = nf.newList(((Node)yyVals[-2+yyTop]));
}
break;
case 200:
// line 853 "parse.y"
{
yyVal = ph.list_append(((Node)yyVals[-4+yyTop]), ((Node)yyVals[-2+yyTop]));
}
break;
case 203:
// line 861 "parse.y"
{
yyVal = nf.newList(((Node)yyVals[0+yyTop]));
}
break;
case 204:
// line 865 "parse.y"
{
yyVal = ph.list_append(((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 205:
// line 869 "parse.y"
{
yyVal = ph.arg_blk_pass(((Node)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 206:
// line 873 "parse.y"
{
ph.value_expr(((Node)yyVals[-1+yyTop]));
yyVal = ph.arg_concat(((Node)yyVals[-4+yyTop]), ((Node)yyVals[-1+yyTop]));
yyVal = ph.arg_blk_pass(((Node)yyVal), ((Node)yyVals[0+yyTop]));
}
break;
case 207:
// line 879 "parse.y"
{
yyVal = nf.newList(nf.newHash(((Node)yyVals[-1+yyTop])));
yyVal = ph.arg_blk_pass(((Node)yyVal), ((Node)yyVals[0+yyTop]));
}
break;
case 208:
// line 884 "parse.y"
{
ph.value_expr(((Node)yyVals[-1+yyTop]));
yyVal = ph.arg_concat(nf.newList(nf.newHash(((Node)yyVals[-4+yyTop]))), ((Node)yyVals[-1+yyTop]));
yyVal = ph.arg_blk_pass(((Node)yyVal), ((Node)yyVals[0+yyTop]));
}
break;
case 209:
// line 890 "parse.y"
{
yyVal = ph.list_append(((Node)yyVals[-3+yyTop]), nf.newHash(((Node)yyVals[-1+yyTop])));
yyVal = ph.arg_blk_pass(((Node)yyVal), ((Node)yyVals[0+yyTop]));
}
break;
case 210:
// line 895 "parse.y"
{
ph.value_expr(((Node)yyVals[-1+yyTop]));
yyVal = ph.arg_concat(ph.list_append(((Node)yyVals[-6+yyTop]), nf.newHash(((Node)yyVals[-4+yyTop]))), ((Node)yyVals[-1+yyTop]));
yyVal = ph.arg_blk_pass(((Node)yyVal), ((Node)yyVals[0+yyTop]));
}
break;
case 211:
// line 901 "parse.y"
{
ph.value_expr(((Node)yyVals[-1+yyTop]));
yyVal = ph.arg_blk_pass(nf.newRestArgs(((Node)yyVals[-1+yyTop])), ((Node)yyVals[0+yyTop]));
}
break;
case 213:
// line 907 "parse.y"
{ rs.CMDARG_PUSH(); }
break;
case 214:
// line 908 "parse.y"
{
rs.CMDARG_POP();
yyVal = ((Node)yyVals[0+yyTop]);
}
break;
case 215:
// line 914 "parse.y"
{
ph.value_expr(((Node)yyVals[0+yyTop]));
yyVal = nf.newBlockPass(((Node)yyVals[0+yyTop]));
}
break;
case 216:
// line 920 "parse.y"
{
yyVal = ((Node)yyVals[0+yyTop]);
}
break;
case 218:
// line 926 "parse.y"
{
ph.value_expr(((Node)yyVals[0+yyTop]));
yyVal = nf.newList(((Node)yyVals[0+yyTop]));
}
break;
case 219:
// line 931 "parse.y"
{
ph.value_expr(((Node)yyVals[0+yyTop]));
yyVal = ph.list_append(((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 220:
// line 937 "parse.y"
{
ph.value_expr(((Node)yyVals[0+yyTop]));
yyVal = ((Node)yyVals[0+yyTop]);
}
break;
case 222:
// line 944 "parse.y"
{
ph.value_expr(((Node)yyVals[0+yyTop]));
yyVal = ph.list_append(((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 223:
// line 949 "parse.y"
{
ph.value_expr(((Node)yyVals[0+yyTop]));
yyVal = ph.arg_concat(((Node)yyVals[-3+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 224:
// line 954 "parse.y"
{
ph.value_expr(((Node)yyVals[0+yyTop]));
yyVal = ((Node)yyVals[0+yyTop]);
}
break;
case 225:
// line 960 "parse.y"
{
yyVal = ((Node)yyVals[0+yyTop]);
if (((Node)yyVals[0+yyTop]) != null) {
if (((Node)yyVals[0+yyTop]).getType() == Constants.NODE_ARRAY && ((Node)yyVals[0+yyTop]).getNextNode() == null) {
yyVal = ((Node)yyVals[0+yyTop]).getHeadNode();
} else if (((Node)yyVals[0+yyTop]).getType() == Constants.NODE_BLOCK_PASS) {
ph.rb_compile_error("block argument should not be given");
}
}
}
break;
case 226:
// line 972 "parse.y"
{
yyVal = nf.newLit(((RubyObject)yyVals[0+yyTop]));
}
break;
case 228:
// line 977 "parse.y"
{
yyVal = nf.newXStr(((RubyObject)yyVals[0+yyTop]));
}
break;
case 233:
// line 985 "parse.y"
{
yyVal = nf.newVCall(((RubyId)yyVals[0+yyTop]));
}
break;
case 234:
// line 994 "parse.y"
{
if (((Node)yyVals[-3+yyTop]) == null && ((Node)yyVals[-2+yyTop]) == null && ((Node)yyVals[-1+yyTop]) == null)
yyVal = nf.newBegin(((Node)yyVals[-4+yyTop]));
else {
if (((Node)yyVals[-3+yyTop]) != null) yyVals[-4+yyTop] = nf.newRescue(((Node)yyVals[-4+yyTop]), ((Node)yyVals[-3+yyTop]), ((Node)yyVals[-2+yyTop]));
else if (((Node)yyVals[-2+yyTop]) != null) {
ph.rb_warn("else without rescue is useless");
yyVals[-4+yyTop] = ph.block_append(((Node)yyVals[-4+yyTop]), ((Node)yyVals[-2+yyTop]));
}
if (((Node)yyVals[-1+yyTop]) != null) yyVals[-4+yyTop] = nf.newEnsure(((Node)yyVals[-4+yyTop]), ((Node)yyVals[-1+yyTop]));
yyVal = ((Node)yyVals[-4+yyTop]);
}
ph.fixpos(yyVal, ((Node)yyVals[-4+yyTop]));
}
break;
case 235:
// line 1009 "parse.y"
{
yyVal = ((Node)yyVals[-1+yyTop]);
}
break;
case 236:
// line 1013 "parse.y"
{
ph.value_expr(((Node)yyVals[-2+yyTop]));
yyVal = nf.newColon2(((Node)yyVals[-2+yyTop]), ((RubyId)yyVals[0+yyTop]));
}
break;
case 237:
// line 1018 "parse.y"
{
yyVal = nf.newColon3(((RubyId)yyVals[0+yyTop]));
}
break;
case 238:
// line 1022 "parse.y"
{
ph.value_expr(((Node)yyVals[-3+yyTop]));
yyVal = nf.newCall(((Node)yyVals[-3+yyTop]), ph.newId(tAREF), ((Node)yyVals[-1+yyTop]));
}
break;
case 239:
// line 1027 "parse.y"
{
if (((Node)yyVals[-1+yyTop]) == null) {
yyVal = nf.newZArray(); /* zero length array*/
} else {
yyVal = ((Node)yyVals[-1+yyTop]);
}
}
break;
case 240:
// line 1035 "parse.y"
{
yyVal = nf.newHash(((Node)yyVals[-1+yyTop]));
}
break;
case 241:
// line 1039 "parse.y"
{
if (!ph.isCompileForEval() && !ph.isInDef() && !ph.isInSingle())
yyerror("return appeared outside of method");
ph.value_expr(((Node)yyVals[-1+yyTop]));
yyVal = nf.newReturn(((Node)yyVals[-1+yyTop]));
}
break;
case 242:
// line 1046 "parse.y"
{
if (!ph.isCompileForEval() && !ph.isInDef() && !ph.isInSingle())
yyerror("return appeared outside of method");
yyVal = nf.newReturn(null);
}
break;
case 243:
// line 1052 "parse.y"
{
if (!ph.isCompileForEval() && !ph.isInDef() && !ph.isInSingle())
yyerror("return appeared outside of method");
yyVal = nf.newReturn(null);
}
break;
case 244:
// line 1058 "parse.y"
{
ph.value_expr(((Node)yyVals[-1+yyTop]));
yyVal = nf.newYield(((Node)yyVals[-1+yyTop]));
}
break;
case 245:
// line 1063 "parse.y"
{
yyVal = nf.newYield(null);
}
break;
case 246:
// line 1067 "parse.y"
{
yyVal = nf.newYield(null);
}
break;
case 247:
// line 1070 "parse.y"
{ph.setInDefined(true);}
break;
case 248:
// line 1071 "parse.y"
{
ph.setInDefined(false);
yyVal = nf.newDefined(((Node)yyVals[-1+yyTop]));
}
break;
case 249:
// line 1076 "parse.y"
{
((Node)yyVals[0+yyTop]).setIterNode(nf.newFCall(((RubyId)yyVals[-1+yyTop]), null));
yyVal = ((Node)yyVals[0+yyTop]);
}
break;
case 251:
// line 1082 "parse.y"
{
if (((Node)yyVals[-1+yyTop]) != null && ((Node)yyVals[-1+yyTop]).getType() == Constants.NODE_BLOCK_PASS) {
ph.rb_compile_error("both block arg and actual block given");
}
((Node)yyVals[0+yyTop]).setIterNode(((Node)yyVals[-1+yyTop]));
yyVal = ((Node)yyVals[0+yyTop]);
ph.fixpos(yyVal, ((Node)yyVals[-1+yyTop]));
}
break;
case 252:
// line 1094 "parse.y"
{
ph.value_expr(((Node)yyVals[-4+yyTop]));
yyVal = nf.newIf(ph.cond(((Node)yyVals[-4+yyTop])), ((Node)yyVals[-2+yyTop]), ((Node)yyVals[-1+yyTop]));
ph.fixpos(yyVal, ((Node)yyVals[-4+yyTop]));
}
break;
case 253:
// line 1103 "parse.y"
{
ph.value_expr(((Node)yyVals[-4+yyTop]));
yyVal = nf.newUnless(ph.cond(((Node)yyVals[-4+yyTop])), ((Node)yyVals[-2+yyTop]), ((Node)yyVals[-1+yyTop]));
ph.fixpos(yyVal, ((Node)yyVals[-4+yyTop]));
}
break;
case 254:
// line 1108 "parse.y"
{ rs.COND_PUSH(); }
break;
case 255:
// line 1108 "parse.y"
{ rs.COND_POP(); }
break;
case 256:
// line 1111 "parse.y"
{
ph.value_expr(((Node)yyVals[-4+yyTop]));
yyVal = nf.newWhile(ph.cond(((Node)yyVals[-4+yyTop])), ((Node)yyVals[-1+yyTop])); /* , 1*/
ph.fixpos(yyVal, ((Node)yyVals[-4+yyTop]));
}
break;
case 257:
// line 1116 "parse.y"
{ rs.COND_PUSH(); }
break;
case 258:
// line 1116 "parse.y"
{ rs.COND_POP(); }
break;
case 259:
// line 1119 "parse.y"
{
ph.value_expr(((Node)yyVals[-4+yyTop]));
yyVal = nf.newUntil(ph.cond(((Node)yyVals[-4+yyTop])), ((Node)yyVals[-1+yyTop])); /*, 1*/
ph.fixpos(yyVal, ((Node)yyVals[-4+yyTop]));
}
break;
case 260:
// line 1127 "parse.y"
{
ph.value_expr(((Node)yyVals[-3+yyTop]));
yyVal = nf.newCase(((Node)yyVals[-3+yyTop]), ((Node)yyVals[-1+yyTop]));
ph.fixpos(yyVal, ((Node)yyVals[-3+yyTop]));
}
break;
case 261:
// line 1133 "parse.y"
{
yyVal = ((Node)yyVals[-1+yyTop]);
}
break;
case 262:
// line 1136 "parse.y"
{ rs.COND_PUSH(); }
break;
case 263:
// line 1136 "parse.y"
{ rs.COND_POP(); }
break;
case 264:
// line 1139 "parse.y"
{
ph.value_expr(((Node)yyVals[-4+yyTop]));
yyVal = nf.newFor(((Node)yyVals[-7+yyTop]), ((Node)yyVals[-4+yyTop]), ((Node)yyVals[-1+yyTop]));
ph.fixpos(yyVal, ((Node)yyVals[-7+yyTop]));
}
break;
case 265:
// line 1145 "parse.y"
{
if (ph.isInDef() || ph.isInSingle())
yyerror("class definition in method body");
ph.setClassNest(ph.getClassNest() + 1);
ph.local_push();
yyVal = new Integer(ruby.getSourceLine());
}
break;
case 266:
// line 1154 "parse.y"
{
yyVal = nf.newClass(((RubyId)yyVals[-4+yyTop]), ((Node)yyVals[-1+yyTop]), ((Node)yyVals[-3+yyTop]));
((Node)yyVal).setLine(((Integer)yyVals[-2+yyTop]).intValue());
ph.local_pop();
ph.setClassNest(ph.getClassNest() - 1);
}
break;
case 267:
// line 1161 "parse.y"
{
yyVal = new Integer(ph.getInDef());
ph.setInDef(0);
}
break;
case 268:
// line 1166 "parse.y"
{
yyVal = new Integer(ph.getInSingle());
ph.setInSingle(0);
ph.setClassNest(ph.getClassNest() - 1);
ph.local_push();
}
break;
case 269:
// line 1174 "parse.y"
{
yyVal = nf.newSClass(((Node)yyVals[-5+yyTop]), ((Node)yyVals[-1+yyTop]));
ph.fixpos(yyVal, ((Node)yyVals[-5+yyTop]));
ph.local_pop();
ph.setClassNest(ph.getClassNest() - 1);
ph.setInDef(((Integer)yyVals[-4+yyTop]).intValue());
ph.setInSingle(((Integer)yyVals[-2+yyTop]).intValue());
}
break;
case 270:
// line 1183 "parse.y"
{
if (ph.isInDef() || ph.isInSingle())
yyerror("module definition in method body");
ph.setClassNest(ph.getClassNest() + 1);
ph.local_push();
yyVal = new Integer(ruby.getSourceLine());
}
break;
case 271:
// line 1192 "parse.y"
{
yyVal = nf.newModule(((RubyId)yyVals[-3+yyTop]), ((Node)yyVals[-1+yyTop]));
((Node)yyVal).setLine(((Integer)yyVals[-2+yyTop]).intValue());
ph.local_pop();
ph.setClassNest(ph.getClassNest() - 1);
}
break;
case 272:
// line 1199 "parse.y"
{
if (ph.isInDef() || ph.isInSingle())
yyerror("nested method definition");
yyVal = ph.getCurMid();
ph.setCurMid(((RubyId)yyVals[0+yyTop]));
ph.setInDef(ph.getInDef() + 1);
ph.local_push();
}
break;
case 273:
// line 1213 "parse.y"
{
if (((Node)yyVals[-3+yyTop]) != null)
yyVals[-4+yyTop] = nf.newRescue(((Node)yyVals[-4+yyTop]), ((Node)yyVals[-3+yyTop]), ((Node)yyVals[-2+yyTop]));
else if (((Node)yyVals[-2+yyTop]) != null) {
ph.rb_warn("else without rescue is useless");
yyVals[-4+yyTop] = ph.block_append(((Node)yyVals[-4+yyTop]), ((Node)yyVals[-2+yyTop]));
}
if (((Node)yyVals[-1+yyTop]) != null)
yyVals[-4+yyTop] = nf.newEnsure(((Node)yyVals[-4+yyTop]), ((Node)yyVals[-1+yyTop]));
/* NOEX_PRIVATE for toplevel */
yyVal = nf.newDefn(((RubyId)yyVals[-7+yyTop]), ((Node)yyVals[-5+yyTop]), ((Node)yyVals[-4+yyTop]), ph.getClassNest() !=0 ?
Constants.NOEX_PUBLIC : Constants.NOEX_PRIVATE);
if (((RubyId)yyVals[-7+yyTop]).isAttrSetId())
((Node)yyVal).setNoex(Constants.NOEX_PUBLIC);
ph.fixpos(yyVal, ((Node)yyVals[-5+yyTop]));
ph.local_pop();
ph.setInDef(ph.getInDef() - 1);
ph.setCurMid(((RubyId)yyVals[-6+yyTop]));
}
break;
case 274:
// line 1233 "parse.y"
{ph.setLexState(LexState.EXPR_FNAME);}
break;
case 275:
// line 1234 "parse.y"
{
ph.value_expr(((Node)yyVals[-3+yyTop]));
ph.setInSingle(ph.getInSingle() + 1);
ph.local_push();
ph.setLexState(LexState.EXPR_END); /* force for args */
}
break;
case 276:
// line 1246 "parse.y"
{
if (((Node)yyVals[-3+yyTop]) != null)
yyVals[-4+yyTop] = nf.newRescue(((Node)yyVals[-4+yyTop]), ((Node)yyVals[-3+yyTop]), ((Node)yyVals[-2+yyTop]));
else if (((Node)yyVals[-2+yyTop]) != null) {
ph.rb_warn("else without rescue is useless");
yyVals[-4+yyTop] = ph.block_append(((Node)yyVals[-4+yyTop]), ((Node)yyVals[-2+yyTop]));
}
if (((Node)yyVals[-1+yyTop]) != null) yyVals[-4+yyTop] = nf.newEnsure(((Node)yyVals[-4+yyTop]), ((Node)yyVals[-1+yyTop]));
yyVal = nf.newDefs(((Node)yyVals[-10+yyTop]), ((RubyId)yyVals[-7+yyTop]), ((Node)yyVals[-5+yyTop]), ((Node)yyVals[-4+yyTop]));
ph.fixpos(yyVal, ((Node)yyVals[-10+yyTop]));
ph.local_pop();
ph.setInSingle(ph.getInSingle() - 1);
}
break;
case 277:
// line 1261 "parse.y"
{
yyVal = nf.newBreak();
}
break;
case 278:
// line 1265 "parse.y"
{
yyVal = nf.newNext();
}
break;
case 279:
// line 1269 "parse.y"
{
yyVal = nf.newRedo();
}
break;
case 280:
// line 1273 "parse.y"
{
yyVal = nf.newRetry();
}
break;
case 287:
// line 1288 "parse.y"
{
ph.value_expr(((Node)yyVals[-3+yyTop]));
yyVal = nf.newIf(ph.cond(((Node)yyVals[-3+yyTop])), ((Node)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
ph.fixpos(yyVal, ((Node)yyVals[-3+yyTop]));
}
break;
case 289:
// line 1296 "parse.y"
{
yyVal = ((Node)yyVals[0+yyTop]);
}
break;
case 293:
// line 1305 "parse.y"
{
yyVal = Node.ONE; /* new Integer(1); //XXX (Node*)1;*/
}
break;
case 294:
// line 1309 "parse.y"
{
yyVal = Node.ONE; /* new Integer(1); //XXX (Node*)1;*/
}
break;
case 295:
// line 1313 "parse.y"
{
yyVal = ((Node)yyVals[-1+yyTop]);
}
break;
case 296:
// line 1318 "parse.y"
{
yyVal = ph.dyna_push();
}
break;
case 297:
// line 1324 "parse.y"
{
yyVal = nf.newIter(((Node)yyVals[-2+yyTop]), null, ((Node)yyVals[-1+yyTop]));
ph.fixpos(yyVal, ((Node)yyVals[-2+yyTop])!=null?((Node)yyVals[-2+yyTop]):((Node)yyVals[-1+yyTop]));
ph.dyna_pop(((RubyVarmap)yyVals[-3+yyTop]));
}
break;
case 298:
// line 1331 "parse.y"
{
if (((Node)yyVals[-1+yyTop]) != null && ((Node)yyVals[-1+yyTop]).getType() == Constants.NODE_BLOCK_PASS) {
ph.rb_compile_error("both block arg and actual block given");
}
((Node)yyVals[0+yyTop]).setIterNode(((Node)yyVals[-1+yyTop]));
yyVal = ((Node)yyVals[0+yyTop]);
ph.fixpos(yyVal, ((Node)yyVals[0+yyTop]));
}
break;
case 299:
// line 1340 "parse.y"
{
ph.value_expr(((Node)yyVals[-3+yyTop]));
yyVal = ph.new_call(((Node)yyVals[-3+yyTop]), ((RubyId)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 300:
// line 1345 "parse.y"
{
ph.value_expr(((Node)yyVals[-3+yyTop]));
yyVal = ph.new_call(((Node)yyVals[-3+yyTop]), ((RubyId)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 301:
// line 1351 "parse.y"
{
yyVal = ph.new_fcall(((RubyId)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
ph.fixpos(yyVal, ((Node)yyVals[0+yyTop]));
}
break;
case 302:
// line 1356 "parse.y"
{
ph.value_expr(((Node)yyVals[-3+yyTop]));
yyVal = ph.new_call(((Node)yyVals[-3+yyTop]), ((RubyId)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
ph.fixpos(yyVal, ((Node)yyVals[-3+yyTop]));
}
break;
case 303:
// line 1362 "parse.y"
{
ph.value_expr(((Node)yyVals[-3+yyTop]));
yyVal = ph.new_call(((Node)yyVals[-3+yyTop]), ((RubyId)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
ph.fixpos(yyVal, ((Node)yyVals[-3+yyTop]));
}
break;
case 304:
// line 1368 "parse.y"
{
ph.value_expr(((Node)yyVals[-2+yyTop]));
yyVal = ph.new_call(((Node)yyVals[-2+yyTop]), ((RubyId)yyVals[0+yyTop]), null);
}
break;
case 305:
// line 1373 "parse.y"
{
if (!ph.isCompileForEval() && !ph.isInDef() && !ph.isInSingle() && !ph.isInDefined())
yyerror("super called outside of method");
yyVal = ph.new_super(((Node)yyVals[0+yyTop]));
}
break;
case 306:
// line 1379 "parse.y"
{
if (!ph.isCompileForEval() && !ph.isInDef() && !ph.isInSingle() && !ph.isInDefined())
yyerror("super called outside of method");
yyVal = nf.newZSuper();
}
break;
case 307:
// line 1386 "parse.y"
{
yyVal = ph.dyna_push();
}
break;
case 308:
// line 1391 "parse.y"
{
yyVal = nf.newIter(((Node)yyVals[-2+yyTop]), null, ((Node)yyVals[-1+yyTop]));
ph.fixpos(yyVal, ((Node)yyVals[-1+yyTop]));
ph.dyna_pop(((RubyVarmap)yyVals[-3+yyTop]));
}
break;
case 309:
// line 1397 "parse.y"
{
yyVal = ph.dyna_push();
}
break;
case 310:
// line 1402 "parse.y"
{
yyVal = nf.newIter(((Node)yyVals[-2+yyTop]), null, ((Node)yyVals[-1+yyTop]));
ph.fixpos(yyVal, ((Node)yyVals[-1+yyTop]));
ph.dyna_pop(((RubyVarmap)yyVals[-3+yyTop]));
}
break;
case 311:
// line 1411 "parse.y"
{
yyVal = nf.newWhen(((Node)yyVals[-3+yyTop]), ((Node)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 313:
// line 1417 "parse.y"
{
ph.value_expr(((Node)yyVals[0+yyTop]));
yyVal = ph.list_append(((Node)yyVals[-3+yyTop]), nf.newWhen(((Node)yyVals[0+yyTop]), null, null));
}
break;
case 314:
// line 1422 "parse.y"
{
ph.value_expr(((Node)yyVals[0+yyTop]));
yyVal = nf.newList(nf.newWhen(((Node)yyVals[0+yyTop]), null, null));
}
break;
case 319:
// line 1434 "parse.y"
{
yyVal = ((Node)yyVals[0+yyTop]);
}
break;
case 321:
// line 1442 "parse.y"
{
if (((Node)yyVals[-3+yyTop]) != null) {
yyVals[-3+yyTop] = ph.node_assign(((Node)yyVals[-3+yyTop]), nf.newGVar(ruby.intern("$!")));
yyVals[-1+yyTop] = ph.block_append(((Node)yyVals[-3+yyTop]), ((Node)yyVals[-1+yyTop]));
}
yyVal = nf.newResBody(((Node)yyVals[-4+yyTop]), ((Node)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
ph.fixpos(yyVal, ((Node)yyVals[-4+yyTop])!=null?((Node)yyVals[-4+yyTop]):((Node)yyVals[-1+yyTop]));
}
break;
case 324:
// line 1454 "parse.y"
{
if (((Node)yyVals[0+yyTop]) != null)
yyVal = ((Node)yyVals[0+yyTop]);
else
/* place holder */
yyVal = nf.newNil();
}
break;
case 326:
// line 1464 "parse.y"
{
yyVal = ((RubyId)yyVals[0+yyTop]).toSymbol();
}
break;
case 328:
// line 1470 "parse.y"
{
yyVal = nf.newStr(((RubyObject)yyVals[0+yyTop]));
}
break;
case 330:
// line 1475 "parse.y"
{
if (((Node)yyVals[-1+yyTop]).getType() == Constants.NODE_DSTR) {
ph.list_append(((Node)yyVals[-1+yyTop]), nf.newStr(((RubyObject)yyVals[0+yyTop])));
} else {
((RubyString)((Node)yyVals[-1+yyTop]).getLiteral()).m_concat((RubyString)((RubyObject)yyVals[0+yyTop]));
}
yyVal = ((Node)yyVals[-1+yyTop]);
}
break;
case 331:
// line 1484 "parse.y"
{
if (((Node)yyVals[-1+yyTop]).getType() == Constants.NODE_STR) {
yyVal = nf.newDStr(((Node)yyVals[-1+yyTop]).getLiteral());
} else {
yyVal = ((Node)yyVals[-1+yyTop]);
}
((Node)yyVals[0+yyTop]).setHeadNode(nf.newStr(((Node)yyVals[0+yyTop]).getLiteral()));
new RuntimeException("[BUG] Want to change " + ((Node)yyVals[0+yyTop]).getClass().getName() + " to ArrayNode.").printStackTrace();
/* $2.nd_set_type(Constants.NODE_ARRAY);*/
ph.list_concat(((Node)yyVal), ((Node)yyVals[0+yyTop]));
}
break;
case 332:
// line 1497 "parse.y"
{
ph.setLexState(LexState.EXPR_END);
yyVal = ((RubyId)yyVals[0+yyTop]);
}
break;
case 344:
// line 1515 "parse.y"
{yyVal = ph.newId(kNIL);}
break;
case 345:
// line 1516 "parse.y"
{yyVal = ph.newId(kSELF);}
break;
case 346:
// line 1517 "parse.y"
{yyVal = ph.newId(kTRUE);}
break;
case 347:
// line 1518 "parse.y"
{yyVal = ph.newId(kFALSE);}
break;
case 348:
// line 1519 "parse.y"
{yyVal = ph.newId(k__FILE__);}
break;
case 349:
// line 1520 "parse.y"
{yyVal = ph.newId(k__LINE__);}
break;
case 350:
// line 1523 "parse.y"
{
yyVal = ph.gettable(((RubyId)yyVals[0+yyTop]));
}
break;
case 353:
// line 1531 "parse.y"
{
yyVal = null;
}
break;
case 354:
// line 1535 "parse.y"
{
ph.setLexState(LexState.EXPR_BEG);
}
break;
case 355:
// line 1539 "parse.y"
{
yyVal = ((Node)yyVals[-1+yyTop]);
}
break;
case 356:
// line 1542 "parse.y"
{yyerrok(); yyVal = null;}
break;
case 357:
// line 1545 "parse.y"
{
yyVal = ((Node)yyVals[-2+yyTop]);
ph.setLexState(LexState.EXPR_BEG);
}
break;
case 358:
// line 1550 "parse.y"
{
yyVal = ((Node)yyVals[-1+yyTop]);
}
break;
case 359:
// line 1555 "parse.y"
{
- yyVal = ph.block_append(nf.newArgs(((Integer)yyVals[-5+yyTop]), ((Node)yyVals[-3+yyTop]), ((RubyId)yyVals[-1+yyTop])), ((Node)yyVals[0+yyTop]));
+ yyVal = ph.block_append(nf.newArgs(((Integer)yyVals[-5+yyTop]), ((Node)yyVals[-3+yyTop]), ((Integer)yyVals[-1+yyTop]).intValue()), ((Node)yyVals[0+yyTop]));
}
break;
case 360:
// line 1559 "parse.y"
{
- yyVal = ph.block_append(nf.newArgs(((Integer)yyVals[-3+yyTop]), ((Node)yyVals[-1+yyTop]), RubyId.newId(ruby, -1)), ((Node)yyVals[0+yyTop]));
+ yyVal = ph.block_append(nf.newArgs(((Integer)yyVals[-3+yyTop]), ((Node)yyVals[-1+yyTop]), -1), ((Node)yyVals[0+yyTop]));
}
break;
case 361:
// line 1563 "parse.y"
{
- yyVal = ph.block_append(nf.newArgs(((Integer)yyVals[-3+yyTop]), null, ((RubyId)yyVals[-1+yyTop])), ((Node)yyVals[0+yyTop]));
+ yyVal = ph.block_append(nf.newArgs(((Integer)yyVals[-3+yyTop]), null, ((Integer)yyVals[-1+yyTop]).intValue()), ((Node)yyVals[0+yyTop]));
}
break;
case 362:
// line 1567 "parse.y"
{
- yyVal = ph.block_append(nf.newArgs(((Integer)yyVals[-1+yyTop]), null, RubyId.newId(ruby, -1)), ((Node)yyVals[0+yyTop]));
+ yyVal = ph.block_append(nf.newArgs(((Integer)yyVals[-1+yyTop]), null, -1), ((Node)yyVals[0+yyTop]));
}
break;
case 363:
// line 1571 "parse.y"
{
- yyVal = ph.block_append(nf.newArgs(null, ((Node)yyVals[-3+yyTop]), ((RubyId)yyVals[-1+yyTop])), ((Node)yyVals[0+yyTop]));
+ yyVal = ph.block_append(nf.newArgs(null, ((Node)yyVals[-3+yyTop]), ((Integer)yyVals[-1+yyTop]).intValue()), ((Node)yyVals[0+yyTop]));
}
break;
case 364:
// line 1575 "parse.y"
{
- yyVal = ph.block_append(nf.newArgs(null, ((Node)yyVals[-1+yyTop]), RubyId.newId(ruby, -1)), ((Node)yyVals[0+yyTop]));
+ yyVal = ph.block_append(nf.newArgs(null, ((Node)yyVals[-1+yyTop]), -1), ((Node)yyVals[0+yyTop]));
}
break;
case 365:
// line 1579 "parse.y"
{
- yyVal = ph.block_append(nf.newArgs(null, null, ((RubyId)yyVals[-1+yyTop])), ((Node)yyVals[0+yyTop]));
+ yyVal = ph.block_append(nf.newArgs(null, null, ((Integer)yyVals[-1+yyTop]).intValue()), ((Node)yyVals[0+yyTop]));
}
break;
case 366:
// line 1583 "parse.y"
{
- yyVal = ph.block_append(nf.newArgs(null, null, RubyId.newId(ruby, -1)), ((Node)yyVals[0+yyTop]));
+ yyVal = ph.block_append(nf.newArgs(null, null, -1), ((Node)yyVals[0+yyTop]));
}
break;
case 367:
// line 1587 "parse.y"
{
- yyVal = nf.newArgs(null, null, RubyId.newId(ruby, -1));
+ yyVal = nf.newArgs(null, null, -1);
}
break;
case 368:
// line 1592 "parse.y"
{
yyerror("formal argument cannot be a constant");
}
break;
case 369:
// line 1596 "parse.y"
{
yyerror("formal argument cannot be an instance variable");
}
break;
case 370:
// line 1600 "parse.y"
{
yyerror("formal argument cannot be a global variable");
}
break;
case 371:
// line 1604 "parse.y"
{
yyerror("formal argument cannot be a class variable");
}
break;
case 372:
// line 1608 "parse.y"
{
if (!((RubyId)yyVals[0+yyTop]).isLocalId())
yyerror("formal argument must be local variable");
else if (ph.local_id(((RubyId)yyVals[0+yyTop])))
yyerror("duplicate argument name");
ph.local_cnt(((RubyId)yyVals[0+yyTop]));
yyVal = new Integer(1);
}
break;
case 374:
// line 1619 "parse.y"
{
yyVal = new Integer(((Integer)yyVal).intValue() + 1);
}
break;
case 375:
// line 1624 "parse.y"
{
if (!((RubyId)yyVals[-2+yyTop]).isLocalId())
yyerror("formal argument must be local variable");
else if (ph.local_id(((RubyId)yyVals[-2+yyTop])))
yyerror("duplicate optional argument name");
yyVal = ph.assignable(((RubyId)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 376:
// line 1633 "parse.y"
{
yyVal = nf.newBlock(((Node)yyVals[0+yyTop]));
((Node)yyVal).setEndNode(((Node)yyVal));
}
break;
case 377:
// line 1638 "parse.y"
{
yyVal = ph.block_append(((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 378:
// line 1643 "parse.y"
{
if (!((RubyId)yyVals[0+yyTop]).isLocalId())
yyerror("rest argument must be local variable");
else if (ph.local_id(((RubyId)yyVals[0+yyTop])))
yyerror("duplicate rest argument name");
yyVal = new Integer(ph.local_cnt(((RubyId)yyVals[0+yyTop])));
}
break;
case 379:
// line 1651 "parse.y"
{
yyVal = new Integer(-2);
}
break;
case 380:
// line 1656 "parse.y"
{
if (!((RubyId)yyVals[0+yyTop]).isLocalId())
yyerror("block argument must be local variable");
else if (ph.local_id(((RubyId)yyVals[0+yyTop])))
yyerror("duplicate block argument name");
yyVal = nf.newBlockArg(((RubyId)yyVals[0+yyTop]));
}
break;
case 381:
// line 1665 "parse.y"
{
yyVal = ((Node)yyVals[0+yyTop]);
}
break;
case 383:
// line 1671 "parse.y"
{
if (((Node)yyVals[0+yyTop]).getType() == Constants.NODE_SELF) {
yyVal = nf.newSelf();
} else {
yyVal = ((Node)yyVals[0+yyTop]);
}
}
break;
case 384:
// line 1678 "parse.y"
{ph.setLexState(LexState.EXPR_BEG);}
break;
case 385:
// line 1679 "parse.y"
{
switch (((Node)yyVals[-2+yyTop]).getType()) {
case Constants.NODE_STR:
case Constants.NODE_DSTR:
case Constants.NODE_XSTR:
case Constants.NODE_DXSTR:
case Constants.NODE_DREGX:
case Constants.NODE_LIT:
case Constants.NODE_ARRAY:
case Constants.NODE_ZARRAY:
yyerror("can't define single method for literals.");
default:
break;
}
yyVal = ((Node)yyVals[-2+yyTop]);
}
break;
case 387:
// line 1698 "parse.y"
{
yyVal = ((Node)yyVals[-1+yyTop]);
}
break;
case 388:
// line 1702 "parse.y"
{
/* if ($1.getLength() % 2 != 0) {
yyerror("odd number list for Hash");
}*/
yyVal = ((Node)yyVals[-1+yyTop]);
}
break;
case 390:
// line 1711 "parse.y"
{
yyVal = ph.list_concat(((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 391:
// line 1716 "parse.y"
{
yyVal = ph.list_append(nf.newList(((Node)yyVals[-2+yyTop])), ((Node)yyVals[0+yyTop]));
}
break;
case 411:
// line 1746 "parse.y"
{yyerrok();}
break;
case 414:
// line 1750 "parse.y"
{yyerrok();}
break;
case 415:
// line 1753 "parse.y"
{
yyVal = null; /*XXX 0;*/
}
break;
// line 2370 "-"
}
yyTop -= YyLenClass.yyLen[yyN];
yyState = yyStates[yyTop];
int yyM = YyLhsClass.yyLhs[yyN];
if (yyState == 0 && yyM == 0) {
yyState = yyFinal;
if (yyToken < 0) {
yyToken = yyLex.advance() ? yyLex.token() : 0;
}
if (yyToken == 0) {
return yyVal;
}
continue yyLoop;
}
if ((yyN = YyGindexClass.yyGindex[yyM]) != 0 && (yyN += yyState) >= 0
&& yyN < YyTableClass.yyTable.length && YyCheckClass.yyCheck[yyN] == yyState)
yyState = YyTableClass.yyTable[yyN];
else
yyState = YyDgotoClass.yyDgoto[yyM];
continue yyLoop;
}
}
}
protected static final class YyLhsClass {
public static final short yyLhs [] = { -1,
74, 0, 5, 6, 6, 6, 6, 77, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 78, 7,
7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
8, 8, 8, 12, 12, 37, 37, 37, 11, 11,
11, 11, 11, 55, 55, 58, 58, 57, 57, 57,
57, 57, 57, 59, 59, 56, 56, 60, 60, 60,
60, 60, 60, 53, 53, 53, 53, 53, 53, 68,
68, 69, 69, 69, 69, 69, 61, 61, 47, 80,
47, 70, 70, 70, 70, 70, 70, 70, 70, 70,
70, 70, 70, 70, 70, 70, 70, 70, 70, 70,
70, 70, 70, 70, 70, 70, 70, 79, 79, 79,
79, 79, 79, 79, 79, 79, 79, 79, 79, 79,
79, 79, 79, 79, 79, 79, 79, 79, 79, 79,
79, 79, 79, 79, 79, 79, 79, 79, 79, 79,
79, 79, 79, 79, 79, 79, 79, 79, 9, 81,
9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
9, 9, 9, 9, 9, 83, 9, 9, 9, 29,
29, 29, 29, 29, 29, 29, 26, 26, 26, 26,
27, 27, 25, 25, 25, 25, 25, 25, 25, 25,
25, 25, 85, 28, 31, 30, 30, 22, 22, 33,
33, 34, 34, 34, 23, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 86, 10, 10, 10,
10, 10, 10, 88, 90, 10, 91, 92, 10, 10,
10, 93, 94, 10, 95, 10, 97, 98, 10, 99,
10, 100, 10, 102, 103, 10, 10, 10, 10, 10,
87, 87, 87, 89, 89, 14, 14, 15, 15, 49,
49, 50, 50, 50, 50, 104, 52, 36, 36, 36,
13, 13, 13, 13, 13, 13, 105, 51, 106, 51,
16, 24, 24, 24, 17, 17, 19, 19, 20, 20,
18, 18, 21, 21, 3, 3, 3, 2, 2, 2,
2, 64, 63, 63, 63, 63, 4, 4, 62, 62,
62, 62, 62, 62, 62, 62, 62, 62, 62, 32,
48, 48, 35, 107, 35, 35, 38, 38, 39, 39,
39, 39, 39, 39, 39, 39, 39, 72, 72, 72,
72, 72, 73, 73, 41, 40, 40, 71, 71, 42,
43, 43, 1, 108, 1, 44, 44, 44, 45, 45,
46, 65, 65, 65, 66, 66, 66, 66, 67, 67,
67, 101, 101, 75, 75, 82, 82, 84, 84, 84,
96, 96, 76, 76, 54,
};
} /* End of class YyLhsClass */
protected static final class YyLenClass {
public static final short yyLen [] = { 2,
0, 2, 2, 1, 1, 3, 2, 0, 4, 3,
3, 3, 2, 3, 3, 3, 3, 3, 0, 5,
4, 3, 3, 3, 1, 3, 2, 1, 3, 3,
2, 2, 1, 1, 1, 1, 4, 4, 2, 4,
4, 2, 2, 1, 3, 1, 3, 1, 2, 3,
2, 2, 1, 1, 3, 2, 3, 1, 4, 3,
3, 3, 1, 1, 4, 3, 3, 3, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 0,
4, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 3, 0,
4, 6, 5, 5, 5, 3, 3, 3, 3, 3,
3, 3, 3, 3, 2, 2, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 2,
2, 3, 3, 3, 3, 0, 4, 5, 1, 1,
2, 4, 2, 5, 2, 3, 3, 4, 4, 6,
1, 1, 1, 3, 2, 5, 2, 5, 4, 7,
3, 1, 0, 2, 2, 2, 1, 1, 3, 1,
1, 3, 4, 2, 1, 1, 1, 1, 1, 1,
1, 1, 1, 6, 3, 3, 2, 4, 3, 3,
4, 3, 1, 4, 3, 1, 0, 6, 2, 1,
2, 6, 6, 0, 0, 7, 0, 0, 7, 5,
4, 0, 0, 9, 0, 6, 0, 0, 8, 0,
5, 0, 9, 0, 0, 12, 1, 1, 1, 1,
1, 1, 2, 1, 1, 1, 5, 1, 2, 1,
1, 1, 2, 1, 3, 0, 5, 2, 4, 4,
2, 4, 4, 3, 2, 1, 0, 5, 0, 5,
5, 1, 4, 2, 1, 1, 1, 1, 2, 1,
6, 1, 1, 2, 1, 1, 1, 1, 1, 2,
2, 2, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 0, 4, 2, 4, 2, 6, 4,
4, 2, 4, 2, 2, 1, 0, 1, 1, 1,
1, 1, 1, 3, 3, 1, 3, 2, 1, 2,
2, 1, 1, 0, 5, 1, 2, 2, 1, 3,
3, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 0, 1, 0, 1, 0, 1, 1,
1, 1, 1, 2, 0,
};
} /* End class YyLenClass */
protected static final class YyDefRedClass {
public static final short yyDefRed [] = { 1,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 254, 257, 0, 277, 278, 279, 280, 0, 0,
0, 345, 344, 346, 347, 0, 0, 0, 19, 0,
349, 348, 0, 0, 341, 340, 0, 343, 337, 338,
328, 228, 327, 329, 229, 230, 351, 352, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 226,
325, 2, 0, 0, 0, 0, 0, 0, 28, 0,
231, 0, 35, 0, 0, 4, 0, 0, 44, 0,
54, 0, 326, 0, 0, 70, 71, 0, 0, 270,
117, 129, 118, 142, 114, 135, 124, 123, 140, 122,
121, 116, 145, 126, 115, 130, 134, 136, 128, 120,
137, 147, 139, 0, 0, 0, 0, 113, 133, 132,
127, 143, 146, 144, 148, 112, 119, 110, 111, 0,
0, 0, 74, 0, 103, 104, 101, 85, 86, 87,
90, 92, 88, 105, 106, 93, 94, 98, 89, 91,
82, 83, 84, 95, 96, 97, 99, 100, 102, 107,
384, 0, 383, 350, 272, 75, 76, 138, 131, 141,
125, 108, 109, 72, 73, 0, 79, 78, 77, 0,
0, 0, 0, 0, 412, 411, 0, 0, 0, 413,
0, 0, 0, 0, 0, 0, 0, 0, 0, 290,
291, 0, 0, 0, 0, 0, 0, 0, 0, 0,
203, 0, 27, 212, 0, 389, 0, 0, 0, 43,
0, 305, 42, 0, 31, 0, 8, 407, 0, 0,
0, 0, 0, 0, 237, 0, 0, 0, 0, 0,
0, 0, 0, 0, 190, 0, 0, 0, 386, 0,
0, 52, 0, 335, 334, 336, 332, 333, 0, 32,
0, 330, 331, 3, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 296, 298, 309, 307, 251, 0, 0, 0, 0,
0, 0, 0, 0, 56, 150, 301, 39, 249, 0,
0, 354, 265, 353, 0, 0, 403, 402, 274, 0,
80, 0, 0, 322, 282, 0, 0, 0, 0, 0,
0, 0, 0, 414, 0, 0, 0, 0, 0, 0,
262, 0, 0, 242, 0, 225, 0, 0, 0, 0,
0, 205, 217, 0, 207, 245, 0, 0, 0, 0,
0, 0, 214, 10, 12, 11, 0, 247, 0, 0,
0, 0, 0, 0, 235, 0, 0, 191, 0, 409,
193, 239, 0, 195, 0, 388, 240, 387, 0, 0,
0, 0, 0, 0, 0, 0, 18, 29, 30, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 304,
0, 0, 397, 0, 0, 398, 0, 0, 0, 0,
395, 396, 0, 0, 0, 0, 0, 22, 0, 24,
0, 23, 26, 221, 0, 50, 57, 0, 0, 356,
0, 0, 0, 0, 0, 0, 370, 369, 368, 371,
0, 0, 0, 0, 0, 0, 376, 366, 0, 373,
0, 0, 0, 0, 0, 317, 0, 0, 288, 0,
283, 0, 0, 0, 0, 0, 0, 261, 285, 255,
284, 258, 0, 0, 0, 0, 0, 0, 0, 0,
211, 241, 0, 0, 0, 0, 0, 0, 0, 204,
216, 0, 0, 0, 390, 244, 0, 0, 0, 0,
0, 197, 9, 0, 0, 0, 21, 0, 196, 0,
0, 0, 0, 0, 0, 0, 0, 0, 303, 41,
0, 0, 202, 302, 40, 201, 0, 294, 0, 0,
292, 0, 0, 300, 38, 299, 37, 0, 0, 55,
0, 268, 0, 0, 271, 0, 275, 0, 378, 380,
0, 0, 358, 0, 364, 382, 0, 365, 0, 362,
81, 0, 0, 320, 0, 289, 0, 0, 323, 0,
0, 286, 0, 260, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 209, 0, 0, 0, 198, 0,
0, 199, 0, 20, 0, 192, 0, 0, 0, 0,
0, 0, 293, 0, 0, 0, 0, 0, 0, 0,
355, 266, 385, 0, 0, 0, 0, 0, 377, 381,
0, 0, 0, 374, 0, 0, 319, 0, 0, 324,
234, 0, 252, 253, 0, 0, 0, 0, 263, 206,
0, 208, 0, 248, 194, 0, 295, 297, 310, 308,
0, 0, 0, 357, 0, 363, 0, 360, 361, 0,
0, 0, 0, 0, 0, 315, 316, 311, 256, 259,
0, 0, 200, 269, 0, 0, 0, 0, 0, 0,
0, 321, 0, 0, 210, 0, 273, 359, 0, 287,
264, 0, 0, 276,
};
} /* End of class YyDefRedClass */
protected static final class YyDgotoClass {
public static final short yyDgoto [] = { 1,
162, 59, 60, 61, 237, 63, 64, 65, 66, 233,
68, 69, 70, 611, 612, 343, 708, 333, 494, 603,
608, 242, 355, 507, 356, 563, 564, 223, 243, 362,
214, 71, 463, 464, 323, 72, 73, 484, 485, 486,
487, 660, 595, 247, 215, 216, 176, 217, 199, 570,
319, 303, 182, 76, 77, 78, 79, 239, 80, 81,
177, 218, 257, 83, 203, 514, 440, 89, 179, 446,
489, 490, 491, 2, 188, 189, 377, 230, 167, 492,
468, 229, 379, 391, 224, 544, 336, 191, 510, 618,
192, 619, 519, 711, 472, 337, 469, 650, 325, 330,
329, 475, 654, 448, 450, 449, 471, 326,
};
} /* End of class YyDgotoClass */
protected static final class YySindexClass {
public static final short yySindex [] = { 0,
0,11890,12220, -237, -60,14758,14486,11890,12716,12716,
11756, 0, 0,14646, 0, 0, 0, 0,12324,12418,
21, 0, 0, 0, 0,12716,14382, 58, 0, -44,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,14088,14088,
-60,11985,13304,14088,16337,14848,14182,14088, -74, 0,
0, 0, 388, 379, -135, 2273, -4, -198, 0, -100,
0, -21, 0, -238, 71, 0, 86,16245, 0, 139,
0, -141, 0, 14, 379, 0, 0,12716, 59, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, -14, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 177, 0, 0, 0, -26,
153, 200, 259, 153, 0, 0, 116, 56, 273, 0,
12716,12716, 300, 303, 21, 58, 62, 0, 68, 0,
0, 0, 14,11890,14088,14088,14088,12520, 1702, 66,
0, 306, 0, 0, 377, 0, -238, -141,12614, 0,
12810, 0, 0,12810, 0, 233, 0, 0, 394, 318,
11890, 136, 69, 136, 0,11985, 422, 0, 425,14088,
58, 144, 378, 205, 0, 214, 348, 205, 0, 76,
0, 0, 0, 0, 0, 0, 0, 0, 136, 0,
136, 0, 0, 0,12128,12716,12716,12716,12716,12220,
12716,12716,14088,14088,14088,14088,14088,14088,14088,14088,
14088,14088,14088,14088,14088,14088,14088,14088,14088,14088,
14088,14088,14088,14088,14088,14088,14088,14088,15185,15220,
13304, 0, 0, 0, 0, 0,15255,15255,14088,13398,
13398,11985,16337, 443, 0, 0, 0, 0, 0, -135,
388, 0, 0, 0,11890,12716, 0, 0, 0, 255,
0,14088, 241, 0, 0,11890, 246,14088,13500,11890,
56,13594, 261, 0, 128, 128, 394,15527,15562,13304,
0, 1834, 2273, 0, 478, 0,14088,15597,15632,13304,
12912, 0, 0,13006, 0, 0, 531, -198, 534, 58,
49, 557, 0, 0, 0, 0,14486, 0,14088,11890,
482,15597,15632, 562, 0, 0, 1069, 0,13696, 0,
0, 0,14088, 0,14088, 0, 0, 0,15667,15702,
13304, 379, -135, -135, -135, -135, 0, 0, 0, 136,
3573, 3573, 3573, 3573, 190, 190, 1475, 3145, 3573, 3573,
2709, 2709, 691, 691, 4453, 190, 190, 208, 208, 236,
41, 41, 136, 136, 136, 269, 0, 0, 21, 0,
0, 271, 0, 280, 21, 0, 536, -76, -76, -76,
0, 0, 21, 21, 2273,14088, 2273, 0, 582, 0,
2273, 0, 0, 0, 590, 0, 0,14088, 388, 0,
12716,11890, 369, 16,15150, 578, 0, 0, 0, 0,
330, 339, 615,11890, 388, 605, 0, 0, 608, 0,
609,14486, 2273, 312, 612, 0,11890, 396, 0, 264,
0, 2273, 241, 406,14088, 636, 33, 0, 0, 0,
0, 0, 0, 21, 0, 0, 21, 600,12716, 352,
0, 0, 2273, 269, 271, 280, 610,14088, 1702, 0,
0, 662,14088, 1702, 0, 0,12912, 667,15255,15255,
669, 0, 0,12716, 2273, 598, 0, 0, 0,14088,
2273, 58, 0, 0, 0, 632,14088,14088, 0, 0,
14088,14088, 0, 0, 0, 0, 398, 0,16153,11890,
0,11890,11890, 0, 0, 0, 0, 2273,13790, 0,
2273, 0, 116, 465, 0, 685, 0,14088, 0, 0,
58, -26, 0, -161, 0, 0, 402, 0, 615, 0,
0,16337, 33, 0,14088, 0,11890, 486, 0,12716,
487, 0, 488, 0, 2273,13892,11890,11890,11890, 0,
128, 398, 1834,13108, 0, 1834, -198, 49, 0, 21,
21, 0, 22, 0, 1069, 0, 0, 2273, 2273, 2273,
2273,14088, 0, 629, 490, 491, 638,14088, 2273,11890,
0, 0, 0, 255, 2273, 716, 241, 578, 0, 0,
608, 722, 608, 0, 77, 0, 0, 0,11890, 0,
0, 153, 0, 0,14088, -97, 504, 505, 0, 0,
14088, 0, 729, 0, 0, 2273, 0, 0, 0, 0,
2273, 509,11890, 0, 396, 0, -161, 0, 0,15745,
15780,13304, -26,11890, 2273, 0, 0, 0, 0, 0,
11890, 1834, 0, 0, -26, 510, 608, 0, 0, 0,
683, 0, 264, 515, 0, 241, 0, 0, 0, 0,
0, 396, 516, 0,
};
} /* End of class YySindexClass */
protected static final class YyRindexClass {
public static final short yyRindex [] = { 0,
0, 184, 0, 0, 0, 0, 0, 498, 0, 0,
518, 0, 0, 0, 0, 0, 0, 0,11468, 6626,
3546, 0, 0, 0, 0, 0, 0,13986, 0, 0,
0, 0, 1794, 3015, 0, 0, 2143, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 215, 694, 668, 138, 0, 0, 0, 5839, 0,
0, 0, 705, 1405, 5280,16018,12046, 6445, 0, 6142,
0,15938, 0,10984, 0, 0, 0, 198, 0, 0,
0,11069, 0,13202, 1733, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 65, 648, 791, 870, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 880,
904, 992, 0, 1001, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 5370, 0, 0, 0, 350,
0, 0, 0, 0, 0, 0, 518, 0, 526, 0,
0, 0, 6227, 6323, 5176, 755, 0, 151, 0, 0,
0, 533, 0, 215, 0, 0, 0, 0,10887, 6806,
0, 1718, 0, 0, 1718, 0, 5355, 5658, 0, 0,
757, 0, 0, 0, 0, 0, 0, 0,14284, 0,
89, 7108, 6711, 7193, 0, 215, 0, 109, 0, 0,
707, 709, 0, 709, 0, 678, 0, 678, 0, 0,
989, 0, 1289, 0, 0, 0, 0, 0, 7288, 0,
7590, 0, 0, 0, 4719, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
694, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 215, 461, 462, 0, 0, 0, 0, 0, 430,
0, 0, 0, 0, 159, 0, 0, 0, 0, 452,
0, 26, 331, 0, 0, 421,11345, 0, 0, 432,
0, 0, 0, 0, 0, 0, 0, 0, 0, 694,
0, 1718, 5961, 0, 0, 0, 0, 0, 0, 694,
0, 0, 0, 0, 0, 0, 0, 216, 474, 772,
772, 0, 0, 0, 0, 0, 0, 0, 0, 89,
0, 0, 0, 0, 0, 385, 707, 0, 721, 0,
0, 0, 36, 0, 690, 0, 0, 0, 0, 0,
694, 4916, 5854, 6078, 6338, 6562, 0, 0, 0, 7675,
1283, 9664, 9817, 9893, 9235, 9421, 9969,10211,10024,10122,
10329,10365, 8613, 8690, 0, 9512, 9588, 9068, 9144, 8992,
8234, 8536, 7770, 8072, 8157, 4323, 3110, 3887,13202, 0,
3451, 4418, 0, 4759, 3982, 0, 0,11553,11553,11659,
0, 0, 4854, 4854, 1641, 0, 5476, 0, 0, 0,
11413, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 159, 0, 772, 0, 497, 0, 0, 0, 0,
622, 0, 496, 498, 0, 215, 0, 0, 215, 0,
215, 0, 18, 34, 72, 0, 521, 555, 0, 555,
0,10401, 555, 0, 0, 35, 0, 0, 0, 0,
0, 0, 788, 0, 1434, 1437, 5265, 0, 0, 0,
0, 0,11284, 2238, 2579, 2674, 0, 0,15868, 0,
0, 1718, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0,10477, 0, 0, 132, 0, 0,
37, 707, 814, 981, 1188, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0,11165, 0, 0, 159,
0, 159, 89, 0, 0, 0, 0,16054, 0, 0,
10513, 0, 0, 0, 0, 0, 0, 0, 0, 0,
772, 350, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 159, 0, 0, 0,
0, 0, 0, 0, 171, 0, 415, 159, 159, 544,
0, 5743, 1718, 0, 0, 1718, 506, 772, 0, 63,
63, 0, 0, 0, 707, 0, 1541,10608,10644,10706,
10742, 0, 0, 0, 0, 0, 0, 0,14574, 159,
0, 0, 0, 452, 737, 0, 331, 0, 0, 0,
215, 215, 215, 0, 0, 161, 0, 201, 498, 0,
0, 0, 0, 0, 0, 555, 0, 0, 0, 0,
0, 0, 0, 0, 0,10792, 0, 0, 0, 0,
16112, 0, 498, 0, 555, 0, 0, 0, 0, 0,
0, 694, 350, 421, 221, 0, 0, 0, 0, 0,
159, 1718, 0, 0, 350, 0, 215, 100, 596, 601,
0, 0, 555, 0, 0, 331, 0, 0, 230, 0,
0, 555, 0, 0,
};
} /* End of class YyRindexClass */
protected static final class YyGindexClass {
public static final short yyGindex [] = { 0,
0, 0, 0, 0, 663, 0, 162, 711, 1147, -2,
-16, -24, 0, 93, -293, -319, 0, -551, 0, 0,
-643, 1252, 602, 0, 524, 6, -340, -69, -280, -213,
103, 818, 0, 523, 0, -184, 0, 166, 342, 248,
-548, -317, 129, 0, -19, -273, 0, 573, 266, 196,
778, 0, 552, 1238, 539, 0, 164, -187, 771, -17,
-11, 446, 0, 12, 125, -242, 0, 51, 8, 4,
-493, 252, 0, 0, 11, 789, 0, 0, 0, 0,
0, -99, 0, 345, 0, 0, -179, 0, -316, 0,
0, 0, 0, 0, 0, 9, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
};
} /* End of class YyGindexClass */
protected static final class YyTableClass {
public static final short yyTable [] = YyTables.yyTable();
} /* End of class YyTableClass */
protected static final class YyCheckClass {
public static final short yyCheck [] = YyTables.yyCheck();
} /* End of class YyCheckClass */
protected static final class YyNameClass {
public static final String yyName [] = {
"end-of-file",null,null,null,null,null,null,null,null,null,"'\\n'",
null,null,null,null,null,null,null,null,null,null,null,null,null,null,
null,null,null,null,null,null,null,null,"'!'",null,null,null,"'%'",
"'&'",null,"'('","')'","'*'","'+'","','","'-'","'.'","'/'",null,null,
null,null,null,null,null,null,null,null,"':'","';'","'<'","'='","'>'",
"'?'",null,null,null,null,null,null,null,null,null,null,null,null,
null,null,null,null,null,null,null,null,null,null,null,null,null,null,
null,"'['",null,"']'","'^'",null,"'`'",null,null,null,null,null,null,
null,null,null,null,null,null,null,null,null,null,null,null,null,null,
null,null,null,null,null,null,"'{'","'|'","'}'","'~'",null,null,null,
null,null,null,null,null,null,null,null,null,null,null,null,null,null,
null,null,null,null,null,null,null,null,null,null,null,null,null,null,
null,null,null,null,null,null,null,null,null,null,null,null,null,null,
null,null,null,null,null,null,null,null,null,null,null,null,null,null,
null,null,null,null,null,null,null,null,null,null,null,null,null,null,
null,null,null,null,null,null,null,null,null,null,null,null,null,null,
null,null,null,null,null,null,null,null,null,null,null,null,null,null,
null,null,null,null,null,null,null,null,null,null,null,null,null,null,
null,null,null,null,null,null,null,null,null,null,null,null,null,null,
null,"kCLASS","kMODULE","kDEF","kUNDEF","kBEGIN","kRESCUE","kENSURE",
"kEND","kIF","kUNLESS","kTHEN","kELSIF","kELSE","kCASE","kWHEN",
"kWHILE","kUNTIL","kFOR","kBREAK","kNEXT","kREDO","kRETRY","kIN",
"kDO","kDO_COND","kDO_BLOCK","kRETURN","kYIELD","kSUPER","kSELF",
"kNIL","kTRUE","kFALSE","kAND","kOR","kNOT","kIF_MOD","kUNLESS_MOD",
"kWHILE_MOD","kUNTIL_MOD","kRESCUE_MOD","kALIAS","kDEFINED","klBEGIN",
"klEND","k__LINE__","k__FILE__","tIDENTIFIER","tFID","tGVAR","tIVAR",
"tCONSTANT","tCVAR","tINTEGER","tFLOAT","tSTRING","tXSTRING",
"tREGEXP","tDSTRING","tDXSTRING","tDREGEXP","tNTH_REF","tBACK_REF",
"tUPLUS","tUMINUS","tPOW","tCMP","tEQ","tEQQ","tNEQ","tGEQ","tLEQ",
"tANDOP","tOROP","tMATCH","tNMATCH","tDOT2","tDOT3","tAREF","tASET",
"tLSHFT","tRSHFT","tCOLON2","tCOLON3","tOP_ASGN","tASSOC","tLPAREN",
"tLBRACK","tLBRACE","tSTAR","tAMPER","tSYMBEG","LAST_TOKEN",
};
} /* End of class YyNameClass */
// line 1757 "parse.y"
// XXX +++
// Helper Methods
void yyerrok() {}
// XXX ---
// -----------------------------------------------------------------------
// scanner stuff
// -----------------------------------------------------------------------
/*
* int yyerror(String msg) {
* char *p, *pe, *buf;
* int len, i;
* rb_compile_error("%s", msg);
* p = lex_p;
* while (lex_pbeg <= p) {
* if (*p == '\n') break;
* p--;
* }
* p++;
* pe = lex_p;
* while (pe < lex_pend) {
* if (*pe == '\n') break;
* pe++;
* }
* len = pe - p;
* if (len > 4) {
* buf = ALLOCA_N(char, len+2);
* MEMCPY(buf, p, char, len);
* buf[len] = '\0';
* rb_compile_error_append("%s", buf);
* i = lex_p - p;
* p = buf; pe = p + len;
* while (p < pe) {
* if (*p != '\t') *p = ' ';
* p++;
* }
* buf[i] = '^';
* buf[i+1] = '\0';
* rb_compile_error_append("%s", buf);
* }
* return 0;
* }
*/
public Node compileString(String f, RubyObject s, int line) {
rs.setLexFileIo(false);
rs.setLexGetsPtr(0);
rs.setLexInput(s);
rs.setLexP(0);
rs.setLexPEnd(0);
ruby.setSourceLine(line - 1);
ph.setCompileForEval(ruby.getInEval());
return yycompile(f, line);
}
public Node compileJavaString(String f, String s, int len, int line) {
return compileString(f, RubyString.m_newString(ruby, s, len), line);
}
public Node compileFile(String f, RubyObject file, int start) {
rs.setLexFileIo(true);
rs.setLexInput(file);
rs.setLexP(0);
rs.setLexPEnd(0);
ruby.setSourceLine(start - 1);
return yycompile(f, start);
}
private void init_for_scanner(String s) {
rs.setLexFileIo(false);
rs.setLexGetsPtr(0);
rs.setLexInput(RubyString.m_newString(ruby, s));
rs.setLexP(0);
rs.setLexPEnd(0);
ruby.setSourceLine(0);
ph.setCompileForEval(ruby.getInEval());
ph.setRubyEndSeen(false); // is there an __end__{} statement?
ph.setHeredocEnd(0);
ph.setRubyInCompile(true);
}
/** This function compiles a given String into a Node.
*
*/
public Node yycompile(String f, int line) {
RubyId sl_id = ruby.intern("SCRIPT_LINES__");
if (!ph.isCompileForEval() && ruby.getSecurityLevel() == 0 && ruby.getClasses().getObjectClass().isConstantDefined(sl_id)) {
RubyHash hash = (RubyHash)ruby.getClasses().getObjectClass().getConstant(sl_id);
RubyString fName = RubyString.m_newString(ruby, f);
// XXX +++
RubyObject debugLines = ruby.getNil(); // = rb_hash_aref(hash, fName);
// XXX ---
if (debugLines.isNil()) {
ph.setRubyDebugLines(RubyArray.m_newArray(ruby));
hash.m_aset(fName, ph.getRubyDebugLines());
} else {
ph.setRubyDebugLines((RubyArray)debugLines);
}
if (line > 1) {
RubyString str = RubyString.m_newString(ruby, null);
while (line > 1) {
ph.getRubyDebugLines().m_push(str);
line--;
}
}
}
ph.setRubyEndSeen(false); // is there an __end__{} statement?
ph.setEvalTree(null); // parser stores Nodes here
ph.setHeredocEnd(0);
ruby.setSourceFile(f); // source file name
ph.setRubyInCompile(true);
try {
yyparse(rs, null);
} catch (Exception e) {
e.printStackTrace();
}
ph.setRubyDebugLines(null); // remove debug info
ph.setCompileForEval(0);
ph.setRubyInCompile(false);
rs.resetStacks();
ph.setClassNest(0);
ph.setInSingle(0);
ph.setInDef(0);
ph.setCurMid(null);
return ph.getEvalTree();
}
}
// line 6722 "-"
| false | true | public Object yyparse (yyInput yyLex)
throws java.io.IOException, yyException {
if (yyMax <= 0) yyMax = 256; // initial size
int yyState = 0, yyStates[] = new int[yyMax]; // state stack
Object yyVal = null, yyVals[] = new Object[yyMax]; // value stack
int yyToken = -1; // current input
int yyErrorFlag = 0; // #tks to shift
yyLoop: for (int yyTop = 0;; ++ yyTop) {
if (yyTop >= yyStates.length) { // dynamically increase
int[] i = new int[yyStates.length+yyMax];
System.arraycopy(yyStates, 0, i, 0, yyStates.length);
yyStates = i;
Object[] o = new Object[yyVals.length+yyMax];
System.arraycopy(yyVals, 0, o, 0, yyVals.length);
yyVals = o;
}
yyStates[yyTop] = yyState;
yyVals[yyTop] = yyVal;
yyDiscarded: for (;;) { // discarding a token does not change stack
int yyN;
if ((yyN = YyDefRedClass.yyDefRed[yyState]) == 0) { // else [default] reduce (yyN)
if (yyToken < 0) {
yyToken = yyLex.advance() ? yyLex.token() : 0;
}
if ((yyN = YySindexClass.yySindex[yyState]) != 0 && (yyN += yyToken) >= 0
&& yyN < YyTableClass.yyTable.length && YyCheckClass.yyCheck[yyN] == yyToken) {
yyState = YyTableClass.yyTable[yyN]; // shift to yyN
yyVal = yyLex.value();
yyToken = -1;
if (yyErrorFlag > 0) -- yyErrorFlag;
continue yyLoop;
}
if ((yyN = YyRindexClass.yyRindex[yyState]) != 0 && (yyN += yyToken) >= 0
&& yyN < YyTableClass.yyTable.length && YyCheckClass.yyCheck[yyN] == yyToken)
yyN = YyTableClass.yyTable[yyN]; // reduce (yyN)
else
switch (yyErrorFlag) {
case 0:
yyerror("syntax error", yyExpecting(yyState));
case 1: case 2:
yyErrorFlag = 3;
do {
if ((yyN = YySindexClass.yySindex[yyStates[yyTop]]) != 0
&& (yyN += yyErrorCode) >= 0 && yyN < YyTableClass.yyTable.length
&& YyCheckClass.yyCheck[yyN] == yyErrorCode) {
yyState = YyTableClass.yyTable[yyN];
yyVal = yyLex.value();
continue yyLoop;
}
} while (-- yyTop >= 0);
throw new yyException("irrecoverable syntax error");
case 3:
if (yyToken == 0) {
throw new yyException("irrecoverable syntax error at end-of-file");
}
yyToken = -1;
continue yyDiscarded; // leave stack alone
}
}
int yyV = yyTop + 1-YyLenClass.yyLen[yyN];
yyVal = yyDefault(yyV > yyTop ? null : yyVals[yyV]);
switch (yyN) {
case 1:
// line 181 "parse.y"
{
yyVal = ruby.getDynamicVars();
ph.setLexState(LexState.EXPR_BEG);
ph.top_local_init();
if (ruby.getRubyClass() == ruby.getClasses().getObjectClass())
ph.setClassNest(0);
else
ph.setClassNest(1);
}
break;
case 2:
// line 191 "parse.y"
{
if (((Node)yyVals[0+yyTop]) != null && !ph.isCompileForEval()) {
/* last expression should not be void */
if (((Node)yyVals[0+yyTop]).getType() != Constants.NODE_BLOCK)
ph.void_expr(((Node)yyVals[0+yyTop]));
else {
Node node = ((Node)yyVals[0+yyTop]);
while (node.getNextNode() != null) {
node = node.getNextNode();
}
ph.void_expr(node.getHeadNode());
}
}
ph.setEvalTree(ph.block_append(ph.getEvalTree(), ((Node)yyVals[0+yyTop])));
ph.top_local_setup();
ph.setClassNest(0);
ruby.setDynamicVars(((RubyVarmap)yyVals[-1+yyTop]));
}
break;
case 3:
// line 211 "parse.y"
{
ph.void_stmts(((Node)yyVals[-1+yyTop]));
yyVal = ((Node)yyVals[-1+yyTop]);
}
break;
case 5:
// line 218 "parse.y"
{
yyVal = ph.newline_node(((Node)yyVals[0+yyTop]));
}
break;
case 6:
// line 222 "parse.y"
{
yyVal = ph.block_append(((Node)yyVals[-2+yyTop]), ph.newline_node(((Node)yyVals[0+yyTop])));
}
break;
case 7:
// line 226 "parse.y"
{
yyVal = ((Node)yyVals[0+yyTop]);
}
break;
case 8:
// line 230 "parse.y"
{ph.setLexState(LexState.EXPR_FNAME);}
break;
case 9:
// line 231 "parse.y"
{
if (ph.isInDef() || ph.isInSingle())
yyerror("alias within method");
yyVal = nf.newAlias(((RubyId)yyVals[-2+yyTop]), ((RubyId)yyVals[0+yyTop]));
}
break;
case 10:
// line 237 "parse.y"
{
if (ph.isInDef() || ph.isInSingle())
yyerror("alias within method");
yyVal = nf.newVAlias(((RubyId)yyVals[-1+yyTop]), ((RubyId)yyVals[0+yyTop]));
}
break;
case 11:
// line 243 "parse.y"
{
if (ph.isInDef() || ph.isInSingle())
yyerror("alias within method");
String buf = "$" + (char)((Node)yyVals[0+yyTop]).getNth();
yyVal = nf.newVAlias(((RubyId)yyVals[-1+yyTop]), ruby.intern(buf));
}
break;
case 12:
// line 250 "parse.y"
{
yyerror("can't make alias for the number variables");
yyVal = null; /*XXX 0*/
}
break;
case 13:
// line 255 "parse.y"
{
if (ph.isInDef() || ph.isInSingle())
yyerror("undef within method");
yyVal = ((Node)yyVals[0+yyTop]);
}
break;
case 14:
// line 261 "parse.y"
{
ph.value_expr(((Node)yyVals[0+yyTop]));
yyVal = nf.newIf(ph.cond(((Node)yyVals[0+yyTop])), ((Node)yyVals[-2+yyTop]), null);
ph.fixpos(yyVal, ((Node)yyVals[0+yyTop]));
}
break;
case 15:
// line 267 "parse.y"
{
ph.value_expr(((Node)yyVals[0+yyTop]));
yyVal = nf.newUnless(ph.cond(((Node)yyVals[0+yyTop])), ((Node)yyVals[-2+yyTop]), null);
ph.fixpos(yyVal, ((Node)yyVals[0+yyTop]));
}
break;
case 16:
// line 273 "parse.y"
{
ph.value_expr(((Node)yyVals[0+yyTop]));
if (((Node)yyVals[-2+yyTop]) != null && ((Node)yyVals[-2+yyTop]) instanceof BeginNode) {
yyVal = nf.newWhile(ph.cond(((Node)yyVals[0+yyTop])), ((Node)yyVals[-2+yyTop]).getBodyNode()); /* , 0*/
} else {
yyVal = nf.newWhile(ph.cond(((Node)yyVals[0+yyTop])), ((Node)yyVals[-2+yyTop])); /* , 1*/
}
}
break;
case 17:
// line 282 "parse.y"
{
ph.value_expr(((Node)yyVals[0+yyTop]));
if (((Node)yyVals[-2+yyTop]) != null && ((Node)yyVals[-2+yyTop]) instanceof BeginNode) {
yyVal = nf.newUntil(ph.cond(((Node)yyVals[0+yyTop])), ((Node)yyVals[-2+yyTop]).getBodyNode()); /* , 0*/
} else {
yyVal = nf.newUntil(ph.cond(((Node)yyVals[0+yyTop])), ((Node)yyVals[-2+yyTop])); /* , 1*/
}
}
break;
case 18:
// line 291 "parse.y"
{
yyVal = nf.newRescue(((Node)yyVals[-2+yyTop]), nf.newResBody(null,((Node)yyVals[0+yyTop]),null), null);
}
break;
case 19:
// line 295 "parse.y"
{
if (ph.isInDef() || ph.isInSingle()) {
yyerror("BEGIN in method");
}
ph.local_push();
}
break;
case 20:
// line 302 "parse.y"
{
ph.setEvalTreeBegin(ph.block_append(ph.getEvalTree(), nf.newPreExe(((Node)yyVals[-1+yyTop]))));
ph.local_pop();
yyVal = null; /*XXX 0;*/
}
break;
case 21:
// line 308 "parse.y"
{
if (ph.isCompileForEval() && (ph.isInDef() || ph.isInSingle())) {
yyerror("END in method; use at_exit");
}
yyVal = nf.newIter(null, nf.newPostExe(), ((Node)yyVals[-1+yyTop]));
}
break;
case 22:
// line 316 "parse.y"
{
ph.value_expr(((Node)yyVals[0+yyTop]));
yyVal = ph.node_assign(((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 23:
// line 321 "parse.y"
{
ph.value_expr(((Node)yyVals[0+yyTop]));
((Node)yyVals[-2+yyTop]).setValueNode(((Node)yyVals[0+yyTop]));
yyVal = ((Node)yyVals[-2+yyTop]);
}
break;
case 24:
// line 327 "parse.y"
{
yyVal = ph.node_assign(((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 26:
// line 333 "parse.y"
{
ph.value_expr(((Node)yyVals[0+yyTop]));
((Node)yyVals[-2+yyTop]).setValueNode(((Node)yyVals[0+yyTop]));
yyVal = ((Node)yyVals[-2+yyTop]);
}
break;
case 27:
// line 339 "parse.y"
{
if (!ph.isCompileForEval() && !ph.isInDef() && !ph.isInSingle())
yyerror("return appeared outside of method");
yyVal = nf.newReturn(ph.ret_args(((Node)yyVals[0+yyTop])));
}
break;
case 29:
// line 346 "parse.y"
{
yyVal = ph.logop(Constants.NODE_AND, ((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 30:
// line 350 "parse.y"
{
yyVal = ph.logop(Constants.NODE_OR, ((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 31:
// line 354 "parse.y"
{
ph.value_expr(((Node)yyVals[0+yyTop]));
yyVal = nf.newNot(ph.cond(((Node)yyVals[0+yyTop])));
}
break;
case 32:
// line 359 "parse.y"
{
yyVal = nf.newNot(ph.cond(((Node)yyVals[0+yyTop])));
}
break;
case 37:
// line 369 "parse.y"
{
ph.value_expr(((Node)yyVals[-3+yyTop]));
yyVal = ph.new_call(((Node)yyVals[-3+yyTop]), ((RubyId)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 38:
// line 374 "parse.y"
{
ph.value_expr(((Node)yyVals[-3+yyTop]));
yyVal = ph.new_call(((Node)yyVals[-3+yyTop]), ((RubyId)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 39:
// line 380 "parse.y"
{
yyVal = ph.new_fcall(((RubyId)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
ph.fixpos(yyVal, ((Node)yyVals[0+yyTop]));
}
break;
case 40:
// line 385 "parse.y"
{
ph.value_expr(((Node)yyVals[-3+yyTop]));
yyVal = ph.new_call(((Node)yyVals[-3+yyTop]), ((RubyId)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
ph.fixpos(yyVal, ((Node)yyVals[-3+yyTop]));
}
break;
case 41:
// line 391 "parse.y"
{
ph.value_expr(((Node)yyVals[-3+yyTop]));
yyVal = ph.new_call(((Node)yyVals[-3+yyTop]), ((RubyId)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
ph.fixpos(yyVal, ((Node)yyVals[-3+yyTop]));
}
break;
case 42:
// line 397 "parse.y"
{
if (!ph.isCompileForEval() && ph.isInDef() && ph.isInSingle())
yyerror("super called outside of method");
yyVal = ph.new_super(((Node)yyVals[0+yyTop]));
ph.fixpos(yyVal, ((Node)yyVals[0+yyTop]));
}
break;
case 43:
// line 404 "parse.y"
{
yyVal = nf.newYield(ph.ret_args(((Node)yyVals[0+yyTop])));
ph.fixpos(yyVal, ((Node)yyVals[0+yyTop]));
}
break;
case 45:
// line 411 "parse.y"
{
yyVal = ((Node)yyVals[-1+yyTop]);
}
break;
case 47:
// line 417 "parse.y"
{
yyVal = nf.newMAsgn(nf.newList(((Node)yyVals[-1+yyTop])), null);
}
break;
case 48:
// line 422 "parse.y"
{
yyVal = nf.newMAsgn(((Node)yyVals[0+yyTop]), null);
}
break;
case 49:
// line 426 "parse.y"
{
yyVal = nf.newMAsgn(ph.list_append(((Node)yyVals[-1+yyTop]),((Node)yyVals[0+yyTop])), null);
}
break;
case 50:
// line 430 "parse.y"
{
yyVal = nf.newMAsgn(((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 51:
// line 434 "parse.y"
{
yyVal = nf.newMAsgn(((Node)yyVals[-1+yyTop]), Node.MINUS_ONE);
}
break;
case 52:
// line 438 "parse.y"
{
yyVal = nf.newMAsgn(null, ((Node)yyVals[0+yyTop]));
}
break;
case 53:
// line 442 "parse.y"
{
yyVal = nf.newMAsgn(null, Node.MINUS_ONE);
}
break;
case 55:
// line 448 "parse.y"
{
yyVal = ((Node)yyVals[-1+yyTop]);
}
break;
case 56:
// line 453 "parse.y"
{
yyVal = nf.newList(((Node)yyVals[-1+yyTop]));
}
break;
case 57:
// line 457 "parse.y"
{
yyVal = ph.list_append(((Node)yyVals[-2+yyTop]), ((Node)yyVals[-1+yyTop]));
}
break;
case 58:
// line 462 "parse.y"
{
yyVal = ph.assignable(((RubyId)yyVals[0+yyTop]), null);
}
break;
case 59:
// line 466 "parse.y"
{
yyVal = ph.aryset(((Node)yyVals[-3+yyTop]), ((Node)yyVals[-1+yyTop]));
}
break;
case 60:
// line 470 "parse.y"
{
yyVal = ph.attrset(((Node)yyVals[-2+yyTop]), ((RubyId)yyVals[0+yyTop]));
}
break;
case 61:
// line 474 "parse.y"
{
yyVal = ph.attrset(((Node)yyVals[-2+yyTop]), ((RubyId)yyVals[0+yyTop]));
}
break;
case 62:
// line 478 "parse.y"
{
yyVal = ph.attrset(((Node)yyVals[-2+yyTop]), ((RubyId)yyVals[0+yyTop]));
}
break;
case 63:
// line 482 "parse.y"
{
ph.rb_backref_error(((Node)yyVals[0+yyTop]));
yyVal = null; /*XXX 0;*/
}
break;
case 64:
// line 488 "parse.y"
{
yyVal = ph.assignable(((RubyId)yyVals[0+yyTop]), null);
}
break;
case 65:
// line 492 "parse.y"
{
yyVal = ph.aryset(((Node)yyVals[-3+yyTop]), ((Node)yyVals[-1+yyTop]));
}
break;
case 66:
// line 496 "parse.y"
{
yyVal = ph.attrset(((Node)yyVals[-2+yyTop]), ((RubyId)yyVals[0+yyTop]));
}
break;
case 67:
// line 500 "parse.y"
{
yyVal = ph.attrset(((Node)yyVals[-2+yyTop]), ((RubyId)yyVals[0+yyTop]));
}
break;
case 68:
// line 504 "parse.y"
{
yyVal = ph.attrset(((Node)yyVals[-2+yyTop]), ((RubyId)yyVals[0+yyTop]));
}
break;
case 69:
// line 508 "parse.y"
{
ph.rb_backref_error(((Node)yyVals[0+yyTop]));
yyVal = null; /*XXX 0;*/
}
break;
case 70:
// line 514 "parse.y"
{
yyerror("class/module name must be CONSTANT");
}
break;
case 75:
// line 523 "parse.y"
{
ph.setLexState(LexState.EXPR_END);
yyVal = ((RubyId)yyVals[0+yyTop]);
}
break;
case 76:
// line 528 "parse.y"
{
ph.setLexState(LexState.EXPR_END);
yyVal = yyVals[0+yyTop];
}
break;
case 79:
// line 537 "parse.y"
{
yyVal = nf.newUndef(((RubyId)yyVals[0+yyTop]));
}
break;
case 80:
// line 540 "parse.y"
{ph.setLexState(LexState.EXPR_FNAME);}
break;
case 81:
// line 541 "parse.y"
{
yyVal = ph.block_append(((Node)yyVals[-3+yyTop]), nf.newUndef(((RubyId)yyVals[0+yyTop])));
}
break;
case 82:
// line 545 "parse.y"
{ yyVal = RubyId.newId(ruby, '|'); }
break;
case 83:
// line 546 "parse.y"
{ yyVal = RubyId.newId(ruby, '^'); }
break;
case 84:
// line 547 "parse.y"
{ yyVal = RubyId.newId(ruby, '&'); }
break;
case 85:
// line 548 "parse.y"
{ yyVal = RubyId.newId(ruby, tCMP); }
break;
case 86:
// line 549 "parse.y"
{ yyVal = RubyId.newId(ruby, tEQ); }
break;
case 87:
// line 550 "parse.y"
{ yyVal = RubyId.newId(ruby, tEQQ); }
break;
case 88:
// line 551 "parse.y"
{ yyVal = RubyId.newId(ruby, tMATCH); }
break;
case 89:
// line 552 "parse.y"
{ yyVal = RubyId.newId(ruby, '>'); }
break;
case 90:
// line 553 "parse.y"
{ yyVal = RubyId.newId(ruby, tGEQ); }
break;
case 91:
// line 554 "parse.y"
{ yyVal = RubyId.newId(ruby, '<'); }
break;
case 92:
// line 555 "parse.y"
{ yyVal = RubyId.newId(ruby, tLEQ); }
break;
case 93:
// line 556 "parse.y"
{ yyVal = RubyId.newId(ruby, tLSHFT); }
break;
case 94:
// line 557 "parse.y"
{ yyVal = RubyId.newId(ruby, tRSHFT); }
break;
case 95:
// line 558 "parse.y"
{ yyVal = RubyId.newId(ruby, '+'); }
break;
case 96:
// line 559 "parse.y"
{ yyVal = RubyId.newId(ruby, '-'); }
break;
case 97:
// line 560 "parse.y"
{ yyVal = RubyId.newId(ruby, '*'); }
break;
case 98:
// line 561 "parse.y"
{ yyVal = RubyId.newId(ruby, '*'); }
break;
case 99:
// line 562 "parse.y"
{ yyVal = RubyId.newId(ruby, '/'); }
break;
case 100:
// line 563 "parse.y"
{ yyVal = RubyId.newId(ruby, '%'); }
break;
case 101:
// line 564 "parse.y"
{ yyVal = RubyId.newId(ruby, tPOW); }
break;
case 102:
// line 565 "parse.y"
{ yyVal = RubyId.newId(ruby, '~'); }
break;
case 103:
// line 566 "parse.y"
{ yyVal = RubyId.newId(ruby, tUPLUS); }
break;
case 104:
// line 567 "parse.y"
{ yyVal = RubyId.newId(ruby, tUMINUS); }
break;
case 105:
// line 568 "parse.y"
{ yyVal = RubyId.newId(ruby, tAREF); }
break;
case 106:
// line 569 "parse.y"
{ yyVal = RubyId.newId(ruby, tASET); }
break;
case 107:
// line 570 "parse.y"
{ yyVal = RubyId.newId(ruby, '`'); }
break;
case 149:
// line 581 "parse.y"
{
ph.value_expr(((Node)yyVals[0+yyTop]));
yyVal = ph.node_assign(((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 150:
// line 585 "parse.y"
{yyVal = ph.assignable(((RubyId)yyVals[-1+yyTop]), null);}
break;
case 151:
// line 586 "parse.y"
{
if (((RubyId)yyVals[-2+yyTop]).intValue() == tOROP) {
((Node)yyVals[-1+yyTop]).setValueNode(((Node)yyVals[0+yyTop]));
yyVal = nf.newOpAsgnOr(ph.gettable(((RubyId)yyVals[-3+yyTop])), ((Node)yyVals[-1+yyTop]));
if (((RubyId)yyVals[-3+yyTop]).isInstanceId()) {
((Node)yyVal).setAId(((RubyId)yyVals[-3+yyTop]));
}
} else if (((RubyId)yyVals[-2+yyTop]).intValue() == tANDOP) {
((Node)yyVals[-1+yyTop]).setValueNode(((Node)yyVals[0+yyTop]));
yyVal = nf.newOpAsgnAnd(ph.gettable(((RubyId)yyVals[-3+yyTop])), ((Node)yyVals[-1+yyTop]));
} else {
yyVal = ((Node)yyVals[-1+yyTop]);
if (yyVal != null) {
((Node)yyVal).setValueNode(ph.call_op(ph.gettable(((RubyId)yyVals[-3+yyTop])),((RubyId)yyVals[-2+yyTop]).intValue(),1,((Node)yyVals[0+yyTop])));
}
}
ph.fixpos(yyVal, ((Node)yyVals[0+yyTop]));
}
break;
case 152:
// line 605 "parse.y"
{
ArrayNode args = nf.newList(((Node)yyVals[0+yyTop]));
ph.list_append(((Node)yyVals[-3+yyTop]), nf.newNil());
ph.list_concat(args, ((Node)yyVals[-3+yyTop]));
if (((RubyId)yyVals[-1+yyTop]).intValue() == Token.tOROP) {
yyVals[-1+yyTop] = RubyId.newId(ruby, 0);
} else if (((RubyId)yyVals[-1+yyTop]).intValue() == Token.tANDOP) {
yyVals[-1+yyTop] = RubyId.newId(ruby, 1);
}
yyVal = nf.newOpAsgn1(((Node)yyVals[-5+yyTop]), ((RubyId)yyVals[-1+yyTop]), args);
ph.fixpos(yyVal, ((Node)yyVals[-5+yyTop]));
}
break;
case 153:
// line 619 "parse.y"
{
if (((RubyId)yyVals[-1+yyTop]).intValue() == Token.tOROP) {
yyVals[-1+yyTop] = RubyId.newId(ruby, 0);
} else if (((RubyId)yyVals[-1+yyTop]).intValue() == Token.tANDOP) {
yyVals[-1+yyTop] = RubyId.newId(ruby, 1);
}
yyVal = nf.newOpAsgn2(((Node)yyVals[-4+yyTop]), ((RubyId)yyVals[-2+yyTop]), ((RubyId)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
ph.fixpos(yyVal, ((Node)yyVals[-4+yyTop]));
}
break;
case 154:
// line 629 "parse.y"
{
if (((RubyId)yyVals[-1+yyTop]).intValue() == Token.tOROP) {
yyVals[-1+yyTop] = RubyId.newId(ruby, 0);
} else if (((RubyId)yyVals[-1+yyTop]).intValue() == Token.tANDOP) {
yyVals[-1+yyTop] = RubyId.newId(ruby, 1);
}
yyVal = nf.newOpAsgn2(((Node)yyVals[-4+yyTop]), ((RubyId)yyVals[-2+yyTop]), ((RubyId)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
ph.fixpos(yyVal, ((Node)yyVals[-4+yyTop]));
}
break;
case 155:
// line 639 "parse.y"
{
if (((RubyId)yyVals[-1+yyTop]).intValue() == Token.tOROP) {
yyVals[-1+yyTop] = RubyId.newId(ruby, 0);
} else if (((RubyId)yyVals[-1+yyTop]).intValue() == Token.tANDOP) {
yyVals[-1+yyTop] = RubyId.newId(ruby, 1);
}
yyVal = nf.newOpAsgn2(((Node)yyVals[-4+yyTop]), ((RubyId)yyVals[-2+yyTop]), ((RubyId)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
ph.fixpos(yyVal, ((Node)yyVals[-4+yyTop]));
}
break;
case 156:
// line 649 "parse.y"
{
ph.rb_backref_error(((Node)yyVals[-2+yyTop]));
yyVal = null; /*XXX 0*/
}
break;
case 157:
// line 654 "parse.y"
{
yyVal = nf.newDot2(((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 158:
// line 658 "parse.y"
{
yyVal = nf.newDot3(((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 159:
// line 662 "parse.y"
{
yyVal = ph.call_op(((Node)yyVals[-2+yyTop]), '+', 1, ((Node)yyVals[0+yyTop]));
}
break;
case 160:
// line 666 "parse.y"
{
yyVal = ph.call_op(((Node)yyVals[-2+yyTop]), '-', 1, ((Node)yyVals[0+yyTop]));
}
break;
case 161:
// line 670 "parse.y"
{
yyVal = ph.call_op(((Node)yyVals[-2+yyTop]), '*', 1, ((Node)yyVals[0+yyTop]));
}
break;
case 162:
// line 674 "parse.y"
{
yyVal = ph.call_op(((Node)yyVals[-2+yyTop]), '/', 1, ((Node)yyVals[0+yyTop]));
}
break;
case 163:
// line 678 "parse.y"
{
yyVal = ph.call_op(((Node)yyVals[-2+yyTop]), '%', 1, ((Node)yyVals[0+yyTop]));
}
break;
case 164:
// line 682 "parse.y"
{
boolean need_negate = false;
if (((Node)yyVals[-2+yyTop]) instanceof LitNode) {
if (((Node)yyVals[-2+yyTop]).getLiteral() instanceof RubyFixnum ||
((Node)yyVals[-2+yyTop]).getLiteral() instanceof RubyFloat ||
((Node)yyVals[-2+yyTop]).getLiteral() instanceof RubyBignum) {
if (((Node)yyVals[-2+yyTop]).getLiteral().funcall(ruby.intern("<"), RubyFixnum.zero(ruby)).isTrue()) {
((Node)yyVals[-2+yyTop]).setLiteral(((Node)yyVals[-2+yyTop]).getLiteral().funcall(ruby.intern("-@")));
need_negate = true;
}
}
}
yyVal = ph.call_op(((Node)yyVals[-2+yyTop]), tPOW, 1, ((Node)yyVals[0+yyTop]));
if (need_negate) {
yyVal = ph.call_op(((Node)yyVal), tUMINUS, 0, null);
}
}
break;
case 165:
// line 701 "parse.y"
{
if (((Node)yyVals[0+yyTop]) != null && ((Node)yyVals[0+yyTop]) instanceof LitNode) {
yyVal = ((Node)yyVals[0+yyTop]);
} else {
yyVal = ph.call_op(((Node)yyVals[0+yyTop]), tUPLUS, 0, null);
}
}
break;
case 166:
// line 709 "parse.y"
{
if (((Node)yyVals[0+yyTop]) != null && ((Node)yyVals[0+yyTop]) instanceof LitNode && ((Node)yyVals[0+yyTop]).getLiteral() instanceof RubyFixnum) {
long i = ((RubyFixnum)((Node)yyVals[0+yyTop]).getLiteral()).getValue();
((Node)yyVals[0+yyTop]).setLiteral(RubyFixnum.m_newFixnum(ruby, -i));
yyVal = ((Node)yyVals[0+yyTop]);
} else {
yyVal = ph.call_op(((Node)yyVals[0+yyTop]), tUMINUS, 0, null);
}
}
break;
case 167:
// line 720 "parse.y"
{
yyVal = ph.call_op(((Node)yyVals[-2+yyTop]), '|', 1, ((Node)yyVals[0+yyTop]));
}
break;
case 168:
// line 724 "parse.y"
{
yyVal = ph.call_op(((Node)yyVals[-2+yyTop]), '^', 1, ((Node)yyVals[0+yyTop]));
}
break;
case 169:
// line 728 "parse.y"
{
yyVal = ph.call_op(((Node)yyVals[-2+yyTop]), '&', 1, ((Node)yyVals[0+yyTop]));
}
break;
case 170:
// line 732 "parse.y"
{
yyVal = ph.call_op(((Node)yyVals[-2+yyTop]), tCMP, 1, ((Node)yyVals[0+yyTop]));
}
break;
case 171:
// line 736 "parse.y"
{
yyVal = ph.call_op(((Node)yyVals[-2+yyTop]), '>', 1, ((Node)yyVals[0+yyTop]));
}
break;
case 172:
// line 740 "parse.y"
{
yyVal = ph.call_op(((Node)yyVals[-2+yyTop]), tGEQ, 1, ((Node)yyVals[0+yyTop]));
}
break;
case 173:
// line 744 "parse.y"
{
yyVal = ph.call_op(((Node)yyVals[-2+yyTop]), '<', 1, ((Node)yyVals[0+yyTop]));
}
break;
case 174:
// line 748 "parse.y"
{
yyVal = ph.call_op(((Node)yyVals[-2+yyTop]), tLEQ, 1, ((Node)yyVals[0+yyTop]));
}
break;
case 175:
// line 752 "parse.y"
{
yyVal = ph.call_op(((Node)yyVals[-2+yyTop]), tEQ, 1, ((Node)yyVals[0+yyTop]));
}
break;
case 176:
// line 756 "parse.y"
{
yyVal = ph.call_op(((Node)yyVals[-2+yyTop]), tEQQ, 1, ((Node)yyVals[0+yyTop]));
}
break;
case 177:
// line 760 "parse.y"
{
yyVal = nf.newNot(ph.call_op(((Node)yyVals[-2+yyTop]), tEQ, 1, ((Node)yyVals[0+yyTop])));
}
break;
case 178:
// line 764 "parse.y"
{
yyVal = ph.match_gen(((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 179:
// line 768 "parse.y"
{
yyVal = nf.newNot(ph.match_gen(((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop])));
}
break;
case 180:
// line 772 "parse.y"
{
ph.value_expr(((Node)yyVals[0+yyTop]));
yyVal = nf.newNot(ph.cond(((Node)yyVals[0+yyTop])));
}
break;
case 181:
// line 777 "parse.y"
{
yyVal = ph.call_op(((Node)yyVals[0+yyTop]), '~', 0, null);
}
break;
case 182:
// line 781 "parse.y"
{
yyVal = ph.call_op(((Node)yyVals[-2+yyTop]), tLSHFT, 1, ((Node)yyVals[0+yyTop]));
}
break;
case 183:
// line 785 "parse.y"
{
yyVal = ph.call_op(((Node)yyVals[-2+yyTop]), tRSHFT, 1, ((Node)yyVals[0+yyTop]));
}
break;
case 184:
// line 789 "parse.y"
{
yyVal = ph.logop(Constants.NODE_AND, ((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 185:
// line 793 "parse.y"
{
yyVal = ph.logop(Constants.NODE_OR, ((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 186:
// line 796 "parse.y"
{ ph.setInDefined(true);}
break;
case 187:
// line 797 "parse.y"
{
ph.setInDefined(false);
yyVal = nf.newDefined(((Node)yyVals[0+yyTop]));
}
break;
case 188:
// line 802 "parse.y"
{
ph.value_expr(((Node)yyVals[-4+yyTop]));
yyVal = nf.newIf(ph.cond(((Node)yyVals[-4+yyTop])), ((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
ph.fixpos(yyVal, ((Node)yyVals[-4+yyTop]));
}
break;
case 189:
// line 808 "parse.y"
{
yyVal = ((Node)yyVals[0+yyTop]);
}
break;
case 191:
// line 814 "parse.y"
{
yyVal = nf.newList(((Node)yyVals[-1+yyTop]));
}
break;
case 192:
// line 818 "parse.y"
{
yyVal = ph.list_append(((Node)yyVals[-3+yyTop]), ((Node)yyVals[-1+yyTop]));
}
break;
case 193:
// line 822 "parse.y"
{
yyVal = ((Node)yyVals[-1+yyTop]);
}
break;
case 194:
// line 826 "parse.y"
{
ph.value_expr(((Node)yyVals[-1+yyTop]));
yyVal = ph.arg_concat(((Node)yyVals[-4+yyTop]), ((Node)yyVals[-1+yyTop]));
}
break;
case 195:
// line 831 "parse.y"
{
yyVal = nf.newList(nf.newHash(((Node)yyVals[-1+yyTop])));
}
break;
case 196:
// line 835 "parse.y"
{
ph.value_expr(((Node)yyVals[-1+yyTop]));
yyVal = nf.newRestArgs(((Node)yyVals[-1+yyTop]));
}
break;
case 197:
// line 841 "parse.y"
{
yyVal = ((Node)yyVals[-1+yyTop]);
}
break;
case 198:
// line 845 "parse.y"
{
yyVal = ((Node)yyVals[-2+yyTop]);
}
break;
case 199:
// line 849 "parse.y"
{
yyVal = nf.newList(((Node)yyVals[-2+yyTop]));
}
break;
case 200:
// line 853 "parse.y"
{
yyVal = ph.list_append(((Node)yyVals[-4+yyTop]), ((Node)yyVals[-2+yyTop]));
}
break;
case 203:
// line 861 "parse.y"
{
yyVal = nf.newList(((Node)yyVals[0+yyTop]));
}
break;
case 204:
// line 865 "parse.y"
{
yyVal = ph.list_append(((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 205:
// line 869 "parse.y"
{
yyVal = ph.arg_blk_pass(((Node)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 206:
// line 873 "parse.y"
{
ph.value_expr(((Node)yyVals[-1+yyTop]));
yyVal = ph.arg_concat(((Node)yyVals[-4+yyTop]), ((Node)yyVals[-1+yyTop]));
yyVal = ph.arg_blk_pass(((Node)yyVal), ((Node)yyVals[0+yyTop]));
}
break;
case 207:
// line 879 "parse.y"
{
yyVal = nf.newList(nf.newHash(((Node)yyVals[-1+yyTop])));
yyVal = ph.arg_blk_pass(((Node)yyVal), ((Node)yyVals[0+yyTop]));
}
break;
case 208:
// line 884 "parse.y"
{
ph.value_expr(((Node)yyVals[-1+yyTop]));
yyVal = ph.arg_concat(nf.newList(nf.newHash(((Node)yyVals[-4+yyTop]))), ((Node)yyVals[-1+yyTop]));
yyVal = ph.arg_blk_pass(((Node)yyVal), ((Node)yyVals[0+yyTop]));
}
break;
case 209:
// line 890 "parse.y"
{
yyVal = ph.list_append(((Node)yyVals[-3+yyTop]), nf.newHash(((Node)yyVals[-1+yyTop])));
yyVal = ph.arg_blk_pass(((Node)yyVal), ((Node)yyVals[0+yyTop]));
}
break;
case 210:
// line 895 "parse.y"
{
ph.value_expr(((Node)yyVals[-1+yyTop]));
yyVal = ph.arg_concat(ph.list_append(((Node)yyVals[-6+yyTop]), nf.newHash(((Node)yyVals[-4+yyTop]))), ((Node)yyVals[-1+yyTop]));
yyVal = ph.arg_blk_pass(((Node)yyVal), ((Node)yyVals[0+yyTop]));
}
break;
case 211:
// line 901 "parse.y"
{
ph.value_expr(((Node)yyVals[-1+yyTop]));
yyVal = ph.arg_blk_pass(nf.newRestArgs(((Node)yyVals[-1+yyTop])), ((Node)yyVals[0+yyTop]));
}
break;
case 213:
// line 907 "parse.y"
{ rs.CMDARG_PUSH(); }
break;
case 214:
// line 908 "parse.y"
{
rs.CMDARG_POP();
yyVal = ((Node)yyVals[0+yyTop]);
}
break;
case 215:
// line 914 "parse.y"
{
ph.value_expr(((Node)yyVals[0+yyTop]));
yyVal = nf.newBlockPass(((Node)yyVals[0+yyTop]));
}
break;
case 216:
// line 920 "parse.y"
{
yyVal = ((Node)yyVals[0+yyTop]);
}
break;
case 218:
// line 926 "parse.y"
{
ph.value_expr(((Node)yyVals[0+yyTop]));
yyVal = nf.newList(((Node)yyVals[0+yyTop]));
}
break;
case 219:
// line 931 "parse.y"
{
ph.value_expr(((Node)yyVals[0+yyTop]));
yyVal = ph.list_append(((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 220:
// line 937 "parse.y"
{
ph.value_expr(((Node)yyVals[0+yyTop]));
yyVal = ((Node)yyVals[0+yyTop]);
}
break;
case 222:
// line 944 "parse.y"
{
ph.value_expr(((Node)yyVals[0+yyTop]));
yyVal = ph.list_append(((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 223:
// line 949 "parse.y"
{
ph.value_expr(((Node)yyVals[0+yyTop]));
yyVal = ph.arg_concat(((Node)yyVals[-3+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 224:
// line 954 "parse.y"
{
ph.value_expr(((Node)yyVals[0+yyTop]));
yyVal = ((Node)yyVals[0+yyTop]);
}
break;
case 225:
// line 960 "parse.y"
{
yyVal = ((Node)yyVals[0+yyTop]);
if (((Node)yyVals[0+yyTop]) != null) {
if (((Node)yyVals[0+yyTop]).getType() == Constants.NODE_ARRAY && ((Node)yyVals[0+yyTop]).getNextNode() == null) {
yyVal = ((Node)yyVals[0+yyTop]).getHeadNode();
} else if (((Node)yyVals[0+yyTop]).getType() == Constants.NODE_BLOCK_PASS) {
ph.rb_compile_error("block argument should not be given");
}
}
}
break;
case 226:
// line 972 "parse.y"
{
yyVal = nf.newLit(((RubyObject)yyVals[0+yyTop]));
}
break;
case 228:
// line 977 "parse.y"
{
yyVal = nf.newXStr(((RubyObject)yyVals[0+yyTop]));
}
break;
case 233:
// line 985 "parse.y"
{
yyVal = nf.newVCall(((RubyId)yyVals[0+yyTop]));
}
break;
case 234:
// line 994 "parse.y"
{
if (((Node)yyVals[-3+yyTop]) == null && ((Node)yyVals[-2+yyTop]) == null && ((Node)yyVals[-1+yyTop]) == null)
yyVal = nf.newBegin(((Node)yyVals[-4+yyTop]));
else {
if (((Node)yyVals[-3+yyTop]) != null) yyVals[-4+yyTop] = nf.newRescue(((Node)yyVals[-4+yyTop]), ((Node)yyVals[-3+yyTop]), ((Node)yyVals[-2+yyTop]));
else if (((Node)yyVals[-2+yyTop]) != null) {
ph.rb_warn("else without rescue is useless");
yyVals[-4+yyTop] = ph.block_append(((Node)yyVals[-4+yyTop]), ((Node)yyVals[-2+yyTop]));
}
if (((Node)yyVals[-1+yyTop]) != null) yyVals[-4+yyTop] = nf.newEnsure(((Node)yyVals[-4+yyTop]), ((Node)yyVals[-1+yyTop]));
yyVal = ((Node)yyVals[-4+yyTop]);
}
ph.fixpos(yyVal, ((Node)yyVals[-4+yyTop]));
}
break;
case 235:
// line 1009 "parse.y"
{
yyVal = ((Node)yyVals[-1+yyTop]);
}
break;
case 236:
// line 1013 "parse.y"
{
ph.value_expr(((Node)yyVals[-2+yyTop]));
yyVal = nf.newColon2(((Node)yyVals[-2+yyTop]), ((RubyId)yyVals[0+yyTop]));
}
break;
case 237:
// line 1018 "parse.y"
{
yyVal = nf.newColon3(((RubyId)yyVals[0+yyTop]));
}
break;
case 238:
// line 1022 "parse.y"
{
ph.value_expr(((Node)yyVals[-3+yyTop]));
yyVal = nf.newCall(((Node)yyVals[-3+yyTop]), ph.newId(tAREF), ((Node)yyVals[-1+yyTop]));
}
break;
case 239:
// line 1027 "parse.y"
{
if (((Node)yyVals[-1+yyTop]) == null) {
yyVal = nf.newZArray(); /* zero length array*/
} else {
yyVal = ((Node)yyVals[-1+yyTop]);
}
}
break;
case 240:
// line 1035 "parse.y"
{
yyVal = nf.newHash(((Node)yyVals[-1+yyTop]));
}
break;
case 241:
// line 1039 "parse.y"
{
if (!ph.isCompileForEval() && !ph.isInDef() && !ph.isInSingle())
yyerror("return appeared outside of method");
ph.value_expr(((Node)yyVals[-1+yyTop]));
yyVal = nf.newReturn(((Node)yyVals[-1+yyTop]));
}
break;
case 242:
// line 1046 "parse.y"
{
if (!ph.isCompileForEval() && !ph.isInDef() && !ph.isInSingle())
yyerror("return appeared outside of method");
yyVal = nf.newReturn(null);
}
break;
case 243:
// line 1052 "parse.y"
{
if (!ph.isCompileForEval() && !ph.isInDef() && !ph.isInSingle())
yyerror("return appeared outside of method");
yyVal = nf.newReturn(null);
}
break;
case 244:
// line 1058 "parse.y"
{
ph.value_expr(((Node)yyVals[-1+yyTop]));
yyVal = nf.newYield(((Node)yyVals[-1+yyTop]));
}
break;
case 245:
// line 1063 "parse.y"
{
yyVal = nf.newYield(null);
}
break;
case 246:
// line 1067 "parse.y"
{
yyVal = nf.newYield(null);
}
break;
case 247:
// line 1070 "parse.y"
{ph.setInDefined(true);}
break;
case 248:
// line 1071 "parse.y"
{
ph.setInDefined(false);
yyVal = nf.newDefined(((Node)yyVals[-1+yyTop]));
}
break;
case 249:
// line 1076 "parse.y"
{
((Node)yyVals[0+yyTop]).setIterNode(nf.newFCall(((RubyId)yyVals[-1+yyTop]), null));
yyVal = ((Node)yyVals[0+yyTop]);
}
break;
case 251:
// line 1082 "parse.y"
{
if (((Node)yyVals[-1+yyTop]) != null && ((Node)yyVals[-1+yyTop]).getType() == Constants.NODE_BLOCK_PASS) {
ph.rb_compile_error("both block arg and actual block given");
}
((Node)yyVals[0+yyTop]).setIterNode(((Node)yyVals[-1+yyTop]));
yyVal = ((Node)yyVals[0+yyTop]);
ph.fixpos(yyVal, ((Node)yyVals[-1+yyTop]));
}
break;
case 252:
// line 1094 "parse.y"
{
ph.value_expr(((Node)yyVals[-4+yyTop]));
yyVal = nf.newIf(ph.cond(((Node)yyVals[-4+yyTop])), ((Node)yyVals[-2+yyTop]), ((Node)yyVals[-1+yyTop]));
ph.fixpos(yyVal, ((Node)yyVals[-4+yyTop]));
}
break;
case 253:
// line 1103 "parse.y"
{
ph.value_expr(((Node)yyVals[-4+yyTop]));
yyVal = nf.newUnless(ph.cond(((Node)yyVals[-4+yyTop])), ((Node)yyVals[-2+yyTop]), ((Node)yyVals[-1+yyTop]));
ph.fixpos(yyVal, ((Node)yyVals[-4+yyTop]));
}
break;
case 254:
// line 1108 "parse.y"
{ rs.COND_PUSH(); }
break;
case 255:
// line 1108 "parse.y"
{ rs.COND_POP(); }
break;
case 256:
// line 1111 "parse.y"
{
ph.value_expr(((Node)yyVals[-4+yyTop]));
yyVal = nf.newWhile(ph.cond(((Node)yyVals[-4+yyTop])), ((Node)yyVals[-1+yyTop])); /* , 1*/
ph.fixpos(yyVal, ((Node)yyVals[-4+yyTop]));
}
break;
case 257:
// line 1116 "parse.y"
{ rs.COND_PUSH(); }
break;
case 258:
// line 1116 "parse.y"
{ rs.COND_POP(); }
break;
case 259:
// line 1119 "parse.y"
{
ph.value_expr(((Node)yyVals[-4+yyTop]));
yyVal = nf.newUntil(ph.cond(((Node)yyVals[-4+yyTop])), ((Node)yyVals[-1+yyTop])); /*, 1*/
ph.fixpos(yyVal, ((Node)yyVals[-4+yyTop]));
}
break;
case 260:
// line 1127 "parse.y"
{
ph.value_expr(((Node)yyVals[-3+yyTop]));
yyVal = nf.newCase(((Node)yyVals[-3+yyTop]), ((Node)yyVals[-1+yyTop]));
ph.fixpos(yyVal, ((Node)yyVals[-3+yyTop]));
}
break;
case 261:
// line 1133 "parse.y"
{
yyVal = ((Node)yyVals[-1+yyTop]);
}
break;
case 262:
// line 1136 "parse.y"
{ rs.COND_PUSH(); }
break;
case 263:
// line 1136 "parse.y"
{ rs.COND_POP(); }
break;
case 264:
// line 1139 "parse.y"
{
ph.value_expr(((Node)yyVals[-4+yyTop]));
yyVal = nf.newFor(((Node)yyVals[-7+yyTop]), ((Node)yyVals[-4+yyTop]), ((Node)yyVals[-1+yyTop]));
ph.fixpos(yyVal, ((Node)yyVals[-7+yyTop]));
}
break;
case 265:
// line 1145 "parse.y"
{
if (ph.isInDef() || ph.isInSingle())
yyerror("class definition in method body");
ph.setClassNest(ph.getClassNest() + 1);
ph.local_push();
yyVal = new Integer(ruby.getSourceLine());
}
break;
case 266:
// line 1154 "parse.y"
{
yyVal = nf.newClass(((RubyId)yyVals[-4+yyTop]), ((Node)yyVals[-1+yyTop]), ((Node)yyVals[-3+yyTop]));
((Node)yyVal).setLine(((Integer)yyVals[-2+yyTop]).intValue());
ph.local_pop();
ph.setClassNest(ph.getClassNest() - 1);
}
break;
case 267:
// line 1161 "parse.y"
{
yyVal = new Integer(ph.getInDef());
ph.setInDef(0);
}
break;
case 268:
// line 1166 "parse.y"
{
yyVal = new Integer(ph.getInSingle());
ph.setInSingle(0);
ph.setClassNest(ph.getClassNest() - 1);
ph.local_push();
}
break;
case 269:
// line 1174 "parse.y"
{
yyVal = nf.newSClass(((Node)yyVals[-5+yyTop]), ((Node)yyVals[-1+yyTop]));
ph.fixpos(yyVal, ((Node)yyVals[-5+yyTop]));
ph.local_pop();
ph.setClassNest(ph.getClassNest() - 1);
ph.setInDef(((Integer)yyVals[-4+yyTop]).intValue());
ph.setInSingle(((Integer)yyVals[-2+yyTop]).intValue());
}
break;
case 270:
// line 1183 "parse.y"
{
if (ph.isInDef() || ph.isInSingle())
yyerror("module definition in method body");
ph.setClassNest(ph.getClassNest() + 1);
ph.local_push();
yyVal = new Integer(ruby.getSourceLine());
}
break;
case 271:
// line 1192 "parse.y"
{
yyVal = nf.newModule(((RubyId)yyVals[-3+yyTop]), ((Node)yyVals[-1+yyTop]));
((Node)yyVal).setLine(((Integer)yyVals[-2+yyTop]).intValue());
ph.local_pop();
ph.setClassNest(ph.getClassNest() - 1);
}
break;
case 272:
// line 1199 "parse.y"
{
if (ph.isInDef() || ph.isInSingle())
yyerror("nested method definition");
yyVal = ph.getCurMid();
ph.setCurMid(((RubyId)yyVals[0+yyTop]));
ph.setInDef(ph.getInDef() + 1);
ph.local_push();
}
break;
case 273:
// line 1213 "parse.y"
{
if (((Node)yyVals[-3+yyTop]) != null)
yyVals[-4+yyTop] = nf.newRescue(((Node)yyVals[-4+yyTop]), ((Node)yyVals[-3+yyTop]), ((Node)yyVals[-2+yyTop]));
else if (((Node)yyVals[-2+yyTop]) != null) {
ph.rb_warn("else without rescue is useless");
yyVals[-4+yyTop] = ph.block_append(((Node)yyVals[-4+yyTop]), ((Node)yyVals[-2+yyTop]));
}
if (((Node)yyVals[-1+yyTop]) != null)
yyVals[-4+yyTop] = nf.newEnsure(((Node)yyVals[-4+yyTop]), ((Node)yyVals[-1+yyTop]));
/* NOEX_PRIVATE for toplevel */
yyVal = nf.newDefn(((RubyId)yyVals[-7+yyTop]), ((Node)yyVals[-5+yyTop]), ((Node)yyVals[-4+yyTop]), ph.getClassNest() !=0 ?
Constants.NOEX_PUBLIC : Constants.NOEX_PRIVATE);
if (((RubyId)yyVals[-7+yyTop]).isAttrSetId())
((Node)yyVal).setNoex(Constants.NOEX_PUBLIC);
ph.fixpos(yyVal, ((Node)yyVals[-5+yyTop]));
ph.local_pop();
ph.setInDef(ph.getInDef() - 1);
ph.setCurMid(((RubyId)yyVals[-6+yyTop]));
}
break;
case 274:
// line 1233 "parse.y"
{ph.setLexState(LexState.EXPR_FNAME);}
break;
case 275:
// line 1234 "parse.y"
{
ph.value_expr(((Node)yyVals[-3+yyTop]));
ph.setInSingle(ph.getInSingle() + 1);
ph.local_push();
ph.setLexState(LexState.EXPR_END); /* force for args */
}
break;
case 276:
// line 1246 "parse.y"
{
if (((Node)yyVals[-3+yyTop]) != null)
yyVals[-4+yyTop] = nf.newRescue(((Node)yyVals[-4+yyTop]), ((Node)yyVals[-3+yyTop]), ((Node)yyVals[-2+yyTop]));
else if (((Node)yyVals[-2+yyTop]) != null) {
ph.rb_warn("else without rescue is useless");
yyVals[-4+yyTop] = ph.block_append(((Node)yyVals[-4+yyTop]), ((Node)yyVals[-2+yyTop]));
}
if (((Node)yyVals[-1+yyTop]) != null) yyVals[-4+yyTop] = nf.newEnsure(((Node)yyVals[-4+yyTop]), ((Node)yyVals[-1+yyTop]));
yyVal = nf.newDefs(((Node)yyVals[-10+yyTop]), ((RubyId)yyVals[-7+yyTop]), ((Node)yyVals[-5+yyTop]), ((Node)yyVals[-4+yyTop]));
ph.fixpos(yyVal, ((Node)yyVals[-10+yyTop]));
ph.local_pop();
ph.setInSingle(ph.getInSingle() - 1);
}
break;
case 277:
// line 1261 "parse.y"
{
yyVal = nf.newBreak();
}
break;
case 278:
// line 1265 "parse.y"
{
yyVal = nf.newNext();
}
break;
case 279:
// line 1269 "parse.y"
{
yyVal = nf.newRedo();
}
break;
case 280:
// line 1273 "parse.y"
{
yyVal = nf.newRetry();
}
break;
case 287:
// line 1288 "parse.y"
{
ph.value_expr(((Node)yyVals[-3+yyTop]));
yyVal = nf.newIf(ph.cond(((Node)yyVals[-3+yyTop])), ((Node)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
ph.fixpos(yyVal, ((Node)yyVals[-3+yyTop]));
}
break;
case 289:
// line 1296 "parse.y"
{
yyVal = ((Node)yyVals[0+yyTop]);
}
break;
case 293:
// line 1305 "parse.y"
{
yyVal = Node.ONE; /* new Integer(1); //XXX (Node*)1;*/
}
break;
case 294:
// line 1309 "parse.y"
{
yyVal = Node.ONE; /* new Integer(1); //XXX (Node*)1;*/
}
break;
case 295:
// line 1313 "parse.y"
{
yyVal = ((Node)yyVals[-1+yyTop]);
}
break;
case 296:
// line 1318 "parse.y"
{
yyVal = ph.dyna_push();
}
break;
case 297:
// line 1324 "parse.y"
{
yyVal = nf.newIter(((Node)yyVals[-2+yyTop]), null, ((Node)yyVals[-1+yyTop]));
ph.fixpos(yyVal, ((Node)yyVals[-2+yyTop])!=null?((Node)yyVals[-2+yyTop]):((Node)yyVals[-1+yyTop]));
ph.dyna_pop(((RubyVarmap)yyVals[-3+yyTop]));
}
break;
case 298:
// line 1331 "parse.y"
{
if (((Node)yyVals[-1+yyTop]) != null && ((Node)yyVals[-1+yyTop]).getType() == Constants.NODE_BLOCK_PASS) {
ph.rb_compile_error("both block arg and actual block given");
}
((Node)yyVals[0+yyTop]).setIterNode(((Node)yyVals[-1+yyTop]));
yyVal = ((Node)yyVals[0+yyTop]);
ph.fixpos(yyVal, ((Node)yyVals[0+yyTop]));
}
break;
case 299:
// line 1340 "parse.y"
{
ph.value_expr(((Node)yyVals[-3+yyTop]));
yyVal = ph.new_call(((Node)yyVals[-3+yyTop]), ((RubyId)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 300:
// line 1345 "parse.y"
{
ph.value_expr(((Node)yyVals[-3+yyTop]));
yyVal = ph.new_call(((Node)yyVals[-3+yyTop]), ((RubyId)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 301:
// line 1351 "parse.y"
{
yyVal = ph.new_fcall(((RubyId)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
ph.fixpos(yyVal, ((Node)yyVals[0+yyTop]));
}
break;
case 302:
// line 1356 "parse.y"
{
ph.value_expr(((Node)yyVals[-3+yyTop]));
yyVal = ph.new_call(((Node)yyVals[-3+yyTop]), ((RubyId)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
ph.fixpos(yyVal, ((Node)yyVals[-3+yyTop]));
}
break;
case 303:
// line 1362 "parse.y"
{
ph.value_expr(((Node)yyVals[-3+yyTop]));
yyVal = ph.new_call(((Node)yyVals[-3+yyTop]), ((RubyId)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
ph.fixpos(yyVal, ((Node)yyVals[-3+yyTop]));
}
break;
case 304:
// line 1368 "parse.y"
{
ph.value_expr(((Node)yyVals[-2+yyTop]));
yyVal = ph.new_call(((Node)yyVals[-2+yyTop]), ((RubyId)yyVals[0+yyTop]), null);
}
break;
case 305:
// line 1373 "parse.y"
{
if (!ph.isCompileForEval() && !ph.isInDef() && !ph.isInSingle() && !ph.isInDefined())
yyerror("super called outside of method");
yyVal = ph.new_super(((Node)yyVals[0+yyTop]));
}
break;
case 306:
// line 1379 "parse.y"
{
if (!ph.isCompileForEval() && !ph.isInDef() && !ph.isInSingle() && !ph.isInDefined())
yyerror("super called outside of method");
yyVal = nf.newZSuper();
}
break;
case 307:
// line 1386 "parse.y"
{
yyVal = ph.dyna_push();
}
break;
case 308:
// line 1391 "parse.y"
{
yyVal = nf.newIter(((Node)yyVals[-2+yyTop]), null, ((Node)yyVals[-1+yyTop]));
ph.fixpos(yyVal, ((Node)yyVals[-1+yyTop]));
ph.dyna_pop(((RubyVarmap)yyVals[-3+yyTop]));
}
break;
case 309:
// line 1397 "parse.y"
{
yyVal = ph.dyna_push();
}
break;
case 310:
// line 1402 "parse.y"
{
yyVal = nf.newIter(((Node)yyVals[-2+yyTop]), null, ((Node)yyVals[-1+yyTop]));
ph.fixpos(yyVal, ((Node)yyVals[-1+yyTop]));
ph.dyna_pop(((RubyVarmap)yyVals[-3+yyTop]));
}
break;
case 311:
// line 1411 "parse.y"
{
yyVal = nf.newWhen(((Node)yyVals[-3+yyTop]), ((Node)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 313:
// line 1417 "parse.y"
{
ph.value_expr(((Node)yyVals[0+yyTop]));
yyVal = ph.list_append(((Node)yyVals[-3+yyTop]), nf.newWhen(((Node)yyVals[0+yyTop]), null, null));
}
break;
case 314:
// line 1422 "parse.y"
{
ph.value_expr(((Node)yyVals[0+yyTop]));
yyVal = nf.newList(nf.newWhen(((Node)yyVals[0+yyTop]), null, null));
}
break;
case 319:
// line 1434 "parse.y"
{
yyVal = ((Node)yyVals[0+yyTop]);
}
break;
case 321:
// line 1442 "parse.y"
{
if (((Node)yyVals[-3+yyTop]) != null) {
yyVals[-3+yyTop] = ph.node_assign(((Node)yyVals[-3+yyTop]), nf.newGVar(ruby.intern("$!")));
yyVals[-1+yyTop] = ph.block_append(((Node)yyVals[-3+yyTop]), ((Node)yyVals[-1+yyTop]));
}
yyVal = nf.newResBody(((Node)yyVals[-4+yyTop]), ((Node)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
ph.fixpos(yyVal, ((Node)yyVals[-4+yyTop])!=null?((Node)yyVals[-4+yyTop]):((Node)yyVals[-1+yyTop]));
}
break;
case 324:
// line 1454 "parse.y"
{
if (((Node)yyVals[0+yyTop]) != null)
yyVal = ((Node)yyVals[0+yyTop]);
else
/* place holder */
yyVal = nf.newNil();
}
break;
case 326:
// line 1464 "parse.y"
{
yyVal = ((RubyId)yyVals[0+yyTop]).toSymbol();
}
break;
case 328:
// line 1470 "parse.y"
{
yyVal = nf.newStr(((RubyObject)yyVals[0+yyTop]));
}
break;
case 330:
// line 1475 "parse.y"
{
if (((Node)yyVals[-1+yyTop]).getType() == Constants.NODE_DSTR) {
ph.list_append(((Node)yyVals[-1+yyTop]), nf.newStr(((RubyObject)yyVals[0+yyTop])));
} else {
((RubyString)((Node)yyVals[-1+yyTop]).getLiteral()).m_concat((RubyString)((RubyObject)yyVals[0+yyTop]));
}
yyVal = ((Node)yyVals[-1+yyTop]);
}
break;
case 331:
// line 1484 "parse.y"
{
if (((Node)yyVals[-1+yyTop]).getType() == Constants.NODE_STR) {
yyVal = nf.newDStr(((Node)yyVals[-1+yyTop]).getLiteral());
} else {
yyVal = ((Node)yyVals[-1+yyTop]);
}
((Node)yyVals[0+yyTop]).setHeadNode(nf.newStr(((Node)yyVals[0+yyTop]).getLiteral()));
new RuntimeException("[BUG] Want to change " + ((Node)yyVals[0+yyTop]).getClass().getName() + " to ArrayNode.").printStackTrace();
/* $2.nd_set_type(Constants.NODE_ARRAY);*/
ph.list_concat(((Node)yyVal), ((Node)yyVals[0+yyTop]));
}
break;
case 332:
// line 1497 "parse.y"
{
ph.setLexState(LexState.EXPR_END);
yyVal = ((RubyId)yyVals[0+yyTop]);
}
break;
case 344:
// line 1515 "parse.y"
{yyVal = ph.newId(kNIL);}
break;
case 345:
// line 1516 "parse.y"
{yyVal = ph.newId(kSELF);}
break;
case 346:
// line 1517 "parse.y"
{yyVal = ph.newId(kTRUE);}
break;
case 347:
// line 1518 "parse.y"
{yyVal = ph.newId(kFALSE);}
break;
case 348:
// line 1519 "parse.y"
{yyVal = ph.newId(k__FILE__);}
break;
case 349:
// line 1520 "parse.y"
{yyVal = ph.newId(k__LINE__);}
break;
case 350:
// line 1523 "parse.y"
{
yyVal = ph.gettable(((RubyId)yyVals[0+yyTop]));
}
break;
case 353:
// line 1531 "parse.y"
{
yyVal = null;
}
break;
case 354:
// line 1535 "parse.y"
{
ph.setLexState(LexState.EXPR_BEG);
}
break;
case 355:
// line 1539 "parse.y"
{
yyVal = ((Node)yyVals[-1+yyTop]);
}
break;
case 356:
// line 1542 "parse.y"
{yyerrok(); yyVal = null;}
break;
case 357:
// line 1545 "parse.y"
{
yyVal = ((Node)yyVals[-2+yyTop]);
ph.setLexState(LexState.EXPR_BEG);
}
break;
case 358:
// line 1550 "parse.y"
{
yyVal = ((Node)yyVals[-1+yyTop]);
}
break;
case 359:
// line 1555 "parse.y"
{
yyVal = ph.block_append(nf.newArgs(((Integer)yyVals[-5+yyTop]), ((Node)yyVals[-3+yyTop]), ((RubyId)yyVals[-1+yyTop])), ((Node)yyVals[0+yyTop]));
}
break;
case 360:
// line 1559 "parse.y"
{
yyVal = ph.block_append(nf.newArgs(((Integer)yyVals[-3+yyTop]), ((Node)yyVals[-1+yyTop]), RubyId.newId(ruby, -1)), ((Node)yyVals[0+yyTop]));
}
break;
case 361:
// line 1563 "parse.y"
{
yyVal = ph.block_append(nf.newArgs(((Integer)yyVals[-3+yyTop]), null, ((RubyId)yyVals[-1+yyTop])), ((Node)yyVals[0+yyTop]));
}
break;
case 362:
// line 1567 "parse.y"
{
yyVal = ph.block_append(nf.newArgs(((Integer)yyVals[-1+yyTop]), null, RubyId.newId(ruby, -1)), ((Node)yyVals[0+yyTop]));
}
break;
case 363:
// line 1571 "parse.y"
{
yyVal = ph.block_append(nf.newArgs(null, ((Node)yyVals[-3+yyTop]), ((RubyId)yyVals[-1+yyTop])), ((Node)yyVals[0+yyTop]));
}
break;
case 364:
// line 1575 "parse.y"
{
yyVal = ph.block_append(nf.newArgs(null, ((Node)yyVals[-1+yyTop]), RubyId.newId(ruby, -1)), ((Node)yyVals[0+yyTop]));
}
break;
case 365:
// line 1579 "parse.y"
{
yyVal = ph.block_append(nf.newArgs(null, null, ((RubyId)yyVals[-1+yyTop])), ((Node)yyVals[0+yyTop]));
}
break;
case 366:
// line 1583 "parse.y"
{
yyVal = ph.block_append(nf.newArgs(null, null, RubyId.newId(ruby, -1)), ((Node)yyVals[0+yyTop]));
}
break;
case 367:
// line 1587 "parse.y"
{
yyVal = nf.newArgs(null, null, RubyId.newId(ruby, -1));
}
break;
case 368:
// line 1592 "parse.y"
{
yyerror("formal argument cannot be a constant");
}
break;
case 369:
// line 1596 "parse.y"
{
yyerror("formal argument cannot be an instance variable");
}
break;
case 370:
// line 1600 "parse.y"
{
yyerror("formal argument cannot be a global variable");
}
break;
case 371:
// line 1604 "parse.y"
{
yyerror("formal argument cannot be a class variable");
}
break;
case 372:
// line 1608 "parse.y"
{
if (!((RubyId)yyVals[0+yyTop]).isLocalId())
yyerror("formal argument must be local variable");
else if (ph.local_id(((RubyId)yyVals[0+yyTop])))
yyerror("duplicate argument name");
ph.local_cnt(((RubyId)yyVals[0+yyTop]));
yyVal = new Integer(1);
}
break;
case 374:
// line 1619 "parse.y"
{
yyVal = new Integer(((Integer)yyVal).intValue() + 1);
}
break;
case 375:
// line 1624 "parse.y"
{
if (!((RubyId)yyVals[-2+yyTop]).isLocalId())
yyerror("formal argument must be local variable");
else if (ph.local_id(((RubyId)yyVals[-2+yyTop])))
yyerror("duplicate optional argument name");
yyVal = ph.assignable(((RubyId)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 376:
// line 1633 "parse.y"
{
yyVal = nf.newBlock(((Node)yyVals[0+yyTop]));
((Node)yyVal).setEndNode(((Node)yyVal));
}
break;
case 377:
// line 1638 "parse.y"
{
yyVal = ph.block_append(((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 378:
// line 1643 "parse.y"
{
if (!((RubyId)yyVals[0+yyTop]).isLocalId())
yyerror("rest argument must be local variable");
else if (ph.local_id(((RubyId)yyVals[0+yyTop])))
yyerror("duplicate rest argument name");
yyVal = new Integer(ph.local_cnt(((RubyId)yyVals[0+yyTop])));
}
break;
case 379:
// line 1651 "parse.y"
{
yyVal = new Integer(-2);
}
break;
case 380:
// line 1656 "parse.y"
{
if (!((RubyId)yyVals[0+yyTop]).isLocalId())
yyerror("block argument must be local variable");
else if (ph.local_id(((RubyId)yyVals[0+yyTop])))
yyerror("duplicate block argument name");
yyVal = nf.newBlockArg(((RubyId)yyVals[0+yyTop]));
}
break;
case 381:
// line 1665 "parse.y"
{
yyVal = ((Node)yyVals[0+yyTop]);
}
break;
case 383:
// line 1671 "parse.y"
{
if (((Node)yyVals[0+yyTop]).getType() == Constants.NODE_SELF) {
yyVal = nf.newSelf();
} else {
yyVal = ((Node)yyVals[0+yyTop]);
}
}
break;
case 384:
// line 1678 "parse.y"
{ph.setLexState(LexState.EXPR_BEG);}
break;
case 385:
// line 1679 "parse.y"
{
switch (((Node)yyVals[-2+yyTop]).getType()) {
case Constants.NODE_STR:
case Constants.NODE_DSTR:
case Constants.NODE_XSTR:
case Constants.NODE_DXSTR:
case Constants.NODE_DREGX:
case Constants.NODE_LIT:
case Constants.NODE_ARRAY:
case Constants.NODE_ZARRAY:
yyerror("can't define single method for literals.");
default:
break;
}
yyVal = ((Node)yyVals[-2+yyTop]);
}
break;
case 387:
// line 1698 "parse.y"
{
yyVal = ((Node)yyVals[-1+yyTop]);
}
break;
case 388:
// line 1702 "parse.y"
{
/* if ($1.getLength() % 2 != 0) {
yyerror("odd number list for Hash");
}*/
yyVal = ((Node)yyVals[-1+yyTop]);
}
break;
case 390:
// line 1711 "parse.y"
{
yyVal = ph.list_concat(((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 391:
// line 1716 "parse.y"
{
yyVal = ph.list_append(nf.newList(((Node)yyVals[-2+yyTop])), ((Node)yyVals[0+yyTop]));
}
break;
case 411:
// line 1746 "parse.y"
{yyerrok();}
break;
case 414:
// line 1750 "parse.y"
{yyerrok();}
break;
case 415:
// line 1753 "parse.y"
{
yyVal = null; /*XXX 0;*/
}
break;
// line 2370 "-"
}
yyTop -= YyLenClass.yyLen[yyN];
yyState = yyStates[yyTop];
int yyM = YyLhsClass.yyLhs[yyN];
if (yyState == 0 && yyM == 0) {
yyState = yyFinal;
if (yyToken < 0) {
yyToken = yyLex.advance() ? yyLex.token() : 0;
}
if (yyToken == 0) {
return yyVal;
}
continue yyLoop;
}
if ((yyN = YyGindexClass.yyGindex[yyM]) != 0 && (yyN += yyState) >= 0
&& yyN < YyTableClass.yyTable.length && YyCheckClass.yyCheck[yyN] == yyState)
yyState = YyTableClass.yyTable[yyN];
else
yyState = YyDgotoClass.yyDgoto[yyM];
continue yyLoop;
}
}
| public Object yyparse (yyInput yyLex)
throws java.io.IOException, yyException {
if (yyMax <= 0) yyMax = 256; // initial size
int yyState = 0, yyStates[] = new int[yyMax]; // state stack
Object yyVal = null, yyVals[] = new Object[yyMax]; // value stack
int yyToken = -1; // current input
int yyErrorFlag = 0; // #tks to shift
yyLoop: for (int yyTop = 0;; ++ yyTop) {
if (yyTop >= yyStates.length) { // dynamically increase
int[] i = new int[yyStates.length+yyMax];
System.arraycopy(yyStates, 0, i, 0, yyStates.length);
yyStates = i;
Object[] o = new Object[yyVals.length+yyMax];
System.arraycopy(yyVals, 0, o, 0, yyVals.length);
yyVals = o;
}
yyStates[yyTop] = yyState;
yyVals[yyTop] = yyVal;
yyDiscarded: for (;;) { // discarding a token does not change stack
int yyN;
if ((yyN = YyDefRedClass.yyDefRed[yyState]) == 0) { // else [default] reduce (yyN)
if (yyToken < 0) {
yyToken = yyLex.advance() ? yyLex.token() : 0;
}
if ((yyN = YySindexClass.yySindex[yyState]) != 0 && (yyN += yyToken) >= 0
&& yyN < YyTableClass.yyTable.length && YyCheckClass.yyCheck[yyN] == yyToken) {
yyState = YyTableClass.yyTable[yyN]; // shift to yyN
yyVal = yyLex.value();
yyToken = -1;
if (yyErrorFlag > 0) -- yyErrorFlag;
continue yyLoop;
}
if ((yyN = YyRindexClass.yyRindex[yyState]) != 0 && (yyN += yyToken) >= 0
&& yyN < YyTableClass.yyTable.length && YyCheckClass.yyCheck[yyN] == yyToken)
yyN = YyTableClass.yyTable[yyN]; // reduce (yyN)
else
switch (yyErrorFlag) {
case 0:
yyerror("syntax error", yyExpecting(yyState));
case 1: case 2:
yyErrorFlag = 3;
do {
if ((yyN = YySindexClass.yySindex[yyStates[yyTop]]) != 0
&& (yyN += yyErrorCode) >= 0 && yyN < YyTableClass.yyTable.length
&& YyCheckClass.yyCheck[yyN] == yyErrorCode) {
yyState = YyTableClass.yyTable[yyN];
yyVal = yyLex.value();
continue yyLoop;
}
} while (-- yyTop >= 0);
throw new yyException("irrecoverable syntax error");
case 3:
if (yyToken == 0) {
throw new yyException("irrecoverable syntax error at end-of-file");
}
yyToken = -1;
continue yyDiscarded; // leave stack alone
}
}
int yyV = yyTop + 1-YyLenClass.yyLen[yyN];
yyVal = yyDefault(yyV > yyTop ? null : yyVals[yyV]);
switch (yyN) {
case 1:
// line 181 "parse.y"
{
yyVal = ruby.getDynamicVars();
ph.setLexState(LexState.EXPR_BEG);
ph.top_local_init();
if (ruby.getRubyClass() == ruby.getClasses().getObjectClass())
ph.setClassNest(0);
else
ph.setClassNest(1);
}
break;
case 2:
// line 191 "parse.y"
{
if (((Node)yyVals[0+yyTop]) != null && !ph.isCompileForEval()) {
/* last expression should not be void */
if (((Node)yyVals[0+yyTop]).getType() != Constants.NODE_BLOCK)
ph.void_expr(((Node)yyVals[0+yyTop]));
else {
Node node = ((Node)yyVals[0+yyTop]);
while (node.getNextNode() != null) {
node = node.getNextNode();
}
ph.void_expr(node.getHeadNode());
}
}
ph.setEvalTree(ph.block_append(ph.getEvalTree(), ((Node)yyVals[0+yyTop])));
ph.top_local_setup();
ph.setClassNest(0);
ruby.setDynamicVars(((RubyVarmap)yyVals[-1+yyTop]));
}
break;
case 3:
// line 211 "parse.y"
{
ph.void_stmts(((Node)yyVals[-1+yyTop]));
yyVal = ((Node)yyVals[-1+yyTop]);
}
break;
case 5:
// line 218 "parse.y"
{
yyVal = ph.newline_node(((Node)yyVals[0+yyTop]));
}
break;
case 6:
// line 222 "parse.y"
{
yyVal = ph.block_append(((Node)yyVals[-2+yyTop]), ph.newline_node(((Node)yyVals[0+yyTop])));
}
break;
case 7:
// line 226 "parse.y"
{
yyVal = ((Node)yyVals[0+yyTop]);
}
break;
case 8:
// line 230 "parse.y"
{ph.setLexState(LexState.EXPR_FNAME);}
break;
case 9:
// line 231 "parse.y"
{
if (ph.isInDef() || ph.isInSingle())
yyerror("alias within method");
yyVal = nf.newAlias(((RubyId)yyVals[-2+yyTop]), ((RubyId)yyVals[0+yyTop]));
}
break;
case 10:
// line 237 "parse.y"
{
if (ph.isInDef() || ph.isInSingle())
yyerror("alias within method");
yyVal = nf.newVAlias(((RubyId)yyVals[-1+yyTop]), ((RubyId)yyVals[0+yyTop]));
}
break;
case 11:
// line 243 "parse.y"
{
if (ph.isInDef() || ph.isInSingle())
yyerror("alias within method");
String buf = "$" + (char)((Node)yyVals[0+yyTop]).getNth();
yyVal = nf.newVAlias(((RubyId)yyVals[-1+yyTop]), ruby.intern(buf));
}
break;
case 12:
// line 250 "parse.y"
{
yyerror("can't make alias for the number variables");
yyVal = null; /*XXX 0*/
}
break;
case 13:
// line 255 "parse.y"
{
if (ph.isInDef() || ph.isInSingle())
yyerror("undef within method");
yyVal = ((Node)yyVals[0+yyTop]);
}
break;
case 14:
// line 261 "parse.y"
{
ph.value_expr(((Node)yyVals[0+yyTop]));
yyVal = nf.newIf(ph.cond(((Node)yyVals[0+yyTop])), ((Node)yyVals[-2+yyTop]), null);
ph.fixpos(yyVal, ((Node)yyVals[0+yyTop]));
}
break;
case 15:
// line 267 "parse.y"
{
ph.value_expr(((Node)yyVals[0+yyTop]));
yyVal = nf.newUnless(ph.cond(((Node)yyVals[0+yyTop])), ((Node)yyVals[-2+yyTop]), null);
ph.fixpos(yyVal, ((Node)yyVals[0+yyTop]));
}
break;
case 16:
// line 273 "parse.y"
{
ph.value_expr(((Node)yyVals[0+yyTop]));
if (((Node)yyVals[-2+yyTop]) != null && ((Node)yyVals[-2+yyTop]) instanceof BeginNode) {
yyVal = nf.newWhile(ph.cond(((Node)yyVals[0+yyTop])), ((Node)yyVals[-2+yyTop]).getBodyNode()); /* , 0*/
} else {
yyVal = nf.newWhile(ph.cond(((Node)yyVals[0+yyTop])), ((Node)yyVals[-2+yyTop])); /* , 1*/
}
}
break;
case 17:
// line 282 "parse.y"
{
ph.value_expr(((Node)yyVals[0+yyTop]));
if (((Node)yyVals[-2+yyTop]) != null && ((Node)yyVals[-2+yyTop]) instanceof BeginNode) {
yyVal = nf.newUntil(ph.cond(((Node)yyVals[0+yyTop])), ((Node)yyVals[-2+yyTop]).getBodyNode()); /* , 0*/
} else {
yyVal = nf.newUntil(ph.cond(((Node)yyVals[0+yyTop])), ((Node)yyVals[-2+yyTop])); /* , 1*/
}
}
break;
case 18:
// line 291 "parse.y"
{
yyVal = nf.newRescue(((Node)yyVals[-2+yyTop]), nf.newResBody(null,((Node)yyVals[0+yyTop]),null), null);
}
break;
case 19:
// line 295 "parse.y"
{
if (ph.isInDef() || ph.isInSingle()) {
yyerror("BEGIN in method");
}
ph.local_push();
}
break;
case 20:
// line 302 "parse.y"
{
ph.setEvalTreeBegin(ph.block_append(ph.getEvalTree(), nf.newPreExe(((Node)yyVals[-1+yyTop]))));
ph.local_pop();
yyVal = null; /*XXX 0;*/
}
break;
case 21:
// line 308 "parse.y"
{
if (ph.isCompileForEval() && (ph.isInDef() || ph.isInSingle())) {
yyerror("END in method; use at_exit");
}
yyVal = nf.newIter(null, nf.newPostExe(), ((Node)yyVals[-1+yyTop]));
}
break;
case 22:
// line 316 "parse.y"
{
ph.value_expr(((Node)yyVals[0+yyTop]));
yyVal = ph.node_assign(((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 23:
// line 321 "parse.y"
{
ph.value_expr(((Node)yyVals[0+yyTop]));
((Node)yyVals[-2+yyTop]).setValueNode(((Node)yyVals[0+yyTop]));
yyVal = ((Node)yyVals[-2+yyTop]);
}
break;
case 24:
// line 327 "parse.y"
{
yyVal = ph.node_assign(((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 26:
// line 333 "parse.y"
{
ph.value_expr(((Node)yyVals[0+yyTop]));
((Node)yyVals[-2+yyTop]).setValueNode(((Node)yyVals[0+yyTop]));
yyVal = ((Node)yyVals[-2+yyTop]);
}
break;
case 27:
// line 339 "parse.y"
{
if (!ph.isCompileForEval() && !ph.isInDef() && !ph.isInSingle())
yyerror("return appeared outside of method");
yyVal = nf.newReturn(ph.ret_args(((Node)yyVals[0+yyTop])));
}
break;
case 29:
// line 346 "parse.y"
{
yyVal = ph.logop(Constants.NODE_AND, ((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 30:
// line 350 "parse.y"
{
yyVal = ph.logop(Constants.NODE_OR, ((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 31:
// line 354 "parse.y"
{
ph.value_expr(((Node)yyVals[0+yyTop]));
yyVal = nf.newNot(ph.cond(((Node)yyVals[0+yyTop])));
}
break;
case 32:
// line 359 "parse.y"
{
yyVal = nf.newNot(ph.cond(((Node)yyVals[0+yyTop])));
}
break;
case 37:
// line 369 "parse.y"
{
ph.value_expr(((Node)yyVals[-3+yyTop]));
yyVal = ph.new_call(((Node)yyVals[-3+yyTop]), ((RubyId)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 38:
// line 374 "parse.y"
{
ph.value_expr(((Node)yyVals[-3+yyTop]));
yyVal = ph.new_call(((Node)yyVals[-3+yyTop]), ((RubyId)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 39:
// line 380 "parse.y"
{
yyVal = ph.new_fcall(((RubyId)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
ph.fixpos(yyVal, ((Node)yyVals[0+yyTop]));
}
break;
case 40:
// line 385 "parse.y"
{
ph.value_expr(((Node)yyVals[-3+yyTop]));
yyVal = ph.new_call(((Node)yyVals[-3+yyTop]), ((RubyId)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
ph.fixpos(yyVal, ((Node)yyVals[-3+yyTop]));
}
break;
case 41:
// line 391 "parse.y"
{
ph.value_expr(((Node)yyVals[-3+yyTop]));
yyVal = ph.new_call(((Node)yyVals[-3+yyTop]), ((RubyId)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
ph.fixpos(yyVal, ((Node)yyVals[-3+yyTop]));
}
break;
case 42:
// line 397 "parse.y"
{
if (!ph.isCompileForEval() && ph.isInDef() && ph.isInSingle())
yyerror("super called outside of method");
yyVal = ph.new_super(((Node)yyVals[0+yyTop]));
ph.fixpos(yyVal, ((Node)yyVals[0+yyTop]));
}
break;
case 43:
// line 404 "parse.y"
{
yyVal = nf.newYield(ph.ret_args(((Node)yyVals[0+yyTop])));
ph.fixpos(yyVal, ((Node)yyVals[0+yyTop]));
}
break;
case 45:
// line 411 "parse.y"
{
yyVal = ((Node)yyVals[-1+yyTop]);
}
break;
case 47:
// line 417 "parse.y"
{
yyVal = nf.newMAsgn(nf.newList(((Node)yyVals[-1+yyTop])), null);
}
break;
case 48:
// line 422 "parse.y"
{
yyVal = nf.newMAsgn(((Node)yyVals[0+yyTop]), null);
}
break;
case 49:
// line 426 "parse.y"
{
yyVal = nf.newMAsgn(ph.list_append(((Node)yyVals[-1+yyTop]),((Node)yyVals[0+yyTop])), null);
}
break;
case 50:
// line 430 "parse.y"
{
yyVal = nf.newMAsgn(((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 51:
// line 434 "parse.y"
{
yyVal = nf.newMAsgn(((Node)yyVals[-1+yyTop]), Node.MINUS_ONE);
}
break;
case 52:
// line 438 "parse.y"
{
yyVal = nf.newMAsgn(null, ((Node)yyVals[0+yyTop]));
}
break;
case 53:
// line 442 "parse.y"
{
yyVal = nf.newMAsgn(null, Node.MINUS_ONE);
}
break;
case 55:
// line 448 "parse.y"
{
yyVal = ((Node)yyVals[-1+yyTop]);
}
break;
case 56:
// line 453 "parse.y"
{
yyVal = nf.newList(((Node)yyVals[-1+yyTop]));
}
break;
case 57:
// line 457 "parse.y"
{
yyVal = ph.list_append(((Node)yyVals[-2+yyTop]), ((Node)yyVals[-1+yyTop]));
}
break;
case 58:
// line 462 "parse.y"
{
yyVal = ph.assignable(((RubyId)yyVals[0+yyTop]), null);
}
break;
case 59:
// line 466 "parse.y"
{
yyVal = ph.aryset(((Node)yyVals[-3+yyTop]), ((Node)yyVals[-1+yyTop]));
}
break;
case 60:
// line 470 "parse.y"
{
yyVal = ph.attrset(((Node)yyVals[-2+yyTop]), ((RubyId)yyVals[0+yyTop]));
}
break;
case 61:
// line 474 "parse.y"
{
yyVal = ph.attrset(((Node)yyVals[-2+yyTop]), ((RubyId)yyVals[0+yyTop]));
}
break;
case 62:
// line 478 "parse.y"
{
yyVal = ph.attrset(((Node)yyVals[-2+yyTop]), ((RubyId)yyVals[0+yyTop]));
}
break;
case 63:
// line 482 "parse.y"
{
ph.rb_backref_error(((Node)yyVals[0+yyTop]));
yyVal = null; /*XXX 0;*/
}
break;
case 64:
// line 488 "parse.y"
{
yyVal = ph.assignable(((RubyId)yyVals[0+yyTop]), null);
}
break;
case 65:
// line 492 "parse.y"
{
yyVal = ph.aryset(((Node)yyVals[-3+yyTop]), ((Node)yyVals[-1+yyTop]));
}
break;
case 66:
// line 496 "parse.y"
{
yyVal = ph.attrset(((Node)yyVals[-2+yyTop]), ((RubyId)yyVals[0+yyTop]));
}
break;
case 67:
// line 500 "parse.y"
{
yyVal = ph.attrset(((Node)yyVals[-2+yyTop]), ((RubyId)yyVals[0+yyTop]));
}
break;
case 68:
// line 504 "parse.y"
{
yyVal = ph.attrset(((Node)yyVals[-2+yyTop]), ((RubyId)yyVals[0+yyTop]));
}
break;
case 69:
// line 508 "parse.y"
{
ph.rb_backref_error(((Node)yyVals[0+yyTop]));
yyVal = null; /*XXX 0;*/
}
break;
case 70:
// line 514 "parse.y"
{
yyerror("class/module name must be CONSTANT");
}
break;
case 75:
// line 523 "parse.y"
{
ph.setLexState(LexState.EXPR_END);
yyVal = ((RubyId)yyVals[0+yyTop]);
}
break;
case 76:
// line 528 "parse.y"
{
ph.setLexState(LexState.EXPR_END);
yyVal = yyVals[0+yyTop];
}
break;
case 79:
// line 537 "parse.y"
{
yyVal = nf.newUndef(((RubyId)yyVals[0+yyTop]));
}
break;
case 80:
// line 540 "parse.y"
{ph.setLexState(LexState.EXPR_FNAME);}
break;
case 81:
// line 541 "parse.y"
{
yyVal = ph.block_append(((Node)yyVals[-3+yyTop]), nf.newUndef(((RubyId)yyVals[0+yyTop])));
}
break;
case 82:
// line 545 "parse.y"
{ yyVal = RubyId.newId(ruby, '|'); }
break;
case 83:
// line 546 "parse.y"
{ yyVal = RubyId.newId(ruby, '^'); }
break;
case 84:
// line 547 "parse.y"
{ yyVal = RubyId.newId(ruby, '&'); }
break;
case 85:
// line 548 "parse.y"
{ yyVal = RubyId.newId(ruby, tCMP); }
break;
case 86:
// line 549 "parse.y"
{ yyVal = RubyId.newId(ruby, tEQ); }
break;
case 87:
// line 550 "parse.y"
{ yyVal = RubyId.newId(ruby, tEQQ); }
break;
case 88:
// line 551 "parse.y"
{ yyVal = RubyId.newId(ruby, tMATCH); }
break;
case 89:
// line 552 "parse.y"
{ yyVal = RubyId.newId(ruby, '>'); }
break;
case 90:
// line 553 "parse.y"
{ yyVal = RubyId.newId(ruby, tGEQ); }
break;
case 91:
// line 554 "parse.y"
{ yyVal = RubyId.newId(ruby, '<'); }
break;
case 92:
// line 555 "parse.y"
{ yyVal = RubyId.newId(ruby, tLEQ); }
break;
case 93:
// line 556 "parse.y"
{ yyVal = RubyId.newId(ruby, tLSHFT); }
break;
case 94:
// line 557 "parse.y"
{ yyVal = RubyId.newId(ruby, tRSHFT); }
break;
case 95:
// line 558 "parse.y"
{ yyVal = RubyId.newId(ruby, '+'); }
break;
case 96:
// line 559 "parse.y"
{ yyVal = RubyId.newId(ruby, '-'); }
break;
case 97:
// line 560 "parse.y"
{ yyVal = RubyId.newId(ruby, '*'); }
break;
case 98:
// line 561 "parse.y"
{ yyVal = RubyId.newId(ruby, '*'); }
break;
case 99:
// line 562 "parse.y"
{ yyVal = RubyId.newId(ruby, '/'); }
break;
case 100:
// line 563 "parse.y"
{ yyVal = RubyId.newId(ruby, '%'); }
break;
case 101:
// line 564 "parse.y"
{ yyVal = RubyId.newId(ruby, tPOW); }
break;
case 102:
// line 565 "parse.y"
{ yyVal = RubyId.newId(ruby, '~'); }
break;
case 103:
// line 566 "parse.y"
{ yyVal = RubyId.newId(ruby, tUPLUS); }
break;
case 104:
// line 567 "parse.y"
{ yyVal = RubyId.newId(ruby, tUMINUS); }
break;
case 105:
// line 568 "parse.y"
{ yyVal = RubyId.newId(ruby, tAREF); }
break;
case 106:
// line 569 "parse.y"
{ yyVal = RubyId.newId(ruby, tASET); }
break;
case 107:
// line 570 "parse.y"
{ yyVal = RubyId.newId(ruby, '`'); }
break;
case 149:
// line 581 "parse.y"
{
ph.value_expr(((Node)yyVals[0+yyTop]));
yyVal = ph.node_assign(((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 150:
// line 585 "parse.y"
{yyVal = ph.assignable(((RubyId)yyVals[-1+yyTop]), null);}
break;
case 151:
// line 586 "parse.y"
{
if (((RubyId)yyVals[-2+yyTop]).intValue() == tOROP) {
((Node)yyVals[-1+yyTop]).setValueNode(((Node)yyVals[0+yyTop]));
yyVal = nf.newOpAsgnOr(ph.gettable(((RubyId)yyVals[-3+yyTop])), ((Node)yyVals[-1+yyTop]));
if (((RubyId)yyVals[-3+yyTop]).isInstanceId()) {
((Node)yyVal).setAId(((RubyId)yyVals[-3+yyTop]));
}
} else if (((RubyId)yyVals[-2+yyTop]).intValue() == tANDOP) {
((Node)yyVals[-1+yyTop]).setValueNode(((Node)yyVals[0+yyTop]));
yyVal = nf.newOpAsgnAnd(ph.gettable(((RubyId)yyVals[-3+yyTop])), ((Node)yyVals[-1+yyTop]));
} else {
yyVal = ((Node)yyVals[-1+yyTop]);
if (yyVal != null) {
((Node)yyVal).setValueNode(ph.call_op(ph.gettable(((RubyId)yyVals[-3+yyTop])),((RubyId)yyVals[-2+yyTop]).intValue(),1,((Node)yyVals[0+yyTop])));
}
}
ph.fixpos(yyVal, ((Node)yyVals[0+yyTop]));
}
break;
case 152:
// line 605 "parse.y"
{
ArrayNode args = nf.newList(((Node)yyVals[0+yyTop]));
ph.list_append(((Node)yyVals[-3+yyTop]), nf.newNil());
ph.list_concat(args, ((Node)yyVals[-3+yyTop]));
if (((RubyId)yyVals[-1+yyTop]).intValue() == Token.tOROP) {
yyVals[-1+yyTop] = RubyId.newId(ruby, 0);
} else if (((RubyId)yyVals[-1+yyTop]).intValue() == Token.tANDOP) {
yyVals[-1+yyTop] = RubyId.newId(ruby, 1);
}
yyVal = nf.newOpAsgn1(((Node)yyVals[-5+yyTop]), ((RubyId)yyVals[-1+yyTop]), args);
ph.fixpos(yyVal, ((Node)yyVals[-5+yyTop]));
}
break;
case 153:
// line 619 "parse.y"
{
if (((RubyId)yyVals[-1+yyTop]).intValue() == Token.tOROP) {
yyVals[-1+yyTop] = RubyId.newId(ruby, 0);
} else if (((RubyId)yyVals[-1+yyTop]).intValue() == Token.tANDOP) {
yyVals[-1+yyTop] = RubyId.newId(ruby, 1);
}
yyVal = nf.newOpAsgn2(((Node)yyVals[-4+yyTop]), ((RubyId)yyVals[-2+yyTop]), ((RubyId)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
ph.fixpos(yyVal, ((Node)yyVals[-4+yyTop]));
}
break;
case 154:
// line 629 "parse.y"
{
if (((RubyId)yyVals[-1+yyTop]).intValue() == Token.tOROP) {
yyVals[-1+yyTop] = RubyId.newId(ruby, 0);
} else if (((RubyId)yyVals[-1+yyTop]).intValue() == Token.tANDOP) {
yyVals[-1+yyTop] = RubyId.newId(ruby, 1);
}
yyVal = nf.newOpAsgn2(((Node)yyVals[-4+yyTop]), ((RubyId)yyVals[-2+yyTop]), ((RubyId)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
ph.fixpos(yyVal, ((Node)yyVals[-4+yyTop]));
}
break;
case 155:
// line 639 "parse.y"
{
if (((RubyId)yyVals[-1+yyTop]).intValue() == Token.tOROP) {
yyVals[-1+yyTop] = RubyId.newId(ruby, 0);
} else if (((RubyId)yyVals[-1+yyTop]).intValue() == Token.tANDOP) {
yyVals[-1+yyTop] = RubyId.newId(ruby, 1);
}
yyVal = nf.newOpAsgn2(((Node)yyVals[-4+yyTop]), ((RubyId)yyVals[-2+yyTop]), ((RubyId)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
ph.fixpos(yyVal, ((Node)yyVals[-4+yyTop]));
}
break;
case 156:
// line 649 "parse.y"
{
ph.rb_backref_error(((Node)yyVals[-2+yyTop]));
yyVal = null; /*XXX 0*/
}
break;
case 157:
// line 654 "parse.y"
{
yyVal = nf.newDot2(((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 158:
// line 658 "parse.y"
{
yyVal = nf.newDot3(((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 159:
// line 662 "parse.y"
{
yyVal = ph.call_op(((Node)yyVals[-2+yyTop]), '+', 1, ((Node)yyVals[0+yyTop]));
}
break;
case 160:
// line 666 "parse.y"
{
yyVal = ph.call_op(((Node)yyVals[-2+yyTop]), '-', 1, ((Node)yyVals[0+yyTop]));
}
break;
case 161:
// line 670 "parse.y"
{
yyVal = ph.call_op(((Node)yyVals[-2+yyTop]), '*', 1, ((Node)yyVals[0+yyTop]));
}
break;
case 162:
// line 674 "parse.y"
{
yyVal = ph.call_op(((Node)yyVals[-2+yyTop]), '/', 1, ((Node)yyVals[0+yyTop]));
}
break;
case 163:
// line 678 "parse.y"
{
yyVal = ph.call_op(((Node)yyVals[-2+yyTop]), '%', 1, ((Node)yyVals[0+yyTop]));
}
break;
case 164:
// line 682 "parse.y"
{
boolean need_negate = false;
if (((Node)yyVals[-2+yyTop]) instanceof LitNode) {
if (((Node)yyVals[-2+yyTop]).getLiteral() instanceof RubyFixnum ||
((Node)yyVals[-2+yyTop]).getLiteral() instanceof RubyFloat ||
((Node)yyVals[-2+yyTop]).getLiteral() instanceof RubyBignum) {
if (((Node)yyVals[-2+yyTop]).getLiteral().funcall(ruby.intern("<"), RubyFixnum.zero(ruby)).isTrue()) {
((Node)yyVals[-2+yyTop]).setLiteral(((Node)yyVals[-2+yyTop]).getLiteral().funcall(ruby.intern("-@")));
need_negate = true;
}
}
}
yyVal = ph.call_op(((Node)yyVals[-2+yyTop]), tPOW, 1, ((Node)yyVals[0+yyTop]));
if (need_negate) {
yyVal = ph.call_op(((Node)yyVal), tUMINUS, 0, null);
}
}
break;
case 165:
// line 701 "parse.y"
{
if (((Node)yyVals[0+yyTop]) != null && ((Node)yyVals[0+yyTop]) instanceof LitNode) {
yyVal = ((Node)yyVals[0+yyTop]);
} else {
yyVal = ph.call_op(((Node)yyVals[0+yyTop]), tUPLUS, 0, null);
}
}
break;
case 166:
// line 709 "parse.y"
{
if (((Node)yyVals[0+yyTop]) != null && ((Node)yyVals[0+yyTop]) instanceof LitNode && ((Node)yyVals[0+yyTop]).getLiteral() instanceof RubyFixnum) {
long i = ((RubyFixnum)((Node)yyVals[0+yyTop]).getLiteral()).getValue();
((Node)yyVals[0+yyTop]).setLiteral(RubyFixnum.m_newFixnum(ruby, -i));
yyVal = ((Node)yyVals[0+yyTop]);
} else {
yyVal = ph.call_op(((Node)yyVals[0+yyTop]), tUMINUS, 0, null);
}
}
break;
case 167:
// line 720 "parse.y"
{
yyVal = ph.call_op(((Node)yyVals[-2+yyTop]), '|', 1, ((Node)yyVals[0+yyTop]));
}
break;
case 168:
// line 724 "parse.y"
{
yyVal = ph.call_op(((Node)yyVals[-2+yyTop]), '^', 1, ((Node)yyVals[0+yyTop]));
}
break;
case 169:
// line 728 "parse.y"
{
yyVal = ph.call_op(((Node)yyVals[-2+yyTop]), '&', 1, ((Node)yyVals[0+yyTop]));
}
break;
case 170:
// line 732 "parse.y"
{
yyVal = ph.call_op(((Node)yyVals[-2+yyTop]), tCMP, 1, ((Node)yyVals[0+yyTop]));
}
break;
case 171:
// line 736 "parse.y"
{
yyVal = ph.call_op(((Node)yyVals[-2+yyTop]), '>', 1, ((Node)yyVals[0+yyTop]));
}
break;
case 172:
// line 740 "parse.y"
{
yyVal = ph.call_op(((Node)yyVals[-2+yyTop]), tGEQ, 1, ((Node)yyVals[0+yyTop]));
}
break;
case 173:
// line 744 "parse.y"
{
yyVal = ph.call_op(((Node)yyVals[-2+yyTop]), '<', 1, ((Node)yyVals[0+yyTop]));
}
break;
case 174:
// line 748 "parse.y"
{
yyVal = ph.call_op(((Node)yyVals[-2+yyTop]), tLEQ, 1, ((Node)yyVals[0+yyTop]));
}
break;
case 175:
// line 752 "parse.y"
{
yyVal = ph.call_op(((Node)yyVals[-2+yyTop]), tEQ, 1, ((Node)yyVals[0+yyTop]));
}
break;
case 176:
// line 756 "parse.y"
{
yyVal = ph.call_op(((Node)yyVals[-2+yyTop]), tEQQ, 1, ((Node)yyVals[0+yyTop]));
}
break;
case 177:
// line 760 "parse.y"
{
yyVal = nf.newNot(ph.call_op(((Node)yyVals[-2+yyTop]), tEQ, 1, ((Node)yyVals[0+yyTop])));
}
break;
case 178:
// line 764 "parse.y"
{
yyVal = ph.match_gen(((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 179:
// line 768 "parse.y"
{
yyVal = nf.newNot(ph.match_gen(((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop])));
}
break;
case 180:
// line 772 "parse.y"
{
ph.value_expr(((Node)yyVals[0+yyTop]));
yyVal = nf.newNot(ph.cond(((Node)yyVals[0+yyTop])));
}
break;
case 181:
// line 777 "parse.y"
{
yyVal = ph.call_op(((Node)yyVals[0+yyTop]), '~', 0, null);
}
break;
case 182:
// line 781 "parse.y"
{
yyVal = ph.call_op(((Node)yyVals[-2+yyTop]), tLSHFT, 1, ((Node)yyVals[0+yyTop]));
}
break;
case 183:
// line 785 "parse.y"
{
yyVal = ph.call_op(((Node)yyVals[-2+yyTop]), tRSHFT, 1, ((Node)yyVals[0+yyTop]));
}
break;
case 184:
// line 789 "parse.y"
{
yyVal = ph.logop(Constants.NODE_AND, ((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 185:
// line 793 "parse.y"
{
yyVal = ph.logop(Constants.NODE_OR, ((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 186:
// line 796 "parse.y"
{ ph.setInDefined(true);}
break;
case 187:
// line 797 "parse.y"
{
ph.setInDefined(false);
yyVal = nf.newDefined(((Node)yyVals[0+yyTop]));
}
break;
case 188:
// line 802 "parse.y"
{
ph.value_expr(((Node)yyVals[-4+yyTop]));
yyVal = nf.newIf(ph.cond(((Node)yyVals[-4+yyTop])), ((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
ph.fixpos(yyVal, ((Node)yyVals[-4+yyTop]));
}
break;
case 189:
// line 808 "parse.y"
{
yyVal = ((Node)yyVals[0+yyTop]);
}
break;
case 191:
// line 814 "parse.y"
{
yyVal = nf.newList(((Node)yyVals[-1+yyTop]));
}
break;
case 192:
// line 818 "parse.y"
{
yyVal = ph.list_append(((Node)yyVals[-3+yyTop]), ((Node)yyVals[-1+yyTop]));
}
break;
case 193:
// line 822 "parse.y"
{
yyVal = ((Node)yyVals[-1+yyTop]);
}
break;
case 194:
// line 826 "parse.y"
{
ph.value_expr(((Node)yyVals[-1+yyTop]));
yyVal = ph.arg_concat(((Node)yyVals[-4+yyTop]), ((Node)yyVals[-1+yyTop]));
}
break;
case 195:
// line 831 "parse.y"
{
yyVal = nf.newList(nf.newHash(((Node)yyVals[-1+yyTop])));
}
break;
case 196:
// line 835 "parse.y"
{
ph.value_expr(((Node)yyVals[-1+yyTop]));
yyVal = nf.newRestArgs(((Node)yyVals[-1+yyTop]));
}
break;
case 197:
// line 841 "parse.y"
{
yyVal = ((Node)yyVals[-1+yyTop]);
}
break;
case 198:
// line 845 "parse.y"
{
yyVal = ((Node)yyVals[-2+yyTop]);
}
break;
case 199:
// line 849 "parse.y"
{
yyVal = nf.newList(((Node)yyVals[-2+yyTop]));
}
break;
case 200:
// line 853 "parse.y"
{
yyVal = ph.list_append(((Node)yyVals[-4+yyTop]), ((Node)yyVals[-2+yyTop]));
}
break;
case 203:
// line 861 "parse.y"
{
yyVal = nf.newList(((Node)yyVals[0+yyTop]));
}
break;
case 204:
// line 865 "parse.y"
{
yyVal = ph.list_append(((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 205:
// line 869 "parse.y"
{
yyVal = ph.arg_blk_pass(((Node)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 206:
// line 873 "parse.y"
{
ph.value_expr(((Node)yyVals[-1+yyTop]));
yyVal = ph.arg_concat(((Node)yyVals[-4+yyTop]), ((Node)yyVals[-1+yyTop]));
yyVal = ph.arg_blk_pass(((Node)yyVal), ((Node)yyVals[0+yyTop]));
}
break;
case 207:
// line 879 "parse.y"
{
yyVal = nf.newList(nf.newHash(((Node)yyVals[-1+yyTop])));
yyVal = ph.arg_blk_pass(((Node)yyVal), ((Node)yyVals[0+yyTop]));
}
break;
case 208:
// line 884 "parse.y"
{
ph.value_expr(((Node)yyVals[-1+yyTop]));
yyVal = ph.arg_concat(nf.newList(nf.newHash(((Node)yyVals[-4+yyTop]))), ((Node)yyVals[-1+yyTop]));
yyVal = ph.arg_blk_pass(((Node)yyVal), ((Node)yyVals[0+yyTop]));
}
break;
case 209:
// line 890 "parse.y"
{
yyVal = ph.list_append(((Node)yyVals[-3+yyTop]), nf.newHash(((Node)yyVals[-1+yyTop])));
yyVal = ph.arg_blk_pass(((Node)yyVal), ((Node)yyVals[0+yyTop]));
}
break;
case 210:
// line 895 "parse.y"
{
ph.value_expr(((Node)yyVals[-1+yyTop]));
yyVal = ph.arg_concat(ph.list_append(((Node)yyVals[-6+yyTop]), nf.newHash(((Node)yyVals[-4+yyTop]))), ((Node)yyVals[-1+yyTop]));
yyVal = ph.arg_blk_pass(((Node)yyVal), ((Node)yyVals[0+yyTop]));
}
break;
case 211:
// line 901 "parse.y"
{
ph.value_expr(((Node)yyVals[-1+yyTop]));
yyVal = ph.arg_blk_pass(nf.newRestArgs(((Node)yyVals[-1+yyTop])), ((Node)yyVals[0+yyTop]));
}
break;
case 213:
// line 907 "parse.y"
{ rs.CMDARG_PUSH(); }
break;
case 214:
// line 908 "parse.y"
{
rs.CMDARG_POP();
yyVal = ((Node)yyVals[0+yyTop]);
}
break;
case 215:
// line 914 "parse.y"
{
ph.value_expr(((Node)yyVals[0+yyTop]));
yyVal = nf.newBlockPass(((Node)yyVals[0+yyTop]));
}
break;
case 216:
// line 920 "parse.y"
{
yyVal = ((Node)yyVals[0+yyTop]);
}
break;
case 218:
// line 926 "parse.y"
{
ph.value_expr(((Node)yyVals[0+yyTop]));
yyVal = nf.newList(((Node)yyVals[0+yyTop]));
}
break;
case 219:
// line 931 "parse.y"
{
ph.value_expr(((Node)yyVals[0+yyTop]));
yyVal = ph.list_append(((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 220:
// line 937 "parse.y"
{
ph.value_expr(((Node)yyVals[0+yyTop]));
yyVal = ((Node)yyVals[0+yyTop]);
}
break;
case 222:
// line 944 "parse.y"
{
ph.value_expr(((Node)yyVals[0+yyTop]));
yyVal = ph.list_append(((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 223:
// line 949 "parse.y"
{
ph.value_expr(((Node)yyVals[0+yyTop]));
yyVal = ph.arg_concat(((Node)yyVals[-3+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 224:
// line 954 "parse.y"
{
ph.value_expr(((Node)yyVals[0+yyTop]));
yyVal = ((Node)yyVals[0+yyTop]);
}
break;
case 225:
// line 960 "parse.y"
{
yyVal = ((Node)yyVals[0+yyTop]);
if (((Node)yyVals[0+yyTop]) != null) {
if (((Node)yyVals[0+yyTop]).getType() == Constants.NODE_ARRAY && ((Node)yyVals[0+yyTop]).getNextNode() == null) {
yyVal = ((Node)yyVals[0+yyTop]).getHeadNode();
} else if (((Node)yyVals[0+yyTop]).getType() == Constants.NODE_BLOCK_PASS) {
ph.rb_compile_error("block argument should not be given");
}
}
}
break;
case 226:
// line 972 "parse.y"
{
yyVal = nf.newLit(((RubyObject)yyVals[0+yyTop]));
}
break;
case 228:
// line 977 "parse.y"
{
yyVal = nf.newXStr(((RubyObject)yyVals[0+yyTop]));
}
break;
case 233:
// line 985 "parse.y"
{
yyVal = nf.newVCall(((RubyId)yyVals[0+yyTop]));
}
break;
case 234:
// line 994 "parse.y"
{
if (((Node)yyVals[-3+yyTop]) == null && ((Node)yyVals[-2+yyTop]) == null && ((Node)yyVals[-1+yyTop]) == null)
yyVal = nf.newBegin(((Node)yyVals[-4+yyTop]));
else {
if (((Node)yyVals[-3+yyTop]) != null) yyVals[-4+yyTop] = nf.newRescue(((Node)yyVals[-4+yyTop]), ((Node)yyVals[-3+yyTop]), ((Node)yyVals[-2+yyTop]));
else if (((Node)yyVals[-2+yyTop]) != null) {
ph.rb_warn("else without rescue is useless");
yyVals[-4+yyTop] = ph.block_append(((Node)yyVals[-4+yyTop]), ((Node)yyVals[-2+yyTop]));
}
if (((Node)yyVals[-1+yyTop]) != null) yyVals[-4+yyTop] = nf.newEnsure(((Node)yyVals[-4+yyTop]), ((Node)yyVals[-1+yyTop]));
yyVal = ((Node)yyVals[-4+yyTop]);
}
ph.fixpos(yyVal, ((Node)yyVals[-4+yyTop]));
}
break;
case 235:
// line 1009 "parse.y"
{
yyVal = ((Node)yyVals[-1+yyTop]);
}
break;
case 236:
// line 1013 "parse.y"
{
ph.value_expr(((Node)yyVals[-2+yyTop]));
yyVal = nf.newColon2(((Node)yyVals[-2+yyTop]), ((RubyId)yyVals[0+yyTop]));
}
break;
case 237:
// line 1018 "parse.y"
{
yyVal = nf.newColon3(((RubyId)yyVals[0+yyTop]));
}
break;
case 238:
// line 1022 "parse.y"
{
ph.value_expr(((Node)yyVals[-3+yyTop]));
yyVal = nf.newCall(((Node)yyVals[-3+yyTop]), ph.newId(tAREF), ((Node)yyVals[-1+yyTop]));
}
break;
case 239:
// line 1027 "parse.y"
{
if (((Node)yyVals[-1+yyTop]) == null) {
yyVal = nf.newZArray(); /* zero length array*/
} else {
yyVal = ((Node)yyVals[-1+yyTop]);
}
}
break;
case 240:
// line 1035 "parse.y"
{
yyVal = nf.newHash(((Node)yyVals[-1+yyTop]));
}
break;
case 241:
// line 1039 "parse.y"
{
if (!ph.isCompileForEval() && !ph.isInDef() && !ph.isInSingle())
yyerror("return appeared outside of method");
ph.value_expr(((Node)yyVals[-1+yyTop]));
yyVal = nf.newReturn(((Node)yyVals[-1+yyTop]));
}
break;
case 242:
// line 1046 "parse.y"
{
if (!ph.isCompileForEval() && !ph.isInDef() && !ph.isInSingle())
yyerror("return appeared outside of method");
yyVal = nf.newReturn(null);
}
break;
case 243:
// line 1052 "parse.y"
{
if (!ph.isCompileForEval() && !ph.isInDef() && !ph.isInSingle())
yyerror("return appeared outside of method");
yyVal = nf.newReturn(null);
}
break;
case 244:
// line 1058 "parse.y"
{
ph.value_expr(((Node)yyVals[-1+yyTop]));
yyVal = nf.newYield(((Node)yyVals[-1+yyTop]));
}
break;
case 245:
// line 1063 "parse.y"
{
yyVal = nf.newYield(null);
}
break;
case 246:
// line 1067 "parse.y"
{
yyVal = nf.newYield(null);
}
break;
case 247:
// line 1070 "parse.y"
{ph.setInDefined(true);}
break;
case 248:
// line 1071 "parse.y"
{
ph.setInDefined(false);
yyVal = nf.newDefined(((Node)yyVals[-1+yyTop]));
}
break;
case 249:
// line 1076 "parse.y"
{
((Node)yyVals[0+yyTop]).setIterNode(nf.newFCall(((RubyId)yyVals[-1+yyTop]), null));
yyVal = ((Node)yyVals[0+yyTop]);
}
break;
case 251:
// line 1082 "parse.y"
{
if (((Node)yyVals[-1+yyTop]) != null && ((Node)yyVals[-1+yyTop]).getType() == Constants.NODE_BLOCK_PASS) {
ph.rb_compile_error("both block arg and actual block given");
}
((Node)yyVals[0+yyTop]).setIterNode(((Node)yyVals[-1+yyTop]));
yyVal = ((Node)yyVals[0+yyTop]);
ph.fixpos(yyVal, ((Node)yyVals[-1+yyTop]));
}
break;
case 252:
// line 1094 "parse.y"
{
ph.value_expr(((Node)yyVals[-4+yyTop]));
yyVal = nf.newIf(ph.cond(((Node)yyVals[-4+yyTop])), ((Node)yyVals[-2+yyTop]), ((Node)yyVals[-1+yyTop]));
ph.fixpos(yyVal, ((Node)yyVals[-4+yyTop]));
}
break;
case 253:
// line 1103 "parse.y"
{
ph.value_expr(((Node)yyVals[-4+yyTop]));
yyVal = nf.newUnless(ph.cond(((Node)yyVals[-4+yyTop])), ((Node)yyVals[-2+yyTop]), ((Node)yyVals[-1+yyTop]));
ph.fixpos(yyVal, ((Node)yyVals[-4+yyTop]));
}
break;
case 254:
// line 1108 "parse.y"
{ rs.COND_PUSH(); }
break;
case 255:
// line 1108 "parse.y"
{ rs.COND_POP(); }
break;
case 256:
// line 1111 "parse.y"
{
ph.value_expr(((Node)yyVals[-4+yyTop]));
yyVal = nf.newWhile(ph.cond(((Node)yyVals[-4+yyTop])), ((Node)yyVals[-1+yyTop])); /* , 1*/
ph.fixpos(yyVal, ((Node)yyVals[-4+yyTop]));
}
break;
case 257:
// line 1116 "parse.y"
{ rs.COND_PUSH(); }
break;
case 258:
// line 1116 "parse.y"
{ rs.COND_POP(); }
break;
case 259:
// line 1119 "parse.y"
{
ph.value_expr(((Node)yyVals[-4+yyTop]));
yyVal = nf.newUntil(ph.cond(((Node)yyVals[-4+yyTop])), ((Node)yyVals[-1+yyTop])); /*, 1*/
ph.fixpos(yyVal, ((Node)yyVals[-4+yyTop]));
}
break;
case 260:
// line 1127 "parse.y"
{
ph.value_expr(((Node)yyVals[-3+yyTop]));
yyVal = nf.newCase(((Node)yyVals[-3+yyTop]), ((Node)yyVals[-1+yyTop]));
ph.fixpos(yyVal, ((Node)yyVals[-3+yyTop]));
}
break;
case 261:
// line 1133 "parse.y"
{
yyVal = ((Node)yyVals[-1+yyTop]);
}
break;
case 262:
// line 1136 "parse.y"
{ rs.COND_PUSH(); }
break;
case 263:
// line 1136 "parse.y"
{ rs.COND_POP(); }
break;
case 264:
// line 1139 "parse.y"
{
ph.value_expr(((Node)yyVals[-4+yyTop]));
yyVal = nf.newFor(((Node)yyVals[-7+yyTop]), ((Node)yyVals[-4+yyTop]), ((Node)yyVals[-1+yyTop]));
ph.fixpos(yyVal, ((Node)yyVals[-7+yyTop]));
}
break;
case 265:
// line 1145 "parse.y"
{
if (ph.isInDef() || ph.isInSingle())
yyerror("class definition in method body");
ph.setClassNest(ph.getClassNest() + 1);
ph.local_push();
yyVal = new Integer(ruby.getSourceLine());
}
break;
case 266:
// line 1154 "parse.y"
{
yyVal = nf.newClass(((RubyId)yyVals[-4+yyTop]), ((Node)yyVals[-1+yyTop]), ((Node)yyVals[-3+yyTop]));
((Node)yyVal).setLine(((Integer)yyVals[-2+yyTop]).intValue());
ph.local_pop();
ph.setClassNest(ph.getClassNest() - 1);
}
break;
case 267:
// line 1161 "parse.y"
{
yyVal = new Integer(ph.getInDef());
ph.setInDef(0);
}
break;
case 268:
// line 1166 "parse.y"
{
yyVal = new Integer(ph.getInSingle());
ph.setInSingle(0);
ph.setClassNest(ph.getClassNest() - 1);
ph.local_push();
}
break;
case 269:
// line 1174 "parse.y"
{
yyVal = nf.newSClass(((Node)yyVals[-5+yyTop]), ((Node)yyVals[-1+yyTop]));
ph.fixpos(yyVal, ((Node)yyVals[-5+yyTop]));
ph.local_pop();
ph.setClassNest(ph.getClassNest() - 1);
ph.setInDef(((Integer)yyVals[-4+yyTop]).intValue());
ph.setInSingle(((Integer)yyVals[-2+yyTop]).intValue());
}
break;
case 270:
// line 1183 "parse.y"
{
if (ph.isInDef() || ph.isInSingle())
yyerror("module definition in method body");
ph.setClassNest(ph.getClassNest() + 1);
ph.local_push();
yyVal = new Integer(ruby.getSourceLine());
}
break;
case 271:
// line 1192 "parse.y"
{
yyVal = nf.newModule(((RubyId)yyVals[-3+yyTop]), ((Node)yyVals[-1+yyTop]));
((Node)yyVal).setLine(((Integer)yyVals[-2+yyTop]).intValue());
ph.local_pop();
ph.setClassNest(ph.getClassNest() - 1);
}
break;
case 272:
// line 1199 "parse.y"
{
if (ph.isInDef() || ph.isInSingle())
yyerror("nested method definition");
yyVal = ph.getCurMid();
ph.setCurMid(((RubyId)yyVals[0+yyTop]));
ph.setInDef(ph.getInDef() + 1);
ph.local_push();
}
break;
case 273:
// line 1213 "parse.y"
{
if (((Node)yyVals[-3+yyTop]) != null)
yyVals[-4+yyTop] = nf.newRescue(((Node)yyVals[-4+yyTop]), ((Node)yyVals[-3+yyTop]), ((Node)yyVals[-2+yyTop]));
else if (((Node)yyVals[-2+yyTop]) != null) {
ph.rb_warn("else without rescue is useless");
yyVals[-4+yyTop] = ph.block_append(((Node)yyVals[-4+yyTop]), ((Node)yyVals[-2+yyTop]));
}
if (((Node)yyVals[-1+yyTop]) != null)
yyVals[-4+yyTop] = nf.newEnsure(((Node)yyVals[-4+yyTop]), ((Node)yyVals[-1+yyTop]));
/* NOEX_PRIVATE for toplevel */
yyVal = nf.newDefn(((RubyId)yyVals[-7+yyTop]), ((Node)yyVals[-5+yyTop]), ((Node)yyVals[-4+yyTop]), ph.getClassNest() !=0 ?
Constants.NOEX_PUBLIC : Constants.NOEX_PRIVATE);
if (((RubyId)yyVals[-7+yyTop]).isAttrSetId())
((Node)yyVal).setNoex(Constants.NOEX_PUBLIC);
ph.fixpos(yyVal, ((Node)yyVals[-5+yyTop]));
ph.local_pop();
ph.setInDef(ph.getInDef() - 1);
ph.setCurMid(((RubyId)yyVals[-6+yyTop]));
}
break;
case 274:
// line 1233 "parse.y"
{ph.setLexState(LexState.EXPR_FNAME);}
break;
case 275:
// line 1234 "parse.y"
{
ph.value_expr(((Node)yyVals[-3+yyTop]));
ph.setInSingle(ph.getInSingle() + 1);
ph.local_push();
ph.setLexState(LexState.EXPR_END); /* force for args */
}
break;
case 276:
// line 1246 "parse.y"
{
if (((Node)yyVals[-3+yyTop]) != null)
yyVals[-4+yyTop] = nf.newRescue(((Node)yyVals[-4+yyTop]), ((Node)yyVals[-3+yyTop]), ((Node)yyVals[-2+yyTop]));
else if (((Node)yyVals[-2+yyTop]) != null) {
ph.rb_warn("else without rescue is useless");
yyVals[-4+yyTop] = ph.block_append(((Node)yyVals[-4+yyTop]), ((Node)yyVals[-2+yyTop]));
}
if (((Node)yyVals[-1+yyTop]) != null) yyVals[-4+yyTop] = nf.newEnsure(((Node)yyVals[-4+yyTop]), ((Node)yyVals[-1+yyTop]));
yyVal = nf.newDefs(((Node)yyVals[-10+yyTop]), ((RubyId)yyVals[-7+yyTop]), ((Node)yyVals[-5+yyTop]), ((Node)yyVals[-4+yyTop]));
ph.fixpos(yyVal, ((Node)yyVals[-10+yyTop]));
ph.local_pop();
ph.setInSingle(ph.getInSingle() - 1);
}
break;
case 277:
// line 1261 "parse.y"
{
yyVal = nf.newBreak();
}
break;
case 278:
// line 1265 "parse.y"
{
yyVal = nf.newNext();
}
break;
case 279:
// line 1269 "parse.y"
{
yyVal = nf.newRedo();
}
break;
case 280:
// line 1273 "parse.y"
{
yyVal = nf.newRetry();
}
break;
case 287:
// line 1288 "parse.y"
{
ph.value_expr(((Node)yyVals[-3+yyTop]));
yyVal = nf.newIf(ph.cond(((Node)yyVals[-3+yyTop])), ((Node)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
ph.fixpos(yyVal, ((Node)yyVals[-3+yyTop]));
}
break;
case 289:
// line 1296 "parse.y"
{
yyVal = ((Node)yyVals[0+yyTop]);
}
break;
case 293:
// line 1305 "parse.y"
{
yyVal = Node.ONE; /* new Integer(1); //XXX (Node*)1;*/
}
break;
case 294:
// line 1309 "parse.y"
{
yyVal = Node.ONE; /* new Integer(1); //XXX (Node*)1;*/
}
break;
case 295:
// line 1313 "parse.y"
{
yyVal = ((Node)yyVals[-1+yyTop]);
}
break;
case 296:
// line 1318 "parse.y"
{
yyVal = ph.dyna_push();
}
break;
case 297:
// line 1324 "parse.y"
{
yyVal = nf.newIter(((Node)yyVals[-2+yyTop]), null, ((Node)yyVals[-1+yyTop]));
ph.fixpos(yyVal, ((Node)yyVals[-2+yyTop])!=null?((Node)yyVals[-2+yyTop]):((Node)yyVals[-1+yyTop]));
ph.dyna_pop(((RubyVarmap)yyVals[-3+yyTop]));
}
break;
case 298:
// line 1331 "parse.y"
{
if (((Node)yyVals[-1+yyTop]) != null && ((Node)yyVals[-1+yyTop]).getType() == Constants.NODE_BLOCK_PASS) {
ph.rb_compile_error("both block arg and actual block given");
}
((Node)yyVals[0+yyTop]).setIterNode(((Node)yyVals[-1+yyTop]));
yyVal = ((Node)yyVals[0+yyTop]);
ph.fixpos(yyVal, ((Node)yyVals[0+yyTop]));
}
break;
case 299:
// line 1340 "parse.y"
{
ph.value_expr(((Node)yyVals[-3+yyTop]));
yyVal = ph.new_call(((Node)yyVals[-3+yyTop]), ((RubyId)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 300:
// line 1345 "parse.y"
{
ph.value_expr(((Node)yyVals[-3+yyTop]));
yyVal = ph.new_call(((Node)yyVals[-3+yyTop]), ((RubyId)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 301:
// line 1351 "parse.y"
{
yyVal = ph.new_fcall(((RubyId)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
ph.fixpos(yyVal, ((Node)yyVals[0+yyTop]));
}
break;
case 302:
// line 1356 "parse.y"
{
ph.value_expr(((Node)yyVals[-3+yyTop]));
yyVal = ph.new_call(((Node)yyVals[-3+yyTop]), ((RubyId)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
ph.fixpos(yyVal, ((Node)yyVals[-3+yyTop]));
}
break;
case 303:
// line 1362 "parse.y"
{
ph.value_expr(((Node)yyVals[-3+yyTop]));
yyVal = ph.new_call(((Node)yyVals[-3+yyTop]), ((RubyId)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
ph.fixpos(yyVal, ((Node)yyVals[-3+yyTop]));
}
break;
case 304:
// line 1368 "parse.y"
{
ph.value_expr(((Node)yyVals[-2+yyTop]));
yyVal = ph.new_call(((Node)yyVals[-2+yyTop]), ((RubyId)yyVals[0+yyTop]), null);
}
break;
case 305:
// line 1373 "parse.y"
{
if (!ph.isCompileForEval() && !ph.isInDef() && !ph.isInSingle() && !ph.isInDefined())
yyerror("super called outside of method");
yyVal = ph.new_super(((Node)yyVals[0+yyTop]));
}
break;
case 306:
// line 1379 "parse.y"
{
if (!ph.isCompileForEval() && !ph.isInDef() && !ph.isInSingle() && !ph.isInDefined())
yyerror("super called outside of method");
yyVal = nf.newZSuper();
}
break;
case 307:
// line 1386 "parse.y"
{
yyVal = ph.dyna_push();
}
break;
case 308:
// line 1391 "parse.y"
{
yyVal = nf.newIter(((Node)yyVals[-2+yyTop]), null, ((Node)yyVals[-1+yyTop]));
ph.fixpos(yyVal, ((Node)yyVals[-1+yyTop]));
ph.dyna_pop(((RubyVarmap)yyVals[-3+yyTop]));
}
break;
case 309:
// line 1397 "parse.y"
{
yyVal = ph.dyna_push();
}
break;
case 310:
// line 1402 "parse.y"
{
yyVal = nf.newIter(((Node)yyVals[-2+yyTop]), null, ((Node)yyVals[-1+yyTop]));
ph.fixpos(yyVal, ((Node)yyVals[-1+yyTop]));
ph.dyna_pop(((RubyVarmap)yyVals[-3+yyTop]));
}
break;
case 311:
// line 1411 "parse.y"
{
yyVal = nf.newWhen(((Node)yyVals[-3+yyTop]), ((Node)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 313:
// line 1417 "parse.y"
{
ph.value_expr(((Node)yyVals[0+yyTop]));
yyVal = ph.list_append(((Node)yyVals[-3+yyTop]), nf.newWhen(((Node)yyVals[0+yyTop]), null, null));
}
break;
case 314:
// line 1422 "parse.y"
{
ph.value_expr(((Node)yyVals[0+yyTop]));
yyVal = nf.newList(nf.newWhen(((Node)yyVals[0+yyTop]), null, null));
}
break;
case 319:
// line 1434 "parse.y"
{
yyVal = ((Node)yyVals[0+yyTop]);
}
break;
case 321:
// line 1442 "parse.y"
{
if (((Node)yyVals[-3+yyTop]) != null) {
yyVals[-3+yyTop] = ph.node_assign(((Node)yyVals[-3+yyTop]), nf.newGVar(ruby.intern("$!")));
yyVals[-1+yyTop] = ph.block_append(((Node)yyVals[-3+yyTop]), ((Node)yyVals[-1+yyTop]));
}
yyVal = nf.newResBody(((Node)yyVals[-4+yyTop]), ((Node)yyVals[-1+yyTop]), ((Node)yyVals[0+yyTop]));
ph.fixpos(yyVal, ((Node)yyVals[-4+yyTop])!=null?((Node)yyVals[-4+yyTop]):((Node)yyVals[-1+yyTop]));
}
break;
case 324:
// line 1454 "parse.y"
{
if (((Node)yyVals[0+yyTop]) != null)
yyVal = ((Node)yyVals[0+yyTop]);
else
/* place holder */
yyVal = nf.newNil();
}
break;
case 326:
// line 1464 "parse.y"
{
yyVal = ((RubyId)yyVals[0+yyTop]).toSymbol();
}
break;
case 328:
// line 1470 "parse.y"
{
yyVal = nf.newStr(((RubyObject)yyVals[0+yyTop]));
}
break;
case 330:
// line 1475 "parse.y"
{
if (((Node)yyVals[-1+yyTop]).getType() == Constants.NODE_DSTR) {
ph.list_append(((Node)yyVals[-1+yyTop]), nf.newStr(((RubyObject)yyVals[0+yyTop])));
} else {
((RubyString)((Node)yyVals[-1+yyTop]).getLiteral()).m_concat((RubyString)((RubyObject)yyVals[0+yyTop]));
}
yyVal = ((Node)yyVals[-1+yyTop]);
}
break;
case 331:
// line 1484 "parse.y"
{
if (((Node)yyVals[-1+yyTop]).getType() == Constants.NODE_STR) {
yyVal = nf.newDStr(((Node)yyVals[-1+yyTop]).getLiteral());
} else {
yyVal = ((Node)yyVals[-1+yyTop]);
}
((Node)yyVals[0+yyTop]).setHeadNode(nf.newStr(((Node)yyVals[0+yyTop]).getLiteral()));
new RuntimeException("[BUG] Want to change " + ((Node)yyVals[0+yyTop]).getClass().getName() + " to ArrayNode.").printStackTrace();
/* $2.nd_set_type(Constants.NODE_ARRAY);*/
ph.list_concat(((Node)yyVal), ((Node)yyVals[0+yyTop]));
}
break;
case 332:
// line 1497 "parse.y"
{
ph.setLexState(LexState.EXPR_END);
yyVal = ((RubyId)yyVals[0+yyTop]);
}
break;
case 344:
// line 1515 "parse.y"
{yyVal = ph.newId(kNIL);}
break;
case 345:
// line 1516 "parse.y"
{yyVal = ph.newId(kSELF);}
break;
case 346:
// line 1517 "parse.y"
{yyVal = ph.newId(kTRUE);}
break;
case 347:
// line 1518 "parse.y"
{yyVal = ph.newId(kFALSE);}
break;
case 348:
// line 1519 "parse.y"
{yyVal = ph.newId(k__FILE__);}
break;
case 349:
// line 1520 "parse.y"
{yyVal = ph.newId(k__LINE__);}
break;
case 350:
// line 1523 "parse.y"
{
yyVal = ph.gettable(((RubyId)yyVals[0+yyTop]));
}
break;
case 353:
// line 1531 "parse.y"
{
yyVal = null;
}
break;
case 354:
// line 1535 "parse.y"
{
ph.setLexState(LexState.EXPR_BEG);
}
break;
case 355:
// line 1539 "parse.y"
{
yyVal = ((Node)yyVals[-1+yyTop]);
}
break;
case 356:
// line 1542 "parse.y"
{yyerrok(); yyVal = null;}
break;
case 357:
// line 1545 "parse.y"
{
yyVal = ((Node)yyVals[-2+yyTop]);
ph.setLexState(LexState.EXPR_BEG);
}
break;
case 358:
// line 1550 "parse.y"
{
yyVal = ((Node)yyVals[-1+yyTop]);
}
break;
case 359:
// line 1555 "parse.y"
{
yyVal = ph.block_append(nf.newArgs(((Integer)yyVals[-5+yyTop]), ((Node)yyVals[-3+yyTop]), ((Integer)yyVals[-1+yyTop]).intValue()), ((Node)yyVals[0+yyTop]));
}
break;
case 360:
// line 1559 "parse.y"
{
yyVal = ph.block_append(nf.newArgs(((Integer)yyVals[-3+yyTop]), ((Node)yyVals[-1+yyTop]), -1), ((Node)yyVals[0+yyTop]));
}
break;
case 361:
// line 1563 "parse.y"
{
yyVal = ph.block_append(nf.newArgs(((Integer)yyVals[-3+yyTop]), null, ((Integer)yyVals[-1+yyTop]).intValue()), ((Node)yyVals[0+yyTop]));
}
break;
case 362:
// line 1567 "parse.y"
{
yyVal = ph.block_append(nf.newArgs(((Integer)yyVals[-1+yyTop]), null, -1), ((Node)yyVals[0+yyTop]));
}
break;
case 363:
// line 1571 "parse.y"
{
yyVal = ph.block_append(nf.newArgs(null, ((Node)yyVals[-3+yyTop]), ((Integer)yyVals[-1+yyTop]).intValue()), ((Node)yyVals[0+yyTop]));
}
break;
case 364:
// line 1575 "parse.y"
{
yyVal = ph.block_append(nf.newArgs(null, ((Node)yyVals[-1+yyTop]), -1), ((Node)yyVals[0+yyTop]));
}
break;
case 365:
// line 1579 "parse.y"
{
yyVal = ph.block_append(nf.newArgs(null, null, ((Integer)yyVals[-1+yyTop]).intValue()), ((Node)yyVals[0+yyTop]));
}
break;
case 366:
// line 1583 "parse.y"
{
yyVal = ph.block_append(nf.newArgs(null, null, -1), ((Node)yyVals[0+yyTop]));
}
break;
case 367:
// line 1587 "parse.y"
{
yyVal = nf.newArgs(null, null, -1);
}
break;
case 368:
// line 1592 "parse.y"
{
yyerror("formal argument cannot be a constant");
}
break;
case 369:
// line 1596 "parse.y"
{
yyerror("formal argument cannot be an instance variable");
}
break;
case 370:
// line 1600 "parse.y"
{
yyerror("formal argument cannot be a global variable");
}
break;
case 371:
// line 1604 "parse.y"
{
yyerror("formal argument cannot be a class variable");
}
break;
case 372:
// line 1608 "parse.y"
{
if (!((RubyId)yyVals[0+yyTop]).isLocalId())
yyerror("formal argument must be local variable");
else if (ph.local_id(((RubyId)yyVals[0+yyTop])))
yyerror("duplicate argument name");
ph.local_cnt(((RubyId)yyVals[0+yyTop]));
yyVal = new Integer(1);
}
break;
case 374:
// line 1619 "parse.y"
{
yyVal = new Integer(((Integer)yyVal).intValue() + 1);
}
break;
case 375:
// line 1624 "parse.y"
{
if (!((RubyId)yyVals[-2+yyTop]).isLocalId())
yyerror("formal argument must be local variable");
else if (ph.local_id(((RubyId)yyVals[-2+yyTop])))
yyerror("duplicate optional argument name");
yyVal = ph.assignable(((RubyId)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 376:
// line 1633 "parse.y"
{
yyVal = nf.newBlock(((Node)yyVals[0+yyTop]));
((Node)yyVal).setEndNode(((Node)yyVal));
}
break;
case 377:
// line 1638 "parse.y"
{
yyVal = ph.block_append(((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 378:
// line 1643 "parse.y"
{
if (!((RubyId)yyVals[0+yyTop]).isLocalId())
yyerror("rest argument must be local variable");
else if (ph.local_id(((RubyId)yyVals[0+yyTop])))
yyerror("duplicate rest argument name");
yyVal = new Integer(ph.local_cnt(((RubyId)yyVals[0+yyTop])));
}
break;
case 379:
// line 1651 "parse.y"
{
yyVal = new Integer(-2);
}
break;
case 380:
// line 1656 "parse.y"
{
if (!((RubyId)yyVals[0+yyTop]).isLocalId())
yyerror("block argument must be local variable");
else if (ph.local_id(((RubyId)yyVals[0+yyTop])))
yyerror("duplicate block argument name");
yyVal = nf.newBlockArg(((RubyId)yyVals[0+yyTop]));
}
break;
case 381:
// line 1665 "parse.y"
{
yyVal = ((Node)yyVals[0+yyTop]);
}
break;
case 383:
// line 1671 "parse.y"
{
if (((Node)yyVals[0+yyTop]).getType() == Constants.NODE_SELF) {
yyVal = nf.newSelf();
} else {
yyVal = ((Node)yyVals[0+yyTop]);
}
}
break;
case 384:
// line 1678 "parse.y"
{ph.setLexState(LexState.EXPR_BEG);}
break;
case 385:
// line 1679 "parse.y"
{
switch (((Node)yyVals[-2+yyTop]).getType()) {
case Constants.NODE_STR:
case Constants.NODE_DSTR:
case Constants.NODE_XSTR:
case Constants.NODE_DXSTR:
case Constants.NODE_DREGX:
case Constants.NODE_LIT:
case Constants.NODE_ARRAY:
case Constants.NODE_ZARRAY:
yyerror("can't define single method for literals.");
default:
break;
}
yyVal = ((Node)yyVals[-2+yyTop]);
}
break;
case 387:
// line 1698 "parse.y"
{
yyVal = ((Node)yyVals[-1+yyTop]);
}
break;
case 388:
// line 1702 "parse.y"
{
/* if ($1.getLength() % 2 != 0) {
yyerror("odd number list for Hash");
}*/
yyVal = ((Node)yyVals[-1+yyTop]);
}
break;
case 390:
// line 1711 "parse.y"
{
yyVal = ph.list_concat(((Node)yyVals[-2+yyTop]), ((Node)yyVals[0+yyTop]));
}
break;
case 391:
// line 1716 "parse.y"
{
yyVal = ph.list_append(nf.newList(((Node)yyVals[-2+yyTop])), ((Node)yyVals[0+yyTop]));
}
break;
case 411:
// line 1746 "parse.y"
{yyerrok();}
break;
case 414:
// line 1750 "parse.y"
{yyerrok();}
break;
case 415:
// line 1753 "parse.y"
{
yyVal = null; /*XXX 0;*/
}
break;
// line 2370 "-"
}
yyTop -= YyLenClass.yyLen[yyN];
yyState = yyStates[yyTop];
int yyM = YyLhsClass.yyLhs[yyN];
if (yyState == 0 && yyM == 0) {
yyState = yyFinal;
if (yyToken < 0) {
yyToken = yyLex.advance() ? yyLex.token() : 0;
}
if (yyToken == 0) {
return yyVal;
}
continue yyLoop;
}
if ((yyN = YyGindexClass.yyGindex[yyM]) != 0 && (yyN += yyState) >= 0
&& yyN < YyTableClass.yyTable.length && YyCheckClass.yyCheck[yyN] == yyState)
yyState = YyTableClass.yyTable[yyN];
else
yyState = YyDgotoClass.yyDgoto[yyM];
continue yyLoop;
}
}
|
diff --git a/sch-kp-web/src/main/java/hu/sch/web/kp/pages/group/ShowGroup.java b/sch-kp-web/src/main/java/hu/sch/web/kp/pages/group/ShowGroup.java
index 12fb1882..a65b7b01 100644
--- a/sch-kp-web/src/main/java/hu/sch/web/kp/pages/group/ShowGroup.java
+++ b/sch-kp-web/src/main/java/hu/sch/web/kp/pages/group/ShowGroup.java
@@ -1,145 +1,145 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package hu.sch.web.kp.pages.group;
import hu.sch.domain.Group;
import hu.sch.domain.Membership;
import hu.sch.domain.User;
import hu.sch.web.components.ActiveMembershipsPanel;
import hu.sch.web.components.AdminMembershipsPanel;
import hu.sch.web.components.AdminOldBoysPanel;
import hu.sch.web.components.ConfirmationBoxRenderer;
import hu.sch.web.components.OldBoysPanel;
import hu.sch.web.kp.pages.user.ShowUser;
import hu.sch.web.kp.templates.SecuredPageTemplate;
import java.util.Date;
import java.util.List;
import org.apache.wicket.PageParameters;
import org.apache.wicket.RestartResponseException;
import org.apache.wicket.extensions.markup.html.basic.SmartLinkLabel;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.basic.MultiLineLabel;
import org.apache.wicket.markup.html.link.BookmarkablePageLink;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.CompoundPropertyModel;
/**
* Az egyes körökről ezen az oldalon jelenítünk meg részletes adatokat. A
* körvezetők számára lehetőség van a kör egyes feladatait kezelni.
* @author hege
*/
public class ShowGroup extends SecuredPageTemplate {
/**
* Paraméter nélküli konstruktor, hogy a nem létező paraméter is le legyen
* kezelve.
*/
public ShowGroup() {
error("Hibás paraméter!");
throw new RestartResponseException(getApplication().getHomePage());
}
/**
* A kör adatlapját itt állítjuk össze.
* @param parameters A megjelenítendő kör azonosítója
*/
public ShowGroup(PageParameters parameters) {
//az oldal paraméterének dekódolása
Object p = parameters.get("id");
Long id = null;
try {
id = Long.parseLong(p.toString());
} catch (NumberFormatException e) {
error("Hibás paraméter!");
throw new RestartResponseException(getApplication().getHomePage());
}
final Group group = userManager.findGroupWithCsoporttagsagokById(id);
final User user = userManager.findUserWithCsoporttagsagokById(getSession().getUserId());
//ha a kör nem létezik
if (group == null) {
error("A megadott kör nem létezik!");
throw new RestartResponseException(getApplication().getHomePage());
}
//headercímke szövegének megadása, csalni kell MAVE hosszú neve miatt..
if (group.getName().contains("Informatikus-hallgatók")) {
setHeaderLabelText("MAVE adatlapja");
} else {
setHeaderLabelText(group.getName());
}
//Egy feedbackpanel a felhasználókkal történő kommunikációhoz
add(new FeedbackPanel("pagemessages"));
//A jobb oldali leugró menühöz előállítjuk a csoporttörténetes linket.
add(new BookmarkablePageLink<GroupHistory>("detailView", GroupHistory.class,
new PageParameters("id=" + group.getId().toString())));
//A kör admin felületéhez szükséges link jogosultságellenőrzéssel
Link<EditGroupInfo> editPageLink = new BookmarkablePageLink<EditGroupInfo>("editPage", EditGroupInfo.class,
new PageParameters("id=" + group.getId().toString()));
if (user != null && isUserGroupLeader(group)) {
editPageLink.setVisible(true);
} else {
editPageLink.setVisible(false);
}
add(editPageLink);
//A kör küldöttjeinek beállításához szükséges link jogosultságellenőrzéssel
Link<ChangeDelegates> editDelegates =
new BookmarkablePageLink<ChangeDelegates>("editDelegates", ChangeDelegates.class,
new PageParameters("id=" + group.getId().toString()));
if (user != null && isUserGroupLeader(group) && group.getIsSvie()) {
editDelegates.setVisible(true);
} else {
editDelegates.setVisible(false);
}
add(editDelegates);
//A kör adatlapjának előállítása (kis táblázat)
setDefaultModel(new CompoundPropertyModel<Group>(group));
add(new Label("name"));
add(new Label("founded"));
add(new Label("svieMs", (group.getIsSvie() ? "igen" : "nem")));
add(new SmartLinkLabel("webPage"));
add(new SmartLinkLabel("mailingList"));
add(new MultiLineLabel("introduction"));
//körbe jelentkezéshez a link, JS-es kérdezéssel
Link<Void> applyLink = new Link<Void>("applyToGroup") {
@Override
public void onClick() {
userManager.addUserToGroup(user, group, new Date(), null);
getSession().info("Sikeres jelentkezés");
setResponsePage(ShowUser.class);
return;
}
};
applyLink.add(new ConfirmationBoxRenderer("Biztosan szeretnél jelentkezni a körbe?"));
- if (user != null && user.getGroups().contains(group)) {
+ if (user == null || user.getGroups().contains(group)) {
applyLink.setVisible(false);
}
add(applyLink);
//az egyes paneleket elő kell állítani, ez a jogosultságtól függ.
List<Membership> activeMembers = group.getActiveMemberships();
List<Membership> inactiveMembers = group.getInactiveMemberships();
Panel adminOrActivePanel;
Panel adminOrOldBoysPanel;
if (isUserGroupLeader(group) || hasUserDelegatedPostInGroup(group)) {
adminOrActivePanel = new AdminMembershipsPanel("adminOrActive", activeMembers);
adminOrOldBoysPanel = new AdminOldBoysPanel("adminOrOldBoy", inactiveMembers);
} else {
adminOrActivePanel = new ActiveMembershipsPanel("adminOrActive", activeMembers);
adminOrOldBoysPanel = new OldBoysPanel("adminOrOldBoy", inactiveMembers);
}
add(adminOrActivePanel);
add(adminOrOldBoysPanel);
}
}
| true | true | public ShowGroup(PageParameters parameters) {
//az oldal paraméterének dekódolása
Object p = parameters.get("id");
Long id = null;
try {
id = Long.parseLong(p.toString());
} catch (NumberFormatException e) {
error("Hibás paraméter!");
throw new RestartResponseException(getApplication().getHomePage());
}
final Group group = userManager.findGroupWithCsoporttagsagokById(id);
final User user = userManager.findUserWithCsoporttagsagokById(getSession().getUserId());
//ha a kör nem létezik
if (group == null) {
error("A megadott kör nem létezik!");
throw new RestartResponseException(getApplication().getHomePage());
}
//headercímke szövegének megadása, csalni kell MAVE hosszú neve miatt..
if (group.getName().contains("Informatikus-hallgatók")) {
setHeaderLabelText("MAVE adatlapja");
} else {
setHeaderLabelText(group.getName());
}
//Egy feedbackpanel a felhasználókkal történő kommunikációhoz
add(new FeedbackPanel("pagemessages"));
//A jobb oldali leugró menühöz előállítjuk a csoporttörténetes linket.
add(new BookmarkablePageLink<GroupHistory>("detailView", GroupHistory.class,
new PageParameters("id=" + group.getId().toString())));
//A kör admin felületéhez szükséges link jogosultságellenőrzéssel
Link<EditGroupInfo> editPageLink = new BookmarkablePageLink<EditGroupInfo>("editPage", EditGroupInfo.class,
new PageParameters("id=" + group.getId().toString()));
if (user != null && isUserGroupLeader(group)) {
editPageLink.setVisible(true);
} else {
editPageLink.setVisible(false);
}
add(editPageLink);
//A kör küldöttjeinek beállításához szükséges link jogosultságellenőrzéssel
Link<ChangeDelegates> editDelegates =
new BookmarkablePageLink<ChangeDelegates>("editDelegates", ChangeDelegates.class,
new PageParameters("id=" + group.getId().toString()));
if (user != null && isUserGroupLeader(group) && group.getIsSvie()) {
editDelegates.setVisible(true);
} else {
editDelegates.setVisible(false);
}
add(editDelegates);
//A kör adatlapjának előállítása (kis táblázat)
setDefaultModel(new CompoundPropertyModel<Group>(group));
add(new Label("name"));
add(new Label("founded"));
add(new Label("svieMs", (group.getIsSvie() ? "igen" : "nem")));
add(new SmartLinkLabel("webPage"));
add(new SmartLinkLabel("mailingList"));
add(new MultiLineLabel("introduction"));
//körbe jelentkezéshez a link, JS-es kérdezéssel
Link<Void> applyLink = new Link<Void>("applyToGroup") {
@Override
public void onClick() {
userManager.addUserToGroup(user, group, new Date(), null);
getSession().info("Sikeres jelentkezés");
setResponsePage(ShowUser.class);
return;
}
};
applyLink.add(new ConfirmationBoxRenderer("Biztosan szeretnél jelentkezni a körbe?"));
if (user != null && user.getGroups().contains(group)) {
applyLink.setVisible(false);
}
add(applyLink);
//az egyes paneleket elő kell állítani, ez a jogosultságtól függ.
List<Membership> activeMembers = group.getActiveMemberships();
List<Membership> inactiveMembers = group.getInactiveMemberships();
Panel adminOrActivePanel;
Panel adminOrOldBoysPanel;
if (isUserGroupLeader(group) || hasUserDelegatedPostInGroup(group)) {
adminOrActivePanel = new AdminMembershipsPanel("adminOrActive", activeMembers);
adminOrOldBoysPanel = new AdminOldBoysPanel("adminOrOldBoy", inactiveMembers);
} else {
adminOrActivePanel = new ActiveMembershipsPanel("adminOrActive", activeMembers);
adminOrOldBoysPanel = new OldBoysPanel("adminOrOldBoy", inactiveMembers);
}
add(adminOrActivePanel);
add(adminOrOldBoysPanel);
}
| public ShowGroup(PageParameters parameters) {
//az oldal paraméterének dekódolása
Object p = parameters.get("id");
Long id = null;
try {
id = Long.parseLong(p.toString());
} catch (NumberFormatException e) {
error("Hibás paraméter!");
throw new RestartResponseException(getApplication().getHomePage());
}
final Group group = userManager.findGroupWithCsoporttagsagokById(id);
final User user = userManager.findUserWithCsoporttagsagokById(getSession().getUserId());
//ha a kör nem létezik
if (group == null) {
error("A megadott kör nem létezik!");
throw new RestartResponseException(getApplication().getHomePage());
}
//headercímke szövegének megadása, csalni kell MAVE hosszú neve miatt..
if (group.getName().contains("Informatikus-hallgatók")) {
setHeaderLabelText("MAVE adatlapja");
} else {
setHeaderLabelText(group.getName());
}
//Egy feedbackpanel a felhasználókkal történő kommunikációhoz
add(new FeedbackPanel("pagemessages"));
//A jobb oldali leugró menühöz előállítjuk a csoporttörténetes linket.
add(new BookmarkablePageLink<GroupHistory>("detailView", GroupHistory.class,
new PageParameters("id=" + group.getId().toString())));
//A kör admin felületéhez szükséges link jogosultságellenőrzéssel
Link<EditGroupInfo> editPageLink = new BookmarkablePageLink<EditGroupInfo>("editPage", EditGroupInfo.class,
new PageParameters("id=" + group.getId().toString()));
if (user != null && isUserGroupLeader(group)) {
editPageLink.setVisible(true);
} else {
editPageLink.setVisible(false);
}
add(editPageLink);
//A kör küldöttjeinek beállításához szükséges link jogosultságellenőrzéssel
Link<ChangeDelegates> editDelegates =
new BookmarkablePageLink<ChangeDelegates>("editDelegates", ChangeDelegates.class,
new PageParameters("id=" + group.getId().toString()));
if (user != null && isUserGroupLeader(group) && group.getIsSvie()) {
editDelegates.setVisible(true);
} else {
editDelegates.setVisible(false);
}
add(editDelegates);
//A kör adatlapjának előállítása (kis táblázat)
setDefaultModel(new CompoundPropertyModel<Group>(group));
add(new Label("name"));
add(new Label("founded"));
add(new Label("svieMs", (group.getIsSvie() ? "igen" : "nem")));
add(new SmartLinkLabel("webPage"));
add(new SmartLinkLabel("mailingList"));
add(new MultiLineLabel("introduction"));
//körbe jelentkezéshez a link, JS-es kérdezéssel
Link<Void> applyLink = new Link<Void>("applyToGroup") {
@Override
public void onClick() {
userManager.addUserToGroup(user, group, new Date(), null);
getSession().info("Sikeres jelentkezés");
setResponsePage(ShowUser.class);
return;
}
};
applyLink.add(new ConfirmationBoxRenderer("Biztosan szeretnél jelentkezni a körbe?"));
if (user == null || user.getGroups().contains(group)) {
applyLink.setVisible(false);
}
add(applyLink);
//az egyes paneleket elő kell állítani, ez a jogosultságtól függ.
List<Membership> activeMembers = group.getActiveMemberships();
List<Membership> inactiveMembers = group.getInactiveMemberships();
Panel adminOrActivePanel;
Panel adminOrOldBoysPanel;
if (isUserGroupLeader(group) || hasUserDelegatedPostInGroup(group)) {
adminOrActivePanel = new AdminMembershipsPanel("adminOrActive", activeMembers);
adminOrOldBoysPanel = new AdminOldBoysPanel("adminOrOldBoy", inactiveMembers);
} else {
adminOrActivePanel = new ActiveMembershipsPanel("adminOrActive", activeMembers);
adminOrOldBoysPanel = new OldBoysPanel("adminOrOldBoy", inactiveMembers);
}
add(adminOrActivePanel);
add(adminOrOldBoysPanel);
}
|
diff --git a/ghana-national-functional-tests/src/main/java/org/motechproject/ghana/national/functional/framework/ScheduleTracker.java b/ghana-national-functional-tests/src/main/java/org/motechproject/ghana/national/functional/framework/ScheduleTracker.java
index df45e3c6..079090f1 100644
--- a/ghana-national-functional-tests/src/main/java/org/motechproject/ghana/national/functional/framework/ScheduleTracker.java
+++ b/ghana-national-functional-tests/src/main/java/org/motechproject/ghana/national/functional/framework/ScheduleTracker.java
@@ -1,261 +1,261 @@
package org.motechproject.ghana.national.functional.framework;
import org.joda.time.DateTime;
import org.joda.time.LocalDate;
import org.joda.time.Period;
import org.motechproject.ghana.national.functional.domain.Alert;
import org.motechproject.model.Time;
import org.motechproject.scheduler.MotechSchedulerService;
import org.motechproject.scheduler.MotechSchedulerServiceImpl;
import org.motechproject.scheduletracking.api.domain.Enrollment;
import org.motechproject.scheduletracking.api.domain.Milestone;
import org.motechproject.scheduletracking.api.domain.MilestoneWindow;
import org.motechproject.scheduletracking.api.domain.WindowName;
import org.motechproject.scheduletracking.api.events.constants.EventDataKeys;
import org.motechproject.scheduletracking.api.events.constants.EventSubjects;
import org.motechproject.scheduletracking.api.repository.AllEnrollments;
import org.motechproject.scheduletracking.api.repository.AllTrackedSchedules;
import org.motechproject.scheduletracking.api.service.EnrollmentRecord;
import org.motechproject.scheduletracking.api.service.impl.ScheduleTrackingServiceImpl;
import org.motechproject.util.DateUtil;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Component;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Calendar;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static java.lang.String.format;
import static org.apache.commons.lang.time.DateUtils.parseDate;
import static org.joda.time.PeriodType.millis;
import static org.motechproject.ghana.national.tools.Utility.nullSafe;
import static org.motechproject.util.DateUtil.newDateTime;
@Component
public class ScheduleTracker {
@Autowired
protected MotechSchedulerService motechSchedulerService;
@Autowired
private AllEnrollments allEnrollments;
@Autowired
private SchedulerFactoryBean schedulerFactoryBean;
@Autowired
protected ScheduleTrackingServiceImpl scheduleTrackingService;
@Autowired
AllTrackedSchedules allTrackedSchedules;
private Pattern ALERT_ORDER_INDEX_REGEX = Pattern.compile("^.*\\.(.*?)-repeat$");
protected Time preferredAlertTime;
public void setUp() {
preferredAlertTime = new Time(10, 10);
}
public String getActiveMilestone(String externalId, String scheduleName){
return allEnrollments.getActiveEnrollment(externalId, scheduleName).getCurrentMilestoneName();
}
public EnrollmentRecord activeEnrollment(String externalId, String scheduleName){
return scheduleTrackingService.getEnrollment(externalId, scheduleName);
}
public void deleteAllJobs() throws SchedulerException {
for (Enrollment enrollment : allEnrollments.getAll()) {
allEnrollments.remove(enrollment);
}
Scheduler scheduler = schedulerFactoryBean.getScheduler();
for (String jobGroup : scheduler.getJobGroupNames()) {
for (String jobName : scheduler.getJobNames(jobGroup)) {
scheduler.deleteJob(jobName, jobGroup);
}
}
}
private void assertNotNull(Object object) {
if (object == null) throw new AssertionError("should not be null");
}
public List<org.motechproject.ghana.national.functional.domain.JobDetail> captureScheduleAlerts(String externalId, String scheduleName) {
Enrollment activeEnrollment = allEnrollments.getActiveEnrollment(externalId, scheduleName);
assertNotNull(activeEnrollment);
return captureAlertsForNextMilestone(activeEnrollment.getId());
}
protected List<org.motechproject.ghana.national.functional.domain.JobDetail> captureAlertsForNextMilestone(String enrollmentId) {
final Scheduler scheduler = schedulerFactoryBean.getScheduler();
final String jobGroupName = MotechSchedulerServiceImpl.JOB_GROUP_NAME;
String[] jobNames = new String[0];
List<org.motechproject.ghana.national.functional.domain.JobDetail> alertTriggers = new ArrayList<org.motechproject.ghana.national.functional.domain.JobDetail>();
try {
jobNames = scheduler.getJobNames(jobGroupName);
for (String jobName : jobNames) {
if (jobName.contains(format("%s-%s", EventSubjects.MILESTONE_ALERT, enrollmentId))) {
Trigger[] triggersOfJob = scheduler.getTriggersOfJob(jobName, jobGroupName);
alertTriggers.add(new org.motechproject.ghana.national.functional.domain.JobDetail((SimpleTrigger) triggersOfJob[0], scheduler.getJobDetail(jobName, jobGroupName)));
}
}
} catch (SchedulerException e) {
throw new RuntimeException(e);
}
return alertTriggers;
}
public List<Date> alerts(List<org.motechproject.ghana.national.functional.domain.JobDetail> testJobDetails) {
sortBasedOnIndexInAlertName(testJobDetails);
List<Date> actualAlertTimes = new ArrayList<Date>();
for (org.motechproject.ghana.national.functional.domain.JobDetail testJobDetail : testJobDetails) {
SimpleTrigger alert = testJobDetail.trigger();
Date nextFireTime = alert.getNextFireTime();
actualAlertTimes.add(nextFireTime);
for (int i = 1; i <= alert.getRepeatCount() - alert.getTimesTriggered(); i++) {
Calendar calendar = Calendar.getInstance();
calendar.setTime((Date) nextFireTime.clone());
calendar.add(Calendar.DAY_OF_MONTH, toDays(i * alert.getRepeatInterval()));
actualAlertTimes.add(calendar.getTime());
}
}
return actualAlertTimes;
}
private List<Alert> createActualAlertTimes(List<org.motechproject.ghana.national.functional.domain.JobDetail> alertsJobDetails) {
sortBasedOnIndexInAlertName(alertsJobDetails);
List<Alert> actualAlertTimes = new ArrayList<Alert>();
for (org.motechproject.ghana.national.functional.domain.JobDetail testJobDetail : alertsJobDetails) {
SimpleTrigger alert = testJobDetail.trigger();
Date nextFireTime = alert.getNextFireTime();
JobDataMap dataMap = testJobDetail.getJobDetail().getJobDataMap();
actualAlertTimes.add(new Alert(window(dataMap), nextFireTime));
for (int i = 1; i <= alert.getRepeatCount(); i++) {
Calendar calendar = Calendar.getInstance();
calendar.setTime((Date) nextFireTime.clone());
calendar.add(Calendar.DAY_OF_MONTH, toDays(i * alert.getRepeatInterval()));
actualAlertTimes.add(new Alert(window(dataMap), calendar.getTime()));
}
}
return actualAlertTimes;
}
private WindowName window(JobDataMap dataMap) {
return WindowName.valueOf((String) dataMap.get(EventDataKeys.WINDOW_NAME));
}
private Integer extractIndexFromAlertName(String name) {
Matcher matcher = ALERT_ORDER_INDEX_REGEX.matcher(name);
return matcher.find() ? Integer.parseInt(matcher.group(1)) : null;
}
private void sortBasedOnIndexInAlertName(List<org.motechproject.ghana.national.functional.domain.JobDetail> alertJobDetails) {
Collections.sort(alertJobDetails, new Comparator<org.motechproject.ghana.national.functional.domain.JobDetail>() {
@Override
public int compare(org.motechproject.ghana.national.functional.domain.JobDetail testJobDetail1, org.motechproject.ghana.national.functional.domain.JobDetail testJobDetail2) {
return extractIndexFromAlertName(testJobDetail1.trigger().getName()).compareTo(extractIndexFromAlertName(testJobDetail2.trigger().getName()));
}
});
}
private int toDays(long milliseconds) {
return (int) (milliseconds / 1000 / 60 / 60 / 24);
}
protected Date onDate(LocalDate referenceDate, int numberOfWeeks, Time alertTime) {
return newDateTime(referenceDate.plusWeeks(numberOfWeeks), alertTime).toDate();
}
protected Date onDate(LocalDate referenceDate, Time alertTime) {
return newDateTime(referenceDate, alertTime).toDate();
}
protected Date onDate(LocalDate localDate) {
return newDateTime(localDate, preferredAlertTime).toDate();
}
protected Date onDate(String date) {
return newDateTime(newDate(date), preferredAlertTime).toDate();
}
protected LocalDate newDate(String date) {
try {
return DateUtil.newDate(new SimpleDateFormat("dd-MMM-yyyy").parse(date));
} catch (ParseException e) {
throw new IllegalArgumentException(e);
}
}
protected DateTime newDateWithTime(String date, String time) {
try {
String dateToParse = date + " " + time;
return newDateTime(parseDate(dateToParse, new String[]{"dd-MMM-yyyy HH:mm", "dd-MMM-yyyy HH:mm:ss", "dd-MMM-yyyy HH:mm:ss.SSS"}));
} catch (ParseException e) {
throw new IllegalArgumentException(e);
}
}
protected Alert alert(WindowName windowName, Date alertDate) {
return new Alert(windowName, alertDate);
}
protected ArrayList<Date> dates(LocalDate... dates) {
ArrayList<Date> dateList = new ArrayList<Date>();
for (LocalDate localDate : dates) {
dateList.add(onDate(localDate));
}
return dateList;
}
protected ArrayList<Date> dateTimes(DateTime... dates) {
ArrayList<Date> dateList = new ArrayList<Date>();
for (DateTime date : dates) {
dateList.add(date.toDate());
}
return dateList;
}
public Alert firstAlertScheduledFor(String externalId, String scheduleName) {
return nullSafe(createActualAlertTimes(captureScheduleAlerts(externalId, scheduleName)), 0, null);
}
public LocalDate firstAlert(String scheduleName, LocalDate referenceDate) {
return firstAlert(scheduleName, referenceDate, allTrackedSchedules.getByName(scheduleName).getFirstMilestone().getName());
}
public LocalDate firstAlert(String scheduleName, LocalDate referenceDate, String milestoneName) {
org.motechproject.scheduletracking.api.domain.Schedule schedule = allTrackedSchedules.getByName(scheduleName);
Milestone milestone = schedule.getMilestone(milestoneName);
return findFirstApplicableAlert(milestone, referenceDate);
}
private LocalDate findFirstApplicableAlert(Milestone milestone, LocalDate referenceDate) {
List<MilestoneWindow> milestoneWindows = milestone.getMilestoneWindows();
for (MilestoneWindow milestoneWindow : milestoneWindows) {
Period windowStart = milestone.getWindowStart(milestoneWindow.getName());
Period windowEnd = milestone.getWindowEnd(milestoneWindow.getName());
for (org.motechproject.scheduletracking.api.domain.Alert alert : milestoneWindow.getAlerts()) {
LocalDate referenceWindowStartDate = referenceDate.plus(windowStart);
LocalDate referenceWindowEndDate = referenceDate.plus(windowEnd);
- int alertCount = alert.getRemainingAlertCount(newDateTime(referenceWindowStartDate.toDate()), newDateTime(referenceWindowEndDate.toDate()), null);
+ int alertCount = alert.getRemainingAlertCount(newDateTime(referenceWindowStartDate.toDate()), null);
for (long count = 0; count <= alertCount; count++) {
Period interval = new Period(alert.getInterval().toStandardDuration().getMillis() * count, millis());
LocalDate idealStartDate = referenceWindowStartDate.plus(alert.getOffset()).plusDays((int) interval.toStandardDuration().getStandardDays());
if (idealStartDate.compareTo(DateUtil.today()) > 0) return idealStartDate;
}
}
}
return null;
}
}
| true | true | private LocalDate findFirstApplicableAlert(Milestone milestone, LocalDate referenceDate) {
List<MilestoneWindow> milestoneWindows = milestone.getMilestoneWindows();
for (MilestoneWindow milestoneWindow : milestoneWindows) {
Period windowStart = milestone.getWindowStart(milestoneWindow.getName());
Period windowEnd = milestone.getWindowEnd(milestoneWindow.getName());
for (org.motechproject.scheduletracking.api.domain.Alert alert : milestoneWindow.getAlerts()) {
LocalDate referenceWindowStartDate = referenceDate.plus(windowStart);
LocalDate referenceWindowEndDate = referenceDate.plus(windowEnd);
int alertCount = alert.getRemainingAlertCount(newDateTime(referenceWindowStartDate.toDate()), newDateTime(referenceWindowEndDate.toDate()), null);
for (long count = 0; count <= alertCount; count++) {
Period interval = new Period(alert.getInterval().toStandardDuration().getMillis() * count, millis());
LocalDate idealStartDate = referenceWindowStartDate.plus(alert.getOffset()).plusDays((int) interval.toStandardDuration().getStandardDays());
if (idealStartDate.compareTo(DateUtil.today()) > 0) return idealStartDate;
}
}
}
return null;
}
| private LocalDate findFirstApplicableAlert(Milestone milestone, LocalDate referenceDate) {
List<MilestoneWindow> milestoneWindows = milestone.getMilestoneWindows();
for (MilestoneWindow milestoneWindow : milestoneWindows) {
Period windowStart = milestone.getWindowStart(milestoneWindow.getName());
Period windowEnd = milestone.getWindowEnd(milestoneWindow.getName());
for (org.motechproject.scheduletracking.api.domain.Alert alert : milestoneWindow.getAlerts()) {
LocalDate referenceWindowStartDate = referenceDate.plus(windowStart);
LocalDate referenceWindowEndDate = referenceDate.plus(windowEnd);
int alertCount = alert.getRemainingAlertCount(newDateTime(referenceWindowStartDate.toDate()), null);
for (long count = 0; count <= alertCount; count++) {
Period interval = new Period(alert.getInterval().toStandardDuration().getMillis() * count, millis());
LocalDate idealStartDate = referenceWindowStartDate.plus(alert.getOffset()).plusDays((int) interval.toStandardDuration().getStandardDays());
if (idealStartDate.compareTo(DateUtil.today()) > 0) return idealStartDate;
}
}
}
return null;
}
|
diff --git a/mes-plugins/mes-plugins-basic/src/main/java/com/qcadoo/mes/basic/CompanyService.java b/mes-plugins/mes-plugins-basic/src/main/java/com/qcadoo/mes/basic/CompanyService.java
index cf58e3b24d..fcfbd4b83f 100644
--- a/mes-plugins/mes-plugins-basic/src/main/java/com/qcadoo/mes/basic/CompanyService.java
+++ b/mes-plugins/mes-plugins-basic/src/main/java/com/qcadoo/mes/basic/CompanyService.java
@@ -1,160 +1,160 @@
/**
* ***************************************************************************
* Copyright (c) 2010 Qcadoo Limited
* Project: Qcadoo MES
* Version: 1.2.0
*
* This file is part of Qcadoo.
*
* Qcadoo is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation; either version 3 of the License,
* or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
* ***************************************************************************
*/
package com.qcadoo.mes.basic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.qcadoo.mes.basic.constants.BasicConstants;
import com.qcadoo.mes.basic.constants.ParameterFields;
import com.qcadoo.model.api.DataDefinition;
import com.qcadoo.model.api.DataDefinitionService;
import com.qcadoo.model.api.Entity;
import com.qcadoo.view.api.ComponentState;
import com.qcadoo.view.api.ViewDefinitionState;
import com.qcadoo.view.api.components.FormComponent;
import com.qcadoo.view.api.components.GridComponent;
import com.qcadoo.view.api.components.WindowComponent;
import com.qcadoo.view.api.ribbon.RibbonActionItem;
import com.qcadoo.view.api.ribbon.RibbonGroup;
@Service
public class CompanyService {
private static final String L_FORM = "form";
private static final String L_WINDOW = "window";
@Autowired
private DataDefinitionService dataDefinitionService;
@Autowired
private ParameterService parameterService;
/**
* Returns basic company entity id for current user
*
* @return company entity id
*
*/
public Long getCompanyId() {
if (getCompany() == null) {
return null;
} else {
return getCompany().getId();
}
}
/**
* Returns basic company entity for current user.
*
* @return company entity
*
*/
@Transactional
public Entity getCompany() {
Entity parameter = parameterService.getParameter();
return parameter.getBelongsToField(ParameterFields.COMPANY);
}
/**
* Returns company entity
*
* @param companyId
* companyId
*
* @return company
*/
@Transactional
public Entity getCompany(final Long companyId) {
return getCompanyDD().get(companyId);
}
private DataDefinition getCompanyDD() {
return dataDefinitionService.get(BasicConstants.PLUGIN_IDENTIFIER, BasicConstants.MODEL_COMPANY);
}
public final Boolean isCompanyOwner(final Entity company) {
- Long compantId = company.getId();
+ Long companyId = company.getId();
if (companyId == null) {
return Boolean.FALSE;
}
Entity companyFromDB = getCompanyDD().get(companyId);
if (companyFromDB == null) {
return Boolean.FALSE;
}
Entity parameter = parameterService.getParameter();
Entity owner = parameter.getBelongsToField(ParameterFields.COMPANY);
if (owner == null) {
return Boolean.FALSE;
}
return companyFromDB.getId().equals(owner.getId());
}
public void disabledGridWhenCompanyIsOwner(final ViewDefinitionState view, final String... references) {
FormComponent companyForm = (FormComponent) view.getComponentByReference(L_FORM);
Entity company = companyForm.getEntity();
Boolean isOwner = isCompanyOwner(company);
disableGridComponents(view, !isOwner, references);
}
private void disableGridComponents(final ViewDefinitionState view, final Boolean isEditable, final String... references) {
for (String reference : references) {
ComponentState componentState = view.getComponentByReference(reference);
if (componentState instanceof GridComponent) {
((GridComponent) componentState).setEditable(isEditable);
}
}
}
public void disableButton(final ViewDefinitionState view, final String ribbonGroupName, final String ribbonActionItemName,
final boolean isEnabled, final String message) {
WindowComponent window = (WindowComponent) view.getComponentByReference(L_WINDOW);
RibbonGroup ribbonGroup = (RibbonGroup) window.getRibbon().getGroupByName(ribbonGroupName);
RibbonActionItem ribbonActionItem = (RibbonActionItem) ribbonGroup.getItemByName(ribbonActionItemName);
ribbonActionItem.setEnabled(isEnabled);
if (isEnabled) {
ribbonActionItem.setMessage(null);
} else {
ribbonActionItem.setMessage(message);
}
ribbonActionItem.requestUpdate(true);
}
}
| true | true | public final Boolean isCompanyOwner(final Entity company) {
Long compantId = company.getId();
if (companyId == null) {
return Boolean.FALSE;
}
Entity companyFromDB = getCompanyDD().get(companyId);
if (companyFromDB == null) {
return Boolean.FALSE;
}
Entity parameter = parameterService.getParameter();
Entity owner = parameter.getBelongsToField(ParameterFields.COMPANY);
if (owner == null) {
return Boolean.FALSE;
}
return companyFromDB.getId().equals(owner.getId());
}
| public final Boolean isCompanyOwner(final Entity company) {
Long companyId = company.getId();
if (companyId == null) {
return Boolean.FALSE;
}
Entity companyFromDB = getCompanyDD().get(companyId);
if (companyFromDB == null) {
return Boolean.FALSE;
}
Entity parameter = parameterService.getParameter();
Entity owner = parameter.getBelongsToField(ParameterFields.COMPANY);
if (owner == null) {
return Boolean.FALSE;
}
return companyFromDB.getId().equals(owner.getId());
}
|
diff --git a/src/main/java/hudson/plugins/analysis/core/HealthAwareReporter.java b/src/main/java/hudson/plugins/analysis/core/HealthAwareReporter.java
index 81d2295..271d64e 100644
--- a/src/main/java/hudson/plugins/analysis/core/HealthAwareReporter.java
+++ b/src/main/java/hudson/plugins/analysis/core/HealthAwareReporter.java
@@ -1,658 +1,657 @@
package hudson.plugins.analysis.core;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Collection;
import org.apache.commons.lang.StringUtils;
import org.apache.maven.project.MavenProject;
import hudson.FilePath;
import hudson.Launcher;
import hudson.maven.MavenAggregatedReport;
import hudson.maven.MavenBuildProxy;
import hudson.maven.MavenBuildProxy.BuildCallable;
import hudson.maven.MavenReporter;
import hudson.maven.MojoInfo;
import hudson.maven.MavenBuild;
import hudson.maven.MavenModuleSetBuild;
import hudson.model.BuildListener;
import hudson.model.Result;
import hudson.model.AbstractBuild;
import hudson.plugins.analysis.Messages;
import hudson.plugins.analysis.util.PluginLogger;
import hudson.plugins.analysis.util.StringPluginLogger;
import hudson.plugins.analysis.util.model.AbstractAnnotation;
import hudson.plugins.analysis.util.model.AnnotationContainer;
import hudson.plugins.analysis.util.model.DefaultAnnotationContainer;
import hudson.plugins.analysis.util.model.FileAnnotation;
import hudson.plugins.analysis.util.model.Priority;
import hudson.plugins.analysis.util.model.WorkspaceFile;
import hudson.remoting.Channel;
import hudson.remoting.VirtualChannel;
import hudson.tasks.BuildStep;
/**
* A base class for Maven reporters with the following two characteristics:
* <ul>
* <li>It provides a unstable threshold, that could be enabled and set in the
* configuration screen. If the number of annotations in a build exceeds this
* value then the build is considered as {@link Result#UNSTABLE UNSTABLE}.
* </li>
* <li>It provides thresholds for the build health, that could be adjusted in
* the configuration screen. These values are used by the
* {@link HealthReportBuilder} to compute the health and the health trend graph.</li>
* </ul>
*
* @param <T> the actual type of the build result
* @author Ulli Hafner
* @since 1.20
*/
// CHECKSTYLE:COUPLING-OFF
@SuppressWarnings("PMD.TooManyFields")
public abstract class HealthAwareReporter<T extends BuildResult> extends MavenReporter implements HealthDescriptor {
/** Default threshold priority limit. */
private static final String DEFAULT_PRIORITY_THRESHOLD_LIMIT = "low";
/** Unique identifier of this class. */
private static final long serialVersionUID = -5369644266347796143L;
/** Report health as 100% when the number of warnings is less than this value. */
private final String healthy;
/** Report health as 0% when the number of warnings is greater than this value. */
private final String unHealthy;
/** The name of the plug-in. */
private final String pluginName;
/** Determines which warning priorities should be considered when evaluating the build stability and health. */
private String thresholdLimit;
/** The default encoding to be used when reading and parsing files. */
private String defaultEncoding;
/** Determines whether the plug-in should run for failed builds, too. @since 1.6 */
private final boolean canRunOnFailed;
/**
* Determines whether the absolute annotations delta or the actual
* annotations set difference should be used to evaluate the build stability.
*
* @since 1.20
*/
private final boolean useDeltaValues;
/**
* Thresholds for build status unstable and failed, resp. and priorities
* all, high, normal, and low, resp.
*
* @since 1.20
*/
private Thresholds thresholds = new Thresholds();
/**
* Determines whether new warnings should be computed (with respect to baseline).
*
* @since 1.34
*/
private final boolean dontComputeNew;
/**
* Creates a new instance of <code>HealthReportingMavenReporter</code>.
*
* @param healthy
* Report health as 100% when the number of warnings is less than
* this value
* @param unHealthy
* Report health as 0% when the number of warnings is greater
* than this value
* @param thresholdLimit
* determines which warning priorities should be considered when
* evaluating the build stability and health
* @param useDeltaValues
* determines whether the absolute annotations delta or the
* actual annotations set difference should be used to evaluate
* the build stability
* @param unstableTotalAll
* annotation threshold
* @param unstableTotalHigh
* annotation threshold
* @param unstableTotalNormal
* annotation threshold
* @param unstableTotalLow
* annotation threshold
* @param unstableNewAll
* annotation threshold
* @param unstableNewHigh
* annotation threshold
* @param unstableNewNormal
* annotation threshold
* @param unstableNewLow
* annotation threshold
* @param failedTotalAll
* annotation threshold
* @param failedTotalHigh
* annotation threshold
* @param failedTotalNormal
* annotation threshold
* @param failedTotalLow
* annotation threshold
* @param failedNewAll
* annotation threshold
* @param failedNewHigh
* annotation threshold
* @param failedNewNormal
* annotation threshold
* @param failedNewLow
* annotation threshold
* @param canRunOnFailed
* determines whether the plug-in can run for failed builds, too
* @param canComputeNew
* determines whether new warnings should be computed (with respect to baseline)
* @param pluginName
* the name of the plug-in
*/
// CHECKSTYLE:OFF
@SuppressWarnings("PMD.ExcessiveParameterList")
public HealthAwareReporter(final String healthy, final String unHealthy, final String thresholdLimit, final boolean useDeltaValues,
final String unstableTotalAll, final String unstableTotalHigh, final String unstableTotalNormal, final String unstableTotalLow,
final String unstableNewAll, final String unstableNewHigh, final String unstableNewNormal, final String unstableNewLow,
final String failedTotalAll, final String failedTotalHigh, final String failedTotalNormal, final String failedTotalLow,
final String failedNewAll, final String failedNewHigh, final String failedNewNormal, final String failedNewLow,
final boolean canRunOnFailed, final boolean canComputeNew,
final String pluginName) {
super();
this.healthy = healthy;
this.unHealthy = unHealthy;
this.thresholdLimit = thresholdLimit;
this.canRunOnFailed = canRunOnFailed;
this.dontComputeNew = !canComputeNew;
this.pluginName = "[" + pluginName + "] ";
this.useDeltaValues = useDeltaValues;
thresholds.unstableTotalAll = unstableTotalAll;
thresholds.unstableTotalHigh = unstableTotalHigh;
thresholds.unstableTotalNormal = unstableTotalNormal;
thresholds.unstableTotalLow = unstableTotalLow;
thresholds.unstableNewAll = unstableNewAll;
thresholds.unstableNewHigh = unstableNewHigh;
thresholds.unstableNewNormal = unstableNewNormal;
thresholds.unstableNewLow = unstableNewLow;
thresholds.failedTotalAll = failedTotalAll;
thresholds.failedTotalHigh = failedTotalHigh;
thresholds.failedTotalNormal = failedTotalNormal;
thresholds.failedTotalLow = failedTotalLow;
thresholds.failedNewAll = failedNewAll;
thresholds.failedNewHigh = failedNewHigh;
thresholds.failedNewNormal = failedNewNormal;
thresholds.failedNewLow = failedNewLow;
System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.Jdk14Logger");
}
// CHECKSTYLE:ON
// CHECKSTYLE:OFF
@SuppressWarnings("PMD.ExcessiveParameterList")
@Deprecated
public HealthAwareReporter(final String healthy, final String unHealthy, final String thresholdLimit, final boolean useDeltaValues,
final String unstableTotalAll, final String unstableTotalHigh, final String unstableTotalNormal, final String unstableTotalLow,
final String unstableNewAll, final String unstableNewHigh, final String unstableNewNormal, final String unstableNewLow,
final String failedTotalAll, final String failedTotalHigh, final String failedTotalNormal, final String failedTotalLow,
final String failedNewAll, final String failedNewHigh, final String failedNewNormal, final String failedNewLow,
final boolean canRunOnFailed, final String pluginName) {
this(healthy, unHealthy, thresholdLimit, useDeltaValues,
unstableTotalAll, unstableTotalHigh, unstableTotalNormal, unstableTotalLow,
unstableNewAll, unstableNewHigh, unstableNewNormal, unstableNewLow,
failedTotalAll, failedTotalHigh, failedTotalNormal, failedTotalLow,
failedNewAll, failedNewHigh, failedNewNormal, failedNewLow,
canRunOnFailed, true, pluginName);
}
// CHECKSTYLE:ON
/**
* Returns whether new warnings should be computed (with respect to
* baseline).
*
* @return <code>true</code> if new warnings should be computed (with
* respect to baseline), <code>false</code> otherwise
*/
public boolean getCanComputeNew() {
return canComputeNew();
}
/**
* Returns whether new warnings should be computed (with respect to
* baseline).
*
* @return <code>true</code> if new warnings should be computed (with
* respect to baseline), <code>false</code> otherwise
*/
public boolean canComputeNew() {
return !dontComputeNew;
}
/**
* Returns whether absolute annotations delta or the actual annotations set
* difference should be used to evaluate the build stability.
*
* @return <code>true</code> if the annotation count should be used,
* <code>false</code> if the actual (set) difference should be
* computed
*/
public boolean getUseDeltaValues() {
return useDeltaValues;
}
/** {@inheritDoc} */
public Thresholds getThresholds() {
return thresholds;
}
/**
* Initializes new fields that are not serialized yet.
*
* @return the object
*/
@SuppressWarnings("deprecation")
@edu.umd.cs.findbugs.annotations.SuppressWarnings("Se")
private Object readResolve() {
if (thresholdLimit == null) {
thresholdLimit = DEFAULT_PRIORITY_THRESHOLD_LIMIT;
}
if (thresholds == null) {
thresholds = new Thresholds();
if (threshold != null) {
thresholds.unstableTotalAll = threshold;
threshold = null; // NOPMD
}
if (newThreshold != null) {
thresholds.unstableNewAll = newThreshold;
newThreshold = null; // NOPMD
}
if (failureThreshold != null) {
thresholds.failedTotalAll = failureThreshold;
failureThreshold = null; //NOPMD
}
if (newFailureThreshold != null) {
thresholds.failedNewAll = newFailureThreshold;
newFailureThreshold = null; // NOPMD
}
}
return this;
}
/** {@inheritDoc} */
@SuppressWarnings({"serial", "PMD.AvoidFinalLocalVariable"})
@Override
public final boolean postExecute(final MavenBuildProxy build, final MavenProject pom, final MojoInfo mojo,
final BuildListener listener, final Throwable error) throws InterruptedException, IOException {
PluginLogger logger = new PluginLogger(listener.getLogger(), pluginName);
if (!acceptGoal(mojo.getGoal())) {
return true;
}
Result currentResult = getCurrentResult(build);
if (!canContinue(currentResult)) {
logger.log("Skipping reporter since build result is " + currentResult);
return true;
}
if (hasResultAction(build)) {
- logger.log("Skipping maven reporter: there is already a result available.");
return true;
}
final ParserResult result;
try {
result = perform(build, pom, mojo, logger);
if (result.getModules().isEmpty() && result.getNumberOfAnnotations() == 0) {
logger.log("No report found for mojo " + mojo.getGoal());
return true;
}
}
catch (InterruptedException exception) {
logger.log(exception.getMessage());
return false;
}
logger.logLines(result.getLogMessages());
defaultEncoding = pom.getProperties().getProperty("project.build.sourceEncoding");
if (defaultEncoding == null) {
logger.log(Messages.Reporter_Error_NoEncoding(Charset.defaultCharset().displayName()));
result.addErrorMessage(pom.getName(), Messages.Reporter_Error_NoEncoding(Charset.defaultCharset().displayName()));
}
String resultLog = build.execute(new BuildCallable<String, IOException>() {
public String call(final MavenBuild mavenBuild) throws IOException, InterruptedException {
return registerResults(result, mavenBuild);
}
});
logger.logLines(resultLog);
copyFilesWithAnnotationsToBuildFolder(logger, build.getRootDir(), result.getAnnotations());
return true;
}
private String registerResults(final ParserResult result, final MavenBuild mavenBuild) {
T buildResult = createResult(mavenBuild, result);
StringPluginLogger pluginLogger = new StringPluginLogger(pluginName);
buildResult.evaluateStatus(thresholds, useDeltaValues, canComputeNew(), pluginLogger);
mavenBuild.getActions().add(createMavenAggregatedReport(mavenBuild, buildResult));
mavenBuild.registerAsProjectAction(HealthAwareReporter.this);
AbstractBuild<?, ?> referenceBuild = buildResult.getHistory().getReferenceBuild();
if (referenceBuild != null) {
pluginLogger.log("Computing warning deltas based on reference build " + referenceBuild.getDisplayName());
}
return pluginLogger.toString();
}
/**
* Since aggregation is done in background we still need to log all messages
* of that step to the log.
*
* @param build
* the finished maven module build
* @param launcher
* the launcher
* @param listener
* the lister that holds the log
* @return <code>true</code>
*/
@Override
public boolean end(final MavenBuild build, final Launcher launcher, final BuildListener listener) {
MavenModuleSetBuild moduleSetBuild = build.getParentBuild();
if (moduleSetBuild != null) {
MavenResultAction<T> action = moduleSetBuild.getAction(getResultActionClass());
if (action != null) {
listener.getLogger().append(action.getLog());
}
}
return true;
}
/**
* Returns the current result of the build.
*
* @param build
* the build proxy
* @return the current result of the build
* @throws IOException
* if the results could not be read
* @throws InterruptedException
* if the user canceled the operation
*/
private Result getCurrentResult(final MavenBuildProxy build) throws IOException, InterruptedException {
return build.execute(new BuildResultCallable());
}
/**
* Returns whether this plug-in can run for failed builds, too.
*
* @return <code>true</code> if this plug-in can run for failed builds,
* <code>false</code> otherwise
*/
public boolean getCanRunOnFailed() {
return canRunOnFailed;
}
/**
* Returns whether this reporter can continue processing. This default
* implementation returns <code>true</code> if the property
* <code>canRunOnFailed</code> is set or if the build is not aborted or
* failed.
*
* @param result
* build result
* @return <code>true</code> if the build can continue
*/
protected boolean canContinue(final Result result) {
if (canRunOnFailed) {
return result != Result.ABORTED;
}
else {
return result != Result.ABORTED && result != Result.FAILURE;
}
}
/**
* Copies all files with annotations from the workspace to the build folder.
*
* @param logger
* logger to log any problems
* @param buildRoot
* directory to store the copied files in
* @param annotations
* annotations determining the actual files to copy
* @throws IOException
* if the files could not be written
* @throws FileNotFoundException
* if the files could not be written
* @throws InterruptedException
* if the user cancels the processing
*/
private void copyFilesWithAnnotationsToBuildFolder(final PluginLogger logger, final FilePath buildRoot, final Collection<FileAnnotation> annotations) throws IOException,
FileNotFoundException, InterruptedException {
FilePath directory = new FilePath(buildRoot, AbstractAnnotation.WORKSPACE_FILES);
if (!directory.exists()) {
directory.mkdirs();
}
AnnotationContainer container = new DefaultAnnotationContainer(annotations);
for (WorkspaceFile file : container.getFiles()) {
FilePath masterFile = new FilePath(directory, file.getTempName());
if (!masterFile.exists()) {
try {
new FilePath((Channel)null, file.getName()).copyTo(masterFile);
}
catch (IOException exception) {
String message = "Can't copy source file: source=" + file.getName() + ", destination=" + masterFile.getName();
logger.log(message);
logger.printStackTrace(exception);
}
}
}
}
/**
* Determines whether this plug-in will accept the specified goal. The
* {@link #postExecute(MavenBuildProxy, MavenProject, MojoInfo,
* BuildListener, Throwable)} will only by invoked if the plug-in returns
* <code>true</code>.
*
* @param goal the maven goal
* @return <code>true</code> if the plug-in accepts this goal
*/
protected abstract boolean acceptGoal(final String goal);
/**
* Performs the publishing of the results of this plug-in.
*
* @param build
* the build proxy (on the slave)
* @param pom
* the pom of the module
* @param mojo
* the executed mojo
* @param logger
* the logger to report the progress to
* @return the java project containing the found annotations
* @throws InterruptedException
* If the build is interrupted by the user (in an attempt to
* abort the build.) Normally the {@link BuildStep}
* implementations may simply forward the exception it got from
* its lower-level functions.
* @throws IOException
* If the implementation wants to abort the processing when an
* {@link IOException} happens, it can simply propagate the
* exception to the caller. This will cause the build to fail,
* with the default error message. Implementations are
* encouraged to catch {@link IOException} on its own to provide
* a better error message, if it can do so, so that users have
* better understanding on why it failed.
*/
protected abstract ParserResult perform(MavenBuildProxy build, MavenProject pom, MojoInfo mojo,
PluginLogger logger) throws InterruptedException, IOException;
/**
* Creates a new {@link BuildResult} instance.
*
* @param build
* the build (on the master)
* @param project
* the created project
* @return the created result
*/
protected abstract T createResult(final MavenBuild build, ParserResult project);
/**
* Creates a new {@link BuildResult} instance.
*
* @param build
* the build (on the master)
* @param result
* the build result
* @return the created result
*/
protected abstract MavenAggregatedReport createMavenAggregatedReport(final MavenBuild build, T result);
/**
* Returns the default encoding derived from the maven pom file.
*
* @return the default encoding
*/
protected String getDefaultEncoding() {
return defaultEncoding;
}
/**
* Returns whether we already have a result for this build.
*
* @param build
* the current build.
* @return <code>true</code> if we already have a task result action.
* @throws IOException
* in case of an IO error
* @throws InterruptedException
* if the call has been interrupted
*/
@SuppressWarnings("serial")
private Boolean hasResultAction(final MavenBuildProxy build) throws IOException, InterruptedException {
return build.execute(new BuildCallable<Boolean, IOException>() {
public Boolean call(final MavenBuild mavenBuild) throws IOException, InterruptedException {
return mavenBuild.getAction(getResultActionClass()) != null;
}
});
}
/**
* Returns the type of the result action.
*
* @return the type of the result action
*/
protected abstract Class<? extends MavenResultAction<T>> getResultActionClass();
/**
* Returns the path to the target folder.
*
* @param pom the maven pom
* @return the path to the target folder
*/
protected FilePath getTargetPath(final MavenProject pom) {
return new FilePath((VirtualChannel)null, pom.getBuild().getDirectory());
}
/**
* Returns the healthy threshold, i.e. when health is reported as 100%.
*
* @return the 100% healthiness
*/
public String getHealthy() {
return healthy;
}
/**
* Returns the unhealthy threshold, i.e. when health is reported as 0%.
*
* @return the 0% unhealthiness
*/
public String getUnHealthy() {
return unHealthy;
}
/** {@inheritDoc} */
public Priority getMinimumPriority() {
return Priority.valueOf(StringUtils.upperCase(getThresholdLimit()));
}
/**
* Returns the threshold limit.
*
* @return the threshold limit
*/
public String getThresholdLimit() {
return thresholdLimit;
}
/**
* Returns the name of the module.
*
* @param pom
* the pom
* @return the name of the module
*/
protected String getModuleName(final MavenProject pom) {
return StringUtils.defaultString(pom.getName(), pom.getArtifactId());
}
/**
* Gets the build result from the master.
*/
private static final class BuildResultCallable implements BuildCallable<Result, IOException> {
/** Unique ID. */
private static final long serialVersionUID = -270795641776014760L;
/** {@inheritDoc} */
public Result call(final MavenBuild mavenBuild) throws IOException, InterruptedException {
return mavenBuild.getResult();
}
}
/** Backward compatibility. @deprecated */
@SuppressWarnings("unused")
@Deprecated
private transient boolean thresholdEnabled;
/** Backward compatibility. @deprecated */
@SuppressWarnings("unused")
@Deprecated
private transient int minimumAnnotations;
/** Backward compatibility. @deprecated */
@SuppressWarnings("unused")
@Deprecated
private transient int healthyAnnotations;
/** Backward compatibility. @deprecated */
@SuppressWarnings("unused")
@Deprecated
private transient int unHealthyAnnotations;
/** Backward compatibility. @deprecated */
@SuppressWarnings("unused")
@Deprecated
private transient boolean healthyReportEnabled;
/** Backward compatibility. @deprecated */
@SuppressWarnings("unused")
@Deprecated
private transient String height;
/** Backward compatibility. @deprecated */
@Deprecated
private transient String threshold;
/** Backward compatibility. @deprecated */
@Deprecated
private transient String failureThreshold;
/** Backward compatibility. @deprecated */
@Deprecated
private transient String newFailureThreshold;
/** Backward compatibility. @deprecated */
@Deprecated
private transient String newThreshold;
}
| true | true | public final boolean postExecute(final MavenBuildProxy build, final MavenProject pom, final MojoInfo mojo,
final BuildListener listener, final Throwable error) throws InterruptedException, IOException {
PluginLogger logger = new PluginLogger(listener.getLogger(), pluginName);
if (!acceptGoal(mojo.getGoal())) {
return true;
}
Result currentResult = getCurrentResult(build);
if (!canContinue(currentResult)) {
logger.log("Skipping reporter since build result is " + currentResult);
return true;
}
if (hasResultAction(build)) {
logger.log("Skipping maven reporter: there is already a result available.");
return true;
}
final ParserResult result;
try {
result = perform(build, pom, mojo, logger);
if (result.getModules().isEmpty() && result.getNumberOfAnnotations() == 0) {
logger.log("No report found for mojo " + mojo.getGoal());
return true;
}
}
catch (InterruptedException exception) {
logger.log(exception.getMessage());
return false;
}
logger.logLines(result.getLogMessages());
defaultEncoding = pom.getProperties().getProperty("project.build.sourceEncoding");
if (defaultEncoding == null) {
logger.log(Messages.Reporter_Error_NoEncoding(Charset.defaultCharset().displayName()));
result.addErrorMessage(pom.getName(), Messages.Reporter_Error_NoEncoding(Charset.defaultCharset().displayName()));
}
String resultLog = build.execute(new BuildCallable<String, IOException>() {
public String call(final MavenBuild mavenBuild) throws IOException, InterruptedException {
return registerResults(result, mavenBuild);
}
});
logger.logLines(resultLog);
copyFilesWithAnnotationsToBuildFolder(logger, build.getRootDir(), result.getAnnotations());
return true;
}
| public final boolean postExecute(final MavenBuildProxy build, final MavenProject pom, final MojoInfo mojo,
final BuildListener listener, final Throwable error) throws InterruptedException, IOException {
PluginLogger logger = new PluginLogger(listener.getLogger(), pluginName);
if (!acceptGoal(mojo.getGoal())) {
return true;
}
Result currentResult = getCurrentResult(build);
if (!canContinue(currentResult)) {
logger.log("Skipping reporter since build result is " + currentResult);
return true;
}
if (hasResultAction(build)) {
return true;
}
final ParserResult result;
try {
result = perform(build, pom, mojo, logger);
if (result.getModules().isEmpty() && result.getNumberOfAnnotations() == 0) {
logger.log("No report found for mojo " + mojo.getGoal());
return true;
}
}
catch (InterruptedException exception) {
logger.log(exception.getMessage());
return false;
}
logger.logLines(result.getLogMessages());
defaultEncoding = pom.getProperties().getProperty("project.build.sourceEncoding");
if (defaultEncoding == null) {
logger.log(Messages.Reporter_Error_NoEncoding(Charset.defaultCharset().displayName()));
result.addErrorMessage(pom.getName(), Messages.Reporter_Error_NoEncoding(Charset.defaultCharset().displayName()));
}
String resultLog = build.execute(new BuildCallable<String, IOException>() {
public String call(final MavenBuild mavenBuild) throws IOException, InterruptedException {
return registerResults(result, mavenBuild);
}
});
logger.logLines(resultLog);
copyFilesWithAnnotationsToBuildFolder(logger, build.getRootDir(), result.getAnnotations());
return true;
}
|
diff --git a/project/src/com/jeffboody/GearsES2eclair/GearsES2eclairAbout.java b/project/src/com/jeffboody/GearsES2eclair/GearsES2eclairAbout.java
index a1b2f42..c608842 100644
--- a/project/src/com/jeffboody/GearsES2eclair/GearsES2eclairAbout.java
+++ b/project/src/com/jeffboody/GearsES2eclair/GearsES2eclairAbout.java
@@ -1,183 +1,186 @@
/*
* Copyright (c) 2009-2011 Jeff Boody
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
package com.jeffboody.GearsES2eclair;
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;
public class GearsES2eclairAbout extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
WebView wv = new WebView(this);
String text = "<html><body bgcolor=\"#37547c\" text=\"#FFFFFF\" link=\"#a08f6b\" vlink=\"#a08f6b\">" +
"<h2>About Gears for Android(TM)</h2>" +
"<p>" +
" Gears for Android(TM) is a heavily modified port of the infamous \"gears\" demo to Android." +
"</p>" +
"<p>" +
" The Gears demo is an open source project intended to help developers learn how to create " +
" OpenGL ES programs on Android. The Gears demo was originally written by Brian Paul as " +
" part of the Mesa3D project. My implementation includes variations for Java/OpenGL ES 1.x, " +
" Java/C/OpenGL ES 1.x and Java/C/OpenGL ES 2.0. I have also added several features not " +
" found in the original implementation including touch screen support, VBOs and an " +
" on-screen FPS counter." +
"</p>" +
"<p>" +
" The FPS (frames-per-second) counter is often used as a benchmark metric for graphics " +
" programs. On Android the frame rate is limited by v-sync (typically 60 FPS) which is " +
" the fastest rate that a display can refresh the screen. Since Gears is capable of " +
" rendering much faster than v-sync on most devices it provides limited benchmarking " +
" value." +
"</p>" +
"<h2>Source Code</h2>" +
"<p>" +
" Source code is available at the <a href=\"http://www.jeffboody.net/gears4android.php\">Gears for Android(TM)</a> website" +
"</p>" +
"<h2>Release Notes</h2>" +
"<p>20110501" +
" <ul>" +
" <li>For Android 2.0 (eclair)</li>" +
" <li>Fix lighting bug observed when zooming</li>" +
" <li>Replaced simclist library</li>" +
" <li>Compile in thumb mode</li>" +
" <li>Simplified a3d GL wrapper</li>" +
" <li>Updated Gears icon (again)</li>" +
" <li>Uploaded source to github</li>" +
" </ul>" +
+ "</p>" +
"<p>20101218" +
" <ul>" +
" <li>For Android 2.0 (eclair)</li>" +
" <li>Workaround for rendering corruption on Nexus S and Galaxy S</li>" +
" <li>Updated Gears icon</li>" +
" </ul>" +
+ "</p>" +
"<p>20101113" +
" <ul>" +
" <li>For Android 2.0 (eclair)</li>" +
" <li>Reimplemented in OpenGL ES 2.0</li>" +
" <li>Based on 20100905 release</li>" +
" </ul>" +
+ "</p>" +
"<p>20100905" +
" <ul>" +
" <li>For Android 2.0 (eclair)</li>" +
" <li>Reimplemented in C with NDK</li>" +
" <li>Included better FPS counter font</li>" +
" <li>Added GLES performance analysis logging</li>" +
" </ul>" +
"</p>" +
"<p>20100211" +
" <ul>" +
" <li>For Android 2.0 (eclair)</li>" +
" <li>Multitouch zoom support</li>" +
" <li>Fullscreen support</li>" +
" <li>Faster orientation changes</li>" +
" <li>Render gears with VBOs</li>" +
" <li>Disable blending when not required</li>" +
" </ul>" +
"</p>" +
"<p>20091229" +
" <ul>" +
" <li>For Android 1.6 or Android 2.0 (donut or eclair)</li>" +
" <li>Fixed EGL config selection for Droid</li>" +
" <li>I would like to thank David Van de Ven for help debugging/testing on the Droid</li>" +
" </ul>" +
"</p>" +
"<p>20091010" +
" <ul>" +
" <li>For Android 1.6 (donut)</li>" +
" <li>Touchscreen performance patched by Greg Copeland with additional suggestions by Alexander Mikhnin</li>" +
" <li>Rewrote texture loader</li>" +
" <li>Changed data passed into gl*Pointer functions to be allocateDirect</li>" +
" <li>Changed various data to be nativeOrder</li>" +
" <li>Added directions for running Traceview</li>" +
" </ul>" +
"</p>" +
"<p>20090621" +
" <ul>" +
" <li>For Android 1.5 (cupcake)</li>" +
" <li>Fixed performance bug (allocating variables on heap causing gc to run)</li>" +
" </ul>" +
"</p>" +
"<p>20090620" +
" <ul>" +
" <li>For Android 1.5 (cupcake)</li>" +
" <li>Added on-screen fps counter at 1 second interval</li>" +
" <li>Removed logcat fps counter</li>" +
" <li>Fixed a bug handling EGL_CONTEXT_LOST event</li>" +
" <li>Updated About screen to use WebView</li>" +
" <li>Updated Gears icon</li>" +
" </ul>" +
"</p>" +
"<p>20090502" +
" <ul>" +
" <li>For Android 1.1 (pre-cupcake)</li>" +
" <li>3D hardware accelerated rendering is implemented using OpenGL ES 1.0</li>" +
" <li>Demo may be run on either an Android device such as the T-Mobile G1 or on the emulator that is included with the Android SDK</li>" +
" <li>Available from the Android market</li>" +
" <li>Touchscreen may be used to rotate camera</li>" +
" <li>fps is written to logcat</li>" +
" <li>Achieves 60 fps on the T-Mobile G1 (performance is limited by display, not GPU)</li>" +
" <li>Performance may drop while using the touchscreen (known problem with the Android SDK)</li>" +
" </ul>" +
"</p>" +
"<h2>Feedback</h2>" +
"<p>" +
" Send questions or comments to Jeff Boody at [email protected]" +
"</p>" +
"<h2>License</h2>" +
"<p>" +
" Copyright (c) 2009-2011 Jeff Boody<br/>" +
" Gears for Android(TM) is a heavily modified port of the infamous \"gears\" demo to " +
" Android/Java/GLES 1.0. As such, it is a derived work subject to the license " +
" requirements (below) of the original work.<br/>" +
" <br/>" +
" Copyright (c) 1999-2001 Brian Paul All Rights Reserved.<br/>" +
" <br/>" +
" Permission is hereby granted, free of charge, to any person obtaining a " +
" copy of this software and associated documentation files (the \"Software\"), " +
" to deal in the Software without restriction, including without limitation " +
" the rights to use, copy, modify, merge, publish, distribute, sublicense, " +
" and/or sell copies of the Software, and to permit persons to whom the " +
" Software is furnished to do so, subject to the following conditions:<br/>" +
" <br/>" +
" The above copyright notice and this permission notice shall be included " +
" in all copies or substantial portions of the Software.<br/>" +
" <br/>" +
" THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR " +
" IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, " +
" FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE " +
" AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER " +
" LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, " +
" OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN " +
" THE SOFTWARE." +
"</p>" +
"</body></html>";
wv.loadData(text, "text/html", "utf-8");
setContentView(wv);
}
}
| false | true | public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
WebView wv = new WebView(this);
String text = "<html><body bgcolor=\"#37547c\" text=\"#FFFFFF\" link=\"#a08f6b\" vlink=\"#a08f6b\">" +
"<h2>About Gears for Android(TM)</h2>" +
"<p>" +
" Gears for Android(TM) is a heavily modified port of the infamous \"gears\" demo to Android." +
"</p>" +
"<p>" +
" The Gears demo is an open source project intended to help developers learn how to create " +
" OpenGL ES programs on Android. The Gears demo was originally written by Brian Paul as " +
" part of the Mesa3D project. My implementation includes variations for Java/OpenGL ES 1.x, " +
" Java/C/OpenGL ES 1.x and Java/C/OpenGL ES 2.0. I have also added several features not " +
" found in the original implementation including touch screen support, VBOs and an " +
" on-screen FPS counter." +
"</p>" +
"<p>" +
" The FPS (frames-per-second) counter is often used as a benchmark metric for graphics " +
" programs. On Android the frame rate is limited by v-sync (typically 60 FPS) which is " +
" the fastest rate that a display can refresh the screen. Since Gears is capable of " +
" rendering much faster than v-sync on most devices it provides limited benchmarking " +
" value." +
"</p>" +
"<h2>Source Code</h2>" +
"<p>" +
" Source code is available at the <a href=\"http://www.jeffboody.net/gears4android.php\">Gears for Android(TM)</a> website" +
"</p>" +
"<h2>Release Notes</h2>" +
"<p>20110501" +
" <ul>" +
" <li>For Android 2.0 (eclair)</li>" +
" <li>Fix lighting bug observed when zooming</li>" +
" <li>Replaced simclist library</li>" +
" <li>Compile in thumb mode</li>" +
" <li>Simplified a3d GL wrapper</li>" +
" <li>Updated Gears icon (again)</li>" +
" <li>Uploaded source to github</li>" +
" </ul>" +
"<p>20101218" +
" <ul>" +
" <li>For Android 2.0 (eclair)</li>" +
" <li>Workaround for rendering corruption on Nexus S and Galaxy S</li>" +
" <li>Updated Gears icon</li>" +
" </ul>" +
"<p>20101113" +
" <ul>" +
" <li>For Android 2.0 (eclair)</li>" +
" <li>Reimplemented in OpenGL ES 2.0</li>" +
" <li>Based on 20100905 release</li>" +
" </ul>" +
"<p>20100905" +
" <ul>" +
" <li>For Android 2.0 (eclair)</li>" +
" <li>Reimplemented in C with NDK</li>" +
" <li>Included better FPS counter font</li>" +
" <li>Added GLES performance analysis logging</li>" +
" </ul>" +
"</p>" +
"<p>20100211" +
" <ul>" +
" <li>For Android 2.0 (eclair)</li>" +
" <li>Multitouch zoom support</li>" +
" <li>Fullscreen support</li>" +
" <li>Faster orientation changes</li>" +
" <li>Render gears with VBOs</li>" +
" <li>Disable blending when not required</li>" +
" </ul>" +
"</p>" +
"<p>20091229" +
" <ul>" +
" <li>For Android 1.6 or Android 2.0 (donut or eclair)</li>" +
" <li>Fixed EGL config selection for Droid</li>" +
" <li>I would like to thank David Van de Ven for help debugging/testing on the Droid</li>" +
" </ul>" +
"</p>" +
"<p>20091010" +
" <ul>" +
" <li>For Android 1.6 (donut)</li>" +
" <li>Touchscreen performance patched by Greg Copeland with additional suggestions by Alexander Mikhnin</li>" +
" <li>Rewrote texture loader</li>" +
" <li>Changed data passed into gl*Pointer functions to be allocateDirect</li>" +
" <li>Changed various data to be nativeOrder</li>" +
" <li>Added directions for running Traceview</li>" +
" </ul>" +
"</p>" +
"<p>20090621" +
" <ul>" +
" <li>For Android 1.5 (cupcake)</li>" +
" <li>Fixed performance bug (allocating variables on heap causing gc to run)</li>" +
" </ul>" +
"</p>" +
"<p>20090620" +
" <ul>" +
" <li>For Android 1.5 (cupcake)</li>" +
" <li>Added on-screen fps counter at 1 second interval</li>" +
" <li>Removed logcat fps counter</li>" +
" <li>Fixed a bug handling EGL_CONTEXT_LOST event</li>" +
" <li>Updated About screen to use WebView</li>" +
" <li>Updated Gears icon</li>" +
" </ul>" +
"</p>" +
"<p>20090502" +
" <ul>" +
" <li>For Android 1.1 (pre-cupcake)</li>" +
" <li>3D hardware accelerated rendering is implemented using OpenGL ES 1.0</li>" +
" <li>Demo may be run on either an Android device such as the T-Mobile G1 or on the emulator that is included with the Android SDK</li>" +
" <li>Available from the Android market</li>" +
" <li>Touchscreen may be used to rotate camera</li>" +
" <li>fps is written to logcat</li>" +
" <li>Achieves 60 fps on the T-Mobile G1 (performance is limited by display, not GPU)</li>" +
" <li>Performance may drop while using the touchscreen (known problem with the Android SDK)</li>" +
" </ul>" +
"</p>" +
"<h2>Feedback</h2>" +
"<p>" +
" Send questions or comments to Jeff Boody at [email protected]" +
"</p>" +
"<h2>License</h2>" +
"<p>" +
" Copyright (c) 2009-2011 Jeff Boody<br/>" +
" Gears for Android(TM) is a heavily modified port of the infamous \"gears\" demo to " +
" Android/Java/GLES 1.0. As such, it is a derived work subject to the license " +
" requirements (below) of the original work.<br/>" +
" <br/>" +
" Copyright (c) 1999-2001 Brian Paul All Rights Reserved.<br/>" +
" <br/>" +
" Permission is hereby granted, free of charge, to any person obtaining a " +
" copy of this software and associated documentation files (the \"Software\"), " +
" to deal in the Software without restriction, including without limitation " +
" the rights to use, copy, modify, merge, publish, distribute, sublicense, " +
" and/or sell copies of the Software, and to permit persons to whom the " +
" Software is furnished to do so, subject to the following conditions:<br/>" +
" <br/>" +
" The above copyright notice and this permission notice shall be included " +
" in all copies or substantial portions of the Software.<br/>" +
" <br/>" +
" THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR " +
" IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, " +
" FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE " +
" AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER " +
" LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, " +
" OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN " +
" THE SOFTWARE." +
"</p>" +
"</body></html>";
wv.loadData(text, "text/html", "utf-8");
setContentView(wv);
}
| public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
WebView wv = new WebView(this);
String text = "<html><body bgcolor=\"#37547c\" text=\"#FFFFFF\" link=\"#a08f6b\" vlink=\"#a08f6b\">" +
"<h2>About Gears for Android(TM)</h2>" +
"<p>" +
" Gears for Android(TM) is a heavily modified port of the infamous \"gears\" demo to Android." +
"</p>" +
"<p>" +
" The Gears demo is an open source project intended to help developers learn how to create " +
" OpenGL ES programs on Android. The Gears demo was originally written by Brian Paul as " +
" part of the Mesa3D project. My implementation includes variations for Java/OpenGL ES 1.x, " +
" Java/C/OpenGL ES 1.x and Java/C/OpenGL ES 2.0. I have also added several features not " +
" found in the original implementation including touch screen support, VBOs and an " +
" on-screen FPS counter." +
"</p>" +
"<p>" +
" The FPS (frames-per-second) counter is often used as a benchmark metric for graphics " +
" programs. On Android the frame rate is limited by v-sync (typically 60 FPS) which is " +
" the fastest rate that a display can refresh the screen. Since Gears is capable of " +
" rendering much faster than v-sync on most devices it provides limited benchmarking " +
" value." +
"</p>" +
"<h2>Source Code</h2>" +
"<p>" +
" Source code is available at the <a href=\"http://www.jeffboody.net/gears4android.php\">Gears for Android(TM)</a> website" +
"</p>" +
"<h2>Release Notes</h2>" +
"<p>20110501" +
" <ul>" +
" <li>For Android 2.0 (eclair)</li>" +
" <li>Fix lighting bug observed when zooming</li>" +
" <li>Replaced simclist library</li>" +
" <li>Compile in thumb mode</li>" +
" <li>Simplified a3d GL wrapper</li>" +
" <li>Updated Gears icon (again)</li>" +
" <li>Uploaded source to github</li>" +
" </ul>" +
"</p>" +
"<p>20101218" +
" <ul>" +
" <li>For Android 2.0 (eclair)</li>" +
" <li>Workaround for rendering corruption on Nexus S and Galaxy S</li>" +
" <li>Updated Gears icon</li>" +
" </ul>" +
"</p>" +
"<p>20101113" +
" <ul>" +
" <li>For Android 2.0 (eclair)</li>" +
" <li>Reimplemented in OpenGL ES 2.0</li>" +
" <li>Based on 20100905 release</li>" +
" </ul>" +
"</p>" +
"<p>20100905" +
" <ul>" +
" <li>For Android 2.0 (eclair)</li>" +
" <li>Reimplemented in C with NDK</li>" +
" <li>Included better FPS counter font</li>" +
" <li>Added GLES performance analysis logging</li>" +
" </ul>" +
"</p>" +
"<p>20100211" +
" <ul>" +
" <li>For Android 2.0 (eclair)</li>" +
" <li>Multitouch zoom support</li>" +
" <li>Fullscreen support</li>" +
" <li>Faster orientation changes</li>" +
" <li>Render gears with VBOs</li>" +
" <li>Disable blending when not required</li>" +
" </ul>" +
"</p>" +
"<p>20091229" +
" <ul>" +
" <li>For Android 1.6 or Android 2.0 (donut or eclair)</li>" +
" <li>Fixed EGL config selection for Droid</li>" +
" <li>I would like to thank David Van de Ven for help debugging/testing on the Droid</li>" +
" </ul>" +
"</p>" +
"<p>20091010" +
" <ul>" +
" <li>For Android 1.6 (donut)</li>" +
" <li>Touchscreen performance patched by Greg Copeland with additional suggestions by Alexander Mikhnin</li>" +
" <li>Rewrote texture loader</li>" +
" <li>Changed data passed into gl*Pointer functions to be allocateDirect</li>" +
" <li>Changed various data to be nativeOrder</li>" +
" <li>Added directions for running Traceview</li>" +
" </ul>" +
"</p>" +
"<p>20090621" +
" <ul>" +
" <li>For Android 1.5 (cupcake)</li>" +
" <li>Fixed performance bug (allocating variables on heap causing gc to run)</li>" +
" </ul>" +
"</p>" +
"<p>20090620" +
" <ul>" +
" <li>For Android 1.5 (cupcake)</li>" +
" <li>Added on-screen fps counter at 1 second interval</li>" +
" <li>Removed logcat fps counter</li>" +
" <li>Fixed a bug handling EGL_CONTEXT_LOST event</li>" +
" <li>Updated About screen to use WebView</li>" +
" <li>Updated Gears icon</li>" +
" </ul>" +
"</p>" +
"<p>20090502" +
" <ul>" +
" <li>For Android 1.1 (pre-cupcake)</li>" +
" <li>3D hardware accelerated rendering is implemented using OpenGL ES 1.0</li>" +
" <li>Demo may be run on either an Android device such as the T-Mobile G1 or on the emulator that is included with the Android SDK</li>" +
" <li>Available from the Android market</li>" +
" <li>Touchscreen may be used to rotate camera</li>" +
" <li>fps is written to logcat</li>" +
" <li>Achieves 60 fps on the T-Mobile G1 (performance is limited by display, not GPU)</li>" +
" <li>Performance may drop while using the touchscreen (known problem with the Android SDK)</li>" +
" </ul>" +
"</p>" +
"<h2>Feedback</h2>" +
"<p>" +
" Send questions or comments to Jeff Boody at [email protected]" +
"</p>" +
"<h2>License</h2>" +
"<p>" +
" Copyright (c) 2009-2011 Jeff Boody<br/>" +
" Gears for Android(TM) is a heavily modified port of the infamous \"gears\" demo to " +
" Android/Java/GLES 1.0. As such, it is a derived work subject to the license " +
" requirements (below) of the original work.<br/>" +
" <br/>" +
" Copyright (c) 1999-2001 Brian Paul All Rights Reserved.<br/>" +
" <br/>" +
" Permission is hereby granted, free of charge, to any person obtaining a " +
" copy of this software and associated documentation files (the \"Software\"), " +
" to deal in the Software without restriction, including without limitation " +
" the rights to use, copy, modify, merge, publish, distribute, sublicense, " +
" and/or sell copies of the Software, and to permit persons to whom the " +
" Software is furnished to do so, subject to the following conditions:<br/>" +
" <br/>" +
" The above copyright notice and this permission notice shall be included " +
" in all copies or substantial portions of the Software.<br/>" +
" <br/>" +
" THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR " +
" IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, " +
" FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE " +
" AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER " +
" LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, " +
" OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN " +
" THE SOFTWARE." +
"</p>" +
"</body></html>";
wv.loadData(text, "text/html", "utf-8");
setContentView(wv);
}
|
diff --git a/org.caleydo.core/src/org/caleydo/core/data/graph/tree/TreePorter.java b/org.caleydo.core/src/org/caleydo/core/data/graph/tree/TreePorter.java
index 45c5e1260..db5804957 100644
--- a/org.caleydo.core/src/org/caleydo/core/data/graph/tree/TreePorter.java
+++ b/org.caleydo.core/src/org/caleydo/core/data/graph/tree/TreePorter.java
@@ -1,236 +1,236 @@
/*******************************************************************************
* Caleydo - visualization for molecular biology - http://caleydo.org
*
* Copyright(C) 2005, 2012 Graz University of Technology, Marc Streit, Alexander
* Lex, Christian Partl, Johannes Kepler University Linz </p>
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>
*******************************************************************************/
package org.caleydo.core.data.graph.tree;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import org.caleydo.core.data.datadomain.ATableBasedDataDomain;
import org.caleydo.core.id.IDType;
import org.caleydo.core.manager.GeneralManager;
import org.caleydo.core.util.logging.Logger;
import org.eclipse.core.runtime.Status;
import org.jgrapht.DirectedGraph;
import org.jgrapht.graph.DefaultDirectedGraph;
import org.jgrapht.graph.DefaultEdge;
/**
* Class responsible for exporting and importing (clustered) {@link Tree}
*
* @author Bernhard Schlegl
* @author Alexander Lex
*/
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class TreePorter {
private static final long serialVersionUID = 1L;
@XmlElementWrapper(name = "edges")
@XmlElement(name = "edge")
ArrayList<Integer[]> edges = new ArrayList<Integer[]>();
@XmlElementWrapper(name = "nodes")
@XmlElement(name = "node")
Set<ClusterNode> nodeSet;
String leaveIDTypeString;
private ATableBasedDataDomain dataDomain;
@XmlElement
private ESortingStrategy sortingStrategy = ESortingStrategy.DEFAULT;
public void setDataDomain(ATableBasedDataDomain dataDomain) {
this.dataDomain = dataDomain;
}
public ATableBasedDataDomain getDataDomain() {
return dataDomain;
}
/**
* Imports a tree with the aid of {@link JAXBContext}.
*
* @param fileName
* Full file name of the serialized tree
* @return the imported tree
* @throws JAXBException
* in case of a XML-serialization error
*/
public ClusterTree importTree(String fileName, IDType leafIDType)
throws JAXBException, FileNotFoundException {
JAXBContext jaxbContext = null;
TreePorter treePorter = null;
Unmarshaller unmarshaller;
jaxbContext = JAXBContext.newInstance(TreePorter.class);
unmarshaller = jaxbContext.createUnmarshaller();
BufferedReader treeFileReader;
try {
treeFileReader = GeneralManager.get().getResourceLoader()
.getResource(fileName);
} catch (FileNotFoundException fnfe) {
- Logger.log(new Status(Status.INFO, "TreePorter", "No tree available for "
- + fileName));
+// Logger.log(new Status(Status.INFO, "TreePorter", "No tree available for "
+// + fileName));
return null;
}
treePorter = (TreePorter) unmarshaller.unmarshal(treeFileReader);
ClusterTree tree = new ClusterTree(leafIDType, treePorter.nodeSet.size());
// tree.initializeIDTypes(IDType.getIDType(leaveIDTypeString));
ClusterNode rootNode = null;
DirectedGraph<ClusterNode, DefaultEdge> graph = new DefaultDirectedGraph<ClusterNode, DefaultEdge>(
DefaultEdge.class);
tree.setSortingStrategy(treePorter.sortingStrategy);
int size = (int) (treePorter.nodeSet.size() * 1.5);
HashMap<Integer, ClusterNode> hashClusterNr = new HashMap<Integer, ClusterNode>(
size);
// HashMap<String, ClusterNode> hashClusterNodes = new HashMap<String,
// ClusterNode>(size);
HashMap<Integer, ArrayList<Integer>> hashLeafIDToNodeIDs = new HashMap<Integer, ArrayList<Integer>>(
size);
for (ClusterNode node : treePorter.nodeSet) {
graph.addVertex(node);
// hashClusterNodes.put(node.toString(), node);
hashClusterNr.put(node.getID(), node);
if (node.isRootNode())
rootNode = node;
node.setTree(tree);
node.setNode(node);
// take care of hashing leaf ids to node ids
if (node.getLeafID() >= 0) {
if (hashLeafIDToNodeIDs.containsKey(node.getLeafID())) {
ArrayList<Integer> alNodeIDs = hashLeafIDToNodeIDs.get(node
.getLeafID());
alNodeIDs.add(node.getID());
} else {
ArrayList<Integer> alNodeIDs = new ArrayList<Integer>();
alNodeIDs.add(node.getID());
hashLeafIDToNodeIDs.put(node.getLeafID(), alNodeIDs);
}
}
}
for (Integer[] edge : treePorter.edges) {
graph.addEdge(hashClusterNr.get(edge[0]), hashClusterNr.get(edge[1]));
}
tree.setHashMap(hashClusterNr);
tree.setRootNode(rootNode);
tree.setGraph(graph);
tree.hashLeafIDToNodeIDs = hashLeafIDToNodeIDs;
return tree;
}
public ClusterTree importDimensionTree(String fileName) throws JAXBException,
FileNotFoundException {
ClusterTree tree = importTree(fileName, dataDomain.getDimensionIDType());
return tree;
}
/**
* Export function uses {@link JAXBContext} to export a given tree into an
* XML file.
*
* @param fileName
* name of the file where the exported tree should be saved
* @param tree
* the tree wanted to export
* @throws JAXBException
* in case of a XML-serialization error
* @throws IOException
* in case of an error while writing to the stream
*/
public void exportTree(String fileName, Tree<ClusterNode> tree) throws JAXBException,
IOException {
FileWriter writer = new FileWriter(fileName);
try {
exportTree(writer, tree);
writer.close();
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException ex) {
// nothing to do here, assuming the writer is closed
}
writer = null;
}
}
}
/**
* Export function uses {@link JAXBContext} to export a given tree to a
* {@link Writer}
*
* @param writer
* {@link Writer} to write the serialized tree to.
* @param tree
* the tree wanted to export
* @throws JAXBException
* in case of a XML-serialization error
* @throws IOException
* in case of an error while writing to the stream
*/
public void exportTree(Writer writer, Tree<ClusterNode> tree) throws JAXBException,
IOException {
Set<DefaultEdge> edgeSet = tree.graph.edgeSet();
for (DefaultEdge edge : edgeSet) {
Integer temp[] = new Integer[2];
temp[0] = tree.graph.getEdgeSource(edge).getID();
temp[1] = tree.graph.getEdgeTarget(edge).getID();
edges.add(temp);
}
nodeSet = tree.graph.vertexSet();
leaveIDTypeString = tree.getLeaveIDType().getTypeName();
sortingStrategy = tree.getSortingStrategy();
JAXBContext jaxbContext = JAXBContext.newInstance(TreePorter.class,
DefaultEdge.class);
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.marshal(this, writer);
}
}
| true | true | public ClusterTree importTree(String fileName, IDType leafIDType)
throws JAXBException, FileNotFoundException {
JAXBContext jaxbContext = null;
TreePorter treePorter = null;
Unmarshaller unmarshaller;
jaxbContext = JAXBContext.newInstance(TreePorter.class);
unmarshaller = jaxbContext.createUnmarshaller();
BufferedReader treeFileReader;
try {
treeFileReader = GeneralManager.get().getResourceLoader()
.getResource(fileName);
} catch (FileNotFoundException fnfe) {
Logger.log(new Status(Status.INFO, "TreePorter", "No tree available for "
+ fileName));
return null;
}
treePorter = (TreePorter) unmarshaller.unmarshal(treeFileReader);
ClusterTree tree = new ClusterTree(leafIDType, treePorter.nodeSet.size());
// tree.initializeIDTypes(IDType.getIDType(leaveIDTypeString));
ClusterNode rootNode = null;
DirectedGraph<ClusterNode, DefaultEdge> graph = new DefaultDirectedGraph<ClusterNode, DefaultEdge>(
DefaultEdge.class);
tree.setSortingStrategy(treePorter.sortingStrategy);
int size = (int) (treePorter.nodeSet.size() * 1.5);
HashMap<Integer, ClusterNode> hashClusterNr = new HashMap<Integer, ClusterNode>(
size);
// HashMap<String, ClusterNode> hashClusterNodes = new HashMap<String,
// ClusterNode>(size);
HashMap<Integer, ArrayList<Integer>> hashLeafIDToNodeIDs = new HashMap<Integer, ArrayList<Integer>>(
size);
for (ClusterNode node : treePorter.nodeSet) {
graph.addVertex(node);
// hashClusterNodes.put(node.toString(), node);
hashClusterNr.put(node.getID(), node);
if (node.isRootNode())
rootNode = node;
node.setTree(tree);
node.setNode(node);
// take care of hashing leaf ids to node ids
if (node.getLeafID() >= 0) {
if (hashLeafIDToNodeIDs.containsKey(node.getLeafID())) {
ArrayList<Integer> alNodeIDs = hashLeafIDToNodeIDs.get(node
.getLeafID());
alNodeIDs.add(node.getID());
} else {
ArrayList<Integer> alNodeIDs = new ArrayList<Integer>();
alNodeIDs.add(node.getID());
hashLeafIDToNodeIDs.put(node.getLeafID(), alNodeIDs);
}
}
}
for (Integer[] edge : treePorter.edges) {
graph.addEdge(hashClusterNr.get(edge[0]), hashClusterNr.get(edge[1]));
}
tree.setHashMap(hashClusterNr);
tree.setRootNode(rootNode);
tree.setGraph(graph);
tree.hashLeafIDToNodeIDs = hashLeafIDToNodeIDs;
return tree;
}
| public ClusterTree importTree(String fileName, IDType leafIDType)
throws JAXBException, FileNotFoundException {
JAXBContext jaxbContext = null;
TreePorter treePorter = null;
Unmarshaller unmarshaller;
jaxbContext = JAXBContext.newInstance(TreePorter.class);
unmarshaller = jaxbContext.createUnmarshaller();
BufferedReader treeFileReader;
try {
treeFileReader = GeneralManager.get().getResourceLoader()
.getResource(fileName);
} catch (FileNotFoundException fnfe) {
// Logger.log(new Status(Status.INFO, "TreePorter", "No tree available for "
// + fileName));
return null;
}
treePorter = (TreePorter) unmarshaller.unmarshal(treeFileReader);
ClusterTree tree = new ClusterTree(leafIDType, treePorter.nodeSet.size());
// tree.initializeIDTypes(IDType.getIDType(leaveIDTypeString));
ClusterNode rootNode = null;
DirectedGraph<ClusterNode, DefaultEdge> graph = new DefaultDirectedGraph<ClusterNode, DefaultEdge>(
DefaultEdge.class);
tree.setSortingStrategy(treePorter.sortingStrategy);
int size = (int) (treePorter.nodeSet.size() * 1.5);
HashMap<Integer, ClusterNode> hashClusterNr = new HashMap<Integer, ClusterNode>(
size);
// HashMap<String, ClusterNode> hashClusterNodes = new HashMap<String,
// ClusterNode>(size);
HashMap<Integer, ArrayList<Integer>> hashLeafIDToNodeIDs = new HashMap<Integer, ArrayList<Integer>>(
size);
for (ClusterNode node : treePorter.nodeSet) {
graph.addVertex(node);
// hashClusterNodes.put(node.toString(), node);
hashClusterNr.put(node.getID(), node);
if (node.isRootNode())
rootNode = node;
node.setTree(tree);
node.setNode(node);
// take care of hashing leaf ids to node ids
if (node.getLeafID() >= 0) {
if (hashLeafIDToNodeIDs.containsKey(node.getLeafID())) {
ArrayList<Integer> alNodeIDs = hashLeafIDToNodeIDs.get(node
.getLeafID());
alNodeIDs.add(node.getID());
} else {
ArrayList<Integer> alNodeIDs = new ArrayList<Integer>();
alNodeIDs.add(node.getID());
hashLeafIDToNodeIDs.put(node.getLeafID(), alNodeIDs);
}
}
}
for (Integer[] edge : treePorter.edges) {
graph.addEdge(hashClusterNr.get(edge[0]), hashClusterNr.get(edge[1]));
}
tree.setHashMap(hashClusterNr);
tree.setRootNode(rootNode);
tree.setGraph(graph);
tree.hashLeafIDToNodeIDs = hashLeafIDToNodeIDs;
return tree;
}
|
diff --git a/src/com/owncloud/android/operations/DownloadFileOperation.java b/src/com/owncloud/android/operations/DownloadFileOperation.java
index 24990a2d3..04011c102 100644
--- a/src/com/owncloud/android/operations/DownloadFileOperation.java
+++ b/src/com/owncloud/android/operations/DownloadFileOperation.java
@@ -1,170 +1,171 @@
/* ownCloud Android client application
* Copyright (C) 2012-2013 ownCloud Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.owncloud.android.operations;
import java.io.File;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import com.owncloud.android.datamodel.OCFile;
import com.owncloud.android.lib.network.OnDatatransferProgressListener;
import com.owncloud.android.lib.network.OwnCloudClient;
import com.owncloud.android.lib.operations.common.RemoteOperation;
import com.owncloud.android.lib.operations.common.RemoteOperationResult;
import com.owncloud.android.lib.operations.remote.DownloadRemoteFileOperation;
import com.owncloud.android.utils.FileStorageUtils;
import com.owncloud.android.utils.Log_OC;
import android.accounts.Account;
import android.webkit.MimeTypeMap;
/**
* Remote mDownloadOperation performing the download of a file to an ownCloud server
*
* @author David A. Velasco
* @author masensio
*/
public class DownloadFileOperation extends RemoteOperation {
private static final String TAG = DownloadFileOperation.class.getSimpleName();
private Account mAccount;
private OCFile mFile;
private Set<OnDatatransferProgressListener> mDataTransferListeners = new HashSet<OnDatatransferProgressListener>();
private long mModificationTimestamp = 0;
private DownloadRemoteFileOperation mDownloadOperation;
public DownloadFileOperation(Account account, OCFile file) {
if (account == null)
throw new IllegalArgumentException("Illegal null account in DownloadFileOperation creation");
if (file == null)
throw new IllegalArgumentException("Illegal null file in DownloadFileOperation creation");
mAccount = account;
mFile = file;
}
public Account getAccount() {
return mAccount;
}
public OCFile getFile() {
return mFile;
}
public String getSavePath() {
String path = mFile.getStoragePath(); // re-downloads should be done over the original file
if (path != null && path.length() > 0) {
return path;
}
return FileStorageUtils.getDefaultSavePathFor(mAccount.name, mFile);
}
public String getTmpPath() {
return FileStorageUtils.getTemporalPath(mAccount.name) + mFile.getRemotePath();
}
public String getTmpFolder() {
return FileStorageUtils.getTemporalPath(mAccount.name);
}
public String getRemotePath() {
return mFile.getRemotePath();
}
public String getMimeType() {
String mimeType = mFile.getMimetype();
if (mimeType == null || mimeType.length() <= 0) {
try {
mimeType = MimeTypeMap.getSingleton()
.getMimeTypeFromExtension(
mFile.getRemotePath().substring(mFile.getRemotePath().lastIndexOf('.') + 1));
} catch (IndexOutOfBoundsException e) {
Log_OC.e(TAG, "Trying to find out MIME type of a file without extension: " + mFile.getRemotePath());
}
}
if (mimeType == null) {
mimeType = "application/octet-stream";
}
return mimeType;
}
public long getSize() {
return mFile.getFileLength();
}
public long getModificationTimestamp() {
return (mModificationTimestamp > 0) ? mModificationTimestamp : mFile.getModificationTimestamp();
}
@Override
protected RemoteOperationResult run(OwnCloudClient client) {
RemoteOperationResult result = null;
File newFile = null;
boolean moved = true;
/// download will be performed to a temporal file, then moved to the final location
File tmpFile = new File(getTmpPath());
String tmpFolder = getTmpFolder();
/// perform the download
mDownloadOperation = new DownloadRemoteFileOperation(mFile.getRemotePath(), tmpFolder);
Iterator<OnDatatransferProgressListener> listener = mDataTransferListeners.iterator();
while (listener.hasNext()) {
mDownloadOperation.addDatatransferProgressListener(listener.next());
}
result = mDownloadOperation.execute(client);
if (result.isSuccess()) {
+ mModificationTimestamp = mDownloadOperation.getModificationTimestamp();
newFile = new File(getSavePath());
newFile.getParentFile().mkdirs();
moved = tmpFile.renameTo(newFile);
if (!moved)
result = new RemoteOperationResult(RemoteOperationResult.ResultCode.LOCAL_STORAGE_NOT_MOVED);
}
Log_OC.i(TAG, "Download of " + mFile.getRemotePath() + " to " + getSavePath() + ": " + result.getLogMessage());
return result;
}
public void cancel() {
mDownloadOperation.cancel();
}
public void addDatatransferProgressListener (OnDatatransferProgressListener listener) {
synchronized (mDataTransferListeners) {
mDataTransferListeners.add(listener);
}
}
public void removeDatatransferProgressListener(OnDatatransferProgressListener listener) {
synchronized (mDataTransferListeners) {
mDataTransferListeners.remove(listener);
}
}
}
| true | true | protected RemoteOperationResult run(OwnCloudClient client) {
RemoteOperationResult result = null;
File newFile = null;
boolean moved = true;
/// download will be performed to a temporal file, then moved to the final location
File tmpFile = new File(getTmpPath());
String tmpFolder = getTmpFolder();
/// perform the download
mDownloadOperation = new DownloadRemoteFileOperation(mFile.getRemotePath(), tmpFolder);
Iterator<OnDatatransferProgressListener> listener = mDataTransferListeners.iterator();
while (listener.hasNext()) {
mDownloadOperation.addDatatransferProgressListener(listener.next());
}
result = mDownloadOperation.execute(client);
if (result.isSuccess()) {
newFile = new File(getSavePath());
newFile.getParentFile().mkdirs();
moved = tmpFile.renameTo(newFile);
if (!moved)
result = new RemoteOperationResult(RemoteOperationResult.ResultCode.LOCAL_STORAGE_NOT_MOVED);
}
Log_OC.i(TAG, "Download of " + mFile.getRemotePath() + " to " + getSavePath() + ": " + result.getLogMessage());
return result;
}
| protected RemoteOperationResult run(OwnCloudClient client) {
RemoteOperationResult result = null;
File newFile = null;
boolean moved = true;
/// download will be performed to a temporal file, then moved to the final location
File tmpFile = new File(getTmpPath());
String tmpFolder = getTmpFolder();
/// perform the download
mDownloadOperation = new DownloadRemoteFileOperation(mFile.getRemotePath(), tmpFolder);
Iterator<OnDatatransferProgressListener> listener = mDataTransferListeners.iterator();
while (listener.hasNext()) {
mDownloadOperation.addDatatransferProgressListener(listener.next());
}
result = mDownloadOperation.execute(client);
if (result.isSuccess()) {
mModificationTimestamp = mDownloadOperation.getModificationTimestamp();
newFile = new File(getSavePath());
newFile.getParentFile().mkdirs();
moved = tmpFile.renameTo(newFile);
if (!moved)
result = new RemoteOperationResult(RemoteOperationResult.ResultCode.LOCAL_STORAGE_NOT_MOVED);
}
Log_OC.i(TAG, "Download of " + mFile.getRemotePath() + " to " + getSavePath() + ": " + result.getLogMessage());
return result;
}
|
diff --git a/lib/src/main/java/com/github/fhirschmann/clozegen/lib/util/StringUtils.java b/lib/src/main/java/com/github/fhirschmann/clozegen/lib/util/StringUtils.java
index 2e773b6..387b2ed 100644
--- a/lib/src/main/java/com/github/fhirschmann/clozegen/lib/util/StringUtils.java
+++ b/lib/src/main/java/com/github/fhirschmann/clozegen/lib/util/StringUtils.java
@@ -1,33 +1,33 @@
/*
* Copyright (C) 2012 Fabian Hirschmann <[email protected]>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package com.github.fhirschmann.clozegen.lib.util;
import com.google.common.base.CharMatcher;
import static com.google.common.base.Preconditions.checkNotNull;
/**
*
* @author Fabian Hirschmann <[email protected]>
*/
public class StringUtils {
public static final CharMatcher SENTENCE_DELIMITER_MATCHER = CharMatcher.anyOf("!.?");
- public static final boolean isSentenceDelimiter(String subject) {
+ public static boolean isSentenceDelimiter(final String subject) {
return SENTENCE_DELIMITER_MATCHER.matches(checkNotNull(subject.charAt(0)));
}
}
| true | true | public static final boolean isSentenceDelimiter(String subject) {
return SENTENCE_DELIMITER_MATCHER.matches(checkNotNull(subject.charAt(0)));
}
| public static boolean isSentenceDelimiter(final String subject) {
return SENTENCE_DELIMITER_MATCHER.matches(checkNotNull(subject.charAt(0)));
}
|
diff --git a/ide/plugins/combinatorialtesting/src/main/java/org/overture/ide/plugins/combinatorialtesting/views/ViewContentProvider.java b/ide/plugins/combinatorialtesting/src/main/java/org/overture/ide/plugins/combinatorialtesting/views/ViewContentProvider.java
index 918d0cdd90..61cea16286 100644
--- a/ide/plugins/combinatorialtesting/src/main/java/org/overture/ide/plugins/combinatorialtesting/views/ViewContentProvider.java
+++ b/ide/plugins/combinatorialtesting/src/main/java/org/overture/ide/plugins/combinatorialtesting/views/ViewContentProvider.java
@@ -1,463 +1,464 @@
/*******************************************************************************
* Copyright (c) 2009, 2011 Overture Team and others.
*
* Overture is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Overture is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Overture. If not, see <http://www.gnu.org/licenses/>.
*
* The Overture Tool web-site: http://overturetool.org/
*******************************************************************************/
package org.overture.ide.plugins.combinatorialtesting.views;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.ui.part.ViewPart;
import org.overture.ast.analysis.AnalysisAdaptor;
import org.overture.ast.analysis.AnalysisException;
import org.overture.ast.definitions.ANamedTraceDefinition;
import org.overture.ast.definitions.PDefinition;
import org.overture.ast.definitions.SClassDefinition;
import org.overture.ast.modules.AModuleModules;
import org.overture.ast.node.INode;
import org.overture.ct.utils.TraceHelperNotInitializedException;
import org.overture.ide.core.resources.IVdmProject;
import org.overture.ide.plugins.combinatorialtesting.views.treeView.ITreeNode;
import org.overture.ide.plugins.combinatorialtesting.views.treeView.NotYetReadyTreeNode;
import org.overture.ide.plugins.combinatorialtesting.views.treeView.ProjectTreeNode;
import org.overture.ide.plugins.combinatorialtesting.views.treeView.TraceTreeNode;
import org.overture.ide.plugins.combinatorialtesting.views.treeView.TreeParent;
import org.xml.sax.SAXException;
public class ViewContentProvider implements IStructuredContentProvider,
ITreeContentProvider
{
private TreeParent invisibleRoot;
// Map<String, ITracesHelper> traceHelpers;
// Map<INode, IVdmProject> nodeToProject = new HashMap<INode, IVdmProject>();
ViewPart viewer;
Map<INode, List<TraceTreeNode>> containerNodes = new HashMap<INode, List<TraceTreeNode>>();
public ViewContentProvider(ViewPart p)
{
// this.traceHelpers = trs;
viewer = p;
}
public void inputChanged(Viewer v, Object oldInput, Object newInput)
{
}
public void resetCache(IVdmProject project)
{
Set<INode> containers = TraceAstUtility.getTraceContainers(project);
for (INode iNode : containers)
{
containerNodes.remove(iNode);
}
}
public void dispose()
{
}
public void addChild(ProjectTreeNode project)
{
invisibleRoot.addChild(project);
}
public Object[] getElements(Object parent)
{
if (invisibleRoot == null)
{
initialize();
}
return getChildren(invisibleRoot);
}
public Object getParent(Object child)
{
if (child instanceof ITreeNode)
{
return ((ITreeNode) child).getParent();
}
return null;
}
public Object[] getChildren(Object parent)
{
if (parent instanceof ProjectTreeNode)
{
Set<INode> containers = TraceAstUtility.getTraceContainers(((ProjectTreeNode) parent).project);
return containers.toArray();
}
if (parent instanceof ITreeNode)
{
return ((ITreeNode) parent).getChildren().toArray();
}
if (parent instanceof SClassDefinition
|| parent instanceof AModuleModules)
{
List<TraceTreeNode> children = new Vector<TraceTreeNode>();
List<ANamedTraceDefinition> traceDefs = TraceAstUtility.getTraceDefinitions((INode) parent);
if (containerNodes.containsKey(parent)
&& containerNodes.get(parent).size() == traceDefs.size())
{
return containerNodes.get(parent).toArray();
} else
{
for (ANamedTraceDefinition def : traceDefs)
{
// ITracesHelper tr = traceHelpers.get(TraceAstUtility.getProject(def));
try
{
children.add(new TraceTreeNode(def));
} catch (SAXException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TraceHelperNotInitializedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
containerNodes.put((INode) parent, children);
}
return children.toArray();
}
return new Object[0];
}
public boolean hasChildren(Object parent)
{
if (parent instanceof ProjectTreeNode)
{
HasTraceAnalysis analysis = new HasTraceAnalysis();
for (INode node : ((ProjectTreeNode) parent).project.getModel().getRootElementList())
{
if (analysis.hasTrace(node))
{
return true;
}
}
return false;
} else if (parent instanceof NotYetReadyTreeNode)
{
return false;
}
if (parent instanceof ITreeNode)
{
return ((ITreeNode) parent).hasChildren();
} else if (parent instanceof SClassDefinition
|| parent instanceof AModuleModules)
{
return true;
}
return false;
}
static class HasTraceAnalysis extends AnalysisAdaptor
{
/**
*
*/
private static final long serialVersionUID = 1L;
boolean hasTrace = false;
public boolean hasTrace(INode node)
{
hasTrace = false;
try
{
node.apply(this);
} catch (Throwable e)
{
}
return hasTrace;
}
@Override
public void defaultSClassDefinition(SClassDefinition node)
throws AnalysisException
{
for (PDefinition def : node.getDefinitions())
{
if (def instanceof ANamedTraceDefinition)
{
hasTrace = true;
throw new AnalysisException("stop search");
}
}
}
@Override
public void caseAModuleModules(AModuleModules node)
throws AnalysisException
{
for (PDefinition def : node.getDefs())
{
if (def instanceof ANamedTraceDefinition)
{
hasTrace = true;
throw new AnalysisException("stop search");
}
}
}
// @Override
// public void caseANamedTraceDefinition(ANamedTraceDefinition node)
// {
// hasTrace = true;
// throw new UndeclaredThrowableException(new Exception("stop search"));
// }
}
static class TraceContainerSearch extends AnalysisAdaptor
{
/**
*
*/
private static final long serialVersionUID = 1L;
Set<INode> containers = new HashSet<INode>();
public Set<INode> getTraceContainers(INode node)
{
containers.clear();
try
{
node.apply(this);
} catch (Throwable e)
{
}
return containers;
}
@Override
public void defaultSClassDefinition(SClassDefinition node)
throws AnalysisException
{
for (PDefinition def : node.getDefinitions())
{
if (def instanceof ANamedTraceDefinition)
{
containers.add(node);
throw new AnalysisException("stop search");
}
}
}
@Override
public void caseAModuleModules(AModuleModules node)
throws AnalysisException
{
for (PDefinition def : node.getDefs())
{
if (def instanceof ANamedTraceDefinition)
{
containers.add(node);
throw new AnalysisException("stop search");
}
}
}
// @Override
// public void caseANamedTraceDefinition(ANamedTraceDefinition node)
// {
// INode ancestor = null;
// ancestor = node.getAncestor(SClassDefinition.class);
// if (ancestor != null)
// {
// containers.add(ancestor);
// return;
// }
// ancestor = node.getAncestor(AModuleModules.class);
// if (ancestor != null)
// {
// containers.add(ancestor);
// return;
// }
//
// }
}
static class TraceSearch extends AnalysisAdaptor
{
/**
*
*/
private static final long serialVersionUID = 1L;
List<ANamedTraceDefinition> containers = new Vector<ANamedTraceDefinition>();
public List<ANamedTraceDefinition> getTraces(INode node)
{
containers.clear();
try
{
node.apply(this);
} catch (Throwable e)
{
}
return containers;
}
@Override
public void defaultSClassDefinition(SClassDefinition node)
{
for (PDefinition def : node.getDefinitions())
{
if (def instanceof ANamedTraceDefinition)
{
containers.add((ANamedTraceDefinition) def);
}
}
}
@Override
public void caseAModuleModules(AModuleModules node)
{
for (PDefinition def : node.getDefs())
{
if (def instanceof ANamedTraceDefinition)
{
containers.add((ANamedTraceDefinition) def);
}
}
}
// @Override
// public void caseANamedTraceDefinition(ANamedTraceDefinition node)
// {
// INode ancestor = null;
// ancestor = node.getAncestor(SClassDefinition.class);
// if (ancestor != null)
// {
// containers.add(ancestor);
// return;
// }
// ancestor = node.getAncestor(AModuleModules.class);
// if (ancestor != null)
// {
// containers.add(ancestor);
// return;
// }
//
// }
}
/*
* We will set up a dummy model to initialize tree heararchy. In a real code, you will connect to a real model and
* expose its hierarchy.
*/
private void initialize()
{
invisibleRoot = new TreeParent("");
// IWorkspaceRoot iworkspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
// IProject[] iprojects = iworkspaceRoot.getProjects();
// ArrayList<String> fileNameList = new ArrayList<String>();
ProjectTreeNode projectTreeNode;
for (IVdmProject project : TraceAstUtility.getProjects())
{
HasTraceAnalysis analysis = new HasTraceAnalysis();
for (INode node : project.getModel().getRootElementList())
{
if (analysis.hasTrace(node))
{
projectTreeNode = new ProjectTreeNode(project);
invisibleRoot.addChild(projectTreeNode);
+ break;
}
}
}
// ArrayList<TreeParent> projectTree = new ArrayList<TreeParent>();
// for (int j = 0; j < iprojects.length; j++)
// {
//
// try
// {
// IVdmProject vdmProject = (IVdmProject) iprojects[j].getAdapter(IVdmProject.class);
//
// if (vdmProject != null)
// {
// projectTreeNode = new ProjectTreeNode(vdmProject);
// invisibleRoot.addChild(projectTreeNode);
// }
// // if the project is a overture project
// // if (TracesTreeView.isValidProject(iprojects[j]))
// // {
// //
// // // create project node
// // projectTreeNode = new ProjectTreeNode(iprojects[j]);
// //
// // ITracesHelper tr = traceHelpers.get(iprojects[j].getName());
// // if (tr == null)
// // continue;
// //
// // List<String> classes = tr.getClassNamesWithTraces();
// // boolean isTraceProject = false;
// // for (String className : classes)
// // {
// // if (className != null)
// // {
// // isTraceProject = true;
// // ClassTreeNode classTreeNode = new ClassTreeNode(className);
// //
// // // // add to project and root
// // projectTreeNode.addChild(classTreeNode);
// // }
// // }
// // if (isTraceProject && classes.size() > 0)
// // {
// // invisibleRoot.addChild(projectTreeNode);
// // }
// // }
// } catch (Exception e1)
// {
// System.out.println("Exception: " + e1.getMessage());
// e1.printStackTrace();
// }
// }
}
}
| true | true | private void initialize()
{
invisibleRoot = new TreeParent("");
// IWorkspaceRoot iworkspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
// IProject[] iprojects = iworkspaceRoot.getProjects();
// ArrayList<String> fileNameList = new ArrayList<String>();
ProjectTreeNode projectTreeNode;
for (IVdmProject project : TraceAstUtility.getProjects())
{
HasTraceAnalysis analysis = new HasTraceAnalysis();
for (INode node : project.getModel().getRootElementList())
{
if (analysis.hasTrace(node))
{
projectTreeNode = new ProjectTreeNode(project);
invisibleRoot.addChild(projectTreeNode);
}
}
}
// ArrayList<TreeParent> projectTree = new ArrayList<TreeParent>();
// for (int j = 0; j < iprojects.length; j++)
// {
//
// try
// {
// IVdmProject vdmProject = (IVdmProject) iprojects[j].getAdapter(IVdmProject.class);
//
// if (vdmProject != null)
// {
// projectTreeNode = new ProjectTreeNode(vdmProject);
// invisibleRoot.addChild(projectTreeNode);
// }
// // if the project is a overture project
// // if (TracesTreeView.isValidProject(iprojects[j]))
// // {
// //
// // // create project node
// // projectTreeNode = new ProjectTreeNode(iprojects[j]);
// //
// // ITracesHelper tr = traceHelpers.get(iprojects[j].getName());
// // if (tr == null)
// // continue;
// //
// // List<String> classes = tr.getClassNamesWithTraces();
// // boolean isTraceProject = false;
// // for (String className : classes)
// // {
// // if (className != null)
// // {
// // isTraceProject = true;
// // ClassTreeNode classTreeNode = new ClassTreeNode(className);
// //
// // // // add to project and root
// // projectTreeNode.addChild(classTreeNode);
// // }
// // }
// // if (isTraceProject && classes.size() > 0)
// // {
// // invisibleRoot.addChild(projectTreeNode);
// // }
// // }
// } catch (Exception e1)
// {
// System.out.println("Exception: " + e1.getMessage());
// e1.printStackTrace();
// }
// }
}
| private void initialize()
{
invisibleRoot = new TreeParent("");
// IWorkspaceRoot iworkspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
// IProject[] iprojects = iworkspaceRoot.getProjects();
// ArrayList<String> fileNameList = new ArrayList<String>();
ProjectTreeNode projectTreeNode;
for (IVdmProject project : TraceAstUtility.getProjects())
{
HasTraceAnalysis analysis = new HasTraceAnalysis();
for (INode node : project.getModel().getRootElementList())
{
if (analysis.hasTrace(node))
{
projectTreeNode = new ProjectTreeNode(project);
invisibleRoot.addChild(projectTreeNode);
break;
}
}
}
// ArrayList<TreeParent> projectTree = new ArrayList<TreeParent>();
// for (int j = 0; j < iprojects.length; j++)
// {
//
// try
// {
// IVdmProject vdmProject = (IVdmProject) iprojects[j].getAdapter(IVdmProject.class);
//
// if (vdmProject != null)
// {
// projectTreeNode = new ProjectTreeNode(vdmProject);
// invisibleRoot.addChild(projectTreeNode);
// }
// // if the project is a overture project
// // if (TracesTreeView.isValidProject(iprojects[j]))
// // {
// //
// // // create project node
// // projectTreeNode = new ProjectTreeNode(iprojects[j]);
// //
// // ITracesHelper tr = traceHelpers.get(iprojects[j].getName());
// // if (tr == null)
// // continue;
// //
// // List<String> classes = tr.getClassNamesWithTraces();
// // boolean isTraceProject = false;
// // for (String className : classes)
// // {
// // if (className != null)
// // {
// // isTraceProject = true;
// // ClassTreeNode classTreeNode = new ClassTreeNode(className);
// //
// // // // add to project and root
// // projectTreeNode.addChild(classTreeNode);
// // }
// // }
// // if (isTraceProject && classes.size() > 0)
// // {
// // invisibleRoot.addChild(projectTreeNode);
// // }
// // }
// } catch (Exception e1)
// {
// System.out.println("Exception: " + e1.getMessage());
// e1.printStackTrace();
// }
// }
}
|
diff --git a/piggy/src/string_utils/JsonParser.java b/piggy/src/string_utils/JsonParser.java
index 4ed8fdb..22a186f 100644
--- a/piggy/src/string_utils/JsonParser.java
+++ b/piggy/src/string_utils/JsonParser.java
@@ -1,63 +1,68 @@
package string_utils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import org.apache.pig.EvalFunc;
import org.apache.pig.PigWarning;
import org.apache.pig.backend.executionengine.ExecException;
import org.apache.pig.data.DataType;
import org.apache.pig.data.Tuple;
import org.apache.pig.data.TupleFactory;
import org.apache.pig.impl.logicalLayer.schema.Schema;
import date_utils.DataChecker;
public class JsonParser extends EvalFunc<Tuple> {
public Tuple exec(Tuple input) throws IOException {
List<Tuple> bagtuples = new ArrayList<Tuple>();
;
Tuple result = TupleFactory.getInstance().newTuple(bagtuples);
String[] paramColumns = getParamColumns();
+ String jj = "";
try {
if (DataChecker.isValid(input, 1)) {
String json = "{}";
if (input.get(0) != null) {
json = input.get(0).toString();
+ json = json.replace("\\", "");
}
+ jj = json;
JSONObject jsonObject = JSONObject.fromObject(json);
for (String column : paramColumns) {
String data = (String) jsonObject.get(column);
if (data == null) {
data = "-";
}
result.append(data);
}
}
} catch (ExecException e) {
e.printStackTrace();
- } catch (JSONException e) {
+ }
+ catch (JSONException e) {
+ result.append(jj);
for (String column : paramColumns) {
- result.append(column + "-");
+ result.append("-");
}
}
return result;
}
public String[] getParamColumns() {
String[] paramColumns = { "cart_id", "cart_line_id", "sales_event_id",
"product_id", "ds_cat_id", "l1",
"l2", "sku_id", "quantity", "payment_card_id" };
return paramColumns;
}
public Schema outputSchema(Schema input) {
return new Schema(new Schema.FieldSchema(null, DataType.CHARARRAY));
}
}
| false | true | public Tuple exec(Tuple input) throws IOException {
List<Tuple> bagtuples = new ArrayList<Tuple>();
;
Tuple result = TupleFactory.getInstance().newTuple(bagtuples);
String[] paramColumns = getParamColumns();
try {
if (DataChecker.isValid(input, 1)) {
String json = "{}";
if (input.get(0) != null) {
json = input.get(0).toString();
}
JSONObject jsonObject = JSONObject.fromObject(json);
for (String column : paramColumns) {
String data = (String) jsonObject.get(column);
if (data == null) {
data = "-";
}
result.append(data);
}
}
} catch (ExecException e) {
e.printStackTrace();
} catch (JSONException e) {
for (String column : paramColumns) {
result.append(column + "-");
}
}
return result;
}
| public Tuple exec(Tuple input) throws IOException {
List<Tuple> bagtuples = new ArrayList<Tuple>();
;
Tuple result = TupleFactory.getInstance().newTuple(bagtuples);
String[] paramColumns = getParamColumns();
String jj = "";
try {
if (DataChecker.isValid(input, 1)) {
String json = "{}";
if (input.get(0) != null) {
json = input.get(0).toString();
json = json.replace("\\", "");
}
jj = json;
JSONObject jsonObject = JSONObject.fromObject(json);
for (String column : paramColumns) {
String data = (String) jsonObject.get(column);
if (data == null) {
data = "-";
}
result.append(data);
}
}
} catch (ExecException e) {
e.printStackTrace();
}
catch (JSONException e) {
result.append(jj);
for (String column : paramColumns) {
result.append("-");
}
}
return result;
}
|
diff --git a/Tamagotchi/src/com/redditandroiddevelopers/tamagotchi/TamagotchiGame.java b/Tamagotchi/src/com/redditandroiddevelopers/tamagotchi/TamagotchiGame.java
index 58f1d4e..250530c 100644
--- a/Tamagotchi/src/com/redditandroiddevelopers/tamagotchi/TamagotchiGame.java
+++ b/Tamagotchi/src/com/redditandroiddevelopers/tamagotchi/TamagotchiGame.java
@@ -1,115 +1,116 @@
package com.redditandroiddevelopers.tamagotchi;
import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.InputMultiplexer;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.assets.loaders.TextureLoader;
import com.badlogic.gdx.assets.loaders.resolvers.InternalFileHandleResolver;
import com.badlogic.gdx.assets.loaders.resolvers.ResolutionFileResolver;
import com.badlogic.gdx.assets.loaders.resolvers.ResolutionFileResolver.Resolution;
import com.badlogic.gdx.graphics.Texture;
import com.redditandroiddevelopers.tamagotchi.screens.CommonScreen;
import com.redditandroiddevelopers.tamagotchi.screens.MainGameScreen;
import com.redditandroiddevelopers.tamagotchi.screens.MainMenuScreen;
import com.redditandroiddevelopers.tamagotchi.screens.PauseScreen;
import com.redditandroiddevelopers.tamagotchi.screens.SplashScreen;
import java.util.ArrayList;
/**
* The main activity for our game. This will be the only activity running in our
* app, it will delegate what screen instance will render to the display based
* on the state.
*/
public class TamagotchiGame extends Game {
public static final int STATE_MAIN_MENU = 0;
public static final int STATE_MAIN_GAME = 1;
public static final int STATE_PAUSED = 2;
public static final int STATE_SELECT_PET = 3;
public static final int STATE_MEMORIES = 4;
public static final int STATE_SETTINGS = 5;
private CommonScreen[] screens;
private static ArrayList<Integer> screenHistory = new ArrayList<Integer>();
public final TamagotchiConfiguration config;
public InputMultiplexer inputMultiplexer;
public AssetManager assetManager;
public TamagotchiAssets assets;
public TamagotchiGame(TamagotchiConfiguration config) {
this.config = config;
}
@Override
public void create() {
// do first-time configurations that should live as long as the
// application does
Gdx.app.setLogLevel(config.logLevel);
// create screen objects we're going to need throughout
screens = new CommonScreen[] {
new MainMenuScreen(this),
new MainGameScreen(this),
new PauseScreen(this),
new PauseScreen(this), // TODO: implement PetSelectionScreen
new PauseScreen(this), // TODO: implement MemoriesScreen
new PauseScreen(this), // TODO: implement SettingsScreen
};
final Resolution resolution = new Resolution(Gdx.graphics.getWidth(),
Gdx.graphics.getHeight(), "");
final ResolutionFileResolver resolver = new ResolutionFileResolver(
new InternalFileHandleResolver(), resolution);
assetManager = new AssetManager();
assetManager.setLoader(Texture.class, new TextureLoader(resolver));
assets = new TamagotchiAssets(assetManager);
inputMultiplexer = new InputMultiplexer();
Gdx.input.setInputProcessor(inputMultiplexer);
+ Gdx.app.getInput().setCatchBackKey(true);
setScreen(new SplashScreen(this));
}
@Override
public void render() {
// TODO FrameBuffer here?
// actually render the current screen
super.render();
}
/**
* Update the state, all updates outside of this class should use this
* method
*
* @param state The int val of the new state
*/
public void updateState(int state) {
if (state < 0 || state >= 6) {
assert false;
throw new IllegalArgumentException("Invalid state value");
}
screenHistory.add(state);
setScreen(screens[state]);
}
public void goToPreviousScreen() {
screenHistory.remove(screenHistory.size() - 1);
updateState(screenHistory.get(screenHistory.size() - 1));
}
@Override
public void dispose() {
super.dispose();
assetManager.dispose();
assetManager = null;
assets = null;
Gdx.input.setInputProcessor(null);
inputMultiplexer = null;
}
}
| true | true | public void create() {
// do first-time configurations that should live as long as the
// application does
Gdx.app.setLogLevel(config.logLevel);
// create screen objects we're going to need throughout
screens = new CommonScreen[] {
new MainMenuScreen(this),
new MainGameScreen(this),
new PauseScreen(this),
new PauseScreen(this), // TODO: implement PetSelectionScreen
new PauseScreen(this), // TODO: implement MemoriesScreen
new PauseScreen(this), // TODO: implement SettingsScreen
};
final Resolution resolution = new Resolution(Gdx.graphics.getWidth(),
Gdx.graphics.getHeight(), "");
final ResolutionFileResolver resolver = new ResolutionFileResolver(
new InternalFileHandleResolver(), resolution);
assetManager = new AssetManager();
assetManager.setLoader(Texture.class, new TextureLoader(resolver));
assets = new TamagotchiAssets(assetManager);
inputMultiplexer = new InputMultiplexer();
Gdx.input.setInputProcessor(inputMultiplexer);
setScreen(new SplashScreen(this));
}
| public void create() {
// do first-time configurations that should live as long as the
// application does
Gdx.app.setLogLevel(config.logLevel);
// create screen objects we're going to need throughout
screens = new CommonScreen[] {
new MainMenuScreen(this),
new MainGameScreen(this),
new PauseScreen(this),
new PauseScreen(this), // TODO: implement PetSelectionScreen
new PauseScreen(this), // TODO: implement MemoriesScreen
new PauseScreen(this), // TODO: implement SettingsScreen
};
final Resolution resolution = new Resolution(Gdx.graphics.getWidth(),
Gdx.graphics.getHeight(), "");
final ResolutionFileResolver resolver = new ResolutionFileResolver(
new InternalFileHandleResolver(), resolution);
assetManager = new AssetManager();
assetManager.setLoader(Texture.class, new TextureLoader(resolver));
assets = new TamagotchiAssets(assetManager);
inputMultiplexer = new InputMultiplexer();
Gdx.input.setInputProcessor(inputMultiplexer);
Gdx.app.getInput().setCatchBackKey(true);
setScreen(new SplashScreen(this));
}
|
diff --git a/xmlimplsrc/org/mozilla/javascript/xmlimpl/XMLList.java b/xmlimplsrc/org/mozilla/javascript/xmlimpl/XMLList.java
index 4b90b9bc..f40e599d 100644
--- a/xmlimplsrc/org/mozilla/javascript/xmlimpl/XMLList.java
+++ b/xmlimplsrc/org/mozilla/javascript/xmlimpl/XMLList.java
@@ -1,824 +1,829 @@
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Rhino code, released
* May 6, 1999.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1997-2000
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Ethan Hugg
* Terry Lucas
* Milen Nankov
* David P. Caldwell <[email protected]>
*
* Alternatively, the contents of this file may be used under the terms of
* the GNU General Public License Version 2 or later (the "GPL"), in which
* case the provisions of the GPL are applicable instead of those above. If
* you wish to allow use of your version of this file only under the terms of
* the GPL and not to allow others to use your version of this file under the
* MPL, indicate your decision by deleting the provisions above and replacing
* them with the notice and other provisions required by the GPL. If you do
* not delete the provisions above, a recipient may use your version of this
* file under either the MPL or the GPL.
*
* ***** END LICENSE BLOCK ***** */
package org.mozilla.javascript.xmlimpl;
import org.mozilla.javascript.*;
import org.mozilla.javascript.xml.*;
import java.util.ArrayList;
class XMLList extends XMLObjectImpl implements Function {
static final long serialVersionUID = -4543618751670781135L;
private XmlNode.InternalList _annos;
private XMLObjectImpl targetObject = null;
private XmlNode.QName targetProperty = null;
XMLList(XMLLibImpl lib, Scriptable scope, XMLObject prototype) {
super(lib, scope, prototype);
_annos = new XmlNode.InternalList();
}
/* TODO Will probably end up unnecessary as we move things around */
XmlNode.InternalList getNodeList() {
return _annos;
}
// TODO Should be XMLObjectImpl, XMLName?
void setTargets(XMLObjectImpl object, XmlNode.QName property) {
targetObject = object;
targetProperty = property;
}
/* TODO: original author marked this as deprecated */
private XML getXmlFromAnnotation(int index) {
return getXML(_annos, index);
}
@Override
XML getXML() {
if (length() == 1) return getXmlFromAnnotation(0);
return null;
}
private void internalRemoveFromList(int index) {
_annos.remove(index);
}
void replace(int index, XML xml) {
if (index < length()) {
XmlNode.InternalList newAnnoList = new XmlNode.InternalList();
newAnnoList.add(_annos, 0, index);
newAnnoList.add(xml);
newAnnoList.add(_annos, index+1, length());
_annos = newAnnoList;
}
}
private void insert(int index, XML xml) {
if (index < length()) {
XmlNode.InternalList newAnnoList = new XmlNode.InternalList();
newAnnoList.add(_annos, 0, index);
newAnnoList.add(xml);
newAnnoList.add(_annos, index, length());
_annos = newAnnoList;
}
}
//
//
// methods overriding ScriptableObject
//
//
@Override
public String getClassName() {
return "XMLList";
}
//
//
// methods overriding IdScriptableObject
//
//
@Override
public Object get(int index, Scriptable start) {
//Log("get index: " + index);
if (index >= 0 && index < length()) {
return getXmlFromAnnotation(index);
} else {
return Scriptable.NOT_FOUND;
}
}
@Override
boolean hasXMLProperty(XMLName xmlName) {
boolean result = false;
// Has now should return true if the property would have results > 0 or
// if it's a method name
String name = xmlName.localName();
if ((getPropertyList(xmlName).length() > 0) ||
(getMethod(name) != NOT_FOUND)) {
result = true;
}
return result;
}
@Override
public boolean has(int index, Scriptable start) {
return 0 <= index && index < length();
}
@Override
void putXMLProperty(XMLName xmlName, Object value) {
//Log("put property: " + name);
// Special-case checks for undefined and null
if (value == null) {
value = "null";
} else if (value instanceof Undefined) {
value = "undefined";
}
if (length() > 1) {
throw ScriptRuntime.typeError(
"Assignment to lists with more than one item is not supported");
} else if (length() == 0) {
// Secret sauce for super-expandos.
// We set an element here, and then add ourselves to our target.
if (targetObject != null && targetProperty != null &&
targetProperty.getLocalName() != null &&
targetProperty.getLocalName().length() > 0)
{
// Add an empty element with our targetProperty name and
// then set it.
XML xmlValue = newTextElementXML(null, targetProperty, null);
addToList(xmlValue);
if(xmlName.isAttributeName()) {
setAttribute(xmlName, value);
} else {
XML xml = item(0);
xml.putXMLProperty(xmlName, value);
// Update the list with the new item at location 0.
replace(0, item(0));
}
// Now add us to our parent
XMLName name2 = XMLName.formProperty(
targetProperty.getNamespace().getUri(),
targetProperty.getLocalName());
targetObject.putXMLProperty(name2, this);
} else {
throw ScriptRuntime.typeError(
"Assignment to empty XMLList without targets not supported");
}
} else if(xmlName.isAttributeName()) {
setAttribute(xmlName, value);
} else {
XML xml = item(0);
xml.putXMLProperty(xmlName, value);
// Update the list with the new item at location 0.
replace(0, item(0));
if (targetObject != null && targetProperty != null &&
targetProperty.getLocalName() != null)
{
// Now add us to our parent
XMLName name2 = XMLName.formProperty(
targetProperty.getNamespace().getUri(),
targetProperty.getLocalName());
targetObject.putXMLProperty(name2, this);
}
}
}
@Override
Object getXMLProperty(XMLName name) {
return getPropertyList(name);
}
private void replaceNode(XML xml, XML with) {
xml.replaceWith(with);
}
@Override
public void put(int index, Scriptable start, Object value) {
Object parent = Undefined.instance;
// Convert text into XML if needed.
XMLObject xmlValue;
// Special-case checks for undefined and null
if (value == null) {
value = "null";
} else if (value instanceof Undefined) {
value = "undefined";
}
if (value instanceof XMLObject) {
xmlValue = (XMLObject) value;
} else {
if (targetProperty == null) {
xmlValue = newXMLFromJs(value.toString());
} else {
// Note that later in the code, we will use this as an argument to replace(int,value)
// So we will be "replacing" this element with itself
// There may well be a better way to do this
// TODO Find a way to refactor this whole method and simplify it
xmlValue = item(index);
if (xmlValue == null) {
- xmlValue = item(0).copy();
+ XML x = item(0);
+ xmlValue = x == null
+ ? newTextElementXML(null,targetProperty,null)
+ : x.copy();
}
((XML)xmlValue).setChildren(value);
}
}
// Find the parent
if (index < length()) {
- parent = item(index).parent();
+ parent = item(index).parent();
+ } else if (length() == 0) {
+ parent = targetObject != null ? targetObject.getXML() : parent();
} else {
- // Appending
- parent = parent();
+ // Appending
+ parent = parent();
}
if (parent instanceof XML) {
// found parent, alter doc
XML xmlParent = (XML) parent;
if (index < length()) {
// We're replacing the the node.
XML xmlNode = getXmlFromAnnotation(index);
if (xmlValue instanceof XML) {
replaceNode(xmlNode, (XML) xmlValue);
replace(index, xmlNode);
} else if (xmlValue instanceof XMLList) {
// Replace the first one, and add the rest on the list.
XMLList list = (XMLList) xmlValue;
if (list.length() > 0) {
int lastIndexAdded = xmlNode.childIndex();
replaceNode(xmlNode, list.item(0));
replace(index, list.item(0));
for (int i = 1; i < list.length(); i++) {
xmlParent.insertChildAfter(xmlParent.getXmlChild(lastIndexAdded), list.item(i));
lastIndexAdded++;
insert(index + i, list.item(i));
}
}
}
} else {
// Appending
xmlParent.appendChild(xmlValue);
addToList(xmlParent.getXmlChild(index));
}
} else {
// Don't all have same parent, no underlying doc to alter
if (index < length()) {
XML xmlNode = getXML(_annos, index);
if (xmlValue instanceof XML) {
replaceNode(xmlNode, (XML) xmlValue);
replace(index, xmlNode);
} else if (xmlValue instanceof XMLList) {
// Replace the first one, and add the rest on the list.
XMLList list = (XMLList) xmlValue;
if (list.length() > 0) {
replaceNode(xmlNode, list.item(0));
replace(index, list.item(0));
for (int i = 1; i < list.length(); i++) {
insert(index + i, list.item(i));
}
}
}
} else {
addToList(xmlValue);
}
}
}
private XML getXML(XmlNode.InternalList _annos, int index) {
if (index >= 0 && index < length()) {
return xmlFromNode(_annos.item(index));
} else {
return null;
}
}
@Override
void deleteXMLProperty(XMLName name) {
for (int i = 0; i < length(); i++) {
XML xml = getXmlFromAnnotation(i);
if (xml.isElement()) {
xml.deleteXMLProperty(name);
}
}
}
@Override
public void delete(int index) {
if (index >= 0 && index < length()) {
XML xml = getXmlFromAnnotation(index);
xml.remove();
internalRemoveFromList(index);
}
}
@Override
public Object[] getIds() {
Object enumObjs[];
if (isPrototype()) {
enumObjs = new Object[0];
} else {
enumObjs = new Object[length()];
for (int i = 0; i < enumObjs.length; i++) {
enumObjs[i] = Integer.valueOf(i);
}
}
return enumObjs;
}
public Object[] getIdsForDebug() {
return getIds();
}
// XMLList will remove will delete all items in the list (a set delete) this differs from the XMLList delete operator.
void remove() {
int nLen = length();
for (int i = nLen - 1; i >= 0; i--) {
XML xml = getXmlFromAnnotation(i);
if (xml != null) {
xml.remove();
internalRemoveFromList(i);
}
}
}
XML item(int index) {
return _annos != null
? getXmlFromAnnotation(index) : createEmptyXML();
}
private void setAttribute(XMLName xmlName, Object value) {
for (int i = 0; i < length(); i++) {
XML xml = getXmlFromAnnotation(i);
xml.setAttribute(xmlName, value);
}
}
void addToList(Object toAdd) {
_annos.addToList(toAdd);
}
//
//
// Methods from section 12.4.4 in the spec
//
//
@Override
XMLList child(int index) {
XMLList result = newXMLList();
for (int i = 0; i < length(); i++) {
result.addToList(getXmlFromAnnotation(i).child(index));
}
return result;
}
@Override
XMLList child(XMLName xmlName) {
XMLList result = newXMLList();
for (int i = 0; i < length(); i++) {
result.addToList(getXmlFromAnnotation(i).child(xmlName));
}
return result;
}
@Override
void addMatches(XMLList rv, XMLName name) {
for (int i=0; i<length(); i++) {
getXmlFromAnnotation(i).addMatches(rv, name);
}
}
@Override
XMLList children() {
ArrayList<XML> list = new ArrayList<XML>();
for (int i = 0; i < length(); i++) {
XML xml = getXmlFromAnnotation(i);
if (xml != null) {
XMLList childList = xml.children();
int cChildren = childList.length();
for (int j = 0; j < cChildren; j++) {
list.add(childList.item(j));
}
}
}
XMLList allChildren = newXMLList();
int sz = list.size();
for (int i = 0; i < sz; i++) {
allChildren.addToList(list.get(i));
}
return allChildren;
}
@Override
XMLList comments() {
XMLList result = newXMLList();
for (int i = 0; i < length(); i++) {
XML xml = getXmlFromAnnotation(i);
result.addToList(xml.comments());
}
return result;
}
@Override
XMLList elements(XMLName name) {
XMLList rv = newXMLList();
for (int i=0; i<length(); i++) {
XML xml = getXmlFromAnnotation(i);
rv.addToList(xml.elements(name));
}
return rv;
}
@Override
boolean contains(Object xml) {
boolean result = false;
for (int i = 0; i < length(); i++) {
XML member = getXmlFromAnnotation(i);
if (member.equivalentXml(xml)) {
result = true;
break;
}
}
return result;
}
@Override
XMLObjectImpl copy() {
XMLList result = newXMLList();
for (int i = 0; i < length(); i++) {
XML xml = getXmlFromAnnotation(i);
result.addToList(xml.copy());
}
return result;
}
@Override
boolean hasOwnProperty(XMLName xmlName) {
if (isPrototype()) {
String property = xmlName.localName();
return (findPrototypeId(property) != 0);
} else {
return (getPropertyList(xmlName).length() > 0);
}
}
@Override
boolean hasComplexContent() {
boolean complexContent;
int length = length();
if (length == 0) {
complexContent = false;
} else if (length == 1) {
complexContent = getXmlFromAnnotation(0).hasComplexContent();
} else {
complexContent = false;
for (int i = 0; i < length; i++) {
XML nextElement = getXmlFromAnnotation(i);
if (nextElement.isElement()) {
complexContent = true;
break;
}
}
}
return complexContent;
}
@Override
boolean hasSimpleContent() {
if (length() == 0) {
return true;
} else if (length() == 1) {
return getXmlFromAnnotation(0).hasSimpleContent();
} else {
for (int i=0; i<length(); i++) {
XML nextElement = getXmlFromAnnotation(i);
if (nextElement.isElement()) {
return false;
}
}
return true;
}
}
@Override
int length() {
int result = 0;
if (_annos != null) {
result = _annos.length();
}
return result;
}
@Override
void normalize() {
for (int i = 0; i < length(); i++) {
getXmlFromAnnotation(i).normalize();
}
}
/**
* If list is empty, return undefined, if elements have different parents return undefined,
* If they all have the same parent, return that parent
*/
@Override
Object parent() {
if (length() == 0) return Undefined.instance;
XML candidateParent = null;
for (int i = 0; i < length(); i++) {
Object currParent = getXmlFromAnnotation(i).parent();
if (!(currParent instanceof XML)) return Undefined.instance;
XML xml = (XML)currParent;
if (i == 0) {
// Set the first for the rest to compare to.
candidateParent = xml;
} else {
if (candidateParent.is(xml)) {
// keep looking
} else {
return Undefined.instance;
}
}
}
return candidateParent;
}
@Override
XMLList processingInstructions(XMLName xmlName) {
XMLList result = newXMLList();
for (int i = 0; i < length(); i++) {
XML xml = getXmlFromAnnotation(i);
result.addToList(xml.processingInstructions(xmlName));
}
return result;
}
@Override
boolean propertyIsEnumerable(Object name) {
long index;
if (name instanceof Integer) {
index = ((Integer)name).intValue();
} else if (name instanceof Number) {
double x = ((Number)name).doubleValue();
index = (long)x;
if (index != x) {
return false;
}
if (index == 0 && 1.0 / x < 0) {
// Negative 0
return false;
}
} else {
String s = ScriptRuntime.toString(name);
index = ScriptRuntime.testUint32String(s);
}
return (0 <= index && index < length());
}
@Override
XMLList text() {
XMLList result = newXMLList();
for (int i = 0; i < length(); i++) {
result.addToList(getXmlFromAnnotation(i).text());
}
return result;
}
@Override
public String toString() {
// ECMA357 10.1.2
if (hasSimpleContent()) {
StringBuffer sb = new StringBuffer();
for(int i = 0; i < length(); i++) {
XML next = getXmlFromAnnotation(i);
if (next.isComment() || next.isProcessingInstruction()) {
// do nothing
} else {
sb.append(next.toString());
}
}
return sb.toString();
} else {
return toXMLString();
}
}
@Override
String toSource(int indent) {
return toXMLString();
}
@Override
String toXMLString() {
// See ECMA 10.2.1
StringBuffer sb = new StringBuffer();
for (int i=0; i<length(); i++) {
if (getProcessor().isPrettyPrinting() && i != 0) {
sb.append('\n');
}
sb.append(getXmlFromAnnotation(i).toXMLString());
}
return sb.toString();
}
@Override
Object valueOf() {
return this;
}
//
// Other public Functions from XMLObject
//
@Override
boolean equivalentXml(Object target) {
boolean result = false;
// Zero length list should equate to undefined
if (target instanceof Undefined && length() == 0) {
result = true;
} else if (length() == 1) {
result = getXmlFromAnnotation(0).equivalentXml(target);
} else if (target instanceof XMLList) {
XMLList otherList = (XMLList) target;
if (otherList.length() == length()) {
result = true;
for (int i = 0; i < length(); i++) {
if (!getXmlFromAnnotation(i).equivalentXml(otherList.getXmlFromAnnotation(i))) {
result = false;
break;
}
}
}
}
return result;
}
private XMLList getPropertyList(XMLName name) {
XMLList propertyList = newXMLList();
XmlNode.QName qname = null;
if (!name.isDescendants() && !name.isAttributeName()) {
// Only set the targetProperty if this is a regular child get
// and not a descendant or attribute get
qname = name.toQname();
}
propertyList.setTargets(this, qname);
for (int i = 0; i < length(); i++) {
propertyList.addToList(
getXmlFromAnnotation(i).getPropertyList(name));
}
return propertyList;
}
private Object applyOrCall(boolean isApply,
Context cx, Scriptable scope,
Scriptable thisObj, Object[] args) {
String methodName = isApply ? "apply" : "call";
if(!(thisObj instanceof XMLList) ||
((XMLList)thisObj).targetProperty == null)
throw ScriptRuntime.typeError1("msg.isnt.function",
methodName);
return ScriptRuntime.applyOrCall(isApply, cx, scope, thisObj, args);
}
@Override
protected Object jsConstructor(Context cx, boolean inNewExpr,
Object[] args)
{
if (args.length == 0) {
return newXMLList();
} else {
Object arg0 = args[0];
if (!inNewExpr && arg0 instanceof XMLList) {
// XMLList(XMLList) returns the same object.
return arg0;
}
return newXMLListFrom(arg0);
}
}
/**
* See ECMA 357, 11_2_2_1, Semantics, 3_e.
*/
@Override
public Scriptable getExtraMethodSource(Context cx) {
if (length() == 1) {
return getXmlFromAnnotation(0);
}
return null;
}
public Object call(Context cx, Scriptable scope, Scriptable thisObj,
Object[] args) {
// This XMLList is being called as a Function.
// Let's find the real Function object.
if(targetProperty == null)
throw ScriptRuntime.notFunctionError(this);
String methodName = targetProperty.getLocalName();
boolean isApply = methodName.equals("apply");
if(isApply || methodName.equals("call"))
return applyOrCall(isApply, cx, scope, thisObj, args);
Callable method = ScriptRuntime.getElemFunctionAndThis(
this, methodName, cx);
// Call lastStoredScriptable to clear stored thisObj
// but ignore the result as the method should use the supplied
// thisObj, not one from redirected call
ScriptRuntime.lastStoredScriptable(cx);
return method.call(cx, scope, thisObj, args);
}
public Scriptable construct(Context cx, Scriptable scope, Object[] args) {
throw ScriptRuntime.typeError1("msg.not.ctor", "XMLList");
}
}
| false | true | public void put(int index, Scriptable start, Object value) {
Object parent = Undefined.instance;
// Convert text into XML if needed.
XMLObject xmlValue;
// Special-case checks for undefined and null
if (value == null) {
value = "null";
} else if (value instanceof Undefined) {
value = "undefined";
}
if (value instanceof XMLObject) {
xmlValue = (XMLObject) value;
} else {
if (targetProperty == null) {
xmlValue = newXMLFromJs(value.toString());
} else {
// Note that later in the code, we will use this as an argument to replace(int,value)
// So we will be "replacing" this element with itself
// There may well be a better way to do this
// TODO Find a way to refactor this whole method and simplify it
xmlValue = item(index);
if (xmlValue == null) {
xmlValue = item(0).copy();
}
((XML)xmlValue).setChildren(value);
}
}
// Find the parent
if (index < length()) {
parent = item(index).parent();
} else {
// Appending
parent = parent();
}
if (parent instanceof XML) {
// found parent, alter doc
XML xmlParent = (XML) parent;
if (index < length()) {
// We're replacing the the node.
XML xmlNode = getXmlFromAnnotation(index);
if (xmlValue instanceof XML) {
replaceNode(xmlNode, (XML) xmlValue);
replace(index, xmlNode);
} else if (xmlValue instanceof XMLList) {
// Replace the first one, and add the rest on the list.
XMLList list = (XMLList) xmlValue;
if (list.length() > 0) {
int lastIndexAdded = xmlNode.childIndex();
replaceNode(xmlNode, list.item(0));
replace(index, list.item(0));
for (int i = 1; i < list.length(); i++) {
xmlParent.insertChildAfter(xmlParent.getXmlChild(lastIndexAdded), list.item(i));
lastIndexAdded++;
insert(index + i, list.item(i));
}
}
}
} else {
// Appending
xmlParent.appendChild(xmlValue);
addToList(xmlParent.getXmlChild(index));
}
} else {
// Don't all have same parent, no underlying doc to alter
if (index < length()) {
XML xmlNode = getXML(_annos, index);
if (xmlValue instanceof XML) {
replaceNode(xmlNode, (XML) xmlValue);
replace(index, xmlNode);
} else if (xmlValue instanceof XMLList) {
// Replace the first one, and add the rest on the list.
XMLList list = (XMLList) xmlValue;
if (list.length() > 0) {
replaceNode(xmlNode, list.item(0));
replace(index, list.item(0));
for (int i = 1; i < list.length(); i++) {
insert(index + i, list.item(i));
}
}
}
} else {
addToList(xmlValue);
}
}
}
| public void put(int index, Scriptable start, Object value) {
Object parent = Undefined.instance;
// Convert text into XML if needed.
XMLObject xmlValue;
// Special-case checks for undefined and null
if (value == null) {
value = "null";
} else if (value instanceof Undefined) {
value = "undefined";
}
if (value instanceof XMLObject) {
xmlValue = (XMLObject) value;
} else {
if (targetProperty == null) {
xmlValue = newXMLFromJs(value.toString());
} else {
// Note that later in the code, we will use this as an argument to replace(int,value)
// So we will be "replacing" this element with itself
// There may well be a better way to do this
// TODO Find a way to refactor this whole method and simplify it
xmlValue = item(index);
if (xmlValue == null) {
XML x = item(0);
xmlValue = x == null
? newTextElementXML(null,targetProperty,null)
: x.copy();
}
((XML)xmlValue).setChildren(value);
}
}
// Find the parent
if (index < length()) {
parent = item(index).parent();
} else if (length() == 0) {
parent = targetObject != null ? targetObject.getXML() : parent();
} else {
// Appending
parent = parent();
}
if (parent instanceof XML) {
// found parent, alter doc
XML xmlParent = (XML) parent;
if (index < length()) {
// We're replacing the the node.
XML xmlNode = getXmlFromAnnotation(index);
if (xmlValue instanceof XML) {
replaceNode(xmlNode, (XML) xmlValue);
replace(index, xmlNode);
} else if (xmlValue instanceof XMLList) {
// Replace the first one, and add the rest on the list.
XMLList list = (XMLList) xmlValue;
if (list.length() > 0) {
int lastIndexAdded = xmlNode.childIndex();
replaceNode(xmlNode, list.item(0));
replace(index, list.item(0));
for (int i = 1; i < list.length(); i++) {
xmlParent.insertChildAfter(xmlParent.getXmlChild(lastIndexAdded), list.item(i));
lastIndexAdded++;
insert(index + i, list.item(i));
}
}
}
} else {
// Appending
xmlParent.appendChild(xmlValue);
addToList(xmlParent.getXmlChild(index));
}
} else {
// Don't all have same parent, no underlying doc to alter
if (index < length()) {
XML xmlNode = getXML(_annos, index);
if (xmlValue instanceof XML) {
replaceNode(xmlNode, (XML) xmlValue);
replace(index, xmlNode);
} else if (xmlValue instanceof XMLList) {
// Replace the first one, and add the rest on the list.
XMLList list = (XMLList) xmlValue;
if (list.length() > 0) {
replaceNode(xmlNode, list.item(0));
replace(index, list.item(0));
for (int i = 1; i < list.length(); i++) {
insert(index + i, list.item(i));
}
}
}
} else {
addToList(xmlValue);
}
}
}
|
diff --git a/src/java/server/org/jor/rest/report/report/InsiderActivityLast14Days.java b/src/java/server/org/jor/rest/report/report/InsiderActivityLast14Days.java
index e6f9d6f..31d6e2e 100644
--- a/src/java/server/org/jor/rest/report/report/InsiderActivityLast14Days.java
+++ b/src/java/server/org/jor/rest/report/report/InsiderActivityLast14Days.java
@@ -1,83 +1,84 @@
package org.jor.rest.report.report;
import java.util.List;
import org.jor.server.services.db.DataService;
import com.google.visualization.datasource.datatable.DataTable;
import com.google.visualization.datasource.datatable.value.ValueType;
import com.google.visualization.datasource.query.Query;
public class InsiderActivityLast14Days extends BaseReport
{
public InsiderActivityLast14Days(Query query)
{
super(query);
}
@Override
public DataTable getData()
{
DataService service = DataService.getDataService("metrics-postgres");
String sql =
"SELECT email," +
" (COUNT(event_type_id) - SUM ( CASE WHEN (event_type_id = 16) THEN 1 ELSE 0 END)) AS activity_count,"
+ " SUM ( CASE WHEN (event_type_id = 0) THEN 1 ELSE 0 END) AS unknown,"
+ " SUM ( CASE WHEN (event_type_id = 1) THEN 1 ELSE 0 END) AS project_created,"
+ " SUM ( CASE WHEN (event_type_id = 2) THEN 1 ELSE 0 END) AS project_opened,"
+ " SUM ( CASE WHEN (event_type_id = 3) THEN 1 ELSE 0 END) AS file_added,"
+ " SUM ( CASE WHEN (event_type_id = 4) THEN 1 ELSE 0 END) AS file_downloaded,"
+ " SUM ( CASE WHEN (event_type_id = 5) THEN 1 ELSE 0 END) AS file_deleted,"
+ " SUM ( CASE WHEN (event_type_id = 6) THEN 1 ELSE 0 END) AS viewer_opened,"
+ " SUM ( CASE WHEN (event_type_id = 7) THEN 1 ELSE 0 END) AS comment_added,"
+ " SUM ( CASE WHEN (event_type_id = 8) THEN 1 ELSE 0 END) AS file_comment_added,"
+ " SUM ( CASE WHEN (event_type_id = 9) THEN 1 ELSE 0 END) AS pin_comment_added,"
+ " SUM ( CASE WHEN (event_type_id = 10) THEN 1 ELSE 0 END) AS project_owner_added,"
+ " SUM ( CASE WHEN (event_type_id = 11) THEN 1 ELSE 0 END) AS collaborator_added,"
+ " SUM ( CASE WHEN (event_type_id = 12) THEN 1 ELSE 0 END) AS limited_collaborator_added,"
+ " SUM ( CASE WHEN (event_type_id = 13) THEN 1 ELSE 0 END) AS project_owner_deleted,"
+ " SUM ( CASE WHEN (event_type_id = 14) THEN 1 ELSE 0 END) AS collaborator_deleted,"
+ " SUM ( CASE WHEN (event_type_id = 15) THEN 1 ELSE 0 END) AS limited_collaborator_deleted"
+ " FROM"
+ " ("
+ " SELECT m.email, e.member_id, e.event_type_id"
+ " FROM events e"
+ " INNER JOIN member_dimension m ON (e.member_id = m.id AND m.email NOT LIKE '%grabcad.com')"
+ " INNER JOIN project_dimension p ON (e.project_id = p.id AND p.is_private = true)"
+ " WHERE e.event_time > extract (epoch FROM (now() - interval '14 days'))"
+ + " AND event_type_id != 16"
+ " ) a"
+ " GROUP by email"
+ " ORDER BY COUNT(event_type_id)";
List<Object[]> rows = service.runSQLQuery(sql);
// Create a data table,
addColumn("email", ValueType.TEXT, "Email");
addColumn("activity_count", ValueType.NUMBER, "Activity Count");
addColumn("unknown", ValueType.NUMBER, "unknown");
addColumn("project_created", ValueType.NUMBER, "project_created");
addColumn("project_opened", ValueType.NUMBER, "project_opened");
addColumn("file_added", ValueType.NUMBER, "file_added");
addColumn("file_downloaded", ValueType.NUMBER, "file_downloaded");
addColumn("file_deleted", ValueType.NUMBER, "file_deleted");
addColumn("viewer_opened", ValueType.NUMBER, "viewer_opened");
addColumn("comment_added", ValueType.NUMBER, "comment_added");
addColumn("file_comment_added", ValueType.NUMBER, "file_comment_added");
addColumn("pin_comment_added", ValueType.NUMBER, "pin_comment_added");
addColumn("project_owner_added", ValueType.NUMBER, "project_owner_added");
addColumn("collaborator_added", ValueType.NUMBER, "collaborator_added");
addColumn("limited_collaborator_added", ValueType.NUMBER, "limited_collaborator_added");
addColumn("project_owner_deleted", ValueType.NUMBER, "project_owner_deleted");
addColumn("collaborator_deleted", ValueType.NUMBER, "collaborator_deleted");
addColumn("limited_collaborator_deleted", ValueType.NUMBER, "limited_collaborator_deleted");
// Fill the data table.
for (int i = 0; i < rows.size(); i ++)
{
Object[] row = rows.get(i);
addRow(row);
}
return getTable();
}
}
| true | true | public DataTable getData()
{
DataService service = DataService.getDataService("metrics-postgres");
String sql =
"SELECT email," +
" (COUNT(event_type_id) - SUM ( CASE WHEN (event_type_id = 16) THEN 1 ELSE 0 END)) AS activity_count,"
+ " SUM ( CASE WHEN (event_type_id = 0) THEN 1 ELSE 0 END) AS unknown,"
+ " SUM ( CASE WHEN (event_type_id = 1) THEN 1 ELSE 0 END) AS project_created,"
+ " SUM ( CASE WHEN (event_type_id = 2) THEN 1 ELSE 0 END) AS project_opened,"
+ " SUM ( CASE WHEN (event_type_id = 3) THEN 1 ELSE 0 END) AS file_added,"
+ " SUM ( CASE WHEN (event_type_id = 4) THEN 1 ELSE 0 END) AS file_downloaded,"
+ " SUM ( CASE WHEN (event_type_id = 5) THEN 1 ELSE 0 END) AS file_deleted,"
+ " SUM ( CASE WHEN (event_type_id = 6) THEN 1 ELSE 0 END) AS viewer_opened,"
+ " SUM ( CASE WHEN (event_type_id = 7) THEN 1 ELSE 0 END) AS comment_added,"
+ " SUM ( CASE WHEN (event_type_id = 8) THEN 1 ELSE 0 END) AS file_comment_added,"
+ " SUM ( CASE WHEN (event_type_id = 9) THEN 1 ELSE 0 END) AS pin_comment_added,"
+ " SUM ( CASE WHEN (event_type_id = 10) THEN 1 ELSE 0 END) AS project_owner_added,"
+ " SUM ( CASE WHEN (event_type_id = 11) THEN 1 ELSE 0 END) AS collaborator_added,"
+ " SUM ( CASE WHEN (event_type_id = 12) THEN 1 ELSE 0 END) AS limited_collaborator_added,"
+ " SUM ( CASE WHEN (event_type_id = 13) THEN 1 ELSE 0 END) AS project_owner_deleted,"
+ " SUM ( CASE WHEN (event_type_id = 14) THEN 1 ELSE 0 END) AS collaborator_deleted,"
+ " SUM ( CASE WHEN (event_type_id = 15) THEN 1 ELSE 0 END) AS limited_collaborator_deleted"
+ " FROM"
+ " ("
+ " SELECT m.email, e.member_id, e.event_type_id"
+ " FROM events e"
+ " INNER JOIN member_dimension m ON (e.member_id = m.id AND m.email NOT LIKE '%grabcad.com')"
+ " INNER JOIN project_dimension p ON (e.project_id = p.id AND p.is_private = true)"
+ " WHERE e.event_time > extract (epoch FROM (now() - interval '14 days'))"
+ " ) a"
+ " GROUP by email"
+ " ORDER BY COUNT(event_type_id)";
List<Object[]> rows = service.runSQLQuery(sql);
// Create a data table,
addColumn("email", ValueType.TEXT, "Email");
addColumn("activity_count", ValueType.NUMBER, "Activity Count");
addColumn("unknown", ValueType.NUMBER, "unknown");
addColumn("project_created", ValueType.NUMBER, "project_created");
addColumn("project_opened", ValueType.NUMBER, "project_opened");
addColumn("file_added", ValueType.NUMBER, "file_added");
addColumn("file_downloaded", ValueType.NUMBER, "file_downloaded");
addColumn("file_deleted", ValueType.NUMBER, "file_deleted");
addColumn("viewer_opened", ValueType.NUMBER, "viewer_opened");
addColumn("comment_added", ValueType.NUMBER, "comment_added");
addColumn("file_comment_added", ValueType.NUMBER, "file_comment_added");
addColumn("pin_comment_added", ValueType.NUMBER, "pin_comment_added");
addColumn("project_owner_added", ValueType.NUMBER, "project_owner_added");
addColumn("collaborator_added", ValueType.NUMBER, "collaborator_added");
addColumn("limited_collaborator_added", ValueType.NUMBER, "limited_collaborator_added");
addColumn("project_owner_deleted", ValueType.NUMBER, "project_owner_deleted");
addColumn("collaborator_deleted", ValueType.NUMBER, "collaborator_deleted");
addColumn("limited_collaborator_deleted", ValueType.NUMBER, "limited_collaborator_deleted");
// Fill the data table.
for (int i = 0; i < rows.size(); i ++)
{
Object[] row = rows.get(i);
addRow(row);
}
return getTable();
}
| public DataTable getData()
{
DataService service = DataService.getDataService("metrics-postgres");
String sql =
"SELECT email," +
" (COUNT(event_type_id) - SUM ( CASE WHEN (event_type_id = 16) THEN 1 ELSE 0 END)) AS activity_count,"
+ " SUM ( CASE WHEN (event_type_id = 0) THEN 1 ELSE 0 END) AS unknown,"
+ " SUM ( CASE WHEN (event_type_id = 1) THEN 1 ELSE 0 END) AS project_created,"
+ " SUM ( CASE WHEN (event_type_id = 2) THEN 1 ELSE 0 END) AS project_opened,"
+ " SUM ( CASE WHEN (event_type_id = 3) THEN 1 ELSE 0 END) AS file_added,"
+ " SUM ( CASE WHEN (event_type_id = 4) THEN 1 ELSE 0 END) AS file_downloaded,"
+ " SUM ( CASE WHEN (event_type_id = 5) THEN 1 ELSE 0 END) AS file_deleted,"
+ " SUM ( CASE WHEN (event_type_id = 6) THEN 1 ELSE 0 END) AS viewer_opened,"
+ " SUM ( CASE WHEN (event_type_id = 7) THEN 1 ELSE 0 END) AS comment_added,"
+ " SUM ( CASE WHEN (event_type_id = 8) THEN 1 ELSE 0 END) AS file_comment_added,"
+ " SUM ( CASE WHEN (event_type_id = 9) THEN 1 ELSE 0 END) AS pin_comment_added,"
+ " SUM ( CASE WHEN (event_type_id = 10) THEN 1 ELSE 0 END) AS project_owner_added,"
+ " SUM ( CASE WHEN (event_type_id = 11) THEN 1 ELSE 0 END) AS collaborator_added,"
+ " SUM ( CASE WHEN (event_type_id = 12) THEN 1 ELSE 0 END) AS limited_collaborator_added,"
+ " SUM ( CASE WHEN (event_type_id = 13) THEN 1 ELSE 0 END) AS project_owner_deleted,"
+ " SUM ( CASE WHEN (event_type_id = 14) THEN 1 ELSE 0 END) AS collaborator_deleted,"
+ " SUM ( CASE WHEN (event_type_id = 15) THEN 1 ELSE 0 END) AS limited_collaborator_deleted"
+ " FROM"
+ " ("
+ " SELECT m.email, e.member_id, e.event_type_id"
+ " FROM events e"
+ " INNER JOIN member_dimension m ON (e.member_id = m.id AND m.email NOT LIKE '%grabcad.com')"
+ " INNER JOIN project_dimension p ON (e.project_id = p.id AND p.is_private = true)"
+ " WHERE e.event_time > extract (epoch FROM (now() - interval '14 days'))"
+ " AND event_type_id != 16"
+ " ) a"
+ " GROUP by email"
+ " ORDER BY COUNT(event_type_id)";
List<Object[]> rows = service.runSQLQuery(sql);
// Create a data table,
addColumn("email", ValueType.TEXT, "Email");
addColumn("activity_count", ValueType.NUMBER, "Activity Count");
addColumn("unknown", ValueType.NUMBER, "unknown");
addColumn("project_created", ValueType.NUMBER, "project_created");
addColumn("project_opened", ValueType.NUMBER, "project_opened");
addColumn("file_added", ValueType.NUMBER, "file_added");
addColumn("file_downloaded", ValueType.NUMBER, "file_downloaded");
addColumn("file_deleted", ValueType.NUMBER, "file_deleted");
addColumn("viewer_opened", ValueType.NUMBER, "viewer_opened");
addColumn("comment_added", ValueType.NUMBER, "comment_added");
addColumn("file_comment_added", ValueType.NUMBER, "file_comment_added");
addColumn("pin_comment_added", ValueType.NUMBER, "pin_comment_added");
addColumn("project_owner_added", ValueType.NUMBER, "project_owner_added");
addColumn("collaborator_added", ValueType.NUMBER, "collaborator_added");
addColumn("limited_collaborator_added", ValueType.NUMBER, "limited_collaborator_added");
addColumn("project_owner_deleted", ValueType.NUMBER, "project_owner_deleted");
addColumn("collaborator_deleted", ValueType.NUMBER, "collaborator_deleted");
addColumn("limited_collaborator_deleted", ValueType.NUMBER, "limited_collaborator_deleted");
// Fill the data table.
for (int i = 0; i < rows.size(); i ++)
{
Object[] row = rows.get(i);
addRow(row);
}
return getTable();
}
|
diff --git a/Terminal/src/device/Device.java b/Terminal/src/device/Device.java
index de8b4ad..3eaefd1 100644
--- a/Terminal/src/device/Device.java
+++ b/Terminal/src/device/Device.java
@@ -1,39 +1,40 @@
package device;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Vector;
public class Device {
String ID;
Hashtable<String, Object> props;
Vector<Service> services = new Vector<Service>();
@SuppressWarnings("unchecked")
public Device(Hashtable<String, Object> device_info) {
props = device_info;
ID = (String) device_info.get("UPnP.device.UDN");
Hashtable<String, ArrayList<Object>> Services =
(Hashtable<String, ArrayList<Object>>) device_info.get("Device Services");
for (String key : Services.keySet()) {
services.add(new Service(ID, key, Services.get(key)));
}
props.remove("Device Services");
props.remove("objectClass");
props.remove("UPnP");
props.remove("UPNP_SERVICE_ID");
+ props.remove("UPNP_SERVICE_TYPE");
}
public Vector<Service> getServices() {
return services;
}
public Hashtable<String, Object> getDeviceInfo() {
return props;
}
public String getName() {
return props.get("UPnP.device.modelName").toString();
}
}
| true | true | public Device(Hashtable<String, Object> device_info) {
props = device_info;
ID = (String) device_info.get("UPnP.device.UDN");
Hashtable<String, ArrayList<Object>> Services =
(Hashtable<String, ArrayList<Object>>) device_info.get("Device Services");
for (String key : Services.keySet()) {
services.add(new Service(ID, key, Services.get(key)));
}
props.remove("Device Services");
props.remove("objectClass");
props.remove("UPnP");
props.remove("UPNP_SERVICE_ID");
}
| public Device(Hashtable<String, Object> device_info) {
props = device_info;
ID = (String) device_info.get("UPnP.device.UDN");
Hashtable<String, ArrayList<Object>> Services =
(Hashtable<String, ArrayList<Object>>) device_info.get("Device Services");
for (String key : Services.keySet()) {
services.add(new Service(ID, key, Services.get(key)));
}
props.remove("Device Services");
props.remove("objectClass");
props.remove("UPnP");
props.remove("UPNP_SERVICE_ID");
props.remove("UPNP_SERVICE_TYPE");
}
|
diff --git a/src/org/apache/xalan/xsltc/trax/TransformerFactoryImpl.java b/src/org/apache/xalan/xsltc/trax/TransformerFactoryImpl.java
index 9c8daa7d..d7df3b28 100644
--- a/src/org/apache/xalan/xsltc/trax/TransformerFactoryImpl.java
+++ b/src/org/apache/xalan/xsltc/trax/TransformerFactoryImpl.java
@@ -1,721 +1,713 @@
/*
* @(#)$Id$
*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 2001, Sun
* Microsystems., http://www.sun.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* @author G. Todd Miller
* @author Morten Jorgensen
*
*/
package org.apache.xalan.xsltc.trax;
import java.io.File;
import java.io.Reader;
import java.io.InputStream;
import java.io.ByteArrayInputStream;
import java.net.URL;
import java.net.MalformedURLException;
import java.util.Vector;
import java.util.Hashtable;
import javax.xml.transform.*;
import javax.xml.transform.sax.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
import org.w3c.dom.Document;
import org.xml.sax.XMLFilter;
import org.xml.sax.InputSource;
import org.apache.xalan.xsltc.Translet;
import org.apache.xalan.xsltc.runtime.AbstractTranslet;
import org.apache.xalan.xsltc.compiler.XSLTC;
import org.apache.xalan.xsltc.compiler.SourceLoader;
import org.apache.xalan.xsltc.compiler.CompilerException;
import org.apache.xalan.xsltc.compiler.util.Util;
import org.apache.xalan.xsltc.compiler.util.ErrorMsg;
/**
* Implementation of a JAXP1.1 TransformerFactory for Translets.
*/
public class TransformerFactoryImpl
extends SAXTransformerFactory implements SourceLoader, ErrorListener {
// This error listener is used only for this factory and is not passed to
// the Templates or Transformer objects that we create!!!
private ErrorListener _errorListener = this;
// This URIResolver is passed to all created Templates and Transformers
private URIResolver _uriResolver = null;
// As Gregor Samsa awoke one morning from uneasy dreams he found himself
// transformed in his bed into a gigantic insect. He was lying on his hard,
// as it were armour plated, back, and if he lifted his head a little he
// could see his big, brown belly divided into stiff, arched segments, on
// top of which the bed quilt could hardly keep in position and was about
// to slide off completely. His numerous legs, which were pitifully thin
// compared to the rest of his bulk, waved helplessly before his eyes.
// "What has happened to me?", he thought. It was no dream....
protected static String _defaultTransletName = "GregorSamsa";
// Cache for the newTransformer() method - see method for details
private Transformer _copyTransformer = null;
// XSL document for the default transformer
private static final String COPY_TRANSLET_CODE =
"<xsl:stylesheet xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">"+
"<xsl:template match=\"/\">"+
" <xsl:copy-of select=\".\"/>"+
"</xsl:template>"+
"</xsl:stylesheet>";
// This Hashtable is used to store parameters for locating
// <?xml-stylesheet ...?> processing instructions in XML documents.
private Hashtable _piParams = null;
// The above hashtable stores objects of this class only:
private class PIParamWrapper {
public String _media = null;
public String _title = null;
public String _charset = null;
public PIParamWrapper(String media, String title, String charset) {
_media = media;
_title = title;
_charset = charset;
}
}
// This flag is passed to the compiler - will produce stack traces etc.
private boolean _debug = false;
/**
* javax.xml.transform.sax.TransformerFactory implementation.
* Contains nothing yet
*/
public TransformerFactoryImpl() {
// Don't need anything here so far...
}
/**
* javax.xml.transform.sax.TransformerFactory implementation.
* Set the error event listener for the TransformerFactory, which is used
* for the processing of transformation instructions, and not for the
* transformation itself.
*
* @param listener The error listener to use with the TransformerFactory
* @throws IllegalArgumentException
*/
public void setErrorListener(ErrorListener listener)
throws IllegalArgumentException {
if (listener == null) {
ErrorMsg err = new ErrorMsg(ErrorMsg.ERROR_LISTENER_NULL_ERR,
"TransformerFactory");
throw new IllegalArgumentException(err.toString());
}
_errorListener = listener;
}
/**
* javax.xml.transform.sax.TransformerFactory implementation.
* Get the error event handler for the TransformerFactory.
*
* @return The error listener used with the TransformerFactory
*/
public ErrorListener getErrorListener() {
return _errorListener;
}
/**
* javax.xml.transform.sax.TransformerFactory implementation.
* Returns the value set for a TransformerFactory attribute
*
* @param name The attribute name
* @return An object representing the attribute value
* @throws IllegalArgumentException
*/
public Object getAttribute(String name)
throws IllegalArgumentException {
// Return value for attribute 'translet-name'
if (name.equals("translet-name")) return(_defaultTransletName);
// Throw an exception for all other attributes
ErrorMsg err = new ErrorMsg(ErrorMsg.JAXP_INVALID_ATTR_ERR, name);
throw new IllegalArgumentException(err.toString());
}
/**
* javax.xml.transform.sax.TransformerFactory implementation.
* Sets the value for a TransformerFactory attribute.
*
* @param name The attribute name
* @param value An object representing the attribute value
* @throws IllegalArgumentException
*/
public void setAttribute(String name, Object value)
throws IllegalArgumentException {
// Set the default translet name (ie. class name), which will be used
// for translets that cannot be given a name from their system-id.
if ((name.equals("translet-name")) && (value instanceof String)) {
_defaultTransletName = (String)value;
}
else if (name.equals("debug")) {
_debug = true;
}
else {
// Throw an exception for all other attributes
ErrorMsg err = new ErrorMsg(ErrorMsg.JAXP_INVALID_ATTR_ERR, name);
throw new IllegalArgumentException(err.toString());
}
}
/**
* javax.xml.transform.sax.TransformerFactory implementation.
* Look up the value of a feature (to see if it is supported).
* This method must be updated as the various methods and features of this
* class are implemented.
*
* @param name The feature name
* @return 'true' if feature is supported, 'false' if not
*/
public boolean getFeature(String name) {
// All supported features should be listed here
String[] features = {
DOMSource.FEATURE,
DOMResult.FEATURE,
SAXSource.FEATURE,
SAXResult.FEATURE,
StreamSource.FEATURE,
StreamResult.FEATURE
};
// Inefficient, but it really does not matter in a function like this
for (int i=0; i<features.length; i++)
if (name.equals(features[i])) return true;
// Feature not supported
return false;
}
/**
* javax.xml.transform.sax.TransformerFactory implementation.
* Get the object that is used by default during the transformation to
* resolve URIs used in document(), xsl:import, or xsl:include.
*
* @return The URLResolver used for this TransformerFactory and all
* Templates and Transformer objects created using this factory
*/
public URIResolver getURIResolver() {
return(_uriResolver);
}
/**
* javax.xml.transform.sax.TransformerFactory implementation.
* Set the object that is used by default during the transformation to
* resolve URIs used in document(), xsl:import, or xsl:include. Note that
* this does not affect Templates and Transformers that are already
* created with this factory.
*
* @param resolver The URLResolver used for this TransformerFactory and all
* Templates and Transformer objects created using this factory
*/
public void setURIResolver(URIResolver resolver) {
_uriResolver = resolver;
}
/**
* javax.xml.transform.sax.TransformerFactory implementation.
* Get the stylesheet specification(s) associated via the xml-stylesheet
* processing instruction (see http://www.w3.org/TR/xml-stylesheet/) with
* the document document specified in the source parameter, and that match
* the given criteria.
*
* @param source The XML source document.
* @param media The media attribute to be matched. May be null, in which
* case the prefered templates will be used (i.e. alternate = no).
* @param title The value of the title attribute to match. May be null.
* @param charset The value of the charset attribute to match. May be null.
* @return A Source object suitable for passing to the TransformerFactory.
* @throws TransformerConfigurationException
*/
public Source getAssociatedStylesheet(Source source, String media,
String title, String charset)
throws TransformerConfigurationException {
// First create a hashtable that maps Source refs. to parameters
if (_piParams == null) _piParams = new Hashtable();
// Store the parameters for this Source in the Hashtable
_piParams.put(source, new PIParamWrapper(media, title, charset));
// Return the same Source - we'll locate the stylesheet later
return(source);
}
/**
* javax.xml.transform.sax.TransformerFactory implementation.
* Create a Transformer object that copies the input document to the result.
*
* @return A Transformer object that simply copies the source to the result.
* @throws TransformerConfigurationException
*/
public Transformer newTransformer()
throws TransformerConfigurationException {
if (_copyTransformer != null) {
if (_uriResolver != null)
_copyTransformer.setURIResolver(_uriResolver);
return _copyTransformer;
}
XSLTC xsltc = new XSLTC();
if (_debug) xsltc.setDebug(true);
xsltc.init();
// Compile the default copy-stylesheet
byte[] bytes = COPY_TRANSLET_CODE.getBytes();
ByteArrayInputStream bytestream = new ByteArrayInputStream(bytes);
InputSource input = new InputSource(bytestream);
input.setSystemId(_defaultTransletName);
byte[][] bytecodes = xsltc.compile(_defaultTransletName, input);
// Check that the transformation went well before returning
if (bytecodes == null) {
ErrorMsg err = new ErrorMsg(ErrorMsg.JAXP_COMPILE_ERR);
throw new TransformerConfigurationException(err.toString());
}
// Create a Transformer object and store for other calls
Templates templates = new TemplatesImpl(bytecodes,_defaultTransletName);
_copyTransformer = templates.newTransformer();
if (_uriResolver != null) _copyTransformer.setURIResolver(_uriResolver);
return(_copyTransformer);
}
/**
* javax.xml.transform.sax.TransformerFactory implementation.
* Process the Source into a Templates object, which is a a compiled
* representation of the source. Note that this method should not be
* used with XSLTC, as the time-consuming compilation is done for each
* and every transformation.
*
* @return A Templates object that can be used to create Transformers.
* @throws TransformerConfigurationException
*/
public Transformer newTransformer(Source source) throws
TransformerConfigurationException {
final Templates templates = newTemplates(source);
final Transformer transformer = templates.newTransformer();
if (_uriResolver != null) transformer.setURIResolver(_uriResolver);
return(transformer);
}
/**
* Pass warning messages from the compiler to the error listener
*/
private void passWarningsToListener(Vector messages) {
try {
// Nothing to do if there is no registered error listener
if (_errorListener == null) return;
// Nothing to do if there are not warning messages
if (messages == null) return;
// Pass messages to listener, one by one
final int count = messages.size();
for (int pos=0; pos<count; pos++) {
String message = messages.elementAt(pos).toString();
_errorListener.warning(new TransformerException(message));
}
}
catch (TransformerException e) {
// nada
}
}
/**
* Pass error messages from the compiler to the error listener
*/
private void passErrorsToListener(Vector messages) {
try {
// Nothing to do if there is no registered error listener
if (_errorListener == null) return;
// Nothing to do if there are not warning messages
if (messages == null) return;
// Pass messages to listener, one by one
final int count = messages.size();
for (int pos=0; pos<count; pos++) {
String message = messages.elementAt(pos).toString();
_errorListener.error(new TransformerException(message));
}
}
catch (TransformerException e) {
// nada
}
}
/**
* Creates a SAX2 InputSource object from a TrAX Source object
*/
private InputSource getInputSource(XSLTC xsltc, Source source)
throws TransformerConfigurationException {
InputSource input = null;
String systemId = source.getSystemId();
- if (systemId == null) {
- systemId = "";
- }
+ if (systemId == null) ystemId = "";
try {
// Try to get InputSource from SAXSource input
if (source instanceof SAXSource) {
final SAXSource sax = (SAXSource)source;
input = sax.getInputSource();
// Pass the SAX parser to the compiler
xsltc.setXMLReader(sax.getXMLReader());
}
// handle DOMSource
else if (source instanceof DOMSource) {
final DOMSource domsrc = (DOMSource)source;
final Document dom = (Document)domsrc.getNode();
final DOM2SAX dom2sax = new DOM2SAX(dom);
xsltc.setXMLReader(dom2sax);
// try to get SAX InputSource from DOM Source.
input = SAXSource.sourceToInputSource(source);
}
// Try to get InputStream or Reader from StreamSource
else if (source instanceof StreamSource) {
final StreamSource stream = (StreamSource)source;
final InputStream istream = stream.getInputStream();
final Reader reader = stream.getReader();
// Create InputSource from Reader or InputStream in Source
if (istream != null)
input = new InputSource(istream);
else if (reader != null)
input = new InputSource(reader);
- else if ((new File(systemId)).exists()) {
- input = new InputSource(
- new File(systemId).toURL().toExternalForm());
- }
+ else
+ input = new InputSource(systemId);
}
else {
ErrorMsg err = new ErrorMsg(ErrorMsg.JAXP_UNKNOWN_SOURCE_ERR);
throw new TransformerConfigurationException(err.toString());
}
input.setSystemId(systemId);
}
catch (NullPointerException e) {
ErrorMsg err = new ErrorMsg(ErrorMsg.JAXP_NO_SOURCE_ERR,
"TransformerFactory.newTemplates()");
throw new TransformerConfigurationException(err.toString());
}
catch (SecurityException e) {
ErrorMsg err = new ErrorMsg(ErrorMsg.FILE_ACCESS_ERR, systemId);
throw new TransformerConfigurationException(err.toString());
}
- catch (MalformedURLException e){
- ErrorMsg err = new ErrorMsg(ErrorMsg.FILE_ACCESS_ERR, systemId);
- throw new TransformerConfigurationException(err.toString());
- }
finally {
return(input);
}
}
/**
* javax.xml.transform.sax.TransformerFactory implementation.
* Process the Source into a Templates object, which is a a compiled
* representation of the source.
*
* @param stylesheet The input stylesheet - DOMSource not supported!!!
* @return A Templates object that can be used to create Transformers.
* @throws TransformerConfigurationException
*/
public Templates newTemplates(Source source)
throws TransformerConfigurationException {
// Create and initialize a stylesheet compiler
final XSLTC xsltc = new XSLTC();
if (_debug) xsltc.setDebug(true);
xsltc.init();
// Set a document loader (for xsl:include/import) if defined
if (_uriResolver != null) xsltc.setSourceLoader(this);
// Pass parameters to the Parser to make sure it locates the correct
// <?xml-stylesheet ...?> PI in an XML input document
if ((_piParams != null) && (_piParams.get(source) != null)) {
// Get the parameters for this Source object
PIParamWrapper p = (PIParamWrapper)_piParams.get(source);
// Pass them on to the compiler (which will pass then to the parser)
if (p != null)
xsltc.setPIParameters(p._media, p._title, p._charset);
}
// Compile the stylesheet
final InputSource input = getInputSource(xsltc, source);
byte[][] bytecodes = xsltc.compile(null, input);
final String transletName = xsltc.getClassName();
// Pass compiler warnings to the error listener
if (_errorListener != null)
passWarningsToListener(xsltc.getWarnings());
else
xsltc.printWarnings();
// Check that the transformation went well before returning
if (bytecodes == null) {
// Pass compiler errors to the error listener
if (_errorListener != null)
passErrorsToListener(xsltc.getErrors());
else
xsltc.printErrors();
ErrorMsg err = new ErrorMsg(ErrorMsg.JAXP_COMPILE_ERR);
throw new TransformerConfigurationException(err.toString());
}
return(new TemplatesImpl(bytecodes, transletName));
}
/**
* javax.xml.transform.sax.SAXTransformerFactory implementation.
* Get a TemplatesHandler object that can process SAX ContentHandler
* events into a Templates object.
*
* @return A TemplatesHandler object that can handle SAX events
* @throws TransformerConfigurationException
*/
public TemplatesHandler newTemplatesHandler()
throws TransformerConfigurationException {
return(new TemplatesHandlerImpl());
}
/**
* javax.xml.transform.sax.SAXTransformerFactory implementation.
* Get a TransformerHandler object that can process SAX ContentHandler
* events into a Result. This method will return a pure copy transformer.
*
* @return A TransformerHandler object that can handle SAX events
* @throws TransformerConfigurationException
*/
public TransformerHandler newTransformerHandler()
throws TransformerConfigurationException {
final Transformer transformer = newTransformer();
final TransformerImpl internal = (TransformerImpl)transformer;
return(new TransformerHandlerImpl(internal));
}
/**
* javax.xml.transform.sax.SAXTransformerFactory implementation.
* Get a TransformerHandler object that can process SAX ContentHandler
* events into a Result, based on the transformation instructions
* specified by the argument.
*
* @param src The source of the transformation instructions.
* @return A TransformerHandler object that can handle SAX events
* @throws TransformerConfigurationException
*/
public TransformerHandler newTransformerHandler(Source src)
throws TransformerConfigurationException {
final Transformer transformer = newTransformer(src);
final TransformerImpl internal = (TransformerImpl)transformer;
return(new TransformerHandlerImpl(internal));
}
/**
* javax.xml.transform.sax.SAXTransformerFactory implementation.
* Get a TransformerHandler object that can process SAX ContentHandler
* events into a Result, based on the transformation instructions
* specified by the argument.
*
* @param templates Represents a pre-processed stylesheet
* @return A TransformerHandler object that can handle SAX events
* @throws TransformerConfigurationException
*/
public TransformerHandler newTransformerHandler(Templates templates)
throws TransformerConfigurationException {
final Transformer transformer = templates.newTransformer();
final TransformerImpl internal = (TransformerImpl)transformer;
return(new TransformerHandlerImpl(internal));
}
/**
* javax.xml.transform.sax.SAXTransformerFactory implementation.
* Create an XMLFilter that uses the given source as the
* transformation instructions.
*
* @param src The source of the transformation instructions.
* @return An XMLFilter object, or null if this feature is not supported.
* @throws TransformerConfigurationException
*/
public XMLFilter newXMLFilter(Source src)
throws TransformerConfigurationException {
Templates templates = newTemplates(src);
if (templates == null ) return null;
return newXMLFilter(templates);
}
/**
* javax.xml.transform.sax.SAXTransformerFactory implementation.
* Create an XMLFilter that uses the given source as the
* transformation instructions.
*
* @param src The source of the transformation instructions.
* @return An XMLFilter object, or null if this feature is not supported.
* @throws TransformerConfigurationException
*/
public XMLFilter newXMLFilter(Templates templates)
throws TransformerConfigurationException {
try {
return new org.apache.xalan.xsltc.trax.TrAXFilter(templates);
}
catch(TransformerConfigurationException e1) {
if(_errorListener != null) {
try {
_errorListener.fatalError(e1);
return null;
}
catch( TransformerException e2) {
new TransformerConfigurationException(e2);
}
}
throw e1;
}
}
/**
* This method implements XSLTC's SourceLoader interface. It is used to
* glue a TrAX URIResolver to the XSLTC compiler's Input and Import classes.
*
* @param href The URI of the document to load
* @param context The URI of the currently loaded document
* @param xsltc The compiler that resuests the document
* @return An InputSource with the loaded document
*/
public InputSource loadSource(String href, String context, XSLTC xsltc) {
try {
final Source source = _uriResolver.resolve(href, context);
final InputSource input = getInputSource(xsltc, source);
return(input);
}
catch (TransformerConfigurationException e) {
return null;
}
catch (TransformerException e) {
return null;
}
}
/**
* Receive notification of a recoverable error.
* The transformer must continue to provide normal parsing events after
* invoking this method. It should still be possible for the application
* to process the document through to the end.
*
* @param exception The warning information encapsulated in a transformer
* exception.
* @throws TransformerException if the application chooses to discontinue
* the transformation (always does in our case).
*/
public void error(TransformerException e)
throws TransformerException {
System.err.println("ERROR: "+e.getMessageAndLocation());
Throwable wrapped = e.getException();
if (wrapped != null)
System.err.println(" : "+wrapped.getMessage());
throw(e);
}
/**
* Receive notification of a non-recoverable error.
* The application must assume that the transformation cannot continue
* after the Transformer has invoked this method, and should continue
* (if at all) only to collect addition error messages. In fact,
* Transformers are free to stop reporting events once this method has
* been invoked.
*
* @param exception The warning information encapsulated in a transformer
* exception.
* @throws TransformerException if the application chooses to discontinue
* the transformation (always does in our case).
*/
public void fatalError(TransformerException e)
throws TransformerException {
System.err.println("FATAL: "+e.getMessageAndLocation());
Throwable wrapped = e.getException();
if (wrapped != null)
System.err.println(" : "+wrapped.getMessage());
throw(e);
}
/**
* Receive notification of a warning.
* Transformers can use this method to report conditions that are not
* errors or fatal errors. The default behaviour is to take no action.
* After invoking this method, the Transformer must continue with the
* transformation. It should still be possible for the application to
* process the document through to the end.
*
* @param exception The warning information encapsulated in a transformer
* exception.
* @throws TransformerException if the application chooses to discontinue
* the transformation (never does in our case).
*/
public void warning(TransformerException e)
throws TransformerException {
System.err.println("WARNING: "+e.getMessageAndLocation());
Throwable wrapped = e.getException();
if (wrapped != null)
System.err.println(" : "+wrapped.getMessage());
}
}
| false | true | private InputSource getInputSource(XSLTC xsltc, Source source)
throws TransformerConfigurationException {
InputSource input = null;
String systemId = source.getSystemId();
if (systemId == null) {
systemId = "";
}
try {
// Try to get InputSource from SAXSource input
if (source instanceof SAXSource) {
final SAXSource sax = (SAXSource)source;
input = sax.getInputSource();
// Pass the SAX parser to the compiler
xsltc.setXMLReader(sax.getXMLReader());
}
// handle DOMSource
else if (source instanceof DOMSource) {
final DOMSource domsrc = (DOMSource)source;
final Document dom = (Document)domsrc.getNode();
final DOM2SAX dom2sax = new DOM2SAX(dom);
xsltc.setXMLReader(dom2sax);
// try to get SAX InputSource from DOM Source.
input = SAXSource.sourceToInputSource(source);
}
// Try to get InputStream or Reader from StreamSource
else if (source instanceof StreamSource) {
final StreamSource stream = (StreamSource)source;
final InputStream istream = stream.getInputStream();
final Reader reader = stream.getReader();
// Create InputSource from Reader or InputStream in Source
if (istream != null)
input = new InputSource(istream);
else if (reader != null)
input = new InputSource(reader);
else if ((new File(systemId)).exists()) {
input = new InputSource(
new File(systemId).toURL().toExternalForm());
}
}
else {
ErrorMsg err = new ErrorMsg(ErrorMsg.JAXP_UNKNOWN_SOURCE_ERR);
throw new TransformerConfigurationException(err.toString());
}
input.setSystemId(systemId);
}
catch (NullPointerException e) {
ErrorMsg err = new ErrorMsg(ErrorMsg.JAXP_NO_SOURCE_ERR,
"TransformerFactory.newTemplates()");
throw new TransformerConfigurationException(err.toString());
}
catch (SecurityException e) {
ErrorMsg err = new ErrorMsg(ErrorMsg.FILE_ACCESS_ERR, systemId);
throw new TransformerConfigurationException(err.toString());
}
catch (MalformedURLException e){
ErrorMsg err = new ErrorMsg(ErrorMsg.FILE_ACCESS_ERR, systemId);
throw new TransformerConfigurationException(err.toString());
}
finally {
return(input);
}
}
| private InputSource getInputSource(XSLTC xsltc, Source source)
throws TransformerConfigurationException {
InputSource input = null;
String systemId = source.getSystemId();
if (systemId == null) ystemId = "";
try {
// Try to get InputSource from SAXSource input
if (source instanceof SAXSource) {
final SAXSource sax = (SAXSource)source;
input = sax.getInputSource();
// Pass the SAX parser to the compiler
xsltc.setXMLReader(sax.getXMLReader());
}
// handle DOMSource
else if (source instanceof DOMSource) {
final DOMSource domsrc = (DOMSource)source;
final Document dom = (Document)domsrc.getNode();
final DOM2SAX dom2sax = new DOM2SAX(dom);
xsltc.setXMLReader(dom2sax);
// try to get SAX InputSource from DOM Source.
input = SAXSource.sourceToInputSource(source);
}
// Try to get InputStream or Reader from StreamSource
else if (source instanceof StreamSource) {
final StreamSource stream = (StreamSource)source;
final InputStream istream = stream.getInputStream();
final Reader reader = stream.getReader();
// Create InputSource from Reader or InputStream in Source
if (istream != null)
input = new InputSource(istream);
else if (reader != null)
input = new InputSource(reader);
else
input = new InputSource(systemId);
}
else {
ErrorMsg err = new ErrorMsg(ErrorMsg.JAXP_UNKNOWN_SOURCE_ERR);
throw new TransformerConfigurationException(err.toString());
}
input.setSystemId(systemId);
}
catch (NullPointerException e) {
ErrorMsg err = new ErrorMsg(ErrorMsg.JAXP_NO_SOURCE_ERR,
"TransformerFactory.newTemplates()");
throw new TransformerConfigurationException(err.toString());
}
catch (SecurityException e) {
ErrorMsg err = new ErrorMsg(ErrorMsg.FILE_ACCESS_ERR, systemId);
throw new TransformerConfigurationException(err.toString());
}
finally {
return(input);
}
}
|
diff --git a/openejb0/src/main/org/openejb/core/entity/EntityEjbHomeHandler.java b/openejb0/src/main/org/openejb/core/entity/EntityEjbHomeHandler.java
index b62601e10..bdf607f1e 100644
--- a/openejb0/src/main/org/openejb/core/entity/EntityEjbHomeHandler.java
+++ b/openejb0/src/main/org/openejb/core/entity/EntityEjbHomeHandler.java
@@ -1,302 +1,302 @@
/**
* Redistribution and use of this software and associated documentation
* ("Software"), with or without modification, are permitted provided
* that the following conditions are met:
*
* 1. Redistributions of source code must retain copyright
* statements and notices. Redistributions must also contain a
* copy of this document.
*
* 2. Redistributions in binary form must reproduce the
* above copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. The name "Exolab" must not be used to endorse or promote
* products derived from this Software without prior written
* permission of Exoffice Technologies. For written permission,
* please contact [email protected].
*
* 4. Products derived from this Software may not be called "Exolab"
* nor may "Exolab" appear in their names without prior written
* permission of Exoffice Technologies. Exolab is a registered
* trademark of Exoffice Technologies.
*
* 5. Due credit should be given to the Exolab Project
* (http://www.exolab.org/).
*
* THIS SOFTWARE IS PROVIDED BY EXOFFICE TECHNOLOGIES AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT
* NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* EXOFFICE TECHNOLOGIES OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Copyright 1999 (C) Exoffice Technologies Inc. All Rights Reserved.
*
* $Id$
*/
package org.openejb.core.entity;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.rmi.RemoteException;
import java.security.Principal;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
import javax.ejb.EJBHome;
import org.openejb.DeploymentInfo;
import org.openejb.InvalidateReferenceException;
import org.openejb.OpenEJB;
import org.openejb.OpenEJBException;
import org.openejb.ProxyInfo;
import org.openejb.RpcContainer;
import org.openejb.core.ThreadContext;
import org.openejb.core.ivm.EjbHomeProxyHandler;
import org.openejb.core.ivm.EjbObjectProxyHandler;
import org.openejb.core.ivm.IntraVmHandle;
import org.openejb.core.ivm.IntraVmMetaData;
import org.openejb.util.proxy.InvalidatedReferenceHandler;
import org.openejb.util.proxy.InvocationHandler;
import org.openejb.util.proxy.InvocationHandler;
import org.openejb.util.proxy.ProxyManager;
/**
* This InvocationHandler and its proxy are serializable and can be used by
* HomeHandle, Handle, and MetaData to persist and revive handles. It maintains
* its original client identity which allows the container to be more discerning about
* allowing the revieed proxy to be used. See StatefulContaer manager for more details.
*
* @author <a href="mailto:[email protected]">David Blevins</a>
* @author <a href="mailto:[email protected]">Richard Monson-Haefel</a>
*/
public class EntityEjbHomeHandler extends EjbHomeProxyHandler {
public EntityEjbHomeHandler(RpcContainer container, Object pk, Object depID){
super(container, pk, depID);
}
protected Object createProxy(ProxyInfo proxyInfo){
Object proxy = super.createProxy(proxyInfo);
EjbObjectProxyHandler handler = (EjbObjectProxyHandler)ProxyManager.getInvocationHandler(proxy);
/*
* Register the handle with the BaseEjbProxyHandler.liveHandleRegistry
* If the bean is removed by its home or by an identical proxy, then the
* this proxy will be automatically invalidated because its properly registered
* with the liveHandleRegistry.
*/
registerHandler(handler.getRegistryId(),handler);
return proxy;
}
/**
* <P>
* Locates and returns a new EJBObject or a collection
* of EJBObjects. The EJBObject(s) is a new proxy with
* a new handler. This implementation should not be
* sent outside the virtual machine.
* </P>
* <P>
* This method propogates to the container
* system.
* </P>
* <P>
* The find method is required to be defined
* by the bean's home interface of Entity beans.
* </P>
*
* @param method
* @param args
* @param proxy
* @return Returns an new EJBObject proxy and handler
* @exception Throwable
*/
/**
* <P>
* Locates and returns a new EJBObject or a collection
* of EJBObjects. The EJBObject(s) is a new proxy with
* a new handler. This implementation should not be
* sent outside the virtual machine.
* </P>
* <P>
* This method propogates to the container
* system.
* </P>
* <P>
* The find method is required to be defined
* by the bean's home interface of Entity beans.
* </P>
*
* @param method
* @param args
* @param proxy
* @return Returns an new EJBObject proxy and handler
* @exception Throwable
*/
protected Object findX(Method method, Object[] args, Object proxy) throws Throwable {
Object retValue = container.invoke(deploymentID,method,args,null, getThreadSpecificSecurityIdentity());
if ( retValue instanceof java.util.Collection ) {
Object [] proxyInfos = ((java.util.Collection)retValue).toArray();
Vector proxies = new Vector();
for ( int i = 0; i < proxyInfos.length; i++ ) {
proxies.addElement( createProxy((ProxyInfo)proxyInfos[i]) );
}
if(method.getReturnType() == Enumeration.class){
/*
FIXME: This needs to change for two reasons:
a) Although we know the core containers return a Vector we shouldn't assume that
b) The Vector's impl of Enumeration is not serializable.
*/
- return ((java.util.Vector)proxies).elements();
+ return new org.openejb.util.ArrayEnumeration(proxies);
}else
return proxies;// vector is a type of Collection.
} else {
org.openejb.ProxyInfo proxyInfo = (org.openejb.ProxyInfo)
container.invoke(deploymentID,method,args,null, getThreadSpecificSecurityIdentity());
return createProxy(proxyInfo);
}
}
/**
* <P>
* Attempts to remove an EJBObject from the
* container system. The EJBObject to be removed
* is represented by the primaryKey passed
* into the remove method of the EJBHome.
* </P>
* <P>
* This method propogates to the container system.
* </P>
* <P>
* remove(Object primary) is a method of javax.ejb.EJBHome
* </P>
* <P>
* Checks if the caller is authorized to invoke the
* javax.ejb.EJBHome.remove on the EJBHome of the
* deployment.
* </P>
*
* @param method
* @param args
* @return Returns null
* @exception Throwable
* @see javax.ejb.EJBHome
* @see javax.ejb.EJBHome#remove
*/
protected Object removeByPrimaryKey(Method method, Object[] args, Object proxy) throws Throwable{
checkAuthorization(method);
Object primKey = args[0];
container.invoke(deploymentID, method, args, primKey, getThreadSpecificSecurityIdentity());
/*
* This operation takes care of invalidating all the EjbObjectProxyHanders associated with
* the same RegistryId. See this.createProxy().
*/
invalidateAllHandlers(EntityEjbObjectHandler.getRegistryId(primKey,deploymentID,container));
return null;
}
/**
* <P>
* Attempts to remove an EJBObject from the
* container system. The EJBObject to be removed
* is represented by the javax.ejb.Handle object passed
* into the remove method in the EJBHome.
* </P>
* <P>
* This method propogates to the container system.
* </P>
* <P>
* remove(Handle handle) is a method of javax.ejb.EJBHome
* </P>
* <P>
* Checks if the caller is authorized to invoke the
* javax.ejb.EJBHome.remove on the EJBHome of the
* deployment.
* </P>
*
* @param method
* @param args
* @return Returns null
* @exception Throwable
* @see javax.ejb.EJBHome
* @see javax.ejb.EJBHome#remove
*/
protected Object removeWithHandle(Method method, Object[] args, Object proxy) throws Throwable{
checkAuthorization(method);
// Extract the primary key from the handle
IntraVmHandle handle = (IntraVmHandle)args[0];
EjbObjectProxyHandler stub = (EjbObjectProxyHandler)ProxyManager.getInvocationHandler(handle.theProxy);
Object primKey = stub.primaryKey;
// invoke the remove on the container
container.invoke(deploymentID, method, args, primKey, ThreadContext.getThreadContext().getSecurityIdentity());
/*
* This operation takes care of invalidating all the EjbObjectProxyHanders associated with
* the same RegistryId. See this.createProxy().
*/
invalidateAllHandlers(stub.getRegistryId());
return null;
}
/*-------------------------------------------------*/
/* EJBHome methods */
/*-------------------------------------------------*/
/**
* <P>
* Returns an EJBMetaData implementation that is
* valid inside this virtual machine. This
* implementation should not be sent outside the
* virtual machine.
* </P>
* <P>
* This method does not propogate to the container
* system.
* </P>
* <P>
* getMetaData is a method of javax.ejb.EJBHome
* </P>
* <P>
* Checks if the caller is authorized to invoke the
* javax.ejb.EJBHome.getMetaData on the EJBHome of the
* deployment.
* </P>
*
* @return Returns an IntraVmMetaData
* @exception Throwable
* @see IntraVmMetaData
* @see javax.ejb.EJBHome
* @see javax.ejb.EJBHome#getEJBMetaData
*/
protected Object getEJBMetaData(Method method, Object[] args, Object proxy) throws Throwable {
checkAuthorization(method);
byte compType = IntraVmMetaData.ENTITY;
// component type is identified outside the IntraVmMetaData so that IntraVmMetaData doesn't reference DeploymentInfo avoiding the need to load the DeploymentInfo class into the client VM.
IntraVmMetaData metaData = new IntraVmMetaData(deploymentInfo.getHomeInterface(), deploymentInfo.getRemoteInterface(),deploymentInfo.getPrimaryKeyClass(),compType);
metaData.setEJBHome((EJBHome)proxy);
return metaData;
}
protected EjbObjectProxyHandler newEjbObjectHandler(RpcContainer container, Object pk, Object depID) {
return new EntityEjbObjectHandler(container, pk, depID);
}
}
| true | true | protected Object findX(Method method, Object[] args, Object proxy) throws Throwable {
Object retValue = container.invoke(deploymentID,method,args,null, getThreadSpecificSecurityIdentity());
if ( retValue instanceof java.util.Collection ) {
Object [] proxyInfos = ((java.util.Collection)retValue).toArray();
Vector proxies = new Vector();
for ( int i = 0; i < proxyInfos.length; i++ ) {
proxies.addElement( createProxy((ProxyInfo)proxyInfos[i]) );
}
if(method.getReturnType() == Enumeration.class){
/*
FIXME: This needs to change for two reasons:
a) Although we know the core containers return a Vector we shouldn't assume that
b) The Vector's impl of Enumeration is not serializable.
*/
return ((java.util.Vector)proxies).elements();
}else
return proxies;// vector is a type of Collection.
} else {
org.openejb.ProxyInfo proxyInfo = (org.openejb.ProxyInfo)
container.invoke(deploymentID,method,args,null, getThreadSpecificSecurityIdentity());
return createProxy(proxyInfo);
}
}
| protected Object findX(Method method, Object[] args, Object proxy) throws Throwable {
Object retValue = container.invoke(deploymentID,method,args,null, getThreadSpecificSecurityIdentity());
if ( retValue instanceof java.util.Collection ) {
Object [] proxyInfos = ((java.util.Collection)retValue).toArray();
Vector proxies = new Vector();
for ( int i = 0; i < proxyInfos.length; i++ ) {
proxies.addElement( createProxy((ProxyInfo)proxyInfos[i]) );
}
if(method.getReturnType() == Enumeration.class){
/*
FIXME: This needs to change for two reasons:
a) Although we know the core containers return a Vector we shouldn't assume that
b) The Vector's impl of Enumeration is not serializable.
*/
return new org.openejb.util.ArrayEnumeration(proxies);
}else
return proxies;// vector is a type of Collection.
} else {
org.openejb.ProxyInfo proxyInfo = (org.openejb.ProxyInfo)
container.invoke(deploymentID,method,args,null, getThreadSpecificSecurityIdentity());
return createProxy(proxyInfo);
}
}
|
diff --git a/src/jp/mitukiii/tumblife/parser/TLPostParser.java b/src/jp/mitukiii/tumblife/parser/TLPostParser.java
index 41b8112..63b297d 100644
--- a/src/jp/mitukiii/tumblife/parser/TLPostParser.java
+++ b/src/jp/mitukiii/tumblife/parser/TLPostParser.java
@@ -1,120 +1,124 @@
package jp.mitukiii.tumblife.parser;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import jp.mitukiii.tumblife.model.TLPost;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
public class TLPostParser extends TLParser
{
public TLPostParser(InputStream input)
throws XmlPullParserException
{
super(input);
}
public List<TLPost> parse()
throws NumberFormatException, XmlPullParserException, IOException
{
List<TLPost> posts = new ArrayList<TLPost>(50);
TLPost post = null;
for (int e = parser.getEventType(); e != XmlPullParser.END_DOCUMENT; e = parser.next()) {
String tag = parser.getName();
if (e == XmlPullParser.START_TAG) {
if ("post".equals(tag)) {
post = new TLPost();
post.setId(Long.valueOf(parser.getAttributeValue(NAME_SPACE, "id")));
post.setUrl(parser.getAttributeValue(NAME_SPACE, "url"));
post.setUrlWithSlug(parser.getAttributeValue(NAME_SPACE, "url-with-slug"));
post.setType(parser.getAttributeValue(NAME_SPACE, "type"));
post.setDateGmt(parser.getAttributeValue(NAME_SPACE, "date-gmt"));
post.setDate(parser.getAttributeValue(NAME_SPACE, "date"));
post.setUnixTimestamp(Integer.valueOf(parser.getAttributeValue(NAME_SPACE, "unix-timestamp")));
post.setFormat(parser.getAttributeValue(NAME_SPACE, "format"));
post.setReblogKey(parser.getAttributeValue(NAME_SPACE, "reblog-key"));
post.setSlug(parser.getAttributeValue(NAME_SPACE, "slug"));
String noteCount = parser.getAttributeValue(NAME_SPACE, "note-count");
if (noteCount == null || noteCount.length() == 0) {
post.setNoteCount(0);
} else {
post.setNoteCount(Integer.valueOf(noteCount));
}
post.setRebloggedFromUrl(parser.getAttributeValue(NAME_SPACE, "reblogged-from-url"));
post.setRebloggedFromName(parser.getAttributeValue(NAME_SPACE, "reblogged-from-name"));
post.setRebloggedFromTitle(parser.getAttributeValue(NAME_SPACE, "reblogged-from-title"));
} else if ("tumblelog".equals(tag)) {
post.setTumblelogTitle(parser.getAttributeValue(NAME_SPACE, "title"));
post.setTumblelogName(parser.getAttributeValue(NAME_SPACE, "name"));
post.setTumblelogUrl(parser.getAttributeValue(NAME_SPACE, "url"));
post.setTumblelogTimezone(parser.getAttributeValue(NAME_SPACE, "timezone"));
} else if ("tag".equals(tag)) {
post.setTag(parser.nextText());
} else if ("quote-text".equals(tag)) {
post.setQuoteText(parser.nextText());
} else if ("quote-source".equals(tag)) {
post.setQuoteSource(parser.nextText());
} else if ("photo-caption".equals(tag)) {
post.setPhotoCaption(parser.nextText());
} else if ("photo-link-url".equals(tag)) {
post.setPhotoLinkUrl(parser.nextText());
} else if ("photo-url".equals(tag)) {
String maxWidth = parser.getAttributeValue(NAME_SPACE, "max-width");
if ("1280".equals(maxWidth)) {
post.setPhotoUrlMaxWidth1280(parser.nextText());
} else if ("500".equals(maxWidth)) {
post.setPhotoUrlMaxWidth500(parser.nextText());
} else if ("400".equals(maxWidth)) {
post.setPhotoUrlMaxWidth400(parser.nextText());
} else if ("250".equals(maxWidth)) {
post.setPhotoUrlMaxWidth250(parser.nextText());
} else if ("100".equals(maxWidth)) {
post.setPhotoUrlMaxWidth100(parser.nextText());
} else if ("75".equals(maxWidth)) {
post.setPhotoUrlMaxWidth75(parser.nextText());
}
} else if ("link-text".equals(tag)) {
post.setLinkText(parser.nextText());
} else if ("link-url".equals(tag)) {
post.setLinkUrl(parser.nextText());
} else if ("link-description".equals(tag)) {
post.setLinkDescription(parser.nextText());
} else if ("conversation-title".equals(tag)) {
post.setConversationTitle(parser.nextText());
} else if ("conversation-text".equals(tag)) {
post.setConversationText(parser.nextText());
} else if ("line".equals(tag)) {
String beforeText = post.getConversation();
if (beforeText == null) {
beforeText = "";
}
post.setConversation(beforeText + "<p>" + parser.getAttributeValue(NAME_SPACE, "label") + parser.nextText() + "</p>");
} else if ("video-caption".equals(tag)) {
post.setVideoCaption(parser.nextText());
} else if ("video-source".equals(tag)) {
- post.setVideoSource(parser.nextText());
+ try {
+ post.setVideoSource(parser.nextText());
+ } catch (XmlPullParserException exception) {
+ // Raise error if contains meta info of video by XML.
+ }
} else if ("video-player".equals(tag)) {
post.setVideoPlayer(parser.nextText());
} else if ("audio-caption".equals(tag)) {
post.setAudioCaption(parser.nextText());
} else if ("audio-player".equals(tag)) {
post.setAudioPlayer(parser.nextText());
} else if ("download-url".equals(tag)) {
post.setDownloadUrl(parser.nextText());
} else if ("regular-title".equals(tag)) {
post.setRegularTitle(parser.nextText());
} else if ("regular-body".equals(tag)) {
post.setRegularBody(parser.nextText());
}
} else if (e == XmlPullParser.END_TAG) {
if ("post".equals(tag)) {
posts.add(post);
}
}
}
return posts;
}
}
| true | true | public List<TLPost> parse()
throws NumberFormatException, XmlPullParserException, IOException
{
List<TLPost> posts = new ArrayList<TLPost>(50);
TLPost post = null;
for (int e = parser.getEventType(); e != XmlPullParser.END_DOCUMENT; e = parser.next()) {
String tag = parser.getName();
if (e == XmlPullParser.START_TAG) {
if ("post".equals(tag)) {
post = new TLPost();
post.setId(Long.valueOf(parser.getAttributeValue(NAME_SPACE, "id")));
post.setUrl(parser.getAttributeValue(NAME_SPACE, "url"));
post.setUrlWithSlug(parser.getAttributeValue(NAME_SPACE, "url-with-slug"));
post.setType(parser.getAttributeValue(NAME_SPACE, "type"));
post.setDateGmt(parser.getAttributeValue(NAME_SPACE, "date-gmt"));
post.setDate(parser.getAttributeValue(NAME_SPACE, "date"));
post.setUnixTimestamp(Integer.valueOf(parser.getAttributeValue(NAME_SPACE, "unix-timestamp")));
post.setFormat(parser.getAttributeValue(NAME_SPACE, "format"));
post.setReblogKey(parser.getAttributeValue(NAME_SPACE, "reblog-key"));
post.setSlug(parser.getAttributeValue(NAME_SPACE, "slug"));
String noteCount = parser.getAttributeValue(NAME_SPACE, "note-count");
if (noteCount == null || noteCount.length() == 0) {
post.setNoteCount(0);
} else {
post.setNoteCount(Integer.valueOf(noteCount));
}
post.setRebloggedFromUrl(parser.getAttributeValue(NAME_SPACE, "reblogged-from-url"));
post.setRebloggedFromName(parser.getAttributeValue(NAME_SPACE, "reblogged-from-name"));
post.setRebloggedFromTitle(parser.getAttributeValue(NAME_SPACE, "reblogged-from-title"));
} else if ("tumblelog".equals(tag)) {
post.setTumblelogTitle(parser.getAttributeValue(NAME_SPACE, "title"));
post.setTumblelogName(parser.getAttributeValue(NAME_SPACE, "name"));
post.setTumblelogUrl(parser.getAttributeValue(NAME_SPACE, "url"));
post.setTumblelogTimezone(parser.getAttributeValue(NAME_SPACE, "timezone"));
} else if ("tag".equals(tag)) {
post.setTag(parser.nextText());
} else if ("quote-text".equals(tag)) {
post.setQuoteText(parser.nextText());
} else if ("quote-source".equals(tag)) {
post.setQuoteSource(parser.nextText());
} else if ("photo-caption".equals(tag)) {
post.setPhotoCaption(parser.nextText());
} else if ("photo-link-url".equals(tag)) {
post.setPhotoLinkUrl(parser.nextText());
} else if ("photo-url".equals(tag)) {
String maxWidth = parser.getAttributeValue(NAME_SPACE, "max-width");
if ("1280".equals(maxWidth)) {
post.setPhotoUrlMaxWidth1280(parser.nextText());
} else if ("500".equals(maxWidth)) {
post.setPhotoUrlMaxWidth500(parser.nextText());
} else if ("400".equals(maxWidth)) {
post.setPhotoUrlMaxWidth400(parser.nextText());
} else if ("250".equals(maxWidth)) {
post.setPhotoUrlMaxWidth250(parser.nextText());
} else if ("100".equals(maxWidth)) {
post.setPhotoUrlMaxWidth100(parser.nextText());
} else if ("75".equals(maxWidth)) {
post.setPhotoUrlMaxWidth75(parser.nextText());
}
} else if ("link-text".equals(tag)) {
post.setLinkText(parser.nextText());
} else if ("link-url".equals(tag)) {
post.setLinkUrl(parser.nextText());
} else if ("link-description".equals(tag)) {
post.setLinkDescription(parser.nextText());
} else if ("conversation-title".equals(tag)) {
post.setConversationTitle(parser.nextText());
} else if ("conversation-text".equals(tag)) {
post.setConversationText(parser.nextText());
} else if ("line".equals(tag)) {
String beforeText = post.getConversation();
if (beforeText == null) {
beforeText = "";
}
post.setConversation(beforeText + "<p>" + parser.getAttributeValue(NAME_SPACE, "label") + parser.nextText() + "</p>");
} else if ("video-caption".equals(tag)) {
post.setVideoCaption(parser.nextText());
} else if ("video-source".equals(tag)) {
post.setVideoSource(parser.nextText());
} else if ("video-player".equals(tag)) {
post.setVideoPlayer(parser.nextText());
} else if ("audio-caption".equals(tag)) {
post.setAudioCaption(parser.nextText());
} else if ("audio-player".equals(tag)) {
post.setAudioPlayer(parser.nextText());
} else if ("download-url".equals(tag)) {
post.setDownloadUrl(parser.nextText());
} else if ("regular-title".equals(tag)) {
post.setRegularTitle(parser.nextText());
} else if ("regular-body".equals(tag)) {
post.setRegularBody(parser.nextText());
}
} else if (e == XmlPullParser.END_TAG) {
if ("post".equals(tag)) {
posts.add(post);
}
}
}
return posts;
}
| public List<TLPost> parse()
throws NumberFormatException, XmlPullParserException, IOException
{
List<TLPost> posts = new ArrayList<TLPost>(50);
TLPost post = null;
for (int e = parser.getEventType(); e != XmlPullParser.END_DOCUMENT; e = parser.next()) {
String tag = parser.getName();
if (e == XmlPullParser.START_TAG) {
if ("post".equals(tag)) {
post = new TLPost();
post.setId(Long.valueOf(parser.getAttributeValue(NAME_SPACE, "id")));
post.setUrl(parser.getAttributeValue(NAME_SPACE, "url"));
post.setUrlWithSlug(parser.getAttributeValue(NAME_SPACE, "url-with-slug"));
post.setType(parser.getAttributeValue(NAME_SPACE, "type"));
post.setDateGmt(parser.getAttributeValue(NAME_SPACE, "date-gmt"));
post.setDate(parser.getAttributeValue(NAME_SPACE, "date"));
post.setUnixTimestamp(Integer.valueOf(parser.getAttributeValue(NAME_SPACE, "unix-timestamp")));
post.setFormat(parser.getAttributeValue(NAME_SPACE, "format"));
post.setReblogKey(parser.getAttributeValue(NAME_SPACE, "reblog-key"));
post.setSlug(parser.getAttributeValue(NAME_SPACE, "slug"));
String noteCount = parser.getAttributeValue(NAME_SPACE, "note-count");
if (noteCount == null || noteCount.length() == 0) {
post.setNoteCount(0);
} else {
post.setNoteCount(Integer.valueOf(noteCount));
}
post.setRebloggedFromUrl(parser.getAttributeValue(NAME_SPACE, "reblogged-from-url"));
post.setRebloggedFromName(parser.getAttributeValue(NAME_SPACE, "reblogged-from-name"));
post.setRebloggedFromTitle(parser.getAttributeValue(NAME_SPACE, "reblogged-from-title"));
} else if ("tumblelog".equals(tag)) {
post.setTumblelogTitle(parser.getAttributeValue(NAME_SPACE, "title"));
post.setTumblelogName(parser.getAttributeValue(NAME_SPACE, "name"));
post.setTumblelogUrl(parser.getAttributeValue(NAME_SPACE, "url"));
post.setTumblelogTimezone(parser.getAttributeValue(NAME_SPACE, "timezone"));
} else if ("tag".equals(tag)) {
post.setTag(parser.nextText());
} else if ("quote-text".equals(tag)) {
post.setQuoteText(parser.nextText());
} else if ("quote-source".equals(tag)) {
post.setQuoteSource(parser.nextText());
} else if ("photo-caption".equals(tag)) {
post.setPhotoCaption(parser.nextText());
} else if ("photo-link-url".equals(tag)) {
post.setPhotoLinkUrl(parser.nextText());
} else if ("photo-url".equals(tag)) {
String maxWidth = parser.getAttributeValue(NAME_SPACE, "max-width");
if ("1280".equals(maxWidth)) {
post.setPhotoUrlMaxWidth1280(parser.nextText());
} else if ("500".equals(maxWidth)) {
post.setPhotoUrlMaxWidth500(parser.nextText());
} else if ("400".equals(maxWidth)) {
post.setPhotoUrlMaxWidth400(parser.nextText());
} else if ("250".equals(maxWidth)) {
post.setPhotoUrlMaxWidth250(parser.nextText());
} else if ("100".equals(maxWidth)) {
post.setPhotoUrlMaxWidth100(parser.nextText());
} else if ("75".equals(maxWidth)) {
post.setPhotoUrlMaxWidth75(parser.nextText());
}
} else if ("link-text".equals(tag)) {
post.setLinkText(parser.nextText());
} else if ("link-url".equals(tag)) {
post.setLinkUrl(parser.nextText());
} else if ("link-description".equals(tag)) {
post.setLinkDescription(parser.nextText());
} else if ("conversation-title".equals(tag)) {
post.setConversationTitle(parser.nextText());
} else if ("conversation-text".equals(tag)) {
post.setConversationText(parser.nextText());
} else if ("line".equals(tag)) {
String beforeText = post.getConversation();
if (beforeText == null) {
beforeText = "";
}
post.setConversation(beforeText + "<p>" + parser.getAttributeValue(NAME_SPACE, "label") + parser.nextText() + "</p>");
} else if ("video-caption".equals(tag)) {
post.setVideoCaption(parser.nextText());
} else if ("video-source".equals(tag)) {
try {
post.setVideoSource(parser.nextText());
} catch (XmlPullParserException exception) {
// Raise error if contains meta info of video by XML.
}
} else if ("video-player".equals(tag)) {
post.setVideoPlayer(parser.nextText());
} else if ("audio-caption".equals(tag)) {
post.setAudioCaption(parser.nextText());
} else if ("audio-player".equals(tag)) {
post.setAudioPlayer(parser.nextText());
} else if ("download-url".equals(tag)) {
post.setDownloadUrl(parser.nextText());
} else if ("regular-title".equals(tag)) {
post.setRegularTitle(parser.nextText());
} else if ("regular-body".equals(tag)) {
post.setRegularBody(parser.nextText());
}
} else if (e == XmlPullParser.END_TAG) {
if ("post".equals(tag)) {
posts.add(post);
}
}
}
return posts;
}
|
diff --git a/mydlp-ui-dao/src/main/java/com/mydlp/ui/schema/granules/_000_00026_Config_Icap.java b/mydlp-ui-dao/src/main/java/com/mydlp/ui/schema/granules/_000_00026_Config_Icap.java
index 3fabddc4..0f2fa92d 100644
--- a/mydlp-ui-dao/src/main/java/com/mydlp/ui/schema/granules/_000_00026_Config_Icap.java
+++ b/mydlp-ui-dao/src/main/java/com/mydlp/ui/schema/granules/_000_00026_Config_Icap.java
@@ -1,44 +1,44 @@
package com.mydlp.ui.schema.granules;
import com.mydlp.ui.domain.Config;
import com.mydlp.ui.schema.AbstractGranule;
public class _000_00026_Config_Icap extends AbstractGranule {
@Override
protected void callback() {
Config icapReqModPath = new Config();
icapReqModPath.setKey("icap_reqmod_path");
- icapReqModPath.setValue("\\dlp");
+ icapReqModPath.setValue("/dlp");
Config icapRespModPath = new Config();
icapRespModPath.setKey("icap_respmod_path");
- icapRespModPath.setValue("dlp-respmod");
+ icapRespModPath.setValue("/dlp-respmod");
Config icapMaxConnections = new Config();
icapMaxConnections.setKey("icap_max_connections");
icapMaxConnections.setValue("0");
Config icapOptionsTTL = new Config();
icapOptionsTTL.setKey("icap_options_ttl");
icapOptionsTTL.setValue("0");
Config icapLogPass = new Config();
icapLogPass.setKey("icap_log_pass");
icapLogPass.setValue("false");
Config icapLogPassLowerLimit = new Config();
icapLogPassLowerLimit.setKey("icap_log_pass_lower_limit");
icapLogPassLowerLimit.setValue("10240");
getHibernateTemplate().saveOrUpdate(icapReqModPath);
getHibernateTemplate().saveOrUpdate(icapRespModPath);
getHibernateTemplate().saveOrUpdate(icapMaxConnections);
getHibernateTemplate().saveOrUpdate(icapOptionsTTL);
getHibernateTemplate().saveOrUpdate(icapLogPass);
getHibernateTemplate().saveOrUpdate(icapLogPassLowerLimit);
}
}
| false | true | protected void callback() {
Config icapReqModPath = new Config();
icapReqModPath.setKey("icap_reqmod_path");
icapReqModPath.setValue("\\dlp");
Config icapRespModPath = new Config();
icapRespModPath.setKey("icap_respmod_path");
icapRespModPath.setValue("dlp-respmod");
Config icapMaxConnections = new Config();
icapMaxConnections.setKey("icap_max_connections");
icapMaxConnections.setValue("0");
Config icapOptionsTTL = new Config();
icapOptionsTTL.setKey("icap_options_ttl");
icapOptionsTTL.setValue("0");
Config icapLogPass = new Config();
icapLogPass.setKey("icap_log_pass");
icapLogPass.setValue("false");
Config icapLogPassLowerLimit = new Config();
icapLogPassLowerLimit.setKey("icap_log_pass_lower_limit");
icapLogPassLowerLimit.setValue("10240");
getHibernateTemplate().saveOrUpdate(icapReqModPath);
getHibernateTemplate().saveOrUpdate(icapRespModPath);
getHibernateTemplate().saveOrUpdate(icapMaxConnections);
getHibernateTemplate().saveOrUpdate(icapOptionsTTL);
getHibernateTemplate().saveOrUpdate(icapLogPass);
getHibernateTemplate().saveOrUpdate(icapLogPassLowerLimit);
}
| protected void callback() {
Config icapReqModPath = new Config();
icapReqModPath.setKey("icap_reqmod_path");
icapReqModPath.setValue("/dlp");
Config icapRespModPath = new Config();
icapRespModPath.setKey("icap_respmod_path");
icapRespModPath.setValue("/dlp-respmod");
Config icapMaxConnections = new Config();
icapMaxConnections.setKey("icap_max_connections");
icapMaxConnections.setValue("0");
Config icapOptionsTTL = new Config();
icapOptionsTTL.setKey("icap_options_ttl");
icapOptionsTTL.setValue("0");
Config icapLogPass = new Config();
icapLogPass.setKey("icap_log_pass");
icapLogPass.setValue("false");
Config icapLogPassLowerLimit = new Config();
icapLogPassLowerLimit.setKey("icap_log_pass_lower_limit");
icapLogPassLowerLimit.setValue("10240");
getHibernateTemplate().saveOrUpdate(icapReqModPath);
getHibernateTemplate().saveOrUpdate(icapRespModPath);
getHibernateTemplate().saveOrUpdate(icapMaxConnections);
getHibernateTemplate().saveOrUpdate(icapOptionsTTL);
getHibernateTemplate().saveOrUpdate(icapLogPass);
getHibernateTemplate().saveOrUpdate(icapLogPassLowerLimit);
}
|
diff --git a/ide/eclipse/esb/org.wso2.developerstudio.eclipse.gmf.esb.diagram/src/org/wso2/developerstudio/eclipse/gmf/esb/diagram/custom/ExceptionMessageMapper.java b/ide/eclipse/esb/org.wso2.developerstudio.eclipse.gmf.esb.diagram/src/org/wso2/developerstudio/eclipse/gmf/esb/diagram/custom/ExceptionMessageMapper.java
index 3958b9d56..91f566071 100644
--- a/ide/eclipse/esb/org.wso2.developerstudio.eclipse.gmf.esb.diagram/src/org/wso2/developerstudio/eclipse/gmf/esb/diagram/custom/ExceptionMessageMapper.java
+++ b/ide/eclipse/esb/org.wso2.developerstudio.eclipse.gmf.esb.diagram/src/org/wso2/developerstudio/eclipse/gmf/esb/diagram/custom/ExceptionMessageMapper.java
@@ -1,20 +1,20 @@
package org.wso2.developerstudio.eclipse.gmf.esb.diagram.custom;
public class ExceptionMessageMapper {
public static String getNonTechnicalMessage(String message) {
String simpleMessage = message;
if (message.contains("Only one resource can be designated as default"))
{
- simpleMessage = "You have defined more than one resources where no uri-mapping(or uri-template) is provided or with empty uir-maping(or uri-template)s, " +
+ simpleMessage = "You have defined more than one resources where no uri-mapping(or uri-template) is provided or with empty uri-maping(or uri-template)s, " +
"which leads to treat all these resources as default resources, But Only one resource can be designated as default. ";
} /*else if (place your other mappings here)
{
}
*/
return simpleMessage;
}
}
| true | true | public static String getNonTechnicalMessage(String message) {
String simpleMessage = message;
if (message.contains("Only one resource can be designated as default"))
{
simpleMessage = "You have defined more than one resources where no uri-mapping(or uri-template) is provided or with empty uir-maping(or uri-template)s, " +
"which leads to treat all these resources as default resources, But Only one resource can be designated as default. ";
} /*else if (place your other mappings here)
{
}
*/
return simpleMessage;
}
| public static String getNonTechnicalMessage(String message) {
String simpleMessage = message;
if (message.contains("Only one resource can be designated as default"))
{
simpleMessage = "You have defined more than one resources where no uri-mapping(or uri-template) is provided or with empty uri-maping(or uri-template)s, " +
"which leads to treat all these resources as default resources, But Only one resource can be designated as default. ";
} /*else if (place your other mappings here)
{
}
*/
return simpleMessage;
}
|
diff --git a/lib/src/main/java/com/github/fhirschmann/clozegen/lib/annotators/GapAnnotator.java b/lib/src/main/java/com/github/fhirschmann/clozegen/lib/annotators/GapAnnotator.java
index 6c54935..01202d7 100644
--- a/lib/src/main/java/com/github/fhirschmann/clozegen/lib/annotators/GapAnnotator.java
+++ b/lib/src/main/java/com/github/fhirschmann/clozegen/lib/annotators/GapAnnotator.java
@@ -1,86 +1,89 @@
/*
* Copyright (C) 2012 Fabian Hirschmann <[email protected]>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package com.github.fhirschmann.clozegen.lib.annotators;
import com.github.fhirschmann.clozegen.lib.type.GapAnnotation;
import java.util.Iterator;
import org.apache.uima.analysis_engine.AnalysisEngineProcessException;
import org.apache.uima.jcas.JCas;
import org.apache.uima.jcas.cas.NonEmptyStringList;
import org.uimafit.component.JCasAnnotator_ImplBase;
import org.apache.uima.jcas.tcas.Annotation;
import org.uimafit.util.FSCollectionFactory;
/**
* Base class for all cloze item annotations.
*
* @author Fabian Hirschmann <[email protected]>
*/
public abstract class GapAnnotator extends JCasAnnotator_ImplBase {
/**
* Returns the type of the word class an extending class is looking for.
*
* This should be implemented by all inheriting classes.
*
* @see de.tudarmstadt.ukp.dkpro.core.api.lexmorph.type.pos
* @return word class type
*/
public abstract int getType();
/**
* Generates cloze tests item from a given subject (a word in a word class).
*
* This method should generate a number of valid and invalid answers
* for a given subject. For example, the subject "a" in the "articles" class
* might have "a" as only valid answers and {"an","the"} as invalid answers.
*
* @param subject the word to generate a cloze test item for
* @return valid and invalid answers for a gap
*/
public abstract Gap generate(Annotation subject);
/**
* Process the annotator.
*
* This method will set up the annotation for words in a word class
* (as defined by the extending classes) and call generate() in the
* extending class for each word in this class.
*
* @param jcas the CAS to work on
* @throws AnalysisEngineProcessException
*/
@Override
- public void process(JCas jcas) throws AnalysisEngineProcessException {
- for (Iterator<Annotation> i = jcas.getAnnotationIndex(getType()).iterator(); i.hasNext();) {
+ public void process(final JCas jcas) throws AnalysisEngineProcessException {
+ for (Iterator<Annotation> i = jcas.getAnnotationIndex(
+ getType()).iterator(); i.hasNext();) {
Annotation subject = i.next();
GapAnnotation annotation = new GapAnnotation(jcas);
annotation.setBegin(subject.getBegin());
annotation.setEnd(subject.getEnd());
Gap pair = generate(subject);
- NonEmptyStringList d = (NonEmptyStringList) FSCollectionFactory.createStringList(jcas, pair.getInvalidAnswers());
+ NonEmptyStringList d = (NonEmptyStringList) FSCollectionFactory.
+ createStringList(jcas, pair.getInvalidAnswers());
annotation.setInvalidAnswers(d);
- NonEmptyStringList a = (NonEmptyStringList) FSCollectionFactory.createStringList(jcas, pair.getValidAnswers());
+ NonEmptyStringList a = (NonEmptyStringList) FSCollectionFactory.
+ createStringList(jcas, pair.getValidAnswers());
annotation.setValidAnswers(a);
annotation.addToIndexes();
}
}
}
| false | true | public void process(JCas jcas) throws AnalysisEngineProcessException {
for (Iterator<Annotation> i = jcas.getAnnotationIndex(getType()).iterator(); i.hasNext();) {
Annotation subject = i.next();
GapAnnotation annotation = new GapAnnotation(jcas);
annotation.setBegin(subject.getBegin());
annotation.setEnd(subject.getEnd());
Gap pair = generate(subject);
NonEmptyStringList d = (NonEmptyStringList) FSCollectionFactory.createStringList(jcas, pair.getInvalidAnswers());
annotation.setInvalidAnswers(d);
NonEmptyStringList a = (NonEmptyStringList) FSCollectionFactory.createStringList(jcas, pair.getValidAnswers());
annotation.setValidAnswers(a);
annotation.addToIndexes();
}
}
| public void process(final JCas jcas) throws AnalysisEngineProcessException {
for (Iterator<Annotation> i = jcas.getAnnotationIndex(
getType()).iterator(); i.hasNext();) {
Annotation subject = i.next();
GapAnnotation annotation = new GapAnnotation(jcas);
annotation.setBegin(subject.getBegin());
annotation.setEnd(subject.getEnd());
Gap pair = generate(subject);
NonEmptyStringList d = (NonEmptyStringList) FSCollectionFactory.
createStringList(jcas, pair.getInvalidAnswers());
annotation.setInvalidAnswers(d);
NonEmptyStringList a = (NonEmptyStringList) FSCollectionFactory.
createStringList(jcas, pair.getValidAnswers());
annotation.setValidAnswers(a);
annotation.addToIndexes();
}
}
|
diff --git a/Core/src/com/serotonin/m2m2/web/dwr/BaseDwr.java b/Core/src/com/serotonin/m2m2/web/dwr/BaseDwr.java
index cafc55b11..82c04fd0d 100644
--- a/Core/src/com/serotonin/m2m2/web/dwr/BaseDwr.java
+++ b/Core/src/com/serotonin/m2m2/web/dwr/BaseDwr.java
@@ -1,679 +1,679 @@
/*
Copyright (C) 2006-2011 Serotonin Software Technologies Inc. All rights reserved.
@author Matthew Lohbihler
*/
package com.serotonin.m2m2.web.dwr;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.measure.converter.UnitConverter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.directwebremoting.WebContextFactory;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.IllegalFieldValueException;
import com.serotonin.ShouldNeverHappenException;
import com.serotonin.m2m2.Common;
import com.serotonin.m2m2.DataTypes;
import com.serotonin.m2m2.ILifecycle;
import com.serotonin.m2m2.db.dao.DataPointDao;
import com.serotonin.m2m2.db.dao.EventDao;
import com.serotonin.m2m2.db.dao.EventInstanceDao;
import com.serotonin.m2m2.db.dao.SystemSettingsDao;
import com.serotonin.m2m2.db.dao.UserDao;
import com.serotonin.m2m2.i18n.TranslatableMessage;
import com.serotonin.m2m2.i18n.Translations;
import com.serotonin.m2m2.module.LongPollDefinition;
import com.serotonin.m2m2.module.ModuleRegistry;
import com.serotonin.m2m2.rt.dataImage.DataPointRT;
import com.serotonin.m2m2.rt.dataImage.PointValueTime;
import com.serotonin.m2m2.rt.dataImage.SetPointSource;
import com.serotonin.m2m2.rt.dataImage.types.DataValue;
import com.serotonin.m2m2.rt.dataImage.types.ImageValue;
import com.serotonin.m2m2.rt.dataImage.types.NumericValue;
import com.serotonin.m2m2.rt.event.AlarmLevels;
import com.serotonin.m2m2.rt.event.EventInstance;
import com.serotonin.m2m2.util.DateUtils;
import com.serotonin.m2m2.view.chart.ChartRenderer;
import com.serotonin.m2m2.view.text.ConvertingRenderer;
import com.serotonin.m2m2.view.text.TextRenderer;
import com.serotonin.m2m2.vo.DataPointExtendedNameComparator;
import com.serotonin.m2m2.vo.DataPointVO;
import com.serotonin.m2m2.vo.User;
import com.serotonin.m2m2.vo.UserComment;
import com.serotonin.m2m2.vo.event.EventInstanceVO;
import com.serotonin.m2m2.vo.permission.Permissions;
import com.serotonin.m2m2.web.dwr.beans.BasePointState;
import com.serotonin.m2m2.web.dwr.beans.DataPointBean;
import com.serotonin.m2m2.web.dwr.beans.PointDetailsState;
import com.serotonin.m2m2.web.dwr.longPoll.LongPollData;
import com.serotonin.m2m2.web.dwr.longPoll.LongPollHandler;
import com.serotonin.m2m2.web.dwr.longPoll.LongPollRequest;
import com.serotonin.m2m2.web.dwr.longPoll.LongPollState;
import com.serotonin.m2m2.web.dwr.util.DwrPermission;
import com.serotonin.m2m2.web.mvc.controller.ControllerUtils;
import com.serotonin.m2m2.web.taglib.Functions;
import com.serotonin.provider.Providers;
import com.serotonin.web.content.ContentGenerator;
abstract public class BaseDwr {
public static final String MODEL_ATTR_EVENTS = "events";
public static final String MODEL_ATTR_HAS_UNACKED_EVENT = "hasUnacknowledgedEvent";
public static final String MODEL_ATTR_TRANSLATIONS = "bundle";
protected static EventDao EVENT_DAO;
public static void initialize() {
EVENT_DAO = new EventDao();
}
public BaseDwr() {
// Cache the long poll handlers.
for (LongPollDefinition def : ModuleRegistry.getDefinitions(LongPollDefinition.class))
longPollHandlers.add(def.getHandler());
}
/**
* Base method for preparing information in a state object and returning a point value.
*
* @param componentId
* a unique id for the browser side component. Required for set point snippets.
* @param state
* @param point
* @param status
* @param model
* @return
*/
protected static PointValueTime prepareBasePointState(String componentId, BasePointState state,
DataPointVO pointVO, DataPointRT point, Map<String, Object> model) {
model.clear();
model.put("componentId", componentId);
model.put("point", pointVO);
model.put("pointRT", point);
model.put(MODEL_ATTR_TRANSLATIONS, getTranslations());
PointValueTime pointValue = null;
if (point == null)
model.put("disabled", "true");
else {
pointValue = point.getPointValue();
if (pointValue != null)
model.put("pointValue", pointValue);
}
return pointValue;
}
protected static void setEvents(DataPointVO pointVO, User user, Map<String, Object> model) {
int userId = 0;
if (user != null)
userId = user.getId();
List<EventInstance> events = EVENT_DAO.getPendingEventsForDataPoint(pointVO.getId(), userId);
if (events != null) {
model.put(MODEL_ATTR_EVENTS, events);
for (EventInstance event : events) {
if (!event.isAcknowledged())
model.put(MODEL_ATTR_HAS_UNACKED_EVENT, true);
}
}
}
protected static void setPrettyText(HttpServletRequest request, PointDetailsState state, DataPointVO pointVO,
Map<String, Object> model, PointValueTime pointValue) {
if (pointValue != null && pointValue.getValue() instanceof ImageValue) {
if (!ObjectUtils.equals(pointVO.lastValue(), pointValue)) {
state.setValue(generateContent(request, "imageValueThumbnail.jsp", model));
state.setTime(Functions.getTime(pointValue));
pointVO.updateLastValue(pointValue);
}
}
else {
String prettyText = Functions.getHtmlText(pointVO, pointValue);
model.put("text", prettyText);
if (!ObjectUtils.equals(pointVO.lastValue(), pointValue)) {
state.setValue(prettyText);
if (pointValue != null)
state.setTime(Functions.getTime(pointValue));
pointVO.updateLastValue(pointValue);
}
}
}
protected static void setChange(DataPointVO pointVO, BasePointState state, DataPointRT point,
HttpServletRequest request, Map<String, Object> model, User user) {
if (Permissions.hasDataPointSetPermission(user, pointVO))
setChange(pointVO, state, point, request, model);
}
protected static void setChange(DataPointVO pointVO, BasePointState state, DataPointRT point,
HttpServletRequest request, Map<String, Object> model) {
if (pointVO.getPointLocator().isSettable()) {
if (point == null)
state.setChange(translate("common.pointDisabled"));
else {
String snippet = pointVO.getTextRenderer().getChangeSnippetFilename();
state.setChange(generateContent(request, snippet, model));
}
}
}
protected static void setChart(DataPointVO point, BasePointState state, HttpServletRequest request,
Map<String, Object> model) {
ChartRenderer chartRenderer = point.getChartRenderer();
if (chartRenderer != null) {
chartRenderer.addDataToModel(model, point);
String snippet = chartRenderer.getChartSnippetFilename();
state.setChart(generateContent(request, snippet, model));
}
}
protected static void setMessages(BasePointState state, HttpServletRequest request, String snippet,
Map<String, Object> model) {
state.setMessages(generateContent(request, snippet, model).trim());
}
/**
* Allows the setting of a given data point. Used by the watch list and point details pages. Views implement their
* own version to accommodate anonymous users.
*
* @param pointId
* @param valueStr
* @return
*/
@DwrPermission(user = true)
public int setPoint(int pointId, int componentId, String valueStr) {
User user = Common.getUser();
DataPointVO point = new DataPointDao().getDataPoint(pointId);
// Check permissions.
Permissions.ensureDataPointSetPermission(user, point);
setPointImpl(point, valueStr, user);
return componentId;
}
protected void setPointImpl(DataPointVO point, String valueStr, SetPointSource source) {
if (point == null)
return;
if (valueStr == null)
Common.runtimeManager.relinquish(point.getId());
else {
// Convert the string value into an object.
DataValue value = DataValue.stringToValue(valueStr, point.getPointLocator().getDataTypeId());
// do reverse conversion of renderer
TextRenderer tr = point.getTextRenderer();
if (point.getPointLocator().getDataTypeId() == DataTypes.NUMERIC &&
tr instanceof ConvertingRenderer) {
ConvertingRenderer cr = (ConvertingRenderer) tr;
UnitConverter converter = cr.getRenderedUnit().getConverterTo(cr.getUnit());
double convertedValue = converter.convert(value.getDoubleValue());
value = new NumericValue(convertedValue);
}
Common.runtimeManager.setDataPointValue(point.getId(), value, source);
}
}
@DwrPermission(user = true)
public void forcePointRead(int pointId) {
User user = Common.getUser();
DataPointVO point = new DataPointDao().getDataPoint(pointId);
// Check permissions.
Permissions.ensureDataPointReadPermission(user, point);
Common.runtimeManager.forcePointRead(pointId);
}
/**
* Logs a user comment after validation.
*
* @param eventId
* @param comment
* @return
*/
@DwrPermission(user = true)
public UserComment addUserComment(int typeId, int referenceId, String comment) {
if (StringUtils.isBlank(comment))
return null;
User user = Common.getUser();
UserComment c = new UserComment();
c.setComment(comment);
c.setTs(System.currentTimeMillis());
c.setUserId(user.getId());
c.setUsername(user.getUsername());
if (typeId == UserComment.TYPE_EVENT)
EVENT_DAO.insertEventComment(referenceId, c);
else if (typeId == UserComment.TYPE_POINT)
new UserDao().insertUserComment(UserComment.TYPE_POINT, referenceId, c);
else
throw new ShouldNeverHappenException("Invalid comment type: " + typeId);
return c;
}
protected List<DataPointBean> getReadablePoints() {
User user = Common.getUser();
List<DataPointVO> points = new DataPointDao().getDataPoints(DataPointExtendedNameComparator.instance, false);
if (!Permissions.hasAdmin(user)) {
List<DataPointVO> userPoints = new ArrayList<DataPointVO>();
for (DataPointVO dp : points) {
if (Permissions.hasDataPointReadPermission(user, dp))
userPoints.add(dp);
}
points = userPoints;
}
List<DataPointBean> result = new ArrayList<DataPointBean>();
for (DataPointVO dp : points)
result.add(new DataPointBean(dp));
return result;
}
@DwrPermission(anonymous = true)
public Map<String, Object> getDateRangeDefaults(int periodType, int period) {
Map<String, Object> result = new HashMap<String, Object>();
DateTimeZone dtz = Common.getUserDateTimeZone(Common.getUser());
// Default the specific date fields.
DateTime dt = new DateTime(dtz);
result.put("toYear", dt.getYear());
result.put("toMonth", dt.getMonthOfYear());
result.put("toDay", dt.getDayOfMonth());
result.put("toHour", dt.getHourOfDay());
result.put("toMinute", dt.getMinuteOfHour());
result.put("toSecond", 0);
dt = DateUtils.minus(dt, periodType, period);
result.put("fromYear", dt.getYear());
result.put("fromMonth", dt.getMonthOfYear());
result.put("fromDay", dt.getDayOfMonth());
result.put("fromHour", dt.getHourOfDay());
result.put("fromMinute", dt.getMinuteOfHour());
result.put("fromSecond", 0);
return result;
}
protected static String translate(String key, Object... args) {
if (args == null || args.length == 0)
return getTranslations().translate(key);
return new TranslatableMessage(key, args).translate(getTranslations());
}
protected static String translate(TranslatableMessage message) {
return message.translate(getTranslations());
}
protected static Translations getTranslations() {
return Translations.getTranslations(getLocale());
}
protected static Locale getLocale() {
return ControllerUtils.getLocale(WebContextFactory.get().getHttpServletRequest());
}
public static String generateContent(HttpServletRequest request, String snippet, Map<String, Object> model) {
if (!snippet.startsWith("/"))
snippet = "/WEB-INF/snippet/" + snippet;
try {
return ContentGenerator.generateContent(request, snippet, model);
}
catch (ServletException e) {
throw new ShouldNeverHappenException(e);
}
catch (IOException e) {
throw new ShouldNeverHappenException(e);
}
}
protected List<User> getShareUsers(User excludeUser) {
List<User> users = new ArrayList<User>();
for (User u : new UserDao().getUsers()) {
if (u.getId() != excludeUser.getId())
users.add(u);
}
return users;
}
//
//
// Long Poll
//
private static final String LONG_POLL_DATA_KEY = "LONG_POLL_DATA";
private static final String LONG_POLL_DATA_TIMEOUT_KEY = "LONG_POLL_DATA_TIMEOUT";
private final List<LongPollHandler> longPollHandlers = new ArrayList<LongPollHandler>();
@DwrPermission(anonymous = true)
public Map<String, Object> initializeLongPoll(int pollSessionId, LongPollRequest request) {
LongPollData data = getLongPollData(pollSessionId, true);
data.setRequest(request);
return doLongPoll(pollSessionId);
}
@DwrPermission(anonymous = true)
public Map<String, Object> doLongPoll(int pollSessionId) {
Map<String, Object> response = new HashMap<String, Object>();
HttpServletRequest httpRequest = WebContextFactory.get().getHttpServletRequest();
User user = Common.getUser(httpRequest);
EventDao eventDao = new EventDao();
LongPollData data = getLongPollData(pollSessionId, false);
data.updateTimestamp();
LongPollRequest pollRequest = data.getRequest();
long expireTime = System.currentTimeMillis() + 60000; // One minute
LongPollState state = data.getState();
int waitTime = SystemSettingsDao.getIntValue(SystemSettingsDao.UI_PERFORMANCE);
// For users that log in on multiple machines (or browsers), reset the last alarm timestamp so that it always
// gets reset with at least each new poll. For now this beats writing user-specific event change tracking code.
state.setLastAlarmLevelChange(0);
while (!pollRequest.isTerminated() && System.currentTimeMillis() < expireTime) {
if (Providers.get(ILifecycle.class).isTerminated()) {
pollRequest.setTerminated(true);
break;
}
if (pollRequest.isMaxAlarm() && user != null) {
//Track the last alarm count to see if we need to update the alarm toaster
Integer lastUnsilencedAlarmCount = (Integer) data.getState().getAttribute("lastUnsilencedAlarmCount");
//Ensure we have one, as we won't on first run
if(lastUnsilencedAlarmCount == null)
lastUnsilencedAlarmCount = 0;
List<EventInstanceVO> events = EventInstanceDao.instance.getUnsilencedEvents(user.getId());
//Sort into lists for the different types
int lifeSafetyTotal=0, noneTotal=0, informationTotal=0, criticalTotal=0, urgentTotal=0;
for(EventInstanceVO event : events){
switch(event.getAlarmLevel()){
case AlarmLevels.NONE:
noneTotal++;
break;
case AlarmLevels.INFORMATION:
informationTotal++;
break;
case AlarmLevels.URGENT:
urgentTotal++;
break;
case AlarmLevels.CRITICAL:
criticalTotal++;
break;
case AlarmLevels.LIFE_SAFETY:
lifeSafetyTotal++;
break;
default:
//Nothing for now...
}
}
int currentUnsilencedAlarmCount = noneTotal + informationTotal + urgentTotal + criticalTotal + lifeSafetyTotal;
//If we have some new information we should show it
if(lastUnsilencedAlarmCount != currentUnsilencedAlarmCount ){
data.getState().setAttribute("lastUnsilencedAlarmCount", currentUnsilencedAlarmCount); //Update the value
response.put("alarmsUpdated",true); //Indicate to UI that there is a new alarm
response.put("alarmsNone", noneTotal);
if(noneTotal == 1){
EventInstanceVO event = EventInstanceDao.instance.getHighestUnsilencedEvent(user.getId(), AlarmLevels.NONE);
response.put("noneEvent",event);
}
response.put("alarmsInformation", informationTotal);
if(informationTotal == 1){
EventInstanceVO event = EventInstanceDao.instance.getHighestUnsilencedEvent(user.getId(), AlarmLevels.INFORMATION);
response.put("informationEvent",event);
}
response.put("alarmsUrgent", urgentTotal);
if(urgentTotal == 1){
EventInstanceVO event = EventInstanceDao.instance.getHighestUnsilencedEvent(user.getId(), AlarmLevels.URGENT);
response.put("urgentEvent",event);
}
response.put("alarmsCritical", criticalTotal);
if(criticalTotal == 1){
EventInstanceVO event = EventInstanceDao.instance.getHighestUnsilencedEvent(user.getId(), AlarmLevels.CRITICAL);
response.put("criticalEvent",event);
}
response.put("alarmsLifeSafety", lifeSafetyTotal);
if(lifeSafetyTotal == 1){
EventInstanceVO event = EventInstanceDao.instance.getHighestUnsilencedEvent(user.getId(), AlarmLevels.LIFE_SAFETY);
response.put("lifeSafetyEvent",event);
}
}else{//end if new alarm toaster info
- response.put("alarmsUpdated",false);
+ //response.put("alarmsUpdated",false);
}
// The events have changed. See if the user's particular max alarm level has changed.
int maxAlarmLevel = eventDao.getHighestUnsilencedAlarmLevel(user.getId());
if (maxAlarmLevel != state.getMaxAlarmLevel()) {
response.put("highestUnsilencedAlarmLevel", maxAlarmLevel);
state.setMaxAlarmLevel(maxAlarmLevel);
}
// Check the max alarm. First check if the events have changed since the last time this request checked.
long lastEMUpdate = Common.eventManager.getLastAlarmTimestamp();
//If there is a new alarm then do stuff
if (state.getLastAlarmLevelChange() < lastEMUpdate) {
state.setLastAlarmLevelChange(lastEMUpdate);
}else{//end no new alarms
- response.put("alarmsUpdated",false);
+ //Don't add data for nothing, this will cause tons of polls. response.put("alarmsUpdated",false);
}
}//end for max alarms
if (pollRequest.isPointDetails() && user != null) {
PointDetailsState newState = DataPointDetailsDwr.getPointData();
PointDetailsState responseState;
PointDetailsState oldState = state.getPointDetailsState();
if (oldState == null)
responseState = newState;
else {
responseState = newState.clone();
responseState.removeEqualValue(oldState);
}
if (!responseState.isEmpty()) {
response.put("pointDetailsState", responseState);
state.setPointDetailsState(newState);
}
}
//TODO This is dead code as of 2.0.7, can remove eventually
if (pollRequest.isPendingAlarms() && user != null) {
// Create the list of most current pending alarm content.
Map<String, Object> model = new HashMap<String, Object>();
model.put("events", eventDao.getPendingEvents(user.getId()));
model.put("pendingEvents", true);
model.put("noContentWhenEmpty", true);
String currentContent = generateContent(httpRequest, "eventList.jsp", model);
currentContent = com.serotonin.util.StringUtils.trimWhitespace(currentContent);
if (!StringUtils.equals(currentContent, state.getPendingAlarmsContent())) {
response.put("newAlarms",true);
response.put("pendingAlarmsContent", currentContent);
state.setPendingAlarmsContent(currentContent);
}else{
response.put("newAlarms", false);
}
}
// Module handlers
for (int i = 0; i < longPollHandlers.size(); i++) {
LongPollHandler handler = longPollHandlers.get(i);
handler.handleLongPoll(data, response, user);
}
if (!response.isEmpty())
break;
synchronized (pollRequest) {
try {
pollRequest.wait(waitTime);
}
catch (InterruptedException e) {
// no op
}
}
}
if (pollRequest.isTerminated())
response.put("terminated", true);
return response;
}
@DwrPermission(anonymous = true)
public void terminateLongPoll(int pollSessionId) {
terminateLongPollImpl(getLongPollData(pollSessionId, false));
}
@DwrPermission(anonymous = true)
public static void terminateLongPollImpl(LongPollData longPollData) {
LongPollRequest request = longPollData.getRequest();
if (request == null)
return;
request.setTerminated(true);
notifyLongPollImpl(request);
}
@DwrPermission(anonymous = true)
public void notifyLongPoll(int pollSessionId) {
notifyLongPollImpl(getLongPollData(pollSessionId, false).getRequest());
}
protected static void notifyLongPollImpl(LongPollRequest request) {
synchronized (request) {
request.notifyAll();
}
}
protected LongPollData getLongPollData(int pollSessionId, boolean refreshState) {
List<LongPollData> dataList = getLongPollData();
LongPollData data = getDataFromList(dataList, pollSessionId);
if (data == null) {
synchronized (dataList) {
data = getDataFromList(dataList, pollSessionId);
if (data == null) {
data = new LongPollData(pollSessionId);
refreshState = true;
dataList.add(data);
}
}
}
if (refreshState)
data.setState(new LongPollState());
return data;
}
private LongPollData getDataFromList(List<LongPollData> dataList, int pollSessionId) {
for (LongPollData data : dataList) {
if (data.getPollSessionId() == pollSessionId)
return data;
}
return null;
}
@SuppressWarnings("unchecked")
private List<LongPollData> getLongPollData() {
HttpSession session = WebContextFactory.get().getSession();
List<LongPollData> data = (List<LongPollData>) session.getAttribute(LONG_POLL_DATA_KEY);
if (data == null) {
synchronized (session) {
data = (List<LongPollData>) session.getAttribute(LONG_POLL_DATA_KEY);
if (data == null) {
data = new ArrayList<LongPollData>();
session.setAttribute(LONG_POLL_DATA_KEY, data);
}
}
}
// Check for old data objects.
Long lastTimeoutCheck = (Long) session.getAttribute(LONG_POLL_DATA_TIMEOUT_KEY);
if (lastTimeoutCheck == null)
lastTimeoutCheck = 0L;
long cutoff = System.currentTimeMillis() - (1000 * 60 * 5); // Five minutes.
if (lastTimeoutCheck < cutoff) {
synchronized (data) {
Iterator<LongPollData> iter = data.iterator();
while (iter.hasNext()) {
LongPollData lpd = iter.next();
if (lpd.getTimestamp() < cutoff)
iter.remove();
}
}
session.setAttribute(LONG_POLL_DATA_TIMEOUT_KEY, System.currentTimeMillis());
}
return data;
}
protected void resetLastAlarmLevelChange() {
List<LongPollData> data = getLongPollData();
synchronized (data) {
// Check if this user has a current long poll request (very likely)
for (LongPollData lpd : data) {
LongPollState state = lpd.getState();
// Reset the last alarm level change time so that the alarm level gets rechecked.
state.setLastAlarmLevelChange(0);
// Notify the long poll thread so that any change
notifyLongPollImpl(lpd.getRequest());
}
}
}
//
//
// Charts and data in a time frame
//
protected DateTime createDateTime(int year, int month, int day, int hour, int minute, int second, boolean none,
DateTimeZone dtz) {
DateTime dt = null;
try {
if (!none)
dt = new DateTime(year, month, day, hour, minute, second, 0, dtz);
}
catch (IllegalFieldValueException e) {
dt = new DateTime(dtz);
}
return dt;
}
/**
* Every DWR-enabled app needs a ping method.
*/
@DwrPermission(anonymous = true)
public void ping() {
// no op
}
}
| false | true | public Map<String, Object> doLongPoll(int pollSessionId) {
Map<String, Object> response = new HashMap<String, Object>();
HttpServletRequest httpRequest = WebContextFactory.get().getHttpServletRequest();
User user = Common.getUser(httpRequest);
EventDao eventDao = new EventDao();
LongPollData data = getLongPollData(pollSessionId, false);
data.updateTimestamp();
LongPollRequest pollRequest = data.getRequest();
long expireTime = System.currentTimeMillis() + 60000; // One minute
LongPollState state = data.getState();
int waitTime = SystemSettingsDao.getIntValue(SystemSettingsDao.UI_PERFORMANCE);
// For users that log in on multiple machines (or browsers), reset the last alarm timestamp so that it always
// gets reset with at least each new poll. For now this beats writing user-specific event change tracking code.
state.setLastAlarmLevelChange(0);
while (!pollRequest.isTerminated() && System.currentTimeMillis() < expireTime) {
if (Providers.get(ILifecycle.class).isTerminated()) {
pollRequest.setTerminated(true);
break;
}
if (pollRequest.isMaxAlarm() && user != null) {
//Track the last alarm count to see if we need to update the alarm toaster
Integer lastUnsilencedAlarmCount = (Integer) data.getState().getAttribute("lastUnsilencedAlarmCount");
//Ensure we have one, as we won't on first run
if(lastUnsilencedAlarmCount == null)
lastUnsilencedAlarmCount = 0;
List<EventInstanceVO> events = EventInstanceDao.instance.getUnsilencedEvents(user.getId());
//Sort into lists for the different types
int lifeSafetyTotal=0, noneTotal=0, informationTotal=0, criticalTotal=0, urgentTotal=0;
for(EventInstanceVO event : events){
switch(event.getAlarmLevel()){
case AlarmLevels.NONE:
noneTotal++;
break;
case AlarmLevels.INFORMATION:
informationTotal++;
break;
case AlarmLevels.URGENT:
urgentTotal++;
break;
case AlarmLevels.CRITICAL:
criticalTotal++;
break;
case AlarmLevels.LIFE_SAFETY:
lifeSafetyTotal++;
break;
default:
//Nothing for now...
}
}
int currentUnsilencedAlarmCount = noneTotal + informationTotal + urgentTotal + criticalTotal + lifeSafetyTotal;
//If we have some new information we should show it
if(lastUnsilencedAlarmCount != currentUnsilencedAlarmCount ){
data.getState().setAttribute("lastUnsilencedAlarmCount", currentUnsilencedAlarmCount); //Update the value
response.put("alarmsUpdated",true); //Indicate to UI that there is a new alarm
response.put("alarmsNone", noneTotal);
if(noneTotal == 1){
EventInstanceVO event = EventInstanceDao.instance.getHighestUnsilencedEvent(user.getId(), AlarmLevels.NONE);
response.put("noneEvent",event);
}
response.put("alarmsInformation", informationTotal);
if(informationTotal == 1){
EventInstanceVO event = EventInstanceDao.instance.getHighestUnsilencedEvent(user.getId(), AlarmLevels.INFORMATION);
response.put("informationEvent",event);
}
response.put("alarmsUrgent", urgentTotal);
if(urgentTotal == 1){
EventInstanceVO event = EventInstanceDao.instance.getHighestUnsilencedEvent(user.getId(), AlarmLevels.URGENT);
response.put("urgentEvent",event);
}
response.put("alarmsCritical", criticalTotal);
if(criticalTotal == 1){
EventInstanceVO event = EventInstanceDao.instance.getHighestUnsilencedEvent(user.getId(), AlarmLevels.CRITICAL);
response.put("criticalEvent",event);
}
response.put("alarmsLifeSafety", lifeSafetyTotal);
if(lifeSafetyTotal == 1){
EventInstanceVO event = EventInstanceDao.instance.getHighestUnsilencedEvent(user.getId(), AlarmLevels.LIFE_SAFETY);
response.put("lifeSafetyEvent",event);
}
}else{//end if new alarm toaster info
response.put("alarmsUpdated",false);
}
// The events have changed. See if the user's particular max alarm level has changed.
int maxAlarmLevel = eventDao.getHighestUnsilencedAlarmLevel(user.getId());
if (maxAlarmLevel != state.getMaxAlarmLevel()) {
response.put("highestUnsilencedAlarmLevel", maxAlarmLevel);
state.setMaxAlarmLevel(maxAlarmLevel);
}
// Check the max alarm. First check if the events have changed since the last time this request checked.
long lastEMUpdate = Common.eventManager.getLastAlarmTimestamp();
//If there is a new alarm then do stuff
if (state.getLastAlarmLevelChange() < lastEMUpdate) {
state.setLastAlarmLevelChange(lastEMUpdate);
}else{//end no new alarms
response.put("alarmsUpdated",false);
}
}//end for max alarms
if (pollRequest.isPointDetails() && user != null) {
PointDetailsState newState = DataPointDetailsDwr.getPointData();
PointDetailsState responseState;
PointDetailsState oldState = state.getPointDetailsState();
if (oldState == null)
responseState = newState;
else {
responseState = newState.clone();
responseState.removeEqualValue(oldState);
}
if (!responseState.isEmpty()) {
response.put("pointDetailsState", responseState);
state.setPointDetailsState(newState);
}
}
//TODO This is dead code as of 2.0.7, can remove eventually
if (pollRequest.isPendingAlarms() && user != null) {
// Create the list of most current pending alarm content.
Map<String, Object> model = new HashMap<String, Object>();
model.put("events", eventDao.getPendingEvents(user.getId()));
model.put("pendingEvents", true);
model.put("noContentWhenEmpty", true);
String currentContent = generateContent(httpRequest, "eventList.jsp", model);
currentContent = com.serotonin.util.StringUtils.trimWhitespace(currentContent);
if (!StringUtils.equals(currentContent, state.getPendingAlarmsContent())) {
response.put("newAlarms",true);
response.put("pendingAlarmsContent", currentContent);
state.setPendingAlarmsContent(currentContent);
}else{
response.put("newAlarms", false);
}
}
// Module handlers
for (int i = 0; i < longPollHandlers.size(); i++) {
LongPollHandler handler = longPollHandlers.get(i);
handler.handleLongPoll(data, response, user);
}
if (!response.isEmpty())
break;
synchronized (pollRequest) {
try {
pollRequest.wait(waitTime);
}
catch (InterruptedException e) {
// no op
}
}
}
if (pollRequest.isTerminated())
response.put("terminated", true);
return response;
}
| public Map<String, Object> doLongPoll(int pollSessionId) {
Map<String, Object> response = new HashMap<String, Object>();
HttpServletRequest httpRequest = WebContextFactory.get().getHttpServletRequest();
User user = Common.getUser(httpRequest);
EventDao eventDao = new EventDao();
LongPollData data = getLongPollData(pollSessionId, false);
data.updateTimestamp();
LongPollRequest pollRequest = data.getRequest();
long expireTime = System.currentTimeMillis() + 60000; // One minute
LongPollState state = data.getState();
int waitTime = SystemSettingsDao.getIntValue(SystemSettingsDao.UI_PERFORMANCE);
// For users that log in on multiple machines (or browsers), reset the last alarm timestamp so that it always
// gets reset with at least each new poll. For now this beats writing user-specific event change tracking code.
state.setLastAlarmLevelChange(0);
while (!pollRequest.isTerminated() && System.currentTimeMillis() < expireTime) {
if (Providers.get(ILifecycle.class).isTerminated()) {
pollRequest.setTerminated(true);
break;
}
if (pollRequest.isMaxAlarm() && user != null) {
//Track the last alarm count to see if we need to update the alarm toaster
Integer lastUnsilencedAlarmCount = (Integer) data.getState().getAttribute("lastUnsilencedAlarmCount");
//Ensure we have one, as we won't on first run
if(lastUnsilencedAlarmCount == null)
lastUnsilencedAlarmCount = 0;
List<EventInstanceVO> events = EventInstanceDao.instance.getUnsilencedEvents(user.getId());
//Sort into lists for the different types
int lifeSafetyTotal=0, noneTotal=0, informationTotal=0, criticalTotal=0, urgentTotal=0;
for(EventInstanceVO event : events){
switch(event.getAlarmLevel()){
case AlarmLevels.NONE:
noneTotal++;
break;
case AlarmLevels.INFORMATION:
informationTotal++;
break;
case AlarmLevels.URGENT:
urgentTotal++;
break;
case AlarmLevels.CRITICAL:
criticalTotal++;
break;
case AlarmLevels.LIFE_SAFETY:
lifeSafetyTotal++;
break;
default:
//Nothing for now...
}
}
int currentUnsilencedAlarmCount = noneTotal + informationTotal + urgentTotal + criticalTotal + lifeSafetyTotal;
//If we have some new information we should show it
if(lastUnsilencedAlarmCount != currentUnsilencedAlarmCount ){
data.getState().setAttribute("lastUnsilencedAlarmCount", currentUnsilencedAlarmCount); //Update the value
response.put("alarmsUpdated",true); //Indicate to UI that there is a new alarm
response.put("alarmsNone", noneTotal);
if(noneTotal == 1){
EventInstanceVO event = EventInstanceDao.instance.getHighestUnsilencedEvent(user.getId(), AlarmLevels.NONE);
response.put("noneEvent",event);
}
response.put("alarmsInformation", informationTotal);
if(informationTotal == 1){
EventInstanceVO event = EventInstanceDao.instance.getHighestUnsilencedEvent(user.getId(), AlarmLevels.INFORMATION);
response.put("informationEvent",event);
}
response.put("alarmsUrgent", urgentTotal);
if(urgentTotal == 1){
EventInstanceVO event = EventInstanceDao.instance.getHighestUnsilencedEvent(user.getId(), AlarmLevels.URGENT);
response.put("urgentEvent",event);
}
response.put("alarmsCritical", criticalTotal);
if(criticalTotal == 1){
EventInstanceVO event = EventInstanceDao.instance.getHighestUnsilencedEvent(user.getId(), AlarmLevels.CRITICAL);
response.put("criticalEvent",event);
}
response.put("alarmsLifeSafety", lifeSafetyTotal);
if(lifeSafetyTotal == 1){
EventInstanceVO event = EventInstanceDao.instance.getHighestUnsilencedEvent(user.getId(), AlarmLevels.LIFE_SAFETY);
response.put("lifeSafetyEvent",event);
}
}else{//end if new alarm toaster info
//response.put("alarmsUpdated",false);
}
// The events have changed. See if the user's particular max alarm level has changed.
int maxAlarmLevel = eventDao.getHighestUnsilencedAlarmLevel(user.getId());
if (maxAlarmLevel != state.getMaxAlarmLevel()) {
response.put("highestUnsilencedAlarmLevel", maxAlarmLevel);
state.setMaxAlarmLevel(maxAlarmLevel);
}
// Check the max alarm. First check if the events have changed since the last time this request checked.
long lastEMUpdate = Common.eventManager.getLastAlarmTimestamp();
//If there is a new alarm then do stuff
if (state.getLastAlarmLevelChange() < lastEMUpdate) {
state.setLastAlarmLevelChange(lastEMUpdate);
}else{//end no new alarms
//Don't add data for nothing, this will cause tons of polls. response.put("alarmsUpdated",false);
}
}//end for max alarms
if (pollRequest.isPointDetails() && user != null) {
PointDetailsState newState = DataPointDetailsDwr.getPointData();
PointDetailsState responseState;
PointDetailsState oldState = state.getPointDetailsState();
if (oldState == null)
responseState = newState;
else {
responseState = newState.clone();
responseState.removeEqualValue(oldState);
}
if (!responseState.isEmpty()) {
response.put("pointDetailsState", responseState);
state.setPointDetailsState(newState);
}
}
//TODO This is dead code as of 2.0.7, can remove eventually
if (pollRequest.isPendingAlarms() && user != null) {
// Create the list of most current pending alarm content.
Map<String, Object> model = new HashMap<String, Object>();
model.put("events", eventDao.getPendingEvents(user.getId()));
model.put("pendingEvents", true);
model.put("noContentWhenEmpty", true);
String currentContent = generateContent(httpRequest, "eventList.jsp", model);
currentContent = com.serotonin.util.StringUtils.trimWhitespace(currentContent);
if (!StringUtils.equals(currentContent, state.getPendingAlarmsContent())) {
response.put("newAlarms",true);
response.put("pendingAlarmsContent", currentContent);
state.setPendingAlarmsContent(currentContent);
}else{
response.put("newAlarms", false);
}
}
// Module handlers
for (int i = 0; i < longPollHandlers.size(); i++) {
LongPollHandler handler = longPollHandlers.get(i);
handler.handleLongPoll(data, response, user);
}
if (!response.isEmpty())
break;
synchronized (pollRequest) {
try {
pollRequest.wait(waitTime);
}
catch (InterruptedException e) {
// no op
}
}
}
if (pollRequest.isTerminated())
response.put("terminated", true);
return response;
}
|
diff --git a/lang/src/test/java/net/openhft/lang/testing/RunningMinimumTest.java b/lang/src/test/java/net/openhft/lang/testing/RunningMinimumTest.java
index a1e9a6233..4d4c6f5b7 100644
--- a/lang/src/test/java/net/openhft/lang/testing/RunningMinimumTest.java
+++ b/lang/src/test/java/net/openhft/lang/testing/RunningMinimumTest.java
@@ -1,28 +1,28 @@
package net.openhft.lang.testing;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* User: peter
* Date: 05/08/13
* Time: 19:14
*/
public class RunningMinimumTest {
@Test
public void testSample() throws Exception {
for (int k = 0; k < 1000; k++) {
for (long delta : new long[]{0, Integer.MIN_VALUE, Integer.MAX_VALUE}) {
RunningMinimum rm = new RunningMinimum(50 * 1000);
int j;
- for (j = 0; j < 40 * 1000000; j += 1000000) {
+ for (j = 0; j < 50 * 1000000; j += 1000000) {
long startTime = System.nanoTime() + j;
long endTime = System.nanoTime() + j + delta + (long) (Math.pow(10 * 1000, Math.random()) * 1000);
rm.sample(startTime, endTime);
}
assertEquals("delta=" + delta, delta, rm.minimum(), 10 * 1000);
}
}
}
}
| true | true | public void testSample() throws Exception {
for (int k = 0; k < 1000; k++) {
for (long delta : new long[]{0, Integer.MIN_VALUE, Integer.MAX_VALUE}) {
RunningMinimum rm = new RunningMinimum(50 * 1000);
int j;
for (j = 0; j < 40 * 1000000; j += 1000000) {
long startTime = System.nanoTime() + j;
long endTime = System.nanoTime() + j + delta + (long) (Math.pow(10 * 1000, Math.random()) * 1000);
rm.sample(startTime, endTime);
}
assertEquals("delta=" + delta, delta, rm.minimum(), 10 * 1000);
}
}
}
| public void testSample() throws Exception {
for (int k = 0; k < 1000; k++) {
for (long delta : new long[]{0, Integer.MIN_VALUE, Integer.MAX_VALUE}) {
RunningMinimum rm = new RunningMinimum(50 * 1000);
int j;
for (j = 0; j < 50 * 1000000; j += 1000000) {
long startTime = System.nanoTime() + j;
long endTime = System.nanoTime() + j + delta + (long) (Math.pow(10 * 1000, Math.random()) * 1000);
rm.sample(startTime, endTime);
}
assertEquals("delta=" + delta, delta, rm.minimum(), 10 * 1000);
}
}
}
|
diff --git a/plugins/org.eclipse.xtext.ui.core/src/org/eclipse/xtext/ui/core/editor/validation/MarkerCreator.java b/plugins/org.eclipse.xtext.ui.core/src/org/eclipse/xtext/ui/core/editor/validation/MarkerCreator.java
index e98385d11..48dce2ea6 100644
--- a/plugins/org.eclipse.xtext.ui.core/src/org/eclipse/xtext/ui/core/editor/validation/MarkerCreator.java
+++ b/plugins/org.eclipse.xtext.ui.core/src/org/eclipse/xtext/ui/core/editor/validation/MarkerCreator.java
@@ -1,48 +1,49 @@
/*******************************************************************************
* Copyright (c) 2009 itemis AG (http://www.itemis.eu) and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package org.eclipse.xtext.ui.core.editor.validation;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.xtext.validation.Issue;
/**
* @author Sven Efftinge - Initial contribution and API
*/
public class MarkerCreator {
public void createMarker(Issue issue, IResource resource, String markerId) throws CoreException {
IMarker marker = resource.createMarker(markerId);
String lineNR = "";
if (issue.getLineNumber() != null) {
lineNR = "line: " + issue.getLineNumber() + " ";
}
marker.setAttribute(IMarker.LOCATION, lineNR + resource.getFullPath().toString());
marker.setAttribute(IMarker.CHAR_START, issue.getOffset());
- marker.setAttribute(IMarker.CHAR_END, issue.getOffset()+issue.getLength());
+ if(issue.getOffset() != null && issue.getLength() != null)
+ marker.setAttribute(IMarker.CHAR_END, issue.getOffset()+issue.getLength());
marker.setAttribute(IMarker.LINE_NUMBER, issue.getLineNumber());
marker.setAttribute(IMarker.MESSAGE, issue.getMessage());
marker.setAttribute(IMarker.SEVERITY, getSeverity(issue));
marker.setAttribute(Issue.CODE_KEY, issue.getCode());
if (issue.getUriToProblem()!=null)
marker.setAttribute(Issue.URI_KEY, issue.getUriToProblem().toString());
}
private Object getSeverity(Issue issue) {
switch (issue.getSeverity()) {
case ERROR :
return IMarker.SEVERITY_ERROR;
case WARNING :
return IMarker.SEVERITY_WARNING;
case INFO :
return IMarker.SEVERITY_INFO;
}
throw new IllegalArgumentException();
}
}
| true | true | public void createMarker(Issue issue, IResource resource, String markerId) throws CoreException {
IMarker marker = resource.createMarker(markerId);
String lineNR = "";
if (issue.getLineNumber() != null) {
lineNR = "line: " + issue.getLineNumber() + " ";
}
marker.setAttribute(IMarker.LOCATION, lineNR + resource.getFullPath().toString());
marker.setAttribute(IMarker.CHAR_START, issue.getOffset());
marker.setAttribute(IMarker.CHAR_END, issue.getOffset()+issue.getLength());
marker.setAttribute(IMarker.LINE_NUMBER, issue.getLineNumber());
marker.setAttribute(IMarker.MESSAGE, issue.getMessage());
marker.setAttribute(IMarker.SEVERITY, getSeverity(issue));
marker.setAttribute(Issue.CODE_KEY, issue.getCode());
if (issue.getUriToProblem()!=null)
marker.setAttribute(Issue.URI_KEY, issue.getUriToProblem().toString());
}
| public void createMarker(Issue issue, IResource resource, String markerId) throws CoreException {
IMarker marker = resource.createMarker(markerId);
String lineNR = "";
if (issue.getLineNumber() != null) {
lineNR = "line: " + issue.getLineNumber() + " ";
}
marker.setAttribute(IMarker.LOCATION, lineNR + resource.getFullPath().toString());
marker.setAttribute(IMarker.CHAR_START, issue.getOffset());
if(issue.getOffset() != null && issue.getLength() != null)
marker.setAttribute(IMarker.CHAR_END, issue.getOffset()+issue.getLength());
marker.setAttribute(IMarker.LINE_NUMBER, issue.getLineNumber());
marker.setAttribute(IMarker.MESSAGE, issue.getMessage());
marker.setAttribute(IMarker.SEVERITY, getSeverity(issue));
marker.setAttribute(Issue.CODE_KEY, issue.getCode());
if (issue.getUriToProblem()!=null)
marker.setAttribute(Issue.URI_KEY, issue.getUriToProblem().toString());
}
|
diff --git a/Essentials/src/com/earth2me/essentials/commands/EssentialsCommand.java b/Essentials/src/com/earth2me/essentials/commands/EssentialsCommand.java
index ab2c3c2..3091e3f 100644
--- a/Essentials/src/com/earth2me/essentials/commands/EssentialsCommand.java
+++ b/Essentials/src/com/earth2me/essentials/commands/EssentialsCommand.java
@@ -1,89 +1,89 @@
package com.earth2me.essentials.commands;
import java.util.List;
import org.bukkit.Server;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import com.earth2me.essentials.Essentials;
import org.bukkit.entity.Player;
import com.earth2me.essentials.User;
import com.earth2me.essentials.Util;
import java.util.logging.Logger;
public abstract class EssentialsCommand implements IEssentialsCommand
{
private final String name;
protected Essentials ess;
protected final static Logger logger = Logger.getLogger("Minecraft");
protected EssentialsCommand(String name)
{
this.name = name;
this.ess = Essentials.getStatic();
}
public String getName()
{
return name;
}
protected User getPlayer(Server server, String[] args, int pos) throws NoSuchFieldException, NotEnoughArgumentsException
{
if (args.length <= pos) throw new NotEnoughArgumentsException();
List<Player> matches = server.matchPlayer(args[pos]);
- if (matches.size() < 1) throw new NoSuchFieldException(Util.i18n("noPlayerFound"));
+ if (matches.size() < 1) throw new NoSuchFieldException(Util.i18n("playerNotFound"));
for (Player p : matches)
{
if (p.getDisplayName().startsWith(args[pos]))
{
return ess.getUser(p);
}
}
return ess.getUser(matches.get(0));
}
@Override
public final void run(Server server, User user, String commandLabel, Command cmd, String[] args) throws Exception
{
run(server, user, commandLabel, args);
}
protected void run(Server server, User user, String commandLabel, String[] args) throws Exception
{
run(server, (CommandSender)user.getBase(), commandLabel, args);
}
@Override
public final void run(Server server, CommandSender sender, String commandLabel, Command cmd, String[] args) throws Exception
{
run(server, sender, commandLabel, args);
}
protected void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{
throw new Exception(Util.format("onlyPlayers", commandLabel));
}
public static String getFinalArg(String[] args, int start)
{
StringBuilder bldr = new StringBuilder();
for (int i = start; i < args.length; i++)
{
if (i != start)
{
bldr.append(" ");
}
bldr.append(args[i]);
}
return bldr.toString();
}
protected void charge(CommandSender sender) throws Exception
{
if (sender instanceof Player)
{
ess.getUser((Player)sender).charge(this);
}
}
}
| true | true | protected User getPlayer(Server server, String[] args, int pos) throws NoSuchFieldException, NotEnoughArgumentsException
{
if (args.length <= pos) throw new NotEnoughArgumentsException();
List<Player> matches = server.matchPlayer(args[pos]);
if (matches.size() < 1) throw new NoSuchFieldException(Util.i18n("noPlayerFound"));
for (Player p : matches)
{
if (p.getDisplayName().startsWith(args[pos]))
{
return ess.getUser(p);
}
}
return ess.getUser(matches.get(0));
}
| protected User getPlayer(Server server, String[] args, int pos) throws NoSuchFieldException, NotEnoughArgumentsException
{
if (args.length <= pos) throw new NotEnoughArgumentsException();
List<Player> matches = server.matchPlayer(args[pos]);
if (matches.size() < 1) throw new NoSuchFieldException(Util.i18n("playerNotFound"));
for (Player p : matches)
{
if (p.getDisplayName().startsWith(args[pos]))
{
return ess.getUser(p);
}
}
return ess.getUser(matches.get(0));
}
|
diff --git a/src/test/Test03.java b/src/test/Test03.java
index d306a96..43ece58 100644
--- a/src/test/Test03.java
+++ b/src/test/Test03.java
@@ -1,72 +1,72 @@
package test;
import java.sql.*;
public class Test03 implements Test.Case
{
private String error;
private Exception ex;
public boolean run() throws Exception {
int res;
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection(
"jdbc:sqlite:build/test/test.db");
ResultSet rs;
Statement stat = conn.createStatement();
// test empty ResultSets
rs = stat.executeQuery("SELECT * FROM People WHERE pid = -100;");
if (rs.next()) {
error = "results found when none expected";
return false;
}
rs.close();
// test single-row ResultSets
rs = stat.executeQuery(
"SELECT pid, firstname FROM People WHERE pid = 1;");
if (!rs.next()) {
error = "no results found when one expected"; return false;
}
if (rs.getInt(1) != 1) {
error = "bad getInt(1): " + rs.getInt(1); return false;
} else if (!"Mohandas".equals(rs.getString(2))) {
error = "bad getString(2): " + rs.getString(2); return false;
}
if (rs.next()) {
error = "more data than expected"; return false;
}
rs.close();
// test multi-row ResultSets
rs = stat.executeQuery(
"SELECT pid, firstname FROM People "
+ "WHERE pid = 1 OR pid = 2 ORDER BY pid ASC;");
if (!rs.next()) {
error = "no results found when two rows expected"; return false;
}
if (rs.getInt(1) != 1) {
error = "bad row 1 getInt(1): " + rs.getInt(1); return false;
} else if (!"Mohandas".equals(rs.getString(2))) {
- error = "bad getString(2): " + rs.getString(2); return false;
+ error = "bad row 1 getString(2): " + rs.getString(2); return false;
}
if (!rs.next()) {
error = "one row found when two rows expected"; return false;
}
if (rs.getInt(1) != 2) {
- error = "bad getInt(1): " + rs.getInt(1); return false;
+ error = "bad row 2 getInt(1): " + rs.getInt(1); return false;
} else if (!"Winston".equals(rs.getString(2))) {
- error = "bad getString(2): " + rs.getString(2); return false;
+ error = "bad row 2 getString(2): " + rs.getString(2); return false;
}
rs.close();
stat.close();
conn.close();
return true;
}
public String name() { return "BasicExecuteQuery"; }
public String error() { return error; }
public Exception ex() { return ex; }
}
| false | true | public boolean run() throws Exception {
int res;
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection(
"jdbc:sqlite:build/test/test.db");
ResultSet rs;
Statement stat = conn.createStatement();
// test empty ResultSets
rs = stat.executeQuery("SELECT * FROM People WHERE pid = -100;");
if (rs.next()) {
error = "results found when none expected";
return false;
}
rs.close();
// test single-row ResultSets
rs = stat.executeQuery(
"SELECT pid, firstname FROM People WHERE pid = 1;");
if (!rs.next()) {
error = "no results found when one expected"; return false;
}
if (rs.getInt(1) != 1) {
error = "bad getInt(1): " + rs.getInt(1); return false;
} else if (!"Mohandas".equals(rs.getString(2))) {
error = "bad getString(2): " + rs.getString(2); return false;
}
if (rs.next()) {
error = "more data than expected"; return false;
}
rs.close();
// test multi-row ResultSets
rs = stat.executeQuery(
"SELECT pid, firstname FROM People "
+ "WHERE pid = 1 OR pid = 2 ORDER BY pid ASC;");
if (!rs.next()) {
error = "no results found when two rows expected"; return false;
}
if (rs.getInt(1) != 1) {
error = "bad row 1 getInt(1): " + rs.getInt(1); return false;
} else if (!"Mohandas".equals(rs.getString(2))) {
error = "bad getString(2): " + rs.getString(2); return false;
}
if (!rs.next()) {
error = "one row found when two rows expected"; return false;
}
if (rs.getInt(1) != 2) {
error = "bad getInt(1): " + rs.getInt(1); return false;
} else if (!"Winston".equals(rs.getString(2))) {
error = "bad getString(2): " + rs.getString(2); return false;
}
rs.close();
stat.close();
conn.close();
return true;
}
| public boolean run() throws Exception {
int res;
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection(
"jdbc:sqlite:build/test/test.db");
ResultSet rs;
Statement stat = conn.createStatement();
// test empty ResultSets
rs = stat.executeQuery("SELECT * FROM People WHERE pid = -100;");
if (rs.next()) {
error = "results found when none expected";
return false;
}
rs.close();
// test single-row ResultSets
rs = stat.executeQuery(
"SELECT pid, firstname FROM People WHERE pid = 1;");
if (!rs.next()) {
error = "no results found when one expected"; return false;
}
if (rs.getInt(1) != 1) {
error = "bad getInt(1): " + rs.getInt(1); return false;
} else if (!"Mohandas".equals(rs.getString(2))) {
error = "bad getString(2): " + rs.getString(2); return false;
}
if (rs.next()) {
error = "more data than expected"; return false;
}
rs.close();
// test multi-row ResultSets
rs = stat.executeQuery(
"SELECT pid, firstname FROM People "
+ "WHERE pid = 1 OR pid = 2 ORDER BY pid ASC;");
if (!rs.next()) {
error = "no results found when two rows expected"; return false;
}
if (rs.getInt(1) != 1) {
error = "bad row 1 getInt(1): " + rs.getInt(1); return false;
} else if (!"Mohandas".equals(rs.getString(2))) {
error = "bad row 1 getString(2): " + rs.getString(2); return false;
}
if (!rs.next()) {
error = "one row found when two rows expected"; return false;
}
if (rs.getInt(1) != 2) {
error = "bad row 2 getInt(1): " + rs.getInt(1); return false;
} else if (!"Winston".equals(rs.getString(2))) {
error = "bad row 2 getString(2): " + rs.getString(2); return false;
}
rs.close();
stat.close();
conn.close();
return true;
}
|
diff --git a/SimplyVanish/src/asofold/simplyvanish/SimplyVanishCore.java b/SimplyVanish/src/asofold/simplyvanish/SimplyVanishCore.java
index aeac8c8..a85df2c 100644
--- a/SimplyVanish/src/asofold/simplyvanish/SimplyVanishCore.java
+++ b/SimplyVanish/src/asofold/simplyvanish/SimplyVanishCore.java
@@ -1,791 +1,793 @@
package asofold.simplyvanish;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Server;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Entity;
import org.bukkit.entity.ExperienceOrb;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityTargetEvent;
import org.bukkit.event.entity.PotionSplashEvent;
import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerKickEvent;
import org.bukkit.event.player.PlayerPickupItemEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
import org.bukkit.util.Vector;
import asofold.simplyvanish.config.Settings;
import asofold.simplyvanish.config.VanishConfig;
import asofold.simplyvanish.util.Utils;
/**
* Core methods for vanish/reappear.
* @author mc_dev
*
*/
public class SimplyVanishCore implements Listener{
/**
* Vanished players.
*/
private final Map<String, VanishConfig> vanishConfigs = new HashMap<String, VanishConfig>();
/**
* Flag for if the plugin is enabled.
*/
boolean enabled = false;
Settings settings = new Settings();
/*
* File to save vanished players to.
*/
private File vanishedFile = null;
@EventHandler(priority=EventPriority.HIGHEST)
void onPlayerJoin( PlayerJoinEvent event){
Player player = event.getPlayer();
String playerName = player.getName();
VanishConfig cfg = getVanishConfig(playerName);
boolean auto = false;
if (cfg.auto == null){
if (settings.autoVanishUse) auto = true;
}
else if (cfg.auto.state) auto = true;
if (auto){
if (Utils.hasPermission(player, settings.autoVanishPerm)) addVanishedName(playerName);
}
updateVanishState(event.getPlayer());
if ( settings.suppressJoinMessage && isVanished(playerName)){
event.setJoinMessage(null);
}
}
/**
* Save vanished names to file, does NOT update states (!).
*/
public void saveVanished(){
File file = getVanishedFile();
if ( file==null){
Utils.warn("Can not save vanished players: File is not set.");
return;
}
if (!createFile(file, "vanished players")) return;
BufferedWriter writer = null;
try {
writer = new BufferedWriter( new FileWriter(file));
writer.write("\n"); // to write something at least.
for (Entry<String, VanishConfig> entry : vanishConfigs.entrySet()){
String n = entry.getKey();
VanishConfig cfg = entry.getValue();
if (cfg.needsSave()){
writer.write(n);
writer.write(cfg.toLine());
writer.write("\n");
}
cfg.changed = false;
}
}
catch (IOException e) {
Utils.warn("Can not save vanished players: "+e.getMessage());
}
finally{
if ( writer != null)
try {
writer.close();
} catch (IOException e) {
}
}
}
/**
* Load vanished names from file.<br>
* This does not update vanished states!<br>
* Assumes each involved VanishConfig to be changed by loading.
*/
public void loadVanished(){
File file = getVanishedFile();
if ( file == null){
Utils.warn("Can not load vanished players: File is not set.");
return;
}
if (!createFile(file, "vanished players")) return;
BufferedReader reader = null;
try {
reader = new BufferedReader( new FileReader(file));
String line = "";
while ( line != null){
String n = line.trim().toLowerCase();
if (!n.isEmpty()){
if (n.startsWith("nosee:") && n.length()>6){
// kept for compatibility:
n = n.substring(7).trim();
if (n.isEmpty()) continue;
VanishConfig cfg = getVanishConfig(n);
cfg.see.state = false;
cfg.changed = true;
}
else{
String[] split = n.split(" ");
n = split[0].trim().toLowerCase();
if (n.isEmpty()) continue;
VanishConfig cfg = getVanishConfig(n);
cfg.readFromArray(split, 1, true);
}
}
line = reader.readLine();
}
}
catch (IOException e) {
Utils.warn("Can not load vanished players: "+e.getMessage());
}
finally{
if ( reader != null)
try {
reader.close();
} catch (IOException e) {
}
}
}
/**
* Create if not exists.
* @param file
* @param tag
* @return if exists now.
*/
public boolean createFile(File file, String tag){
if ( !file.exists() ){
try {
if ( file.createNewFile()) return true;
else{
Utils.warn("Could not create "+tag+" file.");
}
} catch (IOException e) {
Utils.warn("Could not create "+tag+" file: "+e.getMessage());
return false;
}
}
return true;
}
public File getVanishedFile(){
return vanishedFile;
}
public void setVanishedFile(File file) {
vanishedFile = file;
}
@EventHandler(priority=EventPriority.HIGHEST)
void onPlayerQuit(PlayerQuitEvent event){
Player player = event.getPlayer();
String name = player.getName();
if ( settings.suppressQuitMessage && isVanished(name)){
event.setQuitMessage(null);
if (settings.notifyState){
String msg = SimplyVanish.msgLabel+ChatColor.GREEN+name+ChatColor.GRAY+" quit.";
for (Player other : Bukkit.getServer().getOnlinePlayers()){
if ( Utils.hasPermission(other, settings.notifyStatePerm)) other.sendMessage(msg);
}
}
}
}
@EventHandler(priority=EventPriority.HIGHEST)
void onPlayerKick(PlayerKickEvent event){
// (still set if cancelled)
Player player = event.getPlayer();
String name = player.getName();
if ( settings.suppressQuitMessage && isVanished(name)){
event.setLeaveMessage(null);
if (settings.notifyState && !event.isCancelled()){
String msg = SimplyVanish.msgLabel+ChatColor.GREEN+name+ChatColor.GRAY+" was kicked.";
for (Player other : Bukkit.getServer().getOnlinePlayers()){
if ( Utils.hasPermission(other, settings.notifyStatePerm)) other.sendMessage(msg);
}
}
}
}
@EventHandler(priority=EventPriority.LOW)
final void onEntityTarget(final EntityTargetEvent event){
if ( event.isCancelled() ) return;
final Entity target = event.getTarget();
if (!(target instanceof Player)) return;
final String playerName = ((Player) target).getName();
final VanishConfig cfg = vanishConfigs.get(playerName.toLowerCase());
if (cfg == null) return;
if (cfg.vanished.state){
if (settings.expEnabled && !cfg.pickup.state){
Entity entity = event.getEntity();
if ( entity instanceof ExperienceOrb){
repellExpOrb((Player) target, (ExperienceOrb) entity);
event.setCancelled(true);
event.setTarget(null);
return;
}
}
if (!cfg.target.state) event.setTarget(null);
}
}
@EventHandler(priority=EventPriority.HIGHEST)
void onPotionSplash(PotionSplashEvent event){
try{
final List<Entity> rem = new LinkedList<Entity>();
final Collection<LivingEntity> affected = event.getAffectedEntities();
for ( LivingEntity entity : affected){
if (entity instanceof Player ){
String playerName = ((Player) entity).getName();
VanishConfig cfg = vanishConfigs.get(playerName.toLowerCase());
if (cfg == null) continue;
if (cfg.vanished.state){
if (!cfg.damage.state) rem.add(entity);
}
}
}
if (!rem.isEmpty()) affected.removeAll(rem);
} catch(Throwable t){
// ignore (fast addition.)
}
}
// @EventHandler(priority=EventPriority.HIGHEST)
// void onServerListPing(ServerListPingEvent event){
// // TODO: try reflection ??
// }
/**
* Attempt some workaround for experience orbs:
* prevent it getting near the player.
* @param target
* @param entity
*/
void repellExpOrb(Player player, ExperienceOrb orb) {
Location pLoc = player.getLocation();
Location oLoc = orb.getLocation();
Vector dir = oLoc.toVector().subtract(pLoc.toVector());
double dx = Math.abs(dir.getX());
double dz = Math.abs(dir.getZ());
if ( (dx == 0.0) && (dz == 0.0)){
// Special case probably never happens
dir.setX(0.001);
}
if ((dx < settings.expThreshold) && (dz < settings.expThreshold)){
Vector nDir = dir.normalize();
Vector newV = nDir.clone().multiply(settings.expVelocity);
newV.setY(0);
orb.setVelocity(newV);
if ((dx < settings.expTeleDist) && (dz < settings.expTeleDist)){
// maybe oLoc
orb.teleport(oLoc.clone().add(nDir.multiply(settings.expTeleDist)), TeleportCause.PLUGIN);
}
if ((dx < settings.expKillDist) && (dz < settings.expKillDist)){
orb.remove();
}
}
}
@EventHandler(priority=EventPriority.LOW)
final void onEntityDamage(final EntityDamageEvent event){
if ( event.isCancelled() ) return;
final Entity entity = event.getEntity();
if (!(entity instanceof Player)) return;
final String playerName = ((Player) entity).getName();
final VanishConfig cfg = vanishConfigs.get(playerName.toLowerCase());
if (cfg == null) return;
if (!cfg.vanished.state || cfg.damage.state) return;
event.setCancelled(true);
if ( entity.getFireTicks()>0) entity.setFireTicks(0);
}
@EventHandler(priority=EventPriority.LOW)
void onItemPickUp(PlayerPickupItemEvent event){
if ( event.isCancelled() ) return;
Player player = event.getPlayer();
VanishConfig cfg = vanishConfigs.get(player.getName().toLowerCase());
if (cfg == null) return;
if (!cfg.vanished.state) return;
if (!cfg.pickup.state) event.setCancelled(true);
}
@EventHandler(priority=EventPriority.LOW)
void onItemDrop(PlayerDropItemEvent event){
if ( event.isCancelled() ) return;
Player player = event.getPlayer();
VanishConfig cfg = vanishConfigs.get(player.getName().toLowerCase());
if (cfg == null) return;
if (!cfg.vanished.state) return;
if (!cfg.drop.state) event.setCancelled(true);
}
/**
* Only has relevance for static access by Plugin.
* @param enabled
*/
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
/**
* Only for static access by plugin.
* @return
*/
public boolean isEnabled(){
return enabled;
}
public void setSettings(Settings settings){
this.settings = settings;
}
/**
* Adjust state of player to vanished, message player.
* @param player
*/
public void onVanish(Player player) {
onVanish(player, true);
}
/**
* Adjust state of player to vanished.
* @param player
* @param message If to message players.
*/
public void onVanish(Player player, boolean message) {
String name = player.getName();
boolean was = !addVanishedName(name);
String msg = null;
if (settings.sendFakeMessages && !settings.fakeQuitMessage.isEmpty()){
msg = settings.fakeQuitMessage.replaceAll("%name", name);
msg = msg.replaceAll("%displayname", player.getDisplayName());
}
for ( Player other : Bukkit.getServer().getOnlinePlayers()){
if (other.getName().equals(name)) continue;
if ( other.canSee(player)){
// (only consider a changed canSee state)
if (settings.notifyState && Utils.hasPermission(other, settings.notifyStatePerm)){
if (!was){
if (message) other.sendMessage(SimplyVanish.msgLabel+ChatColor.GREEN+name+ChatColor.GRAY+" vanished.");
}
if (!shouldSeeVanished(other)) hidePlayer(player, other);
} else if (!shouldSeeVanished(other)){
hidePlayer(player, other);
if (msg != null) other.sendMessage(msg);
}
} else if (!was && settings.notifyState && Utils.hasPermission(other, settings.notifyStatePerm)){
if (message) other.sendMessage(SimplyVanish.msgLabel+ChatColor.GREEN+name+ChatColor.GRAY+" vanished.");
}
}
if (message) player.sendMessage(was?SimplyVanish.msgStillInvisible:SimplyVanish.msgNowInvisible);
}
/**
* Central access point for checking if player has permission and wants to see vanished players.
* @param player
* @return
*/
public boolean shouldSeeVanished(Player player) {
VanishConfig cfg = vanishConfigs.get(player.getName().toLowerCase());
if(cfg!=null){
if (!cfg.see.state) return false;
}
return Utils.hasPermission(player, "simplyvanish.see-all");
}
/**
* Adjust state of player to not vanished.
* @param player
*/
public void onReappear(Player player) {
String name = player.getName();
boolean was = removeVanishedName(name);
String msg = null;
if (settings.sendFakeMessages && !settings.fakeJoinMessage.isEmpty()){
msg = settings.fakeJoinMessage.replaceAll("%name", name);
msg = msg.replaceAll("%displayname", player.getDisplayName());
}
for ( Player other : Bukkit.getServer().getOnlinePlayers()){
if (other.getName().equals(name)) continue;
if (!other.canSee(player)){
// (only consider a changed canSee state)
showPlayer(player, other);
if (settings.notifyState && Utils.hasPermission(other, settings.notifyStatePerm)){
other.sendMessage(SimplyVanish.msgLabel+ChatColor.RED+name+ChatColor.GRAY+" reappeared.");
} else if (!shouldSeeVanished(other)){
if (msg != null) other.sendMessage(msg);
}
}
else if (was && settings.notifyState && Utils.hasPermission(other, settings.notifyStatePerm)){
other.sendMessage(SimplyVanish.msgLabel+ChatColor.RED+name+ChatColor.GRAY+" reappeared.");
}
}
player.sendMessage(SimplyVanish.msgLabel+ChatColor.GRAY+"You are "+(was?"now":"still")+" "+ChatColor.RED+"visible"+ChatColor.GRAY+" to everyone!");
}
/**
* Heavy update for who can see this player and whom this player can see.
* @param player
*/
public void updateVanishState(Player player){
updateVanishState(player, true);
}
/**
* Heavy update for who can see this player and whom this player can see and other way round.
* @param player
* @param message If to message the player.
*/
public void updateVanishState(Player player, boolean message){
String playerName = player.getName();
String lcName = playerName.toLowerCase();
Server server = Bukkit.getServer();
Player[] players = server.getOnlinePlayers();
boolean shouldSee = shouldSeeVanished(player);
boolean was = removeVanishedName(lcName);
// Show or hide other players to player:
for (Player other : players){
if (shouldSee||!isVanished(other.getName())){
if (!player.canSee(other)) showPlayer(other, player);
}
else if (player.canSee(other)) hidePlayer(other, player);
if (!was && !other.canSee(player)) showPlayer(player, other);
}
if (was) onVanish(player, message); // remove: a) do not save 2x b) people will get notified.
}
/**
* Unlikely that sorted is needed, but anyway.
* @return
*/
public List<String> getSortedVanished(){
Collection<String> vanished = getVanishedPlayers();
List<String> sorted = new ArrayList<String>(vanished.size());
sorted.addAll(vanished);
Collections.sort(sorted);
return sorted;
}
/**
* Show player to canSee.
* Delegating method, for the case of other things to be checked.
* @param player The player to show.
* @param canSee
*/
void showPlayer(Player player, Player canSee){
if (!checkInvolved(player, canSee, "showPlayer")) return;
try{
canSee.showPlayer(player);
} catch(Throwable t){
Utils.severe("showPlayer failed (show "+player.getName()+" to "+canSee.getName()+"): "+t.getMessage());
t.printStackTrace();
onPanic(new Player[]{player, canSee});
}
}
/**
* Hide player from canNotSee.
* Delegating method, for the case of other things to be checked.
* @param player The player to hide.
* @param canNotSee
*/
void hidePlayer(Player player, Player canNotSee){
if (!checkInvolved(player, canNotSee, "hidePlayer")) return;
try{
canNotSee.hidePlayer(player);
} catch ( Throwable t){
Utils.severe("hidePlayer failed (hide "+player.getName()+" from "+canNotSee.getName()+"): "+t.getMessage());
t.printStackTrace();
onPanic(new Player[]{player, canNotSee});
}
}
/**
* Do online checking and also check settings if to continue.
* @param player1 The player to be shown or hidden.
* @param player2
* @param tag
* @return true if to continue false if to abort.
*/
boolean checkInvolved(Player player1, Player player2, String tag){
boolean inconsistent = false;
if (!Utils.checkOnline(player1, tag)) inconsistent = true;
if (!Utils.checkOnline(player2, tag)) inconsistent = true;
if (settings.noAbort){
return true;
} else if (inconsistent){
try{
player1.sendMessage(SimplyVanish.msgLabel+ChatColor.RED+"Warning: Could not use "+tag+" to player: "+player2.getName());
} catch (Throwable t){
}
}
return !inconsistent; // "true = continue = not inconsistent"
}
void onPanic(Player[] involved){
Server server = Bukkit.getServer();
if ( settings.panicKickAll){
for ( Player player : server.getOnlinePlayers()){
try{
player.kickPlayer(settings.panicKickMessage);
} catch (Throwable t){
// ignore
}
}
}
else if (settings.panicKickInvolved){
for ( Player player : involved){
try{
player.kickPlayer(settings.panicKickMessage);
} catch (Throwable t){
// ignore
}
}
}
try{
Utils.sendToTargets(settings.panicMessage, settings.panicMessageTargets);
} catch ( Throwable t){
Utils.warn("[Panic] Failed to send to: "+settings.panicMessageTargets+" ("+t.getMessage()+")");
t.printStackTrace();
}
if (settings.panicRunCommand && !"".equals(settings.panicCommand)){
try{
server.dispatchCommand(server.getConsoleSender(), settings.panicCommand);
} catch (Throwable t){
Utils.warn("[Panic] Failed to dispathc command: "+settings.panicCommand+" ("+t.getMessage()+")");
t.printStackTrace();
}
}
}
public boolean addVanishedName(String name) {
VanishConfig cfg = getVanishConfig(name);
boolean res = false;
if (!cfg.vanished.state){
cfg.vanished.state = true;
cfg.changed = true;
res = true;
}
if (cfg.changed && settings.saveVanishedAlways) saveVanished();
return res;
}
/**
*
* @param name
* @return If the player was vanished.
*/
public boolean removeVanishedName(String name) {
VanishConfig cfg = vanishConfigs.get(name.toLowerCase());
if (cfg==null) return false;
boolean res = false;
if (cfg.vanished.state){
cfg.vanished.state = false;
if (!cfg.needsSave()) vanishConfigs.remove(name.toLowerCase());
cfg.changed = true;
res = true;
}
if (cfg.changed && settings.saveVanishedAlways) saveVanished();
return res;
}
public String getVanishedMessage() {
List<String> sorted = getSortedVanished();
StringBuilder builder = new StringBuilder();
builder.append(ChatColor.GOLD+"[VANISHED]");
Server server = Bukkit.getServer();
boolean found = false;
for ( String n : sorted){
Player player = server.getPlayerExact(n);
VanishConfig cfg = vanishConfigs.get(n);
if (!cfg.vanished.state) continue;
found = true;
boolean isNosee = !cfg.see.state; // is lower case
if ( player == null ){
builder.append(" "+ChatColor.GRAY+"("+n+")");
if (isNosee) builder.append(ChatColor.DARK_RED+"[NOSEE]");
}
else{
builder.append(" "+ChatColor.GREEN+player.getName());
if (!Utils.hasPermission(player, "simplyvanish.see-all")) builder.append(ChatColor.DARK_RED+"[CANTSEE]");
else if (isNosee) builder.append(ChatColor.RED+"[NOSEE]");
}
}
if (!found) builder.append(" "+ChatColor.DARK_GRAY+"<none>");
return builder.toString();
}
/**
* Get a VanishConfig, create it if necessary.<br>
* (Might be from vanished, parked, or new thus put to parked).
* @param playerName
* @return
*/
public VanishConfig getVanishConfig(String playerName){
playerName = playerName.toLowerCase();
VanishConfig cfg = vanishConfigs.get(playerName);
if (cfg != null) return cfg;
cfg = new VanishConfig();
vanishConfigs.put(playerName, cfg);
return cfg;
}
public boolean isVanished(final String playerName) {
final VanishConfig cfg = vanishConfigs.get(playerName.toLowerCase());
if (cfg == null) return false;
else return cfg.vanished.state;
}
public void setVanished(String playerName, boolean vanished) {
Player player = Bukkit.getServer().getPlayerExact(playerName);
if (player != null){
// The simple part.
if ( vanished) onVanish(player, true);
else onReappear(player);
return;
}
// The less simple part.
if (vanished) addVanishedName(playerName);
else if (removeVanishedName(playerName)) return;
else{
// Expensive part:
String match = null;
for (String n : vanishConfigs.keySet()){
if ( n.equalsIgnoreCase(playerName)){
match = n;
break;
}
}
if ( match != null) removeVanishedName(match);
}
}
/**
* Lower case names.<br>
* Currently iterates over all VanishConfig entries.
* @return
*/
public Set<String> getVanishedPlayers() {
Set<String> out = new HashSet<String>();
for (Entry<String, VanishConfig> entry : vanishConfigs.entrySet()){
if (entry.getValue().vanished.state) out.add(entry.getKey());
}
return out;
}
/**
* Only set the flags, no save.
* TODO: probably needs a basic mix-in permission to avoid abuse (though that would need command spam).
* @param playerName
* @param args
* @param startIndex Start parsing flags from that index on.
* @param sender For performing permission checks.
* @param hasBypass Has some bypass permission (results in no checks)
* @param other If is sender is other than name
* @param save If to save state.
*/
public void setFlags(String playerName, String[] args, int startIndex, CommandSender sender, boolean hasBypass, boolean other, boolean save) {
playerName = playerName.trim().toLowerCase();
if (playerName.isEmpty()) return;
final String permBase = "simplyvanish.flags.set."+(other?"other":"self"); // bypass permission
if (!hasBypass) hasBypass = Utils.hasPermission(sender, permBase);
VanishConfig cfg = vanishConfigs.get(playerName);
boolean hasSomePerm = hasBypass; // indicates that the player has any permission at all.
if (cfg == null) cfg = new VanishConfig();
boolean hasClearFlag = false;
for ( int i = startIndex; i<args.length; i++){
String name = VanishConfig.getMappedFlagName(args[i].trim().toLowerCase());
if ( name.equals("clear")){
hasClearFlag = true;
break;
}
}
VanishConfig newCfg;
if (hasClearFlag){
newCfg = new VanishConfig();
newCfg.set("vanished", cfg.get("vanished"));
}
else newCfg = cfg.clone();
newCfg.readFromArray(args, startIndex, false);
List<String> changes = cfg.getChanges(newCfg);
// Determine permissions and apply valid changes:
Set<String> missing = null;
if (!hasBypass){
missing = new HashSet<String>();
- for ( String name : changes){
- if (!Utils.hasPermission(sender, permBase+".name")) missing.add(name);
+ for ( String fn : changes){
+ String name = fn.substring(1);
+ System.out.println(name);
+ if (!Utils.hasPermission(sender, permBase+"."+name)) missing.add(name);
else{
hasSomePerm = true;
cfg.set(name, newCfg.get(name));
}
}
}
if (missing != null && !missing.isEmpty()) Utils.send(sender, SimplyVanish.msgLabel+ChatColor.RED+"Missing permission for flags: "+Utils.join(missing, ", "));
if (!hasBypass && !hasSomePerm){
// Difficult: might be a player without ANY permission.
// TODO: maybe check permissions for all flags
Utils.send(sender, SimplyVanish.msgLabel+ChatColor.DARK_RED+"You can not set these flags.");
return;
}
// if pass:
vanishConfigs.put(playerName, cfg); // just to ensure it is there.
if ( save && cfg.changed && settings.saveVanishedAlways) saveVanished();
Player player = Bukkit.getServer().getPlayerExact(playerName);
if (player != null) updateVanishState(player, false);
}
public void onShowFlags(CommandSender sender, String name) {
if ( name == null) name = sender.getName();
name = name.toLowerCase();
VanishConfig cfg = vanishConfigs.get(name);
if (cfg==null) return;
sender.sendMessage(SimplyVanish.msgLabel+ChatColor.GRAY+"Flags("+name+"): "+cfg.toLine());
}
public void onNotifyPing() {
if (!settings.pingEnabled) return;
for ( final Entry<String, VanishConfig> entry : vanishConfigs.entrySet()){
final Player player = Bukkit.getPlayerExact(entry.getKey());
if (player==null) continue;
final VanishConfig cfg = entry.getValue();
if (!cfg.vanished.state) continue;
if (!cfg.ping.state) continue;
player.sendMessage(SimplyVanish.msgNotifyPing);
}
}
}
| true | true | public void setFlags(String playerName, String[] args, int startIndex, CommandSender sender, boolean hasBypass, boolean other, boolean save) {
playerName = playerName.trim().toLowerCase();
if (playerName.isEmpty()) return;
final String permBase = "simplyvanish.flags.set."+(other?"other":"self"); // bypass permission
if (!hasBypass) hasBypass = Utils.hasPermission(sender, permBase);
VanishConfig cfg = vanishConfigs.get(playerName);
boolean hasSomePerm = hasBypass; // indicates that the player has any permission at all.
if (cfg == null) cfg = new VanishConfig();
boolean hasClearFlag = false;
for ( int i = startIndex; i<args.length; i++){
String name = VanishConfig.getMappedFlagName(args[i].trim().toLowerCase());
if ( name.equals("clear")){
hasClearFlag = true;
break;
}
}
VanishConfig newCfg;
if (hasClearFlag){
newCfg = new VanishConfig();
newCfg.set("vanished", cfg.get("vanished"));
}
else newCfg = cfg.clone();
newCfg.readFromArray(args, startIndex, false);
List<String> changes = cfg.getChanges(newCfg);
// Determine permissions and apply valid changes:
Set<String> missing = null;
if (!hasBypass){
missing = new HashSet<String>();
for ( String name : changes){
if (!Utils.hasPermission(sender, permBase+".name")) missing.add(name);
else{
hasSomePerm = true;
cfg.set(name, newCfg.get(name));
}
}
}
if (missing != null && !missing.isEmpty()) Utils.send(sender, SimplyVanish.msgLabel+ChatColor.RED+"Missing permission for flags: "+Utils.join(missing, ", "));
if (!hasBypass && !hasSomePerm){
// Difficult: might be a player without ANY permission.
// TODO: maybe check permissions for all flags
Utils.send(sender, SimplyVanish.msgLabel+ChatColor.DARK_RED+"You can not set these flags.");
return;
}
// if pass:
vanishConfigs.put(playerName, cfg); // just to ensure it is there.
if ( save && cfg.changed && settings.saveVanishedAlways) saveVanished();
Player player = Bukkit.getServer().getPlayerExact(playerName);
if (player != null) updateVanishState(player, false);
}
| public void setFlags(String playerName, String[] args, int startIndex, CommandSender sender, boolean hasBypass, boolean other, boolean save) {
playerName = playerName.trim().toLowerCase();
if (playerName.isEmpty()) return;
final String permBase = "simplyvanish.flags.set."+(other?"other":"self"); // bypass permission
if (!hasBypass) hasBypass = Utils.hasPermission(sender, permBase);
VanishConfig cfg = vanishConfigs.get(playerName);
boolean hasSomePerm = hasBypass; // indicates that the player has any permission at all.
if (cfg == null) cfg = new VanishConfig();
boolean hasClearFlag = false;
for ( int i = startIndex; i<args.length; i++){
String name = VanishConfig.getMappedFlagName(args[i].trim().toLowerCase());
if ( name.equals("clear")){
hasClearFlag = true;
break;
}
}
VanishConfig newCfg;
if (hasClearFlag){
newCfg = new VanishConfig();
newCfg.set("vanished", cfg.get("vanished"));
}
else newCfg = cfg.clone();
newCfg.readFromArray(args, startIndex, false);
List<String> changes = cfg.getChanges(newCfg);
// Determine permissions and apply valid changes:
Set<String> missing = null;
if (!hasBypass){
missing = new HashSet<String>();
for ( String fn : changes){
String name = fn.substring(1);
System.out.println(name);
if (!Utils.hasPermission(sender, permBase+"."+name)) missing.add(name);
else{
hasSomePerm = true;
cfg.set(name, newCfg.get(name));
}
}
}
if (missing != null && !missing.isEmpty()) Utils.send(sender, SimplyVanish.msgLabel+ChatColor.RED+"Missing permission for flags: "+Utils.join(missing, ", "));
if (!hasBypass && !hasSomePerm){
// Difficult: might be a player without ANY permission.
// TODO: maybe check permissions for all flags
Utils.send(sender, SimplyVanish.msgLabel+ChatColor.DARK_RED+"You can not set these flags.");
return;
}
// if pass:
vanishConfigs.put(playerName, cfg); // just to ensure it is there.
if ( save && cfg.changed && settings.saveVanishedAlways) saveVanished();
Player player = Bukkit.getServer().getPlayerExact(playerName);
if (player != null) updateVanishState(player, false);
}
|
diff --git a/src/org/mozilla/javascript/Interpreter.java b/src/org/mozilla/javascript/Interpreter.java
index 0673433c..189d6193 100644
--- a/src/org/mozilla/javascript/Interpreter.java
+++ b/src/org/mozilla/javascript/Interpreter.java
@@ -1,3042 +1,3041 @@
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is Rhino code, released
* May 6, 1999.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1997-2000 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Patrick Beard
* Norris Boyd
* Igor Bukanov
* Roger Lawrence
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU Public License (the "GPL"), in which case the
* provisions of the GPL are applicable instead of those above.
* If you wish to allow use of your version of this file only
* under the terms of the GPL and not to allow others to use your
* version of this file under the NPL, indicate your decision by
* deleting the provisions above and replace them with the notice
* and other provisions required by the GPL. If you do not delete
* the provisions above, a recipient may use your version of this
* file under either the NPL or the GPL.
*/
package org.mozilla.javascript;
import java.io.*;
import org.mozilla.javascript.debug.*;
public class Interpreter
{
// Additional interpreter-specific codes
private static final int BASE_ICODE = Token.LAST_BYTECODE_TOKEN;
private static final int
Icode_DUP = BASE_ICODE + 1,
// various types of ++/--
Icode_NAMEINC = BASE_ICODE + 2,
Icode_PROPINC = BASE_ICODE + 3,
Icode_ELEMINC = BASE_ICODE + 4,
Icode_VARINC = BASE_ICODE + 5,
Icode_NAMEDEC = BASE_ICODE + 6,
Icode_PROPDEC = BASE_ICODE + 7,
Icode_ELEMDEC = BASE_ICODE + 8,
Icode_VARDEC = BASE_ICODE + 9,
// helper codes to deal with activation
Icode_SCOPE = BASE_ICODE + 10,
Icode_TYPEOFNAME = BASE_ICODE + 11,
// Access to parent scope and prototype
Icode_GETPROTO = BASE_ICODE + 12,
Icode_GETPARENT = BASE_ICODE + 13,
Icode_GETSCOPEPARENT = BASE_ICODE + 14,
Icode_SETPROTO = BASE_ICODE + 15,
Icode_SETPARENT = BASE_ICODE + 16,
// Create closure object for nested functions
Icode_CLOSURE = BASE_ICODE + 17,
// Special calls
Icode_CALLSPECIAL = BASE_ICODE + 18,
// To return undefined value
Icode_RETUNDEF = BASE_ICODE + 19,
// Exception handling implementation
Icode_CATCH = BASE_ICODE + 20,
Icode_GOSUB = BASE_ICODE + 21,
Icode_RETSUB = BASE_ICODE + 22,
// To indicating a line number change in icodes.
Icode_LINE = BASE_ICODE + 23,
// To store shorts and ints inline
Icode_SHORTNUMBER = BASE_ICODE + 24,
Icode_INTNUMBER = BASE_ICODE + 25,
// Last icode
Icode_END = BASE_ICODE + 26;
public IRFactory createIRFactory(Context cx, TokenStream ts)
{
return new IRFactory(this, ts);
}
public FunctionNode createFunctionNode(IRFactory irFactory, String name)
{
return new FunctionNode(name);
}
public ScriptOrFnNode transform(Context cx, IRFactory irFactory,
ScriptOrFnNode tree)
{
(new NodeTransformer(irFactory)).transform(tree);
return tree;
}
public Object compile(Context cx, Scriptable scope, ScriptOrFnNode tree,
SecurityController securityController,
Object securityDomain, String encodedSource)
{
scriptOrFn = tree;
itsData = new InterpreterData(securityDomain, cx.getLanguageVersion());
itsData.itsSourceFile = scriptOrFn.getSourceName();
itsData.encodedSource = encodedSource;
if (tree instanceof FunctionNode) {
generateFunctionICode(cx, scope);
return createFunction(cx, scope, itsData, false);
} else {
generateICodeFromTree(cx, scope, scriptOrFn);
return new InterpretedScript(itsData);
}
}
public void notifyDebuggerCompilationDone(Context cx,
Object scriptOrFunction,
String debugSource)
{
InterpreterData idata;
if (scriptOrFunction instanceof InterpretedScript) {
idata = ((InterpretedScript)scriptOrFunction).itsData;
} else {
idata = ((InterpretedFunction)scriptOrFunction).itsData;
}
notifyDebugger_r(cx, idata, debugSource);
}
private static void notifyDebugger_r(Context cx, InterpreterData idata,
String debugSource)
{
if (idata.itsNestedFunctions != null) {
for (int i = 0; i != idata.itsNestedFunctions.length; ++i) {
notifyDebugger_r(cx, idata.itsNestedFunctions[i], debugSource);
}
}
cx.debugger.handleCompilationDone(cx, idata, debugSource);
}
private void generateFunctionICode(Context cx, Scriptable scope)
{
FunctionNode theFunction = (FunctionNode)scriptOrFn;
itsData.itsFunctionType = theFunction.getFunctionType();
itsData.itsNeedsActivation = theFunction.requiresActivation();
itsData.itsName = theFunction.getFunctionName();
generateICodeFromTree(cx, scope, theFunction.getLastChild());
}
private void generateICodeFromTree(Context cx, Scriptable scope, Node tree)
{
generateNestedFunctions(cx, scope);
generateRegExpLiterals(cx, scope);
int theICodeTop = 0;
theICodeTop = generateICode(tree, theICodeTop);
itsLabels.fixLabelGotos(itsData.itsICode);
// add Icode_END only to scripts as function always ends with RETURN
if (itsData.itsFunctionType == 0) {
theICodeTop = addIcode(Icode_END, theICodeTop);
}
// Add special CATCH to simplify Interpreter.interpret logic
// and workaround lack of goto in Java
theICodeTop = addIcode(Icode_CATCH, theICodeTop);
itsData.itsICodeTop = theICodeTop;
if (itsData.itsICode.length != theICodeTop) {
// Make itsData.itsICode length exactly theICodeTop to save memory
// and catch bugs with jumps beyound icode as early as possible
byte[] tmp = new byte[theICodeTop];
System.arraycopy(itsData.itsICode, 0, tmp, 0, theICodeTop);
itsData.itsICode = tmp;
}
if (itsStrings.size() == 0) {
itsData.itsStringTable = null;
} else {
itsData.itsStringTable = new String[itsStrings.size()];
ObjToIntMap.Iterator iter = itsStrings.newIterator();
for (iter.start(); !iter.done(); iter.next()) {
String str = (String)iter.getKey();
int index = iter.getValue();
if (itsData.itsStringTable[index] != null) Context.codeBug();
itsData.itsStringTable[index] = str;
}
}
if (itsDoubleTableTop == 0) {
itsData.itsDoubleTable = null;
} else if (itsData.itsDoubleTable.length != itsDoubleTableTop) {
double[] tmp = new double[itsDoubleTableTop];
System.arraycopy(itsData.itsDoubleTable, 0, tmp, 0,
itsDoubleTableTop);
itsData.itsDoubleTable = tmp;
}
if (itsExceptionTableTop != 0
&& itsData.itsExceptionTable.length != itsExceptionTableTop)
{
int[] tmp = new int[itsExceptionTableTop];
System.arraycopy(itsData.itsExceptionTable, 0, tmp, 0,
itsExceptionTableTop);
itsData.itsExceptionTable = tmp;
}
itsData.itsMaxVars = scriptOrFn.getParamAndVarCount();
// itsMaxFrameArray: interpret method needs this amount for its
// stack and sDbl arrays
itsData.itsMaxFrameArray = itsData.itsMaxVars
+ itsData.itsMaxLocals
+ itsData.itsMaxStack;
itsData.argNames = scriptOrFn.getParamAndVarNames();
itsData.argCount = scriptOrFn.getParamCount();
itsData.encodedSourceStart = scriptOrFn.getEncodedSourceStart();
itsData.encodedSourceEnd = scriptOrFn.getEncodedSourceEnd();
if (Token.printICode) dumpICode(itsData);
}
private void generateNestedFunctions(Context cx, Scriptable scope)
{
int functionCount = scriptOrFn.getFunctionCount();
if (functionCount == 0) return;
InterpreterData[] array = new InterpreterData[functionCount];
for (int i = 0; i != functionCount; i++) {
FunctionNode def = scriptOrFn.getFunctionNode(i);
Interpreter jsi = new Interpreter();
jsi.scriptOrFn = def;
jsi.itsData = new InterpreterData(itsData.securityDomain,
itsData.languageVersion);
jsi.itsData.itsSourceFile = itsData.itsSourceFile;
jsi.itsData.encodedSource = itsData.encodedSource;
jsi.itsData.itsCheckThis = def.getCheckThis();
jsi.itsInFunctionFlag = true;
jsi.generateFunctionICode(cx, scope);
array[i] = jsi.itsData;
}
itsData.itsNestedFunctions = array;
}
private void generateRegExpLiterals(Context cx, Scriptable scope)
{
int N = scriptOrFn.getRegexpCount();
if (N == 0) return;
RegExpProxy rep = cx.getRegExpProxy();
if (rep == null) {
throw cx.reportRuntimeError0("msg.no.regexp");
}
Object[] array = new Object[N];
for (int i = 0; i != N; i++) {
String string = scriptOrFn.getRegexpString(i);
String flags = scriptOrFn.getRegexpFlags(i);
array[i] = rep.newRegExp(cx, scope, string, flags, false);
}
itsData.itsRegExpLiterals = array;
}
private int updateLineNumber(Node node, int iCodeTop)
{
int lineno = node.getLineno();
if (lineno != itsLineNumber && lineno >= 0) {
itsLineNumber = lineno;
iCodeTop = addIcode(Icode_LINE, iCodeTop);
iCodeTop = addShort(lineno, iCodeTop);
}
return iCodeTop;
}
private void badTree(Node node)
{
throw new RuntimeException("Un-handled node: "+node.toString());
}
private int generateICode(Node node, int iCodeTop)
{
int type = node.getType();
Node child = node.getFirstChild();
Node firstChild = child;
switch (type) {
case Token.FUNCTION : {
int fnIndex = node.getExistingIntProp(Node.FUNCTION_PROP);
FunctionNode fn = scriptOrFn.getFunctionNode(fnIndex);
if (fn.itsFunctionType != FunctionNode.FUNCTION_STATEMENT) {
// Only function expressions or function expression
// statements needs closure code creating new function
// object on stack as function statements are initialized
// at script/function start
iCodeTop = addIcode(Icode_CLOSURE, iCodeTop);
iCodeTop = addIndex(fnIndex, iCodeTop);
itsStackDepth++;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
}
break;
}
case Token.SCRIPT :
iCodeTop = updateLineNumber(node, iCodeTop);
while (child != null) {
if (child.getType() != Token.FUNCTION)
iCodeTop = generateICode(child, iCodeTop);
child = child.getNext();
}
break;
case Token.CASE :
iCodeTop = updateLineNumber(node, iCodeTop);
child = child.getNext();
while (child != null) {
iCodeTop = generateICode(child, iCodeTop);
child = child.getNext();
}
break;
case Token.LABEL :
case Token.LOOP :
case Token.DEFAULT :
case Token.BLOCK :
case Token.EMPTY :
case Token.NOP :
iCodeTop = updateLineNumber(node, iCodeTop);
while (child != null) {
iCodeTop = generateICode(child, iCodeTop);
child = child.getNext();
}
break;
case Token.WITH :
++itsWithDepth;
iCodeTop = updateLineNumber(node, iCodeTop);
while (child != null) {
iCodeTop = generateICode(child, iCodeTop);
child = child.getNext();
}
--itsWithDepth;
break;
case Token.COMMA :
iCodeTop = generateICode(child, iCodeTop);
while (null != (child = child.getNext())) {
iCodeTop = addToken(Token.POP, iCodeTop);
itsStackDepth--;
iCodeTop = generateICode(child, iCodeTop);
}
break;
case Token.SWITCH : {
iCodeTop = updateLineNumber(node, iCodeTop);
iCodeTop = generateICode(child, iCodeTop);
int theLocalSlot = itsData.itsMaxLocals++;
iCodeTop = addToken(Token.NEWTEMP, iCodeTop);
iCodeTop = addByte(theLocalSlot, iCodeTop);
iCodeTop = addToken(Token.POP, iCodeTop);
itsStackDepth--;
ObjArray cases = (ObjArray) node.getProp(Node.CASES_PROP);
for (int i = 0; i < cases.size(); i++) {
Node thisCase = (Node)cases.get(i);
Node first = thisCase.getFirstChild();
// the case expression is the firstmost child
// the rest will be generated when the case
// statements are encountered as siblings of
// the switch statement.
iCodeTop = generateICode(first, iCodeTop);
iCodeTop = addToken(Token.USETEMP, iCodeTop);
iCodeTop = addByte(theLocalSlot, iCodeTop);
itsStackDepth++;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
iCodeTop = addToken(Token.SHEQ, iCodeTop);
itsStackDepth--;
Node target = new Node(Token.TARGET);
thisCase.addChildAfter(target, first);
iCodeTop = addGoto(target, Token.IFEQ, iCodeTop);
}
Node defaultNode = (Node) node.getProp(Node.DEFAULT_PROP);
if (defaultNode != null) {
Node defaultTarget = new Node(Token.TARGET);
defaultNode.getFirstChild().
addChildToFront(defaultTarget);
iCodeTop = addGoto(defaultTarget, Token.GOTO,
iCodeTop);
}
Node breakTarget = (Node) node.getProp(Node.BREAK_PROP);
iCodeTop = addGoto(breakTarget, Token.GOTO,
iCodeTop);
break;
}
case Token.TARGET :
markTargetLabel(node, iCodeTop);
break;
case Token.NEW :
case Token.CALL : {
int childCount = 0;
String functionName = null;
while (child != null) {
iCodeTop = generateICode(child, iCodeTop);
if (functionName == null) {
int childType = child.getType();
if (childType == Token.NAME
|| childType == Token.GETPROP)
{
functionName = lastAddString;
}
}
child = child.getNext();
childCount++;
}
int callType = node.getIntProp(Node.SPECIALCALL_PROP,
Node.NON_SPECIALCALL);
if (callType != Node.NON_SPECIALCALL) {
// embed line number and source filename
iCodeTop = addIcode(Icode_CALLSPECIAL, iCodeTop);
iCodeTop = addByte(callType, iCodeTop);
iCodeTop = addByte(type == Token.NEW ? 1 : 0, iCodeTop);
iCodeTop = addShort(itsLineNumber, iCodeTop);
} else {
iCodeTop = addToken(type, iCodeTop);
iCodeTop = addString(functionName, iCodeTop);
}
itsStackDepth -= (childCount - 1); // always a result value
// subtract from child count to account for [thisObj &] fun
if (type == Token.NEW) {
childCount -= 1;
} else {
childCount -= 2;
}
iCodeTop = addIndex(childCount, iCodeTop);
if (childCount > itsData.itsMaxCalleeArgs)
itsData.itsMaxCalleeArgs = childCount;
break;
}
case Token.NEWLOCAL :
case Token.NEWTEMP : {
iCodeTop = generateICode(child, iCodeTop);
iCodeTop = addToken(Token.NEWTEMP, iCodeTop);
iCodeTop = addLocalRef(node, iCodeTop);
break;
}
case Token.USELOCAL : {
if (node.getProp(Node.TARGET_PROP) != null) {
iCodeTop = addIcode(Icode_RETSUB, iCodeTop);
} else {
iCodeTop = addToken(Token.USETEMP, iCodeTop);
itsStackDepth++;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
}
Node temp = (Node) node.getProp(Node.LOCAL_PROP);
iCodeTop = addLocalRef(temp, iCodeTop);
break;
}
case Token.USETEMP : {
iCodeTop = addToken(Token.USETEMP, iCodeTop);
Node temp = (Node) node.getProp(Node.TEMP_PROP);
iCodeTop = addLocalRef(temp, iCodeTop);
itsStackDepth++;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
break;
}
case Token.IFEQ :
case Token.IFNE :
iCodeTop = generateICode(child, iCodeTop);
itsStackDepth--; // after the conditional GOTO, really
// fall thru...
case Token.GOTO : {
Node target = (Node)(node.getProp(Node.TARGET_PROP));
iCodeTop = addGoto(target, (byte) type, iCodeTop);
break;
}
case Token.JSR : {
Node target = (Node)(node.getProp(Node.TARGET_PROP));
iCodeTop = addGoto(target, Icode_GOSUB, iCodeTop);
break;
}
case Token.AND : {
iCodeTop = generateICode(child, iCodeTop);
iCodeTop = addIcode(Icode_DUP, iCodeTop);
itsStackDepth++;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
int falseJumpStart = iCodeTop;
iCodeTop = addForwardGoto(Token.IFNE, iCodeTop);
iCodeTop = addToken(Token.POP, iCodeTop);
itsStackDepth--;
child = child.getNext();
iCodeTop = generateICode(child, iCodeTop);
resolveForwardGoto(falseJumpStart, iCodeTop);
break;
}
case Token.OR : {
iCodeTop = generateICode(child, iCodeTop);
iCodeTop = addIcode(Icode_DUP, iCodeTop);
itsStackDepth++;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
int trueJumpStart = iCodeTop;
iCodeTop = addForwardGoto(Token.IFEQ, iCodeTop);
iCodeTop = addToken(Token.POP, iCodeTop);
itsStackDepth--;
child = child.getNext();
iCodeTop = generateICode(child, iCodeTop);
resolveForwardGoto(trueJumpStart, iCodeTop);
break;
}
case Token.GETPROP : {
iCodeTop = generateICode(child, iCodeTop);
String s = (String) node.getProp(Node.SPECIAL_PROP_PROP);
if (s != null) {
if (s.equals("__proto__")) {
iCodeTop = addIcode(Icode_GETPROTO, iCodeTop);
} else if (s.equals("__parent__")) {
iCodeTop = addIcode(Icode_GETSCOPEPARENT, iCodeTop);
} else {
badTree(node);
}
} else {
child = child.getNext();
iCodeTop = generateICode(child, iCodeTop);
iCodeTop = addToken(Token.GETPROP, iCodeTop);
itsStackDepth--;
}
break;
}
case Token.DELPROP :
case Token.BITAND :
case Token.BITOR :
case Token.BITXOR :
case Token.LSH :
case Token.RSH :
case Token.URSH :
case Token.ADD :
case Token.SUB :
case Token.MOD :
case Token.DIV :
case Token.MUL :
case Token.GETELEM :
case Token.EQ:
case Token.NE:
case Token.SHEQ:
case Token.SHNE:
case Token.IN :
case Token.INSTANCEOF :
case Token.LE :
case Token.LT :
case Token.GE :
case Token.GT :
iCodeTop = generateICode(child, iCodeTop);
child = child.getNext();
iCodeTop = generateICode(child, iCodeTop);
iCodeTop = addToken(type, iCodeTop);
itsStackDepth--;
break;
case Token.POS :
case Token.NEG :
case Token.NOT :
case Token.BITNOT :
case Token.TYPEOF :
case Token.VOID :
iCodeTop = generateICode(child, iCodeTop);
if (type == Token.VOID) {
iCodeTop = addToken(Token.POP, iCodeTop);
iCodeTop = addToken(Token.UNDEFINED, iCodeTop);
} else {
iCodeTop = addToken(type, iCodeTop);
}
break;
case Token.SETPROP : {
iCodeTop = generateICode(child, iCodeTop);
child = child.getNext();
iCodeTop = generateICode(child, iCodeTop);
String s = (String) node.getProp(Node.SPECIAL_PROP_PROP);
if (s != null) {
if (s.equals("__proto__")) {
iCodeTop = addIcode(Icode_SETPROTO, iCodeTop);
} else if (s.equals("__parent__")) {
iCodeTop = addIcode(Icode_SETPARENT, iCodeTop);
} else {
badTree(node);
}
} else {
child = child.getNext();
iCodeTop = generateICode(child, iCodeTop);
iCodeTop = addToken(Token.SETPROP, iCodeTop);
itsStackDepth -= 2;
}
break;
}
case Token.SETELEM :
iCodeTop = generateICode(child, iCodeTop);
child = child.getNext();
iCodeTop = generateICode(child, iCodeTop);
child = child.getNext();
iCodeTop = generateICode(child, iCodeTop);
iCodeTop = addToken(Token.SETELEM, iCodeTop);
itsStackDepth -= 2;
break;
case Token.SETNAME :
iCodeTop = generateICode(child, iCodeTop);
child = child.getNext();
iCodeTop = generateICode(child, iCodeTop);
iCodeTop = addToken(Token.SETNAME, iCodeTop);
iCodeTop = addString(firstChild.getString(), iCodeTop);
itsStackDepth--;
break;
case Token.TYPEOFNAME : {
String name = node.getString();
int index = -1;
// use typeofname if an activation frame exists
// since the vars all exist there instead of in jregs
if (itsInFunctionFlag && !itsData.itsNeedsActivation)
index = scriptOrFn.getParamOrVarIndex(name);
if (index == -1) {
iCodeTop = addIcode(Icode_TYPEOFNAME, iCodeTop);
iCodeTop = addString(name, iCodeTop);
} else {
iCodeTop = addToken(Token.GETVAR, iCodeTop);
iCodeTop = addByte(index, iCodeTop);
iCodeTop = addToken(Token.TYPEOF, iCodeTop);
}
itsStackDepth++;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
break;
}
case Token.PARENT :
iCodeTop = generateICode(child, iCodeTop);
iCodeTop = addIcode(Icode_GETPARENT, iCodeTop);
break;
case Token.GETBASE :
case Token.BINDNAME :
case Token.NAME :
case Token.STRING :
iCodeTop = addToken(type, iCodeTop);
iCodeTop = addString(node.getString(), iCodeTop);
itsStackDepth++;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
break;
case Token.INC :
case Token.DEC : {
int childType = child.getType();
switch (childType) {
case Token.GETVAR : {
String name = child.getString();
if (itsData.itsNeedsActivation) {
iCodeTop = addIcode(Icode_SCOPE, iCodeTop);
iCodeTop = addToken(Token.STRING, iCodeTop);
iCodeTop = addString(name, iCodeTop);
itsStackDepth += 2;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
iCodeTop = addIcode(type == Token.INC
? Icode_PROPINC
: Icode_PROPDEC,
iCodeTop);
itsStackDepth--;
} else {
int i = scriptOrFn.getParamOrVarIndex(name);
iCodeTop = addIcode(type == Token.INC
? Icode_VARINC
: Icode_VARDEC,
iCodeTop);
iCodeTop = addByte(i, iCodeTop);
itsStackDepth++;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
}
break;
}
case Token.GETPROP :
case Token.GETELEM : {
Node getPropChild = child.getFirstChild();
iCodeTop = generateICode(getPropChild, iCodeTop);
getPropChild = getPropChild.getNext();
iCodeTop = generateICode(getPropChild, iCodeTop);
int icode;
if (childType == Token.GETPROP) {
icode = (type == Token.INC)
? Icode_PROPINC : Icode_PROPDEC;
} else {
icode = (type == Token.INC)
? Icode_ELEMINC : Icode_ELEMDEC;
}
iCodeTop = addIcode(icode, iCodeTop);
itsStackDepth--;
break;
}
default : {
iCodeTop = addIcode(type == Token.INC
? Icode_NAMEINC
: Icode_NAMEDEC,
iCodeTop);
iCodeTop = addString(child.getString(), iCodeTop);
itsStackDepth++;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
break;
}
}
break;
}
case Token.NUMBER : {
double num = node.getDouble();
int inum = (int)num;
if (inum == num) {
if (inum == 0) {
iCodeTop = addToken(Token.ZERO, iCodeTop);
} else if (inum == 1) {
iCodeTop = addToken(Token.ONE, iCodeTop);
} else if ((short)inum == inum) {
iCodeTop = addIcode(Icode_SHORTNUMBER, iCodeTop);
iCodeTop = addShort(inum, iCodeTop);
} else {
iCodeTop = addIcode(Icode_INTNUMBER, iCodeTop);
iCodeTop = addInt(inum, iCodeTop);
}
} else {
iCodeTop = addToken(Token.NUMBER, iCodeTop);
iCodeTop = addDouble(num, iCodeTop);
}
itsStackDepth++;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
break;
}
case Token.POP :
case Token.POPV :
iCodeTop = updateLineNumber(node, iCodeTop);
iCodeTop = generateICode(child, iCodeTop);
iCodeTop = addToken(type, iCodeTop);
itsStackDepth--;
break;
case Token.ENTERWITH :
iCodeTop = generateICode(child, iCodeTop);
iCodeTop = addToken(Token.ENTERWITH, iCodeTop);
itsStackDepth--;
break;
case Token.GETTHIS :
iCodeTop = generateICode(child, iCodeTop);
iCodeTop = addToken(Token.GETTHIS, iCodeTop);
break;
case Token.NEWSCOPE :
iCodeTop = addToken(Token.NEWSCOPE, iCodeTop);
itsStackDepth++;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
break;
case Token.LEAVEWITH :
iCodeTop = addToken(Token.LEAVEWITH, iCodeTop);
break;
case Token.TRY : {
Node catchTarget = (Node)node.getProp(Node.TARGET_PROP);
Node finallyTarget = (Node)node.getProp(Node.FINALLY_PROP);
int tryStart = iCodeTop;
int tryEnd = -1;
int catchStart = -1;
int finallyStart = -1;
while (child != null) {
boolean generated = false;
if (child == catchTarget) {
if (child.getType() != Token.TARGET)
Context.codeBug();
if (tryEnd >= 0) Context.codeBug();
tryEnd = iCodeTop;
catchStart = iCodeTop;
markTargetLabel(child, iCodeTop);
generated = true;
// Catch code has exception object on the stack
itsStackDepth = 1;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
} else if (child == finallyTarget) {
if (child.getType() != Token.TARGET)
Context.codeBug();
if (tryEnd < 0) {
tryEnd = iCodeTop;
}
finallyStart = iCodeTop;
markTargetLabel(child, iCodeTop);
generated = true;
// Adjust stack for finally code: on the top of the
// stack it has either a PC value when called from
// GOSUB or exception object to rethrow when called
// from exception handler
itsStackDepth = 1;
if (itsStackDepth > itsData.itsMaxStack) {
itsData.itsMaxStack = itsStackDepth;
}
}
if (!generated) {
iCodeTop = generateICode(child, iCodeTop);
}
child = child.getNext();
}
itsStackDepth = 0;
// [tryStart, tryEnd) contains GOSUB to call finally when it
// presents at the end of try code and before return, break
// continue that transfer control outside try.
// After finally is executed the control will be
// transfered back into [tryStart, tryEnd) and exception
// handling assumes that the only code executed after
// finally returns will be a jump outside try which could not
// trigger exceptions.
// It does not hold if instruction observer throws during
// goto. Currently it may lead to double execution of finally.
addExceptionHandler(tryStart, tryEnd, catchStart, finallyStart,
itsWithDepth);
break;
}
case Token.THROW :
iCodeTop = updateLineNumber(node, iCodeTop);
iCodeTop = generateICode(child, iCodeTop);
iCodeTop = addToken(Token.THROW, iCodeTop);
iCodeTop = addShort(itsLineNumber, iCodeTop);
itsStackDepth--;
break;
case Token.RETURN :
iCodeTop = updateLineNumber(node, iCodeTop);
if (child != null) {
iCodeTop = generateICode(child, iCodeTop);
iCodeTop = addToken(Token.RETURN, iCodeTop);
itsStackDepth--;
} else {
iCodeTop = addIcode(Icode_RETUNDEF, iCodeTop);
}
break;
case Token.GETVAR : {
String name = node.getString();
if (itsData.itsNeedsActivation) {
// SETVAR handled this by turning into a SETPROP, but
// we can't do that to a GETVAR without manufacturing
// bogus children. Instead we use a special op to
// push the current scope.
iCodeTop = addIcode(Icode_SCOPE, iCodeTop);
iCodeTop = addToken(Token.STRING, iCodeTop);
iCodeTop = addString(name, iCodeTop);
itsStackDepth += 2;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
iCodeTop = addToken(Token.GETPROP, iCodeTop);
itsStackDepth--;
} else {
int index = scriptOrFn.getParamOrVarIndex(name);
iCodeTop = addToken(Token.GETVAR, iCodeTop);
iCodeTop = addByte(index, iCodeTop);
itsStackDepth++;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
}
break;
}
case Token.SETVAR : {
if (itsData.itsNeedsActivation) {
child.setType(Token.BINDNAME);
node.setType(Token.SETNAME);
iCodeTop = generateICode(node, iCodeTop);
} else {
String name = child.getString();
child = child.getNext();
iCodeTop = generateICode(child, iCodeTop);
int index = scriptOrFn.getParamOrVarIndex(name);
iCodeTop = addToken(Token.SETVAR, iCodeTop);
iCodeTop = addByte(index, iCodeTop);
}
break;
}
case Token.NULL:
case Token.THIS:
case Token.THISFN:
case Token.FALSE:
case Token.TRUE:
case Token.UNDEFINED:
iCodeTop = addToken(type, iCodeTop);
itsStackDepth++;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
break;
case Token.ENUMINIT :
iCodeTop = generateICode(child, iCodeTop);
iCodeTop = addToken(Token.ENUMINIT, iCodeTop);
iCodeTop = addLocalRef(node, iCodeTop);
itsStackDepth--;
break;
case Token.ENUMNEXT : {
iCodeTop = addToken(Token.ENUMNEXT, iCodeTop);
Node init = (Node)node.getProp(Node.ENUM_PROP);
iCodeTop = addLocalRef(init, iCodeTop);
itsStackDepth++;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
break;
}
case Token.ENUMDONE :
// could release the local here??
break;
case Token.REGEXP : {
int index = node.getExistingIntProp(Node.REGEXP_PROP);
iCodeTop = addToken(Token.REGEXP, iCodeTop);
iCodeTop = addIndex(index, iCodeTop);
itsStackDepth++;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
break;
}
default :
badTree(node);
break;
}
return iCodeTop;
}
private int addLocalRef(Node node, int iCodeTop)
{
int theLocalSlot = node.getIntProp(Node.LOCAL_PROP, -1);
if (theLocalSlot == -1) {
theLocalSlot = itsData.itsMaxLocals++;
node.putIntProp(Node.LOCAL_PROP, theLocalSlot);
}
iCodeTop = addByte(theLocalSlot, iCodeTop);
if (theLocalSlot >= itsData.itsMaxLocals)
itsData.itsMaxLocals = theLocalSlot + 1;
return iCodeTop;
}
private int getTargetLabel(Node target) {
int targetLabel = target.getIntProp(Node.LABEL_PROP, -1);
if (targetLabel == -1) {
targetLabel = itsLabels.acquireLabel();
target.putIntProp(Node.LABEL_PROP, targetLabel);
}
return targetLabel;
}
private void markTargetLabel(Node target, int iCodeTop)
{
int label = getTargetLabel(target);
itsLabels.markLabel(label, iCodeTop);
}
private int addGoto(Node target, int gotoOp, int iCodeTop)
{
int targetLabel = getTargetLabel(target);
int gotoPC = iCodeTop;
if (gotoOp > BASE_ICODE) {
iCodeTop = addIcode(gotoOp, iCodeTop);
} else {
iCodeTop = addToken(gotoOp, iCodeTop);
}
iCodeTop = addShort(0, iCodeTop);
int targetPC = itsLabels.getLabelPC(targetLabel);
if (targetPC != -1) {
recordJumpOffset(gotoPC + 1, targetPC - gotoPC);
} else {
itsLabels.addLabelFixup(targetLabel, gotoPC + 1);
}
return iCodeTop;
}
private int addForwardGoto(int gotoOp, int iCodeTop)
{
iCodeTop = addToken(gotoOp, iCodeTop);
iCodeTop = addShort(0, iCodeTop);
return iCodeTop;
}
private void resolveForwardGoto(int jumpStart, int iCodeTop)
{
if (jumpStart + 3 > iCodeTop) Context.codeBug();
int offset = iCodeTop - jumpStart;
// +1 to write after jump icode
recordJumpOffset(jumpStart + 1, offset);
}
private void recordJumpOffset(int pos, int offset)
{
if (offset != (short)offset) {
throw Context.reportRuntimeError0("msg.too.big.jump");
}
itsData.itsICode[pos] = (byte)(offset >> 8);
itsData.itsICode[pos + 1] = (byte)offset;
}
private int addByte(int b, int iCodeTop)
{
byte[] array = itsData.itsICode;
if (iCodeTop == array.length) {
array = increaseICodeCapasity(iCodeTop, 1);
}
array[iCodeTop++] = (byte)b;
return iCodeTop;
}
private int addToken(int token, int iCodeTop)
{
if (!(Token.FIRST_BYTECODE_TOKEN <= token
&& token <= Token.LAST_BYTECODE_TOKEN))
{
Context.codeBug();
}
return addByte(token, iCodeTop);
}
private int addIcode(int icode, int iCodeTop)
{
if (!(BASE_ICODE < icode && icode <= Icode_END)) Context.codeBug();
return addByte(icode, iCodeTop);
}
private int addShort(int s, int iCodeTop)
{
byte[] array = itsData.itsICode;
if (iCodeTop + 2 > array.length) {
array = increaseICodeCapasity(iCodeTop, 2);
}
array[iCodeTop] = (byte)(s >>> 8);
array[iCodeTop + 1] = (byte)s;
return iCodeTop + 2;
}
private int addIndex(int index, int iCodeTop)
{
if (index < 0) Context.codeBug();
if (index > 0xFFFF) {
throw Context.reportRuntimeError0("msg.too.big.index");
}
byte[] array = itsData.itsICode;
if (iCodeTop + 2 > array.length) {
array = increaseICodeCapasity(iCodeTop, 2);
}
array[iCodeTop] = (byte)(index >>> 8);
array[iCodeTop + 1] = (byte)index;
return iCodeTop + 2;
}
private int addInt(int i, int iCodeTop)
{
byte[] array = itsData.itsICode;
if (iCodeTop + 4 > array.length) {
array = increaseICodeCapasity(iCodeTop, 4);
}
array[iCodeTop] = (byte)(i >>> 24);
array[iCodeTop + 1] = (byte)(i >>> 16);
array[iCodeTop + 2] = (byte)(i >>> 8);
array[iCodeTop + 3] = (byte)i;
return iCodeTop + 4;
}
private int addDouble(double num, int iCodeTop)
{
int index = itsDoubleTableTop;
if (index == 0) {
itsData.itsDoubleTable = new double[64];
} else if (itsData.itsDoubleTable.length == index) {
double[] na = new double[index * 2];
System.arraycopy(itsData.itsDoubleTable, 0, na, 0, index);
itsData.itsDoubleTable = na;
}
itsData.itsDoubleTable[index] = num;
itsDoubleTableTop = index + 1;
iCodeTop = addIndex(index, iCodeTop);
return iCodeTop;
}
private int addString(String str, int iCodeTop)
{
int index = itsStrings.get(str, -1);
if (index == -1) {
index = itsStrings.size();
itsStrings.put(str, index);
}
iCodeTop = addIndex(index, iCodeTop);
lastAddString = str;
return iCodeTop;
}
private void addExceptionHandler(int icodeStart, int icodeEnd,
int catchStart, int finallyStart,
int withDepth)
{
int top = itsExceptionTableTop;
int[] table = itsData.itsExceptionTable;
if (table == null) {
if (top != 0) Context.codeBug();
table = new int[EXCEPTION_SLOT_SIZE * 2];
itsData.itsExceptionTable = table;
} else if (table.length == top) {
table = new int[table.length * 2];
System.arraycopy(itsData.itsExceptionTable, 0, table, 0, top);
itsData.itsExceptionTable = table;
}
table[top + EXCEPTION_TRY_START_SLOT] = icodeStart;
table[top + EXCEPTION_TRY_END_SLOT] = icodeEnd;
table[top + EXCEPTION_CATCH_SLOT] = catchStart;
table[top + EXCEPTION_FINALLY_SLOT] = finallyStart;
table[top + EXCEPTION_WITH_DEPTH_SLOT] = withDepth;
itsExceptionTableTop = top + EXCEPTION_SLOT_SIZE;
}
private byte[] increaseICodeCapasity(int iCodeTop, int extraSize) {
int capacity = itsData.itsICode.length;
if (iCodeTop + extraSize <= capacity) Context.codeBug();
capacity *= 2;
if (iCodeTop + extraSize > capacity) {
capacity = iCodeTop + extraSize;
}
byte[] array = new byte[capacity];
System.arraycopy(itsData.itsICode, 0, array, 0, iCodeTop);
itsData.itsICode = array;
return array;
}
private static int getShort(byte[] iCode, int pc) {
return (iCode[pc] << 8) | (iCode[pc + 1] & 0xFF);
}
private static int getIndex(byte[] iCode, int pc) {
return ((iCode[pc] & 0xFF) << 8) | (iCode[pc + 1] & 0xFF);
}
private static int getInt(byte[] iCode, int pc) {
return (iCode[pc] << 24) | ((iCode[pc + 1] & 0xFF) << 16)
| ((iCode[pc + 2] & 0xFF) << 8) | (iCode[pc + 3] & 0xFF);
}
private static int getTarget(byte[] iCode, int pc) {
int displacement = getShort(iCode, pc);
return pc - 1 + displacement;
}
private static int getExceptionHandler(int[] exceptionTable, int pc)
{
// OPT: use binary search
if (exceptionTable == null) { return -1; }
int best = -1, bestStart = 0, bestEnd = 0;
for (int i = 0; i != exceptionTable.length; i += EXCEPTION_SLOT_SIZE) {
int start = exceptionTable[i + EXCEPTION_TRY_START_SLOT];
int end = exceptionTable[i + EXCEPTION_TRY_END_SLOT];
if (start <= pc && pc < end) {
if (best < 0 || bestStart <= start) {
// Check handlers are nested
if (best >= 0 && bestEnd < end) Context.codeBug();
best = i;
bestStart = start;
bestEnd = end;
}
}
}
return best;
}
private static String icodeToName(int icode)
{
if (Token.printICode) {
if (icode <= Token.LAST_BYTECODE_TOKEN) {
return Token.name(icode);
} else {
switch (icode) {
case Icode_DUP: return "dup";
case Icode_NAMEINC: return "nameinc";
case Icode_PROPINC: return "propinc";
case Icode_ELEMINC: return "eleminc";
case Icode_VARINC: return "varinc";
case Icode_NAMEDEC: return "namedec";
case Icode_PROPDEC: return "propdec";
case Icode_ELEMDEC: return "elemdec";
case Icode_VARDEC: return "vardec";
case Icode_SCOPE: return "scope";
case Icode_TYPEOFNAME: return "typeofname";
case Icode_GETPROTO: return "getproto";
case Icode_GETPARENT: return "getparent";
case Icode_GETSCOPEPARENT: return "getscopeparent";
case Icode_SETPROTO: return "setproto";
case Icode_SETPARENT: return "setparent";
case Icode_CLOSURE: return "closure";
case Icode_CALLSPECIAL: return "callspecial";
case Icode_RETUNDEF: return "retundef";
case Icode_CATCH: return "catch";
case Icode_GOSUB: return "gosub";
case Icode_RETSUB: return "retsub";
case Icode_LINE: return "line";
case Icode_SHORTNUMBER: return "shortnumber";
case Icode_INTNUMBER: return "intnumber";
case Icode_END: return "end";
}
}
return "<UNKNOWN ICODE: "+icode+">";
}
return "";
}
private static void dumpICode(InterpreterData idata)
{
if (Token.printICode) {
int iCodeLength = idata.itsICodeTop;
byte iCode[] = idata.itsICode;
String[] strings = idata.itsStringTable;
PrintStream out = System.out;
out.println("ICode dump, for " + idata.itsName
+ ", length = " + iCodeLength);
out.println("MaxStack = " + idata.itsMaxStack);
for (int pc = 0; pc < iCodeLength; ) {
out.flush();
out.print(" [" + pc + "] ");
int token = iCode[pc] & 0xff;
String tname = icodeToName(token);
int old_pc = pc;
++pc;
int icodeLength = icodeTokenLength(token);
switch (token) {
default:
if (icodeLength != 1) Context.codeBug();
out.println(tname);
break;
case Icode_GOSUB :
case Token.GOTO :
case Token.IFEQ :
case Token.IFNE : {
int newPC = getTarget(iCode, pc);
out.println(tname + " " + newPC);
pc += 2;
break;
}
case Icode_RETSUB :
case Token.ENUMINIT :
case Token.ENUMNEXT :
case Icode_VARINC :
case Icode_VARDEC :
case Token.GETVAR :
case Token.SETVAR :
case Token.NEWTEMP :
case Token.USETEMP : {
int slot = (iCode[pc] & 0xFF);
out.println(tname + " " + slot);
pc++;
break;
}
case Icode_CALLSPECIAL : {
int callType = iCode[pc] & 0xFF;
boolean isNew = (iCode[pc + 1] != 0);
int line = getShort(iCode, pc+2);
int count = getIndex(iCode, pc + 4);
out.println(tname+" "+callType+" "+isNew
+" "+count+" "+line);
pc += 8;
break;
}
case Token.REGEXP : {
int i = getIndex(iCode, pc);
Object regexp = idata.itsRegExpLiterals[i];
out.println(tname + " " + regexp);
pc += 2;
break;
}
case Icode_CLOSURE : {
int i = getIndex(iCode, pc);
InterpreterData data2 = idata.itsNestedFunctions[i];
out.println(tname + " " + data2);
pc += 2;
break;
}
case Token.NEW :
case Token.CALL : {
int count = getIndex(iCode, pc + 2);
String name = strings[getIndex(iCode, pc)];
out.println(tname+' '+count+" \""+name+'"');
pc += 4;
break;
}
case Icode_SHORTNUMBER : {
int value = getShort(iCode, pc);
out.println(tname + " " + value);
pc += 2;
break;
}
case Icode_INTNUMBER : {
int value = getInt(iCode, pc);
out.println(tname + " " + value);
pc += 4;
break;
}
case Token.NUMBER : {
int index = getIndex(iCode, pc);
double value = idata.itsDoubleTable[index];
out.println(tname + " " + value);
pc += 2;
break;
}
case Icode_TYPEOFNAME :
case Token.GETBASE :
case Token.BINDNAME :
case Token.SETNAME :
case Token.NAME :
case Icode_NAMEINC :
case Icode_NAMEDEC :
case Token.STRING : {
String str = strings[getIndex(iCode, pc)];
out.println(tname + " \"" + str + '"');
pc += 2;
break;
}
case Icode_LINE : {
int line = getShort(iCode, pc);
out.println(tname + " : " + line);
pc += 2;
break;
}
}
if (old_pc + icodeLength != pc) Context.codeBug();
}
int[] table = idata.itsExceptionTable;
if (table != null) {
out.println("Exception handlers: "
+table.length / EXCEPTION_SLOT_SIZE);
for (int i = 0; i != table.length;
i += EXCEPTION_SLOT_SIZE)
{
int tryStart = table[i + EXCEPTION_TRY_START_SLOT];
int tryEnd = table[i + EXCEPTION_TRY_END_SLOT];
int catchStart = table[i + EXCEPTION_CATCH_SLOT];
int finallyStart = table[i + EXCEPTION_FINALLY_SLOT];
int withDepth = table[i + EXCEPTION_WITH_DEPTH_SLOT];
out.println(" "+tryStart+"\t "+tryEnd+"\t "
+catchStart+"\t "+finallyStart
+"\t "+withDepth);
}
}
out.flush();
}
}
private static int icodeTokenLength(int icodeToken) {
switch (icodeToken) {
case Icode_SCOPE :
case Icode_GETPROTO :
case Icode_GETPARENT :
case Icode_GETSCOPEPARENT :
case Icode_SETPROTO :
case Icode_SETPARENT :
case Token.DELPROP :
case Token.TYPEOF :
case Token.NEWSCOPE :
case Token.ENTERWITH :
case Token.LEAVEWITH :
case Token.RETURN :
case Token.GETTHIS :
case Token.SETELEM :
case Token.GETELEM :
case Token.SETPROP :
case Token.GETPROP :
case Icode_PROPINC :
case Icode_PROPDEC :
case Icode_ELEMINC :
case Icode_ELEMDEC :
case Token.BITNOT :
case Token.BITAND :
case Token.BITOR :
case Token.BITXOR :
case Token.LSH :
case Token.RSH :
case Token.URSH :
case Token.NOT :
case Token.POS :
case Token.NEG :
case Token.SUB :
case Token.MUL :
case Token.DIV :
case Token.MOD :
case Token.ADD :
case Token.POPV :
case Token.POP :
case Icode_DUP :
case Token.LT :
case Token.GT :
case Token.LE :
case Token.GE :
case Token.IN :
case Token.INSTANCEOF :
case Token.EQ :
case Token.NE :
case Token.SHEQ :
case Token.SHNE :
case Token.ZERO :
case Token.ONE :
case Token.NULL :
case Token.THIS :
case Token.THISFN :
case Token.FALSE :
case Token.TRUE :
case Token.UNDEFINED :
case Icode_CATCH:
case Icode_RETUNDEF:
case Icode_END:
return 1;
case Token.THROW :
// source line
return 1 + 2;
case Icode_GOSUB :
case Token.GOTO :
case Token.IFEQ :
case Token.IFNE :
// target pc offset
return 1 + 2;
case Icode_RETSUB :
case Token.ENUMINIT :
case Token.ENUMNEXT :
case Icode_VARINC :
case Icode_VARDEC :
case Token.GETVAR :
case Token.SETVAR :
case Token.NEWTEMP :
case Token.USETEMP :
// slot index
return 1 + 1;
case Icode_CALLSPECIAL :
// call type
// is new
// line number
// arg count
return 1 + 1 + 1 + 2 + 2;
case Token.REGEXP :
// regexp index
return 1 + 2;
case Icode_CLOSURE :
// index of closure master copy
return 1 + 2;
case Token.NEW :
case Token.CALL :
// name string index
// arg count
return 1 + 2 + 2;
case Icode_SHORTNUMBER :
// short number
return 1 + 2;
case Icode_INTNUMBER :
// int number
return 1 + 4;
case Token.NUMBER :
// index of double number
return 1 + 2;
case Icode_TYPEOFNAME :
case Token.GETBASE :
case Token.BINDNAME :
case Token.SETNAME :
case Token.NAME :
case Icode_NAMEINC :
case Icode_NAMEDEC :
case Token.STRING :
// string index
return 1 + 2;
case Icode_LINE :
// line number
return 1 + 2;
default:
Context.codeBug(); // Bad icodeToken
return 0;
}
}
static int[] getLineNumbers(InterpreterData data) {
UintMap presentLines = new UintMap();
int iCodeLength = data.itsICodeTop;
byte[] iCode = data.itsICode;
for (int pc = 0; pc != iCodeLength;) {
int icodeToken = iCode[pc] & 0xff;
int icodeLength = icodeTokenLength(icodeToken);
if (icodeToken == Icode_LINE) {
if (icodeLength != 3) Context.codeBug();
int line = getShort(iCode, pc + 1);
presentLines.put(line, 0);
}
pc += icodeLength;
}
return presentLines.getKeys();
}
static Object getEncodedSource(InterpreterData idata)
{
if (idata.encodedSource == null) {
return null;
}
return idata.encodedSource.substring(idata.encodedSourceStart,
idata.encodedSourceEnd);
}
private static InterpretedFunction createFunction(Context cx,
Scriptable scope,
InterpreterData idata,
boolean fromEvalCode)
{
InterpretedFunction fn = new InterpretedFunction(idata);
if (cx.hasCompileFunctionsWithDynamicScope()) {
// Nested functions are not affected by the dynamic scope flag
// as dynamic scope is already a parent of their scope
// Functions defined under the with statement also immune to
// this setup, in which case dynamic scope is ignored in favor
// of with object.
if (!(scope instanceof NativeCall
|| scope instanceof NativeWith))
{
fn.itsUseDynamicScope = true;
}
}
ScriptRuntime.initFunction(cx, scope, fn, idata.itsFunctionType,
fromEvalCode);
return fn;
}
static Object interpret(Context cx, Scriptable scope, Scriptable thisObj,
Object[] args, double[] argsDbl,
int argShift, int argCount,
NativeFunction fnOrScript,
InterpreterData idata)
throws JavaScriptException
{
if (cx.interpreterSecurityDomain != idata.securityDomain) {
return execWithNewDomain(cx, scope, thisObj,
args, argsDbl, argShift, argCount,
fnOrScript, idata);
}
final Object DBL_MRK = Interpreter.DBL_MRK;
final Scriptable undefined = Undefined.instance;
final int VAR_SHFT = 0;
final int maxVars = idata.itsMaxVars;
final int LOCAL_SHFT = VAR_SHFT + maxVars;
final int STACK_SHFT = LOCAL_SHFT + idata.itsMaxLocals;
// stack[VAR_SHFT <= i < LOCAL_SHFT]: variables
// stack[LOCAL_SHFT <= i < TRY_STACK_SHFT]: used for newtemp/usetemp
// stack[STACK_SHFT <= i < STACK_SHFT + idata.itsMaxStack]: stack data
// sDbl[i]: if stack[i] is DBL_MRK, sDbl[i] holds the number value
int maxFrameArray = idata.itsMaxFrameArray;
if (maxFrameArray != STACK_SHFT + idata.itsMaxStack)
Context.codeBug();
Object[] stack = new Object[maxFrameArray];
double[] sDbl = new double[maxFrameArray];
int stackTop = STACK_SHFT - 1;
int withDepth = 0;
int definedArgs = fnOrScript.argCount;
if (definedArgs > argCount) { definedArgs = argCount; }
for (int i = 0; i != definedArgs; ++i) {
Object arg = args[argShift + i];
stack[VAR_SHFT + i] = arg;
if (arg == DBL_MRK) {
sDbl[VAR_SHFT + i] = argsDbl[argShift + i];
}
}
for (int i = definedArgs; i != maxVars; ++i) {
stack[VAR_SHFT + i] = undefined;
}
DebugFrame debuggerFrame = null;
if (cx.debugger != null) {
debuggerFrame = cx.debugger.getFrame(cx, idata);
}
if (idata.itsFunctionType != 0) {
InterpretedFunction f = (InterpretedFunction)fnOrScript;
if (!f.itsUseDynamicScope) {
scope = fnOrScript.getParentScope();
}
if (idata.itsCheckThis) {
thisObj = ScriptRuntime.getThis(thisObj);
}
if (idata.itsNeedsActivation) {
if (argsDbl != null) {
args = getArgsArray(args, argsDbl, argShift, argCount);
argShift = 0;
argsDbl = null;
}
scope = ScriptRuntime.initVarObj(cx, scope, fnOrScript,
thisObj, args);
}
} else {
scope = ScriptRuntime.initScript(cx, scope, fnOrScript, thisObj,
idata.itsFromEvalCode);
}
if (idata.itsNestedFunctions != null) {
if (idata.itsFunctionType != 0 && !idata.itsNeedsActivation)
Context.codeBug();
for (int i = 0; i < idata.itsNestedFunctions.length; i++) {
InterpreterData fdata = idata.itsNestedFunctions[i];
if (fdata.itsFunctionType == FunctionNode.FUNCTION_STATEMENT) {
createFunction(cx, scope, fdata, idata.itsFromEvalCode);
}
}
}
boolean useActivationVars = false;
if (debuggerFrame != null) {
if (argsDbl != null) {
args = getArgsArray(args, argsDbl, argShift, argCount);
argShift = 0;
argsDbl = null;
}
if (idata.itsFunctionType != 0 && !idata.itsNeedsActivation) {
useActivationVars = true;
scope = ScriptRuntime.initVarObj(cx, scope, fnOrScript,
thisObj, args);
}
debuggerFrame.onEnter(cx, scope, thisObj, args);
}
String savedSourceFile = cx.interpreterSourceFile;
cx.interpreterSourceFile = idata.itsSourceFile;
Object result = undefined;
// If javaException != null on exit, it will be throw instead of
// normal return
Throwable javaException = null;
int exceptionPC = -1;
byte[] iCode = idata.itsICode;
String[] strings = idata.itsStringTable;
int pc = 0;
int pcPrevBranch = pc;
final int instructionThreshold = cx.instructionThreshold;
// During function call this will be set to -1 so catch can properly
// adjust it
int instructionCount = cx.instructionCount;
// arbitrary number to add to instructionCount when calling
// other functions
final int INVOCATION_COST = 100;
Loop: for (;;) {
try {
switch (iCode[pc] & 0xff) {
// Back indent to ease imlementation reading
case Icode_CATCH: {
// The following code should be executed inside try/catch inside main
// loop, not in the loop catch block itself to deal withnexceptions
// from observeInstructionCount. A special bytecode is used only to
// simplify logic.
if (javaException == null) Context.codeBug();
int pcNew = -1;
boolean doCatch = false;
int handlerOffset = getExceptionHandler(idata.itsExceptionTable,
exceptionPC);
if (handlerOffset >= 0) {
final int SCRIPT_CAN_CATCH = 0, ONLY_FINALLY = 1, OTHER = 2;
int exType;
if (javaException instanceof JavaScriptException) {
exType = SCRIPT_CAN_CATCH;
} else if (javaException instanceof EcmaError) {
// an offical ECMA error object,
exType = SCRIPT_CAN_CATCH;
} else if (javaException instanceof WrappedException) {
exType = SCRIPT_CAN_CATCH;
} else if (javaException instanceof RuntimeException) {
exType = ONLY_FINALLY;
} else {
// Error instance
exType = OTHER;
}
if (exType != OTHER) {
// Do not allow for JS to interfere with Error instances
// (exType == OTHER), as they can be used to terminate
// long running script
if (exType == SCRIPT_CAN_CATCH) {
// Allow JS to catch only JavaScriptException and
// EcmaError
pcNew = idata.itsExceptionTable[handlerOffset
+ EXCEPTION_CATCH_SLOT];
if (pcNew >= 0) {
// Has catch block
doCatch = true;
}
}
if (pcNew < 0) {
pcNew = idata.itsExceptionTable[handlerOffset
+ EXCEPTION_FINALLY_SLOT];
}
}
}
if (debuggerFrame != null && !(javaException instanceof Error)) {
debuggerFrame.onExceptionThrown(cx, javaException);
}
if (pcNew < 0) {
break Loop;
}
// We caught an exception
// restore scope at try point
int tryWithDepth = idata.itsExceptionTable[
handlerOffset + EXCEPTION_WITH_DEPTH_SLOT];
while (tryWithDepth != withDepth) {
if (scope == null) Context.codeBug();
scope = ScriptRuntime.leaveWith(scope);
--withDepth;
}
// make stack to contain single exception object
stackTop = STACK_SHFT;
if (doCatch) {
stack[stackTop] = ScriptRuntime.getCatchObject(cx, scope,
javaException);
} else {
// Call finally handler with javaException on stack top to
// distinguish from normal invocation through GOSUB
// which would contain DBL_MRK on the stack
stack[stackTop] = javaException;
}
// clear exception
javaException = null;
// Notify instruction observer if necessary
// and point pc and pcPrevBranch to start of catch/finally block
if (instructionThreshold != 0) {
if (instructionCount > instructionThreshold) {
// Note: this can throw Error
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
}
pcPrevBranch = pc = pcNew;
continue Loop;
}
case Token.THROW: {
Object value = stack[stackTop];
if (value == DBL_MRK) value = doubleWrap(sDbl[stackTop]);
--stackTop;
int sourceLine = getShort(iCode, pc + 1);
javaException = new JavaScriptException(value, idata.itsSourceFile,
sourceLine);
exceptionPC = pc;
if (instructionThreshold != 0) {
instructionCount += pc + 1 - pcPrevBranch;
if (instructionCount > instructionThreshold) {
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
}
pcPrevBranch = pc = getJavaCatchPC(iCode);
continue Loop;
}
case Token.GE : {
--stackTop;
Object rhs = stack[stackTop + 1];
Object lhs = stack[stackTop];
boolean valBln;
if (rhs == DBL_MRK || lhs == DBL_MRK) {
double rDbl = stack_double(stack, sDbl, stackTop + 1);
double lDbl = stack_double(stack, sDbl, stackTop);
valBln = (rDbl == rDbl && lDbl == lDbl && rDbl <= lDbl);
} else {
valBln = (1 == ScriptRuntime.cmp_LE(rhs, lhs));
}
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case Token.LE : {
--stackTop;
Object rhs = stack[stackTop + 1];
Object lhs = stack[stackTop];
boolean valBln;
if (rhs == DBL_MRK || lhs == DBL_MRK) {
double rDbl = stack_double(stack, sDbl, stackTop + 1);
double lDbl = stack_double(stack, sDbl, stackTop);
valBln = (rDbl == rDbl && lDbl == lDbl && lDbl <= rDbl);
} else {
valBln = (1 == ScriptRuntime.cmp_LE(lhs, rhs));
}
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case Token.GT : {
--stackTop;
Object rhs = stack[stackTop + 1];
Object lhs = stack[stackTop];
boolean valBln;
if (rhs == DBL_MRK || lhs == DBL_MRK) {
double rDbl = stack_double(stack, sDbl, stackTop + 1);
double lDbl = stack_double(stack, sDbl, stackTop);
valBln = (rDbl == rDbl && lDbl == lDbl && rDbl < lDbl);
} else {
valBln = (1 == ScriptRuntime.cmp_LT(rhs, lhs));
}
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case Token.LT : {
--stackTop;
Object rhs = stack[stackTop + 1];
Object lhs = stack[stackTop];
boolean valBln;
if (rhs == DBL_MRK || lhs == DBL_MRK) {
double rDbl = stack_double(stack, sDbl, stackTop + 1);
double lDbl = stack_double(stack, sDbl, stackTop);
valBln = (rDbl == rDbl && lDbl == lDbl && lDbl < rDbl);
} else {
valBln = (1 == ScriptRuntime.cmp_LT(lhs, rhs));
}
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case Token.IN : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
boolean valBln = ScriptRuntime.in(lhs, rhs, scope);
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case Token.INSTANCEOF : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
boolean valBln = ScriptRuntime.instanceOf(lhs, rhs, scope);
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case Token.EQ : {
--stackTop;
boolean valBln = do_eq(stack, sDbl, stackTop);
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case Token.NE : {
--stackTop;
boolean valBln = !do_eq(stack, sDbl, stackTop);
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case Token.SHEQ : {
--stackTop;
boolean valBln = do_sheq(stack, sDbl, stackTop);
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case Token.SHNE : {
--stackTop;
boolean valBln = !do_sheq(stack, sDbl, stackTop);
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case Token.IFNE : {
boolean valBln = stack_boolean(stack, sDbl, stackTop);
--stackTop;
if (!valBln) {
if (instructionThreshold != 0) {
instructionCount += pc + 3 - pcPrevBranch;
if (instructionCount > instructionThreshold) {
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
}
pcPrevBranch = pc = getTarget(iCode, pc + 1);
continue Loop;
}
pc += 2;
break;
}
case Token.IFEQ : {
boolean valBln = stack_boolean(stack, sDbl, stackTop);
--stackTop;
if (valBln) {
if (instructionThreshold != 0) {
instructionCount += pc + 3 - pcPrevBranch;
if (instructionCount > instructionThreshold) {
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
}
pcPrevBranch = pc = getTarget(iCode, pc + 1);
continue Loop;
}
pc += 2;
break;
}
case Token.GOTO :
if (instructionThreshold != 0) {
instructionCount += pc + 3 - pcPrevBranch;
if (instructionCount > instructionThreshold) {
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
}
pcPrevBranch = pc = getTarget(iCode, pc + 1);
continue Loop;
case Icode_GOSUB :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = pc + 3;
if (instructionThreshold != 0) {
instructionCount += pc + 3 - pcPrevBranch;
if (instructionCount > instructionThreshold) {
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
}
pcPrevBranch = pc = getTarget(iCode, pc + 1); continue Loop;
case Icode_RETSUB : {
int slot = (iCode[pc + 1] & 0xFF);
if (instructionThreshold != 0) {
instructionCount += pc + 2 - pcPrevBranch;
if (instructionCount > instructionThreshold) {
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
}
int newPC;
Object value = stack[LOCAL_SHFT + slot];
if (value != DBL_MRK) {
// Invocation from exception handler, restore object to rethrow
javaException = (Throwable)value;
exceptionPC = pc;
newPC = getJavaCatchPC(iCode);
} else {
// Normal return from GOSUB
newPC = (int)sDbl[LOCAL_SHFT + slot];
}
pcPrevBranch = pc = newPC;
continue Loop;
}
case Token.POP :
stack[stackTop] = null;
stackTop--;
break;
case Icode_DUP :
stack[stackTop + 1] = stack[stackTop];
sDbl[stackTop + 1] = sDbl[stackTop];
stackTop++;
break;
case Token.POPV :
result = stack[stackTop];
if (result == DBL_MRK) result = doubleWrap(sDbl[stackTop]);
stack[stackTop] = null;
--stackTop;
break;
case Token.RETURN :
result = stack[stackTop];
if (result == DBL_MRK) result = doubleWrap(sDbl[stackTop]);
--stackTop;
break Loop;
case Icode_RETUNDEF :
result = undefined;
break Loop;
case Icode_END:
break Loop;
case Token.BITNOT : {
int rIntValue = stack_int32(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = ~rIntValue;
break;
}
case Token.BITAND : {
int rIntValue = stack_int32(stack, sDbl, stackTop);
--stackTop;
int lIntValue = stack_int32(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lIntValue & rIntValue;
break;
}
case Token.BITOR : {
int rIntValue = stack_int32(stack, sDbl, stackTop);
--stackTop;
int lIntValue = stack_int32(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lIntValue | rIntValue;
break;
}
case Token.BITXOR : {
int rIntValue = stack_int32(stack, sDbl, stackTop);
--stackTop;
int lIntValue = stack_int32(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lIntValue ^ rIntValue;
break;
}
case Token.LSH : {
int rIntValue = stack_int32(stack, sDbl, stackTop);
--stackTop;
int lIntValue = stack_int32(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lIntValue << rIntValue;
break;
}
case Token.RSH : {
int rIntValue = stack_int32(stack, sDbl, stackTop);
--stackTop;
int lIntValue = stack_int32(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lIntValue >> rIntValue;
break;
}
case Token.URSH : {
int rIntValue = stack_int32(stack, sDbl, stackTop) & 0x1F;
--stackTop;
double lDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = ScriptRuntime.toUint32(lDbl) >>> rIntValue;
break;
}
case Token.ADD :
--stackTop;
do_add(stack, sDbl, stackTop);
break;
case Token.SUB : {
double rDbl = stack_double(stack, sDbl, stackTop);
--stackTop;
double lDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lDbl - rDbl;
break;
}
case Token.NEG : {
double rDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = -rDbl;
break;
}
case Token.POS : {
double rDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = rDbl;
break;
}
case Token.MUL : {
double rDbl = stack_double(stack, sDbl, stackTop);
--stackTop;
double lDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lDbl * rDbl;
break;
}
case Token.DIV : {
double rDbl = stack_double(stack, sDbl, stackTop);
--stackTop;
double lDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
// Detect the divide by zero or let Java do it ?
sDbl[stackTop] = lDbl / rDbl;
break;
}
case Token.MOD : {
double rDbl = stack_double(stack, sDbl, stackTop);
--stackTop;
double lDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lDbl % rDbl;
break;
}
case Token.NOT : {
stack[stackTop] = stack_boolean(stack, sDbl, stackTop)
? Boolean.FALSE : Boolean.TRUE;
break;
}
case Token.BINDNAME : {
String name = strings[getIndex(iCode, pc + 1)];
stack[++stackTop] = ScriptRuntime.bind(scope, name);
pc += 2;
break;
}
case Token.GETBASE : {
String name = strings[getIndex(iCode, pc + 1)];
stack[++stackTop] = ScriptRuntime.getBase(scope, name);
pc += 2;
break;
}
case Token.SETNAME : {
String name = strings[getIndex(iCode, pc + 1)];
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
// what about class cast exception here for lhs?
Scriptable lhs = (Scriptable)stack[stackTop];
stack[stackTop] = ScriptRuntime.setName(lhs, rhs, scope, name);
pc += 2;
break;
}
case Token.DELPROP : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.delete(cx, scope, lhs, rhs);
break;
}
case Token.GETPROP : {
String name = (String)stack[stackTop];
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.getProp(lhs, name, scope);
break;
}
case Token.SETPROP : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
String name = (String)stack[stackTop];
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.setProp(lhs, name, rhs, scope);
break;
}
case Token.GETELEM :
do_getElem(cx, stack, sDbl, stackTop, scope);
--stackTop;
break;
case Token.SETELEM :
do_setElem(cx, stack, sDbl, stackTop, scope);
stackTop -= 2;
break;
case Icode_PROPINC : {
String name = (String)stack[stackTop];
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.postIncrement(lhs, name, scope);
break;
}
case Icode_PROPDEC : {
String name = (String)stack[stackTop];
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.postDecrement(lhs, name, scope);
break;
}
case Icode_ELEMINC : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.postIncrementElem(lhs, rhs, scope);
break;
}
case Icode_ELEMDEC : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.postDecrementElem(lhs, rhs, scope);
break;
}
case Token.GETTHIS : {
Scriptable lhs = (Scriptable)stack[stackTop];
stack[stackTop] = ScriptRuntime.getThis(lhs);
break;
}
case Token.NEWTEMP : {
int slot = (iCode[++pc] & 0xFF);
stack[LOCAL_SHFT + slot] = stack[stackTop];
sDbl[LOCAL_SHFT + slot] = sDbl[stackTop];
break;
}
case Token.USETEMP : {
int slot = (iCode[++pc] & 0xFF);
++stackTop;
stack[stackTop] = stack[LOCAL_SHFT + slot];
sDbl[stackTop] = sDbl[LOCAL_SHFT + slot];
break;
}
case Icode_CALLSPECIAL : {
if (instructionThreshold != 0) {
instructionCount += INVOCATION_COST;
cx.instructionCount = instructionCount;
instructionCount = -1;
}
int callType = iCode[pc + 1] & 0xFF;
boolean isNew = (iCode[pc + 2] != 0);
int sourceLine = getShort(iCode, pc + 3);
int count = getIndex(iCode, pc + 5);
stackTop -= count;
Object[] outArgs = getArgsArray(stack, sDbl, stackTop + 1, count);
Object functionThis;
if (isNew) {
functionThis = null;
} else {
functionThis = stack[stackTop];
if (functionThis == DBL_MRK) {
functionThis = doubleWrap(sDbl[stackTop]);
}
--stackTop;
}
Object function = stack[stackTop];
if (function == DBL_MRK) function = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.callSpecial(
cx, function, isNew, functionThis, outArgs,
scope, thisObj, callType,
idata.itsSourceFile, sourceLine);
pc += 6;
instructionCount = cx.instructionCount;
break;
}
case Token.CALL : {
if (instructionThreshold != 0) {
instructionCount += INVOCATION_COST;
cx.instructionCount = instructionCount;
instructionCount = -1;
}
- cx.instructionCount = instructionCount;
int count = getIndex(iCode, pc + 3);
stackTop -= count;
int calleeArgShft = stackTop + 1;
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
Scriptable calleeScope = scope;
if (idata.itsNeedsActivation) {
calleeScope = ScriptableObject.getTopLevelScope(scope);
}
Scriptable calleeThis;
if (rhs instanceof Scriptable || rhs == null) {
calleeThis = (Scriptable)rhs;
} else {
calleeThis = ScriptRuntime.toObject(cx, calleeScope, rhs);
}
if (lhs instanceof InterpretedFunction) {
// Inlining of InterpretedFunction.call not to create
// argument array
InterpretedFunction f = (InterpretedFunction)lhs;
stack[stackTop] = interpret(cx, calleeScope, calleeThis,
stack, sDbl, calleeArgShft, count,
f, f.itsData);
} else if (lhs instanceof Function) {
Function f = (Function)lhs;
Object[] outArgs = getArgsArray(stack, sDbl, calleeArgShft, count);
stack[stackTop] = f.call(cx, calleeScope, calleeThis, outArgs);
} else {
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
else if (lhs == undefined) {
// special code for better error message for call
// to undefined
lhs = strings[getIndex(iCode, pc + 1)];
if (lhs == null) lhs = undefined;
}
throw NativeGlobal.typeError1
("msg.isnt.function", ScriptRuntime.toString(lhs), calleeScope);
}
pc += 4;
instructionCount = cx.instructionCount;
break;
}
case Token.NEW : {
if (instructionThreshold != 0) {
instructionCount += INVOCATION_COST;
cx.instructionCount = instructionCount;
instructionCount = -1;
}
int count = getIndex(iCode, pc + 3);
stackTop -= count;
int calleeArgShft = stackTop + 1;
Object lhs = stack[stackTop];
if (lhs instanceof InterpretedFunction) {
// Inlining of InterpretedFunction.construct not to create
// argument array
InterpretedFunction f = (InterpretedFunction)lhs;
Scriptable newInstance = f.createObject(cx, scope);
Object callResult = interpret(cx, scope, newInstance,
stack, sDbl, calleeArgShft, count,
f, f.itsData);
if (callResult instanceof Scriptable && callResult != undefined) {
stack[stackTop] = callResult;
} else {
stack[stackTop] = newInstance;
}
} else if (lhs instanceof Function) {
Function f = (Function)lhs;
Object[] outArgs = getArgsArray(stack, sDbl, calleeArgShft, count);
stack[stackTop] = f.construct(cx, scope, outArgs);
} else {
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
else if (lhs == undefined) {
// special code for better error message for call
// to undefined
lhs = strings[getIndex(iCode, pc + 1)];
if (lhs == null) lhs = undefined;
}
throw NativeGlobal.typeError1
("msg.isnt.function", ScriptRuntime.toString(lhs), scope);
}
pc += 4; instructionCount = cx.instructionCount;
break;
}
case Token.TYPEOF : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.typeof(lhs);
break;
}
case Icode_TYPEOFNAME : {
String name = strings[getIndex(iCode, pc + 1)];
stack[++stackTop] = ScriptRuntime.typeofName(scope, name);
pc += 2;
break;
}
case Token.STRING :
stack[++stackTop] = strings[getIndex(iCode, pc + 1)];
pc += 2;
break;
case Icode_SHORTNUMBER :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = getShort(iCode, pc + 1);
pc += 2;
break;
case Icode_INTNUMBER :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = getInt(iCode, pc + 1);
pc += 4;
break;
case Token.NUMBER :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = idata.itsDoubleTable[getIndex(iCode, pc + 1)];
pc += 2;
break;
case Token.NAME : {
String name = strings[getIndex(iCode, pc + 1)];
stack[++stackTop] = ScriptRuntime.name(scope, name);
pc += 2;
break;
}
case Icode_NAMEINC : {
String name = strings[getIndex(iCode, pc + 1)];
stack[++stackTop] = ScriptRuntime.postIncrement(scope, name);
pc += 2;
break;
}
case Icode_NAMEDEC : {
String name = strings[getIndex(iCode, pc + 1)];
stack[++stackTop] = ScriptRuntime.postDecrement(scope, name);
pc += 2;
break;
}
case Token.SETVAR : {
int slot = (iCode[++pc] & 0xFF);
if (!useActivationVars) {
stack[VAR_SHFT + slot] = stack[stackTop];
sDbl[VAR_SHFT + slot] = sDbl[stackTop];
} else {
Object val = stack[stackTop];
if (val == DBL_MRK) val = doubleWrap(sDbl[stackTop]);
activationPut(fnOrScript, scope, slot, val);
}
break;
}
case Token.GETVAR : {
int slot = (iCode[++pc] & 0xFF);
++stackTop;
if (!useActivationVars) {
stack[stackTop] = stack[VAR_SHFT + slot];
sDbl[stackTop] = sDbl[VAR_SHFT + slot];
} else {
stack[stackTop] = activationGet(fnOrScript, scope, slot);
}
break;
}
case Icode_VARINC : {
int slot = (iCode[++pc] & 0xFF);
++stackTop;
if (!useActivationVars) {
stack[stackTop] = stack[VAR_SHFT + slot];
sDbl[stackTop] = sDbl[VAR_SHFT + slot];
stack[VAR_SHFT + slot] = DBL_MRK;
sDbl[VAR_SHFT + slot] = stack_double(stack, sDbl, stackTop) + 1.0;
} else {
Object val = activationGet(fnOrScript, scope, slot);
stack[stackTop] = val;
val = doubleWrap(ScriptRuntime.toNumber(val) + 1.0);
activationPut(fnOrScript, scope, slot, val);
}
break;
}
case Icode_VARDEC : {
int slot = (iCode[++pc] & 0xFF);
++stackTop;
if (!useActivationVars) {
stack[stackTop] = stack[VAR_SHFT + slot];
sDbl[stackTop] = sDbl[VAR_SHFT + slot];
stack[VAR_SHFT + slot] = DBL_MRK;
sDbl[VAR_SHFT + slot] = stack_double(stack, sDbl, stackTop) - 1.0;
} else {
Object val = activationGet(fnOrScript, scope, slot);
stack[stackTop] = val;
val = doubleWrap(ScriptRuntime.toNumber(val) - 1.0);
activationPut(fnOrScript, scope, slot, val);
}
break;
}
case Token.ZERO :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = 0;
break;
case Token.ONE :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = 1;
break;
case Token.NULL :
stack[++stackTop] = null;
break;
case Token.THIS :
stack[++stackTop] = thisObj;
break;
case Token.THISFN :
stack[++stackTop] = fnOrScript;
break;
case Token.FALSE :
stack[++stackTop] = Boolean.FALSE;
break;
case Token.TRUE :
stack[++stackTop] = Boolean.TRUE;
break;
case Token.UNDEFINED :
stack[++stackTop] = Undefined.instance;
break;
case Token.ENTERWITH : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
--stackTop;
scope = ScriptRuntime.enterWith(lhs, scope);
++withDepth;
break;
}
case Token.LEAVEWITH :
scope = ScriptRuntime.leaveWith(scope);
--withDepth;
break;
case Token.NEWSCOPE :
stack[++stackTop] = ScriptRuntime.newScope();
break;
case Token.ENUMINIT : {
int slot = (iCode[++pc] & 0xFF);
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
--stackTop;
stack[LOCAL_SHFT + slot] = ScriptRuntime.initEnum(lhs, scope);
break;
}
case Token.ENUMNEXT : {
int slot = (iCode[++pc] & 0xFF);
Object val = stack[LOCAL_SHFT + slot];
++stackTop;
stack[stackTop] = ScriptRuntime.nextEnum(val);
break;
}
case Icode_GETPROTO : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.getProto(lhs, scope);
break;
}
case Icode_GETPARENT : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.getParent(lhs);
break;
}
case Icode_GETSCOPEPARENT : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.getParent(lhs, scope);
break;
}
case Icode_SETPROTO : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.setProto(lhs, rhs, scope);
break;
}
case Icode_SETPARENT : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.setParent(lhs, rhs, scope);
break;
}
case Icode_SCOPE :
stack[++stackTop] = scope;
break;
case Icode_CLOSURE : {
int i = getIndex(iCode, pc + 1);
InterpreterData closureData = idata.itsNestedFunctions[i];
stack[++stackTop] = createFunction(cx, scope, closureData,
idata.itsFromEvalCode);
pc += 2;
break;
}
case Token.REGEXP : {
int i = getIndex(iCode, pc + 1);
stack[++stackTop] = idata.itsRegExpLiterals[i];
pc += 2;
break;
}
case Icode_LINE : {
int line = getShort(iCode, pc + 1);
cx.interpreterLine = line;
if (debuggerFrame != null) {
debuggerFrame.onLineChange(cx, line);
}
pc += 2;
break;
}
default : {
dumpICode(idata);
throw new RuntimeException
("Unknown icode : "+(iCode[pc] & 0xff)+" @ pc : "+pc);
}
// end of interpreter switch
}
pc++;
}
catch (Throwable ex) {
if (instructionThreshold != 0) {
if (instructionCount < 0) {
// throw during function call
instructionCount = cx.instructionCount;
} else {
// throw during any other operation
instructionCount += pc - pcPrevBranch;
cx.instructionCount = instructionCount;
}
}
javaException = ex;
exceptionPC = pc;
pc = getJavaCatchPC(iCode);
continue Loop;
}
}
cx.interpreterSourceFile = savedSourceFile;
if (debuggerFrame != null) {
if (javaException != null) {
debuggerFrame.onExit(cx, true, javaException);
} else {
debuggerFrame.onExit(cx, false, result);
}
}
if (idata.itsNeedsActivation) {
ScriptRuntime.popActivation(cx);
}
if (instructionThreshold != 0) {
if (instructionCount > instructionThreshold) {
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
cx.instructionCount = instructionCount;
}
if (javaException != null) {
if (javaException instanceof JavaScriptException) {
throw (JavaScriptException)javaException;
} else if (javaException instanceof RuntimeException) {
throw (RuntimeException)javaException;
} else {
// Must be instance of Error or code bug
throw (Error)javaException;
}
}
return result;
}
private static Object doubleWrap(double x)
{
return new Double(x);
}
private static int stack_int32(Object[] stack, double[] stackDbl, int i) {
Object x = stack[i];
return (x != DBL_MRK)
? ScriptRuntime.toInt32(x)
: ScriptRuntime.toInt32(stackDbl[i]);
}
private static double stack_double(Object[] stack, double[] stackDbl,
int i)
{
Object x = stack[i];
return (x != DBL_MRK) ? ScriptRuntime.toNumber(x) : stackDbl[i];
}
private static boolean stack_boolean(Object[] stack, double[] stackDbl,
int i)
{
Object x = stack[i];
if (x == DBL_MRK) {
double d = stackDbl[i];
return d == d && d != 0.0;
} else if (x instanceof Boolean) {
return ((Boolean)x).booleanValue();
} else if (x == null || x == Undefined.instance) {
return false;
} else if (x instanceof Number) {
double d = ((Number)x).doubleValue();
return (d == d && d != 0.0);
} else {
return ScriptRuntime.toBoolean(x);
}
}
private static void do_add(Object[] stack, double[] stackDbl, int stackTop)
{
Object rhs = stack[stackTop + 1];
Object lhs = stack[stackTop];
if (rhs == DBL_MRK) {
double rDbl = stackDbl[stackTop + 1];
if (lhs == DBL_MRK) {
stackDbl[stackTop] += rDbl;
} else {
do_add(lhs, rDbl, stack, stackDbl, stackTop, true);
}
} else if (lhs == DBL_MRK) {
do_add(rhs, stackDbl[stackTop], stack, stackDbl, stackTop, false);
} else {
if (lhs instanceof Scriptable)
lhs = ((Scriptable) lhs).getDefaultValue(null);
if (rhs instanceof Scriptable)
rhs = ((Scriptable) rhs).getDefaultValue(null);
if (lhs instanceof String) {
String lstr = (String)lhs;
String rstr = ScriptRuntime.toString(rhs);
stack[stackTop] = lstr.concat(rstr);
} else if (rhs instanceof String) {
String lstr = ScriptRuntime.toString(lhs);
String rstr = (String)rhs;
stack[stackTop] = lstr.concat(rstr);
} else {
double lDbl = (lhs instanceof Number)
? ((Number)lhs).doubleValue() : ScriptRuntime.toNumber(lhs);
double rDbl = (rhs instanceof Number)
? ((Number)rhs).doubleValue() : ScriptRuntime.toNumber(rhs);
stack[stackTop] = DBL_MRK;
stackDbl[stackTop] = lDbl + rDbl;
}
}
}
// x + y when x is Number
private static void do_add
(Object lhs, double rDbl,
Object[] stack, double[] stackDbl, int stackTop,
boolean left_right_order)
{
if (lhs instanceof Scriptable) {
if (lhs == Undefined.instance) {
lhs = ScriptRuntime.NaNobj;
} else {
lhs = ((Scriptable)lhs).getDefaultValue(null);
}
}
if (lhs instanceof String) {
String lstr = (String)lhs;
String rstr = ScriptRuntime.toString(rDbl);
if (left_right_order) {
stack[stackTop] = lstr.concat(rstr);
} else {
stack[stackTop] = rstr.concat(lstr);
}
} else {
double lDbl = (lhs instanceof Number)
? ((Number)lhs).doubleValue() : ScriptRuntime.toNumber(lhs);
stack[stackTop] = DBL_MRK;
stackDbl[stackTop] = lDbl + rDbl;
}
}
private static boolean do_eq(Object[] stack, double[] stackDbl,
int stackTop)
{
boolean result;
Object rhs = stack[stackTop + 1];
Object lhs = stack[stackTop];
if (rhs == DBL_MRK) {
if (lhs == DBL_MRK) {
result = (stackDbl[stackTop] == stackDbl[stackTop + 1]);
} else {
result = do_eq(stackDbl[stackTop + 1], lhs);
}
} else {
if (lhs == DBL_MRK) {
result = do_eq(stackDbl[stackTop], rhs);
} else {
result = ScriptRuntime.eq(lhs, rhs);
}
}
return result;
}
// Optimized version of ScriptRuntime.eq if x is a Number
private static boolean do_eq(double x, Object y)
{
for (;;) {
if (y instanceof Number) {
return x == ((Number) y).doubleValue();
}
if (y instanceof String) {
return x == ScriptRuntime.toNumber((String)y);
}
if (y instanceof Boolean) {
return x == (((Boolean)y).booleanValue() ? 1 : 0);
}
if (y instanceof Scriptable) {
if (y == Undefined.instance) { return false; }
y = ScriptRuntime.toPrimitive(y);
continue;
}
return false;
}
}
private static boolean do_sheq(Object[] stack, double[] stackDbl,
int stackTop)
{
boolean result;
Object rhs = stack[stackTop + 1];
Object lhs = stack[stackTop];
if (rhs == DBL_MRK) {
double rDbl = stackDbl[stackTop + 1];
if (lhs == DBL_MRK) {
result = (stackDbl[stackTop] == rDbl);
} else {
result = (lhs instanceof Number);
if (result) {
result = (((Number)lhs).doubleValue() == rDbl);
}
}
} else if (rhs instanceof Number) {
double rDbl = ((Number)rhs).doubleValue();
if (lhs == DBL_MRK) {
result = (stackDbl[stackTop] == rDbl);
} else {
result = (lhs instanceof Number);
if (result) {
result = (((Number)lhs).doubleValue() == rDbl);
}
}
} else {
result = ScriptRuntime.shallowEq(lhs, rhs);
}
return result;
}
private static void do_getElem(Context cx,
Object[] stack, double[] stackDbl,
int stackTop, Scriptable scope)
{
Object lhs = stack[stackTop - 1];
if (lhs == DBL_MRK) lhs = doubleWrap(stackDbl[stackTop - 1]);
Object result;
Object id = stack[stackTop];
if (id != DBL_MRK) {
result = ScriptRuntime.getElem(lhs, id, scope);
} else {
double val = stackDbl[stackTop];
if (lhs == null || lhs == Undefined.instance) {
throw NativeGlobal.undefReadError(
lhs, ScriptRuntime.toString(val), scope);
}
Scriptable obj = (lhs instanceof Scriptable)
? (Scriptable)lhs
: ScriptRuntime.toObject(cx, scope, lhs);
int index = (int)val;
if (index == val) {
result = ScriptRuntime.getElem(obj, index);
} else {
String s = ScriptRuntime.toString(val);
result = ScriptRuntime.getStrIdElem(obj, s);
}
}
stack[stackTop - 1] = result;
}
private static void do_setElem(Context cx,
Object[] stack, double[] stackDbl,
int stackTop, Scriptable scope)
{
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(stackDbl[stackTop]);
Object lhs = stack[stackTop - 2];
if (lhs == DBL_MRK) lhs = doubleWrap(stackDbl[stackTop - 2]);
Object result;
Object id = stack[stackTop - 1];
if (id != DBL_MRK) {
result = ScriptRuntime.setElem(lhs, id, rhs, scope);
} else {
double val = stackDbl[stackTop - 1];
if (lhs == null || lhs == Undefined.instance) {
throw NativeGlobal.undefWriteError(
lhs, ScriptRuntime.toString(val), rhs, scope);
}
Scriptable obj = (lhs instanceof Scriptable)
? (Scriptable)lhs
: ScriptRuntime.toObject(cx, scope, lhs);
int index = (int)val;
if (index == val) {
result = ScriptRuntime.setElem(obj, index, rhs);
} else {
String s = ScriptRuntime.toString(val);
result = ScriptRuntime.setStrIdElem(obj, s, rhs, scope);
}
}
stack[stackTop - 2] = result;
}
private static Object[] getArgsArray(Object[] stack, double[] sDbl,
int shift, int count)
{
if (count == 0) {
return ScriptRuntime.emptyArgs;
}
Object[] args = new Object[count];
for (int i = 0; i != count; ++i, ++shift) {
Object val = stack[shift];
if (val == DBL_MRK) val = doubleWrap(sDbl[shift]);
args[i] = val;
}
return args;
}
private static Object activationGet(NativeFunction f,
Scriptable activation, int slot)
{
String name = f.argNames[slot];
Object val = activation.get(name, activation);
// Activation parameter or var is permanent
if (val == Scriptable.NOT_FOUND) Context.codeBug();
return val;
}
private static void activationPut(NativeFunction f,
Scriptable activation, int slot,
Object value)
{
String name = f.argNames[slot];
activation.put(name, activation, value);
}
private static Object execWithNewDomain(Context cx, Scriptable scope,
final Scriptable thisObj,
final Object[] args,
final double[] argsDbl,
final int argShift,
final int argCount,
final NativeFunction fnOrScript,
final InterpreterData idata)
throws JavaScriptException
{
if (cx.interpreterSecurityDomain == idata.securityDomain)
Context.codeBug();
Script code = new Script() {
public Object exec(Context cx, Scriptable scope)
throws JavaScriptException
{
return interpret(cx, scope, thisObj,
args, argsDbl, argShift, argCount,
fnOrScript, idata);
}
};
Object savedDomain = cx.interpreterSecurityDomain;
cx.interpreterSecurityDomain = idata.securityDomain;
try {
return cx.getSecurityController().
execWithDomain(cx, scope, code, idata.securityDomain);
} finally {
cx.interpreterSecurityDomain = savedDomain;
}
}
private static int getJavaCatchPC(byte[] iCode)
{
int pc = iCode.length - 1;
if ((iCode[pc] & 0xFF) != Icode_CATCH) Context.codeBug();
return pc;
}
private boolean itsInFunctionFlag;
private InterpreterData itsData;
private ScriptOrFnNode scriptOrFn;
private int itsStackDepth = 0;
private int itsWithDepth = 0;
private int itsLineNumber = 0;
private LabelTable itsLabels = new LabelTable();
private int itsDoubleTableTop;
private ObjToIntMap itsStrings = new ObjToIntMap(20);
private String lastAddString;
private int itsExceptionTableTop = 0;
// 5 = space for try start/end, catch begin, finally begin and with depth
private static final int EXCEPTION_SLOT_SIZE = 5;
private static final int EXCEPTION_TRY_START_SLOT = 0;
private static final int EXCEPTION_TRY_END_SLOT = 1;
private static final int EXCEPTION_CATCH_SLOT = 2;
private static final int EXCEPTION_FINALLY_SLOT = 3;
private static final int EXCEPTION_WITH_DEPTH_SLOT = 4;
private static final Object DBL_MRK = new Object();
}
| true | true | static Object interpret(Context cx, Scriptable scope, Scriptable thisObj,
Object[] args, double[] argsDbl,
int argShift, int argCount,
NativeFunction fnOrScript,
InterpreterData idata)
throws JavaScriptException
{
if (cx.interpreterSecurityDomain != idata.securityDomain) {
return execWithNewDomain(cx, scope, thisObj,
args, argsDbl, argShift, argCount,
fnOrScript, idata);
}
final Object DBL_MRK = Interpreter.DBL_MRK;
final Scriptable undefined = Undefined.instance;
final int VAR_SHFT = 0;
final int maxVars = idata.itsMaxVars;
final int LOCAL_SHFT = VAR_SHFT + maxVars;
final int STACK_SHFT = LOCAL_SHFT + idata.itsMaxLocals;
// stack[VAR_SHFT <= i < LOCAL_SHFT]: variables
// stack[LOCAL_SHFT <= i < TRY_STACK_SHFT]: used for newtemp/usetemp
// stack[STACK_SHFT <= i < STACK_SHFT + idata.itsMaxStack]: stack data
// sDbl[i]: if stack[i] is DBL_MRK, sDbl[i] holds the number value
int maxFrameArray = idata.itsMaxFrameArray;
if (maxFrameArray != STACK_SHFT + idata.itsMaxStack)
Context.codeBug();
Object[] stack = new Object[maxFrameArray];
double[] sDbl = new double[maxFrameArray];
int stackTop = STACK_SHFT - 1;
int withDepth = 0;
int definedArgs = fnOrScript.argCount;
if (definedArgs > argCount) { definedArgs = argCount; }
for (int i = 0; i != definedArgs; ++i) {
Object arg = args[argShift + i];
stack[VAR_SHFT + i] = arg;
if (arg == DBL_MRK) {
sDbl[VAR_SHFT + i] = argsDbl[argShift + i];
}
}
for (int i = definedArgs; i != maxVars; ++i) {
stack[VAR_SHFT + i] = undefined;
}
DebugFrame debuggerFrame = null;
if (cx.debugger != null) {
debuggerFrame = cx.debugger.getFrame(cx, idata);
}
if (idata.itsFunctionType != 0) {
InterpretedFunction f = (InterpretedFunction)fnOrScript;
if (!f.itsUseDynamicScope) {
scope = fnOrScript.getParentScope();
}
if (idata.itsCheckThis) {
thisObj = ScriptRuntime.getThis(thisObj);
}
if (idata.itsNeedsActivation) {
if (argsDbl != null) {
args = getArgsArray(args, argsDbl, argShift, argCount);
argShift = 0;
argsDbl = null;
}
scope = ScriptRuntime.initVarObj(cx, scope, fnOrScript,
thisObj, args);
}
} else {
scope = ScriptRuntime.initScript(cx, scope, fnOrScript, thisObj,
idata.itsFromEvalCode);
}
if (idata.itsNestedFunctions != null) {
if (idata.itsFunctionType != 0 && !idata.itsNeedsActivation)
Context.codeBug();
for (int i = 0; i < idata.itsNestedFunctions.length; i++) {
InterpreterData fdata = idata.itsNestedFunctions[i];
if (fdata.itsFunctionType == FunctionNode.FUNCTION_STATEMENT) {
createFunction(cx, scope, fdata, idata.itsFromEvalCode);
}
}
}
boolean useActivationVars = false;
if (debuggerFrame != null) {
if (argsDbl != null) {
args = getArgsArray(args, argsDbl, argShift, argCount);
argShift = 0;
argsDbl = null;
}
if (idata.itsFunctionType != 0 && !idata.itsNeedsActivation) {
useActivationVars = true;
scope = ScriptRuntime.initVarObj(cx, scope, fnOrScript,
thisObj, args);
}
debuggerFrame.onEnter(cx, scope, thisObj, args);
}
String savedSourceFile = cx.interpreterSourceFile;
cx.interpreterSourceFile = idata.itsSourceFile;
Object result = undefined;
// If javaException != null on exit, it will be throw instead of
// normal return
Throwable javaException = null;
int exceptionPC = -1;
byte[] iCode = idata.itsICode;
String[] strings = idata.itsStringTable;
int pc = 0;
int pcPrevBranch = pc;
final int instructionThreshold = cx.instructionThreshold;
// During function call this will be set to -1 so catch can properly
// adjust it
int instructionCount = cx.instructionCount;
// arbitrary number to add to instructionCount when calling
// other functions
final int INVOCATION_COST = 100;
Loop: for (;;) {
try {
switch (iCode[pc] & 0xff) {
// Back indent to ease imlementation reading
case Icode_CATCH: {
// The following code should be executed inside try/catch inside main
// loop, not in the loop catch block itself to deal withnexceptions
// from observeInstructionCount. A special bytecode is used only to
// simplify logic.
if (javaException == null) Context.codeBug();
int pcNew = -1;
boolean doCatch = false;
int handlerOffset = getExceptionHandler(idata.itsExceptionTable,
exceptionPC);
if (handlerOffset >= 0) {
final int SCRIPT_CAN_CATCH = 0, ONLY_FINALLY = 1, OTHER = 2;
int exType;
if (javaException instanceof JavaScriptException) {
exType = SCRIPT_CAN_CATCH;
} else if (javaException instanceof EcmaError) {
// an offical ECMA error object,
exType = SCRIPT_CAN_CATCH;
} else if (javaException instanceof WrappedException) {
exType = SCRIPT_CAN_CATCH;
} else if (javaException instanceof RuntimeException) {
exType = ONLY_FINALLY;
} else {
// Error instance
exType = OTHER;
}
if (exType != OTHER) {
// Do not allow for JS to interfere with Error instances
// (exType == OTHER), as they can be used to terminate
// long running script
if (exType == SCRIPT_CAN_CATCH) {
// Allow JS to catch only JavaScriptException and
// EcmaError
pcNew = idata.itsExceptionTable[handlerOffset
+ EXCEPTION_CATCH_SLOT];
if (pcNew >= 0) {
// Has catch block
doCatch = true;
}
}
if (pcNew < 0) {
pcNew = idata.itsExceptionTable[handlerOffset
+ EXCEPTION_FINALLY_SLOT];
}
}
}
if (debuggerFrame != null && !(javaException instanceof Error)) {
debuggerFrame.onExceptionThrown(cx, javaException);
}
if (pcNew < 0) {
break Loop;
}
// We caught an exception
// restore scope at try point
int tryWithDepth = idata.itsExceptionTable[
handlerOffset + EXCEPTION_WITH_DEPTH_SLOT];
while (tryWithDepth != withDepth) {
if (scope == null) Context.codeBug();
scope = ScriptRuntime.leaveWith(scope);
--withDepth;
}
// make stack to contain single exception object
stackTop = STACK_SHFT;
if (doCatch) {
stack[stackTop] = ScriptRuntime.getCatchObject(cx, scope,
javaException);
} else {
// Call finally handler with javaException on stack top to
// distinguish from normal invocation through GOSUB
// which would contain DBL_MRK on the stack
stack[stackTop] = javaException;
}
// clear exception
javaException = null;
// Notify instruction observer if necessary
// and point pc and pcPrevBranch to start of catch/finally block
if (instructionThreshold != 0) {
if (instructionCount > instructionThreshold) {
// Note: this can throw Error
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
}
pcPrevBranch = pc = pcNew;
continue Loop;
}
case Token.THROW: {
Object value = stack[stackTop];
if (value == DBL_MRK) value = doubleWrap(sDbl[stackTop]);
--stackTop;
int sourceLine = getShort(iCode, pc + 1);
javaException = new JavaScriptException(value, idata.itsSourceFile,
sourceLine);
exceptionPC = pc;
if (instructionThreshold != 0) {
instructionCount += pc + 1 - pcPrevBranch;
if (instructionCount > instructionThreshold) {
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
}
pcPrevBranch = pc = getJavaCatchPC(iCode);
continue Loop;
}
case Token.GE : {
--stackTop;
Object rhs = stack[stackTop + 1];
Object lhs = stack[stackTop];
boolean valBln;
if (rhs == DBL_MRK || lhs == DBL_MRK) {
double rDbl = stack_double(stack, sDbl, stackTop + 1);
double lDbl = stack_double(stack, sDbl, stackTop);
valBln = (rDbl == rDbl && lDbl == lDbl && rDbl <= lDbl);
} else {
valBln = (1 == ScriptRuntime.cmp_LE(rhs, lhs));
}
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case Token.LE : {
--stackTop;
Object rhs = stack[stackTop + 1];
Object lhs = stack[stackTop];
boolean valBln;
if (rhs == DBL_MRK || lhs == DBL_MRK) {
double rDbl = stack_double(stack, sDbl, stackTop + 1);
double lDbl = stack_double(stack, sDbl, stackTop);
valBln = (rDbl == rDbl && lDbl == lDbl && lDbl <= rDbl);
} else {
valBln = (1 == ScriptRuntime.cmp_LE(lhs, rhs));
}
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case Token.GT : {
--stackTop;
Object rhs = stack[stackTop + 1];
Object lhs = stack[stackTop];
boolean valBln;
if (rhs == DBL_MRK || lhs == DBL_MRK) {
double rDbl = stack_double(stack, sDbl, stackTop + 1);
double lDbl = stack_double(stack, sDbl, stackTop);
valBln = (rDbl == rDbl && lDbl == lDbl && rDbl < lDbl);
} else {
valBln = (1 == ScriptRuntime.cmp_LT(rhs, lhs));
}
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case Token.LT : {
--stackTop;
Object rhs = stack[stackTop + 1];
Object lhs = stack[stackTop];
boolean valBln;
if (rhs == DBL_MRK || lhs == DBL_MRK) {
double rDbl = stack_double(stack, sDbl, stackTop + 1);
double lDbl = stack_double(stack, sDbl, stackTop);
valBln = (rDbl == rDbl && lDbl == lDbl && lDbl < rDbl);
} else {
valBln = (1 == ScriptRuntime.cmp_LT(lhs, rhs));
}
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case Token.IN : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
boolean valBln = ScriptRuntime.in(lhs, rhs, scope);
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case Token.INSTANCEOF : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
boolean valBln = ScriptRuntime.instanceOf(lhs, rhs, scope);
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case Token.EQ : {
--stackTop;
boolean valBln = do_eq(stack, sDbl, stackTop);
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case Token.NE : {
--stackTop;
boolean valBln = !do_eq(stack, sDbl, stackTop);
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case Token.SHEQ : {
--stackTop;
boolean valBln = do_sheq(stack, sDbl, stackTop);
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case Token.SHNE : {
--stackTop;
boolean valBln = !do_sheq(stack, sDbl, stackTop);
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case Token.IFNE : {
boolean valBln = stack_boolean(stack, sDbl, stackTop);
--stackTop;
if (!valBln) {
if (instructionThreshold != 0) {
instructionCount += pc + 3 - pcPrevBranch;
if (instructionCount > instructionThreshold) {
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
}
pcPrevBranch = pc = getTarget(iCode, pc + 1);
continue Loop;
}
pc += 2;
break;
}
case Token.IFEQ : {
boolean valBln = stack_boolean(stack, sDbl, stackTop);
--stackTop;
if (valBln) {
if (instructionThreshold != 0) {
instructionCount += pc + 3 - pcPrevBranch;
if (instructionCount > instructionThreshold) {
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
}
pcPrevBranch = pc = getTarget(iCode, pc + 1);
continue Loop;
}
pc += 2;
break;
}
case Token.GOTO :
if (instructionThreshold != 0) {
instructionCount += pc + 3 - pcPrevBranch;
if (instructionCount > instructionThreshold) {
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
}
pcPrevBranch = pc = getTarget(iCode, pc + 1);
continue Loop;
case Icode_GOSUB :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = pc + 3;
if (instructionThreshold != 0) {
instructionCount += pc + 3 - pcPrevBranch;
if (instructionCount > instructionThreshold) {
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
}
pcPrevBranch = pc = getTarget(iCode, pc + 1); continue Loop;
case Icode_RETSUB : {
int slot = (iCode[pc + 1] & 0xFF);
if (instructionThreshold != 0) {
instructionCount += pc + 2 - pcPrevBranch;
if (instructionCount > instructionThreshold) {
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
}
int newPC;
Object value = stack[LOCAL_SHFT + slot];
if (value != DBL_MRK) {
// Invocation from exception handler, restore object to rethrow
javaException = (Throwable)value;
exceptionPC = pc;
newPC = getJavaCatchPC(iCode);
} else {
// Normal return from GOSUB
newPC = (int)sDbl[LOCAL_SHFT + slot];
}
pcPrevBranch = pc = newPC;
continue Loop;
}
case Token.POP :
stack[stackTop] = null;
stackTop--;
break;
case Icode_DUP :
stack[stackTop + 1] = stack[stackTop];
sDbl[stackTop + 1] = sDbl[stackTop];
stackTop++;
break;
case Token.POPV :
result = stack[stackTop];
if (result == DBL_MRK) result = doubleWrap(sDbl[stackTop]);
stack[stackTop] = null;
--stackTop;
break;
case Token.RETURN :
result = stack[stackTop];
if (result == DBL_MRK) result = doubleWrap(sDbl[stackTop]);
--stackTop;
break Loop;
case Icode_RETUNDEF :
result = undefined;
break Loop;
case Icode_END:
break Loop;
case Token.BITNOT : {
int rIntValue = stack_int32(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = ~rIntValue;
break;
}
case Token.BITAND : {
int rIntValue = stack_int32(stack, sDbl, stackTop);
--stackTop;
int lIntValue = stack_int32(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lIntValue & rIntValue;
break;
}
case Token.BITOR : {
int rIntValue = stack_int32(stack, sDbl, stackTop);
--stackTop;
int lIntValue = stack_int32(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lIntValue | rIntValue;
break;
}
case Token.BITXOR : {
int rIntValue = stack_int32(stack, sDbl, stackTop);
--stackTop;
int lIntValue = stack_int32(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lIntValue ^ rIntValue;
break;
}
case Token.LSH : {
int rIntValue = stack_int32(stack, sDbl, stackTop);
--stackTop;
int lIntValue = stack_int32(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lIntValue << rIntValue;
break;
}
case Token.RSH : {
int rIntValue = stack_int32(stack, sDbl, stackTop);
--stackTop;
int lIntValue = stack_int32(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lIntValue >> rIntValue;
break;
}
case Token.URSH : {
int rIntValue = stack_int32(stack, sDbl, stackTop) & 0x1F;
--stackTop;
double lDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = ScriptRuntime.toUint32(lDbl) >>> rIntValue;
break;
}
case Token.ADD :
--stackTop;
do_add(stack, sDbl, stackTop);
break;
case Token.SUB : {
double rDbl = stack_double(stack, sDbl, stackTop);
--stackTop;
double lDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lDbl - rDbl;
break;
}
case Token.NEG : {
double rDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = -rDbl;
break;
}
case Token.POS : {
double rDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = rDbl;
break;
}
case Token.MUL : {
double rDbl = stack_double(stack, sDbl, stackTop);
--stackTop;
double lDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lDbl * rDbl;
break;
}
case Token.DIV : {
double rDbl = stack_double(stack, sDbl, stackTop);
--stackTop;
double lDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
// Detect the divide by zero or let Java do it ?
sDbl[stackTop] = lDbl / rDbl;
break;
}
case Token.MOD : {
double rDbl = stack_double(stack, sDbl, stackTop);
--stackTop;
double lDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lDbl % rDbl;
break;
}
case Token.NOT : {
stack[stackTop] = stack_boolean(stack, sDbl, stackTop)
? Boolean.FALSE : Boolean.TRUE;
break;
}
case Token.BINDNAME : {
String name = strings[getIndex(iCode, pc + 1)];
stack[++stackTop] = ScriptRuntime.bind(scope, name);
pc += 2;
break;
}
case Token.GETBASE : {
String name = strings[getIndex(iCode, pc + 1)];
stack[++stackTop] = ScriptRuntime.getBase(scope, name);
pc += 2;
break;
}
case Token.SETNAME : {
String name = strings[getIndex(iCode, pc + 1)];
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
// what about class cast exception here for lhs?
Scriptable lhs = (Scriptable)stack[stackTop];
stack[stackTop] = ScriptRuntime.setName(lhs, rhs, scope, name);
pc += 2;
break;
}
case Token.DELPROP : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.delete(cx, scope, lhs, rhs);
break;
}
case Token.GETPROP : {
String name = (String)stack[stackTop];
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.getProp(lhs, name, scope);
break;
}
case Token.SETPROP : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
String name = (String)stack[stackTop];
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.setProp(lhs, name, rhs, scope);
break;
}
case Token.GETELEM :
do_getElem(cx, stack, sDbl, stackTop, scope);
--stackTop;
break;
case Token.SETELEM :
do_setElem(cx, stack, sDbl, stackTop, scope);
stackTop -= 2;
break;
case Icode_PROPINC : {
String name = (String)stack[stackTop];
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.postIncrement(lhs, name, scope);
break;
}
case Icode_PROPDEC : {
String name = (String)stack[stackTop];
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.postDecrement(lhs, name, scope);
break;
}
case Icode_ELEMINC : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.postIncrementElem(lhs, rhs, scope);
break;
}
case Icode_ELEMDEC : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.postDecrementElem(lhs, rhs, scope);
break;
}
case Token.GETTHIS : {
Scriptable lhs = (Scriptable)stack[stackTop];
stack[stackTop] = ScriptRuntime.getThis(lhs);
break;
}
case Token.NEWTEMP : {
int slot = (iCode[++pc] & 0xFF);
stack[LOCAL_SHFT + slot] = stack[stackTop];
sDbl[LOCAL_SHFT + slot] = sDbl[stackTop];
break;
}
case Token.USETEMP : {
int slot = (iCode[++pc] & 0xFF);
++stackTop;
stack[stackTop] = stack[LOCAL_SHFT + slot];
sDbl[stackTop] = sDbl[LOCAL_SHFT + slot];
break;
}
case Icode_CALLSPECIAL : {
if (instructionThreshold != 0) {
instructionCount += INVOCATION_COST;
cx.instructionCount = instructionCount;
instructionCount = -1;
}
int callType = iCode[pc + 1] & 0xFF;
boolean isNew = (iCode[pc + 2] != 0);
int sourceLine = getShort(iCode, pc + 3);
int count = getIndex(iCode, pc + 5);
stackTop -= count;
Object[] outArgs = getArgsArray(stack, sDbl, stackTop + 1, count);
Object functionThis;
if (isNew) {
functionThis = null;
} else {
functionThis = stack[stackTop];
if (functionThis == DBL_MRK) {
functionThis = doubleWrap(sDbl[stackTop]);
}
--stackTop;
}
Object function = stack[stackTop];
if (function == DBL_MRK) function = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.callSpecial(
cx, function, isNew, functionThis, outArgs,
scope, thisObj, callType,
idata.itsSourceFile, sourceLine);
pc += 6;
instructionCount = cx.instructionCount;
break;
}
case Token.CALL : {
if (instructionThreshold != 0) {
instructionCount += INVOCATION_COST;
cx.instructionCount = instructionCount;
instructionCount = -1;
}
cx.instructionCount = instructionCount;
int count = getIndex(iCode, pc + 3);
stackTop -= count;
int calleeArgShft = stackTop + 1;
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
Scriptable calleeScope = scope;
if (idata.itsNeedsActivation) {
calleeScope = ScriptableObject.getTopLevelScope(scope);
}
Scriptable calleeThis;
if (rhs instanceof Scriptable || rhs == null) {
calleeThis = (Scriptable)rhs;
} else {
calleeThis = ScriptRuntime.toObject(cx, calleeScope, rhs);
}
if (lhs instanceof InterpretedFunction) {
// Inlining of InterpretedFunction.call not to create
// argument array
InterpretedFunction f = (InterpretedFunction)lhs;
stack[stackTop] = interpret(cx, calleeScope, calleeThis,
stack, sDbl, calleeArgShft, count,
f, f.itsData);
} else if (lhs instanceof Function) {
Function f = (Function)lhs;
Object[] outArgs = getArgsArray(stack, sDbl, calleeArgShft, count);
stack[stackTop] = f.call(cx, calleeScope, calleeThis, outArgs);
} else {
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
else if (lhs == undefined) {
// special code for better error message for call
// to undefined
lhs = strings[getIndex(iCode, pc + 1)];
if (lhs == null) lhs = undefined;
}
throw NativeGlobal.typeError1
("msg.isnt.function", ScriptRuntime.toString(lhs), calleeScope);
}
pc += 4;
instructionCount = cx.instructionCount;
break;
}
case Token.NEW : {
if (instructionThreshold != 0) {
instructionCount += INVOCATION_COST;
cx.instructionCount = instructionCount;
instructionCount = -1;
}
int count = getIndex(iCode, pc + 3);
stackTop -= count;
int calleeArgShft = stackTop + 1;
Object lhs = stack[stackTop];
if (lhs instanceof InterpretedFunction) {
// Inlining of InterpretedFunction.construct not to create
// argument array
InterpretedFunction f = (InterpretedFunction)lhs;
Scriptable newInstance = f.createObject(cx, scope);
Object callResult = interpret(cx, scope, newInstance,
stack, sDbl, calleeArgShft, count,
f, f.itsData);
if (callResult instanceof Scriptable && callResult != undefined) {
stack[stackTop] = callResult;
} else {
stack[stackTop] = newInstance;
}
} else if (lhs instanceof Function) {
Function f = (Function)lhs;
Object[] outArgs = getArgsArray(stack, sDbl, calleeArgShft, count);
stack[stackTop] = f.construct(cx, scope, outArgs);
} else {
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
else if (lhs == undefined) {
// special code for better error message for call
// to undefined
lhs = strings[getIndex(iCode, pc + 1)];
if (lhs == null) lhs = undefined;
}
throw NativeGlobal.typeError1
("msg.isnt.function", ScriptRuntime.toString(lhs), scope);
}
pc += 4; instructionCount = cx.instructionCount;
break;
}
case Token.TYPEOF : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.typeof(lhs);
break;
}
case Icode_TYPEOFNAME : {
String name = strings[getIndex(iCode, pc + 1)];
stack[++stackTop] = ScriptRuntime.typeofName(scope, name);
pc += 2;
break;
}
case Token.STRING :
stack[++stackTop] = strings[getIndex(iCode, pc + 1)];
pc += 2;
break;
case Icode_SHORTNUMBER :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = getShort(iCode, pc + 1);
pc += 2;
break;
case Icode_INTNUMBER :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = getInt(iCode, pc + 1);
pc += 4;
break;
case Token.NUMBER :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = idata.itsDoubleTable[getIndex(iCode, pc + 1)];
pc += 2;
break;
case Token.NAME : {
String name = strings[getIndex(iCode, pc + 1)];
stack[++stackTop] = ScriptRuntime.name(scope, name);
pc += 2;
break;
}
case Icode_NAMEINC : {
String name = strings[getIndex(iCode, pc + 1)];
stack[++stackTop] = ScriptRuntime.postIncrement(scope, name);
pc += 2;
break;
}
case Icode_NAMEDEC : {
String name = strings[getIndex(iCode, pc + 1)];
stack[++stackTop] = ScriptRuntime.postDecrement(scope, name);
pc += 2;
break;
}
case Token.SETVAR : {
int slot = (iCode[++pc] & 0xFF);
if (!useActivationVars) {
stack[VAR_SHFT + slot] = stack[stackTop];
sDbl[VAR_SHFT + slot] = sDbl[stackTop];
} else {
Object val = stack[stackTop];
if (val == DBL_MRK) val = doubleWrap(sDbl[stackTop]);
activationPut(fnOrScript, scope, slot, val);
}
break;
}
case Token.GETVAR : {
int slot = (iCode[++pc] & 0xFF);
++stackTop;
if (!useActivationVars) {
stack[stackTop] = stack[VAR_SHFT + slot];
sDbl[stackTop] = sDbl[VAR_SHFT + slot];
} else {
stack[stackTop] = activationGet(fnOrScript, scope, slot);
}
break;
}
case Icode_VARINC : {
int slot = (iCode[++pc] & 0xFF);
++stackTop;
if (!useActivationVars) {
stack[stackTop] = stack[VAR_SHFT + slot];
sDbl[stackTop] = sDbl[VAR_SHFT + slot];
stack[VAR_SHFT + slot] = DBL_MRK;
sDbl[VAR_SHFT + slot] = stack_double(stack, sDbl, stackTop) + 1.0;
} else {
Object val = activationGet(fnOrScript, scope, slot);
stack[stackTop] = val;
val = doubleWrap(ScriptRuntime.toNumber(val) + 1.0);
activationPut(fnOrScript, scope, slot, val);
}
break;
}
case Icode_VARDEC : {
int slot = (iCode[++pc] & 0xFF);
++stackTop;
if (!useActivationVars) {
stack[stackTop] = stack[VAR_SHFT + slot];
sDbl[stackTop] = sDbl[VAR_SHFT + slot];
stack[VAR_SHFT + slot] = DBL_MRK;
sDbl[VAR_SHFT + slot] = stack_double(stack, sDbl, stackTop) - 1.0;
} else {
Object val = activationGet(fnOrScript, scope, slot);
stack[stackTop] = val;
val = doubleWrap(ScriptRuntime.toNumber(val) - 1.0);
activationPut(fnOrScript, scope, slot, val);
}
break;
}
case Token.ZERO :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = 0;
break;
case Token.ONE :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = 1;
break;
case Token.NULL :
stack[++stackTop] = null;
break;
case Token.THIS :
stack[++stackTop] = thisObj;
break;
case Token.THISFN :
stack[++stackTop] = fnOrScript;
break;
case Token.FALSE :
stack[++stackTop] = Boolean.FALSE;
break;
case Token.TRUE :
stack[++stackTop] = Boolean.TRUE;
break;
case Token.UNDEFINED :
stack[++stackTop] = Undefined.instance;
break;
case Token.ENTERWITH : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
--stackTop;
scope = ScriptRuntime.enterWith(lhs, scope);
++withDepth;
break;
}
case Token.LEAVEWITH :
scope = ScriptRuntime.leaveWith(scope);
--withDepth;
break;
case Token.NEWSCOPE :
stack[++stackTop] = ScriptRuntime.newScope();
break;
case Token.ENUMINIT : {
int slot = (iCode[++pc] & 0xFF);
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
--stackTop;
stack[LOCAL_SHFT + slot] = ScriptRuntime.initEnum(lhs, scope);
break;
}
case Token.ENUMNEXT : {
int slot = (iCode[++pc] & 0xFF);
Object val = stack[LOCAL_SHFT + slot];
++stackTop;
stack[stackTop] = ScriptRuntime.nextEnum(val);
break;
}
case Icode_GETPROTO : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.getProto(lhs, scope);
break;
}
case Icode_GETPARENT : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.getParent(lhs);
break;
}
case Icode_GETSCOPEPARENT : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.getParent(lhs, scope);
break;
}
case Icode_SETPROTO : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.setProto(lhs, rhs, scope);
break;
}
case Icode_SETPARENT : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.setParent(lhs, rhs, scope);
break;
}
case Icode_SCOPE :
stack[++stackTop] = scope;
break;
case Icode_CLOSURE : {
int i = getIndex(iCode, pc + 1);
InterpreterData closureData = idata.itsNestedFunctions[i];
stack[++stackTop] = createFunction(cx, scope, closureData,
idata.itsFromEvalCode);
pc += 2;
break;
}
case Token.REGEXP : {
int i = getIndex(iCode, pc + 1);
stack[++stackTop] = idata.itsRegExpLiterals[i];
pc += 2;
break;
}
case Icode_LINE : {
int line = getShort(iCode, pc + 1);
cx.interpreterLine = line;
if (debuggerFrame != null) {
debuggerFrame.onLineChange(cx, line);
}
pc += 2;
break;
}
default : {
dumpICode(idata);
throw new RuntimeException
("Unknown icode : "+(iCode[pc] & 0xff)+" @ pc : "+pc);
}
// end of interpreter switch
}
pc++;
}
catch (Throwable ex) {
if (instructionThreshold != 0) {
if (instructionCount < 0) {
// throw during function call
instructionCount = cx.instructionCount;
} else {
// throw during any other operation
instructionCount += pc - pcPrevBranch;
cx.instructionCount = instructionCount;
}
}
javaException = ex;
exceptionPC = pc;
pc = getJavaCatchPC(iCode);
continue Loop;
}
}
cx.interpreterSourceFile = savedSourceFile;
if (debuggerFrame != null) {
if (javaException != null) {
debuggerFrame.onExit(cx, true, javaException);
} else {
debuggerFrame.onExit(cx, false, result);
}
}
if (idata.itsNeedsActivation) {
ScriptRuntime.popActivation(cx);
}
if (instructionThreshold != 0) {
if (instructionCount > instructionThreshold) {
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
cx.instructionCount = instructionCount;
}
if (javaException != null) {
if (javaException instanceof JavaScriptException) {
throw (JavaScriptException)javaException;
} else if (javaException instanceof RuntimeException) {
throw (RuntimeException)javaException;
} else {
// Must be instance of Error or code bug
throw (Error)javaException;
}
}
return result;
}
| static Object interpret(Context cx, Scriptable scope, Scriptable thisObj,
Object[] args, double[] argsDbl,
int argShift, int argCount,
NativeFunction fnOrScript,
InterpreterData idata)
throws JavaScriptException
{
if (cx.interpreterSecurityDomain != idata.securityDomain) {
return execWithNewDomain(cx, scope, thisObj,
args, argsDbl, argShift, argCount,
fnOrScript, idata);
}
final Object DBL_MRK = Interpreter.DBL_MRK;
final Scriptable undefined = Undefined.instance;
final int VAR_SHFT = 0;
final int maxVars = idata.itsMaxVars;
final int LOCAL_SHFT = VAR_SHFT + maxVars;
final int STACK_SHFT = LOCAL_SHFT + idata.itsMaxLocals;
// stack[VAR_SHFT <= i < LOCAL_SHFT]: variables
// stack[LOCAL_SHFT <= i < TRY_STACK_SHFT]: used for newtemp/usetemp
// stack[STACK_SHFT <= i < STACK_SHFT + idata.itsMaxStack]: stack data
// sDbl[i]: if stack[i] is DBL_MRK, sDbl[i] holds the number value
int maxFrameArray = idata.itsMaxFrameArray;
if (maxFrameArray != STACK_SHFT + idata.itsMaxStack)
Context.codeBug();
Object[] stack = new Object[maxFrameArray];
double[] sDbl = new double[maxFrameArray];
int stackTop = STACK_SHFT - 1;
int withDepth = 0;
int definedArgs = fnOrScript.argCount;
if (definedArgs > argCount) { definedArgs = argCount; }
for (int i = 0; i != definedArgs; ++i) {
Object arg = args[argShift + i];
stack[VAR_SHFT + i] = arg;
if (arg == DBL_MRK) {
sDbl[VAR_SHFT + i] = argsDbl[argShift + i];
}
}
for (int i = definedArgs; i != maxVars; ++i) {
stack[VAR_SHFT + i] = undefined;
}
DebugFrame debuggerFrame = null;
if (cx.debugger != null) {
debuggerFrame = cx.debugger.getFrame(cx, idata);
}
if (idata.itsFunctionType != 0) {
InterpretedFunction f = (InterpretedFunction)fnOrScript;
if (!f.itsUseDynamicScope) {
scope = fnOrScript.getParentScope();
}
if (idata.itsCheckThis) {
thisObj = ScriptRuntime.getThis(thisObj);
}
if (idata.itsNeedsActivation) {
if (argsDbl != null) {
args = getArgsArray(args, argsDbl, argShift, argCount);
argShift = 0;
argsDbl = null;
}
scope = ScriptRuntime.initVarObj(cx, scope, fnOrScript,
thisObj, args);
}
} else {
scope = ScriptRuntime.initScript(cx, scope, fnOrScript, thisObj,
idata.itsFromEvalCode);
}
if (idata.itsNestedFunctions != null) {
if (idata.itsFunctionType != 0 && !idata.itsNeedsActivation)
Context.codeBug();
for (int i = 0; i < idata.itsNestedFunctions.length; i++) {
InterpreterData fdata = idata.itsNestedFunctions[i];
if (fdata.itsFunctionType == FunctionNode.FUNCTION_STATEMENT) {
createFunction(cx, scope, fdata, idata.itsFromEvalCode);
}
}
}
boolean useActivationVars = false;
if (debuggerFrame != null) {
if (argsDbl != null) {
args = getArgsArray(args, argsDbl, argShift, argCount);
argShift = 0;
argsDbl = null;
}
if (idata.itsFunctionType != 0 && !idata.itsNeedsActivation) {
useActivationVars = true;
scope = ScriptRuntime.initVarObj(cx, scope, fnOrScript,
thisObj, args);
}
debuggerFrame.onEnter(cx, scope, thisObj, args);
}
String savedSourceFile = cx.interpreterSourceFile;
cx.interpreterSourceFile = idata.itsSourceFile;
Object result = undefined;
// If javaException != null on exit, it will be throw instead of
// normal return
Throwable javaException = null;
int exceptionPC = -1;
byte[] iCode = idata.itsICode;
String[] strings = idata.itsStringTable;
int pc = 0;
int pcPrevBranch = pc;
final int instructionThreshold = cx.instructionThreshold;
// During function call this will be set to -1 so catch can properly
// adjust it
int instructionCount = cx.instructionCount;
// arbitrary number to add to instructionCount when calling
// other functions
final int INVOCATION_COST = 100;
Loop: for (;;) {
try {
switch (iCode[pc] & 0xff) {
// Back indent to ease imlementation reading
case Icode_CATCH: {
// The following code should be executed inside try/catch inside main
// loop, not in the loop catch block itself to deal withnexceptions
// from observeInstructionCount. A special bytecode is used only to
// simplify logic.
if (javaException == null) Context.codeBug();
int pcNew = -1;
boolean doCatch = false;
int handlerOffset = getExceptionHandler(idata.itsExceptionTable,
exceptionPC);
if (handlerOffset >= 0) {
final int SCRIPT_CAN_CATCH = 0, ONLY_FINALLY = 1, OTHER = 2;
int exType;
if (javaException instanceof JavaScriptException) {
exType = SCRIPT_CAN_CATCH;
} else if (javaException instanceof EcmaError) {
// an offical ECMA error object,
exType = SCRIPT_CAN_CATCH;
} else if (javaException instanceof WrappedException) {
exType = SCRIPT_CAN_CATCH;
} else if (javaException instanceof RuntimeException) {
exType = ONLY_FINALLY;
} else {
// Error instance
exType = OTHER;
}
if (exType != OTHER) {
// Do not allow for JS to interfere with Error instances
// (exType == OTHER), as they can be used to terminate
// long running script
if (exType == SCRIPT_CAN_CATCH) {
// Allow JS to catch only JavaScriptException and
// EcmaError
pcNew = idata.itsExceptionTable[handlerOffset
+ EXCEPTION_CATCH_SLOT];
if (pcNew >= 0) {
// Has catch block
doCatch = true;
}
}
if (pcNew < 0) {
pcNew = idata.itsExceptionTable[handlerOffset
+ EXCEPTION_FINALLY_SLOT];
}
}
}
if (debuggerFrame != null && !(javaException instanceof Error)) {
debuggerFrame.onExceptionThrown(cx, javaException);
}
if (pcNew < 0) {
break Loop;
}
// We caught an exception
// restore scope at try point
int tryWithDepth = idata.itsExceptionTable[
handlerOffset + EXCEPTION_WITH_DEPTH_SLOT];
while (tryWithDepth != withDepth) {
if (scope == null) Context.codeBug();
scope = ScriptRuntime.leaveWith(scope);
--withDepth;
}
// make stack to contain single exception object
stackTop = STACK_SHFT;
if (doCatch) {
stack[stackTop] = ScriptRuntime.getCatchObject(cx, scope,
javaException);
} else {
// Call finally handler with javaException on stack top to
// distinguish from normal invocation through GOSUB
// which would contain DBL_MRK on the stack
stack[stackTop] = javaException;
}
// clear exception
javaException = null;
// Notify instruction observer if necessary
// and point pc and pcPrevBranch to start of catch/finally block
if (instructionThreshold != 0) {
if (instructionCount > instructionThreshold) {
// Note: this can throw Error
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
}
pcPrevBranch = pc = pcNew;
continue Loop;
}
case Token.THROW: {
Object value = stack[stackTop];
if (value == DBL_MRK) value = doubleWrap(sDbl[stackTop]);
--stackTop;
int sourceLine = getShort(iCode, pc + 1);
javaException = new JavaScriptException(value, idata.itsSourceFile,
sourceLine);
exceptionPC = pc;
if (instructionThreshold != 0) {
instructionCount += pc + 1 - pcPrevBranch;
if (instructionCount > instructionThreshold) {
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
}
pcPrevBranch = pc = getJavaCatchPC(iCode);
continue Loop;
}
case Token.GE : {
--stackTop;
Object rhs = stack[stackTop + 1];
Object lhs = stack[stackTop];
boolean valBln;
if (rhs == DBL_MRK || lhs == DBL_MRK) {
double rDbl = stack_double(stack, sDbl, stackTop + 1);
double lDbl = stack_double(stack, sDbl, stackTop);
valBln = (rDbl == rDbl && lDbl == lDbl && rDbl <= lDbl);
} else {
valBln = (1 == ScriptRuntime.cmp_LE(rhs, lhs));
}
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case Token.LE : {
--stackTop;
Object rhs = stack[stackTop + 1];
Object lhs = stack[stackTop];
boolean valBln;
if (rhs == DBL_MRK || lhs == DBL_MRK) {
double rDbl = stack_double(stack, sDbl, stackTop + 1);
double lDbl = stack_double(stack, sDbl, stackTop);
valBln = (rDbl == rDbl && lDbl == lDbl && lDbl <= rDbl);
} else {
valBln = (1 == ScriptRuntime.cmp_LE(lhs, rhs));
}
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case Token.GT : {
--stackTop;
Object rhs = stack[stackTop + 1];
Object lhs = stack[stackTop];
boolean valBln;
if (rhs == DBL_MRK || lhs == DBL_MRK) {
double rDbl = stack_double(stack, sDbl, stackTop + 1);
double lDbl = stack_double(stack, sDbl, stackTop);
valBln = (rDbl == rDbl && lDbl == lDbl && rDbl < lDbl);
} else {
valBln = (1 == ScriptRuntime.cmp_LT(rhs, lhs));
}
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case Token.LT : {
--stackTop;
Object rhs = stack[stackTop + 1];
Object lhs = stack[stackTop];
boolean valBln;
if (rhs == DBL_MRK || lhs == DBL_MRK) {
double rDbl = stack_double(stack, sDbl, stackTop + 1);
double lDbl = stack_double(stack, sDbl, stackTop);
valBln = (rDbl == rDbl && lDbl == lDbl && lDbl < rDbl);
} else {
valBln = (1 == ScriptRuntime.cmp_LT(lhs, rhs));
}
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case Token.IN : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
boolean valBln = ScriptRuntime.in(lhs, rhs, scope);
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case Token.INSTANCEOF : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
boolean valBln = ScriptRuntime.instanceOf(lhs, rhs, scope);
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case Token.EQ : {
--stackTop;
boolean valBln = do_eq(stack, sDbl, stackTop);
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case Token.NE : {
--stackTop;
boolean valBln = !do_eq(stack, sDbl, stackTop);
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case Token.SHEQ : {
--stackTop;
boolean valBln = do_sheq(stack, sDbl, stackTop);
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case Token.SHNE : {
--stackTop;
boolean valBln = !do_sheq(stack, sDbl, stackTop);
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case Token.IFNE : {
boolean valBln = stack_boolean(stack, sDbl, stackTop);
--stackTop;
if (!valBln) {
if (instructionThreshold != 0) {
instructionCount += pc + 3 - pcPrevBranch;
if (instructionCount > instructionThreshold) {
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
}
pcPrevBranch = pc = getTarget(iCode, pc + 1);
continue Loop;
}
pc += 2;
break;
}
case Token.IFEQ : {
boolean valBln = stack_boolean(stack, sDbl, stackTop);
--stackTop;
if (valBln) {
if (instructionThreshold != 0) {
instructionCount += pc + 3 - pcPrevBranch;
if (instructionCount > instructionThreshold) {
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
}
pcPrevBranch = pc = getTarget(iCode, pc + 1);
continue Loop;
}
pc += 2;
break;
}
case Token.GOTO :
if (instructionThreshold != 0) {
instructionCount += pc + 3 - pcPrevBranch;
if (instructionCount > instructionThreshold) {
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
}
pcPrevBranch = pc = getTarget(iCode, pc + 1);
continue Loop;
case Icode_GOSUB :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = pc + 3;
if (instructionThreshold != 0) {
instructionCount += pc + 3 - pcPrevBranch;
if (instructionCount > instructionThreshold) {
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
}
pcPrevBranch = pc = getTarget(iCode, pc + 1); continue Loop;
case Icode_RETSUB : {
int slot = (iCode[pc + 1] & 0xFF);
if (instructionThreshold != 0) {
instructionCount += pc + 2 - pcPrevBranch;
if (instructionCount > instructionThreshold) {
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
}
int newPC;
Object value = stack[LOCAL_SHFT + slot];
if (value != DBL_MRK) {
// Invocation from exception handler, restore object to rethrow
javaException = (Throwable)value;
exceptionPC = pc;
newPC = getJavaCatchPC(iCode);
} else {
// Normal return from GOSUB
newPC = (int)sDbl[LOCAL_SHFT + slot];
}
pcPrevBranch = pc = newPC;
continue Loop;
}
case Token.POP :
stack[stackTop] = null;
stackTop--;
break;
case Icode_DUP :
stack[stackTop + 1] = stack[stackTop];
sDbl[stackTop + 1] = sDbl[stackTop];
stackTop++;
break;
case Token.POPV :
result = stack[stackTop];
if (result == DBL_MRK) result = doubleWrap(sDbl[stackTop]);
stack[stackTop] = null;
--stackTop;
break;
case Token.RETURN :
result = stack[stackTop];
if (result == DBL_MRK) result = doubleWrap(sDbl[stackTop]);
--stackTop;
break Loop;
case Icode_RETUNDEF :
result = undefined;
break Loop;
case Icode_END:
break Loop;
case Token.BITNOT : {
int rIntValue = stack_int32(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = ~rIntValue;
break;
}
case Token.BITAND : {
int rIntValue = stack_int32(stack, sDbl, stackTop);
--stackTop;
int lIntValue = stack_int32(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lIntValue & rIntValue;
break;
}
case Token.BITOR : {
int rIntValue = stack_int32(stack, sDbl, stackTop);
--stackTop;
int lIntValue = stack_int32(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lIntValue | rIntValue;
break;
}
case Token.BITXOR : {
int rIntValue = stack_int32(stack, sDbl, stackTop);
--stackTop;
int lIntValue = stack_int32(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lIntValue ^ rIntValue;
break;
}
case Token.LSH : {
int rIntValue = stack_int32(stack, sDbl, stackTop);
--stackTop;
int lIntValue = stack_int32(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lIntValue << rIntValue;
break;
}
case Token.RSH : {
int rIntValue = stack_int32(stack, sDbl, stackTop);
--stackTop;
int lIntValue = stack_int32(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lIntValue >> rIntValue;
break;
}
case Token.URSH : {
int rIntValue = stack_int32(stack, sDbl, stackTop) & 0x1F;
--stackTop;
double lDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = ScriptRuntime.toUint32(lDbl) >>> rIntValue;
break;
}
case Token.ADD :
--stackTop;
do_add(stack, sDbl, stackTop);
break;
case Token.SUB : {
double rDbl = stack_double(stack, sDbl, stackTop);
--stackTop;
double lDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lDbl - rDbl;
break;
}
case Token.NEG : {
double rDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = -rDbl;
break;
}
case Token.POS : {
double rDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = rDbl;
break;
}
case Token.MUL : {
double rDbl = stack_double(stack, sDbl, stackTop);
--stackTop;
double lDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lDbl * rDbl;
break;
}
case Token.DIV : {
double rDbl = stack_double(stack, sDbl, stackTop);
--stackTop;
double lDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
// Detect the divide by zero or let Java do it ?
sDbl[stackTop] = lDbl / rDbl;
break;
}
case Token.MOD : {
double rDbl = stack_double(stack, sDbl, stackTop);
--stackTop;
double lDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lDbl % rDbl;
break;
}
case Token.NOT : {
stack[stackTop] = stack_boolean(stack, sDbl, stackTop)
? Boolean.FALSE : Boolean.TRUE;
break;
}
case Token.BINDNAME : {
String name = strings[getIndex(iCode, pc + 1)];
stack[++stackTop] = ScriptRuntime.bind(scope, name);
pc += 2;
break;
}
case Token.GETBASE : {
String name = strings[getIndex(iCode, pc + 1)];
stack[++stackTop] = ScriptRuntime.getBase(scope, name);
pc += 2;
break;
}
case Token.SETNAME : {
String name = strings[getIndex(iCode, pc + 1)];
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
// what about class cast exception here for lhs?
Scriptable lhs = (Scriptable)stack[stackTop];
stack[stackTop] = ScriptRuntime.setName(lhs, rhs, scope, name);
pc += 2;
break;
}
case Token.DELPROP : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.delete(cx, scope, lhs, rhs);
break;
}
case Token.GETPROP : {
String name = (String)stack[stackTop];
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.getProp(lhs, name, scope);
break;
}
case Token.SETPROP : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
String name = (String)stack[stackTop];
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.setProp(lhs, name, rhs, scope);
break;
}
case Token.GETELEM :
do_getElem(cx, stack, sDbl, stackTop, scope);
--stackTop;
break;
case Token.SETELEM :
do_setElem(cx, stack, sDbl, stackTop, scope);
stackTop -= 2;
break;
case Icode_PROPINC : {
String name = (String)stack[stackTop];
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.postIncrement(lhs, name, scope);
break;
}
case Icode_PROPDEC : {
String name = (String)stack[stackTop];
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.postDecrement(lhs, name, scope);
break;
}
case Icode_ELEMINC : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.postIncrementElem(lhs, rhs, scope);
break;
}
case Icode_ELEMDEC : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.postDecrementElem(lhs, rhs, scope);
break;
}
case Token.GETTHIS : {
Scriptable lhs = (Scriptable)stack[stackTop];
stack[stackTop] = ScriptRuntime.getThis(lhs);
break;
}
case Token.NEWTEMP : {
int slot = (iCode[++pc] & 0xFF);
stack[LOCAL_SHFT + slot] = stack[stackTop];
sDbl[LOCAL_SHFT + slot] = sDbl[stackTop];
break;
}
case Token.USETEMP : {
int slot = (iCode[++pc] & 0xFF);
++stackTop;
stack[stackTop] = stack[LOCAL_SHFT + slot];
sDbl[stackTop] = sDbl[LOCAL_SHFT + slot];
break;
}
case Icode_CALLSPECIAL : {
if (instructionThreshold != 0) {
instructionCount += INVOCATION_COST;
cx.instructionCount = instructionCount;
instructionCount = -1;
}
int callType = iCode[pc + 1] & 0xFF;
boolean isNew = (iCode[pc + 2] != 0);
int sourceLine = getShort(iCode, pc + 3);
int count = getIndex(iCode, pc + 5);
stackTop -= count;
Object[] outArgs = getArgsArray(stack, sDbl, stackTop + 1, count);
Object functionThis;
if (isNew) {
functionThis = null;
} else {
functionThis = stack[stackTop];
if (functionThis == DBL_MRK) {
functionThis = doubleWrap(sDbl[stackTop]);
}
--stackTop;
}
Object function = stack[stackTop];
if (function == DBL_MRK) function = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.callSpecial(
cx, function, isNew, functionThis, outArgs,
scope, thisObj, callType,
idata.itsSourceFile, sourceLine);
pc += 6;
instructionCount = cx.instructionCount;
break;
}
case Token.CALL : {
if (instructionThreshold != 0) {
instructionCount += INVOCATION_COST;
cx.instructionCount = instructionCount;
instructionCount = -1;
}
int count = getIndex(iCode, pc + 3);
stackTop -= count;
int calleeArgShft = stackTop + 1;
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
Scriptable calleeScope = scope;
if (idata.itsNeedsActivation) {
calleeScope = ScriptableObject.getTopLevelScope(scope);
}
Scriptable calleeThis;
if (rhs instanceof Scriptable || rhs == null) {
calleeThis = (Scriptable)rhs;
} else {
calleeThis = ScriptRuntime.toObject(cx, calleeScope, rhs);
}
if (lhs instanceof InterpretedFunction) {
// Inlining of InterpretedFunction.call not to create
// argument array
InterpretedFunction f = (InterpretedFunction)lhs;
stack[stackTop] = interpret(cx, calleeScope, calleeThis,
stack, sDbl, calleeArgShft, count,
f, f.itsData);
} else if (lhs instanceof Function) {
Function f = (Function)lhs;
Object[] outArgs = getArgsArray(stack, sDbl, calleeArgShft, count);
stack[stackTop] = f.call(cx, calleeScope, calleeThis, outArgs);
} else {
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
else if (lhs == undefined) {
// special code for better error message for call
// to undefined
lhs = strings[getIndex(iCode, pc + 1)];
if (lhs == null) lhs = undefined;
}
throw NativeGlobal.typeError1
("msg.isnt.function", ScriptRuntime.toString(lhs), calleeScope);
}
pc += 4;
instructionCount = cx.instructionCount;
break;
}
case Token.NEW : {
if (instructionThreshold != 0) {
instructionCount += INVOCATION_COST;
cx.instructionCount = instructionCount;
instructionCount = -1;
}
int count = getIndex(iCode, pc + 3);
stackTop -= count;
int calleeArgShft = stackTop + 1;
Object lhs = stack[stackTop];
if (lhs instanceof InterpretedFunction) {
// Inlining of InterpretedFunction.construct not to create
// argument array
InterpretedFunction f = (InterpretedFunction)lhs;
Scriptable newInstance = f.createObject(cx, scope);
Object callResult = interpret(cx, scope, newInstance,
stack, sDbl, calleeArgShft, count,
f, f.itsData);
if (callResult instanceof Scriptable && callResult != undefined) {
stack[stackTop] = callResult;
} else {
stack[stackTop] = newInstance;
}
} else if (lhs instanceof Function) {
Function f = (Function)lhs;
Object[] outArgs = getArgsArray(stack, sDbl, calleeArgShft, count);
stack[stackTop] = f.construct(cx, scope, outArgs);
} else {
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
else if (lhs == undefined) {
// special code for better error message for call
// to undefined
lhs = strings[getIndex(iCode, pc + 1)];
if (lhs == null) lhs = undefined;
}
throw NativeGlobal.typeError1
("msg.isnt.function", ScriptRuntime.toString(lhs), scope);
}
pc += 4; instructionCount = cx.instructionCount;
break;
}
case Token.TYPEOF : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.typeof(lhs);
break;
}
case Icode_TYPEOFNAME : {
String name = strings[getIndex(iCode, pc + 1)];
stack[++stackTop] = ScriptRuntime.typeofName(scope, name);
pc += 2;
break;
}
case Token.STRING :
stack[++stackTop] = strings[getIndex(iCode, pc + 1)];
pc += 2;
break;
case Icode_SHORTNUMBER :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = getShort(iCode, pc + 1);
pc += 2;
break;
case Icode_INTNUMBER :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = getInt(iCode, pc + 1);
pc += 4;
break;
case Token.NUMBER :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = idata.itsDoubleTable[getIndex(iCode, pc + 1)];
pc += 2;
break;
case Token.NAME : {
String name = strings[getIndex(iCode, pc + 1)];
stack[++stackTop] = ScriptRuntime.name(scope, name);
pc += 2;
break;
}
case Icode_NAMEINC : {
String name = strings[getIndex(iCode, pc + 1)];
stack[++stackTop] = ScriptRuntime.postIncrement(scope, name);
pc += 2;
break;
}
case Icode_NAMEDEC : {
String name = strings[getIndex(iCode, pc + 1)];
stack[++stackTop] = ScriptRuntime.postDecrement(scope, name);
pc += 2;
break;
}
case Token.SETVAR : {
int slot = (iCode[++pc] & 0xFF);
if (!useActivationVars) {
stack[VAR_SHFT + slot] = stack[stackTop];
sDbl[VAR_SHFT + slot] = sDbl[stackTop];
} else {
Object val = stack[stackTop];
if (val == DBL_MRK) val = doubleWrap(sDbl[stackTop]);
activationPut(fnOrScript, scope, slot, val);
}
break;
}
case Token.GETVAR : {
int slot = (iCode[++pc] & 0xFF);
++stackTop;
if (!useActivationVars) {
stack[stackTop] = stack[VAR_SHFT + slot];
sDbl[stackTop] = sDbl[VAR_SHFT + slot];
} else {
stack[stackTop] = activationGet(fnOrScript, scope, slot);
}
break;
}
case Icode_VARINC : {
int slot = (iCode[++pc] & 0xFF);
++stackTop;
if (!useActivationVars) {
stack[stackTop] = stack[VAR_SHFT + slot];
sDbl[stackTop] = sDbl[VAR_SHFT + slot];
stack[VAR_SHFT + slot] = DBL_MRK;
sDbl[VAR_SHFT + slot] = stack_double(stack, sDbl, stackTop) + 1.0;
} else {
Object val = activationGet(fnOrScript, scope, slot);
stack[stackTop] = val;
val = doubleWrap(ScriptRuntime.toNumber(val) + 1.0);
activationPut(fnOrScript, scope, slot, val);
}
break;
}
case Icode_VARDEC : {
int slot = (iCode[++pc] & 0xFF);
++stackTop;
if (!useActivationVars) {
stack[stackTop] = stack[VAR_SHFT + slot];
sDbl[stackTop] = sDbl[VAR_SHFT + slot];
stack[VAR_SHFT + slot] = DBL_MRK;
sDbl[VAR_SHFT + slot] = stack_double(stack, sDbl, stackTop) - 1.0;
} else {
Object val = activationGet(fnOrScript, scope, slot);
stack[stackTop] = val;
val = doubleWrap(ScriptRuntime.toNumber(val) - 1.0);
activationPut(fnOrScript, scope, slot, val);
}
break;
}
case Token.ZERO :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = 0;
break;
case Token.ONE :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = 1;
break;
case Token.NULL :
stack[++stackTop] = null;
break;
case Token.THIS :
stack[++stackTop] = thisObj;
break;
case Token.THISFN :
stack[++stackTop] = fnOrScript;
break;
case Token.FALSE :
stack[++stackTop] = Boolean.FALSE;
break;
case Token.TRUE :
stack[++stackTop] = Boolean.TRUE;
break;
case Token.UNDEFINED :
stack[++stackTop] = Undefined.instance;
break;
case Token.ENTERWITH : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
--stackTop;
scope = ScriptRuntime.enterWith(lhs, scope);
++withDepth;
break;
}
case Token.LEAVEWITH :
scope = ScriptRuntime.leaveWith(scope);
--withDepth;
break;
case Token.NEWSCOPE :
stack[++stackTop] = ScriptRuntime.newScope();
break;
case Token.ENUMINIT : {
int slot = (iCode[++pc] & 0xFF);
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
--stackTop;
stack[LOCAL_SHFT + slot] = ScriptRuntime.initEnum(lhs, scope);
break;
}
case Token.ENUMNEXT : {
int slot = (iCode[++pc] & 0xFF);
Object val = stack[LOCAL_SHFT + slot];
++stackTop;
stack[stackTop] = ScriptRuntime.nextEnum(val);
break;
}
case Icode_GETPROTO : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.getProto(lhs, scope);
break;
}
case Icode_GETPARENT : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.getParent(lhs);
break;
}
case Icode_GETSCOPEPARENT : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.getParent(lhs, scope);
break;
}
case Icode_SETPROTO : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.setProto(lhs, rhs, scope);
break;
}
case Icode_SETPARENT : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.setParent(lhs, rhs, scope);
break;
}
case Icode_SCOPE :
stack[++stackTop] = scope;
break;
case Icode_CLOSURE : {
int i = getIndex(iCode, pc + 1);
InterpreterData closureData = idata.itsNestedFunctions[i];
stack[++stackTop] = createFunction(cx, scope, closureData,
idata.itsFromEvalCode);
pc += 2;
break;
}
case Token.REGEXP : {
int i = getIndex(iCode, pc + 1);
stack[++stackTop] = idata.itsRegExpLiterals[i];
pc += 2;
break;
}
case Icode_LINE : {
int line = getShort(iCode, pc + 1);
cx.interpreterLine = line;
if (debuggerFrame != null) {
debuggerFrame.onLineChange(cx, line);
}
pc += 2;
break;
}
default : {
dumpICode(idata);
throw new RuntimeException
("Unknown icode : "+(iCode[pc] & 0xff)+" @ pc : "+pc);
}
// end of interpreter switch
}
pc++;
}
catch (Throwable ex) {
if (instructionThreshold != 0) {
if (instructionCount < 0) {
// throw during function call
instructionCount = cx.instructionCount;
} else {
// throw during any other operation
instructionCount += pc - pcPrevBranch;
cx.instructionCount = instructionCount;
}
}
javaException = ex;
exceptionPC = pc;
pc = getJavaCatchPC(iCode);
continue Loop;
}
}
cx.interpreterSourceFile = savedSourceFile;
if (debuggerFrame != null) {
if (javaException != null) {
debuggerFrame.onExit(cx, true, javaException);
} else {
debuggerFrame.onExit(cx, false, result);
}
}
if (idata.itsNeedsActivation) {
ScriptRuntime.popActivation(cx);
}
if (instructionThreshold != 0) {
if (instructionCount > instructionThreshold) {
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
cx.instructionCount = instructionCount;
}
if (javaException != null) {
if (javaException instanceof JavaScriptException) {
throw (JavaScriptException)javaException;
} else if (javaException instanceof RuntimeException) {
throw (RuntimeException)javaException;
} else {
// Must be instance of Error or code bug
throw (Error)javaException;
}
}
return result;
}
|
diff --git a/src/main/java/hu/ppke/itk/nlpg/purepos/common/SpecTokenMatcher.java b/src/main/java/hu/ppke/itk/nlpg/purepos/common/SpecTokenMatcher.java
index 8e60b41..768b173 100644
--- a/src/main/java/hu/ppke/itk/nlpg/purepos/common/SpecTokenMatcher.java
+++ b/src/main/java/hu/ppke/itk/nlpg/purepos/common/SpecTokenMatcher.java
@@ -1,68 +1,68 @@
/*******************************************************************************
* Copyright (c) 2012 György Orosz, Attila Novák.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v3
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/
*
* This file is part of PurePos.
*
* PurePos is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* PurePos is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser Public License for more details.
*
* Contributors:
* György Orosz - initial API and implementation
******************************************************************************/
package hu.ppke.itk.nlpg.purepos.common;
import hu.ppke.itk.nlpg.purepos.model.ISpecTokenMatcher;
import java.util.LinkedHashMap;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Class for matching special tokens.
*
* @author György Orosz
*
*/
public class SpecTokenMatcher implements ISpecTokenMatcher {
protected LinkedHashMap<String, Pattern> patterns = new LinkedHashMap<String, Pattern>();
/**
* Initialize patterns from HunPos
*/
public SpecTokenMatcher() {
- addPattern("@CARD", "^[0-9]*$");
+ addPattern("@CARD", "^[0-9]+$");
addPattern("@CARDPUNCT", "^[0-9]+\\.$");
addPattern("@CARDSEPS", "^[0-9\\.,:-]+[0-9]+$");
addPattern("@CARDSUFFIX", "^[0-9]+[a-zA-Z][a-zA-Z]?[a-zA-Z]?$");
addPattern("@HTMLENTITY", "^&[^;]+;?$");
addPattern("@PUNCT", "^\\pP+$");
}
@Override
public String matchLexicalElement(String token) {
for (Entry<String, Pattern> pattern : patterns.entrySet()) {
Matcher m = pattern.getValue().matcher(token);
if (m.matches())
return pattern.getKey();
}
return null;
}
protected void addPattern(String name, String pattern) {
patterns.put(name, Pattern.compile(pattern));
}
}
| true | true | public SpecTokenMatcher() {
addPattern("@CARD", "^[0-9]*$");
addPattern("@CARDPUNCT", "^[0-9]+\\.$");
addPattern("@CARDSEPS", "^[0-9\\.,:-]+[0-9]+$");
addPattern("@CARDSUFFIX", "^[0-9]+[a-zA-Z][a-zA-Z]?[a-zA-Z]?$");
addPattern("@HTMLENTITY", "^&[^;]+;?$");
addPattern("@PUNCT", "^\\pP+$");
}
| public SpecTokenMatcher() {
addPattern("@CARD", "^[0-9]+$");
addPattern("@CARDPUNCT", "^[0-9]+\\.$");
addPattern("@CARDSEPS", "^[0-9\\.,:-]+[0-9]+$");
addPattern("@CARDSUFFIX", "^[0-9]+[a-zA-Z][a-zA-Z]?[a-zA-Z]?$");
addPattern("@HTMLENTITY", "^&[^;]+;?$");
addPattern("@PUNCT", "^\\pP+$");
}
|
diff --git a/ide/eclipse/esb/org.wso2.developerstudio.eclipse.esb/src/org/wso2/developerstudio/eclipse/esb/mediators/impl/SequenceMediatorImpl.java b/ide/eclipse/esb/org.wso2.developerstudio.eclipse.esb/src/org/wso2/developerstudio/eclipse/esb/mediators/impl/SequenceMediatorImpl.java
index d7644a853..c1b20657c 100644
--- a/ide/eclipse/esb/org.wso2.developerstudio.eclipse.esb/src/org/wso2/developerstudio/eclipse/esb/mediators/impl/SequenceMediatorImpl.java
+++ b/ide/eclipse/esb/org.wso2.developerstudio.eclipse.esb/src/org/wso2/developerstudio/eclipse/esb/mediators/impl/SequenceMediatorImpl.java
@@ -1,448 +1,448 @@
/*
* Copyright 2009-2010 WSO2, Inc. (http://wso2.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.developerstudio.eclipse.esb.mediators.impl;
import java.util.List;
import java.util.Map;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.w3c.dom.Element;
import org.wso2.developerstudio.eclipse.esb.NamespacedProperty;
import org.wso2.developerstudio.eclipse.esb.RegistryKeyProperty;
import org.wso2.developerstudio.eclipse.esb.core.utils.ESBMediaTypeConstants;
import org.wso2.developerstudio.eclipse.esb.impl.MediatorImpl;
import org.wso2.developerstudio.eclipse.esb.mediators.KeyType;
import org.wso2.developerstudio.eclipse.esb.mediators.MediatorsPackage;
import org.wso2.developerstudio.eclipse.esb.mediators.SequenceMediator;
import org.wso2.developerstudio.eclipse.esb.util.ObjectValidator;
import org.wso2.developerstudio.eclipse.platform.core.utils.CSProviderConstants;
import org.wso2.developerstudio.eclipse.platform.core.utils.DeveloperStudioProviderUtils;
/**
* <!-- begin-user-doc --> An implementation of the model object '
* <em><b>Sequence Mediator</b></em>'. <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link org.wso2.developerstudio.eclipse.esb.mediators.impl.SequenceMediatorImpl#getReferringSequenceType <em>Referring Sequence Type</em>}</li>
* <li>{@link org.wso2.developerstudio.eclipse.esb.mediators.impl.SequenceMediatorImpl#getDynamicReferenceKey <em>Dynamic Reference Key</em>}</li>
* <li>{@link org.wso2.developerstudio.eclipse.esb.mediators.impl.SequenceMediatorImpl#getStaticReferenceKey <em>Static Reference Key</em>}</li>
* <li>{@link org.wso2.developerstudio.eclipse.esb.mediators.impl.SequenceMediatorImpl#getSequenceKey <em>Sequence Key</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public class SequenceMediatorImpl extends MediatorImpl implements
SequenceMediator {
/**
* The default value of the '{@link #getReferringSequenceType() <em>Referring Sequence Type</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getReferringSequenceType()
* @generated
* @ordered
*/
protected static final KeyType REFERRING_SEQUENCE_TYPE_EDEFAULT = KeyType.STATIC;
/**
* The cached value of the '{@link #getReferringSequenceType() <em>Referring Sequence Type</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getReferringSequenceType()
* @generated
* @ordered
*/
protected KeyType referringSequenceType = REFERRING_SEQUENCE_TYPE_EDEFAULT;
/**
* The cached value of the '{@link #getDynamicReferenceKey() <em>Dynamic Reference Key</em>}' reference.
* <!-- begin-user-doc --> <!--
* end-user-doc -->
* @see #getDynamicReferenceKey()
* @generated
* @ordered
*/
protected NamespacedProperty dynamicReferenceKey;
/**
* The cached value of the '{@link #getStaticReferenceKey() <em>Static Reference Key</em>}' reference.
* <!-- begin-user-doc --> <!--
* end-user-doc -->
* @see #getStaticReferenceKey()
* @generated
* @ordered
*/
protected RegistryKeyProperty staticReferenceKey;
/**
* The cached value of the '{@link #getSequenceKey() <em>Sequence Key</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getSequenceKey()
* @generated
* @ordered
*/
protected RegistryKeyProperty sequenceKey;
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*/
protected SequenceMediatorImpl() {
super();
// Static Reference Key
staticReferenceKey = getEsbFactory().createRegistryKeyProperty();
DeveloperStudioProviderUtils.addFilter(
(Map<String, List<String>>) staticReferenceKey.getFilters(),
CSProviderConstants.FILTER_MEDIA_TYPE,
ESBMediaTypeConstants.MEDIA_TYPE_SEQUENCE);
staticReferenceKey.setPrettyName("Static Reference Key");
staticReferenceKey.setKeyName("key");
staticReferenceKey.setKeyValue(DEFAULT_SEQUENCE_REFERENCE_REGISTRY_KEY);
setStaticReferenceKey(staticReferenceKey);
// Dynamic Reference Key
dynamicReferenceKey = getEsbFactory().createNamespacedProperty();
dynamicReferenceKey.setPropertyName("key");
dynamicReferenceKey.setPropertyValue(DEFAULT_XPATH_PROPERTY_VALUE);
dynamicReferenceKey.setPrettyName("Dynamic Reference Key");
setDynamicReferenceKey(dynamicReferenceKey);
// Sequence key.
sequenceKey = getEsbFactory().createRegistryKeyProperty();
//Set filter properties to filter in only sequences media type
DeveloperStudioProviderUtils.addFilter((Map<String, List<String>>)sequenceKey.getFilters(), CSProviderConstants.FILTER_MEDIA_TYPE, ESBMediaTypeConstants.MEDIA_TYPE_SEQUENCE);
sequenceKey.setPrettyName("Sequence Key");
sequenceKey.setKeyName("key");
sequenceKey.setKeyValue(DEFAULT_SEQUENCE_REFERENCE_REGISTRY_KEY);
setSequenceKey(sequenceKey);
}
/**
* {@inheritDoc}
*/
protected void doLoad(Element self) throws Exception {
switch (getCurrentEsbVersion()) {
case ESB301:
if (self.hasAttribute("key")) {
getSequenceKey().load(self);
} else {
throw new Exception("Expected sequence key.");
}
break;
case ESB400:
if (self.hasAttribute("key")) {
getSequenceKey().load(self);
String referenceKeyValue = self.getAttribute("key");
if (referenceKeyValue == null) {
referenceKeyValue = "";
}
referenceKeyValue = referenceKeyValue.trim();
if (referenceKeyValue.startsWith("{")
&& referenceKeyValue.endsWith("}")) {
setReferringSequenceType(getReferringSequenceType().DYNAMIC);
referenceKeyValue = referenceKeyValue.substring(1,
- referenceKeyValue.length() - 2);
+ referenceKeyValue.length() - 1);
getDynamicReferenceKey()
.setPropertyValue(referenceKeyValue);
} else {
setReferringSequenceType(getReferringSequenceType().STATIC);
getStaticReferenceKey().setKeyValue(referenceKeyValue);
}
} else {
setReferringSequenceType(getReferringSequenceType().STATIC);
// throw new Exception("Expected sequence key.");
}
break;
}
}
/**
* {@inheritDoc}
*/
protected Element doSave(Element parent) throws Exception {
Element self = createChildElement(parent, "sequence");
switch (getCurrentEsbVersion()) {
case ESB301:
getSequenceKey().save(self);
break;
case ESB400:
switch (getReferringSequenceType()) {
case STATIC:
getStaticReferenceKey().save(self);
break;
case DYNAMIC:
self.setAttribute(getDynamicReferenceKey().getPropertyName(),
"{" + getDynamicReferenceKey().getPropertyValue() + "}");
break;
}
break;
}
return self;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
protected EClass eStaticClass() {
return MediatorsPackage.Literals.SEQUENCE_MEDIATOR;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public KeyType getReferringSequenceType() {
return referringSequenceType;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public void setReferringSequenceType(KeyType newReferringSequenceType) {
KeyType oldReferringSequenceType = referringSequenceType;
referringSequenceType = newReferringSequenceType == null ? REFERRING_SEQUENCE_TYPE_EDEFAULT : newReferringSequenceType;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, MediatorsPackage.SEQUENCE_MEDIATOR__REFERRING_SEQUENCE_TYPE, oldReferringSequenceType, referringSequenceType));
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public NamespacedProperty getDynamicReferenceKey() {
if (dynamicReferenceKey != null && dynamicReferenceKey.eIsProxy()) {
InternalEObject oldDynamicReferenceKey = (InternalEObject)dynamicReferenceKey;
dynamicReferenceKey = (NamespacedProperty)eResolveProxy(oldDynamicReferenceKey);
if (dynamicReferenceKey != oldDynamicReferenceKey) {
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE, MediatorsPackage.SEQUENCE_MEDIATOR__DYNAMIC_REFERENCE_KEY, oldDynamicReferenceKey, dynamicReferenceKey));
}
}
return dynamicReferenceKey;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public NamespacedProperty basicGetDynamicReferenceKey() {
return dynamicReferenceKey;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public void setDynamicReferenceKey(NamespacedProperty newDynamicReferenceKey) {
NamespacedProperty oldDynamicReferenceKey = dynamicReferenceKey;
dynamicReferenceKey = newDynamicReferenceKey;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, MediatorsPackage.SEQUENCE_MEDIATOR__DYNAMIC_REFERENCE_KEY, oldDynamicReferenceKey, dynamicReferenceKey));
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public RegistryKeyProperty getStaticReferenceKey() {
if (staticReferenceKey != null && staticReferenceKey.eIsProxy()) {
InternalEObject oldStaticReferenceKey = (InternalEObject)staticReferenceKey;
staticReferenceKey = (RegistryKeyProperty)eResolveProxy(oldStaticReferenceKey);
if (staticReferenceKey != oldStaticReferenceKey) {
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE, MediatorsPackage.SEQUENCE_MEDIATOR__STATIC_REFERENCE_KEY, oldStaticReferenceKey, staticReferenceKey));
}
}
return staticReferenceKey;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public RegistryKeyProperty basicGetStaticReferenceKey() {
return staticReferenceKey;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public void setStaticReferenceKey(RegistryKeyProperty newStaticReferenceKey) {
RegistryKeyProperty oldStaticReferenceKey = staticReferenceKey;
staticReferenceKey = newStaticReferenceKey;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, MediatorsPackage.SEQUENCE_MEDIATOR__STATIC_REFERENCE_KEY, oldStaticReferenceKey, staticReferenceKey));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public RegistryKeyProperty getSequenceKey() {
if (sequenceKey != null && sequenceKey.eIsProxy()) {
InternalEObject oldSequenceKey = (InternalEObject)sequenceKey;
sequenceKey = (RegistryKeyProperty)eResolveProxy(oldSequenceKey);
if (sequenceKey != oldSequenceKey) {
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE, MediatorsPackage.SEQUENCE_MEDIATOR__SEQUENCE_KEY, oldSequenceKey, sequenceKey));
}
}
return sequenceKey;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public RegistryKeyProperty basicGetSequenceKey() {
return sequenceKey;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setSequenceKey(RegistryKeyProperty newSequenceKey) {
RegistryKeyProperty oldSequenceKey = sequenceKey;
sequenceKey = newSequenceKey;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, MediatorsPackage.SEQUENCE_MEDIATOR__SEQUENCE_KEY, oldSequenceKey, sequenceKey));
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case MediatorsPackage.SEQUENCE_MEDIATOR__REFERRING_SEQUENCE_TYPE:
return getReferringSequenceType();
case MediatorsPackage.SEQUENCE_MEDIATOR__DYNAMIC_REFERENCE_KEY:
if (resolve) return getDynamicReferenceKey();
return basicGetDynamicReferenceKey();
case MediatorsPackage.SEQUENCE_MEDIATOR__STATIC_REFERENCE_KEY:
if (resolve) return getStaticReferenceKey();
return basicGetStaticReferenceKey();
case MediatorsPackage.SEQUENCE_MEDIATOR__SEQUENCE_KEY:
if (resolve) return getSequenceKey();
return basicGetSequenceKey();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case MediatorsPackage.SEQUENCE_MEDIATOR__REFERRING_SEQUENCE_TYPE:
setReferringSequenceType((KeyType)newValue);
return;
case MediatorsPackage.SEQUENCE_MEDIATOR__DYNAMIC_REFERENCE_KEY:
setDynamicReferenceKey((NamespacedProperty)newValue);
return;
case MediatorsPackage.SEQUENCE_MEDIATOR__STATIC_REFERENCE_KEY:
setStaticReferenceKey((RegistryKeyProperty)newValue);
return;
case MediatorsPackage.SEQUENCE_MEDIATOR__SEQUENCE_KEY:
setSequenceKey((RegistryKeyProperty)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public void eUnset(int featureID) {
switch (featureID) {
case MediatorsPackage.SEQUENCE_MEDIATOR__REFERRING_SEQUENCE_TYPE:
setReferringSequenceType(REFERRING_SEQUENCE_TYPE_EDEFAULT);
return;
case MediatorsPackage.SEQUENCE_MEDIATOR__DYNAMIC_REFERENCE_KEY:
setDynamicReferenceKey((NamespacedProperty)null);
return;
case MediatorsPackage.SEQUENCE_MEDIATOR__STATIC_REFERENCE_KEY:
setStaticReferenceKey((RegistryKeyProperty)null);
return;
case MediatorsPackage.SEQUENCE_MEDIATOR__SEQUENCE_KEY:
setSequenceKey((RegistryKeyProperty)null);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public boolean eIsSet(int featureID) {
switch (featureID) {
case MediatorsPackage.SEQUENCE_MEDIATOR__REFERRING_SEQUENCE_TYPE:
return referringSequenceType != REFERRING_SEQUENCE_TYPE_EDEFAULT;
case MediatorsPackage.SEQUENCE_MEDIATOR__DYNAMIC_REFERENCE_KEY:
return dynamicReferenceKey != null;
case MediatorsPackage.SEQUENCE_MEDIATOR__STATIC_REFERENCE_KEY:
return staticReferenceKey != null;
case MediatorsPackage.SEQUENCE_MEDIATOR__SEQUENCE_KEY:
return sequenceKey != null;
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public String toString() {
if (eIsProxy()) return super.toString();
StringBuffer result = new StringBuffer(super.toString());
result.append(" (referringSequenceType: ");
result.append(referringSequenceType);
result.append(')');
return result.toString();
}
public Map<String, ObjectValidator> validate() {
// TODO Auto-generated method stub
return null;
}
} // SequenceMediatorImpl
| true | true | protected void doLoad(Element self) throws Exception {
switch (getCurrentEsbVersion()) {
case ESB301:
if (self.hasAttribute("key")) {
getSequenceKey().load(self);
} else {
throw new Exception("Expected sequence key.");
}
break;
case ESB400:
if (self.hasAttribute("key")) {
getSequenceKey().load(self);
String referenceKeyValue = self.getAttribute("key");
if (referenceKeyValue == null) {
referenceKeyValue = "";
}
referenceKeyValue = referenceKeyValue.trim();
if (referenceKeyValue.startsWith("{")
&& referenceKeyValue.endsWith("}")) {
setReferringSequenceType(getReferringSequenceType().DYNAMIC);
referenceKeyValue = referenceKeyValue.substring(1,
referenceKeyValue.length() - 2);
getDynamicReferenceKey()
.setPropertyValue(referenceKeyValue);
} else {
setReferringSequenceType(getReferringSequenceType().STATIC);
getStaticReferenceKey().setKeyValue(referenceKeyValue);
}
} else {
setReferringSequenceType(getReferringSequenceType().STATIC);
// throw new Exception("Expected sequence key.");
}
break;
}
}
| protected void doLoad(Element self) throws Exception {
switch (getCurrentEsbVersion()) {
case ESB301:
if (self.hasAttribute("key")) {
getSequenceKey().load(self);
} else {
throw new Exception("Expected sequence key.");
}
break;
case ESB400:
if (self.hasAttribute("key")) {
getSequenceKey().load(self);
String referenceKeyValue = self.getAttribute("key");
if (referenceKeyValue == null) {
referenceKeyValue = "";
}
referenceKeyValue = referenceKeyValue.trim();
if (referenceKeyValue.startsWith("{")
&& referenceKeyValue.endsWith("}")) {
setReferringSequenceType(getReferringSequenceType().DYNAMIC);
referenceKeyValue = referenceKeyValue.substring(1,
referenceKeyValue.length() - 1);
getDynamicReferenceKey()
.setPropertyValue(referenceKeyValue);
} else {
setReferringSequenceType(getReferringSequenceType().STATIC);
getStaticReferenceKey().setKeyValue(referenceKeyValue);
}
} else {
setReferringSequenceType(getReferringSequenceType().STATIC);
// throw new Exception("Expected sequence key.");
}
break;
}
}
|
diff --git a/nuxeo-platform-ui-web/src/main/java/org/nuxeo/ecm/platform/ui/web/directory/DirectoryEntryOutputRenderer.java b/nuxeo-platform-ui-web/src/main/java/org/nuxeo/ecm/platform/ui/web/directory/DirectoryEntryOutputRenderer.java
index bd718291..0ed97e47 100644
--- a/nuxeo-platform-ui-web/src/main/java/org/nuxeo/ecm/platform/ui/web/directory/DirectoryEntryOutputRenderer.java
+++ b/nuxeo-platform-ui-web/src/main/java/org/nuxeo/ecm/platform/ui/web/directory/DirectoryEntryOutputRenderer.java
@@ -1,122 +1,122 @@
/*
* (C) Copyright 2006-2007 Nuxeo SAS (http://nuxeo.com/) and contributors.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser General Public License
* (LGPL) version 2.1 which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl.html
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* Contributors:
* Nuxeo - initial API and implementation
*
* $Id: DirectoryEntryOutputRenderer.java 29611 2008-01-24 16:51:03Z gracinet $
*/
package org.nuxeo.ecm.platform.ui.web.directory;
import java.util.Locale;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import javax.faces.render.Renderer;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.nuxeo.common.utils.i18n.I18NUtils;
import org.nuxeo.ecm.core.api.ClientException;
import org.nuxeo.ecm.core.api.DocumentModel;
import org.nuxeo.ecm.directory.DirectoryException;
/**
* Renderer for directory entry.
*
* @author <a href="mailto:[email protected]">Anahide Tchertchian</a>
*
*/
public class DirectoryEntryOutputRenderer extends Renderer {
private static final Log log = LogFactory.getLog(DirectoryHelper.class);
@Override
public void encodeBegin(FacesContext context, UIComponent component) {
DirectoryEntryOutputComponent dirComponent = (DirectoryEntryOutputComponent) component;
String entryId = (String) dirComponent.getValue();
if (entryId == null) {
// BBB
entryId = dirComponent.getEntryId();
}
String directoryName = dirComponent.getDirectoryName();
String toWrite = null;
if (directoryName != null) {
// get the entry information
String keySeparator = (String) dirComponent.getAttributes().get(
"keySeparator");
String schema;
try {
schema = DirectoryHelper.getDirectoryService().getDirectorySchema(directoryName);
} catch (DirectoryException de) {
log.error("Unable to get directory schema for " + directoryName, de);
schema = keySeparator != null ? "xvocabulary" : "vocabulary";
}
- if (keySeparator != null) {
+ if (keySeparator != null && entryId != null) {
entryId = entryId.substring(
entryId.lastIndexOf(keySeparator) + 1, entryId.length());
}
DocumentModel entry = DirectoryHelper.getEntry(directoryName,
entryId);
if (entry != null) {
Boolean displayIdAndLabel = dirComponent.getDisplayIdAndLabel();
if (displayIdAndLabel == null) {
displayIdAndLabel = Boolean.FALSE; // unboxed later
}
Boolean translate = dirComponent.getLocalize();
String label;
try {
label = (String) entry.getProperty(schema, "label");
} catch (ClientException e) {
label = null;
}
String display = (String) dirComponent.getAttributes().get(
"display");
if (label == null || "".equals(label)) {
label = entryId;
}
if (Boolean.TRUE.equals(translate)) {
label = translate(context, label);
}
toWrite = display != null ? DirectoryHelper.instance().getOptionValue(
entryId, label, display, displayIdAndLabel, " ")
: label;
}
}
if (toWrite == null) {
// default rendering: the entry id itself
toWrite = entryId;
}
try {
if (toWrite != null) {
ResponseWriter writer = context.getResponseWriter();
writer.writeText(toWrite, null);
writer.flush();
}
} catch (Exception e) {
log.error("IOException trying to write on the response", e);
}
}
protected static String translate(FacesContext context, String label) {
String bundleName = context.getApplication().getMessageBundle();
Locale locale = context.getViewRoot().getLocale();
label = I18NUtils.getMessageString(bundleName, label, null, locale);
return label;
}
}
| true | true | public void encodeBegin(FacesContext context, UIComponent component) {
DirectoryEntryOutputComponent dirComponent = (DirectoryEntryOutputComponent) component;
String entryId = (String) dirComponent.getValue();
if (entryId == null) {
// BBB
entryId = dirComponent.getEntryId();
}
String directoryName = dirComponent.getDirectoryName();
String toWrite = null;
if (directoryName != null) {
// get the entry information
String keySeparator = (String) dirComponent.getAttributes().get(
"keySeparator");
String schema;
try {
schema = DirectoryHelper.getDirectoryService().getDirectorySchema(directoryName);
} catch (DirectoryException de) {
log.error("Unable to get directory schema for " + directoryName, de);
schema = keySeparator != null ? "xvocabulary" : "vocabulary";
}
if (keySeparator != null) {
entryId = entryId.substring(
entryId.lastIndexOf(keySeparator) + 1, entryId.length());
}
DocumentModel entry = DirectoryHelper.getEntry(directoryName,
entryId);
if (entry != null) {
Boolean displayIdAndLabel = dirComponent.getDisplayIdAndLabel();
if (displayIdAndLabel == null) {
displayIdAndLabel = Boolean.FALSE; // unboxed later
}
Boolean translate = dirComponent.getLocalize();
String label;
try {
label = (String) entry.getProperty(schema, "label");
} catch (ClientException e) {
label = null;
}
String display = (String) dirComponent.getAttributes().get(
"display");
if (label == null || "".equals(label)) {
label = entryId;
}
if (Boolean.TRUE.equals(translate)) {
label = translate(context, label);
}
toWrite = display != null ? DirectoryHelper.instance().getOptionValue(
entryId, label, display, displayIdAndLabel, " ")
: label;
}
}
if (toWrite == null) {
// default rendering: the entry id itself
toWrite = entryId;
}
try {
if (toWrite != null) {
ResponseWriter writer = context.getResponseWriter();
writer.writeText(toWrite, null);
writer.flush();
}
} catch (Exception e) {
log.error("IOException trying to write on the response", e);
}
}
| public void encodeBegin(FacesContext context, UIComponent component) {
DirectoryEntryOutputComponent dirComponent = (DirectoryEntryOutputComponent) component;
String entryId = (String) dirComponent.getValue();
if (entryId == null) {
// BBB
entryId = dirComponent.getEntryId();
}
String directoryName = dirComponent.getDirectoryName();
String toWrite = null;
if (directoryName != null) {
// get the entry information
String keySeparator = (String) dirComponent.getAttributes().get(
"keySeparator");
String schema;
try {
schema = DirectoryHelper.getDirectoryService().getDirectorySchema(directoryName);
} catch (DirectoryException de) {
log.error("Unable to get directory schema for " + directoryName, de);
schema = keySeparator != null ? "xvocabulary" : "vocabulary";
}
if (keySeparator != null && entryId != null) {
entryId = entryId.substring(
entryId.lastIndexOf(keySeparator) + 1, entryId.length());
}
DocumentModel entry = DirectoryHelper.getEntry(directoryName,
entryId);
if (entry != null) {
Boolean displayIdAndLabel = dirComponent.getDisplayIdAndLabel();
if (displayIdAndLabel == null) {
displayIdAndLabel = Boolean.FALSE; // unboxed later
}
Boolean translate = dirComponent.getLocalize();
String label;
try {
label = (String) entry.getProperty(schema, "label");
} catch (ClientException e) {
label = null;
}
String display = (String) dirComponent.getAttributes().get(
"display");
if (label == null || "".equals(label)) {
label = entryId;
}
if (Boolean.TRUE.equals(translate)) {
label = translate(context, label);
}
toWrite = display != null ? DirectoryHelper.instance().getOptionValue(
entryId, label, display, displayIdAndLabel, " ")
: label;
}
}
if (toWrite == null) {
// default rendering: the entry id itself
toWrite = entryId;
}
try {
if (toWrite != null) {
ResponseWriter writer = context.getResponseWriter();
writer.writeText(toWrite, null);
writer.flush();
}
} catch (Exception e) {
log.error("IOException trying to write on the response", e);
}
}
|
diff --git a/jsword/java/jswordtest/JSwordAllTests.java b/jsword/java/jswordtest/JSwordAllTests.java
index 67455596..d79d631b 100644
--- a/jsword/java/jswordtest/JSwordAllTests.java
+++ b/jsword/java/jswordtest/JSwordAllTests.java
@@ -1,47 +1,48 @@
// package default;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
public class JSwordAllTests extends TestCase
{
public JSwordAllTests(String s)
{
super(s);
}
public static Test suite()
{
TestSuite suite = new TestSuite();
suite.addTestSuite(org.crosswire.jsword.book.jdbc.TestJDBCBible.class);
suite.addTestSuite(org.crosswire.jsword.book.raw.TestRawBible.class);
suite.addTestSuite(org.crosswire.jsword.book.ser.TestSerBible.class);
suite.addTestSuite(org.crosswire.jsword.book.ser.TestSerBibleDriver.class);
suite.addTestSuite(org.crosswire.jsword.book.TestBibles.class);
suite.addTestSuite(org.crosswire.jsword.book.TestBookMetaData.class);
suite.addTestSuite(org.crosswire.jsword.book.TestBookUtil.class);
suite.addTestSuite(org.crosswire.jsword.book.TestDriverManager.class);
suite.addTestSuite(org.crosswire.jsword.control.dictionary.TestDictionary.class);
suite.addTestSuite(org.crosswire.jsword.control.search.TestCustomTokenizer.class);
suite.addTestSuite(org.crosswire.jsword.control.search.TestEngine.class);
suite.addTestSuite(org.crosswire.jsword.control.search.TestSearchWords.class);
suite.addTestSuite(org.crosswire.jsword.passage.TestBooks.class);
suite.addTestSuite(org.crosswire.jsword.passage.TestPassageConstants.class);
suite.addTestSuite(org.crosswire.jsword.passage.TestPassageMix.class);
suite.addTestSuite(org.crosswire.jsword.passage.TestPassageSize.class);
suite.addTestSuite(org.crosswire.jsword.passage.TestPassageSpeed.class);
- suite.addTestSuite(org.crosswire.jsword.passage.TestPassageSpeedOpt.class);
+ // commented out because it causes OutOfMemoryErrors.
+ //suite.addTestSuite(org.crosswire.jsword.passage.TestPassageSpeedOpt.class);
suite.addTestSuite(org.crosswire.jsword.passage.TestPassageTally.class);
suite.addTestSuite(org.crosswire.jsword.passage.TestPassageTally2.class);
suite.addTestSuite(org.crosswire.jsword.passage.TestPassageUtil.class);
suite.addTestSuite(org.crosswire.jsword.passage.TestPassageWriteSpeed.class);
suite.addTestSuite(org.crosswire.jsword.passage.TestVerse.class);
suite.addTestSuite(org.crosswire.jsword.passage.TestVerseRange.class);
suite.addTestSuite(org.crosswire.jsword.view.style.TestStyle.class);
return suite;
}
}
| true | true | public static Test suite()
{
TestSuite suite = new TestSuite();
suite.addTestSuite(org.crosswire.jsword.book.jdbc.TestJDBCBible.class);
suite.addTestSuite(org.crosswire.jsword.book.raw.TestRawBible.class);
suite.addTestSuite(org.crosswire.jsword.book.ser.TestSerBible.class);
suite.addTestSuite(org.crosswire.jsword.book.ser.TestSerBibleDriver.class);
suite.addTestSuite(org.crosswire.jsword.book.TestBibles.class);
suite.addTestSuite(org.crosswire.jsword.book.TestBookMetaData.class);
suite.addTestSuite(org.crosswire.jsword.book.TestBookUtil.class);
suite.addTestSuite(org.crosswire.jsword.book.TestDriverManager.class);
suite.addTestSuite(org.crosswire.jsword.control.dictionary.TestDictionary.class);
suite.addTestSuite(org.crosswire.jsword.control.search.TestCustomTokenizer.class);
suite.addTestSuite(org.crosswire.jsword.control.search.TestEngine.class);
suite.addTestSuite(org.crosswire.jsword.control.search.TestSearchWords.class);
suite.addTestSuite(org.crosswire.jsword.passage.TestBooks.class);
suite.addTestSuite(org.crosswire.jsword.passage.TestPassageConstants.class);
suite.addTestSuite(org.crosswire.jsword.passage.TestPassageMix.class);
suite.addTestSuite(org.crosswire.jsword.passage.TestPassageSize.class);
suite.addTestSuite(org.crosswire.jsword.passage.TestPassageSpeed.class);
suite.addTestSuite(org.crosswire.jsword.passage.TestPassageSpeedOpt.class);
suite.addTestSuite(org.crosswire.jsword.passage.TestPassageTally.class);
suite.addTestSuite(org.crosswire.jsword.passage.TestPassageTally2.class);
suite.addTestSuite(org.crosswire.jsword.passage.TestPassageUtil.class);
suite.addTestSuite(org.crosswire.jsword.passage.TestPassageWriteSpeed.class);
suite.addTestSuite(org.crosswire.jsword.passage.TestVerse.class);
suite.addTestSuite(org.crosswire.jsword.passage.TestVerseRange.class);
suite.addTestSuite(org.crosswire.jsword.view.style.TestStyle.class);
return suite;
}
| public static Test suite()
{
TestSuite suite = new TestSuite();
suite.addTestSuite(org.crosswire.jsword.book.jdbc.TestJDBCBible.class);
suite.addTestSuite(org.crosswire.jsword.book.raw.TestRawBible.class);
suite.addTestSuite(org.crosswire.jsword.book.ser.TestSerBible.class);
suite.addTestSuite(org.crosswire.jsword.book.ser.TestSerBibleDriver.class);
suite.addTestSuite(org.crosswire.jsword.book.TestBibles.class);
suite.addTestSuite(org.crosswire.jsword.book.TestBookMetaData.class);
suite.addTestSuite(org.crosswire.jsword.book.TestBookUtil.class);
suite.addTestSuite(org.crosswire.jsword.book.TestDriverManager.class);
suite.addTestSuite(org.crosswire.jsword.control.dictionary.TestDictionary.class);
suite.addTestSuite(org.crosswire.jsword.control.search.TestCustomTokenizer.class);
suite.addTestSuite(org.crosswire.jsword.control.search.TestEngine.class);
suite.addTestSuite(org.crosswire.jsword.control.search.TestSearchWords.class);
suite.addTestSuite(org.crosswire.jsword.passage.TestBooks.class);
suite.addTestSuite(org.crosswire.jsword.passage.TestPassageConstants.class);
suite.addTestSuite(org.crosswire.jsword.passage.TestPassageMix.class);
suite.addTestSuite(org.crosswire.jsword.passage.TestPassageSize.class);
suite.addTestSuite(org.crosswire.jsword.passage.TestPassageSpeed.class);
// commented out because it causes OutOfMemoryErrors.
//suite.addTestSuite(org.crosswire.jsword.passage.TestPassageSpeedOpt.class);
suite.addTestSuite(org.crosswire.jsword.passage.TestPassageTally.class);
suite.addTestSuite(org.crosswire.jsword.passage.TestPassageTally2.class);
suite.addTestSuite(org.crosswire.jsword.passage.TestPassageUtil.class);
suite.addTestSuite(org.crosswire.jsword.passage.TestPassageWriteSpeed.class);
suite.addTestSuite(org.crosswire.jsword.passage.TestVerse.class);
suite.addTestSuite(org.crosswire.jsword.passage.TestVerseRange.class);
suite.addTestSuite(org.crosswire.jsword.view.style.TestStyle.class);
return suite;
}
|
diff --git a/basex-core/src/main/java/org/basex/query/expr/Try.java b/basex-core/src/main/java/org/basex/query/expr/Try.java
index b0ab74ea3..883edbbb6 100644
--- a/basex-core/src/main/java/org/basex/query/expr/Try.java
+++ b/basex-core/src/main/java/org/basex/query/expr/Try.java
@@ -1,161 +1,162 @@
package org.basex.query.expr;
import org.basex.query.*;
import org.basex.query.func.*;
import org.basex.query.iter.*;
import org.basex.query.util.*;
import org.basex.query.value.*;
import org.basex.query.value.node.*;
import org.basex.query.var.*;
import org.basex.util.*;
import org.basex.util.hash.*;
/**
* Project specific try/catch expression.
*
* @author BaseX Team 2005-14, BSD License
* @author Christian Gruen
*/
public final class Try extends Single {
/** Catches. */
private final Catch[] ctch;
/**
* Constructor.
* @param ii input info
* @param t try expression
* @param c catch expressions
*/
public Try(final InputInfo ii, final Expr t, final Catch[] c) {
super(ii, t);
ctch = c;
}
@Override
public void checkUp() throws QueryException {
// check if no or all try/catch expressions are updating
final Expr[] tmp = new Expr[ctch.length + 1];
tmp[0] = expr;
for(int c = 0; c < ctch.length; ++c) tmp[c + 1] = ctch[c].expr;
checkAllUp(tmp);
}
@Override
public Expr compile(final QueryContext ctx, final VarScope scp) throws QueryException {
try {
super.compile(ctx, scp);
if(expr.isValue()) return optPre(expr, ctx);
} catch(final QueryException ex) {
if(!ex.isCatchable()) throw ex;
for(final Catch c : ctch) {
if(c.matches(ex)) {
// found a matching clause, compile and inline error message
return optPre(c.compile(ctx, scp).asExpr(ex, ctx, scp), ctx);
}
}
throw ex;
}
for(final Catch c : ctch) c.compile(ctx, scp);
type = expr.type();
for(final Catch c : ctch)
if(!c.expr.isFunction(Function.ERROR)) type = type.union(c.type());
return this;
}
@Override
public Iter iter(final QueryContext ctx) throws QueryException {
return value(ctx).iter();
}
@Override
public Value value(final QueryContext ctx) throws QueryException {
// don't catch errors from error handlers
try {
return ctx.value(expr);
} catch(final QueryException ex) {
if(!ex.isCatchable()) throw ex;
for(final Catch c : ctch) if(c.matches(ex)) return c.value(ctx, ex);
throw ex;
}
}
@Override
public VarUsage count(final Var v) {
return VarUsage.maximum(v, ctch).plus(expr.count(v));
}
@Override
public Expr inline(final QueryContext ctx, final VarScope scp, final Var v, final Expr e)
throws QueryException {
boolean change = false;
try {
final Expr sub = expr.inline(ctx, scp, v, e);
if(sub != null) {
if(sub.isValue()) return optPre(sub, ctx);
expr = sub;
change = true;
}
} catch(final QueryException qe) {
if(!qe.isCatchable()) throw qe;
for(final Catch c : ctch) {
if(c.matches(qe)) {
// found a matching clause, inline variable and error message
- return optPre(c.inline(ctx, scp, v, e).asExpr(qe, ctx, scp), ctx);
+ final Catch ca = c.inline(ctx, scp, v, e);
+ if(ca != null) return optPre(ca.asExpr(qe, ctx, scp), ctx);
}
}
throw qe;
}
for(final Catch c : ctch) change |= c.inline(ctx, scp, v, e) != null;
return change ? this : null;
}
@Override
public Expr copy(final QueryContext ctx, final VarScope scp, final IntObjMap<Var> vs) {
return new Try(info, expr.copy(ctx, scp, vs), Arr.copyAll(ctx, scp, vs, ctch));
}
@Override
public boolean has(final Flag flag) {
for(final Catch c : ctch) if(c.has(flag)) return true;
return super.has(flag);
}
@Override
public boolean removable(final Var v) {
for(final Catch c : ctch) if(!c.removable(v)) return false;
return super.removable(v);
}
@Override
public void plan(final FElem plan) {
addPlan(plan, planElem(), expr, ctch);
}
@Override
public void markTailCalls(final QueryContext ctx) {
for(final Catch c : ctch) c.markTailCalls(ctx);
expr.markTailCalls(ctx);
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("try { " + expr + " }");
for(final Catch c : ctch) sb.append(' ').append(c);
return sb.toString();
}
@Override
public boolean accept(final ASTVisitor visitor) {
return super.accept(visitor) && visitAll(visitor, ctch);
}
@Override
public int exprSize() {
int sz = 1;
for(final Expr e : ctch) sz += e.exprSize();
return sz;
}
}
| true | true | public Expr inline(final QueryContext ctx, final VarScope scp, final Var v, final Expr e)
throws QueryException {
boolean change = false;
try {
final Expr sub = expr.inline(ctx, scp, v, e);
if(sub != null) {
if(sub.isValue()) return optPre(sub, ctx);
expr = sub;
change = true;
}
} catch(final QueryException qe) {
if(!qe.isCatchable()) throw qe;
for(final Catch c : ctch) {
if(c.matches(qe)) {
// found a matching clause, inline variable and error message
return optPre(c.inline(ctx, scp, v, e).asExpr(qe, ctx, scp), ctx);
}
}
throw qe;
}
for(final Catch c : ctch) change |= c.inline(ctx, scp, v, e) != null;
return change ? this : null;
}
| public Expr inline(final QueryContext ctx, final VarScope scp, final Var v, final Expr e)
throws QueryException {
boolean change = false;
try {
final Expr sub = expr.inline(ctx, scp, v, e);
if(sub != null) {
if(sub.isValue()) return optPre(sub, ctx);
expr = sub;
change = true;
}
} catch(final QueryException qe) {
if(!qe.isCatchable()) throw qe;
for(final Catch c : ctch) {
if(c.matches(qe)) {
// found a matching clause, inline variable and error message
final Catch ca = c.inline(ctx, scp, v, e);
if(ca != null) return optPre(ca.asExpr(qe, ctx, scp), ctx);
}
}
throw qe;
}
for(final Catch c : ctch) change |= c.inline(ctx, scp, v, e) != null;
return change ? this : null;
}
|
diff --git a/museumassault/MuseumAssault.java b/museumassault/MuseumAssault.java
index 4363c12..8ccb42e 100644
--- a/museumassault/MuseumAssault.java
+++ b/museumassault/MuseumAssault.java
@@ -1,84 +1,87 @@
package museumassault;
import java.util.Random;
import museumassault.monitor.Corridor;
import museumassault.monitor.Logger;
import museumassault.monitor.Room;
import museumassault.monitor.SharedSite;
/**
* MuseumAssault main class.
*
* @author Andre Cruz <[email protected]>
*/
public class MuseumAssault
{
/**
* Program entry point.
*
* @param args the command line arguments
*/
public static void main(String[] args)
{
// Configurable params
int nrChiefs = 1;
- int nrTeams = 2;
+ int nrTeams = 4;
int nrThievesPerTeam = 3;
int nrRooms = 5;
int maxDistanceBetweenThieves = 1;
+ int maxPositionsInCorridor = 30;
+ int maxPowerPerThief = 5;
+ int maxCanvasInRoom = 50;
String logFileName = "log.txt";
int totalThieves = nrTeams * nrThievesPerTeam;
Random random = new Random();
Logger logger = new Logger(logFileName);
// Initializing the necessary entities
Team[] teams = new Team[nrTeams];
for (int x = 0; x < nrTeams; x++) {
teams[x] = new Team(x + 1, nrThievesPerTeam);
}
Room[] rooms = new Room[nrRooms];
for (int x = 0; x < nrRooms; x++) {
- rooms[x] = new Room(x + 1, random.nextInt(nrRooms - 2 <= 0 ? 1 : nrRooms - 2) + 1, new Corridor((random.nextInt(nrRooms - 2 <= 0 ? 1 : nrRooms - 2) + 1), maxDistanceBetweenThieves, logger), logger);
+ rooms[x] = new Room(x + 1, random.nextInt(maxCanvasInRoom - 1) + 1, new Corridor((random.nextInt(maxPositionsInCorridor - 1) + 1), maxDistanceBetweenThieves, logger), logger);
}
SharedSite site = new SharedSite(rooms, teams, logger, (nrChiefs > 1));
Thief[] thieves = new Thief[totalThieves];
for (int x = 0; x < totalThieves; x++) {
- Thief thief = new Thief(x + 1, random.nextInt(totalThieves - 3) + 1, site);
+ Thief thief = new Thief(x + 1, random.nextInt(maxPowerPerThief - 1) + 1, site);
thieves[x] = thief;
}
Chief[] chiefs = new Chief[nrChiefs];
for (int x = 0; x < nrChiefs; x++) {
Chief chief = new Chief(x + 1, site);
chiefs[x] = chief;
}
// Initialize the logger
logger.initialize(chiefs, thieves, teams);
// Start the threads
for (int x = 0; x < totalThieves; x++) {
thieves[x].start();
}
for (int x = 0; x < nrChiefs; x++) {
chiefs[x].start();
}
// Wait for the chiefs to join
for (int x = 0; x < nrChiefs; x++) {
try {
chiefs[x].join();
} catch (InterruptedException e) {}
}
logger.terminateLog(site.getNrCollectedCanvas());
System.out.println("Program terminated successfully, please check the log file.");
System.exit(0);
}
}
| false | true | public static void main(String[] args)
{
// Configurable params
int nrChiefs = 1;
int nrTeams = 2;
int nrThievesPerTeam = 3;
int nrRooms = 5;
int maxDistanceBetweenThieves = 1;
String logFileName = "log.txt";
int totalThieves = nrTeams * nrThievesPerTeam;
Random random = new Random();
Logger logger = new Logger(logFileName);
// Initializing the necessary entities
Team[] teams = new Team[nrTeams];
for (int x = 0; x < nrTeams; x++) {
teams[x] = new Team(x + 1, nrThievesPerTeam);
}
Room[] rooms = new Room[nrRooms];
for (int x = 0; x < nrRooms; x++) {
rooms[x] = new Room(x + 1, random.nextInt(nrRooms - 2 <= 0 ? 1 : nrRooms - 2) + 1, new Corridor((random.nextInt(nrRooms - 2 <= 0 ? 1 : nrRooms - 2) + 1), maxDistanceBetweenThieves, logger), logger);
}
SharedSite site = new SharedSite(rooms, teams, logger, (nrChiefs > 1));
Thief[] thieves = new Thief[totalThieves];
for (int x = 0; x < totalThieves; x++) {
Thief thief = new Thief(x + 1, random.nextInt(totalThieves - 3) + 1, site);
thieves[x] = thief;
}
Chief[] chiefs = new Chief[nrChiefs];
for (int x = 0; x < nrChiefs; x++) {
Chief chief = new Chief(x + 1, site);
chiefs[x] = chief;
}
// Initialize the logger
logger.initialize(chiefs, thieves, teams);
// Start the threads
for (int x = 0; x < totalThieves; x++) {
thieves[x].start();
}
for (int x = 0; x < nrChiefs; x++) {
chiefs[x].start();
}
// Wait for the chiefs to join
for (int x = 0; x < nrChiefs; x++) {
try {
chiefs[x].join();
} catch (InterruptedException e) {}
}
logger.terminateLog(site.getNrCollectedCanvas());
System.out.println("Program terminated successfully, please check the log file.");
System.exit(0);
}
| public static void main(String[] args)
{
// Configurable params
int nrChiefs = 1;
int nrTeams = 4;
int nrThievesPerTeam = 3;
int nrRooms = 5;
int maxDistanceBetweenThieves = 1;
int maxPositionsInCorridor = 30;
int maxPowerPerThief = 5;
int maxCanvasInRoom = 50;
String logFileName = "log.txt";
int totalThieves = nrTeams * nrThievesPerTeam;
Random random = new Random();
Logger logger = new Logger(logFileName);
// Initializing the necessary entities
Team[] teams = new Team[nrTeams];
for (int x = 0; x < nrTeams; x++) {
teams[x] = new Team(x + 1, nrThievesPerTeam);
}
Room[] rooms = new Room[nrRooms];
for (int x = 0; x < nrRooms; x++) {
rooms[x] = new Room(x + 1, random.nextInt(maxCanvasInRoom - 1) + 1, new Corridor((random.nextInt(maxPositionsInCorridor - 1) + 1), maxDistanceBetweenThieves, logger), logger);
}
SharedSite site = new SharedSite(rooms, teams, logger, (nrChiefs > 1));
Thief[] thieves = new Thief[totalThieves];
for (int x = 0; x < totalThieves; x++) {
Thief thief = new Thief(x + 1, random.nextInt(maxPowerPerThief - 1) + 1, site);
thieves[x] = thief;
}
Chief[] chiefs = new Chief[nrChiefs];
for (int x = 0; x < nrChiefs; x++) {
Chief chief = new Chief(x + 1, site);
chiefs[x] = chief;
}
// Initialize the logger
logger.initialize(chiefs, thieves, teams);
// Start the threads
for (int x = 0; x < totalThieves; x++) {
thieves[x].start();
}
for (int x = 0; x < nrChiefs; x++) {
chiefs[x].start();
}
// Wait for the chiefs to join
for (int x = 0; x < nrChiefs; x++) {
try {
chiefs[x].join();
} catch (InterruptedException e) {}
}
logger.terminateLog(site.getNrCollectedCanvas());
System.out.println("Program terminated successfully, please check the log file.");
System.exit(0);
}
|
diff --git a/src/test/TestCar01.java b/src/test/TestCar01.java
index e84bb71..c18764a 100644
--- a/src/test/TestCar01.java
+++ b/src/test/TestCar01.java
@@ -1,37 +1,37 @@
package test;
import com.github.kenji0717.a3cs.*;
import javax.vecmath.Vector3d;
public class TestCar01 extends RaceCarBase {
public void exec() {
Vector3d loc = getLoc();//現在の車の座標
Vector3d point = getPoint(13.0);//前方13メートルの座標
Vector3d dir = getDirection(13.0);//前方13メートルの方向
point.sub(loc);//車から見たポイントの方向
point.normalize();//長さを1に正規化
Vector3d left = getUnitVecX();//車の左向き方向
Vector3d front = getUnitVecZ();//車の前方方向
boolean noborizaka = point.y>0.1;//10%以上の上り坂
boolean kyuukaabu = front.dot(dir)<0.9;//ポイント方向と車の方向の一致度が0.9以下
double engineForce = 700.0; //エンジン出力
if (noborizaka) engineForce += 200; //上り坂では加速
if (kyuukaabu) engineForce = 300; //急カーブでは減速
double steering = 0.3*point.dot(left); //左にハンドルを切る量
double breakingForce = kyuukaabu?10.0:0.0;//急カーブの時ブレーキ
double drift=0.0; //ドリフトしない。
- setForce(engineForce,steering,breakingForce,drift);
+ setForce(engineForce,steering,breakingForce,drift);//実際にパラメータを設定
//以下デバッグ用のプリント文(必要に応じてコメントを外す)
//if (noborizaka)System.out.println("上り坂");
//if (kyuukaabu)System.out.println("急カーブ");
//System.out.println("Debug: "+getPoint());
//System.out.println("Debug: "+getDirection(10.0));
//System.out.println("Debug: "+getVel());
//System.out.println("Debug: "+getDist());
//System.out.println("-");
}
}
| true | true | public void exec() {
Vector3d loc = getLoc();//現在の車の座標
Vector3d point = getPoint(13.0);//前方13メートルの座標
Vector3d dir = getDirection(13.0);//前方13メートルの方向
point.sub(loc);//車から見たポイントの方向
point.normalize();//長さを1に正規化
Vector3d left = getUnitVecX();//車の左向き方向
Vector3d front = getUnitVecZ();//車の前方方向
boolean noborizaka = point.y>0.1;//10%以上の上り坂
boolean kyuukaabu = front.dot(dir)<0.9;//ポイント方向と車の方向の一致度が0.9以下
double engineForce = 700.0; //エンジン出力
if (noborizaka) engineForce += 200; //上り坂では加速
if (kyuukaabu) engineForce = 300; //急カーブでは減速
double steering = 0.3*point.dot(left); //左にハンドルを切る量
double breakingForce = kyuukaabu?10.0:0.0;//急カーブの時ブレーキ
double drift=0.0; //ドリフトしない。
setForce(engineForce,steering,breakingForce,drift);
//以下デバッグ用のプリント文(必要に応じてコメントを外す)
//if (noborizaka)System.out.println("上り坂");
//if (kyuukaabu)System.out.println("急カーブ");
//System.out.println("Debug: "+getPoint());
//System.out.println("Debug: "+getDirection(10.0));
//System.out.println("Debug: "+getVel());
//System.out.println("Debug: "+getDist());
//System.out.println("-");
}
| public void exec() {
Vector3d loc = getLoc();//現在の車の座標
Vector3d point = getPoint(13.0);//前方13メートルの座標
Vector3d dir = getDirection(13.0);//前方13メートルの方向
point.sub(loc);//車から見たポイントの方向
point.normalize();//長さを1に正規化
Vector3d left = getUnitVecX();//車の左向き方向
Vector3d front = getUnitVecZ();//車の前方方向
boolean noborizaka = point.y>0.1;//10%以上の上り坂
boolean kyuukaabu = front.dot(dir)<0.9;//ポイント方向と車の方向の一致度が0.9以下
double engineForce = 700.0; //エンジン出力
if (noborizaka) engineForce += 200; //上り坂では加速
if (kyuukaabu) engineForce = 300; //急カーブでは減速
double steering = 0.3*point.dot(left); //左にハンドルを切る量
double breakingForce = kyuukaabu?10.0:0.0;//急カーブの時ブレーキ
double drift=0.0; //ドリフトしない。
setForce(engineForce,steering,breakingForce,drift);//実際にパラメータを設定
//以下デバッグ用のプリント文(必要に応じてコメントを外す)
//if (noborizaka)System.out.println("上り坂");
//if (kyuukaabu)System.out.println("急カーブ");
//System.out.println("Debug: "+getPoint());
//System.out.println("Debug: "+getDirection(10.0));
//System.out.println("Debug: "+getVel());
//System.out.println("Debug: "+getDist());
//System.out.println("-");
}
|
diff --git a/src/java/com/idega/content/themes/presentation/ThemesSliderViewer.java b/src/java/com/idega/content/themes/presentation/ThemesSliderViewer.java
index 9ef31fae..434e5c08 100644
--- a/src/java/com/idega/content/themes/presentation/ThemesSliderViewer.java
+++ b/src/java/com/idega/content/themes/presentation/ThemesSliderViewer.java
@@ -1,146 +1,146 @@
package com.idega.content.themes.presentation;
import java.rmi.RemoteException;
import java.util.Arrays;
import com.idega.block.web2.business.Web2Business;
import com.idega.content.business.ContentConstants;
import com.idega.idegaweb.IWBundle;
import com.idega.idegaweb.IWResourceBundle;
import com.idega.presentation.Block;
import com.idega.presentation.IWContext;
import com.idega.presentation.Image;
import com.idega.presentation.Layer;
import com.idega.util.CoreConstants;
import com.idega.util.CoreUtil;
import com.idega.util.PresentationUtil;
import com.idega.util.StringUtil;
import com.idega.util.expression.ELUtil;
public class ThemesSliderViewer extends Block {
private String mainId = "themesSliderContainer";
private String mainStyleClass = "themesSlider";
private boolean hiddenOnLoad = false;
private String initAction;
@Override
public void main(IWContext iwc) {
IWBundle bundle = getBundle(iwc);
IWResourceBundle iwrb = getResourceBundle(iwc);
// Main container
Layer container = new Layer();
container.setId(getMainId());
container.setStyleClass(getMainStyleClass());
if (hiddenOnLoad) {
container.setStyleAttribute("display", "none");
}
// Left scroller
Layer leftScroller = new Layer();
leftScroller.setId("leftScrollerContainer");
leftScroller.setStyleClass("themeScroller");
- leftScroller.add(getScrollImage(bundle.getVirtualPathWithFileNameString("images/left.gif"),
+ leftScroller.add(getScrollImage(bundle.getVirtualPathWithFileNameString("images/left.png"),
iwrb.getLocalizedString("scroll_left", "Scroll to left"), "leftScroller"));
container.add(leftScroller);
// Ticker
Layer tickerContainer = new Layer();
tickerContainer.setId("themesTickerContainer");
tickerContainer.setStyleClass("themesTicker");
Layer ticker = new Layer();
ticker.setId("themes");
ticker.setStyleClass("multiImageGallery");
ticker.setStyleAttribute("left", "0px");
tickerContainer.add(ticker);
container.add(tickerContainer);
// Right scroller
Layer rightScroller = new Layer();
rightScroller.setId("rightScrollerContainer");
rightScroller.setStyleClass("themeScroller rightThemeScroller");
- rightScroller.add(getScrollImage(bundle.getVirtualPathWithFileNameString("images/right.gif"),
+ rightScroller.add(getScrollImage(bundle.getVirtualPathWithFileNameString("images/right.png"),
iwrb.getLocalizedString("scroll_right", "Scroll to right"), "rightScroller"));
container.add(rightScroller);
// Resources
Web2Business web2 = ELUtil.getInstance().getBean(Web2Business.SPRING_BEAN_IDENTIFIER);
try {
PresentationUtil.addJavaScriptSourcesLinesToHeader(iwc, Arrays.asList(
web2.getBundleURIToMootoolsLib(),
web2.getReflectionForMootoolsScriptFilePath(),
web2.getBundleURIToJQueryLib(),
web2.getBundleUriToContextMenuScript(),
CoreConstants.DWR_ENGINE_SCRIPT,
"/dwr/interface/ThemesEngine.js",
bundle.getVirtualPathWithFileNameString("javascript/ThemesHelper-compressed.js"),
bundle.getVirtualPathWithFileNameString("javascript/ThemesManagerHelper-compressed.js"),
bundle.getVirtualPathWithFileNameString("javascript/ThemesSliderHelper-compressed.js")
));
} catch (RemoteException e) {
e.printStackTrace();
}
PresentationUtil.addStyleSheetToHeader(iwc, bundle.getVirtualPathWithFileNameString("style/content.css"));
if (!StringUtil.isEmpty(initAction)) {
String action = getInitAction();
if (!CoreUtil.isSingleComponentRenderingProcess(iwc)) {
action = new StringBuilder("jQuery(window).load(function() {").append(action).append("});").toString();
}
PresentationUtil.addJavaScriptActionToBody(iwc, action);
}
add(container);
}
private Image getScrollImage(String uri, String name, String id) {
Image image = new Image(uri, name);
image.setId(id);
image.setOnClick(new StringBuffer("scroll('").append(image.getId()).append("');").toString());
return image;
}
public String getMainId() {
return mainId;
}
public void setMainId(String mainId) {
this.mainId = mainId;
}
public String getMainStyleClass() {
return mainStyleClass;
}
public void setMainStyleClass(String mainStyleClass) {
this.mainStyleClass = mainStyleClass;
}
public boolean isHiddenOnLoad() {
return hiddenOnLoad;
}
public void setHiddenOnLoad(boolean hiddenOnLoad) {
this.hiddenOnLoad = hiddenOnLoad;
}
public String getInitAction() {
return initAction;
}
public void setInitAction(String initAction) {
this.initAction = initAction;
}
@Override
public String getBundleIdentifier() {
return ContentConstants.IW_BUNDLE_IDENTIFIER;
}
}
| false | true | public void main(IWContext iwc) {
IWBundle bundle = getBundle(iwc);
IWResourceBundle iwrb = getResourceBundle(iwc);
// Main container
Layer container = new Layer();
container.setId(getMainId());
container.setStyleClass(getMainStyleClass());
if (hiddenOnLoad) {
container.setStyleAttribute("display", "none");
}
// Left scroller
Layer leftScroller = new Layer();
leftScroller.setId("leftScrollerContainer");
leftScroller.setStyleClass("themeScroller");
leftScroller.add(getScrollImage(bundle.getVirtualPathWithFileNameString("images/left.gif"),
iwrb.getLocalizedString("scroll_left", "Scroll to left"), "leftScroller"));
container.add(leftScroller);
// Ticker
Layer tickerContainer = new Layer();
tickerContainer.setId("themesTickerContainer");
tickerContainer.setStyleClass("themesTicker");
Layer ticker = new Layer();
ticker.setId("themes");
ticker.setStyleClass("multiImageGallery");
ticker.setStyleAttribute("left", "0px");
tickerContainer.add(ticker);
container.add(tickerContainer);
// Right scroller
Layer rightScroller = new Layer();
rightScroller.setId("rightScrollerContainer");
rightScroller.setStyleClass("themeScroller rightThemeScroller");
rightScroller.add(getScrollImage(bundle.getVirtualPathWithFileNameString("images/right.gif"),
iwrb.getLocalizedString("scroll_right", "Scroll to right"), "rightScroller"));
container.add(rightScroller);
// Resources
Web2Business web2 = ELUtil.getInstance().getBean(Web2Business.SPRING_BEAN_IDENTIFIER);
try {
PresentationUtil.addJavaScriptSourcesLinesToHeader(iwc, Arrays.asList(
web2.getBundleURIToMootoolsLib(),
web2.getReflectionForMootoolsScriptFilePath(),
web2.getBundleURIToJQueryLib(),
web2.getBundleUriToContextMenuScript(),
CoreConstants.DWR_ENGINE_SCRIPT,
"/dwr/interface/ThemesEngine.js",
bundle.getVirtualPathWithFileNameString("javascript/ThemesHelper-compressed.js"),
bundle.getVirtualPathWithFileNameString("javascript/ThemesManagerHelper-compressed.js"),
bundle.getVirtualPathWithFileNameString("javascript/ThemesSliderHelper-compressed.js")
));
} catch (RemoteException e) {
e.printStackTrace();
}
PresentationUtil.addStyleSheetToHeader(iwc, bundle.getVirtualPathWithFileNameString("style/content.css"));
if (!StringUtil.isEmpty(initAction)) {
String action = getInitAction();
if (!CoreUtil.isSingleComponentRenderingProcess(iwc)) {
action = new StringBuilder("jQuery(window).load(function() {").append(action).append("});").toString();
}
PresentationUtil.addJavaScriptActionToBody(iwc, action);
}
add(container);
}
| public void main(IWContext iwc) {
IWBundle bundle = getBundle(iwc);
IWResourceBundle iwrb = getResourceBundle(iwc);
// Main container
Layer container = new Layer();
container.setId(getMainId());
container.setStyleClass(getMainStyleClass());
if (hiddenOnLoad) {
container.setStyleAttribute("display", "none");
}
// Left scroller
Layer leftScroller = new Layer();
leftScroller.setId("leftScrollerContainer");
leftScroller.setStyleClass("themeScroller");
leftScroller.add(getScrollImage(bundle.getVirtualPathWithFileNameString("images/left.png"),
iwrb.getLocalizedString("scroll_left", "Scroll to left"), "leftScroller"));
container.add(leftScroller);
// Ticker
Layer tickerContainer = new Layer();
tickerContainer.setId("themesTickerContainer");
tickerContainer.setStyleClass("themesTicker");
Layer ticker = new Layer();
ticker.setId("themes");
ticker.setStyleClass("multiImageGallery");
ticker.setStyleAttribute("left", "0px");
tickerContainer.add(ticker);
container.add(tickerContainer);
// Right scroller
Layer rightScroller = new Layer();
rightScroller.setId("rightScrollerContainer");
rightScroller.setStyleClass("themeScroller rightThemeScroller");
rightScroller.add(getScrollImage(bundle.getVirtualPathWithFileNameString("images/right.png"),
iwrb.getLocalizedString("scroll_right", "Scroll to right"), "rightScroller"));
container.add(rightScroller);
// Resources
Web2Business web2 = ELUtil.getInstance().getBean(Web2Business.SPRING_BEAN_IDENTIFIER);
try {
PresentationUtil.addJavaScriptSourcesLinesToHeader(iwc, Arrays.asList(
web2.getBundleURIToMootoolsLib(),
web2.getReflectionForMootoolsScriptFilePath(),
web2.getBundleURIToJQueryLib(),
web2.getBundleUriToContextMenuScript(),
CoreConstants.DWR_ENGINE_SCRIPT,
"/dwr/interface/ThemesEngine.js",
bundle.getVirtualPathWithFileNameString("javascript/ThemesHelper-compressed.js"),
bundle.getVirtualPathWithFileNameString("javascript/ThemesManagerHelper-compressed.js"),
bundle.getVirtualPathWithFileNameString("javascript/ThemesSliderHelper-compressed.js")
));
} catch (RemoteException e) {
e.printStackTrace();
}
PresentationUtil.addStyleSheetToHeader(iwc, bundle.getVirtualPathWithFileNameString("style/content.css"));
if (!StringUtil.isEmpty(initAction)) {
String action = getInitAction();
if (!CoreUtil.isSingleComponentRenderingProcess(iwc)) {
action = new StringBuilder("jQuery(window).load(function() {").append(action).append("});").toString();
}
PresentationUtil.addJavaScriptActionToBody(iwc, action);
}
add(container);
}
|
diff --git a/TheHolyFlint/src/me/reddy360/theholyflint/listeners/WorldListener.java b/TheHolyFlint/src/me/reddy360/theholyflint/listeners/WorldListener.java
index 01117cf..bd696bd 100644
--- a/TheHolyFlint/src/me/reddy360/theholyflint/listeners/WorldListener.java
+++ b/TheHolyFlint/src/me/reddy360/theholyflint/listeners/WorldListener.java
@@ -1,166 +1,162 @@
package me.reddy360.theholyflint.listeners;
import me.reddy360.theholyflint.PluginMain;
import net.minecraft.server.v1_4_6.Block;
import net.minecraft.server.v1_4_6.Item;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.block.Chest;
import org.bukkit.block.Dispenser;
import org.bukkit.block.Sign;
import org.bukkit.entity.ItemFrame;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockDispenseEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.block.SignChangeEvent;
import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.event.player.PlayerInteractEntityEvent;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.weather.WeatherChangeEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import org.bukkit.util.Vector;
public class WorldListener implements Listener {
PluginMain pluginMain;
public WorldListener(PluginMain pluginMain) {
this.pluginMain = pluginMain;
}
@EventHandler
public void onBlockBreak(BlockBreakEvent e){
Player player = e.getPlayer();
if(e.isCancelled()){
return;
}
if(!player.hasPermission(pluginMain.pluginManager.getPermission("thf.world.modify"))){
player.sendMessage(ChatColor.DARK_RED + "You don't have permission to break blocks!");
e.setCancelled(true);
}
}
@EventHandler
public void onBlockPlace(BlockPlaceEvent e){
Player player = e.getPlayer();
if(e.isCancelled()){
return;
}
if(!player.hasPermission(pluginMain.pluginManager.getPermission("thf.world.modify"))){
player.sendMessage(ChatColor.DARK_RED + "You don't have permission to place blocks!");
e.setCancelled(true);
}
}
@EventHandler
public void onBlockDispense(BlockDispenseEvent e){
if(e.isCancelled()){
return;
}
Dispenser dispenser = (Dispenser) e.getBlock().getState();
dispenser.getInventory().addItem(e.getItem());
}
@EventHandler
public void onWeatherChange(WeatherChangeEvent e){
if(e.toWeatherState()){
e.setCancelled(true);
}
}
@EventHandler
public void onSignChange(SignChangeEvent e){
for(int x = 0; x < 4; x++){
e.setLine(x, ChatColor.translateAlternateColorCodes('&', e.getLine(x)));
}
}
@EventHandler
public void onEntityInteract(PlayerInteractEntityEvent e){
Player player = e.getPlayer();
if(e.getRightClicked() instanceof ItemFrame){
if(player.hasPermission(pluginMain.pluginManager.getPermission("thf.world.modify"))){
}
}
}
@EventHandler
public void onItemDrop(PlayerDropItemEvent e){
Player player = e.getPlayer();
if(player.hasPermission(pluginMain.pluginManager.getPermission("thf.drop"))){
if(e.getItemDrop().getItemStack().getTypeId() != Item.FLINT.id){
player.sendMessage(ChatColor.DARK_RED + "You can only drop Flint!");
e.setCancelled(true);
}
}else if(player.hasPermission(pluginMain.pluginManager.getPermission("thf.drop.destroy"))){
if(e.getItemDrop().getItemStack().getTypeId() != Item.FLINT.id){
player.sendMessage(ChatColor.DARK_RED + "You can only drop Flint!");
e.setCancelled(true);
e.getItemDrop().setItemStack(new ItemStack(0, 0));
}
}else{
e.setCancelled(true);
}
}
@EventHandler
public void onPlayerMove(PlayerMoveEvent e){
Player player = e.getPlayer();
if(e.getFrom().getBlock().getLocation().equals(e.getTo().getBlock().getLocation())){
return;
}
Location location = e.getTo();
location.setY(location.getY() - 2);
if(location.getBlock().getState() instanceof Sign){
Sign sign = (Sign) location.getBlock().getState();
if(sign.getLine(1).equalsIgnoreCase("[THF]")){
doSignEvent(sign.getLine(2), player, location);
}
}
}
private void doSignEvent(String line, Player player, Location signLocation) {
if(line.startsWith("Launch:")){
if(line.split(":").length == 1){
return;
}
player.getWorld().createExplosion(player.getLocation(), 0F);
Location location = player.getLocation().clone();
location.setPitch(-90);
Vector direction = location.getDirection();
try{
player.setVelocity(direction.multiply(Float.parseFloat(line.split(":")[1])));
// player.addPotionEffect(new PotionEffect(PotionEffectType.DAMAGE_RESISTANCE, Integer.parseInt(line.split(":")[1]) * 2 * 20, 5)
// , true);
- player.setFallDistance(Float.parseFloat(line.split(":")[1]) - (Float.parseFloat(line.split(":")[1]) * 2));
}catch(NumberFormatException e){
}
- }else if(line.startsWith("Chest:")){
- if(line.split(":").length == 1){
- return;
- }
+ }else if(line.equalsIgnoreCase("Chest")){
Location location = signLocation;
location.setY(location.getY() - 1);
if(location.getBlock().getTypeId() == Block.CHEST.id){
Chest chest = (Chest) location.getBlock().getState();
player.getInventory().setContents(chest.getBlockInventory().getContents());
}
}else if(line.startsWith("Potion:")){
if(line.split(":").length < 4){
return;
}
String[] lines = line.split(":");
player.addPotionEffect(new PotionEffect(PotionEffectType.getById(Integer.parseInt(lines[1])), Integer.parseInt(lines[2]), Integer.parseInt(lines[3]), true));
}
}
}
| false | true | private void doSignEvent(String line, Player player, Location signLocation) {
if(line.startsWith("Launch:")){
if(line.split(":").length == 1){
return;
}
player.getWorld().createExplosion(player.getLocation(), 0F);
Location location = player.getLocation().clone();
location.setPitch(-90);
Vector direction = location.getDirection();
try{
player.setVelocity(direction.multiply(Float.parseFloat(line.split(":")[1])));
// player.addPotionEffect(new PotionEffect(PotionEffectType.DAMAGE_RESISTANCE, Integer.parseInt(line.split(":")[1]) * 2 * 20, 5)
// , true);
player.setFallDistance(Float.parseFloat(line.split(":")[1]) - (Float.parseFloat(line.split(":")[1]) * 2));
}catch(NumberFormatException e){
}
}else if(line.startsWith("Chest:")){
if(line.split(":").length == 1){
return;
}
Location location = signLocation;
location.setY(location.getY() - 1);
if(location.getBlock().getTypeId() == Block.CHEST.id){
Chest chest = (Chest) location.getBlock().getState();
player.getInventory().setContents(chest.getBlockInventory().getContents());
}
}else if(line.startsWith("Potion:")){
if(line.split(":").length < 4){
return;
}
String[] lines = line.split(":");
player.addPotionEffect(new PotionEffect(PotionEffectType.getById(Integer.parseInt(lines[1])), Integer.parseInt(lines[2]), Integer.parseInt(lines[3]), true));
}
}
| private void doSignEvent(String line, Player player, Location signLocation) {
if(line.startsWith("Launch:")){
if(line.split(":").length == 1){
return;
}
player.getWorld().createExplosion(player.getLocation(), 0F);
Location location = player.getLocation().clone();
location.setPitch(-90);
Vector direction = location.getDirection();
try{
player.setVelocity(direction.multiply(Float.parseFloat(line.split(":")[1])));
// player.addPotionEffect(new PotionEffect(PotionEffectType.DAMAGE_RESISTANCE, Integer.parseInt(line.split(":")[1]) * 2 * 20, 5)
// , true);
}catch(NumberFormatException e){
}
}else if(line.equalsIgnoreCase("Chest")){
Location location = signLocation;
location.setY(location.getY() - 1);
if(location.getBlock().getTypeId() == Block.CHEST.id){
Chest chest = (Chest) location.getBlock().getState();
player.getInventory().setContents(chest.getBlockInventory().getContents());
}
}else if(line.startsWith("Potion:")){
if(line.split(":").length < 4){
return;
}
String[] lines = line.split(":");
player.addPotionEffect(new PotionEffect(PotionEffectType.getById(Integer.parseInt(lines[1])), Integer.parseInt(lines[2]), Integer.parseInt(lines[3]), true));
}
}
|
diff --git a/com.versionone.taskview/src/com/versionone/taskview/views/ProjectSelectDialog.java b/com.versionone.taskview/src/com/versionone/taskview/views/ProjectSelectDialog.java
index 6d68122..5c1fcfa 100644
--- a/com.versionone.taskview/src/com/versionone/taskview/views/ProjectSelectDialog.java
+++ b/com.versionone.taskview/src/com/versionone/taskview/views/ProjectSelectDialog.java
@@ -1,153 +1,155 @@
package com.versionone.taskview.views;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
import org.eclipse.ui.PlatformUI;
import com.versionone.common.sdk.IProjectTreeNode;
import com.versionone.common.preferences.PreferenceConstants;
import com.versionone.common.preferences.PreferencePage;
/**
* Dialog box used to select projects.
* Pressing Okay updates the PreferenceStore with the selected item.
* @author Jerry D. Odenwelder Jr.
*
*/
public class ProjectSelectDialog extends Dialog implements SelectionListener {
private Tree projectTree = null;
private IProjectTreeNode _rootNode;
private IProjectTreeNode _selectedProjectTreeNode;
private TreeItem _selectedTreeItem;
static int WINDOW_HEIGHT = 200;
static int WINDOW_WIDTH = 200;
/**
* Create
* @param parentShell - @see Dialog
* @param rootNode - root node of tree to display
* @param defaultSelected - node of project to select by default, if null, the root is selected
*/
public ProjectSelectDialog(Shell parentShell, IProjectTreeNode rootNode, IProjectTreeNode defaultSelected) {
super(parentShell);
setShellStyle(this.getShellStyle() | SWT.RESIZE);
_rootNode = rootNode;
_selectedProjectTreeNode = defaultSelected;
if(null == _selectedProjectTreeNode)
_selectedProjectTreeNode = _rootNode;
}
/**
* Get the project selected by the user
* @return
*/
public IProjectTreeNode getSelectedProject() {
return _selectedProjectTreeNode;
}
/**
* {@link #createDialogArea(Composite)}
*/
@Override
protected Control createDialogArea(Composite parent) {
Composite container = (Composite) super.createDialogArea(parent);
container.setLayout(new FillLayout(SWT.VERTICAL));
projectTree = new Tree(container, SWT.SINGLE);
projectTree.addSelectionListener(this);
populateTree();
return container;
}
/**
* {@link #configureShell(Shell)}
*/
@Override
protected void configureShell(Shell newShell) {
super.configureShell(newShell);
newShell.setText("Project Selection");
Display display = PlatformUI.getWorkbench().getDisplay();
Point size = newShell.computeSize(WINDOW_WIDTH, WINDOW_HEIGHT);
Rectangle screen = display.getMonitors()[0].getBounds();
newShell.setBounds((screen.width-size.x)/2, (screen.height-size.y)/2, size.x, size.y);
newShell.setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
}
/**
* Populate the Tree control with IProjectTreeNode data
*/
private void populateTree() {
if(_rootNode.hasChildren()) {
IProjectTreeNode[] rootNodes = _rootNode.getChildren();
for(int i=0; i<rootNodes.length;++i) {
final TreeItem treeItem = new TreeItem(this.projectTree, SWT.NONE, i);
treeItem.setText(rootNodes[i].getName());
treeItem.setData(rootNodes[i]);
treeItem.setExpanded(true);
IProjectTreeNode[] children = rootNodes[i].getChildren();
for(int childIndex = 0; childIndex < children.length; ++childIndex) {
populateTree(treeItem, children[childIndex], childIndex);
}
}
- if(null == _selectedTreeItem)
+ if(null == _selectedTreeItem) {
_selectedTreeItem = projectTree.getItem(0);
+ _selectedProjectTreeNode = (IProjectTreeNode) _selectedTreeItem.getData();
+ }
projectTree.setSelection(_selectedTreeItem);
}
}
/**
* Populate child tree nodes with IProjectTreeNode data
* @param tree - parent node for children
* @param node - IProjectTreeNode data for this node
* @param index - index for this TreeItem in the parent node
*/
private void populateTree(TreeItem tree, IProjectTreeNode node, int index) {
final TreeItem treeItem = new TreeItem(tree, SWT.NONE, index);
if(_selectedProjectTreeNode.equals(node)) {
_selectedTreeItem = treeItem;
}
treeItem.setText(node.getName());
treeItem.setData(node);
if(node.hasChildren()) {
IProjectTreeNode[] children = node.getChildren();
for(int i=0; i<children.length;++i) {
populateTree(treeItem, children[i], i);
}
}
treeItem.setExpanded(true);
}
/**
* {@link #widgetDefaultSelected(SelectionEvent)}
*/
public void widgetDefaultSelected(SelectionEvent e) {
}
/**
* {@link #widgetSelected(SelectionEvent)}
*/
public void widgetSelected(SelectionEvent e) {
this._selectedProjectTreeNode = (IProjectTreeNode) ((TreeItem) e.item).getData();;
}
/**
* {@link #okPressed()}
*/
@Override
protected void okPressed() {
super.okPressed();
PreferencePage.getPreferences().setValue(PreferenceConstants.P_PROJECT_TOKEN, _selectedProjectTreeNode.getToken());
}
}
| false | true | private void populateTree() {
if(_rootNode.hasChildren()) {
IProjectTreeNode[] rootNodes = _rootNode.getChildren();
for(int i=0; i<rootNodes.length;++i) {
final TreeItem treeItem = new TreeItem(this.projectTree, SWT.NONE, i);
treeItem.setText(rootNodes[i].getName());
treeItem.setData(rootNodes[i]);
treeItem.setExpanded(true);
IProjectTreeNode[] children = rootNodes[i].getChildren();
for(int childIndex = 0; childIndex < children.length; ++childIndex) {
populateTree(treeItem, children[childIndex], childIndex);
}
}
if(null == _selectedTreeItem)
_selectedTreeItem = projectTree.getItem(0);
projectTree.setSelection(_selectedTreeItem);
}
}
| private void populateTree() {
if(_rootNode.hasChildren()) {
IProjectTreeNode[] rootNodes = _rootNode.getChildren();
for(int i=0; i<rootNodes.length;++i) {
final TreeItem treeItem = new TreeItem(this.projectTree, SWT.NONE, i);
treeItem.setText(rootNodes[i].getName());
treeItem.setData(rootNodes[i]);
treeItem.setExpanded(true);
IProjectTreeNode[] children = rootNodes[i].getChildren();
for(int childIndex = 0; childIndex < children.length; ++childIndex) {
populateTree(treeItem, children[childIndex], childIndex);
}
}
if(null == _selectedTreeItem) {
_selectedTreeItem = projectTree.getItem(0);
_selectedProjectTreeNode = (IProjectTreeNode) _selectedTreeItem.getData();
}
projectTree.setSelection(_selectedTreeItem);
}
}
|
diff --git a/src/hdfs/org/apache/hadoop/hdfs/server/namenode/GetImageServlet.java b/src/hdfs/org/apache/hadoop/hdfs/server/namenode/GetImageServlet.java
index b92e0d0..dda31d1 100644
--- a/src/hdfs/org/apache/hadoop/hdfs/server/namenode/GetImageServlet.java
+++ b/src/hdfs/org/apache/hadoop/hdfs/server/namenode/GetImageServlet.java
@@ -1,74 +1,81 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hdfs.server.namenode;
import java.util.*;
import java.io.*;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.hadoop.util.StringUtils;
/**
* This class is used in Namesystem's jetty to retrieve a file.
* Typically used by the Secondary NameNode to retrieve image and
* edit file for periodic checkpointing.
*/
public class GetImageServlet extends HttpServlet {
private static final long serialVersionUID = -7669068179452648952L;
@SuppressWarnings("unchecked")
public void doGet(HttpServletRequest request,
HttpServletResponse response
) throws ServletException, IOException {
Map<String,String[]> pmap = request.getParameterMap();
try {
ServletContext context = getServletContext();
FSImage nnImage = (FSImage)context.getAttribute("name.system.image");
TransferFsImage ff = new TransferFsImage(pmap, request, response);
if (ff.getImage()) {
response.setHeader(TransferFsImage.CONTENT_LENGTH,
String.valueOf(nnImage.getFsImageName().length()));
// send fsImage
TransferFsImage.getFileServer(response.getOutputStream(),
nnImage.getFsImageName());
} else if (ff.getEdit()) {
response.setHeader(TransferFsImage.CONTENT_LENGTH,
String.valueOf(nnImage.getFsEditName().length()));
// send edits
TransferFsImage.getFileServer(response.getOutputStream(),
nnImage.getFsEditName());
} else if (ff.putImage()) {
- // issue a HTTP get request to download the new fsimage
+ // issue a HTTP get request to download the new fsimage
+ long filesize = 0;
+ for (int a = 0; a < nnImage.getFsImageNameCheckpoint().length; a++) {
+ File file = nnImage.getFsImageNameCheckpoint()[a];
+ filesize += file.length();
+ }
+ response.setHeader(TransferFsImage.CONTENT_LENGTH,
+ String.valueOf(filesize));
nnImage.validateCheckpointUpload(ff.getToken());
TransferFsImage.getFileClient(ff.getInfoServer(), "getimage=1",
nnImage.getFsImageNameCheckpoint());
nnImage.checkpointUploadDone();
}
} catch (Exception ie) {
String errMsg = "GetImage failed. " + StringUtils.stringifyException(ie);
response.sendError(HttpServletResponse.SC_GONE, errMsg);
throw new IOException(errMsg);
} finally {
response.getOutputStream().close();
}
}
}
| true | true | public void doGet(HttpServletRequest request,
HttpServletResponse response
) throws ServletException, IOException {
Map<String,String[]> pmap = request.getParameterMap();
try {
ServletContext context = getServletContext();
FSImage nnImage = (FSImage)context.getAttribute("name.system.image");
TransferFsImage ff = new TransferFsImage(pmap, request, response);
if (ff.getImage()) {
response.setHeader(TransferFsImage.CONTENT_LENGTH,
String.valueOf(nnImage.getFsImageName().length()));
// send fsImage
TransferFsImage.getFileServer(response.getOutputStream(),
nnImage.getFsImageName());
} else if (ff.getEdit()) {
response.setHeader(TransferFsImage.CONTENT_LENGTH,
String.valueOf(nnImage.getFsEditName().length()));
// send edits
TransferFsImage.getFileServer(response.getOutputStream(),
nnImage.getFsEditName());
} else if (ff.putImage()) {
// issue a HTTP get request to download the new fsimage
nnImage.validateCheckpointUpload(ff.getToken());
TransferFsImage.getFileClient(ff.getInfoServer(), "getimage=1",
nnImage.getFsImageNameCheckpoint());
nnImage.checkpointUploadDone();
}
} catch (Exception ie) {
String errMsg = "GetImage failed. " + StringUtils.stringifyException(ie);
response.sendError(HttpServletResponse.SC_GONE, errMsg);
throw new IOException(errMsg);
} finally {
response.getOutputStream().close();
}
}
| public void doGet(HttpServletRequest request,
HttpServletResponse response
) throws ServletException, IOException {
Map<String,String[]> pmap = request.getParameterMap();
try {
ServletContext context = getServletContext();
FSImage nnImage = (FSImage)context.getAttribute("name.system.image");
TransferFsImage ff = new TransferFsImage(pmap, request, response);
if (ff.getImage()) {
response.setHeader(TransferFsImage.CONTENT_LENGTH,
String.valueOf(nnImage.getFsImageName().length()));
// send fsImage
TransferFsImage.getFileServer(response.getOutputStream(),
nnImage.getFsImageName());
} else if (ff.getEdit()) {
response.setHeader(TransferFsImage.CONTENT_LENGTH,
String.valueOf(nnImage.getFsEditName().length()));
// send edits
TransferFsImage.getFileServer(response.getOutputStream(),
nnImage.getFsEditName());
} else if (ff.putImage()) {
// issue a HTTP get request to download the new fsimage
long filesize = 0;
for (int a = 0; a < nnImage.getFsImageNameCheckpoint().length; a++) {
File file = nnImage.getFsImageNameCheckpoint()[a];
filesize += file.length();
}
response.setHeader(TransferFsImage.CONTENT_LENGTH,
String.valueOf(filesize));
nnImage.validateCheckpointUpload(ff.getToken());
TransferFsImage.getFileClient(ff.getInfoServer(), "getimage=1",
nnImage.getFsImageNameCheckpoint());
nnImage.checkpointUploadDone();
}
} catch (Exception ie) {
String errMsg = "GetImage failed. " + StringUtils.stringifyException(ie);
response.sendError(HttpServletResponse.SC_GONE, errMsg);
throw new IOException(errMsg);
} finally {
response.getOutputStream().close();
}
}
|
diff --git a/src/main/java/org/topstack/simianarmy/basic/SimplerDbRecorder.java b/src/main/java/org/topstack/simianarmy/basic/SimplerDbRecorder.java
index 6cac75e..13bffd0 100644
--- a/src/main/java/org/topstack/simianarmy/basic/SimplerDbRecorder.java
+++ b/src/main/java/org/topstack/simianarmy/basic/SimplerDbRecorder.java
@@ -1,325 +1,319 @@
/*
* TopStack (c) Copyright 2012-2013 Transcend Computing, Inc.
*
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.topstack.simianarmy.basic;
import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentNavigableMap;
import org.mapdb.Atomic;
import org.mapdb.DB;
import org.mapdb.DBMaker;
import org.mapdb.Fun;
import org.mapdb.Utils;
import com.netflix.simianarmy.MonkeyConfiguration;
import com.netflix.simianarmy.MonkeyRecorder;
import com.netflix.simianarmy.chaos.ChaosMonkey;
/**
* Replacement for SimpleDB on non-AWS: use a embedded db.
*
* @author jgardner
*
*/
public class SimplerDbRecorder implements MonkeyRecorder {
private static DB db = null;
private static Atomic.Long nextId = null;
private static ConcurrentNavigableMap<Fun.Tuple2<Long, Long>, Event> eventMap = null;
// Upper bound, so we don't fill the disk with monkey events
private static final double MAX_EVENTS = 10000;
private double max_events = MAX_EVENTS;
private String dbFilename = "simianarmy_events";
private String dbpassword = null;
/**
*
*/
public SimplerDbRecorder(MonkeyConfiguration configuration) {
if (configuration != null) {
dbFilename = configuration.getStrOrElse("simianarmy.db.file", null);
max_events = configuration.getNumOrElse("simianarmy.db.max_events", MAX_EVENTS);
dbpassword = configuration.getStrOrElse("simianarmy.db.password", null);
}
}
private synchronized void init() {
if (nextId != null) {
return;
}
File dbFile = null;
dbFile = (dbFilename == null)? Utils.tempDbFile() : new File(dbFilename);
if (dbpassword != null) {
db = DBMaker.newFileDB(dbFile)
.closeOnJvmShutdown()
.encryptionEnable(dbpassword)
.make();
} else {
db = DBMaker.newFileDB(dbFile)
.closeOnJvmShutdown()
.make();
}
eventMap = db.getTreeMap("eventMap");
nextId = db.createAtomicLong("next", 1);
}
/* (non-Javadoc)
* @see com.netflix.simianarmy.MonkeyRecorder#newEvent(java.lang.Enum, java.lang.Enum, java.lang.String, java.lang.String)
*/
@SuppressWarnings("rawtypes")
@Override
public Event newEvent(Enum monkeyType, Enum eventType, String region,
String id) {
init();
return new MapDbRecorderEvent(monkeyType, eventType, region, id);
}
/* (non-Javadoc)
* @see com.netflix.simianarmy.MonkeyRecorder#recordEvent(com.netflix.simianarmy.MonkeyRecorder.Event)
*/
@Override
public void recordEvent(Event evt) {
init();
Fun.Tuple2<Long, Long> id = Fun.t2(evt.eventTime().getTime(),
nextId.incrementAndGet());
if (eventMap.size()+1 > max_events) {
eventMap.remove(eventMap.firstKey());
}
eventMap.put(id, evt);
db.commit();
}
/* (non-Javadoc)
* @see com.netflix.simianarmy.MonkeyRecorder#findEvents(java.util.Map, java.util.Date)
*/
@Override
public List<Event> findEvents(Map<String, String> query, Date after) {
init();
List<Event> foundEvents = new ArrayList<Event>();
for (Event evt : eventMap.tailMap(toKey(after)).values()) {
boolean matched = true;
for (Map.Entry<String, String> pair : query.entrySet()) {
- if (pair.getKey().equals("id")) {
- if (! evt.id().equals(pair.getValue())) {
- matched = false;
- }
+ if (pair.getKey().equals("id") && !evt.id().equals(pair.getValue())) {
+ matched = false;
}
- if (pair.getKey().equals("monkeyType")) {
- if (! evt.monkeyType().toString().equals(pair.getValue())) {
- matched = false;
- }
+ if (pair.getKey().equals("monkeyType") && ! evt.monkeyType().toString().equals(pair.getValue())) {
+ matched = false;
}
- if (pair.getKey().equals("eventType")) {
- if (! evt.eventType().toString().equals(pair.getValue())) {
- matched = false;
- }
+ if (pair.getKey().equals("eventType") && !evt.eventType().toString().equals(pair.getValue())) {
+ matched = false;
}
}
if (matched) {
foundEvents.add(evt);
}
}
return foundEvents;
}
/* (non-Javadoc)
* @see com.netflix.simianarmy.MonkeyRecorder#findEvents(java.lang.Enum, java.util.Map, java.util.Date)
*/
@SuppressWarnings("rawtypes")
@Override
public List<Event> findEvents(Enum monkeyType, Map<String, String> query,
Date after) {
Map<String, String> copy = new LinkedHashMap<String, String>(query);
copy.put("monkeyType", monkeyType.name());
return findEvents(copy, after);
}
/* (non-Javadoc)
* @see com.netflix.simianarmy.MonkeyRecorder#findEvents(java.lang.Enum, java.lang.Enum, java.util.Map, java.util.Date)
*/
@SuppressWarnings("rawtypes")
@Override
public List<Event> findEvents(Enum monkeyType, Enum eventType,
Map<String, String> query, Date after) {
Map<String, String> copy = new LinkedHashMap<String, String>(query);
copy.put("monkeyType", monkeyType.name());
copy.put("eventType", eventType.name());
return findEvents(copy, after);
}
private Fun.Tuple2<Long, Long> toKey(Date date) {
return Fun.t2(date.getTime(), 0L);
}
public static class MapDbRecorderEvent implements MonkeyRecorder.Event, Serializable {
/** The monkey type. */
@SuppressWarnings("rawtypes")
private Enum monkeyType;
/** The event type. */
@SuppressWarnings("rawtypes")
private Enum eventType;
/** The event id. */
private String id;
/** The event region. */
private String region;
/** The fields. */
private Map<String, String> fields = new HashMap<String, String>();
/** The event time. */
private Date date;
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* @param monkeyType
* @param eventType
* @param region
* @param id
*/
@SuppressWarnings("rawtypes")
public MapDbRecorderEvent(Enum monkeyType, Enum eventType,
String region, String id) {
this.monkeyType = monkeyType;
this.eventType = eventType;
this.id = id;
this.region = region;
this.date = new Date();
}
/**
* @param monkeyType
* @param eventType
* @param region
* @param id
* @param time
*/
@SuppressWarnings("rawtypes")
public MapDbRecorderEvent(Enum monkeyType, Enum eventType,
String region, String id, long time) {
this.monkeyType = monkeyType;
this.eventType = eventType;
this.id = id;
this.region = region;
this.date = new Date(time);
}
/* (non-Javadoc)
* @see com.netflix.simianarmy.MonkeyRecorder.Event#id()
*/
@Override
public String id() {
return id;
}
/* (non-Javadoc)
* @see com.netflix.simianarmy.MonkeyRecorder.Event#eventTime()
*/
@Override
public Date eventTime() {
return new Date(date.getTime());
}
/* (non-Javadoc)
* @see com.netflix.simianarmy.MonkeyRecorder.Event#monkeyType()
*/
@SuppressWarnings("rawtypes")
@Override
public Enum monkeyType() {
return monkeyType;
}
/* (non-Javadoc)
* @see com.netflix.simianarmy.MonkeyRecorder.Event#eventType()
*/
@SuppressWarnings("rawtypes")
@Override
public Enum eventType() {
return eventType;
}
/* (non-Javadoc)
* @see com.netflix.simianarmy.MonkeyRecorder.Event#region()
*/
@Override
public String region() {
return region;
}
/* (non-Javadoc)
* @see com.netflix.simianarmy.MonkeyRecorder.Event#fields()
*/
@Override
public Map<String, String> fields() {
return Collections.unmodifiableMap(fields);
}
/* (non-Javadoc)
* @see com.netflix.simianarmy.MonkeyRecorder.Event#field(java.lang.String)
*/
@Override
public String field(String name) {
return fields.get(name);
}
/* (non-Javadoc)
* @see com.netflix.simianarmy.MonkeyRecorder.Event#addField(java.lang.String, java.lang.String)
*/
@Override
public Event addField(String name, String value) {
fields.put(name, value);
return this;
}
}
public static void main(String[] args) {
SimplerDbRecorder r = new SimplerDbRecorder(null);
r.init();
List<Event> events2 = r.findEvents(new HashMap<String, String>(), new Date(0));
for (Event event : events2) {
System.out.println("Got:" + event + ": " + event.eventTime().getTime());
}
for (int i = 0; i < 10; i++) {
Event event = r.newEvent(ChaosMonkey.Type.CHAOS,
ChaosMonkey.EventTypes.CHAOS_TERMINATION, "1", "1");
r.recordEvent(event);
System.out.println("Added:" + event + ": " + event.eventTime().getTime());
}
List<Event> events = r.findEvents(new HashMap<String, String>(), new Date(0));
for (Event event : events) {
System.out.println("Got:" + event + ": " + event.eventTime().getTime());
}
}
}
| false | true | public List<Event> findEvents(Map<String, String> query, Date after) {
init();
List<Event> foundEvents = new ArrayList<Event>();
for (Event evt : eventMap.tailMap(toKey(after)).values()) {
boolean matched = true;
for (Map.Entry<String, String> pair : query.entrySet()) {
if (pair.getKey().equals("id")) {
if (! evt.id().equals(pair.getValue())) {
matched = false;
}
}
if (pair.getKey().equals("monkeyType")) {
if (! evt.monkeyType().toString().equals(pair.getValue())) {
matched = false;
}
}
if (pair.getKey().equals("eventType")) {
if (! evt.eventType().toString().equals(pair.getValue())) {
matched = false;
}
}
}
if (matched) {
foundEvents.add(evt);
}
}
return foundEvents;
}
| public List<Event> findEvents(Map<String, String> query, Date after) {
init();
List<Event> foundEvents = new ArrayList<Event>();
for (Event evt : eventMap.tailMap(toKey(after)).values()) {
boolean matched = true;
for (Map.Entry<String, String> pair : query.entrySet()) {
if (pair.getKey().equals("id") && !evt.id().equals(pair.getValue())) {
matched = false;
}
if (pair.getKey().equals("monkeyType") && ! evt.monkeyType().toString().equals(pair.getValue())) {
matched = false;
}
if (pair.getKey().equals("eventType") && !evt.eventType().toString().equals(pair.getValue())) {
matched = false;
}
}
if (matched) {
foundEvents.add(evt);
}
}
return foundEvents;
}
|
diff --git a/entitlement/src/test/java/com/ning/billing/entitlement/api/TestDefaultSubscriptionApi.java b/entitlement/src/test/java/com/ning/billing/entitlement/api/TestDefaultSubscriptionApi.java
index 6856ec918..6e610dfb5 100644
--- a/entitlement/src/test/java/com/ning/billing/entitlement/api/TestDefaultSubscriptionApi.java
+++ b/entitlement/src/test/java/com/ning/billing/entitlement/api/TestDefaultSubscriptionApi.java
@@ -1,247 +1,247 @@
/*
* Copyright 2010-2013 Ning, Inc.
*
* Ning licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.ning.billing.entitlement.api;
import java.util.List;
import java.util.UUID;
import org.joda.time.LocalDate;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.ning.billing.ErrorCode;
import com.ning.billing.account.api.Account;
import com.ning.billing.account.api.AccountApiException;
import com.ning.billing.api.TestApiListener.NextEvent;
import com.ning.billing.catalog.api.BillingPeriod;
import com.ning.billing.catalog.api.PlanPhaseSpecifier;
import com.ning.billing.catalog.api.PriceListSet;
import com.ning.billing.catalog.api.ProductCategory;
import com.ning.billing.entitlement.EntitlementTestSuiteWithEmbeddedDB;
import com.ning.billing.junction.DefaultBlockingState;
import com.ning.billing.util.api.AuditLevel;
import com.ning.billing.util.audit.AuditLog;
import com.ning.billing.util.audit.ChangeType;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertNull;
public class TestDefaultSubscriptionApi extends EntitlementTestSuiteWithEmbeddedDB {
@Test(groups = "slow", description = "Verify blocking states are exposed in SubscriptionBundle")
public void testBlockingStatesInTimelineApi() throws Exception {
final LocalDate initialDate = new LocalDate(2013, 8, 7);
clock.setDay(initialDate);
final Account account = accountApi.createAccount(getAccountData(7), callContext);
final PlanPhaseSpecifier spec = new PlanPhaseSpecifier("Shotgun", ProductCategory.BASE, BillingPeriod.MONTHLY, PriceListSet.DEFAULT_PRICELIST_NAME, null);
testListener.pushExpectedEvents(NextEvent.CREATE, NextEvent.CREATE, NextEvent.BLOCK);
final Entitlement entitlement1 = entitlementApi.createBaseEntitlement(account.getId(), spec, UUID.randomUUID().toString(), initialDate, callContext);
// Sleep 1 sec so created date are apparts from each other and ordering in the bundle does not default on the UUID which is random.
try {Thread.sleep(1000); } catch (InterruptedException ignore) {};
final Entitlement entitlement2 = entitlementApi.createBaseEntitlement(account.getId(), spec, UUID.randomUUID().toString(), initialDate, callContext);
entitlementUtils.setBlockingStateAndPostBlockingTransitionEvent(new DefaultBlockingState(account.getId(), BlockingStateType.ACCOUNT, "stateName", "service", false, false, false, clock.getUTCNow()),
internalCallContextFactory.createInternalCallContext(account.getId(), callContext));
assertListenerStatus();
final List<SubscriptionBundle> bundles = subscriptionApi.getSubscriptionBundlesForAccountId(account.getId(), callContext);
Assert.assertEquals(bundles.size(), 2);
// This will test the ordering as well
subscriptionBundleChecker(bundles, initialDate, entitlement1, 0);
subscriptionBundleChecker(bundles, initialDate, entitlement2, 1);
}
private void subscriptionBundleChecker(final List<SubscriptionBundle> bundles, final LocalDate initialDate, final Entitlement entitlement, final int idx) {
Assert.assertEquals(bundles.get(idx).getId(), entitlement.getBundleId());
Assert.assertEquals(bundles.get(idx).getSubscriptions().size(), 1);
Assert.assertEquals(bundles.get(idx).getSubscriptions().get(0).getId(), entitlement.getId());
Assert.assertEquals(bundles.get(idx).getTimeline().getSubscriptionEvents().size(), 4);
Assert.assertEquals(bundles.get(idx).getTimeline().getSubscriptionEvents().get(0).getEffectiveDate(), initialDate);
Assert.assertEquals(bundles.get(idx).getTimeline().getSubscriptionEvents().get(0).getSubscriptionEventType(), SubscriptionEventType.START_ENTITLEMENT);
Assert.assertEquals(bundles.get(idx).getTimeline().getSubscriptionEvents().get(1).getEffectiveDate(), initialDate);
Assert.assertEquals(bundles.get(idx).getTimeline().getSubscriptionEvents().get(1).getSubscriptionEventType(), SubscriptionEventType.START_BILLING);
Assert.assertEquals(bundles.get(idx).getTimeline().getSubscriptionEvents().get(2).getEffectiveDate(), initialDate);
Assert.assertEquals(bundles.get(idx).getTimeline().getSubscriptionEvents().get(2).getSubscriptionEventType(), SubscriptionEventType.SERVICE_STATE_CHANGE);
Assert.assertEquals(bundles.get(idx).getTimeline().getSubscriptionEvents().get(2).getServiceName(), "service");
Assert.assertEquals(bundles.get(idx).getTimeline().getSubscriptionEvents().get(2).getServiceStateName(), "stateName");
Assert.assertEquals(bundles.get(idx).getTimeline().getSubscriptionEvents().get(3).getEffectiveDate(), new LocalDate(2013, 9, 6));
Assert.assertEquals(bundles.get(idx).getTimeline().getSubscriptionEvents().get(3).getSubscriptionEventType(), SubscriptionEventType.PHASE);
}
@Test(groups = "slow")
public void testWithMultipleBundle() throws AccountApiException, SubscriptionApiException, EntitlementApiException {
final String externalKey = "fooXXX";
final LocalDate initialDate = new LocalDate(2013, 8, 7);
clock.setDay(initialDate);
final Account account = accountApi.createAccount(getAccountData(7), callContext);
final PlanPhaseSpecifier spec = new PlanPhaseSpecifier("Shotgun", ProductCategory.BASE, BillingPeriod.MONTHLY, PriceListSet.DEFAULT_PRICELIST_NAME, null);
// Create entitlement and check each field
testListener.pushExpectedEvent(NextEvent.CREATE);
final Entitlement entitlement = entitlementApi.createBaseEntitlement(account.getId(), spec, externalKey, initialDate, callContext);
assertListenerStatus();
assertEquals(entitlement.getAccountId(), account.getId());
assertEquals(entitlement.getExternalKey(), externalKey);
assertEquals(entitlement.getEffectiveStartDate(), initialDate);
assertNull(entitlement.getEffectiveEndDate());
final List<SubscriptionBundle> bundles = subscriptionApi.getSubscriptionBundlesForExternalKey(externalKey, callContext);
assertEquals(bundles.size(), 1);
final SubscriptionBundle activeBundle = subscriptionApi.getActiveSubscriptionBundleForExternalKey(externalKey, callContext);
assertEquals(activeBundle.getId(), entitlement.getBundleId());
// Cancel entitlement
clock.addDays(3);
testListener.pushExpectedEvents(NextEvent.CANCEL, NextEvent.BLOCK);
entitlement.cancelEntitlementWithDate(new LocalDate(clock.getUTCNow(), account.getTimeZone()), true, callContext);
assertListenerStatus();
try {
subscriptionApi.getActiveSubscriptionBundleForExternalKey(externalKey, callContext);
Assert.fail("Expected getActiveSubscriptionBundleForExternalKey to fail after cancellation");
} catch (SubscriptionApiException e) {
- assertEquals(e.getCode(), ErrorCode.SUB_CREATE_ACTIVE_BUNDLE_KEY_EXISTS.getCode());
+ assertEquals(e.getCode(), ErrorCode.SUB_GET_INVALID_BUNDLE_KEY.getCode());
}
clock.addDays(1);
// Re-create a new bundle with same externalKey
final PlanPhaseSpecifier spec2 = new PlanPhaseSpecifier("Pistol", ProductCategory.BASE, BillingPeriod.MONTHLY, PriceListSet.DEFAULT_PRICELIST_NAME, null);
// Create entitlement and check each field
testListener.pushExpectedEvent(NextEvent.CREATE);
final Entitlement entitlement2 = entitlementApi.createBaseEntitlement(account.getId(), spec2, externalKey, new LocalDate(clock.getUTCNow(), account.getTimeZone()), callContext);
assertListenerStatus();
assertEquals(entitlement2.getAccountId(), account.getId());
assertEquals(entitlement2.getExternalKey(), externalKey);
final List<SubscriptionBundle> bundles2 = subscriptionApi.getSubscriptionBundlesForExternalKey(externalKey, callContext);
assertEquals(bundles2.size(), 2);
SubscriptionBundle firstbundle = bundles2.get(0);
assertEquals(firstbundle.getSubscriptions().size(), 1);
assertEquals(firstbundle.getSubscriptions().get(0).getEffectiveStartDate(), new LocalDate(2013, 8, 7));
assertEquals(firstbundle.getSubscriptions().get(0).getBillingStartDate(), new LocalDate(2013, 8, 7));
assertEquals(firstbundle.getSubscriptions().get(0).getEffectiveEndDate(), new LocalDate(2013, 8, 10));
assertEquals(firstbundle.getSubscriptions().get(0).getBillingEndDate(), new LocalDate(2013, 8, 10));
SubscriptionBundle secondbundle = bundles2.get(1);
assertEquals(secondbundle.getSubscriptions().size(), 1);
assertEquals(secondbundle.getSubscriptions().get(0).getEffectiveStartDate(), new LocalDate(2013, 8, 11));
assertEquals(secondbundle.getSubscriptions().get(0).getBillingStartDate(), new LocalDate(2013, 8, 11));
assertNull(secondbundle.getSubscriptions().get(0).getEffectiveEndDate());
assertNull(secondbundle.getSubscriptions().get(0).getBillingEndDate());
assertEquals(secondbundle.getOriginalCreatedDate().compareTo(firstbundle.getCreatedDate()), 0);
final List<SubscriptionBundle> bundles2Again = subscriptionApi.getSubscriptionBundlesForAccountIdAndExternalKey(account.getId(), externalKey, callContext);
assertEquals(bundles2Again.size(), 2);
clock.addDays(3);
final Account account2 = accountApi.createAccount(getAccountData(7), callContext);
testListener.pushExpectedEvents(NextEvent.TRANSFER, NextEvent.CANCEL, NextEvent.BLOCK);
entitlementApi.transferEntitlements(account.getId(), account2.getId(), externalKey, new LocalDate(clock.getUTCNow(), account.getTimeZone()), callContext);
assertListenerStatus();
final List<SubscriptionBundle> bundles3 = subscriptionApi.getSubscriptionBundlesForExternalKey(externalKey, callContext);
assertEquals(bundles3.size(), 3);
firstbundle = bundles3.get(0);
assertEquals(firstbundle.getSubscriptions().size(), 1);
assertEquals(firstbundle.getSubscriptions().get(0).getEffectiveStartDate(), new LocalDate(2013, 8, 7));
assertEquals(firstbundle.getSubscriptions().get(0).getBillingStartDate(), new LocalDate(2013, 8, 7));
assertEquals(firstbundle.getSubscriptions().get(0).getEffectiveEndDate(), new LocalDate(2013, 8, 10));
assertEquals(firstbundle.getSubscriptions().get(0).getBillingEndDate(), new LocalDate(2013, 8, 10));
secondbundle = bundles3.get(1);
assertEquals(secondbundle.getSubscriptions().size(), 1);
assertEquals(secondbundle.getSubscriptions().get(0).getEffectiveStartDate(), new LocalDate(2013, 8, 11));
assertEquals(secondbundle.getSubscriptions().get(0).getBillingStartDate(), new LocalDate(2013, 8, 11));
assertEquals(secondbundle.getSubscriptions().get(0).getEffectiveEndDate(), new LocalDate(2013, 8, 14));
assertEquals(secondbundle.getSubscriptions().get(0).getBillingEndDate(), new LocalDate(2013, 8, 14));
assertEquals(secondbundle.getOriginalCreatedDate().compareTo(firstbundle.getCreatedDate()), 0);
SubscriptionBundle thirdBundle = bundles3.get(2);
assertEquals(thirdBundle.getSubscriptions().size(), 1);
assertEquals(thirdBundle.getSubscriptions().get(0).getEffectiveStartDate(), new LocalDate(2013, 8, 14));
assertEquals(thirdBundle.getSubscriptions().get(0).getBillingStartDate(), new LocalDate(2013, 8, 14));
assertNull(thirdBundle.getSubscriptions().get(0).getEffectiveEndDate());
assertNull(thirdBundle.getSubscriptions().get(0).getBillingEndDate());
assertEquals(thirdBundle.getOriginalCreatedDate().compareTo(firstbundle.getCreatedDate()), 0);
}
@Test(groups = "slow", description = "Test for https://github.com/killbill/killbill/issues/136")
public void testAuditLogsForEntitlementAndSubscriptionBaseObjects() throws AccountApiException, EntitlementApiException, SubscriptionApiException {
final LocalDate initialDate = new LocalDate(2013, 8, 7);
clock.setDay(initialDate);
final Account account = accountApi.createAccount(getAccountData(7), callContext);
// Create entitlement
testListener.pushExpectedEvent(NextEvent.CREATE);
final PlanPhaseSpecifier spec = new PlanPhaseSpecifier("Shotgun", ProductCategory.BASE, BillingPeriod.ANNUAL, PriceListSet.DEFAULT_PRICELIST_NAME, null);
final Entitlement baseEntitlement = entitlementApi.createBaseEntitlement(account.getId(), spec, account.getExternalKey(), initialDate, callContext);
assertListenerStatus();
// Get the phase event out of the way
testListener.pushExpectedEvents(NextEvent.PHASE);
clock.setDay(new LocalDate(2013, 9, 7));
assertListenerStatus();
final LocalDate pauseDate = new LocalDate(2013, 9, 17);
entitlementApi.pause(baseEntitlement.getBundleId(), pauseDate, callContext);
final LocalDate resumeDate = new LocalDate(2013, 12, 24);
entitlementApi.resume(baseEntitlement.getBundleId(), resumeDate, callContext);
final LocalDate cancelDate = new LocalDate(2013, 12, 27);
baseEntitlement.cancelEntitlementWithDate(cancelDate, true, callContext);
testListener.pushExpectedEvents(NextEvent.PAUSE, NextEvent.BLOCK, NextEvent.RESUME, NextEvent.BLOCK, NextEvent.CANCEL, NextEvent.BLOCK);
clock.setDay(cancelDate.plusDays(1));
assertListenerStatus();
final SubscriptionBundle bundle = subscriptionApi.getSubscriptionBundle(baseEntitlement.getBundleId(), callContext);
final List<SubscriptionEvent> transitions = bundle.getTimeline().getSubscriptionEvents();
assertEquals(transitions.size(), 9);
checkSubscriptionEventAuditLog(transitions, 0, SubscriptionEventType.START_ENTITLEMENT);
checkSubscriptionEventAuditLog(transitions, 1, SubscriptionEventType.START_BILLING);
checkSubscriptionEventAuditLog(transitions, 2, SubscriptionEventType.PHASE);
checkSubscriptionEventAuditLog(transitions, 3, SubscriptionEventType.PAUSE_ENTITLEMENT);
checkSubscriptionEventAuditLog(transitions, 4, SubscriptionEventType.PAUSE_BILLING);
checkSubscriptionEventAuditLog(transitions, 5, SubscriptionEventType.RESUME_ENTITLEMENT);
checkSubscriptionEventAuditLog(transitions, 6, SubscriptionEventType.RESUME_BILLING);
checkSubscriptionEventAuditLog(transitions, 7, SubscriptionEventType.STOP_ENTITLEMENT);
checkSubscriptionEventAuditLog(transitions, 8, SubscriptionEventType.STOP_BILLING);
}
private void checkSubscriptionEventAuditLog(final List<SubscriptionEvent> transitions, final int idx, final SubscriptionEventType expectedType) {
assertEquals(transitions.get(idx).getSubscriptionEventType(), expectedType);
final List<AuditLog> auditLogs = auditUserApi.getAuditLogs(transitions.get(idx).getId(), transitions.get(idx).getSubscriptionEventType().getObjectType(), AuditLevel.FULL, callContext);
assertEquals(auditLogs.size(), 1);
assertEquals(auditLogs.get(0).getChangeType(), ChangeType.INSERT);
}
}
| true | true | public void testWithMultipleBundle() throws AccountApiException, SubscriptionApiException, EntitlementApiException {
final String externalKey = "fooXXX";
final LocalDate initialDate = new LocalDate(2013, 8, 7);
clock.setDay(initialDate);
final Account account = accountApi.createAccount(getAccountData(7), callContext);
final PlanPhaseSpecifier spec = new PlanPhaseSpecifier("Shotgun", ProductCategory.BASE, BillingPeriod.MONTHLY, PriceListSet.DEFAULT_PRICELIST_NAME, null);
// Create entitlement and check each field
testListener.pushExpectedEvent(NextEvent.CREATE);
final Entitlement entitlement = entitlementApi.createBaseEntitlement(account.getId(), spec, externalKey, initialDate, callContext);
assertListenerStatus();
assertEquals(entitlement.getAccountId(), account.getId());
assertEquals(entitlement.getExternalKey(), externalKey);
assertEquals(entitlement.getEffectiveStartDate(), initialDate);
assertNull(entitlement.getEffectiveEndDate());
final List<SubscriptionBundle> bundles = subscriptionApi.getSubscriptionBundlesForExternalKey(externalKey, callContext);
assertEquals(bundles.size(), 1);
final SubscriptionBundle activeBundle = subscriptionApi.getActiveSubscriptionBundleForExternalKey(externalKey, callContext);
assertEquals(activeBundle.getId(), entitlement.getBundleId());
// Cancel entitlement
clock.addDays(3);
testListener.pushExpectedEvents(NextEvent.CANCEL, NextEvent.BLOCK);
entitlement.cancelEntitlementWithDate(new LocalDate(clock.getUTCNow(), account.getTimeZone()), true, callContext);
assertListenerStatus();
try {
subscriptionApi.getActiveSubscriptionBundleForExternalKey(externalKey, callContext);
Assert.fail("Expected getActiveSubscriptionBundleForExternalKey to fail after cancellation");
} catch (SubscriptionApiException e) {
assertEquals(e.getCode(), ErrorCode.SUB_CREATE_ACTIVE_BUNDLE_KEY_EXISTS.getCode());
}
clock.addDays(1);
// Re-create a new bundle with same externalKey
final PlanPhaseSpecifier spec2 = new PlanPhaseSpecifier("Pistol", ProductCategory.BASE, BillingPeriod.MONTHLY, PriceListSet.DEFAULT_PRICELIST_NAME, null);
// Create entitlement and check each field
testListener.pushExpectedEvent(NextEvent.CREATE);
final Entitlement entitlement2 = entitlementApi.createBaseEntitlement(account.getId(), spec2, externalKey, new LocalDate(clock.getUTCNow(), account.getTimeZone()), callContext);
assertListenerStatus();
assertEquals(entitlement2.getAccountId(), account.getId());
assertEquals(entitlement2.getExternalKey(), externalKey);
final List<SubscriptionBundle> bundles2 = subscriptionApi.getSubscriptionBundlesForExternalKey(externalKey, callContext);
assertEquals(bundles2.size(), 2);
SubscriptionBundle firstbundle = bundles2.get(0);
assertEquals(firstbundle.getSubscriptions().size(), 1);
assertEquals(firstbundle.getSubscriptions().get(0).getEffectiveStartDate(), new LocalDate(2013, 8, 7));
assertEquals(firstbundle.getSubscriptions().get(0).getBillingStartDate(), new LocalDate(2013, 8, 7));
assertEquals(firstbundle.getSubscriptions().get(0).getEffectiveEndDate(), new LocalDate(2013, 8, 10));
assertEquals(firstbundle.getSubscriptions().get(0).getBillingEndDate(), new LocalDate(2013, 8, 10));
SubscriptionBundle secondbundle = bundles2.get(1);
assertEquals(secondbundle.getSubscriptions().size(), 1);
assertEquals(secondbundle.getSubscriptions().get(0).getEffectiveStartDate(), new LocalDate(2013, 8, 11));
assertEquals(secondbundle.getSubscriptions().get(0).getBillingStartDate(), new LocalDate(2013, 8, 11));
assertNull(secondbundle.getSubscriptions().get(0).getEffectiveEndDate());
assertNull(secondbundle.getSubscriptions().get(0).getBillingEndDate());
assertEquals(secondbundle.getOriginalCreatedDate().compareTo(firstbundle.getCreatedDate()), 0);
final List<SubscriptionBundle> bundles2Again = subscriptionApi.getSubscriptionBundlesForAccountIdAndExternalKey(account.getId(), externalKey, callContext);
assertEquals(bundles2Again.size(), 2);
clock.addDays(3);
final Account account2 = accountApi.createAccount(getAccountData(7), callContext);
testListener.pushExpectedEvents(NextEvent.TRANSFER, NextEvent.CANCEL, NextEvent.BLOCK);
entitlementApi.transferEntitlements(account.getId(), account2.getId(), externalKey, new LocalDate(clock.getUTCNow(), account.getTimeZone()), callContext);
assertListenerStatus();
final List<SubscriptionBundle> bundles3 = subscriptionApi.getSubscriptionBundlesForExternalKey(externalKey, callContext);
assertEquals(bundles3.size(), 3);
firstbundle = bundles3.get(0);
assertEquals(firstbundle.getSubscriptions().size(), 1);
assertEquals(firstbundle.getSubscriptions().get(0).getEffectiveStartDate(), new LocalDate(2013, 8, 7));
assertEquals(firstbundle.getSubscriptions().get(0).getBillingStartDate(), new LocalDate(2013, 8, 7));
assertEquals(firstbundle.getSubscriptions().get(0).getEffectiveEndDate(), new LocalDate(2013, 8, 10));
assertEquals(firstbundle.getSubscriptions().get(0).getBillingEndDate(), new LocalDate(2013, 8, 10));
secondbundle = bundles3.get(1);
assertEquals(secondbundle.getSubscriptions().size(), 1);
assertEquals(secondbundle.getSubscriptions().get(0).getEffectiveStartDate(), new LocalDate(2013, 8, 11));
assertEquals(secondbundle.getSubscriptions().get(0).getBillingStartDate(), new LocalDate(2013, 8, 11));
assertEquals(secondbundle.getSubscriptions().get(0).getEffectiveEndDate(), new LocalDate(2013, 8, 14));
assertEquals(secondbundle.getSubscriptions().get(0).getBillingEndDate(), new LocalDate(2013, 8, 14));
assertEquals(secondbundle.getOriginalCreatedDate().compareTo(firstbundle.getCreatedDate()), 0);
SubscriptionBundle thirdBundle = bundles3.get(2);
assertEquals(thirdBundle.getSubscriptions().size(), 1);
assertEquals(thirdBundle.getSubscriptions().get(0).getEffectiveStartDate(), new LocalDate(2013, 8, 14));
assertEquals(thirdBundle.getSubscriptions().get(0).getBillingStartDate(), new LocalDate(2013, 8, 14));
assertNull(thirdBundle.getSubscriptions().get(0).getEffectiveEndDate());
assertNull(thirdBundle.getSubscriptions().get(0).getBillingEndDate());
assertEquals(thirdBundle.getOriginalCreatedDate().compareTo(firstbundle.getCreatedDate()), 0);
}
| public void testWithMultipleBundle() throws AccountApiException, SubscriptionApiException, EntitlementApiException {
final String externalKey = "fooXXX";
final LocalDate initialDate = new LocalDate(2013, 8, 7);
clock.setDay(initialDate);
final Account account = accountApi.createAccount(getAccountData(7), callContext);
final PlanPhaseSpecifier spec = new PlanPhaseSpecifier("Shotgun", ProductCategory.BASE, BillingPeriod.MONTHLY, PriceListSet.DEFAULT_PRICELIST_NAME, null);
// Create entitlement and check each field
testListener.pushExpectedEvent(NextEvent.CREATE);
final Entitlement entitlement = entitlementApi.createBaseEntitlement(account.getId(), spec, externalKey, initialDate, callContext);
assertListenerStatus();
assertEquals(entitlement.getAccountId(), account.getId());
assertEquals(entitlement.getExternalKey(), externalKey);
assertEquals(entitlement.getEffectiveStartDate(), initialDate);
assertNull(entitlement.getEffectiveEndDate());
final List<SubscriptionBundle> bundles = subscriptionApi.getSubscriptionBundlesForExternalKey(externalKey, callContext);
assertEquals(bundles.size(), 1);
final SubscriptionBundle activeBundle = subscriptionApi.getActiveSubscriptionBundleForExternalKey(externalKey, callContext);
assertEquals(activeBundle.getId(), entitlement.getBundleId());
// Cancel entitlement
clock.addDays(3);
testListener.pushExpectedEvents(NextEvent.CANCEL, NextEvent.BLOCK);
entitlement.cancelEntitlementWithDate(new LocalDate(clock.getUTCNow(), account.getTimeZone()), true, callContext);
assertListenerStatus();
try {
subscriptionApi.getActiveSubscriptionBundleForExternalKey(externalKey, callContext);
Assert.fail("Expected getActiveSubscriptionBundleForExternalKey to fail after cancellation");
} catch (SubscriptionApiException e) {
assertEquals(e.getCode(), ErrorCode.SUB_GET_INVALID_BUNDLE_KEY.getCode());
}
clock.addDays(1);
// Re-create a new bundle with same externalKey
final PlanPhaseSpecifier spec2 = new PlanPhaseSpecifier("Pistol", ProductCategory.BASE, BillingPeriod.MONTHLY, PriceListSet.DEFAULT_PRICELIST_NAME, null);
// Create entitlement and check each field
testListener.pushExpectedEvent(NextEvent.CREATE);
final Entitlement entitlement2 = entitlementApi.createBaseEntitlement(account.getId(), spec2, externalKey, new LocalDate(clock.getUTCNow(), account.getTimeZone()), callContext);
assertListenerStatus();
assertEquals(entitlement2.getAccountId(), account.getId());
assertEquals(entitlement2.getExternalKey(), externalKey);
final List<SubscriptionBundle> bundles2 = subscriptionApi.getSubscriptionBundlesForExternalKey(externalKey, callContext);
assertEquals(bundles2.size(), 2);
SubscriptionBundle firstbundle = bundles2.get(0);
assertEquals(firstbundle.getSubscriptions().size(), 1);
assertEquals(firstbundle.getSubscriptions().get(0).getEffectiveStartDate(), new LocalDate(2013, 8, 7));
assertEquals(firstbundle.getSubscriptions().get(0).getBillingStartDate(), new LocalDate(2013, 8, 7));
assertEquals(firstbundle.getSubscriptions().get(0).getEffectiveEndDate(), new LocalDate(2013, 8, 10));
assertEquals(firstbundle.getSubscriptions().get(0).getBillingEndDate(), new LocalDate(2013, 8, 10));
SubscriptionBundle secondbundle = bundles2.get(1);
assertEquals(secondbundle.getSubscriptions().size(), 1);
assertEquals(secondbundle.getSubscriptions().get(0).getEffectiveStartDate(), new LocalDate(2013, 8, 11));
assertEquals(secondbundle.getSubscriptions().get(0).getBillingStartDate(), new LocalDate(2013, 8, 11));
assertNull(secondbundle.getSubscriptions().get(0).getEffectiveEndDate());
assertNull(secondbundle.getSubscriptions().get(0).getBillingEndDate());
assertEquals(secondbundle.getOriginalCreatedDate().compareTo(firstbundle.getCreatedDate()), 0);
final List<SubscriptionBundle> bundles2Again = subscriptionApi.getSubscriptionBundlesForAccountIdAndExternalKey(account.getId(), externalKey, callContext);
assertEquals(bundles2Again.size(), 2);
clock.addDays(3);
final Account account2 = accountApi.createAccount(getAccountData(7), callContext);
testListener.pushExpectedEvents(NextEvent.TRANSFER, NextEvent.CANCEL, NextEvent.BLOCK);
entitlementApi.transferEntitlements(account.getId(), account2.getId(), externalKey, new LocalDate(clock.getUTCNow(), account.getTimeZone()), callContext);
assertListenerStatus();
final List<SubscriptionBundle> bundles3 = subscriptionApi.getSubscriptionBundlesForExternalKey(externalKey, callContext);
assertEquals(bundles3.size(), 3);
firstbundle = bundles3.get(0);
assertEquals(firstbundle.getSubscriptions().size(), 1);
assertEquals(firstbundle.getSubscriptions().get(0).getEffectiveStartDate(), new LocalDate(2013, 8, 7));
assertEquals(firstbundle.getSubscriptions().get(0).getBillingStartDate(), new LocalDate(2013, 8, 7));
assertEquals(firstbundle.getSubscriptions().get(0).getEffectiveEndDate(), new LocalDate(2013, 8, 10));
assertEquals(firstbundle.getSubscriptions().get(0).getBillingEndDate(), new LocalDate(2013, 8, 10));
secondbundle = bundles3.get(1);
assertEquals(secondbundle.getSubscriptions().size(), 1);
assertEquals(secondbundle.getSubscriptions().get(0).getEffectiveStartDate(), new LocalDate(2013, 8, 11));
assertEquals(secondbundle.getSubscriptions().get(0).getBillingStartDate(), new LocalDate(2013, 8, 11));
assertEquals(secondbundle.getSubscriptions().get(0).getEffectiveEndDate(), new LocalDate(2013, 8, 14));
assertEquals(secondbundle.getSubscriptions().get(0).getBillingEndDate(), new LocalDate(2013, 8, 14));
assertEquals(secondbundle.getOriginalCreatedDate().compareTo(firstbundle.getCreatedDate()), 0);
SubscriptionBundle thirdBundle = bundles3.get(2);
assertEquals(thirdBundle.getSubscriptions().size(), 1);
assertEquals(thirdBundle.getSubscriptions().get(0).getEffectiveStartDate(), new LocalDate(2013, 8, 14));
assertEquals(thirdBundle.getSubscriptions().get(0).getBillingStartDate(), new LocalDate(2013, 8, 14));
assertNull(thirdBundle.getSubscriptions().get(0).getEffectiveEndDate());
assertNull(thirdBundle.getSubscriptions().get(0).getBillingEndDate());
assertEquals(thirdBundle.getOriginalCreatedDate().compareTo(firstbundle.getCreatedDate()), 0);
}
|
diff --git a/src/com/wolvencraft/prison/mines/cmd/EditCommand.java b/src/com/wolvencraft/prison/mines/cmd/EditCommand.java
index 283dd17..626f533 100644
--- a/src/com/wolvencraft/prison/mines/cmd/EditCommand.java
+++ b/src/com/wolvencraft/prison/mines/cmd/EditCommand.java
@@ -1,227 +1,227 @@
package com.wolvencraft.prison.mines.cmd;
import java.text.DecimalFormat;
import java.util.List;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.material.MaterialData;
import com.wolvencraft.prison.PrisonSuite;
import com.wolvencraft.prison.hooks.TimedTask;
import com.wolvencraft.prison.mines.CommandManager;
import com.wolvencraft.prison.mines.PrisonMine;
import com.wolvencraft.prison.mines.mine.Mine;
import com.wolvencraft.prison.mines.settings.Language;
import com.wolvencraft.prison.mines.settings.MineData;
import com.wolvencraft.prison.mines.util.Message;
import com.wolvencraft.prison.mines.util.Util;
import com.wolvencraft.prison.mines.util.data.MineBlock;
public class EditCommand implements BaseCommand {
@Override
public boolean run(String[] args) {
Language language = PrisonMine.getLanguage();
Mine curMine = PrisonMine.getCurMine();
if(curMine == null
&& !args[0].equalsIgnoreCase("edit")
&& !args[0].equalsIgnoreCase("delete")) {
Message.sendFormattedError(language.ERROR_MINENOTSELECTED);
return false;
}
if(args[0].equalsIgnoreCase("edit")) {
if(args.length == 1) {
if(PrisonMine.getCurMine() != null) {
Message.sendFormattedSuccess(language.MINE_DESELECTED);
PrisonMine.setCurMine(null);
return true;
} else { getHelp(); return true; }
} else if(args.length == 2) {
if(args[1].equalsIgnoreCase("help")) { getHelp(); return true; }
curMine = Mine.get(args[1]);
if(curMine == null) { Message.sendFormattedError(language.ERROR_MINENAME.replace("<ID>", args[1])); return false; }
PrisonMine.setCurMine(curMine);
Message.sendFormattedSuccess(language.MINE_SELECTED);
return true;
} else { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
} else if(args[0].equalsIgnoreCase("add") || args[0].equalsIgnoreCase("+")) {
if(args.length == 1) { getHelp(); return true; }
if(args.length > 3) { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
List<MineBlock> localBlocks = curMine.getLocalBlocks();
if(localBlocks.size() == 0) curMine.addBlock(new MaterialData(Material.AIR), 1);
MaterialData block = Util.getBlock(args[1]);
MineBlock air = curMine.getBlock(new MaterialData(Material.AIR));
if(block == null) { Message.sendFormattedError(language.ERROR_NOSUCHBLOCK.replaceAll("<BLOCK>", args[1])); return false; }
if(block.equals(air.getBlock())) { Message.sendFormattedError(language.ERROR_FUCKIGNNOOB); return false; }
double percent, percentAvailable = air.getChance();
if(args.length == 3) {
if(Util.isNumeric(args[2])) percent = Double.parseDouble(args[2]);
else {
try { percent = Double.parseDouble(args[2].replace("%", "")); }
catch(NumberFormatException nfe) { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
}
percent = percent / 100;
}
else percent = percentAvailable;
if(percent <= 0) { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
DecimalFormat dFormat = new DecimalFormat("#.########");
percent = Double.valueOf(dFormat.format(percent));
if((percentAvailable - percent) < 0) { Message.sendFormattedError("Invalid percentage. Use /mine info " + curMine.getId() + " to review the percentages"); return false; }
else percentAvailable -= percent;
- air.setChance(percentAvailable);
+ air.setChance(Double.valueOf(dFormat.format(percentAvailable)));
MineBlock index = curMine.getBlock(block);
if(index == null) curMine.addBlock(block, percent);
else index.setChance(index.getChance() + percent);
Message.sendFormattedMine(Util.formatPercent(percent)+ " of " + block.getItemType().toString().toLowerCase().replace("_", " ") + " added to the mine");
Message.sendFormattedMine("Reset the mine for the changes to take effect");
return curMine.saveFile();
} else if(args[0].equalsIgnoreCase("remove") || args[0].equalsIgnoreCase("-")) {
if(args.length == 1) { getHelp(); return true; }
if(args.length > 3) { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
MineBlock blockData = curMine.getBlock(Util.getBlock(args[1]));
if(blockData == null) { Message.sendFormattedError("There is no " + ChatColor.RED + args[1] + ChatColor.WHITE + " in mine '" + curMine.getId() + "'"); return false; }
MineBlock air = curMine.getBlock(new MaterialData(Material.AIR));
if(blockData.getBlock().equals(air.getBlock())) { Message.sendFormattedError(language.ERROR_FUCKIGNNOOB); return false; }
double percent = 0;
if(args.length == 3) {
if(Util.isNumeric(args[2])) percent = Double.parseDouble(args[2]);
else {
try { percent = Double.parseDouble(args[2].replace("%", "")); }
catch(NumberFormatException nfe) { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
}
percent = percent / 100;
if(percent > blockData.getChance()) percent = blockData.getChance();
air.setChance(air.getChance() + percent);
blockData.setChance(blockData.getChance() - percent);
Message.sendFormattedMine(Util.formatPercent(percent) + " of " + args[1] + " was successfully removed from the mine");
}
else {
air.setChance(air.getChance() + blockData.getChance());
curMine.removeBlock(blockData);
Message.sendFormattedMine(args[1] + " was successfully removed from the mine");
}
return curMine.saveFile();
} else if(args[0].equalsIgnoreCase("name")) {
if(args.length == 1) {
curMine.setName("");
Message.sendFormattedMine("Mine display name has been cleared");
return true;
}
if(args.length < 2) { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
String name = args[1];
for(int i = 2; i < args.length; i++) name = name + " " + args[i];
curMine.setName(name);
Message.sendFormattedMine("Mine now has a display name '" + ChatColor.GOLD + name + ChatColor.WHITE + "'");
return curMine.saveFile();
} else if(args[0].equalsIgnoreCase("cooldown")) {
if(args.length > 2) { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
if(args.length == 1) {
if(curMine.getCooldown()) {
curMine.setCooldownEnabled(false);
Message.sendFormattedMine("Reset cooldown " + ChatColor.RED + "disabled");
}
else {
curMine.setCooldownEnabled(true);
Message.sendFormattedMine("Reset cooldown " + ChatColor.GREEN + "enabled");
}
} else if(args.length == 2) {
int seconds = Util.timeToSeconds(args[1]);
if(seconds == -1) { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
curMine.setCooldownPeriod(seconds);
Message.sendFormattedMine("Reset cooldown set to " + ChatColor.GREEN + Util.secondsToTime(seconds));
} else { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
return curMine.saveFile();
} else if(args[0].equalsIgnoreCase("setparent") || args[0].equalsIgnoreCase("link")) {
if(args.length > 2) { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
if(args.length == 1) {
if(curMine.getParent() != null) {
Message.sendFormattedMine("Mine is no longer linked to " + ChatColor.RED + curMine.getParent());
curMine.setParent(null);
} else { getHelp(); return true; }
} else {
Mine parentMine = Mine.get(args[1]);
if(parentMine == null) { Message.sendFormattedError(language.ERROR_MINENAME); return false; }
if(parentMine.getId().equalsIgnoreCase(curMine.getId())) { Message.sendFormattedError("The mine cannot be a parent of itself"); return false; }
if(parentMine.hasParent() && parentMine.getSuperParent().getId().equalsIgnoreCase(curMine.getId())) { Message.sendFormattedError("Looping structure detected!"); return false; }
curMine.setParent(args[1]);
Message.sendFormattedMine("Mine is now linked to " + ChatColor.GREEN + args[1]);
}
return curMine.saveFile();
} else if(args[0].equalsIgnoreCase("setwarp")) {
if(args.length != 1) { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
curMine.setTpPoint(((Player) CommandManager.getSender()).getLocation());
Message.sendFormattedMine("Mine tp point is set to your current location");
return curMine.saveFile();
} else if(args[0].equalsIgnoreCase("delete") || args[0].equalsIgnoreCase("del")) {
if(args.length == 1 && curMine == null) { getHelp(); return true; }
if(args.length > 2) { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
if(args.length != 1) {
curMine = Mine.get(args[1]);
if(curMine == null) { Message.sendFormattedError(language.ERROR_MINENAME); return false; }
}
for(Mine child : curMine.getChildren()) { child.setParent(null); }
for(TimedTask task : PrisonSuite.getLocalTasks()) {
if(task.getName().endsWith(curMine.getId())) task.cancel();
}
PrisonMine.removeMine(curMine);
PrisonMine.setCurMine(curMine);
Message.sendFormattedMine("Mine successfully deleted");
PrisonMine.setCurMine(null);
curMine.deleteFile();
MineData.saveAll();
return true;
} else {
Message.sendFormattedError(language.ERROR_COMMAND);
return false;
}
}
@Override
public void getHelp() {
Message.formatHeader(20, "Editing");
Message.formatHelp("edit", "<id>", "Selects a mine to edit its properties");
Message.formatHelp("edit", "", "Deselects the current mine");
Message.formatHelp("+", "<block> [percentage]", "Adds a block type to the mine");
Message.formatHelp("-", "<block> [percentage]", "Removes the block from the mine");
Message.formatHelp("name", "<name>", "Sets a display name for a mine. Spaces allowed");
Message.formatHelp("cooldown", "", "Toggles the reset cooldown");
Message.formatHelp("cooldown <time>", "", "Sets the cooldown time");
Message.formatHelp("setparent", "<id>", "Links the timers of two mines");
Message.formatHelp("setwarp", "", "Sets the teleportation point for the mine");
Message.formatHelp("delete", "[id]", "Deletes all the mine data");
return;
}
@Override
public void getHelpLine() { Message.formatHelp("edit help", "", "Shows a help page on mine attribute editing", "prison.mine.edit"); }
}
| true | true | public boolean run(String[] args) {
Language language = PrisonMine.getLanguage();
Mine curMine = PrisonMine.getCurMine();
if(curMine == null
&& !args[0].equalsIgnoreCase("edit")
&& !args[0].equalsIgnoreCase("delete")) {
Message.sendFormattedError(language.ERROR_MINENOTSELECTED);
return false;
}
if(args[0].equalsIgnoreCase("edit")) {
if(args.length == 1) {
if(PrisonMine.getCurMine() != null) {
Message.sendFormattedSuccess(language.MINE_DESELECTED);
PrisonMine.setCurMine(null);
return true;
} else { getHelp(); return true; }
} else if(args.length == 2) {
if(args[1].equalsIgnoreCase("help")) { getHelp(); return true; }
curMine = Mine.get(args[1]);
if(curMine == null) { Message.sendFormattedError(language.ERROR_MINENAME.replace("<ID>", args[1])); return false; }
PrisonMine.setCurMine(curMine);
Message.sendFormattedSuccess(language.MINE_SELECTED);
return true;
} else { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
} else if(args[0].equalsIgnoreCase("add") || args[0].equalsIgnoreCase("+")) {
if(args.length == 1) { getHelp(); return true; }
if(args.length > 3) { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
List<MineBlock> localBlocks = curMine.getLocalBlocks();
if(localBlocks.size() == 0) curMine.addBlock(new MaterialData(Material.AIR), 1);
MaterialData block = Util.getBlock(args[1]);
MineBlock air = curMine.getBlock(new MaterialData(Material.AIR));
if(block == null) { Message.sendFormattedError(language.ERROR_NOSUCHBLOCK.replaceAll("<BLOCK>", args[1])); return false; }
if(block.equals(air.getBlock())) { Message.sendFormattedError(language.ERROR_FUCKIGNNOOB); return false; }
double percent, percentAvailable = air.getChance();
if(args.length == 3) {
if(Util.isNumeric(args[2])) percent = Double.parseDouble(args[2]);
else {
try { percent = Double.parseDouble(args[2].replace("%", "")); }
catch(NumberFormatException nfe) { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
}
percent = percent / 100;
}
else percent = percentAvailable;
if(percent <= 0) { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
DecimalFormat dFormat = new DecimalFormat("#.########");
percent = Double.valueOf(dFormat.format(percent));
if((percentAvailable - percent) < 0) { Message.sendFormattedError("Invalid percentage. Use /mine info " + curMine.getId() + " to review the percentages"); return false; }
else percentAvailable -= percent;
air.setChance(percentAvailable);
MineBlock index = curMine.getBlock(block);
if(index == null) curMine.addBlock(block, percent);
else index.setChance(index.getChance() + percent);
Message.sendFormattedMine(Util.formatPercent(percent)+ " of " + block.getItemType().toString().toLowerCase().replace("_", " ") + " added to the mine");
Message.sendFormattedMine("Reset the mine for the changes to take effect");
return curMine.saveFile();
} else if(args[0].equalsIgnoreCase("remove") || args[0].equalsIgnoreCase("-")) {
if(args.length == 1) { getHelp(); return true; }
if(args.length > 3) { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
MineBlock blockData = curMine.getBlock(Util.getBlock(args[1]));
if(blockData == null) { Message.sendFormattedError("There is no " + ChatColor.RED + args[1] + ChatColor.WHITE + " in mine '" + curMine.getId() + "'"); return false; }
MineBlock air = curMine.getBlock(new MaterialData(Material.AIR));
if(blockData.getBlock().equals(air.getBlock())) { Message.sendFormattedError(language.ERROR_FUCKIGNNOOB); return false; }
double percent = 0;
if(args.length == 3) {
if(Util.isNumeric(args[2])) percent = Double.parseDouble(args[2]);
else {
try { percent = Double.parseDouble(args[2].replace("%", "")); }
catch(NumberFormatException nfe) { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
}
percent = percent / 100;
if(percent > blockData.getChance()) percent = blockData.getChance();
air.setChance(air.getChance() + percent);
blockData.setChance(blockData.getChance() - percent);
Message.sendFormattedMine(Util.formatPercent(percent) + " of " + args[1] + " was successfully removed from the mine");
}
else {
air.setChance(air.getChance() + blockData.getChance());
curMine.removeBlock(blockData);
Message.sendFormattedMine(args[1] + " was successfully removed from the mine");
}
return curMine.saveFile();
} else if(args[0].equalsIgnoreCase("name")) {
if(args.length == 1) {
curMine.setName("");
Message.sendFormattedMine("Mine display name has been cleared");
return true;
}
if(args.length < 2) { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
String name = args[1];
for(int i = 2; i < args.length; i++) name = name + " " + args[i];
curMine.setName(name);
Message.sendFormattedMine("Mine now has a display name '" + ChatColor.GOLD + name + ChatColor.WHITE + "'");
return curMine.saveFile();
} else if(args[0].equalsIgnoreCase("cooldown")) {
if(args.length > 2) { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
if(args.length == 1) {
if(curMine.getCooldown()) {
curMine.setCooldownEnabled(false);
Message.sendFormattedMine("Reset cooldown " + ChatColor.RED + "disabled");
}
else {
curMine.setCooldownEnabled(true);
Message.sendFormattedMine("Reset cooldown " + ChatColor.GREEN + "enabled");
}
} else if(args.length == 2) {
int seconds = Util.timeToSeconds(args[1]);
if(seconds == -1) { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
curMine.setCooldownPeriod(seconds);
Message.sendFormattedMine("Reset cooldown set to " + ChatColor.GREEN + Util.secondsToTime(seconds));
} else { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
return curMine.saveFile();
} else if(args[0].equalsIgnoreCase("setparent") || args[0].equalsIgnoreCase("link")) {
if(args.length > 2) { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
if(args.length == 1) {
if(curMine.getParent() != null) {
Message.sendFormattedMine("Mine is no longer linked to " + ChatColor.RED + curMine.getParent());
curMine.setParent(null);
} else { getHelp(); return true; }
} else {
Mine parentMine = Mine.get(args[1]);
if(parentMine == null) { Message.sendFormattedError(language.ERROR_MINENAME); return false; }
if(parentMine.getId().equalsIgnoreCase(curMine.getId())) { Message.sendFormattedError("The mine cannot be a parent of itself"); return false; }
if(parentMine.hasParent() && parentMine.getSuperParent().getId().equalsIgnoreCase(curMine.getId())) { Message.sendFormattedError("Looping structure detected!"); return false; }
curMine.setParent(args[1]);
Message.sendFormattedMine("Mine is now linked to " + ChatColor.GREEN + args[1]);
}
return curMine.saveFile();
} else if(args[0].equalsIgnoreCase("setwarp")) {
if(args.length != 1) { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
curMine.setTpPoint(((Player) CommandManager.getSender()).getLocation());
Message.sendFormattedMine("Mine tp point is set to your current location");
return curMine.saveFile();
} else if(args[0].equalsIgnoreCase("delete") || args[0].equalsIgnoreCase("del")) {
if(args.length == 1 && curMine == null) { getHelp(); return true; }
if(args.length > 2) { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
if(args.length != 1) {
curMine = Mine.get(args[1]);
if(curMine == null) { Message.sendFormattedError(language.ERROR_MINENAME); return false; }
}
for(Mine child : curMine.getChildren()) { child.setParent(null); }
for(TimedTask task : PrisonSuite.getLocalTasks()) {
if(task.getName().endsWith(curMine.getId())) task.cancel();
}
PrisonMine.removeMine(curMine);
PrisonMine.setCurMine(curMine);
Message.sendFormattedMine("Mine successfully deleted");
PrisonMine.setCurMine(null);
curMine.deleteFile();
MineData.saveAll();
return true;
} else {
Message.sendFormattedError(language.ERROR_COMMAND);
return false;
}
}
| public boolean run(String[] args) {
Language language = PrisonMine.getLanguage();
Mine curMine = PrisonMine.getCurMine();
if(curMine == null
&& !args[0].equalsIgnoreCase("edit")
&& !args[0].equalsIgnoreCase("delete")) {
Message.sendFormattedError(language.ERROR_MINENOTSELECTED);
return false;
}
if(args[0].equalsIgnoreCase("edit")) {
if(args.length == 1) {
if(PrisonMine.getCurMine() != null) {
Message.sendFormattedSuccess(language.MINE_DESELECTED);
PrisonMine.setCurMine(null);
return true;
} else { getHelp(); return true; }
} else if(args.length == 2) {
if(args[1].equalsIgnoreCase("help")) { getHelp(); return true; }
curMine = Mine.get(args[1]);
if(curMine == null) { Message.sendFormattedError(language.ERROR_MINENAME.replace("<ID>", args[1])); return false; }
PrisonMine.setCurMine(curMine);
Message.sendFormattedSuccess(language.MINE_SELECTED);
return true;
} else { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
} else if(args[0].equalsIgnoreCase("add") || args[0].equalsIgnoreCase("+")) {
if(args.length == 1) { getHelp(); return true; }
if(args.length > 3) { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
List<MineBlock> localBlocks = curMine.getLocalBlocks();
if(localBlocks.size() == 0) curMine.addBlock(new MaterialData(Material.AIR), 1);
MaterialData block = Util.getBlock(args[1]);
MineBlock air = curMine.getBlock(new MaterialData(Material.AIR));
if(block == null) { Message.sendFormattedError(language.ERROR_NOSUCHBLOCK.replaceAll("<BLOCK>", args[1])); return false; }
if(block.equals(air.getBlock())) { Message.sendFormattedError(language.ERROR_FUCKIGNNOOB); return false; }
double percent, percentAvailable = air.getChance();
if(args.length == 3) {
if(Util.isNumeric(args[2])) percent = Double.parseDouble(args[2]);
else {
try { percent = Double.parseDouble(args[2].replace("%", "")); }
catch(NumberFormatException nfe) { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
}
percent = percent / 100;
}
else percent = percentAvailable;
if(percent <= 0) { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
DecimalFormat dFormat = new DecimalFormat("#.########");
percent = Double.valueOf(dFormat.format(percent));
if((percentAvailable - percent) < 0) { Message.sendFormattedError("Invalid percentage. Use /mine info " + curMine.getId() + " to review the percentages"); return false; }
else percentAvailable -= percent;
air.setChance(Double.valueOf(dFormat.format(percentAvailable)));
MineBlock index = curMine.getBlock(block);
if(index == null) curMine.addBlock(block, percent);
else index.setChance(index.getChance() + percent);
Message.sendFormattedMine(Util.formatPercent(percent)+ " of " + block.getItemType().toString().toLowerCase().replace("_", " ") + " added to the mine");
Message.sendFormattedMine("Reset the mine for the changes to take effect");
return curMine.saveFile();
} else if(args[0].equalsIgnoreCase("remove") || args[0].equalsIgnoreCase("-")) {
if(args.length == 1) { getHelp(); return true; }
if(args.length > 3) { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
MineBlock blockData = curMine.getBlock(Util.getBlock(args[1]));
if(blockData == null) { Message.sendFormattedError("There is no " + ChatColor.RED + args[1] + ChatColor.WHITE + " in mine '" + curMine.getId() + "'"); return false; }
MineBlock air = curMine.getBlock(new MaterialData(Material.AIR));
if(blockData.getBlock().equals(air.getBlock())) { Message.sendFormattedError(language.ERROR_FUCKIGNNOOB); return false; }
double percent = 0;
if(args.length == 3) {
if(Util.isNumeric(args[2])) percent = Double.parseDouble(args[2]);
else {
try { percent = Double.parseDouble(args[2].replace("%", "")); }
catch(NumberFormatException nfe) { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
}
percent = percent / 100;
if(percent > blockData.getChance()) percent = blockData.getChance();
air.setChance(air.getChance() + percent);
blockData.setChance(blockData.getChance() - percent);
Message.sendFormattedMine(Util.formatPercent(percent) + " of " + args[1] + " was successfully removed from the mine");
}
else {
air.setChance(air.getChance() + blockData.getChance());
curMine.removeBlock(blockData);
Message.sendFormattedMine(args[1] + " was successfully removed from the mine");
}
return curMine.saveFile();
} else if(args[0].equalsIgnoreCase("name")) {
if(args.length == 1) {
curMine.setName("");
Message.sendFormattedMine("Mine display name has been cleared");
return true;
}
if(args.length < 2) { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
String name = args[1];
for(int i = 2; i < args.length; i++) name = name + " " + args[i];
curMine.setName(name);
Message.sendFormattedMine("Mine now has a display name '" + ChatColor.GOLD + name + ChatColor.WHITE + "'");
return curMine.saveFile();
} else if(args[0].equalsIgnoreCase("cooldown")) {
if(args.length > 2) { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
if(args.length == 1) {
if(curMine.getCooldown()) {
curMine.setCooldownEnabled(false);
Message.sendFormattedMine("Reset cooldown " + ChatColor.RED + "disabled");
}
else {
curMine.setCooldownEnabled(true);
Message.sendFormattedMine("Reset cooldown " + ChatColor.GREEN + "enabled");
}
} else if(args.length == 2) {
int seconds = Util.timeToSeconds(args[1]);
if(seconds == -1) { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
curMine.setCooldownPeriod(seconds);
Message.sendFormattedMine("Reset cooldown set to " + ChatColor.GREEN + Util.secondsToTime(seconds));
} else { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
return curMine.saveFile();
} else if(args[0].equalsIgnoreCase("setparent") || args[0].equalsIgnoreCase("link")) {
if(args.length > 2) { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
if(args.length == 1) {
if(curMine.getParent() != null) {
Message.sendFormattedMine("Mine is no longer linked to " + ChatColor.RED + curMine.getParent());
curMine.setParent(null);
} else { getHelp(); return true; }
} else {
Mine parentMine = Mine.get(args[1]);
if(parentMine == null) { Message.sendFormattedError(language.ERROR_MINENAME); return false; }
if(parentMine.getId().equalsIgnoreCase(curMine.getId())) { Message.sendFormattedError("The mine cannot be a parent of itself"); return false; }
if(parentMine.hasParent() && parentMine.getSuperParent().getId().equalsIgnoreCase(curMine.getId())) { Message.sendFormattedError("Looping structure detected!"); return false; }
curMine.setParent(args[1]);
Message.sendFormattedMine("Mine is now linked to " + ChatColor.GREEN + args[1]);
}
return curMine.saveFile();
} else if(args[0].equalsIgnoreCase("setwarp")) {
if(args.length != 1) { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
curMine.setTpPoint(((Player) CommandManager.getSender()).getLocation());
Message.sendFormattedMine("Mine tp point is set to your current location");
return curMine.saveFile();
} else if(args[0].equalsIgnoreCase("delete") || args[0].equalsIgnoreCase("del")) {
if(args.length == 1 && curMine == null) { getHelp(); return true; }
if(args.length > 2) { Message.sendFormattedError(language.ERROR_ARGUMENTS); return false; }
if(args.length != 1) {
curMine = Mine.get(args[1]);
if(curMine == null) { Message.sendFormattedError(language.ERROR_MINENAME); return false; }
}
for(Mine child : curMine.getChildren()) { child.setParent(null); }
for(TimedTask task : PrisonSuite.getLocalTasks()) {
if(task.getName().endsWith(curMine.getId())) task.cancel();
}
PrisonMine.removeMine(curMine);
PrisonMine.setCurMine(curMine);
Message.sendFormattedMine("Mine successfully deleted");
PrisonMine.setCurMine(null);
curMine.deleteFile();
MineData.saveAll();
return true;
} else {
Message.sendFormattedError(language.ERROR_COMMAND);
return false;
}
}
|
diff --git a/src/CS565/RationalTestRun.java b/src/CS565/RationalTestRun.java
index dfa08dd..4a4c6fd 100644
--- a/src/CS565/RationalTestRun.java
+++ b/src/CS565/RationalTestRun.java
@@ -1,58 +1,58 @@
package CS565;
public class RationalTestRun {
public static void main(String[] args) {
// default ctor returns 1/1
Rational r = new Rational();
- puts("default ctor returns 1/1: "+ r.toFractionString() + " or " + r.toFloatString());
+ puts("default ctor returns 1/1: \n\t"+ r.toFractionString() + " or " + r.toFloatString());
// constructor can take numerator, denominator to initialize
Rational half = new Rational(1, 2);
- puts("ctor takes numerator, denominator to initialize: new Rational(1, 2) == "+ half.toFractionString() + " or " + half.toFloatString());
+ puts("ctor takes numerator, denominator to initialize: \n\tnew Rational(1, 2) == "+ half.toFractionString() + " or " + half.toFloatString());
// we can print the value as a fraction
- puts("we can print the value as a fraction: new Rational(1, 2) == "+ half.toFractionString());
+ puts("we can print the value as a fraction: \n\tnew Rational(1, 2) == "+ half.toFractionString());
// we can print the value as a float
- puts("we can print the value as a float: new Rational(1, 2) == "+ half.toFloatString());
+ puts("we can print the value as a float: \n\tnew Rational(1, 2) == "+ half.toFloatString());
// we can specify number of decimals when printing float
- puts("we can specify number of decimals when printing float: new Rational(1, 2).toFloat(4) == "+ half.toFloatString(4));
+ puts("we can specify number of decimals when printing float: \n\tnew Rational(1, 2).toFloat(4) == "+ half.toFloatString(4));
// it is automatically reduced when initialized
Rational third = new Rational(17, 51);
- puts("it is automatically reduced when initialized: new Rational(17, 51) == "+ new Rational(17, 51).toFractionString());
+ puts("it is automatically reduced when initialized: \n\tnew Rational(17, 51) == "+ new Rational(17, 51).toFractionString());
// we can add two rationals to produce a new rational
- puts("we can add two rationals to produce a new rational: 1/2 plus 1/3 == "+ Rational.add(half, third).toFractionString());
+ puts("we can add two rationals to produce a new rational: \n\t1/2 plus 1/3 == "+ Rational.add(half, third).toFractionString());
// Add is commutative
- puts("add is commutative: 1/3 + 1/2 == "+ Rational.add(third, half).toFractionString());
+ puts("add is commutative: \n\t1/3 + 1/2 == "+ Rational.add(third, half).toFractionString());
// we can subtract two rationals
- puts("we can subtract two rationals: 1/2 - 1/3 == "+ Rational.subtract(half, third).toFractionString());
+ puts("we can subtract two rationals: \n\t1/2 - 1/3 == "+ Rational.subtract(half, third).toFractionString());
// we can multiply two rationals to produce a new rational
Rational quarter = new Rational(1, 4);
- puts("we can multiply two rationals to produce a new rational: 1/4 * 1/3 == "+ Rational.multiply(quarter, third).toFractionString());
+ puts("we can multiply two rationals to produce a new rational: \n\t1/4 * 1/3 == "+ Rational.multiply(quarter, third).toFractionString());
// we can divide two rationals
- puts("we can divide two rationals: 1/4 / 1/3 == "+ Rational.divide(quarter, third).toFractionString());
+ puts("we can divide two rationals: \n\t1/4 / 1/3 == "+ Rational.divide(quarter, third).toFractionString());
// divide by zero is handled
puts("divide by zero is handled:");
Rational zero = new Rational(0, 1);
try {
Rational.divide(quarter, zero);
} catch (RuntimeException ex) {
puts("\tthrew and handled exception since divide by zero occured");
}
}
// shortcut functions to simplify and shorten above code
private static void puts(String out) {
System.out.println(out + "\n");
}
}
| false | true | public static void main(String[] args) {
// default ctor returns 1/1
Rational r = new Rational();
puts("default ctor returns 1/1: "+ r.toFractionString() + " or " + r.toFloatString());
// constructor can take numerator, denominator to initialize
Rational half = new Rational(1, 2);
puts("ctor takes numerator, denominator to initialize: new Rational(1, 2) == "+ half.toFractionString() + " or " + half.toFloatString());
// we can print the value as a fraction
puts("we can print the value as a fraction: new Rational(1, 2) == "+ half.toFractionString());
// we can print the value as a float
puts("we can print the value as a float: new Rational(1, 2) == "+ half.toFloatString());
// we can specify number of decimals when printing float
puts("we can specify number of decimals when printing float: new Rational(1, 2).toFloat(4) == "+ half.toFloatString(4));
// it is automatically reduced when initialized
Rational third = new Rational(17, 51);
puts("it is automatically reduced when initialized: new Rational(17, 51) == "+ new Rational(17, 51).toFractionString());
// we can add two rationals to produce a new rational
puts("we can add two rationals to produce a new rational: 1/2 plus 1/3 == "+ Rational.add(half, third).toFractionString());
// Add is commutative
puts("add is commutative: 1/3 + 1/2 == "+ Rational.add(third, half).toFractionString());
// we can subtract two rationals
puts("we can subtract two rationals: 1/2 - 1/3 == "+ Rational.subtract(half, third).toFractionString());
// we can multiply two rationals to produce a new rational
Rational quarter = new Rational(1, 4);
puts("we can multiply two rationals to produce a new rational: 1/4 * 1/3 == "+ Rational.multiply(quarter, third).toFractionString());
// we can divide two rationals
puts("we can divide two rationals: 1/4 / 1/3 == "+ Rational.divide(quarter, third).toFractionString());
// divide by zero is handled
puts("divide by zero is handled:");
Rational zero = new Rational(0, 1);
try {
Rational.divide(quarter, zero);
} catch (RuntimeException ex) {
puts("\tthrew and handled exception since divide by zero occured");
}
}
| public static void main(String[] args) {
// default ctor returns 1/1
Rational r = new Rational();
puts("default ctor returns 1/1: \n\t"+ r.toFractionString() + " or " + r.toFloatString());
// constructor can take numerator, denominator to initialize
Rational half = new Rational(1, 2);
puts("ctor takes numerator, denominator to initialize: \n\tnew Rational(1, 2) == "+ half.toFractionString() + " or " + half.toFloatString());
// we can print the value as a fraction
puts("we can print the value as a fraction: \n\tnew Rational(1, 2) == "+ half.toFractionString());
// we can print the value as a float
puts("we can print the value as a float: \n\tnew Rational(1, 2) == "+ half.toFloatString());
// we can specify number of decimals when printing float
puts("we can specify number of decimals when printing float: \n\tnew Rational(1, 2).toFloat(4) == "+ half.toFloatString(4));
// it is automatically reduced when initialized
Rational third = new Rational(17, 51);
puts("it is automatically reduced when initialized: \n\tnew Rational(17, 51) == "+ new Rational(17, 51).toFractionString());
// we can add two rationals to produce a new rational
puts("we can add two rationals to produce a new rational: \n\t1/2 plus 1/3 == "+ Rational.add(half, third).toFractionString());
// Add is commutative
puts("add is commutative: \n\t1/3 + 1/2 == "+ Rational.add(third, half).toFractionString());
// we can subtract two rationals
puts("we can subtract two rationals: \n\t1/2 - 1/3 == "+ Rational.subtract(half, third).toFractionString());
// we can multiply two rationals to produce a new rational
Rational quarter = new Rational(1, 4);
puts("we can multiply two rationals to produce a new rational: \n\t1/4 * 1/3 == "+ Rational.multiply(quarter, third).toFractionString());
// we can divide two rationals
puts("we can divide two rationals: \n\t1/4 / 1/3 == "+ Rational.divide(quarter, third).toFractionString());
// divide by zero is handled
puts("divide by zero is handled:");
Rational zero = new Rational(0, 1);
try {
Rational.divide(quarter, zero);
} catch (RuntimeException ex) {
puts("\tthrew and handled exception since divide by zero occured");
}
}
|
diff --git a/ananya-reference-data-flw/src/test/java/org/motechproject/ananya/referencedata/flw/repository/AllSyncJobsTest.java b/ananya-reference-data-flw/src/test/java/org/motechproject/ananya/referencedata/flw/repository/AllSyncJobsTest.java
index 4aa0dc5..1a8f449 100644
--- a/ananya-reference-data-flw/src/test/java/org/motechproject/ananya/referencedata/flw/repository/AllSyncJobsTest.java
+++ b/ananya-reference-data-flw/src/test/java/org/motechproject/ananya/referencedata/flw/repository/AllSyncJobsTest.java
@@ -1,37 +1,37 @@
package org.motechproject.ananya.referencedata.flw.repository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.motechproject.ananya.referencedata.flw.domain.jobs.FrontLineWorkerSyncJob;
import org.motechproject.model.CronSchedulableJob;
import org.motechproject.scheduler.MotechSchedulerService;
import java.util.Properties;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class AllSyncJobsTest {
@Mock
private MotechSchedulerService schedulerService;
@Mock
private Properties referenceDataProperteies;
@Test
public void shouldScheduleJobToAddFLWToQueue() {
AllSyncJobs allSyncJobs = new AllSyncJobs(schedulerService, referenceDataProperteies);
- when(referenceDataProperteies.get("cronExpression")).thenReturn("* * * * *");
+ when(referenceDataProperteies.get("scheduler.cron.expression")).thenReturn("* * * * * ?");
allSyncJobs.addFrontLineWorkerSyncJob();
ArgumentCaptor<CronSchedulableJob> captor = ArgumentCaptor.forClass(CronSchedulableJob.class);
verify(schedulerService).safeScheduleJob(captor.capture());
assertEquals(FrontLineWorkerSyncJob.class, captor.getValue().getClass());
}
}
| true | true | public void shouldScheduleJobToAddFLWToQueue() {
AllSyncJobs allSyncJobs = new AllSyncJobs(schedulerService, referenceDataProperteies);
when(referenceDataProperteies.get("cronExpression")).thenReturn("* * * * *");
allSyncJobs.addFrontLineWorkerSyncJob();
ArgumentCaptor<CronSchedulableJob> captor = ArgumentCaptor.forClass(CronSchedulableJob.class);
verify(schedulerService).safeScheduleJob(captor.capture());
assertEquals(FrontLineWorkerSyncJob.class, captor.getValue().getClass());
}
| public void shouldScheduleJobToAddFLWToQueue() {
AllSyncJobs allSyncJobs = new AllSyncJobs(schedulerService, referenceDataProperteies);
when(referenceDataProperteies.get("scheduler.cron.expression")).thenReturn("* * * * * ?");
allSyncJobs.addFrontLineWorkerSyncJob();
ArgumentCaptor<CronSchedulableJob> captor = ArgumentCaptor.forClass(CronSchedulableJob.class);
verify(schedulerService).safeScheduleJob(captor.capture());
assertEquals(FrontLineWorkerSyncJob.class, captor.getValue().getClass());
}
|
diff --git a/hazelcast-client/src/main/java/com/hazelcast/client/connection/SmartClientConnectionManager.java b/hazelcast-client/src/main/java/com/hazelcast/client/connection/SmartClientConnectionManager.java
index 3ea83f3ad8..ff0daf3b61 100644
--- a/hazelcast-client/src/main/java/com/hazelcast/client/connection/SmartClientConnectionManager.java
+++ b/hazelcast-client/src/main/java/com/hazelcast/client/connection/SmartClientConnectionManager.java
@@ -1,231 +1,229 @@
/*
* Copyright (c) 2008-2013, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.client.connection;
import com.hazelcast.client.ClientTypes;
import com.hazelcast.client.HazelcastClient;
import com.hazelcast.client.LoadBalancer;
import com.hazelcast.client.config.ClientConfig;
import com.hazelcast.client.config.SocketOptions;
import com.hazelcast.client.util.Destructor;
import com.hazelcast.client.util.Factory;
import com.hazelcast.client.util.ObjectPool;
import com.hazelcast.client.util.QueueBasedObjectPool;
import com.hazelcast.core.HazelcastInstanceNotActiveException;
import com.hazelcast.logging.ILogger;
import com.hazelcast.logging.Logger;
import com.hazelcast.nio.Address;
import com.hazelcast.nio.IOUtil;
import com.hazelcast.nio.Protocols;
import com.hazelcast.nio.SocketInterceptor;
import com.hazelcast.nio.serialization.Data;
import com.hazelcast.util.ConstructorFunction;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
public class SmartClientConnectionManager implements ClientConnectionManager {
private static final ILogger logger = Logger.getLogger(ClientConnectionManager.class);
private final int poolSize;
private final Authenticator authenticator;
private final HazelcastClient client;
private final Router router;
private final ConcurrentMap<Address, ObjectPool<ConnectionWrapper>> poolMap
= new ConcurrentHashMap<Address, ObjectPool<ConnectionWrapper>>(16, 0.75f, 1);
private final SocketOptions socketOptions;
private final SocketInterceptor socketInterceptor;
private final HeartBeatChecker heartbeat;
private volatile boolean live = true;
public SmartClientConnectionManager(HazelcastClient client, Authenticator authenticator, LoadBalancer loadBalancer) {
this.authenticator = authenticator;
this.client = client;
ClientConfig config = client.getClientConfig();
router = new Router(loadBalancer);
socketInterceptor = config.getSocketInterceptor();
poolSize = config.getConnectionPoolSize();
int connectionTimeout = config.getConnectionTimeout();
heartbeat = new HeartBeatChecker(connectionTimeout, client.getSerializationService(), client.getClientExecutionService());
socketOptions = config.getSocketOptions();
}
public Connection firstConnection(Address address, Authenticator authenticator) throws IOException {
return newConnection(address, authenticator);
}
public Connection newConnection(Address address, Authenticator authenticator) throws IOException {
checkLive();
final ConnectionImpl connection = new ConnectionImpl(address, socketOptions, client.getSerializationService());
connection.write(Protocols.CLIENT_BINARY.getBytes());
connection.write(ClientTypes.JAVA.getBytes());
if (socketInterceptor != null) {
socketInterceptor.onConnect(connection.getSocket());
}
authenticator.auth(connection);
return connection;
}
public Connection getRandomConnection() throws IOException {
checkLive();
final Address address = router.next();
if (address == null) {
throw new IOException("LoadBalancer '" + router + "' could not find a address to route to");
}
return getConnection(address);
}
public Connection getConnection(Address address) throws IOException {
checkLive();
if (address == null) {
throw new IllegalArgumentException("Target address is required!");
}
final ObjectPool<ConnectionWrapper> pool = getConnectionPool(address);
if (pool == null){
return null;
}
Connection connection = null;
try {
connection = pool.take();
} catch (Exception e) {
if (logger.isFinestEnabled()) {
logger.warning("Error during connection creation... To -> " + address, e);
- } else {
- logger.warning("Error during connection creation... To -> " + address + ", Error: " + e.toString());
}
}
// Could be that this address is dead and that's why pool is not able to create and give a connection.
// We will call it again, and hopefully at some time LoadBalancer will give us the right target for the connection.
if (connection != null && !heartbeat.checkHeartBeat(connection)) {
logger.warning(connection + " failed to heartbeat, closing...");
connection.close();
connection = null;
}
return connection;
}
private void checkLive() {
if (!live) {
throw new HazelcastInstanceNotActiveException();
}
}
private final ConstructorFunction<Address, ObjectPool<ConnectionWrapper>> ctor = new ConstructorFunction<Address, ObjectPool<ConnectionWrapper>>() {
public ObjectPool<ConnectionWrapper> createNew(final Address address) {
return new QueueBasedObjectPool<ConnectionWrapper>(poolSize, new Factory<ConnectionWrapper>() {
public ConnectionWrapper create() throws IOException {
return new ConnectionWrapper(newConnection(address, authenticator));
}
}, new Destructor<ConnectionWrapper>() {
public void destroy(ConnectionWrapper connection) {
connection.close();
}
}
);
}
};
private ObjectPool<ConnectionWrapper> getConnectionPool(final Address address) {
checkLive();
ObjectPool<ConnectionWrapper> pool = poolMap.get(address);
if (pool == null) {
if (client.getClientClusterService().getMember(address) == null){
return null;
}
pool = ctor.createNew(address);
ObjectPool<ConnectionWrapper> current = poolMap.putIfAbsent(address, pool);
pool = current == null ? pool : current;
}
return pool;
}
private class ConnectionWrapper implements Connection {
final Connection connection;
private ConnectionWrapper(Connection connection) {
this.connection = connection;
}
public Address getEndpoint() {
return connection.getEndpoint();
}
public boolean write(Data data) throws IOException {
return connection.write(data);
}
public Data read() throws IOException {
return connection.read();
}
public void release() throws IOException {
releaseConnection(this);
}
public void close() {
logger.info("Closing connection -> " + connection);
IOUtil.closeResource(connection);
}
public int getId() {
return connection.getId();
}
public long getLastReadTime() {
return connection.getLastReadTime();
}
public void setEndpoint(Address address) {
connection.setEndpoint(address);
}
public String toString() {
return connection.toString();
}
}
private void releaseConnection(ConnectionWrapper connection) {
if (live) {
final ObjectPool<ConnectionWrapper> pool = poolMap.get(connection.getEndpoint());
if (pool != null) {
pool.release(connection);
} else {
connection.close();
}
} else {
connection.close();
}
}
public void removeConnectionPool(Address address){
ObjectPool<ConnectionWrapper> pool = poolMap.remove(address);
if (pool != null){
pool.destroy();
}
}
public void shutdown() {
live = false;
for (ObjectPool<ConnectionWrapper> pool : poolMap.values()) {
pool.destroy();
}
poolMap.clear();
}
}
| true | true | public Connection getConnection(Address address) throws IOException {
checkLive();
if (address == null) {
throw new IllegalArgumentException("Target address is required!");
}
final ObjectPool<ConnectionWrapper> pool = getConnectionPool(address);
if (pool == null){
return null;
}
Connection connection = null;
try {
connection = pool.take();
} catch (Exception e) {
if (logger.isFinestEnabled()) {
logger.warning("Error during connection creation... To -> " + address, e);
} else {
logger.warning("Error during connection creation... To -> " + address + ", Error: " + e.toString());
}
}
// Could be that this address is dead and that's why pool is not able to create and give a connection.
// We will call it again, and hopefully at some time LoadBalancer will give us the right target for the connection.
if (connection != null && !heartbeat.checkHeartBeat(connection)) {
logger.warning(connection + " failed to heartbeat, closing...");
connection.close();
connection = null;
}
return connection;
}
| public Connection getConnection(Address address) throws IOException {
checkLive();
if (address == null) {
throw new IllegalArgumentException("Target address is required!");
}
final ObjectPool<ConnectionWrapper> pool = getConnectionPool(address);
if (pool == null){
return null;
}
Connection connection = null;
try {
connection = pool.take();
} catch (Exception e) {
if (logger.isFinestEnabled()) {
logger.warning("Error during connection creation... To -> " + address, e);
}
}
// Could be that this address is dead and that's why pool is not able to create and give a connection.
// We will call it again, and hopefully at some time LoadBalancer will give us the right target for the connection.
if (connection != null && !heartbeat.checkHeartBeat(connection)) {
logger.warning(connection + " failed to heartbeat, closing...");
connection.close();
connection = null;
}
return connection;
}
|
diff --git a/test/com/eteks/sweethome3d/junit/ImportedTextureWizardTest.java b/test/com/eteks/sweethome3d/junit/ImportedTextureWizardTest.java
index 3063821f..ab972836 100644
--- a/test/com/eteks/sweethome3d/junit/ImportedTextureWizardTest.java
+++ b/test/com/eteks/sweethome3d/junit/ImportedTextureWizardTest.java
@@ -1,530 +1,531 @@
/*
* ImportedTextureWizardTest.java 07 Oct. 2008
*
* Copyright (c) 2008 Emmanuel PUYBARET / eTeks <[email protected]>. All Rights Reserved.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place, Suite 330, Boston, MA 02111-1307 USA
*/
package com.eteks.sweethome3d.junit;
import java.awt.Component;
import java.awt.Container;
import java.awt.KeyboardFocusManager;
import java.awt.event.InputEvent;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Locale;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import junit.extensions.abbot.ComponentTestFixture;
import abbot.finder.AWTHierarchy;
import abbot.finder.BasicFinder;
import abbot.finder.ComponentSearchException;
import abbot.finder.Matcher;
import abbot.finder.matchers.ClassMatcher;
import abbot.finder.matchers.WindowMatcher;
import abbot.tester.JComponentTester;
import com.eteks.sweethome3d.io.FileUserPreferences;
import com.eteks.sweethome3d.model.CatalogTexture;
import com.eteks.sweethome3d.model.Content;
import com.eteks.sweethome3d.model.Home;
import com.eteks.sweethome3d.model.LengthUnit;
import com.eteks.sweethome3d.model.RecorderException;
import com.eteks.sweethome3d.model.TexturesCategory;
import com.eteks.sweethome3d.model.UserPreferences;
import com.eteks.sweethome3d.model.Wall;
import com.eteks.sweethome3d.swing.HomePane;
import com.eteks.sweethome3d.swing.ImportedTextureWizardStepsPanel;
import com.eteks.sweethome3d.swing.PlanComponent;
import com.eteks.sweethome3d.swing.SwingViewFactory;
import com.eteks.sweethome3d.swing.TextureChoiceComponent;
import com.eteks.sweethome3d.swing.WallPanel;
import com.eteks.sweethome3d.swing.WizardPane;
import com.eteks.sweethome3d.tools.URLContent;
import com.eteks.sweethome3d.viewcontroller.ContentManager;
import com.eteks.sweethome3d.viewcontroller.HomeController;
import com.eteks.sweethome3d.viewcontroller.ImportedTextureWizardController;
import com.eteks.sweethome3d.viewcontroller.View;
import com.eteks.sweethome3d.viewcontroller.ViewFactory;
import com.eteks.sweethome3d.viewcontroller.WallController;
/**
* Tests imported texture wizard.
* @author Emmanuel Puybaret
*/
public class ImportedTextureWizardTest extends ComponentTestFixture {
public void testImportedTextureWizard() throws ComponentSearchException, InterruptedException,
NoSuchFieldException, IllegalAccessException, InvocationTargetException {
String language = Locale.getDefault().getLanguage();
final UserPreferences preferences = new FileUserPreferences() {
@Override
public boolean isActionTipIgnored(String actionKey) {
return true;
}
};
// Ensure we use default language and centimeter unit
preferences.setLanguage(language);
preferences.setUnit(LengthUnit.CENTIMETER);
ViewFactory viewFactory = new SwingViewFactory();
// Create a dummy content manager
final URL testedImageName = BackgroundImageWizardTest.class.getResource("resources/test.png");
final ContentManager contentManager = new ContentManager() {
public Content getContent(String contentName) throws RecorderException {
try {
// Let's consider contentName is a URL
return new URLContent(new URL(contentName));
} catch (IOException ex) {
fail();
return null;
}
}
public String getPresentationName(String contentName, ContentType contentType) {
return "test";
}
public boolean isAcceptable(String contentName, ContentType contentType) {
return true;
}
public String showOpenDialog(View parentView, String dialogTitle, ContentType contentType) {
// Return tested model name URL
return testedImageName.toString();
}
public String showSaveDialog(View parentView, String dialogTitle, ContentType contentType, String name) {
return null;
}
};
Home home = new Home();
final HomeController controller =
new HomeController(home, preferences, viewFactory, contentManager);
JComponent homeView = (JComponent)controller.getView();
PlanComponent planComponent = (PlanComponent)TestUtilities.findComponent(
homeView, PlanComponent.class);
// 1. Create a frame that displays a home view
JFrame frame = new JFrame("Imported Texture Wizard Test");
frame.add(homeView);
frame.pack();
// Show home plan frame
showWindow(frame);
JComponentTester tester = new JComponentTester();
tester.waitForIdle();
// Transfer focus to plan view
planComponent.requestFocusInWindow();
tester.waitForIdle();
// Check plan view has focus
assertTrue("Plan component doesn't have the focus", planComponent.isFocusOwner());
// 2. Create two wall between points (50, 50), (150, 50) and (150, 150)
runAction(controller, HomePane.ActionType.CREATE_WALLS);
tester.actionClick(planComponent, 50, 50);
tester.actionClick(planComponent, 150, 50);
tester.actionClick(planComponent, 150, 150, InputEvent.BUTTON1_MASK, 2);
runAction(controller, HomePane.ActionType.SELECT);
// Check two walls were created and selected
assertEquals("Wrong wall count in home", 2, home.getWalls().size());
assertEquals("Wrong selected items count in home", 2, home.getSelectedItems().size());
Iterator<Wall> iterator = home.getWalls().iterator();
Wall wall1 = iterator.next();
Wall wall2 = iterator.next();
// Check walls don't use texture yet
assertNull("Wrong texture on wall 1 left side", wall1.getLeftSideTexture());
assertNull("Wrong texture on wall 2 left side", wall2.getLeftSideTexture());
assertNull("Wrong texture on wall 1 right side", wall1.getRightSideTexture());
assertNull("Wrong texture on wall 2 right side", wall2.getRightSideTexture());
// 3. Edit walls
JDialog attributesDialog = showWallPanel(preferences, controller, frame, tester);
// Retrieve WallPanel components
WallPanel wallPanel = (WallPanel)TestUtilities.findComponent(
attributesDialog, WallPanel.class);
JSpinner xStartSpinner =
(JSpinner)TestUtilities.getField(wallPanel, "xStartSpinner");
JSpinner xEndSpinner =
(JSpinner)TestUtilities.getField(wallPanel, "xEndSpinner");
TextureChoiceComponent rightSideTextureComponent =
(TextureChoiceComponent)TestUtilities.getField(wallPanel, "rightSideTextureComponent");
// Check xStartSpinner and xEndSpinner panels aren't visible
assertFalse("X start spinner panel is visible", xStartSpinner.getParent().isVisible());
assertFalse("X end spinner panel is visible", xEndSpinner.getParent().isVisible());
// Edit right side texture
JDialog textureDialog = showTexturePanel(preferences, rightSideTextureComponent, false, attributesDialog, tester);
JList availableTexturesList = (JList)new BasicFinder().find(textureDialog,
new ClassMatcher(JList.class, true));
int textureCount = availableTexturesList.getModel().getSize();
CatalogTexture defaultTexture = (CatalogTexture)availableTexturesList.getSelectedValue();
// Import texture
JDialog textureWizardDialog = showImportTextureWizard(preferences, frame, tester, false);
// Retrieve ImportedFurnitureWizardStepsPanel components
ImportedTextureWizardStepsPanel panel = (ImportedTextureWizardStepsPanel)TestUtilities.findComponent(
textureWizardDialog, ImportedTextureWizardStepsPanel.class);
final JButton imageChoiceOrChangeButton = (JButton)TestUtilities.getField(panel, "imageChoiceOrChangeButton");
final JTextField nameTextField = (JTextField)TestUtilities.getField(panel, "nameTextField");
JComboBox categoryComboBox = (JComboBox)TestUtilities.getField(panel, "categoryComboBox");
JSpinner widthSpinner = (JSpinner)TestUtilities.getField(panel, "widthSpinner");
JSpinner heightSpinner = (JSpinner)TestUtilities.getField(panel, "heightSpinner");
// Check current step is image
tester.waitForIdle();
assertStepShowing(panel, true, false);
WizardPane view = (WizardPane)TestUtilities.findComponent(textureWizardDialog, WizardPane.class);
// Check wizard view next button is disabled
final JButton nextFinishOptionButton = (JButton)TestUtilities.getField(view, "nextFinishOptionButton");
assertFalse("Next button is enabled", nextFinishOptionButton.isEnabled());
// 4. Choose tested image
String imageChoiceOrChangeButtonText = imageChoiceOrChangeButton.getText();
tester.invokeAndWait(new Runnable() {
public void run() {
imageChoiceOrChangeButton.doClick();
}
});
// Wait 200 ms to let time to Java to load the image
Thread.sleep(200);
// Check choice button text changed
assertFalse("Choice button text didn't change",
imageChoiceOrChangeButtonText.equals(imageChoiceOrChangeButton.getText()));
// Click on next button
tester.invokeAndWait(new Runnable() {
public void run() {
nextFinishOptionButton.doClick();
}
});
// Check current step is attributes
assertStepShowing(panel, false, true);
// 5. Check default furniture name is the presentation name proposed by content manager
assertEquals("Wrong default name",
contentManager.getPresentationName(testedImageName.toString(), ContentManager.ContentType.IMAGE),
nameTextField.getText());
// Check name text field has focus
assertSame("Name text field doesn't have focus", nameTextField,
KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner());
// Check default category is user category
String userCategoryName = preferences.getLocalizedString(
ImportedTextureWizardStepsPanel.class, "userCategory");
assertEquals("Wrong default category", userCategoryName,
((TexturesCategory)categoryComboBox.getSelectedItem()).getName());
// Rename texture
final String textureTestName = "#@" + System.currentTimeMillis() + "@#";
tester.invokeAndWait(new Runnable() {
public void run() {
nameTextField.setText(textureTestName);
}
});
// Check next button is enabled again
assertTrue("Next button isn't enabled", nextFinishOptionButton.isEnabled());
// 6. Change width with a value 5 times greater
float width = (Float)widthSpinner.getValue();
float height = (Float)heightSpinner.getValue();
widthSpinner.setValue(width * 5);
// Check height is 5 times greater
float newWidth = (Float)widthSpinner.getValue();
float newHeight = (Float)heightSpinner.getValue();
assertEquals("width", 5 * width, newWidth);
assertEquals("height", 5 * height, newHeight);
tester.invokeAndWait(new Runnable() {
public void run() {
// Click on Finish to hide dialog box in Event Dispatch Thread
nextFinishOptionButton.doClick();
}
});
assertFalse("Import texture wizard still showing", textureWizardDialog.isShowing());
// Check the list of available textures has one more selected modifiable texture
assertEquals("Wrong texture count in list", textureCount + 1, availableTexturesList.getModel().getSize());
assertEquals("No selected texture in list", 1, availableTexturesList.getSelectedValues().length);
CatalogTexture importedTexture = (CatalogTexture)availableTexturesList.getSelectedValue();
assertNotSame("Wrong selected texture in list", defaultTexture, importedTexture);
// Check the attributes of the new texture
assertEquals("Wrong name", textureTestName, importedTexture.getName());
assertEquals("Wrong category", userCategoryName, importedTexture.getCategory().getName());
assertEquals("Wrong width", newWidth, importedTexture.getWidth());
assertEquals("Wrong height", newHeight, importedTexture.getHeight());
assertTrue("New texture isn't modifiable", importedTexture.isModifiable());
// 7. Click on OK in texture dialog box
doClickOnOkInDialog(textureDialog, tester);
// Click on OK in wall dialog box
doClickOnOkInDialog(attributesDialog, tester);
// Check wall attributes are modified accordingly
assertNull("Wrong texture on wall 1 left side", wall1.getLeftSideTexture());
assertNull("Wrong texture on wall 2 left side", wall2.getLeftSideTexture());
assertEquals("Wrong texture on wall 1 right side", textureTestName, wall1.getRightSideTexture().getName());
assertEquals("Wrong texture on wall 2 right side", textureTestName, wall2.getRightSideTexture().getName());
// 8. Edit left side texture of first wall
home.setSelectedItems(Arrays.asList(wall1));
assertEquals("Wrong selected items count in home", 1, home.getSelectedItems().size());
attributesDialog = showWallPanel(preferences, controller, frame, tester);
// Retrieve WallPanel components
wallPanel = (WallPanel)TestUtilities.findComponent(attributesDialog, WallPanel.class);
xStartSpinner = (JSpinner)TestUtilities.getField(wallPanel, "xStartSpinner");
xEndSpinner = (JSpinner)TestUtilities.getField(wallPanel, "xEndSpinner");
TextureChoiceComponent leftSideTextureComponent =
(TextureChoiceComponent)TestUtilities.getField(wallPanel, "leftSideTextureComponent");
// Check xStartSpinner and xEndSpinner panels are visible
assertTrue("X start spinner panel isn't visible", xStartSpinner.getParent().isVisible());
assertTrue("X end spinner panel isn't visible", xEndSpinner.getParent().isVisible());
// Edit left side texture
textureDialog = showTexturePanel(preferences, leftSideTextureComponent, true, attributesDialog, tester);
availableTexturesList = (JList)new BasicFinder().find(textureDialog,
new ClassMatcher(JList.class, true));
textureCount = availableTexturesList.getModel().getSize();
// Select imported texture
availableTexturesList.setSelectedValue(importedTexture, true);
// Modify texture
textureWizardDialog = showImportTextureWizard(preferences, frame, tester, true);
// Retrieve ImportedFurnitureWizardStepsPanel components
panel = (ImportedTextureWizardStepsPanel)TestUtilities.findComponent(
textureWizardDialog, ImportedTextureWizardStepsPanel.class);
widthSpinner = (JSpinner)TestUtilities.getField(panel, "widthSpinner");
final JButton nextFinishOptionButton2 = (JButton)TestUtilities.getField(
TestUtilities.findComponent(textureWizardDialog, WizardPane.class), "nextFinishOptionButton");
tester.invokeAndWait(new Runnable() {
public void run() {
nextFinishOptionButton2.doClick();
}
});
// Change width
widthSpinner.setValue((Float)widthSpinner.getValue() * 2);
newWidth = (Float)widthSpinner.getValue();
tester.invokeAndWait(new Runnable() {
public void run() {
// Click on Finish to hide dialog box in Event Dispatch Thread
nextFinishOptionButton2.doClick();
}
});
assertFalse("Import texture wizard still showing", textureWizardDialog.isShowing());
// Check the list of available textures has the same texture count
// and a new selected texture
assertEquals("Wrong texture count in list", textureCount, availableTexturesList.getModel().getSize());
assertEquals("No selected texture in list", 1, availableTexturesList.getSelectedValues().length);
CatalogTexture modifiedTexture = (CatalogTexture)availableTexturesList.getSelectedValue();
assertNotSame("Wrong selected texture in list", importedTexture, modifiedTexture);
// Check the attributes of the new texture
assertEquals("Wrong name", textureTestName, modifiedTexture.getName());
assertEquals("Wrong category", userCategoryName, modifiedTexture.getCategory().getName());
assertEquals("Wrong width", newWidth, modifiedTexture.getWidth());
assertTrue("New texture isn't modifiable", modifiedTexture.isModifiable());
// 9. Click on OK in texture dialog box
doClickOnOkInDialog(textureDialog, tester);
// Click on OK in wall dialog box
doClickOnOkInDialog(attributesDialog, tester);
// Check wall attributes are modified accordingly
assertEquals("Wrong texture on wall 1 left side", newWidth, wall1.getLeftSideTexture().getWidth());
assertNull("Wrong texture on wall 2 left side", wall2.getLeftSideTexture());
assertEquals("Wrong texture on wall 1 right side", newWidth / 2, wall1.getRightSideTexture().getWidth());
assertEquals("Wrong texture on wall 2 right side", newWidth / 2, wall2.getRightSideTexture().getWidth());
// 10. Open wall dialog a last time to delete the modified texture
attributesDialog = showWallPanel(preferences, controller, frame, tester);
// Retrieve WallPanel components
wallPanel = (WallPanel)TestUtilities.findComponent(attributesDialog, WallPanel.class);
leftSideTextureComponent = (TextureChoiceComponent)TestUtilities.getField(wallPanel, "leftSideTextureComponent");
// Edit left side texture
textureDialog = showTexturePanel(preferences, leftSideTextureComponent, true, attributesDialog, tester);
availableTexturesList = (JList)new BasicFinder().find(textureDialog,
new ClassMatcher(JList.class, true));
textureCount = availableTexturesList.getModel().getSize();
// Select modified texture
availableTexturesList.setSelectedValue(modifiedTexture, true);
final JButton deleteButton = (JButton)new BasicFinder().find(textureDialog,
new Matcher() {
public boolean matches(Component c) {
return c instanceof JButton && ((JButton)c).getText().equals(preferences.getLocalizedString(
TextureChoiceComponent.class, "deleteTextureButton.text"));
}
});
- tester.invokeLater(new Runnable() {
- public void run() {
- // Display confirm dialog box later in Event Dispatch Thread to avoid blocking test thread
- deleteButton.doClick(); }
- });
+ tester.invokeAndWait(new Runnable() {
+ public void run() {
+ // Display confirm dialog box later in Event Dispatch Thread to avoid blocking test thread
+ deleteButton.doClick();
+ }
+ });
// Wait for confirm dialog to be shown
final String confirmDeleteSelectedCatalogTextureDialogTitle = preferences.getLocalizedString(
TextureChoiceComponent.class, "confirmDeleteSelectedCatalogTexture.title");
tester.waitForFrameShowing(new AWTHierarchy(), confirmDeleteSelectedCatalogTextureDialogTitle);
// Check dialog box is displayed
JDialog confirmDialog = (JDialog)new BasicFinder().find(textureDialog,
new Matcher() {
public boolean matches(Component c) {
return c instanceof JDialog && ((JDialog)c).getTitle().equals(
confirmDeleteSelectedCatalogTextureDialogTitle);
}
});
assertTrue("Confirm dialog not showing", confirmDialog.isShowing());
doClickOnOkInDialog(confirmDialog, tester);
tester.waitForIdle();
// Check the list of available textures has one less texture and no selected texture
assertEquals("Wrong texture count in list", textureCount - 1, availableTexturesList.getModel().getSize());
assertEquals("No selected texture in list", 0, availableTexturesList.getSelectedValues().length);
// Check delete button is disabled
assertFalse("Delete button isn't disabled", deleteButton.isEnabled());
// Click on OK in texture dialog box
doClickOnOkInDialog(textureDialog, tester);
// Click on OK in wall dialog box
doClickOnOkInDialog(attributesDialog, tester);
// Check wall attributes didn't change
assertNotNull("Wrong texture on wall 1 left side", wall1.getLeftSideTexture());
assertNull("Wrong texture on wall 2 left side", wall2.getLeftSideTexture());
assertNotNull("Wrong texture on wall 1 right side", wall1.getRightSideTexture());
assertNotNull("Wrong texture on wall 2 right side", wall2.getRightSideTexture());
}
/**
* Returns the dialog that displays wall attributes.
*/
private JDialog showWallPanel(UserPreferences preferences,
final HomeController controller,
JFrame parent, JComponentTester tester)
throws ComponentSearchException {
tester.invokeLater(new Runnable() {
public void run() {
// Display dialog box later in Event Dispatch Thread to avoid blocking test thread
runAction(controller, HomePane.ActionType.MODIFY_WALL);
}
});
// Wait for wall view to be shown
tester.waitForFrameShowing(new AWTHierarchy(), preferences.getLocalizedString(
WallPanel.class, "wall.title"));
// Check dialog box is displayed
JDialog attributesDialog = (JDialog)new BasicFinder().find(parent,
new ClassMatcher (JDialog.class, true));
assertTrue("Wall dialog not showing", attributesDialog.isShowing());
return attributesDialog;
}
/**
* Returns the dialog that displays texture panel.
*/
private JDialog showTexturePanel(UserPreferences preferences,
final TextureChoiceComponent textureComponent,
boolean leftSide,
Container parent, JComponentTester tester)
throws ComponentSearchException {
tester.invokeLater(new Runnable() {
public void run() {
// Display dialog box later in Event Dispatch Thread to avoid blocking test thread
textureComponent.doClick(); }
});
// Wait for texture panel to be shown
String textureTitle = preferences.getLocalizedString(
WallController.class, leftSide ? "leftSideTextureTitle" : "rightSideTextureTitle");
tester.waitForFrameShowing(new AWTHierarchy(), textureTitle);
// Check texture dialog box is displayed
JDialog textureDialog = (JDialog)new BasicFinder().find(parent,
new WindowMatcher(textureTitle));
assertTrue("Texture dialog not showing", textureDialog.isShowing());
return textureDialog;
}
/**
* Returns the dialog that displays texture import wizard.
*/
private JDialog showImportTextureWizard(final UserPreferences preferences,
Container parent, JComponentTester tester,
final boolean modify)
throws ComponentSearchException {
final JButton button = (JButton)new BasicFinder().find(parent,
new Matcher() {
public boolean matches(Component c) {
return c instanceof JButton
&& ((JButton)c).getText() != null
&& ((JButton)c).getText().equals(preferences.getLocalizedString(
TextureChoiceComponent.class,
modify ? "modifyTextureButton.text" : "importTextureButton.text"));
}
});
tester.invokeLater(new Runnable() {
public void run() {
// Display dialog box later in Event Dispatch Thread to avoid blocking test thread
button.doClick();
}
});
// Wait for texture wizard to be shown
String textureWizardTitle = preferences.getLocalizedString(
ImportedTextureWizardController.class,
modify ? "modifyTextureWizard.title" : "importTextureWizard.title");
tester.waitForFrameShowing(new AWTHierarchy(), textureWizardTitle);
// Check texture dialog box is displayed
JDialog textureDialog = (JDialog)new BasicFinder().find(parent,
new WindowMatcher(textureWizardTitle));
assertTrue("Texture wizard not showing", textureDialog.isShowing());
return textureDialog;
}
/**
* Clicks on OK in dialog to close it.
*/
private void doClickOnOkInDialog(JDialog dialog, JComponentTester tester)
throws ComponentSearchException {
final JOptionPane attributesOptionPane = (JOptionPane)TestUtilities.findComponent(
dialog, JOptionPane.class);
tester.invokeAndWait(new Runnable() {
public void run() {
// Select Ok option to hide dialog box in Event Dispatch Thread
if (attributesOptionPane.getOptions() != null) {
attributesOptionPane.setValue(attributesOptionPane.getOptions() [0]);
} else {
attributesOptionPane.setValue(JOptionPane.OK_OPTION);
}
}
});
assertFalse("Dialog still showing", dialog.isShowing());
}
/**
* Runs <code>actionPerformed</code> method matching <code>actionType</code>
* in <code>HomePane</code>.
*/
private void runAction(HomeController controller,
HomePane.ActionType actionType) {
((JComponent)controller.getView()).getActionMap().get(actionType).actionPerformed(null);
}
/**
* Asserts if each <code>panel</code> step preview component is showing or not.
*/
private void assertStepShowing(ImportedTextureWizardStepsPanel panel,
boolean imageStepShwing,
boolean attributesStepShowing) throws NoSuchFieldException, IllegalAccessException {
assertEquals("Wrong image step visibility", imageStepShwing,
((JComponent)TestUtilities.getField(panel, "imageChoicePreviewComponent")).isShowing());
assertEquals("Wrong attributes step visibility", attributesStepShowing,
((JComponent)TestUtilities.getField(panel, "attributesPreviewComponent")).isShowing());
}
}
| true | true | public void testImportedTextureWizard() throws ComponentSearchException, InterruptedException,
NoSuchFieldException, IllegalAccessException, InvocationTargetException {
String language = Locale.getDefault().getLanguage();
final UserPreferences preferences = new FileUserPreferences() {
@Override
public boolean isActionTipIgnored(String actionKey) {
return true;
}
};
// Ensure we use default language and centimeter unit
preferences.setLanguage(language);
preferences.setUnit(LengthUnit.CENTIMETER);
ViewFactory viewFactory = new SwingViewFactory();
// Create a dummy content manager
final URL testedImageName = BackgroundImageWizardTest.class.getResource("resources/test.png");
final ContentManager contentManager = new ContentManager() {
public Content getContent(String contentName) throws RecorderException {
try {
// Let's consider contentName is a URL
return new URLContent(new URL(contentName));
} catch (IOException ex) {
fail();
return null;
}
}
public String getPresentationName(String contentName, ContentType contentType) {
return "test";
}
public boolean isAcceptable(String contentName, ContentType contentType) {
return true;
}
public String showOpenDialog(View parentView, String dialogTitle, ContentType contentType) {
// Return tested model name URL
return testedImageName.toString();
}
public String showSaveDialog(View parentView, String dialogTitle, ContentType contentType, String name) {
return null;
}
};
Home home = new Home();
final HomeController controller =
new HomeController(home, preferences, viewFactory, contentManager);
JComponent homeView = (JComponent)controller.getView();
PlanComponent planComponent = (PlanComponent)TestUtilities.findComponent(
homeView, PlanComponent.class);
// 1. Create a frame that displays a home view
JFrame frame = new JFrame("Imported Texture Wizard Test");
frame.add(homeView);
frame.pack();
// Show home plan frame
showWindow(frame);
JComponentTester tester = new JComponentTester();
tester.waitForIdle();
// Transfer focus to plan view
planComponent.requestFocusInWindow();
tester.waitForIdle();
// Check plan view has focus
assertTrue("Plan component doesn't have the focus", planComponent.isFocusOwner());
// 2. Create two wall between points (50, 50), (150, 50) and (150, 150)
runAction(controller, HomePane.ActionType.CREATE_WALLS);
tester.actionClick(planComponent, 50, 50);
tester.actionClick(planComponent, 150, 50);
tester.actionClick(planComponent, 150, 150, InputEvent.BUTTON1_MASK, 2);
runAction(controller, HomePane.ActionType.SELECT);
// Check two walls were created and selected
assertEquals("Wrong wall count in home", 2, home.getWalls().size());
assertEquals("Wrong selected items count in home", 2, home.getSelectedItems().size());
Iterator<Wall> iterator = home.getWalls().iterator();
Wall wall1 = iterator.next();
Wall wall2 = iterator.next();
// Check walls don't use texture yet
assertNull("Wrong texture on wall 1 left side", wall1.getLeftSideTexture());
assertNull("Wrong texture on wall 2 left side", wall2.getLeftSideTexture());
assertNull("Wrong texture on wall 1 right side", wall1.getRightSideTexture());
assertNull("Wrong texture on wall 2 right side", wall2.getRightSideTexture());
// 3. Edit walls
JDialog attributesDialog = showWallPanel(preferences, controller, frame, tester);
// Retrieve WallPanel components
WallPanel wallPanel = (WallPanel)TestUtilities.findComponent(
attributesDialog, WallPanel.class);
JSpinner xStartSpinner =
(JSpinner)TestUtilities.getField(wallPanel, "xStartSpinner");
JSpinner xEndSpinner =
(JSpinner)TestUtilities.getField(wallPanel, "xEndSpinner");
TextureChoiceComponent rightSideTextureComponent =
(TextureChoiceComponent)TestUtilities.getField(wallPanel, "rightSideTextureComponent");
// Check xStartSpinner and xEndSpinner panels aren't visible
assertFalse("X start spinner panel is visible", xStartSpinner.getParent().isVisible());
assertFalse("X end spinner panel is visible", xEndSpinner.getParent().isVisible());
// Edit right side texture
JDialog textureDialog = showTexturePanel(preferences, rightSideTextureComponent, false, attributesDialog, tester);
JList availableTexturesList = (JList)new BasicFinder().find(textureDialog,
new ClassMatcher(JList.class, true));
int textureCount = availableTexturesList.getModel().getSize();
CatalogTexture defaultTexture = (CatalogTexture)availableTexturesList.getSelectedValue();
// Import texture
JDialog textureWizardDialog = showImportTextureWizard(preferences, frame, tester, false);
// Retrieve ImportedFurnitureWizardStepsPanel components
ImportedTextureWizardStepsPanel panel = (ImportedTextureWizardStepsPanel)TestUtilities.findComponent(
textureWizardDialog, ImportedTextureWizardStepsPanel.class);
final JButton imageChoiceOrChangeButton = (JButton)TestUtilities.getField(panel, "imageChoiceOrChangeButton");
final JTextField nameTextField = (JTextField)TestUtilities.getField(panel, "nameTextField");
JComboBox categoryComboBox = (JComboBox)TestUtilities.getField(panel, "categoryComboBox");
JSpinner widthSpinner = (JSpinner)TestUtilities.getField(panel, "widthSpinner");
JSpinner heightSpinner = (JSpinner)TestUtilities.getField(panel, "heightSpinner");
// Check current step is image
tester.waitForIdle();
assertStepShowing(panel, true, false);
WizardPane view = (WizardPane)TestUtilities.findComponent(textureWizardDialog, WizardPane.class);
// Check wizard view next button is disabled
final JButton nextFinishOptionButton = (JButton)TestUtilities.getField(view, "nextFinishOptionButton");
assertFalse("Next button is enabled", nextFinishOptionButton.isEnabled());
// 4. Choose tested image
String imageChoiceOrChangeButtonText = imageChoiceOrChangeButton.getText();
tester.invokeAndWait(new Runnable() {
public void run() {
imageChoiceOrChangeButton.doClick();
}
});
// Wait 200 ms to let time to Java to load the image
Thread.sleep(200);
// Check choice button text changed
assertFalse("Choice button text didn't change",
imageChoiceOrChangeButtonText.equals(imageChoiceOrChangeButton.getText()));
// Click on next button
tester.invokeAndWait(new Runnable() {
public void run() {
nextFinishOptionButton.doClick();
}
});
// Check current step is attributes
assertStepShowing(panel, false, true);
// 5. Check default furniture name is the presentation name proposed by content manager
assertEquals("Wrong default name",
contentManager.getPresentationName(testedImageName.toString(), ContentManager.ContentType.IMAGE),
nameTextField.getText());
// Check name text field has focus
assertSame("Name text field doesn't have focus", nameTextField,
KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner());
// Check default category is user category
String userCategoryName = preferences.getLocalizedString(
ImportedTextureWizardStepsPanel.class, "userCategory");
assertEquals("Wrong default category", userCategoryName,
((TexturesCategory)categoryComboBox.getSelectedItem()).getName());
// Rename texture
final String textureTestName = "#@" + System.currentTimeMillis() + "@#";
tester.invokeAndWait(new Runnable() {
public void run() {
nameTextField.setText(textureTestName);
}
});
// Check next button is enabled again
assertTrue("Next button isn't enabled", nextFinishOptionButton.isEnabled());
// 6. Change width with a value 5 times greater
float width = (Float)widthSpinner.getValue();
float height = (Float)heightSpinner.getValue();
widthSpinner.setValue(width * 5);
// Check height is 5 times greater
float newWidth = (Float)widthSpinner.getValue();
float newHeight = (Float)heightSpinner.getValue();
assertEquals("width", 5 * width, newWidth);
assertEquals("height", 5 * height, newHeight);
tester.invokeAndWait(new Runnable() {
public void run() {
// Click on Finish to hide dialog box in Event Dispatch Thread
nextFinishOptionButton.doClick();
}
});
assertFalse("Import texture wizard still showing", textureWizardDialog.isShowing());
// Check the list of available textures has one more selected modifiable texture
assertEquals("Wrong texture count in list", textureCount + 1, availableTexturesList.getModel().getSize());
assertEquals("No selected texture in list", 1, availableTexturesList.getSelectedValues().length);
CatalogTexture importedTexture = (CatalogTexture)availableTexturesList.getSelectedValue();
assertNotSame("Wrong selected texture in list", defaultTexture, importedTexture);
// Check the attributes of the new texture
assertEquals("Wrong name", textureTestName, importedTexture.getName());
assertEquals("Wrong category", userCategoryName, importedTexture.getCategory().getName());
assertEquals("Wrong width", newWidth, importedTexture.getWidth());
assertEquals("Wrong height", newHeight, importedTexture.getHeight());
assertTrue("New texture isn't modifiable", importedTexture.isModifiable());
// 7. Click on OK in texture dialog box
doClickOnOkInDialog(textureDialog, tester);
// Click on OK in wall dialog box
doClickOnOkInDialog(attributesDialog, tester);
// Check wall attributes are modified accordingly
assertNull("Wrong texture on wall 1 left side", wall1.getLeftSideTexture());
assertNull("Wrong texture on wall 2 left side", wall2.getLeftSideTexture());
assertEquals("Wrong texture on wall 1 right side", textureTestName, wall1.getRightSideTexture().getName());
assertEquals("Wrong texture on wall 2 right side", textureTestName, wall2.getRightSideTexture().getName());
// 8. Edit left side texture of first wall
home.setSelectedItems(Arrays.asList(wall1));
assertEquals("Wrong selected items count in home", 1, home.getSelectedItems().size());
attributesDialog = showWallPanel(preferences, controller, frame, tester);
// Retrieve WallPanel components
wallPanel = (WallPanel)TestUtilities.findComponent(attributesDialog, WallPanel.class);
xStartSpinner = (JSpinner)TestUtilities.getField(wallPanel, "xStartSpinner");
xEndSpinner = (JSpinner)TestUtilities.getField(wallPanel, "xEndSpinner");
TextureChoiceComponent leftSideTextureComponent =
(TextureChoiceComponent)TestUtilities.getField(wallPanel, "leftSideTextureComponent");
// Check xStartSpinner and xEndSpinner panels are visible
assertTrue("X start spinner panel isn't visible", xStartSpinner.getParent().isVisible());
assertTrue("X end spinner panel isn't visible", xEndSpinner.getParent().isVisible());
// Edit left side texture
textureDialog = showTexturePanel(preferences, leftSideTextureComponent, true, attributesDialog, tester);
availableTexturesList = (JList)new BasicFinder().find(textureDialog,
new ClassMatcher(JList.class, true));
textureCount = availableTexturesList.getModel().getSize();
// Select imported texture
availableTexturesList.setSelectedValue(importedTexture, true);
// Modify texture
textureWizardDialog = showImportTextureWizard(preferences, frame, tester, true);
// Retrieve ImportedFurnitureWizardStepsPanel components
panel = (ImportedTextureWizardStepsPanel)TestUtilities.findComponent(
textureWizardDialog, ImportedTextureWizardStepsPanel.class);
widthSpinner = (JSpinner)TestUtilities.getField(panel, "widthSpinner");
final JButton nextFinishOptionButton2 = (JButton)TestUtilities.getField(
TestUtilities.findComponent(textureWizardDialog, WizardPane.class), "nextFinishOptionButton");
tester.invokeAndWait(new Runnable() {
public void run() {
nextFinishOptionButton2.doClick();
}
});
// Change width
widthSpinner.setValue((Float)widthSpinner.getValue() * 2);
newWidth = (Float)widthSpinner.getValue();
tester.invokeAndWait(new Runnable() {
public void run() {
// Click on Finish to hide dialog box in Event Dispatch Thread
nextFinishOptionButton2.doClick();
}
});
assertFalse("Import texture wizard still showing", textureWizardDialog.isShowing());
// Check the list of available textures has the same texture count
// and a new selected texture
assertEquals("Wrong texture count in list", textureCount, availableTexturesList.getModel().getSize());
assertEquals("No selected texture in list", 1, availableTexturesList.getSelectedValues().length);
CatalogTexture modifiedTexture = (CatalogTexture)availableTexturesList.getSelectedValue();
assertNotSame("Wrong selected texture in list", importedTexture, modifiedTexture);
// Check the attributes of the new texture
assertEquals("Wrong name", textureTestName, modifiedTexture.getName());
assertEquals("Wrong category", userCategoryName, modifiedTexture.getCategory().getName());
assertEquals("Wrong width", newWidth, modifiedTexture.getWidth());
assertTrue("New texture isn't modifiable", modifiedTexture.isModifiable());
// 9. Click on OK in texture dialog box
doClickOnOkInDialog(textureDialog, tester);
// Click on OK in wall dialog box
doClickOnOkInDialog(attributesDialog, tester);
// Check wall attributes are modified accordingly
assertEquals("Wrong texture on wall 1 left side", newWidth, wall1.getLeftSideTexture().getWidth());
assertNull("Wrong texture on wall 2 left side", wall2.getLeftSideTexture());
assertEquals("Wrong texture on wall 1 right side", newWidth / 2, wall1.getRightSideTexture().getWidth());
assertEquals("Wrong texture on wall 2 right side", newWidth / 2, wall2.getRightSideTexture().getWidth());
// 10. Open wall dialog a last time to delete the modified texture
attributesDialog = showWallPanel(preferences, controller, frame, tester);
// Retrieve WallPanel components
wallPanel = (WallPanel)TestUtilities.findComponent(attributesDialog, WallPanel.class);
leftSideTextureComponent = (TextureChoiceComponent)TestUtilities.getField(wallPanel, "leftSideTextureComponent");
// Edit left side texture
textureDialog = showTexturePanel(preferences, leftSideTextureComponent, true, attributesDialog, tester);
availableTexturesList = (JList)new BasicFinder().find(textureDialog,
new ClassMatcher(JList.class, true));
textureCount = availableTexturesList.getModel().getSize();
// Select modified texture
availableTexturesList.setSelectedValue(modifiedTexture, true);
final JButton deleteButton = (JButton)new BasicFinder().find(textureDialog,
new Matcher() {
public boolean matches(Component c) {
return c instanceof JButton && ((JButton)c).getText().equals(preferences.getLocalizedString(
TextureChoiceComponent.class, "deleteTextureButton.text"));
}
});
tester.invokeLater(new Runnable() {
public void run() {
// Display confirm dialog box later in Event Dispatch Thread to avoid blocking test thread
deleteButton.doClick(); }
});
// Wait for confirm dialog to be shown
final String confirmDeleteSelectedCatalogTextureDialogTitle = preferences.getLocalizedString(
TextureChoiceComponent.class, "confirmDeleteSelectedCatalogTexture.title");
tester.waitForFrameShowing(new AWTHierarchy(), confirmDeleteSelectedCatalogTextureDialogTitle);
// Check dialog box is displayed
JDialog confirmDialog = (JDialog)new BasicFinder().find(textureDialog,
new Matcher() {
public boolean matches(Component c) {
return c instanceof JDialog && ((JDialog)c).getTitle().equals(
confirmDeleteSelectedCatalogTextureDialogTitle);
}
});
assertTrue("Confirm dialog not showing", confirmDialog.isShowing());
doClickOnOkInDialog(confirmDialog, tester);
tester.waitForIdle();
// Check the list of available textures has one less texture and no selected texture
assertEquals("Wrong texture count in list", textureCount - 1, availableTexturesList.getModel().getSize());
assertEquals("No selected texture in list", 0, availableTexturesList.getSelectedValues().length);
// Check delete button is disabled
assertFalse("Delete button isn't disabled", deleteButton.isEnabled());
// Click on OK in texture dialog box
doClickOnOkInDialog(textureDialog, tester);
// Click on OK in wall dialog box
doClickOnOkInDialog(attributesDialog, tester);
// Check wall attributes didn't change
assertNotNull("Wrong texture on wall 1 left side", wall1.getLeftSideTexture());
assertNull("Wrong texture on wall 2 left side", wall2.getLeftSideTexture());
assertNotNull("Wrong texture on wall 1 right side", wall1.getRightSideTexture());
assertNotNull("Wrong texture on wall 2 right side", wall2.getRightSideTexture());
}
| public void testImportedTextureWizard() throws ComponentSearchException, InterruptedException,
NoSuchFieldException, IllegalAccessException, InvocationTargetException {
String language = Locale.getDefault().getLanguage();
final UserPreferences preferences = new FileUserPreferences() {
@Override
public boolean isActionTipIgnored(String actionKey) {
return true;
}
};
// Ensure we use default language and centimeter unit
preferences.setLanguage(language);
preferences.setUnit(LengthUnit.CENTIMETER);
ViewFactory viewFactory = new SwingViewFactory();
// Create a dummy content manager
final URL testedImageName = BackgroundImageWizardTest.class.getResource("resources/test.png");
final ContentManager contentManager = new ContentManager() {
public Content getContent(String contentName) throws RecorderException {
try {
// Let's consider contentName is a URL
return new URLContent(new URL(contentName));
} catch (IOException ex) {
fail();
return null;
}
}
public String getPresentationName(String contentName, ContentType contentType) {
return "test";
}
public boolean isAcceptable(String contentName, ContentType contentType) {
return true;
}
public String showOpenDialog(View parentView, String dialogTitle, ContentType contentType) {
// Return tested model name URL
return testedImageName.toString();
}
public String showSaveDialog(View parentView, String dialogTitle, ContentType contentType, String name) {
return null;
}
};
Home home = new Home();
final HomeController controller =
new HomeController(home, preferences, viewFactory, contentManager);
JComponent homeView = (JComponent)controller.getView();
PlanComponent planComponent = (PlanComponent)TestUtilities.findComponent(
homeView, PlanComponent.class);
// 1. Create a frame that displays a home view
JFrame frame = new JFrame("Imported Texture Wizard Test");
frame.add(homeView);
frame.pack();
// Show home plan frame
showWindow(frame);
JComponentTester tester = new JComponentTester();
tester.waitForIdle();
// Transfer focus to plan view
planComponent.requestFocusInWindow();
tester.waitForIdle();
// Check plan view has focus
assertTrue("Plan component doesn't have the focus", planComponent.isFocusOwner());
// 2. Create two wall between points (50, 50), (150, 50) and (150, 150)
runAction(controller, HomePane.ActionType.CREATE_WALLS);
tester.actionClick(planComponent, 50, 50);
tester.actionClick(planComponent, 150, 50);
tester.actionClick(planComponent, 150, 150, InputEvent.BUTTON1_MASK, 2);
runAction(controller, HomePane.ActionType.SELECT);
// Check two walls were created and selected
assertEquals("Wrong wall count in home", 2, home.getWalls().size());
assertEquals("Wrong selected items count in home", 2, home.getSelectedItems().size());
Iterator<Wall> iterator = home.getWalls().iterator();
Wall wall1 = iterator.next();
Wall wall2 = iterator.next();
// Check walls don't use texture yet
assertNull("Wrong texture on wall 1 left side", wall1.getLeftSideTexture());
assertNull("Wrong texture on wall 2 left side", wall2.getLeftSideTexture());
assertNull("Wrong texture on wall 1 right side", wall1.getRightSideTexture());
assertNull("Wrong texture on wall 2 right side", wall2.getRightSideTexture());
// 3. Edit walls
JDialog attributesDialog = showWallPanel(preferences, controller, frame, tester);
// Retrieve WallPanel components
WallPanel wallPanel = (WallPanel)TestUtilities.findComponent(
attributesDialog, WallPanel.class);
JSpinner xStartSpinner =
(JSpinner)TestUtilities.getField(wallPanel, "xStartSpinner");
JSpinner xEndSpinner =
(JSpinner)TestUtilities.getField(wallPanel, "xEndSpinner");
TextureChoiceComponent rightSideTextureComponent =
(TextureChoiceComponent)TestUtilities.getField(wallPanel, "rightSideTextureComponent");
// Check xStartSpinner and xEndSpinner panels aren't visible
assertFalse("X start spinner panel is visible", xStartSpinner.getParent().isVisible());
assertFalse("X end spinner panel is visible", xEndSpinner.getParent().isVisible());
// Edit right side texture
JDialog textureDialog = showTexturePanel(preferences, rightSideTextureComponent, false, attributesDialog, tester);
JList availableTexturesList = (JList)new BasicFinder().find(textureDialog,
new ClassMatcher(JList.class, true));
int textureCount = availableTexturesList.getModel().getSize();
CatalogTexture defaultTexture = (CatalogTexture)availableTexturesList.getSelectedValue();
// Import texture
JDialog textureWizardDialog = showImportTextureWizard(preferences, frame, tester, false);
// Retrieve ImportedFurnitureWizardStepsPanel components
ImportedTextureWizardStepsPanel panel = (ImportedTextureWizardStepsPanel)TestUtilities.findComponent(
textureWizardDialog, ImportedTextureWizardStepsPanel.class);
final JButton imageChoiceOrChangeButton = (JButton)TestUtilities.getField(panel, "imageChoiceOrChangeButton");
final JTextField nameTextField = (JTextField)TestUtilities.getField(panel, "nameTextField");
JComboBox categoryComboBox = (JComboBox)TestUtilities.getField(panel, "categoryComboBox");
JSpinner widthSpinner = (JSpinner)TestUtilities.getField(panel, "widthSpinner");
JSpinner heightSpinner = (JSpinner)TestUtilities.getField(panel, "heightSpinner");
// Check current step is image
tester.waitForIdle();
assertStepShowing(panel, true, false);
WizardPane view = (WizardPane)TestUtilities.findComponent(textureWizardDialog, WizardPane.class);
// Check wizard view next button is disabled
final JButton nextFinishOptionButton = (JButton)TestUtilities.getField(view, "nextFinishOptionButton");
assertFalse("Next button is enabled", nextFinishOptionButton.isEnabled());
// 4. Choose tested image
String imageChoiceOrChangeButtonText = imageChoiceOrChangeButton.getText();
tester.invokeAndWait(new Runnable() {
public void run() {
imageChoiceOrChangeButton.doClick();
}
});
// Wait 200 ms to let time to Java to load the image
Thread.sleep(200);
// Check choice button text changed
assertFalse("Choice button text didn't change",
imageChoiceOrChangeButtonText.equals(imageChoiceOrChangeButton.getText()));
// Click on next button
tester.invokeAndWait(new Runnable() {
public void run() {
nextFinishOptionButton.doClick();
}
});
// Check current step is attributes
assertStepShowing(panel, false, true);
// 5. Check default furniture name is the presentation name proposed by content manager
assertEquals("Wrong default name",
contentManager.getPresentationName(testedImageName.toString(), ContentManager.ContentType.IMAGE),
nameTextField.getText());
// Check name text field has focus
assertSame("Name text field doesn't have focus", nameTextField,
KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner());
// Check default category is user category
String userCategoryName = preferences.getLocalizedString(
ImportedTextureWizardStepsPanel.class, "userCategory");
assertEquals("Wrong default category", userCategoryName,
((TexturesCategory)categoryComboBox.getSelectedItem()).getName());
// Rename texture
final String textureTestName = "#@" + System.currentTimeMillis() + "@#";
tester.invokeAndWait(new Runnable() {
public void run() {
nameTextField.setText(textureTestName);
}
});
// Check next button is enabled again
assertTrue("Next button isn't enabled", nextFinishOptionButton.isEnabled());
// 6. Change width with a value 5 times greater
float width = (Float)widthSpinner.getValue();
float height = (Float)heightSpinner.getValue();
widthSpinner.setValue(width * 5);
// Check height is 5 times greater
float newWidth = (Float)widthSpinner.getValue();
float newHeight = (Float)heightSpinner.getValue();
assertEquals("width", 5 * width, newWidth);
assertEquals("height", 5 * height, newHeight);
tester.invokeAndWait(new Runnable() {
public void run() {
// Click on Finish to hide dialog box in Event Dispatch Thread
nextFinishOptionButton.doClick();
}
});
assertFalse("Import texture wizard still showing", textureWizardDialog.isShowing());
// Check the list of available textures has one more selected modifiable texture
assertEquals("Wrong texture count in list", textureCount + 1, availableTexturesList.getModel().getSize());
assertEquals("No selected texture in list", 1, availableTexturesList.getSelectedValues().length);
CatalogTexture importedTexture = (CatalogTexture)availableTexturesList.getSelectedValue();
assertNotSame("Wrong selected texture in list", defaultTexture, importedTexture);
// Check the attributes of the new texture
assertEquals("Wrong name", textureTestName, importedTexture.getName());
assertEquals("Wrong category", userCategoryName, importedTexture.getCategory().getName());
assertEquals("Wrong width", newWidth, importedTexture.getWidth());
assertEquals("Wrong height", newHeight, importedTexture.getHeight());
assertTrue("New texture isn't modifiable", importedTexture.isModifiable());
// 7. Click on OK in texture dialog box
doClickOnOkInDialog(textureDialog, tester);
// Click on OK in wall dialog box
doClickOnOkInDialog(attributesDialog, tester);
// Check wall attributes are modified accordingly
assertNull("Wrong texture on wall 1 left side", wall1.getLeftSideTexture());
assertNull("Wrong texture on wall 2 left side", wall2.getLeftSideTexture());
assertEquals("Wrong texture on wall 1 right side", textureTestName, wall1.getRightSideTexture().getName());
assertEquals("Wrong texture on wall 2 right side", textureTestName, wall2.getRightSideTexture().getName());
// 8. Edit left side texture of first wall
home.setSelectedItems(Arrays.asList(wall1));
assertEquals("Wrong selected items count in home", 1, home.getSelectedItems().size());
attributesDialog = showWallPanel(preferences, controller, frame, tester);
// Retrieve WallPanel components
wallPanel = (WallPanel)TestUtilities.findComponent(attributesDialog, WallPanel.class);
xStartSpinner = (JSpinner)TestUtilities.getField(wallPanel, "xStartSpinner");
xEndSpinner = (JSpinner)TestUtilities.getField(wallPanel, "xEndSpinner");
TextureChoiceComponent leftSideTextureComponent =
(TextureChoiceComponent)TestUtilities.getField(wallPanel, "leftSideTextureComponent");
// Check xStartSpinner and xEndSpinner panels are visible
assertTrue("X start spinner panel isn't visible", xStartSpinner.getParent().isVisible());
assertTrue("X end spinner panel isn't visible", xEndSpinner.getParent().isVisible());
// Edit left side texture
textureDialog = showTexturePanel(preferences, leftSideTextureComponent, true, attributesDialog, tester);
availableTexturesList = (JList)new BasicFinder().find(textureDialog,
new ClassMatcher(JList.class, true));
textureCount = availableTexturesList.getModel().getSize();
// Select imported texture
availableTexturesList.setSelectedValue(importedTexture, true);
// Modify texture
textureWizardDialog = showImportTextureWizard(preferences, frame, tester, true);
// Retrieve ImportedFurnitureWizardStepsPanel components
panel = (ImportedTextureWizardStepsPanel)TestUtilities.findComponent(
textureWizardDialog, ImportedTextureWizardStepsPanel.class);
widthSpinner = (JSpinner)TestUtilities.getField(panel, "widthSpinner");
final JButton nextFinishOptionButton2 = (JButton)TestUtilities.getField(
TestUtilities.findComponent(textureWizardDialog, WizardPane.class), "nextFinishOptionButton");
tester.invokeAndWait(new Runnable() {
public void run() {
nextFinishOptionButton2.doClick();
}
});
// Change width
widthSpinner.setValue((Float)widthSpinner.getValue() * 2);
newWidth = (Float)widthSpinner.getValue();
tester.invokeAndWait(new Runnable() {
public void run() {
// Click on Finish to hide dialog box in Event Dispatch Thread
nextFinishOptionButton2.doClick();
}
});
assertFalse("Import texture wizard still showing", textureWizardDialog.isShowing());
// Check the list of available textures has the same texture count
// and a new selected texture
assertEquals("Wrong texture count in list", textureCount, availableTexturesList.getModel().getSize());
assertEquals("No selected texture in list", 1, availableTexturesList.getSelectedValues().length);
CatalogTexture modifiedTexture = (CatalogTexture)availableTexturesList.getSelectedValue();
assertNotSame("Wrong selected texture in list", importedTexture, modifiedTexture);
// Check the attributes of the new texture
assertEquals("Wrong name", textureTestName, modifiedTexture.getName());
assertEquals("Wrong category", userCategoryName, modifiedTexture.getCategory().getName());
assertEquals("Wrong width", newWidth, modifiedTexture.getWidth());
assertTrue("New texture isn't modifiable", modifiedTexture.isModifiable());
// 9. Click on OK in texture dialog box
doClickOnOkInDialog(textureDialog, tester);
// Click on OK in wall dialog box
doClickOnOkInDialog(attributesDialog, tester);
// Check wall attributes are modified accordingly
assertEquals("Wrong texture on wall 1 left side", newWidth, wall1.getLeftSideTexture().getWidth());
assertNull("Wrong texture on wall 2 left side", wall2.getLeftSideTexture());
assertEquals("Wrong texture on wall 1 right side", newWidth / 2, wall1.getRightSideTexture().getWidth());
assertEquals("Wrong texture on wall 2 right side", newWidth / 2, wall2.getRightSideTexture().getWidth());
// 10. Open wall dialog a last time to delete the modified texture
attributesDialog = showWallPanel(preferences, controller, frame, tester);
// Retrieve WallPanel components
wallPanel = (WallPanel)TestUtilities.findComponent(attributesDialog, WallPanel.class);
leftSideTextureComponent = (TextureChoiceComponent)TestUtilities.getField(wallPanel, "leftSideTextureComponent");
// Edit left side texture
textureDialog = showTexturePanel(preferences, leftSideTextureComponent, true, attributesDialog, tester);
availableTexturesList = (JList)new BasicFinder().find(textureDialog,
new ClassMatcher(JList.class, true));
textureCount = availableTexturesList.getModel().getSize();
// Select modified texture
availableTexturesList.setSelectedValue(modifiedTexture, true);
final JButton deleteButton = (JButton)new BasicFinder().find(textureDialog,
new Matcher() {
public boolean matches(Component c) {
return c instanceof JButton && ((JButton)c).getText().equals(preferences.getLocalizedString(
TextureChoiceComponent.class, "deleteTextureButton.text"));
}
});
tester.invokeAndWait(new Runnable() {
public void run() {
// Display confirm dialog box later in Event Dispatch Thread to avoid blocking test thread
deleteButton.doClick();
}
});
// Wait for confirm dialog to be shown
final String confirmDeleteSelectedCatalogTextureDialogTitle = preferences.getLocalizedString(
TextureChoiceComponent.class, "confirmDeleteSelectedCatalogTexture.title");
tester.waitForFrameShowing(new AWTHierarchy(), confirmDeleteSelectedCatalogTextureDialogTitle);
// Check dialog box is displayed
JDialog confirmDialog = (JDialog)new BasicFinder().find(textureDialog,
new Matcher() {
public boolean matches(Component c) {
return c instanceof JDialog && ((JDialog)c).getTitle().equals(
confirmDeleteSelectedCatalogTextureDialogTitle);
}
});
assertTrue("Confirm dialog not showing", confirmDialog.isShowing());
doClickOnOkInDialog(confirmDialog, tester);
tester.waitForIdle();
// Check the list of available textures has one less texture and no selected texture
assertEquals("Wrong texture count in list", textureCount - 1, availableTexturesList.getModel().getSize());
assertEquals("No selected texture in list", 0, availableTexturesList.getSelectedValues().length);
// Check delete button is disabled
assertFalse("Delete button isn't disabled", deleteButton.isEnabled());
// Click on OK in texture dialog box
doClickOnOkInDialog(textureDialog, tester);
// Click on OK in wall dialog box
doClickOnOkInDialog(attributesDialog, tester);
// Check wall attributes didn't change
assertNotNull("Wrong texture on wall 1 left side", wall1.getLeftSideTexture());
assertNull("Wrong texture on wall 2 left side", wall2.getLeftSideTexture());
assertNotNull("Wrong texture on wall 1 right side", wall1.getRightSideTexture());
assertNotNull("Wrong texture on wall 2 right side", wall2.getRightSideTexture());
}
|
diff --git a/src/org/gridlab/gridsphere/provider/portlet/tags/jsr/NamespaceTag.java b/src/org/gridlab/gridsphere/provider/portlet/tags/jsr/NamespaceTag.java
index 472076e14..e92af3f13 100644
--- a/src/org/gridlab/gridsphere/provider/portlet/tags/jsr/NamespaceTag.java
+++ b/src/org/gridlab/gridsphere/provider/portlet/tags/jsr/NamespaceTag.java
@@ -1,35 +1,34 @@
/**
* @author <a href="mailto:[email protected]">Jason Novotny</a>
* @version $Id$
*/
package org.gridlab.gridsphere.provider.portlet.tags.jsr;
import javax.portlet.RenderResponse;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.TagSupport;
import java.io.IOException;
/**
* This tag produces a unique value for the current portlet.
* <p/>
* Supporting class for the <CODE>namespace</CODE> tag.
* writes a unique value for the current portlet
* <BR>This tag has no attributes
*/
public class NamespaceTag extends TagSupport {
public int doStartTag() throws JspException {
RenderResponse renderResponse = (RenderResponse) pageContext.getAttribute("renderResponse", PageContext.PAGE_SCOPE);
String namespace = renderResponse.getNamespace();
JspWriter writer = pageContext.getOut();
try {
writer.print(namespace);
- writer.flush();
} catch (IOException e) {
throw new JspException("namespace Tag Exception: cannot write to the output writer.", e);
}
return SKIP_BODY;
}
}
| true | true | public int doStartTag() throws JspException {
RenderResponse renderResponse = (RenderResponse) pageContext.getAttribute("renderResponse", PageContext.PAGE_SCOPE);
String namespace = renderResponse.getNamespace();
JspWriter writer = pageContext.getOut();
try {
writer.print(namespace);
writer.flush();
} catch (IOException e) {
throw new JspException("namespace Tag Exception: cannot write to the output writer.", e);
}
return SKIP_BODY;
}
| public int doStartTag() throws JspException {
RenderResponse renderResponse = (RenderResponse) pageContext.getAttribute("renderResponse", PageContext.PAGE_SCOPE);
String namespace = renderResponse.getNamespace();
JspWriter writer = pageContext.getOut();
try {
writer.print(namespace);
} catch (IOException e) {
throw new JspException("namespace Tag Exception: cannot write to the output writer.", e);
}
return SKIP_BODY;
}
|
diff --git a/library/src/com/androidformenhancer/validator/AlphaNumValidator.java b/library/src/com/androidformenhancer/validator/AlphaNumValidator.java
index 01611f9..b7d8985 100644
--- a/library/src/com/androidformenhancer/validator/AlphaNumValidator.java
+++ b/library/src/com/androidformenhancer/validator/AlphaNumValidator.java
@@ -1,60 +1,60 @@
/*
* Copyright 2012 Soichiro Kashima
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.androidformenhancer.validator;
import com.androidformenhancer.R;
import com.androidformenhancer.annotation.AlphaNum;
import android.text.TextUtils;
import java.lang.reflect.Field;
/**
* Validates that the value of the field consists of ASCII alphabet and number
* characters or not.
*
* @author Soichiro Kashima
*/
public class AlphaNumValidator extends Validator {
private static final String REGEX = "^[a-zA-Z0-9]+$";
private static final String REGEX_WITH_SPACE = "^[a-zA-Z0-9 ]+$";
@Override
public String validate(final Field field) {
final String value = getValueAsString(field);
AlphaNum alphaNum = field.getAnnotation(AlphaNum.class);
if (alphaNum != null) {
final Class<?> type = field.getType();
if (type.equals(String.class)) {
if (TextUtils.isEmpty(value)) {
return null;
}
String regex = alphaNum.allowSpace() ? REGEX_WITH_SPACE : REGEX;
if (!value.matches(regex)) {
- return getMessage(R.styleable.ValidatorMessages_afeErrorAlphabet,
- R.string.afe__msg_validation_alphabet,
+ return getMessage(R.styleable.ValidatorMessages_afeErrorAlphaNum,
+ R.string.afe__msg_validation_alphanum,
getName(field, alphaNum.nameResId()));
}
}
}
return null;
}
}
| true | true | public String validate(final Field field) {
final String value = getValueAsString(field);
AlphaNum alphaNum = field.getAnnotation(AlphaNum.class);
if (alphaNum != null) {
final Class<?> type = field.getType();
if (type.equals(String.class)) {
if (TextUtils.isEmpty(value)) {
return null;
}
String regex = alphaNum.allowSpace() ? REGEX_WITH_SPACE : REGEX;
if (!value.matches(regex)) {
return getMessage(R.styleable.ValidatorMessages_afeErrorAlphabet,
R.string.afe__msg_validation_alphabet,
getName(field, alphaNum.nameResId()));
}
}
}
return null;
}
| public String validate(final Field field) {
final String value = getValueAsString(field);
AlphaNum alphaNum = field.getAnnotation(AlphaNum.class);
if (alphaNum != null) {
final Class<?> type = field.getType();
if (type.equals(String.class)) {
if (TextUtils.isEmpty(value)) {
return null;
}
String regex = alphaNum.allowSpace() ? REGEX_WITH_SPACE : REGEX;
if (!value.matches(regex)) {
return getMessage(R.styleable.ValidatorMessages_afeErrorAlphaNum,
R.string.afe__msg_validation_alphanum,
getName(field, alphaNum.nameResId()));
}
}
}
return null;
}
|
diff --git a/code/src/ca/mcgill/dpm/winter2013/group6/localization/SmartLightLocalizer.java b/code/src/ca/mcgill/dpm/winter2013/group6/localization/SmartLightLocalizer.java
index 9c0ecd4..6dde5d7 100644
--- a/code/src/ca/mcgill/dpm/winter2013/group6/localization/SmartLightLocalizer.java
+++ b/code/src/ca/mcgill/dpm/winter2013/group6/localization/SmartLightLocalizer.java
@@ -1,194 +1,194 @@
package ca.mcgill.dpm.winter2013.group6.localization;
import lejos.nxt.LightSensor;
import lejos.nxt.Sound;
import ca.mcgill.dpm.winter2013.group6.navigator.Navigator;
import ca.mcgill.dpm.winter2013.group6.odometer.Odometer;
import ca.mcgill.dpm.winter2013.group6.util.Coordinate;
/**
* A {@link Localizer} implementation that uses a {@link LightSensor} for
* performing its localization.
*
* @author Arthur Kam
*
*/
public class SmartLightLocalizer extends LightLocalizer {
private final double LIGHT_SENSOR_DISTANCE = 11.8;
private Coordinate coordinates;
private int count = 0;
/**
* The constructor the smart light localizer class.
*
* @param odometer
* The {@link Odometer} we'll be reading from.
* @param navigator
* The navigator class that will be used by the localizer.
* @param lightSensor
* The {@link LightSensor} object.
* @param coordinates
* The coordinates that the localizer will think it is localizing in
* reference to (must be an intersetction)
*/
public SmartLightLocalizer(Odometer odometer, Navigator navigator, LightSensor lightSensor,
Coordinate coordinates) {
super(odometer, navigator, lightSensor, 1);
this.coordinates = coordinates;
}
public SmartLightLocalizer(Odometer odometer, Navigator navigator, LightSensor lightSensor) {
super(odometer, navigator, lightSensor, 1);
this.coordinates = new Coordinate(0, 0);
}
public void setCoordinates(Coordinate coordinates) {
if (coordinates != null) {
this.coordinates = coordinates;
}
}
@Override
public void localize() {
if (3 <= count) {
Sound.beepSequence();
count = 0;
return;
}
navigator.face(45);
odometer.setPosition(new double[] { 0, 0, 0 }, new boolean[] { true, true, true });
lightSensor.setFloodlight(true);
int lineCounter = 0;
double[] raw = new double[4];
// Filter the light sensor
try {
Thread.sleep(300);
}
catch (InterruptedException e) {
}
// Rotate and clock the 4 grid lines
calibrateSensorAverage();
navigator.setMotorRotateSpeed(-robot.getRotateSpeed() - 150);
// Detect the four lines
double[] heading = new double[2];
odometer.getDisplacementAndHeading(heading);
double startingAngle = heading[1];
double currAngle = startingAngle;
boolean error = false;
while (lineCounter < 4) {
if (blackLineDetected()) {
Sound.beep();
raw[lineCounter] = odometer.getTheta();
odometer.getDisplacementAndHeading(heading);
currAngle += heading[1];
// its negative since we are rotating the negative direction
- if (currAngle + 360 < startingAngle) {
+ if (currAngle + 400 < startingAngle) {
Sound.buzz();
error = true;
break;
}
lineCounter++;
try {
// sleeping to avoid counting the same line twice
Thread.sleep(150);
}
catch (InterruptedException e) {
}
}
}
// Stop the robot
navigator.stop();
// write code to handle situations where it wouldn't work
// which means it has rotated for 360 degrees but havent scanned all 4 lines
// yet
if (error) {
// seriously i cant fix it at this stage...gg
if (lineCounter == 0) {
navigator.face(45);
navigator.travelStraight(15);
count++;
localize();
return;
}
// not very likely but here is an attempt to fix it
else if (lineCounter == 1) {
// move to the line
raw[0] += 180;
navigator.turnTo(raw[0]);
navigator.travelStraight(LIGHT_SENSOR_DISTANCE);
count++;
// calling it again here to try to localize
localize();
}
// two causes in this case
// one is one axis is off
// the other is both axis is off
else if (lineCounter == 2) {
// if the lines are opposite of each other
if (Math.abs(raw[1] - raw[0]) > 175) {
navigator.face(raw[0]);
navigator.travelStraight(10);
}
else {
navigator.face(raw[1] - raw[0] + 180 + 45);
navigator.travelStraight(10);
}
count++;
localize();
}
else if (lineCounter == 3) {
return;
}
return;
}
// happens if it is displaced too far right from the y axis
if (raw[0] > 60) {
double swap = raw[1];
double swap2 = raw[2];
raw[1] = raw[0];
raw[2] = swap;
swap = raw[3];
raw[3] = swap2;
raw[0] = swap;
}
// formula modified from the tutorial slides
double thetaX = (raw[3] - raw[1]) / 2;
double thetaY = (raw[2] - raw[0]) / 2;
double newX = -LIGHT_SENSOR_DISTANCE * Math.cos(Math.toRadians(thetaY));
double newY = -LIGHT_SENSOR_DISTANCE * Math.cos(Math.toRadians(thetaX));
double newTheta = 180 + thetaX - raw[3];
newTheta += odometer.getTheta();
odometer.setPosition(new double[] {
newX + coordinates.getX(),
newY + coordinates.getY(),
newTheta }, new boolean[] { true, true, true });
count = 0;
// travel to the coordinate
navigator.face(0);
navigator.travelStraight(-newY);
navigator.face(90);
navigator.travelStraight(-newX);
Sound.twoBeeps();
return;
}
@Override
public void run() {
localize();
}
}
| true | true | public void localize() {
if (3 <= count) {
Sound.beepSequence();
count = 0;
return;
}
navigator.face(45);
odometer.setPosition(new double[] { 0, 0, 0 }, new boolean[] { true, true, true });
lightSensor.setFloodlight(true);
int lineCounter = 0;
double[] raw = new double[4];
// Filter the light sensor
try {
Thread.sleep(300);
}
catch (InterruptedException e) {
}
// Rotate and clock the 4 grid lines
calibrateSensorAverage();
navigator.setMotorRotateSpeed(-robot.getRotateSpeed() - 150);
// Detect the four lines
double[] heading = new double[2];
odometer.getDisplacementAndHeading(heading);
double startingAngle = heading[1];
double currAngle = startingAngle;
boolean error = false;
while (lineCounter < 4) {
if (blackLineDetected()) {
Sound.beep();
raw[lineCounter] = odometer.getTheta();
odometer.getDisplacementAndHeading(heading);
currAngle += heading[1];
// its negative since we are rotating the negative direction
if (currAngle + 360 < startingAngle) {
Sound.buzz();
error = true;
break;
}
lineCounter++;
try {
// sleeping to avoid counting the same line twice
Thread.sleep(150);
}
catch (InterruptedException e) {
}
}
}
// Stop the robot
navigator.stop();
// write code to handle situations where it wouldn't work
// which means it has rotated for 360 degrees but havent scanned all 4 lines
// yet
if (error) {
// seriously i cant fix it at this stage...gg
if (lineCounter == 0) {
navigator.face(45);
navigator.travelStraight(15);
count++;
localize();
return;
}
// not very likely but here is an attempt to fix it
else if (lineCounter == 1) {
// move to the line
raw[0] += 180;
navigator.turnTo(raw[0]);
navigator.travelStraight(LIGHT_SENSOR_DISTANCE);
count++;
// calling it again here to try to localize
localize();
}
// two causes in this case
// one is one axis is off
// the other is both axis is off
else if (lineCounter == 2) {
// if the lines are opposite of each other
if (Math.abs(raw[1] - raw[0]) > 175) {
navigator.face(raw[0]);
navigator.travelStraight(10);
}
else {
navigator.face(raw[1] - raw[0] + 180 + 45);
navigator.travelStraight(10);
}
count++;
localize();
}
else if (lineCounter == 3) {
return;
}
return;
}
// happens if it is displaced too far right from the y axis
if (raw[0] > 60) {
double swap = raw[1];
double swap2 = raw[2];
raw[1] = raw[0];
raw[2] = swap;
swap = raw[3];
raw[3] = swap2;
raw[0] = swap;
}
// formula modified from the tutorial slides
double thetaX = (raw[3] - raw[1]) / 2;
double thetaY = (raw[2] - raw[0]) / 2;
double newX = -LIGHT_SENSOR_DISTANCE * Math.cos(Math.toRadians(thetaY));
double newY = -LIGHT_SENSOR_DISTANCE * Math.cos(Math.toRadians(thetaX));
double newTheta = 180 + thetaX - raw[3];
newTheta += odometer.getTheta();
odometer.setPosition(new double[] {
newX + coordinates.getX(),
newY + coordinates.getY(),
newTheta }, new boolean[] { true, true, true });
count = 0;
// travel to the coordinate
navigator.face(0);
navigator.travelStraight(-newY);
navigator.face(90);
navigator.travelStraight(-newX);
Sound.twoBeeps();
return;
}
| public void localize() {
if (3 <= count) {
Sound.beepSequence();
count = 0;
return;
}
navigator.face(45);
odometer.setPosition(new double[] { 0, 0, 0 }, new boolean[] { true, true, true });
lightSensor.setFloodlight(true);
int lineCounter = 0;
double[] raw = new double[4];
// Filter the light sensor
try {
Thread.sleep(300);
}
catch (InterruptedException e) {
}
// Rotate and clock the 4 grid lines
calibrateSensorAverage();
navigator.setMotorRotateSpeed(-robot.getRotateSpeed() - 150);
// Detect the four lines
double[] heading = new double[2];
odometer.getDisplacementAndHeading(heading);
double startingAngle = heading[1];
double currAngle = startingAngle;
boolean error = false;
while (lineCounter < 4) {
if (blackLineDetected()) {
Sound.beep();
raw[lineCounter] = odometer.getTheta();
odometer.getDisplacementAndHeading(heading);
currAngle += heading[1];
// its negative since we are rotating the negative direction
if (currAngle + 400 < startingAngle) {
Sound.buzz();
error = true;
break;
}
lineCounter++;
try {
// sleeping to avoid counting the same line twice
Thread.sleep(150);
}
catch (InterruptedException e) {
}
}
}
// Stop the robot
navigator.stop();
// write code to handle situations where it wouldn't work
// which means it has rotated for 360 degrees but havent scanned all 4 lines
// yet
if (error) {
// seriously i cant fix it at this stage...gg
if (lineCounter == 0) {
navigator.face(45);
navigator.travelStraight(15);
count++;
localize();
return;
}
// not very likely but here is an attempt to fix it
else if (lineCounter == 1) {
// move to the line
raw[0] += 180;
navigator.turnTo(raw[0]);
navigator.travelStraight(LIGHT_SENSOR_DISTANCE);
count++;
// calling it again here to try to localize
localize();
}
// two causes in this case
// one is one axis is off
// the other is both axis is off
else if (lineCounter == 2) {
// if the lines are opposite of each other
if (Math.abs(raw[1] - raw[0]) > 175) {
navigator.face(raw[0]);
navigator.travelStraight(10);
}
else {
navigator.face(raw[1] - raw[0] + 180 + 45);
navigator.travelStraight(10);
}
count++;
localize();
}
else if (lineCounter == 3) {
return;
}
return;
}
// happens if it is displaced too far right from the y axis
if (raw[0] > 60) {
double swap = raw[1];
double swap2 = raw[2];
raw[1] = raw[0];
raw[2] = swap;
swap = raw[3];
raw[3] = swap2;
raw[0] = swap;
}
// formula modified from the tutorial slides
double thetaX = (raw[3] - raw[1]) / 2;
double thetaY = (raw[2] - raw[0]) / 2;
double newX = -LIGHT_SENSOR_DISTANCE * Math.cos(Math.toRadians(thetaY));
double newY = -LIGHT_SENSOR_DISTANCE * Math.cos(Math.toRadians(thetaX));
double newTheta = 180 + thetaX - raw[3];
newTheta += odometer.getTheta();
odometer.setPosition(new double[] {
newX + coordinates.getX(),
newY + coordinates.getY(),
newTheta }, new boolean[] { true, true, true });
count = 0;
// travel to the coordinate
navigator.face(0);
navigator.travelStraight(-newY);
navigator.face(90);
navigator.travelStraight(-newX);
Sound.twoBeeps();
return;
}
|
diff --git a/src/me/libraryaddict/Hungergames/Managers/KitManager.java b/src/me/libraryaddict/Hungergames/Managers/KitManager.java
index 47a01de..e81d2b3 100644
--- a/src/me/libraryaddict/Hungergames/Managers/KitManager.java
+++ b/src/me/libraryaddict/Hungergames/Managers/KitManager.java
@@ -1,292 +1,296 @@
package me.libraryaddict.Hungergames.Managers;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import me.libraryaddict.Hungergames.Hungergames;
import me.libraryaddict.Hungergames.Types.HungergamesApi;
import me.libraryaddict.Hungergames.Types.Kit;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Color;
import org.bukkit.Material;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.LeatherArmorMeta;
public class KitManager {
private TranslationManager cm = HungergamesApi.getTranslationManager();
public String defaultKitName;
private ConcurrentLinkedQueue<Kit> defaultKits = new ConcurrentLinkedQueue<Kit>();
private Hungergames hg = HungergamesApi.getHungergames();
private ConcurrentHashMap<String, List<Kit>> hisKits = new ConcurrentHashMap<String, List<Kit>>();
private ArrayList<Kit> kits = new ArrayList<Kit>();
public KitManager() {
File file = new File(hg.getDataFolder().toString() + "/kits.yml");
ConfigurationSection config;
if (!file.exists()) {
file.getParentFile().mkdirs();
hg.saveResource("kits.yml", false);
}
config = YamlConfiguration.loadConfiguration(file);
defaultKitName = config.getString("DefaultKit", null);
for (String string : config.getConfigurationSection("Kits").getKeys(false)) {
if (config.contains("BadKits") && config.getStringList("BadKits").contains(string))
continue;
Kit kit = parseKit(config.getConfigurationSection("Kits." + string));
addKit(kit);
}
}
public void addItem(Player p, ItemStack item) {
int repeat = item.getAmount();
item.setAmount(1);
for (int i = 0; i < repeat; i++) {
if (canFit(p.getInventory(), new ItemStack[] { item }))
p.getInventory().addItem(item);
else {
if (item == null || item.getType() == Material.AIR)
continue;
else if (item.hasItemMeta())
p.getWorld().dropItemNaturally(p.getLocation(), item.clone()).getItemStack().setItemMeta(item.getItemMeta());
else
p.getWorld().dropItemNaturally(p.getLocation(), item);
}
}
}
public void addKit(final Kit newKit) {
if (getKitByName(newKit.getName()) != null) {
System.out.print(String.format(cm.getLoggerKitAlreadyExists(), newKit.getName()));
return;
}
kits.add(newKit);
if (newKit.isFree())
defaultKits.add(newKit);
List<String> kitNames = new ArrayList<String>();
for (Kit kit : kits)
kitNames.add(ChatColor.stripColor(kit.getName()));
Collections.sort(kitNames, String.CASE_INSENSITIVE_ORDER);
ArrayList<Kit> newKits = new ArrayList<Kit>();
for (int i = 0; i < kitNames.size(); i++) {
Kit kit = getKitByName(kitNames.get(i));
kit.setId(i);
newKits.add(kit);
}
kits = newKits;
}
public boolean addKitToPlayer(Player player, Kit kit) {
if (!HungergamesApi.getConfigManager().isMySqlEnabled())
return false;
if (!hisKits.containsKey(player.getName()))
hisKits.put(player.getName(), new ArrayList<Kit>());
if (!hisKits.get(player.getName()).contains(kit))
hisKits.get(player.getName()).add(kit);
return true;
}
public boolean canFit(Inventory pInv, ItemStack[] items) {
Inventory inv = Bukkit.createInventory(null, pInv.getContents().length);
for (int i = 0; i < inv.getSize(); i++) {
if (pInv.getItem(i) == null || pInv.getItem(i).getType() == Material.AIR)
continue;
inv.setItem(i, pInv.getItem(i).clone());
}
for (ItemStack i : items) {
HashMap<Integer, ItemStack> item = inv.addItem(i);
if (item != null && !item.isEmpty()) {
return false;
}
}
return true;
}
public Kit getKitByName(String name) {
name = ChatColor.stripColor(name);
for (Kit kit : kits)
if (ChatColor.stripColor(kit.getName()).equalsIgnoreCase(name))
return kit;
else if (hg.isNumeric(name) && Integer.parseInt(name) == kit.getId())
return kit;
return null;
}
public Kit getKitByPlayer(Player player) {
for (Kit kit : kits)
if (kit.getPlayers().contains(player))
return kit;
return null;
}
public ArrayList<Kit> getKits() {
return kits;
}
public List<Kit> getPlayersKits(Player player) {
return hisKits.get(player.getName());
}
public boolean ownsKit(Player player, Kit kit) {
if (defaultKits.contains(kit))
return true;
if (player.hasPermission(kit.getPermission()))
return true;
return hisKits.containsKey(player.getName()) && hisKits.get(player.getName()).contains(kit);
}
public ItemStack[] parseItem(String string) {
if (string == null)
return new ItemStack[] { null };
String[] args = string.split(" ");
try {
double amount = Integer.parseInt(args[2]);
ItemStack[] items = new ItemStack[(int) Math.ceil(amount / 64)];
if (items.length <= 0)
return new ItemStack[] { null };
for (int i = 0; i < items.length; i++) {
int id = hg.isNumeric(args[0]) ? Integer.parseInt(args[0])
: (Material.getMaterial(args[0].toUpperCase()) == null ? Material.AIR : Material.getMaterial(args[0]
.toUpperCase())).getId();
if (id == 0) {
System.out.print(String.format(cm.getLoggerUnrecognisedItemId(), args[0]));
return new ItemStack[] { null };
}
ItemStack item = new ItemStack(id, (int) amount, (short) Integer.parseInt(args[1]));
String[] newArgs = Arrays.copyOfRange(args, 3, args.length);
for (String argString : newArgs) {
if (argString.contains("Name=")) {
String name = ChatColor.translateAlternateColorCodes('&', argString.substring(5)).replaceAll("_", " ");
if (ChatColor.getLastColors(name).equals(""))
name = ChatColor.WHITE + name;
ItemMeta meta = item.getItemMeta();
String previous = meta.getDisplayName();
if (previous == null)
previous = "";
meta.setDisplayName(name + previous);
item.setItemMeta(meta);
} else if (argString.contains("Color=") && item.getType().name().contains("LEATHER")) {
String[] name = argString.substring(6).split(":");
int[] ids = new int[3];
for (int o = 0; o < 3; o++)
ids[o] = Integer.parseInt(name[o]);
LeatherArmorMeta meta = (LeatherArmorMeta) item.getItemMeta();
meta.setColor(Color.fromRGB(ids[0], ids[1], ids[2]));
item.setItemMeta(meta);
} else if (argString.equalsIgnoreCase("UniqueItem")) {
ItemMeta meta = item.getItemMeta();
String previous = meta.getDisplayName();
if (previous == null)
previous = "";
meta.setDisplayName(previous + "UniqueIdentifier");
item.setItemMeta(meta);
}
if (argString.contains("Lore=")) {
String name = ChatColor.translateAlternateColorCodes('&', argString.substring(5)).replaceAll("_", " ");
ItemMeta meta = item.getItemMeta();
List<String> lore = meta.getLore();
if (lore == null)
lore = new ArrayList<String>();
for (String a : name.split("\\n"))
lore.add(a);
meta.setLore(lore);
item.setItemMeta(meta);
}
}
for (int n = 0; n < newArgs.length; n++) {
Enchantment ench = Enchantment.getByName(newArgs[n]);
if (ench == null)
ench = Enchantment.getByName(newArgs[n].replace("_", " "));
if (ench == null)
ench = Enchantment.getByName(newArgs[n].replace("_", " ").toUpperCase());
if (ench == null)
continue;
item.addUnsafeEnchantment(ench, Integer.parseInt(newArgs[n + 1]));
n++;
}
item = EnchantmentManager.updateEnchants(item);
amount = amount - 64;
items[i] = item;
}
return items;
} catch (Exception ex) {
- System.out.print(String.format(cm.getLoggerErrorWhileParsingItemStack(), string, ex.getMessage()));
+ String message = ex.getMessage();
+ if (ex instanceof ArrayIndexOutOfBoundsException)
+ message = "java.lang.ArrayIndexOutOfBoundsException: " + message;
+ System.out.print(String.format(cm.getLoggerErrorWhileParsingItemStack(), string, message));
+ ex.printStackTrace();
}
return new ItemStack[] { null };
}
public Kit parseKit(ConfigurationSection path) {
String desc = ChatColor.translateAlternateColorCodes('&', path.getString("Description"));
String name = path.getString("Name");
if (name == null)
name = path.getName();
name = ChatColor.translateAlternateColorCodes('&', name);
ItemStack[] armor = new ItemStack[4];
armor[3] = parseItem(path.getString("Helmet"))[0];
armor[2] = parseItem(path.getString("Chestplate"))[0];
armor[1] = parseItem(path.getString("Leggings"))[0];
armor[0] = parseItem(path.getString("Boots"))[0];
List<String> itemList = path.getStringList("Items");
ArrayList<ItemStack> item = new ArrayList<ItemStack>();
if (itemList != null)
for (String string : itemList) {
ItemStack[] itemstacks = parseItem(string);
for (ItemStack itemstack : itemstacks)
if (itemstack != null)
item.add(itemstack);
}
ItemStack[] items = new ItemStack[item.size()];
for (int n = 0; n < item.size(); n++)
items[n] = item.get(n);
List<String> abilityList = path.getStringList("Ability");
String[] ability;
if (abilityList != null) {
ability = new String[abilityList.size()];
for (int n = 0; n < abilityList.size(); n++)
ability[n] = abilityList.get(n);
} else
ability = new String[0];
ItemStack icon = new ItemStack(Material.STONE);
if (path.contains("Icon")) {
icon = this.parseItem(path.getString("Icon"))[0];
if (icon == null)
icon = new ItemStack(Material.STONE);
}
Kit kit = new Kit(name, icon, armor, items, desc, ability);
if (path.getBoolean("Free", false) == true)
kit.setFree(true);
if (path.getInt("Price", -1) != -1)
kit.setPrice(path.getInt("Price"));
return kit;
}
public boolean removeKitFromPlayer(Player player, Kit kit) {
if (!hisKits.containsKey(player.getName()))
return false;
return hisKits.get(player.getName()).remove(kit);
}
public boolean setKit(Player p, String name) {
Kit kit = getKitByName(name);
if (kit == null)
return false;
Kit kita = getKitByPlayer(p);
if (kita != null)
kita.removePlayer(p);
kit.addPlayer(p);
return true;
}
}
| true | true | public ItemStack[] parseItem(String string) {
if (string == null)
return new ItemStack[] { null };
String[] args = string.split(" ");
try {
double amount = Integer.parseInt(args[2]);
ItemStack[] items = new ItemStack[(int) Math.ceil(amount / 64)];
if (items.length <= 0)
return new ItemStack[] { null };
for (int i = 0; i < items.length; i++) {
int id = hg.isNumeric(args[0]) ? Integer.parseInt(args[0])
: (Material.getMaterial(args[0].toUpperCase()) == null ? Material.AIR : Material.getMaterial(args[0]
.toUpperCase())).getId();
if (id == 0) {
System.out.print(String.format(cm.getLoggerUnrecognisedItemId(), args[0]));
return new ItemStack[] { null };
}
ItemStack item = new ItemStack(id, (int) amount, (short) Integer.parseInt(args[1]));
String[] newArgs = Arrays.copyOfRange(args, 3, args.length);
for (String argString : newArgs) {
if (argString.contains("Name=")) {
String name = ChatColor.translateAlternateColorCodes('&', argString.substring(5)).replaceAll("_", " ");
if (ChatColor.getLastColors(name).equals(""))
name = ChatColor.WHITE + name;
ItemMeta meta = item.getItemMeta();
String previous = meta.getDisplayName();
if (previous == null)
previous = "";
meta.setDisplayName(name + previous);
item.setItemMeta(meta);
} else if (argString.contains("Color=") && item.getType().name().contains("LEATHER")) {
String[] name = argString.substring(6).split(":");
int[] ids = new int[3];
for (int o = 0; o < 3; o++)
ids[o] = Integer.parseInt(name[o]);
LeatherArmorMeta meta = (LeatherArmorMeta) item.getItemMeta();
meta.setColor(Color.fromRGB(ids[0], ids[1], ids[2]));
item.setItemMeta(meta);
} else if (argString.equalsIgnoreCase("UniqueItem")) {
ItemMeta meta = item.getItemMeta();
String previous = meta.getDisplayName();
if (previous == null)
previous = "";
meta.setDisplayName(previous + "UniqueIdentifier");
item.setItemMeta(meta);
}
if (argString.contains("Lore=")) {
String name = ChatColor.translateAlternateColorCodes('&', argString.substring(5)).replaceAll("_", " ");
ItemMeta meta = item.getItemMeta();
List<String> lore = meta.getLore();
if (lore == null)
lore = new ArrayList<String>();
for (String a : name.split("\\n"))
lore.add(a);
meta.setLore(lore);
item.setItemMeta(meta);
}
}
for (int n = 0; n < newArgs.length; n++) {
Enchantment ench = Enchantment.getByName(newArgs[n]);
if (ench == null)
ench = Enchantment.getByName(newArgs[n].replace("_", " "));
if (ench == null)
ench = Enchantment.getByName(newArgs[n].replace("_", " ").toUpperCase());
if (ench == null)
continue;
item.addUnsafeEnchantment(ench, Integer.parseInt(newArgs[n + 1]));
n++;
}
item = EnchantmentManager.updateEnchants(item);
amount = amount - 64;
items[i] = item;
}
return items;
} catch (Exception ex) {
System.out.print(String.format(cm.getLoggerErrorWhileParsingItemStack(), string, ex.getMessage()));
}
return new ItemStack[] { null };
}
| public ItemStack[] parseItem(String string) {
if (string == null)
return new ItemStack[] { null };
String[] args = string.split(" ");
try {
double amount = Integer.parseInt(args[2]);
ItemStack[] items = new ItemStack[(int) Math.ceil(amount / 64)];
if (items.length <= 0)
return new ItemStack[] { null };
for (int i = 0; i < items.length; i++) {
int id = hg.isNumeric(args[0]) ? Integer.parseInt(args[0])
: (Material.getMaterial(args[0].toUpperCase()) == null ? Material.AIR : Material.getMaterial(args[0]
.toUpperCase())).getId();
if (id == 0) {
System.out.print(String.format(cm.getLoggerUnrecognisedItemId(), args[0]));
return new ItemStack[] { null };
}
ItemStack item = new ItemStack(id, (int) amount, (short) Integer.parseInt(args[1]));
String[] newArgs = Arrays.copyOfRange(args, 3, args.length);
for (String argString : newArgs) {
if (argString.contains("Name=")) {
String name = ChatColor.translateAlternateColorCodes('&', argString.substring(5)).replaceAll("_", " ");
if (ChatColor.getLastColors(name).equals(""))
name = ChatColor.WHITE + name;
ItemMeta meta = item.getItemMeta();
String previous = meta.getDisplayName();
if (previous == null)
previous = "";
meta.setDisplayName(name + previous);
item.setItemMeta(meta);
} else if (argString.contains("Color=") && item.getType().name().contains("LEATHER")) {
String[] name = argString.substring(6).split(":");
int[] ids = new int[3];
for (int o = 0; o < 3; o++)
ids[o] = Integer.parseInt(name[o]);
LeatherArmorMeta meta = (LeatherArmorMeta) item.getItemMeta();
meta.setColor(Color.fromRGB(ids[0], ids[1], ids[2]));
item.setItemMeta(meta);
} else if (argString.equalsIgnoreCase("UniqueItem")) {
ItemMeta meta = item.getItemMeta();
String previous = meta.getDisplayName();
if (previous == null)
previous = "";
meta.setDisplayName(previous + "UniqueIdentifier");
item.setItemMeta(meta);
}
if (argString.contains("Lore=")) {
String name = ChatColor.translateAlternateColorCodes('&', argString.substring(5)).replaceAll("_", " ");
ItemMeta meta = item.getItemMeta();
List<String> lore = meta.getLore();
if (lore == null)
lore = new ArrayList<String>();
for (String a : name.split("\\n"))
lore.add(a);
meta.setLore(lore);
item.setItemMeta(meta);
}
}
for (int n = 0; n < newArgs.length; n++) {
Enchantment ench = Enchantment.getByName(newArgs[n]);
if (ench == null)
ench = Enchantment.getByName(newArgs[n].replace("_", " "));
if (ench == null)
ench = Enchantment.getByName(newArgs[n].replace("_", " ").toUpperCase());
if (ench == null)
continue;
item.addUnsafeEnchantment(ench, Integer.parseInt(newArgs[n + 1]));
n++;
}
item = EnchantmentManager.updateEnchants(item);
amount = amount - 64;
items[i] = item;
}
return items;
} catch (Exception ex) {
String message = ex.getMessage();
if (ex instanceof ArrayIndexOutOfBoundsException)
message = "java.lang.ArrayIndexOutOfBoundsException: " + message;
System.out.print(String.format(cm.getLoggerErrorWhileParsingItemStack(), string, message));
ex.printStackTrace();
}
return new ItemStack[] { null };
}
|
diff --git a/src/uk/ac/gla/dcs/tp3/w/Main.java b/src/uk/ac/gla/dcs/tp3/w/Main.java
index b84e034..0a68e38 100644
--- a/src/uk/ac/gla/dcs/tp3/w/Main.java
+++ b/src/uk/ac/gla/dcs/tp3/w/Main.java
@@ -1,52 +1,52 @@
package uk.ac.gla.dcs.tp3.w;
import java.io.File;
import java.util.HashMap;
import javax.swing.SwingUtilities;
import uk.ac.gla.dcs.tp3.w.algorithm.Algorithm;
import uk.ac.gla.dcs.tp3.w.league.Division;
import uk.ac.gla.dcs.tp3.w.league.Team;
import uk.ac.gla.dcs.tp3.w.parser.Parser;
import uk.ac.gla.dcs.tp3.w.ui.MainFrame;
public class Main {
private static final String DEFAULT_FILE = System.getProperty("user.dir")
+ "/src/uk/ac/gla/dcs/tp3/w/parser/baseballSource.txt";
public static void main(String[] args) {
Parser p = null;
File source;
if (args.length == 0)
source = new File(DEFAULT_FILE);
else
source = new File(args[0]);
if (source.exists())
p = new Parser(source);
else
System.err.println("File not found.");
if (p == null)
return;
final HashMap<String, Division> map = new HashMap<String, Division>();
map.put("American Central", p.getAmericanCentral());
map.put("American East", p.getAmericanEast());
map.put("American West", p.getAmericanWest());
map.put("National Central", p.getNationalCentral());
map.put("National East", p.getNationalEast());
map.put("National West", p.getNationalWest());
Algorithm algorithm = new Algorithm();
for (Division d : map.values()) {
algorithm = new Algorithm(d);
for (Team t : d.getTeams())
- algorithm.isEliminated(t);
+ t.setEliminated(algorithm.isEliminated(t));
}
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new MainFrame(map);
}
});
}
}
| true | true | public static void main(String[] args) {
Parser p = null;
File source;
if (args.length == 0)
source = new File(DEFAULT_FILE);
else
source = new File(args[0]);
if (source.exists())
p = new Parser(source);
else
System.err.println("File not found.");
if (p == null)
return;
final HashMap<String, Division> map = new HashMap<String, Division>();
map.put("American Central", p.getAmericanCentral());
map.put("American East", p.getAmericanEast());
map.put("American West", p.getAmericanWest());
map.put("National Central", p.getNationalCentral());
map.put("National East", p.getNationalEast());
map.put("National West", p.getNationalWest());
Algorithm algorithm = new Algorithm();
for (Division d : map.values()) {
algorithm = new Algorithm(d);
for (Team t : d.getTeams())
algorithm.isEliminated(t);
}
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new MainFrame(map);
}
});
}
| public static void main(String[] args) {
Parser p = null;
File source;
if (args.length == 0)
source = new File(DEFAULT_FILE);
else
source = new File(args[0]);
if (source.exists())
p = new Parser(source);
else
System.err.println("File not found.");
if (p == null)
return;
final HashMap<String, Division> map = new HashMap<String, Division>();
map.put("American Central", p.getAmericanCentral());
map.put("American East", p.getAmericanEast());
map.put("American West", p.getAmericanWest());
map.put("National Central", p.getNationalCentral());
map.put("National East", p.getNationalEast());
map.put("National West", p.getNationalWest());
Algorithm algorithm = new Algorithm();
for (Division d : map.values()) {
algorithm = new Algorithm(d);
for (Team t : d.getTeams())
t.setEliminated(algorithm.isEliminated(t));
}
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new MainFrame(map);
}
});
}
|
diff --git a/ha/src/test/java/slavetest/AbstractHaTest.java b/ha/src/test/java/slavetest/AbstractHaTest.java
index d6e87bfb..68c5879f 100644
--- a/ha/src/test/java/slavetest/AbstractHaTest.java
+++ b/ha/src/test/java/slavetest/AbstractHaTest.java
@@ -1,813 +1,812 @@
/**
* Copyright (c) 2002-2011 "Neo Technology,"
* Network Engine for Objects in Lund AB [http://neotechnology.com]
*
* This file is part of Neo4j.
*
* Neo4j is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package slavetest;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.neo4j.helpers.collection.MapUtil.map;
import static org.neo4j.helpers.collection.MapUtil.stringMap;
import static org.neo4j.kernel.HighlyAvailableGraphDatabase.CONFIG_KEY_HA_PULL_INTERVAL;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;
import org.neo4j.com.Client;
import org.neo4j.graphdb.Direction;
import org.neo4j.graphdb.DynamicRelationshipType;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.PropertyContainer;
import org.neo4j.graphdb.Relationship;
import org.neo4j.graphdb.RelationshipType;
import org.neo4j.helpers.collection.IteratorUtil;
import org.neo4j.helpers.collection.MapUtil;
import org.neo4j.kernel.ha.Broker;
import org.neo4j.kernel.ha.BrokerFactory;
import org.neo4j.kernel.impl.batchinsert.BatchInserter;
import org.neo4j.kernel.impl.batchinsert.BatchInserterImpl;
import org.neo4j.kernel.impl.util.FileUtils;
public abstract class AbstractHaTest
{
static final RelationshipType REL_TYPE = DynamicRelationshipType.withName( "HA_TEST" );
static final File PARENT_PATH = new File( "target"+File.separator+"havar" );
static final File DBS_PATH = new File( PARENT_PATH, "dbs" );
static final File SKELETON_DB_PATH = new File( DBS_PATH, "skeleton" );
private boolean expectsResults;
private int nodeCount;
private int relCount;
private int nodePropCount;
private int relPropCount;
private int nodeIndexServicePropCount;
private int nodeIndexProviderPropCount;
private boolean doVerificationAfterTest;
private long storePrefix;
private int maxNum;
public @Rule
TestName testName = new TestName()
{
@Override
public String getMethodName()
{
return AbstractHaTest.this.getClass().getName() + "." + super.getMethodName();
}
};
public static BrokerFactory wrapBrokerAndSetPlaceHolderDb(
final PlaceHolderGraphDatabaseService placeHolderDb, final Broker broker )
{
return new BrokerFactory()
{
@Override
public Broker create( GraphDatabaseService graphDb, Map<String, String> graphDbConfig )
{
placeHolderDb.setDb( graphDb );
return broker;
}
};
}
protected String getStorePrefix()
{
return Long.toString( storePrefix ) + "-";
}
protected File dbPath( int num )
{
maxNum = Math.max( maxNum, num );
return new File( DBS_PATH, getStorePrefix() + num );
}
protected boolean shouldDoVerificationAfterTests()
{
return doVerificationAfterTest;
}
/**
* Here we do a best effort to remove all files from the test. In windows
* this occasionally fails and this is not a reason to fail the test. So we
* simply spawn off a thread that tries to delete what we created and if it
* actually succeeds so much the better. Otherwise, each test runs in its
* own directory, so no one will be stepping on anyone else's toes.
*/
@After
public void clearDb()
{
// Keep a local copy for the main thread to delete this
final List<File> toDelete = new LinkedList<File>();
for ( int i = 0; i <= maxNum; i++ )
{
toDelete.add( dbPath( i ) );
}
new Thread( new Runnable()
{
@Override
public void run()
{
for ( File deleteMe : toDelete )
{
try
{
FileUtils.deleteRecursively( deleteMe );
}
catch ( IOException e )
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
} ).start();
}
@Before
public void clearExpectedResults() throws Exception
{
maxNum = 0;
storePrefix = System.currentTimeMillis();
doVerificationAfterTest = true;
expectsResults = false;
}
public void verify( GraphDatabaseService refDb, GraphDatabaseService... dbs )
{
if ( !shouldDoVerificationAfterTests() )
{
return;
}
for ( GraphDatabaseService otherDb : dbs )
{
int vNodeCount = 0;
int vRelCount = 0;
int vNodePropCount = 0;
int vRelPropCount = 0;
int vNodeIndexServicePropCount = 0;
int vNodeIndexProviderPropCount = 0;
Set<Node> otherNodes = IteratorUtil.addToCollection( otherDb.getAllNodes().iterator(),
new HashSet<Node>() );
for ( Node node : refDb.getAllNodes() )
{
Node otherNode = otherDb.getNodeById( node.getId() );
int[] counts = verifyNode( node, otherNode, refDb, otherDb );
vRelCount += counts[0];
vNodePropCount += counts[1];
vRelPropCount += counts[2];
vNodeIndexServicePropCount += counts[3];
vNodeIndexProviderPropCount += counts[4];
otherNodes.remove( otherNode );
vNodeCount++;
}
if ( !otherNodes.isEmpty() ) System.out.println( otherNodes );
assertTrue( otherNodes.isEmpty() );
if ( expectsResults )
{
assertEquals( nodeCount, vNodeCount );
assertEquals( relCount, vRelCount );
assertEquals( nodePropCount, vNodePropCount );
assertEquals( relPropCount, vRelPropCount );
// assertEquals( nodeIndexServicePropCount, vNodeIndexServicePropCount );
assertEquals( nodeIndexProviderPropCount, vNodeIndexProviderPropCount );
}
}
}
private static int[] verifyNode( Node node, Node otherNode,
GraphDatabaseService refDb, GraphDatabaseService otherDb )
{
int vNodePropCount = verifyProperties( node, otherNode );
// int vNodeIndexServicePropCount = verifyIndexService( node, otherNode, refDb, otherDb );
int vNodeIndexProviderProCount = verifyIndexProvider( node, otherNode, refDb, otherDb );
Set<Long> otherRelIds = new HashSet<Long>();
for ( Relationship otherRel : otherNode.getRelationships( Direction.OUTGOING ) )
{
otherRelIds.add( otherRel.getId() );
}
int vRelCount = 0;
int vRelPropCount = 0;
for ( Relationship rel : node.getRelationships( Direction.OUTGOING ) )
{
Relationship otherRel = otherDb.getRelationshipById( rel.getId() );
vRelPropCount += verifyProperties( rel, otherRel );
if ( rel.getStartNode().getId() != otherRel.getStartNode().getId() )
{
throw new RuntimeException( "Start node differs on " + rel );
}
if ( rel.getEndNode().getId() != otherRel.getEndNode().getId() )
{
throw new RuntimeException( "End node differs on " + rel );
}
if ( !rel.getType().name().equals( otherRel.getType().name() ) )
{
throw new RuntimeException( "Type differs on " + rel );
}
otherRelIds.remove( rel.getId() );
vRelCount++;
}
if ( !otherRelIds.isEmpty() )
{
fail( "Other node " + otherNode + " has more relationships " + otherRelIds );
}
return new int[] { vRelCount, vNodePropCount, vRelPropCount, -1, vNodeIndexProviderProCount };
}
/* private static int verifyIndexService( Node node, Node otherNode, VerifyDbContext refDb,
VerifyDbContext otherDb )
{
return 0;
int count = 0;
if ( refDb.indexService == null || otherDb.indexService == null )
{
return count;
}
Set<String> otherKeys = new HashSet<String>();
for ( String key : otherNode.getPropertyKeys() )
{
if ( isIndexedWithIndexService( otherNode, otherDb, key ) )
{
otherKeys.add( key );
}
}
count = otherKeys.size();
for ( String key : node.getPropertyKeys() )
{
if ( otherKeys.remove( key ) != isIndexedWithIndexService( node, refDb, key ) )
{
throw new RuntimeException( "Index differs on " + node + ", " + key );
}
}
if ( !otherKeys.isEmpty() )
{
throw new RuntimeException( "Other node " + otherNode + " has more indexing: " +
otherKeys );
}
return count;
}*/
// private static boolean isIndexedWithIndexService( Node node, VerifyDbContext db, String key )
// {
// return false;
// // return db.indexService.getSingleNode( key, node.getProperty( key ) ) != null;
// }
/**
* This method is bogus... it really needs to ask all indexes, not the "users" index :)
*/
private static int verifyIndexProvider( Node node, Node otherNode, GraphDatabaseService refDb,
GraphDatabaseService otherDb )
{
int count = 0;
Set<String> otherKeys = new HashSet<String>();
for ( String key : otherNode.getPropertyKeys() )
{
if ( isIndexedWithIndexProvider( otherNode, otherDb, key ) )
{
otherKeys.add( key );
}
}
count = otherKeys.size();
for ( String key : node.getPropertyKeys() )
{
if ( otherKeys.remove( key ) != isIndexedWithIndexProvider( node, refDb, key ) )
{
throw new RuntimeException( "Index differs on " + node + ", " + key );
}
}
if ( !otherKeys.isEmpty() )
{
throw new RuntimeException( "Other node " + otherNode + " has more indexing: " +
otherKeys );
}
return count;
}
private static boolean isIndexedWithIndexProvider( Node node, GraphDatabaseService db, String key )
{
return db.index().forNodes( "users" ).get( key, node.getProperty( key ) ).getSingle() != null;
}
private static int verifyProperties( PropertyContainer entity, PropertyContainer otherEntity )
{
int count = 0;
Set<String> otherKeys = IteratorUtil.addToCollection(
otherEntity.getPropertyKeys().iterator(), new HashSet<String>() );
for ( String key : entity.getPropertyKeys() )
{
Object value1 = entity.getProperty( key );
Object value2 = otherEntity.getProperty( key );
if ( value1.getClass().isArray() && value2.getClass().isArray() )
{
}
else if ( !value1.equals( value2 ) )
{
throw new RuntimeException( entity + " not equals property '" + key + "': " +
value1 + ", " + value2 );
}
otherKeys.remove( key );
count++;
}
if ( !otherKeys.isEmpty() )
{
throw new RuntimeException( "Other node " + otherEntity + " has more properties: " +
otherKeys );
}
return count;
}
public static <T> void assertCollection( Collection<T> collection, T... expectedItems )
{
String collectionString = join( ", ", collection.toArray() );
assertEquals( collectionString, expectedItems.length,
collection.size() );
for ( T item : expectedItems )
{
assertTrue( collection.contains( item ) );
}
}
public static <T> String join( String delimiter, T... items )
{
StringBuffer buffer = new StringBuffer();
for ( T item : items )
{
if ( buffer.length() > 0 )
{
buffer.append( delimiter );
}
buffer.append( item.toString() );
}
return buffer.toString();
}
protected void initializeDbs( int numSlaves ) throws Exception
{
initializeDbs( numSlaves, MapUtil.stringMap() );
}
protected void initializeDbs( int numSlaves, Map<String, String> config ) throws Exception
{
startUpMaster( config );
for ( int i = 0; i < numSlaves; i++ )
{
addDb( config, true );
}
}
protected abstract void awaitAllStarted() throws Exception;
protected abstract int addDb( Map<String, String> config, boolean awaitStarted ) throws Exception;
protected abstract void startDb( int machineId, Map<String, String> config, boolean awaitStarted ) throws Exception;
protected abstract void pullUpdates( int... slaves ) throws Exception;
protected abstract <T> T executeJob( Job<T> job, int onSlave ) throws Exception;
protected abstract <T> T executeJobOnMaster( Job<T> job ) throws Exception;
protected abstract void startUpMaster( Map<String, String> config ) throws Exception;
protected abstract CommonJobs.ShutdownDispatcher getMasterShutdownDispatcher();
protected abstract void shutdownDbs() throws Exception;
protected abstract void shutdownDb( int machineId );
protected abstract Fetcher<DoubleLatch> getDoubleLatch() throws Exception;
private class Worker extends Thread
{
private boolean successfull;
private boolean deadlocked;
private final int slave;
private final Job<Boolean[]> job;
Worker( int slave, Job<Boolean[]> job )
{
this.slave = slave;
this.job = job;
}
@Override
public void run()
{
try
{
Boolean[] result = executeJob( job, slave );
successfull = result[0];
deadlocked = result[1];
}
catch ( Exception e )
{
e.printStackTrace();
}
}
}
protected void setExpectedResults( int nodeCount, int relCount,
int nodePropCount, int relPropCount, int nodeIndexServicePropCount, int nodeIndexProviderPropCount )
{
this.expectsResults = true;
this.nodeCount = nodeCount;
this.relCount = relCount;
this.nodePropCount = nodePropCount;
this.relPropCount = relPropCount;
this.nodeIndexServicePropCount = nodeIndexServicePropCount;
this.nodeIndexProviderPropCount = nodeIndexProviderPropCount;
}
@Test
public void slaveCreateNode() throws Exception
{
setExpectedResults( 3, 2, 2, 2, 0, 0 );
initializeDbs( 1 );
executeJob( new CommonJobs.CreateSomeEntitiesJob(), 0 );
}
@Test
public void slaveCanPullTransactionsThatOtherSlaveCommited() throws Exception
{
setExpectedResults( 2, 1, 1, 1, 0, 0 );
initializeDbs( 3 );
executeJob( new CommonJobs.CreateSubRefNodeJob( CommonJobs.REL_TYPE.name(), null, null ), 0 );
executeJob( new CommonJobs.SetSubRefPropertyJob( "name", "Hello" ), 1 );
pullUpdates( 0, 2 );
}
@Test
public void shutdownMasterBeforeFinishingTx() throws Exception
{
initializeDbs( 1 );
Serializable[] result = executeJob( new CommonJobs.CreateSubRefNodeMasterFailJob(
getMasterShutdownDispatcher() ), 0 );
assertFalse( (Boolean) result[0] );
startUpMaster( MapUtil.stringMap() );
long nodeId = (Long) result[1];
Boolean existed = executeJob( new CommonJobs.GetNodeByIdJob( nodeId ), 0 );
assertFalse( existed.booleanValue() );
}
@Test
public void slaveCannotDoAnInvalidTransaction() throws Exception
{
setExpectedResults( 2, 1, 0, 1, 0, 0 );
initializeDbs( 1 );
Long nodeId = executeJob( new CommonJobs.CreateSubRefNodeJob(
CommonJobs.REL_TYPE.name(), null, null ), 0 );
Boolean successful = executeJob( new CommonJobs.DeleteNodeJob( nodeId.longValue(),
false ), 0 );
assertFalse( successful.booleanValue() );
}
@Test
public void masterCannotDoAnInvalidTransaction() throws Exception
{
setExpectedResults( 2, 1, 1, 1, 0, 0 );
initializeDbs( 1 );
Long nodeId = executeJob( new CommonJobs.CreateSubRefNodeJob( CommonJobs.REL_TYPE.name(),
"name", "Mattias" ), 0 );
Boolean successful = executeJobOnMaster(
new CommonJobs.DeleteNodeJob( nodeId.longValue(), false ) );
assertFalse( successful.booleanValue() );
pullUpdates();
}
@Test
public void cacheInvalidationOfRelationships() throws Exception
{
setExpectedResults( 3, 2, 0, 0, 0, 0 );
initializeDbs( 1 );
assertEquals( (Integer) 1, executeJob( new CommonJobs.CreateSubRefNodeWithRelCountJob(
CommonJobs.REL_TYPE.name(), CommonJobs.REL_TYPE.name(), CommonJobs.KNOWS.name() ), 0 ) );
assertEquals( (Integer) 2, executeJob( new CommonJobs.CreateSubRefNodeWithRelCountJob(
CommonJobs.REL_TYPE.name(), CommonJobs.REL_TYPE.name(), CommonJobs.KNOWS.name() ), 0 ) );
assertEquals( (Integer) 2, executeJob( new CommonJobs.GetRelationshipCountJob(
CommonJobs.REL_TYPE.name(), CommonJobs.KNOWS.name() ), 0 ) );
assertEquals( (Integer) 2, executeJobOnMaster( new CommonJobs.GetRelationshipCountJob(
CommonJobs.REL_TYPE.name(), CommonJobs.KNOWS.name() ) ) );
}
@Test
public void writeOperationNeedsTransaction() throws Exception
{
setExpectedResults( 2, 1, 0, 1, 0, 0 );
initializeDbs( 1 );
executeJobOnMaster( new CommonJobs.CreateSubRefNodeJob(
CommonJobs.REL_TYPE.name(), null, null ) );
assertFalse( executeJob( new CommonJobs.CreateNodeOutsideOfTxJob(), 0 ).booleanValue() );
assertFalse( executeJobOnMaster( new CommonJobs.CreateNodeOutsideOfTxJob() ).booleanValue() );
}
@Test
public void slaveSetPropertyOnNodeDeletedByMaster() throws Exception
{
setExpectedResults( 1, 0, 0, 0, 0, 0 );
initializeDbs( 1 );
Long nodeId = executeJobOnMaster( new CommonJobs.CreateNodeJob() );
pullUpdates();
assertTrue( executeJobOnMaster( new CommonJobs.DeleteNodeJob(
nodeId.longValue(), false ) ).booleanValue() );
assertFalse( executeJob( new CommonJobs.SetNodePropertyJob( nodeId.longValue(), "something",
"some thing" ), 0 ) );
}
@Test
public void deadlockDetectionIsEnforced() throws Exception
{
initializeDbs( 2 );
Long[] nodes = executeJobOnMaster( new CommonJobs.CreateNodesJob( 2 ) );
pullUpdates();
Fetcher<DoubleLatch> fetcher = getDoubleLatch();
Worker w1 = new Worker( 0, new CommonJobs.Worker1Job( nodes[0], nodes[1], fetcher ) );
Worker w2 = new Worker( 1, new CommonJobs.Worker2Job( nodes[0], nodes[1], fetcher ) );
w1.start();
w2.start();
w1.join();
w2.join();
boolean case1 = w2.successfull && !w2.deadlocked && !w1.successfull && w1.deadlocked;
boolean case2 = !w2.successfull && w2.deadlocked && w1.successfull && !w1.deadlocked;
assertTrue( case1 != case2 );
assertTrue( case1 || case2 );
pullUpdates();
}
@Test
public void createNodeAndIndex() throws Exception
{
setExpectedResults( 2, 0, 1, 0, 1, 0 );
initializeDbs( 1 );
executeJob( new CommonJobs.CreateNodeAndIndexJob( "name", "Neo" ), 0 );
}
@Test
public void indexingIsSynchronizedBetweenInstances() throws Exception
{
initializeDbs( 2 );
long id = executeJobOnMaster( new CommonJobs.CreateNodeAndIndexJob( "name", "Morpheus" ) );
pullUpdates();
long id2 = executeJobOnMaster( new CommonJobs.CreateNodeAndIndexJob( "name", "Trinity" ) );
executeJob( new CommonJobs.AddIndex( id, MapUtil.map( "key1",
new String[] { "value1", "value2" }, "key 2", 105.43f ) ), 1 );
pullUpdates();
}
@Ignore( "Not suitable for a unit test, rely on HA Cronies to test this" )
@Test
public void testLargeTransaction() throws Exception
{
initializeDbs( 1 );
executeJob( new CommonJobs.LargeTransactionJob( 20, 1 ), 0 );
}
@Ignore( "Not suitable for a unit test, rely on HA Cronies to test this" )
@Test
public void testPullLargeTransaction() throws Exception
{
initializeDbs( 1 );
executeJobOnMaster( new CommonJobs.LargeTransactionJob( 20, 1 ) );
pullUpdates();
}
@Ignore( "Not suitable for a unit test, rely on HA Cronies to test this" )
@Test
public void testLargeTransactionData() throws Exception
{
initializeDbs( 1 );
executeJob( new CommonJobs.LargeTransactionJob( 1, 20 ), 0 );
}
@Ignore( "Not suitable for a unit test, rely on HA Cronies to test this" )
@Test
public void testPullLargeTransactionData() throws Exception
{
initializeDbs( 1 );
executeJobOnMaster( new CommonJobs.LargeTransactionJob( 1, 20 ) );
pullUpdates();
}
@Ignore( "Not suitable for a unit test, rely on HA Cronies to test this" )
@Test
public void makeSureSlaveCanCopyLargeInitialDatabase() throws Exception
{
disableVerificationAfterTest();
createBigMasterStore( 500 );
startUpMaster( MapUtil.stringMap() );
addDb( MapUtil.stringMap(), true );
awaitAllStarted();
executeJob( new CommonJobs.CreateSubRefNodeJob( "whatever", "my_key", "my_value" ), 0 );
}
protected void createBigMasterStore( int numberOfMegabytes )
{
// Will result in a 500Mb store
BatchInserter inserter = new BatchInserterImpl( dbPath( 0 ).getAbsolutePath() );
byte[] array = new byte[100000];
for ( int i = 0; i < numberOfMegabytes*10; i++ )
{
inserter.createNode( map( "array", array ) );
}
inserter.shutdown();
}
@Test
public void canCopyInitialDbWithLuceneIndexes() throws Exception
{
int additionalNodeCount = 50;
setExpectedResults( 1+additionalNodeCount, 0, additionalNodeCount*2, 0, 0, additionalNodeCount*2 );
startUpMaster( MapUtil.stringMap() );
for ( int i = 0; i < additionalNodeCount; i++ )
{
executeJobOnMaster( new CommonJobs.CreateNodeAndNewIndexJob( "users",
"the key " + i, "the best value",
"a key " + i, "the worst value" ) );
}
addDb( MapUtil.stringMap(), true );
awaitAllStarted();
}
@Test
public void makeSurePullIntervalWorks() throws Exception
{
startUpMaster( stringMap() );
int waitTime = 2;
addDb( stringMap( CONFIG_KEY_HA_PULL_INTERVAL, String.valueOf( waitTime ) ), true );
Long nodeId = executeJobOnMaster( new CommonJobs.CreateSubRefNodeJob( "PULL", "key", "value" ) );
sleeep( waitTime*1000*2 );
assertTrue( executeJob( new CommonJobs.GetNodeByIdJob( nodeId ), 0 ) );
}
- @Ignore( "Turn on when problem has been fixed" )
@Test
public void testChannelResourcePool() throws Exception
{
initializeDbs( 1 );
List<WorkerThread> jobs = new LinkedList<WorkerThread>();
for ( int i = 0; i < Client.DEFAULT_MAX_NUMBER_OF_CONCURRENT_REQUESTS_PER_CLIENT; i++ )
{
WorkerThread job = new WorkerThread( this );
jobs.add( job );
job.start();
}
for ( int i = 0; i < 10; i++ )
{
int count = 0;
for ( WorkerThread job : jobs )
{
if ( job.nodeHasBeenCreatedOnTx() )
{
count++;
}
else
{
break;
}
}
if ( count == jobs.size() )
{
break;
}
sleeep( 100 );
}
WorkerThread jobShouldNotBlock = new WorkerThread( this );
jobShouldNotBlock.start();
for ( int i = 0; i < 10; i++ )
{
if ( jobShouldNotBlock.nodeHasBeenCreatedOnTx() )
{
break;
}
sleeep( 250 );
}
assertTrue( "Create node should not have been blocked", jobShouldNotBlock.nodeHasBeenCreatedOnTx() );
for ( WorkerThread job : jobs )
{
job.finish();
job.join();
}
jobShouldNotBlock.finish();
jobShouldNotBlock.join();
}
static class WorkerThread extends Thread
{
private final AbstractHaTest testCase;
private volatile boolean keepRunning = true;
private volatile boolean nodeCreatedOnTx = false;
WorkerThread( AbstractHaTest testCase )
{
this.testCase = testCase;
}
@Override
public void run()
{
final CommonJobs.CreateNodeNoCommit job = new CommonJobs.CreateNodeNoCommit();
try
{
testCase.executeJob( job, 0 );
nodeCreatedOnTx = true;
}
catch ( Exception e )
{
// TODO Auto-generated catch block
e.printStackTrace();
}
while ( keepRunning )
{
try
{
synchronized ( this )
{
wait( 100 );
}
}
catch ( InterruptedException e )
{
Thread.interrupted();
}
}
job.rollback();
}
void finish()
{
keepRunning = false;
}
boolean nodeHasBeenCreatedOnTx()
{
return nodeCreatedOnTx;
}
}
protected void disableVerificationAfterTest()
{
doVerificationAfterTest = false;
}
protected void sleeep( int i )
{
try
{
Thread.sleep( i );
}
catch ( InterruptedException e )
{
Thread.interrupted();
throw new RuntimeException( e );
}
}
}
| true | true | public void indexingIsSynchronizedBetweenInstances() throws Exception
{
initializeDbs( 2 );
long id = executeJobOnMaster( new CommonJobs.CreateNodeAndIndexJob( "name", "Morpheus" ) );
pullUpdates();
long id2 = executeJobOnMaster( new CommonJobs.CreateNodeAndIndexJob( "name", "Trinity" ) );
executeJob( new CommonJobs.AddIndex( id, MapUtil.map( "key1",
new String[] { "value1", "value2" }, "key 2", 105.43f ) ), 1 );
pullUpdates();
}
@Ignore( "Not suitable for a unit test, rely on HA Cronies to test this" )
@Test
public void testLargeTransaction() throws Exception
{
initializeDbs( 1 );
executeJob( new CommonJobs.LargeTransactionJob( 20, 1 ), 0 );
}
@Ignore( "Not suitable for a unit test, rely on HA Cronies to test this" )
@Test
public void testPullLargeTransaction() throws Exception
{
initializeDbs( 1 );
executeJobOnMaster( new CommonJobs.LargeTransactionJob( 20, 1 ) );
pullUpdates();
}
@Ignore( "Not suitable for a unit test, rely on HA Cronies to test this" )
@Test
public void testLargeTransactionData() throws Exception
{
initializeDbs( 1 );
executeJob( new CommonJobs.LargeTransactionJob( 1, 20 ), 0 );
}
@Ignore( "Not suitable for a unit test, rely on HA Cronies to test this" )
@Test
public void testPullLargeTransactionData() throws Exception
{
initializeDbs( 1 );
executeJobOnMaster( new CommonJobs.LargeTransactionJob( 1, 20 ) );
pullUpdates();
}
@Ignore( "Not suitable for a unit test, rely on HA Cronies to test this" )
@Test
public void makeSureSlaveCanCopyLargeInitialDatabase() throws Exception
{
disableVerificationAfterTest();
createBigMasterStore( 500 );
startUpMaster( MapUtil.stringMap() );
addDb( MapUtil.stringMap(), true );
awaitAllStarted();
executeJob( new CommonJobs.CreateSubRefNodeJob( "whatever", "my_key", "my_value" ), 0 );
}
protected void createBigMasterStore( int numberOfMegabytes )
{
// Will result in a 500Mb store
BatchInserter inserter = new BatchInserterImpl( dbPath( 0 ).getAbsolutePath() );
byte[] array = new byte[100000];
for ( int i = 0; i < numberOfMegabytes*10; i++ )
{
inserter.createNode( map( "array", array ) );
}
inserter.shutdown();
}
@Test
public void canCopyInitialDbWithLuceneIndexes() throws Exception
{
int additionalNodeCount = 50;
setExpectedResults( 1+additionalNodeCount, 0, additionalNodeCount*2, 0, 0, additionalNodeCount*2 );
startUpMaster( MapUtil.stringMap() );
for ( int i = 0; i < additionalNodeCount; i++ )
{
executeJobOnMaster( new CommonJobs.CreateNodeAndNewIndexJob( "users",
"the key " + i, "the best value",
"a key " + i, "the worst value" ) );
}
addDb( MapUtil.stringMap(), true );
awaitAllStarted();
}
@Test
public void makeSurePullIntervalWorks() throws Exception
{
startUpMaster( stringMap() );
int waitTime = 2;
addDb( stringMap( CONFIG_KEY_HA_PULL_INTERVAL, String.valueOf( waitTime ) ), true );
Long nodeId = executeJobOnMaster( new CommonJobs.CreateSubRefNodeJob( "PULL", "key", "value" ) );
sleeep( waitTime*1000*2 );
assertTrue( executeJob( new CommonJobs.GetNodeByIdJob( nodeId ), 0 ) );
}
@Ignore( "Turn on when problem has been fixed" )
@Test
public void testChannelResourcePool() throws Exception
{
initializeDbs( 1 );
List<WorkerThread> jobs = new LinkedList<WorkerThread>();
for ( int i = 0; i < Client.DEFAULT_MAX_NUMBER_OF_CONCURRENT_REQUESTS_PER_CLIENT; i++ )
{
WorkerThread job = new WorkerThread( this );
jobs.add( job );
job.start();
}
for ( int i = 0; i < 10; i++ )
{
int count = 0;
for ( WorkerThread job : jobs )
{
if ( job.nodeHasBeenCreatedOnTx() )
{
count++;
}
else
{
break;
}
}
if ( count == jobs.size() )
{
break;
}
sleeep( 100 );
}
WorkerThread jobShouldNotBlock = new WorkerThread( this );
jobShouldNotBlock.start();
for ( int i = 0; i < 10; i++ )
{
if ( jobShouldNotBlock.nodeHasBeenCreatedOnTx() )
{
break;
}
sleeep( 250 );
}
assertTrue( "Create node should not have been blocked", jobShouldNotBlock.nodeHasBeenCreatedOnTx() );
for ( WorkerThread job : jobs )
{
job.finish();
job.join();
}
jobShouldNotBlock.finish();
jobShouldNotBlock.join();
}
static class WorkerThread extends Thread
{
private final AbstractHaTest testCase;
private volatile boolean keepRunning = true;
private volatile boolean nodeCreatedOnTx = false;
WorkerThread( AbstractHaTest testCase )
{
this.testCase = testCase;
}
@Override
public void run()
{
final CommonJobs.CreateNodeNoCommit job = new CommonJobs.CreateNodeNoCommit();
try
{
testCase.executeJob( job, 0 );
nodeCreatedOnTx = true;
}
catch ( Exception e )
{
// TODO Auto-generated catch block
e.printStackTrace();
}
while ( keepRunning )
{
try
{
synchronized ( this )
{
wait( 100 );
}
}
catch ( InterruptedException e )
{
Thread.interrupted();
}
}
job.rollback();
}
void finish()
{
keepRunning = false;
}
boolean nodeHasBeenCreatedOnTx()
{
return nodeCreatedOnTx;
}
}
protected void disableVerificationAfterTest()
{
doVerificationAfterTest = false;
}
protected void sleeep( int i )
{
try
{
Thread.sleep( i );
}
catch ( InterruptedException e )
{
Thread.interrupted();
throw new RuntimeException( e );
}
}
}
| public void indexingIsSynchronizedBetweenInstances() throws Exception
{
initializeDbs( 2 );
long id = executeJobOnMaster( new CommonJobs.CreateNodeAndIndexJob( "name", "Morpheus" ) );
pullUpdates();
long id2 = executeJobOnMaster( new CommonJobs.CreateNodeAndIndexJob( "name", "Trinity" ) );
executeJob( new CommonJobs.AddIndex( id, MapUtil.map( "key1",
new String[] { "value1", "value2" }, "key 2", 105.43f ) ), 1 );
pullUpdates();
}
@Ignore( "Not suitable for a unit test, rely on HA Cronies to test this" )
@Test
public void testLargeTransaction() throws Exception
{
initializeDbs( 1 );
executeJob( new CommonJobs.LargeTransactionJob( 20, 1 ), 0 );
}
@Ignore( "Not suitable for a unit test, rely on HA Cronies to test this" )
@Test
public void testPullLargeTransaction() throws Exception
{
initializeDbs( 1 );
executeJobOnMaster( new CommonJobs.LargeTransactionJob( 20, 1 ) );
pullUpdates();
}
@Ignore( "Not suitable for a unit test, rely on HA Cronies to test this" )
@Test
public void testLargeTransactionData() throws Exception
{
initializeDbs( 1 );
executeJob( new CommonJobs.LargeTransactionJob( 1, 20 ), 0 );
}
@Ignore( "Not suitable for a unit test, rely on HA Cronies to test this" )
@Test
public void testPullLargeTransactionData() throws Exception
{
initializeDbs( 1 );
executeJobOnMaster( new CommonJobs.LargeTransactionJob( 1, 20 ) );
pullUpdates();
}
@Ignore( "Not suitable for a unit test, rely on HA Cronies to test this" )
@Test
public void makeSureSlaveCanCopyLargeInitialDatabase() throws Exception
{
disableVerificationAfterTest();
createBigMasterStore( 500 );
startUpMaster( MapUtil.stringMap() );
addDb( MapUtil.stringMap(), true );
awaitAllStarted();
executeJob( new CommonJobs.CreateSubRefNodeJob( "whatever", "my_key", "my_value" ), 0 );
}
protected void createBigMasterStore( int numberOfMegabytes )
{
// Will result in a 500Mb store
BatchInserter inserter = new BatchInserterImpl( dbPath( 0 ).getAbsolutePath() );
byte[] array = new byte[100000];
for ( int i = 0; i < numberOfMegabytes*10; i++ )
{
inserter.createNode( map( "array", array ) );
}
inserter.shutdown();
}
@Test
public void canCopyInitialDbWithLuceneIndexes() throws Exception
{
int additionalNodeCount = 50;
setExpectedResults( 1+additionalNodeCount, 0, additionalNodeCount*2, 0, 0, additionalNodeCount*2 );
startUpMaster( MapUtil.stringMap() );
for ( int i = 0; i < additionalNodeCount; i++ )
{
executeJobOnMaster( new CommonJobs.CreateNodeAndNewIndexJob( "users",
"the key " + i, "the best value",
"a key " + i, "the worst value" ) );
}
addDb( MapUtil.stringMap(), true );
awaitAllStarted();
}
@Test
public void makeSurePullIntervalWorks() throws Exception
{
startUpMaster( stringMap() );
int waitTime = 2;
addDb( stringMap( CONFIG_KEY_HA_PULL_INTERVAL, String.valueOf( waitTime ) ), true );
Long nodeId = executeJobOnMaster( new CommonJobs.CreateSubRefNodeJob( "PULL", "key", "value" ) );
sleeep( waitTime*1000*2 );
assertTrue( executeJob( new CommonJobs.GetNodeByIdJob( nodeId ), 0 ) );
}
@Test
public void testChannelResourcePool() throws Exception
{
initializeDbs( 1 );
List<WorkerThread> jobs = new LinkedList<WorkerThread>();
for ( int i = 0; i < Client.DEFAULT_MAX_NUMBER_OF_CONCURRENT_REQUESTS_PER_CLIENT; i++ )
{
WorkerThread job = new WorkerThread( this );
jobs.add( job );
job.start();
}
for ( int i = 0; i < 10; i++ )
{
int count = 0;
for ( WorkerThread job : jobs )
{
if ( job.nodeHasBeenCreatedOnTx() )
{
count++;
}
else
{
break;
}
}
if ( count == jobs.size() )
{
break;
}
sleeep( 100 );
}
WorkerThread jobShouldNotBlock = new WorkerThread( this );
jobShouldNotBlock.start();
for ( int i = 0; i < 10; i++ )
{
if ( jobShouldNotBlock.nodeHasBeenCreatedOnTx() )
{
break;
}
sleeep( 250 );
}
assertTrue( "Create node should not have been blocked", jobShouldNotBlock.nodeHasBeenCreatedOnTx() );
for ( WorkerThread job : jobs )
{
job.finish();
job.join();
}
jobShouldNotBlock.finish();
jobShouldNotBlock.join();
}
static class WorkerThread extends Thread
{
private final AbstractHaTest testCase;
private volatile boolean keepRunning = true;
private volatile boolean nodeCreatedOnTx = false;
WorkerThread( AbstractHaTest testCase )
{
this.testCase = testCase;
}
@Override
public void run()
{
final CommonJobs.CreateNodeNoCommit job = new CommonJobs.CreateNodeNoCommit();
try
{
testCase.executeJob( job, 0 );
nodeCreatedOnTx = true;
}
catch ( Exception e )
{
// TODO Auto-generated catch block
e.printStackTrace();
}
while ( keepRunning )
{
try
{
synchronized ( this )
{
wait( 100 );
}
}
catch ( InterruptedException e )
{
Thread.interrupted();
}
}
job.rollback();
}
void finish()
{
keepRunning = false;
}
boolean nodeHasBeenCreatedOnTx()
{
return nodeCreatedOnTx;
}
}
protected void disableVerificationAfterTest()
{
doVerificationAfterTest = false;
}
protected void sleeep( int i )
{
try
{
Thread.sleep( i );
}
catch ( InterruptedException e )
{
Thread.interrupted();
throw new RuntimeException( e );
}
}
}
|
diff --git a/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/DatasourceComponent.java b/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/DatasourceComponent.java
index 4a7c4cc8f3..68c0bce802 100644
--- a/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/DatasourceComponent.java
+++ b/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/DatasourceComponent.java
@@ -1,120 +1,120 @@
package org.rhq.modules.plugins.jbossas7;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.rhq.core.domain.configuration.Configuration;
import org.rhq.core.domain.configuration.PropertySimple;
import org.rhq.core.pluginapi.operation.OperationFacet;
import org.rhq.core.pluginapi.operation.OperationResult;
import org.rhq.modules.plugins.jbossas7.json.Address;
import org.rhq.modules.plugins.jbossas7.json.Operation;
import org.rhq.modules.plugins.jbossas7.json.PROPERTY_VALUE;
import org.rhq.modules.plugins.jbossas7.json.Result;
/**
* Handle JDBC-driver related stuff
* @author Heiko W. Rupp
*/
public class DatasourceComponent extends BaseComponent implements OperationFacet {
private static final String NOTSET = "-notset-";
private final Log log = LogFactory.getLog(DatasourceComponent.class);
@Override
public OperationResult invokeOperation(String operationName,
Configuration parameters) throws Exception {
OperationResult result = new OperationResult();
ASConnection connection = getASConnection();
Operation op;
if (operationName.equals("addDriver")) { // TODO decide if we need this at all. See also the plugin-descriptor
String drivername = parameters.getSimpleValue("driver-name", NOTSET);
Address theAddress = new Address(address);
theAddress.add("jdbc-driver", drivername);
op = new Operation("add",theAddress);
op.addAdditionalProperty("driver-name",drivername);
op.addAdditionalProperty("deployment-name",parameters.getSimpleValue("deployment-name", NOTSET));
op.addAdditionalProperty("driver-class-name",parameters.getSimpleValue("driver-class-name", NOTSET));
}
else if (operationName.equals("addDatasource")) {
String name = parameters.getSimpleValue("name",NOTSET);
Address theAddress = new Address(address);
theAddress.add("data-source", name);
op = new Operation("add",theAddress);
addRequiredToOp(op,parameters,"driver-name");
addRequiredToOp(op,parameters,"jndi-name");
addRequiredToOp(op, parameters, "connection-url");
addOptionalToOp(op, parameters, "user-name");
addOptionalToOp(op,parameters,"password");
}
else if (operationName.equals("addXADatasource")) {
String name = parameters.getSimpleValue("name",NOTSET);
Address theAddress = new Address(address);
theAddress.add("xa-data-source",name);
op = new Operation("add",theAddress);
addRequiredToOp(op,parameters,"driver-name");
addRequiredToOp(op,parameters,"jndi-name");
addOptionalToOp(op,parameters,"user-name");
addOptionalToOp(op,parameters,"password");
- addRequiredToOp(op,parameters,"xa-data-source-class");
+ addRequiredToOp(op,parameters,"xa-datasource-class");
Map<String,Object> props = new HashMap<String, Object>(); // TODO
op.addAdditionalProperty("xa-data-source-properties",props);
}
else {
/*
* This is a catch all for operations that are not explicitly treated above.
*/
op = new Operation(operationName,address);
}
Result res = connection.execute(op);
if (res.isSuccess()) {
result.setSimpleResult("Success");
}
else {
result.setErrorMessage(res.getFailureDescription());
}
return result;
}
void addAdditionalToOp(Operation op, Configuration parameters, String property, boolean optional) {
PropertySimple ps = parameters.getSimple(property);
if (ps==null) {
if (!optional)
throw new IllegalArgumentException("Property " + property + " not found for required parameter");
}
else {
String tmp = ps.getStringValue();
if (tmp!=null) {
op.addAdditionalProperty(property,tmp);
}
}
}
void addRequiredToOp(Operation op, Configuration parameters, String property) {
addAdditionalToOp(op,parameters,property,false);
}
void addOptionalToOp(Operation op, Configuration parameters, String property) {
addAdditionalToOp(op,parameters,property,true);
}
}
| true | true | public OperationResult invokeOperation(String operationName,
Configuration parameters) throws Exception {
OperationResult result = new OperationResult();
ASConnection connection = getASConnection();
Operation op;
if (operationName.equals("addDriver")) { // TODO decide if we need this at all. See also the plugin-descriptor
String drivername = parameters.getSimpleValue("driver-name", NOTSET);
Address theAddress = new Address(address);
theAddress.add("jdbc-driver", drivername);
op = new Operation("add",theAddress);
op.addAdditionalProperty("driver-name",drivername);
op.addAdditionalProperty("deployment-name",parameters.getSimpleValue("deployment-name", NOTSET));
op.addAdditionalProperty("driver-class-name",parameters.getSimpleValue("driver-class-name", NOTSET));
}
else if (operationName.equals("addDatasource")) {
String name = parameters.getSimpleValue("name",NOTSET);
Address theAddress = new Address(address);
theAddress.add("data-source", name);
op = new Operation("add",theAddress);
addRequiredToOp(op,parameters,"driver-name");
addRequiredToOp(op,parameters,"jndi-name");
addRequiredToOp(op, parameters, "connection-url");
addOptionalToOp(op, parameters, "user-name");
addOptionalToOp(op,parameters,"password");
}
else if (operationName.equals("addXADatasource")) {
String name = parameters.getSimpleValue("name",NOTSET);
Address theAddress = new Address(address);
theAddress.add("xa-data-source",name);
op = new Operation("add",theAddress);
addRequiredToOp(op,parameters,"driver-name");
addRequiredToOp(op,parameters,"jndi-name");
addOptionalToOp(op,parameters,"user-name");
addOptionalToOp(op,parameters,"password");
addRequiredToOp(op,parameters,"xa-data-source-class");
Map<String,Object> props = new HashMap<String, Object>(); // TODO
op.addAdditionalProperty("xa-data-source-properties",props);
}
else {
/*
* This is a catch all for operations that are not explicitly treated above.
*/
op = new Operation(operationName,address);
}
Result res = connection.execute(op);
if (res.isSuccess()) {
result.setSimpleResult("Success");
}
else {
result.setErrorMessage(res.getFailureDescription());
}
return result;
}
| public OperationResult invokeOperation(String operationName,
Configuration parameters) throws Exception {
OperationResult result = new OperationResult();
ASConnection connection = getASConnection();
Operation op;
if (operationName.equals("addDriver")) { // TODO decide if we need this at all. See also the plugin-descriptor
String drivername = parameters.getSimpleValue("driver-name", NOTSET);
Address theAddress = new Address(address);
theAddress.add("jdbc-driver", drivername);
op = new Operation("add",theAddress);
op.addAdditionalProperty("driver-name",drivername);
op.addAdditionalProperty("deployment-name",parameters.getSimpleValue("deployment-name", NOTSET));
op.addAdditionalProperty("driver-class-name",parameters.getSimpleValue("driver-class-name", NOTSET));
}
else if (operationName.equals("addDatasource")) {
String name = parameters.getSimpleValue("name",NOTSET);
Address theAddress = new Address(address);
theAddress.add("data-source", name);
op = new Operation("add",theAddress);
addRequiredToOp(op,parameters,"driver-name");
addRequiredToOp(op,parameters,"jndi-name");
addRequiredToOp(op, parameters, "connection-url");
addOptionalToOp(op, parameters, "user-name");
addOptionalToOp(op,parameters,"password");
}
else if (operationName.equals("addXADatasource")) {
String name = parameters.getSimpleValue("name",NOTSET);
Address theAddress = new Address(address);
theAddress.add("xa-data-source",name);
op = new Operation("add",theAddress);
addRequiredToOp(op,parameters,"driver-name");
addRequiredToOp(op,parameters,"jndi-name");
addOptionalToOp(op,parameters,"user-name");
addOptionalToOp(op,parameters,"password");
addRequiredToOp(op,parameters,"xa-datasource-class");
Map<String,Object> props = new HashMap<String, Object>(); // TODO
op.addAdditionalProperty("xa-data-source-properties",props);
}
else {
/*
* This is a catch all for operations that are not explicitly treated above.
*/
op = new Operation(operationName,address);
}
Result res = connection.execute(op);
if (res.isSuccess()) {
result.setSimpleResult("Success");
}
else {
result.setErrorMessage(res.getFailureDescription());
}
return result;
}
|
diff --git a/src/com/orange/place/api/service/ServiceHandler.java b/src/com/orange/place/api/service/ServiceHandler.java
index 7bd51b2..059b109 100644
--- a/src/com/orange/place/api/service/ServiceHandler.java
+++ b/src/com/orange/place/api/service/ServiceHandler.java
@@ -1,127 +1,127 @@
package com.orange.place.api.service;
import java.io.IOException;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONException;
import me.prettyprint.hector.api.exceptions.HectorException;
import com.orange.common.cassandra.CassandraClient;
import com.orange.place.api.PlaceAPIServer;
import com.orange.place.constant.DBConstants;
import com.orange.place.constant.ErrorCode;
import com.orange.place.constant.ServiceConstant;
public class ServiceHandler {
public static final CassandraClient cassandraClient = new CassandraClient(
DBConstants.SERVER, DBConstants.CLUSTERNAME, DBConstants.KEYSPACE);
private static final Logger log = Logger.getLogger(PlaceAPIServer.class
.getName());
public static ServiceHandler getServiceHandler() {
ServiceHandler handler = new ServiceHandler();
return handler;
}
public void handlRequest(HttpServletRequest request,
HttpServletResponse response) {
printRequest(request);
String method = request.getParameter(ServiceConstant.METHOD);
CommonService obj = null;
try {
obj = CommonService.createServiceObjectByMethod(method);
} catch (InstantiationException e1) {
log
.severe("<handlRequest> but exception while create service object for method("
+ method + "), exception=" + e1.toString());
e1.printStackTrace();
} catch (IllegalAccessException e1) {
log
.severe("<handlRequest> but exception while create service object for method("
+ method + "), exception=" + e1.toString());
e1.printStackTrace();
}
try {
if (obj == null) {
sendResponseByErrorCode(response,
ErrorCode.ERROR_PARA_METHOD_NOT_FOUND);
return;
}
obj.setCassandraClient(cassandraClient);
obj.setRequest(request);
if (!obj.validateSecurity(request)) {
sendResponseByErrorCode(response,
ErrorCode.ERROR_INVALID_SECURITY);
return;
}
// parse request parameters
- sendResponseByErrorCode(response, obj.resultCode);
if (!obj.setDataFromRequest(request)) {
+ sendResponseByErrorCode(response, obj.resultCode);
return;
}
// print parameters
obj.printData();
// handle request
obj.handleData();
} catch (HectorException e) {
obj.resultCode = ErrorCode.ERROR_CASSANDRA;
log.severe("catch DB exception=" + e.toString());
e.printStackTrace();
} catch (JSONException e) {
obj.resultCode = ErrorCode.ERROR_JSON;
log.severe("catch JSON exception=" + e.toString());
e.printStackTrace();
} catch (Exception e) {
obj.resultCode = ErrorCode.ERROR_SYSTEM;
log.severe("catch general exception=" + e.toString());
e.printStackTrace();
} finally {
}
String responseData = obj.getResponseString();
// send back response
sendResponse(response, responseData);
}
void printRequest(HttpServletRequest request) {
log.info("[RECV] request = " + request.getQueryString());
}
void printResponse(HttpServletResponse reponse, String responseData) {
log.info("[SEND] response data = " + responseData);
}
void sendResponse(HttpServletResponse response, String responseData) {
printResponse(response, responseData);
response.setContentType("application/json; charset=utf-8");
try {
response.getWriter().write(responseData);
response.getWriter().flush();
} catch (IOException e) {
log.severe("sendResponse, catch exception=" + e.toString());
}
}
void sendResponseByErrorCode(HttpServletResponse response, int errorCode) {
String resultString = ErrorCode.getJSONByErrorCode(errorCode);
sendResponse(response, resultString);
}
}
| false | true | public void handlRequest(HttpServletRequest request,
HttpServletResponse response) {
printRequest(request);
String method = request.getParameter(ServiceConstant.METHOD);
CommonService obj = null;
try {
obj = CommonService.createServiceObjectByMethod(method);
} catch (InstantiationException e1) {
log
.severe("<handlRequest> but exception while create service object for method("
+ method + "), exception=" + e1.toString());
e1.printStackTrace();
} catch (IllegalAccessException e1) {
log
.severe("<handlRequest> but exception while create service object for method("
+ method + "), exception=" + e1.toString());
e1.printStackTrace();
}
try {
if (obj == null) {
sendResponseByErrorCode(response,
ErrorCode.ERROR_PARA_METHOD_NOT_FOUND);
return;
}
obj.setCassandraClient(cassandraClient);
obj.setRequest(request);
if (!obj.validateSecurity(request)) {
sendResponseByErrorCode(response,
ErrorCode.ERROR_INVALID_SECURITY);
return;
}
// parse request parameters
sendResponseByErrorCode(response, obj.resultCode);
if (!obj.setDataFromRequest(request)) {
return;
}
// print parameters
obj.printData();
// handle request
obj.handleData();
} catch (HectorException e) {
obj.resultCode = ErrorCode.ERROR_CASSANDRA;
log.severe("catch DB exception=" + e.toString());
e.printStackTrace();
} catch (JSONException e) {
obj.resultCode = ErrorCode.ERROR_JSON;
log.severe("catch JSON exception=" + e.toString());
e.printStackTrace();
} catch (Exception e) {
obj.resultCode = ErrorCode.ERROR_SYSTEM;
log.severe("catch general exception=" + e.toString());
e.printStackTrace();
} finally {
}
String responseData = obj.getResponseString();
// send back response
sendResponse(response, responseData);
}
| public void handlRequest(HttpServletRequest request,
HttpServletResponse response) {
printRequest(request);
String method = request.getParameter(ServiceConstant.METHOD);
CommonService obj = null;
try {
obj = CommonService.createServiceObjectByMethod(method);
} catch (InstantiationException e1) {
log
.severe("<handlRequest> but exception while create service object for method("
+ method + "), exception=" + e1.toString());
e1.printStackTrace();
} catch (IllegalAccessException e1) {
log
.severe("<handlRequest> but exception while create service object for method("
+ method + "), exception=" + e1.toString());
e1.printStackTrace();
}
try {
if (obj == null) {
sendResponseByErrorCode(response,
ErrorCode.ERROR_PARA_METHOD_NOT_FOUND);
return;
}
obj.setCassandraClient(cassandraClient);
obj.setRequest(request);
if (!obj.validateSecurity(request)) {
sendResponseByErrorCode(response,
ErrorCode.ERROR_INVALID_SECURITY);
return;
}
// parse request parameters
if (!obj.setDataFromRequest(request)) {
sendResponseByErrorCode(response, obj.resultCode);
return;
}
// print parameters
obj.printData();
// handle request
obj.handleData();
} catch (HectorException e) {
obj.resultCode = ErrorCode.ERROR_CASSANDRA;
log.severe("catch DB exception=" + e.toString());
e.printStackTrace();
} catch (JSONException e) {
obj.resultCode = ErrorCode.ERROR_JSON;
log.severe("catch JSON exception=" + e.toString());
e.printStackTrace();
} catch (Exception e) {
obj.resultCode = ErrorCode.ERROR_SYSTEM;
log.severe("catch general exception=" + e.toString());
e.printStackTrace();
} finally {
}
String responseData = obj.getResponseString();
// send back response
sendResponse(response, responseData);
}
|
diff --git a/pi/pipair.java b/pi/pipair.java
index 6b7555d..fb219f3 100644
--- a/pi/pipair.java
+++ b/pi/pipair.java
@@ -1,151 +1,151 @@
package fauna.testing;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Collections;
import java.io.IOException;
import java.util.Hashtable;
import java.util.HashSet;
import java.util.Set;
import java.util.Iterator;
import java.util.Map;
import java.io.InputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.text.NumberFormat;
import java.math.RoundingMode;
class Pipair {
int tSupport = 3;
float tConfidence = 0.65f;
NumberFormat numf = NumberFormat.getNumberInstance();
public static String getPairName(String a, String b) {
if (a.compareTo(b) > 0) {
String temp = a;
a = b;
b = temp;
}
return a + ":" + b;
}
class SupportGraph {
Hashtable<String,Integer> supports = new Hashtable<String,Integer>();
HashSet<String> allNames = new HashSet<String>();
private void parseFromCallGraph(Hashtable<String,ArrayList<String>> cg) {
Enumeration funcs = cg.elements();
while (funcs.hasMoreElements()) {
ArrayList<String> calls = (ArrayList<String>)funcs.nextElement();
calls = removeDuplicateCalls(calls);
for (int i = 0; i < calls.size(); i++) {
allNames.add(calls.get(i));
for (int j = i + 1; j < calls.size(); j++) {
String name = Pipair.getPairName(calls.get(i),
calls.get(j));
createOrIncrementSupport(name);
}
createOrIncrementSupport(calls.get(i));
}
}
}
private ArrayList<String> removeDuplicateCalls(ArrayList<String> calls) {
HashSet<String> callSet = new HashSet<String>(calls);
calls = new ArrayList<String>(callSet);
return calls;
}
private void createOrIncrementSupport(String name) {
Integer curSing = supports.get(name);
if (curSing == null) {
supports.put(name, 1);
} else {
supports.put(name, new Integer(curSing + 1));
}
}
}
public void findAndPrintViolations(Hashtable<String,ArrayList<String>> cg,
SupportGraph sg) {
Enumeration<String> cgKeySet = cg.keys();
while (cgKeySet.hasMoreElements()) {
String caller = (String)cgKeySet.nextElement();
ArrayList<String> callsL = (ArrayList<String>)cg.get(caller);
HashSet<String> calls = new HashSet<String>(callsL);
Iterator i = calls.iterator();
while (i.hasNext()) {
String f = (String)i.next();
printInvariantsForFunction(caller, f, sg, calls);
}
}
}
private void printInvariantsForFunction(String caller,
String f1,
SupportGraph sg,
HashSet<String> calls) {
Iterator<String> i = sg.allNames.iterator();
while (i.hasNext()) {
String f2 = i.next();
String key = Pipair.getPairName(f1, f2);
- if (!sg.supports.contains(key) ||
- !sg.supports.contains(f1)) {
+ if (!sg.supports.containsKey(key) ||
+ !sg.supports.containsKey(f1)) {
continue;
}
int pairSupport = sg.supports.get(key).intValue();
int singleSupport = sg.supports.get(f1).intValue();
float confidence = (float)pairSupport/singleSupport;
- if (confidence > tConfidence && pairSupport > tSupport) {
+ if (confidence >= tConfidence && pairSupport >= tSupport) {
if (!calls.contains(f2)) {
printViolation(caller, f1, f2, pairSupport,
confidence);
}
}
}
}
public void printViolation(String caller, String f1, String f2,
int support, float confidence) {
System.out.println("bug: " + f1 + " in " + caller + ", " +
"pair: (" +
f1 + " " + f2 + "), support: " +
support + ", confidence: " +
numf.format(confidence * 100.0) + "%");
}
public void run(String cgFile) {
numf.setMaximumFractionDigits(2);
numf.setMinimumFractionDigits(2);
numf.setRoundingMode(RoundingMode.HALF_EVEN);
Hashtable<String,ArrayList<String>> cg = Parser.parseFile(cgFile);
SupportGraph sg = new SupportGraph();
sg.parseFromCallGraph(cg);
findAndPrintViolations(cg, sg);
}
public static void main(String[] args) {
if (args.length < 1) {
System.out.println("Usage: ./pipair <bitcode file> <T SUPPORT> <T CONFIDENCE>,");
System.exit(0);
}
Pipair prog = new Pipair();
if (args.length >= 2) {
prog.tSupport = Integer.parseInt(args[1]);
}
if (args.length >= 3) {
prog.tConfidence = Float.parseFloat(args[2]);
}
if (args.length >= 4) {
Parser.levels = Integer.parseInt(args[3]);
}
prog.run(args[0]);
}
}
| false | true | private void printInvariantsForFunction(String caller,
String f1,
SupportGraph sg,
HashSet<String> calls) {
Iterator<String> i = sg.allNames.iterator();
while (i.hasNext()) {
String f2 = i.next();
String key = Pipair.getPairName(f1, f2);
if (!sg.supports.contains(key) ||
!sg.supports.contains(f1)) {
continue;
}
int pairSupport = sg.supports.get(key).intValue();
int singleSupport = sg.supports.get(f1).intValue();
float confidence = (float)pairSupport/singleSupport;
if (confidence > tConfidence && pairSupport > tSupport) {
if (!calls.contains(f2)) {
printViolation(caller, f1, f2, pairSupport,
confidence);
}
}
}
}
| private void printInvariantsForFunction(String caller,
String f1,
SupportGraph sg,
HashSet<String> calls) {
Iterator<String> i = sg.allNames.iterator();
while (i.hasNext()) {
String f2 = i.next();
String key = Pipair.getPairName(f1, f2);
if (!sg.supports.containsKey(key) ||
!sg.supports.containsKey(f1)) {
continue;
}
int pairSupport = sg.supports.get(key).intValue();
int singleSupport = sg.supports.get(f1).intValue();
float confidence = (float)pairSupport/singleSupport;
if (confidence >= tConfidence && pairSupport >= tSupport) {
if (!calls.contains(f2)) {
printViolation(caller, f1, f2, pairSupport,
confidence);
}
}
}
}
|
diff --git a/android/src/org/openqa/selenium/android/server/handler/GetCapabilities.java b/android/src/org/openqa/selenium/android/server/handler/GetCapabilities.java
index 0893c4599..6d35e547d 100644
--- a/android/src/org/openqa/selenium/android/server/handler/GetCapabilities.java
+++ b/android/src/org/openqa/selenium/android/server/handler/GetCapabilities.java
@@ -1,54 +1,55 @@
/*
Copyright 2010 WebDriver committers
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.openqa.selenium.android.server.handler;
import com.google.common.collect.Maps;
import android.os.Build;
import org.openqa.selenium.android.app.MainActivity;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.server.Session;
import org.openqa.selenium.remote.server.handler.GetSessionCapabilities;
import java.util.Collections;
import java.util.Map;
/**
* @author [email protected] (Dounia Berrada)
*/
public class GetCapabilities extends GetSessionCapabilities {
public GetCapabilities(Session session) {
super(session);
}
@Override
protected Map<String, Object> describeSession(Map<String, Object> capabilities) {
// Creating a new map because the map received is not modifiable.
Map<String, Object> caps = Maps.newHashMap();
caps.putAll(capabilities);
caps.put(CapabilityType.TAKES_SCREENSHOT, true);
caps.put(CapabilityType.BROWSER_NAME, "android");
caps.put(CapabilityType.ROTATABLE, true);
caps.put(CapabilityType.PLATFORM, "android");
caps.put(CapabilityType.SUPPORTS_ALERTS, true);
caps.put(CapabilityType.SUPPORTS_JAVASCRIPT, true);
caps.put(CapabilityType.VERSION, Build.VERSION.SDK);
+ caps.put(CapabilityType.ACCEPT_SSL_CERTS, true);
return caps;
}
}
| true | true | protected Map<String, Object> describeSession(Map<String, Object> capabilities) {
// Creating a new map because the map received is not modifiable.
Map<String, Object> caps = Maps.newHashMap();
caps.putAll(capabilities);
caps.put(CapabilityType.TAKES_SCREENSHOT, true);
caps.put(CapabilityType.BROWSER_NAME, "android");
caps.put(CapabilityType.ROTATABLE, true);
caps.put(CapabilityType.PLATFORM, "android");
caps.put(CapabilityType.SUPPORTS_ALERTS, true);
caps.put(CapabilityType.SUPPORTS_JAVASCRIPT, true);
caps.put(CapabilityType.VERSION, Build.VERSION.SDK);
return caps;
}
| protected Map<String, Object> describeSession(Map<String, Object> capabilities) {
// Creating a new map because the map received is not modifiable.
Map<String, Object> caps = Maps.newHashMap();
caps.putAll(capabilities);
caps.put(CapabilityType.TAKES_SCREENSHOT, true);
caps.put(CapabilityType.BROWSER_NAME, "android");
caps.put(CapabilityType.ROTATABLE, true);
caps.put(CapabilityType.PLATFORM, "android");
caps.put(CapabilityType.SUPPORTS_ALERTS, true);
caps.put(CapabilityType.SUPPORTS_JAVASCRIPT, true);
caps.put(CapabilityType.VERSION, Build.VERSION.SDK);
caps.put(CapabilityType.ACCEPT_SSL_CERTS, true);
return caps;
}
|
diff --git a/src/main/java/me/xhawk87/Coinage/commands/SpendCoinsCommand.java b/src/main/java/me/xhawk87/Coinage/commands/SpendCoinsCommand.java
index 2456f42..ed06d62 100644
--- a/src/main/java/me/xhawk87/Coinage/commands/SpendCoinsCommand.java
+++ b/src/main/java/me/xhawk87/Coinage/commands/SpendCoinsCommand.java
@@ -1,85 +1,85 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package me.xhawk87.Coinage.commands;
import me.xhawk87.Coinage.Coinage;
import me.xhawk87.Coinage.Currency;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
/**
*
* @author XHawk87
*/
public class SpendCoinsCommand extends CoinCommand {
private Coinage plugin;
public SpendCoinsCommand(Coinage plugin) {
this.plugin = plugin;
}
@Override
public String getHelpMessage(CommandSender sender) {
return "/SpendCoins [player] ([currency]) [value]. Remove the given value of coins from the specified player and give change where needed";
}
@Override
public String getPermission() {
return "coinage.commands.spendcoins";
}
@Override
public boolean execute(CommandSender sender, String[] args) {
if (args.length < 2 || args.length > 3) {
return false;
}
int index = 0;
String playerName = args[index++];
Player player = plugin.getServer().getPlayer(playerName);
if (player == null) {
sender.sendMessage("There is no player matching " + playerName);
return true;
}
Currency currency;
if (args.length == 3) {
String currencyName = args[index++];
- currency = plugin.getCurrency(playerName);
+ currency = plugin.getCurrency(currencyName);
if (currency == null) {
sender.sendMessage("There is no currency with id " + currencyName);
return true;
}
} else {
currency = plugin.getDefaultCurrency();
}
int value;
String valueString = args[index++];
try {
value = Integer.parseInt(valueString);
if (value < 1) {
sender.sendMessage("The value must be at least 1 " + currency.toString() + ": " + valueString);
return true;
}
} catch (NumberFormatException ex) {
sender.sendMessage("The value was not a valid number: " + valueString);
return true;
}
if (currency.spend(player, value)) {
if (sender != player) {
sender.sendMessage(value + " in " + currency.toString() + " was deducted from " + player.getDisplayName());
}
} else {
if (sender != player) {
sender.sendMessage(player.getDisplayName() + " does not have " + value + " in " + currency.toString() + " to spend");
}
}
return true;
}
}
| true | true | public boolean execute(CommandSender sender, String[] args) {
if (args.length < 2 || args.length > 3) {
return false;
}
int index = 0;
String playerName = args[index++];
Player player = plugin.getServer().getPlayer(playerName);
if (player == null) {
sender.sendMessage("There is no player matching " + playerName);
return true;
}
Currency currency;
if (args.length == 3) {
String currencyName = args[index++];
currency = plugin.getCurrency(playerName);
if (currency == null) {
sender.sendMessage("There is no currency with id " + currencyName);
return true;
}
} else {
currency = plugin.getDefaultCurrency();
}
int value;
String valueString = args[index++];
try {
value = Integer.parseInt(valueString);
if (value < 1) {
sender.sendMessage("The value must be at least 1 " + currency.toString() + ": " + valueString);
return true;
}
} catch (NumberFormatException ex) {
sender.sendMessage("The value was not a valid number: " + valueString);
return true;
}
if (currency.spend(player, value)) {
if (sender != player) {
sender.sendMessage(value + " in " + currency.toString() + " was deducted from " + player.getDisplayName());
}
} else {
if (sender != player) {
sender.sendMessage(player.getDisplayName() + " does not have " + value + " in " + currency.toString() + " to spend");
}
}
return true;
}
| public boolean execute(CommandSender sender, String[] args) {
if (args.length < 2 || args.length > 3) {
return false;
}
int index = 0;
String playerName = args[index++];
Player player = plugin.getServer().getPlayer(playerName);
if (player == null) {
sender.sendMessage("There is no player matching " + playerName);
return true;
}
Currency currency;
if (args.length == 3) {
String currencyName = args[index++];
currency = plugin.getCurrency(currencyName);
if (currency == null) {
sender.sendMessage("There is no currency with id " + currencyName);
return true;
}
} else {
currency = plugin.getDefaultCurrency();
}
int value;
String valueString = args[index++];
try {
value = Integer.parseInt(valueString);
if (value < 1) {
sender.sendMessage("The value must be at least 1 " + currency.toString() + ": " + valueString);
return true;
}
} catch (NumberFormatException ex) {
sender.sendMessage("The value was not a valid number: " + valueString);
return true;
}
if (currency.spend(player, value)) {
if (sender != player) {
sender.sendMessage(value + " in " + currency.toString() + " was deducted from " + player.getDisplayName());
}
} else {
if (sender != player) {
sender.sendMessage(player.getDisplayName() + " does not have " + value + " in " + currency.toString() + " to spend");
}
}
return true;
}
|
diff --git a/jsf-ri/src/com/sun/faces/renderkit/html_basic/RadioRenderer.java b/jsf-ri/src/com/sun/faces/renderkit/html_basic/RadioRenderer.java
index feb37a258..1e749862e 100644
--- a/jsf-ri/src/com/sun/faces/renderkit/html_basic/RadioRenderer.java
+++ b/jsf-ri/src/com/sun/faces/renderkit/html_basic/RadioRenderer.java
@@ -1,228 +1,228 @@
/*
* $Id: RadioRenderer.java,v 1.90 2008/01/15 20:34:50 rlubke Exp $
*/
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can obtain
* a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html
* or glassfish/bootstrap/legal/LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at glassfish/bootstrap/legal/LICENSE.txt.
* Sun designates this particular file as subject to the "Classpath" exception
* as provided by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the License
* Header, with the fields enclosed by brackets [] replaced by your own
* identifying information: "Portions Copyrighted [year]
* [name of copyright owner]"
*
* Contributor(s):
*
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
// RadioRenderer.java
package com.sun.faces.renderkit.html_basic;
import com.sun.faces.renderkit.Attribute;
import com.sun.faces.renderkit.AttributeManager;
import com.sun.faces.renderkit.RenderKitUtils;
import com.sun.faces.util.RequestStateManager;
import javax.el.ELException;
import javax.faces.component.UIComponent;
import javax.faces.component.UINamingContainer;
import javax.faces.component.UISelectOne;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import javax.faces.convert.Converter;
import javax.faces.model.SelectItem;
import java.util.Collection;
import java.util.Iterator;
import java.io.IOException;
/**
* <B>ReadoRenderer</B> is a class that renders the current value of
* <code>UISelectOne<code> or <code>UISelectMany<code> component as a list of
* radio buttons
*/
public class RadioRenderer extends SelectManyCheckboxListRenderer {
private static final Attribute[] ATTRIBUTES =
AttributeManager.getAttributes(AttributeManager.Key.SELECTONERADIO);
// ------------------------------------------------------- Protected Methods
@Override
protected void renderOption(FacesContext context,
UIComponent component,
Converter converter,
SelectItem curItem,
Object currentSelections,
Object[] submittedValues,
boolean alignVertical,
int itemNumber,
OptionComponentInfo optionInfo) throws IOException {
ResponseWriter writer = context.getResponseWriter();
assert (writer != null);
UISelectOne selectOne = (UISelectOne) component;
Object curValue = selectOne.getSubmittedValue();
if (curValue == null) {
curValue = selectOne.getValue();
}
Class type = String.class;
if (curValue != null) {
type = curValue.getClass();
if (type.isArray()) {
curValue = ((Object[]) curValue)[0];
if (null != curValue) {
type = curValue.getClass();
}
} else if (Collection.class.isAssignableFrom(type)) {
Iterator valueIter = ((Collection) curValue).iterator();
if (null != valueIter && valueIter.hasNext()) {
curValue = valueIter.next();
if (null != curValue) {
type = curValue.getClass();
}
}
}
}
Object itemValue = curItem.getValue();
RequestStateManager.set(context,
RequestStateManager.TARGET_COMPONENT_ATTRIBUTE_NAME,
component);
Object newValue;
try {
newValue = context.getApplication().getExpressionFactory().
coerceToType(itemValue, type);
} catch (ELException ele) {
newValue = itemValue;
} catch (IllegalArgumentException iae) {
// If coerceToType fails, per the docs it should throw
// an ELException, however, GF 9.0 and 9.0u1 will throw
// an IllegalArgumentException instead (see GF issue 1527).
newValue = itemValue;
}
- boolean checked = newValue.equals(curValue);
+ boolean checked = null != newValue && newValue.equals(curValue);
if (optionInfo.isHideNoSelection()
&& curItem.isNoSelectionOption()
&& curValue != null
&& !checked) {
return;
}
if (alignVertical) {
writer.writeText("\t", component, null);
writer.startElement("tr", component);
writer.writeText("\n", component, null);
}
String labelClass;
if (optionInfo.isDisabled() || curItem.isDisabled()) {
labelClass = optionInfo.getDisabledClass();
} else {
labelClass = optionInfo.getEnabledClass();
}
writer.startElement("td", component);
writer.writeText("\n", component, null);
writer.startElement("input", component);
writer.writeAttribute("type", "radio", "type");
if (checked) {
writer.writeAttribute("checked", Boolean.TRUE, null);
}
writer.writeAttribute("name", component.getClientId(context),
"clientId");
String idString = component.getClientId(context)
+ UINamingContainer.getSeparatorChar(context)
+ Integer.toString(itemNumber);
writer.writeAttribute("id", idString, "id");
writer.writeAttribute("value",
(getFormattedValue(context, component,
curItem.getValue(), converter)),
"value");
// Don't render the disabled attribute twice if the 'parent'
// component is already marked disabled.
if (!optionInfo.isDisabled()) {
if (curItem.isDisabled()) {
writer.writeAttribute("disabled", true, "disabled");
}
}
// Apply HTML 4.x attributes specified on UISelectMany component to all
// items in the list except styleClass and style which are rendered as
// attributes of outer most table.
RenderKitUtils.renderPassThruAttributes(context,
writer,
component,
ATTRIBUTES,
getNonOnChangeBehaviors(component));
RenderKitUtils.renderXHTMLStyleBooleanAttributes(writer,
component);
RenderKitUtils.renderOnchange(context, component, false);
writer.endElement("input");
writer.startElement("label", component);
writer.writeAttribute("for", idString, "for");
// if enabledClass or disabledClass attributes are specified, apply
// it on the label.
if (labelClass != null) {
writer.writeAttribute("class", labelClass, "labelClass");
}
String itemLabel = curItem.getLabel();
if (itemLabel != null) {
writer.writeText(" ", component, null);
if (!curItem.isEscape()) {
// It seems the ResponseWriter API should
// have a writeText() with a boolean property
// to determine if it content written should
// be escaped or not.
writer.write(itemLabel);
} else {
writer.writeText(itemLabel, component, "label");
}
}
writer.endElement("label");
writer.endElement("td");
writer.writeText("\n", component, null);
if (alignVertical) {
writer.writeText("\t", component, null);
writer.endElement("tr");
writer.writeText("\n", component, null);
}
}
} // end of class RadioRenderer
| true | true | protected void renderOption(FacesContext context,
UIComponent component,
Converter converter,
SelectItem curItem,
Object currentSelections,
Object[] submittedValues,
boolean alignVertical,
int itemNumber,
OptionComponentInfo optionInfo) throws IOException {
ResponseWriter writer = context.getResponseWriter();
assert (writer != null);
UISelectOne selectOne = (UISelectOne) component;
Object curValue = selectOne.getSubmittedValue();
if (curValue == null) {
curValue = selectOne.getValue();
}
Class type = String.class;
if (curValue != null) {
type = curValue.getClass();
if (type.isArray()) {
curValue = ((Object[]) curValue)[0];
if (null != curValue) {
type = curValue.getClass();
}
} else if (Collection.class.isAssignableFrom(type)) {
Iterator valueIter = ((Collection) curValue).iterator();
if (null != valueIter && valueIter.hasNext()) {
curValue = valueIter.next();
if (null != curValue) {
type = curValue.getClass();
}
}
}
}
Object itemValue = curItem.getValue();
RequestStateManager.set(context,
RequestStateManager.TARGET_COMPONENT_ATTRIBUTE_NAME,
component);
Object newValue;
try {
newValue = context.getApplication().getExpressionFactory().
coerceToType(itemValue, type);
} catch (ELException ele) {
newValue = itemValue;
} catch (IllegalArgumentException iae) {
// If coerceToType fails, per the docs it should throw
// an ELException, however, GF 9.0 and 9.0u1 will throw
// an IllegalArgumentException instead (see GF issue 1527).
newValue = itemValue;
}
boolean checked = newValue.equals(curValue);
if (optionInfo.isHideNoSelection()
&& curItem.isNoSelectionOption()
&& curValue != null
&& !checked) {
return;
}
if (alignVertical) {
writer.writeText("\t", component, null);
writer.startElement("tr", component);
writer.writeText("\n", component, null);
}
String labelClass;
if (optionInfo.isDisabled() || curItem.isDisabled()) {
labelClass = optionInfo.getDisabledClass();
} else {
labelClass = optionInfo.getEnabledClass();
}
writer.startElement("td", component);
writer.writeText("\n", component, null);
writer.startElement("input", component);
writer.writeAttribute("type", "radio", "type");
if (checked) {
writer.writeAttribute("checked", Boolean.TRUE, null);
}
writer.writeAttribute("name", component.getClientId(context),
"clientId");
String idString = component.getClientId(context)
+ UINamingContainer.getSeparatorChar(context)
+ Integer.toString(itemNumber);
writer.writeAttribute("id", idString, "id");
writer.writeAttribute("value",
(getFormattedValue(context, component,
curItem.getValue(), converter)),
"value");
// Don't render the disabled attribute twice if the 'parent'
// component is already marked disabled.
if (!optionInfo.isDisabled()) {
if (curItem.isDisabled()) {
writer.writeAttribute("disabled", true, "disabled");
}
}
// Apply HTML 4.x attributes specified on UISelectMany component to all
// items in the list except styleClass and style which are rendered as
// attributes of outer most table.
RenderKitUtils.renderPassThruAttributes(context,
writer,
component,
ATTRIBUTES,
getNonOnChangeBehaviors(component));
RenderKitUtils.renderXHTMLStyleBooleanAttributes(writer,
component);
RenderKitUtils.renderOnchange(context, component, false);
writer.endElement("input");
writer.startElement("label", component);
writer.writeAttribute("for", idString, "for");
// if enabledClass or disabledClass attributes are specified, apply
// it on the label.
if (labelClass != null) {
writer.writeAttribute("class", labelClass, "labelClass");
}
String itemLabel = curItem.getLabel();
if (itemLabel != null) {
writer.writeText(" ", component, null);
if (!curItem.isEscape()) {
// It seems the ResponseWriter API should
// have a writeText() with a boolean property
// to determine if it content written should
// be escaped or not.
writer.write(itemLabel);
} else {
writer.writeText(itemLabel, component, "label");
}
}
writer.endElement("label");
writer.endElement("td");
writer.writeText("\n", component, null);
if (alignVertical) {
writer.writeText("\t", component, null);
writer.endElement("tr");
writer.writeText("\n", component, null);
}
}
| protected void renderOption(FacesContext context,
UIComponent component,
Converter converter,
SelectItem curItem,
Object currentSelections,
Object[] submittedValues,
boolean alignVertical,
int itemNumber,
OptionComponentInfo optionInfo) throws IOException {
ResponseWriter writer = context.getResponseWriter();
assert (writer != null);
UISelectOne selectOne = (UISelectOne) component;
Object curValue = selectOne.getSubmittedValue();
if (curValue == null) {
curValue = selectOne.getValue();
}
Class type = String.class;
if (curValue != null) {
type = curValue.getClass();
if (type.isArray()) {
curValue = ((Object[]) curValue)[0];
if (null != curValue) {
type = curValue.getClass();
}
} else if (Collection.class.isAssignableFrom(type)) {
Iterator valueIter = ((Collection) curValue).iterator();
if (null != valueIter && valueIter.hasNext()) {
curValue = valueIter.next();
if (null != curValue) {
type = curValue.getClass();
}
}
}
}
Object itemValue = curItem.getValue();
RequestStateManager.set(context,
RequestStateManager.TARGET_COMPONENT_ATTRIBUTE_NAME,
component);
Object newValue;
try {
newValue = context.getApplication().getExpressionFactory().
coerceToType(itemValue, type);
} catch (ELException ele) {
newValue = itemValue;
} catch (IllegalArgumentException iae) {
// If coerceToType fails, per the docs it should throw
// an ELException, however, GF 9.0 and 9.0u1 will throw
// an IllegalArgumentException instead (see GF issue 1527).
newValue = itemValue;
}
boolean checked = null != newValue && newValue.equals(curValue);
if (optionInfo.isHideNoSelection()
&& curItem.isNoSelectionOption()
&& curValue != null
&& !checked) {
return;
}
if (alignVertical) {
writer.writeText("\t", component, null);
writer.startElement("tr", component);
writer.writeText("\n", component, null);
}
String labelClass;
if (optionInfo.isDisabled() || curItem.isDisabled()) {
labelClass = optionInfo.getDisabledClass();
} else {
labelClass = optionInfo.getEnabledClass();
}
writer.startElement("td", component);
writer.writeText("\n", component, null);
writer.startElement("input", component);
writer.writeAttribute("type", "radio", "type");
if (checked) {
writer.writeAttribute("checked", Boolean.TRUE, null);
}
writer.writeAttribute("name", component.getClientId(context),
"clientId");
String idString = component.getClientId(context)
+ UINamingContainer.getSeparatorChar(context)
+ Integer.toString(itemNumber);
writer.writeAttribute("id", idString, "id");
writer.writeAttribute("value",
(getFormattedValue(context, component,
curItem.getValue(), converter)),
"value");
// Don't render the disabled attribute twice if the 'parent'
// component is already marked disabled.
if (!optionInfo.isDisabled()) {
if (curItem.isDisabled()) {
writer.writeAttribute("disabled", true, "disabled");
}
}
// Apply HTML 4.x attributes specified on UISelectMany component to all
// items in the list except styleClass and style which are rendered as
// attributes of outer most table.
RenderKitUtils.renderPassThruAttributes(context,
writer,
component,
ATTRIBUTES,
getNonOnChangeBehaviors(component));
RenderKitUtils.renderXHTMLStyleBooleanAttributes(writer,
component);
RenderKitUtils.renderOnchange(context, component, false);
writer.endElement("input");
writer.startElement("label", component);
writer.writeAttribute("for", idString, "for");
// if enabledClass or disabledClass attributes are specified, apply
// it on the label.
if (labelClass != null) {
writer.writeAttribute("class", labelClass, "labelClass");
}
String itemLabel = curItem.getLabel();
if (itemLabel != null) {
writer.writeText(" ", component, null);
if (!curItem.isEscape()) {
// It seems the ResponseWriter API should
// have a writeText() with a boolean property
// to determine if it content written should
// be escaped or not.
writer.write(itemLabel);
} else {
writer.writeText(itemLabel, component, "label");
}
}
writer.endElement("label");
writer.endElement("td");
writer.writeText("\n", component, null);
if (alignVertical) {
writer.writeText("\t", component, null);
writer.endElement("tr");
writer.writeText("\n", component, null);
}
}
|
diff --git a/core/org.eclipse.ptp.remote.rse.core/miners/org/eclipse/ptp/internal/remote/rse/core/miners/SpawnerMiner.java b/core/org.eclipse.ptp.remote.rse.core/miners/org/eclipse/ptp/internal/remote/rse/core/miners/SpawnerMiner.java
index be627e0a7..c0f007602 100644
--- a/core/org.eclipse.ptp.remote.rse.core/miners/org/eclipse/ptp/internal/remote/rse/core/miners/SpawnerMiner.java
+++ b/core/org.eclipse.ptp.remote.rse.core/miners/org/eclipse/ptp/internal/remote/rse/core/miners/SpawnerMiner.java
@@ -1,304 +1,304 @@
/*******************************************************************************
* Copyright (c) 2010, 2013 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM - Initial API and implementation
*******************************************************************************/
package org.eclipse.ptp.internal.remote.rse.core.miners;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.cdt.utils.pty.PTY;
import org.eclipse.cdt.utils.spawner.ProcessFactory;
import org.eclipse.dstore.core.miners.Miner;
import org.eclipse.dstore.core.model.DE;
import org.eclipse.dstore.core.model.DataElement;
import org.eclipse.dstore.core.model.DataStoreResources;
import org.eclipse.dstore.core.model.DataStoreSchema;
import org.eclipse.rse.dstore.universal.miners.UniversalServerUtilities;
import org.eclipse.rse.internal.dstore.universal.miners.command.patterns.Patterns;
/**
* @author crecoskie
*
*/
@SuppressWarnings("restriction")
public class SpawnerMiner extends Miner {
public static final String SPAWN_ERROR = "spawnError"; //$NON-NLS-1$
public class CommandMinerDescriptors
{
public DataElement _stdout;
public DataElement _stderr;
public DataElement _prompt;
public DataElement _grep;
public DataElement _pathenvvar;
public DataElement _envvar;
public DataElement _libenvvar;
public DataElement _error;
public DataElement _warning;
public DataElement _informational;
public DataElement _process;
public DataElement getDescriptorFor(String type)
{
DataElement descriptor = null;
if (type.equals("stdout")) //$NON-NLS-1$
{
descriptor = _stdout;
}
else if (type.equals("pathenvvar")) //$NON-NLS-1$
{
descriptor = _pathenvvar;
}
else if (type.equals("envvar")) //$NON-NLS-1$
{
descriptor = _envvar;
}
else if (type.equals("libenvvar")) //$NON-NLS-1$
{
descriptor = _libenvvar;
}
else if (type.equals("error")) //$NON-NLS-1$
{
descriptor = _error;
}
else if (type.equals("warning")) //$NON-NLS-1$
{
descriptor = _warning;
}
else if (type.equals("informational")) //$NON-NLS-1$
{
descriptor = _informational;
}
else if (type.equals("process")) //$NON-NLS-1$
{
descriptor = _process;
}
else if (type.equals("grep")) //$NON-NLS-1$
{
descriptor = _grep;
}
else if (type.equals("stderr")) //$NON-NLS-1$
{
descriptor = _stderr;
}
return descriptor;
}
}
public static final String C_SPAWN_REDIRECTED = "C_SPAWN_REDIRECTED"; //$NON-NLS-1$
public static final String C_SPAWN_NOT_REDIRECTED = "C_SPAWN_NOT_REDIRECTED"; //$NON-NLS-1$
public static final String C_SPAWN_TTY = "C_SPAWN_TTY"; //$NON-NLS-1$
public static final String T_SPAWNER_STRING_DESCRIPTOR = "Type.Spawner.String"; //$NON-NLS-1$
public static final String LOG_TAG = "SpawnerMiner"; //$NON-NLS-1$
private CommandMinerDescriptors fDescriptors = new CommandMinerDescriptors();
boolean fSupportsCharConversion;
private DataElement _status;
private Map<DataElement, Process> fProcessMap = new HashMap<DataElement, Process>();
public boolean _supportsCharConversion = true;
private Patterns _patterns;
/* (non-Javadoc)
* @see org.eclipse.dstore.core.miners.Miner#getVersion()
*/
@Override
public String getVersion() {
return "0.0.2"; //$NON-NLS-1$
}
/* (non-Javadoc)
* @see org.eclipse.dstore.core.miners.Miner#handleCommand(org.eclipse.dstore.core.model.DataElement)
*/
@Override
public DataElement handleCommand(DataElement theCommand) throws Exception {
try {
return doHandleCommand(theCommand);
}
catch(RuntimeException e) {
UniversalServerUtilities.logError(LOG_TAG, e.toString(), e, _dataStore);
_dataStore.refresh(theCommand);
_dataStore.disconnectObject(theCommand);
throw e;
}
}
private DataElement doHandleCommand(DataElement theCommand) {
String name = getCommandName(theCommand);
DataElement status = getCommandStatus(theCommand);
_status = status;
DataElement subject = getCommandArgument(theCommand, 0);
if (name.equals(C_SPAWN_REDIRECTED)) {
String cmd = getString(theCommand, 1);
String directory = getString(theCommand, 2);
File dir = new File(directory);
int envSize = getInt(theCommand, 3);
String[] envp = new String[envSize];
for (int i = 0; i < envSize; i++) {
envp[i] = getString(theCommand, i+4);
}
handleSpawnRedirected(subject, cmd, dir, envp, status);
- return statusDone(status);
+ return status;
}
else if(name.equals(DataStoreSchema.C_CANCEL)) {
DataElement cancelStatus = getCommandStatus(subject);
// get the name of the command that is to be canceled
String commandName = subject.getName().trim();
if(commandName.equals(C_SPAWN_REDIRECTED) || commandName.equals(C_SPAWN_NOT_REDIRECTED) || commandName.equals(C_SPAWN_TTY)) {
handleSpawnCancel(cancelStatus);
}
// add more cancelable commands here
}
else if (name.equals("C_CHAR_CONVERSION")) //$NON-NLS-1$
{
fSupportsCharConversion = true;
return statusDone(status);
}
return null;
}
private void handleSpawnCancel(DataElement cancelStatus) {
Process processToCancel = fProcessMap.get(cancelStatus);
if(processToCancel != null) {
processToCancel.destroy();
synchronized(fProcessMap) {
fProcessMap.put(cancelStatus, null);
}
}
statusDone(cancelStatus);
}
/**
* @param subject
* @param cmd
* @param dir
* @param envp
* @throws IOException
*/
private void handleSpawnRedirected(DataElement subject, String cmd, File dir, String[] envp, DataElement status) {
try {
final Process process = ProcessFactory.getFactory().exec(cmd.split(" "), envp, dir, new PTY()); //$NON-NLS-1$
synchronized(this) {
fProcessMap.put(status, process);
}
CommandMinerThread newCommand = new CommandMinerThread(subject, process, cmd, dir.getAbsolutePath(), status, getPatterns(), fDescriptors);
newCommand.start();
} catch (IOException e) {
// report the error to the client so that it should show up in their console
_dataStore.createObject(status, SPAWN_ERROR, cmd, ""); //$NON-NLS-1$
refreshStatus();
// tell the client that the operation is done (even though unsuccessful)
statusDone(status);
// log to the server log
UniversalServerUtilities.logError(LOG_TAG, e.toString(), e, _dataStore);
}
// statusDone(status);
}
/**
* Complete status.
*/
public static DataElement statusDone(DataElement status) {
status.setAttribute(DE.A_NAME, DataStoreResources.model_done);
status.getDataStore().refresh(status);
status.getDataStore().disconnectObject(status.getParent());
return status;
}
private String getString(DataElement command, int index) {
DataElement element = getCommandArgument(command, index);
return element.getName();
}
private int getInt(DataElement command, int index) {
DataElement element = getCommandArgument(command, index);
Integer i = new Integer(element.getName());
return i.intValue();
}
/* (non-Javadoc)
* @see org.eclipse.dstore.core.model.ISchemaExtender#extendSchema(org.eclipse.dstore.core.model.DataElement)
*/
public void extendSchema(DataElement schemaRoot) {
// make sure we can load the spawner... if we can't, then bail out
try {
System.loadLibrary("spawner"); //$NON-NLS-1$
}
catch(UnsatisfiedLinkError e) {
// don't log this error, as it may just be that we are running a
// generic server that doesn't have a spawner library
return;
}
DataElement cancellable = _dataStore.findObjectDescriptor(DataStoreResources.model_Cancellable);
DataElement e0_cmd = createCommandDescriptor(schemaRoot, "Spawn process without redirection", C_SPAWN_REDIRECTED, false); //$NON-NLS-1$
_dataStore.createReference(cancellable, e0_cmd, DataStoreResources.model_abstracts, DataStoreResources.model_abstracted_by);
fDescriptors = new CommandMinerDescriptors();
fDescriptors._stdout = _dataStore.createObjectDescriptor(schemaRoot, "stdout"); //$NON-NLS-1$
fDescriptors._stderr = _dataStore.createObjectDescriptor(schemaRoot, "stderr"); //$NON-NLS-1$
fDescriptors._prompt = _dataStore.createObjectDescriptor(schemaRoot, "prompt"); //$NON-NLS-1$
fDescriptors._grep = _dataStore.createObjectDescriptor(schemaRoot, "grep"); //$NON-NLS-1$
fDescriptors._pathenvvar = _dataStore.createObjectDescriptor(schemaRoot, "pathenvvar"); //$NON-NLS-1$
fDescriptors._envvar = _dataStore.createObjectDescriptor(schemaRoot, "envvar"); //$NON-NLS-1$
fDescriptors._libenvvar = _dataStore.createObjectDescriptor(schemaRoot, "libenvvar"); //$NON-NLS-1$
fDescriptors._error = _dataStore.createObjectDescriptor(schemaRoot, "error"); //$NON-NLS-1$
fDescriptors._warning = _dataStore.createObjectDescriptor(schemaRoot, "warning"); //$NON-NLS-1$
fDescriptors._informational = _dataStore.createObjectDescriptor(schemaRoot, "informational"); //$NON-NLS-1$
fDescriptors._process =_dataStore.createObjectDescriptor(schemaRoot, "process"); //$NON-NLS-1$
_dataStore.refresh(schemaRoot);
}
public void refreshStatus()
{
_dataStore.refresh(_status);
}
private Patterns getPatterns()
{
if (_patterns == null)
{
_patterns = new Patterns(_dataStore);
}
return _patterns;
}
}
| true | true | private DataElement doHandleCommand(DataElement theCommand) {
String name = getCommandName(theCommand);
DataElement status = getCommandStatus(theCommand);
_status = status;
DataElement subject = getCommandArgument(theCommand, 0);
if (name.equals(C_SPAWN_REDIRECTED)) {
String cmd = getString(theCommand, 1);
String directory = getString(theCommand, 2);
File dir = new File(directory);
int envSize = getInt(theCommand, 3);
String[] envp = new String[envSize];
for (int i = 0; i < envSize; i++) {
envp[i] = getString(theCommand, i+4);
}
handleSpawnRedirected(subject, cmd, dir, envp, status);
return statusDone(status);
}
else if(name.equals(DataStoreSchema.C_CANCEL)) {
DataElement cancelStatus = getCommandStatus(subject);
// get the name of the command that is to be canceled
String commandName = subject.getName().trim();
if(commandName.equals(C_SPAWN_REDIRECTED) || commandName.equals(C_SPAWN_NOT_REDIRECTED) || commandName.equals(C_SPAWN_TTY)) {
handleSpawnCancel(cancelStatus);
}
// add more cancelable commands here
}
else if (name.equals("C_CHAR_CONVERSION")) //$NON-NLS-1$
{
fSupportsCharConversion = true;
return statusDone(status);
}
return null;
}
| private DataElement doHandleCommand(DataElement theCommand) {
String name = getCommandName(theCommand);
DataElement status = getCommandStatus(theCommand);
_status = status;
DataElement subject = getCommandArgument(theCommand, 0);
if (name.equals(C_SPAWN_REDIRECTED)) {
String cmd = getString(theCommand, 1);
String directory = getString(theCommand, 2);
File dir = new File(directory);
int envSize = getInt(theCommand, 3);
String[] envp = new String[envSize];
for (int i = 0; i < envSize; i++) {
envp[i] = getString(theCommand, i+4);
}
handleSpawnRedirected(subject, cmd, dir, envp, status);
return status;
}
else if(name.equals(DataStoreSchema.C_CANCEL)) {
DataElement cancelStatus = getCommandStatus(subject);
// get the name of the command that is to be canceled
String commandName = subject.getName().trim();
if(commandName.equals(C_SPAWN_REDIRECTED) || commandName.equals(C_SPAWN_NOT_REDIRECTED) || commandName.equals(C_SPAWN_TTY)) {
handleSpawnCancel(cancelStatus);
}
// add more cancelable commands here
}
else if (name.equals("C_CHAR_CONVERSION")) //$NON-NLS-1$
{
fSupportsCharConversion = true;
return statusDone(status);
}
return null;
}
|
diff --git a/source/base/file/File.java b/source/base/file/File.java
index 4b83931..0c6e0b2 100755
--- a/source/base/file/File.java
+++ b/source/base/file/File.java
@@ -1,135 +1,141 @@
package base.file;
import java.io.IOException;
import java.io.RandomAccessFile;
import base.data.Bay;
import base.data.Data;
import base.exception.DiskException;
import base.process.Mistake;
import base.size.Stripe;
import base.size.StripePattern;
import base.state.Close;
/** An open file on the disk with access to its data. */
public class File extends Close {
// Make
/** Make and open the file at the given path. */
public File(Open open) {
try {
// Get and save the path
path = open.path;
// Enforce and check how we are told to open the file
if (open.how == Open.overwrite) path.delete(); // Delete a file or empty folder at path, or throw a DiskException
if ((open.how == Open.overwrite || open.how == Open.make) && path.exists()) throw new DiskException("exists"); // Make requires available path
if ((open.how == Open.read || open.how == Open.write) && !path.existsFile()) throw new DiskException("not found"); // Open requires file at path
// Make or open the file
String access = "rw"; // For the make, overwrite, and write commands, get read and write access
if (open.how == Open.read) access = "r"; // For the read command, get read access
file = new RandomAccessFile(path.file, access);
// Get or create and save the pattern
StripePattern pattern = open.pattern;
if (pattern == null) { // If no pattern given in path, make one
pattern = new StripePattern(); // If file is empty, pattern is ready
long size = file.getChannel().size(); // If the file has gaps, size will be as if they are full
if (size > 0) pattern = pattern.add(new Stripe(0, size)); // Mark the whole file as full
}
this.pattern = pattern;
- } catch (IOException e) { throw new DiskException(e); }
+ } catch (IOException e) {
+ close(this);
+ throw new DiskException(e);
+ } catch (RuntimeException e) {
+ close(this);
+ throw e;
+ }
}
// Look
/** The Path to our open file on the disk. */
public final Path path;
/** The Java RandomAccessFile object that gives us access to the data in our file. */
public final RandomAccessFile file;
// Close
/** Close our open connection to this file on the disk. */
public void close() {
if (already()) return;
try { file.close(); } catch (IOException e) { Mistake.log(e); } // Also closes file's FileChannel
}
/** Close and delete this file on the disk. */
public void delete() {
close(this);
path.delete(); // Delete it at its Path
}
// Size
/** The size of this file, as though any gaps in it are full. */
public long size() { return pattern.size(); } // Ask our StripePattern
/** True if this File has a size of 0 bytes. */
public boolean isEmpty() { return size() == 0; }
/** True if this File has 1 or more bytes of data inside. */
public boolean hasData() { return size() > 0; }
/** A StripePattern that shows what parts of this File have data, and which parts are gaps. */
public StripePattern pattern() { return pattern; }
private StripePattern pattern;
/** Tell this File that you wrote stripe of data to it. */
public void add(Stripe stripe) {
pattern = pattern.add(stripe);
}
// Transfer
/** Read the contents of this File into memory. */
public Data read() { Bay bay = new Bay(); read(bay); return bay.data(); }
/** Read the part of the File stripe identifies into memory. */
public Data read(Stripe stripe) { Bay bay = new Bay(); read(bay, stripe); return bay.data(); }
/** Read the contents of this File into bay. */
public void read(Bay bay) {
if (size() == 0) return; // This File is empty
read(bay, new Stripe(0, size())); // Call the next method with a Stripe that clips out this whole file
}
/** Read the part of this File stripe identifies into bay. */
public void read(Bay bay, Stripe stripe) {
if (!pattern.is(true, stripe)) throw new DiskException("hole"); // Make sure we have data where stripe is
bay.read(this, stripe); // Add stripe.size bytes from stripe.i in our file to bay
}
/** Write d a distance i bytes into this File. */
public void write(long i, Data data) {
try {
if (data.isEmpty()) return; // Nothing to write
int did = file.getChannel().write(data.toByteBuffer(), i);
if (did != data.size()) throw new DiskException("did " + did); // Make sure write() wrote everything
add(new Stripe(i, data.size())); // Update pattern
} catch (IOException e) { throw new DiskException(e); }
}
// Small
/** Open the file at path, copy its contents into memory, and close it. */
public static Data data(Path path) {
File f = new File(new Open(path, null, Open.read));
Data d = f.read(); // Copy the file's contents into memory
close(f);
return d;
}
/** Save d to a file at path, overwriting one already there. */
public static void save(Path path, Data d) {
try {
File f = new File(new Open(path, null, Open.overwrite));
f.write(0, d);
f.file.getChannel().truncate(d.size()); // Chop the file off after that
close(f);
} catch (IOException e) { throw new DiskException(e); }
}
}
| true | true | public File(Open open) {
try {
// Get and save the path
path = open.path;
// Enforce and check how we are told to open the file
if (open.how == Open.overwrite) path.delete(); // Delete a file or empty folder at path, or throw a DiskException
if ((open.how == Open.overwrite || open.how == Open.make) && path.exists()) throw new DiskException("exists"); // Make requires available path
if ((open.how == Open.read || open.how == Open.write) && !path.existsFile()) throw new DiskException("not found"); // Open requires file at path
// Make or open the file
String access = "rw"; // For the make, overwrite, and write commands, get read and write access
if (open.how == Open.read) access = "r"; // For the read command, get read access
file = new RandomAccessFile(path.file, access);
// Get or create and save the pattern
StripePattern pattern = open.pattern;
if (pattern == null) { // If no pattern given in path, make one
pattern = new StripePattern(); // If file is empty, pattern is ready
long size = file.getChannel().size(); // If the file has gaps, size will be as if they are full
if (size > 0) pattern = pattern.add(new Stripe(0, size)); // Mark the whole file as full
}
this.pattern = pattern;
} catch (IOException e) { throw new DiskException(e); }
}
| public File(Open open) {
try {
// Get and save the path
path = open.path;
// Enforce and check how we are told to open the file
if (open.how == Open.overwrite) path.delete(); // Delete a file or empty folder at path, or throw a DiskException
if ((open.how == Open.overwrite || open.how == Open.make) && path.exists()) throw new DiskException("exists"); // Make requires available path
if ((open.how == Open.read || open.how == Open.write) && !path.existsFile()) throw new DiskException("not found"); // Open requires file at path
// Make or open the file
String access = "rw"; // For the make, overwrite, and write commands, get read and write access
if (open.how == Open.read) access = "r"; // For the read command, get read access
file = new RandomAccessFile(path.file, access);
// Get or create and save the pattern
StripePattern pattern = open.pattern;
if (pattern == null) { // If no pattern given in path, make one
pattern = new StripePattern(); // If file is empty, pattern is ready
long size = file.getChannel().size(); // If the file has gaps, size will be as if they are full
if (size > 0) pattern = pattern.add(new Stripe(0, size)); // Mark the whole file as full
}
this.pattern = pattern;
} catch (IOException e) {
close(this);
throw new DiskException(e);
} catch (RuntimeException e) {
close(this);
throw e;
}
}
|
diff --git a/src/java/liquibase/migrator/change/AddAutoIncrementChange.java b/src/java/liquibase/migrator/change/AddAutoIncrementChange.java
index 99f3854f..561fa4a7 100644
--- a/src/java/liquibase/migrator/change/AddAutoIncrementChange.java
+++ b/src/java/liquibase/migrator/change/AddAutoIncrementChange.java
@@ -1,75 +1,75 @@
package liquibase.migrator.change;
import liquibase.database.Database;
import liquibase.database.MSSQLDatabase;
import liquibase.database.OracleDatabase;
import liquibase.database.PostgresDatabase;
import liquibase.migrator.UnsupportedChangeException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
* Makes an existing column into an auto-increment column.
* This change is only valid for databases with auto-increment/identity columns.
* The current version does not support MS-SQL.
*/
public class AddAutoIncrementChange extends AbstractChange {
private String tableName;
private String columnName;
private String columnDataType;
public AddAutoIncrementChange() {
super("addAutoIncrement", "Set Column as Auto-Increment");
}
public String getTableName() {
return tableName;
}
public void setTableName(String tableName) {
this.tableName = tableName;
}
public String getColumnName() {
return columnName;
}
public void setColumnName(String columnName) {
this.columnName = columnName;
}
public String getColumnDataType() {
return columnDataType;
}
public void setColumnDataType(String columnDataType) {
this.columnDataType = columnDataType;
}
public String[] generateStatements(Database database) throws UnsupportedChangeException {
if (database instanceof OracleDatabase) {
throw new UnsupportedChangeException("Oracle does not support auto-increment columns");
} else if (database instanceof MSSQLDatabase) {
- throw new UnsupportedChangeException("MS-SQL does not support adding identities to existing tables");
+ throw new UnsupportedChangeException("MS SQL Server does not support auto-increment columns");
} else if (database instanceof PostgresDatabase) {
- throw new UnsupportedChangeException("Oracle does not support auto-increment columns");
+ throw new UnsupportedChangeException("PostgreSQL does not support auto-increment columns");
}
return new String[]{
"ALTER TABLE " + getTableName() + " MODIFY " + getColumnName() + " " + getColumnDataType() + " AUTO_INCREMENT",
};
}
public String getConfirmationMessage() {
return "Column Set as Auto-Increment";
}
public Element createNode(Document currentChangeLogFileDOM) {
Element node = currentChangeLogFileDOM.createElement("addAutoIncrement");
node.setAttribute("tableName", getTableName());
node.setAttribute("columnName", getColumnName());
return node;
}
}
| false | true | public String[] generateStatements(Database database) throws UnsupportedChangeException {
if (database instanceof OracleDatabase) {
throw new UnsupportedChangeException("Oracle does not support auto-increment columns");
} else if (database instanceof MSSQLDatabase) {
throw new UnsupportedChangeException("MS-SQL does not support adding identities to existing tables");
} else if (database instanceof PostgresDatabase) {
throw new UnsupportedChangeException("Oracle does not support auto-increment columns");
}
return new String[]{
"ALTER TABLE " + getTableName() + " MODIFY " + getColumnName() + " " + getColumnDataType() + " AUTO_INCREMENT",
};
}
| public String[] generateStatements(Database database) throws UnsupportedChangeException {
if (database instanceof OracleDatabase) {
throw new UnsupportedChangeException("Oracle does not support auto-increment columns");
} else if (database instanceof MSSQLDatabase) {
throw new UnsupportedChangeException("MS SQL Server does not support auto-increment columns");
} else if (database instanceof PostgresDatabase) {
throw new UnsupportedChangeException("PostgreSQL does not support auto-increment columns");
}
return new String[]{
"ALTER TABLE " + getTableName() + " MODIFY " + getColumnName() + " " + getColumnDataType() + " AUTO_INCREMENT",
};
}
|
diff --git a/org.cloudsmith.geppetto.pp.dsl/src/org/cloudsmith/geppetto/pp/dsl/validation/PPJavaValidator.java b/org.cloudsmith.geppetto.pp.dsl/src/org/cloudsmith/geppetto/pp/dsl/validation/PPJavaValidator.java
index ca9c0e28..af682c13 100644
--- a/org.cloudsmith.geppetto.pp.dsl/src/org/cloudsmith/geppetto/pp/dsl/validation/PPJavaValidator.java
+++ b/org.cloudsmith.geppetto.pp.dsl/src/org/cloudsmith/geppetto/pp/dsl/validation/PPJavaValidator.java
@@ -1,1180 +1,1180 @@
/**
* Copyright (c) 2011 Cloudsmith Inc. and other contributors, as listed below.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Cloudsmith
*
*/
package org.cloudsmith.geppetto.pp.dsl.validation;
import static org.cloudsmith.geppetto.pp.adapters.ClassifierAdapter.RESOURCE_IS_BAD;
import static org.cloudsmith.geppetto.pp.adapters.ClassifierAdapter.RESOURCE_IS_CLASSPARAMS;
import static org.cloudsmith.geppetto.pp.adapters.ClassifierAdapter.RESOURCE_IS_DEFAULT;
import static org.cloudsmith.geppetto.pp.adapters.ClassifierAdapter.RESOURCE_IS_OVERRIDE;
import static org.cloudsmith.geppetto.pp.adapters.ClassifierAdapter.RESOURCE_IS_REGULAR;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import org.cloudsmith.geppetto.pp.AndExpression;
import org.cloudsmith.geppetto.pp.AppendExpression;
import org.cloudsmith.geppetto.pp.AssignmentExpression;
import org.cloudsmith.geppetto.pp.AtExpression;
import org.cloudsmith.geppetto.pp.AttributeAddition;
import org.cloudsmith.geppetto.pp.AttributeDefinition;
import org.cloudsmith.geppetto.pp.AttributeOperation;
import org.cloudsmith.geppetto.pp.AttributeOperations;
import org.cloudsmith.geppetto.pp.BinaryExpression;
import org.cloudsmith.geppetto.pp.BinaryOpExpression;
import org.cloudsmith.geppetto.pp.CaseExpression;
import org.cloudsmith.geppetto.pp.CollectExpression;
import org.cloudsmith.geppetto.pp.Definition;
import org.cloudsmith.geppetto.pp.DefinitionArgument;
import org.cloudsmith.geppetto.pp.DoubleQuotedString;
import org.cloudsmith.geppetto.pp.ElseExpression;
import org.cloudsmith.geppetto.pp.ElseIfExpression;
import org.cloudsmith.geppetto.pp.EqualityExpression;
import org.cloudsmith.geppetto.pp.Expression;
import org.cloudsmith.geppetto.pp.ExpressionTE;
import org.cloudsmith.geppetto.pp.FunctionCall;
import org.cloudsmith.geppetto.pp.HostClassDefinition;
import org.cloudsmith.geppetto.pp.IQuotedString;
import org.cloudsmith.geppetto.pp.IfExpression;
import org.cloudsmith.geppetto.pp.ImportExpression;
import org.cloudsmith.geppetto.pp.InExpression;
import org.cloudsmith.geppetto.pp.LiteralBoolean;
import org.cloudsmith.geppetto.pp.LiteralDefault;
import org.cloudsmith.geppetto.pp.LiteralHash;
import org.cloudsmith.geppetto.pp.LiteralList;
import org.cloudsmith.geppetto.pp.LiteralName;
import org.cloudsmith.geppetto.pp.LiteralNameOrReference;
import org.cloudsmith.geppetto.pp.LiteralRegex;
import org.cloudsmith.geppetto.pp.LiteralUndef;
import org.cloudsmith.geppetto.pp.MatchingExpression;
import org.cloudsmith.geppetto.pp.MultiplicativeExpression;
import org.cloudsmith.geppetto.pp.NodeDefinition;
import org.cloudsmith.geppetto.pp.OrExpression;
import org.cloudsmith.geppetto.pp.PPPackage;
import org.cloudsmith.geppetto.pp.ParenthesisedExpression;
import org.cloudsmith.geppetto.pp.PuppetManifest;
import org.cloudsmith.geppetto.pp.RelationalExpression;
import org.cloudsmith.geppetto.pp.RelationshipExpression;
import org.cloudsmith.geppetto.pp.ResourceBody;
import org.cloudsmith.geppetto.pp.ResourceExpression;
import org.cloudsmith.geppetto.pp.SelectorEntry;
import org.cloudsmith.geppetto.pp.SelectorExpression;
import org.cloudsmith.geppetto.pp.ShiftExpression;
import org.cloudsmith.geppetto.pp.SingleQuotedString;
import org.cloudsmith.geppetto.pp.StringExpression;
import org.cloudsmith.geppetto.pp.UnaryExpression;
import org.cloudsmith.geppetto.pp.UnaryMinusExpression;
import org.cloudsmith.geppetto.pp.UnaryNotExpression;
import org.cloudsmith.geppetto.pp.VariableExpression;
import org.cloudsmith.geppetto.pp.VerbatimTE;
import org.cloudsmith.geppetto.pp.VirtualNameOrReference;
import org.cloudsmith.geppetto.pp.adapters.ClassifierAdapter;
import org.cloudsmith.geppetto.pp.adapters.ClassifierAdapterFactory;
import org.cloudsmith.geppetto.pp.dsl.linking.IMessageAcceptor;
import org.cloudsmith.geppetto.pp.dsl.linking.ValidationBasedMessageAcceptor;
import org.cloudsmith.geppetto.pp.dsl.services.PPGrammarAccess;
import org.cloudsmith.geppetto.pp.util.TextExpressionHelper;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.EReference;
import org.eclipse.xtext.IGrammarAccess;
import org.eclipse.xtext.RuleCall;
import org.eclipse.xtext.nodemodel.ICompositeNode;
import org.eclipse.xtext.nodemodel.ILeafNode;
import org.eclipse.xtext.nodemodel.INode;
import org.eclipse.xtext.nodemodel.util.NodeModelUtils;
import org.eclipse.xtext.util.Exceptions;
import org.eclipse.xtext.util.PolymorphicDispatcher;
import org.eclipse.xtext.util.PolymorphicDispatcher.ErrorHandler;
import org.eclipse.xtext.validation.Check;
import com.google.inject.Inject;
public class PPJavaValidator extends AbstractPPJavaValidator implements IPPDiagnostics {
/**
* The CollectChecker is used to check the validity of puppet CollectExpression
*/
protected class CollectChecker {
private final PolymorphicDispatcher<Void> collectCheckerDispatch = new PolymorphicDispatcher<Void>(
"check", 1, 2, Collections.singletonList(this), new ErrorHandler<Void>() {
public Void handle(Object[] params, Throwable e) {
return handleError(params, e);
}
});
public void check(AndExpression o) {
doCheck(o.getLeftExpr());
doCheck(o.getRightExpr());
}
public void check(EqualityExpression o) {
doCheck(o.getLeftExpr(), Boolean.TRUE);
doCheck(o.getRightExpr(), Boolean.FALSE);
}
public void check(EqualityExpression o, boolean left) {
check(o);
}
public void check(Expression o) {
acceptor.acceptError(
"Expression type not allowed here.", o, o.eContainingFeature(), INSIGNIFICANT_INDEX,
IPPDiagnostics.ISSUE__UNSUPPORTED_EXPRESSION);
}
public void check(Expression o, boolean left) {
acceptor.acceptError(
"Expression type not allowed as " + (left
? "left"
: "right") + " expression.", o, o.eContainingFeature(), INSIGNIFICANT_INDEX,
IPPDiagnostics.ISSUE__UNSUPPORTED_EXPRESSION);
}
public void check(LiteralBoolean o, boolean left) {
if(left)
check(o);
}
public void check(LiteralName o, boolean left) {
// intrinsic check of LiteralName is enough
}
public void check(LiteralNameOrReference o, boolean left) {
if(isNAME(o.getValue()))
return; // ok both left and right
if(!left && isCLASSREF(o.getValue())) // accept "type" if right
return;
acceptor.acceptError("Must be a name" + (!left
? " or type."
: "."), o, PPPackage.Literals.LITERAL_NAME_OR_REFERENCE__VALUE, INSIGNIFICANT_INDEX, left
? IPPDiagnostics.ISSUE__NOT_NAME
: IPPDiagnostics.ISSUE__NOT_NAME_OR_REF);
}
public void check(OrExpression o) {
doCheck(o.getLeftExpr());
doCheck(o.getRightExpr());
}
public void check(ParenthesisedExpression o) {
doCheck(o.getExpr());
}
public void check(SelectorExpression o, boolean left) {
if(left)
check(o);
}
public void check(StringExpression o, boolean left) {
// TODO: follow up if all types of StringExpression (single, double, and unquoted are supported).
if(left)
check(o);
}
public void check(VariableExpression o, boolean left) {
// intrinsic variable check is enough
}
/**
* Calls "collectCheck" in polymorphic fashion.
*
* @param o
*/
public void doCheck(Object... o) {
collectCheckerDispatch.invoke(o);
}
public Void handleError(Object[] params, Throwable e) {
return Exceptions.throwUncheckedException(e);
}
}
final protected IMessageAcceptor acceptor;
@Inject
private PPPatternHelper patternHelper;
private PPGrammarAccess puppetGrammarAccess;
/**
* Classes accepted as top level statements in a pp manifest.
*/
private static final Class<?>[] topLevelExprClasses = { ResourceExpression.class, // resource, virtual, resource override
RelationshipExpression.class, //
CollectExpression.class, //
AssignmentExpression.class, //
IfExpression.class, //
CaseExpression.class, //
ImportExpression.class, //
FunctionCall.class, //
Definition.class, HostClassDefinition.class, //
NodeDefinition.class, //
AppendExpression.class //
};
/**
* Classes accepted as RVALUE.
*/
private static final Class<?>[] rvalueClasses = { StringExpression.class, // TODO: was LiteralString, follow up
LiteralNameOrReference.class, // NAME and TYPE
LiteralBoolean.class, //
SelectorExpression.class, //
VariableExpression.class, //
LiteralList.class, //
LiteralHash.class, //
AtExpression.class, // HashArray access or ResourceReference are accepted
// resource reference - see AtExpression
FunctionCall.class, // i.e. only parenthesized form
LiteralUndef.class, };
private static final String[] keywords = {
"and", "or", "case", "default", "define", "import", "if", "elsif", "else", "inherits", "node", "in",
"undef", "true", "false" };
@Inject
public PPJavaValidator(IGrammarAccess ga) {
acceptor = new ValidationBasedMessageAcceptor(this);
puppetGrammarAccess = (PPGrammarAccess) ga;
}
@Check
public void checkAdditiveExpression(ShiftExpression o) {
checkOperator(o, "+", "-");
}
@Check
public void checkAppendExpression(AppendExpression o) {
Expression leftExpr = o.getLeftExpr();
if(!(leftExpr instanceof VariableExpression))
acceptor.acceptError(
"Not an appendable expression", o, PPPackage.Literals.BINARY_EXPRESSION__LEFT_EXPR,
INSIGNIFICANT_INDEX, IPPDiagnostics.ISSUE__NOT_APPENDABLE);
}
@Check
public void checkAssignmentExpression(AssignmentExpression o) {
Expression leftExpr = o.getLeftExpr();
if(!(leftExpr instanceof VariableExpression || leftExpr instanceof AtExpression))
acceptor.acceptError(
"Not an assignable expression", o, PPPackage.Literals.BINARY_EXPRESSION__LEFT_EXPR,
INSIGNIFICANT_INDEX, IPPDiagnostics.ISSUE__NOT_ASSIGNABLE);
// TODO: rhs is not validated, it allows expression, which includes rvalue, but some top level expressions
// are probably not allowed (case?)
}
/**
* Checks if an AtExpression is either a valid hash access, or a resource reference.
* Use isStandardAtExpression to check if an AtExpression is one or the other.
* Also see {@link #isStandardAtExpression(AtExpression)})
*
* @param o
*/
@Check
public void checkAtExpression(AtExpression o) {
if(!isStandardAtExpression(o)) {
checkAtExpressionAsResourceReference(o);
return;
}
// Puppet grammar At expression is VARIABLE[expr]([expr])? (i.e. only one nested level).
//
final Expression leftExpr = o.getLeftExpr();
if(leftExpr == null)
acceptor.acceptError(
"Expression left of [] is required", o, PPPackage.Literals.PARAMETERIZED_EXPRESSION__LEFT_EXPR,
INSIGNIFICANT_INDEX, IPPDiagnostics.ISSUE__REQUIRED_EXPRESSION);
else if(!(leftExpr instanceof VariableExpression || (o.eContainer() instanceof ExpressionTE && leftExpr instanceof LiteralNameOrReference))) {
// then, the leftExpression *must* be an AtExpression with a leftExpr being a variable
if(leftExpr instanceof AtExpression) {
// older versions limited access to two levels.
if(!PuppetCompatibilityHelper.allowMoreThan2AtInSequence()) {
final Expression nestedLeftExpr = ((AtExpression) leftExpr).getLeftExpr();
// if nestedLeftExpr is null, it is validated for the nested instance
if(nestedLeftExpr != null &&
!(nestedLeftExpr instanceof VariableExpression || (o.eContainer() instanceof ExpressionTE && nestedLeftExpr instanceof LiteralNameOrReference)))
acceptor.acceptError(
"Expression left of [] must be a variable.", nestedLeftExpr,
PPPackage.Literals.PARAMETERIZED_EXPRESSION__LEFT_EXPR, INSIGNIFICANT_INDEX,
IPPDiagnostics.ISSUE__UNSUPPORTED_EXPRESSION);
}
}
else {
acceptor.acceptError(
"Expression left of [] must be a variable.", leftExpr,
PPPackage.Literals.PARAMETERIZED_EXPRESSION__LEFT_EXPR, INSIGNIFICANT_INDEX,
IPPDiagnostics.ISSUE__UNSUPPORTED_EXPRESSION);
}
}
// -- check that there is exactly one parameter expression (the key)
switch(o.getParameters().size()) {
case 0:
acceptor.acceptError(
"Key/index expression is required", o, PPPackage.Literals.PARAMETERIZED_EXPRESSION__PARAMETERS,
INSIGNIFICANT_INDEX, IPPDiagnostics.ISSUE__REQUIRED_EXPRESSION);
break;
case 1:
break; // ok
default:
acceptor.acceptError(
"Multiple expressions are not allowed", o, PPPackage.Literals.PARAMETERIZED_EXPRESSION__PARAMETERS,
INSIGNIFICANT_INDEX, IPPDiagnostics.ISSUE__UNSUPPORTED_EXPRESSION);
}
// // TODO: Check for valid expressions (don't know if any expression is acceptable)
// for(Expression expr : o.getParameters()) {
// //
// }
}
/**
* Checks that an AtExpression that acts as a ResourceReference is valid.
*
* @param resourceRef
* @param errorStartText
*/
public void checkAtExpressionAsResourceReference(AtExpression resourceRef) {
final String errorStartText = "A resource reference";
Expression leftExpr = resourceRef.getLeftExpr();
if(leftExpr == null)
acceptor.acceptError(
errorStartText + " must start with a name or referece (was null).", resourceRef,
PPPackage.Literals.PARAMETERIZED_EXPRESSION__LEFT_EXPR, INSIGNIFICANT_INDEX,
IPPDiagnostics.ISSUE__RESOURCE_REFERENCE_NO_REFERENCE);
else {
String name = leftExpr instanceof LiteralNameOrReference
? ((LiteralNameOrReference) leftExpr).getValue()
: null;
boolean isref = isCLASSREF(name);
boolean isname = isNAME(name);
if(!isref) {
if(!isname)
acceptor.acceptError(
errorStartText + " must start with a [(deprecated) name, or] class reference.", resourceRef,
PPPackage.Literals.PARAMETERIZED_EXPRESSION__LEFT_EXPR, INSIGNIFICANT_INDEX,
IPPDiagnostics.ISSUE__NOT_CLASSREF);
else
acceptor.acceptWarning(
errorStartText + " uses deprecated form of reference. Should start with upper case letter.",
resourceRef, PPPackage.Literals.PARAMETERIZED_EXPRESSION__LEFT_EXPR, INSIGNIFICANT_INDEX,
IPPDiagnostics.ISSUE__DEPRECATED_REFERENCE);
}
}
if(resourceRef.getParameters().size() < 1)
acceptor.acceptError(
errorStartText + " must have at least one expression in list.", resourceRef,
PPPackage.Literals.PARAMETERIZED_EXPRESSION__PARAMETERS, INSIGNIFICANT_INDEX,
IPPDiagnostics.ISSUE__RESOURCE_REFERENCE_NO_PARAMETERS);
// TODO: Possibly check valid expressions in the list, there are probably many illegal constructs valid in Puppet grammar
// TODO: Handle all relaxations in the puppet model/grammar
for(Expression expr : resourceRef.getParameters()) {
if(expr instanceof LiteralRegex)
acceptor.acceptError(
errorStartText + " invalid resource reference parameter expression type.", resourceRef,
PPPackage.Literals.PARAMETERIZED_EXPRESSION__PARAMETERS, resourceRef.getParameters().indexOf(expr),
IPPDiagnostics.ISSUE__UNSUPPORTED_EXPRESSION);
}
}
@Check
public void checkAttributeAddition(AttributeAddition o) {
if(!isNAME(o.getKey()))
acceptor.acceptError(
"Bad name format.", o, PPPackage.Literals.ATTRIBUTE_OPERATION__KEY, INSIGNIFICANT_INDEX,
IPPDiagnostics.ISSUE__NOT_NAME);
}
@Check
public void checkAttributeDefinition(AttributeDefinition o) {
if(!isNAME(o.getKey()))
acceptor.acceptError(
"Bad name format.", o, PPPackage.Literals.ATTRIBUTE_OPERATION__KEY, INSIGNIFICANT_INDEX,
IPPDiagnostics.ISSUE__NOT_NAME);
}
/**
* Checks that AttributeOperation objects in the list are separated by commas
* (if there is an associated node model).
*
* @param o
*/
@Check
public void checkAttributeOperations(AttributeOperations o) {
ICompositeNode rootNode = NodeModelUtils.getNode(o);
if(rootNode != null) {
boolean expectComma = false;
int expectOffset = 0;
for(INode n : rootNode.getChildren()) {
// skip whitespace and comments
if(n instanceof ILeafNode && ((ILeafNode) n).isHidden())
continue;
if(expectComma) {
if(!(n instanceof ILeafNode && ",".equals(n.getText()))) {
acceptor.acceptError(
"Missing Comma", n.getSemanticElement(), expectOffset, 1,
IPPDiagnostics.ISSUE__MISSING_COMMA);
}
expectComma = false;
}
if(n.getGrammarElement() instanceof RuleCall) {
RuleCall rc = (RuleCall) n.getGrammarElement();
// TODO: Check against real rule - not string
// if(rc.getRule().getName().equals("AttributeOperation")) {
if(rc.getRule().equals(puppetGrammarAccess.getAttributeOperationRule())) {
expectComma = true;
// pos where would have liked to see a comma
expectOffset = n.getTotalOffset() + n.getTotalLength();
}
}
}
}
}
@Check
public void checkBinaryExpression(BinaryExpression o) {
if(o.getLeftExpr() == null)
acceptor.acceptError(
"A binary expression must have a left expr", o, PPPackage.Literals.BINARY_EXPRESSION__LEFT_EXPR,
INSIGNIFICANT_INDEX, IPPDiagnostics.ISSUE__NULL_EXPRESSION);
if(o.getRightExpr() == null)
acceptor.acceptError(
"A binary expression must have a right expr", o, PPPackage.Literals.BINARY_EXPRESSION__RIGHT_EXPR,
INSIGNIFICANT_INDEX, IPPDiagnostics.ISSUE__NULL_EXPRESSION);
}
@Check
public void checkCollectExpression(CollectExpression o) {
// -- the class reference must have valid class ref format
final Expression classRefExpr = o.getClassReference();
if(classRefExpr instanceof LiteralNameOrReference) {
final String classRefString = ((LiteralNameOrReference) classRefExpr).getValue();
if(!isCLASSREF(classRefString))
acceptor.acceptError(
"Not a well formed class reference.", o, PPPackage.Literals.COLLECT_EXPRESSION__CLASS_REFERENCE,
INSIGNIFICANT_INDEX, IPPDiagnostics.ISSUE__NOT_CLASSREF);
}
else {
acceptor.acceptError(
"Not a class reference.", o, PPPackage.Literals.COLLECT_EXPRESSION__CLASS_REFERENCE,
INSIGNIFICANT_INDEX, IPPDiagnostics.ISSUE__NOT_CLASSREF);
}
// -- the rhs expressions do not allow a full set of expressions, an extensive search must be made
// Note: queries must implement both IQuery and be UnaryExpressions
UnaryExpression q = (UnaryExpression) o.getQuery();
Expression queryExpr = q.getExpr();
// null expression is accepted, if stated it must comply with the simplified expressions allowed
// for a collect expression
if(queryExpr != null) {
CollectChecker cc = new CollectChecker();
cc.doCheck(queryExpr);
}
}
@Check
public void checkDefinition(Definition o) {
// Can only be contained by manifest (global scope), or another class.
EObject container = o.eContainer();
if(!(container instanceof PuppetManifest || container instanceof HostClassDefinition))
acceptor.acceptError(
"A definition may only appear at toplevel or directly inside classes.", o.eContainer(),
o.eContainingFeature(), INSIGNIFICANT_INDEX, IPPDiagnostics.ISSUE__NOT_AT_TOPLEVEL_OR_CLASS);
}
@Check
public void checkDefinitionArgument(DefinitionArgument o) {
// -- LHS should be a variable, use of name is deprecated
String argName = o.getArgName();
if(argName == null || argName.length() < 1)
acceptor.acceptError(
"Empty or null argument", o, PPPackage.Literals.DEFINITION_ARGUMENT__ARG_NAME, INSIGNIFICANT_INDEX,
IPPDiagnostics.ISSUE__NOT_VARNAME);
else if(!argName.startsWith("$"))
acceptor.acceptWarning(
"Deprecation: Definition argument should now start with $", o,
PPPackage.Literals.DEFINITION_ARGUMENT__ARG_NAME, INSIGNIFICANT_INDEX,
IPPDiagnostics.ISSUE__NOT_VARNAME);
else if(!isVARIABLE(argName))
acceptor.acceptError(
"Not a valid variable name", o, PPPackage.Literals.DEFINITION_ARGUMENT__ARG_NAME, INSIGNIFICANT_INDEX,
IPPDiagnostics.ISSUE__NOT_VARNAME);
// -- RHS should be a rvalue
internalCheckRvalueExpression(o.getValue());
}
@Check
public void checkElseExpression(ElseExpression o) {
EObject container = o.eContainer();
if(container instanceof IfExpression || container instanceof ElseExpression ||
container instanceof ElseIfExpression)
return;
acceptor.acceptError(
"'else' expression can only be used in an 'if', 'else' or 'elsif'", o, o.eContainingFeature(),
INSIGNIFICANT_INDEX, IPPDiagnostics.ISSUE__UNSUPPORTED_EXPRESSION);
}
@Check
public void checkElseIfExpression(ElseIfExpression o) {
EObject container = o.eContainer();
if(container instanceof IfExpression || container instanceof ElseExpression ||
container instanceof ElseIfExpression)
return;
acceptor.acceptError(
"'elsif' expression can only be used in an 'if', 'else' or 'elsif'", o, o.eContainingFeature(),
INSIGNIFICANT_INDEX, IPPDiagnostics.ISSUE__UNSUPPORTED_EXPRESSION);
}
@Check
public void checkEqualityExpression(EqualityExpression o) {
checkOperator(o, "==", "!=");
}
@Check
public void checkFunctionCall(FunctionCall o) {
if(!(o.getLeftExpr() instanceof LiteralNameOrReference))
acceptor.acceptError(
"Must be a name or reference.", o, PPPackage.Literals.PARAMETERIZED_EXPRESSION__LEFT_EXPR,
IPPDiagnostics.ISSUE__NOT_NAME_OR_REF);
// rest of validation - valid function - is done during linking
}
@Check
public void checkHostClassDefinition(HostClassDefinition o) {
// TODO: name must be NAME, CLASSNAME or "class"
// TODO: parent should be a known class
// Can only be contained by manifest (global scope), or another class.
EObject container = o.eContainer();
if(!(container instanceof PuppetManifest || container instanceof HostClassDefinition))
acceptor.acceptError(
"Classes may only appear at toplevel or directly inside other classes.", o,
IPPDiagnostics.ISSUE__NOT_AT_TOPLEVEL_OR_CLASS);
internalCheckTopLevelExpressions(o.getStatements());
}
@Check
public void checkIfExpression(IfExpression o) {
Expression elseStatement = o.getElseStatement();
if(elseStatement == null || elseStatement instanceof ElseExpression || elseStatement instanceof IfExpression ||
elseStatement instanceof ElseIfExpression)
return;
acceptor.acceptError(
"If Expression's else part can only be an 'if' or 'elsif'", o,
PPPackage.Literals.IF_EXPRESSION__ELSE_STATEMENT, INSIGNIFICANT_INDEX,
IPPDiagnostics.ISSUE__UNSUPPORTED_EXPRESSION);
}
@Check
public void checkImportExpression(ImportExpression o) {
if(o.getValues().size() <= 0)
acceptor.acceptError(
"Empty import - should be followed by at least one string.", o,
PPPackage.Literals.IMPORT_EXPRESSION__VALUES, INSIGNIFICANT_INDEX,
IPPDiagnostics.ISSUE__REQUIRED_EXPRESSION);
// warn against interpolation in double quoted strings
for(IQuotedString s : o.getValues()) {
if(s instanceof DoubleQuotedString)
if(hasInterpolation(s))
acceptor.acceptWarning(
"String has interpolation expressions that will not be evaluated", s,
PPPackage.Literals.IMPORT_EXPRESSION__VALUES, o.getValues().indexOf(s),
IPPDiagnostics.ISSUE__UNSUPPORTED_EXPRESSION);
}
}
@Check
public void checkInExpression(InExpression o) {
checkOperator(o, "in");
}
@Check
public void checkLiteralName(LiteralName o) {
if(!isNAME(o.getValue()))
acceptor.acceptError(
"Expected to comply with NAME rule", o, PPPackage.Literals.LITERAL_NAME__VALUE, INSIGNIFICANT_INDEX,
IPPDiagnostics.ISSUE__NOT_NAME);
}
@Check
public void checkLiteralNameOrReference(LiteralNameOrReference o) {
if(isKEYWORD(o.getValue())) {
acceptor.acceptError(
"Reserved word.", o, PPPackage.Literals.LITERAL_NAME_OR_REFERENCE__VALUE, INSIGNIFICANT_INDEX,
IPPDiagnostics.ISSUE__RESERVED_WORD);
return;
}
if(isCLASSNAME_OR_REFERENCE(o.getValue()))
return;
acceptor.acceptError(
"Must be a name or type.", o, PPPackage.Literals.LITERAL_NAME_OR_REFERENCE__VALUE, INSIGNIFICANT_INDEX,
IPPDiagnostics.ISSUE__NOT_NAME_OR_REF);
}
@Check
public void checkLiteralRegex(LiteralRegex o) {
if(!isREGEX(o.getValue())) {
acceptor.acceptError(
"Expected to comply with Puppet regular expression", o, PPPackage.Literals.LITERAL_REGEX__VALUE,
INSIGNIFICANT_INDEX, IPPDiagnostics.ISSUE__NOT_REGEX);
return;
}
if(!o.getValue().endsWith("/"))
acceptor.acceptError(
"Puppet regular expression does not support flags after end slash", o,
PPPackage.Literals.LITERAL_REGEX__VALUE, INSIGNIFICANT_INDEX,
IPPDiagnostics.ISSUE__UNSUPPORTED_REGEX_FLAGS);
}
@Check
public void checkMatchingExpression(MatchingExpression o) {
Expression regex = o.getRightExpr();
if(regex == null || !(regex instanceof LiteralRegex))
acceptor.acceptError(
"Right expression must be a regular expression.", o, PPPackage.Literals.BINARY_EXPRESSION__RIGHT_EXPR,
INSIGNIFICANT_INDEX, IPPDiagnostics.ISSUE__UNSUPPORTED_EXPRESSION);
checkOperator(o, "=~", "!~");
}
@Check
public void checkMultiplicativeExpression(MultiplicativeExpression o) {
checkOperator(o, "*", "/");
}
@Check
public void checkNodeDefinition(NodeDefinition o) {
// Can only be contained by manifest (global scope), or another class.
EObject container = o.eContainer();
if(!(container instanceof PuppetManifest || container instanceof HostClassDefinition))
acceptor.acceptError(
"A node definition may only appear at toplevel or directly inside classes.", o, o.eContainingFeature(),
INSIGNIFICANT_INDEX, IPPDiagnostics.ISSUE__NOT_AT_TOPLEVEL_OR_CLASS);
}
protected void checkOperator(BinaryOpExpression o, String... ops) {
String op = o.getOpName();
for(String s : ops)
if(s.equals(op))
return;
acceptor.acceptError(
"Illegal operator: " + op == null
? "null"
: op, o, PPPackage.Literals.BINARY_OP_EXPRESSION__OP_NAME, INSIGNIFICANT_INDEX,
IPPDiagnostics.ISSUE__ILLEGAL_OP);
}
@Check
public void checkPuppetManifest(PuppetManifest o) {
internalCheckTopLevelExpressions(o.getStatements());
}
@Check
public void checkRelationalExpression(RelationalExpression o) {
String op = o.getOpName();
if("<".equals(op) || "<=".equals(op) || ">".equals(op) || ">=".equals(op))
return;
acceptor.acceptError(
"Illegal operator.", o, PPPackage.Literals.BINARY_OP_EXPRESSION__OP_NAME, INSIGNIFICANT_INDEX,
IPPDiagnostics.ISSUE__ILLEGAL_OP);
}
/**
* Checks that a RelationshipExpression
* only has left and right of type
* - ResourceExpression (but not a ResourceOverride)
* - ResourceReference
* - CollectExpression
*
* That the operator name is a valid name (if defined from code).
* INEDGE : MINUS GT; // '->'
* OUTEDGE : LT MINUS; // '<-'
* INEDGE_SUB : TILDE GT; // '~>'
* OUTEDGE_SUB : LT TILDE; // '<~'
*/
@Check
public void checkRelationshipExpression(RelationshipExpression o) {
// -- Check operator validity
String opName = o.getOpName();
if(opName == null ||
!("->".equals(opName) || "<-".equals(opName) || "~>".equals(opName) || "<~".equals(opName)))
acceptor.acceptError(
"Illegal operator: " + opName == null
? "null"
: opName, o, PPPackage.Literals.BINARY_OP_EXPRESSION__OP_NAME, INSIGNIFICANT_INDEX,
IPPDiagnostics.ISSUE__ILLEGAL_OP);
internalCheckRelationshipOperand(o, o.getLeftExpr(), PPPackage.Literals.BINARY_EXPRESSION__LEFT_EXPR);
internalCheckRelationshipOperand(o, o.getRightExpr(), PPPackage.Literals.BINARY_EXPRESSION__RIGHT_EXPR);
}
@Check
public void checkResourceBody(ResourceBody o) {
Expression nameExpr = o.getNameExpr();
// missing name is checked by container (if it is ok or not)
if(nameExpr == null)
return;
if(!(nameExpr instanceof StringExpression ||
// TODO: was LiteralString, follow up
nameExpr instanceof LiteralNameOrReference || nameExpr instanceof LiteralName ||
nameExpr instanceof VariableExpression || nameExpr instanceof AtExpression ||
nameExpr instanceof LiteralList || nameExpr instanceof SelectorExpression))
acceptor.acceptError(
"Expression unsupported as resource name/title.", o, PPPackage.Literals.RESOURCE_BODY__NAME_EXPR,
INSIGNIFICANT_INDEX, IPPDiagnostics.ISSUE__UNSUPPORTED_EXPRESSION);
}
/**
* Checks ResourceExpression and derived VirtualResourceExpression.
*
* @param o
*/
@Check
public void checkResourceExpression(ResourceExpression o) {
// A regular resource must have a classname
// Use of class reference is deprecated
// classname : NAME | "class" | CLASSNAME
int resourceType = RESOURCE_IS_BAD; // unknown at this point
final Expression resourceExpr = o.getResourceExpr();
String resourceTypeName = null;
if(resourceExpr instanceof LiteralNameOrReference || resourceExpr instanceof VirtualNameOrReference) {
if(resourceExpr instanceof LiteralNameOrReference) {
LiteralNameOrReference resourceTypeExpr = (LiteralNameOrReference) resourceExpr;
resourceTypeName = resourceTypeExpr.getValue();
}
else {
VirtualNameOrReference vn = (VirtualNameOrReference) resourceExpr;
resourceTypeName = vn.getValue();
}
if("class".equals(resourceTypeName))
resourceType = RESOURCE_IS_CLASSPARAMS;
else if(isCLASSREF(resourceTypeName))
resourceType = RESOURCE_IS_DEFAULT;
else if(isNAME(resourceTypeName) || isCLASSNAME(resourceTypeName))
resourceType = RESOURCE_IS_REGULAR;
// else the resource is BAD
}
if(resourceExpr instanceof AtExpression) {
resourceType = RESOURCE_IS_OVERRIDE;
}
/*
* IMPORTANT: set the validated classifier to enable others to more quickly determine the type of
* resource, and its typeName (what it is a reference to).
*/
ClassifierAdapter adapter = ClassifierAdapterFactory.eINSTANCE.adapt(o);
adapter.setClassifier(resourceType);
adapter.setResourceType(null);
adapter.setResourceTypeName(resourceTypeName);
if(resourceType == RESOURCE_IS_BAD) {
acceptor.acceptError(
"Resource type must be a literal name, 'class', class reference, or a resource reference.", o,
PPPackage.Literals.RESOURCE_EXPRESSION__RESOURCE_EXPR, INSIGNIFICANT_INDEX,
ISSUE__RESOURCE_BAD_TYPE_FORMAT);
// not much use checking the rest
return;
}
// -- can not virtualize/export non regular resources
if(resourceExpr instanceof VirtualNameOrReference && resourceType != RESOURCE_IS_REGULAR) {
acceptor.acceptError(
"Only regular resources can be virtual", o, PPPackage.Literals.RESOURCE_EXPRESSION__RESOURCE_EXPR,
INSIGNIFICANT_INDEX, IPPDiagnostics.ISSUE__RESOURCE_NOT_VIRTUALIZEABLE);
}
boolean onlyOneBody = resourceType == RESOURCE_IS_DEFAULT || resourceType == RESOURCE_IS_OVERRIDE;
boolean titleExpected = !onlyOneBody;
boolean attrAdditionAllowed = resourceType == RESOURCE_IS_OVERRIDE;
String errorStartText = "Resource ";
switch(resourceType) {
case RESOURCE_IS_OVERRIDE:
errorStartText = "Resource override ";
break;
case RESOURCE_IS_DEFAULT:
- errorStartText = "Reousrce defaults ";
+ errorStartText = "Resource defaults ";
break;
case RESOURCE_IS_CLASSPARAMS:
errorStartText = "Class parameter defaults ";
break;
}
// check multiple bodies
if(onlyOneBody && o.getResourceData().size() > 1)
acceptor.acceptError(
errorStartText + "can not have multiple resource instances.", o,
PPPackage.Literals.RESOURCE_EXPRESSION__RESOURCE_DATA, INSIGNIFICANT_INDEX,
ISSUE__RESOURCE_MULTIPLE_BODIES);
// rules for body:
// - should not have a title (deprecated for default, but not allowed
// for override)
// TODO: Make deprecation error optional for default
// - only override may have attribute additions
//
// check title
for(ResourceBody body : o.getResourceData()) {
boolean hasTitle = body.getNameExpr() != null; // && body.getName().length() > 0;
if(titleExpected) {
if(!hasTitle)
acceptor.acceptError(
errorStartText + "must have a title.", body, PPPackage.Literals.RESOURCE_BODY__NAME_EXPR,
INSIGNIFICANT_INDEX, IPPDiagnostics.ISSUE__RESOURCE_WITHOUT_TITLE);
else {
// TODO: Validate the expression type
}
}
else if(hasTitle) {
acceptor.acceptError(
errorStartText + " can not have a title", body, PPPackage.Literals.RESOURCE_BODY__NAME_EXPR,
INSIGNIFICANT_INDEX, IPPDiagnostics.ISSUE__RESOURCE_WITH_TITLE);
}
// ensure that only resource override has AttributeAdditions
if(!attrAdditionAllowed && body.getAttributes() != null) {
for(AttributeOperation ao : body.getAttributes().getAttributes()) {
if(ao instanceof AttributeAddition)
acceptor.acceptError(
errorStartText + " can not have attribute additions.", body,
PPPackage.Literals.RESOURCE_BODY__ATTRIBUTES,
body.getAttributes().getAttributes().indexOf(ao),
IPPDiagnostics.ISSUE__RESOURCE_WITH_ADDITIONS);
}
}
}
// --Check Resource Override (the AtExpression)
if(resourceType == RESOURCE_IS_OVERRIDE) {
if(isStandardAtExpression((AtExpression) o.getResourceExpr()))
acceptor.acceptError(
"Resource override can not be done with array/hash access", o,
PPPackage.Literals.RESOURCE_EXPRESSION__RESOURCE_EXPR, INSIGNIFICANT_INDEX,
IPPDiagnostics.ISSUE__UNSUPPORTED_EXPRESSION);
}
}
@Check
public void checkSelectorEntry(SelectorEntry o) {
Expression lhs = o.getLeftExpr();
if(!isSELECTOR_LHS(lhs))
acceptor.acceptError(
"Not an acceptable selector entry left hand side expression. Was: " + lhs.getClass().getSimpleName(),
o, PPPackage.Literals.BINARY_EXPRESSION__LEFT_EXPR, INSIGNIFICANT_INDEX,
IPPDiagnostics.ISSUE__UNSUPPORTED_EXPRESSION);
// TODO: check rhs is "rvalue"
}
@Check
public void checkSelectorExpression(SelectorExpression o) {
Expression lhs = o.getLeftExpr();
// -- non null lhs, and must be an acceptable lhs value for selector
if(lhs == null)
acceptor.acceptError(
"A selector expression must have a left expression", o,
PPPackage.Literals.PARAMETERIZED_EXPRESSION__LEFT_EXPR, INSIGNIFICANT_INDEX,
IPPDiagnostics.ISSUE__NULL_EXPRESSION);
else if(!isSELECTOR_LHS(lhs))
acceptor.acceptError(
"Not an acceptable selector left hand side expression", o,
PPPackage.Literals.PARAMETERIZED_EXPRESSION__LEFT_EXPR, INSIGNIFICANT_INDEX,
IPPDiagnostics.ISSUE__UNSUPPORTED_EXPRESSION);
// -- there must be at least one parameter
if(o.getParameters().size() < 1)
acceptor.acceptError(
"A selector expression must have at least one right side entry", o,
PPPackage.Literals.PARAMETERIZED_EXPRESSION__PARAMETERS, INSIGNIFICANT_INDEX,
IPPDiagnostics.ISSUE__NULL_EXPRESSION);
// -- all parameters must be SelectorEntry instances
for(Expression e : o.getParameters())
if(!(e instanceof SelectorEntry))
acceptor.acceptError(
"Must be a selector entry. Was:" + e.getClass().getSimpleName(), o,
PPPackage.Literals.PARAMETERIZED_EXPRESSION__PARAMETERS, o.getParameters().indexOf(e),
IPPDiagnostics.ISSUE__UNSUPPORTED_EXPRESSION);
}
@Check
public void checkShiftExpression(ShiftExpression o) {
checkOperator(o, "<<", ">>");
}
@Check
public void checkSingleQuotedString(SingleQuotedString o) {
if(!isSTRING(o.getText()))
acceptor.acceptError(
"Expected to comply with String rule", o, PPPackage.Literals.SINGLE_QUOTED_STRING__TEXT,
IPPDiagnostics.ISSUE__NOT_STRING);
String s = o.getText();
// remove all escaped \ to make it easier to find the illegal escapes
Matcher m1 = patternHelper.getRecognizedSQEscapePattern().matcher(s);
s = m1.replaceAll("");
Matcher m = patternHelper.getUnrecognizedSQEscapesPattern().matcher(s);
StringBuffer unrecognized = new StringBuffer();
while(m.find())
unrecognized.append(m.group());
if(unrecognized.length() > 0)
acceptor.acceptWarning(
"Unrecognized escape sequence(s): " + unrecognized.toString(), o,
PPPackage.Literals.SINGLE_QUOTED_STRING__TEXT, IPPDiagnostics.ISSUE__UNRECOGNIZED_ESCAPE);
}
@Check
public void checkUnaryExpression(UnaryMinusExpression o) {
if(o.getExpr() == null)
acceptor.acceptError(
"An unary minus expression must have right hand side expression", o,
PPPackage.Literals.BINARY_EXPRESSION__LEFT_EXPR, INSIGNIFICANT_INDEX,
IPPDiagnostics.ISSUE__NULL_EXPRESSION);
}
@Check
public void checkUnaryExpression(UnaryNotExpression o) {
if(o.getExpr() == null)
acceptor.acceptError(
"A not expression must have a righ hand side expression", o,
PPPackage.Literals.BINARY_EXPRESSION__LEFT_EXPR, INSIGNIFICANT_INDEX,
IPPDiagnostics.ISSUE__NULL_EXPRESSION);
}
@Check
public void checkVariableExpression(VariableExpression o) {
if(!isVARIABLE(o.getVarName()))
acceptor.acceptError(
"Expected to comply with Variable rule", o, PPPackage.Literals.VARIABLE_EXPRESSION__VAR_NAME,
INSIGNIFICANT_INDEX, IPPDiagnostics.ISSUE__NOT_VARNAME);
}
@Check
public void checkVerbatimTextExpression(VerbatimTE o) {
String s = o.getText();
if(s == null || s.length() == 0)
return;
// remove all escaped \ to make it easier to find the illegal escapes
Matcher m1 = patternHelper.getRecognizedDQEscapePattern().matcher(s);
s = m1.replaceAll("");
Matcher m = patternHelper.getUnrecognizedDQEscapesPattern().matcher(s);
StringBuffer unrecognized = new StringBuffer();
while(m.find())
unrecognized.append(m.group());
if(unrecognized.length() > 0)
acceptor.acceptWarning(
"Unrecognized escape sequence(s): " + unrecognized.toString(), o,
IPPDiagnostics.ISSUE__UNRECOGNIZED_ESCAPE);
}
/**
* NOTE: Adds validation to the puppet package (in 1.0 the package was not added
* automatically, in 2.0 it is.
*/
@Override
protected List<EPackage> getEPackages() {
List<EPackage> result = super.getEPackages();
if(!result.contains(PPPackage.eINSTANCE))
result.add(PPPackage.eINSTANCE);
return result;
}
protected boolean hasInterpolation(IQuotedString s) {
if(!(s instanceof DoubleQuotedString))
return false;
return TextExpressionHelper.hasInterpolation((DoubleQuotedString) s);
}
private void internalCheckRelationshipOperand(RelationshipExpression r, Expression o, EReference feature) {
// -- chained relationsips A -> B -> C
if(o instanceof RelationshipExpression)
return; // ok, they are chained
if(o instanceof ResourceExpression) {
// may not be a resource override
ResourceExpression re = (ResourceExpression) o;
if(re.getResourceExpr() instanceof AtExpression)
acceptor.acceptError(
"Dependency can not be defined for a resource override.", r, feature, INSIGNIFICANT_INDEX,
IPPDiagnostics.ISSUE__UNSUPPORTED_EXPRESSION);
}
else if(o instanceof AtExpression) {
// the AtExpression is validated as standard or resource reference, so only need
// to check correct form
if(isStandardAtExpression((AtExpression) o))
acceptor.acceptError(
"Dependency can not be formed for an array/hash access", r, feature, INSIGNIFICANT_INDEX,
IPPDiagnostics.ISSUE__UNSUPPORTED_EXPRESSION);
}
else if(o instanceof VirtualNameOrReference) {
acceptor.acceptError(
"Dependency can not be formed for virtual resource", r, feature, INSIGNIFICANT_INDEX,
IPPDiagnostics.ISSUE__UNSUPPORTED_EXPRESSION);
}
else if(!(o instanceof CollectExpression)) {
acceptor.acceptError(
"Dependency can not be formed for this type of expression", r, feature, INSIGNIFICANT_INDEX,
IPPDiagnostics.ISSUE__UNSUPPORTED_EXPRESSION);
}
}
protected void internalCheckRvalueExpression(EList<Expression> statements) {
for(Expression expr : statements)
internalCheckRvalueExpression(expr);
}
protected void internalCheckRvalueExpression(Expression expr) {
if(expr == null)
return;
for(Class<?> c : rvalueClasses) {
if(c.isAssignableFrom(expr.getClass()))
return;
}
acceptor.acceptError(
"Not a right hand side value. Was: " + expr.getClass().getSimpleName(), expr.eContainer(),
expr.eContainingFeature(), INSIGNIFICANT_INDEX, IPPDiagnostics.ISSUE__NOT_RVALUE);
}
protected void internalCheckTopLevelExpressions(EList<Expression> statements) {
if(statements == null || statements.size() == 0)
return;
// check that all statements are valid as top level statements
each_top: for(int i = 0; i < statements.size(); i++) {
Expression s = statements.get(i);
// -- may be a non parenthesized function call
if(s instanceof LiteralNameOrReference) {
// there must be one more expression in the list (a single argument, or
// an Expression list
// TODO: different issue, can be fixed by adding "()" if this is a function call without
// parameters.
if((i + 1) >= statements.size()) {
acceptor.acceptError(
"Not a top level expression. (Looks like a function call without arguments, use '()')",
s.eContainer(), s.eContainingFeature(), i, IPPDiagnostics.ISSUE__NOT_TOPLEVEL);
// continue each_top;
}
// the next expression is consumed as a single arg, or an expr list
// TODO: if there are expressions that can not be used as arguments check them here
i++;
continue each_top;
}
for(Class<?> c : topLevelExprClasses) {
if(c.isAssignableFrom(s.getClass()))
continue each_top;
}
acceptor.acceptError(
"Not a top level expression. Was: " + s.getClass().getSimpleName(), s.eContainer(),
s.eContainingFeature(), i, IPPDiagnostics.ISSUE__NOT_TOPLEVEL);
}
}
private boolean isCLASSNAME(String s) {
return patternHelper.isCLASSNAME(s);
}
private boolean isCLASSNAME_OR_REFERENCE(String s) {
return patternHelper.isCLASSNAME(s) || patternHelper.isCLASSREF(s) || patternHelper.isNAME(s);
}
private boolean isCLASSREF(String s) {
return patternHelper.isCLASSREF(s);
}
// NOT considered to be keywords:
// "class" - it is used when describing defaults TODO: follow up after migration to 2.0 model
private boolean isKEYWORD(String s) {
if(s == null || s.length() < 1)
return false;
for(String k : keywords)
if(k.equals(s))
return true;
return false;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.xtext.validation.AbstractInjectableValidator#isLanguageSpecific()
* ISSUE: See https://bugs.eclipse.org/bugs/show_bug.cgi?id=335624
* TODO: remove work around now that issue is fixed.
*/
@Override
public boolean isLanguageSpecific() {
// return super.isLanguageSpecific(); // when issue is fixed, or remove method
return false;
}
private boolean isNAME(String s) {
return patternHelper.isNAME(s);
}
private boolean isREGEX(String s) {
return patternHelper.isREGEXP(s);
}
/**
* Checks acceptable expression types for SELECTOR lhs
*
* @param lhs
* @return
*/
protected boolean isSELECTOR_LHS(Expression lhs) {
// the lhs can be one of:
// name, type, quotedtext, variable, funccall, boolean, undef, default, or regex.
// Or after fix of puppet issue #5515 also hash/At
if(lhs instanceof StringExpression ||
// TODO: was LiteralString follow up
lhs instanceof LiteralName || lhs instanceof LiteralNameOrReference ||
lhs instanceof VariableExpression || lhs instanceof FunctionCall || lhs instanceof LiteralBoolean ||
lhs instanceof LiteralUndef || lhs instanceof LiteralRegex || lhs instanceof LiteralDefault)
return true;
if(PuppetCompatibilityHelper.allowHashInSelector() && lhs instanceof AtExpression)
return true;
return false;
}
private boolean isStandardAtExpression(AtExpression o) {
// an At expression is standard if the lhs is a variable or an AtExpression
Expression lhs = o.getLeftExpr();
return (lhs instanceof VariableExpression || lhs instanceof AtExpression || (o.eContainer() instanceof ExpressionTE && lhs instanceof LiteralNameOrReference));
}
private boolean isSTRING(String s) {
return patternHelper.isSQSTRING(s);
}
private boolean isVARIABLE(String s) {
return patternHelper.isVARIABLE(s);
}
}
| true | true | public void checkResourceExpression(ResourceExpression o) {
// A regular resource must have a classname
// Use of class reference is deprecated
// classname : NAME | "class" | CLASSNAME
int resourceType = RESOURCE_IS_BAD; // unknown at this point
final Expression resourceExpr = o.getResourceExpr();
String resourceTypeName = null;
if(resourceExpr instanceof LiteralNameOrReference || resourceExpr instanceof VirtualNameOrReference) {
if(resourceExpr instanceof LiteralNameOrReference) {
LiteralNameOrReference resourceTypeExpr = (LiteralNameOrReference) resourceExpr;
resourceTypeName = resourceTypeExpr.getValue();
}
else {
VirtualNameOrReference vn = (VirtualNameOrReference) resourceExpr;
resourceTypeName = vn.getValue();
}
if("class".equals(resourceTypeName))
resourceType = RESOURCE_IS_CLASSPARAMS;
else if(isCLASSREF(resourceTypeName))
resourceType = RESOURCE_IS_DEFAULT;
else if(isNAME(resourceTypeName) || isCLASSNAME(resourceTypeName))
resourceType = RESOURCE_IS_REGULAR;
// else the resource is BAD
}
if(resourceExpr instanceof AtExpression) {
resourceType = RESOURCE_IS_OVERRIDE;
}
/*
* IMPORTANT: set the validated classifier to enable others to more quickly determine the type of
* resource, and its typeName (what it is a reference to).
*/
ClassifierAdapter adapter = ClassifierAdapterFactory.eINSTANCE.adapt(o);
adapter.setClassifier(resourceType);
adapter.setResourceType(null);
adapter.setResourceTypeName(resourceTypeName);
if(resourceType == RESOURCE_IS_BAD) {
acceptor.acceptError(
"Resource type must be a literal name, 'class', class reference, or a resource reference.", o,
PPPackage.Literals.RESOURCE_EXPRESSION__RESOURCE_EXPR, INSIGNIFICANT_INDEX,
ISSUE__RESOURCE_BAD_TYPE_FORMAT);
// not much use checking the rest
return;
}
// -- can not virtualize/export non regular resources
if(resourceExpr instanceof VirtualNameOrReference && resourceType != RESOURCE_IS_REGULAR) {
acceptor.acceptError(
"Only regular resources can be virtual", o, PPPackage.Literals.RESOURCE_EXPRESSION__RESOURCE_EXPR,
INSIGNIFICANT_INDEX, IPPDiagnostics.ISSUE__RESOURCE_NOT_VIRTUALIZEABLE);
}
boolean onlyOneBody = resourceType == RESOURCE_IS_DEFAULT || resourceType == RESOURCE_IS_OVERRIDE;
boolean titleExpected = !onlyOneBody;
boolean attrAdditionAllowed = resourceType == RESOURCE_IS_OVERRIDE;
String errorStartText = "Resource ";
switch(resourceType) {
case RESOURCE_IS_OVERRIDE:
errorStartText = "Resource override ";
break;
case RESOURCE_IS_DEFAULT:
errorStartText = "Reousrce defaults ";
break;
case RESOURCE_IS_CLASSPARAMS:
errorStartText = "Class parameter defaults ";
break;
}
// check multiple bodies
if(onlyOneBody && o.getResourceData().size() > 1)
acceptor.acceptError(
errorStartText + "can not have multiple resource instances.", o,
PPPackage.Literals.RESOURCE_EXPRESSION__RESOURCE_DATA, INSIGNIFICANT_INDEX,
ISSUE__RESOURCE_MULTIPLE_BODIES);
// rules for body:
// - should not have a title (deprecated for default, but not allowed
// for override)
// TODO: Make deprecation error optional for default
// - only override may have attribute additions
//
// check title
for(ResourceBody body : o.getResourceData()) {
boolean hasTitle = body.getNameExpr() != null; // && body.getName().length() > 0;
if(titleExpected) {
if(!hasTitle)
acceptor.acceptError(
errorStartText + "must have a title.", body, PPPackage.Literals.RESOURCE_BODY__NAME_EXPR,
INSIGNIFICANT_INDEX, IPPDiagnostics.ISSUE__RESOURCE_WITHOUT_TITLE);
else {
// TODO: Validate the expression type
}
}
else if(hasTitle) {
acceptor.acceptError(
errorStartText + " can not have a title", body, PPPackage.Literals.RESOURCE_BODY__NAME_EXPR,
INSIGNIFICANT_INDEX, IPPDiagnostics.ISSUE__RESOURCE_WITH_TITLE);
}
// ensure that only resource override has AttributeAdditions
if(!attrAdditionAllowed && body.getAttributes() != null) {
for(AttributeOperation ao : body.getAttributes().getAttributes()) {
if(ao instanceof AttributeAddition)
acceptor.acceptError(
errorStartText + " can not have attribute additions.", body,
PPPackage.Literals.RESOURCE_BODY__ATTRIBUTES,
body.getAttributes().getAttributes().indexOf(ao),
IPPDiagnostics.ISSUE__RESOURCE_WITH_ADDITIONS);
}
}
}
// --Check Resource Override (the AtExpression)
if(resourceType == RESOURCE_IS_OVERRIDE) {
if(isStandardAtExpression((AtExpression) o.getResourceExpr()))
acceptor.acceptError(
"Resource override can not be done with array/hash access", o,
PPPackage.Literals.RESOURCE_EXPRESSION__RESOURCE_EXPR, INSIGNIFICANT_INDEX,
IPPDiagnostics.ISSUE__UNSUPPORTED_EXPRESSION);
}
}
| public void checkResourceExpression(ResourceExpression o) {
// A regular resource must have a classname
// Use of class reference is deprecated
// classname : NAME | "class" | CLASSNAME
int resourceType = RESOURCE_IS_BAD; // unknown at this point
final Expression resourceExpr = o.getResourceExpr();
String resourceTypeName = null;
if(resourceExpr instanceof LiteralNameOrReference || resourceExpr instanceof VirtualNameOrReference) {
if(resourceExpr instanceof LiteralNameOrReference) {
LiteralNameOrReference resourceTypeExpr = (LiteralNameOrReference) resourceExpr;
resourceTypeName = resourceTypeExpr.getValue();
}
else {
VirtualNameOrReference vn = (VirtualNameOrReference) resourceExpr;
resourceTypeName = vn.getValue();
}
if("class".equals(resourceTypeName))
resourceType = RESOURCE_IS_CLASSPARAMS;
else if(isCLASSREF(resourceTypeName))
resourceType = RESOURCE_IS_DEFAULT;
else if(isNAME(resourceTypeName) || isCLASSNAME(resourceTypeName))
resourceType = RESOURCE_IS_REGULAR;
// else the resource is BAD
}
if(resourceExpr instanceof AtExpression) {
resourceType = RESOURCE_IS_OVERRIDE;
}
/*
* IMPORTANT: set the validated classifier to enable others to more quickly determine the type of
* resource, and its typeName (what it is a reference to).
*/
ClassifierAdapter adapter = ClassifierAdapterFactory.eINSTANCE.adapt(o);
adapter.setClassifier(resourceType);
adapter.setResourceType(null);
adapter.setResourceTypeName(resourceTypeName);
if(resourceType == RESOURCE_IS_BAD) {
acceptor.acceptError(
"Resource type must be a literal name, 'class', class reference, or a resource reference.", o,
PPPackage.Literals.RESOURCE_EXPRESSION__RESOURCE_EXPR, INSIGNIFICANT_INDEX,
ISSUE__RESOURCE_BAD_TYPE_FORMAT);
// not much use checking the rest
return;
}
// -- can not virtualize/export non regular resources
if(resourceExpr instanceof VirtualNameOrReference && resourceType != RESOURCE_IS_REGULAR) {
acceptor.acceptError(
"Only regular resources can be virtual", o, PPPackage.Literals.RESOURCE_EXPRESSION__RESOURCE_EXPR,
INSIGNIFICANT_INDEX, IPPDiagnostics.ISSUE__RESOURCE_NOT_VIRTUALIZEABLE);
}
boolean onlyOneBody = resourceType == RESOURCE_IS_DEFAULT || resourceType == RESOURCE_IS_OVERRIDE;
boolean titleExpected = !onlyOneBody;
boolean attrAdditionAllowed = resourceType == RESOURCE_IS_OVERRIDE;
String errorStartText = "Resource ";
switch(resourceType) {
case RESOURCE_IS_OVERRIDE:
errorStartText = "Resource override ";
break;
case RESOURCE_IS_DEFAULT:
errorStartText = "Resource defaults ";
break;
case RESOURCE_IS_CLASSPARAMS:
errorStartText = "Class parameter defaults ";
break;
}
// check multiple bodies
if(onlyOneBody && o.getResourceData().size() > 1)
acceptor.acceptError(
errorStartText + "can not have multiple resource instances.", o,
PPPackage.Literals.RESOURCE_EXPRESSION__RESOURCE_DATA, INSIGNIFICANT_INDEX,
ISSUE__RESOURCE_MULTIPLE_BODIES);
// rules for body:
// - should not have a title (deprecated for default, but not allowed
// for override)
// TODO: Make deprecation error optional for default
// - only override may have attribute additions
//
// check title
for(ResourceBody body : o.getResourceData()) {
boolean hasTitle = body.getNameExpr() != null; // && body.getName().length() > 0;
if(titleExpected) {
if(!hasTitle)
acceptor.acceptError(
errorStartText + "must have a title.", body, PPPackage.Literals.RESOURCE_BODY__NAME_EXPR,
INSIGNIFICANT_INDEX, IPPDiagnostics.ISSUE__RESOURCE_WITHOUT_TITLE);
else {
// TODO: Validate the expression type
}
}
else if(hasTitle) {
acceptor.acceptError(
errorStartText + " can not have a title", body, PPPackage.Literals.RESOURCE_BODY__NAME_EXPR,
INSIGNIFICANT_INDEX, IPPDiagnostics.ISSUE__RESOURCE_WITH_TITLE);
}
// ensure that only resource override has AttributeAdditions
if(!attrAdditionAllowed && body.getAttributes() != null) {
for(AttributeOperation ao : body.getAttributes().getAttributes()) {
if(ao instanceof AttributeAddition)
acceptor.acceptError(
errorStartText + " can not have attribute additions.", body,
PPPackage.Literals.RESOURCE_BODY__ATTRIBUTES,
body.getAttributes().getAttributes().indexOf(ao),
IPPDiagnostics.ISSUE__RESOURCE_WITH_ADDITIONS);
}
}
}
// --Check Resource Override (the AtExpression)
if(resourceType == RESOURCE_IS_OVERRIDE) {
if(isStandardAtExpression((AtExpression) o.getResourceExpr()))
acceptor.acceptError(
"Resource override can not be done with array/hash access", o,
PPPackage.Literals.RESOURCE_EXPRESSION__RESOURCE_EXPR, INSIGNIFICANT_INDEX,
IPPDiagnostics.ISSUE__UNSUPPORTED_EXPRESSION);
}
}
|
diff --git a/src/no/HiOAProsjektV2013/Main/Person.java b/src/no/HiOAProsjektV2013/Main/Person.java
index 5dd0152..faeb95f 100644
--- a/src/no/HiOAProsjektV2013/Main/Person.java
+++ b/src/no/HiOAProsjektV2013/Main/Person.java
@@ -1,44 +1,44 @@
package no.HiOAProsjektV2013.Main;
public class Person {
private String fNavn, eNavn = null, epost;
private int telefonNr;
//variable for posisjon i string-arrayen av navn
private final int FORNAVN = 0, ETTERNAVN = -1, KUNETNAVNSKREVET = 1;
public Person(String navn, String epost, int tlf){
nameSplitter(navn);
this.epost = epost;
telefonNr = tlf;
}
//Metoden gjør at vi tar inn kun en string som input, men outputter første og siste navn
//som fornavn og etternavn i Person
private void nameSplitter(String navn){
String regex = "\\s";
String[] alleNavn = navn.split(regex);
this.fNavn = alleNavn[FORNAVN];
- if(alleNavn.length <= KUNETNAVNSKREVET)
+ if(alleNavn.length >= KUNETNAVNSKREVET)
this.eNavn = alleNavn[alleNavn.length + ETTERNAVN];
}
public int getTelefonNr() {
return telefonNr;
}
public String getEpost(){
return epost;
}
public String getfNavn() {
return fNavn;
}
public String geteNavn() {
return eNavn;
}
}
| true | true | private void nameSplitter(String navn){
String regex = "\\s";
String[] alleNavn = navn.split(regex);
this.fNavn = alleNavn[FORNAVN];
if(alleNavn.length <= KUNETNAVNSKREVET)
this.eNavn = alleNavn[alleNavn.length + ETTERNAVN];
}
| private void nameSplitter(String navn){
String regex = "\\s";
String[] alleNavn = navn.split(regex);
this.fNavn = alleNavn[FORNAVN];
if(alleNavn.length >= KUNETNAVNSKREVET)
this.eNavn = alleNavn[alleNavn.length + ETTERNAVN];
}
|
diff --git a/src/java/com/scratchdisk/util/EnumUtils.java b/src/java/com/scratchdisk/util/EnumUtils.java
index 79a5cdbe..fe779ad1 100644
--- a/src/java/com/scratchdisk/util/EnumUtils.java
+++ b/src/java/com/scratchdisk/util/EnumUtils.java
@@ -1,73 +1,78 @@
/*
* Scriptographer
*
* This file is part of Scriptographer, a Plugin for Adobe Illustrator.
*
* Copyright (c) 2002-2010 Juerg Lehni, http://www.scratchdisk.com.
* All rights reserved.
*
* Please visit http://scriptographer.org/ for updates and contact.
*
* -- GPL LICENSE NOTICE --
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
* -- GPL LICENSE NOTICE --
*
* File created on Aug 14, 2009.
*
* $Id$
*/
package com.scratchdisk.util;
import java.util.Arrays;
import java.util.Collection;
import java.util.EnumSet;
import java.util.Iterator;
/**
* @author lehni
*
*/
public class EnumUtils {
protected EnumUtils() {
}
/**
* An alternative to EnumSet.copyOf, with the addition to filter out null
* values.
*/
public static <E extends Enum<E>> EnumSet<E> asSet(Collection<E> list) {
if (list instanceof EnumSet) {
return ((EnumSet<E>)list).clone();
} else {
- Iterator<E> i = list.iterator();
- E first = i.next();
- while (first == null)
- first = i.next();
- EnumSet<E> result = EnumSet.of(first);
- while (i.hasNext()) {
- E next = i.next();
- if (next != null)
- result.add(next);
+ Iterator<E> it = list.iterator();
+ if (it.hasNext()) {
+ E first = it.next();
+ while (first == null && it.hasNext())
+ first = it.next();
+ if (first != null) {
+ EnumSet<E> result = EnumSet.of(first);
+ while (it.hasNext()) {
+ E next = it.next();
+ if (next != null)
+ result.add(next);
+ }
+ return result;
+ }
}
- return result;
+ return null;
}
}
public static <E extends Enum<E>> EnumSet<E> asSet(E[] array) {
return array != null ? asSet(Arrays.asList(array)) : null;
}
}
| false | true | public static <E extends Enum<E>> EnumSet<E> asSet(Collection<E> list) {
if (list instanceof EnumSet) {
return ((EnumSet<E>)list).clone();
} else {
Iterator<E> i = list.iterator();
E first = i.next();
while (first == null)
first = i.next();
EnumSet<E> result = EnumSet.of(first);
while (i.hasNext()) {
E next = i.next();
if (next != null)
result.add(next);
}
return result;
}
}
| public static <E extends Enum<E>> EnumSet<E> asSet(Collection<E> list) {
if (list instanceof EnumSet) {
return ((EnumSet<E>)list).clone();
} else {
Iterator<E> it = list.iterator();
if (it.hasNext()) {
E first = it.next();
while (first == null && it.hasNext())
first = it.next();
if (first != null) {
EnumSet<E> result = EnumSet.of(first);
while (it.hasNext()) {
E next = it.next();
if (next != null)
result.add(next);
}
return result;
}
}
return null;
}
}
|
diff --git a/src/main/java/fr/adhoc/leboncoin/model/Utilisateur.java b/src/main/java/fr/adhoc/leboncoin/model/Utilisateur.java
index 2ee9388..3c2ff14 100644
--- a/src/main/java/fr/adhoc/leboncoin/model/Utilisateur.java
+++ b/src/main/java/fr/adhoc/leboncoin/model/Utilisateur.java
@@ -1,86 +1,87 @@
package fr.adhoc.leboncoin.model;
import java.util.Set;
public class Utilisateur {
private int U_ID;
private String nom;
private String mail;
private float note;
private Set<Offre> listeOffres;
private Set<Produit> listeProduits;
//------------------------------------------------------
// Constructeurs
//------------------------------------------------------
public Utilisateur() {
// TODO Auto-generated constructor stub
}
public Utilisateur(String nom, String mail) {
super();
this.nom = nom;
this.mail = mail;
+ this.note = (float) nom.charAt(0) - (float) 'A' +1;
}
//------------------------------------------------------
// Get/Set
//------------------------------------------------------
public int getID() {
return U_ID;
}
public void setID(int iD) {
U_ID = iD;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getMail() {
return mail;
}
public void setMail(String mail) {
this.mail = mail;
}
public float getNote() {
return note;
}
public void setNote(float note) {
this.note = note;
}
public Set<Offre> getListeOffres() {
return listeOffres;
}
public void setListeOffres(Set<Offre> listeOffres) {
this.listeOffres = listeOffres;
}
public Set<Produit> getListeProduits() {
return listeProduits;
}
public void setListeProduits(Set<Produit> listeProduits) {
this.listeProduits = listeProduits;
}
}
| true | true | public Utilisateur(String nom, String mail) {
super();
this.nom = nom;
this.mail = mail;
}
| public Utilisateur(String nom, String mail) {
super();
this.nom = nom;
this.mail = mail;
this.note = (float) nom.charAt(0) - (float) 'A' +1;
}
|
diff --git a/src/contrib/gridmix/src/java/org/apache/hadoop/mapred/gridmix/Statistics.java b/src/contrib/gridmix/src/java/org/apache/hadoop/mapred/gridmix/Statistics.java
index 92a1e97445..6d8c166a67 100644
--- a/src/contrib/gridmix/src/java/org/apache/hadoop/mapred/gridmix/Statistics.java
+++ b/src/contrib/gridmix/src/java/org/apache/hadoop/mapred/gridmix/Statistics.java
@@ -1,322 +1,323 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.mapred.gridmix;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.mapred.ClusterStatus;
import org.apache.hadoop.mapred.JobClient;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.gridmix.Gridmix.Component;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.tools.rumen.JobStory;
import java.io.IOException;
import java.security.PrivilegedExceptionAction;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
/**
* Component collecting the stats required by other components
* to make decisions.
* Single thread Collector tries to collec the stats.
* Each of thread poll updates certain datastructure(Currently ClusterStats).
* Components interested in these datastructure, need to register.
* StatsCollector notifies each of the listeners.
*/
public class Statistics implements Component<Job> {
public static final Log LOG = LogFactory.getLog(Statistics.class);
private final StatCollector statistics = new StatCollector();
private JobClient cluster;
//List of cluster status listeners.
private final List<StatListener<ClusterStats>> clusterStatlisteners =
new CopyOnWriteArrayList<StatListener<ClusterStats>>();
//List of job status listeners.
private final List<StatListener<JobStats>> jobStatListeners =
new CopyOnWriteArrayList<StatListener<JobStats>>();
//List of jobids and noofMaps for each job
private static final Map<Integer, JobStats> jobMaps =
new ConcurrentHashMap<Integer,JobStats>();
private int completedJobsInCurrentInterval = 0;
private final int jtPollingInterval;
private volatile boolean shutdown = false;
private final int maxJobCompletedInInterval;
private static final String MAX_JOBS_COMPLETED_IN_POLL_INTERVAL_KEY =
"gridmix.max-jobs-completed-in-poll-interval";
private final ReentrantLock lock = new ReentrantLock();
private final Condition jobCompleted = lock.newCondition();
private final CountDownLatch startFlag;
public Statistics(
final Configuration conf, int pollingInterval, CountDownLatch startFlag)
throws IOException, InterruptedException {
UserGroupInformation ugi = UserGroupInformation.getLoginUser();
this.cluster = ugi.doAs(new PrivilegedExceptionAction<JobClient>() {
public JobClient run() throws IOException {
return new JobClient(new JobConf(conf));
}
});
this.jtPollingInterval = pollingInterval;
maxJobCompletedInInterval = conf.getInt(
MAX_JOBS_COMPLETED_IN_POLL_INTERVAL_KEY, 1);
this.startFlag = startFlag;
}
public void addJobStats(Job job, JobStory jobdesc) {
int seq = GridmixJob.getJobSeqId(job);
if (seq < 0) {
LOG.info("Not tracking job " + job.getJobName()
+ " as seq id is less than zero: " + seq);
return;
}
int maps = 0;
if (jobdesc == null) {
throw new IllegalArgumentException(
" JobStory not available for job " + job.getJobName());
} else {
maps = jobdesc.getNumberMaps();
}
JobStats stats = new JobStats(maps,job);
jobMaps.put(seq,stats);
}
/**
* Used by JobMonitor to add the completed job.
*/
@Override
public void add(Job job) {
//This thread will be notified initially by jobmonitor incase of
//data generation. Ignore that as we are getting once the input is
//generated.
if (!statistics.isAlive()) {
return;
}
JobStats stat = jobMaps.remove(GridmixJob.getJobSeqId(job));
if (stat == null) return;
completedJobsInCurrentInterval++;
//check if we have reached the maximum level of job completions.
if (completedJobsInCurrentInterval >= maxJobCompletedInInterval) {
if (LOG.isDebugEnabled()) {
LOG.debug(
" Reached maximum limit of jobs in a polling interval " +
completedJobsInCurrentInterval);
}
completedJobsInCurrentInterval = 0;
lock.lock();
try {
//Job is completed notify all the listeners.
for (StatListener<JobStats> l : jobStatListeners) {
l.update(stat);
}
this.jobCompleted.signalAll();
} finally {
lock.unlock();
}
}
}
//TODO: We have just 2 types of listeners as of now . If no of listeners
//increase then we should move to map kind of model.
public void addClusterStatsObservers(StatListener<ClusterStats> listener) {
clusterStatlisteners.add(listener);
}
public void addJobStatsListeners(StatListener<JobStats> listener) {
this.jobStatListeners.add(listener);
}
/**
* Attempt to start the service.
*/
@Override
public void start() {
statistics.start();
}
private class StatCollector extends Thread {
StatCollector() {
super("StatsCollectorThread");
}
public void run() {
try {
startFlag.await();
if (Thread.currentThread().isInterrupted()) {
return;
}
} catch (InterruptedException ie) {
LOG.error(
"Statistics Error while waiting for other threads to get ready ", ie);
return;
}
while (!shutdown) {
lock.lock();
try {
jobCompleted.await(jtPollingInterval, TimeUnit.MILLISECONDS);
} catch (InterruptedException ie) {
- LOG.error(
- "Statistics interrupt while waiting for polling " + ie.getCause(),
- ie);
+ if (!shutdown) {
+ LOG.error("Statistics interrupt while waiting for completion of "
+ + "a job.", ie);
+ }
return;
} finally {
lock.unlock();
}
//Fetch cluster data only if required.i.e .
// only if there are clusterStats listener.
if (clusterStatlisteners.size() > 0) {
try {
ClusterStatus clusterStatus = cluster.getClusterStatus();
updateAndNotifyClusterStatsListeners(clusterStatus);
} catch (IOException e) {
LOG.error(
"Statistics io exception while polling JT ", e);
return;
}
}
}
}
private void updateAndNotifyClusterStatsListeners(
ClusterStatus clusterStatus) {
ClusterStats stats = ClusterStats.getClusterStats();
stats.setClusterMetric(clusterStatus);
for (StatListener<ClusterStats> listener : clusterStatlisteners) {
listener.update(stats);
}
}
}
/**
* Wait until the service completes. It is assumed that either a
* {@link #shutdown} or {@link #abort} has been requested.
*/
@Override
public void join(long millis) throws InterruptedException {
statistics.join(millis);
}
@Override
public void shutdown() {
shutdown = true;
jobMaps.clear();
clusterStatlisteners.clear();
jobStatListeners.clear();
statistics.interrupt();
}
@Override
public void abort() {
shutdown = true;
jobMaps.clear();
clusterStatlisteners.clear();
jobStatListeners.clear();
statistics.interrupt();
}
/**
* Class to encapsulate the JobStats information.
* Current we just need information about completedJob.
* TODO: In future we need to extend this to send more information.
*/
static class JobStats {
private int noOfMaps;
private Job job;
public JobStats(int noOfMaps,Job job){
this.job = job;
this.noOfMaps = noOfMaps;
}
public int getNoOfMaps() {
return noOfMaps;
}
/**
* Returns the job ,
* We should not use job.getJobID it returns null in 20.1xx.
* Use (GridmixJob.getJobSeqId(job)) instead
* @return job
*/
public Job getJob() {
return job;
}
}
static class ClusterStats {
private ClusterStatus status = null;
private static ClusterStats stats = new ClusterStats();
private ClusterStats() {
}
/**
* @return stats
*/
static ClusterStats getClusterStats() {
return stats;
}
/**
* @param metrics
*/
void setClusterMetric(ClusterStatus metrics) {
this.status = metrics;
}
/**
* @return metrics
*/
public ClusterStatus getStatus() {
return status;
}
int getNumRunningJob() {
return jobMaps.size();
}
/**
* @return runningWatitingJobs
*/
static Collection<JobStats> getRunningJobStats() {
return jobMaps.values();
}
}
}
| true | true | public void run() {
try {
startFlag.await();
if (Thread.currentThread().isInterrupted()) {
return;
}
} catch (InterruptedException ie) {
LOG.error(
"Statistics Error while waiting for other threads to get ready ", ie);
return;
}
while (!shutdown) {
lock.lock();
try {
jobCompleted.await(jtPollingInterval, TimeUnit.MILLISECONDS);
} catch (InterruptedException ie) {
LOG.error(
"Statistics interrupt while waiting for polling " + ie.getCause(),
ie);
return;
} finally {
lock.unlock();
}
//Fetch cluster data only if required.i.e .
// only if there are clusterStats listener.
if (clusterStatlisteners.size() > 0) {
try {
ClusterStatus clusterStatus = cluster.getClusterStatus();
updateAndNotifyClusterStatsListeners(clusterStatus);
} catch (IOException e) {
LOG.error(
"Statistics io exception while polling JT ", e);
return;
}
}
}
}
| public void run() {
try {
startFlag.await();
if (Thread.currentThread().isInterrupted()) {
return;
}
} catch (InterruptedException ie) {
LOG.error(
"Statistics Error while waiting for other threads to get ready ", ie);
return;
}
while (!shutdown) {
lock.lock();
try {
jobCompleted.await(jtPollingInterval, TimeUnit.MILLISECONDS);
} catch (InterruptedException ie) {
if (!shutdown) {
LOG.error("Statistics interrupt while waiting for completion of "
+ "a job.", ie);
}
return;
} finally {
lock.unlock();
}
//Fetch cluster data only if required.i.e .
// only if there are clusterStats listener.
if (clusterStatlisteners.size() > 0) {
try {
ClusterStatus clusterStatus = cluster.getClusterStatus();
updateAndNotifyClusterStatsListeners(clusterStatus);
} catch (IOException e) {
LOG.error(
"Statistics io exception while polling JT ", e);
return;
}
}
}
}
|
diff --git a/src/fr/gcastel/freeboxV6GeekIncDownloader/ProgressTask.java b/src/fr/gcastel/freeboxV6GeekIncDownloader/ProgressTask.java
index 75ab2a9..63ebd17 100644
--- a/src/fr/gcastel/freeboxV6GeekIncDownloader/ProgressTask.java
+++ b/src/fr/gcastel/freeboxV6GeekIncDownloader/ProgressTask.java
@@ -1,205 +1,213 @@
/*
Copyright 2011 Gerben CASTEL
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package fr.gcastel.freeboxV6GeekIncDownloader;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import fr.gcastel.freeboxV6GeekIncDownloader.services.GeekIncLogoDownloadService;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
/**
* La classe de notre t�che asynchrone
* de chargement du flux RSS
*
* @author Gerben
*/
public class ProgressTask extends AsyncTask<Void, Void, Void> {
private GeekIncRssListActivity activity = null;
private ProgressDialog dialog = null;
private int progress = 0;
private String fluxRSS = null;
private List<PodcastElement> podcastElements;
private final String logoDataPath;
private final String logoFileName;
/**
* Le constructeur principal
*
* @param activity l'activit� li�e
*/
ProgressTask(GeekIncRssListActivity activity) {
super();
dialog = activity.dialog;
logoDataPath = activity.getString(R.string.dataPath);
logoFileName = activity.getString(R.string.geekIncLogoFileName);
attach(activity);
}
/**
* M�thode effectuant la recherche du flux RSS
*
* @throws Exception
* en cas de probl�mes
*/
private void fetchFluxRSS() throws Exception {
// R�cup�ration du flux RSS
StringBuilder fluxRssStringBuilder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(
activity.getString(R.string.geekIncRSSFeedURL));
HttpResponse response = client.execute(request);
// Traitement de la r�ponse
InputStream repStream = response.getEntity().getContent();
BufferedReader repReader = new BufferedReader(new InputStreamReader(
repStream));
String line = null;
while ((line = repReader.readLine()) != null) {
fluxRssStringBuilder.append(line);
fluxRssStringBuilder.append('\n');
}
repReader.close();
repStream.close();
fluxRSS = fluxRssStringBuilder.toString();
}
/**
* M�thode retournant l'url du logo GeekInc On ne fait pas de parsing XML
* complet, c'est trop couteux
*
* @return l'url trouv�e
*/
private String getGeekIncLogoURL() {
// On cherche <channel> puis <image> puis <url></url>
int indexChannel = fluxRSS.indexOf("<channel>");
int indexImage = fluxRSS.indexOf("<image>", indexChannel + 1);
int indexURL = fluxRSS.indexOf("<url>", indexImage + 1);
// Extraction jusqu'� </url>
return fluxRSS.substring(indexURL + 5,
fluxRSS.indexOf("</url>", indexURL));
}
/*
* C'est ici qu'on fait le requ�tage du flux RSS GeekInc
*/
@Override
protected Void doInBackground(Void... unused) {
// R�cup�ration du flux RSS
try {
fetchFluxRSS();
} catch (Exception ex) {
Log.w("ProgressTask", "HTTP request error");
return (null);
}
progress += 40;
publishProgress();
// Parsing
- String logoURL = getGeekIncLogoURL();
+ String logoURL = null;
+ try {
+ logoURL = getGeekIncLogoURL();
+ } catch (Exception ex) {
+ Log.w("ProgressTask", "HTTP request error when getting logo");
+ return (null);
+ }
progress += 10;
publishProgress();
// R�cup�ration du logo GeekInc
- Log.i("ProgressTask", "URL trouv�e : " + logoURL);
- GeekIncLogoDownloadService downService = new GeekIncLogoDownloadService(
+ if (logoURL != null) {
+ Log.i("ProgressTask", "URL trouv�e : " + logoURL);
+ GeekIncLogoDownloadService downService = new GeekIncLogoDownloadService(
logoURL, logoDataPath + logoFileName);
- try {
- downService.download();
- } catch (Exception ex) {
- Log.w("ProgressTask", "HTTP download error " + ex.getMessage());
- return (null);
+ try {
+ downService.download();
+ } catch (Exception ex) {
+ Log.w("ProgressTask", "HTTP download error " + ex.getMessage());
+ return (null);
+ }
}
progress += 30;
publishProgress();
// Parsing du flux RSS pour g�n�rer les liens
progress += 20;
GeekIncRSSParserService parser = new GeekIncRSSParserService(fluxRSS);
podcastElements = parser.getPodcastElements();
publishProgress();
return (null);
}
@Override
protected void onProgressUpdate(Void... unused) {
if (activity != null) {
activity.updateProgress(getProgress(), podcastElements, fluxRSS);
} else {
Log.w("ProgressTask", "onProgressUpdate skipped, no activity");
}
}
@Override
protected void onPostExecute(Void unused) {
if (activity != null) {
if (fluxRSS != null) {
Toast.makeText(activity, "Donn�es � jour !", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(activity,
"Impossible de r�cup�rer le flux RSS de GeekInc HD !",
Toast.LENGTH_SHORT).show();
if (activity.dialog != null) {
activity.dialog.hide();
}
}
} else {
Log.w("ProgressTask", "onPostExecute skipped, no activity");
}
}
void detach() {
dialog = activity.dialog;
activity = null;
}
protected void attach(GeekIncRssListActivity inActivity) {
activity = inActivity;
activity.dialog = dialog;
}
public int getProgress() {
return progress;
}
public List<PodcastElement> getPodcastElements() {
return podcastElements;
}
public String getFluxRSS() {
return fluxRSS;
}
}
| false | true | protected Void doInBackground(Void... unused) {
// R�cup�ration du flux RSS
try {
fetchFluxRSS();
} catch (Exception ex) {
Log.w("ProgressTask", "HTTP request error");
return (null);
}
progress += 40;
publishProgress();
// Parsing
String logoURL = getGeekIncLogoURL();
progress += 10;
publishProgress();
// R�cup�ration du logo GeekInc
Log.i("ProgressTask", "URL trouv�e : " + logoURL);
GeekIncLogoDownloadService downService = new GeekIncLogoDownloadService(
logoURL, logoDataPath + logoFileName);
try {
downService.download();
} catch (Exception ex) {
Log.w("ProgressTask", "HTTP download error " + ex.getMessage());
return (null);
}
progress += 30;
publishProgress();
// Parsing du flux RSS pour g�n�rer les liens
progress += 20;
GeekIncRSSParserService parser = new GeekIncRSSParserService(fluxRSS);
podcastElements = parser.getPodcastElements();
publishProgress();
return (null);
}
| protected Void doInBackground(Void... unused) {
// R�cup�ration du flux RSS
try {
fetchFluxRSS();
} catch (Exception ex) {
Log.w("ProgressTask", "HTTP request error");
return (null);
}
progress += 40;
publishProgress();
// Parsing
String logoURL = null;
try {
logoURL = getGeekIncLogoURL();
} catch (Exception ex) {
Log.w("ProgressTask", "HTTP request error when getting logo");
return (null);
}
progress += 10;
publishProgress();
// R�cup�ration du logo GeekInc
if (logoURL != null) {
Log.i("ProgressTask", "URL trouv�e : " + logoURL);
GeekIncLogoDownloadService downService = new GeekIncLogoDownloadService(
logoURL, logoDataPath + logoFileName);
try {
downService.download();
} catch (Exception ex) {
Log.w("ProgressTask", "HTTP download error " + ex.getMessage());
return (null);
}
}
progress += 30;
publishProgress();
// Parsing du flux RSS pour g�n�rer les liens
progress += 20;
GeekIncRSSParserService parser = new GeekIncRSSParserService(fluxRSS);
podcastElements = parser.getPodcastElements();
publishProgress();
return (null);
}
|
diff --git a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/full/AllTests.java b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/full/AllTests.java
index 00f1b472e..7add26707 100644
--- a/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/full/AllTests.java
+++ b/bundles/org.eclipse.equinox.p2.tests/src/org/eclipse/equinox/p2/tests/full/AllTests.java
@@ -1,28 +1,28 @@
/*******************************************************************************
* Copyright (c) 2007, 2009 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.equinox.p2.tests.full;
import junit.framework.*;
/**
* Performs all automated download manager tests.
*/
public class AllTests extends TestCase {
public static Test suite() {
TestSuite suite = new TestSuite(AllTests.class.getName());
suite.addTestSuite(End2EndTest.class);
- suite.addTest(From35to36.suite());
- suite.addTest(Install36from35.suite());
+ // suite.addTest(From35to36.suite());
+ // suite.addTest(Install36from35.suite());
return suite;
}
}
| true | true | public static Test suite() {
TestSuite suite = new TestSuite(AllTests.class.getName());
suite.addTestSuite(End2EndTest.class);
suite.addTest(From35to36.suite());
suite.addTest(Install36from35.suite());
return suite;
}
| public static Test suite() {
TestSuite suite = new TestSuite(AllTests.class.getName());
suite.addTestSuite(End2EndTest.class);
// suite.addTest(From35to36.suite());
// suite.addTest(Install36from35.suite());
return suite;
}
|
diff --git a/src/uk/co/quartzcraft/kingdoms/QuartzKingdoms.java b/src/uk/co/quartzcraft/kingdoms/QuartzKingdoms.java
index f6cf9f7..c453037 100644
--- a/src/uk/co/quartzcraft/kingdoms/QuartzKingdoms.java
+++ b/src/uk/co/quartzcraft/kingdoms/QuartzKingdoms.java
@@ -1,126 +1,126 @@
package uk.co.quartzcraft.kingdoms;
import java.sql.Connection;
import java.util.Arrays;
import java.util.logging.Logger;
import com.sun.tools.javac.util.List;
import org.bukkit.Bukkit;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
import uk.co.quartzcraft.core.QuartzCore;
import uk.co.quartzcraft.core.chat.ChatPhrase;
import uk.co.quartzcraft.core.database.MySQL;
import uk.co.quartzcraft.kingdoms.command.*;
import uk.co.quartzcraft.kingdoms.listeners.*;
public class QuartzKingdoms extends JavaPlugin {
public Plugin plugin = this.plugin;
public static final Logger log = Logger.getLogger("Minecraft");
public static String releaseVersion = QuartzCore.displayReleaseVersion();
public static Connection DBKing = null;
public static MySQL MySQLking = null;
@Override
public void onDisable() {
//Shutdown notice
log.info("[QK]The QuartzKingdoms Plugin has been disabled!");
}
@Override
public void onEnable() {
log.info("[QC]Running plugin configuration");
this.saveDefaultConfig();
String SQLKingHost = this.getConfig().getString("database.kingdoms.host");
String SQLKingDatabase = this.getConfig().getString("database.kingdoms.database");
String SQLKingUser = this.getConfig().getString("database.kingdoms.username");
String SQLKingPassword = this.getConfig().getString("database.kingdoms.password");
MySQLking = new MySQL(plugin, SQLKingHost, "3306", SQLKingDatabase, SQLKingUser, SQLKingPassword);
//Phrases
log.info("[QK][STARTUP]Creating Phrases");
ChatPhrase.addPhrase("kingdom_name_single_word", "&cA kingdoms name may only be a single word!");
ChatPhrase.addPhrase("created_kingdom_yes", "&aSuccessfully created kingdom: ");
ChatPhrase.addPhrase("created_kingdom_no", "&cFailed to create kingdom: ");
ChatPhrase.addPhrase("deleted_kingdom_yes", "&aSuccessfully deleted kingdom: ");
ChatPhrase.addPhrase("deleted_kingdom_no", "&cFailed to delete kingdom: ");
ChatPhrase.addPhrase("specify_kingdom_name", "&cPlease specify a name!");
ChatPhrase.addPhrase("kingdomname_already_used", "&cAnother kingdom is using that name! &aConsider using a different name and overtaking that kingdom!");
ChatPhrase.addPhrase("info_kingdom", "&bInfo on Kingdom: ");
ChatPhrase.addPhrase("chunk_claimed_for_kingdom_yes", "&aChunk successfully claimed for Kingdom: ");
ChatPhrase.addPhrase("chunk_claimed_for_kingdom_no", "&aChunk was not successfully claimed for Kingdom: ");
ChatPhrase.addPhrase("chunk_unclaimed_for_kingdom_yes", "&aChunk successfully unclaimed for Kingdom: ");
ChatPhrase.addPhrase("chunk_unclaimed_for_kingdom_no", "&aChunk was not successfully unclaimed for Kingdom: ");
ChatPhrase.addPhrase("now_entering_the_land_of", "&aNow entering the land of ");
ChatPhrase.addPhrase("now_leaving_the_land_of", "&aNow entering the land of ");
ChatPhrase.addPhrase("got_promoted_kingdom_yes", "&aYou were moved group by your king!");
ChatPhrase.addPhrase("you_must_be_member_kingdom", "&cYou must be a member of a kingdom!");
ChatPhrase.addPhrase("you_must_be_member_kingdom_leave", "&cYou must be a member of a kingdom to leave one!");
ChatPhrase.addPhrase("you_are_already_in_a_Kingdom", "&cYou are already a member of a kingdom!");
ChatPhrase.addPhrase("successfully_joined_kingdom_X", "&aSuccessfully joined the kingdom ");
ChatPhrase.addPhrase("failed_join_kingdom", "&cFailed to join the specified kingdom. Please check that it is not invite only.");
ChatPhrase.addPhrase("successfully_left_kingdom_X", "&aSuccessfully left the kingdom ");
ChatPhrase.addPhrase("failed_leave_kingdom", "&cFailed to leave the specified kingdom.");
ChatPhrase.addPhrase("kingdom_already_open", " &cThe kingdom is already open!");
ChatPhrase.addPhrase("kingdom_now_open", " &aYour kingdom is now open!");
ChatPhrase.addPhrase("failed_open_kingdom", " &cFailed to open the kingdom!");
ChatPhrase.addPhrase("kingdom_already_closed", " &cThe kingdom is already closed!");
ChatPhrase.addPhrase("kingdom_now_closed", " &aYour kingdom is now closed!");
ChatPhrase.addPhrase("failed_close_kingdom", " &cFailed to close the kingdom!");
ChatPhrase.addPhrase("kingdom_is_now_at_war_with_kingdom", " &cis now at war with ");
ChatPhrase.addPhrase("kingdom_is_now_allied_with_kingdom", " &ais now allied with ");
ChatPhrase.addPhrase("kingdom_is_now_neutral_relationship_with_kingdom", " &6is now in a neutral relationship with ");
ChatPhrase.addPhrase("failed_to_ally_with_kingdom", "&cFailed to become an ally with ");
ChatPhrase.addPhrase("failed_to_neutral_with_kingdom", "&cFailed to become neutral with ");
ChatPhrase.addPhrase("failed_to_war_with_kingdom", "&cFailed to go to war with ");
- ChatPhrase.addPhrase("could_not_create_kingdoms_player", "&cYou're playerdata could not be added to the QuartzKingdoms database!");
+ ChatPhrase.addPhrase("could_not_create_kingdoms_player", "&cYour player data could not be added to the QuartzKingdoms database!");
//Database
//logger.info("[STARTUP]Connecting to Database");
DBKing = MySQLking.openConnection();
//Listeners
log.info("[QK][STARTUP]Registering Listeners");
//getServer().getPluginManager().registerEvents(new BlockListener(), this);
new BlockListener(this);
new PlayerCreationListener(this);
new PlayerMoveListener(this);
//Commands
log.info("[QK][STARTUP]Registering Commands");
getCommand("kingdom").setExecutor(new CommandKingdom());
CommandKingdom.addCommand(Arrays.asList("info"), new KingdomInfoSubCommand());
CommandKingdom.addCommand(Arrays.asList("create"), new KingdomCreateSubCommand());
CommandKingdom.addCommand(Arrays.asList("delete"), new KingdomDeleteSubCommand());
CommandKingdom.addCommand(Arrays.asList("promote"), new KingdomPromoteSubCommand());
CommandKingdom.addCommand(Arrays.asList("claim"), new KingdomClaimSubCommand());
CommandKingdom.addCommand(Arrays.asList("unclaim"), new KingdomUnClaimSubCommand());
CommandKingdom.addCommand(Arrays.asList("war"), new KingdomWarSubCommand());
CommandKingdom.addCommand(Arrays.asList("ally"), new KingdomAllySubCommand());
CommandKingdom.addCommand(Arrays.asList("neutral"), new KingdomNeutralSubCommand());
CommandKingdom.addCommand(Arrays.asList("join"), new KingdomJoinSubCommand());
CommandKingdom.addCommand(Arrays.asList("leave"), new KingdomJoinSubCommand());
CommandKingdom.addCommand(Arrays.asList("open"), new KingdomOpenSubCommand());
CommandKingdom.addCommand(Arrays.asList("close"), new KingdomOpenSubCommand());
//Startup notice
log.info("[QK]The QuartzKingdoms Plugin has been enabled!");
log.info("[QK]Compiled using QuartzCore version " + releaseVersion);
}
}
| true | true | public void onEnable() {
log.info("[QC]Running plugin configuration");
this.saveDefaultConfig();
String SQLKingHost = this.getConfig().getString("database.kingdoms.host");
String SQLKingDatabase = this.getConfig().getString("database.kingdoms.database");
String SQLKingUser = this.getConfig().getString("database.kingdoms.username");
String SQLKingPassword = this.getConfig().getString("database.kingdoms.password");
MySQLking = new MySQL(plugin, SQLKingHost, "3306", SQLKingDatabase, SQLKingUser, SQLKingPassword);
//Phrases
log.info("[QK][STARTUP]Creating Phrases");
ChatPhrase.addPhrase("kingdom_name_single_word", "&cA kingdoms name may only be a single word!");
ChatPhrase.addPhrase("created_kingdom_yes", "&aSuccessfully created kingdom: ");
ChatPhrase.addPhrase("created_kingdom_no", "&cFailed to create kingdom: ");
ChatPhrase.addPhrase("deleted_kingdom_yes", "&aSuccessfully deleted kingdom: ");
ChatPhrase.addPhrase("deleted_kingdom_no", "&cFailed to delete kingdom: ");
ChatPhrase.addPhrase("specify_kingdom_name", "&cPlease specify a name!");
ChatPhrase.addPhrase("kingdomname_already_used", "&cAnother kingdom is using that name! &aConsider using a different name and overtaking that kingdom!");
ChatPhrase.addPhrase("info_kingdom", "&bInfo on Kingdom: ");
ChatPhrase.addPhrase("chunk_claimed_for_kingdom_yes", "&aChunk successfully claimed for Kingdom: ");
ChatPhrase.addPhrase("chunk_claimed_for_kingdom_no", "&aChunk was not successfully claimed for Kingdom: ");
ChatPhrase.addPhrase("chunk_unclaimed_for_kingdom_yes", "&aChunk successfully unclaimed for Kingdom: ");
ChatPhrase.addPhrase("chunk_unclaimed_for_kingdom_no", "&aChunk was not successfully unclaimed for Kingdom: ");
ChatPhrase.addPhrase("now_entering_the_land_of", "&aNow entering the land of ");
ChatPhrase.addPhrase("now_leaving_the_land_of", "&aNow entering the land of ");
ChatPhrase.addPhrase("got_promoted_kingdom_yes", "&aYou were moved group by your king!");
ChatPhrase.addPhrase("you_must_be_member_kingdom", "&cYou must be a member of a kingdom!");
ChatPhrase.addPhrase("you_must_be_member_kingdom_leave", "&cYou must be a member of a kingdom to leave one!");
ChatPhrase.addPhrase("you_are_already_in_a_Kingdom", "&cYou are already a member of a kingdom!");
ChatPhrase.addPhrase("successfully_joined_kingdom_X", "&aSuccessfully joined the kingdom ");
ChatPhrase.addPhrase("failed_join_kingdom", "&cFailed to join the specified kingdom. Please check that it is not invite only.");
ChatPhrase.addPhrase("successfully_left_kingdom_X", "&aSuccessfully left the kingdom ");
ChatPhrase.addPhrase("failed_leave_kingdom", "&cFailed to leave the specified kingdom.");
ChatPhrase.addPhrase("kingdom_already_open", " &cThe kingdom is already open!");
ChatPhrase.addPhrase("kingdom_now_open", " &aYour kingdom is now open!");
ChatPhrase.addPhrase("failed_open_kingdom", " &cFailed to open the kingdom!");
ChatPhrase.addPhrase("kingdom_already_closed", " &cThe kingdom is already closed!");
ChatPhrase.addPhrase("kingdom_now_closed", " &aYour kingdom is now closed!");
ChatPhrase.addPhrase("failed_close_kingdom", " &cFailed to close the kingdom!");
ChatPhrase.addPhrase("kingdom_is_now_at_war_with_kingdom", " &cis now at war with ");
ChatPhrase.addPhrase("kingdom_is_now_allied_with_kingdom", " &ais now allied with ");
ChatPhrase.addPhrase("kingdom_is_now_neutral_relationship_with_kingdom", " &6is now in a neutral relationship with ");
ChatPhrase.addPhrase("failed_to_ally_with_kingdom", "&cFailed to become an ally with ");
ChatPhrase.addPhrase("failed_to_neutral_with_kingdom", "&cFailed to become neutral with ");
ChatPhrase.addPhrase("failed_to_war_with_kingdom", "&cFailed to go to war with ");
ChatPhrase.addPhrase("could_not_create_kingdoms_player", "&cYou're playerdata could not be added to the QuartzKingdoms database!");
//Database
//logger.info("[STARTUP]Connecting to Database");
DBKing = MySQLking.openConnection();
//Listeners
log.info("[QK][STARTUP]Registering Listeners");
//getServer().getPluginManager().registerEvents(new BlockListener(), this);
new BlockListener(this);
new PlayerCreationListener(this);
new PlayerMoveListener(this);
//Commands
log.info("[QK][STARTUP]Registering Commands");
getCommand("kingdom").setExecutor(new CommandKingdom());
CommandKingdom.addCommand(Arrays.asList("info"), new KingdomInfoSubCommand());
CommandKingdom.addCommand(Arrays.asList("create"), new KingdomCreateSubCommand());
CommandKingdom.addCommand(Arrays.asList("delete"), new KingdomDeleteSubCommand());
CommandKingdom.addCommand(Arrays.asList("promote"), new KingdomPromoteSubCommand());
CommandKingdom.addCommand(Arrays.asList("claim"), new KingdomClaimSubCommand());
CommandKingdom.addCommand(Arrays.asList("unclaim"), new KingdomUnClaimSubCommand());
CommandKingdom.addCommand(Arrays.asList("war"), new KingdomWarSubCommand());
CommandKingdom.addCommand(Arrays.asList("ally"), new KingdomAllySubCommand());
CommandKingdom.addCommand(Arrays.asList("neutral"), new KingdomNeutralSubCommand());
CommandKingdom.addCommand(Arrays.asList("join"), new KingdomJoinSubCommand());
CommandKingdom.addCommand(Arrays.asList("leave"), new KingdomJoinSubCommand());
CommandKingdom.addCommand(Arrays.asList("open"), new KingdomOpenSubCommand());
CommandKingdom.addCommand(Arrays.asList("close"), new KingdomOpenSubCommand());
//Startup notice
log.info("[QK]The QuartzKingdoms Plugin has been enabled!");
log.info("[QK]Compiled using QuartzCore version " + releaseVersion);
}
| public void onEnable() {
log.info("[QC]Running plugin configuration");
this.saveDefaultConfig();
String SQLKingHost = this.getConfig().getString("database.kingdoms.host");
String SQLKingDatabase = this.getConfig().getString("database.kingdoms.database");
String SQLKingUser = this.getConfig().getString("database.kingdoms.username");
String SQLKingPassword = this.getConfig().getString("database.kingdoms.password");
MySQLking = new MySQL(plugin, SQLKingHost, "3306", SQLKingDatabase, SQLKingUser, SQLKingPassword);
//Phrases
log.info("[QK][STARTUP]Creating Phrases");
ChatPhrase.addPhrase("kingdom_name_single_word", "&cA kingdoms name may only be a single word!");
ChatPhrase.addPhrase("created_kingdom_yes", "&aSuccessfully created kingdom: ");
ChatPhrase.addPhrase("created_kingdom_no", "&cFailed to create kingdom: ");
ChatPhrase.addPhrase("deleted_kingdom_yes", "&aSuccessfully deleted kingdom: ");
ChatPhrase.addPhrase("deleted_kingdom_no", "&cFailed to delete kingdom: ");
ChatPhrase.addPhrase("specify_kingdom_name", "&cPlease specify a name!");
ChatPhrase.addPhrase("kingdomname_already_used", "&cAnother kingdom is using that name! &aConsider using a different name and overtaking that kingdom!");
ChatPhrase.addPhrase("info_kingdom", "&bInfo on Kingdom: ");
ChatPhrase.addPhrase("chunk_claimed_for_kingdom_yes", "&aChunk successfully claimed for Kingdom: ");
ChatPhrase.addPhrase("chunk_claimed_for_kingdom_no", "&aChunk was not successfully claimed for Kingdom: ");
ChatPhrase.addPhrase("chunk_unclaimed_for_kingdom_yes", "&aChunk successfully unclaimed for Kingdom: ");
ChatPhrase.addPhrase("chunk_unclaimed_for_kingdom_no", "&aChunk was not successfully unclaimed for Kingdom: ");
ChatPhrase.addPhrase("now_entering_the_land_of", "&aNow entering the land of ");
ChatPhrase.addPhrase("now_leaving_the_land_of", "&aNow entering the land of ");
ChatPhrase.addPhrase("got_promoted_kingdom_yes", "&aYou were moved group by your king!");
ChatPhrase.addPhrase("you_must_be_member_kingdom", "&cYou must be a member of a kingdom!");
ChatPhrase.addPhrase("you_must_be_member_kingdom_leave", "&cYou must be a member of a kingdom to leave one!");
ChatPhrase.addPhrase("you_are_already_in_a_Kingdom", "&cYou are already a member of a kingdom!");
ChatPhrase.addPhrase("successfully_joined_kingdom_X", "&aSuccessfully joined the kingdom ");
ChatPhrase.addPhrase("failed_join_kingdom", "&cFailed to join the specified kingdom. Please check that it is not invite only.");
ChatPhrase.addPhrase("successfully_left_kingdom_X", "&aSuccessfully left the kingdom ");
ChatPhrase.addPhrase("failed_leave_kingdom", "&cFailed to leave the specified kingdom.");
ChatPhrase.addPhrase("kingdom_already_open", " &cThe kingdom is already open!");
ChatPhrase.addPhrase("kingdom_now_open", " &aYour kingdom is now open!");
ChatPhrase.addPhrase("failed_open_kingdom", " &cFailed to open the kingdom!");
ChatPhrase.addPhrase("kingdom_already_closed", " &cThe kingdom is already closed!");
ChatPhrase.addPhrase("kingdom_now_closed", " &aYour kingdom is now closed!");
ChatPhrase.addPhrase("failed_close_kingdom", " &cFailed to close the kingdom!");
ChatPhrase.addPhrase("kingdom_is_now_at_war_with_kingdom", " &cis now at war with ");
ChatPhrase.addPhrase("kingdom_is_now_allied_with_kingdom", " &ais now allied with ");
ChatPhrase.addPhrase("kingdom_is_now_neutral_relationship_with_kingdom", " &6is now in a neutral relationship with ");
ChatPhrase.addPhrase("failed_to_ally_with_kingdom", "&cFailed to become an ally with ");
ChatPhrase.addPhrase("failed_to_neutral_with_kingdom", "&cFailed to become neutral with ");
ChatPhrase.addPhrase("failed_to_war_with_kingdom", "&cFailed to go to war with ");
ChatPhrase.addPhrase("could_not_create_kingdoms_player", "&cYour player data could not be added to the QuartzKingdoms database!");
//Database
//logger.info("[STARTUP]Connecting to Database");
DBKing = MySQLking.openConnection();
//Listeners
log.info("[QK][STARTUP]Registering Listeners");
//getServer().getPluginManager().registerEvents(new BlockListener(), this);
new BlockListener(this);
new PlayerCreationListener(this);
new PlayerMoveListener(this);
//Commands
log.info("[QK][STARTUP]Registering Commands");
getCommand("kingdom").setExecutor(new CommandKingdom());
CommandKingdom.addCommand(Arrays.asList("info"), new KingdomInfoSubCommand());
CommandKingdom.addCommand(Arrays.asList("create"), new KingdomCreateSubCommand());
CommandKingdom.addCommand(Arrays.asList("delete"), new KingdomDeleteSubCommand());
CommandKingdom.addCommand(Arrays.asList("promote"), new KingdomPromoteSubCommand());
CommandKingdom.addCommand(Arrays.asList("claim"), new KingdomClaimSubCommand());
CommandKingdom.addCommand(Arrays.asList("unclaim"), new KingdomUnClaimSubCommand());
CommandKingdom.addCommand(Arrays.asList("war"), new KingdomWarSubCommand());
CommandKingdom.addCommand(Arrays.asList("ally"), new KingdomAllySubCommand());
CommandKingdom.addCommand(Arrays.asList("neutral"), new KingdomNeutralSubCommand());
CommandKingdom.addCommand(Arrays.asList("join"), new KingdomJoinSubCommand());
CommandKingdom.addCommand(Arrays.asList("leave"), new KingdomJoinSubCommand());
CommandKingdom.addCommand(Arrays.asList("open"), new KingdomOpenSubCommand());
CommandKingdom.addCommand(Arrays.asList("close"), new KingdomOpenSubCommand());
//Startup notice
log.info("[QK]The QuartzKingdoms Plugin has been enabled!");
log.info("[QK]Compiled using QuartzCore version " + releaseVersion);
}
|
diff --git a/src/main/gradeapp/ExcelReader.java b/src/main/gradeapp/ExcelReader.java
index 00bbb11..16552cd 100644
--- a/src/main/gradeapp/ExcelReader.java
+++ b/src/main/gradeapp/ExcelReader.java
@@ -1,115 +1,115 @@
package gradeapp;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Vector;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/**
*
* @author sandro
*/
public class ExcelReader{
Vector<Character> key = new Vector<Character>();
Vector<Vector<Character>> students = new Vector<Vector<Character>>();
public ExcelReader (File in) throws IOException, GraphFormatException{
Workbook wb;
if (in.getName().endsWith("xlsx")){
wb = new XSSFWorkbook(new FileInputStream(in));
}else{
wb = new HSSFWorkbook(new FileInputStream(in));
}
Sheet MainSheet = wb.getSheetAt(0);
Row TitleRow = MainSheet.getRow(0);
Cell TitleCell = TitleRow.getCell(0);
String Title = TitleCell.getStringCellValue();
if(Title.equals("Scanner Results")){
Row KeyRow = MainSheet.getRow(3);
Cell QNumCell = KeyRow.getCell(4);
int QNum = new Integer(QNumCell.getRichStringCellValue().getString());
int rowCount = MainSheet.getPhysicalNumberOfRows();
//Grabs the Key from Excel Sheet
for(int i=7; i <= 7+QNum-1; i++){
Cell keyCell = KeyRow.getCell(i);
char tempKey;
int keyCellLength = keyCell.getRichStringCellValue().getString().length();
try{
if(keyCellLength == 1){
tempKey = Character.toUpperCase(keyCell.getRichStringCellValue().getString().charAt(0));
}
else{
throw new GraphFormatException();
}
}
catch(IllegalStateException ex){
throw new GraphFormatException();
}
if(tempKey >='A' && tempKey <='Z'){
key.add(tempKey);
}
else{
throw new GraphFormatException();
}
}
//Grabs Student Answers from Excel Sheet
- for(int j=4; j < rowCount-3; j++){
+ for(int j=4; j <= rowCount; j++){
Vector<Character> studAns = new Vector<Character>();
char tempStudAns;
Row studRow = MainSheet.getRow(j);
for(int k=7; k<=(7+QNum-1); k++){
Cell studCell = studRow.getCell(k);
if(studCell == null){
studAns.add(' ');
}
else{
try{
int studCellLength = studCell.getRichStringCellValue().getString().length();
if(studCellLength == 1){
tempStudAns = Character.toUpperCase(studCell.getRichStringCellValue().getString().charAt(0));
}
else{
throw new GraphFormatException();
}
}
catch(IllegalStateException ex){
throw new GraphFormatException();
}
if(tempStudAns >='A' && tempStudAns <='Z'){
studAns.add(tempStudAns);
}
else{
throw new GraphFormatException();
}
}
}
students.add(studAns);
}
}
else{
throw new GraphFormatException();
}
}
public Vector <Character> getAnswerKey(){
return key;
}
public Vector <Vector <Character>> getGrades(){
return students;
}
}
| true | true | public ExcelReader (File in) throws IOException, GraphFormatException{
Workbook wb;
if (in.getName().endsWith("xlsx")){
wb = new XSSFWorkbook(new FileInputStream(in));
}else{
wb = new HSSFWorkbook(new FileInputStream(in));
}
Sheet MainSheet = wb.getSheetAt(0);
Row TitleRow = MainSheet.getRow(0);
Cell TitleCell = TitleRow.getCell(0);
String Title = TitleCell.getStringCellValue();
if(Title.equals("Scanner Results")){
Row KeyRow = MainSheet.getRow(3);
Cell QNumCell = KeyRow.getCell(4);
int QNum = new Integer(QNumCell.getRichStringCellValue().getString());
int rowCount = MainSheet.getPhysicalNumberOfRows();
//Grabs the Key from Excel Sheet
for(int i=7; i <= 7+QNum-1; i++){
Cell keyCell = KeyRow.getCell(i);
char tempKey;
int keyCellLength = keyCell.getRichStringCellValue().getString().length();
try{
if(keyCellLength == 1){
tempKey = Character.toUpperCase(keyCell.getRichStringCellValue().getString().charAt(0));
}
else{
throw new GraphFormatException();
}
}
catch(IllegalStateException ex){
throw new GraphFormatException();
}
if(tempKey >='A' && tempKey <='Z'){
key.add(tempKey);
}
else{
throw new GraphFormatException();
}
}
//Grabs Student Answers from Excel Sheet
for(int j=4; j < rowCount-3; j++){
Vector<Character> studAns = new Vector<Character>();
char tempStudAns;
Row studRow = MainSheet.getRow(j);
for(int k=7; k<=(7+QNum-1); k++){
Cell studCell = studRow.getCell(k);
if(studCell == null){
studAns.add(' ');
}
else{
try{
int studCellLength = studCell.getRichStringCellValue().getString().length();
if(studCellLength == 1){
tempStudAns = Character.toUpperCase(studCell.getRichStringCellValue().getString().charAt(0));
}
else{
throw new GraphFormatException();
}
}
catch(IllegalStateException ex){
throw new GraphFormatException();
}
if(tempStudAns >='A' && tempStudAns <='Z'){
studAns.add(tempStudAns);
}
else{
throw new GraphFormatException();
}
}
}
students.add(studAns);
}
}
else{
throw new GraphFormatException();
}
}
| public ExcelReader (File in) throws IOException, GraphFormatException{
Workbook wb;
if (in.getName().endsWith("xlsx")){
wb = new XSSFWorkbook(new FileInputStream(in));
}else{
wb = new HSSFWorkbook(new FileInputStream(in));
}
Sheet MainSheet = wb.getSheetAt(0);
Row TitleRow = MainSheet.getRow(0);
Cell TitleCell = TitleRow.getCell(0);
String Title = TitleCell.getStringCellValue();
if(Title.equals("Scanner Results")){
Row KeyRow = MainSheet.getRow(3);
Cell QNumCell = KeyRow.getCell(4);
int QNum = new Integer(QNumCell.getRichStringCellValue().getString());
int rowCount = MainSheet.getPhysicalNumberOfRows();
//Grabs the Key from Excel Sheet
for(int i=7; i <= 7+QNum-1; i++){
Cell keyCell = KeyRow.getCell(i);
char tempKey;
int keyCellLength = keyCell.getRichStringCellValue().getString().length();
try{
if(keyCellLength == 1){
tempKey = Character.toUpperCase(keyCell.getRichStringCellValue().getString().charAt(0));
}
else{
throw new GraphFormatException();
}
}
catch(IllegalStateException ex){
throw new GraphFormatException();
}
if(tempKey >='A' && tempKey <='Z'){
key.add(tempKey);
}
else{
throw new GraphFormatException();
}
}
//Grabs Student Answers from Excel Sheet
for(int j=4; j <= rowCount; j++){
Vector<Character> studAns = new Vector<Character>();
char tempStudAns;
Row studRow = MainSheet.getRow(j);
for(int k=7; k<=(7+QNum-1); k++){
Cell studCell = studRow.getCell(k);
if(studCell == null){
studAns.add(' ');
}
else{
try{
int studCellLength = studCell.getRichStringCellValue().getString().length();
if(studCellLength == 1){
tempStudAns = Character.toUpperCase(studCell.getRichStringCellValue().getString().charAt(0));
}
else{
throw new GraphFormatException();
}
}
catch(IllegalStateException ex){
throw new GraphFormatException();
}
if(tempStudAns >='A' && tempStudAns <='Z'){
studAns.add(tempStudAns);
}
else{
throw new GraphFormatException();
}
}
}
students.add(studAns);
}
}
else{
throw new GraphFormatException();
}
}
|
diff --git a/geoserver/src/org/vfny/geoserver/wfs/responses/TransactionResponse.java b/geoserver/src/org/vfny/geoserver/wfs/responses/TransactionResponse.java
index f7ab0b2239..43363b2a29 100644
--- a/geoserver/src/org/vfny/geoserver/wfs/responses/TransactionResponse.java
+++ b/geoserver/src/org/vfny/geoserver/wfs/responses/TransactionResponse.java
@@ -1,841 +1,842 @@
/* Copyright (c) 2001, 2003 TOPP - www.openplans.org. All rights reserved.
* This code is licensed under the GPL 2.0 license, availible at the root
* application directory.
*/
package org.vfny.geoserver.wfs.responses;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.URI;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.TreeMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.geotools.data.DataSourceException;
import org.geotools.data.DataStore;
import org.geotools.data.DataUtilities;
import org.geotools.data.DefaultQuery;
import org.geotools.data.DefaultTransaction;
import org.geotools.data.FeatureLocking;
import org.geotools.data.FeatureReader;
import org.geotools.data.FeatureSource;
import org.geotools.data.FeatureStore;
import org.geotools.data.FeatureWriter;
import org.geotools.data.Transaction;
import org.geotools.feature.AttributeType;
import org.geotools.feature.Feature;
import org.geotools.feature.FeatureCollection;
import org.geotools.feature.FeatureType;
import org.geotools.feature.IllegalAttributeException;
import org.geotools.feature.SchemaException;
import org.geotools.filter.FidFilter;
import org.geotools.filter.Filter;
import org.geotools.filter.FilterFactory;
import org.geotools.validation.Validation;
import org.geotools.validation.ValidationProcessor;
import org.geotools.validation.ValidationResults;
import org.vfny.geoserver.Request;
import org.vfny.geoserver.Response;
import org.vfny.geoserver.ServiceException;
import org.vfny.geoserver.global.Data;
import org.vfny.geoserver.global.FeatureTypeInfo;
import org.vfny.geoserver.global.GeoServer;
import org.vfny.geoserver.global.Service;
import org.vfny.geoserver.global.dto.WFSDTO;
import org.vfny.geoserver.wfs.WfsException;
import org.vfny.geoserver.wfs.requests.DeleteRequest;
import org.vfny.geoserver.wfs.requests.InsertRequest;
import org.vfny.geoserver.wfs.requests.SubTransactionRequest;
import org.vfny.geoserver.wfs.requests.TransactionRequest;
import org.vfny.geoserver.wfs.requests.UpdateRequest;
import com.vividsolutions.jts.geom.Envelope;
/**
* Handles a Transaction request and creates a TransactionResponse string.
*
* @author Chris Holmes, TOPP
* @version $Id: TransactionResponse.java,v 1.32 2004/06/29 11:27:54 sploreg Exp $
*/
public class TransactionResponse implements Response {
/** Standard logging instance for class */
private static final Logger LOGGER = Logger.getLogger(
"org.vfny.geoserver.responses");
/** Response to be streamed during writeTo */
private WfsTransResponse response;
/** Request provided to Execute method */
private TransactionRequest request;
/** Geotools2 transaction used for this opperations */
protected Transaction transaction;
/**
* Constructor
*/
public TransactionResponse() {
transaction = null;
}
public void execute(Request request) throws ServiceException, WfsException {
if (!(request instanceof TransactionRequest)) {
throw new WfsException(
"bad request, expected TransactionRequest, but got " + request);
}
if ((request.getWFS().getServiceLevel() & WFSDTO.TRANSACTIONAL) == 0) {
throw new ServiceException("Transaction support is not enabled");
}
//REVISIT: this should maybe integrate with the other exception
//handlers better - but things that go wrong here should cause
//transaction exceptions.
//try {
execute((TransactionRequest) request);
//} catch (Throwable thrown) {
// throw new WfsTransactionException(thrown);
//}
}
/**
* Execute Transaction request.
*
* <p>
* The results of this opperation are stored for use by writeTo:
*
* <ul>
* <li>
* transaction: used by abort & writeTo to commit/rollback
* </li>
* <li>
* request: used for users getHandle information to report errors
* </li>
* <li>
* stores: FeatureStores required for Transaction
* </li>
* <li>
* failures: List of failures produced
* </li>
* </ul>
* </p>
*
* <p>
* Because we are using geotools2 locking facilities our modification will
* simply fail with IOException if we have not provided proper
* authorization.
* </p>
*
* <p>
* The specification allows a WFS to implement PARTIAL sucess if it is
* unable to rollback all the requested changes. This implementation is
* able to offer full Rollback support and will not require the use of
* PARTIAL success.
* </p>
*
* @param transactionRequest
*
* @throws ServiceException DOCUMENT ME!
* @throws WfsException
* @throws WfsTransactionException DOCUMENT ME!
*/
protected void execute(TransactionRequest transactionRequest)
throws ServiceException, WfsException {
request = transactionRequest; // preserved toWrite() handle access
transaction = new DefaultTransaction();
LOGGER.fine("request is " + request);
Data catalog = transactionRequest.getWFS().getData();
WfsTransResponse build = new WfsTransResponse(WfsTransResponse.SUCCESS,
transactionRequest.getGeoServer().isVerbose());
//
// We are going to preprocess our elements,
// gathering all the FeatureSources we need
//
// Map of required FeatureStores by typeName
Map stores = new HashMap();
// Map of required FeatureStores by typeRef (dataStoreId:typeName)
// (This will be added to the contents are harmed)
Map stores2= new HashMap();
// Gather FeatureStores required by Transaction Elements
// and configure them with our transaction
//
// (I am using element rather than transaction sub request
// to agree with the spec docs)
for (int i = 0; i < request.getSubRequestSize(); i++) {
SubTransactionRequest element = request.getSubRequest(i);
String typeRef = null;
String elementName = null;
FeatureTypeInfo meta = null;
if (element instanceof InsertRequest) {
// Option 1: Guess FeatureStore based on insert request
//
Feature feature = ((InsertRequest) element).getFeatures()
.features().next();
if (feature != null) {
String name = feature.getFeatureType().getTypeName();
URI uri = feature.getFeatureType().getNamespace();
LOGGER.fine("Locating FeatureSource uri:'"+uri+"' name:'"+name+"'");
meta = catalog.getFeatureTypeInfo(name, uri==null?null:uri.toString()); //change suggested by DZweirs
//HACK: The insert request does not get the correct typename,
//as we can no longer hack in the prefix since we are using the
//real featureType. So this is the only good place to do the
//look-up for the internal typename to use. We should probably
//rethink our use of prefixed internal typenames (cdf:bc_roads),
//and have our requests actually use a type uri and type name.
//Internally we can keep the prefixes, but if we do that then
//this will be less hacky and we'll also be able to read in xml
//for real, since the prefix should refer to the uri.
//
// JG:
// Transalation Insert does not have a clue about prefix - this provides the clue
element.setTypeName( meta.getNameSpace().getPrefix()+":"+meta.getTypeName() );
}
else {
LOGGER.finer("Insert was empty - does not need a FeatuerSoruce");
continue; // insert is actually empty
}
}
else {
// Option 2: lookup based on elmentName (assume prefix:typeName)
typeRef = null; // unknown at this time
elementName = element.getTypeName();
if( stores.containsKey( elementName )) {
LOGGER.finer("FeatureSource '"+elementName+"' already loaded." );
continue;
}
LOGGER.fine("Locating FeatureSource '"+elementName+"'...");
meta = catalog.getFeatureTypeInfo(elementName);
element.setTypeName( meta.getNameSpace().getPrefix()+":"+meta.getTypeName() );
}
typeRef = meta.getDataStoreInfo().getId()+":"+meta.getTypeName();
elementName = meta.getNameSpace().getPrefix()+":"+meta.getTypeName();
LOGGER.fine("located FeatureType w/ typeRef '"+typeRef+"' and elementName '"+elementName+"'" );
if (stores.containsKey(elementName)) {
// typeName already loaded
continue;
}
try {
FeatureSource source = meta.getFeatureSource();
if (source instanceof FeatureStore) {
FeatureStore store = (FeatureStore) source;
store.setTransaction(transaction);
stores.put( elementName, source );
stores2.put( typeRef, source );
} else {
throw new WfsTransactionException(elementName
+ " is read-only", element.getHandle(),
request.getHandle());
}
} catch (IOException ioException) {
throw new WfsTransactionException(elementName
+ " is not available:" + ioException,
element.getHandle(), request.getHandle());
}
}
// provide authorization for transaction
//
String authorizationID = request.getLockId();
if (authorizationID != null) {
if ((request.getWFS().getServiceLevel() & WFSDTO.SERVICE_LOCKING) == 0) {
// could we catch this during the handler, rather than during execution?
throw new ServiceException("Lock support is not enabled");
}
LOGGER.finer("got lockId: " + authorizationID);
if (!catalog.lockExists(authorizationID)) {
String mesg = "Attempting to use a lockID that does not exist"
+ ", it has either expired or was entered wrong.";
throw new WfsException(mesg);
}
try {
transaction.addAuthorization(authorizationID);
} catch (IOException ioException) {
// This is a real failure - not associated with a element
//
throw new WfsException("Authorization ID '" + authorizationID
+ "' not useable", ioException);
}
}
// execute elements in order,
// recording results as we go
//
// I will need to record the damaged area for
// pre commit validation checks
//
Envelope envelope = new Envelope();
for (int i = 0; i < request.getSubRequestSize(); i++) {
SubTransactionRequest element = request.getSubRequest(i);
// We expect element name to be of the format prefix:typeName
// We take care to force the insert element to have this format above.
//
String elementName = element.getTypeName();
String handle = element.getHandle();
FeatureStore store = (FeatureStore) stores.get(elementName);
if( store == null ){
throw new ServiceException( "Could not locate FeatureStore for '"+elementName+"'" );
}
String typeName = store.getSchema().getTypeName();
if (element instanceof DeleteRequest) {
if ((request.getWFS().getServiceLevel() & WFSDTO.SERVICE_DELETE) == 0) {
// could we catch this during the handler, rather than during execution?
throw new ServiceException(
"Transaction Delete support is not enabled");
}
LOGGER.finer( "Transaction Delete:"+element );
try {
DeleteRequest delete = (DeleteRequest) element;
Filter filter = delete.getFilter();
Envelope damaged = store.getBounds(new DefaultQuery(
delete.getTypeName(), filter));
if (damaged == null) {
damaged = store.getFeatures(filter).getBounds();
}
if ((request.getLockId() != null)
&& store instanceof FeatureLocking
&& (request.getReleaseAction() == TransactionRequest.SOME)) {
FeatureLocking locking = (FeatureLocking) store;
// TODO: Revisit Lock/Delete interaction in gt2
if (false) {
// REVISIT: This is bad - by releasing locks before
// we remove features we open ourselves up to the danger
// of someone else locking the features we are about to
// remove.
//
// We cannot do it the other way round, as the Features will
// not exist
//
// We cannot grab the fids offline using AUTO_COMMIT
// because we may have removed some of them earlier in the
// transaction
//
locking.unLockFeatures(filter);
store.removeFeatures(filter);
} else {
// This a bit better and what should be done, we will
// need to rework the gt2 locking api to work with
// fids or something
//
// The only other thing that would work would be
// to specify that FeatureLocking is required to
// remove locks when removing Features.
//
// While that sounds like a good idea, it would be
// extra work when doing release mode ALL.
//
DataStore data = store.getDataStore();
FilterFactory factory = FilterFactory
.createFilterFactory();
FeatureWriter writer;
writer = data.getFeatureWriter(typeName, filter,
transaction);
try {
while (writer.hasNext()) {
String fid = writer.next().getID();
locking.unLockFeatures(factory
.createFidFilter(fid));
writer.remove();
}
} finally {
writer.close();
}
store.removeFeatures(filter);
}
} else {
// We don't have to worry about locking right now
//
store.removeFeatures(filter);
}
envelope.expandToInclude(damaged);
} catch (IOException ioException) {
throw new WfsTransactionException(ioException.getMessage(),
element.getHandle(), request.getHandle());
}
}
if (element instanceof InsertRequest) {
if ((request.getWFS().getServiceLevel() & WFSDTO.SERVICE_INSERT) == 0) {
// could we catch this during the handler, rather than during execution?
throw new ServiceException(
"Transaction INSERT support is not enabled");
}
LOGGER.finer( "Transasction Insert:"+element );
try {
InsertRequest insert = (InsertRequest) element;
FeatureCollection collection = insert.getFeatures();
FeatureReader reader = DataUtilities.reader(collection);
FeatureType schema = store.getSchema();
// Need to use the namespace here for the lookup, due to our weird
// prefixed internal typenames. see
// http://jira.codehaus.org/secure/ViewIssue.jspa?key=GEOS-143
// Once we get our datastores making features with the correct namespaces
// we can do something like this:
// FeatureTypeInfo typeInfo = catalog.getFeatureTypeInfo(schema.getTypeName(), schema.getNamespace());
// until then (when geos-144 is resolved) we're stuck with:
FeatureTypeInfo typeInfo = catalog.getFeatureTypeInfo(element.getTypeName() );
// this is possible with the insert hack above.
LOGGER.finer("Use featureValidation to check contents of insert" );
featureValidation( typeInfo.getDataStoreInfo().getId(), schema, collection );
Set fids = store.addFeatures(reader);
build.addInsertResult(element.getHandle(), fids);
//
// Add to validation check envelope
envelope.expandToInclude(collection.getBounds());
} catch (IOException ioException) {
throw new WfsTransactionException(ioException,
element.getHandle(), request.getHandle());
}
}
if (element instanceof UpdateRequest) {
if ((request.getWFS().getServiceLevel() & WFSDTO.SERVICE_UPDATE) == 0) {
// could we catch this during the handler, rather than during execution?
throw new ServiceException(
"Transaction Update support is not enabled");
}
LOGGER.finer( "Transaction Update:"+element);
try {
UpdateRequest update = (UpdateRequest) element;
Filter filter = update.getFilter();
AttributeType[] types = update.getTypes(store.getSchema());
Object[] values = update.getValues();
DefaultQuery query = new DefaultQuery(update.getTypeName(),
filter);
// Pass through data to collect fids and damaged region
// for validation
//
Set fids = new HashSet();
LOGGER.finer("Preprocess to remember modification as a set of fids" );
FeatureReader preprocess = store.getFeatures( filter ).reader();
try {
while( preprocess.hasNext() ){
Feature feature = preprocess.next();
fids.add( feature.getID() );
envelope.expandToInclude( feature.getBounds() );
}
} catch (NoSuchElementException e) {
throw new ServiceException( "Could not aquire FeatureIDs", e );
} catch (IllegalAttributeException e) {
throw new ServiceException( "Could not aquire FeatureIDs", e );
}
finally {
preprocess.close();
}
try{
if (types.length == 1) {
store.modifyFeatures(types[0], values[0], filter);
} else {
store.modifyFeatures(types, values, filter);
}
}catch (IOException e) //DJB: this is for cite tests. We should probaby do this for all the exceptions here - throw a transaction FAIL instead of serice exception
{
//this failed - we want a FAILED not a service exception!
build = new WfsTransResponse(WfsTransResponse.FAILED,
transactionRequest.getGeoServer().isVerbose());
// add in exception details here??
+ build.setMessage(e.getLocalizedMessage());
response = build;
// DJB: it looks like the transaction is rolled back in writeTo()
return;
}
if ((request.getLockId() != null)
&& store instanceof FeatureLocking
&& (request.getReleaseAction() == TransactionRequest.SOME)) {
FeatureLocking locking = (FeatureLocking) store;
locking.unLockFeatures(filter);
}
// Post process - check features for changed boundary and
// pass them off to the ValidationProcessor
//
if( !fids.isEmpty() ) {
LOGGER.finer("Post process update for boundary update and featureValidation");
FidFilter modified = FilterFactory.createFilterFactory().createFidFilter();
modified.addAllFids( fids );
FeatureCollection changed = store.getFeatures( modified ).collection();
envelope.expandToInclude( changed.getBounds() );
FeatureTypeInfo typeInfo = catalog.getFeatureTypeInfo(element.getTypeName());
featureValidation(typeInfo.getDataStoreInfo().getId(),store.getSchema(), changed);
}
} catch (IOException ioException) {
throw new WfsTransactionException(ioException,
element.getHandle(), request.getHandle());
} catch (SchemaException typeException) {
throw new WfsTransactionException(typeName
+ " inconsistent with update:"
+ typeException.getMessage(), element.getHandle(),
request.getHandle());
}
}
}
// All opperations have worked thus far
//
// Time for some global Validation Checks against envelope
//
try {
integrityValidation(stores2, envelope);
} catch (Exception invalid) {
throw new WfsTransactionException(invalid);
}
// we will commit in the writeTo method
// after user has got the response
response = build;
}
protected void featureValidation(String dsid, FeatureType type,
FeatureCollection collection)
throws IOException, WfsTransactionException {
LOGGER.finer("FeatureValidation called on "+dsid+":"+type.getTypeName() );
ValidationProcessor validation = request.getValidationProcessor();
if (validation == null){
//This is a bit hackish, as the validation processor should not
//be null, but confDemo gives us a null processor right now, some
//thing to do with no test element in the xml files in validation.
//But I'm taking no validation process to mean that we can't do
//any validation. Hopefully this doesn't mess people up?
//could mess up some validation stuff, but not everyone makes use
//of that, and I don't want normal transaction stuff messed up. ch
LOGGER.warning("ValidationProcessor unavailable");
return;
}
final Map failed = new TreeMap();
ValidationResults results = new ValidationResults() {
String name;
String description;
public void setValidation(Validation validation) {
name = validation.getName();
description = validation.getDescription();
}
public void error(Feature feature, String message) {
LOGGER.warning(name + ": " + message + " (" + description
+ ")");
failed.put(feature.getID(),
name + ": " + message + " " + "(" + description + ")");
}
public void warning(Feature feature, String message) {
LOGGER.warning(name + ": " + message + " (" + description
+ ")");
}
};
try {
// HACK: turned the collection into a feature reader for the validation processor
FeatureReader fr = DataUtilities.reader(collection);
validation.runFeatureTests(dsid, type, fr, results);
} catch (Exception badIdea) {
// ValidationResults should of handled stuff will redesign :-)
throw new DataSourceException("Validation Failed", badIdea);
}
if (failed.isEmpty()) {
return; // everything worked out
}
StringBuffer message = new StringBuffer();
for (Iterator i = failed.entrySet().iterator(); i.hasNext();) {
Map.Entry entry = (Map.Entry) i.next();
message.append(entry.getKey());
message.append(" failed test ");
message.append(entry.getValue());
message.append("\n");
}
throw new WfsTransactionException(message.toString(), "validation");
}
protected void integrityValidation(Map stores, Envelope check)
throws IOException, WfsTransactionException {
Data catalog = request.getWFS().getData();
ValidationProcessor validation = request.getValidationProcessor();
if( validation == null ) {
LOGGER.warning( "Validation Processor unavaialble" );
return;
}
LOGGER.finer( "Required to validate "+stores.size()+" typeRefs" );
LOGGER.finer( "within "+check );
// go through each modified typeName
// and ask what we need to check
//
Set typeRefs = new HashSet();
for (Iterator i = stores.keySet().iterator(); i.hasNext();) {
String typeRef = (String) i.next();
typeRefs.add( typeRef );
Set dependencies = validation.getDependencies( typeRef );
LOGGER.finer( "typeRef "+typeRef+" requires "+dependencies);
typeRefs.addAll( dependencies );
}
// Grab a source for each typeName we need to check
// Grab from the provided stores - so we check against
// the transaction
//
Map sources = new HashMap();
for (Iterator i = typeRefs.iterator(); i.hasNext();) {
String typeRef = (String) i.next();
LOGGER.finer("Searching for required typeRef: " + typeRef );
if (stores.containsKey( typeRef )) {
LOGGER.finer(" found required typeRef: " + typeRef +" (it was already loaded)");
sources.put( typeRef, stores.get(typeRef));
} else {
// These will be using Transaction.AUTO_COMMIT
// this is okay as they were not involved in our
// Transaction...
LOGGER.finer(" could not find typeRef: " + typeRef +" (we will now load it)");
String split[] = typeRef.split(":");
String dataStoreId = split[0];
String typeName = split[1];
LOGGER.finer(" going to look for dataStoreId:"+dataStoreId+" and typeName:"+typeName );
// FeatureTypeInfo meta = catalog.getFeatureTypeInfo(typeName);
String uri = catalog.getDataStoreInfo( dataStoreId ).getNameSpace().getURI();
LOGGER.finer(" sorry I mean uri: " + uri +" and typeName:"+typeName );
FeatureTypeInfo meta = catalog.getFeatureTypeInfo( typeName, uri );
if( meta == null ){
throw new IOException( "Could not find typeRef:"+typeRef +" for validation processor" );
}
LOGGER.finer(" loaded required typeRef: " + typeRef );
sources.put( typeRef, meta.getFeatureSource());
}
}
LOGGER.finer( "Total of "+sources.size()+" featureSource marshalled for testing" );
final Map failed = new TreeMap();
ValidationResults results = new ValidationResults() {
String name;
String description;
public void setValidation(Validation validation) {
name = validation.getName();
description = validation.getDescription();
}
public void error(Feature feature, String message) {
LOGGER.warning(name + ": " + message + " (" + description
+ ")");
if (feature == null) {
failed.put("ALL",
name + ": " + message + " " + "(" + description + ")");
} else {
failed.put(feature.getID(),
name + ": " + message + " " + "(" + description + ")");
}
}
public void warning(Feature feature, String message) {
LOGGER.warning(name + ": " + message + " (" + description
+ ")");
}
};
try {
//should never be null, but confDemo is giving grief, and I
//don't want transactions to mess up just because validation
//stuff is messed up. ch
LOGGER.finer("Runing integrity tests using validation processor ");
validation.runIntegrityTests(stores.keySet(), sources, check, results);
} catch (Exception badIdea) {
badIdea.printStackTrace();
// ValidationResults should of handled stuff will redesign :-)
throw new DataSourceException("Validation Failed", badIdea);
}
if (failed.isEmpty()) {
LOGGER.finer( "All validation tests passed" );
return; // everything worked out
}
LOGGER.finer( "Validation fail - marshal result for transaction document" );
StringBuffer message = new StringBuffer();
for (Iterator i = failed.entrySet().iterator(); i.hasNext();) {
Map.Entry entry = (Map.Entry) i.next();
message.append(entry.getKey());
message.append(" failed test ");
message.append(entry.getValue());
message.append("\n");
}
throw new WfsTransactionException(message.toString(), "validation");
}
/**
* Responce MIME type as define by ServerConig.
*
* @param gs DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public String getContentType(GeoServer gs) {
return gs.getMimeType();
}
public String getContentEncoding() {
return null;
}
/**
* Writes generated xmlResponse.
*
* <p>
* I have delayed commiting the result until we have returned it to the
* user, this gives us a chance to rollback if we are not able to provide
* a response.
* </p>
* I could not quite figure out what to about releasing locks. It could be
* we are supposed to release locks even if the transaction fails, or only
* if it succeeds.
*
* @param out DOCUMENT ME!
*
* @throws ServiceException DOCUMENT ME!
* @throws IOException DOCUMENT ME!
*/
public void writeTo(OutputStream out) throws ServiceException, IOException {
if ((transaction == null) || (response == null)) {
throw new ServiceException("Transaction not executed");
}
if (response.status == WfsTransResponse.PARTIAL) {
throw new ServiceException("Canceling PARTIAL response");
}
try {
Writer writer;
writer = new OutputStreamWriter(out);
writer = new BufferedWriter(writer);
response.writeXmlResponse(writer, request);
writer.flush();
switch (response.status) {
case WfsTransResponse.SUCCESS:
transaction.commit();
break;
case WfsTransResponse.FAILED:
transaction.rollback();
break;
}
} catch (IOException ioException) {
transaction.rollback();
throw ioException;
} finally {
transaction.close();
transaction = null;
}
//
// Lets deal with the locks
//
// Q: Why talk to Data you ask
// A: Only class that knows all the DataStores
//
// We really need to ask all DataStores to release/refresh
// because we may have locked Features with this Authorizations
// on them, even though we did not refer to them in this transaction.
//
// Q: Why here, why now?
// A: The opperation was a success, and we have completed the opperation
//
// We also need to do this if the opperation is not a success,
// you can find this same code in the abort method
//
Data catalog = request.getWFS().getData();
if (request.getLockId() != null) {
if (request.getReleaseAction() == TransactionRequest.ALL) {
catalog.lockRelease(request.getLockId());
} else if (request.getReleaseAction() == TransactionRequest.SOME) {
catalog.lockRefresh(request.getLockId());
}
}
}
/* (non-Javadoc)
* @see org.vfny.geoserver.responses.Response#abort()
*/
public void abort(Service gs) {
if (transaction == null) {
return; // no transaction to rollback
}
try {
transaction.rollback();
transaction.close();
} catch (IOException ioException) {
// nothing we can do here
LOGGER.log(Level.SEVERE,
"Failed trying to rollback a transaction:" + ioException);
}
if (request != null) {
//
// TODO: Do we need release/refresh during an abort?
if (request.getLockId() != null) {
Data catalog = gs.getData();
if (request.getReleaseAction() == TransactionRequest.ALL) {
catalog.lockRelease(request.getLockId());
} else if (request.getReleaseAction() == TransactionRequest.SOME) {
catalog.lockRefresh(request.getLockId());
}
}
}
request = null;
response = null;
}
}
| true | true | protected void execute(TransactionRequest transactionRequest)
throws ServiceException, WfsException {
request = transactionRequest; // preserved toWrite() handle access
transaction = new DefaultTransaction();
LOGGER.fine("request is " + request);
Data catalog = transactionRequest.getWFS().getData();
WfsTransResponse build = new WfsTransResponse(WfsTransResponse.SUCCESS,
transactionRequest.getGeoServer().isVerbose());
//
// We are going to preprocess our elements,
// gathering all the FeatureSources we need
//
// Map of required FeatureStores by typeName
Map stores = new HashMap();
// Map of required FeatureStores by typeRef (dataStoreId:typeName)
// (This will be added to the contents are harmed)
Map stores2= new HashMap();
// Gather FeatureStores required by Transaction Elements
// and configure them with our transaction
//
// (I am using element rather than transaction sub request
// to agree with the spec docs)
for (int i = 0; i < request.getSubRequestSize(); i++) {
SubTransactionRequest element = request.getSubRequest(i);
String typeRef = null;
String elementName = null;
FeatureTypeInfo meta = null;
if (element instanceof InsertRequest) {
// Option 1: Guess FeatureStore based on insert request
//
Feature feature = ((InsertRequest) element).getFeatures()
.features().next();
if (feature != null) {
String name = feature.getFeatureType().getTypeName();
URI uri = feature.getFeatureType().getNamespace();
LOGGER.fine("Locating FeatureSource uri:'"+uri+"' name:'"+name+"'");
meta = catalog.getFeatureTypeInfo(name, uri==null?null:uri.toString()); //change suggested by DZweirs
//HACK: The insert request does not get the correct typename,
//as we can no longer hack in the prefix since we are using the
//real featureType. So this is the only good place to do the
//look-up for the internal typename to use. We should probably
//rethink our use of prefixed internal typenames (cdf:bc_roads),
//and have our requests actually use a type uri and type name.
//Internally we can keep the prefixes, but if we do that then
//this will be less hacky and we'll also be able to read in xml
//for real, since the prefix should refer to the uri.
//
// JG:
// Transalation Insert does not have a clue about prefix - this provides the clue
element.setTypeName( meta.getNameSpace().getPrefix()+":"+meta.getTypeName() );
}
else {
LOGGER.finer("Insert was empty - does not need a FeatuerSoruce");
continue; // insert is actually empty
}
}
else {
// Option 2: lookup based on elmentName (assume prefix:typeName)
typeRef = null; // unknown at this time
elementName = element.getTypeName();
if( stores.containsKey( elementName )) {
LOGGER.finer("FeatureSource '"+elementName+"' already loaded." );
continue;
}
LOGGER.fine("Locating FeatureSource '"+elementName+"'...");
meta = catalog.getFeatureTypeInfo(elementName);
element.setTypeName( meta.getNameSpace().getPrefix()+":"+meta.getTypeName() );
}
typeRef = meta.getDataStoreInfo().getId()+":"+meta.getTypeName();
elementName = meta.getNameSpace().getPrefix()+":"+meta.getTypeName();
LOGGER.fine("located FeatureType w/ typeRef '"+typeRef+"' and elementName '"+elementName+"'" );
if (stores.containsKey(elementName)) {
// typeName already loaded
continue;
}
try {
FeatureSource source = meta.getFeatureSource();
if (source instanceof FeatureStore) {
FeatureStore store = (FeatureStore) source;
store.setTransaction(transaction);
stores.put( elementName, source );
stores2.put( typeRef, source );
} else {
throw new WfsTransactionException(elementName
+ " is read-only", element.getHandle(),
request.getHandle());
}
} catch (IOException ioException) {
throw new WfsTransactionException(elementName
+ " is not available:" + ioException,
element.getHandle(), request.getHandle());
}
}
// provide authorization for transaction
//
String authorizationID = request.getLockId();
if (authorizationID != null) {
if ((request.getWFS().getServiceLevel() & WFSDTO.SERVICE_LOCKING) == 0) {
// could we catch this during the handler, rather than during execution?
throw new ServiceException("Lock support is not enabled");
}
LOGGER.finer("got lockId: " + authorizationID);
if (!catalog.lockExists(authorizationID)) {
String mesg = "Attempting to use a lockID that does not exist"
+ ", it has either expired or was entered wrong.";
throw new WfsException(mesg);
}
try {
transaction.addAuthorization(authorizationID);
} catch (IOException ioException) {
// This is a real failure - not associated with a element
//
throw new WfsException("Authorization ID '" + authorizationID
+ "' not useable", ioException);
}
}
// execute elements in order,
// recording results as we go
//
// I will need to record the damaged area for
// pre commit validation checks
//
Envelope envelope = new Envelope();
for (int i = 0; i < request.getSubRequestSize(); i++) {
SubTransactionRequest element = request.getSubRequest(i);
// We expect element name to be of the format prefix:typeName
// We take care to force the insert element to have this format above.
//
String elementName = element.getTypeName();
String handle = element.getHandle();
FeatureStore store = (FeatureStore) stores.get(elementName);
if( store == null ){
throw new ServiceException( "Could not locate FeatureStore for '"+elementName+"'" );
}
String typeName = store.getSchema().getTypeName();
if (element instanceof DeleteRequest) {
if ((request.getWFS().getServiceLevel() & WFSDTO.SERVICE_DELETE) == 0) {
// could we catch this during the handler, rather than during execution?
throw new ServiceException(
"Transaction Delete support is not enabled");
}
LOGGER.finer( "Transaction Delete:"+element );
try {
DeleteRequest delete = (DeleteRequest) element;
Filter filter = delete.getFilter();
Envelope damaged = store.getBounds(new DefaultQuery(
delete.getTypeName(), filter));
if (damaged == null) {
damaged = store.getFeatures(filter).getBounds();
}
if ((request.getLockId() != null)
&& store instanceof FeatureLocking
&& (request.getReleaseAction() == TransactionRequest.SOME)) {
FeatureLocking locking = (FeatureLocking) store;
// TODO: Revisit Lock/Delete interaction in gt2
if (false) {
// REVISIT: This is bad - by releasing locks before
// we remove features we open ourselves up to the danger
// of someone else locking the features we are about to
// remove.
//
// We cannot do it the other way round, as the Features will
// not exist
//
// We cannot grab the fids offline using AUTO_COMMIT
// because we may have removed some of them earlier in the
// transaction
//
locking.unLockFeatures(filter);
store.removeFeatures(filter);
} else {
// This a bit better and what should be done, we will
// need to rework the gt2 locking api to work with
// fids or something
//
// The only other thing that would work would be
// to specify that FeatureLocking is required to
// remove locks when removing Features.
//
// While that sounds like a good idea, it would be
// extra work when doing release mode ALL.
//
DataStore data = store.getDataStore();
FilterFactory factory = FilterFactory
.createFilterFactory();
FeatureWriter writer;
writer = data.getFeatureWriter(typeName, filter,
transaction);
try {
while (writer.hasNext()) {
String fid = writer.next().getID();
locking.unLockFeatures(factory
.createFidFilter(fid));
writer.remove();
}
} finally {
writer.close();
}
store.removeFeatures(filter);
}
} else {
// We don't have to worry about locking right now
//
store.removeFeatures(filter);
}
envelope.expandToInclude(damaged);
} catch (IOException ioException) {
throw new WfsTransactionException(ioException.getMessage(),
element.getHandle(), request.getHandle());
}
}
if (element instanceof InsertRequest) {
if ((request.getWFS().getServiceLevel() & WFSDTO.SERVICE_INSERT) == 0) {
// could we catch this during the handler, rather than during execution?
throw new ServiceException(
"Transaction INSERT support is not enabled");
}
LOGGER.finer( "Transasction Insert:"+element );
try {
InsertRequest insert = (InsertRequest) element;
FeatureCollection collection = insert.getFeatures();
FeatureReader reader = DataUtilities.reader(collection);
FeatureType schema = store.getSchema();
// Need to use the namespace here for the lookup, due to our weird
// prefixed internal typenames. see
// http://jira.codehaus.org/secure/ViewIssue.jspa?key=GEOS-143
// Once we get our datastores making features with the correct namespaces
// we can do something like this:
// FeatureTypeInfo typeInfo = catalog.getFeatureTypeInfo(schema.getTypeName(), schema.getNamespace());
// until then (when geos-144 is resolved) we're stuck with:
FeatureTypeInfo typeInfo = catalog.getFeatureTypeInfo(element.getTypeName() );
// this is possible with the insert hack above.
LOGGER.finer("Use featureValidation to check contents of insert" );
featureValidation( typeInfo.getDataStoreInfo().getId(), schema, collection );
Set fids = store.addFeatures(reader);
build.addInsertResult(element.getHandle(), fids);
//
// Add to validation check envelope
envelope.expandToInclude(collection.getBounds());
} catch (IOException ioException) {
throw new WfsTransactionException(ioException,
element.getHandle(), request.getHandle());
}
}
if (element instanceof UpdateRequest) {
if ((request.getWFS().getServiceLevel() & WFSDTO.SERVICE_UPDATE) == 0) {
// could we catch this during the handler, rather than during execution?
throw new ServiceException(
"Transaction Update support is not enabled");
}
LOGGER.finer( "Transaction Update:"+element);
try {
UpdateRequest update = (UpdateRequest) element;
Filter filter = update.getFilter();
AttributeType[] types = update.getTypes(store.getSchema());
Object[] values = update.getValues();
DefaultQuery query = new DefaultQuery(update.getTypeName(),
filter);
// Pass through data to collect fids and damaged region
// for validation
//
Set fids = new HashSet();
LOGGER.finer("Preprocess to remember modification as a set of fids" );
FeatureReader preprocess = store.getFeatures( filter ).reader();
try {
while( preprocess.hasNext() ){
Feature feature = preprocess.next();
fids.add( feature.getID() );
envelope.expandToInclude( feature.getBounds() );
}
} catch (NoSuchElementException e) {
throw new ServiceException( "Could not aquire FeatureIDs", e );
} catch (IllegalAttributeException e) {
throw new ServiceException( "Could not aquire FeatureIDs", e );
}
finally {
preprocess.close();
}
try{
if (types.length == 1) {
store.modifyFeatures(types[0], values[0], filter);
} else {
store.modifyFeatures(types, values, filter);
}
}catch (IOException e) //DJB: this is for cite tests. We should probaby do this for all the exceptions here - throw a transaction FAIL instead of serice exception
{
//this failed - we want a FAILED not a service exception!
build = new WfsTransResponse(WfsTransResponse.FAILED,
transactionRequest.getGeoServer().isVerbose());
// add in exception details here??
response = build;
// DJB: it looks like the transaction is rolled back in writeTo()
return;
}
if ((request.getLockId() != null)
&& store instanceof FeatureLocking
&& (request.getReleaseAction() == TransactionRequest.SOME)) {
FeatureLocking locking = (FeatureLocking) store;
locking.unLockFeatures(filter);
}
// Post process - check features for changed boundary and
// pass them off to the ValidationProcessor
//
if( !fids.isEmpty() ) {
LOGGER.finer("Post process update for boundary update and featureValidation");
FidFilter modified = FilterFactory.createFilterFactory().createFidFilter();
modified.addAllFids( fids );
FeatureCollection changed = store.getFeatures( modified ).collection();
envelope.expandToInclude( changed.getBounds() );
FeatureTypeInfo typeInfo = catalog.getFeatureTypeInfo(element.getTypeName());
featureValidation(typeInfo.getDataStoreInfo().getId(),store.getSchema(), changed);
}
} catch (IOException ioException) {
throw new WfsTransactionException(ioException,
element.getHandle(), request.getHandle());
} catch (SchemaException typeException) {
throw new WfsTransactionException(typeName
+ " inconsistent with update:"
+ typeException.getMessage(), element.getHandle(),
request.getHandle());
}
}
}
// All opperations have worked thus far
//
// Time for some global Validation Checks against envelope
//
try {
integrityValidation(stores2, envelope);
} catch (Exception invalid) {
throw new WfsTransactionException(invalid);
}
// we will commit in the writeTo method
// after user has got the response
response = build;
}
| protected void execute(TransactionRequest transactionRequest)
throws ServiceException, WfsException {
request = transactionRequest; // preserved toWrite() handle access
transaction = new DefaultTransaction();
LOGGER.fine("request is " + request);
Data catalog = transactionRequest.getWFS().getData();
WfsTransResponse build = new WfsTransResponse(WfsTransResponse.SUCCESS,
transactionRequest.getGeoServer().isVerbose());
//
// We are going to preprocess our elements,
// gathering all the FeatureSources we need
//
// Map of required FeatureStores by typeName
Map stores = new HashMap();
// Map of required FeatureStores by typeRef (dataStoreId:typeName)
// (This will be added to the contents are harmed)
Map stores2= new HashMap();
// Gather FeatureStores required by Transaction Elements
// and configure them with our transaction
//
// (I am using element rather than transaction sub request
// to agree with the spec docs)
for (int i = 0; i < request.getSubRequestSize(); i++) {
SubTransactionRequest element = request.getSubRequest(i);
String typeRef = null;
String elementName = null;
FeatureTypeInfo meta = null;
if (element instanceof InsertRequest) {
// Option 1: Guess FeatureStore based on insert request
//
Feature feature = ((InsertRequest) element).getFeatures()
.features().next();
if (feature != null) {
String name = feature.getFeatureType().getTypeName();
URI uri = feature.getFeatureType().getNamespace();
LOGGER.fine("Locating FeatureSource uri:'"+uri+"' name:'"+name+"'");
meta = catalog.getFeatureTypeInfo(name, uri==null?null:uri.toString()); //change suggested by DZweirs
//HACK: The insert request does not get the correct typename,
//as we can no longer hack in the prefix since we are using the
//real featureType. So this is the only good place to do the
//look-up for the internal typename to use. We should probably
//rethink our use of prefixed internal typenames (cdf:bc_roads),
//and have our requests actually use a type uri and type name.
//Internally we can keep the prefixes, but if we do that then
//this will be less hacky and we'll also be able to read in xml
//for real, since the prefix should refer to the uri.
//
// JG:
// Transalation Insert does not have a clue about prefix - this provides the clue
element.setTypeName( meta.getNameSpace().getPrefix()+":"+meta.getTypeName() );
}
else {
LOGGER.finer("Insert was empty - does not need a FeatuerSoruce");
continue; // insert is actually empty
}
}
else {
// Option 2: lookup based on elmentName (assume prefix:typeName)
typeRef = null; // unknown at this time
elementName = element.getTypeName();
if( stores.containsKey( elementName )) {
LOGGER.finer("FeatureSource '"+elementName+"' already loaded." );
continue;
}
LOGGER.fine("Locating FeatureSource '"+elementName+"'...");
meta = catalog.getFeatureTypeInfo(elementName);
element.setTypeName( meta.getNameSpace().getPrefix()+":"+meta.getTypeName() );
}
typeRef = meta.getDataStoreInfo().getId()+":"+meta.getTypeName();
elementName = meta.getNameSpace().getPrefix()+":"+meta.getTypeName();
LOGGER.fine("located FeatureType w/ typeRef '"+typeRef+"' and elementName '"+elementName+"'" );
if (stores.containsKey(elementName)) {
// typeName already loaded
continue;
}
try {
FeatureSource source = meta.getFeatureSource();
if (source instanceof FeatureStore) {
FeatureStore store = (FeatureStore) source;
store.setTransaction(transaction);
stores.put( elementName, source );
stores2.put( typeRef, source );
} else {
throw new WfsTransactionException(elementName
+ " is read-only", element.getHandle(),
request.getHandle());
}
} catch (IOException ioException) {
throw new WfsTransactionException(elementName
+ " is not available:" + ioException,
element.getHandle(), request.getHandle());
}
}
// provide authorization for transaction
//
String authorizationID = request.getLockId();
if (authorizationID != null) {
if ((request.getWFS().getServiceLevel() & WFSDTO.SERVICE_LOCKING) == 0) {
// could we catch this during the handler, rather than during execution?
throw new ServiceException("Lock support is not enabled");
}
LOGGER.finer("got lockId: " + authorizationID);
if (!catalog.lockExists(authorizationID)) {
String mesg = "Attempting to use a lockID that does not exist"
+ ", it has either expired or was entered wrong.";
throw new WfsException(mesg);
}
try {
transaction.addAuthorization(authorizationID);
} catch (IOException ioException) {
// This is a real failure - not associated with a element
//
throw new WfsException("Authorization ID '" + authorizationID
+ "' not useable", ioException);
}
}
// execute elements in order,
// recording results as we go
//
// I will need to record the damaged area for
// pre commit validation checks
//
Envelope envelope = new Envelope();
for (int i = 0; i < request.getSubRequestSize(); i++) {
SubTransactionRequest element = request.getSubRequest(i);
// We expect element name to be of the format prefix:typeName
// We take care to force the insert element to have this format above.
//
String elementName = element.getTypeName();
String handle = element.getHandle();
FeatureStore store = (FeatureStore) stores.get(elementName);
if( store == null ){
throw new ServiceException( "Could not locate FeatureStore for '"+elementName+"'" );
}
String typeName = store.getSchema().getTypeName();
if (element instanceof DeleteRequest) {
if ((request.getWFS().getServiceLevel() & WFSDTO.SERVICE_DELETE) == 0) {
// could we catch this during the handler, rather than during execution?
throw new ServiceException(
"Transaction Delete support is not enabled");
}
LOGGER.finer( "Transaction Delete:"+element );
try {
DeleteRequest delete = (DeleteRequest) element;
Filter filter = delete.getFilter();
Envelope damaged = store.getBounds(new DefaultQuery(
delete.getTypeName(), filter));
if (damaged == null) {
damaged = store.getFeatures(filter).getBounds();
}
if ((request.getLockId() != null)
&& store instanceof FeatureLocking
&& (request.getReleaseAction() == TransactionRequest.SOME)) {
FeatureLocking locking = (FeatureLocking) store;
// TODO: Revisit Lock/Delete interaction in gt2
if (false) {
// REVISIT: This is bad - by releasing locks before
// we remove features we open ourselves up to the danger
// of someone else locking the features we are about to
// remove.
//
// We cannot do it the other way round, as the Features will
// not exist
//
// We cannot grab the fids offline using AUTO_COMMIT
// because we may have removed some of them earlier in the
// transaction
//
locking.unLockFeatures(filter);
store.removeFeatures(filter);
} else {
// This a bit better and what should be done, we will
// need to rework the gt2 locking api to work with
// fids or something
//
// The only other thing that would work would be
// to specify that FeatureLocking is required to
// remove locks when removing Features.
//
// While that sounds like a good idea, it would be
// extra work when doing release mode ALL.
//
DataStore data = store.getDataStore();
FilterFactory factory = FilterFactory
.createFilterFactory();
FeatureWriter writer;
writer = data.getFeatureWriter(typeName, filter,
transaction);
try {
while (writer.hasNext()) {
String fid = writer.next().getID();
locking.unLockFeatures(factory
.createFidFilter(fid));
writer.remove();
}
} finally {
writer.close();
}
store.removeFeatures(filter);
}
} else {
// We don't have to worry about locking right now
//
store.removeFeatures(filter);
}
envelope.expandToInclude(damaged);
} catch (IOException ioException) {
throw new WfsTransactionException(ioException.getMessage(),
element.getHandle(), request.getHandle());
}
}
if (element instanceof InsertRequest) {
if ((request.getWFS().getServiceLevel() & WFSDTO.SERVICE_INSERT) == 0) {
// could we catch this during the handler, rather than during execution?
throw new ServiceException(
"Transaction INSERT support is not enabled");
}
LOGGER.finer( "Transasction Insert:"+element );
try {
InsertRequest insert = (InsertRequest) element;
FeatureCollection collection = insert.getFeatures();
FeatureReader reader = DataUtilities.reader(collection);
FeatureType schema = store.getSchema();
// Need to use the namespace here for the lookup, due to our weird
// prefixed internal typenames. see
// http://jira.codehaus.org/secure/ViewIssue.jspa?key=GEOS-143
// Once we get our datastores making features with the correct namespaces
// we can do something like this:
// FeatureTypeInfo typeInfo = catalog.getFeatureTypeInfo(schema.getTypeName(), schema.getNamespace());
// until then (when geos-144 is resolved) we're stuck with:
FeatureTypeInfo typeInfo = catalog.getFeatureTypeInfo(element.getTypeName() );
// this is possible with the insert hack above.
LOGGER.finer("Use featureValidation to check contents of insert" );
featureValidation( typeInfo.getDataStoreInfo().getId(), schema, collection );
Set fids = store.addFeatures(reader);
build.addInsertResult(element.getHandle(), fids);
//
// Add to validation check envelope
envelope.expandToInclude(collection.getBounds());
} catch (IOException ioException) {
throw new WfsTransactionException(ioException,
element.getHandle(), request.getHandle());
}
}
if (element instanceof UpdateRequest) {
if ((request.getWFS().getServiceLevel() & WFSDTO.SERVICE_UPDATE) == 0) {
// could we catch this during the handler, rather than during execution?
throw new ServiceException(
"Transaction Update support is not enabled");
}
LOGGER.finer( "Transaction Update:"+element);
try {
UpdateRequest update = (UpdateRequest) element;
Filter filter = update.getFilter();
AttributeType[] types = update.getTypes(store.getSchema());
Object[] values = update.getValues();
DefaultQuery query = new DefaultQuery(update.getTypeName(),
filter);
// Pass through data to collect fids and damaged region
// for validation
//
Set fids = new HashSet();
LOGGER.finer("Preprocess to remember modification as a set of fids" );
FeatureReader preprocess = store.getFeatures( filter ).reader();
try {
while( preprocess.hasNext() ){
Feature feature = preprocess.next();
fids.add( feature.getID() );
envelope.expandToInclude( feature.getBounds() );
}
} catch (NoSuchElementException e) {
throw new ServiceException( "Could not aquire FeatureIDs", e );
} catch (IllegalAttributeException e) {
throw new ServiceException( "Could not aquire FeatureIDs", e );
}
finally {
preprocess.close();
}
try{
if (types.length == 1) {
store.modifyFeatures(types[0], values[0], filter);
} else {
store.modifyFeatures(types, values, filter);
}
}catch (IOException e) //DJB: this is for cite tests. We should probaby do this for all the exceptions here - throw a transaction FAIL instead of serice exception
{
//this failed - we want a FAILED not a service exception!
build = new WfsTransResponse(WfsTransResponse.FAILED,
transactionRequest.getGeoServer().isVerbose());
// add in exception details here??
build.setMessage(e.getLocalizedMessage());
response = build;
// DJB: it looks like the transaction is rolled back in writeTo()
return;
}
if ((request.getLockId() != null)
&& store instanceof FeatureLocking
&& (request.getReleaseAction() == TransactionRequest.SOME)) {
FeatureLocking locking = (FeatureLocking) store;
locking.unLockFeatures(filter);
}
// Post process - check features for changed boundary and
// pass them off to the ValidationProcessor
//
if( !fids.isEmpty() ) {
LOGGER.finer("Post process update for boundary update and featureValidation");
FidFilter modified = FilterFactory.createFilterFactory().createFidFilter();
modified.addAllFids( fids );
FeatureCollection changed = store.getFeatures( modified ).collection();
envelope.expandToInclude( changed.getBounds() );
FeatureTypeInfo typeInfo = catalog.getFeatureTypeInfo(element.getTypeName());
featureValidation(typeInfo.getDataStoreInfo().getId(),store.getSchema(), changed);
}
} catch (IOException ioException) {
throw new WfsTransactionException(ioException,
element.getHandle(), request.getHandle());
} catch (SchemaException typeException) {
throw new WfsTransactionException(typeName
+ " inconsistent with update:"
+ typeException.getMessage(), element.getHandle(),
request.getHandle());
}
}
}
// All opperations have worked thus far
//
// Time for some global Validation Checks against envelope
//
try {
integrityValidation(stores2, envelope);
} catch (Exception invalid) {
throw new WfsTransactionException(invalid);
}
// we will commit in the writeTo method
// after user has got the response
response = build;
}
|
diff --git a/modules/quercus/src/com/caucho/quercus/env/DefinitionState.java b/modules/quercus/src/com/caucho/quercus/env/DefinitionState.java
index c275fbef9..bb94a45ad 100644
--- a/modules/quercus/src/com/caucho/quercus/env/DefinitionState.java
+++ b/modules/quercus/src/com/caucho/quercus/env/DefinitionState.java
@@ -1,439 +1,442 @@
/*
* Copyright (c) 1998-2006 Caucho Technology -- all rights reserved
*
* This file is part of Resin(R) Open Source
*
* Each copy or derived work must preserve the copyright notice and this
* notice unmodified.
*
* Resin Open Source is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Resin Open Source is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty
* of NON-INFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with Resin Open Source; if not, write to the
*
* Free Software Foundation, Inc.
* 59 Temple Place, Suite 330
* Boston, MA 02111-1307 USA
*
* @author Scott Ferguson
*/
package com.caucho.quercus.env;
import com.caucho.quercus.Quercus;
import com.caucho.quercus.QuercusException;
import com.caucho.quercus.program.AbstractFunction;
import com.caucho.quercus.program.ClassDef;
import com.caucho.quercus.program.UnsetFunction;
import com.caucho.util.Crc64;
import com.caucho.util.L10N;
import com.caucho.util.LruCache;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.logging.Logger;
/**
* Represents the state of the definitions: functions, classes and
* constants.
*/
public final class DefinitionState {
private static final L10N L = new L10N(DefinitionState.class);
private static final Logger log
= Logger.getLogger(DefinitionState.class.getName());
private static final
LruCache<ClassKey,SoftReference<QuercusClass>> _classCache
= new LruCache<ClassKey,SoftReference<QuercusClass>>(4096);
private final Quercus _quercus;
private boolean _isStrict;
private HashMap<String, AbstractFunction> _funMap;
private HashMap<String, AbstractFunction> _lowerFunMap;
private HashMap<String, ClassDef> _classDefMap;
private HashMap<String, ClassDef> _lowerClassDefMap;
private boolean _isLazy;
// crc of the entries
private long _crc;
public DefinitionState(Quercus quercus)
{
_quercus = quercus;
_isStrict = quercus.isStrict();
_funMap = new HashMap<String, AbstractFunction>(256, 0.25F);
_classDefMap = new HashMap<String, ClassDef>(256, 0.25F);
if (! _isStrict) {
_lowerFunMap = new HashMap<String, AbstractFunction>(256, 0.25F);
_lowerClassDefMap = new HashMap<String, ClassDef>(256, 0.25F);
}
}
private DefinitionState(DefinitionState oldState)
{
this(oldState._quercus);
_funMap.putAll(oldState._funMap);
if (_lowerFunMap != null)
_lowerFunMap.putAll(oldState._lowerFunMap);
_classDefMap.putAll(oldState._classDefMap);
if (_lowerClassDefMap != null)
_lowerClassDefMap.putAll(oldState._lowerClassDefMap);
_crc = oldState._crc;
}
private DefinitionState(DefinitionState oldState, boolean isLazy)
{
_isLazy = true;
_quercus = oldState._quercus;
_isStrict = oldState._isStrict;
_funMap = oldState._funMap;
_lowerFunMap = oldState._lowerFunMap;
_classDefMap = oldState._classDefMap;
_lowerClassDefMap = oldState._lowerClassDefMap;
_crc = oldState._crc;
}
/**
* Returns true for strict mode.
*/
public final boolean isStrict()
{
return _isStrict;
}
/**
* Returns the owning PHP engine.
*/
public Quercus getQuercus()
{
return _quercus;
}
/**
* returns the crc.
*/
public long getCrc()
{
return _crc;
}
/**
* Returns an array of the defined functions.
*/
public ArrayValue getDefinedFunctions()
{
ArrayValue result = new ArrayValueImpl();
ArrayValue internal = _quercus.getDefinedFunctions();
ArrayValue user = new ArrayValueImpl();
result.put(new StringValueImpl("internal"), internal);
result.put(new StringValueImpl("user"), user);
for (String name : _funMap.keySet()) {
StringValue key = new StringValueImpl(name);
if (! internal.contains(key).isset())
user.put(name);
}
return result;
}
/**
* Finds the java reflection method for the function with the given name.
*
* @param name the method name
* @return the found method or null if no method found.
*/
public AbstractFunction findFunction(String name)
{
AbstractFunction fun = _funMap.get(name);
if (fun == null) {
}
else if (fun instanceof UnsetFunction) {
UnsetFunction unsetFun = (UnsetFunction) fun;
if (_crc == unsetFun.getCrc())
return null;
}
else {
return fun;
}
if (_lowerFunMap != null) {
fun = _lowerFunMap.get(name.toLowerCase());
if (fun != null) {
- _funMap.put(name, fun);
+ copyOnWrite();
+ _funMap.put(name, fun);
- return fun;
+ return fun;
}
}
fun = findModuleFunction(name);
if (fun != null) {
+ copyOnWrite();
_funMap.put(name, fun);
return fun;
}
else {
+ copyOnWrite();
_funMap.put(name, new UnsetFunction(_crc));
return null;
}
}
/**
* Finds the java reflection method for the function with the given name.
*
* @param name the method name
* @return the found method or null if no method found.
*/
private AbstractFunction findModuleFunction(String name)
{
AbstractFunction fun = null;
fun = _quercus.findFunction(name);
if (fun != null)
return fun;
return fun;
}
/**
* Adds a function, e.g. from an include.
*/
public Value addFunction(String name, AbstractFunction fun)
{
AbstractFunction oldFun = findFunction(name);
if (oldFun != null) {
throw new QuercusException(L.l("can't redefine function {0}", name));
}
copyOnWrite();
_funMap.put(name, fun);
_crc = Crc64.generate(_crc, name);
if (_lowerFunMap != null)
_lowerFunMap.put(name.toLowerCase(), fun);
return BooleanValue.TRUE;
}
/**
* Adds a function from a compiled include
*
* @param name the function name, must be an intern() string
* @param lowerName the function name, must be an intern() string
*/
public Value addFunction(String name, String lowerName, AbstractFunction fun)
{
// XXX: skip the old function check since the include for compiled
// pages is already verified. Might have a switch here?
/*
AbstractFunction oldFun = _lowerFunMap.get(lowerName);
if (oldFun == null)
oldFun = _quercus.findLowerFunctionImpl(lowerName);
if (oldFun != null) {
throw new QuercusException(L.l("can't redefine function {0}", name));
}
*/
copyOnWrite();
_funMap.put(name, fun);
_crc = Crc64.generate(_crc, name);
if (_lowerFunMap != null)
_lowerFunMap.put(lowerName, fun);
return BooleanValue.TRUE;
}
/**
* Adds a class, e.g. from an include.
*/
public void addClassDef(String name, ClassDef cl)
{
copyOnWrite();
_classDefMap.put(name, cl);
_crc = Crc64.generate(_crc, name);
if (_lowerClassDefMap != null)
_lowerClassDefMap.put(name.toLowerCase(), cl);
}
/**
* Adds a class, e.g. from an include.
*/
public ClassDef findClassDef(String name)
{
ClassDef def = _classDefMap.get(name);
if (def != null)
return def;
if (_lowerClassDefMap != null)
def = _lowerClassDefMap.get(name.toLowerCase());
return def;
}
/**
* Returns the declared classes.
*
* @return an array of the declared classes()
*/
public Value getDeclaredClasses()
{
ArrayList<String> names = new ArrayList<String>();
/*
for (String name : _classMap.keySet()) {
if (! names.contains(name))
names.add(name);
}
*/
for (String name : _classDefMap.keySet()) {
if (! names.contains(name))
names.add(name);
}
for (String name : _quercus.getClassMap().keySet()) {
if (! names.contains(name))
names.add(name);
}
Collections.sort(names);
ArrayValue array = new ArrayValueImpl();
for (String name : names) {
array.put(new StringValueImpl(name));
}
return array;
}
public DefinitionState copy()
{
return new DefinitionState(this);
}
public DefinitionState copyLazy()
{
return new DefinitionState(this, true);
}
private void copyOnWrite()
{
if (! _isLazy)
return;
_isLazy = false;
_funMap = new HashMap<String, AbstractFunction>(_funMap);
if (_lowerFunMap != null) {
_lowerFunMap = new HashMap<String, AbstractFunction>(_lowerFunMap);
}
_classDefMap = new HashMap<String, ClassDef>(_classDefMap);
if (_lowerClassDefMap != null) {
_lowerClassDefMap = new HashMap<String, ClassDef>(_lowerClassDefMap);
}
}
static class ClassKey {
private final WeakReference<ClassDef> _defRef;
private final WeakReference<QuercusClass> _parentRef;
ClassKey(ClassDef def, QuercusClass parent)
{
_defRef = new WeakReference<ClassDef>(def);
if (parent != null)
_parentRef = new WeakReference<QuercusClass>(parent);
else
_parentRef = null;
}
public int hashCode()
{
int hash = 37;
ClassDef def = _defRef.get();
QuercusClass parent = null;
if (_parentRef != null)
parent = _parentRef.get();
if (def != null)
hash = 65521 * hash + def.hashCode();
if (parent != null)
hash = 65521 * hash + parent.hashCode();
return hash;
}
public boolean equals(Object o)
{
ClassKey key = (ClassKey) o;
ClassDef aDef = _defRef.get();
ClassDef bDef = key._defRef.get();
if (aDef != bDef)
return false;
if (_parentRef == key._parentRef)
return true;
else if (_parentRef != null && key._parentRef != null)
return _parentRef.get() == key._parentRef.get();
else
return false;
}
}
}
| false | true | public AbstractFunction findFunction(String name)
{
AbstractFunction fun = _funMap.get(name);
if (fun == null) {
}
else if (fun instanceof UnsetFunction) {
UnsetFunction unsetFun = (UnsetFunction) fun;
if (_crc == unsetFun.getCrc())
return null;
}
else {
return fun;
}
if (_lowerFunMap != null) {
fun = _lowerFunMap.get(name.toLowerCase());
if (fun != null) {
_funMap.put(name, fun);
return fun;
}
}
fun = findModuleFunction(name);
if (fun != null) {
_funMap.put(name, fun);
return fun;
}
else {
_funMap.put(name, new UnsetFunction(_crc));
return null;
}
}
| public AbstractFunction findFunction(String name)
{
AbstractFunction fun = _funMap.get(name);
if (fun == null) {
}
else if (fun instanceof UnsetFunction) {
UnsetFunction unsetFun = (UnsetFunction) fun;
if (_crc == unsetFun.getCrc())
return null;
}
else {
return fun;
}
if (_lowerFunMap != null) {
fun = _lowerFunMap.get(name.toLowerCase());
if (fun != null) {
copyOnWrite();
_funMap.put(name, fun);
return fun;
}
}
fun = findModuleFunction(name);
if (fun != null) {
copyOnWrite();
_funMap.put(name, fun);
return fun;
}
else {
copyOnWrite();
_funMap.put(name, new UnsetFunction(_crc));
return null;
}
}
|
diff --git a/test/org/plovr/ManifestTest.java b/test/org/plovr/ManifestTest.java
index b180165b..fc7a28b5 100644
--- a/test/org/plovr/ManifestTest.java
+++ b/test/org/plovr/ManifestTest.java
@@ -1,137 +1,138 @@
package org.plovr;
import java.io.File;
import java.util.Collection;
import java.util.List;
import junit.framework.TestCase;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.javascript.jscomp.JSSourceFile;
/**
* {@link ManifestTest} is a unit test for {@link Manifest}.
*
* @author [email protected] (Michael Bolin)
*/
public class ManifestTest extends TestCase {
/** Converts a {@link JSSourceFile} to its name. */
private static Function<JSSourceFile, String> JS_SOURCE_FILE_TO_NAME =
new Function<JSSourceFile, String>() {
@Override
public String apply(JSSourceFile jsSourceFile) {
return jsSourceFile.getName();
}
};
/** Converts a {@link JsInput} to its name. */
private static Function<JsInput, String> JS_INPUT_TO_NAME =
new Function<JsInput, String>() {
@Override
public String apply(JsInput jsInput) {
return jsInput.getName();
}
};
public void testSimpleManifest() throws CompilationException {
File closureLibraryDirectory = new File("../closure-library/closure/goog/");
final List<File> dependencies = ImmutableList.of();
String path = "test/org/plovr/example.js";
File testFile = new File(path);
JsSourceFile requiredInput = new JsSourceFile(path, testFile);
final List<File> externs = ImmutableList.of();
final boolean customExternsOnly = false;
Manifest manifest = new Manifest(
closureLibraryDirectory,
dependencies,
ImmutableList.<JsInput>of(requiredInput),
externs,
customExternsOnly);
final ModuleConfig moduleConfig = null;
Compilation compilerArguments = manifest.getCompilerArguments(moduleConfig);
List<JSSourceFile> inputs = compilerArguments.getInputs();
List<String> expectedNames = ImmutableList.copyOf(
new String[] {
"base.js",
"/goog/debug/error.js",
"/goog/string/string.js",
"/goog/asserts/asserts.js",
"/goog/array/array.js",
"/goog/debug/entrypointregistry.js",
"/goog/debug/errorhandlerweakdep.js",
"/goog/useragent/useragent.js",
"/goog/events/browserfeature.js",
"/goog/disposable/disposable.js",
"/goog/events/event.js",
"/goog/events/eventtype.js",
+ "/goog/reflect/reflect.js",
"/goog/events/browserevent.js",
"/goog/events/eventwrapper.js",
"/goog/events/listener.js",
"/goog/structs/simplepool.js",
"/goog/useragent/jscript.js",
"/goog/events/pools.js",
"/goog/object/object.js",
"/goog/events/events.js",
"test/org/plovr/example.js"
}
);
assertEquals(expectedNames, Lists.transform(inputs, JS_SOURCE_FILE_TO_NAME));
}
public void testCompilationOrder() throws CompilationException {
File closureLibraryDirectory = new File("../closure-library/closure/goog/");
final List<File> dependencies = ImmutableList.of();
final List<File> externs = ImmutableList.of();
final boolean customExternsOnly = false;
// Set up a set of files so that there's a dependency loop of
// a -> b -> c -> a
DummyJsInput a, b, c;
a = new DummyJsInput("a", "", ImmutableList.of("a"), ImmutableList.of("b"));
b = new DummyJsInput("b", "", ImmutableList.of("b"), ImmutableList.of("c"));
c = new DummyJsInput("c", "", ImmutableList.of("c"), ImmutableList.of("a"));
Manifest manifest = new Manifest(
closureLibraryDirectory,
dependencies,
ImmutableList.<JsInput>of(a, b, c),
externs,
customExternsOnly);
List<JsInput> order;
try {
order = manifest.getInputsInCompilationOrder();
fail("Got order for unorderable inputs: " + order);
} catch (CircularDependencyException e) {
Collection<JsInput> circularDepdenency = e.getCircularDependency();
assertEquals(ImmutableList.copyOf(circularDepdenency),
ImmutableList.of(a, b, c));
}
// Now adjust c so that it no longer creates a loop
c = new DummyJsInput("c", "", ImmutableList.of("c"), null);
manifest = new Manifest(
closureLibraryDirectory,
dependencies,
ImmutableList.<JsInput>of(a, b, c),
externs,
customExternsOnly);
order = manifest.getInputsInCompilationOrder();
List<String> expectedNames = ImmutableList.of("base.js", "c", "b", "a");
assertEquals(expectedNames, Lists.transform(order, JS_INPUT_TO_NAME));
}
}
| true | true | public void testSimpleManifest() throws CompilationException {
File closureLibraryDirectory = new File("../closure-library/closure/goog/");
final List<File> dependencies = ImmutableList.of();
String path = "test/org/plovr/example.js";
File testFile = new File(path);
JsSourceFile requiredInput = new JsSourceFile(path, testFile);
final List<File> externs = ImmutableList.of();
final boolean customExternsOnly = false;
Manifest manifest = new Manifest(
closureLibraryDirectory,
dependencies,
ImmutableList.<JsInput>of(requiredInput),
externs,
customExternsOnly);
final ModuleConfig moduleConfig = null;
Compilation compilerArguments = manifest.getCompilerArguments(moduleConfig);
List<JSSourceFile> inputs = compilerArguments.getInputs();
List<String> expectedNames = ImmutableList.copyOf(
new String[] {
"base.js",
"/goog/debug/error.js",
"/goog/string/string.js",
"/goog/asserts/asserts.js",
"/goog/array/array.js",
"/goog/debug/entrypointregistry.js",
"/goog/debug/errorhandlerweakdep.js",
"/goog/useragent/useragent.js",
"/goog/events/browserfeature.js",
"/goog/disposable/disposable.js",
"/goog/events/event.js",
"/goog/events/eventtype.js",
"/goog/events/browserevent.js",
"/goog/events/eventwrapper.js",
"/goog/events/listener.js",
"/goog/structs/simplepool.js",
"/goog/useragent/jscript.js",
"/goog/events/pools.js",
"/goog/object/object.js",
"/goog/events/events.js",
"test/org/plovr/example.js"
}
);
assertEquals(expectedNames, Lists.transform(inputs, JS_SOURCE_FILE_TO_NAME));
}
| public void testSimpleManifest() throws CompilationException {
File closureLibraryDirectory = new File("../closure-library/closure/goog/");
final List<File> dependencies = ImmutableList.of();
String path = "test/org/plovr/example.js";
File testFile = new File(path);
JsSourceFile requiredInput = new JsSourceFile(path, testFile);
final List<File> externs = ImmutableList.of();
final boolean customExternsOnly = false;
Manifest manifest = new Manifest(
closureLibraryDirectory,
dependencies,
ImmutableList.<JsInput>of(requiredInput),
externs,
customExternsOnly);
final ModuleConfig moduleConfig = null;
Compilation compilerArguments = manifest.getCompilerArguments(moduleConfig);
List<JSSourceFile> inputs = compilerArguments.getInputs();
List<String> expectedNames = ImmutableList.copyOf(
new String[] {
"base.js",
"/goog/debug/error.js",
"/goog/string/string.js",
"/goog/asserts/asserts.js",
"/goog/array/array.js",
"/goog/debug/entrypointregistry.js",
"/goog/debug/errorhandlerweakdep.js",
"/goog/useragent/useragent.js",
"/goog/events/browserfeature.js",
"/goog/disposable/disposable.js",
"/goog/events/event.js",
"/goog/events/eventtype.js",
"/goog/reflect/reflect.js",
"/goog/events/browserevent.js",
"/goog/events/eventwrapper.js",
"/goog/events/listener.js",
"/goog/structs/simplepool.js",
"/goog/useragent/jscript.js",
"/goog/events/pools.js",
"/goog/object/object.js",
"/goog/events/events.js",
"test/org/plovr/example.js"
}
);
assertEquals(expectedNames, Lists.transform(inputs, JS_SOURCE_FILE_TO_NAME));
}
|
diff --git a/src/com/android/launcher2/LauncherModel.java b/src/com/android/launcher2/LauncherModel.java
index 7d620622..4ad8922f 100644
--- a/src/com/android/launcher2/LauncherModel.java
+++ b/src/com/android/launcher2/LauncherModel.java
@@ -1,1945 +1,1947 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.launcher2;
import android.app.SearchManager;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProviderInfo;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentProviderClient;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.Intent.ShortcutIconResource;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Parcelable;
import android.os.Process;
import android.os.RemoteException;
import android.os.SystemClock;
import android.util.Log;
import com.android.launcher.R;
import com.android.launcher2.InstallWidgetReceiver.WidgetMimeTypeHandlerData;
import java.lang.ref.WeakReference;
import java.net.URISyntaxException;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
/**
* Maintains in-memory state of the Launcher. It is expected that there should be only one
* LauncherModel object held in a static. Also provide APIs for updating the database state
* for the Launcher.
*/
public class LauncherModel extends BroadcastReceiver {
static final boolean DEBUG_LOADERS = false;
static final String TAG = "Launcher.Model";
private static final int ITEMS_CHUNK = 6; // batch size for the workspace icons
private final boolean mAppsCanBeOnExternalStorage;
private int mBatchSize; // 0 is all apps at once
private int mAllAppsLoadDelay; // milliseconds between batches
private final LauncherApplication mApp;
private final Object mLock = new Object();
private DeferredHandler mHandler = new DeferredHandler();
private LoaderTask mLoaderTask;
private static final HandlerThread sWorkerThread = new HandlerThread("launcher-loader");
static {
sWorkerThread.start();
}
private static final Handler sWorker = new Handler(sWorkerThread.getLooper());
// We start off with everything not loaded. After that, we assume that
// our monitoring of the package manager provides all updates and we never
// need to do a requery. These are only ever touched from the loader thread.
private boolean mWorkspaceLoaded;
private boolean mAllAppsLoaded;
private WeakReference<Callbacks> mCallbacks;
// < only access in worker thread >
private AllAppsList mAllAppsList;
// sItemsIdMap maps *all* the ItemInfos (shortcuts, folders, and widgets) created by
// LauncherModel to their ids
static final HashMap<Long, ItemInfo> sItemsIdMap = new HashMap<Long, ItemInfo>();
// sItems is passed to bindItems, which expects a list of all folders and shortcuts created by
// LauncherModel that are directly on the home screen (however, no widgets or shortcuts
// within folders).
static final ArrayList<ItemInfo> sWorkspaceItems = new ArrayList<ItemInfo>();
// sAppWidgets is all LauncherAppWidgetInfo created by LauncherModel. Passed to bindAppWidget()
static final ArrayList<LauncherAppWidgetInfo> sAppWidgets =
new ArrayList<LauncherAppWidgetInfo>();
// sFolders is all FolderInfos created by LauncherModel. Passed to bindFolders()
static final HashMap<Long, FolderInfo> sFolders = new HashMap<Long, FolderInfo>();
// sDbIconCache is the set of ItemInfos that need to have their icons updated in the database
static final HashMap<Object, byte[]> sDbIconCache = new HashMap<Object, byte[]>();
// </ only access in worker thread >
private IconCache mIconCache;
private Bitmap mDefaultIcon;
private static int mCellCountX;
private static int mCellCountY;
public interface Callbacks {
public boolean setLoadOnResume();
public int getCurrentWorkspaceScreen();
public void startBinding();
public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end);
public void bindFolders(HashMap<Long,FolderInfo> folders);
public void finishBindingItems();
public void bindAppWidget(LauncherAppWidgetInfo info);
public void bindAllApplications(ArrayList<ApplicationInfo> apps);
public void bindAppsAdded(ArrayList<ApplicationInfo> apps);
public void bindAppsUpdated(ArrayList<ApplicationInfo> apps);
public void bindAppsRemoved(ArrayList<ApplicationInfo> apps, boolean permanent);
public void bindPackagesUpdated();
public boolean isAllAppsVisible();
public void bindSearchablesChanged();
}
LauncherModel(LauncherApplication app, IconCache iconCache) {
mAppsCanBeOnExternalStorage = !Environment.isExternalStorageEmulated();
mApp = app;
mAllAppsList = new AllAppsList(iconCache);
mIconCache = iconCache;
mDefaultIcon = Utilities.createIconBitmap(
mIconCache.getFullResDefaultActivityIcon(), app);
mAllAppsLoadDelay = app.getResources().getInteger(R.integer.config_allAppsBatchLoadDelay);
mBatchSize = app.getResources().getInteger(R.integer.config_allAppsBatchSize);
}
public Bitmap getFallbackIcon() {
return Bitmap.createBitmap(mDefaultIcon);
}
public static void unbindWorkspaceItems() {
for (ItemInfo item: sWorkspaceItems) {
item.unbind();
}
}
/**
* Adds an item to the DB if it was not created previously, or move it to a new
* <container, screen, cellX, cellY>
*/
static void addOrMoveItemInDatabase(Context context, ItemInfo item, long container,
int screen, int cellX, int cellY) {
if (item.container == ItemInfo.NO_ID) {
// From all apps
addItemToDatabase(context, item, container, screen, cellX, cellY, false);
} else {
// From somewhere else
moveItemInDatabase(context, item, container, screen, cellX, cellY);
}
}
/**
* Move an item in the DB to a new <container, screen, cellX, cellY>
*/
static void moveItemInDatabase(Context context, final ItemInfo item, final long container,
final int screen, final int cellX, final int cellY) {
item.container = container;
item.cellX = cellX;
item.cellY = cellY;
// We store hotseat items in canonical form which is this orientation invariant position
// in the hotseat
if (context instanceof Launcher && screen < 0 &&
container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
item.screen = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
} else {
item.screen = screen;
}
final Uri uri = LauncherSettings.Favorites.getContentUri(item.id, false);
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
values.put(LauncherSettings.Favorites.CONTAINER, item.container);
values.put(LauncherSettings.Favorites.CELLX, item.cellX);
values.put(LauncherSettings.Favorites.CELLY, item.cellY);
values.put(LauncherSettings.Favorites.SCREEN, item.screen);
sWorker.post(new Runnable() {
public void run() {
cr.update(uri, values, null, null);
ItemInfo modelItem = sItemsIdMap.get(item.id);
if (item != modelItem) {
// the modelItem needs to match up perfectly with item if our model is to be
// consistent with the database-- for now, just require modelItem == item
String msg = "item: " + ((item != null) ? item.toString() : "null") +
"modelItem: " + ((modelItem != null) ? modelItem.toString() : "null") +
"Error: ItemInfo passed to moveItemInDatabase doesn't match original";
throw new RuntimeException(msg);
}
// Items are added/removed from the corresponding FolderInfo elsewhere, such
// as in Workspace.onDrop. Here, we just add/remove them from the list of items
// that are on the desktop, as appropriate
if (modelItem.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
modelItem.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
if (!sWorkspaceItems.contains(modelItem)) {
sWorkspaceItems.add(modelItem);
}
} else {
sWorkspaceItems.remove(modelItem);
}
}
});
}
/**
* Resize an item in the DB to a new <spanX, spanY, cellX, cellY>
*/
static void resizeItemInDatabase(Context context, final ItemInfo item, final int cellX,
final int cellY, final int spanX, final int spanY) {
item.spanX = spanX;
item.spanY = spanY;
item.cellX = cellX;
item.cellY = cellY;
final Uri uri = LauncherSettings.Favorites.getContentUri(item.id, false);
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
values.put(LauncherSettings.Favorites.CONTAINER, item.container);
values.put(LauncherSettings.Favorites.SPANX, spanX);
values.put(LauncherSettings.Favorites.SPANY, spanY);
values.put(LauncherSettings.Favorites.CELLX, cellX);
values.put(LauncherSettings.Favorites.CELLY, cellY);
sWorker.post(new Runnable() {
public void run() {
cr.update(uri, values, null, null);
ItemInfo modelItem = sItemsIdMap.get(item.id);
if (item != modelItem) {
// the modelItem needs to match up perfectly with item if our model is to be
// consistent with the database-- for now, just require modelItem == item
String msg = "item: " + ((item != null) ? item.toString() : "null") +
"modelItem: " + ((modelItem != null) ? modelItem.toString() : "null") +
"Error: ItemInfo passed to resizeItemInDatabase doesn't match original";
throw new RuntimeException(msg);
}
}
});
}
/**
* Returns true if the shortcuts already exists in the database.
* we identify a shortcut by its title and intent.
*/
static boolean shortcutExists(Context context, String title, Intent intent) {
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
new String[] { "title", "intent" }, "title=? and intent=?",
new String[] { title, intent.toUri(0) }, null);
boolean result = false;
try {
result = c.moveToFirst();
} finally {
c.close();
}
return result;
}
/**
* Returns an ItemInfo array containing all the items in the LauncherModel.
* The ItemInfo.id is not set through this function.
*/
static ArrayList<ItemInfo> getItemsInLocalCoordinates(Context context) {
ArrayList<ItemInfo> items = new ArrayList<ItemInfo>();
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] {
LauncherSettings.Favorites.ITEM_TYPE, LauncherSettings.Favorites.CONTAINER,
LauncherSettings.Favorites.SCREEN, LauncherSettings.Favorites.CELLX, LauncherSettings.Favorites.CELLY,
LauncherSettings.Favorites.SPANX, LauncherSettings.Favorites.SPANY }, null, null, null);
final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
final int spanXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANX);
final int spanYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANY);
try {
while (c.moveToNext()) {
ItemInfo item = new ItemInfo();
item.cellX = c.getInt(cellXIndex);
item.cellY = c.getInt(cellYIndex);
item.spanX = c.getInt(spanXIndex);
item.spanY = c.getInt(spanYIndex);
item.container = c.getInt(containerIndex);
item.itemType = c.getInt(itemTypeIndex);
item.screen = c.getInt(screenIndex);
items.add(item);
}
} catch (Exception e) {
items.clear();
} finally {
c.close();
}
return items;
}
/**
* Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
*/
FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) {
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
"_id=? and (itemType=? or itemType=?)",
new String[] { String.valueOf(id),
String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)}, null);
try {
if (c.moveToFirst()) {
final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
FolderInfo folderInfo = null;
switch (c.getInt(itemTypeIndex)) {
case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
folderInfo = findOrMakeFolder(folderList, id);
break;
}
folderInfo.title = c.getString(titleIndex);
folderInfo.id = id;
folderInfo.container = c.getInt(containerIndex);
folderInfo.screen = c.getInt(screenIndex);
folderInfo.cellX = c.getInt(cellXIndex);
folderInfo.cellY = c.getInt(cellYIndex);
return folderInfo;
}
} finally {
c.close();
}
return null;
}
/**
* Add an item to the database in a specified container. Sets the container, screen, cellX and
* cellY fields of the item. Also assigns an ID to the item.
*/
static void addItemToDatabase(Context context, final ItemInfo item, final long container,
final int screen, final int cellX, final int cellY, final boolean notify) {
item.container = container;
item.cellX = cellX;
item.cellY = cellY;
// We store hotseat items in canonical form which is this orientation invariant position
// in the hotseat
if (context instanceof Launcher && screen < 0 &&
container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
item.screen = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
} else {
item.screen = screen;
}
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
item.onAddToDatabase(values);
LauncherApplication app = (LauncherApplication) context.getApplicationContext();
item.id = app.getLauncherProvider().generateNewId();
values.put(LauncherSettings.Favorites._ID, item.id);
item.updateValuesWithCoordinates(values, item.cellX, item.cellY);
sWorker.post(new Runnable() {
public void run() {
cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI :
LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values);
if (sItemsIdMap.containsKey(item.id)) {
// we should not be adding new items in the db with the same id
throw new RuntimeException("Error: ItemInfo id (" + item.id + ") passed to " +
"addItemToDatabase already exists." + item.toString());
}
sItemsIdMap.put(item.id, item);
switch (item.itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
sFolders.put(item.id, (FolderInfo) item);
// Fall through
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
sWorkspaceItems.add(item);
}
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
sAppWidgets.add((LauncherAppWidgetInfo) item);
break;
}
}
});
}
/**
* Creates a new unique child id, for a given cell span across all layouts.
*/
static int getCellLayoutChildId(
long container, int screen, int localCellX, int localCellY, int spanX, int spanY) {
return (((int) container & 0xFF) << 24)
| (screen & 0xFF) << 16 | (localCellX & 0xFF) << 8 | (localCellY & 0xFF);
}
static int getCellCountX() {
return mCellCountX;
}
static int getCellCountY() {
return mCellCountY;
}
/**
* Updates the model orientation helper to take into account the current layout dimensions
* when performing local/canonical coordinate transformations.
*/
static void updateWorkspaceLayoutCells(int shortAxisCellCount, int longAxisCellCount) {
mCellCountX = shortAxisCellCount;
mCellCountY = longAxisCellCount;
}
/**
* Update an item to the database in a specified container.
*/
static void updateItemInDatabase(Context context, final ItemInfo item) {
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
item.onAddToDatabase(values);
item.updateValuesWithCoordinates(values, item.cellX, item.cellY);
sWorker.post(new Runnable() {
public void run() {
cr.update(LauncherSettings.Favorites.getContentUri(item.id, false),
values, null, null);
final ItemInfo modelItem = sItemsIdMap.get(item.id);
if (item != modelItem) {
// the modelItem needs to match up perfectly with item if our model is to be
// consistent with the database-- for now, just require modelItem == item
String msg = "item: " + ((item != null) ? item.toString() : "null") +
"modelItem: " + ((modelItem != null) ? modelItem.toString() : "null") +
"Error: ItemInfo passed to updateItemInDatabase doesn't match original";
throw new RuntimeException(msg);
}
}
});
}
/**
* Removes the specified item from the database
* @param context
* @param item
*/
static void deleteItemFromDatabase(Context context, final ItemInfo item) {
final ContentResolver cr = context.getContentResolver();
final Uri uriToDelete = LauncherSettings.Favorites.getContentUri(item.id, false);
sWorker.post(new Runnable() {
public void run() {
cr.delete(uriToDelete, null, null);
switch (item.itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
sFolders.remove(item.id);
sWorkspaceItems.remove(item);
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
sWorkspaceItems.remove(item);
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
sAppWidgets.remove((LauncherAppWidgetInfo) item);
break;
}
sItemsIdMap.remove(item.id);
sDbIconCache.remove(item);
}
});
}
/**
* Remove the contents of the specified folder from the database
*/
static void deleteFolderContentsFromDatabase(Context context, final FolderInfo info) {
final ContentResolver cr = context.getContentResolver();
sWorker.post(new Runnable() {
public void run() {
cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null);
sItemsIdMap.remove(info.id);
sFolders.remove(info.id);
sDbIconCache.remove(info);
sWorkspaceItems.remove(info);
cr.delete(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
for (ItemInfo childInfo : info.contents) {
sItemsIdMap.remove(childInfo.id);
sDbIconCache.remove(childInfo);
}
}
});
}
/**
* Set this as the current Launcher activity object for the loader.
*/
public void initialize(Callbacks callbacks) {
synchronized (mLock) {
mCallbacks = new WeakReference<Callbacks>(callbacks);
}
}
/**
* Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
* ACTION_PACKAGE_CHANGED.
*/
@Override
public void onReceive(Context context, Intent intent) {
if (DEBUG_LOADERS) Log.d(TAG, "onReceive intent=" + intent);
final String action = intent.getAction();
if (Intent.ACTION_PACKAGE_CHANGED.equals(action)
|| Intent.ACTION_PACKAGE_REMOVED.equals(action)
|| Intent.ACTION_PACKAGE_ADDED.equals(action)) {
final String packageName = intent.getData().getSchemeSpecificPart();
final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
int op = PackageUpdatedTask.OP_NONE;
if (packageName == null || packageName.length() == 0) {
// they sent us a bad intent
return;
}
if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
op = PackageUpdatedTask.OP_UPDATE;
} else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
if (!replacing) {
op = PackageUpdatedTask.OP_REMOVE;
}
// else, we are replacing the package, so a PACKAGE_ADDED will be sent
// later, we will update the package at this time
} else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
if (!replacing) {
op = PackageUpdatedTask.OP_ADD;
} else {
op = PackageUpdatedTask.OP_UPDATE;
}
}
if (op != PackageUpdatedTask.OP_NONE) {
enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName }));
}
} else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
// First, schedule to add these apps back in.
String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_ADD, packages));
// Then, rebind everything.
startLoaderFromBackground();
} else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
enqueuePackageUpdated(new PackageUpdatedTask(
PackageUpdatedTask.OP_UNAVAILABLE, packages));
} else if (Intent.ACTION_LOCALE_CHANGED.equals(action)) {
// If we have changed locale we need to clear out the labels in all apps.
// Do this here because if the launcher activity is running it will be restarted.
// If it's not running startLoaderFromBackground will merely tell it that it needs
// to reload. Either way, mAllAppsLoaded will be cleared so it re-reads everything
// next time.
mAllAppsLoaded = false;
mWorkspaceLoaded = false;
startLoaderFromBackground();
} else if (SearchManager.INTENT_GLOBAL_SEARCH_ACTIVITY_CHANGED.equals(action) ||
SearchManager.INTENT_ACTION_SEARCHABLES_CHANGED.equals(action)) {
- Callbacks callbacks = mCallbacks.get();
- if (callbacks != null) {
- callbacks.bindSearchablesChanged();
+ if (mCallbacks != null) {
+ Callbacks callbacks = mCallbacks.get();
+ if (callbacks != null) {
+ callbacks.bindSearchablesChanged();
+ }
}
}
}
/**
* When the launcher is in the background, it's possible for it to miss paired
* configuration changes. So whenever we trigger the loader from the background
* tell the launcher that it needs to re-run the loader when it comes back instead
* of doing it now.
*/
public void startLoaderFromBackground() {
boolean runLoader = false;
if (mCallbacks != null) {
Callbacks callbacks = mCallbacks.get();
if (callbacks != null) {
// Only actually run the loader if they're not paused.
if (!callbacks.setLoadOnResume()) {
runLoader = true;
}
}
}
if (runLoader) {
startLoader(mApp, false);
}
}
public void startLoader(Context context, boolean isLaunching) {
synchronized (mLock) {
if (DEBUG_LOADERS) {
Log.d(TAG, "startLoader isLaunching=" + isLaunching);
}
// Don't bother to start the thread if we know it's not going to do anything
if (mCallbacks != null && mCallbacks.get() != null) {
// If there is already one running, tell it to stop.
LoaderTask oldTask = mLoaderTask;
if (oldTask != null) {
if (oldTask.isLaunching()) {
// don't downgrade isLaunching if we're already running
isLaunching = true;
}
oldTask.stopLocked();
}
mLoaderTask = new LoaderTask(context, isLaunching);
sWorker.post(mLoaderTask);
}
}
}
public void stopLoader() {
synchronized (mLock) {
if (mLoaderTask != null) {
mLoaderTask.stopLocked();
}
}
}
public boolean isAllAppsLoaded() {
return mAllAppsLoaded;
}
/**
* Runnable for the thread that loads the contents of the launcher:
* - workspace icons
* - widgets
* - all apps icons
*/
private class LoaderTask implements Runnable {
private Context mContext;
private Thread mWaitThread;
private boolean mIsLaunching;
private boolean mStopped;
private boolean mLoadAndBindStepFinished;
private HashMap<Object, CharSequence> mLabelCache;
LoaderTask(Context context, boolean isLaunching) {
mContext = context;
mIsLaunching = isLaunching;
mLabelCache = new HashMap<Object, CharSequence>();
}
boolean isLaunching() {
return mIsLaunching;
}
private void loadAndBindWorkspace() {
// Load the workspace
if (DEBUG_LOADERS) {
Log.d(TAG, "loadAndBindWorkspace mWorkspaceLoaded=" + mWorkspaceLoaded);
}
if (!mWorkspaceLoaded) {
loadWorkspace();
if (mStopped) {
return;
}
mWorkspaceLoaded = true;
}
// Bind the workspace
bindWorkspace();
}
private void waitForIdle() {
// Wait until the either we're stopped or the other threads are done.
// This way we don't start loading all apps until the workspace has settled
// down.
synchronized (LoaderTask.this) {
final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
mHandler.postIdle(new Runnable() {
public void run() {
synchronized (LoaderTask.this) {
mLoadAndBindStepFinished = true;
if (DEBUG_LOADERS) {
Log.d(TAG, "done with previous binding step");
}
LoaderTask.this.notify();
}
}
});
while (!mStopped && !mLoadAndBindStepFinished) {
try {
this.wait();
} catch (InterruptedException ex) {
// Ignore
}
}
if (DEBUG_LOADERS) {
Log.d(TAG, "waited "
+ (SystemClock.uptimeMillis()-workspaceWaitTime)
+ "ms for previous step to finish binding");
}
}
}
public void run() {
// Optimize for end-user experience: if the Launcher is up and // running with the
// All Apps interface in the foreground, load All Apps first. Otherwise, load the
// workspace first (default).
final Callbacks cbk = mCallbacks.get();
final boolean loadWorkspaceFirst = cbk != null ? (!cbk.isAllAppsVisible()) : true;
keep_running: {
// Elevate priority when Home launches for the first time to avoid
// starving at boot time. Staring at a blank home is not cool.
synchronized (mLock) {
if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to " +
(mIsLaunching ? "DEFAULT" : "BACKGROUND"));
android.os.Process.setThreadPriority(mIsLaunching
? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
}
if (loadWorkspaceFirst) {
if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace");
loadAndBindWorkspace();
} else {
if (DEBUG_LOADERS) Log.d(TAG, "step 1: special: loading all apps");
loadAndBindAllApps();
}
if (mStopped) {
break keep_running;
}
// Whew! Hard work done. Slow us down, and wait until the UI thread has
// settled down.
synchronized (mLock) {
if (mIsLaunching) {
if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to BACKGROUND");
android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
}
}
waitForIdle();
// second step
if (loadWorkspaceFirst) {
if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps");
loadAndBindAllApps();
} else {
if (DEBUG_LOADERS) Log.d(TAG, "step 2: special: loading workspace");
loadAndBindWorkspace();
}
}
// Update the saved icons if necessary
if (DEBUG_LOADERS) Log.d(TAG, "Comparing loaded icons to database icons");
for (Object key : sDbIconCache.keySet()) {
updateSavedIcon(mContext, (ShortcutInfo) key, sDbIconCache.get(key));
}
sDbIconCache.clear();
// Clear out this reference, otherwise we end up holding it until all of the
// callback runnables are done.
mContext = null;
synchronized (mLock) {
// If we are still the last one to be scheduled, remove ourselves.
if (mLoaderTask == this) {
mLoaderTask = null;
}
}
}
public void stopLocked() {
synchronized (LoaderTask.this) {
mStopped = true;
this.notify();
}
}
/**
* Gets the callbacks object. If we've been stopped, or if the launcher object
* has somehow been garbage collected, return null instead. Pass in the Callbacks
* object that was around when the deferred message was scheduled, and if there's
* a new Callbacks object around then also return null. This will save us from
* calling onto it with data that will be ignored.
*/
Callbacks tryGetCallbacks(Callbacks oldCallbacks) {
synchronized (mLock) {
if (mStopped) {
return null;
}
if (mCallbacks == null) {
return null;
}
final Callbacks callbacks = mCallbacks.get();
if (callbacks != oldCallbacks) {
return null;
}
if (callbacks == null) {
Log.w(TAG, "no mCallbacks");
return null;
}
return callbacks;
}
}
// check & update map of what's occupied; used to discard overlapping/invalid items
private boolean checkItemPlacement(ItemInfo occupied[][][], ItemInfo item) {
int containerIndex = item.screen;
if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
// We use the last index to refer to the hotseat
containerIndex = Launcher.SCREEN_COUNT;
// Return early if we detect that an item is under the hotseat button
if (Hotseat.isAllAppsButtonRank(item.screen)) {
return false;
}
} else if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
// Skip further checking if it is not the hotseat or workspace container
return true;
}
for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
if (occupied[containerIndex][x][y] != null) {
Log.e(TAG, "Error loading shortcut " + item
+ " into cell (" + containerIndex + "-" + item.screen + ":"
+ x + "," + y
+ ") occupied by "
+ occupied[containerIndex][x][y]);
return false;
}
}
}
for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
occupied[containerIndex][x][y] = item;
}
}
return true;
}
private void loadWorkspace() {
final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
final Context context = mContext;
final ContentResolver contentResolver = context.getContentResolver();
final PackageManager manager = context.getPackageManager();
final AppWidgetManager widgets = AppWidgetManager.getInstance(context);
final boolean isSafeMode = manager.isSafeMode();
sWorkspaceItems.clear();
sAppWidgets.clear();
sFolders.clear();
sItemsIdMap.clear();
sDbIconCache.clear();
final ArrayList<Long> itemsToRemove = new ArrayList<Long>();
final Cursor c = contentResolver.query(
LauncherSettings.Favorites.CONTENT_URI, null, null, null, null);
// +1 for the hotseat (it can be larger than the workspace)
final ItemInfo occupied[][][] =
new ItemInfo[Launcher.SCREEN_COUNT + 1][mCellCountX + 1][mCellCountY + 1];
try {
final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
final int intentIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.INTENT);
final int titleIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.TITLE);
final int iconTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_TYPE);
final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
final int iconPackageIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_PACKAGE);
final int iconResourceIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_RESOURCE);
final int containerIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.CONTAINER);
final int itemTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ITEM_TYPE);
final int appWidgetIdIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.APPWIDGET_ID);
final int screenIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLY);
final int spanXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.SPANX);
final int spanYIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SPANY);
final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
final int displayModeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.DISPLAY_MODE);
ShortcutInfo info;
String intentDescription;
LauncherAppWidgetInfo appWidgetInfo;
int container;
long id;
Intent intent;
while (!mStopped && c.moveToNext()) {
try {
int itemType = c.getInt(itemTypeIndex);
switch (itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
intentDescription = c.getString(intentIndex);
try {
intent = Intent.parseUri(intentDescription, 0);
} catch (URISyntaxException e) {
continue;
}
if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
info = getShortcutInfo(manager, intent, context, c, iconIndex,
titleIndex, mLabelCache);
} else {
info = getShortcutInfo(c, context, iconTypeIndex,
iconPackageIndex, iconResourceIndex, iconIndex,
titleIndex);
}
if (info != null) {
info.intent = intent;
info.id = c.getLong(idIndex);
container = c.getInt(containerIndex);
info.container = container;
info.screen = c.getInt(screenIndex);
info.cellX = c.getInt(cellXIndex);
info.cellY = c.getInt(cellYIndex);
// check & update map of what's occupied
if (!checkItemPlacement(occupied, info)) {
break;
}
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
sWorkspaceItems.add(info);
break;
default:
// Item is in a user folder
FolderInfo folderInfo =
findOrMakeFolder(sFolders, container);
folderInfo.add(info);
break;
}
sItemsIdMap.put(info.id, info);
// now that we've loaded everthing re-save it with the
// icon in case it disappears somehow.
queueIconToBeChecked(sDbIconCache, info, c, iconIndex);
} else {
// Failed to load the shortcut, probably because the
// activity manager couldn't resolve it (maybe the app
// was uninstalled), or the db row was somehow screwed up.
// Delete it.
id = c.getLong(idIndex);
Log.e(TAG, "Error loading shortcut " + id + ", removing it");
contentResolver.delete(LauncherSettings.Favorites.getContentUri(
id, false), null, null);
}
break;
case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
id = c.getLong(idIndex);
FolderInfo folderInfo = findOrMakeFolder(sFolders, id);
folderInfo.title = c.getString(titleIndex);
folderInfo.id = id;
container = c.getInt(containerIndex);
folderInfo.container = container;
folderInfo.screen = c.getInt(screenIndex);
folderInfo.cellX = c.getInt(cellXIndex);
folderInfo.cellY = c.getInt(cellYIndex);
// check & update map of what's occupied
if (!checkItemPlacement(occupied, folderInfo)) {
break;
}
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
sWorkspaceItems.add(folderInfo);
break;
}
sItemsIdMap.put(folderInfo.id, folderInfo);
sFolders.put(folderInfo.id, folderInfo);
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
// Read all Launcher-specific widget details
int appWidgetId = c.getInt(appWidgetIdIndex);
id = c.getLong(idIndex);
final AppWidgetProviderInfo provider =
widgets.getAppWidgetInfo(appWidgetId);
if (!isSafeMode && (provider == null || provider.provider == null ||
provider.provider.getPackageName() == null)) {
Log.e(TAG, "Deleting widget that isn't installed anymore: id="
+ id + " appWidgetId=" + appWidgetId);
itemsToRemove.add(id);
} else {
appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId);
appWidgetInfo.id = id;
appWidgetInfo.screen = c.getInt(screenIndex);
appWidgetInfo.cellX = c.getInt(cellXIndex);
appWidgetInfo.cellY = c.getInt(cellYIndex);
appWidgetInfo.spanX = c.getInt(spanXIndex);
appWidgetInfo.spanY = c.getInt(spanYIndex);
container = c.getInt(containerIndex);
if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Log.e(TAG, "Widget found where container "
+ "!= CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!");
continue;
}
appWidgetInfo.container = c.getInt(containerIndex);
// check & update map of what's occupied
if (!checkItemPlacement(occupied, appWidgetInfo)) {
break;
}
sItemsIdMap.put(appWidgetInfo.id, appWidgetInfo);
sAppWidgets.add(appWidgetInfo);
}
break;
}
} catch (Exception e) {
Log.w(TAG, "Desktop items loading interrupted:", e);
}
}
} finally {
c.close();
}
if (itemsToRemove.size() > 0) {
ContentProviderClient client = contentResolver.acquireContentProviderClient(
LauncherSettings.Favorites.CONTENT_URI);
// Remove dead items
for (long id : itemsToRemove) {
if (DEBUG_LOADERS) {
Log.d(TAG, "Removed id = " + id);
}
// Don't notify content observers
try {
client.delete(LauncherSettings.Favorites.getContentUri(id, false),
null, null);
} catch (RemoteException e) {
Log.w(TAG, "Could not remove id = " + id);
}
}
}
if (DEBUG_LOADERS) {
Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
Log.d(TAG, "workspace layout: ");
for (int y = 0; y < mCellCountY; y++) {
String line = "";
for (int s = 0; s < Launcher.SCREEN_COUNT; s++) {
if (s > 0) {
line += " | ";
}
for (int x = 0; x < mCellCountX; x++) {
line += ((occupied[s][x][y] != null) ? "#" : ".");
}
}
Log.d(TAG, "[ " + line + " ]");
}
}
}
/**
* Read everything out of our database.
*/
private void bindWorkspace() {
final long t = SystemClock.uptimeMillis();
// Don't use these two variables in any of the callback runnables.
// Otherwise we hold a reference to them.
final Callbacks oldCallbacks = mCallbacks.get();
if (oldCallbacks == null) {
// This launcher has exited and nobody bothered to tell us. Just bail.
Log.w(TAG, "LoaderTask running with no launcher");
return;
}
int N;
// Tell the workspace that we're about to start firing items at it
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.startBinding();
}
}
});
// Add the items to the workspace.
N = sWorkspaceItems.size();
for (int i=0; i<N; i+=ITEMS_CHUNK) {
final int start = i;
final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindItems(sWorkspaceItems, start, start+chunkSize);
}
}
});
}
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindFolders(sFolders);
}
}
});
// Wait until the queue goes empty.
mHandler.post(new Runnable() {
public void run() {
if (DEBUG_LOADERS) {
Log.d(TAG, "Going to start binding widgets soon.");
}
}
});
// Bind the widgets, one at a time.
// WARNING: this is calling into the workspace from the background thread,
// but since getCurrentScreen() just returns the int, we should be okay. This
// is just a hint for the order, and if it's wrong, we'll be okay.
// TODO: instead, we should have that push the current screen into here.
final int currentScreen = oldCallbacks.getCurrentWorkspaceScreen();
N = sAppWidgets.size();
// once for the current screen
for (int i=0; i<N; i++) {
final LauncherAppWidgetInfo widget = sAppWidgets.get(i);
if (widget.screen == currentScreen) {
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindAppWidget(widget);
}
}
});
}
}
// once for the other screens
for (int i=0; i<N; i++) {
final LauncherAppWidgetInfo widget = sAppWidgets.get(i);
if (widget.screen != currentScreen) {
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindAppWidget(widget);
}
}
});
}
}
// Tell the workspace that we're done.
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.finishBindingItems();
}
}
});
// If we're profiling, this is the last thing in the queue.
mHandler.post(new Runnable() {
public void run() {
if (DEBUG_LOADERS) {
Log.d(TAG, "bound workspace in "
+ (SystemClock.uptimeMillis()-t) + "ms");
}
}
});
}
private void loadAndBindAllApps() {
if (DEBUG_LOADERS) {
Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded);
}
if (!mAllAppsLoaded) {
loadAllAppsByBatch();
if (mStopped) {
return;
}
mAllAppsLoaded = true;
} else {
onlyBindAllApps();
}
}
private void onlyBindAllApps() {
final Callbacks oldCallbacks = mCallbacks.get();
if (oldCallbacks == null) {
// This launcher has exited and nobody bothered to tell us. Just bail.
Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)");
return;
}
// shallow copy
final ArrayList<ApplicationInfo> list
= (ArrayList<ApplicationInfo>)mAllAppsList.data.clone();
mHandler.post(new Runnable() {
public void run() {
final long t = SystemClock.uptimeMillis();
final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindAllApplications(list);
}
if (DEBUG_LOADERS) {
Log.d(TAG, "bound all " + list.size() + " apps from cache in "
+ (SystemClock.uptimeMillis()-t) + "ms");
}
}
});
}
private void loadAllAppsByBatch() {
final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
// Don't use these two variables in any of the callback runnables.
// Otherwise we hold a reference to them.
final Callbacks oldCallbacks = mCallbacks.get();
if (oldCallbacks == null) {
// This launcher has exited and nobody bothered to tell us. Just bail.
Log.w(TAG, "LoaderTask running with no launcher (loadAllAppsByBatch)");
return;
}
final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
final PackageManager packageManager = mContext.getPackageManager();
List<ResolveInfo> apps = null;
int N = Integer.MAX_VALUE;
int startIndex;
int i=0;
int batchSize = -1;
while (i < N && !mStopped) {
if (i == 0) {
mAllAppsList.clear();
final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
apps = packageManager.queryIntentActivities(mainIntent, 0);
if (DEBUG_LOADERS) {
Log.d(TAG, "queryIntentActivities took "
+ (SystemClock.uptimeMillis()-qiaTime) + "ms");
}
if (apps == null) {
return;
}
N = apps.size();
if (DEBUG_LOADERS) {
Log.d(TAG, "queryIntentActivities got " + N + " apps");
}
if (N == 0) {
// There are no apps?!?
return;
}
if (mBatchSize == 0) {
batchSize = N;
} else {
batchSize = mBatchSize;
}
final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Collections.sort(apps,
new LauncherModel.ShortcutNameComparator(packageManager, mLabelCache));
if (DEBUG_LOADERS) {
Log.d(TAG, "sort took "
+ (SystemClock.uptimeMillis()-sortTime) + "ms");
}
}
final long t2 = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
startIndex = i;
for (int j=0; i<N && j<batchSize; j++) {
// This builds the icon bitmaps.
mAllAppsList.add(new ApplicationInfo(packageManager, apps.get(i),
mIconCache, mLabelCache));
i++;
}
final boolean first = i <= batchSize;
final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
final ArrayList<ApplicationInfo> added = mAllAppsList.added;
mAllAppsList.added = new ArrayList<ApplicationInfo>();
mHandler.post(new Runnable() {
public void run() {
final long t = SystemClock.uptimeMillis();
if (callbacks != null) {
if (first) {
callbacks.bindAllApplications(added);
} else {
callbacks.bindAppsAdded(added);
}
if (DEBUG_LOADERS) {
Log.d(TAG, "bound " + added.size() + " apps in "
+ (SystemClock.uptimeMillis() - t) + "ms");
}
} else {
Log.i(TAG, "not binding apps: no Launcher activity");
}
}
});
if (DEBUG_LOADERS) {
Log.d(TAG, "batch of " + (i-startIndex) + " icons processed in "
+ (SystemClock.uptimeMillis()-t2) + "ms");
}
if (mAllAppsLoadDelay > 0 && i < N) {
try {
if (DEBUG_LOADERS) {
Log.d(TAG, "sleeping for " + mAllAppsLoadDelay + "ms");
}
Thread.sleep(mAllAppsLoadDelay);
} catch (InterruptedException exc) { }
}
}
if (DEBUG_LOADERS) {
Log.d(TAG, "cached all " + N + " apps in "
+ (SystemClock.uptimeMillis()-t) + "ms"
+ (mAllAppsLoadDelay > 0 ? " (including delay)" : ""));
}
}
public void dumpState() {
Log.d(TAG, "mLoaderTask.mContext=" + mContext);
Log.d(TAG, "mLoaderTask.mWaitThread=" + mWaitThread);
Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching);
Log.d(TAG, "mLoaderTask.mStopped=" + mStopped);
Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished);
Log.d(TAG, "mItems size=" + sWorkspaceItems.size());
}
}
void enqueuePackageUpdated(PackageUpdatedTask task) {
sWorker.post(task);
}
private class PackageUpdatedTask implements Runnable {
int mOp;
String[] mPackages;
public static final int OP_NONE = 0;
public static final int OP_ADD = 1;
public static final int OP_UPDATE = 2;
public static final int OP_REMOVE = 3; // uninstlled
public static final int OP_UNAVAILABLE = 4; // external media unmounted
public PackageUpdatedTask(int op, String[] packages) {
mOp = op;
mPackages = packages;
}
public void run() {
final Context context = mApp;
final String[] packages = mPackages;
final int N = packages.length;
switch (mOp) {
case OP_ADD:
for (int i=0; i<N; i++) {
if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]);
mAllAppsList.addPackage(context, packages[i]);
}
break;
case OP_UPDATE:
for (int i=0; i<N; i++) {
if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]);
mAllAppsList.updatePackage(context, packages[i]);
}
break;
case OP_REMOVE:
case OP_UNAVAILABLE:
for (int i=0; i<N; i++) {
if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
mAllAppsList.removePackage(packages[i]);
}
break;
}
ArrayList<ApplicationInfo> added = null;
ArrayList<ApplicationInfo> removed = null;
ArrayList<ApplicationInfo> modified = null;
if (mAllAppsList.added.size() > 0) {
added = mAllAppsList.added;
mAllAppsList.added = new ArrayList<ApplicationInfo>();
}
if (mAllAppsList.removed.size() > 0) {
removed = mAllAppsList.removed;
mAllAppsList.removed = new ArrayList<ApplicationInfo>();
for (ApplicationInfo info: removed) {
mIconCache.remove(info.intent.getComponent());
}
}
if (mAllAppsList.modified.size() > 0) {
modified = mAllAppsList.modified;
mAllAppsList.modified = new ArrayList<ApplicationInfo>();
}
final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == null) {
Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading.");
return;
}
if (added != null) {
final ArrayList<ApplicationInfo> addedFinal = added;
mHandler.post(new Runnable() {
public void run() {
Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == cb && cb != null) {
callbacks.bindAppsAdded(addedFinal);
}
}
});
}
if (modified != null) {
final ArrayList<ApplicationInfo> modifiedFinal = modified;
mHandler.post(new Runnable() {
public void run() {
Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == cb && cb != null) {
callbacks.bindAppsUpdated(modifiedFinal);
}
}
});
}
if (removed != null) {
final boolean permanent = mOp != OP_UNAVAILABLE;
final ArrayList<ApplicationInfo> removedFinal = removed;
mHandler.post(new Runnable() {
public void run() {
Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == cb && cb != null) {
callbacks.bindAppsRemoved(removedFinal, permanent);
}
}
});
}
mHandler.post(new Runnable() {
@Override
public void run() {
Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == cb && cb != null) {
callbacks.bindPackagesUpdated();
}
}
});
}
}
/**
* This is called from the code that adds shortcuts from the intent receiver. This
* doesn't have a Cursor, but
*/
public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context) {
return getShortcutInfo(manager, intent, context, null, -1, -1, null);
}
/**
* Make an ShortcutInfo object for a shortcut that is an application.
*
* If c is not null, then it will be used to fill in missing data like the title and icon.
*/
public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context,
Cursor c, int iconIndex, int titleIndex, HashMap<Object, CharSequence> labelCache) {
Bitmap icon = null;
final ShortcutInfo info = new ShortcutInfo();
ComponentName componentName = intent.getComponent();
if (componentName == null) {
return null;
}
// TODO: See if the PackageManager knows about this case. If it doesn't
// then return null & delete this.
// the resource -- This may implicitly give us back the fallback icon,
// but don't worry about that. All we're doing with usingFallbackIcon is
// to avoid saving lots of copies of that in the database, and most apps
// have icons anyway.
final ResolveInfo resolveInfo = manager.resolveActivity(intent, 0);
if (resolveInfo != null) {
icon = mIconCache.getIcon(componentName, resolveInfo, labelCache);
}
// the db
if (icon == null) {
if (c != null) {
icon = getIconFromCursor(c, iconIndex, context);
}
}
// the fallback icon
if (icon == null) {
icon = getFallbackIcon();
info.usingFallbackIcon = true;
}
info.setIcon(icon);
// from the resource
if (resolveInfo != null) {
ComponentName key = LauncherModel.getComponentNameFromResolveInfo(resolveInfo);
if (labelCache != null && labelCache.containsKey(key)) {
info.title = labelCache.get(key);
} else {
info.title = resolveInfo.activityInfo.loadLabel(manager);
if (labelCache != null) {
labelCache.put(key, info.title);
}
}
}
// from the db
if (info.title == null) {
if (c != null) {
info.title = c.getString(titleIndex);
}
}
// fall back to the class name of the activity
if (info.title == null) {
info.title = componentName.getClassName();
}
info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
return info;
}
/**
* Make an ShortcutInfo object for a shortcut that isn't an application.
*/
private ShortcutInfo getShortcutInfo(Cursor c, Context context,
int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex,
int titleIndex) {
Bitmap icon = null;
final ShortcutInfo info = new ShortcutInfo();
info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
// TODO: If there's an explicit component and we can't install that, delete it.
info.title = c.getString(titleIndex);
int iconType = c.getInt(iconTypeIndex);
switch (iconType) {
case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
String packageName = c.getString(iconPackageIndex);
String resourceName = c.getString(iconResourceIndex);
PackageManager packageManager = context.getPackageManager();
info.customIcon = false;
// the resource
try {
Resources resources = packageManager.getResourcesForApplication(packageName);
if (resources != null) {
final int id = resources.getIdentifier(resourceName, null, null);
icon = Utilities.createIconBitmap(
mIconCache.getFullResIcon(resources, id), context);
}
} catch (Exception e) {
// drop this. we have other places to look for icons
}
// the db
if (icon == null) {
icon = getIconFromCursor(c, iconIndex, context);
}
// the fallback icon
if (icon == null) {
icon = getFallbackIcon();
info.usingFallbackIcon = true;
}
break;
case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
icon = getIconFromCursor(c, iconIndex, context);
if (icon == null) {
icon = getFallbackIcon();
info.customIcon = false;
info.usingFallbackIcon = true;
} else {
info.customIcon = true;
}
break;
default:
icon = getFallbackIcon();
info.usingFallbackIcon = true;
info.customIcon = false;
break;
}
info.setIcon(icon);
return info;
}
Bitmap getIconFromCursor(Cursor c, int iconIndex, Context context) {
if (false) {
Log.d(TAG, "getIconFromCursor app="
+ c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE)));
}
byte[] data = c.getBlob(iconIndex);
try {
return Utilities.createIconBitmap(
BitmapFactory.decodeByteArray(data, 0, data.length), context);
} catch (Exception e) {
return null;
}
}
ShortcutInfo addShortcut(Context context, Intent data, long container, int screen,
int cellX, int cellY, boolean notify) {
final ShortcutInfo info = infoFromShortcutIntent(context, data, null);
addItemToDatabase(context, info, container, screen, cellX, cellY, notify);
return info;
}
/**
* Attempts to find an AppWidgetProviderInfo that matches the given component.
*/
AppWidgetProviderInfo findAppWidgetProviderInfoWithComponent(Context context,
ComponentName component) {
List<AppWidgetProviderInfo> widgets =
AppWidgetManager.getInstance(context).getInstalledProviders();
for (AppWidgetProviderInfo info : widgets) {
if (info.provider.equals(component)) {
return info;
}
}
return null;
}
/**
* Returns a list of all the widgets that can handle configuration with a particular mimeType.
*/
List<WidgetMimeTypeHandlerData> resolveWidgetsForMimeType(Context context, String mimeType) {
final PackageManager packageManager = context.getPackageManager();
final List<WidgetMimeTypeHandlerData> supportedConfigurationActivities =
new ArrayList<WidgetMimeTypeHandlerData>();
final Intent supportsIntent =
new Intent(InstallWidgetReceiver.ACTION_SUPPORTS_CLIPDATA_MIMETYPE);
supportsIntent.setType(mimeType);
// Create a set of widget configuration components that we can test against
final List<AppWidgetProviderInfo> widgets =
AppWidgetManager.getInstance(context).getInstalledProviders();
final HashMap<ComponentName, AppWidgetProviderInfo> configurationComponentToWidget =
new HashMap<ComponentName, AppWidgetProviderInfo>();
for (AppWidgetProviderInfo info : widgets) {
configurationComponentToWidget.put(info.configure, info);
}
// Run through each of the intents that can handle this type of clip data, and cross
// reference them with the components that are actual configuration components
final List<ResolveInfo> activities = packageManager.queryIntentActivities(supportsIntent,
PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo info : activities) {
final ActivityInfo activityInfo = info.activityInfo;
final ComponentName infoComponent = new ComponentName(activityInfo.packageName,
activityInfo.name);
if (configurationComponentToWidget.containsKey(infoComponent)) {
supportedConfigurationActivities.add(
new InstallWidgetReceiver.WidgetMimeTypeHandlerData(info,
configurationComponentToWidget.get(infoComponent)));
}
}
return supportedConfigurationActivities;
}
ShortcutInfo infoFromShortcutIntent(Context context, Intent data, Bitmap fallbackIcon) {
Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
Bitmap icon = null;
boolean customIcon = false;
ShortcutIconResource iconResource = null;
if (bitmap != null && bitmap instanceof Bitmap) {
icon = Utilities.createIconBitmap(new FastBitmapDrawable((Bitmap)bitmap), context);
customIcon = true;
} else {
Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
if (extra != null && extra instanceof ShortcutIconResource) {
try {
iconResource = (ShortcutIconResource) extra;
final PackageManager packageManager = context.getPackageManager();
Resources resources = packageManager.getResourcesForApplication(
iconResource.packageName);
final int id = resources.getIdentifier(iconResource.resourceName, null, null);
icon = Utilities.createIconBitmap(
mIconCache.getFullResIcon(resources, id), context);
} catch (Exception e) {
Log.w(TAG, "Could not load shortcut icon: " + extra);
}
}
}
final ShortcutInfo info = new ShortcutInfo();
if (icon == null) {
if (fallbackIcon != null) {
icon = fallbackIcon;
} else {
icon = getFallbackIcon();
info.usingFallbackIcon = true;
}
}
info.setIcon(icon);
info.title = name;
info.intent = intent;
info.customIcon = customIcon;
info.iconResource = iconResource;
return info;
}
boolean queueIconToBeChecked(HashMap<Object, byte[]> cache, ShortcutInfo info, Cursor c,
int iconIndex) {
// If apps can't be on SD, don't even bother.
if (!mAppsCanBeOnExternalStorage) {
return false;
}
// If this icon doesn't have a custom icon, check to see
// what's stored in the DB, and if it doesn't match what
// we're going to show, store what we are going to show back
// into the DB. We do this so when we're loading, if the
// package manager can't find an icon (for example because
// the app is on SD) then we can use that instead.
if (!info.customIcon && !info.usingFallbackIcon) {
cache.put(info, c.getBlob(iconIndex));
return true;
}
return false;
}
void updateSavedIcon(Context context, ShortcutInfo info, byte[] data) {
boolean needSave = false;
try {
if (data != null) {
Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length);
Bitmap loaded = info.getIcon(mIconCache);
needSave = !saved.sameAs(loaded);
} else {
needSave = true;
}
} catch (Exception e) {
needSave = true;
}
if (needSave) {
Log.d(TAG, "going to save icon bitmap for info=" + info);
// This is slower than is ideal, but this only happens once
// or when the app is updated with a new icon.
updateItemInDatabase(context, info);
}
}
/**
* Return an existing FolderInfo object if we have encountered this ID previously,
* or make a new one.
*/
private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) {
// See if a placeholder was created for us already
FolderInfo folderInfo = folders.get(id);
if (folderInfo == null) {
// No placeholder -- create a new instance
folderInfo = new FolderInfo();
folders.put(id, folderInfo);
}
return folderInfo;
}
private static final Collator sCollator = Collator.getInstance();
public static final Comparator<ApplicationInfo> APP_NAME_COMPARATOR
= new Comparator<ApplicationInfo>() {
public final int compare(ApplicationInfo a, ApplicationInfo b) {
int result = sCollator.compare(a.title.toString(), b.title.toString());
if (result == 0) {
result = a.componentName.compareTo(b.componentName);
}
return result;
}
};
public static final Comparator<ApplicationInfo> APP_INSTALL_TIME_COMPARATOR
= new Comparator<ApplicationInfo>() {
public final int compare(ApplicationInfo a, ApplicationInfo b) {
if (a.firstInstallTime < b.firstInstallTime) return 1;
if (a.firstInstallTime > b.firstInstallTime) return -1;
return 0;
}
};
public static final Comparator<AppWidgetProviderInfo> WIDGET_NAME_COMPARATOR
= new Comparator<AppWidgetProviderInfo>() {
public final int compare(AppWidgetProviderInfo a, AppWidgetProviderInfo b) {
return sCollator.compare(a.label.toString(), b.label.toString());
}
};
static ComponentName getComponentNameFromResolveInfo(ResolveInfo info) {
if (info.activityInfo != null) {
return new ComponentName(info.activityInfo.packageName, info.activityInfo.name);
} else {
return new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name);
}
}
public static class ShortcutNameComparator implements Comparator<ResolveInfo> {
private PackageManager mPackageManager;
private HashMap<Object, CharSequence> mLabelCache;
ShortcutNameComparator(PackageManager pm) {
mPackageManager = pm;
mLabelCache = new HashMap<Object, CharSequence>();
}
ShortcutNameComparator(PackageManager pm, HashMap<Object, CharSequence> labelCache) {
mPackageManager = pm;
mLabelCache = labelCache;
}
public final int compare(ResolveInfo a, ResolveInfo b) {
CharSequence labelA, labelB;
ComponentName keyA = LauncherModel.getComponentNameFromResolveInfo(a);
ComponentName keyB = LauncherModel.getComponentNameFromResolveInfo(b);
if (mLabelCache.containsKey(keyA)) {
labelA = mLabelCache.get(keyA);
} else {
labelA = a.loadLabel(mPackageManager).toString();
mLabelCache.put(keyA, labelA);
}
if (mLabelCache.containsKey(keyB)) {
labelB = mLabelCache.get(keyB);
} else {
labelB = b.loadLabel(mPackageManager).toString();
mLabelCache.put(keyB, labelB);
}
return sCollator.compare(labelA, labelB);
}
};
public static class WidgetAndShortcutNameComparator implements Comparator<Object> {
private PackageManager mPackageManager;
private HashMap<Object, String> mLabelCache;
WidgetAndShortcutNameComparator(PackageManager pm) {
mPackageManager = pm;
mLabelCache = new HashMap<Object, String>();
}
public final int compare(Object a, Object b) {
String labelA, labelB;
if (mLabelCache.containsKey(a)) {
labelA = mLabelCache.get(a);
} else {
labelA = (a instanceof AppWidgetProviderInfo) ?
((AppWidgetProviderInfo) a).label :
((ResolveInfo) a).loadLabel(mPackageManager).toString();
mLabelCache.put(a, labelA);
}
if (mLabelCache.containsKey(b)) {
labelB = mLabelCache.get(b);
} else {
labelB = (b instanceof AppWidgetProviderInfo) ?
((AppWidgetProviderInfo) b).label :
((ResolveInfo) b).loadLabel(mPackageManager).toString();
mLabelCache.put(b, labelB);
}
return sCollator.compare(labelA, labelB);
}
};
public void dumpState() {
Log.d(TAG, "mCallbacks=" + mCallbacks);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mAllAppsList.data);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mAllAppsList.added);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mAllAppsList.removed);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mAllAppsList.modified);
if (mLoaderTask != null) {
mLoaderTask.dumpState();
} else {
Log.d(TAG, "mLoaderTask=null");
}
}
}
| true | true | static boolean shortcutExists(Context context, String title, Intent intent) {
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
new String[] { "title", "intent" }, "title=? and intent=?",
new String[] { title, intent.toUri(0) }, null);
boolean result = false;
try {
result = c.moveToFirst();
} finally {
c.close();
}
return result;
}
/**
* Returns an ItemInfo array containing all the items in the LauncherModel.
* The ItemInfo.id is not set through this function.
*/
static ArrayList<ItemInfo> getItemsInLocalCoordinates(Context context) {
ArrayList<ItemInfo> items = new ArrayList<ItemInfo>();
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] {
LauncherSettings.Favorites.ITEM_TYPE, LauncherSettings.Favorites.CONTAINER,
LauncherSettings.Favorites.SCREEN, LauncherSettings.Favorites.CELLX, LauncherSettings.Favorites.CELLY,
LauncherSettings.Favorites.SPANX, LauncherSettings.Favorites.SPANY }, null, null, null);
final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
final int spanXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANX);
final int spanYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANY);
try {
while (c.moveToNext()) {
ItemInfo item = new ItemInfo();
item.cellX = c.getInt(cellXIndex);
item.cellY = c.getInt(cellYIndex);
item.spanX = c.getInt(spanXIndex);
item.spanY = c.getInt(spanYIndex);
item.container = c.getInt(containerIndex);
item.itemType = c.getInt(itemTypeIndex);
item.screen = c.getInt(screenIndex);
items.add(item);
}
} catch (Exception e) {
items.clear();
} finally {
c.close();
}
return items;
}
/**
* Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
*/
FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) {
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
"_id=? and (itemType=? or itemType=?)",
new String[] { String.valueOf(id),
String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)}, null);
try {
if (c.moveToFirst()) {
final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
FolderInfo folderInfo = null;
switch (c.getInt(itemTypeIndex)) {
case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
folderInfo = findOrMakeFolder(folderList, id);
break;
}
folderInfo.title = c.getString(titleIndex);
folderInfo.id = id;
folderInfo.container = c.getInt(containerIndex);
folderInfo.screen = c.getInt(screenIndex);
folderInfo.cellX = c.getInt(cellXIndex);
folderInfo.cellY = c.getInt(cellYIndex);
return folderInfo;
}
} finally {
c.close();
}
return null;
}
/**
* Add an item to the database in a specified container. Sets the container, screen, cellX and
* cellY fields of the item. Also assigns an ID to the item.
*/
static void addItemToDatabase(Context context, final ItemInfo item, final long container,
final int screen, final int cellX, final int cellY, final boolean notify) {
item.container = container;
item.cellX = cellX;
item.cellY = cellY;
// We store hotseat items in canonical form which is this orientation invariant position
// in the hotseat
if (context instanceof Launcher && screen < 0 &&
container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
item.screen = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
} else {
item.screen = screen;
}
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
item.onAddToDatabase(values);
LauncherApplication app = (LauncherApplication) context.getApplicationContext();
item.id = app.getLauncherProvider().generateNewId();
values.put(LauncherSettings.Favorites._ID, item.id);
item.updateValuesWithCoordinates(values, item.cellX, item.cellY);
sWorker.post(new Runnable() {
public void run() {
cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI :
LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values);
if (sItemsIdMap.containsKey(item.id)) {
// we should not be adding new items in the db with the same id
throw new RuntimeException("Error: ItemInfo id (" + item.id + ") passed to " +
"addItemToDatabase already exists." + item.toString());
}
sItemsIdMap.put(item.id, item);
switch (item.itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
sFolders.put(item.id, (FolderInfo) item);
// Fall through
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
sWorkspaceItems.add(item);
}
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
sAppWidgets.add((LauncherAppWidgetInfo) item);
break;
}
}
});
}
/**
* Creates a new unique child id, for a given cell span across all layouts.
*/
static int getCellLayoutChildId(
long container, int screen, int localCellX, int localCellY, int spanX, int spanY) {
return (((int) container & 0xFF) << 24)
| (screen & 0xFF) << 16 | (localCellX & 0xFF) << 8 | (localCellY & 0xFF);
}
static int getCellCountX() {
return mCellCountX;
}
static int getCellCountY() {
return mCellCountY;
}
/**
* Updates the model orientation helper to take into account the current layout dimensions
* when performing local/canonical coordinate transformations.
*/
static void updateWorkspaceLayoutCells(int shortAxisCellCount, int longAxisCellCount) {
mCellCountX = shortAxisCellCount;
mCellCountY = longAxisCellCount;
}
/**
* Update an item to the database in a specified container.
*/
static void updateItemInDatabase(Context context, final ItemInfo item) {
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
item.onAddToDatabase(values);
item.updateValuesWithCoordinates(values, item.cellX, item.cellY);
sWorker.post(new Runnable() {
public void run() {
cr.update(LauncherSettings.Favorites.getContentUri(item.id, false),
values, null, null);
final ItemInfo modelItem = sItemsIdMap.get(item.id);
if (item != modelItem) {
// the modelItem needs to match up perfectly with item if our model is to be
// consistent with the database-- for now, just require modelItem == item
String msg = "item: " + ((item != null) ? item.toString() : "null") +
"modelItem: " + ((modelItem != null) ? modelItem.toString() : "null") +
"Error: ItemInfo passed to updateItemInDatabase doesn't match original";
throw new RuntimeException(msg);
}
}
});
}
/**
* Removes the specified item from the database
* @param context
* @param item
*/
static void deleteItemFromDatabase(Context context, final ItemInfo item) {
final ContentResolver cr = context.getContentResolver();
final Uri uriToDelete = LauncherSettings.Favorites.getContentUri(item.id, false);
sWorker.post(new Runnable() {
public void run() {
cr.delete(uriToDelete, null, null);
switch (item.itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
sFolders.remove(item.id);
sWorkspaceItems.remove(item);
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
sWorkspaceItems.remove(item);
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
sAppWidgets.remove((LauncherAppWidgetInfo) item);
break;
}
sItemsIdMap.remove(item.id);
sDbIconCache.remove(item);
}
});
}
/**
* Remove the contents of the specified folder from the database
*/
static void deleteFolderContentsFromDatabase(Context context, final FolderInfo info) {
final ContentResolver cr = context.getContentResolver();
sWorker.post(new Runnable() {
public void run() {
cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null);
sItemsIdMap.remove(info.id);
sFolders.remove(info.id);
sDbIconCache.remove(info);
sWorkspaceItems.remove(info);
cr.delete(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
for (ItemInfo childInfo : info.contents) {
sItemsIdMap.remove(childInfo.id);
sDbIconCache.remove(childInfo);
}
}
});
}
/**
* Set this as the current Launcher activity object for the loader.
*/
public void initialize(Callbacks callbacks) {
synchronized (mLock) {
mCallbacks = new WeakReference<Callbacks>(callbacks);
}
}
/**
* Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
* ACTION_PACKAGE_CHANGED.
*/
@Override
public void onReceive(Context context, Intent intent) {
if (DEBUG_LOADERS) Log.d(TAG, "onReceive intent=" + intent);
final String action = intent.getAction();
if (Intent.ACTION_PACKAGE_CHANGED.equals(action)
|| Intent.ACTION_PACKAGE_REMOVED.equals(action)
|| Intent.ACTION_PACKAGE_ADDED.equals(action)) {
final String packageName = intent.getData().getSchemeSpecificPart();
final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
int op = PackageUpdatedTask.OP_NONE;
if (packageName == null || packageName.length() == 0) {
// they sent us a bad intent
return;
}
if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
op = PackageUpdatedTask.OP_UPDATE;
} else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
if (!replacing) {
op = PackageUpdatedTask.OP_REMOVE;
}
// else, we are replacing the package, so a PACKAGE_ADDED will be sent
// later, we will update the package at this time
} else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
if (!replacing) {
op = PackageUpdatedTask.OP_ADD;
} else {
op = PackageUpdatedTask.OP_UPDATE;
}
}
if (op != PackageUpdatedTask.OP_NONE) {
enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName }));
}
} else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
// First, schedule to add these apps back in.
String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_ADD, packages));
// Then, rebind everything.
startLoaderFromBackground();
} else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
enqueuePackageUpdated(new PackageUpdatedTask(
PackageUpdatedTask.OP_UNAVAILABLE, packages));
} else if (Intent.ACTION_LOCALE_CHANGED.equals(action)) {
// If we have changed locale we need to clear out the labels in all apps.
// Do this here because if the launcher activity is running it will be restarted.
// If it's not running startLoaderFromBackground will merely tell it that it needs
// to reload. Either way, mAllAppsLoaded will be cleared so it re-reads everything
// next time.
mAllAppsLoaded = false;
mWorkspaceLoaded = false;
startLoaderFromBackground();
} else if (SearchManager.INTENT_GLOBAL_SEARCH_ACTIVITY_CHANGED.equals(action) ||
SearchManager.INTENT_ACTION_SEARCHABLES_CHANGED.equals(action)) {
Callbacks callbacks = mCallbacks.get();
if (callbacks != null) {
callbacks.bindSearchablesChanged();
}
}
}
/**
* When the launcher is in the background, it's possible for it to miss paired
* configuration changes. So whenever we trigger the loader from the background
* tell the launcher that it needs to re-run the loader when it comes back instead
* of doing it now.
*/
public void startLoaderFromBackground() {
boolean runLoader = false;
if (mCallbacks != null) {
Callbacks callbacks = mCallbacks.get();
if (callbacks != null) {
// Only actually run the loader if they're not paused.
if (!callbacks.setLoadOnResume()) {
runLoader = true;
}
}
}
if (runLoader) {
startLoader(mApp, false);
}
}
public void startLoader(Context context, boolean isLaunching) {
synchronized (mLock) {
if (DEBUG_LOADERS) {
Log.d(TAG, "startLoader isLaunching=" + isLaunching);
}
// Don't bother to start the thread if we know it's not going to do anything
if (mCallbacks != null && mCallbacks.get() != null) {
// If there is already one running, tell it to stop.
LoaderTask oldTask = mLoaderTask;
if (oldTask != null) {
if (oldTask.isLaunching()) {
// don't downgrade isLaunching if we're already running
isLaunching = true;
}
oldTask.stopLocked();
}
mLoaderTask = new LoaderTask(context, isLaunching);
sWorker.post(mLoaderTask);
}
}
}
public void stopLoader() {
synchronized (mLock) {
if (mLoaderTask != null) {
mLoaderTask.stopLocked();
}
}
}
public boolean isAllAppsLoaded() {
return mAllAppsLoaded;
}
/**
* Runnable for the thread that loads the contents of the launcher:
* - workspace icons
* - widgets
* - all apps icons
*/
private class LoaderTask implements Runnable {
private Context mContext;
private Thread mWaitThread;
private boolean mIsLaunching;
private boolean mStopped;
private boolean mLoadAndBindStepFinished;
private HashMap<Object, CharSequence> mLabelCache;
LoaderTask(Context context, boolean isLaunching) {
mContext = context;
mIsLaunching = isLaunching;
mLabelCache = new HashMap<Object, CharSequence>();
}
boolean isLaunching() {
return mIsLaunching;
}
private void loadAndBindWorkspace() {
// Load the workspace
if (DEBUG_LOADERS) {
Log.d(TAG, "loadAndBindWorkspace mWorkspaceLoaded=" + mWorkspaceLoaded);
}
if (!mWorkspaceLoaded) {
loadWorkspace();
if (mStopped) {
return;
}
mWorkspaceLoaded = true;
}
// Bind the workspace
bindWorkspace();
}
private void waitForIdle() {
// Wait until the either we're stopped or the other threads are done.
// This way we don't start loading all apps until the workspace has settled
// down.
synchronized (LoaderTask.this) {
final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
mHandler.postIdle(new Runnable() {
public void run() {
synchronized (LoaderTask.this) {
mLoadAndBindStepFinished = true;
if (DEBUG_LOADERS) {
Log.d(TAG, "done with previous binding step");
}
LoaderTask.this.notify();
}
}
});
while (!mStopped && !mLoadAndBindStepFinished) {
try {
this.wait();
} catch (InterruptedException ex) {
// Ignore
}
}
if (DEBUG_LOADERS) {
Log.d(TAG, "waited "
+ (SystemClock.uptimeMillis()-workspaceWaitTime)
+ "ms for previous step to finish binding");
}
}
}
public void run() {
// Optimize for end-user experience: if the Launcher is up and // running with the
// All Apps interface in the foreground, load All Apps first. Otherwise, load the
// workspace first (default).
final Callbacks cbk = mCallbacks.get();
final boolean loadWorkspaceFirst = cbk != null ? (!cbk.isAllAppsVisible()) : true;
keep_running: {
// Elevate priority when Home launches for the first time to avoid
// starving at boot time. Staring at a blank home is not cool.
synchronized (mLock) {
if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to " +
(mIsLaunching ? "DEFAULT" : "BACKGROUND"));
android.os.Process.setThreadPriority(mIsLaunching
? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
}
if (loadWorkspaceFirst) {
if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace");
loadAndBindWorkspace();
} else {
if (DEBUG_LOADERS) Log.d(TAG, "step 1: special: loading all apps");
loadAndBindAllApps();
}
if (mStopped) {
break keep_running;
}
// Whew! Hard work done. Slow us down, and wait until the UI thread has
// settled down.
synchronized (mLock) {
if (mIsLaunching) {
if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to BACKGROUND");
android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
}
}
waitForIdle();
// second step
if (loadWorkspaceFirst) {
if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps");
loadAndBindAllApps();
} else {
if (DEBUG_LOADERS) Log.d(TAG, "step 2: special: loading workspace");
loadAndBindWorkspace();
}
}
// Update the saved icons if necessary
if (DEBUG_LOADERS) Log.d(TAG, "Comparing loaded icons to database icons");
for (Object key : sDbIconCache.keySet()) {
updateSavedIcon(mContext, (ShortcutInfo) key, sDbIconCache.get(key));
}
sDbIconCache.clear();
// Clear out this reference, otherwise we end up holding it until all of the
// callback runnables are done.
mContext = null;
synchronized (mLock) {
// If we are still the last one to be scheduled, remove ourselves.
if (mLoaderTask == this) {
mLoaderTask = null;
}
}
}
public void stopLocked() {
synchronized (LoaderTask.this) {
mStopped = true;
this.notify();
}
}
/**
* Gets the callbacks object. If we've been stopped, or if the launcher object
* has somehow been garbage collected, return null instead. Pass in the Callbacks
* object that was around when the deferred message was scheduled, and if there's
* a new Callbacks object around then also return null. This will save us from
* calling onto it with data that will be ignored.
*/
Callbacks tryGetCallbacks(Callbacks oldCallbacks) {
synchronized (mLock) {
if (mStopped) {
return null;
}
if (mCallbacks == null) {
return null;
}
final Callbacks callbacks = mCallbacks.get();
if (callbacks != oldCallbacks) {
return null;
}
if (callbacks == null) {
Log.w(TAG, "no mCallbacks");
return null;
}
return callbacks;
}
}
// check & update map of what's occupied; used to discard overlapping/invalid items
private boolean checkItemPlacement(ItemInfo occupied[][][], ItemInfo item) {
int containerIndex = item.screen;
if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
// We use the last index to refer to the hotseat
containerIndex = Launcher.SCREEN_COUNT;
// Return early if we detect that an item is under the hotseat button
if (Hotseat.isAllAppsButtonRank(item.screen)) {
return false;
}
} else if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
// Skip further checking if it is not the hotseat or workspace container
return true;
}
for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
if (occupied[containerIndex][x][y] != null) {
Log.e(TAG, "Error loading shortcut " + item
+ " into cell (" + containerIndex + "-" + item.screen + ":"
+ x + "," + y
+ ") occupied by "
+ occupied[containerIndex][x][y]);
return false;
}
}
}
for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
occupied[containerIndex][x][y] = item;
}
}
return true;
}
private void loadWorkspace() {
final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
final Context context = mContext;
final ContentResolver contentResolver = context.getContentResolver();
final PackageManager manager = context.getPackageManager();
final AppWidgetManager widgets = AppWidgetManager.getInstance(context);
final boolean isSafeMode = manager.isSafeMode();
sWorkspaceItems.clear();
sAppWidgets.clear();
sFolders.clear();
sItemsIdMap.clear();
sDbIconCache.clear();
final ArrayList<Long> itemsToRemove = new ArrayList<Long>();
final Cursor c = contentResolver.query(
LauncherSettings.Favorites.CONTENT_URI, null, null, null, null);
// +1 for the hotseat (it can be larger than the workspace)
final ItemInfo occupied[][][] =
new ItemInfo[Launcher.SCREEN_COUNT + 1][mCellCountX + 1][mCellCountY + 1];
try {
final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
final int intentIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.INTENT);
final int titleIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.TITLE);
final int iconTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_TYPE);
final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
final int iconPackageIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_PACKAGE);
final int iconResourceIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_RESOURCE);
final int containerIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.CONTAINER);
final int itemTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ITEM_TYPE);
final int appWidgetIdIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.APPWIDGET_ID);
final int screenIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLY);
final int spanXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.SPANX);
final int spanYIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SPANY);
final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
final int displayModeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.DISPLAY_MODE);
ShortcutInfo info;
String intentDescription;
LauncherAppWidgetInfo appWidgetInfo;
int container;
long id;
Intent intent;
while (!mStopped && c.moveToNext()) {
try {
int itemType = c.getInt(itemTypeIndex);
switch (itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
intentDescription = c.getString(intentIndex);
try {
intent = Intent.parseUri(intentDescription, 0);
} catch (URISyntaxException e) {
continue;
}
if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
info = getShortcutInfo(manager, intent, context, c, iconIndex,
titleIndex, mLabelCache);
} else {
info = getShortcutInfo(c, context, iconTypeIndex,
iconPackageIndex, iconResourceIndex, iconIndex,
titleIndex);
}
if (info != null) {
info.intent = intent;
info.id = c.getLong(idIndex);
container = c.getInt(containerIndex);
info.container = container;
info.screen = c.getInt(screenIndex);
info.cellX = c.getInt(cellXIndex);
info.cellY = c.getInt(cellYIndex);
// check & update map of what's occupied
if (!checkItemPlacement(occupied, info)) {
break;
}
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
sWorkspaceItems.add(info);
break;
default:
// Item is in a user folder
FolderInfo folderInfo =
findOrMakeFolder(sFolders, container);
folderInfo.add(info);
break;
}
sItemsIdMap.put(info.id, info);
// now that we've loaded everthing re-save it with the
// icon in case it disappears somehow.
queueIconToBeChecked(sDbIconCache, info, c, iconIndex);
} else {
// Failed to load the shortcut, probably because the
// activity manager couldn't resolve it (maybe the app
// was uninstalled), or the db row was somehow screwed up.
// Delete it.
id = c.getLong(idIndex);
Log.e(TAG, "Error loading shortcut " + id + ", removing it");
contentResolver.delete(LauncherSettings.Favorites.getContentUri(
id, false), null, null);
}
break;
case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
id = c.getLong(idIndex);
FolderInfo folderInfo = findOrMakeFolder(sFolders, id);
folderInfo.title = c.getString(titleIndex);
folderInfo.id = id;
container = c.getInt(containerIndex);
folderInfo.container = container;
folderInfo.screen = c.getInt(screenIndex);
folderInfo.cellX = c.getInt(cellXIndex);
folderInfo.cellY = c.getInt(cellYIndex);
// check & update map of what's occupied
if (!checkItemPlacement(occupied, folderInfo)) {
break;
}
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
sWorkspaceItems.add(folderInfo);
break;
}
sItemsIdMap.put(folderInfo.id, folderInfo);
sFolders.put(folderInfo.id, folderInfo);
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
// Read all Launcher-specific widget details
int appWidgetId = c.getInt(appWidgetIdIndex);
id = c.getLong(idIndex);
final AppWidgetProviderInfo provider =
widgets.getAppWidgetInfo(appWidgetId);
if (!isSafeMode && (provider == null || provider.provider == null ||
provider.provider.getPackageName() == null)) {
Log.e(TAG, "Deleting widget that isn't installed anymore: id="
+ id + " appWidgetId=" + appWidgetId);
itemsToRemove.add(id);
} else {
appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId);
appWidgetInfo.id = id;
appWidgetInfo.screen = c.getInt(screenIndex);
appWidgetInfo.cellX = c.getInt(cellXIndex);
appWidgetInfo.cellY = c.getInt(cellYIndex);
appWidgetInfo.spanX = c.getInt(spanXIndex);
appWidgetInfo.spanY = c.getInt(spanYIndex);
container = c.getInt(containerIndex);
if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Log.e(TAG, "Widget found where container "
+ "!= CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!");
continue;
}
appWidgetInfo.container = c.getInt(containerIndex);
// check & update map of what's occupied
if (!checkItemPlacement(occupied, appWidgetInfo)) {
break;
}
sItemsIdMap.put(appWidgetInfo.id, appWidgetInfo);
sAppWidgets.add(appWidgetInfo);
}
break;
}
} catch (Exception e) {
Log.w(TAG, "Desktop items loading interrupted:", e);
}
}
} finally {
c.close();
}
if (itemsToRemove.size() > 0) {
ContentProviderClient client = contentResolver.acquireContentProviderClient(
LauncherSettings.Favorites.CONTENT_URI);
// Remove dead items
for (long id : itemsToRemove) {
if (DEBUG_LOADERS) {
Log.d(TAG, "Removed id = " + id);
}
// Don't notify content observers
try {
client.delete(LauncherSettings.Favorites.getContentUri(id, false),
null, null);
} catch (RemoteException e) {
Log.w(TAG, "Could not remove id = " + id);
}
}
}
if (DEBUG_LOADERS) {
Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
Log.d(TAG, "workspace layout: ");
for (int y = 0; y < mCellCountY; y++) {
String line = "";
for (int s = 0; s < Launcher.SCREEN_COUNT; s++) {
if (s > 0) {
line += " | ";
}
for (int x = 0; x < mCellCountX; x++) {
line += ((occupied[s][x][y] != null) ? "#" : ".");
}
}
Log.d(TAG, "[ " + line + " ]");
}
}
}
/**
* Read everything out of our database.
*/
private void bindWorkspace() {
final long t = SystemClock.uptimeMillis();
// Don't use these two variables in any of the callback runnables.
// Otherwise we hold a reference to them.
final Callbacks oldCallbacks = mCallbacks.get();
if (oldCallbacks == null) {
// This launcher has exited and nobody bothered to tell us. Just bail.
Log.w(TAG, "LoaderTask running with no launcher");
return;
}
int N;
// Tell the workspace that we're about to start firing items at it
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.startBinding();
}
}
});
// Add the items to the workspace.
N = sWorkspaceItems.size();
for (int i=0; i<N; i+=ITEMS_CHUNK) {
final int start = i;
final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindItems(sWorkspaceItems, start, start+chunkSize);
}
}
});
}
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindFolders(sFolders);
}
}
});
// Wait until the queue goes empty.
mHandler.post(new Runnable() {
public void run() {
if (DEBUG_LOADERS) {
Log.d(TAG, "Going to start binding widgets soon.");
}
}
});
// Bind the widgets, one at a time.
// WARNING: this is calling into the workspace from the background thread,
// but since getCurrentScreen() just returns the int, we should be okay. This
// is just a hint for the order, and if it's wrong, we'll be okay.
// TODO: instead, we should have that push the current screen into here.
final int currentScreen = oldCallbacks.getCurrentWorkspaceScreen();
N = sAppWidgets.size();
// once for the current screen
for (int i=0; i<N; i++) {
final LauncherAppWidgetInfo widget = sAppWidgets.get(i);
if (widget.screen == currentScreen) {
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindAppWidget(widget);
}
}
});
}
}
// once for the other screens
for (int i=0; i<N; i++) {
final LauncherAppWidgetInfo widget = sAppWidgets.get(i);
if (widget.screen != currentScreen) {
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindAppWidget(widget);
}
}
});
}
}
// Tell the workspace that we're done.
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.finishBindingItems();
}
}
});
// If we're profiling, this is the last thing in the queue.
mHandler.post(new Runnable() {
public void run() {
if (DEBUG_LOADERS) {
Log.d(TAG, "bound workspace in "
+ (SystemClock.uptimeMillis()-t) + "ms");
}
}
});
}
private void loadAndBindAllApps() {
if (DEBUG_LOADERS) {
Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded);
}
if (!mAllAppsLoaded) {
loadAllAppsByBatch();
if (mStopped) {
return;
}
mAllAppsLoaded = true;
} else {
onlyBindAllApps();
}
}
private void onlyBindAllApps() {
final Callbacks oldCallbacks = mCallbacks.get();
if (oldCallbacks == null) {
// This launcher has exited and nobody bothered to tell us. Just bail.
Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)");
return;
}
// shallow copy
final ArrayList<ApplicationInfo> list
= (ArrayList<ApplicationInfo>)mAllAppsList.data.clone();
mHandler.post(new Runnable() {
public void run() {
final long t = SystemClock.uptimeMillis();
final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindAllApplications(list);
}
if (DEBUG_LOADERS) {
Log.d(TAG, "bound all " + list.size() + " apps from cache in "
+ (SystemClock.uptimeMillis()-t) + "ms");
}
}
});
}
private void loadAllAppsByBatch() {
final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
// Don't use these two variables in any of the callback runnables.
// Otherwise we hold a reference to them.
final Callbacks oldCallbacks = mCallbacks.get();
if (oldCallbacks == null) {
// This launcher has exited and nobody bothered to tell us. Just bail.
Log.w(TAG, "LoaderTask running with no launcher (loadAllAppsByBatch)");
return;
}
final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
final PackageManager packageManager = mContext.getPackageManager();
List<ResolveInfo> apps = null;
int N = Integer.MAX_VALUE;
int startIndex;
int i=0;
int batchSize = -1;
while (i < N && !mStopped) {
if (i == 0) {
mAllAppsList.clear();
final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
apps = packageManager.queryIntentActivities(mainIntent, 0);
if (DEBUG_LOADERS) {
Log.d(TAG, "queryIntentActivities took "
+ (SystemClock.uptimeMillis()-qiaTime) + "ms");
}
if (apps == null) {
return;
}
N = apps.size();
if (DEBUG_LOADERS) {
Log.d(TAG, "queryIntentActivities got " + N + " apps");
}
if (N == 0) {
// There are no apps?!?
return;
}
if (mBatchSize == 0) {
batchSize = N;
} else {
batchSize = mBatchSize;
}
final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Collections.sort(apps,
new LauncherModel.ShortcutNameComparator(packageManager, mLabelCache));
if (DEBUG_LOADERS) {
Log.d(TAG, "sort took "
+ (SystemClock.uptimeMillis()-sortTime) + "ms");
}
}
final long t2 = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
startIndex = i;
for (int j=0; i<N && j<batchSize; j++) {
// This builds the icon bitmaps.
mAllAppsList.add(new ApplicationInfo(packageManager, apps.get(i),
mIconCache, mLabelCache));
i++;
}
final boolean first = i <= batchSize;
final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
final ArrayList<ApplicationInfo> added = mAllAppsList.added;
mAllAppsList.added = new ArrayList<ApplicationInfo>();
mHandler.post(new Runnable() {
public void run() {
final long t = SystemClock.uptimeMillis();
if (callbacks != null) {
if (first) {
callbacks.bindAllApplications(added);
} else {
callbacks.bindAppsAdded(added);
}
if (DEBUG_LOADERS) {
Log.d(TAG, "bound " + added.size() + " apps in "
+ (SystemClock.uptimeMillis() - t) + "ms");
}
} else {
Log.i(TAG, "not binding apps: no Launcher activity");
}
}
});
if (DEBUG_LOADERS) {
Log.d(TAG, "batch of " + (i-startIndex) + " icons processed in "
+ (SystemClock.uptimeMillis()-t2) + "ms");
}
if (mAllAppsLoadDelay > 0 && i < N) {
try {
if (DEBUG_LOADERS) {
Log.d(TAG, "sleeping for " + mAllAppsLoadDelay + "ms");
}
Thread.sleep(mAllAppsLoadDelay);
} catch (InterruptedException exc) { }
}
}
if (DEBUG_LOADERS) {
Log.d(TAG, "cached all " + N + " apps in "
+ (SystemClock.uptimeMillis()-t) + "ms"
+ (mAllAppsLoadDelay > 0 ? " (including delay)" : ""));
}
}
public void dumpState() {
Log.d(TAG, "mLoaderTask.mContext=" + mContext);
Log.d(TAG, "mLoaderTask.mWaitThread=" + mWaitThread);
Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching);
Log.d(TAG, "mLoaderTask.mStopped=" + mStopped);
Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished);
Log.d(TAG, "mItems size=" + sWorkspaceItems.size());
}
}
void enqueuePackageUpdated(PackageUpdatedTask task) {
sWorker.post(task);
}
private class PackageUpdatedTask implements Runnable {
int mOp;
String[] mPackages;
public static final int OP_NONE = 0;
public static final int OP_ADD = 1;
public static final int OP_UPDATE = 2;
public static final int OP_REMOVE = 3; // uninstlled
public static final int OP_UNAVAILABLE = 4; // external media unmounted
public PackageUpdatedTask(int op, String[] packages) {
mOp = op;
mPackages = packages;
}
public void run() {
final Context context = mApp;
final String[] packages = mPackages;
final int N = packages.length;
switch (mOp) {
case OP_ADD:
for (int i=0; i<N; i++) {
if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]);
mAllAppsList.addPackage(context, packages[i]);
}
break;
case OP_UPDATE:
for (int i=0; i<N; i++) {
if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]);
mAllAppsList.updatePackage(context, packages[i]);
}
break;
case OP_REMOVE:
case OP_UNAVAILABLE:
for (int i=0; i<N; i++) {
if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
mAllAppsList.removePackage(packages[i]);
}
break;
}
ArrayList<ApplicationInfo> added = null;
ArrayList<ApplicationInfo> removed = null;
ArrayList<ApplicationInfo> modified = null;
if (mAllAppsList.added.size() > 0) {
added = mAllAppsList.added;
mAllAppsList.added = new ArrayList<ApplicationInfo>();
}
if (mAllAppsList.removed.size() > 0) {
removed = mAllAppsList.removed;
mAllAppsList.removed = new ArrayList<ApplicationInfo>();
for (ApplicationInfo info: removed) {
mIconCache.remove(info.intent.getComponent());
}
}
if (mAllAppsList.modified.size() > 0) {
modified = mAllAppsList.modified;
mAllAppsList.modified = new ArrayList<ApplicationInfo>();
}
final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == null) {
Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading.");
return;
}
if (added != null) {
final ArrayList<ApplicationInfo> addedFinal = added;
mHandler.post(new Runnable() {
public void run() {
Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == cb && cb != null) {
callbacks.bindAppsAdded(addedFinal);
}
}
});
}
if (modified != null) {
final ArrayList<ApplicationInfo> modifiedFinal = modified;
mHandler.post(new Runnable() {
public void run() {
Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == cb && cb != null) {
callbacks.bindAppsUpdated(modifiedFinal);
}
}
});
}
if (removed != null) {
final boolean permanent = mOp != OP_UNAVAILABLE;
final ArrayList<ApplicationInfo> removedFinal = removed;
mHandler.post(new Runnable() {
public void run() {
Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == cb && cb != null) {
callbacks.bindAppsRemoved(removedFinal, permanent);
}
}
});
}
mHandler.post(new Runnable() {
@Override
public void run() {
Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == cb && cb != null) {
callbacks.bindPackagesUpdated();
}
}
});
}
}
/**
* This is called from the code that adds shortcuts from the intent receiver. This
* doesn't have a Cursor, but
*/
public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context) {
return getShortcutInfo(manager, intent, context, null, -1, -1, null);
}
/**
* Make an ShortcutInfo object for a shortcut that is an application.
*
* If c is not null, then it will be used to fill in missing data like the title and icon.
*/
public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context,
Cursor c, int iconIndex, int titleIndex, HashMap<Object, CharSequence> labelCache) {
Bitmap icon = null;
final ShortcutInfo info = new ShortcutInfo();
ComponentName componentName = intent.getComponent();
if (componentName == null) {
return null;
}
// TODO: See if the PackageManager knows about this case. If it doesn't
// then return null & delete this.
// the resource -- This may implicitly give us back the fallback icon,
// but don't worry about that. All we're doing with usingFallbackIcon is
// to avoid saving lots of copies of that in the database, and most apps
// have icons anyway.
final ResolveInfo resolveInfo = manager.resolveActivity(intent, 0);
if (resolveInfo != null) {
icon = mIconCache.getIcon(componentName, resolveInfo, labelCache);
}
// the db
if (icon == null) {
if (c != null) {
icon = getIconFromCursor(c, iconIndex, context);
}
}
// the fallback icon
if (icon == null) {
icon = getFallbackIcon();
info.usingFallbackIcon = true;
}
info.setIcon(icon);
// from the resource
if (resolveInfo != null) {
ComponentName key = LauncherModel.getComponentNameFromResolveInfo(resolveInfo);
if (labelCache != null && labelCache.containsKey(key)) {
info.title = labelCache.get(key);
} else {
info.title = resolveInfo.activityInfo.loadLabel(manager);
if (labelCache != null) {
labelCache.put(key, info.title);
}
}
}
// from the db
if (info.title == null) {
if (c != null) {
info.title = c.getString(titleIndex);
}
}
// fall back to the class name of the activity
if (info.title == null) {
info.title = componentName.getClassName();
}
info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
return info;
}
/**
* Make an ShortcutInfo object for a shortcut that isn't an application.
*/
private ShortcutInfo getShortcutInfo(Cursor c, Context context,
int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex,
int titleIndex) {
Bitmap icon = null;
final ShortcutInfo info = new ShortcutInfo();
info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
// TODO: If there's an explicit component and we can't install that, delete it.
info.title = c.getString(titleIndex);
int iconType = c.getInt(iconTypeIndex);
switch (iconType) {
case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
String packageName = c.getString(iconPackageIndex);
String resourceName = c.getString(iconResourceIndex);
PackageManager packageManager = context.getPackageManager();
info.customIcon = false;
// the resource
try {
Resources resources = packageManager.getResourcesForApplication(packageName);
if (resources != null) {
final int id = resources.getIdentifier(resourceName, null, null);
icon = Utilities.createIconBitmap(
mIconCache.getFullResIcon(resources, id), context);
}
} catch (Exception e) {
// drop this. we have other places to look for icons
}
// the db
if (icon == null) {
icon = getIconFromCursor(c, iconIndex, context);
}
// the fallback icon
if (icon == null) {
icon = getFallbackIcon();
info.usingFallbackIcon = true;
}
break;
case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
icon = getIconFromCursor(c, iconIndex, context);
if (icon == null) {
icon = getFallbackIcon();
info.customIcon = false;
info.usingFallbackIcon = true;
} else {
info.customIcon = true;
}
break;
default:
icon = getFallbackIcon();
info.usingFallbackIcon = true;
info.customIcon = false;
break;
}
info.setIcon(icon);
return info;
}
Bitmap getIconFromCursor(Cursor c, int iconIndex, Context context) {
if (false) {
Log.d(TAG, "getIconFromCursor app="
+ c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE)));
}
byte[] data = c.getBlob(iconIndex);
try {
return Utilities.createIconBitmap(
BitmapFactory.decodeByteArray(data, 0, data.length), context);
} catch (Exception e) {
return null;
}
}
ShortcutInfo addShortcut(Context context, Intent data, long container, int screen,
int cellX, int cellY, boolean notify) {
final ShortcutInfo info = infoFromShortcutIntent(context, data, null);
addItemToDatabase(context, info, container, screen, cellX, cellY, notify);
return info;
}
/**
* Attempts to find an AppWidgetProviderInfo that matches the given component.
*/
AppWidgetProviderInfo findAppWidgetProviderInfoWithComponent(Context context,
ComponentName component) {
List<AppWidgetProviderInfo> widgets =
AppWidgetManager.getInstance(context).getInstalledProviders();
for (AppWidgetProviderInfo info : widgets) {
if (info.provider.equals(component)) {
return info;
}
}
return null;
}
/**
* Returns a list of all the widgets that can handle configuration with a particular mimeType.
*/
List<WidgetMimeTypeHandlerData> resolveWidgetsForMimeType(Context context, String mimeType) {
final PackageManager packageManager = context.getPackageManager();
final List<WidgetMimeTypeHandlerData> supportedConfigurationActivities =
new ArrayList<WidgetMimeTypeHandlerData>();
final Intent supportsIntent =
new Intent(InstallWidgetReceiver.ACTION_SUPPORTS_CLIPDATA_MIMETYPE);
supportsIntent.setType(mimeType);
// Create a set of widget configuration components that we can test against
final List<AppWidgetProviderInfo> widgets =
AppWidgetManager.getInstance(context).getInstalledProviders();
final HashMap<ComponentName, AppWidgetProviderInfo> configurationComponentToWidget =
new HashMap<ComponentName, AppWidgetProviderInfo>();
for (AppWidgetProviderInfo info : widgets) {
configurationComponentToWidget.put(info.configure, info);
}
// Run through each of the intents that can handle this type of clip data, and cross
// reference them with the components that are actual configuration components
final List<ResolveInfo> activities = packageManager.queryIntentActivities(supportsIntent,
PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo info : activities) {
final ActivityInfo activityInfo = info.activityInfo;
final ComponentName infoComponent = new ComponentName(activityInfo.packageName,
activityInfo.name);
if (configurationComponentToWidget.containsKey(infoComponent)) {
supportedConfigurationActivities.add(
new InstallWidgetReceiver.WidgetMimeTypeHandlerData(info,
configurationComponentToWidget.get(infoComponent)));
}
}
return supportedConfigurationActivities;
}
ShortcutInfo infoFromShortcutIntent(Context context, Intent data, Bitmap fallbackIcon) {
Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
Bitmap icon = null;
boolean customIcon = false;
ShortcutIconResource iconResource = null;
if (bitmap != null && bitmap instanceof Bitmap) {
icon = Utilities.createIconBitmap(new FastBitmapDrawable((Bitmap)bitmap), context);
customIcon = true;
} else {
Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
if (extra != null && extra instanceof ShortcutIconResource) {
try {
iconResource = (ShortcutIconResource) extra;
final PackageManager packageManager = context.getPackageManager();
Resources resources = packageManager.getResourcesForApplication(
iconResource.packageName);
final int id = resources.getIdentifier(iconResource.resourceName, null, null);
icon = Utilities.createIconBitmap(
mIconCache.getFullResIcon(resources, id), context);
} catch (Exception e) {
Log.w(TAG, "Could not load shortcut icon: " + extra);
}
}
}
final ShortcutInfo info = new ShortcutInfo();
if (icon == null) {
if (fallbackIcon != null) {
icon = fallbackIcon;
} else {
icon = getFallbackIcon();
info.usingFallbackIcon = true;
}
}
info.setIcon(icon);
info.title = name;
info.intent = intent;
info.customIcon = customIcon;
info.iconResource = iconResource;
return info;
}
boolean queueIconToBeChecked(HashMap<Object, byte[]> cache, ShortcutInfo info, Cursor c,
int iconIndex) {
// If apps can't be on SD, don't even bother.
if (!mAppsCanBeOnExternalStorage) {
return false;
}
// If this icon doesn't have a custom icon, check to see
// what's stored in the DB, and if it doesn't match what
// we're going to show, store what we are going to show back
// into the DB. We do this so when we're loading, if the
// package manager can't find an icon (for example because
// the app is on SD) then we can use that instead.
if (!info.customIcon && !info.usingFallbackIcon) {
cache.put(info, c.getBlob(iconIndex));
return true;
}
return false;
}
void updateSavedIcon(Context context, ShortcutInfo info, byte[] data) {
boolean needSave = false;
try {
if (data != null) {
Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length);
Bitmap loaded = info.getIcon(mIconCache);
needSave = !saved.sameAs(loaded);
} else {
needSave = true;
}
} catch (Exception e) {
needSave = true;
}
if (needSave) {
Log.d(TAG, "going to save icon bitmap for info=" + info);
// This is slower than is ideal, but this only happens once
// or when the app is updated with a new icon.
updateItemInDatabase(context, info);
}
}
/**
* Return an existing FolderInfo object if we have encountered this ID previously,
* or make a new one.
*/
private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) {
// See if a placeholder was created for us already
FolderInfo folderInfo = folders.get(id);
if (folderInfo == null) {
// No placeholder -- create a new instance
folderInfo = new FolderInfo();
folders.put(id, folderInfo);
}
return folderInfo;
}
private static final Collator sCollator = Collator.getInstance();
public static final Comparator<ApplicationInfo> APP_NAME_COMPARATOR
= new Comparator<ApplicationInfo>() {
public final int compare(ApplicationInfo a, ApplicationInfo b) {
int result = sCollator.compare(a.title.toString(), b.title.toString());
if (result == 0) {
result = a.componentName.compareTo(b.componentName);
}
return result;
}
};
public static final Comparator<ApplicationInfo> APP_INSTALL_TIME_COMPARATOR
= new Comparator<ApplicationInfo>() {
public final int compare(ApplicationInfo a, ApplicationInfo b) {
if (a.firstInstallTime < b.firstInstallTime) return 1;
if (a.firstInstallTime > b.firstInstallTime) return -1;
return 0;
}
};
public static final Comparator<AppWidgetProviderInfo> WIDGET_NAME_COMPARATOR
= new Comparator<AppWidgetProviderInfo>() {
public final int compare(AppWidgetProviderInfo a, AppWidgetProviderInfo b) {
return sCollator.compare(a.label.toString(), b.label.toString());
}
};
static ComponentName getComponentNameFromResolveInfo(ResolveInfo info) {
if (info.activityInfo != null) {
return new ComponentName(info.activityInfo.packageName, info.activityInfo.name);
} else {
return new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name);
}
}
public static class ShortcutNameComparator implements Comparator<ResolveInfo> {
private PackageManager mPackageManager;
private HashMap<Object, CharSequence> mLabelCache;
ShortcutNameComparator(PackageManager pm) {
mPackageManager = pm;
mLabelCache = new HashMap<Object, CharSequence>();
}
ShortcutNameComparator(PackageManager pm, HashMap<Object, CharSequence> labelCache) {
mPackageManager = pm;
mLabelCache = labelCache;
}
public final int compare(ResolveInfo a, ResolveInfo b) {
CharSequence labelA, labelB;
ComponentName keyA = LauncherModel.getComponentNameFromResolveInfo(a);
ComponentName keyB = LauncherModel.getComponentNameFromResolveInfo(b);
if (mLabelCache.containsKey(keyA)) {
labelA = mLabelCache.get(keyA);
} else {
labelA = a.loadLabel(mPackageManager).toString();
mLabelCache.put(keyA, labelA);
}
if (mLabelCache.containsKey(keyB)) {
labelB = mLabelCache.get(keyB);
} else {
labelB = b.loadLabel(mPackageManager).toString();
mLabelCache.put(keyB, labelB);
}
return sCollator.compare(labelA, labelB);
}
};
public static class WidgetAndShortcutNameComparator implements Comparator<Object> {
private PackageManager mPackageManager;
private HashMap<Object, String> mLabelCache;
WidgetAndShortcutNameComparator(PackageManager pm) {
mPackageManager = pm;
mLabelCache = new HashMap<Object, String>();
}
public final int compare(Object a, Object b) {
String labelA, labelB;
if (mLabelCache.containsKey(a)) {
labelA = mLabelCache.get(a);
} else {
labelA = (a instanceof AppWidgetProviderInfo) ?
((AppWidgetProviderInfo) a).label :
((ResolveInfo) a).loadLabel(mPackageManager).toString();
mLabelCache.put(a, labelA);
}
if (mLabelCache.containsKey(b)) {
labelB = mLabelCache.get(b);
} else {
labelB = (b instanceof AppWidgetProviderInfo) ?
((AppWidgetProviderInfo) b).label :
((ResolveInfo) b).loadLabel(mPackageManager).toString();
mLabelCache.put(b, labelB);
}
return sCollator.compare(labelA, labelB);
}
};
public void dumpState() {
Log.d(TAG, "mCallbacks=" + mCallbacks);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mAllAppsList.data);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mAllAppsList.added);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mAllAppsList.removed);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mAllAppsList.modified);
if (mLoaderTask != null) {
mLoaderTask.dumpState();
} else {
Log.d(TAG, "mLoaderTask=null");
}
}
}
| static boolean shortcutExists(Context context, String title, Intent intent) {
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
new String[] { "title", "intent" }, "title=? and intent=?",
new String[] { title, intent.toUri(0) }, null);
boolean result = false;
try {
result = c.moveToFirst();
} finally {
c.close();
}
return result;
}
/**
* Returns an ItemInfo array containing all the items in the LauncherModel.
* The ItemInfo.id is not set through this function.
*/
static ArrayList<ItemInfo> getItemsInLocalCoordinates(Context context) {
ArrayList<ItemInfo> items = new ArrayList<ItemInfo>();
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] {
LauncherSettings.Favorites.ITEM_TYPE, LauncherSettings.Favorites.CONTAINER,
LauncherSettings.Favorites.SCREEN, LauncherSettings.Favorites.CELLX, LauncherSettings.Favorites.CELLY,
LauncherSettings.Favorites.SPANX, LauncherSettings.Favorites.SPANY }, null, null, null);
final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
final int spanXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANX);
final int spanYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANY);
try {
while (c.moveToNext()) {
ItemInfo item = new ItemInfo();
item.cellX = c.getInt(cellXIndex);
item.cellY = c.getInt(cellYIndex);
item.spanX = c.getInt(spanXIndex);
item.spanY = c.getInt(spanYIndex);
item.container = c.getInt(containerIndex);
item.itemType = c.getInt(itemTypeIndex);
item.screen = c.getInt(screenIndex);
items.add(item);
}
} catch (Exception e) {
items.clear();
} finally {
c.close();
}
return items;
}
/**
* Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
*/
FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) {
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
"_id=? and (itemType=? or itemType=?)",
new String[] { String.valueOf(id),
String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)}, null);
try {
if (c.moveToFirst()) {
final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
FolderInfo folderInfo = null;
switch (c.getInt(itemTypeIndex)) {
case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
folderInfo = findOrMakeFolder(folderList, id);
break;
}
folderInfo.title = c.getString(titleIndex);
folderInfo.id = id;
folderInfo.container = c.getInt(containerIndex);
folderInfo.screen = c.getInt(screenIndex);
folderInfo.cellX = c.getInt(cellXIndex);
folderInfo.cellY = c.getInt(cellYIndex);
return folderInfo;
}
} finally {
c.close();
}
return null;
}
/**
* Add an item to the database in a specified container. Sets the container, screen, cellX and
* cellY fields of the item. Also assigns an ID to the item.
*/
static void addItemToDatabase(Context context, final ItemInfo item, final long container,
final int screen, final int cellX, final int cellY, final boolean notify) {
item.container = container;
item.cellX = cellX;
item.cellY = cellY;
// We store hotseat items in canonical form which is this orientation invariant position
// in the hotseat
if (context instanceof Launcher && screen < 0 &&
container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
item.screen = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY);
} else {
item.screen = screen;
}
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
item.onAddToDatabase(values);
LauncherApplication app = (LauncherApplication) context.getApplicationContext();
item.id = app.getLauncherProvider().generateNewId();
values.put(LauncherSettings.Favorites._ID, item.id);
item.updateValuesWithCoordinates(values, item.cellX, item.cellY);
sWorker.post(new Runnable() {
public void run() {
cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI :
LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values);
if (sItemsIdMap.containsKey(item.id)) {
// we should not be adding new items in the db with the same id
throw new RuntimeException("Error: ItemInfo id (" + item.id + ") passed to " +
"addItemToDatabase already exists." + item.toString());
}
sItemsIdMap.put(item.id, item);
switch (item.itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
sFolders.put(item.id, (FolderInfo) item);
// Fall through
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP ||
item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
sWorkspaceItems.add(item);
}
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
sAppWidgets.add((LauncherAppWidgetInfo) item);
break;
}
}
});
}
/**
* Creates a new unique child id, for a given cell span across all layouts.
*/
static int getCellLayoutChildId(
long container, int screen, int localCellX, int localCellY, int spanX, int spanY) {
return (((int) container & 0xFF) << 24)
| (screen & 0xFF) << 16 | (localCellX & 0xFF) << 8 | (localCellY & 0xFF);
}
static int getCellCountX() {
return mCellCountX;
}
static int getCellCountY() {
return mCellCountY;
}
/**
* Updates the model orientation helper to take into account the current layout dimensions
* when performing local/canonical coordinate transformations.
*/
static void updateWorkspaceLayoutCells(int shortAxisCellCount, int longAxisCellCount) {
mCellCountX = shortAxisCellCount;
mCellCountY = longAxisCellCount;
}
/**
* Update an item to the database in a specified container.
*/
static void updateItemInDatabase(Context context, final ItemInfo item) {
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
item.onAddToDatabase(values);
item.updateValuesWithCoordinates(values, item.cellX, item.cellY);
sWorker.post(new Runnable() {
public void run() {
cr.update(LauncherSettings.Favorites.getContentUri(item.id, false),
values, null, null);
final ItemInfo modelItem = sItemsIdMap.get(item.id);
if (item != modelItem) {
// the modelItem needs to match up perfectly with item if our model is to be
// consistent with the database-- for now, just require modelItem == item
String msg = "item: " + ((item != null) ? item.toString() : "null") +
"modelItem: " + ((modelItem != null) ? modelItem.toString() : "null") +
"Error: ItemInfo passed to updateItemInDatabase doesn't match original";
throw new RuntimeException(msg);
}
}
});
}
/**
* Removes the specified item from the database
* @param context
* @param item
*/
static void deleteItemFromDatabase(Context context, final ItemInfo item) {
final ContentResolver cr = context.getContentResolver();
final Uri uriToDelete = LauncherSettings.Favorites.getContentUri(item.id, false);
sWorker.post(new Runnable() {
public void run() {
cr.delete(uriToDelete, null, null);
switch (item.itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
sFolders.remove(item.id);
sWorkspaceItems.remove(item);
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
sWorkspaceItems.remove(item);
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
sAppWidgets.remove((LauncherAppWidgetInfo) item);
break;
}
sItemsIdMap.remove(item.id);
sDbIconCache.remove(item);
}
});
}
/**
* Remove the contents of the specified folder from the database
*/
static void deleteFolderContentsFromDatabase(Context context, final FolderInfo info) {
final ContentResolver cr = context.getContentResolver();
sWorker.post(new Runnable() {
public void run() {
cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null);
sItemsIdMap.remove(info.id);
sFolders.remove(info.id);
sDbIconCache.remove(info);
sWorkspaceItems.remove(info);
cr.delete(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
for (ItemInfo childInfo : info.contents) {
sItemsIdMap.remove(childInfo.id);
sDbIconCache.remove(childInfo);
}
}
});
}
/**
* Set this as the current Launcher activity object for the loader.
*/
public void initialize(Callbacks callbacks) {
synchronized (mLock) {
mCallbacks = new WeakReference<Callbacks>(callbacks);
}
}
/**
* Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
* ACTION_PACKAGE_CHANGED.
*/
@Override
public void onReceive(Context context, Intent intent) {
if (DEBUG_LOADERS) Log.d(TAG, "onReceive intent=" + intent);
final String action = intent.getAction();
if (Intent.ACTION_PACKAGE_CHANGED.equals(action)
|| Intent.ACTION_PACKAGE_REMOVED.equals(action)
|| Intent.ACTION_PACKAGE_ADDED.equals(action)) {
final String packageName = intent.getData().getSchemeSpecificPart();
final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
int op = PackageUpdatedTask.OP_NONE;
if (packageName == null || packageName.length() == 0) {
// they sent us a bad intent
return;
}
if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
op = PackageUpdatedTask.OP_UPDATE;
} else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
if (!replacing) {
op = PackageUpdatedTask.OP_REMOVE;
}
// else, we are replacing the package, so a PACKAGE_ADDED will be sent
// later, we will update the package at this time
} else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
if (!replacing) {
op = PackageUpdatedTask.OP_ADD;
} else {
op = PackageUpdatedTask.OP_UPDATE;
}
}
if (op != PackageUpdatedTask.OP_NONE) {
enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName }));
}
} else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
// First, schedule to add these apps back in.
String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_ADD, packages));
// Then, rebind everything.
startLoaderFromBackground();
} else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
enqueuePackageUpdated(new PackageUpdatedTask(
PackageUpdatedTask.OP_UNAVAILABLE, packages));
} else if (Intent.ACTION_LOCALE_CHANGED.equals(action)) {
// If we have changed locale we need to clear out the labels in all apps.
// Do this here because if the launcher activity is running it will be restarted.
// If it's not running startLoaderFromBackground will merely tell it that it needs
// to reload. Either way, mAllAppsLoaded will be cleared so it re-reads everything
// next time.
mAllAppsLoaded = false;
mWorkspaceLoaded = false;
startLoaderFromBackground();
} else if (SearchManager.INTENT_GLOBAL_SEARCH_ACTIVITY_CHANGED.equals(action) ||
SearchManager.INTENT_ACTION_SEARCHABLES_CHANGED.equals(action)) {
if (mCallbacks != null) {
Callbacks callbacks = mCallbacks.get();
if (callbacks != null) {
callbacks.bindSearchablesChanged();
}
}
}
}
/**
* When the launcher is in the background, it's possible for it to miss paired
* configuration changes. So whenever we trigger the loader from the background
* tell the launcher that it needs to re-run the loader when it comes back instead
* of doing it now.
*/
public void startLoaderFromBackground() {
boolean runLoader = false;
if (mCallbacks != null) {
Callbacks callbacks = mCallbacks.get();
if (callbacks != null) {
// Only actually run the loader if they're not paused.
if (!callbacks.setLoadOnResume()) {
runLoader = true;
}
}
}
if (runLoader) {
startLoader(mApp, false);
}
}
public void startLoader(Context context, boolean isLaunching) {
synchronized (mLock) {
if (DEBUG_LOADERS) {
Log.d(TAG, "startLoader isLaunching=" + isLaunching);
}
// Don't bother to start the thread if we know it's not going to do anything
if (mCallbacks != null && mCallbacks.get() != null) {
// If there is already one running, tell it to stop.
LoaderTask oldTask = mLoaderTask;
if (oldTask != null) {
if (oldTask.isLaunching()) {
// don't downgrade isLaunching if we're already running
isLaunching = true;
}
oldTask.stopLocked();
}
mLoaderTask = new LoaderTask(context, isLaunching);
sWorker.post(mLoaderTask);
}
}
}
public void stopLoader() {
synchronized (mLock) {
if (mLoaderTask != null) {
mLoaderTask.stopLocked();
}
}
}
public boolean isAllAppsLoaded() {
return mAllAppsLoaded;
}
/**
* Runnable for the thread that loads the contents of the launcher:
* - workspace icons
* - widgets
* - all apps icons
*/
private class LoaderTask implements Runnable {
private Context mContext;
private Thread mWaitThread;
private boolean mIsLaunching;
private boolean mStopped;
private boolean mLoadAndBindStepFinished;
private HashMap<Object, CharSequence> mLabelCache;
LoaderTask(Context context, boolean isLaunching) {
mContext = context;
mIsLaunching = isLaunching;
mLabelCache = new HashMap<Object, CharSequence>();
}
boolean isLaunching() {
return mIsLaunching;
}
private void loadAndBindWorkspace() {
// Load the workspace
if (DEBUG_LOADERS) {
Log.d(TAG, "loadAndBindWorkspace mWorkspaceLoaded=" + mWorkspaceLoaded);
}
if (!mWorkspaceLoaded) {
loadWorkspace();
if (mStopped) {
return;
}
mWorkspaceLoaded = true;
}
// Bind the workspace
bindWorkspace();
}
private void waitForIdle() {
// Wait until the either we're stopped or the other threads are done.
// This way we don't start loading all apps until the workspace has settled
// down.
synchronized (LoaderTask.this) {
final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
mHandler.postIdle(new Runnable() {
public void run() {
synchronized (LoaderTask.this) {
mLoadAndBindStepFinished = true;
if (DEBUG_LOADERS) {
Log.d(TAG, "done with previous binding step");
}
LoaderTask.this.notify();
}
}
});
while (!mStopped && !mLoadAndBindStepFinished) {
try {
this.wait();
} catch (InterruptedException ex) {
// Ignore
}
}
if (DEBUG_LOADERS) {
Log.d(TAG, "waited "
+ (SystemClock.uptimeMillis()-workspaceWaitTime)
+ "ms for previous step to finish binding");
}
}
}
public void run() {
// Optimize for end-user experience: if the Launcher is up and // running with the
// All Apps interface in the foreground, load All Apps first. Otherwise, load the
// workspace first (default).
final Callbacks cbk = mCallbacks.get();
final boolean loadWorkspaceFirst = cbk != null ? (!cbk.isAllAppsVisible()) : true;
keep_running: {
// Elevate priority when Home launches for the first time to avoid
// starving at boot time. Staring at a blank home is not cool.
synchronized (mLock) {
if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to " +
(mIsLaunching ? "DEFAULT" : "BACKGROUND"));
android.os.Process.setThreadPriority(mIsLaunching
? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
}
if (loadWorkspaceFirst) {
if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace");
loadAndBindWorkspace();
} else {
if (DEBUG_LOADERS) Log.d(TAG, "step 1: special: loading all apps");
loadAndBindAllApps();
}
if (mStopped) {
break keep_running;
}
// Whew! Hard work done. Slow us down, and wait until the UI thread has
// settled down.
synchronized (mLock) {
if (mIsLaunching) {
if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to BACKGROUND");
android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
}
}
waitForIdle();
// second step
if (loadWorkspaceFirst) {
if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps");
loadAndBindAllApps();
} else {
if (DEBUG_LOADERS) Log.d(TAG, "step 2: special: loading workspace");
loadAndBindWorkspace();
}
}
// Update the saved icons if necessary
if (DEBUG_LOADERS) Log.d(TAG, "Comparing loaded icons to database icons");
for (Object key : sDbIconCache.keySet()) {
updateSavedIcon(mContext, (ShortcutInfo) key, sDbIconCache.get(key));
}
sDbIconCache.clear();
// Clear out this reference, otherwise we end up holding it until all of the
// callback runnables are done.
mContext = null;
synchronized (mLock) {
// If we are still the last one to be scheduled, remove ourselves.
if (mLoaderTask == this) {
mLoaderTask = null;
}
}
}
public void stopLocked() {
synchronized (LoaderTask.this) {
mStopped = true;
this.notify();
}
}
/**
* Gets the callbacks object. If we've been stopped, or if the launcher object
* has somehow been garbage collected, return null instead. Pass in the Callbacks
* object that was around when the deferred message was scheduled, and if there's
* a new Callbacks object around then also return null. This will save us from
* calling onto it with data that will be ignored.
*/
Callbacks tryGetCallbacks(Callbacks oldCallbacks) {
synchronized (mLock) {
if (mStopped) {
return null;
}
if (mCallbacks == null) {
return null;
}
final Callbacks callbacks = mCallbacks.get();
if (callbacks != oldCallbacks) {
return null;
}
if (callbacks == null) {
Log.w(TAG, "no mCallbacks");
return null;
}
return callbacks;
}
}
// check & update map of what's occupied; used to discard overlapping/invalid items
private boolean checkItemPlacement(ItemInfo occupied[][][], ItemInfo item) {
int containerIndex = item.screen;
if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
// We use the last index to refer to the hotseat
containerIndex = Launcher.SCREEN_COUNT;
// Return early if we detect that an item is under the hotseat button
if (Hotseat.isAllAppsButtonRank(item.screen)) {
return false;
}
} else if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
// Skip further checking if it is not the hotseat or workspace container
return true;
}
for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
if (occupied[containerIndex][x][y] != null) {
Log.e(TAG, "Error loading shortcut " + item
+ " into cell (" + containerIndex + "-" + item.screen + ":"
+ x + "," + y
+ ") occupied by "
+ occupied[containerIndex][x][y]);
return false;
}
}
}
for (int x = item.cellX; x < (item.cellX+item.spanX); x++) {
for (int y = item.cellY; y < (item.cellY+item.spanY); y++) {
occupied[containerIndex][x][y] = item;
}
}
return true;
}
private void loadWorkspace() {
final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
final Context context = mContext;
final ContentResolver contentResolver = context.getContentResolver();
final PackageManager manager = context.getPackageManager();
final AppWidgetManager widgets = AppWidgetManager.getInstance(context);
final boolean isSafeMode = manager.isSafeMode();
sWorkspaceItems.clear();
sAppWidgets.clear();
sFolders.clear();
sItemsIdMap.clear();
sDbIconCache.clear();
final ArrayList<Long> itemsToRemove = new ArrayList<Long>();
final Cursor c = contentResolver.query(
LauncherSettings.Favorites.CONTENT_URI, null, null, null, null);
// +1 for the hotseat (it can be larger than the workspace)
final ItemInfo occupied[][][] =
new ItemInfo[Launcher.SCREEN_COUNT + 1][mCellCountX + 1][mCellCountY + 1];
try {
final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
final int intentIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.INTENT);
final int titleIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.TITLE);
final int iconTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_TYPE);
final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
final int iconPackageIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_PACKAGE);
final int iconResourceIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_RESOURCE);
final int containerIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.CONTAINER);
final int itemTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ITEM_TYPE);
final int appWidgetIdIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.APPWIDGET_ID);
final int screenIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLY);
final int spanXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.SPANX);
final int spanYIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SPANY);
final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
final int displayModeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.DISPLAY_MODE);
ShortcutInfo info;
String intentDescription;
LauncherAppWidgetInfo appWidgetInfo;
int container;
long id;
Intent intent;
while (!mStopped && c.moveToNext()) {
try {
int itemType = c.getInt(itemTypeIndex);
switch (itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
intentDescription = c.getString(intentIndex);
try {
intent = Intent.parseUri(intentDescription, 0);
} catch (URISyntaxException e) {
continue;
}
if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
info = getShortcutInfo(manager, intent, context, c, iconIndex,
titleIndex, mLabelCache);
} else {
info = getShortcutInfo(c, context, iconTypeIndex,
iconPackageIndex, iconResourceIndex, iconIndex,
titleIndex);
}
if (info != null) {
info.intent = intent;
info.id = c.getLong(idIndex);
container = c.getInt(containerIndex);
info.container = container;
info.screen = c.getInt(screenIndex);
info.cellX = c.getInt(cellXIndex);
info.cellY = c.getInt(cellYIndex);
// check & update map of what's occupied
if (!checkItemPlacement(occupied, info)) {
break;
}
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
sWorkspaceItems.add(info);
break;
default:
// Item is in a user folder
FolderInfo folderInfo =
findOrMakeFolder(sFolders, container);
folderInfo.add(info);
break;
}
sItemsIdMap.put(info.id, info);
// now that we've loaded everthing re-save it with the
// icon in case it disappears somehow.
queueIconToBeChecked(sDbIconCache, info, c, iconIndex);
} else {
// Failed to load the shortcut, probably because the
// activity manager couldn't resolve it (maybe the app
// was uninstalled), or the db row was somehow screwed up.
// Delete it.
id = c.getLong(idIndex);
Log.e(TAG, "Error loading shortcut " + id + ", removing it");
contentResolver.delete(LauncherSettings.Favorites.getContentUri(
id, false), null, null);
}
break;
case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
id = c.getLong(idIndex);
FolderInfo folderInfo = findOrMakeFolder(sFolders, id);
folderInfo.title = c.getString(titleIndex);
folderInfo.id = id;
container = c.getInt(containerIndex);
folderInfo.container = container;
folderInfo.screen = c.getInt(screenIndex);
folderInfo.cellX = c.getInt(cellXIndex);
folderInfo.cellY = c.getInt(cellYIndex);
// check & update map of what's occupied
if (!checkItemPlacement(occupied, folderInfo)) {
break;
}
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
case LauncherSettings.Favorites.CONTAINER_HOTSEAT:
sWorkspaceItems.add(folderInfo);
break;
}
sItemsIdMap.put(folderInfo.id, folderInfo);
sFolders.put(folderInfo.id, folderInfo);
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
// Read all Launcher-specific widget details
int appWidgetId = c.getInt(appWidgetIdIndex);
id = c.getLong(idIndex);
final AppWidgetProviderInfo provider =
widgets.getAppWidgetInfo(appWidgetId);
if (!isSafeMode && (provider == null || provider.provider == null ||
provider.provider.getPackageName() == null)) {
Log.e(TAG, "Deleting widget that isn't installed anymore: id="
+ id + " appWidgetId=" + appWidgetId);
itemsToRemove.add(id);
} else {
appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId);
appWidgetInfo.id = id;
appWidgetInfo.screen = c.getInt(screenIndex);
appWidgetInfo.cellX = c.getInt(cellXIndex);
appWidgetInfo.cellY = c.getInt(cellYIndex);
appWidgetInfo.spanX = c.getInt(spanXIndex);
appWidgetInfo.spanY = c.getInt(spanYIndex);
container = c.getInt(containerIndex);
if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP &&
container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
Log.e(TAG, "Widget found where container "
+ "!= CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!");
continue;
}
appWidgetInfo.container = c.getInt(containerIndex);
// check & update map of what's occupied
if (!checkItemPlacement(occupied, appWidgetInfo)) {
break;
}
sItemsIdMap.put(appWidgetInfo.id, appWidgetInfo);
sAppWidgets.add(appWidgetInfo);
}
break;
}
} catch (Exception e) {
Log.w(TAG, "Desktop items loading interrupted:", e);
}
}
} finally {
c.close();
}
if (itemsToRemove.size() > 0) {
ContentProviderClient client = contentResolver.acquireContentProviderClient(
LauncherSettings.Favorites.CONTENT_URI);
// Remove dead items
for (long id : itemsToRemove) {
if (DEBUG_LOADERS) {
Log.d(TAG, "Removed id = " + id);
}
// Don't notify content observers
try {
client.delete(LauncherSettings.Favorites.getContentUri(id, false),
null, null);
} catch (RemoteException e) {
Log.w(TAG, "Could not remove id = " + id);
}
}
}
if (DEBUG_LOADERS) {
Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
Log.d(TAG, "workspace layout: ");
for (int y = 0; y < mCellCountY; y++) {
String line = "";
for (int s = 0; s < Launcher.SCREEN_COUNT; s++) {
if (s > 0) {
line += " | ";
}
for (int x = 0; x < mCellCountX; x++) {
line += ((occupied[s][x][y] != null) ? "#" : ".");
}
}
Log.d(TAG, "[ " + line + " ]");
}
}
}
/**
* Read everything out of our database.
*/
private void bindWorkspace() {
final long t = SystemClock.uptimeMillis();
// Don't use these two variables in any of the callback runnables.
// Otherwise we hold a reference to them.
final Callbacks oldCallbacks = mCallbacks.get();
if (oldCallbacks == null) {
// This launcher has exited and nobody bothered to tell us. Just bail.
Log.w(TAG, "LoaderTask running with no launcher");
return;
}
int N;
// Tell the workspace that we're about to start firing items at it
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.startBinding();
}
}
});
// Add the items to the workspace.
N = sWorkspaceItems.size();
for (int i=0; i<N; i+=ITEMS_CHUNK) {
final int start = i;
final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindItems(sWorkspaceItems, start, start+chunkSize);
}
}
});
}
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindFolders(sFolders);
}
}
});
// Wait until the queue goes empty.
mHandler.post(new Runnable() {
public void run() {
if (DEBUG_LOADERS) {
Log.d(TAG, "Going to start binding widgets soon.");
}
}
});
// Bind the widgets, one at a time.
// WARNING: this is calling into the workspace from the background thread,
// but since getCurrentScreen() just returns the int, we should be okay. This
// is just a hint for the order, and if it's wrong, we'll be okay.
// TODO: instead, we should have that push the current screen into here.
final int currentScreen = oldCallbacks.getCurrentWorkspaceScreen();
N = sAppWidgets.size();
// once for the current screen
for (int i=0; i<N; i++) {
final LauncherAppWidgetInfo widget = sAppWidgets.get(i);
if (widget.screen == currentScreen) {
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindAppWidget(widget);
}
}
});
}
}
// once for the other screens
for (int i=0; i<N; i++) {
final LauncherAppWidgetInfo widget = sAppWidgets.get(i);
if (widget.screen != currentScreen) {
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindAppWidget(widget);
}
}
});
}
}
// Tell the workspace that we're done.
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.finishBindingItems();
}
}
});
// If we're profiling, this is the last thing in the queue.
mHandler.post(new Runnable() {
public void run() {
if (DEBUG_LOADERS) {
Log.d(TAG, "bound workspace in "
+ (SystemClock.uptimeMillis()-t) + "ms");
}
}
});
}
private void loadAndBindAllApps() {
if (DEBUG_LOADERS) {
Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded);
}
if (!mAllAppsLoaded) {
loadAllAppsByBatch();
if (mStopped) {
return;
}
mAllAppsLoaded = true;
} else {
onlyBindAllApps();
}
}
private void onlyBindAllApps() {
final Callbacks oldCallbacks = mCallbacks.get();
if (oldCallbacks == null) {
// This launcher has exited and nobody bothered to tell us. Just bail.
Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)");
return;
}
// shallow copy
final ArrayList<ApplicationInfo> list
= (ArrayList<ApplicationInfo>)mAllAppsList.data.clone();
mHandler.post(new Runnable() {
public void run() {
final long t = SystemClock.uptimeMillis();
final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
if (callbacks != null) {
callbacks.bindAllApplications(list);
}
if (DEBUG_LOADERS) {
Log.d(TAG, "bound all " + list.size() + " apps from cache in "
+ (SystemClock.uptimeMillis()-t) + "ms");
}
}
});
}
private void loadAllAppsByBatch() {
final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
// Don't use these two variables in any of the callback runnables.
// Otherwise we hold a reference to them.
final Callbacks oldCallbacks = mCallbacks.get();
if (oldCallbacks == null) {
// This launcher has exited and nobody bothered to tell us. Just bail.
Log.w(TAG, "LoaderTask running with no launcher (loadAllAppsByBatch)");
return;
}
final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
final PackageManager packageManager = mContext.getPackageManager();
List<ResolveInfo> apps = null;
int N = Integer.MAX_VALUE;
int startIndex;
int i=0;
int batchSize = -1;
while (i < N && !mStopped) {
if (i == 0) {
mAllAppsList.clear();
final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
apps = packageManager.queryIntentActivities(mainIntent, 0);
if (DEBUG_LOADERS) {
Log.d(TAG, "queryIntentActivities took "
+ (SystemClock.uptimeMillis()-qiaTime) + "ms");
}
if (apps == null) {
return;
}
N = apps.size();
if (DEBUG_LOADERS) {
Log.d(TAG, "queryIntentActivities got " + N + " apps");
}
if (N == 0) {
// There are no apps?!?
return;
}
if (mBatchSize == 0) {
batchSize = N;
} else {
batchSize = mBatchSize;
}
final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
Collections.sort(apps,
new LauncherModel.ShortcutNameComparator(packageManager, mLabelCache));
if (DEBUG_LOADERS) {
Log.d(TAG, "sort took "
+ (SystemClock.uptimeMillis()-sortTime) + "ms");
}
}
final long t2 = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0;
startIndex = i;
for (int j=0; i<N && j<batchSize; j++) {
// This builds the icon bitmaps.
mAllAppsList.add(new ApplicationInfo(packageManager, apps.get(i),
mIconCache, mLabelCache));
i++;
}
final boolean first = i <= batchSize;
final Callbacks callbacks = tryGetCallbacks(oldCallbacks);
final ArrayList<ApplicationInfo> added = mAllAppsList.added;
mAllAppsList.added = new ArrayList<ApplicationInfo>();
mHandler.post(new Runnable() {
public void run() {
final long t = SystemClock.uptimeMillis();
if (callbacks != null) {
if (first) {
callbacks.bindAllApplications(added);
} else {
callbacks.bindAppsAdded(added);
}
if (DEBUG_LOADERS) {
Log.d(TAG, "bound " + added.size() + " apps in "
+ (SystemClock.uptimeMillis() - t) + "ms");
}
} else {
Log.i(TAG, "not binding apps: no Launcher activity");
}
}
});
if (DEBUG_LOADERS) {
Log.d(TAG, "batch of " + (i-startIndex) + " icons processed in "
+ (SystemClock.uptimeMillis()-t2) + "ms");
}
if (mAllAppsLoadDelay > 0 && i < N) {
try {
if (DEBUG_LOADERS) {
Log.d(TAG, "sleeping for " + mAllAppsLoadDelay + "ms");
}
Thread.sleep(mAllAppsLoadDelay);
} catch (InterruptedException exc) { }
}
}
if (DEBUG_LOADERS) {
Log.d(TAG, "cached all " + N + " apps in "
+ (SystemClock.uptimeMillis()-t) + "ms"
+ (mAllAppsLoadDelay > 0 ? " (including delay)" : ""));
}
}
public void dumpState() {
Log.d(TAG, "mLoaderTask.mContext=" + mContext);
Log.d(TAG, "mLoaderTask.mWaitThread=" + mWaitThread);
Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching);
Log.d(TAG, "mLoaderTask.mStopped=" + mStopped);
Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished);
Log.d(TAG, "mItems size=" + sWorkspaceItems.size());
}
}
void enqueuePackageUpdated(PackageUpdatedTask task) {
sWorker.post(task);
}
private class PackageUpdatedTask implements Runnable {
int mOp;
String[] mPackages;
public static final int OP_NONE = 0;
public static final int OP_ADD = 1;
public static final int OP_UPDATE = 2;
public static final int OP_REMOVE = 3; // uninstlled
public static final int OP_UNAVAILABLE = 4; // external media unmounted
public PackageUpdatedTask(int op, String[] packages) {
mOp = op;
mPackages = packages;
}
public void run() {
final Context context = mApp;
final String[] packages = mPackages;
final int N = packages.length;
switch (mOp) {
case OP_ADD:
for (int i=0; i<N; i++) {
if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]);
mAllAppsList.addPackage(context, packages[i]);
}
break;
case OP_UPDATE:
for (int i=0; i<N; i++) {
if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]);
mAllAppsList.updatePackage(context, packages[i]);
}
break;
case OP_REMOVE:
case OP_UNAVAILABLE:
for (int i=0; i<N; i++) {
if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]);
mAllAppsList.removePackage(packages[i]);
}
break;
}
ArrayList<ApplicationInfo> added = null;
ArrayList<ApplicationInfo> removed = null;
ArrayList<ApplicationInfo> modified = null;
if (mAllAppsList.added.size() > 0) {
added = mAllAppsList.added;
mAllAppsList.added = new ArrayList<ApplicationInfo>();
}
if (mAllAppsList.removed.size() > 0) {
removed = mAllAppsList.removed;
mAllAppsList.removed = new ArrayList<ApplicationInfo>();
for (ApplicationInfo info: removed) {
mIconCache.remove(info.intent.getComponent());
}
}
if (mAllAppsList.modified.size() > 0) {
modified = mAllAppsList.modified;
mAllAppsList.modified = new ArrayList<ApplicationInfo>();
}
final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == null) {
Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading.");
return;
}
if (added != null) {
final ArrayList<ApplicationInfo> addedFinal = added;
mHandler.post(new Runnable() {
public void run() {
Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == cb && cb != null) {
callbacks.bindAppsAdded(addedFinal);
}
}
});
}
if (modified != null) {
final ArrayList<ApplicationInfo> modifiedFinal = modified;
mHandler.post(new Runnable() {
public void run() {
Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == cb && cb != null) {
callbacks.bindAppsUpdated(modifiedFinal);
}
}
});
}
if (removed != null) {
final boolean permanent = mOp != OP_UNAVAILABLE;
final ArrayList<ApplicationInfo> removedFinal = removed;
mHandler.post(new Runnable() {
public void run() {
Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == cb && cb != null) {
callbacks.bindAppsRemoved(removedFinal, permanent);
}
}
});
}
mHandler.post(new Runnable() {
@Override
public void run() {
Callbacks cb = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == cb && cb != null) {
callbacks.bindPackagesUpdated();
}
}
});
}
}
/**
* This is called from the code that adds shortcuts from the intent receiver. This
* doesn't have a Cursor, but
*/
public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context) {
return getShortcutInfo(manager, intent, context, null, -1, -1, null);
}
/**
* Make an ShortcutInfo object for a shortcut that is an application.
*
* If c is not null, then it will be used to fill in missing data like the title and icon.
*/
public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context,
Cursor c, int iconIndex, int titleIndex, HashMap<Object, CharSequence> labelCache) {
Bitmap icon = null;
final ShortcutInfo info = new ShortcutInfo();
ComponentName componentName = intent.getComponent();
if (componentName == null) {
return null;
}
// TODO: See if the PackageManager knows about this case. If it doesn't
// then return null & delete this.
// the resource -- This may implicitly give us back the fallback icon,
// but don't worry about that. All we're doing with usingFallbackIcon is
// to avoid saving lots of copies of that in the database, and most apps
// have icons anyway.
final ResolveInfo resolveInfo = manager.resolveActivity(intent, 0);
if (resolveInfo != null) {
icon = mIconCache.getIcon(componentName, resolveInfo, labelCache);
}
// the db
if (icon == null) {
if (c != null) {
icon = getIconFromCursor(c, iconIndex, context);
}
}
// the fallback icon
if (icon == null) {
icon = getFallbackIcon();
info.usingFallbackIcon = true;
}
info.setIcon(icon);
// from the resource
if (resolveInfo != null) {
ComponentName key = LauncherModel.getComponentNameFromResolveInfo(resolveInfo);
if (labelCache != null && labelCache.containsKey(key)) {
info.title = labelCache.get(key);
} else {
info.title = resolveInfo.activityInfo.loadLabel(manager);
if (labelCache != null) {
labelCache.put(key, info.title);
}
}
}
// from the db
if (info.title == null) {
if (c != null) {
info.title = c.getString(titleIndex);
}
}
// fall back to the class name of the activity
if (info.title == null) {
info.title = componentName.getClassName();
}
info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
return info;
}
/**
* Make an ShortcutInfo object for a shortcut that isn't an application.
*/
private ShortcutInfo getShortcutInfo(Cursor c, Context context,
int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex,
int titleIndex) {
Bitmap icon = null;
final ShortcutInfo info = new ShortcutInfo();
info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
// TODO: If there's an explicit component and we can't install that, delete it.
info.title = c.getString(titleIndex);
int iconType = c.getInt(iconTypeIndex);
switch (iconType) {
case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
String packageName = c.getString(iconPackageIndex);
String resourceName = c.getString(iconResourceIndex);
PackageManager packageManager = context.getPackageManager();
info.customIcon = false;
// the resource
try {
Resources resources = packageManager.getResourcesForApplication(packageName);
if (resources != null) {
final int id = resources.getIdentifier(resourceName, null, null);
icon = Utilities.createIconBitmap(
mIconCache.getFullResIcon(resources, id), context);
}
} catch (Exception e) {
// drop this. we have other places to look for icons
}
// the db
if (icon == null) {
icon = getIconFromCursor(c, iconIndex, context);
}
// the fallback icon
if (icon == null) {
icon = getFallbackIcon();
info.usingFallbackIcon = true;
}
break;
case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
icon = getIconFromCursor(c, iconIndex, context);
if (icon == null) {
icon = getFallbackIcon();
info.customIcon = false;
info.usingFallbackIcon = true;
} else {
info.customIcon = true;
}
break;
default:
icon = getFallbackIcon();
info.usingFallbackIcon = true;
info.customIcon = false;
break;
}
info.setIcon(icon);
return info;
}
Bitmap getIconFromCursor(Cursor c, int iconIndex, Context context) {
if (false) {
Log.d(TAG, "getIconFromCursor app="
+ c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE)));
}
byte[] data = c.getBlob(iconIndex);
try {
return Utilities.createIconBitmap(
BitmapFactory.decodeByteArray(data, 0, data.length), context);
} catch (Exception e) {
return null;
}
}
ShortcutInfo addShortcut(Context context, Intent data, long container, int screen,
int cellX, int cellY, boolean notify) {
final ShortcutInfo info = infoFromShortcutIntent(context, data, null);
addItemToDatabase(context, info, container, screen, cellX, cellY, notify);
return info;
}
/**
* Attempts to find an AppWidgetProviderInfo that matches the given component.
*/
AppWidgetProviderInfo findAppWidgetProviderInfoWithComponent(Context context,
ComponentName component) {
List<AppWidgetProviderInfo> widgets =
AppWidgetManager.getInstance(context).getInstalledProviders();
for (AppWidgetProviderInfo info : widgets) {
if (info.provider.equals(component)) {
return info;
}
}
return null;
}
/**
* Returns a list of all the widgets that can handle configuration with a particular mimeType.
*/
List<WidgetMimeTypeHandlerData> resolveWidgetsForMimeType(Context context, String mimeType) {
final PackageManager packageManager = context.getPackageManager();
final List<WidgetMimeTypeHandlerData> supportedConfigurationActivities =
new ArrayList<WidgetMimeTypeHandlerData>();
final Intent supportsIntent =
new Intent(InstallWidgetReceiver.ACTION_SUPPORTS_CLIPDATA_MIMETYPE);
supportsIntent.setType(mimeType);
// Create a set of widget configuration components that we can test against
final List<AppWidgetProviderInfo> widgets =
AppWidgetManager.getInstance(context).getInstalledProviders();
final HashMap<ComponentName, AppWidgetProviderInfo> configurationComponentToWidget =
new HashMap<ComponentName, AppWidgetProviderInfo>();
for (AppWidgetProviderInfo info : widgets) {
configurationComponentToWidget.put(info.configure, info);
}
// Run through each of the intents that can handle this type of clip data, and cross
// reference them with the components that are actual configuration components
final List<ResolveInfo> activities = packageManager.queryIntentActivities(supportsIntent,
PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo info : activities) {
final ActivityInfo activityInfo = info.activityInfo;
final ComponentName infoComponent = new ComponentName(activityInfo.packageName,
activityInfo.name);
if (configurationComponentToWidget.containsKey(infoComponent)) {
supportedConfigurationActivities.add(
new InstallWidgetReceiver.WidgetMimeTypeHandlerData(info,
configurationComponentToWidget.get(infoComponent)));
}
}
return supportedConfigurationActivities;
}
ShortcutInfo infoFromShortcutIntent(Context context, Intent data, Bitmap fallbackIcon) {
Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
Bitmap icon = null;
boolean customIcon = false;
ShortcutIconResource iconResource = null;
if (bitmap != null && bitmap instanceof Bitmap) {
icon = Utilities.createIconBitmap(new FastBitmapDrawable((Bitmap)bitmap), context);
customIcon = true;
} else {
Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
if (extra != null && extra instanceof ShortcutIconResource) {
try {
iconResource = (ShortcutIconResource) extra;
final PackageManager packageManager = context.getPackageManager();
Resources resources = packageManager.getResourcesForApplication(
iconResource.packageName);
final int id = resources.getIdentifier(iconResource.resourceName, null, null);
icon = Utilities.createIconBitmap(
mIconCache.getFullResIcon(resources, id), context);
} catch (Exception e) {
Log.w(TAG, "Could not load shortcut icon: " + extra);
}
}
}
final ShortcutInfo info = new ShortcutInfo();
if (icon == null) {
if (fallbackIcon != null) {
icon = fallbackIcon;
} else {
icon = getFallbackIcon();
info.usingFallbackIcon = true;
}
}
info.setIcon(icon);
info.title = name;
info.intent = intent;
info.customIcon = customIcon;
info.iconResource = iconResource;
return info;
}
boolean queueIconToBeChecked(HashMap<Object, byte[]> cache, ShortcutInfo info, Cursor c,
int iconIndex) {
// If apps can't be on SD, don't even bother.
if (!mAppsCanBeOnExternalStorage) {
return false;
}
// If this icon doesn't have a custom icon, check to see
// what's stored in the DB, and if it doesn't match what
// we're going to show, store what we are going to show back
// into the DB. We do this so when we're loading, if the
// package manager can't find an icon (for example because
// the app is on SD) then we can use that instead.
if (!info.customIcon && !info.usingFallbackIcon) {
cache.put(info, c.getBlob(iconIndex));
return true;
}
return false;
}
void updateSavedIcon(Context context, ShortcutInfo info, byte[] data) {
boolean needSave = false;
try {
if (data != null) {
Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length);
Bitmap loaded = info.getIcon(mIconCache);
needSave = !saved.sameAs(loaded);
} else {
needSave = true;
}
} catch (Exception e) {
needSave = true;
}
if (needSave) {
Log.d(TAG, "going to save icon bitmap for info=" + info);
// This is slower than is ideal, but this only happens once
// or when the app is updated with a new icon.
updateItemInDatabase(context, info);
}
}
/**
* Return an existing FolderInfo object if we have encountered this ID previously,
* or make a new one.
*/
private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) {
// See if a placeholder was created for us already
FolderInfo folderInfo = folders.get(id);
if (folderInfo == null) {
// No placeholder -- create a new instance
folderInfo = new FolderInfo();
folders.put(id, folderInfo);
}
return folderInfo;
}
private static final Collator sCollator = Collator.getInstance();
public static final Comparator<ApplicationInfo> APP_NAME_COMPARATOR
= new Comparator<ApplicationInfo>() {
public final int compare(ApplicationInfo a, ApplicationInfo b) {
int result = sCollator.compare(a.title.toString(), b.title.toString());
if (result == 0) {
result = a.componentName.compareTo(b.componentName);
}
return result;
}
};
public static final Comparator<ApplicationInfo> APP_INSTALL_TIME_COMPARATOR
= new Comparator<ApplicationInfo>() {
public final int compare(ApplicationInfo a, ApplicationInfo b) {
if (a.firstInstallTime < b.firstInstallTime) return 1;
if (a.firstInstallTime > b.firstInstallTime) return -1;
return 0;
}
};
public static final Comparator<AppWidgetProviderInfo> WIDGET_NAME_COMPARATOR
= new Comparator<AppWidgetProviderInfo>() {
public final int compare(AppWidgetProviderInfo a, AppWidgetProviderInfo b) {
return sCollator.compare(a.label.toString(), b.label.toString());
}
};
static ComponentName getComponentNameFromResolveInfo(ResolveInfo info) {
if (info.activityInfo != null) {
return new ComponentName(info.activityInfo.packageName, info.activityInfo.name);
} else {
return new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name);
}
}
public static class ShortcutNameComparator implements Comparator<ResolveInfo> {
private PackageManager mPackageManager;
private HashMap<Object, CharSequence> mLabelCache;
ShortcutNameComparator(PackageManager pm) {
mPackageManager = pm;
mLabelCache = new HashMap<Object, CharSequence>();
}
ShortcutNameComparator(PackageManager pm, HashMap<Object, CharSequence> labelCache) {
mPackageManager = pm;
mLabelCache = labelCache;
}
public final int compare(ResolveInfo a, ResolveInfo b) {
CharSequence labelA, labelB;
ComponentName keyA = LauncherModel.getComponentNameFromResolveInfo(a);
ComponentName keyB = LauncherModel.getComponentNameFromResolveInfo(b);
if (mLabelCache.containsKey(keyA)) {
labelA = mLabelCache.get(keyA);
} else {
labelA = a.loadLabel(mPackageManager).toString();
mLabelCache.put(keyA, labelA);
}
if (mLabelCache.containsKey(keyB)) {
labelB = mLabelCache.get(keyB);
} else {
labelB = b.loadLabel(mPackageManager).toString();
mLabelCache.put(keyB, labelB);
}
return sCollator.compare(labelA, labelB);
}
};
public static class WidgetAndShortcutNameComparator implements Comparator<Object> {
private PackageManager mPackageManager;
private HashMap<Object, String> mLabelCache;
WidgetAndShortcutNameComparator(PackageManager pm) {
mPackageManager = pm;
mLabelCache = new HashMap<Object, String>();
}
public final int compare(Object a, Object b) {
String labelA, labelB;
if (mLabelCache.containsKey(a)) {
labelA = mLabelCache.get(a);
} else {
labelA = (a instanceof AppWidgetProviderInfo) ?
((AppWidgetProviderInfo) a).label :
((ResolveInfo) a).loadLabel(mPackageManager).toString();
mLabelCache.put(a, labelA);
}
if (mLabelCache.containsKey(b)) {
labelB = mLabelCache.get(b);
} else {
labelB = (b instanceof AppWidgetProviderInfo) ?
((AppWidgetProviderInfo) b).label :
((ResolveInfo) b).loadLabel(mPackageManager).toString();
mLabelCache.put(b, labelB);
}
return sCollator.compare(labelA, labelB);
}
};
public void dumpState() {
Log.d(TAG, "mCallbacks=" + mCallbacks);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mAllAppsList.data);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mAllAppsList.added);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mAllAppsList.removed);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mAllAppsList.modified);
if (mLoaderTask != null) {
mLoaderTask.dumpState();
} else {
Log.d(TAG, "mLoaderTask=null");
}
}
}
|
diff --git a/srcj/com/sun/electric/tool/Job.java b/srcj/com/sun/electric/tool/Job.java
index 633b5726e..2eb20fd95 100644
--- a/srcj/com/sun/electric/tool/Job.java
+++ b/srcj/com/sun/electric/tool/Job.java
@@ -1,771 +1,771 @@
/* -*- tab-width: 4 -*-
*
* Electric(tm) VLSI Design System
*
* File: Job.java
*
* Copyright (c) 2003 Sun Microsystems and Static Free Software
*
* Electric(tm) is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* Electric(tm) is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Electric(tm); see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, Mass 02111-1307, USA.
*/
package com.sun.electric.tool;
import com.sun.electric.database.EditingPreferences;
import com.sun.electric.database.Environment;
import com.sun.electric.database.Snapshot;
import com.sun.electric.database.hierarchy.Cell;
import com.sun.electric.database.hierarchy.EDatabase;
import com.sun.electric.database.hierarchy.Library;
import com.sun.electric.database.id.CellId;
import com.sun.electric.database.id.IdManager;
import com.sun.electric.database.id.IdReader;
import com.sun.electric.database.id.IdWriter;
import com.sun.electric.database.id.LibId;
import com.sun.electric.database.id.TechId;
import com.sun.electric.database.text.Pref;
import com.sun.electric.database.text.TextUtils;
import com.sun.electric.database.variable.UserInterface;
import com.sun.electric.technology.TechPool;
import com.sun.electric.technology.Technology;
import com.sun.electric.tool.user.ActivityLogger;
import com.sun.electric.tool.user.CantEditException;
import com.sun.electric.tool.user.ErrorLogger;
import java.io.IOException;
import java.io.Serializable;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Logger;
/**
* Jobs are processes that will run in the background, such as
* DRC, NCC, Netlisters, etc. Each Job gets placed in a Job
* window, and reports its status. A job can be cancelled.
*
* <p>To start a new job, do:
* <p>Job job = new Job(name);
* <p>job.start();
*
* <p>Job subclass must implement "doIt" method, it may override "terminateOK" method.
* <p>Job subclass is activated by "Job.startJob()". In case of exception in constructor it is not activated.
* Hence "doIt" and "terminateOK" method are not called.
* <p>Job subclass must be serializable for CHANGE and REMOTE_EXAMINE mode.
* Serialization occurs at the moment when "Job.startJob()" is called.
* Fields that are not needed on the server are escaped from serialization by "transient" keyword.
* "doIt" is executed on serverDatabase for CHANGE and REMOTE_EXAMINE mode.
* "doIt" is executed on clientDatabase for EXAMINE mode, Job subclass need not be serializable.
* <p>"doIt" may return true, may return false, may throw JobException or any other Exception/Error.
* Return true is considered normal termination.
* Return false and throwing any Exception/Throwable are failure terminations.
* <p>On normal termination in CHANGE or REMOTE_EXAMINE mode "fieldVariableChanged" variables are serialized.
* In case of REMOTE_EXAMINE they are serialized on read-only database state.
* In case of CHANGE they are serialized on database state after Constraint propagation.
* In case of EXAMINE they are not serialized, but they are checked for valid field names.
* Some time later the changed variables are deserialized on client database.
* If serialization on server and deserialization on client was OK then terminateOK method is called on client database for
* all three modes CHANGE, REMOTE_EXAMINE, EXAMINE.
* If serialization/deserialization failed then terminateOK is not called, error message is issued.
* <p>In case of failure termination no terminateOK is called, error message is issued,
*
* <p>The extendig class may override getProgress(),
* which returns a string indicating the current status.
* Job also contains boolean abort, which gets set when the user decides
* to abort the Job. The extending class' code should check abort when/where
* applicable.
*
* <p>Note that if your Job calls methods outside of this thread
* that access shared data, those called methods should be synchronized.
*
* @author gainsley
*/
public abstract class Job implements Serializable {
private static boolean GLOBALDEBUG = false;
private static int recommendedNumThreads;
static final int PROTOCOL_VERSION = 19; // Apr 17
public static boolean LOCALDEBUGFLAG; // Gilda's case
// private static final String CLASS_NAME = Job.class.getName();
static final Logger logger = Logger.getLogger("com.sun.electric.tool.job");
/**
* Method to tell whether Electric is running in "debug" mode.
* If the program is started with the "-debug" switch, debug mode is enabled.
* @return true if running in debug mode.
*/
public static boolean getDebug() { return GLOBALDEBUG; }
public static void setDebug(boolean f) { GLOBALDEBUG = f; }
/**
* Type is a typesafe enum class that describes the type of job (CHANGE or EXAMINE).
*/
public static enum Type {
/** Describes a server database change. */ CHANGE,
/** Describes a server database undo/redo. */ UNDO,
/** Describes a server database examination. */ SERVER_EXAMINE,
/** Describes a client database examination. */ CLIENT_EXAMINE;
}
/**
* Priority is a typesafe enum class that describes the priority of a job.
*/
public static enum Priority {
/** The highest priority: from the user. */ USER,
/** Next lower priority: visible changes. */ VISCHANGES,
/** Next lower priority: invisible changes. */ INVISCHANGES,
/** Lowest priority: analysis. */ ANALYSIS;
}
/** default execution time in milis */ /*private*/ public static final int MIN_NUM_SECONDS = 60000;
/** job manager */ /*private*/ static JobManager jobManager;
/** job manager */ /*private*/ static ServerJobManager serverJobManager;
/** job manager */ /*private*/ static ClientJobManager clientJobManager;
static AbstractUserInterface currentUI;
static Thread clientThread;
/** delete when done if true */ /*private*/ boolean deleteWhenDone;
// Job Status
/** job start time */ public /*protected*/ long startTime;
/** job end time */ public /*protected*/ long endTime;
/** was job started? */ /*private*/boolean started;
/** is job finished? */ /*private*/ public boolean finished;
/** thread aborted? */ /*private*/ boolean aborted;
/** schedule thread to abort */ /*private*/ boolean scheduledToAbort;
/** report execution time regardless MIN_NUM_SECONDS */
/*private*/ public boolean reportExecution = false;
/** tool running the job */ /*private*/ Tool tool;
/** current technology */ final TechId curTechId;
/** current library */ final LibId curLibId;
/** current Cell */ final CellId curCellId;
// /** priority of job */ private Priority priority;
// /** bottom of "up-tree" of cells affected */private Cell upCell;
// /** top of "down-tree" of cells affected */ private Cell downCell;
// /** status */ private String status = null;
transient EJob ejob;
transient EDatabase database;
public static void initJobManager(int numThreads, String loggingFilePath, int socketPort, AbstractUserInterface ui, Job initDatabaseJob) {
Job.recommendedNumThreads = numThreads;
currentUI = ui;
jobManager = serverJobManager = new ServerJobManager(numThreads, loggingFilePath, false, socketPort);
serverJobManager.runLoop(initDatabaseJob);
}
public static void pipeServer(int numThreads, String loggingFilePath, int socketPort) {
Pref.forbidPreferences();
EDatabase.setServerDatabase(new EDatabase(IdManager.stdIdManager.getInitialSnapshot()));
Tool.initAllTools();
jobManager = serverJobManager = new ServerJobManager(numThreads, loggingFilePath, true, socketPort);
}
public static void socketClient(String serverMachineName, int socketPort, AbstractUserInterface ui, Job initDatabaseJob) {
currentUI = ui;
try {
jobManager = clientJobManager = new ClientJobManager(serverMachineName, socketPort);
clientJobManager.runLoop(initDatabaseJob);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void pipeClient(Process process, AbstractUserInterface ui, Job initDatabaseJob, boolean skipOneLine) {
currentUI = ui;
try {
jobManager = clientJobManager = new ClientJobManager(process, skipOneLine);
clientJobManager.runLoop(initDatabaseJob);
} catch (IOException e) {
e.printStackTrace();
}
}
// public static Mode getRunMode() { return threadMode; }
// public static int getNumThreads() { return recommendedNumThreads; }
/**
* Constructor creates a new instance of Job.
* @param jobName a string that describes this Job.
* @param tool the Tool that originated this Job.
* @param jobType the Type of this Job (EXAMINE or CHANGE).
* @param upCell the Cell at the bottom of a hierarchical "up cone" of change.
* If this and "downCell" are null, the entire database is presumed.
* @param downCell the Cell at the top of a hierarchical "down tree" of changes/examinations.
* If this and "upCell" are null, the entire database is presumed.
* @param priority the priority of this Job.
*/
public Job(String jobName, Tool tool, Type jobType, Cell upCell, Cell downCell, Priority priority) {
ejob = new EJob(this, jobType, jobName, EditingPreferences.getThreadEditingPreferences());
UserInterface ui = getUserInterface();
database = ui != null ? ui.getDatabase() : EDatabase.clientDatabase();
this.tool = tool;
this.deleteWhenDone = true;
startTime = endTime = 0;
Technology curTech = ui != null ? ui.getCurrentTechnology() : null;
curTechId = curTech != null ? curTech.getId() : null;
Library curLib = ui != null ? ui.getCurrentLibrary() : null;
curLibId = curLib != null ? curLib.getId() : null;
Cell curCell = ui != null ? ui.getCurrentCell() : null;
curCellId = curCell != null ? curCell.getId() : null;
// started = finished = aborted = scheduledToAbort = false;
// thread = null;
}
/**
* Start a job. By default displays Job on Job List UI, and
* delete Job when done. Jobs that have state the user would like to use
* after the Job finishes (like DRC, NCC, etc) should call
* <code>startJob(true, true)</code>.
*/
public void startJob()
{
startJob(true);
}
/**
* Start a job on snapshot obtained at the end of current job. By default displays Job on Job List UI, and
* delete Job when done.
*/
public void startJobOnMyResult()
{
startJob(true, true);
}
/**
* Start the job by placing it on the JobThread queue.
* If <code>deleteWhenDone</code> is true, Job will be deleted
* after it is done (frees all data and references it stores/created)
* @param deleteWhenDone delete when job is done if true, otherwise leave it around
*/
public void startJob(boolean deleteWhenDone) {
startJob(deleteWhenDone, false);
}
/**
* Start the job by placing it on the JobThread queue.
* If <code>deleteWhenDone</code> is true, Job will be deleted
* after it is done (frees all data and references it stores/created)
* @param deleteWhenDone delete when job is done if true, otherwise leave it around
*/
private void startJob(boolean deleteWhenDone, boolean onMySnapshot)
{
this.deleteWhenDone = deleteWhenDone;
UserInterface ui = getUserInterface();
Job.Key curJobKey = ui.getJobKey();
- boolean startedByServer = curJobKey.jobId > 0;
+ boolean startedByServer = curJobKey.doItOnServer;
boolean doItOnServer = ejob.jobType != Job.Type.CLIENT_EXAMINE;
// Thread currentThread = Thread.currentThread();
if (startedByServer) {
// if (currentThread instanceof EThread && ((EThread)currentThread).ejob.jobType != Job.Type.CLIENT_EXAMINE) {
ejob.startedByServer = true;
ejob.client = Job.serverJobManager.serverConnections.get(curJobKey.clientId);
// ejob.client = ((EThread)currentThread).ejob.client;
ejob.jobKey = ejob.client.newJobId(ejob.startedByServer, doItOnServer);
ejob.serverJob.startTime = System.currentTimeMillis();
ejob.serialize(EDatabase.serverDatabase());
ejob.clientJob = null;
} else {
ejob.client = Job.getExtendedUserInterface();
ejob.jobKey = ejob.client.newJobId(ejob.startedByServer, doItOnServer);
ejob.clientJob.startTime = System.currentTimeMillis();
ejob.serverJob = null;
if (doItOnServer)
ejob.serialize(EDatabase.clientDatabase());
}
jobManager.addJob(ejob, onMySnapshot);
}
/**
* Method to remember that a field variable of the Job has been changed by the doIt() method.
* @param variableName the name of the variable that changed.
*/
protected void fieldVariableChanged(String variableName) { ejob.fieldVariableChanged(variableName); }
//--------------------------ABSTRACT METHODS--------------------------
/** This is the main work method. This method should
* perform all needed tasks.
* @throws JobException TODO
*/
public abstract boolean doIt() throws JobException;
/**
* This method executes in the Client side after termination of doIt method.
* This method should perform all needed termination actions.
* @param jobException null if doIt terminated normally, otherwise exception thrown by doIt.
*/
public void terminateIt(Throwable jobException) {
if (jobException == null)
terminateOK();
else
terminateFail(jobException);
}
/**
* This method executes in the Client side after normal termination of doIt method.
* This method should perform all needed termination actions.
*/
public void terminateOK() {}
/**
* This method executes in the Client side after exceptional termination of doIt method.
* @param jobException null exception thrown by doIt.
*/
public void terminateFail(Throwable jobException) {
if (jobException instanceof CantEditException) {
((CantEditException)jobException).presentProblem();
} else if (jobException instanceof JobException) {
String message = jobException.getMessage();
if (message == null)
message = "Job " + ejob.jobName + " failed";
System.out.println(message);
} else {
ActivityLogger.logException(jobException);
}
}
//--------------------------PRIVATE JOB METHODS--------------------------
//--------------------------PROTECTED JOB METHODS-----------------------
/** Set reportExecution flag on/off */
protected void setReportExecutionFlag(boolean flag)
{
reportExecution = flag;
}
//--------------------------PUBLIC JOB METHODS--------------------------
// /**
// * Method to end the current batch of changes and start another.
// * Besides starting a new batch, it cleans up the constraint system, and
// */
// protected void flushBatch()
// {
// if (jobType != Type.CHANGE) return;
// Undo.endChanges();
// Undo.startChanges(tool, jobName, /*upCell,*/ savedHighlights, savedHighlightsOffset);
// }
protected synchronized void setProgress(String progress) {
jobManager.setProgress(ejob, progress);
}
private synchronized String getProgress() { return ejob.progress; }
/** Return run status */
public boolean isFinished() { return finished; }
/** Tell thread to abort. Extending class should check
* abort when/where applicable
*/
public synchronized void abort() {
// if (ejob.jobType != Job.Type.EXAMINE) return;
if (aborted) {
System.out.println("Job already aborted: "+getStatus());
return;
}
scheduledToAbort = true;
if (ejob.jobType != Job.Type.CLIENT_EXAMINE && ejob.serverJob != null)
ejob.serverJob.scheduledToAbort = true;
// Job.getUserInterface().wantToRedoJobTree();
}
/** Confirmation that thread is aborted */
private synchronized void setAborted() { aborted = true; /*Job.getUserInterface().wantToRedoJobTree();*/ }
/** get scheduled to abort status */
protected synchronized boolean getScheduledToAbort() { return scheduledToAbort; }
/**
* Method to get abort status. Please leave this function as private.
* To retrieve abort status from another class, use checkAbort which also
* checks if job is scheduled to be aborted.
* @return
*/
private synchronized boolean getAborted() { return aborted; }
/** get deleteWhenDone status */
public boolean getDeleteWhenDone() { return deleteWhenDone; }
/**
* Check if we are scheduled to abort. If so, print msg if non null
* and return true.
* This is because setAbort and getScheduledToAbort
* are protected in Job.
* @return true on abort, false otherwise. If job is scheduled for abort or aborted.
* and it will report it to std output
*/
public boolean checkAbort()
{
// if (ejob.jobType != Job.Type.EXAMINE) return false;
if (getAborted()) return (true);
boolean scheduledAbort = getScheduledToAbort();
if (scheduledAbort)
{
System.out.println(this + ": aborted"); // should call Job.toString()
setReportExecutionFlag(true); // Force reporting
setAborted(); // Job has been aborted
}
return scheduledAbort;
}
/** get all jobs iterator */
public static Iterator<Job> getAllJobs() { return jobManager.getAllJobs(); }
/**
* If this current thread is a EThread running a Job return the Job.
* Return null otherwise.
* @return a running Job or null
*/
public static Job getRunningJob() {
Thread thread = Thread.currentThread();
return thread instanceof EThread ? ((EThread)thread).getRunningJob() : null;
}
/**
* Returns true if this current thread is a EThread running a server Job.
* @return true if this current thread is a EThread running a server Job.
*/
public static boolean inServerThread() {
Thread thread = Thread.currentThread();
return thread instanceof EThread && ((EThread)thread).isServerThread;
}
public static void setCurrentLibraryInJob(Library lib) {
EThread thread = (EThread)Thread.currentThread();
assert thread.ejob.jobType == Type.CHANGE;
thread.userInterface.curLibId = lib != null ? lib.getId() : null;
}
/** get status */
public String getStatus() {
switch (ejob.state) {
// case CLIENT_WAITING: return "cwaiting";
case WAITING:
return "waiting";
case RUNNING:
return getProgress() == null ? "running" : getProgress();
case SERVER_DONE:
return getProgress() == null ? "done" : getProgress();
case CLIENT_DONE:
return "cdone";
}
if (!started) return "waiting";
if (aborted) return "aborted";
if (finished) return "done";
if (scheduledToAbort) return "scheduled to abort";
if (getProgress() == null) return "running";
return getProgress();
}
/** Remove job from Job list if it is done */
public boolean remove() {
if (!finished && !aborted) {
//System.out.println("Cannot delete running jobs. Wait till finished or abort");
return false;
}
jobManager.removeJob(this);
return true;
}
private static final ThreadLocal<UserInterface> threadUserInterface = new ThreadLocal<UserInterface>() {
@Override
protected UserInterface initialValue() {
throw new IllegalStateException();
}
};
public static UserInterface getUserInterface() {
Thread currentThread = Thread.currentThread();
if (currentThread instanceof EThread)
return ((EThread)currentThread).getUserInterface();
else if (currentThread == clientThread)
return currentUI;
else
return threadUserInterface.get();
}
public static void setUserInterface(UserInterface ui) {
Thread currentThread = Thread.currentThread();
assert !(currentThread instanceof EThread) && currentThread != clientThread;
if (ui == null)
throw new UnsupportedOperationException();
threadUserInterface.set(ui);
}
/**
* Low-level method.
*/
public static AbstractUserInterface getExtendedUserInterface() {
// if (!isClientThread())
// ActivityLogger.logException(new IllegalStateException());
return currentUI;
}
public static boolean isClientThread() {
return Thread.currentThread() == clientThread;
}
public EDatabase getDatabase() {
return database;
}
public Environment getEnvironment() {
return database.getEnvironment();
}
public TechPool getTechPool() {
return database.getTechPool();
}
public Tool getTool() {
return tool;
}
public EditingPreferences getEditingPreferences() {
return ejob.editingPreferences;
}
public static void updateNetworkErrors(Cell cell, List<ErrorLogger.MessageLog> errors) {
if (currentUI != null)
currentUI.updateNetworkErrors(cell, errors);
}
public static void updateIncrementalDRCErrors(Cell cell, List<ErrorLogger.MessageLog> newErrors,
List<ErrorLogger.MessageLog> delErrors) {
currentUI.updateIncrementalDRCErrors(cell, newErrors, delErrors);
}
/**
* Find some valid snapshot in cache.
* @return some valid snapshot
*/
public static Snapshot findValidSnapshot() {
return EThread.findValidSnapshot();
}
//-------------------------------JOB UI--------------------------------
public String toString() { return ejob.jobName+" ("+getStatus()+")"; }
/** Get info on Job */
public String getInfo() {
StringBuffer buf = new StringBuffer();
buf.append("Job "+toString());
//buf.append(" start time: "+start+"\n");
if (finished) {
// Date end = new Date(endTime);
//buf.append(" end time: "+end+"\n");
long time = endTime - startTime;
buf.append(" took: "+TextUtils.getElapsedTime(time));
Date start = new Date(startTime);
buf.append(" (started at "+start+")");
} else if (getProgress() == null) {
long time = System.currentTimeMillis()-startTime;
buf.append(" has not finished. Current running time: " + TextUtils.getElapsedTime(time));
} else {
buf.append(" did not successfully finish.");
}
return buf.toString();
}
// static void runTerminate(EJob ejob) {
// Throwable jobException = ejob.deserializeResult();
// Job job = ejob.clientJob;
// try {
// job.terminateIt(jobException);
// } catch (Throwable e) {
// System.out.println("Exception executing terminateIt");
// e.printStackTrace(System.out);
// }
// job.endTime = System.currentTimeMillis();
// job.finished = true; // is this redundant with Thread.isAlive()?
//
// // say something if it took more than a minute by default
// if (job.reportExecution || (job.endTime - job.startTime) >= MIN_NUM_SECONDS) {
// if (User.isBeepAfterLongJobs()) {
// Toolkit.getDefaultToolkit().beep();
// }
// System.out.println(job.getInfo());
// }
// }
public Key getKey() {
return ejob.jobKey;
}
public Inform getInform() {
return new Inform(this);
}
/**
* Identifies a Job in a given Electric client/server session.
* Job obtains its Key in startJob method.
* Also can identify Jobless context (for example Client's Gui)
*/
public static class Key implements Serializable {
/**
* Client which launched the Job
*/
public final int clientId;
/**
* Job id.
* 0 - Jobless context
* positive - Job started from server side
* negative - Job started from client side
*/
public final int jobId;
public final boolean doItOnServer;
Key(int clientId, int jobId, boolean doItOnServer) {
this.clientId = clientId;
this.jobId = jobId;
this.doItOnServer = doItOnServer;
}
Key(Client client, int jobId, boolean doItOnServer) {
this(client.connectionId, jobId, doItOnServer);
}
@Override
public boolean equals(Object o) {
if (o == this) return true;
if (o instanceof Key) {
Key that = (Key)o;
if (this.clientId == that.clientId && this.jobId == that.jobId) {
assert this.doItOnServer == that.doItOnServer;
return true;
}
}
return false;
}
@Override
public int hashCode() {
return jobId;
}
public void write(IdWriter writer) throws IOException {
writer.writeInt(clientId);
writer.writeInt(jobId);
writer.writeBoolean(doItOnServer);
}
public static Key read(IdReader reader) throws IOException {
int clientId = reader.readInt();
int jobId = reader.readInt();
boolean doItOnServer = reader.readBoolean();
return new Key(clientId, jobId, doItOnServer);
}
}
public static class Inform implements Serializable {
private final Key jobKey;
private final boolean isChange;
private final String toString;
private final long startTime;
private final long endTime;
private final int finished;
Inform(Job job) {
jobKey = job.getKey();
isChange = (job.ejob.jobType == Type.CHANGE) || (job.ejob.jobType == Type.UNDO);
toString = job.toString();
startTime = job.startTime;
endTime = job.endTime;
if (job.finished)
finished = 1;
else if (job.getProgress() == null)
finished = 0;
else
finished = -1;
}
Inform(Key jobKey, boolean isChange, String toString, long startTime, long endTime, int finished) {
this.jobKey = jobKey;
this.isChange = isChange;
this.toString = toString;
this.startTime = startTime;
this.endTime = endTime;
this.finished = finished;
}
public void abort() {
for (Iterator<Job> it = getAllJobs(); it.hasNext(); ) {
Job job = it.next();
if (job.getKey().equals(jobKey)) {
job.abort();
break;
}
}
}
public boolean remove() { return false; /*return job.remove();*/ }
public Key getKey() { return jobKey; }
@Override
public String toString() { return toString; }
public String getInfo() {
StringBuilder buf = new StringBuilder();
buf.append("Job "+toString());
//buf.append(" start time: "+start+"\n");
if (finished == 1) {
// Date end = new Date(endTime);
//buf.append(" end time: "+end+"\n");
long time = endTime - startTime;
buf.append(" took: "+TextUtils.getElapsedTime(time));
Date start = new Date(startTime);
buf.append(" (started at "+start+")");
} else if (finished == 0) {
long time = System.currentTimeMillis()-startTime;
buf.append(" has not finished. Current running time: " + TextUtils.getElapsedTime(time));
} else {
buf.append(" did not successfully finish.");
}
return buf.toString();
}
public boolean isChangeJobQueuedOrRunning() {
return finished != 1 && isChange;
}
public void write(IdWriter writer) throws IOException {
jobKey.write(writer);
writer.writeBoolean(isChange);
writer.writeString(toString);
writer.writeLong(startTime);
writer.writeLong(endTime);
writer.writeInt(finished);
}
public static Inform read(IdReader reader) throws IOException {
Key jobKey = Key.read(reader);
boolean isChange = reader.readBoolean();
String toString = reader.readString();
long startTime = reader.readLong();
long endTime = reader.readLong();
int finished = reader.readInt();
return new Inform(jobKey, isChange, toString, startTime, endTime, finished);
}
}
}
| true | true | private void startJob(boolean deleteWhenDone, boolean onMySnapshot)
{
this.deleteWhenDone = deleteWhenDone;
UserInterface ui = getUserInterface();
Job.Key curJobKey = ui.getJobKey();
boolean startedByServer = curJobKey.jobId > 0;
boolean doItOnServer = ejob.jobType != Job.Type.CLIENT_EXAMINE;
// Thread currentThread = Thread.currentThread();
if (startedByServer) {
// if (currentThread instanceof EThread && ((EThread)currentThread).ejob.jobType != Job.Type.CLIENT_EXAMINE) {
ejob.startedByServer = true;
ejob.client = Job.serverJobManager.serverConnections.get(curJobKey.clientId);
// ejob.client = ((EThread)currentThread).ejob.client;
ejob.jobKey = ejob.client.newJobId(ejob.startedByServer, doItOnServer);
ejob.serverJob.startTime = System.currentTimeMillis();
ejob.serialize(EDatabase.serverDatabase());
ejob.clientJob = null;
} else {
ejob.client = Job.getExtendedUserInterface();
ejob.jobKey = ejob.client.newJobId(ejob.startedByServer, doItOnServer);
ejob.clientJob.startTime = System.currentTimeMillis();
ejob.serverJob = null;
if (doItOnServer)
ejob.serialize(EDatabase.clientDatabase());
}
jobManager.addJob(ejob, onMySnapshot);
}
| private void startJob(boolean deleteWhenDone, boolean onMySnapshot)
{
this.deleteWhenDone = deleteWhenDone;
UserInterface ui = getUserInterface();
Job.Key curJobKey = ui.getJobKey();
boolean startedByServer = curJobKey.doItOnServer;
boolean doItOnServer = ejob.jobType != Job.Type.CLIENT_EXAMINE;
// Thread currentThread = Thread.currentThread();
if (startedByServer) {
// if (currentThread instanceof EThread && ((EThread)currentThread).ejob.jobType != Job.Type.CLIENT_EXAMINE) {
ejob.startedByServer = true;
ejob.client = Job.serverJobManager.serverConnections.get(curJobKey.clientId);
// ejob.client = ((EThread)currentThread).ejob.client;
ejob.jobKey = ejob.client.newJobId(ejob.startedByServer, doItOnServer);
ejob.serverJob.startTime = System.currentTimeMillis();
ejob.serialize(EDatabase.serverDatabase());
ejob.clientJob = null;
} else {
ejob.client = Job.getExtendedUserInterface();
ejob.jobKey = ejob.client.newJobId(ejob.startedByServer, doItOnServer);
ejob.clientJob.startTime = System.currentTimeMillis();
ejob.serverJob = null;
if (doItOnServer)
ejob.serialize(EDatabase.clientDatabase());
}
jobManager.addJob(ejob, onMySnapshot);
}
|
diff --git a/src/knapsack/KnapSackMutation.java b/src/knapsack/KnapSackMutation.java
index 2a388e6..4b05863 100644
--- a/src/knapsack/KnapSackMutation.java
+++ b/src/knapsack/KnapSackMutation.java
@@ -1,23 +1,19 @@
package knapsack;
import java.util.BitSet;
import java.util.Random;
import model.Genome;
import model.Mutation;
public class KnapSackMutation implements Mutation {
private Random rand = new Random();
public Genome mutate(Genome victim) {
BitSet bits = victim.getBits();
int length = bits.length();
- if (length == -1) {
- bits.flip(rand.nextInt(0));
- }
- else {
- bits.flip(length);
- }
+ System.out.println(length);
+ bits.flip(rand.nextInt(length));
return new Genome(bits);
}
}
| true | true | public Genome mutate(Genome victim) {
BitSet bits = victim.getBits();
int length = bits.length();
if (length == -1) {
bits.flip(rand.nextInt(0));
}
else {
bits.flip(length);
}
return new Genome(bits);
}
| public Genome mutate(Genome victim) {
BitSet bits = victim.getBits();
int length = bits.length();
System.out.println(length);
bits.flip(rand.nextInt(length));
return new Genome(bits);
}
|
diff --git a/flexodesktop/modules/flexoworkfloweditor/src/main/java/org/openflexo/wkf/controller/WKFClipboard.java b/flexodesktop/modules/flexoworkfloweditor/src/main/java/org/openflexo/wkf/controller/WKFClipboard.java
index ff92280d7..f8c125cb2 100644
--- a/flexodesktop/modules/flexoworkfloweditor/src/main/java/org/openflexo/wkf/controller/WKFClipboard.java
+++ b/flexodesktop/modules/flexoworkfloweditor/src/main/java/org/openflexo/wkf/controller/WKFClipboard.java
@@ -1,487 +1,488 @@
/*
* (c) Copyright 2010-2011 AgileBirds
*
* This file is part of OpenFlexo.
*
* OpenFlexo is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* OpenFlexo is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenFlexo. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.openflexo.wkf.controller;
import java.awt.geom.Point2D;
import java.io.File;
import java.util.Enumeration;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JComponent;
import javax.swing.JMenuItem;
import org.openflexo.fge.geom.FGEDimension;
import org.openflexo.fge.geom.FGEGeometricObject.Filling;
import org.openflexo.fge.geom.FGEPoint;
import org.openflexo.fge.geom.FGERectangle;
import org.openflexo.foundation.FlexoModelObject;
import org.openflexo.foundation.RepresentableFlexoModelObject;
import org.openflexo.foundation.rm.FlexoProject;
import org.openflexo.foundation.wkf.DuplicateRoleException;
import org.openflexo.foundation.wkf.FlexoLevel;
import org.openflexo.foundation.wkf.FlexoPetriGraph;
import org.openflexo.foundation.wkf.FlexoProcess;
import org.openflexo.foundation.wkf.Role;
import org.openflexo.foundation.wkf.RoleCompound;
import org.openflexo.foundation.wkf.RoleList;
import org.openflexo.foundation.wkf.WKFArtefact;
import org.openflexo.foundation.wkf.WKFGroup;
import org.openflexo.foundation.wkf.WKFObject;
import org.openflexo.foundation.wkf.action.AddPort;
import org.openflexo.foundation.wkf.action.DropWKFElement;
import org.openflexo.foundation.wkf.edge.WKFEdge;
import org.openflexo.foundation.wkf.node.AbstractActivityNode;
import org.openflexo.foundation.wkf.node.LOOPOperator;
import org.openflexo.foundation.wkf.node.NodeCompound;
import org.openflexo.foundation.wkf.node.OperationNode;
import org.openflexo.foundation.wkf.node.PetriGraphNode;
import org.openflexo.foundation.wkf.node.SelfExecutableNode;
import org.openflexo.foundation.wkf.ws.DeletePort;
import org.openflexo.foundation.wkf.ws.FlexoPort;
import org.openflexo.foundation.wkf.ws.InOutPort;
import org.openflexo.foundation.wkf.ws.InPort;
import org.openflexo.foundation.wkf.ws.NewPort;
import org.openflexo.foundation.wkf.ws.OutPort;
import org.openflexo.foundation.wkf.ws.PortRegistery;
import org.openflexo.localization.FlexoLocalization;
import org.openflexo.selection.FlexoClipboard;
import org.openflexo.selection.PastingGraphicalContext;
import org.openflexo.toolbox.FileUtils;
import org.openflexo.view.controller.FlexoController;
import org.openflexo.wkf.processeditor.ProcessEditorConstants;
import org.openflexo.xmlcode.XMLSerializable;
/**
* WKFClipboard is intented to be the object working with the
* WKFSelectionManager and storing copied, cutted and pasted objects. Handled
* objects are instances implementing
* {@link org.openflexo.selection.SelectableView}.
*
* @author sguerin
*/
public class WKFClipboard extends FlexoClipboard {
private static final Logger logger = Logger.getLogger(WKFClipboard.class.getPackage().getName());
protected WKFSelectionManager _wkfSelectionManager;
private FlexoModelObject _clipboardData;
private FlexoLevel currentCopyLevel = null;
public WKFClipboard(WKFSelectionManager aSelectionManager, JMenuItem copyMenuItem, JMenuItem pasteMenuItem, JMenuItem cutMenuItem) {
super(aSelectionManager, copyMenuItem, pasteMenuItem, cutMenuItem);
_wkfSelectionManager = aSelectionManager;
resetClipboard();
}
public WKFSelectionManager getSelectionManager() {
return _wkfSelectionManager;
}
public WKFController getWKFController() {
return getSelectionManager().getWKFController();
}
@Override
public boolean performSelectionPaste() {
if (_isPasteEnabled) {
/*
* if (getWKFController().getFlexoPaletteWindow().hasFocus()) {
* //JTabbedPane tabs =
* getWKFController().getFlexoPaletteWindow().currentTabbedPane;
* //String selectedTabName =
* tabs.getComponent(tabs.getSelectedIndex()).getName(); String
* selectedTabName =
* getWKFController().getFlexoPaletteWindow().getPalette
* ().getCurrentPalettePanel().getName(); File dir = new
* File(((WKFPalette
* )getWKFController().getFlexoPaletteWindow().getPalette
* ()).paletteDirectory(), selectedTabName); String exportedName =
* WKFController
* .askForString("Please enter a name for the exported element.");
* exportClipboardToPalette(dir, exportedName);
* getWKFController().recreatePalette(); return true; } else {
*/
return super.performSelectionPaste();
// }
} else {
if (logger.isLoggable(Level.FINE)) {
logger.fine("Sorry, PASTE disabled");
}
return false;
}
}
@Override
protected void performSelectionPaste(FlexoModelObject pastingContext, PastingGraphicalContext graphicalContext)
{
logger.info("performSelectionPaste() with context "+pastingContext);
JComponent targetContainer = null;
Point2D location = null;
if (graphicalContext != null) {
targetContainer = graphicalContext.targetContainer;
location = graphicalContext.precisePastingLocation;
if (location==null) {
location = graphicalContext.pastingLocation;
}
}
if (location==null) {
location = new Point2D.Double();
}
if (pastingContext instanceof PetriGraphNode) {
pastingContext = ((PetriGraphNode) pastingContext).getParentPetriGraph();
} else if (pastingContext instanceof WKFArtefact) {
pastingContext = ((WKFArtefact) pastingContext).getParentPetriGraph();
}
if (isTargetValidForPasting(pastingContext)) {
if (logger.isLoggable(Level.FINE)) {
logger.fine("Paste is legal");
}
getSelectionManager().resetSelection();
XMLSerializable pasted = null;
try {
pasted = _clipboardData.cloneUsingXMLMapping();
} catch (Exception ex) {
if (logger.isLoggable(Level.WARNING)) {
logger.warning("Unexpected exception raised during pasting: " + ex.getMessage());
}
ex.printStackTrace();
return;
}
if (pasted instanceof NodeCompound && pastingContext instanceof WKFObject) {
Vector<WKFObject> newSelection = pasteNodeCompound((WKFObject)pastingContext, (NodeCompound)pasted, location);
getWKFController().getSelectionManager().setSelectedObjects(newSelection);
}
else if (pasted instanceof RoleCompound && pastingContext instanceof RoleList) {
Vector<Role> newSelection = pasteRoleCompound((RoleList)pastingContext, (RoleCompound)pasted, location);
getWKFController().getSelectionManager().setSelectedObjects(newSelection);
}
} else {
FlexoController.notify(FlexoLocalization.localizedForKey("cannot_paste_at_this_place_wrong_level"));
if (logger.isLoggable(Level.INFO)) {
logger.info("Paste is NOT legal");
logger.info("pastingContext="+pastingContext+" of "+pastingContext.getClass().getSimpleName());
logger.info("_clipboardData="+_clipboardData);
logger.info("xml="+(_clipboardData!=null?_clipboardData.getXMLRepresentation():null));
}
}
}
protected Vector<WKFObject> pasteNodeCompound(WKFObject pastingContext, NodeCompound pastedCompound, Point2D location)
{
WKFObject container = pastingContext;
FlexoProcess process = container.getProcess();
// We paste as a selection of nodes inside a NodeCompound
NodeCompound compound = pastedCompound;
String context = ProcessEditorConstants.BASIC_PROCESS_EDITOR;
compound.setLocation(location, context);
Vector<WKFObject> newSelection = new Vector<WKFObject>();
FGERectangle bounds = new FGERectangle(new FGEPoint(location), new FGEDimension(0, 0), Filling.FILLED);
for (Enumeration<WKFObject> e = compound.getAllEmbeddedWKFObjects().elements(); e.hasMoreElements();) {
WKFObject node = e.nextElement();
if (node == compound) {
continue;
}
bounds.width = Math.max(bounds.width,node.getX(context)+node.getWidth(context)-bounds.x);
bounds.height = Math.max(bounds.height,node.getY(context)+node.getHeight(context)-bounds.y);
}
// GPO: Not sure it is required, so I leave it but commented
/*bounds.width+=20; // We add this for the borders of the GR
bounds.height+=10;*/
FGERectangle processBounds = new FGERectangle(0, 0, process.getWidth(context), process.getHeight(context), Filling.FILLED);
processBounds = processBounds.rectangleUnion(bounds);
process.setWidth(processBounds.width, context);
process.setHeight(processBounds.height, context);
for (Enumeration<WKFObject> e = compound.getAllEmbeddedWKFObjects().elements(); e.hasMoreElements();) {
WKFObject node = e.nextElement();
if (node == compound) {
continue;
}
insertWKFObject(node, container);
newSelection.add(node);
}
return newSelection;
}
protected Vector<Role> pasteRoleCompound(RoleList pastingContext, RoleCompound pastedCompound, Point2D location)
{
pastedCompound.setLocation(location, RepresentableFlexoModelObject.DEFAULT);
Vector<Role> newSelection = new Vector<Role>();
FGERectangle bounds = new FGERectangle(new FGEPoint(location), new FGEDimension(0, 0), Filling.FILLED);
for (Enumeration<Role> e = pastedCompound.getRoles().elements(); e.hasMoreElements();) {
Role role = e.nextElement();
bounds.width = Math.max(bounds.width,role.getX(RepresentableFlexoModelObject.DEFAULT)+role.getWidth(RepresentableFlexoModelObject.DEFAULT)-bounds.x);
bounds.height = Math.max(bounds.height,role.getY(RepresentableFlexoModelObject.DEFAULT)+role.getHeight(RepresentableFlexoModelObject.DEFAULT)-bounds.y);
}
FGERectangle roleListBounds = new FGERectangle(0, 0, pastingContext.getWidth(RepresentableFlexoModelObject.DEFAULT), pastingContext.getHeight(RepresentableFlexoModelObject.DEFAULT), Filling.FILLED);
roleListBounds = roleListBounds.rectangleUnion(bounds);
pastingContext.setWidth(roleListBounds.width, RepresentableFlexoModelObject.DEFAULT);
pastingContext.setHeight(roleListBounds.height, RepresentableFlexoModelObject.DEFAULT);
for (Enumeration<Role> e = pastedCompound.getRoles().elements(); e.hasMoreElements();) {
Role role = e.nextElement();
insertRole(role, pastingContext);
newSelection.add(role);
}
return newSelection;
}
private void insertRole(Role toInsert, RoleList roleList)
{
logger.info("Insert role "+toInsert);
try {
roleList.addToRoles(toInsert);
}
catch (DuplicateRoleException e) {
int i=1;
String baseName = toInsert.getName();
boolean ok = false;
while (!ok) {
try {
toInsert.setName(baseName+"-"+i);
roleList.addToRoles(toInsert);
ok = true;
} catch (DuplicateRoleException e1) {
i++;
}
}
}
}
public void insertWKFObject(WKFObject toInsert, WKFObject container)
{
if (toInsert instanceof FlexoPort) {
FlexoPort port = (FlexoPort) toInsert;
if (container instanceof PortRegistery) {
AddPort action = null;
if (port instanceof NewPort) {
action = AddPort.createNewPort.makeNewAction(container, null, getWKFController().getEditor());
}
else if (port instanceof DeletePort) {
action = AddPort.createDeletePort.makeNewAction(container, null, getWKFController().getEditor());
}
else if (port instanceof InPort) {
action = AddPort.createInPort.makeNewAction(container, null, getWKFController().getEditor());
}
else if (port instanceof OutPort) {
action = AddPort.createOutPort.makeNewAction(container, null, getWKFController().getEditor());
}
else if (port instanceof InOutPort) {
action = AddPort.createInOutPort.makeNewAction(container, null, getWKFController().getEditor());
}
action.setNewPortName(port.getDefaultName());
action.setEditNodeLabel(false);
action.doAction();
}
} else {
FlexoPetriGraph pg = null;
if (container instanceof SelfExecutableNode) {
pg = ((SelfExecutableNode) container).getExecutionPetriGraph();
}
if (container instanceof FlexoProcess) {
pg = ((FlexoProcess) container).getActivityPetriGraph();
}
if (container instanceof AbstractActivityNode) {
pg = ((AbstractActivityNode) container).getOperationPetriGraph();
}
if (container instanceof OperationNode) {
pg = ((OperationNode) container).getActionPetriGraph();
}
if (container instanceof LOOPOperator) {
pg = ((LOOPOperator) container).getExecutionPetriGraph();
}
if (container instanceof FlexoPetriGraph) {
pg = (FlexoPetriGraph) container;
}
if (container instanceof WKFGroup) {
pg = ((WKFGroup) container).getParentPetriGraph();
}
if (pg!=null) {
DropWKFElement action = DropWKFElement.actionType.makeNewAction(pg, null, getWKFController().getEditor());
action.setObject(toInsert);
action.setResetNodeName(false);
action.setEditNodeLabel(false);
action.setLeaveSubProcessNodeUnchanged(true);
if (container instanceof WKFGroup) {
action.setGroup((WKFGroup) container);
}
action.doAction();
}
}
}
@Override
protected boolean isCurrentSelectionValidForCopy(Vector<FlexoModelObject> currentlySelectedObjects) {
return getSelectionManager().getSelectionSize() > 0;
}
protected void resetClipboard() {
currentCopyLevel = null;
_clipboardData = null;
}
public FlexoModelObject getClipboardData() {
return _clipboardData;
}
/**
* Selection procedure for copy
*/
@Override
protected boolean performCopyOfSelection(Vector<FlexoModelObject> currentlySelectedObjects)
{
logger.info("performCopyOfSelection() for "+currentlySelectedObjects);
// TODO reimplement all of this
resetClipboard();
if (currentlySelectedObjects.size() > 0) {
if (currentlySelectedObjects.firstElement() instanceof PetriGraphNode
+ || currentlySelectedObjects.firstElement() instanceof WKFArtefact
|| currentlySelectedObjects.firstElement() instanceof WKFEdge<?,?>) {
Vector<PetriGraphNode> selectedNodes = new Vector<PetriGraphNode>();
Vector<WKFArtefact> selectedAnnotations = new Vector<WKFArtefact>();
FlexoProcess process = null;
for (Enumeration<FlexoModelObject> e = currentlySelectedObjects.elements(); e.hasMoreElements();) {
FlexoModelObject next = e.nextElement();
if (logger.isLoggable(Level.FINE)) {
logger.fine("Selected: " + next);
}
if (next instanceof PetriGraphNode ) {
PetriGraphNode node = (PetriGraphNode) next;
process = node.getProcess();
selectedNodes.add(node);
} else if (next instanceof WKFArtefact) {
WKFArtefact annotation = (WKFArtefact) next;
process = annotation.getProcess();
selectedAnnotations.add(annotation);
}
}
currentCopyLevel = getSelectionManager().getSelectionLevel();
if (selectedNodes.size() + selectedAnnotations.size() > 0) { // We make
// a
// NodeCompound
_clipboardData = new NodeCompound(process, selectedNodes, selectedAnnotations);
}
}
else if (currentlySelectedObjects.firstElement() instanceof Role) {
FlexoProject project = ((Role)currentlySelectedObjects.firstElement()).getProject();
Vector<Role> rolesToBeCopied = new Vector<Role>();
for (FlexoModelObject o : currentlySelectedObjects) {
if (o instanceof Role) {
rolesToBeCopied.add((Role)o);
}
}
_clipboardData = new RoleCompound(project.getFlexoWorkflow(),rolesToBeCopied);
currentCopyLevel = FlexoLevel.WORKFLOW;
}
}
if (_clipboardData != null) {
// Call XMLRepresentation can be tricky because it trigger XML encoding and later some issues with FlexoID's
// logger.fine("Storing in clipboard: " + _clipboardData.getXMLRepresentation());
}
else {
logger.warning("null value in clipboard ! ");
}
return true;
}
protected boolean isTargetValidForPasting(FlexoModelObject pastingContext)
{
if (pastingContext == null) {
return false;
}
if (_clipboardData instanceof NodeCompound) {
if (pastingContext instanceof PortRegistery) {
return ((NodeCompound)_clipboardData).getLevel() == FlexoLevel.PORT;
} else {
FlexoPetriGraph targetPetriGraph = null;
if (pastingContext instanceof FlexoProcess) {
targetPetriGraph = ((FlexoProcess) pastingContext).getActivityPetriGraph();
} else if (pastingContext instanceof FlexoPetriGraph) {
targetPetriGraph = (FlexoPetriGraph) pastingContext;
} else if (pastingContext instanceof WKFGroup) {
targetPetriGraph = ((WKFGroup)pastingContext).getParentPetriGraph();
} else {
if (logger.isLoggable(Level.INFO)) {
logger.info("Cannot paste into " + pastingContext.getClass().getName());
}
}
if (targetPetriGraph != null) {
return targetPetriGraph.acceptsObject((NodeCompound)_clipboardData);
}
}
}
else if (_clipboardData instanceof RoleCompound) {
if (pastingContext instanceof RoleList) {
return true;
} else if (pastingContext instanceof Role) {
return true;
}
}
return false;
}
protected void exportClipboardToPalette(File paletteDirectory, String newPaletteElementName)
{
if (_clipboardData instanceof NodeCompound) {
NodeCompound compound = (NodeCompound)_clipboardData;
if (compound.isSingleNode()) {
if (!newPaletteElementName.endsWith(".xml")) {
newPaletteElementName = newPaletteElementName + ".xml";
try {
FileUtils.saveToFile(newPaletteElementName, compound.getFirstNode().getXMLRepresentation(), paletteDirectory);
} catch (Exception e) {
if (logger.isLoggable(Level.WARNING)) {
logger.warning("Error occurs while saving node in the palette\n" + e.getMessage());
}
}
}
} else {
if (logger.isLoggable(Level.WARNING)) {
logger.warning("Sorry, but you can't export more than one top level node in the palette");
}
}
}
}
}
| true | true | protected boolean performCopyOfSelection(Vector<FlexoModelObject> currentlySelectedObjects)
{
logger.info("performCopyOfSelection() for "+currentlySelectedObjects);
// TODO reimplement all of this
resetClipboard();
if (currentlySelectedObjects.size() > 0) {
if (currentlySelectedObjects.firstElement() instanceof PetriGraphNode
|| currentlySelectedObjects.firstElement() instanceof WKFEdge<?,?>) {
Vector<PetriGraphNode> selectedNodes = new Vector<PetriGraphNode>();
Vector<WKFArtefact> selectedAnnotations = new Vector<WKFArtefact>();
FlexoProcess process = null;
for (Enumeration<FlexoModelObject> e = currentlySelectedObjects.elements(); e.hasMoreElements();) {
FlexoModelObject next = e.nextElement();
if (logger.isLoggable(Level.FINE)) {
logger.fine("Selected: " + next);
}
if (next instanceof PetriGraphNode ) {
PetriGraphNode node = (PetriGraphNode) next;
process = node.getProcess();
selectedNodes.add(node);
} else if (next instanceof WKFArtefact) {
WKFArtefact annotation = (WKFArtefact) next;
process = annotation.getProcess();
selectedAnnotations.add(annotation);
}
}
currentCopyLevel = getSelectionManager().getSelectionLevel();
if (selectedNodes.size() + selectedAnnotations.size() > 0) { // We make
// a
// NodeCompound
_clipboardData = new NodeCompound(process, selectedNodes, selectedAnnotations);
}
}
else if (currentlySelectedObjects.firstElement() instanceof Role) {
FlexoProject project = ((Role)currentlySelectedObjects.firstElement()).getProject();
Vector<Role> rolesToBeCopied = new Vector<Role>();
for (FlexoModelObject o : currentlySelectedObjects) {
if (o instanceof Role) {
rolesToBeCopied.add((Role)o);
}
}
_clipboardData = new RoleCompound(project.getFlexoWorkflow(),rolesToBeCopied);
currentCopyLevel = FlexoLevel.WORKFLOW;
}
}
if (_clipboardData != null) {
// Call XMLRepresentation can be tricky because it trigger XML encoding and later some issues with FlexoID's
// logger.fine("Storing in clipboard: " + _clipboardData.getXMLRepresentation());
}
else {
logger.warning("null value in clipboard ! ");
}
return true;
}
| protected boolean performCopyOfSelection(Vector<FlexoModelObject> currentlySelectedObjects)
{
logger.info("performCopyOfSelection() for "+currentlySelectedObjects);
// TODO reimplement all of this
resetClipboard();
if (currentlySelectedObjects.size() > 0) {
if (currentlySelectedObjects.firstElement() instanceof PetriGraphNode
|| currentlySelectedObjects.firstElement() instanceof WKFArtefact
|| currentlySelectedObjects.firstElement() instanceof WKFEdge<?,?>) {
Vector<PetriGraphNode> selectedNodes = new Vector<PetriGraphNode>();
Vector<WKFArtefact> selectedAnnotations = new Vector<WKFArtefact>();
FlexoProcess process = null;
for (Enumeration<FlexoModelObject> e = currentlySelectedObjects.elements(); e.hasMoreElements();) {
FlexoModelObject next = e.nextElement();
if (logger.isLoggable(Level.FINE)) {
logger.fine("Selected: " + next);
}
if (next instanceof PetriGraphNode ) {
PetriGraphNode node = (PetriGraphNode) next;
process = node.getProcess();
selectedNodes.add(node);
} else if (next instanceof WKFArtefact) {
WKFArtefact annotation = (WKFArtefact) next;
process = annotation.getProcess();
selectedAnnotations.add(annotation);
}
}
currentCopyLevel = getSelectionManager().getSelectionLevel();
if (selectedNodes.size() + selectedAnnotations.size() > 0) { // We make
// a
// NodeCompound
_clipboardData = new NodeCompound(process, selectedNodes, selectedAnnotations);
}
}
else if (currentlySelectedObjects.firstElement() instanceof Role) {
FlexoProject project = ((Role)currentlySelectedObjects.firstElement()).getProject();
Vector<Role> rolesToBeCopied = new Vector<Role>();
for (FlexoModelObject o : currentlySelectedObjects) {
if (o instanceof Role) {
rolesToBeCopied.add((Role)o);
}
}
_clipboardData = new RoleCompound(project.getFlexoWorkflow(),rolesToBeCopied);
currentCopyLevel = FlexoLevel.WORKFLOW;
}
}
if (_clipboardData != null) {
// Call XMLRepresentation can be tricky because it trigger XML encoding and later some issues with FlexoID's
// logger.fine("Storing in clipboard: " + _clipboardData.getXMLRepresentation());
}
else {
logger.warning("null value in clipboard ! ");
}
return true;
}
|
diff --git a/processor/src/main/java/org/apache/camel/processor/mashup/model/Mashup.java b/processor/src/main/java/org/apache/camel/processor/mashup/model/Mashup.java
index 23d2df0..2be50ba 100644
--- a/processor/src/main/java/org/apache/camel/processor/mashup/model/Mashup.java
+++ b/processor/src/main/java/org/apache/camel/processor/mashup/model/Mashup.java
@@ -1,100 +1,101 @@
package org.apache.camel.processor.mashup.model;
import org.apache.commons.digester3.Digester;
import java.io.InputStream;
import java.util.LinkedList;
import java.util.List;
public class Mashup {
private String id;
private CookieStore cookieStore;
private Proxy proxy;
private List<Page> pages = new LinkedList<Page>();
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public CookieStore getCookieStore() {
return cookieStore;
}
public void setCookieStore(CookieStore cookieStore) {
this.cookieStore = cookieStore;
}
public Proxy getProxy() {
return proxy;
}
public void setProxy(Proxy proxy) {
this.proxy = proxy;
}
public List<Page> getPages() {
return pages;
}
public void setPages(List<Page> pages) {
this.pages = pages;
}
public void addPage(Page page) {
this.pages.add(page);
}
public void digeste(InputStream inputStream) throws Exception {
Digester digester = new Digester();
digester.push(this);
digester.addSetProperties("mashup");
digester.addObjectCreate("mashup/cookiestore", CookieStore.class);
digester.addSetProperties("mashup/cookiestore");
digester.addSetNext("mashup/cookiestore", "setCookieStore");
digester.addObjectCreate("mashup/proxy", Proxy.class);
digester.addSetProperties("mashup/proxy");
digester.addSetNext("mashup/proxy", "setProxy");
digester.addObjectCreate("mashup/page", Page.class);
digester.addSetProperties("mashup/page");
digester.addCallMethod("mashup/page/url", "setUrl", 0);
digester.addSetNext("mashup/page", "addPage");
digester.addObjectCreate("mashup/page/param", Param.class);
digester.addSetProperties("mashup/page/param");
digester.addSetNext("mashup/page/param", "addParam");
digester.addObjectCreate("mashup/page/extractor", Extractor.class);
digester.addSetProperties("mashup/page/extractor");
digester.addSetNext("mashup/page/extractor", "addExtractor");
digester.addObjectCreate("mashup/page/extractor/property", Property.class);
digester.addSetProperties("mashup/page/extractor/property");
digester.addCallMethod("mashup/page/extractor/property", "setValue", 0);
digester.addSetNext("mashup/page/extractor/property", "addProperty");
digester.addObjectCreate("mashup/page/errorhandler", ErrorHandler.class);
digester.addSetProperties("mashup/page/errorhandler");
digester.addSetNext("mashup/page/errorhandler", "setErrorHandler");
digester.addObjectCreate("mashup/page/errorhandler/extractor", Extractor.class);
digester.addSetProperties("mashup/page/errorhandler/extractor");
digester.addSetNext("mashup/page/errorhandler/extractor", "addExtractor");
digester.addObjectCreate("mashup/page/errorhandler/extractor/property", Property.class);
digester.addSetProperties("mashup/page/errorhandler/extractor/property");
+ digester.addCallMethod("mashup/page/extractor/property", "setValue", 0);
digester.addSetNext("mashup/page/errorhandler/extractor/property", "addProperty");
digester.parse(inputStream);
}
}
| true | true | public void digeste(InputStream inputStream) throws Exception {
Digester digester = new Digester();
digester.push(this);
digester.addSetProperties("mashup");
digester.addObjectCreate("mashup/cookiestore", CookieStore.class);
digester.addSetProperties("mashup/cookiestore");
digester.addSetNext("mashup/cookiestore", "setCookieStore");
digester.addObjectCreate("mashup/proxy", Proxy.class);
digester.addSetProperties("mashup/proxy");
digester.addSetNext("mashup/proxy", "setProxy");
digester.addObjectCreate("mashup/page", Page.class);
digester.addSetProperties("mashup/page");
digester.addCallMethod("mashup/page/url", "setUrl", 0);
digester.addSetNext("mashup/page", "addPage");
digester.addObjectCreate("mashup/page/param", Param.class);
digester.addSetProperties("mashup/page/param");
digester.addSetNext("mashup/page/param", "addParam");
digester.addObjectCreate("mashup/page/extractor", Extractor.class);
digester.addSetProperties("mashup/page/extractor");
digester.addSetNext("mashup/page/extractor", "addExtractor");
digester.addObjectCreate("mashup/page/extractor/property", Property.class);
digester.addSetProperties("mashup/page/extractor/property");
digester.addCallMethod("mashup/page/extractor/property", "setValue", 0);
digester.addSetNext("mashup/page/extractor/property", "addProperty");
digester.addObjectCreate("mashup/page/errorhandler", ErrorHandler.class);
digester.addSetProperties("mashup/page/errorhandler");
digester.addSetNext("mashup/page/errorhandler", "setErrorHandler");
digester.addObjectCreate("mashup/page/errorhandler/extractor", Extractor.class);
digester.addSetProperties("mashup/page/errorhandler/extractor");
digester.addSetNext("mashup/page/errorhandler/extractor", "addExtractor");
digester.addObjectCreate("mashup/page/errorhandler/extractor/property", Property.class);
digester.addSetProperties("mashup/page/errorhandler/extractor/property");
digester.addSetNext("mashup/page/errorhandler/extractor/property", "addProperty");
digester.parse(inputStream);
}
| public void digeste(InputStream inputStream) throws Exception {
Digester digester = new Digester();
digester.push(this);
digester.addSetProperties("mashup");
digester.addObjectCreate("mashup/cookiestore", CookieStore.class);
digester.addSetProperties("mashup/cookiestore");
digester.addSetNext("mashup/cookiestore", "setCookieStore");
digester.addObjectCreate("mashup/proxy", Proxy.class);
digester.addSetProperties("mashup/proxy");
digester.addSetNext("mashup/proxy", "setProxy");
digester.addObjectCreate("mashup/page", Page.class);
digester.addSetProperties("mashup/page");
digester.addCallMethod("mashup/page/url", "setUrl", 0);
digester.addSetNext("mashup/page", "addPage");
digester.addObjectCreate("mashup/page/param", Param.class);
digester.addSetProperties("mashup/page/param");
digester.addSetNext("mashup/page/param", "addParam");
digester.addObjectCreate("mashup/page/extractor", Extractor.class);
digester.addSetProperties("mashup/page/extractor");
digester.addSetNext("mashup/page/extractor", "addExtractor");
digester.addObjectCreate("mashup/page/extractor/property", Property.class);
digester.addSetProperties("mashup/page/extractor/property");
digester.addCallMethod("mashup/page/extractor/property", "setValue", 0);
digester.addSetNext("mashup/page/extractor/property", "addProperty");
digester.addObjectCreate("mashup/page/errorhandler", ErrorHandler.class);
digester.addSetProperties("mashup/page/errorhandler");
digester.addSetNext("mashup/page/errorhandler", "setErrorHandler");
digester.addObjectCreate("mashup/page/errorhandler/extractor", Extractor.class);
digester.addSetProperties("mashup/page/errorhandler/extractor");
digester.addSetNext("mashup/page/errorhandler/extractor", "addExtractor");
digester.addObjectCreate("mashup/page/errorhandler/extractor/property", Property.class);
digester.addSetProperties("mashup/page/errorhandler/extractor/property");
digester.addCallMethod("mashup/page/extractor/property", "setValue", 0);
digester.addSetNext("mashup/page/errorhandler/extractor/property", "addProperty");
digester.parse(inputStream);
}
|
diff --git a/src/java/org/apache/cassandra/service/GCInspector.java b/src/java/org/apache/cassandra/service/GCInspector.java
index dedb3b51..e565e33b 100644
--- a/src/java/org/apache/cassandra/service/GCInspector.java
+++ b/src/java/org/apache/cassandra/service/GCInspector.java
@@ -1,145 +1,147 @@
package org.apache.cassandra.service;
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
import java.lang.management.GarbageCollectorMXBean;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.MemoryUsage;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.utils.StatusLogger;
public class GCInspector
{
private static final Logger logger = LoggerFactory.getLogger(GCInspector.class);
final static long INTERVAL_IN_MS = 1000;
final static long MIN_DURATION = 200;
final static long MIN_DURATION_TPSTATS = 1000;
public static final GCInspector instance = new GCInspector();
private HashMap<String, Long> gctimes = new HashMap<String, Long>();
private HashMap<String, Long> gccounts = new HashMap<String, Long>();
List<GarbageCollectorMXBean> beans = new ArrayList<GarbageCollectorMXBean>();
MemoryMXBean membean = ManagementFactory.getMemoryMXBean();
private volatile boolean cacheSizesReduced;
public GCInspector()
{
MBeanServer server = ManagementFactory.getPlatformMBeanServer();
try
{
ObjectName gcName = new ObjectName(ManagementFactory.GARBAGE_COLLECTOR_MXBEAN_DOMAIN_TYPE + ",*");
for (ObjectName name : server.queryNames(gcName, null))
{
GarbageCollectorMXBean gc = ManagementFactory.newPlatformMXBeanProxy(server, name.getCanonicalName(), GarbageCollectorMXBean.class);
beans.add(gc);
}
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
public void start()
{
// don't bother starting a thread that will do nothing.
if (beans.size() == 0)
return;
Runnable t = new Runnable()
{
public void run()
{
logGCResults();
}
};
StorageService.scheduledTasks.scheduleWithFixedDelay(t, INTERVAL_IN_MS, INTERVAL_IN_MS, TimeUnit.MILLISECONDS);
}
private void logGCResults()
{
for (GarbageCollectorMXBean gc : beans)
{
Long previousTotal = gctimes.get(gc.getName());
Long total = gc.getCollectionTime();
if (previousTotal == null)
previousTotal = 0L;
if (previousTotal.equals(total))
continue;
gctimes.put(gc.getName(), total);
Long duration = total - previousTotal;
assert duration > 0;
Long previousCount = gccounts.get(gc.getName());
Long count = gc.getCollectionCount();
+ if (count == 0)
+ continue;
if (previousCount == null)
previousCount = 0L;
gccounts.put(gc.getName(), count);
MemoryUsage mu = membean.getHeapMemoryUsage();
long memoryUsed = mu.getUsed();
long memoryMax = mu.getMax();
String st = String.format("GC for %s: %s ms for %s collections, %s used; max is %s",
gc.getName(), duration, count - previousCount, memoryUsed, memoryMax);
long durationPerCollection = duration / (count - previousCount);
if (durationPerCollection > MIN_DURATION)
logger.info(st);
else if (logger.isDebugEnabled())
logger.debug(st);
if (durationPerCollection > MIN_DURATION_TPSTATS)
StatusLogger.log();
// if we just finished a full collection and we're still using a lot of memory, try to reduce the pressure
if (gc.getName().equals("ConcurrentMarkSweep"))
{
double usage = (double) memoryUsed / memoryMax;
if (memoryUsed > DatabaseDescriptor.getReduceCacheSizesAt() * memoryMax && !cacheSizesReduced)
{
cacheSizesReduced = true;
logger.warn("Heap is " + usage + " full. You may need to reduce memtable and/or cache sizes. Cassandra is now reducing cache sizes to free up memory. Adjust reduce_cache_sizes_at threshold in cassandra.yaml if you don't want Cassandra to do this automatically");
StorageService.instance.reduceCacheSizes();
}
if (memoryUsed > DatabaseDescriptor.getFlushLargestMemtablesAt() * memoryMax)
{
logger.warn("Heap is " + usage + " full. You may need to reduce memtable and/or cache sizes. Cassandra will now flush up to the two largest memtables to free up memory. Adjust flush_largest_memtables_at threshold in cassandra.yaml if you don't want Cassandra to do this automatically");
StorageService.instance.flushLargestMemtables();
}
}
}
}
}
| true | true | private void logGCResults()
{
for (GarbageCollectorMXBean gc : beans)
{
Long previousTotal = gctimes.get(gc.getName());
Long total = gc.getCollectionTime();
if (previousTotal == null)
previousTotal = 0L;
if (previousTotal.equals(total))
continue;
gctimes.put(gc.getName(), total);
Long duration = total - previousTotal;
assert duration > 0;
Long previousCount = gccounts.get(gc.getName());
Long count = gc.getCollectionCount();
if (previousCount == null)
previousCount = 0L;
gccounts.put(gc.getName(), count);
MemoryUsage mu = membean.getHeapMemoryUsage();
long memoryUsed = mu.getUsed();
long memoryMax = mu.getMax();
String st = String.format("GC for %s: %s ms for %s collections, %s used; max is %s",
gc.getName(), duration, count - previousCount, memoryUsed, memoryMax);
long durationPerCollection = duration / (count - previousCount);
if (durationPerCollection > MIN_DURATION)
logger.info(st);
else if (logger.isDebugEnabled())
logger.debug(st);
if (durationPerCollection > MIN_DURATION_TPSTATS)
StatusLogger.log();
// if we just finished a full collection and we're still using a lot of memory, try to reduce the pressure
if (gc.getName().equals("ConcurrentMarkSweep"))
{
double usage = (double) memoryUsed / memoryMax;
if (memoryUsed > DatabaseDescriptor.getReduceCacheSizesAt() * memoryMax && !cacheSizesReduced)
{
cacheSizesReduced = true;
logger.warn("Heap is " + usage + " full. You may need to reduce memtable and/or cache sizes. Cassandra is now reducing cache sizes to free up memory. Adjust reduce_cache_sizes_at threshold in cassandra.yaml if you don't want Cassandra to do this automatically");
StorageService.instance.reduceCacheSizes();
}
if (memoryUsed > DatabaseDescriptor.getFlushLargestMemtablesAt() * memoryMax)
{
logger.warn("Heap is " + usage + " full. You may need to reduce memtable and/or cache sizes. Cassandra will now flush up to the two largest memtables to free up memory. Adjust flush_largest_memtables_at threshold in cassandra.yaml if you don't want Cassandra to do this automatically");
StorageService.instance.flushLargestMemtables();
}
}
}
}
| private void logGCResults()
{
for (GarbageCollectorMXBean gc : beans)
{
Long previousTotal = gctimes.get(gc.getName());
Long total = gc.getCollectionTime();
if (previousTotal == null)
previousTotal = 0L;
if (previousTotal.equals(total))
continue;
gctimes.put(gc.getName(), total);
Long duration = total - previousTotal;
assert duration > 0;
Long previousCount = gccounts.get(gc.getName());
Long count = gc.getCollectionCount();
if (count == 0)
continue;
if (previousCount == null)
previousCount = 0L;
gccounts.put(gc.getName(), count);
MemoryUsage mu = membean.getHeapMemoryUsage();
long memoryUsed = mu.getUsed();
long memoryMax = mu.getMax();
String st = String.format("GC for %s: %s ms for %s collections, %s used; max is %s",
gc.getName(), duration, count - previousCount, memoryUsed, memoryMax);
long durationPerCollection = duration / (count - previousCount);
if (durationPerCollection > MIN_DURATION)
logger.info(st);
else if (logger.isDebugEnabled())
logger.debug(st);
if (durationPerCollection > MIN_DURATION_TPSTATS)
StatusLogger.log();
// if we just finished a full collection and we're still using a lot of memory, try to reduce the pressure
if (gc.getName().equals("ConcurrentMarkSweep"))
{
double usage = (double) memoryUsed / memoryMax;
if (memoryUsed > DatabaseDescriptor.getReduceCacheSizesAt() * memoryMax && !cacheSizesReduced)
{
cacheSizesReduced = true;
logger.warn("Heap is " + usage + " full. You may need to reduce memtable and/or cache sizes. Cassandra is now reducing cache sizes to free up memory. Adjust reduce_cache_sizes_at threshold in cassandra.yaml if you don't want Cassandra to do this automatically");
StorageService.instance.reduceCacheSizes();
}
if (memoryUsed > DatabaseDescriptor.getFlushLargestMemtablesAt() * memoryMax)
{
logger.warn("Heap is " + usage + " full. You may need to reduce memtable and/or cache sizes. Cassandra will now flush up to the two largest memtables to free up memory. Adjust flush_largest_memtables_at threshold in cassandra.yaml if you don't want Cassandra to do this automatically");
StorageService.instance.flushLargestMemtables();
}
}
}
}
|
diff --git a/QCMediaPlayer/com/qualcomm/qcmedia/QCTimedText.java b/QCMediaPlayer/com/qualcomm/qcmedia/QCTimedText.java
index a9ee42f..1acd35c 100644
--- a/QCMediaPlayer/com/qualcomm/qcmedia/QCTimedText.java
+++ b/QCMediaPlayer/com/qualcomm/qcmedia/QCTimedText.java
@@ -1,769 +1,768 @@
/*
* Copyright (c) 2012-2013, The Linux Foundation. All rights reserved.
*
* Not a Contribution, Apache license notifications and license are retained
* for attribution purposes only.
*/
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* File: QCTimedText.java
* Description: Snapdragon SDK for Android support class.
* Provides access to QC-provided TimedText APIs and interfaces
*
*/
package com.qualcomm.qcmedia;
import android.media.MediaPlayer;
import android.util.Log;
import android.os.Parcel;
import android.util.Log;
import java.util.HashMap;
import java.util.Set;
import java.util.List;
import java.util.ArrayList;
/**
* Class to hold the timed text's metadata.
* It holds local settings(per sample) as well as global settings.
*
* {@hide}
*/
public class QCTimedText
{
private static final int FIRST_PUBLIC_KEY = 1;
// These keys must be in sync with the keys in TextDescription.h
public static final int KEY_DISPLAY_FLAGS = 1; // int
public static final int KEY_STYLE_FLAGS = 2; // int
public static final int KEY_BACKGROUND_COLOR_RGBA = 3; // int
public static final int KEY_HIGHLIGHT_COLOR_RGBA = 4; // int
public static final int KEY_SCROLL_DELAY = 5; // int
public static final int KEY_WRAP_TEXT = 6; // int
public static final int KEY_START_TIME = 7; // int
public static final int KEY_STRUCT_BLINKING_TEXT_LIST = 8; // List<CharPos>
public static final int KEY_STRUCT_FONT_LIST = 9; // List<Font>
public static final int KEY_STRUCT_HIGHLIGHT_LIST = 10; // List<CharPos>
public static final int KEY_STRUCT_HYPER_TEXT_LIST = 11; // List<HyperText>
public static final int KEY_STRUCT_KARAOKE_LIST = 12; // List<Karaoke>
public static final int KEY_STRUCT_STYLE_LIST = 13; // List<Style>
public static final int KEY_STRUCT_TEXT_POS = 14; // TextPos
public static final int KEY_STRUCT_JUSTIFICATION = 15; // Justification
public static final int KEY_STRUCT_TEXT = 16; // Text
public static final int KEY_HEIGHT = 17;
public static final int KEY_WIDTH = 18;
public static final int KEY_DURATION = 19;
public static final int KEY_START_OFFSET = 20;
public static final int KEY_SUBS_ATOM = 21;
private static final int LAST_PUBLIC_KEY = 21;
private static final int FIRST_PRIVATE_KEY = 101;
// The following keys are used between QCTimedText.java and
// TextDescription.cpp in order to parce the Parcel.
private static final int KEY_GLOBAL_SETTING = 101;
private static final int KEY_LOCAL_SETTING = 102;
private static final int KEY_START_CHAR = 103;
private static final int KEY_END_CHAR = 104;
private static final int KEY_FONT_ID = 105;
private static final int KEY_FONT_SIZE = 106;
private static final int KEY_TEXT_COLOR_RGBA = 107;
private static final int KEY_TEXT_EOS = 108;
private static final int LAST_PRIVATE_KEY = 108;
private static final String TAG = "QCTimedText";
private final HashMap<Integer, Object> mKeyObjectMap =
new HashMap<Integer, Object>();
private int mDisplayFlags = -1;
private int mBackgroundColorRGBA = -1;
private int mHighlightColorRGBA = -1;
private int mScrollDelay = -1;
private int mWrapText = -1;
private List<CharPos> mBlinkingPosList = null;
private List<CharPos> mHighlightPosList = null;
private List<Karaoke> mKaraokeList = null;
private List<Font> mFontList = null;
private List<Style> mStyleList = null;
private List<HyperText> mHyperTextList = null;
private TextPos mTextPos;
private Justification mJustification;
private Text mTextStruct;
private SubsAtom mSubsAtomStruct;
/**
* Helper class to hold the text length and text content of
* one text sample. The member variables in this class are
* read-only.
*/
public class Text {
public static final int TIMED_TEXT_FLAG_FRAME = 0; // int
public static final int TIMED_TEXT_FLAG_CODEC_CONFIG = 1; // int
public static final int TIMED_TEXT_FLAG_EOS = 2; // int
/**
* The byte-count of this text sample
*/
public int textLen;
/**
* The flags associated with frame
*/
public int flags;
/**
* The text sample
*/
public byte[] text;
public Text() { }
}
/**
* Helper class to hold the start char offset and end char offset
* for Blinking Text or Highlight Text. endChar is the end offset
* of the text (startChar + number of characters to be highlighted
* or blinked). The member variables in this class are read-only.
*/
public class CharPos {
/**
* The offset of the start character
*/
public int startChar = -1;
/**
* The offset of the end character
*/
public int endChar = -1;
public CharPos() { }
}
/**
* Helper class to hold the box position to display the text sample.
* The member variables in this class are read-only.
*/
public class TextPos {
/**
* The top position of the text
*/
public int top = -1;
/**
* The left position of the text
*/
public int left = -1;
/**
* The bottom position of the text
*/
public int bottom = -1;
/**
* The right position of the text
*/
public int right = -1;
public TextPos() { }
}
/**
* Helper class to hold the justification for text display in the text box.
* The member variables in this class are read-only.
*/
public class Justification {
/**
* horizontalJustification 0: left, 1: centered, -1: right
*/
public int horizontalJustification = -1;
/**
* verticalJustification 0: top, 1: centered, -1: bottom
*/
public int verticalJustification = -1;
public Justification() { }
}
/**
* Helper class to hold the style information to display the text.
* The member variables in this class are read-only.
*/
public class Style {
/**
* The offset of the start character which applys this style
*/
public int startChar = -1;
/**
* The offset of the end character which applys this style
*/
public int endChar = -1;
/**
* ID of the font. This ID will be used to choose the font
* to be used from the font list.
*/
public int fontID = -1;
/**
* True if the characters should be bold
*/
public boolean isBold = false;
/**
* True if the characters should be italic
*/
public boolean isItalic = false;
/**
* True if the characters should be underlined
*/
public boolean isUnderlined = false;
/**
* The size of the font
*/
public int fontSize = -1;
/**
* To specify the RGBA color: 8 bits each of red, green, blue,
* and an alpha(transparency) value
*/
public int colorRGBA = -1;
public Style() { }
}
/**
* Helper class to hold the font ID and name.
* The member variables in this class are read-only.
*/
public class Font {
/**
* The font ID
*/
public int ID = -1;
/**
* The font name
*/
public String name;
public Font() { }
}
/**
* Helper class to hold the karaoke information.
* The member variables in this class are read-only.
*/
public class Karaoke {
/**
* The start time (in milliseconds) to highlight the characters
* specified by startChar and endChar.
*/
public int startTimeMs = -1;
/**
* The end time (in milliseconds) to highlight the characters
* specified by startChar and endChar.
*/
public int endTimeMs = -1;
/**
* The offset of the start character to be highlighted
*/
public int startChar = -1;
/**
* The offset of the end character to be highlighted
*/
public int endChar = -1;
public Karaoke() { }
}
/**
* Helper class to hold the hyper text information.
* The member variables in this class are read-only.
*/
public class HyperText {
/**
* The offset of the start character
*/
public int startChar = -1;
/**
* The offset of the end character
*/
public int endChar = -1;
/**
* The linked-to URL
*/
public String URL;
/**
* The "alt" string for user display
*/
public String altString;
public HyperText() { }
}
/* Subs Atom*/
public class SubsAtom {
/**
* The byte-count of this subs
*/
public int subsAtomLen;
/**
* The subs data
*/
public byte[] subsAtomData;
public SubsAtom () { }
}
/**
* @param obj the byte array which contains the timed text.
* @throws IllegalArgumentExcept if parseParcel() fails.
* {@hide}
*/
public QCTimedText(Parcel mParcel) {
if (!parseParcel(mParcel)) {
mKeyObjectMap.clear();
throw new IllegalArgumentException("parseParcel() fails");
}
}
/**
* Go over all the records, collecting metadata keys and fields in the
* Parcel. These are stored in mKeyObjectMap for application to retrieve.
* @return false if an error occurred during parsing. Otherwise, true.
*/
private boolean parseParcel(Parcel mParcel) {
mParcel.setDataPosition(0);
if (mParcel.dataAvail() == 0) {
Log.e(TAG, "mParcel.dataAvail()");
return false;
}
int type = mParcel.readInt();
if (type == KEY_LOCAL_SETTING) {
type = mParcel.readInt();
if (type == KEY_TEXT_EOS)
{
mKeyObjectMap.put(KEY_START_TIME, 0);
mTextStruct = new Text();
mTextStruct.textLen = 0; //Zero length buffer in case of EOS
mKeyObjectMap.put(KEY_STRUCT_TEXT, mTextStruct);
mKeyObjectMap.put(KEY_HEIGHT, 0);
mKeyObjectMap.put(KEY_WIDTH, 0);
mKeyObjectMap.put(KEY_DURATION, 0);
mKeyObjectMap.put(KEY_START_OFFSET, 0);
mTextStruct.flags = Text.TIMED_TEXT_FLAG_EOS;
return true;
}
if (type != KEY_START_TIME) {
Log.e(TAG, "Invalid KEY_START_TIME key");
return false;
}
int mStartTimeMs = mParcel.readInt();
mKeyObjectMap.put(type, mStartTimeMs);
type = mParcel.readInt();
if (type != KEY_STRUCT_TEXT) {
Log.e(TAG, "Invalid KEY_STRUCT_TEXT key");
return false;
}
mTextStruct = new Text();
mTextStruct.flags = mParcel.readInt();
mTextStruct.textLen = mParcel.readInt();
mTextStruct.text = mParcel.createByteArray();
mKeyObjectMap.put(type, mTextStruct);
type = mParcel.readInt();
if (type != KEY_HEIGHT) {
Log.e(TAG, "Invalid KEY_HEIGHT key");
return false;
}
int mHeight = mParcel.readInt();
Log.e(TAG, "mHeight: " + mHeight);
mKeyObjectMap.put(type, mHeight);
type = mParcel.readInt();
if (type != KEY_WIDTH) {
Log.e(TAG, "Invalid KEY_WIDTH key");
return false;
}
int mWidth = mParcel.readInt();
Log.e(TAG, "mWidth: " + mWidth);
mKeyObjectMap.put(type, mWidth);
type = mParcel.readInt();
if (type != KEY_DURATION) {
Log.e(TAG, "Invalid KEY_DURATION key");
return false;
}
int mDuration = mParcel.readInt();
Log.e(TAG, "mDuration: " + mDuration);
mKeyObjectMap.put(type, mDuration);
type = mParcel.readInt();
if (type != KEY_START_OFFSET) {
Log.e(TAG, "Invalid KEY_START_OFFSET key");
return false;
}
int mStartOffset = mParcel.readInt();
Log.e(TAG, "mStartOffset: " + mStartOffset);
mKeyObjectMap.put(type, mStartOffset);
//Parse SubsAtom
type = mParcel.readInt();
if (type == KEY_SUBS_ATOM) {
mSubsAtomStruct = new SubsAtom();
mSubsAtomStruct.subsAtomLen = mParcel.readInt();
mSubsAtomStruct.subsAtomData = mParcel.createByteArray();
mKeyObjectMap.put(type, mSubsAtomStruct);
return true;
}
} else if (type != KEY_GLOBAL_SETTING) {
Log.w(TAG, "Invalid timed text key found: " + type);
return false;
}
while (mParcel.dataAvail() > 0) {
int key = mParcel.readInt();
if (!isValidKey(key)) {
Log.w(TAG, "Invalid timed text key found: " + key);
return false;
}
Object object = null;
switch (key) {
case KEY_STRUCT_STYLE_LIST: {
readStyle(mParcel);
object = mStyleList;
break;
}
case KEY_STRUCT_FONT_LIST: {
readFont(mParcel);
object = mFontList;
break;
}
case KEY_STRUCT_HIGHLIGHT_LIST: {
readHighlight(mParcel);
object = mHighlightPosList;
break;
}
case KEY_STRUCT_KARAOKE_LIST: {
readKaraoke(mParcel);
object = mKaraokeList;
break;
}
case KEY_STRUCT_HYPER_TEXT_LIST: {
readHyperText(mParcel);
object = mHyperTextList;
break;
}
case KEY_STRUCT_BLINKING_TEXT_LIST: {
readBlinkingText(mParcel);
object = mBlinkingPosList;
break;
}
case KEY_WRAP_TEXT: {
mWrapText = mParcel.readInt();
object = mWrapText;
break;
}
case KEY_HIGHLIGHT_COLOR_RGBA: {
mHighlightColorRGBA = mParcel.readInt();
object = mHighlightColorRGBA;
break;
}
case KEY_DISPLAY_FLAGS: {
mDisplayFlags = mParcel.readInt();
object = mDisplayFlags;
break;
}
case KEY_STRUCT_JUSTIFICATION: {
mJustification = new Justification();
mJustification.horizontalJustification = mParcel.readInt();
mJustification.verticalJustification = mParcel.readInt();
object = mJustification;
break;
}
case KEY_BACKGROUND_COLOR_RGBA: {
mBackgroundColorRGBA = mParcel.readInt();
object = mBackgroundColorRGBA;
break;
}
case KEY_STRUCT_TEXT_POS: {
mTextPos = new TextPos();
mTextPos.top = mParcel.readInt();
mTextPos.left = mParcel.readInt();
mTextPos.bottom = mParcel.readInt();
mTextPos.right = mParcel.readInt();
object = mTextPos;
break;
}
case KEY_SCROLL_DELAY: {
mScrollDelay = mParcel.readInt();
object = mScrollDelay;
break;
}
default: {
break;
}
}
if (object != null) {
if (mKeyObjectMap.containsKey(key)) {
mKeyObjectMap.remove(key);
}
mKeyObjectMap.put(key, object);
}
}
- mParcel.recycle();
return true;
}
/**
* To parse and store the Style list.
*/
private void readStyle(Parcel mParcel) {
Style style = new Style();
boolean endOfStyle = false;
while (!endOfStyle && (mParcel.dataAvail() > 0)) {
int key = mParcel.readInt();
switch (key) {
case KEY_START_CHAR: {
style.startChar = mParcel.readInt();
break;
}
case KEY_END_CHAR: {
style.endChar = mParcel.readInt();
break;
}
case KEY_FONT_ID: {
style.fontID = mParcel.readInt();
break;
}
case KEY_STYLE_FLAGS: {
int flags = mParcel.readInt();
// In the absence of any bits set in flags, the text
// is plain. Otherwise, 1: bold, 2: italic, 4: underline
style.isBold = ((flags % 2) == 1);
style.isItalic = ((flags % 4) >= 2);
style.isUnderlined = ((flags / 4) == 1);
break;
}
case KEY_FONT_SIZE: {
style.fontSize = mParcel.readInt();
break;
}
case KEY_TEXT_COLOR_RGBA: {
style.colorRGBA = mParcel.readInt();
break;
}
default: {
// End of the Style parsing. Reset the data position back
// to the position before the last mParcel.readInt() call.
mParcel.setDataPosition(mParcel.dataPosition() - 4);
endOfStyle = true;
break;
}
}
}
if (mStyleList == null) {
mStyleList = new ArrayList<Style>();
}
mStyleList.add(style);
}
/**
* To parse and store the Font list
*/
private void readFont(Parcel mParcel) {
int entryCount = mParcel.readInt();
for (int i = 0; i < entryCount; i++) {
Font font = new Font();
font.ID = mParcel.readInt();
int nameLen = mParcel.readInt();
byte[] text = mParcel.createByteArray();
font.name = new String(text, 0, nameLen);
if (mFontList == null) {
mFontList = new ArrayList<Font>();
}
mFontList.add(font);
}
}
/**
* To parse and store the Highlight list
*/
private void readHighlight(Parcel mParcel) {
CharPos pos = new CharPos();
pos.startChar = mParcel.readInt();
pos.endChar = mParcel.readInt();
if (mHighlightPosList == null) {
mHighlightPosList = new ArrayList<CharPos>();
}
mHighlightPosList.add(pos);
}
/**
* To parse and store the Karaoke list
*/
private void readKaraoke(Parcel mParcel) {
int entryCount = mParcel.readInt();
for (int i = 0; i < entryCount; i++) {
Karaoke kara = new Karaoke();
kara.startTimeMs = mParcel.readInt();
kara.endTimeMs = mParcel.readInt();
kara.startChar = mParcel.readInt();
kara.endChar = mParcel.readInt();
if (mKaraokeList == null) {
mKaraokeList = new ArrayList<Karaoke>();
}
mKaraokeList.add(kara);
}
}
/**
* To parse and store HyperText list
*/
private void readHyperText(Parcel mParcel) {
HyperText hyperText = new HyperText();
hyperText.startChar = mParcel.readInt();
hyperText.endChar = mParcel.readInt();
int len = mParcel.readInt();
byte[] url = mParcel.createByteArray();
hyperText.URL = new String(url, 0, len);
len = mParcel.readInt();
byte[] alt = mParcel.createByteArray();
hyperText.altString = new String(alt, 0, len);
if (mHyperTextList == null) {
mHyperTextList = new ArrayList<HyperText>();
}
mHyperTextList.add(hyperText);
}
/**
* To parse and store blinking text list
*/
private void readBlinkingText(Parcel mParcel) {
CharPos blinkingPos = new CharPos();
blinkingPos.startChar = mParcel.readInt();
blinkingPos.endChar = mParcel.readInt();
if (mBlinkingPosList == null) {
mBlinkingPosList = new ArrayList<CharPos>();
}
mBlinkingPosList.add(blinkingPos);
}
/**
* To check whether the given key is valid.
* @param key the key to be checked.
* @return true if the key is a valid one. Otherwise, false.
*/
public boolean isValidKey(final int key) {
if (!((key >= FIRST_PUBLIC_KEY) && (key <= LAST_PUBLIC_KEY))
&& !((key >= FIRST_PRIVATE_KEY) && (key <= LAST_PRIVATE_KEY))) {
return false;
}
return true;
}
/**
* To check whether the given key is contained in this QCTimedText object.
* @param key the key to be checked.
* @return true if the key is contained in this QCTimedText object.
* Otherwise, false.
*/
public boolean containsKey(final int key) {
if (isValidKey(key) && mKeyObjectMap.containsKey(key)) {
return true;
}
return false;
}
/**
* @return a set of the keys contained in this QCTimedText object.
*/
public Set keySet() {
return mKeyObjectMap.keySet();
}
/**
* To retrieve the object associated with the key. Caller must make sure
* the key is present using the containsKey method otherwise a
* RuntimeException will occur.
* @param key the key used to retrieve the object.
* @return an object. The object could be an instanceof Integer, List, or
* any of the helper classes such as TextPos, Justification, and Text.
*/
public Object getObject(final int key) {
if (containsKey(key)) {
return mKeyObjectMap.get(key);
}
return null;
/*
//!Warning : Not Sure if to throw an exception or return null , return null is good option
else {
throw new IllegalArgumentException("Invalid key: " + key);
}
*/
}
}
| true | true | private boolean parseParcel(Parcel mParcel) {
mParcel.setDataPosition(0);
if (mParcel.dataAvail() == 0) {
Log.e(TAG, "mParcel.dataAvail()");
return false;
}
int type = mParcel.readInt();
if (type == KEY_LOCAL_SETTING) {
type = mParcel.readInt();
if (type == KEY_TEXT_EOS)
{
mKeyObjectMap.put(KEY_START_TIME, 0);
mTextStruct = new Text();
mTextStruct.textLen = 0; //Zero length buffer in case of EOS
mKeyObjectMap.put(KEY_STRUCT_TEXT, mTextStruct);
mKeyObjectMap.put(KEY_HEIGHT, 0);
mKeyObjectMap.put(KEY_WIDTH, 0);
mKeyObjectMap.put(KEY_DURATION, 0);
mKeyObjectMap.put(KEY_START_OFFSET, 0);
mTextStruct.flags = Text.TIMED_TEXT_FLAG_EOS;
return true;
}
if (type != KEY_START_TIME) {
Log.e(TAG, "Invalid KEY_START_TIME key");
return false;
}
int mStartTimeMs = mParcel.readInt();
mKeyObjectMap.put(type, mStartTimeMs);
type = mParcel.readInt();
if (type != KEY_STRUCT_TEXT) {
Log.e(TAG, "Invalid KEY_STRUCT_TEXT key");
return false;
}
mTextStruct = new Text();
mTextStruct.flags = mParcel.readInt();
mTextStruct.textLen = mParcel.readInt();
mTextStruct.text = mParcel.createByteArray();
mKeyObjectMap.put(type, mTextStruct);
type = mParcel.readInt();
if (type != KEY_HEIGHT) {
Log.e(TAG, "Invalid KEY_HEIGHT key");
return false;
}
int mHeight = mParcel.readInt();
Log.e(TAG, "mHeight: " + mHeight);
mKeyObjectMap.put(type, mHeight);
type = mParcel.readInt();
if (type != KEY_WIDTH) {
Log.e(TAG, "Invalid KEY_WIDTH key");
return false;
}
int mWidth = mParcel.readInt();
Log.e(TAG, "mWidth: " + mWidth);
mKeyObjectMap.put(type, mWidth);
type = mParcel.readInt();
if (type != KEY_DURATION) {
Log.e(TAG, "Invalid KEY_DURATION key");
return false;
}
int mDuration = mParcel.readInt();
Log.e(TAG, "mDuration: " + mDuration);
mKeyObjectMap.put(type, mDuration);
type = mParcel.readInt();
if (type != KEY_START_OFFSET) {
Log.e(TAG, "Invalid KEY_START_OFFSET key");
return false;
}
int mStartOffset = mParcel.readInt();
Log.e(TAG, "mStartOffset: " + mStartOffset);
mKeyObjectMap.put(type, mStartOffset);
//Parse SubsAtom
type = mParcel.readInt();
if (type == KEY_SUBS_ATOM) {
mSubsAtomStruct = new SubsAtom();
mSubsAtomStruct.subsAtomLen = mParcel.readInt();
mSubsAtomStruct.subsAtomData = mParcel.createByteArray();
mKeyObjectMap.put(type, mSubsAtomStruct);
return true;
}
} else if (type != KEY_GLOBAL_SETTING) {
Log.w(TAG, "Invalid timed text key found: " + type);
return false;
}
while (mParcel.dataAvail() > 0) {
int key = mParcel.readInt();
if (!isValidKey(key)) {
Log.w(TAG, "Invalid timed text key found: " + key);
return false;
}
Object object = null;
switch (key) {
case KEY_STRUCT_STYLE_LIST: {
readStyle(mParcel);
object = mStyleList;
break;
}
case KEY_STRUCT_FONT_LIST: {
readFont(mParcel);
object = mFontList;
break;
}
case KEY_STRUCT_HIGHLIGHT_LIST: {
readHighlight(mParcel);
object = mHighlightPosList;
break;
}
case KEY_STRUCT_KARAOKE_LIST: {
readKaraoke(mParcel);
object = mKaraokeList;
break;
}
case KEY_STRUCT_HYPER_TEXT_LIST: {
readHyperText(mParcel);
object = mHyperTextList;
break;
}
case KEY_STRUCT_BLINKING_TEXT_LIST: {
readBlinkingText(mParcel);
object = mBlinkingPosList;
break;
}
case KEY_WRAP_TEXT: {
mWrapText = mParcel.readInt();
object = mWrapText;
break;
}
case KEY_HIGHLIGHT_COLOR_RGBA: {
mHighlightColorRGBA = mParcel.readInt();
object = mHighlightColorRGBA;
break;
}
case KEY_DISPLAY_FLAGS: {
mDisplayFlags = mParcel.readInt();
object = mDisplayFlags;
break;
}
case KEY_STRUCT_JUSTIFICATION: {
mJustification = new Justification();
mJustification.horizontalJustification = mParcel.readInt();
mJustification.verticalJustification = mParcel.readInt();
object = mJustification;
break;
}
case KEY_BACKGROUND_COLOR_RGBA: {
mBackgroundColorRGBA = mParcel.readInt();
object = mBackgroundColorRGBA;
break;
}
case KEY_STRUCT_TEXT_POS: {
mTextPos = new TextPos();
mTextPos.top = mParcel.readInt();
mTextPos.left = mParcel.readInt();
mTextPos.bottom = mParcel.readInt();
mTextPos.right = mParcel.readInt();
object = mTextPos;
break;
}
case KEY_SCROLL_DELAY: {
mScrollDelay = mParcel.readInt();
object = mScrollDelay;
break;
}
default: {
break;
}
}
if (object != null) {
if (mKeyObjectMap.containsKey(key)) {
mKeyObjectMap.remove(key);
}
mKeyObjectMap.put(key, object);
}
}
mParcel.recycle();
return true;
}
| private boolean parseParcel(Parcel mParcel) {
mParcel.setDataPosition(0);
if (mParcel.dataAvail() == 0) {
Log.e(TAG, "mParcel.dataAvail()");
return false;
}
int type = mParcel.readInt();
if (type == KEY_LOCAL_SETTING) {
type = mParcel.readInt();
if (type == KEY_TEXT_EOS)
{
mKeyObjectMap.put(KEY_START_TIME, 0);
mTextStruct = new Text();
mTextStruct.textLen = 0; //Zero length buffer in case of EOS
mKeyObjectMap.put(KEY_STRUCT_TEXT, mTextStruct);
mKeyObjectMap.put(KEY_HEIGHT, 0);
mKeyObjectMap.put(KEY_WIDTH, 0);
mKeyObjectMap.put(KEY_DURATION, 0);
mKeyObjectMap.put(KEY_START_OFFSET, 0);
mTextStruct.flags = Text.TIMED_TEXT_FLAG_EOS;
return true;
}
if (type != KEY_START_TIME) {
Log.e(TAG, "Invalid KEY_START_TIME key");
return false;
}
int mStartTimeMs = mParcel.readInt();
mKeyObjectMap.put(type, mStartTimeMs);
type = mParcel.readInt();
if (type != KEY_STRUCT_TEXT) {
Log.e(TAG, "Invalid KEY_STRUCT_TEXT key");
return false;
}
mTextStruct = new Text();
mTextStruct.flags = mParcel.readInt();
mTextStruct.textLen = mParcel.readInt();
mTextStruct.text = mParcel.createByteArray();
mKeyObjectMap.put(type, mTextStruct);
type = mParcel.readInt();
if (type != KEY_HEIGHT) {
Log.e(TAG, "Invalid KEY_HEIGHT key");
return false;
}
int mHeight = mParcel.readInt();
Log.e(TAG, "mHeight: " + mHeight);
mKeyObjectMap.put(type, mHeight);
type = mParcel.readInt();
if (type != KEY_WIDTH) {
Log.e(TAG, "Invalid KEY_WIDTH key");
return false;
}
int mWidth = mParcel.readInt();
Log.e(TAG, "mWidth: " + mWidth);
mKeyObjectMap.put(type, mWidth);
type = mParcel.readInt();
if (type != KEY_DURATION) {
Log.e(TAG, "Invalid KEY_DURATION key");
return false;
}
int mDuration = mParcel.readInt();
Log.e(TAG, "mDuration: " + mDuration);
mKeyObjectMap.put(type, mDuration);
type = mParcel.readInt();
if (type != KEY_START_OFFSET) {
Log.e(TAG, "Invalid KEY_START_OFFSET key");
return false;
}
int mStartOffset = mParcel.readInt();
Log.e(TAG, "mStartOffset: " + mStartOffset);
mKeyObjectMap.put(type, mStartOffset);
//Parse SubsAtom
type = mParcel.readInt();
if (type == KEY_SUBS_ATOM) {
mSubsAtomStruct = new SubsAtom();
mSubsAtomStruct.subsAtomLen = mParcel.readInt();
mSubsAtomStruct.subsAtomData = mParcel.createByteArray();
mKeyObjectMap.put(type, mSubsAtomStruct);
return true;
}
} else if (type != KEY_GLOBAL_SETTING) {
Log.w(TAG, "Invalid timed text key found: " + type);
return false;
}
while (mParcel.dataAvail() > 0) {
int key = mParcel.readInt();
if (!isValidKey(key)) {
Log.w(TAG, "Invalid timed text key found: " + key);
return false;
}
Object object = null;
switch (key) {
case KEY_STRUCT_STYLE_LIST: {
readStyle(mParcel);
object = mStyleList;
break;
}
case KEY_STRUCT_FONT_LIST: {
readFont(mParcel);
object = mFontList;
break;
}
case KEY_STRUCT_HIGHLIGHT_LIST: {
readHighlight(mParcel);
object = mHighlightPosList;
break;
}
case KEY_STRUCT_KARAOKE_LIST: {
readKaraoke(mParcel);
object = mKaraokeList;
break;
}
case KEY_STRUCT_HYPER_TEXT_LIST: {
readHyperText(mParcel);
object = mHyperTextList;
break;
}
case KEY_STRUCT_BLINKING_TEXT_LIST: {
readBlinkingText(mParcel);
object = mBlinkingPosList;
break;
}
case KEY_WRAP_TEXT: {
mWrapText = mParcel.readInt();
object = mWrapText;
break;
}
case KEY_HIGHLIGHT_COLOR_RGBA: {
mHighlightColorRGBA = mParcel.readInt();
object = mHighlightColorRGBA;
break;
}
case KEY_DISPLAY_FLAGS: {
mDisplayFlags = mParcel.readInt();
object = mDisplayFlags;
break;
}
case KEY_STRUCT_JUSTIFICATION: {
mJustification = new Justification();
mJustification.horizontalJustification = mParcel.readInt();
mJustification.verticalJustification = mParcel.readInt();
object = mJustification;
break;
}
case KEY_BACKGROUND_COLOR_RGBA: {
mBackgroundColorRGBA = mParcel.readInt();
object = mBackgroundColorRGBA;
break;
}
case KEY_STRUCT_TEXT_POS: {
mTextPos = new TextPos();
mTextPos.top = mParcel.readInt();
mTextPos.left = mParcel.readInt();
mTextPos.bottom = mParcel.readInt();
mTextPos.right = mParcel.readInt();
object = mTextPos;
break;
}
case KEY_SCROLL_DELAY: {
mScrollDelay = mParcel.readInt();
object = mScrollDelay;
break;
}
default: {
break;
}
}
if (object != null) {
if (mKeyObjectMap.containsKey(key)) {
mKeyObjectMap.remove(key);
}
mKeyObjectMap.put(key, object);
}
}
return true;
}
|
diff --git a/PC/src/main/java/edu/thu/cslab/footwith/form/InsertPlanForm.java b/PC/src/main/java/edu/thu/cslab/footwith/form/InsertPlanForm.java
index 5a885ef..ff49fe8 100644
--- a/PC/src/main/java/edu/thu/cslab/footwith/form/InsertPlanForm.java
+++ b/PC/src/main/java/edu/thu/cslab/footwith/form/InsertPlanForm.java
@@ -1,183 +1,183 @@
package edu.thu.cslab.footwith.form;
import edu.thu.cslab.footwith.server.Mediator;
import edu.thu.cslab.footwith.server.TextFormatException;
import org.json.JSONException;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Vector;
import java.util.logging.SimpleFormatter;
/**
* Created with IntelliJ IDEA.
* User: wangjiayu
* Date: 13-3-16
* Time: 下午4:03
* To change this template use File | Settings | File Templates.
*/
public class InsertPlanForm extends JFrame {
private JTextField siteName = new JTextField();
private JTextField startTime = new JTextField();
private JTextField endTime = new JTextField();
private JTextField organizer = new JTextField();
private JTextField numbers = new JTextField();
public InsertPlanForm() {
this.setBounds(200,200,300,200);
init();
this.setTitle("订制行程");
this.setVisible(true);
}
private void init() {
final BorderLayout borderLayout = new BorderLayout();
borderLayout.setVgap(5);
getContentPane().setLayout(borderLayout);
JPanel mainPanel = new JPanel();
mainPanel.setBorder(new EmptyBorder(5,10,5,10)); // need to understand
final GridLayout gridLayout = new GridLayout(4,4);
gridLayout.setVgap(5);
gridLayout.setHgap(5);
mainPanel.setLayout(gridLayout);
getContentPane().add(mainPanel,"North");
JLabel organizerLabel = new JLabel("组织者");
mainPanel.add(organizerLabel);
final JTextField organizer = new JTextField();
mainPanel.add(organizer);
JLabel groupNumMaxLabel = new JLabel("人数");
mainPanel.add(groupNumMaxLabel);
final JTextField groupNumMax = new JTextField();
mainPanel.add(groupNumMax);
JLabel siteIdLb1 = new JLabel(("具体景点信息"));
mainPanel.add(siteIdLb1);
final JTextField siteName1 = new JTextField();
mainPanel.add(siteName1);
JLabel siteIdLb2 = new JLabel("景点2");
final JTextField siteName2 = new JTextField();
mainPanel.add(siteIdLb2);
mainPanel.add(siteName2);
JLabel siteIdLb3 = new JLabel("景点3");
final JTextField siteName3 = new JTextField();
mainPanel.add(siteIdLb3);
mainPanel.add(siteName3);
JLabel siteIdOther = new JLabel("其它景点");
final JTextField siteNameText = new JTextField();
siteNameText.setText("请以,间隔");
siteNameText.setEnabled(false);
mainPanel.add(siteIdOther);
mainPanel.add(siteNameText);
JLabel startTimeLb = new JLabel("开始时间");
SimpleDateFormat myfmt = new SimpleDateFormat("yyyy-MM-dd");
final JFormattedTextField startTime = new JFormattedTextField(myfmt);
startTime.setValue(new java.util.Date());
mainPanel.add(startTimeLb);
mainPanel.add(startTime);
JLabel endTimeLb = new JLabel("结束时间");
final JFormattedTextField endTime = new JFormattedTextField(myfmt);
endTime.setValue(new Date());
mainPanel.add(endTimeLb);
mainPanel.add(endTime);
final JPanel bottomPanel = new JPanel();
bottomPanel.setBorder(new LineBorder(SystemColor.activeCaptionBorder,1,false));
getContentPane().add(bottomPanel,"South") ;
final FlowLayout flowLayout = new FlowLayout();
flowLayout.setVgap(2);
flowLayout.setHgap(30);
flowLayout.setAlignment(FlowLayout.RIGHT);
bottomPanel.setLayout(flowLayout);
final JButton btnAdd = new JButton("增加");
final JButton btnReset = new JButton("重置");
bottomPanel.add(btnAdd);
bottomPanel.add(btnReset);
// MyActionActionLister myBtnAddActionLister = new MyActionActionLister();
btnAdd.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
SimpleDateFormat smf = new SimpleDateFormat("yyyy-MM-dd");
String siteNames = siteName.getText() + ","+ siteName1.getText()+ ","+siteName2.getText()+ ","+siteName3.getText();
try {
if( smf.parse(startTime.getValue().toString()).before(smf.parse(endTime.getValue().toString()))) {
JOptionPane.showMessageDialog(null,"时间不对");
} else if(siteNames.length() == 0 || organizer.getText().length() ==0 || groupNumMax.getText().length() == 0)
{
JOptionPane.showMessageDialog(null,"信息不全");
} else{
int response = JOptionPane.showConfirmDialog(null,"确定提交","are you sure",JOptionPane.YES_NO_OPTION);
if(response == JOptionPane.YES_OPTION){
Mediator pm=new Mediator();
try{
- pm.addPlanFromForm(siteName.getText(), startTime.getText(),endTime.getText(),organizer.getText());
+ pm.addPlanFromForm(siteName.getText(),0,0, startTime.getText(),endTime.getText(),organizer.getText(),null);
}catch (TextFormatException e1) {
e1.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (SQLException e1) {
e1.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (JSONException e1) {
e1.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
}
} catch (ParseException e2) {
e2.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
});
btnReset.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
siteName.setText("");
// startTime.setText("");
// endTime.setText("");
organizer.setText("");
groupNumMax.setText("");
}
});
}
class MyActionActionLister implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
}
}
}
| true | true | private void init() {
final BorderLayout borderLayout = new BorderLayout();
borderLayout.setVgap(5);
getContentPane().setLayout(borderLayout);
JPanel mainPanel = new JPanel();
mainPanel.setBorder(new EmptyBorder(5,10,5,10)); // need to understand
final GridLayout gridLayout = new GridLayout(4,4);
gridLayout.setVgap(5);
gridLayout.setHgap(5);
mainPanel.setLayout(gridLayout);
getContentPane().add(mainPanel,"North");
JLabel organizerLabel = new JLabel("组织者");
mainPanel.add(organizerLabel);
final JTextField organizer = new JTextField();
mainPanel.add(organizer);
JLabel groupNumMaxLabel = new JLabel("人数");
mainPanel.add(groupNumMaxLabel);
final JTextField groupNumMax = new JTextField();
mainPanel.add(groupNumMax);
JLabel siteIdLb1 = new JLabel(("具体景点信息"));
mainPanel.add(siteIdLb1);
final JTextField siteName1 = new JTextField();
mainPanel.add(siteName1);
JLabel siteIdLb2 = new JLabel("景点2");
final JTextField siteName2 = new JTextField();
mainPanel.add(siteIdLb2);
mainPanel.add(siteName2);
JLabel siteIdLb3 = new JLabel("景点3");
final JTextField siteName3 = new JTextField();
mainPanel.add(siteIdLb3);
mainPanel.add(siteName3);
JLabel siteIdOther = new JLabel("其它景点");
final JTextField siteNameText = new JTextField();
siteNameText.setText("请以,间隔");
siteNameText.setEnabled(false);
mainPanel.add(siteIdOther);
mainPanel.add(siteNameText);
JLabel startTimeLb = new JLabel("开始时间");
SimpleDateFormat myfmt = new SimpleDateFormat("yyyy-MM-dd");
final JFormattedTextField startTime = new JFormattedTextField(myfmt);
startTime.setValue(new java.util.Date());
mainPanel.add(startTimeLb);
mainPanel.add(startTime);
JLabel endTimeLb = new JLabel("结束时间");
final JFormattedTextField endTime = new JFormattedTextField(myfmt);
endTime.setValue(new Date());
mainPanel.add(endTimeLb);
mainPanel.add(endTime);
final JPanel bottomPanel = new JPanel();
bottomPanel.setBorder(new LineBorder(SystemColor.activeCaptionBorder,1,false));
getContentPane().add(bottomPanel,"South") ;
final FlowLayout flowLayout = new FlowLayout();
flowLayout.setVgap(2);
flowLayout.setHgap(30);
flowLayout.setAlignment(FlowLayout.RIGHT);
bottomPanel.setLayout(flowLayout);
final JButton btnAdd = new JButton("增加");
final JButton btnReset = new JButton("重置");
bottomPanel.add(btnAdd);
bottomPanel.add(btnReset);
// MyActionActionLister myBtnAddActionLister = new MyActionActionLister();
btnAdd.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
SimpleDateFormat smf = new SimpleDateFormat("yyyy-MM-dd");
String siteNames = siteName.getText() + ","+ siteName1.getText()+ ","+siteName2.getText()+ ","+siteName3.getText();
try {
if( smf.parse(startTime.getValue().toString()).before(smf.parse(endTime.getValue().toString()))) {
JOptionPane.showMessageDialog(null,"时间不对");
} else if(siteNames.length() == 0 || organizer.getText().length() ==0 || groupNumMax.getText().length() == 0)
{
JOptionPane.showMessageDialog(null,"信息不全");
} else{
int response = JOptionPane.showConfirmDialog(null,"确定提交","are you sure",JOptionPane.YES_NO_OPTION);
if(response == JOptionPane.YES_OPTION){
Mediator pm=new Mediator();
try{
pm.addPlanFromForm(siteName.getText(), startTime.getText(),endTime.getText(),organizer.getText());
}catch (TextFormatException e1) {
e1.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (SQLException e1) {
e1.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (JSONException e1) {
e1.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
}
} catch (ParseException e2) {
e2.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
});
btnReset.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
siteName.setText("");
// startTime.setText("");
// endTime.setText("");
organizer.setText("");
groupNumMax.setText("");
}
});
}
| private void init() {
final BorderLayout borderLayout = new BorderLayout();
borderLayout.setVgap(5);
getContentPane().setLayout(borderLayout);
JPanel mainPanel = new JPanel();
mainPanel.setBorder(new EmptyBorder(5,10,5,10)); // need to understand
final GridLayout gridLayout = new GridLayout(4,4);
gridLayout.setVgap(5);
gridLayout.setHgap(5);
mainPanel.setLayout(gridLayout);
getContentPane().add(mainPanel,"North");
JLabel organizerLabel = new JLabel("组织者");
mainPanel.add(organizerLabel);
final JTextField organizer = new JTextField();
mainPanel.add(organizer);
JLabel groupNumMaxLabel = new JLabel("人数");
mainPanel.add(groupNumMaxLabel);
final JTextField groupNumMax = new JTextField();
mainPanel.add(groupNumMax);
JLabel siteIdLb1 = new JLabel(("具体景点信息"));
mainPanel.add(siteIdLb1);
final JTextField siteName1 = new JTextField();
mainPanel.add(siteName1);
JLabel siteIdLb2 = new JLabel("景点2");
final JTextField siteName2 = new JTextField();
mainPanel.add(siteIdLb2);
mainPanel.add(siteName2);
JLabel siteIdLb3 = new JLabel("景点3");
final JTextField siteName3 = new JTextField();
mainPanel.add(siteIdLb3);
mainPanel.add(siteName3);
JLabel siteIdOther = new JLabel("其它景点");
final JTextField siteNameText = new JTextField();
siteNameText.setText("请以,间隔");
siteNameText.setEnabled(false);
mainPanel.add(siteIdOther);
mainPanel.add(siteNameText);
JLabel startTimeLb = new JLabel("开始时间");
SimpleDateFormat myfmt = new SimpleDateFormat("yyyy-MM-dd");
final JFormattedTextField startTime = new JFormattedTextField(myfmt);
startTime.setValue(new java.util.Date());
mainPanel.add(startTimeLb);
mainPanel.add(startTime);
JLabel endTimeLb = new JLabel("结束时间");
final JFormattedTextField endTime = new JFormattedTextField(myfmt);
endTime.setValue(new Date());
mainPanel.add(endTimeLb);
mainPanel.add(endTime);
final JPanel bottomPanel = new JPanel();
bottomPanel.setBorder(new LineBorder(SystemColor.activeCaptionBorder,1,false));
getContentPane().add(bottomPanel,"South") ;
final FlowLayout flowLayout = new FlowLayout();
flowLayout.setVgap(2);
flowLayout.setHgap(30);
flowLayout.setAlignment(FlowLayout.RIGHT);
bottomPanel.setLayout(flowLayout);
final JButton btnAdd = new JButton("增加");
final JButton btnReset = new JButton("重置");
bottomPanel.add(btnAdd);
bottomPanel.add(btnReset);
// MyActionActionLister myBtnAddActionLister = new MyActionActionLister();
btnAdd.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
SimpleDateFormat smf = new SimpleDateFormat("yyyy-MM-dd");
String siteNames = siteName.getText() + ","+ siteName1.getText()+ ","+siteName2.getText()+ ","+siteName3.getText();
try {
if( smf.parse(startTime.getValue().toString()).before(smf.parse(endTime.getValue().toString()))) {
JOptionPane.showMessageDialog(null,"时间不对");
} else if(siteNames.length() == 0 || organizer.getText().length() ==0 || groupNumMax.getText().length() == 0)
{
JOptionPane.showMessageDialog(null,"信息不全");
} else{
int response = JOptionPane.showConfirmDialog(null,"确定提交","are you sure",JOptionPane.YES_NO_OPTION);
if(response == JOptionPane.YES_OPTION){
Mediator pm=new Mediator();
try{
pm.addPlanFromForm(siteName.getText(),0,0, startTime.getText(),endTime.getText(),organizer.getText(),null);
}catch (TextFormatException e1) {
e1.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (SQLException e1) {
e1.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (JSONException e1) {
e1.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
}
} catch (ParseException e2) {
e2.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
});
btnReset.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
siteName.setText("");
// startTime.setText("");
// endTime.setText("");
organizer.setText("");
groupNumMax.setText("");
}
});
}
|
diff --git a/ui-tests/src/test/java/org/openmrs/reference/RegistrationAppTest.java b/ui-tests/src/test/java/org/openmrs/reference/RegistrationAppTest.java
index 77c230c..7eeb93d 100644
--- a/ui-tests/src/test/java/org/openmrs/reference/RegistrationAppTest.java
+++ b/ui-tests/src/test/java/org/openmrs/reference/RegistrationAppTest.java
@@ -1,78 +1,77 @@
package org.openmrs.reference;
import static org.junit.Assert.assertEquals;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.openmrs.reference.helper.PatientGenerator;
import org.openmrs.reference.helper.TestPatient;
import org.openmrs.reference.page.HeaderPage;
import org.openmrs.reference.page.HomePage;
import org.openmrs.reference.page.LoginPage;
import org.openmrs.reference.page.RegistrationPage;
public class RegistrationAppTest extends TestBase{
private HeaderPage headerPage;
private LoginPage loginPage;
private RegistrationPage registrationPage;
private HomePage homePage;
@Before
public void setUp() {
loginPage = new LoginPage(driver);
headerPage = new HeaderPage(driver);
homePage = new HomePage(driver);
registrationPage = new RegistrationPage(driver);
loginPage.loginAsAdmin();
}
@Ignore
public void verifyRegistrationSuccessful() {
homePage.openRegisterAPatientApp();
// registrationPage.registerPatient();
// breeze - commented this test out as it is a WIP
//todo - Verification of the Patient Registration once RA-72 is completed
}
// Test for Story RA-71
@Test
public void verifyAddressValuesDisplayedInConfirmationPage() {
homePage.openRegisterAPatientApp();
TestPatient patient = PatientGenerator.generateTestPatient();
registrationPage.enterPatientGivenName(patient.givenName);
registrationPage.enterPatientFamilyName(patient.familyName);
registrationPage.clickOnGenderLink();
registrationPage.selectPatientGender(patient.gender);
registrationPage.clickOnBirthDateLink();
registrationPage.enterPatientBirthDate(patient);
registrationPage.clickOnContactInfo();
- registrationPage.clickOnAddressLink();
registrationPage.enterPatientAddress(patient);
registrationPage.clickOnPhoneNumber();
registrationPage.enterPhoneNumber(patient.phone);
registrationPage.clickOnConfirm();
String address = patient.address1 + " " +
patient.address2 + " " +
patient.city + " " +
patient.state + " " +
patient.country + " " +
patient.postalCode + " " +
patient.latitude + " " +
patient.longitude;
assertEquals(address, registrationPage.getAddressValueInConfirmationPage());
}
@After
public void tearDown(){
headerPage.logOut();
}
}
| true | true | public void verifyAddressValuesDisplayedInConfirmationPage() {
homePage.openRegisterAPatientApp();
TestPatient patient = PatientGenerator.generateTestPatient();
registrationPage.enterPatientGivenName(patient.givenName);
registrationPage.enterPatientFamilyName(patient.familyName);
registrationPage.clickOnGenderLink();
registrationPage.selectPatientGender(patient.gender);
registrationPage.clickOnBirthDateLink();
registrationPage.enterPatientBirthDate(patient);
registrationPage.clickOnContactInfo();
registrationPage.clickOnAddressLink();
registrationPage.enterPatientAddress(patient);
registrationPage.clickOnPhoneNumber();
registrationPage.enterPhoneNumber(patient.phone);
registrationPage.clickOnConfirm();
String address = patient.address1 + " " +
patient.address2 + " " +
patient.city + " " +
patient.state + " " +
patient.country + " " +
patient.postalCode + " " +
patient.latitude + " " +
patient.longitude;
assertEquals(address, registrationPage.getAddressValueInConfirmationPage());
}
| public void verifyAddressValuesDisplayedInConfirmationPage() {
homePage.openRegisterAPatientApp();
TestPatient patient = PatientGenerator.generateTestPatient();
registrationPage.enterPatientGivenName(patient.givenName);
registrationPage.enterPatientFamilyName(patient.familyName);
registrationPage.clickOnGenderLink();
registrationPage.selectPatientGender(patient.gender);
registrationPage.clickOnBirthDateLink();
registrationPage.enterPatientBirthDate(patient);
registrationPage.clickOnContactInfo();
registrationPage.enterPatientAddress(patient);
registrationPage.clickOnPhoneNumber();
registrationPage.enterPhoneNumber(patient.phone);
registrationPage.clickOnConfirm();
String address = patient.address1 + " " +
patient.address2 + " " +
patient.city + " " +
patient.state + " " +
patient.country + " " +
patient.postalCode + " " +
patient.latitude + " " +
patient.longitude;
assertEquals(address, registrationPage.getAddressValueInConfirmationPage());
}
|
diff --git a/src/btwmod/tinyurl/mod_TinyUrl.java b/src/btwmod/tinyurl/mod_TinyUrl.java
index 9542287..8e36687 100644
--- a/src/btwmod/tinyurl/mod_TinyUrl.java
+++ b/src/btwmod/tinyurl/mod_TinyUrl.java
@@ -1,93 +1,93 @@
package btwmod.tinyurl;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.nio.ByteBuffer;
import java.util.Random;
import java.util.logging.Level;
import btwmods.IMod;
import btwmods.ModLoader;
import btwmods.PlayerAPI;
import btwmods.io.Settings;
import btwmods.player.IPlayerChatListener;
import btwmods.player.PlayerChatEvent;
import btwmods.util.Base64;
public class mod_TinyUrl implements IMod, IPlayerChatListener {
private static final String redirectHTML = "<!DOCTYPE html><html><head><meta charset=\"utf-8\">"
+ "<title>Redirecting...</title>"
+ "<script>location.replace(\"@@@\");</script></head>"
+ "<body><p>Redirecting to <a href=\"###\">###</a></p></body></html>";
private int index = new Random().nextInt(100000) + 100000;
private String url = null;
private File redirectDirectory = null;
@Override
public String getName() {
return "Tiny URL";
}
@Override
public void init(Settings settings, Settings data) throws Exception {
if (settings.hasKey("directory"))
redirectDirectory = new File(settings.get("directory"));
else {
ModLoader.outputError(getName() + "'s directory setting is not set.");
return;
}
if (settings.hasKey("url"))
url = settings.get("url");
else {
ModLoader.outputError(getName() + "'s url setting is not set.");
return;
}
if (!redirectDirectory.isDirectory()) {
ModLoader.outputError(getName() + "'s directory setting does not point to a directory.", Level.SEVERE);
return;
}
PlayerAPI.addListener(this);
}
@Override
public void unload() throws Exception {
PlayerAPI.removeListener(this);
}
@Override
public IMod getMod() {
return this;
}
@Override
public void onPlayerChatAction(PlayerChatEvent event) {
String message = event.getMessage();
- if (!message.startsWith("/")) {
+ if (event.type == PlayerChatEvent.TYPE.AUTO_COMPLETE && !message.startsWith("/")) {
String[] split = message.split(" ", -1);
String last = split[split.length - 1];
if (last.length() >= url.length() && (last.startsWith("http://") || last.startsWith("https://")) && !last.startsWith(url)) {
try {
File redirectFile = new File(redirectDirectory,
Base64.encodeToString(ByteBuffer.allocate(4).putInt(index++).array(), false).replaceAll("=+$", "").replace("/", "_").replace("+", "-"));
BufferedWriter bw = new BufferedWriter(new FileWriter(redirectFile));
bw.write(redirectHTML
.replace("@@@", last.replace("'", "\\'").replace("\"", "\\\"").replace("\0", "\\0"))
.replace("###", last.replace("&", "&").replace("\"", """).replace("'", "'").replace("<", "<").replace(">", ">")));
bw.close();
event.addCompletion(url + redirectFile.getName());
event.markHandled();
} catch (Exception e) {
ModLoader.outputError(e, getName() + " failed to create a redirect file:" + e.getMessage());
}
}
}
}
}
| true | true | public void onPlayerChatAction(PlayerChatEvent event) {
String message = event.getMessage();
if (!message.startsWith("/")) {
String[] split = message.split(" ", -1);
String last = split[split.length - 1];
if (last.length() >= url.length() && (last.startsWith("http://") || last.startsWith("https://")) && !last.startsWith(url)) {
try {
File redirectFile = new File(redirectDirectory,
Base64.encodeToString(ByteBuffer.allocate(4).putInt(index++).array(), false).replaceAll("=+$", "").replace("/", "_").replace("+", "-"));
BufferedWriter bw = new BufferedWriter(new FileWriter(redirectFile));
bw.write(redirectHTML
.replace("@@@", last.replace("'", "\\'").replace("\"", "\\\"").replace("\0", "\\0"))
.replace("###", last.replace("&", "&").replace("\"", """).replace("'", "'").replace("<", "<").replace(">", ">")));
bw.close();
event.addCompletion(url + redirectFile.getName());
event.markHandled();
} catch (Exception e) {
ModLoader.outputError(e, getName() + " failed to create a redirect file:" + e.getMessage());
}
}
}
}
| public void onPlayerChatAction(PlayerChatEvent event) {
String message = event.getMessage();
if (event.type == PlayerChatEvent.TYPE.AUTO_COMPLETE && !message.startsWith("/")) {
String[] split = message.split(" ", -1);
String last = split[split.length - 1];
if (last.length() >= url.length() && (last.startsWith("http://") || last.startsWith("https://")) && !last.startsWith(url)) {
try {
File redirectFile = new File(redirectDirectory,
Base64.encodeToString(ByteBuffer.allocate(4).putInt(index++).array(), false).replaceAll("=+$", "").replace("/", "_").replace("+", "-"));
BufferedWriter bw = new BufferedWriter(new FileWriter(redirectFile));
bw.write(redirectHTML
.replace("@@@", last.replace("'", "\\'").replace("\"", "\\\"").replace("\0", "\\0"))
.replace("###", last.replace("&", "&").replace("\"", """).replace("'", "'").replace("<", "<").replace(">", ">")));
bw.close();
event.addCompletion(url + redirectFile.getName());
event.markHandled();
} catch (Exception e) {
ModLoader.outputError(e, getName() + " failed to create a redirect file:" + e.getMessage());
}
}
}
}
|
diff --git a/src/org/apache/xalan/xslt/Process.java b/src/org/apache/xalan/xslt/Process.java
index 83b05ddc..a9648409 100644
--- a/src/org/apache/xalan/xslt/Process.java
+++ b/src/org/apache/xalan/xslt/Process.java
@@ -1,1192 +1,1192 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* $Id$
*/
package org.apache.xalan.xslt;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.StringReader;
import java.util.Properties;
import java.util.ResourceBundle;
import java.util.Vector;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Templates;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.URIResolver;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.sax.SAXResult;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.apache.xalan.Version;
import org.apache.xalan.res.XSLMessages;
import org.apache.xalan.res.XSLTErrorResources;
import org.apache.xalan.trace.PrintTraceListener;
import org.apache.xalan.trace.TraceManager;
import org.apache.xalan.transformer.XalanProperties;
import org.apache.xml.utils.DefaultErrorHandler;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.ContentHandler;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;
/**
* The main() method handles the Xalan command-line interface.
* @xsl.usage general
*/
public class Process
{
/**
* Prints argument options.
*
* @param resbundle Resource bundle
*/
protected static void printArgOptions(ResourceBundle resbundle)
{
System.out.println(resbundle.getString("xslProc_option")); //"xslproc options: ");
System.out.println("\n\t\t\t" + resbundle.getString("xslProc_common_options") + "\n");
System.out.println(resbundle.getString("optionXSLTC")); //" [-XSLTC (use XSLTC for transformation)]
System.out.println(resbundle.getString("optionIN")); //" [-IN inputXMLURL]");
System.out.println(resbundle.getString("optionXSL")); //" [-XSL XSLTransformationURL]");
System.out.println(resbundle.getString("optionOUT")); //" [-OUT outputFileName]");
// System.out.println(resbundle.getString("optionE")); //" [-E (Do not expand entity refs)]");
System.out.println(resbundle.getString("optionV")); //" [-V (Version info)]");
// System.out.println(resbundle.getString("optionVALIDATE")); //" [-VALIDATE (Set whether validation occurs. Validation is off by default.)]");
System.out.println(resbundle.getString("optionEDUMP")); //" [-EDUMP {optional filename} (Do stackdump on error.)]");
System.out.println(resbundle.getString("optionXML")); //" [-XML (Use XML formatter and add XML header.)]");
System.out.println(resbundle.getString("optionTEXT")); //" [-TEXT (Use simple Text formatter.)]");
System.out.println(resbundle.getString("optionHTML")); //" [-HTML (Use HTML formatter.)]");
System.out.println(resbundle.getString("optionPARAM")); //" [-PARAM name expression (Set a stylesheet parameter)]");
System.out.println(resbundle.getString("optionMEDIA"));
System.out.println(resbundle.getString("optionFLAVOR"));
System.out.println(resbundle.getString("optionDIAG"));
System.out.println(resbundle.getString("optionURIRESOLVER")); //" [-URIRESOLVER full class name (URIResolver to be used to resolve URIs)]");
System.out.println(resbundle.getString("optionENTITYRESOLVER")); //" [-ENTITYRESOLVER full class name (EntityResolver to be used to resolve entities)]");
waitForReturnKey(resbundle);
System.out.println(resbundle.getString("optionCONTENTHANDLER")); //" [-CONTENTHANDLER full class name (ContentHandler to be used to serialize output)]");
System.out.println(resbundle.getString("optionSECUREPROCESSING")); //" [-SECURE (set the secure processing feature to true)]");
System.out.println("\n\t\t\t" + resbundle.getString("xslProc_xalan_options") + "\n");
System.out.println(resbundle.getString("optionQC")); //" [-QC (Quiet Pattern Conflicts Warnings)]");
// System.out.println(resbundle.getString("optionQ")); //" [-Q (Quiet Mode)]"); // sc 28-Feb-01 commented out
System.out.println(resbundle.getString("optionTT")); //" [-TT (Trace the templates as they are being called.)]");
System.out.println(resbundle.getString("optionTG")); //" [-TG (Trace each generation event.)]");
System.out.println(resbundle.getString("optionTS")); //" [-TS (Trace each selection event.)]");
System.out.println(resbundle.getString("optionTTC")); //" [-TTC (Trace the template children as they are being processed.)]");
System.out.println(resbundle.getString("optionTCLASS")); //" [-TCLASS (TraceListener class for trace extensions.)]");
System.out.println(resbundle.getString("optionLINENUMBERS")); //" [-L use line numbers]"
System.out.println(resbundle.getString("optionINCREMENTAL"));
System.out.println(resbundle.getString("optionNOOPTIMIMIZE"));
System.out.println(resbundle.getString("optionRL"));
System.out.println("\n\t\t\t" + resbundle.getString("xslProc_xsltc_options") + "\n");
System.out.println(resbundle.getString("optionXO"));
waitForReturnKey(resbundle);
System.out.println(resbundle.getString("optionXD"));
System.out.println(resbundle.getString("optionXJ"));
System.out.println(resbundle.getString("optionXP"));
System.out.println(resbundle.getString("optionXN"));
System.out.println(resbundle.getString("optionXX"));
System.out.println(resbundle.getString("optionXT"));
}
/**
* Command line interface to transform an XML document according to
* the instructions found in an XSL stylesheet.
* <p>The Process class provides basic functionality for
* performing transformations from the command line. To see a
* list of arguments supported, call with zero arguments.</p>
* <p>To set stylesheet parameters from the command line, use
* <code>-PARAM name expression</code>. If you want to set the
* parameter to a string value, simply pass the string value
* as-is, and it will be interpreted as a string. (Note: if
* the value has spaces in it, you may need to quote it depending
* on your shell environment).</p>
*
* @param argv Input parameters from command line
*/
public static void main(String argv[])
{
// Runtime.getRuntime().traceMethodCalls(false); // turns Java tracing off
boolean doStackDumpOnError = false;
boolean setQuietMode = false;
boolean doDiag = false;
String msg = null;
boolean isSecureProcessing = false;
// Runtime.getRuntime().traceMethodCalls(false);
// Runtime.getRuntime().traceInstructions(false);
/**
* The default diagnostic writer...
*/
java.io.PrintWriter diagnosticsWriter = new PrintWriter(System.err, true);
java.io.PrintWriter dumpWriter = diagnosticsWriter;
ResourceBundle resbundle =
(XSLMessages.loadResourceBundle(
org.apache.xml.utils.res.XResourceBundle.ERROR_RESOURCES));
String flavor = "s2s";
if (argv.length < 1)
{
printArgOptions(resbundle);
}
else
{
boolean useXSLTC = false;
for (int i = 0; i < argv.length; i++)
{
if ("-XSLTC".equalsIgnoreCase(argv[i]))
{
useXSLTC = true;
}
}
TransformerFactory tfactory;
if (useXSLTC)
{
String key = "javax.xml.transform.TransformerFactory";
String value = "org.apache.xalan.xsltc.trax.TransformerFactoryImpl";
Properties props = System.getProperties();
props.put(key, value);
System.setProperties(props);
}
try
{
tfactory = TransformerFactory.newInstance();
- tfactory.setErrorListener(new DefaultErrorHandler());
+ tfactory.setErrorListener(new DefaultErrorHandler(false));
}
catch (TransformerFactoryConfigurationError pfe)
{
pfe.printStackTrace(dumpWriter);
// "XSL Process was not successful.");
msg = XSLMessages.createMessage(
XSLTErrorResources.ER_NOT_SUCCESSFUL, null);
diagnosticsWriter.println(msg);
tfactory = null; // shut up compiler
doExit(msg);
}
boolean formatOutput = false;
boolean useSourceLocation = false;
String inFileName = null;
String outFileName = null;
String dumpFileName = null;
String xslFileName = null;
String treedumpFileName = null;
PrintTraceListener tracer = null;
String outputType = null;
String media = null;
Vector params = new Vector();
boolean quietConflictWarnings = false;
URIResolver uriResolver = null;
EntityResolver entityResolver = null;
ContentHandler contentHandler = null;
int recursionLimit=-1;
for (int i = 0; i < argv.length; i++)
{
if ("-XSLTC".equalsIgnoreCase(argv[i]))
{
// The -XSLTC option has been processed.
}
else if ("-TT".equalsIgnoreCase(argv[i]))
{
if (!useXSLTC)
{
if (null == tracer)
tracer = new PrintTraceListener(diagnosticsWriter);
tracer.m_traceTemplates = true;
}
else
printInvalidXSLTCOption("-TT");
// tfactory.setTraceTemplates(true);
}
else if ("-TG".equalsIgnoreCase(argv[i]))
{
if (!useXSLTC)
{
if (null == tracer)
tracer = new PrintTraceListener(diagnosticsWriter);
tracer.m_traceGeneration = true;
}
else
printInvalidXSLTCOption("-TG");
// tfactory.setTraceSelect(true);
}
else if ("-TS".equalsIgnoreCase(argv[i]))
{
if (!useXSLTC)
{
if (null == tracer)
tracer = new PrintTraceListener(diagnosticsWriter);
tracer.m_traceSelection = true;
}
else
printInvalidXSLTCOption("-TS");
// tfactory.setTraceTemplates(true);
}
else if ("-TTC".equalsIgnoreCase(argv[i]))
{
if (!useXSLTC)
{
if (null == tracer)
tracer = new PrintTraceListener(diagnosticsWriter);
tracer.m_traceElements = true;
}
else
printInvalidXSLTCOption("-TTC");
// tfactory.setTraceTemplateChildren(true);
}
else if ("-INDENT".equalsIgnoreCase(argv[i]))
{
int indentAmount;
if (((i + 1) < argv.length) && (argv[i + 1].charAt(0) != '-'))
{
indentAmount = Integer.parseInt(argv[++i]);
}
else
{
indentAmount = 0;
}
// TBD:
// xmlProcessorLiaison.setIndent(indentAmount);
}
else if ("-IN".equalsIgnoreCase(argv[i]))
{
if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-')
inFileName = argv[++i];
else
System.err.println(
XSLMessages.createMessage(
XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
new Object[]{ "-IN" })); //"Missing argument for);
}
else if ("-MEDIA".equalsIgnoreCase(argv[i]))
{
if (i + 1 < argv.length)
media = argv[++i];
else
System.err.println(
XSLMessages.createMessage(
XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
new Object[]{ "-MEDIA" })); //"Missing argument for);
}
else if ("-OUT".equalsIgnoreCase(argv[i]))
{
if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-')
outFileName = argv[++i];
else
System.err.println(
XSLMessages.createMessage(
XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
new Object[]{ "-OUT" })); //"Missing argument for);
}
else if ("-XSL".equalsIgnoreCase(argv[i]))
{
if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-')
xslFileName = argv[++i];
else
System.err.println(
XSLMessages.createMessage(
XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
new Object[]{ "-XSL" })); //"Missing argument for);
}
else if ("-FLAVOR".equalsIgnoreCase(argv[i]))
{
if (i + 1 < argv.length)
{
flavor = argv[++i];
}
else
System.err.println(
XSLMessages.createMessage(
XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
new Object[]{ "-FLAVOR" })); //"Missing argument for);
}
else if ("-PARAM".equalsIgnoreCase(argv[i]))
{
if (i + 2 < argv.length)
{
String name = argv[++i];
params.addElement(name);
String expression = argv[++i];
params.addElement(expression);
}
else
System.err.println(
XSLMessages.createMessage(
XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
new Object[]{ "-PARAM" })); //"Missing argument for);
}
else if ("-E".equalsIgnoreCase(argv[i]))
{
// TBD:
// xmlProcessorLiaison.setShouldExpandEntityRefs(false);
}
else if ("-V".equalsIgnoreCase(argv[i]))
{
diagnosticsWriter.println(resbundle.getString("version") //">>>>>>> Xalan Version "
+ Version.getVersion() + ", " +
/* xmlProcessorLiaison.getParserDescription()+ */
resbundle.getString("version2")); // "<<<<<<<");
}
else if ("-QC".equalsIgnoreCase(argv[i]))
{
if (!useXSLTC)
quietConflictWarnings = true;
else
printInvalidXSLTCOption("-QC");
}
else if ("-Q".equalsIgnoreCase(argv[i]))
{
setQuietMode = true;
}
else if ("-DIAG".equalsIgnoreCase(argv[i]))
{
doDiag = true;
}
else if ("-XML".equalsIgnoreCase(argv[i]))
{
outputType = "xml";
}
else if ("-TEXT".equalsIgnoreCase(argv[i]))
{
outputType = "text";
}
else if ("-HTML".equalsIgnoreCase(argv[i]))
{
outputType = "html";
}
else if ("-EDUMP".equalsIgnoreCase(argv[i]))
{
doStackDumpOnError = true;
if (((i + 1) < argv.length) && (argv[i + 1].charAt(0) != '-'))
{
dumpFileName = argv[++i];
}
}
else if ("-URIRESOLVER".equalsIgnoreCase(argv[i]))
{
if (i + 1 < argv.length)
{
try
{
uriResolver = (URIResolver) ObjectFactory.newInstance(
argv[++i], ObjectFactory.findClassLoader(), true);
tfactory.setURIResolver(uriResolver);
}
catch (ObjectFactory.ConfigurationError cnfe)
{
msg = XSLMessages.createMessage(
XSLTErrorResources.ER_CLASS_NOT_FOUND_FOR_OPTION,
new Object[]{ "-URIResolver" });
System.err.println(msg);
doExit(msg);
}
}
else
{
msg = XSLMessages.createMessage(
XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
new Object[]{ "-URIResolver" }); //"Missing argument for);
System.err.println(msg);
doExit(msg);
}
}
else if ("-ENTITYRESOLVER".equalsIgnoreCase(argv[i]))
{
if (i + 1 < argv.length)
{
try
{
entityResolver = (EntityResolver) ObjectFactory.newInstance(
argv[++i], ObjectFactory.findClassLoader(), true);
}
catch (ObjectFactory.ConfigurationError cnfe)
{
msg = XSLMessages.createMessage(
XSLTErrorResources.ER_CLASS_NOT_FOUND_FOR_OPTION,
new Object[]{ "-EntityResolver" });
System.err.println(msg);
doExit(msg);
}
}
else
{
// "Missing argument for);
msg = XSLMessages.createMessage(
XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
new Object[]{ "-EntityResolver" });
System.err.println(msg);
doExit(msg);
}
}
else if ("-CONTENTHANDLER".equalsIgnoreCase(argv[i]))
{
if (i + 1 < argv.length)
{
try
{
contentHandler = (ContentHandler) ObjectFactory.newInstance(
argv[++i], ObjectFactory.findClassLoader(), true);
}
catch (ObjectFactory.ConfigurationError cnfe)
{
msg = XSLMessages.createMessage(
XSLTErrorResources.ER_CLASS_NOT_FOUND_FOR_OPTION,
new Object[]{ "-ContentHandler" });
System.err.println(msg);
doExit(msg);
}
}
else
{
// "Missing argument for);
msg = XSLMessages.createMessage(
XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
new Object[]{ "-ContentHandler" });
System.err.println(msg);
doExit(msg);
}
}
else if ("-L".equalsIgnoreCase(argv[i]))
{
if (!useXSLTC)
tfactory.setAttribute(XalanProperties.SOURCE_LOCATION, Boolean.TRUE);
else
printInvalidXSLTCOption("-L");
}
else if ("-INCREMENTAL".equalsIgnoreCase(argv[i]))
{
if (!useXSLTC)
tfactory.setAttribute
("http://xml.apache.org/xalan/features/incremental",
java.lang.Boolean.TRUE);
else
printInvalidXSLTCOption("-INCREMENTAL");
}
else if ("-NOOPTIMIZE".equalsIgnoreCase(argv[i]))
{
// Default is true.
//
// %REVIEW% We should have a generalized syntax for negative
// switches... and probably should accept the inverse even
// if it is the default.
if (!useXSLTC)
tfactory.setAttribute
("http://xml.apache.org/xalan/features/optimize",
java.lang.Boolean.FALSE);
else
printInvalidXSLTCOption("-NOOPTIMIZE");
}
else if ("-RL".equalsIgnoreCase(argv[i]))
{
if (!useXSLTC)
{
if (i + 1 < argv.length)
recursionLimit = Integer.parseInt(argv[++i]);
else
System.err.println(
XSLMessages.createMessage(
XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
new Object[]{ "-rl" })); //"Missing argument for);
}
else
{
if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-')
i++;
printInvalidXSLTCOption("-RL");
}
}
// Generate the translet class and optionally specify the name
// of the translet class.
else if ("-XO".equalsIgnoreCase(argv[i]))
{
if (useXSLTC)
{
if (i + 1 < argv.length && argv[i+1].charAt(0) != '-')
{
tfactory.setAttribute("generate-translet", "true");
tfactory.setAttribute("translet-name", argv[++i]);
}
else
tfactory.setAttribute("generate-translet", "true");
}
else
{
if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-')
i++;
printInvalidXalanOption("-XO");
}
}
// Specify the destination directory for the translet classes.
else if ("-XD".equalsIgnoreCase(argv[i]))
{
if (useXSLTC)
{
if (i + 1 < argv.length && argv[i+1].charAt(0) != '-')
tfactory.setAttribute("destination-directory", argv[++i]);
else
System.err.println(
XSLMessages.createMessage(
XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
new Object[]{ "-XD" })); //"Missing argument for);
}
else
{
if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-')
i++;
printInvalidXalanOption("-XD");
}
}
// Specify the jar file name which the translet classes are packaged into.
else if ("-XJ".equalsIgnoreCase(argv[i]))
{
if (useXSLTC)
{
if (i + 1 < argv.length && argv[i+1].charAt(0) != '-')
{
tfactory.setAttribute("generate-translet", "true");
tfactory.setAttribute("jar-name", argv[++i]);
}
else
System.err.println(
XSLMessages.createMessage(
XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
new Object[]{ "-XJ" })); //"Missing argument for);
}
else
{
if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-')
i++;
printInvalidXalanOption("-XJ");
}
}
// Specify the package name prefix for the generated translet classes.
else if ("-XP".equalsIgnoreCase(argv[i]))
{
if (useXSLTC)
{
if (i + 1 < argv.length && argv[i+1].charAt(0) != '-')
tfactory.setAttribute("package-name", argv[++i]);
else
System.err.println(
XSLMessages.createMessage(
XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
new Object[]{ "-XP" })); //"Missing argument for);
}
else
{
if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-')
i++;
printInvalidXalanOption("-XP");
}
}
// Enable template inlining.
else if ("-XN".equalsIgnoreCase(argv[i]))
{
if (useXSLTC)
{
tfactory.setAttribute("enable-inlining", "true");
}
else
printInvalidXalanOption("-XN");
}
// Turns on additional debugging message output
else if ("-XX".equalsIgnoreCase(argv[i]))
{
if (useXSLTC)
{
tfactory.setAttribute("debug", "true");
}
else
printInvalidXalanOption("-XX");
}
// Create the Transformer from the translet if the translet class is newer
// than the stylesheet.
else if ("-XT".equalsIgnoreCase(argv[i]))
{
if (useXSLTC)
{
tfactory.setAttribute("auto-translet", "true");
}
else
printInvalidXalanOption("-XT");
}
else if ("-SECURE".equalsIgnoreCase(argv[i]))
{
isSecureProcessing = true;
try
{
tfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
}
catch (TransformerConfigurationException e) {}
}
else
System.err.println(
XSLMessages.createMessage(
XSLTErrorResources.ER_INVALID_OPTION, new Object[]{ argv[i] })); //"Invalid argument:);
}
// Print usage instructions if no xml and xsl file is specified in the command line
if (inFileName == null && xslFileName == null)
{
msg = resbundle.getString("xslProc_no_input");
System.err.println(msg);
doExit(msg);
}
// Note that there are usage cases for calling us without a -IN arg
// The main XSL transformation occurs here!
try
{
long start = System.currentTimeMillis();
if (null != dumpFileName)
{
dumpWriter = new PrintWriter(new FileWriter(dumpFileName));
}
Templates stylesheet = null;
if (null != xslFileName)
{
if (flavor.equals("d2d"))
{
// Parse in the xml data into a DOM
DocumentBuilderFactory dfactory =
DocumentBuilderFactory.newInstance();
dfactory.setNamespaceAware(true);
if (isSecureProcessing)
{
try
{
dfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
}
catch (ParserConfigurationException pce) {}
}
DocumentBuilder docBuilder = dfactory.newDocumentBuilder();
Node xslDOM = docBuilder.parse(new InputSource(xslFileName));
stylesheet = tfactory.newTemplates(new DOMSource(xslDOM,
xslFileName));
}
else
{
// System.out.println("Calling newTemplates: "+xslFileName);
stylesheet = tfactory.newTemplates(new StreamSource(xslFileName));
// System.out.println("Done calling newTemplates: "+xslFileName);
}
}
PrintWriter resultWriter;
StreamResult strResult;
if (null != outFileName)
{
strResult = new StreamResult(new FileOutputStream(outFileName));
// One possible improvement might be to ensure this is
// a valid URI before setting the systemId, but that
// might have subtle changes that pre-existing users
// might notice; we can think about that later -sc r1.46
strResult.setSystemId(outFileName);
}
else
{
strResult = new StreamResult(System.out);
// We used to default to incremental mode in this case.
// We've since decided that since the -INCREMENTAL switch is
// available, that default is probably not necessary nor
// necessarily a good idea.
}
SAXTransformerFactory stf = (SAXTransformerFactory) tfactory;
// This is currently controlled via TransformerFactoryImpl.
if (!useXSLTC && useSourceLocation)
stf.setAttribute(XalanProperties.SOURCE_LOCATION, Boolean.TRUE);
// Did they pass in a stylesheet, or should we get it from the
// document?
if (null == stylesheet)
{
Source source =
stf.getAssociatedStylesheet(new StreamSource(inFileName), media,
null, null);
if (null != source)
stylesheet = tfactory.newTemplates(source);
else
{
if (null != media)
throw new TransformerException(XSLMessages.createMessage(XSLTErrorResources.ER_NO_STYLESHEET_IN_MEDIA, new Object[]{inFileName, media})); //"No stylesheet found in: "
// + inFileName + ", media="
// + media);
else
throw new TransformerException(XSLMessages.createMessage(XSLTErrorResources.ER_NO_STYLESHEET_PI, new Object[]{inFileName})); //"No xml-stylesheet PI found in: "
//+ inFileName);
}
}
if (null != stylesheet)
{
Transformer transformer = flavor.equals("th") ? null : stylesheet.newTransformer();
- transformer.setErrorListener(new DefaultErrorHandler());
+ transformer.setErrorListener(new DefaultErrorHandler(false));
// Override the output format?
if (null != outputType)
{
transformer.setOutputProperty(OutputKeys.METHOD, outputType);
}
if (transformer instanceof org.apache.xalan.transformer.TransformerImpl)
{
org.apache.xalan.transformer.TransformerImpl impl = (org.apache.xalan.transformer.TransformerImpl)transformer;
TraceManager tm = impl.getTraceManager();
if (null != tracer)
tm.addTraceListener(tracer);
impl.setQuietConflictWarnings(quietConflictWarnings);
// This is currently controlled via TransformerFactoryImpl.
if (useSourceLocation)
impl.setProperty(XalanProperties.SOURCE_LOCATION, Boolean.TRUE);
if(recursionLimit>0)
impl.setRecursionLimit(recursionLimit);
// sc 28-Feb-01 if we re-implement this, please uncomment helpmsg in printArgOptions
// impl.setDiagnosticsOutput( setQuietMode ? null : diagnosticsWriter );
}
int nParams = params.size();
for (int i = 0; i < nParams; i += 2)
{
transformer.setParameter((String) params.elementAt(i),
(String) params.elementAt(i + 1));
}
if (uriResolver != null)
transformer.setURIResolver(uriResolver);
if (null != inFileName)
{
if (flavor.equals("d2d"))
{
// Parse in the xml data into a DOM
DocumentBuilderFactory dfactory =
DocumentBuilderFactory.newInstance();
dfactory.setCoalescing(true);
dfactory.setNamespaceAware(true);
if (isSecureProcessing)
{
try
{
dfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
}
catch (ParserConfigurationException pce) {}
}
DocumentBuilder docBuilder = dfactory.newDocumentBuilder();
if (entityResolver != null)
docBuilder.setEntityResolver(entityResolver);
Node xmlDoc = docBuilder.parse(new InputSource(inFileName));
Document doc = docBuilder.newDocument();
org.w3c.dom.DocumentFragment outNode =
doc.createDocumentFragment();
transformer.transform(new DOMSource(xmlDoc, inFileName),
new DOMResult(outNode));
// Now serialize output to disk with identity transformer
Transformer serializer = stf.newTransformer();
- serializer.setErrorListener(new DefaultErrorHandler());
+ serializer.setErrorListener(new DefaultErrorHandler(false));
Properties serializationProps =
stylesheet.getOutputProperties();
serializer.setOutputProperties(serializationProps);
if (contentHandler != null)
{
SAXResult result = new SAXResult(contentHandler);
serializer.transform(new DOMSource(outNode), result);
}
else
serializer.transform(new DOMSource(outNode), strResult);
}
else if (flavor.equals("th"))
{
for (int i = 0; i < 1; i++) // Loop for diagnosing bugs with inconsistent behavior
{
// System.out.println("Testing the TransformerHandler...");
// ===============
XMLReader reader = null;
// Use JAXP1.1 ( if possible )
try
{
javax.xml.parsers.SAXParserFactory factory =
javax.xml.parsers.SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
if (isSecureProcessing)
{
try
{
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
}
catch (org.xml.sax.SAXException se) {}
}
javax.xml.parsers.SAXParser jaxpParser =
factory.newSAXParser();
reader = jaxpParser.getXMLReader();
}
catch (javax.xml.parsers.ParserConfigurationException ex)
{
throw new org.xml.sax.SAXException(ex);
}
catch (javax.xml.parsers.FactoryConfigurationError ex1)
{
throw new org.xml.sax.SAXException(ex1.toString());
}
catch (NoSuchMethodError ex2){}
catch (AbstractMethodError ame){}
if (null == reader)
{
reader = XMLReaderFactory.createXMLReader();
}
if (!useXSLTC)
stf.setAttribute(org.apache.xalan.processor.TransformerFactoryImpl.FEATURE_INCREMENTAL,
Boolean.TRUE);
TransformerHandler th = stf.newTransformerHandler(stylesheet);
reader.setContentHandler(th);
reader.setDTDHandler(th);
if(th instanceof org.xml.sax.ErrorHandler)
reader.setErrorHandler((org.xml.sax.ErrorHandler)th);
try
{
reader.setProperty(
"http://xml.org/sax/properties/lexical-handler", th);
}
catch (org.xml.sax.SAXNotRecognizedException e){}
catch (org.xml.sax.SAXNotSupportedException e){}
try
{
reader.setFeature("http://xml.org/sax/features/namespace-prefixes",
true);
} catch (org.xml.sax.SAXException se) {}
th.setResult(strResult);
reader.parse(new InputSource(inFileName));
}
}
else
{
if (entityResolver != null)
{
XMLReader reader = null;
// Use JAXP1.1 ( if possible )
try
{
javax.xml.parsers.SAXParserFactory factory =
javax.xml.parsers.SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
if (isSecureProcessing)
{
try
{
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
}
catch (org.xml.sax.SAXException se) {}
}
javax.xml.parsers.SAXParser jaxpParser =
factory.newSAXParser();
reader = jaxpParser.getXMLReader();
}
catch (javax.xml.parsers.ParserConfigurationException ex)
{
throw new org.xml.sax.SAXException(ex);
}
catch (javax.xml.parsers.FactoryConfigurationError ex1)
{
throw new org.xml.sax.SAXException(ex1.toString());
}
catch (NoSuchMethodError ex2){}
catch (AbstractMethodError ame){}
if (null == reader)
{
reader = XMLReaderFactory.createXMLReader();
}
reader.setEntityResolver(entityResolver);
if (contentHandler != null)
{
SAXResult result = new SAXResult(contentHandler);
transformer.transform(
new SAXSource(reader, new InputSource(inFileName)),
result);
}
else
{
transformer.transform(
new SAXSource(reader, new InputSource(inFileName)),
strResult);
}
}
else if (contentHandler != null)
{
SAXResult result = new SAXResult(contentHandler);
transformer.transform(new StreamSource(inFileName), result);
}
else
{
// System.out.println("Starting transform");
transformer.transform(new StreamSource(inFileName),
strResult);
// System.out.println("Done with transform");
}
}
}
else
{
StringReader reader =
new StringReader("<?xml version=\"1.0\"?> <doc/>");
transformer.transform(new StreamSource(reader), strResult);
}
}
else
{
// "XSL Process was not successful.");
msg = XSLMessages.createMessage(
XSLTErrorResources.ER_NOT_SUCCESSFUL, null);
diagnosticsWriter.println(msg);
doExit(msg);
}
// close output streams
if (null != outFileName && strResult!=null)
{
java.io.OutputStream out = strResult.getOutputStream();
java.io.Writer writer = strResult.getWriter();
try
{
if (out != null) out.close();
if (writer != null) writer.close();
}
catch(java.io.IOException ie) {}
}
long stop = System.currentTimeMillis();
long millisecondsDuration = stop - start;
if (doDiag)
{
Object[] msgArgs = new Object[]{ inFileName, xslFileName, new Long(millisecondsDuration) };
msg = XSLMessages.createMessage("diagTiming", msgArgs);
diagnosticsWriter.println('\n');
diagnosticsWriter.println(msg);
}
}
catch (Throwable throwable)
{
while (throwable
instanceof org.apache.xml.utils.WrappedRuntimeException)
{
throwable =
((org.apache.xml.utils.WrappedRuntimeException) throwable).getException();
}
if ((throwable instanceof NullPointerException)
|| (throwable instanceof ClassCastException))
doStackDumpOnError = true;
diagnosticsWriter.println();
if (doStackDumpOnError)
throwable.printStackTrace(dumpWriter);
else
{
DefaultErrorHandler.printLocation(diagnosticsWriter, throwable);
diagnosticsWriter.println(
XSLMessages.createMessage(XSLTErrorResources.ER_XSLT_ERROR, null)
+ " (" + throwable.getClass().getName() + "): "
+ throwable.getMessage());
}
// diagnosticsWriter.println(XSLMessages.createMessage(XSLTErrorResources.ER_NOT_SUCCESSFUL, null)); //"XSL Process was not successful.");
if (null != dumpFileName)
{
dumpWriter.close();
}
doExit(throwable.getMessage());
}
if (null != dumpFileName)
{
dumpWriter.close();
}
if (null != diagnosticsWriter)
{
// diagnosticsWriter.close();
}
// if(!setQuietMode)
// diagnosticsWriter.println(resbundle.getString("xsldone")); //"Xalan: done");
// else
// diagnosticsWriter.println(""); //"Xalan: done");
}
}
/** It is _much_ easier to debug under VJ++ if I can set a single breakpoint
* before this blows itself out of the water...
* (I keep checking this in, it keeps vanishing. Grr!)
* */
static void doExit(String msg)
{
throw new RuntimeException(msg);
}
/**
* Wait for a return key to continue
*
* @param resbundle The resource bundle
*/
private static void waitForReturnKey(ResourceBundle resbundle)
{
System.out.println(resbundle.getString("xslProc_return_to_continue"));
try
{
while (System.in.read() != '\n');
}
catch (java.io.IOException e) { }
}
/**
* Print a message if an option cannot be used with -XSLTC.
*
* @param option The option String
*/
private static void printInvalidXSLTCOption(String option)
{
System.err.println(XSLMessages.createMessage("xslProc_invalid_xsltc_option", new Object[]{option}));
}
/**
* Print a message if an option can only be used with -XSLTC.
*
* @param option The option String
*/
private static void printInvalidXalanOption(String option)
{
System.err.println(XSLMessages.createMessage("xslProc_invalid_xalan_option", new Object[]{option}));
}
}
| false | true | public static void main(String argv[])
{
// Runtime.getRuntime().traceMethodCalls(false); // turns Java tracing off
boolean doStackDumpOnError = false;
boolean setQuietMode = false;
boolean doDiag = false;
String msg = null;
boolean isSecureProcessing = false;
// Runtime.getRuntime().traceMethodCalls(false);
// Runtime.getRuntime().traceInstructions(false);
/**
* The default diagnostic writer...
*/
java.io.PrintWriter diagnosticsWriter = new PrintWriter(System.err, true);
java.io.PrintWriter dumpWriter = diagnosticsWriter;
ResourceBundle resbundle =
(XSLMessages.loadResourceBundle(
org.apache.xml.utils.res.XResourceBundle.ERROR_RESOURCES));
String flavor = "s2s";
if (argv.length < 1)
{
printArgOptions(resbundle);
}
else
{
boolean useXSLTC = false;
for (int i = 0; i < argv.length; i++)
{
if ("-XSLTC".equalsIgnoreCase(argv[i]))
{
useXSLTC = true;
}
}
TransformerFactory tfactory;
if (useXSLTC)
{
String key = "javax.xml.transform.TransformerFactory";
String value = "org.apache.xalan.xsltc.trax.TransformerFactoryImpl";
Properties props = System.getProperties();
props.put(key, value);
System.setProperties(props);
}
try
{
tfactory = TransformerFactory.newInstance();
tfactory.setErrorListener(new DefaultErrorHandler());
}
catch (TransformerFactoryConfigurationError pfe)
{
pfe.printStackTrace(dumpWriter);
// "XSL Process was not successful.");
msg = XSLMessages.createMessage(
XSLTErrorResources.ER_NOT_SUCCESSFUL, null);
diagnosticsWriter.println(msg);
tfactory = null; // shut up compiler
doExit(msg);
}
boolean formatOutput = false;
boolean useSourceLocation = false;
String inFileName = null;
String outFileName = null;
String dumpFileName = null;
String xslFileName = null;
String treedumpFileName = null;
PrintTraceListener tracer = null;
String outputType = null;
String media = null;
Vector params = new Vector();
boolean quietConflictWarnings = false;
URIResolver uriResolver = null;
EntityResolver entityResolver = null;
ContentHandler contentHandler = null;
int recursionLimit=-1;
for (int i = 0; i < argv.length; i++)
{
if ("-XSLTC".equalsIgnoreCase(argv[i]))
{
// The -XSLTC option has been processed.
}
else if ("-TT".equalsIgnoreCase(argv[i]))
{
if (!useXSLTC)
{
if (null == tracer)
tracer = new PrintTraceListener(diagnosticsWriter);
tracer.m_traceTemplates = true;
}
else
printInvalidXSLTCOption("-TT");
// tfactory.setTraceTemplates(true);
}
else if ("-TG".equalsIgnoreCase(argv[i]))
{
if (!useXSLTC)
{
if (null == tracer)
tracer = new PrintTraceListener(diagnosticsWriter);
tracer.m_traceGeneration = true;
}
else
printInvalidXSLTCOption("-TG");
// tfactory.setTraceSelect(true);
}
else if ("-TS".equalsIgnoreCase(argv[i]))
{
if (!useXSLTC)
{
if (null == tracer)
tracer = new PrintTraceListener(diagnosticsWriter);
tracer.m_traceSelection = true;
}
else
printInvalidXSLTCOption("-TS");
// tfactory.setTraceTemplates(true);
}
else if ("-TTC".equalsIgnoreCase(argv[i]))
{
if (!useXSLTC)
{
if (null == tracer)
tracer = new PrintTraceListener(diagnosticsWriter);
tracer.m_traceElements = true;
}
else
printInvalidXSLTCOption("-TTC");
// tfactory.setTraceTemplateChildren(true);
}
else if ("-INDENT".equalsIgnoreCase(argv[i]))
{
int indentAmount;
if (((i + 1) < argv.length) && (argv[i + 1].charAt(0) != '-'))
{
indentAmount = Integer.parseInt(argv[++i]);
}
else
{
indentAmount = 0;
}
// TBD:
// xmlProcessorLiaison.setIndent(indentAmount);
}
else if ("-IN".equalsIgnoreCase(argv[i]))
{
if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-')
inFileName = argv[++i];
else
System.err.println(
XSLMessages.createMessage(
XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
new Object[]{ "-IN" })); //"Missing argument for);
}
else if ("-MEDIA".equalsIgnoreCase(argv[i]))
{
if (i + 1 < argv.length)
media = argv[++i];
else
System.err.println(
XSLMessages.createMessage(
XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
new Object[]{ "-MEDIA" })); //"Missing argument for);
}
else if ("-OUT".equalsIgnoreCase(argv[i]))
{
if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-')
outFileName = argv[++i];
else
System.err.println(
XSLMessages.createMessage(
XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
new Object[]{ "-OUT" })); //"Missing argument for);
}
else if ("-XSL".equalsIgnoreCase(argv[i]))
{
if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-')
xslFileName = argv[++i];
else
System.err.println(
XSLMessages.createMessage(
XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
new Object[]{ "-XSL" })); //"Missing argument for);
}
else if ("-FLAVOR".equalsIgnoreCase(argv[i]))
{
if (i + 1 < argv.length)
{
flavor = argv[++i];
}
else
System.err.println(
XSLMessages.createMessage(
XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
new Object[]{ "-FLAVOR" })); //"Missing argument for);
}
else if ("-PARAM".equalsIgnoreCase(argv[i]))
{
if (i + 2 < argv.length)
{
String name = argv[++i];
params.addElement(name);
String expression = argv[++i];
params.addElement(expression);
}
else
System.err.println(
XSLMessages.createMessage(
XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
new Object[]{ "-PARAM" })); //"Missing argument for);
}
else if ("-E".equalsIgnoreCase(argv[i]))
{
// TBD:
// xmlProcessorLiaison.setShouldExpandEntityRefs(false);
}
else if ("-V".equalsIgnoreCase(argv[i]))
{
diagnosticsWriter.println(resbundle.getString("version") //">>>>>>> Xalan Version "
+ Version.getVersion() + ", " +
/* xmlProcessorLiaison.getParserDescription()+ */
resbundle.getString("version2")); // "<<<<<<<");
}
else if ("-QC".equalsIgnoreCase(argv[i]))
{
if (!useXSLTC)
quietConflictWarnings = true;
else
printInvalidXSLTCOption("-QC");
}
else if ("-Q".equalsIgnoreCase(argv[i]))
{
setQuietMode = true;
}
else if ("-DIAG".equalsIgnoreCase(argv[i]))
{
doDiag = true;
}
else if ("-XML".equalsIgnoreCase(argv[i]))
{
outputType = "xml";
}
else if ("-TEXT".equalsIgnoreCase(argv[i]))
{
outputType = "text";
}
else if ("-HTML".equalsIgnoreCase(argv[i]))
{
outputType = "html";
}
else if ("-EDUMP".equalsIgnoreCase(argv[i]))
{
doStackDumpOnError = true;
if (((i + 1) < argv.length) && (argv[i + 1].charAt(0) != '-'))
{
dumpFileName = argv[++i];
}
}
else if ("-URIRESOLVER".equalsIgnoreCase(argv[i]))
{
if (i + 1 < argv.length)
{
try
{
uriResolver = (URIResolver) ObjectFactory.newInstance(
argv[++i], ObjectFactory.findClassLoader(), true);
tfactory.setURIResolver(uriResolver);
}
catch (ObjectFactory.ConfigurationError cnfe)
{
msg = XSLMessages.createMessage(
XSLTErrorResources.ER_CLASS_NOT_FOUND_FOR_OPTION,
new Object[]{ "-URIResolver" });
System.err.println(msg);
doExit(msg);
}
}
else
{
msg = XSLMessages.createMessage(
XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
new Object[]{ "-URIResolver" }); //"Missing argument for);
System.err.println(msg);
doExit(msg);
}
}
else if ("-ENTITYRESOLVER".equalsIgnoreCase(argv[i]))
{
if (i + 1 < argv.length)
{
try
{
entityResolver = (EntityResolver) ObjectFactory.newInstance(
argv[++i], ObjectFactory.findClassLoader(), true);
}
catch (ObjectFactory.ConfigurationError cnfe)
{
msg = XSLMessages.createMessage(
XSLTErrorResources.ER_CLASS_NOT_FOUND_FOR_OPTION,
new Object[]{ "-EntityResolver" });
System.err.println(msg);
doExit(msg);
}
}
else
{
// "Missing argument for);
msg = XSLMessages.createMessage(
XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
new Object[]{ "-EntityResolver" });
System.err.println(msg);
doExit(msg);
}
}
else if ("-CONTENTHANDLER".equalsIgnoreCase(argv[i]))
{
if (i + 1 < argv.length)
{
try
{
contentHandler = (ContentHandler) ObjectFactory.newInstance(
argv[++i], ObjectFactory.findClassLoader(), true);
}
catch (ObjectFactory.ConfigurationError cnfe)
{
msg = XSLMessages.createMessage(
XSLTErrorResources.ER_CLASS_NOT_FOUND_FOR_OPTION,
new Object[]{ "-ContentHandler" });
System.err.println(msg);
doExit(msg);
}
}
else
{
// "Missing argument for);
msg = XSLMessages.createMessage(
XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
new Object[]{ "-ContentHandler" });
System.err.println(msg);
doExit(msg);
}
}
else if ("-L".equalsIgnoreCase(argv[i]))
{
if (!useXSLTC)
tfactory.setAttribute(XalanProperties.SOURCE_LOCATION, Boolean.TRUE);
else
printInvalidXSLTCOption("-L");
}
else if ("-INCREMENTAL".equalsIgnoreCase(argv[i]))
{
if (!useXSLTC)
tfactory.setAttribute
("http://xml.apache.org/xalan/features/incremental",
java.lang.Boolean.TRUE);
else
printInvalidXSLTCOption("-INCREMENTAL");
}
else if ("-NOOPTIMIZE".equalsIgnoreCase(argv[i]))
{
// Default is true.
//
// %REVIEW% We should have a generalized syntax for negative
// switches... and probably should accept the inverse even
// if it is the default.
if (!useXSLTC)
tfactory.setAttribute
("http://xml.apache.org/xalan/features/optimize",
java.lang.Boolean.FALSE);
else
printInvalidXSLTCOption("-NOOPTIMIZE");
}
else if ("-RL".equalsIgnoreCase(argv[i]))
{
if (!useXSLTC)
{
if (i + 1 < argv.length)
recursionLimit = Integer.parseInt(argv[++i]);
else
System.err.println(
XSLMessages.createMessage(
XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
new Object[]{ "-rl" })); //"Missing argument for);
}
else
{
if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-')
i++;
printInvalidXSLTCOption("-RL");
}
}
// Generate the translet class and optionally specify the name
// of the translet class.
else if ("-XO".equalsIgnoreCase(argv[i]))
{
if (useXSLTC)
{
if (i + 1 < argv.length && argv[i+1].charAt(0) != '-')
{
tfactory.setAttribute("generate-translet", "true");
tfactory.setAttribute("translet-name", argv[++i]);
}
else
tfactory.setAttribute("generate-translet", "true");
}
else
{
if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-')
i++;
printInvalidXalanOption("-XO");
}
}
// Specify the destination directory for the translet classes.
else if ("-XD".equalsIgnoreCase(argv[i]))
{
if (useXSLTC)
{
if (i + 1 < argv.length && argv[i+1].charAt(0) != '-')
tfactory.setAttribute("destination-directory", argv[++i]);
else
System.err.println(
XSLMessages.createMessage(
XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
new Object[]{ "-XD" })); //"Missing argument for);
}
else
{
if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-')
i++;
printInvalidXalanOption("-XD");
}
}
// Specify the jar file name which the translet classes are packaged into.
else if ("-XJ".equalsIgnoreCase(argv[i]))
{
if (useXSLTC)
{
if (i + 1 < argv.length && argv[i+1].charAt(0) != '-')
{
tfactory.setAttribute("generate-translet", "true");
tfactory.setAttribute("jar-name", argv[++i]);
}
else
System.err.println(
XSLMessages.createMessage(
XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
new Object[]{ "-XJ" })); //"Missing argument for);
}
else
{
if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-')
i++;
printInvalidXalanOption("-XJ");
}
}
// Specify the package name prefix for the generated translet classes.
else if ("-XP".equalsIgnoreCase(argv[i]))
{
if (useXSLTC)
{
if (i + 1 < argv.length && argv[i+1].charAt(0) != '-')
tfactory.setAttribute("package-name", argv[++i]);
else
System.err.println(
XSLMessages.createMessage(
XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
new Object[]{ "-XP" })); //"Missing argument for);
}
else
{
if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-')
i++;
printInvalidXalanOption("-XP");
}
}
// Enable template inlining.
else if ("-XN".equalsIgnoreCase(argv[i]))
{
if (useXSLTC)
{
tfactory.setAttribute("enable-inlining", "true");
}
else
printInvalidXalanOption("-XN");
}
// Turns on additional debugging message output
else if ("-XX".equalsIgnoreCase(argv[i]))
{
if (useXSLTC)
{
tfactory.setAttribute("debug", "true");
}
else
printInvalidXalanOption("-XX");
}
// Create the Transformer from the translet if the translet class is newer
// than the stylesheet.
else if ("-XT".equalsIgnoreCase(argv[i]))
{
if (useXSLTC)
{
tfactory.setAttribute("auto-translet", "true");
}
else
printInvalidXalanOption("-XT");
}
else if ("-SECURE".equalsIgnoreCase(argv[i]))
{
isSecureProcessing = true;
try
{
tfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
}
catch (TransformerConfigurationException e) {}
}
else
System.err.println(
XSLMessages.createMessage(
XSLTErrorResources.ER_INVALID_OPTION, new Object[]{ argv[i] })); //"Invalid argument:);
}
// Print usage instructions if no xml and xsl file is specified in the command line
if (inFileName == null && xslFileName == null)
{
msg = resbundle.getString("xslProc_no_input");
System.err.println(msg);
doExit(msg);
}
// Note that there are usage cases for calling us without a -IN arg
// The main XSL transformation occurs here!
try
{
long start = System.currentTimeMillis();
if (null != dumpFileName)
{
dumpWriter = new PrintWriter(new FileWriter(dumpFileName));
}
Templates stylesheet = null;
if (null != xslFileName)
{
if (flavor.equals("d2d"))
{
// Parse in the xml data into a DOM
DocumentBuilderFactory dfactory =
DocumentBuilderFactory.newInstance();
dfactory.setNamespaceAware(true);
if (isSecureProcessing)
{
try
{
dfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
}
catch (ParserConfigurationException pce) {}
}
DocumentBuilder docBuilder = dfactory.newDocumentBuilder();
Node xslDOM = docBuilder.parse(new InputSource(xslFileName));
stylesheet = tfactory.newTemplates(new DOMSource(xslDOM,
xslFileName));
}
else
{
// System.out.println("Calling newTemplates: "+xslFileName);
stylesheet = tfactory.newTemplates(new StreamSource(xslFileName));
// System.out.println("Done calling newTemplates: "+xslFileName);
}
}
PrintWriter resultWriter;
StreamResult strResult;
if (null != outFileName)
{
strResult = new StreamResult(new FileOutputStream(outFileName));
// One possible improvement might be to ensure this is
// a valid URI before setting the systemId, but that
// might have subtle changes that pre-existing users
// might notice; we can think about that later -sc r1.46
strResult.setSystemId(outFileName);
}
else
{
strResult = new StreamResult(System.out);
// We used to default to incremental mode in this case.
// We've since decided that since the -INCREMENTAL switch is
// available, that default is probably not necessary nor
// necessarily a good idea.
}
SAXTransformerFactory stf = (SAXTransformerFactory) tfactory;
// This is currently controlled via TransformerFactoryImpl.
if (!useXSLTC && useSourceLocation)
stf.setAttribute(XalanProperties.SOURCE_LOCATION, Boolean.TRUE);
// Did they pass in a stylesheet, or should we get it from the
// document?
if (null == stylesheet)
{
Source source =
stf.getAssociatedStylesheet(new StreamSource(inFileName), media,
null, null);
if (null != source)
stylesheet = tfactory.newTemplates(source);
else
{
if (null != media)
throw new TransformerException(XSLMessages.createMessage(XSLTErrorResources.ER_NO_STYLESHEET_IN_MEDIA, new Object[]{inFileName, media})); //"No stylesheet found in: "
// + inFileName + ", media="
// + media);
else
throw new TransformerException(XSLMessages.createMessage(XSLTErrorResources.ER_NO_STYLESHEET_PI, new Object[]{inFileName})); //"No xml-stylesheet PI found in: "
//+ inFileName);
}
}
if (null != stylesheet)
{
Transformer transformer = flavor.equals("th") ? null : stylesheet.newTransformer();
transformer.setErrorListener(new DefaultErrorHandler());
// Override the output format?
if (null != outputType)
{
transformer.setOutputProperty(OutputKeys.METHOD, outputType);
}
if (transformer instanceof org.apache.xalan.transformer.TransformerImpl)
{
org.apache.xalan.transformer.TransformerImpl impl = (org.apache.xalan.transformer.TransformerImpl)transformer;
TraceManager tm = impl.getTraceManager();
if (null != tracer)
tm.addTraceListener(tracer);
impl.setQuietConflictWarnings(quietConflictWarnings);
// This is currently controlled via TransformerFactoryImpl.
if (useSourceLocation)
impl.setProperty(XalanProperties.SOURCE_LOCATION, Boolean.TRUE);
if(recursionLimit>0)
impl.setRecursionLimit(recursionLimit);
// sc 28-Feb-01 if we re-implement this, please uncomment helpmsg in printArgOptions
// impl.setDiagnosticsOutput( setQuietMode ? null : diagnosticsWriter );
}
int nParams = params.size();
for (int i = 0; i < nParams; i += 2)
{
transformer.setParameter((String) params.elementAt(i),
(String) params.elementAt(i + 1));
}
if (uriResolver != null)
transformer.setURIResolver(uriResolver);
if (null != inFileName)
{
if (flavor.equals("d2d"))
{
// Parse in the xml data into a DOM
DocumentBuilderFactory dfactory =
DocumentBuilderFactory.newInstance();
dfactory.setCoalescing(true);
dfactory.setNamespaceAware(true);
if (isSecureProcessing)
{
try
{
dfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
}
catch (ParserConfigurationException pce) {}
}
DocumentBuilder docBuilder = dfactory.newDocumentBuilder();
if (entityResolver != null)
docBuilder.setEntityResolver(entityResolver);
Node xmlDoc = docBuilder.parse(new InputSource(inFileName));
Document doc = docBuilder.newDocument();
org.w3c.dom.DocumentFragment outNode =
doc.createDocumentFragment();
transformer.transform(new DOMSource(xmlDoc, inFileName),
new DOMResult(outNode));
// Now serialize output to disk with identity transformer
Transformer serializer = stf.newTransformer();
serializer.setErrorListener(new DefaultErrorHandler());
Properties serializationProps =
stylesheet.getOutputProperties();
serializer.setOutputProperties(serializationProps);
if (contentHandler != null)
{
SAXResult result = new SAXResult(contentHandler);
serializer.transform(new DOMSource(outNode), result);
}
else
serializer.transform(new DOMSource(outNode), strResult);
}
else if (flavor.equals("th"))
{
for (int i = 0; i < 1; i++) // Loop for diagnosing bugs with inconsistent behavior
{
// System.out.println("Testing the TransformerHandler...");
// ===============
XMLReader reader = null;
// Use JAXP1.1 ( if possible )
try
{
javax.xml.parsers.SAXParserFactory factory =
javax.xml.parsers.SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
if (isSecureProcessing)
{
try
{
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
}
catch (org.xml.sax.SAXException se) {}
}
javax.xml.parsers.SAXParser jaxpParser =
factory.newSAXParser();
reader = jaxpParser.getXMLReader();
}
catch (javax.xml.parsers.ParserConfigurationException ex)
{
throw new org.xml.sax.SAXException(ex);
}
catch (javax.xml.parsers.FactoryConfigurationError ex1)
{
throw new org.xml.sax.SAXException(ex1.toString());
}
catch (NoSuchMethodError ex2){}
catch (AbstractMethodError ame){}
if (null == reader)
{
reader = XMLReaderFactory.createXMLReader();
}
if (!useXSLTC)
stf.setAttribute(org.apache.xalan.processor.TransformerFactoryImpl.FEATURE_INCREMENTAL,
Boolean.TRUE);
TransformerHandler th = stf.newTransformerHandler(stylesheet);
reader.setContentHandler(th);
reader.setDTDHandler(th);
if(th instanceof org.xml.sax.ErrorHandler)
reader.setErrorHandler((org.xml.sax.ErrorHandler)th);
try
{
reader.setProperty(
"http://xml.org/sax/properties/lexical-handler", th);
}
catch (org.xml.sax.SAXNotRecognizedException e){}
catch (org.xml.sax.SAXNotSupportedException e){}
try
{
reader.setFeature("http://xml.org/sax/features/namespace-prefixes",
true);
} catch (org.xml.sax.SAXException se) {}
th.setResult(strResult);
reader.parse(new InputSource(inFileName));
}
}
else
{
if (entityResolver != null)
{
XMLReader reader = null;
// Use JAXP1.1 ( if possible )
try
{
javax.xml.parsers.SAXParserFactory factory =
javax.xml.parsers.SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
if (isSecureProcessing)
{
try
{
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
}
catch (org.xml.sax.SAXException se) {}
}
javax.xml.parsers.SAXParser jaxpParser =
factory.newSAXParser();
reader = jaxpParser.getXMLReader();
}
catch (javax.xml.parsers.ParserConfigurationException ex)
{
throw new org.xml.sax.SAXException(ex);
}
catch (javax.xml.parsers.FactoryConfigurationError ex1)
{
throw new org.xml.sax.SAXException(ex1.toString());
}
catch (NoSuchMethodError ex2){}
catch (AbstractMethodError ame){}
if (null == reader)
{
reader = XMLReaderFactory.createXMLReader();
}
reader.setEntityResolver(entityResolver);
if (contentHandler != null)
{
SAXResult result = new SAXResult(contentHandler);
transformer.transform(
new SAXSource(reader, new InputSource(inFileName)),
result);
}
else
{
transformer.transform(
new SAXSource(reader, new InputSource(inFileName)),
strResult);
}
}
else if (contentHandler != null)
{
SAXResult result = new SAXResult(contentHandler);
transformer.transform(new StreamSource(inFileName), result);
}
else
{
// System.out.println("Starting transform");
transformer.transform(new StreamSource(inFileName),
strResult);
// System.out.println("Done with transform");
}
}
}
else
{
StringReader reader =
new StringReader("<?xml version=\"1.0\"?> <doc/>");
transformer.transform(new StreamSource(reader), strResult);
}
}
else
{
// "XSL Process was not successful.");
msg = XSLMessages.createMessage(
XSLTErrorResources.ER_NOT_SUCCESSFUL, null);
diagnosticsWriter.println(msg);
doExit(msg);
}
// close output streams
if (null != outFileName && strResult!=null)
{
java.io.OutputStream out = strResult.getOutputStream();
java.io.Writer writer = strResult.getWriter();
try
{
if (out != null) out.close();
if (writer != null) writer.close();
}
catch(java.io.IOException ie) {}
}
long stop = System.currentTimeMillis();
long millisecondsDuration = stop - start;
if (doDiag)
{
Object[] msgArgs = new Object[]{ inFileName, xslFileName, new Long(millisecondsDuration) };
msg = XSLMessages.createMessage("diagTiming", msgArgs);
diagnosticsWriter.println('\n');
diagnosticsWriter.println(msg);
}
}
catch (Throwable throwable)
{
while (throwable
instanceof org.apache.xml.utils.WrappedRuntimeException)
{
throwable =
((org.apache.xml.utils.WrappedRuntimeException) throwable).getException();
}
if ((throwable instanceof NullPointerException)
|| (throwable instanceof ClassCastException))
doStackDumpOnError = true;
diagnosticsWriter.println();
if (doStackDumpOnError)
throwable.printStackTrace(dumpWriter);
else
{
DefaultErrorHandler.printLocation(diagnosticsWriter, throwable);
diagnosticsWriter.println(
XSLMessages.createMessage(XSLTErrorResources.ER_XSLT_ERROR, null)
+ " (" + throwable.getClass().getName() + "): "
+ throwable.getMessage());
}
// diagnosticsWriter.println(XSLMessages.createMessage(XSLTErrorResources.ER_NOT_SUCCESSFUL, null)); //"XSL Process was not successful.");
if (null != dumpFileName)
{
dumpWriter.close();
}
doExit(throwable.getMessage());
}
if (null != dumpFileName)
{
dumpWriter.close();
}
if (null != diagnosticsWriter)
{
// diagnosticsWriter.close();
}
// if(!setQuietMode)
// diagnosticsWriter.println(resbundle.getString("xsldone")); //"Xalan: done");
// else
// diagnosticsWriter.println(""); //"Xalan: done");
}
}
/** It is _much_ easier to debug under VJ++ if I can set a single breakpoint
* before this blows itself out of the water...
* (I keep checking this in, it keeps vanishing. Grr!)
* */
static void doExit(String msg)
{
throw new RuntimeException(msg);
}
/**
* Wait for a return key to continue
*
* @param resbundle The resource bundle
*/
private static void waitForReturnKey(ResourceBundle resbundle)
{
System.out.println(resbundle.getString("xslProc_return_to_continue"));
try
{
while (System.in.read() != '\n');
}
catch (java.io.IOException e) { }
}
/**
* Print a message if an option cannot be used with -XSLTC.
*
* @param option The option String
*/
private static void printInvalidXSLTCOption(String option)
{
System.err.println(XSLMessages.createMessage("xslProc_invalid_xsltc_option", new Object[]{option}));
}
/**
* Print a message if an option can only be used with -XSLTC.
*
* @param option The option String
*/
private static void printInvalidXalanOption(String option)
{
System.err.println(XSLMessages.createMessage("xslProc_invalid_xalan_option", new Object[]{option}));
}
}
| public static void main(String argv[])
{
// Runtime.getRuntime().traceMethodCalls(false); // turns Java tracing off
boolean doStackDumpOnError = false;
boolean setQuietMode = false;
boolean doDiag = false;
String msg = null;
boolean isSecureProcessing = false;
// Runtime.getRuntime().traceMethodCalls(false);
// Runtime.getRuntime().traceInstructions(false);
/**
* The default diagnostic writer...
*/
java.io.PrintWriter diagnosticsWriter = new PrintWriter(System.err, true);
java.io.PrintWriter dumpWriter = diagnosticsWriter;
ResourceBundle resbundle =
(XSLMessages.loadResourceBundle(
org.apache.xml.utils.res.XResourceBundle.ERROR_RESOURCES));
String flavor = "s2s";
if (argv.length < 1)
{
printArgOptions(resbundle);
}
else
{
boolean useXSLTC = false;
for (int i = 0; i < argv.length; i++)
{
if ("-XSLTC".equalsIgnoreCase(argv[i]))
{
useXSLTC = true;
}
}
TransformerFactory tfactory;
if (useXSLTC)
{
String key = "javax.xml.transform.TransformerFactory";
String value = "org.apache.xalan.xsltc.trax.TransformerFactoryImpl";
Properties props = System.getProperties();
props.put(key, value);
System.setProperties(props);
}
try
{
tfactory = TransformerFactory.newInstance();
tfactory.setErrorListener(new DefaultErrorHandler(false));
}
catch (TransformerFactoryConfigurationError pfe)
{
pfe.printStackTrace(dumpWriter);
// "XSL Process was not successful.");
msg = XSLMessages.createMessage(
XSLTErrorResources.ER_NOT_SUCCESSFUL, null);
diagnosticsWriter.println(msg);
tfactory = null; // shut up compiler
doExit(msg);
}
boolean formatOutput = false;
boolean useSourceLocation = false;
String inFileName = null;
String outFileName = null;
String dumpFileName = null;
String xslFileName = null;
String treedumpFileName = null;
PrintTraceListener tracer = null;
String outputType = null;
String media = null;
Vector params = new Vector();
boolean quietConflictWarnings = false;
URIResolver uriResolver = null;
EntityResolver entityResolver = null;
ContentHandler contentHandler = null;
int recursionLimit=-1;
for (int i = 0; i < argv.length; i++)
{
if ("-XSLTC".equalsIgnoreCase(argv[i]))
{
// The -XSLTC option has been processed.
}
else if ("-TT".equalsIgnoreCase(argv[i]))
{
if (!useXSLTC)
{
if (null == tracer)
tracer = new PrintTraceListener(diagnosticsWriter);
tracer.m_traceTemplates = true;
}
else
printInvalidXSLTCOption("-TT");
// tfactory.setTraceTemplates(true);
}
else if ("-TG".equalsIgnoreCase(argv[i]))
{
if (!useXSLTC)
{
if (null == tracer)
tracer = new PrintTraceListener(diagnosticsWriter);
tracer.m_traceGeneration = true;
}
else
printInvalidXSLTCOption("-TG");
// tfactory.setTraceSelect(true);
}
else if ("-TS".equalsIgnoreCase(argv[i]))
{
if (!useXSLTC)
{
if (null == tracer)
tracer = new PrintTraceListener(diagnosticsWriter);
tracer.m_traceSelection = true;
}
else
printInvalidXSLTCOption("-TS");
// tfactory.setTraceTemplates(true);
}
else if ("-TTC".equalsIgnoreCase(argv[i]))
{
if (!useXSLTC)
{
if (null == tracer)
tracer = new PrintTraceListener(diagnosticsWriter);
tracer.m_traceElements = true;
}
else
printInvalidXSLTCOption("-TTC");
// tfactory.setTraceTemplateChildren(true);
}
else if ("-INDENT".equalsIgnoreCase(argv[i]))
{
int indentAmount;
if (((i + 1) < argv.length) && (argv[i + 1].charAt(0) != '-'))
{
indentAmount = Integer.parseInt(argv[++i]);
}
else
{
indentAmount = 0;
}
// TBD:
// xmlProcessorLiaison.setIndent(indentAmount);
}
else if ("-IN".equalsIgnoreCase(argv[i]))
{
if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-')
inFileName = argv[++i];
else
System.err.println(
XSLMessages.createMessage(
XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
new Object[]{ "-IN" })); //"Missing argument for);
}
else if ("-MEDIA".equalsIgnoreCase(argv[i]))
{
if (i + 1 < argv.length)
media = argv[++i];
else
System.err.println(
XSLMessages.createMessage(
XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
new Object[]{ "-MEDIA" })); //"Missing argument for);
}
else if ("-OUT".equalsIgnoreCase(argv[i]))
{
if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-')
outFileName = argv[++i];
else
System.err.println(
XSLMessages.createMessage(
XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
new Object[]{ "-OUT" })); //"Missing argument for);
}
else if ("-XSL".equalsIgnoreCase(argv[i]))
{
if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-')
xslFileName = argv[++i];
else
System.err.println(
XSLMessages.createMessage(
XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
new Object[]{ "-XSL" })); //"Missing argument for);
}
else if ("-FLAVOR".equalsIgnoreCase(argv[i]))
{
if (i + 1 < argv.length)
{
flavor = argv[++i];
}
else
System.err.println(
XSLMessages.createMessage(
XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
new Object[]{ "-FLAVOR" })); //"Missing argument for);
}
else if ("-PARAM".equalsIgnoreCase(argv[i]))
{
if (i + 2 < argv.length)
{
String name = argv[++i];
params.addElement(name);
String expression = argv[++i];
params.addElement(expression);
}
else
System.err.println(
XSLMessages.createMessage(
XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
new Object[]{ "-PARAM" })); //"Missing argument for);
}
else if ("-E".equalsIgnoreCase(argv[i]))
{
// TBD:
// xmlProcessorLiaison.setShouldExpandEntityRefs(false);
}
else if ("-V".equalsIgnoreCase(argv[i]))
{
diagnosticsWriter.println(resbundle.getString("version") //">>>>>>> Xalan Version "
+ Version.getVersion() + ", " +
/* xmlProcessorLiaison.getParserDescription()+ */
resbundle.getString("version2")); // "<<<<<<<");
}
else if ("-QC".equalsIgnoreCase(argv[i]))
{
if (!useXSLTC)
quietConflictWarnings = true;
else
printInvalidXSLTCOption("-QC");
}
else if ("-Q".equalsIgnoreCase(argv[i]))
{
setQuietMode = true;
}
else if ("-DIAG".equalsIgnoreCase(argv[i]))
{
doDiag = true;
}
else if ("-XML".equalsIgnoreCase(argv[i]))
{
outputType = "xml";
}
else if ("-TEXT".equalsIgnoreCase(argv[i]))
{
outputType = "text";
}
else if ("-HTML".equalsIgnoreCase(argv[i]))
{
outputType = "html";
}
else if ("-EDUMP".equalsIgnoreCase(argv[i]))
{
doStackDumpOnError = true;
if (((i + 1) < argv.length) && (argv[i + 1].charAt(0) != '-'))
{
dumpFileName = argv[++i];
}
}
else if ("-URIRESOLVER".equalsIgnoreCase(argv[i]))
{
if (i + 1 < argv.length)
{
try
{
uriResolver = (URIResolver) ObjectFactory.newInstance(
argv[++i], ObjectFactory.findClassLoader(), true);
tfactory.setURIResolver(uriResolver);
}
catch (ObjectFactory.ConfigurationError cnfe)
{
msg = XSLMessages.createMessage(
XSLTErrorResources.ER_CLASS_NOT_FOUND_FOR_OPTION,
new Object[]{ "-URIResolver" });
System.err.println(msg);
doExit(msg);
}
}
else
{
msg = XSLMessages.createMessage(
XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
new Object[]{ "-URIResolver" }); //"Missing argument for);
System.err.println(msg);
doExit(msg);
}
}
else if ("-ENTITYRESOLVER".equalsIgnoreCase(argv[i]))
{
if (i + 1 < argv.length)
{
try
{
entityResolver = (EntityResolver) ObjectFactory.newInstance(
argv[++i], ObjectFactory.findClassLoader(), true);
}
catch (ObjectFactory.ConfigurationError cnfe)
{
msg = XSLMessages.createMessage(
XSLTErrorResources.ER_CLASS_NOT_FOUND_FOR_OPTION,
new Object[]{ "-EntityResolver" });
System.err.println(msg);
doExit(msg);
}
}
else
{
// "Missing argument for);
msg = XSLMessages.createMessage(
XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
new Object[]{ "-EntityResolver" });
System.err.println(msg);
doExit(msg);
}
}
else if ("-CONTENTHANDLER".equalsIgnoreCase(argv[i]))
{
if (i + 1 < argv.length)
{
try
{
contentHandler = (ContentHandler) ObjectFactory.newInstance(
argv[++i], ObjectFactory.findClassLoader(), true);
}
catch (ObjectFactory.ConfigurationError cnfe)
{
msg = XSLMessages.createMessage(
XSLTErrorResources.ER_CLASS_NOT_FOUND_FOR_OPTION,
new Object[]{ "-ContentHandler" });
System.err.println(msg);
doExit(msg);
}
}
else
{
// "Missing argument for);
msg = XSLMessages.createMessage(
XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
new Object[]{ "-ContentHandler" });
System.err.println(msg);
doExit(msg);
}
}
else if ("-L".equalsIgnoreCase(argv[i]))
{
if (!useXSLTC)
tfactory.setAttribute(XalanProperties.SOURCE_LOCATION, Boolean.TRUE);
else
printInvalidXSLTCOption("-L");
}
else if ("-INCREMENTAL".equalsIgnoreCase(argv[i]))
{
if (!useXSLTC)
tfactory.setAttribute
("http://xml.apache.org/xalan/features/incremental",
java.lang.Boolean.TRUE);
else
printInvalidXSLTCOption("-INCREMENTAL");
}
else if ("-NOOPTIMIZE".equalsIgnoreCase(argv[i]))
{
// Default is true.
//
// %REVIEW% We should have a generalized syntax for negative
// switches... and probably should accept the inverse even
// if it is the default.
if (!useXSLTC)
tfactory.setAttribute
("http://xml.apache.org/xalan/features/optimize",
java.lang.Boolean.FALSE);
else
printInvalidXSLTCOption("-NOOPTIMIZE");
}
else if ("-RL".equalsIgnoreCase(argv[i]))
{
if (!useXSLTC)
{
if (i + 1 < argv.length)
recursionLimit = Integer.parseInt(argv[++i]);
else
System.err.println(
XSLMessages.createMessage(
XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
new Object[]{ "-rl" })); //"Missing argument for);
}
else
{
if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-')
i++;
printInvalidXSLTCOption("-RL");
}
}
// Generate the translet class and optionally specify the name
// of the translet class.
else if ("-XO".equalsIgnoreCase(argv[i]))
{
if (useXSLTC)
{
if (i + 1 < argv.length && argv[i+1].charAt(0) != '-')
{
tfactory.setAttribute("generate-translet", "true");
tfactory.setAttribute("translet-name", argv[++i]);
}
else
tfactory.setAttribute("generate-translet", "true");
}
else
{
if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-')
i++;
printInvalidXalanOption("-XO");
}
}
// Specify the destination directory for the translet classes.
else if ("-XD".equalsIgnoreCase(argv[i]))
{
if (useXSLTC)
{
if (i + 1 < argv.length && argv[i+1].charAt(0) != '-')
tfactory.setAttribute("destination-directory", argv[++i]);
else
System.err.println(
XSLMessages.createMessage(
XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
new Object[]{ "-XD" })); //"Missing argument for);
}
else
{
if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-')
i++;
printInvalidXalanOption("-XD");
}
}
// Specify the jar file name which the translet classes are packaged into.
else if ("-XJ".equalsIgnoreCase(argv[i]))
{
if (useXSLTC)
{
if (i + 1 < argv.length && argv[i+1].charAt(0) != '-')
{
tfactory.setAttribute("generate-translet", "true");
tfactory.setAttribute("jar-name", argv[++i]);
}
else
System.err.println(
XSLMessages.createMessage(
XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
new Object[]{ "-XJ" })); //"Missing argument for);
}
else
{
if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-')
i++;
printInvalidXalanOption("-XJ");
}
}
// Specify the package name prefix for the generated translet classes.
else if ("-XP".equalsIgnoreCase(argv[i]))
{
if (useXSLTC)
{
if (i + 1 < argv.length && argv[i+1].charAt(0) != '-')
tfactory.setAttribute("package-name", argv[++i]);
else
System.err.println(
XSLMessages.createMessage(
XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
new Object[]{ "-XP" })); //"Missing argument for);
}
else
{
if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-')
i++;
printInvalidXalanOption("-XP");
}
}
// Enable template inlining.
else if ("-XN".equalsIgnoreCase(argv[i]))
{
if (useXSLTC)
{
tfactory.setAttribute("enable-inlining", "true");
}
else
printInvalidXalanOption("-XN");
}
// Turns on additional debugging message output
else if ("-XX".equalsIgnoreCase(argv[i]))
{
if (useXSLTC)
{
tfactory.setAttribute("debug", "true");
}
else
printInvalidXalanOption("-XX");
}
// Create the Transformer from the translet if the translet class is newer
// than the stylesheet.
else if ("-XT".equalsIgnoreCase(argv[i]))
{
if (useXSLTC)
{
tfactory.setAttribute("auto-translet", "true");
}
else
printInvalidXalanOption("-XT");
}
else if ("-SECURE".equalsIgnoreCase(argv[i]))
{
isSecureProcessing = true;
try
{
tfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
}
catch (TransformerConfigurationException e) {}
}
else
System.err.println(
XSLMessages.createMessage(
XSLTErrorResources.ER_INVALID_OPTION, new Object[]{ argv[i] })); //"Invalid argument:);
}
// Print usage instructions if no xml and xsl file is specified in the command line
if (inFileName == null && xslFileName == null)
{
msg = resbundle.getString("xslProc_no_input");
System.err.println(msg);
doExit(msg);
}
// Note that there are usage cases for calling us without a -IN arg
// The main XSL transformation occurs here!
try
{
long start = System.currentTimeMillis();
if (null != dumpFileName)
{
dumpWriter = new PrintWriter(new FileWriter(dumpFileName));
}
Templates stylesheet = null;
if (null != xslFileName)
{
if (flavor.equals("d2d"))
{
// Parse in the xml data into a DOM
DocumentBuilderFactory dfactory =
DocumentBuilderFactory.newInstance();
dfactory.setNamespaceAware(true);
if (isSecureProcessing)
{
try
{
dfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
}
catch (ParserConfigurationException pce) {}
}
DocumentBuilder docBuilder = dfactory.newDocumentBuilder();
Node xslDOM = docBuilder.parse(new InputSource(xslFileName));
stylesheet = tfactory.newTemplates(new DOMSource(xslDOM,
xslFileName));
}
else
{
// System.out.println("Calling newTemplates: "+xslFileName);
stylesheet = tfactory.newTemplates(new StreamSource(xslFileName));
// System.out.println("Done calling newTemplates: "+xslFileName);
}
}
PrintWriter resultWriter;
StreamResult strResult;
if (null != outFileName)
{
strResult = new StreamResult(new FileOutputStream(outFileName));
// One possible improvement might be to ensure this is
// a valid URI before setting the systemId, but that
// might have subtle changes that pre-existing users
// might notice; we can think about that later -sc r1.46
strResult.setSystemId(outFileName);
}
else
{
strResult = new StreamResult(System.out);
// We used to default to incremental mode in this case.
// We've since decided that since the -INCREMENTAL switch is
// available, that default is probably not necessary nor
// necessarily a good idea.
}
SAXTransformerFactory stf = (SAXTransformerFactory) tfactory;
// This is currently controlled via TransformerFactoryImpl.
if (!useXSLTC && useSourceLocation)
stf.setAttribute(XalanProperties.SOURCE_LOCATION, Boolean.TRUE);
// Did they pass in a stylesheet, or should we get it from the
// document?
if (null == stylesheet)
{
Source source =
stf.getAssociatedStylesheet(new StreamSource(inFileName), media,
null, null);
if (null != source)
stylesheet = tfactory.newTemplates(source);
else
{
if (null != media)
throw new TransformerException(XSLMessages.createMessage(XSLTErrorResources.ER_NO_STYLESHEET_IN_MEDIA, new Object[]{inFileName, media})); //"No stylesheet found in: "
// + inFileName + ", media="
// + media);
else
throw new TransformerException(XSLMessages.createMessage(XSLTErrorResources.ER_NO_STYLESHEET_PI, new Object[]{inFileName})); //"No xml-stylesheet PI found in: "
//+ inFileName);
}
}
if (null != stylesheet)
{
Transformer transformer = flavor.equals("th") ? null : stylesheet.newTransformer();
transformer.setErrorListener(new DefaultErrorHandler(false));
// Override the output format?
if (null != outputType)
{
transformer.setOutputProperty(OutputKeys.METHOD, outputType);
}
if (transformer instanceof org.apache.xalan.transformer.TransformerImpl)
{
org.apache.xalan.transformer.TransformerImpl impl = (org.apache.xalan.transformer.TransformerImpl)transformer;
TraceManager tm = impl.getTraceManager();
if (null != tracer)
tm.addTraceListener(tracer);
impl.setQuietConflictWarnings(quietConflictWarnings);
// This is currently controlled via TransformerFactoryImpl.
if (useSourceLocation)
impl.setProperty(XalanProperties.SOURCE_LOCATION, Boolean.TRUE);
if(recursionLimit>0)
impl.setRecursionLimit(recursionLimit);
// sc 28-Feb-01 if we re-implement this, please uncomment helpmsg in printArgOptions
// impl.setDiagnosticsOutput( setQuietMode ? null : diagnosticsWriter );
}
int nParams = params.size();
for (int i = 0; i < nParams; i += 2)
{
transformer.setParameter((String) params.elementAt(i),
(String) params.elementAt(i + 1));
}
if (uriResolver != null)
transformer.setURIResolver(uriResolver);
if (null != inFileName)
{
if (flavor.equals("d2d"))
{
// Parse in the xml data into a DOM
DocumentBuilderFactory dfactory =
DocumentBuilderFactory.newInstance();
dfactory.setCoalescing(true);
dfactory.setNamespaceAware(true);
if (isSecureProcessing)
{
try
{
dfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
}
catch (ParserConfigurationException pce) {}
}
DocumentBuilder docBuilder = dfactory.newDocumentBuilder();
if (entityResolver != null)
docBuilder.setEntityResolver(entityResolver);
Node xmlDoc = docBuilder.parse(new InputSource(inFileName));
Document doc = docBuilder.newDocument();
org.w3c.dom.DocumentFragment outNode =
doc.createDocumentFragment();
transformer.transform(new DOMSource(xmlDoc, inFileName),
new DOMResult(outNode));
// Now serialize output to disk with identity transformer
Transformer serializer = stf.newTransformer();
serializer.setErrorListener(new DefaultErrorHandler(false));
Properties serializationProps =
stylesheet.getOutputProperties();
serializer.setOutputProperties(serializationProps);
if (contentHandler != null)
{
SAXResult result = new SAXResult(contentHandler);
serializer.transform(new DOMSource(outNode), result);
}
else
serializer.transform(new DOMSource(outNode), strResult);
}
else if (flavor.equals("th"))
{
for (int i = 0; i < 1; i++) // Loop for diagnosing bugs with inconsistent behavior
{
// System.out.println("Testing the TransformerHandler...");
// ===============
XMLReader reader = null;
// Use JAXP1.1 ( if possible )
try
{
javax.xml.parsers.SAXParserFactory factory =
javax.xml.parsers.SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
if (isSecureProcessing)
{
try
{
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
}
catch (org.xml.sax.SAXException se) {}
}
javax.xml.parsers.SAXParser jaxpParser =
factory.newSAXParser();
reader = jaxpParser.getXMLReader();
}
catch (javax.xml.parsers.ParserConfigurationException ex)
{
throw new org.xml.sax.SAXException(ex);
}
catch (javax.xml.parsers.FactoryConfigurationError ex1)
{
throw new org.xml.sax.SAXException(ex1.toString());
}
catch (NoSuchMethodError ex2){}
catch (AbstractMethodError ame){}
if (null == reader)
{
reader = XMLReaderFactory.createXMLReader();
}
if (!useXSLTC)
stf.setAttribute(org.apache.xalan.processor.TransformerFactoryImpl.FEATURE_INCREMENTAL,
Boolean.TRUE);
TransformerHandler th = stf.newTransformerHandler(stylesheet);
reader.setContentHandler(th);
reader.setDTDHandler(th);
if(th instanceof org.xml.sax.ErrorHandler)
reader.setErrorHandler((org.xml.sax.ErrorHandler)th);
try
{
reader.setProperty(
"http://xml.org/sax/properties/lexical-handler", th);
}
catch (org.xml.sax.SAXNotRecognizedException e){}
catch (org.xml.sax.SAXNotSupportedException e){}
try
{
reader.setFeature("http://xml.org/sax/features/namespace-prefixes",
true);
} catch (org.xml.sax.SAXException se) {}
th.setResult(strResult);
reader.parse(new InputSource(inFileName));
}
}
else
{
if (entityResolver != null)
{
XMLReader reader = null;
// Use JAXP1.1 ( if possible )
try
{
javax.xml.parsers.SAXParserFactory factory =
javax.xml.parsers.SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
if (isSecureProcessing)
{
try
{
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
}
catch (org.xml.sax.SAXException se) {}
}
javax.xml.parsers.SAXParser jaxpParser =
factory.newSAXParser();
reader = jaxpParser.getXMLReader();
}
catch (javax.xml.parsers.ParserConfigurationException ex)
{
throw new org.xml.sax.SAXException(ex);
}
catch (javax.xml.parsers.FactoryConfigurationError ex1)
{
throw new org.xml.sax.SAXException(ex1.toString());
}
catch (NoSuchMethodError ex2){}
catch (AbstractMethodError ame){}
if (null == reader)
{
reader = XMLReaderFactory.createXMLReader();
}
reader.setEntityResolver(entityResolver);
if (contentHandler != null)
{
SAXResult result = new SAXResult(contentHandler);
transformer.transform(
new SAXSource(reader, new InputSource(inFileName)),
result);
}
else
{
transformer.transform(
new SAXSource(reader, new InputSource(inFileName)),
strResult);
}
}
else if (contentHandler != null)
{
SAXResult result = new SAXResult(contentHandler);
transformer.transform(new StreamSource(inFileName), result);
}
else
{
// System.out.println("Starting transform");
transformer.transform(new StreamSource(inFileName),
strResult);
// System.out.println("Done with transform");
}
}
}
else
{
StringReader reader =
new StringReader("<?xml version=\"1.0\"?> <doc/>");
transformer.transform(new StreamSource(reader), strResult);
}
}
else
{
// "XSL Process was not successful.");
msg = XSLMessages.createMessage(
XSLTErrorResources.ER_NOT_SUCCESSFUL, null);
diagnosticsWriter.println(msg);
doExit(msg);
}
// close output streams
if (null != outFileName && strResult!=null)
{
java.io.OutputStream out = strResult.getOutputStream();
java.io.Writer writer = strResult.getWriter();
try
{
if (out != null) out.close();
if (writer != null) writer.close();
}
catch(java.io.IOException ie) {}
}
long stop = System.currentTimeMillis();
long millisecondsDuration = stop - start;
if (doDiag)
{
Object[] msgArgs = new Object[]{ inFileName, xslFileName, new Long(millisecondsDuration) };
msg = XSLMessages.createMessage("diagTiming", msgArgs);
diagnosticsWriter.println('\n');
diagnosticsWriter.println(msg);
}
}
catch (Throwable throwable)
{
while (throwable
instanceof org.apache.xml.utils.WrappedRuntimeException)
{
throwable =
((org.apache.xml.utils.WrappedRuntimeException) throwable).getException();
}
if ((throwable instanceof NullPointerException)
|| (throwable instanceof ClassCastException))
doStackDumpOnError = true;
diagnosticsWriter.println();
if (doStackDumpOnError)
throwable.printStackTrace(dumpWriter);
else
{
DefaultErrorHandler.printLocation(diagnosticsWriter, throwable);
diagnosticsWriter.println(
XSLMessages.createMessage(XSLTErrorResources.ER_XSLT_ERROR, null)
+ " (" + throwable.getClass().getName() + "): "
+ throwable.getMessage());
}
// diagnosticsWriter.println(XSLMessages.createMessage(XSLTErrorResources.ER_NOT_SUCCESSFUL, null)); //"XSL Process was not successful.");
if (null != dumpFileName)
{
dumpWriter.close();
}
doExit(throwable.getMessage());
}
if (null != dumpFileName)
{
dumpWriter.close();
}
if (null != diagnosticsWriter)
{
// diagnosticsWriter.close();
}
// if(!setQuietMode)
// diagnosticsWriter.println(resbundle.getString("xsldone")); //"Xalan: done");
// else
// diagnosticsWriter.println(""); //"Xalan: done");
}
}
/** It is _much_ easier to debug under VJ++ if I can set a single breakpoint
* before this blows itself out of the water...
* (I keep checking this in, it keeps vanishing. Grr!)
* */
static void doExit(String msg)
{
throw new RuntimeException(msg);
}
/**
* Wait for a return key to continue
*
* @param resbundle The resource bundle
*/
private static void waitForReturnKey(ResourceBundle resbundle)
{
System.out.println(resbundle.getString("xslProc_return_to_continue"));
try
{
while (System.in.read() != '\n');
}
catch (java.io.IOException e) { }
}
/**
* Print a message if an option cannot be used with -XSLTC.
*
* @param option The option String
*/
private static void printInvalidXSLTCOption(String option)
{
System.err.println(XSLMessages.createMessage("xslProc_invalid_xsltc_option", new Object[]{option}));
}
/**
* Print a message if an option can only be used with -XSLTC.
*
* @param option The option String
*/
private static void printInvalidXalanOption(String option)
{
System.err.println(XSLMessages.createMessage("xslProc_invalid_xalan_option", new Object[]{option}));
}
}
|
diff --git a/src/main/java/org/glite/authz/pap/distribution/DistributionConfiguration.java b/src/main/java/org/glite/authz/pap/distribution/DistributionConfiguration.java
index 468b569..87e64e1 100644
--- a/src/main/java/org/glite/authz/pap/distribution/DistributionConfiguration.java
+++ b/src/main/java/org/glite/authz/pap/distribution/DistributionConfiguration.java
@@ -1,293 +1,295 @@
package org.glite.authz.pap.distribution;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import org.glite.authz.pap.common.PAP;
import org.glite.authz.pap.common.PAPConfiguration;
import org.glite.authz.pap.distribution.exceptions.AliasNotFoundException;
import org.glite.authz.pap.distribution.exceptions.DistributionConfigurationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class DistributionConfiguration {
private static final String CONFIGURATION_STANZA = "distribution-configuration";
private static DistributionConfiguration instance = null;
private static final Logger log = LoggerFactory.getLogger(DistributionConfiguration.class);
private static final String REMOTE_PAPS_STANZA = "remote-paps";
public static DistributionConfiguration getInstance() {
if (instance == null)
instance = new DistributionConfiguration();
return instance;
}
private static String aliasKey(String papAlias) {
return REMOTE_PAPS_STANZA + "." + papAlias;
}
private static String dnKey(String papAlias) {
return aliasKey(papAlias) + "." + "dn";
}
private static String hostnameKey(String papAlias) {
return aliasKey(papAlias) + "." + "hostname";
}
private static String minKeyLengthKey() {
return CONFIGURATION_STANZA + "." + "min-key-length";
}
private static String minKeyLengthKey(String papAlias) {
return aliasKey(papAlias) + "." + "min-key-length";
}
private static String papOrderKey() {
return CONFIGURATION_STANZA + "." + "pap-order";
}
private static String pathKey(String papAlias) {
return aliasKey(papAlias) + "." + "path";
}
private static String pollIntervallKey() {
return CONFIGURATION_STANZA + "." + "poll-interval";
}
private static String portKey(String papAlias) {
return aliasKey(papAlias) + "." + "port";
}
private static String protocolKey(String papAlias) {
return aliasKey(papAlias) + "." + "protocol";
}
private static String visibilityPublicKey(String papAlias) {
return aliasKey(papAlias) + "." + "public";
}
private PAPConfiguration papConfiguration;
public DistributionConfiguration() {
papConfiguration = PAPConfiguration.instance();
}
public String[] getPAPOrderArray() throws AliasNotFoundException {
String[] papOrderArray = papConfiguration.getStringArray(papOrderKey());
if (papOrderArray == null)
papOrderArray = new String[0];
for (String alias : papOrderArray) {
if (!aliasExists(alias))
throw new DistributionConfigurationException(
"Undefined PAP alias \"" + alias + "\" in \"pap-order\"");
}
return papOrderArray;
}
public long getPollIntervallInMilliSecs() {
long pollIntervalInSecs = papConfiguration.getLong(pollIntervallKey());
log.info("Polling interval for remote PAPs is set to: " + pollIntervalInSecs + " seconds");
return pollIntervalInSecs * 1000;
}
public List<PAP> getRemotePAPList() {
List<String> aliasList = getAliasList();
if (aliasList.isEmpty())
log.info("No remote PAPs has been defined");
List<PAP> papList = new LinkedList<PAP>();
for (String papAlias : aliasList) {
PAP pap = getPAPFromProperties(papAlias);
log.info("Adding remote PAP: " + pap);
papList.add(pap);
}
return papList;
}
public void removePAP(String papAlias) {
String[] oldAliasOrderArray = getPAPOrderArray();
int newArraySize = oldAliasOrderArray.length - 1;
String[] newAliasOrderArray = new String[newArraySize];
for (int i = 0, j = 0; i < oldAliasOrderArray.length; i++) {
String aliasItem = oldAliasOrderArray[i];
if (!(aliasItem.equals(papAlias))) {
if (j < newArraySize) {
newAliasOrderArray[j] = aliasItem;
j++;
}
}
}
clearPAPProperties(papAlias);
savePAPOrder(newAliasOrderArray);
papConfiguration.saveStartupConfiguration();
}
public void savePAP(PAP pap) {
setPAPProperties(pap);
papConfiguration.saveStartupConfiguration();
}
public void savePAPOrder(String[] aliasArray) throws AliasNotFoundException {
- papConfiguration.clearDistributionProperty(papOrderKey());
if (aliasArray == null) {
+ papConfiguration.clearDistributionProperty(papOrderKey());
papConfiguration.saveStartupConfiguration();
return;
}
if (aliasArray.length == 0) {
+ papConfiguration.clearDistributionProperty(papOrderKey());
papConfiguration.saveStartupConfiguration();
return;
}
if (!aliasExists(aliasArray[0]))
throw new AliasNotFoundException("Unknown alias \"" + aliasArray[0] + "\"");
StringBuilder sb = new StringBuilder(aliasArray[0]);
for (int i=1; i<aliasArray.length; i++) {
if (!aliasExists(aliasArray[i]))
throw new AliasNotFoundException("Unknown alias \"" + aliasArray[i] + "\"");
sb.append(", " + aliasArray[i]);
}
log.info("Setting new PAP order to: " + sb.toString());
+ papConfiguration.clearDistributionProperty(papOrderKey());
papConfiguration.setDistributionProperty(papOrderKey(), aliasArray);
papConfiguration.saveStartupConfiguration();
}
private void clearPAPProperties(String papAlias) {
papConfiguration.clearDistributionProperty(dnKey(papAlias));
papConfiguration.clearDistributionProperty(hostnameKey(papAlias));
papConfiguration.clearDistributionProperty(portKey(papAlias));
papConfiguration.clearDistributionProperty(pathKey(papAlias));
papConfiguration.clearDistributionProperty(protocolKey(papAlias));
papConfiguration.clearDistributionProperty(visibilityPublicKey(papAlias));
}
private List<String> getAliasList() throws AliasNotFoundException {
Set<String> aliasSet = getAliasSet();
List<String> aliasList = new ArrayList<String>(aliasSet.size());
// get an ordered list of PAP aliases
String[] aliasOrderArray = getPAPOrderArray();
for (String alias : aliasOrderArray) {
if (aliasSet.remove(alias)) {
aliasList.add(alias);
} else {
throw new AliasNotFoundException("BUG alias not found: \"" + alias + "\"");
}
}
// order can be partially defined so get the remaining aliases
for (String alias : aliasSet) {
aliasList.add(alias);
}
return aliasList;
}
@SuppressWarnings("unchecked")
private Set<String> getAliasSet() {
Set<String> aliasSet = new HashSet<String>();
Iterator iterator = papConfiguration.getKeys(REMOTE_PAPS_STANZA);
while (iterator.hasNext()) {
String key = (String) iterator.next();
int firstAliasChar = key.indexOf('.') + 1;
int lastAliasChar = key.indexOf('.', firstAliasChar);
String alias = key.substring(firstAliasChar, lastAliasChar);
aliasSet.add(alias);
}
return aliasSet;
}
private PAP getPAPFromProperties(String papAlias) {
String dn = papConfiguration.getString(dnKey(papAlias));
if (dn == null) {
throw new DistributionConfigurationException("DN is not set for remote PAP \""
+ papAlias + "\"");
}
String hostname = papConfiguration.getString(hostnameKey(papAlias));
if (hostname == null)
throw new DistributionConfigurationException("Hostname is not set for remote PAP \""
+ papAlias + "\"");
String port = papConfiguration.getString(portKey(papAlias));
String path = papConfiguration.getString(pathKey(papAlias));
String protocol = papConfiguration.getString(protocolKey(papAlias));
boolean visibilityPublic = papConfiguration.getBoolean(visibilityPublicKey(papAlias));
// port, path and protocol can be null or empty
return new PAP(papAlias, dn, hostname, port, path, protocol, visibilityPublic);
}
private boolean isEmpty(String s) {
if (s == null)
return true;
if (s.length() == 0)
return true;
return false;
}
private boolean aliasExists(String alias) {
if (isEmpty(alias))
return false;
String value = papConfiguration.getString(dnKey(alias));
if (isEmpty(value))
return false;
return true;
}
private void setPAPProperties(PAP pap) {
String papAlias = pap.getAlias();
papConfiguration.setDistributionProperty(dnKey(papAlias), pap.getDn());
papConfiguration.setDistributionProperty(hostnameKey(papAlias), pap.getHostname());
papConfiguration.setDistributionProperty(portKey(papAlias), pap.getPort());
papConfiguration.setDistributionProperty(pathKey(papAlias), pap.getPath());
papConfiguration.setDistributionProperty(protocolKey(papAlias), pap.getProtocol());
papConfiguration.setDistributionProperty(visibilityPublicKey(papAlias), pap.isVisibilityPublic());
}
}
| false | true | public void savePAPOrder(String[] aliasArray) throws AliasNotFoundException {
papConfiguration.clearDistributionProperty(papOrderKey());
if (aliasArray == null) {
papConfiguration.saveStartupConfiguration();
return;
}
if (aliasArray.length == 0) {
papConfiguration.saveStartupConfiguration();
return;
}
if (!aliasExists(aliasArray[0]))
throw new AliasNotFoundException("Unknown alias \"" + aliasArray[0] + "\"");
StringBuilder sb = new StringBuilder(aliasArray[0]);
for (int i=1; i<aliasArray.length; i++) {
if (!aliasExists(aliasArray[i]))
throw new AliasNotFoundException("Unknown alias \"" + aliasArray[i] + "\"");
sb.append(", " + aliasArray[i]);
}
log.info("Setting new PAP order to: " + sb.toString());
papConfiguration.setDistributionProperty(papOrderKey(), aliasArray);
papConfiguration.saveStartupConfiguration();
}
| public void savePAPOrder(String[] aliasArray) throws AliasNotFoundException {
if (aliasArray == null) {
papConfiguration.clearDistributionProperty(papOrderKey());
papConfiguration.saveStartupConfiguration();
return;
}
if (aliasArray.length == 0) {
papConfiguration.clearDistributionProperty(papOrderKey());
papConfiguration.saveStartupConfiguration();
return;
}
if (!aliasExists(aliasArray[0]))
throw new AliasNotFoundException("Unknown alias \"" + aliasArray[0] + "\"");
StringBuilder sb = new StringBuilder(aliasArray[0]);
for (int i=1; i<aliasArray.length; i++) {
if (!aliasExists(aliasArray[i]))
throw new AliasNotFoundException("Unknown alias \"" + aliasArray[i] + "\"");
sb.append(", " + aliasArray[i]);
}
log.info("Setting new PAP order to: " + sb.toString());
papConfiguration.clearDistributionProperty(papOrderKey());
papConfiguration.setDistributionProperty(papOrderKey(), aliasArray);
papConfiguration.saveStartupConfiguration();
}
|
diff --git a/application/src/main/java/org/richfaces/tests/metamer/bean/RichInputNumberSpinnerBean.java b/application/src/main/java/org/richfaces/tests/metamer/bean/RichInputNumberSpinnerBean.java
index 5dc5d74b..9b2e0351 100644
--- a/application/src/main/java/org/richfaces/tests/metamer/bean/RichInputNumberSpinnerBean.java
+++ b/application/src/main/java/org/richfaces/tests/metamer/bean/RichInputNumberSpinnerBean.java
@@ -1,78 +1,77 @@
/*******************************************************************************
* JBoss, Home of Professional Open Source
* Copyright 2010-2011, Red Hat, Inc. and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*******************************************************************************/
package org.richfaces.tests.metamer.bean;
import java.io.Serializable;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import org.richfaces.component.html.HtmlInputNumberSpinner;
import org.richfaces.tests.metamer.Attributes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Managed bean for rich:inputNumberSpinner.
*
* @author <a href="mailto:[email protected]">Pavol Pitonak</a>
* @version $Revision$
*/
@ManagedBean(name = "richInputNumberSpinnerBean")
@ViewScoped
public class RichInputNumberSpinnerBean implements Serializable {
private static final long serialVersionUID = -1L;
private static Logger logger;
private Attributes attributes;
/**
* Initializes the managed bean.
*/
@PostConstruct
public void init() {
logger = LoggerFactory.getLogger(getClass());
logger.debug("initializing bean " + getClass().getName());
attributes = Attributes.getComponentAttributesFromFacesConfig(HtmlInputNumberSpinner.class, getClass());
attributes.setAttribute("enableManualInput", true);
attributes.setAttribute("maxValue", 10);
attributes.setAttribute("minValue", -10);
attributes.setAttribute("rendered", true);
- attributes.get("rendered").setType(boolean.class);
attributes.setAttribute("step", 1);
attributes.setAttribute("value", 2);
// will be tested in another way
attributes.remove("valueChangeListener");
}
public Attributes getAttributes() {
return attributes;
}
public void setAttributes(Attributes attributes) {
this.attributes = attributes;
}
}
| true | true | public void init() {
logger = LoggerFactory.getLogger(getClass());
logger.debug("initializing bean " + getClass().getName());
attributes = Attributes.getComponentAttributesFromFacesConfig(HtmlInputNumberSpinner.class, getClass());
attributes.setAttribute("enableManualInput", true);
attributes.setAttribute("maxValue", 10);
attributes.setAttribute("minValue", -10);
attributes.setAttribute("rendered", true);
attributes.get("rendered").setType(boolean.class);
attributes.setAttribute("step", 1);
attributes.setAttribute("value", 2);
// will be tested in another way
attributes.remove("valueChangeListener");
}
| public void init() {
logger = LoggerFactory.getLogger(getClass());
logger.debug("initializing bean " + getClass().getName());
attributes = Attributes.getComponentAttributesFromFacesConfig(HtmlInputNumberSpinner.class, getClass());
attributes.setAttribute("enableManualInput", true);
attributes.setAttribute("maxValue", 10);
attributes.setAttribute("minValue", -10);
attributes.setAttribute("rendered", true);
attributes.setAttribute("step", 1);
attributes.setAttribute("value", 2);
// will be tested in another way
attributes.remove("valueChangeListener");
}
|
diff --git a/src/test/webui/recipes/applications/TerminateServiceContainerLogsPanelTest.java b/src/test/webui/recipes/applications/TerminateServiceContainerLogsPanelTest.java
index c64046bf..d1ed2332 100644
--- a/src/test/webui/recipes/applications/TerminateServiceContainerLogsPanelTest.java
+++ b/src/test/webui/recipes/applications/TerminateServiceContainerLogsPanelTest.java
@@ -1,95 +1,95 @@
package test.webui.recipes.applications;
import java.io.IOException;
import org.openspaces.admin.gsc.GridServiceContainer;
import org.openspaces.admin.machine.Machine;
import org.openspaces.admin.pu.DeploymentStatus;
import org.openspaces.admin.pu.ProcessingUnit;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import framework.utils.AssertUtils;
import framework.utils.AssertUtils.RepetitiveConditionProvider;
import framework.utils.ProcessingUnitUtils;
import test.webui.objects.LoginPage;
import test.webui.objects.MainNavigation;
import test.webui.objects.services.HostsAndServicesGrid;
import test.webui.objects.services.ServicesTab;
import test.webui.objects.topology.TopologyTab;
import test.webui.objects.topology.applicationmap.ApplicationMap;
import test.webui.objects.topology.applicationmap.ApplicationNode;
import test.webui.objects.topology.logspanel.LogsMachine;
import test.webui.objects.topology.logspanel.LogsPanel;
import test.webui.objects.topology.logspanel.PuLogsPanelService;
import test.webui.resources.WebConstants;
public class TerminateServiceContainerLogsPanelTest extends AbstractSeleniumApplicationRecipeTest {
@Override
@BeforeMethod
public void install() throws IOException, InterruptedException {
setBrowser(WebConstants.CHROME);
setCurrentApplication("travel");
super.install();
}
@Test(timeOut = DEFAULT_TEST_TIMEOUT * 2)
public void terminateContainerTest() throws InterruptedException {
// get new login page
LoginPage loginPage = getLoginPage();
MainNavigation mainNav = loginPage.login();
TopologyTab topology = mainNav.switchToTopology();
ApplicationMap appMap = topology.getApplicationMap();
appMap.selectApplication("travel");
ApplicationNode travelNode = appMap.getApplicationNode("tomcat");
travelNode.select();
ProcessingUnit travelPu = admin.getProcessingUnits().getProcessingUnit("travel.tomcat");
final GridServiceContainer travelContainer = travelPu.getInstances()[0].getGridServiceContainer();
LogsPanel logsPanel = topology.getTopologySubPanel().switchToLogsPanel();
- PuLogsPanelService travelLogsService = logsPanel.getPuLogsPanelService("tomcat");
+ PuLogsPanelService travelLogsService = logsPanel.getPuLogsPanelService("travel.tomcat");
Machine localHost = travelContainer.getMachine();
final LogsMachine logsLocalHost = travelLogsService.getMachine(localHost.getHostName());
assertTrue(logsLocalHost.containsGridServiceContainer(travelContainer));
ServicesTab servicesTab = mainNav.switchToServices();
HostsAndServicesGrid hostAndServicesGrid = servicesTab.getHostAndServicesGrid();
hostAndServicesGrid.terminateGSC(travelContainer);
mainNav.switchToTopology();
travelNode.select();
ProcessingUnitUtils.waitForDeploymentStatus(travelPu, DeploymentStatus.SCHEDULED);
ProcessingUnitUtils.waitForDeploymentStatus(travelPu, DeploymentStatus.INTACT);
appMap.deselectAllNodes();
RepetitiveConditionProvider condition = new RepetitiveConditionProvider() {
@Override
public boolean getCondition() {
return (!logsLocalHost.containsGridServiceContainer(travelContainer));
}
};
AssertUtils.repetitiveAssertTrue("Container" + travelContainer.getAgentId() + "is still present", condition, waitingTime);
}
}
| true | true | public void terminateContainerTest() throws InterruptedException {
// get new login page
LoginPage loginPage = getLoginPage();
MainNavigation mainNav = loginPage.login();
TopologyTab topology = mainNav.switchToTopology();
ApplicationMap appMap = topology.getApplicationMap();
appMap.selectApplication("travel");
ApplicationNode travelNode = appMap.getApplicationNode("tomcat");
travelNode.select();
ProcessingUnit travelPu = admin.getProcessingUnits().getProcessingUnit("travel.tomcat");
final GridServiceContainer travelContainer = travelPu.getInstances()[0].getGridServiceContainer();
LogsPanel logsPanel = topology.getTopologySubPanel().switchToLogsPanel();
PuLogsPanelService travelLogsService = logsPanel.getPuLogsPanelService("tomcat");
Machine localHost = travelContainer.getMachine();
final LogsMachine logsLocalHost = travelLogsService.getMachine(localHost.getHostName());
assertTrue(logsLocalHost.containsGridServiceContainer(travelContainer));
ServicesTab servicesTab = mainNav.switchToServices();
HostsAndServicesGrid hostAndServicesGrid = servicesTab.getHostAndServicesGrid();
hostAndServicesGrid.terminateGSC(travelContainer);
mainNav.switchToTopology();
travelNode.select();
ProcessingUnitUtils.waitForDeploymentStatus(travelPu, DeploymentStatus.SCHEDULED);
ProcessingUnitUtils.waitForDeploymentStatus(travelPu, DeploymentStatus.INTACT);
appMap.deselectAllNodes();
RepetitiveConditionProvider condition = new RepetitiveConditionProvider() {
@Override
public boolean getCondition() {
return (!logsLocalHost.containsGridServiceContainer(travelContainer));
}
};
AssertUtils.repetitiveAssertTrue("Container" + travelContainer.getAgentId() + "is still present", condition, waitingTime);
}
| public void terminateContainerTest() throws InterruptedException {
// get new login page
LoginPage loginPage = getLoginPage();
MainNavigation mainNav = loginPage.login();
TopologyTab topology = mainNav.switchToTopology();
ApplicationMap appMap = topology.getApplicationMap();
appMap.selectApplication("travel");
ApplicationNode travelNode = appMap.getApplicationNode("tomcat");
travelNode.select();
ProcessingUnit travelPu = admin.getProcessingUnits().getProcessingUnit("travel.tomcat");
final GridServiceContainer travelContainer = travelPu.getInstances()[0].getGridServiceContainer();
LogsPanel logsPanel = topology.getTopologySubPanel().switchToLogsPanel();
PuLogsPanelService travelLogsService = logsPanel.getPuLogsPanelService("travel.tomcat");
Machine localHost = travelContainer.getMachine();
final LogsMachine logsLocalHost = travelLogsService.getMachine(localHost.getHostName());
assertTrue(logsLocalHost.containsGridServiceContainer(travelContainer));
ServicesTab servicesTab = mainNav.switchToServices();
HostsAndServicesGrid hostAndServicesGrid = servicesTab.getHostAndServicesGrid();
hostAndServicesGrid.terminateGSC(travelContainer);
mainNav.switchToTopology();
travelNode.select();
ProcessingUnitUtils.waitForDeploymentStatus(travelPu, DeploymentStatus.SCHEDULED);
ProcessingUnitUtils.waitForDeploymentStatus(travelPu, DeploymentStatus.INTACT);
appMap.deselectAllNodes();
RepetitiveConditionProvider condition = new RepetitiveConditionProvider() {
@Override
public boolean getCondition() {
return (!logsLocalHost.containsGridServiceContainer(travelContainer));
}
};
AssertUtils.repetitiveAssertTrue("Container" + travelContainer.getAgentId() + "is still present", condition, waitingTime);
}
|
diff --git a/common/test/java/org/openqa/selenium/browserlaunchers/WindowsUtilsUnitTest.java b/common/test/java/org/openqa/selenium/browserlaunchers/WindowsUtilsUnitTest.java
index 5f96ba000..fa48e1534 100644
--- a/common/test/java/org/openqa/selenium/browserlaunchers/WindowsUtilsUnitTest.java
+++ b/common/test/java/org/openqa/selenium/browserlaunchers/WindowsUtilsUnitTest.java
@@ -1,85 +1,85 @@
/*
* Copyright 2006 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.openqa.selenium.browserlaunchers;
import junit.framework.TestCase;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class WindowsUtilsUnitTest extends TestCase {
private int majorVersion;
private int minorVersion;
private Pattern WIN_OS_VERSION = Pattern.compile("^(\\d)+\\.(\\d)+$");
public void setUp() {
if (!WindowsUtils.thisIsWindows()) return;
String osVersion = System.getProperty("os.version");
Matcher m = WIN_OS_VERSION.matcher(osVersion);
if (!m.find()) fail("osVersion doesn't look right: " + osVersion);
majorVersion = Integer.parseInt(m.group(1));
minorVersion = Integer.parseInt(m.group(2));
}
private boolean isXpOrHigher() {
return majorVersion >= 5 && minorVersion >= 1;
}
public void testLoadEnvironment() {
if (!WindowsUtils.thisIsWindows()) return;
Map p =WindowsUtils.loadEnvironment();
assertFalse("Environment appears to be empty!", p.isEmpty());
assertNotNull("SystemRoot env var apparently not set on Windows!", WindowsUtils.findSystemRoot());
}
public void testWMIC() {
if (!WindowsUtils.thisIsWindows()) return;
if (!isXpOrHigher()) return;
assertTrue("wmic should be found", "wmic" != WindowsUtils.findWMIC());
}
public void testTaskKill() {
if (!WindowsUtils.thisIsWindows()) return;
if (!isXpOrHigher()) return;
assertTrue("taskkill should be found", "taskkill" != WindowsUtils.findTaskKill());
}
public void testRegistry() {
if (!WindowsUtils.thisIsWindows()) return;
//TODO(danielwh): Uncomment or remove assert
//String keyCurrentVersion = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\CurrentVersion";
String keyProxyEnable = "HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings\\ProxyEnable";
String keySeleniumFoo = "HKEY_CURRENT_USER\\Software\\Selenium\\RemoteControl\\foo";
- //assertTrue("Standard Windows reg key CurrentVersion doesn't exist", WindowsUtils.doesRegistryValueExist(keyCurrentVersion));
- //System.out.println("CurrentVersion: " + WindowsUtils.readStringRegistryValue(keyCurrentVersion));
- assertTrue("Standard Windows reg key ProxyEnable doesn't exist", WindowsUtils.doesRegistryValueExist(keyProxyEnable));
- System.out.println("ProxyEnable: " + WindowsUtils.readIntRegistryValue(keyProxyEnable));
+ assertTrue("Standard Windows reg key CurrentVersion doesn't exist", WindowsUtils.doesRegistryValueExist(keyCurrentVersion));
+ System.out.println("CurrentVersion: " + WindowsUtils.readStringRegistryValue(keyCurrentVersion));
+ //assertTrue("Standard Windows reg key ProxyEnable doesn't exist", WindowsUtils.doesRegistryValueExist(keyProxyEnable));
+ //System.out.println("ProxyEnable: " + WindowsUtils.readIntRegistryValue(keyProxyEnable));
WindowsUtils.writeStringRegistryValue(keySeleniumFoo, "bar");
assertEquals("Didn't set Foo string key correctly", "bar", WindowsUtils.readStringRegistryValue(keySeleniumFoo));
WindowsUtils.writeStringRegistryValue(keySeleniumFoo, "baz");
assertEquals("Didn't modify Foo string key correctly", "baz", WindowsUtils.readStringRegistryValue(keySeleniumFoo));
WindowsUtils.deleteRegistryValue(keySeleniumFoo);
assertFalse("Didn't delete Foo key correctly", WindowsUtils.doesRegistryValueExist(keySeleniumFoo));
WindowsUtils.writeBooleanRegistryValue(keySeleniumFoo, true);
assertTrue("Didn't set Foo boolean key correctly", WindowsUtils.readBooleanRegistryValue(keySeleniumFoo));
WindowsUtils.deleteRegistryValue(keySeleniumFoo);
assertFalse("Didn't delete Foo key correctly", WindowsUtils.doesRegistryValueExist(keySeleniumFoo));
}
public void testVersion1() {
if (!WindowsUtils.thisIsWindows()) return;
System.out.println("Version 1: " + WindowsUtils.isRegExeVersion1());
}
}
| true | true | public void testRegistry() {
if (!WindowsUtils.thisIsWindows()) return;
//TODO(danielwh): Uncomment or remove assert
//String keyCurrentVersion = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\CurrentVersion";
String keyProxyEnable = "HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings\\ProxyEnable";
String keySeleniumFoo = "HKEY_CURRENT_USER\\Software\\Selenium\\RemoteControl\\foo";
//assertTrue("Standard Windows reg key CurrentVersion doesn't exist", WindowsUtils.doesRegistryValueExist(keyCurrentVersion));
//System.out.println("CurrentVersion: " + WindowsUtils.readStringRegistryValue(keyCurrentVersion));
assertTrue("Standard Windows reg key ProxyEnable doesn't exist", WindowsUtils.doesRegistryValueExist(keyProxyEnable));
System.out.println("ProxyEnable: " + WindowsUtils.readIntRegistryValue(keyProxyEnable));
WindowsUtils.writeStringRegistryValue(keySeleniumFoo, "bar");
assertEquals("Didn't set Foo string key correctly", "bar", WindowsUtils.readStringRegistryValue(keySeleniumFoo));
WindowsUtils.writeStringRegistryValue(keySeleniumFoo, "baz");
assertEquals("Didn't modify Foo string key correctly", "baz", WindowsUtils.readStringRegistryValue(keySeleniumFoo));
WindowsUtils.deleteRegistryValue(keySeleniumFoo);
assertFalse("Didn't delete Foo key correctly", WindowsUtils.doesRegistryValueExist(keySeleniumFoo));
WindowsUtils.writeBooleanRegistryValue(keySeleniumFoo, true);
assertTrue("Didn't set Foo boolean key correctly", WindowsUtils.readBooleanRegistryValue(keySeleniumFoo));
WindowsUtils.deleteRegistryValue(keySeleniumFoo);
assertFalse("Didn't delete Foo key correctly", WindowsUtils.doesRegistryValueExist(keySeleniumFoo));
}
| public void testRegistry() {
if (!WindowsUtils.thisIsWindows()) return;
//TODO(danielwh): Uncomment or remove assert
//String keyCurrentVersion = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\CurrentVersion";
String keyProxyEnable = "HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings\\ProxyEnable";
String keySeleniumFoo = "HKEY_CURRENT_USER\\Software\\Selenium\\RemoteControl\\foo";
assertTrue("Standard Windows reg key CurrentVersion doesn't exist", WindowsUtils.doesRegistryValueExist(keyCurrentVersion));
System.out.println("CurrentVersion: " + WindowsUtils.readStringRegistryValue(keyCurrentVersion));
//assertTrue("Standard Windows reg key ProxyEnable doesn't exist", WindowsUtils.doesRegistryValueExist(keyProxyEnable));
//System.out.println("ProxyEnable: " + WindowsUtils.readIntRegistryValue(keyProxyEnable));
WindowsUtils.writeStringRegistryValue(keySeleniumFoo, "bar");
assertEquals("Didn't set Foo string key correctly", "bar", WindowsUtils.readStringRegistryValue(keySeleniumFoo));
WindowsUtils.writeStringRegistryValue(keySeleniumFoo, "baz");
assertEquals("Didn't modify Foo string key correctly", "baz", WindowsUtils.readStringRegistryValue(keySeleniumFoo));
WindowsUtils.deleteRegistryValue(keySeleniumFoo);
assertFalse("Didn't delete Foo key correctly", WindowsUtils.doesRegistryValueExist(keySeleniumFoo));
WindowsUtils.writeBooleanRegistryValue(keySeleniumFoo, true);
assertTrue("Didn't set Foo boolean key correctly", WindowsUtils.readBooleanRegistryValue(keySeleniumFoo));
WindowsUtils.deleteRegistryValue(keySeleniumFoo);
assertFalse("Didn't delete Foo key correctly", WindowsUtils.doesRegistryValueExist(keySeleniumFoo));
}
|
diff --git a/org.dawnsci.conversion/src/org/dawnsci/conversion/Activator.java b/org.dawnsci.conversion/src/org/dawnsci/conversion/Activator.java
index dd1c7596..298925d7 100644
--- a/org.dawnsci.conversion/src/org/dawnsci/conversion/Activator.java
+++ b/org.dawnsci.conversion/src/org/dawnsci/conversion/Activator.java
@@ -1,37 +1,37 @@
package org.dawnsci.conversion;
import java.util.Hashtable;
import org.dawb.common.services.IConversionService;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
public class Activator implements BundleActivator {
private static BundleContext context;
static BundleContext getContext() {
return context;
}
/*
* (non-Javadoc)
* @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext)
*/
public void start(BundleContext bundleContext) throws Exception {
- System.out.println("Starting org.dawnsci.persistence");
+ System.out.println("Starting "+bundleContext.getBundle().getSymbolicName());
Hashtable<String, String> props = new Hashtable<String, String>(1);
props.put("description", "A service used to convert hdf5 files");
- context.registerService(IConversionService.class, new ConversionServiceImpl(), props);
+ bundleContext.registerService(IConversionService.class, new ConversionServiceImpl(), props);
Activator.context = bundleContext;
}
/*
* (non-Javadoc)
* @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext)
*/
public void stop(BundleContext bundleContext) throws Exception {
Activator.context = null;
}
}
| false | true | public void start(BundleContext bundleContext) throws Exception {
System.out.println("Starting org.dawnsci.persistence");
Hashtable<String, String> props = new Hashtable<String, String>(1);
props.put("description", "A service used to convert hdf5 files");
context.registerService(IConversionService.class, new ConversionServiceImpl(), props);
Activator.context = bundleContext;
}
| public void start(BundleContext bundleContext) throws Exception {
System.out.println("Starting "+bundleContext.getBundle().getSymbolicName());
Hashtable<String, String> props = new Hashtable<String, String>(1);
props.put("description", "A service used to convert hdf5 files");
bundleContext.registerService(IConversionService.class, new ConversionServiceImpl(), props);
Activator.context = bundleContext;
}
|
diff --git a/src/com/android/launcher2/Launcher.java b/src/com/android/launcher2/Launcher.java
index 8c73c294..4ae9c7d2 100644
--- a/src/com/android/launcher2/Launcher.java
+++ b/src/com/android/launcher2/Launcher.java
@@ -1,3815 +1,3815 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.launcher2;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.animation.ValueAnimator;
import android.animation.ValueAnimator.AnimatorUpdateListener;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityOptions;
import android.app.SearchManager;
import android.appwidget.AppWidgetHostView;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProviderInfo;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.ComponentCallbacks2;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.database.ContentObserver;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.PorterDuff;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.os.SystemClock;
import android.provider.Settings;
import android.speech.RecognizerIntent;
import android.text.Selection;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.method.TextKeyListener;
import android.util.Log;
import android.view.Display;
import android.view.HapticFeedbackConstants;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.WindowManager;
import android.view.accessibility.AccessibilityEvent;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.view.inputmethod.InputMethodManager;
import android.widget.Advanceable;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.common.Search;
import com.android.launcher.R;
import com.android.launcher2.DropTarget.DragObject;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Default launcher application.
*/
public final class Launcher extends Activity
implements View.OnClickListener, OnLongClickListener, LauncherModel.Callbacks,
View.OnTouchListener {
static final String TAG = "Launcher";
static final boolean LOGD = false;
static final boolean PROFILE_STARTUP = false;
static final boolean DEBUG_WIDGETS = false;
static final boolean DEBUG_STRICT_MODE = false;
private static final int MENU_GROUP_WALLPAPER = 1;
private static final int MENU_WALLPAPER_SETTINGS = Menu.FIRST + 1;
private static final int MENU_MANAGE_APPS = MENU_WALLPAPER_SETTINGS + 1;
private static final int MENU_SYSTEM_SETTINGS = MENU_MANAGE_APPS + 1;
private static final int MENU_HELP = MENU_SYSTEM_SETTINGS + 1;
private static final int REQUEST_CREATE_SHORTCUT = 1;
private static final int REQUEST_CREATE_APPWIDGET = 5;
private static final int REQUEST_PICK_APPLICATION = 6;
private static final int REQUEST_PICK_SHORTCUT = 7;
private static final int REQUEST_PICK_APPWIDGET = 9;
private static final int REQUEST_PICK_WALLPAPER = 10;
private static final int REQUEST_BIND_APPWIDGET = 11;
static final String EXTRA_SHORTCUT_DUPLICATE = "duplicate";
static final int SCREEN_COUNT = 5;
static final int DEFAULT_SCREEN = 2;
private static final String PREFERENCES = "launcher.preferences";
static final String FORCE_ENABLE_ROTATION_PROPERTY = "debug.force_enable_rotation";
static final String DUMP_STATE_PROPERTY = "debug.dumpstate";
// The Intent extra that defines whether to ignore the launch animation
static final String INTENT_EXTRA_IGNORE_LAUNCH_ANIMATION =
"com.android.launcher.intent.extra.shortcut.INGORE_LAUNCH_ANIMATION";
// Type: int
private static final String RUNTIME_STATE_CURRENT_SCREEN = "launcher.current_screen";
// Type: int
private static final String RUNTIME_STATE = "launcher.state";
// Type: int
private static final String RUNTIME_STATE_PENDING_ADD_CONTAINER = "launcher.add_container";
// Type: int
private static final String RUNTIME_STATE_PENDING_ADD_SCREEN = "launcher.add_screen";
// Type: int
private static final String RUNTIME_STATE_PENDING_ADD_CELL_X = "launcher.add_cell_x";
// Type: int
private static final String RUNTIME_STATE_PENDING_ADD_CELL_Y = "launcher.add_cell_y";
// Type: boolean
private static final String RUNTIME_STATE_PENDING_FOLDER_RENAME = "launcher.rename_folder";
// Type: long
private static final String RUNTIME_STATE_PENDING_FOLDER_RENAME_ID = "launcher.rename_folder_id";
// Type: int
private static final String RUNTIME_STATE_PENDING_ADD_SPAN_X = "launcher.add_span_x";
// Type: int
private static final String RUNTIME_STATE_PENDING_ADD_SPAN_Y = "launcher.add_span_y";
// Type: parcelable
private static final String RUNTIME_STATE_PENDING_ADD_WIDGET_INFO = "launcher.add_widget_info";
private static final String TOOLBAR_ICON_METADATA_NAME = "com.android.launcher.toolbar_icon";
private static final String TOOLBAR_SEARCH_ICON_METADATA_NAME =
"com.android.launcher.toolbar_search_icon";
private static final String TOOLBAR_VOICE_SEARCH_ICON_METADATA_NAME =
"com.android.launcher.toolbar_voice_search_icon";
/** The different states that Launcher can be in. */
private enum State { NONE, WORKSPACE, APPS_CUSTOMIZE, APPS_CUSTOMIZE_SPRING_LOADED };
private State mState = State.WORKSPACE;
private AnimatorSet mStateAnimation;
private AnimatorSet mDividerAnimator;
static final int APPWIDGET_HOST_ID = 1024;
private static final int EXIT_SPRINGLOADED_MODE_SHORT_TIMEOUT = 300;
private static final int EXIT_SPRINGLOADED_MODE_LONG_TIMEOUT = 600;
private static final int SHOW_CLING_DURATION = 550;
private static final int DISMISS_CLING_DURATION = 250;
private static final Object sLock = new Object();
private static int sScreen = DEFAULT_SCREEN;
// How long to wait before the new-shortcut animation automatically pans the workspace
private static int NEW_APPS_ANIMATION_INACTIVE_TIMEOUT_SECONDS = 10;
private final BroadcastReceiver mCloseSystemDialogsReceiver
= new CloseSystemDialogsIntentReceiver();
private final ContentObserver mWidgetObserver = new AppWidgetResetObserver();
private LayoutInflater mInflater;
private Workspace mWorkspace;
private View mQsbDivider;
private View mDockDivider;
private DragLayer mDragLayer;
private DragController mDragController;
private AppWidgetManager mAppWidgetManager;
private LauncherAppWidgetHost mAppWidgetHost;
private ItemInfo mPendingAddInfo = new ItemInfo();
private AppWidgetProviderInfo mPendingAddWidgetInfo;
private int[] mTmpAddItemCellCoordinates = new int[2];
private FolderInfo mFolderInfo;
private Hotseat mHotseat;
private View mAllAppsButton;
private SearchDropTargetBar mSearchDropTargetBar;
private AppsCustomizeTabHost mAppsCustomizeTabHost;
private AppsCustomizePagedView mAppsCustomizeContent;
private boolean mAutoAdvanceRunning = false;
private Bundle mSavedState;
// We set the state in both onCreate and then onNewIntent in some cases, which causes both
// scroll issues (because the workspace may not have been measured yet) and extra work.
// Instead, just save the state that we need to restore Launcher to, and commit it in onResume.
private State mOnResumeState = State.NONE;
private SpannableStringBuilder mDefaultKeySsb = null;
private boolean mWorkspaceLoading = true;
private boolean mPaused = true;
private boolean mRestoring;
private boolean mWaitingForResult;
private boolean mOnResumeNeedsLoad;
// Keep track of whether the user has left launcher
private static boolean sPausedFromUserAction = false;
private Bundle mSavedInstanceState;
private LauncherModel mModel;
private IconCache mIconCache;
private boolean mUserPresent = true;
private boolean mVisible = false;
private boolean mAttached = false;
private static LocaleConfiguration sLocaleConfiguration = null;
private static HashMap<Long, FolderInfo> sFolders = new HashMap<Long, FolderInfo>();
private Intent mAppMarketIntent = null;
// Related to the auto-advancing of widgets
private final int ADVANCE_MSG = 1;
private final int mAdvanceInterval = 20000;
private final int mAdvanceStagger = 250;
private long mAutoAdvanceSentTime;
private long mAutoAdvanceTimeLeft = -1;
private HashMap<View, AppWidgetProviderInfo> mWidgetsToAdvance =
new HashMap<View, AppWidgetProviderInfo>();
// Determines how long to wait after a rotation before restoring the screen orientation to
// match the sensor state.
private final int mRestoreScreenOrientationDelay = 500;
// External icons saved in case of resource changes, orientation, etc.
private static Drawable.ConstantState[] sGlobalSearchIcon = new Drawable.ConstantState[2];
private static Drawable.ConstantState[] sVoiceSearchIcon = new Drawable.ConstantState[2];
private static Drawable.ConstantState[] sAppMarketIcon = new Drawable.ConstantState[2];
private final ArrayList<Integer> mSynchronouslyBoundPages = new ArrayList<Integer>();
static final ArrayList<String> sDumpLogs = new ArrayList<String>();
// We only want to get the SharedPreferences once since it does an FS stat each time we get
// it from the context.
private SharedPreferences mSharedPrefs;
// Holds the page that we need to animate to, and the icon views that we need to animate up
// when we scroll to that page on resume.
private int mNewShortcutAnimatePage = -1;
private ArrayList<View> mNewShortcutAnimateViews = new ArrayList<View>();
private ImageView mFolderIconImageView;
private Bitmap mFolderIconBitmap;
private Canvas mFolderIconCanvas;
private Rect mRectForFolderAnimation = new Rect();
private BubbleTextView mWaitingForResume;
private Runnable mBuildLayersRunnable = new Runnable() {
public void run() {
if (mWorkspace != null) {
mWorkspace.buildPageHardwareLayers();
}
}
};
private static ArrayList<PendingAddArguments> sPendingAddList
= new ArrayList<PendingAddArguments>();
private static class PendingAddArguments {
int requestCode;
Intent intent;
long container;
int screen;
int cellX;
int cellY;
}
private boolean doesFileExist(String filename) {
FileInputStream fis = null;
try {
fis = openFileInput(filename);
fis.close();
return true;
} catch (java.io.FileNotFoundException e) {
return false;
} catch (java.io.IOException e) {
return true;
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
if (DEBUG_STRICT_MODE) {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
.detectNetwork() // or .detectAll() for all detectable problems
.penaltyLog()
.build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectLeakedSqlLiteObjects()
.detectLeakedClosableObjects()
.penaltyLog()
.penaltyDeath()
.build());
}
super.onCreate(savedInstanceState);
LauncherApplication app = ((LauncherApplication)getApplication());
mSharedPrefs = getSharedPreferences(LauncherApplication.getSharedPreferencesKey(),
Context.MODE_PRIVATE);
mModel = app.setLauncher(this);
mIconCache = app.getIconCache();
mDragController = new DragController(this);
mInflater = getLayoutInflater();
mAppWidgetManager = AppWidgetManager.getInstance(this);
mAppWidgetHost = new LauncherAppWidgetHost(this, APPWIDGET_HOST_ID);
mAppWidgetHost.startListening();
// If we are getting an onCreate, we can actually preempt onResume and unset mPaused here,
// this also ensures that any synchronous binding below doesn't re-trigger another
// LauncherModel load.
mPaused = false;
if (PROFILE_STARTUP) {
android.os.Debug.startMethodTracing(
Environment.getExternalStorageDirectory() + "/launcher");
}
checkForLocaleChange();
setContentView(R.layout.launcher);
setupViews();
showFirstRunWorkspaceCling();
registerContentObservers();
lockAllApps();
mSavedState = savedInstanceState;
restoreState(mSavedState);
// Update customization drawer _after_ restoring the states
if (mAppsCustomizeContent != null) {
mAppsCustomizeContent.onPackagesUpdated();
}
if (PROFILE_STARTUP) {
android.os.Debug.stopMethodTracing();
}
if (!mRestoring) {
if (sPausedFromUserAction) {
// If the user leaves launcher, then we should just load items asynchronously when
// they return.
mModel.startLoader(true, -1);
} else {
// We only load the page synchronously if the user rotates (or triggers a
// configuration change) while launcher is in the foreground
mModel.startLoader(true, mWorkspace.getCurrentPage());
}
}
if (!mModel.isAllAppsLoaded()) {
ViewGroup appsCustomizeContentParent = (ViewGroup) mAppsCustomizeContent.getParent();
mInflater.inflate(R.layout.apps_customize_progressbar, appsCustomizeContentParent);
}
// For handling default keys
mDefaultKeySsb = new SpannableStringBuilder();
Selection.setSelection(mDefaultKeySsb, 0);
IntentFilter filter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
registerReceiver(mCloseSystemDialogsReceiver, filter);
updateGlobalIcons();
// On large interfaces, we want the screen to auto-rotate based on the current orientation
unlockScreenOrientation(true);
}
protected void onUserLeaveHint() {
super.onUserLeaveHint();
sPausedFromUserAction = true;
}
private void updateGlobalIcons() {
boolean searchVisible = false;
boolean voiceVisible = false;
// If we have a saved version of these external icons, we load them up immediately
int coi = getCurrentOrientationIndexForGlobalIcons();
if (sGlobalSearchIcon[coi] == null || sVoiceSearchIcon[coi] == null ||
sAppMarketIcon[coi] == null) {
updateAppMarketIcon();
searchVisible = updateGlobalSearchIcon();
voiceVisible = updateVoiceSearchIcon(searchVisible);
}
if (sGlobalSearchIcon[coi] != null) {
updateGlobalSearchIcon(sGlobalSearchIcon[coi]);
searchVisible = true;
}
if (sVoiceSearchIcon[coi] != null) {
updateVoiceSearchIcon(sVoiceSearchIcon[coi]);
voiceVisible = true;
}
if (sAppMarketIcon[coi] != null) {
updateAppMarketIcon(sAppMarketIcon[coi]);
}
if (mSearchDropTargetBar != null) {
mSearchDropTargetBar.onSearchPackagesChanged(searchVisible, voiceVisible);
}
}
private void checkForLocaleChange() {
if (sLocaleConfiguration == null) {
new AsyncTask<Void, Void, LocaleConfiguration>() {
@Override
protected LocaleConfiguration doInBackground(Void... unused) {
LocaleConfiguration localeConfiguration = new LocaleConfiguration();
readConfiguration(Launcher.this, localeConfiguration);
return localeConfiguration;
}
@Override
protected void onPostExecute(LocaleConfiguration result) {
sLocaleConfiguration = result;
checkForLocaleChange(); // recursive, but now with a locale configuration
}
}.execute();
return;
}
final Configuration configuration = getResources().getConfiguration();
final String previousLocale = sLocaleConfiguration.locale;
final String locale = configuration.locale.toString();
final int previousMcc = sLocaleConfiguration.mcc;
final int mcc = configuration.mcc;
final int previousMnc = sLocaleConfiguration.mnc;
final int mnc = configuration.mnc;
boolean localeChanged = !locale.equals(previousLocale) || mcc != previousMcc || mnc != previousMnc;
if (localeChanged) {
sLocaleConfiguration.locale = locale;
sLocaleConfiguration.mcc = mcc;
sLocaleConfiguration.mnc = mnc;
mIconCache.flush();
final LocaleConfiguration localeConfiguration = sLocaleConfiguration;
new Thread("WriteLocaleConfiguration") {
@Override
public void run() {
writeConfiguration(Launcher.this, localeConfiguration);
}
}.start();
}
}
private static class LocaleConfiguration {
public String locale;
public int mcc = -1;
public int mnc = -1;
}
private static void readConfiguration(Context context, LocaleConfiguration configuration) {
DataInputStream in = null;
try {
in = new DataInputStream(context.openFileInput(PREFERENCES));
configuration.locale = in.readUTF();
configuration.mcc = in.readInt();
configuration.mnc = in.readInt();
} catch (FileNotFoundException e) {
// Ignore
} catch (IOException e) {
// Ignore
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// Ignore
}
}
}
}
private static void writeConfiguration(Context context, LocaleConfiguration configuration) {
DataOutputStream out = null;
try {
out = new DataOutputStream(context.openFileOutput(PREFERENCES, MODE_PRIVATE));
out.writeUTF(configuration.locale);
out.writeInt(configuration.mcc);
out.writeInt(configuration.mnc);
out.flush();
} catch (FileNotFoundException e) {
// Ignore
} catch (IOException e) {
//noinspection ResultOfMethodCallIgnored
context.getFileStreamPath(PREFERENCES).delete();
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
// Ignore
}
}
}
}
public DragLayer getDragLayer() {
return mDragLayer;
}
boolean isDraggingEnabled() {
// We prevent dragging when we are loading the workspace as it is possible to pick up a view
// that is subsequently removed from the workspace in startBinding().
return !mModel.isLoadingWorkspace();
}
static int getScreen() {
synchronized (sLock) {
return sScreen;
}
}
static void setScreen(int screen) {
synchronized (sLock) {
sScreen = screen;
}
}
/**
* Returns whether we should delay spring loaded mode -- for shortcuts and widgets that have
* a configuration step, this allows the proper animations to run after other transitions.
*/
private boolean completeAdd(PendingAddArguments args) {
boolean result = false;
switch (args.requestCode) {
case REQUEST_PICK_APPLICATION:
completeAddApplication(args.intent, args.container, args.screen, args.cellX,
args.cellY);
break;
case REQUEST_PICK_SHORTCUT:
processShortcut(args.intent);
break;
case REQUEST_CREATE_SHORTCUT:
completeAddShortcut(args.intent, args.container, args.screen, args.cellX,
args.cellY);
result = true;
break;
case REQUEST_CREATE_APPWIDGET:
int appWidgetId = args.intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
completeAddAppWidget(appWidgetId, args.container, args.screen, null, null);
result = true;
break;
case REQUEST_PICK_WALLPAPER:
// We just wanted the activity result here so we can clear mWaitingForResult
break;
}
// Before adding this resetAddInfo(), after a shortcut was added to a workspace screen,
// if you turned the screen off and then back while in All Apps, Launcher would not
// return to the workspace. Clearing mAddInfo.container here fixes this issue
resetAddInfo();
return result;
}
@Override
protected void onActivityResult(
final int requestCode, final int resultCode, final Intent data) {
if (requestCode == REQUEST_BIND_APPWIDGET) {
int appWidgetId = data != null ?
data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1) : -1;
if (resultCode == RESULT_CANCELED) {
completeTwoStageWidgetDrop(RESULT_CANCELED, appWidgetId);
} else if (resultCode == RESULT_OK) {
addAppWidgetImpl(appWidgetId, mPendingAddInfo, null, mPendingAddWidgetInfo);
}
return;
}
boolean delayExitSpringLoadedMode = false;
boolean isWidgetDrop = (requestCode == REQUEST_PICK_APPWIDGET ||
requestCode == REQUEST_CREATE_APPWIDGET);
mWaitingForResult = false;
// We have special handling for widgets
if (isWidgetDrop) {
int appWidgetId = data != null ?
data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1) : -1;
if (appWidgetId < 0) {
Log.e(TAG, "Error: appWidgetId (EXTRA_APPWIDGET_ID) was not returned from the \\" +
"widget configuration activity.");
completeTwoStageWidgetDrop(RESULT_CANCELED, appWidgetId);
} else {
completeTwoStageWidgetDrop(resultCode, appWidgetId);
}
return;
}
// The pattern used here is that a user PICKs a specific application,
// which, depending on the target, might need to CREATE the actual target.
// For example, the user would PICK_SHORTCUT for "Music playlist", and we
// launch over to the Music app to actually CREATE_SHORTCUT.
if (resultCode == RESULT_OK && mPendingAddInfo.container != ItemInfo.NO_ID) {
final PendingAddArguments args = new PendingAddArguments();
args.requestCode = requestCode;
args.intent = data;
args.container = mPendingAddInfo.container;
args.screen = mPendingAddInfo.screen;
args.cellX = mPendingAddInfo.cellX;
args.cellY = mPendingAddInfo.cellY;
if (isWorkspaceLocked()) {
sPendingAddList.add(args);
} else {
delayExitSpringLoadedMode = completeAdd(args);
}
}
mDragLayer.clearAnimatedView();
// Exit spring loaded mode if necessary after cancelling the configuration of a widget
exitSpringLoadedDragModeDelayed((resultCode != RESULT_CANCELED), delayExitSpringLoadedMode,
null);
}
private void completeTwoStageWidgetDrop(final int resultCode, final int appWidgetId) {
CellLayout cellLayout =
(CellLayout) mWorkspace.getChildAt(mPendingAddInfo.screen);
Runnable onCompleteRunnable = null;
int animationType = 0;
AppWidgetHostView boundWidget = null;
if (resultCode == RESULT_OK) {
animationType = Workspace.COMPLETE_TWO_STAGE_WIDGET_DROP_ANIMATION;
final AppWidgetHostView layout = mAppWidgetHost.createView(this, appWidgetId,
mPendingAddWidgetInfo);
boundWidget = layout;
onCompleteRunnable = new Runnable() {
@Override
public void run() {
completeAddAppWidget(appWidgetId, mPendingAddInfo.container,
mPendingAddInfo.screen, layout, null);
exitSpringLoadedDragModeDelayed((resultCode != RESULT_CANCELED), false,
null);
}
};
} else if (resultCode == RESULT_CANCELED) {
animationType = Workspace.CANCEL_TWO_STAGE_WIDGET_DROP_ANIMATION;
onCompleteRunnable = new Runnable() {
@Override
public void run() {
exitSpringLoadedDragModeDelayed((resultCode != RESULT_CANCELED), false,
null);
}
};
}
if (mDragLayer.getAnimatedView() != null) {
mWorkspace.animateWidgetDrop(mPendingAddInfo, cellLayout,
(DragView) mDragLayer.getAnimatedView(), onCompleteRunnable,
animationType, boundWidget, true);
} else {
// The animated view may be null in the case of a rotation during widget configuration
onCompleteRunnable.run();
}
}
@Override
protected void onResume() {
super.onResume();
// Restore the previous launcher state
if (mOnResumeState == State.WORKSPACE) {
showWorkspace(false);
} else if (mOnResumeState == State.APPS_CUSTOMIZE) {
showAllApps(false);
}
mOnResumeState = State.NONE;
// Process any items that were added while Launcher was away
InstallShortcutReceiver.flushInstallQueue(this);
mPaused = false;
sPausedFromUserAction = false;
if (mRestoring || mOnResumeNeedsLoad) {
mWorkspaceLoading = true;
mModel.startLoader(true, -1);
mRestoring = false;
mOnResumeNeedsLoad = false;
}
// Reset the pressed state of icons that were locked in the press state while activities
// were launching
if (mWaitingForResume != null) {
// Resets the previous workspace icon press state
mWaitingForResume.setStayPressed(false);
}
if (mAppsCustomizeContent != null) {
// Resets the previous all apps icon press state
mAppsCustomizeContent.resetDrawableState();
}
// It is possible that widgets can receive updates while launcher is not in the foreground.
// Consequently, the widgets will be inflated in the orientation of the foreground activity
// (framework issue). On resuming, we ensure that any widgets are inflated for the current
// orientation.
getWorkspace().reinflateWidgetsIfNecessary();
// Again, as with the above scenario, it's possible that one or more of the global icons
// were updated in the wrong orientation.
updateGlobalIcons();
}
@Override
protected void onPause() {
// NOTE: We want all transitions from launcher to act as if the wallpaper were enabled
// to be consistent. So re-enable the flag here, and we will re-disable it as necessary
// when Launcher resumes and we are still in AllApps.
updateWallpaperVisibility(true);
super.onPause();
mPaused = true;
mDragController.cancelDrag();
mDragController.resetLastGestureUpTime();
}
@Override
public Object onRetainNonConfigurationInstance() {
// Flag the loader to stop early before switching
mModel.stopLoader();
if (mAppsCustomizeContent != null) {
mAppsCustomizeContent.surrender();
}
return Boolean.TRUE;
}
// We can't hide the IME if it was forced open. So don't bother
/*
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus) {
final InputMethodManager inputManager = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
WindowManager.LayoutParams lp = getWindow().getAttributes();
inputManager.hideSoftInputFromWindow(lp.token, 0, new android.os.ResultReceiver(new
android.os.Handler()) {
protected void onReceiveResult(int resultCode, Bundle resultData) {
Log.d(TAG, "ResultReceiver got resultCode=" + resultCode);
}
});
Log.d(TAG, "called hideSoftInputFromWindow from onWindowFocusChanged");
}
}
*/
private boolean acceptFilter() {
final InputMethodManager inputManager = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
return !inputManager.isFullscreenMode();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
final int uniChar = event.getUnicodeChar();
final boolean handled = super.onKeyDown(keyCode, event);
final boolean isKeyNotWhitespace = uniChar > 0 && !Character.isWhitespace(uniChar);
if (!handled && acceptFilter() && isKeyNotWhitespace) {
boolean gotKey = TextKeyListener.getInstance().onKeyDown(mWorkspace, mDefaultKeySsb,
keyCode, event);
if (gotKey && mDefaultKeySsb != null && mDefaultKeySsb.length() > 0) {
// something usable has been typed - start a search
// the typed text will be retrieved and cleared by
// showSearchDialog()
// If there are multiple keystrokes before the search dialog takes focus,
// onSearchRequested() will be called for every keystroke,
// but it is idempotent, so it's fine.
return onSearchRequested();
}
}
// Eat the long press event so the keyboard doesn't come up.
if (keyCode == KeyEvent.KEYCODE_MENU && event.isLongPress()) {
return true;
}
return handled;
}
private String getTypedText() {
return mDefaultKeySsb.toString();
}
private void clearTypedText() {
mDefaultKeySsb.clear();
mDefaultKeySsb.clearSpans();
Selection.setSelection(mDefaultKeySsb, 0);
}
/**
* Given the integer (ordinal) value of a State enum instance, convert it to a variable of type
* State
*/
private static State intToState(int stateOrdinal) {
State state = State.WORKSPACE;
final State[] stateValues = State.values();
for (int i = 0; i < stateValues.length; i++) {
if (stateValues[i].ordinal() == stateOrdinal) {
state = stateValues[i];
break;
}
}
return state;
}
/**
* Restores the previous state, if it exists.
*
* @param savedState The previous state.
*/
private void restoreState(Bundle savedState) {
if (savedState == null) {
return;
}
State state = intToState(savedState.getInt(RUNTIME_STATE, State.WORKSPACE.ordinal()));
if (state == State.APPS_CUSTOMIZE) {
mOnResumeState = State.APPS_CUSTOMIZE;
}
int currentScreen = savedState.getInt(RUNTIME_STATE_CURRENT_SCREEN, -1);
if (currentScreen > -1) {
mWorkspace.setCurrentPage(currentScreen);
}
final long pendingAddContainer = savedState.getLong(RUNTIME_STATE_PENDING_ADD_CONTAINER, -1);
final int pendingAddScreen = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SCREEN, -1);
if (pendingAddContainer != ItemInfo.NO_ID && pendingAddScreen > -1) {
mPendingAddInfo.container = pendingAddContainer;
mPendingAddInfo.screen = pendingAddScreen;
mPendingAddInfo.cellX = savedState.getInt(RUNTIME_STATE_PENDING_ADD_CELL_X);
mPendingAddInfo.cellY = savedState.getInt(RUNTIME_STATE_PENDING_ADD_CELL_Y);
mPendingAddInfo.spanX = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SPAN_X);
mPendingAddInfo.spanY = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SPAN_Y);
mPendingAddWidgetInfo = savedState.getParcelable(RUNTIME_STATE_PENDING_ADD_WIDGET_INFO);
mWaitingForResult = true;
mRestoring = true;
}
boolean renameFolder = savedState.getBoolean(RUNTIME_STATE_PENDING_FOLDER_RENAME, false);
if (renameFolder) {
long id = savedState.getLong(RUNTIME_STATE_PENDING_FOLDER_RENAME_ID);
mFolderInfo = mModel.getFolderById(this, sFolders, id);
mRestoring = true;
}
// Restore the AppsCustomize tab
if (mAppsCustomizeTabHost != null) {
String curTab = savedState.getString("apps_customize_currentTab");
if (curTab != null) {
mAppsCustomizeTabHost.setContentTypeImmediate(
mAppsCustomizeTabHost.getContentTypeForTabTag(curTab));
mAppsCustomizeContent.loadAssociatedPages(
mAppsCustomizeContent.getCurrentPage());
}
int currentIndex = savedState.getInt("apps_customize_currentIndex");
mAppsCustomizeContent.restorePageForIndex(currentIndex);
}
}
/**
* Finds all the views we need and configure them properly.
*/
private void setupViews() {
final DragController dragController = mDragController;
mDragLayer = (DragLayer) findViewById(R.id.drag_layer);
mWorkspace = (Workspace) mDragLayer.findViewById(R.id.workspace);
mQsbDivider = (ImageView) findViewById(R.id.qsb_divider);
mDockDivider = (ImageView) findViewById(R.id.dock_divider);
// Setup the drag layer
mDragLayer.setup(this, dragController);
// Setup the hotseat
mHotseat = (Hotseat) findViewById(R.id.hotseat);
if (mHotseat != null) {
mHotseat.setup(this);
}
// Setup the workspace
mWorkspace.setHapticFeedbackEnabled(false);
mWorkspace.setOnLongClickListener(this);
mWorkspace.setup(dragController);
dragController.addDragListener(mWorkspace);
// Get the search/delete bar
mSearchDropTargetBar = (SearchDropTargetBar) mDragLayer.findViewById(R.id.qsb_bar);
// Setup AppsCustomize
mAppsCustomizeTabHost = (AppsCustomizeTabHost)
findViewById(R.id.apps_customize_pane);
mAppsCustomizeContent = (AppsCustomizePagedView)
mAppsCustomizeTabHost.findViewById(R.id.apps_customize_pane_content);
mAppsCustomizeContent.setup(this, dragController);
// Setup the drag controller (drop targets have to be added in reverse order in priority)
dragController.setDragScoller(mWorkspace);
dragController.setScrollView(mDragLayer);
dragController.setMoveTarget(mWorkspace);
dragController.addDropTarget(mWorkspace);
if (mSearchDropTargetBar != null) {
mSearchDropTargetBar.setup(this, dragController);
}
}
/**
* Creates a view representing a shortcut.
*
* @param info The data structure describing the shortcut.
*
* @return A View inflated from R.layout.application.
*/
View createShortcut(ShortcutInfo info) {
return createShortcut(R.layout.application,
(ViewGroup) mWorkspace.getChildAt(mWorkspace.getCurrentPage()), info);
}
/**
* Creates a view representing a shortcut inflated from the specified resource.
*
* @param layoutResId The id of the XML layout used to create the shortcut.
* @param parent The group the shortcut belongs to.
* @param info The data structure describing the shortcut.
*
* @return A View inflated from layoutResId.
*/
View createShortcut(int layoutResId, ViewGroup parent, ShortcutInfo info) {
BubbleTextView favorite = (BubbleTextView) mInflater.inflate(layoutResId, parent, false);
favorite.applyFromShortcutInfo(info, mIconCache);
favorite.setOnClickListener(this);
return favorite;
}
/**
* Add an application shortcut to the workspace.
*
* @param data The intent describing the application.
* @param cellInfo The position on screen where to create the shortcut.
*/
void completeAddApplication(Intent data, long container, int screen, int cellX, int cellY) {
final int[] cellXY = mTmpAddItemCellCoordinates;
final CellLayout layout = getCellLayout(container, screen);
// First we check if we already know the exact location where we want to add this item.
if (cellX >= 0 && cellY >= 0) {
cellXY[0] = cellX;
cellXY[1] = cellY;
} else if (!layout.findCellForSpan(cellXY, 1, 1)) {
showOutOfSpaceMessage(isHotseatLayout(layout));
return;
}
final ShortcutInfo info = mModel.getShortcutInfo(getPackageManager(), data, this);
if (info != null) {
info.setActivity(data.getComponent(), Intent.FLAG_ACTIVITY_NEW_TASK |
Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
info.container = ItemInfo.NO_ID;
mWorkspace.addApplicationShortcut(info, layout, container, screen, cellXY[0], cellXY[1],
isWorkspaceLocked(), cellX, cellY);
} else {
Log.e(TAG, "Couldn't find ActivityInfo for selected application: " + data);
}
}
/**
* Add a shortcut to the workspace.
*
* @param data The intent describing the shortcut.
* @param cellInfo The position on screen where to create the shortcut.
*/
private void completeAddShortcut(Intent data, long container, int screen, int cellX,
int cellY) {
int[] cellXY = mTmpAddItemCellCoordinates;
int[] touchXY = mPendingAddInfo.dropPos;
CellLayout layout = getCellLayout(container, screen);
boolean foundCellSpan = false;
ShortcutInfo info = mModel.infoFromShortcutIntent(this, data, null);
if (info == null) {
return;
}
final View view = createShortcut(info);
// First we check if we already know the exact location where we want to add this item.
if (cellX >= 0 && cellY >= 0) {
cellXY[0] = cellX;
cellXY[1] = cellY;
foundCellSpan = true;
// If appropriate, either create a folder or add to an existing folder
if (mWorkspace.createUserFolderIfNecessary(view, container, layout, cellXY, 0,
true, null,null)) {
return;
}
DragObject dragObject = new DragObject();
dragObject.dragInfo = info;
if (mWorkspace.addToExistingFolderIfNecessary(view, layout, cellXY, 0, dragObject,
true)) {
return;
}
} else if (touchXY != null) {
// when dragging and dropping, just find the closest free spot
int[] result = layout.findNearestVacantArea(touchXY[0], touchXY[1], 1, 1, cellXY);
foundCellSpan = (result != null);
} else {
foundCellSpan = layout.findCellForSpan(cellXY, 1, 1);
}
if (!foundCellSpan) {
showOutOfSpaceMessage(isHotseatLayout(layout));
return;
}
LauncherModel.addItemToDatabase(this, info, container, screen, cellXY[0], cellXY[1], false);
if (!mRestoring) {
mWorkspace.addInScreen(view, container, screen, cellXY[0], cellXY[1], 1, 1,
isWorkspaceLocked());
}
}
static int[] getSpanForWidget(Context context, ComponentName component, int minWidth,
int minHeight) {
Rect padding = AppWidgetHostView.getDefaultPaddingForWidget(context, component, null);
// We want to account for the extra amount of padding that we are adding to the widget
// to ensure that it gets the full amount of space that it has requested
int requiredWidth = minWidth + padding.left + padding.right;
int requiredHeight = minHeight + padding.top + padding.bottom;
return CellLayout.rectToCell(context.getResources(), requiredWidth, requiredHeight, null);
}
static int[] getSpanForWidget(Context context, AppWidgetProviderInfo info) {
return getSpanForWidget(context, info.provider, info.minWidth, info.minHeight);
}
static int[] getMinSpanForWidget(Context context, AppWidgetProviderInfo info) {
return getSpanForWidget(context, info.provider, info.minResizeWidth, info.minResizeHeight);
}
static int[] getSpanForWidget(Context context, PendingAddWidgetInfo info) {
return getSpanForWidget(context, info.componentName, info.minWidth, info.minHeight);
}
static int[] getMinSpanForWidget(Context context, PendingAddWidgetInfo info) {
return getSpanForWidget(context, info.componentName, info.minResizeWidth,
info.minResizeHeight);
}
/**
* Add a widget to the workspace.
*
* @param appWidgetId The app widget id
* @param cellInfo The position on screen where to create the widget.
*/
private void completeAddAppWidget(final int appWidgetId, long container, int screen,
AppWidgetHostView hostView, AppWidgetProviderInfo appWidgetInfo) {
if (appWidgetInfo == null) {
appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(appWidgetId);
}
// Calculate the grid spans needed to fit this widget
CellLayout layout = getCellLayout(container, screen);
int[] minSpanXY = getMinSpanForWidget(this, appWidgetInfo);
int[] spanXY = getSpanForWidget(this, appWidgetInfo);
// Try finding open space on Launcher screen
// We have saved the position to which the widget was dragged-- this really only matters
// if we are placing widgets on a "spring-loaded" screen
int[] cellXY = mTmpAddItemCellCoordinates;
int[] touchXY = mPendingAddInfo.dropPos;
int[] finalSpan = new int[2];
boolean foundCellSpan = false;
if (mPendingAddInfo.cellX >= 0 && mPendingAddInfo.cellY >= 0) {
cellXY[0] = mPendingAddInfo.cellX;
cellXY[1] = mPendingAddInfo.cellY;
spanXY[0] = mPendingAddInfo.spanX;
spanXY[1] = mPendingAddInfo.spanY;
foundCellSpan = true;
} else if (touchXY != null) {
// when dragging and dropping, just find the closest free spot
int[] result = layout.findNearestVacantArea(
touchXY[0], touchXY[1], minSpanXY[0], minSpanXY[1], spanXY[0],
spanXY[1], cellXY, finalSpan);
spanXY[0] = finalSpan[0];
spanXY[1] = finalSpan[1];
foundCellSpan = (result != null);
} else {
foundCellSpan = layout.findCellForSpan(cellXY, minSpanXY[0], minSpanXY[1]);
}
if (!foundCellSpan) {
if (appWidgetId != -1) {
// Deleting an app widget ID is a void call but writes to disk before returning
// to the caller...
new Thread("deleteAppWidgetId") {
public void run() {
mAppWidgetHost.deleteAppWidgetId(appWidgetId);
}
}.start();
}
showOutOfSpaceMessage(isHotseatLayout(layout));
return;
}
// Build Launcher-specific widget info and save to database
LauncherAppWidgetInfo launcherInfo = new LauncherAppWidgetInfo(appWidgetId,
appWidgetInfo.provider);
launcherInfo.spanX = spanXY[0];
launcherInfo.spanY = spanXY[1];
launcherInfo.minSpanX = mPendingAddInfo.minSpanX;
launcherInfo.minSpanY = mPendingAddInfo.minSpanY;
LauncherModel.addItemToDatabase(this, launcherInfo,
container, screen, cellXY[0], cellXY[1], false);
if (!mRestoring) {
if (hostView == null) {
// Perform actual inflation because we're live
launcherInfo.hostView = mAppWidgetHost.createView(this, appWidgetId, appWidgetInfo);
launcherInfo.hostView.setAppWidget(appWidgetId, appWidgetInfo);
} else {
// The AppWidgetHostView has already been inflated and instantiated
launcherInfo.hostView = hostView;
}
launcherInfo.hostView.setTag(launcherInfo);
launcherInfo.hostView.setVisibility(View.VISIBLE);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
launcherInfo.notifyWidgetSizeChanged(this);
}
mWorkspace.addInScreen(launcherInfo.hostView, container, screen, cellXY[0], cellXY[1],
launcherInfo.spanX, launcherInfo.spanY, isWorkspaceLocked());
addWidgetToAutoAdvanceIfNeeded(launcherInfo.hostView, appWidgetInfo);
}
resetAddInfo();
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (Intent.ACTION_SCREEN_OFF.equals(action)) {
mUserPresent = false;
mDragLayer.clearAllResizeFrames();
updateRunning();
// Reset AllApps to its initial state only if we are not in the middle of
// processing a multi-step drop
if (mAppsCustomizeTabHost != null && mPendingAddInfo.container == ItemInfo.NO_ID) {
mAppsCustomizeTabHost.reset();
showWorkspace(false);
}
} else if (Intent.ACTION_USER_PRESENT.equals(action)) {
mUserPresent = true;
updateRunning();
}
}
};
@Override
public void onAttachedToWindow() {
super.onAttachedToWindow();
// Listen for broadcasts related to user-presence
final IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_USER_PRESENT);
registerReceiver(mReceiver, filter);
mAttached = true;
mVisible = true;
}
@Override
public void onDetachedFromWindow() {
super.onDetachedFromWindow();
mVisible = false;
if (mAttached) {
unregisterReceiver(mReceiver);
mAttached = false;
}
updateRunning();
}
public void onWindowVisibilityChanged(int visibility) {
mVisible = visibility == View.VISIBLE;
updateRunning();
// The following code used to be in onResume, but it turns out onResume is called when
// you're in All Apps and click home to go to the workspace. onWindowVisibilityChanged
// is a more appropriate event to handle
if (mVisible) {
mAppsCustomizeTabHost.onWindowVisible();
if (!mWorkspaceLoading) {
final ViewTreeObserver observer = mWorkspace.getViewTreeObserver();
// We want to let Launcher draw itself at least once before we force it to build
// layers on all the workspace pages, so that transitioning to Launcher from other
// apps is nice and speedy. Usually the first call to preDraw doesn't correspond to
// a true draw so we wait until the second preDraw call to be safe
observer.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
public boolean onPreDraw() {
// We delay the layer building a bit in order to give
// other message processing a time to run. In particular
// this avoids a delay in hiding the IME if it was
// currently shown, because doing that may involve
// some communication back with the app.
mWorkspace.postDelayed(mBuildLayersRunnable, 500);
observer.removeOnPreDrawListener(this);
return true;
}
});
}
// When Launcher comes back to foreground, a different Activity might be responsible for
// the app market intent, so refresh the icon
updateAppMarketIcon();
clearTypedText();
}
}
private void sendAdvanceMessage(long delay) {
mHandler.removeMessages(ADVANCE_MSG);
Message msg = mHandler.obtainMessage(ADVANCE_MSG);
mHandler.sendMessageDelayed(msg, delay);
mAutoAdvanceSentTime = System.currentTimeMillis();
}
private void updateRunning() {
boolean autoAdvanceRunning = mVisible && mUserPresent && !mWidgetsToAdvance.isEmpty();
if (autoAdvanceRunning != mAutoAdvanceRunning) {
mAutoAdvanceRunning = autoAdvanceRunning;
if (autoAdvanceRunning) {
long delay = mAutoAdvanceTimeLeft == -1 ? mAdvanceInterval : mAutoAdvanceTimeLeft;
sendAdvanceMessage(delay);
} else {
if (!mWidgetsToAdvance.isEmpty()) {
mAutoAdvanceTimeLeft = Math.max(0, mAdvanceInterval -
(System.currentTimeMillis() - mAutoAdvanceSentTime));
}
mHandler.removeMessages(ADVANCE_MSG);
mHandler.removeMessages(0); // Remove messages sent using postDelayed()
}
}
}
private final Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == ADVANCE_MSG) {
int i = 0;
for (View key: mWidgetsToAdvance.keySet()) {
final View v = key.findViewById(mWidgetsToAdvance.get(key).autoAdvanceViewId);
final int delay = mAdvanceStagger * i;
if (v instanceof Advanceable) {
postDelayed(new Runnable() {
public void run() {
((Advanceable) v).advance();
}
}, delay);
}
i++;
}
sendAdvanceMessage(mAdvanceInterval);
}
}
};
void addWidgetToAutoAdvanceIfNeeded(View hostView, AppWidgetProviderInfo appWidgetInfo) {
if (appWidgetInfo == null || appWidgetInfo.autoAdvanceViewId == -1) return;
View v = hostView.findViewById(appWidgetInfo.autoAdvanceViewId);
if (v instanceof Advanceable) {
mWidgetsToAdvance.put(hostView, appWidgetInfo);
((Advanceable) v).fyiWillBeAdvancedByHostKThx();
updateRunning();
}
}
void removeWidgetToAutoAdvance(View hostView) {
if (mWidgetsToAdvance.containsKey(hostView)) {
mWidgetsToAdvance.remove(hostView);
updateRunning();
}
}
public void removeAppWidget(LauncherAppWidgetInfo launcherInfo) {
removeWidgetToAutoAdvance(launcherInfo.hostView);
launcherInfo.hostView = null;
}
void showOutOfSpaceMessage(boolean isHotseatLayout) {
int strId = (isHotseatLayout ? R.string.hotseat_out_of_space : R.string.out_of_space);
Toast.makeText(this, getString(strId), Toast.LENGTH_SHORT).show();
}
public LauncherAppWidgetHost getAppWidgetHost() {
return mAppWidgetHost;
}
public LauncherModel getModel() {
return mModel;
}
void closeSystemDialogs() {
getWindow().closeAllPanels();
// Whatever we were doing is hereby canceled.
mWaitingForResult = false;
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
// Close the menu
if (Intent.ACTION_MAIN.equals(intent.getAction())) {
// also will cancel mWaitingForResult.
closeSystemDialogs();
boolean alreadyOnHome = ((intent.getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT)
!= Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
Folder openFolder = mWorkspace.getOpenFolder();
// In all these cases, only animate if we're already on home
mWorkspace.exitWidgetResizeMode();
if (alreadyOnHome && mState == State.WORKSPACE && !mWorkspace.isTouchActive() &&
openFolder == null) {
mWorkspace.moveToDefaultScreen(true);
}
closeFolder();
exitSpringLoadedDragMode();
// If we are already on home, then just animate back to the workspace, otherwise, just
// wait until onResume to set the state back to Workspace
if (alreadyOnHome) {
showWorkspace(true);
} else {
mOnResumeState = State.WORKSPACE;
}
final View v = getWindow().peekDecorView();
if (v != null && v.getWindowToken() != null) {
InputMethodManager imm = (InputMethodManager)getSystemService(
INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
// Reset AllApps to its initial state
if (!alreadyOnHome && mAppsCustomizeTabHost != null) {
mAppsCustomizeTabHost.reset();
}
}
}
@Override
public void onRestoreInstanceState(Bundle state) {
super.onRestoreInstanceState(state);
for (int page: mSynchronouslyBoundPages) {
mWorkspace.restoreInstanceStateForChild(page);
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
outState.putInt(RUNTIME_STATE_CURRENT_SCREEN, mWorkspace.getNextPage());
super.onSaveInstanceState(outState);
outState.putInt(RUNTIME_STATE, mState.ordinal());
// We close any open folder since it will not be re-opened, and we need to make sure
// this state is reflected.
closeFolder();
if (mPendingAddInfo.container != ItemInfo.NO_ID && mPendingAddInfo.screen > -1 &&
mWaitingForResult) {
outState.putLong(RUNTIME_STATE_PENDING_ADD_CONTAINER, mPendingAddInfo.container);
outState.putInt(RUNTIME_STATE_PENDING_ADD_SCREEN, mPendingAddInfo.screen);
outState.putInt(RUNTIME_STATE_PENDING_ADD_CELL_X, mPendingAddInfo.cellX);
outState.putInt(RUNTIME_STATE_PENDING_ADD_CELL_Y, mPendingAddInfo.cellY);
outState.putInt(RUNTIME_STATE_PENDING_ADD_SPAN_X, mPendingAddInfo.spanX);
outState.putInt(RUNTIME_STATE_PENDING_ADD_SPAN_Y, mPendingAddInfo.spanY);
outState.putParcelable(RUNTIME_STATE_PENDING_ADD_WIDGET_INFO, mPendingAddWidgetInfo);
}
if (mFolderInfo != null && mWaitingForResult) {
outState.putBoolean(RUNTIME_STATE_PENDING_FOLDER_RENAME, true);
outState.putLong(RUNTIME_STATE_PENDING_FOLDER_RENAME_ID, mFolderInfo.id);
}
// Save the current AppsCustomize tab
if (mAppsCustomizeTabHost != null) {
String currentTabTag = mAppsCustomizeTabHost.getCurrentTabTag();
if (currentTabTag != null) {
outState.putString("apps_customize_currentTab", currentTabTag);
}
int currentIndex = mAppsCustomizeContent.getSaveInstanceStateIndex();
outState.putInt("apps_customize_currentIndex", currentIndex);
}
}
@Override
public void onDestroy() {
super.onDestroy();
// Remove all pending runnables
mHandler.removeMessages(ADVANCE_MSG);
mHandler.removeMessages(0);
mWorkspace.removeCallbacks(mBuildLayersRunnable);
// Stop callbacks from LauncherModel
LauncherApplication app = ((LauncherApplication) getApplication());
mModel.stopLoader();
app.setLauncher(null);
try {
mAppWidgetHost.stopListening();
} catch (NullPointerException ex) {
Log.w(TAG, "problem while stopping AppWidgetHost during Launcher destruction", ex);
}
mAppWidgetHost = null;
mWidgetsToAdvance.clear();
TextKeyListener.getInstance().release();
// Disconnect any of the callbacks and drawables associated with ItemInfos on the workspace
// to prevent leaking Launcher activities on orientation change.
if (mModel != null) {
mModel.unbindItemInfosAndClearQueuedBindRunnables();
}
getContentResolver().unregisterContentObserver(mWidgetObserver);
unregisterReceiver(mCloseSystemDialogsReceiver);
mDragLayer.clearAllResizeFrames();
((ViewGroup) mWorkspace.getParent()).removeAllViews();
mWorkspace.removeAllViews();
mWorkspace = null;
mDragController = null;
LauncherAnimUtils.onDestroyActivity();
}
public DragController getDragController() {
return mDragController;
}
@Override
public void startActivityForResult(Intent intent, int requestCode) {
if (requestCode >= 0) mWaitingForResult = true;
super.startActivityForResult(intent, requestCode);
}
/**
* Indicates that we want global search for this activity by setting the globalSearch
* argument for {@link #startSearch} to true.
*/
@Override
public void startSearch(String initialQuery, boolean selectInitialQuery,
Bundle appSearchData, boolean globalSearch) {
showWorkspace(true);
if (initialQuery == null) {
// Use any text typed in the launcher as the initial query
initialQuery = getTypedText();
}
if (appSearchData == null) {
appSearchData = new Bundle();
appSearchData.putString(Search.SOURCE, "launcher-search");
}
Rect sourceBounds = new Rect();
if (mSearchDropTargetBar != null) {
sourceBounds = mSearchDropTargetBar.getSearchBarBounds();
}
startGlobalSearch(initialQuery, selectInitialQuery,
appSearchData, sourceBounds);
}
/**
* Starts the global search activity. This code is a copied from SearchManager
*/
public void startGlobalSearch(String initialQuery,
boolean selectInitialQuery, Bundle appSearchData, Rect sourceBounds) {
final SearchManager searchManager =
(SearchManager) getSystemService(Context.SEARCH_SERVICE);
ComponentName globalSearchActivity = searchManager.getGlobalSearchActivity();
if (globalSearchActivity == null) {
Log.w(TAG, "No global search activity found.");
return;
}
Intent intent = new Intent(SearchManager.INTENT_ACTION_GLOBAL_SEARCH);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setComponent(globalSearchActivity);
// Make sure that we have a Bundle to put source in
if (appSearchData == null) {
appSearchData = new Bundle();
} else {
appSearchData = new Bundle(appSearchData);
}
// Set source to package name of app that starts global search, if not set already.
if (!appSearchData.containsKey("source")) {
appSearchData.putString("source", getPackageName());
}
intent.putExtra(SearchManager.APP_DATA, appSearchData);
if (!TextUtils.isEmpty(initialQuery)) {
intent.putExtra(SearchManager.QUERY, initialQuery);
}
if (selectInitialQuery) {
intent.putExtra(SearchManager.EXTRA_SELECT_QUERY, selectInitialQuery);
}
intent.setSourceBounds(sourceBounds);
try {
startActivity(intent);
} catch (ActivityNotFoundException ex) {
Log.e(TAG, "Global search activity not found: " + globalSearchActivity);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if (isWorkspaceLocked()) {
return false;
}
super.onCreateOptionsMenu(menu);
Intent manageApps = new Intent(Settings.ACTION_MANAGE_ALL_APPLICATIONS_SETTINGS);
manageApps.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
Intent settings = new Intent(android.provider.Settings.ACTION_SETTINGS);
settings.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
String helpUrl = getString(R.string.help_url);
Intent help = new Intent(Intent.ACTION_VIEW, Uri.parse(helpUrl));
help.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
menu.add(MENU_GROUP_WALLPAPER, MENU_WALLPAPER_SETTINGS, 0, R.string.menu_wallpaper)
.setIcon(android.R.drawable.ic_menu_gallery)
.setAlphabeticShortcut('W');
menu.add(0, MENU_MANAGE_APPS, 0, R.string.menu_manage_apps)
.setIcon(android.R.drawable.ic_menu_manage)
.setIntent(manageApps)
.setAlphabeticShortcut('M');
menu.add(0, MENU_SYSTEM_SETTINGS, 0, R.string.menu_settings)
.setIcon(android.R.drawable.ic_menu_preferences)
.setIntent(settings)
.setAlphabeticShortcut('P');
if (!helpUrl.isEmpty()) {
menu.add(0, MENU_HELP, 0, R.string.menu_help)
.setIcon(android.R.drawable.ic_menu_help)
.setIntent(help)
.setAlphabeticShortcut('H');
}
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
if (mAppsCustomizeTabHost.isTransitioning()) {
return false;
}
boolean allAppsVisible = (mAppsCustomizeTabHost.getVisibility() == View.VISIBLE);
menu.setGroupVisible(MENU_GROUP_WALLPAPER, !allAppsVisible);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_WALLPAPER_SETTINGS:
startWallpaper();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public boolean onSearchRequested() {
startSearch(null, false, null, true);
// Use a custom animation for launching search
return true;
}
public boolean isWorkspaceLocked() {
return mWorkspaceLoading || mWaitingForResult;
}
private void resetAddInfo() {
mPendingAddInfo.container = ItemInfo.NO_ID;
mPendingAddInfo.screen = -1;
mPendingAddInfo.cellX = mPendingAddInfo.cellY = -1;
mPendingAddInfo.spanX = mPendingAddInfo.spanY = -1;
mPendingAddInfo.minSpanX = mPendingAddInfo.minSpanY = -1;
mPendingAddInfo.dropPos = null;
}
void addAppWidgetImpl(final int appWidgetId, ItemInfo info, AppWidgetHostView boundWidget,
AppWidgetProviderInfo appWidgetInfo) {
if (appWidgetInfo.configure != null) {
mPendingAddWidgetInfo = appWidgetInfo;
// Launch over to configure widget, if needed
Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_CONFIGURE);
intent.setComponent(appWidgetInfo.configure);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
startActivityForResultSafely(intent, REQUEST_CREATE_APPWIDGET);
} else {
// Otherwise just add it
completeAddAppWidget(appWidgetId, info.container, info.screen, boundWidget,
appWidgetInfo);
// Exit spring loaded mode if necessary after adding the widget
exitSpringLoadedDragModeDelayed(true, false, null);
}
}
/**
* Process a shortcut drop.
*
* @param componentName The name of the component
* @param screen The screen where it should be added
* @param cell The cell it should be added to, optional
* @param position The location on the screen where it was dropped, optional
*/
void processShortcutFromDrop(ComponentName componentName, long container, int screen,
int[] cell, int[] loc) {
resetAddInfo();
mPendingAddInfo.container = container;
mPendingAddInfo.screen = screen;
mPendingAddInfo.dropPos = loc;
if (cell != null) {
mPendingAddInfo.cellX = cell[0];
mPendingAddInfo.cellY = cell[1];
}
Intent createShortcutIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
createShortcutIntent.setComponent(componentName);
processShortcut(createShortcutIntent);
}
/**
* Process a widget drop.
*
* @param info The PendingAppWidgetInfo of the widget being added.
* @param screen The screen where it should be added
* @param cell The cell it should be added to, optional
* @param position The location on the screen where it was dropped, optional
*/
void addAppWidgetFromDrop(PendingAddWidgetInfo info, long container, int screen,
int[] cell, int[] span, int[] loc) {
resetAddInfo();
mPendingAddInfo.container = info.container = container;
mPendingAddInfo.screen = info.screen = screen;
mPendingAddInfo.dropPos = loc;
mPendingAddInfo.minSpanX = info.minSpanX;
mPendingAddInfo.minSpanY = info.minSpanY;
if (cell != null) {
mPendingAddInfo.cellX = cell[0];
mPendingAddInfo.cellY = cell[1];
}
if (span != null) {
mPendingAddInfo.spanX = span[0];
mPendingAddInfo.spanY = span[1];
}
AppWidgetHostView hostView = info.boundWidget;
int appWidgetId;
if (hostView != null) {
appWidgetId = hostView.getAppWidgetId();
addAppWidgetImpl(appWidgetId, info, hostView, info.info);
} else {
// In this case, we either need to start an activity to get permission to bind
// the widget, or we need to start an activity to configure the widget, or both.
appWidgetId = getAppWidgetHost().allocateAppWidgetId();
if (mAppWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId, info.componentName)) {
addAppWidgetImpl(appWidgetId, info, null, info.info);
} else {
mPendingAddWidgetInfo = info.info;
Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_BIND);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_PROVIDER, info.componentName);
startActivityForResult(intent, REQUEST_BIND_APPWIDGET);
}
}
}
void processShortcut(Intent intent) {
// Handle case where user selected "Applications"
String applicationName = getResources().getString(R.string.group_applications);
String shortcutName = intent.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
if (applicationName != null && applicationName.equals(shortcutName)) {
Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
Intent pickIntent = new Intent(Intent.ACTION_PICK_ACTIVITY);
pickIntent.putExtra(Intent.EXTRA_INTENT, mainIntent);
pickIntent.putExtra(Intent.EXTRA_TITLE, getText(R.string.title_select_application));
startActivityForResultSafely(pickIntent, REQUEST_PICK_APPLICATION);
} else {
startActivityForResultSafely(intent, REQUEST_CREATE_SHORTCUT);
}
}
void processWallpaper(Intent intent) {
startActivityForResult(intent, REQUEST_PICK_WALLPAPER);
}
FolderIcon addFolder(CellLayout layout, long container, final int screen, int cellX,
int cellY) {
final FolderInfo folderInfo = new FolderInfo();
folderInfo.title = getText(R.string.folder_name);
// Update the model
LauncherModel.addItemToDatabase(Launcher.this, folderInfo, container, screen, cellX, cellY,
false);
sFolders.put(folderInfo.id, folderInfo);
// Create the view
FolderIcon newFolder =
FolderIcon.fromXml(R.layout.folder_icon, this, layout, folderInfo, mIconCache);
mWorkspace.addInScreen(newFolder, container, screen, cellX, cellY, 1, 1,
isWorkspaceLocked());
return newFolder;
}
void removeFolder(FolderInfo folder) {
sFolders.remove(folder.id);
}
private void startWallpaper() {
showWorkspace(true);
final Intent pickWallpaper = new Intent(Intent.ACTION_SET_WALLPAPER);
Intent chooser = Intent.createChooser(pickWallpaper,
getText(R.string.chooser_wallpaper));
// NOTE: Adds a configure option to the chooser if the wallpaper supports it
// Removed in Eclair MR1
// WallpaperManager wm = (WallpaperManager)
// getSystemService(Context.WALLPAPER_SERVICE);
// WallpaperInfo wi = wm.getWallpaperInfo();
// if (wi != null && wi.getSettingsActivity() != null) {
// LabeledIntent li = new LabeledIntent(getPackageName(),
// R.string.configure_wallpaper, 0);
// li.setClassName(wi.getPackageName(), wi.getSettingsActivity());
// chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] { li });
// }
startActivityForResult(chooser, REQUEST_PICK_WALLPAPER);
}
/**
* Registers various content observers. The current implementation registers
* only a favorites observer to keep track of the favorites applications.
*/
private void registerContentObservers() {
ContentResolver resolver = getContentResolver();
resolver.registerContentObserver(LauncherProvider.CONTENT_APPWIDGET_RESET_URI,
true, mWidgetObserver);
}
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (event.getKeyCode()) {
case KeyEvent.KEYCODE_HOME:
return true;
case KeyEvent.KEYCODE_VOLUME_DOWN:
if (doesFileExist(DUMP_STATE_PROPERTY)) {
dumpState();
return true;
}
break;
}
} else if (event.getAction() == KeyEvent.ACTION_UP) {
switch (event.getKeyCode()) {
case KeyEvent.KEYCODE_HOME:
return true;
}
}
return super.dispatchKeyEvent(event);
}
@Override
public void onBackPressed() {
if (isAllAppsVisible()) {
showWorkspace(true);
} else if (mWorkspace.getOpenFolder() != null) {
Folder openFolder = mWorkspace.getOpenFolder();
if (openFolder.isEditingName()) {
openFolder.dismissEditingName();
} else {
closeFolder();
}
} else {
mWorkspace.exitWidgetResizeMode();
// Back button is a no-op here, but give at least some feedback for the button press
mWorkspace.showOutlinesTemporarily();
}
}
/**
* Re-listen when widgets are reset.
*/
private void onAppWidgetReset() {
if (mAppWidgetHost != null) {
mAppWidgetHost.startListening();
}
}
/**
* Launches the intent referred by the clicked shortcut.
*
* @param v The view representing the clicked shortcut.
*/
public void onClick(View v) {
// Make sure that rogue clicks don't get through while allapps is launching, or after the
// view has detached (it's possible for this to happen if the view is removed mid touch).
if (v.getWindowToken() == null) {
return;
}
if (!mWorkspace.isFinishedSwitchingState()) {
return;
}
Object tag = v.getTag();
if (tag instanceof ShortcutInfo) {
// Open shortcut
final Intent intent = ((ShortcutInfo) tag).intent;
int[] pos = new int[2];
v.getLocationOnScreen(pos);
intent.setSourceBounds(new Rect(pos[0], pos[1],
pos[0] + v.getWidth(), pos[1] + v.getHeight()));
boolean success = startActivitySafely(v, intent, tag);
if (success && v instanceof BubbleTextView) {
mWaitingForResume = (BubbleTextView) v;
mWaitingForResume.setStayPressed(true);
}
} else if (tag instanceof FolderInfo) {
if (v instanceof FolderIcon) {
FolderIcon fi = (FolderIcon) v;
handleFolderClick(fi);
}
} else if (v == mAllAppsButton) {
if (isAllAppsVisible()) {
showWorkspace(true);
} else {
onClickAllAppsButton(v);
}
}
}
public boolean onTouch(View v, MotionEvent event) {
// this is an intercepted event being forwarded from mWorkspace;
// clicking anywhere on the workspace causes the customization drawer to slide down
showWorkspace(true);
return false;
}
/**
* Event handler for the search button
*
* @param v The view that was clicked.
*/
public void onClickSearchButton(View v) {
v.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
onSearchRequested();
}
/**
* Event handler for the voice button
*
* @param v The view that was clicked.
*/
public void onClickVoiceButton(View v) {
v.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
try {
final SearchManager searchManager =
(SearchManager) getSystemService(Context.SEARCH_SERVICE);
ComponentName activityName = searchManager.getGlobalSearchActivity();
Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (activityName != null) {
intent.setPackage(activityName.getPackageName());
}
startActivity(null, intent, "onClickVoiceButton");
} catch (ActivityNotFoundException e) {
Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivitySafely(null, intent, "onClickVoiceButton");
}
}
/**
* Event handler for the "grid" button that appears on the home screen, which
* enters all apps mode.
*
* @param v The view that was clicked.
*/
public void onClickAllAppsButton(View v) {
showAllApps(true);
}
public void onTouchDownAllAppsButton(View v) {
// Provide the same haptic feedback that the system offers for virtual keys.
v.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
}
public void onClickAppMarketButton(View v) {
if (mAppMarketIntent != null) {
startActivitySafely(v, mAppMarketIntent, "app market");
} else {
Log.e(TAG, "Invalid app market intent.");
}
}
void startApplicationDetailsActivity(ComponentName componentName) {
String packageName = componentName.getPackageName();
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
Uri.fromParts("package", packageName, null));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
startActivitySafely(null, intent, "startApplicationDetailsActivity");
}
void startApplicationUninstallActivity(ApplicationInfo appInfo) {
if ((appInfo.flags & ApplicationInfo.DOWNLOADED_FLAG) == 0) {
// System applications cannot be installed. For now, show a toast explaining that.
// We may give them the option of disabling apps this way.
int messageId = R.string.uninstall_system_app_text;
Toast.makeText(this, messageId, Toast.LENGTH_SHORT).show();
} else {
String packageName = appInfo.componentName.getPackageName();
String className = appInfo.componentName.getClassName();
Intent intent = new Intent(
Intent.ACTION_DELETE, Uri.fromParts("package", packageName, className));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
startActivity(intent);
}
}
boolean startActivity(View v, Intent intent, Object tag) {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
// Only launch using the new animation if the shortcut has not opted out (this is a
// private contract between launcher and may be ignored in the future).
boolean useLaunchAnimation = (v != null) &&
!intent.hasExtra(INTENT_EXTRA_IGNORE_LAUNCH_ANIMATION);
if (useLaunchAnimation) {
ActivityOptions opts = ActivityOptions.makeScaleUpAnimation(v, 0, 0,
v.getMeasuredWidth(), v.getMeasuredHeight());
startActivity(intent, opts.toBundle());
} else {
startActivity(intent);
}
return true;
} catch (SecurityException e) {
Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
Log.e(TAG, "Launcher does not have the permission to launch " + intent +
". Make sure to create a MAIN intent-filter for the corresponding activity " +
"or use the exported attribute for this activity. "
+ "tag="+ tag + " intent=" + intent, e);
}
return false;
}
boolean startActivitySafely(View v, Intent intent, Object tag) {
boolean success = false;
try {
success = startActivity(v, intent, tag);
} catch (ActivityNotFoundException e) {
Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
Log.e(TAG, "Unable to launch. tag=" + tag + " intent=" + intent, e);
}
return success;
}
void startActivityForResultSafely(Intent intent, int requestCode) {
try {
startActivityForResult(intent, requestCode);
} catch (ActivityNotFoundException e) {
Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
} catch (SecurityException e) {
Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
Log.e(TAG, "Launcher does not have the permission to launch " + intent +
". Make sure to create a MAIN intent-filter for the corresponding activity " +
"or use the exported attribute for this activity.", e);
}
}
private void handleFolderClick(FolderIcon folderIcon) {
final FolderInfo info = folderIcon.getFolderInfo();
Folder openFolder = mWorkspace.getFolderForTag(info);
// If the folder info reports that the associated folder is open, then verify that
// it is actually opened. There have been a few instances where this gets out of sync.
if (info.opened && openFolder == null) {
Log.d(TAG, "Folder info marked as open, but associated folder is not open. Screen: "
+ info.screen + " (" + info.cellX + ", " + info.cellY + ")");
info.opened = false;
}
if (!info.opened && !folderIcon.getFolder().isDestroyed()) {
// Close any open folder
closeFolder();
// Open the requested folder
openFolder(folderIcon);
} else {
// Find the open folder...
int folderScreen;
if (openFolder != null) {
folderScreen = mWorkspace.getPageForView(openFolder);
// .. and close it
closeFolder(openFolder);
if (folderScreen != mWorkspace.getCurrentPage()) {
// Close any folder open on the current screen
closeFolder();
// Pull the folder onto this screen
openFolder(folderIcon);
}
}
}
}
/**
* This method draws the FolderIcon to an ImageView and then adds and positions that ImageView
* in the DragLayer in the exact absolute location of the original FolderIcon.
*/
private void copyFolderIconToImage(FolderIcon fi) {
final int width = fi.getMeasuredWidth();
final int height = fi.getMeasuredHeight();
// Lazy load ImageView, Bitmap and Canvas
if (mFolderIconImageView == null) {
mFolderIconImageView = new ImageView(this);
}
if (mFolderIconBitmap == null || mFolderIconBitmap.getWidth() != width ||
mFolderIconBitmap.getHeight() != height) {
mFolderIconBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
mFolderIconCanvas = new Canvas(mFolderIconBitmap);
}
DragLayer.LayoutParams lp;
if (mFolderIconImageView.getLayoutParams() instanceof DragLayer.LayoutParams) {
lp = (DragLayer.LayoutParams) mFolderIconImageView.getLayoutParams();
} else {
lp = new DragLayer.LayoutParams(width, height);
}
// The layout from which the folder is being opened may be scaled, adjust the starting
// view size by this scale factor.
float scale = mDragLayer.getDescendantRectRelativeToSelf(fi, mRectForFolderAnimation);
lp.customPosition = true;
lp.x = mRectForFolderAnimation.left;
lp.y = mRectForFolderAnimation.top;
lp.width = (int) (scale * width);
lp.height = (int) (scale * height);
mFolderIconCanvas.drawColor(0, PorterDuff.Mode.CLEAR);
fi.draw(mFolderIconCanvas);
mFolderIconImageView.setImageBitmap(mFolderIconBitmap);
if (fi.getFolder() != null) {
mFolderIconImageView.setPivotX(fi.getFolder().getPivotXForIconAnimation());
mFolderIconImageView.setPivotY(fi.getFolder().getPivotYForIconAnimation());
}
// Just in case this image view is still in the drag layer from a previous animation,
// we remove it and re-add it.
if (mDragLayer.indexOfChild(mFolderIconImageView) != -1) {
mDragLayer.removeView(mFolderIconImageView);
}
mDragLayer.addView(mFolderIconImageView, lp);
if (fi.getFolder() != null) {
fi.getFolder().bringToFront();
}
}
private void growAndFadeOutFolderIcon(FolderIcon fi) {
if (fi == null) return;
PropertyValuesHolder alpha = PropertyValuesHolder.ofFloat("alpha", 0);
PropertyValuesHolder scaleX = PropertyValuesHolder.ofFloat("scaleX", 1.5f);
PropertyValuesHolder scaleY = PropertyValuesHolder.ofFloat("scaleY", 1.5f);
FolderInfo info = (FolderInfo) fi.getTag();
if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
CellLayout cl = (CellLayout) fi.getParent().getParent();
CellLayout.LayoutParams lp = (CellLayout.LayoutParams) fi.getLayoutParams();
cl.setFolderLeaveBehindCell(lp.cellX, lp.cellY);
}
// Push an ImageView copy of the FolderIcon into the DragLayer and hide the original
copyFolderIconToImage(fi);
fi.setVisibility(View.INVISIBLE);
ObjectAnimator oa = LauncherAnimUtils.ofPropertyValuesHolder(mFolderIconImageView, alpha,
scaleX, scaleY);
oa.setDuration(getResources().getInteger(R.integer.config_folderAnimDuration));
oa.start();
}
private void shrinkAndFadeInFolderIcon(final FolderIcon fi) {
if (fi == null) return;
PropertyValuesHolder alpha = PropertyValuesHolder.ofFloat("alpha", 1.0f);
PropertyValuesHolder scaleX = PropertyValuesHolder.ofFloat("scaleX", 1.0f);
PropertyValuesHolder scaleY = PropertyValuesHolder.ofFloat("scaleY", 1.0f);
final CellLayout cl = (CellLayout) fi.getParent().getParent();
// We remove and re-draw the FolderIcon in-case it has changed
mDragLayer.removeView(mFolderIconImageView);
copyFolderIconToImage(fi);
ObjectAnimator oa = LauncherAnimUtils.ofPropertyValuesHolder(mFolderIconImageView, alpha,
scaleX, scaleY);
oa.setDuration(getResources().getInteger(R.integer.config_folderAnimDuration));
oa.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
if (cl != null) {
cl.clearFolderLeaveBehind();
// Remove the ImageView copy of the FolderIcon and make the original visible.
mDragLayer.removeView(mFolderIconImageView);
fi.setVisibility(View.VISIBLE);
}
}
});
oa.start();
}
/**
* Opens the user folder described by the specified tag. The opening of the folder
* is animated relative to the specified View. If the View is null, no animation
* is played.
*
* @param folderInfo The FolderInfo describing the folder to open.
*/
public void openFolder(FolderIcon folderIcon) {
Folder folder = folderIcon.getFolder();
FolderInfo info = folder.mInfo;
info.opened = true;
// Just verify that the folder hasn't already been added to the DragLayer.
// There was a one-off crash where the folder had a parent already.
if (folder.getParent() == null) {
mDragLayer.addView(folder);
mDragController.addDropTarget((DropTarget) folder);
} else {
Log.w(TAG, "Opening folder (" + folder + ") which already has a parent (" +
folder.getParent() + ").");
}
folder.animateOpen();
growAndFadeOutFolderIcon(folderIcon);
}
public void closeFolder() {
Folder folder = mWorkspace.getOpenFolder();
if (folder != null) {
if (folder.isEditingName()) {
folder.dismissEditingName();
}
closeFolder(folder);
// Dismiss the folder cling
dismissFolderCling(null);
}
}
void closeFolder(Folder folder) {
folder.getInfo().opened = false;
ViewGroup parent = (ViewGroup) folder.getParent().getParent();
if (parent != null) {
FolderIcon fi = (FolderIcon) mWorkspace.getViewForTag(folder.mInfo);
shrinkAndFadeInFolderIcon(fi);
}
folder.animateClosed();
}
public boolean onLongClick(View v) {
if (!isDraggingEnabled()) return false;
if (isWorkspaceLocked()) return false;
if (mState != State.WORKSPACE) return false;
if (!(v instanceof CellLayout)) {
v = (View) v.getParent().getParent();
}
resetAddInfo();
CellLayout.CellInfo longClickCellInfo = (CellLayout.CellInfo) v.getTag();
// This happens when long clicking an item with the dpad/trackball
if (longClickCellInfo == null) {
return true;
}
// The hotseat touch handling does not go through Workspace, and we always allow long press
// on hotseat items.
final View itemUnderLongClick = longClickCellInfo.cell;
boolean allowLongPress = isHotseatLayout(v) || mWorkspace.allowLongPress();
if (allowLongPress && !mDragController.isDragging()) {
if (itemUnderLongClick == null) {
// User long pressed on empty space
mWorkspace.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS,
HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING);
startWallpaper();
} else {
if (!(itemUnderLongClick instanceof Folder)) {
// User long pressed on an item
mWorkspace.startDrag(longClickCellInfo);
}
}
}
return true;
}
boolean isHotseatLayout(View layout) {
return mHotseat != null && layout != null &&
(layout instanceof CellLayout) && (layout == mHotseat.getLayout());
}
Hotseat getHotseat() {
return mHotseat;
}
SearchDropTargetBar getSearchBar() {
return mSearchDropTargetBar;
}
/**
* Returns the CellLayout of the specified container at the specified screen.
*/
CellLayout getCellLayout(long container, int screen) {
if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
if (mHotseat != null) {
return mHotseat.getLayout();
} else {
return null;
}
} else {
return (CellLayout) mWorkspace.getChildAt(screen);
}
}
Workspace getWorkspace() {
return mWorkspace;
}
// Now a part of LauncherModel.Callbacks. Used to reorder loading steps.
public boolean isAllAppsVisible() {
return (mState == State.APPS_CUSTOMIZE) || (mOnResumeState == State.APPS_CUSTOMIZE);
}
public boolean isAllAppsButtonRank(int rank) {
return mHotseat.isAllAppsButtonRank(rank);
}
/**
* Helper method for the cameraZoomIn/cameraZoomOut animations
* @param view The view being animated
* @param state The state that we are moving in or out of (eg. APPS_CUSTOMIZE)
* @param scaleFactor The scale factor used for the zoom
*/
private void setPivotsForZoom(View view, float scaleFactor) {
view.setPivotX(view.getWidth() / 2.0f);
view.setPivotY(view.getHeight() / 2.0f);
}
void disableWallpaperIfInAllApps() {
// Only disable it if we are in all apps
if (isAllAppsVisible()) {
if (mAppsCustomizeTabHost != null &&
!mAppsCustomizeTabHost.isTransitioning()) {
updateWallpaperVisibility(false);
}
}
}
void updateWallpaperVisibility(boolean visible) {
int wpflags = visible ? WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER : 0;
int curflags = getWindow().getAttributes().flags
& WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER;
if (wpflags != curflags) {
getWindow().setFlags(wpflags, WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER);
}
}
private void dispatchOnLauncherTransitionPrepare(View v, boolean animated, boolean toWorkspace) {
if (v instanceof LauncherTransitionable) {
((LauncherTransitionable) v).onLauncherTransitionPrepare(this, animated, toWorkspace);
}
}
private void dispatchOnLauncherTransitionStart(View v, boolean animated, boolean toWorkspace) {
if (v instanceof LauncherTransitionable) {
((LauncherTransitionable) v).onLauncherTransitionStart(this, animated, toWorkspace);
}
// Update the workspace transition step as well
dispatchOnLauncherTransitionStep(v, 0f);
}
private void dispatchOnLauncherTransitionStep(View v, float t) {
if (v instanceof LauncherTransitionable) {
((LauncherTransitionable) v).onLauncherTransitionStep(this, t);
}
}
private void dispatchOnLauncherTransitionEnd(View v, boolean animated, boolean toWorkspace) {
if (v instanceof LauncherTransitionable) {
((LauncherTransitionable) v).onLauncherTransitionEnd(this, animated, toWorkspace);
}
// Update the workspace transition step as well
dispatchOnLauncherTransitionStep(v, 1f);
}
/**
* Things to test when changing the following seven functions.
* - Home from workspace
* - from center screen
* - from other screens
* - Home from all apps
* - from center screen
* - from other screens
* - Back from all apps
* - from center screen
* - from other screens
* - Launch app from workspace and quit
* - with back
* - with home
* - Launch app from all apps and quit
* - with back
* - with home
* - Go to a screen that's not the default, then all
* apps, and launch and app, and go back
* - with back
* -with home
* - On workspace, long press power and go back
* - with back
* - with home
* - On all apps, long press power and go back
* - with back
* - with home
* - On workspace, power off
* - On all apps, power off
* - Launch an app and turn off the screen while in that app
* - Go back with home key
* - Go back with back key TODO: make this not go to workspace
* - From all apps
* - From workspace
* - Enter and exit car mode (becuase it causes an extra configuration changed)
* - From all apps
* - From the center workspace
* - From another workspace
*/
/**
* Zoom the camera out from the workspace to reveal 'toView'.
* Assumes that the view to show is anchored at either the very top or very bottom
* of the screen.
*/
private void showAppsCustomizeHelper(final boolean animated, final boolean springLoaded) {
if (mStateAnimation != null) {
mStateAnimation.cancel();
mStateAnimation = null;
}
final Resources res = getResources();
final int duration = res.getInteger(R.integer.config_appsCustomizeZoomInTime);
final int fadeDuration = res.getInteger(R.integer.config_appsCustomizeFadeInTime);
final float scale = (float) res.getInteger(R.integer.config_appsCustomizeZoomScaleFactor);
final View fromView = mWorkspace;
final AppsCustomizeTabHost toView = mAppsCustomizeTabHost;
final int startDelay =
res.getInteger(R.integer.config_workspaceAppsCustomizeAnimationStagger);
setPivotsForZoom(toView, scale);
// Shrink workspaces away if going to AppsCustomize from workspace
Animator workspaceAnim =
mWorkspace.getChangeStateAnimation(Workspace.State.SMALL, animated);
if (animated) {
toView.setScaleX(scale);
toView.setScaleY(scale);
final LauncherViewPropertyAnimator scaleAnim = new LauncherViewPropertyAnimator(toView);
scaleAnim.
scaleX(1f).scaleY(1f).
setDuration(duration).
setInterpolator(new Workspace.ZoomOutInterpolator());
toView.setVisibility(View.VISIBLE);
toView.setAlpha(0f);
final ObjectAnimator alphaAnim = ObjectAnimator
.ofFloat(toView, "alpha", 0f, 1f)
.setDuration(fadeDuration);
alphaAnim.setInterpolator(new DecelerateInterpolator(1.5f));
alphaAnim.addUpdateListener(new AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
if (animation == null) {
throw new RuntimeException("animation is null");
}
float t = (Float) animation.getAnimatedValue();
dispatchOnLauncherTransitionStep(fromView, t);
dispatchOnLauncherTransitionStep(toView, t);
}
});
// toView should appear right at the end of the workspace shrink
// animation
mStateAnimation = LauncherAnimUtils.createAnimatorSet();
mStateAnimation.play(scaleAnim).after(startDelay);
mStateAnimation.play(alphaAnim).after(startDelay);
mStateAnimation.addListener(new AnimatorListenerAdapter() {
boolean animationCancelled = false;
@Override
public void onAnimationStart(Animator animation) {
updateWallpaperVisibility(true);
// Prepare the position
toView.setTranslationX(0.0f);
toView.setTranslationY(0.0f);
toView.setVisibility(View.VISIBLE);
toView.bringToFront();
}
@Override
public void onAnimationEnd(Animator animation) {
dispatchOnLauncherTransitionEnd(fromView, animated, false);
dispatchOnLauncherTransitionEnd(toView, animated, false);
- if (!springLoaded && !LauncherApplication.isScreenLarge()) {
+ if (mWorkspace != null && !springLoaded && !LauncherApplication.isScreenLarge()) {
// Hide the workspace scrollbar
mWorkspace.hideScrollingIndicator(true);
hideDockDivider();
}
if (!animationCancelled) {
updateWallpaperVisibility(false);
}
// Hide the search bar
if (mSearchDropTargetBar != null) {
mSearchDropTargetBar.hideSearchBar(false);
}
}
@Override
public void onAnimationCancel(Animator animation) {
animationCancelled = true;
}
});
if (workspaceAnim != null) {
mStateAnimation.play(workspaceAnim);
}
boolean delayAnim = false;
final ViewTreeObserver observer;
dispatchOnLauncherTransitionPrepare(fromView, animated, false);
dispatchOnLauncherTransitionPrepare(toView, animated, false);
// If any of the objects being animated haven't been measured/laid out
// yet, delay the animation until we get a layout pass
if ((((LauncherTransitionable) toView).getContent().getMeasuredWidth() == 0) ||
(mWorkspace.getMeasuredWidth() == 0) ||
(toView.getMeasuredWidth() == 0)) {
observer = mWorkspace.getViewTreeObserver();
delayAnim = true;
} else {
observer = null;
}
final AnimatorSet stateAnimation = mStateAnimation;
final Runnable startAnimRunnable = new Runnable() {
public void run() {
// Check that mStateAnimation hasn't changed while
// we waited for a layout/draw pass
if (mStateAnimation != stateAnimation)
return;
setPivotsForZoom(toView, scale);
dispatchOnLauncherTransitionStart(fromView, animated, false);
dispatchOnLauncherTransitionStart(toView, animated, false);
toView.post(new Runnable() {
public void run() {
// Check that mStateAnimation hasn't changed while
// we waited for a layout/draw pass
if (mStateAnimation != stateAnimation)
return;
mStateAnimation.start();
}
});
}
};
if (delayAnim) {
final OnGlobalLayoutListener delayedStart = new OnGlobalLayoutListener() {
public void onGlobalLayout() {
toView.post(startAnimRunnable);
observer.removeOnGlobalLayoutListener(this);
}
};
observer.addOnGlobalLayoutListener(delayedStart);
} else {
startAnimRunnable.run();
}
} else {
toView.setTranslationX(0.0f);
toView.setTranslationY(0.0f);
toView.setScaleX(1.0f);
toView.setScaleY(1.0f);
toView.setVisibility(View.VISIBLE);
toView.bringToFront();
if (!springLoaded && !LauncherApplication.isScreenLarge()) {
// Hide the workspace scrollbar
mWorkspace.hideScrollingIndicator(true);
hideDockDivider();
// Hide the search bar
if (mSearchDropTargetBar != null) {
mSearchDropTargetBar.hideSearchBar(false);
}
}
dispatchOnLauncherTransitionPrepare(fromView, animated, false);
dispatchOnLauncherTransitionStart(fromView, animated, false);
dispatchOnLauncherTransitionEnd(fromView, animated, false);
dispatchOnLauncherTransitionPrepare(toView, animated, false);
dispatchOnLauncherTransitionStart(toView, animated, false);
dispatchOnLauncherTransitionEnd(toView, animated, false);
updateWallpaperVisibility(false);
}
}
/**
* Zoom the camera back into the workspace, hiding 'fromView'.
* This is the opposite of showAppsCustomizeHelper.
* @param animated If true, the transition will be animated.
*/
private void hideAppsCustomizeHelper(State toState, final boolean animated,
final boolean springLoaded, final Runnable onCompleteRunnable) {
if (mStateAnimation != null) {
mStateAnimation.cancel();
mStateAnimation = null;
}
Resources res = getResources();
final int duration = res.getInteger(R.integer.config_appsCustomizeZoomOutTime);
final int fadeOutDuration =
res.getInteger(R.integer.config_appsCustomizeFadeOutTime);
final float scaleFactor = (float)
res.getInteger(R.integer.config_appsCustomizeZoomScaleFactor);
final View fromView = mAppsCustomizeTabHost;
final View toView = mWorkspace;
Animator workspaceAnim = null;
if (toState == State.WORKSPACE) {
int stagger = res.getInteger(R.integer.config_appsCustomizeWorkspaceAnimationStagger);
workspaceAnim = mWorkspace.getChangeStateAnimation(
Workspace.State.NORMAL, animated, stagger);
} else if (toState == State.APPS_CUSTOMIZE_SPRING_LOADED) {
workspaceAnim = mWorkspace.getChangeStateAnimation(
Workspace.State.SPRING_LOADED, animated);
}
setPivotsForZoom(fromView, scaleFactor);
updateWallpaperVisibility(true);
showHotseat(animated);
if (animated) {
final LauncherViewPropertyAnimator scaleAnim =
new LauncherViewPropertyAnimator(fromView);
scaleAnim.
scaleX(scaleFactor).scaleY(scaleFactor).
setDuration(duration).
setInterpolator(new Workspace.ZoomInInterpolator());
final ObjectAnimator alphaAnim = ObjectAnimator
.ofFloat(fromView, "alpha", 1f, 0f)
.setDuration(fadeOutDuration);
alphaAnim.setInterpolator(new AccelerateDecelerateInterpolator());
alphaAnim.addUpdateListener(new AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
float t = 1f - (Float) animation.getAnimatedValue();
dispatchOnLauncherTransitionStep(fromView, t);
dispatchOnLauncherTransitionStep(toView, t);
}
});
mStateAnimation = LauncherAnimUtils.createAnimatorSet();
dispatchOnLauncherTransitionPrepare(fromView, animated, true);
dispatchOnLauncherTransitionPrepare(toView, animated, true);
mStateAnimation.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
updateWallpaperVisibility(true);
fromView.setVisibility(View.GONE);
dispatchOnLauncherTransitionEnd(fromView, animated, true);
dispatchOnLauncherTransitionEnd(toView, animated, true);
if (mWorkspace != null) {
mWorkspace.hideScrollingIndicator(false);
}
if (onCompleteRunnable != null) {
onCompleteRunnable.run();
}
}
});
mStateAnimation.playTogether(scaleAnim, alphaAnim);
if (workspaceAnim != null) {
mStateAnimation.play(workspaceAnim);
}
dispatchOnLauncherTransitionStart(fromView, animated, true);
dispatchOnLauncherTransitionStart(toView, animated, true);
final Animator stateAnimation = mStateAnimation;
mWorkspace.post(new Runnable() {
public void run() {
if (stateAnimation != mStateAnimation)
return;
mStateAnimation.start();
}
});
} else {
fromView.setVisibility(View.GONE);
dispatchOnLauncherTransitionPrepare(fromView, animated, true);
dispatchOnLauncherTransitionStart(fromView, animated, true);
dispatchOnLauncherTransitionEnd(fromView, animated, true);
dispatchOnLauncherTransitionPrepare(toView, animated, true);
dispatchOnLauncherTransitionStart(toView, animated, true);
dispatchOnLauncherTransitionEnd(toView, animated, true);
mWorkspace.hideScrollingIndicator(false);
}
}
@Override
public void onTrimMemory(int level) {
super.onTrimMemory(level);
if (level >= ComponentCallbacks2.TRIM_MEMORY_MODERATE) {
mAppsCustomizeTabHost.onTrimMemory();
}
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
if (!hasFocus) {
// When another window occludes launcher (like the notification shade, or recents),
// ensure that we enable the wallpaper flag so that transitions are done correctly.
updateWallpaperVisibility(true);
} else {
// When launcher has focus again, disable the wallpaper if we are in AllApps
mWorkspace.postDelayed(new Runnable() {
@Override
public void run() {
disableWallpaperIfInAllApps();
}
}, 500);
}
}
void showWorkspace(boolean animated) {
showWorkspace(animated, null);
}
void showWorkspace(boolean animated, Runnable onCompleteRunnable) {
if (mState != State.WORKSPACE) {
boolean wasInSpringLoadedMode = (mState == State.APPS_CUSTOMIZE_SPRING_LOADED);
mWorkspace.setVisibility(View.VISIBLE);
hideAppsCustomizeHelper(State.WORKSPACE, animated, false, onCompleteRunnable);
// Show the search bar (only animate if we were showing the drop target bar in spring
// loaded mode)
if (mSearchDropTargetBar != null) {
mSearchDropTargetBar.showSearchBar(wasInSpringLoadedMode);
}
// We only need to animate in the dock divider if we're going from spring loaded mode
showDockDivider(animated && wasInSpringLoadedMode);
// Set focus to the AppsCustomize button
if (mAllAppsButton != null) {
mAllAppsButton.requestFocus();
}
}
mWorkspace.flashScrollingIndicator(animated);
// Change the state *after* we've called all the transition code
mState = State.WORKSPACE;
// Resume the auto-advance of widgets
mUserPresent = true;
updateRunning();
// send an accessibility event to announce the context change
getWindow().getDecorView().sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED);
}
void showAllApps(boolean animated) {
if (mState != State.WORKSPACE) return;
showAppsCustomizeHelper(animated, false);
mAppsCustomizeTabHost.requestFocus();
// Change the state *after* we've called all the transition code
mState = State.APPS_CUSTOMIZE;
// Pause the auto-advance of widgets until we are out of AllApps
mUserPresent = false;
updateRunning();
closeFolder();
// Send an accessibility event to announce the context change
getWindow().getDecorView().sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED);
}
void enterSpringLoadedDragMode() {
if (isAllAppsVisible()) {
hideAppsCustomizeHelper(State.APPS_CUSTOMIZE_SPRING_LOADED, true, true, null);
hideDockDivider();
mState = State.APPS_CUSTOMIZE_SPRING_LOADED;
}
}
void exitSpringLoadedDragModeDelayed(final boolean successfulDrop, boolean extendedDelay,
final Runnable onCompleteRunnable) {
if (mState != State.APPS_CUSTOMIZE_SPRING_LOADED) return;
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
if (successfulDrop) {
// Before we show workspace, hide all apps again because
// exitSpringLoadedDragMode made it visible. This is a bit hacky; we should
// clean up our state transition functions
mAppsCustomizeTabHost.setVisibility(View.GONE);
showWorkspace(true, onCompleteRunnable);
} else {
exitSpringLoadedDragMode();
}
}
}, (extendedDelay ?
EXIT_SPRINGLOADED_MODE_LONG_TIMEOUT :
EXIT_SPRINGLOADED_MODE_SHORT_TIMEOUT));
}
void exitSpringLoadedDragMode() {
if (mState == State.APPS_CUSTOMIZE_SPRING_LOADED) {
final boolean animated = true;
final boolean springLoaded = true;
showAppsCustomizeHelper(animated, springLoaded);
mState = State.APPS_CUSTOMIZE;
}
// Otherwise, we are not in spring loaded mode, so don't do anything.
}
void hideDockDivider() {
if (mQsbDivider != null && mDockDivider != null) {
mQsbDivider.setVisibility(View.INVISIBLE);
mDockDivider.setVisibility(View.INVISIBLE);
}
}
void showDockDivider(boolean animated) {
if (mQsbDivider != null && mDockDivider != null) {
mQsbDivider.setVisibility(View.VISIBLE);
mDockDivider.setVisibility(View.VISIBLE);
if (mDividerAnimator != null) {
mDividerAnimator.cancel();
mQsbDivider.setAlpha(1f);
mDockDivider.setAlpha(1f);
mDividerAnimator = null;
}
if (animated) {
mDividerAnimator = LauncherAnimUtils.createAnimatorSet();
mDividerAnimator.playTogether(LauncherAnimUtils.ofFloat(mQsbDivider, "alpha", 1f),
LauncherAnimUtils.ofFloat(mDockDivider, "alpha", 1f));
int duration = 0;
if (mSearchDropTargetBar != null) {
duration = mSearchDropTargetBar.getTransitionInDuration();
}
mDividerAnimator.setDuration(duration);
mDividerAnimator.start();
}
}
}
void lockAllApps() {
// TODO
}
void unlockAllApps() {
// TODO
}
/**
* Shows the hotseat area.
*/
void showHotseat(boolean animated) {
if (!LauncherApplication.isScreenLarge()) {
if (animated) {
if (mHotseat.getAlpha() != 1f) {
int duration = 0;
if (mSearchDropTargetBar != null) {
duration = mSearchDropTargetBar.getTransitionInDuration();
}
mHotseat.animate().alpha(1f).setDuration(duration);
}
} else {
mHotseat.setAlpha(1f);
}
}
}
/**
* Hides the hotseat area.
*/
void hideHotseat(boolean animated) {
if (!LauncherApplication.isScreenLarge()) {
if (animated) {
if (mHotseat.getAlpha() != 0f) {
int duration = 0;
if (mSearchDropTargetBar != null) {
duration = mSearchDropTargetBar.getTransitionOutDuration();
}
mHotseat.animate().alpha(0f).setDuration(duration);
}
} else {
mHotseat.setAlpha(0f);
}
}
}
/**
* Add an item from all apps or customize onto the given workspace screen.
* If layout is null, add to the current screen.
*/
void addExternalItemToScreen(ItemInfo itemInfo, final CellLayout layout) {
if (!mWorkspace.addExternalItemToScreen(itemInfo, layout)) {
showOutOfSpaceMessage(isHotseatLayout(layout));
}
}
/** Maps the current orientation to an index for referencing orientation correct global icons */
private int getCurrentOrientationIndexForGlobalIcons() {
// default - 0, landscape - 1
switch (getResources().getConfiguration().orientation) {
case Configuration.ORIENTATION_LANDSCAPE:
return 1;
default:
return 0;
}
}
private Drawable getExternalPackageToolbarIcon(ComponentName activityName, String resourceName) {
try {
PackageManager packageManager = getPackageManager();
// Look for the toolbar icon specified in the activity meta-data
Bundle metaData = packageManager.getActivityInfo(
activityName, PackageManager.GET_META_DATA).metaData;
if (metaData != null) {
int iconResId = metaData.getInt(resourceName);
if (iconResId != 0) {
Resources res = packageManager.getResourcesForActivity(activityName);
return res.getDrawable(iconResId);
}
}
} catch (NameNotFoundException e) {
// This can happen if the activity defines an invalid drawable
Log.w(TAG, "Failed to load toolbar icon; " + activityName.flattenToShortString() +
" not found", e);
} catch (Resources.NotFoundException nfe) {
// This can happen if the activity defines an invalid drawable
Log.w(TAG, "Failed to load toolbar icon from " + activityName.flattenToShortString(),
nfe);
}
return null;
}
// if successful in getting icon, return it; otherwise, set button to use default drawable
private Drawable.ConstantState updateTextButtonWithIconFromExternalActivity(
int buttonId, ComponentName activityName, int fallbackDrawableId,
String toolbarResourceName) {
Drawable toolbarIcon = getExternalPackageToolbarIcon(activityName, toolbarResourceName);
Resources r = getResources();
int w = r.getDimensionPixelSize(R.dimen.toolbar_external_icon_width);
int h = r.getDimensionPixelSize(R.dimen.toolbar_external_icon_height);
TextView button = (TextView) findViewById(buttonId);
// If we were unable to find the icon via the meta-data, use a generic one
if (toolbarIcon == null) {
toolbarIcon = r.getDrawable(fallbackDrawableId);
toolbarIcon.setBounds(0, 0, w, h);
if (button != null) {
button.setCompoundDrawables(toolbarIcon, null, null, null);
}
return null;
} else {
toolbarIcon.setBounds(0, 0, w, h);
if (button != null) {
button.setCompoundDrawables(toolbarIcon, null, null, null);
}
return toolbarIcon.getConstantState();
}
}
// if successful in getting icon, return it; otherwise, set button to use default drawable
private Drawable.ConstantState updateButtonWithIconFromExternalActivity(
int buttonId, ComponentName activityName, int fallbackDrawableId,
String toolbarResourceName) {
ImageView button = (ImageView) findViewById(buttonId);
Drawable toolbarIcon = getExternalPackageToolbarIcon(activityName, toolbarResourceName);
if (button != null) {
// If we were unable to find the icon via the meta-data, use a
// generic one
if (toolbarIcon == null) {
button.setImageResource(fallbackDrawableId);
} else {
button.setImageDrawable(toolbarIcon);
}
}
return toolbarIcon != null ? toolbarIcon.getConstantState() : null;
}
private void updateTextButtonWithDrawable(int buttonId, Drawable d) {
TextView button = (TextView) findViewById(buttonId);
button.setCompoundDrawables(d, null, null, null);
}
private void updateButtonWithDrawable(int buttonId, Drawable.ConstantState d) {
ImageView button = (ImageView) findViewById(buttonId);
button.setImageDrawable(d.newDrawable(getResources()));
}
private void invalidatePressedFocusedStates(View container, View button) {
if (container instanceof HolographicLinearLayout) {
HolographicLinearLayout layout = (HolographicLinearLayout) container;
layout.invalidatePressedFocusedStates();
} else if (button instanceof HolographicImageView) {
HolographicImageView view = (HolographicImageView) button;
view.invalidatePressedFocusedStates();
}
}
private boolean updateGlobalSearchIcon() {
final View searchButtonContainer = findViewById(R.id.search_button_container);
final ImageView searchButton = (ImageView) findViewById(R.id.search_button);
final View voiceButtonContainer = findViewById(R.id.voice_button_container);
final View voiceButton = findViewById(R.id.voice_button);
final View voiceButtonProxy = findViewById(R.id.voice_button_proxy);
final SearchManager searchManager =
(SearchManager) getSystemService(Context.SEARCH_SERVICE);
ComponentName activityName = searchManager.getGlobalSearchActivity();
if (activityName != null) {
int coi = getCurrentOrientationIndexForGlobalIcons();
sGlobalSearchIcon[coi] = updateButtonWithIconFromExternalActivity(
R.id.search_button, activityName, R.drawable.ic_home_search_normal_holo,
TOOLBAR_SEARCH_ICON_METADATA_NAME);
if (sGlobalSearchIcon[coi] == null) {
sGlobalSearchIcon[coi] = updateButtonWithIconFromExternalActivity(
R.id.search_button, activityName, R.drawable.ic_home_search_normal_holo,
TOOLBAR_ICON_METADATA_NAME);
}
if (searchButtonContainer != null) searchButtonContainer.setVisibility(View.VISIBLE);
searchButton.setVisibility(View.VISIBLE);
invalidatePressedFocusedStates(searchButtonContainer, searchButton);
return true;
} else {
// We disable both search and voice search when there is no global search provider
if (searchButtonContainer != null) searchButtonContainer.setVisibility(View.GONE);
if (voiceButtonContainer != null) voiceButtonContainer.setVisibility(View.GONE);
searchButton.setVisibility(View.GONE);
voiceButton.setVisibility(View.GONE);
if (voiceButtonProxy != null) {
voiceButtonProxy.setVisibility(View.GONE);
}
return false;
}
}
private void updateGlobalSearchIcon(Drawable.ConstantState d) {
final View searchButtonContainer = findViewById(R.id.search_button_container);
final View searchButton = (ImageView) findViewById(R.id.search_button);
updateButtonWithDrawable(R.id.search_button, d);
invalidatePressedFocusedStates(searchButtonContainer, searchButton);
}
private boolean updateVoiceSearchIcon(boolean searchVisible) {
final View voiceButtonContainer = findViewById(R.id.voice_button_container);
final View voiceButton = findViewById(R.id.voice_button);
final View voiceButtonProxy = findViewById(R.id.voice_button_proxy);
// We only show/update the voice search icon if the search icon is enabled as well
final SearchManager searchManager =
(SearchManager) getSystemService(Context.SEARCH_SERVICE);
ComponentName globalSearchActivity = searchManager.getGlobalSearchActivity();
ComponentName activityName = null;
if (globalSearchActivity != null) {
// Check if the global search activity handles voice search
Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
intent.setPackage(globalSearchActivity.getPackageName());
activityName = intent.resolveActivity(getPackageManager());
}
if (activityName == null) {
// Fallback: check if an activity other than the global search activity
// resolves this
Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
activityName = intent.resolveActivity(getPackageManager());
}
if (searchVisible && activityName != null) {
int coi = getCurrentOrientationIndexForGlobalIcons();
sVoiceSearchIcon[coi] = updateButtonWithIconFromExternalActivity(
R.id.voice_button, activityName, R.drawable.ic_home_voice_search_holo,
TOOLBAR_VOICE_SEARCH_ICON_METADATA_NAME);
if (sVoiceSearchIcon[coi] == null) {
sVoiceSearchIcon[coi] = updateButtonWithIconFromExternalActivity(
R.id.voice_button, activityName, R.drawable.ic_home_voice_search_holo,
TOOLBAR_ICON_METADATA_NAME);
}
if (voiceButtonContainer != null) voiceButtonContainer.setVisibility(View.VISIBLE);
voiceButton.setVisibility(View.VISIBLE);
if (voiceButtonProxy != null) {
voiceButtonProxy.setVisibility(View.VISIBLE);
}
invalidatePressedFocusedStates(voiceButtonContainer, voiceButton);
return true;
} else {
if (voiceButtonContainer != null) voiceButtonContainer.setVisibility(View.GONE);
voiceButton.setVisibility(View.GONE);
if (voiceButtonProxy != null) {
voiceButtonProxy.setVisibility(View.GONE);
}
return false;
}
}
private void updateVoiceSearchIcon(Drawable.ConstantState d) {
final View voiceButtonContainer = findViewById(R.id.voice_button_container);
final View voiceButton = findViewById(R.id.voice_button);
updateButtonWithDrawable(R.id.voice_button, d);
invalidatePressedFocusedStates(voiceButtonContainer, voiceButton);
}
/**
* Sets the app market icon
*/
private void updateAppMarketIcon() {
final View marketButton = findViewById(R.id.market_button);
Intent intent = new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_APP_MARKET);
// Find the app market activity by resolving an intent.
// (If multiple app markets are installed, it will return the ResolverActivity.)
ComponentName activityName = intent.resolveActivity(getPackageManager());
if (activityName != null) {
int coi = getCurrentOrientationIndexForGlobalIcons();
mAppMarketIntent = intent;
sAppMarketIcon[coi] = updateTextButtonWithIconFromExternalActivity(
R.id.market_button, activityName, R.drawable.ic_launcher_market_holo,
TOOLBAR_ICON_METADATA_NAME);
marketButton.setVisibility(View.VISIBLE);
} else {
// We should hide and disable the view so that we don't try and restore the visibility
// of it when we swap between drag & normal states from IconDropTarget subclasses.
marketButton.setVisibility(View.GONE);
marketButton.setEnabled(false);
}
}
private void updateAppMarketIcon(Drawable.ConstantState d) {
// Ensure that the new drawable we are creating has the approprate toolbar icon bounds
Resources r = getResources();
Drawable marketIconDrawable = d.newDrawable(r);
int w = r.getDimensionPixelSize(R.dimen.toolbar_external_icon_width);
int h = r.getDimensionPixelSize(R.dimen.toolbar_external_icon_height);
marketIconDrawable.setBounds(0, 0, w, h);
updateTextButtonWithDrawable(R.id.market_button, marketIconDrawable);
}
@Override
public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
boolean result = super.dispatchPopulateAccessibilityEvent(event);
final List<CharSequence> text = event.getText();
text.clear();
text.add(getString(R.string.home));
return result;
}
/**
* Receives notifications when system dialogs are to be closed.
*/
private class CloseSystemDialogsIntentReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
closeSystemDialogs();
}
}
/**
* Receives notifications whenever the appwidgets are reset.
*/
private class AppWidgetResetObserver extends ContentObserver {
public AppWidgetResetObserver() {
super(new Handler());
}
@Override
public void onChange(boolean selfChange) {
onAppWidgetReset();
}
}
/**
* If the activity is currently paused, signal that we need to re-run the loader
* in onResume.
*
* This needs to be called from incoming places where resources might have been loaded
* while we are paused. That is becaues the Configuration might be wrong
* when we're not running, and if it comes back to what it was when we
* were paused, we are not restarted.
*
* Implementation of the method from LauncherModel.Callbacks.
*
* @return true if we are currently paused. The caller might be able to
* skip some work in that case since we will come back again.
*/
public boolean setLoadOnResume() {
if (mPaused) {
Log.i(TAG, "setLoadOnResume");
mOnResumeNeedsLoad = true;
return true;
} else {
return false;
}
}
/**
* Implementation of the method from LauncherModel.Callbacks.
*/
public int getCurrentWorkspaceScreen() {
if (mWorkspace != null) {
return mWorkspace.getCurrentPage();
} else {
return SCREEN_COUNT / 2;
}
}
/**
* Refreshes the shortcuts shown on the workspace.
*
* Implementation of the method from LauncherModel.Callbacks.
*/
public void startBinding() {
final Workspace workspace = mWorkspace;
mNewShortcutAnimatePage = -1;
mNewShortcutAnimateViews.clear();
mWorkspace.clearDropTargets();
int count = workspace.getChildCount();
for (int i = 0; i < count; i++) {
// Use removeAllViewsInLayout() to avoid an extra requestLayout() and invalidate().
final CellLayout layoutParent = (CellLayout) workspace.getChildAt(i);
layoutParent.removeAllViewsInLayout();
}
mWidgetsToAdvance.clear();
if (mHotseat != null) {
mHotseat.resetLayout();
}
}
/**
* Bind the items start-end from the list.
*
* Implementation of the method from LauncherModel.Callbacks.
*/
public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end) {
setLoadOnResume();
// Get the list of added shortcuts and intersect them with the set of shortcuts here
Set<String> newApps = new HashSet<String>();
newApps = mSharedPrefs.getStringSet(InstallShortcutReceiver.NEW_APPS_LIST_KEY, newApps);
Workspace workspace = mWorkspace;
for (int i = start; i < end; i++) {
final ItemInfo item = shortcuts.get(i);
// Short circuit if we are loading dock items for a configuration which has no dock
if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT &&
mHotseat == null) {
continue;
}
switch (item.itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
ShortcutInfo info = (ShortcutInfo) item;
String uri = info.intent.toUri(0).toString();
View shortcut = createShortcut(info);
workspace.addInScreen(shortcut, item.container, item.screen, item.cellX,
item.cellY, 1, 1, false);
boolean animateIconUp = false;
synchronized (newApps) {
if (newApps.contains(uri)) {
animateIconUp = newApps.remove(uri);
}
}
if (animateIconUp) {
// Prepare the view to be animated up
shortcut.setAlpha(0f);
shortcut.setScaleX(0f);
shortcut.setScaleY(0f);
mNewShortcutAnimatePage = item.screen;
if (!mNewShortcutAnimateViews.contains(shortcut)) {
mNewShortcutAnimateViews.add(shortcut);
}
}
break;
case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
FolderIcon newFolder = FolderIcon.fromXml(R.layout.folder_icon, this,
(ViewGroup) workspace.getChildAt(workspace.getCurrentPage()),
(FolderInfo) item, mIconCache);
workspace.addInScreen(newFolder, item.container, item.screen, item.cellX,
item.cellY, 1, 1, false);
break;
}
}
workspace.requestLayout();
}
/**
* Implementation of the method from LauncherModel.Callbacks.
*/
public void bindFolders(HashMap<Long, FolderInfo> folders) {
setLoadOnResume();
sFolders.clear();
sFolders.putAll(folders);
}
/**
* Add the views for a widget to the workspace.
*
* Implementation of the method from LauncherModel.Callbacks.
*/
public void bindAppWidget(LauncherAppWidgetInfo item) {
setLoadOnResume();
final long start = DEBUG_WIDGETS ? SystemClock.uptimeMillis() : 0;
if (DEBUG_WIDGETS) {
Log.d(TAG, "bindAppWidget: " + item);
}
final Workspace workspace = mWorkspace;
final int appWidgetId = item.appWidgetId;
final AppWidgetProviderInfo appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(appWidgetId);
if (DEBUG_WIDGETS) {
Log.d(TAG, "bindAppWidget: id=" + item.appWidgetId + " belongs to component " + appWidgetInfo.provider);
}
item.hostView = mAppWidgetHost.createView(this, appWidgetId, appWidgetInfo);
item.hostView.setTag(item);
item.onBindAppWidget(this);
workspace.addInScreen(item.hostView, item.container, item.screen, item.cellX,
item.cellY, item.spanX, item.spanY, false);
addWidgetToAutoAdvanceIfNeeded(item.hostView, appWidgetInfo);
workspace.requestLayout();
if (DEBUG_WIDGETS) {
Log.d(TAG, "bound widget id="+item.appWidgetId+" in "
+ (SystemClock.uptimeMillis()-start) + "ms");
}
}
public void onPageBoundSynchronously(int page) {
mSynchronouslyBoundPages.add(page);
}
/**
* Callback saying that there aren't any more items to bind.
*
* Implementation of the method from LauncherModel.Callbacks.
*/
public void finishBindingItems() {
setLoadOnResume();
if (mSavedState != null) {
if (!mWorkspace.hasFocus()) {
mWorkspace.getChildAt(mWorkspace.getCurrentPage()).requestFocus();
}
mSavedState = null;
}
mWorkspace.restoreInstanceStateForRemainingPages();
// If we received the result of any pending adds while the loader was running (e.g. the
// widget configuration forced an orientation change), process them now.
for (int i = 0; i < sPendingAddList.size(); i++) {
completeAdd(sPendingAddList.get(i));
}
sPendingAddList.clear();
// Update the market app icon as necessary (the other icons will be managed in response to
// package changes in bindSearchablesChanged()
updateAppMarketIcon();
// Animate up any icons as necessary
if (mVisible || mWorkspaceLoading) {
Runnable newAppsRunnable = new Runnable() {
@Override
public void run() {
runNewAppsAnimation(false);
}
};
boolean willSnapPage = mNewShortcutAnimatePage > -1 &&
mNewShortcutAnimatePage != mWorkspace.getCurrentPage();
if (canRunNewAppsAnimation()) {
// If the user has not interacted recently, then either snap to the new page to show
// the new-apps animation or just run them if they are to appear on the current page
if (willSnapPage) {
mWorkspace.snapToPage(mNewShortcutAnimatePage, newAppsRunnable);
} else {
runNewAppsAnimation(false);
}
} else {
// If the user has interacted recently, then just add the items in place if they
// are on another page (or just normally if they are added to the current page)
runNewAppsAnimation(willSnapPage);
}
}
mWorkspaceLoading = false;
}
private boolean canRunNewAppsAnimation() {
long diff = System.currentTimeMillis() - mDragController.getLastGestureUpTime();
return diff > (NEW_APPS_ANIMATION_INACTIVE_TIMEOUT_SECONDS * 1000);
}
/**
* Runs a new animation that scales up icons that were added while Launcher was in the
* background.
*
* @param immediate whether to run the animation or show the results immediately
*/
private void runNewAppsAnimation(boolean immediate) {
AnimatorSet anim = LauncherAnimUtils.createAnimatorSet();
Collection<Animator> bounceAnims = new ArrayList<Animator>();
// Order these new views spatially so that they animate in order
Collections.sort(mNewShortcutAnimateViews, new Comparator<View>() {
@Override
public int compare(View a, View b) {
CellLayout.LayoutParams alp = (CellLayout.LayoutParams) a.getLayoutParams();
CellLayout.LayoutParams blp = (CellLayout.LayoutParams) b.getLayoutParams();
int cellCountX = LauncherModel.getCellCountX();
return (alp.cellY * cellCountX + alp.cellX) - (blp.cellY * cellCountX + blp.cellX);
}
});
// Animate each of the views in place (or show them immediately if requested)
if (immediate) {
for (View v : mNewShortcutAnimateViews) {
v.setAlpha(1f);
v.setScaleX(1f);
v.setScaleY(1f);
}
} else {
for (int i = 0; i < mNewShortcutAnimateViews.size(); ++i) {
View v = mNewShortcutAnimateViews.get(i);
ValueAnimator bounceAnim = LauncherAnimUtils.ofPropertyValuesHolder(v,
PropertyValuesHolder.ofFloat("alpha", 1f),
PropertyValuesHolder.ofFloat("scaleX", 1f),
PropertyValuesHolder.ofFloat("scaleY", 1f));
bounceAnim.setDuration(InstallShortcutReceiver.NEW_SHORTCUT_BOUNCE_DURATION);
bounceAnim.setStartDelay(i * InstallShortcutReceiver.NEW_SHORTCUT_STAGGER_DELAY);
bounceAnim.setInterpolator(new SmoothPagedView.OvershootInterpolator());
bounceAnims.add(bounceAnim);
}
anim.playTogether(bounceAnims);
anim.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mWorkspace.postDelayed(mBuildLayersRunnable, 500);
}
});
anim.start();
}
// Clean up
mNewShortcutAnimatePage = -1;
mNewShortcutAnimateViews.clear();
new Thread("clearNewAppsThread") {
public void run() {
mSharedPrefs.edit()
.putInt(InstallShortcutReceiver.NEW_APPS_PAGE_KEY, -1)
.putStringSet(InstallShortcutReceiver.NEW_APPS_LIST_KEY, null)
.commit();
}
}.start();
}
@Override
public void bindSearchablesChanged() {
boolean searchVisible = updateGlobalSearchIcon();
boolean voiceVisible = updateVoiceSearchIcon(searchVisible);
if (mSearchDropTargetBar != null) {
mSearchDropTargetBar.onSearchPackagesChanged(searchVisible, voiceVisible);
}
}
/**
* Add the icons for all apps.
*
* Implementation of the method from LauncherModel.Callbacks.
*/
public void bindAllApplications(final ArrayList<ApplicationInfo> apps) {
Runnable setAllAppsRunnable = new Runnable() {
public void run() {
if (mAppsCustomizeContent != null) {
mAppsCustomizeContent.setApps(apps);
}
}
};
// Remove the progress bar entirely; we could also make it GONE
// but better to remove it since we know it's not going to be used
View progressBar = mAppsCustomizeTabHost.
findViewById(R.id.apps_customize_progress_bar);
if (progressBar != null) {
((ViewGroup)progressBar.getParent()).removeView(progressBar);
// We just post the call to setApps so the user sees the progress bar
// disappear-- otherwise, it just looks like the progress bar froze
// which doesn't look great
mAppsCustomizeTabHost.post(setAllAppsRunnable);
} else {
// If we did not initialize the spinner in onCreate, then we can directly set the
// list of applications without waiting for any progress bars views to be hidden.
setAllAppsRunnable.run();
}
}
/**
* A package was installed.
*
* Implementation of the method from LauncherModel.Callbacks.
*/
public void bindAppsAdded(ArrayList<ApplicationInfo> apps) {
setLoadOnResume();
if (mAppsCustomizeContent != null) {
mAppsCustomizeContent.addApps(apps);
}
}
/**
* A package was updated.
*
* Implementation of the method from LauncherModel.Callbacks.
*/
public void bindAppsUpdated(ArrayList<ApplicationInfo> apps) {
setLoadOnResume();
if (mWorkspace != null) {
mWorkspace.updateShortcuts(apps);
}
if (mAppsCustomizeContent != null) {
mAppsCustomizeContent.updateApps(apps);
}
}
/**
* A package was uninstalled.
*
* Implementation of the method from LauncherModel.Callbacks.
*/
public void bindAppsRemoved(ArrayList<String> packageNames, boolean permanent) {
if (permanent) {
mWorkspace.removeItems(packageNames);
}
if (mAppsCustomizeContent != null) {
mAppsCustomizeContent.removeApps(packageNames);
}
// Notify the drag controller
mDragController.onAppsRemoved(packageNames, this);
}
/**
* A number of packages were updated.
*/
public void bindPackagesUpdated() {
if (mAppsCustomizeContent != null) {
mAppsCustomizeContent.onPackagesUpdated();
}
}
private int mapConfigurationOriActivityInfoOri(int configOri) {
final Display d = getWindowManager().getDefaultDisplay();
int naturalOri = Configuration.ORIENTATION_LANDSCAPE;
switch (d.getRotation()) {
case Surface.ROTATION_0:
case Surface.ROTATION_180:
// We are currently in the same basic orientation as the natural orientation
naturalOri = configOri;
break;
case Surface.ROTATION_90:
case Surface.ROTATION_270:
// We are currently in the other basic orientation to the natural orientation
naturalOri = (configOri == Configuration.ORIENTATION_LANDSCAPE) ?
Configuration.ORIENTATION_PORTRAIT : Configuration.ORIENTATION_LANDSCAPE;
break;
}
int[] oriMap = {
ActivityInfo.SCREEN_ORIENTATION_PORTRAIT,
ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE,
ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT,
ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE
};
// Since the map starts at portrait, we need to offset if this device's natural orientation
// is landscape.
int indexOffset = 0;
if (naturalOri == Configuration.ORIENTATION_LANDSCAPE) {
indexOffset = 1;
}
return oriMap[(d.getRotation() + indexOffset) % 4];
}
public boolean isRotationEnabled() {
boolean forceEnableRotation = doesFileExist(FORCE_ENABLE_ROTATION_PROPERTY);
boolean enableRotation = forceEnableRotation ||
getResources().getBoolean(R.bool.allow_rotation);
return enableRotation;
}
public void lockScreenOrientation() {
if (isRotationEnabled()) {
setRequestedOrientation(mapConfigurationOriActivityInfoOri(getResources()
.getConfiguration().orientation));
}
}
public void unlockScreenOrientation(boolean immediate) {
if (isRotationEnabled()) {
if (immediate) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
} else {
mHandler.postDelayed(new Runnable() {
public void run() {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
}
}, mRestoreScreenOrientationDelay);
}
}
}
/* Cling related */
private boolean isClingsEnabled() {
// disable clings when running in a test harness
if(ActivityManager.isRunningInTestHarness()) return false;
return true;
}
private Cling initCling(int clingId, int[] positionData, boolean animate, int delay) {
Cling cling = (Cling) findViewById(clingId);
if (cling != null) {
cling.init(this, positionData);
cling.setVisibility(View.VISIBLE);
cling.setLayerType(View.LAYER_TYPE_HARDWARE, null);
if (animate) {
cling.buildLayer();
cling.setAlpha(0f);
cling.animate()
.alpha(1f)
.setInterpolator(new AccelerateInterpolator())
.setDuration(SHOW_CLING_DURATION)
.setStartDelay(delay)
.start();
} else {
cling.setAlpha(1f);
}
}
return cling;
}
private void dismissCling(final Cling cling, final String flag, int duration) {
if (cling != null) {
ObjectAnimator anim = LauncherAnimUtils.ofFloat(cling, "alpha", 0f);
anim.setDuration(duration);
anim.addListener(new AnimatorListenerAdapter() {
public void onAnimationEnd(Animator animation) {
cling.setVisibility(View.GONE);
cling.cleanup();
// We should update the shared preferences on a background thread
new Thread("dismissClingThread") {
public void run() {
SharedPreferences.Editor editor = mSharedPrefs.edit();
editor.putBoolean(flag, true);
editor.commit();
}
}.start();
};
});
anim.start();
}
}
private void removeCling(int id) {
final View cling = findViewById(id);
if (cling != null) {
final ViewGroup parent = (ViewGroup) cling.getParent();
parent.post(new Runnable() {
@Override
public void run() {
parent.removeView(cling);
}
});
}
}
private boolean skipCustomClingIfNoAccounts() {
Cling cling = (Cling) findViewById(R.id.workspace_cling);
boolean customCling = cling.getDrawIdentifier().equals("workspace_custom");
if (customCling) {
AccountManager am = AccountManager.get(this);
Account[] accounts = am.getAccountsByType("com.google");
return accounts.length == 0;
}
return false;
}
public void showFirstRunWorkspaceCling() {
// Enable the clings only if they have not been dismissed before
if (isClingsEnabled() &&
!mSharedPrefs.getBoolean(Cling.WORKSPACE_CLING_DISMISSED_KEY, false) &&
!skipCustomClingIfNoAccounts() ) {
initCling(R.id.workspace_cling, null, false, 0);
} else {
removeCling(R.id.workspace_cling);
}
}
public void showFirstRunAllAppsCling(int[] position) {
// Enable the clings only if they have not been dismissed before
if (isClingsEnabled() &&
!mSharedPrefs.getBoolean(Cling.ALLAPPS_CLING_DISMISSED_KEY, false)) {
initCling(R.id.all_apps_cling, position, true, 0);
} else {
removeCling(R.id.all_apps_cling);
}
}
public Cling showFirstRunFoldersCling() {
// Enable the clings only if they have not been dismissed before
if (isClingsEnabled() &&
!mSharedPrefs.getBoolean(Cling.FOLDER_CLING_DISMISSED_KEY, false)) {
return initCling(R.id.folder_cling, null, true, 0);
} else {
removeCling(R.id.folder_cling);
return null;
}
}
public boolean isFolderClingVisible() {
Cling cling = (Cling) findViewById(R.id.folder_cling);
if (cling != null) {
return cling.getVisibility() == View.VISIBLE;
}
return false;
}
public void dismissWorkspaceCling(View v) {
Cling cling = (Cling) findViewById(R.id.workspace_cling);
dismissCling(cling, Cling.WORKSPACE_CLING_DISMISSED_KEY, DISMISS_CLING_DURATION);
}
public void dismissAllAppsCling(View v) {
Cling cling = (Cling) findViewById(R.id.all_apps_cling);
dismissCling(cling, Cling.ALLAPPS_CLING_DISMISSED_KEY, DISMISS_CLING_DURATION);
}
public void dismissFolderCling(View v) {
Cling cling = (Cling) findViewById(R.id.folder_cling);
dismissCling(cling, Cling.FOLDER_CLING_DISMISSED_KEY, DISMISS_CLING_DURATION);
}
/**
* Prints out out state for debugging.
*/
public void dumpState() {
Log.d(TAG, "BEGIN launcher2 dump state for launcher " + this);
Log.d(TAG, "mSavedState=" + mSavedState);
Log.d(TAG, "mWorkspaceLoading=" + mWorkspaceLoading);
Log.d(TAG, "mRestoring=" + mRestoring);
Log.d(TAG, "mWaitingForResult=" + mWaitingForResult);
Log.d(TAG, "mSavedInstanceState=" + mSavedInstanceState);
Log.d(TAG, "sFolders.size=" + sFolders.size());
mModel.dumpState();
if (mAppsCustomizeContent != null) {
mAppsCustomizeContent.dumpState();
}
Log.d(TAG, "END launcher2 dump state");
}
@Override
public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
super.dump(prefix, fd, writer, args);
writer.println(" ");
writer.println("Debug logs: ");
for (int i = 0; i < sDumpLogs.size(); i++) {
writer.println(" " + sDumpLogs.get(i));
}
}
public static void dumpDebugLogsToConsole() {
Log.d(TAG, "");
Log.d(TAG, "*********************");
Log.d(TAG, "Launcher debug logs: ");
for (int i = 0; i < sDumpLogs.size(); i++) {
Log.d(TAG, " " + sDumpLogs.get(i));
}
Log.d(TAG, "*********************");
Log.d(TAG, "");
}
}
interface LauncherTransitionable {
View getContent();
void onLauncherTransitionPrepare(Launcher l, boolean animated, boolean toWorkspace);
void onLauncherTransitionStart(Launcher l, boolean animated, boolean toWorkspace);
void onLauncherTransitionStep(Launcher l, float t);
void onLauncherTransitionEnd(Launcher l, boolean animated, boolean toWorkspace);
}
| true | true | private void showAppsCustomizeHelper(final boolean animated, final boolean springLoaded) {
if (mStateAnimation != null) {
mStateAnimation.cancel();
mStateAnimation = null;
}
final Resources res = getResources();
final int duration = res.getInteger(R.integer.config_appsCustomizeZoomInTime);
final int fadeDuration = res.getInteger(R.integer.config_appsCustomizeFadeInTime);
final float scale = (float) res.getInteger(R.integer.config_appsCustomizeZoomScaleFactor);
final View fromView = mWorkspace;
final AppsCustomizeTabHost toView = mAppsCustomizeTabHost;
final int startDelay =
res.getInteger(R.integer.config_workspaceAppsCustomizeAnimationStagger);
setPivotsForZoom(toView, scale);
// Shrink workspaces away if going to AppsCustomize from workspace
Animator workspaceAnim =
mWorkspace.getChangeStateAnimation(Workspace.State.SMALL, animated);
if (animated) {
toView.setScaleX(scale);
toView.setScaleY(scale);
final LauncherViewPropertyAnimator scaleAnim = new LauncherViewPropertyAnimator(toView);
scaleAnim.
scaleX(1f).scaleY(1f).
setDuration(duration).
setInterpolator(new Workspace.ZoomOutInterpolator());
toView.setVisibility(View.VISIBLE);
toView.setAlpha(0f);
final ObjectAnimator alphaAnim = ObjectAnimator
.ofFloat(toView, "alpha", 0f, 1f)
.setDuration(fadeDuration);
alphaAnim.setInterpolator(new DecelerateInterpolator(1.5f));
alphaAnim.addUpdateListener(new AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
if (animation == null) {
throw new RuntimeException("animation is null");
}
float t = (Float) animation.getAnimatedValue();
dispatchOnLauncherTransitionStep(fromView, t);
dispatchOnLauncherTransitionStep(toView, t);
}
});
// toView should appear right at the end of the workspace shrink
// animation
mStateAnimation = LauncherAnimUtils.createAnimatorSet();
mStateAnimation.play(scaleAnim).after(startDelay);
mStateAnimation.play(alphaAnim).after(startDelay);
mStateAnimation.addListener(new AnimatorListenerAdapter() {
boolean animationCancelled = false;
@Override
public void onAnimationStart(Animator animation) {
updateWallpaperVisibility(true);
// Prepare the position
toView.setTranslationX(0.0f);
toView.setTranslationY(0.0f);
toView.setVisibility(View.VISIBLE);
toView.bringToFront();
}
@Override
public void onAnimationEnd(Animator animation) {
dispatchOnLauncherTransitionEnd(fromView, animated, false);
dispatchOnLauncherTransitionEnd(toView, animated, false);
if (!springLoaded && !LauncherApplication.isScreenLarge()) {
// Hide the workspace scrollbar
mWorkspace.hideScrollingIndicator(true);
hideDockDivider();
}
if (!animationCancelled) {
updateWallpaperVisibility(false);
}
// Hide the search bar
if (mSearchDropTargetBar != null) {
mSearchDropTargetBar.hideSearchBar(false);
}
}
@Override
public void onAnimationCancel(Animator animation) {
animationCancelled = true;
}
});
if (workspaceAnim != null) {
mStateAnimation.play(workspaceAnim);
}
boolean delayAnim = false;
final ViewTreeObserver observer;
dispatchOnLauncherTransitionPrepare(fromView, animated, false);
dispatchOnLauncherTransitionPrepare(toView, animated, false);
// If any of the objects being animated haven't been measured/laid out
// yet, delay the animation until we get a layout pass
if ((((LauncherTransitionable) toView).getContent().getMeasuredWidth() == 0) ||
(mWorkspace.getMeasuredWidth() == 0) ||
(toView.getMeasuredWidth() == 0)) {
observer = mWorkspace.getViewTreeObserver();
delayAnim = true;
} else {
observer = null;
}
final AnimatorSet stateAnimation = mStateAnimation;
final Runnable startAnimRunnable = new Runnable() {
public void run() {
// Check that mStateAnimation hasn't changed while
// we waited for a layout/draw pass
if (mStateAnimation != stateAnimation)
return;
setPivotsForZoom(toView, scale);
dispatchOnLauncherTransitionStart(fromView, animated, false);
dispatchOnLauncherTransitionStart(toView, animated, false);
toView.post(new Runnable() {
public void run() {
// Check that mStateAnimation hasn't changed while
// we waited for a layout/draw pass
if (mStateAnimation != stateAnimation)
return;
mStateAnimation.start();
}
});
}
};
if (delayAnim) {
final OnGlobalLayoutListener delayedStart = new OnGlobalLayoutListener() {
public void onGlobalLayout() {
toView.post(startAnimRunnable);
observer.removeOnGlobalLayoutListener(this);
}
};
observer.addOnGlobalLayoutListener(delayedStart);
} else {
startAnimRunnable.run();
}
} else {
toView.setTranslationX(0.0f);
toView.setTranslationY(0.0f);
toView.setScaleX(1.0f);
toView.setScaleY(1.0f);
toView.setVisibility(View.VISIBLE);
toView.bringToFront();
if (!springLoaded && !LauncherApplication.isScreenLarge()) {
// Hide the workspace scrollbar
mWorkspace.hideScrollingIndicator(true);
hideDockDivider();
// Hide the search bar
if (mSearchDropTargetBar != null) {
mSearchDropTargetBar.hideSearchBar(false);
}
}
dispatchOnLauncherTransitionPrepare(fromView, animated, false);
dispatchOnLauncherTransitionStart(fromView, animated, false);
dispatchOnLauncherTransitionEnd(fromView, animated, false);
dispatchOnLauncherTransitionPrepare(toView, animated, false);
dispatchOnLauncherTransitionStart(toView, animated, false);
dispatchOnLauncherTransitionEnd(toView, animated, false);
updateWallpaperVisibility(false);
}
}
| private void showAppsCustomizeHelper(final boolean animated, final boolean springLoaded) {
if (mStateAnimation != null) {
mStateAnimation.cancel();
mStateAnimation = null;
}
final Resources res = getResources();
final int duration = res.getInteger(R.integer.config_appsCustomizeZoomInTime);
final int fadeDuration = res.getInteger(R.integer.config_appsCustomizeFadeInTime);
final float scale = (float) res.getInteger(R.integer.config_appsCustomizeZoomScaleFactor);
final View fromView = mWorkspace;
final AppsCustomizeTabHost toView = mAppsCustomizeTabHost;
final int startDelay =
res.getInteger(R.integer.config_workspaceAppsCustomizeAnimationStagger);
setPivotsForZoom(toView, scale);
// Shrink workspaces away if going to AppsCustomize from workspace
Animator workspaceAnim =
mWorkspace.getChangeStateAnimation(Workspace.State.SMALL, animated);
if (animated) {
toView.setScaleX(scale);
toView.setScaleY(scale);
final LauncherViewPropertyAnimator scaleAnim = new LauncherViewPropertyAnimator(toView);
scaleAnim.
scaleX(1f).scaleY(1f).
setDuration(duration).
setInterpolator(new Workspace.ZoomOutInterpolator());
toView.setVisibility(View.VISIBLE);
toView.setAlpha(0f);
final ObjectAnimator alphaAnim = ObjectAnimator
.ofFloat(toView, "alpha", 0f, 1f)
.setDuration(fadeDuration);
alphaAnim.setInterpolator(new DecelerateInterpolator(1.5f));
alphaAnim.addUpdateListener(new AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
if (animation == null) {
throw new RuntimeException("animation is null");
}
float t = (Float) animation.getAnimatedValue();
dispatchOnLauncherTransitionStep(fromView, t);
dispatchOnLauncherTransitionStep(toView, t);
}
});
// toView should appear right at the end of the workspace shrink
// animation
mStateAnimation = LauncherAnimUtils.createAnimatorSet();
mStateAnimation.play(scaleAnim).after(startDelay);
mStateAnimation.play(alphaAnim).after(startDelay);
mStateAnimation.addListener(new AnimatorListenerAdapter() {
boolean animationCancelled = false;
@Override
public void onAnimationStart(Animator animation) {
updateWallpaperVisibility(true);
// Prepare the position
toView.setTranslationX(0.0f);
toView.setTranslationY(0.0f);
toView.setVisibility(View.VISIBLE);
toView.bringToFront();
}
@Override
public void onAnimationEnd(Animator animation) {
dispatchOnLauncherTransitionEnd(fromView, animated, false);
dispatchOnLauncherTransitionEnd(toView, animated, false);
if (mWorkspace != null && !springLoaded && !LauncherApplication.isScreenLarge()) {
// Hide the workspace scrollbar
mWorkspace.hideScrollingIndicator(true);
hideDockDivider();
}
if (!animationCancelled) {
updateWallpaperVisibility(false);
}
// Hide the search bar
if (mSearchDropTargetBar != null) {
mSearchDropTargetBar.hideSearchBar(false);
}
}
@Override
public void onAnimationCancel(Animator animation) {
animationCancelled = true;
}
});
if (workspaceAnim != null) {
mStateAnimation.play(workspaceAnim);
}
boolean delayAnim = false;
final ViewTreeObserver observer;
dispatchOnLauncherTransitionPrepare(fromView, animated, false);
dispatchOnLauncherTransitionPrepare(toView, animated, false);
// If any of the objects being animated haven't been measured/laid out
// yet, delay the animation until we get a layout pass
if ((((LauncherTransitionable) toView).getContent().getMeasuredWidth() == 0) ||
(mWorkspace.getMeasuredWidth() == 0) ||
(toView.getMeasuredWidth() == 0)) {
observer = mWorkspace.getViewTreeObserver();
delayAnim = true;
} else {
observer = null;
}
final AnimatorSet stateAnimation = mStateAnimation;
final Runnable startAnimRunnable = new Runnable() {
public void run() {
// Check that mStateAnimation hasn't changed while
// we waited for a layout/draw pass
if (mStateAnimation != stateAnimation)
return;
setPivotsForZoom(toView, scale);
dispatchOnLauncherTransitionStart(fromView, animated, false);
dispatchOnLauncherTransitionStart(toView, animated, false);
toView.post(new Runnable() {
public void run() {
// Check that mStateAnimation hasn't changed while
// we waited for a layout/draw pass
if (mStateAnimation != stateAnimation)
return;
mStateAnimation.start();
}
});
}
};
if (delayAnim) {
final OnGlobalLayoutListener delayedStart = new OnGlobalLayoutListener() {
public void onGlobalLayout() {
toView.post(startAnimRunnable);
observer.removeOnGlobalLayoutListener(this);
}
};
observer.addOnGlobalLayoutListener(delayedStart);
} else {
startAnimRunnable.run();
}
} else {
toView.setTranslationX(0.0f);
toView.setTranslationY(0.0f);
toView.setScaleX(1.0f);
toView.setScaleY(1.0f);
toView.setVisibility(View.VISIBLE);
toView.bringToFront();
if (!springLoaded && !LauncherApplication.isScreenLarge()) {
// Hide the workspace scrollbar
mWorkspace.hideScrollingIndicator(true);
hideDockDivider();
// Hide the search bar
if (mSearchDropTargetBar != null) {
mSearchDropTargetBar.hideSearchBar(false);
}
}
dispatchOnLauncherTransitionPrepare(fromView, animated, false);
dispatchOnLauncherTransitionStart(fromView, animated, false);
dispatchOnLauncherTransitionEnd(fromView, animated, false);
dispatchOnLauncherTransitionPrepare(toView, animated, false);
dispatchOnLauncherTransitionStart(toView, animated, false);
dispatchOnLauncherTransitionEnd(toView, animated, false);
updateWallpaperVisibility(false);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.