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/no/arcticdrakefox/wolfbot/roles/Wolf.java b/src/no/arcticdrakefox/wolfbot/roles/Wolf.java
index 6f94e6e..ac1d4af 100644
--- a/src/no/arcticdrakefox/wolfbot/roles/Wolf.java
+++ b/src/no/arcticdrakefox/wolfbot/roles/Wolf.java
@@ -1,94 +1,98 @@
package no.arcticdrakefox.wolfbot.roles;
import no.arcticdrakefox.wolfbot.management.*;
import no.arcticdrakefox.wolfbot.model.Role;
import no.arcticdrakefox.wolfbot.model.Team;
import no.arcticdrakefox.wolfbot.model.WolfBotModel;
public class Wolf extends Player {
private boolean ill = false;
public boolean isIll() {
return ill;
}
public void setIll(boolean ill) {
this.ill = ill;
}
public Wolf(String name){
super(name);
setTeam (Team.Wolves);
}
@Override
public boolean isWolf() {
return true;
}
@Override
public Role getRole() {
return Role.wolf;
}
@Override
public String roleInfo(PlayerList players) {
return String.format("You're a werewolf! The wolves are %s",
StringHandler.listToString(players.getWolves())
);
}
@Override
public String nightStart() {
isReady = false;
if (ill) {
return "Something you ate last night did not agree with you. You rest till you feel better";
} else {
return "As a wolf, you can !kill someone tonight or just !rest";
}
}
@Override
public String nightAction(String message, PlayerList players) {
if (!ill) {
String[] args = message.trim().split(" ", 2);
if (args[0].equals("!kill")) {
if (args.length != 2)
return "Correct usage: !kill <someone>";
Player target = players.getPlayer(args[1]);
if (target == null)
return targetNotFound(args[1]);
else {
if (target.equals(this)) {
return "Killing yourself doesn't seem very productive.";
} else if (target.isAlive()) {
vote(target);
isReady = true;
return String
.format("You sharpen your fangs. They will taste %s's blood tonight!",
target);
} else
return String.format("%s is already dead.", target);
}
} else if (args[0].equals("!rest")) {
isReady = true;
vote = null;
return "You decide to quell your bloodlust tonight.";
} else
return null;
- } else return null;
+ } else {
+ isReady = true;
+ vote = null;
+ return null;
+ }
}
@Override
public String nightEnd() {
ill = false;
return null;
}
@Override
public String helpText() {
// TODO Auto-generated method stub
return null;
}
}
| true | true | public String nightAction(String message, PlayerList players) {
if (!ill) {
String[] args = message.trim().split(" ", 2);
if (args[0].equals("!kill")) {
if (args.length != 2)
return "Correct usage: !kill <someone>";
Player target = players.getPlayer(args[1]);
if (target == null)
return targetNotFound(args[1]);
else {
if (target.equals(this)) {
return "Killing yourself doesn't seem very productive.";
} else if (target.isAlive()) {
vote(target);
isReady = true;
return String
.format("You sharpen your fangs. They will taste %s's blood tonight!",
target);
} else
return String.format("%s is already dead.", target);
}
} else if (args[0].equals("!rest")) {
isReady = true;
vote = null;
return "You decide to quell your bloodlust tonight.";
} else
return null;
} else return null;
}
| public String nightAction(String message, PlayerList players) {
if (!ill) {
String[] args = message.trim().split(" ", 2);
if (args[0].equals("!kill")) {
if (args.length != 2)
return "Correct usage: !kill <someone>";
Player target = players.getPlayer(args[1]);
if (target == null)
return targetNotFound(args[1]);
else {
if (target.equals(this)) {
return "Killing yourself doesn't seem very productive.";
} else if (target.isAlive()) {
vote(target);
isReady = true;
return String
.format("You sharpen your fangs. They will taste %s's blood tonight!",
target);
} else
return String.format("%s is already dead.", target);
}
} else if (args[0].equals("!rest")) {
isReady = true;
vote = null;
return "You decide to quell your bloodlust tonight.";
} else
return null;
} else {
isReady = true;
vote = null;
return null;
}
}
|
diff --git a/vizmap-impl/impl/src/main/java/org/cytoscape/view/vizmap/internal/mappings/ContinuousMappingImpl.java b/vizmap-impl/impl/src/main/java/org/cytoscape/view/vizmap/internal/mappings/ContinuousMappingImpl.java
index 42da90e27..60c7e132c 100644
--- a/vizmap-impl/impl/src/main/java/org/cytoscape/view/vizmap/internal/mappings/ContinuousMappingImpl.java
+++ b/vizmap-impl/impl/src/main/java/org/cytoscape/view/vizmap/internal/mappings/ContinuousMappingImpl.java
@@ -1,247 +1,248 @@
package org.cytoscape.view.vizmap.internal.mappings;
/*
* #%L
* Cytoscape VizMap Impl (vizmap-impl)
* $Id:$
* $HeadURL:$
* %%
* Copyright (C) 2006 - 2013 The Cytoscape Consortium
* %%
* This program 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 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 Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.awt.Color;
import java.awt.Paint;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.cytoscape.event.CyEventHelper;
import org.cytoscape.model.CyRow;
import org.cytoscape.view.model.VisualProperty;
import org.cytoscape.view.vizmap.VisualMappingFunction;
import org.cytoscape.view.vizmap.events.VisualMappingFunctionChangeRecord;
import org.cytoscape.view.vizmap.events.VisualMappingFunctionChangedEvent;
import org.cytoscape.view.vizmap.internal.mappings.interpolators.FlatInterpolator;
import org.cytoscape.view.vizmap.internal.mappings.interpolators.Interpolator;
import org.cytoscape.view.vizmap.internal.mappings.interpolators.LinearNumberToColorInterpolator;
import org.cytoscape.view.vizmap.internal.mappings.interpolators.LinearNumberToNumberInterpolator;
import org.cytoscape.view.vizmap.mappings.AbstractVisualMappingFunction;
import org.cytoscape.view.vizmap.mappings.BoundaryRangeValues;
import org.cytoscape.view.vizmap.mappings.ContinuousMapping;
import org.cytoscape.view.vizmap.mappings.ContinuousMappingPoint;
/**
* Implements an interpolation table mapping data to values of a particular
* class. The data value is extracted from a bundle of attributes by using a
* specified data attribute name.
*
* @param <V>
* Type of object Visual Property holds
*
* For refactoring changes in this class, please refer to:
* cytoscape.visual.mappings.continuous.README.txt.
*
*/
public class ContinuousMappingImpl<K, V> extends AbstractVisualMappingFunction<K, V> implements ContinuousMapping<K, V> {
// used to interpolate between boundaries
private Interpolator<K, V> interpolator;
// Contains List of Data Points
private List<ContinuousMappingPoint<K, V>> points;
@SuppressWarnings({ "unchecked", "rawtypes" })
public ContinuousMappingImpl(final String attrName, final Class<K> attrType, final VisualProperty<V> vp, final CyEventHelper eventHelper) {
super(attrName, attrType, vp, eventHelper);
// Validate type. K is always a number.
if (Number.class.isAssignableFrom(attrType) == false)
throw new IllegalArgumentException("Column type should be Number.");
this.points = new ArrayList<ContinuousMappingPoint<K, V>>();
// TODO FIXME use factory here.
// Create Interpolator
if (vp.getRange().getType() == Color.class || vp.getRange().getType() == Paint.class)
interpolator = (Interpolator<K, V>) new LinearNumberToColorInterpolator();
else if (Number.class.isAssignableFrom(vp.getRange().getType()))
interpolator = (Interpolator<K, V>) new LinearNumberToNumberInterpolator();
else
interpolator = (Interpolator<K, V>) new FlatInterpolator();
}
@Override
public String toString() {
return ContinuousMapping.CONTINUOUS;
}
@Override
public List<ContinuousMappingPoint<K, V>> getAllPoints() {
return Collections.unmodifiableList(points);
}
@Override
public void addPoint(K value, BoundaryRangeValues<V> brv) {
points.add(new ContinuousMappingPoint<K, V>(value, brv, this, eventHelper));
eventHelper.addEventPayload((VisualMappingFunction) this, new VisualMappingFunctionChangeRecord(),
VisualMappingFunctionChangedEvent.class);
}
@Override
public void removePoint(int index) {
points.remove(index);
eventHelper.addEventPayload((VisualMappingFunction) this, new VisualMappingFunctionChangeRecord(),
VisualMappingFunctionChangedEvent.class);
}
@Override
public int getPointCount() {
return points.size();
}
@Override
public ContinuousMappingPoint<K, V> getPoint(int index) {
if(points.isEmpty())
return null;
else if(points.size()>index)
return points.get(index);
else {
throw new IllegalArgumentException("Invalid Index: " + index + ". There are " + points.size() + " points.");
}
}
@Override
public V getMappedValue(final CyRow row) {
V value = null;
if (row != null && row.isSet(columnName)) {
// Skip if source attribute is not defined.
// ViewColumn will automatically substitute the per-VS or global default, as appropriate
// In all cases, attribute value should be a number for continuous mapping.
final K attrValue = row.get(columnName, columnType);
value = getRangeValue(attrValue);
}
return value;
}
private V getRangeValue(K domainValue) {
- if(points.isEmpty())
+ if (points.isEmpty() ||
+ (domainValue instanceof Number && Double.isNaN(((Number)domainValue).doubleValue())))
return null;
ContinuousMappingPoint<K, V> firstPoint = points.get(0);
K minDomain = firstPoint.getValue();
// if given domain value is smaller than any in our list,
// return the range value for the smallest domain value we have.
int firstCmp = compareValues(domainValue, minDomain);
if (firstCmp <= 0) {
BoundaryRangeValues<V> bv = firstPoint.getRange();
if (firstCmp < 0)
return bv.lesserValue;
else
return bv.equalValue;
}
// if given domain value is larger than any in our Vector,
// return the range value for the largest domain value we have.
ContinuousMappingPoint<K, V> lastPoint = points.get(points.size() - 1);
K maxDomain = lastPoint.getValue();
if (compareValues(domainValue, maxDomain) > 0) {
BoundaryRangeValues<V> bv = lastPoint.getRange();
return bv.greaterValue;
}
// OK, it's somewhere in the middle, so find the boundaries and
// pass to our interpolator function. First check for a null
// interpolator function
if (this.interpolator == null)
return null;
// Note that the list of Points is sorted.
// Also, the case of the inValue equalling the smallest key was
// checked above.
ContinuousMappingPoint<K, V> currentPoint;
int index = 0;
for (index = 0; index < points.size(); index++) {
currentPoint = points.get(index);
K currentValue = currentPoint.getValue();
int cmpValue = compareValues(domainValue, currentValue);
if (cmpValue == 0) {
BoundaryRangeValues<V> bv = currentPoint.getRange();
return bv.equalValue;
} else if (cmpValue < 0)
break;
}
return getRangeValue(index, domainValue);
}
/**
* This is tricky. The desired domain value is greater than lowerDomain and
* less than upperDomain. Therefore, we want the "greater" field of the
* lower boundary value (because the desired domain value is greater) and
* the "lesser" field of the upper boundary value (semantic difficulties).
*/
private V getRangeValue(int index, K domainValue) {
// Get Lower Domain and Range
ContinuousMappingPoint<K, V> lowerBound = points.get(index - 1);
K lowerDomain = lowerBound.getValue();
BoundaryRangeValues<V> lv = lowerBound.getRange();
V lowerRange = lv.greaterValue;
// Get Upper Domain and Range
ContinuousMappingPoint<K, V> upperBound = points.get(index);
K upperDomain = upperBound.getValue();
BoundaryRangeValues<V> gv = upperBound.getRange();
V upperRange = gv.lesserValue;
V value = interpolator.getRangeValue(lowerDomain, lowerRange, upperDomain, upperRange, domainValue);
return value;
}
/**
* Helper function to compare Number objects. This is needed because Java
* doesn't allow comparing, for example, Integer objects to Double objects.
*/
private int compareValues(K probe, K target) {
final Number n1 = (Number) probe;
final Number n2 = (Number) target;
double d1 = n1.doubleValue();
double d2 = n2.doubleValue();
if (d1 < d2)
return -1;
else if (d1 > d2)
return 1;
else
return 0;
}
}
| true | true | private V getRangeValue(K domainValue) {
if(points.isEmpty())
return null;
ContinuousMappingPoint<K, V> firstPoint = points.get(0);
K minDomain = firstPoint.getValue();
// if given domain value is smaller than any in our list,
// return the range value for the smallest domain value we have.
int firstCmp = compareValues(domainValue, minDomain);
if (firstCmp <= 0) {
BoundaryRangeValues<V> bv = firstPoint.getRange();
if (firstCmp < 0)
return bv.lesserValue;
else
return bv.equalValue;
}
// if given domain value is larger than any in our Vector,
// return the range value for the largest domain value we have.
ContinuousMappingPoint<K, V> lastPoint = points.get(points.size() - 1);
K maxDomain = lastPoint.getValue();
if (compareValues(domainValue, maxDomain) > 0) {
BoundaryRangeValues<V> bv = lastPoint.getRange();
return bv.greaterValue;
}
// OK, it's somewhere in the middle, so find the boundaries and
// pass to our interpolator function. First check for a null
// interpolator function
if (this.interpolator == null)
return null;
// Note that the list of Points is sorted.
// Also, the case of the inValue equalling the smallest key was
// checked above.
ContinuousMappingPoint<K, V> currentPoint;
int index = 0;
for (index = 0; index < points.size(); index++) {
currentPoint = points.get(index);
K currentValue = currentPoint.getValue();
int cmpValue = compareValues(domainValue, currentValue);
if (cmpValue == 0) {
BoundaryRangeValues<V> bv = currentPoint.getRange();
return bv.equalValue;
} else if (cmpValue < 0)
break;
}
return getRangeValue(index, domainValue);
}
| private V getRangeValue(K domainValue) {
if (points.isEmpty() ||
(domainValue instanceof Number && Double.isNaN(((Number)domainValue).doubleValue())))
return null;
ContinuousMappingPoint<K, V> firstPoint = points.get(0);
K minDomain = firstPoint.getValue();
// if given domain value is smaller than any in our list,
// return the range value for the smallest domain value we have.
int firstCmp = compareValues(domainValue, minDomain);
if (firstCmp <= 0) {
BoundaryRangeValues<V> bv = firstPoint.getRange();
if (firstCmp < 0)
return bv.lesserValue;
else
return bv.equalValue;
}
// if given domain value is larger than any in our Vector,
// return the range value for the largest domain value we have.
ContinuousMappingPoint<K, V> lastPoint = points.get(points.size() - 1);
K maxDomain = lastPoint.getValue();
if (compareValues(domainValue, maxDomain) > 0) {
BoundaryRangeValues<V> bv = lastPoint.getRange();
return bv.greaterValue;
}
// OK, it's somewhere in the middle, so find the boundaries and
// pass to our interpolator function. First check for a null
// interpolator function
if (this.interpolator == null)
return null;
// Note that the list of Points is sorted.
// Also, the case of the inValue equalling the smallest key was
// checked above.
ContinuousMappingPoint<K, V> currentPoint;
int index = 0;
for (index = 0; index < points.size(); index++) {
currentPoint = points.get(index);
K currentValue = currentPoint.getValue();
int cmpValue = compareValues(domainValue, currentValue);
if (cmpValue == 0) {
BoundaryRangeValues<V> bv = currentPoint.getRange();
return bv.equalValue;
} else if (cmpValue < 0)
break;
}
return getRangeValue(index, domainValue);
}
|
diff --git a/srcj/com/sun/electric/tool/user/ui/PixelDrawing.java b/srcj/com/sun/electric/tool/user/ui/PixelDrawing.java
index 7b45df6ee..dac88d1c0 100755
--- a/srcj/com/sun/electric/tool/user/ui/PixelDrawing.java
+++ b/srcj/com/sun/electric/tool/user/ui/PixelDrawing.java
@@ -1,3222 +1,3223 @@
/* -*- tab-width: 4 -*-
*
* Electric(tm) VLSI Design System
*
* File: PixelDrawing.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 2 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.user.ui;
import com.sun.electric.database.geometry.DBMath;
import com.sun.electric.database.geometry.EGraphics;
import com.sun.electric.database.geometry.Poly;
import com.sun.electric.database.hierarchy.Cell;
import com.sun.electric.database.hierarchy.Export;
import com.sun.electric.database.hierarchy.View;
import com.sun.electric.database.prototype.ArcProto;
import com.sun.electric.database.prototype.NodeProto;
import com.sun.electric.database.prototype.PortProto;
import com.sun.electric.database.topology.ArcInst;
import com.sun.electric.database.topology.Connection;
import com.sun.electric.database.topology.NodeInst;
import com.sun.electric.database.topology.PortInst;
import com.sun.electric.database.variable.FlagSet;
import com.sun.electric.database.variable.TextDescriptor;
import com.sun.electric.database.text.TextUtils;
import com.sun.electric.technology.Layer;
import com.sun.electric.technology.PrimitiveArc;
import com.sun.electric.technology.PrimitiveNode;
import com.sun.electric.technology.Technology;
import com.sun.electric.technology.technologies.Generic;
import com.sun.electric.tool.user.User;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.font.FontRenderContext;
import java.awt.font.GlyphVector;
import java.awt.font.LineMetrics;
import java.awt.geom.AffineTransform;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.awt.image.DataBufferInt;
import java.awt.image.Raster;
import java.awt.image.WritableRaster;
import java.util.HashMap;
import java.util.Iterator;
/**
* This class manages an offscreen display for an associated EditWindow.
* It renders an Image for copying to the display.
* <P>
* Every offscreen display consists of two parts: the transparent layers and the opaque image.
* To tell how a layer is displayed, look at the "transparentLayer" field of its "EGraphics" object.
* When this is nonzero, the layer is drawn transparent.
* When this is zero, use the "red, green, blue" fields for the opaque color.
* <P>
* The opaque image is a full-color Image that is the size of the EditWindow.
* Any layers that are marked "opaque" are drawin in full color in the image.
* Colors are not combined in the opaque image: every color placed in it overwrites the previous color.
* For this reason, opaque colors are often stipple patterns, so that they won't completely obscure other
* opaque layers.
* <P>
* The transparent layers are able to combine with each other.
* Typically, the more popular layers are made transparent (metal, poly, active, etc.)
* For every transparent layer, there is a 1-bit deep bitmap that is the size of the EditWindow.
* The bitmap is an array of "byte []" pointers, one for every Y coordinate in the EditWindow.
* Each array contains the bits for that row, packed 8 per byte.
* All of this information is in the "layerBitMaps" field, which is triply indexed.
* <P>
* Thus, to find bit (x,y) of transparent layer T, first lookup the appropriate transparent layer,
* ("layerBitMaps[T]").
* Then, for that layer, find the array of bytes for the appropriate row
* (by indexing the the Y coordinate into the rowstart array, "layerBitMaps[T][y]").
* Next, figure out which byte has the bit (by dividing the X coordinate by 8: "layerBitMaps[T][y][x>>3]").
* Finally, determine which bit to use (by using the low 3 bits of the X coordinate,
* layerBitMaps[T][y][x>>3] & (1 << (x&7)) ).
* <P>
* Transparent layers are not allocated until needed. Thus, if there are 5 possible transparent layers,
* but only 2 are used, then only two bitplanes will be created.
* <P>
* Each technology declares the number of possible transparent layers that it can generate.
* In addition, it must provide a color map for describing every combination of transparent layer.
* This map is, of course, 2-to-the-number-of-possible-transparent-layers long.
* <P>
* When all rendering is done, the full-color image is composited with the transparent layers to produce
* the final image.
* This is done by scanning the full-color image for any entries that were not filled-in.
* These are then replaced by the transparent color at that point.
* The transparent color is computed by looking at the bits in every transparent bitmap and
* constructing an index. This is looked-up in the color table and the appropriate color is used.
* If no transparent layers are set, the background color is used.
* <P>
* There are a number of efficiencies implemented here.
* <UL>
* <LI><B>Setting bits directly into the offscreen memory</B>.
* Although Java's Swing package has a rendering model, it was found to be 3 times slower than
* setting bits directly inot the offscreen memory.</LI>
* <LI><B>Tiny nodes and arcs are approximated</B>.
* When a node or arc will be only 1 or 2 pixels in size on the screen, it is not necessary
* to actually compute the edges of all of its parts. Instead, a single pixel of color is placed.
* The color is taken from all of the layers that compose the node or arc.
* This optimization adds another factor of 2 to the speed of display.</LI>
* <LI><B>Expanded cell contents are cached</B>.
* When a cell is expanded, and its contents is drawn, the contents are preserved so that they
* need be rendered only once. Subsequent instances of that expanded cell are able to be instantly drawn.
* There are a number of extra considerations here:
* <UL>
* <LI>Cell instances can appear in any orientation. Therefore, the cache of drawn cells must
* include the orientation.</LI>
* <LI>Cell instances may appear at different levels of the hierarchy. Therefore, it is not
* sufficient to merely remember their location on the screen and copy them. An instance may have been
* rendered at one level of hierarchy, and other items at that same level then rendered over it.
* It is then no longer possible to copy those bits when the instance appears again at another place
* in the hierarchy because it has been altered by neighboring circuitry. The same problem happens
* when cell instances overlap. Therefore, it is necessary to render each expanded cell instance
* into its own offscreen map. To do this, a new "EditWindow" with associated "PixelDrawing"
* object are created for each cached cell.</LI>
* <LI>Subpixel alignment may not be the same for each cached instance. This turns out not to be
* a problem, because at such zoomed-out scales, it is impossible to see individual objects anyway.</LI>
* <LI>Large cell instances should not be cached. When zoomed-in, an expanded cell instance could
* be many megabytes in size, and only a portion of it appears on the screen. Therefore, large cell
* instances are not cached, but drawn directly. It is assumed that there will be few such instances.
* The rule currently is that any cell whose width is greater than half of the display size AND whose
* height is greater than half of the display size is too large to cache.</LI>
* <LI>If an instance only appears once, it is not cached. This requires a preprocessing step to scan
* the hierarchy and count the number of times that a particular cell-transformation is used. During
* rendering, if the count is only 1, it is not cached.</LI>
* <LI>Texture patterns don't line-up. When drawing texture pattern to the final buffer, it is easy
* to use the screen coordinates to index the pattern map, causeing all of them to line-up.
* Any two adjoining objects that use the same pattern will have their patterns line-up smoothly.
* However, when caching cell instances, it is not possible to know where the contents will be placed
* on the screen, and so the texture patterns rendered into the cache cannot be aligned globally.
* To solve this, there are additional bitmaps created for every Patterned-Opaque-Layer (POL).
* When rendering on a layer that is patterned and opaque, the bitmap is dynamically allocated
* and filled (all bits are filled on the bitmap, not just those in the pattern).
* When combining lower-level cell images with higher-level ones, these POLs are copied, too.
* When compositing at the top level, however, the POLs are converted back to patterns, and they now line-up.</LI>
* </UL>
* </UL>
*
*/
public class PixelDrawing
{
/** Text smaller than this will not be drawn. */ public static final int MINIMUMTEXTSIZE = 5;
private static class PolySeg
{
int fx,fy, tx,ty, direction, increment;
PolySeg nextedge;
PolySeg nextactive;
}
// statistics stuff
private static final boolean TAKE_STATS = false;
private static int tinyCells, tinyPrims, totalCells, totalPrims, tinyArcs, totalArcs, offscreensCreated, offscreensUsed;
/**
* This class holds information about expanded cell instances.
* For efficiency, Electric remembers the bits in an expanded cell instance
* and uses them when another expanded instance appears elsewhere.
* Of course, the orientation of the instance matters, so each combination of
* cell and orientation forms a "cell cache". The Cell Cache is stored in the
* "wnd" field (which has its own PixelDrawing object).
*/
private static class ExpandedCellInfo
{
int instanceCount;
EditWindow wnd;
}
/** the EditWindow being drawn */ private EditWindow wnd;
/** the size of the EditWindow */ private Dimension sz;
/** the area of the cell to draw, in DB units */ private Rectangle2D drawBounds;
// the full-depth image
/** the offscreen opaque image of the window */ private Image img;
/** opaque layer of the window */ private int [] opaqueData;
/** size of the opaque layer of the window */ private int total;
/** the background color of the offscreen image */ private int backgroundColor;
/** the "unset" color of the offscreen image */ private int backgroundValue;
// the transparent bitmaps
/** the offscreen maps for transparent layers */ private byte [][][] layerBitMaps;
/** row pointers for transparent layers */ private byte [][] compositeRows;
/** the number of transparent layers */ private int numLayerBitMaps;
/** the number of bytes per row in offscreen maps */ private int numBytesPerRow;
/** the number of offscreen transparent maps made */ private int numLayerBitMapsCreated;
/** the technology of the window */ private Technology curTech;
// the patterned opaque bitmaps
private static class PatternedOpaqueLayer
{
byte [][] bitMap;
byte [] compositeRow;
}
/** the map from layers to Patterned Opaque bitmaps */ private HashMap patternedOpaqueLayers;
/** the top-level window being rendered */ private boolean renderedWindow;
/** whether to occasionally update the display. */ private boolean periodicRefresh;
/** keeps track of when to update the display. */ private int objectCount;
/** keeps track of when to update the display. */ private long lastRefreshTime;
/** the size of the top-level EditWindow */ private static Dimension topSz;
/** the last Technology that had transparent layers */ private static Technology techWithLayers = null;
/** list of cell expansions. */ private static HashMap expandedCells = null;
/** TextDescriptor for empty window text. */ private static TextDescriptor noCellTextDescriptor = null;
/** zero rectangle */ private static final Rectangle2D CENTERRECT = new Rectangle2D.Double(0, 0, 0, 0);
private static EGraphics blackGraphics = new EGraphics(EGraphics.SOLID, EGraphics.SOLID, 0, 0,0,0, 1.0,1,
new int[] {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0});
private static EGraphics portGraphics = new EGraphics(EGraphics.SOLID, EGraphics.SOLID, 0, 255,0,0, 1.0,1,
new int[] {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0});
private static final boolean DEBUGRENDERTIMING = false;
private static long renderTextTime;
private static long renderPolyTime;
// ************************************* TOP LEVEL *************************************
/**
* Constructor creates an offscreen PixelDrawing object for a given EditWindow.
* @param wnd the EditWindow associated with this PixelDrawing.
*/
public PixelDrawing(EditWindow wnd)
{
this.wnd = wnd;
this.sz = wnd.getScreenSize();
// allocate pointer to the opaque image
img = new BufferedImage(sz.width, sz.height, BufferedImage.TYPE_INT_RGB);
WritableRaster raster = ((BufferedImage)img).getRaster();
DataBufferInt dbi = (DataBufferInt)raster.getDataBuffer();
opaqueData = dbi.getData();
total = sz.height * sz.width;
numBytesPerRow = (sz.width + 7) / 8;
backgroundColor = User.getColorBackground() & 0xFFFFFF;
backgroundValue = backgroundColor | 0xFF000000;
patternedOpaqueLayers = new HashMap();
renderedWindow = true;
curTech = null;
initForTechnology();
// initialize the data
clearImage(false);
}
/**
* Method to override the background color.
* Must be called before "drawImage()".
* This is used by printing, which forces the background to be white.
* @param bg the background color to use.
*/
public void setBackgroundColor(Color bg)
{
backgroundColor = bg.getRGB() & 0xFFFFFF;
}
/**
* Method for obtaining the rendered image after "drawImage" has finished.
* @return an Image for this edit window.
*/
public Image getImage() { return img; }
/**
* This is the entrypoint for rendering.
* It displays a cell in this offscreen window.
* @param expandBounds the area in the cell to expand fully.
* If null, draw the cell normally; otherwise expand all the way in that area.
* The rendered Image can then be obtained with "getImage()".
*/
public void drawImage(Rectangle2D expandBounds)
{
Cell cell = wnd.getCell();
drawBounds = wnd.getDisplayedBounds();
long startTime = 0;
// if (TAKE_STATS)
// {
// startTime = System.currentTimeMillis();
// tinyCells = tinyPrims = totalCells = totalPrims = tinyArcs = totalArcs = offscreensCreated = offscreensUsed = 0;
// }
// initialize the cache of expanded cell displays
expandedCells = new HashMap();
// remember the true window size (since recursive calls may cache individual cells that are smaller)
topSz = sz;
// initialize rendering into the offscreen image
clearImage(true);
if (cell == null)
{
if (noCellTextDescriptor == null)
{
noCellTextDescriptor = new TextDescriptor(null);
noCellTextDescriptor.setAbsSize(18);
noCellTextDescriptor.setBold(true);
}
Rectangle rect = new Rectangle(sz);
blackGraphics.setColor(new Color(User.getColorText()));
drawText(rect, Poly.Type.TEXTBOX, noCellTextDescriptor, "No cell in this window", null, blackGraphics);
} else
{
// determine which cells should be cached (must have at least 2 instances)
countCell(cell, DBMath.MATID);
// now render it all
drawCell(cell, expandBounds, DBMath.MATID, true);
}
// merge transparent image into opaque one
synchronized(img) { composite(); };
// if (TAKE_STATS)
// {
// long endTime = System.currentTimeMillis();
// System.out.println("Took "+com.sun.electric.database.text.TextUtils.getElapsedTime(endTime-startTime));
// System.out.println(" "+tinyCells+" out of "+totalCells+" cells are tiny; "+tinyPrims+" out of "+totalPrims+
// " primitives are tiny; "+tinyArcs+" out of "+totalArcs+" arcs are tiny");
// int numExpandedCells = 0;
// int numCellsExpandedOnce = 0;
// for(Iterator it = expandedCells.keySet().iterator(); it.hasNext(); )
// {
// String c = (String)it.next();
// ExpandedCellInfo count = (ExpandedCellInfo)expandedCells.get(c);
// if (count != null)
// {
// numExpandedCells++;
// if (count.instanceCount == 1) numCellsExpandedOnce++;
// }
// }
// System.out.println(" Of "+numExpandedCells+" cell cache possibilities, "+numCellsExpandedOnce+
// " were used only once and not cached");
// if (offscreensCreated > 0)
// System.out.println(" Remaining "+offscreensCreated+" cell caches were used an average of "+
// ((double)offscreensUsed/offscreensCreated)+" times");
// }
}
// ************************************* INTERMEDIATE CONTROL LEVEL *************************************
/**
* Method to erase the offscreen data in this PixelDrawing.
* This is called before any rendering is done.
* @param periodicRefresh true to periodically refresh the display if it takes too long.
*/
public void clearImage(boolean periodicRefresh)
{
// pickup new technology if it changed
initForTechnology();
// erase the transparent bitmaps
for(int i=0; i<numLayerBitMaps; i++)
{
byte [][] layerBitMap = layerBitMaps[i];
if (layerBitMap == null) continue;
for(int y=0; y<sz.height; y++)
{
byte [] row = layerBitMap[y];
for(int x=0; x<numBytesPerRow; x++)
row[x] = 0;
}
}
// erase the patterned opaque layer bitmaps
for(Iterator it = patternedOpaqueLayers.entrySet().iterator(); it.hasNext(); )
{
PatternedOpaqueLayer pol = (PatternedOpaqueLayer)it.next();
byte [][] layerBitMap = pol.bitMap;
for(int y=0; y<sz.height; y++)
{
byte [] row = layerBitMap[y];
for(int x=0; x<numBytesPerRow; x++)
row[x] = 0;
}
}
// erase opaque image
for(int i=0; i<total; i++) opaqueData[i] = backgroundValue;
this.periodicRefresh = periodicRefresh;
if (periodicRefresh)
{
objectCount = 0;
lastRefreshTime = System.currentTimeMillis();
}
}
/**
* Method to complete rendering by combining the transparent and opaque imagery.
* This is called after all rendering is done.
* @return the offscreen Image with the final display.
*/
public Image composite()
{
// merge in the transparent layers
if (numLayerBitMapsCreated > 0)
{
Color [] colorMap = curTech.getColorMap();
for(int y=0; y<sz.height; y++)
{
for(int i=0; i<numLayerBitMaps; i++)
{
byte [][] layerBitMap = layerBitMaps[i];
if (layerBitMap == null) compositeRows[i] = null; else
{
compositeRows[i] = layerBitMap[y];
}
}
int baseIndex = y * sz.width;
for(int x=0; x<sz.width; x++)
{
int index = baseIndex + x;
int pixelValue = opaqueData[index];
// the value of Alpha starts at 0xFF, which means "background"
// opaque drawing typically sets it to 0, which means "filled"
// Text drawing can antialias by setting the edge values in the range 0-254
// where the lower the value, the more saturated the color (so 0 means all color, 254 means little color)
int alpha = (pixelValue >> 24) & 0xFF;
if (alpha != 0)
{
// aggregate the transparent bitplanes at this pixel
int bits = 0;
int entry = x >> 3;
int maskBit = 1 << (x & 7);
for(int i=0; i<numLayerBitMaps; i++)
{
if (compositeRows[i] == null) continue;
int byt = compositeRows[i][entry];
if ((byt & maskBit) != 0) bits |= (1<<i);
}
// determine the transparent color to draw
int newColor = backgroundColor;
if (bits != 0)
{
// set a transparent color
newColor = colorMap[bits].getRGB() & 0xFFFFFF;
}
// if alpha blending, merge with the opaque data
if (alpha != 0xFF)
{
newColor = alphaBlend(pixelValue, newColor, alpha);
}
opaqueData[index] = newColor;
}
}
}
} else
{
// nothing in transparent layers: make sure background color is right
for(int i=0; i<total; i++)
{
int pixelValue = opaqueData[i];
if (pixelValue == backgroundValue) opaqueData[i] = backgroundColor; else
{
if ((pixelValue&0xFF000000) != 0)
{
int alpha = (pixelValue >> 24) & 0xFF;
opaqueData[i] = alphaBlend(pixelValue, backgroundColor, alpha);
}
}
}
}
return img;
}
private void initForTechnology()
{
// allocate pointers to the overlappable layers
Technology tech = Technology.getCurrent();
if (tech == null) return;
if (tech == curTech) return;
int transLayers = tech.getNumTransparentLayers();
if (transLayers != 0)
{
techWithLayers = curTech = tech;
}
if (curTech == null) curTech = techWithLayers;
numLayerBitMaps = curTech.getNumTransparentLayers();
layerBitMaps = new byte[numLayerBitMaps][][];
compositeRows = new byte[numLayerBitMaps][];
for(int i=0; i<numLayerBitMaps; i++) layerBitMaps[i] = null;
numLayerBitMapsCreated = 0;
}
// ************************************* HIERARCHY TRAVERSAL *************************************
/**
* Method to draw the contents of a cell, transformed through "prevTrans".
*/
private void drawCell(Cell cell, Rectangle2D expandBounds, AffineTransform prevTrans, boolean topLevel)
{
renderPolyTime = 0;
renderTextTime = 0;
// draw all arcs
for(Iterator arcs = cell.getArcs(); arcs.hasNext(); )
{
drawArc((ArcInst)arcs.next(), prevTrans);
}
// draw all nodes
for(Iterator nodes = cell.getNodes(); nodes.hasNext(); )
{
drawNode((NodeInst)nodes.next(), prevTrans, topLevel, expandBounds);
}
// show cell variables if at the top level
if (topLevel && User.isTextVisibilityOnCell())
{
// show displayable variables on the instance
int numPolys = cell.numDisplayableVariables(true);
Poly [] polys = new Poly[numPolys];
cell.addDisplayableVariables(CENTERRECT, polys, 0, wnd, true);
drawPolys(polys, DBMath.MATID);
}
if (DEBUGRENDERTIMING) {
System.out.println("Total time to render polys: "+TextUtils.getElapsedTime(renderPolyTime));
System.out.println("Total time to render text: "+TextUtils.getElapsedTime(renderTextTime));
}
}
/**
* Method to draw a NodeInst into the offscreen image.
* @param ni the NodeInst to draw.
* @param trans the transformation of the NodeInst to the display.
* @param topLevel true if this is the top-level of display (not in a subcell).
* @param expandBounds bounds in which to draw nodes fully expanded
*/
public void drawNode(NodeInst ni, AffineTransform trans, boolean topLevel, Rectangle2D expandBounds)
{
NodeProto np = ni.getProto();
AffineTransform localTrans = ni.rotateOut(trans);
// see if the node is completely clipped from the screen
Point2D ctr = ni.getTrueCenter();
trans.transform(ctr, ctr);
double halfWidth = Math.max(ni.getXSize(), ni.getYSize()) / 2;
Rectangle2D databaseBounds = wnd.getDisplayedBounds();
double ctrX = ctr.getX();
double ctrY = ctr.getY();
if (ctrX + halfWidth < databaseBounds.getMinX()) return;
if (ctrX - halfWidth > databaseBounds.getMaxX()) return;
if (ctrY + halfWidth < databaseBounds.getMinY()) return;
if (ctrY - halfWidth > databaseBounds.getMaxY()) return;
// if the node is tiny, just approximate it with a single dot
if (np instanceof Cell) totalCells++; else totalPrims++;
if (!np.isCanBeZeroSize() && halfWidth * wnd.getScale() < 1)
{
if (np instanceof Cell) tinyCells++; else
{
tinyPrims++;
// draw a tiny primitive by setting a single dot from each layer
int x = wnd.databaseToScreenX(ctrX);
int y = wnd.databaseToScreenY(ctrY);
if (x >= 0 && x < sz.width && y >= 0 && y < sz.height)
{
drawTinyLayers(((PrimitiveNode)np).layerIterator(), x, y);
}
}
return;
}
// draw the node
if (np instanceof Cell)
{
// cell instance
Cell subCell = (Cell)np;
boolean expanded = ni.isExpanded();
if (expandBounds != null)
{
if (ni.getBounds().intersects(expandBounds))
{
expanded = true;
AffineTransform transRI = ni.rotateIn();
AffineTransform transTI = ni.translateIn();
transRI.preConcatenate(transTI);
Rectangle2D subBounds = new Rectangle2D.Double();
subBounds.setRect(expandBounds);
DBMath.transformRect(subBounds, transRI);
expandBounds = subBounds;
}
}
// two ways to draw a cell instance
if (expanded)
{
// show the contents of the cell
AffineTransform subTrans = ni.translateOut(localTrans);
if (expandedCellCached(subCell, subTrans, expandBounds)) return;
// just draw it directly
drawCell(subCell, expandBounds, subTrans, false);
showCellPorts(ni, trans, Color.BLACK);
} else
{
// draw the black box of the instance
drawUnexpandedCell(ni, trans);
showCellPorts(ni, trans, null);
}
// draw any displayable variables on the instance
if (User.isTextVisibilityOnNode())
{
int numPolys = ni.numDisplayableVariables(true);
Poly [] polys = new Poly[numPolys];
Rectangle2D rect = ni.getBounds();
ni.addDisplayableVariables(rect, polys, 0, wnd, true);
drawPolys(polys, localTrans);
}
} else
{
// primitive
if (topLevel || !ni.isVisInside())
{
EditWindow nodeWnd = wnd;
PrimitiveNode prim = (PrimitiveNode)np;
if (!User.isTextVisibilityOnNode()) nodeWnd = null;
if (prim == Generic.tech.invisiblePinNode)
{
if (!User.isTextVisibilityOnAnnotation()) nodeWnd = null;
}
Technology tech = prim.getTechnology();
Poly [] polys = tech.getShapeOfNode(ni, nodeWnd);
drawPolys(polys, localTrans);
}
}
// draw any exports from the node
if (topLevel && User.isTextVisibilityOnExport())
{
int exportDisplayLevel = User.getExportDisplayLevel();
Iterator it = ni.getExports();
blackGraphics.setColor(new Color(User.getColorText()));
while (it.hasNext())
{
Export e = (Export)it.next();
Poly poly = e.getNamePoly();
Rectangle2D rect = (Rectangle2D)poly.getBounds2D().clone();
if (exportDisplayLevel == 2)
{
// draw port as a cross
drawCross(poly, blackGraphics);
} else
{
// draw port as text
TextDescriptor descript = poly.getTextDescriptor();
Poly.Type type = descript.getPos().getPolyType();
String portName = e.getName();
if (exportDisplayLevel == 1)
{
// use shorter port name
portName = e.getShortName();
}
Point pt = wnd.databaseToScreen(poly.getCenterX(), poly.getCenterY());
Rectangle textRect = new Rectangle(pt);
type = Poly.rotateType(type, ni);
drawText(textRect, type, descript, portName, null, blackGraphics);
}
// draw variables on the export
int numPolys = e.numDisplayableVariables(true);
if (numPolys > 0)
{
Poly [] polys = new Poly[numPolys];
e.addDisplayableVariables(rect, polys, 0, wnd, true);
drawPolys(polys, localTrans);
}
}
}
}
/**
* Method to render an ArcInst into the offscreen image.
* @param ai the ArcInst to draw.
* @param trans the transformation of the ArcInst to the display.
*/
public void drawArc(ArcInst ai, AffineTransform trans)
{
// see if the arc is completely clipped from the screen
Rectangle2D arcBounds = ai.getBounds();
Rectangle2D dbBounds = new Rectangle2D.Double(arcBounds.getX(), arcBounds.getY(), arcBounds.getWidth(), arcBounds.getHeight());
// java doesn't think they intersect if they contain no area, so add some area if needed
if (arcBounds.getWidth() == 0) dbBounds.setRect(dbBounds.getX(), dbBounds.getY(), 0.0001, dbBounds.getHeight());
if (arcBounds.getHeight() == 0) dbBounds.setRect(dbBounds.getX(), dbBounds.getY(), dbBounds.getWidth(), 0.0001);
Poly p = new Poly(dbBounds);
p.transform(trans);
if (drawBounds != null && !p.getBounds2D().intersects(drawBounds)) {
return;
}
double arcSize = Math.max(arcBounds.getWidth(), arcBounds.getHeight());
// if the arc it tiny, just approximate it with a single dot
totalArcs++;
if (arcSize * wnd.getScale() < 2)
{
tinyArcs++;
// draw a tiny arc by setting a single dot from each layer
Point2D ctr = ai.getTrueCenter();
trans.transform(ctr, ctr);
int x = wnd.databaseToScreenX(ctr.getX());
int y = wnd.databaseToScreenY(ctr.getY());
if (x >= 0 && x < sz.width && y >= 0 && y < sz.height)
{
PrimitiveArc prim = (PrimitiveArc)ai.getProto();
drawTinyLayers(prim.layerIterator(), x, y);
}
return;
}
// draw the arc
ArcProto ap = ai.getProto();
Technology tech = ap.getTechnology();
EditWindow arcWnd = wnd;
if (!User.isTextVisibilityOnArc()) arcWnd = null;
Poly [] polys = tech.getShapeOfArc(ai, arcWnd);
drawPolys(polys, trans);
}
private void showCellPorts(NodeInst ni, AffineTransform trans, Color col)
{
// show the ports that are not further exported or connected
FlagSet fs = PortProto.getFlagSet(1);
for(Iterator it = ni.getProto().getPorts(); it.hasNext(); )
{
PortProto pp = (PortProto)it.next();
pp.clearBit(fs);
}
for(Iterator it = ni.getConnections(); it.hasNext();)
{
Connection con = (Connection) it.next();
PortInst pi = con.getPortInst();
pi.getPortProto().setBit(fs);
}
for(Iterator it = ni.getExports(); it.hasNext();)
{
Export exp = (Export) it.next();
PortInst pi = exp.getOriginalPort();
pi.getPortProto().setBit(fs);
}
int portDisplayLevel = User.getPortDisplayLevel();
for(Iterator it = ni.getProto().getPorts(); it.hasNext(); )
{
PortProto pp = (PortProto)it.next();
if (pp.isBit(fs)) continue;
Poly portPoly = ni.getShapeOfPort(pp);
if (portPoly == null) continue;
portPoly.transform(trans);
Color portColor = col;
if (portColor == null) portColor = pp.colorOfPort();
portGraphics.setColor(portColor);
if (portDisplayLevel == 2)
{
// draw port as a cross
drawCross(portPoly, portGraphics);
} else
{
// draw port as text
if (User.isTextVisibilityOnPort())
{
TextDescriptor descript = portPoly.getTextDescriptor();
Poly.Type type = descript.getPos().getPolyType();
String portName = pp.getName();
if (portDisplayLevel == 1)
{
// use shorter port name
portName = pp.getShortName();
}
Point pt = wnd.databaseToScreen(portPoly.getCenterX(), portPoly.getCenterY());
Rectangle rect = new Rectangle(pt);
drawText(rect, type, descript, portName, null, portGraphics);
}
}
}
fs.freeFlagSet();
}
private void drawUnexpandedCell(NodeInst ni, AffineTransform trans)
{
NodeProto np = ni.getProto();
// draw the instance outline
Poly poly = new Poly(ni.getTrueCenterX(), ni.getTrueCenterY(), ni.getXSize(), ni.getYSize());
AffineTransform localPureTrans = ni.rotateOutAboutTrueCenter(trans);
poly.transform(localPureTrans);
Point2D [] points = poly.getPoints();
for(int i=0; i<points.length; i++)
{
int lastI = i - 1;
if (lastI < 0) lastI = points.length - 1;
Point from = wnd.databaseToScreen(points[lastI]);
Point to = wnd.databaseToScreen(points[i]);
blackGraphics.setColor(new Color(User.getColorInstanceOutline()));
drawLine(from, to, null, blackGraphics, 0);
}
// draw the instance name
if (User.isTextVisibilityOnInstance())
{
Rectangle2D bounds = poly.getBounds2D();
Rectangle rect = wnd.databaseToScreen(bounds);
TextDescriptor descript = ni.getProtoTextDescriptor();
blackGraphics.setColor(new Color(User.getColorText()));
drawText(rect, Poly.Type.TEXTBOX, descript, np.describe(), null, blackGraphics);
}
}
private void drawTinyLayers(Iterator layerIterator, int x, int y)
{
for(Iterator it = layerIterator; it.hasNext(); )
{
Layer layer = (Layer)it.next();
if (layer == null) continue;
int layerNum = -1;
int col = 0;
EGraphics graphics = layer.getGraphics();
if (graphics != null)
{
if (graphics.isPatternedOnDisplay())
{
int [] pattern = graphics.getPattern();
if (pattern != null)
{
int pat = pattern[y&15];
if (pat == 0 || (pat & (0x8000 >> (x&15))) == 0) continue;
}
}
layerNum = graphics.getTransparentLayer() - 1;
col = graphics.getColor().getRGB() & 0xFFFFFF;
}
if (layerNum >= numLayerBitMaps) continue;
byte [][] layerBitMap = getLayerBitMap(layerNum);
// set the bit
if (layerBitMap == null)
{
opaqueData[y * sz.width + x] = col;
} else
{
layerBitMap[y][x>>3] |= (1 << (x&7));
}
}
}
// ************************************* CELL CACHING *************************************
/**
* @return true if the cell is properly handled and need no further processing.
* False to render the contents recursively.
*/
private boolean expandedCellCached(Cell subCell, AffineTransform subTrans, Rectangle2D bounds)
{
// if there is no global for remembering cached cells, do not cache
if (expandedCells == null) return false;
// do not cache icons: they can be redrawn each time
if (subCell.getView() == View.ICON) return false;
// find this cell-transformation combination in the global list of cached cells
String expandedName = makeExpandedName(subCell, subTrans);
ExpandedCellInfo expandedCellCount = (ExpandedCellInfo)expandedCells.get(expandedName);
if (expandedCellCount != null)
{
// if this combination is not used multiple times, do not cache it
if (expandedCellCount.instanceCount < 2) return false;
}
// compute where this cell lands on the screen
Rectangle2D cellBounds = new Rectangle2D.Double();
cellBounds.setRect(subCell.getBounds());
Poly poly = new Poly(cellBounds);
poly.transform(subTrans);
Rectangle screenBounds = new Rectangle(wnd.databaseToScreen(poly.getBounds2D()));
if (screenBounds.width <= 0 || screenBounds.height <= 0) return true;
// do not cache if the cell is too large (creates immense offscreen buffers)
if (screenBounds.width >= topSz.width/2 && screenBounds.height >= topSz.height/2)
return false;
// if this is the first use, create the offscreen buffer
if (expandedCellCount == null)
{
expandedCellCount = new ExpandedCellInfo();
expandedCellCount.instanceCount = 0;
expandedCellCount.wnd = null;
expandedCells.put(expandedName, expandedCellCount);
}
// render into the offscreen buffer (on the first time)
EditWindow renderedCell = expandedCellCount.wnd;
if (renderedCell == null)
{
renderedCell = EditWindow.CreateElectricDoc(subCell, null);
expandedCellCount.wnd = renderedCell;
renderedCell.setScreenSize(new Dimension(screenBounds.width, screenBounds.height));
renderedCell.setScale(wnd.getScale());
renderedCell.getOffscreen().clearImage(true);
Point2D cellCtr = new Point2D.Double(cellBounds.getCenterX(), cellBounds.getCenterY());
subTrans.transform(cellCtr, cellCtr);
renderedCell.setOffset(cellCtr);
// render the contents of the expanded cell into its own offscreen cache
renderedCell.getOffscreen().renderedWindow = false;
renderedCell.getOffscreen().drawCell(subCell, bounds, subTrans, false);
offscreensCreated++;
}
// copy out of the offscreen buffer into the main buffer
copyBits(renderedCell, screenBounds);
offscreensUsed++;
return true;
}
/**
* Recursive method to count the number of times that a cell-transformation is used
*/
private void countCell(Cell cell, AffineTransform prevTrans)
{
// look for subcells
for(Iterator nodes = cell.getNodes(); nodes.hasNext(); )
{
NodeInst ni = (NodeInst)nodes.next();
if (!(ni.getProto() instanceof Cell)) continue;
countNode(ni, prevTrans);
}
}
/**
* Recursive method to count the number of times that a cell-transformation is used
*/
private void countNode(NodeInst ni, AffineTransform trans)
{
NodeProto np = ni.getProto();
Cell subCell = (Cell)np;
// if the node is tiny, it will be approximated
double halfWidth = Math.max(ni.getXSize(), ni.getYSize()) / 2;
if (halfWidth * wnd.getScale() < 1) return;
// see if the node is completely clipped from the screen
Point2D ctr = ni.getTrueCenter();
trans.transform(ctr, ctr);
Rectangle2D databaseBounds = wnd.getDisplayedBounds();
double ctrX = ctr.getX();
double ctrY = ctr.getY();
if (ctrX + halfWidth < databaseBounds.getMinX()) return;
if (ctrX - halfWidth > databaseBounds.getMaxX()) return;
if (ctrY + halfWidth < databaseBounds.getMinY()) return;
if (ctrY - halfWidth > databaseBounds.getMaxY()) return;
// only interested in expanded instances
if (!ni.isExpanded()) return;
// transform into the subcell
AffineTransform localTrans = ni.rotateOut(trans);
AffineTransform subTrans = ni.translateOut(localTrans);
// compute where this cell lands on the screen
Rectangle2D cellBounds = subCell.getBounds();
Poly poly = new Poly(cellBounds);
poly.transform(subTrans);
Rectangle screenBounds = wnd.databaseToScreen(poly.getBounds2D());
if (screenBounds.width <= 0 || screenBounds.height <= 0) return;
if (screenBounds.width < sz.width/2 || screenBounds.height <= sz.height/2)
{
// construct the cell name that combines with the transformation
String expandedName = makeExpandedName(subCell, subTrans);
ExpandedCellInfo expansionCount = (ExpandedCellInfo)expandedCells.get(expandedName);
if (expansionCount == null)
{
expansionCount = new ExpandedCellInfo();
expansionCount.instanceCount = 1;
expandedCells.put(expandedName, expansionCount);
} else
{
expansionCount.instanceCount++;
return;
}
}
// now recurse
countCell(subCell, subTrans);
}
/**
* Method to construct a string that describes a transformation of a cell.
* Appends the upper-left 2x2 part of the transformation matrix to the cell name.
* Scaling by 100 and making it an integer ensures that similar transformation
* matrices get merged into one name.
*/
private String makeExpandedName(Cell subCell, AffineTransform subTrans)
{
int t00 = (int)(subTrans.getScaleX() * 100);
int t01 = (int)(subTrans.getShearX() * 100);
int t10 = (int)(subTrans.getShearY() * 100);
int t11 = (int)(subTrans.getScaleY() * 100);
String expandedName = subCell.describe() + " " + t00 + " " + t01 + " " + t10 + " " + t11;
return expandedName;
}
/**
* Method to copy the offscreen bits for a cell into the offscreen bits for the entire screen.
*/
private void copyBits(EditWindow renderedCell, Rectangle screenBounds)
{
PixelDrawing srcOffscreen = renderedCell.getOffscreen();
if (srcOffscreen == null) return;
// if (srcOffscreen.layerBitMaps == null)
// {
// System.out.println("Null bitmaps, at "+screenBounds);
// return;
// }
Dimension dim = srcOffscreen.sz;
// copy the opaque and transparent layers
for(int srcY=0; srcY<dim.height; srcY++)
{
int destY = srcY + screenBounds.y;
if (destY < 0 || destY >= sz.height) continue;
int srcBase = srcY * dim.width;
int destBase = destY * sz.width;
for(int srcX=0; srcX<dim.width; srcX++)
{
int destX = srcX + screenBounds.x;
if (destX < 0 || destX >= sz.width) continue;
int srcColor = srcOffscreen.opaqueData[srcBase + srcX];
if (srcColor != backgroundValue)
opaqueData[destBase + destX] = srcColor;
for(int i=0; i<numLayerBitMaps; i++)
{
byte [][] srcLayerBitMap = srcOffscreen.layerBitMaps[i];
if (srcLayerBitMap == null) continue;
byte [] srcRow = srcLayerBitMap[srcY];
byte [][] destLayerBitMap = getLayerBitMap(i);
byte [] destRow = destLayerBitMap[destY];
if ((srcRow[srcX>>3] & (1<<(srcX&7))) != 0)
destRow[destX>>3] |= (1 << (destX&7));
}
}
}
// copy the patterned opaque layers
for(Iterator it = srcOffscreen.patternedOpaqueLayers.keySet().iterator(); it.hasNext(); )
{
Layer layer = (Layer)it.next();
PatternedOpaqueLayer polSrc = (PatternedOpaqueLayer)srcOffscreen.patternedOpaqueLayers.get(layer);
byte [][] srcLayerBitMap = polSrc.bitMap;
if (srcLayerBitMap == null) continue;
if (renderedWindow)
{
// this is the top-level of display: convert patterned opaque to patterns
EGraphics desc = layer.getGraphics();
int col = desc.getColor().getRGB() & 0xFFFFFF;
int [] pattern = desc.getPattern();
// setup pattern for this row
for(int srcY=0; srcY<dim.height; srcY++)
{
int destY = srcY + screenBounds.y;
if (destY < 0 || destY >= sz.height) continue;
int destBase = destY * sz.width;
int pat = pattern[destY&15];
if (pat == 0) continue;
byte [] srcRow = srcLayerBitMap[srcY];
for(int srcX=0; srcX<dim.width; srcX++)
{
int destX = srcX + screenBounds.x;
if (destX < 0 || destX >= sz.width) continue;
if ((srcRow[srcX>>3] & (1<<(srcX&7))) != 0)
{
if ((pat & (0x8000 >> (destX&15))) != 0)
opaqueData[destBase + destX] = col;
}
}
}
} else
{
// a lower level being copied to a low level: just copy the patterned opaque layers
PatternedOpaqueLayer polDest = (PatternedOpaqueLayer)patternedOpaqueLayers.get(layer);
if (polDest == null)
{
polDest = new PatternedOpaqueLayer();
polDest.bitMap = new byte[sz.height][];
for(int y=0; y<sz.height; y++)
{
byte [] row = new byte[numBytesPerRow];
for(int x=0; x<numBytesPerRow; x++) row[x] = 0;
polDest.bitMap[y] = row;
}
patternedOpaqueLayers.put(layer, polDest);
}
byte [][] destLayerBitMap = polDest.bitMap;
for(int srcY=0; srcY<dim.height; srcY++)
{
int destY = srcY + screenBounds.y;
if (destY < 0 || destY >= sz.height) continue;
int destBase = destY * sz.width;
byte [] srcRow = srcLayerBitMap[srcY];
byte [] destRow = destLayerBitMap[destY];
for(int srcX=0; srcX<dim.width; srcX++)
{
int destX = srcX + screenBounds.x;
if (destX < 0 || destX >= sz.width) continue;
if ((srcRow[srcX>>3] & (1<<(srcX&7))) != 0)
destRow[destX>>3] |= (1 << (destX&7));
}
}
}
}
}
// ************************************* RENDERING POLY SHAPES *************************************
/**
* Method to draw polygon "poly", transformed through "trans".
*/
private void drawPolys(Poly [] polys, AffineTransform trans)
{
if (polys == null) return;
for(int i = 0; i < polys.length; i++)
{
// get the polygon and transform it
Poly poly = polys[i];
if (poly == null) continue;
Layer layer = poly.getLayer();
EGraphics graphics = null;
if (layer != null)
{
if (!layer.isVisible()) continue;
graphics = layer.getGraphics();
}
// transform the bounds
poly.transform(trans);
// render the polygon
long startTime = System.currentTimeMillis();
renderPoly(poly, graphics);
renderPolyTime += (System.currentTimeMillis() - startTime);
// handle refreshing
if (periodicRefresh)
{
objectCount++;
if (objectCount > 100)
{
objectCount = 0;
long currentTime = System.currentTimeMillis();
if (currentTime - lastRefreshTime > 1000)
{
lastRefreshTime = currentTime;
wnd.repaint();
}
}
}
}
}
private byte [][] getLayerBitMap(int layerNum)
{
if (layerNum < 0) return null;
byte [][] layerBitMap = layerBitMaps[layerNum];
if (layerBitMap == null)
{
// allocate this bitplane dynamically
layerBitMap = new byte[sz.height][];
for(int y=0; y<sz.height; y++)
{
byte [] row = new byte[numBytesPerRow];
for(int x=0; x<numBytesPerRow; x++) row[x] = 0;
layerBitMap[y] = row;
}
layerBitMaps[layerNum] = layerBitMap;
numLayerBitMapsCreated++;
}
return layerBitMap;
}
/**
* Render a Poly to the offscreen buffer.
*/
private void renderPoly(Poly poly, EGraphics graphics)
{
int layerNum = -1;
if (graphics != null) layerNum = graphics.getTransparentLayer() - 1;
if (layerNum >= numLayerBitMaps) return;
byte [][] layerBitMap = getLayerBitMap(layerNum);
Poly.Type style = poly.getStyle();
// only do this for lower-level (cached cells)
if (!renderedWindow)
{
// for fills, handle patterned opaque layers specially
if (style == Poly.Type.FILLED || style == Poly.Type.DISC)
{
// see if it is opaque
if (layerBitMap == null)
{
// see if it is patterned
if (graphics.isPatternedOnDisplay())
{
Layer layer = poly.getLayer();
PatternedOpaqueLayer pol = (PatternedOpaqueLayer)patternedOpaqueLayers.get(layer);
if (pol == null)
{
pol = new PatternedOpaqueLayer();
pol.bitMap = new byte[sz.height][];
for(int y=0; y<sz.height; y++)
{
byte [] row = new byte[numBytesPerRow];
for(int x=0; x<numBytesPerRow; x++) row[x] = 0;
pol.bitMap[y] = row;
}
patternedOpaqueLayers.put(layer, pol);
}
layerBitMap = pol.bitMap;
graphics = null;
}
}
}
}
// now draw it
Point2D [] points = poly.getPoints();
if (style == Poly.Type.FILLED)
{
Rectangle2D bounds = poly.getBox();
if (bounds != null)
{
// convert coordinates
int lX = wnd.databaseToScreenX(bounds.getMinX());
int hX = wnd.databaseToScreenX(bounds.getMaxX());
int hY = wnd.databaseToScreenY(bounds.getMinY());
int lY = wnd.databaseToScreenY(bounds.getMaxY());
// do clipping
if (lX < 0) lX = 0;
if (hX >= sz.width) hX = sz.width-1;
if (lY < 0) lY = 0;
if (hY >= sz.height) hY = sz.height-1;
if (lX > hX || lY > hY) return;
// draw the box
drawBox(lX, hX, lY, hY, layerBitMap, graphics);
return;
}
Point [] intPoints = new Point[points.length];
for(int i=0; i<points.length; i++)
intPoints[i] = wnd.databaseToScreen(points[i]);
Point [] clippedPoints = clipPoly(intPoints, 0, sz.width-1, 0, sz.height-1);
drawPolygon(clippedPoints, layerBitMap, graphics);
return;
}
if (style == Poly.Type.CROSSED)
{
Point pt0a = wnd.databaseToScreen(points[0]);
Point pt1a = wnd.databaseToScreen(points[1]);
Point pt2a = wnd.databaseToScreen(points[2]);
Point pt3a = wnd.databaseToScreen(points[3]);
Point pt0b = new Point(pt0a); Point pt0c = new Point(pt0a);
Point pt1b = new Point(pt1a); Point pt1c = new Point(pt1a);
Point pt2b = new Point(pt2a); Point pt2c = new Point(pt2a);
Point pt3b = new Point(pt3a); Point pt3c = new Point(pt3a);
drawLine(pt0a, pt1a, layerBitMap, graphics, 0);
drawLine(pt1b, pt2a, layerBitMap, graphics, 0);
drawLine(pt2b, pt3a, layerBitMap, graphics, 0);
drawLine(pt3b, pt0b, layerBitMap, graphics, 0);
drawLine(pt0c, pt2c, layerBitMap, graphics, 0);
drawLine(pt1c, pt3c, layerBitMap, graphics, 0);
return;
}
if (style.isText())
{
Rectangle2D bounds = poly.getBounds2D();
Rectangle rect = wnd.databaseToScreen(bounds);
TextDescriptor descript = poly.getTextDescriptor();
String str = poly.getString();
drawText(rect, style, descript, str, layerBitMap, graphics);
return;
}
if (style == Poly.Type.CLOSED || style == Poly.Type.OPENED || style == Poly.Type.OPENEDT1 ||
style == Poly.Type.OPENEDT2 || style == Poly.Type.OPENEDT3)
{
int lineType = 0;
if (style == Poly.Type.OPENEDT1) lineType = 1; else
if (style == Poly.Type.OPENEDT2) lineType = 2; else
if (style == Poly.Type.OPENEDT3) lineType = 3;
for(int j=1; j<points.length; j++)
{
Point pt1 = wnd.databaseToScreen(points[j-1]);
Point pt2 = wnd.databaseToScreen(points[j]);
drawLine(pt1, pt2, layerBitMap, graphics, lineType);
}
if (style == Poly.Type.CLOSED)
{
Point pt1 = wnd.databaseToScreen(points[points.length-1]);
Point pt2 = wnd.databaseToScreen(points[0]);
drawLine(pt1, pt2, layerBitMap, graphics, lineType);
}
return;
}
if (style == Poly.Type.VECTORS)
{
for(int j=0; j<points.length; j+=2)
{
Point pt1 = wnd.databaseToScreen(points[j]);
Point pt2 = wnd.databaseToScreen(points[j+1]);
drawLine(pt1, pt2, layerBitMap, graphics, 0);
}
return;
}
if (style == Poly.Type.CIRCLE)
{
Point center = wnd.databaseToScreen(points[0]);
Point edge = wnd.databaseToScreen(points[1]);
drawCircle(center, edge, layerBitMap, graphics);
return;
}
if (style == Poly.Type.THICKCIRCLE)
{
Point center = wnd.databaseToScreen(points[0]);
Point edge = wnd.databaseToScreen(points[1]);
drawThickCircle(center, edge, layerBitMap, graphics);
return;
}
if (style == Poly.Type.DISC)
{
Point center = wnd.databaseToScreen(points[0]);
Point edge = wnd.databaseToScreen(points[1]);
drawDisc(center, edge, layerBitMap, graphics);
return;
}
if (style == Poly.Type.CIRCLEARC || style == Poly.Type.THICKCIRCLEARC)
{
Point center = wnd.databaseToScreen(points[0]);
Point edge1 = wnd.databaseToScreen(points[1]);
Point edge2 = wnd.databaseToScreen(points[2]);
drawCircleArc(center, edge1, edge2, style == Poly.Type.THICKCIRCLEARC, layerBitMap, graphics);
return;
}
if (style == Poly.Type.CROSS)
{
// draw the cross
drawCross(poly, graphics);
return;
}
if (style == Poly.Type.BIGCROSS)
{
// draw the big cross
Point center = wnd.databaseToScreen(points[0]);
int size = 5;
drawLine(new Point(center.x-size, center.y), new Point(center.x+size, center.y), layerBitMap, graphics, 0);
drawLine(new Point(center.x, center.y-size), new Point(center.x, center.y+size), layerBitMap, graphics, 0);
return;
}
}
// ************************************* BOX DRAWING *************************************
/**
* Method to draw a box on the off-screen buffer.
*/
private void drawBox(int lX, int hX, int lY, int hY, byte [][] layerBitMap, EGraphics desc)
{
// get color and pattern information
int col = 0;
int [] pattern = null;
if (desc != null)
{
col = desc.getColor().getRGB() & 0xFFFFFF;
if (desc.isPatternedOnDisplay())
pattern = desc.getPattern();
}
// different code for patterned and solid
if (pattern == null)
{
// solid fill
if (layerBitMap == null)
{
// solid fill in opaque area
for(int y=lY; y<=hY; y++)
{
int baseIndex = y * sz.width + lX;
for(int x=lX; x<=hX; x++)
opaqueData[baseIndex++] = col;
}
} else
{
// solid fill in transparent layers
for(int y=lY; y<=hY; y++)
{
byte [] row = layerBitMap[y];
for(int x=lX; x<=hX; x++)
row[x>>3] |= (1 << (x&7));
}
}
} else
{
// patterned fill
if (layerBitMap == null)
{
// patterned fill in opaque area
for(int y=lY; y<=hY; y++)
{
// setup pattern for this row
int pat = pattern[y&15];
if (pat == 0) continue;
int baseIndex = y * sz.width;
for(int x=lX; x<=hX; x++)
{
if ((pat & (0x8000 >> (x&15))) != 0)
opaqueData[baseIndex + x] = col;
}
}
} else
{
// patterned fill in transparent layers
for(int y=lY; y<=hY; y++)
{
// setup pattern for this row
int pat = pattern[y&15];
if (pat == 0) continue;
byte [] row = layerBitMap[y];
for(int x=lX; x<=hX; x++)
{
if ((pat & (0x8000 >> (x&15))) != 0)
row[x>>3] |= (1 << (x&7));
}
}
}
}
}
// ************************************* LINE DRAWING *************************************
/**
* Method to draw a line on the off-screen buffer.
*/
private void drawLine(Point pt1, Point pt2, byte [][] layerBitMap, EGraphics desc, int texture)
{
// first clip the line
if (clipLine(pt1, pt2, 0, sz.width-1, 0, sz.height-1)) return;
// now draw with the proper line type
switch (texture)
{
case 0: drawSolidLine(pt1.x, pt1.y, pt2.x, pt2.y, layerBitMap, desc); break;
case 1: drawPatLine(pt1.x, pt1.y, pt2.x, pt2.y, layerBitMap, desc, 0x88); break;
case 2: drawPatLine(pt1.x, pt1.y, pt2.x, pt2.y, layerBitMap, desc, 0xE7); break;
case 3: drawThickLine(pt1.x, pt1.y, pt2.x, pt2.y, layerBitMap, desc); break;
}
}
private void drawCross(Poly poly, EGraphics graphics)
{
Point2D [] points = poly.getPoints();
Point center = wnd.databaseToScreen(points[0]);
int size = 3;
drawLine(new Point(center.x-size, center.y), new Point(center.x+size, center.y), null, graphics, 0);
drawLine(new Point(center.x, center.y-size), new Point(center.x, center.y+size), null, graphics, 0);
}
private void drawSolidLine(int x1, int y1, int x2, int y2, byte [][] layerBitMap, EGraphics desc)
{
// get color and pattern information
int col = 0;
int [] pattern = null;
if (desc != null)
{
col = desc.getColor().getRGB() & 0xFFFFFF;
if (desc.isPatternedOnDisplay())
pattern = desc.getPattern();
}
// initialize the Bresenham algorithm
int dx = Math.abs(x2-x1);
int dy = Math.abs(y2-y1);
if (dx > dy)
{
// initialize for lines that increment along X
int incr1 = 2 * dy;
int incr2 = 2 * (dy - dx);
int d = incr2;
int x, y, xend, yend, yincr;
if (x1 > x2)
{
x = x2; y = y2; xend = x1; yend = y1;
} else
{
x = x1; y = y1; xend = x2; yend = y2;
}
if (yend < y) yincr = -1; else yincr = 1;
if (layerBitMap == null) opaqueData[y * sz.width + x] = col; else
layerBitMap[y][x>>3] |= (1 << (x&7));
// draw line that increments along X
while (x < xend)
{
x++;
if (d < 0) d += incr1; else
{
y += yincr; d += incr2;
}
if (layerBitMap == null) opaqueData[y * sz.width + x] = col; else
layerBitMap[y][x>>3] |= (1 << (x&7));
}
} else
{
// initialize for lines that increment along Y
int incr1 = 2 * dx;
int incr2 = 2 * (dx - dy);
int d = incr2;
int x, y, xend, yend, xincr;
if (y1 > y2)
{
x = x2; y = y2; xend = x1; yend = y1;
} else
{
x = x1; y = y1; xend = x2; yend = y2;
}
if (xend < x) xincr = -1; else xincr = 1;
if (layerBitMap == null) opaqueData[y * sz.width + x] = col; else
layerBitMap[y][x>>3] |= (1 << (x&7));
// draw line that increments along X
while (y < yend)
{
y++;
if (d < 0) d += incr1; else
{
x += xincr; d += incr2;
}
if (layerBitMap == null) opaqueData[y * sz.width + x] = col; else
layerBitMap[y][x>>3] |= (1 << (x&7));
}
}
}
private void drawPatLine(int x1, int y1, int x2, int y2, byte [][] layerBitMap, EGraphics desc, int pattern)
{
// get color and pattern information
int col = 0;
if (desc != null) col = desc.getColor().getRGB() & 0xFFFFFF;
// initialize counter for line style
int i = 0;
// initialize the Bresenham algorithm
int dx = Math.abs(x2-x1);
int dy = Math.abs(y2-y1);
if (dx > dy)
{
// initialize for lines that increment along X
int incr1 = 2 * dy;
int incr2 = 2 * (dy - dx);
int d = incr2;
int x, y, xend, yend, yincr;
if (x1 > x2)
{
x = x2; y = y2; xend = x1; yend = y1;
} else
{
x = x1; y = y1; xend = x2; yend = y2;
}
if (yend < y) yincr = -1; else yincr = 1;
if (layerBitMap == null) opaqueData[y * sz.width + x] = col; else
layerBitMap[y][x>>3] |= (1 << (x&7));
// draw line that increments along X
while (x < xend)
{
x++;
if (d < 0) d += incr1; else
{
y += yincr; d += incr2;
}
if (i == 7) i = 0; else i++;
if ((pattern & (1 << i)) == 0) continue;
if (layerBitMap == null) opaqueData[y * sz.width + x] = col; else
layerBitMap[y][x>>3] |= (1 << (x&7));
}
} else
{
// initialize for lines that increment along Y
int incr1 = 2 * dx;
int incr2 = 2 * (dx - dy);
int d = incr2;
int x, y, xend, yend, xincr;
if (y1 > y2)
{
x = x2; y = y2; xend = x1; yend = y1;
} else
{
x = x1; y = y1; xend = x2; yend = y2;
}
if (xend < x) xincr = -1; else xincr = 1;
if (layerBitMap == null) opaqueData[y * sz.width + x] = col; else
layerBitMap[y][x>>3] |= (1 << (x&7));
// draw line that increments along X
while (y < yend)
{
y++;
if (d < 0) d += incr1; else
{
x += xincr; d += incr2;
}
if (i == 7) i = 0; else i++;
if ((pattern & (1 << i)) == 0) continue;
if (layerBitMap == null) opaqueData[y * sz.width + x] = col; else
layerBitMap[y][x>>3] |= (1 << (x&7));
}
}
}
private void drawThickLine(int x1, int y1, int x2, int y2, byte [][] layerBitMap, EGraphics desc)
{
// get color and pattern information
int col = 0;
if (desc != null) col = desc.getColor().getRGB() & 0xFFFFFF;
// initialize the Bresenham algorithm
int dx = Math.abs(x2-x1);
int dy = Math.abs(y2-y1);
if (dx > dy)
{
// initialize for lines that increment along X
int incr1 = 2 * dy;
int incr2 = 2 * (dy - dx);
int d = incr2;
int x, y, xend, yend, yincr;
if (x1 > x2)
{
x = x2; y = y2; xend = x1; yend = y1;
} else
{
x = x1; y = y1; xend = x2; yend = y2;
}
if (yend < y) yincr = -1; else yincr = 1;
drawThickPoint(x, y, layerBitMap, col);
// draw line that increments along X
while (x < xend)
{
x++;
if (d < 0) d += incr1; else
{
y += yincr;
d += incr2;
}
drawThickPoint(x, y, layerBitMap, col);
}
} else
{
// initialize for lines that increment along Y
int incr1 = 2 * dx;
int incr2 = 2 * (dx - dy);
int d = incr2;
int x, y, xend, yend, xincr;
if (y1 > y2)
{
x = x2; y = y2; xend = x1; yend = y1;
} else
{
x = x1; y = y1; xend = x2; yend = y2;
}
if (xend < x) xincr = -1; else xincr = 1;
drawThickPoint(x, y, layerBitMap, col);
// draw line that increments along X
while (y < yend)
{
y++;
if (d < 0) d += incr1; else
{
x += xincr;
d += incr2;
}
drawThickPoint(x, y, layerBitMap, col);
}
}
}
// ************************************* POLYGON DRAWING *************************************
/**
* Method to draw a polygon on the off-screen buffer.
*/
private void drawPolygon(Point [] points, byte [][] layerBitMap, EGraphics desc)
{
// get color and pattern information
int col = 0;
int [] pattern = null;
if (desc != null)
{
col = desc.getColor().getRGB() & 0xFFFFFF;
if (desc.isPatternedOnDisplay())
pattern = desc.getPattern();
}
// fill in internal structures
PolySeg edgelist = null;
PolySeg [] polySegs = new PolySeg[points.length];
for(int i=0; i<points.length; i++)
{
polySegs[i] = new PolySeg();
if (i == 0)
{
polySegs[i].fx = points[points.length-1].x;
polySegs[i].fy = points[points.length-1].y;
} else
{
polySegs[i].fx = points[i-1].x;
polySegs[i].fy = points[i-1].y;
}
polySegs[i].tx = points[i].x; polySegs[i].ty = points[i].y;
}
for(int i=0; i<points.length; i++)
{
// draw the edge lines to make the polygon clean
if (pattern != null && desc.isOutlinedOnDisplay())
drawSolidLine(polySegs[i].fx, polySegs[i].fy, polySegs[i].tx, polySegs[i].ty, layerBitMap, desc);
// compute the direction of this edge
int j = polySegs[i].ty - polySegs[i].fy;
if (j > 0) polySegs[i].direction = 1; else
if (j < 0) polySegs[i].direction = -1; else
polySegs[i].direction = 0;
// compute the X increment of this edge
if (j == 0) polySegs[i].increment = 0; else
{
polySegs[i].increment = polySegs[i].tx - polySegs[i].fx;
if (polySegs[i].increment != 0) polySegs[i].increment =
(polySegs[i].increment * 65536 - j + 1) / j;
}
polySegs[i].tx <<= 16; polySegs[i].fx <<= 16;
// make sure "from" is above "to"
if (polySegs[i].fy > polySegs[i].ty)
{
j = polySegs[i].tx;
polySegs[i].tx = polySegs[i].fx;
polySegs[i].fx = j;
j = polySegs[i].ty;
polySegs[i].ty = polySegs[i].fy;
polySegs[i].fy = j;
}
// insert this edge into the edgelist, sorted by ascending "fy"
if (edgelist == null)
{
edgelist = polySegs[i];
polySegs[i].nextedge = null;
} else
{
// insert by ascending "fy"
if (edgelist.fy > polySegs[i].fy)
{
polySegs[i].nextedge = edgelist;
edgelist = polySegs[i];
} else for(PolySeg a = edgelist; a != null; a = a.nextedge)
{
if (a.nextedge == null ||
a.nextedge.fy > polySegs[i].fy)
{
// insert after this
polySegs[i].nextedge = a.nextedge;
a.nextedge = polySegs[i];
break;
}
}
}
}
// scan polygon and render
int ycur = 0;
PolySeg active = null;
while (active != null || edgelist != null)
{
if (active == null)
{
active = edgelist;
active.nextactive = null;
edgelist = edgelist.nextedge;
ycur = active.fy;
}
// introduce edges from edge list into active list
while (edgelist != null && edgelist.fy <= ycur)
{
// insert "edgelist" into active list, sorted by "fx" coordinate
if (active.fx > edgelist.fx ||
(active.fx == edgelist.fx && active.increment > edgelist.increment))
{
edgelist.nextactive = active;
active = edgelist;
edgelist = edgelist.nextedge;
} else for(PolySeg a = active; a != null; a = a.nextactive)
{
if (a.nextactive == null ||
a.nextactive.fx > edgelist.fx ||
(a.nextactive.fx == edgelist.fx &&
a.nextactive.increment > edgelist.increment))
{
// insert after this
edgelist.nextactive = a.nextactive;
a.nextactive = edgelist;
edgelist = edgelist.nextedge;
break;
}
}
}
// generate regions to be filled in on current scan line
int wrap = 0;
PolySeg left = active;
for(PolySeg edge = active; edge != null; edge = edge.nextactive)
{
wrap = wrap + edge.direction;
if (wrap == 0)
{
int j = (left.fx + 32768) >> 16;
int k = (edge.fx + 32768) >> 16;
if (pattern != null)
{
int pat = pattern[ycur & 15];
if (pat != 0)
{
if (layerBitMap == null)
{
int baseIndex = ycur * sz.width;
for(int x=j; x<=k; x++)
{
if ((pat & (1 << (15-(x&15)))) != 0)
opaqueData[baseIndex + x] = col;
}
} else
{
byte [] row = layerBitMap[ycur];
for(int x=j; x<=k; x++)
{
if ((pat & (1 << (15-(x&15)))) != 0)
row[x>>3] |= (1 << (x&7));
}
}
}
} else
{
if (layerBitMap == null)
{
int baseIndex = ycur * sz.width;
for(int x=j; x<=k; x++)
{
opaqueData[baseIndex + x] = col;
}
} else
{
byte [] row = layerBitMap[ycur];
for(int x=j; x<=k; x++)
{
row[x>>3] |= (1 << (x&7));
}
}
}
left = edge.nextactive;
}
}
ycur++;
// update edges in active list
PolySeg lastedge = null;
for(PolySeg edge = active; edge != null; edge = edge.nextactive)
{
if (ycur >= edge.ty)
{
if (lastedge == null) active = edge.nextactive;
else lastedge.nextactive = edge.nextactive;
} else
{
edge.fx += edge.increment;
lastedge = edge;
}
}
}
}
// ************************************* TEXT DRAWING *************************************
/**
* Method to draw a text on the off-screen buffer
*/
private void drawText(Rectangle rect, Poly.Type style, TextDescriptor descript, String s, byte [][] layerBitMap, EGraphics desc)
{
// quit if string is null
int len = s.length();
if (len == 0) return;
// get parameters
int col = 0;
if (desc != null) col = desc.getColor().getRGB() & 0xFFFFFF;
// get text description
int size = EditWindow.getDefaultFontSize();
int fontStyle = Font.PLAIN;
String fontName = User.getDefaultFont();
boolean italic = false;
boolean bold = false;
boolean underline = false;
int rotation = 0;
if (descript != null)
{
size = descript.getTrueSize(wnd);
if (size < MINIMUMTEXTSIZE) return;
italic = descript.isItalic();
bold = descript.isBold();
underline = descript.isUnderline();
int fontIndex = descript.getFace();
if (fontIndex != 0)
{
TextDescriptor.ActiveFont af = TextDescriptor.ActiveFont.findActiveFont(fontIndex);
if (af != null) fontName = af.getName();
}
rotation = descript.getRotation().getIndex();
}
// get box information for limiting text size
int boxedWidth = -1, boxedHeight = -1;
if (style == Poly.Type.TEXTBOX)
{
boxedWidth = (int)rect.getWidth();
boxedHeight = (int)rect.getHeight();
// clip if not within bounds
- if (drawBounds != null && !drawBounds.intersects(rect)) return;
+ Rectangle2D dbBounds = wnd.screenToDatabase(rect);
+ if (drawBounds != null && !drawBounds.intersects(dbBounds)) return;
}
// create RenderInfo
long startTime = System.currentTimeMillis();
RenderTextInfo renderInfo = new RenderTextInfo();
if (!renderInfo.buildInfo(s, fontName, size, italic, bold, underline, rect, style, rotation))
return;
// check if text is on-screen
Rectangle2D dbBounds = wnd.screenToDatabase(renderInfo.bounds);
if (drawBounds != null && !drawBounds.intersects(dbBounds))
return;
// render the text
Raster ras = renderText(renderInfo);
renderTextTime += (System.currentTimeMillis() - startTime);
//System.out.println("Rendered text: "+s);
if (ras == null) return;
Point pt = getTextCorner(ras.getWidth(), ras.getHeight(), style, rect, rotation);
int atX = pt.x;
int atY = pt.y;
DataBufferByte dbb = (DataBufferByte)ras.getDataBuffer();
byte [] samples = dbb.getData();
int sx, ex;
int rasWidth = ras.getWidth();
int rasHeight = ras.getHeight();
switch (rotation)
{
case 0: // no rotation
if (atX < 0) sx = -atX; else sx = 0;
if (atX+rasWidth >= sz.width) ex = sz.width-1 - atX; else
ex = rasWidth;
for(int y=0; y<rasHeight; y++)
{
int trueY = atY + y;
if (trueY < 0 || trueY >= sz.height) continue;
// setup pointers for filling this row
byte [] row = null;
int baseIndex = 0;
if (layerBitMap == null) baseIndex = trueY * sz.width; else
row = layerBitMap[trueY];
int samp = y * rasWidth + sx;
for(int x=sx; x<ex; x++)
{
int trueX = atX + x;
int alpha = samples[samp++] & 0xFF;
if (alpha == 0) continue;
if (layerBitMap == null)
{
// drawing opaque
int fullIndex = baseIndex + trueX;
int pixelValue = opaqueData[fullIndex];
int oldAlpha = (pixelValue >> 24) & 0xFF;
int color = col;
if (oldAlpha == 0)
{
// blend with opaque
if (alpha != 0xFF) color = alphaBlend(color, pixelValue, alpha);
} else if (oldAlpha == 0xFF)
{
// blend with background
if (alpha < 255) color = (color & 0xFFFFFF) | (alpha << 24);
}
opaqueData[fullIndex] = color;
} else
{
// draw in a transparent layer
if (alpha >= 128) row[trueX>>3] |= (1 << (trueX&7));
}
}
}
break;
case 1: // 90 degrees counterclockwise
if (atX-rasHeight < 0) sx = rasHeight-atX; else sx = 0;
if (atX >= sz.height) ex = sz.height - atX; else
ex = rasHeight;
for(int y=0; y<rasWidth; y++)
{
int trueY = atY + y;
if (trueY < 0 || trueY >= sz.height) continue;
// setup pointers for filling this row
byte [] row = null;
int baseIndex = 0;
if (layerBitMap == null) baseIndex = trueY * sz.width; else
row = layerBitMap[trueY];
for(int x=sx; x<ex; x++)
{
int trueX = atX + x;
int alpha = samples[x * rasWidth + (rasWidth-y-1)] & 0xFF;
if (alpha == 0) continue;
if (layerBitMap == null)
{
// drawing opaque
int fullIndex = baseIndex + trueX;
int pixelValue = opaqueData[fullIndex];
int oldAlpha = (pixelValue >> 24) & 0xFF;
int color = col;
if (oldAlpha == 0)
{
// blend with opaque
if (alpha != 0xFF) color = alphaBlend(color, pixelValue, alpha);
} else if (oldAlpha == 0xFF)
{
// blend with background
if (alpha < 255) color = (color & 0xFFFFFF) | (alpha << 24);
}
opaqueData[fullIndex] = color;
} else
{
if (alpha >= 128) row[trueX>>3] |= (1 << (trueX&7));
}
}
}
break;
case 2: // 180 degrees
atX -= rasWidth;
atY -= rasHeight;
if (atX < 0) sx = -atX; else sx = 0;
if (atX+rasWidth >= sz.width) ex = sz.width-1 - atX; else
ex = rasWidth;
for(int y=0; y<rasHeight; y++)
{
int trueY = atY + y;
if (trueY < 0 || trueY >= sz.height) continue;
// setup pointers for filling this row
byte [] row = null;
int baseIndex = 0;
if (layerBitMap == null) baseIndex = trueY * sz.width; else
row = layerBitMap[trueY];
for(int x=sx; x<ex; x++)
{
int trueX = atX + x;
int alpha = samples[(rasHeight-y-1) * rasWidth + (rasWidth-x-1)] & 0xFF;
if (alpha == 0) continue;
if (layerBitMap == null)
{
// drawing opaque
int fullIndex = baseIndex + trueX;
int pixelValue = opaqueData[fullIndex];
int oldAlpha = (pixelValue >> 24) & 0xFF;
int color = col;
if (oldAlpha == 0)
{
// blend with opaque
if (alpha != 0xFF) color = alphaBlend(color, pixelValue, alpha);
} else if (oldAlpha == 0xFF)
{
// blend with background
if (alpha < 255) color = (color & 0xFFFFFF) | (alpha << 24);
}
opaqueData[fullIndex] = color;
} else
{
if (alpha >= 128) row[trueX>>3] |= (1 << (trueX&7));
}
}
}
break;
case 3: // 90 degrees clockwise
if (atX-rasHeight < 0) sx = rasHeight-atX; else sx = 0;
if (atX >= sz.height) ex = sz.height - atX; else
ex = rasHeight;
for(int y=0; y<rasWidth; y++)
{
int trueY = atY + y;
if (trueY < 0 || trueY >= sz.height) continue;
// setup pointers for filling this row
byte [] row = null;
int baseIndex = 0;
if (layerBitMap == null) baseIndex = trueY * sz.width; else
row = layerBitMap[trueY];
for(int x=sx; x<ex; x++)
{
int trueX = atX + x;
int alpha = samples[(rasHeight-x-1) * rasWidth + y] & 0xFF;
if (alpha == 0) continue;
if (layerBitMap == null)
{
// drawing opaque
int fullIndex = baseIndex + trueX;
int pixelValue = opaqueData[fullIndex];
int oldAlpha = (pixelValue >> 24) & 0xFF;
int color = col;
if (oldAlpha == 0)
{
// blend with opaque
if (alpha != 0xFF) color = alphaBlend(color, pixelValue, alpha);
} else if (oldAlpha == 0xFF)
{
// blend with background
if (alpha < 255) color = (color & 0xFFFFFF) | (alpha << 24);
}
opaqueData[fullIndex] = color;
} else
{
if (alpha >= 128) row[trueX>>3] |= (1 << (trueX&7));
}
}
}
break;
}
}
private int alphaBlend(int color, int backgroundColor, int alpha)
{
int red = (color >> 16) & 0xFF;
int green = (color >> 8) & 0xFF;
int blue = color & 0xFF;
int inverseAlpha = 254 - alpha;
int redBack = (backgroundColor >> 16) & 0xFF;
int greenBack = (backgroundColor >> 8) & 0xFF;
int blueBack = backgroundColor & 0xFF;
red = ((red * alpha) + (redBack * inverseAlpha)) / 255;
green = ((green * alpha) + (greenBack * inverseAlpha)) / 255;
blue = ((blue * alpha) + (blueBack * inverseAlpha)) / 255;
color = (red << 16) | (green << 8) + blue;
return color;
}
private static class RenderTextInfo {
private Font font;
private GlyphVector gv;
private LineMetrics lm;
private Point2D anchorPoint;
private Rectangle2D rasBounds; // the raster bounds of the unrotated text, in pixels (screen units)
private Rectangle2D bounds; // the real bounds of the rotated, anchored text (in screen units)
private boolean underline;
private boolean buildInfo(String msg, String fontName, int tSize, boolean italic, boolean bold, boolean underline,
Rectangle probableBoxedBounds, Poly.Type style, int rotation) {
font = getFont(msg, fontName, tSize, italic, bold, underline);
this.underline = underline;
// convert the text to a GlyphVector
FontRenderContext frc = new FontRenderContext(null, true, true);
gv = font.createGlyphVector(frc, msg);
lm = font.getLineMetrics(msg, frc);
// figure bounding box of text
//Rectangle rasRect = gv.getOutline(0, (float)(lm.getAscent()-lm.getLeading())).getBounds();
Rectangle2D rasRect = gv.getLogicalBounds();
int width = (int)rasRect.getWidth();
int height = (int)(lm.getHeight()+0.5);
if (width <= 0 || height <= 0) return false;
int fontStyle = font.getStyle();
int boxedWidth = (int)probableBoxedBounds.getWidth();
int boxedHeight = (int)probableBoxedBounds.getHeight();
// if text is to be "boxed", make sure it fits
if (boxedWidth > 0 && boxedHeight > 0)
{
if (width > boxedWidth || height > boxedHeight)
{
double scale = Math.min((double)boxedWidth / width, (double)boxedHeight / height);
font = new Font(fontName, fontStyle, (int)(tSize*scale));
if (font != null)
{
// convert the text to a GlyphVector
gv = font.createGlyphVector(frc, msg);
lm = font.getLineMetrics(msg, frc);
//rasRect = gv.getOutline(0, (float)(lm.getAscent()-lm.getLeading())).getBounds();
rasRect = gv.getLogicalBounds();
height = (int)(lm.getHeight()+0.5);
if (height <= 0) return false;
width = (int)rasRect.getWidth();
}
}
}
if (underline) height++;
rasBounds = new Rectangle2D.Double(0, (float)lm.getAscent()-lm.getLeading(), width, height);
anchorPoint = getTextCorner(width, height, style, probableBoxedBounds, rotation);
if (rotation == 1 || rotation == 3) {
bounds = new Rectangle2D.Double(anchorPoint.getX(), anchorPoint.getY(), height, width);
} else {
bounds = new Rectangle2D.Double(anchorPoint.getX(), anchorPoint.getY(), width, height);
}
return true;
}
}
/**
* Method to return the coordinates of the lower-left corner of text in this window.
* @param gv the GlyphVector describing the text.
* @param style the anchor information for the text.
* @param rect the bounds of the polygon containing the text.
* @param rotation the rotation of the text (0=normal, 1=90 counterclockwise, 2=180, 3=90 clockwise).
* @return the coordinates of the lower-left corner of the text.
*/
private static Point getTextCorner(int rasterWidth, int rasterHeight, Poly.Type style, Rectangle rect, int rotation)
{
// adjust to place text in the center
int textWidth = rasterWidth;
int textHeight = rasterHeight;
int offX = 0, offY = 0;
if (style == Poly.Type.TEXTCENT)
{
offX = -textWidth/2;
offY = -textHeight/2;
} else if (style == Poly.Type.TEXTTOP)
{
offX = -textWidth/2;
} else if (style == Poly.Type.TEXTBOT)
{
offX = -textWidth/2;
offY = -textHeight;
} else if (style == Poly.Type.TEXTLEFT)
{
offY = -textHeight/2;
} else if (style == Poly.Type.TEXTRIGHT)
{
offX = -textWidth;
offY = -textHeight/2;
} else if (style == Poly.Type.TEXTTOPLEFT)
{
} else if (style == Poly.Type.TEXTBOTLEFT)
{
offY = -textHeight;
} else if (style == Poly.Type.TEXTTOPRIGHT)
{
offX = -textWidth;
} else if (style == Poly.Type.TEXTBOTRIGHT)
{
offX = -textWidth;
offY = -textHeight;
} if (style == Poly.Type.TEXTBOX)
{
// if (textWidth > rect.getWidth())
// {
// // text too big for box: scale it down
// textScale *= rect.getWidth() / textWidth;
// }
offX = -textWidth/2;
offY = -textHeight/2;
}
if (rotation != 0)
{
int saveOffX = offX;
switch (rotation)
{
case 1:
offX = offY;
offY = saveOffX;
break;
case 2:
offX = -offX;
offY = -offY;
break;
case 3:
offX = offY;
offY = saveOffX;
break;
}
}
int cX = (int)rect.getCenterX() + offX;
int cY = (int)rect.getCenterY() + offY;
return new Point(cX, cY);
}
/**
* Method to convert text to an array of pixels.
* This is used for text rendering, as well as for creating "layout text" which is placed as geometry in the circuit.
* @param msg the string of text to be converted.
* @param font the name of the font to use.
* @param tSize the size of the font to use.
* @param italic true to make the text italic.
* @param bold true to make the text bold.
* @param underline true to underline the text.
* @param boxedWidth the maximum width of the text (it is scaled down to fit).
* @param boxedHeight the maximum height of the text (it is scaled down to fit).
* @return a Raster with the text bits.
*/
public static Raster renderText(String msg, String font, int tSize, boolean italic, boolean bold, boolean underline, int boxedWidth, int boxedHeight)
{
RenderTextInfo renderInfo = new RenderTextInfo();
if (!renderInfo.buildInfo(msg, font, tSize, italic, bold, underline, new Rectangle(boxedWidth, boxedHeight), null, 0))
return null;
return renderText(renderInfo);
}
private static Raster renderText(RenderTextInfo renderInfo) {
Font theFont = renderInfo.font;
if (theFont == null) return null;
int width = (int)renderInfo.rasBounds.getWidth();
int height = (int)renderInfo.rasBounds.getHeight();
GlyphVector gv = renderInfo.gv;
LineMetrics lm = renderInfo.lm;
BufferedImage textImage = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);
// now render it
Graphics2D g2 = (Graphics2D)textImage.getGraphics();
g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g2.setColor(new Color(255,255,255));
g2.drawGlyphVector(gv, (float)-renderInfo.rasBounds.getX(), (float)(lm.getAscent()-lm.getLeading()));
if (renderInfo.underline)
{
g2.drawLine(0, height-1, width, height-1);
}
// return the bits
return textImage.getData();
}
public static Font getFont(String msg, String font, int tSize, boolean italic, boolean bold, boolean underline) {
// get the font
int fontStyle = Font.PLAIN;
if (italic) fontStyle |= Font.ITALIC;
if (bold) fontStyle |= Font.BOLD;
Font theFont = new Font(font, fontStyle, tSize);
if (theFont == null)
{
System.out.println("Could not find font "+font+" to render text: "+msg);
return null;
}
return theFont;
}
// ************************************* CIRCLE DRAWING *************************************
/**
* Method to draw a circle on the off-screen buffer
*/
private void drawCircle(Point center, Point edge, byte [][] layerBitMap, EGraphics desc)
{
// get parameters
int radius = (int)center.distance(edge);
int col = 0;
if (desc != null) col = desc.getColor().getRGB() & 0xFFFFFF;
// set redraw area
int left = center.x - radius;
int right = center.x + radius + 1;
int top = center.y - radius;
int bottom = center.y + radius + 1;
int x = 0; int y = radius;
int d = 3 - 2 * radius;
if (left >= 0 && right < sz.width && top >= 0 && bottom < sz.height)
{
// no clip version is faster
while (x <= y)
{
if (layerBitMap == null)
{
int baseIndex = (center.y + y) * sz.width;
opaqueData[baseIndex + (center.x+x)] = col;
opaqueData[baseIndex + (center.x-x)] = col;
baseIndex = (center.y - y) * sz.width;
opaqueData[baseIndex + (center.x+x)] = col;
opaqueData[baseIndex + (center.x-x)] = col;
baseIndex = (center.y + x) * sz.width;
opaqueData[baseIndex + (center.x+y)] = col;
opaqueData[baseIndex + (center.x-y)] = col;
baseIndex = (center.y - x) * sz.width;
opaqueData[baseIndex + (center.x+y)] = col;
opaqueData[baseIndex + (center.x-y)] = col;
} else
{
byte [] row = layerBitMap[center.y + y];
row[(center.x+x)>>3] |= (1 << ((center.x+x)&7));
row[(center.x-x)>>3] |= (1 << ((center.x-x)&7));
row = layerBitMap[center.y - y];
row[(center.x+x)>>3] |= (1 << ((center.x+x)&7));
row[(center.x-x)>>3] |= (1 << ((center.x-x)&7));
row = layerBitMap[center.y + x];
row[(center.x+y)>>3] |= (1 << ((center.x+y)&7));
row[(center.x-y)>>3] |= (1 << ((center.x-y)&7));
row = layerBitMap[center.y - x];
row[(center.x+y)>>3] |= (1 << ((center.x+y)&7));
row[(center.x-y)>>3] |= (1 << ((center.x-y)&7));
}
if (d < 0) d += 4*x + 6; else
{
d += 4 * (x-y) + 10;
y--;
}
x++;
}
} else
{
// clip version
while (x <= y)
{
int thisy = center.y + y;
if (thisy >= 0 && thisy < sz.height)
{
int thisx = center.x + x;
if (thisx >= 0 && thisx < sz.width)
drawPoint(thisx, thisy, layerBitMap, col);
thisx = center.x - x;
if (thisx >= 0 && thisx < sz.width)
drawPoint(thisx, thisy, layerBitMap, col);
}
thisy = center.y - y;
if (thisy >= 0 && thisy < sz.height)
{
int thisx = center.x + x;
if (thisx >= 0 && thisx < sz.width)
drawPoint(thisx, thisy, layerBitMap, col);
thisx = center.x - x;
if (thisx >= 0 && thisx < sz.width)
drawPoint(thisx, thisy, layerBitMap, col);
}
thisy = center.y + x;
if (thisy >= 0 && thisy < sz.height)
{
int thisx = center.x + y;
if (thisx >= 0 && thisx < sz.width)
drawPoint(thisx, thisy, layerBitMap, col);
thisx = center.x - y;
if (thisx >= 0 && thisx < sz.width)
drawPoint(thisx, thisy, layerBitMap, col);
}
thisy = center.y - x;
if (thisy >= 0 && thisy < sz.height)
{
int thisx = center.x + y;
if (thisx >= 0 && thisx < sz.width)
drawPoint(thisx, thisy, layerBitMap, col);
thisx = center.x - y;
if (thisx >= 0 && thisx < sz.width)
drawPoint(thisx, thisy, layerBitMap, col);
}
if (d < 0) d += 4*x + 6; else
{
d += 4 * (x-y) + 10;
y--;
}
x++;
}
}
}
/**
* Method to draw a thick circle on the off-screen buffer
*/
private void drawThickCircle(Point center, Point edge, byte [][] layerBitMap, EGraphics desc)
{
// get parameters
int radius = (int)center.distance(edge);
int col = 0;
if (desc != null) col = desc.getColor().getRGB() & 0xFFFFFF;
int x = 0; int y = radius;
int d = 3 - 2 * radius;
while (x <= y)
{
int thisy = center.y + y;
if (thisy >= 0 && thisy < sz.height)
{
int thisx = center.x + x;
if (thisx >= 0 && thisx < sz.width)
drawThickPoint(thisx, thisy, layerBitMap, col);
thisx = center.x - x;
if (thisx >= 0 && thisx < sz.width)
drawThickPoint(thisx, thisy, layerBitMap, col);
}
thisy = center.y - y;
if (thisy >= 0 && thisy < sz.height)
{
int thisx = center.x + x;
if (thisx >= 0 && thisx < sz.width)
drawThickPoint(thisx, thisy, layerBitMap, col);
thisx = center.x - x;
if (thisx >= 0 && thisx < sz.width)
drawThickPoint(thisx, thisy, layerBitMap, col);
}
thisy = center.y + x;
if (thisy >= 0 && thisy < sz.height)
{
int thisx = center.x + y;
if (thisx >= 0 && thisx < sz.width)
drawThickPoint(thisx, thisy, layerBitMap, col);
thisx = center.x - y;
if (thisx >= 0 && thisx < sz.width)
drawThickPoint(thisx, thisy, layerBitMap, col);
}
thisy = center.y - x;
if (thisy >= 0 && thisy < sz.height)
{
int thisx = center.x + y;
if (thisx >= 0 && thisx < sz.width)
drawThickPoint(thisx, thisy, layerBitMap, col);
thisx = center.x - y;
if (thisx >= 0 && thisx < sz.width)
drawThickPoint(thisx, thisy, layerBitMap, col);
}
if (d < 0) d += 4*x + 6; else
{
d += 4 * (x-y) + 10;
y--;
}
x++;
}
}
// ************************************* DISC DRAWING *************************************
/**
* Method to draw a scan line of the filled-in circle of radius "radius"
*/
private void drawDiscRow(int thisy, int startx, int endx, byte [][] layerBitMap, int col, int [] pattern)
{
if (thisy < 0 || thisy >= sz.height) return;
if (startx < 0) startx = 0;
if (endx >= sz.width) endx = sz.width - 1;
if (pattern != null)
{
int pat = pattern[thisy & 15];
if (pat != 0)
{
if (layerBitMap == null)
{
int baseIndex = thisy * sz.width;
for(int x=startx; x<=endx; x++)
{
if ((pat & (1 << (15-(x&15)))) != 0)
opaqueData[baseIndex + x] = col;
}
} else
{
byte [] row = layerBitMap[thisy];
for(int x=startx; x<=endx; x++)
{
if ((pat & (1 << (15-(x&15)))) != 0)
row[x>>3] |= (1 << (x&7));
}
}
}
} else
{
if (layerBitMap == null)
{
int baseIndex = thisy * sz.width;
for(int x=startx; x<=endx; x++)
{
opaqueData[baseIndex + x] = col;
}
} else
{
byte [] row = layerBitMap[thisy];
for(int x=startx; x<=endx; x++)
{
row[x>>3] |= (1 << (x&7));
}
}
}
}
/**
* Method to draw a filled-in circle of radius "radius" on the off-screen buffer
*/
private void drawDisc(Point center, Point edge, byte [][] layerBitMap, EGraphics desc)
{
// get parameters
int radius = (int)center.distance(edge);
int col = 0;
int [] pattern = null;
if (desc != null)
{
col = desc.getColor().getRGB() & 0xFFFFFF;
if (desc.isPatternedOnDisplay())
{
pattern = desc.getPattern();
if (desc.isOutlinedOnDisplay())
{
drawCircle(center, edge, layerBitMap, desc);
}
}
}
// set redraw area
int left = center.x - radius;
int right = center.x + radius + 1;
int top = center.y - radius;
int bottom = center.y + radius + 1;
if (radius == 1)
{
// just fill the area for discs this small
if (left < 0) left = 0;
if (right >= sz.width) right = sz.width - 1;
for(int y=top; y<bottom; y++)
{
if (y < 0 || y >= sz.height) continue;
for(int x=left; x<right; x++)
drawPoint(x, y, layerBitMap, col);
}
return;
}
int x = 0; int y = radius;
int d = 3 - 2 * radius;
while (x <= y)
{
drawDiscRow(center.y+y, center.x-x, center.x+x, layerBitMap, col, pattern);
drawDiscRow(center.y-y, center.x-x, center.x+x, layerBitMap, col, pattern);
drawDiscRow(center.y+x, center.x-y, center.x+y, layerBitMap, col, pattern);
drawDiscRow(center.y-x, center.x-y, center.x+y, layerBitMap, col, pattern);
if (d < 0) d += 4*x + 6; else
{
d += 4 * (x-y) + 10;
y--;
}
x++;
}
}
// ************************************* ARC DRAWING *************************************
private boolean [] arcOctTable = new boolean[9];
private Point arcCenter;
private int arcRadius;
private int arcCol;
private byte [][] arcLayerBitMap;
private boolean arcThick;
private int arcFindOctant(int x, int y)
{
if (x > 0)
{
if (y >= 0)
{
if (y >= x) return 7;
return 8;
}
if (x >= -y) return 1;
return 2;
}
if (y > 0)
{
if (y > -x) return 6;
return 5;
}
if (y > x) return 4;
return 3;
}
private Point arcXformOctant(int x, int y, int oct)
{
switch (oct)
{
case 1 : return new Point(-y, x);
case 2 : return new Point( x, -y);
case 3 : return new Point(-x, -y);
case 4 : return new Point(-y, -x);
case 5 : return new Point( y, -x);
case 6 : return new Point(-x, y);
case 7 : return new Point( x, y);
case 8 : return new Point( y, x);
}
return null;
}
private void arcDoPixel(int x, int y)
{
if (x < 0 || x >= sz.width || y < 0 || y >= sz.height) return;
if (arcThick)
{
drawThickPoint(x, y, arcLayerBitMap, arcCol);
} else
{
drawPoint(x, y, arcLayerBitMap, arcCol);
}
}
private void arcOutXform(int x, int y)
{
if (arcOctTable[1]) arcDoPixel( y + arcCenter.x, -x + arcCenter.y);
if (arcOctTable[2]) arcDoPixel( x + arcCenter.x, -y + arcCenter.y);
if (arcOctTable[3]) arcDoPixel(-x + arcCenter.x, -y + arcCenter.y);
if (arcOctTable[4]) arcDoPixel(-y + arcCenter.x, -x + arcCenter.y);
if (arcOctTable[5]) arcDoPixel(-y + arcCenter.x, x + arcCenter.y);
if (arcOctTable[6]) arcDoPixel(-x + arcCenter.x, y + arcCenter.y);
if (arcOctTable[7]) arcDoPixel( x + arcCenter.x, y + arcCenter.y);
if (arcOctTable[8]) arcDoPixel( y + arcCenter.x, x + arcCenter.y);
}
private void arcBresCW(Point pt, Point pt1)
{
int d = 3 - 2 * pt.y + 4 * pt.x;
while (pt.x < pt1.x && pt.y > pt1.y)
{
arcOutXform(pt.x, pt.y);
if (d < 0) d += 4 * pt.x + 6; else
{
d += 4 * (pt.x-pt.y) + 10;
pt.y--;
}
pt.x++;
}
// get to the end
for ( ; pt.x < pt1.x; pt.x++) arcOutXform(pt.x, pt.y);
for ( ; pt.y > pt1.y; pt.y--) arcOutXform(pt.x, pt.y);
arcOutXform(pt1.x, pt1.y);
}
private void arcBresMidCW(Point pt)
{
int d = 3 - 2 * pt.y + 4 * pt.x;
while (pt.x < pt.y)
{
arcOutXform(pt.x, pt.y);
if (d < 0) d += 4 * pt.x + 6; else
{
d += 4 * (pt.x-pt.y) + 10;
pt.y--;
}
pt.x++;
}
if (pt.x == pt.y) arcOutXform(pt.x, pt.y);
}
private void arcBresMidCCW(Point pt)
{
int d = 3 + 2 * pt.y - 4 * pt.x;
while (pt.x > 0)
{
arcOutXform(pt.x, pt.y);
if (d > 0) d += 6-4 * pt.x; else
{
d += 4 * (pt.y-pt.x) + 10;
pt.y++;
}
pt.x--;
}
arcOutXform(0, arcRadius);
}
private void arcBresCCW(Point pt, Point pt1)
{
int d = 3 + 2 * pt.y + 4 * pt.x;
while(pt.x > pt1.x && pt.y < pt1.y)
{
// not always correct
arcOutXform(pt.x, pt.y);
if (d > 0) d += 6 - 4 * pt.x; else
{
d += 4 * (pt.y-pt.x) + 10;
pt.y++;
}
pt.x--;
}
// get to the end
for ( ; pt.x > pt1.x; pt.x--) arcOutXform(pt.x, pt.y);
for ( ; pt.y < pt1.y; pt.y++) arcOutXform(pt.x, pt.y);
arcOutXform(pt1.x, pt1.y);
}
/**
* draws an arc centered at (centerx, centery), clockwise,
* passing by (x1,y1) and (x2,y2)
*/
private void drawCircleArc(Point center, Point p1, Point p2, boolean thick, byte [][] layerBitMap, EGraphics desc)
{
// ignore tiny arcs
if (p1.x == p2.x && p1.y == p2.y) return;
// get parameters
arcLayerBitMap = layerBitMap;
arcCol = 0;
if (desc != null) arcCol = desc.getColor().getRGB() & 0xFFFFFF;
arcCenter = center;
int pa_x = p2.x - arcCenter.x;
int pa_y = p2.y - arcCenter.y;
int pb_x = p1.x - arcCenter.x;
int pb_y = p1.y - arcCenter.y;
arcRadius = (int)arcCenter.distance(p2);
int alternate = (int)arcCenter.distance(p1);
int start_oct = arcFindOctant(pa_x, pa_y);
int end_oct = arcFindOctant(pb_x, pb_y);
arcThick = thick;
// move the point
if (arcRadius != alternate)
{
int diff = arcRadius-alternate;
switch (end_oct)
{
case 6:
case 7: /* y > x */ pb_y += diff; break;
case 8: /* x > y */
case 1: /* x > -y */ pb_x += diff; break;
case 2: /* -y > x */
case 3: /* -y > -x */ pb_y -= diff; break;
case 4: /* -y < -x */
case 5: /* y < -x */ pb_x -= diff; break;
}
}
for(int i=1; i<9; i++) arcOctTable[i] = false;
if (start_oct == end_oct)
{
arcOctTable[start_oct] = true;
Point pa = arcXformOctant(pa_x, pa_y, start_oct);
Point pb = arcXformOctant(pb_x, pb_y, start_oct);
if ((start_oct&1) != 0) arcBresCW(pa, pb);
else arcBresCCW(pa, pb);
arcOctTable[start_oct] = false;
} else
{
arcOctTable[start_oct] = true;
Point pt = arcXformOctant(pa_x, pa_y, start_oct);
if ((start_oct&1) != 0) arcBresMidCW(pt);
else arcBresMidCCW(pt);
arcOctTable[start_oct] = false;
arcOctTable[end_oct] = true;
pt = arcXformOctant(pb_x, pb_y, end_oct);
if ((end_oct&1) != 0) arcBresMidCCW(pt);
else arcBresMidCW(pt);
arcOctTable[end_oct] = false;
if (MODP(start_oct+1) != end_oct)
{
if (MODP(start_oct+1) == MODM(end_oct-1))
{
arcOctTable[MODP(start_oct+1)] = true;
} else
{
for(int i = MODP(start_oct+1); i != end_oct; i = MODP(i+1))
arcOctTable[i] = true;
}
arcBresMidCW(new Point(0, arcRadius));
}
}
}
private int MODM(int x) { return (x<1) ? x+8 : x; }
private int MODP(int x) { return (x>8) ? x-8 : x; }
// ************************************* RENDERING SUPPORT *************************************
private void drawPoint(int x, int y, byte [][] layerBitMap, int col)
{
if (layerBitMap == null)
{
opaqueData[y * sz.width + x] = col;
} else
{
layerBitMap[y][x>>3] |= (1 << (x&7));
}
}
private void drawThickPoint(int x, int y, byte [][] layerBitMap, int col)
{
if (layerBitMap == null)
{
opaqueData[y * sz.width + x] = col;
if (x > 0)
opaqueData[y * sz.width + (x-1)] = col;
if (x < sz.width-1)
opaqueData[y * sz.width + (x+1)] = col;
if (y > 0)
opaqueData[(y-1) * sz.width + (x+1)] = col;
if (y < sz.height-1)
opaqueData[(y+1) * sz.width + (x+1)] = col;
} else
{
layerBitMap[y][x>>3] |= (1 << (x&7));
if (x > 0)
layerBitMap[y][(x-1)>>3] |= (1 << (x&7));
if (x < sz.width-1)
layerBitMap[y][(x+1)>>3] |= (1 << (x&7));
if (y > 0)
layerBitMap[y-1][x>>3] |= (1 << (x&7));
if (y < sz.height-1)
layerBitMap[y+1][x>>3] |= (1 << (x&7));
}
}
// ************************************* CLIPPING *************************************
// clipping directions
private static final int LEFT = 1;
private static final int RIGHT = 2;
private static final int BOTTOM = 4;
private static final int TOP = 8;
/**
* Method to clip a line from (fx,fy) to (tx,ty) in the rectangle lx <= X <= hx and ly <= Y <= hy.
* Returns true if the line is not visible.
*/
private boolean clipLine(Point from, Point to, int lx, int hx, int ly, int hy)
{
for(;;)
{
// compute code bits for "from" point
int fc = 0;
if (from.x < lx) fc |= LEFT; else
if (from.x > hx) fc |= RIGHT;
if (from.y < ly) fc |= BOTTOM; else
if (from.y > hy) fc |= TOP;
// compute code bits for "to" point
int tc = 0;
if (to.x < lx) tc |= LEFT; else
if (to.x > hx) tc |= RIGHT;
if (to.y < ly) tc |= BOTTOM; else
if (to.y > hy) tc |= TOP;
// look for trivial acceptance or rejection
if (fc == 0 && tc == 0) return false;
if (fc == tc || (fc & tc) != 0) return true;
// make sure the "from" side needs clipping
if (fc == 0)
{
int t = from.x; from.x = to.x; to.x = t;
t = from.y; from.y = to.y; to.y = t;
t = fc; fc = tc; tc = t;
}
if ((fc&LEFT) != 0)
{
if (to.x == from.x) return true;
int t = (to.y - from.y) * (lx - from.x) / (to.x - from.x);
from.y += t;
from.x = lx;
}
if ((fc&RIGHT) != 0)
{
if (to.x == from.x) return true;
int t = (to.y - from.y) * (hx - from.x) / (to.x - from.x);
from.y += t;
from.x = hx;
}
if ((fc&BOTTOM) != 0)
{
if (to.y == from.y) return true;
int t = (to.x - from.x) * (ly - from.y) / (to.y - from.y);
from.x += t;
from.y = ly;
}
if ((fc&TOP) != 0)
{
if (to.y == from.y) return true;
int t = (to.x - from.x) * (hy - from.y) / (to.y - from.y);
from.x += t;
from.y = hy;
}
}
}
private Point [] clipPoly(Point [] points, int lx, int hx, int ly, int hy)
{
// see if any points are outside
int count = points.length;
int pre = 0;
for(int i=0; i<count; i++)
{
if (points[i].x < lx) pre |= LEFT; else
if (points[i].x > hx) pre |= RIGHT;
if (points[i].y < ly) pre |= BOTTOM; else
if (points[i].y > hy) pre |= TOP;
}
if (pre == 0) return points;
// get polygon
Point [] in = new Point[count*2];
for(int i=0; i<count*2; i++)
{
in[i] = new Point();
if (i < count) in[i].setLocation(points[i]);
}
Point [] out = new Point[count*2];
for(int i=0; i<count*2; i++)
out[i] = new Point();
// clip on all four sides
Point [] a = in;
Point [] b = out;
if ((pre & LEFT) != 0)
{
count = clipEdge(a, count, b, LEFT, lx);
Point [] swap = a; a = b; b = swap;
}
if ((pre & RIGHT) != 0)
{
count = clipEdge(a, count, b, RIGHT, hx);
Point [] swap = a; a = b; b = swap;
}
if ((pre & TOP) != 0)
{
count = clipEdge(a, count, b, TOP, hy);
Point [] swap = a; a = b; b = swap;
}
if ((pre & BOTTOM) != 0)
{
count = clipEdge(a, count, b, BOTTOM, ly);
Point [] swap = a; a = b; b = swap;
}
// remove redundant points from polygon
pre = 0;
for(int i=0; i<count; i++)
{
if (i > 0 && a[i-1].x == a[i].x && a[i-1].y == a[i].y) continue;
b[pre].x = a[i].x; b[pre].y = a[i].y;
pre++;
}
// closed polygon: remove redundancy on wrap-around
while (pre != 0 && b[0].x == b[pre-1].x && b[0].y == b[pre-1].y) pre--;
count = pre;
// copy the polygon back if it in the wrong place
Point [] retArr = new Point[count];
for(int i=0; i<count; i++)
retArr[i] = b[i];
return retArr;
}
/**
* Method to clip polygon "in" against line "edge" (1:left, 2:right,
* 4:bottom, 8:top) and place clipped result in "out".
*/
private int clipEdge(Point [] in, int inCount, Point [] out, int edge, int value)
{
// look at all the lines
Point first = new Point();
Point second = new Point();
int firstx = 0, firsty = 0;
int outcount = 0;
for(int i=0; i<inCount; i++)
{
int pre = i - 1;
if (i == 0) pre = inCount-1;
first.setLocation(in[pre]);
second.setLocation(in[i]);
if (clipSegment(first, second, edge, value)) continue;
int x1 = first.x; int y1 = first.y;
int x2 = second.x; int y2 = second.y;
if (outcount != 0)
{
if (x1 != out[outcount-1].x || y1 != out[outcount-1].y)
{
out[outcount].x = x1; out[outcount++].y = y1;
}
} else { firstx = x1; firsty = y1; }
out[outcount].x = x2; out[outcount++].y = y2;
}
if (outcount != 0 && (out[outcount-1].x != firstx || out[outcount-1].y != firsty))
{
out[outcount].x = firstx; out[outcount++].y = firsty;
}
return outcount;
}
/**
* Method to do clipping on the vector from (x1,y1) to (x2,y2).
* If the vector is completely invisible, true is returned.
*/
private boolean clipSegment(Point p1, Point p2, int codebit, int value)
{
int x1 = p1.x; int y1 = p1.y;
int x2 = p2.x; int y2 = p2.y;
int c1 = 0, c2 = 0;
if (codebit == LEFT)
{
if (x1 < value) c1 = codebit;
if (x2 < value) c2 = codebit;
} else if (codebit == BOTTOM)
{
if (y1 < value) c1 = codebit;
if (y2 < value) c2 = codebit;
} else if (codebit == RIGHT)
{
if (x1 > value) c1 = codebit;
if (x2 > value) c2 = codebit;
} else if (codebit == TOP)
{
if (y1 > value) c1 = codebit;
if (y2 > value) c2 = codebit;
}
if (c1 == c2) return c1 != 0;
boolean flip = false;
if (c1 == 0)
{
int t = x1; x1 = x2; x2 = t;
t = y1; y1 = y2; y2 = t;
flip = true;
}
if (codebit == LEFT || codebit == RIGHT)
{
int t = (y2-y1) * (value-x1) / (x2-x1);
y1 += t;
x1 = value;
} else if (codebit == BOTTOM || codebit == TOP)
{
int t = (x2-x1) * (value-y1) / (y2-y1);
x1 += t;
y1 = value;
}
if (flip)
{
p1.x = x2; p1.y = y2;
p2.x = x1; p2.y = y1;
} else
{
p1.x = x1; p1.y = y1;
p2.x = x2; p2.y = y2;
}
return false;
}
}
| true | true | private void drawText(Rectangle rect, Poly.Type style, TextDescriptor descript, String s, byte [][] layerBitMap, EGraphics desc)
{
// quit if string is null
int len = s.length();
if (len == 0) return;
// get parameters
int col = 0;
if (desc != null) col = desc.getColor().getRGB() & 0xFFFFFF;
// get text description
int size = EditWindow.getDefaultFontSize();
int fontStyle = Font.PLAIN;
String fontName = User.getDefaultFont();
boolean italic = false;
boolean bold = false;
boolean underline = false;
int rotation = 0;
if (descript != null)
{
size = descript.getTrueSize(wnd);
if (size < MINIMUMTEXTSIZE) return;
italic = descript.isItalic();
bold = descript.isBold();
underline = descript.isUnderline();
int fontIndex = descript.getFace();
if (fontIndex != 0)
{
TextDescriptor.ActiveFont af = TextDescriptor.ActiveFont.findActiveFont(fontIndex);
if (af != null) fontName = af.getName();
}
rotation = descript.getRotation().getIndex();
}
// get box information for limiting text size
int boxedWidth = -1, boxedHeight = -1;
if (style == Poly.Type.TEXTBOX)
{
boxedWidth = (int)rect.getWidth();
boxedHeight = (int)rect.getHeight();
// clip if not within bounds
if (drawBounds != null && !drawBounds.intersects(rect)) return;
}
// create RenderInfo
long startTime = System.currentTimeMillis();
RenderTextInfo renderInfo = new RenderTextInfo();
if (!renderInfo.buildInfo(s, fontName, size, italic, bold, underline, rect, style, rotation))
return;
// check if text is on-screen
Rectangle2D dbBounds = wnd.screenToDatabase(renderInfo.bounds);
if (drawBounds != null && !drawBounds.intersects(dbBounds))
return;
// render the text
Raster ras = renderText(renderInfo);
renderTextTime += (System.currentTimeMillis() - startTime);
//System.out.println("Rendered text: "+s);
if (ras == null) return;
Point pt = getTextCorner(ras.getWidth(), ras.getHeight(), style, rect, rotation);
int atX = pt.x;
int atY = pt.y;
DataBufferByte dbb = (DataBufferByte)ras.getDataBuffer();
byte [] samples = dbb.getData();
int sx, ex;
int rasWidth = ras.getWidth();
int rasHeight = ras.getHeight();
switch (rotation)
{
case 0: // no rotation
if (atX < 0) sx = -atX; else sx = 0;
if (atX+rasWidth >= sz.width) ex = sz.width-1 - atX; else
ex = rasWidth;
for(int y=0; y<rasHeight; y++)
{
int trueY = atY + y;
if (trueY < 0 || trueY >= sz.height) continue;
// setup pointers for filling this row
byte [] row = null;
int baseIndex = 0;
if (layerBitMap == null) baseIndex = trueY * sz.width; else
row = layerBitMap[trueY];
int samp = y * rasWidth + sx;
for(int x=sx; x<ex; x++)
{
int trueX = atX + x;
int alpha = samples[samp++] & 0xFF;
if (alpha == 0) continue;
if (layerBitMap == null)
{
// drawing opaque
int fullIndex = baseIndex + trueX;
int pixelValue = opaqueData[fullIndex];
int oldAlpha = (pixelValue >> 24) & 0xFF;
int color = col;
if (oldAlpha == 0)
{
// blend with opaque
if (alpha != 0xFF) color = alphaBlend(color, pixelValue, alpha);
} else if (oldAlpha == 0xFF)
{
// blend with background
if (alpha < 255) color = (color & 0xFFFFFF) | (alpha << 24);
}
opaqueData[fullIndex] = color;
} else
{
// draw in a transparent layer
if (alpha >= 128) row[trueX>>3] |= (1 << (trueX&7));
}
}
}
break;
case 1: // 90 degrees counterclockwise
if (atX-rasHeight < 0) sx = rasHeight-atX; else sx = 0;
if (atX >= sz.height) ex = sz.height - atX; else
ex = rasHeight;
for(int y=0; y<rasWidth; y++)
{
int trueY = atY + y;
if (trueY < 0 || trueY >= sz.height) continue;
// setup pointers for filling this row
byte [] row = null;
int baseIndex = 0;
if (layerBitMap == null) baseIndex = trueY * sz.width; else
row = layerBitMap[trueY];
for(int x=sx; x<ex; x++)
{
int trueX = atX + x;
int alpha = samples[x * rasWidth + (rasWidth-y-1)] & 0xFF;
if (alpha == 0) continue;
if (layerBitMap == null)
{
// drawing opaque
int fullIndex = baseIndex + trueX;
int pixelValue = opaqueData[fullIndex];
int oldAlpha = (pixelValue >> 24) & 0xFF;
int color = col;
if (oldAlpha == 0)
{
// blend with opaque
if (alpha != 0xFF) color = alphaBlend(color, pixelValue, alpha);
} else if (oldAlpha == 0xFF)
{
// blend with background
if (alpha < 255) color = (color & 0xFFFFFF) | (alpha << 24);
}
opaqueData[fullIndex] = color;
} else
{
if (alpha >= 128) row[trueX>>3] |= (1 << (trueX&7));
}
}
}
break;
case 2: // 180 degrees
atX -= rasWidth;
atY -= rasHeight;
if (atX < 0) sx = -atX; else sx = 0;
if (atX+rasWidth >= sz.width) ex = sz.width-1 - atX; else
ex = rasWidth;
for(int y=0; y<rasHeight; y++)
{
int trueY = atY + y;
if (trueY < 0 || trueY >= sz.height) continue;
// setup pointers for filling this row
byte [] row = null;
int baseIndex = 0;
if (layerBitMap == null) baseIndex = trueY * sz.width; else
row = layerBitMap[trueY];
for(int x=sx; x<ex; x++)
{
int trueX = atX + x;
int alpha = samples[(rasHeight-y-1) * rasWidth + (rasWidth-x-1)] & 0xFF;
if (alpha == 0) continue;
if (layerBitMap == null)
{
// drawing opaque
int fullIndex = baseIndex + trueX;
int pixelValue = opaqueData[fullIndex];
int oldAlpha = (pixelValue >> 24) & 0xFF;
int color = col;
if (oldAlpha == 0)
{
// blend with opaque
if (alpha != 0xFF) color = alphaBlend(color, pixelValue, alpha);
} else if (oldAlpha == 0xFF)
{
// blend with background
if (alpha < 255) color = (color & 0xFFFFFF) | (alpha << 24);
}
opaqueData[fullIndex] = color;
} else
{
if (alpha >= 128) row[trueX>>3] |= (1 << (trueX&7));
}
}
}
break;
case 3: // 90 degrees clockwise
if (atX-rasHeight < 0) sx = rasHeight-atX; else sx = 0;
if (atX >= sz.height) ex = sz.height - atX; else
ex = rasHeight;
for(int y=0; y<rasWidth; y++)
{
int trueY = atY + y;
if (trueY < 0 || trueY >= sz.height) continue;
// setup pointers for filling this row
byte [] row = null;
int baseIndex = 0;
if (layerBitMap == null) baseIndex = trueY * sz.width; else
row = layerBitMap[trueY];
for(int x=sx; x<ex; x++)
{
int trueX = atX + x;
int alpha = samples[(rasHeight-x-1) * rasWidth + y] & 0xFF;
if (alpha == 0) continue;
if (layerBitMap == null)
{
// drawing opaque
int fullIndex = baseIndex + trueX;
int pixelValue = opaqueData[fullIndex];
int oldAlpha = (pixelValue >> 24) & 0xFF;
int color = col;
if (oldAlpha == 0)
{
// blend with opaque
if (alpha != 0xFF) color = alphaBlend(color, pixelValue, alpha);
} else if (oldAlpha == 0xFF)
{
// blend with background
if (alpha < 255) color = (color & 0xFFFFFF) | (alpha << 24);
}
opaqueData[fullIndex] = color;
} else
{
if (alpha >= 128) row[trueX>>3] |= (1 << (trueX&7));
}
}
}
break;
}
}
| private void drawText(Rectangle rect, Poly.Type style, TextDescriptor descript, String s, byte [][] layerBitMap, EGraphics desc)
{
// quit if string is null
int len = s.length();
if (len == 0) return;
// get parameters
int col = 0;
if (desc != null) col = desc.getColor().getRGB() & 0xFFFFFF;
// get text description
int size = EditWindow.getDefaultFontSize();
int fontStyle = Font.PLAIN;
String fontName = User.getDefaultFont();
boolean italic = false;
boolean bold = false;
boolean underline = false;
int rotation = 0;
if (descript != null)
{
size = descript.getTrueSize(wnd);
if (size < MINIMUMTEXTSIZE) return;
italic = descript.isItalic();
bold = descript.isBold();
underline = descript.isUnderline();
int fontIndex = descript.getFace();
if (fontIndex != 0)
{
TextDescriptor.ActiveFont af = TextDescriptor.ActiveFont.findActiveFont(fontIndex);
if (af != null) fontName = af.getName();
}
rotation = descript.getRotation().getIndex();
}
// get box information for limiting text size
int boxedWidth = -1, boxedHeight = -1;
if (style == Poly.Type.TEXTBOX)
{
boxedWidth = (int)rect.getWidth();
boxedHeight = (int)rect.getHeight();
// clip if not within bounds
Rectangle2D dbBounds = wnd.screenToDatabase(rect);
if (drawBounds != null && !drawBounds.intersects(dbBounds)) return;
}
// create RenderInfo
long startTime = System.currentTimeMillis();
RenderTextInfo renderInfo = new RenderTextInfo();
if (!renderInfo.buildInfo(s, fontName, size, italic, bold, underline, rect, style, rotation))
return;
// check if text is on-screen
Rectangle2D dbBounds = wnd.screenToDatabase(renderInfo.bounds);
if (drawBounds != null && !drawBounds.intersects(dbBounds))
return;
// render the text
Raster ras = renderText(renderInfo);
renderTextTime += (System.currentTimeMillis() - startTime);
//System.out.println("Rendered text: "+s);
if (ras == null) return;
Point pt = getTextCorner(ras.getWidth(), ras.getHeight(), style, rect, rotation);
int atX = pt.x;
int atY = pt.y;
DataBufferByte dbb = (DataBufferByte)ras.getDataBuffer();
byte [] samples = dbb.getData();
int sx, ex;
int rasWidth = ras.getWidth();
int rasHeight = ras.getHeight();
switch (rotation)
{
case 0: // no rotation
if (atX < 0) sx = -atX; else sx = 0;
if (atX+rasWidth >= sz.width) ex = sz.width-1 - atX; else
ex = rasWidth;
for(int y=0; y<rasHeight; y++)
{
int trueY = atY + y;
if (trueY < 0 || trueY >= sz.height) continue;
// setup pointers for filling this row
byte [] row = null;
int baseIndex = 0;
if (layerBitMap == null) baseIndex = trueY * sz.width; else
row = layerBitMap[trueY];
int samp = y * rasWidth + sx;
for(int x=sx; x<ex; x++)
{
int trueX = atX + x;
int alpha = samples[samp++] & 0xFF;
if (alpha == 0) continue;
if (layerBitMap == null)
{
// drawing opaque
int fullIndex = baseIndex + trueX;
int pixelValue = opaqueData[fullIndex];
int oldAlpha = (pixelValue >> 24) & 0xFF;
int color = col;
if (oldAlpha == 0)
{
// blend with opaque
if (alpha != 0xFF) color = alphaBlend(color, pixelValue, alpha);
} else if (oldAlpha == 0xFF)
{
// blend with background
if (alpha < 255) color = (color & 0xFFFFFF) | (alpha << 24);
}
opaqueData[fullIndex] = color;
} else
{
// draw in a transparent layer
if (alpha >= 128) row[trueX>>3] |= (1 << (trueX&7));
}
}
}
break;
case 1: // 90 degrees counterclockwise
if (atX-rasHeight < 0) sx = rasHeight-atX; else sx = 0;
if (atX >= sz.height) ex = sz.height - atX; else
ex = rasHeight;
for(int y=0; y<rasWidth; y++)
{
int trueY = atY + y;
if (trueY < 0 || trueY >= sz.height) continue;
// setup pointers for filling this row
byte [] row = null;
int baseIndex = 0;
if (layerBitMap == null) baseIndex = trueY * sz.width; else
row = layerBitMap[trueY];
for(int x=sx; x<ex; x++)
{
int trueX = atX + x;
int alpha = samples[x * rasWidth + (rasWidth-y-1)] & 0xFF;
if (alpha == 0) continue;
if (layerBitMap == null)
{
// drawing opaque
int fullIndex = baseIndex + trueX;
int pixelValue = opaqueData[fullIndex];
int oldAlpha = (pixelValue >> 24) & 0xFF;
int color = col;
if (oldAlpha == 0)
{
// blend with opaque
if (alpha != 0xFF) color = alphaBlend(color, pixelValue, alpha);
} else if (oldAlpha == 0xFF)
{
// blend with background
if (alpha < 255) color = (color & 0xFFFFFF) | (alpha << 24);
}
opaqueData[fullIndex] = color;
} else
{
if (alpha >= 128) row[trueX>>3] |= (1 << (trueX&7));
}
}
}
break;
case 2: // 180 degrees
atX -= rasWidth;
atY -= rasHeight;
if (atX < 0) sx = -atX; else sx = 0;
if (atX+rasWidth >= sz.width) ex = sz.width-1 - atX; else
ex = rasWidth;
for(int y=0; y<rasHeight; y++)
{
int trueY = atY + y;
if (trueY < 0 || trueY >= sz.height) continue;
// setup pointers for filling this row
byte [] row = null;
int baseIndex = 0;
if (layerBitMap == null) baseIndex = trueY * sz.width; else
row = layerBitMap[trueY];
for(int x=sx; x<ex; x++)
{
int trueX = atX + x;
int alpha = samples[(rasHeight-y-1) * rasWidth + (rasWidth-x-1)] & 0xFF;
if (alpha == 0) continue;
if (layerBitMap == null)
{
// drawing opaque
int fullIndex = baseIndex + trueX;
int pixelValue = opaqueData[fullIndex];
int oldAlpha = (pixelValue >> 24) & 0xFF;
int color = col;
if (oldAlpha == 0)
{
// blend with opaque
if (alpha != 0xFF) color = alphaBlend(color, pixelValue, alpha);
} else if (oldAlpha == 0xFF)
{
// blend with background
if (alpha < 255) color = (color & 0xFFFFFF) | (alpha << 24);
}
opaqueData[fullIndex] = color;
} else
{
if (alpha >= 128) row[trueX>>3] |= (1 << (trueX&7));
}
}
}
break;
case 3: // 90 degrees clockwise
if (atX-rasHeight < 0) sx = rasHeight-atX; else sx = 0;
if (atX >= sz.height) ex = sz.height - atX; else
ex = rasHeight;
for(int y=0; y<rasWidth; y++)
{
int trueY = atY + y;
if (trueY < 0 || trueY >= sz.height) continue;
// setup pointers for filling this row
byte [] row = null;
int baseIndex = 0;
if (layerBitMap == null) baseIndex = trueY * sz.width; else
row = layerBitMap[trueY];
for(int x=sx; x<ex; x++)
{
int trueX = atX + x;
int alpha = samples[(rasHeight-x-1) * rasWidth + y] & 0xFF;
if (alpha == 0) continue;
if (layerBitMap == null)
{
// drawing opaque
int fullIndex = baseIndex + trueX;
int pixelValue = opaqueData[fullIndex];
int oldAlpha = (pixelValue >> 24) & 0xFF;
int color = col;
if (oldAlpha == 0)
{
// blend with opaque
if (alpha != 0xFF) color = alphaBlend(color, pixelValue, alpha);
} else if (oldAlpha == 0xFF)
{
// blend with background
if (alpha < 255) color = (color & 0xFFFFFF) | (alpha << 24);
}
opaqueData[fullIndex] = color;
} else
{
if (alpha >= 128) row[trueX>>3] |= (1 << (trueX&7));
}
}
}
break;
}
}
|
diff --git a/TraficLight/src/test/java/frans/traficLight/AppTest.java b/TraficLight/src/test/java/frans/traficLight/AppTest.java
index 6bcf5a1..fb5e07e 100644
--- a/TraficLight/src/test/java/frans/traficLight/AppTest.java
+++ b/TraficLight/src/test/java/frans/traficLight/AppTest.java
@@ -1,63 +1,63 @@
package frans.traficLight;
import enviroment.Color;
import enviroment.Crossing;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* Unit test for simple App.
*/
public class AppTest
extends TestCase
{
/**
* Create the test case
*
* @param testName name of the test case
*/
public AppTest( String testName )
{
super( testName );
}
/**
* @return the suite of tests being tested
*/
public static Test suite()
{
return new TestSuite( AppTest.class );
}
/**
* Rigourous Test :-)
*/
public void testApp()
{
Crossing crossing = new Crossing();
TraficLight traficLight = new TraficLight(crossing);
//TODO add test
crossing.getEastSensor().setCarDetected(false);
crossing.getWestSensor().setCarDetected(false);
crossing.getNorthSensor().setCarDetected(false);
crossing.getSouthSensor().setCarDetected(false);
traficLight.Execute();
assertTrue(crossing.getEastLight().isRed());
assertTrue(crossing.getNorthLight().isRed());
assertTrue(crossing.getSouthLight().isRed());
assertTrue(crossing.getWestLight().isRed());
crossing.getEastSensor().setCarDetected(true);
traficLight.Execute();
assertTrue(crossing.getEastLight().getColor() == Color.GREEN);
assertTrue(crossing.getNorthLight().getColor() == Color.RED);
assertTrue(crossing.getSouthLight().getColor() == Color.RED);
- crossing.getEastSensor().setValidity(false);
+ crossing.getEastSensor().setValid(false);
}
}
| true | true | public void testApp()
{
Crossing crossing = new Crossing();
TraficLight traficLight = new TraficLight(crossing);
//TODO add test
crossing.getEastSensor().setCarDetected(false);
crossing.getWestSensor().setCarDetected(false);
crossing.getNorthSensor().setCarDetected(false);
crossing.getSouthSensor().setCarDetected(false);
traficLight.Execute();
assertTrue(crossing.getEastLight().isRed());
assertTrue(crossing.getNorthLight().isRed());
assertTrue(crossing.getSouthLight().isRed());
assertTrue(crossing.getWestLight().isRed());
crossing.getEastSensor().setCarDetected(true);
traficLight.Execute();
assertTrue(crossing.getEastLight().getColor() == Color.GREEN);
assertTrue(crossing.getNorthLight().getColor() == Color.RED);
assertTrue(crossing.getSouthLight().getColor() == Color.RED);
crossing.getEastSensor().setValidity(false);
}
| public void testApp()
{
Crossing crossing = new Crossing();
TraficLight traficLight = new TraficLight(crossing);
//TODO add test
crossing.getEastSensor().setCarDetected(false);
crossing.getWestSensor().setCarDetected(false);
crossing.getNorthSensor().setCarDetected(false);
crossing.getSouthSensor().setCarDetected(false);
traficLight.Execute();
assertTrue(crossing.getEastLight().isRed());
assertTrue(crossing.getNorthLight().isRed());
assertTrue(crossing.getSouthLight().isRed());
assertTrue(crossing.getWestLight().isRed());
crossing.getEastSensor().setCarDetected(true);
traficLight.Execute();
assertTrue(crossing.getEastLight().getColor() == Color.GREEN);
assertTrue(crossing.getNorthLight().getColor() == Color.RED);
assertTrue(crossing.getSouthLight().getColor() == Color.RED);
crossing.getEastSensor().setValid(false);
}
|
diff --git a/jniast/src/main/uk/ac/starlink/ast/xml/XAstReader.java b/jniast/src/main/uk/ac/starlink/ast/xml/XAstReader.java
index aefa5516c..51574e80e 100644
--- a/jniast/src/main/uk/ac/starlink/ast/xml/XAstReader.java
+++ b/jniast/src/main/uk/ac/starlink/ast/xml/XAstReader.java
@@ -1,165 +1,165 @@
package uk.ac.starlink.ast.xml;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.xml.transform.Source;
import javax.xml.transform.TransformerException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import uk.ac.starlink.ast.AstException;
import uk.ac.starlink.ast.AstObject;
import uk.ac.starlink.ast.Channel;
import uk.ac.starlink.util.SourceReader;
/**
* Provides a method of getting an AstObject from its XML representation.
*
* @author Mark Taylor
* @author Peter W. Draper
*/
public class XAstReader {
/**
* Constructs an AstObject from an Element.
*
* @param el the Element to transform
* @param prefix the namespace prefix for elements and
* attributes, null for none (include :)
* @return the AstObject constructed from <tt>el</tt>
* @throws IOException if <tt>el</tt> does not have the correct
* structure to be an <tt>AstObject</tt>
*/
public AstObject makeAst( Element el, String prefix ) throws IOException {
ChannelWriter chan = new ChannelWriter( prefix );
chan.writeElement( el );
try {
return chan.read();
}
catch ( AstException e ) {
throw (IOException) new IOException( e.getMessage() )
.initCause( e );
}
}
/**
* Constructs an AstObject from an XML Source.
*
* @param xsrc the XML Source to transform
* @param prefix the namespace prefix for elements and
* attributes, null for none (include :)
* @return the AstObject constructed from <tt>xsrc</tt>
* @throws IOException if <tt>xsrc</tt> does not have the right
* structure to be an <tt>AstObject</tt>
*/
public AstObject makeAst( Source xsrc, String prefix ) throws IOException {
Node node;
try {
node = new SourceReader().getDOM( xsrc );
}
catch ( TransformerException e ) {
throw (IOException)
new IOException( "Error transforming XML source: "
+ e.getMessage() )
.initCause( e );
}
Element el;
if ( node instanceof Document ) {
el = ((Document) node).getDocumentElement();
}
else if ( node instanceof Element ) {
el = (Element) node;
}
else {
throw new IOException(
"Source does not represent an Element or Document" );
}
return makeAst( el, prefix );
}
/*
* Handles the work of turning an XML Element into an AstObject.
*/
private static class ChannelWriter extends Channel {
private List eLines = new ArrayList();
private String prefix = null;
// Instance versions of fixed names (may need namespace
// qualification).
private String attributeName = XAstNames.ATTRIBUTE;
private String isaName = XAstNames.ISA;
private String labelName = XAstNames.LABEL;
private String nameName = XAstNames.NAME;
private String valueName = XAstNames.VALUE;
private String className = XAstNames.CLASS;
private String quotedName = XAstNames.QUOTED;
ChannelWriter( String prefix ) {
this.prefix = prefix;
if ( prefix != null ) {
attributeName = prefix + attributeName;
isaName = prefix + isaName;
labelName = prefix + labelName;
nameName = prefix + nameName;
valueName = prefix + valueName;
className = prefix + className;
quotedName = prefix + quotedName;
}
}
/*
* Prepares an XML element for writing to an AST Channel.
* It turns it into a List of strings, which subsequent calls
* of the sink method can retrieve. The read method of the
* Channel can only be called after this method has been called.
*/
synchronized void writeElement( Element el ) {
if ( el.hasAttribute( labelName ) ) {
appendLine( el.getAttribute( labelName ) + " =" );
}
String elName = el.getNodeName();
if ( prefix != null ) {
elName = elName.substring( prefix.length() );
}
appendLine( "Begin " + elName );
for ( Node child = el.getFirstChild(); child != null;
child = child.getNextSibling() ) {
if ( child.getNodeType() == Node.ELEMENT_NODE ) {
Element subel = (Element) child;
String name = subel.getTagName();
if ( name.equals( attributeName ) ) {
String attName = subel.getAttribute( nameName );
String attVal = subel.getAttribute( valueName );
- if ( Boolean
- .getBoolean( subel.getAttribute( quotedName ) ) ) {
+ String quoteVal = subel.getAttribute( quotedName );
+ if ( Boolean.valueOf( quoteVal ).booleanValue() ) {
attVal = '"' + attVal + '"';
}
appendLine( attName + " = " + attVal );
}
else if ( name.equals( isaName ) ) {
appendLine( "IsA " + subel.getAttribute( className ) );
}
else {
writeElement( subel );
}
}
}
appendLine( "End " + elName );
}
/*
* Appends a line to the internal buffer used for storing lines
* of AST-ready text.
*/
private void appendLine( String s ) {
eLines.add( s );
}
protected synchronized String source() throws IOException {
return (String) ( eLines.size() > 0 ? eLines.remove( 0 ) : null );
}
}
}
| true | true | synchronized void writeElement( Element el ) {
if ( el.hasAttribute( labelName ) ) {
appendLine( el.getAttribute( labelName ) + " =" );
}
String elName = el.getNodeName();
if ( prefix != null ) {
elName = elName.substring( prefix.length() );
}
appendLine( "Begin " + elName );
for ( Node child = el.getFirstChild(); child != null;
child = child.getNextSibling() ) {
if ( child.getNodeType() == Node.ELEMENT_NODE ) {
Element subel = (Element) child;
String name = subel.getTagName();
if ( name.equals( attributeName ) ) {
String attName = subel.getAttribute( nameName );
String attVal = subel.getAttribute( valueName );
if ( Boolean
.getBoolean( subel.getAttribute( quotedName ) ) ) {
attVal = '"' + attVal + '"';
}
appendLine( attName + " = " + attVal );
}
else if ( name.equals( isaName ) ) {
appendLine( "IsA " + subel.getAttribute( className ) );
}
else {
writeElement( subel );
}
}
}
appendLine( "End " + elName );
}
| synchronized void writeElement( Element el ) {
if ( el.hasAttribute( labelName ) ) {
appendLine( el.getAttribute( labelName ) + " =" );
}
String elName = el.getNodeName();
if ( prefix != null ) {
elName = elName.substring( prefix.length() );
}
appendLine( "Begin " + elName );
for ( Node child = el.getFirstChild(); child != null;
child = child.getNextSibling() ) {
if ( child.getNodeType() == Node.ELEMENT_NODE ) {
Element subel = (Element) child;
String name = subel.getTagName();
if ( name.equals( attributeName ) ) {
String attName = subel.getAttribute( nameName );
String attVal = subel.getAttribute( valueName );
String quoteVal = subel.getAttribute( quotedName );
if ( Boolean.valueOf( quoteVal ).booleanValue() ) {
attVal = '"' + attVal + '"';
}
appendLine( attName + " = " + attVal );
}
else if ( name.equals( isaName ) ) {
appendLine( "IsA " + subel.getAttribute( className ) );
}
else {
writeElement( subel );
}
}
}
appendLine( "End " + elName );
}
|
diff --git a/com/imjake9/simplejail/SimpleJailCommandHandler.java b/com/imjake9/simplejail/SimpleJailCommandHandler.java
index dccaee7..79e23b1 100644
--- a/com/imjake9/simplejail/SimpleJailCommandHandler.java
+++ b/com/imjake9/simplejail/SimpleJailCommandHandler.java
@@ -1,311 +1,312 @@
package com.imjake9.simplejail;
import com.imjake9.simplejail.SimpleJail.JailMessage;
import com.imjake9.simplejail.api.SimpleJailCommandListener;
import com.imjake9.simplejail.api.SimpleJailCommandListener.Priority;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import org.bukkit.Location;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class SimpleJailCommandHandler implements CommandExecutor {
private final SimpleJail plugin;
private Map<Priority, List<SimpleJailCommandListener>> commandListeners = new EnumMap<Priority, List<SimpleJailCommandListener>>(Priority.class);
public SimpleJailCommandHandler(SimpleJail plugin) {
this.plugin = plugin;
this.registerCommands();
}
private void registerCommands() {
plugin.getCommand("jail").setExecutor(this);
plugin.getCommand("unjail").setExecutor(this);
plugin.getCommand("setjail").setExecutor(this);
plugin.getCommand("setunjail").setExecutor(this);
plugin.getCommand("jailtime").setExecutor(this);
}
@Override
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
if(commandLabel.equalsIgnoreCase("jail")) {
if(!hasPermission(sender, "simplejail.jail")) {
JailMessage.LACKS_PERMISSIONS.send(sender, "simplejail.jail");
return true;
}
if (this.dispatchCommandToListeners(sender, commandLabel, args))
return true;
if (args.length != 1 && args.length != 2) return false;
// Catch JailExceptions
+ int time = 0;
try {
// Jail/tempjail player:
if (args.length == 1)
plugin.jailPlayer(args[0], sender.getName());
else {
- int time = plugin.parseTimeString(args[1]);
+ time = plugin.parseTimeString(args[1]);
plugin.jailPlayer(args[0], sender.getName(), time);
}
} catch (JailException ex) {
// Send error message
sender.sendMessage(ex.getFormattedMessage());
return true;
}
// Send success message:
if (args.length == 1)
JailMessage.JAIL.send(sender, args[0]);
else
- JailMessage.TEMPJAIL.send(sender, args[0], args[1]);
+ JailMessage.TEMPJAIL.send(sender, args[0], plugin.prettifyMinutes(time));
return true;
} else if(commandLabel.equalsIgnoreCase("unjail")) {
if(!hasPermission(sender, "simplejail.unjail")) {
JailMessage.LACKS_PERMISSIONS.send(sender, "simplejail.unjail");
return true;
}
if (this.dispatchCommandToListeners(sender, commandLabel, args))
return true;
if (args.length != 1) return false;
// Catch JailExceptions
try {
// Unjail player
plugin.unjailPlayer(args[0]);
} catch (JailException ex) {
// Send error message
sender.sendMessage(ex.getFormattedMessage());
return true;
}
// Send success message
JailMessage.UNJAIL.send(sender, args[0]);
return true;
} else if(commandLabel.equalsIgnoreCase("setjail")) {
if(!hasPermission(sender, "simplejail.setjail")) {
JailMessage.LACKS_PERMISSIONS.send(sender, "simplejail.setjail");
return true;
}
if (args.length != 0 && args.length != 4) return false;
// If not a player, only use explicit notation:
if (!(sender instanceof Player) && args.length != 4) {
JailMessage.ONLY_PLAYERS.send(sender);
return true;
}
Location loc;
// Use explicit vs current location:
if (args.length == 0) {
Player player = (Player)sender;
loc = player.getLocation();
} else {
// Check if passed coordinates are correct:
if (!(new Scanner(args[0]).hasNextInt()) || !(new Scanner(args[1]).hasNextInt()) || !(new Scanner(args[2]).hasNextInt())) {
JailMessage.INVALID_COORDINATE.send(sender);
return true;
}
// Set up Location value
loc = new Location(
plugin.getServer().getWorld(args[3]),
Integer.parseInt(args[0]),
Integer.parseInt(args[1]),
Integer.parseInt(args[2]));
}
// Set the jail point
plugin.setJail(loc);
// Send success message
JailMessage.JAIL_POINT_SET.send(sender);
return true;
} else if(commandLabel.equalsIgnoreCase("setunjail")) {
if(!hasPermission(sender, "simplejail.setjail")) {
JailMessage.LACKS_PERMISSIONS.send(sender, "simplejail.setjail");
return true;
}
if (args.length != 0 && args.length != 4) return false;
// If not a player, only use explicit notation:
if (!(sender instanceof Player) && args.length != 4) {
JailMessage.ONLY_PLAYERS.send(sender);
return true;
}
Location loc;
// Use explicit vs current location:
if (args.length == 0) {
Player player = (Player)sender;
loc = player.getLocation();
} else {
// Check if passed coordinates are correct:
if (!(new Scanner(args[0]).hasNextInt()) || !(new Scanner(args[1]).hasNextInt()) || !(new Scanner(args[2]).hasNextInt())) {
JailMessage.INVALID_COORDINATE.send(sender);
return true;
}
// Set up Location value
loc = new Location(
plugin.getServer().getWorld(args[3]),
Integer.parseInt(args[0]),
Integer.parseInt(args[1]),
Integer.parseInt(args[2]));
}
// Set the jail point
plugin.setUnjail(loc);
// Send success message
JailMessage.UNJAIL_POINT_SET.send(sender);
return true;
} else if(commandLabel.equalsIgnoreCase("jailtime")) {
if(!hasPermission(sender, "simplejail.jailtime")) {
JailMessage.LACKS_PERMISSIONS.send(sender, "simplejail.jailtime");
return true;
}
if (args.length > 1) return false;
// If not a player, a target must be explicit:
if (!(sender instanceof Player) && args.length == 0) {
JailMessage.MUST_SPECIFY_TARGET.send(sender);
return true;
}
// Get the target
Player player = (args.length == 0) ? (Player) sender : plugin.getServer().getPlayer(args[0]);
// Validate target:
if (player == null || !player.isOnline()) {
JailMessage.PLAYER_NOT_FOUND.send(sender, args[0]);
return true;
}
if (!plugin.playerIsTempJailed(player)) {
JailMessage.NOT_TEMPJAILED.send(sender, (args.length == 0) ? sender.getName() : args[0]);
return true;
}
// Send success message:
int minutes = (int) ((plugin.getTempJailTime(player) - System.currentTimeMillis()) / 60000);
JailMessage.JAIL_TIME.send(sender, plugin.prettifyMinutes(minutes));
return true;
} else {
return false;
}
}
/**
* Checks any CommandSender for a permission node.
*
* @param sender
* @param permission
* @return
*/
private boolean hasPermission(CommandSender sender, String permission) {
if (sender instanceof Player)
return sender.hasPermission(permission);
else return true;
}
/**
* Dispatches a particular command to all listeners, ordered by priority.
*
* @param sender
* @param command
* @param args
* @return
*/
private boolean dispatchCommandToListeners(CommandSender sender, String command, String args[]) {
boolean handled = false;
execute:
for (Priority priority : commandListeners.keySet()) {
if (priority.equals(Priority.MONITOR)) break;
for (SimpleJailCommandListener listener : commandListeners.get(priority)) {
if (listener.handleJailCommand(sender, command, args)) {
handled = true;
break execute;
}
}
}
if (commandListeners.containsKey(Priority.MONITOR))
for (SimpleJailCommandListener listener : commandListeners.get(Priority.MONITOR)) {
listener.handleJailCommand(sender, command, args);
}
return handled;
}
/**
* Registers a command listener.
*
* @param listener
* @param priority
*/
public void addListener(SimpleJailCommandListener listener, Priority priority) {
if (!commandListeners.containsKey(priority))
commandListeners.put(priority, new ArrayList<SimpleJailCommandListener>());
commandListeners.get(priority).add(listener);
}
/**
* Unregisters a command listener.
*
* @param listener
* @param priority
*/
public void removeListener(SimpleJailCommandListener listener, Priority priority) {
if (!commandListeners.containsKey(priority)) return;
if (!commandListeners.get(priority).contains(listener)) return;
commandListeners.get(priority).remove(listener);
}
}
| false | true | public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
if(commandLabel.equalsIgnoreCase("jail")) {
if(!hasPermission(sender, "simplejail.jail")) {
JailMessage.LACKS_PERMISSIONS.send(sender, "simplejail.jail");
return true;
}
if (this.dispatchCommandToListeners(sender, commandLabel, args))
return true;
if (args.length != 1 && args.length != 2) return false;
// Catch JailExceptions
try {
// Jail/tempjail player:
if (args.length == 1)
plugin.jailPlayer(args[0], sender.getName());
else {
int time = plugin.parseTimeString(args[1]);
plugin.jailPlayer(args[0], sender.getName(), time);
}
} catch (JailException ex) {
// Send error message
sender.sendMessage(ex.getFormattedMessage());
return true;
}
// Send success message:
if (args.length == 1)
JailMessage.JAIL.send(sender, args[0]);
else
JailMessage.TEMPJAIL.send(sender, args[0], args[1]);
return true;
} else if(commandLabel.equalsIgnoreCase("unjail")) {
if(!hasPermission(sender, "simplejail.unjail")) {
JailMessage.LACKS_PERMISSIONS.send(sender, "simplejail.unjail");
return true;
}
if (this.dispatchCommandToListeners(sender, commandLabel, args))
return true;
if (args.length != 1) return false;
// Catch JailExceptions
try {
// Unjail player
plugin.unjailPlayer(args[0]);
} catch (JailException ex) {
// Send error message
sender.sendMessage(ex.getFormattedMessage());
return true;
}
// Send success message
JailMessage.UNJAIL.send(sender, args[0]);
return true;
} else if(commandLabel.equalsIgnoreCase("setjail")) {
if(!hasPermission(sender, "simplejail.setjail")) {
JailMessage.LACKS_PERMISSIONS.send(sender, "simplejail.setjail");
return true;
}
if (args.length != 0 && args.length != 4) return false;
// If not a player, only use explicit notation:
if (!(sender instanceof Player) && args.length != 4) {
JailMessage.ONLY_PLAYERS.send(sender);
return true;
}
Location loc;
// Use explicit vs current location:
if (args.length == 0) {
Player player = (Player)sender;
loc = player.getLocation();
} else {
// Check if passed coordinates are correct:
if (!(new Scanner(args[0]).hasNextInt()) || !(new Scanner(args[1]).hasNextInt()) || !(new Scanner(args[2]).hasNextInt())) {
JailMessage.INVALID_COORDINATE.send(sender);
return true;
}
// Set up Location value
loc = new Location(
plugin.getServer().getWorld(args[3]),
Integer.parseInt(args[0]),
Integer.parseInt(args[1]),
Integer.parseInt(args[2]));
}
// Set the jail point
plugin.setJail(loc);
// Send success message
JailMessage.JAIL_POINT_SET.send(sender);
return true;
} else if(commandLabel.equalsIgnoreCase("setunjail")) {
if(!hasPermission(sender, "simplejail.setjail")) {
JailMessage.LACKS_PERMISSIONS.send(sender, "simplejail.setjail");
return true;
}
if (args.length != 0 && args.length != 4) return false;
// If not a player, only use explicit notation:
if (!(sender instanceof Player) && args.length != 4) {
JailMessage.ONLY_PLAYERS.send(sender);
return true;
}
Location loc;
// Use explicit vs current location:
if (args.length == 0) {
Player player = (Player)sender;
loc = player.getLocation();
} else {
// Check if passed coordinates are correct:
if (!(new Scanner(args[0]).hasNextInt()) || !(new Scanner(args[1]).hasNextInt()) || !(new Scanner(args[2]).hasNextInt())) {
JailMessage.INVALID_COORDINATE.send(sender);
return true;
}
// Set up Location value
loc = new Location(
plugin.getServer().getWorld(args[3]),
Integer.parseInt(args[0]),
Integer.parseInt(args[1]),
Integer.parseInt(args[2]));
}
// Set the jail point
plugin.setUnjail(loc);
// Send success message
JailMessage.UNJAIL_POINT_SET.send(sender);
return true;
} else if(commandLabel.equalsIgnoreCase("jailtime")) {
if(!hasPermission(sender, "simplejail.jailtime")) {
JailMessage.LACKS_PERMISSIONS.send(sender, "simplejail.jailtime");
return true;
}
if (args.length > 1) return false;
// If not a player, a target must be explicit:
if (!(sender instanceof Player) && args.length == 0) {
JailMessage.MUST_SPECIFY_TARGET.send(sender);
return true;
}
// Get the target
Player player = (args.length == 0) ? (Player) sender : plugin.getServer().getPlayer(args[0]);
// Validate target:
if (player == null || !player.isOnline()) {
JailMessage.PLAYER_NOT_FOUND.send(sender, args[0]);
return true;
}
if (!plugin.playerIsTempJailed(player)) {
JailMessage.NOT_TEMPJAILED.send(sender, (args.length == 0) ? sender.getName() : args[0]);
return true;
}
// Send success message:
int minutes = (int) ((plugin.getTempJailTime(player) - System.currentTimeMillis()) / 60000);
JailMessage.JAIL_TIME.send(sender, plugin.prettifyMinutes(minutes));
return true;
} else {
return false;
}
}
| public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
if(commandLabel.equalsIgnoreCase("jail")) {
if(!hasPermission(sender, "simplejail.jail")) {
JailMessage.LACKS_PERMISSIONS.send(sender, "simplejail.jail");
return true;
}
if (this.dispatchCommandToListeners(sender, commandLabel, args))
return true;
if (args.length != 1 && args.length != 2) return false;
// Catch JailExceptions
int time = 0;
try {
// Jail/tempjail player:
if (args.length == 1)
plugin.jailPlayer(args[0], sender.getName());
else {
time = plugin.parseTimeString(args[1]);
plugin.jailPlayer(args[0], sender.getName(), time);
}
} catch (JailException ex) {
// Send error message
sender.sendMessage(ex.getFormattedMessage());
return true;
}
// Send success message:
if (args.length == 1)
JailMessage.JAIL.send(sender, args[0]);
else
JailMessage.TEMPJAIL.send(sender, args[0], plugin.prettifyMinutes(time));
return true;
} else if(commandLabel.equalsIgnoreCase("unjail")) {
if(!hasPermission(sender, "simplejail.unjail")) {
JailMessage.LACKS_PERMISSIONS.send(sender, "simplejail.unjail");
return true;
}
if (this.dispatchCommandToListeners(sender, commandLabel, args))
return true;
if (args.length != 1) return false;
// Catch JailExceptions
try {
// Unjail player
plugin.unjailPlayer(args[0]);
} catch (JailException ex) {
// Send error message
sender.sendMessage(ex.getFormattedMessage());
return true;
}
// Send success message
JailMessage.UNJAIL.send(sender, args[0]);
return true;
} else if(commandLabel.equalsIgnoreCase("setjail")) {
if(!hasPermission(sender, "simplejail.setjail")) {
JailMessage.LACKS_PERMISSIONS.send(sender, "simplejail.setjail");
return true;
}
if (args.length != 0 && args.length != 4) return false;
// If not a player, only use explicit notation:
if (!(sender instanceof Player) && args.length != 4) {
JailMessage.ONLY_PLAYERS.send(sender);
return true;
}
Location loc;
// Use explicit vs current location:
if (args.length == 0) {
Player player = (Player)sender;
loc = player.getLocation();
} else {
// Check if passed coordinates are correct:
if (!(new Scanner(args[0]).hasNextInt()) || !(new Scanner(args[1]).hasNextInt()) || !(new Scanner(args[2]).hasNextInt())) {
JailMessage.INVALID_COORDINATE.send(sender);
return true;
}
// Set up Location value
loc = new Location(
plugin.getServer().getWorld(args[3]),
Integer.parseInt(args[0]),
Integer.parseInt(args[1]),
Integer.parseInt(args[2]));
}
// Set the jail point
plugin.setJail(loc);
// Send success message
JailMessage.JAIL_POINT_SET.send(sender);
return true;
} else if(commandLabel.equalsIgnoreCase("setunjail")) {
if(!hasPermission(sender, "simplejail.setjail")) {
JailMessage.LACKS_PERMISSIONS.send(sender, "simplejail.setjail");
return true;
}
if (args.length != 0 && args.length != 4) return false;
// If not a player, only use explicit notation:
if (!(sender instanceof Player) && args.length != 4) {
JailMessage.ONLY_PLAYERS.send(sender);
return true;
}
Location loc;
// Use explicit vs current location:
if (args.length == 0) {
Player player = (Player)sender;
loc = player.getLocation();
} else {
// Check if passed coordinates are correct:
if (!(new Scanner(args[0]).hasNextInt()) || !(new Scanner(args[1]).hasNextInt()) || !(new Scanner(args[2]).hasNextInt())) {
JailMessage.INVALID_COORDINATE.send(sender);
return true;
}
// Set up Location value
loc = new Location(
plugin.getServer().getWorld(args[3]),
Integer.parseInt(args[0]),
Integer.parseInt(args[1]),
Integer.parseInt(args[2]));
}
// Set the jail point
plugin.setUnjail(loc);
// Send success message
JailMessage.UNJAIL_POINT_SET.send(sender);
return true;
} else if(commandLabel.equalsIgnoreCase("jailtime")) {
if(!hasPermission(sender, "simplejail.jailtime")) {
JailMessage.LACKS_PERMISSIONS.send(sender, "simplejail.jailtime");
return true;
}
if (args.length > 1) return false;
// If not a player, a target must be explicit:
if (!(sender instanceof Player) && args.length == 0) {
JailMessage.MUST_SPECIFY_TARGET.send(sender);
return true;
}
// Get the target
Player player = (args.length == 0) ? (Player) sender : plugin.getServer().getPlayer(args[0]);
// Validate target:
if (player == null || !player.isOnline()) {
JailMessage.PLAYER_NOT_FOUND.send(sender, args[0]);
return true;
}
if (!plugin.playerIsTempJailed(player)) {
JailMessage.NOT_TEMPJAILED.send(sender, (args.length == 0) ? sender.getName() : args[0]);
return true;
}
// Send success message:
int minutes = (int) ((plugin.getTempJailTime(player) - System.currentTimeMillis()) / 60000);
JailMessage.JAIL_TIME.send(sender, plugin.prettifyMinutes(minutes));
return true;
} else {
return false;
}
}
|
diff --git a/flexodesktop/GUI/flexo/src/main/java/org/openflexo/view/menu/FileMenu.java b/flexodesktop/GUI/flexo/src/main/java/org/openflexo/view/menu/FileMenu.java
index 6d9d8d234..f448cd2df 100644
--- a/flexodesktop/GUI/flexo/src/main/java/org/openflexo/view/menu/FileMenu.java
+++ b/flexodesktop/GUI/flexo/src/main/java/org/openflexo/view/menu/FileMenu.java
@@ -1,650 +1,650 @@
/*
* (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.view.menu;
import java.awt.Cursor;
import java.awt.event.ActionEvent;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.AbstractAction;
import javax.swing.JMenu;
import javax.swing.JOptionPane;
import javax.swing.KeyStroke;
import org.openflexo.FlexoCst;
import org.openflexo.GeneralPreferences;
import org.openflexo.components.AskParametersDialog;
import org.openflexo.components.NewProjectComponent;
import org.openflexo.components.OpenProjectComponent;
import org.openflexo.foundation.FlexoEditor;
import org.openflexo.foundation.action.ImportProject;
import org.openflexo.foundation.action.ValidateProject;
import org.openflexo.foundation.param.CheckboxParameter;
import org.openflexo.foundation.param.ParameterDefinition;
import org.openflexo.foundation.rm.FlexoProject;
import org.openflexo.foundation.rm.SaveResourceExceptionList;
import org.openflexo.foundation.utils.OperationCancelledException;
import org.openflexo.foundation.utils.ProjectInitializerException;
import org.openflexo.foundation.utils.ProjectLoadingCancelledException;
import org.openflexo.icon.IconLibrary;
import org.openflexo.localization.FlexoLocalization;
import org.openflexo.module.ProjectLoader;
import org.openflexo.print.PrintManagingController;
import org.openflexo.rest.action.UploadProjectAction;
import org.openflexo.toolbox.ToolBox;
import org.openflexo.view.controller.FlexoController;
import org.openflexo.view.controller.model.ControllerModel;
/**
* 'File' menu
*
* @author sguerin
*/
public class FileMenu extends FlexoMenu {
static final Logger logger = Logger.getLogger(FileMenu.class.getPackage().getName());
public JMenu recentProjectMenu;
public JMenu exportMenu;
public JMenu importMenu;
protected FlexoController _controller;
protected FileMenu(FlexoController controller) {
this(controller, true);
}
protected FileMenu(FlexoController controller, boolean insertCommonItems) {
super("file", controller);
_controller = controller;
if (insertCommonItems) {
add(new NewProjectItem());
add(new OpenProjectItem());
add(recentProjectMenu = new JMenu());
recentProjectMenu.setText(FlexoLocalization.localizedForKey("recent_projects", recentProjectMenu));
add(new ImportProjectMenuItem());
add(new SaveProjectItem());
add(new SaveAllProjectItem());
add(new SaveAsProjectItem());
add(new SaveProjectForServerItem());
add(new SendProjectToFlexoServerItem());
// TODO: repair reload project. this includes to also support close project.
// add(reloadProjectItem = new ReloadProjectItem());
addSeparator();
if (addImportItems()) {
add(importMenu);
}
if (addExportItems()) {
add(exportMenu);
}
if (importMenu != null || exportMenu != null) {
addSeparator();
}
}
addSpecificItems();
if (insertCommonItems) {
add(new InspectProjectItem());
if (controller instanceof PrintManagingController) {
addSeparator();
addPrintItems();
add(new PageSetUpItem());
}
addSeparator();
}
add(new QuitItem());
updateRecentProjectMenu();
}
public void updateRecentProjectMenu() {
if (recentProjectMenu != null) {
recentProjectMenu.removeAll();
Enumeration<File> en = GeneralPreferences.getLastOpenedProjects().elements();
while (en.hasMoreElements()) {
File f = en.nextElement();
recentProjectMenu.add(new ProjectItem(f));
}
}
}
public void addToExportItems(FlexoMenuItem exportItem) {
if (exportMenu == null) {
exportMenu = new JMenu();
exportMenu.setText(FlexoLocalization.localizedForKey("export", exportMenu));
}
exportMenu.add(exportItem);
}
public void addToImportItems(FlexoMenuItem importItem) {
if (importMenu == null) {
importMenu = new JMenu();
importMenu.setText(FlexoLocalization.localizedForKey("import", importMenu));
}
importMenu.add(importItem);
}
protected boolean addExportItems() {
return false;
}
protected boolean addImportItems() {
return false;
}
public void addSpecificItems() {
// No specific item here, please override this method when required
}
public void addPrintItems() {
// No specific item here, please override this method when required
}
public void quit() {
try {
getModuleLoader().quit(true);
} catch (OperationCancelledException e) {
// User pressed cancel.
if (logger.isLoggable(Level.FINEST)) {
logger.log(Level.FINEST, "Cancelled saving", e);
}
}
}
public class NewProjectItem extends FlexoMenuItem {
public NewProjectItem() {
super(new NewProjectAction(), "new_project", KeyStroke.getKeyStroke(KeyEvent.VK_N, FlexoCst.META_MASK), getController(), true);
setIcon(IconLibrary.NEW_ICON);
}
}
public class NewProjectAction extends AbstractAction {
public NewProjectAction() {
super();
}
@Override
public void actionPerformed(ActionEvent arg0) {
File projectDirectory = NewProjectComponent.getProjectDirectory();
if (projectDirectory != null) {
try {
getController().getProjectLoader().newProject(projectDirectory);
} catch (ProjectInitializerException e) {
e.printStackTrace();
FlexoController.notify(e.getMessage());
}
}
}
}
public class OpenProjectItem extends FlexoMenuItem {
public OpenProjectItem() {
super(new OpenProjectAction(), "open_project", KeyStroke.getKeyStroke(KeyEvent.VK_O, FlexoCst.META_MASK), getController(), true);
setIcon(IconLibrary.OPEN_ICON);
}
}
public class OpenProjectAction extends AbstractAction {
public OpenProjectAction() {
super();
}
@Override
public void actionPerformed(ActionEvent arg0) {
File projectDirectory = OpenProjectComponent.getProjectDirectory();
if (projectDirectory != null) {
try {
getProjectLoader().loadProject(projectDirectory);
} catch (ProjectLoadingCancelledException e) {
} catch (ProjectInitializerException e) {
e.printStackTrace();
FlexoController.notify(FlexoLocalization.localizedForKey("could_not_open_project_located_at")
+ projectDirectory.getAbsolutePath());
}
}
}
}
public class ProjectItem extends FlexoMenuItem {
/**
*
*/
public ProjectItem(File project) {
super(new RecentProjectAction(project), project.getName(), null, getController(), false);
}
}
public class RecentProjectAction extends AbstractAction {
private File projectDirectory;
public RecentProjectAction(File projectDirectory) {
super();
this.projectDirectory = projectDirectory;
}
@Override
public void actionPerformed(ActionEvent arg0) {
try {
getProjectLoader().loadProject(projectDirectory);
} catch (ProjectLoadingCancelledException e) {
} catch (ProjectInitializerException e) {
e.printStackTrace();
FlexoController.notify(FlexoLocalization.localizedForKey("could_not_open_project_located_at")
+ projectDirectory.getAbsolutePath());
}
}
}
public class ImportProjectMenuItem extends FlexoMenuItem {
public ImportProjectMenuItem() {
super(new ImportProjectAction(), "import_project", null, getController(), true);
setIcon(IconLibrary.IMPORT_ICON);
}
}
public class ImportProjectAction extends AbstractAction {
public ImportProjectAction() {
super();
}
@Override
public void actionPerformed(ActionEvent e) {
FlexoEditor editor = getController().getEditor();
if (editor != null) {
editor.performActionType(ImportProject.actionType, editor.getProject(), null, e);
}
}
}
public class SaveProjectItem extends FlexoMenuItem {
public SaveProjectItem() {
super(new SaveProjectAction(), "save_current_project", KeyStroke.getKeyStroke(KeyEvent.VK_S, FlexoCst.META_MASK),
getController(), true);
setIcon(IconLibrary.SAVE_ICON);
}
}
public class SaveProjectAction extends AbstractAction implements PropertyChangeListener {
public SaveProjectAction() {
super();
if (getController() != null) {
manager.addListener(ControllerModel.CURRENT_EDITOR, this, getController().getControllerModel());
}
updateEnability();
}
@Override
public void actionPerformed(ActionEvent arg0) {
if (getController() == null || getController().getProject() == null) {
return;
}
if (getController().getProject().hasUnsaveStorageResources()) {
Cursor c = getController().getFlexoFrame().getCursor();
FileMenu.this._controller.getFlexoFrame().setCursor(Cursor.WAIT_CURSOR);
try {
getProjectLoader().saveProjects(Arrays.asList(getController().getProject()));
} catch (SaveResourceExceptionList e) {
e.printStackTrace();
FlexoController.showError(FlexoLocalization.localizedForKey("errors_during_saving"),
FlexoLocalization.localizedForKey("errors_during_saving"));
} finally {
getController().getFlexoFrame().setCursor(c);
}
}
}
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (getController() != null) {
if (evt.getSource() == getController().getControllerModel()) {
if (ControllerModel.CURRENT_EDITOR.equals(evt.getPropertyName())) {
updateEnability();
}
}
}
}
private void updateEnability() {
setEnabled(getController() != null && getController().getProject() != null);
}
}
public class SaveAsProjectItem extends FlexoMenuItem {
public SaveAsProjectItem() {
super(new SaveAsProjectAction(), "save_current_project_as", null, getController(), true);
setIcon(IconLibrary.SAVE_AS_ICON);
}
}
public class SaveAsProjectAction extends AbstractAction {
public SaveAsProjectAction() {
super();
}
@Override
public void actionPerformed(ActionEvent arg0) {
getProjectLoader().saveAsProject(getController().getProject());
}
}
public class SendProjectToFlexoServerItem extends FlexoMenuItem {
public SendProjectToFlexoServerItem() {
super(new SendProjectToFlexoServerAction(), "send_project_to_flexo_server", null, getController(), true);
setIcon(IconLibrary.NETWORK_ICON);
}
}
public class SendProjectToFlexoServerAction extends AbstractAction {
public SendProjectToFlexoServerAction() {
super();
}
@Override
public void actionPerformed(ActionEvent arg0) {
/*
boolean isOperationConfirmed = saveForServerPreprocessing();
if (!isOperationConfirmed) {
return;
}
*/
UploadProjectAction refresh = UploadProjectAction.actionType.makeNewAction(getController().getProject(), null, getController()
.getEditor());
refresh.doAction();
}
}
// ==========================================================================
// ============================= SaveProjectForServer =============================
// ==========================================================================
public class SaveProjectForServerItem extends FlexoMenuItem {
public SaveProjectForServerItem() {
super(new SaveProjectForServerAction(), "save_project_for_server", null, getController(), true);
setIcon(IconLibrary.SAVE_ICON);
}
}
private boolean saveForServerPreprocessing() {
FlexoProject project = _controller.getProject();
int i = FlexoController.confirmYesNoCancel(FlexoLocalization
.localizedForKey("would_you_like_to_check_your_project_consistency_first") + "?");
switch (i) {
case JOptionPane.YES_OPTION:
ValidateProject validate = ValidateProject.actionType.makeNewAction(project, null, getController().getEditor());
validate.doAction();
if (validate.getErrorsNb() > 0) {
StringBuilder sb = new StringBuilder();
- if (validate.getIeValidationReport().getErrorNb() > 0) {
+ if (validate.getIeValidationReport() != null & validate.getIeValidationReport().getErrorNb() > 0) {
sb.append(FlexoLocalization.localizedForKey("there_are_errors_in_your_components") + "\n");
}
- if (validate.getWkfValidationReport().getErrorNb() > 0) {
+ if (validate.getWkfValidationReport() != null && validate.getWkfValidationReport().getErrorNb() > 0) {
sb.append(FlexoLocalization.localizedForKey("there_are_errors_in_your_processes") + "\n");
}
- if (validate.getDmValidationReport().getErrorNb() > 0) {
+ if (validate.getDmValidationReport() != null && validate.getDmValidationReport().getErrorNb() > 0) {
sb.append(FlexoLocalization.localizedForKey("there_are_errors_in_your_data_model") + "\n");
}
- if (validate.getDkvValidationReport().getErrorNb() > 0) {
+ if (validate.getDkvValidationReport() != null && validate.getDkvValidationReport().getErrorNb() > 0) {
sb.append(FlexoLocalization.localizedForKey("there_are_errors_in_the_dkv") + "\n");
}
sb.append(FlexoLocalization.localizedForKey("would_you_like_to_continue_anyway") + "?");
if (!FlexoController.confirmWithWarning(sb.toString())) {
return false;
}
} else {
if (GeneralPreferences.getNotifyValidProject()) {
ParameterDefinition[] params = new ParameterDefinition[1];
CheckboxParameter dontNotify = new CheckboxParameter("dont_notify", "dont_notify_if_project_is_valid", false);
params[0] = dontNotify;
AskParametersDialog dialog = AskParametersDialog.createAskParametersDialog(project,
FlexoLocalization.localizedForKey("project_is_valid"), FlexoLocalization.localizedForKey("project_is_valid"),
params);
if (dialog.getStatus() == AskParametersDialog.VALIDATE) {
if (dontNotify.getValue()) {
GeneralPreferences.setNotifyValidProject(false);
GeneralPreferences.save();
}
} else {
return false;
}
}
}
break;
case JOptionPane.NO_OPTION:
break;
default:
return false;
}
return true;
}
public class SaveAllProjectItem extends FlexoMenuItem {
public SaveAllProjectItem() {
super(new SaveAllProjectAction(), "save_all_project", KeyStroke.getKeyStroke(KeyEvent.VK_S, FlexoCst.META_MASK
| KeyEvent.SHIFT_MASK), getController(), true);
setIcon(IconLibrary.SAVE_ALL_ICON);
}
}
public class SaveAllProjectAction extends AbstractAction implements PropertyChangeListener {
public SaveAllProjectAction() {
super();
if (getProjectLoader() != null) {
manager.addListener(ProjectLoader.ROOT_PROJECTS, this, getProjectLoader());
}
updateEnability();
}
@Override
public void actionPerformed(ActionEvent arg0) {
if (getProjectLoader().someProjectsAreModified()) {
Cursor c = getController().getFlexoFrame().getCursor();
FileMenu.this._controller.getFlexoFrame().setCursor(Cursor.WAIT_CURSOR);
try {
getProjectLoader().saveAllProjects();
} catch (SaveResourceExceptionList e) {
e.printStackTrace();
FlexoController.showError(FlexoLocalization.localizedForKey("errors_during_saving"),
FlexoLocalization.localizedForKey("errors_during_saving"));
} finally {
getController().getFlexoFrame().setCursor(c);
}
}
}
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (getProjectLoader() != null) {
if (evt.getSource() == getProjectLoader()) {
if (ProjectLoader.ROOT_PROJECTS.equals(evt.getPropertyName())) {
updateEnability();
}
}
}
}
private void updateEnability() {
setEnabled(getProjectLoader().getRootProjects().size() > 0);
}
}
protected ProjectLoader getProjectLoader() {
return getController().getProjectLoader();
}
public class SaveProjectForServerAction extends AbstractAction {
public SaveProjectForServerAction() {
super();
}
@Override
public void actionPerformed(ActionEvent arg0) {
boolean isOperationConfirmed = saveForServerPreprocessing();
if (isOperationConfirmed) {
getProjectLoader().saveProjectForServer(getController().getProject());
}
}
}
// ==========================================================================
// ============================= ReloadProject =============================
// ==========================================================================
public class ReloadProjectItem extends FlexoMenuItem {
public ReloadProjectItem() {
super(new ReloadProjectAction(), "reload_project", null, getController(), true);
}
}
public class ReloadProjectAction extends AbstractAction {
public ReloadProjectAction() {
super();
}
@Override
public void actionPerformed(ActionEvent arg0) {
try {
getProjectLoader().reloadProject(getController().getProject());
} catch (ProjectLoadingCancelledException e) {
} catch (ProjectInitializerException e) {
e.printStackTrace();
FlexoController.notify(FlexoLocalization.localizedForKey("could_not_open_project_located_at")
+ e.getProjectDirectory().getAbsolutePath());
}
}
}
// ==========================================================================
// ============================= InspectProject
// =============================
// ==========================================================================
public class InspectProjectItem extends FlexoMenuItem {
public InspectProjectItem() {
super(new InspectProjectAction(), "inspect_project", null, getController(), true);
setIcon(IconLibrary.INSPECT_ICON);
}
}
public class InspectProjectAction extends AbstractAction {
public InspectProjectAction() {
super();
}
@Override
public void actionPerformed(ActionEvent arg0) {
// FlexoModule.getActiveModule().getFlexoController().showInspector();
// FlexoModule.getActiveModule().getFlexoController().setCurrentInspectedObject(FlexoModule.getActiveModule().getFlexoController().getProject());
FlexoController controller = getController();
controller.getSelectionManager().setSelectedObject(controller.getProject());
controller.showInspector();
/*
* int state = controller.getInspectorWindow().getExtendedState(); state &= ~Frame.ICONIFIED;
* controller.getInspectorWindow().setExtendedState(state);
*/
}
}
// ==========================================================================
// ============================= Quit Flexo
// =================================
// ==========================================================================
public class QuitItem extends FlexoMenuItem {
public QuitItem() {
super(new QuitAction(), "quit", ToolBox.getPLATFORM() == ToolBox.WINDOWS ? KeyStroke.getKeyStroke(KeyEvent.VK_F4,
InputEvent.ALT_MASK) : KeyStroke.getKeyStroke(KeyEvent.VK_Q, FlexoCst.META_MASK), getController(), true);
}
}
public class QuitAction extends AbstractAction {
public QuitAction() {
super();
}
@Override
public void actionPerformed(ActionEvent arg0) {
quit();
}
}
// ==========================================================================
// ============================= PageSetUP ================================
// ==========================================================================
public class PageSetUpItem extends FlexoMenuItem {
public PageSetUpItem() {
super(new PageSetUpAction(), "page_setup", null, getController(), true);
}
}
public class PageSetUpAction extends AbstractAction {
public PageSetUpAction() {
super();
}
@Override
public void actionPerformed(ActionEvent arg0) {
((PrintManagingController) _controller).getPrintManager().pageSetup();
}
}
}
| false | true | private boolean saveForServerPreprocessing() {
FlexoProject project = _controller.getProject();
int i = FlexoController.confirmYesNoCancel(FlexoLocalization
.localizedForKey("would_you_like_to_check_your_project_consistency_first") + "?");
switch (i) {
case JOptionPane.YES_OPTION:
ValidateProject validate = ValidateProject.actionType.makeNewAction(project, null, getController().getEditor());
validate.doAction();
if (validate.getErrorsNb() > 0) {
StringBuilder sb = new StringBuilder();
if (validate.getIeValidationReport().getErrorNb() > 0) {
sb.append(FlexoLocalization.localizedForKey("there_are_errors_in_your_components") + "\n");
}
if (validate.getWkfValidationReport().getErrorNb() > 0) {
sb.append(FlexoLocalization.localizedForKey("there_are_errors_in_your_processes") + "\n");
}
if (validate.getDmValidationReport().getErrorNb() > 0) {
sb.append(FlexoLocalization.localizedForKey("there_are_errors_in_your_data_model") + "\n");
}
if (validate.getDkvValidationReport().getErrorNb() > 0) {
sb.append(FlexoLocalization.localizedForKey("there_are_errors_in_the_dkv") + "\n");
}
sb.append(FlexoLocalization.localizedForKey("would_you_like_to_continue_anyway") + "?");
if (!FlexoController.confirmWithWarning(sb.toString())) {
return false;
}
} else {
if (GeneralPreferences.getNotifyValidProject()) {
ParameterDefinition[] params = new ParameterDefinition[1];
CheckboxParameter dontNotify = new CheckboxParameter("dont_notify", "dont_notify_if_project_is_valid", false);
params[0] = dontNotify;
AskParametersDialog dialog = AskParametersDialog.createAskParametersDialog(project,
FlexoLocalization.localizedForKey("project_is_valid"), FlexoLocalization.localizedForKey("project_is_valid"),
params);
if (dialog.getStatus() == AskParametersDialog.VALIDATE) {
if (dontNotify.getValue()) {
GeneralPreferences.setNotifyValidProject(false);
GeneralPreferences.save();
}
} else {
return false;
}
}
}
break;
case JOptionPane.NO_OPTION:
break;
default:
return false;
}
return true;
}
| private boolean saveForServerPreprocessing() {
FlexoProject project = _controller.getProject();
int i = FlexoController.confirmYesNoCancel(FlexoLocalization
.localizedForKey("would_you_like_to_check_your_project_consistency_first") + "?");
switch (i) {
case JOptionPane.YES_OPTION:
ValidateProject validate = ValidateProject.actionType.makeNewAction(project, null, getController().getEditor());
validate.doAction();
if (validate.getErrorsNb() > 0) {
StringBuilder sb = new StringBuilder();
if (validate.getIeValidationReport() != null & validate.getIeValidationReport().getErrorNb() > 0) {
sb.append(FlexoLocalization.localizedForKey("there_are_errors_in_your_components") + "\n");
}
if (validate.getWkfValidationReport() != null && validate.getWkfValidationReport().getErrorNb() > 0) {
sb.append(FlexoLocalization.localizedForKey("there_are_errors_in_your_processes") + "\n");
}
if (validate.getDmValidationReport() != null && validate.getDmValidationReport().getErrorNb() > 0) {
sb.append(FlexoLocalization.localizedForKey("there_are_errors_in_your_data_model") + "\n");
}
if (validate.getDkvValidationReport() != null && validate.getDkvValidationReport().getErrorNb() > 0) {
sb.append(FlexoLocalization.localizedForKey("there_are_errors_in_the_dkv") + "\n");
}
sb.append(FlexoLocalization.localizedForKey("would_you_like_to_continue_anyway") + "?");
if (!FlexoController.confirmWithWarning(sb.toString())) {
return false;
}
} else {
if (GeneralPreferences.getNotifyValidProject()) {
ParameterDefinition[] params = new ParameterDefinition[1];
CheckboxParameter dontNotify = new CheckboxParameter("dont_notify", "dont_notify_if_project_is_valid", false);
params[0] = dontNotify;
AskParametersDialog dialog = AskParametersDialog.createAskParametersDialog(project,
FlexoLocalization.localizedForKey("project_is_valid"), FlexoLocalization.localizedForKey("project_is_valid"),
params);
if (dialog.getStatus() == AskParametersDialog.VALIDATE) {
if (dontNotify.getValue()) {
GeneralPreferences.setNotifyValidProject(false);
GeneralPreferences.save();
}
} else {
return false;
}
}
}
break;
case JOptionPane.NO_OPTION:
break;
default:
return false;
}
return true;
}
|
diff --git a/vlc-android/src/org/videolan/vlc/Util.java b/vlc-android/src/org/videolan/vlc/Util.java
index 2588bdfb..88146a8f 100644
--- a/vlc-android/src/org/videolan/vlc/Util.java
+++ b/vlc-android/src/org/videolan/vlc/Util.java
@@ -1,364 +1,361 @@
/*****************************************************************************
* Util.java
*****************************************************************************
* Copyright © 2011-2012 VLC authors and VideoLAN
*
* 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., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
package org.videolan.vlc;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.HashSet;
import java.util.Locale;
import java.util.Properties;
import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;
public class Util {
public final static String TAG = "VLC/Util";
public final static boolean hasNavBar;
/** A set of utility functions for the VLC application */
static {
HashSet<String> devicesWithoutNavBar = new HashSet<String>();
devicesWithoutNavBar.add("HTC One V");
devicesWithoutNavBar.add("HTC One S");
devicesWithoutNavBar.add("HTC One X");
devicesWithoutNavBar.add("HTC One XL");
hasNavBar = isICSOrLater() && !devicesWithoutNavBar.contains(android.os.Build.MODEL);
}
/** Print an on-screen message to alert the user */
public static void toaster(Context context, int stringId, int duration) {
Toast.makeText(context, stringId, duration).show();
}
public static void toaster(Context context, int stringId) {
toaster(context, stringId, Toast.LENGTH_SHORT);
}
public static File URItoFile(String URI) {
return new File(Uri.decode(URI).replace("file://",""));
}
public static String URItoFileName(String URI) {
return URItoFile(URI).getName();
}
public static String PathToURI(String path) {
String URI;
try {
URI = LibVLC.getInstance().nativeToURI(path);
} catch (LibVlcException e) {
URI = "";
}
return URI;
}
public static String stripTrailingSlash(String s) {
if( s.endsWith("/") && s.length() > 1 )
return s.substring(0, s.length() - 1);
return s;
}
public static String readAsset(String assetName, String defaultS) {
try {
InputStream is = VLCApplication.getAppResources().getAssets().open(assetName);
BufferedReader r = new BufferedReader(new InputStreamReader(is, "UTF8"));
StringBuilder sb = new StringBuilder();
String line = r.readLine();
if(line != null) {
sb.append(line);
line = r.readLine();
while(line != null) {
sb.append('\n');
sb.append(line);
line = r.readLine();
}
}
return sb.toString();
} catch (IOException e) {
return defaultS;
}
}
/**
* Convert time to a string
* @param millis e.g.time/length from file
* @return formated string (hh:)mm:ss
*/
public static String millisToString(long millis) {
boolean negative = millis < 0;
millis = java.lang.Math.abs(millis);
millis /= 1000;
int sec = (int) (millis % 60);
millis /= 60;
int min = (int) (millis % 60);
millis /= 60;
int hours = (int) millis;
String time;
DecimalFormat format = (DecimalFormat)NumberFormat.getInstance(Locale.US);
format.applyPattern("00");
if (millis > 0) {
time = (negative ? "-" : "") + hours + ":" + format.format(min) + ":" + format.format(sec);
} else {
time = (negative ? "-" : "") + min + ":" + format.format(sec);
}
return time;
}
public static Bitmap scaleDownBitmap(Context context, Bitmap bitmap, int width) {
if (bitmap != null) {
final float densityMultiplier = context.getResources().getDisplayMetrics().density;
int w = (int) (width * densityMultiplier);
int h = (int) (w * bitmap.getHeight() / ((double) bitmap.getWidth()));
bitmap = Bitmap.createScaledBitmap(bitmap, w, h, true);
}
return bitmap;
}
public static Bitmap cropBorders(Bitmap bitmap, int width, int height)
{
int top = 0;
for (int i = 0; i < height / 2; i++) {
int pixel1 = bitmap.getPixel(width / 2, i);
int pixel2 = bitmap.getPixel(width / 2, height - i - 1);
if ((pixel1 == 0 || pixel1 == -16777216) &&
(pixel2 == 0 || pixel2 == -16777216)) {
top = i;
} else {
break;
}
}
int left = 0;
for (int i = 0; i < width / 2; i++) {
int pixel1 = bitmap.getPixel(i, height / 2);
int pixel2 = bitmap.getPixel(width - i - 1, height / 2);
if ((pixel1 == 0 || pixel1 == -16777216) &&
(pixel2 == 0 || pixel2 == -16777216)) {
left = i;
} else {
break;
}
}
if (left >= width / 2 - 10 || top >= height / 2 - 10)
return bitmap;
// Cut off the transparency on the borders
return Bitmap.createBitmap(bitmap, left, top,
(width - (2 * left)), (height - (2 * top)));
}
public static String getValue(String string, int defaultId)
{
return (string != null && string.length() > 0) ?
string : VLCApplication.getAppContext().getString(defaultId);
}
public static void setItemBackground(View v, int position) {
v.setBackgroundResource(position % 2 == 0
? R.drawable.background_item1
: R.drawable.background_item2);
}
public static int convertPxToDp(int px) {
WindowManager wm = (WindowManager)VLCApplication.getAppContext().
getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
DisplayMetrics metrics = new DisplayMetrics();
display.getMetrics(metrics);
float logicalDensity = metrics.density;
int dp = Math.round(px / logicalDensity);
return dp;
}
public static int convertDpToPx(int dp) {
return Math.round(
TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
VLCApplication.getAppResources().getDisplayMetrics())
);
}
public static boolean isGingerbreadOrLater()
{
return android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD;
}
public static boolean isHoneycombOrLater()
{
return android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB;
}
public static boolean isICSOrLater()
{
return android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH;
}
public static boolean isJellyBeanOrLater()
{
return android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN;
}
public static boolean hasNavBar()
{
return hasNavBar;
}
private static String errorMsg = null;
private static boolean isCompatible = false;
public static String getErrorMsg() {
return errorMsg;
}
public static boolean hasCompatibleCPU()
{
// If already checked return cached result
if(errorMsg != null) return isCompatible;
Properties properties = new Properties();
try {
properties.load(new ByteArrayInputStream(Util.readAsset("env.txt", "").getBytes("UTF-8")));
} catch (IOException e) {
// Shouldn't happen if done correctly
e.printStackTrace();
errorMsg = "IOException whilst reading compile flags";
isCompatible = false;
return false;
}
String CPU_ABI = android.os.Build.CPU_ABI;
String CPU_ABI2 = "none";
if(android.os.Build.VERSION.SDK_INT >= 8) { // CPU_ABI2 since 2.2
try {
CPU_ABI2 = (String)android.os.Build.class.getDeclaredField("CPU_ABI2").get(null);
} catch (Exception e) { }
}
String ANDROID_ABI = properties.getProperty("ANDROID_ABI");
- boolean NO_NEON = properties.getProperty("NO_NEON","0").equals("1");
boolean NO_FPU = properties.getProperty("NO_FPU","0").equals("1");
boolean NO_ARMV6 = properties.getProperty("NO_ARMV6","0").equals("1");
boolean hasNeon = false, hasFpu = false, hasArmV6 = false, hasArmV7 = false;
boolean hasX86 = false;
if(CPU_ABI.equals("x86")) {
hasX86 = true;
} else if(CPU_ABI.equals("armeabi-v7a") ||
CPU_ABI2.equals("armeabi-v7a")) {
hasArmV7 = true;
hasArmV6 = true; /* Armv7 is backwards compatible to < v6 */
} else if(CPU_ABI.equals("armeabi") ||
CPU_ABI2.equals("armeabi")) {
hasArmV6 = true;
}
try {
FileReader fileReader = new FileReader("/proc/cpuinfo");
BufferedReader br = new BufferedReader(fileReader);
String line;
while((line = br.readLine()) != null) {
if(!hasArmV7 && line.contains("ARMv7")) {
hasArmV7 = true;
hasArmV6 = true; /* Armv7 is backwards compatible to < v6 */
}
if(!hasArmV7 && !hasArmV6 && line.contains("ARMv6"))
hasArmV6 = true;
// "clflush size" is a x86-specific cpuinfo tag.
// (see kernel sources arch/x86/kernel/cpu/proc.c)
if(line.contains("clflush size"))
hasX86 = true;
// TODO: MIPS - "microsecond timers"; see arch/mips/kernel/proc.c
if(!hasNeon && line.contains("neon"))
hasNeon = true;
if(!hasFpu && line.contains("vfp"))
hasFpu = true;
}
fileReader.close();
} catch(IOException ex){
ex.printStackTrace();
errorMsg = "IOException whilst reading cpuinfo flags";
isCompatible = false;
return false;
}
// Enforce proper architecture to prevent problems
if(ANDROID_ABI.equals("x86") && !hasX86) {
errorMsg = "x86 build on non-x86 device";
isCompatible = false;
return false;
} else if(hasX86 && ANDROID_ABI.contains("armeabi")) {
errorMsg = "ARM build on x86 device";
isCompatible = false;
return false;
}
if(ANDROID_ABI.equals("armeabi-v7a") && !hasArmV7) {
errorMsg = "ARMv7 build on non-ARMv7 device";
isCompatible = false;
return false;
}
if(ANDROID_ABI.equals("armeabi")) {
if(!NO_ARMV6 && !hasArmV6) {
errorMsg = "ARMv6 build on non-ARMv6 device";
isCompatible = false;
return false;
} else if(!NO_FPU && !hasFpu) {
errorMsg = "FPU-enabled build on non-FPU device";
isCompatible = false;
return false;
}
}
if(ANDROID_ABI.equals("armeabi") || ANDROID_ABI.equals("armeabi-v7a")) {
- if(!NO_NEON && !hasNeon) {
+ if(!hasNeon) {
errorMsg = "NEON build on non-NEON device";
- isCompatible = false;
- return false;
}
}
errorMsg = null;
isCompatible = true;
return true;
}
public static boolean isPhone(){
TelephonyManager manager = (TelephonyManager)VLCApplication.getAppContext().getSystemService(Context.TELEPHONY_SERVICE);
if(manager.getPhoneType() == TelephonyManager.PHONE_TYPE_NONE){
return false;
}else{
return true;
}
}
}
| false | true | public static boolean hasCompatibleCPU()
{
// If already checked return cached result
if(errorMsg != null) return isCompatible;
Properties properties = new Properties();
try {
properties.load(new ByteArrayInputStream(Util.readAsset("env.txt", "").getBytes("UTF-8")));
} catch (IOException e) {
// Shouldn't happen if done correctly
e.printStackTrace();
errorMsg = "IOException whilst reading compile flags";
isCompatible = false;
return false;
}
String CPU_ABI = android.os.Build.CPU_ABI;
String CPU_ABI2 = "none";
if(android.os.Build.VERSION.SDK_INT >= 8) { // CPU_ABI2 since 2.2
try {
CPU_ABI2 = (String)android.os.Build.class.getDeclaredField("CPU_ABI2").get(null);
} catch (Exception e) { }
}
String ANDROID_ABI = properties.getProperty("ANDROID_ABI");
boolean NO_NEON = properties.getProperty("NO_NEON","0").equals("1");
boolean NO_FPU = properties.getProperty("NO_FPU","0").equals("1");
boolean NO_ARMV6 = properties.getProperty("NO_ARMV6","0").equals("1");
boolean hasNeon = false, hasFpu = false, hasArmV6 = false, hasArmV7 = false;
boolean hasX86 = false;
if(CPU_ABI.equals("x86")) {
hasX86 = true;
} else if(CPU_ABI.equals("armeabi-v7a") ||
CPU_ABI2.equals("armeabi-v7a")) {
hasArmV7 = true;
hasArmV6 = true; /* Armv7 is backwards compatible to < v6 */
} else if(CPU_ABI.equals("armeabi") ||
CPU_ABI2.equals("armeabi")) {
hasArmV6 = true;
}
try {
FileReader fileReader = new FileReader("/proc/cpuinfo");
BufferedReader br = new BufferedReader(fileReader);
String line;
while((line = br.readLine()) != null) {
if(!hasArmV7 && line.contains("ARMv7")) {
hasArmV7 = true;
hasArmV6 = true; /* Armv7 is backwards compatible to < v6 */
}
if(!hasArmV7 && !hasArmV6 && line.contains("ARMv6"))
hasArmV6 = true;
// "clflush size" is a x86-specific cpuinfo tag.
// (see kernel sources arch/x86/kernel/cpu/proc.c)
if(line.contains("clflush size"))
hasX86 = true;
// TODO: MIPS - "microsecond timers"; see arch/mips/kernel/proc.c
if(!hasNeon && line.contains("neon"))
hasNeon = true;
if(!hasFpu && line.contains("vfp"))
hasFpu = true;
}
fileReader.close();
} catch(IOException ex){
ex.printStackTrace();
errorMsg = "IOException whilst reading cpuinfo flags";
isCompatible = false;
return false;
}
// Enforce proper architecture to prevent problems
if(ANDROID_ABI.equals("x86") && !hasX86) {
errorMsg = "x86 build on non-x86 device";
isCompatible = false;
return false;
} else if(hasX86 && ANDROID_ABI.contains("armeabi")) {
errorMsg = "ARM build on x86 device";
isCompatible = false;
return false;
}
if(ANDROID_ABI.equals("armeabi-v7a") && !hasArmV7) {
errorMsg = "ARMv7 build on non-ARMv7 device";
isCompatible = false;
return false;
}
if(ANDROID_ABI.equals("armeabi")) {
if(!NO_ARMV6 && !hasArmV6) {
errorMsg = "ARMv6 build on non-ARMv6 device";
isCompatible = false;
return false;
} else if(!NO_FPU && !hasFpu) {
errorMsg = "FPU-enabled build on non-FPU device";
isCompatible = false;
return false;
}
}
if(ANDROID_ABI.equals("armeabi") || ANDROID_ABI.equals("armeabi-v7a")) {
if(!NO_NEON && !hasNeon) {
errorMsg = "NEON build on non-NEON device";
isCompatible = false;
return false;
}
}
errorMsg = null;
isCompatible = true;
return true;
}
| public static boolean hasCompatibleCPU()
{
// If already checked return cached result
if(errorMsg != null) return isCompatible;
Properties properties = new Properties();
try {
properties.load(new ByteArrayInputStream(Util.readAsset("env.txt", "").getBytes("UTF-8")));
} catch (IOException e) {
// Shouldn't happen if done correctly
e.printStackTrace();
errorMsg = "IOException whilst reading compile flags";
isCompatible = false;
return false;
}
String CPU_ABI = android.os.Build.CPU_ABI;
String CPU_ABI2 = "none";
if(android.os.Build.VERSION.SDK_INT >= 8) { // CPU_ABI2 since 2.2
try {
CPU_ABI2 = (String)android.os.Build.class.getDeclaredField("CPU_ABI2").get(null);
} catch (Exception e) { }
}
String ANDROID_ABI = properties.getProperty("ANDROID_ABI");
boolean NO_FPU = properties.getProperty("NO_FPU","0").equals("1");
boolean NO_ARMV6 = properties.getProperty("NO_ARMV6","0").equals("1");
boolean hasNeon = false, hasFpu = false, hasArmV6 = false, hasArmV7 = false;
boolean hasX86 = false;
if(CPU_ABI.equals("x86")) {
hasX86 = true;
} else if(CPU_ABI.equals("armeabi-v7a") ||
CPU_ABI2.equals("armeabi-v7a")) {
hasArmV7 = true;
hasArmV6 = true; /* Armv7 is backwards compatible to < v6 */
} else if(CPU_ABI.equals("armeabi") ||
CPU_ABI2.equals("armeabi")) {
hasArmV6 = true;
}
try {
FileReader fileReader = new FileReader("/proc/cpuinfo");
BufferedReader br = new BufferedReader(fileReader);
String line;
while((line = br.readLine()) != null) {
if(!hasArmV7 && line.contains("ARMv7")) {
hasArmV7 = true;
hasArmV6 = true; /* Armv7 is backwards compatible to < v6 */
}
if(!hasArmV7 && !hasArmV6 && line.contains("ARMv6"))
hasArmV6 = true;
// "clflush size" is a x86-specific cpuinfo tag.
// (see kernel sources arch/x86/kernel/cpu/proc.c)
if(line.contains("clflush size"))
hasX86 = true;
// TODO: MIPS - "microsecond timers"; see arch/mips/kernel/proc.c
if(!hasNeon && line.contains("neon"))
hasNeon = true;
if(!hasFpu && line.contains("vfp"))
hasFpu = true;
}
fileReader.close();
} catch(IOException ex){
ex.printStackTrace();
errorMsg = "IOException whilst reading cpuinfo flags";
isCompatible = false;
return false;
}
// Enforce proper architecture to prevent problems
if(ANDROID_ABI.equals("x86") && !hasX86) {
errorMsg = "x86 build on non-x86 device";
isCompatible = false;
return false;
} else if(hasX86 && ANDROID_ABI.contains("armeabi")) {
errorMsg = "ARM build on x86 device";
isCompatible = false;
return false;
}
if(ANDROID_ABI.equals("armeabi-v7a") && !hasArmV7) {
errorMsg = "ARMv7 build on non-ARMv7 device";
isCompatible = false;
return false;
}
if(ANDROID_ABI.equals("armeabi")) {
if(!NO_ARMV6 && !hasArmV6) {
errorMsg = "ARMv6 build on non-ARMv6 device";
isCompatible = false;
return false;
} else if(!NO_FPU && !hasFpu) {
errorMsg = "FPU-enabled build on non-FPU device";
isCompatible = false;
return false;
}
}
if(ANDROID_ABI.equals("armeabi") || ANDROID_ABI.equals("armeabi-v7a")) {
if(!hasNeon) {
errorMsg = "NEON build on non-NEON device";
}
}
errorMsg = null;
isCompatible = true;
return true;
}
|
diff --git a/src/play/modules/solar/SolarPlugin.java b/src/play/modules/solar/SolarPlugin.java
index 4beffba..5f1634c 100644
--- a/src/play/modules/solar/SolarPlugin.java
+++ b/src/play/modules/solar/SolarPlugin.java
@@ -1,196 +1,200 @@
package play.modules.solar;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.List;
import play.Play;
import play.Play.Mode;
import play.PlayPlugin;
import play.libs.IO;
import play.mvc.Http.Request;
import play.mvc.Http.Response;
import play.classloading.ApplicationClasses.ApplicationClass;
import play.exceptions.CompilationException;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
public class SolarPlugin extends PlayPlugin {
@Override
public boolean rawInvocation(Request request, Response response) {
try {
if (Play.mode == Mode.PROD) {
return false;
}
// -- /bespin
if (request.path.equals("/solar") || request.path.equals("/solar/")) {
response.status = 302;
response.setHeader("Location", "/solar/public/index.html");
return true;
}
if (request.path.equals("/solar/compile")) {
- ApplicationClass applicationClass = Play.classes.getApplicationClass("");
+ ApplicationClass applicationClass = Play.classes.getApplicationClass("controllers.Application");
if (applicationClass != null) {
try {
+ applicationClass.refresh();
applicationClass.compile();
+ response.status = 200;
+ response.out.write("compile".getBytes());
} catch (CompilationException e) {
- //todo
+ response.status = 200;
+ response.out.write("does not compile".getBytes());
}
}
return true;
}
// -- /bespin/serverconfig.js
if (request.path.equals("/solar/serverconfig.js")) {
return serveConfig(request, response);
}
// -- Static files (/bespin/public)
if (request.path.startsWith("/solar/public/")) {
String path = request.path.substring("/solar/public".length());
return servePublic(request, response, path);
}
// -- /bespin/file/at
if (request.path.startsWith("/solar/file/at/")) {
File file = Play.getFile(request.path.substring("/solar/file/at".length()));
return serveStatic(request, response, file);
}
// -- /bespin/save/
if (request.path.startsWith("/solar/save/")) {
File file = Play.getFile(request.path.substring("/solar/save".length()));
InputStream content = request.body;
save(content, file);
return true;
}
// -- bespin/list
if (request.path.startsWith("/solar/list/")) {
String root = request.path.substring("/solar/list".length());
List<File> fileList = Arrays.asList(Play.getFile(root).listFiles());
response.status = 200;
response.out.write(serialize(fileList).getBytes("utf-8"));
return true;
}
return false;
} catch(Exception e) {
throw new RuntimeException(e);
}
}
public void save(InputStream is, File target) {
FileOutputStream os;
try {
os = new FileOutputStream(target);
} catch (FileNotFoundException e) {
// TODO create the file
e.printStackTrace();
return;
}
int c;
try {
while ((c = is.read()) != -1) {
os.write(c);
}
is.close();
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return;
}
}
private boolean servePublic(Request request, Response response, String path) throws Exception {
String fullPath = getBespinFolder().getPath() + File.separator + "public" + path;
boolean binary = false;
if (path.endsWith(".html") || path.endsWith(".htm")) {
response.contentType = "text/html; charset=utf8";
} else if (path.endsWith(".css")) {
response.contentType = "text/css; charset=utf8";
} else if (path.endsWith(".png")) {
response.contentType = "image/png";
binary = true;
}
if (binary)
return serveBinary(request, response, new File(fullPath));
else
return serveStatic(request, response, new File(fullPath));
}
private boolean serveBinary(Request request, Response response, File file) throws Exception {
FileInputStream is = new FileInputStream(file);
byte[] buffer = new byte[8092];
int count = 0;
while ((count = is.read(buffer)) > 0) {
response.out.write(buffer, 0, count);
}
is.close();
return true;
}
private boolean serveStatic(Request request, Response response, File file) throws Exception {
try {
if(request.method.equals("GET")) {
response.status = 200;
response.out.write(IO.readContentAsString(file).replace("\t", " ").getBytes("utf-8"));
} else {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int r = -1;
while((r = request.body.read()) != -1) {
baos.write(r);
}
IO.writeContent(new String(baos.toByteArray(), "utf-8"), file);
}
return true;
} catch (FileNotFoundException e) {
response.status = 404;
return false;
}
}
private boolean serveConfig(Request request, Response response) throws Exception {
response.status = 200;
String body = "var serverConfig = { 'rootUrl': '"
+ Play.applicationPath
+ "' }";
response.out.write(body.replace("\t", " ").getBytes("utf-8"));
return true;
}
@Override
public void onConfigurationRead() {
if (!Play.configuration.contains("play.editor")) {
Play.configuration.put("play.editor", "/solar/public/index.html#%s|%s");
}
}
private File getBespinFolder() {
return Play.modules.get("solar").getRealFile();
}
public static final Type listFileType = new TypeToken<List<File>>(){}.getType();
private static String serialize(List<File> list) {
GsonBuilder gson = new GsonBuilder();
gson.registerTypeAdapter(File.class, new FileSerializer());
gson.registerTypeAdapter(listFileType, new FileListSerializer());
String result = gson.create().toJson(list, listFileType);
return result;
}
}
| false | true | public boolean rawInvocation(Request request, Response response) {
try {
if (Play.mode == Mode.PROD) {
return false;
}
// -- /bespin
if (request.path.equals("/solar") || request.path.equals("/solar/")) {
response.status = 302;
response.setHeader("Location", "/solar/public/index.html");
return true;
}
if (request.path.equals("/solar/compile")) {
ApplicationClass applicationClass = Play.classes.getApplicationClass("");
if (applicationClass != null) {
try {
applicationClass.compile();
} catch (CompilationException e) {
//todo
}
}
return true;
}
// -- /bespin/serverconfig.js
if (request.path.equals("/solar/serverconfig.js")) {
return serveConfig(request, response);
}
// -- Static files (/bespin/public)
if (request.path.startsWith("/solar/public/")) {
String path = request.path.substring("/solar/public".length());
return servePublic(request, response, path);
}
// -- /bespin/file/at
if (request.path.startsWith("/solar/file/at/")) {
File file = Play.getFile(request.path.substring("/solar/file/at".length()));
return serveStatic(request, response, file);
}
// -- /bespin/save/
if (request.path.startsWith("/solar/save/")) {
File file = Play.getFile(request.path.substring("/solar/save".length()));
InputStream content = request.body;
save(content, file);
return true;
}
// -- bespin/list
if (request.path.startsWith("/solar/list/")) {
String root = request.path.substring("/solar/list".length());
List<File> fileList = Arrays.asList(Play.getFile(root).listFiles());
response.status = 200;
response.out.write(serialize(fileList).getBytes("utf-8"));
return true;
}
return false;
} catch(Exception e) {
throw new RuntimeException(e);
}
}
| public boolean rawInvocation(Request request, Response response) {
try {
if (Play.mode == Mode.PROD) {
return false;
}
// -- /bespin
if (request.path.equals("/solar") || request.path.equals("/solar/")) {
response.status = 302;
response.setHeader("Location", "/solar/public/index.html");
return true;
}
if (request.path.equals("/solar/compile")) {
ApplicationClass applicationClass = Play.classes.getApplicationClass("controllers.Application");
if (applicationClass != null) {
try {
applicationClass.refresh();
applicationClass.compile();
response.status = 200;
response.out.write("compile".getBytes());
} catch (CompilationException e) {
response.status = 200;
response.out.write("does not compile".getBytes());
}
}
return true;
}
// -- /bespin/serverconfig.js
if (request.path.equals("/solar/serverconfig.js")) {
return serveConfig(request, response);
}
// -- Static files (/bespin/public)
if (request.path.startsWith("/solar/public/")) {
String path = request.path.substring("/solar/public".length());
return servePublic(request, response, path);
}
// -- /bespin/file/at
if (request.path.startsWith("/solar/file/at/")) {
File file = Play.getFile(request.path.substring("/solar/file/at".length()));
return serveStatic(request, response, file);
}
// -- /bespin/save/
if (request.path.startsWith("/solar/save/")) {
File file = Play.getFile(request.path.substring("/solar/save".length()));
InputStream content = request.body;
save(content, file);
return true;
}
// -- bespin/list
if (request.path.startsWith("/solar/list/")) {
String root = request.path.substring("/solar/list".length());
List<File> fileList = Arrays.asList(Play.getFile(root).listFiles());
response.status = 200;
response.out.write(serialize(fileList).getBytes("utf-8"));
return true;
}
return false;
} catch(Exception e) {
throw new RuntimeException(e);
}
}
|
diff --git a/src/main/java/org/spoutcraft/launcher/technic/InstalledRest.java b/src/main/java/org/spoutcraft/launcher/technic/InstalledRest.java
index 2d02eed..c36be30 100644
--- a/src/main/java/org/spoutcraft/launcher/technic/InstalledRest.java
+++ b/src/main/java/org/spoutcraft/launcher/technic/InstalledRest.java
@@ -1,100 +1,100 @@
/*
* This file is part of Technic Launcher.
*
* Copyright (c) 2013-2013, Technic <http://www.technicpack.net/>
* Technic Launcher is licensed under the Spout License Version 1.
*
* Technic Launcher 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 3 of the License, or
* (at your option) any later version.
*
* In addition, 180 days after any changes are published, you can use the
* software, incorporating those changes, under the terms of the MIT license,
* as described in the Spout License Version 1.
*
* Technic Launcher 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,
* the MIT license and the Spout License Version 1 along with this program.
* If not, see <http://www.gnu.org/licenses/> for the GNU Lesser General Public
* License and see <http://www.spout.org/SpoutDevLicenseV1.txt> for the full license,
* including the MIT license.
*/
package org.spoutcraft.launcher.technic;
import java.awt.Image;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import javax.swing.ImageIcon;
import org.spoutcraft.launcher.exceptions.RestfulAPIException;
import org.spoutcraft.launcher.technic.rest.Modpack;
import org.spoutcraft.launcher.technic.rest.info.RestInfo;
import org.spoutcraft.launcher.technic.rest.pack.FallbackModpack;
public class InstalledRest extends InstalledPack {
private final RestInfo info;
public InstalledRest(RestInfo info) throws IOException {
super(info.getIcon(), info.getLogo(), new ImageIcon(info.getBackground().getScaledInstance(880, 520, Image.SCALE_SMOOTH)));
this.info = info;
init();
}
public RestInfo getInfo() {
return info;
}
@Override
public String getName() {
return info.getName();
}
@Override
public String getDisplayName() {
return info.getDisplayName();
}
@Override
public String getRecommended() {
return info.getRecommended();
}
@Override
public String getLatest() {
return info.getLatest();
}
@Override
public String getLogoURL() {
return info.getLogoURL();
}
@Override
public List<String> getBuilds() {
return Arrays.asList(info.getBuilds());
}
@Override
public Modpack getModpack() {
try {
return info.getRest().getModpack(info, getBuild());
} catch (RestfulAPIException e) {
e.printStackTrace();
- File installed = new File(this.getPackDirectory(), "installed");
+ File installed = new File(this.getBinDir(), "installed");
if (installed.exists()) {
return new FallbackModpack(getName(), getBuild());
}
return null;
}
}
}
| true | true | public Modpack getModpack() {
try {
return info.getRest().getModpack(info, getBuild());
} catch (RestfulAPIException e) {
e.printStackTrace();
File installed = new File(this.getPackDirectory(), "installed");
if (installed.exists()) {
return new FallbackModpack(getName(), getBuild());
}
return null;
}
}
| public Modpack getModpack() {
try {
return info.getRest().getModpack(info, getBuild());
} catch (RestfulAPIException e) {
e.printStackTrace();
File installed = new File(this.getBinDir(), "installed");
if (installed.exists()) {
return new FallbackModpack(getName(), getBuild());
}
return null;
}
}
|
diff --git a/src/main/java/org/sonatype/ziptest/App.java b/src/main/java/org/sonatype/ziptest/App.java
index 8da75e0..f77ad36 100644
--- a/src/main/java/org/sonatype/ziptest/App.java
+++ b/src/main/java/org/sonatype/ziptest/App.java
@@ -1,191 +1,191 @@
package org.sonatype.ziptest;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
import de.schlichtherle.truezip.file.TFile;
public class App
{
public static final long KB = 1024;
public static final long MB = 1024 * 1024;
public static void main( String[] args )
throws IOException
{
if ( args != null && args.length == 2 )
{
final File file = new File( args[1] );
final String sw = args[0];
if ( "all".equalsIgnoreCase( sw ) )
{
test( file, "zf" );
test( file, "zis" );
test( file, "tzf" );
test( file, "tzt" );
}
else
{
test( file, sw );
}
}
else
{
System.out.println( "java -jar thisjar.jar [1|2] <aZipFile>" );
}
}
public static void test( final File file, final String sw )
throws IOException
{
final long started = System.currentTimeMillis();
if ( "zf".equalsIgnoreCase( sw ) )
{
testZipFile( file );
}
else if ( "zis".equalsIgnoreCase( sw ) )
{
testZipInputStream( file );
}
else if ( "tzf".equalsIgnoreCase( sw ) )
{
testTrueZipZipFile( file );
}
else if ( "tzt".equalsIgnoreCase( sw ) )
{
- testTrueZipZipFile( file );
+ testTrueZipTFile( file );
}
else
{
System.out.println( "Boo!" );
}
System.out.println( String.format( "Done in %s millis.", System.currentTimeMillis() - started ) );
Runtime r = Runtime.getRuntime();
System.out.println( "Final Memory: " + ( r.totalMemory() - r.freeMemory() ) / KB + "kB/" + r.totalMemory() / KB
+ "kB" );
System.gc();
System.out.println( "Final Memory: " + ( r.totalMemory() - r.freeMemory() ) / KB + "kB/" + r.totalMemory() / KB
+ "kB (after GC)" );
}
public static void testZipFile( final File file )
throws IOException
{
System.out.println( "=======" );
System.out.println( "ZipFile" );
System.out.println( "=======" );
ZipFile zf = new ZipFile( file );
Enumeration<? extends ZipEntry> entries = zf.entries();
int count = 0;
while ( entries.hasMoreElements() )
{
ZipEntry entry = entries.nextElement();
// System.out.println( entry.getName() );
count++;
}
// System.out.println( "=====" );
System.out.println( String.format( "Total of %s entries.", count ) );
}
public static void testZipInputStream( final File file )
throws IOException
{
System.out.println( "==============" );
System.out.println( "ZipInputStream" );
System.out.println( "==============" );
ZipInputStream zi = new ZipInputStream( new BufferedInputStream( new FileInputStream( file ) ) );
ZipEntry entry = null;
int count = 0;
while ( ( entry = zi.getNextEntry() ) != null )
{
// System.out.println( entry.getName() );
count++;
}
// System.out.println( "=====" );
System.out.println( String.format( "Total of %s entries.", count ) );
}
public static void testTrueZipZipFile( final File file )
throws IOException
{
System.out.println( "===============" );
System.out.println( "TrueZip ZipFile" );
System.out.println( "===============" );
de.schlichtherle.truezip.zip.ZipFile zf = new de.schlichtherle.truezip.zip.ZipFile( file );
Enumeration<? extends de.schlichtherle.truezip.zip.ZipEntry> entries = zf.entries();
int count = 0;
while ( entries.hasMoreElements() )
{
de.schlichtherle.truezip.zip.ZipEntry entry = entries.nextElement();
// System.out.println( entry.getName() );
count++;
}
// System.out.println( "=====" );
System.out.println( String.format( "Total of %s entries.", count ) );
}
public static void testTrueZipTFile( final File file )
throws IOException
{
System.out.println( "=============" );
System.out.println( "TrueZip TFile" );
System.out.println( "=============" );
TFile zf = new TFile( file );
TFile[] entries = zf.listFiles();
int count = 0;
for ( TFile entry : entries )
{
// System.out.println( entry.getName() );
count++;
}
// System.out.println( "=====" );
System.out.println( String.format( "Total of %s entries.", count ) );
}
}
| true | true | public static void test( final File file, final String sw )
throws IOException
{
final long started = System.currentTimeMillis();
if ( "zf".equalsIgnoreCase( sw ) )
{
testZipFile( file );
}
else if ( "zis".equalsIgnoreCase( sw ) )
{
testZipInputStream( file );
}
else if ( "tzf".equalsIgnoreCase( sw ) )
{
testTrueZipZipFile( file );
}
else if ( "tzt".equalsIgnoreCase( sw ) )
{
testTrueZipZipFile( file );
}
else
{
System.out.println( "Boo!" );
}
System.out.println( String.format( "Done in %s millis.", System.currentTimeMillis() - started ) );
Runtime r = Runtime.getRuntime();
System.out.println( "Final Memory: " + ( r.totalMemory() - r.freeMemory() ) / KB + "kB/" + r.totalMemory() / KB
+ "kB" );
System.gc();
System.out.println( "Final Memory: " + ( r.totalMemory() - r.freeMemory() ) / KB + "kB/" + r.totalMemory() / KB
+ "kB (after GC)" );
}
| public static void test( final File file, final String sw )
throws IOException
{
final long started = System.currentTimeMillis();
if ( "zf".equalsIgnoreCase( sw ) )
{
testZipFile( file );
}
else if ( "zis".equalsIgnoreCase( sw ) )
{
testZipInputStream( file );
}
else if ( "tzf".equalsIgnoreCase( sw ) )
{
testTrueZipZipFile( file );
}
else if ( "tzt".equalsIgnoreCase( sw ) )
{
testTrueZipTFile( file );
}
else
{
System.out.println( "Boo!" );
}
System.out.println( String.format( "Done in %s millis.", System.currentTimeMillis() - started ) );
Runtime r = Runtime.getRuntime();
System.out.println( "Final Memory: " + ( r.totalMemory() - r.freeMemory() ) / KB + "kB/" + r.totalMemory() / KB
+ "kB" );
System.gc();
System.out.println( "Final Memory: " + ( r.totalMemory() - r.freeMemory() ) / KB + "kB/" + r.totalMemory() / KB
+ "kB (after GC)" );
}
|
diff --git a/src/test/java/org/jboss/ejb/client/ipv6/IPv6TestCase.java b/src/test/java/org/jboss/ejb/client/ipv6/IPv6TestCase.java
index f9a5388..efabdd9 100644
--- a/src/test/java/org/jboss/ejb/client/ipv6/IPv6TestCase.java
+++ b/src/test/java/org/jboss/ejb/client/ipv6/IPv6TestCase.java
@@ -1,169 +1,172 @@
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file 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.jboss.ejb.client.ipv6;
import org.jboss.ejb.client.ContextSelector;
import org.jboss.ejb.client.EJBClient;
import org.jboss.ejb.client.EJBClientConfiguration;
import org.jboss.ejb.client.EJBClientContext;
import org.jboss.ejb.client.PropertiesBasedEJBClientConfiguration;
import org.jboss.ejb.client.StatelessEJBLocator;
import org.jboss.ejb.client.remoting.ConfigBasedEJBClientContextSelector;
import org.jboss.ejb.client.test.client.EchoBean;
import org.jboss.ejb.client.test.client.EchoRemote;
import org.jboss.ejb.client.test.common.DummyServer;
import org.jboss.logging.Logger;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.io.IOException;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;
/**
* Basic testcase for testing IPv6 connection handling within the EJB client project
*
* @author Jaikiran Pai
*/
@RunWith(Parameterized.class)
public class IPv6TestCase {
private static final Logger logger = Logger.getLogger(IPv6TestCase.class);
private static final String APP_NAME = "my-foo-app";
private static final String MODULE_NAME = "my-bar-module";
private static final String DISTINCT_NAME = "";
private final DummyServer server;
private ContextSelector<EJBClientContext> previousSelector;
private final String destinationHost;
private final int destinationPort;
/**
* Looks for any IPv6 addresses on the system and returns those to be used as parameters for the testcase
*
* @return
* @throws Exception
*/
@Parameterized.Parameters
public static Collection<Object[]> getIPv6Addresses() throws Exception {
final Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
if (networkInterfaces == null) {
return Collections.emptyList();
}
final List<String> ipv6Addresses = new ArrayList<String>();
while (networkInterfaces.hasMoreElements()) {
final NetworkInterface networkInterface = networkInterfaces.nextElement();
+ if (!networkInterface.isUp()) {
+ continue;
+ }
final Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();
if (addresses == null) {
continue;
}
while (addresses.hasMoreElements()) {
final InetAddress address = addresses.nextElement();
if (address instanceof Inet6Address) {
ipv6Addresses.add(address.getHostAddress());
}
}
}
final Object[][] data = new Object[ipv6Addresses.size()][];
for (int i = 0; i < ipv6Addresses.size(); i++) {
data[i] = new Object[]{ipv6Addresses.get(i)};
}
return Arrays.asList(data);
}
public IPv6TestCase(final String ipv6Host) {
this.destinationHost = ipv6Host;
this.destinationPort = 6999;
logger.info("Creating server for IPv6 address " + this.destinationHost);
server = new DummyServer(destinationHost, destinationPort, "ipv6-test-server");
}
@Before
public void beforeTest() throws IOException {
server.start();
final EchoBean bean = new EchoBean();
// deploy on server
server.register(APP_NAME, MODULE_NAME, DISTINCT_NAME, EchoBean.class.getSimpleName(), bean);
// setup EJB client context
final Properties clientProps = new Properties();
clientProps.put("remote.connectionprovider.create.options.org.xnio.Options.SSL_ENABLED", "false");
clientProps.put("remote.connections", "ipv6server");
clientProps.put("remote.connection.ipv6server.host", this.destinationHost);
clientProps.put("remote.connection.ipv6server.port", String.valueOf(this.destinationPort));
clientProps.put("remote.connection.ipv6server.connect.options.org.xnio.Options.SASL_POLICY_NOANONYMOUS", "false");
final EJBClientConfiguration clientConfiguration = new PropertiesBasedEJBClientConfiguration(clientProps);
final ConfigBasedEJBClientContextSelector selector = new ConfigBasedEJBClientContextSelector(clientConfiguration);
this.previousSelector = EJBClientContext.setSelector(selector);
}
@After
public void afterTest() throws IOException {
try {
this.server.stop();
} catch (Exception e) {
logger.info("Could not stop server", e);
}
if (this.previousSelector != null) {
EJBClientContext.setSelector(previousSelector);
}
}
/**
* Tests a simple invocation on a IPv6 server which hosts a bean
*
* @throws Exception
*/
@Test
public void testInvocationOnIPv6Server() throws Exception {
logger.info("Running test for " + this.destinationHost + ":" + this.destinationPort);
// create a proxy for invocation
final StatelessEJBLocator<EchoRemote> statelessEJBLocator = new StatelessEJBLocator<EchoRemote>(EchoRemote.class, APP_NAME, MODULE_NAME, EchoBean.class.getSimpleName(), "");
final EchoRemote bean = EJBClient.createProxy(statelessEJBLocator);
Assert.assertNotNull("Received a null proxy", bean);
final String message = "hello to ipv6 server";
final String echo = bean.echo(message);
Assert.assertEquals("Unexpected echo received from IPv6 server " + this.destinationHost + ":" + this.destinationPort, message, echo);
}
}
| true | true | public static Collection<Object[]> getIPv6Addresses() throws Exception {
final Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
if (networkInterfaces == null) {
return Collections.emptyList();
}
final List<String> ipv6Addresses = new ArrayList<String>();
while (networkInterfaces.hasMoreElements()) {
final NetworkInterface networkInterface = networkInterfaces.nextElement();
final Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();
if (addresses == null) {
continue;
}
while (addresses.hasMoreElements()) {
final InetAddress address = addresses.nextElement();
if (address instanceof Inet6Address) {
ipv6Addresses.add(address.getHostAddress());
}
}
}
final Object[][] data = new Object[ipv6Addresses.size()][];
for (int i = 0; i < ipv6Addresses.size(); i++) {
data[i] = new Object[]{ipv6Addresses.get(i)};
}
return Arrays.asList(data);
}
| public static Collection<Object[]> getIPv6Addresses() throws Exception {
final Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
if (networkInterfaces == null) {
return Collections.emptyList();
}
final List<String> ipv6Addresses = new ArrayList<String>();
while (networkInterfaces.hasMoreElements()) {
final NetworkInterface networkInterface = networkInterfaces.nextElement();
if (!networkInterface.isUp()) {
continue;
}
final Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();
if (addresses == null) {
continue;
}
while (addresses.hasMoreElements()) {
final InetAddress address = addresses.nextElement();
if (address instanceof Inet6Address) {
ipv6Addresses.add(address.getHostAddress());
}
}
}
final Object[][] data = new Object[ipv6Addresses.size()][];
for (int i = 0; i < ipv6Addresses.size(); i++) {
data[i] = new Object[]{ipv6Addresses.get(i)};
}
return Arrays.asList(data);
}
|
diff --git a/src/test/java/uk/co/caprica/vlcj/test/discoverer/MediaDirsTest.java b/src/test/java/uk/co/caprica/vlcj/test/discoverer/MediaDirsTest.java
index b24f4d19..0237933f 100644
--- a/src/test/java/uk/co/caprica/vlcj/test/discoverer/MediaDirsTest.java
+++ b/src/test/java/uk/co/caprica/vlcj/test/discoverer/MediaDirsTest.java
@@ -1,101 +1,102 @@
/*
* This file is part of VLCJ.
*
* VLCJ 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.
*
* VLCJ 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 VLCJ. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2009, 2010, 2011, 2012 Caprica Software Limited.
*/
package uk.co.caprica.vlcj.test.discoverer;
import java.util.List;
import uk.co.caprica.vlcj.binding.internal.libvlc_media_t;
import uk.co.caprica.vlcj.medialist.MediaList;
import uk.co.caprica.vlcj.medialist.MediaListEventListener;
import uk.co.caprica.vlcj.medialist.MediaListItem;
import uk.co.caprica.vlcj.player.MediaPlayerFactory;
import uk.co.caprica.vlcj.player.discoverer.MediaDiscoverer;
import uk.co.caprica.vlcj.test.VlcjTest;
/**
* Simple media directories discovery test.
*/
public class MediaDirsTest extends VlcjTest implements MediaListEventListener {
public static void main(String[] args) throws Exception {
new MediaDirsTest();
}
public MediaDirsTest() throws Exception {
MediaPlayerFactory mediaPlayerFactory = new MediaPlayerFactory();
MediaDiscoverer videoMediaDiscoverer = mediaPlayerFactory.newMediaDiscoverer("video_dir");
Thread.sleep(500); // FIXME not acceptable
MediaList videoFileList = videoMediaDiscoverer.getMediaList();
// videoFileList.addMediaListEventListener(this);
List<MediaListItem> videoFiles = videoFileList.items();
System.out.println("Video Files:");
dumpItems(videoFiles, 1);
System.out.println();
MediaDiscoverer audioMediaDiscoverer = mediaPlayerFactory.newMediaDiscoverer("audio_dir");
Thread.sleep(500); // FIXME not acceptable
MediaList audioFileList = audioMediaDiscoverer.getMediaList();
// audioFileList.addMediaListEventListener(this);
List<MediaListItem> audioFiles = audioFileList.items();
System.out.println("Audio Files:");
dumpItems(audioFiles, 1);
System.out.println();
MediaDiscoverer pictureMediaDiscoverer = mediaPlayerFactory.newMediaDiscoverer("picture_dir");
Thread.sleep(500); // FIXME not acceptable
MediaList pictureFileList = pictureMediaDiscoverer.getMediaList();
// pictureFileList.addMediaListEventListener(this);
List<MediaListItem> pictureFiles = pictureFileList.items();
System.out.println("Picture Files:");
dumpItems(pictureFiles, 1);
System.out.println("DONE!");
- Thread.currentThread().join();
+// Thread.currentThread().join();
+ System.exit(0);
}
private static void dumpItems(List<MediaListItem> items, int indent) {
for(MediaListItem item : items) {
System.out.printf("%" + indent + "s%s%n", " ", item);
dumpItems(item.subItems(), indent + 1);
}
}
@Override
public void mediaListWillAddItem(MediaList mediaList, libvlc_media_t mediaInstance, int index) {
}
@Override
public void mediaListItemAdded(MediaList mediaList, libvlc_media_t mediaInstance, int index) {
System.out.println("ITEM ADDED: " + index + " -> " + mediaList.items());
}
@Override
public void mediaListWillDeleteItem(MediaList mediaList, libvlc_media_t mediaInstance, int index) {
}
@Override
public void mediaListItemDeleted(MediaList mediaList, libvlc_media_t mediaInstance, int index) {
System.out.println("ITEM DELETED: " + index + " -> " + mediaList.items());
}
}
| true | true | public MediaDirsTest() throws Exception {
MediaPlayerFactory mediaPlayerFactory = new MediaPlayerFactory();
MediaDiscoverer videoMediaDiscoverer = mediaPlayerFactory.newMediaDiscoverer("video_dir");
Thread.sleep(500); // FIXME not acceptable
MediaList videoFileList = videoMediaDiscoverer.getMediaList();
// videoFileList.addMediaListEventListener(this);
List<MediaListItem> videoFiles = videoFileList.items();
System.out.println("Video Files:");
dumpItems(videoFiles, 1);
System.out.println();
MediaDiscoverer audioMediaDiscoverer = mediaPlayerFactory.newMediaDiscoverer("audio_dir");
Thread.sleep(500); // FIXME not acceptable
MediaList audioFileList = audioMediaDiscoverer.getMediaList();
// audioFileList.addMediaListEventListener(this);
List<MediaListItem> audioFiles = audioFileList.items();
System.out.println("Audio Files:");
dumpItems(audioFiles, 1);
System.out.println();
MediaDiscoverer pictureMediaDiscoverer = mediaPlayerFactory.newMediaDiscoverer("picture_dir");
Thread.sleep(500); // FIXME not acceptable
MediaList pictureFileList = pictureMediaDiscoverer.getMediaList();
// pictureFileList.addMediaListEventListener(this);
List<MediaListItem> pictureFiles = pictureFileList.items();
System.out.println("Picture Files:");
dumpItems(pictureFiles, 1);
System.out.println("DONE!");
Thread.currentThread().join();
}
| public MediaDirsTest() throws Exception {
MediaPlayerFactory mediaPlayerFactory = new MediaPlayerFactory();
MediaDiscoverer videoMediaDiscoverer = mediaPlayerFactory.newMediaDiscoverer("video_dir");
Thread.sleep(500); // FIXME not acceptable
MediaList videoFileList = videoMediaDiscoverer.getMediaList();
// videoFileList.addMediaListEventListener(this);
List<MediaListItem> videoFiles = videoFileList.items();
System.out.println("Video Files:");
dumpItems(videoFiles, 1);
System.out.println();
MediaDiscoverer audioMediaDiscoverer = mediaPlayerFactory.newMediaDiscoverer("audio_dir");
Thread.sleep(500); // FIXME not acceptable
MediaList audioFileList = audioMediaDiscoverer.getMediaList();
// audioFileList.addMediaListEventListener(this);
List<MediaListItem> audioFiles = audioFileList.items();
System.out.println("Audio Files:");
dumpItems(audioFiles, 1);
System.out.println();
MediaDiscoverer pictureMediaDiscoverer = mediaPlayerFactory.newMediaDiscoverer("picture_dir");
Thread.sleep(500); // FIXME not acceptable
MediaList pictureFileList = pictureMediaDiscoverer.getMediaList();
// pictureFileList.addMediaListEventListener(this);
List<MediaListItem> pictureFiles = pictureFileList.items();
System.out.println("Picture Files:");
dumpItems(pictureFiles, 1);
System.out.println("DONE!");
// Thread.currentThread().join();
System.exit(0);
}
|
diff --git a/src/org/eclipse/core/tests/filesystem/URIUtilTest.java b/src/org/eclipse/core/tests/filesystem/URIUtilTest.java
index 9468adc..61860ca 100644
--- a/src/org/eclipse/core/tests/filesystem/URIUtilTest.java
+++ b/src/org/eclipse/core/tests/filesystem/URIUtilTest.java
@@ -1,80 +1,85 @@
/*******************************************************************************
* Copyright (c) 2007 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.core.tests.filesystem;
import java.net.URI;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.eclipse.core.filesystem.EFS;
import org.eclipse.core.filesystem.URIUtil;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
/**
* Tests API methods of the class {@link org.eclipse.core.filesystem.URIUtil}.
*/
public class URIUtilTest extends FileSystemTest {
public static Test suite() {
return new TestSuite(URIUtilTest.class);
}
public URIUtilTest() {
super("");
}
public URIUtilTest(String name) {
super(name);
}
/**
* Tests API method {@link org.eclipse.core.filesystem.URIUtil#equals(java.net.URI, java.net.URI)}.
*/
public void testEquals() {
if (EFS.getLocalFileSystem().isCaseSensitive()) {
+ //test that case variants are not equal
+ URI one = new java.io.File("c:\\temp\\test").toURI();
+ URI two = new java.io.File("c:\\TEMP\\test").toURI();
+ assertTrue("1.0", !URIUtil.equals(one, two));
+ } else {
//test that case variants are equal
URI one = new java.io.File("c:\\temp\\test").toURI();
URI two = new java.io.File("c:\\TEMP\\test").toURI();
assertTrue("1.0", URIUtil.equals(one, two));
}
}
/**
* Tests API method {@link org.eclipse.core.filesystem.URIUtil#toURI(org.eclipse.core.runtime.IPath)}.
*/
public void testPathToURI() {
if (Platform.getOS().equals(Platform.OS_WIN32)) {
//path with spaces
assertEquals("1.0", "/c:/temp/with spaces", URIUtil.toURI("c:\\temp\\with spaces").getSchemeSpecificPart());
} else {
//path with spaces
assertEquals("2.0", "/tmp/with spaces", URIUtil.toURI("/tmp/with spaces").getSchemeSpecificPart());
}
}
/**
* Tests API method {@link org.eclipse.core.filesystem.URIUtil#toURI(String)}.
*/
public void testStringToURI() {
if (Platform.getOS().equals(Platform.OS_WIN32)) {
assertEquals("1.0", "/c:/temp/with spaces", URIUtil.toURI(new Path("c:\\temp\\with spaces")).getSchemeSpecificPart());
} else {
assertEquals("1.0", "/tmp/with spaces", URIUtil.toURI(new Path("/tmp/with spaces")).getSchemeSpecificPart());
}
}
/**
* Tests API method {@link org.eclipse.core.filesystem.URIUtil#toPath(java.net.URI)}.
*/
public void testToPath() {
//TODO
}
}
| true | true | public void testEquals() {
if (EFS.getLocalFileSystem().isCaseSensitive()) {
//test that case variants are equal
URI one = new java.io.File("c:\\temp\\test").toURI();
URI two = new java.io.File("c:\\TEMP\\test").toURI();
assertTrue("1.0", URIUtil.equals(one, two));
}
}
| public void testEquals() {
if (EFS.getLocalFileSystem().isCaseSensitive()) {
//test that case variants are not equal
URI one = new java.io.File("c:\\temp\\test").toURI();
URI two = new java.io.File("c:\\TEMP\\test").toURI();
assertTrue("1.0", !URIUtil.equals(one, two));
} else {
//test that case variants are equal
URI one = new java.io.File("c:\\temp\\test").toURI();
URI two = new java.io.File("c:\\TEMP\\test").toURI();
assertTrue("1.0", URIUtil.equals(one, two));
}
}
|
diff --git a/src/java/org/apache/bcel/generic/InstructionComparator.java b/src/java/org/apache/bcel/generic/InstructionComparator.java
index 115689c8..ac63370b 100644
--- a/src/java/org/apache/bcel/generic/InstructionComparator.java
+++ b/src/java/org/apache/bcel/generic/InstructionComparator.java
@@ -1,107 +1,107 @@
package org.apache.bcel.generic;
/* ====================================================================
* 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 "Apache" and "Apache Software Foundation" and
* "Apache BCEL" 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",
* "Apache BCEL", 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. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/**
* Equality of instructions isn't clearly to be defined. You might
* wish, for example, to compare whether instructions have the same
* meaning. E.g., whether two INVOKEVIRTUALs describe the same
* call.<br>The DEFAULT comparator however, considers two instructions
* to be equal if they have same opcode and point to the same indexes
* (if any) in the constant pool or the same local variable index. Branch
* instructions must have the same target.
*
* @see Instruction
* @version $Id$
* @author <A HREF="mailto:[email protected]">M. Dahm</A>
*/
public interface InstructionComparator {
public static final InstructionComparator DEFAULT =
new InstructionComparator() {
public boolean equals(Instruction i1, Instruction i2) {
if(i1.opcode == i2.opcode) {
if(i1 instanceof Select) {
InstructionHandle[] t1 = ((Select)i1).getTargets();
InstructionHandle[] t2 = ((Select)i2).getTargets();
if(t1.length == t2.length) {
for(int i = 0; i < t1.length; i++) {
if(t1[i] != t2[i]) {
return false;
}
}
return true;
}
} else if(i1 instanceof BranchInstruction) {
return ((BranchInstruction)i1).target ==
((BranchInstruction)i2).target;
} else if(i1 instanceof ConstantPushInstruction) {
return ((ConstantPushInstruction)i1).getValue().
equals(((ConstantPushInstruction)i2).getValue());
} else if(i1 instanceof IndexedInstruction) {
return ((IndexedInstruction)i1).getIndex() ==
((IndexedInstruction)i2).getIndex();
} else if(i1 instanceof NEWARRAY) {
- return ((NEWARRAY)i1).type == ((NEWARRAY)i2).type;
+ return ((NEWARRAY)i1).getTypecode() == ((NEWARRAY)i2).getTypecode();
}
}
return false;
}
};
public boolean equals(Instruction i1, Instruction i2);
}
| true | true | public boolean equals(Instruction i1, Instruction i2) {
if(i1.opcode == i2.opcode) {
if(i1 instanceof Select) {
InstructionHandle[] t1 = ((Select)i1).getTargets();
InstructionHandle[] t2 = ((Select)i2).getTargets();
if(t1.length == t2.length) {
for(int i = 0; i < t1.length; i++) {
if(t1[i] != t2[i]) {
return false;
}
}
return true;
}
} else if(i1 instanceof BranchInstruction) {
return ((BranchInstruction)i1).target ==
((BranchInstruction)i2).target;
} else if(i1 instanceof ConstantPushInstruction) {
return ((ConstantPushInstruction)i1).getValue().
equals(((ConstantPushInstruction)i2).getValue());
} else if(i1 instanceof IndexedInstruction) {
return ((IndexedInstruction)i1).getIndex() ==
((IndexedInstruction)i2).getIndex();
} else if(i1 instanceof NEWARRAY) {
return ((NEWARRAY)i1).type == ((NEWARRAY)i2).type;
}
}
return false;
}
| public boolean equals(Instruction i1, Instruction i2) {
if(i1.opcode == i2.opcode) {
if(i1 instanceof Select) {
InstructionHandle[] t1 = ((Select)i1).getTargets();
InstructionHandle[] t2 = ((Select)i2).getTargets();
if(t1.length == t2.length) {
for(int i = 0; i < t1.length; i++) {
if(t1[i] != t2[i]) {
return false;
}
}
return true;
}
} else if(i1 instanceof BranchInstruction) {
return ((BranchInstruction)i1).target ==
((BranchInstruction)i2).target;
} else if(i1 instanceof ConstantPushInstruction) {
return ((ConstantPushInstruction)i1).getValue().
equals(((ConstantPushInstruction)i2).getValue());
} else if(i1 instanceof IndexedInstruction) {
return ((IndexedInstruction)i1).getIndex() ==
((IndexedInstruction)i2).getIndex();
} else if(i1 instanceof NEWARRAY) {
return ((NEWARRAY)i1).getTypecode() == ((NEWARRAY)i2).getTypecode();
}
}
return false;
}
|
diff --git a/bte-io/src/main/java/gr/ekt/bteio/loaders/CSVDataLoader.java b/bte-io/src/main/java/gr/ekt/bteio/loaders/CSVDataLoader.java
index 232ec9b..c5a5cf7 100644
--- a/bte-io/src/main/java/gr/ekt/bteio/loaders/CSVDataLoader.java
+++ b/bte-io/src/main/java/gr/ekt/bteio/loaders/CSVDataLoader.java
@@ -1,216 +1,219 @@
/**
* Copyright (c) 2007-2013, National Documentation Centre (EKT, www.ekt.gr)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 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.
*
* Neither the name of the National Documentation Centre nor the
* names of its contributors may be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS 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 COPYRIGHT
* HOLDER OR 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.
*/
package gr.ekt.bteio.loaders;
import gr.ekt.bte.core.DataLoadingSpec;
import gr.ekt.bte.core.RecordSet;
import gr.ekt.bte.core.StringValue;
import gr.ekt.bte.dataloader.FileDataLoader;
import gr.ekt.bte.exceptions.EmptySourceException;
import gr.ekt.bte.exceptions.MalformedSourceException;
import gr.ekt.bte.record.MapRecord;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Map;
import org.apache.log4j.Logger;
import au.com.bytecode.opencsv.CSVReader;
public class CSVDataLoader extends FileDataLoader {
private static Logger logger_ = Logger.getLogger(CSVDataLoader.class);
private CSVReader reader_;
private Map<Integer, String> field_map_;
private int skip_lines_ = 0;
private char separator_ = ',';
private char quote_char_ = '"';
private String value_separator_ = null;
public CSVDataLoader() {
super();
reader_ = null;
field_map_ = null;
}
public CSVDataLoader(String filename, Map<Integer, String> fields) throws EmptySourceException {
super(filename);
field_map_ = fields;
openReader();
}
public CSVDataLoader(String filename, Map<Integer, String> fields, char separator, char quote_char, int skip_lines, String value_separator) throws EmptySourceException {
super(filename);
field_map_ = fields;
separator_ = separator;
quote_char_ = quote_char;
skip_lines_ = skip_lines;
value_separator_ = value_separator;
openReader();
}
@Override
public RecordSet getRecords() throws MalformedSourceException {
if (reader_ == null) {
throw new EmptySourceException("Input file is not open");
}
RecordSet rs = null;
try {
String [] next_line;
rs = new RecordSet();
while((next_line = reader_.readNext()) != null) {
MapRecord rec = new MapRecord();
for(Map.Entry<Integer,String> en : field_map_.entrySet()) {
int i = en.getKey();
+ if (next_line.length <= i) {
+ throw new MalformedSourceException("The requested column " + i + " does not exist");
+ }
if (value_separator_ != null) {
String values[] = next_line[i].split(value_separator_);
for(int j = 0; j < values.length; j++) {
rec.addValue(field_map_.get(i), new StringValue(values[j]));
}
}
else {
rec.addValue(field_map_.get(i), new StringValue(next_line[i]));
}
}
rs.addRecord(rec);
}
} catch(IOException e) {
logger_.info(e.getMessage());
throw new MalformedSourceException("");
}
return rs;
}
@Override
public RecordSet getRecords(DataLoadingSpec spec) throws MalformedSourceException {
//Not using the DataLoadingSpec for the moment
return getRecords();
}
@Override
protected void finalize() throws Throwable {
reader_.close();
}
private void openReader() throws EmptySourceException {
try {
reader_ = new CSVReader(new FileReader(filename), separator_, quote_char_, skip_lines_);
} catch (FileNotFoundException e) {
throw new EmptySourceException("File " + filename + " not found");
}
}
@Override
public void setFilename(String filename) {
this.filename = filename;
try {
openReader();
} catch (EmptySourceException e) {
logger_.info("Could not open file " + filename);
reader_ = null;
}
}
/**
* @return the fields_
*/
public Map<Integer, String> getFieldMap() {
return field_map_;
}
/**
* @param fields_ the fields_ to set
*/
public void setFieldMap(Map<Integer, String> fields_) {
this.field_map_ = fields_;
}
/**
* @return the skip_lines_
*/
public int getSkipLines() {
return skip_lines_;
}
/**
* @param skip_lines_ the skip_lines_ to set
*/
public void setSkipLines(int skip_lines_) {
this.skip_lines_ = skip_lines_;
}
/**
* @return the separator_
*/
public char getSeparator() {
return separator_;
}
/**
* @param separator_ the separator_ to set
*/
public void setSeparator(char separator_) {
this.separator_ = separator_;
}
/**
* @return the quote_char_
*/
public char getQuoteChar() {
return quote_char_;
}
/**
* @param quote_char_ the quote_char_ to set
*/
public void setQuoteChar(char quote_char_) {
this.quote_char_ = quote_char_;
}
/**
* @return the value_separator_
*/
public String getValueSeparator() {
return value_separator_;
}
/**
* @param value_separator_ the value_separator_ to set
*/
public void setValueSeparator(String value_separator_) {
this.value_separator_ = value_separator_;
}
}
| true | true | public RecordSet getRecords() throws MalformedSourceException {
if (reader_ == null) {
throw new EmptySourceException("Input file is not open");
}
RecordSet rs = null;
try {
String [] next_line;
rs = new RecordSet();
while((next_line = reader_.readNext()) != null) {
MapRecord rec = new MapRecord();
for(Map.Entry<Integer,String> en : field_map_.entrySet()) {
int i = en.getKey();
if (value_separator_ != null) {
String values[] = next_line[i].split(value_separator_);
for(int j = 0; j < values.length; j++) {
rec.addValue(field_map_.get(i), new StringValue(values[j]));
}
}
else {
rec.addValue(field_map_.get(i), new StringValue(next_line[i]));
}
}
rs.addRecord(rec);
}
} catch(IOException e) {
logger_.info(e.getMessage());
throw new MalformedSourceException("");
}
return rs;
}
| public RecordSet getRecords() throws MalformedSourceException {
if (reader_ == null) {
throw new EmptySourceException("Input file is not open");
}
RecordSet rs = null;
try {
String [] next_line;
rs = new RecordSet();
while((next_line = reader_.readNext()) != null) {
MapRecord rec = new MapRecord();
for(Map.Entry<Integer,String> en : field_map_.entrySet()) {
int i = en.getKey();
if (next_line.length <= i) {
throw new MalformedSourceException("The requested column " + i + " does not exist");
}
if (value_separator_ != null) {
String values[] = next_line[i].split(value_separator_);
for(int j = 0; j < values.length; j++) {
rec.addValue(field_map_.get(i), new StringValue(values[j]));
}
}
else {
rec.addValue(field_map_.get(i), new StringValue(next_line[i]));
}
}
rs.addRecord(rec);
}
} catch(IOException e) {
logger_.info(e.getMessage());
throw new MalformedSourceException("");
}
return rs;
}
|
diff --git a/gdx/src/com/badlogic/gdx/assets/loaders/TextureLoader.java b/gdx/src/com/badlogic/gdx/assets/loaders/TextureLoader.java
index f4df20cbd..6112737a1 100644
--- a/gdx/src/com/badlogic/gdx/assets/loaders/TextureLoader.java
+++ b/gdx/src/com/badlogic/gdx/assets/loaders/TextureLoader.java
@@ -1,120 +1,120 @@
/*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* 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.badlogic.gdx.assets.loaders;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.assets.AssetDescriptor;
import com.badlogic.gdx.assets.AssetLoaderParameters;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.Pixmap.Format;
import com.badlogic.gdx.graphics.PixmapIO;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.Texture.TextureFilter;
import com.badlogic.gdx.graphics.Texture.TextureWrap;
import com.badlogic.gdx.graphics.TextureData;
import com.badlogic.gdx.graphics.glutils.ETC1TextureData;
import com.badlogic.gdx.graphics.glutils.FileTextureData;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.ObjectMap;
/** {@link AssetLoader} for {@link Texture} instances. The pixel data is loaded asynchronously. The texture is then created on the
* rendering thread, synchronously. Passing a {@link TextureParameter} to
* {@link AssetManager#load(String, Class, AssetLoaderParameters)} allows one to specify parameters as can be passed to the
* various Texture constructors, e.g. filtering, whether to generate mipmaps and so on.
* @author mzechner */
public class TextureLoader extends AsynchronousAssetLoader<Texture, TextureLoader.TextureParameter> {
static public class TextureLoaderInfo {
String filename;
TextureData data;
Texture texture;
};
TextureLoaderInfo info = new TextureLoaderInfo();
public TextureLoader (FileHandleResolver resolver) {
super(resolver);
}
@Override
public void loadAsync (AssetManager manager, String fileName, FileHandle file, TextureParameter parameter) {
info.filename = fileName;
if (parameter == null || parameter.textureData == null) {
Pixmap pixmap = null;
Format format = null;
boolean genMipMaps = false;
info.texture = null;
if (parameter != null) {
format = parameter.format;
genMipMaps = parameter.genMipMaps;
info.texture = parameter.texture;
}
if (!fileName.contains(".etc1")) {
if (fileName.contains(".cim"))
pixmap = PixmapIO.readCIM(file);
else
pixmap = new Pixmap(file);
info.data = new FileTextureData(file, pixmap, format, genMipMaps);
} else {
info.data = new ETC1TextureData(file, genMipMaps);
}
} else {
info.data = parameter.textureData;
- if (!info.data.isPrepared()) info.data.prepare();
info.texture = parameter.texture;
}
+ if (!info.data.isPrepared()) info.data.prepare();
}
@Override
public Texture loadSync (AssetManager manager, String fileName, FileHandle file, TextureParameter parameter) {
if (info == null)
return null;
Texture texture = info.texture;
if (texture != null) {
texture.load(info.data);
} else {
texture = new Texture(info.data);
}
if (parameter != null) {
texture.setFilter(parameter.minFilter, parameter.magFilter);
texture.setWrap(parameter.wrapU, parameter.wrapV);
}
return texture;
}
@Override
public Array<AssetDescriptor> getDependencies (String fileName, FileHandle file, TextureParameter parameter) {
return null;
}
static public class TextureParameter extends AssetLoaderParameters<Texture> {
/** the format of the final Texture. Uses the source images format if null **/
public Format format = null;
/** whether to generate mipmaps **/
public boolean genMipMaps = false;
/** The texture to put the {@link TextureData} in, optional. **/
public Texture texture = null;
/** TextureData for textures created on the fly, optional. When set, all format and genMipMaps are ignored */
public TextureData textureData = null;
public TextureFilter minFilter = TextureFilter.Nearest;
public TextureFilter magFilter = TextureFilter.Nearest;
public TextureWrap wrapU = TextureWrap.ClampToEdge;
public TextureWrap wrapV = TextureWrap.ClampToEdge;
}
}
| false | true | public void loadAsync (AssetManager manager, String fileName, FileHandle file, TextureParameter parameter) {
info.filename = fileName;
if (parameter == null || parameter.textureData == null) {
Pixmap pixmap = null;
Format format = null;
boolean genMipMaps = false;
info.texture = null;
if (parameter != null) {
format = parameter.format;
genMipMaps = parameter.genMipMaps;
info.texture = parameter.texture;
}
if (!fileName.contains(".etc1")) {
if (fileName.contains(".cim"))
pixmap = PixmapIO.readCIM(file);
else
pixmap = new Pixmap(file);
info.data = new FileTextureData(file, pixmap, format, genMipMaps);
} else {
info.data = new ETC1TextureData(file, genMipMaps);
}
} else {
info.data = parameter.textureData;
if (!info.data.isPrepared()) info.data.prepare();
info.texture = parameter.texture;
}
}
| public void loadAsync (AssetManager manager, String fileName, FileHandle file, TextureParameter parameter) {
info.filename = fileName;
if (parameter == null || parameter.textureData == null) {
Pixmap pixmap = null;
Format format = null;
boolean genMipMaps = false;
info.texture = null;
if (parameter != null) {
format = parameter.format;
genMipMaps = parameter.genMipMaps;
info.texture = parameter.texture;
}
if (!fileName.contains(".etc1")) {
if (fileName.contains(".cim"))
pixmap = PixmapIO.readCIM(file);
else
pixmap = new Pixmap(file);
info.data = new FileTextureData(file, pixmap, format, genMipMaps);
} else {
info.data = new ETC1TextureData(file, genMipMaps);
}
} else {
info.data = parameter.textureData;
info.texture = parameter.texture;
}
if (!info.data.isPrepared()) info.data.prepare();
}
|
diff --git a/examples/rest-assured-itest-java/src/test/java/com/jayway/restassured/itest/java/GivenWhenTheni18nITest.java b/examples/rest-assured-itest-java/src/test/java/com/jayway/restassured/itest/java/GivenWhenTheni18nITest.java
index 7697be8d..d8aa168c 100644
--- a/examples/rest-assured-itest-java/src/test/java/com/jayway/restassured/itest/java/GivenWhenTheni18nITest.java
+++ b/examples/rest-assured-itest-java/src/test/java/com/jayway/restassured/itest/java/GivenWhenTheni18nITest.java
@@ -1,33 +1,32 @@
/*
* Copyright 2013 the original author or authors.
*
* 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.jayway.restassured.itest.java;
import com.jayway.restassured.itest.java.support.WithJetty;
import org.junit.Test;
import static com.jayway.restassured.RestAssured.get;
import static org.hamcrest.Matchers.equalTo;
public class GivenWhenTheni18nITest extends WithJetty {
@Test public void
given_when_then_using_i18n_works() {
- // When
get("/i18n").then().assertThat().body("ön", equalTo("Är ån"));
}
}
| true | true | @Test public void
given_when_then_using_i18n_works() {
// When
get("/i18n").then().assertThat().body("ön", equalTo("Är ån"));
}
| @Test public void
given_when_then_using_i18n_works() {
get("/i18n").then().assertThat().body("ön", equalTo("Är ån"));
}
|
diff --git a/src/com/android/contacts/socialwidget/SocialWidgetProvider.java b/src/com/android/contacts/socialwidget/SocialWidgetProvider.java
index 2ce15ff79..593c4b217 100644
--- a/src/com/android/contacts/socialwidget/SocialWidgetProvider.java
+++ b/src/com/android/contacts/socialwidget/SocialWidgetProvider.java
@@ -1,235 +1,238 @@
/*
* Copyright (C) 2010 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.contacts.socialwidget;
import com.android.contacts.ContactLoader;
import com.android.contacts.R;
import com.android.contacts.model.AccountType;
import com.android.contacts.model.AccountTypeManager;
import com.android.contacts.util.ContactBadgeUtil;
import com.android.contacts.util.HtmlUtils;
import com.android.contacts.util.StreamItemEntry;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.Loader;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.net.Uri;
import android.provider.ContactsContract.QuickContact;
import android.provider.ContactsContract.StreamItems;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.StyleSpan;
import android.util.Log;
import android.util.SparseArray;
import android.view.View;
import android.widget.RemoteViews;
import java.util.List;
public class SocialWidgetProvider extends AppWidgetProvider {
private static final String TAG = "SocialWidgetProvider";
/**
* Max length of a snippet that is considered "short" and displayed in
* a separate line.
*/
private static final int SHORT_SNIPPET_LENGTH = 48;
private static SparseArray<ContactLoader> sLoaders = new SparseArray<ContactLoader>();
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
for (int appWidgetId : appWidgetIds) {
Log.d(TAG, "onUpdate called for " + appWidgetId);
}
for (int appWidgetId : appWidgetIds) {
loadWidgetData(context, appWidgetManager, appWidgetId, false);
}
}
@Override
public void onDeleted(Context context, int[] appWidgetIds) {
for (int appWidgetId : appWidgetIds) {
ContactLoader loader = sLoaders.get(appWidgetId);
if (loader != null) {
Log.d(TAG, "Stopping loader for widget with id=" + appWidgetId);
loader.stopLoading();
sLoaders.delete(appWidgetId);
}
}
SocialWidgetSettings.getInstance().remove(context, appWidgetIds);
}
public static void loadWidgetData(final Context context,
final AppWidgetManager appWidgetManager, final int widgetId, boolean forceLoad) {
ContactLoader previousLoader = sLoaders.get(widgetId);
if (previousLoader != null && !forceLoad) {
previousLoader.startLoading();
return;
}
if (previousLoader != null) {
previousLoader.reset();
}
// Show that we are loading
final RemoteViews loadingViews =
new RemoteViews(context.getPackageName(), R.layout.social_widget);
loadingViews.setTextViewText(R.id.name,
context.getString(R.string.social_widget_loading));
loadingViews.setViewVisibility(R.id.name, View.VISIBLE);
loadingViews.setViewVisibility(R.id.name_and_snippet, View.GONE);
appWidgetManager.updateAppWidget(widgetId, loadingViews);
// Load
final Uri contactUri =
SocialWidgetSettings.getInstance().getContactUri(context, widgetId);
if (contactUri == null) {
// Not yet set-up (this can happen while the Configuration activity is visible)
return;
}
final ContactLoader contactLoader = new ContactLoader(context, contactUri, false, true,
false);
contactLoader.registerListener(0,
new ContactLoader.OnLoadCompleteListener<ContactLoader.Result>() {
@Override
public void onLoadComplete(Loader<ContactLoader.Result> loader,
ContactLoader.Result contactData) {
bindRemoteViews(context, widgetId, appWidgetManager, contactData);
}
});
contactLoader.startLoading();
sLoaders.append(widgetId, contactLoader);
}
private static void bindRemoteViews(final Context context, final int widgetId,
final AppWidgetManager widgetManager, ContactLoader.Result contactData) {
Log.d(TAG, "Loaded " + contactData.getLookupKey()
+ " for widget with id=" + widgetId);
final RemoteViews views = new RemoteViews(context.getPackageName(),
R.layout.social_widget);
if (!contactData.isLoaded()) {
setDisplayNameAndSnippet(context, views,
context.getString(R.string.invalidContactMessage), null, null, null);
setPhoto(views, ContactBadgeUtil.loadDefaultAvatarPhoto(context, false, false));
} else {
byte[] photo = contactData.getPhotoBinaryData();
setPhoto(views, photo != null
? BitmapFactory.decodeByteArray(photo, 0, photo.length)
: ContactBadgeUtil.loadDefaultAvatarPhoto(context, false, false));
// TODO: Rotate between all the stream items?
// OnClick launch QuickContact
final Intent intent = new Intent(QuickContact.ACTION_QUICK_CONTACT);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
intent.setData(contactData.getLookupUri());
intent.putExtra(QuickContact.EXTRA_MODE, QuickContact.MODE_SMALL);
final PendingIntent pendingIntent = PendingIntent.getActivity(context,
0, intent, 0);
views.setOnClickPendingIntent(R.id.border, pendingIntent);
setDisplayNameAndSnippet(context, views, contactData.getDisplayName(),
contactData.getPhoneticName(), contactData.getStreamItems(), pendingIntent);
}
// Configure UI
widgetManager.updateAppWidget(widgetId, views);
}
private static void setPhoto(RemoteViews views, Bitmap photo) {
views.setImageViewBitmap(R.id.image, photo);
}
/**
* Set the display name, phonetic name and the social snippet.
*/
private static void setDisplayNameAndSnippet(Context context, RemoteViews views,
CharSequence displayName, CharSequence phoneticName,
List<StreamItemEntry> streamItems, PendingIntent defaultIntent) {
SpannableStringBuilder sb = new SpannableStringBuilder();
CharSequence name = displayName;
// If there is no display name, use the default missing name string
if (TextUtils.isEmpty(name)) {
name = context.getString(R.string.missing_name);
}
if (!TextUtils.isEmpty(phoneticName)) {
name = context.getString(R.string.widget_name_and_phonetic,
name, phoneticName);
}
sb.append(name);
AbsoluteSizeSpan sizeSpan = new AbsoluteSizeSpan(
context.getResources().getDimensionPixelSize(R.dimen.widget_text_size_name));
StyleSpan styleSpan = new StyleSpan(Typeface.BOLD);
sb.setSpan(sizeSpan, 0, name.length(), 0);
sb.setSpan(styleSpan, 0, name.length(), 0);
if (streamItems == null || streamItems.isEmpty()) {
views.setTextViewText(R.id.name, sb);
views.setViewVisibility(R.id.name, View.VISIBLE);
views.setViewVisibility(R.id.name_and_snippet, View.GONE);
// Don't set a pending intent if the intent is null, otherwise the system will try
// to write the null intent to a Parcel.
if (defaultIntent != null) {
views.setOnClickPendingIntent(R.id.widget_container, defaultIntent);
}
} else {
// TODO: Rotate between all the stream items?
StreamItemEntry streamItem = streamItems.get(0);
CharSequence status = HtmlUtils.fromHtml(context, streamItem.getText());
+ if (status == null) {
+ status = "";
+ }
if (status.length() <= SHORT_SNIPPET_LENGTH) {
sb.append("\n");
} else {
sb.append(" ");
}
sb.append(status);
views.setTextViewText(R.id.name_and_snippet, sb);
views.setViewVisibility(R.id.name, View.GONE);
views.setViewVisibility(R.id.name_and_snippet, View.VISIBLE);
final AccountTypeManager manager = AccountTypeManager.getInstance(context);
final AccountType accountType =
manager.getAccountType(streamItem.getAccountType(), streamItem.getDataSet());
if (accountType.getViewStreamItemActivity() != null) {
final Uri uri = ContentUris.withAppendedId(StreamItems.CONTENT_URI,
streamItem.getId());
final Intent intent = new Intent(Intent.ACTION_VIEW, uri);
intent.setClassName(accountType.resPackageName,
accountType.getViewStreamItemActivity());
views.setOnClickPendingIntent(R.id.name_and_snippet_container,
PendingIntent.getActivity(context, 0, intent, 0));
}
}
}
}
| true | true | private static void setDisplayNameAndSnippet(Context context, RemoteViews views,
CharSequence displayName, CharSequence phoneticName,
List<StreamItemEntry> streamItems, PendingIntent defaultIntent) {
SpannableStringBuilder sb = new SpannableStringBuilder();
CharSequence name = displayName;
// If there is no display name, use the default missing name string
if (TextUtils.isEmpty(name)) {
name = context.getString(R.string.missing_name);
}
if (!TextUtils.isEmpty(phoneticName)) {
name = context.getString(R.string.widget_name_and_phonetic,
name, phoneticName);
}
sb.append(name);
AbsoluteSizeSpan sizeSpan = new AbsoluteSizeSpan(
context.getResources().getDimensionPixelSize(R.dimen.widget_text_size_name));
StyleSpan styleSpan = new StyleSpan(Typeface.BOLD);
sb.setSpan(sizeSpan, 0, name.length(), 0);
sb.setSpan(styleSpan, 0, name.length(), 0);
if (streamItems == null || streamItems.isEmpty()) {
views.setTextViewText(R.id.name, sb);
views.setViewVisibility(R.id.name, View.VISIBLE);
views.setViewVisibility(R.id.name_and_snippet, View.GONE);
// Don't set a pending intent if the intent is null, otherwise the system will try
// to write the null intent to a Parcel.
if (defaultIntent != null) {
views.setOnClickPendingIntent(R.id.widget_container, defaultIntent);
}
} else {
// TODO: Rotate between all the stream items?
StreamItemEntry streamItem = streamItems.get(0);
CharSequence status = HtmlUtils.fromHtml(context, streamItem.getText());
if (status.length() <= SHORT_SNIPPET_LENGTH) {
sb.append("\n");
} else {
sb.append(" ");
}
sb.append(status);
views.setTextViewText(R.id.name_and_snippet, sb);
views.setViewVisibility(R.id.name, View.GONE);
views.setViewVisibility(R.id.name_and_snippet, View.VISIBLE);
final AccountTypeManager manager = AccountTypeManager.getInstance(context);
final AccountType accountType =
manager.getAccountType(streamItem.getAccountType(), streamItem.getDataSet());
if (accountType.getViewStreamItemActivity() != null) {
final Uri uri = ContentUris.withAppendedId(StreamItems.CONTENT_URI,
streamItem.getId());
final Intent intent = new Intent(Intent.ACTION_VIEW, uri);
intent.setClassName(accountType.resPackageName,
accountType.getViewStreamItemActivity());
views.setOnClickPendingIntent(R.id.name_and_snippet_container,
PendingIntent.getActivity(context, 0, intent, 0));
}
}
}
| private static void setDisplayNameAndSnippet(Context context, RemoteViews views,
CharSequence displayName, CharSequence phoneticName,
List<StreamItemEntry> streamItems, PendingIntent defaultIntent) {
SpannableStringBuilder sb = new SpannableStringBuilder();
CharSequence name = displayName;
// If there is no display name, use the default missing name string
if (TextUtils.isEmpty(name)) {
name = context.getString(R.string.missing_name);
}
if (!TextUtils.isEmpty(phoneticName)) {
name = context.getString(R.string.widget_name_and_phonetic,
name, phoneticName);
}
sb.append(name);
AbsoluteSizeSpan sizeSpan = new AbsoluteSizeSpan(
context.getResources().getDimensionPixelSize(R.dimen.widget_text_size_name));
StyleSpan styleSpan = new StyleSpan(Typeface.BOLD);
sb.setSpan(sizeSpan, 0, name.length(), 0);
sb.setSpan(styleSpan, 0, name.length(), 0);
if (streamItems == null || streamItems.isEmpty()) {
views.setTextViewText(R.id.name, sb);
views.setViewVisibility(R.id.name, View.VISIBLE);
views.setViewVisibility(R.id.name_and_snippet, View.GONE);
// Don't set a pending intent if the intent is null, otherwise the system will try
// to write the null intent to a Parcel.
if (defaultIntent != null) {
views.setOnClickPendingIntent(R.id.widget_container, defaultIntent);
}
} else {
// TODO: Rotate between all the stream items?
StreamItemEntry streamItem = streamItems.get(0);
CharSequence status = HtmlUtils.fromHtml(context, streamItem.getText());
if (status == null) {
status = "";
}
if (status.length() <= SHORT_SNIPPET_LENGTH) {
sb.append("\n");
} else {
sb.append(" ");
}
sb.append(status);
views.setTextViewText(R.id.name_and_snippet, sb);
views.setViewVisibility(R.id.name, View.GONE);
views.setViewVisibility(R.id.name_and_snippet, View.VISIBLE);
final AccountTypeManager manager = AccountTypeManager.getInstance(context);
final AccountType accountType =
manager.getAccountType(streamItem.getAccountType(), streamItem.getDataSet());
if (accountType.getViewStreamItemActivity() != null) {
final Uri uri = ContentUris.withAppendedId(StreamItems.CONTENT_URI,
streamItem.getId());
final Intent intent = new Intent(Intent.ACTION_VIEW, uri);
intent.setClassName(accountType.resPackageName,
accountType.getViewStreamItemActivity());
views.setOnClickPendingIntent(R.id.name_and_snippet_container,
PendingIntent.getActivity(context, 0, intent, 0));
}
}
}
|
diff --git a/PaintroidTest/src/org/catrobat/paintroid/test/junit/tools/MoveZoomTest.java b/PaintroidTest/src/org/catrobat/paintroid/test/junit/tools/MoveZoomTest.java
index dd58af67..3820c503 100644
--- a/PaintroidTest/src/org/catrobat/paintroid/test/junit/tools/MoveZoomTest.java
+++ b/PaintroidTest/src/org/catrobat/paintroid/test/junit/tools/MoveZoomTest.java
@@ -1,49 +1,49 @@
package org.catrobat.paintroid.test.junit.tools;
import org.catrobat.paintroid.PaintroidApplication;
import org.catrobat.paintroid.test.utils.PrivateAccess;
import org.catrobat.paintroid.tools.Tool.ToolType;
import org.catrobat.paintroid.tools.implementation.MoveZoomTool;
import org.catrobat.paintroid.ui.implementation.PerspectiveImplementation;
import org.junit.Before;
import android.graphics.PointF;
public class MoveZoomTest extends BaseToolTest {
@Override
@Before
protected void setUp() throws Exception {
mToolToTest = new MoveZoomTool(getActivity(), ToolType.MOVE);
super.setUp();
}
public void testMove() throws SecurityException, IllegalArgumentException, NoSuchFieldException,
IllegalAccessException {
float screenWidth = getActivity().getWindowManager().getDefaultDisplay().getWidth();
float screenHeight = getActivity().getWindowManager().getDefaultDisplay().getHeight();
int offset = 50;
- PointF fromPoint = new PointF(screenWidth / 2, screenHeight);
+ PointF fromPoint = new PointF(screenWidth / 2, screenHeight / 2);
PointF toPoint = new PointF(fromPoint.x + offset, fromPoint.y + offset);
float translationXBefore = (Float) PrivateAccess.getMemberValue(PerspectiveImplementation.class,
PaintroidApplication.CURRENT_PERSPECTIVE, "mSurfaceTranslationX");
float translationYBefore = (Float) PrivateAccess.getMemberValue(PerspectiveImplementation.class,
PaintroidApplication.CURRENT_PERSPECTIVE, "mSurfaceTranslationY");
mToolToTest.handleDown(fromPoint);
mToolToTest.handleMove(toPoint);
float translationXAfter = (Float) PrivateAccess.getMemberValue(PerspectiveImplementation.class,
PaintroidApplication.CURRENT_PERSPECTIVE, "mSurfaceTranslationX");
float translationYAfter = (Float) PrivateAccess.getMemberValue(PerspectiveImplementation.class,
PaintroidApplication.CURRENT_PERSPECTIVE, "mSurfaceTranslationY");
assertEquals("translation of X should be the offset", translationXAfter - offset, translationXBefore);
assertEquals("translation of Y should be the offset", translationYAfter - offset, translationYBefore);
}
}
| true | true | public void testMove() throws SecurityException, IllegalArgumentException, NoSuchFieldException,
IllegalAccessException {
float screenWidth = getActivity().getWindowManager().getDefaultDisplay().getWidth();
float screenHeight = getActivity().getWindowManager().getDefaultDisplay().getHeight();
int offset = 50;
PointF fromPoint = new PointF(screenWidth / 2, screenHeight);
PointF toPoint = new PointF(fromPoint.x + offset, fromPoint.y + offset);
float translationXBefore = (Float) PrivateAccess.getMemberValue(PerspectiveImplementation.class,
PaintroidApplication.CURRENT_PERSPECTIVE, "mSurfaceTranslationX");
float translationYBefore = (Float) PrivateAccess.getMemberValue(PerspectiveImplementation.class,
PaintroidApplication.CURRENT_PERSPECTIVE, "mSurfaceTranslationY");
mToolToTest.handleDown(fromPoint);
mToolToTest.handleMove(toPoint);
float translationXAfter = (Float) PrivateAccess.getMemberValue(PerspectiveImplementation.class,
PaintroidApplication.CURRENT_PERSPECTIVE, "mSurfaceTranslationX");
float translationYAfter = (Float) PrivateAccess.getMemberValue(PerspectiveImplementation.class,
PaintroidApplication.CURRENT_PERSPECTIVE, "mSurfaceTranslationY");
assertEquals("translation of X should be the offset", translationXAfter - offset, translationXBefore);
assertEquals("translation of Y should be the offset", translationYAfter - offset, translationYBefore);
}
| public void testMove() throws SecurityException, IllegalArgumentException, NoSuchFieldException,
IllegalAccessException {
float screenWidth = getActivity().getWindowManager().getDefaultDisplay().getWidth();
float screenHeight = getActivity().getWindowManager().getDefaultDisplay().getHeight();
int offset = 50;
PointF fromPoint = new PointF(screenWidth / 2, screenHeight / 2);
PointF toPoint = new PointF(fromPoint.x + offset, fromPoint.y + offset);
float translationXBefore = (Float) PrivateAccess.getMemberValue(PerspectiveImplementation.class,
PaintroidApplication.CURRENT_PERSPECTIVE, "mSurfaceTranslationX");
float translationYBefore = (Float) PrivateAccess.getMemberValue(PerspectiveImplementation.class,
PaintroidApplication.CURRENT_PERSPECTIVE, "mSurfaceTranslationY");
mToolToTest.handleDown(fromPoint);
mToolToTest.handleMove(toPoint);
float translationXAfter = (Float) PrivateAccess.getMemberValue(PerspectiveImplementation.class,
PaintroidApplication.CURRENT_PERSPECTIVE, "mSurfaceTranslationX");
float translationYAfter = (Float) PrivateAccess.getMemberValue(PerspectiveImplementation.class,
PaintroidApplication.CURRENT_PERSPECTIVE, "mSurfaceTranslationY");
assertEquals("translation of X should be the offset", translationXAfter - offset, translationXBefore);
assertEquals("translation of Y should be the offset", translationYAfter - offset, translationYBefore);
}
|
diff --git a/bw-calendar-client-webcommon/src/main/java/org/bedework/webcommon/category/FetchCategoriesAction.java b/bw-calendar-client-webcommon/src/main/java/org/bedework/webcommon/category/FetchCategoriesAction.java
index a59a6bb..8db0817 100644
--- a/bw-calendar-client-webcommon/src/main/java/org/bedework/webcommon/category/FetchCategoriesAction.java
+++ b/bw-calendar-client-webcommon/src/main/java/org/bedework/webcommon/category/FetchCategoriesAction.java
@@ -1,43 +1,43 @@
/* ********************************************************************
Licensed to Jasig under one or more contributor license
agreements. See the NOTICE file distributed with this work
for additional information regarding copyright ownership.
Jasig 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.bedework.webcommon.category;
import org.bedework.webcommon.BwAbstractAction;
import org.bedework.webcommon.BwActionFormBase;
import org.bedework.webcommon.BwRequest;
/** This action fetches all categories and embeds them in the session.
*
* <p>Forwards to:<ul>
* <li>"success" ok.</li>
* </ul>
*
* @author Mike Douglass [email protected]
*/
public class FetchCategoriesAction extends BwAbstractAction {
/* (non-Javadoc)
* @see org.bedework.webcommon.BwAbstractAction#doAction(org.bedework.webcommon.BwRequest, org.bedework.webcommon.BwActionFormBase)
*/
public int doAction(BwRequest request,
BwActionFormBase form) throws Throwable {
- embedCategories(request, false);
+ embedEditableCategories(request, false);
return forwardSuccess;
}
}
| true | true | public int doAction(BwRequest request,
BwActionFormBase form) throws Throwable {
embedCategories(request, false);
return forwardSuccess;
}
| public int doAction(BwRequest request,
BwActionFormBase form) throws Throwable {
embedEditableCategories(request, false);
return forwardSuccess;
}
|
diff --git a/src/main/java/com/mtihc/regionselfservice/v2/plots/PlotWorld.java b/src/main/java/com/mtihc/regionselfservice/v2/plots/PlotWorld.java
index 8554365..8d515a7 100644
--- a/src/main/java/com/mtihc/regionselfservice/v2/plots/PlotWorld.java
+++ b/src/main/java/com/mtihc/regionselfservice/v2/plots/PlotWorld.java
@@ -1,83 +1,84 @@
package com.mtihc.regionselfservice.v2.plots;
import java.util.HashSet;
import java.util.Set;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.block.Sign;
import com.mtihc.regionselfservice.v2.plots.exceptions.SignException;
import com.mtihc.regionselfservice.v2.plots.signs.PlotSignType;
import com.sk89q.worldguard.protection.managers.RegionManager;
public class PlotWorld {
protected final PlotManager manager;
protected final String worldName;
protected final IPlotWorldConfig config;
protected final IPlotDataRepository plots;
protected final RegionManager regionManager;
public PlotWorld(PlotManager manager, World world, IPlotWorldConfig config, IPlotDataRepository plots) {
this.manager = manager;
this.worldName = world.getName();
this.config = config;
this.plots = plots;
this.regionManager = manager.getWorldGuard().getRegionManager(world);
}
public String getName() {
return worldName;
}
public World getWorld() {
return Bukkit.getWorld(worldName);
}
public IPlotWorldConfig getConfig() {
return config;
}
public PlotManager getPlotManager() {
return manager;
}
public IPlotDataRepository getPlotData() {
return plots;
}
public Plot getPlot(String regionId) {
PlotData data = plots.get(regionId);
if(data == null) {
data = new PlotData(regionId, 0, 0);
}
return createPlot(data);
}
public Plot getPlot(Sign sign) throws SignException {
String regionId = PlotSignType.getRegionId(sign, sign.getLines());
return getPlot(regionId);
}
protected Plot createPlot(PlotData data) {
return new Plot(this, data);
}
public RegionManager getRegionManager() {
return regionManager;
}
public Set<String> getPotentialHomeless(Set<String> names) {
Set<String> result = new HashSet<String>();
World world = getWorld();
for (String name : names) {
int count = manager.control.getRegionCountOfPlayer(world, name);
if(count - 1 <= 0) {
result.add(name);
}
}
+ return result;
}
}
| true | true | public Set<String> getPotentialHomeless(Set<String> names) {
Set<String> result = new HashSet<String>();
World world = getWorld();
for (String name : names) {
int count = manager.control.getRegionCountOfPlayer(world, name);
if(count - 1 <= 0) {
result.add(name);
}
}
}
| public Set<String> getPotentialHomeless(Set<String> names) {
Set<String> result = new HashSet<String>();
World world = getWorld();
for (String name : names) {
int count = manager.control.getRegionCountOfPlayer(world, name);
if(count - 1 <= 0) {
result.add(name);
}
}
return result;
}
|
diff --git a/src/com/finalyear/controlrobot/MainActivity.java b/src/com/finalyear/controlrobot/MainActivity.java
index b231d7b..e999acd 100644
--- a/src/com/finalyear/controlrobot/MainActivity.java
+++ b/src/com/finalyear/controlrobot/MainActivity.java
@@ -1,300 +1,302 @@
package com.finalyear.controlrobot;
import java.util.ArrayList;
import com.example.controlrobot.R;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import at.abraxas.amarino.Amarino;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
public class MainActivity extends Activity {
private static final String DEVICE_ADDRESS = "00:12:12:04:32:51";
ImageButton forward;
ImageButton left;
ImageButton right;
ImageButton backward;
TextView Display1;
TextView Display2;
TextView Display3;
TextView Display4;
TextView Display5;
TextView Display6;
TextView Display7;
TextView Display8;
TextView Display9;
TextView Display10;
TextView Display11;
TextView Display12;
TextView Display13;
TextView Display14;
TextView Display15;
TextView Display16;
TextView Display17;
TextView Display18;
Button button;
Button button2;
static char Maze[][] ={
{'#','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','#'}
};
static char Wall = '#';
static char Free = '0';
static char Path = 'X';
static int Height = 9;
static int Width = 9;
static Coordinate Start = new Coordinate(7,8);
static Coordinate End = new Coordinate(1,0);
static char CurrentDirection = 'n';
static int previousX = 0;
static int previousY = 0;
static int currentX = 7;
static int currentY = 8;
static ArrayList<String> instructions = new ArrayList<String>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Amarino.connect(this, DEVICE_ADDRESS);
/*forward = (ImageButton) findViewById(R.id.imageButton1);
right = (ImageButton) findViewById(R.id.imageButton2);
left = (ImageButton) findViewById(R.id.imageButton4);
backward = (ImageButton) findViewById(R.id.imageButton3);*/
Display1 = (TextView) findViewById(R.id.textView2);
Display2 = (TextView) findViewById(R.id.textView3);
Display3 = (TextView) findViewById(R.id.textView4);
Display4 = (TextView) findViewById(R.id.textView5);
Display5 = (TextView) findViewById(R.id.textView6);
Display6 = (TextView) findViewById(R.id.textView7);
Display7 = (TextView) findViewById(R.id.textView8);
Display8 = (TextView) findViewById(R.id.textView9);
Display9 = (TextView) findViewById(R.id.textView10);
Display1.setText(new String(Maze[0]));
Display2.setText(new String(Maze[1]));
Display3.setText(new String(Maze[2]));
Display4.setText(new String(Maze[3]));
Display5.setText(new String(Maze[4]));
Display6.setText(new String(Maze[5]));
Display7.setText(new String(Maze[6]));
Display8.setText(new String(Maze[7]));
Display9.setText(new String(Maze[8]));
Display10 = (TextView) findViewById(R.id.textView12);
Display11 = (TextView) findViewById(R.id.textView13);
Display12 = (TextView) findViewById(R.id.textView14);
Display13 = (TextView) findViewById(R.id.textView15);
Display14 = (TextView) findViewById(R.id.textView16);
Display15 = (TextView) findViewById(R.id.textView17);
Display16 = (TextView) findViewById(R.id.textView18);
Display17 = (TextView) findViewById(R.id.textView19);
Display18 = (TextView) findViewById(R.id.textView20);
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
if(solve(Start.getX(), Start.getY())){
findpath();
Display10.setText(new String(Maze[0]));
Display11.setText(new String(Maze[1]));
Display12.setText(new String(Maze[2]));
Display13.setText(new String(Maze[3]));
Display14.setText(new String(Maze[4]));
Display15.setText(new String(Maze[5]));
Display16.setText(new String(Maze[6]));
Display17.setText(new String(Maze[7]));
Display18.setText(new String(Maze[8]));
button.setVisibility(View.INVISIBLE);
button2.setVisibility(0);
}
}
});
button2 = (Button) findViewById(R.id.button2);
button2.setVisibility(View.INVISIBLE);
button2.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
for(String x: instructions){
if(x.equals("Forward")){
forward();
} else if (x.equals("Left")){
left();
+ forward();
} else if(x.equals("Right")){
right();
+ forward();
}
}
}
});
}
public static void findpath(){
while(currentX != End.getX() && currentY != End.getY()){
switch(CurrentDirection){
case 'n':
if(currentY - 1 >= 0 && (Maze[currentY - 1][currentX] == Path) || (Maze[currentY - 1][currentX] == 'E')){
currentY = currentY - 1;
instructions.add("Forward");
break;
}
if(currentX - 1 >= 0 && (Maze[currentY][currentX - 1] == Path) || (Maze[currentY][currentX - 1] == 'E')){
currentX = currentX - 1;
instructions.add("Left");
CurrentDirection = 'w';
break;
}
if(currentX + 1 < Width && (Maze[currentY][currentX + 1] == Path) || (Maze[currentY][currentX + 1] == 'E')){
currentX = currentX + 1;
instructions.add("Right");
CurrentDirection = 'e';
break;
}
case 'e':
if(currentX + 1 < Width && (Maze[currentY][currentX + 1] == Path) || (Maze[currentY][currentX + 1] == 'E')){
currentX = currentX - 1;
CurrentDirection = 'e';
instructions.add("Forward");
break;
}
if(currentY - 1 >= 0 && (Maze[currentY - 1][currentX] == Path) || (Maze[currentY - 1][currentX] == 'E')){
currentY = currentY - 1;
instructions.add("Left");
CurrentDirection = 'n';
break;
}
if(currentY + 1 < Height && (Maze[currentY + 1][currentX] == Path) || (Maze[currentY + 1][currentX] == 'E')){
currentY = currentY + 1;
instructions.add("Right");
CurrentDirection = 's';
break;
}
case 's':
if(currentY + 1 < Height && (Maze[currentY + 1][currentX] == Path) || (Maze[currentY + 1][currentX] == 'E')){
currentY = currentY + 1;
instructions.add("Forward");
break;
}
if(currentX + 1 < Width && (Maze[currentY][currentX + 1] == Path) || (Maze[currentY][currentX + 1] == 'E')){
currentX = currentX + 1;
instructions.add("Left");
CurrentDirection = 'e';
break;
}
if(currentX - 1 >= 0 && (Maze[currentY][currentX - 1] == Path) || (Maze[currentY][currentX - 1] == 'E')){
currentX = currentX - 1;
instructions.add("Right");
CurrentDirection = 'w';
break;
}
case 'w':
if(currentY - 1 >= 0 && (Maze[currentY - 1][currentX] == Path) || (Maze[currentY - 1][currentX] == 'E')){
currentY = currentY - 1;
instructions.add("Right");
CurrentDirection = 'n';
break;
}
if(currentX - 1 >= 0 && (Maze[currentY][currentX - 1] == Path) || (Maze[currentY][currentX - 1] == 'E')){
currentX = currentX - 1;
instructions.add("Forward");
break;
}
if(currentY + 1 < Height && (Maze[currentY+1][currentX] == Path) || (Maze[currentY+1][currentX] == 'E')){
currentY = currentY + 1;
instructions.add("Left");
CurrentDirection = 's';
break;
}
}
}
}
public static boolean solve(int x, int y){
if(x == Start.getX() && y == Start.getY()){
Maze[y][x] = 'S';
} else if (x == End.getX() && y == End.getY()){
Maze[y][x] = 'E';
}else{
Maze[y][x] = Path;
}
if(x == End.getX() && y == End.getY()){
return true;
}
if(x > 0 && Maze[y][x - 1] == Free && solve(x - 1, y)){
return true;
}
if(x < Width && Maze[y][x+1] == Free && solve(x+1,y)){
return true;
}
if(y > 0 && Maze[y - 1][x] == Free && solve(x,y - 1)){
return true;
}
if(y < Height && Maze[y + 1][x] == Free && solve(x,y+1)){
return true;
}
Maze[y][x] = Free;
return false;
}
private void forward(){
Amarino.sendDataToArduino(this, DEVICE_ADDRESS, 'A', 0);
}
private void backward(){
Amarino.sendDataToArduino(this, DEVICE_ADDRESS, 'B', 0);
}
private void right(){
Amarino.sendDataToArduino(this, DEVICE_ADDRESS, 'C', 0);
}
private void left(){
Amarino.sendDataToArduino(this, DEVICE_ADDRESS, 'D', 0);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
| false | true | protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Amarino.connect(this, DEVICE_ADDRESS);
/*forward = (ImageButton) findViewById(R.id.imageButton1);
right = (ImageButton) findViewById(R.id.imageButton2);
left = (ImageButton) findViewById(R.id.imageButton4);
backward = (ImageButton) findViewById(R.id.imageButton3);*/
Display1 = (TextView) findViewById(R.id.textView2);
Display2 = (TextView) findViewById(R.id.textView3);
Display3 = (TextView) findViewById(R.id.textView4);
Display4 = (TextView) findViewById(R.id.textView5);
Display5 = (TextView) findViewById(R.id.textView6);
Display6 = (TextView) findViewById(R.id.textView7);
Display7 = (TextView) findViewById(R.id.textView8);
Display8 = (TextView) findViewById(R.id.textView9);
Display9 = (TextView) findViewById(R.id.textView10);
Display1.setText(new String(Maze[0]));
Display2.setText(new String(Maze[1]));
Display3.setText(new String(Maze[2]));
Display4.setText(new String(Maze[3]));
Display5.setText(new String(Maze[4]));
Display6.setText(new String(Maze[5]));
Display7.setText(new String(Maze[6]));
Display8.setText(new String(Maze[7]));
Display9.setText(new String(Maze[8]));
Display10 = (TextView) findViewById(R.id.textView12);
Display11 = (TextView) findViewById(R.id.textView13);
Display12 = (TextView) findViewById(R.id.textView14);
Display13 = (TextView) findViewById(R.id.textView15);
Display14 = (TextView) findViewById(R.id.textView16);
Display15 = (TextView) findViewById(R.id.textView17);
Display16 = (TextView) findViewById(R.id.textView18);
Display17 = (TextView) findViewById(R.id.textView19);
Display18 = (TextView) findViewById(R.id.textView20);
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
if(solve(Start.getX(), Start.getY())){
findpath();
Display10.setText(new String(Maze[0]));
Display11.setText(new String(Maze[1]));
Display12.setText(new String(Maze[2]));
Display13.setText(new String(Maze[3]));
Display14.setText(new String(Maze[4]));
Display15.setText(new String(Maze[5]));
Display16.setText(new String(Maze[6]));
Display17.setText(new String(Maze[7]));
Display18.setText(new String(Maze[8]));
button.setVisibility(View.INVISIBLE);
button2.setVisibility(0);
}
}
});
button2 = (Button) findViewById(R.id.button2);
button2.setVisibility(View.INVISIBLE);
button2.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
for(String x: instructions){
if(x.equals("Forward")){
forward();
} else if (x.equals("Left")){
left();
} else if(x.equals("Right")){
right();
}
}
}
});
}
| protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Amarino.connect(this, DEVICE_ADDRESS);
/*forward = (ImageButton) findViewById(R.id.imageButton1);
right = (ImageButton) findViewById(R.id.imageButton2);
left = (ImageButton) findViewById(R.id.imageButton4);
backward = (ImageButton) findViewById(R.id.imageButton3);*/
Display1 = (TextView) findViewById(R.id.textView2);
Display2 = (TextView) findViewById(R.id.textView3);
Display3 = (TextView) findViewById(R.id.textView4);
Display4 = (TextView) findViewById(R.id.textView5);
Display5 = (TextView) findViewById(R.id.textView6);
Display6 = (TextView) findViewById(R.id.textView7);
Display7 = (TextView) findViewById(R.id.textView8);
Display8 = (TextView) findViewById(R.id.textView9);
Display9 = (TextView) findViewById(R.id.textView10);
Display1.setText(new String(Maze[0]));
Display2.setText(new String(Maze[1]));
Display3.setText(new String(Maze[2]));
Display4.setText(new String(Maze[3]));
Display5.setText(new String(Maze[4]));
Display6.setText(new String(Maze[5]));
Display7.setText(new String(Maze[6]));
Display8.setText(new String(Maze[7]));
Display9.setText(new String(Maze[8]));
Display10 = (TextView) findViewById(R.id.textView12);
Display11 = (TextView) findViewById(R.id.textView13);
Display12 = (TextView) findViewById(R.id.textView14);
Display13 = (TextView) findViewById(R.id.textView15);
Display14 = (TextView) findViewById(R.id.textView16);
Display15 = (TextView) findViewById(R.id.textView17);
Display16 = (TextView) findViewById(R.id.textView18);
Display17 = (TextView) findViewById(R.id.textView19);
Display18 = (TextView) findViewById(R.id.textView20);
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
if(solve(Start.getX(), Start.getY())){
findpath();
Display10.setText(new String(Maze[0]));
Display11.setText(new String(Maze[1]));
Display12.setText(new String(Maze[2]));
Display13.setText(new String(Maze[3]));
Display14.setText(new String(Maze[4]));
Display15.setText(new String(Maze[5]));
Display16.setText(new String(Maze[6]));
Display17.setText(new String(Maze[7]));
Display18.setText(new String(Maze[8]));
button.setVisibility(View.INVISIBLE);
button2.setVisibility(0);
}
}
});
button2 = (Button) findViewById(R.id.button2);
button2.setVisibility(View.INVISIBLE);
button2.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
for(String x: instructions){
if(x.equals("Forward")){
forward();
} else if (x.equals("Left")){
left();
forward();
} else if(x.equals("Right")){
right();
forward();
}
}
}
});
}
|
diff --git a/src/utils/FileUtils.java b/src/utils/FileUtils.java
index 3c3fd25..d7f3ff0 100644
--- a/src/utils/FileUtils.java
+++ b/src/utils/FileUtils.java
@@ -1,31 +1,38 @@
package utils;
import java.io.File;
import java.io.FileReader;
import java.util.Scanner;
public class FileUtils {
public static void createDir(String dir) {
File f = new File(dir);
f.mkdir();
}
public static String getStringFromFile (String fileLocation) {
+ Scanner in = null;
try {
File f = new File(fileLocation);
if(f.exists()) {
- Scanner in = new Scanner(new FileReader(fileLocation));
+ in = new Scanner(new FileReader(fileLocation));
String s, str="";
while(in.hasNext() && (s=in.nextLine())!=null) str+=s+"\n";
return str;
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
- }
+ } finally {
+ try {
+ if(in!=null) in.close();
+ } catch(Exception e) {
+ e.printStackTrace();
+ }
+ }
}
}
| false | true | public static String getStringFromFile (String fileLocation) {
try {
File f = new File(fileLocation);
if(f.exists()) {
Scanner in = new Scanner(new FileReader(fileLocation));
String s, str="";
while(in.hasNext() && (s=in.nextLine())!=null) str+=s+"\n";
return str;
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
| public static String getStringFromFile (String fileLocation) {
Scanner in = null;
try {
File f = new File(fileLocation);
if(f.exists()) {
in = new Scanner(new FileReader(fileLocation));
String s, str="";
while(in.hasNext() && (s=in.nextLine())!=null) str+=s+"\n";
return str;
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
try {
if(in!=null) in.close();
} catch(Exception e) {
e.printStackTrace();
}
}
}
|
diff --git a/plugins/org.eclipse.birt.core/src/org/eclipse/birt/core/framework/PlatformFileContext.java b/plugins/org.eclipse.birt.core/src/org/eclipse/birt/core/framework/PlatformFileContext.java
index 903f59f..ccc5d0d 100644
--- a/plugins/org.eclipse.birt.core/src/org/eclipse/birt/core/framework/PlatformFileContext.java
+++ b/plugins/org.eclipse.birt.core/src/org/eclipse/birt/core/framework/PlatformFileContext.java
@@ -1,80 +1,80 @@
/*******************************************************************************
* Copyright (c) 2004 Actuate Corporation. 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: Actuate Corporation -
* initial API and implementation
******************************************************************************/
package org.eclipse.birt.core.framework;
import java.security.AccessController;
import java.security.PrivilegedAction;
/**
* An platform context that is based on file operations. Since in web
* environment WAR deployment, absolute file path is not available. In this
* case, user should NOT use this class. In this case, user should use
* PlatformServletContext or develop his own PlatformContext to make sure
* reousce operation are used.
*/
public class PlatformFileContext implements IPlatformContext
{
protected String root;
protected String[] arguments;
/**
* PlatformFileContext Constructor
*
*/
public PlatformFileContext( )
{
root = getSystemBirtHome( );
arguments = null;
}
/**
* PlatformFileContext Constructor( String , IPlatformConfig )
*
* @param root
* @param platformConfig
*/
public PlatformFileContext( PlatformConfig config )
{
assert config != null;
root = config.getBIRTHome( );
if ( root == null )
{
root = getSystemBirtHome( );
}
arguments = config.getOSGiArguments( );
}
public String getPlatform( )
{
return root;
}
public String[] getLaunchArguments( )
{
return arguments;
}
private String getSystemBirtHome( )
{
return AccessController.doPrivileged( new PrivilegedAction<String>( ) {
public String run( )
{
String home = System.getProperty( IPlatformConfig.BIRT_HOME );
- if ( home == null || home.isEmpty( ) )
+ if ( home == null || "".equals( home ) )
{
return ".";
}
return home;
}
} );
}
}
| true | true | private String getSystemBirtHome( )
{
return AccessController.doPrivileged( new PrivilegedAction<String>( ) {
public String run( )
{
String home = System.getProperty( IPlatformConfig.BIRT_HOME );
if ( home == null || home.isEmpty( ) )
{
return ".";
}
return home;
}
} );
}
| private String getSystemBirtHome( )
{
return AccessController.doPrivileged( new PrivilegedAction<String>( ) {
public String run( )
{
String home = System.getProperty( IPlatformConfig.BIRT_HOME );
if ( home == null || "".equals( home ) )
{
return ".";
}
return home;
}
} );
}
|
diff --git a/core/src/visad/trunk/Gridded2DDoubleSet.java b/core/src/visad/trunk/Gridded2DDoubleSet.java
index 62c7319e3..06c88e413 100644
--- a/core/src/visad/trunk/Gridded2DDoubleSet.java
+++ b/core/src/visad/trunk/Gridded2DDoubleSet.java
@@ -1,896 +1,896 @@
//
// Gridded2DDoubleSet.java
//
/*
VisAD system for interactive analysis and visualization of numerical
data. Copyright (C) 1996 - 2002 Bill Hibbard, Curtis Rueden, Tom
Rink, Dave Glowacki, Steve Emmerson, Tom Whittaker, Don Murray, and
Tommy Jasmin.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
MA 02111-1307, USA
*/
package visad;
/**
Gridded2DDoubleSet is a Gridded2DSet with double-precision samples.<P>
*/
public class Gridded2DDoubleSet extends Gridded2DSet
implements GriddedDoubleSet {
double[] Low = new double[2];
double[] Hi = new double[2];
double LowX, HiX, LowY, HiY;
double[][] Samples;
// Overridden Gridded2DSet constructors (float[][])
/** a 2-D set whose topology is a lengthX x lengthY grid, with
null errors, CoordinateSystem and Units are defaults from type */
public Gridded2DDoubleSet(MathType type, float[][] samples, int lengthX, int lengthY)
throws VisADException {
this(type, Set.floatToDouble(samples), lengthX, lengthY, null, null, null, true);
}
/** a 2-D set whose topology is a lengthX x lengthY grid;
samples array is organized float[2][number_of_samples] where
lengthX * lengthY = number_of_samples; samples must form a
non-degenerate 2-D grid (no bow-tie-shaped grid boxes); the
X component increases fastest in the second index of samples;
coordinate_system and units must be compatible with defaults
for type, or may be null; errors may be null */
public Gridded2DDoubleSet(MathType type, float[][] samples, int lengthX, int lengthY,
CoordinateSystem coord_sys, Unit[] units,
ErrorEstimate[] errors) throws VisADException {
this(type, Set.floatToDouble(samples), lengthX, lengthY, coord_sys,
units, errors, true);
}
Gridded2DDoubleSet(MathType type, float[][] samples, int lengthX, int lengthY,
CoordinateSystem coord_sys, Unit[] units,
ErrorEstimate[] errors, boolean copy)
throws VisADException {
this(type, Set.floatToDouble(samples), lengthX, lengthY, coord_sys,
units, errors, copy);
}
/** a 2-D set with manifold dimension = 1, with null errors,
CoordinateSystem and Units are defaults from type */
public Gridded2DDoubleSet(MathType type, float[][] samples, int lengthX)
throws VisADException {
this(type, Set.floatToDouble(samples), lengthX, null, null, null, true);
}
/** a 2-D set with manifold dimension = 1; samples array is
organized float[2][number_of_samples] where lengthX =
number_of_samples; no geometric constraint on samples;
coordinate_system and units must be compatible with defaults
for type, or may be null; errors may be null */
public Gridded2DDoubleSet(MathType type, float[][] samples, int lengthX,
CoordinateSystem coord_sys, Unit[] units,
ErrorEstimate[] errors) throws VisADException {
this(type, Set.floatToDouble(samples), lengthX, coord_sys, units, errors, true);
}
public Gridded2DDoubleSet(MathType type, float[][] samples, int lengthX,
CoordinateSystem coord_sys, Unit[] units,
ErrorEstimate[] errors, boolean copy)
throws VisADException {
this(type, Set.floatToDouble(samples), lengthX, coord_sys, units, errors, copy);
}
// Corresponding Gridded2DDoubleSet constructors (double[][])
/** a 2-D set whose topology is a lengthX x lengthY grid, with
null errors, CoordinateSystem and Units are defaults from type */
public Gridded2DDoubleSet(MathType type, double[][] samples, int lengthX, int lengthY)
throws VisADException {
this(type, samples, lengthX, lengthY, null, null, null, true);
}
/** a 2-D set whose topology is a lengthX x lengthY grid;
samples array is organized double[2][number_of_samples] where
lengthX * lengthY = number_of_samples; samples must form a
non-degenerate 2-D grid (no bow-tie-shaped grid boxes); the
X component increases fastest in the second index of samples;
coordinate_system and units must be compatible with defaults
for type, or may be null; errors may be null */
public Gridded2DDoubleSet(MathType type, double[][] samples, int lengthX, int lengthY,
CoordinateSystem coord_sys, Unit[] units,
ErrorEstimate[] errors) throws VisADException {
this(type, samples, lengthX, lengthY, coord_sys, units, errors, true);
}
public Gridded2DDoubleSet(MathType type, double[][] samples, int lengthX,
int lengthY, CoordinateSystem coord_sys, Unit[] units,
ErrorEstimate[] errors, boolean copy)
throws VisADException {
super(type, null, lengthX, lengthY, coord_sys, units, errors, copy);
if (samples == null) {
throw new SetException("Gridded2DDoubleSet: samples are null");
}
init_doubles(samples, copy);
LowX = Low[0];
HiX = Hi[0];
LengthX = Lengths[0];
LowY = Low[1];
HiY = Hi[1];
LengthY = Lengths[1];
if (Samples != null && Lengths[0] > 1 && Lengths[1] > 1) {
for (int i=0; i<Length; i++) {
if (Samples[0][i] != Samples[0][i]) {
throw new SetException(
"Gridded2DDoubleSet: samples values may not be missing");
}
}
// Samples consistency test
Pos = ( (Samples[0][1]-Samples[0][0])
*(Samples[1][LengthX+1]-Samples[1][1])
- (Samples[1][1]-Samples[1][0])
*(Samples[0][LengthX+1]-Samples[0][1]) > 0);
for (int j=0; j<LengthY-1; j++) {
for (int i=0; i<LengthX-1; i++) {
double[] v00 = new double[2];
double[] v10 = new double[2];
double[] v01 = new double[2];
double[] v11 = new double[2];
for (int v=0; v<2; v++) {
v00[v] = Samples[v][j*LengthX+i];
v10[v] = Samples[v][j*LengthX+i+1];
v01[v] = Samples[v][(j+1)*LengthX+i];
v11[v] = Samples[v][(j+1)*LengthX+i+1];
}
if ( ( (v10[0]-v00[0])*(v11[1]-v10[1])
- (v10[1]-v00[1])*(v11[0]-v10[0]) > 0 != Pos)
|| ( (v11[0]-v10[0])*(v01[1]-v11[1])
- (v11[1]-v10[1])*(v01[0]-v11[0]) > 0 != Pos)
|| ( (v01[0]-v11[0])*(v00[1]-v01[1])
- (v01[1]-v11[1])*(v00[0]-v01[0]) > 0 != Pos)
|| ( (v00[0]-v01[0])*(v10[1]-v00[1])
- (v00[1]-v01[1])*(v10[0]-v00[0]) > 0 != Pos) ) {
throw new SetException(
"Gridded2DDoubleSet: samples do not form a valid grid ("+i+","+j+")");
}
}
}
}
}
/** a 2-D set with manifold dimension = 1, with null errors,
CoordinateSystem and Units are defaults from type */
public Gridded2DDoubleSet(MathType type, double[][] samples, int lengthX)
throws VisADException {
this(type, samples, lengthX, null, null, null);
}
/** a 2-D set with manifold dimension = 1; samples array is
organized double[2][number_of_samples] where lengthX =
number_of_samples; no geometric constraint on samples;
coordinate_system and units must be compatible with defaults
for type, or may be null; errors may be null */
public Gridded2DDoubleSet(MathType type, double[][] samples, int lengthX,
CoordinateSystem coord_sys, Unit[] units,
ErrorEstimate[] errors) throws VisADException {
this(type, samples, lengthX, coord_sys, units, errors, true);
}
public Gridded2DDoubleSet(MathType type, double[][] samples, int lengthX,
CoordinateSystem coord_sys, Unit[] units,
ErrorEstimate[] errors, boolean copy)
throws VisADException {
super(type, null, lengthX, coord_sys, units, errors, copy);
if (samples == null) {
throw new SetException("Gridded2DDoubleSet: samples are null");
}
init_doubles(samples, copy);
LowX = Low[0];
HiX = Hi[0];
LengthX = Lengths[0];
LowY = Low[1];
HiY = Hi[1];
// no Samples consistency test
}
//END
// Overridden Gridded2DSet methods (float[][])
public float[][] getSamples() throws VisADException {
return getSamples(true);
}
public float[][] getSamples(boolean copy) throws VisADException {
return Set.doubleToFloat(Samples);
}
/** convert an array of 1-D indices to an array of values in R^DomainDimension */
public float[][] indexToValue(int[] index) throws VisADException {
return Set.doubleToFloat(indexToDouble(index));
}
/** convert an array of values in R^DomainDimension to an array of 1-D indices */
public int[] valueToIndex(float[][] value) throws VisADException {
return doubleToIndex(Set.floatToDouble(value));
}
/** transform an array of non-integer grid coordinates to an array
of values in R^DomainDimension */
public float[][] gridToValue(float[][] grid) throws VisADException {
return Set.doubleToFloat(gridToDouble(Set.floatToDouble(grid)));
}
/** transform an array of values in R^DomainDimension to an array
of non-integer grid coordinates */
public float[][] valueToGrid(float[][] value) throws VisADException {
return Set.doubleToFloat(doubleToGrid(Set.floatToDouble(value)));
}
/** for each of an array of values in R^DomainDimension, compute an array
of 1-D indices and an array of weights, to be used for interpolation;
indices[i] and weights[i] are null if i-th value is outside grid
(i.e., if no interpolation is possible) */
public void valueToInterp(float[][] value, int[][] indices,
float[][] weights) throws VisADException
{
int len = weights.length;
double[][] w = new double[len][];
doubleToInterp(Set.floatToDouble(value), indices, w);
for (int i=0; i<len; i++) {
if (w[i] != null) {
weights[i] = new float[w[i].length];
for (int j=0; j<w[i].length; j++) {
weights[i][j] = (float) w[i][j];
}
}
}
}
// Corresponding Gridded2DDoubleSet methods (double[][])
public double[][] getDoubles() throws VisADException {
return getDoubles(true);
}
public double[][] getDoubles(boolean copy) throws VisADException {
return copy ? Set.copyDoubles(Samples) : Samples;
}
/** convert an array of 1-D indices to an array of values in
R^DomainDimension */
public double[][] indexToDouble(int[] index) throws VisADException {
int length = index.length;
if (Samples == null) {
// not used - over-ridden by Linear2DSet.indexToValue
int indexX, indexY;
double[][] grid = new double[ManifoldDimension][length];
for (int i=0; i<length; i++) {
if (0 <= index[i] && index[i] < Length) {
indexX = index[i] % LengthX;
indexY = index[i] / LengthX;
}
else {
indexX = -1;
indexY = -1;
}
grid[0][i] = indexX;
grid[1][i] = indexY;
}
return gridToDouble(grid);
}
else {
double[][] values = new double[2][length];
for (int i=0; i<length; i++) {
if (0 <= index[i] && index[i] < Length) {
values[0][i] = Samples[0][index[i]];
values[1][i] = Samples[1][index[i]];
}
else {
values[0][i] = Double.NaN;
values[1][i] = Double.NaN;
}
}
return values;
}
}
/** convert an array of values in R^DomainDimension to an array of 1-D indices */
public int[] doubleToIndex(double[][] value) throws VisADException {
if (value.length != DomainDimension) {
throw new SetException("Gridded2DDoubleSet.doubleToIndex: value dimension " +
value.length + " not equal to Domain dimension " +
DomainDimension);
}
int length = value[0].length;
int[] index = new int[length];
double[][] grid = doubleToGrid(value);
double[] grid0 = grid[0];
double[] grid1 = grid[1];
double g0, g1;
for (int i=0; i<length; i++) {
g0 = grid0[i];
g1 = grid1[i];
/* WLH 24 Oct 97
index[i] = (Double.isNaN(g0) || Double.isNaN(g1)) ? -1 :
*/
// test for missing
index[i] = (g0 != g0 || g1 != g1) ? -1 :
((int) (g0 + 0.5)) + LengthX * ((int) (g1 + 0.5));
}
return index;
}
/** transform an array of non-integer grid coordinates to an array
of values in R^DomainDimension */
public double[][] gridToDouble(double[][] grid) throws VisADException {
if (grid.length != ManifoldDimension) {
throw new SetException("Gridded2DDoubleSet.gridToDouble: bad dimension");
}
if (ManifoldDimension < 2) {
throw new SetException("Gridded2DDoubleSet.gridToDouble: ManifoldDimension " +
"must be 2");
}
if (Length > 1 && (Lengths[0] < 2 || Lengths[1] < 2)) {
throw new SetException("Gridded2DDoubleSet.gridToDouble: requires all grid " +
"dimensions to be > 1");
}
// avoid any ArrayOutOfBounds exceptions by taking the shortest length
int length = Math.min(grid[0].length, grid[1].length);
double[][] value = new double[2][length];
for (int i=0; i<length; i++) {
// let gx and gy by the current grid values
double gx = grid[0][i];
double gy = grid[1][i];
if ( (gx < -0.5) || (gy < -0.5) ||
(gx > LengthX-0.5) || (gy > LengthY-0.5) ) {
value[0][i] = value[1][i] = Double.NaN;
} else if (Length == 1) {
value[0][i] = Samples[0][0];
value[1][i] = Samples[1][0];
} else {
// calculate closest integer variables
int igx = (int) gx;
int igy = (int) gy;
if (igx < 0) igx = 0;
if (igx > LengthX-2) igx = LengthX-2;
if (igy < 0) igy = 0;
if (igy > LengthY-2) igy = LengthY-2;
// set up conversion to 1D Samples array
int[][] s = { {LengthX*igy+igx, // (0, 0)
LengthX*(igy+1)+igx}, // (0, 1)
{LengthX*igy+igx+1, // (1, 0)
LengthX*(igy+1)+igx+1} }; // (1, 1)
if (gx+gy-igx-igy-1 <= 0) {
// point is in LOWER triangle
for (int j=0; j<2; j++) {
value[j][i] = Samples[j][s[0][0]]
+ (gx-igx)*(Samples[j][s[1][0]]-Samples[j][s[0][0]])
+ (gy-igy)*(Samples[j][s[0][1]]-Samples[j][s[0][0]]);
}
}
else {
// point is in UPPER triangle
for (int j=0; j<2; j++) {
value[j][i] = Samples[j][s[1][1]]
+ (1+igx-gx)*(Samples[j][s[0][1]]-Samples[j][s[1][1]])
+ (1+igy-gy)*(Samples[j][s[1][0]]-Samples[j][s[1][1]]);
}
}
}
}
return value;
}
// WLH 6 Dec 2001
private int gx = -1;
private int gy = -1;
/** transform an array of values in R^DomainDimension to an array
of non-integer grid coordinates */
public double[][] doubleToGrid(double[][] value) throws VisADException {
if (value.length < DomainDimension) {
throw new SetException("Gridded2DDoubleSet.doubleToGrid: bad dimension");
}
if (ManifoldDimension < 2) {
throw new SetException("Gridded2DDoubleSet.doubleToGrid: ManifoldDimension " +
"must be 2");
}
if (Length > 1 && (Lengths[0] < 2 || Lengths[1] < 2)) {
throw new SetException("Gridded2DDoubleSet.doubleToGrid: requires all grid " +
"dimensions to be > 1");
}
int length = Math.min(value[0].length, value[1].length);
double[][] grid = new double[ManifoldDimension][length];
// (gx, gy) is the current grid box guess
/* WLH 6 Dec 2001
int gx = (LengthX-1)/2;
int gy = (LengthY-1)/2;
*/
// use value from last call as first guess, if reasonable
if (gx < 0 || gx >= LengthX || gy < 0 || gy >= LengthY) {
gx = (LengthX-1)/2;
gy = (LengthY-1)/2;
}
boolean lowertri = true;
for (int i=0; i<length; i++) {
// grid box guess starts at previous box unless there was no solution
/* WLH 24 Oct 97
if ( (i != 0) && (Double.isNaN(grid[0][i-1])) )
*/
if (Length == 1) {
if (Double.isNaN(value[0][i]) || Double.isNaN(value[1][i])) {
grid[0][i] = grid[1][i] = Double.NaN;
} else {
grid[0][i] = 0;
grid[1][i] = 0;
}
continue;
}
// test for missing
if ( (i != 0) && grid[0][i-1] != grid[0][i-1] ) {
gx = (LengthX-1)/2;
gy = (LengthY-1)/2;
}
// if the loop doesn't find the answer, the result should be NaN
grid[0][i] = grid[1][i] = Double.NaN;
for (int itnum=0; itnum<2*(LengthX+LengthY); itnum++) {
// define the four vertices of the current grid box
double[] v0 = {Samples[0][gy*LengthX+gx],
Samples[1][gy*LengthX+gx]};
double[] v1 = {Samples[0][gy*LengthX+gx+1],
Samples[1][gy*LengthX+gx+1]};
double[] v2 = {Samples[0][(gy+1)*LengthX+gx],
Samples[1][(gy+1)*LengthX+gx]};
double[] v3 = {Samples[0][(gy+1)*LengthX+gx+1],
Samples[1][(gy+1)*LengthX+gx+1]};
// Both cases use diagonal D-B and point distances P-B and P-D
double[] bd = {v2[0]-v1[0], v2[1]-v1[1]};
double[] bp = {value[0][i]-v1[0], value[1][i]-v1[1]};
double[] dp = {value[0][i]-v2[0], value[1][i]-v2[1]};
// check the LOWER triangle of the grid box
if (lowertri) {
double[] ab = {v1[0]-v0[0], v1[1]-v0[1]};
double[] da = {v0[0]-v2[0], v0[1]-v2[1]};
double[] ap = {value[0][i]-v0[0], value[1][i]-v0[1]};
double tval1 = ab[0]*ap[1]-ab[1]*ap[0];
double tval2 = bd[0]*bp[1]-bd[1]*bp[0];
double tval3 = da[0]*dp[1]-da[1]*dp[0];
boolean test1 = (tval1 == 0) || ((tval1 > 0) == Pos);
boolean test2 = (tval2 == 0) || ((tval2 > 0) == Pos);
boolean test3 = (tval3 == 0) || ((tval3 > 0) == Pos);
int ogx = gx;
int ogy = gy;
if (!test1 && !test2) { // Go UP & RIGHT
gx++;
gy--;
}
else if (!test2 && !test3) { // Go DOWN & LEFT
gx--;
gy++;
}
else if (!test1 && !test3) { // Go UP & LEFT
gx--;
gy--;
}
else if (!test1) { // Go UP
gy--;
}
else if (!test3) { // Go LEFT
gx--;
}
// Snap guesses back into the grid
if (gx < 0) gx = 0;
if (gx > LengthX-2) gx = LengthX-2;
if (gy < 0) gy = 0;
if (gy > LengthY-2) gy = LengthY-2;
if ( (gx == ogx) && (gy == ogy) && (test2) ) {
// Found correct grid triangle
// Solve the point with the reverse interpolation
grid[0][i] = ((value[0][i]-v0[0])*(v2[1]-v0[1])
+ (v0[1]-value[1][i])*(v2[0]-v0[0]))
/ ((v1[0]-v0[0])*(v2[1]-v0[1])
+ (v0[1]-v1[1])*(v2[0]-v0[0])) + gx;
grid[1][i] = ((value[0][i]-v0[0])*(v1[1]-v0[1])
+ (v0[1]-value[1][i])*(v1[0]-v0[0]))
/ ((v2[0]-v0[0])*(v1[1]-v0[1])
+ (v0[1]-v2[1])*(v1[0]-v0[0])) + gy;
break;
}
else {
lowertri = false;
}
}
// check the UPPER triangle of the grid box
else {
double[] bc = {v3[0]-v1[0], v3[1]-v1[1]};
double[] cd = {v2[0]-v3[0], v2[1]-v3[1]};
double[] cp = {value[0][i]-v3[0], value[1][i]-v3[1]};
double tval1 = bc[0]*bp[1]-bc[1]*bp[0];
double tval2 = cd[0]*cp[1]-cd[1]*cp[0];
double tval3 = bd[0]*dp[1]-bd[1]*dp[0];
boolean test1 = (tval1 == 0) || ((tval1 > 0) == Pos);
boolean test2 = (tval2 == 0) || ((tval2 > 0) == Pos);
boolean test3 = (tval3 == 0) || ((tval3 < 0) == Pos);
int ogx = gx;
int ogy = gy;
if (!test1 && !test3) { // Go UP & RIGHT
gx++;
gy--;
}
else if (!test2 && !test3) { // Go DOWN & LEFT
gx--;
gy++;
}
else if (!test1 && !test2) { // Go DOWN & RIGHT
gx++;
gy++;
}
else if (!test1) { // Go RIGHT
gx++;
}
else if (!test2) { // Go DOWN
gy++;
}
// Snap guesses back into the grid
if (gx < 0) gx = 0;
if (gx > LengthX-2) gx = LengthX-2;
if (gy < 0) gy = 0;
if (gy > LengthY-2) gy = LengthY-2;
if ( (gx == ogx) && (gy == ogy) && (test3) ) {
// Found correct grid triangle
// Solve the point with the reverse interpolation
grid[0][i] = ((v3[0]-value[0][i])*(v1[1]-v3[1])
+ (value[1][i]-v3[1])*(v1[0]-v3[0]))
/ ((v2[0]-v3[0])*(v1[1]-v3[1])
- (v2[1]-v3[1])*(v1[0]-v3[0])) + gx + 1;
grid[1][i] = ((v2[1]-v3[1])*(v3[0]-value[0][i])
+ (v2[0]-v3[0])*(value[1][i]-v3[1]))
/ ((v1[0]-v3[0])*(v2[1]-v3[1])
- (v2[0]-v3[0])*(v1[1]-v3[1])) + gy + 1;
break;
}
else {
lowertri = true;
}
}
- if ( (grid[0][i] >= LengthX-0.5) || (grid[1][i] >= LengthY-0.5)
- || (grid[0][i] <= -0.5) || (grid[1][i] <= -0.5) ) {
- grid[0][i] = grid[1][i] = Double.NaN;
- }
+ }
+ if ( (grid[0][i] >= LengthX-0.5) || (grid[1][i] >= LengthY-0.5)
+ || (grid[0][i] <= -0.5) || (grid[1][i] <= -0.5) ) {
+ grid[0][i] = grid[1][i] = Double.NaN;
}
}
return grid;
}
/** for each of an array of values in R^DomainDimension, compute an array
of 1-D indices and an array of weights, to be used for interpolation;
indices[i] and weights[i] are null if i-th value is outside grid
(i.e., if no interpolation is possible) */
public void doubleToInterp(double[][] value, int[][] indices,
double[][] weights) throws VisADException
{
if (value.length != DomainDimension) {
throw new SetException("Gridded2DDoubleSet.doubleToInterp: value dimension " +
value.length + " not equal to Domain dimension " +
DomainDimension);
}
int length = value[0].length; // number of values
if (indices.length != length) {
throw new SetException("Gridded2DDoubleSet.valueToInterp: indices length " +
indices.length +
" doesn't match value[0] length " +
value[0].length);
}
if (weights.length != length) {
throw new SetException("Gridded2DDoubleSet.valueToInterp: weights length " +
weights.length +
" doesn't match value[0] length " +
value[0].length);
}
// convert value array to grid coord array
double[][] grid = doubleToGrid(value);
int i, j, k; // loop indices
int lis; // temporary length of is & cs
int length_is; // final length of is & cs, varies by i
int isoff; // offset along one grid dimension
double a, b; // weights along one grid dimension; a + b = 1.0
int[] is; // array of indices, becomes part of indices
double[] cs; // array of coefficients, become part of weights
int base; // base index, as would be returned by valueToIndex
int[] l = new int[ManifoldDimension]; // integer 'factors' of base
// fractions with l; -0.5 <= c <= 0.5
double[] c = new double[ManifoldDimension];
// array of index offsets by grid dimension
int[] off = new int[ManifoldDimension];
off[0] = 1;
for (j=1; j<ManifoldDimension; j++) off[j] = off[j-1] * Lengths[j-1];
for (i=0; i<length; i++) {
// compute length_is, base, l & c
length_is = 1;
if (Double.isNaN(grid[ManifoldDimension-1][i])) {
base = -1;
}
else {
l[ManifoldDimension-1] = (int) (grid[ManifoldDimension-1][i] + 0.5);
// WLH 23 Dec 99
if (l[ManifoldDimension-1] == Lengths[ManifoldDimension-1]) {
l[ManifoldDimension-1]--;
}
c[ManifoldDimension-1] = grid[ManifoldDimension-1][i] -
((double) l[ManifoldDimension-1]);
if (!((l[ManifoldDimension-1] == 0 && c[ManifoldDimension-1] <= 0.0) ||
(l[ManifoldDimension-1] == Lengths[ManifoldDimension-1] - 1 &&
c[ManifoldDimension-1] >= 0.0))) {
// only interp along ManifoldDimension-1
// if between two valid grid coords
length_is *= 2;
}
base = l[ManifoldDimension-1];
}
for (j=ManifoldDimension-2; j>=0 && base>=0; j--) {
if (Double.isNaN(grid[j][i])) {
base = -1;
}
else {
l[j] = (int) (grid[j][i] + 0.5);
if (l[j] == Lengths[j]) l[j]--; // WLH 23 Dec 99
c[j] = grid[j][i] - ((double) l[j]);
if (!((l[j] == 0 && c[j] <= 0.0) ||
(l[j] == Lengths[j] - 1 && c[j] >= 0.0))) {
// only interp along dimension j if between two valid grid coords
length_is *= 2;
}
base = l[j] + Lengths[j] * base;
}
}
if (base < 0) {
// value is out of grid so return null
is = null;
cs = null;
}
else {
// create is & cs of proper length, and init first element
is = new int[length_is];
cs = new double[length_is];
is[0] = base;
cs[0] = 1.0f;
lis = 1;
for (j=0; j<ManifoldDimension; j++) {
if (!((l[j] == 0 && c[j] <= 0.0) ||
(l[j] == Lengths[j] - 1 && c[j] >= 0.0))) {
// only interp along dimension j if between two valid grid coords
if (c[j] >= 0.0) {
// grid coord above base
isoff = off[j];
a = 1.0f - c[j];
b = c[j];
}
else {
// grid coord below base
isoff = -off[j];
a = 1.0f + c[j];
b = -c[j];
}
// double is & cs; adjust new offsets; split weights
for (k=0; k<lis; k++) {
is[k+lis] = is[k] + isoff;
cs[k+lis] = cs[k] * b;
cs[k] *= a;
}
lis *= 2;
}
}
}
indices[i] = is;
weights[i] = cs;
}
}
// Miscellaneous Set methods that must be overridden
// (this code is duplicated throughout all *DoubleSet classes)
void init_doubles(double[][] samples, boolean copy)
throws VisADException {
if (samples.length != DomainDimension) {
throw new SetException("Gridded2DDoubleSet.init_doubles: samples " +
" dimension " + samples.length +
" not equal to domain dimension " +
DomainDimension);
}
if (Length == 0) {
// Length set in init_lengths, but not called for IrregularSet
Length = samples[0].length;
}
else {
if (Length != samples[0].length) {
throw new SetException("Gridded2DDoubleSet.init_doubles: " +
"samples[0] length " + samples[0].length +
" doesn't match expected length " + Length);
}
}
// MEM
if (copy) {
Samples = new double[DomainDimension][Length];
}
else {
Samples = samples;
}
for (int j=0; j<DomainDimension; j++) {
if (samples[j].length != Length) {
throw new SetException("Gridded2DDoubleSet.init_doubles: " +
"samples[" + j + "] length " +
samples[0].length +
" doesn't match expected length " + Length);
}
double[] samplesJ = samples[j];
double[] SamplesJ = Samples[j];
if (copy) {
System.arraycopy(samplesJ, 0, SamplesJ, 0, Length);
}
Low[j] = Double.POSITIVE_INFINITY;
Hi[j] = Double.NEGATIVE_INFINITY;
double sum = 0.0f;
for (int i=0; i<Length; i++) {
if (SamplesJ[i] == SamplesJ[i] && !Double.isInfinite(SamplesJ[i])) {
if (SamplesJ[i] < Low[j]) Low[j] = SamplesJ[i];
if (SamplesJ[i] > Hi[j]) Hi[j] = SamplesJ[i];
}
else {
SamplesJ[i] = Double.NaN;
}
sum += SamplesJ[i];
}
if (SetErrors[j] != null ) {
SetErrors[j] =
new ErrorEstimate(SetErrors[j].getErrorValue(), sum / Length,
Length, SetErrors[j].getUnit());
}
super.Low[j] = (float) Low[j];
super.Hi[j] = (float) Hi[j];
}
}
public void cram_missing(boolean[] range_select) {
int n = Math.min(range_select.length, Samples[0].length);
for (int i=0; i<n; i++) {
if (!range_select[i]) Samples[0][i] = Double.NaN;
}
}
public boolean isMissing() {
return (Samples == null);
}
public boolean equals(Object set) {
if (!(set instanceof Gridded2DDoubleSet) || set == null) return false;
if (this == set) return true;
if (testNotEqualsCache((Set) set)) return false;
if (testEqualsCache((Set) set)) return true;
if (!equalUnitAndCS((Set) set)) return false;
try {
int i, j;
if (DomainDimension != ((Gridded2DDoubleSet) set).getDimension() ||
ManifoldDimension !=
((Gridded2DDoubleSet) set).getManifoldDimension() ||
Length != ((Gridded2DDoubleSet) set).getLength()) return false;
for (j=0; j<ManifoldDimension; j++) {
if (Lengths[j] != ((Gridded2DDoubleSet) set).getLength(j)) {
return false;
}
}
// Sets are immutable, so no need for 'synchronized'
double[][] samples = ((Gridded2DDoubleSet) set).getDoubles(false);
if (Samples != null && samples != null) {
for (j=0; j<DomainDimension; j++) {
for (i=0; i<Length; i++) {
if (Samples[j][i] != samples[j][i]) {
addNotEqualsCache((Set) set);
return false;
}
}
}
}
else {
double[][] this_samples = getDoubles(false);
if (this_samples == null) {
if (samples != null) {
return false;
}
} else if (samples == null) {
return false;
} else {
for (j=0; j<DomainDimension; j++) {
for (i=0; i<Length; i++) {
if (this_samples[j][i] != samples[j][i]) {
addNotEqualsCache((Set) set);
return false;
}
}
}
}
}
addEqualsCache((Set) set);
return true;
}
catch (VisADException e) {
return false;
}
}
/**
* Clones this instance.
*
* @return A clone of this instance.
*/
public Object clone() {
Gridded2DDoubleSet clone = (Gridded2DDoubleSet)super.clone();
if (Samples != null) {
/*
* The Samples array is cloned because getDoubles(false) allows clients
* to manipulate the array and the general clone() contract forbids
* cross-clone contamination.
*/
clone.Samples = (double[][])Samples.clone();
for (int i = 0; i < Samples.length; i++)
clone.Samples[i] = (double[])Samples[i].clone();
}
return clone;
}
public Object cloneButType(MathType type) throws VisADException {
if (ManifoldDimension == 2) {
return new Gridded2DDoubleSet(type, Samples, LengthX, LengthY,
DomainCoordinateSystem, SetUnits, SetErrors);
}
else {
return new Gridded2DDoubleSet(type, Samples, LengthX,
DomainCoordinateSystem, SetUnits, SetErrors);
}
}
/* WLH 3 April 2003
public Object cloneButType(MathType type) throws VisADException {
return new Gridded2DDoubleSet(type, Samples, Length,
DomainCoordinateSystem, SetUnits, SetErrors);
}
*/
}
| true | true | public double[][] doubleToGrid(double[][] value) throws VisADException {
if (value.length < DomainDimension) {
throw new SetException("Gridded2DDoubleSet.doubleToGrid: bad dimension");
}
if (ManifoldDimension < 2) {
throw new SetException("Gridded2DDoubleSet.doubleToGrid: ManifoldDimension " +
"must be 2");
}
if (Length > 1 && (Lengths[0] < 2 || Lengths[1] < 2)) {
throw new SetException("Gridded2DDoubleSet.doubleToGrid: requires all grid " +
"dimensions to be > 1");
}
int length = Math.min(value[0].length, value[1].length);
double[][] grid = new double[ManifoldDimension][length];
// (gx, gy) is the current grid box guess
/* WLH 6 Dec 2001
int gx = (LengthX-1)/2;
int gy = (LengthY-1)/2;
*/
// use value from last call as first guess, if reasonable
if (gx < 0 || gx >= LengthX || gy < 0 || gy >= LengthY) {
gx = (LengthX-1)/2;
gy = (LengthY-1)/2;
}
boolean lowertri = true;
for (int i=0; i<length; i++) {
// grid box guess starts at previous box unless there was no solution
/* WLH 24 Oct 97
if ( (i != 0) && (Double.isNaN(grid[0][i-1])) )
*/
if (Length == 1) {
if (Double.isNaN(value[0][i]) || Double.isNaN(value[1][i])) {
grid[0][i] = grid[1][i] = Double.NaN;
} else {
grid[0][i] = 0;
grid[1][i] = 0;
}
continue;
}
// test for missing
if ( (i != 0) && grid[0][i-1] != grid[0][i-1] ) {
gx = (LengthX-1)/2;
gy = (LengthY-1)/2;
}
// if the loop doesn't find the answer, the result should be NaN
grid[0][i] = grid[1][i] = Double.NaN;
for (int itnum=0; itnum<2*(LengthX+LengthY); itnum++) {
// define the four vertices of the current grid box
double[] v0 = {Samples[0][gy*LengthX+gx],
Samples[1][gy*LengthX+gx]};
double[] v1 = {Samples[0][gy*LengthX+gx+1],
Samples[1][gy*LengthX+gx+1]};
double[] v2 = {Samples[0][(gy+1)*LengthX+gx],
Samples[1][(gy+1)*LengthX+gx]};
double[] v3 = {Samples[0][(gy+1)*LengthX+gx+1],
Samples[1][(gy+1)*LengthX+gx+1]};
// Both cases use diagonal D-B and point distances P-B and P-D
double[] bd = {v2[0]-v1[0], v2[1]-v1[1]};
double[] bp = {value[0][i]-v1[0], value[1][i]-v1[1]};
double[] dp = {value[0][i]-v2[0], value[1][i]-v2[1]};
// check the LOWER triangle of the grid box
if (lowertri) {
double[] ab = {v1[0]-v0[0], v1[1]-v0[1]};
double[] da = {v0[0]-v2[0], v0[1]-v2[1]};
double[] ap = {value[0][i]-v0[0], value[1][i]-v0[1]};
double tval1 = ab[0]*ap[1]-ab[1]*ap[0];
double tval2 = bd[0]*bp[1]-bd[1]*bp[0];
double tval3 = da[0]*dp[1]-da[1]*dp[0];
boolean test1 = (tval1 == 0) || ((tval1 > 0) == Pos);
boolean test2 = (tval2 == 0) || ((tval2 > 0) == Pos);
boolean test3 = (tval3 == 0) || ((tval3 > 0) == Pos);
int ogx = gx;
int ogy = gy;
if (!test1 && !test2) { // Go UP & RIGHT
gx++;
gy--;
}
else if (!test2 && !test3) { // Go DOWN & LEFT
gx--;
gy++;
}
else if (!test1 && !test3) { // Go UP & LEFT
gx--;
gy--;
}
else if (!test1) { // Go UP
gy--;
}
else if (!test3) { // Go LEFT
gx--;
}
// Snap guesses back into the grid
if (gx < 0) gx = 0;
if (gx > LengthX-2) gx = LengthX-2;
if (gy < 0) gy = 0;
if (gy > LengthY-2) gy = LengthY-2;
if ( (gx == ogx) && (gy == ogy) && (test2) ) {
// Found correct grid triangle
// Solve the point with the reverse interpolation
grid[0][i] = ((value[0][i]-v0[0])*(v2[1]-v0[1])
+ (v0[1]-value[1][i])*(v2[0]-v0[0]))
/ ((v1[0]-v0[0])*(v2[1]-v0[1])
+ (v0[1]-v1[1])*(v2[0]-v0[0])) + gx;
grid[1][i] = ((value[0][i]-v0[0])*(v1[1]-v0[1])
+ (v0[1]-value[1][i])*(v1[0]-v0[0]))
/ ((v2[0]-v0[0])*(v1[1]-v0[1])
+ (v0[1]-v2[1])*(v1[0]-v0[0])) + gy;
break;
}
else {
lowertri = false;
}
}
// check the UPPER triangle of the grid box
else {
double[] bc = {v3[0]-v1[0], v3[1]-v1[1]};
double[] cd = {v2[0]-v3[0], v2[1]-v3[1]};
double[] cp = {value[0][i]-v3[0], value[1][i]-v3[1]};
double tval1 = bc[0]*bp[1]-bc[1]*bp[0];
double tval2 = cd[0]*cp[1]-cd[1]*cp[0];
double tval3 = bd[0]*dp[1]-bd[1]*dp[0];
boolean test1 = (tval1 == 0) || ((tval1 > 0) == Pos);
boolean test2 = (tval2 == 0) || ((tval2 > 0) == Pos);
boolean test3 = (tval3 == 0) || ((tval3 < 0) == Pos);
int ogx = gx;
int ogy = gy;
if (!test1 && !test3) { // Go UP & RIGHT
gx++;
gy--;
}
else if (!test2 && !test3) { // Go DOWN & LEFT
gx--;
gy++;
}
else if (!test1 && !test2) { // Go DOWN & RIGHT
gx++;
gy++;
}
else if (!test1) { // Go RIGHT
gx++;
}
else if (!test2) { // Go DOWN
gy++;
}
// Snap guesses back into the grid
if (gx < 0) gx = 0;
if (gx > LengthX-2) gx = LengthX-2;
if (gy < 0) gy = 0;
if (gy > LengthY-2) gy = LengthY-2;
if ( (gx == ogx) && (gy == ogy) && (test3) ) {
// Found correct grid triangle
// Solve the point with the reverse interpolation
grid[0][i] = ((v3[0]-value[0][i])*(v1[1]-v3[1])
+ (value[1][i]-v3[1])*(v1[0]-v3[0]))
/ ((v2[0]-v3[0])*(v1[1]-v3[1])
- (v2[1]-v3[1])*(v1[0]-v3[0])) + gx + 1;
grid[1][i] = ((v2[1]-v3[1])*(v3[0]-value[0][i])
+ (v2[0]-v3[0])*(value[1][i]-v3[1]))
/ ((v1[0]-v3[0])*(v2[1]-v3[1])
- (v2[0]-v3[0])*(v1[1]-v3[1])) + gy + 1;
break;
}
else {
lowertri = true;
}
}
if ( (grid[0][i] >= LengthX-0.5) || (grid[1][i] >= LengthY-0.5)
|| (grid[0][i] <= -0.5) || (grid[1][i] <= -0.5) ) {
grid[0][i] = grid[1][i] = Double.NaN;
}
}
}
return grid;
}
| public double[][] doubleToGrid(double[][] value) throws VisADException {
if (value.length < DomainDimension) {
throw new SetException("Gridded2DDoubleSet.doubleToGrid: bad dimension");
}
if (ManifoldDimension < 2) {
throw new SetException("Gridded2DDoubleSet.doubleToGrid: ManifoldDimension " +
"must be 2");
}
if (Length > 1 && (Lengths[0] < 2 || Lengths[1] < 2)) {
throw new SetException("Gridded2DDoubleSet.doubleToGrid: requires all grid " +
"dimensions to be > 1");
}
int length = Math.min(value[0].length, value[1].length);
double[][] grid = new double[ManifoldDimension][length];
// (gx, gy) is the current grid box guess
/* WLH 6 Dec 2001
int gx = (LengthX-1)/2;
int gy = (LengthY-1)/2;
*/
// use value from last call as first guess, if reasonable
if (gx < 0 || gx >= LengthX || gy < 0 || gy >= LengthY) {
gx = (LengthX-1)/2;
gy = (LengthY-1)/2;
}
boolean lowertri = true;
for (int i=0; i<length; i++) {
// grid box guess starts at previous box unless there was no solution
/* WLH 24 Oct 97
if ( (i != 0) && (Double.isNaN(grid[0][i-1])) )
*/
if (Length == 1) {
if (Double.isNaN(value[0][i]) || Double.isNaN(value[1][i])) {
grid[0][i] = grid[1][i] = Double.NaN;
} else {
grid[0][i] = 0;
grid[1][i] = 0;
}
continue;
}
// test for missing
if ( (i != 0) && grid[0][i-1] != grid[0][i-1] ) {
gx = (LengthX-1)/2;
gy = (LengthY-1)/2;
}
// if the loop doesn't find the answer, the result should be NaN
grid[0][i] = grid[1][i] = Double.NaN;
for (int itnum=0; itnum<2*(LengthX+LengthY); itnum++) {
// define the four vertices of the current grid box
double[] v0 = {Samples[0][gy*LengthX+gx],
Samples[1][gy*LengthX+gx]};
double[] v1 = {Samples[0][gy*LengthX+gx+1],
Samples[1][gy*LengthX+gx+1]};
double[] v2 = {Samples[0][(gy+1)*LengthX+gx],
Samples[1][(gy+1)*LengthX+gx]};
double[] v3 = {Samples[0][(gy+1)*LengthX+gx+1],
Samples[1][(gy+1)*LengthX+gx+1]};
// Both cases use diagonal D-B and point distances P-B and P-D
double[] bd = {v2[0]-v1[0], v2[1]-v1[1]};
double[] bp = {value[0][i]-v1[0], value[1][i]-v1[1]};
double[] dp = {value[0][i]-v2[0], value[1][i]-v2[1]};
// check the LOWER triangle of the grid box
if (lowertri) {
double[] ab = {v1[0]-v0[0], v1[1]-v0[1]};
double[] da = {v0[0]-v2[0], v0[1]-v2[1]};
double[] ap = {value[0][i]-v0[0], value[1][i]-v0[1]};
double tval1 = ab[0]*ap[1]-ab[1]*ap[0];
double tval2 = bd[0]*bp[1]-bd[1]*bp[0];
double tval3 = da[0]*dp[1]-da[1]*dp[0];
boolean test1 = (tval1 == 0) || ((tval1 > 0) == Pos);
boolean test2 = (tval2 == 0) || ((tval2 > 0) == Pos);
boolean test3 = (tval3 == 0) || ((tval3 > 0) == Pos);
int ogx = gx;
int ogy = gy;
if (!test1 && !test2) { // Go UP & RIGHT
gx++;
gy--;
}
else if (!test2 && !test3) { // Go DOWN & LEFT
gx--;
gy++;
}
else if (!test1 && !test3) { // Go UP & LEFT
gx--;
gy--;
}
else if (!test1) { // Go UP
gy--;
}
else if (!test3) { // Go LEFT
gx--;
}
// Snap guesses back into the grid
if (gx < 0) gx = 0;
if (gx > LengthX-2) gx = LengthX-2;
if (gy < 0) gy = 0;
if (gy > LengthY-2) gy = LengthY-2;
if ( (gx == ogx) && (gy == ogy) && (test2) ) {
// Found correct grid triangle
// Solve the point with the reverse interpolation
grid[0][i] = ((value[0][i]-v0[0])*(v2[1]-v0[1])
+ (v0[1]-value[1][i])*(v2[0]-v0[0]))
/ ((v1[0]-v0[0])*(v2[1]-v0[1])
+ (v0[1]-v1[1])*(v2[0]-v0[0])) + gx;
grid[1][i] = ((value[0][i]-v0[0])*(v1[1]-v0[1])
+ (v0[1]-value[1][i])*(v1[0]-v0[0]))
/ ((v2[0]-v0[0])*(v1[1]-v0[1])
+ (v0[1]-v2[1])*(v1[0]-v0[0])) + gy;
break;
}
else {
lowertri = false;
}
}
// check the UPPER triangle of the grid box
else {
double[] bc = {v3[0]-v1[0], v3[1]-v1[1]};
double[] cd = {v2[0]-v3[0], v2[1]-v3[1]};
double[] cp = {value[0][i]-v3[0], value[1][i]-v3[1]};
double tval1 = bc[0]*bp[1]-bc[1]*bp[0];
double tval2 = cd[0]*cp[1]-cd[1]*cp[0];
double tval3 = bd[0]*dp[1]-bd[1]*dp[0];
boolean test1 = (tval1 == 0) || ((tval1 > 0) == Pos);
boolean test2 = (tval2 == 0) || ((tval2 > 0) == Pos);
boolean test3 = (tval3 == 0) || ((tval3 < 0) == Pos);
int ogx = gx;
int ogy = gy;
if (!test1 && !test3) { // Go UP & RIGHT
gx++;
gy--;
}
else if (!test2 && !test3) { // Go DOWN & LEFT
gx--;
gy++;
}
else if (!test1 && !test2) { // Go DOWN & RIGHT
gx++;
gy++;
}
else if (!test1) { // Go RIGHT
gx++;
}
else if (!test2) { // Go DOWN
gy++;
}
// Snap guesses back into the grid
if (gx < 0) gx = 0;
if (gx > LengthX-2) gx = LengthX-2;
if (gy < 0) gy = 0;
if (gy > LengthY-2) gy = LengthY-2;
if ( (gx == ogx) && (gy == ogy) && (test3) ) {
// Found correct grid triangle
// Solve the point with the reverse interpolation
grid[0][i] = ((v3[0]-value[0][i])*(v1[1]-v3[1])
+ (value[1][i]-v3[1])*(v1[0]-v3[0]))
/ ((v2[0]-v3[0])*(v1[1]-v3[1])
- (v2[1]-v3[1])*(v1[0]-v3[0])) + gx + 1;
grid[1][i] = ((v2[1]-v3[1])*(v3[0]-value[0][i])
+ (v2[0]-v3[0])*(value[1][i]-v3[1]))
/ ((v1[0]-v3[0])*(v2[1]-v3[1])
- (v2[0]-v3[0])*(v1[1]-v3[1])) + gy + 1;
break;
}
else {
lowertri = true;
}
}
}
if ( (grid[0][i] >= LengthX-0.5) || (grid[1][i] >= LengthY-0.5)
|| (grid[0][i] <= -0.5) || (grid[1][i] <= -0.5) ) {
grid[0][i] = grid[1][i] = Double.NaN;
}
}
return grid;
}
|
diff --git a/src/main/java/de/codecentric/moviedatabase/service/InMemoryMovieService.java b/src/main/java/de/codecentric/moviedatabase/service/InMemoryMovieService.java
index d93fc55..aa9858a 100644
--- a/src/main/java/de/codecentric/moviedatabase/service/InMemoryMovieService.java
+++ b/src/main/java/de/codecentric/moviedatabase/service/InMemoryMovieService.java
@@ -1,156 +1,156 @@
package de.codecentric.moviedatabase.service;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.util.Assert;
import de.codecentric.moviedatabase.domain.Comment;
import de.codecentric.moviedatabase.domain.Movie;
import de.codecentric.moviedatabase.domain.Tag;
import de.codecentric.moviedatabase.exception.ResourceNotFoundException;
public class InMemoryMovieService implements MovieService {
private Map<UUID, Movie> idToMovieMap = new ConcurrentHashMap<UUID, Movie>();
private Map<Tag, Set<Movie>> tagToMoviesMap = new ConcurrentHashMap<Tag, Set<Movie>>();
public InMemoryMovieService(){
// let the dummy Movie have always the same ID to test it easily via command line tools / unit tests
Movie movie = new Movie(UUID.fromString("240342ea-84c8-415f-b1d5-8e4376191aeb"),
"Star Wars","In einer Galaxie weit, weit entfernt",
new Date());
Tag tag = new Tag("Science Fiction");
movie.getTags().add(tag);
idToMovieMap.put(movie.getId(), movie);
Set<Movie> movies = new HashSet<Movie>();
movies.add(movie);
tagToMoviesMap.put(tag, movies);
}
@Override
public void createMovie(Movie movie) {
Assert.notNull(movie);
idToMovieMap.put(movie.getId(), movie);
for (Tag tag: movie.getTags()){
Set<Movie> movies = tagToMoviesMap.get(tag);
if (movies == null){
movies = new HashSet<Movie>();
}
movies.add(movie);
tagToMoviesMap.put(tag, movies);
}
}
@Override
public void updateMovie(Movie movie) {
// Tags may not be added or removed by this method
Assert.notNull(movie);
idToMovieMap.put(movie.getId(), movie);
}
@Override
public void deleteMovie(UUID id) {
Assert.notNull(id);
Movie movie = idToMovieMap.remove(id);
for (Set<Movie> movies: tagToMoviesMap.values()){
movies.remove(movie);
}
}
@Override
public void addCommentToMovie(Comment comment, UUID movieId) {
Assert.notNull(comment);
Assert.notNull(movieId);
Movie movie = idToMovieMap.get(movieId);
if (movie == null){
throw new ResourceNotFoundException("Movie not found.");
}
movie.getComments().add(comment);
}
@Override
public void addTagToMovie(Tag tag, UUID movieId) {
Assert.notNull(tag);
Assert.notNull(movieId);
Movie movie = idToMovieMap.get(movieId);
if (movie == null){
throw new ResourceNotFoundException("Movie not found.");
}
movie.getTags().add(tag);
Set<Movie> movies = tagToMoviesMap.get(tag);
if (movies == null){
movies = new HashSet<Movie>();
}
movies.add(movie);
tagToMoviesMap.put(tag, movies);
}
@Override
public void removeTagFromMovie(Tag tag, UUID movieId) {
Assert.notNull(tag);
Assert.notNull(movieId);
Movie movie = idToMovieMap.get(movieId);
if (movie == null){
throw new ResourceNotFoundException("Movie not found.");
}
movie.getTags().remove(tag);
Set<Movie> movies = tagToMoviesMap.get(tag);
if (movies != null){
movies.remove(movie);
}
}
@Override
public Movie findMovieById(UUID id) {
Assert.notNull(id);
Movie movie = idToMovieMap.get(id);
if (movie == null){
throw new ResourceNotFoundException("Movie not found.");
}
return movie;
}
@Override
public List<Movie> findMovieByTagsAndSearchString(Set<Tag> tags,
Set<String> searchWords) {
Set<Movie> taggedMovies = new HashSet<Movie>();
List<Movie> searchResult = new ArrayList<Movie>();
if (tags == null || tags.isEmpty()){
taggedMovies = new HashSet<Movie>(idToMovieMap.values());
} else {
for (Tag tag: tags){
Collection<Movie> movies = tagToMoviesMap.get(tag);
if (movies != null){
taggedMovies.addAll(tagToMoviesMap.get(tag));
}
}
}
searchResult.addAll(taggedMovies);
if (searchWords != null && !searchWords.isEmpty()){
for (String searchWord: searchWords){
for (Iterator<Movie> it = searchResult.iterator();it.hasNext();){
Movie movie = it.next();
- if (!(movie.getTitle().toLowerCase().contains(searchWord.toLowerCase())) && !(movie.getDescription().toLowerCase().contains(searchWord.toLowerCase()))){
+ if (!(movie.getTitle().toLowerCase().contains(searchWord.toLowerCase())) && !(movie.getDescription() != null && movie.getDescription().toLowerCase().contains(searchWord.toLowerCase()))){
it.remove();
}
}
}
}
return searchResult;
}
@Override
public List<Tag> findAllTags() {
return new ArrayList<Tag>(tagToMoviesMap.keySet());
}
}
| true | true | public List<Movie> findMovieByTagsAndSearchString(Set<Tag> tags,
Set<String> searchWords) {
Set<Movie> taggedMovies = new HashSet<Movie>();
List<Movie> searchResult = new ArrayList<Movie>();
if (tags == null || tags.isEmpty()){
taggedMovies = new HashSet<Movie>(idToMovieMap.values());
} else {
for (Tag tag: tags){
Collection<Movie> movies = tagToMoviesMap.get(tag);
if (movies != null){
taggedMovies.addAll(tagToMoviesMap.get(tag));
}
}
}
searchResult.addAll(taggedMovies);
if (searchWords != null && !searchWords.isEmpty()){
for (String searchWord: searchWords){
for (Iterator<Movie> it = searchResult.iterator();it.hasNext();){
Movie movie = it.next();
if (!(movie.getTitle().toLowerCase().contains(searchWord.toLowerCase())) && !(movie.getDescription().toLowerCase().contains(searchWord.toLowerCase()))){
it.remove();
}
}
}
}
return searchResult;
}
| public List<Movie> findMovieByTagsAndSearchString(Set<Tag> tags,
Set<String> searchWords) {
Set<Movie> taggedMovies = new HashSet<Movie>();
List<Movie> searchResult = new ArrayList<Movie>();
if (tags == null || tags.isEmpty()){
taggedMovies = new HashSet<Movie>(idToMovieMap.values());
} else {
for (Tag tag: tags){
Collection<Movie> movies = tagToMoviesMap.get(tag);
if (movies != null){
taggedMovies.addAll(tagToMoviesMap.get(tag));
}
}
}
searchResult.addAll(taggedMovies);
if (searchWords != null && !searchWords.isEmpty()){
for (String searchWord: searchWords){
for (Iterator<Movie> it = searchResult.iterator();it.hasNext();){
Movie movie = it.next();
if (!(movie.getTitle().toLowerCase().contains(searchWord.toLowerCase())) && !(movie.getDescription() != null && movie.getDescription().toLowerCase().contains(searchWord.toLowerCase()))){
it.remove();
}
}
}
}
return searchResult;
}
|
diff --git a/x10.compiler/src/x10/ExtensionInfo.java b/x10.compiler/src/x10/ExtensionInfo.java
index 2a561ea3f..7ca8164a3 100644
--- a/x10.compiler/src/x10/ExtensionInfo.java
+++ b/x10.compiler/src/x10/ExtensionInfo.java
@@ -1,1045 +1,1045 @@
/*
* This file is part of the X10 project (http://x10-lang.org).
*
* This file is licensed to You under the Eclipse Public License (EPL);
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.opensource.org/licenses/eclipse-1.0.php
*
* (C) Copyright IBM Corporation 2006-2010.
*/
package x10;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import polyglot.ast.ClassMember;
import polyglot.ast.Node;
import polyglot.ast.NodeFactory;
import polyglot.ast.SourceFile;
import polyglot.ast.TopLevelDecl;
import polyglot.ast.TypeNode;
import polyglot.frontend.AllBarrierGoal;
import polyglot.frontend.BarrierGoal;
import polyglot.frontend.Compiler;
import polyglot.frontend.CyclicDependencyException;
import polyglot.frontend.FileResource;
import polyglot.frontend.FileSource;
import polyglot.frontend.ForgivingVisitorGoal;
import polyglot.frontend.Globals;
import polyglot.frontend.Goal;
import polyglot.frontend.JLScheduler;
import polyglot.frontend.Job;
import polyglot.frontend.JobExt;
import polyglot.frontend.OutputGoal;
import polyglot.frontend.Parser;
import polyglot.frontend.ParserGoal;
import polyglot.frontend.Scheduler;
import polyglot.frontend.Source;
import polyglot.frontend.SourceGoal;
import polyglot.frontend.SourceGoal_c;
import polyglot.frontend.TargetFactory;
import polyglot.frontend.VisitorGoal;
import polyglot.main.Options;
import polyglot.main.Report;
import polyglot.types.Flags;
import polyglot.types.MemberClassResolver;
import polyglot.types.QName;
import polyglot.types.SemanticException;
import polyglot.types.TopLevelResolver;
import polyglot.types.TypeSystem;
import polyglot.util.ErrorInfo;
import polyglot.util.ErrorQueue;
import polyglot.util.InternalCompilerError;
import polyglot.util.Position;
import polyglot.visit.ConformanceChecker;
import polyglot.visit.ConstructorCallChecker;
import polyglot.visit.ContextVisitor;
import polyglot.visit.ExceptionChecker;
import polyglot.visit.ExitChecker;
import polyglot.visit.FwdReferenceChecker;
import polyglot.visit.InitChecker;
import polyglot.visit.NodeVisitor;
import polyglot.visit.PruningVisitor;
import polyglot.visit.ReachChecker;
import polyglot.visit.Translator;
import x10.ast.X10NodeFactory_c;
import x10.compiler.ws.WSCodeGenerator;
import x10.errors.Warnings;
import x10.extension.X10Ext;
//import x10.finish.table.CallTableKey;
//import x10.finish.table.CallTableVal;
import x10.optimizations.Optimizer;
import x10.parser.X10Lexer;
import x10.parser.X10SemanticRules;
import x10.plugin.CompilerPlugin;
import x10.plugin.LoadJobPlugins;
import x10.plugin.LoadPlugins;
import x10.plugin.RegisterPlugins;
import x10.types.X10SourceClassResolver;
import polyglot.types.TypeSystem;
import x10.types.X10TypeSystem_c;
import x10.visit.CheckNativeAnnotationsVisitor;
import x10.visit.Lowerer;
import x10.visit.Desugarer;
import x10.visit.ExpressionFlattener;
import x10.visit.FieldInitializerMover;
//import x10.visit.FinishAsyncVisitor;
import x10.visit.MainMethodFinder;
import x10.visit.NativeClassVisitor;
import x10.visit.RewriteAtomicMethodVisitor;
import x10.visit.StaticNestedClassRemover;
import x10.visit.X10Caster;
import x10.visit.X10ImplicitDeclarationExpander;
import x10.visit.X10InnerClassRemover;
import x10.visit.X10MLVerifier;
import x10.visit.X10Translator;
import x10.visit.X10TypeBuilder;
import x10.visit.X10TypeChecker;
import x10.visit.PositionInvariantChecker;
import x10.visit.InstanceInvariantChecker;
import x10.visit.CheckEscapingThis;
/**
* Extension information for x10 extension.
*/
public class ExtensionInfo extends polyglot.frontend.ParserlessJLExtensionInfo {
static final boolean DEBUG_ = false;
static {
// force Topics to load
Topics t = new Topics();
}
protected Map<QName,CompilerPlugin> plugins;
public static final String XML_FILE_EXTENSION = "x10ml";
public static final String XML_FILE_DOT_EXTENSION = "." + XML_FILE_EXTENSION;
// private static HashMap<CallTableKey, LinkedList<CallTableVal>> calltable = new HashMap<CallTableKey, LinkedList<CallTableVal>>();
public static String clock = "clock";
static {
Report.topics.add(clock);
}
public polyglot.main.Version version() {
return new Version();
}
public String[] fileExtensions() {
return new String[] { "x10", XML_FILE_EXTENSION };
}
// public String defaultFileExtension() {
// return "x10";
// }
public String compilerName() {
return "x10c";
}
//
// Replace the Flex/Cup parser with a JikesPG parser
//
// public Parser parser(Reader reader, FileSource source, ErrorQueue eq) {
// Lexer lexer = new Lexer_c(reader, source.name(), eq);
// Grm grm = new Grm(lexer, ts, nf, eq);
// return new CupParser(grm, source, eq);
// }
//
public Parser parser(Reader reader, FileSource source, ErrorQueue eq) {
// ###
// if (source.path().endsWith(XML_FILE_DOT_EXTENSION)) {
// return new DomParser(reader, (X10TypeSystem) ts, (X10NodeFactory) nf, source, eq);
// }
try {
//
// X10Lexer may be invoked using one of two constructors.
// One constructor takes as argument a string representing
// a (fully-qualified) filename; the other constructor takes
// as arguments a (file) Reader and a string representing the
// name of the file in question. Invoking the first
// constructor is more efficient because a buffered File is created
// from that string and read with one (read) operation. However,
// we depend on Polyglot to provide us with a fully qualified
// name for the file. In Version 1.3.0, source.name() yielded a
// fully-qualied name. In 1.3.2, source.path() yields a fully-
// qualified name. If this assumption still holds then the
// first constructor will work.
// The advantage of using the Reader constructor is that it
// will always work, though not as efficiently.
//
// X10Lexer x10_lexer = new X10Lexer(reader, source.name());
//
// FIXME: HACK! Unwrap the escaping unicode reader, because LPG will do its own decoding
// if (reader instanceof polyglot.lex.EscapedUnicodeReader)
// reader = ((polyglot.lex.EscapedUnicodeReader)reader).getSource();
X10Lexer x10_lexer =
// Optimization: it's faster to read from a file
source.resource().getClass() == FileResource.class ?
new X10Lexer(source.path()) :
new X10Lexer(reader, source.toString());
X10SemanticRules x10_parser = new X10SemanticRules(x10_lexer.getILexStream(), ts, nf, source, eq); // Create the parser
x10_lexer.lexer(x10_parser.getIPrsStream());
return x10_parser; // Parse the token stream to produce an AST
} catch (IOException e) {
e.printStackTrace();
}
throw new IllegalStateException("Could not parse " + source.path());
}
protected HashSet<String> manifest = new HashSet<String>();
public boolean manifestContains(String path) {
path = path.replace(File.separatorChar, '/');
// FIXME: HACK! Try all prefixes
int s = 0;
while ((s = path.indexOf('/')) != -1) {
if (manifest.contains(path))
return true;
path = path.substring(s+1);
}
if (manifest.contains(path))
return true;
return false;
}
static class WarningComparator implements Comparator<ErrorInfo> {
public int compare(ErrorInfo a, ErrorInfo b) {
Position pa = a.getPosition();
Position pb = b.getPosition();
if (pa == null && pb == null) {
if (a.getMessage() == null && b.getMessage() == null)
return 0;
else if (a.getMessage() != null && a.getMessage().equals(b.getMessage()))
return 0;
}
if (pa == null)
return -1;
if (pb == null)
return 1;
if (pa.line() < pb.line())
return -1;
if (pb.line() < pa.line())
return 1;
if (pa.column() < pb.column())
return -1;
if (pb.column() < pa.column())
return 1;
return 0;
}
}
Set<ErrorInfo> warnings = new TreeSet<ErrorInfo>(new WarningComparator());
public Set<ErrorInfo> warningSet() {
return warnings;
}
static class ExceptionComparator implements Comparator<SemanticException> {
public int compare(SemanticException a, SemanticException b) {
int r = (a.getClass().toString().compareToIgnoreCase(b.getClass().toString()));
if (r != 0)
return r;
Position pa = a.position();
Position pb = b.position();
if (pa == null && pb == null) {
if (a.getMessage() == null && b.getMessage() == null)
return 0;
else if (a.getMessage() != null && a.getMessage().equals(b.getMessage()))
return 0;
}
if (pa == null)
return -1;
if (pb == null)
return 1;
if (pa.line() < pb.line())
return -1;
if (pb.line() < pa.line())
return 1;
// If they have the same message and are on the same line, they're equal
if (a.getMessage() == null && b.getMessage() == null)
return 0;
if (a.getMessage() == null)
return -1;
if (b.getMessage() == null)
return 1;
if (!a.getMessage().equals(b.getMessage()))
return a.getMessage().compareToIgnoreCase(b.getMessage());
if (a.getMessage().equals(b.getMessage()))
return 0;
if (pa.column() < pb.column())
return -1;
if (pb.column() < pa.column())
return 1;
return 0;
}
}
Set<SemanticException> errors = new TreeSet<SemanticException>(new ExceptionComparator());
public Set<SemanticException> errorSet() {
return errors;
}
private int weakCallsCount = 0;
public void incrWeakCallsCount() {
weakCallsCount++;
}
public int weakCallsCount() {
return weakCallsCount;
}
protected void initTypeSystem() {
try {
TopLevelResolver r = new X10SourceClassResolver(compiler, this, getOptions().constructFullClasspath(),
getOptions().compile_command_line_only,
getOptions().ignore_mod_times);
// FIXME: [IP] HACK
if (Configuration.MANIFEST != null) {
try {
FileReader fr = new FileReader(Configuration.MANIFEST);
BufferedReader br = new BufferedReader(fr);
String file = "";
while ((file = br.readLine()) != null)
if (file.endsWith(".x10") || file.endsWith(".jar")) // FIXME: hard-codes the source extension.
manifest.add(file);
} catch (IOException e) { }
} else {
for (File f : getOptions().source_path) {
if (f.getName().endsWith("x10.jar")) {
try {
JarFile jf = new JarFile(f);
manifest.add("x10.jar");
Enumeration<JarEntry> entries = jf.entries();
while (entries.hasMoreElements()) {
JarEntry je = entries.nextElement();
if (je.getName().endsWith(".x10")) { // FIXME: hard-codes the source extension.
manifest.add(je.getName());
}
}
} catch (IOException e) { }
}
}
}
// Resolver to handle lookups of member classes.
if (true || TypeSystem.SERIALIZE_MEMBERS_WITH_CONTAINER) {
MemberClassResolver mcr = new MemberClassResolver(ts, r, true);
r = mcr;
}
ts.initialize(r, this);
}
catch (SemanticException e) {
throw new InternalCompilerError(
"Unable to initialize type system: " + e.getMessage(), e);
}
}
protected NodeFactory createNodeFactory() {
return new X10NodeFactory_c(this);
}
protected TypeSystem createTypeSystem() {
return new X10TypeSystem_c();
}
public void initCompiler(Compiler compiler) {
super.initCompiler(compiler);
//QueryEngine.init(this);
}
// =================================
// X10-specific goals and scheduling
// =================================
protected Scheduler createScheduler() {
return new X10Scheduler(this);
}
public static class X10Scheduler extends JLScheduler {
public X10Scheduler(ExtensionInfo extInfo) {
super(extInfo);
}
protected List<Goal> validateOnlyGoals(Job job) {
List<Goal> goals = new ArrayList<Goal>();
addValidateOnlyGoals(job, goals);
return goals;
}
private void addValidateOnlyGoals(Job job, List<Goal> goals) {
goals.add(Parsed(job));
goals.add(ImportTableInitialized(job));
goals.add(TypesInitialized(job));
if (job.source() != null && job.source().path().endsWith(XML_FILE_DOT_EXTENSION)) {
goals.add(X10MLTypeChecked(job));
}
// Do not include LoadPlugins in list. It would cause prereqs to be added
// goals.add(LoadPlugins());
goals.add(PropagateAnnotations(job));
goals.add(LoadJobPlugins(job));
goals.add(RegisterPlugins(job));
goals.add(PreTypeCheck(job));
goals.add(TypesInitializedForCommandLineBarrier());
goals.add(TypeChecked(job));
goals.add(ReassembleAST(job));
goals.add(ConformanceChecked(job));
// Data-flow analyses
goals.add(ReachabilityChecked(job)); // This must be the first dataflow analysis (see DataFlow.reportCFG_Errors)
// goals.add(ExceptionsChecked(job));
goals.add(ExitPathsChecked(job));
goals.add(InitializationsChecked(job));
goals.add(ConstructorCallsChecked(job));
goals.add(ForwardReferencesChecked(job));
// goals.add(CheckNativeAnnotations(job));
goals.add(CheckEscapingThis(job));
goals.add(CheckASTForErrors(job));
// goals.add(TypeCheckBarrier());
goals.add(End(job));
}
public List<Goal> goals(Job job) {
List<Goal> goals = new ArrayList<Goal>();
addValidateOnlyGoals(job, goals);
Goal endGoal = goals.remove(goals.size()-1);
if (!x10.Configuration.ONLY_TYPE_CHECKING) {
if (x10.Configuration.WALA || x10.Configuration.FINISH_ASYNCS) {
try{
ClassLoader cl = Thread.currentThread().getContextClassLoader();
- Class<?> c = cl.loadClass("com.ibm.wala.cast.x10.translator.polyglot.X102IRGoal");
+ Class<?> c = cl.loadClass("com.ibm.wala.cast.x10.translator.X102IRGoal");
Constructor<?> con = c.getConstructor(Job.class);
Method hasMain = c.getMethod("hasMain", String.class);
Goal ir = ((Goal) con.newInstance(job)).intern(this);
goals.add(ir);
Goal finder = MainMethodFinder(job, hasMain);
finder.addPrereq(TypeCheckBarrier());
ir.addPrereq(finder);
Goal barrier;
if(x10.Configuration.FINISH_ASYNCS){
Method buildCallTableMethod = c.getMethod("analyze");
barrier = IRBarrier(ir, buildCallTableMethod);
} else {
Method printCallGraph = c.getMethod("printCallGraph");
barrier = IRBarrier(ir, printCallGraph);
}
goals.add(barrier);
goals.add(FinishAsyncBarrier(barrier,job,this));
} catch (Throwable e) {
System.err.println("WALA not found.");
e.printStackTrace();
}
}
goals.add(Desugarer(job));
goals.add(X10Casted(job));
goals.add(MoveFieldInitializers(job));
goals.add(X10Expanded(job));
goals.add(X10RewriteAtomicMethods(job));
goals.add(NativeClassVisitor(job));
goals.add(Serialized(job));
if (x10.Configuration.WORK_STEALING) {
Goal wsCodeGenGoal = WSCodeGenerator(job);
goals.add(wsCodeGenGoal);
wsCodeGenGoal.addPrereq(WSCallGraphBarrier());
}
goals.add(Preoptimization(job));
goals.addAll(Optimizer.goals(this, job));
goals.add(Postoptimization(job));
goals.add(Lowerer(job));
goals.add(InnerClassRemover(job)); // TODO: move earlier
goals.add(CodeGenerated(job));
InnerClassRemover(job).addPrereq(Serialized(job));
InnerClassRemover(job).addPrereq(TypeCheckBarrier());
// the barrier will handle prereqs on its own
Desugarer(job).addPrereq(TypeCheckBarrier());
CodeGenerated(job).addPrereq(CodeGenBarrier());
Lowerer(job).addPrereq(TypeCheckBarrier());
CodeGenerated(job).addPrereq(Lowerer(job));
List<Goal> optimizations = Optimizer.goals(this, job);
for (Goal goal : optimizations) {
goal.addPrereq(TypeCheckBarrier());
CodeGenerated(job).addPrereq(goal);
}
}
goals.add(endGoal);
if (x10.Configuration.CHECK_INVARIANTS) {
ArrayList<Goal> newGoals = new ArrayList<Goal>(goals.size()*2);
boolean reachedTypeChecking = false;
int ctr = 0;
for (Goal g : goals) {
newGoals.add(g);
if (!reachedTypeChecking)
newGoals.add(new VisitorGoal("PositionInvariantChecker"+(ctr++), job, new PositionInvariantChecker(job, g.name())).intern(this));
if (g==TypeChecked(job)) {
newGoals.add(new VisitorGoal("InstanceInvariantChecker", job, new InstanceInvariantChecker(job)).intern(this));
reachedTypeChecking = true;
}
}
goals = newGoals;
}
return goals;
}
public Goal Preoptimization(Job job) {
return new SourceGoal_c("Preoptimization", job) {
private static final long serialVersionUID = 1L;
public boolean runTask() { return true; }
}.intern(this);
}
public Goal Postoptimization(Job job) {
return new SourceGoal_c("Postoptimization", job) {
private static final long serialVersionUID = 1L;
public boolean runTask() { return true; }
}.intern(this);
}
Goal PrintWeakCallsCount;
@Override
protected Goal EndAll() {
if (PrintWeakCallsCount == null) {
PrintWeakCallsCount = new PrintWeakCallsCount((ExtensionInfo) extInfo).intern(this);
Goal postcompiled = PostCompiled();
PrintWeakCallsCount.addPrereq(postcompiled);
}
return PrintWeakCallsCount;
}
static class PrintWeakCallsCount extends AllBarrierGoal {
private static final long serialVersionUID = 6978580691962888126L;
ExtensionInfo ext;
public PrintWeakCallsCount(ExtensionInfo extInfo) {
super("PrintWeakCallsCount",extInfo.scheduler());
this.ext = extInfo;
}
public Goal prereqForJob(Job job) {
if (scheduler.shouldCompile(job)) {
return scheduler.End(job);
}
else {
return new SourceGoal_c("WCCDummyEnd", job) {
private static final long serialVersionUID = 1L;
public boolean runTask() { return true; }
}.intern(scheduler);
}
}
public boolean runTask() {
Compiler compiler = ext.compiler();
if ((! Configuration.VERBOSE_CALLS) && (! Configuration.STATIC_CALLS)) {
int count = ext.weakCallsCount();
if (count > 0) {
compiler.errorQueue().enqueue(ErrorInfo.WARNING, count + " dynamically checked calls or field accesses, run with -VERBOSE_CALLS for more details.");
}
}
return true;
}
}
@SuppressWarnings("unchecked")
public static <T> T invokeGeneric(Method method) {
try {
return (T) method.invoke(null);
} catch (IllegalArgumentException e) {
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {
}
return null;
}
public Goal IRBarrier(final Goal goal, final Method method) {
return new AllBarrierGoal("IRBarrier", this) {
private static final long serialVersionUID = -3692329571101709400L;
@Override
public Goal prereqForJob(Job job) {
if (!super.scheduler.commandLineJobs().contains(job) &&
((ExtensionInfo) extInfo).manifestContains(job.source().path())) {
return null;
}
return goal;
}
public boolean runTask() {
if (Configuration.FINISH_ASYNCS) {
// calltable = X10Scheduler.<HashMap<CallTableKey, LinkedList<CallTableVal>>>invokeGeneric(method);
} else {
try {
method.invoke(null);
} catch (IllegalArgumentException e) {
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {
}
}
return true;
}
}.intern(this);
}
public Goal TypeCheckBarrier() {
String name = "TypeCheckBarrier";
if (extInfo.getOptions().compile_command_line_only) {
return new BarrierGoal(name, commandLineJobs()) {
private static final long serialVersionUID = -1495893515710977644L;
@Override
public Goal prereqForJob(Job job) {
return CheckASTForErrors(job);
}
}.intern(this);
}
else {
return new AllBarrierGoal(name, this) {
private static final long serialVersionUID = 6757229496093951388L;
@Override
public Goal prereqForJob(Job job) {
if (!super.scheduler.commandLineJobs().contains(job) &&
((ExtensionInfo) extInfo).manifestContains(job.source().path()))
{
return null;
}
return CheckASTForErrors(job);
}
}.intern(this);
}
}
protected Goal codegenPrereq(Job job) {
return InnerClassRemover(job);
}
public Goal CodeGenBarrier() {
String name = "CodeGenBarrier";
if (extInfo.getOptions().compile_command_line_only) {
return new BarrierGoal(name, commandLineJobs()) {
private static final long serialVersionUID = 2258041064037983928L;
@Override
public Goal prereqForJob(Job job) {
return codegenPrereq(job);
}
}.intern(this);
}
else {
return new AllBarrierGoal(name, this) {
private static final long serialVersionUID = 4089824072381830523L;
@Override
public Goal prereqForJob(Job job) {
if (!super.scheduler.commandLineJobs().contains(job) &&
((ExtensionInfo) extInfo).manifestContains(job.source().path()))
{
return null;
}
return codegenPrereq(job);
}
}.intern(this);
}
}
public Goal CheckASTForErrors(Job job) {
return new SourceGoal_c("CheckASTForErrors", job) {
private static final long serialVersionUID = 565345690079406384L;
public boolean runTask() {
if (job.reportedErrors()) {
Node ast = job.ast();
job.ast(((X10Ext)ast.ext()).setSubtreeValid(false));
}
return true;
}
}.intern(this);
}
public Goal Serialized(Job job) {
Compiler compiler = job.extensionInfo().compiler();
TypeSystem ts = job.extensionInfo().typeSystem();
NodeFactory nf = job.extensionInfo().nodeFactory();
TargetFactory tf = job.extensionInfo().targetFactory();
return new SourceGoal_c("Serialized", job) {
private static final long serialVersionUID = 4813624372034550114L;
public boolean runTask() {
return true;
}
}.intern(this);
}
// @Override
// public Goal ImportTableInitialized(Job job) {
// TypeSystem ts = job.extensionInfo().typeSystem();
// NodeFactory nf = job.extensionInfo().nodeFactory();
// Goal g = new VisitorGoal("ImportTableInitialized", job, new X10InitImportsVisitor(job, ts, nf));
// Goal g2 = g.intern(this);
// if (g == g2) {
// g.addPrereq(TypesInitializedForCommandLine());
// }
// return g2;
// }
public Goal LoadPlugins() {
return new LoadPlugins((ExtensionInfo) extInfo).intern(this);
}
public Goal LoadJobPlugins(Job job) {
return new LoadJobPlugins(job).intern(this);
}
public Goal RegisterPlugins(Job job) {
Goal g = new RegisterPlugins(job);
Goal g2 = g.intern(this);
if (g == g2) {
g.addPrereq(LoadPlugins());
}
return g2;
}
public Goal PropagateAnnotations(Job job) {
// ###
return new VisitorGoal("PropagateAnnotations", job, new PruningVisitor()).intern(this);
}
@Override
public Goal InitializationsChecked(Job job) {
TypeSystem ts = job.extensionInfo().typeSystem();
NodeFactory nf = job.extensionInfo().nodeFactory();
return new ForgivingVisitorGoal("InitializationsChecked", job, new InitChecker(job, ts, nf)).intern(this);
}
public static class ValidatingOutputGoal extends OutputGoal {
private static final long serialVersionUID = -7021152686342225925L;
public ValidatingOutputGoal(Job job, Translator translator) {
super(job, translator);
}
public boolean runTask() {
Node ast = job().ast();
if (ast != null && !((X10Ext)ast.ext()).subtreeValid()) {
return false;
}
return super.runTask();
}
}
@Override
public Goal CodeGenerated(Job job) {
TypeSystem ts = extInfo.typeSystem();
NodeFactory nf = extInfo.nodeFactory();
Goal cg = new ValidatingOutputGoal(job, new X10Translator(job, ts, nf, extInfo.targetFactory()));
Goal cg2 = cg.intern(this);
return cg2;
}
static class X10ParserGoal extends ParserGoal {
private static final long serialVersionUID = 6811976416160592748L;
public X10ParserGoal(Compiler compiler, Job job) {
super(compiler, job);
}
@Override
protected SourceFile createDummyAST() {
NodeFactory nf = job().extensionInfo().nodeFactory();
String fName = job.source().name();
Position pos = new Position("", job.source().path(), 1, 1);
String name = fName.substring(fName.lastIndexOf(File.separatorChar)+1, fName.lastIndexOf('.'));
TopLevelDecl decl = nf.ClassDecl(pos, nf.FlagsNode(pos, Flags.PUBLIC),
nf.Id(pos, name), null, Collections.<TypeNode>emptyList(),
nf.ClassBody(pos, Collections.<ClassMember>emptyList()));
SourceFile ast = nf.SourceFile(pos, Collections.singletonList(decl)).source(job.source());
return ast;
}
}
@Override
public Goal Parsed(Job job) {
return new X10ParserGoal(extInfo.compiler(), job).intern(this);
}
@Override
public Goal constructTypesInitialized(Job job) {
TypeSystem ts = job.extensionInfo().typeSystem();
NodeFactory nf = job.extensionInfo().nodeFactory();
return new ForgivingVisitorGoal("TypesInitialized", job, new X10TypeBuilder(job, ts, nf)).intern(this);
}
public Goal X10MLTypeChecked(Job job) {
TypeSystem ts = extInfo.typeSystem();
NodeFactory nf = extInfo.nodeFactory();
return new VisitorGoal("X10MLTypeChecked", job, new X10MLVerifier(job, ts, nf)).intern(this);
}
@Override
public Goal TypeChecked(Job job) {
TypeSystem ts = job.extensionInfo().typeSystem();
NodeFactory nf = job.extensionInfo().nodeFactory();
return new ForgivingVisitorGoal("TypeChecked", job, new X10TypeChecker(job, ts, nf, job.nodeMemo())).intern(this);
}
public Goal ConformanceChecked(Job job) {
TypeSystem ts = job.extensionInfo().typeSystem();
NodeFactory nf = job.extensionInfo().nodeFactory();
return new ForgivingVisitorGoal("ConformanceChecked", job, new ConformanceChecker(job, ts, nf)).intern(this);
}
public Goal ReachabilityChecked(Job job) {
TypeSystem ts = job.extensionInfo().typeSystem();
NodeFactory nf = job.extensionInfo().nodeFactory();
return new ForgivingVisitorGoal("ReachChecked", job, new ReachChecker(job, ts, nf)).intern(this);
}
public Goal ExceptionsChecked(Job job) {
TypeSystem ts = job.extensionInfo().typeSystem();
NodeFactory nf = job.extensionInfo().nodeFactory();
return new ForgivingVisitorGoal("ExceptionsChecked", job, new ExceptionChecker(job, ts, nf)).intern(this);
}
public Goal ExitPathsChecked(Job job) {
TypeSystem ts = job.extensionInfo().typeSystem();
NodeFactory nf = job.extensionInfo().nodeFactory();
return new ForgivingVisitorGoal("ExitChecked", job, new ExitChecker(job, ts, nf)).intern(this);
}
public Goal ConstructorCallsChecked(Job job) {
TypeSystem ts = job.extensionInfo().typeSystem();
NodeFactory nf = job.extensionInfo().nodeFactory();
return new ForgivingVisitorGoal("ContructorCallsChecked", job, new ConstructorCallChecker(job, ts, nf)).intern(this);
}
public Goal ForwardReferencesChecked(Job job) {
TypeSystem ts = job.extensionInfo().typeSystem();
NodeFactory nf = job.extensionInfo().nodeFactory();
return new ForgivingVisitorGoal("ForwardRefsChecked", job, new FwdReferenceChecker(job, ts, nf)).intern(this);
}
public Goal CheckEscapingThis(Job job) {
return new VisitorGoal("CheckEscapingThis", job, new CheckEscapingThis.Main(job)).intern(this);
}
public String nativeAnnotationLanguage() { return "java"; }
public Goal CheckNativeAnnotations(Job job) {
TypeSystem ts = extInfo.typeSystem();
NodeFactory nf = extInfo.nodeFactory();
return new VisitorGoal("CheckNativeAnnotations", job, new CheckNativeAnnotationsVisitor(job, ts, nf, nativeAnnotationLanguage())).intern(this);
}
public static class ValidatingVisitorGoal extends VisitorGoal {
private static final long serialVersionUID = 5119557747721488612L;
public ValidatingVisitorGoal(String name, Job job, NodeVisitor v) {
super(name, job, v);
}
public boolean runTask() {
Node ast = job().ast();
if (ast != null && !((X10Ext)ast.ext()).subtreeValid()) {
//Warnings.issue(job(), "Invalid Visitor Goal: " +this.name()+ ", visitor: " +this.visitor(), Position.COMPILER_GENERATED);
return true;
}
return super.runTask();
}
}
public Goal X10Casted(Job job) {
TypeSystem ts = extInfo.typeSystem();
NodeFactory nf = extInfo.nodeFactory();
return new ValidatingVisitorGoal("X10Casted", job, new X10Caster(job, ts, nf)).intern(this);
}
public Goal MoveFieldInitializers(Job job) {
TypeSystem ts = extInfo.typeSystem();
NodeFactory nf = extInfo.nodeFactory();
return new ValidatingVisitorGoal("MoveFieldInitializers", job, new FieldInitializerMover(job, ts, nf)).intern(this);
}
public Goal X10RewriteAtomicMethods(Job job) {
TypeSystem ts = extInfo.typeSystem();
NodeFactory nf = extInfo.nodeFactory();
return new ValidatingVisitorGoal("X10RewriteAtomicMethods", job, new RewriteAtomicMethodVisitor(job, ts, nf)).intern(this);
}
public Goal X10Expanded(Job job) {
TypeSystem ts = extInfo.typeSystem();
NodeFactory nf = extInfo.nodeFactory();
return new ValidatingVisitorGoal("X10Expanded", job, new X10ImplicitDeclarationExpander(job, ts, nf)).intern(this);
}
public Goal NativeClassVisitor(Job job) {
TypeSystem ts = extInfo.typeSystem();
NodeFactory nf = extInfo.nodeFactory();
return new ValidatingVisitorGoal("NativeClassVisitor", job, new NativeClassVisitor(job, ts, nf, nativeAnnotationLanguage())).intern(this);
}
public Goal MainMethodFinder(Job job, Method hasMain) {
TypeSystem ts = extInfo.typeSystem();
NodeFactory nf = extInfo.nodeFactory();
return new ValidatingVisitorGoal("MainMethodFinder", job, new MainMethodFinder(job, ts, nf, hasMain)).intern(this);
}
public Goal WSCallGraphBarrier() {
final TypeSystem ts = extInfo.typeSystem();
final NodeFactory nf = extInfo.nodeFactory();
return new AllBarrierGoal("WSCallGraphBarrier", this) {
@Override
public Goal prereqForJob(Job job) {
return TypeChecked(job);
}
@Override
public boolean runTask() {
WSCodeGenerator.buildCallGraph(ts, nf, nativeAnnotationLanguage());
return true;
}
}.intern(this);
}
public Goal WSCodeGenerator(Job job) {
TypeSystem ts = extInfo.typeSystem();
NodeFactory nf = extInfo.nodeFactory();
return new ValidatingVisitorGoal("WSCodeGenerator", job, new WSCodeGenerator(job, ts, nf)).intern(this);
}
public Goal Desugarer(Job job) {
TypeSystem ts = extInfo.typeSystem();
NodeFactory nf = extInfo.nodeFactory();
return new ValidatingVisitorGoal("Desugarer", job, new Desugarer(job, ts, nf)).intern(this);
}
public Goal Lowerer(Job job) {
TypeSystem ts = extInfo.typeSystem();
NodeFactory nf = extInfo.nodeFactory();
return new ValidatingVisitorGoal("Lowerer", job, new Lowerer(job, ts, nf)).intern(this);
}
public Goal WSExpressionFlattener(Job job) {
TypeSystem ts = extInfo.typeSystem();
NodeFactory nf = extInfo.nodeFactory();
VisitorGoal ef = new ValidatingVisitorGoal("WorkStealing ExpressionFlattener", job, new ExpressionFlattener(job, ts, nf));
Goal ef2 = ef.intern(this);
if (ef == ef2) {
ef.addPrereq(Serialized(job));
}
return ef2;
}
public Goal InnerClassRemover(Job job) {
TypeSystem ts = extInfo.typeSystem();
NodeFactory nf = extInfo.nodeFactory();
return new ValidatingVisitorGoal("InnerClassRemover", job, new X10InnerClassRemover(job, ts, nf)).intern(this);
}
public Goal StaticNestedClassRemover(Job job) {
TypeSystem ts = extInfo.typeSystem();
NodeFactory nf = extInfo.nodeFactory();
return new ValidatingVisitorGoal("StaticNestedClassRemover", job, new StaticNestedClassRemover(job, ts, nf)).intern(this);
}
public Goal FinishAsyncBarrier(final Goal goal, final Job job, final Scheduler s) {
return new AllBarrierGoal("FinishAsyncBarrier", this) {
private static final long serialVersionUID = -4172220184246138069L;
@Override
public Goal prereqForJob(Job job) {
//TODO: probably need to also annotation code in "runtime"
if (!super.scheduler.commandLineJobs().contains(job) &&
((ExtensionInfo) extInfo).manifestContains(job.source().path())) {
return null;
}
return goal;
}
public boolean runTask() {
try {
TypeSystem ts = extInfo.typeSystem();
NodeFactory nf = extInfo.nodeFactory();
// FinishAsyncVisitor favisitor = new FinishAsyncVisitor(job, ts, nf, nativeAnnotationLanguage(), calltable);
// Goal finish = new ValidatingVisitorGoal("FinishAsyncs", job, favisitor).intern(s);
// finish.runTask();
} catch (Throwable t) {}
return true;
}
}.intern(this);
}
public static class X10Job extends Job {
public X10Job(polyglot.frontend.ExtensionInfo lang, JobExt ext, Source source, Node ast) {
super(lang, ext, source, ast);
}
public int initialErrorCount() { return initialErrorCount; }
public void initialErrorCount(int count) { initialErrorCount = count; }
}
@Override
protected Job createSourceJob(Source source, Node ast) {
return new X10Job(extInfo, extInfo.jobExt(), source, ast);
}
@Override
protected boolean runPass(Goal goal) throws CyclicDependencyException {
Job job = goal instanceof SourceGoal ? ((SourceGoal) goal).job() : null;
int savedInitialErrorCount = -1;
if (job != null)
savedInitialErrorCount = ((X10Job) job).initialErrorCount();
boolean result = super.runPass(goal);
if (job != null)
((X10Job) job).initialErrorCount(savedInitialErrorCount);
return result;
}
}
protected Options createOptions() {
return new X10CompilerOptions(this);
}
public Map<QName,CompilerPlugin> plugins() {
if (plugins == null) {
return Collections.emptyMap();
}
return plugins;
}
public void addPlugin(QName pluginName, CompilerPlugin plugin) {
if (plugins == null) {
plugins = new HashMap<QName,CompilerPlugin>();
}
plugins.put(pluginName, plugin);
}
public CompilerPlugin getPlugin(QName pluginName) {
if (plugins == null) {
return null;
}
return plugins.get(pluginName);
}
}
| true | true | public List<Goal> goals(Job job) {
List<Goal> goals = new ArrayList<Goal>();
addValidateOnlyGoals(job, goals);
Goal endGoal = goals.remove(goals.size()-1);
if (!x10.Configuration.ONLY_TYPE_CHECKING) {
if (x10.Configuration.WALA || x10.Configuration.FINISH_ASYNCS) {
try{
ClassLoader cl = Thread.currentThread().getContextClassLoader();
Class<?> c = cl.loadClass("com.ibm.wala.cast.x10.translator.polyglot.X102IRGoal");
Constructor<?> con = c.getConstructor(Job.class);
Method hasMain = c.getMethod("hasMain", String.class);
Goal ir = ((Goal) con.newInstance(job)).intern(this);
goals.add(ir);
Goal finder = MainMethodFinder(job, hasMain);
finder.addPrereq(TypeCheckBarrier());
ir.addPrereq(finder);
Goal barrier;
if(x10.Configuration.FINISH_ASYNCS){
Method buildCallTableMethod = c.getMethod("analyze");
barrier = IRBarrier(ir, buildCallTableMethod);
} else {
Method printCallGraph = c.getMethod("printCallGraph");
barrier = IRBarrier(ir, printCallGraph);
}
goals.add(barrier);
goals.add(FinishAsyncBarrier(barrier,job,this));
} catch (Throwable e) {
System.err.println("WALA not found.");
e.printStackTrace();
}
}
goals.add(Desugarer(job));
goals.add(X10Casted(job));
goals.add(MoveFieldInitializers(job));
goals.add(X10Expanded(job));
goals.add(X10RewriteAtomicMethods(job));
goals.add(NativeClassVisitor(job));
goals.add(Serialized(job));
if (x10.Configuration.WORK_STEALING) {
Goal wsCodeGenGoal = WSCodeGenerator(job);
goals.add(wsCodeGenGoal);
wsCodeGenGoal.addPrereq(WSCallGraphBarrier());
}
goals.add(Preoptimization(job));
goals.addAll(Optimizer.goals(this, job));
goals.add(Postoptimization(job));
goals.add(Lowerer(job));
goals.add(InnerClassRemover(job)); // TODO: move earlier
goals.add(CodeGenerated(job));
InnerClassRemover(job).addPrereq(Serialized(job));
InnerClassRemover(job).addPrereq(TypeCheckBarrier());
// the barrier will handle prereqs on its own
Desugarer(job).addPrereq(TypeCheckBarrier());
CodeGenerated(job).addPrereq(CodeGenBarrier());
Lowerer(job).addPrereq(TypeCheckBarrier());
CodeGenerated(job).addPrereq(Lowerer(job));
List<Goal> optimizations = Optimizer.goals(this, job);
for (Goal goal : optimizations) {
goal.addPrereq(TypeCheckBarrier());
CodeGenerated(job).addPrereq(goal);
}
}
goals.add(endGoal);
if (x10.Configuration.CHECK_INVARIANTS) {
ArrayList<Goal> newGoals = new ArrayList<Goal>(goals.size()*2);
boolean reachedTypeChecking = false;
int ctr = 0;
for (Goal g : goals) {
newGoals.add(g);
if (!reachedTypeChecking)
newGoals.add(new VisitorGoal("PositionInvariantChecker"+(ctr++), job, new PositionInvariantChecker(job, g.name())).intern(this));
if (g==TypeChecked(job)) {
newGoals.add(new VisitorGoal("InstanceInvariantChecker", job, new InstanceInvariantChecker(job)).intern(this));
reachedTypeChecking = true;
}
}
goals = newGoals;
}
return goals;
}
| public List<Goal> goals(Job job) {
List<Goal> goals = new ArrayList<Goal>();
addValidateOnlyGoals(job, goals);
Goal endGoal = goals.remove(goals.size()-1);
if (!x10.Configuration.ONLY_TYPE_CHECKING) {
if (x10.Configuration.WALA || x10.Configuration.FINISH_ASYNCS) {
try{
ClassLoader cl = Thread.currentThread().getContextClassLoader();
Class<?> c = cl.loadClass("com.ibm.wala.cast.x10.translator.X102IRGoal");
Constructor<?> con = c.getConstructor(Job.class);
Method hasMain = c.getMethod("hasMain", String.class);
Goal ir = ((Goal) con.newInstance(job)).intern(this);
goals.add(ir);
Goal finder = MainMethodFinder(job, hasMain);
finder.addPrereq(TypeCheckBarrier());
ir.addPrereq(finder);
Goal barrier;
if(x10.Configuration.FINISH_ASYNCS){
Method buildCallTableMethod = c.getMethod("analyze");
barrier = IRBarrier(ir, buildCallTableMethod);
} else {
Method printCallGraph = c.getMethod("printCallGraph");
barrier = IRBarrier(ir, printCallGraph);
}
goals.add(barrier);
goals.add(FinishAsyncBarrier(barrier,job,this));
} catch (Throwable e) {
System.err.println("WALA not found.");
e.printStackTrace();
}
}
goals.add(Desugarer(job));
goals.add(X10Casted(job));
goals.add(MoveFieldInitializers(job));
goals.add(X10Expanded(job));
goals.add(X10RewriteAtomicMethods(job));
goals.add(NativeClassVisitor(job));
goals.add(Serialized(job));
if (x10.Configuration.WORK_STEALING) {
Goal wsCodeGenGoal = WSCodeGenerator(job);
goals.add(wsCodeGenGoal);
wsCodeGenGoal.addPrereq(WSCallGraphBarrier());
}
goals.add(Preoptimization(job));
goals.addAll(Optimizer.goals(this, job));
goals.add(Postoptimization(job));
goals.add(Lowerer(job));
goals.add(InnerClassRemover(job)); // TODO: move earlier
goals.add(CodeGenerated(job));
InnerClassRemover(job).addPrereq(Serialized(job));
InnerClassRemover(job).addPrereq(TypeCheckBarrier());
// the barrier will handle prereqs on its own
Desugarer(job).addPrereq(TypeCheckBarrier());
CodeGenerated(job).addPrereq(CodeGenBarrier());
Lowerer(job).addPrereq(TypeCheckBarrier());
CodeGenerated(job).addPrereq(Lowerer(job));
List<Goal> optimizations = Optimizer.goals(this, job);
for (Goal goal : optimizations) {
goal.addPrereq(TypeCheckBarrier());
CodeGenerated(job).addPrereq(goal);
}
}
goals.add(endGoal);
if (x10.Configuration.CHECK_INVARIANTS) {
ArrayList<Goal> newGoals = new ArrayList<Goal>(goals.size()*2);
boolean reachedTypeChecking = false;
int ctr = 0;
for (Goal g : goals) {
newGoals.add(g);
if (!reachedTypeChecking)
newGoals.add(new VisitorGoal("PositionInvariantChecker"+(ctr++), job, new PositionInvariantChecker(job, g.name())).intern(this));
if (g==TypeChecked(job)) {
newGoals.add(new VisitorGoal("InstanceInvariantChecker", job, new InstanceInvariantChecker(job)).intern(this));
reachedTypeChecking = true;
}
}
goals = newGoals;
}
return goals;
}
|
diff --git a/modules/activiti-engine/src/main/java/org/activiti/engine/impl/pvm/runtime/AtomicOperationTransitionDestroyScope.java b/modules/activiti-engine/src/main/java/org/activiti/engine/impl/pvm/runtime/AtomicOperationTransitionDestroyScope.java
index 487f6a69e..6da6b05e6 100644
--- a/modules/activiti-engine/src/main/java/org/activiti/engine/impl/pvm/runtime/AtomicOperationTransitionDestroyScope.java
+++ b/modules/activiti-engine/src/main/java/org/activiti/engine/impl/pvm/runtime/AtomicOperationTransitionDestroyScope.java
@@ -1,123 +1,123 @@
/* 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.activiti.engine.impl.pvm.runtime;
import java.util.List;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.impl.pvm.process.ScopeImpl;
import org.activiti.engine.impl.pvm.process.TransitionImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Tom Baeyens
*/
public class AtomicOperationTransitionDestroyScope implements AtomicOperation {
private static Logger log = LoggerFactory.getLogger(AtomicOperationTransitionDestroyScope.class);
public boolean isAsync(InterpretableExecution execution) {
return false;
}
@SuppressWarnings("unchecked")
public void execute(InterpretableExecution execution) {
InterpretableExecution propagatingExecution = null;
ActivityImpl activity = (ActivityImpl) execution.getActivity();
// if this transition is crossing a scope boundary
if (activity.isScope()) {
InterpretableExecution parentScopeInstance = null;
// if this is a concurrent execution crossing a scope boundary
if (execution.isConcurrent() && !execution.isScope()) {
// first remove the execution from the current root
InterpretableExecution concurrentRoot = (InterpretableExecution) execution.getParent();
parentScopeInstance = (InterpretableExecution) execution.getParent().getParent();
log.debug("moving concurrent {} one scope up under {}", execution, parentScopeInstance);
List<InterpretableExecution> parentScopeInstanceExecutions = (List<InterpretableExecution>) parentScopeInstance.getExecutions();
List<InterpretableExecution> concurrentRootExecutions = (List<InterpretableExecution>) concurrentRoot.getExecutions();
// if the parent scope had only one single scope child
if (parentScopeInstanceExecutions.size()==1) {
// it now becomes a concurrent execution
parentScopeInstanceExecutions.get(0).setConcurrent(true);
}
concurrentRootExecutions.remove(execution);
parentScopeInstanceExecutions.add(execution);
execution.setParent(parentScopeInstance);
execution.setActivity(activity);
propagatingExecution = execution;
// if there is only a single concurrent execution left
// in the concurrent root, auto-prune it. meaning, the
// last concurrent child execution data should be cloned into
// the concurrent root.
if (concurrentRootExecutions.size()==1) {
InterpretableExecution lastConcurrent = concurrentRootExecutions.get(0);
if (lastConcurrent.isScope()) {
lastConcurrent.setConcurrent(false);
} else {
log.debug("merging last concurrent {} into concurrent root {}", lastConcurrent, concurrentRoot);
// We can't just merge the data of the lastConcurrent into the concurrentRoot.
// This is because the concurrent root might be in a takeAll-loop. So the
- // concurrent execution is the one that will be receiveing the take
+ // concurrent execution is the one that will be receiving the take
concurrentRoot.setActivity((ActivityImpl) lastConcurrent.getActivity());
concurrentRoot.setActive(lastConcurrent.isActive());
lastConcurrent.setReplacedBy(concurrentRoot);
lastConcurrent.remove();
}
}
} else if (execution.isConcurrent() && execution.isScope()) {
log.debug("scoped concurrent {} becomes concurrent and remains under {}", execution, execution.getParent());
// TODO!
execution.destroy();
propagatingExecution = execution;
} else {
propagatingExecution = (InterpretableExecution) execution.getParent();
propagatingExecution.setActivity((ActivityImpl) execution.getActivity());
propagatingExecution.setTransition(execution.getTransition());
propagatingExecution.setActive(true);
log.debug("destroy scope: scoped {} continues as parent scope {}", execution, propagatingExecution);
execution.destroy();
execution.remove();
}
} else {
propagatingExecution = execution;
}
// if there is another scope element that is ended
ScopeImpl nextOuterScopeElement = activity.getParent();
TransitionImpl transition = propagatingExecution.getTransition();
ActivityImpl destination = transition.getDestination();
if (transitionLeavesNextOuterScope(nextOuterScopeElement, destination)) {
propagatingExecution.setActivity((ActivityImpl) nextOuterScopeElement);
propagatingExecution.performOperation(TRANSITION_NOTIFY_LISTENER_END);
} else {
propagatingExecution.performOperation(TRANSITION_NOTIFY_LISTENER_TAKE);
}
}
public boolean transitionLeavesNextOuterScope(ScopeImpl nextScopeElement, ActivityImpl destination) {
return !nextScopeElement.contains(destination);
}
}
| true | true | public void execute(InterpretableExecution execution) {
InterpretableExecution propagatingExecution = null;
ActivityImpl activity = (ActivityImpl) execution.getActivity();
// if this transition is crossing a scope boundary
if (activity.isScope()) {
InterpretableExecution parentScopeInstance = null;
// if this is a concurrent execution crossing a scope boundary
if (execution.isConcurrent() && !execution.isScope()) {
// first remove the execution from the current root
InterpretableExecution concurrentRoot = (InterpretableExecution) execution.getParent();
parentScopeInstance = (InterpretableExecution) execution.getParent().getParent();
log.debug("moving concurrent {} one scope up under {}", execution, parentScopeInstance);
List<InterpretableExecution> parentScopeInstanceExecutions = (List<InterpretableExecution>) parentScopeInstance.getExecutions();
List<InterpretableExecution> concurrentRootExecutions = (List<InterpretableExecution>) concurrentRoot.getExecutions();
// if the parent scope had only one single scope child
if (parentScopeInstanceExecutions.size()==1) {
// it now becomes a concurrent execution
parentScopeInstanceExecutions.get(0).setConcurrent(true);
}
concurrentRootExecutions.remove(execution);
parentScopeInstanceExecutions.add(execution);
execution.setParent(parentScopeInstance);
execution.setActivity(activity);
propagatingExecution = execution;
// if there is only a single concurrent execution left
// in the concurrent root, auto-prune it. meaning, the
// last concurrent child execution data should be cloned into
// the concurrent root.
if (concurrentRootExecutions.size()==1) {
InterpretableExecution lastConcurrent = concurrentRootExecutions.get(0);
if (lastConcurrent.isScope()) {
lastConcurrent.setConcurrent(false);
} else {
log.debug("merging last concurrent {} into concurrent root {}", lastConcurrent, concurrentRoot);
// We can't just merge the data of the lastConcurrent into the concurrentRoot.
// This is because the concurrent root might be in a takeAll-loop. So the
// concurrent execution is the one that will be receiveing the take
concurrentRoot.setActivity((ActivityImpl) lastConcurrent.getActivity());
concurrentRoot.setActive(lastConcurrent.isActive());
lastConcurrent.setReplacedBy(concurrentRoot);
lastConcurrent.remove();
}
}
} else if (execution.isConcurrent() && execution.isScope()) {
log.debug("scoped concurrent {} becomes concurrent and remains under {}", execution, execution.getParent());
// TODO!
execution.destroy();
propagatingExecution = execution;
} else {
propagatingExecution = (InterpretableExecution) execution.getParent();
propagatingExecution.setActivity((ActivityImpl) execution.getActivity());
propagatingExecution.setTransition(execution.getTransition());
propagatingExecution.setActive(true);
log.debug("destroy scope: scoped {} continues as parent scope {}", execution, propagatingExecution);
execution.destroy();
execution.remove();
}
} else {
propagatingExecution = execution;
}
// if there is another scope element that is ended
ScopeImpl nextOuterScopeElement = activity.getParent();
TransitionImpl transition = propagatingExecution.getTransition();
ActivityImpl destination = transition.getDestination();
if (transitionLeavesNextOuterScope(nextOuterScopeElement, destination)) {
propagatingExecution.setActivity((ActivityImpl) nextOuterScopeElement);
propagatingExecution.performOperation(TRANSITION_NOTIFY_LISTENER_END);
} else {
propagatingExecution.performOperation(TRANSITION_NOTIFY_LISTENER_TAKE);
}
}
| public void execute(InterpretableExecution execution) {
InterpretableExecution propagatingExecution = null;
ActivityImpl activity = (ActivityImpl) execution.getActivity();
// if this transition is crossing a scope boundary
if (activity.isScope()) {
InterpretableExecution parentScopeInstance = null;
// if this is a concurrent execution crossing a scope boundary
if (execution.isConcurrent() && !execution.isScope()) {
// first remove the execution from the current root
InterpretableExecution concurrentRoot = (InterpretableExecution) execution.getParent();
parentScopeInstance = (InterpretableExecution) execution.getParent().getParent();
log.debug("moving concurrent {} one scope up under {}", execution, parentScopeInstance);
List<InterpretableExecution> parentScopeInstanceExecutions = (List<InterpretableExecution>) parentScopeInstance.getExecutions();
List<InterpretableExecution> concurrentRootExecutions = (List<InterpretableExecution>) concurrentRoot.getExecutions();
// if the parent scope had only one single scope child
if (parentScopeInstanceExecutions.size()==1) {
// it now becomes a concurrent execution
parentScopeInstanceExecutions.get(0).setConcurrent(true);
}
concurrentRootExecutions.remove(execution);
parentScopeInstanceExecutions.add(execution);
execution.setParent(parentScopeInstance);
execution.setActivity(activity);
propagatingExecution = execution;
// if there is only a single concurrent execution left
// in the concurrent root, auto-prune it. meaning, the
// last concurrent child execution data should be cloned into
// the concurrent root.
if (concurrentRootExecutions.size()==1) {
InterpretableExecution lastConcurrent = concurrentRootExecutions.get(0);
if (lastConcurrent.isScope()) {
lastConcurrent.setConcurrent(false);
} else {
log.debug("merging last concurrent {} into concurrent root {}", lastConcurrent, concurrentRoot);
// We can't just merge the data of the lastConcurrent into the concurrentRoot.
// This is because the concurrent root might be in a takeAll-loop. So the
// concurrent execution is the one that will be receiving the take
concurrentRoot.setActivity((ActivityImpl) lastConcurrent.getActivity());
concurrentRoot.setActive(lastConcurrent.isActive());
lastConcurrent.setReplacedBy(concurrentRoot);
lastConcurrent.remove();
}
}
} else if (execution.isConcurrent() && execution.isScope()) {
log.debug("scoped concurrent {} becomes concurrent and remains under {}", execution, execution.getParent());
// TODO!
execution.destroy();
propagatingExecution = execution;
} else {
propagatingExecution = (InterpretableExecution) execution.getParent();
propagatingExecution.setActivity((ActivityImpl) execution.getActivity());
propagatingExecution.setTransition(execution.getTransition());
propagatingExecution.setActive(true);
log.debug("destroy scope: scoped {} continues as parent scope {}", execution, propagatingExecution);
execution.destroy();
execution.remove();
}
} else {
propagatingExecution = execution;
}
// if there is another scope element that is ended
ScopeImpl nextOuterScopeElement = activity.getParent();
TransitionImpl transition = propagatingExecution.getTransition();
ActivityImpl destination = transition.getDestination();
if (transitionLeavesNextOuterScope(nextOuterScopeElement, destination)) {
propagatingExecution.setActivity((ActivityImpl) nextOuterScopeElement);
propagatingExecution.performOperation(TRANSITION_NOTIFY_LISTENER_END);
} else {
propagatingExecution.performOperation(TRANSITION_NOTIFY_LISTENER_TAKE);
}
}
|
diff --git a/src/fi/helsinki/cs/scheduler3000/cli/NewSchedule.java b/src/fi/helsinki/cs/scheduler3000/cli/NewSchedule.java
index 0a3fd09..5a38e0e 100644
--- a/src/fi/helsinki/cs/scheduler3000/cli/NewSchedule.java
+++ b/src/fi/helsinki/cs/scheduler3000/cli/NewSchedule.java
@@ -1,62 +1,62 @@
package fi.helsinki.cs.scheduler3000.cli;
import java.util.ArrayList;
import fi.helsinki.cs.scheduler3000.model.Schedule;
import fi.helsinki.cs.scheduler3000.model.Weekday.Day;
public class NewSchedule extends CliCommand {
NewSchedule(Schedule schedule) {
this.schedule = schedule;
}
void run() {
newScheduleDialog();
}
private void newScheduleDialog() {
String in = "";
ArrayList<Day> dates = new ArrayList<Day>();
System.out.println("Enter the period this schedule is for:");
printPrompt();
String period = input.nextLine();
System.out.println("Give dates you want to include in the scedule");
System.out.println("Stop giving the dates by entering \""+endCommand+"\"");
System.out.println("One at a time, please");
- while( in.toLowerCase().equals(endCommand) ) {
+ while( !in.toLowerCase().equals(endCommand) ) {
Helpers.printDates();
Helpers.printSelection(dates);
printPrompt();
in = input.nextLine().trim();
try {
Day day = Helpers.getDay( in.trim() );
dates.add(day);
} catch (Exception e) {
System.out.println("Invalid date given");
}
}
System.out.print("Creating schedule...");
this.excecute(period, dates );
System.out.println("ok!");
}
private void excecute(String period, ArrayList<Day> dates) {
// TODO: Fixme! Uusi tapahtuma on nyt luotu tuolla CLIssä -> rumaa.
this.schedule.setPeriod(period);
this.schedule.setDays(dates);
}
}
| true | true | private void newScheduleDialog() {
String in = "";
ArrayList<Day> dates = new ArrayList<Day>();
System.out.println("Enter the period this schedule is for:");
printPrompt();
String period = input.nextLine();
System.out.println("Give dates you want to include in the scedule");
System.out.println("Stop giving the dates by entering \""+endCommand+"\"");
System.out.println("One at a time, please");
while( in.toLowerCase().equals(endCommand) ) {
Helpers.printDates();
Helpers.printSelection(dates);
printPrompt();
in = input.nextLine().trim();
try {
Day day = Helpers.getDay( in.trim() );
dates.add(day);
} catch (Exception e) {
System.out.println("Invalid date given");
}
}
System.out.print("Creating schedule...");
this.excecute(period, dates );
System.out.println("ok!");
}
| private void newScheduleDialog() {
String in = "";
ArrayList<Day> dates = new ArrayList<Day>();
System.out.println("Enter the period this schedule is for:");
printPrompt();
String period = input.nextLine();
System.out.println("Give dates you want to include in the scedule");
System.out.println("Stop giving the dates by entering \""+endCommand+"\"");
System.out.println("One at a time, please");
while( !in.toLowerCase().equals(endCommand) ) {
Helpers.printDates();
Helpers.printSelection(dates);
printPrompt();
in = input.nextLine().trim();
try {
Day day = Helpers.getDay( in.trim() );
dates.add(day);
} catch (Exception e) {
System.out.println("Invalid date given");
}
}
System.out.print("Creating schedule...");
this.excecute(period, dates );
System.out.println("ok!");
}
|
diff --git a/webit-script/src/main/java/webit/script/core/ast/expressions/ArrayValue.java b/webit-script/src/main/java/webit/script/core/ast/expressions/ArrayValue.java
index d06599b4..7783f200 100644
--- a/webit-script/src/main/java/webit/script/core/ast/expressions/ArrayValue.java
+++ b/webit-script/src/main/java/webit/script/core/ast/expressions/ArrayValue.java
@@ -1,32 +1,33 @@
// Copyright (c) 2013, Webit Team. All Rights Reserved.
package webit.script.core.ast.expressions;
import webit.script.Context;
import webit.script.core.ast.AbstractExpression;
import webit.script.core.ast.Expression;
import webit.script.util.StatmentUtil;
/**
*
* @author Zqq
*/
public final class ArrayValue extends AbstractExpression {
private final Expression[] valueExprs;
public ArrayValue(Expression[] valueExprs, int line, int column) {
super(line, column);
this.valueExprs = valueExprs;
}
public Object execute(final Context context) {
final Expression[] valueExprs;
final int len;
final Object[] value = new Object[len = (valueExprs = this.valueExprs).length];
int i = 0;
while (i < len) {
- value[i++] = StatmentUtil.execute(valueExprs[i], context);
+ value[i] = StatmentUtil.execute(valueExprs[i], context);
+ i++;
}
return value;
}
}
| true | true | public Object execute(final Context context) {
final Expression[] valueExprs;
final int len;
final Object[] value = new Object[len = (valueExprs = this.valueExprs).length];
int i = 0;
while (i < len) {
value[i++] = StatmentUtil.execute(valueExprs[i], context);
}
return value;
}
| public Object execute(final Context context) {
final Expression[] valueExprs;
final int len;
final Object[] value = new Object[len = (valueExprs = this.valueExprs).length];
int i = 0;
while (i < len) {
value[i] = StatmentUtil.execute(valueExprs[i], context);
i++;
}
return value;
}
|
diff --git a/nexus/nexus-proxy/src/main/java/org/sonatype/nexus/proxy/access/AbstractPropertiesFileBasedAccessDecisionVoter.java b/nexus/nexus-proxy/src/main/java/org/sonatype/nexus/proxy/access/AbstractPropertiesFileBasedAccessDecisionVoter.java
index 7f4a12726..0697ddf63 100644
--- a/nexus/nexus-proxy/src/main/java/org/sonatype/nexus/proxy/access/AbstractPropertiesFileBasedAccessDecisionVoter.java
+++ b/nexus/nexus-proxy/src/main/java/org/sonatype/nexus/proxy/access/AbstractPropertiesFileBasedAccessDecisionVoter.java
@@ -1,101 +1,117 @@
package org.sonatype.nexus.proxy.access;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public abstract class AbstractPropertiesFileBasedAccessDecisionVoter
extends AbstractAccessDecisionVoter
{
public static final String PARAM_PROPERTIES_FILE_PATH = "propertiesFilePath";
/** The properties base. */
private Properties properties;
/**
* Gets the properties path.
*
* @return the properties path
*/
public String getPropertiesPath()
{
return getConfigurationValue( PARAM_PROPERTIES_FILE_PATH );
}
/**
* Gets the properties.
*
* @return the properties
*/
public Properties getProperties()
{
if ( properties == null )
{
try
{
properties = loadProperties( getPropertiesPath() );
}
catch ( IOException e )
{
throw new IllegalArgumentException( "Could not initialize voter!", e );
}
}
return properties;
}
/**
* Load properties.
*
* @param resource the resource
* @throws IOException Signals that an I/O exception has occurred.
*/
protected Properties loadProperties( String resource )
throws IOException
{
if ( resource == null )
{
throw new IllegalArgumentException( "Authorization source properties file path cannot be 'null'!" );
}
Properties result = new Properties();
File resourceFile = null;
// try to get it acainst config dir
resourceFile = new File( getConfigurationDir(), resource );
if ( resourceFile.exists() )
{
- result.load( new FileInputStream( resourceFile ) );
+ FileInputStream fis = new FileInputStream( resourceFile );
+ try
+ {
+ result.load( fis );
+ }
+ finally
+ {
+ fis.close();
+ }
return result;
}
// First see if the resource is a valid file
resourceFile = new File( resource );
if ( resourceFile.exists() )
{
- result.load( new FileInputStream( resourceFile ) );
+ FileInputStream fis = new FileInputStream( resourceFile );
+ try
+ {
+ result.load( fis );
+ }
+ finally
+ {
+ fis.close();
+ }
return result;
}
// Otherwise try to load it from the classpath
InputStream is = getClass().getClassLoader().getResourceAsStream( resource );
if ( is != null )
{
result.load( is );
return result;
}
throw new IllegalArgumentException( "Authorization source cannot be loaded because it is not found on "
+ resource );
}
}
| false | true | protected Properties loadProperties( String resource )
throws IOException
{
if ( resource == null )
{
throw new IllegalArgumentException( "Authorization source properties file path cannot be 'null'!" );
}
Properties result = new Properties();
File resourceFile = null;
// try to get it acainst config dir
resourceFile = new File( getConfigurationDir(), resource );
if ( resourceFile.exists() )
{
result.load( new FileInputStream( resourceFile ) );
return result;
}
// First see if the resource is a valid file
resourceFile = new File( resource );
if ( resourceFile.exists() )
{
result.load( new FileInputStream( resourceFile ) );
return result;
}
// Otherwise try to load it from the classpath
InputStream is = getClass().getClassLoader().getResourceAsStream( resource );
if ( is != null )
{
result.load( is );
return result;
}
throw new IllegalArgumentException( "Authorization source cannot be loaded because it is not found on "
+ resource );
}
| protected Properties loadProperties( String resource )
throws IOException
{
if ( resource == null )
{
throw new IllegalArgumentException( "Authorization source properties file path cannot be 'null'!" );
}
Properties result = new Properties();
File resourceFile = null;
// try to get it acainst config dir
resourceFile = new File( getConfigurationDir(), resource );
if ( resourceFile.exists() )
{
FileInputStream fis = new FileInputStream( resourceFile );
try
{
result.load( fis );
}
finally
{
fis.close();
}
return result;
}
// First see if the resource is a valid file
resourceFile = new File( resource );
if ( resourceFile.exists() )
{
FileInputStream fis = new FileInputStream( resourceFile );
try
{
result.load( fis );
}
finally
{
fis.close();
}
return result;
}
// Otherwise try to load it from the classpath
InputStream is = getClass().getClassLoader().getResourceAsStream( resource );
if ( is != null )
{
result.load( is );
return result;
}
throw new IllegalArgumentException( "Authorization source cannot be loaded because it is not found on "
+ resource );
}
|
diff --git a/src/com/android/browser/FetchUrlMimeType.java b/src/com/android/browser/FetchUrlMimeType.java
index 07c9b936..33b58086 100644
--- a/src/com/android/browser/FetchUrlMimeType.java
+++ b/src/com/android/browser/FetchUrlMimeType.java
@@ -1,138 +1,139 @@
/*
* 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.browser;
import org.apache.http.Header;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.conn.params.ConnRouteParams;
import android.app.DownloadManager;
import android.content.Context;
import android.net.Proxy;
import android.net.http.AndroidHttpClient;
import android.os.Environment;
import android.util.Log;
import android.webkit.MimeTypeMap;
import android.webkit.URLUtil;
import java.io.IOException;
/**
* This class is used to pull down the http headers of a given URL so that
* we can analyse the mimetype and make any correction needed before we give
* the URL to the download manager.
* This operation is needed when the user long-clicks on a link or image and
* we don't know the mimetype. If the user just clicks on the link, we will
* do the same steps of correcting the mimetype down in
* android.os.webkit.LoadListener rather than handling it here.
*
*/
class FetchUrlMimeType extends Thread {
private final static String LOGTAG = "FetchUrlMimeType";
private Context mContext;
private DownloadManager.Request mRequest;
private String mUri;
private String mCookies;
private String mUserAgent;
public FetchUrlMimeType(Context context, DownloadManager.Request request,
String uri, String cookies, String userAgent) {
mContext = context.getApplicationContext();
mRequest = request;
mUri = uri;
mCookies = cookies;
mUserAgent = userAgent;
}
@Override
public void run() {
// User agent is likely to be null, though the AndroidHttpClient
// seems ok with that.
AndroidHttpClient client = AndroidHttpClient.newInstance(mUserAgent);
HttpHost httpHost;
try {
httpHost = Proxy.getPreferredHttpHost(mContext, mUri);
if (httpHost != null) {
ConnRouteParams.setDefaultProxy(client.getParams(), httpHost);
}
} catch (IllegalArgumentException ex) {
Log.e(LOGTAG,"Download failed: " + ex);
client.close();
return;
}
HttpHead request = new HttpHead(mUri);
if (mCookies != null && mCookies.length() > 0) {
request.addHeader("Cookie", mCookies);
}
HttpResponse response;
String mimeType = null;
String contentDisposition = null;
try {
response = client.execute(request);
// We could get a redirect here, but if we do lets let
// the download manager take care of it, and thus trust that
// the server sends the right mimetype
if (response.getStatusLine().getStatusCode() == 200) {
Header header = response.getFirstHeader("Content-Type");
if (header != null) {
mimeType = header.getValue();
final int semicolonIndex = mimeType.indexOf(';');
if (semicolonIndex != -1) {
mimeType = mimeType.substring(0, semicolonIndex);
}
}
Header contentDispositionHeader = response.getFirstHeader("Content-Disposition");
if (contentDispositionHeader != null) {
contentDisposition = contentDispositionHeader.getValue();
}
}
} catch (IllegalArgumentException ex) {
request.abort();
} catch (IOException ex) {
request.abort();
} finally {
client.close();
}
if (mimeType != null) {
if (mimeType.equalsIgnoreCase("text/plain") ||
mimeType.equalsIgnoreCase("application/octet-stream")) {
String newMimeType =
MimeTypeMap.getSingleton().getMimeTypeFromExtension(
MimeTypeMap.getFileExtensionFromUrl(mUri));
if (newMimeType != null) {
+ mimeType = newMimeType;
mRequest.setMimeType(newMimeType);
}
}
String filename = URLUtil.guessFileName(mUri, contentDisposition,
mimeType);
mRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename);
}
// Start the download
DownloadManager manager = (DownloadManager) mContext.getSystemService(
Context.DOWNLOAD_SERVICE);
manager.enqueue(mRequest);
}
}
| true | true | public void run() {
// User agent is likely to be null, though the AndroidHttpClient
// seems ok with that.
AndroidHttpClient client = AndroidHttpClient.newInstance(mUserAgent);
HttpHost httpHost;
try {
httpHost = Proxy.getPreferredHttpHost(mContext, mUri);
if (httpHost != null) {
ConnRouteParams.setDefaultProxy(client.getParams(), httpHost);
}
} catch (IllegalArgumentException ex) {
Log.e(LOGTAG,"Download failed: " + ex);
client.close();
return;
}
HttpHead request = new HttpHead(mUri);
if (mCookies != null && mCookies.length() > 0) {
request.addHeader("Cookie", mCookies);
}
HttpResponse response;
String mimeType = null;
String contentDisposition = null;
try {
response = client.execute(request);
// We could get a redirect here, but if we do lets let
// the download manager take care of it, and thus trust that
// the server sends the right mimetype
if (response.getStatusLine().getStatusCode() == 200) {
Header header = response.getFirstHeader("Content-Type");
if (header != null) {
mimeType = header.getValue();
final int semicolonIndex = mimeType.indexOf(';');
if (semicolonIndex != -1) {
mimeType = mimeType.substring(0, semicolonIndex);
}
}
Header contentDispositionHeader = response.getFirstHeader("Content-Disposition");
if (contentDispositionHeader != null) {
contentDisposition = contentDispositionHeader.getValue();
}
}
} catch (IllegalArgumentException ex) {
request.abort();
} catch (IOException ex) {
request.abort();
} finally {
client.close();
}
if (mimeType != null) {
if (mimeType.equalsIgnoreCase("text/plain") ||
mimeType.equalsIgnoreCase("application/octet-stream")) {
String newMimeType =
MimeTypeMap.getSingleton().getMimeTypeFromExtension(
MimeTypeMap.getFileExtensionFromUrl(mUri));
if (newMimeType != null) {
mRequest.setMimeType(newMimeType);
}
}
String filename = URLUtil.guessFileName(mUri, contentDisposition,
mimeType);
mRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename);
}
// Start the download
DownloadManager manager = (DownloadManager) mContext.getSystemService(
Context.DOWNLOAD_SERVICE);
manager.enqueue(mRequest);
}
| public void run() {
// User agent is likely to be null, though the AndroidHttpClient
// seems ok with that.
AndroidHttpClient client = AndroidHttpClient.newInstance(mUserAgent);
HttpHost httpHost;
try {
httpHost = Proxy.getPreferredHttpHost(mContext, mUri);
if (httpHost != null) {
ConnRouteParams.setDefaultProxy(client.getParams(), httpHost);
}
} catch (IllegalArgumentException ex) {
Log.e(LOGTAG,"Download failed: " + ex);
client.close();
return;
}
HttpHead request = new HttpHead(mUri);
if (mCookies != null && mCookies.length() > 0) {
request.addHeader("Cookie", mCookies);
}
HttpResponse response;
String mimeType = null;
String contentDisposition = null;
try {
response = client.execute(request);
// We could get a redirect here, but if we do lets let
// the download manager take care of it, and thus trust that
// the server sends the right mimetype
if (response.getStatusLine().getStatusCode() == 200) {
Header header = response.getFirstHeader("Content-Type");
if (header != null) {
mimeType = header.getValue();
final int semicolonIndex = mimeType.indexOf(';');
if (semicolonIndex != -1) {
mimeType = mimeType.substring(0, semicolonIndex);
}
}
Header contentDispositionHeader = response.getFirstHeader("Content-Disposition");
if (contentDispositionHeader != null) {
contentDisposition = contentDispositionHeader.getValue();
}
}
} catch (IllegalArgumentException ex) {
request.abort();
} catch (IOException ex) {
request.abort();
} finally {
client.close();
}
if (mimeType != null) {
if (mimeType.equalsIgnoreCase("text/plain") ||
mimeType.equalsIgnoreCase("application/octet-stream")) {
String newMimeType =
MimeTypeMap.getSingleton().getMimeTypeFromExtension(
MimeTypeMap.getFileExtensionFromUrl(mUri));
if (newMimeType != null) {
mimeType = newMimeType;
mRequest.setMimeType(newMimeType);
}
}
String filename = URLUtil.guessFileName(mUri, contentDisposition,
mimeType);
mRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename);
}
// Start the download
DownloadManager manager = (DownloadManager) mContext.getSystemService(
Context.DOWNLOAD_SERVICE);
manager.enqueue(mRequest);
}
|
diff --git a/lib-dempsyimpl/src/main/java/com/nokia/dempsy/container/MpContainer.java b/lib-dempsyimpl/src/main/java/com/nokia/dempsy/container/MpContainer.java
index cd86ad0..4a73998 100644
--- a/lib-dempsyimpl/src/main/java/com/nokia/dempsy/container/MpContainer.java
+++ b/lib-dempsyimpl/src/main/java/com/nokia/dempsy/container/MpContainer.java
@@ -1,933 +1,939 @@
/*
* Copyright 2012 the original author or authors.
*
* 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.nokia.dempsy.container;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.nokia.dempsy.Dispatcher;
import com.nokia.dempsy.KeySource;
import com.nokia.dempsy.annotations.MessageKey;
import com.nokia.dempsy.config.ClusterId;
import com.nokia.dempsy.container.internal.AnnotatedMethodInvoker;
import com.nokia.dempsy.container.internal.LifecycleHelper;
import com.nokia.dempsy.internal.util.SafeString;
import com.nokia.dempsy.messagetransport.Listener;
import com.nokia.dempsy.monitoring.StatsCollector;
import com.nokia.dempsy.output.OutputInvoker;
import com.nokia.dempsy.router.RoutingStrategy;
import com.nokia.dempsy.serialization.SerializationException;
import com.nokia.dempsy.serialization.Serializer;
import com.nokia.dempsy.serialization.java.JavaSerializer;
/**
* <p>The {@link MpContainer} manages the lifecycle of message processors for the
* node that it's instantiated in.</p>
*
* The container is simple in that it does no thread management. When it's called
* it assumes that the transport has provided the thread that's needed
*/
public class MpContainer implements Listener, OutputInvoker, RoutingStrategy.Inbound.KeyspaceResponsibilityChangeListener
{
private Logger logger = LoggerFactory.getLogger(getClass());
// these are set during configuration
private LifecycleHelper prototype;
private Dispatcher dispatcher;
// Note that this is set via spring/guice. Tests that need it,
// should set it them selves. Having a default leaks 8 threads per
// instance.
private StatsCollector statCollector;
// default instance optionally replaced via dependency injection
private Serializer<Object> serializer = new JavaSerializer<Object>();
// this is used to retrieve message keys
private AnnotatedMethodInvoker keyMethods = new AnnotatedMethodInvoker(MessageKey.class);
// message key -> instance that handles messages with this key
// changes to this map will be synchronized; read-only may be concurrent
private ConcurrentHashMap<Object,InstanceWrapper> instances = new ConcurrentHashMap<Object,InstanceWrapper>();
// Scheduler to handle eviction thread.
private ScheduledExecutorService evictionScheduler;
// The ClusterId is set for the sake of error messages.
private ClusterId clusterId;
// This holds the keySource for pre(re)-instantiation
private KeySource<?> keySource = null;
private volatile boolean isRunning = true;
public MpContainer(ClusterId clusterId) { this.clusterId = clusterId; }
protected static class InstanceWrapper
{
private Object instance;
private Semaphore lock = new Semaphore(1,true); // basically a mutex
private AtomicBoolean evicted = new AtomicBoolean(false);
/**
* DO NOT CALL THIS WITH NULL OR THE LOCKING LOGIC WONT WORK
*/
public InstanceWrapper(Object o) { this.instance = o; }
/**
* MAKE SURE YOU USE A FINALLY CLAUSE TO RELEASE THE LOCK.
* @param block - whether or not to wait for the lock.
* @return the instance if the lock was aquired. null otherwise.
*/
public Object getExclusive(boolean block)
{
if (block)
{
boolean gotLock = false;
while (!gotLock)
{
try { lock.acquire(); gotLock = true; } catch (InterruptedException e) { }
}
}
else
{
if (!lock.tryAcquire())
return null;
}
// if we got here we have the lock
return instance;
}
/**
* MAKE SURE YOU USE A FINALLY CLAUSE TO RELEASE THE LOCK.
* MAKE SURE YOU OWN THE LOCK IF YOU UNLOCK IT.
*/
public void releaseLock()
{
lock.release();
}
public boolean tryLock()
{
return lock.tryAcquire();
}
/**
* This will set the instance reference to null. MAKE SURE
* YOU OWN THE LOCK BEFORE CALLING.
*/
public void markPassivated() { instance = null; }
/**
* This will tell you if the instance reference is null. MAKE SURE
* YOU OWN THE LOCK BEFORE CALLING.
*/
public boolean isPassivated() { return instance == null; }
/**
* This will prevent further operations on this instance.
* MAKE SURE YOU OWN THE LOCK BEFORE CALLING.
*/
public void markEvicted() { evicted.set(true); }
/**
* Flag to indicate this instance has been evicted and no further operations should be enacted.
*/
public boolean isEvicted() { return evicted.get(); }
//----------------------------------------------------------------------------
// Test access
//----------------------------------------------------------------------------
protected Object getInstance() { return instance; }
}
//----------------------------------------------------------------------------
// Configuration
//----------------------------------------------------------------------------
public void setPrototype(Object prototype) throws ContainerException
{
this.prototype = new LifecycleHelper(prototype);
if (outputConcurrency > 0)
setupOutputConcurrency();
}
public Object getPrototype()
{
return prototype == null ? null : prototype.getPrototype();
}
public LifecycleHelper getLifecycleHelper() {
return prototype;
}
public Map<Object,InstanceWrapper> getInstances() {
return instances;
}
public void setDispatcher(Dispatcher dispatcher)
{
this.dispatcher = dispatcher;
}
/**
* Set the StatsCollector. This is optional, but likely desired in
* a production environment. The default is to use the Coda Metrics
* StatsCollector with only the default JMX reporters. Production
* environments will likely want to export stats to a centralized
* monitor like Graphite or Ganglia.
*/
public void setStatCollector(StatsCollector collector)
{
this.statCollector = collector;
}
/**
* Set the serializer. This can be injected to change the serialization
* scheme, but is optional. The default serializer uses Java Serialization.
*
* @param serializer
*/
public void setSerializer(Serializer<Object> serializer) { this.serializer = serializer; }
public Serializer<Object> getSerializer() { return this.serializer; }
public void setKeySource(KeySource<?> keySource) { this.keySource = keySource; }
//----------------------------------------------------------------------------
// Monitoring / Management
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
// Operation
//----------------------------------------------------------------------------
/**
* {@inheritDoc}
* @return true, to acknowledge the message.
*/
@Override
public boolean onMessage(byte[] data, boolean fastfail)
{
Object message = null;
try
{
message = serializer.deserialize(data);
statCollector.messageReceived(data);
return dispatch(message,!fastfail);
}
catch(SerializationException e2)
{
logger.warn("the container for " + clusterId + " failed to deserialize message received for " + clusterId, e2);
}
catch (Throwable ex)
{
logger.warn("the container for " + clusterId + " failed to dispatch message the following message " +
SafeString.objectDescription(message) + " to the message processor " + SafeString.valueOf(prototype), ex);
}
return false;
}
/**
* {@inheritDoc}
*/
@Override
public void shuttingDown()
{
isRunning = false;
shutdown();
// we don't care about the transport shutting down (currently)
}
public void shutdown()
{
if (evictionScheduler != null)
evictionScheduler.shutdownNow();
// the following will close up any output executor that might be running
setConcurrency(-1);
}
//----------------------------------------------------------------------------
// Monitoring and Management
//----------------------------------------------------------------------------
/**
* Returns the number of message processors controlled by this manager.
*/
public int getProcessorCount()
{
return instances.size();
}
AtomicBoolean isRunningMpInst = new AtomicBoolean(false);
AtomicBoolean stopRunningMpInst = new AtomicBoolean(false);
Object keyspaceResponsibilityChangedLock = new Object(); // we need to synchronize keyspaceResponsibilityChanged alone
@Override
public void keyspaceResponsibilityChanged(final RoutingStrategy.Inbound strategyInbound, boolean less, boolean more)
{
synchronized(keyspaceResponsibilityChangedLock)
{
// need to handle less by passivating ... but we'll ignore for now.
// If more were added and we have a keySource we need to do
// preinstantiation
if (more && keySource != null)
{
// We need to see if we're already executing
stopRunningMpInst.set(true); // kick out any running instantiation thread
// wait for it to exit, it it's even running
synchronized(isRunningMpInst)
{
while (isRunningMpInst.get() && isRunning)
{
try { isRunningMpInst.wait(); } catch (InterruptedException e) {}
}
}
// this flag is used to hold up the calling thread's exit of this method
// until the Runnable is underway.
final AtomicBoolean running = new AtomicBoolean(false);
Thread t = new Thread(new Runnable()
{
@Override
public void run()
{
synchronized(isRunningMpInst) { isRunningMpInst.set(true); }
stopRunningMpInst.set(false); // reset this flag in case it's been set
synchronized(running)
{
running.set(true);
running.notify();
}
StatsCollector.TimerContext tcontext = null;
try{
tcontext = statCollector.preInstantiationStarted();
Iterable<?> iterable = keySource.getAllPossibleKeys();
for(Object key: iterable)
{
if (stopRunningMpInst.get() || !isRunning)
break;
try
{
if(strategyInbound.doesMessageKeyBelongToNode(key))
getInstanceForKey(key);
}
catch(ContainerException e)
{
logger.error("Failed to instantiate MP for Key "+key +
" of type "+key.getClass().getSimpleName(), e);
}
}
}
catch(Throwable e)
{
logger.error("Exception occured while processing keys during pre-instantiation using KeyStore method"+
keySource.getClass().getSimpleName()+":getAllPossibleKeys()", e);
}
finally
{
if (tcontext != null) tcontext.stop();
synchronized(isRunningMpInst)
{
isRunningMpInst.set(false);
isRunningMpInst.notify();
}
}
}
}, "Pre-Instantation Thread");
t.setDaemon(true);
t.start();
// make sure the thread is running before we head out from the synchronized block
synchronized(running)
{
while (running.get() == false && isRunning)
{
try { running.wait(); } catch (InterruptedException ie) {}
}
}
}
}
}
//----------------------------------------------------------------------------
// Test Hooks
//----------------------------------------------------------------------------
protected Dispatcher getDispatcher() { return dispatcher; }
protected StatsCollector getStatsCollector() { return statCollector; }
/**
* Returns the Message Processor that is associated with a given key,
* <code>null</code> if there is no such MP. Does <em>not</em> create
* a new MP.
* <p>
* <em>This method exists for testing; don't do anything stupid</em>
*/
public Object getMessageProcessor(Object key)
{
InstanceWrapper wrapper = instances.get(key);
return (wrapper != null) ? wrapper.getInstance() : null;
}
//----------------------------------------------------------------------------
// Internals
//----------------------------------------------------------------------------
// this is called directly from tests but shouldn't be accessed otherwise.
protected boolean dispatch(Object message, boolean block) throws ContainerException {
if (message == null)
return false; // No. We didn't process the null message
InstanceWrapper wrapper;
wrapper = getInstanceForDispatch(message);
boolean ret = false;
// wrapper cannot be null ... look at the getInstanceForDispatch method
boolean gotLock = false;
if(wrapper.isEvicted()){
logger.trace("the container for " + clusterId + " failed to obtain lock on " + SafeString.valueOf(prototype)
+ " due to eviction");
statCollector.messageDiscarded(message);
return ret;
}
try {
Object instance = wrapper.getExclusive(block);
if (instance != null) // null indicates we didn't get the lock
{
if(wrapper.isEvicted()){
logger.trace("the container for " + clusterId + " failed to obtain lock on " + SafeString.valueOf(prototype)
+ " due to eviction");
statCollector.messageDiscarded(message);
return ret;
}
gotLock = true;
invokeOperation(wrapper.getInstance(), Operation.handle, message);
ret = true;
} else {
if (logger.isTraceEnabled())
logger.trace("the container for " + clusterId + " failed to obtain lock on " + SafeString.valueOf(prototype));
statCollector.messageDiscarded(message);
}
} finally {
if (gotLock)
wrapper.releaseLock();
}
return ret;
}
/**
* Returns the instance associated with the given message, creating it if
* necessary. Will append the message to the instance's work queue (which
* may also contain an activation invocation).
*/
protected InstanceWrapper getInstanceForDispatch(Object message) throws ContainerException
{
if (message == null)
throw new ContainerException("the container for " + clusterId + " attempted to dispatch null message.");
if (!prototype.isMessageSupported(message))
throw new ContainerException("the container for " + clusterId + " has a prototype " + SafeString.valueOf(prototype) +
" that does not handle messages of class " + SafeString.valueOfClass(message));
Object key = getKeyFromMessage(message);
InstanceWrapper wrapper = getInstanceForKey(key);
return wrapper;
}
public void evict() {
if (!prototype.isEvictableSupported() || !isRunning)
return;
StatsCollector.TimerContext tctx = null;
try
{
tctx = statCollector.evictionPassStarted();
// we need to make a copy of the instances in order to make sure
// the eviction check is done at once.
Map<Object,InstanceWrapper> instancesToEvict = new HashMap<Object,InstanceWrapper>(instances.size() + 10);
instancesToEvict.putAll(instances);
while (instancesToEvict.size() > 0 && instances.size() > 0 && isRunning)
{
// store off anything that passes for later removal. This is to avoid a
// ConcurrentModificationException.
Set<Object> keysToRemove = new HashSet<Object>();
for (Map.Entry<Object, InstanceWrapper> entry : instancesToEvict.entrySet())
{
Object key = entry.getKey();
InstanceWrapper wrapper = entry.getValue();
boolean gotLock = false;
try {
gotLock = wrapper.tryLock();
if (gotLock) {
// since we got here we're done with this instance,
// so add it's key to the list of keys we plan don't
// need to return to.
keysToRemove.add(key);
Object instance = wrapper.getInstance();
try {
if (prototype.invokeEvictable(instance)) {
wrapper.markEvicted();
prototype.passivate(wrapper.getInstance());
wrapper.markPassivated();
instances.remove(key);
statCollector.messageProcessorDeleted(key);
}
}
catch (InvocationTargetException e)
{
logger.warn("Checking the eviction status/passivating of the Mp " + SafeString.objectDescription(instance) +
" resulted in an exception.",e.getCause());
}
catch (IllegalAccessException e)
{
logger.warn("It appears that the method for checking the eviction or passivating the Mp " + SafeString.objectDescription(instance) +
" is not defined correctly. Is it visible?",e);
}
catch (RuntimeException e)
{
logger.warn("Checking the eviction status/passivating of the Mp " + SafeString.objectDescription(instance) +
" resulted in an exception.",e);
}
}
} finally {
if (gotLock)
wrapper.releaseLock();
}
}
// now clean up everything we managed to get hold of
for (Object key : keysToRemove)
instancesToEvict.remove(key);
}
}
finally
{
if (tctx != null) tctx.stop();
}
}
public void startEvictionThread(long evictionFrequency, TimeUnit timeUnit) {
if (0 == evictionFrequency || null == timeUnit) {
logger.warn("Eviction Thread cannot start with zero frequency or null TimeUnit {} {}", evictionFrequency, timeUnit);
return;
}
if (prototype != null && prototype.isEvictableSupported()) {
evictionScheduler = Executors.newSingleThreadScheduledExecutor();
evictionScheduler.scheduleWithFixedDelay(new Runnable(){ public void run(){ evict(); }}, evictionFrequency, evictionFrequency, timeUnit);
}
}
private ExecutorService outputExecutorService = null;
private int outputConcurrency = -1;
private Object lockForExecutorServiceSetter = new Object();
@Override
public void setConcurrency(int concurrency)
{
synchronized(lockForExecutorServiceSetter)
{
outputConcurrency = concurrency;
if (prototype != null) // otherwise this isn't initialized yet
setupOutputConcurrency();
}
}
private void setupOutputConcurrency()
{
if (prototype.isOutputSupported() && isRunning)
{
synchronized(lockForExecutorServiceSetter)
{
if (outputConcurrency > 1)
outputExecutorService = Executors.newFixedThreadPool(outputConcurrency);
else
{
if (outputExecutorService != null)
outputExecutorService.shutdown();
outputExecutorService = null;
}
}
}
}
// This method MUST NOT THROW
public void outputPass() {
if (!prototype.isOutputSupported())
return;
// take a snapshot of the current container state.
LinkedList<InstanceWrapper> toOutput = new LinkedList<InstanceWrapper>(instances.values());
Executor executorService = null;
Semaphore taskLock = null;
synchronized(lockForExecutorServiceSetter)
{
executorService = outputExecutorService;
if (executorService != null)
taskLock = new Semaphore(outputConcurrency);
}
// This keeps track of the number of concurrently running
// output tasks so that this method can wait until they're
// all done to return.
//
// It's also used as a condition variable signaling on its
// own state changes.
final AtomicLong numExecutingOutputs = new AtomicLong(0);
// keep going until all of the outputs have been invoked
while (toOutput.size() > 0 && isRunning)
{
for (final Iterator<InstanceWrapper> iter = toOutput.iterator(); iter.hasNext();)
{
final InstanceWrapper wrapper = iter.next();
boolean gotLock = false;
gotLock = wrapper.tryLock();
if (gotLock)
{
// If we've been evicted then we're on our way out
// so don't do anything else with this.
if (wrapper.isEvicted())
{
iter.remove();
wrapper.releaseLock();
continue;
}
final Object instance = wrapper.getInstance(); // only called while holding the lock
final Semaphore taskSepaphore = taskLock;
// This task will release the wrapper's lock.
Runnable task = new Runnable()
{
@Override
public void run()
{
try
{
if (isRunning && !wrapper.isEvicted())
invokeOperation(instance, Operation.output, null);
}
finally
{
wrapper.releaseLock();
// this signals that we're done.
synchronized(numExecutingOutputs)
{
numExecutingOutputs.decrementAndGet();
numExecutingOutputs.notifyAll();
}
if (taskSepaphore != null) taskSepaphore.release();
}
}
};
synchronized(numExecutingOutputs)
{
numExecutingOutputs.incrementAndGet();
}
if (executorService != null)
{
try
{
taskSepaphore.acquire();
executorService.execute(task);
}
catch (RejectedExecutionException e)
{
// this may happen because of a race condition between the
taskSepaphore.release();
+ wrapper.releaseLock(); // we never got into the run so we need to release the lock
}
catch (InterruptedException e)
{
// this can happen while blocked in the semaphore.acquire.
// if we're no longer running we should just get out
// of here.
+ //
+ // Not releasing the taskSepaphore assumes the acquire never executed.
+ // if (since) the acquire never executed we also need to release the
+ // wrapper lock or that Mp will never be usable again.
+ wrapper.releaseLock(); // we never got into the run so we need to release the lock
}
}
else
task.run();
iter.remove();
} // end if we got the lock
} // end loop over every Mp
} // end while there are still Mps that haven't had output invoked.
// =======================================================
// now make sure all of the running tasks have completed
synchronized(numExecutingOutputs)
{
while (numExecutingOutputs.get() > 0)
{
try { numExecutingOutputs.wait(); }
catch (InterruptedException e)
{
// if we were interupted for a shutdown then just stop
// waiting for all of the threads to finish
if (!isRunning)
break;
// otherwise continue checking.
}
}
}
// =======================================================
}
@Override
public void invokeOutput() {
StatsCollector.TimerContext tctx = statCollector.outputInvokeStarted();
outputPass();
tctx.stop();
}
//----------------------------------------------------------------------------
// Internals
//----------------------------------------------------------------------------
private Object getKeyFromMessage(Object message) throws ContainerException
{
Object key = null;
try
{
key = keyMethods.invokeGetter(message);
}
catch (IllegalArgumentException e)
{
throw new ContainerException("the container for " + clusterId + " is unable to retrieve key from message " + SafeString.objectDescription(message) +
". Are you sure that the method to retrieve the key takes no parameters?",e);
}
catch(IllegalAccessException e)
{
throw new ContainerException("the container for " + clusterId + " is unable to retrieve key from message " + SafeString.objectDescription(message) +
". Are you sure that the method to retrieve the key is publically accessible (both the class and the method must be public)?");
}
catch(InvocationTargetException e)
{
throw new ContainerException("the container for " + clusterId + " is unable to retrieve key from message " + SafeString.objectDescription(message) +
" because the method to retrieve the key threw an exception.",e.getCause());
}
if (key == null)
throw new ContainerException("the container for " + clusterId + " retrieved a null message key from " +
SafeString.objectDescription(message));
return key;
}
/**
* This is required to return non null or throw a ContainerException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
public InstanceWrapper getInstanceForKey(Object key) throws ContainerException
{
// common case has "no" contention
InstanceWrapper wrapper = instances.get(key);
if(wrapper != null)
return wrapper;
// otherwise we'll do an atomic check-and-update
synchronized (this)
{
wrapper = instances.get(key); // double checked lock?????
if (wrapper != null)
return wrapper;
Object instance = null;
try
{
instance = prototype.newInstance();
}
catch(InvocationTargetException e)
{
throw new ContainerException("the container for " + clusterId + " failed to create a new instance of " +
SafeString.valueOf(prototype) + " for the key " + SafeString.objectDescription(key) +
" because the clone method threw an exception.",e.getCause());
}
catch(IllegalAccessException e)
{
throw new ContainerException("the container for " + clusterId + " failed to create a new instance of " +
SafeString.valueOf(prototype) + " for the key " + SafeString.objectDescription(key) +
" because the clone method is not accessible. Is the class public? Is the clone method public? Does the class implement Cloneable?",e);
}
catch(RuntimeException e)
{
throw new ContainerException("the container for " + clusterId + " failed to create a new instance of " +
SafeString.valueOf(prototype) + " for the key " + SafeString.objectDescription(key) +
" because the clone invocation resulted in an unknown exception.",e);
}
if (instance == null)
throw new ContainerException("the container for " + clusterId + " failed to create a new instance of " +
SafeString.valueOf(prototype) + " for the key " + SafeString.objectDescription(key) +
". The value returned from the clone call appears to be null.");
wrapper = new InstanceWrapper(instance); // null check above.
instances.put(key, wrapper);
statCollector.messageProcessorCreated(key);
// activate
byte[] data = null;
if (logger.isTraceEnabled())
logger.trace("the container for " + clusterId + " is activating instance " + String.valueOf(instance)
+ " with " + ((data != null) ? data.length : 0) + " bytes of data"
+ " via " + SafeString.valueOf(prototype));
try
{
prototype.activate(instance, key, data);
}
catch(IllegalArgumentException e)
{
throw new ContainerException("the container for " + clusterId + " failed to invoke the activate method of " + SafeString.valueOf(prototype) +
". Is it declared to take a byte[]?",e);
}
catch(IllegalAccessException e)
{
throw new ContainerException("the container for " + clusterId + " failed to invoke the activate method of " + SafeString.valueOf(prototype) +
". Is the active method accessible - the class is public and the method is public?",e);
}
catch(InvocationTargetException e)
{
throw new ContainerException("the container for " + clusterId + " failed to invoke the activate method of " + SafeString.valueOf(prototype) +
" because the method itself threw an exception.",e.getCause());
}
catch(RuntimeException e)
{
throw new ContainerException("the container for " + clusterId + " failed to invoke the activate method of " + SafeString.valueOf(prototype) +
" because of an unknown exception.",e);
}
return wrapper;
}
}
public enum Operation { handle, output };
/**
* helper method to invoke an operation (handle a message or run output) handling all of hte
* exceptions and forwarding any results.
*/
private void invokeOperation(Object instance, Operation op, Object message)
{
if (instance != null) // possibly passivated ...
{
try
{
statCollector.messageDispatched(message);
Object result = op == Operation.output ? prototype.invokeOutput(instance) : prototype.invoke(instance, message,statCollector);
statCollector.messageProcessed(message);
if (result != null)
{
dispatcher.dispatch(result);
}
}
catch(ContainerException e)
{
logger.warn("the container for " + clusterId + " failed to invoke " + op + " on the message processor " +
SafeString.valueOf(prototype) + (op == Operation.handle ? (" with " + SafeString.objectDescription(message)) : ""),e);
statCollector.messageFailed(false);
}
// this is an exception thrown as a result of the reflected call having an illegal argument.
// This should actually be impossible since the container itself manages the calling.
catch(IllegalArgumentException e)
{
logger.error("the container for " + clusterId + " failed when trying to invoke " + prototype.invokeDescription(op,message) +
" due to a declaration problem. Are you sure the method takes the type being routed to it? If this is an output operation are you sure the output method doesn't take any arguments?", e);
statCollector.messageFailed(true);
}
// can't access the method? Did the app developer annotate it correctly?
catch(IllegalAccessException e)
{
logger.error("the container for " + clusterId + " failed when trying to invoke " + prototype.invokeDescription(op,message) +
" due an access problem. Is the method public?", e);
statCollector.messageFailed(true);
}
// The app threw an exception.
catch(InvocationTargetException e)
{
logger.warn("the container for " + clusterId + " failed when trying to invoke " + prototype.invokeDescription(op,message) +
" because an exception was thrown by the Message Processeor itself.", e.getCause() );
statCollector.messageFailed(true);
}
// RuntimeExceptions bookeeping
catch (RuntimeException e)
{
logger.error("the container for " + clusterId + " failed when trying to invoke " + prototype.invokeDescription(op,message) +
" due to an unknown exception.", e);
statCollector.messageFailed(false);
if (op == Operation.handle)
throw e;
}
}
}
}
| false | true | public void outputPass() {
if (!prototype.isOutputSupported())
return;
// take a snapshot of the current container state.
LinkedList<InstanceWrapper> toOutput = new LinkedList<InstanceWrapper>(instances.values());
Executor executorService = null;
Semaphore taskLock = null;
synchronized(lockForExecutorServiceSetter)
{
executorService = outputExecutorService;
if (executorService != null)
taskLock = new Semaphore(outputConcurrency);
}
// This keeps track of the number of concurrently running
// output tasks so that this method can wait until they're
// all done to return.
//
// It's also used as a condition variable signaling on its
// own state changes.
final AtomicLong numExecutingOutputs = new AtomicLong(0);
// keep going until all of the outputs have been invoked
while (toOutput.size() > 0 && isRunning)
{
for (final Iterator<InstanceWrapper> iter = toOutput.iterator(); iter.hasNext();)
{
final InstanceWrapper wrapper = iter.next();
boolean gotLock = false;
gotLock = wrapper.tryLock();
if (gotLock)
{
// If we've been evicted then we're on our way out
// so don't do anything else with this.
if (wrapper.isEvicted())
{
iter.remove();
wrapper.releaseLock();
continue;
}
final Object instance = wrapper.getInstance(); // only called while holding the lock
final Semaphore taskSepaphore = taskLock;
// This task will release the wrapper's lock.
Runnable task = new Runnable()
{
@Override
public void run()
{
try
{
if (isRunning && !wrapper.isEvicted())
invokeOperation(instance, Operation.output, null);
}
finally
{
wrapper.releaseLock();
// this signals that we're done.
synchronized(numExecutingOutputs)
{
numExecutingOutputs.decrementAndGet();
numExecutingOutputs.notifyAll();
}
if (taskSepaphore != null) taskSepaphore.release();
}
}
};
synchronized(numExecutingOutputs)
{
numExecutingOutputs.incrementAndGet();
}
if (executorService != null)
{
try
{
taskSepaphore.acquire();
executorService.execute(task);
}
catch (RejectedExecutionException e)
{
// this may happen because of a race condition between the
taskSepaphore.release();
}
catch (InterruptedException e)
{
// this can happen while blocked in the semaphore.acquire.
// if we're no longer running we should just get out
// of here.
}
}
else
task.run();
iter.remove();
} // end if we got the lock
} // end loop over every Mp
} // end while there are still Mps that haven't had output invoked.
// =======================================================
// now make sure all of the running tasks have completed
synchronized(numExecutingOutputs)
{
while (numExecutingOutputs.get() > 0)
{
try { numExecutingOutputs.wait(); }
catch (InterruptedException e)
{
// if we were interupted for a shutdown then just stop
// waiting for all of the threads to finish
if (!isRunning)
break;
// otherwise continue checking.
}
}
}
// =======================================================
}
| public void outputPass() {
if (!prototype.isOutputSupported())
return;
// take a snapshot of the current container state.
LinkedList<InstanceWrapper> toOutput = new LinkedList<InstanceWrapper>(instances.values());
Executor executorService = null;
Semaphore taskLock = null;
synchronized(lockForExecutorServiceSetter)
{
executorService = outputExecutorService;
if (executorService != null)
taskLock = new Semaphore(outputConcurrency);
}
// This keeps track of the number of concurrently running
// output tasks so that this method can wait until they're
// all done to return.
//
// It's also used as a condition variable signaling on its
// own state changes.
final AtomicLong numExecutingOutputs = new AtomicLong(0);
// keep going until all of the outputs have been invoked
while (toOutput.size() > 0 && isRunning)
{
for (final Iterator<InstanceWrapper> iter = toOutput.iterator(); iter.hasNext();)
{
final InstanceWrapper wrapper = iter.next();
boolean gotLock = false;
gotLock = wrapper.tryLock();
if (gotLock)
{
// If we've been evicted then we're on our way out
// so don't do anything else with this.
if (wrapper.isEvicted())
{
iter.remove();
wrapper.releaseLock();
continue;
}
final Object instance = wrapper.getInstance(); // only called while holding the lock
final Semaphore taskSepaphore = taskLock;
// This task will release the wrapper's lock.
Runnable task = new Runnable()
{
@Override
public void run()
{
try
{
if (isRunning && !wrapper.isEvicted())
invokeOperation(instance, Operation.output, null);
}
finally
{
wrapper.releaseLock();
// this signals that we're done.
synchronized(numExecutingOutputs)
{
numExecutingOutputs.decrementAndGet();
numExecutingOutputs.notifyAll();
}
if (taskSepaphore != null) taskSepaphore.release();
}
}
};
synchronized(numExecutingOutputs)
{
numExecutingOutputs.incrementAndGet();
}
if (executorService != null)
{
try
{
taskSepaphore.acquire();
executorService.execute(task);
}
catch (RejectedExecutionException e)
{
// this may happen because of a race condition between the
taskSepaphore.release();
wrapper.releaseLock(); // we never got into the run so we need to release the lock
}
catch (InterruptedException e)
{
// this can happen while blocked in the semaphore.acquire.
// if we're no longer running we should just get out
// of here.
//
// Not releasing the taskSepaphore assumes the acquire never executed.
// if (since) the acquire never executed we also need to release the
// wrapper lock or that Mp will never be usable again.
wrapper.releaseLock(); // we never got into the run so we need to release the lock
}
}
else
task.run();
iter.remove();
} // end if we got the lock
} // end loop over every Mp
} // end while there are still Mps that haven't had output invoked.
// =======================================================
// now make sure all of the running tasks have completed
synchronized(numExecutingOutputs)
{
while (numExecutingOutputs.get() > 0)
{
try { numExecutingOutputs.wait(); }
catch (InterruptedException e)
{
// if we were interupted for a shutdown then just stop
// waiting for all of the threads to finish
if (!isRunning)
break;
// otherwise continue checking.
}
}
}
// =======================================================
}
|
diff --git a/poem/src/test/java/org/melati/poem/test/PreparedTailoredQueryTest.java b/poem/src/test/java/org/melati/poem/test/PreparedTailoredQueryTest.java
index 61c1539ef..4f677aba0 100644
--- a/poem/src/test/java/org/melati/poem/test/PreparedTailoredQueryTest.java
+++ b/poem/src/test/java/org/melati/poem/test/PreparedTailoredQueryTest.java
@@ -1,217 +1,216 @@
/**
*
*/
package org.melati.poem.test;
import java.util.Enumeration;
import org.melati.poem.AccessPoemException;
import org.melati.poem.Capability;
import org.melati.poem.Column;
import org.melati.poem.FieldSet;
import org.melati.poem.PoemTask;
import org.melati.poem.PoemThread;
import org.melati.poem.PreparedTailoredQuery;
import org.melati.poem.Table;
import org.melati.poem.User;
import org.melati.poem.util.EnumUtils;
/**
* @author timp
* @since 22 Jan 2007
*
*/
public class PreparedTailoredQueryTest extends EverythingTestCase {
/**
* Constructor.
*
* @param name
*/
public PreparedTailoredQueryTest(String name) {
super(name);
}
/**
* {@inheritDoc}
*
* @see org.melati.poem.test.PoemTestCase#setUp()
*/
protected void setUp() throws Exception {
super.setUp();
}
/**
* {@inheritDoc}
*
* @see org.melati.poem.test.PoemTestCase#tearDown()
*/
protected void tearDown() throws Exception {
super.tearDown();
}
/**
* Test method for {@link org.melati.poem.PreparedTailoredQuery#selection()}.
*/
public void testSelection() {
EverythingDatabase db = (EverythingDatabase)getDb();
Capability spyMaster = db.getCapabilityTable().ensure("spyMaster");
final Capability moneyPenny = db.getCapabilityTable().ensure("moneyPenny");
User spy = (User)db.getUserTable().newPersistent();
spy.setLogin("spy");
spy.setName("Spy");
spy.setPassword("spy");
spy.makePersistent();
Protected spyMission = (Protected)db.getProtectedTable().newPersistent();
spyMission.setCanRead(moneyPenny);
spyMission.setCanSelect(moneyPenny);
spyMission.setCanWrite(moneyPenny);
spyMission.setCanDelete(spyMaster);
spyMission.setSpy(spy);
spyMission.setMission("impossible");
spyMission.setDeleted(false);
spyMission.makePersistent();
final Column canReadColumn = db.getProtectedTable().getCanReadColumn();
final PreparedTailoredQuery ptq = new PreparedTailoredQuery(
new Column[] { canReadColumn }, new Table[0], canReadColumn
.fullQuotedName()
+ "=" + moneyPenny.troid(), null);
assertEquals(new Integer(1), new Integer(EnumUtils
.vectorOf(ptq.selection()).size()));
Enumeration en = ptq.selection();
while (en.hasMoreElements()) {
Object ne = en.nextElement();
System.err.println("FieldSet:" + ne);
}
PoemTask readAsGuest = new PoemTask() {
public void run() {
try {
Enumeration en = ptq.selection();
assertEquals(new Integer(1), new Integer(EnumUtils.vectorOf(en)
.size()));
en = ptq.selection();
while (en.hasMoreElements()) {
System.err.println(en.nextElement());
}
fail("Should have blown up");
} catch (AccessPoemException e) {
e = null;
}
}
};
PoemThread.withAccessToken(db.guestAccessToken(), readAsGuest);
final Column missionColumn = db.getProtectedTable().getMissionColumn();
assertEquals("moneyPenny", spyMission.getCanRead().getName());
final PreparedTailoredQuery ptq2 = new PreparedTailoredQuery(new Column[] {
missionColumn, db.getUserTable().getPasswordColumn() },
new Table[] { db.getUserTable() }, missionColumn.fullQuotedName()
+ " = 'impossible' AND "
+ db.getProtectedTable().getSpyColumn().fullQuotedName()
+ " = " + db.getUserTable().troidColumn().fullQuotedName(),
null);
PoemTask readAsGuest2 = new PoemTask() {
public void run() {
Enumeration en = ptq2.selection();
+ assertEquals(1, EnumUtils.vectorOf(en).size());
try {
- assertEquals(new Integer(1), new Integer(EnumUtils.vectorOf(
- ptq2.selection()).size()));
en = ptq2.selection();
while (en.hasMoreElements()) {
FieldSet tuple = (FieldSet)en.nextElement();
System.err.println(tuple);
}
fail("Should have blown up");
} catch (AccessPoemException e) {
e = null;
}
}
};
PoemThread.withAccessToken(db.guestAccessToken(), readAsGuest2);
// Now remove row's capability and set Users capability;
// (as Protected does not get checked in {@link
// TailoredResultSetEnumeration}).
spyMission.setCanRead(null);
db.getUserTable().getTableInfo().setDefaultcanread(moneyPenny);
try {
PoemThread.withAccessToken(db.guestAccessToken(), readAsGuest2);
} catch (AccessPoemException e) {
e = null;
}
// Check that table level protection is used if row level is missing
db.getProtectedTable().getTableInfo().setDefaultcanread(moneyPenny);
try {
PoemThread.withAccessToken(db.guestAccessToken(), readAsGuest2);
} catch (AccessPoemException e) {
e = null;
}
// cleanup
db.getProtectedTable().getTableInfo().setDefaultcanread(null);
db.getUserTable().getTableInfo().setDefaultcanread(null);
spyMission.delete();
spy.delete();
spyMaster.delete();
moneyPenny.delete();
}
/**
* Test method for
* {@link org.melati.poem.PreparedTailoredQuery#selection_firstRaw()}.
*/
public void testSelection_firstRaw() {
}
/**
* Test method for
* {@link org.melati.poem.PreparedTailoredQuery#PreparedTailoredQuery(java.lang.String, org.melati.poem.Column[], org.melati.poem.Table[], java.lang.String, java.lang.String)}.
*/
public void testPreparedTailoredQueryStringColumnArrayTableArrayStringString() {
}
/**
* Test method for
* {@link org.melati.poem.PreparedTailoredQuery#PreparedTailoredQuery(org.melati.poem.Column[], org.melati.poem.Table[], java.lang.String, java.lang.String)}.
*/
public void testPreparedTailoredQueryColumnArrayTableArrayStringString() {
}
/**
* Test method for
* {@link org.melati.poem.TailoredQuery#TailoredQuery(org.melati.poem.Column[], org.melati.poem.Table[], java.lang.String, java.lang.String)}.
*/
public void testTailoredQueryColumnArrayTableArrayStringString() {
}
/**
* Test method for
* {@link org.melati.poem.TailoredQuery#TailoredQuery(java.lang.String, org.melati.poem.Column[], org.melati.poem.Table[], java.lang.String, java.lang.String)}.
*/
public void testTailoredQueryStringColumnArrayTableArrayStringString() {
}
/**
* Test method for {@link org.melati.poem.TailoredQuery#toString()}.
*/
public void testToString() {
}
}
| false | true | public void testSelection() {
EverythingDatabase db = (EverythingDatabase)getDb();
Capability spyMaster = db.getCapabilityTable().ensure("spyMaster");
final Capability moneyPenny = db.getCapabilityTable().ensure("moneyPenny");
User spy = (User)db.getUserTable().newPersistent();
spy.setLogin("spy");
spy.setName("Spy");
spy.setPassword("spy");
spy.makePersistent();
Protected spyMission = (Protected)db.getProtectedTable().newPersistent();
spyMission.setCanRead(moneyPenny);
spyMission.setCanSelect(moneyPenny);
spyMission.setCanWrite(moneyPenny);
spyMission.setCanDelete(spyMaster);
spyMission.setSpy(spy);
spyMission.setMission("impossible");
spyMission.setDeleted(false);
spyMission.makePersistent();
final Column canReadColumn = db.getProtectedTable().getCanReadColumn();
final PreparedTailoredQuery ptq = new PreparedTailoredQuery(
new Column[] { canReadColumn }, new Table[0], canReadColumn
.fullQuotedName()
+ "=" + moneyPenny.troid(), null);
assertEquals(new Integer(1), new Integer(EnumUtils
.vectorOf(ptq.selection()).size()));
Enumeration en = ptq.selection();
while (en.hasMoreElements()) {
Object ne = en.nextElement();
System.err.println("FieldSet:" + ne);
}
PoemTask readAsGuest = new PoemTask() {
public void run() {
try {
Enumeration en = ptq.selection();
assertEquals(new Integer(1), new Integer(EnumUtils.vectorOf(en)
.size()));
en = ptq.selection();
while (en.hasMoreElements()) {
System.err.println(en.nextElement());
}
fail("Should have blown up");
} catch (AccessPoemException e) {
e = null;
}
}
};
PoemThread.withAccessToken(db.guestAccessToken(), readAsGuest);
final Column missionColumn = db.getProtectedTable().getMissionColumn();
assertEquals("moneyPenny", spyMission.getCanRead().getName());
final PreparedTailoredQuery ptq2 = new PreparedTailoredQuery(new Column[] {
missionColumn, db.getUserTable().getPasswordColumn() },
new Table[] { db.getUserTable() }, missionColumn.fullQuotedName()
+ " = 'impossible' AND "
+ db.getProtectedTable().getSpyColumn().fullQuotedName()
+ " = " + db.getUserTable().troidColumn().fullQuotedName(),
null);
PoemTask readAsGuest2 = new PoemTask() {
public void run() {
Enumeration en = ptq2.selection();
try {
assertEquals(new Integer(1), new Integer(EnumUtils.vectorOf(
ptq2.selection()).size()));
en = ptq2.selection();
while (en.hasMoreElements()) {
FieldSet tuple = (FieldSet)en.nextElement();
System.err.println(tuple);
}
fail("Should have blown up");
} catch (AccessPoemException e) {
e = null;
}
}
};
PoemThread.withAccessToken(db.guestAccessToken(), readAsGuest2);
// Now remove row's capability and set Users capability;
// (as Protected does not get checked in {@link
// TailoredResultSetEnumeration}).
spyMission.setCanRead(null);
db.getUserTable().getTableInfo().setDefaultcanread(moneyPenny);
try {
PoemThread.withAccessToken(db.guestAccessToken(), readAsGuest2);
} catch (AccessPoemException e) {
e = null;
}
// Check that table level protection is used if row level is missing
db.getProtectedTable().getTableInfo().setDefaultcanread(moneyPenny);
try {
PoemThread.withAccessToken(db.guestAccessToken(), readAsGuest2);
} catch (AccessPoemException e) {
e = null;
}
// cleanup
db.getProtectedTable().getTableInfo().setDefaultcanread(null);
db.getUserTable().getTableInfo().setDefaultcanread(null);
spyMission.delete();
spy.delete();
spyMaster.delete();
moneyPenny.delete();
}
| public void testSelection() {
EverythingDatabase db = (EverythingDatabase)getDb();
Capability spyMaster = db.getCapabilityTable().ensure("spyMaster");
final Capability moneyPenny = db.getCapabilityTable().ensure("moneyPenny");
User spy = (User)db.getUserTable().newPersistent();
spy.setLogin("spy");
spy.setName("Spy");
spy.setPassword("spy");
spy.makePersistent();
Protected spyMission = (Protected)db.getProtectedTable().newPersistent();
spyMission.setCanRead(moneyPenny);
spyMission.setCanSelect(moneyPenny);
spyMission.setCanWrite(moneyPenny);
spyMission.setCanDelete(spyMaster);
spyMission.setSpy(spy);
spyMission.setMission("impossible");
spyMission.setDeleted(false);
spyMission.makePersistent();
final Column canReadColumn = db.getProtectedTable().getCanReadColumn();
final PreparedTailoredQuery ptq = new PreparedTailoredQuery(
new Column[] { canReadColumn }, new Table[0], canReadColumn
.fullQuotedName()
+ "=" + moneyPenny.troid(), null);
assertEquals(new Integer(1), new Integer(EnumUtils
.vectorOf(ptq.selection()).size()));
Enumeration en = ptq.selection();
while (en.hasMoreElements()) {
Object ne = en.nextElement();
System.err.println("FieldSet:" + ne);
}
PoemTask readAsGuest = new PoemTask() {
public void run() {
try {
Enumeration en = ptq.selection();
assertEquals(new Integer(1), new Integer(EnumUtils.vectorOf(en)
.size()));
en = ptq.selection();
while (en.hasMoreElements()) {
System.err.println(en.nextElement());
}
fail("Should have blown up");
} catch (AccessPoemException e) {
e = null;
}
}
};
PoemThread.withAccessToken(db.guestAccessToken(), readAsGuest);
final Column missionColumn = db.getProtectedTable().getMissionColumn();
assertEquals("moneyPenny", spyMission.getCanRead().getName());
final PreparedTailoredQuery ptq2 = new PreparedTailoredQuery(new Column[] {
missionColumn, db.getUserTable().getPasswordColumn() },
new Table[] { db.getUserTable() }, missionColumn.fullQuotedName()
+ " = 'impossible' AND "
+ db.getProtectedTable().getSpyColumn().fullQuotedName()
+ " = " + db.getUserTable().troidColumn().fullQuotedName(),
null);
PoemTask readAsGuest2 = new PoemTask() {
public void run() {
Enumeration en = ptq2.selection();
assertEquals(1, EnumUtils.vectorOf(en).size());
try {
en = ptq2.selection();
while (en.hasMoreElements()) {
FieldSet tuple = (FieldSet)en.nextElement();
System.err.println(tuple);
}
fail("Should have blown up");
} catch (AccessPoemException e) {
e = null;
}
}
};
PoemThread.withAccessToken(db.guestAccessToken(), readAsGuest2);
// Now remove row's capability and set Users capability;
// (as Protected does not get checked in {@link
// TailoredResultSetEnumeration}).
spyMission.setCanRead(null);
db.getUserTable().getTableInfo().setDefaultcanread(moneyPenny);
try {
PoemThread.withAccessToken(db.guestAccessToken(), readAsGuest2);
} catch (AccessPoemException e) {
e = null;
}
// Check that table level protection is used if row level is missing
db.getProtectedTable().getTableInfo().setDefaultcanread(moneyPenny);
try {
PoemThread.withAccessToken(db.guestAccessToken(), readAsGuest2);
} catch (AccessPoemException e) {
e = null;
}
// cleanup
db.getProtectedTable().getTableInfo().setDefaultcanread(null);
db.getUserTable().getTableInfo().setDefaultcanread(null);
spyMission.delete();
spy.delete();
spyMaster.delete();
moneyPenny.delete();
}
|
diff --git a/atlas-web/src/main/java/ae3/anatomogram/Anatomogram.java b/atlas-web/src/main/java/ae3/anatomogram/Anatomogram.java
index 27ce750dc..a2571883c 100644
--- a/atlas-web/src/main/java/ae3/anatomogram/Anatomogram.java
+++ b/atlas-web/src/main/java/ae3/anatomogram/Anatomogram.java
@@ -1,277 +1,278 @@
package ae3.anatomogram;
import org.apache.batik.dom.util.DOMUtilities;
import org.apache.batik.parser.PathHandler;
import org.apache.batik.transcoder.TranscoderException;
import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.batik.transcoder.image.JPEGTranscoder;
import org.apache.batik.transcoder.image.PNGTranscoder;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* This code originally extracted from the Annotator.java...
*
* @author Olga Melnichuk
* Date: Dec 13, 2010
*/
public class Anatomogram {
static class Annotation {
private String id;
private String caption;
private int up;
private int dn;
private float x;
private float y;
public Annotation(String id, String caption, int up, int dn, float x, float y) {
this.id = id;
this.caption = caption;
this.up = up;
this.dn = dn;
this.x = x;
this.y = y;
}
}
public enum Encoding {
Svg, Jpeg, Png
}
enum HeatmapStyle {
UpDn, Up, Dn, Blank;
public static HeatmapStyle forUpDnValues(int up, int dn) {
if ((up > 0) && (dn > 0)) {
return UpDn;
} else if (up > 0) {
return Up;
} else if (dn > 0) {
return Dn;
}
return Blank;
}
}
public static final int MAX_ANNOTATIONS = 9;
private final Document svgDocument;
private List<Annotation> annotations = new ArrayList<Annotation>();
private List<AnatomogramArea> map = new ArrayList<AnatomogramArea>();
public Anatomogram(Document svgDocument) {
this.svgDocument = svgDocument;
}
public void writePngToStream(OutputStream outputStream) throws IOException, TranscoderException {
writeToStream(Encoding.Png, outputStream);
}
public void writeToStream(Encoding encoding, OutputStream outputStream) throws IOException, TranscoderException {
if (outputStream == null) {
return;
}
switch (encoding) {
case Svg: {
DOMUtilities.writeDocument(svgDocument, new OutputStreamWriter(outputStream));
break;
}
case Jpeg: {
JPEGTranscoder t = new JPEGTranscoder();
// t.addTranscodingHint(JPEGTranscoder.KEY_QUALITY, new Float(. 8));
TranscoderInput input = new TranscoderInput(svgDocument);
TranscoderOutput output = new TranscoderOutput(outputStream);
t.transcode(input, output);
break;
}
case Png: {
PNGTranscoder t = new PNGTranscoder();
//t.addTranscodingHint(JPEGTranscoder.KEY_WIDTH, new Float(350));
//t.addTranscodingHint(JPEGTranscoder.KEY_HEIGHT, new Float(150));
TranscoderInput input = new TranscoderInput(svgDocument);
TranscoderOutput output = new TranscoderOutput(outputStream);
t.transcode(input, output);
break;
}
default:
throw new IllegalStateException("unknown encoding");
}
}
public List<AnatomogramArea> getAreaMap() {
List<AnatomogramArea> list = new ArrayList<AnatomogramArea>();
list.addAll(map);
return list;
}
public void addAnnotation(String id, String caption, int up, int dn) {
if (map.size() >= MAX_ANNOTATIONS) {
return;
}
Element elem = svgDocument.getElementById(id);
if (elem != null) {
AnnotationPathHandler pathHandler = new AnnotationPathHandler();
parseElement(elem, pathHandler);
annotations.add(new Annotation(id, caption, up, dn, pathHandler.getCenterX(), pathHandler.getCenterY()));
applyChanges();
}
}
public boolean isEmpty() {
return annotations.isEmpty();
}
private void applyChanges() {
map.clear();
Collections.sort(annotations, new Comparator<Annotation>() {
public int compare(Annotation a1, Annotation a2) {
return Float.compare(a1.y, a2.y);
}
});
Editor editor = new Editor(svgDocument);
for (int i = 1; i <= MAX_ANNOTATIONS; i++) {
String index = formatInt(i);
final String calloutId = "pathCallout" + index;
final String rectId = "rectCallout" + index;
final String triangleId = "triangleCallout" + index;
final String textCalloutUpId = "textCalloutUp" + index;
final String textCalloutDnId = "textCalloutDn" + index;
final String textCalloutCenterId = "textCalloutCenter" + index;
final String textCalloutCaptionId = "textCalloutCaption" + index;
boolean noAnnotation = i >= annotations.size();
String visibility = noAnnotation ? "hidden" : "visible";
editor.setVisibility(calloutId, visibility);
editor.setVisibility(rectId, visibility);
editor.setVisibility(triangleId, visibility);
editor.setVisibility(textCalloutUpId, visibility);
editor.setVisibility(textCalloutDnId, visibility);
editor.setVisibility(textCalloutCenterId, visibility);
editor.setVisibility(textCalloutCaptionId, visibility);
if (noAnnotation) {
continue;
}
Element calloutEl = svgDocument.getElementById(calloutId);
if (null == calloutEl)
throw new IllegalStateException("can not find element" + calloutId);
- Annotation currAn = annotations.get(i);
+ // NB. i-1 because while indexing in svg file starts from 1, java arrays are indexed from 0
+ Annotation currAn = annotations.get(i-1);
CalloutPathHandler calloutPathHandler = new CalloutPathHandler();
parseElement(calloutEl, calloutPathHandler);
final float X = calloutPathHandler.getRightmostX();
final float Y = calloutPathHandler.getRightmostY();
String calloutPath = String.format("M %f,%f L %f,%f"
, currAn.x
, currAn.y
, X
, Y);
calloutEl.setAttributeNS(null, "d", calloutPath);
final HeatmapStyle style = HeatmapStyle.forUpDnValues(currAn.up, currAn.dn);
switch (style) {
case UpDn:
editor.fill(rectId, "blue");
editor.fill(triangleId, "red");
editor.setTextAndAlign(textCalloutUpId, formatInt(currAn.up));
editor.setTextAndAlign(textCalloutDnId, formatInt(currAn.dn));
editor.setVisibility(textCalloutCenterId, "hidden");
editor.fill(currAn.id, "grey");
editor.setOpacity(currAn.id, "0.5");
break;
case Up:
editor.fill(rectId, "red");
editor.setVisibility(triangleId, "hidden");
editor.setTextAndAlign(textCalloutCenterId, formatInt(currAn.up));
editor.setVisibility(textCalloutUpId, "hidden");
editor.setVisibility(textCalloutDnId, "hidden");
editor.fill(currAn.id, "red");
editor.setOpacity(currAn.id, "0.5");
break;
case Dn:
editor.fill(rectId, "blue");
editor.setVisibility(triangleId, "hidden");
editor.setTextAndAlign(textCalloutCenterId, formatInt(currAn.dn));
editor.setVisibility(textCalloutUpId, "hidden");
editor.setVisibility(textCalloutDnId, "hidden");
editor.fill(currAn.id, "blue");
editor.setOpacity(currAn.id, "0.5");
break;
case Blank:
editor.fill(rectId, "none");
editor.setVisibility(triangleId, "hidden");
editor.setText(textCalloutCenterId, formatInt(0));
editor.setVisibility(textCalloutUpId, "hidden");
editor.setVisibility(textCalloutDnId, "hidden");
editor.setStroke(textCalloutCenterId, "black");
editor.setOpacity(currAn.id, "0.5");
break;
}
editor.setText(textCalloutCaptionId, currAn.caption);
Element rectEl = svgDocument.getElementById(rectId);
Float x = Float.parseFloat(rectEl.getAttribute("x"));
Float y = Float.parseFloat(rectEl.getAttribute("y"));
Float height = Float.parseFloat(rectEl.getAttribute("height"));
Float width = Float.parseFloat(rectEl.getAttribute("width"));
AnatomogramArea area = new AnatomogramArea();
area.x0 = x.intValue();
area.x1 = Math.round(x + width + 200);
area.y0 = y.intValue();
area.y1 = Math.round(y + height);
area.name = currAn.caption;
area.efo = currAn.id;
map.add(area);
}
}
private void parseElement(Element elem, PathHandler pathHandler) {
String s_efo0 = elem.getAttribute("d");
org.apache.batik.parser.PathParser pa = new org.apache.batik.parser.PathParser();
pa.setPathHandler(pathHandler);
pa.parse(s_efo0);
}
private static String formatInt(int i) {
return String.format("%1$d", i);
}
}
| true | true | private void applyChanges() {
map.clear();
Collections.sort(annotations, new Comparator<Annotation>() {
public int compare(Annotation a1, Annotation a2) {
return Float.compare(a1.y, a2.y);
}
});
Editor editor = new Editor(svgDocument);
for (int i = 1; i <= MAX_ANNOTATIONS; i++) {
String index = formatInt(i);
final String calloutId = "pathCallout" + index;
final String rectId = "rectCallout" + index;
final String triangleId = "triangleCallout" + index;
final String textCalloutUpId = "textCalloutUp" + index;
final String textCalloutDnId = "textCalloutDn" + index;
final String textCalloutCenterId = "textCalloutCenter" + index;
final String textCalloutCaptionId = "textCalloutCaption" + index;
boolean noAnnotation = i >= annotations.size();
String visibility = noAnnotation ? "hidden" : "visible";
editor.setVisibility(calloutId, visibility);
editor.setVisibility(rectId, visibility);
editor.setVisibility(triangleId, visibility);
editor.setVisibility(textCalloutUpId, visibility);
editor.setVisibility(textCalloutDnId, visibility);
editor.setVisibility(textCalloutCenterId, visibility);
editor.setVisibility(textCalloutCaptionId, visibility);
if (noAnnotation) {
continue;
}
Element calloutEl = svgDocument.getElementById(calloutId);
if (null == calloutEl)
throw new IllegalStateException("can not find element" + calloutId);
Annotation currAn = annotations.get(i);
CalloutPathHandler calloutPathHandler = new CalloutPathHandler();
parseElement(calloutEl, calloutPathHandler);
final float X = calloutPathHandler.getRightmostX();
final float Y = calloutPathHandler.getRightmostY();
String calloutPath = String.format("M %f,%f L %f,%f"
, currAn.x
, currAn.y
, X
, Y);
calloutEl.setAttributeNS(null, "d", calloutPath);
final HeatmapStyle style = HeatmapStyle.forUpDnValues(currAn.up, currAn.dn);
switch (style) {
case UpDn:
editor.fill(rectId, "blue");
editor.fill(triangleId, "red");
editor.setTextAndAlign(textCalloutUpId, formatInt(currAn.up));
editor.setTextAndAlign(textCalloutDnId, formatInt(currAn.dn));
editor.setVisibility(textCalloutCenterId, "hidden");
editor.fill(currAn.id, "grey");
editor.setOpacity(currAn.id, "0.5");
break;
case Up:
editor.fill(rectId, "red");
editor.setVisibility(triangleId, "hidden");
editor.setTextAndAlign(textCalloutCenterId, formatInt(currAn.up));
editor.setVisibility(textCalloutUpId, "hidden");
editor.setVisibility(textCalloutDnId, "hidden");
editor.fill(currAn.id, "red");
editor.setOpacity(currAn.id, "0.5");
break;
case Dn:
editor.fill(rectId, "blue");
editor.setVisibility(triangleId, "hidden");
editor.setTextAndAlign(textCalloutCenterId, formatInt(currAn.dn));
editor.setVisibility(textCalloutUpId, "hidden");
editor.setVisibility(textCalloutDnId, "hidden");
editor.fill(currAn.id, "blue");
editor.setOpacity(currAn.id, "0.5");
break;
case Blank:
editor.fill(rectId, "none");
editor.setVisibility(triangleId, "hidden");
editor.setText(textCalloutCenterId, formatInt(0));
editor.setVisibility(textCalloutUpId, "hidden");
editor.setVisibility(textCalloutDnId, "hidden");
editor.setStroke(textCalloutCenterId, "black");
editor.setOpacity(currAn.id, "0.5");
break;
}
editor.setText(textCalloutCaptionId, currAn.caption);
Element rectEl = svgDocument.getElementById(rectId);
Float x = Float.parseFloat(rectEl.getAttribute("x"));
Float y = Float.parseFloat(rectEl.getAttribute("y"));
Float height = Float.parseFloat(rectEl.getAttribute("height"));
Float width = Float.parseFloat(rectEl.getAttribute("width"));
AnatomogramArea area = new AnatomogramArea();
area.x0 = x.intValue();
area.x1 = Math.round(x + width + 200);
area.y0 = y.intValue();
area.y1 = Math.round(y + height);
area.name = currAn.caption;
area.efo = currAn.id;
map.add(area);
}
}
| private void applyChanges() {
map.clear();
Collections.sort(annotations, new Comparator<Annotation>() {
public int compare(Annotation a1, Annotation a2) {
return Float.compare(a1.y, a2.y);
}
});
Editor editor = new Editor(svgDocument);
for (int i = 1; i <= MAX_ANNOTATIONS; i++) {
String index = formatInt(i);
final String calloutId = "pathCallout" + index;
final String rectId = "rectCallout" + index;
final String triangleId = "triangleCallout" + index;
final String textCalloutUpId = "textCalloutUp" + index;
final String textCalloutDnId = "textCalloutDn" + index;
final String textCalloutCenterId = "textCalloutCenter" + index;
final String textCalloutCaptionId = "textCalloutCaption" + index;
boolean noAnnotation = i >= annotations.size();
String visibility = noAnnotation ? "hidden" : "visible";
editor.setVisibility(calloutId, visibility);
editor.setVisibility(rectId, visibility);
editor.setVisibility(triangleId, visibility);
editor.setVisibility(textCalloutUpId, visibility);
editor.setVisibility(textCalloutDnId, visibility);
editor.setVisibility(textCalloutCenterId, visibility);
editor.setVisibility(textCalloutCaptionId, visibility);
if (noAnnotation) {
continue;
}
Element calloutEl = svgDocument.getElementById(calloutId);
if (null == calloutEl)
throw new IllegalStateException("can not find element" + calloutId);
// NB. i-1 because while indexing in svg file starts from 1, java arrays are indexed from 0
Annotation currAn = annotations.get(i-1);
CalloutPathHandler calloutPathHandler = new CalloutPathHandler();
parseElement(calloutEl, calloutPathHandler);
final float X = calloutPathHandler.getRightmostX();
final float Y = calloutPathHandler.getRightmostY();
String calloutPath = String.format("M %f,%f L %f,%f"
, currAn.x
, currAn.y
, X
, Y);
calloutEl.setAttributeNS(null, "d", calloutPath);
final HeatmapStyle style = HeatmapStyle.forUpDnValues(currAn.up, currAn.dn);
switch (style) {
case UpDn:
editor.fill(rectId, "blue");
editor.fill(triangleId, "red");
editor.setTextAndAlign(textCalloutUpId, formatInt(currAn.up));
editor.setTextAndAlign(textCalloutDnId, formatInt(currAn.dn));
editor.setVisibility(textCalloutCenterId, "hidden");
editor.fill(currAn.id, "grey");
editor.setOpacity(currAn.id, "0.5");
break;
case Up:
editor.fill(rectId, "red");
editor.setVisibility(triangleId, "hidden");
editor.setTextAndAlign(textCalloutCenterId, formatInt(currAn.up));
editor.setVisibility(textCalloutUpId, "hidden");
editor.setVisibility(textCalloutDnId, "hidden");
editor.fill(currAn.id, "red");
editor.setOpacity(currAn.id, "0.5");
break;
case Dn:
editor.fill(rectId, "blue");
editor.setVisibility(triangleId, "hidden");
editor.setTextAndAlign(textCalloutCenterId, formatInt(currAn.dn));
editor.setVisibility(textCalloutUpId, "hidden");
editor.setVisibility(textCalloutDnId, "hidden");
editor.fill(currAn.id, "blue");
editor.setOpacity(currAn.id, "0.5");
break;
case Blank:
editor.fill(rectId, "none");
editor.setVisibility(triangleId, "hidden");
editor.setText(textCalloutCenterId, formatInt(0));
editor.setVisibility(textCalloutUpId, "hidden");
editor.setVisibility(textCalloutDnId, "hidden");
editor.setStroke(textCalloutCenterId, "black");
editor.setOpacity(currAn.id, "0.5");
break;
}
editor.setText(textCalloutCaptionId, currAn.caption);
Element rectEl = svgDocument.getElementById(rectId);
Float x = Float.parseFloat(rectEl.getAttribute("x"));
Float y = Float.parseFloat(rectEl.getAttribute("y"));
Float height = Float.parseFloat(rectEl.getAttribute("height"));
Float width = Float.parseFloat(rectEl.getAttribute("width"));
AnatomogramArea area = new AnatomogramArea();
area.x0 = x.intValue();
area.x1 = Math.round(x + width + 200);
area.y0 = y.intValue();
area.y1 = Math.round(y + height);
area.name = currAn.caption;
area.efo = currAn.id;
map.add(area);
}
}
|
diff --git a/solvers/java/src/test/java/com/analog/lyric/dimple/test/learning/TestTrainingSet.java b/solvers/java/src/test/java/com/analog/lyric/dimple/test/learning/TestTrainingSet.java
index 7fc4a7c4..915a0a27 100644
--- a/solvers/java/src/test/java/com/analog/lyric/dimple/test/learning/TestTrainingSet.java
+++ b/solvers/java/src/test/java/com/analog/lyric/dimple/test/learning/TestTrainingSet.java
@@ -1,87 +1,89 @@
package com.analog.lyric.dimple.test.learning;
import static org.junit.Assert.*;
import org.junit.Test;
import com.analog.lyric.dimple.learning.ITrainingSet;
import com.analog.lyric.dimple.learning.TrainingAssignment;
import com.analog.lyric.dimple.learning.TrainingAssignmentType;
import com.analog.lyric.dimple.model.Bit;
import com.analog.lyric.dimple.model.FactorGraph;
import com.analog.lyric.dimple.model.Real;
import com.analog.lyric.dimple.model.VariableBase;
import com.analog.lyric.dimple.test.dummySolver.DummySolver;
import com.analog.lyric.util.test.SerializationTester;
/**
* Tests for {@link ITrainingSet} and related classes.
*/
public class TestTrainingSet
{
@Test
public void testTrainingAssignment()
{
FactorGraph model = makeModel();
for (VariableBase var : model.getVariables())
{
TrainingAssignment missing = TrainingAssignment.create(var, TrainingAssignmentType.MISSING, null);
assertEquals(TrainingAssignmentType.MISSING, missing.getAssignmentType());
assertNull(missing.getValue());
assertSame(var, missing.getVariable(model));
testTrainingAssignment(model, missing);
TrainingAssignment fixed = TrainingAssignment.create(var.getUUID(), TrainingAssignmentType.FIXED, 0);
assertEquals(TrainingAssignmentType.FIXED, fixed.getAssignmentType());
assertEquals(0, fixed.getValue());
assertSame(var, fixed.getVariable(model));
testTrainingAssignment(model, fixed);
}
}
private FactorGraph makeModel()
{
FactorGraph model = new FactorGraph();
model.setSolverFactory(new DummySolver());
model.addVariables(new Bit(), new Real());
return model;
}
private void testTrainingAssignment(FactorGraph model, TrainingAssignment assignment)
{
assertTrainingAssignmentInvariants(model, assignment);
}
private void assertTrainingAssignmentInvariants(FactorGraph model, TrainingAssignment assignment)
{
VariableBase var = assignment.getVariable(model);
TrainingAssignmentType type = assignment.getAssignmentType();
Object value = assignment.getValue();
assertSame(var.getSolver(), assignment.getSolverVariable(model.getSolver()));
assertNull(assignment.getSolverVariable(null));
switch (type)
{
case MISSING:
assertNull(value);
break;
case FIXED:
case VALUE:
assertTrue(var.getDomain().containsValueWithRepresentation(value));
break;
+ case INPUTS:
+ break;
}
// Test serialization
// FIXME: handle case where underlying value is not serializable.
TrainingAssignment assignment2 = SerializationTester.clone(assignment);
assertNotSame(assignment, assignment2);
assertEquals(type, assignment2.getAssignmentType());
assertEquals(assignment.getValue(), assignment2.getValue());
assertEquals(var, assignment2.getVariable(model));
}
}
| true | true | private void assertTrainingAssignmentInvariants(FactorGraph model, TrainingAssignment assignment)
{
VariableBase var = assignment.getVariable(model);
TrainingAssignmentType type = assignment.getAssignmentType();
Object value = assignment.getValue();
assertSame(var.getSolver(), assignment.getSolverVariable(model.getSolver()));
assertNull(assignment.getSolverVariable(null));
switch (type)
{
case MISSING:
assertNull(value);
break;
case FIXED:
case VALUE:
assertTrue(var.getDomain().containsValueWithRepresentation(value));
break;
}
// Test serialization
// FIXME: handle case where underlying value is not serializable.
TrainingAssignment assignment2 = SerializationTester.clone(assignment);
assertNotSame(assignment, assignment2);
assertEquals(type, assignment2.getAssignmentType());
assertEquals(assignment.getValue(), assignment2.getValue());
assertEquals(var, assignment2.getVariable(model));
}
| private void assertTrainingAssignmentInvariants(FactorGraph model, TrainingAssignment assignment)
{
VariableBase var = assignment.getVariable(model);
TrainingAssignmentType type = assignment.getAssignmentType();
Object value = assignment.getValue();
assertSame(var.getSolver(), assignment.getSolverVariable(model.getSolver()));
assertNull(assignment.getSolverVariable(null));
switch (type)
{
case MISSING:
assertNull(value);
break;
case FIXED:
case VALUE:
assertTrue(var.getDomain().containsValueWithRepresentation(value));
break;
case INPUTS:
break;
}
// Test serialization
// FIXME: handle case where underlying value is not serializable.
TrainingAssignment assignment2 = SerializationTester.clone(assignment);
assertNotSame(assignment, assignment2);
assertEquals(type, assignment2.getAssignmentType());
assertEquals(assignment.getValue(), assignment2.getValue());
assertEquals(var, assignment2.getVariable(model));
}
|
diff --git a/cspi-webui/src/main/java/org/collectionspace/chain/csp/webui/misc/RecordTraverser.java b/cspi-webui/src/main/java/org/collectionspace/chain/csp/webui/misc/RecordTraverser.java
index d484001e..b9f29af7 100644
--- a/cspi-webui/src/main/java/org/collectionspace/chain/csp/webui/misc/RecordTraverser.java
+++ b/cspi-webui/src/main/java/org/collectionspace/chain/csp/webui/misc/RecordTraverser.java
@@ -1,82 +1,85 @@
package org.collectionspace.chain.csp.webui.misc;
import org.apache.commons.lang.StringUtils;
import org.collectionspace.chain.csp.schema.Spec;
import org.collectionspace.chain.csp.webui.main.Request;
import org.collectionspace.chain.csp.webui.main.WebMethod;
import org.collectionspace.chain.csp.webui.main.WebUI;
import org.collectionspace.csp.api.persistence.Storage;
import org.collectionspace.csp.api.ui.UIException;
import org.collectionspace.csp.api.ui.UIRequest;
import org.collectionspace.csp.api.ui.UISession;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The current search sends back a complex object which consist of a pagination object and a list of one page search results to UI whenever user clicked search.
* Some elements in the list could be of a mixed recordType type (e.g. related records).
* RecordTraverser is a UI component that will display the current record alongside with its adjacent records and will be present on recordEditor page.
* Thus, the component would allow navigation from current record to previous/next based on some predefined order.
*
* The whole interaction/navigation would be dramatically simplified if we could refer to the latest/current search through some token and an overall index of the current record.
* RecordTraverser component would not need the whole list of search results
* (only current, next and previous record information, if it's available).
* http://issues.collectionspace.org/browse/CSPACE-4806
* {
* "current": { Here goes a mini-record, similar to what's in search results. },
* "previous": {...},
* "next": {...},
* "token": "abc",
* "index": 6
* }
* @author csm22
*
*/
public class RecordTraverser implements WebMethod {
private static final Logger log=LoggerFactory.getLogger(RecordTraverser.class);
Spec spec;
public RecordTraverser(Spec spec) {
this.spec = spec;
}
private void store_get(Storage storage,UIRequest request,String path) throws UIException {
JSONObject outputJSON = new JSONObject();
try {
String[] bits = path.split("/");
String token = bits[0];
Integer indexvalue = Integer.getInteger(bits[1]);
String key = UISession.SEARCHTRAVERSER+""+token;
if(request.getSession().getValue(key) instanceof JSONArray){
JSONArray data = (JSONArray)request.getSession().getValue(key);
if((indexvalue -1) >=0){
outputJSON.put("previous", data.get(indexvalue -1));
}
if((indexvalue +1) <=data.length()){
outputJSON.put("next", data.get(indexvalue +1));
}
outputJSON.put("current", data.get(indexvalue));
outputJSON.put("index",indexvalue.toString());
outputJSON.put("token", token);
}
+ else{
+ outputJSON.put("error", "Cannot find the traverser token");
+ }
} catch (JSONException e) {
- throw new UIException("Cannot find the traverser data",e);
+ throw new UIException("Error with the traverser data",e);
}
request.sendJSONResponse(outputJSON);
}
@Override
public void configure(WebUI ui, Spec spec) {
// TODO Auto-generated method stub
}
@Override
public void run(Object in, String[] tail) throws UIException {
Request q=(Request)in;
store_get(q.getStorage(),q.getUIRequest(),StringUtils.join(tail,"/"));
}
}
| false | true | private void store_get(Storage storage,UIRequest request,String path) throws UIException {
JSONObject outputJSON = new JSONObject();
try {
String[] bits = path.split("/");
String token = bits[0];
Integer indexvalue = Integer.getInteger(bits[1]);
String key = UISession.SEARCHTRAVERSER+""+token;
if(request.getSession().getValue(key) instanceof JSONArray){
JSONArray data = (JSONArray)request.getSession().getValue(key);
if((indexvalue -1) >=0){
outputJSON.put("previous", data.get(indexvalue -1));
}
if((indexvalue +1) <=data.length()){
outputJSON.put("next", data.get(indexvalue +1));
}
outputJSON.put("current", data.get(indexvalue));
outputJSON.put("index",indexvalue.toString());
outputJSON.put("token", token);
}
} catch (JSONException e) {
throw new UIException("Cannot find the traverser data",e);
}
request.sendJSONResponse(outputJSON);
}
| private void store_get(Storage storage,UIRequest request,String path) throws UIException {
JSONObject outputJSON = new JSONObject();
try {
String[] bits = path.split("/");
String token = bits[0];
Integer indexvalue = Integer.getInteger(bits[1]);
String key = UISession.SEARCHTRAVERSER+""+token;
if(request.getSession().getValue(key) instanceof JSONArray){
JSONArray data = (JSONArray)request.getSession().getValue(key);
if((indexvalue -1) >=0){
outputJSON.put("previous", data.get(indexvalue -1));
}
if((indexvalue +1) <=data.length()){
outputJSON.put("next", data.get(indexvalue +1));
}
outputJSON.put("current", data.get(indexvalue));
outputJSON.put("index",indexvalue.toString());
outputJSON.put("token", token);
}
else{
outputJSON.put("error", "Cannot find the traverser token");
}
} catch (JSONException e) {
throw new UIException("Error with the traverser data",e);
}
request.sendJSONResponse(outputJSON);
}
|
diff --git a/src/edu/ucla/cens/wifigpslocation/WiFiGPSLocationService.java b/src/edu/ucla/cens/wifigpslocation/WiFiGPSLocationService.java
index c912148..3e9ec7c 100755
--- a/src/edu/ucla/cens/wifigpslocation/WiFiGPSLocationService.java
+++ b/src/edu/ucla/cens/wifigpslocation/WiFiGPSLocationService.java
@@ -1,1104 +1,1103 @@
package edu.ucla.cens.wifigpslocation;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Collections;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ConcurrentModificationException;
import android.content.BroadcastReceiver;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiManager.WifiLock;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
import android.os.SystemClock;
import android.os.RemoteCallbackList;
import android.widget.Toast;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.database.Cursor;
import android.database.SQLException;
import edu.ucla.cens.systemlog.ISystemLog;
import edu.ucla.cens.systemlog.Log;
import edu.ucla.cens.accelservice.IAccelService;
//import android.util.Log;
/**
* WiFiGPSLocationService runs as a service that continuously
* scans for visible WiFi access points.
* Based on the WiFi AP signature, it infers if
* the user is at a location with GPS or not. If it detects that
* GPS is available it will constantly poll GPS with a given interval,
* and return the last location to its clients. If the user is at a
* location without GPS, it will return the last known GPS location to
* clients.
*/
public class WiFiGPSLocationService
extends Service
implements LocationListener
{
/** name of the service used for debug bridge */
private static final String TAG = "WiFiGPSLocationService";
/** Version of this service */
public static final String VER = "1.0";
/** State variable indicating if the services should run or not */
private boolean mRun;
/** Operational power consumption regime variable*/
private int mRegime;
/** DB Adaptor */
private DbAdaptor mDbAdaptor;
/** State variable indicating if the GPS location is being used */
private boolean mGPSRunning;
/** Counter for the number of connected clients */
private int mClientCount = 0;
/** List of callback objects */
private RemoteCallbackList<ILocationChangedCallback> mCallbacks;
/** Counter for the callbacks */
private int mCallbackCount = 0;
/** AccelService object */
private IAccelService mAccelService;
private boolean mAccelConnected;
/** Operational power consumption regime constant values*/
public static final int REGIME_RELAXED = 0;
public static final int REGIME_CONTROLLED = 1;
/** Types of messages used by this service */
private static final int WIFI_SCAN_TIMER_MSG = 1;
private static final int CACHE_CLEANUP_TIMER_MSG = 2;
private static final int LOC_UPDATE_MSG = 3;
/** Time unit constants */
private static final int ONE_SECOND = 1000;
private static final int ONE_MINUTE = 60 * ONE_SECOND;
private static final int ONE_HOUR = 60 * ONE_MINUTE;
private static final int ONE_DAY = 24 * ONE_HOUR;
/** Default timers in milliseconds*/
private static final int DEFAULT_WIFI_SCANNING_INTERVAL
= 2 * ONE_MINUTE; // Two minutes
private static final int DEFAULT_GPS_SCANNING_INTERVAL
= 60 * ONE_SECOND; // One minute
private static final int CLEANUP_INTERVAL
= ONE_HOUR; // One hour
private static final int LOC_UPDATE_TIMEOUT = 5 * ONE_SECOND;
private static final int CACHE_TIMEOUT
= 3 * ONE_DAY; // Three days
private static final int EXTENTION_TIME
= 10 * ONE_MINUTE; // Ten minutes
private static final int SIGNAL_THRESHOLD
= -80;
private static final double GPS_ACCURACY_THRESHOLD
= 10.0;
private static final int SIGNIFICANCE_THRESHOLD
= 3;
/** WiFi object used for scanning */
private WifiManager mWifi;
private WifiLock mWifiLock;
private LocationManager mLocManager;
private MessageDigest mDigest;
/** Map of WiFi scan results to to GPS availability */
private HashMap<String, GPSInfo> mScanCache;
/** The last known location object */
private Location mLastKnownLoc;
/** Temporary location object that is not accurate enough */
private Location mTempKnownLoc;
/** Last seen WiFi set*/
private String mLastWifiSet;
/** Fake location object */
private Location mFakeLocation;
/** Scanning interval variable */
private int mWifiScanInterval;
private int mGpsScanInterval;
//private NotificationManager mNotificationManager;
private final IWiFiGPSLocationServiceControl.Stub mControlBinder
= new IWiFiGPSLocationServiceControl.Stub()
{
/**
* Sets the current operational regime. REGIME_RELAXED
* (0x00000000) is the default regime where the service can
* take suggestions from its clients. Other integer values
* indicate next levels of power consumption limitations
*
* @param regime new power consumption regime
*/
public void setOperationRegime(int regime)
{
mRegime = regime;
if (regime == REGIME_RELAXED)
resetToDefault();
}
/**
* Increases the GPS sampling interval of the service.
* The value after the modification is returned
*
* @return current GPS sampling interval in milliseconds
*/
public int increaseInterval()
{
mRegime = REGIME_CONTROLLED;
mGpsScanInterval = mGpsScanInterval * 2;
return mGpsScanInterval;
}
/**
* Decreases the GPS sampling interval of the service.
* The value after the modification is returned.
*
* @return current GPS sampling interval in milliseconds
*/
public int decreaseInterval()
{
mRegime = REGIME_CONTROLLED;
mGpsScanInterval = mGpsScanInterval / 2;
return mGpsScanInterval;
}
/**
* Sets the sampling interval of GPS and returns the current
* value to verify.
*
* @param interval new sampling interval in milliseconds
* @return current sampling interval in milliseconds
*/
public int setInterval(int interval)
{
mRegime = REGIME_CONTROLLED;
mGpsScanInterval = interval;
return mGpsScanInterval;
}
/**
* Retruns the current GPS sampling interval.
*
* @return current GPS sampling interval in milliseconds
*/
public int getInterval()
{
return mGpsScanInterval;
}
/**
* Sets teh power consumption level.
*
* @param power new power consumption level
*/
public void setPower(int power)
{
//TODO: Not implemented yet
}
/**
* Returns the current power consumption level.
*
* @return current power consumption level
*/
public int getPower()
{
//TODO: not implemented yet.
return 0;
}
};
private final IWiFiGPSLocationService.Stub mBinder
= new IWiFiGPSLocationService.Stub()
{
/**
* Returns the current location.
* If the service is not active, this call will activate it.
*
* @return the last known location
*/
public Location getLocation ()
{
if (!mRun)
start();
return mLastKnownLoc;
}
/**
* Change the GPS sampling interval.
*
* @param interval GPS sampling interval in milliseconds
*/
public int suggestInterval (int interval)
{
if (mRegime == REGIME_RELAXED)
mGpsScanInterval = interval;
return mGpsScanInterval;
}
/**
* Registers a callback to be called when location changes.
*
*
*/
public void registerCallback(ILocationChangedCallback callback,
double threshold)
{
if (callback != null)
{
mCallbacks.register(callback, new Double(threshold));
mCallbackCount++;
}
if ((mCallbackCount == 1) && mAccelConnected)
{
try
{
mAccelService.start();
}
catch (RemoteException re)
{
Log.e(TAG, "Exception when starting AccelService", re);
}
}
else
{
Log.i(TAG, "Not connected to AccelService");
}
}
/**
* Unregisters the callback
*
*/
public void unregisterCallback(ILocationChangedCallback
callback)
{
if (callback != null)
{
mCallbacks.unregister(callback);
mCallbackCount--;
}
if ((mCallbackCount == 0) && mAccelConnected)
{
try
{
mAccelService.stop();
}
catch (RemoteException re)
{
Log.e(TAG, "Exception when stoping AccelService", re);
}
}
else
{
Log.w(TAG, "Not connected to AccelService");
}
}
/**
* Puts the WiFiGPSLocationService in an "inactive" mode.
* Cancels are pending scans and sets the Run flag to stop.
* The Android service is still running and can receive calls,
* but it does not perform any energy consuming tasks.
*
*/
public void stop ()
{
mClientCount--;
Log.i(TAG, "Received a stop() call");
if (mClientCount <= 0)
{
Log.i(TAG, "Stoping operations");
mHandler.removeMessages(WIFI_SCAN_TIMER_MSG);
mWifiLock.release();
mRun = false;
mClientCount = 0;
}
else
{
Log.i(TAG, "Continuing operations");
}
}
/**
* Starts the WiFiGPSLocationService.
* Schedules a new scan message and sets the Run flag to true.
*/
public void start ()
{
Log.i(TAG, "Received a start() call");
mClientCount++;
if (!mRun)
{
mRun = true;
setupWiFi();
//Send a message to schedule the first scan
if (!mHandler.hasMessage( WIFI_SCAN_TIMER_MSG ))
mHandler.sendMessageAtTime(
mHandler.obtainMessage( WIFI_SCAN_TIMER_MSG),
SystemClock.uptimeMillis());
// Start running GPS to get current location ASAP
Log.i(TAG, "Starting GPS.");
mLocManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
mGpsScanInterval, 0, this);
mGPSRunning = true;
}
}
};
/**
* Broadcast receiver for WiFi scan updates.
* An object of this class has been passed to the system through
* registerReceiver.
*
*/
private BroadcastReceiver mWifiScanReceiver = new BroadcastReceiver()
{
@Override
public void onReceive(Context context, Intent intent)
{
String action = intent.getAction();
if (action.equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION))
{
List<ScanResult> results = mWifi.getScanResults();
Log.v(TAG, "WiFi scan found " + results.size()
+ " APs");
List<String> sResult = new ArrayList<String>();
for (ScanResult result : results)
{
//It seems APs with higher signal strengths are
//more stable. So I am ignoring weak APs.
if (result.level > SIGNAL_THRESHOLD)
sResult.add(result.BSSID);
Log.v(TAG, result.BSSID + " (" + result.level
+ "dBm)");
}
Log.v(TAG, "Filtered "
+ (results.size() - sResult.size())
+ " APs.");
Collections.sort(sResult);
updateLocation(sResult);
}
else if (action.equals(
WifiManager.WIFI_STATE_CHANGED_ACTION))
{
int wifiState = (int)
intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, 0);
if (wifiState == WifiManager.WIFI_STATE_DISABLED)
{
Log.v(TAG, "User disabeled Wifi." +
" Setting up WiFi again");
setupWiFi();
}
}
}
};
public synchronized void onLocationChanged(Location location) {
double accuracy = location.getAccuracy();
Log.i(TAG, "Received location update. Accuracy: " + accuracy);
if ( accuracy < GPS_ACCURACY_THRESHOLD)
{
mHandler.removeMessages(LOC_UPDATE_MSG);
mLastKnownLoc = location;
if (mScanCache.containsKey(mLastWifiSet))
{
if (!mScanCache.get(mLastWifiSet).known)
{
Log.i(TAG, "Updating the record: " +
cacheEntry(mLastWifiSet));
mScanCache.get(mLastWifiSet).known = true;
mScanCache.get(mLastWifiSet).loc = location;
mLastKnownLoc = location;
}
else
{
Log.v(TAG, "There is a valid record. "
+ "but still updating "
+ cacheEntry(mLastWifiSet) );
mScanCache.get(mLastWifiSet).loc = location;
mLastKnownLoc = location;
}
}
}
else
{
//Log.v(TAG, "Not accurate enough.");
mTempKnownLoc = location;
mHandler.removeMessages(LOC_UPDATE_MSG);
mHandler.sendMessageAtTime(
mHandler.obtainMessage(LOC_UPDATE_MSG),
SystemClock.uptimeMillis() + LOC_UPDATE_TIMEOUT);
}
}
//@Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
// TODO Auto-generated method stub
}
//@Override
public void onProviderEnabled(String provider)
{
// TODO Auto-generated method stub
}
//@Override
public void onProviderDisabled(String provider)
{
// TODO Auto-generated method stub
}
private synchronized void updateLocation(List<String> wifiSet)
{
long curTime = System.currentTimeMillis();
GPSInfo record;
byte[] byteKey = mDigest.digest(wifiSet.toString().getBytes());
String key = new String(byteKey);
Log.v(TAG, "Updating cache for: " + wifiSet.toString());
//TODO: If there is no wifi still check for accelearion.
// First check if the current WiFi signature is different
// from the last visited Wifi set. If they are different,
// check acceleration. If acceleration is "high" call
// each registered client
if ((!mLastWifiSet.equals(key)) || (wifiSet.size() == 0) )
{
final int N = mCallbacks.beginBroadcast();
if ((N > 0) && mAccelConnected)
{
Log.v(TAG, "Checking for acceleration threshold.");
double threshold;
ILocationChangedCallback callBack;
for (int i = 0; i < N; i++)
{
threshold = (Double) mCallbacks.getBroadcastCookie(i);
callBack = mCallbacks.getBroadcastItem(i);
try
{
if (mAccelService.significantForce(threshold))
callBack.locationChanged();
Log.i(TAG, "Exceeded " + threshold);
}
catch (RemoteException re)
{
Log.e(TAG, "Exception when calling AccelService",
re);
}
}
}
mCallbacks.finishBroadcast();
}
if (mScanCache.containsKey(mLastWifiSet))
{
if (!mScanCache.get(mLastWifiSet).known)
{
- Log.i(TAG, "Concluded no lock for ["
- + mLastWifiSet + "]");
+ Log.i(TAG, "Concluded no lock for last WiFi set");
mScanCache.get(mLastWifiSet).known = true;
}
}
// First thing, if the set is "empty", I am at a location with
// no WiFi coverage. We default to GPS scanning in such
// situations. So turn on GPS and return
if (wifiSet.size() == 0)
{
Log.i(TAG, "No WiFi AP found.");
if (!mGPSRunning)
{
Log.i(TAG, "Starting GPS.");
mLocManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
mGpsScanInterval, 0, this);
mGPSRunning = true;
}
else
{
Log.i(TAG, "Continue scanning GPS.");
}
return;
}
Log.v(TAG, "Current cache has " + mScanCache.size() + " entries.");
if (mScanCache.containsKey(key))
{
mScanCache.get(key).increment();
record = mScanCache.get(key);
Log.i(TAG, "Found a record: " + record.toString());
if (record.count <= SIGNIFICANCE_THRESHOLD)
{
Log.i(TAG, "Not significant yet. Still need to run GPS.");
if (!mGPSRunning)
{
Log.i(TAG, "Starting GPS.");
mLocManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
mGpsScanInterval, 0, this);
mGPSRunning = true;
}
else
{
Log.i(TAG, "Continue scanning GPS.");
}
}
else if (record.count > SIGNIFICANCE_THRESHOLD)
{
Log.i(TAG, "Significant record.");
// update the time stamp of the last known GPS location
if (record.loc != null)
{
// If the matching record has a location object use
// that
Log.v(TAG, "Using known location.");
mLastKnownLoc = record.loc;
}
else
{
// If the matching record does not have a location
// object
Log.i(TAG, "Using fake location.");
mLastKnownLoc = mFakeLocation;
}
mLastKnownLoc.setTime(curTime);
mLastKnownLoc.setSpeed(0);
if (mGPSRunning)
{
Log.i(TAG, "Stop scanning GPS" );
mLocManager.removeUpdates(this);
mGPSRunning = false;
}
}
}
else
{
Log.i(TAG, "New WiFi set.");
//Schedule a GPS scan
record = new GPSInfo(false, curTime);
mScanCache.put(key, record);
Log.i(TAG, "Created new cache entry: " +
record.toString());
if (!mGPSRunning)
{
Log.i(TAG, "Starting GPS.");
mLocManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
mGpsScanInterval, 0, this);
mGPSRunning = true;
}
else
{
Log.i(TAG, "Continue scanning GPS.");
}
}
mLastWifiSet = key;
}
/**
* Message handler object.
*/
private final Handler mHandler = new Handler()
{
@Override
public void handleMessage(Message msg)
{
if (msg.what == WIFI_SCAN_TIMER_MSG)
{
mWifi.startScan();
if (mRun)
mHandler.sendMessageAtTime(
mHandler.obtainMessage( WIFI_SCAN_TIMER_MSG),
SystemClock.uptimeMillis()
+ mWifiScanInterval);
}
else if (msg.what == CACHE_CLEANUP_TIMER_MSG)
{
cleanCache();
if (mRun)
mHandler.sendMessageAtTime(
mHandler.obtainMessage(CACHE_CLEANUP_TIMER_MSG
),
SystemClock.uptimeMillis() + CLEANUP_INTERVAL);
}
else if (msg.what == LOC_UPDATE_MSG)
{
Log.i(TAG, "Dealing with inaccurate location. "
+ "Accuracy: " + mTempKnownLoc.getAccuracy());
mLastKnownLoc = mTempKnownLoc;
if (mScanCache.containsKey(mLastWifiSet))
{
if (!mScanCache.get(mLastWifiSet).known)
{
Log.i(TAG, "Updating the record: " +
cacheEntry(mLastWifiSet));
mScanCache.get(mLastWifiSet).known = true;
mScanCache.get(mLastWifiSet).loc =
mTempKnownLoc;
}
}
else
{
Log.v(TAG, "No familar WiFi signature");
}
}
}
};
/**
* Finds records in the cache that have been timed out.
*/
private synchronized void cleanCache()
{
long curTime = System.currentTimeMillis();
GPSInfo record, removed;
long cacheTime;
int count;
long timeout;
HashSet<String> toBeDeleted = new HashSet<String>();
Log.i(TAG, "Cleaning up the cache.");
Log.i(TAG, "Current cache has " + mScanCache.size() + " entries.");
for (String key: mScanCache.keySet())
{
record = mScanCache.get(key);
cacheTime = record.time;
count = record.count;
timeout = curTime - (cacheTime + count*EXTENTION_TIME);
Log.i(TAG, "Checking " + cacheEntry(key));
if (count < SIGNIFICANCE_THRESHOLD)
{
if (curTime - cacheTime > ONE_HOUR)
{
Log.v(TAG, "Marking transient record for deletion: " +
record.toString());
toBeDeleted.add(key);
}
}
else if (timeout > CACHE_TIMEOUT )
{
Log.v(TAG, "Marking stale record for deletion: " +
record.toString());
// The cache entry has timed out. Remove it!
toBeDeleted.add(key);
}
}
try
{
for (String delKey : toBeDeleted)
{
Log.i(TAG, "Deleting " + cacheEntry(delKey));
removed = mScanCache.remove(delKey);
}
}
catch (ConcurrentModificationException cme)
{
Log.e(TAG, "Exception while cleaning cache.", cme);
}
}
private ServiceConnection mAccelServiceConnection
= new ServiceConnection() {
public void onServiceConnected(ComponentName className,
IBinder service)
{
mAccelService = IAccelService.Stub.asInterface(service);
mAccelConnected = true;
}
public void onServiceDisconnected(ComponentName className)
{
mAccelService = null;
mAccelConnected = false;
}
};
@Override
public IBinder onBind(Intent intent)
{
if (IWiFiGPSLocationService.class.getName().equals(
intent.getAction()))
{
return mBinder;
}
if (IWiFiGPSLocationServiceControl.class.getName().equals(
intent.getAction()))
{
return mControlBinder;
}
return null;
}
@Override
public void onStart(Intent intent, int startId)
{
super.onStart(intent, startId);
Log.i(TAG, "onStart");
}
@Override
public void onCreate() {
super.onCreate();
bindService(new Intent(ISystemLog.class.getName()),
Log.SystemLogConnection, Context.BIND_AUTO_CREATE);
bindService(new Intent(IAccelService.class.getName()),
mAccelServiceConnection, Context.BIND_AUTO_CREATE);
mCallbacks = new RemoteCallbackList<ILocationChangedCallback>();
Log.i(TAG, "onCreate");
mDbAdaptor = new DbAdaptor(this);
try
{
mDbAdaptor.open();
}
catch(SQLException e)
{
Log.e(TAG, "Exception", e);
}
//Initialize the scan cache
mScanCache = new HashMap<String, GPSInfo>();
Log.i(TAG, "Reading last saved cache");
readDb();
mFakeLocation = new Location("fake");
mFakeLocation.setLatitude(Double.NaN);
mFakeLocation.setLongitude(Double.NaN);
mFakeLocation.setSpeed(0);
mLastKnownLoc = mFakeLocation;
mLastWifiSet = " ";
resetToDefault();
try
{
mDigest = java.security.MessageDigest.getInstance("MD5");
}
catch (NoSuchAlgorithmException nae)
{
Log.e(TAG, "Exception", nae);
}
mWifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
mLocManager = (LocationManager) getSystemService(LOCATION_SERVICE);
setupWiFi();
//Register to receive WiFi scans
registerReceiver(mWifiScanReceiver, new IntentFilter(
WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
//Register to receive WiFi state changes
registerReceiver(mWifiScanReceiver, new IntentFilter(
WifiManager.WIFI_STATE_CHANGED_ACTION));
mHandler.sendMessageAtTime(
mHandler.obtainMessage(CACHE_CLEANUP_TIMER_MSG),
SystemClock.uptimeMillis() + CLEANUP_INTERVAL);
}
@Override
public void onDestroy()
{
mDbAdaptor.syncDb(mScanCache);
// Remove pending WiFi scan messages
mHandler.removeMessages(WIFI_SCAN_TIMER_MSG);
mHandler.removeMessages(CACHE_CLEANUP_TIMER_MSG);
// Cancel location update registration
mLocManager.removeUpdates(this);
mGPSRunning = false;
// Cancel WiFi scan registration
unregisterReceiver(mWifiScanReceiver);
unbindService(Log.SystemLogConnection);
unbindService(mAccelServiceConnection);
}
private void readDb()
{
String sign;
int count, hasloc;
double lat, lon, acc;
long time;
GPSInfo gpsInfo;
Location curLoc;
String provider;
Cursor c = mDbAdaptor.fetchAllEntries();
int timeIndex = c.getColumnIndex(DbAdaptor.KEY_TIME);
int countIndex = c.getColumnIndex(DbAdaptor.KEY_COUNT);
int signIndex = c.getColumnIndex(DbAdaptor.KEY_SIGNATURE);
int latIndex = c.getColumnIndex(DbAdaptor.KEY_LAT);
int lonIndex = c.getColumnIndex(DbAdaptor.KEY_LON);
int accIndex = c.getColumnIndex(DbAdaptor.KEY_ACC);
int providerIndex = c.getColumnIndex(DbAdaptor.KEY_PROVIDER);
int haslocIndex = c.getColumnIndex(DbAdaptor.KEY_HASLOC);
int dbSize = c.getCount();
Log.i(TAG, "Found " + dbSize + " entries in database.");
c.moveToFirst();
for (int i = 0; i < dbSize; i++)
{
time = c.getInt(timeIndex);
count = c.getInt(countIndex);
sign = c.getString(signIndex);
hasloc = c.getInt(haslocIndex);
gpsInfo = new GPSInfo(true, time);
if (hasloc == DbAdaptor.YES)
{
lat = c.getDouble(latIndex);
lon = c.getDouble(lonIndex);
acc = c.getDouble(accIndex);
provider = c.getString(providerIndex);
curLoc = new Location(provider);
curLoc.setLatitude(lat);
curLoc.setLongitude(lon);
curLoc.setAccuracy((float)acc);
gpsInfo.loc = curLoc;
}
else
{
Log.i(TAG, "Entry with no location.");
}
gpsInfo.count = count;
mScanCache.put(sign, gpsInfo);
Log.i(TAG, "Synced " + gpsInfo.toString());
c.moveToNext();
}
c.close();
}
private void setupWiFi()
{
// Check if WiFi is enabled
if (!mWifi.isWifiEnabled())
mWifi.setWifiEnabled(true);
if (mWifi == null)
mWifiLock = mWifi.createWifiLock(
WifiManager.WIFI_MODE_SCAN_ONLY, TAG);
if (!mWifiLock.isHeld())
mWifiLock.acquire();
}
/*
* Sets all operational parameters to their default values
*/
private void resetToDefault()
{
mWifiScanInterval = DEFAULT_WIFI_SCANNING_INTERVAL;
mGpsScanInterval = DEFAULT_GPS_SCANNING_INTERVAL;
}
private String cacheEntry(String wifiSet)
{
String res = "";
if (mScanCache.containsKey(wifiSet))
{
res += mScanCache.get(wifiSet);
}
else
{
res += "null";
}
return res;
}
}
| true | true | private synchronized void updateLocation(List<String> wifiSet)
{
long curTime = System.currentTimeMillis();
GPSInfo record;
byte[] byteKey = mDigest.digest(wifiSet.toString().getBytes());
String key = new String(byteKey);
Log.v(TAG, "Updating cache for: " + wifiSet.toString());
//TODO: If there is no wifi still check for accelearion.
// First check if the current WiFi signature is different
// from the last visited Wifi set. If they are different,
// check acceleration. If acceleration is "high" call
// each registered client
if ((!mLastWifiSet.equals(key)) || (wifiSet.size() == 0) )
{
final int N = mCallbacks.beginBroadcast();
if ((N > 0) && mAccelConnected)
{
Log.v(TAG, "Checking for acceleration threshold.");
double threshold;
ILocationChangedCallback callBack;
for (int i = 0; i < N; i++)
{
threshold = (Double) mCallbacks.getBroadcastCookie(i);
callBack = mCallbacks.getBroadcastItem(i);
try
{
if (mAccelService.significantForce(threshold))
callBack.locationChanged();
Log.i(TAG, "Exceeded " + threshold);
}
catch (RemoteException re)
{
Log.e(TAG, "Exception when calling AccelService",
re);
}
}
}
mCallbacks.finishBroadcast();
}
if (mScanCache.containsKey(mLastWifiSet))
{
if (!mScanCache.get(mLastWifiSet).known)
{
Log.i(TAG, "Concluded no lock for ["
+ mLastWifiSet + "]");
mScanCache.get(mLastWifiSet).known = true;
}
}
// First thing, if the set is "empty", I am at a location with
// no WiFi coverage. We default to GPS scanning in such
// situations. So turn on GPS and return
if (wifiSet.size() == 0)
{
Log.i(TAG, "No WiFi AP found.");
if (!mGPSRunning)
{
Log.i(TAG, "Starting GPS.");
mLocManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
mGpsScanInterval, 0, this);
mGPSRunning = true;
}
else
{
Log.i(TAG, "Continue scanning GPS.");
}
return;
}
Log.v(TAG, "Current cache has " + mScanCache.size() + " entries.");
if (mScanCache.containsKey(key))
{
mScanCache.get(key).increment();
record = mScanCache.get(key);
Log.i(TAG, "Found a record: " + record.toString());
if (record.count <= SIGNIFICANCE_THRESHOLD)
{
Log.i(TAG, "Not significant yet. Still need to run GPS.");
if (!mGPSRunning)
{
Log.i(TAG, "Starting GPS.");
mLocManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
mGpsScanInterval, 0, this);
mGPSRunning = true;
}
else
{
Log.i(TAG, "Continue scanning GPS.");
}
}
else if (record.count > SIGNIFICANCE_THRESHOLD)
{
Log.i(TAG, "Significant record.");
// update the time stamp of the last known GPS location
if (record.loc != null)
{
// If the matching record has a location object use
// that
Log.v(TAG, "Using known location.");
mLastKnownLoc = record.loc;
}
else
{
// If the matching record does not have a location
// object
Log.i(TAG, "Using fake location.");
mLastKnownLoc = mFakeLocation;
}
mLastKnownLoc.setTime(curTime);
mLastKnownLoc.setSpeed(0);
if (mGPSRunning)
{
Log.i(TAG, "Stop scanning GPS" );
mLocManager.removeUpdates(this);
mGPSRunning = false;
}
}
}
else
{
Log.i(TAG, "New WiFi set.");
//Schedule a GPS scan
record = new GPSInfo(false, curTime);
mScanCache.put(key, record);
Log.i(TAG, "Created new cache entry: " +
record.toString());
if (!mGPSRunning)
{
Log.i(TAG, "Starting GPS.");
mLocManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
mGpsScanInterval, 0, this);
mGPSRunning = true;
}
else
{
Log.i(TAG, "Continue scanning GPS.");
}
}
mLastWifiSet = key;
}
| private synchronized void updateLocation(List<String> wifiSet)
{
long curTime = System.currentTimeMillis();
GPSInfo record;
byte[] byteKey = mDigest.digest(wifiSet.toString().getBytes());
String key = new String(byteKey);
Log.v(TAG, "Updating cache for: " + wifiSet.toString());
//TODO: If there is no wifi still check for accelearion.
// First check if the current WiFi signature is different
// from the last visited Wifi set. If they are different,
// check acceleration. If acceleration is "high" call
// each registered client
if ((!mLastWifiSet.equals(key)) || (wifiSet.size() == 0) )
{
final int N = mCallbacks.beginBroadcast();
if ((N > 0) && mAccelConnected)
{
Log.v(TAG, "Checking for acceleration threshold.");
double threshold;
ILocationChangedCallback callBack;
for (int i = 0; i < N; i++)
{
threshold = (Double) mCallbacks.getBroadcastCookie(i);
callBack = mCallbacks.getBroadcastItem(i);
try
{
if (mAccelService.significantForce(threshold))
callBack.locationChanged();
Log.i(TAG, "Exceeded " + threshold);
}
catch (RemoteException re)
{
Log.e(TAG, "Exception when calling AccelService",
re);
}
}
}
mCallbacks.finishBroadcast();
}
if (mScanCache.containsKey(mLastWifiSet))
{
if (!mScanCache.get(mLastWifiSet).known)
{
Log.i(TAG, "Concluded no lock for last WiFi set");
mScanCache.get(mLastWifiSet).known = true;
}
}
// First thing, if the set is "empty", I am at a location with
// no WiFi coverage. We default to GPS scanning in such
// situations. So turn on GPS and return
if (wifiSet.size() == 0)
{
Log.i(TAG, "No WiFi AP found.");
if (!mGPSRunning)
{
Log.i(TAG, "Starting GPS.");
mLocManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
mGpsScanInterval, 0, this);
mGPSRunning = true;
}
else
{
Log.i(TAG, "Continue scanning GPS.");
}
return;
}
Log.v(TAG, "Current cache has " + mScanCache.size() + " entries.");
if (mScanCache.containsKey(key))
{
mScanCache.get(key).increment();
record = mScanCache.get(key);
Log.i(TAG, "Found a record: " + record.toString());
if (record.count <= SIGNIFICANCE_THRESHOLD)
{
Log.i(TAG, "Not significant yet. Still need to run GPS.");
if (!mGPSRunning)
{
Log.i(TAG, "Starting GPS.");
mLocManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
mGpsScanInterval, 0, this);
mGPSRunning = true;
}
else
{
Log.i(TAG, "Continue scanning GPS.");
}
}
else if (record.count > SIGNIFICANCE_THRESHOLD)
{
Log.i(TAG, "Significant record.");
// update the time stamp of the last known GPS location
if (record.loc != null)
{
// If the matching record has a location object use
// that
Log.v(TAG, "Using known location.");
mLastKnownLoc = record.loc;
}
else
{
// If the matching record does not have a location
// object
Log.i(TAG, "Using fake location.");
mLastKnownLoc = mFakeLocation;
}
mLastKnownLoc.setTime(curTime);
mLastKnownLoc.setSpeed(0);
if (mGPSRunning)
{
Log.i(TAG, "Stop scanning GPS" );
mLocManager.removeUpdates(this);
mGPSRunning = false;
}
}
}
else
{
Log.i(TAG, "New WiFi set.");
//Schedule a GPS scan
record = new GPSInfo(false, curTime);
mScanCache.put(key, record);
Log.i(TAG, "Created new cache entry: " +
record.toString());
if (!mGPSRunning)
{
Log.i(TAG, "Starting GPS.");
mLocManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
mGpsScanInterval, 0, this);
mGPSRunning = true;
}
else
{
Log.i(TAG, "Continue scanning GPS.");
}
}
mLastWifiSet = key;
}
|
diff --git a/src/test/java/org/jvnet/hudson/crypto/RSAPublicKeyUtilTest.java b/src/test/java/org/jvnet/hudson/crypto/RSAPublicKeyUtilTest.java
index f9c4134..cce8332 100644
--- a/src/test/java/org/jvnet/hudson/crypto/RSAPublicKeyUtilTest.java
+++ b/src/test/java/org/jvnet/hudson/crypto/RSAPublicKeyUtilTest.java
@@ -1,25 +1,25 @@
package org.jvnet.hudson.crypto;
import junit.framework.TestCase;
import java.math.BigInteger;
import java.security.interfaces.RSAPublicKey;
/**
* @author Kohsuke Kawaguchi
*/
public class RSAPublicKeyUtilTest extends TestCase {
public void testReadPublicKey() throws Exception {
RSAPublicKey p = (RSAPublicKey) RSAPublicKeyUtil.readPublicKey("ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCzBy1GEihAxSgrsEANgCxYwxS8Yy0U7cKq/1MMtr4/IrW2m2rzDcr4a7ZG/p/XrchCMn5eIekq1dYHsB0hY81iJr7jMZi7XbQx/LohF833YhIRctALpNzPunqBxZvOUVDib/dfX6LuoZTOojI/W5UPYrzAjyrjKMQvF5Mo0LaZ6eN1LElVaGzWExqO7mNkOrJY3IVurPu81mK4E+59FHTuB/oIawHUlxjMgBFPGKZBmb0cyVyViEmY6E78bNcN+frdSxZ72gcK/J7l1gfGz6YNQX6hKA+3v2O+/6pHf282W2hy0u4nw2DTs5NrsTnG8koiivilXC3VbhgVmQnUFKx5 [email protected]");
System.out.println(p);
- assertEquals(p.getModulus(), new BigInteger("65537"));
+ assertEquals(p.getModulus(), new BigInteger("B3072D46122840C5282BB0400D802C58C314BC632D14EDC2AAFF530CB6BE3F22B5B69B6AF30DCAF86BB646FE9FD7ADC842327E5E21E92AD5D607B01D2163CD6226BEE33198BB5DB431FCBA2117CDF762121172D00BA4DCCFBA7A81C59BCE5150E26FF75F5FA2EEA194CEA2323F5B950F62BCC08F2AE328C42F179328D0B699E9E3752C4955686CD6131A8EEE63643AB258DC856EACFBBCD662B813EE7D1474EE07FA086B01D49718CC80114F18A64199BD1CC95C95884998E84EFC6CD70DF9FADD4B167BDA070AFC9EE5D607C6CFA60D417EA1280FB7BF63BEFFAA477F6F365B6872D2EE27C360D3B3936BB139C6F24A228AF8A55C2DD56E18159909D414AC79",16));
// this hex output I got from "openssl rsa -modulus -noout -in ~/.ssh/id_rsa"
- assertEquals(p.getPublicExponent(), new BigInteger("B3072D46122840C5282BB0400D802C58C314BC632D14EDC2AAFF530CB6BE3F22B5B69B6AF30DCAF86BB646FE9FD7ADC842327E5E21E92AD5D607B01D2163CD6226BEE33198BB5DB431FCBA2117CDF762121172D00BA4DCCFBA7A81C59BCE5150E26FF75F5FA2EEA194CEA2323F5B950F62BCC08F2AE328C42F179328D0B699E9E3752C4955686CD6131A8EEE63643AB258DC856EACFBBCD662B813EE7D1474EE07FA086B01D49718CC80114F18A64199BD1CC95C95884998E84EFC6CD70DF9FADD4B167BDA070AFC9EE5D607C6CFA60D417EA1280FB7BF63BEFFAA477F6F365B6872D2EE27C360D3B3936BB139C6F24A228AF8A55C2DD56E18159909D414AC79",16));
+ assertEquals(p.getPublicExponent(), new BigInteger("65537"));
}
public void testGetFingerPrint() throws Exception {
RSAPublicKey p = (RSAPublicKey) RSAPublicKeyUtil.readPublicKey("ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCzBy1GEihAxSgrsEANgCxYwxS8Yy0U7cKq/1MMtr4/IrW2m2rzDcr4a7ZG/p/XrchCMn5eIekq1dYHsB0hY81iJr7jMZi7XbQx/LohF833YhIRctALpNzPunqBxZvOUVDib/dfX6LuoZTOojI/W5UPYrzAjyrjKMQvF5Mo0LaZ6eN1LElVaGzWExqO7mNkOrJY3IVurPu81mK4E+59FHTuB/oIawHUlxjMgBFPGKZBmb0cyVyViEmY6E78bNcN+frdSxZ72gcK/J7l1gfGz6YNQX6hKA+3v2O+/6pHf282W2hy0u4nw2DTs5NrsTnG8koiivilXC3VbhgVmQnUFKx5 [email protected]");
assertEquals("f7:7a:42:76:79:e8:8a:1a:4a:32:0c:b3:f9:3b:53:d4",RSAPublicKeyUtil.getFingerPrint(p));
}
}
| false | true | public void testReadPublicKey() throws Exception {
RSAPublicKey p = (RSAPublicKey) RSAPublicKeyUtil.readPublicKey("ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCzBy1GEihAxSgrsEANgCxYwxS8Yy0U7cKq/1MMtr4/IrW2m2rzDcr4a7ZG/p/XrchCMn5eIekq1dYHsB0hY81iJr7jMZi7XbQx/LohF833YhIRctALpNzPunqBxZvOUVDib/dfX6LuoZTOojI/W5UPYrzAjyrjKMQvF5Mo0LaZ6eN1LElVaGzWExqO7mNkOrJY3IVurPu81mK4E+59FHTuB/oIawHUlxjMgBFPGKZBmb0cyVyViEmY6E78bNcN+frdSxZ72gcK/J7l1gfGz6YNQX6hKA+3v2O+/6pHf282W2hy0u4nw2DTs5NrsTnG8koiivilXC3VbhgVmQnUFKx5 [email protected]");
System.out.println(p);
assertEquals(p.getModulus(), new BigInteger("65537"));
// this hex output I got from "openssl rsa -modulus -noout -in ~/.ssh/id_rsa"
assertEquals(p.getPublicExponent(), new BigInteger("B3072D46122840C5282BB0400D802C58C314BC632D14EDC2AAFF530CB6BE3F22B5B69B6AF30DCAF86BB646FE9FD7ADC842327E5E21E92AD5D607B01D2163CD6226BEE33198BB5DB431FCBA2117CDF762121172D00BA4DCCFBA7A81C59BCE5150E26FF75F5FA2EEA194CEA2323F5B950F62BCC08F2AE328C42F179328D0B699E9E3752C4955686CD6131A8EEE63643AB258DC856EACFBBCD662B813EE7D1474EE07FA086B01D49718CC80114F18A64199BD1CC95C95884998E84EFC6CD70DF9FADD4B167BDA070AFC9EE5D607C6CFA60D417EA1280FB7BF63BEFFAA477F6F365B6872D2EE27C360D3B3936BB139C6F24A228AF8A55C2DD56E18159909D414AC79",16));
}
| public void testReadPublicKey() throws Exception {
RSAPublicKey p = (RSAPublicKey) RSAPublicKeyUtil.readPublicKey("ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCzBy1GEihAxSgrsEANgCxYwxS8Yy0U7cKq/1MMtr4/IrW2m2rzDcr4a7ZG/p/XrchCMn5eIekq1dYHsB0hY81iJr7jMZi7XbQx/LohF833YhIRctALpNzPunqBxZvOUVDib/dfX6LuoZTOojI/W5UPYrzAjyrjKMQvF5Mo0LaZ6eN1LElVaGzWExqO7mNkOrJY3IVurPu81mK4E+59FHTuB/oIawHUlxjMgBFPGKZBmb0cyVyViEmY6E78bNcN+frdSxZ72gcK/J7l1gfGz6YNQX6hKA+3v2O+/6pHf282W2hy0u4nw2DTs5NrsTnG8koiivilXC3VbhgVmQnUFKx5 [email protected]");
System.out.println(p);
assertEquals(p.getModulus(), new BigInteger("B3072D46122840C5282BB0400D802C58C314BC632D14EDC2AAFF530CB6BE3F22B5B69B6AF30DCAF86BB646FE9FD7ADC842327E5E21E92AD5D607B01D2163CD6226BEE33198BB5DB431FCBA2117CDF762121172D00BA4DCCFBA7A81C59BCE5150E26FF75F5FA2EEA194CEA2323F5B950F62BCC08F2AE328C42F179328D0B699E9E3752C4955686CD6131A8EEE63643AB258DC856EACFBBCD662B813EE7D1474EE07FA086B01D49718CC80114F18A64199BD1CC95C95884998E84EFC6CD70DF9FADD4B167BDA070AFC9EE5D607C6CFA60D417EA1280FB7BF63BEFFAA477F6F365B6872D2EE27C360D3B3936BB139C6F24A228AF8A55C2DD56E18159909D414AC79",16));
// this hex output I got from "openssl rsa -modulus -noout -in ~/.ssh/id_rsa"
assertEquals(p.getPublicExponent(), new BigInteger("65537"));
}
|
diff --git a/WEB-INF/src/hygeia/Algorithm.java b/WEB-INF/src/hygeia/Algorithm.java
index 2e6b740..6dad44d 100644
--- a/WEB-INF/src/hygeia/Algorithm.java
+++ b/WEB-INF/src/hygeia/Algorithm.java
@@ -1,137 +1,137 @@
package hygeia;
import java.sql.*;
import java.security.*;
import java.util.StringTokenizer;
import java.util.ArrayList;
import java.util.Random;
public class Algorithm {
private Database db;
private int uid;
private static final int BREAKFAST = 0x08;
private static final int LUNCH = 0x04;
private static final int DINNER = 0x02;
private static final int SNACK = 0x01;
private static final double SAME = 0.1; //used as a margin of error for relatively balanced meals
public Algorithm(Database db, User u) {
this.uid = u.getUid();
this.db = u.getDb();
}
/* Main algorithm. */
/* Based on what kind of meal requested an int matching the legend is passed. */
public static Meal suggestMeal(User u, int type) {
try {
Meal m = suggestMeal0(u, type);
u.getDb().free();
return m;
} catch (SQLException e) {
u.getDb().free();
return null;
}
}
public static Meal suggestMeal0(User u, int type) throws SQLException {
if (u == null) {
return null;
}
Database db = u.getDb();
//pulls all meals from the universal meal list and the user's personal meals
- ResultSet rs = db.execute("select mid from meals where uid = " + u.getUid() + " or uid = 0;");
+ ResultSet rs = db.execute("select mid from meals where (uid = " +
+ u.getUid() + " or uid = 0) and type & " + type + " = " + type + ";");
//arraylist of meal IDs that come from the database
ArrayList<Integer> results = new ArrayList<Integer>();
while(rs.next())
{
results.add(rs.getInt("mid"));
}
//retrieves a list of food in the inventory
Inventory inven = new Inventory(u);
Food.Update[] fu = inven.getInventory();
//random generator to select a meal at random from available MIDs
- Random r = new Random(results.size());
+ Random r = new Random();
//if the inventorymatchcount variable equals the number of ingredients in a recipe, all necessary ingredients are available
int inventorymatchcount = 0;
//Meal m is the variable used to store meals as they are accessed for comparison to ingredients
Meal m;
//while loop runs while a suitable meal isn't found yet
while (results.size() > 0)
{
inventorymatchcount = 0;
- m = new Meal(db, results.get(r.nextInt()));
+ m = new Meal(db, results.get(r.nextInt(results.size())));
Food.Update mu[] = m.getMeal();
for (int i = 0; i < mu.length; i++)
{
for (int j = 0; j < fu.length; j++)
{
if (mu[i].equals(fu[j]))
inventorymatchcount += 1;
}
}
if (inventorymatchcount == mu.length)
{
//currently not calorie budget based. Functionality will be added if budget is accessible.
//begins balanced suggestion based on the 40:30:30 ideal,
//+ and - 10% (defined as constant SAME, Suggest A Meal Error) to find relatively balanced meals
Nutrition n = m.getNutrition();
double totalGrams = 0;
totalGrams = (n.getCarbohydrates() + n.getProtein() + n.getFat());
if (n.getCarbohydrates() / totalGrams > 0.4 - SAME
&& n.getCarbohydrates() / totalGrams < 0.4 + SAME)
{
if (n.getProtein() / totalGrams > 0.3 - SAME
&& n.getProtein() / totalGrams < 0.3 + SAME)
{
if (n.getFat() / totalGrams > 0.3 - SAME
&& n.getFat() / totalGrams < 0.3 + SAME)
{
return m;
}
}
}
}
else
{
//if the contents of the inventory don't satisfy the recipe, remove that recipe
//from the ArrayList of meals so it won't accidentally be compared again
results.remove(m.getMid());
- r = new Random(results.size());
}
}
//if no meal matches the SAME margin of error for balancedness, return null
return null;
}
/* Sanitizes a String for use. */
public static String Clean(String s) {
StringTokenizer toke = new StringTokenizer(s, "*/\\\"\':;-()=+[]");
String r = new String("");
while(toke.hasMoreTokens())
{
r = new String(r + toke.nextToken());
}
return r;
}
/* Should return MD5 hashes.. but may be platform dependent. And this was
written by some anonymous author. FYI. */
public static String MD5(String md5) {
try {
java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
byte[] array = md.digest(md5.getBytes());
StringBuffer sb = new StringBuffer();
for (int i = 0; i < array.length; ++i) {
sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1,3));
}
return sb.toString();
} catch (java.security.NoSuchAlgorithmException e) {
}
return null;
}
}
| false | true | public static Meal suggestMeal0(User u, int type) throws SQLException {
if (u == null) {
return null;
}
Database db = u.getDb();
//pulls all meals from the universal meal list and the user's personal meals
ResultSet rs = db.execute("select mid from meals where uid = " + u.getUid() + " or uid = 0;");
//arraylist of meal IDs that come from the database
ArrayList<Integer> results = new ArrayList<Integer>();
while(rs.next())
{
results.add(rs.getInt("mid"));
}
//retrieves a list of food in the inventory
Inventory inven = new Inventory(u);
Food.Update[] fu = inven.getInventory();
//random generator to select a meal at random from available MIDs
Random r = new Random(results.size());
//if the inventorymatchcount variable equals the number of ingredients in a recipe, all necessary ingredients are available
int inventorymatchcount = 0;
//Meal m is the variable used to store meals as they are accessed for comparison to ingredients
Meal m;
//while loop runs while a suitable meal isn't found yet
while (results.size() > 0)
{
inventorymatchcount = 0;
m = new Meal(db, results.get(r.nextInt()));
Food.Update mu[] = m.getMeal();
for (int i = 0; i < mu.length; i++)
{
for (int j = 0; j < fu.length; j++)
{
if (mu[i].equals(fu[j]))
inventorymatchcount += 1;
}
}
if (inventorymatchcount == mu.length)
{
//currently not calorie budget based. Functionality will be added if budget is accessible.
//begins balanced suggestion based on the 40:30:30 ideal,
//+ and - 10% (defined as constant SAME, Suggest A Meal Error) to find relatively balanced meals
Nutrition n = m.getNutrition();
double totalGrams = 0;
totalGrams = (n.getCarbohydrates() + n.getProtein() + n.getFat());
if (n.getCarbohydrates() / totalGrams > 0.4 - SAME
&& n.getCarbohydrates() / totalGrams < 0.4 + SAME)
{
if (n.getProtein() / totalGrams > 0.3 - SAME
&& n.getProtein() / totalGrams < 0.3 + SAME)
{
if (n.getFat() / totalGrams > 0.3 - SAME
&& n.getFat() / totalGrams < 0.3 + SAME)
{
return m;
}
}
}
}
else
{
//if the contents of the inventory don't satisfy the recipe, remove that recipe
//from the ArrayList of meals so it won't accidentally be compared again
results.remove(m.getMid());
r = new Random(results.size());
}
}
//if no meal matches the SAME margin of error for balancedness, return null
return null;
}
| public static Meal suggestMeal0(User u, int type) throws SQLException {
if (u == null) {
return null;
}
Database db = u.getDb();
//pulls all meals from the universal meal list and the user's personal meals
ResultSet rs = db.execute("select mid from meals where (uid = " +
u.getUid() + " or uid = 0) and type & " + type + " = " + type + ";");
//arraylist of meal IDs that come from the database
ArrayList<Integer> results = new ArrayList<Integer>();
while(rs.next())
{
results.add(rs.getInt("mid"));
}
//retrieves a list of food in the inventory
Inventory inven = new Inventory(u);
Food.Update[] fu = inven.getInventory();
//random generator to select a meal at random from available MIDs
Random r = new Random();
//if the inventorymatchcount variable equals the number of ingredients in a recipe, all necessary ingredients are available
int inventorymatchcount = 0;
//Meal m is the variable used to store meals as they are accessed for comparison to ingredients
Meal m;
//while loop runs while a suitable meal isn't found yet
while (results.size() > 0)
{
inventorymatchcount = 0;
m = new Meal(db, results.get(r.nextInt(results.size())));
Food.Update mu[] = m.getMeal();
for (int i = 0; i < mu.length; i++)
{
for (int j = 0; j < fu.length; j++)
{
if (mu[i].equals(fu[j]))
inventorymatchcount += 1;
}
}
if (inventorymatchcount == mu.length)
{
//currently not calorie budget based. Functionality will be added if budget is accessible.
//begins balanced suggestion based on the 40:30:30 ideal,
//+ and - 10% (defined as constant SAME, Suggest A Meal Error) to find relatively balanced meals
Nutrition n = m.getNutrition();
double totalGrams = 0;
totalGrams = (n.getCarbohydrates() + n.getProtein() + n.getFat());
if (n.getCarbohydrates() / totalGrams > 0.4 - SAME
&& n.getCarbohydrates() / totalGrams < 0.4 + SAME)
{
if (n.getProtein() / totalGrams > 0.3 - SAME
&& n.getProtein() / totalGrams < 0.3 + SAME)
{
if (n.getFat() / totalGrams > 0.3 - SAME
&& n.getFat() / totalGrams < 0.3 + SAME)
{
return m;
}
}
}
}
else
{
//if the contents of the inventory don't satisfy the recipe, remove that recipe
//from the ArrayList of meals so it won't accidentally be compared again
results.remove(m.getMid());
}
}
//if no meal matches the SAME margin of error for balancedness, return null
return null;
}
|
diff --git a/choco-solver/src/main/java/solver/constraints/propagators/reified/PropImplied.java b/choco-solver/src/main/java/solver/constraints/propagators/reified/PropImplied.java
index 6c0f73d5e..3720cd8f0 100644
--- a/choco-solver/src/main/java/solver/constraints/propagators/reified/PropImplied.java
+++ b/choco-solver/src/main/java/solver/constraints/propagators/reified/PropImplied.java
@@ -1,146 +1,148 @@
/*
* Copyright (c) 1999-2012, Ecole des Mines de Nantes
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * 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.
* * Neither the name of the Ecole des Mines de Nantes nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY
* EXPRESS 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 REGENTS AND 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.
*/
package solver.constraints.propagators.reified;
import solver.constraints.Constraint;
import solver.constraints.propagators.Propagator;
import solver.constraints.propagators.PropagatorPriority;
import solver.constraints.reified.ImplicationConstraint;
import solver.exception.ContradictionException;
import solver.explanations.Deduction;
import solver.explanations.Explanation;
import solver.explanations.VariableState;
import solver.variables.BoolVar;
import solver.variables.EventType;
import solver.variables.Variable;
import util.ESat;
import util.tools.ArrayUtils;
/**
* Implication propagator
* <p/>
* <br/>
*
* @author Jean-Guillaume Fages
* @since 02/2013
*/
public class PropImplied extends Propagator<Variable> {
// boolean variable of the reification
private final BoolVar bVar;
// constraint to apply if bVar = true
private final Constraint trueCons;
// constraint of this propagator
// constraint to apply if bVar = false
private final Constraint falseCons;
private final ImplicationConstraint reifCons;
public PropImplied(BoolVar bool, ImplicationConstraint reifCons, Constraint consIfBoolTrue, Constraint consIfBoolFalse) {
super(ArrayUtils.append(new BoolVar[]{bool}, reifCons.getVariables()), PropagatorPriority.LINEAR, false);
this.bVar = (BoolVar) vars[0];
this.trueCons = consIfBoolTrue;
this.falseCons = consIfBoolFalse;
this.reifCons = reifCons;
}
@Override
public void propagate(int evtmask) throws ContradictionException {
if (bVar.instantiated()) {
if (bVar.getBooleanValue() == ESat.TRUE) {
reifCons.activate(0);
} else {
reifCons.activate(1);
}
setPassive();
} else {
ESat sat = trueCons.isEntailed();
if (sat == ESat.FALSE) {
bVar.setToFalse(aCause);
+ reifCons.activate(1);
setPassive();
}
sat = falseCons.isEntailed();
if (sat == ESat.FALSE) {
bVar.setToTrue(aCause);
+ reifCons.activate(0);
setPassive();
}
}
}
@Override
public void propagate(int varIdx, int mask) throws ContradictionException {
if (varIdx == 0) {
if (bVar.getBooleanValue() == ESat.TRUE) {
reifCons.activate(0);
} else {
reifCons.activate(1);
}
setPassive();
} else {
forcePropagate(EventType.FULL_PROPAGATION);
}
}
@Override
public int getPropagationConditions(int vIdx) {
// we do not known which kind of variables are involved in the target constraint
return EventType.ALL_FINE_EVENTS.mask;
}
@Override
public ESat isEntailed() {
if (bVar.instantiated()) {
if (bVar.getValue() == 1) {
return trueCons.isEntailed();
} else {
return falseCons.isEntailed();
}
}
return ESat.UNDEFINED;
}
@Override
public void explain(Deduction d, Explanation e) {
e.add(solver.getExplainer().getPropagatorActivation(this));
e.add(this);
if (d.getVar() == bVar) {
// the current deduction is due to the current domain of the involved variables
for (Variable v : reifCons.getVariables()) {
v.explain(VariableState.DOM, e);
}
} else {
throw new UnsupportedOperationException();
}
// and the application of the current propagator
}
@Override
public String toString() {
return bVar.toString() + "=>" + trueCons.toString()+", !"+bVar.toString() + "=>" + falseCons.toString();
}
}
| false | true | public void propagate(int evtmask) throws ContradictionException {
if (bVar.instantiated()) {
if (bVar.getBooleanValue() == ESat.TRUE) {
reifCons.activate(0);
} else {
reifCons.activate(1);
}
setPassive();
} else {
ESat sat = trueCons.isEntailed();
if (sat == ESat.FALSE) {
bVar.setToFalse(aCause);
setPassive();
}
sat = falseCons.isEntailed();
if (sat == ESat.FALSE) {
bVar.setToTrue(aCause);
setPassive();
}
}
}
| public void propagate(int evtmask) throws ContradictionException {
if (bVar.instantiated()) {
if (bVar.getBooleanValue() == ESat.TRUE) {
reifCons.activate(0);
} else {
reifCons.activate(1);
}
setPassive();
} else {
ESat sat = trueCons.isEntailed();
if (sat == ESat.FALSE) {
bVar.setToFalse(aCause);
reifCons.activate(1);
setPassive();
}
sat = falseCons.isEntailed();
if (sat == ESat.FALSE) {
bVar.setToTrue(aCause);
reifCons.activate(0);
setPassive();
}
}
}
|
diff --git a/core-jndi/src/main/java/org/apache/directory/server/core/jndi/ServerContext.java b/core-jndi/src/main/java/org/apache/directory/server/core/jndi/ServerContext.java
index c4d77f4bd8..1d4115ecb9 100644
--- a/core-jndi/src/main/java/org/apache/directory/server/core/jndi/ServerContext.java
+++ b/core-jndi/src/main/java/org/apache/directory/server/core/jndi/ServerContext.java
@@ -1,1812 +1,1812 @@
/*
* 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.directory.server.core.jndi;
import java.io.Serializable;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import javax.naming.Context;
import javax.naming.InvalidNameException;
import javax.naming.Name;
import javax.naming.NameNotFoundException;
import javax.naming.NameParser;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.NoPermissionException;
import javax.naming.Reference;
import javax.naming.Referenceable;
import javax.naming.directory.DirContext;
import javax.naming.directory.SchemaViolationException;
import javax.naming.directory.SearchControls;
import javax.naming.event.EventContext;
import javax.naming.event.NamingListener;
import javax.naming.ldap.Control;
import javax.naming.ldap.LdapName;
import javax.naming.spi.DirStateFactory;
import javax.naming.spi.DirectoryManager;
import org.apache.directory.server.core.CoreSession;
import org.apache.directory.server.core.DefaultCoreSession;
import org.apache.directory.server.core.DirectoryService;
import org.apache.directory.server.core.LdapPrincipal;
import org.apache.directory.server.core.OperationManager;
import org.apache.directory.server.core.entry.ServerEntryUtils;
import org.apache.directory.server.core.event.DirectoryListener;
import org.apache.directory.server.core.event.NotificationCriteria;
import org.apache.directory.server.core.filtering.BaseEntryFilteringCursor;
import org.apache.directory.server.core.filtering.EntryFilteringCursor;
import org.apache.directory.server.core.interceptor.context.AddOperationContext;
import org.apache.directory.server.core.interceptor.context.BindOperationContext;
import org.apache.directory.server.core.interceptor.context.CompareOperationContext;
import org.apache.directory.server.core.interceptor.context.DeleteOperationContext;
import org.apache.directory.server.core.interceptor.context.EntryOperationContext;
import org.apache.directory.server.core.interceptor.context.GetRootDSEOperationContext;
import org.apache.directory.server.core.interceptor.context.ListOperationContext;
import org.apache.directory.server.core.interceptor.context.LookupOperationContext;
import org.apache.directory.server.core.interceptor.context.ModifyOperationContext;
import org.apache.directory.server.core.interceptor.context.MoveAndRenameOperationContext;
import org.apache.directory.server.core.interceptor.context.MoveOperationContext;
import org.apache.directory.server.core.interceptor.context.OperationContext;
import org.apache.directory.server.core.interceptor.context.RenameOperationContext;
import org.apache.directory.server.core.interceptor.context.SearchOperationContext;
import org.apache.directory.server.i18n.I18n;
import org.apache.directory.shared.asn1.DecoderException;
import org.apache.directory.shared.asn1.ber.Asn1Decoder;
import org.apache.directory.shared.ldap.codec.controls.Cascade;
import org.apache.directory.shared.ldap.codec.controls.CascadeDecorator;
import org.apache.directory.shared.ldap.codec.controls.ControlEnum;
import org.apache.directory.shared.ldap.codec.controls.ManageDsaIT;
import org.apache.directory.shared.ldap.codec.controls.ManageDsaITDecorator;
import org.apache.directory.shared.ldap.codec.controls.ppolicy.PasswordPolicyRequestControl;
import org.apache.directory.shared.ldap.codec.controls.ppolicy.PasswordPolicyResponseControl;
import org.apache.directory.shared.ldap.codec.controls.ppolicy.PasswordPolicyResponseControlContainer;
import org.apache.directory.shared.ldap.codec.controls.ppolicy.PasswordPolicyResponseControlDecoder;
import org.apache.directory.shared.ldap.codec.controls.replication.syncDoneValue.SyncDoneValueControl;
import org.apache.directory.shared.ldap.codec.controls.replication.syncDoneValue.SyncDoneValueControlContainer;
import org.apache.directory.shared.ldap.codec.controls.replication.syncDoneValue.SyncDoneValueControlDecoder;
import org.apache.directory.shared.ldap.codec.controls.replication.syncInfoValue.SyncInfoValueControl;
import org.apache.directory.shared.ldap.codec.controls.replication.syncInfoValue.SyncInfoValueControlContainer;
import org.apache.directory.shared.ldap.codec.controls.replication.syncInfoValue.SyncInfoValueControlDecoder;
import org.apache.directory.shared.ldap.codec.controls.replication.syncRequestValue.SyncRequestValueControl;
import org.apache.directory.shared.ldap.codec.controls.replication.syncRequestValue.SyncRequestValueControlContainer;
import org.apache.directory.shared.ldap.codec.controls.replication.syncRequestValue.SyncRequestValueControlDecoder;
import org.apache.directory.shared.ldap.codec.controls.replication.syncStateValue.SyncStateValueControl;
import org.apache.directory.shared.ldap.codec.controls.replication.syncStateValue.SyncStateValueControlContainer;
import org.apache.directory.shared.ldap.codec.controls.replication.syncStateValue.SyncStateValueControlDecoder;
import org.apache.directory.shared.ldap.codec.controls.replication.syncmodifydn.SyncModifyDnControl;
import org.apache.directory.shared.ldap.codec.controls.replication.syncmodifydn.SyncModifyDnControlContainer;
import org.apache.directory.shared.ldap.codec.controls.replication.syncmodifydn.SyncModifyDnControlDecoder;
import org.apache.directory.shared.ldap.codec.search.controls.entryChange.EntryChange;
import org.apache.directory.shared.ldap.codec.search.controls.entryChange.EntryChangeContainer;
import org.apache.directory.shared.ldap.codec.search.controls.entryChange.EntryChangeDecorator;
import org.apache.directory.shared.ldap.codec.search.controls.entryChange.EntryChangeDecoder;
import org.apache.directory.shared.ldap.codec.search.controls.pagedSearch.PagedResults;
import org.apache.directory.shared.ldap.codec.search.controls.pagedSearch.PagedResultsContainer;
import org.apache.directory.shared.ldap.codec.search.controls.pagedSearch.PagedResultsDecoder;
import org.apache.directory.shared.ldap.codec.search.controls.pagedSearch.PagedResultsDecorator;
import org.apache.directory.shared.ldap.codec.search.controls.persistentSearch.PersistentSearch;
import org.apache.directory.shared.ldap.codec.search.controls.persistentSearch.PersistentSearchContainer;
import org.apache.directory.shared.ldap.codec.search.controls.persistentSearch.PersistentSearchDecoder;
import org.apache.directory.shared.ldap.codec.search.controls.persistentSearch.PersistentSearchDecorator;
import org.apache.directory.shared.ldap.codec.search.controls.subentries.Subentries;
import org.apache.directory.shared.ldap.codec.search.controls.subentries.SubentriesDecorator;
import org.apache.directory.shared.ldap.codec.search.controls.subentries.SubentriesContainer;
import org.apache.directory.shared.ldap.codec.search.controls.subentries.SubentriesDecoder;
import org.apache.directory.shared.ldap.model.constants.JndiPropertyConstants;
import org.apache.directory.shared.ldap.model.constants.SchemaConstants;
import org.apache.directory.shared.ldap.model.cursor.EmptyCursor;
import org.apache.directory.shared.ldap.model.cursor.SingletonCursor;
import org.apache.directory.shared.ldap.model.entry.*;
import org.apache.directory.shared.ldap.model.exception.LdapException;
import org.apache.directory.shared.ldap.model.exception.LdapInvalidAttributeTypeException;
import org.apache.directory.shared.ldap.model.exception.LdapInvalidDnException;
import org.apache.directory.shared.ldap.model.filter.EqualityNode;
import org.apache.directory.shared.ldap.model.filter.ExprNode;
import org.apache.directory.shared.ldap.model.filter.PresenceNode;
import org.apache.directory.shared.ldap.model.filter.SearchScope;
import org.apache.directory.shared.ldap.model.message.AliasDerefMode;
import org.apache.directory.shared.ldap.model.name.Dn;
import org.apache.directory.shared.ldap.model.name.Rdn;
import org.apache.directory.shared.ldap.model.name.Ava;
import org.apache.directory.shared.ldap.model.schema.AttributeType;
import org.apache.directory.shared.ldap.model.schema.SchemaManager;
import org.apache.directory.shared.ldap.util.JndiUtils;
import org.apache.directory.shared.util.Strings;
/**
* A non-federated abstract Context implementation.
*
* @author <a href="mailto:[email protected]">Apache Directory Project</a>
*/
public abstract class ServerContext implements EventContext
{
/** property key used for deleting the old Rdn on a rename */
public static final String DELETE_OLD_RDN_PROP = JndiPropertyConstants.JNDI_LDAP_DELETE_RDN;
/** Empty array of controls for use in dealing with them */
protected static final Control[] EMPTY_CONTROLS = new Control[0];
/** The directory service which owns this context **/
private final DirectoryService service;
/** The SchemManager instance */
protected SchemaManager schemaManager;
/** A reference to the ObjectClass AT */
protected AttributeType OBJECT_CLASS_AT;
/** The cloned environment used by this Context */
private final Hashtable<String, Object> env;
/** The distinguished name of this Context */
private final Dn dn;
/** The set of registered NamingListeners */
private final Map<NamingListener,DirectoryListener> listeners =
new HashMap<NamingListener,DirectoryListener>();
/** The request controls to set on operations before performing them */
protected Control[] requestControls = EMPTY_CONTROLS;
/** The response controls to set after performing operations */
protected Control[] responseControls = EMPTY_CONTROLS;
/** Connection level controls associated with the session */
protected Control[] connectControls = EMPTY_CONTROLS;
/** The session */
private final CoreSession session;
private static final Map<String, ControlEnum> ADS_CONTROLS = new HashMap<String, ControlEnum>();
static
{
ADS_CONTROLS.put( Cascade.OID, ControlEnum.CASCADE_CONTROL );
ADS_CONTROLS.put( EntryChange.OID, ControlEnum.ENTRY_CHANGE_CONTROL );
ADS_CONTROLS.put( ManageDsaIT.OID, ControlEnum.MANAGE_DSA_IT_CONTROL );
ADS_CONTROLS.put( PagedResults.OID, ControlEnum.PAGED_RESULTS_CONTROL );
ADS_CONTROLS.put( PasswordPolicyRequestControl.CONTROL_OID, ControlEnum.PASSWORD_POLICY_REQUEST_CONTROL );
ADS_CONTROLS.put( PersistentSearch.CONTROL_OID, ControlEnum.PERSISTENT_SEARCH_CONTROL );
ADS_CONTROLS.put( Subentries.OID, ControlEnum.SUBENTRIES_CONTROL );
ADS_CONTROLS.put( SyncDoneValueControl.CONTROL_OID, ControlEnum.SYNC_DONE_VALUE_CONTROL );
ADS_CONTROLS.put( SyncInfoValueControl.CONTROL_OID, ControlEnum.SYNC_INFO_VALUE_CONTROL );
ADS_CONTROLS.put( SyncModifyDnControl.CONTROL_OID, ControlEnum.SYNC_MODIFY_DN_CONTROL );
ADS_CONTROLS.put( SyncRequestValueControl.CONTROL_OID, ControlEnum.SYNC_REQUEST_VALUE_CONTROL );
ADS_CONTROLS.put( SyncStateValueControl.CONTROL_OID, ControlEnum.SYNC_STATE_VALUE_CONTROL );
}
// ------------------------------------------------------------------------
// Constructors
// ------------------------------------------------------------------------
/**
* Must be called by all subclasses to initialize the nexus proxy and the
* environment settings to be used by this Context implementation. This
* specific constructor relies on the presence of the {@link
* Context#PROVIDER_URL} key and value to determine the distinguished name
* of the newly created context. It also checks to make sure the
* referenced name actually exists within the system. This constructor
* is used for all InitialContext requests.
*
* @param service the parent service that manages this context
* @param env the environment properties used by this context.
* @throws NamingException if the environment parameters are not set
* correctly.
*/
protected ServerContext( DirectoryService service, Hashtable<String, Object> env ) throws Exception
{
this.service = service;
this.env = env;
LdapJndiProperties props = LdapJndiProperties.getLdapJndiProperties( this.env );
dn = props.getProviderDn();
/*
* Need do bind operation here, and bindContext returned contains the
* newly created session.
*/
BindOperationContext bindContext = doBindOperation( props.getBindDn(), props.getCredentials(),
props.getSaslMechanism(), props.getSaslAuthId() );
session = bindContext.getSession();
OperationManager operationManager = service.getOperationManager();
if ( ! operationManager.hasEntry( new EntryOperationContext( session, dn ) ) )
{
throw new NameNotFoundException( I18n.err( I18n.ERR_490, dn ) );
}
schemaManager = service.getSchemaManager();
// setup attribute type value
OBJECT_CLASS_AT = schemaManager.getAttributeType( SchemaConstants.OBJECT_CLASS_AT );
}
/**
* Must be called by all subclasses to initialize the nexus proxy and the
* environment settings to be used by this Context implementation. This
* constructor is used to propagate new contexts from existing contexts.
*
* @param service the directory service core
* @param principal the directory user principal that is propagated
* @param name the distinguished name of this context
* @throws NamingException if there is a problem creating the new context
*/
public ServerContext( DirectoryService service, LdapPrincipal principal, Name name ) throws Exception
{
this.service = service;
this.dn = JndiUtils.fromName( name );
this.env = new Hashtable<String, Object>();
this.env.put( PROVIDER_URL, dn.toString() );
this.env.put( DirectoryService.JNDI_KEY, service );
session = new DefaultCoreSession( principal, service );
OperationManager operationManager = service.getOperationManager();
if ( ! operationManager.hasEntry( new EntryOperationContext( session, dn ) ) )
{
throw new NameNotFoundException( I18n.err( I18n.ERR_490, dn ) );
}
schemaManager = service.getSchemaManager();
// setup attribute type value
OBJECT_CLASS_AT = schemaManager.getAttributeType( SchemaConstants.OBJECT_CLASS_AT );
}
public ServerContext( DirectoryService service, CoreSession session, Name name ) throws Exception
{
this.service = service;
this.dn = JndiUtils.fromName( name );
this.env = new Hashtable<String, Object>();
this.env.put( PROVIDER_URL, dn.toString() );
this.env.put( DirectoryService.JNDI_KEY, service );
this.session = session;
OperationManager operationManager = service.getOperationManager();
if ( ! operationManager.hasEntry( new EntryOperationContext( session, dn ) ) )
{
throw new NameNotFoundException( I18n.err( I18n.ERR_490, dn ) );
}
schemaManager = service.getSchemaManager();
// setup attribute type value
OBJECT_CLASS_AT = schemaManager.getAttributeType( SchemaConstants.OBJECT_CLASS_AT );
}
/**
* Set the referral handling flag into the operation context using
* the JNDI value stored into the environment.
*/
protected void injectReferralControl( OperationContext opCtx )
{
if ( "ignore".equalsIgnoreCase( (String)env.get( Context.REFERRAL ) ) )
{
opCtx.ignoreReferral();
}
else if ( "throw".equalsIgnoreCase( (String)env.get( Context.REFERRAL ) ) )
{
opCtx.throwReferral();
}
else
{
// TODO : handle the 'follow' referral option
opCtx.throwReferral();
}
}
// ------------------------------------------------------------------------
// Protected Methods for Operations
// ------------------------------------------------------------------------
// Use these methods instead of manually calling the nexusProxy so we can
// add request controls to operation contexts before the call and extract
// response controls from the contexts after the call. NOTE that the
// convertControls( requestControls ) must be cleared after each operation. This makes a
// context not thread safe.
// ------------------------------------------------------------------------
/**
* Used to encapsulate [de]marshalling of controls before and after add operations.
* @param entry
* @param target
*/
protected void doAddOperation( Dn target, Entry entry ) throws Exception
{
// setup the op context and populate with request controls
AddOperationContext opCtx = new AddOperationContext( session, entry );
opCtx.addRequestControls( convertControls( true, requestControls ) );
// Inject the referral handling into the operation context
injectReferralControl( opCtx );
// execute add operation
OperationManager operationManager = service.getOperationManager();
operationManager.add( opCtx );
// clear the request controls and set the response controls
requestControls = EMPTY_CONTROLS;
responseControls = JndiUtils.toJndiControls( opCtx.getResponseControls() );
}
/**
* Used to encapsulate [de]marshalling of controls before and after delete operations.
* @param target
*/
protected void doDeleteOperation( Dn target ) throws Exception
{
// setup the op context and populate with request controls
DeleteOperationContext opCtx = new DeleteOperationContext( session, target );
opCtx.addRequestControls( convertControls( true, requestControls ) );
// Inject the referral handling into the operation context
injectReferralControl( opCtx );
// execute delete operation
OperationManager operationManager = service.getOperationManager();
operationManager.delete( opCtx );
// clear the request controls and set the response controls
requestControls = EMPTY_CONTROLS;
responseControls = JndiUtils.toJndiControls( opCtx.getResponseControls() );
}
private org.apache.directory.shared.ldap.model.message.Control convertControl( boolean isRequest,
Control jndiControl ) throws DecoderException
{
String controlIDStr = jndiControl.getID();
org.apache.directory.shared.ldap.model.message.Control control = null;
ControlEnum controlId = ADS_CONTROLS.get( controlIDStr );
switch ( controlId )
{
case CASCADE_CONTROL:
control = new CascadeDecorator();
break;
case ENTRY_CHANGE_CONTROL:
control = new EntryChangeDecorator();
Asn1Decoder entryChangeControlDecoder = new EntryChangeDecoder();
EntryChangeContainer entryChangeContainer = new EntryChangeContainer();
- entryChangeContainer.setEntryChangeControl( ( EntryChangeDecorator ) control );
+ entryChangeContainer.setEntryChangeDecorator( ( EntryChangeDecorator ) control );
ByteBuffer bb = ByteBuffer.allocate( jndiControl.getEncodedValue().length );
bb.put( jndiControl.getEncodedValue() ).flip();
entryChangeControlDecoder.decode( bb, entryChangeContainer );
break;
case MANAGE_DSA_IT_CONTROL:
control = new ManageDsaITDecorator();
break;
case PAGED_RESULTS_CONTROL:
control = new PagedResultsDecorator();
entryChangeControlDecoder = new PagedResultsDecoder();
PagedResultsContainer pagedSearchContainer = new PagedResultsContainer();
pagedSearchContainer.setPagedSearchControl( ( PagedResultsDecorator ) control );
bb = ByteBuffer.allocate( jndiControl.getEncodedValue().length );
bb.put( jndiControl.getEncodedValue() ).flip();
entryChangeControlDecoder.decode( bb, pagedSearchContainer );
break;
case PASSWORD_POLICY_REQUEST_CONTROL:
if ( isRequest )
{
control = new PasswordPolicyRequestControl();
}
else
{
control = new PasswordPolicyResponseControl();
PasswordPolicyResponseControlDecoder passwordPolicyResponseControlDecoder = new PasswordPolicyResponseControlDecoder();
PasswordPolicyResponseControlContainer passwordPolicyResponseControlContainer = new PasswordPolicyResponseControlContainer();
passwordPolicyResponseControlContainer
.setPasswordPolicyResponseControl( ( PasswordPolicyResponseControl ) control );
bb = ByteBuffer.allocate( jndiControl.getEncodedValue().length );
bb.put( jndiControl.getEncodedValue() ).flip();
passwordPolicyResponseControlDecoder.decode( bb, passwordPolicyResponseControlContainer );
}
break;
case PERSISTENT_SEARCH_CONTROL:
control = new PersistentSearchDecorator();
PersistentSearchDecoder persistentSearchDecoder = new PersistentSearchDecoder();
PersistentSearchContainer persistentSearchContainer = new PersistentSearchContainer();
- persistentSearchContainer.setPSearchControl( ( PersistentSearchDecorator ) control );
+ persistentSearchContainer.setPSearchDecorator( ( PersistentSearchDecorator ) control );
bb = ByteBuffer.allocate( jndiControl.getEncodedValue().length );
bb.put( jndiControl.getEncodedValue() ).flip();
persistentSearchDecoder.decode( bb, persistentSearchContainer );
break;
case SUBENTRIES_CONTROL:
control = new SubentriesDecorator();
SubentriesDecoder decoder = new SubentriesDecoder();
SubentriesContainer subentriesContainer = new SubentriesContainer();
subentriesContainer.setSubEntryControl( ( SubentriesDecorator ) control );
bb = ByteBuffer.allocate( jndiControl.getEncodedValue().length );
bb.put( jndiControl.getEncodedValue() ).flip();
decoder.decode( bb, subentriesContainer );
break;
case SYNC_DONE_VALUE_CONTROL:
control = new SyncDoneValueControl();
SyncDoneValueControlDecoder syncDoneValueControlDecoder = new SyncDoneValueControlDecoder();
SyncDoneValueControlContainer syncDoneValueControlContainer = new SyncDoneValueControlContainer();
syncDoneValueControlContainer.setSyncDoneValueControl( ( SyncDoneValueControl ) control );
bb = ByteBuffer.allocate( jndiControl.getEncodedValue().length );
bb.put( jndiControl.getEncodedValue() ).flip();
syncDoneValueControlDecoder.decode( bb, syncDoneValueControlContainer );
break;
case SYNC_INFO_VALUE_CONTROL:
control = new SyncInfoValueControl();
SyncInfoValueControlDecoder syncInfoValueControlDecoder = new SyncInfoValueControlDecoder();
SyncInfoValueControlContainer syncInfoValueControlContainer = new SyncInfoValueControlContainer();
syncInfoValueControlContainer.setSyncInfoValueControl( ( SyncInfoValueControl ) control );
bb = ByteBuffer.allocate( jndiControl.getEncodedValue().length );
bb.put( jndiControl.getEncodedValue() ).flip();
syncInfoValueControlDecoder.decode( bb, syncInfoValueControlContainer );
break;
case SYNC_MODIFY_DN_CONTROL:
control = new SyncModifyDnControl();
SyncModifyDnControlDecoder syncModifyDnControlDecoder = new SyncModifyDnControlDecoder();
SyncModifyDnControlContainer syncModifyDnControlContainer = new SyncModifyDnControlContainer();
syncModifyDnControlContainer.setSyncModifyDnControl( ( SyncModifyDnControl ) control );
bb = ByteBuffer.allocate( jndiControl.getEncodedValue().length );
bb.put( jndiControl.getEncodedValue() ).flip();
syncModifyDnControlDecoder.decode( bb, syncModifyDnControlContainer );
break;
case SYNC_REQUEST_VALUE_CONTROL:
control = new SyncRequestValueControl();
SyncRequestValueControlDecoder syncRequestValueControlDecoder = new SyncRequestValueControlDecoder();
SyncRequestValueControlContainer syncRequestValueControlContainer = new SyncRequestValueControlContainer();
syncRequestValueControlContainer.setSyncRequestValueControl( ( SyncRequestValueControl ) control );
bb = ByteBuffer.allocate( jndiControl.getEncodedValue().length );
bb.put( jndiControl.getEncodedValue() ).flip();
syncRequestValueControlDecoder.decode( bb, syncRequestValueControlContainer );
break;
case SYNC_STATE_VALUE_CONTROL:
control = new SyncStateValueControl();
SyncStateValueControlDecoder syncStateValueControlDecoder = new SyncStateValueControlDecoder();
SyncStateValueControlContainer syncStateValueControlContainer = new SyncStateValueControlContainer();
syncStateValueControlContainer.setSyncStateValueControl( ( SyncStateValueControl ) control );
bb = ByteBuffer.allocate( jndiControl.getEncodedValue().length );
bb.put( jndiControl.getEncodedValue() ).flip();
syncStateValueControlDecoder.decode( bb, syncStateValueControlContainer );
break;
}
control.setCritical( jndiControl.isCritical() );
control.setValue( jndiControl.getEncodedValue() );
return control;
}
/**
* Convert the JNDI controls to ADS controls
* TODO convertControls.
*/
private org.apache.directory.shared.ldap.model.message.Control[] convertControls( boolean isRequest,
Control[] jndiControls ) throws DecoderException
{
if ( jndiControls != null )
{
org.apache.directory.shared.ldap.model.message.Control[] controls =
new org.apache.directory.shared.ldap.model.message.Control[jndiControls.length];
int i = 0;
for ( javax.naming.ldap.Control jndiControl : jndiControls )
{
controls[i++] = convertControl( isRequest, jndiControl );
}
return controls;
}
else
{
return null;
}
}
/**
* Used to encapsulate [de]marshalling of controls before and after list operations.
* @param dn
* @param aliasDerefMode
* @param filter
* @param searchControls
* @return NamingEnumeration
*/
protected EntryFilteringCursor doSearchOperation( Dn dn, AliasDerefMode aliasDerefMode,
ExprNode filter, SearchControls searchControls ) throws Exception
{
OperationManager operationManager = service.getOperationManager();
EntryFilteringCursor results = null;
Object typesOnlyObj = getEnvironment().get( "java.naming.ldap.typesOnly" );
boolean typesOnly = false;
if( typesOnlyObj != null )
{
typesOnly = Boolean.parseBoolean( typesOnlyObj.toString() );
}
SearchOperationContext searchContext = null;
// We have to check if it's a compare operation or a search.
// A compare operation has a OBJECT scope search, the filter must
// be of the form (object=value) (no wildcards), and no attributes
// should be asked to be returned.
if ( ( searchControls.getSearchScope() == SearchControls.OBJECT_SCOPE )
&& ( ( searchControls.getReturningAttributes() != null )
&& ( searchControls.getReturningAttributes().length == 0 ) )
&& ( filter instanceof EqualityNode ) )
{
CompareOperationContext compareContext = new CompareOperationContext( session, dn, ((EqualityNode)filter).getAttribute(), ((EqualityNode)filter).getValue() );
// Inject the referral handling into the operation context
injectReferralControl( compareContext );
// Call the operation
boolean result = operationManager.compare( compareContext );
// setup the op context and populate with request controls
searchContext = new SearchOperationContext( session, dn, filter,
searchControls );
searchContext.setAliasDerefMode( aliasDerefMode );
searchContext.addRequestControls( convertControls( true, requestControls ) );
searchContext.setTypesOnly( typesOnly );
if ( result )
{
Entry emptyEntry = new DefaultEntry( service.getSchemaManager(), Dn.EMPTY_DN );
return new BaseEntryFilteringCursor( new SingletonCursor<Entry>( emptyEntry ), searchContext );
}
else
{
return new BaseEntryFilteringCursor( new EmptyCursor<Entry>(), searchContext );
}
}
else
{
// It's a Search
// setup the op context and populate with request controls
searchContext = new SearchOperationContext( session, dn, filter, searchControls );
searchContext.setAliasDerefMode( aliasDerefMode );
searchContext.addRequestControls( convertControls( true, requestControls ) );
searchContext.setTypesOnly( typesOnly );
// Inject the referral handling into the operation context
injectReferralControl( searchContext );
// execute search operation
results = operationManager.search( searchContext );
}
// clear the request controls and set the response controls
requestControls = EMPTY_CONTROLS;
responseControls = JndiUtils.toJndiControls( searchContext.getResponseControls() );
return results;
}
/**
* Used to encapsulate [de]marshalling of controls before and after list operations.
*/
protected EntryFilteringCursor doListOperation( Dn target ) throws Exception
{
// setup the op context and populate with request controls
ListOperationContext listContext = new ListOperationContext( session, target );
listContext.addRequestControls( convertControls( true, requestControls ) );
// execute list operation
OperationManager operationManager = service.getOperationManager();
EntryFilteringCursor results = operationManager.list( listContext );
// clear the request controls and set the response controls
requestControls = EMPTY_CONTROLS;
responseControls = JndiUtils.toJndiControls( listContext.getResponseControls() );
return results;
}
protected Entry doGetRootDSEOperation( Dn target ) throws Exception
{
GetRootDSEOperationContext getRootDseContext = new GetRootDSEOperationContext( session, target );
getRootDseContext.addRequestControls( convertControls( true, requestControls ) );
// do not reset request controls since this is not an external
// operation and not do bother setting the response controls either
OperationManager operationManager = service.getOperationManager();
return operationManager.getRootDSE( getRootDseContext );
}
/**
* Used to encapsulate [de]marshalling of controls before and after lookup operations.
*/
protected Entry doLookupOperation( Dn target ) throws Exception
{
// setup the op context and populate with request controls
// execute lookup/getRootDSE operation
LookupOperationContext lookupContext = new LookupOperationContext( session, target );
lookupContext.addRequestControls( convertControls( true, requestControls ) );
OperationManager operationManager = service.getOperationManager();
Entry serverEntry = operationManager.lookup( lookupContext );
// clear the request controls and set the response controls
requestControls = EMPTY_CONTROLS;
responseControls = JndiUtils.toJndiControls( lookupContext.getResponseControls() );
return serverEntry;
}
/**
* Used to encapsulate [de]marshalling of controls before and after lookup operations.
*/
protected Entry doLookupOperation( Dn target, String[] attrIds ) throws Exception
{
// setup the op context and populate with request controls
// execute lookup/getRootDSE operation
LookupOperationContext lookupContext = new LookupOperationContext( session, target, attrIds );
lookupContext.addRequestControls( convertControls( true, requestControls ) );
OperationManager operationManager = service.getOperationManager();
Entry serverEntry = operationManager.lookup( lookupContext );
// clear the request controls and set the response controls
requestControls = EMPTY_CONTROLS;
responseControls = JndiUtils.toJndiControls( lookupContext.getResponseControls() );
// Now remove the ObjectClass attribute if it has not been requested
if ( ( lookupContext.getAttrsId() != null ) && ( lookupContext.getAttrsId().size() != 0 ) &&
( ( serverEntry.get( SchemaConstants.OBJECT_CLASS_AT ) != null )
&& ( serverEntry.get( SchemaConstants.OBJECT_CLASS_AT ).size() == 0 ) ) )
{
serverEntry.removeAttributes( SchemaConstants.OBJECT_CLASS_AT );
}
return serverEntry;
}
/**
* Used to encapsulate [de]marshalling of controls before and after bind operations.
*/
protected BindOperationContext doBindOperation( Dn bindDn, byte[] credentials, String saslMechanism,
String saslAuthId ) throws Exception
{
// setup the op context and populate with request controls
BindOperationContext bindContext = new BindOperationContext( null );
bindContext.setDn( bindDn );
bindContext.setCredentials( credentials );
bindContext.setSaslMechanism( saslMechanism );
bindContext.setSaslAuthId( saslAuthId );
bindContext.addRequestControls( convertControls( true, requestControls ) );
// execute bind operation
OperationManager operationManager = service.getOperationManager();
operationManager.bind( bindContext );
// clear the request controls and set the response controls
requestControls = EMPTY_CONTROLS;
responseControls = JndiUtils.toJndiControls( bindContext.getResponseControls() );
return bindContext;
}
/**
* Used to encapsulate [de]marshalling of controls before and after moveAndRename operations.
*/
protected void doMoveAndRenameOperation( Dn oldDn, Dn parent, Rdn newRdn, boolean delOldDn )
throws Exception
{
// setup the op context and populate with request controls
MoveAndRenameOperationContext moveAndRenameContext = new MoveAndRenameOperationContext( session, oldDn, parent, new Rdn(
newRdn ), delOldDn );
moveAndRenameContext.addRequestControls( convertControls( true, requestControls ) );
// Inject the referral handling into the operation context
injectReferralControl( moveAndRenameContext );
// execute moveAndRename operation
OperationManager operationManager = service.getOperationManager();
operationManager.moveAndRename( moveAndRenameContext );
// clear the request controls and set the response controls
requestControls = EMPTY_CONTROLS;
responseControls = JndiUtils.toJndiControls( moveAndRenameContext.getResponseControls() );
}
/**
* Used to encapsulate [de]marshalling of controls before and after modify operations.
*/
protected void doModifyOperation( Dn dn, List<Modification> modifications ) throws Exception
{
// setup the op context and populate with request controls
ModifyOperationContext modifyContext = new ModifyOperationContext( session, dn, modifications );
modifyContext.addRequestControls( convertControls( true, requestControls ) );
// Inject the referral handling into the operation context
injectReferralControl( modifyContext );
// execute modify operation
OperationManager operationManager = service.getOperationManager();
operationManager.modify( modifyContext );
// clear the request controls and set the response controls
requestControls = EMPTY_CONTROLS;
responseControls = JndiUtils.toJndiControls( modifyContext.getResponseControls() );
}
/**
* Used to encapsulate [de]marshalling of controls before and after moveAndRename operations.
*/
protected void doMove( Dn oldDn, Dn target ) throws Exception
{
// setup the op context and populate with request controls
MoveOperationContext moveContext = new MoveOperationContext( session, oldDn, target );
moveContext.addRequestControls( convertControls( true, requestControls ) );
// Inject the referral handling into the operation context
injectReferralControl( moveContext );
// execute move operation
OperationManager operationManager = service.getOperationManager();
operationManager.move( moveContext );
// clear the request controls and set the response controls
requestControls = EMPTY_CONTROLS;
responseControls = JndiUtils.toJndiControls( moveContext.getResponseControls() );
}
/**
* Used to encapsulate [de]marshalling of controls before and after rename operations.
*/
protected void doRename( Dn oldDn, Rdn newRdn, boolean delOldRdn ) throws Exception
{
// setup the op context and populate with request controls
RenameOperationContext renameContext = new RenameOperationContext( session, oldDn, newRdn, delOldRdn );
renameContext.addRequestControls( convertControls( true, requestControls ) );
// Inject the referral handling into the operation context
injectReferralControl( renameContext );
// execute rename operation
OperationManager operationManager = service.getOperationManager();
operationManager.rename( renameContext );
// clear the request controls and set the response controls
requestControls = EMPTY_CONTROLS;
responseControls = JndiUtils.toJndiControls( renameContext.getResponseControls() );
}
public CoreSession getSession()
{
return session;
}
public DirectoryService getDirectoryService()
{
return service;
}
// ------------------------------------------------------------------------
// New Impl Specific Public Methods
// ------------------------------------------------------------------------
/**
* Gets a handle on the root context of the DIT. The RootDSE as the present user.
*
* @return the rootDSE context
* @throws NamingException if this fails
*/
public abstract ServerContext getRootContext() throws NamingException;
/**
* Gets the {@link DirectoryService} associated with this context.
*
* @return the directory service associated with this context
*/
public DirectoryService getService()
{
return service;
}
// ------------------------------------------------------------------------
// Protected Accessor Methods
// ------------------------------------------------------------------------
/**
* Gets the distinguished name of the entry associated with this Context.
*
* @return the distinguished name of this Context's entry.
*/
protected Dn getDn()
{
return dn;
}
// ------------------------------------------------------------------------
// JNDI Context Interface Methods
// ------------------------------------------------------------------------
/**
* @see javax.naming.Context#close()
*/
public void close() throws NamingException
{
for ( DirectoryListener listener : listeners.values() )
{
try
{
service.getEventService().removeListener( listener );
}
catch ( Exception e )
{
JndiUtils.wrap( e );
}
}
listeners.clear();
}
/**
* @see javax.naming.Context#getNameInNamespace()
*/
public String getNameInNamespace() throws NamingException
{
return dn.getName();
}
/**
* @see javax.naming.Context#getEnvironment()
*/
public Hashtable<String, Object> getEnvironment()
{
return env;
}
/**
* @see javax.naming.Context#addToEnvironment(java.lang.String,
* java.lang.Object)
*/
public Object addToEnvironment( String propName, Object propVal ) throws NamingException
{
return env.put( propName, propVal );
}
/**
* @see javax.naming.Context#removeFromEnvironment(java.lang.String)
*/
public Object removeFromEnvironment( String propName ) throws NamingException
{
return env.remove( propName );
}
/**
* @see javax.naming.Context#createSubcontext(java.lang.String)
*/
public Context createSubcontext( String name ) throws NamingException
{
return createSubcontext( new LdapName( name ) );
}
/**
* @see javax.naming.Context#createSubcontext(javax.naming.Name)
*/
public Context createSubcontext( Name name ) throws NamingException
{
Dn target = buildTarget( JndiUtils.fromName( name ) );
Entry serverEntry = null;
try
{
serverEntry = service.newEntry( target );
}
catch ( LdapException le )
{
throw new NamingException( le.getMessage() );
}
try
{
serverEntry.add( SchemaConstants.OBJECT_CLASS_AT, SchemaConstants.TOP_OC, JavaLdapSupport.JCONTAINER_ATTR );
}
catch ( LdapException le )
{
throw new SchemaViolationException( I18n.err( I18n.ERR_491, name) );
}
// Now add the CN attribute, which is mandatory
Rdn rdn = target.getRdn();
if ( rdn != null )
{
if ( SchemaConstants.CN_AT_OID.equals( rdn.getNormType() ) )
{
serverEntry.put( rdn.getUpType(), rdn.getUpValue() );
}
else
{
// No CN in the rdn, this is an error
throw new SchemaViolationException( I18n.err( I18n.ERR_491, name) );
}
}
else
{
// No CN in the rdn, this is an error
throw new SchemaViolationException( I18n.err( I18n.ERR_491, name) );
}
/*
* Add the new context to the server which as a side effect adds
* operational attributes to the serverEntry refering instance which
* can them be used to initialize a new ServerLdapContext. Remember
* we need to copy over the controls as well to propagate the complete
* environment besides what's in the hashtable for env.
*/
try
{
doAddOperation( target, serverEntry );
}
catch ( Exception e )
{
JndiUtils.wrap( e );
}
ServerLdapContext ctx = null;
try
{
ctx = new ServerLdapContext( service, session.getEffectivePrincipal(), JndiUtils.toName( target ) );
}
catch ( Exception e )
{
JndiUtils.wrap( e );
}
return ctx;
}
/**
* @see javax.naming.Context#destroySubcontext(java.lang.String)
*/
public void destroySubcontext( String name ) throws NamingException
{
destroySubcontext( new LdapName( name ) );
}
/**
* @see javax.naming.Context#destroySubcontext(javax.naming.Name)
*/
public void destroySubcontext( Name name ) throws NamingException
{
Dn target = buildTarget( JndiUtils.fromName( name ) );
if ( target.size() == 0 )
{
throw new NoPermissionException( I18n.err( I18n.ERR_492 ) );
}
try
{
doDeleteOperation( target );
}
catch ( Exception e )
{
JndiUtils.wrap( e );
}
}
/**
* @see javax.naming.Context#bind(java.lang.String, java.lang.Object)
*/
public void bind( String name, Object obj ) throws NamingException
{
bind( new LdapName( name ), obj );
}
private void injectRdnAttributeValues( Dn target, Entry serverEntry ) throws NamingException
{
// Add all the Rdn attributes and their values to this entry
Rdn rdn = target.getRdn( target.size() - 1 );
if ( rdn.size() == 1 )
{
serverEntry.put( rdn.getUpType(), rdn.getUpValue() );
}
else
{
for ( Ava atav : rdn )
{
serverEntry.put( atav.getUpType(), atav.getUpValue() );
}
}
}
/**
* @see javax.naming.Context#bind(javax.naming.Name, java.lang.Object)
*/
public void bind( Name name, Object obj ) throws NamingException
{
// First, use state factories to do a transformation
DirStateFactory.Result res = DirectoryManager.getStateToBind( obj, name, this, env, null );
Dn target = buildTarget( JndiUtils.fromName( name ) );
// let's be sure that the Attributes is case insensitive
Entry outServerEntry = null;
try
{
outServerEntry = ServerEntryUtils.toServerEntry( AttributeUtils.toCaseInsensitive(res
.getAttributes()), target, service.getSchemaManager() );
}
catch ( LdapInvalidAttributeTypeException liate )
{
throw new NamingException( I18n.err( I18n.ERR_495, obj ) );
}
if ( outServerEntry != null )
{
try
{
doAddOperation( target, outServerEntry );
}
catch ( Exception e )
{
JndiUtils.wrap( e );
}
return;
}
if ( obj instanceof Entry )
{
try
{
doAddOperation( target, ( Entry ) obj );
}
catch ( Exception e )
{
JndiUtils.wrap( e );
}
}
// Check for Referenceable
else if ( obj instanceof Referenceable )
{
throw new NamingException( I18n.err( I18n.ERR_493 ) );
}
// Store different formats
else if ( obj instanceof Reference )
{
// Store as ref and add outAttrs
throw new NamingException( I18n.err( I18n.ERR_494 ) );
}
else if ( obj instanceof Serializable )
{
// Serialize and add outAttrs
Entry serverEntry = null;
try
{
serverEntry = service.newEntry( target );
}
catch ( LdapException le )
{
throw new NamingException( I18n.err( I18n.ERR_495, obj ) );
}
if ( ( outServerEntry != null ) && ( outServerEntry.size() > 0 ) )
{
for ( EntryAttribute serverAttribute : outServerEntry )
{
try
{
serverEntry.put( serverAttribute );
}
catch ( LdapException le )
{
throw new NamingException( I18n.err( I18n.ERR_495, obj ) );
}
}
}
// Get target and inject all rdn attributes into entry
injectRdnAttributeValues( target, serverEntry );
// Serialize object into entry attributes and add it.
try
{
JavaLdapSupport.serialize( serverEntry, obj, service.getSchemaManager() );
}
catch ( LdapException le )
{
throw new NamingException( I18n.err( I18n.ERR_495, obj ) );
}
try
{
doAddOperation( target, serverEntry );
}
catch ( Exception e )
{
JndiUtils.wrap( e );
}
}
else if ( obj instanceof DirContext )
{
// Grab attributes and merge with outAttrs
Entry serverEntry = null;
try
{
serverEntry = ServerEntryUtils.toServerEntry( ( ( DirContext ) obj ).getAttributes( "" ),
target, service.getSchemaManager() );
}
catch ( LdapInvalidAttributeTypeException liate )
{
throw new NamingException( I18n.err( I18n.ERR_495, obj ) );
}
if ( ( outServerEntry != null ) && ( outServerEntry.size() > 0 ) )
{
for ( EntryAttribute serverAttribute : outServerEntry )
{
try
{
serverEntry.put( serverAttribute );
}
catch ( LdapException le )
{
throw new NamingException( I18n.err( I18n.ERR_495, obj ) );
}
}
}
injectRdnAttributeValues( target, serverEntry );
try
{
doAddOperation( target, serverEntry );
}
catch ( Exception e )
{
JndiUtils.wrap( e );
}
}
else
{
throw new NamingException( I18n.err( I18n.ERR_495, obj ) );
}
}
/**
* @see javax.naming.Context#rename(java.lang.String, java.lang.String)
*/
public void rename( String oldName, String newName ) throws NamingException
{
rename( new LdapName( oldName ), new LdapName( newName ) );
}
/**
* @see javax.naming.Context#rename(javax.naming.Name, javax.naming.Name)
*/
public void rename( Name oldName, Name newName ) throws NamingException
{
Dn oldDn = buildTarget( JndiUtils.fromName( oldName ) );
Dn newDn = buildTarget( JndiUtils.fromName( newName ) );
if ( oldDn.size() == 0 )
{
throw new NoPermissionException( I18n.err( I18n.ERR_312 ) );
}
// calculate parents
Dn oldParent = oldDn;
try
{
oldParent = oldParent.remove( oldDn.size() - 1 );
}
catch ( LdapInvalidDnException lide )
{
throw new NamingException( I18n.err( I18n.ERR_313, lide.getMessage() ) );
}
Dn newParent = newDn;
try
{
newParent = newParent.remove( newDn.size() - 1 );
}
catch ( LdapInvalidDnException lide )
{
throw new NamingException( I18n.err( I18n.ERR_313, lide.getMessage() ) );
}
Rdn oldRdn = oldDn.getRdn();
Rdn newRdn = newDn.getRdn();
boolean delOldRdn = true;
/*
* Attempt to use the java.naming.ldap.deleteRDN environment property
* to get an override for the deleteOldRdn option to modifyRdn.
*/
if ( null != env.get( DELETE_OLD_RDN_PROP ) )
{
String delOldRdnStr = ( String ) env.get( DELETE_OLD_RDN_PROP );
delOldRdn = !delOldRdnStr.equalsIgnoreCase( "false" ) && !delOldRdnStr.equalsIgnoreCase( "no" )
&& !delOldRdnStr.equals( "0" );
}
/*
* We need to determine if this rename operation corresponds to a simple
* Rdn name change or a move operation. If the two names are the same
* except for the Rdn then it is a simple modifyRdn operation. If the
* names differ in size or have a different baseDN then the operation is
* a move operation. Furthermore if the Rdn in the move operation
* changes it is both an Rdn change and a move operation.
*/
if ( oldParent.equals( newParent ) )
{
try
{
doRename( oldDn, newRdn, delOldRdn );
}
catch ( Exception e )
{
JndiUtils.wrap( e );
}
}
else
{
if ( newRdn.equals( oldRdn ) )
{
try
{
doMove( oldDn, newParent );
}
catch ( Exception e )
{
JndiUtils.wrap( e );
}
}
else
{
try
{
doMoveAndRenameOperation( oldDn, newParent, newRdn, delOldRdn );
}
catch ( Exception e )
{
JndiUtils.wrap( e );
}
}
}
}
/**
* @see javax.naming.Context#rebind(java.lang.String, java.lang.Object)
*/
public void rebind( String name, Object obj ) throws NamingException
{
rebind( new LdapName( name ), obj );
}
/**
* @see javax.naming.Context#rebind(javax.naming.Name, java.lang.Object)
*/
public void rebind( Name name, Object obj ) throws NamingException
{
Dn target = buildTarget( JndiUtils.fromName( name ) );
OperationManager operationManager = service.getOperationManager();
try
{
if ( operationManager.hasEntry( new EntryOperationContext( session, target ) ) )
{
doDeleteOperation( target );
}
}
catch ( Exception e )
{
JndiUtils.wrap( e );
}
bind( name, obj );
}
/**
* @see javax.naming.Context#unbind(java.lang.String)
*/
public void unbind( String name ) throws NamingException
{
unbind( new LdapName( name ) );
}
/**
* @see javax.naming.Context#unbind(javax.naming.Name)
*/
public void unbind( Name name ) throws NamingException
{
try
{
doDeleteOperation( buildTarget( JndiUtils.fromName( name ) ) );
}
catch ( Exception e )
{
JndiUtils.wrap( e );
}
}
/**
* @see javax.naming.Context#lookup(java.lang.String)
*/
public Object lookup( String name ) throws NamingException
{
if ( Strings.isEmpty(name) )
{
return lookup( new LdapName( "" ) );
}
else
{
return lookup( new LdapName( name ) );
}
}
/**
* @see javax.naming.Context#lookup(javax.naming.Name)
*/
public Object lookup( Name name ) throws NamingException
{
Object obj;
Dn target = buildTarget( JndiUtils.fromName( name ) );
Entry serverEntry = null;
try
{
if ( name.size() == 0 )
{
serverEntry = doGetRootDSEOperation( target );
}
else
{
serverEntry = doLookupOperation( target );
}
}
catch ( Exception e )
{
JndiUtils.wrap( e );
}
try
{
obj = DirectoryManager.getObjectInstance( null, name, this, env,
ServerEntryUtils.toBasicAttributes( serverEntry ) );
}
catch ( Exception e )
{
String msg = I18n.err( I18n.ERR_497, target );
NamingException ne = new NamingException( msg );
ne.setRootCause( e );
throw ne;
}
if ( obj != null )
{
return obj;
}
// First lets test and see if the entry is a serialized java object
if ( serverEntry.get( JavaLdapSupport.JCLASSNAME_ATTR ) != null )
{
// Give back serialized object and not a context
return JavaLdapSupport.deserialize( serverEntry );
}
// Initialize and return a context since the entry is not a java object
ServerLdapContext ctx = null;
try
{
ctx = new ServerLdapContext( service, session.getEffectivePrincipal(), JndiUtils.toName( target ) );
}
catch ( Exception e )
{
JndiUtils.wrap( e );
}
return ctx;
}
/**
* @see javax.naming.Context#lookupLink(java.lang.String)
*/
public Object lookupLink( String name ) throws NamingException
{
throw new UnsupportedOperationException();
}
/**
* @see javax.naming.Context#lookupLink(javax.naming.Name)
*/
public Object lookupLink( Name name ) throws NamingException
{
throw new UnsupportedOperationException();
}
/**
* Non-federated implementation presuming the name argument is not a
* composite name spanning multiple namespaces but a compound name in
* the same LDAP namespace. Hence the parser returned is always the
* same as calling this method with the empty String.
*
* @see javax.naming.Context#getNameParser(java.lang.String)
*/
public NameParser getNameParser( String name ) throws NamingException
{
return new NameParser()
{
public Name parse( String name ) throws NamingException
{
try
{
return JndiUtils.toName( new Dn( name ) );
}
catch ( LdapInvalidDnException lide )
{
throw new InvalidNameException( lide.getMessage() );
}
}
};
}
/**
* Non-federated implementation presuming the name argument is not a
* composite name spanning multiple namespaces but a compound name in
* the same LDAP namespace. Hence the parser returned is always the
* same as calling this method with the empty String Name.
*
* @see javax.naming.Context#getNameParser(javax.naming.Name)
*/
public NameParser getNameParser( final Name name ) throws NamingException
{
return new NameParser()
{
public Name parse( String n ) throws NamingException
{
try
{
return JndiUtils.toName( new Dn( name.toString() ) );
}
catch ( LdapInvalidDnException lide )
{
throw new InvalidNameException( lide.getMessage() );
}
}
};
}
/**
* @see javax.naming.Context#list(java.lang.String)
*/
@SuppressWarnings(value =
{ "unchecked" })
public NamingEnumeration list( String name ) throws NamingException
{
return list( new LdapName( name ) );
}
/**
* @see javax.naming.Context#list(javax.naming.Name)
*/
@SuppressWarnings(value =
{ "unchecked" })
public NamingEnumeration list( Name name ) throws NamingException
{
try
{
return new NamingEnumerationAdapter( doListOperation( buildTarget( JndiUtils.fromName(name) ) ) );
}
catch ( Exception e )
{
JndiUtils.wrap( e );
return null; // shut up compiler
}
}
/**
* @see javax.naming.Context#listBindings(java.lang.String)
*/
@SuppressWarnings(value =
{ "unchecked" })
public NamingEnumeration listBindings( String name ) throws NamingException
{
return listBindings( new LdapName( name ) );
}
/**
* @see javax.naming.Context#listBindings(javax.naming.Name)
*/
@SuppressWarnings(value =
{ "unchecked" })
public NamingEnumeration listBindings( Name name ) throws NamingException
{
// Conduct a special one level search at base for all objects
Dn base = buildTarget( JndiUtils.fromName( name ) );
PresenceNode filter = new PresenceNode( OBJECT_CLASS_AT );
SearchControls ctls = new SearchControls();
ctls.setSearchScope( SearchControls.ONELEVEL_SCOPE );
AliasDerefMode aliasDerefMode = AliasDerefMode.getEnum( getEnvironment() );
try
{
return new NamingEnumerationAdapter( doSearchOperation( base, aliasDerefMode, filter, ctls ) );
}
catch ( Exception e )
{
JndiUtils.wrap( e );
return null; // shutup compiler
}
}
/**
* @see javax.naming.Context#composeName(java.lang.String, java.lang.String)
*/
public String composeName( String name, String prefix ) throws NamingException
{
return composeName( new LdapName( name ), new LdapName( prefix ) ).toString();
}
/**
* @see javax.naming.Context#composeName(javax.naming.Name,
* javax.naming.Name)
*/
public Name composeName( Name name, Name prefix ) throws NamingException
{
// No prefix reduces to name, or the name relative to this context
if ( prefix == null || prefix.size() == 0 )
{
return name;
}
/*
* Example: This context is ou=people and say name is the relative
* name of uid=jwalker and the prefix is dc=domain. Then we must
* compose the name relative to prefix which would be:
*
* uid=jwalker,ou=people,dc=domain.
*
* The following general algorithm generates the right name:
* 1). Find the Dn for name and walk it from the head to tail
* trying to match for the head of prefix.
* 2). Remove name components from the Dn until a match for the
* head of the prefix is found.
* 3). Return the remainder of the fqn or Dn after chewing off some
*/
// 1). Find the Dn for name and walk it from the head to tail
Dn fqn = buildTarget( JndiUtils.fromName( name ) );
String head = prefix.get( 0 );
// 2). Walk the fqn trying to match for the head of the prefix
while ( fqn.size() > 0 )
{
// match found end loop
if ( fqn.get( 0 ).equalsIgnoreCase( head ) )
{
return JndiUtils.toName( fqn );
}
else
// 2). Remove name components from the Dn until a match
{
try
{
fqn = fqn.remove( 0 );
}
catch ( LdapInvalidDnException lide )
{
throw new NamingException( lide.getMessage() );
}
}
}
String msg = I18n.err( I18n.ERR_498, prefix, dn );
throw new NamingException( msg );
}
// ------------------------------------------------------------------------
// EventContext implementations
// ------------------------------------------------------------------------
public void addNamingListener( Name name, int scope, NamingListener namingListener ) throws NamingException
{
ExprNode filter = new PresenceNode( OBJECT_CLASS_AT );
try
{
DirectoryListener listener = new EventListenerAdapter( ( ServerLdapContext ) this, namingListener );
NotificationCriteria criteria = new NotificationCriteria();
criteria.setFilter( filter );
criteria.setScope( SearchScope.getSearchScope( scope ) );
criteria.setAliasDerefMode( AliasDerefMode.getEnum( env ) );
criteria.setBase( buildTarget( JndiUtils.fromName( name ) ) );
service.getEventService().addListener( listener );
listeners.put( namingListener, listener );
}
catch ( Exception e )
{
JndiUtils.wrap( e );
}
}
public void addNamingListener( String name, int scope, NamingListener namingListener ) throws NamingException
{
addNamingListener( new LdapName( name ), scope, namingListener );
}
public void removeNamingListener( NamingListener namingListener ) throws NamingException
{
try
{
DirectoryListener listener = listeners.remove( namingListener );
if ( listener != null )
{
service.getEventService().removeListener( listener );
}
}
catch ( Exception e )
{
JndiUtils.wrap( e );
}
}
public boolean targetMustExist() throws NamingException
{
return false;
}
/**
* Allows subclasses to register and unregister listeners.
*
* @return the set of listeners used for tracking registered name listeners.
*/
protected Map<NamingListener, DirectoryListener> getListeners()
{
return listeners;
}
// ------------------------------------------------------------------------
// Utility Methods to Reduce Code
// ------------------------------------------------------------------------
/**
* Clones this context's Dn and adds the components of the name relative to
* this context to the left hand side of this context's cloned Dn.
*
* @param relativeName a name relative to this context.
* @return the name of the target
* @throws InvalidNameException if relativeName is not a valid name in
* the LDAP namespace.
*/
Dn buildTarget( Dn relativeName ) throws NamingException
{
Dn target = dn;
// Add to left hand side of cloned Dn the relative name arg
try
{
relativeName.normalize( schemaManager );
target = target.addAllNormalized( target.size(), relativeName );
}
catch (LdapInvalidDnException lide )
{
throw new InvalidNameException( lide.getMessage() );
}
return target;
}
}
| false | true | private org.apache.directory.shared.ldap.model.message.Control convertControl( boolean isRequest,
Control jndiControl ) throws DecoderException
{
String controlIDStr = jndiControl.getID();
org.apache.directory.shared.ldap.model.message.Control control = null;
ControlEnum controlId = ADS_CONTROLS.get( controlIDStr );
switch ( controlId )
{
case CASCADE_CONTROL:
control = new CascadeDecorator();
break;
case ENTRY_CHANGE_CONTROL:
control = new EntryChangeDecorator();
Asn1Decoder entryChangeControlDecoder = new EntryChangeDecoder();
EntryChangeContainer entryChangeContainer = new EntryChangeContainer();
entryChangeContainer.setEntryChangeControl( ( EntryChangeDecorator ) control );
ByteBuffer bb = ByteBuffer.allocate( jndiControl.getEncodedValue().length );
bb.put( jndiControl.getEncodedValue() ).flip();
entryChangeControlDecoder.decode( bb, entryChangeContainer );
break;
case MANAGE_DSA_IT_CONTROL:
control = new ManageDsaITDecorator();
break;
case PAGED_RESULTS_CONTROL:
control = new PagedResultsDecorator();
entryChangeControlDecoder = new PagedResultsDecoder();
PagedResultsContainer pagedSearchContainer = new PagedResultsContainer();
pagedSearchContainer.setPagedSearchControl( ( PagedResultsDecorator ) control );
bb = ByteBuffer.allocate( jndiControl.getEncodedValue().length );
bb.put( jndiControl.getEncodedValue() ).flip();
entryChangeControlDecoder.decode( bb, pagedSearchContainer );
break;
case PASSWORD_POLICY_REQUEST_CONTROL:
if ( isRequest )
{
control = new PasswordPolicyRequestControl();
}
else
{
control = new PasswordPolicyResponseControl();
PasswordPolicyResponseControlDecoder passwordPolicyResponseControlDecoder = new PasswordPolicyResponseControlDecoder();
PasswordPolicyResponseControlContainer passwordPolicyResponseControlContainer = new PasswordPolicyResponseControlContainer();
passwordPolicyResponseControlContainer
.setPasswordPolicyResponseControl( ( PasswordPolicyResponseControl ) control );
bb = ByteBuffer.allocate( jndiControl.getEncodedValue().length );
bb.put( jndiControl.getEncodedValue() ).flip();
passwordPolicyResponseControlDecoder.decode( bb, passwordPolicyResponseControlContainer );
}
break;
case PERSISTENT_SEARCH_CONTROL:
control = new PersistentSearchDecorator();
PersistentSearchDecoder persistentSearchDecoder = new PersistentSearchDecoder();
PersistentSearchContainer persistentSearchContainer = new PersistentSearchContainer();
persistentSearchContainer.setPSearchControl( ( PersistentSearchDecorator ) control );
bb = ByteBuffer.allocate( jndiControl.getEncodedValue().length );
bb.put( jndiControl.getEncodedValue() ).flip();
persistentSearchDecoder.decode( bb, persistentSearchContainer );
break;
case SUBENTRIES_CONTROL:
control = new SubentriesDecorator();
SubentriesDecoder decoder = new SubentriesDecoder();
SubentriesContainer subentriesContainer = new SubentriesContainer();
subentriesContainer.setSubEntryControl( ( SubentriesDecorator ) control );
bb = ByteBuffer.allocate( jndiControl.getEncodedValue().length );
bb.put( jndiControl.getEncodedValue() ).flip();
decoder.decode( bb, subentriesContainer );
break;
case SYNC_DONE_VALUE_CONTROL:
control = new SyncDoneValueControl();
SyncDoneValueControlDecoder syncDoneValueControlDecoder = new SyncDoneValueControlDecoder();
SyncDoneValueControlContainer syncDoneValueControlContainer = new SyncDoneValueControlContainer();
syncDoneValueControlContainer.setSyncDoneValueControl( ( SyncDoneValueControl ) control );
bb = ByteBuffer.allocate( jndiControl.getEncodedValue().length );
bb.put( jndiControl.getEncodedValue() ).flip();
syncDoneValueControlDecoder.decode( bb, syncDoneValueControlContainer );
break;
case SYNC_INFO_VALUE_CONTROL:
control = new SyncInfoValueControl();
SyncInfoValueControlDecoder syncInfoValueControlDecoder = new SyncInfoValueControlDecoder();
SyncInfoValueControlContainer syncInfoValueControlContainer = new SyncInfoValueControlContainer();
syncInfoValueControlContainer.setSyncInfoValueControl( ( SyncInfoValueControl ) control );
bb = ByteBuffer.allocate( jndiControl.getEncodedValue().length );
bb.put( jndiControl.getEncodedValue() ).flip();
syncInfoValueControlDecoder.decode( bb, syncInfoValueControlContainer );
break;
case SYNC_MODIFY_DN_CONTROL:
control = new SyncModifyDnControl();
SyncModifyDnControlDecoder syncModifyDnControlDecoder = new SyncModifyDnControlDecoder();
SyncModifyDnControlContainer syncModifyDnControlContainer = new SyncModifyDnControlContainer();
syncModifyDnControlContainer.setSyncModifyDnControl( ( SyncModifyDnControl ) control );
bb = ByteBuffer.allocate( jndiControl.getEncodedValue().length );
bb.put( jndiControl.getEncodedValue() ).flip();
syncModifyDnControlDecoder.decode( bb, syncModifyDnControlContainer );
break;
case SYNC_REQUEST_VALUE_CONTROL:
control = new SyncRequestValueControl();
SyncRequestValueControlDecoder syncRequestValueControlDecoder = new SyncRequestValueControlDecoder();
SyncRequestValueControlContainer syncRequestValueControlContainer = new SyncRequestValueControlContainer();
syncRequestValueControlContainer.setSyncRequestValueControl( ( SyncRequestValueControl ) control );
bb = ByteBuffer.allocate( jndiControl.getEncodedValue().length );
bb.put( jndiControl.getEncodedValue() ).flip();
syncRequestValueControlDecoder.decode( bb, syncRequestValueControlContainer );
break;
case SYNC_STATE_VALUE_CONTROL:
control = new SyncStateValueControl();
SyncStateValueControlDecoder syncStateValueControlDecoder = new SyncStateValueControlDecoder();
SyncStateValueControlContainer syncStateValueControlContainer = new SyncStateValueControlContainer();
syncStateValueControlContainer.setSyncStateValueControl( ( SyncStateValueControl ) control );
bb = ByteBuffer.allocate( jndiControl.getEncodedValue().length );
bb.put( jndiControl.getEncodedValue() ).flip();
syncStateValueControlDecoder.decode( bb, syncStateValueControlContainer );
break;
}
control.setCritical( jndiControl.isCritical() );
control.setValue( jndiControl.getEncodedValue() );
return control;
}
| private org.apache.directory.shared.ldap.model.message.Control convertControl( boolean isRequest,
Control jndiControl ) throws DecoderException
{
String controlIDStr = jndiControl.getID();
org.apache.directory.shared.ldap.model.message.Control control = null;
ControlEnum controlId = ADS_CONTROLS.get( controlIDStr );
switch ( controlId )
{
case CASCADE_CONTROL:
control = new CascadeDecorator();
break;
case ENTRY_CHANGE_CONTROL:
control = new EntryChangeDecorator();
Asn1Decoder entryChangeControlDecoder = new EntryChangeDecoder();
EntryChangeContainer entryChangeContainer = new EntryChangeContainer();
entryChangeContainer.setEntryChangeDecorator( ( EntryChangeDecorator ) control );
ByteBuffer bb = ByteBuffer.allocate( jndiControl.getEncodedValue().length );
bb.put( jndiControl.getEncodedValue() ).flip();
entryChangeControlDecoder.decode( bb, entryChangeContainer );
break;
case MANAGE_DSA_IT_CONTROL:
control = new ManageDsaITDecorator();
break;
case PAGED_RESULTS_CONTROL:
control = new PagedResultsDecorator();
entryChangeControlDecoder = new PagedResultsDecoder();
PagedResultsContainer pagedSearchContainer = new PagedResultsContainer();
pagedSearchContainer.setPagedSearchControl( ( PagedResultsDecorator ) control );
bb = ByteBuffer.allocate( jndiControl.getEncodedValue().length );
bb.put( jndiControl.getEncodedValue() ).flip();
entryChangeControlDecoder.decode( bb, pagedSearchContainer );
break;
case PASSWORD_POLICY_REQUEST_CONTROL:
if ( isRequest )
{
control = new PasswordPolicyRequestControl();
}
else
{
control = new PasswordPolicyResponseControl();
PasswordPolicyResponseControlDecoder passwordPolicyResponseControlDecoder = new PasswordPolicyResponseControlDecoder();
PasswordPolicyResponseControlContainer passwordPolicyResponseControlContainer = new PasswordPolicyResponseControlContainer();
passwordPolicyResponseControlContainer
.setPasswordPolicyResponseControl( ( PasswordPolicyResponseControl ) control );
bb = ByteBuffer.allocate( jndiControl.getEncodedValue().length );
bb.put( jndiControl.getEncodedValue() ).flip();
passwordPolicyResponseControlDecoder.decode( bb, passwordPolicyResponseControlContainer );
}
break;
case PERSISTENT_SEARCH_CONTROL:
control = new PersistentSearchDecorator();
PersistentSearchDecoder persistentSearchDecoder = new PersistentSearchDecoder();
PersistentSearchContainer persistentSearchContainer = new PersistentSearchContainer();
persistentSearchContainer.setPSearchDecorator( ( PersistentSearchDecorator ) control );
bb = ByteBuffer.allocate( jndiControl.getEncodedValue().length );
bb.put( jndiControl.getEncodedValue() ).flip();
persistentSearchDecoder.decode( bb, persistentSearchContainer );
break;
case SUBENTRIES_CONTROL:
control = new SubentriesDecorator();
SubentriesDecoder decoder = new SubentriesDecoder();
SubentriesContainer subentriesContainer = new SubentriesContainer();
subentriesContainer.setSubEntryControl( ( SubentriesDecorator ) control );
bb = ByteBuffer.allocate( jndiControl.getEncodedValue().length );
bb.put( jndiControl.getEncodedValue() ).flip();
decoder.decode( bb, subentriesContainer );
break;
case SYNC_DONE_VALUE_CONTROL:
control = new SyncDoneValueControl();
SyncDoneValueControlDecoder syncDoneValueControlDecoder = new SyncDoneValueControlDecoder();
SyncDoneValueControlContainer syncDoneValueControlContainer = new SyncDoneValueControlContainer();
syncDoneValueControlContainer.setSyncDoneValueControl( ( SyncDoneValueControl ) control );
bb = ByteBuffer.allocate( jndiControl.getEncodedValue().length );
bb.put( jndiControl.getEncodedValue() ).flip();
syncDoneValueControlDecoder.decode( bb, syncDoneValueControlContainer );
break;
case SYNC_INFO_VALUE_CONTROL:
control = new SyncInfoValueControl();
SyncInfoValueControlDecoder syncInfoValueControlDecoder = new SyncInfoValueControlDecoder();
SyncInfoValueControlContainer syncInfoValueControlContainer = new SyncInfoValueControlContainer();
syncInfoValueControlContainer.setSyncInfoValueControl( ( SyncInfoValueControl ) control );
bb = ByteBuffer.allocate( jndiControl.getEncodedValue().length );
bb.put( jndiControl.getEncodedValue() ).flip();
syncInfoValueControlDecoder.decode( bb, syncInfoValueControlContainer );
break;
case SYNC_MODIFY_DN_CONTROL:
control = new SyncModifyDnControl();
SyncModifyDnControlDecoder syncModifyDnControlDecoder = new SyncModifyDnControlDecoder();
SyncModifyDnControlContainer syncModifyDnControlContainer = new SyncModifyDnControlContainer();
syncModifyDnControlContainer.setSyncModifyDnControl( ( SyncModifyDnControl ) control );
bb = ByteBuffer.allocate( jndiControl.getEncodedValue().length );
bb.put( jndiControl.getEncodedValue() ).flip();
syncModifyDnControlDecoder.decode( bb, syncModifyDnControlContainer );
break;
case SYNC_REQUEST_VALUE_CONTROL:
control = new SyncRequestValueControl();
SyncRequestValueControlDecoder syncRequestValueControlDecoder = new SyncRequestValueControlDecoder();
SyncRequestValueControlContainer syncRequestValueControlContainer = new SyncRequestValueControlContainer();
syncRequestValueControlContainer.setSyncRequestValueControl( ( SyncRequestValueControl ) control );
bb = ByteBuffer.allocate( jndiControl.getEncodedValue().length );
bb.put( jndiControl.getEncodedValue() ).flip();
syncRequestValueControlDecoder.decode( bb, syncRequestValueControlContainer );
break;
case SYNC_STATE_VALUE_CONTROL:
control = new SyncStateValueControl();
SyncStateValueControlDecoder syncStateValueControlDecoder = new SyncStateValueControlDecoder();
SyncStateValueControlContainer syncStateValueControlContainer = new SyncStateValueControlContainer();
syncStateValueControlContainer.setSyncStateValueControl( ( SyncStateValueControl ) control );
bb = ByteBuffer.allocate( jndiControl.getEncodedValue().length );
bb.put( jndiControl.getEncodedValue() ).flip();
syncStateValueControlDecoder.decode( bb, syncStateValueControlContainer );
break;
}
control.setCritical( jndiControl.isCritical() );
control.setValue( jndiControl.getEncodedValue() );
return control;
}
|
diff --git a/src/to/joe/j2mc/admintoolkit/command/WhoIsCommand.java b/src/to/joe/j2mc/admintoolkit/command/WhoIsCommand.java
index 59aa80e..10e5e5d 100644
--- a/src/to/joe/j2mc/admintoolkit/command/WhoIsCommand.java
+++ b/src/to/joe/j2mc/admintoolkit/command/WhoIsCommand.java
@@ -1,58 +1,61 @@
package to.joe.j2mc.admintoolkit.command;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import to.joe.j2mc.admintoolkit.J2MC_AdminToolkit;
import to.joe.j2mc.core.J2MC_Manager;
import to.joe.j2mc.core.command.MasterCommand;
import to.joe.j2mc.core.exceptions.BadPlayerMatchException;
public class WhoIsCommand extends MasterCommand {
public WhoIsCommand(J2MC_AdminToolkit admintoolkit) {
super(admintoolkit);
}
@Override
public void exec(CommandSender sender, String commandName, String[] args, Player player, boolean isPlayer) {
+ if (args.length != 1) {
+ sender.sendMessage(ChatColor.RED + "Usage: /whois <player>");
+ }
Player target = null;
try {
target = J2MC_Manager.getVisibility().getPlayer(args[0], sender);
} catch (BadPlayerMatchException e) {
sender.sendMessage(ChatColor.RED + e.getMessage());
return;
}
String flags = "";
String group = "";
try {
final PreparedStatement ps = J2MC_Manager.getMySQL().getFreshPreparedStatementHotFromTheOven("SELECT `flags` FROM users WHERE name=?");
ps.setString(1, target.getName());
final ResultSet rs = ps.executeQuery();
if (rs.next()) {
flags = rs.getString("flags");
}
final PreparedStatement prep = J2MC_Manager.getMySQL().getFreshPreparedStatementHotFromTheOven("SELECT `group` from users WHERE name=?");
prep.setString(1, target.getName());
final ResultSet rs2 = prep.executeQuery();
if (rs2.next()) {
group = rs2.getString("group");
}
} catch (final Exception e) {
e.printStackTrace();
}
Location loc = target.getLocation();
sender.sendMessage(ChatColor.GOLD + "=====================================");
sender.sendMessage(ChatColor.GOLD + "Whois for " + target.getDisplayName());
sender.sendMessage(ChatColor.GOLD + "IP: " + target.getAddress().getAddress().getHostAddress());
sender.sendMessage(ChatColor.GOLD + "Location: " + (int)Math.round(loc.getX()) + ", " + (int)Math.round(loc.getY()) + ", " + (int)Math.round(loc.getZ()) + " | Light Level: " + loc.getBlock().getLightLevel());
sender.sendMessage(ChatColor.GOLD + "Group: " + group + " | Flags: " + flags);
sender.sendMessage(ChatColor.GOLD + "=====================================");
}
}
| true | true | public void exec(CommandSender sender, String commandName, String[] args, Player player, boolean isPlayer) {
Player target = null;
try {
target = J2MC_Manager.getVisibility().getPlayer(args[0], sender);
} catch (BadPlayerMatchException e) {
sender.sendMessage(ChatColor.RED + e.getMessage());
return;
}
String flags = "";
String group = "";
try {
final PreparedStatement ps = J2MC_Manager.getMySQL().getFreshPreparedStatementHotFromTheOven("SELECT `flags` FROM users WHERE name=?");
ps.setString(1, target.getName());
final ResultSet rs = ps.executeQuery();
if (rs.next()) {
flags = rs.getString("flags");
}
final PreparedStatement prep = J2MC_Manager.getMySQL().getFreshPreparedStatementHotFromTheOven("SELECT `group` from users WHERE name=?");
prep.setString(1, target.getName());
final ResultSet rs2 = prep.executeQuery();
if (rs2.next()) {
group = rs2.getString("group");
}
} catch (final Exception e) {
e.printStackTrace();
}
Location loc = target.getLocation();
sender.sendMessage(ChatColor.GOLD + "=====================================");
sender.sendMessage(ChatColor.GOLD + "Whois for " + target.getDisplayName());
sender.sendMessage(ChatColor.GOLD + "IP: " + target.getAddress().getAddress().getHostAddress());
sender.sendMessage(ChatColor.GOLD + "Location: " + (int)Math.round(loc.getX()) + ", " + (int)Math.round(loc.getY()) + ", " + (int)Math.round(loc.getZ()) + " | Light Level: " + loc.getBlock().getLightLevel());
sender.sendMessage(ChatColor.GOLD + "Group: " + group + " | Flags: " + flags);
sender.sendMessage(ChatColor.GOLD + "=====================================");
}
| public void exec(CommandSender sender, String commandName, String[] args, Player player, boolean isPlayer) {
if (args.length != 1) {
sender.sendMessage(ChatColor.RED + "Usage: /whois <player>");
}
Player target = null;
try {
target = J2MC_Manager.getVisibility().getPlayer(args[0], sender);
} catch (BadPlayerMatchException e) {
sender.sendMessage(ChatColor.RED + e.getMessage());
return;
}
String flags = "";
String group = "";
try {
final PreparedStatement ps = J2MC_Manager.getMySQL().getFreshPreparedStatementHotFromTheOven("SELECT `flags` FROM users WHERE name=?");
ps.setString(1, target.getName());
final ResultSet rs = ps.executeQuery();
if (rs.next()) {
flags = rs.getString("flags");
}
final PreparedStatement prep = J2MC_Manager.getMySQL().getFreshPreparedStatementHotFromTheOven("SELECT `group` from users WHERE name=?");
prep.setString(1, target.getName());
final ResultSet rs2 = prep.executeQuery();
if (rs2.next()) {
group = rs2.getString("group");
}
} catch (final Exception e) {
e.printStackTrace();
}
Location loc = target.getLocation();
sender.sendMessage(ChatColor.GOLD + "=====================================");
sender.sendMessage(ChatColor.GOLD + "Whois for " + target.getDisplayName());
sender.sendMessage(ChatColor.GOLD + "IP: " + target.getAddress().getAddress().getHostAddress());
sender.sendMessage(ChatColor.GOLD + "Location: " + (int)Math.round(loc.getX()) + ", " + (int)Math.round(loc.getY()) + ", " + (int)Math.round(loc.getZ()) + " | Light Level: " + loc.getBlock().getLightLevel());
sender.sendMessage(ChatColor.GOLD + "Group: " + group + " | Flags: " + flags);
sender.sendMessage(ChatColor.GOLD + "=====================================");
}
|
diff --git a/util/src/main/java/com/psddev/dari/util/Settings.java b/util/src/main/java/com/psddev/dari/util/Settings.java
index ca1ab959..a64242c6 100644
--- a/util/src/main/java/com/psddev/dari/util/Settings.java
+++ b/util/src/main/java/com/psddev/dari/util/Settings.java
@@ -1,455 +1,455 @@
package com.psddev.dari.util;
import java.io.InputStream;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Type;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Map;
import java.util.HashMap;
import java.util.TreeMap;
import java.util.Properties;
import javax.naming.Binding;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** Global map of settings. */
public class Settings {
/**
* Sub-key used to identify the implementation class for
* {@link #newInstance}.
*/
public static final String CLASS_SUB_SETTING = "class";
/** Key used to toggle debug mode. */
public static final String DEBUG_SETTING = "DEBUG";
/** Key used to indicate when running in a production environment. */
public static final String PRODUCTION_SETTING = "PRODUCTION";
/** Default properties file that contains all settings. */
public static final String SETTINGS_FILE = "/settings.properties";
private static final Logger LOGGER = LoggerFactory.getLogger(Settings.class);
private static final String JNDI_PREFIX = "java:comp/env";
private static final ThreadLocal<Map<String, Object>> OVERRIDES = new ThreadLocal<Map<String, Object>>();
private static final PullThroughValue<Map<String, Object>> SETTINGS = new PullThroughValue<Map<String, Object>>() {
@Override
protected Map<String, Object> produce() {
return new PeriodicCache<String, Object>(0.0, 10.0) {
@Override
protected Map<String, Object> update() {
// Optional file.
Map<String, Object> settings = new TreeMap<String, Object>();
InputStream input = Settings.class.getResourceAsStream(SETTINGS_FILE);
if (input != null) {
try {
try {
Properties properties = new Properties();
properties.load(input);
putAllMap(settings, properties);
} finally {
input.close();
}
} catch (IOException ex) {
LOGGER.warn(String.format("Cannot read [%s] file!", SETTINGS_FILE), ex);
}
}
putAllMap(settings, System.getenv());
putAllMap(settings, System.getProperties());
// JNDI.
try {
putAllContext(settings, new InitialContext(), JNDI_PREFIX);
- } catch (NamingException ex) {
+ } catch (Throwable error) {
}
return Collections.unmodifiableMap(settings);
}
private void putAllMap(Map<String, Object> map, Map<?, ?> other) {
for (Map.Entry<?, ?> entry : other.entrySet()) {
Object key = entry.getKey();
if (key != null) {
CollectionUtils.putByPath(map, key.toString(), entry.getValue());
}
}
}
private void putAllContext(Map<String, Object> map, Context context, String path) throws NamingException {
String pathWithSlash;
if (path.endsWith("/")) {
pathWithSlash = path;
path = path.substring(0, path.length() - 1);
} else {
pathWithSlash = path + "/";
}
for (Enumeration<Binding> e = context.listBindings(path); e.hasMoreElements(); ) {
Binding binding = e.nextElement();
String name = binding.getName();
if (name.startsWith(pathWithSlash)) {
name = name.substring(pathWithSlash.length());
}
if (!ObjectUtils.isBlank(name)) {
String fullName = pathWithSlash + name;
Object value = binding.getObject();
if (value instanceof Context) {
putAllContext(map, context, fullName);
} else {
CollectionUtils.putByPath(map, fullName.substring(JNDI_PREFIX.length() + 1), value);
}
}
}
}
};
}
};
/**
* Returns the value associated with the given {@code key}, or if not
* found or is blank, the given {@code defaultValue}.
*
* @param key Can be {@code null}.
* @param defaultValue Can be {@code null}.
*/
public static Object getOrDefault(String key, Object defaultValue) {
Object value = null;
Map<String, Object> overrides = OVERRIDES.get();
if (overrides != null) {
value = CollectionUtils.getByPath(overrides, key);
}
if (ObjectUtils.isBlank(value)) {
value = CollectionUtils.getByPath(SETTINGS.get(), key);
}
if (ObjectUtils.isBlank(value)) {
value = defaultValue;
}
return value;
}
/**
* Returns the value associated with the given {@code key} as an instance
* of the given {@code returnType}, or if not found or is blank, the given
* {@code defaultValue}.
*
* @param returnType Can't be {@code null}.
* @param key Can be {@code null}.
* @param defaultValue Can be {@code null}.
*/
public static Object getOrDefault(Type returnType, String key, Object defaultValue) {
return ObjectUtils.to(returnType, getOrDefault(key, defaultValue));
}
/**
* Returns the value associated with the given {@code key} as an instance
* of the given {@code returnClass}, or if not found or is blank, the given
* {@code defaultValue}.
*
* @param returnClass Can't be {@code null}.
* @param key Can be {@code null}.
* @param defaultValue Can be {@code null}.
*/
public static <T> T getOrDefault(Class<T> returnClass, String key, T defaultValue) {
return ObjectUtils.to(returnClass, getOrDefault(key, defaultValue));
}
/**
* Returns the value associated with the given {@code key} as an instance
* of the type referenced by the given {@code returnTypeReference},
* or if not found or is blank, the given {@code defaultValue}.
*
* @param returnTypeReference Can't be {@code null}.
* @param key Can be {@code null}.
* @param defaultValue Can be {@code null}.
*/
public static <T> T getOrDefault(TypeReference<T> returnTypeReference, String key, T defaultValue) {
return ObjectUtils.to(returnTypeReference, getOrDefault(key, defaultValue));
}
/**
* Returns the value associated with the given {@code key}, or if not
* found or is blank, the given {@code defaultValue}.
*
* @param key Can be {@code null}.
*/
public static Object get(String key) {
return get(key, null);
}
/**
* Returns the value, as an instance of the given {@code returnType},
* associated with the given {@code key}, or if not found or is blank,
* the given {@code defaultValue}.
*
* @param returnType Can't be {@code null}.
* @param key Can be {@code null}.
*/
public static Object get(Type returnType, String key) {
return get(returnType, key, null);
}
/**
* Returns the value, as an instance of the given {@code returnClass},
* associated with the given {@code key}, or if not found or is blank,
* the given {@code defaultValue}.
*
* @param returnClass Can't be {@code null}.
* @param key Can be {@code null}.
*/
public static <T> T get(Class<T> returnClass, String key) {
return get(returnClass, key, null);
}
/**
* Returns the value, as an instance of the type referenced by the given
* {@code returnTypeReference}, associated with the given {@code key},
* or if not found or is blank, the given {@code defaultValue}.
*
* @param returnTypeReference Can't be {@code null}.
* @param key Can be {@code null}.
*/
public static <T> T get(TypeReference<T> returnTypeReference, String key) {
return get(returnTypeReference, key, null);
}
private static <T> T checkValue(T value, String key, String message) {
if (ObjectUtils.isBlank(value)) {
throw new SettingsException(key, message != null ? message : "[" + key + "] can't be blank!");
} else {
return value;
}
}
/**
* Returns the value associated with the given {@code key}, or throws
* a {@link SettingsException} with the given {@code message} if not
* found or the value is blank.
*
* @param key Can be {@code null}.
* @param message Can be {@code null}.
* @throws SettingsException If the value associated with the given
* {@code key} isn't found or is blank.
*/
public static Object getOrError(String key, String message) {
return checkValue(get(key), key, message);
}
/**
* Returns the value associated with the given {@code key} as an instance
* of the given {@code returnType}, or throws a {@link SettingsException}
* with the given {@code message} if not found or the value is blank.
*
* @param returnType Can't be {@code null}.
* @param key Can be {@code null}.
* @param message Can be {@code null}.
* @throws SettingsException If the value associated with the given
* {@code key} isn't found or is blank.
*/
public static Object getOrError(Type returnType, String key, String message) {
return checkValue(get(returnType, key), key, message);
}
/**
* Returns the value associated with the given {@code key} as an instance
* of the given {@code returnClass}, or throws a {@link SettingsException}
* with the given {@code message} if not found or the value is blank.
*
* @param returnClass Can't be {@code null}.
* @param key Can be {@code null}.
* @param message Can be {@code null}.
* @throws SettingsException If the value associated with the given
* {@code key} isn't found or is blank.
*/
public static <T> T getOrError(Class<T> returnClass, String key, String message) {
return checkValue(get(returnClass, key), key, message);
}
/**
* Returns the value associated with the given {@code key} as an instance
* of the type referenced by the given {@code returnTypeReference},
* or throws a {@link SettingsException} with the given {@code message}
* if not found or the value is blank.
*
* @param returnTypeReference Can't be {@code null}.
* @param key Can be {@code null}.
* @param message Can be {@code null}.
* @throws SettingsException If the value associated with the given
* {@code key} isn't found or is blank.
*/
public static <T> T getOrError(TypeReference<T> returnTypeReference, String key, String message) {
return checkValue(get(returnTypeReference, key), key, message);
}
/**
* Temporarily overrides the value associated with the given
* {@code key} in the current thread.
*/
public static void setOverride(String key, Object value) {
Map<String, Object> overrides = OVERRIDES.get();
if (value != null) {
if (overrides == null) {
overrides = new HashMap<String, Object>();
OVERRIDES.set(overrides);
}
CollectionUtils.putByPath(overrides, key, value);
} else {
if (overrides != null) {
CollectionUtils.putByPath(overrides, key, null);
}
}
}
/** Returns {@code true} if running in debug mode. */
public static boolean isDebug() {
return get(boolean.class, DEBUG_SETTING);
}
/** Returns {@code true} if running in a production environment. */
public static boolean isProduction() {
return get(boolean.class, PRODUCTION_SETTING);
}
/**
* Returns a view of all settings as a map.
*
* @return Never {@code null}. Immutable.
*/
public static Map<String, Object> asMap() {
return SETTINGS.get();
}
/**
* Creates an instance of the given {@code interfaceClass} based on the
* values associated with the given {@code key}.
*
* @param interfaceClass Can't be {@code null}.
* @param key Can't be blank.
* @return Never {@code null}.
* @throws SettingsException If the values associated with the given
* {@code key} can't be used to create the instance.
*/
@SuppressWarnings("unchecked")
public static <T extends SettingsBackedObject> T newInstance(Class<T> interfaceClass, String key) {
Object instanceSettings = get(key);
if (!(instanceSettings instanceof Map)) {
throw new SettingsException(key, String.format(
"[%s] settings must be a map!",
interfaceClass.getName()));
}
String classKey = key + "/" + CLASS_SUB_SETTING;
String instanceClassName = ObjectUtils.to(String.class, get(classKey));
if (ObjectUtils.isBlank(instanceClassName)) {
throw new SettingsException(classKey, String.format(
"Implementation class for [%s] is missing!",
interfaceClass.getName()));
}
Class<?> instanceClass = null;
try {
instanceClass = Class.forName(instanceClassName);
} catch (ClassNotFoundException ex) {
throw new SettingsException(classKey, String.format(
"[%s] isn't a valid class!",
instanceClassName));
}
for (Class<?> requiredClass : new Class<?>[] {
interfaceClass,
SettingsBackedObject.class }) {
if (!requiredClass.isAssignableFrom(instanceClass)) {
throw new SettingsException(classKey, String.format(
"[%s] doesn't implement [%s]!",
instanceClass.getName(),
requiredClass.getName()));
}
}
Constructor<?> constructor = null;
try {
constructor = instanceClass.getDeclaredConstructor();
} catch (NoSuchMethodException ex) {
throw new SettingsException(classKey, String.format(
"[%s] doesn't have a nullary constructor!"));
}
T object;
try {
constructor.setAccessible(true);
object = (T) constructor.newInstance();
} catch (IllegalAccessException ex) {
throw new IllegalStateException(ex);
} catch (InstantiationException ex) {
throw new IllegalStateException(ex);
} catch (InvocationTargetException ex) {
Throwable cause = ex.getCause();
throw cause instanceof RuntimeException
? (RuntimeException) cause
: new RuntimeException(String.format(
"Unexpected error trying to create [%s]!",
instanceClassName), cause);
}
object.initialize(key, (Map<String, Object>) instanceSettings);
return object;
}
// --- Deprecated ---
/** @deprecated Use {@link #getOrDefault(String, Object)} instead. */
@Deprecated
public static Object get(String key, Object defaultValue) {
return getOrDefault(key, defaultValue);
}
/** @deprecated Use {@link #getOrDefault(Type, String, Object)} instead. */
@Deprecated
public static Object get(Type returnType, String key, Object defaultValue) {
return getOrDefault(returnType, key, defaultValue);
}
/** @deprecated Use {@link #getOrDefault(Class, String, Object)} instead. */
@Deprecated
public static <T> T get(Class<T> returnClass, String key, T defaultValue) {
return getOrDefault(returnClass, key, defaultValue);
}
/** @deprecated Use {@link #getOrDefault(TypeReference, String, Object)} instead. */
@Deprecated
public static <T> T get(TypeReference<T> returnTypeReference, String key, T defaultValue) {
return getOrDefault(returnTypeReference, key, defaultValue);
}
}
| true | true | protected Map<String, Object> produce() {
return new PeriodicCache<String, Object>(0.0, 10.0) {
@Override
protected Map<String, Object> update() {
// Optional file.
Map<String, Object> settings = new TreeMap<String, Object>();
InputStream input = Settings.class.getResourceAsStream(SETTINGS_FILE);
if (input != null) {
try {
try {
Properties properties = new Properties();
properties.load(input);
putAllMap(settings, properties);
} finally {
input.close();
}
} catch (IOException ex) {
LOGGER.warn(String.format("Cannot read [%s] file!", SETTINGS_FILE), ex);
}
}
putAllMap(settings, System.getenv());
putAllMap(settings, System.getProperties());
// JNDI.
try {
putAllContext(settings, new InitialContext(), JNDI_PREFIX);
} catch (NamingException ex) {
}
return Collections.unmodifiableMap(settings);
}
private void putAllMap(Map<String, Object> map, Map<?, ?> other) {
for (Map.Entry<?, ?> entry : other.entrySet()) {
Object key = entry.getKey();
if (key != null) {
CollectionUtils.putByPath(map, key.toString(), entry.getValue());
}
}
}
private void putAllContext(Map<String, Object> map, Context context, String path) throws NamingException {
String pathWithSlash;
if (path.endsWith("/")) {
pathWithSlash = path;
path = path.substring(0, path.length() - 1);
} else {
pathWithSlash = path + "/";
}
for (Enumeration<Binding> e = context.listBindings(path); e.hasMoreElements(); ) {
Binding binding = e.nextElement();
String name = binding.getName();
if (name.startsWith(pathWithSlash)) {
name = name.substring(pathWithSlash.length());
}
if (!ObjectUtils.isBlank(name)) {
String fullName = pathWithSlash + name;
Object value = binding.getObject();
if (value instanceof Context) {
putAllContext(map, context, fullName);
} else {
CollectionUtils.putByPath(map, fullName.substring(JNDI_PREFIX.length() + 1), value);
}
}
}
}
};
}
| protected Map<String, Object> produce() {
return new PeriodicCache<String, Object>(0.0, 10.0) {
@Override
protected Map<String, Object> update() {
// Optional file.
Map<String, Object> settings = new TreeMap<String, Object>();
InputStream input = Settings.class.getResourceAsStream(SETTINGS_FILE);
if (input != null) {
try {
try {
Properties properties = new Properties();
properties.load(input);
putAllMap(settings, properties);
} finally {
input.close();
}
} catch (IOException ex) {
LOGGER.warn(String.format("Cannot read [%s] file!", SETTINGS_FILE), ex);
}
}
putAllMap(settings, System.getenv());
putAllMap(settings, System.getProperties());
// JNDI.
try {
putAllContext(settings, new InitialContext(), JNDI_PREFIX);
} catch (Throwable error) {
}
return Collections.unmodifiableMap(settings);
}
private void putAllMap(Map<String, Object> map, Map<?, ?> other) {
for (Map.Entry<?, ?> entry : other.entrySet()) {
Object key = entry.getKey();
if (key != null) {
CollectionUtils.putByPath(map, key.toString(), entry.getValue());
}
}
}
private void putAllContext(Map<String, Object> map, Context context, String path) throws NamingException {
String pathWithSlash;
if (path.endsWith("/")) {
pathWithSlash = path;
path = path.substring(0, path.length() - 1);
} else {
pathWithSlash = path + "/";
}
for (Enumeration<Binding> e = context.listBindings(path); e.hasMoreElements(); ) {
Binding binding = e.nextElement();
String name = binding.getName();
if (name.startsWith(pathWithSlash)) {
name = name.substring(pathWithSlash.length());
}
if (!ObjectUtils.isBlank(name)) {
String fullName = pathWithSlash + name;
Object value = binding.getObject();
if (value instanceof Context) {
putAllContext(map, context, fullName);
} else {
CollectionUtils.putByPath(map, fullName.substring(JNDI_PREFIX.length() + 1), value);
}
}
}
}
};
}
|
diff --git a/modules/extension/wms/src/main/java/org/geotools/map/WMSMapLayer.java b/modules/extension/wms/src/main/java/org/geotools/map/WMSMapLayer.java
index 6b13ffdd5..8f645a716 100644
--- a/modules/extension/wms/src/main/java/org/geotools/map/WMSMapLayer.java
+++ b/modules/extension/wms/src/main/java/org/geotools/map/WMSMapLayer.java
@@ -1,342 +1,344 @@
/*
* GeoTools - The Open Source Java GIS Toolkit
* http://geotools.org
*
* (C) 2004-2008, Open Source Geospatial Foundation (OSGeo)
*
* This library 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;
* version 2.1 of the License.
*
* 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.
*/
package org.geotools.map;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import org.geotools.coverage.grid.GridCoverage2D;
import org.geotools.coverage.grid.GridCoverageFactory;
import org.geotools.coverage.grid.GridGeometry2D;
import org.geotools.coverage.grid.io.AbstractGridCoverage2DReader;
import org.geotools.coverage.grid.io.AbstractGridFormat;
import org.geotools.data.DataUtilities;
import org.geotools.data.ows.Layer;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.data.wms.WebMapServer;
import org.geotools.data.wms.request.GetFeatureInfoRequest;
import org.geotools.data.wms.request.GetMapRequest;
import org.geotools.data.wms.response.GetFeatureInfoResponse;
import org.geotools.data.wms.response.GetMapResponse;
import org.geotools.factory.CommonFactoryFinder;
import org.geotools.geometry.DirectPosition2D;
import org.geotools.geometry.GeneralEnvelope;
import org.geotools.geometry.jts.ReferencedEnvelope;
import org.geotools.ows.ServiceException;
import org.geotools.referencing.CRS;
import org.geotools.resources.coverage.FeatureUtilities;
import org.geotools.styling.FeatureTypeStyle;
import org.geotools.styling.RasterSymbolizer;
import org.geotools.styling.Rule;
import org.geotools.styling.Style;
import org.geotools.styling.StyleFactory;
import org.opengis.coverage.grid.Format;
import org.opengis.geometry.Envelope;
import org.opengis.parameter.GeneralParameterValue;
import org.opengis.parameter.ParameterValue;
import org.opengis.referencing.ReferenceIdentifier;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.opengis.referencing.operation.MathTransform;
/**
* Wraps a WMS layer into a {@link MapLayer} for interactive rendering usage TODO: expose a
* GetFeatureInfo that returns a feature collection TODO: expose the list of named styles and allow
* choosing which style to use
*
* @author Andrea Aime - OpenGeo
*/
public class WMSMapLayer extends DefaultMapLayer {
/** The logger for the map module. */
static public final Logger LOGGER = org.geotools.util.logging.Logging
.getLogger("org.geotools.map");
/**
* The default raster style
*/
static Style STYLE;
static GridCoverageFactory gcf = new GridCoverageFactory();
WMSCoverageReader reader;
static {
StyleFactory factory = CommonFactoryFinder.getStyleFactory(null);
RasterSymbolizer symbolizer = factory.createRasterSymbolizer();
Rule rule = factory.createRule();
rule.symbolizers().add(symbolizer);
FeatureTypeStyle type = factory.createFeatureTypeStyle();
type.rules().add(rule);
STYLE = factory.createStyle();
STYLE.featureTypeStyles().add(type);
}
/**
* Builds a new WMS alyer
*
* @param wms
* @param layer
*/
public WMSMapLayer(WebMapServer wms, Layer layer) {
super((SimpleFeatureSource) null, null, "");
reader = new WMSCoverageReader(wms, layer);
try {
this.featureSource = DataUtilities.source(FeatureUtilities.wrapGridCoverageReader(
reader, null));
} catch (Throwable t) {
throw new RuntimeException("Unexpected exception occurred during map layer building", t);
}
this.style = STYLE;
}
public synchronized ReferencedEnvelope getBounds() {
return reader.getBounds();
}
/**
* Retrieves the feature info as text
* @param pos
* @return
* @throws IOException
*/
public String getFeatureInfoAsText(DirectPosition2D pos) throws IOException {
return reader.getFeatureInfoAsText(pos);
}
/**
* A grid coverage readers backing onto a WMS server by issuing GetMap
*/
static class WMSCoverageReader extends AbstractGridCoverage2DReader {
/**
* The WMS server
*/
WebMapServer wms;
/**
* The layer
*/
Layer layer;
/**
* The layer bounds
*/
ReferencedEnvelope bounds;
/**
* The chosen SRS name
*/
String srsName;
/**
* The format to use for requests
*/
String format;
/**
* The last GetMap request
*/
private GetMapRequest mapRequest;
/**
* The last GetMap response
*/
GridCoverage2D grid;
/**
* Builds a new WMS coverage reader
* @param wms
* @param layer
*/
public WMSCoverageReader(WebMapServer wms, Layer layer) {
this.wms = wms;
this.layer = layer;
// compute the reader bounds and crs
Set<String> srs = layer.getSrs();
srsName = srs.iterator().next();
if (srs.contains("EPSG:4326")) {
// really we should get the underlying
// map pane CRS from viewport
srsName = "EPSG:4326";
} else {
srsName = (String) srs.iterator().next();
}
CoordinateReferenceSystem crs = null;
try {
crs = CRS.decode(srsName);
} catch (Exception e) {
LOGGER.log(Level.FINE, "Bounds unavailable for layer" + layer);
}
GeneralEnvelope general = layer.getEnvelope(crs);
this.bounds = new ReferencedEnvelope(general);
this.originalEnvelope = new GeneralEnvelope(bounds);
this.crs = crs;
// best guess at the format with a preference for PNG (since it's normally transparent)
List<String> formats = wms.getCapabilities().getRequest().getGetMap().getFormats();
this.format = formats.iterator().next();
for (String format : formats) {
if ("image/png".equals(format) || "image/png24".equals(format)
|| "png".equals(format) || "png24".equals(format))
this.format = format;
}
}
/**
* Issues GetFeatureInfo against a point using the params of the last GetMap request
* @param pos
* @return
* @throws IOException
*/
public String getFeatureInfoAsText(DirectPosition2D pos) throws IOException {
GetFeatureInfoRequest request = wms.createGetFeatureInfoRequest(mapRequest);
request.setFeatureCount(1);
request.setInfoFormat("text/plain");
try {
MathTransform mt = grid.getGridGeometry().getCRSToGrid2D();
DirectPosition2D dest = new DirectPosition2D();
mt.transform(pos, dest);
request.setQueryPoint((int) dest.getX(), (int) dest.getY());
} catch (Exception e) {
throw new IOException("Failed to grab feature info");
}
BufferedReader reader = null;
try {
GetFeatureInfoResponse response = wms.issueRequest(request);
reader = new BufferedReader(new InputStreamReader(response.getInputStream()));
String line;
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line);
}
return sb.toString();
} catch (ServiceException e) {
throw (IOException) new IOException("Failed to grab feature info").initCause(e);
} finally {
if (reader != null)
reader.close();
}
}
@Override
public GridCoverage2D read(GeneralParameterValue[] parameters)
throws IllegalArgumentException, IOException {
// try to get request params from the request
Envelope requestedEnvelope = null;
int width = -1;
int height = -1;
if (parameters != null) {
for (GeneralParameterValue param : parameters) {
final ReferenceIdentifier name = param.getDescriptor().getName();
if (name.equals(AbstractGridFormat.READ_GRIDGEOMETRY2D.getName())) {
final GridGeometry2D gg = (GridGeometry2D) ((ParameterValue) param)
.getValue();
requestedEnvelope = gg.getEnvelope();
- width = gg.getGridRange().getHigh(0);
- height = gg.getGridRange().getHigh(1);
+ // the range high value is the highest pixel included in the raster,
+ // the actual width and height is one more than that
+ width = gg.getGridRange().getHigh(0) + 1;
+ height = gg.getGridRange().getHigh(1) + 1;
break;
}
}
}
// fill in a reasonable default if we did not manage to get the params
if (requestedEnvelope == null) {
requestedEnvelope = getOriginalEnvelope();
width = 640;
height = (int) Math.round(requestedEnvelope.getSpan(1)
/ requestedEnvelope.getSpan(0) * 640);
}
// if the structure did not change reuse the same response
if (grid != null && grid.getGridGeometry().getGridRange2D().getWidth() == width
&& grid.getGridGeometry().getGridRange2D().getHeight() == height
&& grid.getEnvelope().equals(requestedEnvelope))
return grid;
grid = getMap(toReferencedEnvelope(requestedEnvelope), width, height);
return grid;
}
/**
* Execute the GetMap request
*/
GridCoverage2D getMap(ReferencedEnvelope requestedEnvelope, int width, int height)
throws IOException {
// build the request
GetMapRequest mapRequest = wms.createGetMapRequest();
mapRequest.addLayer(layer);
mapRequest.setDimensions(width, height);
mapRequest.setFormat(format);
mapRequest.setSRS(srsName);
mapRequest.setBBox(requestedEnvelope);
mapRequest.setTransparent(true);
// issue the request and wrap response in a grid coverage
InputStream is = null;
try {
GetMapResponse response = wms.issueRequest(mapRequest);
is = response.getInputStream();
BufferedImage image = ImageIO.read(is);
LOGGER.fine("GetMap completed");
this.mapRequest = mapRequest;
return gcf.create(layer.getTitle(), image, requestedEnvelope);
} catch(ServiceException e) {
throw (IOException) new IOException("GetMap failed").initCause(e);
}
}
/**
* Converts a {@link Envelope} into a {@link ReferencedEnvelope}
* @param envelope
* @return
*/
ReferencedEnvelope toReferencedEnvelope(Envelope envelope) {
ReferencedEnvelope env = new ReferencedEnvelope(envelope.getCoordinateReferenceSystem());
env.expandToInclude(envelope.getMinimum(0), envelope.getMinimum(1));
env.expandToInclude(envelope.getMaximum(0), envelope.getMaximum(1));
return env;
}
public Format getFormat() {
// this reader has not backing format
return null;
}
/**
* Returns the layer bounds
* @return
*/
public ReferencedEnvelope getBounds() {
return bounds;
}
}
}
| true | true | public GridCoverage2D read(GeneralParameterValue[] parameters)
throws IllegalArgumentException, IOException {
// try to get request params from the request
Envelope requestedEnvelope = null;
int width = -1;
int height = -1;
if (parameters != null) {
for (GeneralParameterValue param : parameters) {
final ReferenceIdentifier name = param.getDescriptor().getName();
if (name.equals(AbstractGridFormat.READ_GRIDGEOMETRY2D.getName())) {
final GridGeometry2D gg = (GridGeometry2D) ((ParameterValue) param)
.getValue();
requestedEnvelope = gg.getEnvelope();
width = gg.getGridRange().getHigh(0);
height = gg.getGridRange().getHigh(1);
break;
}
}
}
// fill in a reasonable default if we did not manage to get the params
if (requestedEnvelope == null) {
requestedEnvelope = getOriginalEnvelope();
width = 640;
height = (int) Math.round(requestedEnvelope.getSpan(1)
/ requestedEnvelope.getSpan(0) * 640);
}
// if the structure did not change reuse the same response
if (grid != null && grid.getGridGeometry().getGridRange2D().getWidth() == width
&& grid.getGridGeometry().getGridRange2D().getHeight() == height
&& grid.getEnvelope().equals(requestedEnvelope))
return grid;
grid = getMap(toReferencedEnvelope(requestedEnvelope), width, height);
return grid;
}
| public GridCoverage2D read(GeneralParameterValue[] parameters)
throws IllegalArgumentException, IOException {
// try to get request params from the request
Envelope requestedEnvelope = null;
int width = -1;
int height = -1;
if (parameters != null) {
for (GeneralParameterValue param : parameters) {
final ReferenceIdentifier name = param.getDescriptor().getName();
if (name.equals(AbstractGridFormat.READ_GRIDGEOMETRY2D.getName())) {
final GridGeometry2D gg = (GridGeometry2D) ((ParameterValue) param)
.getValue();
requestedEnvelope = gg.getEnvelope();
// the range high value is the highest pixel included in the raster,
// the actual width and height is one more than that
width = gg.getGridRange().getHigh(0) + 1;
height = gg.getGridRange().getHigh(1) + 1;
break;
}
}
}
// fill in a reasonable default if we did not manage to get the params
if (requestedEnvelope == null) {
requestedEnvelope = getOriginalEnvelope();
width = 640;
height = (int) Math.round(requestedEnvelope.getSpan(1)
/ requestedEnvelope.getSpan(0) * 640);
}
// if the structure did not change reuse the same response
if (grid != null && grid.getGridGeometry().getGridRange2D().getWidth() == width
&& grid.getGridGeometry().getGridRange2D().getHeight() == height
&& grid.getEnvelope().equals(requestedEnvelope))
return grid;
grid = getMap(toReferencedEnvelope(requestedEnvelope), width, height);
return grid;
}
|
diff --git a/Ingest/src/org/sleuthkit/autopsy/ingest/IngestDialogPanel.java b/Ingest/src/org/sleuthkit/autopsy/ingest/IngestDialogPanel.java
index 6d01ec233..8e6aa08b9 100644
--- a/Ingest/src/org/sleuthkit/autopsy/ingest/IngestDialogPanel.java
+++ b/Ingest/src/org/sleuthkit/autopsy/ingest/IngestDialogPanel.java
@@ -1,537 +1,537 @@
/*
* Autopsy Forensic Browser
*
* Copyright 2011 Basis Technology Corp.
* Contact: carrier <at> sleuthkit <dot> org
*
* 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.sleuthkit.autopsy.ingest;
import java.awt.Component;
import org.sleuthkit.autopsy.corecomponents.AdvancedConfigurationDialog;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableColumn;
import org.sleuthkit.autopsy.casemodule.IngestConfigurator;
import org.sleuthkit.autopsy.ingest.IngestManager.UpdateFrequency;
import org.sleuthkit.datamodel.Image;
/**
* main configuration panel for all ingest services, reusable JPanel component
*/
public class IngestDialogPanel extends javax.swing.JPanel implements IngestConfigurator {
private IngestManager manager = null;
private List<IngestServiceAbstract> services;
private IngestServiceAbstract currentService;
private Map<String, Boolean> serviceStates;
private ServicesTableModel tableModel;
private static final Logger logger = Logger.getLogger(IngestDialogPanel.class.getName());
// The image that's just been added to the database
private Image image;
private static IngestDialogPanel instance = null;
/** Creates new form IngestDialogPanel */
private IngestDialogPanel() {
tableModel = new ServicesTableModel();
services = new ArrayList<IngestServiceAbstract>();
serviceStates = new HashMap<String, Boolean>();
initComponents();
customizeComponents();
}
synchronized static IngestDialogPanel getDefault() {
if (instance == null) {
instance = new IngestDialogPanel();
}
return instance;
}
private void customizeComponents() {
servicesTable.setModel(tableModel);
this.manager = IngestManager.getDefault();
Collection<IngestServiceImage> imageServices = IngestManager.enumerateImageServices();
for (final IngestServiceImage service : imageServices) {
addService(service);
}
Collection<IngestServiceAbstractFile> fsServices = IngestManager.enumerateAbstractFileServices();
for (final IngestServiceAbstractFile service : fsServices) {
addService(service);
}
//time setting
timeGroup.add(timeRadioButton1);
timeGroup.add(timeRadioButton2);
timeGroup.add(timeRadioButton3);
if (manager.isIngestRunning()) {
setTimeSettingEnabled(false);
} else {
setTimeSettingEnabled(true);
}
//set default
final UpdateFrequency curFreq = manager.getUpdateFrequency();
switch (curFreq) {
case FAST:
timeRadioButton1.setSelected(true);
break;
case AVG:
timeRadioButton2.setSelected(true);
break;
case SLOW:
timeRadioButton3.setSelected(true);
break;
default:
//
}
servicesTable.setTableHeader(null);
servicesTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
//custom renderer for tooltips
ServiceTableRenderer renderer = new ServiceTableRenderer();
//customize column witdhs
final int width = servicesScrollPane.getPreferredSize().width;
TableColumn column = null;
for (int i = 0; i < servicesTable.getColumnCount(); i++) {
column = servicesTable.getColumnModel().getColumn(i);
if (i == 0) {
column.setPreferredWidth(((int) (width * 0.15)));
} else {
column.setCellRenderer(renderer);
column.setPreferredWidth(((int) (width * 0.84)));
}
}
servicesTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
ListSelectionModel listSelectionModel = (ListSelectionModel) e.getSource();
if (!listSelectionModel.isSelectionEmpty()) {
save();
int index = listSelectionModel.getMinSelectionIndex();
currentService = services.get(index);
reloadSimpleConfiguration();
advancedButton.setEnabled(currentService.hasAdvancedConfiguration());
} else {
currentService = null;
}
}
});
processUnallocCheckbox.setSelected(manager.getProcessUnallocSpace());
}
private void setTimeSettingEnabled(boolean enabled) {
timeRadioButton1.setEnabled(enabled);
timeRadioButton2.setEnabled(enabled);
timeRadioButton3.setEnabled(enabled);
}
private void setProcessUnallocSpaceEnabled(boolean enabled) {
processUnallocCheckbox.setEnabled(enabled);
}
@Override
public void paint(Graphics g) {
super.paint(g);
if (manager.isIngestRunning()) {
setTimeSettingEnabled(false);
setProcessUnallocSpaceEnabled(false);
} else {
setTimeSettingEnabled(true);
setProcessUnallocSpaceEnabled(true);
}
}
private void addService(IngestServiceAbstract service) {
final String serviceName = service.getName();
services.add(service);
serviceStates.put(serviceName, true);
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
timeGroup = new javax.swing.ButtonGroup();
servicesScrollPane = new javax.swing.JScrollPane();
servicesTable = new javax.swing.JTable();
jPanel1 = new javax.swing.JPanel();
advancedButton = new javax.swing.JButton();
jSeparator2 = new javax.swing.JSeparator();
jScrollPane1 = new javax.swing.JScrollPane();
simplePanel = new javax.swing.JPanel();
timePanel = new javax.swing.JPanel();
timeRadioButton3 = new javax.swing.JRadioButton();
timeRadioButton2 = new javax.swing.JRadioButton();
timeRadioButton1 = new javax.swing.JRadioButton();
timeLabel = new javax.swing.JLabel();
processUnallocCheckbox = new javax.swing.JCheckBox();
setPreferredSize(new java.awt.Dimension(522, 257));
servicesScrollPane.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(160, 160, 160)));
servicesScrollPane.setPreferredSize(new java.awt.Dimension(160, 160));
servicesTable.setBackground(new java.awt.Color(240, 240, 240));
servicesTable.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
}
));
servicesTable.setShowHorizontalLines(false);
servicesTable.setShowVerticalLines(false);
servicesScrollPane.setViewportView(servicesTable);
jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(160, 160, 160)));
jPanel1.setPreferredSize(new java.awt.Dimension(338, 257));
advancedButton.setText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.advancedButton.text")); // NOI18N
advancedButton.setEnabled(false);
advancedButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
advancedButtonActionPerformed(evt);
}
});
jScrollPane1.setBorder(null);
jScrollPane1.setPreferredSize(new java.awt.Dimension(250, 180));
simplePanel.setLayout(new javax.swing.BoxLayout(simplePanel, javax.swing.BoxLayout.PAGE_AXIS));
jScrollPane1.setViewportView(simplePanel);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 336, Short.MAX_VALUE)
.addComponent(jSeparator2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 336, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap(245, Short.MAX_VALUE)
.addComponent(advancedButton)
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 183, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0)
.addComponent(advancedButton)
.addContainerGap())
);
timePanel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(160, 160, 160)));
timeRadioButton3.setText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.timeRadioButton3.text")); // NOI18N
timeRadioButton3.setToolTipText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.timeRadioButton3.toolTipText")); // NOI18N
timeRadioButton2.setText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.timeRadioButton2.text")); // NOI18N
timeRadioButton2.setToolTipText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.timeRadioButton2.toolTipText")); // NOI18N
timeRadioButton1.setText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.timeRadioButton1.text")); // NOI18N
timeRadioButton1.setToolTipText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.timeRadioButton1.toolTipText")); // NOI18N
timeRadioButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
timeRadioButton1ActionPerformed(evt);
}
});
timeLabel.setText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.timeLabel.text")); // NOI18N
timeLabel.setToolTipText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.timeLabel.toolTipText")); // NOI18N
processUnallocCheckbox.setText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.processUnallocCheckbox.text")); // NOI18N
javax.swing.GroupLayout timePanelLayout = new javax.swing.GroupLayout(timePanel);
timePanel.setLayout(timePanelLayout);
timePanelLayout.setHorizontalGroup(
timePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(timePanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(timeLabel)
.addContainerGap(68, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, timePanelLayout.createSequentialGroup()
- .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
+ .addContainerGap()
.addGroup(timePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(timeRadioButton3)
.addComponent(timeRadioButton2)
.addComponent(timeRadioButton1))
- .addContainerGap())
+ .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(timePanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(processUnallocCheckbox)
.addContainerGap(10, Short.MAX_VALUE))
);
timePanelLayout.setVerticalGroup(
timePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(timePanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(timeLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(timeRadioButton1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(timeRadioButton2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(timeRadioButton3)
.addGap(18, 18, 18)
.addComponent(processUnallocCheckbox)
.addContainerGap(8, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(servicesScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 169, Short.MAX_VALUE)
.addComponent(timePanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 235, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addComponent(servicesScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 82, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(timePanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
);
}// </editor-fold>//GEN-END:initComponents
private void advancedButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_advancedButtonActionPerformed
final AdvancedConfigurationDialog dialog = new AdvancedConfigurationDialog();
dialog.addApplyButtonListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
dialog.close();
currentService.saveAdvancedConfiguration();
reloadSimpleConfiguration();
}
});
dialog.display(currentService.getAdvancedConfiguration());
}//GEN-LAST:event_advancedButtonActionPerformed
private void timeRadioButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_timeRadioButton1ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_timeRadioButton1ActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton advancedButton;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JSeparator jSeparator2;
private javax.swing.JCheckBox processUnallocCheckbox;
private javax.swing.JScrollPane servicesScrollPane;
private javax.swing.JTable servicesTable;
private javax.swing.JPanel simplePanel;
private javax.swing.ButtonGroup timeGroup;
private javax.swing.JLabel timeLabel;
private javax.swing.JPanel timePanel;
private javax.swing.JRadioButton timeRadioButton1;
private javax.swing.JRadioButton timeRadioButton2;
private javax.swing.JRadioButton timeRadioButton3;
// End of variables declaration//GEN-END:variables
private class ServicesTableModel extends AbstractTableModel {
@Override
public int getRowCount() {
return services.size();
}
@Override
public int getColumnCount() {
return 2;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
String name = services.get(rowIndex).getName();
if (columnIndex == 0) {
return serviceStates.get(name);
} else {
return name;
}
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return columnIndex == 0;
}
@Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
if (columnIndex == 0) {
serviceStates.put((String) getValueAt(rowIndex, 1), (Boolean) aValue);
}
}
@Override
public Class<?> getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
}
List<IngestServiceAbstract> getServicesToStart() {
List<IngestServiceAbstract> servicesToStart = new ArrayList<IngestServiceAbstract>();
for (IngestServiceAbstract service : services) {
boolean serviceEnabled = serviceStates.get(service.getName());
if (serviceEnabled) {
servicesToStart.add(service);
}
}
return servicesToStart;
}
private boolean timeSelectionEnabled() {
return timeRadioButton1.isEnabled() && timeRadioButton2.isEnabled() && timeRadioButton3.isEnabled();
}
private boolean processUnallocSpaceEnabled() {
return processUnallocCheckbox.isEnabled();
}
private UpdateFrequency getSelectedTimeValue() {
if (timeRadioButton1.isSelected()) {
return UpdateFrequency.FAST;
} else if (timeRadioButton2.isSelected()) {
return UpdateFrequency.AVG;
} else {
return UpdateFrequency.SLOW;
}
}
private void reloadSimpleConfiguration() {
simplePanel.removeAll();
if (currentService.hasSimpleConfiguration()) {
simplePanel.add(currentService.getSimpleConfiguration());
}
simplePanel.revalidate();
simplePanel.repaint();
}
/**
* To be called whenever the next, close, or start buttons are pressed.
*
*/
@Override
public void save() {
if (currentService != null && currentService.hasSimpleConfiguration()) {
currentService.saveSimpleConfiguration();
}
}
@Override
public JPanel getIngestConfigPanel() {
return this;
}
@Override
public void setImage(Image image) {
this.image = image;
}
@Override
public void start() {
//pick the services
List<IngestServiceAbstract> servicesToStart = getServicesToStart();
if (!servicesToStart.isEmpty()) {
manager.execute(servicesToStart, image);
}
//update ingest freq. refresh
if (timeSelectionEnabled()) {
manager.setUpdateFrequency(getSelectedTimeValue());
}
//update ingest proc. unalloc space
if (processUnallocSpaceEnabled() ) {
manager.setProcessUnallocSpace(processUnallocCheckbox.isSelected());
}
}
@Override
public boolean isIngestRunning() {
return manager.isIngestRunning();
}
/**
* Custom cell renderer for tooltips with service description
*/
private class ServiceTableRenderer extends DefaultTableCellRenderer {
@Override
public Component getTableCellRendererComponent(
JTable table, Object value,
boolean isSelected, boolean hasFocus,
int row, int column) {
super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
if (column == 1) {
//String serviceName = (String) table.getModel().getValueAt(row, column);
IngestServiceAbstract service = services.get(row);
String serviceDescr = service.getDescription();
setToolTipText(serviceDescr);
}
return this;
}
}
}
| false | true | private void initComponents() {
timeGroup = new javax.swing.ButtonGroup();
servicesScrollPane = new javax.swing.JScrollPane();
servicesTable = new javax.swing.JTable();
jPanel1 = new javax.swing.JPanel();
advancedButton = new javax.swing.JButton();
jSeparator2 = new javax.swing.JSeparator();
jScrollPane1 = new javax.swing.JScrollPane();
simplePanel = new javax.swing.JPanel();
timePanel = new javax.swing.JPanel();
timeRadioButton3 = new javax.swing.JRadioButton();
timeRadioButton2 = new javax.swing.JRadioButton();
timeRadioButton1 = new javax.swing.JRadioButton();
timeLabel = new javax.swing.JLabel();
processUnallocCheckbox = new javax.swing.JCheckBox();
setPreferredSize(new java.awt.Dimension(522, 257));
servicesScrollPane.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(160, 160, 160)));
servicesScrollPane.setPreferredSize(new java.awt.Dimension(160, 160));
servicesTable.setBackground(new java.awt.Color(240, 240, 240));
servicesTable.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
}
));
servicesTable.setShowHorizontalLines(false);
servicesTable.setShowVerticalLines(false);
servicesScrollPane.setViewportView(servicesTable);
jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(160, 160, 160)));
jPanel1.setPreferredSize(new java.awt.Dimension(338, 257));
advancedButton.setText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.advancedButton.text")); // NOI18N
advancedButton.setEnabled(false);
advancedButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
advancedButtonActionPerformed(evt);
}
});
jScrollPane1.setBorder(null);
jScrollPane1.setPreferredSize(new java.awt.Dimension(250, 180));
simplePanel.setLayout(new javax.swing.BoxLayout(simplePanel, javax.swing.BoxLayout.PAGE_AXIS));
jScrollPane1.setViewportView(simplePanel);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 336, Short.MAX_VALUE)
.addComponent(jSeparator2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 336, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap(245, Short.MAX_VALUE)
.addComponent(advancedButton)
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 183, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0)
.addComponent(advancedButton)
.addContainerGap())
);
timePanel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(160, 160, 160)));
timeRadioButton3.setText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.timeRadioButton3.text")); // NOI18N
timeRadioButton3.setToolTipText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.timeRadioButton3.toolTipText")); // NOI18N
timeRadioButton2.setText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.timeRadioButton2.text")); // NOI18N
timeRadioButton2.setToolTipText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.timeRadioButton2.toolTipText")); // NOI18N
timeRadioButton1.setText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.timeRadioButton1.text")); // NOI18N
timeRadioButton1.setToolTipText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.timeRadioButton1.toolTipText")); // NOI18N
timeRadioButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
timeRadioButton1ActionPerformed(evt);
}
});
timeLabel.setText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.timeLabel.text")); // NOI18N
timeLabel.setToolTipText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.timeLabel.toolTipText")); // NOI18N
processUnallocCheckbox.setText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.processUnallocCheckbox.text")); // NOI18N
javax.swing.GroupLayout timePanelLayout = new javax.swing.GroupLayout(timePanel);
timePanel.setLayout(timePanelLayout);
timePanelLayout.setHorizontalGroup(
timePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(timePanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(timeLabel)
.addContainerGap(68, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, timePanelLayout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(timePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(timeRadioButton3)
.addComponent(timeRadioButton2)
.addComponent(timeRadioButton1))
.addContainerGap())
.addGroup(timePanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(processUnallocCheckbox)
.addContainerGap(10, Short.MAX_VALUE))
);
timePanelLayout.setVerticalGroup(
timePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(timePanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(timeLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(timeRadioButton1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(timeRadioButton2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(timeRadioButton3)
.addGap(18, 18, 18)
.addComponent(processUnallocCheckbox)
.addContainerGap(8, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(servicesScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 169, Short.MAX_VALUE)
.addComponent(timePanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 235, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addComponent(servicesScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 82, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(timePanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
);
}// </editor-fold>//GEN-END:initComponents
| private void initComponents() {
timeGroup = new javax.swing.ButtonGroup();
servicesScrollPane = new javax.swing.JScrollPane();
servicesTable = new javax.swing.JTable();
jPanel1 = new javax.swing.JPanel();
advancedButton = new javax.swing.JButton();
jSeparator2 = new javax.swing.JSeparator();
jScrollPane1 = new javax.swing.JScrollPane();
simplePanel = new javax.swing.JPanel();
timePanel = new javax.swing.JPanel();
timeRadioButton3 = new javax.swing.JRadioButton();
timeRadioButton2 = new javax.swing.JRadioButton();
timeRadioButton1 = new javax.swing.JRadioButton();
timeLabel = new javax.swing.JLabel();
processUnallocCheckbox = new javax.swing.JCheckBox();
setPreferredSize(new java.awt.Dimension(522, 257));
servicesScrollPane.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(160, 160, 160)));
servicesScrollPane.setPreferredSize(new java.awt.Dimension(160, 160));
servicesTable.setBackground(new java.awt.Color(240, 240, 240));
servicesTable.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
}
));
servicesTable.setShowHorizontalLines(false);
servicesTable.setShowVerticalLines(false);
servicesScrollPane.setViewportView(servicesTable);
jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(160, 160, 160)));
jPanel1.setPreferredSize(new java.awt.Dimension(338, 257));
advancedButton.setText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.advancedButton.text")); // NOI18N
advancedButton.setEnabled(false);
advancedButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
advancedButtonActionPerformed(evt);
}
});
jScrollPane1.setBorder(null);
jScrollPane1.setPreferredSize(new java.awt.Dimension(250, 180));
simplePanel.setLayout(new javax.swing.BoxLayout(simplePanel, javax.swing.BoxLayout.PAGE_AXIS));
jScrollPane1.setViewportView(simplePanel);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 336, Short.MAX_VALUE)
.addComponent(jSeparator2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 336, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap(245, Short.MAX_VALUE)
.addComponent(advancedButton)
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 183, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0)
.addComponent(advancedButton)
.addContainerGap())
);
timePanel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(160, 160, 160)));
timeRadioButton3.setText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.timeRadioButton3.text")); // NOI18N
timeRadioButton3.setToolTipText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.timeRadioButton3.toolTipText")); // NOI18N
timeRadioButton2.setText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.timeRadioButton2.text")); // NOI18N
timeRadioButton2.setToolTipText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.timeRadioButton2.toolTipText")); // NOI18N
timeRadioButton1.setText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.timeRadioButton1.text")); // NOI18N
timeRadioButton1.setToolTipText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.timeRadioButton1.toolTipText")); // NOI18N
timeRadioButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
timeRadioButton1ActionPerformed(evt);
}
});
timeLabel.setText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.timeLabel.text")); // NOI18N
timeLabel.setToolTipText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.timeLabel.toolTipText")); // NOI18N
processUnallocCheckbox.setText(org.openide.util.NbBundle.getMessage(IngestDialogPanel.class, "IngestDialogPanel.processUnallocCheckbox.text")); // NOI18N
javax.swing.GroupLayout timePanelLayout = new javax.swing.GroupLayout(timePanel);
timePanel.setLayout(timePanelLayout);
timePanelLayout.setHorizontalGroup(
timePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(timePanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(timeLabel)
.addContainerGap(68, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, timePanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(timePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(timeRadioButton3)
.addComponent(timeRadioButton2)
.addComponent(timeRadioButton1))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(timePanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(processUnallocCheckbox)
.addContainerGap(10, Short.MAX_VALUE))
);
timePanelLayout.setVerticalGroup(
timePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(timePanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(timeLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(timeRadioButton1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(timeRadioButton2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(timeRadioButton3)
.addGap(18, 18, 18)
.addComponent(processUnallocCheckbox)
.addContainerGap(8, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(servicesScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 169, Short.MAX_VALUE)
.addComponent(timePanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 235, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addComponent(servicesScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 82, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(timePanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
);
}// </editor-fold>//GEN-END:initComponents
|
diff --git a/src/main/java/hex/Summary.java b/src/main/java/hex/Summary.java
index 3c20dbf6e..c10762412 100644
--- a/src/main/java/hex/Summary.java
+++ b/src/main/java/hex/Summary.java
@@ -1,273 +1,274 @@
package hex;
import java.util.Arrays;
import water.*;
import water.ValueArray.Column;
import water.util.Utils;
import com.google.common.base.Objects;
import com.google.gson.*;
public class Summary extends Iced {
public static final int MAX_HIST_SZ = water.parser.Enum.MAX_ENUM_SIZE;
public final static class ColSummary extends Iced {
public transient Summary _summary;
public final int _colId;
final int NMAX = 5;
public static final double [] DEFAULT_PERCENTILES = {0.01,0.05,0.10,0.25,0.33,0.50,0.66,0.75,0.90,0.95,0.99};
final long [] _bins; // bins for histogram
long _n;
final double _start, _end, _binsz, _binszInv;
double [] _min; // min N elements
double [] _max; // max N elements
private double [] _percentileValues;
final double [] _percentiles;
final boolean _enum;
ColSummary(Summary s, int colId) {
this(s,colId,null);
}
ColSummary(Summary s, int colId, double [] percentiles) {
_summary = s;
_colId = colId;
Column c = s.ary()._cols[colId];
_enum = c.isEnum();
if(c.isFloat() || c.numDomainSize() > MAX_HIST_SZ){
_percentiles = Objects.firstNonNull(percentiles, DEFAULT_PERCENTILES);
double binsz = 3.5 * c._sigma/ Math.cbrt(c._n);
int nbin = (int)((c._max - c._min) / binsz);
long n = Math.max(c._n,1);
double a = (c._max - c._min) / n;
double b = Math.pow(10, Math.floor(Math.log10(a)));
// selects among d, 5*d, and 10*d so that the number of
// partitions go in [start, end] is closest to n
if (a > 20*b/3)
b *= 10;
else if (a > 5*b/3)
b *= 5;
double start = b * Math.floor(c._min / b);
double end = b * Math.ceil(c._max / b);
n = (int)((end - start) / b);
_bins = new long[nbin];
_start = start;
_binsz = binsz;
_binszInv = 1.0/binsz;
_end = start + nbin * binsz;
} else {
_start = c._min;
_end = c._max;
int sz = (int)c.numDomainSize();
_bins = new long[sz];
_binszInv = _binsz = 1.0;
_percentiles = (c.isEnum())?null:Objects.firstNonNull(percentiles, DEFAULT_PERCENTILES);
}
if(!_enum){
_min = new double[NMAX];
_max = new double[NMAX];
Arrays.fill(_min, Double.POSITIVE_INFINITY);
Arrays.fill(_max, Double.NEGATIVE_INFINITY);
}
}
public final double [] percentiles(){return _percentiles;}
private void computePercentiles(){
_percentileValues = new double [_percentiles.length];
int k = 0;
long s = 0;
double pval = Double.NEGATIVE_INFINITY;
for(int j = 0; j < _percentiles.length; ++j){
double s1 = _percentiles[j]*_n - s;
long bc = 0;
while(s1 > (bc = binCount(k))){
s1 -= bc;
s += bc;
k++;
}
_percentileValues[j] = pval = Math.max(pval,_min[0] + k*_binsz) + s1/bc*_binsz;
}
}
public double percentileValue(double threshold){
if(_percentiles == null) throw new Error("Percentiles not available for enums!");
int idx = Arrays.binarySearch(_percentiles, threshold);
if(idx < 0) throw new Error("don't have requested percentile");
if(_percentileValues == null)computePercentiles();
return _percentileValues[idx];
}
void add(ColSummary other) {
assert _bins.length == other._bins.length;
assert Math.abs(_start - other._start) < 0.000001;
assert Math.abs(_binszInv - other._binszInv) < 0.000000001;
for (int i = 0; i < _bins.length; i++)
_bins[i] += other._bins[i];
if(_min != null){
int j = 0, k = 0;
double [] min = _min.clone();
double [] max = _max.clone();
for(int i = 0; i < _min.length; ++i){
if(other._min[k] < _min[j]){
min[i] = other._min[k++];
} else if(_min[j] < other._min[k]){
++j;
} else {
++j; ++k;
}
}
j = k = 0;
for(int i = 0; i < _max.length; ++i){
if(other._max[k] > _max[j]){
max[i] = other._max[k++];
} else if (_max[j] > other._max[k]){
++j;
} else {
++j;++k;
}
}
_min = min;
_max = max;
}
}
void add(double val) {
if(!_enum){
// first update min/max
if(val < _min[_min.length-1]){
int j = _min.length-1;
while(j > 0 && _min[j-1] > val)--j;
if(j == 0 || _min[j-1] < val){ // skip dups
for(int k = _min.length-1; k > j; --k)
_min[k] = _min[k-1];
_min[j] = val;
}
}
if(val > _max[_min.length-1]){
int j = _max.length-1;
while(j > 0 && _max[j-1] < val)--j;
if(j == 0 || _max[j-1] > val){ // skip dups
for(int k = _max.length-1; k > j; --k)
_max[k] = _max[k-1];
_max[j] = val;
}
}
}
// update the histogram
int binIdx = (_binsz == 1)
?Math.min((int)(val-_start),_bins.length-1)
:Math.min(_bins.length-1,(int)((val - _start) * _binszInv));
++_bins[binIdx];
++_n;
}
public double binValue(int b){
if(_binsz != 1)
return _start + Math.max(0,(b-1))*_binsz + _binsz*0.5;
else
return _start + b;
}
public long binCount(int b){return _bins[b];}
public double binPercent(int b){return 100*(double)_bins[b]/_n;}
public String toString(){
StringBuilder res = new StringBuilder("ColumnSummary[" + _start + ":" + _end +", binsz=" + _binsz+"]");
if(_percentiles != null) {
for(double d:_percentiles)
res.append(", p("+(int)(100*d)+"%)=" + percentileValue(d));
}
return res.toString();
}
public JsonObject toJson(){
JsonObject res = new JsonObject();
res.addProperty("type", _enum?"enum":"number");
res.addProperty("name", _summary._ary._cols[_colId]._name);
if(!_enum){
JsonArray min = new JsonArray();
for(double d:_min){
if(Double.isInfinite(d))break;
min.add(new JsonPrimitive(d));
}
res.add("min", min);
JsonArray max = new JsonArray();
for(double d:_max){
if(Double.isInfinite(d))break;
max.add(new JsonPrimitive(d));
}
res.add("max", max);
res.addProperty("mean", _summary._ary._cols[_colId]._mean);
res.addProperty("sigma", _summary._ary._cols[_colId]._sigma);
}
res.addProperty("N", _n);
JsonObject histo = new JsonObject();
histo.addProperty("bin_size", _binsz);
JsonArray ary = new JsonArray();
JsonArray binNames = new JsonArray();
if(_summary._ary._cols[_colId].isEnum()){
for(int i = 0; i < _summary._ary._cols[_colId]._domain.length; ++i){
if(_bins[i] != 0){
ary.add(new JsonPrimitive(_bins[i]));
binNames.add(new JsonPrimitive(_summary._ary._cols[_colId]._domain[i]));
}
}
} else {
- double x = _min[0] + _binsz*0.5;
+ double x = _min[0];
+ if(_binsz != 1)x += _binsz*0.5;
for(int i = 0; i < _bins.length; ++i){
if(_bins[i] != 0){
ary.add(new JsonPrimitive(_bins[i]));
binNames.add(new JsonPrimitive(Utils.p2d(x + i*_binsz)));
}
}
}
histo.add("bin_names", binNames);
histo.add("bins", ary);
res.add("histogram", histo);
if(!_enum && _percentiles != null){
if(_percentileValues == null)computePercentiles();
JsonObject percentiles = new JsonObject();
JsonArray thresholds = new JsonArray();
JsonArray values = new JsonArray();
for(int i = 0; i < _percentiles.length; ++i){
thresholds.add(new JsonPrimitive(_percentiles[i]));
values.add(new JsonPrimitive(_percentileValues[i]));
}
percentiles.add("thresholds", thresholds);
percentiles.add("values", values);
res.add("percentiles", percentiles);
}
return res;
}
}
private final ValueArray _ary;
public ValueArray ary(){
return _ary;
}
ColSummary [] _sums;
int [] _cols;
public Summary(ValueArray ary, int [] cols){
assert ary != null;
_ary = ary;
_sums = new ColSummary [cols.length];
_cols = cols;
for(int i = 0; i < cols.length; ++i)
_sums[i] = new ColSummary(this, cols[i]);
}
public Summary add(Summary other){
for(int i = 0; i < _sums.length; ++i)
_sums[i].add(other._sums[i]);
return this;
}
public JsonObject toJson(){
JsonObject res = new JsonObject();
JsonArray sums = new JsonArray();
for(int i = 0; i < _sums.length; ++i){
_sums[i]._summary = this;
sums.add(_sums[i].toJson());
}
res.add("columns",sums);
return res;
}
}
| true | true | public JsonObject toJson(){
JsonObject res = new JsonObject();
res.addProperty("type", _enum?"enum":"number");
res.addProperty("name", _summary._ary._cols[_colId]._name);
if(!_enum){
JsonArray min = new JsonArray();
for(double d:_min){
if(Double.isInfinite(d))break;
min.add(new JsonPrimitive(d));
}
res.add("min", min);
JsonArray max = new JsonArray();
for(double d:_max){
if(Double.isInfinite(d))break;
max.add(new JsonPrimitive(d));
}
res.add("max", max);
res.addProperty("mean", _summary._ary._cols[_colId]._mean);
res.addProperty("sigma", _summary._ary._cols[_colId]._sigma);
}
res.addProperty("N", _n);
JsonObject histo = new JsonObject();
histo.addProperty("bin_size", _binsz);
JsonArray ary = new JsonArray();
JsonArray binNames = new JsonArray();
if(_summary._ary._cols[_colId].isEnum()){
for(int i = 0; i < _summary._ary._cols[_colId]._domain.length; ++i){
if(_bins[i] != 0){
ary.add(new JsonPrimitive(_bins[i]));
binNames.add(new JsonPrimitive(_summary._ary._cols[_colId]._domain[i]));
}
}
} else {
double x = _min[0] + _binsz*0.5;
for(int i = 0; i < _bins.length; ++i){
if(_bins[i] != 0){
ary.add(new JsonPrimitive(_bins[i]));
binNames.add(new JsonPrimitive(Utils.p2d(x + i*_binsz)));
}
}
}
histo.add("bin_names", binNames);
histo.add("bins", ary);
res.add("histogram", histo);
if(!_enum && _percentiles != null){
if(_percentileValues == null)computePercentiles();
JsonObject percentiles = new JsonObject();
JsonArray thresholds = new JsonArray();
JsonArray values = new JsonArray();
for(int i = 0; i < _percentiles.length; ++i){
thresholds.add(new JsonPrimitive(_percentiles[i]));
values.add(new JsonPrimitive(_percentileValues[i]));
}
percentiles.add("thresholds", thresholds);
percentiles.add("values", values);
res.add("percentiles", percentiles);
}
return res;
}
| public JsonObject toJson(){
JsonObject res = new JsonObject();
res.addProperty("type", _enum?"enum":"number");
res.addProperty("name", _summary._ary._cols[_colId]._name);
if(!_enum){
JsonArray min = new JsonArray();
for(double d:_min){
if(Double.isInfinite(d))break;
min.add(new JsonPrimitive(d));
}
res.add("min", min);
JsonArray max = new JsonArray();
for(double d:_max){
if(Double.isInfinite(d))break;
max.add(new JsonPrimitive(d));
}
res.add("max", max);
res.addProperty("mean", _summary._ary._cols[_colId]._mean);
res.addProperty("sigma", _summary._ary._cols[_colId]._sigma);
}
res.addProperty("N", _n);
JsonObject histo = new JsonObject();
histo.addProperty("bin_size", _binsz);
JsonArray ary = new JsonArray();
JsonArray binNames = new JsonArray();
if(_summary._ary._cols[_colId].isEnum()){
for(int i = 0; i < _summary._ary._cols[_colId]._domain.length; ++i){
if(_bins[i] != 0){
ary.add(new JsonPrimitive(_bins[i]));
binNames.add(new JsonPrimitive(_summary._ary._cols[_colId]._domain[i]));
}
}
} else {
double x = _min[0];
if(_binsz != 1)x += _binsz*0.5;
for(int i = 0; i < _bins.length; ++i){
if(_bins[i] != 0){
ary.add(new JsonPrimitive(_bins[i]));
binNames.add(new JsonPrimitive(Utils.p2d(x + i*_binsz)));
}
}
}
histo.add("bin_names", binNames);
histo.add("bins", ary);
res.add("histogram", histo);
if(!_enum && _percentiles != null){
if(_percentileValues == null)computePercentiles();
JsonObject percentiles = new JsonObject();
JsonArray thresholds = new JsonArray();
JsonArray values = new JsonArray();
for(int i = 0; i < _percentiles.length; ++i){
thresholds.add(new JsonPrimitive(_percentiles[i]));
values.add(new JsonPrimitive(_percentileValues[i]));
}
percentiles.add("thresholds", thresholds);
percentiles.add("values", values);
res.add("percentiles", percentiles);
}
return res;
}
|
diff --git a/src/main/ed/js/JSArray.java b/src/main/ed/js/JSArray.java
index f7c4c1a19..4ff794d03 100644
--- a/src/main/ed/js/JSArray.java
+++ b/src/main/ed/js/JSArray.java
@@ -1,1053 +1,1053 @@
// JSArray.java
/**
* Copyright (C) 2008 10gen Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* 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 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 ed.js;
import java.util.*;
import ed.js.func.*;
import ed.js.engine.*;
import static ed.js.JSInternalFunctions.*;
/** @expose
* @anonymous name : {toSource}, desc : {Returns this array serialized as json.}, return : {type : (String), desc : (the array in json form)}
* @anonymous name : {valueOf}, desc : {Returns this array.}, return : {type : (JSArray), desc : (the array)}
* @anonymous name : {reverse}, desc : {Reverses this array in place.}, return : {type : (JSArray), desc : (the reversed array)}
* @anonymous name : {pop}, desc : {Removes the last element of this array and returns it.}, return : {type : (JSObject), desc : (the former last element of the array)}
* @anonymous name : {shift}, desc : {Removes the first element of this array and returns it.}, return : {type : (JSObject), desc : (the former first element of this array)}
* @anonymous name : {join}, desc : {Creates a string from the array using a given delimeter.} param : {type : (String), name : (d), desc : (delimiter to use)}, return : { type : (String), desc : (delimiter-separated string of elements)}
* @anonymous name : {splice}, desc : {Inserts and removes elements from this array in place.}, param : {type : (int), name : (idx), desc : (index at which to start insertion and/or deletion)}, param : { type : (int), name : (num), desc : (number of elements to delete)}, param : {type : (any), name : (elem1 ... elemn), desc : (elements to insert into the array)}, return : {desc : (the deleted elements), type : (Array)}
* @anonymous name : {remove}, desc : {Removes the element at a given index of this array.}, return : { type : (any), desc : (the element removed)}, param : {name : (idx), desc : (index of the element to remove), type : (number)}
* @anonymous name : {push}, desc : {Adds a given object to the end of this array, returning the length of the array.}, return : {type : (number), desc : (the length of this array)}, param : {type : (any), name : (o), desc : (the element to add to the end of this array)}
* @anonymous name : {unshift}, desc : {Adds a given object to the beginning of this array.}, return : { type : (number), desc : (the length of this array)}, param : {type : (any), name : (o), desc : (the element to add to the end of this array)}
* @anonymous name : {concat}, desc : {Adds elements of a given array to this array.}, return : {type : (Array), desc : (the modified array)}, param : {type : (Array), name : (ar), desc : (an array of values to be added)}
* @anonymous name : {filter}, desc : {Returns the elements for which a given function returned true.}, return : {type : (Array), desc : (the elements for which the function returned true)}, param : { type : (function), name : (f), desc : (function to perform on each element)}
* @anonymous name : {reduce}, desc : {Apply a function simultaneously against two values of the array (from left-to-right) as to reduce it to a single value.}, return : {type : (any), desc : (single-value result)}, param : { type : (function), name : (f), desc : (function to perform on each pair of elements)}, param : {name : (initialValue), desc : (value to pass to the function with the first element of the array), type : (any) }
* @anonymous name : {reduceRight}, desc : {Apply a function simultaneously against two values of the array (from right-to-left) as to reduce it to a single value.}, return : {type : (any), desc : (single-value result)}, param : { type : (function), name : (f), desc : (function to perform on each pair of elements)}, param : {name : (initialValue), desc : (value to pass to the function with the last element of the array), type : (any) }
* @anonymous name : {dup}, desc : {Creates a duplicate of this array.}, return : {type : (Array), desc : (a copy of this array)}
* @anonymous name : {forEach}, desc : {Executes a function on each element of this array.}, param : {type : (function), name : (f), desc : (function to perform on each element)}
* @anonymous name : {every}, desc : {Tests whether all elements in the array pass the test implemented by the provided function.}, return : {type : (boolean), desc : (if every element passes)}, param : { type : (function), name : (f), desc : (function to test each element)}
* @anonymous name : {some}, desc : {Tests whether some element in the array passes the test implemented by the provided function.}, return : {type : (boolean), desc : (if there exists an element that passes)}, param : {type : (function), name : (f), desc : (function to test each element)}
* @anonymous name : {collect}, desc : {Creates a new array with the results of calling a provided function on every element in this array.}, return : {type : (Array), desc : (result of running a function on each element)}, param : {type : (function), name : (f), desc : (function to call on each element)}
* @anonymous name : {contains}, desc : {Checks if this array contains a given value.}, return : {type : (boolean), desc : (if this array contains the value)}, param : {type : (any), name : (o), value : (object for which to check)}
* @anonymous name : {indexOf}, desc : {Finds the first occurence of a given object in this array.}, return : {type : (boolean), desc : (the index of the first occurence of this value, or -1)}, param : {type : (any), name : (o), value : (object for which to check)}
* @anonymous name : {lastIndexOf}, desc : {Finds the last occurence of a given object in this array.}, return : {type : (boolean), desc : (the index of the last occurence of this value, or -1)}, param : {type : (any), name : (o), value : (object for which to check)}
* @anonymous name : {sort}, desc : {Sorts the elements of this array, optionally based on a given function. Sorts this array in place. }, return : {type : (Array), desc : (the sorted array)}, param : {type : (function), name : (f), desc : (sorting function taking two parameters and returning 1, 0, or -1.)}
* @anonymous name : {compact}, desc : {Returns this array with any null elements removed. Does not alter this array.}, return : {type : (Array), desc : (array without nulls)}
* @anonymous name : {each}, desc : {Executes a function on each element of this array, breaking if the function returns a false value.}, param : {type : (function), name : (f), desc : (function to perform on each element)}
*
* http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:Array#Iteration_methods
*/
public class JSArray extends JSObjectBase implements Iterable , List {
/** @unexpose */
public final static JSFunction _cons = new JSArrayCons();
static class JSArrayCons extends JSFunctionCalls1{
public JSObject newOne(){
JSArray a = new JSArray();
a._new = true;
return a;
}
public Object call( Scope scope , Object a , Object[] extra ){
int len = 0;
if ( extra == null || extra.length == 0 ){
if ( a instanceof Number )
len = ((Number)a).intValue();
}
else {
len = 1 + extra.length;
}
JSArray arr = null;
Object t = scope.getThis();
if ( t != null && t instanceof JSArray && ((JSArray)t)._new ){
arr = (JSArray)t;
if ( len > 0 )
arr._initSizeSet( len );
arr._new = false;
}
else {
arr = new JSArray( len );
}
if ( ( a != null && ! ( a instanceof Number ) ) ||
( extra != null && extra.length > 0 ) ){
arr.setInt( 0 , a );
if ( extra != null ){
for ( int i=0; i<extra.length; i++)
arr.setInt( 1 + i , extra[i] );
}
}
return arr;
}
protected void init(){
_prototype.set( "toSource" , new JSFunctionCalls0() {
public Object call( Scope s , Object foo[] ){
return new JSString( JSON.serialize( s.getThis() ) );
}
} );
_prototype.set( "valueOf" , new JSFunctionCalls0() {
public Object call( Scope s , Object foo[] ){
return s.getThis();
}
} );
_prototype.set( "reverse" , new JSFunctionCalls0() {
public Object call( Scope s , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
Collections.reverse( a._array );
return a;
}
} );
_prototype.set( "pop" , new JSFunctionCalls0() {
public Object call( Scope s , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
return a._array.remove( a._array.size() - 1 );
}
} );
_prototype.set( "shift" , new JSFunctionCalls0() {
public Object call( Scope s , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
return a._array.remove( 0 );
}
} );
_prototype.set( "join" , new JSFunctionCalls1() {
public Object call( Scope s , Object strJS , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
String str = ",";
if ( strJS != null )
str = strJS.toString();
StringBuilder buf = new StringBuilder();
for ( int i=0; i<a._array.size(); i++ ){
if ( i > 0 )
buf.append( str );
buf.append( a._array.get( i ).toString() );
}
- return buf.toString();
+ return new JSString( buf.toString() );
}
} );
_prototype.set( "splice" , new JSFunctionCalls2() {
public Object call( Scope s , Object startObj , Object numObj , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
JSArray n = new JSArray();
int start = ((Number)startObj).intValue();
int num = numObj == null ? Integer.MAX_VALUE : ((Number)numObj).intValue();
for ( int i=0; i<num && start < a._array.size(); i++ )
n._array.add( a._array.remove( start ) );
if ( foo != null )
for ( int i=0; i<foo.length; i++ )
a._array.add( i + start , foo[i] );
return n;
}
} );
_prototype.set( "slice" , new JSFunctionCalls2() {
public Object call( Scope s , Object startObj , Object numObj , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
JSArray n = new JSArray();
int start = startObj == null ? 0 : ((Number)startObj).intValue();
int end = numObj == null ? Integer.MAX_VALUE : ((Number)numObj).intValue();
if ( end < 0 )
end = a._array.size() + end;
for ( int i=start; i<end && i < a._array.size(); i++ )
n._array.add( a._array.get( i ) );
return n;
}
} );
_prototype.set( "remove" , new JSFunctionCalls1() {
public Object call( Scope s , Object idxObj , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
int idx = ((Number)idxObj).intValue();
if ( idx >= a._array.size() )
return null;
return a._array.remove( idx );
}
} );
_prototype.set( "push" , new JSFunctionCalls1() {
public Object call( Scope s , Object o , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
if ( a == null )
throw new RuntimeException( "this shouldn't be possible. scope id = " + s._id );
a.add( o );
return a.size();
}
} );
_prototype.set( ed.lang.ruby.Ruby.RUBY_SHIFT , _prototype.get( "push" ) );
_prototype.set( "unshift" , new JSFunctionCalls1() {
public Object call( Scope s , Object o , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
if ( a == null )
throw new RuntimeException( "this shouldn't be possible. scope id = " + s._id );
a._array.add( 0 , o );
if ( foo != null )
for ( int i=0; i<foo.length; i++ )
a._array.add( 1 + i , foo[i] );
return a.size();
}
} );
_prototype.set( "__rshift" , new JSFunctionCalls1() {
public Object call( Scope s , Object o , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
if ( a == null )
throw new RuntimeException( "this shouldn't be possible. scope id = " + s._id );
a._array.add( o );
if ( foo != null )
for ( int i=0; i<foo.length; i++ )
a._array.add( foo[i] );
return a;
}
} );
_prototype.set( "concat" , new JSFunctionCalls1() {
public Object call( Scope s , Object o , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
if ( a == null )
throw new RuntimeException( "this shouldn't be possible. scope id = " + s._id );
if ( o == null )
return a;
if ( ! ( o instanceof JSArray ) )
throw new RuntimeException( "trying to concat a non-array");
a = new JSArray( a );
JSArray tempArray = (JSArray)o;
for ( Object temp : tempArray._array )
a.add( temp );
return a;
}
} );
_prototype.set( "filter" , new JSFunctionCalls1() {
public Object call( Scope s , Object fo , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
JSFunction f = (JSFunction)fo;
JSArray n = new JSArray();
for ( Object o : a._array )
if ( JS_evalToBool( f.call( s , o ) ) )
n.add( o );
return n;
}
} );
_prototype.set( "reduce" , new JSFunctionCalls1() {
public Object call( Scope s , Object fo , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
JSFunction f = (JSFunction)fo;
Object val = null;
if ( foo != null && foo.length > 0 )
val = foo[0];
Integer l = a._array.size();
for ( int i=0; i<a._array.size(); i++ ){
val = f.call( s , val , a._array.get(i) , i , l );
}
return val;
}
} );
_prototype.set( "reduceRight" , new JSFunctionCalls1() {
public Object call( Scope s , Object fo , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
JSFunction f = (JSFunction)fo;
Object val = null;
if ( foo != null && foo.length > 0 )
val = foo[0];
Integer l = a._array.size();
for ( int i=a._array.size() -1 ; i >= 0; i-- ){
val = f.call( s , val , a._array.get(i) , i , l );
}
return val;
}
} );
_prototype.set( "unique" , new JSFunctionCalls0() {
public Object call( Scope s , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
JSArray n = new JSArray();
Set seen = new HashSet();
for ( Object o : a._array ){
if ( seen.contains( o ) )
continue;
seen.add( o );
n.add( o );
}
return n;
}
} );
_prototype.set( "dup" , new JSFunctionCalls0() {
public Object call( Scope s , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
return new JSArray( a );
}
} );
_prototype.set( "forEach" , new JSFunctionCalls1() {
public Object call( Scope s , Object fo , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
JSFunction f = (JSFunction)fo;
if ( f == null )
throw new NullPointerException( "forEach needs a function" );
for ( int i=0; i<a._array.size(); i++ )
f.call( s , a._array.get( i ) , i , a._array.size() );
return null;
}
} );
_prototype.set( "every" , new JSFunctionCalls1() {
public Object call( Scope s , Object fo , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
JSFunction f = (JSFunction)fo;
for ( Object o : a._array )
if ( ! JS_evalToBool( f.call( s , o ) ) )
return false;
return true;
}
} );
_prototype.set( "some" , new JSFunctionCalls1() {
public Object call( Scope s , Object fo , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
JSFunction f = (JSFunction)fo;
for ( Object o : a._array )
if ( JS_evalToBool( f.call( s , o ) ) )
return true;
return false;
}
} );
_prototype.set( "map" , new JSFunctionCalls1() {
public Object call( Scope s , Object fo , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
JSFunction f = (JSFunction)fo;
JSArray n = new JSArray();
for ( Object o : a._array )
n.add( fixAndCall( s , f , o ) );
return n;
}
} );
_prototype.set( "collect" , _prototype.get( "map" ) );
_prototype.set( "collect_ex_" , new JSFunctionCalls1() {
public Object call( Scope s , Object fo , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
JSFunction f = (JSFunction)fo;
for ( int i=0; i<a._array.size(); i++ ){
a.set( i , fixAndCall( s , f , a._array.get( i ) ) );
}
return a;
}
} );
_prototype.set( "contains" , new JSFunctionCalls1() {
public Object call( Scope s , Object test , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
for ( Object o : a._array )
if ( JSInternalFunctions.JS_eq( o , test ) )
return true;
return false;
}
} );
_prototype.set( "include_q_" , _prototype.get( "contains" ) );
_prototype.set( "indexOf" , new JSFunctionCalls1() {
public Object call( Scope s , Object test , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
int start = 0;
if ( foo != null && foo.length > 0 && foo[0] instanceof Number )
start = ((Number)foo[0]).intValue();
for ( int i=start; i<a._array.size(); i++ )
if ( JSInternalFunctions.JS_sheq( test , a._array.get( i ) ) )
return i;
return -1;
}
} );
_prototype.set( "lastIndexOf" , new JSFunctionCalls1() {
public Object call( Scope s , Object test , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
int start = a._array.size() - 1 ;
if ( foo != null && foo.length > 0 && foo[0] instanceof Number )
start = ((Number)foo[0]).intValue();
if ( start >= a._array.size() )
start = a._array.size() - 1;
for ( int i=start; i>=0; i-- )
if ( JSInternalFunctions.JS_sheq( test , a._array.get( i ) ) )
return i;
return -1;
}
} );
_prototype.set( "sort" , new JSFunctionCalls1() {
public Object call( Scope s , Object func , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
if ( func == null )
Collections.sort( a._array , _normalComparator );
else
Collections.sort( a._array , new MyComparator( s , (JSFunction)func ) );
return a;
}
} );
/*
ex:
foo = {}
[ 1 , 2, 3 ].__multiAssignment( scope , "a" , foo , "b", q, 3 );
assert( scope.a == 1 )
assert( foo.b == 2 );
assert( q[3] == 3) ;
*/
_prototype.set( "__multiAssignment" , new JSFunctionCalls0() {
public Object call( Scope s , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
if ( foo != null ){
for ( int i=0; i<foo.length-1; i+=2 ){
JSObject obj = (JSObject)foo[i];
obj.set( foo[i+1] , a.get( i / 2 ) );
}
}
return a;
}
} );
_prototype.set( "empty_q_" , new JSFunctionCalls0() {
public Object call( Scope s , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
return a.isEmpty();
}
}
);
_prototype.set( "compact" , new JSFunctionCalls0() {
public Object call( Scope s , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
JSArray n = new JSArray();
for ( Object o : a )
if ( o != null )
n.add( o );
return n;
}
}
);
_prototype.set( "each" , new JSFunctionCalls1(){
public Object call(Scope s, Object funcObject , Object [] args){
if ( funcObject == null )
throw new NullPointerException( "each needs a function" );
JSFunction func = (JSFunction)funcObject;
JSArray a = (JSArray)(s.getThis());
Object blah = s.getParent().getThis();
s.setThis( blah );
Boolean old = func.setUsePassedInScopeTL( true );
for ( int i=0; i<a._array.size(); i++ ){
Object o = a._array.get( i );
Object ret = func.call( s , o );
if ( ret == null )
continue;
if(ret instanceof Number && ((Number)ret).longValue() == -111) {
i--;
continue;
}
if ( JSInternalFunctions.JS_evalToBool( ret ) )
continue;
break;
}
func.setUsePassedInScopeTL( old );
s.clearThisNormal( null );
return null;
}
} );
this.set( "createLinkedList", new JSFunctionCalls0(){
public Object call(Scope s, Object [] extra){
return new JSArray(new LinkedList());
}
} );
}
}
/** Create this array using a variable number of objects passed as arguments.
* @param obj Some number of objects.
* @return Newly created array.
*/
public static JSArray create( Object ... obj ){
return new JSArray( obj );
}
/** Create an empty array.
* The array is initialized with space for 16 elements.
*/
public JSArray(){
this( 0 );
}
/** Create an empty array with a given allocation.
* @param init The initial allocation for the array. The minimum possible value is 16.
*/
public JSArray( int init ){
super( _cons );
_array = new ArrayList( Math.max( 16 , init ) );
_initSizeSet( init );
}
private void _initSizeSet( int init ){
for ( int i=0; i<init; i++ )
_array.add( null );
}
/** Create an array and fill with objects
* @param obj A variable number of objects
*/
public JSArray( Object ... obj ){
super( _cons );
if ( obj == null ){
_array = new ArrayList();
}
else {
_array = new ArrayList( obj.length );
for ( Object o : obj )
_array.add( o );
}
}
/** Create an array that is the copy of an existing array.
* @param a A JavaScript array.
*/
public JSArray( JSArray a ){
super( _cons );
_array = a == null ? new ArrayList() : new ArrayList( a._array );
}
/** Create an array from an existing Java List object.
* @param lst A Java List object
*/
public JSArray( List lst ){
super( _cons );
_array = lst == null ? new ArrayList() : lst;
}
/** Set an element at a specified index to a given value.
* If <tt>pos</tt> exceeds the length of this array, this array's size is increased to <tt>pos</tt>+1 and the elements between
* the original end of this array and the inserted element are set to <tt>null</tt>.
* @param pos The index of the element.
* @param v The object to replace the element at position <tt>pos</tt>.
* @return The inserted object, <tt>v</tt>.
*/
public Object setInt( int pos , Object v ){
while ( _array.size() <= pos )
_array.add( null );
_array.set( pos , v );
return v;
}
/** Return the element at position <tt>pos</tt>.
* If <tt>pos</tt> is greater than the length of this array, return null.
* @param pos The index of the element to return.
* @return The element at the specified position in this array.
*/
public Object getInt( int pos ){
if ( pos >= _array.size() ){
return null;
}
return _array.get( pos );
}
/** Returns the number of elements in this list.
* @return The number of elements in this list.
*/
public int size(){
return _array.size();
}
/** Return the element at position <tt>n</tt>.
* If <tt>n</tt> is greater than the length of this array, return null.
* @param n The index of the element to return.
* @return The element at the specified position in this array.
*/
public Object get( Object n ){
if ( n != null )
if ( n instanceof JSString || n instanceof String )
if ( n.toString().equals( "length" ) )
return _array.size();
int idx = _getInt( n );
if ( idx >=0 )
return getInt( idx );
return super.get( n );
}
/** Set an element at a specified index to a given value.
* If <tt>n.toString()</tt> is equal to "", <tt>v</tt> is pushed onto the end of this array.
* If <tt>n</tt> exceeds the length of this array, this array's size is increased to <tt>n</tt>+1 and the elements between
* the original end of this array and the inserted element are set to <tt>null</tt>.
* @param n The index of the element.
* @param v The object to replace the element at position <tt>n</tt>.
* @return The inserted object, <tt>v</tt>.
*/
public Object set( Object n , Object v ){
if ( n.toString().equals( "" ) ){
_array.add( v );
return v;
}
int idx = _getInt( n );
if ( idx < 0 )
return super.set( n , v );
return setInt( idx , v );
}
/** Returns an array of the indices for this array.
* @return The indices for this array.
*/
public Collection<String> keySet(){
Collection<String> p = super.keySet();
List<String> keys = new ArrayList<String>( p.size() + _array.size() );
for ( int i=0; i<_array.size(); i++ )
keys.add( String.valueOf( i ) );
keys.addAll( p );
keys.remove( "_dbCons" );
return keys;
}
/** If this array contains a certain key.
* @param s The key to check.
* @return If this array contains the key <tt>s</tt>.
*/
@Override
public boolean containsKey(String s) {
return "length".equals(s) || super.containsKey(s);
}
/** Return a comma-separated list of array elements converted to strings.
* @return A comma-separated list of array elements.
*/
public String toString(){
StringBuilder buf = new StringBuilder();
for ( int i=0; i<_array.size(); i++ ){
if ( i > 0 )
buf.append( "," );
Object val = _array.get( i );
buf.append( val == null ? "" : JSInternalFunctions.JS_toString( val ) );
}
return buf.toString();
}
/** Add an object to the end of this array.
* @param o Object to be added.
* @return true
*/
public boolean add( Object o ){
if ( _locked )
throw new RuntimeException( "array locked" );
return _array.add( o );
}
/** Inserts the specified element at the specified position in this array. Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices).
* @param o Object to be added.
* @return true
*/
public void add( int index , Object o ){
if ( _locked )
throw new RuntimeException( "array locked" );
_array.add( index , o );
}
/** Replaces the element at the specified position in this array with the specified element.
* @param index The index of the element.
* @param o The object to replace the element at position <tt>index</tt>.
* @return The element previously at the specified position.
*/
public Object set( int index , Object o ){
if ( _locked )
throw new RuntimeException( "array locked" );
return _array.set( index , o );
}
/** Returns the element at the specified position in this array.
* @param i Index of element to return.
* @return The element at the specified position in this array.
*/
public Object get( int i ){
if ( i >= _array.size() )
return null;
return _array.get( i );
}
/** Append all of the elements of a collection to this array.
* @param c Collection to be appended.
* @return If the array changed.
*/
public boolean addAll( Collection c ){
if ( _locked )
throw new RuntimeException( "array locked" );
return _array.addAll( c );
}
/** Add all of the elements of a collection starting at a specified index of this array, shifting subsequent elements (if any) to the right.
* @param idx Index to begin insertion.
* @param c Collection to be added.
* @return If the array changed.
*/
public boolean addAll( int idx , Collection c ){
if ( _locked )
throw new RuntimeException( "array locked" );
return _array.addAll( idx , c );
}
/** Returns true if this array contains all of the elements of the specified collection.
* @param c Collection to be tested.
* @return true if this array contains all of the elements of the specified collection.
*/
public boolean containsAll( Collection c ){
return _array.containsAll( c );
}
/** Returns a view of the portion of this array between fromIndex, inclusive, and toIndex, exclusive.
* @param start Starting index.
* @param end Ending index.
* @return A view of the specified range within this array.
*/
public List subList( int start , int end ){
return _array.subList( start , end );
}
/** Returns an iterator of the elements in this array.
* @return An iterator of the elements in this array.
*/
public ListIterator listIterator(){
return _array.listIterator();
}
/** Returns a array iterator of the elements in this array, starting at the specified position in the array.
* @param index The index at which to start the iterator.
* @return An iterator of the elements in this array, starting at <tt>index</tt>.
*/
public ListIterator listIterator( int index ){
return _array.listIterator( index );
}
/** Returns the index of the last occurrence of the specified object in this array.
* @param foo Object for which to search.
* @return Last index at which <tt>foo</tt> was found or -1.
*/
public int lastIndexOf( Object foo ){
return _array.lastIndexOf( foo );
}
/** Returns the index of the first occurrence of the specified object in this array.
* @param foo Object for which to search.
* @return First index at which <tt>foo</tt> was found or -1.
*/
public int indexOf( Object foo ){
return _array.indexOf( foo );
}
/** Returns true if this array contains the specified element.
* @param foo Object for which to search.
* @return If the object was found in this array.
*/
public boolean contains( Object foo ){
for ( int i=0; i<_array.size(); i++ ){
Object o = _array.get(i);
if ( o != null && o.equals( foo ) )
return true;
}
return false;
}
/** Tests if this array has no elements.
* @return If the array has no elements.
*/
public boolean isEmpty(){
return _array.isEmpty();
}
/** Remove an element at a specified position. Shifts any subsequent elements left.
* @param i Index at which element should be removed.
* @return The element that was removed from the array.
*/
public Object remove( int i ){
if ( _locked )
throw new RuntimeException( "array locked" );
return _array.remove( i );
}
/** Removes a single instance of the specified element from this array. Shifts any subsequent elements left.
* @param o Object to be removed.
* @return If the array contained the given element.
*/
public boolean remove( Object o ){
if ( _locked )
throw new RuntimeException( "array locked" );
return _array.remove( o );
}
/** Returns an iterator over the elements in this list in proper sequence.
* @return An iterator over the elements in this list in proper sequence.
*/
public Iterator iterator(){
return _array.iterator();
}
/** Retains only the elements in this collection that are contained in the specified collection. In other words, returns the intersection of this array and the given collection.
* @param c Collection with which to intersect the array.
* @return true if this collection changed as a result of the call.
* @throws RuntimeException All the time... this method is not yet implemented.
*/
public boolean retainAll( Collection c ){
throw new RuntimeException( "not implemented" );
}
/** Removes from this list all the elements that are contained in the specified collection.
* @param c Collection of elements to be removed.
* @return true if this list changed as a result of the call.
*/
public boolean removeAll( Collection c ){
boolean removedAny = false;
for ( Object o : c ){
removedAny = remove( o ) || removedAny;
}
return removedAny;
}
/** Converts this array to a Java array of objects. No effect from JavaScript.
* @return Java Object array.
*/
public Object[] toArray(){
return _array.toArray();
}
/** Returns an array containing all of the elements in this list in the correct order; the runtime type of the returned array is that of the specified array. If the list fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this list.
* If the list fits in the specified array with room to spare (i.e., the array has more elements than the list), the element in the array immediately following the end of the collection is set to null. This is useful in determining the length of the list only if the caller knows that the list does not contain any null elements.
* @return Java Object array.
*/
public Object[] toArray( Object[] o ){
return _array.toArray( o );
}
/** @unexpose */
int _getInt( Object o ){
if ( o == null )
return -1;
if ( o instanceof Number )
return ((Number)o).intValue();
if ( o instanceof JSString )
o = o.toString();
if ( ! ( o instanceof String ) )
return -1;
String str = o.toString();
for ( int i=0; i<str.length(); i++ )
if ( ! Character.isDigit( str.charAt( i ) ) )
return -1;
return Integer.parseInt( str );
}
/** Randomly permutes this array using a default source of randomness. All permutations occur with approximately equal likelihood.
* @return This array.
*/
public JSArray shuffle(){
Collections.shuffle( _array );
return this;
}
/** Make this array mostly immutable. */
public void lock(){
_locked = true;
}
/** Remove all array elements. */
public void clear(){
_array.clear();
}
/** Return if the array is locked.
* @return If the array is locked.
*/
public boolean isLocked(){
return _locked;
}
/** Return array getter of a given name
* @param name Getter name.
* @return null
*/
JSFunction getGetter( String name ){
return null;
}
/** Return array setter of a given name
* @param name Setter name.
* @return null
*/
JSFunction getSetter( String name ){
return null;
}
/** Call a function on an array in a specified scope.
* @param s Scope to use.
* @param f Function to call.
* @param o Array to pass to function.
* @return The return value of the function.
*/
public static Object fixAndCall( Scope s , JSFunction f , Object o ){
if ( false ){
System.out.println( "ruby:" + s.isRuby() );
System.out.println( "params: " + f.getNumParameters() );
System.out.println( "thing:" + o.getClass() );
}
if ( s.isRuby() && f.getNumParameters() > 1 && o instanceof JSArray )
return f.call( s , ((JSArray)o).toArray() );
return f.call( s , o );
}
/** The hash code value of this array.
* @return The hash code value of this array.
*/
public int hashCode(){
int hash = super.hashCode();
if ( _array != null ){
hash += _array.hashCode();
}
return hash;
}
private boolean _locked = false;
private boolean _new = false;
/** @unexpose */
final List<Object> _array;
static class MyComparator implements Comparator {
MyComparator( Scope s , JSFunction func ){
_scope = s;
_func = func;
}
public int compare( Object l , Object r ){
if ( _func == null ){
if ( l == null && r == null )
return 0;
if ( l == null )
return 1;
if ( r == null )
return -1;
return l.toString().compareTo( r.toString() );
}
return ((Number)(_func.call( _scope , l , r , null ))).intValue();
}
private final Scope _scope;
private final JSFunction _func;
}
static final MyComparator _normalComparator = new MyComparator( null , null );
}
| true | true | protected void init(){
_prototype.set( "toSource" , new JSFunctionCalls0() {
public Object call( Scope s , Object foo[] ){
return new JSString( JSON.serialize( s.getThis() ) );
}
} );
_prototype.set( "valueOf" , new JSFunctionCalls0() {
public Object call( Scope s , Object foo[] ){
return s.getThis();
}
} );
_prototype.set( "reverse" , new JSFunctionCalls0() {
public Object call( Scope s , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
Collections.reverse( a._array );
return a;
}
} );
_prototype.set( "pop" , new JSFunctionCalls0() {
public Object call( Scope s , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
return a._array.remove( a._array.size() - 1 );
}
} );
_prototype.set( "shift" , new JSFunctionCalls0() {
public Object call( Scope s , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
return a._array.remove( 0 );
}
} );
_prototype.set( "join" , new JSFunctionCalls1() {
public Object call( Scope s , Object strJS , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
String str = ",";
if ( strJS != null )
str = strJS.toString();
StringBuilder buf = new StringBuilder();
for ( int i=0; i<a._array.size(); i++ ){
if ( i > 0 )
buf.append( str );
buf.append( a._array.get( i ).toString() );
}
return buf.toString();
}
} );
_prototype.set( "splice" , new JSFunctionCalls2() {
public Object call( Scope s , Object startObj , Object numObj , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
JSArray n = new JSArray();
int start = ((Number)startObj).intValue();
int num = numObj == null ? Integer.MAX_VALUE : ((Number)numObj).intValue();
for ( int i=0; i<num && start < a._array.size(); i++ )
n._array.add( a._array.remove( start ) );
if ( foo != null )
for ( int i=0; i<foo.length; i++ )
a._array.add( i + start , foo[i] );
return n;
}
} );
_prototype.set( "slice" , new JSFunctionCalls2() {
public Object call( Scope s , Object startObj , Object numObj , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
JSArray n = new JSArray();
int start = startObj == null ? 0 : ((Number)startObj).intValue();
int end = numObj == null ? Integer.MAX_VALUE : ((Number)numObj).intValue();
if ( end < 0 )
end = a._array.size() + end;
for ( int i=start; i<end && i < a._array.size(); i++ )
n._array.add( a._array.get( i ) );
return n;
}
} );
_prototype.set( "remove" , new JSFunctionCalls1() {
public Object call( Scope s , Object idxObj , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
int idx = ((Number)idxObj).intValue();
if ( idx >= a._array.size() )
return null;
return a._array.remove( idx );
}
} );
_prototype.set( "push" , new JSFunctionCalls1() {
public Object call( Scope s , Object o , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
if ( a == null )
throw new RuntimeException( "this shouldn't be possible. scope id = " + s._id );
a.add( o );
return a.size();
}
} );
_prototype.set( ed.lang.ruby.Ruby.RUBY_SHIFT , _prototype.get( "push" ) );
_prototype.set( "unshift" , new JSFunctionCalls1() {
public Object call( Scope s , Object o , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
if ( a == null )
throw new RuntimeException( "this shouldn't be possible. scope id = " + s._id );
a._array.add( 0 , o );
if ( foo != null )
for ( int i=0; i<foo.length; i++ )
a._array.add( 1 + i , foo[i] );
return a.size();
}
} );
_prototype.set( "__rshift" , new JSFunctionCalls1() {
public Object call( Scope s , Object o , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
if ( a == null )
throw new RuntimeException( "this shouldn't be possible. scope id = " + s._id );
a._array.add( o );
if ( foo != null )
for ( int i=0; i<foo.length; i++ )
a._array.add( foo[i] );
return a;
}
} );
_prototype.set( "concat" , new JSFunctionCalls1() {
public Object call( Scope s , Object o , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
if ( a == null )
throw new RuntimeException( "this shouldn't be possible. scope id = " + s._id );
if ( o == null )
return a;
if ( ! ( o instanceof JSArray ) )
throw new RuntimeException( "trying to concat a non-array");
a = new JSArray( a );
JSArray tempArray = (JSArray)o;
for ( Object temp : tempArray._array )
a.add( temp );
return a;
}
} );
_prototype.set( "filter" , new JSFunctionCalls1() {
public Object call( Scope s , Object fo , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
JSFunction f = (JSFunction)fo;
JSArray n = new JSArray();
for ( Object o : a._array )
if ( JS_evalToBool( f.call( s , o ) ) )
n.add( o );
return n;
}
} );
_prototype.set( "reduce" , new JSFunctionCalls1() {
public Object call( Scope s , Object fo , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
JSFunction f = (JSFunction)fo;
Object val = null;
if ( foo != null && foo.length > 0 )
val = foo[0];
Integer l = a._array.size();
for ( int i=0; i<a._array.size(); i++ ){
val = f.call( s , val , a._array.get(i) , i , l );
}
return val;
}
} );
_prototype.set( "reduceRight" , new JSFunctionCalls1() {
public Object call( Scope s , Object fo , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
JSFunction f = (JSFunction)fo;
Object val = null;
if ( foo != null && foo.length > 0 )
val = foo[0];
Integer l = a._array.size();
for ( int i=a._array.size() -1 ; i >= 0; i-- ){
val = f.call( s , val , a._array.get(i) , i , l );
}
return val;
}
} );
_prototype.set( "unique" , new JSFunctionCalls0() {
public Object call( Scope s , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
JSArray n = new JSArray();
Set seen = new HashSet();
for ( Object o : a._array ){
if ( seen.contains( o ) )
continue;
seen.add( o );
n.add( o );
}
return n;
}
} );
_prototype.set( "dup" , new JSFunctionCalls0() {
public Object call( Scope s , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
return new JSArray( a );
}
} );
_prototype.set( "forEach" , new JSFunctionCalls1() {
public Object call( Scope s , Object fo , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
JSFunction f = (JSFunction)fo;
if ( f == null )
throw new NullPointerException( "forEach needs a function" );
for ( int i=0; i<a._array.size(); i++ )
f.call( s , a._array.get( i ) , i , a._array.size() );
return null;
}
} );
_prototype.set( "every" , new JSFunctionCalls1() {
public Object call( Scope s , Object fo , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
JSFunction f = (JSFunction)fo;
for ( Object o : a._array )
if ( ! JS_evalToBool( f.call( s , o ) ) )
return false;
return true;
}
} );
_prototype.set( "some" , new JSFunctionCalls1() {
public Object call( Scope s , Object fo , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
JSFunction f = (JSFunction)fo;
for ( Object o : a._array )
if ( JS_evalToBool( f.call( s , o ) ) )
return true;
return false;
}
} );
_prototype.set( "map" , new JSFunctionCalls1() {
public Object call( Scope s , Object fo , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
JSFunction f = (JSFunction)fo;
JSArray n = new JSArray();
for ( Object o : a._array )
n.add( fixAndCall( s , f , o ) );
return n;
}
} );
_prototype.set( "collect" , _prototype.get( "map" ) );
_prototype.set( "collect_ex_" , new JSFunctionCalls1() {
public Object call( Scope s , Object fo , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
JSFunction f = (JSFunction)fo;
for ( int i=0; i<a._array.size(); i++ ){
a.set( i , fixAndCall( s , f , a._array.get( i ) ) );
}
return a;
}
} );
_prototype.set( "contains" , new JSFunctionCalls1() {
public Object call( Scope s , Object test , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
for ( Object o : a._array )
if ( JSInternalFunctions.JS_eq( o , test ) )
return true;
return false;
}
} );
_prototype.set( "include_q_" , _prototype.get( "contains" ) );
_prototype.set( "indexOf" , new JSFunctionCalls1() {
public Object call( Scope s , Object test , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
int start = 0;
if ( foo != null && foo.length > 0 && foo[0] instanceof Number )
start = ((Number)foo[0]).intValue();
for ( int i=start; i<a._array.size(); i++ )
if ( JSInternalFunctions.JS_sheq( test , a._array.get( i ) ) )
return i;
return -1;
}
} );
_prototype.set( "lastIndexOf" , new JSFunctionCalls1() {
public Object call( Scope s , Object test , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
int start = a._array.size() - 1 ;
if ( foo != null && foo.length > 0 && foo[0] instanceof Number )
start = ((Number)foo[0]).intValue();
if ( start >= a._array.size() )
start = a._array.size() - 1;
for ( int i=start; i>=0; i-- )
if ( JSInternalFunctions.JS_sheq( test , a._array.get( i ) ) )
return i;
return -1;
}
} );
_prototype.set( "sort" , new JSFunctionCalls1() {
public Object call( Scope s , Object func , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
if ( func == null )
Collections.sort( a._array , _normalComparator );
else
Collections.sort( a._array , new MyComparator( s , (JSFunction)func ) );
return a;
}
} );
/*
ex:
foo = {}
[ 1 , 2, 3 ].__multiAssignment( scope , "a" , foo , "b", q, 3 );
assert( scope.a == 1 )
assert( foo.b == 2 );
assert( q[3] == 3) ;
*/
_prototype.set( "__multiAssignment" , new JSFunctionCalls0() {
public Object call( Scope s , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
if ( foo != null ){
for ( int i=0; i<foo.length-1; i+=2 ){
JSObject obj = (JSObject)foo[i];
obj.set( foo[i+1] , a.get( i / 2 ) );
}
}
return a;
}
} );
_prototype.set( "empty_q_" , new JSFunctionCalls0() {
public Object call( Scope s , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
return a.isEmpty();
}
}
);
_prototype.set( "compact" , new JSFunctionCalls0() {
public Object call( Scope s , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
JSArray n = new JSArray();
for ( Object o : a )
if ( o != null )
n.add( o );
return n;
}
}
);
_prototype.set( "each" , new JSFunctionCalls1(){
public Object call(Scope s, Object funcObject , Object [] args){
if ( funcObject == null )
throw new NullPointerException( "each needs a function" );
JSFunction func = (JSFunction)funcObject;
JSArray a = (JSArray)(s.getThis());
Object blah = s.getParent().getThis();
s.setThis( blah );
Boolean old = func.setUsePassedInScopeTL( true );
for ( int i=0; i<a._array.size(); i++ ){
Object o = a._array.get( i );
Object ret = func.call( s , o );
if ( ret == null )
continue;
if(ret instanceof Number && ((Number)ret).longValue() == -111) {
i--;
continue;
}
if ( JSInternalFunctions.JS_evalToBool( ret ) )
continue;
break;
}
func.setUsePassedInScopeTL( old );
s.clearThisNormal( null );
return null;
}
} );
this.set( "createLinkedList", new JSFunctionCalls0(){
public Object call(Scope s, Object [] extra){
return new JSArray(new LinkedList());
}
} );
}
| protected void init(){
_prototype.set( "toSource" , new JSFunctionCalls0() {
public Object call( Scope s , Object foo[] ){
return new JSString( JSON.serialize( s.getThis() ) );
}
} );
_prototype.set( "valueOf" , new JSFunctionCalls0() {
public Object call( Scope s , Object foo[] ){
return s.getThis();
}
} );
_prototype.set( "reverse" , new JSFunctionCalls0() {
public Object call( Scope s , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
Collections.reverse( a._array );
return a;
}
} );
_prototype.set( "pop" , new JSFunctionCalls0() {
public Object call( Scope s , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
return a._array.remove( a._array.size() - 1 );
}
} );
_prototype.set( "shift" , new JSFunctionCalls0() {
public Object call( Scope s , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
return a._array.remove( 0 );
}
} );
_prototype.set( "join" , new JSFunctionCalls1() {
public Object call( Scope s , Object strJS , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
String str = ",";
if ( strJS != null )
str = strJS.toString();
StringBuilder buf = new StringBuilder();
for ( int i=0; i<a._array.size(); i++ ){
if ( i > 0 )
buf.append( str );
buf.append( a._array.get( i ).toString() );
}
return new JSString( buf.toString() );
}
} );
_prototype.set( "splice" , new JSFunctionCalls2() {
public Object call( Scope s , Object startObj , Object numObj , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
JSArray n = new JSArray();
int start = ((Number)startObj).intValue();
int num = numObj == null ? Integer.MAX_VALUE : ((Number)numObj).intValue();
for ( int i=0; i<num && start < a._array.size(); i++ )
n._array.add( a._array.remove( start ) );
if ( foo != null )
for ( int i=0; i<foo.length; i++ )
a._array.add( i + start , foo[i] );
return n;
}
} );
_prototype.set( "slice" , new JSFunctionCalls2() {
public Object call( Scope s , Object startObj , Object numObj , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
JSArray n = new JSArray();
int start = startObj == null ? 0 : ((Number)startObj).intValue();
int end = numObj == null ? Integer.MAX_VALUE : ((Number)numObj).intValue();
if ( end < 0 )
end = a._array.size() + end;
for ( int i=start; i<end && i < a._array.size(); i++ )
n._array.add( a._array.get( i ) );
return n;
}
} );
_prototype.set( "remove" , new JSFunctionCalls1() {
public Object call( Scope s , Object idxObj , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
int idx = ((Number)idxObj).intValue();
if ( idx >= a._array.size() )
return null;
return a._array.remove( idx );
}
} );
_prototype.set( "push" , new JSFunctionCalls1() {
public Object call( Scope s , Object o , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
if ( a == null )
throw new RuntimeException( "this shouldn't be possible. scope id = " + s._id );
a.add( o );
return a.size();
}
} );
_prototype.set( ed.lang.ruby.Ruby.RUBY_SHIFT , _prototype.get( "push" ) );
_prototype.set( "unshift" , new JSFunctionCalls1() {
public Object call( Scope s , Object o , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
if ( a == null )
throw new RuntimeException( "this shouldn't be possible. scope id = " + s._id );
a._array.add( 0 , o );
if ( foo != null )
for ( int i=0; i<foo.length; i++ )
a._array.add( 1 + i , foo[i] );
return a.size();
}
} );
_prototype.set( "__rshift" , new JSFunctionCalls1() {
public Object call( Scope s , Object o , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
if ( a == null )
throw new RuntimeException( "this shouldn't be possible. scope id = " + s._id );
a._array.add( o );
if ( foo != null )
for ( int i=0; i<foo.length; i++ )
a._array.add( foo[i] );
return a;
}
} );
_prototype.set( "concat" , new JSFunctionCalls1() {
public Object call( Scope s , Object o , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
if ( a == null )
throw new RuntimeException( "this shouldn't be possible. scope id = " + s._id );
if ( o == null )
return a;
if ( ! ( o instanceof JSArray ) )
throw new RuntimeException( "trying to concat a non-array");
a = new JSArray( a );
JSArray tempArray = (JSArray)o;
for ( Object temp : tempArray._array )
a.add( temp );
return a;
}
} );
_prototype.set( "filter" , new JSFunctionCalls1() {
public Object call( Scope s , Object fo , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
JSFunction f = (JSFunction)fo;
JSArray n = new JSArray();
for ( Object o : a._array )
if ( JS_evalToBool( f.call( s , o ) ) )
n.add( o );
return n;
}
} );
_prototype.set( "reduce" , new JSFunctionCalls1() {
public Object call( Scope s , Object fo , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
JSFunction f = (JSFunction)fo;
Object val = null;
if ( foo != null && foo.length > 0 )
val = foo[0];
Integer l = a._array.size();
for ( int i=0; i<a._array.size(); i++ ){
val = f.call( s , val , a._array.get(i) , i , l );
}
return val;
}
} );
_prototype.set( "reduceRight" , new JSFunctionCalls1() {
public Object call( Scope s , Object fo , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
JSFunction f = (JSFunction)fo;
Object val = null;
if ( foo != null && foo.length > 0 )
val = foo[0];
Integer l = a._array.size();
for ( int i=a._array.size() -1 ; i >= 0; i-- ){
val = f.call( s , val , a._array.get(i) , i , l );
}
return val;
}
} );
_prototype.set( "unique" , new JSFunctionCalls0() {
public Object call( Scope s , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
JSArray n = new JSArray();
Set seen = new HashSet();
for ( Object o : a._array ){
if ( seen.contains( o ) )
continue;
seen.add( o );
n.add( o );
}
return n;
}
} );
_prototype.set( "dup" , new JSFunctionCalls0() {
public Object call( Scope s , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
return new JSArray( a );
}
} );
_prototype.set( "forEach" , new JSFunctionCalls1() {
public Object call( Scope s , Object fo , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
JSFunction f = (JSFunction)fo;
if ( f == null )
throw new NullPointerException( "forEach needs a function" );
for ( int i=0; i<a._array.size(); i++ )
f.call( s , a._array.get( i ) , i , a._array.size() );
return null;
}
} );
_prototype.set( "every" , new JSFunctionCalls1() {
public Object call( Scope s , Object fo , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
JSFunction f = (JSFunction)fo;
for ( Object o : a._array )
if ( ! JS_evalToBool( f.call( s , o ) ) )
return false;
return true;
}
} );
_prototype.set( "some" , new JSFunctionCalls1() {
public Object call( Scope s , Object fo , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
JSFunction f = (JSFunction)fo;
for ( Object o : a._array )
if ( JS_evalToBool( f.call( s , o ) ) )
return true;
return false;
}
} );
_prototype.set( "map" , new JSFunctionCalls1() {
public Object call( Scope s , Object fo , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
JSFunction f = (JSFunction)fo;
JSArray n = new JSArray();
for ( Object o : a._array )
n.add( fixAndCall( s , f , o ) );
return n;
}
} );
_prototype.set( "collect" , _prototype.get( "map" ) );
_prototype.set( "collect_ex_" , new JSFunctionCalls1() {
public Object call( Scope s , Object fo , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
JSFunction f = (JSFunction)fo;
for ( int i=0; i<a._array.size(); i++ ){
a.set( i , fixAndCall( s , f , a._array.get( i ) ) );
}
return a;
}
} );
_prototype.set( "contains" , new JSFunctionCalls1() {
public Object call( Scope s , Object test , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
for ( Object o : a._array )
if ( JSInternalFunctions.JS_eq( o , test ) )
return true;
return false;
}
} );
_prototype.set( "include_q_" , _prototype.get( "contains" ) );
_prototype.set( "indexOf" , new JSFunctionCalls1() {
public Object call( Scope s , Object test , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
int start = 0;
if ( foo != null && foo.length > 0 && foo[0] instanceof Number )
start = ((Number)foo[0]).intValue();
for ( int i=start; i<a._array.size(); i++ )
if ( JSInternalFunctions.JS_sheq( test , a._array.get( i ) ) )
return i;
return -1;
}
} );
_prototype.set( "lastIndexOf" , new JSFunctionCalls1() {
public Object call( Scope s , Object test , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
int start = a._array.size() - 1 ;
if ( foo != null && foo.length > 0 && foo[0] instanceof Number )
start = ((Number)foo[0]).intValue();
if ( start >= a._array.size() )
start = a._array.size() - 1;
for ( int i=start; i>=0; i-- )
if ( JSInternalFunctions.JS_sheq( test , a._array.get( i ) ) )
return i;
return -1;
}
} );
_prototype.set( "sort" , new JSFunctionCalls1() {
public Object call( Scope s , Object func , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
if ( func == null )
Collections.sort( a._array , _normalComparator );
else
Collections.sort( a._array , new MyComparator( s , (JSFunction)func ) );
return a;
}
} );
/*
ex:
foo = {}
[ 1 , 2, 3 ].__multiAssignment( scope , "a" , foo , "b", q, 3 );
assert( scope.a == 1 )
assert( foo.b == 2 );
assert( q[3] == 3) ;
*/
_prototype.set( "__multiAssignment" , new JSFunctionCalls0() {
public Object call( Scope s , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
if ( foo != null ){
for ( int i=0; i<foo.length-1; i+=2 ){
JSObject obj = (JSObject)foo[i];
obj.set( foo[i+1] , a.get( i / 2 ) );
}
}
return a;
}
} );
_prototype.set( "empty_q_" , new JSFunctionCalls0() {
public Object call( Scope s , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
return a.isEmpty();
}
}
);
_prototype.set( "compact" , new JSFunctionCalls0() {
public Object call( Scope s , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
JSArray n = new JSArray();
for ( Object o : a )
if ( o != null )
n.add( o );
return n;
}
}
);
_prototype.set( "each" , new JSFunctionCalls1(){
public Object call(Scope s, Object funcObject , Object [] args){
if ( funcObject == null )
throw new NullPointerException( "each needs a function" );
JSFunction func = (JSFunction)funcObject;
JSArray a = (JSArray)(s.getThis());
Object blah = s.getParent().getThis();
s.setThis( blah );
Boolean old = func.setUsePassedInScopeTL( true );
for ( int i=0; i<a._array.size(); i++ ){
Object o = a._array.get( i );
Object ret = func.call( s , o );
if ( ret == null )
continue;
if(ret instanceof Number && ((Number)ret).longValue() == -111) {
i--;
continue;
}
if ( JSInternalFunctions.JS_evalToBool( ret ) )
continue;
break;
}
func.setUsePassedInScopeTL( old );
s.clearThisNormal( null );
return null;
}
} );
this.set( "createLinkedList", new JSFunctionCalls0(){
public Object call(Scope s, Object [] extra){
return new JSArray(new LinkedList());
}
} );
}
|
diff --git a/src/community/web2/core/src/main/java/org/geoserver/web/wicket/GeoServerTablePanel.java b/src/community/web2/core/src/main/java/org/geoserver/web/wicket/GeoServerTablePanel.java
index d785d88a79..a6b054ca5b 100644
--- a/src/community/web2/core/src/main/java/org/geoserver/web/wicket/GeoServerTablePanel.java
+++ b/src/community/web2/core/src/main/java/org/geoserver/web/wicket/GeoServerTablePanel.java
@@ -1,500 +1,500 @@
/* Copyright (c) 2001 - 2007 TOPP - www.openplans.org. All rights reserved.
* This code is licensed under the GPL 2.0 license, available at the root
* application directory.
*/
package org.geoserver.web.wicket;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.wicket.Component;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.ajax.markup.html.form.AjaxButton;
import org.apache.wicket.behavior.SimpleAttributeModifier;
import org.apache.wicket.extensions.markup.html.repeater.util.SortParam;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.CheckBox;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.markup.html.panel.Fragment;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.markup.repeater.Item;
import org.apache.wicket.markup.repeater.data.DataView;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.model.ResourceModel;
import org.geoserver.web.wicket.GeoServerDataProvider.Property;
/**
* An abstract filterable, sortable, pageable table with associated filtering form and paging
* navigator.
* <p>
* The construction of the page is driven by the properties returned by a
* {@link GeoServerDataProvider}, subclasses only need to build a component for each property by
* implementing the {@link #getComponentForProperty(String, IModel, Property)} method
*
* @param <T>
*/
@SuppressWarnings("serial")
public abstract class GeoServerTablePanel<T> extends Panel {
private static final int DEFAULT_ITEMS_PER_PAGE = 25;
// filter form components
TextField filter;
// table components
DataView dataView;
WebMarkupContainer listContainer;
Pager navigatorTop;
Pager navigatorBottom;
GeoServerDataProvider<T> dataProvider;
Form filterForm;
CheckBox selectAll;
AjaxButton hiddenSubmit;
/**
* An array of the selected items in the current page. Gets wiped out each
* time the current page, the sorting or the filtering changes.
*/
boolean[] selection;
boolean selectAllValue;
/**
* Builds a non selectable table
*/
public GeoServerTablePanel(final String id, final GeoServerDataProvider<T> dataProvider) {
this(id, dataProvider, false);
}
/**
* Builds a new table panel
*/
public GeoServerTablePanel(final String id, final GeoServerDataProvider<T> dataProvider,
final boolean selectable) {
super(id);
this.dataProvider = dataProvider;
// prepare the selection array
selection = new boolean[DEFAULT_ITEMS_PER_PAGE];
// layer container used for ajax-y udpates of the table
listContainer = new WebMarkupContainer("listContainer");
// build the filter form
filterForm = new Form("filterForm");
add(filterForm);
filterForm.add(filter = new TextField("filter", new Model()));
filterForm.add(hiddenSubmit = hiddenSubmit());
filterForm.setDefaultButton(hiddenSubmit);
// setup the table
listContainer.setOutputMarkupId(true);
add(listContainer);
dataView = new DataView("items", dataProvider) {
@Override
protected void populateItem(Item item) {
final IModel itemModel = item.getModel();
// odd/even style
item.add(new SimpleAttributeModifier("class", item.getIndex() % 2 == 0 ? "even"
: "odd"));
// add row selector (visible only if selection is active)
WebMarkupContainer cnt = new WebMarkupContainer("selectItemContainer");
cnt.add(selectOneCheckbox(item));
cnt.setVisible(selectable);
item.add(cnt);
// create one component per viewable property
item.add(new ListView("itemProperties", dataProvider.getVisibleProperties()) {
@Override
protected void populateItem(ListItem item) {
Property<T> property = (Property<T>) item.getModelObject();
Component component = getComponentForProperty("component", itemModel,
property);
if(component == null) {
// show a plain label if the the subclass did not create any component
- component = new Label(id, property.getModel(itemModel));
+ component = new Label("component", property.getModel(itemModel));
} else if (!"component".equals(component.getId())) {
// add some checks for the id, the error message
// that wicket returns in case of mismatch is not
// that helpful
throw new IllegalArgumentException("getComponentForProperty asked "
+ "to build a component " + "with id = 'component' "
+ "for property '" + property.getName() + "', but got '"
+ component.getId() + "' instead");
}
item.add(component);
}
});
}
};
listContainer.add(dataView);
// add select all checkbox
WebMarkupContainer cnt = new WebMarkupContainer("selectAllContainer");
cnt.add(selectAll = selectAllCheckbox());
cnt.setVisible(selectable);
listContainer.add(cnt);
// add the sorting links
listContainer.add(new ListView("sortableLinks", dataProvider.getVisibleProperties()) {
@Override
protected void populateItem(ListItem item) {
Property<T> property = (Property<T>) item.getModelObject();
// build a sortable link if the property is sortable, a label otherwise
IModel titleModel = getPropertyTitle(property);
if (property.getComparator() != null) {
Fragment f = new Fragment("header", "sortableHeader", item);
AjaxLink link = sortLink(dataProvider, item);
link.add(new Label("label", titleModel));
f.add(link);
item.add(f);
} else {
item.add(new Label("header", titleModel));
}
}
});
// add the paging navigator and set the items per page
dataView.setItemsPerPage(DEFAULT_ITEMS_PER_PAGE);
filterForm.add(navigatorTop = new Pager("navigatorTop"));
navigatorTop.setOutputMarkupId(true);
add(navigatorBottom = new Pager("navigatorBottom"));
navigatorBottom.setOutputMarkupId(true);
}
/**
* Returns the data provider feeding this table
* @return
*/
public GeoServerDataProvider<T> getDataProvider() {
return dataProvider;
}
/**
* Called each time selection checkbox changes state due to a user action.
* By default it does nothing, subclasses can implement this to provide
* extra behavior
* @param target
*/
protected void onSelectionUpdate(AjaxRequestTarget target) {
// by default do nothing
}
/**
* Returns a model for this property title. Default behaviour is to lookup for a
* resource name <page>.th.<propertyName>
* @param property
* @return
*/
IModel getPropertyTitle(Property<T> property) {
String pageName = this.getPage().getClass().getSimpleName();
ResourceModel resMod = new ResourceModel(pageName + ".th." + property.getName(),
property.getName());
return resMod;
}
/**
* Returns the items that have been selected by the user
* @return
*/
public List<T> getSelection() {
List<T> result = new ArrayList<T>();
int i = 0;
for (Iterator it = dataView.iterator(); it.hasNext();) {
Item item = (Item) it.next();
if(selection[i]) {
result.add((T) item.getModelObject());
}
i++;
}
return result;
}
CheckBox selectAllCheckbox() {
CheckBox sa = new CheckBox("selectAll", new PropertyModel(this, "selectAllValue"));
sa.setOutputMarkupId(true);
sa.add(new AjaxFormComponentUpdatingBehavior("onclick") {
@Override
protected void onUpdate(AjaxRequestTarget target) {
// select all the checkboxes
setSelection(selectAllValue);
// update table and the checkbox itself
target.addComponent(getComponent());
target.addComponent(listContainer);
// allow subclasses to play on this change as well
onSelectionUpdate(target);
}
});
return sa;
}
CheckBox selectOneCheckbox(Item item) {
CheckBox cb = new CheckBox("selectItem", new SelectionModel(item.getIndex()));
cb.setOutputMarkupId(true);
cb.add(new AjaxFormComponentUpdatingBehavior("onclick") {
@Override
protected void onUpdate(AjaxRequestTarget target) {
if(Boolean.FALSE.equals(getComponent().getModelObject())) {
selectAllValue = false;
target.addComponent(selectAll);
}
onSelectionUpdate(target);
}
});
return cb;
}
void setSelection(boolean selected) {
for (int i = 0; i < selection.length; i++) {
selection[i] = selected;
}
selectAllValue = selected;
}
/**
* Clears the current selection
*/
public void clearSelection() {
setSelection(false);
}
/**
* Selects all the items in the current page
*/
public void selectAll() {
setSelection(true);
}
/**
* The hidden button that will submit the form when the user
* presses enter in the text field
*/
AjaxButton hiddenSubmit() {
return new AjaxButton("submit") {
@Override
protected void onSubmit(AjaxRequestTarget target, Form form) {
updateFilter(target, filter.getModelObjectAsString());
}
};
}
/**
* Number of visible items per page, should the default {@link #DEFAULT_ITEMS_PER_PAGE} not
* satisfy the programmer needs. Calling this will wipe out the selection
*
* @param items
*/
public void setItemsPerPage(int items) {
dataView.setItemsPerPage(items);
selection = new boolean[items];
}
/**
* Enables/disables filtering for this table. When no filtering is enabled, the top form with
* the top pager and the search box will disappear. Returns self for chaining.
*/
public GeoServerTablePanel<T> setFilterable(boolean filterable) {
filterForm.setVisible(filterable);
return this;
}
/**
* Builds a sort link that will force sorting on a certain column, and flip it to the other
* direction when clicked again
*/
AjaxLink sortLink(final GeoServerDataProvider<T> dataProvider, ListItem item) {
return new AjaxLink("link", item.getModel()) {
@Override
public void onClick(AjaxRequestTarget target) {
SortParam currSort = dataProvider.getSort();
Property<T> property = (Property<T>) getModelObject();
if (currSort == null || !property.getName().equals(currSort.getProperty())) {
dataProvider.setSort(new SortParam(property.getName(), true));
} else {
dataProvider
.setSort(new SortParam(property.getName(), !currSort.isAscending()));
}
setSelection(false);
target.addComponent(listContainer);
}
};
}
/**
* Parses the keywords and sets them into the data provider, forces update of the components
* that need to as a result of the different filtering
*/
private void updateFilter(AjaxRequestTarget target, String flatKeywords) {
if ("".equals(flatKeywords)) {
dataProvider.setKeywords(null);
filter.setModelObject("");
dataView.setCurrentPage(0);
} else {
String[] keywords = flatKeywords.split("\\s+");
dataProvider.setKeywords(keywords);
dataView.setCurrentPage(0);
}
navigatorTop.updateMatched();
navigatorBottom.updateMatched();
setSelection(false);
target.addComponent(listContainer);
target.addComponent(navigatorTop);
target.addComponent(navigatorBottom);
}
/**
* Turns filtering abilities on/off.
*/
public void setFilterVisible(boolean filterVisible) {
filterForm.setVisible(filterVisible);
}
/**
* Returns the component that will represent a property of a table item. Usually it should be a
* label, or a link, but you can return pretty much everything. The subclass can also return null,
* in that case a label will be created
*
* @param itemModel
* @param property
* @return
*/
protected abstract Component getComponentForProperty(String id, IModel itemModel,
Property<T> property);
IModel showingAllRecords(int first, int last, int size) {
return new ParamResourceModel("showingAllRecords", this, first, last, size);
}
IModel matchedXOutOfY(int first, int last, int size, int fullSize) {
return new ParamResourceModel("matchedXOutOfY", this, first, last, size, fullSize);
}
/**
* The two pages in the table panel. Includes a paging navigator and a status label telling the
* user what she is seeing
*/
class Pager extends Panel {
GeoServerPagingNavigator navigator;
Label matched;
Pager(String id) {
super(id);
add(navigator = updatingPagingNavigator());
add(matched = new Label("filterMatch", new Model()));
updateMatched();
}
/**
* Builds a paging navigator that will update both of the labels when the page changes.
*/
private GeoServerPagingNavigator updatingPagingNavigator() {
return new GeoServerPagingNavigator("navigator", dataView) {
@Override
protected void onAjaxEvent(AjaxRequestTarget target) {
super.onAjaxEvent(target);
setSelection(false);
navigatorTop.updateMatched();
navigatorBottom.updateMatched();
target.addComponent(navigatorTop);
target.addComponent(navigatorBottom);
}
};
}
/**
* Updates the label given the current page and filtering status
*/
void updateMatched() {
if (dataProvider.getKeywords() == null) {
matched.setModel(showingAllRecords(first(), last(), dataProvider.fullSize()));
} else {
matched.setModel(matchedXOutOfY(first(), last(), dataProvider.size(), dataProvider.fullSize()));
}
}
/**
* User oriented index of the first item in the current page
*/
int first() {
if (dataView.getDataProvider().size() > 0)
return dataView.getItemsPerPage() * dataView.getCurrentPage() + 1;
else
return 0;
}
/**
* User oriented index of the last item in the current page
*/
int last() {
int count = dataView.getPageCount();
int page = dataView.getCurrentPage();
if (page < (count - 1))
return dataView.getItemsPerPage() * (page + 1);
else
return dataView.getDataProvider().size();
}
}
class SelectionModel implements IModel {
int index;
public SelectionModel(int index) {
this.index = index;
}
public Object getObject() {
return selection[index];
}
public void setObject(Object object) {
selection[index] = ((Boolean) object).booleanValue();
}
public void detach() {
// nothing to do
}
}
}
| true | true | public GeoServerTablePanel(final String id, final GeoServerDataProvider<T> dataProvider,
final boolean selectable) {
super(id);
this.dataProvider = dataProvider;
// prepare the selection array
selection = new boolean[DEFAULT_ITEMS_PER_PAGE];
// layer container used for ajax-y udpates of the table
listContainer = new WebMarkupContainer("listContainer");
// build the filter form
filterForm = new Form("filterForm");
add(filterForm);
filterForm.add(filter = new TextField("filter", new Model()));
filterForm.add(hiddenSubmit = hiddenSubmit());
filterForm.setDefaultButton(hiddenSubmit);
// setup the table
listContainer.setOutputMarkupId(true);
add(listContainer);
dataView = new DataView("items", dataProvider) {
@Override
protected void populateItem(Item item) {
final IModel itemModel = item.getModel();
// odd/even style
item.add(new SimpleAttributeModifier("class", item.getIndex() % 2 == 0 ? "even"
: "odd"));
// add row selector (visible only if selection is active)
WebMarkupContainer cnt = new WebMarkupContainer("selectItemContainer");
cnt.add(selectOneCheckbox(item));
cnt.setVisible(selectable);
item.add(cnt);
// create one component per viewable property
item.add(new ListView("itemProperties", dataProvider.getVisibleProperties()) {
@Override
protected void populateItem(ListItem item) {
Property<T> property = (Property<T>) item.getModelObject();
Component component = getComponentForProperty("component", itemModel,
property);
if(component == null) {
// show a plain label if the the subclass did not create any component
component = new Label(id, property.getModel(itemModel));
} else if (!"component".equals(component.getId())) {
// add some checks for the id, the error message
// that wicket returns in case of mismatch is not
// that helpful
throw new IllegalArgumentException("getComponentForProperty asked "
+ "to build a component " + "with id = 'component' "
+ "for property '" + property.getName() + "', but got '"
+ component.getId() + "' instead");
}
item.add(component);
}
});
}
};
listContainer.add(dataView);
// add select all checkbox
WebMarkupContainer cnt = new WebMarkupContainer("selectAllContainer");
cnt.add(selectAll = selectAllCheckbox());
cnt.setVisible(selectable);
listContainer.add(cnt);
// add the sorting links
listContainer.add(new ListView("sortableLinks", dataProvider.getVisibleProperties()) {
@Override
protected void populateItem(ListItem item) {
Property<T> property = (Property<T>) item.getModelObject();
// build a sortable link if the property is sortable, a label otherwise
IModel titleModel = getPropertyTitle(property);
if (property.getComparator() != null) {
Fragment f = new Fragment("header", "sortableHeader", item);
AjaxLink link = sortLink(dataProvider, item);
link.add(new Label("label", titleModel));
f.add(link);
item.add(f);
} else {
item.add(new Label("header", titleModel));
}
}
});
// add the paging navigator and set the items per page
dataView.setItemsPerPage(DEFAULT_ITEMS_PER_PAGE);
filterForm.add(navigatorTop = new Pager("navigatorTop"));
navigatorTop.setOutputMarkupId(true);
add(navigatorBottom = new Pager("navigatorBottom"));
navigatorBottom.setOutputMarkupId(true);
}
| public GeoServerTablePanel(final String id, final GeoServerDataProvider<T> dataProvider,
final boolean selectable) {
super(id);
this.dataProvider = dataProvider;
// prepare the selection array
selection = new boolean[DEFAULT_ITEMS_PER_PAGE];
// layer container used for ajax-y udpates of the table
listContainer = new WebMarkupContainer("listContainer");
// build the filter form
filterForm = new Form("filterForm");
add(filterForm);
filterForm.add(filter = new TextField("filter", new Model()));
filterForm.add(hiddenSubmit = hiddenSubmit());
filterForm.setDefaultButton(hiddenSubmit);
// setup the table
listContainer.setOutputMarkupId(true);
add(listContainer);
dataView = new DataView("items", dataProvider) {
@Override
protected void populateItem(Item item) {
final IModel itemModel = item.getModel();
// odd/even style
item.add(new SimpleAttributeModifier("class", item.getIndex() % 2 == 0 ? "even"
: "odd"));
// add row selector (visible only if selection is active)
WebMarkupContainer cnt = new WebMarkupContainer("selectItemContainer");
cnt.add(selectOneCheckbox(item));
cnt.setVisible(selectable);
item.add(cnt);
// create one component per viewable property
item.add(new ListView("itemProperties", dataProvider.getVisibleProperties()) {
@Override
protected void populateItem(ListItem item) {
Property<T> property = (Property<T>) item.getModelObject();
Component component = getComponentForProperty("component", itemModel,
property);
if(component == null) {
// show a plain label if the the subclass did not create any component
component = new Label("component", property.getModel(itemModel));
} else if (!"component".equals(component.getId())) {
// add some checks for the id, the error message
// that wicket returns in case of mismatch is not
// that helpful
throw new IllegalArgumentException("getComponentForProperty asked "
+ "to build a component " + "with id = 'component' "
+ "for property '" + property.getName() + "', but got '"
+ component.getId() + "' instead");
}
item.add(component);
}
});
}
};
listContainer.add(dataView);
// add select all checkbox
WebMarkupContainer cnt = new WebMarkupContainer("selectAllContainer");
cnt.add(selectAll = selectAllCheckbox());
cnt.setVisible(selectable);
listContainer.add(cnt);
// add the sorting links
listContainer.add(new ListView("sortableLinks", dataProvider.getVisibleProperties()) {
@Override
protected void populateItem(ListItem item) {
Property<T> property = (Property<T>) item.getModelObject();
// build a sortable link if the property is sortable, a label otherwise
IModel titleModel = getPropertyTitle(property);
if (property.getComparator() != null) {
Fragment f = new Fragment("header", "sortableHeader", item);
AjaxLink link = sortLink(dataProvider, item);
link.add(new Label("label", titleModel));
f.add(link);
item.add(f);
} else {
item.add(new Label("header", titleModel));
}
}
});
// add the paging navigator and set the items per page
dataView.setItemsPerPage(DEFAULT_ITEMS_PER_PAGE);
filterForm.add(navigatorTop = new Pager("navigatorTop"));
navigatorTop.setOutputMarkupId(true);
add(navigatorBottom = new Pager("navigatorBottom"));
navigatorBottom.setOutputMarkupId(true);
}
|
diff --git a/Android/SQLitePlugin/src/com/phonegap/plugins/sqlitePlugin/SQLitePlugin.java b/Android/SQLitePlugin/src/com/phonegap/plugins/sqlitePlugin/SQLitePlugin.java
index 927ef2d..76d3d53 100755
--- a/Android/SQLitePlugin/src/com/phonegap/plugins/sqlitePlugin/SQLitePlugin.java
+++ b/Android/SQLitePlugin/src/com/phonegap/plugins/sqlitePlugin/SQLitePlugin.java
@@ -1,247 +1,249 @@
/*
* PhoneGap is available under *either* the terms of the modified BSD license *or* the
* MIT License (2008). See http://opensource.org/licenses/alphabetical for full text.
*
* Copyright (c) 2005-2010, Nitobi Software Inc.
* Copyright (c) 2010, IBM Corporation
*/
package com.phonegap.plugins.sqlitePlugin;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.phonegap.api.Plugin;
import com.phonegap.api.PluginResult;
import android.database.Cursor;
import android.database.sqlite.*;
import android.util.Log;
public class SQLitePlugin extends Plugin {
// Data Definition Language
SQLiteDatabase myDb = null; // Database object
String path = null; // Database path
String dbName = null; // Database name
/**
* Constructor.
*/
public SQLitePlugin() {
}
/**
* Executes the request and returns PluginResult.
*
* @param action
* The action to execute.
* @param args
* JSONArry of arguments for the plugin.
* @param callbackId
* The callback id used when calling back into JavaScript.
* @return A PluginResult object with a status and message.
*/
public PluginResult execute(String action, JSONArray args, String callbackId) {
PluginResult.Status status = PluginResult.Status.OK;
String result = "";
try {
// TODO: Do we want to allow a user to do this, since they could get
// to other app databases?
if (action.equals("setStorage")) {
this.setStorage(args.getString(0));
} else if (action.equals("open")) {
this.openDatabase(args.getString(0), "1",
"database", 5000000);
//this.openDatabase(args.getString(0), args.getString(1),
// args.getString(2), args.getLong(3));
}
else if (action.equals("executeSqlBatch"))
{
String[] queries = null;
String[] queryIDs = null;
String[][] params = null;
String trans_id = null;
JSONObject a = null;
JSONArray jsonArr = null;
int paramLen = 0;
if (args.isNull(0)) {
queries = new String[0];
} else {
int len = args.length();
queries = new String[len];
queryIDs = new String[len];
params = new String[len][1];
for (int i = 0; i < len; i++)
{
a = args.getJSONObject(i);
queries[i] = a.getString("query");
- queryIDs[i] = a.getString("query_id");
+ queryIDs[i] = a.getString("query_id");
trans_id = a.getString("trans_id");
jsonArr = a.getJSONArray("params");
paramLen = jsonArr.length();
params[i] = new String[paramLen];
for (int j = 0; j < paramLen; j++) {
params[i][j] = jsonArr.getString(j);
+ if(params[i][j] == "null")
+ params[i][j] = "";
}
}
}
if(trans_id != null)
this.executeSqlBatch(queries, params, queryIDs, trans_id);
else
Log.v("error", "null trans_id");
}
return new PluginResult(status, result);
} catch (JSONException e) {
return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
}
}
/**
* Identifies if action to be executed returns a value and should be run
* synchronously.
*
* @param action
* The action to execute
* @return T=returns value
*/
public boolean isSynch(String action) {
return true;
}
/**
* Clean up and close database.
*/
@Override
public void onDestroy() {
if (this.myDb != null) {
this.myDb.close();
this.myDb = null;
}
}
// --------------------------------------------------------------------------
// LOCAL METHODS
// --------------------------------------------------------------------------
/**
* Set the application package for the database. Each application saves its
* database files in a directory with the application package as part of the
* file name.
*
* For example, application "com.phonegap.demo.Demo" would save its database
* files in "/data/data/com.phonegap.demo/databases/" directory.
*
* @param appPackage
* The application package.
*/
public void setStorage(String appPackage) {
this.path = "/data/data/" + appPackage + "/databases/";
}
/**
* Open database.
*
* @param db
* The name of the database
* @param version
* The version
* @param display_name
* The display name
* @param size
* The size in bytes
*/
public void openDatabase(String db, String version, String display_name,
long size) {
// If database is open, then close it
if (this.myDb != null) {
this.myDb.close();
}
// If no database path, generate from application package
if (this.path == null) {
Package pack = this.ctx.getClass().getPackage();
String appPackage = pack.getName();
this.setStorage(appPackage);
}
this.dbName = this.path + db + ".db";
this.myDb = SQLiteDatabase.openOrCreateDatabase(this.dbName, null);
}
public void executeSqlBatch(String[] queryarr, String[][] paramsarr, String[] queryIDs, String tx_id) {
try {
this.myDb.beginTransaction();
String query = "";
String query_id = "";
String[] params;
int len = queryarr.length;
for (int i = 0; i < len; i++) {
query = queryarr[i];
params = paramsarr[i];
query_id = queryIDs[i];
Cursor myCursor = this.myDb.rawQuery(query, params);
if(query_id != "")
this.processResults(myCursor, query_id, tx_id);
myCursor.close();
}
this.myDb.setTransactionSuccessful();
}
catch (SQLiteException ex) {
ex.printStackTrace();
Log.v("executeSqlBatch", "SQLitePlugin.executeSql(): Error=" + ex.getMessage());
this.sendJavascript("SQLitePluginTransaction.txErrorCallback('" + tx_id + "', '"+ex.getMessage()+"');");
}
finally {
this.myDb.endTransaction();
Log.v("executeSqlBatch", tx_id);
this.sendJavascript("SQLitePluginTransaction.txCompleteCallback('" + tx_id + "');");
}
}
/**
* Process query results.
*
* @param cur
* Cursor into query results
* @param tx_id
* Transaction id
*/
public void processResults(Cursor cur, String query_id, String tx_id) {
String result = "[]";
// If query result has rows
if (cur.moveToFirst()) {
JSONArray fullresult = new JSONArray();
String key = "";
String value = "";
int colCount = cur.getColumnCount();
// Build up JSON result object for each row
do {
JSONObject row = new JSONObject();
try {
for (int i = 0; i < colCount; ++i) {
key = cur.getColumnName(i);
value = cur.getString(i);
row.put(key, value);
}
fullresult.put(row);
} catch (JSONException e) {
e.printStackTrace();
}
} while (cur.moveToNext());
result = fullresult.toString();
}
this.sendJavascript(" SQLitePluginTransaction.queryCompleteCallback('" + tx_id + "','" + query_id + "', " + result + ");");
}
}
| false | true | public PluginResult execute(String action, JSONArray args, String callbackId) {
PluginResult.Status status = PluginResult.Status.OK;
String result = "";
try {
// TODO: Do we want to allow a user to do this, since they could get
// to other app databases?
if (action.equals("setStorage")) {
this.setStorage(args.getString(0));
} else if (action.equals("open")) {
this.openDatabase(args.getString(0), "1",
"database", 5000000);
//this.openDatabase(args.getString(0), args.getString(1),
// args.getString(2), args.getLong(3));
}
else if (action.equals("executeSqlBatch"))
{
String[] queries = null;
String[] queryIDs = null;
String[][] params = null;
String trans_id = null;
JSONObject a = null;
JSONArray jsonArr = null;
int paramLen = 0;
if (args.isNull(0)) {
queries = new String[0];
} else {
int len = args.length();
queries = new String[len];
queryIDs = new String[len];
params = new String[len][1];
for (int i = 0; i < len; i++)
{
a = args.getJSONObject(i);
queries[i] = a.getString("query");
queryIDs[i] = a.getString("query_id");
trans_id = a.getString("trans_id");
jsonArr = a.getJSONArray("params");
paramLen = jsonArr.length();
params[i] = new String[paramLen];
for (int j = 0; j < paramLen; j++) {
params[i][j] = jsonArr.getString(j);
}
}
}
if(trans_id != null)
this.executeSqlBatch(queries, params, queryIDs, trans_id);
else
Log.v("error", "null trans_id");
}
return new PluginResult(status, result);
} catch (JSONException e) {
return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
}
}
| public PluginResult execute(String action, JSONArray args, String callbackId) {
PluginResult.Status status = PluginResult.Status.OK;
String result = "";
try {
// TODO: Do we want to allow a user to do this, since they could get
// to other app databases?
if (action.equals("setStorage")) {
this.setStorage(args.getString(0));
} else if (action.equals("open")) {
this.openDatabase(args.getString(0), "1",
"database", 5000000);
//this.openDatabase(args.getString(0), args.getString(1),
// args.getString(2), args.getLong(3));
}
else if (action.equals("executeSqlBatch"))
{
String[] queries = null;
String[] queryIDs = null;
String[][] params = null;
String trans_id = null;
JSONObject a = null;
JSONArray jsonArr = null;
int paramLen = 0;
if (args.isNull(0)) {
queries = new String[0];
} else {
int len = args.length();
queries = new String[len];
queryIDs = new String[len];
params = new String[len][1];
for (int i = 0; i < len; i++)
{
a = args.getJSONObject(i);
queries[i] = a.getString("query");
queryIDs[i] = a.getString("query_id");
trans_id = a.getString("trans_id");
jsonArr = a.getJSONArray("params");
paramLen = jsonArr.length();
params[i] = new String[paramLen];
for (int j = 0; j < paramLen; j++) {
params[i][j] = jsonArr.getString(j);
if(params[i][j] == "null")
params[i][j] = "";
}
}
}
if(trans_id != null)
this.executeSqlBatch(queries, params, queryIDs, trans_id);
else
Log.v("error", "null trans_id");
}
return new PluginResult(status, result);
} catch (JSONException e) {
return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
}
}
|
diff --git a/module-blog/src/test/java/org/devproof/portal/module/blog/page/BlogEditPageTest.java b/module-blog/src/test/java/org/devproof/portal/module/blog/page/BlogEditPageTest.java
index e2534105..c06e8d3e 100644
--- a/module-blog/src/test/java/org/devproof/portal/module/blog/page/BlogEditPageTest.java
+++ b/module-blog/src/test/java/org/devproof/portal/module/blog/page/BlogEditPageTest.java
@@ -1,117 +1,118 @@
/*
* Copyright 2009-2011 Carsten Hufe devproof.org
*
* 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.devproof.portal.module.blog.page;
import org.apache.wicket.model.Model;
import org.apache.wicket.util.tester.FormTester;
import org.apache.wicket.util.tester.WicketTester;
import org.devproof.portal.module.blog.entity.Blog;
import org.devproof.portal.test.MockContextLoader;
import org.devproof.portal.test.PortalTestUtil;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.servlet.ServletContext;
import static org.junit.Assert.assertFalse;
/**
* @author Carsten Hufe
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = MockContextLoader.class,
locations = {"classpath:/org/devproof/portal/module/blog/test-datasource.xml" })
public class BlogEditPageTest {
@SuppressWarnings({"SpringJavaAutowiringInspection"})
@Autowired
private ServletContext servletContext;
private WicketTester tester;
@Before
public void setUp() throws Exception {
tester = PortalTestUtil.createWicketTester(servletContext);
PortalTestUtil.loginDefaultAdminUser(tester);
}
@After
public void tearDown() throws Exception {
PortalTestUtil.destroy(tester);
}
@Test
public void testRenderDefaultPage() {
tester.startPage(createNewBlogEditPage());
tester.assertRenderedPage(BlogEditPage.class);
}
private BlogEditPage createNewBlogEditPage() {
return new BlogEditPage(Model.of(new Blog()));
}
@Test
public void testSaveBlogEntry() {
callBlogEditPage();
submitBlogForm();
assertBlogPage();
}
private void callBlogEditPage() {
tester.startPage(createNewBlogEditPage());
tester.assertRenderedPage(BlogEditPage.class);
}
@Test
public void testEditBlogEntry() {
navigateToBlogEditPage();
submitBlogForm();
assertBlogPage();
String s = tester.getServletResponse().getDocument();
assertFalse(s.contains("This is a sample blog entry."));
}
private void navigateToBlogEditPage() {
tester.startPage(BlogPage.class);
tester.assertRenderedPage(BlogPage.class);
tester.assertContains("This is a sample blog entry.");
tester.debugComponentTrees();
- tester.clickLink("refreshContainerBlogEntries:repeatingBlogEntries:2:blogView:authorButtons:editLink");
+// tester.dumpPage();
+ tester.clickLink("refreshContainerBlogEntries:repeatingBlogEntries:2:blogView:authorButtons:editLink", true);
tester.assertRenderedPage(BlogEditPage.class);
tester.assertContains("This is a sample blog entry.");
}
private void assertBlogPage() {
String expectedMsgs[] = PortalTestUtil.getMessage("msg.saved", createNewBlogEditPage());
tester.assertRenderedPage(BlogPage.class);
tester.assertInfoMessages(expectedMsgs);
tester.startPage(BlogPage.class);
tester.assertRenderedPage(BlogPage.class);
tester.assertContains("testing headline");
tester.assertContains("testing content");
}
private void submitBlogForm() {
FormTester form = tester.newFormTester("form");
form.setValue("tags", "these are tags");
form.setValue("headline", "testing headline");
form.setValue("content", "testing content");
form.submit();
}
}
| true | true | private void navigateToBlogEditPage() {
tester.startPage(BlogPage.class);
tester.assertRenderedPage(BlogPage.class);
tester.assertContains("This is a sample blog entry.");
tester.debugComponentTrees();
tester.clickLink("refreshContainerBlogEntries:repeatingBlogEntries:2:blogView:authorButtons:editLink");
tester.assertRenderedPage(BlogEditPage.class);
tester.assertContains("This is a sample blog entry.");
}
| private void navigateToBlogEditPage() {
tester.startPage(BlogPage.class);
tester.assertRenderedPage(BlogPage.class);
tester.assertContains("This is a sample blog entry.");
tester.debugComponentTrees();
// tester.dumpPage();
tester.clickLink("refreshContainerBlogEntries:repeatingBlogEntries:2:blogView:authorButtons:editLink", true);
tester.assertRenderedPage(BlogEditPage.class);
tester.assertContains("This is a sample blog entry.");
}
|
diff --git a/src/Ranges.java b/src/Ranges.java
index cbb073e..9625327 100644
--- a/src/Ranges.java
+++ b/src/Ranges.java
@@ -1,200 +1,205 @@
package srma;
import java.io.*;
import java.util.*;
import net.sf.picard.reference.*;
import net.sf.samtools.*;
// TODO:
// - need to check references are in order
// - better error messages
// - state how many ranges were found
public class Ranges {
private LinkedList<Range> ranges = null;
public Ranges(File file, SAMSequenceDictionary referenceDictionary, int offset)
{
BufferedReader br = null;
String line = null;
int i, lineNumber = 1;
Map<String, Integer> hm = new HashMap<String, Integer>();
try {
// open
br = new BufferedReader(new FileReader(file));
// init
this.ranges = new LinkedList<Range>();
for(i=0;i<referenceDictionary.size();i++) {
hm.put(referenceDictionary.getSequence(i).getSequenceName(), new Integer(i));
}
// read the file
while(null != (line = br.readLine())) {
this.addRange(line, lineNumber, hm, referenceDictionary, offset);
lineNumber++;
}
// close
br.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
public Ranges(File file, SAMSequenceDictionary referenceDictionary)
{
this(file, referenceDictionary, 0);
}
public Ranges(String range, SAMSequenceDictionary referenceDictionary, int offset)
throws Exception
{
Map<String, Integer> hm = new HashMap<String, Integer>();
int i, colon, dash, referenceIndex;
// init
this.ranges = new LinkedList<Range>();
for(i=0;i<referenceDictionary.size();i++) {
hm.put(referenceDictionary.getSequence(i).getSequenceName(), new Integer(i));
}
// get delimiters
colon = range.indexOf(':');
dash = range.indexOf('-', colon+1);
if(colon <= 0 || (dash - colon) <= 1 || (range.length() - dash) <= 1) {
throw new Exception("RANGE was improperly specified.");
}
String chrName = range.substring(0, colon);
if(null == hm.get(chrName)) {
throw new Exception("Could not find reference name " + chrName + " in RANGE");
}
referenceIndex = (int)hm.get(chrName);
int startPosition = Integer.parseInt(range.substring(colon+1, dash));
int endPosition = Integer.parseInt(range.substring(dash+1));
if(startPosition <= 0 || referenceDictionary.getSequence(referenceIndex).getSequenceLength() < startPosition) {
throw new Exception("startPosition was out of bounds in RANGE");
}
else if(endPosition <= 0 || referenceDictionary.getSequence(referenceIndex).getSequenceLength() < endPosition) {
throw new Exception("endPosition was out of bounds in RANGE");
}
else if(endPosition < startPosition) {
throw new Exception("endPosition < startPosition in RANGE");
}
startPosition -= offset;
if(startPosition <= 0) {
startPosition = 1;
}
endPosition += offset;
if(referenceDictionary.getSequence(referenceIndex).getSequenceLength() < endPosition) {
endPosition = referenceDictionary.getSequence(referenceIndex).getSequenceLength();
}
this.ranges.add(new Range(referenceIndex, startPosition, endPosition));
}
public Ranges(String range, SAMSequenceDictionary referenceDictionary)
throws Exception
{
this(range, referenceDictionary, 0);
}
private void addRange(String line, int lineNumber, Map<String, Integer> m, SAMSequenceDictionary referenceDictionary, int offset)
throws Exception
{
StringTokenizer st = new StringTokenizer(line);
int referenceIndex=-1;
int startPosition=-1, endPosition=-1;
int i=0;
while(st.hasMoreTokens()) {
if(0 == i) {
- Integer tmpInteger = (int)m.get(new String(st.nextToken()));
+ Integer tmpInteger = -1;
+ try {
+ tmpInteger = (int)m.get(new String(st.nextToken()));
+ } catch(java.lang.NullPointerException e) {
+ throw new Exception("Could not find reference name in RANGES on line " + lineNumber);
+ }
if(null == tmpInteger) {
throw new Exception("Could not find reference name in RANGES on line " + lineNumber);
}
referenceIndex = (int)tmpInteger;
}
else if(1 == i) {
startPosition = Integer.parseInt(new String(st.nextToken()));
if(startPosition <= 0 || referenceDictionary.getSequence(referenceIndex).getSequenceLength() < startPosition) {
throw new Exception("start position was out of bounds in RANGES on line " + lineNumber);
}
// add offset
startPosition -= offset;
if(startPosition <= 0) {
startPosition = 1;
}
}
else if(2 == i) {
endPosition = Integer.parseInt(new String(st.nextToken()));
if(endPosition <= 0 || referenceDictionary.getSequence(referenceIndex).getSequenceLength() < endPosition) {
throw new Exception("end position was out of bounds in RANGES on line " + lineNumber);
}
// add offset
endPosition += offset;
if(referenceDictionary.getSequence(referenceIndex).getSequenceLength() < endPosition) {
endPosition = referenceDictionary.getSequence(referenceIndex).getSequenceLength();
}
}
else {
new Exception("Too many entries in RANGES on line " + lineNumber);
}
i++;
}
if(3 != i) {
new Exception("Too few entries in RANGES on line " + lineNumber);
}
if(endPosition < startPosition) {
throw new Exception("End position < start position in RANGES on line " + lineNumber);
}
if(null != this.ranges.peek()) {
Range last = this.ranges.getLast();
if(referenceIndex < last.referenceIndex) {
throw new Exception("Ranges must be in sorted order in RANGES (line numbers " + (lineNumber-1) + "-" + lineNumber);
}
else if(referenceIndex == last.referenceIndex) { // sam reference
if(startPosition < last.startPosition) {
throw new Exception("Ranges must be in sorted order in RANGES (line numbers " + (lineNumber-1) + "-" + lineNumber);
}
else if(last.endPosition + 1 < startPosition) {
// just add
this.ranges.add(new Range(referenceIndex, startPosition, endPosition));
}
else if(last.endPosition < endPosition) {
// merge over-lapping
last.endPosition = endPosition;
}
}
else {
// just add
this.ranges.add(new Range(referenceIndex, startPosition, endPosition));
}
}
else {
// just add
this.ranges.add(new Range(referenceIndex, startPosition, endPosition));
}
}
public Iterator<Range> iterator()
{
return this.ranges.iterator();
}
public Range get(int i)
{
return this.ranges.get(i);
}
public int size()
{
return this.ranges.size();
}
}
| true | true | private void addRange(String line, int lineNumber, Map<String, Integer> m, SAMSequenceDictionary referenceDictionary, int offset)
throws Exception
{
StringTokenizer st = new StringTokenizer(line);
int referenceIndex=-1;
int startPosition=-1, endPosition=-1;
int i=0;
while(st.hasMoreTokens()) {
if(0 == i) {
Integer tmpInteger = (int)m.get(new String(st.nextToken()));
if(null == tmpInteger) {
throw new Exception("Could not find reference name in RANGES on line " + lineNumber);
}
referenceIndex = (int)tmpInteger;
}
else if(1 == i) {
startPosition = Integer.parseInt(new String(st.nextToken()));
if(startPosition <= 0 || referenceDictionary.getSequence(referenceIndex).getSequenceLength() < startPosition) {
throw new Exception("start position was out of bounds in RANGES on line " + lineNumber);
}
// add offset
startPosition -= offset;
if(startPosition <= 0) {
startPosition = 1;
}
}
else if(2 == i) {
endPosition = Integer.parseInt(new String(st.nextToken()));
if(endPosition <= 0 || referenceDictionary.getSequence(referenceIndex).getSequenceLength() < endPosition) {
throw new Exception("end position was out of bounds in RANGES on line " + lineNumber);
}
// add offset
endPosition += offset;
if(referenceDictionary.getSequence(referenceIndex).getSequenceLength() < endPosition) {
endPosition = referenceDictionary.getSequence(referenceIndex).getSequenceLength();
}
}
else {
new Exception("Too many entries in RANGES on line " + lineNumber);
}
i++;
}
if(3 != i) {
new Exception("Too few entries in RANGES on line " + lineNumber);
}
if(endPosition < startPosition) {
throw new Exception("End position < start position in RANGES on line " + lineNumber);
}
if(null != this.ranges.peek()) {
Range last = this.ranges.getLast();
if(referenceIndex < last.referenceIndex) {
throw new Exception("Ranges must be in sorted order in RANGES (line numbers " + (lineNumber-1) + "-" + lineNumber);
}
else if(referenceIndex == last.referenceIndex) { // sam reference
if(startPosition < last.startPosition) {
throw new Exception("Ranges must be in sorted order in RANGES (line numbers " + (lineNumber-1) + "-" + lineNumber);
}
else if(last.endPosition + 1 < startPosition) {
// just add
this.ranges.add(new Range(referenceIndex, startPosition, endPosition));
}
else if(last.endPosition < endPosition) {
// merge over-lapping
last.endPosition = endPosition;
}
}
else {
// just add
this.ranges.add(new Range(referenceIndex, startPosition, endPosition));
}
}
else {
// just add
this.ranges.add(new Range(referenceIndex, startPosition, endPosition));
}
}
| private void addRange(String line, int lineNumber, Map<String, Integer> m, SAMSequenceDictionary referenceDictionary, int offset)
throws Exception
{
StringTokenizer st = new StringTokenizer(line);
int referenceIndex=-1;
int startPosition=-1, endPosition=-1;
int i=0;
while(st.hasMoreTokens()) {
if(0 == i) {
Integer tmpInteger = -1;
try {
tmpInteger = (int)m.get(new String(st.nextToken()));
} catch(java.lang.NullPointerException e) {
throw new Exception("Could not find reference name in RANGES on line " + lineNumber);
}
if(null == tmpInteger) {
throw new Exception("Could not find reference name in RANGES on line " + lineNumber);
}
referenceIndex = (int)tmpInteger;
}
else if(1 == i) {
startPosition = Integer.parseInt(new String(st.nextToken()));
if(startPosition <= 0 || referenceDictionary.getSequence(referenceIndex).getSequenceLength() < startPosition) {
throw new Exception("start position was out of bounds in RANGES on line " + lineNumber);
}
// add offset
startPosition -= offset;
if(startPosition <= 0) {
startPosition = 1;
}
}
else if(2 == i) {
endPosition = Integer.parseInt(new String(st.nextToken()));
if(endPosition <= 0 || referenceDictionary.getSequence(referenceIndex).getSequenceLength() < endPosition) {
throw new Exception("end position was out of bounds in RANGES on line " + lineNumber);
}
// add offset
endPosition += offset;
if(referenceDictionary.getSequence(referenceIndex).getSequenceLength() < endPosition) {
endPosition = referenceDictionary.getSequence(referenceIndex).getSequenceLength();
}
}
else {
new Exception("Too many entries in RANGES on line " + lineNumber);
}
i++;
}
if(3 != i) {
new Exception("Too few entries in RANGES on line " + lineNumber);
}
if(endPosition < startPosition) {
throw new Exception("End position < start position in RANGES on line " + lineNumber);
}
if(null != this.ranges.peek()) {
Range last = this.ranges.getLast();
if(referenceIndex < last.referenceIndex) {
throw new Exception("Ranges must be in sorted order in RANGES (line numbers " + (lineNumber-1) + "-" + lineNumber);
}
else if(referenceIndex == last.referenceIndex) { // sam reference
if(startPosition < last.startPosition) {
throw new Exception("Ranges must be in sorted order in RANGES (line numbers " + (lineNumber-1) + "-" + lineNumber);
}
else if(last.endPosition + 1 < startPosition) {
// just add
this.ranges.add(new Range(referenceIndex, startPosition, endPosition));
}
else if(last.endPosition < endPosition) {
// merge over-lapping
last.endPosition = endPosition;
}
}
else {
// just add
this.ranges.add(new Range(referenceIndex, startPosition, endPosition));
}
}
else {
// just add
this.ranges.add(new Range(referenceIndex, startPosition, endPosition));
}
}
|
diff --git a/src/java-server-framework/org/xins/server/APIServlet.java b/src/java-server-framework/org/xins/server/APIServlet.java
index 62808b93b..f3eaf63f8 100644
--- a/src/java-server-framework/org/xins/server/APIServlet.java
+++ b/src/java-server-framework/org/xins/server/APIServlet.java
@@ -1,401 +1,401 @@
/*
* $Id$
*
* Copyright 2003-2007 Orange Nederland Breedband B.V.
* See the COPYRIGHT file for redistribution and use restrictions.
*/
package org.xins.server;
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.xins.common.MandatoryArgumentChecker;
/**
* HTTP servlet that forwards requests to an <code>API</code>.
*
* <h3>HTTP status codes</h3>
*
* <p>This servlet supports various HTTP methods, depending on the calling
* conventions. A request with an unsupported method makes this servlet
* return the HTTP status code <code>405 Method Not Allowed</code>.
*
* <p>If no matching function is found, then this servlet returns HTTP status
* code <code>404 Not Found</code>.
*
* <p>If the servlet is temporarily unavailable, then the HTTP status
* <code>503 Service Unavailable</code> is returned.
*
* <p>If the servlet encountered an initialization error, then the HTTP status
* code <code>500 Internal Server Error</code> is returned.
*
* <p>If the state is <em>ready</em> then the HTTP status code
* <code>200 OK</code> is returned.
*
*
* <h3>Initialization</h3>
*
* <p>When the servlet is initialized, it gathers configuration information
* from different sources:
*
* <dl>
* <dt><strong>1. Build-time settings</strong></dt>
* <dd>The application package contains a <code>web.xml</code> file with
* build-time settings. Some of these settings are required in order
* for the XINS/Java Server Framework to start up, while others are
* optional. These build-time settings are passed to the servlet by the
* application server as a {@link ServletConfig} object. See
* {@link #init(ServletConfig)}.
* <br>The servlet configuration is the responsibility of the
* <em>assembler</em>.</dd>
*
* <dt><strong>2. System properties</strong></dt>
* <dd>The location of the configuration file must be passed to the Java VM
* at startup, as a system property.
* <br>System properties are the responsibility of the
* <em>system administrator</em>.
* <br>Example:
* <br><code>java -Dorg.xins.server.config=`pwd`/config/xins.properties
* -jar orion.jar</code></dd>
*
* <dt><strong>3. Configuration file</strong></dt>
* <dd>The configuration file should contain runtime configuration
* settings, like the settings for the logging subsystem.
* <br>Runtime properties are the responsibility of the
* <em>system administrator</em>.
* <br>Example contents for a configuration file:
* <blockquote><code>log4j.rootLogger=DEBUG, console
* <br>log4j.appender.console=org.apache.log4j.ConsoleAppender
* <br>log4j.appender.console.layout=org.apache.log4j.PatternLayout
* <br>log4j.appender.console.layout.ConversionPattern=%d %-5p [%c]
* %m%n</code></blockquote></dd>
* </dl>
*
* @version $Revision$ $Date$
* @author <a href="mailto:[email protected]">Ernst de Haan</a>
* @author <a href="mailto:[email protected]">Anthony Goubard</a>
* @author <a href="mailto:[email protected]">Mees Witteman</a>
*
* @since XINS 1.0.0
*/
public final class APIServlet
extends HttpServlet {
// TODO: Log 3611 and return an appropriate HTTP result when the API is not
// usable.
/**
* Serial version UID. Used for serialization. The assigned value is for
* compatibility with XINS 1.2.5.
*/
private static final long serialVersionUID = -1117062458458353841L;
/**
* The name of the system property that specifies the location of the
* configuration file.
*/
public static final String CONFIG_FILE_SYSTEM_PROPERTY =
"org.xins.server.config";
/**
* The name of the runtime property that specifies the interval
* for the configuration file modification checks, in seconds.
*/
public static final String CONFIG_RELOAD_INTERVAL_PROPERTY =
"org.xins.server.config.reload";
/**
* The name of the runtime property that hostname for the server
* running the API.
*/
public static final String HOSTNAME_PROPERTY = "org.xins.server.hostname";
/**
* The default configuration file modification check interval, in seconds.
*/
public static final int DEFAULT_CONFIG_RELOAD_INTERVAL = 60;
/**
* The name of the build property that specifies the name of the
* API class to load.
*/
public static final String API_CLASS_PROPERTY = "org.xins.api.class";
/**
* The name of the build property that specifies the name of the
* API.
*/
public static final String API_NAME_PROPERTY = "org.xins.api.name";
/**
* The name of the build property that specifies the version with which the
* API was built.
*/
public static final String API_BUILD_VERSION_PROPERTY =
"org.xins.api.build.version";
/**
* The name of the build property that specifies the name of the default
* calling convention.
*/
public static final String API_CALLING_CONVENTION_PROPERTY =
"org.xins.api.calling.convention";
/**
* The name of the build property that specifies the class of the default
* calling convention.
*/
public static final String API_CALLING_CONVENTION_CLASS_PROPERTY =
"org.xins.api.calling.convention.class";
/**
* The name of the request parameter that specifies the name of the calling
* convention to use.
*/
public static final String CALLING_CONVENTION_PARAMETER = "_convention";
/**
* The name of the XINS standard calling convention.
*/
public static final String STANDARD_CALLING_CONVENTION = "_xins-std";
/**
* The XINS XML calling convention.
*/
public static final String XML_CALLING_CONVENTION = "_xins-xml";
/**
* The XINS XSLT calling convention.
*/
public static final String XSLT_CALLING_CONVENTION = "_xins-xslt";
/**
* The name of the SOAP calling convention.
*
* @since XINS 1.3.0
*/
public static final String SOAP_CALLING_CONVENTION = "_xins-soap";
/**
* The name of the XML-RPC calling convention.
*
* @since XINS 1.3.0
*/
public static final String XML_RPC_CALLING_CONVENTION = "_xins-xmlrpc";
/**
* The name of the JSON-RPC calling convention.
*
* @since XINS 2.0.
*/
public static final String JSON_RPC_CALLING_CONVENTION = "_xins-jsonrpc";
/**
* The name of the JSON calling convention (Yahoo! style).
*
* @since XINS 2.0.
*/
public static final String JSON_CALLING_CONVENTION = "_xins-json";
/**
* XINS server engine. Initially <code>null</code> but set to a
* non-<code>null</code> value in the {@link #init(ServletConfig)} method.
*/
private Engine _engine;
/**
* Initializes the loggers to log to the console using a simple format
* and no threshold. This is done by calling
* {@link Engine#configureLoggerFallback()}.
*/
static {
ConfigManager.configureLoggerFallback();
}
/**
* Constructs a new <code>APIServlet</code> object.
*/
public APIServlet() {
// empty
}
/**
* Returns information about this servlet, as plain text.
*
* @return
* textual description of this servlet, not <code>null</code> and not an
* empty character string.
*/
public String getServletInfo() {
return "XINS/Java Server Framework " + Library.getVersion();
}
/**
* Initializes this servlet using the specified configuration.
*
* @param config
* the {@link ServletConfig} object which contains build properties for
* this servlet, as specified by the <em>assembler</em>, cannot be
* <code>null</code>.
*
* @throws IllegalArgumentException
* if <code>config == null
* || config.{@link ServletConfig#getServletContext()} == null</code>.
*
* @throws ServletException
* if the servlet could not be initialized.
*/
public void init(ServletConfig config)
throws IllegalArgumentException, ServletException {
// Check arguments
MandatoryArgumentChecker.check("config", config);
// Get the ServletContext
ServletContext context = config.getServletContext();
if (context == null) {
String message = "config.getServletContext() == null";
Log.log_3202(message);
throw new IllegalArgumentException(message);
}
// Compare the expected with the implemented Java Servlet API version;
- // versions 2.2, 2.3 and 2.4 are supported
+ // versions 2.2, 2.3, 2.4 and 2.5 are supported
int major = context.getMajorVersion();
int minor = context.getMinorVersion();
if (major != 2 || minor < 2 || minor > 5) {
String expected = "2.2/2.3/2.4/2.5";
- String actual = "" + major + '.' + minor;
+ String actual = major + "." + minor;
Log.log_3203(actual, expected);
}
// Construct an engine
try {
_engine = new Engine(config);
// Fail silently, so that the servlet container will not keep trying to
// re-initialize this servlet (possibly on each call!)
} catch (Throwable exception) {
String thisClass = APIServlet.class.getName();
String thisMethod = "init(javax.servlet.ServletConfig)";
String thatClass = Engine.class.getName();
String thatMethod = "<init>(javax.servlet.ServletConfig)";
String detail = null;
org.xins.common.Log.log_1052(exception,
thisClass, thisMethod,
thatClass, thatMethod,
detail);
return;
}
}
/**
* Returns the <code>ServletConfig</code> object which contains the
* build properties for this servlet. The returned {@link ServletConfig}
* object is the one passed to the {@link #init(ServletConfig)} method.
*
* @return
* the {@link ServletConfig} object that was used to initialize this
* servlet, or <code>null</code> if this servlet is not yet
* initialized.
*/
public ServletConfig getServletConfig() {
return (_engine == null) ? null : _engine.getServletConfig();
}
/**
* Handles a request to this servlet. If any of the arguments is
* <code>null</code>, then the behaviour of this method is undefined.
*
* @param request
* the servlet request, should not be <code>null</code>.
*
* @param response
* the servlet response, should not be <code>null</code>.
*
* @throws NullPointerException
* if this servlet is yet uninitialized.
*
* @throws ClassCastException
* if <code>! (request instanceof {@link HttpServletRequest}
* && response instanceof {@link HttpServletResponse})</code>.
*
* @throws ServletException
* if this servlet failed for some other reason that an I/O error.
*
* @throws IOException
* if there is an error error writing to the response output stream.
*/
public void service(ServletRequest request,
ServletResponse response)
throws NullPointerException,
ClassCastException,
ServletException,
IOException {
// Convert request and response to HTTP-specific variants
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
// Engine failed to initialize, return '500 Internal Server Error'
if (_engine == null) {
httpResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
// Pass control to the Engine
_engine.service(httpRequest, httpResponse);
}
/**
* Handles an HTTP request to this servlet. If any of the arguments is
* <code>null</code>, then the behaviour of this method is undefined.
*
* @param request
* the servlet request, should not be <code>null</code>.
*
* @param response
* the servlet response, should not be <code>null</code>.
*
* @throws NullPointerException
* if this servlet is yet uninitialized.
*
* @throws IOException
* if there is an error error writing to the response output stream.
*/
public void service(HttpServletRequest request,
HttpServletResponse response)
throws NullPointerException,
IOException {
// Engine failed to initialize, return '500 Internal Server Error'
if (_engine == null) {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
// Pass control to the Engine
_engine.service(request, response);
}
/**
* Destroys this servlet. A best attempt will be made to release all
* resources.
*
* <p>After this method has finished, no more requests will be handled
* successfully.
*/
public void destroy() {
if (_engine != null) {
_engine.destroy();
_engine = null;
}
}
}
| false | true | public void init(ServletConfig config)
throws IllegalArgumentException, ServletException {
// Check arguments
MandatoryArgumentChecker.check("config", config);
// Get the ServletContext
ServletContext context = config.getServletContext();
if (context == null) {
String message = "config.getServletContext() == null";
Log.log_3202(message);
throw new IllegalArgumentException(message);
}
// Compare the expected with the implemented Java Servlet API version;
// versions 2.2, 2.3 and 2.4 are supported
int major = context.getMajorVersion();
int minor = context.getMinorVersion();
if (major != 2 || minor < 2 || minor > 5) {
String expected = "2.2/2.3/2.4/2.5";
String actual = "" + major + '.' + minor;
Log.log_3203(actual, expected);
}
// Construct an engine
try {
_engine = new Engine(config);
// Fail silently, so that the servlet container will not keep trying to
// re-initialize this servlet (possibly on each call!)
} catch (Throwable exception) {
String thisClass = APIServlet.class.getName();
String thisMethod = "init(javax.servlet.ServletConfig)";
String thatClass = Engine.class.getName();
String thatMethod = "<init>(javax.servlet.ServletConfig)";
String detail = null;
org.xins.common.Log.log_1052(exception,
thisClass, thisMethod,
thatClass, thatMethod,
detail);
return;
}
}
| public void init(ServletConfig config)
throws IllegalArgumentException, ServletException {
// Check arguments
MandatoryArgumentChecker.check("config", config);
// Get the ServletContext
ServletContext context = config.getServletContext();
if (context == null) {
String message = "config.getServletContext() == null";
Log.log_3202(message);
throw new IllegalArgumentException(message);
}
// Compare the expected with the implemented Java Servlet API version;
// versions 2.2, 2.3, 2.4 and 2.5 are supported
int major = context.getMajorVersion();
int minor = context.getMinorVersion();
if (major != 2 || minor < 2 || minor > 5) {
String expected = "2.2/2.3/2.4/2.5";
String actual = major + "." + minor;
Log.log_3203(actual, expected);
}
// Construct an engine
try {
_engine = new Engine(config);
// Fail silently, so that the servlet container will not keep trying to
// re-initialize this servlet (possibly on each call!)
} catch (Throwable exception) {
String thisClass = APIServlet.class.getName();
String thisMethod = "init(javax.servlet.ServletConfig)";
String thatClass = Engine.class.getName();
String thatMethod = "<init>(javax.servlet.ServletConfig)";
String detail = null;
org.xins.common.Log.log_1052(exception,
thisClass, thisMethod,
thatClass, thatMethod,
detail);
return;
}
}
|
diff --git a/bpel-runtime/src/main/java/org/apache/ode/bpel/engine/CountLRUDehydrationPolicy.java b/bpel-runtime/src/main/java/org/apache/ode/bpel/engine/CountLRUDehydrationPolicy.java
index 8cc7f4e2a..73701d825 100644
--- a/bpel-runtime/src/main/java/org/apache/ode/bpel/engine/CountLRUDehydrationPolicy.java
+++ b/bpel-runtime/src/main/java/org/apache/ode/bpel/engine/CountLRUDehydrationPolicy.java
@@ -1,56 +1,56 @@
package org.apache.ode.bpel.engine;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* @author Matthieu Riou <mriou at apache dot org>
*/
public class CountLRUDehydrationPolicy implements DehydrationPolicy {
/** Maximum age of a process before it is quiesced */
private long _processMaxAge = 20 * 60 * 1000;
/** Maximum process count before oldest ones get quiesced */
private int _processMaxCount = 1000;
public List<BpelProcess> markForDehydration(List<BpelProcess> runningProcesses) {
ArrayList<BpelProcess> ripped = new ArrayList<BpelProcess>();
if (_processMaxAge > 0) {
// The oldies have to go first
long now = System.currentTimeMillis();
for (BpelProcess process : runningProcesses) {
if (now - process.getLastUsed() > _processMaxAge) {
ripped.add(process);
}
}
}
// If it's not enough, other ones must be put to the axe
if (runningProcesses.size() - ripped.size() > _processMaxCount) {
runningProcesses.removeAll(ripped);
Collections.sort(runningProcesses, new Comparator<BpelProcess>() {
public int compare(BpelProcess p1, BpelProcess p2) {
- if (p1.getLastUsed() > p2.getLastUsed()) return 1;
- if (p1.getLastUsed() < p2.getLastUsed()) return -1;
+ if (p1.getLastUsed() > p2.getLastUsed()) return -1;
+ if (p1.getLastUsed() < p2.getLastUsed()) return 1;
return 0;
}
});
for (int m = _processMaxCount; m < runningProcesses.size(); m++) {
ripped.add(runningProcesses.get(m));
}
}
return ripped;
}
public void setProcessMaxAge(long processMaxAge) {
_processMaxAge = processMaxAge;
}
public void setProcessMaxCount(int processMaxCount) {
_processMaxCount = processMaxCount;
}
}
| true | true | public List<BpelProcess> markForDehydration(List<BpelProcess> runningProcesses) {
ArrayList<BpelProcess> ripped = new ArrayList<BpelProcess>();
if (_processMaxAge > 0) {
// The oldies have to go first
long now = System.currentTimeMillis();
for (BpelProcess process : runningProcesses) {
if (now - process.getLastUsed() > _processMaxAge) {
ripped.add(process);
}
}
}
// If it's not enough, other ones must be put to the axe
if (runningProcesses.size() - ripped.size() > _processMaxCount) {
runningProcesses.removeAll(ripped);
Collections.sort(runningProcesses, new Comparator<BpelProcess>() {
public int compare(BpelProcess p1, BpelProcess p2) {
if (p1.getLastUsed() > p2.getLastUsed()) return 1;
if (p1.getLastUsed() < p2.getLastUsed()) return -1;
return 0;
}
});
for (int m = _processMaxCount; m < runningProcesses.size(); m++) {
ripped.add(runningProcesses.get(m));
}
}
return ripped;
}
| public List<BpelProcess> markForDehydration(List<BpelProcess> runningProcesses) {
ArrayList<BpelProcess> ripped = new ArrayList<BpelProcess>();
if (_processMaxAge > 0) {
// The oldies have to go first
long now = System.currentTimeMillis();
for (BpelProcess process : runningProcesses) {
if (now - process.getLastUsed() > _processMaxAge) {
ripped.add(process);
}
}
}
// If it's not enough, other ones must be put to the axe
if (runningProcesses.size() - ripped.size() > _processMaxCount) {
runningProcesses.removeAll(ripped);
Collections.sort(runningProcesses, new Comparator<BpelProcess>() {
public int compare(BpelProcess p1, BpelProcess p2) {
if (p1.getLastUsed() > p2.getLastUsed()) return -1;
if (p1.getLastUsed() < p2.getLastUsed()) return 1;
return 0;
}
});
for (int m = _processMaxCount; m < runningProcesses.size(); m++) {
ripped.add(runningProcesses.get(m));
}
}
return ripped;
}
|
diff --git a/src/test/java/de/agilecoders/wicket/requirejs/RequireJsConfigTest.java b/src/test/java/de/agilecoders/wicket/requirejs/RequireJsConfigTest.java
index 5209767..5810d31 100644
--- a/src/test/java/de/agilecoders/wicket/requirejs/RequireJsConfigTest.java
+++ b/src/test/java/de/agilecoders/wicket/requirejs/RequireJsConfigTest.java
@@ -1,51 +1,56 @@
package de.agilecoders.wicket.requirejs;
import de.agilecoders.wicket.WicketApplicationTest;
import org.apache.wicket.markup.head.IHeaderResponse;
import org.apache.wicket.request.resource.JavaScriptResourceReference;
import org.junit.Ignore;
import org.junit.Test;
import java.util.regex.Pattern;
/**
* Tests the {@link RequireJsConfig} component
*
* @author miha
*/
public class RequireJsConfigTest extends WicketApplicationTest {
@Test
public void correctMapIsRendered() throws Exception {
tester().startComponentInPage(new RequireJsConfig("id"));
tester().assertContains(Pattern.quote("require.config({\n"
- + " \"baseUrl\": \"../requirejs/\",\n"
+ + " \"baseUrl\": \"..//\",\n"
+ + " \"paths\": {\n"
+ + " \"wicket-event\": \"./resource/org.apache.wicket.ajax.AbstractDefaultAjaxBehavior/res/js/wicket-event-jquery.js\",\n"
+ + " \"Wicket\": \"./resource/org.apache.wicket.ajax.AbstractDefaultAjaxBehavior/res/js/wicket-ajax-jquery.js\",\n"
+ + " \"jquery\": \"./resource/org.apache.wicket.resource.JQueryResourceReference/jquery/jquery-1.10.2.js\"\n"
+ + " },\n"
+ " \"shim\": {\n"
+ " \"wicket-event\": {\n"
+ " \"exports\": \"wicket-event\",\n"
+ " \"deps\": [\"jquery\"]\n"
+ " },\n"
+ " \"Wicket\": {\n"
+ " \"exports\": \"Wicket\",\n"
+ " \"deps\": [\"wicket-event\"]\n"
+ " }\n"
+ " },\n"
- + " \"mappings\": {}\n"
+ + " \"mountPath\": \"./requirejs\"\n"
+ "});"));
}
@Test
public void additionalAmdResourceReferenceIsRendered() throws Exception {
tester().startComponentInPage(new RequireJsConfig("id") {
@Override
public void renderHead(IHeaderResponse response) {
super.renderHead(response);
response.render(AmdJavaScriptHeaderItem.forReference(new JavaScriptResourceReference(RequireJsConfig.class, "test.js"), "test"));
}
});
tester().assertContainsNot(Pattern.quote("\"test\": \"./resource/de.agilecoders.wicket.requirejs.RequireJsConfig/test.js\""));
}
}
| false | true | public void correctMapIsRendered() throws Exception {
tester().startComponentInPage(new RequireJsConfig("id"));
tester().assertContains(Pattern.quote("require.config({\n"
+ " \"baseUrl\": \"../requirejs/\",\n"
+ " \"shim\": {\n"
+ " \"wicket-event\": {\n"
+ " \"exports\": \"wicket-event\",\n"
+ " \"deps\": [\"jquery\"]\n"
+ " },\n"
+ " \"Wicket\": {\n"
+ " \"exports\": \"Wicket\",\n"
+ " \"deps\": [\"wicket-event\"]\n"
+ " }\n"
+ " },\n"
+ " \"mappings\": {}\n"
+ "});"));
}
| public void correctMapIsRendered() throws Exception {
tester().startComponentInPage(new RequireJsConfig("id"));
tester().assertContains(Pattern.quote("require.config({\n"
+ " \"baseUrl\": \"..//\",\n"
+ " \"paths\": {\n"
+ " \"wicket-event\": \"./resource/org.apache.wicket.ajax.AbstractDefaultAjaxBehavior/res/js/wicket-event-jquery.js\",\n"
+ " \"Wicket\": \"./resource/org.apache.wicket.ajax.AbstractDefaultAjaxBehavior/res/js/wicket-ajax-jquery.js\",\n"
+ " \"jquery\": \"./resource/org.apache.wicket.resource.JQueryResourceReference/jquery/jquery-1.10.2.js\"\n"
+ " },\n"
+ " \"shim\": {\n"
+ " \"wicket-event\": {\n"
+ " \"exports\": \"wicket-event\",\n"
+ " \"deps\": [\"jquery\"]\n"
+ " },\n"
+ " \"Wicket\": {\n"
+ " \"exports\": \"Wicket\",\n"
+ " \"deps\": [\"wicket-event\"]\n"
+ " }\n"
+ " },\n"
+ " \"mountPath\": \"./requirejs\"\n"
+ "});"));
}
|
diff --git a/applications/petascope/src/main/java/petascope/wcps/server/core/DimensionPointElement.java b/applications/petascope/src/main/java/petascope/wcps/server/core/DimensionPointElement.java
index 60c2a63c..9bfff750 100644
--- a/applications/petascope/src/main/java/petascope/wcps/server/core/DimensionPointElement.java
+++ b/applications/petascope/src/main/java/petascope/wcps/server/core/DimensionPointElement.java
@@ -1,222 +1,222 @@
/*
* This file is part of rasdaman community.
*
* Rasdaman community 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.
*
* Rasdaman community 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 rasdaman community. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2003 - 2010 Peter Baumann / rasdaman GmbH.
*
* For more information please see <http://www.rasdaman.org>
* or contact Peter Baumann via <[email protected]>.
*/
package petascope.wcps.server.core;
import java.util.Iterator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.*;
import petascope.core.Metadata;
import petascope.exceptions.ExceptionCode;
import petascope.exceptions.PetascopeException;
import petascope.exceptions.WCPSException;
import petascope.util.CrsUtil;
import petascope.util.WCPSConstants;
public class DimensionPointElement extends AbstractRasNode {
Logger log = LoggerFactory.getLogger(DimensionPointElement.class);
private IRasNode child;
private ScalarExpr domain;
private AxisName axis;
private Crs crs;
private boolean finished = false;
private Node nextNode;
private Metadata meta = null; // metadata about the current coverage
private boolean transformedCoordinates = false;
private long coord;
public DimensionPointElement(Node node, XmlQuery xq, CoverageInfo covInfo)
throws WCPSException {
while ((node != null) && node.getNodeName().equals("#" + WCPSConstants.MSG_TEXT)) {
node = node.getNextSibling();
}
log.trace(node.getNodeName());
if (covInfo.getCoverageName() != null) {
// Add Bbox information from coverage metadata, may be useful
// for converting geo-coordinates to pixel-coordinates
String coverageName = covInfo.getCoverageName();
try {
meta = xq.getMetadataSource().read(coverageName);
} catch (Exception ex) {
log.error(ex.getMessage());
throw new WCPSException(ex.getMessage(), ex);
}
}
String name;
while (node != null && finished == false) {
if (node.getNodeName().equals("#" + WCPSConstants.MSG_TEXT)) {
node = node.getNextSibling();
continue;
}
// Try Axis
try {
log.trace(" " + WCPSConstants.MSG_MATCHING_AXIS_NAME);
axis = new AxisName(node, xq);
node = node.getNextSibling();
continue;
} catch (WCPSException e) {
}
// Try CRS name
try {
log.trace(" " + WCPSConstants.MSG_MATCHING_CRS);
crs = new Crs(node, xq);
node = node.getNextSibling();
if (axis == null) {
throw new WCPSException(WCPSConstants.ERRTXT_EXPECTED_AXIS_NODE);
}
continue;
} catch (WCPSException e) {
}
// TODO: how to implement DomainMetadataExpr ?
// // Try last thing
// try
// {
// domain1 = new DomainMetadataExprType(node, xq);
// counter = 1;
// continue;
// }
// catch (WCPSException e)
// {
// log.error("Failed to parse domain metadata!");
// }
// Then it must be a "slicingPosition"
if (node.getNodeName().equals(WCPSConstants.MSG_SLICING_POSITION)) {
log.trace(" " + WCPSConstants.MSG_SLICE_POSITION);
domain = new ScalarExpr(node.getFirstChild(), xq);
if (axis == null) {
throw new WCPSException(WCPSConstants.ERRTXT_EXPECTED_AXIS_NODE_SLICINGP);
}
} else {
throw new WCPSException(WCPSConstants.ERRTXT_UNEXPETCTED_NODE + ": " + node.getFirstChild().getNodeName());
}
if (axis != null && domain != null) {
finished = true;
}
if (finished == true) {
nextNode = node.getNextSibling();
}
node = node.getNextSibling();
}
if (crs == null) {
// if no CRS is specified assume native CRS -- DM 2012-mar-05
String axisName = axis.toRasQL();
DomainElement axisDomain = meta.getDomainByName(axisName);
if (axisDomain != null) {
Iterator<String> crsIt = axisDomain.getCrsSet().iterator();
if (crsIt.hasNext()) {
String crsname = crsIt.next();
log.info(WCPSConstants.MSG_USING_NATIVE_CRS + ": " + crsname);
crs = new Crs(crsname);
} else {
log.warn(WCPSConstants.WARNTXT_NO_NATIVE_CRS_P1 + " " + axisName + ", " + WCPSConstants.WARNTXT_NO_NATIVE_CRS_P2);
crs = new Crs(CrsUtil.GRID_CRS);
}
}
}
// Pixel indices are retrieved from bbox, which is stored for XY plane only.
if (finished == true) {
if (!crs.getName().equals(CrsUtil.GRID_CRS)) {
convertToPixelCoordinate();
} else {
// Set grid values which were directly set in the requests
try {
coord = (long)(domain.getSingleValue());
- this.transformedCoordinates = true;
+ this.transformedCoordinates = false;
} catch (ClassCastException ex) {
String message = ex.getMessage();
log.error(message);
throw new WCPSException(ExceptionCode.InternalComponentError, message);
}
}
}
}
/* If input coordinates are geo-, convert them to pixel coordinates. */
private void convertToPixelCoordinate() throws WCPSException {
//if (meta.getCrs() == null && crs != null && crs.getName().equals(DomainElement.WGS84_CRS)) {
if (meta.getBbox() == null && crs != null) {
throw new RuntimeException(WCPSConstants.MSG_COVERAGE + " '" + meta.getCoverageName()
//+ "' is not georeferenced with 'EPSG:4326' coordinate system.");
+ "' " + WCPSConstants.ERRTXT_IS_NOT_GEOREFERENCED);
}
if (crs != null && domain.isSingleValue()) {
//if (crs.getName().equals(DomainElement.WGS84_CRS)) {
//log.debug("CRS is '{}' and should be equal to '{}'", crs.getName(), DomainElement.WGS84_CRS);
log.debug(WCPSConstants.DEBUGTXT_REQUESTED_SUBSETTING, crs.getName(), meta.getBbox().getCrsName());
try {
this.transformedCoordinates = true;
// Convert to pixel coordinates
Double val = domain.getSingleValue();
String axisName = axis.toRasQL(); //.toUpperCase();
coord = crs.convertToPixelIndices(meta, axisName, val);
} catch (PetascopeException e) {
this.transformedCoordinates = false;
log.error(WCPSConstants.ERRTXT_ERROR_WHILE_TRANSFORMING);
throw new WCPSException(e.getExceptionCode(), e.getMessage());
}
//}
} // else no crs was embedded in the slice expression
}
@Override
public String toRasQL() {
return child.toRasQL();
}
public Node getNextNode() {
return nextNode;
}
public String getAxisName() {
return this.axis.toRasQL();
}
public String getCrsName() {
return this.crs.toRasQL();
}
public String getSlicingPosition() {
if (transformedCoordinates) {
return String.valueOf(coord);
} else {
return this.domain.toRasQL();
}
}
}
| true | true | public DimensionPointElement(Node node, XmlQuery xq, CoverageInfo covInfo)
throws WCPSException {
while ((node != null) && node.getNodeName().equals("#" + WCPSConstants.MSG_TEXT)) {
node = node.getNextSibling();
}
log.trace(node.getNodeName());
if (covInfo.getCoverageName() != null) {
// Add Bbox information from coverage metadata, may be useful
// for converting geo-coordinates to pixel-coordinates
String coverageName = covInfo.getCoverageName();
try {
meta = xq.getMetadataSource().read(coverageName);
} catch (Exception ex) {
log.error(ex.getMessage());
throw new WCPSException(ex.getMessage(), ex);
}
}
String name;
while (node != null && finished == false) {
if (node.getNodeName().equals("#" + WCPSConstants.MSG_TEXT)) {
node = node.getNextSibling();
continue;
}
// Try Axis
try {
log.trace(" " + WCPSConstants.MSG_MATCHING_AXIS_NAME);
axis = new AxisName(node, xq);
node = node.getNextSibling();
continue;
} catch (WCPSException e) {
}
// Try CRS name
try {
log.trace(" " + WCPSConstants.MSG_MATCHING_CRS);
crs = new Crs(node, xq);
node = node.getNextSibling();
if (axis == null) {
throw new WCPSException(WCPSConstants.ERRTXT_EXPECTED_AXIS_NODE);
}
continue;
} catch (WCPSException e) {
}
// TODO: how to implement DomainMetadataExpr ?
// // Try last thing
// try
// {
// domain1 = new DomainMetadataExprType(node, xq);
// counter = 1;
// continue;
// }
// catch (WCPSException e)
// {
// log.error("Failed to parse domain metadata!");
// }
// Then it must be a "slicingPosition"
if (node.getNodeName().equals(WCPSConstants.MSG_SLICING_POSITION)) {
log.trace(" " + WCPSConstants.MSG_SLICE_POSITION);
domain = new ScalarExpr(node.getFirstChild(), xq);
if (axis == null) {
throw new WCPSException(WCPSConstants.ERRTXT_EXPECTED_AXIS_NODE_SLICINGP);
}
} else {
throw new WCPSException(WCPSConstants.ERRTXT_UNEXPETCTED_NODE + ": " + node.getFirstChild().getNodeName());
}
if (axis != null && domain != null) {
finished = true;
}
if (finished == true) {
nextNode = node.getNextSibling();
}
node = node.getNextSibling();
}
if (crs == null) {
// if no CRS is specified assume native CRS -- DM 2012-mar-05
String axisName = axis.toRasQL();
DomainElement axisDomain = meta.getDomainByName(axisName);
if (axisDomain != null) {
Iterator<String> crsIt = axisDomain.getCrsSet().iterator();
if (crsIt.hasNext()) {
String crsname = crsIt.next();
log.info(WCPSConstants.MSG_USING_NATIVE_CRS + ": " + crsname);
crs = new Crs(crsname);
} else {
log.warn(WCPSConstants.WARNTXT_NO_NATIVE_CRS_P1 + " " + axisName + ", " + WCPSConstants.WARNTXT_NO_NATIVE_CRS_P2);
crs = new Crs(CrsUtil.GRID_CRS);
}
}
}
// Pixel indices are retrieved from bbox, which is stored for XY plane only.
if (finished == true) {
if (!crs.getName().equals(CrsUtil.GRID_CRS)) {
convertToPixelCoordinate();
} else {
// Set grid values which were directly set in the requests
try {
coord = (long)(domain.getSingleValue());
this.transformedCoordinates = true;
} catch (ClassCastException ex) {
String message = ex.getMessage();
log.error(message);
throw new WCPSException(ExceptionCode.InternalComponentError, message);
}
}
}
}
| public DimensionPointElement(Node node, XmlQuery xq, CoverageInfo covInfo)
throws WCPSException {
while ((node != null) && node.getNodeName().equals("#" + WCPSConstants.MSG_TEXT)) {
node = node.getNextSibling();
}
log.trace(node.getNodeName());
if (covInfo.getCoverageName() != null) {
// Add Bbox information from coverage metadata, may be useful
// for converting geo-coordinates to pixel-coordinates
String coverageName = covInfo.getCoverageName();
try {
meta = xq.getMetadataSource().read(coverageName);
} catch (Exception ex) {
log.error(ex.getMessage());
throw new WCPSException(ex.getMessage(), ex);
}
}
String name;
while (node != null && finished == false) {
if (node.getNodeName().equals("#" + WCPSConstants.MSG_TEXT)) {
node = node.getNextSibling();
continue;
}
// Try Axis
try {
log.trace(" " + WCPSConstants.MSG_MATCHING_AXIS_NAME);
axis = new AxisName(node, xq);
node = node.getNextSibling();
continue;
} catch (WCPSException e) {
}
// Try CRS name
try {
log.trace(" " + WCPSConstants.MSG_MATCHING_CRS);
crs = new Crs(node, xq);
node = node.getNextSibling();
if (axis == null) {
throw new WCPSException(WCPSConstants.ERRTXT_EXPECTED_AXIS_NODE);
}
continue;
} catch (WCPSException e) {
}
// TODO: how to implement DomainMetadataExpr ?
// // Try last thing
// try
// {
// domain1 = new DomainMetadataExprType(node, xq);
// counter = 1;
// continue;
// }
// catch (WCPSException e)
// {
// log.error("Failed to parse domain metadata!");
// }
// Then it must be a "slicingPosition"
if (node.getNodeName().equals(WCPSConstants.MSG_SLICING_POSITION)) {
log.trace(" " + WCPSConstants.MSG_SLICE_POSITION);
domain = new ScalarExpr(node.getFirstChild(), xq);
if (axis == null) {
throw new WCPSException(WCPSConstants.ERRTXT_EXPECTED_AXIS_NODE_SLICINGP);
}
} else {
throw new WCPSException(WCPSConstants.ERRTXT_UNEXPETCTED_NODE + ": " + node.getFirstChild().getNodeName());
}
if (axis != null && domain != null) {
finished = true;
}
if (finished == true) {
nextNode = node.getNextSibling();
}
node = node.getNextSibling();
}
if (crs == null) {
// if no CRS is specified assume native CRS -- DM 2012-mar-05
String axisName = axis.toRasQL();
DomainElement axisDomain = meta.getDomainByName(axisName);
if (axisDomain != null) {
Iterator<String> crsIt = axisDomain.getCrsSet().iterator();
if (crsIt.hasNext()) {
String crsname = crsIt.next();
log.info(WCPSConstants.MSG_USING_NATIVE_CRS + ": " + crsname);
crs = new Crs(crsname);
} else {
log.warn(WCPSConstants.WARNTXT_NO_NATIVE_CRS_P1 + " " + axisName + ", " + WCPSConstants.WARNTXT_NO_NATIVE_CRS_P2);
crs = new Crs(CrsUtil.GRID_CRS);
}
}
}
// Pixel indices are retrieved from bbox, which is stored for XY plane only.
if (finished == true) {
if (!crs.getName().equals(CrsUtil.GRID_CRS)) {
convertToPixelCoordinate();
} else {
// Set grid values which were directly set in the requests
try {
coord = (long)(domain.getSingleValue());
this.transformedCoordinates = false;
} catch (ClassCastException ex) {
String message = ex.getMessage();
log.error(message);
throw new WCPSException(ExceptionCode.InternalComponentError, message);
}
}
}
}
|
diff --git a/org.eclipse.swtbot.eclipse.finder/src/org/eclipse/swtbot/eclipse/finder/widgets/SWTBotView.java b/org.eclipse.swtbot.eclipse.finder/src/org/eclipse/swtbot/eclipse/finder/widgets/SWTBotView.java
index 06c25f4..5c0bd1b 100644
--- a/org.eclipse.swtbot.eclipse.finder/src/org/eclipse/swtbot/eclipse/finder/widgets/SWTBotView.java
+++ b/org.eclipse.swtbot.eclipse.finder/src/org/eclipse/swtbot/eclipse/finder/widgets/SWTBotView.java
@@ -1,85 +1,85 @@
/*******************************************************************************
* Copyright (c) 2008 Ketan Padegaonkar 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:
* Ketan Padegaonkar - initial API and implementation
*******************************************************************************/
package org.eclipse.swtbot.eclipse.finder.widgets;
import static org.eclipse.swtbot.swt.finder.finders.UIThreadRunnable.syncExec;
import static org.hamcrest.Matchers.anything;
import javax.swing.text.View;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Widget;
import org.eclipse.swtbot.eclipse.finder.SWTEclipseBot;
import org.eclipse.swtbot.eclipse.finder.exceptions.WorkbenchPartNotActiveException;
import org.eclipse.swtbot.swt.finder.exceptions.WidgetNotFoundException;
import org.eclipse.swtbot.swt.finder.results.VoidResult;
import org.eclipse.ui.IViewReference;
/**
* This represents the eclipse {@link View} item.
*
* @author Ketan Padegaonkar <KetanPadegaonkar [at] gmail [dot] com>
* @version $Id$
*/
public class SWTBotView extends SWTBotWorkbenchPart<IViewReference> {
private Widget widget;
/**
* @param partReference the view reference representing this view.
* @param bot the bot that's used to find controls within this view.
* @since 2.0
*/
public SWTBotView(IViewReference partReference, SWTEclipseBot bot) {
super(partReference, bot);
}
public void setFocus() {
syncExec(new VoidResult() {
public void run() {
- ((Control) widget).setFocus();
+ ((Control) getWidget()).setFocus();
}
});
}
/**
* @return the view reference for this view.
*/
public IViewReference getViewReference() {
return partReference;
}
/**
* The parent widget inside the partReference, that is the container for all controls within the view. If you want
* to look for a particular widget within the part, this is a good place to start searching for the widget.
* <p>
* <b>NOTE:</b> Clients must ensure that the view is active at the time of making this call. If the view is not
* active, then this method will throw a {@link WidgetNotFoundException}.
* </p>
*
* @return the parent widget in the view.
* @throws WorkbenchPartNotActiveException if the view was not active.
* @see #findWidget(org.hamcrest.Matcher)
* @see #assertActive()
* @see #show()
*/
public Widget getWidget() {
show();
if (widget == null)
widget = findWidget(anything());
return widget;
}
public boolean isActive() {
return partReference.getPage().getActivePartReference() == partReference;
}
}
| true | true | public void setFocus() {
syncExec(new VoidResult() {
public void run() {
((Control) widget).setFocus();
}
});
}
| public void setFocus() {
syncExec(new VoidResult() {
public void run() {
((Control) getWidget()).setFocus();
}
});
}
|
diff --git a/deegree-misc/deegree-portnumber-plugin/src/main/java/org/deegree/maven/PortnumberPlugin.java b/deegree-misc/deegree-portnumber-plugin/src/main/java/org/deegree/maven/PortnumberPlugin.java
index 2790bf0808..b61d9b15ad 100644
--- a/deegree-misc/deegree-portnumber-plugin/src/main/java/org/deegree/maven/PortnumberPlugin.java
+++ b/deegree-misc/deegree-portnumber-plugin/src/main/java/org/deegree/maven/PortnumberPlugin.java
@@ -1,118 +1,131 @@
//$HeadURL$
/*----------------------------------------------------------------------------
This file is part of deegree, http://deegree.org/
Copyright (C) 2001-2010 by:
- Department of Geography, University of Bonn -
and
- lat/lon GmbH -
This library 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 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.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation, Inc.,
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact information:
lat/lon GmbH
Aennchenstr. 19, 53177 Bonn
Germany
http://lat-lon.de/
Department of Geography, University of Bonn
Prof. Dr. Klaus Greve
Postfach 1147, 53001 Bonn
Germany
http://www.geographie.uni-bonn.de/deegree/
e-mail: [email protected]
----------------------------------------------------------------------------*/
package org.deegree.maven;
import static org.apache.commons.io.IOUtils.closeQuietly;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.nio.channels.FileLock;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.project.MavenProject;
/**
* @goal generate
*
* @author <a href="mailto:[email protected]">Andreas Schmitz</a>
* @author last edited by: $Author$
*
* @version $Revision$, $Date$
*/
public class PortnumberPlugin extends AbstractMojo {
/**
* @parameter default-value="${project}"
* @required
* @readonly
*/
private MavenProject project;
public void execute()
throws MojoExecutionException, MojoFailureException {
PrintStream out = null;
BufferedReader reader = null;
FileLock lock = null;
try {
File portfile = new File( System.getProperty( "java.io.tmpdir" ) + "/portnumbers" );
int port = 1025;
if ( portfile.exists() ) {
FileInputStream fis = new FileInputStream( portfile );
reader = new BufferedReader( new InputStreamReader( fis ) );
- port = Integer.parseInt( reader.readLine() ) + 1;
+ boolean read = false;
+ while ( !read ) {
+ try {
+ port = Integer.parseInt( reader.readLine() ) + 1;
+ read = true;
+ } catch ( NumberFormatException e ) {
+ // someone is currently writing
+ try {
+ Thread.sleep( 100 );
+ } catch ( InterruptedException e1 ) {
+ return;
+ }
+ }
+ }
reader.close();
}
if ( port > 18000 ) {
port = 1025;
}
getLog().info( "Using portnumber " + port + " for this run." );
project.getProperties().put( "portnumber", "" + port );
FileOutputStream fos = new FileOutputStream( portfile );
out = new PrintStream( fos );
while ( ( lock = fos.getChannel().tryLock() ) == null ) {
try {
Thread.sleep( 100 );
} catch ( InterruptedException e ) {
- // then we die
+ return;
}
}
out.println( "" + port );
lock.release();
out.close();
} catch ( FileNotFoundException e ) {
getLog().error( e );
} catch ( NumberFormatException e ) {
getLog().error( e );
} catch ( IOException e ) {
getLog().error( e );
} finally {
closeQuietly( out );
closeQuietly( reader );
}
}
}
| false | true | public void execute()
throws MojoExecutionException, MojoFailureException {
PrintStream out = null;
BufferedReader reader = null;
FileLock lock = null;
try {
File portfile = new File( System.getProperty( "java.io.tmpdir" ) + "/portnumbers" );
int port = 1025;
if ( portfile.exists() ) {
FileInputStream fis = new FileInputStream( portfile );
reader = new BufferedReader( new InputStreamReader( fis ) );
port = Integer.parseInt( reader.readLine() ) + 1;
reader.close();
}
if ( port > 18000 ) {
port = 1025;
}
getLog().info( "Using portnumber " + port + " for this run." );
project.getProperties().put( "portnumber", "" + port );
FileOutputStream fos = new FileOutputStream( portfile );
out = new PrintStream( fos );
while ( ( lock = fos.getChannel().tryLock() ) == null ) {
try {
Thread.sleep( 100 );
} catch ( InterruptedException e ) {
// then we die
}
}
out.println( "" + port );
lock.release();
out.close();
} catch ( FileNotFoundException e ) {
getLog().error( e );
} catch ( NumberFormatException e ) {
getLog().error( e );
} catch ( IOException e ) {
getLog().error( e );
} finally {
closeQuietly( out );
closeQuietly( reader );
}
}
| public void execute()
throws MojoExecutionException, MojoFailureException {
PrintStream out = null;
BufferedReader reader = null;
FileLock lock = null;
try {
File portfile = new File( System.getProperty( "java.io.tmpdir" ) + "/portnumbers" );
int port = 1025;
if ( portfile.exists() ) {
FileInputStream fis = new FileInputStream( portfile );
reader = new BufferedReader( new InputStreamReader( fis ) );
boolean read = false;
while ( !read ) {
try {
port = Integer.parseInt( reader.readLine() ) + 1;
read = true;
} catch ( NumberFormatException e ) {
// someone is currently writing
try {
Thread.sleep( 100 );
} catch ( InterruptedException e1 ) {
return;
}
}
}
reader.close();
}
if ( port > 18000 ) {
port = 1025;
}
getLog().info( "Using portnumber " + port + " for this run." );
project.getProperties().put( "portnumber", "" + port );
FileOutputStream fos = new FileOutputStream( portfile );
out = new PrintStream( fos );
while ( ( lock = fos.getChannel().tryLock() ) == null ) {
try {
Thread.sleep( 100 );
} catch ( InterruptedException e ) {
return;
}
}
out.println( "" + port );
lock.release();
out.close();
} catch ( FileNotFoundException e ) {
getLog().error( e );
} catch ( NumberFormatException e ) {
getLog().error( e );
} catch ( IOException e ) {
getLog().error( e );
} finally {
closeQuietly( out );
closeQuietly( reader );
}
}
|
diff --git a/source/src/net/grinder/engine/process/instrumenter/dcr/Jython22Instrumenter.java b/source/src/net/grinder/engine/process/instrumenter/dcr/Jython22Instrumenter.java
index fef51118..be7edce9 100644
--- a/source/src/net/grinder/engine/process/instrumenter/dcr/Jython22Instrumenter.java
+++ b/source/src/net/grinder/engine/process/instrumenter/dcr/Jython22Instrumenter.java
@@ -1,160 +1,161 @@
// Copyright (C) 2009 Philip Aston
// All rights reserved.
//
// This file is part of The Grinder software distribution. Refer to
// the file LICENSE which is part of The Grinder distribution for
// licensing details. The Grinder distribution is available on the
// Internet at http://grinder.sourceforge.net/
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS 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
// COPYRIGHT HOLDERS OR 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.
package net.grinder.engine.process.instrumenter.dcr;
import java.lang.reflect.Method;
import net.grinder.engine.process.ScriptEngine.Recorder;
import net.grinder.script.NotWrappableTypeException;
import net.grinder.util.weave.Weaver;
import net.grinder.util.weave.Weaver.TargetSource;
import org.python.core.PyClass;
import org.python.core.PyFunction;
import org.python.core.PyInstance;
import org.python.core.PyMethod;
import org.python.core.PyObject;
import org.python.core.PyProxy;
import org.python.core.PyReflectedFunction;
/**
* DCRInstrumenter for Jython 2.1, 2.2.
*
* @author Philip Aston
* @version $Revision:$
*/
final class Jython22Instrumenter extends DCRInstrumenter {
/**
* Constructor for DCRInstrumenter.
*
* @param weaver The weaver.
* @param recorderRegistry The recorder registry.
*/
public Jython22Instrumenter(Weaver weaver,
RecorderRegistry recorderRegistry) {
super(weaver, recorderRegistry);
}
/**
* {@inheritDoc}
*/
public String getDescription() {
return "byte code transforming instrumenter for Jython 2.1/2.2";
}
@Override
protected Object instrument(Object target, Recorder recorder)
throws NotWrappableTypeException {
if (target instanceof PyObject) {
// Jython object.
if (target instanceof PyInstance) {
instrumentPublicMethodsByName(target,
"invoke",
TargetSource.FIRST_PARAMETER,
recorder,
true);
}
else if (target instanceof PyFunction) {
instrumentPublicMethodsByName(target,
"__call__",
TargetSource.FIRST_PARAMETER,
recorder,
false);
}
else if (target instanceof PyMethod) {
instrumentPublicMethodsByName(target,
"__call__",
TargetSource.FIRST_PARAMETER,
recorder,
false);
}
else if (target instanceof PyReflectedFunction) {
final Method callMethod;
try {
callMethod = PyReflectedFunction.class.getMethod("__call__",
- PyObject.class);
+ PyObject[].class,
+ String[].class);
}
catch (Exception e) {
throw new NotWrappableTypeException(
"Correct version of Jython?: " + e.getLocalizedMessage());
}
instrument(target, callMethod, TargetSource.FIRST_PARAMETER, recorder);
}
else if (target instanceof PyClass) {
instrumentPublicMethodsByName(target,
"__call__",
TargetSource.FIRST_PARAMETER,
recorder,
false);
}
else {
// Fail, rather than guess a generic approach.
throw new NotWrappableTypeException("Unknown PyObject:" +
target.getClass());
}
}
else if (target instanceof PyProxy) {
// Jython object that extends a Java class.
// We can't just use the Java wrapping, since then we'd miss the
// Jython methods.
final PyObject pyInstance = ((PyProxy)target)._getPyInstance();
instrumentPublicMethodsByName(pyInstance,
"invoke",
TargetSource.FIRST_PARAMETER,
recorder,
true);
}
else {
return null;
}
return target;
}
private void instrumentPublicMethodsByName(Object target,
String methodName,
TargetSource targetSource,
Recorder recorder,
boolean includeSuperClassMethods)
throws NotWrappableTypeException {
// getMethods() includes superclass methods.
for (Method method : target.getClass().getMethods()) {
if (!includeSuperClassMethods &&
target.getClass() != method.getDeclaringClass()) {
continue;
}
if (!method.getName().equals(methodName)) {
continue;
}
instrument(target, method, targetSource, recorder);
}
}
}
| true | true | protected Object instrument(Object target, Recorder recorder)
throws NotWrappableTypeException {
if (target instanceof PyObject) {
// Jython object.
if (target instanceof PyInstance) {
instrumentPublicMethodsByName(target,
"invoke",
TargetSource.FIRST_PARAMETER,
recorder,
true);
}
else if (target instanceof PyFunction) {
instrumentPublicMethodsByName(target,
"__call__",
TargetSource.FIRST_PARAMETER,
recorder,
false);
}
else if (target instanceof PyMethod) {
instrumentPublicMethodsByName(target,
"__call__",
TargetSource.FIRST_PARAMETER,
recorder,
false);
}
else if (target instanceof PyReflectedFunction) {
final Method callMethod;
try {
callMethod = PyReflectedFunction.class.getMethod("__call__",
PyObject.class);
}
catch (Exception e) {
throw new NotWrappableTypeException(
"Correct version of Jython?: " + e.getLocalizedMessage());
}
instrument(target, callMethod, TargetSource.FIRST_PARAMETER, recorder);
}
else if (target instanceof PyClass) {
instrumentPublicMethodsByName(target,
"__call__",
TargetSource.FIRST_PARAMETER,
recorder,
false);
}
else {
// Fail, rather than guess a generic approach.
throw new NotWrappableTypeException("Unknown PyObject:" +
target.getClass());
}
}
else if (target instanceof PyProxy) {
// Jython object that extends a Java class.
// We can't just use the Java wrapping, since then we'd miss the
// Jython methods.
final PyObject pyInstance = ((PyProxy)target)._getPyInstance();
instrumentPublicMethodsByName(pyInstance,
"invoke",
TargetSource.FIRST_PARAMETER,
recorder,
true);
}
else {
return null;
}
return target;
}
| protected Object instrument(Object target, Recorder recorder)
throws NotWrappableTypeException {
if (target instanceof PyObject) {
// Jython object.
if (target instanceof PyInstance) {
instrumentPublicMethodsByName(target,
"invoke",
TargetSource.FIRST_PARAMETER,
recorder,
true);
}
else if (target instanceof PyFunction) {
instrumentPublicMethodsByName(target,
"__call__",
TargetSource.FIRST_PARAMETER,
recorder,
false);
}
else if (target instanceof PyMethod) {
instrumentPublicMethodsByName(target,
"__call__",
TargetSource.FIRST_PARAMETER,
recorder,
false);
}
else if (target instanceof PyReflectedFunction) {
final Method callMethod;
try {
callMethod = PyReflectedFunction.class.getMethod("__call__",
PyObject[].class,
String[].class);
}
catch (Exception e) {
throw new NotWrappableTypeException(
"Correct version of Jython?: " + e.getLocalizedMessage());
}
instrument(target, callMethod, TargetSource.FIRST_PARAMETER, recorder);
}
else if (target instanceof PyClass) {
instrumentPublicMethodsByName(target,
"__call__",
TargetSource.FIRST_PARAMETER,
recorder,
false);
}
else {
// Fail, rather than guess a generic approach.
throw new NotWrappableTypeException("Unknown PyObject:" +
target.getClass());
}
}
else if (target instanceof PyProxy) {
// Jython object that extends a Java class.
// We can't just use the Java wrapping, since then we'd miss the
// Jython methods.
final PyObject pyInstance = ((PyProxy)target)._getPyInstance();
instrumentPublicMethodsByName(pyInstance,
"invoke",
TargetSource.FIRST_PARAMETER,
recorder,
true);
}
else {
return null;
}
return target;
}
|
diff --git a/modules/org.restlet/src/org/restlet/resource/ServerResource.java b/modules/org.restlet/src/org/restlet/resource/ServerResource.java
index 1dfee2323..d6bee8c4a 100644
--- a/modules/org.restlet/src/org/restlet/resource/ServerResource.java
+++ b/modules/org.restlet/src/org/restlet/resource/ServerResource.java
@@ -1,1471 +1,1469 @@
/**
* Copyright 2005-2009 Noelios Technologies.
*
* The contents of this file are subject to the terms of one of the following
* open source licenses: LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL 1.0 (the
* "Licenses"). You can select the license that you prefer but you may not use
* this file except in compliance with one of these Licenses.
*
* You can obtain a copy of the LGPL 3.0 license at
* http://www.opensource.org/licenses/lgpl-3.0.html
*
* You can obtain a copy of the LGPL 2.1 license at
* http://www.opensource.org/licenses/lgpl-2.1.php
*
* You can obtain a copy of the CDDL 1.0 license at
* http://www.opensource.org/licenses/cddl1.php
*
* You can obtain a copy of the EPL 1.0 license at
* http://www.opensource.org/licenses/eclipse-1.0.php
*
* See the Licenses for the specific language governing permissions and
* limitations under the Licenses.
*
* Alternatively, you can obtain a royalty free commercial license with less
* limitations, transferable or non-transferable, directly at
* http://www.noelios.com/products/restlet-engine
*
* Restlet is a registered trademark of Noelios Technologies.
*/
package org.restlet.resource;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;
import org.restlet.Context;
import org.restlet.Request;
import org.restlet.Response;
import org.restlet.Restlet;
import org.restlet.Uniform;
import org.restlet.data.ChallengeRequest;
import org.restlet.data.ClientInfo;
import org.restlet.data.CookieSetting;
import org.restlet.data.Dimension;
import org.restlet.data.Method;
import org.restlet.data.Reference;
import org.restlet.data.ServerInfo;
import org.restlet.data.Status;
import org.restlet.data.Tag;
import org.restlet.engine.resource.AnnotationInfo;
import org.restlet.engine.resource.AnnotationUtils;
import org.restlet.engine.resource.VariantInfo;
import org.restlet.representation.Representation;
import org.restlet.representation.RepresentationInfo;
import org.restlet.representation.Variant;
import org.restlet.service.ConverterService;
import org.restlet.service.MetadataService;
import org.restlet.util.Series;
/**
* Base class for server-side resources. It is a full replacement for the
* deprecated {@link Resource} class.<br>
* <br>
* Concurrency note: contrary to the {@link org.restlet.Uniform} class and its
* main {@link Restlet} subclass where a single instance can handle several
* calls concurrently, one instance of {@link ServerResource} is created for
* each call handled and accessed by only one thread at a time.
*
* @author Jerome Louvel
*/
public abstract class ServerResource extends UniformResource {
/** Indicates if annotations are supported. */
private volatile boolean annotated;
/** Indicates if conditional handling is enabled. */
private volatile boolean conditional;
/** Indicates if the identified resource exists. */
private volatile boolean existing;
/** Indicates if content negotiation of response entities is enabled. */
private volatile boolean negotiated;
/** Modifiable list of variants. */
private volatile List<Variant> variants;
/**
* Initializer block to ensure that the basic properties are initialized
* consistently across constructors.
*/
{
this.annotated = true;
this.conditional = true;
this.existing = true;
this.negotiated = true;
this.variants = null;
}
/**
* Default constructor. Note that the
* {@link #init(Context, Request, Response)}() method will be invoked right
* after the creation of the resource.
*/
public ServerResource() {
}
/**
* Deletes the resource and all its representations. This method is only
* invoked if content negotiation has been disabled as indicated by the
* {@link #isNegotiated()}, otherwise the {@link #delete(Variant)} method is
* invoked.<br>
* <br>
* The default behavior is to set the response status to
* {@link Status#CLIENT_ERROR_METHOD_NOT_ALLOWED}.
*
* @return The optional response entity.
* @throws ResourceException
* @see <a
* href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.7"
* >HTTP DELETE method</a>
*/
protected Representation delete() throws ResourceException {
Representation result = null;
AnnotationInfo annotationInfo = getAnnotation(Method.DELETE);
if (annotationInfo != null) {
result = doHandle(annotationInfo);
} else {
setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED);
}
return result;
}
/**
* Deletes the resource and all its representations. A variant parameter is
* passed to indicate which representation should be returned if any.<br>
* <br>
* This method is only invoked if content negotiation has been enabled as
* indicated by the {@link #isNegotiated()}, otherwise the {@link #delete()}
* method is invoked.<br>
* <br>
* The default behavior is to set the response status to
* {@link Status#CLIENT_ERROR_METHOD_NOT_ALLOWED}.
*
* @param variant
* The variant of the response entity.
* @return The optional response entity.
* @throws ResourceException
* @see #get(Variant)
* @see <a
* href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.7"
* >HTTP DELETE method</a>
*/
protected Representation delete(Variant variant) throws ResourceException {
Representation result = null;
if (variant instanceof VariantInfo) {
result = doHandle(((VariantInfo) variant).getAnnotationInfo(),
variant);
} else {
setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED);
}
return result;
}
/**
* Describes the available variants to help client-side content negotiation.
* Return null by default.
*
* @return The description of available variants.
*/
protected Representation describeVariants() {
Representation result = null;
// The list of all variants is transmitted to the client
// final ReferenceList refs = new ReferenceList(variants.size());
// for (final Variant variant : variants) {
// if (variant.getIdentifier() != null) {
// refs.add(variant.getIdentifier());
// }
// }
//
// result = refs.getTextRepresentation();
return result;
}
/**
* Handles a call by first verifying the optional request conditions and
* continue the processing if possible. Note that in order to evaluate those
* conditions, {@link #getInfo()} or {@link #getInfo(Variant)} methods might
* be invoked.
*
* @return The response entity.
* @throws ResourceException
*/
protected Representation doConditionalHandle() throws ResourceException {
Representation result = null;
if (getConditions().hasSome()) {
if (!isExisting() && getConditions().getMatch().contains(Tag.ALL)) {
setStatus(Status.CLIENT_ERROR_PRECONDITION_FAILED,
"A non existing resource can't match any tag.");
} else {
RepresentationInfo resultInfo = null;
if (isNegotiated()) {
resultInfo = doGetInfo(getPreferredVariant(getVariants()));
} else {
resultInfo = doGetInfo();
}
if (resultInfo == null) {
if ((getStatus() == null)
|| (getStatus().isSuccess() && !Status.SUCCESS_NO_CONTENT
.equals(getStatus()))) {
setStatus(Status.CLIENT_ERROR_NOT_FOUND);
} else {
// Keep the current status as the developer might prefer
// a special status like 'method not authorized'.
}
} else {
Status status = getConditions().getStatus(getMethod(),
resultInfo);
if (status != null) {
setStatus(status);
}
}
if ((getStatus() != null) && getStatus().isSuccess()) {
// Conditions were passed successfully, continue the normal
- // processing
- // If the representation info obtained to test the
- // conditions
- // is in fact a full representation, return it immediately
- // for optimization purpose
+ // processing. If the representation info obtained to test
+ // the conditions is in fact a full representation, return
+ // it immediately for optimization purpose
if ((Method.GET.equals(getMethod()) || Method.HEAD
.equals(getMethod()))
&& resultInfo instanceof Representation) {
result = (Representation) resultInfo;
} else {
if (isNegotiated()) {
result = doNegotiatedHandle();
} else {
result = doHandle();
}
}
}
}
} else {
if (isNegotiated()) {
result = doNegotiatedHandle();
} else {
result = doHandle();
}
}
return result;
}
/**
* Returns a descriptor of the response entity returned by a
* {@link Method#GET} call.
*
* @return The response entity.
* @throws ResourceException
*/
private RepresentationInfo doGetInfo() throws ResourceException {
RepresentationInfo result = null;
AnnotationInfo annotationInfo = getAnnotation(Method.GET);
if (annotationInfo != null) {
result = doHandle(annotationInfo);
} else {
result = getInfo();
}
return result;
}
/**
* Returns a descriptor of the response entity returned by a negotiated
* {@link Method#GET} call.
*
* @param variant
* The selected variant descriptor.
* @return The response entity descriptor.
* @throws ResourceException
*/
private RepresentationInfo doGetInfo(Variant variant)
throws ResourceException {
RepresentationInfo result = null;
if (variant != null) {
if (variant instanceof VariantInfo) {
result = doHandle(((VariantInfo) variant).getAnnotationInfo(),
variant);
} else if (variant instanceof RepresentationInfo) {
result = (RepresentationInfo) variant;
} else {
result = getInfo(variant);
}
} else {
result = doGetInfo();
}
return result;
}
/**
* Effectively handles a call without content negotiation of the response
* entity. The default behavior is to dispatch the call to one of the
* {@link #get()}, {@link #post(Representation)},
* {@link #put(Representation)}, {@link #delete()}, {@link #head()} or
* {@link #options()} methods.
*
* @return The response entity.
* @throws ResourceException
*/
protected Representation doHandle() throws ResourceException {
Representation result = null;
Method method = getMethod();
if (method == null) {
setStatus(Status.CLIENT_ERROR_BAD_REQUEST, "No method specified");
} else {
if (method.equals(Method.PUT)) {
result = put(getRequestEntity());
} else if (isExisting()) {
if (method.equals(Method.GET)) {
result = get();
} else if (method.equals(Method.POST)) {
result = post(getRequestEntity());
} else if (method.equals(Method.DELETE)) {
result = delete();
} else if (method.equals(Method.HEAD)) {
result = head();
} else if (method.equals(Method.OPTIONS)) {
result = options();
} else {
AnnotationInfo annotationInfo = getAnnotation(method);
if (annotationInfo != null) {
result = doHandle(annotationInfo);
} else {
setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED);
}
}
} else {
setStatus(Status.CLIENT_ERROR_NOT_FOUND);
}
}
return result;
}
/**
* Effectively handle a call using an annotated method.
*
* @param annotationInfo
* The annotation descriptor.
* @return The response entity.
* @throws ResourceException
*/
private Representation doHandle(AnnotationInfo annotationInfo)
throws ResourceException {
Representation result = null;
ConverterService cs = getConverterService();
Class<?>[] parameterTypes = annotationInfo.getJavaInputTypes();
List<Object> parameters = null;
Object resultObject = null;
try {
if (parameterTypes.length > 0) {
parameters = new ArrayList<Object>();
for (Class<?> parameterType : parameterTypes) {
if (getRequestEntity() != null) {
try {
parameters.add(cs.toObject(getRequestEntity(),
parameterType, this));
} catch (IOException e) {
e.printStackTrace();
parameters.add(null);
}
} else {
parameters.add(null);
}
}
// Actually invoke the method
resultObject = annotationInfo.getJavaMethod().invoke(this,
parameters.toArray());
} else {
// Actually invoke the method
resultObject = annotationInfo.getJavaMethod().invoke(this);
}
} catch (IllegalArgumentException e) {
throw new ResourceException(e);
} catch (IllegalAccessException e) {
throw new ResourceException(e);
} catch (InvocationTargetException e) {
if (e.getTargetException() instanceof ResourceException) {
throw (ResourceException) e.getTargetException();
} else {
throw new ResourceException(e.getTargetException());
}
}
if (resultObject != null) {
result = cs.toRepresentation(resultObject);
}
return result;
}
/**
* Effectively handles a call with content negotiation of the response
* entity using an annotated method.
*
* @param annotationInfo
* The annotation descriptor.
* @param variant
* The response variant expected.
* @return The response entity.
* @throws ResourceException
*/
private Representation doHandle(AnnotationInfo annotationInfo,
Variant variant) throws ResourceException {
Representation result = null;
ConverterService cs = getConverterService();
Object resultObject = null;
try {
if ((annotationInfo.getJavaInputTypes() != null)
&& (annotationInfo.getJavaInputTypes().length > 0)) {
List<Object> parameters = new ArrayList<Object>();
Object parameter = null;
for (Class<?> param : annotationInfo.getJavaInputTypes()) {
if (Variant.class.equals(param)) {
parameters.add(variant);
} else {
if (getRequestEntity().isAvailable()) {
try {
parameter = cs.toObject(getRequestEntity(),
param, this);
} catch (IOException e) {
parameter = null;
}
if (parameter == null) {
throw new ResourceException(
Status.CLIENT_ERROR_UNSUPPORTED_MEDIA_TYPE);
}
} else {
parameter = null;
}
parameters.add(parameter);
}
}
resultObject = annotationInfo.getJavaMethod().invoke(this,
parameters.toArray());
} else {
resultObject = annotationInfo.getJavaMethod().invoke(this);
}
result = cs.toRepresentation(resultObject, variant, this);
} catch (IllegalArgumentException e) {
throw new ResourceException(e);
} catch (IllegalAccessException e) {
throw new ResourceException(e);
} catch (InvocationTargetException e) {
if (e.getTargetException() instanceof ResourceException) {
throw (ResourceException) e.getTargetException();
} else {
throw new ResourceException(e.getTargetException());
}
}
return result;
}
/**
* Effectively handles a call with content negotiation of the response
* entity. The default behavior is to dispatch the call to one of the
* {@link #get(Variant)}, {@link #post(Representation,Variant)},
* {@link #put(Representation,Variant)}, {@link #delete(Variant)},
* {@link #head(Variant)} or {@link #options(Variant)} methods.
*
* @param variant
* The response variant expected.
* @return The response entity.
* @throws ResourceException
*/
protected Representation doHandle(Variant variant) throws ResourceException {
Representation result = null;
Method method = getMethod();
if (method == null) {
setStatus(Status.CLIENT_ERROR_BAD_REQUEST, "No method specified");
} else {
if (method.equals(Method.PUT)) {
result = put(getRequestEntity(), variant);
} else if (isExisting()) {
if (method.equals(Method.GET)) {
if (variant instanceof Representation) {
result = (Representation) variant;
} else {
result = get(variant);
}
} else if (method.equals(Method.POST)) {
result = post(getRequestEntity(), variant);
} else if (method.equals(Method.DELETE)) {
result = delete(variant);
} else if (method.equals(Method.HEAD)) {
if (variant instanceof Representation) {
result = (Representation) variant;
} else {
result = head(variant);
}
} else if (method.equals(Method.OPTIONS)) {
if (variant instanceof Representation) {
result = (Representation) variant;
} else {
result = options(variant);
}
} else if (variant instanceof VariantInfo) {
result = doHandle(((VariantInfo) variant)
.getAnnotationInfo(), variant);
} else {
setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED);
}
} else {
setStatus(Status.CLIENT_ERROR_NOT_FOUND);
}
}
return result;
}
/**
* Effectively handles a call with content negotiation of the response
* entity. The default behavior is to dispatch the call to call a matching
* annotated method or one of the {@link #get(Variant)},
* {@link #post(Representation,Variant)},
* {@link #put(Representation,Variant)}, {@link #delete(Variant)},
* {@link #head(Variant)} or {@link #options(Variant)} methods.<br>
* <br>
* If no acceptable variant is found, the
* {@link Status#CLIENT_ERROR_NOT_ACCEPTABLE} status is set.
*
* @return The response entity.
* @throws ResourceException
*/
protected Representation doNegotiatedHandle() throws ResourceException {
Representation result = null;
if ((getVariants() != null) && (!getVariants().isEmpty())) {
Variant preferredVariant = getClientInfo().getPreferredVariant(
getVariants(), getMetadataService());
if (preferredVariant == null) {
// No variant was found matching the client preferences
setStatus(Status.CLIENT_ERROR_NOT_ACCEPTABLE);
result = describeVariants();
} else {
// Update the variant dimensions used for content negotiation
updateDimensions();
result = doHandle(preferredVariant);
}
} else {
// No variant declared for this method.
result = doHandle();
}
return result;
}
/**
* Returns a full representation. This method is only invoked if content
* negotiation has been disabled as indicated by the {@link #isNegotiated()}
* , otherwise the {@link #get(Variant)} method is invoked.<br>
* <br>
* The default behavior is to set the response status to
* {@link Status#CLIENT_ERROR_METHOD_NOT_ALLOWED}.
*
* @return The resource's representation.
* @throws ResourceException
* @see <a
* href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.3">HTTP
* GET method</a>
*/
protected Representation get() throws ResourceException {
Representation result = null;
AnnotationInfo annotationInfo = getAnnotation(Method.GET);
if (annotationInfo != null) {
result = doHandle(annotationInfo);
} else {
setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED);
}
return result;
}
/**
* Returns a full representation for a given variant. A variant parameter is
* passed to indicate which representation should be returned if any.<br>
* <br>
* This method is only invoked if content negotiation has been enabled as
* indicated by the {@link #isNegotiated()}, otherwise the {@link #get()}
* method is invoked.<br>
* <br>
* The default behavior is to set the response status to
* {@link Status#CLIENT_ERROR_METHOD_NOT_ALLOWED}.<br>
*
* @param variant
* The variant whose full representation must be returned.
* @return The resource's representation.
* @see #get(Variant)
* @throws ResourceException
*/
protected Representation get(Variant variant) throws ResourceException {
Representation result = null;
if (variant instanceof VariantInfo) {
result = doHandle(((VariantInfo) variant).getAnnotationInfo(),
variant);
} else {
setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED);
}
return result;
}
/**
* Returns the first annotation descriptor matching the given method.
*
* @param method
* The method to match.
* @return The annotation descriptor.
*/
private AnnotationInfo getAnnotation(Method method) {
if (isAnnotated()) {
return AnnotationUtils.getAnnotation(getAnnotations(), method);
} else {
return null;
}
}
/**
* Returns the annotation descriptors.
*
* @return The annotation descriptors.
*/
private List<AnnotationInfo> getAnnotations() {
return isAnnotated() ? AnnotationUtils
.getAnnotationDescriptors(getClass()) : null;
}
/**
* Returns information about the resource's representation. Those metadata
* are important for conditional method processing. The advantage over the
* complete {@link Representation} class is that it is much lighter to
* create. This method is only invoked if content negotiation has been
* disabled as indicated by the {@link #isNegotiated()}, otherwise the
* {@link #getInfo(Variant)} method is invoked.<br>
* <br>
* The default behavior is to invoke the {@link #get()} method.
*
* @return Information about the resource's representation.
* @throws ResourceException
*/
protected RepresentationInfo getInfo() throws ResourceException {
return get();
}
/**
* Returns information about the resource's representation. Those metadata
* are important for conditional method processing. The advantage over the
* complete {@link Representation} class is that it is much lighter to
* create. A variant parameter is passed to indicate which representation
* should be returned if any.<br>
* <br>
* This method is only invoked if content negotiation has been enabled as
* indicated by the {@link #isNegotiated()}, otherwise the
* {@link #getInfo(Variant)} method is invoked.<br>
* <br>
* The default behavior is to invoke the {@link #get(Variant)} method.
*
* @param variant
* The variant whose representation information must be returned.
* @return Information about the resource's representation.
* @throws ResourceException
*/
protected RepresentationInfo getInfo(Variant variant)
throws ResourceException {
return get(variant);
}
/**
* Returns the callback invoked before sending the response entity.
*
* @return The callback invoked before sending the response entity.
*/
public Uniform getOnContinue() {
return getResponse().getOnContinue();
}
/**
* Returns the callback invoked after sending the response.
*
* @return The callback invoked after sending the response.
*/
public Uniform getOnSent() {
return getResponse().getOnSent();
}
/**
* Returns the preferred variant among a list of available variants. The
* selection is based on the client preferences using the
* {@link ClientInfo#getPreferredVariant(List, MetadataService)} method.
*
* @param variants
* The available variants.
* @return The preferred variant.
*/
protected Variant getPreferredVariant(List<Variant> variants) {
Variant result = null;
// If variants were found, select the best matching one
if ((variants != null) && (!variants.isEmpty())) {
result = getClientInfo().getPreferredVariant(
variants,
(getApplication() == null) ? null : getApplication()
.getMetadataService());
}
return result;
}
/**
* Return a modifiable list of exposed variants for the current request
* method. You can declare variants manually by updating the result list ,
* by overriding this method. By default, the variants will be provided
* based on annotated methods.
*
* @return The modifiable list of variants.
*/
public List<Variant> getVariants() {
List<Variant> result = this.variants;
if (result == null) {
result = new ArrayList<Variant>();
// Add annotation-based variants in priority
if (isAnnotated() && hasAnnotations()) {
List<Variant> annoVariants = null;
for (AnnotationInfo annotationInfo : getAnnotations()) {
if (getMethod().equals(annotationInfo.getRestletMethod())) {
annoVariants = annotationInfo.getResponseVariants(
getRequestEntity(), getMetadataService(),
getConverterService());
if (annoVariants != null) {
for (Variant v : annoVariants) {
result.add(new VariantInfo(v, annotationInfo));
}
}
}
}
}
this.variants = result;
}
return result;
}
/**
* Handles any call to this resource. The default implementation check the
* {@link #isConditional()} and {@link #isNegotiated()} method to determine
* which one of the {@link #doConditionalHandle()},
* {@link #doNegotiatedHandle()} and {@link #doHandle()} methods should be
* invoked. It also catches any {@link ResourceException} thrown and updates
* the response status using the
* {@link #setStatus(Status, Throwable, String)} method.<br>
* <br>
* After handling, if the status is set to
* {@link Status#CLIENT_ERROR_METHOD_NOT_ALLOWED}, then
* {@link #updateAllowedMethods()} is invoked to give the resource a chance
* to inform the client about the allowed methods.
*
* @return The response entity.
*/
@Override
public Representation handle() {
Representation result = null;
// If the resource is not available after initialization and if this a
// retrieval method, then return a "not found" response.
if (!isExisting() && getMethod().isSafe()) {
setStatus(Status.CLIENT_ERROR_NOT_FOUND);
} else {
try {
if (isConditional()) {
result = doConditionalHandle();
} else if (isNegotiated()) {
result = doNegotiatedHandle();
} else {
result = doHandle();
}
getResponse().setEntity(result);
if (Status.CLIENT_ERROR_METHOD_NOT_ALLOWED.equals(getStatus())) {
updateAllowedMethods();
}
} catch (Throwable t) {
doCatch(t);
}
}
return result;
}
/**
* Indicates if annotations were defined on this resource.
*
* @return True if annotations were defined on this resource.
*/
private boolean hasAnnotations() {
return (getAnnotations() != null) && (!getAnnotations().isEmpty());
}
/**
* Returns a representation whose metadata will be returned to the client.
* This method is only invoked if content negotiation has been disabled as
* indicated by the {@link #isNegotiated()}, otherwise the
* {@link #head(Variant)} method is invoked.<br>
* <br>
* The default behavior is to set the response status to
* {@link Status#CLIENT_ERROR_METHOD_NOT_ALLOWED}.
*
* @return The resource's representation.
* @throws ResourceException
* @see <a
* href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.3">HTTP
* GET method</a>
*/
protected Representation head() throws ResourceException {
return get();
}
/**
* Returns a representation whose metadata will be returned to the client. A
* variant parameter is passed to indicate which representation should be
* returned if any.<br>
* <br>
* This method is only invoked if content negotiation has been enabled as
* indicated by the {@link #isNegotiated()}, otherwise the {@link #head()}
* method is invoked.<br>
* <br>
* The default implementation directly returns the variant if it is already
* an instance of {@link Representation}. In other cases, you need to
* override this method in order to provide your own implementation. *
*
* @param variant
* The variant whose full representation must be returned.
* @return The resource's representation.
* @see #get(Variant)
* @throws ResourceException
*/
protected Representation head(Variant variant) throws ResourceException {
return get(variant);
}
/**
* Indicates if annotations are supported. The default value is true.
*
* @return True if annotations are supported.
*/
public boolean isAnnotated() {
return annotated;
}
/**
* Indicates if conditional handling is enabled. The default value is true.
*
* @return True if conditional handling is enabled.
*/
public boolean isConditional() {
return conditional;
}
/**
* Indicates if the identified resource exists. The default value is true.
*
* @return True if the identified resource exists.
*/
public boolean isExisting() {
return existing;
}
/**
* Indicates if the authenticated client user associated to the current
* request is in the given role name.
*
* @param roleName
* The role name to test.
* @return True if the authenticated subject is in the given role.
*/
public boolean isInRole(String roleName) {
return getClientInfo().getRoles().contains(
getApplication().findRole(roleName));
}
/**
* Indicates if content negotiation of response entities is enabled. The
* default value is true.
*
* @return True if content negotiation of response entities is enabled.
*/
public boolean isNegotiated() {
return this.negotiated;
}
/**
* Indicates the communication options available for this resource.This
* method is only invoked if content negotiation has been disabled as
* indicated by the {@link #isNegotiated()}, otherwise the
* {@link #options(Variant)} method is invoked.<br>
* <br>
* The default behavior is to set the response status to
* {@link Status#CLIENT_ERROR_METHOD_NOT_ALLOWED}.
*
* @return The optional response entity.
*/
protected Representation options() throws ResourceException {
Representation result = null;
AnnotationInfo annotationInfo = getAnnotation(Method.OPTIONS);
if (annotationInfo != null) {
result = doHandle(annotationInfo);
} else {
setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED);
}
return result;
}
/**
* Indicates the communication options available for this resource. A
* variant parameter is passed to indicate which representation should be
* returned if any.<br>
* <br>
* This method is only invoked if content negotiation has been enabled as
* indicated by the {@link #isNegotiated()}, otherwise the
* {@link #options()} method is invoked.<br>
* <br>
* The default behavior is to set the response status to
* {@link Status#CLIENT_ERROR_METHOD_NOT_ALLOWED}.<br>
*
* @param variant
* The variant of the response entity.
* @return The optional response entity.
* @see #get(Variant)
*/
protected Representation options(Variant variant) throws ResourceException {
Representation result = null;
if (variant instanceof VariantInfo) {
result = doHandle(((VariantInfo) variant).getAnnotationInfo(),
variant);
} else {
setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED);
}
return result;
}
/**
* Posts a representation to the resource at the target URI reference. This
* method is only invoked if content negotiation has been disabled as
* indicated by the {@link #isNegotiated()}, otherwise the
* {@link #post(Representation, Variant)} method is invoked.<br>
* <br>
* The default behavior is to set the response status to
* {@link Status#CLIENT_ERROR_METHOD_NOT_ALLOWED}.
*
* @param entity
* The posted entity.
* @return The optional response entity.
* @throws ResourceException
* @see #get(Variant)
* @see <a
* href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.5">HTTP
* POST method</a>
*/
protected Representation post(Representation entity)
throws ResourceException {
Representation result = null;
AnnotationInfo annotationInfo = getAnnotation(Method.POST);
if (annotationInfo != null) {
result = doHandle(annotationInfo);
} else {
setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED);
}
return result;
}
/**
* Posts a representation to the resource at the target URI reference. A
* variant parameter is passed to indicate which representation should be
* returned if any.<br>
* <br>
* This method is only invoked if content negotiation has been enabled as
* indicated by the {@link #isNegotiated()}, otherwise the
* {@link #post(Representation)} method is invoked.<br>
* <br>
* The default behavior is to set the response status to
* {@link Status#CLIENT_ERROR_METHOD_NOT_ALLOWED}.<br>
*
* @param entity
* The posted entity.
* @param variant
* The variant of the response entity.
* @return The optional result entity.
* @throws ResourceException
* @see <a
* href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.5"
* >HTTP POST method</a>
*/
protected Representation post(Representation entity, Variant variant)
throws ResourceException {
Representation result = null;
if (variant instanceof VariantInfo) {
result = doHandle(((VariantInfo) variant).getAnnotationInfo(),
variant);
} else {
setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED);
}
return result;
}
/**
* Creates or updates a resource with the given representation as new state
* to be stored. This method is only invoked if content negotiation has been
* disabled as indicated by the {@link #isNegotiated()}, otherwise the
* {@link #put(Representation, Variant)} method is invoked.<br>
* <br>
* The default behavior is to set the response status to
* {@link Status#CLIENT_ERROR_METHOD_NOT_ALLOWED}.
*
* @param representation
* The representation to store.
* @return The optional result entity.
* @throws ResourceException
* @see <a
* href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.6">HTTP
* PUT method</a>
*/
protected Representation put(Representation representation)
throws ResourceException {
Representation result = null;
AnnotationInfo annotationInfo = getAnnotation(Method.PUT);
if (annotationInfo != null) {
result = doHandle(annotationInfo);
} else {
setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED);
}
return result;
}
/**
* Creates or updates a resource with the given representation as new state
* to be stored. A variant parameter is passed to indicate which
* representation should be returned if any.<br>
* <br>
* This method is only invoked if content negotiation has been enabled as
* indicated by the {@link #isNegotiated()}, otherwise the
* {@link #put(Representation)} method is invoked.<br>
* <br>
* The default behavior is to set the response status to
* {@link Status#CLIENT_ERROR_METHOD_NOT_ALLOWED}.<br>
*
* @param representation
* The representation to store.
* @param variant
* The variant of the response entity.
* @return The optional result entity.
* @throws ResourceException
* @see #get(Variant)
* @see <a
* href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.6"
* >HTTP PUT method</a>
*/
protected Representation put(Representation representation, Variant variant)
throws ResourceException {
Representation result = null;
if (variant instanceof VariantInfo) {
result = doHandle(((VariantInfo) variant).getAnnotationInfo(),
variant);
} else {
setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED);
}
return result;
}
/**
* Permanently redirects the client to a target URI. The client is expected
* to reuse the same method for the new request.
*
* @param targetRef
* The target URI reference.
*/
public void redirectPermanent(Reference targetRef) {
if (getResponse() != null) {
getResponse().redirectPermanent(targetRef);
}
}
/**
* Permanently redirects the client to a target URI. The client is expected
* to reuse the same method for the new request.<br>
* <br>
* If you pass a relative target URI, it will be resolved with the current
* base reference of the request's resource reference (see
* {@link Request#getResourceRef()} and {@link Reference#getBaseRef()}.
*
* @param targetUri
* The target URI.
*/
public void redirectPermanent(String targetUri) {
if (getResponse() != null) {
getResponse().redirectPermanent(targetUri);
}
}
/**
* Redirects the client to a different URI that SHOULD be retrieved using a
* GET method on that resource. This method exists primarily to allow the
* output of a POST-activated script to redirect the user agent to a
* selected resource. The new URI is not a substitute reference for the
* originally requested resource.
*
* @param targetRef
* The target reference.
*/
public void redirectSeeOther(Reference targetRef) {
if (getResponse() != null) {
getResponse().redirectSeeOther(targetRef);
}
}
/**
* Redirects the client to a different URI that SHOULD be retrieved using a
* GET method on that resource. This method exists primarily to allow the
* output of a POST-activated script to redirect the user agent to a
* selected resource. The new URI is not a substitute reference for the
* originally requested resource.<br>
* <br>
* If you pass a relative target URI, it will be resolved with the current
* base reference of the request's resource reference (see
* {@link Request#getResourceRef()} and {@link Reference#getBaseRef()}.
*
* @param targetUri
* The target URI.
*/
public void redirectSeeOther(String targetUri) {
if (getResponse() != null) {
getResponse().redirectSeeOther(targetUri);
}
}
/**
* Temporarily redirects the client to a target URI. The client is expected
* to reuse the same method for the new request.
*
* @param targetRef
* The target reference.
*/
public void redirectTemporary(Reference targetRef) {
if (getResponse() != null) {
getResponse().redirectTemporary(targetRef);
}
}
/**
* Temporarily redirects the client to a target URI. The client is expected
* to reuse the same method for the new request.<br>
* <br>
* If you pass a relative target URI, it will be resolved with the current
* base reference of the request's resource reference (see
* {@link Request#getResourceRef()} and {@link Reference#getBaseRef()}.
*
* @param targetUri
* The target URI.
*/
public void redirectTemporary(String targetUri) {
if (getResponse() != null) {
getResponse().redirectTemporary(targetUri);
}
}
/**
* Sets the set of methods allowed on the requested resource. The set
* instance set must be thread-safe (use {@link CopyOnWriteArraySet} for
* example.
*
* @param allowedMethods
* The set of methods allowed on the requested resource.
* @see Response#setAllowedMethods(Set)
*/
public void setAllowedMethods(Set<Method> allowedMethods) {
if (getResponse() != null) {
getResponse().setAllowedMethods(allowedMethods);
}
}
/**
* Indicates if annotations are supported. The default value is true.
*
* @param annotated
* Indicates if annotations are supported.
*/
public void setAnnotated(boolean annotated) {
this.annotated = annotated;
}
/**
* Sets the list of authentication requests sent by an origin server to a
* client. The list instance set must be thread-safe (use
* {@link CopyOnWriteArrayList} for example.
*
* @param requests
* The list of authentication requests sent by an origin server
* to a client.
* @see Response#setChallengeRequests(List)
*/
public void setChallengeRequests(List<ChallengeRequest> requests) {
if (getResponse() != null) {
getResponse().setChallengeRequests(requests);
}
}
/**
* Indicates if conditional handling is enabled. The default value is true.
*
* @param conditional
* True if conditional handling is enabled.
*/
public void setConditional(boolean conditional) {
this.conditional = conditional;
}
/**
* Sets the cookie settings provided by the server.
*
* @param cookieSettings
* The cookie settings provided by the server.
* @see Response#setCookieSettings(Series)
*/
public void setCookieSettings(Series<CookieSetting> cookieSettings) {
if (getResponse() != null) {
getResponse().setCookieSettings(cookieSettings);
}
}
/**
* Sets the set of dimensions on which the response entity may vary. The set
* instance set must be thread-safe (use {@link CopyOnWriteArraySet} for
* example.
*
* @param dimensions
* The set of dimensions on which the response entity may vary.
* @see Response#setDimensions(Set)
*/
public void setDimensions(Set<Dimension> dimensions) {
if (getResponse() != null) {
getResponse().setDimensions(dimensions);
}
}
/**
* Indicates if the identified resource exists. The default value is true.
*
* @param exists
* Indicates if the identified resource exists.
*/
public void setExisting(boolean exists) {
this.existing = exists;
}
/**
* Sets the reference that the client should follow for redirections or
* resource creations.
*
* @param locationRef
* The reference to set.
* @see Response#setLocationRef(Reference)
*/
public void setLocationRef(Reference locationRef) {
if (getResponse() != null) {
getResponse().setLocationRef(locationRef);
}
}
/**
* Sets the reference that the client should follow for redirections or
* resource creations. If you pass a relative location URI, it will be
* resolved with the current base reference of the request's resource
* reference (see {@link Request#getResourceRef()} and
* {@link Reference#getBaseRef()}.
*
* @param locationUri
* The URI to set.
* @see Response#setLocationRef(String)
*/
public void setLocationRef(String locationUri) {
if (getResponse() != null) {
getResponse().setLocationRef(locationUri);
}
}
/**
* Indicates if content negotiation of response entities is enabled. The
* default value is true.
*
* @param negotiateContent
* True if content negotiation of response entities is enabled.
*/
public void setNegotiated(boolean negotiateContent) {
this.negotiated = negotiateContent;
}
/**
* Sets the callback invoked before sending the response entity.
*
* @param onContinueCallback
* The callback invoked before sending the response entity.
*/
public void setOnContinue(Uniform onContinueCallback) {
getResponse().setOnContinue(onContinueCallback);
}
/**
* Sets the callback invoked after sending the response.
*
* @param onSentCallback
* The callback invoked after sending the response.
*/
public void setOnSent(Uniform onSentCallback) {
getResponse().setOnSent(onSentCallback);
}
/**
* Sets the server-specific information.
*
* @param serverInfo
* The server-specific information.
* @see Response#setServerInfo(ServerInfo)
*/
public void setServerInfo(ServerInfo serverInfo) {
if (getResponse() != null) {
getResponse().setServerInfo(serverInfo);
}
}
/**
* Sets the status.
*
* @param status
* The status to set.
* @see Response#setStatus(Status)
*/
public void setStatus(Status status) {
if (getResponse() != null) {
getResponse().setStatus(status);
}
}
/**
* Sets the status.
*
* @param status
* The status to set.
* @param message
* The status message.
* @see Response#setStatus(Status, String)
*/
public void setStatus(Status status, String message) {
if (getResponse() != null) {
getResponse().setStatus(status, message);
}
}
/**
* Sets the status.
*
* @param status
* The status to set.
* @param throwable
* The related error or exception.
* @see Response#setStatus(Status, Throwable)
*/
public void setStatus(Status status, Throwable throwable) {
if (getResponse() != null) {
getResponse().setStatus(status, throwable);
}
}
/**
* Sets the status.
*
* @param status
* The status to set.
* @param throwable
* The related error or exception.
* @param message
* The status message.
* @see Response#setStatus(Status, Throwable, String)
*/
public void setStatus(Status status, Throwable throwable, String message) {
if (getResponse() != null) {
getResponse().setStatus(status, throwable, message);
}
}
/**
* Invoked when the list of allowed methods needs to be updated. The
* {@link #getAllowedMethods()} or the {@link #setAllowedMethods(Set)}
* methods should be used. The default implementation does nothing.
*/
protected void updateAllowedMethods() {
}
/**
* Update the dimensions that were used for content negotiation. By default,
* it adds the {@link Dimension#CHARACTER_SET}, {@link Dimension#ENCODING},
* {@link Dimension#LANGUAGE}and {@link Dimension#MEDIA_TYPE} constants.
*/
protected void updateDimensions() {
getDimensions().add(Dimension.CHARACTER_SET);
getDimensions().add(Dimension.ENCODING);
getDimensions().add(Dimension.LANGUAGE);
getDimensions().add(Dimension.MEDIA_TYPE);
}
}
| true | true | protected Representation doConditionalHandle() throws ResourceException {
Representation result = null;
if (getConditions().hasSome()) {
if (!isExisting() && getConditions().getMatch().contains(Tag.ALL)) {
setStatus(Status.CLIENT_ERROR_PRECONDITION_FAILED,
"A non existing resource can't match any tag.");
} else {
RepresentationInfo resultInfo = null;
if (isNegotiated()) {
resultInfo = doGetInfo(getPreferredVariant(getVariants()));
} else {
resultInfo = doGetInfo();
}
if (resultInfo == null) {
if ((getStatus() == null)
|| (getStatus().isSuccess() && !Status.SUCCESS_NO_CONTENT
.equals(getStatus()))) {
setStatus(Status.CLIENT_ERROR_NOT_FOUND);
} else {
// Keep the current status as the developer might prefer
// a special status like 'method not authorized'.
}
} else {
Status status = getConditions().getStatus(getMethod(),
resultInfo);
if (status != null) {
setStatus(status);
}
}
if ((getStatus() != null) && getStatus().isSuccess()) {
// Conditions were passed successfully, continue the normal
// processing
// If the representation info obtained to test the
// conditions
// is in fact a full representation, return it immediately
// for optimization purpose
if ((Method.GET.equals(getMethod()) || Method.HEAD
.equals(getMethod()))
&& resultInfo instanceof Representation) {
result = (Representation) resultInfo;
} else {
if (isNegotiated()) {
result = doNegotiatedHandle();
} else {
result = doHandle();
}
}
}
}
} else {
if (isNegotiated()) {
result = doNegotiatedHandle();
} else {
result = doHandle();
}
}
return result;
}
| protected Representation doConditionalHandle() throws ResourceException {
Representation result = null;
if (getConditions().hasSome()) {
if (!isExisting() && getConditions().getMatch().contains(Tag.ALL)) {
setStatus(Status.CLIENT_ERROR_PRECONDITION_FAILED,
"A non existing resource can't match any tag.");
} else {
RepresentationInfo resultInfo = null;
if (isNegotiated()) {
resultInfo = doGetInfo(getPreferredVariant(getVariants()));
} else {
resultInfo = doGetInfo();
}
if (resultInfo == null) {
if ((getStatus() == null)
|| (getStatus().isSuccess() && !Status.SUCCESS_NO_CONTENT
.equals(getStatus()))) {
setStatus(Status.CLIENT_ERROR_NOT_FOUND);
} else {
// Keep the current status as the developer might prefer
// a special status like 'method not authorized'.
}
} else {
Status status = getConditions().getStatus(getMethod(),
resultInfo);
if (status != null) {
setStatus(status);
}
}
if ((getStatus() != null) && getStatus().isSuccess()) {
// Conditions were passed successfully, continue the normal
// processing. If the representation info obtained to test
// the conditions is in fact a full representation, return
// it immediately for optimization purpose
if ((Method.GET.equals(getMethod()) || Method.HEAD
.equals(getMethod()))
&& resultInfo instanceof Representation) {
result = (Representation) resultInfo;
} else {
if (isNegotiated()) {
result = doNegotiatedHandle();
} else {
result = doHandle();
}
}
}
}
} else {
if (isNegotiated()) {
result = doNegotiatedHandle();
} else {
result = doHandle();
}
}
return result;
}
|
diff --git a/src/com/android/dialer/calllog/CallLogAdapter.java b/src/com/android/dialer/calllog/CallLogAdapter.java
index b2493cf97..86540efbb 100644
--- a/src/com/android/dialer/calllog/CallLogAdapter.java
+++ b/src/com/android/dialer/calllog/CallLogAdapter.java
@@ -1,926 +1,928 @@
/*
* 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.
*/
package com.android.dialer.calllog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.provider.CallLog.Calls;
import android.provider.ContactsContract.PhoneLookup;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.TextView;
import com.android.common.widget.GroupingListAdapter;
import com.android.contacts.common.ContactPhotoManager;
import com.android.contacts.common.util.UriUtils;
import com.android.dialer.PhoneCallDetails;
import com.android.dialer.PhoneCallDetailsHelper;
import com.android.dialer.R;
import com.android.dialer.util.ExpirableCache;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Objects;
import java.util.LinkedList;
/**
* Adapter class to fill in data for the Call Log.
*/
public class CallLogAdapter extends GroupingListAdapter
implements ViewTreeObserver.OnPreDrawListener, CallLogGroupBuilder.GroupCreator {
/** Interface used to initiate a refresh of the content. */
public interface CallFetcher {
public void fetchCalls();
}
/**
* Stores a phone number of a call with the country code where it originally occurred.
* <p>
* Note the country does not necessarily specifies the country of the phone number itself, but
* it is the country in which the user was in when the call was placed or received.
*/
private static final class NumberWithCountryIso {
public final String number;
public final String countryIso;
public NumberWithCountryIso(String number, String countryIso) {
this.number = number;
this.countryIso = countryIso;
}
@Override
public boolean equals(Object o) {
if (o == null) return false;
if (!(o instanceof NumberWithCountryIso)) return false;
NumberWithCountryIso other = (NumberWithCountryIso) o;
return TextUtils.equals(number, other.number)
&& TextUtils.equals(countryIso, other.countryIso);
}
@Override
public int hashCode() {
return (number == null ? 0 : number.hashCode())
^ (countryIso == null ? 0 : countryIso.hashCode());
}
}
/** The time in millis to delay starting the thread processing requests. */
private static final int START_PROCESSING_REQUESTS_DELAY_MILLIS = 1000;
/** The size of the cache of contact info. */
private static final int CONTACT_INFO_CACHE_SIZE = 100;
protected final Context mContext;
private final ContactInfoHelper mContactInfoHelper;
private final CallFetcher mCallFetcher;
private ViewTreeObserver mViewTreeObserver = null;
/**
* A cache of the contact details for the phone numbers in the call log.
* <p>
* The content of the cache is expired (but not purged) whenever the application comes to
* the foreground.
* <p>
* The key is number with the country in which the call was placed or received.
*/
private ExpirableCache<NumberWithCountryIso, ContactInfo> mContactInfoCache;
/**
* A request for contact details for the given number.
*/
private static final class ContactInfoRequest {
/** The number to look-up. */
public final String number;
/** The country in which a call to or from this number was placed or received. */
public final String countryIso;
/** The cached contact information stored in the call log. */
public final ContactInfo callLogInfo;
public ContactInfoRequest(String number, String countryIso, ContactInfo callLogInfo) {
this.number = number;
this.countryIso = countryIso;
this.callLogInfo = callLogInfo;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (!(obj instanceof ContactInfoRequest)) return false;
ContactInfoRequest other = (ContactInfoRequest) obj;
if (!TextUtils.equals(number, other.number)) return false;
if (!TextUtils.equals(countryIso, other.countryIso)) return false;
if (!Objects.equal(callLogInfo, other.callLogInfo)) return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((callLogInfo == null) ? 0 : callLogInfo.hashCode());
result = prime * result + ((countryIso == null) ? 0 : countryIso.hashCode());
result = prime * result + ((number == null) ? 0 : number.hashCode());
return result;
}
}
/**
* List of requests to update contact details.
* <p>
* Each request is made of a phone number to look up, and the contact info currently stored in
* the call log for this number.
* <p>
* The requests are added when displaying the contacts and are processed by a background
* thread.
*/
private final LinkedList<ContactInfoRequest> mRequests;
private boolean mLoading = true;
private static final int REDRAW = 1;
private static final int START_THREAD = 2;
private QueryThread mCallerIdThread;
/** Instance of helper class for managing views. */
private final CallLogListItemHelper mCallLogViewsHelper;
/** Helper to set up contact photos. */
private final ContactPhotoManager mContactPhotoManager;
/** Helper to parse and process phone numbers. */
private PhoneNumberHelper mPhoneNumberHelper;
/** Helper to group call log entries. */
private final CallLogGroupBuilder mCallLogGroupBuilder;
/** Can be set to true by tests to disable processing of requests. */
private volatile boolean mRequestProcessingDisabled = false;
/** True if CallLogAdapter is created from the PhoneFavoriteFragment, where the primary
* action should be set to call a number instead of opening the detail page. */
private boolean mUseCallAsPrimaryAction = false;
private boolean mIsCallLog = true;
private int mNumMissedCalls = 0;
private int mNumMissedCallsShown = 0;
private Uri mCurrentPhotoUri;
private View mBadgeContainer;
private ImageView mBadgeImageView;
private TextView mBadgeText;
/** Listener for the primary action in the list, opens the call details. */
private final View.OnClickListener mPrimaryActionListener = new View.OnClickListener() {
@Override
public void onClick(View view) {
IntentProvider intentProvider = (IntentProvider) view.getTag();
if (intentProvider != null) {
mContext.startActivity(intentProvider.getIntent(mContext));
}
}
};
/** Listener for the secondary action in the list, either call or play. */
private final View.OnClickListener mSecondaryActionListener = new View.OnClickListener() {
@Override
public void onClick(View view) {
IntentProvider intentProvider = (IntentProvider) view.getTag();
if (intentProvider != null) {
mContext.startActivity(intentProvider.getIntent(mContext));
}
}
};
@Override
public boolean onPreDraw() {
// We only wanted to listen for the first draw (and this is it).
unregisterPreDrawListener();
// Only schedule a thread-creation message if the thread hasn't been
// created yet. This is purely an optimization, to queue fewer messages.
if (mCallerIdThread == null) {
mHandler.sendEmptyMessageDelayed(START_THREAD, START_PROCESSING_REQUESTS_DELAY_MILLIS);
}
return true;
}
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case REDRAW:
notifyDataSetChanged();
break;
case START_THREAD:
startRequestProcessing();
break;
}
}
};
public CallLogAdapter(Context context, CallFetcher callFetcher,
ContactInfoHelper contactInfoHelper, boolean useCallAsPrimaryAction,
boolean isCallLog) {
super(context);
mContext = context;
mCallFetcher = callFetcher;
mContactInfoHelper = contactInfoHelper;
mUseCallAsPrimaryAction = useCallAsPrimaryAction;
mIsCallLog = isCallLog;
mContactInfoCache = ExpirableCache.create(CONTACT_INFO_CACHE_SIZE);
mRequests = new LinkedList<ContactInfoRequest>();
Resources resources = mContext.getResources();
CallTypeHelper callTypeHelper = new CallTypeHelper(resources);
mContactPhotoManager = ContactPhotoManager.getInstance(mContext);
mPhoneNumberHelper = new PhoneNumberHelper(resources);
PhoneCallDetailsHelper phoneCallDetailsHelper = new PhoneCallDetailsHelper(
resources, callTypeHelper, new PhoneNumberUtilsWrapper());
mCallLogViewsHelper =
new CallLogListItemHelper(
phoneCallDetailsHelper, mPhoneNumberHelper, resources);
mCallLogGroupBuilder = new CallLogGroupBuilder(this);
}
/**
* Requery on background thread when {@link Cursor} changes.
*/
@Override
protected void onContentChanged() {
mCallFetcher.fetchCalls();
}
public void setLoading(boolean loading) {
mLoading = loading;
}
@Override
public boolean isEmpty() {
if (mLoading) {
// We don't want the empty state to show when loading.
return false;
} else {
return super.isEmpty();
}
}
/**
* Starts a background thread to process contact-lookup requests, unless one
* has already been started.
*/
private synchronized void startRequestProcessing() {
// For unit-testing.
if (mRequestProcessingDisabled) return;
// Idempotence... if a thread is already started, don't start another.
if (mCallerIdThread != null) return;
mCallerIdThread = new QueryThread();
mCallerIdThread.setPriority(Thread.MIN_PRIORITY);
mCallerIdThread.start();
}
/**
* Stops the background thread that processes updates and cancels any
* pending requests to start it.
*/
public synchronized void stopRequestProcessing() {
// Remove any pending requests to start the processing thread.
mHandler.removeMessages(START_THREAD);
if (mCallerIdThread != null) {
// Stop the thread; we are finished with it.
mCallerIdThread.stopProcessing();
mCallerIdThread.interrupt();
mCallerIdThread = null;
}
}
/**
* Stop receiving onPreDraw() notifications.
*/
private void unregisterPreDrawListener() {
if (mViewTreeObserver != null && mViewTreeObserver.isAlive()) {
mViewTreeObserver.removeOnPreDrawListener(this);
}
mViewTreeObserver = null;
}
public void invalidateCache() {
mContactInfoCache.expireAll();
// Restart the request-processing thread after the next draw.
stopRequestProcessing();
unregisterPreDrawListener();
}
/**
* Enqueues a request to look up the contact details for the given phone number.
* <p>
* It also provides the current contact info stored in the call log for this number.
* <p>
* If the {@code immediate} parameter is true, it will start immediately the thread that looks
* up the contact information (if it has not been already started). Otherwise, it will be
* started with a delay. See {@link #START_PROCESSING_REQUESTS_DELAY_MILLIS}.
*/
protected void enqueueRequest(String number, String countryIso, ContactInfo callLogInfo,
boolean immediate) {
ContactInfoRequest request = new ContactInfoRequest(number, countryIso, callLogInfo);
synchronized (mRequests) {
if (!mRequests.contains(request)) {
mRequests.add(request);
mRequests.notifyAll();
}
}
if (immediate) startRequestProcessing();
}
/**
* Queries the appropriate content provider for the contact associated with the number.
* <p>
* Upon completion it also updates the cache in the call log, if it is different from
* {@code callLogInfo}.
* <p>
* The number might be either a SIP address or a phone number.
* <p>
* It returns true if it updated the content of the cache and we should therefore tell the
* view to update its content.
*/
private boolean queryContactInfo(String number, String countryIso, ContactInfo callLogInfo) {
final ContactInfo info = mContactInfoHelper.lookupNumber(number, countryIso);
if (info == null) {
// The lookup failed, just return without requesting to update the view.
return false;
}
// Check the existing entry in the cache: only if it has changed we should update the
// view.
NumberWithCountryIso numberCountryIso = new NumberWithCountryIso(number, countryIso);
ContactInfo existingInfo = mContactInfoCache.getPossiblyExpired(numberCountryIso);
boolean updated = !info.equals(existingInfo);
// Store the data in the cache so that the UI thread can use to display it. Store it
// even if it has not changed so that it is marked as not expired.
mContactInfoCache.put(numberCountryIso, info);
// Update the call log even if the cache it is up-to-date: it is possible that the cache
// contains the value from a different call log entry.
updateCallLogContactInfoCache(number, countryIso, info, callLogInfo);
return updated;
}
/*
* Handles requests for contact name and number type.
*/
private class QueryThread extends Thread {
private volatile boolean mDone = false;
public QueryThread() {
super("CallLogAdapter.QueryThread");
}
public void stopProcessing() {
mDone = true;
}
@Override
public void run() {
boolean needRedraw = false;
while (true) {
// Check if thread is finished, and if so return immediately.
if (mDone) return;
// Obtain next request, if any is available.
// Keep synchronized section small.
ContactInfoRequest req = null;
synchronized (mRequests) {
if (!mRequests.isEmpty()) {
req = mRequests.removeFirst();
}
}
if (req != null) {
// Process the request. If the lookup succeeds, schedule a
// redraw.
needRedraw |= queryContactInfo(req.number, req.countryIso, req.callLogInfo);
} else {
// Throttle redraw rate by only sending them when there are
// more requests.
if (needRedraw) {
needRedraw = false;
mHandler.sendEmptyMessage(REDRAW);
}
// Wait until another request is available, or until this
// thread is no longer needed (as indicated by being
// interrupted).
try {
synchronized (mRequests) {
mRequests.wait(1000);
}
} catch (InterruptedException ie) {
// Ignore, and attempt to continue processing requests.
}
}
}
}
}
@Override
protected void addGroups(Cursor cursor) {
mCallLogGroupBuilder.addGroups(cursor);
}
@Override
protected View newStandAloneView(Context context, ViewGroup parent) {
return newChildView(context, parent);
}
@Override
protected View newGroupView(Context context, ViewGroup parent) {
return newChildView(context, parent);
}
@Override
protected View newChildView(Context context, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.call_log_list_item, parent, false);
findAndCacheViews(view);
return view;
}
@Override
protected void bindStandAloneView(View view, Context context, Cursor cursor) {
bindView(view, cursor, 1);
}
@Override
protected void bindChildView(View view, Context context, Cursor cursor) {
bindView(view, cursor, 1);
}
@Override
protected void bindGroupView(View view, Context context, Cursor cursor, int groupSize,
boolean expanded) {
bindView(view, cursor, groupSize);
}
private void findAndCacheViews(View view) {
// Get the views to bind to.
CallLogListItemViews views = CallLogListItemViews.fromView(view);
views.primaryActionView.setOnClickListener(mPrimaryActionListener);
views.secondaryActionView.setOnClickListener(mSecondaryActionListener);
view.setTag(views);
}
/**
* Binds the views in the entry to the data in the call log.
*
* @param view the view corresponding to this entry
* @param c the cursor pointing to the entry in the call log
* @param count the number of entries in the current item, greater than 1 if it is a group
*/
private void bindView(View view, Cursor c, int count) {
final CallLogListItemViews views = (CallLogListItemViews) view.getTag();
// Default case: an item in the call log.
views.primaryActionView.setVisibility(View.VISIBLE);
views.listHeaderTextView.setVisibility(View.GONE);
final String number = c.getString(CallLogQuery.NUMBER);
final int numberPresentation = c.getInt(CallLogQuery.NUMBER_PRESENTATION);
final long date = c.getLong(CallLogQuery.DATE);
final long duration = c.getLong(CallLogQuery.DURATION);
final int callType = c.getInt(CallLogQuery.CALL_TYPE);
final String countryIso = c.getString(CallLogQuery.COUNTRY_ISO);
final ContactInfo cachedContactInfo = getContactInfoFromCallLog(c);
if (!mUseCallAsPrimaryAction) {
// Sets the primary action to open call detail page.
views.primaryActionView.setTag(
IntentProvider.getCallDetailIntentProvider(
getCursor(), c.getPosition(), c.getLong(CallLogQuery.ID), count));
} else if (PhoneNumberUtilsWrapper.canPlaceCallsTo(number, numberPresentation)) {
// Sets the primary action to call the number.
views.primaryActionView.setTag(IntentProvider.getReturnCallIntentProvider(number));
+ } else {
+ views.primaryActionView.setTag(null);
}
// Store away the voicemail information so we can play it directly.
if (callType == Calls.VOICEMAIL_TYPE) {
String voicemailUri = c.getString(CallLogQuery.VOICEMAIL_URI);
final long rowId = c.getLong(CallLogQuery.ID);
views.secondaryActionView.setTag(
IntentProvider.getPlayVoicemailIntentProvider(rowId, voicemailUri));
} else if (!TextUtils.isEmpty(number)) {
// Store away the number so we can call it directly if you click on the call icon.
views.secondaryActionView.setTag(
IntentProvider.getReturnCallIntentProvider(number));
} else {
// No action enabled.
views.secondaryActionView.setTag(null);
}
// Lookup contacts with this number
NumberWithCountryIso numberCountryIso = new NumberWithCountryIso(number, countryIso);
ExpirableCache.CachedValue<ContactInfo> cachedInfo =
mContactInfoCache.getCachedValue(numberCountryIso);
ContactInfo info = cachedInfo == null ? null : cachedInfo.getValue();
if (!PhoneNumberUtilsWrapper.canPlaceCallsTo(number, numberPresentation)
|| new PhoneNumberUtilsWrapper().isVoicemailNumber(number)) {
// If this is a number that cannot be dialed, there is no point in looking up a contact
// for it.
info = ContactInfo.EMPTY;
} else if (cachedInfo == null) {
mContactInfoCache.put(numberCountryIso, ContactInfo.EMPTY);
// Use the cached contact info from the call log.
info = cachedContactInfo;
// The db request should happen on a non-UI thread.
// Request the contact details immediately since they are currently missing.
enqueueRequest(number, countryIso, cachedContactInfo, true);
// We will format the phone number when we make the background request.
} else {
if (cachedInfo.isExpired()) {
// The contact info is no longer up to date, we should request it. However, we
// do not need to request them immediately.
enqueueRequest(number, countryIso, cachedContactInfo, false);
} else if (!callLogInfoMatches(cachedContactInfo, info)) {
// The call log information does not match the one we have, look it up again.
// We could simply update the call log directly, but that needs to be done in a
// background thread, so it is easier to simply request a new lookup, which will, as
// a side-effect, update the call log.
enqueueRequest(number, countryIso, cachedContactInfo, false);
}
if (info == ContactInfo.EMPTY) {
// Use the cached contact info from the call log.
info = cachedContactInfo;
}
}
final Uri lookupUri = info.lookupUri;
final String name = info.name;
final int ntype = info.type;
final String label = info.label;
final long photoId = info.photoId;
final Uri photoUri = info.photoUri;
CharSequence formattedNumber = info.formattedNumber;
final int[] callTypes = getCallTypes(c, count);
final String geocode = c.getString(CallLogQuery.GEOCODED_LOCATION);
final PhoneCallDetails details;
if (TextUtils.isEmpty(name)) {
details = new PhoneCallDetails(number, numberPresentation,
formattedNumber, countryIso, geocode, callTypes, date,
duration);
} else {
details = new PhoneCallDetails(number, numberPresentation,
formattedNumber, countryIso, geocode, callTypes, date,
duration, name, ntype, label, lookupUri, photoUri);
}
final boolean isNew = c.getInt(CallLogQuery.IS_READ) == 0;
// New items also use the highlighted version of the text.
final boolean isHighlighted = isNew;
mCallLogViewsHelper.setPhoneCallDetails(views, details, isHighlighted,
mUseCallAsPrimaryAction);
if (photoId == 0 && photoUri != null) {
setPhoto(views, photoUri, lookupUri);
} else {
setPhoto(views, photoId, lookupUri);
}
views.quickContactView.setContentDescription(views.phoneCallDetailsViews.nameView.
getText());
// Listen for the first draw
if (mViewTreeObserver == null) {
mViewTreeObserver = view.getViewTreeObserver();
mViewTreeObserver.addOnPreDrawListener(this);
}
bindBadge(view, info, details, callType);
}
protected void bindBadge(View view, ContactInfo info, PhoneCallDetails details, int callType) {
// Do not show badge in call log.
if (!mIsCallLog) {
final int numMissed = getNumMissedCalls(callType);
final ViewStub stub = (ViewStub) view.findViewById(R.id.link_stub);
if (shouldShowBadge(numMissed, info, details)) {
// stub will be null if it was already inflated.
if (stub != null) {
final View inflated = stub.inflate();
inflated.setVisibility(View.VISIBLE);
mBadgeContainer = inflated.findViewById(R.id.badge_link_container);
mBadgeImageView = (ImageView) inflated.findViewById(R.id.badge_image);
mBadgeText = (TextView) inflated.findViewById(R.id.badge_text);
}
mBadgeContainer.setOnClickListener(getBadgeClickListener());
mBadgeImageView.setImageResource(getBadgeImageResId());
mBadgeText.setText(getBadgeText(numMissed));
mNumMissedCallsShown = numMissed;
} else {
// Hide badge if it was previously shown.
if (stub == null) {
final View container = view.findViewById(R.id.badge_container);
if (container != null) {
container.setVisibility(View.GONE);
}
}
}
}
}
public void setMissedCalls(Cursor data) {
final int missed;
if (data == null) {
missed = 0;
} else {
missed = data.getCount();
}
// Only need to update if the number of calls changed.
if (missed != mNumMissedCalls) {
mNumMissedCalls = missed;
notifyDataSetChanged();
}
}
protected View.OnClickListener getBadgeClickListener() {
return new View.OnClickListener() {
@Override
public void onClick(View v) {
final Intent intent = new Intent(mContext, CallLogActivity.class);
mContext.startActivity(intent);
}
};
}
/**
* Get the resource id for the image to be shown for the badge.
*/
protected int getBadgeImageResId() {
return R.drawable.ic_call_log_blue;
}
/**
* Get the text to be shown for the badge.
*
* @param numMissed The number of missed calls.
*/
protected String getBadgeText(int numMissed) {
return mContext.getResources().getString(R.string.num_missed_calls, numMissed);
}
/**
* Whether to show the badge.
*
* @param numMissedCalls The number of missed calls.
* @param info The contact info.
* @param details The call detail.
* @return {@literal true} if badge should be shown. {@literal false} otherwise.
*/
protected boolean shouldShowBadge(int numMissedCalls, ContactInfo info,
PhoneCallDetails details) {
// Do not process if the data has not changed (optimization since bind view is called
// multiple times due to contact lookup).
if (numMissedCalls == mNumMissedCallsShown) {
return false;
}
return numMissedCalls > 0;
}
private int getNumMissedCalls(int callType) {
if (callType == Calls.MISSED_TYPE) {
// Exclude the current missed call shown in the shortcut.
return mNumMissedCalls - 1;
}
return mNumMissedCalls;
}
/** Checks whether the contact info from the call log matches the one from the contacts db. */
private boolean callLogInfoMatches(ContactInfo callLogInfo, ContactInfo info) {
// The call log only contains a subset of the fields in the contacts db.
// Only check those.
return TextUtils.equals(callLogInfo.name, info.name)
&& callLogInfo.type == info.type
&& TextUtils.equals(callLogInfo.label, info.label);
}
/** Stores the updated contact info in the call log if it is different from the current one. */
private void updateCallLogContactInfoCache(String number, String countryIso,
ContactInfo updatedInfo, ContactInfo callLogInfo) {
final ContentValues values = new ContentValues();
boolean needsUpdate = false;
if (callLogInfo != null) {
if (!TextUtils.equals(updatedInfo.name, callLogInfo.name)) {
values.put(Calls.CACHED_NAME, updatedInfo.name);
needsUpdate = true;
}
if (updatedInfo.type != callLogInfo.type) {
values.put(Calls.CACHED_NUMBER_TYPE, updatedInfo.type);
needsUpdate = true;
}
if (!TextUtils.equals(updatedInfo.label, callLogInfo.label)) {
values.put(Calls.CACHED_NUMBER_LABEL, updatedInfo.label);
needsUpdate = true;
}
if (!UriUtils.areEqual(updatedInfo.lookupUri, callLogInfo.lookupUri)) {
values.put(Calls.CACHED_LOOKUP_URI, UriUtils.uriToString(updatedInfo.lookupUri));
needsUpdate = true;
}
if (!TextUtils.equals(updatedInfo.normalizedNumber, callLogInfo.normalizedNumber)) {
values.put(Calls.CACHED_NORMALIZED_NUMBER, updatedInfo.normalizedNumber);
needsUpdate = true;
}
if (!TextUtils.equals(updatedInfo.number, callLogInfo.number)) {
values.put(Calls.CACHED_MATCHED_NUMBER, updatedInfo.number);
needsUpdate = true;
}
if (updatedInfo.photoId != callLogInfo.photoId) {
values.put(Calls.CACHED_PHOTO_ID, updatedInfo.photoId);
needsUpdate = true;
}
if (!TextUtils.equals(updatedInfo.formattedNumber, callLogInfo.formattedNumber)) {
values.put(Calls.CACHED_FORMATTED_NUMBER, updatedInfo.formattedNumber);
needsUpdate = true;
}
} else {
// No previous values, store all of them.
values.put(Calls.CACHED_NAME, updatedInfo.name);
values.put(Calls.CACHED_NUMBER_TYPE, updatedInfo.type);
values.put(Calls.CACHED_NUMBER_LABEL, updatedInfo.label);
values.put(Calls.CACHED_LOOKUP_URI, UriUtils.uriToString(updatedInfo.lookupUri));
values.put(Calls.CACHED_MATCHED_NUMBER, updatedInfo.number);
values.put(Calls.CACHED_NORMALIZED_NUMBER, updatedInfo.normalizedNumber);
values.put(Calls.CACHED_PHOTO_ID, updatedInfo.photoId);
values.put(Calls.CACHED_FORMATTED_NUMBER, updatedInfo.formattedNumber);
needsUpdate = true;
}
if (!needsUpdate) return;
if (countryIso == null) {
mContext.getContentResolver().update(Calls.CONTENT_URI_WITH_VOICEMAIL, values,
Calls.NUMBER + " = ? AND " + Calls.COUNTRY_ISO + " IS NULL",
new String[]{ number });
} else {
mContext.getContentResolver().update(Calls.CONTENT_URI_WITH_VOICEMAIL, values,
Calls.NUMBER + " = ? AND " + Calls.COUNTRY_ISO + " = ?",
new String[]{ number, countryIso });
}
}
/** Returns the contact information as stored in the call log. */
private ContactInfo getContactInfoFromCallLog(Cursor c) {
ContactInfo info = new ContactInfo();
info.lookupUri = UriUtils.parseUriOrNull(c.getString(CallLogQuery.CACHED_LOOKUP_URI));
info.name = c.getString(CallLogQuery.CACHED_NAME);
info.type = c.getInt(CallLogQuery.CACHED_NUMBER_TYPE);
info.label = c.getString(CallLogQuery.CACHED_NUMBER_LABEL);
String matchedNumber = c.getString(CallLogQuery.CACHED_MATCHED_NUMBER);
info.number = matchedNumber == null ? c.getString(CallLogQuery.NUMBER) : matchedNumber;
info.normalizedNumber = c.getString(CallLogQuery.CACHED_NORMALIZED_NUMBER);
info.photoId = c.getLong(CallLogQuery.CACHED_PHOTO_ID);
info.photoUri = null; // We do not cache the photo URI.
info.formattedNumber = c.getString(CallLogQuery.CACHED_FORMATTED_NUMBER);
return info;
}
/**
* Returns the call types for the given number of items in the cursor.
* <p>
* It uses the next {@code count} rows in the cursor to extract the types.
* <p>
* It position in the cursor is unchanged by this function.
*/
private int[] getCallTypes(Cursor cursor, int count) {
int position = cursor.getPosition();
int[] callTypes = new int[count];
for (int index = 0; index < count; ++index) {
callTypes[index] = cursor.getInt(CallLogQuery.CALL_TYPE);
cursor.moveToNext();
}
cursor.moveToPosition(position);
return callTypes;
}
private void setPhoto(CallLogListItemViews views, long photoId, Uri contactUri) {
mCurrentPhotoUri = null;
views.quickContactView.assignContactUri(contactUri);
mContactPhotoManager.loadThumbnail(views.quickContactView, photoId, false /* darkTheme */);
}
private void setPhoto(CallLogListItemViews views, Uri photoUri, Uri contactUri) {
if (photoUri.equals(mCurrentPhotoUri)) {
// photo manager will perform a fade in transition. To avoid flicker, do not set the
// same photo multiple times.
return;
}
mCurrentPhotoUri = photoUri;
views.quickContactView.assignContactUri(contactUri);
mContactPhotoManager.loadDirectoryPhoto(views.quickContactView, photoUri,
false /* darkTheme */);
}
/**
* Sets whether processing of requests for contact details should be enabled.
* <p>
* This method should be called in tests to disable such processing of requests when not
* needed.
*/
@VisibleForTesting
void disableRequestProcessingForTest() {
mRequestProcessingDisabled = true;
}
@VisibleForTesting
void injectContactInfoForTest(String number, String countryIso, ContactInfo contactInfo) {
NumberWithCountryIso numberCountryIso = new NumberWithCountryIso(number, countryIso);
mContactInfoCache.put(numberCountryIso, contactInfo);
}
@Override
public void addGroup(int cursorPosition, int size, boolean expanded) {
super.addGroup(cursorPosition, size, expanded);
}
/*
* Get the number from the Contacts, if available, since sometimes
* the number provided by caller id may not be formatted properly
* depending on the carrier (roaming) in use at the time of the
* incoming call.
* Logic : If the caller-id number starts with a "+", use it
* Else if the number in the contacts starts with a "+", use that one
* Else if the number in the contacts is longer, use that one
*/
public String getBetterNumberFromContacts(String number, String countryIso) {
String matchingNumber = null;
// Look in the cache first. If it's not found then query the Phones db
NumberWithCountryIso numberCountryIso = new NumberWithCountryIso(number, countryIso);
ContactInfo ci = mContactInfoCache.getPossiblyExpired(numberCountryIso);
if (ci != null && ci != ContactInfo.EMPTY) {
matchingNumber = ci.number;
} else {
try {
Cursor phonesCursor = mContext.getContentResolver().query(
Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, number),
PhoneQuery._PROJECTION, null, null, null);
if (phonesCursor != null) {
if (phonesCursor.moveToFirst()) {
matchingNumber = phonesCursor.getString(PhoneQuery.MATCHED_NUMBER);
}
phonesCursor.close();
}
} catch (Exception e) {
// Use the number from the call log
}
}
if (!TextUtils.isEmpty(matchingNumber) &&
(matchingNumber.startsWith("+")
|| matchingNumber.length() > number.length())) {
number = matchingNumber;
}
return number;
}
}
| true | true | private void bindView(View view, Cursor c, int count) {
final CallLogListItemViews views = (CallLogListItemViews) view.getTag();
// Default case: an item in the call log.
views.primaryActionView.setVisibility(View.VISIBLE);
views.listHeaderTextView.setVisibility(View.GONE);
final String number = c.getString(CallLogQuery.NUMBER);
final int numberPresentation = c.getInt(CallLogQuery.NUMBER_PRESENTATION);
final long date = c.getLong(CallLogQuery.DATE);
final long duration = c.getLong(CallLogQuery.DURATION);
final int callType = c.getInt(CallLogQuery.CALL_TYPE);
final String countryIso = c.getString(CallLogQuery.COUNTRY_ISO);
final ContactInfo cachedContactInfo = getContactInfoFromCallLog(c);
if (!mUseCallAsPrimaryAction) {
// Sets the primary action to open call detail page.
views.primaryActionView.setTag(
IntentProvider.getCallDetailIntentProvider(
getCursor(), c.getPosition(), c.getLong(CallLogQuery.ID), count));
} else if (PhoneNumberUtilsWrapper.canPlaceCallsTo(number, numberPresentation)) {
// Sets the primary action to call the number.
views.primaryActionView.setTag(IntentProvider.getReturnCallIntentProvider(number));
}
// Store away the voicemail information so we can play it directly.
if (callType == Calls.VOICEMAIL_TYPE) {
String voicemailUri = c.getString(CallLogQuery.VOICEMAIL_URI);
final long rowId = c.getLong(CallLogQuery.ID);
views.secondaryActionView.setTag(
IntentProvider.getPlayVoicemailIntentProvider(rowId, voicemailUri));
} else if (!TextUtils.isEmpty(number)) {
// Store away the number so we can call it directly if you click on the call icon.
views.secondaryActionView.setTag(
IntentProvider.getReturnCallIntentProvider(number));
} else {
// No action enabled.
views.secondaryActionView.setTag(null);
}
// Lookup contacts with this number
NumberWithCountryIso numberCountryIso = new NumberWithCountryIso(number, countryIso);
ExpirableCache.CachedValue<ContactInfo> cachedInfo =
mContactInfoCache.getCachedValue(numberCountryIso);
ContactInfo info = cachedInfo == null ? null : cachedInfo.getValue();
if (!PhoneNumberUtilsWrapper.canPlaceCallsTo(number, numberPresentation)
|| new PhoneNumberUtilsWrapper().isVoicemailNumber(number)) {
// If this is a number that cannot be dialed, there is no point in looking up a contact
// for it.
info = ContactInfo.EMPTY;
} else if (cachedInfo == null) {
mContactInfoCache.put(numberCountryIso, ContactInfo.EMPTY);
// Use the cached contact info from the call log.
info = cachedContactInfo;
// The db request should happen on a non-UI thread.
// Request the contact details immediately since they are currently missing.
enqueueRequest(number, countryIso, cachedContactInfo, true);
// We will format the phone number when we make the background request.
} else {
if (cachedInfo.isExpired()) {
// The contact info is no longer up to date, we should request it. However, we
// do not need to request them immediately.
enqueueRequest(number, countryIso, cachedContactInfo, false);
} else if (!callLogInfoMatches(cachedContactInfo, info)) {
// The call log information does not match the one we have, look it up again.
// We could simply update the call log directly, but that needs to be done in a
// background thread, so it is easier to simply request a new lookup, which will, as
// a side-effect, update the call log.
enqueueRequest(number, countryIso, cachedContactInfo, false);
}
if (info == ContactInfo.EMPTY) {
// Use the cached contact info from the call log.
info = cachedContactInfo;
}
}
final Uri lookupUri = info.lookupUri;
final String name = info.name;
final int ntype = info.type;
final String label = info.label;
final long photoId = info.photoId;
final Uri photoUri = info.photoUri;
CharSequence formattedNumber = info.formattedNumber;
final int[] callTypes = getCallTypes(c, count);
final String geocode = c.getString(CallLogQuery.GEOCODED_LOCATION);
final PhoneCallDetails details;
if (TextUtils.isEmpty(name)) {
details = new PhoneCallDetails(number, numberPresentation,
formattedNumber, countryIso, geocode, callTypes, date,
duration);
} else {
details = new PhoneCallDetails(number, numberPresentation,
formattedNumber, countryIso, geocode, callTypes, date,
duration, name, ntype, label, lookupUri, photoUri);
}
final boolean isNew = c.getInt(CallLogQuery.IS_READ) == 0;
// New items also use the highlighted version of the text.
final boolean isHighlighted = isNew;
mCallLogViewsHelper.setPhoneCallDetails(views, details, isHighlighted,
mUseCallAsPrimaryAction);
if (photoId == 0 && photoUri != null) {
setPhoto(views, photoUri, lookupUri);
} else {
setPhoto(views, photoId, lookupUri);
}
views.quickContactView.setContentDescription(views.phoneCallDetailsViews.nameView.
getText());
// Listen for the first draw
if (mViewTreeObserver == null) {
mViewTreeObserver = view.getViewTreeObserver();
mViewTreeObserver.addOnPreDrawListener(this);
}
bindBadge(view, info, details, callType);
}
| private void bindView(View view, Cursor c, int count) {
final CallLogListItemViews views = (CallLogListItemViews) view.getTag();
// Default case: an item in the call log.
views.primaryActionView.setVisibility(View.VISIBLE);
views.listHeaderTextView.setVisibility(View.GONE);
final String number = c.getString(CallLogQuery.NUMBER);
final int numberPresentation = c.getInt(CallLogQuery.NUMBER_PRESENTATION);
final long date = c.getLong(CallLogQuery.DATE);
final long duration = c.getLong(CallLogQuery.DURATION);
final int callType = c.getInt(CallLogQuery.CALL_TYPE);
final String countryIso = c.getString(CallLogQuery.COUNTRY_ISO);
final ContactInfo cachedContactInfo = getContactInfoFromCallLog(c);
if (!mUseCallAsPrimaryAction) {
// Sets the primary action to open call detail page.
views.primaryActionView.setTag(
IntentProvider.getCallDetailIntentProvider(
getCursor(), c.getPosition(), c.getLong(CallLogQuery.ID), count));
} else if (PhoneNumberUtilsWrapper.canPlaceCallsTo(number, numberPresentation)) {
// Sets the primary action to call the number.
views.primaryActionView.setTag(IntentProvider.getReturnCallIntentProvider(number));
} else {
views.primaryActionView.setTag(null);
}
// Store away the voicemail information so we can play it directly.
if (callType == Calls.VOICEMAIL_TYPE) {
String voicemailUri = c.getString(CallLogQuery.VOICEMAIL_URI);
final long rowId = c.getLong(CallLogQuery.ID);
views.secondaryActionView.setTag(
IntentProvider.getPlayVoicemailIntentProvider(rowId, voicemailUri));
} else if (!TextUtils.isEmpty(number)) {
// Store away the number so we can call it directly if you click on the call icon.
views.secondaryActionView.setTag(
IntentProvider.getReturnCallIntentProvider(number));
} else {
// No action enabled.
views.secondaryActionView.setTag(null);
}
// Lookup contacts with this number
NumberWithCountryIso numberCountryIso = new NumberWithCountryIso(number, countryIso);
ExpirableCache.CachedValue<ContactInfo> cachedInfo =
mContactInfoCache.getCachedValue(numberCountryIso);
ContactInfo info = cachedInfo == null ? null : cachedInfo.getValue();
if (!PhoneNumberUtilsWrapper.canPlaceCallsTo(number, numberPresentation)
|| new PhoneNumberUtilsWrapper().isVoicemailNumber(number)) {
// If this is a number that cannot be dialed, there is no point in looking up a contact
// for it.
info = ContactInfo.EMPTY;
} else if (cachedInfo == null) {
mContactInfoCache.put(numberCountryIso, ContactInfo.EMPTY);
// Use the cached contact info from the call log.
info = cachedContactInfo;
// The db request should happen on a non-UI thread.
// Request the contact details immediately since they are currently missing.
enqueueRequest(number, countryIso, cachedContactInfo, true);
// We will format the phone number when we make the background request.
} else {
if (cachedInfo.isExpired()) {
// The contact info is no longer up to date, we should request it. However, we
// do not need to request them immediately.
enqueueRequest(number, countryIso, cachedContactInfo, false);
} else if (!callLogInfoMatches(cachedContactInfo, info)) {
// The call log information does not match the one we have, look it up again.
// We could simply update the call log directly, but that needs to be done in a
// background thread, so it is easier to simply request a new lookup, which will, as
// a side-effect, update the call log.
enqueueRequest(number, countryIso, cachedContactInfo, false);
}
if (info == ContactInfo.EMPTY) {
// Use the cached contact info from the call log.
info = cachedContactInfo;
}
}
final Uri lookupUri = info.lookupUri;
final String name = info.name;
final int ntype = info.type;
final String label = info.label;
final long photoId = info.photoId;
final Uri photoUri = info.photoUri;
CharSequence formattedNumber = info.formattedNumber;
final int[] callTypes = getCallTypes(c, count);
final String geocode = c.getString(CallLogQuery.GEOCODED_LOCATION);
final PhoneCallDetails details;
if (TextUtils.isEmpty(name)) {
details = new PhoneCallDetails(number, numberPresentation,
formattedNumber, countryIso, geocode, callTypes, date,
duration);
} else {
details = new PhoneCallDetails(number, numberPresentation,
formattedNumber, countryIso, geocode, callTypes, date,
duration, name, ntype, label, lookupUri, photoUri);
}
final boolean isNew = c.getInt(CallLogQuery.IS_READ) == 0;
// New items also use the highlighted version of the text.
final boolean isHighlighted = isNew;
mCallLogViewsHelper.setPhoneCallDetails(views, details, isHighlighted,
mUseCallAsPrimaryAction);
if (photoId == 0 && photoUri != null) {
setPhoto(views, photoUri, lookupUri);
} else {
setPhoto(views, photoId, lookupUri);
}
views.quickContactView.setContentDescription(views.phoneCallDetailsViews.nameView.
getText());
// Listen for the first draw
if (mViewTreeObserver == null) {
mViewTreeObserver = view.getViewTreeObserver();
mViewTreeObserver.addOnPreDrawListener(this);
}
bindBadge(view, info, details, callType);
}
|
diff --git a/bennu-core/src/myorg/_development/PropertiesManager.java b/bennu-core/src/myorg/_development/PropertiesManager.java
index 07793812..a1a39464 100755
--- a/bennu-core/src/myorg/_development/PropertiesManager.java
+++ b/bennu-core/src/myorg/_development/PropertiesManager.java
@@ -1,117 +1,117 @@
/*
* @(#)PropertiesManager.java
*
* Copyright 2009 Instituto Superior Tecnico
* Founding Authors: João Figueiredo, Luis Cruz, Paulo Abrantes, Susana Fernandes
*
* https://fenix-ashes.ist.utl.pt/
*
* This file is part of the MyOrg web application infrastructure.
*
* MyOrg 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 3 of the License, or
* (at your option) any later version.*
*
* MyOrg 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 MyOrg. If not, see <http://www.gnu.org/licenses/>.
*
*/
package myorg._development;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import myorg.domain.MyOrg;
import pt.ist.fenixWebFramework.Config;
import pt.ist.fenixWebFramework.Config.CasConfig;
/**
* The <code>PropertiesManager</code> class is a application wide utility for
* accessing the applications configuration and properties.
*
* @author João Figueiredo
* @author Luis Cruz
* @author Paulo Abrantes
* @author Susana Fernandes
*
* @version 1.0
*/
public class PropertiesManager extends pt.utl.ist.fenix.tools.util.PropertiesManager {
private static final Properties properties = new Properties();
static {
try {
loadProperties(properties, "/configuration.properties");
} catch (IOException e) {
throw new RuntimeException("Unable to load properties files.", e);
}
}
public static String getProperty(final String key) {
return properties.getProperty(key);
}
public static boolean getBooleanProperty(final String key) {
return Boolean.parseBoolean(properties.getProperty(key));
}
public static Integer getIntegerProperty(final String key) {
return Integer.valueOf(properties.getProperty(key));
}
public static void setProperty(final String key, final String value) {
properties.setProperty(key, value);
}
public static Config getFenixFrameworkConfig(final String[] domainModels) {
final Map<String, CasConfig> casConfigMap = new HashMap<String, CasConfig>();
for (final Object key : properties.keySet()) {
final String property = (String) key;
int i = property.indexOf(".cas.enable");
if (i >= 0) {
final String hostname = property.substring(0, i);
if (getBooleanProperty(property)) {
final String casLoginUrl = getProperty(hostname + ".cas.loginUrl");
final String casLogoutUrl = getProperty(hostname + ".cas.logoutUrl");
final String casValidateUrl = getProperty(hostname + ".cas.ValidateUrl");
final String serviceUrl = getProperty(hostname + ".cas.serviceUrl");
final CasConfig casConfig = new CasConfig(casLoginUrl, casLogoutUrl, casValidateUrl, serviceUrl);
casConfigMap.put(hostname, casConfig);
}
}
}
return new Config() {{
domainModelPaths = domainModels;
dbAlias = getProperty("db.alias");
dbUsername = getProperty("db.user");
dbPassword = getProperty("db.pass");
appName = getProperty("app.name");
appContext = getProperty("app.context");
filterRequestWithDigest = getBooleanProperty("filter.request.with.digest");
tamperingRedirect = getProperty("digest.tampering.url");
errorIfChangingDeletedObject = getBooleanProperty("error.if.changing.deleted.object");
defaultLanguage = getProperty("language");
defaultLocation = getProperty("location");
defaultVariant = getProperty("variant");
updateDataRepositoryStructure = true;
updateRepositoryStructureIfNeeded = true;
casConfigByHost = Collections.unmodifiableMap(casConfigMap);
rootClass = MyOrg.class;
- javascriptValidationEnabled = false;
+ javascriptValidationEnabled = true;
}};
}
}
| true | true | public static Config getFenixFrameworkConfig(final String[] domainModels) {
final Map<String, CasConfig> casConfigMap = new HashMap<String, CasConfig>();
for (final Object key : properties.keySet()) {
final String property = (String) key;
int i = property.indexOf(".cas.enable");
if (i >= 0) {
final String hostname = property.substring(0, i);
if (getBooleanProperty(property)) {
final String casLoginUrl = getProperty(hostname + ".cas.loginUrl");
final String casLogoutUrl = getProperty(hostname + ".cas.logoutUrl");
final String casValidateUrl = getProperty(hostname + ".cas.ValidateUrl");
final String serviceUrl = getProperty(hostname + ".cas.serviceUrl");
final CasConfig casConfig = new CasConfig(casLoginUrl, casLogoutUrl, casValidateUrl, serviceUrl);
casConfigMap.put(hostname, casConfig);
}
}
}
return new Config() {{
domainModelPaths = domainModels;
dbAlias = getProperty("db.alias");
dbUsername = getProperty("db.user");
dbPassword = getProperty("db.pass");
appName = getProperty("app.name");
appContext = getProperty("app.context");
filterRequestWithDigest = getBooleanProperty("filter.request.with.digest");
tamperingRedirect = getProperty("digest.tampering.url");
errorIfChangingDeletedObject = getBooleanProperty("error.if.changing.deleted.object");
defaultLanguage = getProperty("language");
defaultLocation = getProperty("location");
defaultVariant = getProperty("variant");
updateDataRepositoryStructure = true;
updateRepositoryStructureIfNeeded = true;
casConfigByHost = Collections.unmodifiableMap(casConfigMap);
rootClass = MyOrg.class;
javascriptValidationEnabled = false;
}};
}
| public static Config getFenixFrameworkConfig(final String[] domainModels) {
final Map<String, CasConfig> casConfigMap = new HashMap<String, CasConfig>();
for (final Object key : properties.keySet()) {
final String property = (String) key;
int i = property.indexOf(".cas.enable");
if (i >= 0) {
final String hostname = property.substring(0, i);
if (getBooleanProperty(property)) {
final String casLoginUrl = getProperty(hostname + ".cas.loginUrl");
final String casLogoutUrl = getProperty(hostname + ".cas.logoutUrl");
final String casValidateUrl = getProperty(hostname + ".cas.ValidateUrl");
final String serviceUrl = getProperty(hostname + ".cas.serviceUrl");
final CasConfig casConfig = new CasConfig(casLoginUrl, casLogoutUrl, casValidateUrl, serviceUrl);
casConfigMap.put(hostname, casConfig);
}
}
}
return new Config() {{
domainModelPaths = domainModels;
dbAlias = getProperty("db.alias");
dbUsername = getProperty("db.user");
dbPassword = getProperty("db.pass");
appName = getProperty("app.name");
appContext = getProperty("app.context");
filterRequestWithDigest = getBooleanProperty("filter.request.with.digest");
tamperingRedirect = getProperty("digest.tampering.url");
errorIfChangingDeletedObject = getBooleanProperty("error.if.changing.deleted.object");
defaultLanguage = getProperty("language");
defaultLocation = getProperty("location");
defaultVariant = getProperty("variant");
updateDataRepositoryStructure = true;
updateRepositoryStructureIfNeeded = true;
casConfigByHost = Collections.unmodifiableMap(casConfigMap);
rootClass = MyOrg.class;
javascriptValidationEnabled = true;
}};
}
|
diff --git a/RichClient/src/main/java/com/tihiy/rclint/implement/ControlPanel.java b/RichClient/src/main/java/com/tihiy/rclint/implement/ControlPanel.java
index 0443d44..43b4c28 100644
--- a/RichClient/src/main/java/com/tihiy/rclint/implement/ControlPanel.java
+++ b/RichClient/src/main/java/com/tihiy/rclint/implement/ControlPanel.java
@@ -1,207 +1,207 @@
package com.tihiy.rclint.implement;
import com.tihiy.rclint.control.Controller;
import com.tihiy.rclint.mvcAbstract.AbstractViewPanel;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class ControlPanel extends AbstractViewPanel {
private final Controller mc;
private File defaultPath;
private File sourceFile;
public ControlPanel(Controller mc) {
this.mc = mc;
setBorder(BorderFactory.createLineBorder(Color.BLUE));
setLayout(new GridBagLayout());
initComponent();
}
private void initComponent(){
butChooseSignal = new JButton("Choose Signal");
butChooseFirstLayerSignal = new JButton("First Layer Signal");
butChooseBaseSignal = new JButton("Base signal");
butCalculate = new JButton("Calculate");
butDefault = new JButton("Default signal");
mainSizeA = new JTextField();
mainSizeB = new JTextField();
mainXShift = new JTextField();
mainYShift = new JTextField();
mainRSphere = new JTextField();
mainH = new JTextField();
firstSizeA = new JTextField();
firstSizeB = new JTextField();
butChooseSignal.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
sourceFile = chooseFile();
mc.addSignal("sourceSignal", sourceFile);
} catch (IOException e1) {
e1.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
});
butChooseFirstLayerSignal.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
mc.addSignal("targetSignal", chooseFile());
} catch (IOException e1) {
e1.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
});
butChooseBaseSignal.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
mc.addSignal("baseSignal", chooseFile());
} catch (IOException e1) {
- e1.printStackTrace(); // of catch statement use File | Settings | File Templates.
+ e1.printStackTrace(); // statement use File | Settings | File Templates.
}
}
});
butCalculate.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
double[] main = {Double.valueOf(mainSizeA.getText()), Double.valueOf(mainSizeB.getText()),
Double.valueOf(mainXShift.getText()), Double.valueOf(mainYShift.getText()),
Double.valueOf(mainRSphere.getText()), Double.valueOf(mainH.getText())};
double[] first = {Double.valueOf(firstSizeA.getText()), Double.valueOf(firstSizeB.getText())};
File radiusFile = new File(defaultPath, "radius"+ getDate()+sourceFile.getName());
mc.calculate(main, first, radiusFile, null);
}
});
butDefault.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
sourceFile = new File("C:\\Users\\Home\\Documents\\My Box Files\\Asp\\RoChange\\Rad 20130716\\P1.txt");
File roFile = new File("C:\\Users\\Home\\Documents\\My Box Files\\Asp\\RoChange\\Rad 20130716\\Ro.txt");
File baseFile = new File("C:\\Users\\Home\\Documents\\My Box Files\\Asp\\RoChange\\Rad 20130716\\PB1.txt");
try {
mc.addSignal("sourceSignal", sourceFile);
mc.addSignal("targetSignal", roFile);
mc.addSignal("baseSignal", baseFile);
} catch (IOException e1) {
e1.printStackTrace();
}
double[] main = {0.04,0.02,0,0.037,0.045,0.019};
double[] first = {0.06, 0.03};
defaultPath = new File("C:\\Users\\Home\\Documents\\My Box Files\\Asp\\RoChange\\Rad 20130716");
File radiusFile = new File(defaultPath, "radius"+getDate()+sourceFile.getName());
mc.calculate(main, first, radiusFile, getComment(roFile, baseFile, main, first));
}
});
GridBagConstraints constraints = new GridBagConstraints(0,0, 1,1, 0,0,
GridBagConstraints.NORTH, GridBagConstraints.BOTH, new Insets(5,5,5,5), 0,0);
add(butChooseSignal, constraints);
constraints.gridy = 1;
add(butChooseFirstLayerSignal, constraints);
constraints.gridy = 2;
add(butChooseBaseSignal, constraints);
constraints.gridy = 3;
add(butCalculate, constraints);
constraints.gridy = 4;
add(butDefault);
constraints.gridy = 5;
constraints.gridx = 0;
constraints.insets = new Insets(0,5,0,5);
add(new Label("Size A(main)"), constraints);
constraints.gridx = 1;
add(mainSizeA, constraints);
constraints.gridy = 6;
constraints.gridx = 0;
add(new Label("Size B(main)"), constraints);
constraints.gridx = 1;
add(mainSizeB, constraints);
constraints.gridy = 7;
constraints.gridx = 0;
add(new Label("Shift X(main)"), constraints);
constraints.gridx = 1;
add(mainXShift, constraints);
constraints.gridy = 8;
constraints.gridx = 0;
add(new Label("Shift Y(main)"), constraints);
constraints.gridx = 1;
add(mainYShift, constraints);
constraints.gridy = 9;
constraints.gridx = 0;
add(new Label("R sphere(main)"), constraints);
constraints.gridx = 1;
add(mainRSphere, constraints);
constraints.gridy = 10;
constraints.gridx = 0;
add(new Label("H (main)"), constraints);
constraints.gridx = 1;
add(mainH, constraints);
constraints.gridy = 11;
constraints.gridx = 0;
add(new Label("Size A(FL)"), constraints);
constraints.gridx = 1;
add(firstSizeA, constraints);
constraints.gridy = 12;
constraints.gridx = 0;
add(new Label("Size B(FL)"), constraints);
constraints.gridx = 1;
add(firstSizeB, constraints);
}
@Override
public void modelPropertyChange(PropertyChangeEvent evt) {
}
private JButton butChooseSignal;
private JButton butChooseFirstLayerSignal;
private JButton butChooseBaseSignal;
private JButton butCalculate;
private JButton butDefault;
private JTextField mainSizeA;
private JTextField mainSizeB;
private JTextField mainXShift;
private JTextField mainYShift;
private JTextField mainRSphere;
private JTextField mainH;
private JTextField firstSizeA;
private JTextField firstSizeB;
private File chooseFile(){
JFileChooser fileChooser = new JFileChooser();
fileChooser.changeToParentDirectory();
fileChooser.setCurrentDirectory(new File("C:\\Users\\Home\\Documents\\My Box Files\\Asp\\RoChange\\Rad 20130716"));
// defaultPath = new File("C:\\Users\\Home\\Documents\\My Box Files\\Asp\\RoChange\\Rad 20130716");
if(defaultPath!=null){
fileChooser.setCurrentDirectory( defaultPath);
}
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
fileChooser.showDialog(new JFrame(), "Choose signal!");
if(defaultPath==null){
defaultPath = fileChooser.getCurrentDirectory();
}
return fileChooser.getSelectedFile();
}
private static String getDate(){
Date dNow = new Date( );
SimpleDateFormat ft = new SimpleDateFormat ("_yyyy_MM_dd_hh_mm_ss");
return ft.format(dNow);
}
private String getComment(File roFile, File baseFile, double[] main, double[] first){
String comment = "Pulse="+sourceFile.getName()+" Ro="+roFile.getName()+" Base="+baseFile.getName()+" ";
comment += "pulseES:";
for(double d:main){
comment += " "+d;
}
comment += " baseES" + first[0]+" "+first[1]+" ";
return comment;
}
}
| true | true | private void initComponent(){
butChooseSignal = new JButton("Choose Signal");
butChooseFirstLayerSignal = new JButton("First Layer Signal");
butChooseBaseSignal = new JButton("Base signal");
butCalculate = new JButton("Calculate");
butDefault = new JButton("Default signal");
mainSizeA = new JTextField();
mainSizeB = new JTextField();
mainXShift = new JTextField();
mainYShift = new JTextField();
mainRSphere = new JTextField();
mainH = new JTextField();
firstSizeA = new JTextField();
firstSizeB = new JTextField();
butChooseSignal.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
sourceFile = chooseFile();
mc.addSignal("sourceSignal", sourceFile);
} catch (IOException e1) {
e1.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
});
butChooseFirstLayerSignal.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
mc.addSignal("targetSignal", chooseFile());
} catch (IOException e1) {
e1.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
});
butChooseBaseSignal.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
mc.addSignal("baseSignal", chooseFile());
} catch (IOException e1) {
e1.printStackTrace(); // of catch statement use File | Settings | File Templates.
}
}
});
butCalculate.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
double[] main = {Double.valueOf(mainSizeA.getText()), Double.valueOf(mainSizeB.getText()),
Double.valueOf(mainXShift.getText()), Double.valueOf(mainYShift.getText()),
Double.valueOf(mainRSphere.getText()), Double.valueOf(mainH.getText())};
double[] first = {Double.valueOf(firstSizeA.getText()), Double.valueOf(firstSizeB.getText())};
File radiusFile = new File(defaultPath, "radius"+ getDate()+sourceFile.getName());
mc.calculate(main, first, radiusFile, null);
}
});
butDefault.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
sourceFile = new File("C:\\Users\\Home\\Documents\\My Box Files\\Asp\\RoChange\\Rad 20130716\\P1.txt");
File roFile = new File("C:\\Users\\Home\\Documents\\My Box Files\\Asp\\RoChange\\Rad 20130716\\Ro.txt");
File baseFile = new File("C:\\Users\\Home\\Documents\\My Box Files\\Asp\\RoChange\\Rad 20130716\\PB1.txt");
try {
mc.addSignal("sourceSignal", sourceFile);
mc.addSignal("targetSignal", roFile);
mc.addSignal("baseSignal", baseFile);
} catch (IOException e1) {
e1.printStackTrace();
}
double[] main = {0.04,0.02,0,0.037,0.045,0.019};
double[] first = {0.06, 0.03};
defaultPath = new File("C:\\Users\\Home\\Documents\\My Box Files\\Asp\\RoChange\\Rad 20130716");
File radiusFile = new File(defaultPath, "radius"+getDate()+sourceFile.getName());
mc.calculate(main, first, radiusFile, getComment(roFile, baseFile, main, first));
}
});
GridBagConstraints constraints = new GridBagConstraints(0,0, 1,1, 0,0,
GridBagConstraints.NORTH, GridBagConstraints.BOTH, new Insets(5,5,5,5), 0,0);
add(butChooseSignal, constraints);
constraints.gridy = 1;
add(butChooseFirstLayerSignal, constraints);
constraints.gridy = 2;
add(butChooseBaseSignal, constraints);
constraints.gridy = 3;
add(butCalculate, constraints);
constraints.gridy = 4;
add(butDefault);
constraints.gridy = 5;
constraints.gridx = 0;
constraints.insets = new Insets(0,5,0,5);
add(new Label("Size A(main)"), constraints);
constraints.gridx = 1;
add(mainSizeA, constraints);
constraints.gridy = 6;
constraints.gridx = 0;
add(new Label("Size B(main)"), constraints);
constraints.gridx = 1;
add(mainSizeB, constraints);
constraints.gridy = 7;
constraints.gridx = 0;
add(new Label("Shift X(main)"), constraints);
constraints.gridx = 1;
add(mainXShift, constraints);
constraints.gridy = 8;
constraints.gridx = 0;
add(new Label("Shift Y(main)"), constraints);
constraints.gridx = 1;
add(mainYShift, constraints);
constraints.gridy = 9;
constraints.gridx = 0;
add(new Label("R sphere(main)"), constraints);
constraints.gridx = 1;
add(mainRSphere, constraints);
constraints.gridy = 10;
constraints.gridx = 0;
add(new Label("H (main)"), constraints);
constraints.gridx = 1;
add(mainH, constraints);
constraints.gridy = 11;
constraints.gridx = 0;
add(new Label("Size A(FL)"), constraints);
constraints.gridx = 1;
add(firstSizeA, constraints);
constraints.gridy = 12;
constraints.gridx = 0;
add(new Label("Size B(FL)"), constraints);
constraints.gridx = 1;
add(firstSizeB, constraints);
}
| private void initComponent(){
butChooseSignal = new JButton("Choose Signal");
butChooseFirstLayerSignal = new JButton("First Layer Signal");
butChooseBaseSignal = new JButton("Base signal");
butCalculate = new JButton("Calculate");
butDefault = new JButton("Default signal");
mainSizeA = new JTextField();
mainSizeB = new JTextField();
mainXShift = new JTextField();
mainYShift = new JTextField();
mainRSphere = new JTextField();
mainH = new JTextField();
firstSizeA = new JTextField();
firstSizeB = new JTextField();
butChooseSignal.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
sourceFile = chooseFile();
mc.addSignal("sourceSignal", sourceFile);
} catch (IOException e1) {
e1.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
});
butChooseFirstLayerSignal.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
mc.addSignal("targetSignal", chooseFile());
} catch (IOException e1) {
e1.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
});
butChooseBaseSignal.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
mc.addSignal("baseSignal", chooseFile());
} catch (IOException e1) {
e1.printStackTrace(); // statement use File | Settings | File Templates.
}
}
});
butCalculate.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
double[] main = {Double.valueOf(mainSizeA.getText()), Double.valueOf(mainSizeB.getText()),
Double.valueOf(mainXShift.getText()), Double.valueOf(mainYShift.getText()),
Double.valueOf(mainRSphere.getText()), Double.valueOf(mainH.getText())};
double[] first = {Double.valueOf(firstSizeA.getText()), Double.valueOf(firstSizeB.getText())};
File radiusFile = new File(defaultPath, "radius"+ getDate()+sourceFile.getName());
mc.calculate(main, first, radiusFile, null);
}
});
butDefault.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
sourceFile = new File("C:\\Users\\Home\\Documents\\My Box Files\\Asp\\RoChange\\Rad 20130716\\P1.txt");
File roFile = new File("C:\\Users\\Home\\Documents\\My Box Files\\Asp\\RoChange\\Rad 20130716\\Ro.txt");
File baseFile = new File("C:\\Users\\Home\\Documents\\My Box Files\\Asp\\RoChange\\Rad 20130716\\PB1.txt");
try {
mc.addSignal("sourceSignal", sourceFile);
mc.addSignal("targetSignal", roFile);
mc.addSignal("baseSignal", baseFile);
} catch (IOException e1) {
e1.printStackTrace();
}
double[] main = {0.04,0.02,0,0.037,0.045,0.019};
double[] first = {0.06, 0.03};
defaultPath = new File("C:\\Users\\Home\\Documents\\My Box Files\\Asp\\RoChange\\Rad 20130716");
File radiusFile = new File(defaultPath, "radius"+getDate()+sourceFile.getName());
mc.calculate(main, first, radiusFile, getComment(roFile, baseFile, main, first));
}
});
GridBagConstraints constraints = new GridBagConstraints(0,0, 1,1, 0,0,
GridBagConstraints.NORTH, GridBagConstraints.BOTH, new Insets(5,5,5,5), 0,0);
add(butChooseSignal, constraints);
constraints.gridy = 1;
add(butChooseFirstLayerSignal, constraints);
constraints.gridy = 2;
add(butChooseBaseSignal, constraints);
constraints.gridy = 3;
add(butCalculate, constraints);
constraints.gridy = 4;
add(butDefault);
constraints.gridy = 5;
constraints.gridx = 0;
constraints.insets = new Insets(0,5,0,5);
add(new Label("Size A(main)"), constraints);
constraints.gridx = 1;
add(mainSizeA, constraints);
constraints.gridy = 6;
constraints.gridx = 0;
add(new Label("Size B(main)"), constraints);
constraints.gridx = 1;
add(mainSizeB, constraints);
constraints.gridy = 7;
constraints.gridx = 0;
add(new Label("Shift X(main)"), constraints);
constraints.gridx = 1;
add(mainXShift, constraints);
constraints.gridy = 8;
constraints.gridx = 0;
add(new Label("Shift Y(main)"), constraints);
constraints.gridx = 1;
add(mainYShift, constraints);
constraints.gridy = 9;
constraints.gridx = 0;
add(new Label("R sphere(main)"), constraints);
constraints.gridx = 1;
add(mainRSphere, constraints);
constraints.gridy = 10;
constraints.gridx = 0;
add(new Label("H (main)"), constraints);
constraints.gridx = 1;
add(mainH, constraints);
constraints.gridy = 11;
constraints.gridx = 0;
add(new Label("Size A(FL)"), constraints);
constraints.gridx = 1;
add(firstSizeA, constraints);
constraints.gridy = 12;
constraints.gridx = 0;
add(new Label("Size B(FL)"), constraints);
constraints.gridx = 1;
add(firstSizeB, constraints);
}
|
diff --git a/src/edu/osu/cse/meisam/interpreter/Interpreter.java b/src/edu/osu/cse/meisam/interpreter/Interpreter.java
index c523365..61e17d7 100644
--- a/src/edu/osu/cse/meisam/interpreter/Interpreter.java
+++ b/src/edu/osu/cse/meisam/interpreter/Interpreter.java
@@ -1,57 +1,57 @@
/**
* Lisp Subinterpreter, an interpreter for a sublanguage of Lisp
* Copyright (C) 2011 Meisam Fathi Salmi <[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 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 edu.osu.cse.meisam.interpreter;
import java.io.InputStream;
import java.io.PrintStream;
/**
* @author Meisam Fathi Salmi <[email protected]>
*
*/
public class Interpreter {
private final InputProvider in;
private final Lexer lexer;
private final Parser parser;
public Interpreter(final InputStream in, final PrintStream out) {
this.in = new InputStreamProvider(in);
this.lexer = new Lexer(this.in);
this.parser = new Parser(this.lexer);
}
/**
* @param args
*/
public static void main(final String[] args) {
try {
final Interpreter interpreter = new Interpreter(System.in,
System.out);
interpreter.interpret();
} catch (final Exception ex) {
- System.out.println("Error: " + ex.getMessage());
+ System.err.println("Error: " + ex.getMessage());
}
}
public void interpret() {
this.parser.parse();
}
}
| true | true | public static void main(final String[] args) {
try {
final Interpreter interpreter = new Interpreter(System.in,
System.out);
interpreter.interpret();
} catch (final Exception ex) {
System.out.println("Error: " + ex.getMessage());
}
}
| public static void main(final String[] args) {
try {
final Interpreter interpreter = new Interpreter(System.in,
System.out);
interpreter.interpret();
} catch (final Exception ex) {
System.err.println("Error: " + ex.getMessage());
}
}
|
diff --git a/src/java/fedora/server/access/dissemination/DisseminationService.java b/src/java/fedora/server/access/dissemination/DisseminationService.java
index 67b5f5546..7959beb4a 100755
--- a/src/java/fedora/server/access/dissemination/DisseminationService.java
+++ b/src/java/fedora/server/access/dissemination/DisseminationService.java
@@ -1,756 +1,756 @@
package fedora.server.access.dissemination;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.net.URLEncoder;
import java.sql.Timestamp;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import fedora.common.Constants;
import fedora.server.Context;
import fedora.server.ReadOnlyContext;
import fedora.server.Server;
import fedora.server.errors.DisseminationException;
import fedora.server.errors.DisseminationBindingInfoNotFoundException;
import fedora.server.errors.GeneralException;
import fedora.server.errors.InitializationException;
import fedora.server.errors.ServerException;
import fedora.server.errors.ServerInitializationException;
import fedora.server.security.Authorization;
import fedora.server.storage.DOManager;
import fedora.server.storage.DOReader;
import fedora.server.storage.ExternalContentManager;
import fedora.server.storage.types.Datastream;
import fedora.server.storage.types.DatastreamMediation;
import fedora.server.storage.types.DisseminationBindingInfo;
import fedora.server.storage.types.MIMETypedStream;
import fedora.server.storage.types.MethodParmDef;
import fedora.server.utilities.DateUtility;
/**
* <p><b>Title: </b>DisseminationService.java</p>
* <p><b>Description: </b>A service for executing a dissemination given its
* binding information.</p>
*
* @author [email protected]
* @version $Id$
*/
public class DisseminationService
{
/** The Fedora Server instance */
private static Server s_server;
/** An instance of DO manager */
private static DOManager m_manager;
/** Signifies the special type of address location known as LOCAL.
* An address location of LOCAL implies that no remote host name is
* required for the address location and that the contents of the
* operation location are sufficient to execute the associated mechanism.
*/
private static final String LOCAL_ADDRESS_LOCATION = "LOCAL";
/** The expiration limit in minutes for removing entries from the database. */
private static int datastreamExpirationLimit = 0;
/** An incremental counter used to insure uniqueness of tempIDs used for
* datastream mediation.
*/
private static int counter = 0;
/** Datastream Mediation control flag. */
private static boolean doDatastreamMediation;
/** Make sure we have a server instance for error logging purposes. */
static
{
try
{
String fedoraHome = System.getProperty("fedora.home");
if (fedoraHome == null)
{
throw new ServerInitializationException(
"[DisseminationService] Server failed to initialize: The "
+ "'fedora.home' system property was not set.");
} else
{
s_server = Server.getInstance(new File(fedoraHome));
m_manager = (DOManager) s_server.getModule("fedora.server.storage.DOManager");
String expireLimit = s_server.getParameter("datastreamExpirationLimit");
if (expireLimit == null || expireLimit.equalsIgnoreCase(""))
{
s_server.logWarning("[DisseminationService] Unable to resolve "
+ "the datastream expiration limit from the configuration"
+ "file. The expiration limit has been set to 300 seconds.");
datastreamExpirationLimit = 300;
} else
{
datastreamExpirationLimit = new Integer(expireLimit).intValue();
s_server.logFinest("[DisseminationService] datastreamExpirationLimit: "
+ datastreamExpirationLimit);
}
String dsMediation =
s_server.getModule("fedora.server.access.Access").getParameter("doMediateDatastreams");
if (dsMediation == null || dsMediation.equalsIgnoreCase(""))
{
s_server.logWarning("[DisseminationService] Unable to resolve "
+ "doDatastreamMediation parameter from the configuration "
+ "file. ");
} else
{
doDatastreamMediation = new Boolean(dsMediation).booleanValue();
}
}
} catch (InitializationException ie)
{
System.err.println(ie.getMessage());
}
}
/** The hashtable containing information required for datastream mediation. */
protected static Hashtable dsRegistry = new Hashtable(1000);
/**
* <p>Constructs an instance of DisseminationService. Initializes two class
* variables that contain the IP address and port number of the Fedora server.
* The port number is obtained from the Fedora server config file and the IP
* address of the server is obtained dynamically. These variables are needed
* to perform the datastream proxy service for datastream requests.</p>
*/
public DisseminationService()
{ }
/*
public void checkState(Context context, String state, String dsID, String PID)
throws ServerException
{
// Check Object State
if ( state.equalsIgnoreCase("D") &&
( context.get("canUseDeletedObject")==null
|| (!context.get("canUseDeletedObject").equals("true")) )
)
{
throw new GeneralException("The requested dissemination for data object \""+PID+"\" is no "
+ "longer available. One of its datastreams (dsID=\""+dsID+"\") has been flagged for DELETION "
+ "by the repository administrator. ");
} else if ( state.equalsIgnoreCase("I") &&
( context.get("canUseInactiveObject")==null
|| (!context.get("canUseInactiveObject").equals("true")) )
)
{
throw new GeneralException("The requested dissemination for data object \""+PID+"\" is no "
+ "longer available. One of its datastreams (dsID=\""+dsID+"\") has been flagged as INACTIVE "
+ "by the repository administrator. ");
}
}
*/
/**
* <p>Assembles a dissemination given an instance of <code>
* DisseminationBindingInfo</code> which has the dissemination-related
* information from the digital object and its associated Behavior
* Mechanism object.</p>
*
* @param context The current context.
* @param PID The persistent identifier of the digital object.
* @param h_userParms A hashtable of user-supplied method parameters.
* @param dissBindInfoArray The associated dissemination binding information.
* @return A MIME-typed stream containing the result of the dissemination.
* @throws ServerException If unable to assemble the dissemination for any
* reason.
*/
public MIMETypedStream assembleDissemination(Context context, String PID,
Hashtable h_userParms, DisseminationBindingInfo[] dissBindInfoArray, String reposBaseURL)
throws ServerException
{
if (reposBaseURL == null || reposBaseURL.equals(""))
{
throw new DisseminationException("[DisseminationService] was unable to "
+ "resolve the base URL of the Fedora Server. The URL specified was: \""
+ reposBaseURL + "\". This information is required by the Dissemination Service.");
}
String datastreamResolverServletURL = reposBaseURL + "/fedora/getDS?id=";
if (fedora.server.Debug.DEBUG) {
printBindingInfo(dissBindInfoArray);
}
long initStartTime = new Date().getTime();
long startTime = new Date().getTime();
String protocolType = null;
DisseminationBindingInfo dissBindInfo = null;
String dissURL = null;
MIMETypedStream dissemination = null;
boolean isRedirect = false;
if (dissBindInfoArray != null && dissBindInfoArray.length > 0)
{
String replaceString = null;
int numElements = dissBindInfoArray.length;
// Get row(s) of binding info and perform string substitution
// on DSBindingKey and method parameter values in WSDL
// Note: In case where more than one datastream matches the
// DSBindingKey or there are multiple DSBindingKeys for the
// method, multiple rows will be present; otherwise there is only
// a single row.
for (int i=0; i<dissBindInfoArray.length; i++)
{
- ((Authorization)s_server.getModule("Authorization")).enforce_Internal_DSState(
+ ((Authorization)s_server.getModule("fedora.server.security.Authorization")).enforce_Internal_DSState(
context, dissBindInfoArray[i].dsID, dissBindInfoArray[i].dsState);
dissBindInfo = dissBindInfoArray[i];
// Before doing anything, check whether we can replace any
// placeholders in the datastream url with parameter values from
// the request. This supports the special case where a
// datastream's URL is dependent on user parameters, such
// as when the datastream is actually a dissemination that
// takes parameters.
if (dissBindInfo.dsLocation!=null &&
( dissBindInfo.dsLocation.startsWith("http://")
|| dissBindInfo.dsLocation.startsWith("https://") ) ) {
String[] parts=dissBindInfo.dsLocation.split("=\\("); // regex for =(
if (parts.length>1) {
StringBuffer replaced=new StringBuffer();
replaced.append(parts[0]);
for (int x=1; x<parts.length; x++) {
replaced.append('=');
int rightParenPos=parts[x].indexOf(")");
if (rightParenPos!=-1 && rightParenPos>0) {
String key=parts[x].substring(0, rightParenPos);
String val=(String) h_userParms.get(key);
if (val!=null) {
// We have a match... so insert the urlencoded value.
try {
replaced.append(URLEncoder.encode(val, "UTF-8"));
} catch (UnsupportedEncodingException uee) {
// won't happen: java always supports UTF-8
}
if (rightParenPos<parts[x].length()) {
replaced.append(parts[x].substring(rightParenPos+1));
}
} else {
replaced.append('(');
replaced.append(parts[x]);
}
} else {
replaced.append('(');
replaced.append(parts[x]);
}
}
dissBindInfo.dsLocation=replaced.toString();
}
}
// Match DSBindingKey pattern in WSDL which is a string of the form:
// (DSBindingKey). Rows in DisseminationBindingInfo are sorted
// alphabetically on binding key.
String bindingKeyPattern = "\\(" + dissBindInfo.DSBindKey + "\\)";
if (i == 0)
{
// If addressLocation has a value of "LOCAL", this indicates
// the associated operationLocation requires no addressLocation.
// i.e., the operationLocation contains all information necessary
// to perform the dissemination request. This is a special case
// used when the web services are generally mechanisms like cgi-scripts,
// java servlets, and simple HTTP GETs. Using the value of LOCAL
// in the address location also enables one to have different methods
// serviced by different hosts. In true web services like SOAP, the
// addressLocation specifies the host name of the service and all
// methods are served from that single host location.
if (dissBindInfo.AddressLocation.equalsIgnoreCase(LOCAL_ADDRESS_LOCATION))
{
dissURL = dissBindInfo.OperationLocation;
} else
{
dissURL = dissBindInfo.AddressLocation+dissBindInfo.OperationLocation;
}
protocolType = dissBindInfo.ProtocolType;
}
String currentKey = dissBindInfo.DSBindKey;
String nextKey = "";
if (i != numElements-1)
{
// Except for last row, get the value of the next binding key
// to compare with the value of the current binding key.
nextKey = dissBindInfoArray[i+1].DSBindKey;
}
s_server.logFinest("[DisseminationService] currentKey: '"
+ currentKey + "'");
s_server.logFinest("[DisseminationService] nextKey: '"
+ nextKey + "'");
// In most cases, there is only a single datastream that matches a
// given DSBindingKey so the substitution process is to just replace
// the occurence of (BINDING_KEY) with the value of the datastream
// location. However, when multiple datastreams match the same
// DSBindingKey, the occurrence of (BINDING_KEY) is replaced with the
// value of the datastream location and the value +(BINDING_KEY) is
// appended so that subsequent datastreams matching the binding key
// will be substituted. The end result is that the binding key will
// be replaced by a series of datastream locations separated by a
// plus(+) sign. For example, in the case where 3 datastreams match
// the binding key for PHOTO:
//
// file=(PHOTO) becomes
// file=dslocation1+dslocation2+dslocation3
//
// It is the responsibility of the Behavior Mechanism to know how to
// handle an input parameter with multiple datastream locations.
//
// In the case of a method containing multiple binding keys,
// substitutions are performed on each binding key. For example, in
// the case where there are 2 binding keys named PHOTO and WATERMARK
// where each matches a single datastream:
//
// image=(PHOTO)&watermark=(WATERMARK) becomes
// image=dslocation1&watermark=dslocation2
//
// In the case with mutliple binding keys and multiple datastreams,
// the substitution might appear like the following:
//
// image=(PHOTO)&watermark=(WATERMARK) becomes
// image=dslocation1+dslocation2&watermark=dslocation3
if (nextKey.equalsIgnoreCase(currentKey) & i != numElements)
{
// Case where binding keys are equal which means that multiple
// datastreams matched the same binding key.
if (doDatastreamMediation &&
!dissBindInfo.dsControlGroupType.equalsIgnoreCase("R"))
{
// Use Datastream Mediation (except for redirected datastreams).
replaceString = datastreamResolverServletURL
+ registerDatastreamLocation(dissBindInfo.dsLocation,
dissBindInfo.dsControlGroupType)
+ "+(" + dissBindInfo.DSBindKey + ")";
} else
{
// Bypass Datastream Mediation.
if ( dissBindInfo.dsControlGroupType.equalsIgnoreCase("M") ||
dissBindInfo.dsControlGroupType.equalsIgnoreCase("X"))
{
// Use the Default Disseminator syntax to resolve the internal
// datastream location for Managed and XML datastreams.
replaceString =
resolveInternalDSLocation(context, dissBindInfo.dsLocation, PID, reposBaseURL)
+ "+(" + dissBindInfo.DSBindKey + ")";;
} else {
replaceString =
dissBindInfo.dsLocation + "+(" + dissBindInfo.DSBindKey + ")";
}
if (dissBindInfo.dsControlGroupType.equalsIgnoreCase("R") &&
dissBindInfo.AddressLocation.equals(LOCAL_ADDRESS_LOCATION))
isRedirect = true;
}
} else
{
// Case where there are one or more binding keys.
if (doDatastreamMediation &&
!dissBindInfo.dsControlGroupType.equalsIgnoreCase("R"))
{
// Use Datastream Mediation (except for Redirected datastreams)
replaceString = datastreamResolverServletURL
+ registerDatastreamLocation(dissBindInfo.dsLocation,
dissBindInfo.dsControlGroupType);
} else
{
// Bypass Datastream Mediation.
if ( dissBindInfo.dsControlGroupType.equalsIgnoreCase("M") ||
dissBindInfo.dsControlGroupType.equalsIgnoreCase("X"))
{
// Use the Default Disseminator syntax to resolve the internal
// datastream location for Managed and XML datastreams.
replaceString =
resolveInternalDSLocation(context, dissBindInfo.dsLocation, PID, reposBaseURL);
} else
{
replaceString = dissBindInfo.dsLocation;
}
if (dissBindInfo.dsControlGroupType.equalsIgnoreCase("R") &&
dissBindInfo.AddressLocation.equals(LOCAL_ADDRESS_LOCATION))
isRedirect = true;
}
}
try
{
// If the operationLocation contains datastreamInputParms
// URLEncode each parameter before substitution. Otherwise, the
// operationLocation has no parameters (i.e., it is a simple URL )
// so bypass URLencoding.
if (dissURL.indexOf("=(") != -1 )
{
dissURL = substituteString(dissURL, bindingKeyPattern, URLEncoder.encode(replaceString, "UTF-8"));
} else
{
dissURL = substituteString(dissURL, bindingKeyPattern, replaceString);
}
} catch (UnsupportedEncodingException uee)
{
String message = "[DisseminationService] An error occured. The error "
+ "was \"" + uee.getClass().getName() + "\" . The Reason was \""
+ uee.getMessage() + "\" . String value: " + replaceString + " . ";
s_server.logFinest(message);
throw new GeneralException(message);
}
s_server.logFinest("[DisseminationService] replaced dissURL: "
+ dissURL.toString()
+ " DissBindingInfo index: " + i);
}
// Substitute method parameter values in dissemination URL
Enumeration e = h_userParms.keys();
while (e.hasMoreElements())
{
String name = null;
String value = null;
try
{
name = URLEncoder.encode((String)e.nextElement(), "UTF-8");
value = URLEncoder.encode((String)h_userParms.get(name), "UTF-8");
} catch (UnsupportedEncodingException uee)
{
String message = "[DisseminationService] An error occured. The error "
+ "was \"" + uee.getClass().getName() + "\" . The Reason was \""
+ uee.getMessage() + "\" . Parameter name: " + name + " . "
+ "Parameter value: " + value + " .";
s_server.logFinest(message);
throw new GeneralException(message);
}
String pattern = "\\(" + name + "\\)";
dissURL = substituteString(dissURL, pattern, value);
s_server.logFinest("[DisseminationService] User parm substituted in "
+ "URL: " + dissURL);
}
// FIXME Need a more elegant means of handling optional userInputParm
// method parameters that are not supplied by the invoking client;
// for now, any optional parms that were not supplied are removed from
// the outgoing URL. This works because parms are validated in
// DefaultAccess to insure all required parms are present and all parm
// names match parm names defined for the specific method. The only
// unsubstituted parms left in the operationLocation string at this point
// are those for optional parameters that the client omitted in the
// initial request so they can safely be removed from the outgoing
// dissemination URL. This step is only needed when optional parameters
// are not supplied by the client.
if (dissURL.indexOf("(") != -1)
{
dissURL = stripParms(dissURL);
s_server.logFinest("[DisseminationService] Non-supplied optional "
+ "userInputParm values removed from URL: " + dissURL);
}
// Resolve content referenced by dissemination result.
s_server.logFinest("[DisseminationService] ProtocolType: "+protocolType);
if (protocolType.equalsIgnoreCase("http"))
{
if (isRedirect)
{
// The dsControlGroupType of Redirect("R") is a special control type
// used primarily for streaming media. Datastreams of this type are
// not mediated (proxied by Fedora) and their physical dsLocation is
// simply redirected back to the client. Therefore, the contents
// of the MIMETypedStream returned for dissemination requests will
// contain the raw URL of the dsLocation and will be assigned a
// special fedora-specific MIME type to identify the stream as
// a MIMETypedStream whose contents contain a URL to which the client
// should be redirected.
InputStream is = null;
try
{
is = new ByteArrayInputStream(dissURL.getBytes("UTF-8"));
} catch (UnsupportedEncodingException uee)
{
String message = "[DisseminationService] An error has occurred. "
+ "The error was a \"" + uee.getClass().getName() + "\" . The "
+ "Reason was \"" + uee.getMessage() + "\" . String value: "
+ dissURL + " . ";
s_server.logFinest(message);
throw new GeneralException(message);
}
long stopTime = new Date().getTime();
long interval = stopTime - startTime;
s_server.logFiner("[DisseminationService] Roundtrip assembleDissemination: "
+ interval + " milliseconds.");
dissemination = new MIMETypedStream("application/fedora-redirect",is, null);
} else
{
// For all non-redirected disseminations, Fedora captures and returns
// the MIMETypedStream resulting from the dissemination request.
ExternalContentManager externalContentManager = (ExternalContentManager)
s_server.getModule("fedora.server.storage.ExternalContentManager");
long stopTime = new Date().getTime();
long interval = stopTime - startTime;
s_server.logFiner("[DisseminationService] Roundtrip assembleDissemination: "
+ interval + " milliseconds.");
if (fedora.server.Debug.DEBUG) System.out.println("URL: "+dissURL);
dissemination = externalContentManager.getExternalContent(dissURL, context);
}
} else if (protocolType.equalsIgnoreCase("soap"))
{
// FIXME!! future handling of soap bindings.
String message = "[DisseminationService] Protocol type: "
+ protocolType + "NOT yet implemented";
s_server.logWarning(message);
throw new DisseminationException(message);
} else
{
String message = "[DisseminationService] Protocol type: "
+ protocolType + "NOT supported.";
s_server.logWarning(message);
throw new DisseminationException(message);
}
} else
{
// DisseminationBindingInfo was empty so there was no information
// provided to construct a dissemination.
String message = "[DisseminationService] Dissemination Binding "+
"Info contained no data";
s_server.logWarning(message);
throw new DisseminationBindingInfoNotFoundException(message);
}
return dissemination;
}
/**
* <p>Datastream locations are considered privileged information by the
* Fedora repository. To prevent disclosing physical datastream locations
* to external mechanism services, a proxy is used to disguise the datastream
* locations. This method generates a temporary ID that maps to the
* physical datastream location and registers this information in a
* memory resident hashtable for subsequent resolution of the physical
* datastream location. The servlet <code>DatastreamResolverServlet</code>
* provides the proxy resolution service for datastreams.</p>
* <p></p>
* <p>The format of the tempID is derived from <code>java.sql.Timestamp</code>
* with an arbitrary counter appended to the end to insure uniqueness. The
* syntax is of the form:
* <ul>
* <p>YYYY-MM-DD HH:mm:ss.mmm:dddddd where</p>
* <ul>
* <li>YYYY - year (1900-8099)</li>
* <li>MM - month (01-12)</li>
* <li>DD - day (01-31)</li>
* <li>hh - hours (0-23)</li>
* <li>mm - minutes (0-59)</li>
* <li>ss - seconds (0-59)</li>
* <li>mmm - milliseconds (0-999)</li>
* <li>dddddd - incremental counter (0-999999)</li>
* </ul>
* </ul>
*
* @param dsLocation The physical location of the datastream.
* @param dsControlGroupType The type of the datastream.
* @return A temporary ID used to reference the physical location of the
* specified datastream
* @throws ServerException If an error occurs in registering a datastream
* location.
*/
public String registerDatastreamLocation(String dsLocation,
String dsControlGroupType) throws ServerException
{
String tempID = null;
Timestamp timeStamp = null;
if (counter > 999999) counter = 0;
long currentTime = new Timestamp(new Date().getTime()).getTime();
long expireLimit = currentTime -
(long)datastreamExpirationLimit*1000;
try
{
// Remove any datastream registrations that have expired.
// The expiration limit can be adjusted using the Fedora config parameter
// named "datastreamExpirationLimit" which is in seconds.
for ( Enumeration e = dsRegistry.keys(); e.hasMoreElements(); )
{
String key = (String)e.nextElement();
timeStamp = Timestamp.valueOf(extractTimestamp(key));
if (expireLimit > timeStamp.getTime())
{
dsRegistry.remove(key);
s_server.logFinest("[DisseminationService] DatastreamMediationKey "
+ "removed from Hash: " + key);
}
}
// Register datastream.
if (tempID == null)
{
timeStamp = new Timestamp(new Date().getTime());
tempID = timeStamp.toString()+":"+counter++;
DatastreamMediation dm = new DatastreamMediation();
dm.mediatedDatastreamID = tempID;
dm.dsLocation = dsLocation;
dm.dsControlGroupType = dsControlGroupType;
dsRegistry.put(tempID, dm);
s_server.logFinest("[DisseminationService] DatastreammediationKey "
+ "added to Hash: " + tempID);
}
} catch(Throwable th)
{
throw new DisseminationException("[DisseminationService] register"
+ "DatastreamLocation: "
+ "returned an error. The underlying error was a "
+ th.getClass().getName() + " The message "
+ "was \"" + th.getMessage() + "\" .");
}
// Replace the blank between date and time with the character "T".
return tempID.replaceAll(" ","T");
}
/**
* <p>The tempID that is used for datastream mediation consists of a <code>
* Timestamp</code> plus a counter appended to the end to insure uniqueness.
* This method is a utility method used to extract the Timestamp portion
* from the tempID by stripping off the arbitrary counter at the end of
* the string.</p>
*
* @param tempID The tempID to be extracted.
* @return The extracted Timestamp value as a string.
*/
public String extractTimestamp(String tempID)
{
StringBuffer sb = new StringBuffer();
sb.append(tempID);
sb.replace(tempID.lastIndexOf(":"),tempID.length(),"");
return sb.toString();
}
/**
* <p>Performs simple string replacement using regular expressions.
* All matching occurrences of the pattern string will be replaced in the
* input string by the replacement string.
*
* @param inputString The source string.
* @param patternString The regular expression pattern.
* @param replaceString The replacement string.
* @return The source string with substitutions.
*/
private String substituteString(String inputString, String patternString,
String replaceString)
{
Pattern pattern = Pattern.compile(patternString);
Matcher m = pattern.matcher(inputString);
return m.replaceAll(replaceString);
}
/**
* <p> Removes any optional userInputParms which remain in the dissemination
* URL. This occurs when a method has optional parameters and the user does
* not supply a value for one or more of the optional parameters. The result
* is a syntax similar to "parm=(PARM_BIND_KEY)". This method removes these
* non-supplied optional parameters from the string.</p>
*
* @param dissURL String to be processed.
* @return An edited string with parameters removed where no value was
* specified for any optional parameters.
*/
private String stripParms(String dissURL)
{
String requestURI = dissURL.substring(0,dissURL.indexOf("?")+1);
String parmString = dissURL.substring(dissURL.indexOf("?")+1,dissURL.length());
String[] parms = parmString.split("&");
StringBuffer sb = new StringBuffer();
for (int i=0; i<parms.length; i++)
{
int len = parms[i].length() - 1;
if (parms[i].lastIndexOf(")") != len)
{
sb.append(parms[i]+"&");
}
}
int index = sb.lastIndexOf("&");
if ( index != -1 && index+1 == sb.length())
sb.replace(index,sb.length(),"");
return requestURI+sb.toString();
}
/**
* <p>Converts the internal dsLocation used by managed and XML type datastreams
* to the corresponding Default Dissemination request that will return the
* datastream contents.</p>
*
* @param internalDSLocation - dsLocation of the Managed or XML type datastream.
* @param PID - the persistent identifier of the digital object.
* @return - A URL corresponding to the Default Dissemination request for the
* specified datastream.
* @throws ServerException - If anything goes wrong during the conversion attempt.
*/
private String resolveInternalDSLocation(Context context, String internalDSLocation,
String PID, String reposBaseURL) throws ServerException
{
if (reposBaseURL == null || reposBaseURL.equals(""))
{
throw new DisseminationException("[DisseminationService] was unable to "
+ "resolve the base URL of the Fedora Server. The URL specified was: \""
+ reposBaseURL + "\". This information is required by the Dissemination Service.");
}
String[] s = internalDSLocation.split("\\+");
String dsLocation = null;
if (s.length == 3)
{
DOReader doReader = m_manager.getReader(Server.GLOBAL_CHOICE, context, PID);
Datastream d = (Datastream) doReader.getDatastream(s[1], s[2]);
if (fedora.server.Debug.DEBUG) System.out.println("DSDate: "+DateUtility.convertDateToString(d.DSCreateDT));
dsLocation = reposBaseURL
+"/fedora/get/"+s[0]+"/"+s[1]+"/"
+DateUtility.convertDateToString(d.DSCreateDT);
} else
{
String message = "[DisseminationService] An error has occurred. "
+ "The internal dsLocation: \"" + internalDSLocation + "\" is "
+ "not in the required format of: "
+ "\"doPID+DSID+DSVERSIONID\" .";
s_server.logFinest(message);
throw new GeneralException(message);
}
return dsLocation;
}
public static void printBindingInfo(DisseminationBindingInfo[] info) {
for (int i = 0; i < info.length; i++) {
System.out.println("DisseminationBindingInfo[" + i + "]:");
System.out.println(" DSBindKey : " + info[i].DSBindKey);
System.out.println(" dsLocation : " + info[i].dsLocation);
System.out.println(" dsControlGroupType : " + info[i].dsControlGroupType);
System.out.println(" dsID : " + info[i].dsID);
System.out.println(" dsVersionID : " + info[i].dsVersionID);
System.out.println(" AddressLocation : " + info[i].AddressLocation);
System.out.println(" OperationLocation : " + info[i].OperationLocation);
System.out.println(" ProtocolType : " + info[i].ProtocolType);
System.out.println(" dsState : " + info[i].dsState);
for (int j = 0; j < info[i].methodParms.length; j++) {
MethodParmDef def = info[i].methodParms[j];
System.out.println(" MethodParamDef[" + j + "]:");
System.out.println(" parmName : " + def.parmName);
System.out.println(" parmDefaultValue : " + def.parmDefaultValue);
System.out.println(" parmRequired : " + def.parmRequired);
System.out.println(" parmLabel : " + def.parmLabel);
System.out.println(" parmPassBy : " + def.parmPassBy);
for (int k = 0; k < def.parmDomainValues.length; k++) {
System.out.println(" parmDomainValue : " + def.parmDomainValues[k]);
}
}
}
}
}
| true | true | public MIMETypedStream assembleDissemination(Context context, String PID,
Hashtable h_userParms, DisseminationBindingInfo[] dissBindInfoArray, String reposBaseURL)
throws ServerException
{
if (reposBaseURL == null || reposBaseURL.equals(""))
{
throw new DisseminationException("[DisseminationService] was unable to "
+ "resolve the base URL of the Fedora Server. The URL specified was: \""
+ reposBaseURL + "\". This information is required by the Dissemination Service.");
}
String datastreamResolverServletURL = reposBaseURL + "/fedora/getDS?id=";
if (fedora.server.Debug.DEBUG) {
printBindingInfo(dissBindInfoArray);
}
long initStartTime = new Date().getTime();
long startTime = new Date().getTime();
String protocolType = null;
DisseminationBindingInfo dissBindInfo = null;
String dissURL = null;
MIMETypedStream dissemination = null;
boolean isRedirect = false;
if (dissBindInfoArray != null && dissBindInfoArray.length > 0)
{
String replaceString = null;
int numElements = dissBindInfoArray.length;
// Get row(s) of binding info and perform string substitution
// on DSBindingKey and method parameter values in WSDL
// Note: In case where more than one datastream matches the
// DSBindingKey or there are multiple DSBindingKeys for the
// method, multiple rows will be present; otherwise there is only
// a single row.
for (int i=0; i<dissBindInfoArray.length; i++)
{
((Authorization)s_server.getModule("Authorization")).enforce_Internal_DSState(
context, dissBindInfoArray[i].dsID, dissBindInfoArray[i].dsState);
dissBindInfo = dissBindInfoArray[i];
// Before doing anything, check whether we can replace any
// placeholders in the datastream url with parameter values from
// the request. This supports the special case where a
// datastream's URL is dependent on user parameters, such
// as when the datastream is actually a dissemination that
// takes parameters.
if (dissBindInfo.dsLocation!=null &&
( dissBindInfo.dsLocation.startsWith("http://")
|| dissBindInfo.dsLocation.startsWith("https://") ) ) {
String[] parts=dissBindInfo.dsLocation.split("=\\("); // regex for =(
if (parts.length>1) {
StringBuffer replaced=new StringBuffer();
replaced.append(parts[0]);
for (int x=1; x<parts.length; x++) {
replaced.append('=');
int rightParenPos=parts[x].indexOf(")");
if (rightParenPos!=-1 && rightParenPos>0) {
String key=parts[x].substring(0, rightParenPos);
String val=(String) h_userParms.get(key);
if (val!=null) {
// We have a match... so insert the urlencoded value.
try {
replaced.append(URLEncoder.encode(val, "UTF-8"));
} catch (UnsupportedEncodingException uee) {
// won't happen: java always supports UTF-8
}
if (rightParenPos<parts[x].length()) {
replaced.append(parts[x].substring(rightParenPos+1));
}
} else {
replaced.append('(');
replaced.append(parts[x]);
}
} else {
replaced.append('(');
replaced.append(parts[x]);
}
}
dissBindInfo.dsLocation=replaced.toString();
}
}
// Match DSBindingKey pattern in WSDL which is a string of the form:
// (DSBindingKey). Rows in DisseminationBindingInfo are sorted
// alphabetically on binding key.
String bindingKeyPattern = "\\(" + dissBindInfo.DSBindKey + "\\)";
if (i == 0)
{
// If addressLocation has a value of "LOCAL", this indicates
// the associated operationLocation requires no addressLocation.
// i.e., the operationLocation contains all information necessary
// to perform the dissemination request. This is a special case
// used when the web services are generally mechanisms like cgi-scripts,
// java servlets, and simple HTTP GETs. Using the value of LOCAL
// in the address location also enables one to have different methods
// serviced by different hosts. In true web services like SOAP, the
// addressLocation specifies the host name of the service and all
// methods are served from that single host location.
if (dissBindInfo.AddressLocation.equalsIgnoreCase(LOCAL_ADDRESS_LOCATION))
{
dissURL = dissBindInfo.OperationLocation;
} else
{
dissURL = dissBindInfo.AddressLocation+dissBindInfo.OperationLocation;
}
protocolType = dissBindInfo.ProtocolType;
}
String currentKey = dissBindInfo.DSBindKey;
String nextKey = "";
if (i != numElements-1)
{
// Except for last row, get the value of the next binding key
// to compare with the value of the current binding key.
nextKey = dissBindInfoArray[i+1].DSBindKey;
}
s_server.logFinest("[DisseminationService] currentKey: '"
+ currentKey + "'");
s_server.logFinest("[DisseminationService] nextKey: '"
+ nextKey + "'");
// In most cases, there is only a single datastream that matches a
// given DSBindingKey so the substitution process is to just replace
// the occurence of (BINDING_KEY) with the value of the datastream
// location. However, when multiple datastreams match the same
// DSBindingKey, the occurrence of (BINDING_KEY) is replaced with the
// value of the datastream location and the value +(BINDING_KEY) is
// appended so that subsequent datastreams matching the binding key
// will be substituted. The end result is that the binding key will
// be replaced by a series of datastream locations separated by a
// plus(+) sign. For example, in the case where 3 datastreams match
// the binding key for PHOTO:
//
// file=(PHOTO) becomes
// file=dslocation1+dslocation2+dslocation3
//
// It is the responsibility of the Behavior Mechanism to know how to
// handle an input parameter with multiple datastream locations.
//
// In the case of a method containing multiple binding keys,
// substitutions are performed on each binding key. For example, in
// the case where there are 2 binding keys named PHOTO and WATERMARK
// where each matches a single datastream:
//
// image=(PHOTO)&watermark=(WATERMARK) becomes
// image=dslocation1&watermark=dslocation2
//
// In the case with mutliple binding keys and multiple datastreams,
// the substitution might appear like the following:
//
// image=(PHOTO)&watermark=(WATERMARK) becomes
// image=dslocation1+dslocation2&watermark=dslocation3
if (nextKey.equalsIgnoreCase(currentKey) & i != numElements)
{
// Case where binding keys are equal which means that multiple
// datastreams matched the same binding key.
if (doDatastreamMediation &&
!dissBindInfo.dsControlGroupType.equalsIgnoreCase("R"))
{
// Use Datastream Mediation (except for redirected datastreams).
replaceString = datastreamResolverServletURL
+ registerDatastreamLocation(dissBindInfo.dsLocation,
dissBindInfo.dsControlGroupType)
+ "+(" + dissBindInfo.DSBindKey + ")";
} else
{
// Bypass Datastream Mediation.
if ( dissBindInfo.dsControlGroupType.equalsIgnoreCase("M") ||
dissBindInfo.dsControlGroupType.equalsIgnoreCase("X"))
{
// Use the Default Disseminator syntax to resolve the internal
// datastream location for Managed and XML datastreams.
replaceString =
resolveInternalDSLocation(context, dissBindInfo.dsLocation, PID, reposBaseURL)
+ "+(" + dissBindInfo.DSBindKey + ")";;
} else {
replaceString =
dissBindInfo.dsLocation + "+(" + dissBindInfo.DSBindKey + ")";
}
if (dissBindInfo.dsControlGroupType.equalsIgnoreCase("R") &&
dissBindInfo.AddressLocation.equals(LOCAL_ADDRESS_LOCATION))
isRedirect = true;
}
} else
{
// Case where there are one or more binding keys.
if (doDatastreamMediation &&
!dissBindInfo.dsControlGroupType.equalsIgnoreCase("R"))
{
// Use Datastream Mediation (except for Redirected datastreams)
replaceString = datastreamResolverServletURL
+ registerDatastreamLocation(dissBindInfo.dsLocation,
dissBindInfo.dsControlGroupType);
} else
{
// Bypass Datastream Mediation.
if ( dissBindInfo.dsControlGroupType.equalsIgnoreCase("M") ||
dissBindInfo.dsControlGroupType.equalsIgnoreCase("X"))
{
// Use the Default Disseminator syntax to resolve the internal
// datastream location for Managed and XML datastreams.
replaceString =
resolveInternalDSLocation(context, dissBindInfo.dsLocation, PID, reposBaseURL);
} else
{
replaceString = dissBindInfo.dsLocation;
}
if (dissBindInfo.dsControlGroupType.equalsIgnoreCase("R") &&
dissBindInfo.AddressLocation.equals(LOCAL_ADDRESS_LOCATION))
isRedirect = true;
}
}
try
{
// If the operationLocation contains datastreamInputParms
// URLEncode each parameter before substitution. Otherwise, the
// operationLocation has no parameters (i.e., it is a simple URL )
// so bypass URLencoding.
if (dissURL.indexOf("=(") != -1 )
{
dissURL = substituteString(dissURL, bindingKeyPattern, URLEncoder.encode(replaceString, "UTF-8"));
} else
{
dissURL = substituteString(dissURL, bindingKeyPattern, replaceString);
}
} catch (UnsupportedEncodingException uee)
{
String message = "[DisseminationService] An error occured. The error "
+ "was \"" + uee.getClass().getName() + "\" . The Reason was \""
+ uee.getMessage() + "\" . String value: " + replaceString + " . ";
s_server.logFinest(message);
throw new GeneralException(message);
}
s_server.logFinest("[DisseminationService] replaced dissURL: "
+ dissURL.toString()
+ " DissBindingInfo index: " + i);
}
// Substitute method parameter values in dissemination URL
Enumeration e = h_userParms.keys();
while (e.hasMoreElements())
{
String name = null;
String value = null;
try
{
name = URLEncoder.encode((String)e.nextElement(), "UTF-8");
value = URLEncoder.encode((String)h_userParms.get(name), "UTF-8");
} catch (UnsupportedEncodingException uee)
{
String message = "[DisseminationService] An error occured. The error "
+ "was \"" + uee.getClass().getName() + "\" . The Reason was \""
+ uee.getMessage() + "\" . Parameter name: " + name + " . "
+ "Parameter value: " + value + " .";
s_server.logFinest(message);
throw new GeneralException(message);
}
String pattern = "\\(" + name + "\\)";
dissURL = substituteString(dissURL, pattern, value);
s_server.logFinest("[DisseminationService] User parm substituted in "
+ "URL: " + dissURL);
}
// FIXME Need a more elegant means of handling optional userInputParm
// method parameters that are not supplied by the invoking client;
// for now, any optional parms that were not supplied are removed from
// the outgoing URL. This works because parms are validated in
// DefaultAccess to insure all required parms are present and all parm
// names match parm names defined for the specific method. The only
// unsubstituted parms left in the operationLocation string at this point
// are those for optional parameters that the client omitted in the
// initial request so they can safely be removed from the outgoing
// dissemination URL. This step is only needed when optional parameters
// are not supplied by the client.
if (dissURL.indexOf("(") != -1)
{
dissURL = stripParms(dissURL);
s_server.logFinest("[DisseminationService] Non-supplied optional "
+ "userInputParm values removed from URL: " + dissURL);
}
// Resolve content referenced by dissemination result.
s_server.logFinest("[DisseminationService] ProtocolType: "+protocolType);
if (protocolType.equalsIgnoreCase("http"))
{
if (isRedirect)
{
// The dsControlGroupType of Redirect("R") is a special control type
// used primarily for streaming media. Datastreams of this type are
// not mediated (proxied by Fedora) and their physical dsLocation is
// simply redirected back to the client. Therefore, the contents
// of the MIMETypedStream returned for dissemination requests will
// contain the raw URL of the dsLocation and will be assigned a
// special fedora-specific MIME type to identify the stream as
// a MIMETypedStream whose contents contain a URL to which the client
// should be redirected.
InputStream is = null;
try
{
is = new ByteArrayInputStream(dissURL.getBytes("UTF-8"));
} catch (UnsupportedEncodingException uee)
{
String message = "[DisseminationService] An error has occurred. "
+ "The error was a \"" + uee.getClass().getName() + "\" . The "
+ "Reason was \"" + uee.getMessage() + "\" . String value: "
+ dissURL + " . ";
s_server.logFinest(message);
throw new GeneralException(message);
}
long stopTime = new Date().getTime();
long interval = stopTime - startTime;
s_server.logFiner("[DisseminationService] Roundtrip assembleDissemination: "
+ interval + " milliseconds.");
dissemination = new MIMETypedStream("application/fedora-redirect",is, null);
} else
{
// For all non-redirected disseminations, Fedora captures and returns
// the MIMETypedStream resulting from the dissemination request.
ExternalContentManager externalContentManager = (ExternalContentManager)
s_server.getModule("fedora.server.storage.ExternalContentManager");
long stopTime = new Date().getTime();
long interval = stopTime - startTime;
s_server.logFiner("[DisseminationService] Roundtrip assembleDissemination: "
+ interval + " milliseconds.");
if (fedora.server.Debug.DEBUG) System.out.println("URL: "+dissURL);
dissemination = externalContentManager.getExternalContent(dissURL, context);
}
} else if (protocolType.equalsIgnoreCase("soap"))
{
// FIXME!! future handling of soap bindings.
String message = "[DisseminationService] Protocol type: "
+ protocolType + "NOT yet implemented";
s_server.logWarning(message);
throw new DisseminationException(message);
} else
{
String message = "[DisseminationService] Protocol type: "
+ protocolType + "NOT supported.";
s_server.logWarning(message);
throw new DisseminationException(message);
}
} else
{
// DisseminationBindingInfo was empty so there was no information
// provided to construct a dissemination.
String message = "[DisseminationService] Dissemination Binding "+
"Info contained no data";
s_server.logWarning(message);
throw new DisseminationBindingInfoNotFoundException(message);
}
return dissemination;
}
| public MIMETypedStream assembleDissemination(Context context, String PID,
Hashtable h_userParms, DisseminationBindingInfo[] dissBindInfoArray, String reposBaseURL)
throws ServerException
{
if (reposBaseURL == null || reposBaseURL.equals(""))
{
throw new DisseminationException("[DisseminationService] was unable to "
+ "resolve the base URL of the Fedora Server. The URL specified was: \""
+ reposBaseURL + "\". This information is required by the Dissemination Service.");
}
String datastreamResolverServletURL = reposBaseURL + "/fedora/getDS?id=";
if (fedora.server.Debug.DEBUG) {
printBindingInfo(dissBindInfoArray);
}
long initStartTime = new Date().getTime();
long startTime = new Date().getTime();
String protocolType = null;
DisseminationBindingInfo dissBindInfo = null;
String dissURL = null;
MIMETypedStream dissemination = null;
boolean isRedirect = false;
if (dissBindInfoArray != null && dissBindInfoArray.length > 0)
{
String replaceString = null;
int numElements = dissBindInfoArray.length;
// Get row(s) of binding info and perform string substitution
// on DSBindingKey and method parameter values in WSDL
// Note: In case where more than one datastream matches the
// DSBindingKey or there are multiple DSBindingKeys for the
// method, multiple rows will be present; otherwise there is only
// a single row.
for (int i=0; i<dissBindInfoArray.length; i++)
{
((Authorization)s_server.getModule("fedora.server.security.Authorization")).enforce_Internal_DSState(
context, dissBindInfoArray[i].dsID, dissBindInfoArray[i].dsState);
dissBindInfo = dissBindInfoArray[i];
// Before doing anything, check whether we can replace any
// placeholders in the datastream url with parameter values from
// the request. This supports the special case where a
// datastream's URL is dependent on user parameters, such
// as when the datastream is actually a dissemination that
// takes parameters.
if (dissBindInfo.dsLocation!=null &&
( dissBindInfo.dsLocation.startsWith("http://")
|| dissBindInfo.dsLocation.startsWith("https://") ) ) {
String[] parts=dissBindInfo.dsLocation.split("=\\("); // regex for =(
if (parts.length>1) {
StringBuffer replaced=new StringBuffer();
replaced.append(parts[0]);
for (int x=1; x<parts.length; x++) {
replaced.append('=');
int rightParenPos=parts[x].indexOf(")");
if (rightParenPos!=-1 && rightParenPos>0) {
String key=parts[x].substring(0, rightParenPos);
String val=(String) h_userParms.get(key);
if (val!=null) {
// We have a match... so insert the urlencoded value.
try {
replaced.append(URLEncoder.encode(val, "UTF-8"));
} catch (UnsupportedEncodingException uee) {
// won't happen: java always supports UTF-8
}
if (rightParenPos<parts[x].length()) {
replaced.append(parts[x].substring(rightParenPos+1));
}
} else {
replaced.append('(');
replaced.append(parts[x]);
}
} else {
replaced.append('(');
replaced.append(parts[x]);
}
}
dissBindInfo.dsLocation=replaced.toString();
}
}
// Match DSBindingKey pattern in WSDL which is a string of the form:
// (DSBindingKey). Rows in DisseminationBindingInfo are sorted
// alphabetically on binding key.
String bindingKeyPattern = "\\(" + dissBindInfo.DSBindKey + "\\)";
if (i == 0)
{
// If addressLocation has a value of "LOCAL", this indicates
// the associated operationLocation requires no addressLocation.
// i.e., the operationLocation contains all information necessary
// to perform the dissemination request. This is a special case
// used when the web services are generally mechanisms like cgi-scripts,
// java servlets, and simple HTTP GETs. Using the value of LOCAL
// in the address location also enables one to have different methods
// serviced by different hosts. In true web services like SOAP, the
// addressLocation specifies the host name of the service and all
// methods are served from that single host location.
if (dissBindInfo.AddressLocation.equalsIgnoreCase(LOCAL_ADDRESS_LOCATION))
{
dissURL = dissBindInfo.OperationLocation;
} else
{
dissURL = dissBindInfo.AddressLocation+dissBindInfo.OperationLocation;
}
protocolType = dissBindInfo.ProtocolType;
}
String currentKey = dissBindInfo.DSBindKey;
String nextKey = "";
if (i != numElements-1)
{
// Except for last row, get the value of the next binding key
// to compare with the value of the current binding key.
nextKey = dissBindInfoArray[i+1].DSBindKey;
}
s_server.logFinest("[DisseminationService] currentKey: '"
+ currentKey + "'");
s_server.logFinest("[DisseminationService] nextKey: '"
+ nextKey + "'");
// In most cases, there is only a single datastream that matches a
// given DSBindingKey so the substitution process is to just replace
// the occurence of (BINDING_KEY) with the value of the datastream
// location. However, when multiple datastreams match the same
// DSBindingKey, the occurrence of (BINDING_KEY) is replaced with the
// value of the datastream location and the value +(BINDING_KEY) is
// appended so that subsequent datastreams matching the binding key
// will be substituted. The end result is that the binding key will
// be replaced by a series of datastream locations separated by a
// plus(+) sign. For example, in the case where 3 datastreams match
// the binding key for PHOTO:
//
// file=(PHOTO) becomes
// file=dslocation1+dslocation2+dslocation3
//
// It is the responsibility of the Behavior Mechanism to know how to
// handle an input parameter with multiple datastream locations.
//
// In the case of a method containing multiple binding keys,
// substitutions are performed on each binding key. For example, in
// the case where there are 2 binding keys named PHOTO and WATERMARK
// where each matches a single datastream:
//
// image=(PHOTO)&watermark=(WATERMARK) becomes
// image=dslocation1&watermark=dslocation2
//
// In the case with mutliple binding keys and multiple datastreams,
// the substitution might appear like the following:
//
// image=(PHOTO)&watermark=(WATERMARK) becomes
// image=dslocation1+dslocation2&watermark=dslocation3
if (nextKey.equalsIgnoreCase(currentKey) & i != numElements)
{
// Case where binding keys are equal which means that multiple
// datastreams matched the same binding key.
if (doDatastreamMediation &&
!dissBindInfo.dsControlGroupType.equalsIgnoreCase("R"))
{
// Use Datastream Mediation (except for redirected datastreams).
replaceString = datastreamResolverServletURL
+ registerDatastreamLocation(dissBindInfo.dsLocation,
dissBindInfo.dsControlGroupType)
+ "+(" + dissBindInfo.DSBindKey + ")";
} else
{
// Bypass Datastream Mediation.
if ( dissBindInfo.dsControlGroupType.equalsIgnoreCase("M") ||
dissBindInfo.dsControlGroupType.equalsIgnoreCase("X"))
{
// Use the Default Disseminator syntax to resolve the internal
// datastream location for Managed and XML datastreams.
replaceString =
resolveInternalDSLocation(context, dissBindInfo.dsLocation, PID, reposBaseURL)
+ "+(" + dissBindInfo.DSBindKey + ")";;
} else {
replaceString =
dissBindInfo.dsLocation + "+(" + dissBindInfo.DSBindKey + ")";
}
if (dissBindInfo.dsControlGroupType.equalsIgnoreCase("R") &&
dissBindInfo.AddressLocation.equals(LOCAL_ADDRESS_LOCATION))
isRedirect = true;
}
} else
{
// Case where there are one or more binding keys.
if (doDatastreamMediation &&
!dissBindInfo.dsControlGroupType.equalsIgnoreCase("R"))
{
// Use Datastream Mediation (except for Redirected datastreams)
replaceString = datastreamResolverServletURL
+ registerDatastreamLocation(dissBindInfo.dsLocation,
dissBindInfo.dsControlGroupType);
} else
{
// Bypass Datastream Mediation.
if ( dissBindInfo.dsControlGroupType.equalsIgnoreCase("M") ||
dissBindInfo.dsControlGroupType.equalsIgnoreCase("X"))
{
// Use the Default Disseminator syntax to resolve the internal
// datastream location for Managed and XML datastreams.
replaceString =
resolveInternalDSLocation(context, dissBindInfo.dsLocation, PID, reposBaseURL);
} else
{
replaceString = dissBindInfo.dsLocation;
}
if (dissBindInfo.dsControlGroupType.equalsIgnoreCase("R") &&
dissBindInfo.AddressLocation.equals(LOCAL_ADDRESS_LOCATION))
isRedirect = true;
}
}
try
{
// If the operationLocation contains datastreamInputParms
// URLEncode each parameter before substitution. Otherwise, the
// operationLocation has no parameters (i.e., it is a simple URL )
// so bypass URLencoding.
if (dissURL.indexOf("=(") != -1 )
{
dissURL = substituteString(dissURL, bindingKeyPattern, URLEncoder.encode(replaceString, "UTF-8"));
} else
{
dissURL = substituteString(dissURL, bindingKeyPattern, replaceString);
}
} catch (UnsupportedEncodingException uee)
{
String message = "[DisseminationService] An error occured. The error "
+ "was \"" + uee.getClass().getName() + "\" . The Reason was \""
+ uee.getMessage() + "\" . String value: " + replaceString + " . ";
s_server.logFinest(message);
throw new GeneralException(message);
}
s_server.logFinest("[DisseminationService] replaced dissURL: "
+ dissURL.toString()
+ " DissBindingInfo index: " + i);
}
// Substitute method parameter values in dissemination URL
Enumeration e = h_userParms.keys();
while (e.hasMoreElements())
{
String name = null;
String value = null;
try
{
name = URLEncoder.encode((String)e.nextElement(), "UTF-8");
value = URLEncoder.encode((String)h_userParms.get(name), "UTF-8");
} catch (UnsupportedEncodingException uee)
{
String message = "[DisseminationService] An error occured. The error "
+ "was \"" + uee.getClass().getName() + "\" . The Reason was \""
+ uee.getMessage() + "\" . Parameter name: " + name + " . "
+ "Parameter value: " + value + " .";
s_server.logFinest(message);
throw new GeneralException(message);
}
String pattern = "\\(" + name + "\\)";
dissURL = substituteString(dissURL, pattern, value);
s_server.logFinest("[DisseminationService] User parm substituted in "
+ "URL: " + dissURL);
}
// FIXME Need a more elegant means of handling optional userInputParm
// method parameters that are not supplied by the invoking client;
// for now, any optional parms that were not supplied are removed from
// the outgoing URL. This works because parms are validated in
// DefaultAccess to insure all required parms are present and all parm
// names match parm names defined for the specific method. The only
// unsubstituted parms left in the operationLocation string at this point
// are those for optional parameters that the client omitted in the
// initial request so they can safely be removed from the outgoing
// dissemination URL. This step is only needed when optional parameters
// are not supplied by the client.
if (dissURL.indexOf("(") != -1)
{
dissURL = stripParms(dissURL);
s_server.logFinest("[DisseminationService] Non-supplied optional "
+ "userInputParm values removed from URL: " + dissURL);
}
// Resolve content referenced by dissemination result.
s_server.logFinest("[DisseminationService] ProtocolType: "+protocolType);
if (protocolType.equalsIgnoreCase("http"))
{
if (isRedirect)
{
// The dsControlGroupType of Redirect("R") is a special control type
// used primarily for streaming media. Datastreams of this type are
// not mediated (proxied by Fedora) and their physical dsLocation is
// simply redirected back to the client. Therefore, the contents
// of the MIMETypedStream returned for dissemination requests will
// contain the raw URL of the dsLocation and will be assigned a
// special fedora-specific MIME type to identify the stream as
// a MIMETypedStream whose contents contain a URL to which the client
// should be redirected.
InputStream is = null;
try
{
is = new ByteArrayInputStream(dissURL.getBytes("UTF-8"));
} catch (UnsupportedEncodingException uee)
{
String message = "[DisseminationService] An error has occurred. "
+ "The error was a \"" + uee.getClass().getName() + "\" . The "
+ "Reason was \"" + uee.getMessage() + "\" . String value: "
+ dissURL + " . ";
s_server.logFinest(message);
throw new GeneralException(message);
}
long stopTime = new Date().getTime();
long interval = stopTime - startTime;
s_server.logFiner("[DisseminationService] Roundtrip assembleDissemination: "
+ interval + " milliseconds.");
dissemination = new MIMETypedStream("application/fedora-redirect",is, null);
} else
{
// For all non-redirected disseminations, Fedora captures and returns
// the MIMETypedStream resulting from the dissemination request.
ExternalContentManager externalContentManager = (ExternalContentManager)
s_server.getModule("fedora.server.storage.ExternalContentManager");
long stopTime = new Date().getTime();
long interval = stopTime - startTime;
s_server.logFiner("[DisseminationService] Roundtrip assembleDissemination: "
+ interval + " milliseconds.");
if (fedora.server.Debug.DEBUG) System.out.println("URL: "+dissURL);
dissemination = externalContentManager.getExternalContent(dissURL, context);
}
} else if (protocolType.equalsIgnoreCase("soap"))
{
// FIXME!! future handling of soap bindings.
String message = "[DisseminationService] Protocol type: "
+ protocolType + "NOT yet implemented";
s_server.logWarning(message);
throw new DisseminationException(message);
} else
{
String message = "[DisseminationService] Protocol type: "
+ protocolType + "NOT supported.";
s_server.logWarning(message);
throw new DisseminationException(message);
}
} else
{
// DisseminationBindingInfo was empty so there was no information
// provided to construct a dissemination.
String message = "[DisseminationService] Dissemination Binding "+
"Info contained no data";
s_server.logWarning(message);
throw new DisseminationBindingInfoNotFoundException(message);
}
return dissemination;
}
|
diff --git a/src/webrender/java/nextapp/echo2/webrender/ClientAnalyzerProcessor.java b/src/webrender/java/nextapp/echo2/webrender/ClientAnalyzerProcessor.java
index 2f730c4a..a0bc7e5c 100644
--- a/src/webrender/java/nextapp/echo2/webrender/ClientAnalyzerProcessor.java
+++ b/src/webrender/java/nextapp/echo2/webrender/ClientAnalyzerProcessor.java
@@ -1,244 +1,248 @@
/*
* This file is part of the Echo Web Application Framework (hereinafter "Echo").
* Copyright (C) 2002-2005 NextApp, Inc.
*
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* 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.
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*/
package nextapp.echo2.webrender;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import nextapp.echo2.webrender.service.SynchronizeService;
import nextapp.echo2.webrender.util.DomUtil;
import org.w3c.dom.Element;
/**
* <code>SynchronizeService.ClientMessagePartProcessor</code> which creates
* a <code>ClientProperties</code> object based on the client script's
* analysis of its environment.
*/
public class ClientAnalyzerProcessor
implements SynchronizeService.ClientMessagePartProcessor {
/**
* <code>Set</code> containing valid properties which may be received from
* the client. Property settings received from the client that are not in
* this set are discarded.
*/
private static final Set VALID_PROPERTIES;
static {
Set set = new HashSet();
set.add(ClientProperties.NAVIGATOR_APP_CODE_NAME);
set.add(ClientProperties.NAVIGATOR_APP_NAME);
set.add(ClientProperties.NAVIGATOR_APP_VERSION);
set.add(ClientProperties.NAVIGATOR_COOKIE_ENABLED);
set.add(ClientProperties.NAVIGATOR_JAVA_ENABLED);
set.add(ClientProperties.NAVIGATOR_LANGUAGE);
set.add(ClientProperties.NAVIGATOR_PLATFORM);
set.add(ClientProperties.NAVIGATOR_USER_AGENT);
set.add(ClientProperties.SCREEN_WIDTH);
set.add(ClientProperties.SCREEN_HEIGHT);
set.add(ClientProperties.SCREEN_COLOR_DEPTH);
set.add(ClientProperties.UTC_OFFSET);
set.add(ClientProperties.UNESCAPED_XHR_TEST);
VALID_PROPERTIES = Collections.unmodifiableSet(set);
}
/**
* Analyzes the state of <code>ClientProperties</code> and adds additional
* inferred data, such as quirk attributes based on browser type.
*
* @param clientProperties the <code>ClientProperties</code> to analyze
* and update
*/
private void analyze(ClientProperties clientProperties) {
Connection conn = WebRenderServlet.getActiveConnection();
Enumeration localeEnum = conn.getRequest().getLocales();
List localeList = new ArrayList();
while (localeEnum.hasMoreElements()) {
localeList.add(localeEnum.nextElement());
}
clientProperties.setProperty(ClientProperties.LOCALES, localeList.toArray(new Locale[localeList.size()]));
clientProperties.setProperty(ClientProperties.REMOTE_HOST, conn.getRequest().getRemoteHost());
String userAgent = clientProperties.getString(ClientProperties.NAVIGATOR_USER_AGENT).toLowerCase();
boolean browserOpera = userAgent.indexOf("opera") != -1;
boolean browserSafari = userAgent.indexOf("safari") != -1;
boolean browserKonqueror = userAgent.indexOf("konqueror") != -1;
// Note deceptive user agent fields:
// - Konqueror and Safari UA fields contain "like Gecko"
// - Opera UA field typically contains "MSIE"
boolean deceptiveUserAgent = browserOpera || browserSafari || browserKonqueror;
boolean browserMozilla = !deceptiveUserAgent && userAgent.indexOf("gecko") != -1;
boolean browserFireFox = userAgent.indexOf("firefox") != -1;
boolean browserInternetExplorer = !deceptiveUserAgent && userAgent.indexOf("msie") != -1;
int majorVersion = -1, minorVersion = -1;
// Store browser information.
if (browserOpera) {
clientProperties.setProperty(ClientProperties.BROWSER_OPERA, Boolean.TRUE);
if (userAgent.indexOf("opera/9") != -1 || userAgent.indexOf("opera 9") != -1) {
majorVersion = 9;
} else if (userAgent.indexOf("opera/8") != -1 || userAgent.indexOf("opera 8") != -1) {
majorVersion = 8;
} else {
// Assume future version with Opera 9 compatibility.
// (Versions prior to 8 do not provide minimum requirements, i.e., XMLHTTPRequest.)
majorVersion = 9;
}
} else if (browserKonqueror) {
clientProperties.setProperty(ClientProperties.BROWSER_KONQUEROR, Boolean.TRUE);
} else if (browserSafari) {
clientProperties.setProperty(ClientProperties.BROWSER_SAFARI, Boolean.TRUE);
} else if (browserMozilla) {
clientProperties.setProperty(ClientProperties.BROWSER_MOZILLA, Boolean.TRUE);
if (browserFireFox) {
clientProperties.setProperty(ClientProperties.BROWSER_MOZILLA_FIREFOX, Boolean.TRUE);
+ if (userAgent.indexOf("firefox/3.0") != -1) {
+ majorVersion = 3;
+ minorVersion = 0;
+ }
}
} else if (browserInternetExplorer) {
clientProperties.setProperty(ClientProperties.BROWSER_INTERNET_EXPLORER, Boolean.TRUE);
if (userAgent.indexOf("msie 6.") != -1) {
majorVersion = 6;
} else if (userAgent.indexOf("msie 7.") != -1) {
majorVersion = 7;
}
}
if (majorVersion != -1) {
clientProperties.setProperty(ClientProperties.BROWSER_VERSION_MAJOR, Integer.toString(majorVersion));
}
if (minorVersion != -1) {
clientProperties.setProperty(ClientProperties.BROWSER_VERSION_MINOR, Integer.toString(minorVersion));
}
// Set quirk flags.
if (browserInternetExplorer) {
clientProperties.setProperty(ClientProperties.QUIRK_IE_REPAINT, Boolean.TRUE);
clientProperties.setProperty(ClientProperties.QUIRK_TEXTAREA_CONTENT, Boolean.TRUE);
clientProperties.setProperty(ClientProperties.QUIRK_IE_TEXTAREA_NEWLINE_OBLITERATION, Boolean.TRUE);
clientProperties.setProperty(ClientProperties.QUIRK_IE_SELECT_LIST_DOM_UPDATE, Boolean.TRUE);
clientProperties.setProperty(ClientProperties.QUIRK_CSS_BORDER_COLLAPSE_INSIDE, Boolean.TRUE);
clientProperties.setProperty(ClientProperties.QUIRK_CSS_BORDER_COLLAPSE_FOR_0_PADDING, Boolean.TRUE);
clientProperties.setProperty(ClientProperties.NOT_SUPPORTED_CSS_OPACITY, Boolean.TRUE);
clientProperties.setProperty(ClientProperties.QUIRK_DELAYED_FOCUS_REQUIRED, Boolean.TRUE);
clientProperties.setProperty(ClientProperties.PROPRIETARY_IE_CSS_EXPRESSIONS_SUPPORTED, Boolean.TRUE);
clientProperties.setProperty(ClientProperties.PROPRIETARY_EVENT_MOUSE_ENTER_LEAVE_SUPPORTED, Boolean.TRUE);
clientProperties.setProperty(ClientProperties.PROPRIETARY_IE_OPACITY_FILTER_REQUIRED, Boolean.TRUE);
// The following flaws are verified as present in IE7.0Beta2:
clientProperties.setProperty(ClientProperties.QUIRK_IE_TABLE_PERCENT_WIDTH_SCROLLBAR_ERROR, Boolean.TRUE);
clientProperties.setProperty(ClientProperties.QUIRK_IE_SELECT_PERCENT_WIDTH, Boolean.TRUE);
if (majorVersion < 7) {
// The following flaws are verified as fixed in IE7.0Beta2:
clientProperties.setProperty(ClientProperties.PROPRIETARY_IE_PNG_ALPHA_FILTER_REQUIRED, Boolean.TRUE);
clientProperties.setProperty(ClientProperties.QUIRK_CSS_POSITIONING_ONE_SIDE_ONLY, Boolean.TRUE);
clientProperties.setProperty(ClientProperties.QUIRK_CSS_BACKGROUND_ATTACHMENT_USE_FIXED, Boolean.TRUE);
clientProperties.setProperty(ClientProperties.QUIRK_IE_SELECT_Z_INDEX, Boolean.TRUE);
}
}
if (browserOpera) {
clientProperties.setProperty(ClientProperties.QUIRK_TEXTAREA_CONTENT, Boolean.TRUE);
clientProperties.setProperty(ClientProperties.QUIRK_OPERA_NO_CSS_TEXT, Boolean.TRUE);
clientProperties.setProperty(ClientProperties.QUIRK_SELECT_REQUIRES_NULL_OPTION, Boolean.TRUE);
clientProperties.setProperty(ClientProperties.QUIRK_IE_SELECT_PERCENT_WIDTH, Boolean.TRUE);
if (majorVersion < 9) {
clientProperties.setProperty(ClientProperties.NOT_SUPPORTED_CSS_OPACITY, Boolean.TRUE);
}
}
if (browserMozilla) {
clientProperties.setProperty(ClientProperties.QUIRK_SELECT_REQUIRES_NULL_OPTION, Boolean.TRUE);
clientProperties.setProperty(ClientProperties.QUIRK_MOZILLA_TEXT_INPUT_REPAINT, Boolean.TRUE);
clientProperties.setProperty(ClientProperties.QUIRK_MOZILLA_PERFORMANCE_LARGE_DOM_REMOVE, Boolean.TRUE);
}
if (browserKonqueror) {
clientProperties.setProperty(ClientProperties.QUIRK_SELECT_REQUIRES_NULL_OPTION, Boolean.TRUE);
clientProperties.setProperty(ClientProperties.QUIRK_IE_SELECT_PERCENT_WIDTH, Boolean.TRUE);
clientProperties.setProperty(ClientProperties.NOT_SUPPORTED_CSS_MANIPULATION, Boolean.TRUE);
}
if (browserSafari) {
clientProperties.setProperty(ClientProperties.QUIRK_SELECT_REQUIRES_NULL_OPTION, Boolean.TRUE);
clientProperties.setProperty(ClientProperties.NOT_SUPPORTED_CSS_MANIPULATION, Boolean.TRUE);
String unescapeTest = clientProperties.getString(ClientProperties.UNESCAPED_XHR_TEST);
if (unescapeTest.equals("&")) {
clientProperties.setProperty(ClientProperties.QUIRK_SAFARI_UNESCAPED_XHR, Boolean.TRUE);
}
}
}
/**
* @see nextapp.echo2.webrender.service.SynchronizeService.ClientMessagePartProcessor#getName()
*/
public String getName() {
return "EchoClientAnalyzer";
}
/**
* @see nextapp.echo2.webrender.service.SynchronizeService.ClientMessagePartProcessor#process(
* nextapp.echo2.webrender.UserInstance, org.w3c.dom.Element)
*/
public void process(UserInstance userInstance, Element messagePartElement) {
ClientProperties clientProperties = new ClientProperties();
Element[] propertyElements = DomUtil.getChildElementsByTagName(messagePartElement, "property");
for (int i = 0; i < propertyElements.length; ++i) {
String propertyName = propertyElements[i].getAttribute("name");
if (VALID_PROPERTIES.contains(propertyName)) {
String type = propertyElements[i].getAttribute("type");
if ("text".equals(type)) {
clientProperties.setProperty(propertyName, propertyElements[i].getAttribute("value"));
} else if ("integer".equals(type)) {
try {
clientProperties.setProperty(propertyName,
new Integer(propertyElements[i].getAttribute("value")));
} catch (NumberFormatException ex) { }
} else if ("boolean".equals(type)) {
clientProperties.setProperty(propertyName,
new Boolean("true".equals(propertyElements[i].getAttribute("value"))));
}
}
}
userInstance.setClientProperties(clientProperties);
analyze(clientProperties);
}
}
| true | true | private void analyze(ClientProperties clientProperties) {
Connection conn = WebRenderServlet.getActiveConnection();
Enumeration localeEnum = conn.getRequest().getLocales();
List localeList = new ArrayList();
while (localeEnum.hasMoreElements()) {
localeList.add(localeEnum.nextElement());
}
clientProperties.setProperty(ClientProperties.LOCALES, localeList.toArray(new Locale[localeList.size()]));
clientProperties.setProperty(ClientProperties.REMOTE_HOST, conn.getRequest().getRemoteHost());
String userAgent = clientProperties.getString(ClientProperties.NAVIGATOR_USER_AGENT).toLowerCase();
boolean browserOpera = userAgent.indexOf("opera") != -1;
boolean browserSafari = userAgent.indexOf("safari") != -1;
boolean browserKonqueror = userAgent.indexOf("konqueror") != -1;
// Note deceptive user agent fields:
// - Konqueror and Safari UA fields contain "like Gecko"
// - Opera UA field typically contains "MSIE"
boolean deceptiveUserAgent = browserOpera || browserSafari || browserKonqueror;
boolean browserMozilla = !deceptiveUserAgent && userAgent.indexOf("gecko") != -1;
boolean browserFireFox = userAgent.indexOf("firefox") != -1;
boolean browserInternetExplorer = !deceptiveUserAgent && userAgent.indexOf("msie") != -1;
int majorVersion = -1, minorVersion = -1;
// Store browser information.
if (browserOpera) {
clientProperties.setProperty(ClientProperties.BROWSER_OPERA, Boolean.TRUE);
if (userAgent.indexOf("opera/9") != -1 || userAgent.indexOf("opera 9") != -1) {
majorVersion = 9;
} else if (userAgent.indexOf("opera/8") != -1 || userAgent.indexOf("opera 8") != -1) {
majorVersion = 8;
} else {
// Assume future version with Opera 9 compatibility.
// (Versions prior to 8 do not provide minimum requirements, i.e., XMLHTTPRequest.)
majorVersion = 9;
}
} else if (browserKonqueror) {
clientProperties.setProperty(ClientProperties.BROWSER_KONQUEROR, Boolean.TRUE);
} else if (browserSafari) {
clientProperties.setProperty(ClientProperties.BROWSER_SAFARI, Boolean.TRUE);
} else if (browserMozilla) {
clientProperties.setProperty(ClientProperties.BROWSER_MOZILLA, Boolean.TRUE);
if (browserFireFox) {
clientProperties.setProperty(ClientProperties.BROWSER_MOZILLA_FIREFOX, Boolean.TRUE);
}
} else if (browserInternetExplorer) {
clientProperties.setProperty(ClientProperties.BROWSER_INTERNET_EXPLORER, Boolean.TRUE);
if (userAgent.indexOf("msie 6.") != -1) {
majorVersion = 6;
} else if (userAgent.indexOf("msie 7.") != -1) {
majorVersion = 7;
}
}
if (majorVersion != -1) {
clientProperties.setProperty(ClientProperties.BROWSER_VERSION_MAJOR, Integer.toString(majorVersion));
}
if (minorVersion != -1) {
clientProperties.setProperty(ClientProperties.BROWSER_VERSION_MINOR, Integer.toString(minorVersion));
}
// Set quirk flags.
if (browserInternetExplorer) {
clientProperties.setProperty(ClientProperties.QUIRK_IE_REPAINT, Boolean.TRUE);
clientProperties.setProperty(ClientProperties.QUIRK_TEXTAREA_CONTENT, Boolean.TRUE);
clientProperties.setProperty(ClientProperties.QUIRK_IE_TEXTAREA_NEWLINE_OBLITERATION, Boolean.TRUE);
clientProperties.setProperty(ClientProperties.QUIRK_IE_SELECT_LIST_DOM_UPDATE, Boolean.TRUE);
clientProperties.setProperty(ClientProperties.QUIRK_CSS_BORDER_COLLAPSE_INSIDE, Boolean.TRUE);
clientProperties.setProperty(ClientProperties.QUIRK_CSS_BORDER_COLLAPSE_FOR_0_PADDING, Boolean.TRUE);
clientProperties.setProperty(ClientProperties.NOT_SUPPORTED_CSS_OPACITY, Boolean.TRUE);
clientProperties.setProperty(ClientProperties.QUIRK_DELAYED_FOCUS_REQUIRED, Boolean.TRUE);
clientProperties.setProperty(ClientProperties.PROPRIETARY_IE_CSS_EXPRESSIONS_SUPPORTED, Boolean.TRUE);
clientProperties.setProperty(ClientProperties.PROPRIETARY_EVENT_MOUSE_ENTER_LEAVE_SUPPORTED, Boolean.TRUE);
clientProperties.setProperty(ClientProperties.PROPRIETARY_IE_OPACITY_FILTER_REQUIRED, Boolean.TRUE);
// The following flaws are verified as present in IE7.0Beta2:
clientProperties.setProperty(ClientProperties.QUIRK_IE_TABLE_PERCENT_WIDTH_SCROLLBAR_ERROR, Boolean.TRUE);
clientProperties.setProperty(ClientProperties.QUIRK_IE_SELECT_PERCENT_WIDTH, Boolean.TRUE);
if (majorVersion < 7) {
// The following flaws are verified as fixed in IE7.0Beta2:
clientProperties.setProperty(ClientProperties.PROPRIETARY_IE_PNG_ALPHA_FILTER_REQUIRED, Boolean.TRUE);
clientProperties.setProperty(ClientProperties.QUIRK_CSS_POSITIONING_ONE_SIDE_ONLY, Boolean.TRUE);
clientProperties.setProperty(ClientProperties.QUIRK_CSS_BACKGROUND_ATTACHMENT_USE_FIXED, Boolean.TRUE);
clientProperties.setProperty(ClientProperties.QUIRK_IE_SELECT_Z_INDEX, Boolean.TRUE);
}
}
if (browserOpera) {
clientProperties.setProperty(ClientProperties.QUIRK_TEXTAREA_CONTENT, Boolean.TRUE);
clientProperties.setProperty(ClientProperties.QUIRK_OPERA_NO_CSS_TEXT, Boolean.TRUE);
clientProperties.setProperty(ClientProperties.QUIRK_SELECT_REQUIRES_NULL_OPTION, Boolean.TRUE);
clientProperties.setProperty(ClientProperties.QUIRK_IE_SELECT_PERCENT_WIDTH, Boolean.TRUE);
if (majorVersion < 9) {
clientProperties.setProperty(ClientProperties.NOT_SUPPORTED_CSS_OPACITY, Boolean.TRUE);
}
}
if (browserMozilla) {
clientProperties.setProperty(ClientProperties.QUIRK_SELECT_REQUIRES_NULL_OPTION, Boolean.TRUE);
clientProperties.setProperty(ClientProperties.QUIRK_MOZILLA_TEXT_INPUT_REPAINT, Boolean.TRUE);
clientProperties.setProperty(ClientProperties.QUIRK_MOZILLA_PERFORMANCE_LARGE_DOM_REMOVE, Boolean.TRUE);
}
if (browserKonqueror) {
clientProperties.setProperty(ClientProperties.QUIRK_SELECT_REQUIRES_NULL_OPTION, Boolean.TRUE);
clientProperties.setProperty(ClientProperties.QUIRK_IE_SELECT_PERCENT_WIDTH, Boolean.TRUE);
clientProperties.setProperty(ClientProperties.NOT_SUPPORTED_CSS_MANIPULATION, Boolean.TRUE);
}
if (browserSafari) {
clientProperties.setProperty(ClientProperties.QUIRK_SELECT_REQUIRES_NULL_OPTION, Boolean.TRUE);
clientProperties.setProperty(ClientProperties.NOT_SUPPORTED_CSS_MANIPULATION, Boolean.TRUE);
String unescapeTest = clientProperties.getString(ClientProperties.UNESCAPED_XHR_TEST);
if (unescapeTest.equals("&")) {
clientProperties.setProperty(ClientProperties.QUIRK_SAFARI_UNESCAPED_XHR, Boolean.TRUE);
}
}
}
| private void analyze(ClientProperties clientProperties) {
Connection conn = WebRenderServlet.getActiveConnection();
Enumeration localeEnum = conn.getRequest().getLocales();
List localeList = new ArrayList();
while (localeEnum.hasMoreElements()) {
localeList.add(localeEnum.nextElement());
}
clientProperties.setProperty(ClientProperties.LOCALES, localeList.toArray(new Locale[localeList.size()]));
clientProperties.setProperty(ClientProperties.REMOTE_HOST, conn.getRequest().getRemoteHost());
String userAgent = clientProperties.getString(ClientProperties.NAVIGATOR_USER_AGENT).toLowerCase();
boolean browserOpera = userAgent.indexOf("opera") != -1;
boolean browserSafari = userAgent.indexOf("safari") != -1;
boolean browserKonqueror = userAgent.indexOf("konqueror") != -1;
// Note deceptive user agent fields:
// - Konqueror and Safari UA fields contain "like Gecko"
// - Opera UA field typically contains "MSIE"
boolean deceptiveUserAgent = browserOpera || browserSafari || browserKonqueror;
boolean browserMozilla = !deceptiveUserAgent && userAgent.indexOf("gecko") != -1;
boolean browserFireFox = userAgent.indexOf("firefox") != -1;
boolean browserInternetExplorer = !deceptiveUserAgent && userAgent.indexOf("msie") != -1;
int majorVersion = -1, minorVersion = -1;
// Store browser information.
if (browserOpera) {
clientProperties.setProperty(ClientProperties.BROWSER_OPERA, Boolean.TRUE);
if (userAgent.indexOf("opera/9") != -1 || userAgent.indexOf("opera 9") != -1) {
majorVersion = 9;
} else if (userAgent.indexOf("opera/8") != -1 || userAgent.indexOf("opera 8") != -1) {
majorVersion = 8;
} else {
// Assume future version with Opera 9 compatibility.
// (Versions prior to 8 do not provide minimum requirements, i.e., XMLHTTPRequest.)
majorVersion = 9;
}
} else if (browserKonqueror) {
clientProperties.setProperty(ClientProperties.BROWSER_KONQUEROR, Boolean.TRUE);
} else if (browserSafari) {
clientProperties.setProperty(ClientProperties.BROWSER_SAFARI, Boolean.TRUE);
} else if (browserMozilla) {
clientProperties.setProperty(ClientProperties.BROWSER_MOZILLA, Boolean.TRUE);
if (browserFireFox) {
clientProperties.setProperty(ClientProperties.BROWSER_MOZILLA_FIREFOX, Boolean.TRUE);
if (userAgent.indexOf("firefox/3.0") != -1) {
majorVersion = 3;
minorVersion = 0;
}
}
} else if (browserInternetExplorer) {
clientProperties.setProperty(ClientProperties.BROWSER_INTERNET_EXPLORER, Boolean.TRUE);
if (userAgent.indexOf("msie 6.") != -1) {
majorVersion = 6;
} else if (userAgent.indexOf("msie 7.") != -1) {
majorVersion = 7;
}
}
if (majorVersion != -1) {
clientProperties.setProperty(ClientProperties.BROWSER_VERSION_MAJOR, Integer.toString(majorVersion));
}
if (minorVersion != -1) {
clientProperties.setProperty(ClientProperties.BROWSER_VERSION_MINOR, Integer.toString(minorVersion));
}
// Set quirk flags.
if (browserInternetExplorer) {
clientProperties.setProperty(ClientProperties.QUIRK_IE_REPAINT, Boolean.TRUE);
clientProperties.setProperty(ClientProperties.QUIRK_TEXTAREA_CONTENT, Boolean.TRUE);
clientProperties.setProperty(ClientProperties.QUIRK_IE_TEXTAREA_NEWLINE_OBLITERATION, Boolean.TRUE);
clientProperties.setProperty(ClientProperties.QUIRK_IE_SELECT_LIST_DOM_UPDATE, Boolean.TRUE);
clientProperties.setProperty(ClientProperties.QUIRK_CSS_BORDER_COLLAPSE_INSIDE, Boolean.TRUE);
clientProperties.setProperty(ClientProperties.QUIRK_CSS_BORDER_COLLAPSE_FOR_0_PADDING, Boolean.TRUE);
clientProperties.setProperty(ClientProperties.NOT_SUPPORTED_CSS_OPACITY, Boolean.TRUE);
clientProperties.setProperty(ClientProperties.QUIRK_DELAYED_FOCUS_REQUIRED, Boolean.TRUE);
clientProperties.setProperty(ClientProperties.PROPRIETARY_IE_CSS_EXPRESSIONS_SUPPORTED, Boolean.TRUE);
clientProperties.setProperty(ClientProperties.PROPRIETARY_EVENT_MOUSE_ENTER_LEAVE_SUPPORTED, Boolean.TRUE);
clientProperties.setProperty(ClientProperties.PROPRIETARY_IE_OPACITY_FILTER_REQUIRED, Boolean.TRUE);
// The following flaws are verified as present in IE7.0Beta2:
clientProperties.setProperty(ClientProperties.QUIRK_IE_TABLE_PERCENT_WIDTH_SCROLLBAR_ERROR, Boolean.TRUE);
clientProperties.setProperty(ClientProperties.QUIRK_IE_SELECT_PERCENT_WIDTH, Boolean.TRUE);
if (majorVersion < 7) {
// The following flaws are verified as fixed in IE7.0Beta2:
clientProperties.setProperty(ClientProperties.PROPRIETARY_IE_PNG_ALPHA_FILTER_REQUIRED, Boolean.TRUE);
clientProperties.setProperty(ClientProperties.QUIRK_CSS_POSITIONING_ONE_SIDE_ONLY, Boolean.TRUE);
clientProperties.setProperty(ClientProperties.QUIRK_CSS_BACKGROUND_ATTACHMENT_USE_FIXED, Boolean.TRUE);
clientProperties.setProperty(ClientProperties.QUIRK_IE_SELECT_Z_INDEX, Boolean.TRUE);
}
}
if (browserOpera) {
clientProperties.setProperty(ClientProperties.QUIRK_TEXTAREA_CONTENT, Boolean.TRUE);
clientProperties.setProperty(ClientProperties.QUIRK_OPERA_NO_CSS_TEXT, Boolean.TRUE);
clientProperties.setProperty(ClientProperties.QUIRK_SELECT_REQUIRES_NULL_OPTION, Boolean.TRUE);
clientProperties.setProperty(ClientProperties.QUIRK_IE_SELECT_PERCENT_WIDTH, Boolean.TRUE);
if (majorVersion < 9) {
clientProperties.setProperty(ClientProperties.NOT_SUPPORTED_CSS_OPACITY, Boolean.TRUE);
}
}
if (browserMozilla) {
clientProperties.setProperty(ClientProperties.QUIRK_SELECT_REQUIRES_NULL_OPTION, Boolean.TRUE);
clientProperties.setProperty(ClientProperties.QUIRK_MOZILLA_TEXT_INPUT_REPAINT, Boolean.TRUE);
clientProperties.setProperty(ClientProperties.QUIRK_MOZILLA_PERFORMANCE_LARGE_DOM_REMOVE, Boolean.TRUE);
}
if (browserKonqueror) {
clientProperties.setProperty(ClientProperties.QUIRK_SELECT_REQUIRES_NULL_OPTION, Boolean.TRUE);
clientProperties.setProperty(ClientProperties.QUIRK_IE_SELECT_PERCENT_WIDTH, Boolean.TRUE);
clientProperties.setProperty(ClientProperties.NOT_SUPPORTED_CSS_MANIPULATION, Boolean.TRUE);
}
if (browserSafari) {
clientProperties.setProperty(ClientProperties.QUIRK_SELECT_REQUIRES_NULL_OPTION, Boolean.TRUE);
clientProperties.setProperty(ClientProperties.NOT_SUPPORTED_CSS_MANIPULATION, Boolean.TRUE);
String unescapeTest = clientProperties.getString(ClientProperties.UNESCAPED_XHR_TEST);
if (unescapeTest.equals("&")) {
clientProperties.setProperty(ClientProperties.QUIRK_SAFARI_UNESCAPED_XHR, Boolean.TRUE);
}
}
}
|
diff --git a/src/dataStructure/PointQuadTree.java b/src/dataStructure/PointQuadTree.java
index 609c9e5..7255f42 100644
--- a/src/dataStructure/PointQuadTree.java
+++ b/src/dataStructure/PointQuadTree.java
@@ -1,106 +1,106 @@
package dataStructure;
import java.util.ArrayList;
import java.math.BigDecimal;
/**
* PointQuadTree is a linked list quad tree data structures.
* It is used to structure and quickly find points, taking advantage of their 2D location.
*
* This class is written with inspiration from QuadTree.java by Robert Sedgewick and Kevin Wayne
* http://algs4.cs.princeton.edu/92search/QuadTree.java.html
*
* Thanks to hypesystem and Morten Roed for pushing we towards this data structure and implementation
*
* @author Claus L. Henriksen
* @version 28. Marts 2012
* @param <Point>
* @see Point
*/
public class PointQuadTree<Point> {
private Node root;
private ArrayList<Point> array;
/**
* Wrapper class used for the 2D data structure.
* Each leaf is a Node.
*/
private class Node{
Node NW, NE, SE, SW; //Four subtrees
Point point;
Node(Point point){
this.point = point;
}
}
/**
* Insert new point to the quad tree.
* The point will be wrapped and placed correctly within the tree.
*
* @param point
*/
public void inset(Point point){
root = insert(root, point);
}
/**
* Private method to wrap and insert a new point correctly within the tree.
* This is called recursively until a correct location for the point is found.
*
* @param h Root of the subtree where the point is to be placed
* @param point The point to be placed
* @return The inserted node
*/
private Node insert(Node h, Point point){
if(h == null) return new Node(point); //First point inserted becomes root
else if ( less(point.getX().doubleValue(), h.point.getX().doubleValue()) && less(point.getY().doubleValue(), h.point.getY().doubleValue())) h.SW = insert(h.SW, point);
else if ( less(point.getX().doubleValue(), h.point.getX().doubleValue()) && !less(point.getY().doubleValue(), h.point.getY().doubleValue())) h.NW = insert(h.NW, point);
else if (!less(point.getX().doubleValue(), h.point.getX().doubleValue()) && less(point.getY().doubleValue(), h.point.getY().doubleValue())) h.SE = insert(h.SE, point);
else if (!less(point.getX().doubleValue(), h.point.getX().doubleValue()) && !less(point.getY().doubleValue(), h.point.getY().doubleValue())) h.NE = insert(h.NE, point);
return h;
}
/**
* Find all points within a rectangle.
*
* @param rect A rectangular interval defined by the Interval2D class
* @see Interval2D
* @see Point
* @return ArrayList of points within interval
*/
public ArrayList<Point> getRect(Interval2D rect){
array = new ArrayList<Point>();
getRect(root, rect);
return array;
}
/**
* Private method for finding points within interval. Method works recursively.
* @param h Root of subtree to be searched
* @param rect Interval to be within
* @return ArrayList of points within interval
*/
private ArrayList<Point> getRect(Node h, Interval2D rect){
if (h == null) return null;
- double xmin = rect.intervalX.low;
- double ymin = rect.intervalY.low;
- double xmax = rect.intervalX.high;
- double ymax = rect.intervalY.high;
+ double xmin = rect.getIntervalX().getLow();
+ double ymin = rect.getIntervalY().getLow();
+ double xmax = rect.getIntervalX().getHigh();
+ double ymax = rect.getIntervalY().getHigh();
if (rect.contains(h.point.getX().doubleValue(), h.point.getY().doubleValue()))
array.add(h.point);
if ( less(xmin, h.point.getX().doubleValue()) && less(ymin, h.point.getY().doubleValue())) getRect(h.SW, rect);
if ( less(xmin, h.point.getX().doubleValue()) && !less(ymax, h.point.getY().doubleValue())) getRect(h.NW, rect);
if (!less(xmax, h.point.getX().doubleValue()) && less(ymin, h.point.getY().doubleValue())) getRect(h.SE, rect);
if (!less(xmax, h.point.getX().doubleValue()) && !less(ymax, h.point.getY().doubleValue())) getRect(h.NE, rect);
return array;
}
/**
* Private method to compare doubles
* @param k1 First double
* @param k2 Second double
* @return True if first double is less than the secound double
*/
private boolean less(double k1, double k2) { return k1 - k2 < 0; }
}
| true | true | private ArrayList<Point> getRect(Node h, Interval2D rect){
if (h == null) return null;
double xmin = rect.intervalX.low;
double ymin = rect.intervalY.low;
double xmax = rect.intervalX.high;
double ymax = rect.intervalY.high;
if (rect.contains(h.point.getX().doubleValue(), h.point.getY().doubleValue()))
array.add(h.point);
if ( less(xmin, h.point.getX().doubleValue()) && less(ymin, h.point.getY().doubleValue())) getRect(h.SW, rect);
if ( less(xmin, h.point.getX().doubleValue()) && !less(ymax, h.point.getY().doubleValue())) getRect(h.NW, rect);
if (!less(xmax, h.point.getX().doubleValue()) && less(ymin, h.point.getY().doubleValue())) getRect(h.SE, rect);
if (!less(xmax, h.point.getX().doubleValue()) && !less(ymax, h.point.getY().doubleValue())) getRect(h.NE, rect);
return array;
}
| private ArrayList<Point> getRect(Node h, Interval2D rect){
if (h == null) return null;
double xmin = rect.getIntervalX().getLow();
double ymin = rect.getIntervalY().getLow();
double xmax = rect.getIntervalX().getHigh();
double ymax = rect.getIntervalY().getHigh();
if (rect.contains(h.point.getX().doubleValue(), h.point.getY().doubleValue()))
array.add(h.point);
if ( less(xmin, h.point.getX().doubleValue()) && less(ymin, h.point.getY().doubleValue())) getRect(h.SW, rect);
if ( less(xmin, h.point.getX().doubleValue()) && !less(ymax, h.point.getY().doubleValue())) getRect(h.NW, rect);
if (!less(xmax, h.point.getX().doubleValue()) && less(ymin, h.point.getY().doubleValue())) getRect(h.SE, rect);
if (!less(xmax, h.point.getX().doubleValue()) && !less(ymax, h.point.getY().doubleValue())) getRect(h.NE, rect);
return array;
}
|
diff --git a/Essentials/src/com/earth2me/essentials/Essentials.java b/Essentials/src/com/earth2me/essentials/Essentials.java
index 24ac0ad6..d7f749eb 100644
--- a/Essentials/src/com/earth2me/essentials/Essentials.java
+++ b/Essentials/src/com/earth2me/essentials/Essentials.java
@@ -1,644 +1,644 @@
/*
* Essentials - a bukkit plugin
* Copyright (C) 2011 Essentials Team
*
* 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 com.earth2me.essentials;
import static com.earth2me.essentials.I18n._;
import com.earth2me.essentials.api.Economy;
import com.earth2me.essentials.api.IJails;
import com.earth2me.essentials.commands.EssentialsCommand;
import com.earth2me.essentials.commands.IEssentialsCommand;
import com.earth2me.essentials.commands.NoChargeException;
import com.earth2me.essentials.commands.NotEnoughArgumentsException;
import com.earth2me.essentials.perm.PermissionsHandler;
import com.earth2me.essentials.register.payment.Methods;
import com.earth2me.essentials.signs.SignBlockListener;
import com.earth2me.essentials.signs.SignEntityListener;
import com.earth2me.essentials.signs.SignPlayerListener;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.bukkit.ChatColor;
import org.bukkit.Server;
import org.bukkit.World;
import org.bukkit.command.Command;
import org.bukkit.command.CommandException;
import org.bukkit.command.CommandSender;
import org.bukkit.command.PluginCommand;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.world.WorldLoadEvent;
import org.bukkit.event.world.WorldUnloadEvent;
import org.bukkit.plugin.InvalidDescriptionException;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitScheduler;
import org.yaml.snakeyaml.error.YAMLException;
public class Essentials extends JavaPlugin implements IEssentials
{
public static final int BUKKIT_VERSION = 1988;
private static final Logger LOGGER = Logger.getLogger("Minecraft");
private transient ISettings settings;
private final transient TNTExplodeListener tntListener = new TNTExplodeListener(this);
private transient Jails jails;
private transient Warps warps;
private transient Worth worth;
private transient List<IConf> confList;
private transient Backup backup;
private transient ItemDb itemDb;
private transient final Methods paymentMethod = new Methods();
private transient PermissionsHandler permissionsHandler;
private transient AlternativeCommandsHandler alternativeCommandsHandler;
private transient UserMap userMap;
private transient ExecuteTimer execTimer;
private transient I18n i18n;
@Override
public ISettings getSettings()
{
return settings;
}
public void setupForTesting(final Server server) throws IOException, InvalidDescriptionException
{
final File dataFolder = File.createTempFile("essentialstest", "");
if (!dataFolder.delete())
{
throw new IOException();
}
if (!dataFolder.mkdir())
{
throw new IOException();
}
i18n = new I18n(this);
i18n.onEnable();
LOGGER.log(Level.INFO, _("usingTempFolderForTesting"));
LOGGER.log(Level.INFO, dataFolder.toString());
this.initialize(null, server, new PluginDescriptionFile(new FileReader(new File("src" + File.separator + "plugin.yml"))), dataFolder, null, null);
settings = new Settings(this);
i18n.updateLocale("en");
userMap = new UserMap(this);
permissionsHandler = new PermissionsHandler(this, false);
Economy.setEss(this);
}
@Override
public void onEnable()
{
execTimer = new ExecuteTimer();
execTimer.start();
i18n = new I18n(this);
i18n.onEnable();
execTimer.mark("I18n1");
final PluginManager pm = getServer().getPluginManager();
for (Plugin plugin : pm.getPlugins())
{
if (plugin.getDescription().getName().startsWith("Essentials")
&& !plugin.getDescription().getVersion().equals(this.getDescription().getVersion()))
{
LOGGER.log(Level.WARNING, _("versionMismatch", plugin.getDescription().getName()));
}
}
final Matcher versionMatch = Pattern.compile("git-Bukkit-(?:(?:[0-9]+)\\.)+[0-9]+-R[0-9]+-(?:[0-9]+-g[0-9a-f]+-)?b([0-9]+)jnks.*").matcher(getServer().getVersion());
if (versionMatch.matches())
{
final int versionNumber = Integer.parseInt(versionMatch.group(1));
- if (versionNumber < BUKKIT_VERSION)
+ if (versionNumber < BUKKIT_VERSION && versionNumber > 100)
{
LOGGER.log(Level.SEVERE, _("notRecommendedBukkit"));
LOGGER.log(Level.SEVERE, _("requiredBukkit", Integer.toString(BUKKIT_VERSION)));
this.setEnabled(false);
return;
}
}
else
{
LOGGER.log(Level.INFO, _("bukkitFormatChanged"));
LOGGER.log(Level.INFO, getServer().getVersion());
LOGGER.log(Level.INFO, getServer().getBukkitVersion());
}
execTimer.mark("BukkitCheck");
try
{
final EssentialsUpgrade upgrade = new EssentialsUpgrade(this);
upgrade.beforeSettings();
execTimer.mark("Upgrade");
confList = new ArrayList<IConf>();
settings = new Settings(this);
confList.add(settings);
execTimer.mark("Settings");
upgrade.afterSettings();
execTimer.mark("Upgrade2");
i18n.updateLocale(settings.getLocale());
userMap = new UserMap(this);
confList.add(userMap);
execTimer.mark("Init(Usermap)");
warps = new Warps(getServer(), this.getDataFolder());
confList.add(warps);
execTimer.mark("Init(Spawn/Warp)");
worth = new Worth(this.getDataFolder());
confList.add(worth);
itemDb = new ItemDb(this);
confList.add(itemDb);
execTimer.mark("Init(Worth/ItemDB)");
reload();
}
catch (YAMLException exception)
{
if (pm.getPlugin("EssentialsUpdate") != null)
{
LOGGER.log(Level.SEVERE, _("essentialsHelp2"));
}
else
{
LOGGER.log(Level.SEVERE, _("essentialsHelp1"));
}
LOGGER.log(Level.SEVERE, exception.toString());
pm.registerEvents(new Listener()
{
@EventHandler(priority = EventPriority.LOW)
public void onPlayerJoin(final PlayerJoinEvent event)
{
event.getPlayer().sendMessage("Essentials failed to load, read the log file.");
}
}, this);
for (Player player : getServer().getOnlinePlayers())
{
player.sendMessage("Essentials failed to load, read the log file.");
}
this.setEnabled(false);
return;
}
backup = new Backup(this);
permissionsHandler = new PermissionsHandler(this, settings.useBukkitPermissions());
alternativeCommandsHandler = new AlternativeCommandsHandler(this);
final EssentialsPluginListener serverListener = new EssentialsPluginListener(this);
pm.registerEvents(serverListener, this);
confList.add(serverListener);
final EssentialsPlayerListener playerListener = new EssentialsPlayerListener(this);
pm.registerEvents(playerListener, this);
final EssentialsBlockListener blockListener = new EssentialsBlockListener(this);
pm.registerEvents(blockListener, this);
final SignBlockListener signBlockListener = new SignBlockListener(this);
pm.registerEvents(signBlockListener, this);
final SignPlayerListener signPlayerListener = new SignPlayerListener(this);
pm.registerEvents(signPlayerListener, this);
final SignEntityListener signEntityListener = new SignEntityListener(this);
pm.registerEvents(signEntityListener, this);
final EssentialsEntityListener entityListener = new EssentialsEntityListener(this);
pm.registerEvents(entityListener, this);
final EssentialsWorldListener worldListener = new EssentialsWorldListener(this);
pm.registerEvents(worldListener, this);
//TODO: Check if this should be here, and not above before reload()
jails = new Jails(this);
confList.add(jails);
pm.registerEvents(tntListener, this);
final EssentialsTimer timer = new EssentialsTimer(this);
getScheduler().scheduleSyncRepeatingTask(this, timer, 1, 100);
Economy.setEss(this);
execTimer.mark("RegListeners");
final String timeroutput = execTimer.end();
if (getSettings().isDebug())
{
LOGGER.log(Level.INFO, "Essentials load " + timeroutput);
}
}
@Override
public void onDisable()
{
i18n.onDisable();
Economy.setEss(null);
Trade.closeLog();
}
@Override
public void reload()
{
Trade.closeLog();
for (IConf iConf : confList)
{
iConf.reloadConfig();
execTimer.mark("Reload(" + iConf.getClass().getSimpleName() + ")");
}
i18n.updateLocale(settings.getLocale());
}
@Override
public boolean onCommand(final CommandSender sender, final Command command, final String commandLabel, final String[] args)
{
return onCommandEssentials(sender, command, commandLabel, args, Essentials.class.getClassLoader(), "com.earth2me.essentials.commands.Command", "essentials.", null);
}
@Override
public boolean onCommandEssentials(final CommandSender sender, final Command command, final String commandLabel, final String[] args, final ClassLoader classLoader, final String commandPath, final String permissionPrefix, final IEssentialsModule module)
{
// Allow plugins to override the command via onCommand
if (!getSettings().isCommandOverridden(command.getName()) && (!commandLabel.startsWith("e") || commandLabel.equalsIgnoreCase(command.getName())))
{
final PluginCommand pc = alternativeCommandsHandler.getAlternative(commandLabel);
if (pc != null)
{
alternativeCommandsHandler.executed(commandLabel, pc.getLabel());
try
{
return pc.execute(sender, commandLabel, args);
}
catch (final Exception ex)
{
final ArrayList<StackTraceElement> elements = new ArrayList<StackTraceElement>(Arrays.asList(ex.getStackTrace()));
elements.remove(0);
final ArrayList<StackTraceElement> toRemove = new ArrayList<StackTraceElement>();
for (final StackTraceElement e : elements)
{
if (e.getClassName().equals("com.earth2me.essentials.Essentials"))
{
toRemove.add(e);
}
}
elements.removeAll(toRemove);
final StackTraceElement[] trace = elements.toArray(new StackTraceElement[elements.size()]);
ex.setStackTrace(trace);
ex.printStackTrace();
sender.sendMessage(ChatColor.RED + "An internal error occurred while attempting to perform this command");
return true;
}
}
}
try
{
User user = null;
if (sender instanceof Player)
{
user = getUser(sender);
LOGGER.log(Level.INFO, String.format("[PLAYER_COMMAND] %s: /%s %s ", ((Player)sender).getName(), commandLabel, EssentialsCommand.getFinalArg(args, 0)));
}
// New mail notification
if (user != null && !getSettings().isCommandDisabled("mail") && !commandLabel.equals("mail") && user.isAuthorized("essentials.mail"))
{
final List<String> mail = user.getMails();
if (mail != null && !mail.isEmpty())
{
user.sendMessage(_("youHaveNewMail", mail.size()));
}
}
// Check for disabled commands
if (getSettings().isCommandDisabled(commandLabel))
{
return true;
}
IEssentialsCommand cmd;
try
{
cmd = (IEssentialsCommand)classLoader.loadClass(commandPath + command.getName()).newInstance();
cmd.setEssentials(this);
cmd.setEssentialsModule(module);
}
catch (Exception ex)
{
sender.sendMessage(_("commandNotLoaded", commandLabel));
LOGGER.log(Level.SEVERE, _("commandNotLoaded", commandLabel), ex);
return true;
}
// Check authorization
if (user != null && !user.isAuthorized(cmd, permissionPrefix))
{
LOGGER.log(Level.WARNING, _("deniedAccessCommand", user.getName()));
user.sendMessage(_("noAccessCommand"));
return true;
}
// Run the command
try
{
if (user == null)
{
cmd.run(getServer(), sender, commandLabel, command, args);
}
else
{
cmd.run(getServer(), user, commandLabel, command, args);
}
return true;
}
catch (NoChargeException ex)
{
return true;
}
catch (NotEnoughArgumentsException ex)
{
sender.sendMessage(command.getDescription());
sender.sendMessage(command.getUsage().replaceAll("<command>", commandLabel));
if (!ex.getMessage().isEmpty())
{
sender.sendMessage(ex.getMessage());
}
return true;
}
catch (Throwable ex)
{
showError(sender, ex, commandLabel);
return true;
}
}
catch (Throwable ex)
{
LOGGER.log(Level.SEVERE, _("commandFailed", commandLabel), ex);
return true;
}
}
@Override
public void showError(final CommandSender sender, final Throwable exception, final String commandLabel)
{
sender.sendMessage(_("errorWithMessage", exception.getMessage()));
if (getSettings().isDebug())
{
LOGGER.log(Level.WARNING, _("errorCallingCommand", commandLabel), exception);
}
}
@Override
public BukkitScheduler getScheduler()
{
return this.getServer().getScheduler();
}
@Override
public IJails getJails()
{
return jails;
}
@Override
public Warps getWarps()
{
return warps;
}
@Override
public Worth getWorth()
{
return worth;
}
@Override
public Backup getBackup()
{
return backup;
}
@Override
public User getUser(final Object base)
{
if (base instanceof Player)
{
return getUser((Player)base);
}
if (base instanceof String)
{
final User user = userMap.getUser((String)base);
if (user != null && user.getBase() instanceof OfflinePlayer)
{
((OfflinePlayer)user.getBase()).setName((String)base);
}
return user;
}
return null;
}
private <T extends Player> User getUser(final T base)
{
if (base == null)
{
return null;
}
if (base instanceof User)
{
return (User)base;
}
User user = userMap.getUser(base.getName());
if (user == null)
{
user = new User(base, this);
}
else
{
user.update(base);
}
return user;
}
@Override
public User getOfflineUser(final String name)
{
final User user = userMap.getUser(name);
if (user != null && user.getBase() instanceof OfflinePlayer)
{
((OfflinePlayer)user.getBase()).setName(name);
}
return user;
}
@Override
public World getWorld(final String name)
{
if (name.matches("[0-9]+"))
{
final int worldId = Integer.parseInt(name);
if (worldId < getServer().getWorlds().size())
{
return getServer().getWorlds().get(worldId);
}
}
return getServer().getWorld(name);
}
@Override
public void addReloadListener(final IConf listener)
{
confList.add(listener);
}
@Override
public Methods getPaymentMethod()
{
return paymentMethod;
}
@Override
public int broadcastMessage(final IUser sender, final String message)
{
if (sender == null)
{
return getServer().broadcastMessage(message);
}
if (sender.isHidden())
{
return 0;
}
final Player[] players = getServer().getOnlinePlayers();
for (Player player : players)
{
final User user = getUser(player);
if (!user.isIgnoredPlayer(sender.getName()))
{
player.sendMessage(message);
}
}
return players.length;
}
@Override
public int scheduleAsyncDelayedTask(final Runnable run)
{
return this.getScheduler().scheduleAsyncDelayedTask(this, run);
}
@Override
public int scheduleSyncDelayedTask(final Runnable run)
{
return this.getScheduler().scheduleSyncDelayedTask(this, run);
}
@Override
public int scheduleSyncDelayedTask(final Runnable run, final long delay)
{
return this.getScheduler().scheduleSyncDelayedTask(this, run, delay);
}
@Override
public int scheduleSyncRepeatingTask(final Runnable run, final long delay, final long period)
{
return this.getScheduler().scheduleSyncRepeatingTask(this, run, delay, period);
}
@Override
public TNTExplodeListener getTNTListener()
{
return tntListener;
}
@Override
public PermissionsHandler getPermissionsHandler()
{
return permissionsHandler;
}
@Override
public AlternativeCommandsHandler getAlternativeCommandsHandler()
{
return alternativeCommandsHandler;
}
@Override
public ItemDb getItemDb()
{
return itemDb;
}
@Override
public UserMap getUserMap()
{
return userMap;
}
@Override
public I18n getI18n()
{
return i18n;
}
private static class EssentialsWorldListener implements Listener, Runnable {
private transient final IEssentials ess;
public EssentialsWorldListener(final IEssentials ess)
{
this.ess = ess;
}
@EventHandler(priority = EventPriority.LOW)
public void onWorldLoad(final WorldLoadEvent event)
{
ess.getJails().onReload();
ess.getWarps().reloadConfig();
for (IConf iConf : ((Essentials)ess).confList)
{
if (iConf instanceof IEssentialsModule) {
iConf.reloadConfig();
}
}
}
@EventHandler(priority = EventPriority.LOW)
public void onWorldUnload(final WorldUnloadEvent event)
{
ess.getJails().onReload();
ess.getWarps().reloadConfig();
for (IConf iConf : ((Essentials)ess).confList)
{
if (iConf instanceof IEssentialsModule) {
iConf.reloadConfig();
}
}
}
@Override
public void run()
{
ess.reload();
}
}
}
| true | true | public void onEnable()
{
execTimer = new ExecuteTimer();
execTimer.start();
i18n = new I18n(this);
i18n.onEnable();
execTimer.mark("I18n1");
final PluginManager pm = getServer().getPluginManager();
for (Plugin plugin : pm.getPlugins())
{
if (plugin.getDescription().getName().startsWith("Essentials")
&& !plugin.getDescription().getVersion().equals(this.getDescription().getVersion()))
{
LOGGER.log(Level.WARNING, _("versionMismatch", plugin.getDescription().getName()));
}
}
final Matcher versionMatch = Pattern.compile("git-Bukkit-(?:(?:[0-9]+)\\.)+[0-9]+-R[0-9]+-(?:[0-9]+-g[0-9a-f]+-)?b([0-9]+)jnks.*").matcher(getServer().getVersion());
if (versionMatch.matches())
{
final int versionNumber = Integer.parseInt(versionMatch.group(1));
if (versionNumber < BUKKIT_VERSION)
{
LOGGER.log(Level.SEVERE, _("notRecommendedBukkit"));
LOGGER.log(Level.SEVERE, _("requiredBukkit", Integer.toString(BUKKIT_VERSION)));
this.setEnabled(false);
return;
}
}
else
{
LOGGER.log(Level.INFO, _("bukkitFormatChanged"));
LOGGER.log(Level.INFO, getServer().getVersion());
LOGGER.log(Level.INFO, getServer().getBukkitVersion());
}
execTimer.mark("BukkitCheck");
try
{
final EssentialsUpgrade upgrade = new EssentialsUpgrade(this);
upgrade.beforeSettings();
execTimer.mark("Upgrade");
confList = new ArrayList<IConf>();
settings = new Settings(this);
confList.add(settings);
execTimer.mark("Settings");
upgrade.afterSettings();
execTimer.mark("Upgrade2");
i18n.updateLocale(settings.getLocale());
userMap = new UserMap(this);
confList.add(userMap);
execTimer.mark("Init(Usermap)");
warps = new Warps(getServer(), this.getDataFolder());
confList.add(warps);
execTimer.mark("Init(Spawn/Warp)");
worth = new Worth(this.getDataFolder());
confList.add(worth);
itemDb = new ItemDb(this);
confList.add(itemDb);
execTimer.mark("Init(Worth/ItemDB)");
reload();
}
catch (YAMLException exception)
{
if (pm.getPlugin("EssentialsUpdate") != null)
{
LOGGER.log(Level.SEVERE, _("essentialsHelp2"));
}
else
{
LOGGER.log(Level.SEVERE, _("essentialsHelp1"));
}
LOGGER.log(Level.SEVERE, exception.toString());
pm.registerEvents(new Listener()
{
@EventHandler(priority = EventPriority.LOW)
public void onPlayerJoin(final PlayerJoinEvent event)
{
event.getPlayer().sendMessage("Essentials failed to load, read the log file.");
}
}, this);
for (Player player : getServer().getOnlinePlayers())
{
player.sendMessage("Essentials failed to load, read the log file.");
}
this.setEnabled(false);
return;
}
backup = new Backup(this);
permissionsHandler = new PermissionsHandler(this, settings.useBukkitPermissions());
alternativeCommandsHandler = new AlternativeCommandsHandler(this);
final EssentialsPluginListener serverListener = new EssentialsPluginListener(this);
pm.registerEvents(serverListener, this);
confList.add(serverListener);
final EssentialsPlayerListener playerListener = new EssentialsPlayerListener(this);
pm.registerEvents(playerListener, this);
final EssentialsBlockListener blockListener = new EssentialsBlockListener(this);
pm.registerEvents(blockListener, this);
final SignBlockListener signBlockListener = new SignBlockListener(this);
pm.registerEvents(signBlockListener, this);
final SignPlayerListener signPlayerListener = new SignPlayerListener(this);
pm.registerEvents(signPlayerListener, this);
final SignEntityListener signEntityListener = new SignEntityListener(this);
pm.registerEvents(signEntityListener, this);
final EssentialsEntityListener entityListener = new EssentialsEntityListener(this);
pm.registerEvents(entityListener, this);
final EssentialsWorldListener worldListener = new EssentialsWorldListener(this);
pm.registerEvents(worldListener, this);
//TODO: Check if this should be here, and not above before reload()
jails = new Jails(this);
confList.add(jails);
pm.registerEvents(tntListener, this);
final EssentialsTimer timer = new EssentialsTimer(this);
getScheduler().scheduleSyncRepeatingTask(this, timer, 1, 100);
Economy.setEss(this);
execTimer.mark("RegListeners");
final String timeroutput = execTimer.end();
if (getSettings().isDebug())
{
LOGGER.log(Level.INFO, "Essentials load " + timeroutput);
}
}
| public void onEnable()
{
execTimer = new ExecuteTimer();
execTimer.start();
i18n = new I18n(this);
i18n.onEnable();
execTimer.mark("I18n1");
final PluginManager pm = getServer().getPluginManager();
for (Plugin plugin : pm.getPlugins())
{
if (plugin.getDescription().getName().startsWith("Essentials")
&& !plugin.getDescription().getVersion().equals(this.getDescription().getVersion()))
{
LOGGER.log(Level.WARNING, _("versionMismatch", plugin.getDescription().getName()));
}
}
final Matcher versionMatch = Pattern.compile("git-Bukkit-(?:(?:[0-9]+)\\.)+[0-9]+-R[0-9]+-(?:[0-9]+-g[0-9a-f]+-)?b([0-9]+)jnks.*").matcher(getServer().getVersion());
if (versionMatch.matches())
{
final int versionNumber = Integer.parseInt(versionMatch.group(1));
if (versionNumber < BUKKIT_VERSION && versionNumber > 100)
{
LOGGER.log(Level.SEVERE, _("notRecommendedBukkit"));
LOGGER.log(Level.SEVERE, _("requiredBukkit", Integer.toString(BUKKIT_VERSION)));
this.setEnabled(false);
return;
}
}
else
{
LOGGER.log(Level.INFO, _("bukkitFormatChanged"));
LOGGER.log(Level.INFO, getServer().getVersion());
LOGGER.log(Level.INFO, getServer().getBukkitVersion());
}
execTimer.mark("BukkitCheck");
try
{
final EssentialsUpgrade upgrade = new EssentialsUpgrade(this);
upgrade.beforeSettings();
execTimer.mark("Upgrade");
confList = new ArrayList<IConf>();
settings = new Settings(this);
confList.add(settings);
execTimer.mark("Settings");
upgrade.afterSettings();
execTimer.mark("Upgrade2");
i18n.updateLocale(settings.getLocale());
userMap = new UserMap(this);
confList.add(userMap);
execTimer.mark("Init(Usermap)");
warps = new Warps(getServer(), this.getDataFolder());
confList.add(warps);
execTimer.mark("Init(Spawn/Warp)");
worth = new Worth(this.getDataFolder());
confList.add(worth);
itemDb = new ItemDb(this);
confList.add(itemDb);
execTimer.mark("Init(Worth/ItemDB)");
reload();
}
catch (YAMLException exception)
{
if (pm.getPlugin("EssentialsUpdate") != null)
{
LOGGER.log(Level.SEVERE, _("essentialsHelp2"));
}
else
{
LOGGER.log(Level.SEVERE, _("essentialsHelp1"));
}
LOGGER.log(Level.SEVERE, exception.toString());
pm.registerEvents(new Listener()
{
@EventHandler(priority = EventPriority.LOW)
public void onPlayerJoin(final PlayerJoinEvent event)
{
event.getPlayer().sendMessage("Essentials failed to load, read the log file.");
}
}, this);
for (Player player : getServer().getOnlinePlayers())
{
player.sendMessage("Essentials failed to load, read the log file.");
}
this.setEnabled(false);
return;
}
backup = new Backup(this);
permissionsHandler = new PermissionsHandler(this, settings.useBukkitPermissions());
alternativeCommandsHandler = new AlternativeCommandsHandler(this);
final EssentialsPluginListener serverListener = new EssentialsPluginListener(this);
pm.registerEvents(serverListener, this);
confList.add(serverListener);
final EssentialsPlayerListener playerListener = new EssentialsPlayerListener(this);
pm.registerEvents(playerListener, this);
final EssentialsBlockListener blockListener = new EssentialsBlockListener(this);
pm.registerEvents(blockListener, this);
final SignBlockListener signBlockListener = new SignBlockListener(this);
pm.registerEvents(signBlockListener, this);
final SignPlayerListener signPlayerListener = new SignPlayerListener(this);
pm.registerEvents(signPlayerListener, this);
final SignEntityListener signEntityListener = new SignEntityListener(this);
pm.registerEvents(signEntityListener, this);
final EssentialsEntityListener entityListener = new EssentialsEntityListener(this);
pm.registerEvents(entityListener, this);
final EssentialsWorldListener worldListener = new EssentialsWorldListener(this);
pm.registerEvents(worldListener, this);
//TODO: Check if this should be here, and not above before reload()
jails = new Jails(this);
confList.add(jails);
pm.registerEvents(tntListener, this);
final EssentialsTimer timer = new EssentialsTimer(this);
getScheduler().scheduleSyncRepeatingTask(this, timer, 1, 100);
Economy.setEss(this);
execTimer.mark("RegListeners");
final String timeroutput = execTimer.end();
if (getSettings().isDebug())
{
LOGGER.log(Level.INFO, "Essentials load " + timeroutput);
}
}
|
diff --git a/src/org/proofpad/Acl2Parser.java b/src/org/proofpad/Acl2Parser.java
index 75f7443..a9cf20e 100755
--- a/src/org/proofpad/Acl2Parser.java
+++ b/src/org/proofpad/Acl2Parser.java
@@ -1,759 +1,761 @@
package org.proofpad;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.util.Stack;
import java.util.logging.Logger;
import javax.swing.text.BadLocationException;
import org.fife.ui.rsyntaxtextarea.RSyntaxDocument;
import org.fife.ui.rsyntaxtextarea.Token;
import org.fife.ui.rsyntaxtextarea.parser.AbstractParser;
import org.fife.ui.rsyntaxtextarea.parser.DefaultParseResult;
import org.fife.ui.rsyntaxtextarea.parser.DefaultParserNotice;
import org.fife.ui.rsyntaxtextarea.parser.ParseResult;
import org.fife.ui.rsyntaxtextarea.parser.ParserNotice;
public class Acl2Parser extends AbstractParser {
public interface ParseListener {
void wasParsed();
}
private static Logger logger = Logger.getLogger(Acl2Parser.class.toString());
public static class CacheKey implements Serializable {
private static final long serialVersionUID = -4201796432147755450L;
private final File book;
private final long mtime;
public CacheKey(File book, long mtime) {
this.book = book;
this.mtime = mtime;
}
@Override
public int hashCode() {
return book.hashCode() ^ Long.valueOf(mtime).hashCode();
}
@Override
public boolean equals(Object other) {
return (other instanceof CacheKey &&
((CacheKey) other).book.equals(this.book) &&
((CacheKey) other).mtime == this.mtime);
}
}
private static class Range implements Serializable {
private static final long serialVersionUID = 3510110011135344206L;
public final int lower;
public final int upper;
Range(int lower, int upper) {
this.lower = lower;
this.upper = upper;
}
}
static class CacheSets implements Serializable {
private static final long serialVersionUID = -2233827686979689741L;
public Set<String> functions;
public Set<String> macros;
public Set<String> constants;
}
public Set<String> functions;
public Set<String> macros;
public Set<String> constants;
public File workingDir;
private Map<CacheKey, CacheSets> cache = Main.cache.getBookCache();
private File acl2Dir;
private final List<ParseListener> parseListeners = new LinkedList<Acl2Parser.ParseListener>();
private final Map<String, Acl2ParserNotice> funcNotices = new HashMap<String, Acl2Parser.Acl2ParserNotice>();
public Acl2Parser(File workingDir, File acl2Dir) {
this.workingDir = workingDir;
setAcl2Dir(acl2Dir);
}
private static Map<String, Range> paramCounts = new HashMap<String, Range>();
static {
paramCounts.put("-", new Range(1, 2));
paramCounts.put("/", new Range(1, 2));
paramCounts.put("/=", new Range(2, 2));
paramCounts.put("1+", new Range(1, 1));
paramCounts.put("1-", new Range(1, 1));
paramCounts.put("<=", new Range(2, 2));
paramCounts.put(">", new Range(2, 2));
paramCounts.put(">=", new Range(2, 2));
paramCounts.put("abs", new Range(1, 1));
paramCounts.put("acl2-numberp", new Range(1, 1));
paramCounts.put("acons", new Range(3, 3));
paramCounts.put("add-to-set-eq", new Range(2, 2));
paramCounts.put("add-to-set-eql", new Range(2, 2));
paramCounts.put("add-to-set-equal", new Range(2, 2));
paramCounts.put("alistp", new Range(1, 1));
paramCounts.put("alpha-char-p", new Range(1, 1));
paramCounts.put("alphorder", new Range(2, 2));
paramCounts.put("ash", new Range(2, 2));
paramCounts.put("assert$", new Range(2, 2));
paramCounts.put("assoc-eq", new Range(2, 2));
paramCounts.put("assoc-equal", new Range(2, 2));
paramCounts.put("assoc-keyword", new Range(2, 2));
paramCounts.put("atom", new Range(1, 1));
paramCounts.put("atom-listp", new Range(1, 1));
paramCounts.put("binary-*", new Range(2, 2));
paramCounts.put("binary-+", new Range(2, 2));
paramCounts.put("binary-append", new Range(2, 2));
paramCounts.put("boole$", new Range(3, 3));
paramCounts.put("booleanp", new Range(1, 1));
paramCounts.put("butlast", new Range(2, 2));
paramCounts.put("caaaar", new Range(1, 1));
paramCounts.put("caaadr", new Range(1, 1));
paramCounts.put("caaar", new Range(1, 1));
paramCounts.put("caadar", new Range(1, 1));
paramCounts.put("caaddr", new Range(1, 1));
paramCounts.put("caadr", new Range(1, 1));
paramCounts.put("caar", new Range(1, 1));
paramCounts.put("cadaar", new Range(1, 1));
paramCounts.put("cadadr", new Range(1, 1));
paramCounts.put("cadar", new Range(1, 1));
paramCounts.put("caddar", new Range(1, 1));
paramCounts.put("cadddr", new Range(1, 1));
paramCounts.put("caddr", new Range(1, 1));
paramCounts.put("cadr", new Range(1, 1));
paramCounts.put("car", new Range(1, 1));
paramCounts.put("cdaaar", new Range(1, 1));
paramCounts.put("cdaadr", new Range(1, 1));
paramCounts.put("cdaar", new Range(1, 1));
paramCounts.put("cdadar", new Range(1, 1));
paramCounts.put("cdaddr", new Range(1, 1));
paramCounts.put("cdadr", new Range(1, 1));
paramCounts.put("cdar", new Range(1, 1));
paramCounts.put("cddaar", new Range(1, 1));
paramCounts.put("cddadr", new Range(1, 1));
paramCounts.put("cddar", new Range(1, 1));
paramCounts.put("cdddar", new Range(1, 1));
paramCounts.put("cddddr", new Range(1, 1));
paramCounts.put("cdddr", new Range(1, 1));
paramCounts.put("cddr", new Range(1, 1));
paramCounts.put("cdr", new Range(1, 1));
paramCounts.put("ceiling", new Range(2, 2));
paramCounts.put("char", new Range(2, 2));
paramCounts.put("char-code", new Range(1, 1));
paramCounts.put("char-downcase", new Range(1, 1));
paramCounts.put("char-equal", new Range(2, 2));
paramCounts.put("char-upcase", new Range(1, 1));
paramCounts.put("char<", new Range(2, 2));
paramCounts.put("char<=", new Range(2, 2));
paramCounts.put("char>", new Range(2, 2));
paramCounts.put("char>=", new Range(2, 2));
paramCounts.put("character-alistp", new Range(1, 1));
paramCounts.put("character-listp", new Range(1, 1));
paramCounts.put("characterp", new Range(1, 1));
paramCounts.put("code-char", new Range(1, 1));
paramCounts.put("coerce", new Range(2, 2));
paramCounts.put("comp", new Range(1, 1));
paramCounts.put("comp-gcl", new Range(1, 1));
paramCounts.put("complex", new Range(2, 2));
paramCounts.put("complex-rationalp", new Range(1, 1));
paramCounts.put("complex/complex-rationalp", new Range(1, 1));
paramCounts.put("conjugate", new Range(1, 1));
paramCounts.put("cons", new Range(2, 2));
paramCounts.put("consp", new Range(1, 1));
paramCounts.put("cpu-core-count", new Range(1, 1));
paramCounts.put("delete-assoc-eq", new Range(2, 2));
paramCounts.put("denominator", new Range(1, 1));
paramCounts.put("digit-char-p", new Range(1, 2));
paramCounts.put("digit-to-char", new Range(1, 1));
paramCounts.put("ec-call", new Range(1, 1));
paramCounts.put("eighth", new Range(1, 1));
paramCounts.put("endp", new Range(1, 1));
paramCounts.put("eq", new Range(2, 2));
paramCounts.put("eql", new Range(2, 2));
paramCounts.put("eqlable-alistp", new Range(1, 1));
paramCounts.put("eqlable-listp", new Range(1, 1));
paramCounts.put("eqlablep", new Range(1, 1));
paramCounts.put("equal", new Range(2, 2));
paramCounts.put("error1", new Range(4, 4));
paramCounts.put("evenp", new Range(1, 1));
paramCounts.put("explode-nonnegative-integer", new Range(3, 5));
paramCounts.put("expt", new Range(2, 2));
paramCounts.put("fifth", new Range(1, 1));
paramCounts.put("first", new Range(1, 1));
paramCounts.put("fix", new Range(1, 1));
paramCounts.put("fix-true-list", new Range(1, 1));
paramCounts.put("floor", new Range(2, 2));
paramCounts.put("fms", new Range(5, 5));
paramCounts.put("fms!", new Range(5, 5));
paramCounts.put("fmt", new Range(5, 5));
paramCounts.put("fmt!", new Range(5, 5));
paramCounts.put("fmt1", new Range(6, 6));
paramCounts.put("fmt1!", new Range(6, 6));
paramCounts.put("fourth", new Range(1, 1));
paramCounts.put("get-output-stream-string$", new Range(2, 4));
paramCounts.put("getenv$", new Range(2, 2));
paramCounts.put("getprop", new Range(5, 5));
paramCounts.put("good-atom-listp", new Range(1, 1));
paramCounts.put("hard-error", new Range(3, 3));
paramCounts.put("identity", new Range(1, 1));
paramCounts.put("if", new Range(3, 3));
paramCounts.put("iff", new Range(2, 2));
paramCounts.put("ifix", new Range(1, 1));
paramCounts.put("illegal", new Range(3, 3));
paramCounts.put("imagpart", new Range(1, 1));
paramCounts.put("implies", new Range(2, 2));
paramCounts.put("improper-consp", new Range(1, 1));
paramCounts.put("int=", new Range(2, 2));
paramCounts.put("integer-length", new Range(1, 1));
paramCounts.put("integer-listp", new Range(1, 1));
paramCounts.put("integerp", new Range(1, 1));
paramCounts.put("intern", new Range(2, 2));
paramCounts.put("intern$", new Range(2, 2));
paramCounts.put("intern-in-package-of-symbol", new Range(2, 5));
paramCounts.put("intersectp-eq", new Range(2, 2));
paramCounts.put("intersectp-equal", new Range(2, 2));
paramCounts.put("keywordp", new Range(1, 1));
paramCounts.put("kwote", new Range(1, 1));
paramCounts.put("kwote-lst", new Range(1, 1));
paramCounts.put("last", new Range(1, 1));
paramCounts.put("len", new Range(1, 1));
paramCounts.put("length", new Range(1, 1));
paramCounts.put("lexorder", new Range(2, 2));
paramCounts.put("listp", new Range(1, 1));
paramCounts.put("logandc1", new Range(2, 2));
paramCounts.put("logandc2", new Range(2, 2));
paramCounts.put("logbitp", new Range(2, 2));
paramCounts.put("logcount", new Range(1, 1));
paramCounts.put("lognand", new Range(2, 2));
paramCounts.put("lognor", new Range(2, 2));
paramCounts.put("lognot", new Range(1, 1));
paramCounts.put("logorc1", new Range(2, 2));
paramCounts.put("logorc2", new Range(2, 2));
paramCounts.put("logtest", new Range(2, 2));
paramCounts.put("lower-case-p", new Range(1, 1));
paramCounts.put("make-ord", new Range(3, 3));
paramCounts.put("max", new Range(2, 2));
paramCounts.put("mbe1", new Range(2, 2));
paramCounts.put("mbt", new Range(1, 1));
paramCounts.put("member-eq", new Range(2, 2));
paramCounts.put("member-equal", new Range(2, 2));
paramCounts.put("min", new Range(2, 2));
paramCounts.put("minusp", new Range(1, 1));
paramCounts.put("mod", new Range(2, 2));
paramCounts.put("mod-expt", new Range(3, 3));
paramCounts.put("must-be-equal", new Range(2, 2));
paramCounts.put("mv-list", new Range(2, 2));
paramCounts.put("mv-nth", new Range(2, 2));
paramCounts.put("natp", new Range(1, 1));
paramCounts.put("nfix", new Range(1, 1));
paramCounts.put("ninth", new Range(1, 1));
paramCounts.put("no-duplicatesp-eq", new Range(1, 1));
paramCounts.put("nonnegative-integer-quotient", new Range(2, 4));
paramCounts.put("not", new Range(1, 1));
paramCounts.put("nth", new Range(2, 2));
paramCounts.put("nthcdr", new Range(2, 2));
paramCounts.put("null", new Range(1, 1));
paramCounts.put("numerator", new Range(1, 1));
paramCounts.put("o-finp", new Range(1, 1));
paramCounts.put("o-first-coeff", new Range(1, 1));
paramCounts.put("o-first-expt", new Range(1, 1));
paramCounts.put("o-infp", new Range(1, 1));
paramCounts.put("o-p", new Range(1, 1));
paramCounts.put("o-rst", new Range(1, 1));
paramCounts.put("o<", new Range(2, 2));
paramCounts.put("o<=", new Range(2, 2));
paramCounts.put("o>", new Range(2, 2));
paramCounts.put("o>=", new Range(2, 2));
paramCounts.put("oddp", new Range(1, 1));
paramCounts.put("pairlis$", new Range(2, 2));
paramCounts.put("peek-char$", new Range(2, 2));
paramCounts.put("pkg-imports", new Range(1, 1));
paramCounts.put("pkg-witness", new Range(1, 1));
paramCounts.put("plusp", new Range(1, 1));
paramCounts.put("position-eq", new Range(2, 2));
paramCounts.put("position-equal", new Range(2, 2));
paramCounts.put("posp", new Range(1, 1));
paramCounts.put("print-object$", new Range(3, 3));
paramCounts.put("prog2$", new Range(2, 2));
paramCounts.put("proofs-co", new Range(1, 1));
paramCounts.put("proper-consp", new Range(1, 1));
paramCounts.put("put-assoc-eq", new Range(3, 3));
paramCounts.put("put-assoc-eql", new Range(3, 3));
paramCounts.put("put-assoc-equal", new Range(3, 3));
paramCounts.put("putprop", new Range(4, 4));
paramCounts.put("r-eqlable-alistp", new Range(1, 1));
paramCounts.put("r-symbol-alistp", new Range(1, 1));
paramCounts.put("random$", new Range(2, 2));
paramCounts.put("rassoc-eq", new Range(2, 2));
paramCounts.put("rassoc-equal", new Range(2, 2));
paramCounts.put("rational-listp", new Range(1, 1));
paramCounts.put("rationalp", new Range(1, 1));
paramCounts.put("read-byte$", new Range(2, 2));
paramCounts.put("read-char$", new Range(2, 2));
paramCounts.put("read-object", new Range(2, 2));
paramCounts.put("real/rationalp", new Range(1, 1));
paramCounts.put("realfix", new Range(1, 1));
paramCounts.put("realpart", new Range(1, 1));
paramCounts.put("rem", new Range(2, 2));
paramCounts.put("remove-duplicates-eq", new Range(1, 1));
paramCounts.put("remove-duplicates-equal", new Range(1, 6));
paramCounts.put("remove-eq", new Range(2, 2));
paramCounts.put("remove-equal", new Range(2, 2));
paramCounts.put("remove1-eq", new Range(2, 2));
paramCounts.put("remove1-equal", new Range(2, 2));
paramCounts.put("rest", new Range(1, 1));
paramCounts.put("return-last", new Range(3, 3));
paramCounts.put("revappend", new Range(2, 2));
paramCounts.put("reverse", new Range(1, 1));
paramCounts.put("rfix", new Range(1, 1));
paramCounts.put("round", new Range(2, 2));
paramCounts.put("second", new Range(1, 1));
paramCounts.put("set-difference-eq", new Range(2, 2));
paramCounts.put("setenv$", new Range(2, 2));
paramCounts.put("seventh", new Range(1, 1));
paramCounts.put("signum", new Range(1, 1));
paramCounts.put("sixth", new Range(1, 1));
paramCounts.put("standard-char-p", new Range(1, 1));
paramCounts.put("string", new Range(1, 1));
paramCounts.put("string-append", new Range(2, 2));
paramCounts.put("string-downcase", new Range(1, 1));
paramCounts.put("string-equal", new Range(2, 2));
paramCounts.put("string-listp", new Range(1, 1));
paramCounts.put("string-upcase", new Range(1, 1));
paramCounts.put("string<", new Range(2, 2));
paramCounts.put("string<=", new Range(2, 2));
paramCounts.put("string>", new Range(2, 2));
paramCounts.put("string>=", new Range(2, 2));
paramCounts.put("stringp", new Range(1, 1));
paramCounts.put("strip-cars", new Range(1, 1));
paramCounts.put("strip-cdrs", new Range(1, 1));
paramCounts.put("sublis", new Range(2, 2));
paramCounts.put("subseq", new Range(3, 3));
paramCounts.put("subsetp-eq", new Range(2, 2));
paramCounts.put("subsetp-equal", new Range(2, 2));
paramCounts.put("subst", new Range(3, 3));
paramCounts.put("substitute", new Range(3, 3));
paramCounts.put("symbol-<", new Range(2, 2));
paramCounts.put("symbol-alistp", new Range(1, 1));
paramCounts.put("symbol-listp", new Range(1, 1));
paramCounts.put("symbol-name", new Range(1, 1));
paramCounts.put("symbolp", new Range(1, 1));
paramCounts.put("sys-call-status", new Range(1, 1));
paramCounts.put("take", new Range(2, 2));
paramCounts.put("tenth", new Range(1, 1));
paramCounts.put("the", new Range(2, 2));
paramCounts.put("third", new Range(1, 1));
paramCounts.put("true-list-listp", new Range(1, 1));
paramCounts.put("true-listp", new Range(1, 1));
paramCounts.put("truncate", new Range(2, 2));
paramCounts.put("unary--", new Range(1, 1));
paramCounts.put("unary-/", new Range(1, 1));
paramCounts.put("union-equal", new Range(2, 2));
paramCounts.put("update-nth", new Range(3, 3));
paramCounts.put("upper-case-p", new Range(1, 1));
paramCounts.put("with-live-state", new Range(1, 1));
paramCounts.put("write-byte$", new Range(3, 3));
paramCounts.put("xor", new Range(2, 2));
paramCounts.put("zerop", new Range(1, 1));
paramCounts.put("zip", new Range(1, 1));
paramCounts.put("zp", new Range(1, 1));
paramCounts.put("zpf", new Range(1, 1));
paramCounts.put("comp", new Range(1, 1));
paramCounts.put("defconst", new Range(2, 3));
paramCounts.put("defdoc", new Range(2, 2));
paramCounts.put("defpkg", new Range(2, 5));
paramCounts.put("defproxy", new Range(4, 4));
paramCounts.put("local", new Range(1, 1));
paramCounts.put("remove-custom-keyword-hint", new Range(1, 1));
paramCounts.put("set-body", new Range(2, 2));
paramCounts.put("show-custom-keyword-hint-expansion", new Range(1, 1));
paramCounts.put("table", new Range(1, 5));
paramCounts.put("unmemoize", new Range(1, 1));
paramCounts.put("add-binop", new Range(2, 2));
paramCounts.put("add-dive-into-macro", new Range(2, 2));
paramCounts.put("add-include-book-dir", new Range(2, 2));
paramCounts.put("add-macro-alias", new Range(2, 2));
paramCounts.put("add-nth-alias", new Range(2, 2));
paramCounts.put("binop-table", new Range(1, 1));
paramCounts.put("delete-include-book-dir", new Range(1, 1));
paramCounts.put("remove-binop", new Range(1, 1));
paramCounts.put("remove-default-hints", new Range(1, 1));
paramCounts.put("remove-default-hints!", new Range(1, 1));
paramCounts.put("remove-dive-into-macro", new Range(1, 1));
paramCounts.put("remove-macro-alias", new Range(1, 1));
paramCounts.put("remove-nth-alias", new Range(1, 1));
paramCounts.put("remove-override-hints", new Range(1, 1));
paramCounts.put("remove-override-hints!", new Range(1, 1));
paramCounts.put("set-backchain-limit", new Range(1, 1));
paramCounts.put("set-bogus-defun-hints-ok", new Range(1, 1));
paramCounts.put("set-bogus-mutual-recursion-ok", new Range(1, 1));
paramCounts.put("set-case-split-limitations", new Range(1, 1));
paramCounts.put("set-checkpoint-summary-limit", new Range(1, 1));
paramCounts.put("set-compile-fns", new Range(1, 1));
paramCounts.put("set-debugger-enable", new Range(1, 1));
paramCounts.put("set-default-backchain-limit", new Range(1, 1));
paramCounts.put("set-default-hints", new Range(1, 1));
paramCounts.put("set-default-hints!", new Range(1, 1));
paramCounts.put("set-deferred-ttag-notes", new Range(2, 6));
paramCounts.put("set-enforce-redundancy", new Range(1, 1));
paramCounts.put("set-gag-mode", new Range(1, 1));
paramCounts.put("set-guard-checking", new Range(1, 1));
paramCounts.put("set-ignore-doc-string-error", new Range(1, 1));
paramCounts.put("set-ignore-ok", new Range(1, 1));
paramCounts.put("set-inhibit-output-lst", new Range(1, 1));
paramCounts.put("set-inhibited-summary-types", new Range(1, 1));
paramCounts.put("set-invisible-fns-table", new Range(1, 1));
paramCounts.put("set-irrelevant-formals-ok", new Range(1, 1));
paramCounts.put("set-ld-keyword-aliases", new Range(2, 6));
paramCounts.put("set-ld-redefinition-action", new Range(2, 5));
paramCounts.put("set-ld-skip-proofs", new Range(2, 2));
paramCounts.put("set-let*-abstraction", new Range(1, 1));
paramCounts.put("set-let*-abstractionp", new Range(1, 1));
paramCounts.put("set-match-free-default", new Range(1, 1));
paramCounts.put("set-match-free-error", new Range(1, 1));
paramCounts.put("set-measure-function", new Range(1, 1));
paramCounts.put("set-non-linear", new Range(1, 1));
paramCounts.put("set-non-linearp", new Range(1, 1));
paramCounts.put("set-nu-rewriter-mode", new Range(1, 1));
paramCounts.put("set-override-hints", new Range(1, 1));
paramCounts.put("set-override-hints!", new Range(1, 1));
paramCounts.put("set-print-clause-ids", new Range(1, 1));
paramCounts.put("set-prover-step-limit", new Range(1, 1));
paramCounts.put("set-raw-mode", new Range(1, 1));
paramCounts.put("set-raw-proof-format", new Range(1, 1));
paramCounts.put("set-rewrite-stack-limit", new Range(1, 1));
paramCounts.put("set-ruler-extenders", new Range(1, 1));
paramCounts.put("set-rw-cache-state", new Range(1, 1));
paramCounts.put("set-rw-cache-state!", new Range(1, 1));
paramCounts.put("set-saved-output", new Range(2, 2));
paramCounts.put("set-state-ok", new Range(1, 1));
paramCounts.put("set-tainted-ok", new Range(1, 1));
paramCounts.put("set-tainted-okp", new Range(1, 1));
paramCounts.put("set-verify-guards-eagerness", new Range(1, 1));
paramCounts.put("set-waterfall-parallelism", new Range(1, 2));
paramCounts.put("set-waterfall-printing", new Range(1, 1));
paramCounts.put("set-well-founded-relation", new Range(1, 1));
paramCounts.put("set-write-acl2x", new Range(2, 2));
paramCounts.put("with-guard-checking", new Range(2, 2));
}
public class ParseToken {
public int offset;
public int line;
public String name;
public List<String> params = new ArrayList<String>();
public Set<String> vars = new HashSet<String>();
}
public class Acl2ParserNotice extends DefaultParserNotice {
public String funcName;
public Acl2ParserNotice(Acl2Parser parser, String msg, int line, int offs, int len, int level) {
super(parser, msg, line, offs, len);
//System.out.println("ERROR on line " + line + ": " + msg);
setLevel(level);
}
public Acl2ParserNotice(Acl2Parser parser, String msg,
ParseToken top, int end) {
this(parser, msg, top.line, top.offset, end - top.offset, ERROR);
}
public Acl2ParserNotice(Acl2Parser parser, String msg, int line,
Token token, int level) {
this(parser, msg, line, token.offset, token.textCount, level);
}
@Override
public boolean getShowInEditor() {
return getLevel() != INFO;
}
}
@Override
public ParseResult parse(RSyntaxDocument doc, String style /* ignored */) {
DefaultParseResult result = new DefaultParseResult(this);
int lines = doc.getDefaultRootElement().getElementCount();
result.setParsedLines(0, lines);
if (!Prefs.showErrors.get()) {
for (ParseListener pl : parseListeners) {
pl.wasParsed();
}
return result;
}
functions = new HashSet<String>();
macros = new HashSet<String>(Arrays.asList(new String [] {
"declare", "include-book", "defttag"
}));
constants = new HashSet<String>();
constants.add("state");
Stack<ParseToken> s = new Stack<ParseToken>();
Token token;
for (int line = 0; line < lines; line++) {
token = doc.getTokenListForLine(line);
while (token != null && token.isPaintable()) {
ParseToken top = (s.empty() ? null : s.peek());
String tokenName = token.getLexeme().toLowerCase();
if (top != null && top.name != null && !token.isWhitespace() &&
!token.isComment() && !token.isSingleChar(')') &&
!token.isSingleChar('`') && !token.isSingleChar(',') &&
!token.isSingleChar('\'')) {
// In a parameter position.
top.params.add(token.getLexeme());
if (top.name.equals("defun") && top.params.size() == 1) {
if (!macros.contains(tokenName) && !functions.contains(tokenName)) {
functions.add(tokenName);
if (funcNotices.containsKey(tokenName)) {
Acl2ParserNotice notice = funcNotices.get(tokenName);
notice.setToolTipText(String.format(
"<html>The function <b>%s</b> is defined below. Move the " +
"definition above this call.</html>",
htmlEncode(notice.funcName)));
}
} else {
result.addNotice(new Acl2ParserNotice(this,
"A function with this name is already defined", line, token,
ParserNotice.ERROR));
}
} else if ((top.name.equals("defmacro") || top.name.equals("defabbrev")) &&
top.params.size() == 1) {
if (!functions.contains(tokenName) && !macros.contains(tokenName)) {
macros.add(tokenName);
} else {
result.addNotice(new Acl2ParserNotice(this,
"A function with this name is already defined", line, token,
ParserNotice.ERROR));
}
} else if (top.name.equals("defconst") && top.params.size() == 1) {
if (!tokenName.startsWith("*") || !tokenName.endsWith("*")) {
Main.userData.addParseError("constNames");
result.addNotice(new Acl2ParserNotice(this,
"Constant names must begin and end with *.", line, token,
ParserNotice.ERROR));
} else {
if (!constants.contains(tokenName)) {
constants.add(tokenName);
} else {
result.addNotice(new Acl2ParserNotice(this,
"A constant with this name is already defined", line, token,
ParserNotice.ERROR));
}
}
}
}
ParseToken parent = s.size() <= 1 ? null : s.get(s.size() - 2);
ParseToken grandparent = s.size() <= 2 ? null : s.get(s.size() - 3);
boolean isVariableOfParent = parent != null && parent.name != null &&
(parent.name.equals("defun") && parent.params.size() == 2 ||
parent.name.equals("mv-let") && parent.params.size() == 1);
boolean isVariableOfGrandparent = (grandparent != null && grandparent.name != null &&
((grandparent.name.equals("let") || grandparent.name.equals("let*")) &&
grandparent.params.size() == 1 && top != null && top.params.size() == 0));
if (isVariableOfParent || isVariableOfGrandparent) {
if (token.type == Token.IDENTIFIER) {
if (parent != null && isVariableOfParent) {
parent.vars.add(token.getLexeme());
} else if (grandparent != null && isVariableOfGrandparent) {
grandparent.vars.add(token.getLexeme());
}
} else if (token.type != Token.WHITESPACE && !token.isSingleChar(')')) {
Main.userData.addParseError("expectedVariableName");
result.addNotice(new Acl2ParserNotice(this, "Expected a variable name",
line, token, ParserNotice.ERROR));
}
}
boolean isIgnoredBecauseMacro = false;
boolean isThm = false;
Set<String> vars = new HashSet<String>();
for (ParseToken ancestor : s) {
isIgnoredBecauseMacro |= macros.contains(ancestor.name);
vars.addAll(ancestor.vars);
isThm |= ancestor.name != null && (ancestor.name.equals("thm") ||
ancestor.name.equals("defthm") || ancestor.name.equals("defthmd"));
}
boolean isIgnoredBecauseParent = parent != null && parent.name != null &&
(parent.name.equals("defun") && parent.params.size() == 2 ||
parent.name.equals("defmacro") && parent.params.size() == 2 ||
+ parent.name.equals("defabbrev") && parent.params.size() == 2 ||
parent.name.equals("mv-let") && parent.params.size() == 1 ||
parent.name.equals("cond") /* any parameter */ ||
parent.name.equals("case") /* any parameter */);
boolean isIgnoredBecauseCurrent = top != null && top.name != null &&
(top.name.equals("defun") && top.params.size() == 1 ||
top.name.equals("defmacro") && top.params.size() == 1 ||
+ top.name.equals("defabbrev") && top.params.size() == 1 ||
top.name.equals("assign") && top.params.size() == 1 ||
top.name.equals("@") && top.params.size() == 1);
boolean isIgnored = isIgnoredBecauseMacro || isIgnoredBecauseParent || isIgnoredBecauseCurrent ||
(top != null && grandparent != null && grandparent.name != null &&
(grandparent.name.equals("let") && grandparent.params.size() == 1 && top.params.size() == 0 ||
grandparent.name.equals("let*") && grandparent.params.size() == 1 && top.params.size() == 0));
if (token.isSingleChar('(')) {
if (top != null && top.name == null) top.name = "";
s.push(new ParseToken());
s.peek().line = line;
s.peek().offset = token.offset;
} else if (token.isSingleChar(')')) {
if (top == null) {
Main.userData.addParseError("UnmatchedCloseParen");
result.addNotice(new Acl2ParserNotice(this, "Unmatched )", line, token.offset, 1,
ParserNotice.ERROR));
} else {
Range range = paramCounts.get(top.name);
if (range != null && (top.params.size() < range.lower || top.params.size() > range.upper)) {
String msg;
if (range.lower == range.upper) {
msg = "<html><b>" + htmlEncode(top.name) + "</b> expects "
+ range.lower + " parameter" +
(range.lower == 1 ? "" : "s") + ".</html>";
} else {
msg = "<html><b>" + htmlEncode(top.name) + "</b> expects between "
+ range.lower + " and " + range.upper + " parameters.</html>";
}
Main.userData.addParseError("numOfParams");
result.addNotice(new Acl2ParserNotice(this, msg, top, token.offset + 1));
}
s.pop();
if (top.name != null && top.name.equals("include-book")) {
String bookName = top.params.get(0);
int dirLoc = top.params.indexOf(":dir") + 1;
File dir;
String dirKey = "";
if (dirLoc == 0) {
dir = workingDir;
} else {
dirKey = top.params.get(dirLoc);
if (dirKey.equals(":system")) {
dir = new File(getAcl2Dir(), "books");
} else if (dirKey.equals(":teachpacks")) {
dir = new File(getAcl2Dir(), "dracula");
} else {
Main.userData.addParseError("UnrecongizedBookLocation");
result.addNotice(new Acl2ParserNotice(this,
"Unrecognized book location: " + dirKey, top,
token.offset + 1));
dir = null;
}
}
if (Main.WIN) {
bookName.replaceAll("\\\\/", "\\");
}
File book = new File(dir, bookName.substring(1, bookName.length() - 1) + ".lisp");
CacheSets bookCache = null;
long mtime = book.lastModified();
if (dirKey.equals(":system")) {
mtime = Long.MAX_VALUE;
}
CacheKey key = new CacheKey(book, mtime);
if (cache.containsKey(key)) {
bookCache = cache.get(key);
} else {
try {
System.out.println("Book exists? " + book);
bookCache = parseBook(book, getAcl2Dir(), cache);
cache.put(key, bookCache);
} catch (FileNotFoundException e) {
Main.userData.addParseError("BookNotFound");
result.addNotice(new Acl2ParserNotice(this,
"File could not be found.", top, token.offset + 1));
} catch (BadLocationException e) { }
}
if (bookCache != null) {
functions.addAll(bookCache.functions);
macros.addAll(bookCache.macros);
constants.addAll(bookCache.constants);
}
}
}
} else if (top != null && top.name == null &&
!token.isComment() &&
!token.isWhitespace()) {
// This token is at the beginning of an s expression
top.name = token.getLexeme().toLowerCase();
if (token.type != Token.RESERVED_WORD &&
token.type != Token.RESERVED_WORD_2 &&
!functions.contains(top.name) &&
!macros.contains(top.name) &&
!isIgnored) {
Main.userData.addParseError("undefinedCallable");
Acl2ParserNotice undefinedFuncNotice = new Acl2ParserNotice(this,
String.format("<html>The function <b>%s</b> is undefined.</html>",
htmlEncode(top.name)), line, token, ParserNotice.ERROR);
undefinedFuncNotice.funcName = top.name;
funcNotices.put(top.name, undefinedFuncNotice);
result.addNotice(undefinedFuncNotice);
}
if (token.type == Token.RESERVED_WORD ||
token.type == Token.RESERVED_WORD_2) {
// TODO: Make these more noticeable?
Map<String, String> docs = Main.cache.getDocs();
String upperToken = token.getLexeme().toUpperCase();
if (docs.containsKey(upperToken)) {
String modKey = Main.OSX ? "\u2325\u2318" : "Ctrl + Alt + ";
String msg = "<html>" + docs.get(upperToken) + "<br><font " +
"color=\"gray\" size=\"2\">" + modKey +
"L for more.</font></html>";
result.addNotice(new Acl2ParserNotice(this,
msg, line, token, ParserNotice.INFO));
}
}
} else if (!isThm && !isIgnored && (token.type == Token.IDENTIFIER ||
token.type == Token.RESERVED_WORD || token.type == Token.RESERVED_WORD_2)
&& !constants.contains(token.getLexeme()) &&
!vars.contains(token.getLexeme())) {
Main.userData.addParseError("undeclaredVariable");
result.addNotice(new Acl2ParserNotice(this, token.getLexeme() +
" is undeclared.",
line, token, ParserNotice.ERROR));
}
token = token.getNextToken();
}
}
for (ParseListener pl : parseListeners) {
pl.wasParsed();
}
return result;
}
public static CacheSets parseBook(File book, File acl2Dir, Map<CacheKey, CacheSets> cache)
throws FileNotFoundException, BadLocationException {
CacheSets bookCache;
Scanner bookScanner = new Scanner(book);
bookScanner.useDelimiter("\\Z");
String bookContents = bookScanner.next();
bookScanner.close();
logger.info("PARSING: " + book);
book.lastModified();
Acl2Parser bookParser = new Acl2Parser(book.getParentFile(), acl2Dir);
bookParser.cache = cache;
RSyntaxDocument bookDoc = new PPDocument();
bookDoc.insertString(0, bookContents, null);
bookParser.parse(bookDoc, null);
bookCache = new CacheSets();
bookCache.functions = bookParser.functions;
bookCache.constants = bookParser.constants;
bookCache.macros = bookParser.macros;
return bookCache;
}
private static String htmlEncode(String name) {
return name.replace("&", "&").replace("<", "<").replace(">", ">");
}
public void addParseListener(ParseListener parseListener) {
parseListeners.add(parseListener);
}
public File getAcl2Dir() {
return acl2Dir;
}
public void setAcl2Dir(File acl2Dir) {
this.acl2Dir = acl2Dir;
}
}
| false | true | public ParseResult parse(RSyntaxDocument doc, String style /* ignored */) {
DefaultParseResult result = new DefaultParseResult(this);
int lines = doc.getDefaultRootElement().getElementCount();
result.setParsedLines(0, lines);
if (!Prefs.showErrors.get()) {
for (ParseListener pl : parseListeners) {
pl.wasParsed();
}
return result;
}
functions = new HashSet<String>();
macros = new HashSet<String>(Arrays.asList(new String [] {
"declare", "include-book", "defttag"
}));
constants = new HashSet<String>();
constants.add("state");
Stack<ParseToken> s = new Stack<ParseToken>();
Token token;
for (int line = 0; line < lines; line++) {
token = doc.getTokenListForLine(line);
while (token != null && token.isPaintable()) {
ParseToken top = (s.empty() ? null : s.peek());
String tokenName = token.getLexeme().toLowerCase();
if (top != null && top.name != null && !token.isWhitespace() &&
!token.isComment() && !token.isSingleChar(')') &&
!token.isSingleChar('`') && !token.isSingleChar(',') &&
!token.isSingleChar('\'')) {
// In a parameter position.
top.params.add(token.getLexeme());
if (top.name.equals("defun") && top.params.size() == 1) {
if (!macros.contains(tokenName) && !functions.contains(tokenName)) {
functions.add(tokenName);
if (funcNotices.containsKey(tokenName)) {
Acl2ParserNotice notice = funcNotices.get(tokenName);
notice.setToolTipText(String.format(
"<html>The function <b>%s</b> is defined below. Move the " +
"definition above this call.</html>",
htmlEncode(notice.funcName)));
}
} else {
result.addNotice(new Acl2ParserNotice(this,
"A function with this name is already defined", line, token,
ParserNotice.ERROR));
}
} else if ((top.name.equals("defmacro") || top.name.equals("defabbrev")) &&
top.params.size() == 1) {
if (!functions.contains(tokenName) && !macros.contains(tokenName)) {
macros.add(tokenName);
} else {
result.addNotice(new Acl2ParserNotice(this,
"A function with this name is already defined", line, token,
ParserNotice.ERROR));
}
} else if (top.name.equals("defconst") && top.params.size() == 1) {
if (!tokenName.startsWith("*") || !tokenName.endsWith("*")) {
Main.userData.addParseError("constNames");
result.addNotice(new Acl2ParserNotice(this,
"Constant names must begin and end with *.", line, token,
ParserNotice.ERROR));
} else {
if (!constants.contains(tokenName)) {
constants.add(tokenName);
} else {
result.addNotice(new Acl2ParserNotice(this,
"A constant with this name is already defined", line, token,
ParserNotice.ERROR));
}
}
}
}
ParseToken parent = s.size() <= 1 ? null : s.get(s.size() - 2);
ParseToken grandparent = s.size() <= 2 ? null : s.get(s.size() - 3);
boolean isVariableOfParent = parent != null && parent.name != null &&
(parent.name.equals("defun") && parent.params.size() == 2 ||
parent.name.equals("mv-let") && parent.params.size() == 1);
boolean isVariableOfGrandparent = (grandparent != null && grandparent.name != null &&
((grandparent.name.equals("let") || grandparent.name.equals("let*")) &&
grandparent.params.size() == 1 && top != null && top.params.size() == 0));
if (isVariableOfParent || isVariableOfGrandparent) {
if (token.type == Token.IDENTIFIER) {
if (parent != null && isVariableOfParent) {
parent.vars.add(token.getLexeme());
} else if (grandparent != null && isVariableOfGrandparent) {
grandparent.vars.add(token.getLexeme());
}
} else if (token.type != Token.WHITESPACE && !token.isSingleChar(')')) {
Main.userData.addParseError("expectedVariableName");
result.addNotice(new Acl2ParserNotice(this, "Expected a variable name",
line, token, ParserNotice.ERROR));
}
}
boolean isIgnoredBecauseMacro = false;
boolean isThm = false;
Set<String> vars = new HashSet<String>();
for (ParseToken ancestor : s) {
isIgnoredBecauseMacro |= macros.contains(ancestor.name);
vars.addAll(ancestor.vars);
isThm |= ancestor.name != null && (ancestor.name.equals("thm") ||
ancestor.name.equals("defthm") || ancestor.name.equals("defthmd"));
}
boolean isIgnoredBecauseParent = parent != null && parent.name != null &&
(parent.name.equals("defun") && parent.params.size() == 2 ||
parent.name.equals("defmacro") && parent.params.size() == 2 ||
parent.name.equals("mv-let") && parent.params.size() == 1 ||
parent.name.equals("cond") /* any parameter */ ||
parent.name.equals("case") /* any parameter */);
boolean isIgnoredBecauseCurrent = top != null && top.name != null &&
(top.name.equals("defun") && top.params.size() == 1 ||
top.name.equals("defmacro") && top.params.size() == 1 ||
top.name.equals("assign") && top.params.size() == 1 ||
top.name.equals("@") && top.params.size() == 1);
boolean isIgnored = isIgnoredBecauseMacro || isIgnoredBecauseParent || isIgnoredBecauseCurrent ||
(top != null && grandparent != null && grandparent.name != null &&
(grandparent.name.equals("let") && grandparent.params.size() == 1 && top.params.size() == 0 ||
grandparent.name.equals("let*") && grandparent.params.size() == 1 && top.params.size() == 0));
if (token.isSingleChar('(')) {
if (top != null && top.name == null) top.name = "";
s.push(new ParseToken());
s.peek().line = line;
s.peek().offset = token.offset;
} else if (token.isSingleChar(')')) {
if (top == null) {
Main.userData.addParseError("UnmatchedCloseParen");
result.addNotice(new Acl2ParserNotice(this, "Unmatched )", line, token.offset, 1,
ParserNotice.ERROR));
} else {
Range range = paramCounts.get(top.name);
if (range != null && (top.params.size() < range.lower || top.params.size() > range.upper)) {
String msg;
if (range.lower == range.upper) {
msg = "<html><b>" + htmlEncode(top.name) + "</b> expects "
+ range.lower + " parameter" +
(range.lower == 1 ? "" : "s") + ".</html>";
} else {
msg = "<html><b>" + htmlEncode(top.name) + "</b> expects between "
+ range.lower + " and " + range.upper + " parameters.</html>";
}
Main.userData.addParseError("numOfParams");
result.addNotice(new Acl2ParserNotice(this, msg, top, token.offset + 1));
}
s.pop();
if (top.name != null && top.name.equals("include-book")) {
String bookName = top.params.get(0);
int dirLoc = top.params.indexOf(":dir") + 1;
File dir;
String dirKey = "";
if (dirLoc == 0) {
dir = workingDir;
} else {
dirKey = top.params.get(dirLoc);
if (dirKey.equals(":system")) {
dir = new File(getAcl2Dir(), "books");
} else if (dirKey.equals(":teachpacks")) {
dir = new File(getAcl2Dir(), "dracula");
} else {
Main.userData.addParseError("UnrecongizedBookLocation");
result.addNotice(new Acl2ParserNotice(this,
"Unrecognized book location: " + dirKey, top,
token.offset + 1));
dir = null;
}
}
if (Main.WIN) {
bookName.replaceAll("\\\\/", "\\");
}
File book = new File(dir, bookName.substring(1, bookName.length() - 1) + ".lisp");
CacheSets bookCache = null;
long mtime = book.lastModified();
if (dirKey.equals(":system")) {
mtime = Long.MAX_VALUE;
}
CacheKey key = new CacheKey(book, mtime);
if (cache.containsKey(key)) {
bookCache = cache.get(key);
} else {
try {
System.out.println("Book exists? " + book);
bookCache = parseBook(book, getAcl2Dir(), cache);
cache.put(key, bookCache);
} catch (FileNotFoundException e) {
Main.userData.addParseError("BookNotFound");
result.addNotice(new Acl2ParserNotice(this,
"File could not be found.", top, token.offset + 1));
} catch (BadLocationException e) { }
}
if (bookCache != null) {
functions.addAll(bookCache.functions);
macros.addAll(bookCache.macros);
constants.addAll(bookCache.constants);
}
}
}
} else if (top != null && top.name == null &&
!token.isComment() &&
!token.isWhitespace()) {
// This token is at the beginning of an s expression
top.name = token.getLexeme().toLowerCase();
if (token.type != Token.RESERVED_WORD &&
token.type != Token.RESERVED_WORD_2 &&
!functions.contains(top.name) &&
!macros.contains(top.name) &&
!isIgnored) {
Main.userData.addParseError("undefinedCallable");
Acl2ParserNotice undefinedFuncNotice = new Acl2ParserNotice(this,
String.format("<html>The function <b>%s</b> is undefined.</html>",
htmlEncode(top.name)), line, token, ParserNotice.ERROR);
undefinedFuncNotice.funcName = top.name;
funcNotices.put(top.name, undefinedFuncNotice);
result.addNotice(undefinedFuncNotice);
}
if (token.type == Token.RESERVED_WORD ||
token.type == Token.RESERVED_WORD_2) {
// TODO: Make these more noticeable?
Map<String, String> docs = Main.cache.getDocs();
String upperToken = token.getLexeme().toUpperCase();
if (docs.containsKey(upperToken)) {
String modKey = Main.OSX ? "\u2325\u2318" : "Ctrl + Alt + ";
String msg = "<html>" + docs.get(upperToken) + "<br><font " +
"color=\"gray\" size=\"2\">" + modKey +
"L for more.</font></html>";
result.addNotice(new Acl2ParserNotice(this,
msg, line, token, ParserNotice.INFO));
}
}
} else if (!isThm && !isIgnored && (token.type == Token.IDENTIFIER ||
token.type == Token.RESERVED_WORD || token.type == Token.RESERVED_WORD_2)
&& !constants.contains(token.getLexeme()) &&
!vars.contains(token.getLexeme())) {
Main.userData.addParseError("undeclaredVariable");
result.addNotice(new Acl2ParserNotice(this, token.getLexeme() +
" is undeclared.",
line, token, ParserNotice.ERROR));
}
token = token.getNextToken();
}
}
for (ParseListener pl : parseListeners) {
pl.wasParsed();
}
return result;
}
| public ParseResult parse(RSyntaxDocument doc, String style /* ignored */) {
DefaultParseResult result = new DefaultParseResult(this);
int lines = doc.getDefaultRootElement().getElementCount();
result.setParsedLines(0, lines);
if (!Prefs.showErrors.get()) {
for (ParseListener pl : parseListeners) {
pl.wasParsed();
}
return result;
}
functions = new HashSet<String>();
macros = new HashSet<String>(Arrays.asList(new String [] {
"declare", "include-book", "defttag"
}));
constants = new HashSet<String>();
constants.add("state");
Stack<ParseToken> s = new Stack<ParseToken>();
Token token;
for (int line = 0; line < lines; line++) {
token = doc.getTokenListForLine(line);
while (token != null && token.isPaintable()) {
ParseToken top = (s.empty() ? null : s.peek());
String tokenName = token.getLexeme().toLowerCase();
if (top != null && top.name != null && !token.isWhitespace() &&
!token.isComment() && !token.isSingleChar(')') &&
!token.isSingleChar('`') && !token.isSingleChar(',') &&
!token.isSingleChar('\'')) {
// In a parameter position.
top.params.add(token.getLexeme());
if (top.name.equals("defun") && top.params.size() == 1) {
if (!macros.contains(tokenName) && !functions.contains(tokenName)) {
functions.add(tokenName);
if (funcNotices.containsKey(tokenName)) {
Acl2ParserNotice notice = funcNotices.get(tokenName);
notice.setToolTipText(String.format(
"<html>The function <b>%s</b> is defined below. Move the " +
"definition above this call.</html>",
htmlEncode(notice.funcName)));
}
} else {
result.addNotice(new Acl2ParserNotice(this,
"A function with this name is already defined", line, token,
ParserNotice.ERROR));
}
} else if ((top.name.equals("defmacro") || top.name.equals("defabbrev")) &&
top.params.size() == 1) {
if (!functions.contains(tokenName) && !macros.contains(tokenName)) {
macros.add(tokenName);
} else {
result.addNotice(new Acl2ParserNotice(this,
"A function with this name is already defined", line, token,
ParserNotice.ERROR));
}
} else if (top.name.equals("defconst") && top.params.size() == 1) {
if (!tokenName.startsWith("*") || !tokenName.endsWith("*")) {
Main.userData.addParseError("constNames");
result.addNotice(new Acl2ParserNotice(this,
"Constant names must begin and end with *.", line, token,
ParserNotice.ERROR));
} else {
if (!constants.contains(tokenName)) {
constants.add(tokenName);
} else {
result.addNotice(new Acl2ParserNotice(this,
"A constant with this name is already defined", line, token,
ParserNotice.ERROR));
}
}
}
}
ParseToken parent = s.size() <= 1 ? null : s.get(s.size() - 2);
ParseToken grandparent = s.size() <= 2 ? null : s.get(s.size() - 3);
boolean isVariableOfParent = parent != null && parent.name != null &&
(parent.name.equals("defun") && parent.params.size() == 2 ||
parent.name.equals("mv-let") && parent.params.size() == 1);
boolean isVariableOfGrandparent = (grandparent != null && grandparent.name != null &&
((grandparent.name.equals("let") || grandparent.name.equals("let*")) &&
grandparent.params.size() == 1 && top != null && top.params.size() == 0));
if (isVariableOfParent || isVariableOfGrandparent) {
if (token.type == Token.IDENTIFIER) {
if (parent != null && isVariableOfParent) {
parent.vars.add(token.getLexeme());
} else if (grandparent != null && isVariableOfGrandparent) {
grandparent.vars.add(token.getLexeme());
}
} else if (token.type != Token.WHITESPACE && !token.isSingleChar(')')) {
Main.userData.addParseError("expectedVariableName");
result.addNotice(new Acl2ParserNotice(this, "Expected a variable name",
line, token, ParserNotice.ERROR));
}
}
boolean isIgnoredBecauseMacro = false;
boolean isThm = false;
Set<String> vars = new HashSet<String>();
for (ParseToken ancestor : s) {
isIgnoredBecauseMacro |= macros.contains(ancestor.name);
vars.addAll(ancestor.vars);
isThm |= ancestor.name != null && (ancestor.name.equals("thm") ||
ancestor.name.equals("defthm") || ancestor.name.equals("defthmd"));
}
boolean isIgnoredBecauseParent = parent != null && parent.name != null &&
(parent.name.equals("defun") && parent.params.size() == 2 ||
parent.name.equals("defmacro") && parent.params.size() == 2 ||
parent.name.equals("defabbrev") && parent.params.size() == 2 ||
parent.name.equals("mv-let") && parent.params.size() == 1 ||
parent.name.equals("cond") /* any parameter */ ||
parent.name.equals("case") /* any parameter */);
boolean isIgnoredBecauseCurrent = top != null && top.name != null &&
(top.name.equals("defun") && top.params.size() == 1 ||
top.name.equals("defmacro") && top.params.size() == 1 ||
top.name.equals("defabbrev") && top.params.size() == 1 ||
top.name.equals("assign") && top.params.size() == 1 ||
top.name.equals("@") && top.params.size() == 1);
boolean isIgnored = isIgnoredBecauseMacro || isIgnoredBecauseParent || isIgnoredBecauseCurrent ||
(top != null && grandparent != null && grandparent.name != null &&
(grandparent.name.equals("let") && grandparent.params.size() == 1 && top.params.size() == 0 ||
grandparent.name.equals("let*") && grandparent.params.size() == 1 && top.params.size() == 0));
if (token.isSingleChar('(')) {
if (top != null && top.name == null) top.name = "";
s.push(new ParseToken());
s.peek().line = line;
s.peek().offset = token.offset;
} else if (token.isSingleChar(')')) {
if (top == null) {
Main.userData.addParseError("UnmatchedCloseParen");
result.addNotice(new Acl2ParserNotice(this, "Unmatched )", line, token.offset, 1,
ParserNotice.ERROR));
} else {
Range range = paramCounts.get(top.name);
if (range != null && (top.params.size() < range.lower || top.params.size() > range.upper)) {
String msg;
if (range.lower == range.upper) {
msg = "<html><b>" + htmlEncode(top.name) + "</b> expects "
+ range.lower + " parameter" +
(range.lower == 1 ? "" : "s") + ".</html>";
} else {
msg = "<html><b>" + htmlEncode(top.name) + "</b> expects between "
+ range.lower + " and " + range.upper + " parameters.</html>";
}
Main.userData.addParseError("numOfParams");
result.addNotice(new Acl2ParserNotice(this, msg, top, token.offset + 1));
}
s.pop();
if (top.name != null && top.name.equals("include-book")) {
String bookName = top.params.get(0);
int dirLoc = top.params.indexOf(":dir") + 1;
File dir;
String dirKey = "";
if (dirLoc == 0) {
dir = workingDir;
} else {
dirKey = top.params.get(dirLoc);
if (dirKey.equals(":system")) {
dir = new File(getAcl2Dir(), "books");
} else if (dirKey.equals(":teachpacks")) {
dir = new File(getAcl2Dir(), "dracula");
} else {
Main.userData.addParseError("UnrecongizedBookLocation");
result.addNotice(new Acl2ParserNotice(this,
"Unrecognized book location: " + dirKey, top,
token.offset + 1));
dir = null;
}
}
if (Main.WIN) {
bookName.replaceAll("\\\\/", "\\");
}
File book = new File(dir, bookName.substring(1, bookName.length() - 1) + ".lisp");
CacheSets bookCache = null;
long mtime = book.lastModified();
if (dirKey.equals(":system")) {
mtime = Long.MAX_VALUE;
}
CacheKey key = new CacheKey(book, mtime);
if (cache.containsKey(key)) {
bookCache = cache.get(key);
} else {
try {
System.out.println("Book exists? " + book);
bookCache = parseBook(book, getAcl2Dir(), cache);
cache.put(key, bookCache);
} catch (FileNotFoundException e) {
Main.userData.addParseError("BookNotFound");
result.addNotice(new Acl2ParserNotice(this,
"File could not be found.", top, token.offset + 1));
} catch (BadLocationException e) { }
}
if (bookCache != null) {
functions.addAll(bookCache.functions);
macros.addAll(bookCache.macros);
constants.addAll(bookCache.constants);
}
}
}
} else if (top != null && top.name == null &&
!token.isComment() &&
!token.isWhitespace()) {
// This token is at the beginning of an s expression
top.name = token.getLexeme().toLowerCase();
if (token.type != Token.RESERVED_WORD &&
token.type != Token.RESERVED_WORD_2 &&
!functions.contains(top.name) &&
!macros.contains(top.name) &&
!isIgnored) {
Main.userData.addParseError("undefinedCallable");
Acl2ParserNotice undefinedFuncNotice = new Acl2ParserNotice(this,
String.format("<html>The function <b>%s</b> is undefined.</html>",
htmlEncode(top.name)), line, token, ParserNotice.ERROR);
undefinedFuncNotice.funcName = top.name;
funcNotices.put(top.name, undefinedFuncNotice);
result.addNotice(undefinedFuncNotice);
}
if (token.type == Token.RESERVED_WORD ||
token.type == Token.RESERVED_WORD_2) {
// TODO: Make these more noticeable?
Map<String, String> docs = Main.cache.getDocs();
String upperToken = token.getLexeme().toUpperCase();
if (docs.containsKey(upperToken)) {
String modKey = Main.OSX ? "\u2325\u2318" : "Ctrl + Alt + ";
String msg = "<html>" + docs.get(upperToken) + "<br><font " +
"color=\"gray\" size=\"2\">" + modKey +
"L for more.</font></html>";
result.addNotice(new Acl2ParserNotice(this,
msg, line, token, ParserNotice.INFO));
}
}
} else if (!isThm && !isIgnored && (token.type == Token.IDENTIFIER ||
token.type == Token.RESERVED_WORD || token.type == Token.RESERVED_WORD_2)
&& !constants.contains(token.getLexeme()) &&
!vars.contains(token.getLexeme())) {
Main.userData.addParseError("undeclaredVariable");
result.addNotice(new Acl2ParserNotice(this, token.getLexeme() +
" is undeclared.",
line, token, ParserNotice.ERROR));
}
token = token.getNextToken();
}
}
for (ParseListener pl : parseListeners) {
pl.wasParsed();
}
return result;
}
|
diff --git a/src/main/java/org/bukkit/command/defaults/ScoreboardCommand.java b/src/main/java/org/bukkit/command/defaults/ScoreboardCommand.java
index 64816b62..0b2755a2 100644
--- a/src/main/java/org/bukkit/command/defaults/ScoreboardCommand.java
+++ b/src/main/java/org/bukkit/command/defaults/ScoreboardCommand.java
@@ -1,617 +1,617 @@
package org.bukkit.command.defaults;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.Validate;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.scoreboard.DisplaySlot;
import org.bukkit.scoreboard.Objective;
import org.bukkit.scoreboard.Score;
import org.bukkit.scoreboard.Scoreboard;
import org.bukkit.scoreboard.Team;
import org.bukkit.util.StringUtil;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
public class ScoreboardCommand extends VanillaCommand {
private static final List<String> MAIN_CHOICES = ImmutableList.of("objectives", "players", "teams");
private static final List<String> OBJECTIVES_CHOICES = ImmutableList.of("list", "add", "remove", "setdisplay");
private static final List<String> OBJECTIVES_CRITERIA = ImmutableList.of("health", "playerKillCount", "totalKillCount", "deathCount", "dummy");
private static final List<String> PLAYERS_CHOICES = ImmutableList.of("set", "add", "remove", "reset", "list");
private static final List<String> TEAMS_CHOICES = ImmutableList.of("add", "remove", "join", "leave", "empty", "list", "option");
private static final List<String> TEAMS_OPTION_CHOICES = ImmutableList.of("color", "friendlyfire", "seeFriendlyInvisibles");
private static final Map<String, DisplaySlot> OBJECTIVES_DISPLAYSLOT = ImmutableMap.of("belowName", DisplaySlot.BELOW_NAME, "list", DisplaySlot.PLAYER_LIST, "sidebar", DisplaySlot.SIDEBAR);
private static final Map<String, ChatColor> TEAMS_OPTION_COLOR = ImmutableMap.<String, ChatColor>builder()
.put("aqua", ChatColor.AQUA)
.put("black", ChatColor.BLACK)
.put("blue", ChatColor.BLUE)
.put("bold", ChatColor.BOLD)
.put("dark_aqua", ChatColor.DARK_AQUA)
.put("dark_blue", ChatColor.DARK_BLUE)
.put("dark_gray", ChatColor.DARK_GRAY)
.put("dark_green", ChatColor.DARK_GREEN)
.put("dark_purple", ChatColor.DARK_PURPLE)
.put("dark_red", ChatColor.DARK_RED)
.put("gold", ChatColor.GOLD)
.put("gray", ChatColor.GRAY)
.put("green", ChatColor.GREEN)
.put("italic", ChatColor.ITALIC)
.put("light_purple", ChatColor.LIGHT_PURPLE)
.put("obfuscated", ChatColor.MAGIC) // This is the important line
.put("red", ChatColor.RED)
.put("reset", ChatColor.RESET)
.put("strikethrough", ChatColor.STRIKETHROUGH)
.put("underline", ChatColor.UNDERLINE)
.put("white", ChatColor.WHITE)
.put("yellow", ChatColor.YELLOW)
.build();
private static final List<String> BOOLEAN = ImmutableList.of("true", "false");
public ScoreboardCommand() {
super("scoreboard");
this.description = "Scoreboard control";
this.usageMessage = "/scoreboard";
this.setPermission("bukkit.command.scoreboard");
}
@Override
public boolean execute(CommandSender sender, String currentAlias, String[] args) {
if (!testPermission(sender))
return true;
if (args.length < 1 || args[0].length() == 0) {
sender.sendMessage(ChatColor.RED + "Usage: /scoreboard <objectives|players|teams>");
return false;
}
final Scoreboard mainScoreboard = Bukkit.getScoreboardManager().getMainScoreboard();
if (args[0].equalsIgnoreCase("objectives")) {
if (args.length == 1) {
sender.sendMessage(ChatColor.RED + "Usage: /scoreboard objectives <list|add|remove|setdisplay>");
return false;
}
if (args[1].equalsIgnoreCase("list")) {
Set<Objective> objectives = mainScoreboard.getObjectives();
if (objectives.isEmpty()) {
sender.sendMessage(ChatColor.RED + "There are no objectives on the scoreboard");
return false;
}
sender.sendMessage(ChatColor.DARK_GREEN + "Showing " + objectives.size() + " objective(s) on scoreboard");
for (Objective objective : objectives) {
sender.sendMessage("- " + objective.getName() + ": displays as '" + objective.getDisplayName() + "' and is type '" + objective.getCriteria() + "'");
}
} else if (args[1].equalsIgnoreCase("add")) {
if (args.length < 4) {
sender.sendMessage(ChatColor.RED + "/scoreboard objectives add <name> <criteriaType> [display name ...]");
return false;
}
String name = args[2];
String criteria = args[3];
if (criteria == null) {
sender.sendMessage(ChatColor.RED + "Invalid objective criteria type. Valid types are: " + stringCollectionToString(OBJECTIVES_CRITERIA));
} else if (name.length() > 16) {
sender.sendMessage(ChatColor.RED + "The name '" + name + "' is too long for an objective, it can be at most 16 characters long");
} else if (mainScoreboard.getObjective(name) != null) {
sender.sendMessage(ChatColor.RED + "An objective with the name '" + name + "' already exists");
} else {
String displayName = null;
if (args.length > 4) {
displayName = StringUtils.join(ArrayUtils.subarray(args, 4, args.length), ' ');
if (displayName.length() > 32) {
sender.sendMessage(ChatColor.RED + "The name '" + displayName + "' is too long for an objective, it can be at most 32 characters long");
return false;
}
}
Objective objective = mainScoreboard.registerNewObjective(name, criteria);
if (displayName != null && displayName.length() > 0) {
objective.setDisplayName(displayName);
}
sender.sendMessage("Added new objective '" + name + "' successfully");
}
} else if (args[1].equalsIgnoreCase("remove")) {
if (args.length != 3) {
sender.sendMessage(ChatColor.RED + "/scoreboard objectives remove <name>");
return false;
}
String name = args[2];
Objective objective = mainScoreboard.getObjective(name);
if (objective == null) {
sender.sendMessage(ChatColor.RED + "No objective was found by the name '" + name + "'");
} else {
objective.unregister();
sender.sendMessage("Removed objective '" + name + "' successfully");
}
} else if (args[1].equalsIgnoreCase("setdisplay")) {
if (args.length != 3 && args.length != 4) {
sender.sendMessage(ChatColor.RED + "/scoreboard objectives setdisplay <slot> [objective]");
return false;
}
String slotName = args[2];
DisplaySlot slot = OBJECTIVES_DISPLAYSLOT.get(slotName);
if (slot == null) {
sender.sendMessage(ChatColor.RED + "No such display slot '" + slotName + "'");
} else {
if (args.length == 4) {
String objectiveName = args[3];
Objective objective = mainScoreboard.getObjective(objectiveName);
if (objective == null) {
sender.sendMessage(ChatColor.RED + "No objective was found by the name '" + objectiveName + "'");
return false;
}
objective.setDisplaySlot(slot);
sender.sendMessage("Set the display objective in slot '" + slotName + "' to '" + objective.getName() + "'");
} else {
Objective objective = mainScoreboard.getObjective(slot);
if (objective != null) {
objective.setDisplaySlot(null);
}
sender.sendMessage("Cleared objective display slot '" + slotName + "'");
}
}
}
} else if (args[0].equalsIgnoreCase("players")) {
if (args.length == 1) {
sender.sendMessage(ChatColor.RED + "/scoreboard players <set|add|remove|reset|list>");
return false;
}
if (args[1].equalsIgnoreCase("set") || args[1].equalsIgnoreCase("add") || args[1].equalsIgnoreCase("remove")) {
if (args.length != 5) {
if (args[1].equalsIgnoreCase("set")) {
sender.sendMessage(ChatColor.RED + "/scoreboard players set <player> <objective> <score>");
} else if (args[1].equalsIgnoreCase("add")) {
sender.sendMessage(ChatColor.RED + "/scoreboard players add <player> <objective> <count>");
} else {
sender.sendMessage(ChatColor.RED + "/scoreboard players remove <player> <objective> <count>");
}
return false;
}
String objectiveName = args[3];
Objective objective = mainScoreboard.getObjective(objectiveName);
if (objective == null) {
sender.sendMessage(ChatColor.RED + "No objective was found by the name '" + objectiveName + "'");
return false;
} else if (!objective.isModifiable()) {
sender.sendMessage(ChatColor.RED + "The objective '" + objectiveName + "' is read-only and cannot be set");
return false;
}
String valueString = args[4];
int value;
try {
value = Integer.parseInt(valueString);
} catch (NumberFormatException e) {
sender.sendMessage(ChatColor.RED + "'" + valueString + "' is not a valid number");
return false;
}
if (value < 1 && !args[1].equalsIgnoreCase("set")) {
sender.sendMessage(ChatColor.RED + "The number you have entered (" + value + ") is too small, it must be at least 1");
return false;
}
String playerName = args[2];
if (playerName.length() > 16) {
sender.sendMessage(ChatColor.RED + "'" + playerName + "' is too long for a player name");
return false;
}
Score score = objective.getScore(Bukkit.getOfflinePlayer(playerName));
int newScore;
if (args[1].equalsIgnoreCase("set")) {
newScore = value;
} else if (args[1].equalsIgnoreCase("add")) {
newScore = score.getScore() + value;
} else {
newScore = score.getScore() - value;
}
score.setScore(newScore);
sender.sendMessage("Set score of " + objectiveName + " for player " + playerName + " to " + newScore);
} else if (args[1].equalsIgnoreCase("reset")) {
if (args.length != 3) {
sender.sendMessage(ChatColor.RED + "/scoreboard players reset <player>");
return false;
}
String playerName = args[2];
if (playerName.length() > 16) {
sender.sendMessage(ChatColor.RED + "'" + playerName + "' is too long for a player name");
return false;
}
mainScoreboard.resetScores(Bukkit.getOfflinePlayer(playerName));
sender.sendMessage("Reset all scores of player " + playerName);
} else if (args[1].equalsIgnoreCase("list")) {
if (args.length > 3) {
sender.sendMessage(ChatColor.RED + "/scoreboard players list <player>");
return false;
}
if (args.length == 2) {
Set<OfflinePlayer> players = mainScoreboard.getPlayers();
if (players.isEmpty()) {
sender.sendMessage(ChatColor.RED + "There are no tracked players on the scoreboard");
} else {
sender.sendMessage(ChatColor.DARK_GREEN + "Showing " + players.size() + " tracked players on the scoreboard");
sender.sendMessage(offlinePlayerSetToString(players));
}
} else {
String playerName = args[2];
if (playerName.length() > 16) {
sender.sendMessage(ChatColor.RED + "'" + playerName + "' is too long for a player name");
return false;
}
Set<Score> scores = mainScoreboard.getScores(Bukkit.getOfflinePlayer(playerName));
if (scores.isEmpty()) {
sender.sendMessage(ChatColor.RED + "Player " + playerName + " has no scores recorded");
} else {
sender.sendMessage(ChatColor.DARK_GREEN + "Showing " + scores.size() + " tracked objective(s) for " + playerName);
for (Score score : scores) {
sender.sendMessage("- " + score.getObjective().getDisplayName() + ": " + score.getScore() + " (" + score.getObjective().getName() + ")");
}
}
}
}
} else if (args[0].equalsIgnoreCase("teams")) {
if (args.length == 1) {
sender.sendMessage(ChatColor.RED + "/scoreboard teams <list|add|remove|empty|join|leave|option>");
return false;
}
if (args[1].equalsIgnoreCase("list")) {
if (args.length == 2) {
Set<Team> teams = mainScoreboard.getTeams();
if (teams.isEmpty()) {
sender.sendMessage(ChatColor.RED + "There are no teams registered on the scoreboard");
} else {
sender.sendMessage(ChatColor.DARK_GREEN + "Showing " + teams.size() + " teams on the scoreboard");
for (Team team : teams) {
sender.sendMessage("- " + team.getName() + ": '" + team.getDisplayName() + "' has " + team.getSize() + " players");
}
}
} else if (args.length == 3) {
String teamName = args[2];
Team team = mainScoreboard.getTeam(teamName);
if (team == null) {
sender.sendMessage(ChatColor.RED + "No team was found by the name '" + teamName + "'");
} else {
Set<OfflinePlayer> players = team.getPlayers();
if (players.isEmpty()) {
sender.sendMessage(ChatColor.RED + "Team " + team.getName() + " has no players");
} else {
sender.sendMessage(ChatColor.DARK_GREEN + "Showing " + players.size() + " player(s) in team " + team.getName());
sender.sendMessage(offlinePlayerSetToString(players));
}
}
} else {
sender.sendMessage(ChatColor.RED + "/scoreboard teams list [name]");
return false;
}
} else if (args[1].equalsIgnoreCase("add")) {
if (args.length < 3) {
sender.sendMessage(ChatColor.RED + "/scoreboard teams add <name> [display name ...]");
return false;
}
String name = args[2];
if (name.length() > 16) {
sender.sendMessage(ChatColor.RED + "The name '" + name + "' is too long for a team, it can be at most 16 characters long");
} else if (mainScoreboard.getTeam(name) != null) {
sender.sendMessage(ChatColor.RED + "A team with the name '" + name + "' already exists");
} else {
String displayName = null;
if (args.length > 3) {
displayName = StringUtils.join(ArrayUtils.subarray(args, 4, args.length), ' ');
if (displayName.length() > 32) {
sender.sendMessage(ChatColor.RED + "The display name '" + displayName + "' is too long for a team, it can be at most 32 characters long");
return false;
}
}
Team team = mainScoreboard.registerNewTeam(name);
if (displayName != null && displayName.length() > 0) {
team.setDisplayName(displayName);
}
sender.sendMessage("Added new team '" + team.getName() + "' successfully");
}
} else if (args[1].equalsIgnoreCase("remove")) {
if (args.length != 3) {
sender.sendMessage(ChatColor.RED + "/scoreboard teams remove <name>");
return false;
}
String name = args[2];
Team team = mainScoreboard.getTeam(name);
if (team == null) {
sender.sendMessage(ChatColor.RED + "No team was found by the name '" + name + "'");
} else {
team.unregister();
sender.sendMessage("Removed team " + name);
}
} else if (args[1].equalsIgnoreCase("empty")) {
if (args.length != 3) {
sender.sendMessage(ChatColor.RED + "/scoreboard teams clear <name>");
return false;
}
String name = args[2];
Team team = mainScoreboard.getTeam(name);
if (team == null) {
sender.sendMessage(ChatColor.RED + "No team was found by the name '" + name + "'");
} else {
Set<OfflinePlayer> players = team.getPlayers();
if (players.isEmpty()) {
sender.sendMessage(ChatColor.RED + "Team " + team.getName() + " is already empty, cannot remove nonexistant players");
} else {
for (OfflinePlayer player : players) {
team.removePlayer(player);
}
sender.sendMessage("Removed all " + players.size() + " player(s) from team " + team.getName());
}
}
} else if (args[1].equalsIgnoreCase("join")) {
if ((sender instanceof Player) ? args.length < 3 : args.length < 4) {
sender.sendMessage(ChatColor.RED + "/scoreboard teams join <team> [player...]");
return false;
}
String teamName = args[2];
Team team = mainScoreboard.getTeam(teamName);
if (team == null) {
sender.sendMessage(ChatColor.RED + "No team was found by the name '" + teamName + "'");
} else {
Set<String> addedPlayers = new HashSet<String>();
if ((sender instanceof Player) && args.length == 3) {
team.addPlayer((Player) sender);
addedPlayers.add(sender.getName());
} else {
for (int i = 3; i < args.length; i++) {
String playerName = args[i];
OfflinePlayer offlinePlayer;
Player player = Bukkit.getPlayerExact(playerName);
if (player != null) {
offlinePlayer = player;
} else {
offlinePlayer = Bukkit.getOfflinePlayer(playerName);
}
team.addPlayer(offlinePlayer);
addedPlayers.add(offlinePlayer.getName());
}
}
sender.sendMessage("Added " + addedPlayers.size() + " player(s) to team " + team.getName() + ": " + stringCollectionToString(addedPlayers));
}
} else if (args[1].equalsIgnoreCase("leave")) {
- if ((sender instanceof Player) ? args.length < 2 : args.length < 3) {
+ if (!(sender instanceof Player) && args.length < 3) {
sender.sendMessage(ChatColor.RED + "/scoreboard teams leave [player...]");
return false;
}
Set<String> left = new HashSet<String>();
Set<String> noTeam = new HashSet<String>();
- if ((sender instanceof Player) && args.length == 3) {
+ if ((sender instanceof Player) && args.length == 2) {
Team team = mainScoreboard.getPlayerTeam((Player) sender);
if (team != null) {
team.removePlayer((Player) sender);
left.add(sender.getName());
} else {
noTeam.add(sender.getName());
}
} else {
for (int i = 3; i < args.length; i++) {
String playerName = args[i];
OfflinePlayer offlinePlayer;
Player player = Bukkit.getPlayerExact(playerName);
if (player != null) {
offlinePlayer = player;
} else {
offlinePlayer = Bukkit.getOfflinePlayer(playerName);
}
Team team = mainScoreboard.getPlayerTeam(offlinePlayer);
if (team != null) {
team.removePlayer(offlinePlayer);
left.add(offlinePlayer.getName());
} else {
noTeam.add(offlinePlayer.getName());
}
}
}
if (!left.isEmpty()) {
sender.sendMessage("Removed " + left.size() + " player(s) from their teams: " + stringCollectionToString(left));
}
if (!noTeam.isEmpty()) {
sender.sendMessage("Could not remove " + noTeam.size() + " player(s) from their teams: " + stringCollectionToString(noTeam));
}
} else if (args[1].equalsIgnoreCase("option")) {
if (args.length != 4 && args.length != 5) {
sender.sendMessage(ChatColor.RED + "/scoreboard teams option <team> <friendlyfire|color|seefriendlyinvisibles> <value>");
return false;
}
String teamName = args[2];
Team team = mainScoreboard.getTeam(teamName);
if (team == null) {
sender.sendMessage(ChatColor.RED + "No team was found by the name '" + teamName + "'");
return false;
}
String option = args[3].toLowerCase();
if (!option.equals("friendlyfire") && !option.equals("color") && !option.equals("seefriendlyinvisibles")) {
sender.sendMessage(ChatColor.RED + "/scoreboard teams option <team> <friendlyfire|color|seefriendlyinvisibles> <value>");
return false;
}
if (args.length == 4) {
if (option.equals("color")) {
sender.sendMessage(ChatColor.RED + "Valid values for option color are: " + stringCollectionToString(TEAMS_OPTION_COLOR.keySet()));
} else {
sender.sendMessage(ChatColor.RED + "Valid values for option " + option + " are: true and false");
}
} else {
String value = args[4].toLowerCase();
if (option.equals("color")) {
ChatColor color = TEAMS_OPTION_COLOR.get(value);
if (color == null) {
sender.sendMessage(ChatColor.RED + "Valid values for option color are: " + stringCollectionToString(TEAMS_OPTION_COLOR.keySet()));
return false;
}
team.setPrefix(color.toString());
team.setSuffix(ChatColor.RESET.toString());
} else {
if (!value.equals("true") && !value.equals("false")) {
sender.sendMessage(ChatColor.RED + "Valid values for option " + option + " are: true and false");
return false;
}
if (option.equals("friendlyfire")) {
team.setAllowFriendlyFire(value.equals("true"));
} else {
team.setCanSeeFriendlyInvisibles(value.equals("true"));
}
}
sender.sendMessage("Set option " + option + " for team " + team.getName() + " to " + value);
}
}
} else {
sender.sendMessage(ChatColor.RED + "Usage: /scoreboard <objectives|players|teams>");
return false;
}
return true;
}
@Override
public List<String> tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException {
Validate.notNull(sender, "Sender cannot be null");
Validate.notNull(args, "Arguments cannot be null");
Validate.notNull(alias, "Alias cannot be null");
if (args.length == 1) {
return StringUtil.copyPartialMatches(args[0], MAIN_CHOICES, new ArrayList<String>());
}
if (args.length > 1) {
if (args[0].equalsIgnoreCase("objectives")) {
if (args.length == 2) {
return StringUtil.copyPartialMatches(args[1], OBJECTIVES_CHOICES, new ArrayList<String>());
}
if (args[1].equalsIgnoreCase("add")) {
if (args.length == 4) {
return StringUtil.copyPartialMatches(args[3], OBJECTIVES_CRITERIA, new ArrayList<String>());
}
} else if (args[1].equalsIgnoreCase("remove")) {
if (args.length == 3) {
return StringUtil.copyPartialMatches(args[2], this.getCurrentObjectives(), new ArrayList<String>());
}
} else if (args[1].equalsIgnoreCase("setdisplay")) {
if (args.length == 3) {
return StringUtil.copyPartialMatches(args[2], OBJECTIVES_DISPLAYSLOT.keySet(), new ArrayList<String>());
}
if (args.length == 4) {
return StringUtil.copyPartialMatches(args[3], this.getCurrentObjectives(), new ArrayList<String>());
}
}
} else if (args[0].equalsIgnoreCase("players")) {
if (args.length == 2) {
return StringUtil.copyPartialMatches(args[1], PLAYERS_CHOICES, new ArrayList<String>());
}
if (args[1].equalsIgnoreCase("set") || args[1].equalsIgnoreCase("add") || args[1].equalsIgnoreCase("remove")) {
if (args.length == 3) {
return super.tabComplete(sender, alias, args);
}
if (args.length == 4) {
return StringUtil.copyPartialMatches(args[3], this.getCurrentObjectives(), new ArrayList<String>());
}
} else {
if (args.length == 3) {
return StringUtil.copyPartialMatches(args[2], this.getCurrentPlayers(), new ArrayList<String>());
}
}
} else if (args[0].equalsIgnoreCase("teams")) {
if (args.length == 2) {
return StringUtil.copyPartialMatches(args[1], TEAMS_CHOICES, new ArrayList<String>());
}
if (args[1].equalsIgnoreCase("join")) {
if (args.length == 3) {
return StringUtil.copyPartialMatches(args[2], this.getCurrentTeams(), new ArrayList<String>());
}
if (args.length >= 4) {
return super.tabComplete(sender, alias, args);
}
} else if (args[1].equalsIgnoreCase("leave")) {
return super.tabComplete(sender, alias, args);
} else if (args[1].equalsIgnoreCase("option")) {
if (args.length == 3) {
return StringUtil.copyPartialMatches(args[2], this.getCurrentTeams(), new ArrayList<String>());
}
if (args.length == 4) {
return StringUtil.copyPartialMatches(args[3], TEAMS_OPTION_CHOICES, new ArrayList<String>());
}
if (args.length == 5) {
if (args[3].equalsIgnoreCase("color")) {
return StringUtil.copyPartialMatches(args[4], TEAMS_OPTION_COLOR.keySet(), new ArrayList<String>());
} else {
return StringUtil.copyPartialMatches(args[4], BOOLEAN, new ArrayList<String>());
}
}
} else {
if (args.length == 3) {
return StringUtil.copyPartialMatches(args[2], this.getCurrentTeams(), new ArrayList<String>());
}
}
}
}
return ImmutableList.of();
}
private static String offlinePlayerSetToString(Set<OfflinePlayer> set) {
StringBuilder string = new StringBuilder();
String lastValue = null;
for (OfflinePlayer value : set) {
string.append(lastValue = value.getName()).append(", ");
}
string.delete(string.length() - 2, Integer.MAX_VALUE);
if (string.length() != lastValue.length()) {
string.insert(string.length() - lastValue.length(), "and ");
}
return string.toString();
}
private static String stringCollectionToString(Collection<String> set) {
StringBuilder string = new StringBuilder();
String lastValue = null;
for (String value : set) {
string.append(lastValue = value).append(", ");
}
string.delete(string.length() - 2, Integer.MAX_VALUE);
if (string.length() != lastValue.length()) {
string.insert(string.length() - lastValue.length(), "and ");
}
return string.toString();
}
private List<String> getCurrentObjectives() {
List<String> list = new ArrayList<String>();
for (Objective objective : Bukkit.getScoreboardManager().getMainScoreboard().getObjectives()) {
list.add(objective.getName());
}
Collections.sort(list, String.CASE_INSENSITIVE_ORDER);
return list;
}
private List<String> getCurrentPlayers() {
List<String> list = new ArrayList<String>();
for (OfflinePlayer player : Bukkit.getScoreboardManager().getMainScoreboard().getPlayers()) {
list.add(player.getName());
}
Collections.sort(list, String.CASE_INSENSITIVE_ORDER);
return list;
}
private List<String> getCurrentTeams() {
List<String> list = new ArrayList<String>();
for (Team team : Bukkit.getScoreboardManager().getMainScoreboard().getTeams()) {
list.add(team.getName());
}
Collections.sort(list, String.CASE_INSENSITIVE_ORDER);
return list;
}
}
| false | true | public boolean execute(CommandSender sender, String currentAlias, String[] args) {
if (!testPermission(sender))
return true;
if (args.length < 1 || args[0].length() == 0) {
sender.sendMessage(ChatColor.RED + "Usage: /scoreboard <objectives|players|teams>");
return false;
}
final Scoreboard mainScoreboard = Bukkit.getScoreboardManager().getMainScoreboard();
if (args[0].equalsIgnoreCase("objectives")) {
if (args.length == 1) {
sender.sendMessage(ChatColor.RED + "Usage: /scoreboard objectives <list|add|remove|setdisplay>");
return false;
}
if (args[1].equalsIgnoreCase("list")) {
Set<Objective> objectives = mainScoreboard.getObjectives();
if (objectives.isEmpty()) {
sender.sendMessage(ChatColor.RED + "There are no objectives on the scoreboard");
return false;
}
sender.sendMessage(ChatColor.DARK_GREEN + "Showing " + objectives.size() + " objective(s) on scoreboard");
for (Objective objective : objectives) {
sender.sendMessage("- " + objective.getName() + ": displays as '" + objective.getDisplayName() + "' and is type '" + objective.getCriteria() + "'");
}
} else if (args[1].equalsIgnoreCase("add")) {
if (args.length < 4) {
sender.sendMessage(ChatColor.RED + "/scoreboard objectives add <name> <criteriaType> [display name ...]");
return false;
}
String name = args[2];
String criteria = args[3];
if (criteria == null) {
sender.sendMessage(ChatColor.RED + "Invalid objective criteria type. Valid types are: " + stringCollectionToString(OBJECTIVES_CRITERIA));
} else if (name.length() > 16) {
sender.sendMessage(ChatColor.RED + "The name '" + name + "' is too long for an objective, it can be at most 16 characters long");
} else if (mainScoreboard.getObjective(name) != null) {
sender.sendMessage(ChatColor.RED + "An objective with the name '" + name + "' already exists");
} else {
String displayName = null;
if (args.length > 4) {
displayName = StringUtils.join(ArrayUtils.subarray(args, 4, args.length), ' ');
if (displayName.length() > 32) {
sender.sendMessage(ChatColor.RED + "The name '" + displayName + "' is too long for an objective, it can be at most 32 characters long");
return false;
}
}
Objective objective = mainScoreboard.registerNewObjective(name, criteria);
if (displayName != null && displayName.length() > 0) {
objective.setDisplayName(displayName);
}
sender.sendMessage("Added new objective '" + name + "' successfully");
}
} else if (args[1].equalsIgnoreCase("remove")) {
if (args.length != 3) {
sender.sendMessage(ChatColor.RED + "/scoreboard objectives remove <name>");
return false;
}
String name = args[2];
Objective objective = mainScoreboard.getObjective(name);
if (objective == null) {
sender.sendMessage(ChatColor.RED + "No objective was found by the name '" + name + "'");
} else {
objective.unregister();
sender.sendMessage("Removed objective '" + name + "' successfully");
}
} else if (args[1].equalsIgnoreCase("setdisplay")) {
if (args.length != 3 && args.length != 4) {
sender.sendMessage(ChatColor.RED + "/scoreboard objectives setdisplay <slot> [objective]");
return false;
}
String slotName = args[2];
DisplaySlot slot = OBJECTIVES_DISPLAYSLOT.get(slotName);
if (slot == null) {
sender.sendMessage(ChatColor.RED + "No such display slot '" + slotName + "'");
} else {
if (args.length == 4) {
String objectiveName = args[3];
Objective objective = mainScoreboard.getObjective(objectiveName);
if (objective == null) {
sender.sendMessage(ChatColor.RED + "No objective was found by the name '" + objectiveName + "'");
return false;
}
objective.setDisplaySlot(slot);
sender.sendMessage("Set the display objective in slot '" + slotName + "' to '" + objective.getName() + "'");
} else {
Objective objective = mainScoreboard.getObjective(slot);
if (objective != null) {
objective.setDisplaySlot(null);
}
sender.sendMessage("Cleared objective display slot '" + slotName + "'");
}
}
}
} else if (args[0].equalsIgnoreCase("players")) {
if (args.length == 1) {
sender.sendMessage(ChatColor.RED + "/scoreboard players <set|add|remove|reset|list>");
return false;
}
if (args[1].equalsIgnoreCase("set") || args[1].equalsIgnoreCase("add") || args[1].equalsIgnoreCase("remove")) {
if (args.length != 5) {
if (args[1].equalsIgnoreCase("set")) {
sender.sendMessage(ChatColor.RED + "/scoreboard players set <player> <objective> <score>");
} else if (args[1].equalsIgnoreCase("add")) {
sender.sendMessage(ChatColor.RED + "/scoreboard players add <player> <objective> <count>");
} else {
sender.sendMessage(ChatColor.RED + "/scoreboard players remove <player> <objective> <count>");
}
return false;
}
String objectiveName = args[3];
Objective objective = mainScoreboard.getObjective(objectiveName);
if (objective == null) {
sender.sendMessage(ChatColor.RED + "No objective was found by the name '" + objectiveName + "'");
return false;
} else if (!objective.isModifiable()) {
sender.sendMessage(ChatColor.RED + "The objective '" + objectiveName + "' is read-only and cannot be set");
return false;
}
String valueString = args[4];
int value;
try {
value = Integer.parseInt(valueString);
} catch (NumberFormatException e) {
sender.sendMessage(ChatColor.RED + "'" + valueString + "' is not a valid number");
return false;
}
if (value < 1 && !args[1].equalsIgnoreCase("set")) {
sender.sendMessage(ChatColor.RED + "The number you have entered (" + value + ") is too small, it must be at least 1");
return false;
}
String playerName = args[2];
if (playerName.length() > 16) {
sender.sendMessage(ChatColor.RED + "'" + playerName + "' is too long for a player name");
return false;
}
Score score = objective.getScore(Bukkit.getOfflinePlayer(playerName));
int newScore;
if (args[1].equalsIgnoreCase("set")) {
newScore = value;
} else if (args[1].equalsIgnoreCase("add")) {
newScore = score.getScore() + value;
} else {
newScore = score.getScore() - value;
}
score.setScore(newScore);
sender.sendMessage("Set score of " + objectiveName + " for player " + playerName + " to " + newScore);
} else if (args[1].equalsIgnoreCase("reset")) {
if (args.length != 3) {
sender.sendMessage(ChatColor.RED + "/scoreboard players reset <player>");
return false;
}
String playerName = args[2];
if (playerName.length() > 16) {
sender.sendMessage(ChatColor.RED + "'" + playerName + "' is too long for a player name");
return false;
}
mainScoreboard.resetScores(Bukkit.getOfflinePlayer(playerName));
sender.sendMessage("Reset all scores of player " + playerName);
} else if (args[1].equalsIgnoreCase("list")) {
if (args.length > 3) {
sender.sendMessage(ChatColor.RED + "/scoreboard players list <player>");
return false;
}
if (args.length == 2) {
Set<OfflinePlayer> players = mainScoreboard.getPlayers();
if (players.isEmpty()) {
sender.sendMessage(ChatColor.RED + "There are no tracked players on the scoreboard");
} else {
sender.sendMessage(ChatColor.DARK_GREEN + "Showing " + players.size() + " tracked players on the scoreboard");
sender.sendMessage(offlinePlayerSetToString(players));
}
} else {
String playerName = args[2];
if (playerName.length() > 16) {
sender.sendMessage(ChatColor.RED + "'" + playerName + "' is too long for a player name");
return false;
}
Set<Score> scores = mainScoreboard.getScores(Bukkit.getOfflinePlayer(playerName));
if (scores.isEmpty()) {
sender.sendMessage(ChatColor.RED + "Player " + playerName + " has no scores recorded");
} else {
sender.sendMessage(ChatColor.DARK_GREEN + "Showing " + scores.size() + " tracked objective(s) for " + playerName);
for (Score score : scores) {
sender.sendMessage("- " + score.getObjective().getDisplayName() + ": " + score.getScore() + " (" + score.getObjective().getName() + ")");
}
}
}
}
} else if (args[0].equalsIgnoreCase("teams")) {
if (args.length == 1) {
sender.sendMessage(ChatColor.RED + "/scoreboard teams <list|add|remove|empty|join|leave|option>");
return false;
}
if (args[1].equalsIgnoreCase("list")) {
if (args.length == 2) {
Set<Team> teams = mainScoreboard.getTeams();
if (teams.isEmpty()) {
sender.sendMessage(ChatColor.RED + "There are no teams registered on the scoreboard");
} else {
sender.sendMessage(ChatColor.DARK_GREEN + "Showing " + teams.size() + " teams on the scoreboard");
for (Team team : teams) {
sender.sendMessage("- " + team.getName() + ": '" + team.getDisplayName() + "' has " + team.getSize() + " players");
}
}
} else if (args.length == 3) {
String teamName = args[2];
Team team = mainScoreboard.getTeam(teamName);
if (team == null) {
sender.sendMessage(ChatColor.RED + "No team was found by the name '" + teamName + "'");
} else {
Set<OfflinePlayer> players = team.getPlayers();
if (players.isEmpty()) {
sender.sendMessage(ChatColor.RED + "Team " + team.getName() + " has no players");
} else {
sender.sendMessage(ChatColor.DARK_GREEN + "Showing " + players.size() + " player(s) in team " + team.getName());
sender.sendMessage(offlinePlayerSetToString(players));
}
}
} else {
sender.sendMessage(ChatColor.RED + "/scoreboard teams list [name]");
return false;
}
} else if (args[1].equalsIgnoreCase("add")) {
if (args.length < 3) {
sender.sendMessage(ChatColor.RED + "/scoreboard teams add <name> [display name ...]");
return false;
}
String name = args[2];
if (name.length() > 16) {
sender.sendMessage(ChatColor.RED + "The name '" + name + "' is too long for a team, it can be at most 16 characters long");
} else if (mainScoreboard.getTeam(name) != null) {
sender.sendMessage(ChatColor.RED + "A team with the name '" + name + "' already exists");
} else {
String displayName = null;
if (args.length > 3) {
displayName = StringUtils.join(ArrayUtils.subarray(args, 4, args.length), ' ');
if (displayName.length() > 32) {
sender.sendMessage(ChatColor.RED + "The display name '" + displayName + "' is too long for a team, it can be at most 32 characters long");
return false;
}
}
Team team = mainScoreboard.registerNewTeam(name);
if (displayName != null && displayName.length() > 0) {
team.setDisplayName(displayName);
}
sender.sendMessage("Added new team '" + team.getName() + "' successfully");
}
} else if (args[1].equalsIgnoreCase("remove")) {
if (args.length != 3) {
sender.sendMessage(ChatColor.RED + "/scoreboard teams remove <name>");
return false;
}
String name = args[2];
Team team = mainScoreboard.getTeam(name);
if (team == null) {
sender.sendMessage(ChatColor.RED + "No team was found by the name '" + name + "'");
} else {
team.unregister();
sender.sendMessage("Removed team " + name);
}
} else if (args[1].equalsIgnoreCase("empty")) {
if (args.length != 3) {
sender.sendMessage(ChatColor.RED + "/scoreboard teams clear <name>");
return false;
}
String name = args[2];
Team team = mainScoreboard.getTeam(name);
if (team == null) {
sender.sendMessage(ChatColor.RED + "No team was found by the name '" + name + "'");
} else {
Set<OfflinePlayer> players = team.getPlayers();
if (players.isEmpty()) {
sender.sendMessage(ChatColor.RED + "Team " + team.getName() + " is already empty, cannot remove nonexistant players");
} else {
for (OfflinePlayer player : players) {
team.removePlayer(player);
}
sender.sendMessage("Removed all " + players.size() + " player(s) from team " + team.getName());
}
}
} else if (args[1].equalsIgnoreCase("join")) {
if ((sender instanceof Player) ? args.length < 3 : args.length < 4) {
sender.sendMessage(ChatColor.RED + "/scoreboard teams join <team> [player...]");
return false;
}
String teamName = args[2];
Team team = mainScoreboard.getTeam(teamName);
if (team == null) {
sender.sendMessage(ChatColor.RED + "No team was found by the name '" + teamName + "'");
} else {
Set<String> addedPlayers = new HashSet<String>();
if ((sender instanceof Player) && args.length == 3) {
team.addPlayer((Player) sender);
addedPlayers.add(sender.getName());
} else {
for (int i = 3; i < args.length; i++) {
String playerName = args[i];
OfflinePlayer offlinePlayer;
Player player = Bukkit.getPlayerExact(playerName);
if (player != null) {
offlinePlayer = player;
} else {
offlinePlayer = Bukkit.getOfflinePlayer(playerName);
}
team.addPlayer(offlinePlayer);
addedPlayers.add(offlinePlayer.getName());
}
}
sender.sendMessage("Added " + addedPlayers.size() + " player(s) to team " + team.getName() + ": " + stringCollectionToString(addedPlayers));
}
} else if (args[1].equalsIgnoreCase("leave")) {
if ((sender instanceof Player) ? args.length < 2 : args.length < 3) {
sender.sendMessage(ChatColor.RED + "/scoreboard teams leave [player...]");
return false;
}
Set<String> left = new HashSet<String>();
Set<String> noTeam = new HashSet<String>();
if ((sender instanceof Player) && args.length == 3) {
Team team = mainScoreboard.getPlayerTeam((Player) sender);
if (team != null) {
team.removePlayer((Player) sender);
left.add(sender.getName());
} else {
noTeam.add(sender.getName());
}
} else {
for (int i = 3; i < args.length; i++) {
String playerName = args[i];
OfflinePlayer offlinePlayer;
Player player = Bukkit.getPlayerExact(playerName);
if (player != null) {
offlinePlayer = player;
} else {
offlinePlayer = Bukkit.getOfflinePlayer(playerName);
}
Team team = mainScoreboard.getPlayerTeam(offlinePlayer);
if (team != null) {
team.removePlayer(offlinePlayer);
left.add(offlinePlayer.getName());
} else {
noTeam.add(offlinePlayer.getName());
}
}
}
if (!left.isEmpty()) {
sender.sendMessage("Removed " + left.size() + " player(s) from their teams: " + stringCollectionToString(left));
}
if (!noTeam.isEmpty()) {
sender.sendMessage("Could not remove " + noTeam.size() + " player(s) from their teams: " + stringCollectionToString(noTeam));
}
} else if (args[1].equalsIgnoreCase("option")) {
if (args.length != 4 && args.length != 5) {
sender.sendMessage(ChatColor.RED + "/scoreboard teams option <team> <friendlyfire|color|seefriendlyinvisibles> <value>");
return false;
}
String teamName = args[2];
Team team = mainScoreboard.getTeam(teamName);
if (team == null) {
sender.sendMessage(ChatColor.RED + "No team was found by the name '" + teamName + "'");
return false;
}
String option = args[3].toLowerCase();
if (!option.equals("friendlyfire") && !option.equals("color") && !option.equals("seefriendlyinvisibles")) {
sender.sendMessage(ChatColor.RED + "/scoreboard teams option <team> <friendlyfire|color|seefriendlyinvisibles> <value>");
return false;
}
if (args.length == 4) {
if (option.equals("color")) {
sender.sendMessage(ChatColor.RED + "Valid values for option color are: " + stringCollectionToString(TEAMS_OPTION_COLOR.keySet()));
} else {
sender.sendMessage(ChatColor.RED + "Valid values for option " + option + " are: true and false");
}
} else {
String value = args[4].toLowerCase();
if (option.equals("color")) {
ChatColor color = TEAMS_OPTION_COLOR.get(value);
if (color == null) {
sender.sendMessage(ChatColor.RED + "Valid values for option color are: " + stringCollectionToString(TEAMS_OPTION_COLOR.keySet()));
return false;
}
team.setPrefix(color.toString());
team.setSuffix(ChatColor.RESET.toString());
} else {
if (!value.equals("true") && !value.equals("false")) {
sender.sendMessage(ChatColor.RED + "Valid values for option " + option + " are: true and false");
return false;
}
if (option.equals("friendlyfire")) {
team.setAllowFriendlyFire(value.equals("true"));
} else {
team.setCanSeeFriendlyInvisibles(value.equals("true"));
}
}
sender.sendMessage("Set option " + option + " for team " + team.getName() + " to " + value);
}
}
} else {
sender.sendMessage(ChatColor.RED + "Usage: /scoreboard <objectives|players|teams>");
return false;
}
return true;
}
| public boolean execute(CommandSender sender, String currentAlias, String[] args) {
if (!testPermission(sender))
return true;
if (args.length < 1 || args[0].length() == 0) {
sender.sendMessage(ChatColor.RED + "Usage: /scoreboard <objectives|players|teams>");
return false;
}
final Scoreboard mainScoreboard = Bukkit.getScoreboardManager().getMainScoreboard();
if (args[0].equalsIgnoreCase("objectives")) {
if (args.length == 1) {
sender.sendMessage(ChatColor.RED + "Usage: /scoreboard objectives <list|add|remove|setdisplay>");
return false;
}
if (args[1].equalsIgnoreCase("list")) {
Set<Objective> objectives = mainScoreboard.getObjectives();
if (objectives.isEmpty()) {
sender.sendMessage(ChatColor.RED + "There are no objectives on the scoreboard");
return false;
}
sender.sendMessage(ChatColor.DARK_GREEN + "Showing " + objectives.size() + " objective(s) on scoreboard");
for (Objective objective : objectives) {
sender.sendMessage("- " + objective.getName() + ": displays as '" + objective.getDisplayName() + "' and is type '" + objective.getCriteria() + "'");
}
} else if (args[1].equalsIgnoreCase("add")) {
if (args.length < 4) {
sender.sendMessage(ChatColor.RED + "/scoreboard objectives add <name> <criteriaType> [display name ...]");
return false;
}
String name = args[2];
String criteria = args[3];
if (criteria == null) {
sender.sendMessage(ChatColor.RED + "Invalid objective criteria type. Valid types are: " + stringCollectionToString(OBJECTIVES_CRITERIA));
} else if (name.length() > 16) {
sender.sendMessage(ChatColor.RED + "The name '" + name + "' is too long for an objective, it can be at most 16 characters long");
} else if (mainScoreboard.getObjective(name) != null) {
sender.sendMessage(ChatColor.RED + "An objective with the name '" + name + "' already exists");
} else {
String displayName = null;
if (args.length > 4) {
displayName = StringUtils.join(ArrayUtils.subarray(args, 4, args.length), ' ');
if (displayName.length() > 32) {
sender.sendMessage(ChatColor.RED + "The name '" + displayName + "' is too long for an objective, it can be at most 32 characters long");
return false;
}
}
Objective objective = mainScoreboard.registerNewObjective(name, criteria);
if (displayName != null && displayName.length() > 0) {
objective.setDisplayName(displayName);
}
sender.sendMessage("Added new objective '" + name + "' successfully");
}
} else if (args[1].equalsIgnoreCase("remove")) {
if (args.length != 3) {
sender.sendMessage(ChatColor.RED + "/scoreboard objectives remove <name>");
return false;
}
String name = args[2];
Objective objective = mainScoreboard.getObjective(name);
if (objective == null) {
sender.sendMessage(ChatColor.RED + "No objective was found by the name '" + name + "'");
} else {
objective.unregister();
sender.sendMessage("Removed objective '" + name + "' successfully");
}
} else if (args[1].equalsIgnoreCase("setdisplay")) {
if (args.length != 3 && args.length != 4) {
sender.sendMessage(ChatColor.RED + "/scoreboard objectives setdisplay <slot> [objective]");
return false;
}
String slotName = args[2];
DisplaySlot slot = OBJECTIVES_DISPLAYSLOT.get(slotName);
if (slot == null) {
sender.sendMessage(ChatColor.RED + "No such display slot '" + slotName + "'");
} else {
if (args.length == 4) {
String objectiveName = args[3];
Objective objective = mainScoreboard.getObjective(objectiveName);
if (objective == null) {
sender.sendMessage(ChatColor.RED + "No objective was found by the name '" + objectiveName + "'");
return false;
}
objective.setDisplaySlot(slot);
sender.sendMessage("Set the display objective in slot '" + slotName + "' to '" + objective.getName() + "'");
} else {
Objective objective = mainScoreboard.getObjective(slot);
if (objective != null) {
objective.setDisplaySlot(null);
}
sender.sendMessage("Cleared objective display slot '" + slotName + "'");
}
}
}
} else if (args[0].equalsIgnoreCase("players")) {
if (args.length == 1) {
sender.sendMessage(ChatColor.RED + "/scoreboard players <set|add|remove|reset|list>");
return false;
}
if (args[1].equalsIgnoreCase("set") || args[1].equalsIgnoreCase("add") || args[1].equalsIgnoreCase("remove")) {
if (args.length != 5) {
if (args[1].equalsIgnoreCase("set")) {
sender.sendMessage(ChatColor.RED + "/scoreboard players set <player> <objective> <score>");
} else if (args[1].equalsIgnoreCase("add")) {
sender.sendMessage(ChatColor.RED + "/scoreboard players add <player> <objective> <count>");
} else {
sender.sendMessage(ChatColor.RED + "/scoreboard players remove <player> <objective> <count>");
}
return false;
}
String objectiveName = args[3];
Objective objective = mainScoreboard.getObjective(objectiveName);
if (objective == null) {
sender.sendMessage(ChatColor.RED + "No objective was found by the name '" + objectiveName + "'");
return false;
} else if (!objective.isModifiable()) {
sender.sendMessage(ChatColor.RED + "The objective '" + objectiveName + "' is read-only and cannot be set");
return false;
}
String valueString = args[4];
int value;
try {
value = Integer.parseInt(valueString);
} catch (NumberFormatException e) {
sender.sendMessage(ChatColor.RED + "'" + valueString + "' is not a valid number");
return false;
}
if (value < 1 && !args[1].equalsIgnoreCase("set")) {
sender.sendMessage(ChatColor.RED + "The number you have entered (" + value + ") is too small, it must be at least 1");
return false;
}
String playerName = args[2];
if (playerName.length() > 16) {
sender.sendMessage(ChatColor.RED + "'" + playerName + "' is too long for a player name");
return false;
}
Score score = objective.getScore(Bukkit.getOfflinePlayer(playerName));
int newScore;
if (args[1].equalsIgnoreCase("set")) {
newScore = value;
} else if (args[1].equalsIgnoreCase("add")) {
newScore = score.getScore() + value;
} else {
newScore = score.getScore() - value;
}
score.setScore(newScore);
sender.sendMessage("Set score of " + objectiveName + " for player " + playerName + " to " + newScore);
} else if (args[1].equalsIgnoreCase("reset")) {
if (args.length != 3) {
sender.sendMessage(ChatColor.RED + "/scoreboard players reset <player>");
return false;
}
String playerName = args[2];
if (playerName.length() > 16) {
sender.sendMessage(ChatColor.RED + "'" + playerName + "' is too long for a player name");
return false;
}
mainScoreboard.resetScores(Bukkit.getOfflinePlayer(playerName));
sender.sendMessage("Reset all scores of player " + playerName);
} else if (args[1].equalsIgnoreCase("list")) {
if (args.length > 3) {
sender.sendMessage(ChatColor.RED + "/scoreboard players list <player>");
return false;
}
if (args.length == 2) {
Set<OfflinePlayer> players = mainScoreboard.getPlayers();
if (players.isEmpty()) {
sender.sendMessage(ChatColor.RED + "There are no tracked players on the scoreboard");
} else {
sender.sendMessage(ChatColor.DARK_GREEN + "Showing " + players.size() + " tracked players on the scoreboard");
sender.sendMessage(offlinePlayerSetToString(players));
}
} else {
String playerName = args[2];
if (playerName.length() > 16) {
sender.sendMessage(ChatColor.RED + "'" + playerName + "' is too long for a player name");
return false;
}
Set<Score> scores = mainScoreboard.getScores(Bukkit.getOfflinePlayer(playerName));
if (scores.isEmpty()) {
sender.sendMessage(ChatColor.RED + "Player " + playerName + " has no scores recorded");
} else {
sender.sendMessage(ChatColor.DARK_GREEN + "Showing " + scores.size() + " tracked objective(s) for " + playerName);
for (Score score : scores) {
sender.sendMessage("- " + score.getObjective().getDisplayName() + ": " + score.getScore() + " (" + score.getObjective().getName() + ")");
}
}
}
}
} else if (args[0].equalsIgnoreCase("teams")) {
if (args.length == 1) {
sender.sendMessage(ChatColor.RED + "/scoreboard teams <list|add|remove|empty|join|leave|option>");
return false;
}
if (args[1].equalsIgnoreCase("list")) {
if (args.length == 2) {
Set<Team> teams = mainScoreboard.getTeams();
if (teams.isEmpty()) {
sender.sendMessage(ChatColor.RED + "There are no teams registered on the scoreboard");
} else {
sender.sendMessage(ChatColor.DARK_GREEN + "Showing " + teams.size() + " teams on the scoreboard");
for (Team team : teams) {
sender.sendMessage("- " + team.getName() + ": '" + team.getDisplayName() + "' has " + team.getSize() + " players");
}
}
} else if (args.length == 3) {
String teamName = args[2];
Team team = mainScoreboard.getTeam(teamName);
if (team == null) {
sender.sendMessage(ChatColor.RED + "No team was found by the name '" + teamName + "'");
} else {
Set<OfflinePlayer> players = team.getPlayers();
if (players.isEmpty()) {
sender.sendMessage(ChatColor.RED + "Team " + team.getName() + " has no players");
} else {
sender.sendMessage(ChatColor.DARK_GREEN + "Showing " + players.size() + " player(s) in team " + team.getName());
sender.sendMessage(offlinePlayerSetToString(players));
}
}
} else {
sender.sendMessage(ChatColor.RED + "/scoreboard teams list [name]");
return false;
}
} else if (args[1].equalsIgnoreCase("add")) {
if (args.length < 3) {
sender.sendMessage(ChatColor.RED + "/scoreboard teams add <name> [display name ...]");
return false;
}
String name = args[2];
if (name.length() > 16) {
sender.sendMessage(ChatColor.RED + "The name '" + name + "' is too long for a team, it can be at most 16 characters long");
} else if (mainScoreboard.getTeam(name) != null) {
sender.sendMessage(ChatColor.RED + "A team with the name '" + name + "' already exists");
} else {
String displayName = null;
if (args.length > 3) {
displayName = StringUtils.join(ArrayUtils.subarray(args, 4, args.length), ' ');
if (displayName.length() > 32) {
sender.sendMessage(ChatColor.RED + "The display name '" + displayName + "' is too long for a team, it can be at most 32 characters long");
return false;
}
}
Team team = mainScoreboard.registerNewTeam(name);
if (displayName != null && displayName.length() > 0) {
team.setDisplayName(displayName);
}
sender.sendMessage("Added new team '" + team.getName() + "' successfully");
}
} else if (args[1].equalsIgnoreCase("remove")) {
if (args.length != 3) {
sender.sendMessage(ChatColor.RED + "/scoreboard teams remove <name>");
return false;
}
String name = args[2];
Team team = mainScoreboard.getTeam(name);
if (team == null) {
sender.sendMessage(ChatColor.RED + "No team was found by the name '" + name + "'");
} else {
team.unregister();
sender.sendMessage("Removed team " + name);
}
} else if (args[1].equalsIgnoreCase("empty")) {
if (args.length != 3) {
sender.sendMessage(ChatColor.RED + "/scoreboard teams clear <name>");
return false;
}
String name = args[2];
Team team = mainScoreboard.getTeam(name);
if (team == null) {
sender.sendMessage(ChatColor.RED + "No team was found by the name '" + name + "'");
} else {
Set<OfflinePlayer> players = team.getPlayers();
if (players.isEmpty()) {
sender.sendMessage(ChatColor.RED + "Team " + team.getName() + " is already empty, cannot remove nonexistant players");
} else {
for (OfflinePlayer player : players) {
team.removePlayer(player);
}
sender.sendMessage("Removed all " + players.size() + " player(s) from team " + team.getName());
}
}
} else if (args[1].equalsIgnoreCase("join")) {
if ((sender instanceof Player) ? args.length < 3 : args.length < 4) {
sender.sendMessage(ChatColor.RED + "/scoreboard teams join <team> [player...]");
return false;
}
String teamName = args[2];
Team team = mainScoreboard.getTeam(teamName);
if (team == null) {
sender.sendMessage(ChatColor.RED + "No team was found by the name '" + teamName + "'");
} else {
Set<String> addedPlayers = new HashSet<String>();
if ((sender instanceof Player) && args.length == 3) {
team.addPlayer((Player) sender);
addedPlayers.add(sender.getName());
} else {
for (int i = 3; i < args.length; i++) {
String playerName = args[i];
OfflinePlayer offlinePlayer;
Player player = Bukkit.getPlayerExact(playerName);
if (player != null) {
offlinePlayer = player;
} else {
offlinePlayer = Bukkit.getOfflinePlayer(playerName);
}
team.addPlayer(offlinePlayer);
addedPlayers.add(offlinePlayer.getName());
}
}
sender.sendMessage("Added " + addedPlayers.size() + " player(s) to team " + team.getName() + ": " + stringCollectionToString(addedPlayers));
}
} else if (args[1].equalsIgnoreCase("leave")) {
if (!(sender instanceof Player) && args.length < 3) {
sender.sendMessage(ChatColor.RED + "/scoreboard teams leave [player...]");
return false;
}
Set<String> left = new HashSet<String>();
Set<String> noTeam = new HashSet<String>();
if ((sender instanceof Player) && args.length == 2) {
Team team = mainScoreboard.getPlayerTeam((Player) sender);
if (team != null) {
team.removePlayer((Player) sender);
left.add(sender.getName());
} else {
noTeam.add(sender.getName());
}
} else {
for (int i = 3; i < args.length; i++) {
String playerName = args[i];
OfflinePlayer offlinePlayer;
Player player = Bukkit.getPlayerExact(playerName);
if (player != null) {
offlinePlayer = player;
} else {
offlinePlayer = Bukkit.getOfflinePlayer(playerName);
}
Team team = mainScoreboard.getPlayerTeam(offlinePlayer);
if (team != null) {
team.removePlayer(offlinePlayer);
left.add(offlinePlayer.getName());
} else {
noTeam.add(offlinePlayer.getName());
}
}
}
if (!left.isEmpty()) {
sender.sendMessage("Removed " + left.size() + " player(s) from their teams: " + stringCollectionToString(left));
}
if (!noTeam.isEmpty()) {
sender.sendMessage("Could not remove " + noTeam.size() + " player(s) from their teams: " + stringCollectionToString(noTeam));
}
} else if (args[1].equalsIgnoreCase("option")) {
if (args.length != 4 && args.length != 5) {
sender.sendMessage(ChatColor.RED + "/scoreboard teams option <team> <friendlyfire|color|seefriendlyinvisibles> <value>");
return false;
}
String teamName = args[2];
Team team = mainScoreboard.getTeam(teamName);
if (team == null) {
sender.sendMessage(ChatColor.RED + "No team was found by the name '" + teamName + "'");
return false;
}
String option = args[3].toLowerCase();
if (!option.equals("friendlyfire") && !option.equals("color") && !option.equals("seefriendlyinvisibles")) {
sender.sendMessage(ChatColor.RED + "/scoreboard teams option <team> <friendlyfire|color|seefriendlyinvisibles> <value>");
return false;
}
if (args.length == 4) {
if (option.equals("color")) {
sender.sendMessage(ChatColor.RED + "Valid values for option color are: " + stringCollectionToString(TEAMS_OPTION_COLOR.keySet()));
} else {
sender.sendMessage(ChatColor.RED + "Valid values for option " + option + " are: true and false");
}
} else {
String value = args[4].toLowerCase();
if (option.equals("color")) {
ChatColor color = TEAMS_OPTION_COLOR.get(value);
if (color == null) {
sender.sendMessage(ChatColor.RED + "Valid values for option color are: " + stringCollectionToString(TEAMS_OPTION_COLOR.keySet()));
return false;
}
team.setPrefix(color.toString());
team.setSuffix(ChatColor.RESET.toString());
} else {
if (!value.equals("true") && !value.equals("false")) {
sender.sendMessage(ChatColor.RED + "Valid values for option " + option + " are: true and false");
return false;
}
if (option.equals("friendlyfire")) {
team.setAllowFriendlyFire(value.equals("true"));
} else {
team.setCanSeeFriendlyInvisibles(value.equals("true"));
}
}
sender.sendMessage("Set option " + option + " for team " + team.getName() + " to " + value);
}
}
} else {
sender.sendMessage(ChatColor.RED + "Usage: /scoreboard <objectives|players|teams>");
return false;
}
return true;
}
|
diff --git a/src/org/geometerplus/fbreader/network/opds/OpenSearchDescription.java b/src/org/geometerplus/fbreader/network/opds/OpenSearchDescription.java
index 5dbd8de0..147ee1e1 100644
--- a/src/org/geometerplus/fbreader/network/opds/OpenSearchDescription.java
+++ b/src/org/geometerplus/fbreader/network/opds/OpenSearchDescription.java
@@ -1,89 +1,89 @@
/*
* Copyright (C) 2010-2011 Geometer Plus <[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., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
package org.geometerplus.fbreader.network.opds;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class OpenSearchDescription {
public static OpenSearchDescription createDefault(String template) {
return new OpenSearchDescription(template, -1, -1);
}
public final String Template;
public final int IndexOffset;
public final int PageOffset;
public final int ItemsPerPage = 20;
OpenSearchDescription(String template, int indexOffset, int pageOffset) {
Template = template;
IndexOffset = indexOffset;
PageOffset = pageOffset;
}
public boolean isValid() {
return makeQuery("") != null;
}
// searchTerms -- an HTML-encoded string
public String makeQuery(String searchTerms) {
final StringBuffer query = new StringBuffer();
- final Matcher m = Pattern.compile("\\{(.*)\\}").matcher(Template);
+ final Matcher m = Pattern.compile("\\{([^}]*)\\}").matcher(Template);
while (m.find()) {
String name = m.group(1);
if (name == null || name.length() == 0 || name.contains(":")) {
return null;
}
final boolean optional = name.endsWith("?");
if (optional) {
name = name.substring(0, name.length() - 1);
}
name = name.intern();
if (name == "searchTerms") {
m.appendReplacement(query, searchTerms);
} else if (name == "count") {
m.appendReplacement(query, String.valueOf(ItemsPerPage));
} else if (optional) {
m.appendReplacement(query, "");
} else if (name == "startIndex") {
if (IndexOffset > 0) {
m.appendReplacement(query, String.valueOf(IndexOffset));
} else {
return null;
}
} else if (name == "startPage") {
if (PageOffset > 0) {
m.appendReplacement(query, String.valueOf(PageOffset));
} else {
return null;
}
} else if (name == "language") {
m.appendReplacement(query, "*");
} else if (name == "inputEncoding" || name == "outputEncoding") {
m.appendReplacement(query, "UTF-8");
} else {
return null;
}
}
m.appendTail(query);
return query.toString();
}
}
| true | true | public String makeQuery(String searchTerms) {
final StringBuffer query = new StringBuffer();
final Matcher m = Pattern.compile("\\{(.*)\\}").matcher(Template);
while (m.find()) {
String name = m.group(1);
if (name == null || name.length() == 0 || name.contains(":")) {
return null;
}
final boolean optional = name.endsWith("?");
if (optional) {
name = name.substring(0, name.length() - 1);
}
name = name.intern();
if (name == "searchTerms") {
m.appendReplacement(query, searchTerms);
} else if (name == "count") {
m.appendReplacement(query, String.valueOf(ItemsPerPage));
} else if (optional) {
m.appendReplacement(query, "");
} else if (name == "startIndex") {
if (IndexOffset > 0) {
m.appendReplacement(query, String.valueOf(IndexOffset));
} else {
return null;
}
} else if (name == "startPage") {
if (PageOffset > 0) {
m.appendReplacement(query, String.valueOf(PageOffset));
} else {
return null;
}
} else if (name == "language") {
m.appendReplacement(query, "*");
} else if (name == "inputEncoding" || name == "outputEncoding") {
m.appendReplacement(query, "UTF-8");
} else {
return null;
}
}
m.appendTail(query);
return query.toString();
}
| public String makeQuery(String searchTerms) {
final StringBuffer query = new StringBuffer();
final Matcher m = Pattern.compile("\\{([^}]*)\\}").matcher(Template);
while (m.find()) {
String name = m.group(1);
if (name == null || name.length() == 0 || name.contains(":")) {
return null;
}
final boolean optional = name.endsWith("?");
if (optional) {
name = name.substring(0, name.length() - 1);
}
name = name.intern();
if (name == "searchTerms") {
m.appendReplacement(query, searchTerms);
} else if (name == "count") {
m.appendReplacement(query, String.valueOf(ItemsPerPage));
} else if (optional) {
m.appendReplacement(query, "");
} else if (name == "startIndex") {
if (IndexOffset > 0) {
m.appendReplacement(query, String.valueOf(IndexOffset));
} else {
return null;
}
} else if (name == "startPage") {
if (PageOffset > 0) {
m.appendReplacement(query, String.valueOf(PageOffset));
} else {
return null;
}
} else if (name == "language") {
m.appendReplacement(query, "*");
} else if (name == "inputEncoding" || name == "outputEncoding") {
m.appendReplacement(query, "UTF-8");
} else {
return null;
}
}
m.appendTail(query);
return query.toString();
}
|
diff --git a/pipesFilters/src/main/java/edu/integration/patterns/Main.java b/pipesFilters/src/main/java/edu/integration/patterns/Main.java
index be2d97e..44b1843 100644
--- a/pipesFilters/src/main/java/edu/integration/patterns/Main.java
+++ b/pipesFilters/src/main/java/edu/integration/patterns/Main.java
@@ -1,34 +1,34 @@
package edu.integration.patterns;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import edu.integration.patterns.reseller.Reseller;
/**
* Entry point
*
* @author Diyan Yordanov
*
*/
public final class Main {
private static final String USERNAME = "dido";
private static final String PASSWORD = "pass";
private static final long ITEM_ID = 23542345;
public static void main(String[] args) {
// Initialize Spring application context
ApplicationContext ac = new ClassPathXmlApplicationContext(
"classpath:META-INF/spring/integration/spring-integration-context.xml");
// Get the reseller bean
Reseller testService = ac.getBean(Reseller.class);
- // Send orde rto the reseller
+ // Send order to the reseller
OrderBean order = new OrderBean(USERNAME, PASSWORD, ITEM_ID);
testService.buy(order);
}
}
| true | true | public static void main(String[] args) {
// Initialize Spring application context
ApplicationContext ac = new ClassPathXmlApplicationContext(
"classpath:META-INF/spring/integration/spring-integration-context.xml");
// Get the reseller bean
Reseller testService = ac.getBean(Reseller.class);
// Send orde rto the reseller
OrderBean order = new OrderBean(USERNAME, PASSWORD, ITEM_ID);
testService.buy(order);
}
| public static void main(String[] args) {
// Initialize Spring application context
ApplicationContext ac = new ClassPathXmlApplicationContext(
"classpath:META-INF/spring/integration/spring-integration-context.xml");
// Get the reseller bean
Reseller testService = ac.getBean(Reseller.class);
// Send order to the reseller
OrderBean order = new OrderBean(USERNAME, PASSWORD, ITEM_ID);
testService.buy(order);
}
|
diff --git a/grid-incubation/incubator/projects/ExtendedSDK43QueryProcessor/projects/SDK43SortLimitQueryProcessor/src/org/cagrid/sdkquery43/extension/processor/CustomQueryProcessor.java b/grid-incubation/incubator/projects/ExtendedSDK43QueryProcessor/projects/SDK43SortLimitQueryProcessor/src/org/cagrid/sdkquery43/extension/processor/CustomQueryProcessor.java
index 47864291..1cb97f9f 100644
--- a/grid-incubation/incubator/projects/ExtendedSDK43QueryProcessor/projects/SDK43SortLimitQueryProcessor/src/org/cagrid/sdkquery43/extension/processor/CustomQueryProcessor.java
+++ b/grid-incubation/incubator/projects/ExtendedSDK43QueryProcessor/projects/SDK43SortLimitQueryProcessor/src/org/cagrid/sdkquery43/extension/processor/CustomQueryProcessor.java
@@ -1,574 +1,574 @@
package org.cagrid.sdkquery43.extension.processor;
import gov.nih.nci.cagrid.common.Utils;
import gov.nih.nci.cagrid.data.InitializationException;
import gov.nih.nci.cagrid.data.MalformedQueryException;
import gov.nih.nci.cagrid.data.QueryProcessingException;
import gov.nih.nci.cagrid.data.cql2.CQL2QueryProcessor;
import gov.nih.nci.system.applicationservice.ApplicationService;
import gov.nih.nci.system.client.ApplicationServiceProvider;
import gov.nih.nci.system.client.util.xml.XMLUtility;
import gov.nih.nci.system.client.util.xml.XMLUtilityException;
import gov.nih.nci.system.query.hibernate.HQLCriteria;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Properties;
import javax.xml.namespace.QName;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.cagrid.cql.utilities.AnyNodeHelper;
import org.cagrid.cql.utilities.CQL2SerializationUtil;
import org.cagrid.cql2.Aggregation;
import org.cagrid.cql2.CQLQuery;
import org.cagrid.cql2.CQLQueryModifier;
import org.cagrid.cql2.NamedAttribute;
import org.cagrid.cql2.results.CQLAggregateResult;
import org.cagrid.cql2.results.CQLAttributeResult;
import org.cagrid.cql2.results.CQLObjectResult;
import org.cagrid.cql2.results.CQLQueryResults;
import org.cagrid.cql2.results.CQLResult;
import org.cagrid.cql2.results.TargetAttribute;
import org.cagrid.iso21090.sdkquery.translator.ConstantValueResolver;
import org.cagrid.iso21090.sdkquery.translator.IsoDatatypesConstantValueResolver;
import org.cagrid.iso21090.sdkquery.translator.ParameterizedHqlQuery;
//import org.cagrid.iso21090.sdkquery.translator.cql2.CQL2ToParameterizedHQL;
import org.cagrid.iso21090.sdkquery.translator.cql2.Cql2TypesInformationResolver;
import org.cagrid.iso21090.sdkquery.translator.cql2.HibernateConfigCql2TypesInformationResolver;
import org.exolab.castor.types.AnyNode;
import org.globus.wsrf.security.SecurityManager;
import org.hibernate.cfg.Configuration;
import org.cagrid.sdkquery43.extension.translator.ExtendedCQL2ToParameterizedHQL;
/**
* CustomQueryProcessor
* CQL 2 Query processor for caCORE SDK 4.3 with ISO 21090 data types
* Added Extensions
*
* @author David W. Ervin
*/
public class CustomQueryProcessor extends CQL2QueryProcessor {
private static Log LOG = LogFactory.getLog(CustomQueryProcessor.class);
// general configuration options
public static final String PROPERTY_APPLICATION_NAME = "applicationName";
public static final String PROPERTY_USE_LOCAL_API = "useLocalApiFlag";
// remote service configuration properties
public static final String PROPERTY_HOST_NAME = "applicationHostName";
public static final String PROPERTY_HOST_PORT = "applicationHostPort";
public static final String PROPERTY_HOST_HTTPS = "useHttpsUrl";
// security configuration properties
public static final String PROPERTY_USE_GRID_IDENTITY_LOGIN = "useGridIdentityLogin";
public static final String PROPERTY_USE_STATIC_LOGIN = "useStaticLogin";
public static final String PROPERTY_STATIC_LOGIN_USER = "staticLoginUser";
public static final String PROPERTY_STATIC_LOGIN_PASS = "staticLoginPass";
// default values for properties
public static final String DEFAULT_USE_LOCAL_API = String.valueOf(false);
public static final String DEFAULT_HOST_HTTPS = String.valueOf(false);
public static final String DEFAULT_USE_GRID_IDENTITY_LOGIN = String.valueOf(false);
public static final String DEFAULT_USE_STATIC_LOGIN = String.valueOf(false);
private ExtendedCQL2ToParameterizedHQL cqlTranslator = null;
private QNameResolver qnameResolver = null;
private byte[] wsddBytes = null;
public CustomQueryProcessor() {
super();
}
public Properties getRequiredParameters() {
Properties props = super.getRequiredParameters();
props.setProperty(PROPERTY_APPLICATION_NAME, "");
props.setProperty(PROPERTY_USE_LOCAL_API, DEFAULT_USE_LOCAL_API);
props.setProperty(PROPERTY_HOST_NAME, "");
props.setProperty(PROPERTY_HOST_PORT, "");
props.setProperty(PROPERTY_HOST_HTTPS, DEFAULT_HOST_HTTPS);
props.setProperty(PROPERTY_USE_GRID_IDENTITY_LOGIN, DEFAULT_USE_GRID_IDENTITY_LOGIN);
props.setProperty(PROPERTY_USE_STATIC_LOGIN, DEFAULT_USE_STATIC_LOGIN);
props.setProperty(PROPERTY_STATIC_LOGIN_USER, "");
props.setProperty(PROPERTY_STATIC_LOGIN_PASS, "");
return props;
}
public void initialize() throws InitializationException {
// verify that if we're using grid identity login, we're also using the Local API
if (isUseGridIdentLogin() && !isUseLocalApi()) {
throw new InitializationException("Grid identity + CSM authentication can only be used with the local API!");
}
// verify we have a URL for the remote API
if (!isUseLocalApi()) {
try {
new URL(getRemoteApplicationUrl());
} catch (MalformedURLException ex) {
throw new InitializationException("Could not determine a remote API url: " + ex.getMessage(), ex);
}
}
}
public CQLQueryResults processQuery(CQLQuery cqlQuery) throws MalformedQueryException, QueryProcessingException {
LOG.debug("Starting process query");
Iterator<CQLResult> resultIter = processQueryAndIterate(cqlQuery);
LOG.debug("Converting iterated results to static results");
CQLQueryResults results = new CQLQueryResults();
results.setTargetClassname(cqlQuery.getCQLTargetObject().getClassName());
List<CQLObjectResult> objectResults = new LinkedList<CQLObjectResult>();
List<CQLAttributeResult> attributeResults = new LinkedList<CQLAttributeResult>();
CQLAggregateResult aggregateResult = null;
while (resultIter.hasNext()) {
CQLResult result = resultIter.next();
if (result instanceof CQLObjectResult) {
objectResults.add((CQLObjectResult) result);
} else if (result instanceof CQLAttributeResult) {
attributeResults.add((CQLAttributeResult) result);
} else if (result instanceof CQLAggregateResult) {
aggregateResult = (CQLAggregateResult) result;
}
}
if (objectResults.size() != 0) {
results.setObjectResult(objectResults.toArray(new CQLObjectResult[0]));
} else if (attributeResults.size() != 0) {
results.setAttributeResult(attributeResults.toArray(new CQLAttributeResult[0]));
} else {
results.setAggregationResult(aggregateResult);
}
return results;
}
public Iterator<CQLResult> processQueryAndIterate(CQLQuery query) throws QueryProcessingException {
LOG.debug("Starting process query and iterate results");
CQLQuery runQuery = query;
if (runQuery.getCQLQueryModifier() != null && runQuery.getCQLQueryModifier().getNamedAttribute() != null) {
LOG.debug("Cloning query and editing modifier for unique result tuples");
// HQL will return distinct tuples of attribute names, so we need to include
// the id attribute in those tuples to get a 1:1 correspondence with
// actual data instances in the database
try {
runQuery = CQL2SerializationUtil.cloneQueryBean(query);
NamedAttribute[] namedAttributes = runQuery.getCQLQueryModifier().getNamedAttribute();
NamedAttribute idAttribute = new NamedAttribute("id");
namedAttributes = (NamedAttribute[]) Utils.appendToArray(namedAttributes, idAttribute);
runQuery.getCQLQueryModifier().setNamedAttribute(namedAttributes);
} catch (Exception ex) {
String message = "Error pre-processing query modifier attribute names: " + ex.getMessage();
LOG.error(message, ex);
throw new QueryProcessingException(message, ex);
}
}
// get an instance of the caCORE SDK ApplicationService
ApplicationService sdkService = getApplicationService();
// empty results object
CQLQueryResults queryResults = new CQLQueryResults();
queryResults.setTargetClassname(query.getCQLTargetObject().getClassName());
// convert the CQL to HQL
LOG.debug("Converting CQL query to HQL");
ParameterizedHqlQuery hql = null;
HashMap<String, Object> queryMap;
try {
this.cqlTranslator = getCqlTranslator();
queryMap = cqlTranslator.convertToHql(runQuery);
- hql = (ParameterizedHqlQuery) queryMap.get("hql");
+ hql = (ParameterizedHqlQuery) queryMap.get("ParameterizedHqlQuery");
LOG.debug("Created HQL: " + hql.toString());
} catch (QueryProcessingException ex) {
throw ex;
} catch (Exception ex) {
throw new QueryProcessingException("Error processing query: " + ex.getMessage(), ex);
}
// Process the Limit Extension if it exists
HQLCriteria criteria = null;
if (queryMap.containsKey("firstRow")) {
Integer firstRow = (Integer) queryMap.get("firstRow");
if (queryMap.containsKey("numberOfRows")) {
Integer numberOfRows = (Integer) queryMap.get("numberOfRows");
criteria = new HQLCriteria(hql.getHql(), hql.getParameters(), firstRow.intValue(), numberOfRows.intValue());
} else {
criteria = new HQLCriteria(hql.getHql(), hql.getParameters(), firstRow.intValue());
}
}
else {
criteria = new HQLCriteria(hql.getHql(), hql.getParameters());
}
// query the SDK
LOG.debug("Querying application service");
List<Object> rawResults = null;
try {
rawResults = sdkService.query(criteria);
} catch (Exception ex) {
String message = "Error querying caCORE service: " + ex.getMessage();
LOG.error(message, ex);
throw new QueryProcessingException(message, ex);
}
LOG.debug("Results obtained from application service");
Iterator<CQLResult> cqlResultsIter = null;
// see if there is further processing to be done
if (runQuery.getCQLQueryModifier() != null) {
LOG.debug("Post-processing query modifiers");
CQLQueryModifier mods = runQuery.getCQLQueryModifier();
if (mods.getNamedAttribute() != null) {
LOG.debug("Detected named attribute results");
// trim off the extra id attribute we added earlier
String[] attributeNames = new String[mods.getNamedAttribute().length - 1];
for (int i = 0; i < attributeNames.length; i++) {
attributeNames[i] = mods.getNamedAttribute(i).getAttributeName();
}
// this will happily ignore the last value which is the extra ID attribute
cqlResultsIter = wrapAttributeResult(attributeNames, rawResults);
} else if (mods.getCountOnly() != null && mods.getCountOnly().booleanValue()) {
LOG.debug("Detected count-only aggregate results");
Object resultValue = rawResults.size() != 0 ? rawResults.get(0) : null;
String valueAsString = attributeValueAsString(resultValue);
cqlResultsIter = wrapAggregateResult(Aggregation.COUNT, "id", valueAsString);
} else if (mods.getDistinctAttribute() != null) {
LOG.debug("Detected distinct attribute results");
if (mods.getDistinctAttribute().getAggregation() != null) {
LOG.debug("Detected aggregate results");
Aggregation agg = mods.getDistinctAttribute().getAggregation();
Object resultValue = rawResults.size() != 0 ? rawResults.get(0) : null;
String valueAsString = attributeValueAsString(resultValue);
cqlResultsIter = wrapAggregateResult(agg, mods.getDistinctAttribute().getAttributeName(), valueAsString);
} else {
// standard attribute name / value pairs
cqlResultsIter = wrapAttributeResult(
new String[]{mods.getDistinctAttribute().getAttributeName()}, rawResults);
}
} else if (mods.getModifierExtension() != null) {
LOG.debug("Detected Modifier Extension");
QName targetQName = null;
try {
targetQName = getQNameResolver().getQName(query.getCQLTargetObject().getClassName());
} catch (Exception ex) {
throw new QueryProcessingException("Error obtaining QName for target data type: " + ex.getMessage(), ex);
}
cqlResultsIter = wrapObjectResults(rawResults, targetQName);
}
} else {
LOG.debug("Detected object results");
QName targetQName = null;
try {
targetQName = getQNameResolver().getQName(query.getCQLTargetObject().getClassName());
} catch (Exception ex) {
throw new QueryProcessingException("Error obtaining QName for target data type: " + ex.getMessage(), ex);
}
cqlResultsIter = wrapObjectResults(rawResults, targetQName);
}
return cqlResultsIter;
}
private Iterator<CQLResult> wrapObjectResults(List<Object> rawObjects, final QName targetQName) {
final Iterator<Object> rawObjectIter = rawObjects.iterator();
Iterator<CQLResult> objectIter = new Iterator<CQLResult>() {
public boolean hasNext() {
return rawObjectIter.hasNext();
}
public CQLResult next() {
CQLObjectResult obj = new CQLObjectResult();
Object rawObject = rawObjectIter.next();
LOG.debug("Stripping proxy impl from result instance");
try {
// TODO: should the association flag be false / true?
rawObject = XMLUtility.convertFromProxy(rawObject, false);
} catch (XMLUtilityException ex) {
LOG.error("Error stripping proxy from result instance: " + ex.getMessage(), ex);
throw new NoSuchElementException("Error stripping proxy from result instance: " + ex.getMessage());
}
StringWriter writer = new StringWriter();
try {
InputStream wsdd = getDisposableWsdd();
Utils.serializeObject(rawObject, targetQName, writer, wsdd);
} catch (Exception ex) {
String message = "Error pre-serializing object result: " + ex.getMessage();
LOG.error(message, ex);
NoSuchElementException nse = new NoSuchElementException(message);
nse.initCause(ex);
throw nse;
}
AnyNode node = null;
try {
node = AnyNodeHelper.convertStringToAnyNode(
writer.getBuffer().toString());
} catch (Exception ex) {
String message = "Error creating AnyNode for object results: " + ex.getMessage();
LOG.error(message, ex);
NoSuchElementException nse = new NoSuchElementException(message);
nse.initCause(ex);
throw nse;
}
obj.set_any(node);
return obj;
}
public void remove() {
throw new UnsupportedOperationException("remove() is not supported");
}
};
return objectIter;
}
private Iterator<CQLResult> wrapAggregateResult(Aggregation agg, String attributeName, String value) {
final CQLAggregateResult result = new CQLAggregateResult();
result.setAggregation(agg);
result.setAttributeName(attributeName);
result.setValue(value);
Iterator<CQLResult> iter = new Iterator<CQLResult>() {
boolean hasBeenReturned = false;
public boolean hasNext() {
return !hasBeenReturned;
}
public synchronized CQLResult next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
hasBeenReturned = true;
return result;
}
public void remove() {
throw new UnsupportedOperationException("remove() is not supported");
}
};
return iter;
}
private Iterator<CQLResult> wrapAttributeResult(final String[] attributeNames, List<Object> attributeValues) {
final Iterator<Object> rawValueIter = attributeValues.iterator();
Iterator<CQLResult> iter = new Iterator<CQLResult>() {
public boolean hasNext() {
return rawValueIter.hasNext();
}
public synchronized CQLResult next() {
Object[] values = arrayify(rawValueIter.next());
CQLAttributeResult result = new CQLAttributeResult();
TargetAttribute[] ta = new TargetAttribute[attributeNames.length];
for (int i = 0; i < attributeNames.length; i++) {
Object val = values[i];
ta[i] = new TargetAttribute(attributeNames[i], attributeValueAsString(val));
}
result.setAttribute(ta);
return result;
}
public void remove() {
throw new UnsupportedOperationException("remove() is not supported");
}
private Object[] arrayify(Object o) {
if (o != null && o.getClass().isArray()) {
return (Object[]) o;
}
return new Object[] {o};
}
};
return iter;
}
private String attributeValueAsString(Object val) {
String valAsString = null;
if (val != null) {
if (val instanceof Date) {
valAsString = DateFormat.getDateTimeInstance().format((Date) val);
} else {
valAsString = String.valueOf(val);
}
}
return valAsString;
}
private ExtendedCQL2ToParameterizedHQL getCqlTranslator() throws Exception {
if (cqlTranslator == null) {
LOG.debug("Locating Hibernate configuration");
InputStream configStream = getClass().getResourceAsStream("/hibernate.cfg.xml");
Configuration config = new Configuration();
config.addInputStream(configStream);
config.configure();
configStream.close();
LOG.debug("Initializing types information resolver");
Cql2TypesInformationResolver typesInfoResolver = new HibernateConfigCql2TypesInformationResolver(config, true);
LOG.debug("Loading ISO constant resolver");
ConstantValueResolver constantResolver = new IsoDatatypesConstantValueResolver();
LOG.debug("Initializing CQL 2 to HQL translator");
cqlTranslator = new ExtendedCQL2ToParameterizedHQL(typesInfoResolver, constantResolver, false);
}
return cqlTranslator;
}
private boolean isUseLocalApi() {
boolean useLocal = Boolean.parseBoolean(DEFAULT_USE_LOCAL_API);
String useLocalApiValue = getConfiguredParameters().getProperty(PROPERTY_USE_LOCAL_API);
try {
useLocal = Boolean.parseBoolean(useLocalApiValue);
} catch (Exception ex) {
LOG.error("Error parsing property " + PROPERTY_USE_LOCAL_API
+ ". Value was " + useLocalApiValue, ex);
}
return useLocal;
}
private boolean isUseGridIdentLogin() {
boolean useGridIdent = Boolean.parseBoolean(DEFAULT_USE_GRID_IDENTITY_LOGIN);
String useGridIdentValue = getConfiguredParameters().getProperty(PROPERTY_USE_GRID_IDENTITY_LOGIN);
try {
useGridIdent = Boolean.parseBoolean(useGridIdentValue);
} catch (Exception ex) {
LOG.error("Error parsing property " + PROPERTY_USE_GRID_IDENTITY_LOGIN
+ ". Value was " + useGridIdentValue, ex);
}
return useGridIdent;
}
private boolean isUseStaticLogin() {
boolean useStatic = false;
String useStaticValue = getConfiguredParameters().getProperty(PROPERTY_USE_STATIC_LOGIN);
try {
useStatic = Boolean.parseBoolean(useStaticValue);
} catch (Exception ex) {
LOG.error("Error parsing property " + PROPERTY_USE_STATIC_LOGIN
+ ". Value was " + useStaticValue, ex);
}
return useStatic;
}
private boolean isUseHttps() {
boolean useHttps = Boolean.parseBoolean(DEFAULT_HOST_HTTPS);
String useHttpsValue = getConfiguredParameters().getProperty(PROPERTY_HOST_HTTPS);
try {
useHttps = Boolean.parseBoolean(useHttpsValue);
} catch (Exception ex) {
LOG.error("Error parsing property " + PROPERTY_HOST_HTTPS
+ ". Value was " + useHttpsValue, ex);
}
return useHttps;
}
private String getStaticLoginUser() {
return getConfiguredParameters().getProperty(PROPERTY_STATIC_LOGIN_USER);
}
private String getStaticLoginPass() {
return getConfiguredParameters().getProperty(PROPERTY_STATIC_LOGIN_PASS);
}
private String getRemoteApplicationUrl() {
StringBuffer url = new StringBuffer();
if (isUseHttps()) {
url.append("https://");
} else {
url.append("http://");
}
url.append(getConfiguredParameters().getProperty(PROPERTY_HOST_NAME));
url.append(":");
url.append(getConfiguredParameters().getProperty(PROPERTY_HOST_PORT));
url.append("/");
url.append(getConfiguredParameters().getProperty(PROPERTY_APPLICATION_NAME));
String completedUrl = url.toString();
LOG.debug("Application Service remote URL determined to be: " + completedUrl);
return completedUrl;
}
private ApplicationService getApplicationService() throws QueryProcessingException {
LOG.debug("Getting caCORE SDK application service instance");
ApplicationService service = null;
try {
if (isUseLocalApi()) {
LOG.debug("Using Local API");
if (isUseGridIdentLogin()) {
LOG.debug("Using grid identity login");
SecurityManager securityManager = SecurityManager.getManager();
String username = securityManager.getCaller();
LOG.trace("Identity determined to be " + username);
service = ApplicationServiceProvider.getApplicationServiceForUser(username);
} else {
service = ApplicationServiceProvider.getApplicationService();
}
} else {
LOG.debug("Using Remote API");
String url = getRemoteApplicationUrl();
if (isUseStaticLogin()) {
LOG.debug("Using static login");
String username = getStaticLoginUser();
String password = getStaticLoginPass();
service = ApplicationServiceProvider.getApplicationServiceFromUrl(url, username, password);
} else {
service = ApplicationServiceProvider.getApplicationServiceFromUrl(url);
}
}
} catch (Exception ex) {
throw new QueryProcessingException("Error obtaining application service: " + ex.getMessage(), ex);
}
return service;
}
private QNameResolver getQNameResolver() throws Exception {
if (qnameResolver == null) {
qnameResolver = new MappingFileQNameResolver(getClassToQnameMappings());
}
return qnameResolver;
}
private InputStream getDisposableWsdd() throws IOException {
if (wsddBytes == null) {
wsddBytes = Utils.inputStreamToByteArray(getConfiguredWsddStream());
}
return new ByteArrayInputStream(wsddBytes);
}
}
| true | true | public Iterator<CQLResult> processQueryAndIterate(CQLQuery query) throws QueryProcessingException {
LOG.debug("Starting process query and iterate results");
CQLQuery runQuery = query;
if (runQuery.getCQLQueryModifier() != null && runQuery.getCQLQueryModifier().getNamedAttribute() != null) {
LOG.debug("Cloning query and editing modifier for unique result tuples");
// HQL will return distinct tuples of attribute names, so we need to include
// the id attribute in those tuples to get a 1:1 correspondence with
// actual data instances in the database
try {
runQuery = CQL2SerializationUtil.cloneQueryBean(query);
NamedAttribute[] namedAttributes = runQuery.getCQLQueryModifier().getNamedAttribute();
NamedAttribute idAttribute = new NamedAttribute("id");
namedAttributes = (NamedAttribute[]) Utils.appendToArray(namedAttributes, idAttribute);
runQuery.getCQLQueryModifier().setNamedAttribute(namedAttributes);
} catch (Exception ex) {
String message = "Error pre-processing query modifier attribute names: " + ex.getMessage();
LOG.error(message, ex);
throw new QueryProcessingException(message, ex);
}
}
// get an instance of the caCORE SDK ApplicationService
ApplicationService sdkService = getApplicationService();
// empty results object
CQLQueryResults queryResults = new CQLQueryResults();
queryResults.setTargetClassname(query.getCQLTargetObject().getClassName());
// convert the CQL to HQL
LOG.debug("Converting CQL query to HQL");
ParameterizedHqlQuery hql = null;
HashMap<String, Object> queryMap;
try {
this.cqlTranslator = getCqlTranslator();
queryMap = cqlTranslator.convertToHql(runQuery);
hql = (ParameterizedHqlQuery) queryMap.get("hql");
LOG.debug("Created HQL: " + hql.toString());
} catch (QueryProcessingException ex) {
throw ex;
} catch (Exception ex) {
throw new QueryProcessingException("Error processing query: " + ex.getMessage(), ex);
}
// Process the Limit Extension if it exists
HQLCriteria criteria = null;
if (queryMap.containsKey("firstRow")) {
Integer firstRow = (Integer) queryMap.get("firstRow");
if (queryMap.containsKey("numberOfRows")) {
Integer numberOfRows = (Integer) queryMap.get("numberOfRows");
criteria = new HQLCriteria(hql.getHql(), hql.getParameters(), firstRow.intValue(), numberOfRows.intValue());
} else {
criteria = new HQLCriteria(hql.getHql(), hql.getParameters(), firstRow.intValue());
}
}
else {
criteria = new HQLCriteria(hql.getHql(), hql.getParameters());
}
// query the SDK
LOG.debug("Querying application service");
List<Object> rawResults = null;
try {
rawResults = sdkService.query(criteria);
} catch (Exception ex) {
String message = "Error querying caCORE service: " + ex.getMessage();
LOG.error(message, ex);
throw new QueryProcessingException(message, ex);
}
LOG.debug("Results obtained from application service");
Iterator<CQLResult> cqlResultsIter = null;
// see if there is further processing to be done
if (runQuery.getCQLQueryModifier() != null) {
LOG.debug("Post-processing query modifiers");
CQLQueryModifier mods = runQuery.getCQLQueryModifier();
if (mods.getNamedAttribute() != null) {
LOG.debug("Detected named attribute results");
// trim off the extra id attribute we added earlier
String[] attributeNames = new String[mods.getNamedAttribute().length - 1];
for (int i = 0; i < attributeNames.length; i++) {
attributeNames[i] = mods.getNamedAttribute(i).getAttributeName();
}
// this will happily ignore the last value which is the extra ID attribute
cqlResultsIter = wrapAttributeResult(attributeNames, rawResults);
} else if (mods.getCountOnly() != null && mods.getCountOnly().booleanValue()) {
LOG.debug("Detected count-only aggregate results");
Object resultValue = rawResults.size() != 0 ? rawResults.get(0) : null;
String valueAsString = attributeValueAsString(resultValue);
cqlResultsIter = wrapAggregateResult(Aggregation.COUNT, "id", valueAsString);
} else if (mods.getDistinctAttribute() != null) {
LOG.debug("Detected distinct attribute results");
if (mods.getDistinctAttribute().getAggregation() != null) {
LOG.debug("Detected aggregate results");
Aggregation agg = mods.getDistinctAttribute().getAggregation();
Object resultValue = rawResults.size() != 0 ? rawResults.get(0) : null;
String valueAsString = attributeValueAsString(resultValue);
cqlResultsIter = wrapAggregateResult(agg, mods.getDistinctAttribute().getAttributeName(), valueAsString);
} else {
// standard attribute name / value pairs
cqlResultsIter = wrapAttributeResult(
new String[]{mods.getDistinctAttribute().getAttributeName()}, rawResults);
}
} else if (mods.getModifierExtension() != null) {
LOG.debug("Detected Modifier Extension");
QName targetQName = null;
try {
targetQName = getQNameResolver().getQName(query.getCQLTargetObject().getClassName());
} catch (Exception ex) {
throw new QueryProcessingException("Error obtaining QName for target data type: " + ex.getMessage(), ex);
}
cqlResultsIter = wrapObjectResults(rawResults, targetQName);
}
} else {
LOG.debug("Detected object results");
QName targetQName = null;
try {
targetQName = getQNameResolver().getQName(query.getCQLTargetObject().getClassName());
} catch (Exception ex) {
throw new QueryProcessingException("Error obtaining QName for target data type: " + ex.getMessage(), ex);
}
cqlResultsIter = wrapObjectResults(rawResults, targetQName);
}
return cqlResultsIter;
}
| public Iterator<CQLResult> processQueryAndIterate(CQLQuery query) throws QueryProcessingException {
LOG.debug("Starting process query and iterate results");
CQLQuery runQuery = query;
if (runQuery.getCQLQueryModifier() != null && runQuery.getCQLQueryModifier().getNamedAttribute() != null) {
LOG.debug("Cloning query and editing modifier for unique result tuples");
// HQL will return distinct tuples of attribute names, so we need to include
// the id attribute in those tuples to get a 1:1 correspondence with
// actual data instances in the database
try {
runQuery = CQL2SerializationUtil.cloneQueryBean(query);
NamedAttribute[] namedAttributes = runQuery.getCQLQueryModifier().getNamedAttribute();
NamedAttribute idAttribute = new NamedAttribute("id");
namedAttributes = (NamedAttribute[]) Utils.appendToArray(namedAttributes, idAttribute);
runQuery.getCQLQueryModifier().setNamedAttribute(namedAttributes);
} catch (Exception ex) {
String message = "Error pre-processing query modifier attribute names: " + ex.getMessage();
LOG.error(message, ex);
throw new QueryProcessingException(message, ex);
}
}
// get an instance of the caCORE SDK ApplicationService
ApplicationService sdkService = getApplicationService();
// empty results object
CQLQueryResults queryResults = new CQLQueryResults();
queryResults.setTargetClassname(query.getCQLTargetObject().getClassName());
// convert the CQL to HQL
LOG.debug("Converting CQL query to HQL");
ParameterizedHqlQuery hql = null;
HashMap<String, Object> queryMap;
try {
this.cqlTranslator = getCqlTranslator();
queryMap = cqlTranslator.convertToHql(runQuery);
hql = (ParameterizedHqlQuery) queryMap.get("ParameterizedHqlQuery");
LOG.debug("Created HQL: " + hql.toString());
} catch (QueryProcessingException ex) {
throw ex;
} catch (Exception ex) {
throw new QueryProcessingException("Error processing query: " + ex.getMessage(), ex);
}
// Process the Limit Extension if it exists
HQLCriteria criteria = null;
if (queryMap.containsKey("firstRow")) {
Integer firstRow = (Integer) queryMap.get("firstRow");
if (queryMap.containsKey("numberOfRows")) {
Integer numberOfRows = (Integer) queryMap.get("numberOfRows");
criteria = new HQLCriteria(hql.getHql(), hql.getParameters(), firstRow.intValue(), numberOfRows.intValue());
} else {
criteria = new HQLCriteria(hql.getHql(), hql.getParameters(), firstRow.intValue());
}
}
else {
criteria = new HQLCriteria(hql.getHql(), hql.getParameters());
}
// query the SDK
LOG.debug("Querying application service");
List<Object> rawResults = null;
try {
rawResults = sdkService.query(criteria);
} catch (Exception ex) {
String message = "Error querying caCORE service: " + ex.getMessage();
LOG.error(message, ex);
throw new QueryProcessingException(message, ex);
}
LOG.debug("Results obtained from application service");
Iterator<CQLResult> cqlResultsIter = null;
// see if there is further processing to be done
if (runQuery.getCQLQueryModifier() != null) {
LOG.debug("Post-processing query modifiers");
CQLQueryModifier mods = runQuery.getCQLQueryModifier();
if (mods.getNamedAttribute() != null) {
LOG.debug("Detected named attribute results");
// trim off the extra id attribute we added earlier
String[] attributeNames = new String[mods.getNamedAttribute().length - 1];
for (int i = 0; i < attributeNames.length; i++) {
attributeNames[i] = mods.getNamedAttribute(i).getAttributeName();
}
// this will happily ignore the last value which is the extra ID attribute
cqlResultsIter = wrapAttributeResult(attributeNames, rawResults);
} else if (mods.getCountOnly() != null && mods.getCountOnly().booleanValue()) {
LOG.debug("Detected count-only aggregate results");
Object resultValue = rawResults.size() != 0 ? rawResults.get(0) : null;
String valueAsString = attributeValueAsString(resultValue);
cqlResultsIter = wrapAggregateResult(Aggregation.COUNT, "id", valueAsString);
} else if (mods.getDistinctAttribute() != null) {
LOG.debug("Detected distinct attribute results");
if (mods.getDistinctAttribute().getAggregation() != null) {
LOG.debug("Detected aggregate results");
Aggregation agg = mods.getDistinctAttribute().getAggregation();
Object resultValue = rawResults.size() != 0 ? rawResults.get(0) : null;
String valueAsString = attributeValueAsString(resultValue);
cqlResultsIter = wrapAggregateResult(agg, mods.getDistinctAttribute().getAttributeName(), valueAsString);
} else {
// standard attribute name / value pairs
cqlResultsIter = wrapAttributeResult(
new String[]{mods.getDistinctAttribute().getAttributeName()}, rawResults);
}
} else if (mods.getModifierExtension() != null) {
LOG.debug("Detected Modifier Extension");
QName targetQName = null;
try {
targetQName = getQNameResolver().getQName(query.getCQLTargetObject().getClassName());
} catch (Exception ex) {
throw new QueryProcessingException("Error obtaining QName for target data type: " + ex.getMessage(), ex);
}
cqlResultsIter = wrapObjectResults(rawResults, targetQName);
}
} else {
LOG.debug("Detected object results");
QName targetQName = null;
try {
targetQName = getQNameResolver().getQName(query.getCQLTargetObject().getClassName());
} catch (Exception ex) {
throw new QueryProcessingException("Error obtaining QName for target data type: " + ex.getMessage(), ex);
}
cqlResultsIter = wrapObjectResults(rawResults, targetQName);
}
return cqlResultsIter;
}
|
diff --git a/core/Parser.java b/core/Parser.java
index 35ac83a..5dedee6 100644
--- a/core/Parser.java
+++ b/core/Parser.java
@@ -1,74 +1,74 @@
package core;
import java.lang.reflect.Method;
import java.lang.String;
import cmd.*;
/*
* Parser
* The Parser takes a raw String entered at the prompt. The general form
* for a command in Wormwood is cmd name arguments. For example, the user
* might type ”move e”. The Parser splits this input up into the command and
* the arguments. It then uses Java’s generic class constructors to
* dynamically create the Command class, based on whether or not it can find
* the corresponding cmd name.java file in the cmd package.
*/
public class Parser {
/** @param A raw command and turns it into something the game can understand*/
public static Object parse (String rawCmd) {
String cmd;
String[] params;
String[] stringParse;
// Remove leading/trailing whitespace
rawCmd = rawCmd.trim();
rawCmd = rawCmd.toLowerCase();
//Separate input into individual words and separate into the command and its parameters
stringParse = rawCmd.split(" ");
params = new String[stringParse.length - 1];
// Switch the first letter of the command name from lowercase to upper case
// So that it can be matched (eg, it's Look.java, not look.java)
cmd = handleData.upperFirst(stringParse[0]);
if(stringParse.length > 1)
params = handleData.removeFirst(stringParse);
// Default null cmd, unless proven otherwise
Object obj = null;
//Checks to see if an alias exists
if(Alias.exists(cmd)){
Alias curAlias = Alias.get(cmd);
//Adds the parameters passed to the alias to its param list
if(params.length > 0){
curAlias.addParams(params);
}
//Reassign the parameter list and the command to be run
-g params = curAlias.getParams();
+ params = curAlias.getParams();
cmd = handleData.upperFirst(curAlias.getCommand());
}
try {
//Try to create a class object for the inputted command
//TODO: dynamically create ReferenceType to be parameterized
//Create a new instance of this class
// Get the class object associated with the command name
Class tClass = Class.forName("cmd."+cmd);
obj = tClass.newInstance();
Object parameters[] = {params};
//Grab the method construct from the class
Method con = tClass.getMethod("construct", String[].class);
//Run construct on the object and pass it the parameters
con.invoke(obj, parameters);
} catch(java.lang.reflect.InvocationTargetException e){ //Catches an error within the construct
Output.println("Invalid parameters for command. Type 'help "+cmd+"' for options.");
//Set the object to null so the command won't try to run
obj = null;
} catch(Exception e){ //Catches an error when trying to create the class
Output.println("Invalid command. Type 'help' for a list of commands.");
}
return obj;
}
}
| true | true | public static Object parse (String rawCmd) {
String cmd;
String[] params;
String[] stringParse;
// Remove leading/trailing whitespace
rawCmd = rawCmd.trim();
rawCmd = rawCmd.toLowerCase();
//Separate input into individual words and separate into the command and its parameters
stringParse = rawCmd.split(" ");
params = new String[stringParse.length - 1];
// Switch the first letter of the command name from lowercase to upper case
// So that it can be matched (eg, it's Look.java, not look.java)
cmd = handleData.upperFirst(stringParse[0]);
if(stringParse.length > 1)
params = handleData.removeFirst(stringParse);
// Default null cmd, unless proven otherwise
Object obj = null;
//Checks to see if an alias exists
if(Alias.exists(cmd)){
Alias curAlias = Alias.get(cmd);
//Adds the parameters passed to the alias to its param list
if(params.length > 0){
curAlias.addParams(params);
}
//Reassign the parameter list and the command to be run
g params = curAlias.getParams();
cmd = handleData.upperFirst(curAlias.getCommand());
}
try {
//Try to create a class object for the inputted command
//TODO: dynamically create ReferenceType to be parameterized
//Create a new instance of this class
// Get the class object associated with the command name
Class tClass = Class.forName("cmd."+cmd);
obj = tClass.newInstance();
Object parameters[] = {params};
//Grab the method construct from the class
Method con = tClass.getMethod("construct", String[].class);
//Run construct on the object and pass it the parameters
con.invoke(obj, parameters);
} catch(java.lang.reflect.InvocationTargetException e){ //Catches an error within the construct
Output.println("Invalid parameters for command. Type 'help "+cmd+"' for options.");
//Set the object to null so the command won't try to run
obj = null;
} catch(Exception e){ //Catches an error when trying to create the class
Output.println("Invalid command. Type 'help' for a list of commands.");
}
return obj;
}
| public static Object parse (String rawCmd) {
String cmd;
String[] params;
String[] stringParse;
// Remove leading/trailing whitespace
rawCmd = rawCmd.trim();
rawCmd = rawCmd.toLowerCase();
//Separate input into individual words and separate into the command and its parameters
stringParse = rawCmd.split(" ");
params = new String[stringParse.length - 1];
// Switch the first letter of the command name from lowercase to upper case
// So that it can be matched (eg, it's Look.java, not look.java)
cmd = handleData.upperFirst(stringParse[0]);
if(stringParse.length > 1)
params = handleData.removeFirst(stringParse);
// Default null cmd, unless proven otherwise
Object obj = null;
//Checks to see if an alias exists
if(Alias.exists(cmd)){
Alias curAlias = Alias.get(cmd);
//Adds the parameters passed to the alias to its param list
if(params.length > 0){
curAlias.addParams(params);
}
//Reassign the parameter list and the command to be run
params = curAlias.getParams();
cmd = handleData.upperFirst(curAlias.getCommand());
}
try {
//Try to create a class object for the inputted command
//TODO: dynamically create ReferenceType to be parameterized
//Create a new instance of this class
// Get the class object associated with the command name
Class tClass = Class.forName("cmd."+cmd);
obj = tClass.newInstance();
Object parameters[] = {params};
//Grab the method construct from the class
Method con = tClass.getMethod("construct", String[].class);
//Run construct on the object and pass it the parameters
con.invoke(obj, parameters);
} catch(java.lang.reflect.InvocationTargetException e){ //Catches an error within the construct
Output.println("Invalid parameters for command. Type 'help "+cmd+"' for options.");
//Set the object to null so the command won't try to run
obj = null;
} catch(Exception e){ //Catches an error when trying to create the class
Output.println("Invalid command. Type 'help' for a list of commands.");
}
return obj;
}
|
diff --git a/src/java/davmail/exchange/VCalendar.java b/src/java/davmail/exchange/VCalendar.java
index ceb0bd7..3974958 100644
--- a/src/java/davmail/exchange/VCalendar.java
+++ b/src/java/davmail/exchange/VCalendar.java
@@ -1,567 +1,570 @@
/*
* DavMail POP/IMAP/SMTP/CalDav/LDAP Exchange Gateway
* Copyright (C) 2010 Mickael Guessant
*
* 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package davmail.exchange;
import davmail.Settings;
import davmail.util.StringUtil;
import org.apache.log4j.Logger;
import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* VCalendar object.
*/
public class VCalendar extends VObject {
protected static final Logger LOGGER = Logger.getLogger(VCalendar.class);
protected VObject firstVevent;
protected VObject vTimezone;
protected String email;
/**
* Create VCalendar object from reader;
*
* @param reader stream reader
* @param email current user email
* @param vTimezone user OWA timezone
* @throws IOException on error
*/
public VCalendar(BufferedReader reader, String email, VObject vTimezone) throws IOException {
super(reader);
if (!"VCALENDAR".equals(type)) {
throw new IOException("Invalid type: " + type);
}
this.email = email;
// set OWA timezone information
if (this.vTimezone == null && vTimezone != null) {
this.vObjects.add(0, vTimezone);
this.vTimezone = vTimezone;
}
}
/**
* Create VCalendar object from string;
*
* @param vCalendarBody item body
* @param email current user email
* @param vTimezone user OWA timezone
* @throws IOException on error
*/
public VCalendar(String vCalendarBody, String email, VObject vTimezone) throws IOException {
this(new ICSBufferedReader(new StringReader(vCalendarBody)), email, vTimezone);
}
/**
* Create VCalendar object from string;
*
* @param vCalendarContent item content
* @param email current user email
* @param vTimezone user OWA timezone
* @throws IOException on error
*/
public VCalendar(byte[] vCalendarContent, String email, VObject vTimezone) throws IOException {
this(new ICSBufferedReader(new InputStreamReader(new ByteArrayInputStream(vCalendarContent), "UTF-8")), email, vTimezone);
}
/**
* Empty constructor
*/
public VCalendar() {
type = "VCALENDAR";
}
@Override
public void addVObject(VObject vObject) {
super.addVObject(vObject);
if (firstVevent == null && "VEVENT".equals(vObject.type)) {
firstVevent = vObject;
}
if ("VTIMEZONE".equals(vObject.type)) {
vTimezone = vObject;
}
}
protected boolean isAllDay(VObject vObject) {
VProperty dtstart = vObject.getProperty("DTSTART");
return dtstart != null && dtstart.hasParam("VALUE", "DATE");
}
protected boolean isCdoAllDay(VObject vObject) {
return "TRUE".equals(vObject.getPropertyValue("X-MICROSOFT-CDO-ALLDAYEVENT"));
}
public boolean isCdoAllDay() {
return firstVevent != null && isCdoAllDay(firstVevent);
}
protected String getEmailValue(VProperty property) {
if (property == null) {
return null;
}
String propertyValue = property.getValue();
if (propertyValue != null && (propertyValue.startsWith("MAILTO:") || propertyValue.startsWith("mailto:"))) {
return propertyValue.substring(7);
} else {
return propertyValue;
}
}
protected String getMethod() {
return getPropertyValue("METHOD");
}
protected void fixVCalendar(boolean fromServer) {
// set iCal 4 global X-CALENDARSERVER-ACCESS from CLASS
if (fromServer) {
setPropertyValue("X-CALENDARSERVER-ACCESS", getCalendarServerAccess());
}
// iCal 4 global X-CALENDARSERVER-ACCESS
String calendarServerAccess = getPropertyValue("X-CALENDARSERVER-ACCESS");
String now = ExchangeSession.getZuluDateFormat().format(new Date());
// fix method from iPhone
if (!fromServer && getPropertyValue("METHOD") == null) {
setPropertyValue("METHOD", "PUBLISH");
}
// rename TZID for maximum iCal/iPhone compatibility
String tzid = null;
if (fromServer) {
// get current tzid
VObject vObject = getVTimezone();
if (vObject != null) {
- try {
- tzid = ResourceBundle.getBundle("timezones").getString(vObject.getPropertyValue("TZID"));
- } catch (MissingResourceException e) {
- LOGGER.debug("Timezone rename failed, timezone "+vObject.getPropertyValue("TZID")+" not found in table");
+ String currentTzid = vObject.getPropertyValue("TZID");
+ if (currentTzid != null && currentTzid.indexOf(' ') >= 0) {
+ try {
+ tzid = ResourceBundle.getBundle("timezones").getString(currentTzid);
+ } catch (MissingResourceException e) {
+ LOGGER.debug("Timezone rename failed, timezone " + currentTzid + " not found in table");
+ }
}
}
}
// iterate over vObjects
for (VObject vObject : vObjects) {
if ("VEVENT".equals(vObject.type)) {
if (calendarServerAccess != null) {
vObject.setPropertyValue("CLASS", getEventClass(calendarServerAccess));
// iCal 3, get X-CALENDARSERVER-ACCESS from local VEVENT
} else if (vObject.getPropertyValue("X-CALENDARSERVER-ACCESS") != null) {
vObject.setPropertyValue("CLASS", getEventClass(vObject.getPropertyValue("X-CALENDARSERVER-ACCESS")));
}
if (fromServer) {
// remove organizer line for event without attendees for iPhone
if (vObject.getProperty("ATTENDEE") == null) {
vObject.setPropertyValue("ORGANIZER", null);
}
// detect allday and update date properties
if (isCdoAllDay(vObject)) {
setClientAllday(vObject.getProperty("DTSTART"));
setClientAllday(vObject.getProperty("DTEND"));
}
String cdoBusyStatus = vObject.getPropertyValue("X-MICROSOFT-CDO-BUSYSTATUS");
if (cdoBusyStatus != null) {
vObject.setPropertyValue("TRANSP",
!"FREE".equals(cdoBusyStatus) ? "OPAQUE" : "TRANSPARENT");
}
// Apple iCal doesn't understand this key, and it's entourage
// specific (i.e. not needed by any caldav client): strip it out
vObject.removeProperty("X-ENTOURAGE_UUID");
splitExDate(vObject);
// remove empty properties
if ("".equals(vObject.getPropertyValue("LOCATION"))) {
vObject.removeProperty("LOCATION");
}
if ("".equals(vObject.getPropertyValue("DESCRIPTION"))) {
vObject.removeProperty("DESCRIPTION");
}
if ("".equals(vObject.getPropertyValue("CLASS"))) {
vObject.removeProperty("CLASS");
}
// rename TZID
if (tzid != null) {
VProperty dtStart = vObject.getProperty("DTSTART");
if (dtStart != null && dtStart.getParam("TZID") != null) {
dtStart.setParam("TZID", tzid);
}
VProperty dtEnd = vObject.getProperty("DTEND");
if (dtEnd != null && dtStart.getParam("TZID") != null) {
dtEnd.setParam("TZID", tzid);
}
}
} else {
// add organizer line to all events created in Exchange for active sync
String organizer = getEmailValue(vObject.getProperty("ORGANIZER"));
if (organizer == null) {
vObject.setPropertyValue("ORGANIZER", "MAILTO:" + email);
} else if (!email.equalsIgnoreCase(organizer) && vObject.getProperty("X-MICROSOFT-CDO-REPLYTIME") == null) {
vObject.setPropertyValue("X-MICROSOFT-CDO-REPLYTIME", now);
}
// set OWA allday flag
vObject.setPropertyValue("X-MICROSOFT-CDO-ALLDAYEVENT", isAllDay(vObject) ? "TRUE" : "FALSE");
vObject.setPropertyValue("X-MICROSOFT-CDO-BUSYSTATUS",
!"TRANSPARENT".equals(vObject.getPropertyValue("TRANSP")) ? "BUSY" : "FREE");
if (isAllDay(vObject)) {
// convert date values to outlook compatible values
setServerAllday(vObject.getProperty("DTSTART"));
setServerAllday(vObject.getProperty("DTEND"));
} else {
fixTzid(vObject.getProperty("DTSTART"));
fixTzid(vObject.getProperty("DTEND"));
}
}
fixAttendees(vObject, fromServer);
fixAlarm(vObject, fromServer);
}
}
}
private void fixTzid(VProperty property) {
if (property != null && !property.hasParam("TZID")) {
property.addParam("TZID", vTimezone.getPropertyValue("TZID"));
}
}
protected void splitExDate(VObject vObject) {
List<VProperty> exDateProperties = vObject.getProperties("EXDATE");
if (exDateProperties != null) {
for (VProperty property : exDateProperties) {
String value = property.getValue();
if (value.indexOf(',') >= 0) {
// split property
vObject.removeProperty(property);
for (String singleValue : value.split(",")) {
VProperty singleProperty = new VProperty("EXDATE", singleValue);
singleProperty.setParams(property.getParams());
vObject.addProperty(singleProperty);
}
}
}
}
}
protected void setServerAllday(VProperty property) {
if (vTimezone != null) {
// set TZID param
if (!property.hasParam("TZID")) {
property.addParam("TZID", vTimezone.getPropertyValue("TZID"));
}
// remove VALUE
property.removeParam("VALUE");
String value = property.getValue();
if (value.length() != 8) {
LOGGER.warn("Invalid date value in allday event: " + value);
}
property.setValue(property.getValue() + "T000000");
}
}
protected void setClientAllday(VProperty property) {
if (property != null) {
// set VALUE=DATE param
if (!property.hasParam("VALUE")) {
property.addParam("VALUE", "DATE");
}
// remove TZID
property.removeParam("TZID");
String value = property.getValue();
if (value.length() != 8) {
// try to convert datetime value to date value
try {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat dateParser = new SimpleDateFormat("yyyyMMdd'T'HHmmss");
calendar.setTime(dateParser.parse(value));
calendar.add(Calendar.HOUR_OF_DAY, 12);
SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyyMMdd");
value = dateFormatter.format(calendar.getTime());
} catch (ParseException e) {
LOGGER.warn("Invalid date value in allday event: " + value);
}
}
property.setValue(value);
}
}
protected void fixAlarm(VObject vObject, boolean fromServer) {
if (vObject.vObjects != null) {
for (VObject vAlarm : vObject.vObjects) {
if ("VALARM".equals(vAlarm.type)) {
String action = vAlarm.getPropertyValue("ACTION");
if (fromServer && "DISPLAY".equals(action)
// convert DISPLAY to AUDIO only if user defined an alarm sound
&& Settings.getProperty("davmail.caldavAlarmSound") != null) {
// Convert alarm to audio for iCal
vAlarm.setPropertyValue("ACTION", "AUDIO");
if (vAlarm.getPropertyValue("ATTACH") == null) {
// Add defined sound into the audio alarm
VProperty vProperty = new VProperty("ATTACH", Settings.getProperty("davmail.caldavAlarmSound"));
vProperty.addParam("VALUE", "URI");
vAlarm.addProperty(vProperty);
}
} else if (!fromServer && "AUDIO".equals(action)) {
// Use the alarm action that exchange (and blackberry) understand
// (exchange and blackberry don't understand audio actions)
vAlarm.setPropertyValue("ACTION", "DISPLAY");
}
}
}
}
}
/**
* Replace iCal4 (Snow Leopard) principal paths with mailto expression
*
* @param value attendee value or ics line
* @return fixed value
*/
protected String replaceIcal4Principal(String value) {
if (value.contains("/principals/__uuids__/")) {
return value.replaceAll("/principals/__uuids__/([^/]*)__AT__([^/]*)/", "mailto:$1@$2");
} else {
return value;
}
}
private void fixAttendees(VObject vObject, boolean fromServer) {
if (vObject.properties != null) {
for (VProperty property : vObject.properties) {
if ("ATTENDEE".equalsIgnoreCase(property.getKey())) {
if (fromServer) {
// If this is coming from the server, strip out RSVP for this
// user as an attendee where the partstat is something other
// than PARTSTAT=NEEDS-ACTION since the RSVP confuses iCal4 into
// thinking the attendee has not replied
if (isCurrentUser(property) && property.hasParam("RSVP", "TRUE")) {
VProperty.Param partstat = property.getParam("PARTSTAT");
if (partstat == null || !"NEEDS-ACTION".equals(partstat.getValue())) {
property.removeParam("RSVP");
}
}
} else {
property.setValue(replaceIcal4Principal(property.getValue()));
}
}
}
}
}
private boolean isCurrentUser(VProperty property) {
return property.getValue().equalsIgnoreCase("mailto:" + email);
}
/**
* Return VTimezone object
*
* @return VTimezone
*/
public VObject getVTimezone() {
return vTimezone;
}
/**
* Convert X-CALENDARSERVER-ACCESS to CLASS.
* see http://svn.calendarserver.org/repository/calendarserver/CalendarServer/trunk/doc/Extensions/caldav-privateevents.txt
*
* @param calendarServerAccess X-CALENDARSERVER-ACCESS value
* @return CLASS value
*/
protected String getEventClass(String calendarServerAccess) {
if ("PRIVATE".equalsIgnoreCase(calendarServerAccess)) {
return "CONFIDENTIAL";
} else if ("CONFIDENTIAL".equalsIgnoreCase(calendarServerAccess) || "RESTRICTED".equalsIgnoreCase(calendarServerAccess)) {
return "PRIVATE";
} else {
return null;
}
}
/**
* Convert CLASS to X-CALENDARSERVER-ACCESS.
* see http://svn.calendarserver.org/repository/calendarserver/CalendarServer/trunk/doc/Extensions/caldav-privateevents.txt *
*
* @return X-CALENDARSERVER-ACCESS value
*/
protected String getCalendarServerAccess() {
String eventClass = getFirstVeventPropertyValue("CLASS");
if ("PRIVATE".equalsIgnoreCase(eventClass)) {
return "CONFIDENTIAL";
} else if ("CONFIDENTIAL".equalsIgnoreCase(eventClass)) {
return "PRIVATE";
} else {
return null;
}
}
/**
* Get property value from first VEVENT in VCALENDAR.
*
* @param name property name
* @return property value
*/
public String getFirstVeventPropertyValue(String name) {
if (firstVevent == null) {
return null;
} else {
return firstVevent.getPropertyValue(name);
}
}
protected VProperty getFirstVeventProperty(String name) {
if (firstVevent == null) {
return null;
} else {
return firstVevent.getProperty(name);
}
}
protected List<VProperty> getFirstVeventProperties(String name) {
if (firstVevent == null) {
return null;
} else {
return firstVevent.getProperties(name);
}
}
public void removeVAlarm() {
if (vObjects != null) {
for (VObject vObject : vObjects) {
if ("VEVENT".equals(vObject.type)) {
if (vObject.vObjects != null) {
vObject.vObjects = null;
}
}
}
}
}
public boolean hasVAlarm() {
if (vObjects != null) {
for (VObject vObject : vObjects) {
if ("VEVENT".equals(vObject.type)) {
if (vObject.vObjects != null) {
return true;
}
}
}
}
return false;
}
public boolean isMeeting() {
return getFirstVeventProperty("ATTENDEE") != null;
}
public boolean isMeetingOrganizer() {
return email.equals(getEmailValue(getFirstVeventProperty("ORGANIZER")));
}
public void setFirstVeventPropertyValue(String propertyName, String propertyValue) {
firstVevent.setPropertyValue(propertyName, propertyValue);
}
public void addFirstVeventProperty(VProperty vProperty) {
firstVevent.addProperty(vProperty);
}
/**
* VCalendar recipients for notifications
*/
public static class Recipients {
public String attendees;
public String optionalAttendees;
public String organizer;
}
/**
* Build recipients value for VCalendar.
*
* @param isNotification if true, filter recipients that should receive meeting notifications
* @return notification/event recipients
*/
public Recipients getRecipients(boolean isNotification) {
HashSet<String> attendees = new HashSet<String>();
HashSet<String> optionalAttendees = new HashSet<String>();
// get recipients from first VEVENT
List<VProperty> attendeeProperties = getFirstVeventProperties("ATTENDEE");
if (attendeeProperties != null) {
for (VProperty property : attendeeProperties) {
// exclude current user and invalid values from recipients
// also exclude no action attendees
String attendeeEmail = getEmailValue(property);
if (!email.equalsIgnoreCase(attendeeEmail) && attendeeEmail != null && attendeeEmail.indexOf('@') >= 0
// return all attendees for user calendar folder, filter for notifications
&& (!isNotification
// notify attendee if reply explicitly requested
|| (property.hasParam("RSVP", "TRUE"))
|| (
// workaround for iCal bug: do not notify if reply explicitly not requested
!(property.hasParam("RSVP", "FALSE")) &&
((property.hasParam("PARTSTAT", "NEEDS-ACTION")
// need to include other PARTSTATs participants for CANCEL notifications
|| property.hasParam("PARTSTAT", "ACCEPTED")
|| property.hasParam("PARTSTAT", "DECLINED")
|| property.hasParam("PARTSTAT", "TENTATIVE")))
))) {
if (property.hasParam("ROLE", "OPT-PARTICIPANT")) {
optionalAttendees.add(attendeeEmail);
} else {
attendees.add(attendeeEmail);
}
}
}
}
Recipients recipients = new Recipients();
recipients.organizer = getEmailValue(getFirstVeventProperty("ORGANIZER"));
recipients.attendees = StringUtil.join(attendees, ", ");
recipients.optionalAttendees = StringUtil.join(optionalAttendees, ", ");
return recipients;
}
protected String getAttendeeStatus() {
String status = null;
List<VProperty> attendeeProperties = getFirstVeventProperties("ATTENDEE");
if (attendeeProperties != null) {
for (VProperty property : attendeeProperties) {
String attendeeEmail = getEmailValue(property);
if (email.equalsIgnoreCase(attendeeEmail) && property.hasParam("PARTSTAT")) {
// found current user attendee line
status = property.getParam("PARTSTAT").getValue();
break;
}
}
}
return status;
}
}
| true | true | protected void fixVCalendar(boolean fromServer) {
// set iCal 4 global X-CALENDARSERVER-ACCESS from CLASS
if (fromServer) {
setPropertyValue("X-CALENDARSERVER-ACCESS", getCalendarServerAccess());
}
// iCal 4 global X-CALENDARSERVER-ACCESS
String calendarServerAccess = getPropertyValue("X-CALENDARSERVER-ACCESS");
String now = ExchangeSession.getZuluDateFormat().format(new Date());
// fix method from iPhone
if (!fromServer && getPropertyValue("METHOD") == null) {
setPropertyValue("METHOD", "PUBLISH");
}
// rename TZID for maximum iCal/iPhone compatibility
String tzid = null;
if (fromServer) {
// get current tzid
VObject vObject = getVTimezone();
if (vObject != null) {
try {
tzid = ResourceBundle.getBundle("timezones").getString(vObject.getPropertyValue("TZID"));
} catch (MissingResourceException e) {
LOGGER.debug("Timezone rename failed, timezone "+vObject.getPropertyValue("TZID")+" not found in table");
}
}
}
// iterate over vObjects
for (VObject vObject : vObjects) {
if ("VEVENT".equals(vObject.type)) {
if (calendarServerAccess != null) {
vObject.setPropertyValue("CLASS", getEventClass(calendarServerAccess));
// iCal 3, get X-CALENDARSERVER-ACCESS from local VEVENT
} else if (vObject.getPropertyValue("X-CALENDARSERVER-ACCESS") != null) {
vObject.setPropertyValue("CLASS", getEventClass(vObject.getPropertyValue("X-CALENDARSERVER-ACCESS")));
}
if (fromServer) {
// remove organizer line for event without attendees for iPhone
if (vObject.getProperty("ATTENDEE") == null) {
vObject.setPropertyValue("ORGANIZER", null);
}
// detect allday and update date properties
if (isCdoAllDay(vObject)) {
setClientAllday(vObject.getProperty("DTSTART"));
setClientAllday(vObject.getProperty("DTEND"));
}
String cdoBusyStatus = vObject.getPropertyValue("X-MICROSOFT-CDO-BUSYSTATUS");
if (cdoBusyStatus != null) {
vObject.setPropertyValue("TRANSP",
!"FREE".equals(cdoBusyStatus) ? "OPAQUE" : "TRANSPARENT");
}
// Apple iCal doesn't understand this key, and it's entourage
// specific (i.e. not needed by any caldav client): strip it out
vObject.removeProperty("X-ENTOURAGE_UUID");
splitExDate(vObject);
// remove empty properties
if ("".equals(vObject.getPropertyValue("LOCATION"))) {
vObject.removeProperty("LOCATION");
}
if ("".equals(vObject.getPropertyValue("DESCRIPTION"))) {
vObject.removeProperty("DESCRIPTION");
}
if ("".equals(vObject.getPropertyValue("CLASS"))) {
vObject.removeProperty("CLASS");
}
// rename TZID
if (tzid != null) {
VProperty dtStart = vObject.getProperty("DTSTART");
if (dtStart != null && dtStart.getParam("TZID") != null) {
dtStart.setParam("TZID", tzid);
}
VProperty dtEnd = vObject.getProperty("DTEND");
if (dtEnd != null && dtStart.getParam("TZID") != null) {
dtEnd.setParam("TZID", tzid);
}
}
} else {
// add organizer line to all events created in Exchange for active sync
String organizer = getEmailValue(vObject.getProperty("ORGANIZER"));
if (organizer == null) {
vObject.setPropertyValue("ORGANIZER", "MAILTO:" + email);
} else if (!email.equalsIgnoreCase(organizer) && vObject.getProperty("X-MICROSOFT-CDO-REPLYTIME") == null) {
vObject.setPropertyValue("X-MICROSOFT-CDO-REPLYTIME", now);
}
// set OWA allday flag
vObject.setPropertyValue("X-MICROSOFT-CDO-ALLDAYEVENT", isAllDay(vObject) ? "TRUE" : "FALSE");
vObject.setPropertyValue("X-MICROSOFT-CDO-BUSYSTATUS",
!"TRANSPARENT".equals(vObject.getPropertyValue("TRANSP")) ? "BUSY" : "FREE");
if (isAllDay(vObject)) {
// convert date values to outlook compatible values
setServerAllday(vObject.getProperty("DTSTART"));
setServerAllday(vObject.getProperty("DTEND"));
} else {
fixTzid(vObject.getProperty("DTSTART"));
fixTzid(vObject.getProperty("DTEND"));
}
}
fixAttendees(vObject, fromServer);
fixAlarm(vObject, fromServer);
}
}
}
| protected void fixVCalendar(boolean fromServer) {
// set iCal 4 global X-CALENDARSERVER-ACCESS from CLASS
if (fromServer) {
setPropertyValue("X-CALENDARSERVER-ACCESS", getCalendarServerAccess());
}
// iCal 4 global X-CALENDARSERVER-ACCESS
String calendarServerAccess = getPropertyValue("X-CALENDARSERVER-ACCESS");
String now = ExchangeSession.getZuluDateFormat().format(new Date());
// fix method from iPhone
if (!fromServer && getPropertyValue("METHOD") == null) {
setPropertyValue("METHOD", "PUBLISH");
}
// rename TZID for maximum iCal/iPhone compatibility
String tzid = null;
if (fromServer) {
// get current tzid
VObject vObject = getVTimezone();
if (vObject != null) {
String currentTzid = vObject.getPropertyValue("TZID");
if (currentTzid != null && currentTzid.indexOf(' ') >= 0) {
try {
tzid = ResourceBundle.getBundle("timezones").getString(currentTzid);
} catch (MissingResourceException e) {
LOGGER.debug("Timezone rename failed, timezone " + currentTzid + " not found in table");
}
}
}
}
// iterate over vObjects
for (VObject vObject : vObjects) {
if ("VEVENT".equals(vObject.type)) {
if (calendarServerAccess != null) {
vObject.setPropertyValue("CLASS", getEventClass(calendarServerAccess));
// iCal 3, get X-CALENDARSERVER-ACCESS from local VEVENT
} else if (vObject.getPropertyValue("X-CALENDARSERVER-ACCESS") != null) {
vObject.setPropertyValue("CLASS", getEventClass(vObject.getPropertyValue("X-CALENDARSERVER-ACCESS")));
}
if (fromServer) {
// remove organizer line for event without attendees for iPhone
if (vObject.getProperty("ATTENDEE") == null) {
vObject.setPropertyValue("ORGANIZER", null);
}
// detect allday and update date properties
if (isCdoAllDay(vObject)) {
setClientAllday(vObject.getProperty("DTSTART"));
setClientAllday(vObject.getProperty("DTEND"));
}
String cdoBusyStatus = vObject.getPropertyValue("X-MICROSOFT-CDO-BUSYSTATUS");
if (cdoBusyStatus != null) {
vObject.setPropertyValue("TRANSP",
!"FREE".equals(cdoBusyStatus) ? "OPAQUE" : "TRANSPARENT");
}
// Apple iCal doesn't understand this key, and it's entourage
// specific (i.e. not needed by any caldav client): strip it out
vObject.removeProperty("X-ENTOURAGE_UUID");
splitExDate(vObject);
// remove empty properties
if ("".equals(vObject.getPropertyValue("LOCATION"))) {
vObject.removeProperty("LOCATION");
}
if ("".equals(vObject.getPropertyValue("DESCRIPTION"))) {
vObject.removeProperty("DESCRIPTION");
}
if ("".equals(vObject.getPropertyValue("CLASS"))) {
vObject.removeProperty("CLASS");
}
// rename TZID
if (tzid != null) {
VProperty dtStart = vObject.getProperty("DTSTART");
if (dtStart != null && dtStart.getParam("TZID") != null) {
dtStart.setParam("TZID", tzid);
}
VProperty dtEnd = vObject.getProperty("DTEND");
if (dtEnd != null && dtStart.getParam("TZID") != null) {
dtEnd.setParam("TZID", tzid);
}
}
} else {
// add organizer line to all events created in Exchange for active sync
String organizer = getEmailValue(vObject.getProperty("ORGANIZER"));
if (organizer == null) {
vObject.setPropertyValue("ORGANIZER", "MAILTO:" + email);
} else if (!email.equalsIgnoreCase(organizer) && vObject.getProperty("X-MICROSOFT-CDO-REPLYTIME") == null) {
vObject.setPropertyValue("X-MICROSOFT-CDO-REPLYTIME", now);
}
// set OWA allday flag
vObject.setPropertyValue("X-MICROSOFT-CDO-ALLDAYEVENT", isAllDay(vObject) ? "TRUE" : "FALSE");
vObject.setPropertyValue("X-MICROSOFT-CDO-BUSYSTATUS",
!"TRANSPARENT".equals(vObject.getPropertyValue("TRANSP")) ? "BUSY" : "FREE");
if (isAllDay(vObject)) {
// convert date values to outlook compatible values
setServerAllday(vObject.getProperty("DTSTART"));
setServerAllday(vObject.getProperty("DTEND"));
} else {
fixTzid(vObject.getProperty("DTSTART"));
fixTzid(vObject.getProperty("DTEND"));
}
}
fixAttendees(vObject, fromServer);
fixAlarm(vObject, fromServer);
}
}
}
|
diff --git a/graphml-impl/src/test/java/org/cytoscape/data/reader/graphml/GraphMLReaderTest.java b/graphml-impl/src/test/java/org/cytoscape/data/reader/graphml/GraphMLReaderTest.java
index a0898e99f..56864720c 100644
--- a/graphml-impl/src/test/java/org/cytoscape/data/reader/graphml/GraphMLReaderTest.java
+++ b/graphml-impl/src/test/java/org/cytoscape/data/reader/graphml/GraphMLReaderTest.java
@@ -1,195 +1,193 @@
package org.cytoscape.data.reader.graphml;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.io.File;
import java.io.InputStream;
import org.cytoscape.ding.NetworkViewTestSupport;
import org.cytoscape.io.internal.read.graphml.GraphMLReader;
import org.cytoscape.model.CyColumn;
import org.cytoscape.model.CyEdge;
import org.cytoscape.model.CyNetwork;
import org.cytoscape.model.CyNetworkFactory;
import org.cytoscape.model.CyNode;
import org.cytoscape.model.CyTableEntry;
import org.cytoscape.model.NetworkTestSupport;
import org.cytoscape.model.subnetwork.CyRootNetworkFactory;
import org.cytoscape.view.layout.CyLayoutAlgorithmManager;
import org.cytoscape.view.model.CyNetworkViewFactory;
import org.cytoscape.work.TaskMonitor;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
public class GraphMLReaderTest {
private NetworkTestSupport testSupport;
private NetworkViewTestSupport nvts;
private CyNetworkFactory netFactory;
private CyRootNetworkFactory rootFactory;
private CyNetworkViewFactory viewFactory;
@Mock
private CyLayoutAlgorithmManager layouts;
@Mock
private TaskMonitor tm;
@Before
public void initMocks() {
MockitoAnnotations.initMocks(this);
}
@Before
public void setUp() throws Exception {
testSupport = new NetworkTestSupport();
nvts = new NetworkViewTestSupport();
rootFactory = testSupport.getRootNetworkFactory();
netFactory = testSupport.getNetworkFactory();
viewFactory = nvts.getNetworkViewFactory();
}
@After
public void tearDown() throws Exception {
}
@Test
public void testReadSimpleGraph() throws Exception {
File file = new File("src/test/resources/testGraph1.xml");
InputStream stream = file.toURI().toURL().openStream();
GraphMLReader reader = new GraphMLReader(stream, layouts, netFactory, viewFactory, rootFactory);
assertNotNull(reader);
reader.run(tm);
final CyNetwork[] networks = reader.getCyNetworks();
assertNotNull(networks);
assertEquals(1, networks.length);
final CyNetwork network = networks[0];
assertEquals(11, network.getNodeCount());
assertEquals(12, network.getEdgeCount());
}
@Test
public void testReadAttrGraph() throws Exception {
File file = new File("src/test/resources/simpleWithAttributes.xml");
InputStream stream = file.toURI().toURL().openStream();
GraphMLReader reader = new GraphMLReader(stream, layouts, netFactory, viewFactory, rootFactory);
assertNotNull(reader);
reader.run(tm);
final CyNetwork[] networks = reader.getCyNetworks();
assertNotNull(networks);
assertEquals(1, networks.length);
final CyNetwork network = networks[0];
assertEquals(6, network.getNodeCount());
assertEquals(7, network.getEdgeCount());
final CyNode node1 = network.getNode(0);
assertNotNull(node1);
- assertEquals(4, node1.getCyRow().getTable().getColumns().size());
final CyEdge edge1 = network.getEdge(0);
assertNotNull(edge1);
- assertEquals(5, edge1.getCyRow().getTable().getColumns().size());
final CyColumn colorCol = node1.getCyRow().getTable().getColumn("color");
final CyColumn weightCol = edge1.getCyRow().getTable().getColumn("weight");
assertNotNull(colorCol);
assertNotNull(weightCol);
assertEquals(String.class, colorCol.getType());
assertEquals(Double.class, weightCol.getType());
assertEquals(Double.valueOf(1.0d), edge1.getCyRow().get("weight", Double.class));
}
@Test
public void testReadAttedOutput() throws Exception {
File file = new File("src/test/resources/atted.graphml");
InputStream stream = file.toURI().toURL().openStream();
GraphMLReader reader = new GraphMLReader(stream, layouts, netFactory, viewFactory, rootFactory);
assertNotNull(reader);
reader.run(tm);
final CyNetwork[] networks = reader.getCyNetworks();
assertNotNull(networks);
assertEquals(1, networks.length);
final CyNetwork network = networks[0];
// nodes = network.getno
//
// assertEquals("AtbZIP52", nodeAttr.getAttribute("At1g06850", "symbol"));
// assertEquals("bZIP", nodeAttr.getAttribute("At1g06850", "TF_family"));
//
// assertEquals("correlation", edgeAttr.getAttribute("At5g48880 (pp) At1g65060", "label"));
// assertEquals(5.20, edgeAttr.getAttribute("At5g48880 (pp) At1g65060", "mr_all"));
}
@Test
public void testReadNestedSubgraphs() throws Exception {
File file = new File("src/test/resources/nested.xml");
InputStream stream = file.toURI().toURL().openStream();
GraphMLReader reader = new GraphMLReader(stream, layouts, netFactory, viewFactory, rootFactory);
assertNotNull(reader);
reader.run(tm);
final CyNetwork[] networks = reader.getCyNetworks();
assertNotNull(networks);
assertEquals(4, networks.length);
final CyNetwork rootNetwork = networks[0];
for(CyNode node: rootNetwork.getNodeList())
System.out.println("In root network: " + node.getCyRow().get(CyTableEntry.NAME, String.class));
assertEquals(11, rootNetwork.getNodeCount());
assertEquals(12, rootNetwork.getEdgeCount());
final CyNetwork child1 = networks[1];
assertEquals(3, child1.getNodeCount());
assertEquals(2, child1.getEdgeCount());
final CyNetwork child2 = networks[2];
assertEquals(3, child2.getNodeCount());
assertEquals(2, child2.getEdgeCount());
final CyNetwork child3 = networks[3];
assertEquals(1, child3.getNodeCount());
assertEquals(0, child3.getEdgeCount());
}
@Test
public void testReadNestedSubgraphs2() throws Exception {
File file = new File("src/test/resources/nested2.xml");
InputStream stream = file.toURI().toURL().openStream();
GraphMLReader reader = new GraphMLReader(stream, layouts, netFactory, viewFactory, rootFactory);
assertNotNull(reader);
reader.run(tm);
final CyNetwork[] networks = reader.getCyNetworks();
assertNotNull(networks);
assertEquals(4, networks.length);
final CyNetwork rootNetwork = networks[0];
for(CyNode node: rootNetwork.getNodeList())
System.out.println("In root network: " + node.getCyRow().get(CyTableEntry.NAME, String.class));
assertEquals(8, rootNetwork.getNodeCount());
assertEquals(10, rootNetwork.getEdgeCount());
final CyNetwork child1 = networks[1];
assertEquals(6, child1.getNodeCount());
assertEquals(7, child1.getEdgeCount());
final CyNetwork child2 = networks[2];
assertEquals(3, child2.getNodeCount());
assertEquals(3, child2.getEdgeCount());
final CyNetwork child3 = networks[3];
assertEquals(2, child3.getNodeCount());
assertEquals(1, child3.getEdgeCount());
}
}
| false | true | public void testReadAttrGraph() throws Exception {
File file = new File("src/test/resources/simpleWithAttributes.xml");
InputStream stream = file.toURI().toURL().openStream();
GraphMLReader reader = new GraphMLReader(stream, layouts, netFactory, viewFactory, rootFactory);
assertNotNull(reader);
reader.run(tm);
final CyNetwork[] networks = reader.getCyNetworks();
assertNotNull(networks);
assertEquals(1, networks.length);
final CyNetwork network = networks[0];
assertEquals(6, network.getNodeCount());
assertEquals(7, network.getEdgeCount());
final CyNode node1 = network.getNode(0);
assertNotNull(node1);
assertEquals(4, node1.getCyRow().getTable().getColumns().size());
final CyEdge edge1 = network.getEdge(0);
assertNotNull(edge1);
assertEquals(5, edge1.getCyRow().getTable().getColumns().size());
final CyColumn colorCol = node1.getCyRow().getTable().getColumn("color");
final CyColumn weightCol = edge1.getCyRow().getTable().getColumn("weight");
assertNotNull(colorCol);
assertNotNull(weightCol);
assertEquals(String.class, colorCol.getType());
assertEquals(Double.class, weightCol.getType());
assertEquals(Double.valueOf(1.0d), edge1.getCyRow().get("weight", Double.class));
}
| public void testReadAttrGraph() throws Exception {
File file = new File("src/test/resources/simpleWithAttributes.xml");
InputStream stream = file.toURI().toURL().openStream();
GraphMLReader reader = new GraphMLReader(stream, layouts, netFactory, viewFactory, rootFactory);
assertNotNull(reader);
reader.run(tm);
final CyNetwork[] networks = reader.getCyNetworks();
assertNotNull(networks);
assertEquals(1, networks.length);
final CyNetwork network = networks[0];
assertEquals(6, network.getNodeCount());
assertEquals(7, network.getEdgeCount());
final CyNode node1 = network.getNode(0);
assertNotNull(node1);
final CyEdge edge1 = network.getEdge(0);
assertNotNull(edge1);
final CyColumn colorCol = node1.getCyRow().getTable().getColumn("color");
final CyColumn weightCol = edge1.getCyRow().getTable().getColumn("weight");
assertNotNull(colorCol);
assertNotNull(weightCol);
assertEquals(String.class, colorCol.getType());
assertEquals(Double.class, weightCol.getType());
assertEquals(Double.valueOf(1.0d), edge1.getCyRow().get("weight", Double.class));
}
|
diff --git a/src/gameEngine/GameEngine.java b/src/gameEngine/GameEngine.java
index 3b371ac..c2a7123 100644
--- a/src/gameEngine/GameEngine.java
+++ b/src/gameEngine/GameEngine.java
@@ -1,582 +1,582 @@
package gameEngine;
import java.util.*;
import participant.Chips;
import participant.Player;
import table.Table;
import game.*;
import game.Observable;
import game.Observer;
import cards.*;
public class GameEngine implements Observable {
private Blackjack myGame;
private Table gameTable;
private ArrayList<Observer> observerList = new ArrayList<Observer>();
private BlackjackHand dealerHand = new BlackjackHand();
private HashMap<Player, ArrayList<BlackjackHand>> playersAndHands;
private HashMap<Player, Chips> playersAndChips;
private final int MUST_HIT = 16;
private final int STARTING_CHIPS = 500;
private final int DEALER_WON = 1;
private final int PLAYER_WON = -1;
private final int DRAW = 0;
private final int WIN_CONSTANT = 2;
private final int BLACKJACK_PAYOUT_CONSTANT = 3;
public GameEngine(Player player) {
gameTable = new Table(player);
}
public void reset() {
myGame = new Blackjack();
playersAndHands = new HashMap<Player, ArrayList<BlackjackHand>>();
playersAndChips = new HashMap<Player, Chips>();
this.notifyObservers();
}
public void resetKeepPlayers() {
myGame = new Blackjack();
this.notifyObservers();
}
public HashMap<Player, ArrayList<BlackjackHand>> getPlayersAndHands() {
return this.playersAndHands;
}
public void gameStart() {
reset();
/*
* temporarily adding players here for testing purposes,
* later needs to be modified to create/accept players/spectators
*/
Player bob = new Player("bob","bob");
BlackjackHand hb = new BlackjackHand();
ArrayList<BlackjackHand> hbb = new ArrayList<BlackjackHand>();
hbb.add(hb);
Player bab = new Player("bab","bab");
BlackjackHand hb2 = new BlackjackHand();
ArrayList<BlackjackHand> hbb2 = new ArrayList<BlackjackHand>();
hbb2.add(hb2);
// playersAndHands.put(bob, hbb);
// playersAndHands.put(bab, hbb2);
//temporarily testing adding players to the table
//later to be implemented is the actual passing of players to requestJoin
gameTable.requestJoin(bob);
gameTable.requestJoin(bab);
//deal dealer's hand now
myGame.deal(dealerHand);
//these are not quite implemented but they ideally are supposed to load from a previous saved game...?
loadPlayers();
loadHands();
loadChips();
loadBets();
//gathering bet amounts from all players
ArrayList<Player> players = gameTable.getAllPlayers();
Scanner keyboard = new Scanner(System.in);
for (int i=0; i<players.size(); i++) {
//for (int i=0;i<getNumberOfPlayers();i++){
System.out.println(players.get(i).getUsername() + " how much do you want to bet?");
int a = keyboard.nextInt();
//set the bet and remove the chips
try {
playersAndChips.get(players.get(i)).setBet(a);
playersAndChips.get(players.get(i)).addChips(players.get(i), -a);
System.out.println(" you want to bet " + a);
} catch (Exception IllegalArgumentException) {
while (a > playersAndChips.get(players.get(i)).getChips()) {
//add back chips after evaluating while loop condition
//playersAndChips.get(players.get(i)).addChips(players.get(i), a);
System.out.println("sorry not enough chips, please enter " + playersAndChips.get(players.get(i).getChips()) + " or less" );
//System.out.println("sorry not enough chips, please enter " + playersAndChips.get(gameTable.getAllPlayers().get(i)).getChips() + " or less" );
a = keyboard.nextInt();
playersAndChips.get(players.get(i)).setBet(a);
playersAndChips.get(players.get(i)).addChips(players.get(i), -a);
System.out.println(" you want to bet " + a);
}
}
}
//shows dealer's initial hand, game is over if dealer gets blackjack,
//else then dealer hits until it is above 16 pts
System.out.println("Dealer's hand: " + dealerHand.toString());
if (dealerHand.checkBlackjack()) {
dealerHand.setDone();
System.out.println("Game over!");
} else {
while (dealerHand.getBlackjackValue() < MUST_HIT)
myGame.hit(dealerHand);
dealerHand.setDone();
/*
* Deal everyone
*/
System.out.println("Dealing everyone...");
for (int i=0; i<players.size(); i++){
System.out.println(players.get(i).getUsername());
}
for (ArrayList<BlackjackHand> b : playersAndHands.values()) {
BlackjackHand tmpHand = new BlackjackHand();
myGame.deal(tmpHand);
b.add(tmpHand);
}
for (int i=0;i<getNumberOfPlayers();i++){
ArrayList<BlackjackHand> b = playersAndHands.get(gameTable.getPlayer(i));
System.out.println(gameTable.getPlayer(i).getUsername() + ", your first hand is currently: " + b.get(0).toString());
if (b.size() == 2) {
System.out.println(gameTable.getPlayer(i) + ", your second hand is currently: " + b.get(1).toString());
}
}
/*
* Ask for input moves
*/
for (int i=0; i<players.size(); i++){
ArrayList<BlackjackHand> b = playersAndHands.get(players.get(i));
System.out.println(gameTable.getPlayer(i).getUsername()+": ");
//Scanner keyboard = new Scanner (System.in);
- String s = "";
+// String s = "";
for (int j=0; j < b.size(); j++) {
while (b.get(j).isPlayable() && !(b.get(j).isBust())){
// System.out.println(b.get(j).isPlayable() +"isplayable");
// System.out.println(!(b.get(j).isBust()) +"isbust");
System.out.println("now for your first hand, do you want to hit, stand, double down, split?");
- s = keyboard.nextLine();
+ String s = keyboard.next();
if (s.equals("hit")){
myGame.hit(b.get(j));
System.out.println("hand update: " +b.get(j).toString());
}
else if (s.equals("stand")){
myGame.stand(b.get(j));
System.out.println("final hand: "+b.get(j).toString());
}
else if (s.equals("double down")){
if (playersAndChips.get(gameTable.getPlayer(i)).addChips(players.get(i), playersAndChips.get(i).getBet())==false) {
System.out.print("sorry not enough chips, please enter a different move" );
s = "";
}
else {
myGame.doubleDown(b.get(j));
System.out.println("hand update: "+b.get(j).toString());
}
}
else if (s.equals("split")){
if (b.get(j).checkPair() == false) {
System.out.println("you dont have a pair! select a different move");
s = "";
} else {
myGame.split(b.get(j));
System.out.println("split to be implemented: "+b.get(j).toString());
}
} else {
System.out.println("please enter something valid");
s = "";
}
}
}
}
//shows dealer's final hand
System.out.println("Dealer's new hand: " + dealerHand.toString());
if (dealerHand.isBust())
System.out.println("Dealer bust!");
/*
* Compute all winners
*/
for (int i=0;i<getNumberOfPlayers();i++){
ArrayList<BlackjackHand> b = playersAndHands.get(gameTable.getPlayer(i));
if (b.size() == 1) {
if (processWinner(b.get(0)) == 1)
System.out.println("Dealer wins!");
if (processWinner(b.get(0)) == -1) {
if (b.get(0).checkBlackjack()) {
playersAndChips.get(gameTable.getPlayer(i)).addChips(players.get(i), BLACKJACK_PAYOUT_CONSTANT * playersAndChips.get(gameTable.getPlayer(i)).getBet());
System.out.println("BLACKJACK! X2 PAYOUT! " + gameTable.getPlayer(i).getUsername()+ " wins!");
} else {
playersAndChips.get(gameTable.getPlayer(i)).addChips(players.get(i), WIN_CONSTANT * playersAndChips.get(gameTable.getPlayer(i)).getBet());
System.out.println(gameTable.getPlayer(i).getUsername()+ " wins!");
}
}
if (processWinner(b.get(0)) == 0) {
playersAndChips.get(gameTable.getPlayer(i)).addChips(players.get(i), playersAndChips.get(gameTable.getPlayer(i)).getBet());
System.out.println("Draw!");
}
} else {
if (processWinner(b.get(0)) == 1)
System.out.println("Dealer wins!");
if (processWinner(b.get(0)) == -1) {
if (b.get(0).checkBlackjack()) {
playersAndChips.get(gameTable.getPlayer(i)).addChips(players.get(i), BLACKJACK_PAYOUT_CONSTANT * playersAndChips.get(gameTable.getPlayer(i)).getBet());
System.out.println("BLACKJACK! X2 PAYOUT! " + gameTable.getPlayer(i).getUsername()+ " wins!");
} else {
playersAndChips.get(gameTable.getPlayer(i)).addChips(players.get(i), WIN_CONSTANT * playersAndChips.get(gameTable.getPlayer(i)).getBet());
System.out.println(gameTable.getPlayer(i).getUsername()+ " wins!");
}
}
if (processWinner(b.get(0)) == 0) {
playersAndChips.get(gameTable.getPlayer(i)).addChips(players.get(i), playersAndChips.get(gameTable.getPlayer(i)).getBet());
System.out.println("Draw!");
}
if (processWinner(b.get(1)) == 1)
System.out.println("Dealer wins!");
if (processWinner(b.get(1)) == -1) {
if (b.get(0).checkBlackjack()) {
playersAndChips.get(gameTable.getPlayer(i)).addChips(players.get(i), BLACKJACK_PAYOUT_CONSTANT * playersAndChips.get(gameTable.getPlayer(i)).getBet());
System.out.println("BLACKJACK! X2 PAYOUT! " + gameTable.getPlayer(i).getUsername()+ " wins!");
} else {
playersAndChips.get(gameTable.getPlayer(i)).addChips(players.get(i), WIN_CONSTANT * playersAndChips.get(gameTable.getPlayer(i)).getBet());
System.out.println(gameTable.getPlayer(i).getUsername()+ " wins!");
}
}
if (processWinner(b.get(1)) == 0) {
playersAndChips.get(gameTable.getPlayer(i)).addChips(players.get(i), playersAndChips.get(gameTable.getPlayer(i)).getBet());
System.out.println("Draw!");
}
}
}
}
// for (int i=0;i<getPlayers().size();i++) {
// ArrayList<BlackjackHand> handList = playersAndHands.get(gameTable.getPlayer(i));
// for (int j=0;j<handList.size();j++){
// BlackjackHand tmpHand = new BlackjackHand();
// myGame.deal(tmpHand);
// handList.set(i, tmpHand);
// }
// }
// for (ArrayList<BlackjackHand> b : playersAndHands.values()) {
// int numHands = b.size();
// for ( int j = 0 ; j < numHands ; j++ ) {
// BlackjackHand tmpHand = new BlackjackHand();
// myGame.deal(tmpHand);
// b.add(tmpHand);
//
// System.out.println(tmpHand.toString());
//
// BlackjackHand winnerHand = processWinner(tmpHand);
// if (winnerHand == null)
// System.out.print("Draw!");
// else if (winnerHand.getBlackjackValue() == dealerHand.getBlackjackValue())
// System.out.println("Dealer wins!");
// else if (winnerHand.getBlackjackValue() == tmpHand.getBlackjackValue())
// System.out.println("You win!");
// }
//
// }
// for ( int i = 0 ; i < playersHands.size() ; i++ ) {
// Scanner keyboard = new Scanner(System.in);
// int a= keyboard.nextInt();
// System.out.print(a);
// }
}
@Override
public void notifyObservers()
{
if (!observerList.isEmpty()){
for (Observer ob : observerList) {
ob.handleEvent();
}
}
}
@Override
public void addObservers(Observer obsToAdd)
{
observerList.add(obsToAdd);
}
@Override
public void removeObservers(Observer obsToRemove)
{
observerList.remove(obsToRemove);
}
public void resetObservers() {
observerList = new ArrayList<Observer>();
}
public void loadTable(Table table) {
gameTable = table;
}
public void loadPlayers() {
for ( int i = 0 ; i < getPlayers().size() ; i++ ) {
Player tmpPlayer = getPlayers().get(i);
if (!playersAndHands.containsKey(tmpPlayer)) {
playersAndHands.put(tmpPlayer, new ArrayList<BlackjackHand>());
}
}
}
public ArrayList<Player> getPlayers() {
return gameTable.getAllPlayers();
}
public void loadHands() {
}
public void loadChips() {
for ( int i = 0 ; i < getPlayers().size() ; i++ ) {
Player tmpPlayer = getPlayers().get(i);
if (!playersAndChips.containsKey(tmpPlayer)) {
playersAndChips.put(tmpPlayer, new Chips(STARTING_CHIPS));
}
}
}
public void loadBets() {
}
public void setDealer(Player player) {
}
public ArrayList<BlackjackHand> getPlayerHand(Player player) {
return playersAndHands.get(player);
}
/**
* Returns winner between hands of dealer and player
* @param hand BlackjackHand to compare
* @return 1 if dealer won, 0 if no winner, -1 if player won
*/
public int processWinner(BlackjackHand hand) {
if ((hand.isBust()) && !(dealerHand.isBust()))
return DEALER_WON;
if (!(hand.isBust()) && !(dealerHand.isBust()) && (dealerHand.getBlackjackValue() > hand.getBlackjackValue()))
return DEALER_WON;
if (!(hand.isBust()) && (dealerHand.isBust()))
return PLAYER_WON;
if (!(hand.isBust()) && !(dealerHand.isBust()) && dealerHand.getBlackjackValue() < hand.getBlackjackValue()) {
return PLAYER_WON;
}
return DRAW;
}
// public void resetKeepPlayers() {
// myGame = new Blackjack();
// winner = null;
//
// HashMap<Player, Hand> tmpPlayers = new HashMap<Player, Hand>();
// for (int i = 0 ; i < gameTable.getAllPlayers().size() ; i++) {
// Player tmpPlayer = gameTable.getPlayer(i);
// tmpPlayers.put(tmpPlayer, new Hand());
// }
// playersHands = tmpPlayers;
//
// }
public int getNumberOfPlayers() {
return playersAndHands.size();
}
//
// public void playDoubleDown() {
// if ( hasSufficientChips(player, chipCount)) {
// player.chips -= chipCount;
// chipCount += chipCount;
//
// }
/**
* Checks if there is sufficient specified amount of chips
* @param amount The amount to be checked
* @return True if there is sufficient chips, false otherwise
*/
// public boolean hasSufficientChips(Player player, int amount) {
// if ( player.getChips() < amount ) {
// return false;
// }
// return true;
// }
/**
*
* @param
* @return
*/
// public void bet(Player player, int amount) {
// if ( hasSufficientChips(player,amount) ) {
// chipCount += amount;
// player.getChips() -= amount;
// }
// }
public void doHit(){
ArrayList<Player >allplayers=gameTable.getAllPlayers();
for(int i=0;i<allplayers.size();i++){
ArrayList<BlackjackHand> handList = playersAndHands.get(allplayers.get(i));
for(int j=0; j<handList.size();j++){
BlackjackHand hand=handList.get(j);
while(hand.isPlayable()){
if(hand.isBust()==true){
System.out.println("cannot hit, the hand is bust");
}else if(hand.checkBlackjack()==true){
System.out.println("cannot hit, the hand is blackjack");
}else{
myGame.hit(hand);
}
}
}
}
}
public void doStand(){
ArrayList<Player >allplayers=gameTable.getAllPlayers();
for(int i=0;i<allplayers.size();i++){
ArrayList<BlackjackHand> handList = playersAndHands.get(allplayers.get(i));
for(int j=0; j<handList.size();j++){
BlackjackHand hand=handList.get(j);
if(hand.isBust()==true){
System.out.println("cannot stand, the hand is bust");
}else if(hand.checkBlackjack()==true){
System.out.println("cannot stand, the hand is blackjack");
}else{
myGame.stand(hand);
hand.setDone();
}
}
}
}
public void doSplit(){
ArrayList<Player >allplayers=gameTable.getAllPlayers();
for(int i=0;i<allplayers.size();i++){
ArrayList<BlackjackHand> handList = playersAndHands.get(allplayers.get(i));
for(int j=0; j<handList.size();j++){
BlackjackHand hand=handList.get(j);
while(hand.isPlayable()){
if(hand.checkBlackjack()==true){
System.out.println("cannot split, the hand is blackjack");
}else{
myGame.split(hand);
}
}
}
}
}
public void doDoubleDown(){
ArrayList<Player> allplayers=gameTable.getAllPlayers();
for(int i=0;i<allplayers.size();i++){
ArrayList<BlackjackHand> handList = playersAndHands.get(allplayers.get(i));
for(int j=0; j<handList.size();j++){
BlackjackHand hand=handList.get(j);
while(hand.isPlayable()){
if(hand.checkBlackjack()==true){
System.out.println("cannot double down, the hand is blackjack");
}else{
myGame.doubleDown(hand);
}
}
}
}
}
}
| false | true | public void gameStart() {
reset();
/*
* temporarily adding players here for testing purposes,
* later needs to be modified to create/accept players/spectators
*/
Player bob = new Player("bob","bob");
BlackjackHand hb = new BlackjackHand();
ArrayList<BlackjackHand> hbb = new ArrayList<BlackjackHand>();
hbb.add(hb);
Player bab = new Player("bab","bab");
BlackjackHand hb2 = new BlackjackHand();
ArrayList<BlackjackHand> hbb2 = new ArrayList<BlackjackHand>();
hbb2.add(hb2);
// playersAndHands.put(bob, hbb);
// playersAndHands.put(bab, hbb2);
//temporarily testing adding players to the table
//later to be implemented is the actual passing of players to requestJoin
gameTable.requestJoin(bob);
gameTable.requestJoin(bab);
//deal dealer's hand now
myGame.deal(dealerHand);
//these are not quite implemented but they ideally are supposed to load from a previous saved game...?
loadPlayers();
loadHands();
loadChips();
loadBets();
//gathering bet amounts from all players
ArrayList<Player> players = gameTable.getAllPlayers();
Scanner keyboard = new Scanner(System.in);
for (int i=0; i<players.size(); i++) {
//for (int i=0;i<getNumberOfPlayers();i++){
System.out.println(players.get(i).getUsername() + " how much do you want to bet?");
int a = keyboard.nextInt();
//set the bet and remove the chips
try {
playersAndChips.get(players.get(i)).setBet(a);
playersAndChips.get(players.get(i)).addChips(players.get(i), -a);
System.out.println(" you want to bet " + a);
} catch (Exception IllegalArgumentException) {
while (a > playersAndChips.get(players.get(i)).getChips()) {
//add back chips after evaluating while loop condition
//playersAndChips.get(players.get(i)).addChips(players.get(i), a);
System.out.println("sorry not enough chips, please enter " + playersAndChips.get(players.get(i).getChips()) + " or less" );
//System.out.println("sorry not enough chips, please enter " + playersAndChips.get(gameTable.getAllPlayers().get(i)).getChips() + " or less" );
a = keyboard.nextInt();
playersAndChips.get(players.get(i)).setBet(a);
playersAndChips.get(players.get(i)).addChips(players.get(i), -a);
System.out.println(" you want to bet " + a);
}
}
}
//shows dealer's initial hand, game is over if dealer gets blackjack,
//else then dealer hits until it is above 16 pts
System.out.println("Dealer's hand: " + dealerHand.toString());
if (dealerHand.checkBlackjack()) {
dealerHand.setDone();
System.out.println("Game over!");
} else {
while (dealerHand.getBlackjackValue() < MUST_HIT)
myGame.hit(dealerHand);
dealerHand.setDone();
/*
* Deal everyone
*/
System.out.println("Dealing everyone...");
for (int i=0; i<players.size(); i++){
System.out.println(players.get(i).getUsername());
}
for (ArrayList<BlackjackHand> b : playersAndHands.values()) {
BlackjackHand tmpHand = new BlackjackHand();
myGame.deal(tmpHand);
b.add(tmpHand);
}
for (int i=0;i<getNumberOfPlayers();i++){
ArrayList<BlackjackHand> b = playersAndHands.get(gameTable.getPlayer(i));
System.out.println(gameTable.getPlayer(i).getUsername() + ", your first hand is currently: " + b.get(0).toString());
if (b.size() == 2) {
System.out.println(gameTable.getPlayer(i) + ", your second hand is currently: " + b.get(1).toString());
}
}
/*
* Ask for input moves
*/
for (int i=0; i<players.size(); i++){
ArrayList<BlackjackHand> b = playersAndHands.get(players.get(i));
System.out.println(gameTable.getPlayer(i).getUsername()+": ");
//Scanner keyboard = new Scanner (System.in);
String s = "";
for (int j=0; j < b.size(); j++) {
while (b.get(j).isPlayable() && !(b.get(j).isBust())){
// System.out.println(b.get(j).isPlayable() +"isplayable");
// System.out.println(!(b.get(j).isBust()) +"isbust");
System.out.println("now for your first hand, do you want to hit, stand, double down, split?");
s = keyboard.nextLine();
if (s.equals("hit")){
myGame.hit(b.get(j));
System.out.println("hand update: " +b.get(j).toString());
}
else if (s.equals("stand")){
myGame.stand(b.get(j));
System.out.println("final hand: "+b.get(j).toString());
}
else if (s.equals("double down")){
if (playersAndChips.get(gameTable.getPlayer(i)).addChips(players.get(i), playersAndChips.get(i).getBet())==false) {
System.out.print("sorry not enough chips, please enter a different move" );
s = "";
}
else {
myGame.doubleDown(b.get(j));
System.out.println("hand update: "+b.get(j).toString());
}
}
else if (s.equals("split")){
if (b.get(j).checkPair() == false) {
System.out.println("you dont have a pair! select a different move");
s = "";
} else {
myGame.split(b.get(j));
System.out.println("split to be implemented: "+b.get(j).toString());
}
} else {
System.out.println("please enter something valid");
s = "";
}
}
}
}
//shows dealer's final hand
System.out.println("Dealer's new hand: " + dealerHand.toString());
if (dealerHand.isBust())
System.out.println("Dealer bust!");
/*
* Compute all winners
*/
for (int i=0;i<getNumberOfPlayers();i++){
ArrayList<BlackjackHand> b = playersAndHands.get(gameTable.getPlayer(i));
if (b.size() == 1) {
if (processWinner(b.get(0)) == 1)
System.out.println("Dealer wins!");
if (processWinner(b.get(0)) == -1) {
if (b.get(0).checkBlackjack()) {
playersAndChips.get(gameTable.getPlayer(i)).addChips(players.get(i), BLACKJACK_PAYOUT_CONSTANT * playersAndChips.get(gameTable.getPlayer(i)).getBet());
System.out.println("BLACKJACK! X2 PAYOUT! " + gameTable.getPlayer(i).getUsername()+ " wins!");
} else {
playersAndChips.get(gameTable.getPlayer(i)).addChips(players.get(i), WIN_CONSTANT * playersAndChips.get(gameTable.getPlayer(i)).getBet());
System.out.println(gameTable.getPlayer(i).getUsername()+ " wins!");
}
}
if (processWinner(b.get(0)) == 0) {
playersAndChips.get(gameTable.getPlayer(i)).addChips(players.get(i), playersAndChips.get(gameTable.getPlayer(i)).getBet());
System.out.println("Draw!");
}
} else {
if (processWinner(b.get(0)) == 1)
System.out.println("Dealer wins!");
if (processWinner(b.get(0)) == -1) {
if (b.get(0).checkBlackjack()) {
playersAndChips.get(gameTable.getPlayer(i)).addChips(players.get(i), BLACKJACK_PAYOUT_CONSTANT * playersAndChips.get(gameTable.getPlayer(i)).getBet());
System.out.println("BLACKJACK! X2 PAYOUT! " + gameTable.getPlayer(i).getUsername()+ " wins!");
} else {
playersAndChips.get(gameTable.getPlayer(i)).addChips(players.get(i), WIN_CONSTANT * playersAndChips.get(gameTable.getPlayer(i)).getBet());
System.out.println(gameTable.getPlayer(i).getUsername()+ " wins!");
}
}
if (processWinner(b.get(0)) == 0) {
playersAndChips.get(gameTable.getPlayer(i)).addChips(players.get(i), playersAndChips.get(gameTable.getPlayer(i)).getBet());
System.out.println("Draw!");
}
if (processWinner(b.get(1)) == 1)
System.out.println("Dealer wins!");
if (processWinner(b.get(1)) == -1) {
if (b.get(0).checkBlackjack()) {
playersAndChips.get(gameTable.getPlayer(i)).addChips(players.get(i), BLACKJACK_PAYOUT_CONSTANT * playersAndChips.get(gameTable.getPlayer(i)).getBet());
System.out.println("BLACKJACK! X2 PAYOUT! " + gameTable.getPlayer(i).getUsername()+ " wins!");
} else {
playersAndChips.get(gameTable.getPlayer(i)).addChips(players.get(i), WIN_CONSTANT * playersAndChips.get(gameTable.getPlayer(i)).getBet());
System.out.println(gameTable.getPlayer(i).getUsername()+ " wins!");
}
}
if (processWinner(b.get(1)) == 0) {
playersAndChips.get(gameTable.getPlayer(i)).addChips(players.get(i), playersAndChips.get(gameTable.getPlayer(i)).getBet());
System.out.println("Draw!");
}
}
}
}
// for (int i=0;i<getPlayers().size();i++) {
// ArrayList<BlackjackHand> handList = playersAndHands.get(gameTable.getPlayer(i));
// for (int j=0;j<handList.size();j++){
// BlackjackHand tmpHand = new BlackjackHand();
// myGame.deal(tmpHand);
// handList.set(i, tmpHand);
// }
// }
// for (ArrayList<BlackjackHand> b : playersAndHands.values()) {
// int numHands = b.size();
// for ( int j = 0 ; j < numHands ; j++ ) {
// BlackjackHand tmpHand = new BlackjackHand();
// myGame.deal(tmpHand);
// b.add(tmpHand);
//
// System.out.println(tmpHand.toString());
//
// BlackjackHand winnerHand = processWinner(tmpHand);
// if (winnerHand == null)
// System.out.print("Draw!");
// else if (winnerHand.getBlackjackValue() == dealerHand.getBlackjackValue())
// System.out.println("Dealer wins!");
// else if (winnerHand.getBlackjackValue() == tmpHand.getBlackjackValue())
// System.out.println("You win!");
// }
//
// }
// for ( int i = 0 ; i < playersHands.size() ; i++ ) {
// Scanner keyboard = new Scanner(System.in);
// int a= keyboard.nextInt();
// System.out.print(a);
// }
}
| public void gameStart() {
reset();
/*
* temporarily adding players here for testing purposes,
* later needs to be modified to create/accept players/spectators
*/
Player bob = new Player("bob","bob");
BlackjackHand hb = new BlackjackHand();
ArrayList<BlackjackHand> hbb = new ArrayList<BlackjackHand>();
hbb.add(hb);
Player bab = new Player("bab","bab");
BlackjackHand hb2 = new BlackjackHand();
ArrayList<BlackjackHand> hbb2 = new ArrayList<BlackjackHand>();
hbb2.add(hb2);
// playersAndHands.put(bob, hbb);
// playersAndHands.put(bab, hbb2);
//temporarily testing adding players to the table
//later to be implemented is the actual passing of players to requestJoin
gameTable.requestJoin(bob);
gameTable.requestJoin(bab);
//deal dealer's hand now
myGame.deal(dealerHand);
//these are not quite implemented but they ideally are supposed to load from a previous saved game...?
loadPlayers();
loadHands();
loadChips();
loadBets();
//gathering bet amounts from all players
ArrayList<Player> players = gameTable.getAllPlayers();
Scanner keyboard = new Scanner(System.in);
for (int i=0; i<players.size(); i++) {
//for (int i=0;i<getNumberOfPlayers();i++){
System.out.println(players.get(i).getUsername() + " how much do you want to bet?");
int a = keyboard.nextInt();
//set the bet and remove the chips
try {
playersAndChips.get(players.get(i)).setBet(a);
playersAndChips.get(players.get(i)).addChips(players.get(i), -a);
System.out.println(" you want to bet " + a);
} catch (Exception IllegalArgumentException) {
while (a > playersAndChips.get(players.get(i)).getChips()) {
//add back chips after evaluating while loop condition
//playersAndChips.get(players.get(i)).addChips(players.get(i), a);
System.out.println("sorry not enough chips, please enter " + playersAndChips.get(players.get(i).getChips()) + " or less" );
//System.out.println("sorry not enough chips, please enter " + playersAndChips.get(gameTable.getAllPlayers().get(i)).getChips() + " or less" );
a = keyboard.nextInt();
playersAndChips.get(players.get(i)).setBet(a);
playersAndChips.get(players.get(i)).addChips(players.get(i), -a);
System.out.println(" you want to bet " + a);
}
}
}
//shows dealer's initial hand, game is over if dealer gets blackjack,
//else then dealer hits until it is above 16 pts
System.out.println("Dealer's hand: " + dealerHand.toString());
if (dealerHand.checkBlackjack()) {
dealerHand.setDone();
System.out.println("Game over!");
} else {
while (dealerHand.getBlackjackValue() < MUST_HIT)
myGame.hit(dealerHand);
dealerHand.setDone();
/*
* Deal everyone
*/
System.out.println("Dealing everyone...");
for (int i=0; i<players.size(); i++){
System.out.println(players.get(i).getUsername());
}
for (ArrayList<BlackjackHand> b : playersAndHands.values()) {
BlackjackHand tmpHand = new BlackjackHand();
myGame.deal(tmpHand);
b.add(tmpHand);
}
for (int i=0;i<getNumberOfPlayers();i++){
ArrayList<BlackjackHand> b = playersAndHands.get(gameTable.getPlayer(i));
System.out.println(gameTable.getPlayer(i).getUsername() + ", your first hand is currently: " + b.get(0).toString());
if (b.size() == 2) {
System.out.println(gameTable.getPlayer(i) + ", your second hand is currently: " + b.get(1).toString());
}
}
/*
* Ask for input moves
*/
for (int i=0; i<players.size(); i++){
ArrayList<BlackjackHand> b = playersAndHands.get(players.get(i));
System.out.println(gameTable.getPlayer(i).getUsername()+": ");
//Scanner keyboard = new Scanner (System.in);
// String s = "";
for (int j=0; j < b.size(); j++) {
while (b.get(j).isPlayable() && !(b.get(j).isBust())){
// System.out.println(b.get(j).isPlayable() +"isplayable");
// System.out.println(!(b.get(j).isBust()) +"isbust");
System.out.println("now for your first hand, do you want to hit, stand, double down, split?");
String s = keyboard.next();
if (s.equals("hit")){
myGame.hit(b.get(j));
System.out.println("hand update: " +b.get(j).toString());
}
else if (s.equals("stand")){
myGame.stand(b.get(j));
System.out.println("final hand: "+b.get(j).toString());
}
else if (s.equals("double down")){
if (playersAndChips.get(gameTable.getPlayer(i)).addChips(players.get(i), playersAndChips.get(i).getBet())==false) {
System.out.print("sorry not enough chips, please enter a different move" );
s = "";
}
else {
myGame.doubleDown(b.get(j));
System.out.println("hand update: "+b.get(j).toString());
}
}
else if (s.equals("split")){
if (b.get(j).checkPair() == false) {
System.out.println("you dont have a pair! select a different move");
s = "";
} else {
myGame.split(b.get(j));
System.out.println("split to be implemented: "+b.get(j).toString());
}
} else {
System.out.println("please enter something valid");
s = "";
}
}
}
}
//shows dealer's final hand
System.out.println("Dealer's new hand: " + dealerHand.toString());
if (dealerHand.isBust())
System.out.println("Dealer bust!");
/*
* Compute all winners
*/
for (int i=0;i<getNumberOfPlayers();i++){
ArrayList<BlackjackHand> b = playersAndHands.get(gameTable.getPlayer(i));
if (b.size() == 1) {
if (processWinner(b.get(0)) == 1)
System.out.println("Dealer wins!");
if (processWinner(b.get(0)) == -1) {
if (b.get(0).checkBlackjack()) {
playersAndChips.get(gameTable.getPlayer(i)).addChips(players.get(i), BLACKJACK_PAYOUT_CONSTANT * playersAndChips.get(gameTable.getPlayer(i)).getBet());
System.out.println("BLACKJACK! X2 PAYOUT! " + gameTable.getPlayer(i).getUsername()+ " wins!");
} else {
playersAndChips.get(gameTable.getPlayer(i)).addChips(players.get(i), WIN_CONSTANT * playersAndChips.get(gameTable.getPlayer(i)).getBet());
System.out.println(gameTable.getPlayer(i).getUsername()+ " wins!");
}
}
if (processWinner(b.get(0)) == 0) {
playersAndChips.get(gameTable.getPlayer(i)).addChips(players.get(i), playersAndChips.get(gameTable.getPlayer(i)).getBet());
System.out.println("Draw!");
}
} else {
if (processWinner(b.get(0)) == 1)
System.out.println("Dealer wins!");
if (processWinner(b.get(0)) == -1) {
if (b.get(0).checkBlackjack()) {
playersAndChips.get(gameTable.getPlayer(i)).addChips(players.get(i), BLACKJACK_PAYOUT_CONSTANT * playersAndChips.get(gameTable.getPlayer(i)).getBet());
System.out.println("BLACKJACK! X2 PAYOUT! " + gameTable.getPlayer(i).getUsername()+ " wins!");
} else {
playersAndChips.get(gameTable.getPlayer(i)).addChips(players.get(i), WIN_CONSTANT * playersAndChips.get(gameTable.getPlayer(i)).getBet());
System.out.println(gameTable.getPlayer(i).getUsername()+ " wins!");
}
}
if (processWinner(b.get(0)) == 0) {
playersAndChips.get(gameTable.getPlayer(i)).addChips(players.get(i), playersAndChips.get(gameTable.getPlayer(i)).getBet());
System.out.println("Draw!");
}
if (processWinner(b.get(1)) == 1)
System.out.println("Dealer wins!");
if (processWinner(b.get(1)) == -1) {
if (b.get(0).checkBlackjack()) {
playersAndChips.get(gameTable.getPlayer(i)).addChips(players.get(i), BLACKJACK_PAYOUT_CONSTANT * playersAndChips.get(gameTable.getPlayer(i)).getBet());
System.out.println("BLACKJACK! X2 PAYOUT! " + gameTable.getPlayer(i).getUsername()+ " wins!");
} else {
playersAndChips.get(gameTable.getPlayer(i)).addChips(players.get(i), WIN_CONSTANT * playersAndChips.get(gameTable.getPlayer(i)).getBet());
System.out.println(gameTable.getPlayer(i).getUsername()+ " wins!");
}
}
if (processWinner(b.get(1)) == 0) {
playersAndChips.get(gameTable.getPlayer(i)).addChips(players.get(i), playersAndChips.get(gameTable.getPlayer(i)).getBet());
System.out.println("Draw!");
}
}
}
}
// for (int i=0;i<getPlayers().size();i++) {
// ArrayList<BlackjackHand> handList = playersAndHands.get(gameTable.getPlayer(i));
// for (int j=0;j<handList.size();j++){
// BlackjackHand tmpHand = new BlackjackHand();
// myGame.deal(tmpHand);
// handList.set(i, tmpHand);
// }
// }
// for (ArrayList<BlackjackHand> b : playersAndHands.values()) {
// int numHands = b.size();
// for ( int j = 0 ; j < numHands ; j++ ) {
// BlackjackHand tmpHand = new BlackjackHand();
// myGame.deal(tmpHand);
// b.add(tmpHand);
//
// System.out.println(tmpHand.toString());
//
// BlackjackHand winnerHand = processWinner(tmpHand);
// if (winnerHand == null)
// System.out.print("Draw!");
// else if (winnerHand.getBlackjackValue() == dealerHand.getBlackjackValue())
// System.out.println("Dealer wins!");
// else if (winnerHand.getBlackjackValue() == tmpHand.getBlackjackValue())
// System.out.println("You win!");
// }
//
// }
// for ( int i = 0 ; i < playersHands.size() ; i++ ) {
// Scanner keyboard = new Scanner(System.in);
// int a= keyboard.nextInt();
// System.out.print(a);
// }
}
|
diff --git a/src/main/java/nl/lolmen/sortal/SBlockListener.java b/src/main/java/nl/lolmen/sortal/SBlockListener.java
index 1af51a0..43e9737 100644
--- a/src/main/java/nl/lolmen/sortal/SBlockListener.java
+++ b/src/main/java/nl/lolmen/sortal/SBlockListener.java
@@ -1,63 +1,63 @@
package nl.lolmen.sortal;
import java.io.FileOutputStream;
import java.util.Properties;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.SignChangeEvent;
public class SBlockListener implements Listener{
public Main plugin;
public SBlockListener(Main main) {
plugin = main;
}
@EventHandler(priority = EventPriority.NORMAL)
public void onSignChange(SignChangeEvent event){
Player p = event.getPlayer();
for(int i = 0; i<event.getLines().length; i++){
if(event.getLine(i).toLowerCase().contains("[sortal]") || event.getLine(i).toLowerCase().contains(plugin.signContains)){
if(event.getPlayer().hasPermission("sortal.placesign")){
plugin.log.info("[Sortal] Sign placed by " + p.getDisplayName() + ", AKA " + p.getName() + "!");
}else{
p.sendMessage("You are not allowed to place a [sortal] sign!");
event.setCancelled(true);
}
}
}
}
@EventHandler(priority = EventPriority.NORMAL)
public void onBlockBreak(BlockBreakEvent event){
Block block = event.getBlock();
if ((block.getType() == Material.SIGN_POST || block.getType() == Material.WALL_SIGN)) {
+ if(!plugin.loc.containsKey(block.getLocation())){
+ return;
+ }
if(!event.getPlayer().hasPermission("sortal.delsign")){
event.getPlayer().sendMessage("[Sortal] You do not have permissions to destroy a registered sign!");
event.setCancelled(true);
}
- if(plugin.loc.containsKey(block.getLocation())){
- delLoc(block.getLocation());
- plugin.log.info("Registered sign destroyed by " + event.getPlayer().getDisplayName() + ", AKA " + event.getPlayer().getName() + "!");
- }
- return;
+ delLoc(block.getLocation());
+ plugin.log.info("Registered sign destroyed by " + event.getPlayer().getDisplayName() + ", AKA " + event.getPlayer().getName() + "!");
}
}
private void delLoc(Location location) {
Properties prop = new Properties();
try {
prop.remove(location);
prop.store(new FileOutputStream(plugin.locs), "[Location] = [Name]");
plugin.loc.remove(location);
} catch (Exception e) {
e.printStackTrace();
}
}
}
| false | true | public void onBlockBreak(BlockBreakEvent event){
Block block = event.getBlock();
if ((block.getType() == Material.SIGN_POST || block.getType() == Material.WALL_SIGN)) {
if(!event.getPlayer().hasPermission("sortal.delsign")){
event.getPlayer().sendMessage("[Sortal] You do not have permissions to destroy a registered sign!");
event.setCancelled(true);
}
if(plugin.loc.containsKey(block.getLocation())){
delLoc(block.getLocation());
plugin.log.info("Registered sign destroyed by " + event.getPlayer().getDisplayName() + ", AKA " + event.getPlayer().getName() + "!");
}
return;
}
}
| public void onBlockBreak(BlockBreakEvent event){
Block block = event.getBlock();
if ((block.getType() == Material.SIGN_POST || block.getType() == Material.WALL_SIGN)) {
if(!plugin.loc.containsKey(block.getLocation())){
return;
}
if(!event.getPlayer().hasPermission("sortal.delsign")){
event.getPlayer().sendMessage("[Sortal] You do not have permissions to destroy a registered sign!");
event.setCancelled(true);
}
delLoc(block.getLocation());
plugin.log.info("Registered sign destroyed by " + event.getPlayer().getDisplayName() + ", AKA " + event.getPlayer().getName() + "!");
}
}
|
diff --git a/plugins/org.eclipse.jst.j2ee.ui/j2ee_ui/org/eclipse/jst/j2ee/internal/war/ui/util/J2EEWebAppItemProvider.java b/plugins/org.eclipse.jst.j2ee.ui/j2ee_ui/org/eclipse/jst/j2ee/internal/war/ui/util/J2EEWebAppItemProvider.java
index 1e9f72562..c48e3afa7 100644
--- a/plugins/org.eclipse.jst.j2ee.ui/j2ee_ui/org/eclipse/jst/j2ee/internal/war/ui/util/J2EEWebAppItemProvider.java
+++ b/plugins/org.eclipse.jst.j2ee.ui/j2ee_ui/org/eclipse/jst/j2ee/internal/war/ui/util/J2EEWebAppItemProvider.java
@@ -1,227 +1,229 @@
/*******************************************************************************
* Copyright (c) 2003, 2005 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
*******************************************************************************/
/*
* Created on Mar 29, 2004
*
* To change the template for this generated file go to
* Window - Preferences - Java - Code Generation - Code and Comments
*/
package org.eclipse.jst.j2ee.internal.war.ui.util;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.eclipse.emf.common.notify.AdapterFactory;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.NotificationWrapper;
import org.eclipse.emf.common.notify.impl.AdapterImpl;
import org.eclipse.jst.j2ee.internal.web.providers.WebAppItemProvider;
import org.eclipse.jst.j2ee.webapplication.WebApp;
import org.eclipse.jst.j2ee.webapplication.WebapplicationPackage;
import org.eclipse.jst.j2ee.webservice.wsclient.WebServicesClient;
import org.eclipse.jst.j2ee.webservice.wsclient.Webservice_clientPackage;
import org.eclipse.wst.common.internal.emfworkbench.integration.EditModelEvent;
import org.eclipse.wst.common.internal.emfworkbench.integration.EditModelListener;
/**
* @author jlanuti
*
* To change the template for this generated type comment go to Window - Preferences - Java - Code
* Generation - Code and Comments
*/
public class J2EEWebAppItemProvider extends WebAppItemProvider {
private List children = new ArrayList();
private WebServletGroupItemProvider webServletGroup;
private WebServletMappingGroupItemProvider webServletMappingGroup;
private WebFiltersGroupItemProvider webFiltersGroup;
private WebFilterMappingGroupItemProvider webFilterMappingGroup;
private WebReferencesGroupItemProvider webRefsGroup;
private WebSecurityGroupItemProvider webSecurityGroup;
private J2EEWebServiceClientDDManager clientMgr;
private WebListenerGroupItemProvider webListenerGroup;
/**
* Listen and fire updates for 1.3 web service clients
*/
private class J2EEWebServiceClientDDManager extends AdapterImpl implements EditModelListener {
private WeakReference weakWebApp;
WebServicesClient client;
public J2EEWebServiceClientDDManager(WeakReference weakWebApp) {
this.weakWebApp = weakWebApp;
init();
}
public void init() {
// TODO fix up notification
// editModel = webServiceMgr.getWSEditModel(ProjectUtilities.getProject(webApp));
// if (editModel != null) {
// editModel.addListener(this);
// if (editModel.get13WebServicesClientResource() != null) {
// client = editModel.get13WebServicesClientResource().getWebServicesClient();
// if (client != null)
// client.eAdapters().add(this);
// }
// }
}
/*
* (non-Javadoc)
*
* @see org.eclipse.wst.common.internal.emfworkbench.integration.EditModelListener#editModelChanged(org.eclipse.wst.common.internal.emfworkbench.integration.EditModelEvent)
*/
public void editModelChanged(EditModelEvent anEvent) {
// TODO fix up notification
// if (editModel == null)
// init();
}
/*
* (non-Javadoc)
*
* @see org.eclipse.emf.common.notify.Adapter#notifyChanged(org.eclipse.emf.common.notify.Notification)
*/
public void notifyChanged(Notification notification) {
if (notification.getEventType() == Notification.ADD || notification.getEventType() == Notification.ADD_MANY || notification.getEventType() == Notification.REMOVE || notification.getEventType() == Notification.REMOVE_MANY) {
if (notification.getFeatureID(WebServicesClient.class) == Webservice_clientPackage.WEB_SERVICES_CLIENT__SERVICE_REFS) {
NotificationWrapper notificationWrapper = new NotificationWrapper(webRefsGroup, notification);
fireNotifyChanged(notificationWrapper);
}
}
super.notifyChanged(notification);
}
public void dispose() {
// TODO fix up notification
webServletGroup.dispose();
webServletMappingGroup.dispose();
webFiltersGroup.dispose();
webFilterMappingGroup.dispose();
webRefsGroup.dispose();
webSecurityGroup.dispose();
webListenerGroup.dispose();
weakWebApp = null;
if (client != null)
client.eAdapters().remove(this);
children.clear();
}
}
/**
* Default constructor
*/
public J2EEWebAppItemProvider(AdapterFactory adapterFactory) {
super(adapterFactory);
}
/**
* initilaize list of children
*/
private void initChildren() {
if (clientMgr == null)
clientMgr = new J2EEWebServiceClientDDManager(weakWebApp);
children.add(webServletGroup = new WebServletGroupItemProvider(adapterFactory, weakWebApp));
children.add(webServletMappingGroup = new WebServletMappingGroupItemProvider(adapterFactory, weakWebApp));
children.add(webFiltersGroup = new WebFiltersGroupItemProvider(adapterFactory, weakWebApp));
children.add(webFilterMappingGroup = new WebFilterMappingGroupItemProvider(adapterFactory, weakWebApp));
children.add(webRefsGroup = new WebReferencesGroupItemProvider(adapterFactory, weakWebApp));
children.add(webSecurityGroup = new WebSecurityGroupItemProvider(adapterFactory, weakWebApp));
children.add(webListenerGroup = new WebListenerGroupItemProvider(adapterFactory, weakWebApp));
}
protected WeakReference weakWebApp = null;
public Collection getChildren(Object object) {
children.clear();
if (object instanceof WebApp && children.isEmpty()) {
weakWebApp = new WeakReference(object);
initChildren();
}
if (object instanceof WebApp)
weakWebApp = new WeakReference(object);
return children;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.emf.edit.provider.ItemProviderAdapter#hasChildren(java.lang.Object)
*/
public boolean hasChildren(Object object) {
return true;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.emf.common.notify.Adapter#notifyChanged(org.eclipse.emf.common.notify.Notification)
*/
public void notifyChanged(Notification notification) {
+ if (children == null || children.isEmpty())
+ initChildren();
// We only care about adds and removes for the different item provider
// groups
if (notification.getEventType() == Notification.ADD || notification.getEventType() == Notification.ADD_MANY || notification.getEventType() == Notification.REMOVE || notification.getEventType() == Notification.REMOVE_MANY) {
Object notifier = null;
switch (notification.getFeatureID(WebApp.class)) {
case WebapplicationPackage.WEB_APP__SERVLETS :
notifier = webServletGroup;
break;
case WebapplicationPackage.WEB_APP__SERVLET_MAPPINGS :
notifier = webServletMappingGroup;
break;
case WebapplicationPackage.WEB_APP__FILTERS :
notifier = webFiltersGroup;
break;
case WebapplicationPackage.WEB_APP__FILTER_MAPPINGS :
notifier = webFilterMappingGroup;
break;
case WebapplicationPackage.WEB_APP__EJB_LOCAL_REFS :
case WebapplicationPackage.WEB_APP__EJB_REFS :
case WebapplicationPackage.WEB_APP__MESSAGE_DESTINATION_REFS :
case WebapplicationPackage.WEB_APP__RESOURCE_ENV_REFS :
case WebapplicationPackage.WEB_APP__RESOURCE_REFS :
case WebapplicationPackage.WEB_APP__SERVICE_REFS :
notifier = webRefsGroup;
break;
case WebapplicationPackage.WEB_APP__SECURITY_ROLES :
case WebapplicationPackage.WEB_APP__CONSTRAINTS :
notifier = webSecurityGroup;
break;
case WebapplicationPackage.WEB_APP__LISTENERS :
notifier = webListenerGroup;
break;
}
if (notifier != null) {
NotificationWrapper notificationWrapper = new NotificationWrapper(notifier, notification);
fireNotifyChanged(notificationWrapper);
}
}
super.notifyChanged(notification);
}
/*
* (non-Javadoc)
*
* @see org.eclipse.emf.edit.provider.IDisposable#dispose()
*/
public void dispose() {
if (clientMgr != null)
clientMgr.dispose();
super.dispose();
}
}
| true | true | public void notifyChanged(Notification notification) {
// We only care about adds and removes for the different item provider
// groups
if (notification.getEventType() == Notification.ADD || notification.getEventType() == Notification.ADD_MANY || notification.getEventType() == Notification.REMOVE || notification.getEventType() == Notification.REMOVE_MANY) {
Object notifier = null;
switch (notification.getFeatureID(WebApp.class)) {
case WebapplicationPackage.WEB_APP__SERVLETS :
notifier = webServletGroup;
break;
case WebapplicationPackage.WEB_APP__SERVLET_MAPPINGS :
notifier = webServletMappingGroup;
break;
case WebapplicationPackage.WEB_APP__FILTERS :
notifier = webFiltersGroup;
break;
case WebapplicationPackage.WEB_APP__FILTER_MAPPINGS :
notifier = webFilterMappingGroup;
break;
case WebapplicationPackage.WEB_APP__EJB_LOCAL_REFS :
case WebapplicationPackage.WEB_APP__EJB_REFS :
case WebapplicationPackage.WEB_APP__MESSAGE_DESTINATION_REFS :
case WebapplicationPackage.WEB_APP__RESOURCE_ENV_REFS :
case WebapplicationPackage.WEB_APP__RESOURCE_REFS :
case WebapplicationPackage.WEB_APP__SERVICE_REFS :
notifier = webRefsGroup;
break;
case WebapplicationPackage.WEB_APP__SECURITY_ROLES :
case WebapplicationPackage.WEB_APP__CONSTRAINTS :
notifier = webSecurityGroup;
break;
case WebapplicationPackage.WEB_APP__LISTENERS :
notifier = webListenerGroup;
break;
}
if (notifier != null) {
NotificationWrapper notificationWrapper = new NotificationWrapper(notifier, notification);
fireNotifyChanged(notificationWrapper);
}
}
super.notifyChanged(notification);
}
| public void notifyChanged(Notification notification) {
if (children == null || children.isEmpty())
initChildren();
// We only care about adds and removes for the different item provider
// groups
if (notification.getEventType() == Notification.ADD || notification.getEventType() == Notification.ADD_MANY || notification.getEventType() == Notification.REMOVE || notification.getEventType() == Notification.REMOVE_MANY) {
Object notifier = null;
switch (notification.getFeatureID(WebApp.class)) {
case WebapplicationPackage.WEB_APP__SERVLETS :
notifier = webServletGroup;
break;
case WebapplicationPackage.WEB_APP__SERVLET_MAPPINGS :
notifier = webServletMappingGroup;
break;
case WebapplicationPackage.WEB_APP__FILTERS :
notifier = webFiltersGroup;
break;
case WebapplicationPackage.WEB_APP__FILTER_MAPPINGS :
notifier = webFilterMappingGroup;
break;
case WebapplicationPackage.WEB_APP__EJB_LOCAL_REFS :
case WebapplicationPackage.WEB_APP__EJB_REFS :
case WebapplicationPackage.WEB_APP__MESSAGE_DESTINATION_REFS :
case WebapplicationPackage.WEB_APP__RESOURCE_ENV_REFS :
case WebapplicationPackage.WEB_APP__RESOURCE_REFS :
case WebapplicationPackage.WEB_APP__SERVICE_REFS :
notifier = webRefsGroup;
break;
case WebapplicationPackage.WEB_APP__SECURITY_ROLES :
case WebapplicationPackage.WEB_APP__CONSTRAINTS :
notifier = webSecurityGroup;
break;
case WebapplicationPackage.WEB_APP__LISTENERS :
notifier = webListenerGroup;
break;
}
if (notifier != null) {
NotificationWrapper notificationWrapper = new NotificationWrapper(notifier, notification);
fireNotifyChanged(notificationWrapper);
}
}
super.notifyChanged(notification);
}
|
diff --git a/eclipse/plugins/net.sf.orcc.backends/src/net/sf/orcc/backends/tta/architecture/impl/ArchitectureFactoryImpl.java b/eclipse/plugins/net.sf.orcc.backends/src/net/sf/orcc/backends/tta/architecture/impl/ArchitectureFactoryImpl.java
index 820ebbbf3..15a634e86 100644
--- a/eclipse/plugins/net.sf.orcc.backends/src/net/sf/orcc/backends/tta/architecture/impl/ArchitectureFactoryImpl.java
+++ b/eclipse/plugins/net.sf.orcc.backends/src/net/sf/orcc/backends/tta/architecture/impl/ArchitectureFactoryImpl.java
@@ -1,899 +1,899 @@
/*
* Copyright (c) 2011, IRISA
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * 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.
* * Neither the name of IRISA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS 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 COPYRIGHT OWNER OR 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.
*/
package net.sf.orcc.backends.tta.architecture.impl;
import java.util.Map;
import net.sf.orcc.backends.tta.architecture.AddressSpace;
import net.sf.orcc.backends.tta.architecture.ArchitectureFactory;
import net.sf.orcc.backends.tta.architecture.ArchitecturePackage;
import net.sf.orcc.backends.tta.architecture.Bridge;
import net.sf.orcc.backends.tta.architecture.Bus;
import net.sf.orcc.backends.tta.architecture.Element;
import net.sf.orcc.backends.tta.architecture.ExprBinary;
import net.sf.orcc.backends.tta.architecture.ExprFalse;
import net.sf.orcc.backends.tta.architecture.ExprTrue;
import net.sf.orcc.backends.tta.architecture.ExprUnary;
import net.sf.orcc.backends.tta.architecture.Extension;
import net.sf.orcc.backends.tta.architecture.FunctionUnit;
import net.sf.orcc.backends.tta.architecture.GlobalControlUnit;
import net.sf.orcc.backends.tta.architecture.Guard;
import net.sf.orcc.backends.tta.architecture.OpBinary;
import net.sf.orcc.backends.tta.architecture.OpUnary;
import net.sf.orcc.backends.tta.architecture.Operation;
import net.sf.orcc.backends.tta.architecture.Port;
import net.sf.orcc.backends.tta.architecture.Reads;
import net.sf.orcc.backends.tta.architecture.RegisterFile;
import net.sf.orcc.backends.tta.architecture.Resource;
import net.sf.orcc.backends.tta.architecture.Segment;
import net.sf.orcc.backends.tta.architecture.ShortImmediate;
import net.sf.orcc.backends.tta.architecture.Socket;
import net.sf.orcc.backends.tta.architecture.SocketType;
import net.sf.orcc.backends.tta.architecture.TTA;
import net.sf.orcc.backends.tta.architecture.Term;
import net.sf.orcc.backends.tta.architecture.TermBool;
import net.sf.orcc.backends.tta.architecture.TermUnit;
import net.sf.orcc.backends.tta.architecture.Writes;
import net.sf.orcc.ir.util.EcoreHelper;
import org.eclipse.emf.common.util.BasicEList;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EDataType;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.impl.EFactoryImpl;
import org.eclipse.emf.ecore.plugin.EcorePlugin;
/**
* <!-- begin-user-doc --> An implementation of the model <b>Factory</b>. <!--
* end-user-doc -->
* @generated
*/
public class ArchitectureFactoryImpl extends EFactoryImpl implements
ArchitectureFactory {
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @deprecated
* @generated
*/
@Deprecated
public static ArchitecturePackage getPackage() {
return ArchitecturePackage.eINSTANCE;
}
/**
* Creates the default factory implementation.
* <!-- begin-user-doc --> <!--
* end-user-doc -->
* @generated
*/
public static ArchitectureFactory init() {
try {
ArchitectureFactory theArchitectureFactory = (ArchitectureFactory)EPackage.Registry.INSTANCE.getEFactory("http://orcc.sf.net/backends/tta/architecture/TTA_architecture");
if (theArchitectureFactory != null) {
return theArchitectureFactory;
}
}
catch (Exception exception) {
EcorePlugin.INSTANCE.log(exception);
}
return new ArchitectureFactoryImpl();
}
/**
* Creates an instance of the factory.
* <!-- begin-user-doc --> <!--
* end-user-doc -->
* @generated
*/
public ArchitectureFactoryImpl() {
super();
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public String convertExtensionToString(EDataType eDataType,
Object instanceValue) {
return instanceValue == null ? null : instanceValue.toString();
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public String convertOpBinaryToString(EDataType eDataType,
Object instanceValue) {
return instanceValue == null ? null : instanceValue.toString();
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public String convertOpUnaryToString(EDataType eDataType,
Object instanceValue) {
return instanceValue == null ? null : instanceValue.toString();
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public String convertSocketTypeToString(EDataType eDataType,
Object instanceValue) {
return instanceValue == null ? null : instanceValue.toString();
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
@Override
public String convertToString(EDataType eDataType, Object instanceValue) {
switch (eDataType.getClassifierID()) {
case ArchitecturePackage.SOCKET_TYPE:
return convertSocketTypeToString(eDataType, instanceValue);
case ArchitecturePackage.EXTENSION:
return convertExtensionToString(eDataType, instanceValue);
case ArchitecturePackage.OP_UNARY:
return convertOpUnaryToString(eDataType, instanceValue);
case ArchitecturePackage.OP_BINARY:
return convertOpBinaryToString(eDataType, instanceValue);
default:
throw new IllegalArgumentException("The datatype '" + eDataType.getName() + "' is not a valid classifier");
}
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
@Override
public EObject create(EClass eClass) {
switch (eClass.getClassifierID()) {
case ArchitecturePackage.TTA: return createTTA();
case ArchitecturePackage.BUS: return createBus();
case ArchitecturePackage.BRIDGE: return createBridge();
case ArchitecturePackage.SEGMENT: return createSegment();
case ArchitecturePackage.GLOBAL_CONTROL_UNIT: return createGlobalControlUnit();
case ArchitecturePackage.FUNCTION_UNIT: return createFunctionUnit();
case ArchitecturePackage.REGISTER_FILE: return createRegisterFile();
case ArchitecturePackage.PORT: return createPort();
case ArchitecturePackage.SOCKET: return createSocket();
case ArchitecturePackage.OPERATION: return createOperation();
case ArchitecturePackage.ADDRESS_SPACE: return createAddressSpace();
case ArchitecturePackage.READS: return createReads();
case ArchitecturePackage.WRITES: return createWrites();
case ArchitecturePackage.RESOURCE: return createResource();
case ArchitecturePackage.SHORT_IMMEDIATE: return createShortImmediate();
case ArchitecturePackage.EXPR_UNARY: return createExprUnary();
case ArchitecturePackage.EXPR_BINARY: return createExprBinary();
case ArchitecturePackage.EXPR_TRUE: return createExprTrue();
case ArchitecturePackage.EXPR_FALSE: return createExprFalse();
case ArchitecturePackage.TERM_BOOL: return createTermBool();
case ArchitecturePackage.TERM_UNIT: return createTermUnit();
case ArchitecturePackage.PORT_TO_INDEX_MAP_ENTRY: return (EObject)createportToIndexMapEntry();
default:
throw new IllegalArgumentException("The class '" + eClass.getName() + "' is not a valid classifier");
}
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public AddressSpace createAddressSpace() {
AddressSpaceImpl addressSpace = new AddressSpaceImpl();
return addressSpace;
}
@Override
public AddressSpace createAddressSpace(String name, int width, int minAddress,
int maxAddress) {
AddressSpaceImpl addressSpace = new AddressSpaceImpl();
addressSpace.setName(name);
addressSpace.setWidth(width);
addressSpace.setMinAddress(minAddress);
addressSpace.setMaxAddress(maxAddress);
return addressSpace;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public Bridge createBridge() {
BridgeImpl bridge = new BridgeImpl();
return bridge;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public Bus createBus() {
BusImpl bus = new BusImpl();
return bus;
}
@Override
public Bus createBus(int index, int width) {
BusImpl bus = new BusImpl();
bus.setName("Bus" + index);
bus.setWidth(width);
return bus;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public ExprBinary createExprBinary() {
ExprBinaryImpl exprBinary = new ExprBinaryImpl();
return exprBinary;
}
@Override
public ExprBinary createExprBinary(OpBinary op, ExprUnary e1, ExprUnary e2) {
ExprBinaryImpl exprBinary = new ExprBinaryImpl();
exprBinary.setE1(e1);
exprBinary.setE2(e2);
exprBinary.setOperator(op);
return exprBinary;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public ExprFalse createExprFalse() {
ExprFalseImpl exprFalse = new ExprFalseImpl();
return exprFalse;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public ExprTrue createExprTrue() {
ExprTrueImpl exprTrue = new ExprTrueImpl();
return exprTrue;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public ExprUnary createExprUnary() {
ExprUnaryImpl exprUnary = new ExprUnaryImpl();
return exprUnary;
}
@Override
public ExprUnary createExprUnary(boolean isInverted, Term term) {
ExprUnaryImpl exprUnary = new ExprUnaryImpl();
if (isInverted) {
exprUnary.setOperator(OpUnary.INVERTED);
} else {
exprUnary.setOperator(OpUnary.SIMPLE);
}
exprUnary.setTerm(term);
return exprUnary;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public Extension createExtensionFromString(EDataType eDataType,
String initialValue) {
Extension result = Extension.get(initialValue);
if (result == null) throw new IllegalArgumentException("The value '" + initialValue + "' is not a valid enumerator of '" + eDataType.getName() + "'");
return result;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
@Override
public Object createFromString(EDataType eDataType, String initialValue) {
switch (eDataType.getClassifierID()) {
case ArchitecturePackage.SOCKET_TYPE:
return createSocketTypeFromString(eDataType, initialValue);
case ArchitecturePackage.EXTENSION:
return createExtensionFromString(eDataType, initialValue);
case ArchitecturePackage.OP_UNARY:
return createOpUnaryFromString(eDataType, initialValue);
case ArchitecturePackage.OP_BINARY:
return createOpBinaryFromString(eDataType, initialValue);
default:
throw new IllegalArgumentException("The datatype '" + eDataType.getName() + "' is not a valid classifier");
}
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public FunctionUnit createFunctionUnit() {
FunctionUnitImpl functionUnit = new FunctionUnitImpl();
return functionUnit;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public GlobalControlUnit createGlobalControlUnit() {
GlobalControlUnitImpl globalControlUnit = new GlobalControlUnitImpl();
return globalControlUnit;
}
@Override
public GlobalControlUnit createGlobalControlUnit(int delaySlots,
int guardLatency) {
GlobalControlUnitImpl globalControlUnit = new GlobalControlUnitImpl();
globalControlUnit.setDelaySlots(delaySlots);
globalControlUnit.setGuardLatency(guardLatency);
return globalControlUnit;
}
@Override
public Socket createInputSocket(String name, EList<Segment> segments) {
Socket socket = createSocket(name, segments);
socket.setType(SocketType.INPUT);
return socket;
}
@Override
public FunctionUnit createLSU(TTA tta) {
FunctionUnit LSU = createFonctionUnit(tta, "LSU");
// Operations
EList<Port> ports = LSU.getPorts();
String[] loadOperations = { "ldw", "ldq", "ldh", "ldqu", "ldhu" };
for (String loadOperation : loadOperations) {
LSU.getOperations().add(
createOperationLoad(loadOperation, ports.get(0),
ports.get(2)));
}
String[] storeOperations = { "stw", "stq", "sth" };
for (String storeOperation : storeOperations) {
LSU.getOperations().add(
createOperationLoad(storeOperation, ports.get(0),
ports.get(1)));
}
LSU.setAddressSpace(tta.getData());
return LSU;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public OpBinary createOpBinaryFromString(EDataType eDataType,
String initialValue) {
OpBinary result = OpBinary.get(initialValue);
if (result == null) throw new IllegalArgumentException("The value '" + initialValue + "' is not a valid enumerator of '" + eDataType.getName() + "'");
return result;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public Operation createOperation() {
OperationImpl operation = new OperationImpl();
return operation;
}
@Override
public Operation createOperation(String name) {
OperationImpl operation = new OperationImpl();
operation.setName(name);
return operation;
}
@Override
public Operation createOperationLoad(String name, Port in, Port out) {
return createOperationDefault(name, in, 0, 1, true, out, 2, 1, false);
}
@Override
public Operation createOperationStore(String name, Port in1, Port in2) {
return createOperationDefault(name, in1, 0, 1, true, in2, 2, 1, true);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public OpUnary createOpUnaryFromString(EDataType eDataType,
String initialValue) {
OpUnary result = OpUnary.get(initialValue);
if (result == null) throw new IllegalArgumentException("The value '" + initialValue + "' is not a valid enumerator of '" + eDataType.getName() + "'");
return result;
}
@Override
public Socket createOutputSocket(String name, EList<Segment> segments) {
Socket socket = createSocket(name, segments);
socket.setType(SocketType.OUTPUT);
return socket;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public Port createPort() {
PortImpl port = new PortImpl();
return port;
}
@Override
public Port createPort(String name) {
PortImpl port = new PortImpl();
port.setName(name);
return port;
}
@Override
public Port createPort(String name, int width, boolean isOpcodeSelector,
boolean isTrigger) {
Port port = createPort(name);
port.setWidth(width);
port.setOpcodeSelector(isOpcodeSelector);
port.setTrigger(isTrigger);
return port;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public Map.Entry<Port, Integer> createportToIndexMapEntry() {
portToIndexMapEntryImpl portToIndexMapEntry = new portToIndexMapEntryImpl();
return portToIndexMapEntry;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public Reads createReads() {
ReadsImpl reads = new ReadsImpl();
return reads;
}
@Override
public Reads createReads(Port port, int startCycle, int cycle) {
ReadsImpl reads = new ReadsImpl();
reads.setPort(port);
reads.setStartCycle(startCycle);
reads.setCycles(cycle);
return reads;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public RegisterFile createRegisterFile() {
RegisterFileImpl registerFile = new RegisterFileImpl();
return registerFile;
}
@Override
public RegisterFile createRegisterFile(String name, int size, int width,
int maxReads, int maxWrites) {
RegisterFileImpl registerFile = new RegisterFileImpl();
registerFile.setName(name);
registerFile.setSize(size);
registerFile.setWidth(width);
registerFile.setMaxReads(maxReads);
registerFile.setMaxWrites(maxWrites);
return registerFile;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public Resource createResource() {
ResourceImpl resource = new ResourceImpl();
return resource;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public Segment createSegment() {
SegmentImpl segment = new SegmentImpl();
return segment;
}
@Override
public Segment createSegment(String name) {
SegmentImpl segment = new SegmentImpl();
segment.setName(name);
return segment;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public ShortImmediate createShortImmediate() {
ShortImmediateImpl shortImmediate = new ShortImmediateImpl();
return shortImmediate;
}
@Override
public ShortImmediate createShortImmediate(int width, Extension extension) {
ShortImmediateImpl shortImmediate = new ShortImmediateImpl();
shortImmediate.setWidth(width);
shortImmediate.setExtension(extension);
return shortImmediate;
}
@Override
public Bus createBusDefault(int index, int width) {
Bus bus = createBus(index, width);
bus.getSegments().add(createSegment("segment0"));
bus.setShortImmediate(createShortImmediate(width, Extension.ZERO));
return bus;
}
@Override
public Operation createOperationCtrl(String name, Port port) {
Operation operation = new OperationImpl();
operation.setName(name);
operation.setControl(true);
operation.getPipeline().add(createReads(port, 0, 1));
operation.getPortToIndexMap().put(port, 1);
return operation;
}
@Override
public FunctionUnit createFonctionUnit(TTA tta, String name) {
FunctionUnitImpl functionUnit = new FunctionUnitImpl();
functionUnit.setName(name);
// Sockets
EList<Segment> segments = getAllSegments(tta.getBuses());
Socket i1 = createInputSocket(name + "_i1", segments);
Socket i2 = createInputSocket(name + "_i2", segments);
Socket o1 = createOutputSocket(name + "_o1", segments);
// Port
Port in1t = createPort("in1t", 32, true, true);
Port in2 = createPort("in2", 32, false, false);
Port out1 = createPort("out1", 32, false, false);
in1t.connect(i1);
in2.connect(i2);
out1.connect(o1);
functionUnit.getPorts().add(in1t);
functionUnit.getPorts().add(in2);
functionUnit.getPorts().add(out1);
return functionUnit;
}
@Override
public FunctionUnit createFonctionUnit(TTA tta, String name,
String[] operations1, String[] operations2) {
FunctionUnit functionUnit = createFonctionUnit(tta, name);
EList<Port> ports = functionUnit.getPorts();
// Operations
if (operations1 != null) {
for (String operation : operations1) {
functionUnit.getOperations().add(
createOperationDefault(operation, ports.get(0),
ports.get(2)));
}
}
if (operations2 != null) {
for (String operation : operations2) {
functionUnit.getOperations().add(
createOperationDefault(operation, ports.get(0),
ports.get(1), ports.get(2)));
}
}
return functionUnit;
}
@Override
public GlobalControlUnit createGlobalControlUnitDefault(TTA tta) {
GlobalControlUnit gcu = createGlobalControlUnit(3, 1);
gcu.setAddressSpace(tta.getProgram());
// Sockets
EList<Segment> segments = getAllSegments(tta.getBuses());
Socket gcu_i1 = createInputSocket("gcu_i1", segments);
Socket gcu_i2 = createInputSocket("gcu_i2", segments);
Socket gcu_o1 = createOutputSocket("gcu_o1", segments);
// Ports
Port pc = createPort("pc", 13, true, true);
pc.connect(gcu_i1);
Port ra = createPort("ra", 13, false, false);
ra.connect(gcu_i2);
ra.connect(gcu_o1);
gcu.setReturnAddress(ra);
gcu.getPorts().add(pc);
// Control operations
gcu.getOperations().add(createOperationCtrl("jump", pc));
gcu.getOperations().add(createOperationCtrl("call", pc));
return gcu;
}
@Override
public EList<Guard> createGuardsDefault(RegisterFile register) {
EList<Guard> guards = new BasicEList<Guard>();
guards.add(createExprTrue());
guards.add(createExprUnary(false, createTermBool(register, 0)));
guards.add(createExprUnary(true, createTermBool(register, 0)));
guards.add(createExprUnary(false, createTermBool(register, 1)));
guards.add(createExprUnary(true, createTermBool(register, 1)));
return guards;
}
@Override
public Operation createOperationDefault(String name, Port port1,
int startCycle1, int cycle1, boolean isReads1, Port port2,
int startCycle2, int cycle2, boolean isReads2) {
Operation operation = createOperation(name);
operation.setControl(false);
operation.getPortToIndexMap().put(port1, 1);
operation.getPortToIndexMap().put(port2, 2);
Element element1, element2;
if (isReads1) {
element1 = createReads(port1, startCycle1, cycle1);
} else {
element1 = createWrites(port1, startCycle1, cycle1);
}
if (isReads2) {
element2 = createReads(port2, startCycle2, cycle2);
} else {
element2 = createWrites(port2, startCycle2, cycle2);
}
operation.getPipeline().add(element1);
operation.getPipeline().add(element2);
return operation;
}
@Override
public Operation createOperationDefault(String name, Port in1, Port out1) {
Operation operation = createOperation(name);
operation.setControl(false);
operation.getPortToIndexMap().put(in1, 1);
operation.getPortToIndexMap().put(out1, 2);
operation.getPipeline().add(createReads(in1, 0, 1));
operation.getPipeline().add(createWrites(out1, 0, 1));
return operation;
}
@Override
public Operation createOperationDefault(String name, Port in1, Port in2,
Port out1) {
Operation operation = createOperation(name);
operation.setControl(false);
operation.getPortToIndexMap().put(in1, 1);
operation.getPortToIndexMap().put(in2, 2);
operation.getPortToIndexMap().put(out1, 3);
operation.getPipeline().add(createReads(in1, 0, 1));
operation.getPipeline().add(createReads(in2, 0, 1));
operation.getPipeline().add(createWrites(out1, 0, 1));
return operation;
}
@Override
public RegisterFile createRegisterFileDefault(TTA tta, String name,
int size, int width) {
RegisterFile registerFile = createRegisterFile(name, size, width, 1, 1);
// Sockets
EList<Segment> segments = getAllSegments(tta.getBuses());
Socket i1 = createInputSocket(name + "_i1", segments);
Socket o1 = createOutputSocket(name + "_o1", segments);
// Ports
Port wr = createPort("wr");
wr.connect(o1);
Port rd = createPort("rd");
rd.connect(i1);
registerFile.getPorts().add(wr);
registerFile.getPorts().add(rd);
return registerFile;
}
@Override
public TTA createTTADefault(String name) {
TTA tta = createTTA(name);
// Address spaces
tta.setData(createAddressSpace("data", 8, 0, 131071));
tta.setProgram(createAddressSpace("instructions", 8, 0, 8191));
// Buses
Bus bus0 = createBusDefault(0, 32);
Bus bus1 = createBusDefault(1, 32);
tta.getBuses().add(bus0);
tta.getBuses().add(bus1);
// Global Control Unit
tta.setGcu(createGlobalControlUnitDefault(tta));
// Register files
- RegisterFile bool = createRegisterFileDefault(tta, "BOOL", 1, 2);
- RegisterFile rf1 = createRegisterFileDefault(tta, "RF_1", 32, 12);
- RegisterFile rf2 = createRegisterFileDefault(tta, "RF_2", 32, 12);
+ RegisterFile bool = createRegisterFileDefault(tta, "BOOL", 2, 1);
+ RegisterFile rf1 = createRegisterFileDefault(tta, "RF_1", 12, 32);
+ RegisterFile rf2 = createRegisterFileDefault(tta, "RF_2", 12, 32);
tta.getRegisterFiles().add(bool);
tta.getRegisterFiles().add(rf1);
tta.getRegisterFiles().add(rf2);
// Guards
bus0.getGuards().addAll(createGuardsDefault(bool));
bus1.getGuards().addAll(createGuardsDefault(bool));
// Fonctional units
EList<FunctionUnit> units = tta.getFunctionUnits();
// * ALU
String[] aluOperations1 = { "sxqw", "sxhw" };
String[] aluOperations2 = { "add", "and", "eq", "gt", "gtu", "ior",
"shl", "shr", "shru", "sub", "xor" };
units.add(createFonctionUnit(tta, "ALU", aluOperations1,
aluOperations2));
// * LSU
units.add(createLSU(tta));
// * Mul
String[] mulOperations2 = { "mul" };
units.add(createFonctionUnit(tta, "Mul", null, mulOperations2));
// * And-ior-xor
String[] aixOperations2 = { "and", "ior", "xor" };
units.add(createFonctionUnit(tta, "And_ior_xor", null,
aixOperations2));
return tta;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public Socket createSocket() {
SocketImpl socket = new SocketImpl();
return socket;
}
@Override
public Socket createSocket(String name, EList<Segment> segments) {
SocketImpl socket = new SocketImpl();
socket.setName(name);
socket.getConnectedSegments().addAll(segments);
EcoreHelper.getContainerOfType(segments.get(0), TTA.class).getSockets()
.add(socket);
return socket;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public SocketType createSocketTypeFromString(EDataType eDataType,
String initialValue) {
SocketType result = SocketType.get(initialValue);
if (result == null) throw new IllegalArgumentException("The value '" + initialValue + "' is not a valid enumerator of '" + eDataType.getName() + "'");
return result;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public TermBool createTermBool() {
TermBoolImpl termBool = new TermBoolImpl();
return termBool;
}
@Override
public TermBool createTermBool(RegisterFile register, int index) {
TermBoolImpl termBool = new TermBoolImpl();
termBool.setRegister(register);
termBool.setIndex(index);
return termBool;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public TermUnit createTermUnit() {
TermUnitImpl termUnit = new TermUnitImpl();
return termUnit;
}
@Override
public TermUnit createTermUnit(FunctionUnit unit, Port port) {
TermUnitImpl termUnit = new TermUnitImpl();
termUnit.setFunctionUnit(unit);
termUnit.setPort(port);
return termUnit;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public TTA createTTA() {
TTAImpl tta = new TTAImpl();
return tta;
}
@Override
public TTA createTTA(String name) {
TTAImpl tta = new TTAImpl();
tta.setName(name);
return tta;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public Writes createWrites() {
WritesImpl writes = new WritesImpl();
return writes;
}
@Override
public Writes createWrites(Port port, int startCycle, int cycle) {
WritesImpl writes = new WritesImpl();
writes.setPort(port);
writes.setStartCycle(startCycle);
writes.setCycles(cycle);
return writes;
}
private EList<Segment> getAllSegments(EList<Bus> buses) {
EList<Segment> segments = new BasicEList<Segment>();
for (Bus bus : buses) {
segments.addAll(bus.getSegments());
}
return segments;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public ArchitecturePackage getArchitecturePackage() {
return (ArchitecturePackage)getEPackage();
}
} // ArchitectureFactoryImpl
| true | true | public TTA createTTADefault(String name) {
TTA tta = createTTA(name);
// Address spaces
tta.setData(createAddressSpace("data", 8, 0, 131071));
tta.setProgram(createAddressSpace("instructions", 8, 0, 8191));
// Buses
Bus bus0 = createBusDefault(0, 32);
Bus bus1 = createBusDefault(1, 32);
tta.getBuses().add(bus0);
tta.getBuses().add(bus1);
// Global Control Unit
tta.setGcu(createGlobalControlUnitDefault(tta));
// Register files
RegisterFile bool = createRegisterFileDefault(tta, "BOOL", 1, 2);
RegisterFile rf1 = createRegisterFileDefault(tta, "RF_1", 32, 12);
RegisterFile rf2 = createRegisterFileDefault(tta, "RF_2", 32, 12);
tta.getRegisterFiles().add(bool);
tta.getRegisterFiles().add(rf1);
tta.getRegisterFiles().add(rf2);
// Guards
bus0.getGuards().addAll(createGuardsDefault(bool));
bus1.getGuards().addAll(createGuardsDefault(bool));
// Fonctional units
EList<FunctionUnit> units = tta.getFunctionUnits();
// * ALU
String[] aluOperations1 = { "sxqw", "sxhw" };
String[] aluOperations2 = { "add", "and", "eq", "gt", "gtu", "ior",
"shl", "shr", "shru", "sub", "xor" };
units.add(createFonctionUnit(tta, "ALU", aluOperations1,
aluOperations2));
// * LSU
units.add(createLSU(tta));
// * Mul
String[] mulOperations2 = { "mul" };
units.add(createFonctionUnit(tta, "Mul", null, mulOperations2));
// * And-ior-xor
String[] aixOperations2 = { "and", "ior", "xor" };
units.add(createFonctionUnit(tta, "And_ior_xor", null,
aixOperations2));
return tta;
}
| public TTA createTTADefault(String name) {
TTA tta = createTTA(name);
// Address spaces
tta.setData(createAddressSpace("data", 8, 0, 131071));
tta.setProgram(createAddressSpace("instructions", 8, 0, 8191));
// Buses
Bus bus0 = createBusDefault(0, 32);
Bus bus1 = createBusDefault(1, 32);
tta.getBuses().add(bus0);
tta.getBuses().add(bus1);
// Global Control Unit
tta.setGcu(createGlobalControlUnitDefault(tta));
// Register files
RegisterFile bool = createRegisterFileDefault(tta, "BOOL", 2, 1);
RegisterFile rf1 = createRegisterFileDefault(tta, "RF_1", 12, 32);
RegisterFile rf2 = createRegisterFileDefault(tta, "RF_2", 12, 32);
tta.getRegisterFiles().add(bool);
tta.getRegisterFiles().add(rf1);
tta.getRegisterFiles().add(rf2);
// Guards
bus0.getGuards().addAll(createGuardsDefault(bool));
bus1.getGuards().addAll(createGuardsDefault(bool));
// Fonctional units
EList<FunctionUnit> units = tta.getFunctionUnits();
// * ALU
String[] aluOperations1 = { "sxqw", "sxhw" };
String[] aluOperations2 = { "add", "and", "eq", "gt", "gtu", "ior",
"shl", "shr", "shru", "sub", "xor" };
units.add(createFonctionUnit(tta, "ALU", aluOperations1,
aluOperations2));
// * LSU
units.add(createLSU(tta));
// * Mul
String[] mulOperations2 = { "mul" };
units.add(createFonctionUnit(tta, "Mul", null, mulOperations2));
// * And-ior-xor
String[] aixOperations2 = { "and", "ior", "xor" };
units.add(createFonctionUnit(tta, "And_ior_xor", null,
aixOperations2));
return tta;
}
|
diff --git a/usage/src/test/java/com/ning/billing/usage/timeline/TestDateTimeUtils.java b/usage/src/test/java/com/ning/billing/usage/timeline/TestDateTimeUtils.java
index fc86f8478..4ef9ea234 100644
--- a/usage/src/test/java/com/ning/billing/usage/timeline/TestDateTimeUtils.java
+++ b/usage/src/test/java/com/ning/billing/usage/timeline/TestDateTimeUtils.java
@@ -1,23 +1,23 @@
package com.ning.billing.usage.timeline;
import org.joda.time.DateTime;
import org.joda.time.Seconds;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.ning.billing.util.clock.Clock;
import com.ning.billing.util.clock.ClockMock;
public class TestDateTimeUtils {
private final Clock clock = new ClockMock();
@Test(groups = "fast")
public void testRoundTrip() throws Exception {
final DateTime utcNow = clock.getUTCNow();
final int unixSeconds = DateTimeUtils.unixSeconds(utcNow);
final DateTime dateTimeFromUnixSeconds = DateTimeUtils.dateTimeFromUnixSeconds(unixSeconds);
- Assert.assertEquals(Seconds.secondsBetween(dateTimeFromUnixSeconds, utcNow), 0);
+ Assert.assertEquals(Seconds.secondsBetween(dateTimeFromUnixSeconds, utcNow).getSeconds(), 0);
}
}
| true | true | public void testRoundTrip() throws Exception {
final DateTime utcNow = clock.getUTCNow();
final int unixSeconds = DateTimeUtils.unixSeconds(utcNow);
final DateTime dateTimeFromUnixSeconds = DateTimeUtils.dateTimeFromUnixSeconds(unixSeconds);
Assert.assertEquals(Seconds.secondsBetween(dateTimeFromUnixSeconds, utcNow), 0);
}
| public void testRoundTrip() throws Exception {
final DateTime utcNow = clock.getUTCNow();
final int unixSeconds = DateTimeUtils.unixSeconds(utcNow);
final DateTime dateTimeFromUnixSeconds = DateTimeUtils.dateTimeFromUnixSeconds(unixSeconds);
Assert.assertEquals(Seconds.secondsBetween(dateTimeFromUnixSeconds, utcNow).getSeconds(), 0);
}
|
diff --git a/src/com/movieadvisor/MovieDetails.java b/src/com/movieadvisor/MovieDetails.java
index b5819ac..6993184 100644
--- a/src/com/movieadvisor/MovieDetails.java
+++ b/src/com/movieadvisor/MovieDetails.java
@@ -1,408 +1,416 @@
package com.movieadvisor;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
import com.database.DataHelper;
public class MovieDetails extends Activity {
private ImageView thumb;
private Movie m;
TextView movie;
private String movieId;
private String movieLink;
private ProgressDialog dialog;
private DataHelper dh;
int nstars = 5;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.moviedetails);
dh = new DataHelper(this);
movie = (TextView) findViewById(R.id.movieName);
Bundle b = this.getIntent().getExtras();
movieLink = b.getString("movieLink");
movieId = b.getString("movieId");
if (movieId == null)
movieId = "-1";
dialog = ProgressDialog.show(this, "", "Loading...", true);
dialog.setCancelable(true);
dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
finish();
}
});
new DownloadMovieDetails().execute(movieLink);
}
private class DownloadMovieDetails extends AsyncTask<String, Void, Movie> {
@Override
protected Movie doInBackground(String... arg0) {
GetMovieDetails movieDetails = new GetMovieDetails(arg0[0],
Integer.parseInt(movieId));
try {
return movieDetails.call();
} catch (Exception e) {
return null;
}
}
protected void onPostExecute(Movie result) {
if(result == null)
{
Toast.makeText(MovieDetails.this, "Details unavaliable", Toast.LENGTH_SHORT).show();
MovieDetails.this.finish();
return;
}
+ try
+ {
m = result;
movieId = String.valueOf(m.idRT);
movie.setText(m.name);
thumb = (ImageView) findViewById(R.id.movieThumb);
thumb.setEnabled(false);
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(getBaseContext());
Boolean moviePoster = prefs.getBoolean("showposter", false);
if (!moviePoster)
new DownloadImageTask().execute(m.imageUrl);
RatingBar rb = (RatingBar) findViewById(R.id.rating);
rb.setEnabled(false);
rb.setNumStars(nstars);
rb.setStepSize((float) 0.2);
rb.setRating((float) (nstars * m.rating) / 100);
ListView genresList = (ListView) findViewById(R.id.genres);
genresList.setDividerHeight(2);
genresList.setEnabled(false);
genresList.setAdapter(new PersonView(m.genres));
Utility.setListViewHeightBasedOnChildren(genresList, m.genres);
ListView actorsList = (ListView) findViewById(R.id.actors);
actorsList.setDividerHeight(2);
actorsList.setEnabled(false);
actorsList.setAdapter(new PersonView(m.actors));
Utility.setListViewHeightBasedOnChildren(actorsList, m.actors);
ListView directorsList = (ListView) findViewById(R.id.directors);
directorsList.setDividerHeight(2);
directorsList.setEnabled(false);
directorsList.setAdapter(new PersonView(m.directors));
Utility.setListViewHeightBasedOnChildren(directorsList, m.directors);
TextView synopsis = (TextView) findViewById(R.id.synopsis);
if (!m.synopsis.equals("")) {
synopsis.setGravity(Gravity.FILL_HORIZONTAL
| Gravity.FILL_VERTICAL);
synopsis.setText(m.synopsis);
} else {
synopsis.setGravity(Gravity.CENTER_HORIZONTAL
| Gravity.CENTER_VERTICAL);
synopsis.setText("Not available");
}
TextView pontuation = (TextView) findViewById(R.id.pontuation);
pontuation.setText((int) m.rating + "/100");
pontuation.setGravity(Gravity.CENTER_VERTICAL
| Gravity.CENTER_HORIZONTAL);
TextView movieYear = (TextView) findViewById(R.id.movieYear);
movieYear.setText("" + m.year);
TextView TrailerLink = (TextView) findViewById(R.id.TrailerLink);
if (m.getTrailerLink() != null && !m.getTrailerLink().equals("null"))
TrailerLink.setText(m.getTrailerLink());
else
TrailerLink.setText("Not avaliable...");
dialog.dismiss();
+ }
+ catch (Exception e) {
+ Toast.makeText(MovieDetails.this, "Details unavaliable", Toast.LENGTH_SHORT).show();
+ MovieDetails.this.finish();
+ return;
+ }
}
}
public class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
protected Bitmap doInBackground(String... urls) {
try {
return loadImageFromNetwork(urls[0]);
} catch (IOException e) {
return null;
} catch (OutOfMemoryError e) {
try {
return loadImageFromNetwork("http://images.rottentomatoescdn.com/images/redesign/poster_default.gif");
} catch (Exception e2) {
return null;
}
} catch (Exception e) {
try {
return loadImageFromNetwork("http://images.rottentomatoescdn.com/images/redesign/poster_default.gif");
} catch (Exception e2) {
return null;
}
}
}
protected void onPostExecute(Bitmap result) {
if (result != null)
thumb.setImageBitmap(result);
}
}
private class GetSimilar
extends
AsyncTask<String, Void, Pair<ArrayList<Integer>, ArrayList<String>>> {
protected Pair<ArrayList<Integer>, ArrayList<String>> doInBackground(
String... id) {
try {
return Utility.getSimilar(Integer.parseInt(id[0]));
} catch (Exception e) {
return null;
}
}
protected void onPostExecute(
Pair<ArrayList<Integer>, ArrayList<String>> result) {
if (result != null) {
Intent intent = new Intent(MovieDetails.this, DisplayList.class);
dialog.dismiss();
Bundle b = new Bundle();
b.putIntegerArrayList("ids", result.getFirst());
b.putStringArrayList("names", result.getSecond());
intent.putExtras(b);
startActivity(intent);
}
else {
dialog.dismiss();
Toast.makeText(MovieDetails.this, "A problem has occurred, please try again!", Toast.LENGTH_SHORT).show();
}
}
}
private Bitmap loadImageFromNetwork(String url)
throws MalformedURLException, IOException {
HttpURLConnection conn = (HttpURLConnection) (new URL(url))
.openConnection();
conn.connect();
return BitmapFactory.decodeStream(new FlushedInputStream(conn
.getInputStream()));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.layout.menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(MovieDetails.this);
/*String account = prefs.getString("accountchooser", null);
if (account == null) {
Utility.checkAccount(MovieDetails.this);
return true;
}*/
Boolean sharePopUp = prefs.getBoolean("sharepopup", false);
switch (item.getItemId()) {
case R.id.suggest:
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_SUBJECT, "MovieAdvisor Suggestion");
i.putExtra(Intent.EXTRA_TEXT,
"Hi! I really liked this movie and you should see it!\n"
+ m.name + "(" + m.year + ")" + "\nRating: "
+ m.rating + "\n\n" + m.imdbLink
+ "\n\nSuggested by Movie Advisor.");
try {
startActivity(Intent.createChooser(i, "Sending..."));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(MovieDetails.this,
"There are no email clients installed.",
Toast.LENGTH_SHORT).show();
}
break;
case R.id.like:
share("I just liked: ",false);
break;
case R.id.want:
if(!sharePopUp)
share("I can't wait to see: ",true);
if (!addToDatabase(0))
Toast.makeText(MovieDetails.this, "This movie is already on that list!", Toast.LENGTH_SHORT).show();
else
Toast.makeText(MovieDetails.this, "Movie added with success!", Toast.LENGTH_SHORT).show();
break;
case R.id.seen:
if(!sharePopUp)
share("I have just seen: ",true);
if (!addToDatabase(1))
Toast.makeText(MovieDetails.this, "This movie is already on that list!", Toast.LENGTH_SHORT).show();
else
Toast.makeText(MovieDetails.this, "Movie added with success!", Toast.LENGTH_SHORT).show();
break;
case R.id.similar:
new GetSimilar().execute(m.idRT + "");
break;
}
return true;
}
public boolean addToDatabase(int idList) {
String movieLinkdb = "http://api.rottentomatoes.com/api/public/v1.0/movies/"+movieId+".json";
try {
switch (idList) {
case 0:
dh.insert("table_tosee", movieId, m.name, movieLinkdb);
if(Utility.lists.size()>0)
Utility.lists.get(0).refreshMyList("refresh");
if(Utility.lists.size()>1)
Utility.lists.get(1).refreshMyList("refresh");
break;
case 1:
HashMap<String,ArrayList<String>> info = dh.selectAll("table_tosee");
if(info.containsKey(movieId)){
dh.deleteID("table_tosee", movieId);
}
dh.insert("table_seen", movieId, m.name, movieLinkdb);
if(Utility.lists.size()>0)
Utility.lists.get(0).refreshMyList("refresh");
if(Utility.lists.size()>1)
Utility.lists.get(1).refreshMyList("refresh");
break;
default:
break;
}
} catch (Exception e) {
Log.e("ERROR Inserting on db", e.getMessage());
return false;
}
return true;
}
public void share(final String message, boolean flag) {
final CharSequence[] itemsTrue = { "Facebook", "Twitter",
"No" };
final CharSequence[] itemsFalse = { "Facebook", "Twitter" };
final CharSequence[] items;
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Share?");
if(flag)
items = itemsTrue;
else
items = itemsFalse;
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
switch (item) {
case 0: {
Intent intent;
Bundle b;
String directors;
intent = new Intent(MovieDetails.this,
FacebookActivity.class);
b = new Bundle();
b.putString("message", message);
b.putString("name", m.name);
b.putString("link", m.getTrailerLink());
directors = "Directed by: ";
for (String a : m.directors)
directors = directors.concat(a) + ", ";
if (!directors.equals("Directed by:")) {
directors = directors.substring(0,
directors.length() - 2);
b.putString("caption", directors);
} else
b.putString("caption", "" + m.year);
b.putString("imageLink", m.imageUrl);
if (!m.synopsis.equals(""))
b.putString("description", m.synopsis);
else {
String actors = "Presenting: ";
for (String a : m.actors)
actors = actors.concat(a) + ", ";
if (!actors.equals("Presenting: ")) {
actors = actors.substring(0, actors.length() - 2);
b.putString("description", actors);
}
}
intent.putExtras(b);
startActivity(intent);
break;
}
case 1: {
Bundle b = new Bundle();
b.putString("text", message + " " + m.name);
Intent intent = new Intent(MovieDetails.this,
TestPost.class);
intent.putExtras(b);
startActivity(intent);
break;
}
default:
break;
}
}
});
AlertDialog alert = builder.create();
alert.show();
}
@Override
protected void onDestroy() {
super.onDestroy();
if (dh != null) {
dh.close();
}
}
}
| false | true | protected void onPostExecute(Movie result) {
if(result == null)
{
Toast.makeText(MovieDetails.this, "Details unavaliable", Toast.LENGTH_SHORT).show();
MovieDetails.this.finish();
return;
}
m = result;
movieId = String.valueOf(m.idRT);
movie.setText(m.name);
thumb = (ImageView) findViewById(R.id.movieThumb);
thumb.setEnabled(false);
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(getBaseContext());
Boolean moviePoster = prefs.getBoolean("showposter", false);
if (!moviePoster)
new DownloadImageTask().execute(m.imageUrl);
RatingBar rb = (RatingBar) findViewById(R.id.rating);
rb.setEnabled(false);
rb.setNumStars(nstars);
rb.setStepSize((float) 0.2);
rb.setRating((float) (nstars * m.rating) / 100);
ListView genresList = (ListView) findViewById(R.id.genres);
genresList.setDividerHeight(2);
genresList.setEnabled(false);
genresList.setAdapter(new PersonView(m.genres));
Utility.setListViewHeightBasedOnChildren(genresList, m.genres);
ListView actorsList = (ListView) findViewById(R.id.actors);
actorsList.setDividerHeight(2);
actorsList.setEnabled(false);
actorsList.setAdapter(new PersonView(m.actors));
Utility.setListViewHeightBasedOnChildren(actorsList, m.actors);
ListView directorsList = (ListView) findViewById(R.id.directors);
directorsList.setDividerHeight(2);
directorsList.setEnabled(false);
directorsList.setAdapter(new PersonView(m.directors));
Utility.setListViewHeightBasedOnChildren(directorsList, m.directors);
TextView synopsis = (TextView) findViewById(R.id.synopsis);
if (!m.synopsis.equals("")) {
synopsis.setGravity(Gravity.FILL_HORIZONTAL
| Gravity.FILL_VERTICAL);
synopsis.setText(m.synopsis);
} else {
synopsis.setGravity(Gravity.CENTER_HORIZONTAL
| Gravity.CENTER_VERTICAL);
synopsis.setText("Not available");
}
TextView pontuation = (TextView) findViewById(R.id.pontuation);
pontuation.setText((int) m.rating + "/100");
pontuation.setGravity(Gravity.CENTER_VERTICAL
| Gravity.CENTER_HORIZONTAL);
TextView movieYear = (TextView) findViewById(R.id.movieYear);
movieYear.setText("" + m.year);
TextView TrailerLink = (TextView) findViewById(R.id.TrailerLink);
if (m.getTrailerLink() != null && !m.getTrailerLink().equals("null"))
TrailerLink.setText(m.getTrailerLink());
else
TrailerLink.setText("Not avaliable...");
dialog.dismiss();
}
| protected void onPostExecute(Movie result) {
if(result == null)
{
Toast.makeText(MovieDetails.this, "Details unavaliable", Toast.LENGTH_SHORT).show();
MovieDetails.this.finish();
return;
}
try
{
m = result;
movieId = String.valueOf(m.idRT);
movie.setText(m.name);
thumb = (ImageView) findViewById(R.id.movieThumb);
thumb.setEnabled(false);
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(getBaseContext());
Boolean moviePoster = prefs.getBoolean("showposter", false);
if (!moviePoster)
new DownloadImageTask().execute(m.imageUrl);
RatingBar rb = (RatingBar) findViewById(R.id.rating);
rb.setEnabled(false);
rb.setNumStars(nstars);
rb.setStepSize((float) 0.2);
rb.setRating((float) (nstars * m.rating) / 100);
ListView genresList = (ListView) findViewById(R.id.genres);
genresList.setDividerHeight(2);
genresList.setEnabled(false);
genresList.setAdapter(new PersonView(m.genres));
Utility.setListViewHeightBasedOnChildren(genresList, m.genres);
ListView actorsList = (ListView) findViewById(R.id.actors);
actorsList.setDividerHeight(2);
actorsList.setEnabled(false);
actorsList.setAdapter(new PersonView(m.actors));
Utility.setListViewHeightBasedOnChildren(actorsList, m.actors);
ListView directorsList = (ListView) findViewById(R.id.directors);
directorsList.setDividerHeight(2);
directorsList.setEnabled(false);
directorsList.setAdapter(new PersonView(m.directors));
Utility.setListViewHeightBasedOnChildren(directorsList, m.directors);
TextView synopsis = (TextView) findViewById(R.id.synopsis);
if (!m.synopsis.equals("")) {
synopsis.setGravity(Gravity.FILL_HORIZONTAL
| Gravity.FILL_VERTICAL);
synopsis.setText(m.synopsis);
} else {
synopsis.setGravity(Gravity.CENTER_HORIZONTAL
| Gravity.CENTER_VERTICAL);
synopsis.setText("Not available");
}
TextView pontuation = (TextView) findViewById(R.id.pontuation);
pontuation.setText((int) m.rating + "/100");
pontuation.setGravity(Gravity.CENTER_VERTICAL
| Gravity.CENTER_HORIZONTAL);
TextView movieYear = (TextView) findViewById(R.id.movieYear);
movieYear.setText("" + m.year);
TextView TrailerLink = (TextView) findViewById(R.id.TrailerLink);
if (m.getTrailerLink() != null && !m.getTrailerLink().equals("null"))
TrailerLink.setText(m.getTrailerLink());
else
TrailerLink.setText("Not avaliable...");
dialog.dismiss();
}
catch (Exception e) {
Toast.makeText(MovieDetails.this, "Details unavaliable", Toast.LENGTH_SHORT).show();
MovieDetails.this.finish();
return;
}
}
|
diff --git a/src/main/java/iReport/iReport.java b/src/main/java/iReport/iReport.java
index 80eceda..8dc9cc9 100644
--- a/src/main/java/iReport/iReport.java
+++ b/src/main/java/iReport/iReport.java
@@ -1,53 +1,52 @@
package iReport;
import java.lang.reflect.Field;
import java.util.Set;
import org.bukkit.command.SimpleCommandMap;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
public class iReport extends JavaPlugin {
MYSQL sql;
public MYSQL getMYSQL() {
PluginManager pm = getServer().getPluginManager();
if (this.sql == null) {
try {
this.sql = new MYSQL();
if (MYSQL.isenable) {
this.sql.queryUpdate("CREATE TABLE IF NOT EXISTS Reports (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(16), Reason VARCHAR (100))");
}
} catch (Exception e) {
e.printStackTrace();
}
}
return this.sql;
}
@Override
public void onEnable() {
try {
- Field field = SimpleCommandMap.class.getDeclaredField("fallbackCommands");
- field.setAccessible(true);
- ((Set) field.get(null)).add(new HReport(this));
- ((Set) field.get(null)).add(new greport(this));
- ((Set) field.get(null)).add(new sreport(this));
- ((Set) field.get(null)).add(new ireportc());
- ((Set) field.get(null)).add(new Reports(this));
+ SimpleCommandMap map = new SimpleCommandMap(getServer());
+ map.register("iReport",new HReport(this));
+ map.register("iReport",new greport(this));
+ map.register("iReport",new sreport(this));
+ map.register("iReport",new ireportc());
+ map.register("iReport",new Reports(this));
} catch (Exception e) {
e.printStackTrace();
}
saveConfig();
getConfig().options().copyDefaults(true);
getMYSQL();
}
@Override
public void onDisable() {
if (sql.isenable) {
sql.closeConnection();
}
}
}
| true | true | public void onEnable() {
try {
Field field = SimpleCommandMap.class.getDeclaredField("fallbackCommands");
field.setAccessible(true);
((Set) field.get(null)).add(new HReport(this));
((Set) field.get(null)).add(new greport(this));
((Set) field.get(null)).add(new sreport(this));
((Set) field.get(null)).add(new ireportc());
((Set) field.get(null)).add(new Reports(this));
} catch (Exception e) {
e.printStackTrace();
}
saveConfig();
getConfig().options().copyDefaults(true);
getMYSQL();
}
| public void onEnable() {
try {
SimpleCommandMap map = new SimpleCommandMap(getServer());
map.register("iReport",new HReport(this));
map.register("iReport",new greport(this));
map.register("iReport",new sreport(this));
map.register("iReport",new ireportc());
map.register("iReport",new Reports(this));
} catch (Exception e) {
e.printStackTrace();
}
saveConfig();
getConfig().options().copyDefaults(true);
getMYSQL();
}
|
diff --git a/merger/src/main/java/com/metamx/druid/merger/coordinator/TaskQueue.java b/merger/src/main/java/com/metamx/druid/merger/coordinator/TaskQueue.java
index e16912b4c6..8dd44cb513 100644
--- a/merger/src/main/java/com/metamx/druid/merger/coordinator/TaskQueue.java
+++ b/merger/src/main/java/com/metamx/druid/merger/coordinator/TaskQueue.java
@@ -1,362 +1,362 @@
/*
* Druid - a distributed column store.
* Copyright (C) 2012 Metamarkets Group Inc.
*
* 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package com.metamx.druid.merger.coordinator;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.base.Throwables;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import com.google.common.collect.Ordering;
import com.metamx.common.lifecycle.LifecycleStart;
import com.metamx.common.lifecycle.LifecycleStop;
import com.metamx.druid.merger.common.TaskStatus;
import com.metamx.druid.merger.common.TaskLock;
import com.metamx.druid.merger.common.task.Task;
import com.metamx.emitter.EmittingLogger;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
/**
* Interface between task producers and task consumers.
* <p/>
* The queue accepts tasks from producers using {@link #add} and delivers tasks to consumers using either
* {@link #take} or {@link #poll}. Ordering is mostly-FIFO, with deviations when the natural next task would conflict
* with a currently-running task. In that case, tasks are skipped until a runnable one is found.
* <p/>
* To manage locking, the queue keeps track of currently-running tasks as {@link com.metamx.druid.merger.common.TaskLock} objects. The idea is that
* only one TaskLock can be running on a particular dataSource + interval, and that TaskLock has a single version
* string that all tasks in the group must use to publish segments. Tasks in the same TaskLock may run concurrently.
* <p/>
* For persistence, the queue saves new tasks from {@link #add} and task status updates from {@link #notify} using a
* {@link TaskStorage} obj
* <p/>
* To support leader election of our containing system, the queue can be stopped (in which case it will not accept
* any new tasks, or hand out any more tasks, until started again).
*/
public class TaskQueue
{
private final List<Task> queue = Lists.newLinkedList();
private final TaskStorage taskStorage;
private final TaskLockbox taskLockbox;
private final ReentrantLock giant = new ReentrantLock();
private final Condition workMayBeAvailable = giant.newCondition();
private volatile boolean active = false;
private static final EmittingLogger log = new EmittingLogger(TaskQueue.class);
public TaskQueue(TaskStorage taskStorage, TaskLockbox taskLockbox)
{
this.taskStorage = Preconditions.checkNotNull(taskStorage, "taskStorage");
this.taskLockbox = Preconditions.checkNotNull(taskLockbox, "taskLockbox");
}
/**
* Bootstraps this task queue and associated task lockbox. Clears the lockbox before running. Should be called
* while the queue is stopped. It is not a good idea to start the queue if this method fails.
*/
public void bootstrap()
{
giant.lock();
try {
Preconditions.checkState(!active, "queue must be stopped");
log.info("Bootstrapping queue (and associated lockbox)");
queue.clear();
taskLockbox.clear();
// Add running tasks to the queue
final List<Task> runningTasks = taskStorage.getRunningTasks();
for(final Task task : runningTasks) {
queue.add(task);
}
// Get all locks, along with which tasks they belong to
final Multimap<TaskLock, Task> tasksByLock = ArrayListMultimap.create();
for(final Task runningTask : runningTasks) {
for(final TaskLock taskLock : taskStorage.getLocks(runningTask.getId())) {
tasksByLock.put(taskLock, runningTask);
}
}
// Sort locks by version
- final Ordering<TaskLock> byVersionOrdering = new Ordering<TaskLock>()
+ final Ordering<Map.Entry<TaskLock, Task>> byVersionOrdering = new Ordering<Map.Entry<TaskLock, Task>>()
{
@Override
- public int compare(TaskLock left, TaskLock right)
+ public int compare(Map.Entry<TaskLock, Task> left, Map.Entry<TaskLock, Task> right)
{
- return left.getVersion().compareTo(right.getVersion());
+ return left.getKey().getVersion().compareTo(right.getKey().getVersion());
}
};
// Acquire as many locks as possible, in version order
- for(final Map.Entry<TaskLock, Task> taskAndLock : tasksByLock.entries()) {
+ for(final Map.Entry<TaskLock, Task> taskAndLock : byVersionOrdering.sortedCopy(tasksByLock.entries())) {
final Task task = taskAndLock.getValue();
final TaskLock savedTaskLock = taskAndLock.getKey();
final Optional<TaskLock> acquiredTaskLock = taskLockbox.tryLock(
task,
savedTaskLock.getInterval(),
Optional.of(savedTaskLock.getVersion())
);
if(acquiredTaskLock.isPresent() && savedTaskLock.getVersion().equals(acquiredTaskLock.get().getVersion())) {
log.info(
"Reacquired lock on interval[%s] version[%s] for task: %s",
savedTaskLock.getInterval(),
savedTaskLock.getVersion(),
task.getId()
);
} else if(acquiredTaskLock.isPresent()) {
log.info(
"Could not reacquire lock on interval[%s] version[%s] (got version[%s] instead) for task: %s",
savedTaskLock.getInterval(),
savedTaskLock.getVersion(),
acquiredTaskLock.get().getVersion(),
task.getId()
);
} else {
log.info(
"Could not reacquire lock on interval[%s] version[%s] for task: %s",
savedTaskLock.getInterval(),
savedTaskLock.getVersion(),
task.getId()
);
}
}
log.info("Bootstrapped %,d tasks. Ready to go!", runningTasks.size());
} finally {
giant.unlock();
}
}
/**
* Starts this task queue. Allows {@link #add(Task)} to accept new tasks. This should not be called on
* an already-started queue.
*/
@LifecycleStart
public void start()
{
giant.lock();
try {
Preconditions.checkState(!active, "queue must be stopped");
active = true;
workMayBeAvailable.signalAll();
}
finally {
giant.unlock();
}
}
/**
* Shuts down the queue, for now. This may safely be called on an already-stopped queue. The queue may be restarted
* if desired.
*/
@LifecycleStop
public void stop()
{
giant.lock();
try {
log.info("Naptime! Shutting down until we are started again.");
queue.clear();
taskLockbox.clear();
active = false;
}
finally {
giant.unlock();
}
}
/**
* Adds some work to the queue and the underlying task storage facility with a generic "running" status.
*
* @param task task to add
*
* @return true
*/
public boolean add(final Task task)
{
giant.lock();
try {
Preconditions.checkState(active, "Queue is not active!");
// If this throws with any sort of exception, including TaskExistsException, we don't want to
// insert the task into our queue.
try {
taskStorage.insert(task, TaskStatus.running(task.getId()));
} catch(TaskExistsException e) {
log.warn("Attempt to add task twice: %s", task.getId());
throw Throwables.propagate(e);
}
queue.add(task);
workMayBeAvailable.signalAll();
// Attempt to add this task to a running task group. Silently continue if this is not possible.
// The main reason this is here is so when subtasks are added, they end up in the same task group
// as their parent whenever possible.
if(task.getImplicitLockInterval().isPresent()) {
taskLockbox.tryLock(task, task.getImplicitLockInterval().get());
}
return true;
}
finally {
giant.unlock();
}
}
/**
* Locks and returns next doable work from the queue. Blocks if there is no doable work.
*
* @return runnable task
*/
public Task take() throws InterruptedException
{
giant.lock();
try {
Task task;
log.info("Waiting for work...");
while ((task = poll()) == null) {
// awaitNanos because work may become available without this condition signalling,
// due to other folks messing with the taskLockbox
workMayBeAvailable.awaitNanos(1000000000L /* 1 second */);
}
return task;
}
finally {
giant.unlock();
}
}
/**
* Locks and removes next doable work from the queue. Returns null if there is no doable work.
*
* @return runnable task or null
*/
public Task poll()
{
giant.lock();
try {
for (final Task task : queue) {
if(task.getImplicitLockInterval().isPresent()) {
// If this task has a fixed interval, attempt to lock it right now.
final Optional<TaskLock> maybeLock = taskLockbox.tryLock(task, task.getImplicitLockInterval().get());
if(maybeLock.isPresent()) {
log.info("Task claimed with fixed interval lock: %s", task.getId());
queue.remove(task);
return task;
}
} else {
// No fixed interval. Let's just run this and see what happens.
log.info("Task claimed with no fixed interval lock: %s", task.getId());
queue.remove(task);
return task;
}
}
return null;
}
finally {
giant.unlock();
}
}
/**
* Notify this queue that some task has an updated status. If this update is valid, the status will be persisted in
* the task storage facility. If the status is a completed status, the task will be unlocked and no further
* updates will be accepted.
*
* @param task task to update
* @param taskStatus new task status
*
* @throws NullPointerException if task or status is null
* @throws IllegalArgumentException if the task ID does not match the status ID
* @throws IllegalStateException if this queue is currently shut down
*/
public void notify(final Task task, final TaskStatus taskStatus)
{
giant.lock();
try {
Preconditions.checkNotNull(task, "task");
Preconditions.checkNotNull(taskStatus, "status");
Preconditions.checkState(active, "Queue is not active!");
Preconditions.checkArgument(
task.getId().equals(taskStatus.getId()),
"Mismatching task ids[%s/%s]",
task.getId(),
taskStatus.getId()
);
// Save status to DB
boolean didPersistStatus = false;
try {
final Optional<TaskStatus> previousStatus = taskStorage.getStatus(task.getId());
if (!previousStatus.isPresent() || !previousStatus.get().isRunnable()) {
log.makeAlert("Ignoring notification for dead task").addData("task", task.getId()).emit();
return;
} else {
taskStorage.setStatus(taskStatus);
didPersistStatus = true;
}
} catch(Exception e) {
log.makeAlert(e, "Failed to persist status for task")
.addData("task", task.getId())
.addData("statusCode", taskStatus.getStatusCode())
.emit();
}
if(taskStatus.isComplete()) {
if(didPersistStatus) {
log.info("Task done: %s", task);
taskLockbox.unlock(task);
workMayBeAvailable.signalAll();
} else {
// TODO: This could be a task-status-submission retry queue instead of retrying the entire task,
// TODO: which is heavy and probably not necessary.
log.warn("Status could not be persisted! Reinserting task: %s", task.getId());
queue.add(task);
}
}
}
finally {
giant.unlock();
}
}
}
| false | true | public void bootstrap()
{
giant.lock();
try {
Preconditions.checkState(!active, "queue must be stopped");
log.info("Bootstrapping queue (and associated lockbox)");
queue.clear();
taskLockbox.clear();
// Add running tasks to the queue
final List<Task> runningTasks = taskStorage.getRunningTasks();
for(final Task task : runningTasks) {
queue.add(task);
}
// Get all locks, along with which tasks they belong to
final Multimap<TaskLock, Task> tasksByLock = ArrayListMultimap.create();
for(final Task runningTask : runningTasks) {
for(final TaskLock taskLock : taskStorage.getLocks(runningTask.getId())) {
tasksByLock.put(taskLock, runningTask);
}
}
// Sort locks by version
final Ordering<TaskLock> byVersionOrdering = new Ordering<TaskLock>()
{
@Override
public int compare(TaskLock left, TaskLock right)
{
return left.getVersion().compareTo(right.getVersion());
}
};
// Acquire as many locks as possible, in version order
for(final Map.Entry<TaskLock, Task> taskAndLock : tasksByLock.entries()) {
final Task task = taskAndLock.getValue();
final TaskLock savedTaskLock = taskAndLock.getKey();
final Optional<TaskLock> acquiredTaskLock = taskLockbox.tryLock(
task,
savedTaskLock.getInterval(),
Optional.of(savedTaskLock.getVersion())
);
if(acquiredTaskLock.isPresent() && savedTaskLock.getVersion().equals(acquiredTaskLock.get().getVersion())) {
log.info(
"Reacquired lock on interval[%s] version[%s] for task: %s",
savedTaskLock.getInterval(),
savedTaskLock.getVersion(),
task.getId()
);
} else if(acquiredTaskLock.isPresent()) {
log.info(
"Could not reacquire lock on interval[%s] version[%s] (got version[%s] instead) for task: %s",
savedTaskLock.getInterval(),
savedTaskLock.getVersion(),
acquiredTaskLock.get().getVersion(),
task.getId()
);
} else {
log.info(
"Could not reacquire lock on interval[%s] version[%s] for task: %s",
savedTaskLock.getInterval(),
savedTaskLock.getVersion(),
task.getId()
);
}
}
log.info("Bootstrapped %,d tasks. Ready to go!", runningTasks.size());
} finally {
giant.unlock();
}
}
| public void bootstrap()
{
giant.lock();
try {
Preconditions.checkState(!active, "queue must be stopped");
log.info("Bootstrapping queue (and associated lockbox)");
queue.clear();
taskLockbox.clear();
// Add running tasks to the queue
final List<Task> runningTasks = taskStorage.getRunningTasks();
for(final Task task : runningTasks) {
queue.add(task);
}
// Get all locks, along with which tasks they belong to
final Multimap<TaskLock, Task> tasksByLock = ArrayListMultimap.create();
for(final Task runningTask : runningTasks) {
for(final TaskLock taskLock : taskStorage.getLocks(runningTask.getId())) {
tasksByLock.put(taskLock, runningTask);
}
}
// Sort locks by version
final Ordering<Map.Entry<TaskLock, Task>> byVersionOrdering = new Ordering<Map.Entry<TaskLock, Task>>()
{
@Override
public int compare(Map.Entry<TaskLock, Task> left, Map.Entry<TaskLock, Task> right)
{
return left.getKey().getVersion().compareTo(right.getKey().getVersion());
}
};
// Acquire as many locks as possible, in version order
for(final Map.Entry<TaskLock, Task> taskAndLock : byVersionOrdering.sortedCopy(tasksByLock.entries())) {
final Task task = taskAndLock.getValue();
final TaskLock savedTaskLock = taskAndLock.getKey();
final Optional<TaskLock> acquiredTaskLock = taskLockbox.tryLock(
task,
savedTaskLock.getInterval(),
Optional.of(savedTaskLock.getVersion())
);
if(acquiredTaskLock.isPresent() && savedTaskLock.getVersion().equals(acquiredTaskLock.get().getVersion())) {
log.info(
"Reacquired lock on interval[%s] version[%s] for task: %s",
savedTaskLock.getInterval(),
savedTaskLock.getVersion(),
task.getId()
);
} else if(acquiredTaskLock.isPresent()) {
log.info(
"Could not reacquire lock on interval[%s] version[%s] (got version[%s] instead) for task: %s",
savedTaskLock.getInterval(),
savedTaskLock.getVersion(),
acquiredTaskLock.get().getVersion(),
task.getId()
);
} else {
log.info(
"Could not reacquire lock on interval[%s] version[%s] for task: %s",
savedTaskLock.getInterval(),
savedTaskLock.getVersion(),
task.getId()
);
}
}
log.info("Bootstrapped %,d tasks. Ready to go!", runningTasks.size());
} finally {
giant.unlock();
}
}
|
diff --git a/activiti-webapp-explorer2/src/main/java/org/activiti/explorer/ui/form/BooleanFormPropertyRenderer.java b/activiti-webapp-explorer2/src/main/java/org/activiti/explorer/ui/form/BooleanFormPropertyRenderer.java
index ebbf88d18..217ede589 100644
--- a/activiti-webapp-explorer2/src/main/java/org/activiti/explorer/ui/form/BooleanFormPropertyRenderer.java
+++ b/activiti-webapp-explorer2/src/main/java/org/activiti/explorer/ui/form/BooleanFormPropertyRenderer.java
@@ -1,45 +1,46 @@
/* 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.activiti.explorer.ui.form;
import org.activiti.engine.form.FormProperty;
import org.activiti.engine.impl.form.BooleanFormType;
import com.vaadin.ui.CheckBox;
import com.vaadin.ui.Field;
/**
* @author Frederik Heremans
*/
public class BooleanFormPropertyRenderer extends AbstractFormPropertyRenderer {
public BooleanFormPropertyRenderer() {
super(BooleanFormType.class);
}
@Override
public Field getPropertyField(FormProperty formProperty) {
CheckBox checkBox = new CheckBox(getPropertyLabel(formProperty));
checkBox.setRequired(formProperty.isRequired());
checkBox.setEnabled(formProperty.isWritable());
if (formProperty.getValue() != null) {
- checkBox.setValue(formProperty.getValue());
+ Boolean value = new Boolean(Boolean.parseBoolean(formProperty.getValue()));
+ checkBox.setValue(value);
}
return checkBox;
}
}
| true | true | public Field getPropertyField(FormProperty formProperty) {
CheckBox checkBox = new CheckBox(getPropertyLabel(formProperty));
checkBox.setRequired(formProperty.isRequired());
checkBox.setEnabled(formProperty.isWritable());
if (formProperty.getValue() != null) {
checkBox.setValue(formProperty.getValue());
}
return checkBox;
}
| public Field getPropertyField(FormProperty formProperty) {
CheckBox checkBox = new CheckBox(getPropertyLabel(formProperty));
checkBox.setRequired(formProperty.isRequired());
checkBox.setEnabled(formProperty.isWritable());
if (formProperty.getValue() != null) {
Boolean value = new Boolean(Boolean.parseBoolean(formProperty.getValue()));
checkBox.setValue(value);
}
return checkBox;
}
|
diff --git a/org/python/core/CachedJarsPackageManager.java b/org/python/core/CachedJarsPackageManager.java
index 53509ab3..99cf7d4f 100644
--- a/org/python/core/CachedJarsPackageManager.java
+++ b/org/python/core/CachedJarsPackageManager.java
@@ -1,518 +1,518 @@
// Copyright � Corporation for National Research Initiatives
// Copyright 2000 Samuele Pedroni
package org.python.core;
import java.util.Hashtable;
import java.util.Vector;
import java.util.Enumeration;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipEntry;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
//import java.net.URLDecoder;
import java.lang.reflect.Modifier;
/** Abstract package manager that gathers info about statically known classes
* from a set of jars. This info can be eventually cached.
* Off-the-shelf this class offers a local file-system based cache impl.
*/
public abstract class CachedJarsPackageManager extends PackageManager {
/** Message log method - hook. This default impl does nothing.
* @param msg message text
*/
protected void message(String msg) {
}
/** Warning log method - hook. This default impl does nothing.
* @param warn warning text
*/
protected void warning(String warn) {
}
/** Comment log method - hook. This default impl does nothing.
* @param msg message text
*/
protected void comment(String msg) {
}
/** Debug log method - hook. This default impl does nothing.
* @param msg message text
*/
protected void debug(String msg) {
}
/** Filter class/pkg by name helper method - hook.
* The default impl. is used by {@link #addJarToPackages} in order to filter out classes
* whose name contains '$' (e.g. inner classes,...).
* Should be used or overriden by derived classes too. Also to be used in {@link #doDir}.
* @param name class/pkg name
* @param pkg if true, name refers to a pkg
* @return true if name must be filtered out
*/
protected boolean filterByName(String name,boolean pkg) {
return name.indexOf('$') != -1;
}
/** Filter class by access perms helper method - hook.
* The default impl. is used by {@link #addJarToPackages} in order to filter out non-public classes.
* Should be used or overriden by derived classes too. Also to be used in {@link #doDir}.
* Access perms can be read with {@link #checkAccess}.
* @param name class name
* @param acc class access permissions as int
* @return true if name must be filtered out
*/
protected boolean filterByAccess(String name,int acc) {
return (acc & Modifier.PUBLIC) != Modifier.PUBLIC;
}
private boolean indexModified;
private Hashtable jarfiles;
private static String vectorToString(Vector vec) {
int n = vec.size();
StringBuffer ret = new StringBuffer();
for(int i=0; i<n; i++) {
ret.append((String)vec.elementAt(i));
if (i<n-1) ret.append(",");
}
return ret.toString();
}
// Add a single class from zipFile to zipPackages
// Only add valid, public classes
private void addZipEntry(Hashtable zipPackages, ZipEntry entry,ZipInputStream zip) throws IOException
{
String name = entry.getName();
//System.err.println("entry: "+name);
if (!name.endsWith(".class")) return;
char sep = '/';
int breakPoint = name.lastIndexOf(sep);
if (breakPoint == -1) {
breakPoint = name.lastIndexOf('\\');
sep = '\\';
}
String packageName;
if (breakPoint == -1) {
packageName = "";
} else {
packageName = name.substring(0,breakPoint).replace(sep, '.');
}
String className = name.substring(breakPoint+1, name.length()-6);
if (filterByName(className,false)) return;
// An extra careful test, maybe should be ignored????
int access = checkAccess(zip);
if ((access == -1) || filterByAccess(name,access)) return;
Vector vec = (Vector)zipPackages.get(packageName);
if (vec == null) {
vec = new Vector();
zipPackages.put(packageName, vec);
}
vec.addElement(className);
}
// Extract all of the packages in a single jarfile
private Hashtable getZipPackages(InputStream jarin) throws IOException {
Hashtable zipPackages = new Hashtable();
ZipInputStream zip=new ZipInputStream(jarin);
ZipEntry entry;
while ((entry = zip.getNextEntry()) != null) {
addZipEntry(zipPackages, entry, zip);
zip.closeEntry();
}
// Turn each vector into a comma-separated String
for (Enumeration e = zipPackages.keys() ; e.hasMoreElements() ;) {
Object key = e.nextElement();
Vector vec = (Vector)zipPackages.get(key);
zipPackages.put(key, vectorToString(vec));
}
return zipPackages;
}
/** Gathers classes info from jar specified by jarurl URL.
* Eventually just using previously cached info.
* Eventually updated info is not cached.
* Persistent cache storage access goes through {@link #inOpenCacheFile}, {@link #outCreateCacheFile}.
*/
public void addJarToPackages(java.net.URL jarurl) {
addJarToPackages(jarurl,null,false);
}
/** Gathers classes info from jar specified by jarurl URL.
* Eventually just using previously cached info.
* Eventually updated info is (re-)cached if param cache is true.
* Persistent cache storage access goes through {@link #inOpenCacheFile}, {@link #outCreateCacheFile}.
*/
public void addJarToPackages(URL jarurl,boolean cache) {
addJarToPackages(jarurl,null,cache);
}
/** Gathers classes info from jar specified by File jarfile.
* Eventually just using previously cached info.
* Eventually updated info is not cached.
* Persistent cache storage access goes through {@link #inOpenCacheFile}, {@link #outCreateCacheFile}.
*/
public void addJarToPackages(File jarfile) {
addJarToPackages(null,jarfile,false);
}
/** Gathers classes info from jar specified by File jarfile.
* Eventually just using previously cached info.
* Eventually updated info is (re-)cached if param cache is true.
* Persistent cache storage access goes through {@link #inOpenCacheFile}, {@link #outCreateCacheFile}.
*/
public void addJarToPackages(File jarfile,boolean cache) {
addJarToPackages(null,jarfile,cache);
}
private void addJarToPackages(URL jarurl,File jarfile,boolean cache) {
try {
boolean caching = jarfiles!=null;
URLConnection jarconn = null;
boolean localfile = true;
if (jarfile == null) {
jarconn = jarurl.openConnection();
// This is necessary because 'file:' url-connections
// return always 0 through getLastModified (bug?).
// And in order to handle localfiles (from urls too) uniformly.
if(jarconn.getURL().getProtocol().equals("file")) {
// ??pending: need to use java2 URLDecoder.decode?
// but under 1.1 this is absent and should be simulated.
jarfile = new File(jarurl.getFile().replace('/',File.separatorChar));
}
else localfile = false;
}
if (localfile && !jarfile.exists()) return;
Hashtable zipPackages = null;
long mtime = 0;
String jarcanon = null;
JarXEntry entry = null;
boolean brandNew = false;
if(caching) {
if(localfile) {
mtime = jarfile.lastModified();
jarcanon = jarfile.getCanonicalPath();
} else {
mtime = jarconn.getLastModified();
jarcanon = jarurl.toString();
}
entry = (JarXEntry)jarfiles.get(jarcanon);
if (entry == null) {
message("processing new jar, '"+
jarcanon+"'");
String jarname;
if(localfile) {
jarname = jarfile.getName();
} else {
jarname = jarurl.getFile();
int slash = jarname.lastIndexOf('/');
if (slash != -1)
jarname=jarname.substring(slash+1);
}
jarname=jarname.substring(0,jarname.length()-4);
entry = new JarXEntry(jarname);
jarfiles.put(jarcanon, entry);
brandNew = true;
}
if (mtime != 0 && entry.mtime == mtime) {
zipPackages = readCacheFile(entry, jarcanon);
}
}
if (zipPackages == null) {
caching = caching && cache;
if(caching) {
indexModified = true;
if (entry.mtime != 0) {
message("processing modified jar, '"+
jarcanon+"'");
}
entry.mtime = mtime;
}
InputStream jarin;
if (jarconn == null) jarin = new BufferedInputStream(new FileInputStream(jarfile));
else jarin = jarconn.getInputStream();
zipPackages = getZipPackages(jarin);
if(caching) writeCacheFile(entry, jarcanon, zipPackages, brandNew); // Write the cache file
}
addPackages(zipPackages, jarcanon);
} catch (IOException ioe) {
// silently skip any bad directories
warning("skipping bad jar, '" +
- jarurl.toString() + "'");
+ (jarfile!=null?jarfile.toString():jarurl.toString()) + "'"); // ?? solve bug
}
}
private void addPackages(Hashtable zipPackages, String jarfile) {
for (Enumeration e = zipPackages.keys() ; e.hasMoreElements() ;) {
String pkg = (String)e.nextElement();
String classes = (String)zipPackages.get(pkg);
makeJavaPackage(pkg, classes, jarfile);
}
}
// Read in cache file storing package info for a single .jar
// Return null and delete this cachefile if it is invalid
private Hashtable readCacheFile(JarXEntry entry,String jarcanon)
{
String cachefile = entry.cachefile;
long mtime = entry.mtime;
debug("reading cache, '"+jarcanon+"'");
try {
DataInputStream istream = inOpenCacheFile(cachefile);
String old_jarcanon = istream.readUTF();
long old_mtime = istream.readLong();
if ((!old_jarcanon.equals(jarcanon)) ||
(old_mtime != mtime))
{
comment("invalid cache file: "+
cachefile+", "+jarcanon+":"+
old_jarcanon+", "+mtime+":"+old_mtime);
deleteCacheFile(cachefile);
return null;
}
Hashtable packs = new Hashtable();
try {
while (true) {
String packageName = istream.readUTF();
String classes = istream.readUTF();
packs.put(packageName, classes);
}
} catch (EOFException eof) {
;
}
istream.close();
return packs;
} catch (IOException ioe) {
// if (cachefile.exists()) cachefile.delete();
return null;
}
}
// Write a cache file storing package info for a single .jar
private void writeCacheFile(JarXEntry entry,String jarcanon,
Hashtable zipPackages,boolean brandNew)
{
try {
DataOutputStream ostream = outCreateCacheFile(entry, brandNew);
ostream.writeUTF(jarcanon);
ostream.writeLong(entry.mtime);
comment("rewriting cachefile for '"+jarcanon+"'");
for (Enumeration e = zipPackages.keys() ; e.hasMoreElements() ;) {
String packageName = (String)e.nextElement();
String classes = (String)zipPackages.get(packageName);
ostream.writeUTF(packageName);
ostream.writeUTF(classes);
}
ostream.close();
} catch (IOException ioe) {
warning("can't write cache file for '"+jarcanon+"'");
}
}
/** Initializes cache. Eventually reads back cache index.
* Index persistent storage is accessed through {@link #inOpenIndex}.
*/
protected void initCache() {
indexModified = false;
jarfiles = new Hashtable();
try {
DataInputStream istream = inOpenIndex();
if (istream == null) return;
try {
while (true) {
String jarcanon = istream.readUTF();
String cachefile = istream.readUTF();
long mtime = istream.readLong();
jarfiles.put(jarcanon, new JarXEntry(cachefile,mtime));
}
} catch (EOFException eof) {
;
}
istream.close();
} catch (IOException ioe) {
warning("invalid index file");
}
}
/** Write back cache index.
* Index persistent storage is accessed through {@link #outOpenIndex}.
*/
public void saveCache() {
if(jarfiles == null || !indexModified ) return;
indexModified = false;
comment("writing modified index file");
try {
DataOutputStream ostream = outOpenIndex();
for (Enumeration e = jarfiles.keys(); e.hasMoreElements();) {
String jarcanon = (String)e.nextElement();
JarXEntry entry = (JarXEntry)jarfiles.get(jarcanon);
ostream.writeUTF(jarcanon);
ostream.writeUTF(entry.cachefile);
ostream.writeLong(entry.mtime);
}
ostream.close();
} catch (IOException ioe) {
warning("can't write index file");
}
}
// hooks for changing cache storage
/** To pass a cachefile id by ref. And for internal use.
* @see #outCreateCacheFile
*/
public static class JarXEntry extends Object {
/** cachefile id */
public String cachefile;
public long mtime;
public JarXEntry(String cachefile) {
this.cachefile = cachefile;
}
public JarXEntry(String cachefile,long mtime) {
this.cachefile = cachefile;
this.mtime = mtime;
}
}
/** Open cache index for reading from persistent storage - hook.
* Must Return null if this is absent.
* This default impl is part of the off-the-shelf local file-system cache impl.
* Can be overriden.
*/
protected DataInputStream inOpenIndex() throws IOException {
File indexFile = new File(cachedir, "packages.idx");
if (!indexFile.exists()) return null;
DataInputStream istream = new DataInputStream(
new BufferedInputStream(new FileInputStream(indexFile)));
return istream;
}
/** Open cache index for writing back to persistent storage - hook.
* This default impl is part of the off-the-shelf local file-system cache impl.
* Can be overriden.
*/
protected DataOutputStream outOpenIndex() throws IOException {
File indexFile = new File(cachedir, "packages.idx");
return new DataOutputStream(
new BufferedOutputStream(new FileOutputStream(indexFile)));
}
/** Open cache file for reading from persistent storage - hook.
* This default impl is part of the off-the-shelf local file-system cache impl.
* Can be overriden.
*/
protected DataInputStream inOpenCacheFile(String cachefile) throws IOException {
return new DataInputStream(new BufferedInputStream(new FileInputStream(cachefile)));
}
/** Delete (invalidated) cache file from persistent storage - hook.
* This default impl is part of the off-the-shelf local file-system cache impl.
* Can be overriden.
*/
protected void deleteCacheFile(String cachefile) {
new File(cachefile).delete();
}
/** Create/open cache file for rewriting back to persistent storage - hook.
* If create is false, cache file is supposed to exist and must be opened
* for rewriting, entry.cachefile is a valid cachefile id.
* If create is true, cache file must be created. entry.cachefile is a flat
* jarname to be used to produce a valid cachefile id (to be put back in entry.cachefile
* on exit).
* This default impl is part of the off-the-shelf local file-system cache impl.
* Can be overriden.
*/
protected DataOutputStream outCreateCacheFile(JarXEntry entry, boolean create) throws IOException {
File cachefile = null;
if(create) {
int index = 1;
String suffix = "";
String jarname = entry.cachefile;
while (true) {
cachefile = new File(cachedir, jarname+suffix+".pkc");
//System.err.println("try cachefile: "+cachefile);
if (!cachefile.exists()) break;
suffix = "$"+index;
index += 1;
}
entry.cachefile = cachefile.getCanonicalPath();
} else cachefile = new File(entry.cachefile);
return new DataOutputStream(new BufferedOutputStream(new FileOutputStream(cachefile)));
}
// for default cache (local fs based) impl
private File cachedir;
/** Initialize off-the-shelf (default) local file-system cache impl.
* Must be called before {@link #initCache}.
* cachedir is the cache repository directory, this is eventually created.
* Returns true if dir works.
*/
protected boolean useCacheDir(File cachedir) {
if(cachedir == null) return false;
if (!cachedir.isDirectory() && cachedir.mkdirs() == false) {
warning("can't create package cache dir, '"+cachedir+"'");
return false;
}
this.cachedir = cachedir;
return true;
}
}
| true | true | private void addJarToPackages(URL jarurl,File jarfile,boolean cache) {
try {
boolean caching = jarfiles!=null;
URLConnection jarconn = null;
boolean localfile = true;
if (jarfile == null) {
jarconn = jarurl.openConnection();
// This is necessary because 'file:' url-connections
// return always 0 through getLastModified (bug?).
// And in order to handle localfiles (from urls too) uniformly.
if(jarconn.getURL().getProtocol().equals("file")) {
// ??pending: need to use java2 URLDecoder.decode?
// but under 1.1 this is absent and should be simulated.
jarfile = new File(jarurl.getFile().replace('/',File.separatorChar));
}
else localfile = false;
}
if (localfile && !jarfile.exists()) return;
Hashtable zipPackages = null;
long mtime = 0;
String jarcanon = null;
JarXEntry entry = null;
boolean brandNew = false;
if(caching) {
if(localfile) {
mtime = jarfile.lastModified();
jarcanon = jarfile.getCanonicalPath();
} else {
mtime = jarconn.getLastModified();
jarcanon = jarurl.toString();
}
entry = (JarXEntry)jarfiles.get(jarcanon);
if (entry == null) {
message("processing new jar, '"+
jarcanon+"'");
String jarname;
if(localfile) {
jarname = jarfile.getName();
} else {
jarname = jarurl.getFile();
int slash = jarname.lastIndexOf('/');
if (slash != -1)
jarname=jarname.substring(slash+1);
}
jarname=jarname.substring(0,jarname.length()-4);
entry = new JarXEntry(jarname);
jarfiles.put(jarcanon, entry);
brandNew = true;
}
if (mtime != 0 && entry.mtime == mtime) {
zipPackages = readCacheFile(entry, jarcanon);
}
}
if (zipPackages == null) {
caching = caching && cache;
if(caching) {
indexModified = true;
if (entry.mtime != 0) {
message("processing modified jar, '"+
jarcanon+"'");
}
entry.mtime = mtime;
}
InputStream jarin;
if (jarconn == null) jarin = new BufferedInputStream(new FileInputStream(jarfile));
else jarin = jarconn.getInputStream();
zipPackages = getZipPackages(jarin);
if(caching) writeCacheFile(entry, jarcanon, zipPackages, brandNew); // Write the cache file
}
addPackages(zipPackages, jarcanon);
} catch (IOException ioe) {
// silently skip any bad directories
warning("skipping bad jar, '" +
jarurl.toString() + "'");
}
}
| private void addJarToPackages(URL jarurl,File jarfile,boolean cache) {
try {
boolean caching = jarfiles!=null;
URLConnection jarconn = null;
boolean localfile = true;
if (jarfile == null) {
jarconn = jarurl.openConnection();
// This is necessary because 'file:' url-connections
// return always 0 through getLastModified (bug?).
// And in order to handle localfiles (from urls too) uniformly.
if(jarconn.getURL().getProtocol().equals("file")) {
// ??pending: need to use java2 URLDecoder.decode?
// but under 1.1 this is absent and should be simulated.
jarfile = new File(jarurl.getFile().replace('/',File.separatorChar));
}
else localfile = false;
}
if (localfile && !jarfile.exists()) return;
Hashtable zipPackages = null;
long mtime = 0;
String jarcanon = null;
JarXEntry entry = null;
boolean brandNew = false;
if(caching) {
if(localfile) {
mtime = jarfile.lastModified();
jarcanon = jarfile.getCanonicalPath();
} else {
mtime = jarconn.getLastModified();
jarcanon = jarurl.toString();
}
entry = (JarXEntry)jarfiles.get(jarcanon);
if (entry == null) {
message("processing new jar, '"+
jarcanon+"'");
String jarname;
if(localfile) {
jarname = jarfile.getName();
} else {
jarname = jarurl.getFile();
int slash = jarname.lastIndexOf('/');
if (slash != -1)
jarname=jarname.substring(slash+1);
}
jarname=jarname.substring(0,jarname.length()-4);
entry = new JarXEntry(jarname);
jarfiles.put(jarcanon, entry);
brandNew = true;
}
if (mtime != 0 && entry.mtime == mtime) {
zipPackages = readCacheFile(entry, jarcanon);
}
}
if (zipPackages == null) {
caching = caching && cache;
if(caching) {
indexModified = true;
if (entry.mtime != 0) {
message("processing modified jar, '"+
jarcanon+"'");
}
entry.mtime = mtime;
}
InputStream jarin;
if (jarconn == null) jarin = new BufferedInputStream(new FileInputStream(jarfile));
else jarin = jarconn.getInputStream();
zipPackages = getZipPackages(jarin);
if(caching) writeCacheFile(entry, jarcanon, zipPackages, brandNew); // Write the cache file
}
addPackages(zipPackages, jarcanon);
} catch (IOException ioe) {
// silently skip any bad directories
warning("skipping bad jar, '" +
(jarfile!=null?jarfile.toString():jarurl.toString()) + "'"); // ?? solve bug
}
}
|
diff --git a/bwcaldav/src/org/bedework/caldav/bwserver/BwSysIntfImpl.java b/bwcaldav/src/org/bedework/caldav/bwserver/BwSysIntfImpl.java
index af5b95b..da5aea3 100644
--- a/bwcaldav/src/org/bedework/caldav/bwserver/BwSysIntfImpl.java
+++ b/bwcaldav/src/org/bedework/caldav/bwserver/BwSysIntfImpl.java
@@ -1,918 +1,919 @@
/* **********************************************************************
Copyright 2006 Rensselaer Polytechnic Institute. All worldwide rights reserved.
Redistribution and use of this distribution in source and binary forms,
with or without modification, are permitted provided that:
The above copyright notice and this permission notice appear in all
copies and supporting documentation;
The name, identifiers, and trademarks of Rensselaer Polytechnic
Institute are not used in advertising or publicity without the
express prior written permission of Rensselaer Polytechnic Institute;
DISCLAIMER: The software is distributed" AS IS" without any express or
implied warranty, including but not limited to, any implied warranties
of merchantability or fitness for a particular purpose or any warrant)'
of non-infringement of any current or pending patent rights. The authors
of the software make no representations about the suitability of this
software for any particular purpose. The entire risk as to the quality
and performance of the software is with the user. Should the software
prove defective, the user assumes the cost of all necessary servicing,
repair or correction. In particular, neither Rensselaer Polytechnic
Institute, nor the authors of the software are liable for any indirect,
special, consequential, or incidental damages related to the software,
to the maximum extent the law permits.
*/
package org.bedework.caldav.bwserver;
import org.bedework.caldav.server.SysIntf;
import org.bedework.calfacade.BwCalendar;
import org.bedework.calfacade.BwDateTime;
import org.bedework.calfacade.BwEvent;
import org.bedework.calfacade.BwEventProxy;
import org.bedework.calfacade.BwFreeBusy;
import org.bedework.calfacade.BwSystem;
import org.bedework.calfacade.BwUser;
import org.bedework.calfacade.RecurringRetrievalMode;
import org.bedework.calfacade.ScheduleResult;
import org.bedework.calfacade.base.BwShareableDbentity;
import org.bedework.calfacade.env.CalEnvFactory;
import org.bedework.calfacade.env.CalEnvI;
import org.bedework.calfacade.exc.CalFacadeAccessException;
import org.bedework.calfacade.exc.CalFacadeException;
import org.bedework.calfacade.exc.CalFacadeStaleStateException;
import org.bedework.calfacade.filter.BwEntityTypeFilter;
import org.bedework.calfacade.filter.BwFilter;
import org.bedework.calfacade.filter.BwOrFilter;
import org.bedework.calfacade.svc.BwSubscription;
import org.bedework.calfacade.svc.EventInfo;
import org.bedework.calfacade.timezones.CalTimezones;
import org.bedework.calfacade.util.ChangeTable;
import org.bedework.calsvci.CalSvcFactoryDefault;
import org.bedework.calsvci.CalSvcI;
import org.bedework.calsvci.CalSvcIPars;
import org.bedework.davdefs.CaldavTags;
import org.bedework.icalendar.IcalMalformedException;
import org.bedework.icalendar.IcalTranslator;
import org.bedework.icalendar.Icalendar;
import edu.rpi.cct.webdav.servlet.common.WebdavUtils;
import edu.rpi.cct.webdav.servlet.shared.PrincipalPropertySearch;
import edu.rpi.cct.webdav.servlet.shared.WebdavBadRequest;
import edu.rpi.cct.webdav.servlet.shared.WebdavException;
import edu.rpi.cct.webdav.servlet.shared.WebdavForbidden;
import edu.rpi.cct.webdav.servlet.shared.WebdavProperty;
import edu.rpi.cct.webdav.servlet.shared.WebdavUnauthorized;
import edu.rpi.cmt.access.Ace;
import edu.rpi.cmt.access.Acl.CurrentAccess;
import edu.rpi.sss.util.xml.XmlUtil;
import net.fortuna.ical4j.model.Calendar;
import net.fortuna.ical4j.model.TimeZone;
import org.apache.log4j.Logger;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Collection;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/** Bedework implementation of SysIntf.
*
* @author Mike Douglass douglm at rpi.edu
*/
public class BwSysIntfImpl implements SysIntf {
private boolean debug;
protected transient Logger log;
/* Prefix for our properties */
private String envPrefix;
private CalEnvI env;
private String account;
//private String principalCollectionSetUri;
private String userPrincipalCollectionSetUri;
private String groupPrincipalCollectionSetUri;
/* These two set after a call to getSvci()
*/
private IcalTranslator trans;
private CalSvcI svci;
private String urlPrefix;
public void init(HttpServletRequest req,
String envPrefix,
String account,
boolean debug) throws WebdavException {
try {
this.envPrefix = envPrefix;
this.account = account;
this.debug = debug;
StringBuffer sb = new StringBuffer();
sb.append("http://");
sb.append(req.getLocalName());
int port = req.getLocalPort();
if (port != 80) {
sb.append(":");
sb.append(port);
}
sb.append(req.getContextPath());
String hostPortContext;
hostPortContext = sb.toString();
//BwSystem sys = getSvci().getSyspars();
//String userRootPath = sys.getUserCalendarRoot();
//principalCollectionSetUri = "/" + userRootPath + "/";
userPrincipalCollectionSetUri = hostPortContext + getUserPrincipalRoot() +
"/";
groupPrincipalCollectionSetUri = hostPortContext + getGroupPrincipalRoot() +
"/";
urlPrefix = WebdavUtils.getUrlPrefix(req);
} catch (Throwable t) {
throw new WebdavException(t);
}
}
public String getUrlPrefix() {
return urlPrefix;
}
/* (non-Javadoc)
* @see org.bedework.caldav.server.SysIntf#getPrincipalRoot()
*/
public String getPrincipalRoot() throws WebdavException {
try {
return getSvci().getSyspars().getPrincipalRoot();
} catch (Throwable t) {
throw new WebdavException(t);
}
}
/* (non-Javadoc)
* @see org.bedework.caldav.server.SysIntf#getUserPrincipalRoot()
*/
public String getUserPrincipalRoot() throws WebdavException {
try {
return getSvci().getSyspars().getUserPrincipalRoot();
} catch (Throwable t) {
throw new WebdavException(t);
}
}
/* (non-Javadoc)
* @see org.bedework.caldav.server.SysIntf#getGroupPrincipalRoot()
*/
public String getGroupPrincipalRoot() throws WebdavException {
try {
return getSvci().getSyspars().getGroupPrincipalRoot();
} catch (Throwable t) {
throw new WebdavException(t);
}
}
/* (non-Javadoc)
* @see org.bedework.caldav.server.SysIntf#makeUserHref(java.lang.String)
*/
public String makeUserHref(String id) throws WebdavException {
StringBuffer sb = new StringBuffer(getUrlPrefix());
String root = getUserPrincipalRoot();
if (!root.startsWith("/")) {
sb.append("/");
}
sb.append(root);
sb.append("/");
sb.append(id);
return sb.toString();
}
/* (non-Javadoc)
* @see org.bedework.caldav.server.SysIntf#makeGroupHref(java.lang.String)
*/
public String makeGroupHref(String id) throws WebdavException {
StringBuffer sb = new StringBuffer(getUrlPrefix());
String root = getGroupPrincipalRoot();
if (!root.startsWith("/")) {
sb.append("/");
}
sb.append(root);
sb.append("/");
sb.append(id);
return sb.toString();
}
public boolean getDirectoryBrowsingDisallowed() throws WebdavException {
try {
return getSvci().getSyspars().getDirectoryBrowsingDisallowed();
} catch (Throwable t) {
throw new WebdavException(t);
}
}
/* (non-Javadoc)
* @see org.bedework.caldav.server.SysIntf#caladdrToUser(java.lang.String)
*/
public String caladdrToUser(String caladdr) throws WebdavException {
try {
return getSvci().caladdrToUser(caladdr);
} catch (CalFacadeException cfe) {
throw new WebdavException(cfe);
} catch (Throwable t) {
throw new WebdavException(t);
}
}
/* (non-Javadoc)
* @see org.bedework.caldav.server.SysIntf#userToCaladdr(java.lang.String)
*/
public String userToCaladdr(String account) throws WebdavException {
try {
return getSvci().userToCaladdr(account);
} catch (CalFacadeException cfe) {
throw new WebdavException(cfe);
} catch (Throwable t) {
throw new WebdavException(t);
}
}
public CalUserInfo getCalUserInfo(String caladdr) throws WebdavException {
try {
String account = caladdrToUser(caladdr);
BwSystem sys = getSvci().getSyspars();
String userHomePath = "/" + sys.getUserCalendarRoot() +
"/" + account + "/";
String defaultCalendarPath = userHomePath + sys.getUserDefaultCalendar();
String inboxPath = userHomePath + sys.getUserInbox();
String outboxPath = userHomePath + sys.getUserOutbox();
return new CalUserInfo(account,
userHomePath,
defaultCalendarPath,
inboxPath,
outboxPath);
} catch (CalFacadeException cfe) {
throw new WebdavException(cfe);
} catch (Throwable t) {
throw new WebdavException(t);
}
}
public Collection<String> getPrincipalCollectionSet(String resourceUri)
throws WebdavException {
try {
ArrayList<String> al = new ArrayList<String>();
al.add(userPrincipalCollectionSetUri);
al.add(groupPrincipalCollectionSetUri);
return al;
} catch (Throwable t) {
throw new WebdavException(t);
}
}
public Collection<CalUserInfo> getPrincipals(String resourceUri,
PrincipalPropertySearch pps)
throws WebdavException {
if (pps.applyToPrincipalCollectionSet) {
throw new WebdavException("unimplemented");
}
if (!resourceUri.endsWith("/")) {
resourceUri += "/";
}
ArrayList<CalUserInfo> principals = new ArrayList<CalUserInfo>();
if (!resourceUri.equals(userPrincipalCollectionSetUri)) {
return principals;
}
/* If we don't support any of the properties in the searches we don't match
*/
String caladdr = null;
for (PrincipalPropertySearch.PropertySearch ps: pps.propertySearches) {
for (WebdavProperty prop: ps.props) {
if (!CaldavTags.calendarUserAddressSet.equals(prop.getTag())) {
return principals;
}
}
String mval;
try {
mval = XmlUtil.getElementContent(ps.match);
} catch (Throwable t) {
throw new WebdavException("org.bedework.caldavintf.badvalue");
}
if (debug) {
debugMsg("Try to match " + mval);
}
if ((caladdr != null) && (!caladdr.equals(mval))) {
return principals;
}
caladdr = mval;
}
/* For the moment only support the above
*/
CalUserInfo cui = getCalUserInfo(caladdr);
// XXX This needs to do a search of a system user directory - probably ldap
principals.add(cui);
return principals;
}
public boolean validUser(String account) throws WebdavException {
// XXX do this
return true;
}
public boolean validGroup(String account) throws WebdavException {
// XXX do this
return true;
}
/* ====================================================================
* Scheduling
* ==================================================================== */
public ScheduleResult schedule(BwEvent event) throws WebdavException {
try {
event.setOwner(svci.findUser(account, false));
return getSvci().schedule(event);
} catch (CalFacadeAccessException cfae) {
throw new WebdavForbidden();
} catch (CalFacadeException cfe) {
if (CalFacadeException.duplicateGuid.equals(cfe.getMessage())) {
throw new WebdavBadRequest("Duplicate-guid");
}
throw new WebdavException(cfe);
} catch (Throwable t) {
throw new WebdavException(t);
}
}
public Collection<BwEventProxy> addEvent(BwCalendar cal,
BwEvent event,
Collection<BwEventProxy> overrides,
boolean rollbackOnError) throws WebdavException {
try {
return getSvci().addEvent(cal, event, overrides, rollbackOnError).failedOverrides;
} catch (CalFacadeAccessException cfae) {
throw new WebdavForbidden();
} catch (CalFacadeException cfe) {
if (CalFacadeException.duplicateGuid.equals(cfe.getMessage())) {
throw new WebdavBadRequest("Duplicate-guid");
}
throw new WebdavException(cfe);
} catch (Throwable t) {
throw new WebdavException(t);
}
}
public void updateEvent(BwEvent event,
Collection<BwEventProxy> overrides,
ChangeTable changes) throws WebdavException {
try {
getSvci().updateEvent(event, overrides, changes);
} catch (CalFacadeAccessException cfae) {
throw new WebdavForbidden();
} catch (CalFacadeException cfe) {
if (CalFacadeException.duplicateGuid.equals(cfe.getMessage())) {
throw new WebdavBadRequest("Duplicate-guid");
}
throw new WebdavException(cfe);
} catch (Throwable t) {
throw new WebdavException(t);
}
}
public Collection<EventInfo> getEvents(BwCalendar cal,
boolean getEvents,
boolean getTodos,
boolean getJournals,
BwDateTime startDate, BwDateTime endDate,
RecurringRetrievalMode recurRetrieval)
throws WebdavException {
try {
BwSubscription sub = BwSubscription.makeSubscription(cal);
if ((startDate == null) && (endDate == null)) {
return getSvci().getEvents(sub, recurRetrieval);
}
BwFilter filter = makeFilter(getEvents, getTodos, getJournals);
return getSvci().getEvents(sub, filter, startDate, endDate,
recurRetrieval);
} catch (CalFacadeAccessException cfae) {
throw new WebdavForbidden();
} catch (CalFacadeException cfe) {
throw new WebdavException(cfe);
} catch (WebdavException wde) {
throw wde;
} catch (Throwable t) {
throw new WebdavException(t);
}
}
public EventInfo getEvent(BwCalendar cal, String val,
RecurringRetrievalMode recurRetrieval)
throws WebdavException {
try {
return getSvci().getEvent(cal, val, recurRetrieval);
} catch (Throwable t) {
throw new WebdavException(t);
}
}
public void deleteEvent(BwEvent ev) throws WebdavException {
try {
getSvci().deleteEvent(ev, true);
} catch (Throwable t) {
throw new WebdavException(t);
}
}
public void deleteCalendar(BwCalendar cal) throws WebdavException {
try {
getSvci().deleteCalendar(cal);
} catch (Throwable t) {
throw new WebdavException(t);
}
}
public ScheduleResult requestFreeBusy(BwFreeBusy val) throws WebdavException {
try {
return getSvci().requestFreeBusy(val);
} catch (CalFacadeException cfe) {
throw new WebdavException(cfe);
} catch (Throwable t) {
throw new WebdavException(t);
}
}
public BwFreeBusy getFreeBusy(BwCalendar cal,
String account,
BwDateTime start,
BwDateTime end) throws WebdavException {
try {
BwUser user = getSvci().findUser(account, false);
if (user == null) {
throw new WebdavUnauthorized();
}
if (getSvci().isUserRoot(cal)) {
cal = null;
}
return getSvci().getFreeBusy(null, cal, user, start, end,
null, false);
} catch (CalFacadeException cfe) {
throw new WebdavException(cfe);
} catch (WebdavException wde) {
throw wde;
} catch (Throwable t) {
throw new WebdavException(t);
}
}
public CurrentAccess checkAccess(BwShareableDbentity ent,
int desiredAccess,
boolean returnResult)
throws WebdavException {
try {
return getSvci().checkAccess(ent, desiredAccess, returnResult);
} catch (CalFacadeException cfe) {
throw new WebdavException(cfe);
}
}
public void updateAccess(BwCalendar cal,
Collection<Ace> aces) throws WebdavException {
try {
getSvci().changeAccess(cal, aces);
getSvci().updateCalendar(cal);
} catch (CalFacadeAccessException cfae) {
throw new WebdavForbidden();
} catch (CalFacadeException cfe) {
throw new WebdavException(cfe);
} catch (Throwable t) {
throw new WebdavException(t);
}
}
public void updateAccess(BwEvent ev,
Collection<Ace> aces) throws WebdavException{
try {
getSvci().changeAccess(ev, aces);
getSvci().updateEvent(ev, null, null);
} catch (CalFacadeAccessException cfae) {
throw new WebdavForbidden();
} catch (CalFacadeException cfe) {
throw new WebdavException(cfe);
} catch (Throwable t) {
throw new WebdavException(t);
}
}
public int makeCollection(String name, boolean calendarCollection,
String parentPath) throws WebdavException {
BwCalendar newcal = new BwCalendar();
newcal.setName(name);
newcal.setCalendarCollection(calendarCollection);
try {
getSvci().addCalendar(newcal, parentPath);
return HttpServletResponse.SC_CREATED;
} catch (CalFacadeAccessException cfae) {
return HttpServletResponse.SC_FORBIDDEN;
} catch (CalFacadeException cfe) {
String msg = cfe.getMessage();
if (CalFacadeException.duplicateCalendar.equals(msg)) {
return HttpServletResponse.SC_METHOD_NOT_ALLOWED;
}
throw new WebdavException(cfe);
} catch (Throwable t) {
throw new WebdavException(t);
}
}
/* (non-Javadoc)
* @see org.bedework.caldav.server.SysIntf#copyMove(org.bedework.calfacade.BwCalendar, org.bedework.calfacade.BwCalendar, boolean)
*/
public void copyMove(BwCalendar from,
BwCalendar to,
boolean copy,
boolean overwrite) throws WebdavException {
throw new WebdavException("unimplemented");
}
/* (non-Javadoc)
* @see org.bedework.caldav.server.SysIntf#copyMove(org.bedework.calfacade.BwEvent, org.bedework.calfacade.BwCalendar, java.lang.String, boolean)
*/
public void copyMove(BwEvent from, Collection<BwEventProxy>overrides,
BwCalendar to,
String name,
boolean copy,
boolean overwrite) throws WebdavException {
/* A move of an entity to the same calendar is essentially a rename.
*/
try {
boolean sameCal = from.getCalendar().equals(to);
boolean rename = sameCal && !copy && !overwrite;
if (rename) {
from.setName(name);
getSvci().updateEvent(from, overrides, null);
return;
}
if (!overwrite) {
BwEvent newEvent = (BwEvent)from.clone();
newEvent.setCalendar(to);
newEvent.setName(name);
getSvci().addEvent(to, newEvent, overrides, true);
} else {
/* Should do update
RecurringRetrievalMode rrm =
new RecurringRetrievalMode(Rmode.overrides);
Collection<EventInfo> eis = getSvci().getEvent(null, from.getCalendar(),
from.getUid(),
from.getRecurrenceId(),
rrm);
if (eis.size() != 1) {
throw new WebdavForbidden();
}
EventInfo ei = eis.iterator().next();
// Now I have to effectively replace
BwEvent ...
*/
- BwEvent newEvent = (BwEvent)from.clone();
+ BwEvent delEvent = (BwEvent)from.clone();
- newEvent.setCalendar(to);
- newEvent.setName(name);
- getSvci().deleteEvent(newEvent, true);
+ delEvent.setCalendar(to);
+ delEvent.setName(name);
+ getSvci().deleteEvent(delEvent, true);
+ BwEvent newEvent = (BwEvent)delEvent.clone();
getSvci().addEvent(to, newEvent, overrides, true);
}
if (!copy) {
getSvci().deleteEvent(from, true);
}
} catch (CalFacadeAccessException cfae) {
throw new WebdavForbidden();
} catch (CalFacadeException cfe) {
throw new WebdavException(cfe);
} catch (Throwable t) {
throw new WebdavException(t);
}
}
public BwCalendar getCalendar(String path) throws WebdavException {
try {
return getSvci().getCalendar(path);
} catch (CalFacadeAccessException cfae) {
throw new WebdavForbidden();
} catch (CalFacadeException cfe) {
throw new WebdavException(cfe);
} catch (Throwable t) {
throw new WebdavException(t);
}
}
public Collection<BwCalendar> getCalendars(BwCalendar cal) throws WebdavException {
try {
return getSvci().getCalendars(cal);
} catch (CalFacadeAccessException cfae) {
throw new WebdavForbidden();
} catch (CalFacadeException cfe) {
throw new WebdavException(cfe);
} catch (Throwable t) {
throw new WebdavException(t);
}
}
public Calendar toCalendar(EventInfo ev) throws WebdavException {
try {
return trans.toIcal(ev, Icalendar.methodTypeNone);
} catch (Throwable t) {
throw new WebdavException(t);
}
}
public Icalendar fromIcal(BwCalendar cal, Reader rdr) throws WebdavException {
getSvci(); // Ensure open
try {
return trans.fromIcal(cal, rdr);
} catch (IcalMalformedException ime) {
throw new WebdavBadRequest(ime.getMessage());
} catch (Throwable t) {
throw new WebdavException(t);
}
}
public CalTimezones getTimezones() throws WebdavException {
try {
return getSvci().getTimezones();
} catch (CalFacadeException cfe) {
throw new WebdavException(cfe);
} catch (Throwable t) {
throw new WebdavException(t);
}
}
public TimeZone getDefaultTimeZone() throws WebdavException {
try {
return getSvci().getTimezones().getDefaultTimeZone();
} catch (CalFacadeException cfe) {
throw new WebdavException(cfe);
} catch (Throwable t) {
throw new WebdavException(t);
}
}
public String toStringTzCalendar(String tzid) throws WebdavException {
try {
return trans.toStringTzCalendar(tzid);
} catch (CalFacadeException cfe) {
throw new WebdavException(cfe);
} catch (Throwable t) {
throw new WebdavException(t);
}
}
public int getMaxUserEntitySize() throws WebdavException {
try {
return getSvci().getSyspars().getMaxUserEntitySize();
} catch (CalFacadeException cfe) {
throw new WebdavException(cfe);
} catch (Throwable t) {
throw new WebdavException(t);
}
}
public void close() throws WebdavException {
close(svci);
}
/* ====================================================================
* Private methods
* ==================================================================== */
private BwFilter makeFilter(boolean getEvents,
boolean getTodos,
boolean getJournals) throws WebdavException {
int numTypes = 0;
if (getEvents) {
numTypes++;
}
if (getTodos) {
numTypes++;
}
if (getJournals) {
numTypes++;
}
if (numTypes == 0) {
throw new WebdavBadRequest("org.bedework.caldav.noentitytypespecified");
}
if (numTypes == 3) {
// No filter
return null;
}
BwFilter filter = null;
BwOrFilter orFilter = null;
if (numTypes > 1) {
orFilter = new BwOrFilter();
}
if (getEvents) {
filter = BwEntityTypeFilter.eventFilter(null);
if (numTypes > 1) {
orFilter.addChild(filter);
}
}
if (getTodos) {
filter = BwEntityTypeFilter.todoFilter(null);
if (numTypes > 1) {
orFilter.addChild(filter);
}
}
if (getJournals) {
filter = BwEntityTypeFilter.journalFilter(null);
if (numTypes > 1) {
orFilter.addChild(filter);
}
}
if (numTypes > 1) {
return orFilter;
}
return filter;
}
/**
* @return CalSvcI
* @throws WebdavException
*/
private CalSvcI getSvci() throws WebdavException {
if (svci != null) {
if (!svci.isOpen()) {
try {
svci.open();
svci.beginTransaction();
} catch (Throwable t) {
throw new WebdavException(t);
}
}
return svci;
}
try {
String runAsUser = account;
if (account == null) {
runAsUser = getEnv().getAppProperty("run.as.user");
}
/* account is what we authenticated with.
* user, if non-null, is the user calendar we want to access.
*/
CalSvcIPars pars = new CalSvcIPars(account,
runAsUser,
null, // calsuite
envPrefix,
false, // publicAdmin
false, // adminCanEditAllPublicCategories
false, // adminCanEditAllPublicLocations
false, // adminCanEditAllPublicSponsors
true, // caldav
null, // synchId
debug);
svci = new CalSvcFactoryDefault().getSvc(pars);
svci.open();
svci.beginTransaction();
trans = new IcalTranslator(svci.getIcalCallback(), debug);
} catch (WebdavException wde) {
throw wde;
} catch (Throwable t) {
throw new WebdavException(t);
}
return svci;
}
private CalEnvI getEnv() throws WebdavException {
try {
if (env != null) {
return env;
}
env = CalEnvFactory.getEnv(envPrefix, debug);
return env;
} catch (Throwable t) {
throw new WebdavException(t);
}
}
private void close(CalSvcI svci) throws WebdavException {
if ((svci == null) || !svci.isOpen()) {
return;
}
try {
svci.endTransaction();
} catch (Throwable t) {
try {
svci.close();
} catch (Throwable t1) {
}
svci = null;
if (t instanceof CalFacadeStaleStateException) {
throw new WebdavException(HttpServletResponse.SC_CONFLICT);
}
throw new WebdavException(t);
}
try {
svci.close();
} catch (Throwable t) {
svci = null;
throw new WebdavException(t);
}
}
/* ====================================================================
* Protected methods
* ==================================================================== */
protected Logger getLogger() {
if (log == null) {
log = Logger.getLogger(this.getClass());
}
return log;
}
protected void trace(String msg) {
getLogger().debug(msg);
}
protected void debugMsg(String msg) {
getLogger().debug(msg);
}
protected void warn(String msg) {
getLogger().warn(msg);
}
protected void error(Throwable t) {
getLogger().error(this, t);
}
protected void logIt(String msg) {
getLogger().info(msg);
}
}
| false | true | public void copyMove(BwEvent from, Collection<BwEventProxy>overrides,
BwCalendar to,
String name,
boolean copy,
boolean overwrite) throws WebdavException {
/* A move of an entity to the same calendar is essentially a rename.
*/
try {
boolean sameCal = from.getCalendar().equals(to);
boolean rename = sameCal && !copy && !overwrite;
if (rename) {
from.setName(name);
getSvci().updateEvent(from, overrides, null);
return;
}
if (!overwrite) {
BwEvent newEvent = (BwEvent)from.clone();
newEvent.setCalendar(to);
newEvent.setName(name);
getSvci().addEvent(to, newEvent, overrides, true);
} else {
/* Should do update
RecurringRetrievalMode rrm =
new RecurringRetrievalMode(Rmode.overrides);
Collection<EventInfo> eis = getSvci().getEvent(null, from.getCalendar(),
from.getUid(),
from.getRecurrenceId(),
rrm);
if (eis.size() != 1) {
throw new WebdavForbidden();
}
EventInfo ei = eis.iterator().next();
// Now I have to effectively replace
BwEvent ...
*/
BwEvent newEvent = (BwEvent)from.clone();
newEvent.setCalendar(to);
newEvent.setName(name);
getSvci().deleteEvent(newEvent, true);
getSvci().addEvent(to, newEvent, overrides, true);
}
if (!copy) {
getSvci().deleteEvent(from, true);
}
} catch (CalFacadeAccessException cfae) {
throw new WebdavForbidden();
} catch (CalFacadeException cfe) {
throw new WebdavException(cfe);
} catch (Throwable t) {
throw new WebdavException(t);
}
}
| public void copyMove(BwEvent from, Collection<BwEventProxy>overrides,
BwCalendar to,
String name,
boolean copy,
boolean overwrite) throws WebdavException {
/* A move of an entity to the same calendar is essentially a rename.
*/
try {
boolean sameCal = from.getCalendar().equals(to);
boolean rename = sameCal && !copy && !overwrite;
if (rename) {
from.setName(name);
getSvci().updateEvent(from, overrides, null);
return;
}
if (!overwrite) {
BwEvent newEvent = (BwEvent)from.clone();
newEvent.setCalendar(to);
newEvent.setName(name);
getSvci().addEvent(to, newEvent, overrides, true);
} else {
/* Should do update
RecurringRetrievalMode rrm =
new RecurringRetrievalMode(Rmode.overrides);
Collection<EventInfo> eis = getSvci().getEvent(null, from.getCalendar(),
from.getUid(),
from.getRecurrenceId(),
rrm);
if (eis.size() != 1) {
throw new WebdavForbidden();
}
EventInfo ei = eis.iterator().next();
// Now I have to effectively replace
BwEvent ...
*/
BwEvent delEvent = (BwEvent)from.clone();
delEvent.setCalendar(to);
delEvent.setName(name);
getSvci().deleteEvent(delEvent, true);
BwEvent newEvent = (BwEvent)delEvent.clone();
getSvci().addEvent(to, newEvent, overrides, true);
}
if (!copy) {
getSvci().deleteEvent(from, true);
}
} catch (CalFacadeAccessException cfae) {
throw new WebdavForbidden();
} catch (CalFacadeException cfe) {
throw new WebdavException(cfe);
} catch (Throwable t) {
throw new WebdavException(t);
}
}
|
diff --git a/sonar-server/src/main/java/org/sonar/server/database/EmbeddedDatabase.java b/sonar-server/src/main/java/org/sonar/server/database/EmbeddedDatabase.java
index e678f5551b..9c1a726598 100644
--- a/sonar-server/src/main/java/org/sonar/server/database/EmbeddedDatabase.java
+++ b/sonar-server/src/main/java/org/sonar/server/database/EmbeddedDatabase.java
@@ -1,104 +1,104 @@
/*
* Sonar, open source software quality management tool.
* Copyright (C) 2008-2012 SonarSource
* mailto:contact AT sonarsource DOT com
*
* Sonar 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 3 of the License, or (at your option) any later version.
*
* Sonar 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 Sonar; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
*/
package org.sonar.server.database;
import org.apache.commons.lang.StringUtils;
import org.h2.tools.Server;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.api.CoreProperties;
import org.sonar.api.config.Settings;
import org.sonar.api.database.DatabaseProperties;
import org.sonar.api.utils.SonarException;
import org.sonar.server.platform.ServerStartException;
import java.io.File;
import java.sql.DriverManager;
import java.sql.SQLException;
public class EmbeddedDatabase {
private static final Logger LOG = LoggerFactory.getLogger(EmbeddedDatabase.class);
private final Settings settings;
private Server server;
public EmbeddedDatabase(Settings settings) {
this.settings = settings;
}
public void start() {
File dbHome = getDataDirectory(settings);
if (dbHome.exists() && !dbHome.isDirectory()) {
throw new SonarException("Database home " + dbHome.getPath() + " is not a directory");
}
if (!dbHome.exists()) {
dbHome.mkdirs();
}
String port = getSetting(DatabaseProperties.PROP_EMBEDDED_PORT, DatabaseProperties.PROP_EMBEDDED_PORT_DEFAULT_VALUE);
String user = getSetting(DatabaseProperties.PROP_USER, DatabaseProperties.PROP_USER_DEFAULT_VALUE);
String password = getSetting(DatabaseProperties.PROP_PASSWORD, DatabaseProperties.PROP_PASSWORD_DEFAULT_VALUE);
try {
createDatabase(dbHome, user, password);
- Server server = Server.createTcpServer("-tcpPort", port, "-tcpAllowOthers", "-ifExists", "-baseDir", dbHome.getAbsolutePath());
+ server = Server.createTcpServer("-tcpPort", port, "-tcpAllowOthers", "-ifExists", "-baseDir", dbHome.getAbsolutePath());
LOG.info("Starting embedded database on port " + server.getPort());
server.start();
LOG.info("Embedded database started. Data stored in: " + dbHome.getAbsolutePath());
} catch (Exception e) {
throw new SonarException("Unable to start database", e);
}
}
public void stop() {
if (server != null) {
server.stop();
server = null;
LOG.info("Embedded database stopped");
}
}
private String getSetting(String name, String defaultValue) {
return StringUtils.defaultIfBlank(settings.getString(name), defaultValue);
}
private void createDatabase(File dbHome, String user, String password) throws SQLException {
String url = String.format("jdbc:h2:%s/sonar;USER=%s;PASSWORD=%s", dbHome.getAbsolutePath(), user, password);
DriverManager.getConnection(url).close();
}
private static File getDataDirectory(Settings settings) {
String dirName = settings.getString(DatabaseProperties.PROP_EMBEDDED_DATA_DIR);
if (!StringUtils.isBlank(dirName)) {
return new File(dirName);
}
File sonarHome = new File(settings.getString(CoreProperties.SONAR_HOME));
if (sonarHome.isDirectory() && sonarHome.exists()) {
return new File(sonarHome, "data");
}
throw new ServerStartException("Sonar home directory does not exist");
}
}
| true | true | public void start() {
File dbHome = getDataDirectory(settings);
if (dbHome.exists() && !dbHome.isDirectory()) {
throw new SonarException("Database home " + dbHome.getPath() + " is not a directory");
}
if (!dbHome.exists()) {
dbHome.mkdirs();
}
String port = getSetting(DatabaseProperties.PROP_EMBEDDED_PORT, DatabaseProperties.PROP_EMBEDDED_PORT_DEFAULT_VALUE);
String user = getSetting(DatabaseProperties.PROP_USER, DatabaseProperties.PROP_USER_DEFAULT_VALUE);
String password = getSetting(DatabaseProperties.PROP_PASSWORD, DatabaseProperties.PROP_PASSWORD_DEFAULT_VALUE);
try {
createDatabase(dbHome, user, password);
Server server = Server.createTcpServer("-tcpPort", port, "-tcpAllowOthers", "-ifExists", "-baseDir", dbHome.getAbsolutePath());
LOG.info("Starting embedded database on port " + server.getPort());
server.start();
LOG.info("Embedded database started. Data stored in: " + dbHome.getAbsolutePath());
} catch (Exception e) {
throw new SonarException("Unable to start database", e);
}
}
| public void start() {
File dbHome = getDataDirectory(settings);
if (dbHome.exists() && !dbHome.isDirectory()) {
throw new SonarException("Database home " + dbHome.getPath() + " is not a directory");
}
if (!dbHome.exists()) {
dbHome.mkdirs();
}
String port = getSetting(DatabaseProperties.PROP_EMBEDDED_PORT, DatabaseProperties.PROP_EMBEDDED_PORT_DEFAULT_VALUE);
String user = getSetting(DatabaseProperties.PROP_USER, DatabaseProperties.PROP_USER_DEFAULT_VALUE);
String password = getSetting(DatabaseProperties.PROP_PASSWORD, DatabaseProperties.PROP_PASSWORD_DEFAULT_VALUE);
try {
createDatabase(dbHome, user, password);
server = Server.createTcpServer("-tcpPort", port, "-tcpAllowOthers", "-ifExists", "-baseDir", dbHome.getAbsolutePath());
LOG.info("Starting embedded database on port " + server.getPort());
server.start();
LOG.info("Embedded database started. Data stored in: " + dbHome.getAbsolutePath());
} catch (Exception e) {
throw new SonarException("Unable to start database", e);
}
}
|
diff --git a/src/main/java/jp/sf/fess/job/TriggeredJob.java b/src/main/java/jp/sf/fess/job/TriggeredJob.java
index ed8102086..98c56fa8d 100644
--- a/src/main/java/jp/sf/fess/job/TriggeredJob.java
+++ b/src/main/java/jp/sf/fess/job/TriggeredJob.java
@@ -1,117 +1,122 @@
/*
* Copyright 2009-2013 the Fess Project and the Others.
*
* 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 jp.sf.fess.job;
import java.sql.Timestamp;
import jp.sf.fess.Constants;
import jp.sf.fess.db.exentity.JobLog;
import jp.sf.fess.db.exentity.ScheduledJob;
import jp.sf.fess.helper.SystemHelper;
import jp.sf.fess.service.JobLogService;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.seasar.framework.container.SingletonS2Container;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TriggeredJob implements Job {
private static final Logger logger = LoggerFactory
.getLogger(TriggeredJob.class);
private static final String JOB_EXECUTOR_SUFFIX = "JobExecutor";
@Override
public void execute(final JobExecutionContext context)
throws JobExecutionException {
final JobDataMap data = context.getMergedJobDataMap();
final ScheduledJob scheduledJob = (ScheduledJob) data
.get(Constants.SCHEDULED_JOB);
execute(scheduledJob);
}
public void execute(final ScheduledJob scheduledJob) {
final SystemHelper systemHelper = SingletonS2Container
.getComponent(SystemHelper.class);
final JobLog jobLog = new JobLog(scheduledJob);
final String scriptType = scheduledJob.getScriptType();
final String script = scheduledJob.getScriptData();
final Long id = scheduledJob.getId();
final String jobId = Constants.JOB_ID_PREFIX + id;
final JobExecutor jobExecutor = SingletonS2Container
.getComponent(scriptType + JOB_EXECUTOR_SUFFIX);
if (jobExecutor == null) {
throw new ScheduledJobException("No jobExecutor: " + scriptType
+ JOB_EXECUTOR_SUFFIX);
}
if (systemHelper.startJobExecutoer(id, jobExecutor) != null) {
if (logger.isDebugEnabled()) {
logger.debug(jobId + " is running.");
}
return;
}
try {
if (scheduledJob.isLoggingEnabled()) {
storeJobLog(jobLog);
}
if (logger.isDebugEnabled()) {
logger.debug("Starting Job " + jobId + ". scriptType: "
+ scriptType + ", script: " + script);
- } else if (logger.isInfoEnabled()) {
+ } else if (scheduledJob.isLoggingEnabled()
+ && logger.isInfoEnabled()) {
logger.info("Starting Job " + jobId + ".");
}
final Object ret = jobExecutor.execute(script);
if (ret == null) {
- logger.info("Finished Job " + jobId + ".");
+ if (scheduledJob.isLoggingEnabled() && logger.isInfoEnabled()) {
+ logger.info("Finished Job " + jobId + ".");
+ }
} else {
- logger.info("Finished Job " + jobId
- + ". The return value is:\n" + ret);
+ if (scheduledJob.isLoggingEnabled() && logger.isInfoEnabled()) {
+ logger.info("Finished Job " + jobId
+ + ". The return value is:\n" + ret);
+ }
jobLog.setScriptResult(ret.toString());
}
jobLog.setJobStatus(Constants.OK);
} catch (final Throwable e) {
logger.error("Failed to execute " + jobId + ": " + script, e);
jobLog.setJobStatus(Constants.FAIL);
jobLog.setScriptResult(systemHelper.abbreviateLongText(e
.getLocalizedMessage()));
} finally {
systemHelper.finishJobExecutoer(id);
jobLog.setEndTime(new Timestamp(System.currentTimeMillis()));
if (logger.isDebugEnabled()) {
logger.debug("jobLog: " + jobLog);
}
if (scheduledJob.isLoggingEnabled()) {
storeJobLog(jobLog);
}
}
}
private void storeJobLog(final JobLog jobLog) {
final JobLogService jobLogService = SingletonS2Container
.getComponent(JobLogService.class);
jobLogService.store(jobLog);
}
}
| false | true | public void execute(final ScheduledJob scheduledJob) {
final SystemHelper systemHelper = SingletonS2Container
.getComponent(SystemHelper.class);
final JobLog jobLog = new JobLog(scheduledJob);
final String scriptType = scheduledJob.getScriptType();
final String script = scheduledJob.getScriptData();
final Long id = scheduledJob.getId();
final String jobId = Constants.JOB_ID_PREFIX + id;
final JobExecutor jobExecutor = SingletonS2Container
.getComponent(scriptType + JOB_EXECUTOR_SUFFIX);
if (jobExecutor == null) {
throw new ScheduledJobException("No jobExecutor: " + scriptType
+ JOB_EXECUTOR_SUFFIX);
}
if (systemHelper.startJobExecutoer(id, jobExecutor) != null) {
if (logger.isDebugEnabled()) {
logger.debug(jobId + " is running.");
}
return;
}
try {
if (scheduledJob.isLoggingEnabled()) {
storeJobLog(jobLog);
}
if (logger.isDebugEnabled()) {
logger.debug("Starting Job " + jobId + ". scriptType: "
+ scriptType + ", script: " + script);
} else if (logger.isInfoEnabled()) {
logger.info("Starting Job " + jobId + ".");
}
final Object ret = jobExecutor.execute(script);
if (ret == null) {
logger.info("Finished Job " + jobId + ".");
} else {
logger.info("Finished Job " + jobId
+ ". The return value is:\n" + ret);
jobLog.setScriptResult(ret.toString());
}
jobLog.setJobStatus(Constants.OK);
} catch (final Throwable e) {
logger.error("Failed to execute " + jobId + ": " + script, e);
jobLog.setJobStatus(Constants.FAIL);
jobLog.setScriptResult(systemHelper.abbreviateLongText(e
.getLocalizedMessage()));
} finally {
systemHelper.finishJobExecutoer(id);
jobLog.setEndTime(new Timestamp(System.currentTimeMillis()));
if (logger.isDebugEnabled()) {
logger.debug("jobLog: " + jobLog);
}
if (scheduledJob.isLoggingEnabled()) {
storeJobLog(jobLog);
}
}
}
| public void execute(final ScheduledJob scheduledJob) {
final SystemHelper systemHelper = SingletonS2Container
.getComponent(SystemHelper.class);
final JobLog jobLog = new JobLog(scheduledJob);
final String scriptType = scheduledJob.getScriptType();
final String script = scheduledJob.getScriptData();
final Long id = scheduledJob.getId();
final String jobId = Constants.JOB_ID_PREFIX + id;
final JobExecutor jobExecutor = SingletonS2Container
.getComponent(scriptType + JOB_EXECUTOR_SUFFIX);
if (jobExecutor == null) {
throw new ScheduledJobException("No jobExecutor: " + scriptType
+ JOB_EXECUTOR_SUFFIX);
}
if (systemHelper.startJobExecutoer(id, jobExecutor) != null) {
if (logger.isDebugEnabled()) {
logger.debug(jobId + " is running.");
}
return;
}
try {
if (scheduledJob.isLoggingEnabled()) {
storeJobLog(jobLog);
}
if (logger.isDebugEnabled()) {
logger.debug("Starting Job " + jobId + ". scriptType: "
+ scriptType + ", script: " + script);
} else if (scheduledJob.isLoggingEnabled()
&& logger.isInfoEnabled()) {
logger.info("Starting Job " + jobId + ".");
}
final Object ret = jobExecutor.execute(script);
if (ret == null) {
if (scheduledJob.isLoggingEnabled() && logger.isInfoEnabled()) {
logger.info("Finished Job " + jobId + ".");
}
} else {
if (scheduledJob.isLoggingEnabled() && logger.isInfoEnabled()) {
logger.info("Finished Job " + jobId
+ ". The return value is:\n" + ret);
}
jobLog.setScriptResult(ret.toString());
}
jobLog.setJobStatus(Constants.OK);
} catch (final Throwable e) {
logger.error("Failed to execute " + jobId + ": " + script, e);
jobLog.setJobStatus(Constants.FAIL);
jobLog.setScriptResult(systemHelper.abbreviateLongText(e
.getLocalizedMessage()));
} finally {
systemHelper.finishJobExecutoer(id);
jobLog.setEndTime(new Timestamp(System.currentTimeMillis()));
if (logger.isDebugEnabled()) {
logger.debug("jobLog: " + jobLog);
}
if (scheduledJob.isLoggingEnabled()) {
storeJobLog(jobLog);
}
}
}
|
diff --git a/src/lang/psi/impl/statements/LuaFunctionDefinitionStatementImpl.java b/src/lang/psi/impl/statements/LuaFunctionDefinitionStatementImpl.java
index 4b7d3781..fb8996b5 100644
--- a/src/lang/psi/impl/statements/LuaFunctionDefinitionStatementImpl.java
+++ b/src/lang/psi/impl/statements/LuaFunctionDefinitionStatementImpl.java
@@ -1,147 +1,146 @@
/*
* Copyright 2010 Jon S Akhtar (Sylvanaar)
*
* 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.sylvanaar.idea.Lua.lang.psi.impl.statements;
import com.intellij.lang.ASTNode;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiElementVisitor;
import com.intellij.psi.ResolveState;
import com.intellij.psi.scope.PsiScopeProcessor;
import com.sylvanaar.idea.Lua.lang.parser.LuaElementTypes;
import com.sylvanaar.idea.Lua.lang.psi.expressions.LuaParameter;
import com.sylvanaar.idea.Lua.lang.psi.expressions.LuaParameterList;
import com.sylvanaar.idea.Lua.lang.psi.expressions.LuaVariable;
import com.sylvanaar.idea.Lua.lang.psi.impl.expressions.LuaImpliedSelfParameterImpl;
import com.sylvanaar.idea.Lua.lang.psi.statements.LuaBlock;
import com.sylvanaar.idea.Lua.lang.psi.statements.LuaFunctionDefinitionStatement;
import com.sylvanaar.idea.Lua.lang.psi.visitor.LuaElementVisitor;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* Created by IntelliJ IDEA.
* User: Jon S Akhtar
* Date: Jun 10, 2010
* Time: 10:40:55 AM
*/
public class LuaFunctionDefinitionStatementImpl extends LuaStatementElementImpl implements LuaFunctionDefinitionStatement/*, PsiModifierList */ {
private LuaParameterList parameters = null;
private LuaVariable identifier = null;
private LuaBlock block = null;
private boolean definesSelf = false;
public LuaFunctionDefinitionStatementImpl(ASTNode node) {
super(node);
assert getBlock() != null;
}
public void accept(LuaElementVisitor visitor) {
visitor.visitFunctionDef(this);
}
public void accept(@NotNull PsiElementVisitor visitor) {
if (visitor instanceof LuaElementVisitor) {
((LuaElementVisitor) visitor).visitFunctionDef(this);
} else {
visitor.visitElement(this);
}
}
public boolean processDeclarations(@NotNull PsiScopeProcessor processor,
@NotNull ResolveState resolveState,
PsiElement lastParent,
@NotNull PsiElement place) {
if (lastParent != null && lastParent.getParent() == this) {
-// final LuaParameter[] params = getParameters().getParameters();
-// for (LuaParameter param : params) {
-// if (!processor.execute(param, resolveState)) return false;
-// }
-//
+ final LuaParameter[] params = getParameters().getParameters();
+ for (LuaParameter param : params) {
+ if (!processor.execute(param, resolveState)) return false;
+ }
LuaParameter self = findChildByClass(LuaImpliedSelfParameterImpl.class);
if (self != null) {
if (!processor.execute(self, resolveState)) return false;
}
}
//
// if (!getBlock().processDeclarations(processor, resolveState, lastParent, place))
// return false;
// if (getIdentifier() == null || !getIdentifier().isLocal())
// return true;
// if (!processor.execute(getIdentifier(), resolveState))
// return false;
return true;
}
@Nullable
@NonNls
public String getName() {
LuaVariable name = getIdentifier();
return name != null ? name.getText() : "anonymous";
}
@Override
public PsiElement setName(String s) {
return null;//getIdentifier().setName(s);
}
@Override
public LuaVariable getIdentifier() {
if (identifier == null) {
LuaVariable e = findChildByClass(LuaVariable.class);
if (e != null)
identifier = e;
}
return identifier;
}
@Override
public LuaParameterList getParameters() {
if (parameters == null) {
PsiElement e = findChildByType(LuaElementTypes.PARAMETER_LIST);
if (e != null)
parameters = (LuaParameterList) e;
}
return parameters;
}
public LuaBlock getBlock() {
if (block == null) {
PsiElement e = findChildByType(LuaElementTypes.BLOCK);
if (e != null)
block = (LuaBlock) e;
}
return block;
}
@Override
public String toString() {
return "Function Declaration (" + getIdentifier() + ")";
}
}
| true | true | public boolean processDeclarations(@NotNull PsiScopeProcessor processor,
@NotNull ResolveState resolveState,
PsiElement lastParent,
@NotNull PsiElement place) {
if (lastParent != null && lastParent.getParent() == this) {
// final LuaParameter[] params = getParameters().getParameters();
// for (LuaParameter param : params) {
// if (!processor.execute(param, resolveState)) return false;
// }
//
LuaParameter self = findChildByClass(LuaImpliedSelfParameterImpl.class);
if (self != null) {
if (!processor.execute(self, resolveState)) return false;
}
}
//
// if (!getBlock().processDeclarations(processor, resolveState, lastParent, place))
// return false;
// if (getIdentifier() == null || !getIdentifier().isLocal())
// return true;
// if (!processor.execute(getIdentifier(), resolveState))
// return false;
return true;
}
| public boolean processDeclarations(@NotNull PsiScopeProcessor processor,
@NotNull ResolveState resolveState,
PsiElement lastParent,
@NotNull PsiElement place) {
if (lastParent != null && lastParent.getParent() == this) {
final LuaParameter[] params = getParameters().getParameters();
for (LuaParameter param : params) {
if (!processor.execute(param, resolveState)) return false;
}
LuaParameter self = findChildByClass(LuaImpliedSelfParameterImpl.class);
if (self != null) {
if (!processor.execute(self, resolveState)) return false;
}
}
//
// if (!getBlock().processDeclarations(processor, resolveState, lastParent, place))
// return false;
// if (getIdentifier() == null || !getIdentifier().isLocal())
// return true;
// if (!processor.execute(getIdentifier(), resolveState))
// return false;
return true;
}
|
diff --git a/spring-social-twitter/src/main/java/org/springframework/social/twitter/api/impl/SearchTemplate.java b/spring-social-twitter/src/main/java/org/springframework/social/twitter/api/impl/SearchTemplate.java
index 4ae43773..5104e434 100644
--- a/spring-social-twitter/src/main/java/org/springframework/social/twitter/api/impl/SearchTemplate.java
+++ b/spring-social-twitter/src/main/java/org/springframework/social/twitter/api/impl/SearchTemplate.java
@@ -1,149 +1,150 @@
/*
* Copyright 2011 the original author or authors.
*
* 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.springframework.social.twitter.api.impl;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.social.twitter.api.SavedSearch;
import org.springframework.social.twitter.api.SearchOperations;
import org.springframework.social.twitter.api.SearchResults;
import org.springframework.social.twitter.api.Trends;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
/**
* Implementation of {@link SearchOperations}, providing a binding to Twitter's search and trend-oriented REST resources.
* @author Craig Walls
*/
class SearchTemplate extends AbstractTwitterOperations implements SearchOperations {
private final RestTemplate restTemplate;
private final boolean includeEntities;
public SearchTemplate(RestTemplate restTemplate, boolean isAuthorizedForUser, final boolean includeEntities) {
super(isAuthorizedForUser);
this.restTemplate = restTemplate;
this.includeEntities = includeEntities;
}
public SearchResults search(String query) {
return search(query, 1, DEFAULT_RESULTS_PER_PAGE, 0, 0);
}
public SearchResults search(String query, int page, int resultsPerPage) {
return search(query, page, resultsPerPage, 0, 0);
}
public SearchResults search(String query, int page, int resultsPerPage, long sinceId, long maxId) {
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("query", query);
parameters.put("rpp", String.valueOf(resultsPerPage));
parameters.put("page", String.valueOf(page));
String searchUrl = SEARCH_URL;
if (sinceId > 0) {
searchUrl += "&since_id={since}";
parameters.put("since", String.valueOf(sinceId));
}
if (maxId > 0) {
searchUrl += "&max_id={max}";
parameters.put("max", String.valueOf(maxId));
}
if (this.includeEntities)
{
- parameters.put("include_entities", "true");
+ searchUrl += "&include_entities={entities}";
+ parameters.put("entities", "true");
}
return restTemplate.getForObject(searchUrl, SearchResults.class, parameters);
}
public List<SavedSearch> getSavedSearches() {
requireAuthorization();
return restTemplate.getForObject(buildUri("saved_searches.json"), SavedSearchList.class);
}
public SavedSearch getSavedSearch(long searchId) {
requireAuthorization();
return restTemplate.getForObject(buildUri("saved_searches/show/" + searchId + ".json"), SavedSearch.class);
}
public SavedSearch createSavedSearch(String query) {
requireAuthorization();
MultiValueMap<String, Object> data = new LinkedMultiValueMap<String, Object>();
data.set("query", query);
return restTemplate.postForObject(buildUri("saved_searches/create.json"), data, SavedSearch.class);
}
public void deleteSavedSearch(long searchId) {
requireAuthorization();
restTemplate.delete(buildUri("saved_searches/destroy/" + searchId + ".json"));
}
// Trends
public List<Trends> getDailyTrends() {
return getDailyTrends(false, null);
}
public List<Trends> getDailyTrends(boolean excludeHashtags) {
return getDailyTrends(excludeHashtags, null);
}
public List<Trends> getDailyTrends(boolean excludeHashtags, String startDate) {
String path = makeTrendPath("trends/daily.json", excludeHashtags, startDate);
return restTemplate.getForObject(buildUri(path), DailyTrendsList.class).getList();
}
public List<Trends> getWeeklyTrends() {
return getWeeklyTrends(false, null);
}
public List<Trends> getWeeklyTrends(boolean excludeHashtags) {
return getWeeklyTrends(excludeHashtags, null);
}
public List<Trends> getWeeklyTrends(boolean excludeHashtags, String startDate) {
String path = makeTrendPath("trends/weekly.json", excludeHashtags, startDate);
return restTemplate.getForObject(buildUri(path), WeeklyTrendsList.class).getList();
}
public Trends getLocalTrends(long whereOnEarthId) {
return getLocalTrends(whereOnEarthId, false);
}
public Trends getLocalTrends(long whereOnEarthId, boolean excludeHashtags) {
LinkedMultiValueMap<String, String> parameters = new LinkedMultiValueMap<String, String>();
if(excludeHashtags) {
parameters.set("exclude", "hashtags");
}
return restTemplate.getForObject(buildUri("trends/" + whereOnEarthId + ".json", parameters), LocalTrendsHolder.class).getTrends();
}
private String makeTrendPath(String basePath, boolean excludeHashtags, String startDate) {
String url = basePath + (excludeHashtags || startDate != null ? "?" : "");
url += excludeHashtags ? "exclude=hashtags" : "";
url += excludeHashtags && startDate != null ? "&" : "";
url += startDate != null ? "date=" + startDate : "";
return url;
}
static final int DEFAULT_RESULTS_PER_PAGE = 50;
private static final String SEARCH_API_URL_BASE = "https://search.twitter.com";
private static final String SEARCH_URL = SEARCH_API_URL_BASE + "/search.json?q={query}&rpp={rpp}&page={page}";
}
| true | true | public SearchResults search(String query, int page, int resultsPerPage, long sinceId, long maxId) {
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("query", query);
parameters.put("rpp", String.valueOf(resultsPerPage));
parameters.put("page", String.valueOf(page));
String searchUrl = SEARCH_URL;
if (sinceId > 0) {
searchUrl += "&since_id={since}";
parameters.put("since", String.valueOf(sinceId));
}
if (maxId > 0) {
searchUrl += "&max_id={max}";
parameters.put("max", String.valueOf(maxId));
}
if (this.includeEntities)
{
parameters.put("include_entities", "true");
}
return restTemplate.getForObject(searchUrl, SearchResults.class, parameters);
}
| public SearchResults search(String query, int page, int resultsPerPage, long sinceId, long maxId) {
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("query", query);
parameters.put("rpp", String.valueOf(resultsPerPage));
parameters.put("page", String.valueOf(page));
String searchUrl = SEARCH_URL;
if (sinceId > 0) {
searchUrl += "&since_id={since}";
parameters.put("since", String.valueOf(sinceId));
}
if (maxId > 0) {
searchUrl += "&max_id={max}";
parameters.put("max", String.valueOf(maxId));
}
if (this.includeEntities)
{
searchUrl += "&include_entities={entities}";
parameters.put("entities", "true");
}
return restTemplate.getForObject(searchUrl, SearchResults.class, parameters);
}
|
diff --git a/core/common/src/test/java/org/openengsb/core/common/workflow/model/ProcessBagTest.java b/core/common/src/test/java/org/openengsb/core/common/workflow/model/ProcessBagTest.java
index 5ca050460..ca28be6e3 100644
--- a/core/common/src/test/java/org/openengsb/core/common/workflow/model/ProcessBagTest.java
+++ b/core/common/src/test/java/org/openengsb/core/common/workflow/model/ProcessBagTest.java
@@ -1,119 +1,119 @@
/**
* Copyright 2010 OpenEngSB Division, Vienna University of Technology
*
* 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.openengsb.core.common.workflow.model;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.junit.Before;
import org.junit.Test;
import org.openengsb.core.common.workflow.ProcessBagException;
public class ProcessBagTest {
private ProcessBag pb;
@Before
public void init() throws Exception {
pb = new ProcessBag();
}
@Test(expected = ProcessBagException.class)
public void addProperty_shouldReturnException() throws ProcessBagException {
pb.addProperty("test", "42");
pb.addProperty("test", "42");
}
@Test
public void getPropertyClass_shouldReturnStringClass() throws Exception {
pb.addProperty("test", "42");
assertTrue(pb.getPropertyClass("test") == String.class);
}
@Test
public void getPropertyKeyList_shouldReturnTwo() throws Exception {
pb.addProperty("test", "42");
pb.addProperty("number", 42);
Set<String> list = pb.propertyKeySet();
assertThat(list.size(), is(2));
}
@Test
public void removeProperty_shouldContainStringOnly() throws Exception {
pb.addProperty("number", 42);
pb.addProperty("string", "42");
pb.removeProperty("number");
Set<String> list = pb.propertyKeySet();
assertTrue(list.contains("string"));
assertFalse(list.contains("number"));
}
@Test
public void getPropertyCount_shouldReturnTwo() throws Exception {
pb.addProperty("test", "42");
pb.addProperty("number", 42);
assertTrue(pb.propertyCount() == 2);
}
@Test
public void addOrReplaceProperty_shouldOverwriteValue() throws Exception {
pb.addProperty("test", "42");
pb.addOrReplaceProperty("test", "43");
assertEquals(pb.getProperty("test"), "43");
}
@Test
public void removeAllProperties_shouldDeleteEverything() throws Exception {
pb.addProperty("test", "42");
pb.addProperty("number", 42);
pb.removeAllProperties();
assertTrue(pb.propertyCount() == 0);
}
@Test
public void setProcessIdLater_shouldBlockGetter() throws Exception {
Callable<String> task = new Callable<String>() {
@Override
public String call() throws Exception {
return pb.getProcessId();
}
};
Future<String> processIdFuture = Executors.newSingleThreadExecutor().submit(task);
Thread.sleep(100);
// this task should block now
assertThat(processIdFuture.isDone(), is(false));
// just call it to make sure it isn't blocking
- pb.getPropertyCount();
+ pb.propertyCount();
pb.setProcessId("foo");
processIdFuture.get(1, TimeUnit.SECONDS);
}
}
| true | true | public void setProcessIdLater_shouldBlockGetter() throws Exception {
Callable<String> task = new Callable<String>() {
@Override
public String call() throws Exception {
return pb.getProcessId();
}
};
Future<String> processIdFuture = Executors.newSingleThreadExecutor().submit(task);
Thread.sleep(100);
// this task should block now
assertThat(processIdFuture.isDone(), is(false));
// just call it to make sure it isn't blocking
pb.getPropertyCount();
pb.setProcessId("foo");
processIdFuture.get(1, TimeUnit.SECONDS);
}
| public void setProcessIdLater_shouldBlockGetter() throws Exception {
Callable<String> task = new Callable<String>() {
@Override
public String call() throws Exception {
return pb.getProcessId();
}
};
Future<String> processIdFuture = Executors.newSingleThreadExecutor().submit(task);
Thread.sleep(100);
// this task should block now
assertThat(processIdFuture.isDone(), is(false));
// just call it to make sure it isn't blocking
pb.propertyCount();
pb.setProcessId("foo");
processIdFuture.get(1, TimeUnit.SECONDS);
}
|
diff --git a/src/me/slaps/iCoLand/LandManager.java b/src/me/slaps/iCoLand/LandManager.java
index 6abb094..8b2de45 100644
--- a/src/me/slaps/iCoLand/LandManager.java
+++ b/src/me/slaps/iCoLand/LandManager.java
@@ -1,330 +1,330 @@
package me.slaps.iCoLand;
import java.io.File;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Random;
import java.util.Set;
import org.bukkit.Location;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class LandManager {
Random rn = new Random();
private LandDB landDB;
public LandManager(LandDB db) {
landDB = db;
}
public void close() {
landDB.close();
}
// public void save() {
// //landDB.save();
// }
//
// public void load() {
// //landDB.load();
// }
public boolean addLand(Cuboid sl, String owner, String perms, String addons) {
if ( !sl.isValid() ) return false;
if ( intersectsExistingLand(sl) > 0 ) return false;
Timestamp now = new Timestamp(System.currentTimeMillis());
return landDB.createNewLand(new Land(0, sl, owner, "", Land.parsePermTags(perms),
Land.parseAddonTags(addons), now, now));
}
public boolean removeLandById(Integer id) {
return landDB.removeLandById(id);
}
public String listLand() {
String out = "";
Iterator<Land> itr = landDB.listAllLand().iterator();
while(itr.hasNext()) {
Land tmp = itr.next();
out += tmp.getID();
out += itr.hasNext() ? ", " : "";
}
return out;
}
public ArrayList<Land> listLandPastTaxTime(Timestamp time) {
return landDB.listLandPastTaxTime(time);
}
public Location getCenterOfLand(Integer id) {
Land land = landDB.getLandById(id);
return land.getCenter();
}
public boolean isOwner(String playerName, Integer id) {
return getOwner(id).equals(playerName);
}
public boolean canBuildDestroy(Player player, Location loc) {
String playerName = player.getName();
Integer id = landDB.getLandId(loc);
if ( id > 0 ) {
return landDB.hasPermission(id, playerName);
} else {
if ( !Config.unclaimedLandCanBuild ) {
return iCoLand.hasPermission(player, "canbuild");
} else {
return true;
}
}
}
public boolean inLand(Location loc) {
int id = landDB.getLandId(loc);
return (id>0)?true:false;
}
public Integer getLandId(Location loc) {
return landDB.getLandId(loc);
}
public ArrayList<Land> getAllLands() {
return landDB.listAllLand();
}
public int countLandsOwnedBy(String playerName) {
return landDB.countLandOwnedBy(playerName);
}
public ArrayList<Land> getLandsOwnedBy(String playerName, int limit, int offset) {
return landDB.listLandOwnedBy(playerName, limit, offset);
}
public Land getLandById(Integer id) {
return landDB.getLandById(id);
}
public boolean landIdExists(Integer id) {
return landDB.landIdExists(id);
}
public int intersectsExistingLand(Cuboid loc) {
return landDB.intersectsExistingLand(loc);
}
public void showSelectLandInfo(CommandSender sender, Cuboid select) {
Messaging mess = new Messaging(sender);
Integer id = intersectsExistingLand(select);
if ( id > 0 && iCoLand.landMgr.getLandById(id).location.equals(select) ) {
showExistingLandInfo(sender, landDB.getLandById(id));
} else if ( id > 0 ) {
mess.send("{ERR}Intersects existing land ID# "+id);
mess.send("{ERR}Selecting/showing land ID# "+id+" instead");
iCoLand.tmpCuboidMap.put(((Player)sender).getName(), iCoLand.landMgr.getLandById(id).location );
showExistingLandInfo(sender, landDB.getLandById(id));
} else {
mess.send("{}"+Misc.headerify("{PRM}Unclaimed Land{}"));
mess.send("Dimensoins: " + select.toDimString() );
mess.send("Volume: " + select.volume() );
mess.send("Price: " + iCoLand.df.format(getPrice(sender, select)));
}
}
public void showSelectLandInfo(CommandSender sender, Integer id) {
showExistingLandInfo(sender, landDB.getLandById(id));
}
public void showExistingLandInfo(CommandSender sender, Land land) {
Messaging mess = new Messaging(sender);
mess.send("{}"+Misc.headerify("{} Land ID# {PRM}"+land.getID()+"{} --"+
(land.locationName.isEmpty()?"":" {PRM}"+land.locationName+" {}")
));
mess.send("{CMD}C: {}"+land.location.toCenterCoords()+" {CMD}V: {}"+land.location.volume()+" {CMD}D: {}"+land.location.toDimString());
mess.send("{CMD}Owner: {}"+land.owner);
if ( !(sender instanceof Player) || land.owner.equals(((Player)sender).getName()) || iCoLand.hasPermission(sender,"bypass") ) {
if ( !land.locationName.isEmpty() )
mess.send("{CMD}Name: {}"+land.locationName);
mess.send("{CMD}Created: {}"+land.dateCreated);
mess.send("{CMD}Taxed: {}"+land.dateTaxed);
mess.send("{CMD}Perms: {}"+Land.writePermTags(land.canBuildDestroy));
mess.send("{CMD}Addons: {}"+Land.writeAddonTags(land.addons));
mess.send("{CMD}Addon Prices: {}"+Land.writeAddonPrices(sender, land));
}
}
public double getPrice(CommandSender sender, Cuboid target) {
double sum = 0;
Integer sx = target.LocMax.getBlockX()-target.LocMin.getBlockX()+1;
Integer sy = target.LocMax.getBlockY()-target.LocMin.getBlockY()+1;
Integer sz = target.LocMax.getBlockZ()-target.LocMin.getBlockZ()+1;
for(int x=0;x<sx;x++) {
for(int y=0;y<sy;y++) {
for(int z=0;z<sz;z++) {
sum += getPriceOfBlock(sender, new Location(target.setLoc1.getWorld(),
target.LocMin.getBlockX()+x, target.LocMin.getBlockY()+y, target.LocMin.getBlockZ()+z));
}
}
}
return sum;
}
public double getPriceOfBlock(CommandSender sender, Location target) {
// if ( iCoLand.hasPermission(sender, "nocost") ) {
// return 0;
// } else {
return Config.pricePerBlock.get("raw");
// }
}
public boolean canClaimMoreLands(String playerName) {
return ( landDB.countLandOwnedBy(playerName) < Config.maxLandsClaimable );
}
public boolean canClaimMoreVolume(String playerName, Integer claimSize) {
ArrayList<Land> lands = getLandsOwnedBy(playerName, 0, 0);
Integer totalBlocks = claimSize;
for(Land land : lands) {
totalBlocks += land.location.volume();
}
return ( totalBlocks <= Config.maxBlocksClaimable );
}
public void importDB(File importFile) {
landDB.importDB(importFile);
}
public void exportDB(File exportFile) {
landDB.exportDB(exportFile);
}
public boolean updateName(int id, String name) {
return landDB.updateLandName(id, name);
}
public boolean updateOwner(int id, String playerName) {
return landDB.updateLandOwner(id, playerName);
}
public boolean updateAddons(int id, String addonString) {
return landDB.updateLandAddons(id, addonString);
}
public boolean updateTaxTime(int id, Timestamp time) {
return landDB.updateTaxTime(id, time);
}
public boolean toggleAddons(int id, String tags) {
Set<String> in = Land.parseAddonTags(tags).keySet();
HashMap<String, Boolean> addons = Land.parseAddonTags(iCoLand.landMgr.getAddons(id));
for(String addon : in ) {
if ( addons.containsKey(addon) )
addons.remove(addon);
else
addons.put(addon, true);
}
return updateAddons(id, Land.writeAddonTags(addons));
}
public boolean removeAddon(int id, String addon) {
Boolean ret = false;
HashMap<String, Boolean> addons = Land.parseAddonTags(iCoLand.landMgr.getAddons(id));
if ( addons.containsKey(addon) ) {
addons.remove(addon);
ret = true;
} else {
ret = false;
}
updateAddons(id, Land.writeAddonTags(addons));
return ret;
}
public boolean addAddon(int id, String addon) {
Boolean ret = false;
HashMap<String, Boolean> addons = Land.parseAddonTags(iCoLand.landMgr.getAddons(id));
if ( addons.containsKey(addon) ) {
ret = false;
} else {
addons.put(addon, true);
ret = true;
}
updateAddons(id, Land.writeAddonTags(addons));
return ret;
}
public boolean updatePerms(int id, String permString) {
return landDB.updateLandPerms(id, permString);
}
public boolean modifyPermTags(int id, String args) {
- HashMap<String, Boolean> perms = Land.parseAddonTags(iCoLand.landMgr.getPerms(id));
+ HashMap<String, Boolean> perms = Land.parsePermTags(iCoLand.landMgr.getPerms(id));
if ( args.isEmpty() ) return false;
String[] split = args.split(" ");
for(String tag : split ) {
String[] keys = tag.split(":");
if ( keys.length == 2 ) {
if ( keys[1].equals("-") ) {
perms.remove(keys[0]);
} else if ( keys[1].startsWith("f") ) {
perms.put(keys[0], false);
} else if ( keys[1].startsWith("t") ) {
perms.put(keys[0], true);
} else {
iCoLand.warning("Error parsing tag: "+tag);
}
} else {
iCoLand.warning("Error parsing tag: "+tag);
}
}
return updatePerms(id, Land.writePermTags(perms));
}
public void modifyBuildDestroyWithTags(String tagString) {
}
public String getAddons(int id) {
return landDB.getLandAddons(id);
}
public String getPerms(int id) {
return landDB.getLandPerms(id);
}
public String getOwner(int id) {
return landDB.getLandOwner(id);
}
public void test() {
long start = System.currentTimeMillis();
int numLands = 10000;
for(int i=0;i<numLands;i++) {
Location loc1 = new Location(iCoLand.server.getWorlds().get(0), rand(-10000,10000), 8, rand(-10000,10000));
Location loc2 = new Location(iCoLand.server.getWorlds().get(0), loc1.getBlockX()+rand(0,100), loc1.getBlockY()+rand(0,120), loc1.getBlockZ()+rand(0,100));
iCoLand.landMgr.addLand(new Cuboid(loc1,loc2), "kigam", "", "");
if ( i % 100 == 0 ) {
if ( Config.debugMode ) iCoLand.info(landDB.countLandOwnedBy(null)+" lands in the database");
}
}
if ( Config.debugMode ) iCoLand.info("Inserting "+numLands+" random lands took: "+(System.currentTimeMillis()-start)+" ms");
if ( Config.debugMode ) iCoLand.info(landDB.countLandOwnedBy(null)+" lands in the database");
}
public int rand(int lo, int hi) {
int n = hi - lo + 1;
int i = rn.nextInt() % n;
if ( i < 0 )
i = -i;
return lo+i;
}
}
| true | true | public boolean modifyPermTags(int id, String args) {
HashMap<String, Boolean> perms = Land.parseAddonTags(iCoLand.landMgr.getPerms(id));
if ( args.isEmpty() ) return false;
String[] split = args.split(" ");
for(String tag : split ) {
String[] keys = tag.split(":");
if ( keys.length == 2 ) {
if ( keys[1].equals("-") ) {
perms.remove(keys[0]);
} else if ( keys[1].startsWith("f") ) {
perms.put(keys[0], false);
} else if ( keys[1].startsWith("t") ) {
perms.put(keys[0], true);
} else {
iCoLand.warning("Error parsing tag: "+tag);
}
} else {
iCoLand.warning("Error parsing tag: "+tag);
}
}
return updatePerms(id, Land.writePermTags(perms));
}
| public boolean modifyPermTags(int id, String args) {
HashMap<String, Boolean> perms = Land.parsePermTags(iCoLand.landMgr.getPerms(id));
if ( args.isEmpty() ) return false;
String[] split = args.split(" ");
for(String tag : split ) {
String[] keys = tag.split(":");
if ( keys.length == 2 ) {
if ( keys[1].equals("-") ) {
perms.remove(keys[0]);
} else if ( keys[1].startsWith("f") ) {
perms.put(keys[0], false);
} else if ( keys[1].startsWith("t") ) {
perms.put(keys[0], true);
} else {
iCoLand.warning("Error parsing tag: "+tag);
}
} else {
iCoLand.warning("Error parsing tag: "+tag);
}
}
return updatePerms(id, Land.writePermTags(perms));
}
|
diff --git a/src/com/dmdirc/parser/irc/ProcessListModes.java b/src/com/dmdirc/parser/irc/ProcessListModes.java
index b3d94a00f..2a2406467 100644
--- a/src/com/dmdirc/parser/irc/ProcessListModes.java
+++ b/src/com/dmdirc/parser/irc/ProcessListModes.java
@@ -1,220 +1,227 @@
/*
* Copyright (c) 2006-2009 Chris Smith, Shane Mc Cormack, Gregory Holmes
*
* 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.dmdirc.parser.irc;
import java.util.List;
import java.util.LinkedList;
import java.util.Queue;
/**
* Process a List Modes.
*/
public class ProcessListModes extends IRCProcessor {
/**
* Process a ListModes.
*
* @param sParam Type of line to process
* @param token IRCTokenised line to process
*/
@SuppressWarnings("unchecked")
@Override
public void process(String sParam, String[] token) {
ChannelInfo channel = getChannelInfo(token[3]);
String thisIRCD = myParser.getIRCD(true).toLowerCase();
String item = "";
String owner = "";
byte tokenStart = 4; // Where do the relevent tokens start?
boolean isCleverMode = false;
long time = 0;
char mode = 'b';
boolean isItem = true; // true if item listing, false if "end of .." item
if (channel == null) { return; }
if (sParam.equals("367") || sParam.equals("368")) {
// Ban List/Item.
// (Also used for +d and +q on hyperion... -_-)
mode = 'b';
isItem = sParam.equals("367");
} else if (sParam.equals("348") || sParam.equals("349")) {
// Except / Exempt List etc
mode = 'e';
isItem = sParam.equals("348");
} else if (sParam.equals("346") || sParam.equals("347")) {
// Invite List
mode = 'I';
isItem = sParam.equals("346");
} else if (sParam.equals("940") || sParam.equals("941")) {
// Censored words List
mode = 'g';
isItem = sParam.equals("941");
} else if (sParam.equals("344") || sParam.equals("345")) {
// Reop List, or bad words list, or quiet list. god damn.
if (thisIRCD.equals("euircd")) {
mode = 'w';
} else if (thisIRCD.equals("oftc-hybrid")) {
mode = 'q';
} else {
mode = 'R';
}
isItem = sParam.equals("344");
} else if (thisIRCD.equals("swiftirc") && (sParam.equals("386") || sParam.equals("387"))) {
// Channel Owner list
mode = 'q';
isItem = sParam.equals("387");
} else if (thisIRCD.equals("swiftirc") && (sParam.equals("388") || sParam.equals("389"))) {
// Protected User list
mode = 'a';
isItem = sParam.equals("389");
} else if (sParam.equals(myParser.h005Info.get("LISTMODE")) || sParam.equals(myParser.h005Info.get("LISTMODEEND"))) {
// Support for potential future decent mode listing in the protocol
//
// See my proposal: http://shane.dmdirc.com/listmodes.php
mode = token[4].charAt(0);
isItem = sParam.equals(myParser.h005Info.get("LISTMODE"));
tokenStart = 5;
isCleverMode = true;
}
final Queue<Character> listModeQueue = channel.getListModeQueue();
if (!isCleverMode && listModeQueue != null) {
if (sParam.equals("482")) {
myParser.callDebugInfo(IRCParser.DEBUG_LMQ, "Dropped LMQ mode "+listModeQueue.poll());
return;
} else {
if (listModeQueue.peek() != null) {
Character oldMode = mode;
mode = listModeQueue.peek();
myParser.callDebugInfo(IRCParser.DEBUG_LMQ, "LMQ says this is "+mode);
boolean error = true;
- if ((thisIRCD.equals("hyperion") || thisIRCD.equals("dancer")) && (mode == 'b' || mode == 'q')) {
+ // b or q are given in the same list, d is separate.
+ // b and q remove each other from the LMQ.
+ //
+ // Only raise an LMQ error if the lmqmode isn't one of bdq if the
+ // guess is one of bdq
+ if ((thisIRCD.equals("hyperion") || thisIRCD.equals("dancer")) && (mode == 'b' || mode == 'q' || mode == 'd')) {
LinkedList<Character> lmq = (LinkedList<Character>)listModeQueue;
if (mode == 'b') {
- error = !(oldMode == 'q');
+ error = !(oldMode == 'q' || oldMode == 'd');
lmq.remove((Character)'q');
myParser.callDebugInfo(IRCParser.DEBUG_LMQ, "Dropping q from list");
} else if (mode == 'q') {
- error = !(oldMode == 'b');
+ error = !(oldMode == 'b' || oldMode == 'd');
lmq.remove((Character)'b');
myParser.callDebugInfo(IRCParser.DEBUG_LMQ, "Dropping b from list");
+ } else if (mode == 'd') {
+ error = !(oldMode == 'b' || oldMode == 'q');
}
}
if (oldMode != mode && error) {
myParser.callDebugInfo(IRCParser.DEBUG_LMQ, "LMQ disagrees with guess. LMQ: "+mode+" Guess: "+oldMode);
myParser.callErrorInfo(new ParserError(ParserError.ERROR_WARNING, "LMQ disagrees with guess. LMQ: "+mode+" Guess: "+oldMode, myParser.getLastLine()));
}
if (!isItem) {
listModeQueue.poll();
}
}
}
}
if (isItem) {
if ((!isCleverMode) && listModeQueue == null && (thisIRCD.equals("hyperion") || thisIRCD.equals("dancer")) && token.length > 4 && mode == 'b') {
// Assume mode is a 'd' mode
mode = 'd';
// Now work out if its not (or attempt to.)
int identstart = token[tokenStart].indexOf('!');
int hoststart = token[tokenStart].indexOf('@');
// Check that ! and @ are both in the string - as required by +b and +q
if ((identstart >= 0) && (identstart < hoststart)) {
if (thisIRCD.equals("hyperion") && token[tokenStart].charAt(0) == '%') { mode = 'q'; }
else { mode = 'b'; }
}
} // End Hyperian stupidness of using the same numeric for 3 different things..
if (!channel.getAddState(mode)) {
callDebugInfo(IRCParser.DEBUG_INFO, "New List Mode Batch ("+mode+"): Clearing!");
final List<ChannelListModeItem> list = channel.getListModeParam(mode);
if (list == null) {
myParser.callErrorInfo(new ParserError(ParserError.ERROR_WARNING, "Got list mode: '"+mode+"' - but channel object doesn't agree.", myParser.getLastLine()));
} else {
list.clear();
}
channel.setAddState(mode, true);
}
if (token.length > (tokenStart+2)) {
try { time = Long.parseLong(token[tokenStart+2]); } catch (NumberFormatException e) { time = 0; }
}
if (token.length > (tokenStart+1)) { owner = token[tokenStart+1]; }
if (token.length > tokenStart) { item = token[tokenStart]; }
if (!item.isEmpty()) {
ChannelListModeItem clmi = new ChannelListModeItem(item, owner, time);
callDebugInfo(IRCParser.DEBUG_INFO, "List Mode: %c [%s/%s/%d]",mode, item, owner, time);
channel.setListModeParam(mode, clmi, true);
}
} else {
callDebugInfo(IRCParser.DEBUG_INFO, "List Mode Batch over");
channel.resetAddState();
if (isCleverMode || listModeQueue == null || ((LinkedList<Character>)listModeQueue).size() == 0) {
callDebugInfo(IRCParser.DEBUG_INFO, "Calling GotListModes");
channel.setHasGotListModes(true);
callChannelGotListModes(channel);
}
}
}
/**
* What does this IRCProcessor handle.
*
* @return String[] with the names of the tokens we handle.
*/
@Override
public String[] handles() {
return new String[]{"367", "368", /* Bans */
"344", "345", /* Reop list (ircnet) or bad words (euirc) */
"346", "347", /* Invite List */
"348", "349", /* Except/Exempt List */
"386", "387", /* Channel Owner List (swiftirc ) */
"388", "389", /* Protected User List (swiftirc) */
"940", "941", /* Censored words list */
"482", /* Permission Denied */
"__LISTMODE__" /* Sensible List Modes */
};
}
/**
* Callback to all objects implementing the ChannelGotListModes Callback.
*
* @see IChannelGotListModes
* @param cChannel Channel which the ListModes reply is for
* @return true if a method was called, false otherwise
*/
protected boolean callChannelGotListModes(ChannelInfo cChannel) {
return getCallbackManager().getCallbackType("OnChannelGotListModes").call(cChannel);
}
/**
* Create a new instance of the IRCProcessor Object.
*
* @param parser IRCParser That owns this IRCProcessor
* @param manager ProcessingManager that is in charge of this IRCProcessor
*/
protected ProcessListModes (IRCParser parser, ProcessingManager manager) { super(parser, manager); }
}
| false | true | public void process(String sParam, String[] token) {
ChannelInfo channel = getChannelInfo(token[3]);
String thisIRCD = myParser.getIRCD(true).toLowerCase();
String item = "";
String owner = "";
byte tokenStart = 4; // Where do the relevent tokens start?
boolean isCleverMode = false;
long time = 0;
char mode = 'b';
boolean isItem = true; // true if item listing, false if "end of .." item
if (channel == null) { return; }
if (sParam.equals("367") || sParam.equals("368")) {
// Ban List/Item.
// (Also used for +d and +q on hyperion... -_-)
mode = 'b';
isItem = sParam.equals("367");
} else if (sParam.equals("348") || sParam.equals("349")) {
// Except / Exempt List etc
mode = 'e';
isItem = sParam.equals("348");
} else if (sParam.equals("346") || sParam.equals("347")) {
// Invite List
mode = 'I';
isItem = sParam.equals("346");
} else if (sParam.equals("940") || sParam.equals("941")) {
// Censored words List
mode = 'g';
isItem = sParam.equals("941");
} else if (sParam.equals("344") || sParam.equals("345")) {
// Reop List, or bad words list, or quiet list. god damn.
if (thisIRCD.equals("euircd")) {
mode = 'w';
} else if (thisIRCD.equals("oftc-hybrid")) {
mode = 'q';
} else {
mode = 'R';
}
isItem = sParam.equals("344");
} else if (thisIRCD.equals("swiftirc") && (sParam.equals("386") || sParam.equals("387"))) {
// Channel Owner list
mode = 'q';
isItem = sParam.equals("387");
} else if (thisIRCD.equals("swiftirc") && (sParam.equals("388") || sParam.equals("389"))) {
// Protected User list
mode = 'a';
isItem = sParam.equals("389");
} else if (sParam.equals(myParser.h005Info.get("LISTMODE")) || sParam.equals(myParser.h005Info.get("LISTMODEEND"))) {
// Support for potential future decent mode listing in the protocol
//
// See my proposal: http://shane.dmdirc.com/listmodes.php
mode = token[4].charAt(0);
isItem = sParam.equals(myParser.h005Info.get("LISTMODE"));
tokenStart = 5;
isCleverMode = true;
}
final Queue<Character> listModeQueue = channel.getListModeQueue();
if (!isCleverMode && listModeQueue != null) {
if (sParam.equals("482")) {
myParser.callDebugInfo(IRCParser.DEBUG_LMQ, "Dropped LMQ mode "+listModeQueue.poll());
return;
} else {
if (listModeQueue.peek() != null) {
Character oldMode = mode;
mode = listModeQueue.peek();
myParser.callDebugInfo(IRCParser.DEBUG_LMQ, "LMQ says this is "+mode);
boolean error = true;
if ((thisIRCD.equals("hyperion") || thisIRCD.equals("dancer")) && (mode == 'b' || mode == 'q')) {
LinkedList<Character> lmq = (LinkedList<Character>)listModeQueue;
if (mode == 'b') {
error = !(oldMode == 'q');
lmq.remove((Character)'q');
myParser.callDebugInfo(IRCParser.DEBUG_LMQ, "Dropping q from list");
} else if (mode == 'q') {
error = !(oldMode == 'b');
lmq.remove((Character)'b');
myParser.callDebugInfo(IRCParser.DEBUG_LMQ, "Dropping b from list");
}
}
if (oldMode != mode && error) {
myParser.callDebugInfo(IRCParser.DEBUG_LMQ, "LMQ disagrees with guess. LMQ: "+mode+" Guess: "+oldMode);
myParser.callErrorInfo(new ParserError(ParserError.ERROR_WARNING, "LMQ disagrees with guess. LMQ: "+mode+" Guess: "+oldMode, myParser.getLastLine()));
}
if (!isItem) {
listModeQueue.poll();
}
}
}
}
if (isItem) {
if ((!isCleverMode) && listModeQueue == null && (thisIRCD.equals("hyperion") || thisIRCD.equals("dancer")) && token.length > 4 && mode == 'b') {
// Assume mode is a 'd' mode
mode = 'd';
// Now work out if its not (or attempt to.)
int identstart = token[tokenStart].indexOf('!');
int hoststart = token[tokenStart].indexOf('@');
// Check that ! and @ are both in the string - as required by +b and +q
if ((identstart >= 0) && (identstart < hoststart)) {
if (thisIRCD.equals("hyperion") && token[tokenStart].charAt(0) == '%') { mode = 'q'; }
else { mode = 'b'; }
}
} // End Hyperian stupidness of using the same numeric for 3 different things..
if (!channel.getAddState(mode)) {
callDebugInfo(IRCParser.DEBUG_INFO, "New List Mode Batch ("+mode+"): Clearing!");
final List<ChannelListModeItem> list = channel.getListModeParam(mode);
if (list == null) {
myParser.callErrorInfo(new ParserError(ParserError.ERROR_WARNING, "Got list mode: '"+mode+"' - but channel object doesn't agree.", myParser.getLastLine()));
} else {
list.clear();
}
channel.setAddState(mode, true);
}
if (token.length > (tokenStart+2)) {
try { time = Long.parseLong(token[tokenStart+2]); } catch (NumberFormatException e) { time = 0; }
}
if (token.length > (tokenStart+1)) { owner = token[tokenStart+1]; }
if (token.length > tokenStart) { item = token[tokenStart]; }
if (!item.isEmpty()) {
ChannelListModeItem clmi = new ChannelListModeItem(item, owner, time);
callDebugInfo(IRCParser.DEBUG_INFO, "List Mode: %c [%s/%s/%d]",mode, item, owner, time);
channel.setListModeParam(mode, clmi, true);
}
} else {
| public void process(String sParam, String[] token) {
ChannelInfo channel = getChannelInfo(token[3]);
String thisIRCD = myParser.getIRCD(true).toLowerCase();
String item = "";
String owner = "";
byte tokenStart = 4; // Where do the relevent tokens start?
boolean isCleverMode = false;
long time = 0;
char mode = 'b';
boolean isItem = true; // true if item listing, false if "end of .." item
if (channel == null) { return; }
if (sParam.equals("367") || sParam.equals("368")) {
// Ban List/Item.
// (Also used for +d and +q on hyperion... -_-)
mode = 'b';
isItem = sParam.equals("367");
} else if (sParam.equals("348") || sParam.equals("349")) {
// Except / Exempt List etc
mode = 'e';
isItem = sParam.equals("348");
} else if (sParam.equals("346") || sParam.equals("347")) {
// Invite List
mode = 'I';
isItem = sParam.equals("346");
} else if (sParam.equals("940") || sParam.equals("941")) {
// Censored words List
mode = 'g';
isItem = sParam.equals("941");
} else if (sParam.equals("344") || sParam.equals("345")) {
// Reop List, or bad words list, or quiet list. god damn.
if (thisIRCD.equals("euircd")) {
mode = 'w';
} else if (thisIRCD.equals("oftc-hybrid")) {
mode = 'q';
} else {
mode = 'R';
}
isItem = sParam.equals("344");
} else if (thisIRCD.equals("swiftirc") && (sParam.equals("386") || sParam.equals("387"))) {
// Channel Owner list
mode = 'q';
isItem = sParam.equals("387");
} else if (thisIRCD.equals("swiftirc") && (sParam.equals("388") || sParam.equals("389"))) {
// Protected User list
mode = 'a';
isItem = sParam.equals("389");
} else if (sParam.equals(myParser.h005Info.get("LISTMODE")) || sParam.equals(myParser.h005Info.get("LISTMODEEND"))) {
// Support for potential future decent mode listing in the protocol
//
// See my proposal: http://shane.dmdirc.com/listmodes.php
mode = token[4].charAt(0);
isItem = sParam.equals(myParser.h005Info.get("LISTMODE"));
tokenStart = 5;
isCleverMode = true;
}
final Queue<Character> listModeQueue = channel.getListModeQueue();
if (!isCleverMode && listModeQueue != null) {
if (sParam.equals("482")) {
myParser.callDebugInfo(IRCParser.DEBUG_LMQ, "Dropped LMQ mode "+listModeQueue.poll());
return;
} else {
if (listModeQueue.peek() != null) {
Character oldMode = mode;
mode = listModeQueue.peek();
myParser.callDebugInfo(IRCParser.DEBUG_LMQ, "LMQ says this is "+mode);
boolean error = true;
// b or q are given in the same list, d is separate.
// b and q remove each other from the LMQ.
//
// Only raise an LMQ error if the lmqmode isn't one of bdq if the
// guess is one of bdq
if ((thisIRCD.equals("hyperion") || thisIRCD.equals("dancer")) && (mode == 'b' || mode == 'q' || mode == 'd')) {
LinkedList<Character> lmq = (LinkedList<Character>)listModeQueue;
if (mode == 'b') {
error = !(oldMode == 'q' || oldMode == 'd');
lmq.remove((Character)'q');
myParser.callDebugInfo(IRCParser.DEBUG_LMQ, "Dropping q from list");
} else if (mode == 'q') {
error = !(oldMode == 'b' || oldMode == 'd');
lmq.remove((Character)'b');
myParser.callDebugInfo(IRCParser.DEBUG_LMQ, "Dropping b from list");
} else if (mode == 'd') {
error = !(oldMode == 'b' || oldMode == 'q');
}
}
if (oldMode != mode && error) {
myParser.callDebugInfo(IRCParser.DEBUG_LMQ, "LMQ disagrees with guess. LMQ: "+mode+" Guess: "+oldMode);
myParser.callErrorInfo(new ParserError(ParserError.ERROR_WARNING, "LMQ disagrees with guess. LMQ: "+mode+" Guess: "+oldMode, myParser.getLastLine()));
}
if (!isItem) {
listModeQueue.poll();
}
}
}
}
if (isItem) {
if ((!isCleverMode) && listModeQueue == null && (thisIRCD.equals("hyperion") || thisIRCD.equals("dancer")) && token.length > 4 && mode == 'b') {
// Assume mode is a 'd' mode
mode = 'd';
// Now work out if its not (or attempt to.)
int identstart = token[tokenStart].indexOf('!');
int hoststart = token[tokenStart].indexOf('@');
// Check that ! and @ are both in the string - as required by +b and +q
if ((identstart >= 0) && (identstart < hoststart)) {
if (thisIRCD.equals("hyperion") && token[tokenStart].charAt(0) == '%') { mode = 'q'; }
else { mode = 'b'; }
}
} // End Hyperian stupidness of using the same numeric for 3 different things..
if (!channel.getAddState(mode)) {
callDebugInfo(IRCParser.DEBUG_INFO, "New List Mode Batch ("+mode+"): Clearing!");
final List<ChannelListModeItem> list = channel.getListModeParam(mode);
if (list == null) {
myParser.callErrorInfo(new ParserError(ParserError.ERROR_WARNING, "Got list mode: '"+mode+"' - but channel object doesn't agree.", myParser.getLastLine()));
} else {
list.clear();
}
channel.setAddState(mode, true);
}
if (token.length > (tokenStart+2)) {
try { time = Long.parseLong(token[tokenStart+2]); } catch (NumberFormatException e) { time = 0; }
}
if (token.length > (tokenStart+1)) { owner = token[tokenStart+1]; }
if (token.length > tokenStart) { item = token[tokenStart]; }
if (!item.isEmpty()) {
ChannelListModeItem clmi = new ChannelListModeItem(item, owner, time);
callDebugInfo(IRCParser.DEBUG_INFO, "List Mode: %c [%s/%s/%d]",mode, item, owner, time);
channel.setListModeParam(mode, clmi, true);
}
} else {
|
diff --git a/activiti-engine/src/main/java/org/activiti/engine/impl/bpmn/deployer/BpmnDeployer.java b/activiti-engine/src/main/java/org/activiti/engine/impl/bpmn/deployer/BpmnDeployer.java
index 657504e72..2ef617a15 100644
--- a/activiti-engine/src/main/java/org/activiti/engine/impl/bpmn/deployer/BpmnDeployer.java
+++ b/activiti-engine/src/main/java/org/activiti/engine/impl/bpmn/deployer/BpmnDeployer.java
@@ -1,343 +1,338 @@
/* 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.activiti.engine.impl.bpmn.deployer;
import java.awt.GraphicsEnvironment;
import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.activiti.engine.ActivitiException;
import org.activiti.engine.impl.bpmn.diagram.ProcessDiagramGenerator;
import org.activiti.engine.impl.bpmn.parser.BpmnParse;
import org.activiti.engine.impl.bpmn.parser.BpmnParser;
import org.activiti.engine.impl.bpmn.parser.MessageEventDefinition;
import org.activiti.engine.impl.cfg.IdGenerator;
import org.activiti.engine.impl.cmd.DeleteJobsCmd;
import org.activiti.engine.impl.context.Context;
import org.activiti.engine.impl.db.DbSqlSession;
import org.activiti.engine.impl.el.ExpressionManager;
import org.activiti.engine.impl.event.MessageEventHandler;
import org.activiti.engine.impl.interceptor.CommandContext;
import org.activiti.engine.impl.jobexecutor.TimerDeclarationImpl;
import org.activiti.engine.impl.jobexecutor.TimerStartEventJobHandler;
import org.activiti.engine.impl.persistence.deploy.Deployer;
import org.activiti.engine.impl.persistence.deploy.DeploymentCache;
import org.activiti.engine.impl.persistence.entity.DeploymentEntity;
import org.activiti.engine.impl.persistence.entity.EventSubscriptionEntity;
import org.activiti.engine.impl.persistence.entity.MessageEventSubscriptionEntity;
import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.activiti.engine.impl.persistence.entity.ProcessDefinitionManager;
import org.activiti.engine.impl.persistence.entity.ResourceEntity;
import org.activiti.engine.impl.persistence.entity.TimerEntity;
import org.activiti.engine.impl.util.IoUtil;
import org.activiti.engine.runtime.Job;
/**
* @author Tom Baeyens
* @author Joram Barrez
*/
public class BpmnDeployer implements Deployer {
private static final Logger LOG = Logger.getLogger(BpmnDeployer.class.getName());;
public static final String[] BPMN_RESOURCE_SUFFIXES = new String[] { "bpmn20.xml", "bpmn" };
public static final String[] DIAGRAM_SUFFIXES = new String[]{"png", "jpg", "gif", "svg"};
protected ExpressionManager expressionManager;
protected BpmnParser bpmnParser;
protected IdGenerator idGenerator;
public void deploy(DeploymentEntity deployment) {
List<ProcessDefinitionEntity> processDefinitions = new ArrayList<ProcessDefinitionEntity>();
Map<String, ResourceEntity> resources = deployment.getResources();
for (String resourceName : resources.keySet()) {
LOG.info("Processing resource " + resourceName);
if (isBpmnResource(resourceName)) {
ResourceEntity resource = resources.get(resourceName);
byte[] bytes = resource.getBytes();
ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
BpmnParse bpmnParse = bpmnParser
.createParse()
.sourceInputStream(inputStream)
.deployment(deployment)
.name(resourceName);
if (!deployment.isValidatingSchema()) {
bpmnParse.setSchemaResource(null);
}
bpmnParse.execute();
for (ProcessDefinitionEntity processDefinition: bpmnParse.getProcessDefinitions()) {
processDefinition.setResourceName(resourceName);
String diagramResourceName = getDiagramResourceForProcess(resourceName, processDefinition.getKey(), resources);
if (diagramResourceName==null && processDefinition.isGraphicalNotationDefined()) {
try {
- GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
- if(!ge.isHeadlessInstance()) {
- byte[] diagramBytes = IoUtil.readInputStream(ProcessDiagramGenerator.generatePngDiagram(processDefinition), null);
- diagramResourceName = getProcessImageResourceName(resourceName, processDefinition.getKey(), "png");
- createResource(diagramResourceName, diagramBytes, deployment);
- } else {
- LOG.log(Level.WARNING, "Cannot generate process diagram while running in AWT headless-mode");
- }
+ byte[] diagramBytes = IoUtil.readInputStream(ProcessDiagramGenerator.generatePngDiagram(processDefinition), null);
+ diagramResourceName = getProcessImageResourceName(resourceName, processDefinition.getKey(), "png");
+ createResource(diagramResourceName, diagramBytes, deployment);
} catch (Throwable t) { // if anything goes wrong, we don't store the image (the process will still be executable).
LOG.log(Level.WARNING, "Error while generating process diagram, image will not be stored in repository", t);
}
}
processDefinition.setDiagramResourceName(diagramResourceName);
processDefinitions.add(processDefinition);
}
}
}
CommandContext commandContext = Context.getCommandContext();
ProcessDefinitionManager processDefinitionManager = commandContext.getProcessDefinitionManager();
DeploymentCache deploymentCache = Context.getProcessEngineConfiguration().getDeploymentCache();
DbSqlSession dbSqlSession = commandContext.getSession(DbSqlSession.class);
for (ProcessDefinitionEntity processDefinition : processDefinitions) {
if (deployment.isNew()) {
int processDefinitionVersion;
ProcessDefinitionEntity latestProcessDefinition = processDefinitionManager.findLatestProcessDefinitionByKey(processDefinition.getKey());
if (latestProcessDefinition != null) {
processDefinitionVersion = latestProcessDefinition.getVersion() + 1;
} else {
processDefinitionVersion = 1;
}
processDefinition.setVersion(processDefinitionVersion);
processDefinition.setDeploymentId(deployment.getId());
String nextId = idGenerator.getNextId();
String processDefinitionId = processDefinition.getKey()
+ ":" + processDefinition.getVersion()
+ ":" + nextId; // ACT-505
// ACT-115: maximum id length is 64 charcaters
if (processDefinitionId.length() > 64) {
processDefinitionId = nextId;
}
processDefinition.setId(processDefinitionId);
removeObsoleteTimers(processDefinition);
addTimerDeclarations(processDefinition);
removeObsoleteMessageEventSubscriptions(processDefinition, latestProcessDefinition);
addMessageEventSubscriptions(processDefinition);
dbSqlSession.insert(processDefinition);
deploymentCache.addProcessDefinition(processDefinition);
} else {
String deploymentId = deployment.getId();
processDefinition.setDeploymentId(deploymentId);
ProcessDefinitionEntity persistedProcessDefinition = processDefinitionManager.findProcessDefinitionByDeploymentAndKey(deploymentId, processDefinition.getKey());
processDefinition.setId(persistedProcessDefinition.getId());
processDefinition.setVersion(persistedProcessDefinition.getVersion());
deploymentCache.addProcessDefinition(processDefinition);
}
Context
.getProcessEngineConfiguration()
.getDeploymentCache()
.addProcessDefinition(processDefinition);
}
}
@SuppressWarnings("unchecked")
private void addTimerDeclarations(ProcessDefinitionEntity processDefinition) {
List<TimerDeclarationImpl> timerDeclarations = (List<TimerDeclarationImpl>) processDefinition.getProperty(BpmnParse.PROPERTYNAME_START_TIMER);
if (timerDeclarations!=null) {
for (TimerDeclarationImpl timerDeclaration : timerDeclarations) {
TimerEntity timer = timerDeclaration.prepareTimerEntity(null);
Context
.getCommandContext()
.getJobManager()
.schedule(timer);
}
}
}
private void removeObsoleteTimers(ProcessDefinitionEntity processDefinition) {
List<Job> jobsToDelete = Context
.getCommandContext()
.getJobManager()
.findJobsByConfiguration(TimerStartEventJobHandler.TYPE, processDefinition.getKey());
for (Job job :jobsToDelete) {
new DeleteJobsCmd(job.getId()).execute(Context.getCommandContext());
}
}
protected void removeObsoleteMessageEventSubscriptions(ProcessDefinitionEntity processDefinition, ProcessDefinitionEntity latestProcessDefinition) {
// remove all subscriptions for the previous version
if(latestProcessDefinition != null) {
CommandContext commandContext = Context.getCommandContext();
List<EventSubscriptionEntity> subscriptionsToDelete = commandContext
.getEventSubscriptionManager()
.findEventSubscriptionsByConfiguration(MessageEventHandler.TYPE, latestProcessDefinition.getId());
for (EventSubscriptionEntity eventSubscriptionEntity : subscriptionsToDelete) {
eventSubscriptionEntity.delete();
}
}
}
@SuppressWarnings("unchecked")
protected void addMessageEventSubscriptions(ProcessDefinitionEntity processDefinition) {
CommandContext commandContext = Context.getCommandContext();
List<MessageEventDefinition> messageEventDefinitions = (List<MessageEventDefinition>) processDefinition.getProperty(BpmnParse.PROPERTYNAME_MESSAGE_EVENT_DEFINITIONS);
if(messageEventDefinitions != null) {
for (MessageEventDefinition messageEventDefinition : messageEventDefinitions) {
if(messageEventDefinition.isStartEvent()) {
// look for subscriptions for the same name in db:
List<EventSubscriptionEntity> subscriptionsForSameMessageName = commandContext
.getEventSubscriptionManager()
.findEventSubscriptionByName(MessageEventHandler.TYPE, messageEventDefinition.getName());
// also look for subscriptions created in the session:
List<MessageEventSubscriptionEntity> cachedSubscriptions = commandContext
.getDbSqlSession()
.findInCache(MessageEventSubscriptionEntity.class);
for (MessageEventSubscriptionEntity cachedSubscription : cachedSubscriptions) {
if(messageEventDefinition.getName().equals(cachedSubscription.getEventName())
&& !subscriptionsForSameMessageName.contains(cachedSubscription)) {
subscriptionsForSameMessageName.add(cachedSubscription);
}
}
// remove subscriptions deleted in the same command
subscriptionsForSameMessageName = commandContext
.getDbSqlSession()
.pruneDeletedEntities(subscriptionsForSameMessageName);
if(!subscriptionsForSameMessageName.isEmpty()) {
throw new ActivitiException("Cannot deploy process definition '" + processDefinition.getResourceName()
+ "': there already is a message event subscription for the message with name '" + messageEventDefinition.getName() + "'.");
}
MessageEventSubscriptionEntity newSubscription = new MessageEventSubscriptionEntity();
newSubscription.setEventName(messageEventDefinition.getName());
newSubscription.setActivityId(messageEventDefinition.getActivityId());
newSubscription.setConfiguration(processDefinition.getId());
newSubscription.insert();
}
}
}
}
/**
* Returns the default name of the image resource for a certain process.
*
* It will first look for an image resource which matches the process
* specifically, before resorting to an image resource which matches the BPMN
* 2.0 xml file resource.
*
* Example: if the deployment contains a BPMN 2.0 xml resource called
* 'abc.bpmn20.xml' containing only one process with key 'myProcess', then
* this method will look for an image resources called 'abc.myProcess.png'
* (or .jpg, or .gif, etc.) or 'abc.png' if the previous one wasn't found.
*
* Example 2: if the deployment contains a BPMN 2.0 xml resource called
* 'abc.bpmn20.xml' containing three processes (with keys a, b and c),
* then this method will first look for an image resource called 'abc.a.png'
* before looking for 'abc.png' (likewise for b and c).
* Note that if abc.a.png, abc.b.png and abc.c.png don't exist, all
* processes will have the same image: abc.png.
*
* @return null if no matching image resource is found.
*/
protected String getDiagramResourceForProcess(String bpmnFileResource, String processKey, Map<String, ResourceEntity> resources) {
for (String diagramSuffix: DIAGRAM_SUFFIXES) {
String diagramForBpmnFileResource = getBpmnFileImageResourceName(bpmnFileResource, diagramSuffix);
String processDiagramResource = getProcessImageResourceName(bpmnFileResource, processKey, diagramSuffix);
if (resources.containsKey(processDiagramResource)) {
return processDiagramResource;
} else if (resources.containsKey(diagramForBpmnFileResource)) {
return diagramForBpmnFileResource;
}
}
return null;
}
protected String getBpmnFileImageResourceName(String bpmnFileResource, String diagramSuffix) {
String bpmnFileResourceBase = bpmnFileResource.substring(0, bpmnFileResource.length()-10); // minus 10 to remove 'bpmn20.xml'
return bpmnFileResourceBase + diagramSuffix;
}
protected String getProcessImageResourceName(String bpmnFileResource, String processKey, String diagramSuffix) {
String bpmnFileResourceBase = bpmnFileResource.substring(0, bpmnFileResource.length()-10); // minus 10 to remove 'bpmn20.xml'
return bpmnFileResourceBase + processKey + "." + diagramSuffix;
}
protected void createResource(String name, byte[] bytes, DeploymentEntity deploymentEntity) {
ResourceEntity resource = new ResourceEntity();
resource.setName(name);
resource.setBytes(bytes);
resource.setDeploymentId(deploymentEntity.getId());
// Mark the resource as 'generated'
resource.setGenerated(true);
Context
.getCommandContext()
.getDbSqlSession()
.insert(resource);
}
protected boolean isBpmnResource(String resourceName) {
for (String suffix : BPMN_RESOURCE_SUFFIXES) {
if (resourceName.endsWith(suffix)) {
return true;
}
}
return false;
}
public ExpressionManager getExpressionManager() {
return expressionManager;
}
public void setExpressionManager(ExpressionManager expressionManager) {
this.expressionManager = expressionManager;
}
public BpmnParser getBpmnParser() {
return bpmnParser;
}
public void setBpmnParser(BpmnParser bpmnParser) {
this.bpmnParser = bpmnParser;
}
public IdGenerator getIdGenerator() {
return idGenerator;
}
public void setIdGenerator(IdGenerator idGenerator) {
this.idGenerator = idGenerator;
}
}
| true | true | public void deploy(DeploymentEntity deployment) {
List<ProcessDefinitionEntity> processDefinitions = new ArrayList<ProcessDefinitionEntity>();
Map<String, ResourceEntity> resources = deployment.getResources();
for (String resourceName : resources.keySet()) {
LOG.info("Processing resource " + resourceName);
if (isBpmnResource(resourceName)) {
ResourceEntity resource = resources.get(resourceName);
byte[] bytes = resource.getBytes();
ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
BpmnParse bpmnParse = bpmnParser
.createParse()
.sourceInputStream(inputStream)
.deployment(deployment)
.name(resourceName);
if (!deployment.isValidatingSchema()) {
bpmnParse.setSchemaResource(null);
}
bpmnParse.execute();
for (ProcessDefinitionEntity processDefinition: bpmnParse.getProcessDefinitions()) {
processDefinition.setResourceName(resourceName);
String diagramResourceName = getDiagramResourceForProcess(resourceName, processDefinition.getKey(), resources);
if (diagramResourceName==null && processDefinition.isGraphicalNotationDefined()) {
try {
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
if(!ge.isHeadlessInstance()) {
byte[] diagramBytes = IoUtil.readInputStream(ProcessDiagramGenerator.generatePngDiagram(processDefinition), null);
diagramResourceName = getProcessImageResourceName(resourceName, processDefinition.getKey(), "png");
createResource(diagramResourceName, diagramBytes, deployment);
} else {
LOG.log(Level.WARNING, "Cannot generate process diagram while running in AWT headless-mode");
}
} catch (Throwable t) { // if anything goes wrong, we don't store the image (the process will still be executable).
LOG.log(Level.WARNING, "Error while generating process diagram, image will not be stored in repository", t);
}
}
processDefinition.setDiagramResourceName(diagramResourceName);
processDefinitions.add(processDefinition);
}
}
}
CommandContext commandContext = Context.getCommandContext();
ProcessDefinitionManager processDefinitionManager = commandContext.getProcessDefinitionManager();
DeploymentCache deploymentCache = Context.getProcessEngineConfiguration().getDeploymentCache();
DbSqlSession dbSqlSession = commandContext.getSession(DbSqlSession.class);
for (ProcessDefinitionEntity processDefinition : processDefinitions) {
if (deployment.isNew()) {
int processDefinitionVersion;
ProcessDefinitionEntity latestProcessDefinition = processDefinitionManager.findLatestProcessDefinitionByKey(processDefinition.getKey());
if (latestProcessDefinition != null) {
processDefinitionVersion = latestProcessDefinition.getVersion() + 1;
} else {
processDefinitionVersion = 1;
}
processDefinition.setVersion(processDefinitionVersion);
processDefinition.setDeploymentId(deployment.getId());
String nextId = idGenerator.getNextId();
String processDefinitionId = processDefinition.getKey()
+ ":" + processDefinition.getVersion()
+ ":" + nextId; // ACT-505
// ACT-115: maximum id length is 64 charcaters
if (processDefinitionId.length() > 64) {
processDefinitionId = nextId;
}
processDefinition.setId(processDefinitionId);
removeObsoleteTimers(processDefinition);
addTimerDeclarations(processDefinition);
removeObsoleteMessageEventSubscriptions(processDefinition, latestProcessDefinition);
addMessageEventSubscriptions(processDefinition);
dbSqlSession.insert(processDefinition);
deploymentCache.addProcessDefinition(processDefinition);
} else {
String deploymentId = deployment.getId();
processDefinition.setDeploymentId(deploymentId);
ProcessDefinitionEntity persistedProcessDefinition = processDefinitionManager.findProcessDefinitionByDeploymentAndKey(deploymentId, processDefinition.getKey());
processDefinition.setId(persistedProcessDefinition.getId());
processDefinition.setVersion(persistedProcessDefinition.getVersion());
deploymentCache.addProcessDefinition(processDefinition);
}
Context
.getProcessEngineConfiguration()
.getDeploymentCache()
.addProcessDefinition(processDefinition);
}
}
| public void deploy(DeploymentEntity deployment) {
List<ProcessDefinitionEntity> processDefinitions = new ArrayList<ProcessDefinitionEntity>();
Map<String, ResourceEntity> resources = deployment.getResources();
for (String resourceName : resources.keySet()) {
LOG.info("Processing resource " + resourceName);
if (isBpmnResource(resourceName)) {
ResourceEntity resource = resources.get(resourceName);
byte[] bytes = resource.getBytes();
ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
BpmnParse bpmnParse = bpmnParser
.createParse()
.sourceInputStream(inputStream)
.deployment(deployment)
.name(resourceName);
if (!deployment.isValidatingSchema()) {
bpmnParse.setSchemaResource(null);
}
bpmnParse.execute();
for (ProcessDefinitionEntity processDefinition: bpmnParse.getProcessDefinitions()) {
processDefinition.setResourceName(resourceName);
String diagramResourceName = getDiagramResourceForProcess(resourceName, processDefinition.getKey(), resources);
if (diagramResourceName==null && processDefinition.isGraphicalNotationDefined()) {
try {
byte[] diagramBytes = IoUtil.readInputStream(ProcessDiagramGenerator.generatePngDiagram(processDefinition), null);
diagramResourceName = getProcessImageResourceName(resourceName, processDefinition.getKey(), "png");
createResource(diagramResourceName, diagramBytes, deployment);
} catch (Throwable t) { // if anything goes wrong, we don't store the image (the process will still be executable).
LOG.log(Level.WARNING, "Error while generating process diagram, image will not be stored in repository", t);
}
}
processDefinition.setDiagramResourceName(diagramResourceName);
processDefinitions.add(processDefinition);
}
}
}
CommandContext commandContext = Context.getCommandContext();
ProcessDefinitionManager processDefinitionManager = commandContext.getProcessDefinitionManager();
DeploymentCache deploymentCache = Context.getProcessEngineConfiguration().getDeploymentCache();
DbSqlSession dbSqlSession = commandContext.getSession(DbSqlSession.class);
for (ProcessDefinitionEntity processDefinition : processDefinitions) {
if (deployment.isNew()) {
int processDefinitionVersion;
ProcessDefinitionEntity latestProcessDefinition = processDefinitionManager.findLatestProcessDefinitionByKey(processDefinition.getKey());
if (latestProcessDefinition != null) {
processDefinitionVersion = latestProcessDefinition.getVersion() + 1;
} else {
processDefinitionVersion = 1;
}
processDefinition.setVersion(processDefinitionVersion);
processDefinition.setDeploymentId(deployment.getId());
String nextId = idGenerator.getNextId();
String processDefinitionId = processDefinition.getKey()
+ ":" + processDefinition.getVersion()
+ ":" + nextId; // ACT-505
// ACT-115: maximum id length is 64 charcaters
if (processDefinitionId.length() > 64) {
processDefinitionId = nextId;
}
processDefinition.setId(processDefinitionId);
removeObsoleteTimers(processDefinition);
addTimerDeclarations(processDefinition);
removeObsoleteMessageEventSubscriptions(processDefinition, latestProcessDefinition);
addMessageEventSubscriptions(processDefinition);
dbSqlSession.insert(processDefinition);
deploymentCache.addProcessDefinition(processDefinition);
} else {
String deploymentId = deployment.getId();
processDefinition.setDeploymentId(deploymentId);
ProcessDefinitionEntity persistedProcessDefinition = processDefinitionManager.findProcessDefinitionByDeploymentAndKey(deploymentId, processDefinition.getKey());
processDefinition.setId(persistedProcessDefinition.getId());
processDefinition.setVersion(persistedProcessDefinition.getVersion());
deploymentCache.addProcessDefinition(processDefinition);
}
Context
.getProcessEngineConfiguration()
.getDeploymentCache()
.addProcessDefinition(processDefinition);
}
}
|
diff --git a/run-all-junit-tests/testsrc/AllTests.java b/run-all-junit-tests/testsrc/AllTests.java
index 57ccf35bf..116812b20 100644
--- a/run-all-junit-tests/testsrc/AllTests.java
+++ b/run-all-junit-tests/testsrc/AllTests.java
@@ -1,60 +1,60 @@
/* *******************************************************************
* Copyright (c) 2003 Contributors.
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Common Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Wes Isberg initial implementation
* ******************************************************************/
// default package
import org.aspectj.util.LangUtil;
import org.aspectj.testing.util.TestUtil;
import junit.framework.TestCase;
import junit.framework.TestSuite;
public class AllTests extends TestCase {
public static final boolean skipSupportModules = false;
public static TestSuite suite() {
TestSuite suite = new TestSuite(AllTests.class.getName());
suite.addTest(AjbrowserModuleTests.suite());
suite.addTest(AjdeModuleTests.suite());
suite.addTest(AjdocModuleTests.suite());
suite.addTest(AsmModuleTests.suite());
suite.addTest(BridgeModuleTests.suite());
suite.addTest(LoadtimeModuleTests.suite());
suite.addTest(EajcModuleTests.suite());
//suite.addTest(LibModuleTests.suite());
suite.addTest(RuntimeModuleTests.suite());
suite.addTest(TaskdefsModuleTests.suite());
if (!skipSupportModules) {
suite.addTest(BuildModuleTests.suite());
suite.addTest(TestingModuleTests.suite());
suite.addTest(TestingClientModuleTests.suite());
suite.addTest(TestingDriversModuleTests.suite());
suite.addTest(TestingUtilModuleTests.suite());
}
suite.addTest(UtilModuleTests.suite());
suite.addTest(BcweaverModuleTests.suite());
if (LangUtil.is15VMOrGreater()) {
// these only require 1.3, but in Eclipse they are built
// with 1.5, i.e., wrong class version to load under 1.3
// so the class name can only be used reflectively
TestUtil.loadTestsReflectively(suite, "Aspectj5rtModuleTests", false);
- TestUtil.loadTestsReflectively(suite, "Loadtime515ModuleTests", false);
+ TestUtil.loadTestsReflectively(suite, "Loadtime5ModuleTests", false);
} else {
suite.addTest(TestUtil.skipTest("for 1.5"));
}
return suite;
}
public AllTests(String name) {
super(name);
}
}
| true | true | public static TestSuite suite() {
TestSuite suite = new TestSuite(AllTests.class.getName());
suite.addTest(AjbrowserModuleTests.suite());
suite.addTest(AjdeModuleTests.suite());
suite.addTest(AjdocModuleTests.suite());
suite.addTest(AsmModuleTests.suite());
suite.addTest(BridgeModuleTests.suite());
suite.addTest(LoadtimeModuleTests.suite());
suite.addTest(EajcModuleTests.suite());
//suite.addTest(LibModuleTests.suite());
suite.addTest(RuntimeModuleTests.suite());
suite.addTest(TaskdefsModuleTests.suite());
if (!skipSupportModules) {
suite.addTest(BuildModuleTests.suite());
suite.addTest(TestingModuleTests.suite());
suite.addTest(TestingClientModuleTests.suite());
suite.addTest(TestingDriversModuleTests.suite());
suite.addTest(TestingUtilModuleTests.suite());
}
suite.addTest(UtilModuleTests.suite());
suite.addTest(BcweaverModuleTests.suite());
if (LangUtil.is15VMOrGreater()) {
// these only require 1.3, but in Eclipse they are built
// with 1.5, i.e., wrong class version to load under 1.3
// so the class name can only be used reflectively
TestUtil.loadTestsReflectively(suite, "Aspectj5rtModuleTests", false);
TestUtil.loadTestsReflectively(suite, "Loadtime515ModuleTests", false);
} else {
suite.addTest(TestUtil.skipTest("for 1.5"));
}
return suite;
}
| public static TestSuite suite() {
TestSuite suite = new TestSuite(AllTests.class.getName());
suite.addTest(AjbrowserModuleTests.suite());
suite.addTest(AjdeModuleTests.suite());
suite.addTest(AjdocModuleTests.suite());
suite.addTest(AsmModuleTests.suite());
suite.addTest(BridgeModuleTests.suite());
suite.addTest(LoadtimeModuleTests.suite());
suite.addTest(EajcModuleTests.suite());
//suite.addTest(LibModuleTests.suite());
suite.addTest(RuntimeModuleTests.suite());
suite.addTest(TaskdefsModuleTests.suite());
if (!skipSupportModules) {
suite.addTest(BuildModuleTests.suite());
suite.addTest(TestingModuleTests.suite());
suite.addTest(TestingClientModuleTests.suite());
suite.addTest(TestingDriversModuleTests.suite());
suite.addTest(TestingUtilModuleTests.suite());
}
suite.addTest(UtilModuleTests.suite());
suite.addTest(BcweaverModuleTests.suite());
if (LangUtil.is15VMOrGreater()) {
// these only require 1.3, but in Eclipse they are built
// with 1.5, i.e., wrong class version to load under 1.3
// so the class name can only be used reflectively
TestUtil.loadTestsReflectively(suite, "Aspectj5rtModuleTests", false);
TestUtil.loadTestsReflectively(suite, "Loadtime5ModuleTests", false);
} else {
suite.addTest(TestUtil.skipTest("for 1.5"));
}
return suite;
}
|
diff --git a/plugins/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/script/JSResultSetRow.java b/plugins/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/script/JSResultSetRow.java
index 411c9e041..264963972 100644
--- a/plugins/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/script/JSResultSetRow.java
+++ b/plugins/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/script/JSResultSetRow.java
@@ -1,240 +1,240 @@
/*******************************************************************************
* Copyright (c) 2004 Actuate Corporation.
* 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:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.data.engine.script;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.birt.core.exception.BirtException;
import org.eclipse.birt.core.script.JavascriptEvalUtil;
import org.eclipse.birt.data.engine.api.IBaseExpression;
import org.eclipse.birt.data.engine.api.IBinding;
import org.eclipse.birt.data.engine.core.DataException;
import org.eclipse.birt.data.engine.expression.ExprEvaluateUtil;
import org.eclipse.birt.data.engine.i18n.ResourceConstants;
import org.eclipse.birt.data.engine.impl.ExprManager;
import org.eclipse.birt.data.engine.impl.IExecutorHelper;
import org.eclipse.birt.data.engine.odi.IResultIterator;
import org.eclipse.birt.data.engine.odi.IResultObject;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;
/**
* This JS object serves for the row of binding columns.
*/
public class JSResultSetRow extends ScriptableObject
{
private IResultIterator odiResult;
private ExprManager exprManager;
private Scriptable scope;
private IExecutorHelper helper;
private int currRowIndex;
private Map valueCacheMap;
/** */
private static final long serialVersionUID = 649424371394281464L;
/**
* @param odiResult
* @param exprManager
* @param scope
* @param helper
*/
public JSResultSetRow( IResultIterator odiResult, ExprManager exprManager,
Scriptable scope, IExecutorHelper helper )
{
this.odiResult = odiResult;
this.exprManager = exprManager;
this.scope = scope;
this.helper = helper;
this.currRowIndex = -1;
this.valueCacheMap = new HashMap( );
}
/*
* @see org.mozilla.javascript.ScriptableObject#getClassName()
*/
public String getClassName( )
{
return "ResultSetRow";
}
/*
* @see org.mozilla.javascript.ScriptableObject#has(int,
* org.mozilla.javascript.Scriptable)
*/
public boolean has( int index, Scriptable start )
{
return this.has( String.valueOf( index ), start );
}
/*
* @see org.mozilla.javascript.ScriptableObject#has(java.lang.String,
* org.mozilla.javascript.Scriptable)
*/
public boolean has( String name, Scriptable start )
{
try
{
return exprManager.getExpr( name ) != null;
}
catch ( DataException e )
{
return false;
}
}
/*
* @see org.mozilla.javascript.ScriptableObject#get(int,
* org.mozilla.javascript.Scriptable)
*/
public Object get( int index, Scriptable start )
{
return this.get( String.valueOf( index ), start );
}
/*
* @see org.mozilla.javascript.ScriptableObject#get(java.lang.String,
* org.mozilla.javascript.Scriptable)
*/
public Object get( String name, Scriptable start )
{
if( "_outer".equalsIgnoreCase( name ))
{
if( this.helper.getParent( )!= null)
return helper.getParent( ).getJSRowObject( );
else
return null;
}
int rowIndex = -1;
try
{
rowIndex = odiResult.getCurrentResultIndex( );
}
catch ( BirtException e1 )
{
// impossible, ignore
}
if( "__rownum".equalsIgnoreCase( name )||"0".equalsIgnoreCase( name ))
{
return new Integer( rowIndex );
}
if ( rowIndex == currRowIndex && valueCacheMap.containsKey( name ) )
{
return valueCacheMap.get( name );
}
else
{
Object value = null;
try
{
IBinding binding = this.exprManager.getBinding( name );
if ( binding == null )
{
return new DataExceptionMocker( new DataException( ResourceConstants.INVALID_BOUND_COLUMN_NAME,
name ) );
}
if ( binding.getAggrFunction( )!= null )
return this.odiResult.getAggrValue( name );
IBaseExpression dataExpr = this.exprManager.getExpr( name );
if ( dataExpr == null )
{
return new DataExceptionMocker( new DataException( ResourceConstants.INVALID_BOUND_COLUMN_NAME,
name ) );
}
value = ExprEvaluateUtil.evaluateValue( dataExpr,
this.odiResult.getCurrentResultIndex( ),
this.odiResult.getCurrentResult( ),
this.scope );
}
catch ( BirtException e )
{
value = null;
}
if ( this.currRowIndex != rowIndex )
{
this.valueCacheMap.clear( );
this.currRowIndex = rowIndex;
}
- value = JavascriptEvalUtil.convertToJavascriptValue( value );
+ value = JavascriptEvalUtil.convertToJavascriptValue( value, this.scope );
valueCacheMap.put( name, value );
return value;
}
}
/**
* @param rsObject
* @param index
* @param name
* @return value
* @throws DataException
*/
public Object getValue( IResultObject rsObject, int index, String name )
throws DataException
{
Object value = null;
if ( name.startsWith( "_{" ) )
{
try
{
value = rsObject.getFieldValue( name );
}
catch ( DataException e )
{
// ignore
}
}
else
{
IBaseExpression dataExpr = this.exprManager.getExpr( name );
try
{
value = ExprEvaluateUtil.evaluateValue( dataExpr,
-1,
rsObject,
this.scope );
//value = JavascriptEvalUtil.convertJavascriptValue( value );
}
catch ( BirtException e )
{
}
}
return value;
}
/*
* @see org.mozilla.javascript.ScriptableObject#put(int,
* org.mozilla.javascript.Scriptable, java.lang.Object)
*/
public void put( int index, Scriptable scope, Object value )
{
throw new IllegalArgumentException( "Put value on result set row is not supported." );
}
/*
* @see org.mozilla.javascript.ScriptableObject#put(java.lang.String,
* org.mozilla.javascript.Scriptable, java.lang.Object)
*/
public void put( String name, Scriptable scope, Object value )
{
throw new IllegalArgumentException( "Put value on result set row is not supported." );
}
}
| true | true | public Object get( String name, Scriptable start )
{
if( "_outer".equalsIgnoreCase( name ))
{
if( this.helper.getParent( )!= null)
return helper.getParent( ).getJSRowObject( );
else
return null;
}
int rowIndex = -1;
try
{
rowIndex = odiResult.getCurrentResultIndex( );
}
catch ( BirtException e1 )
{
// impossible, ignore
}
if( "__rownum".equalsIgnoreCase( name )||"0".equalsIgnoreCase( name ))
{
return new Integer( rowIndex );
}
if ( rowIndex == currRowIndex && valueCacheMap.containsKey( name ) )
{
return valueCacheMap.get( name );
}
else
{
Object value = null;
try
{
IBinding binding = this.exprManager.getBinding( name );
if ( binding == null )
{
return new DataExceptionMocker( new DataException( ResourceConstants.INVALID_BOUND_COLUMN_NAME,
name ) );
}
if ( binding.getAggrFunction( )!= null )
return this.odiResult.getAggrValue( name );
IBaseExpression dataExpr = this.exprManager.getExpr( name );
if ( dataExpr == null )
{
return new DataExceptionMocker( new DataException( ResourceConstants.INVALID_BOUND_COLUMN_NAME,
name ) );
}
value = ExprEvaluateUtil.evaluateValue( dataExpr,
this.odiResult.getCurrentResultIndex( ),
this.odiResult.getCurrentResult( ),
this.scope );
}
catch ( BirtException e )
{
value = null;
}
if ( this.currRowIndex != rowIndex )
{
this.valueCacheMap.clear( );
this.currRowIndex = rowIndex;
}
value = JavascriptEvalUtil.convertToJavascriptValue( value );
valueCacheMap.put( name, value );
return value;
}
}
| public Object get( String name, Scriptable start )
{
if( "_outer".equalsIgnoreCase( name ))
{
if( this.helper.getParent( )!= null)
return helper.getParent( ).getJSRowObject( );
else
return null;
}
int rowIndex = -1;
try
{
rowIndex = odiResult.getCurrentResultIndex( );
}
catch ( BirtException e1 )
{
// impossible, ignore
}
if( "__rownum".equalsIgnoreCase( name )||"0".equalsIgnoreCase( name ))
{
return new Integer( rowIndex );
}
if ( rowIndex == currRowIndex && valueCacheMap.containsKey( name ) )
{
return valueCacheMap.get( name );
}
else
{
Object value = null;
try
{
IBinding binding = this.exprManager.getBinding( name );
if ( binding == null )
{
return new DataExceptionMocker( new DataException( ResourceConstants.INVALID_BOUND_COLUMN_NAME,
name ) );
}
if ( binding.getAggrFunction( )!= null )
return this.odiResult.getAggrValue( name );
IBaseExpression dataExpr = this.exprManager.getExpr( name );
if ( dataExpr == null )
{
return new DataExceptionMocker( new DataException( ResourceConstants.INVALID_BOUND_COLUMN_NAME,
name ) );
}
value = ExprEvaluateUtil.evaluateValue( dataExpr,
this.odiResult.getCurrentResultIndex( ),
this.odiResult.getCurrentResult( ),
this.scope );
}
catch ( BirtException e )
{
value = null;
}
if ( this.currRowIndex != rowIndex )
{
this.valueCacheMap.clear( );
this.currRowIndex = rowIndex;
}
value = JavascriptEvalUtil.convertToJavascriptValue( value, this.scope );
valueCacheMap.put( name, value );
return value;
}
}
|
diff --git a/bobo-browse/src/com/browseengine/bobo/facets/impl/DynamicTimeRangeFacetHandler.java b/bobo-browse/src/com/browseengine/bobo/facets/impl/DynamicTimeRangeFacetHandler.java
index 31238c2..d501ac1 100644
--- a/bobo-browse/src/com/browseengine/bobo/facets/impl/DynamicTimeRangeFacetHandler.java
+++ b/bobo-browse/src/com/browseengine/bobo/facets/impl/DynamicTimeRangeFacetHandler.java
@@ -1,148 +1,148 @@
/**
*
*/
package com.browseengine.bobo.facets.impl;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import org.apache.log4j.Logger;
import com.browseengine.bobo.facets.impl.DynamicRangeFacetHandler;
public class DynamicTimeRangeFacetHandler extends DynamicRangeFacetHandler
{
private static final Logger log = Logger.getLogger(DynamicTimeRangeFacetHandler.class.getName());
private static final String NUMBER_FORMAT = "00000000000000000000";
protected ThreadLocal<DecimalFormat> _formatter = null;
public static long MILLIS_IN_DAY = 24L * 60L * 60L * 1000L;
public static long MILLIS_IN_HOUR = 60L * 60L * 1000L;
public static long MILLIS_IN_MIN = 60L * 1000L;
public static long MILLIS_IN_SEC = 1000L;
private final HashMap<String,String> _valueToRangeStringMap;
private final HashMap<String,String> _rangeStringToValueMap;
private final ArrayList<String> _rangeStringList;
/**
* the format of range string is dddhhmmss. (ddd: days (000-999), hh : hours (00-23), mm: minutes (00-59), ss: seconds (00-59))
* @param name
* @param dataFacetName
* @param currentTime
* @param ranges
*/
public DynamicTimeRangeFacetHandler(String name, String dataFacetName, long currentTime, List<String> ranges) throws ParseException
{
super(name, dataFacetName);
_formatter = new ThreadLocal<DecimalFormat>()
{
protected DecimalFormat initialValue()
{
return new DecimalFormat(NUMBER_FORMAT);
}
};
log.info(name +" " + dataFacetName + " " + currentTime);
ArrayList<String> sortedRanges = new ArrayList<String>(ranges);
Collections.sort(sortedRanges);
_valueToRangeStringMap = new HashMap<String,String>();
_rangeStringToValueMap = new HashMap<String,String>();
_rangeStringList = new ArrayList<String>(ranges.size());
String prev = "000000000";
- for(String range : ranges)
+ for(String range : sortedRanges)
{
String rangeString = buildRangeString(currentTime, prev, range);
_valueToRangeStringMap.put(range, rangeString);
_rangeStringToValueMap.put(rangeString, range);
_rangeStringList.add(rangeString);
prev = range;
log.info(range + "\t " + rangeString);
}
}
private DynamicTimeRangeFacetHandler(String name, String dataFacetName,
HashMap<String,String> valueToRangeStringMap,
HashMap<String,String> rangeStringToValueMap,
ArrayList<String> rangeStringList)
{
super(name, dataFacetName);
log.info(dataFacetName);
_valueToRangeStringMap = valueToRangeStringMap;
_rangeStringToValueMap = rangeStringToValueMap;
_rangeStringList = rangeStringList;
}
private static long getTime(long time, String range) throws ParseException
{
if(range.length() != 9) throw new ParseException("invalid range format: " + range, 0);
try
{
int val;
val = Integer.parseInt(range.substring(0, 3));
time -= val * MILLIS_IN_DAY;
val = Integer.parseInt(range.substring(3, 5));
if(val >= 24) throw new ParseException("invalid range format: " + range, 0);
time -= val * MILLIS_IN_HOUR;
val = Integer.parseInt(range.substring(5, 7));
if(val >= 60) throw new ParseException("invalid range format: " + range, 0);
time -= val * MILLIS_IN_MIN;
val = Integer.parseInt(range.substring(7, 9));
if(val >= 60) throw new ParseException("invalid range format: " + range, 0);
time -= val * MILLIS_IN_SEC;
return time;
}
catch (NumberFormatException e)
{
throw new ParseException("invalid time format:" + range, 0);
}
}
private String buildRangeString(long currentTime, String dStart, String dEnd) throws ParseException
{
String end = _formatter.get().format(getTime(currentTime, dStart) - 1);
String start = _formatter.get().format(getTime(currentTime, dEnd));
StringBuilder buf = new StringBuilder();
buf.append("[").append(start).append(" TO ").append(end).append("]");
return buf.toString();
}
@Override
protected String buildRangeString(String val)
{
log.info("buildRangeString:" + val +" " + _valueToRangeStringMap.get(val));
return _valueToRangeStringMap.get(val);
}
@Override
protected List<String> buildAllRangeStrings()
{
log.info("buildAllRangeStrings:");
return _rangeStringList;
}
@Override
protected String getValueFromRangeString(String val)
{
log.info("getValueFromRangeString:" + val +" " + _rangeStringToValueMap.get(val));
return _rangeStringToValueMap.get(val);
}
public DynamicTimeRangeFacetHandler newInstance()
{
return new DynamicTimeRangeFacetHandler(getName(), _dataFacetName, _valueToRangeStringMap, _rangeStringToValueMap, _rangeStringList);
}
}
| true | true | public DynamicTimeRangeFacetHandler(String name, String dataFacetName, long currentTime, List<String> ranges) throws ParseException
{
super(name, dataFacetName);
_formatter = new ThreadLocal<DecimalFormat>()
{
protected DecimalFormat initialValue()
{
return new DecimalFormat(NUMBER_FORMAT);
}
};
log.info(name +" " + dataFacetName + " " + currentTime);
ArrayList<String> sortedRanges = new ArrayList<String>(ranges);
Collections.sort(sortedRanges);
_valueToRangeStringMap = new HashMap<String,String>();
_rangeStringToValueMap = new HashMap<String,String>();
_rangeStringList = new ArrayList<String>(ranges.size());
String prev = "000000000";
for(String range : ranges)
{
String rangeString = buildRangeString(currentTime, prev, range);
_valueToRangeStringMap.put(range, rangeString);
_rangeStringToValueMap.put(rangeString, range);
_rangeStringList.add(rangeString);
prev = range;
log.info(range + "\t " + rangeString);
}
}
| public DynamicTimeRangeFacetHandler(String name, String dataFacetName, long currentTime, List<String> ranges) throws ParseException
{
super(name, dataFacetName);
_formatter = new ThreadLocal<DecimalFormat>()
{
protected DecimalFormat initialValue()
{
return new DecimalFormat(NUMBER_FORMAT);
}
};
log.info(name +" " + dataFacetName + " " + currentTime);
ArrayList<String> sortedRanges = new ArrayList<String>(ranges);
Collections.sort(sortedRanges);
_valueToRangeStringMap = new HashMap<String,String>();
_rangeStringToValueMap = new HashMap<String,String>();
_rangeStringList = new ArrayList<String>(ranges.size());
String prev = "000000000";
for(String range : sortedRanges)
{
String rangeString = buildRangeString(currentTime, prev, range);
_valueToRangeStringMap.put(range, rangeString);
_rangeStringToValueMap.put(rangeString, range);
_rangeStringList.add(rangeString);
prev = range;
log.info(range + "\t " + rangeString);
}
}
|
diff --git a/lucene/test-framework/src/java/org/apache/lucene/store/MockIndexOutputWrapper.java b/lucene/test-framework/src/java/org/apache/lucene/store/MockIndexOutputWrapper.java
index dcf910f0c1..058dc978ef 100644
--- a/lucene/test-framework/src/java/org/apache/lucene/store/MockIndexOutputWrapper.java
+++ b/lucene/test-framework/src/java/org/apache/lucene/store/MockIndexOutputWrapper.java
@@ -1,168 +1,168 @@
package org.apache.lucene.store;
/*
* 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.io.IOException;
import org.apache.lucene.util.LuceneTestCase;
/**
* Used by MockRAMDirectory to create an output stream that
* will throw an IOException on fake disk full, track max
* disk space actually used, and maybe throw random
* IOExceptions.
*/
public class MockIndexOutputWrapper extends IndexOutput {
private MockDirectoryWrapper dir;
private final IndexOutput delegate;
private boolean first=true;
final String name;
byte[] singleByte = new byte[1];
/** Construct an empty output buffer. */
public MockIndexOutputWrapper(MockDirectoryWrapper dir, IndexOutput delegate, String name) {
this.dir = dir;
this.name = name;
this.delegate = delegate;
}
@Override
public void close() throws IOException {
try {
dir.maybeThrowDeterministicException();
} finally {
delegate.close();
if (dir.trackDiskUsage) {
// Now compute actual disk usage & track the maxUsedSize
// in the MockDirectoryWrapper:
long size = dir.getRecomputedActualSizeInBytes();
if (size > dir.maxUsedSize) {
dir.maxUsedSize = size;
}
}
dir.removeIndexOutput(this, name);
}
}
@Override
public void flush() throws IOException {
dir.maybeThrowDeterministicException();
delegate.flush();
}
@Override
public void writeByte(byte b) throws IOException {
singleByte[0] = b;
writeBytes(singleByte, 0, 1);
}
@Override
public void writeBytes(byte[] b, int offset, int len) throws IOException {
long freeSpace = dir.maxSize == 0 ? 0 : dir.maxSize - dir.sizeInBytes();
long realUsage = 0;
- if (dir.rateLimiter != null && len >= 10) {
+ if (dir.rateLimiter != null && len >= 1000) {
dir.rateLimiter.pause(len);
}
// If MockRAMDir crashed since we were opened, then
// don't write anything:
if (dir.crashed)
throw new IOException("MockRAMDirectory was crashed; cannot write to " + name);
// Enforce disk full:
if (dir.maxSize != 0 && freeSpace <= len) {
// Compute the real disk free. This will greatly slow
// down our test but makes it more accurate:
realUsage = dir.getRecomputedActualSizeInBytes();
freeSpace = dir.maxSize - realUsage;
}
if (dir.maxSize != 0 && freeSpace <= len) {
if (freeSpace > 0) {
realUsage += freeSpace;
delegate.writeBytes(b, offset, (int) freeSpace);
}
if (realUsage > dir.maxUsedSize) {
dir.maxUsedSize = realUsage;
}
String message = "fake disk full at " + dir.getRecomputedActualSizeInBytes() + " bytes when writing " + name + " (file length=" + delegate.length();
if (freeSpace > 0) {
message += "; wrote " + freeSpace + " of " + len + " bytes";
}
message += ")";
if (LuceneTestCase.VERBOSE) {
System.out.println(Thread.currentThread().getName() + ": MDW: now throw fake disk full");
new Throwable().printStackTrace(System.out);
}
throw new IOException(message);
} else {
if (dir.randomState.nextInt(200) == 0) {
final int half = len/2;
delegate.writeBytes(b, offset, half);
Thread.yield();
delegate.writeBytes(b, offset+half, len-half);
} else {
delegate.writeBytes(b, offset, len);
}
}
dir.maybeThrowDeterministicException();
if (first) {
// Maybe throw random exception; only do this on first
// write to a new file:
first = false;
dir.maybeThrowIOException(name);
}
}
@Override
public long getFilePointer() {
return delegate.getFilePointer();
}
@Override
public void seek(long pos) throws IOException {
delegate.seek(pos);
}
@Override
public long length() throws IOException {
return delegate.length();
}
@Override
public void setLength(long length) throws IOException {
delegate.setLength(length);
}
@Override
public void copyBytes(DataInput input, long numBytes) throws IOException {
delegate.copyBytes(input, numBytes);
// TODO: we may need to check disk full here as well
dir.maybeThrowDeterministicException();
}
@Override
public String toString() {
return "MockIndexOutputWrapper(" + delegate + ")";
}
}
| true | true | public void writeBytes(byte[] b, int offset, int len) throws IOException {
long freeSpace = dir.maxSize == 0 ? 0 : dir.maxSize - dir.sizeInBytes();
long realUsage = 0;
if (dir.rateLimiter != null && len >= 10) {
dir.rateLimiter.pause(len);
}
// If MockRAMDir crashed since we were opened, then
// don't write anything:
if (dir.crashed)
throw new IOException("MockRAMDirectory was crashed; cannot write to " + name);
// Enforce disk full:
if (dir.maxSize != 0 && freeSpace <= len) {
// Compute the real disk free. This will greatly slow
// down our test but makes it more accurate:
realUsage = dir.getRecomputedActualSizeInBytes();
freeSpace = dir.maxSize - realUsage;
}
if (dir.maxSize != 0 && freeSpace <= len) {
if (freeSpace > 0) {
realUsage += freeSpace;
delegate.writeBytes(b, offset, (int) freeSpace);
}
if (realUsage > dir.maxUsedSize) {
dir.maxUsedSize = realUsage;
}
String message = "fake disk full at " + dir.getRecomputedActualSizeInBytes() + " bytes when writing " + name + " (file length=" + delegate.length();
if (freeSpace > 0) {
message += "; wrote " + freeSpace + " of " + len + " bytes";
}
message += ")";
if (LuceneTestCase.VERBOSE) {
System.out.println(Thread.currentThread().getName() + ": MDW: now throw fake disk full");
new Throwable().printStackTrace(System.out);
}
throw new IOException(message);
} else {
if (dir.randomState.nextInt(200) == 0) {
final int half = len/2;
delegate.writeBytes(b, offset, half);
Thread.yield();
delegate.writeBytes(b, offset+half, len-half);
} else {
delegate.writeBytes(b, offset, len);
}
}
dir.maybeThrowDeterministicException();
if (first) {
// Maybe throw random exception; only do this on first
// write to a new file:
first = false;
dir.maybeThrowIOException(name);
}
}
| public void writeBytes(byte[] b, int offset, int len) throws IOException {
long freeSpace = dir.maxSize == 0 ? 0 : dir.maxSize - dir.sizeInBytes();
long realUsage = 0;
if (dir.rateLimiter != null && len >= 1000) {
dir.rateLimiter.pause(len);
}
// If MockRAMDir crashed since we were opened, then
// don't write anything:
if (dir.crashed)
throw new IOException("MockRAMDirectory was crashed; cannot write to " + name);
// Enforce disk full:
if (dir.maxSize != 0 && freeSpace <= len) {
// Compute the real disk free. This will greatly slow
// down our test but makes it more accurate:
realUsage = dir.getRecomputedActualSizeInBytes();
freeSpace = dir.maxSize - realUsage;
}
if (dir.maxSize != 0 && freeSpace <= len) {
if (freeSpace > 0) {
realUsage += freeSpace;
delegate.writeBytes(b, offset, (int) freeSpace);
}
if (realUsage > dir.maxUsedSize) {
dir.maxUsedSize = realUsage;
}
String message = "fake disk full at " + dir.getRecomputedActualSizeInBytes() + " bytes when writing " + name + " (file length=" + delegate.length();
if (freeSpace > 0) {
message += "; wrote " + freeSpace + " of " + len + " bytes";
}
message += ")";
if (LuceneTestCase.VERBOSE) {
System.out.println(Thread.currentThread().getName() + ": MDW: now throw fake disk full");
new Throwable().printStackTrace(System.out);
}
throw new IOException(message);
} else {
if (dir.randomState.nextInt(200) == 0) {
final int half = len/2;
delegate.writeBytes(b, offset, half);
Thread.yield();
delegate.writeBytes(b, offset+half, len-half);
} else {
delegate.writeBytes(b, offset, len);
}
}
dir.maybeThrowDeterministicException();
if (first) {
// Maybe throw random exception; only do this on first
// write to a new file:
first = false;
dir.maybeThrowIOException(name);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.