=====================================================================
Found a 204 line (728 tokens) duplication in the following files:
Starting at line 39 of /home/tom/pmd/pmd-web/src/geotools2/geotools-src/lite-rendering/src/org/geotools/renderer/lite/ImageLoader.java
Starting at line 39 of /home/tom/pmd/pmd-web/src/geotools2/geotools-src/renderer/src/org/geotools/renderer/style/ImageLoader.java
class ImageLoader implements Runnable {
/** The logger for the rendering module. */
private static final Logger LOGGER = Logger.getLogger("org.geotools.rendering");
/** The images managed by the loader */
private static Map images = new HashMap();
/** A canvas used as the image observer on the tracker */
private static Canvas obs = new Canvas();
/** Used to track the images loading status */
private static MediaTracker tracker = new MediaTracker(obs);
/** Currently loading image */
private static int imageID = 1;
/** A maximum time to wait for the image to load */
private static long timeout = 10000;
/** Location of the loading image */
private URL location;
/** Still waiting for the image? */
private boolean waiting = true;
/**
* Returns the timeout for aborting an image loading sequence
*
* @return the timeout in milliseconds
*/
public static long getTimeout() {
return timeout;
}
/**
* Sets the maximum time to wait for getting an external image. Set it to -1 to wait
* undefinitely
*
* @param newTimeout the new timeout value in milliseconds
*/
public static void setTimeout(long newTimeout) {
timeout = newTimeout;
}
/**
* Add an image to be loaded by the ImageLoader
*
* @param location the image location
* @param interactive if true the methods returns immediatly, otherwise waits for the image to
* be loaded
*/
private void add(URL location, boolean interactive) {
int imgId = imageID;
this.location = location;
LOGGER.finest("adding image, interactive? " + interactive);
Thread t = new Thread(this);
t.start();
if (interactive) {
LOGGER.finest("fast return");
return;
} else {
waiting = true;
long elapsed = 0;
final long step = 500;
while (waiting && (elapsed < timeout || timeout < 0)) {
LOGGER.finest("waiting..." + waiting);
try {
Thread.sleep(step);
elapsed += step;
if (LOGGER.isLoggable(Level.FINEST)) {
LOGGER.finest("Waiting for image " + location + ", elapsed " + elapsed
+ " milliseconds");
}
} catch (InterruptedException e) {
LOGGER.warning(e.toString());
}
}
if (LOGGER.isLoggable(Level.FINEST)) {
LOGGER.finest(imgId + " complete?: " + (isFlagUp(imgId, MediaTracker.COMPLETE)));
LOGGER.finest(imgId + " abort?: " + (isFlagUp(imgId, MediaTracker.ABORTED)));
LOGGER.finest(imgId + " error?: " + (isFlagUp(imgId, MediaTracker.ERRORED)));
LOGGER.finest(imgId + " loading?: " + (isFlagUp(imgId, MediaTracker.LOADING)));
LOGGER.finest(imgId + "slow return " + waiting);
}
return;
}
}
/**
* Checks the state of the current tracker against a flag
*
* @param id the image id
* @param flag the flag to be checked
*
* @return true if the flag is up
*/
private boolean isFlagUp(int id, int flag) {
return (tracker.statusID(id, true) & flag) == flag;
}
/**
* Fetch a buffered image from the loader, if interactive is false then the loader will wait
* for the image to be available before returning, used by printers and file output
* renderers. If interactive is true and the image is ready then return, if image is not ready
* start loading it and return null. The renderer is responsible for finding an alternative
* to use.
*
* @param location the url of the image to be fetched
* @param interactive boolean to signal if the loader should wait for the image to be ready.
*
* @return the buffered image or null
*/
public BufferedImage get(URL location, boolean interactive) {
if (images.containsKey(location)) {
LOGGER.finest("found it");
return (BufferedImage) images.get(location);
} else {
if (!interactive) {
images.put(location, null);
}
LOGGER.finest("adding " + location);
add(location, interactive);
return (BufferedImage) images.get(location);
}
}
/**
* Runs the loading thread
*/
public void run() {
int myID = 0;
Image img = null;
try {
img = Toolkit.getDefaultToolkit().createImage(location);
myID = imageID++;
tracker.addImage(img, myID);
} catch (Exception e) {
LOGGER.warning("Exception fetching image from " + location + "\n" + e);
images.remove(location);
waiting = false;
return;
}
try {
while ((tracker.statusID(myID, true) & MediaTracker.LOADING) != 0) {
tracker.waitForID(myID, 500);
LOGGER.finest(myID + "loading - waiting....");
}
} catch (InterruptedException ie) {
LOGGER.warning(ie.toString());
}
int state = tracker.statusID(myID, true);
if (state == MediaTracker.ERRORED) {
LOGGER.finer("" + myID + " Error loading");
// images.remove(location);
waiting = false;
return;
}
if ((state & MediaTracker.COMPLETE) == MediaTracker.COMPLETE) {
LOGGER.finest("" + myID + "completed load");
int iw = img.getWidth(obs);
int ih = img.getHeight(obs);
BufferedImage bi = new BufferedImage(iw, ih, BufferedImage.TYPE_INT_ARGB);
Graphics2D big = bi.createGraphics();
big.drawImage(img, 0, 0, obs);
images.put(location, bi);
waiting = false;
return;
}
LOGGER.finer("" + myID + " whoops - some other outcome " + state);
waiting = false;
return;
}
/**
* Resets the image cache
*/
public void reset() {
images.clear();
}
}
=====================================================================
Found a 107 line (463 tokens) duplication in the following files:
Starting at line 44 of /home/tom/pmd/pmd-web/src/geotools2/geotools-src/validation/tests/unit/org/geotools/validation/attributes/RangeFeatureValidationTest.java
Starting at line 44 of /home/tom/pmd/pmd-web/src/geotools2/geotools-src/validation/tests/unit/org/geotools/validation/attributes/NullZeroValidationTest.java
public NullZeroValidationTest(String arg0) {
super(arg0);
}
/*
* @see TestCase#setUp()
*/
protected void setUp() throws Exception {
GeometryFactory gf = new GeometryFactory();
test = new RangeValidation();
super.setUp();
type = DataUtilities.createType(getName()+".road",
"id:0,*geom:LineString,name:String");
Coordinate[] coords = new Coordinate[]{ new Coordinate(1, 1), new Coordinate( 2, 2), new Coordinate (4, 2), new Coordinate (5, 1)};
feature = type.create(new Object[] {
new Integer(1),
gf.createLineString(coords),
"r1",
},
"road.rd1"
);
results = new RoadValidationResults();
}
/*
* @see TestCase#tearDown()
*/
protected void tearDown() throws Exception {
test = null;
super.tearDown();
}
public void testRangeFeatureValidation() throws Exception {
test.setPath("id");
assertTrue(test.validate(feature, type, results));
assertEquals(0,results.failedFeatures.size());
test.setMin(5);
assertTrue(!test.validate(feature, type, results));
assertEquals(1,results.failedFeatures.size());
}
public void testValidate() {
//test.validate(feature, type, results);
}
public void testSetName() {
test.setName("foo");
assertEquals("foo", test.getName());
}
public void testGetName() {
test.setName("bork");
assertEquals("bork", test.getName());
}
public void testSetDescription() {
test.setDescription("foo");
assertEquals("foo", test.getDescription());
}
public void testGetDescription() {
test.setDescription("bork");
assertEquals("bork", test.getDescription());
}
public void testGetPriority() {
//TODO Implement getPriority().
}
public void testGetMax() {
test.setMax(100);
assertEquals(100, test.getMax());
}
public void testGetMin() {
test.setMin(10);
assertEquals(10, test.getMin());
}
public void testGetPath() {
test.setPath("path");
assertEquals("path", test.getPath());
}
public void testSetMax() {
test.setMax(500);
assertEquals(500, test.getMax());
}
public void testSetMin() {
test.setMin(5);
assertEquals(5, test.getMin());
}
public void testSetPath() {
test.setPath("path2");
assertEquals("path2", test.getPath());
}
}
=====================================================================
Found a 58 line (427 tokens) duplication in the following files:
Starting at line 50 of /home/tom/pmd/pmd-web/src/geotools2/geotools-src/lite-rendering/src/org/geotools/renderer/lite/Java2DMark.java
Starting at line 37 of /home/tom/pmd/pmd-web/src/geotools2/geotools-src/renderer/src/org/geotools/renderer/style/Java2DMark.java
static Shape X;
static {
cross = new GeneralPath(GeneralPath.WIND_EVEN_ODD);
cross.moveTo(0.5f, 0.125f);
cross.lineTo(0.125f, 0.125f);
cross.lineTo(0.125f, 0.5f);
cross.lineTo(-0.125f, 0.5f);
cross.lineTo(-0.125f, 0.125f);
cross.lineTo(-0.5f, 0.125f);
cross.lineTo(-0.5f, -0.125f);
cross.lineTo(-0.125f, -0.125f);
cross.lineTo(-0.125f, -0.5f);
cross.lineTo(0.125f, -0.5f);
cross.lineTo(0.125f, -0.125f);
cross.lineTo(0.5f, -0.125f);
cross.lineTo(0.5f, 0.125f);
AffineTransform at = new AffineTransform();
at.rotate(Math.PI / 4.0);
X = cross.createTransformedShape(at);
star = new GeneralPath(GeneralPath.WIND_EVEN_ODD);
star.moveTo(0.191f, 0.0f);
star.lineTo(0.25f, 0.344f);
star.lineTo(0.0f, 0.588f);
star.lineTo(0.346f, 0.638f);
star.lineTo(0.5f, 0.951f);
star.lineTo(0.654f, 0.638f);
star.lineTo(1.0f, 0.588f); // max = 7.887
star.lineTo(0.75f, 0.344f);
star.lineTo(0.89f, 0f);
star.lineTo(0.5f, 0.162f);
star.lineTo(0.191f, 0.0f);
at = new AffineTransform();
at.translate(-.5, -.5);
star.transform(at);
triangle = new GeneralPath(GeneralPath.WIND_EVEN_ODD);
triangle.moveTo(0f, 1f);
triangle.lineTo(0.866f, -.5f);
triangle.lineTo(-0.866f, -.5f);
triangle.lineTo(0f, 1f);
at = new AffineTransform();
at.translate(0, -.25);
at.scale(.5, .5);
triangle.transform(at);
arrow = new GeneralPath(GeneralPath.WIND_EVEN_ODD);
arrow.moveTo(0f, -.5f);
arrow.lineTo(.5f, 0f);
arrow.lineTo(0f, .5f);
arrow.lineTo(0f, .1f);
arrow.lineTo(-.5f, .1f);
arrow.lineTo(-.5f, -.1f);
arrow.lineTo(0f, -.1f);
arrow.lineTo(0f, -.5f);
}
=====================================================================
Found a 50 line (403 tokens) duplication in the following files:
Starting at line 35 of /home/tom/pmd/pmd-web/src/geotools2/geotools-src/filter/src/org/geotools/filter/FilterTransformer.java
Starting at line 60 of /home/tom/pmd/pmd-web/src/geotools2/geotools-src/filter/src/org/geotools/filter/XMLEncoder.java
private static Map comparisions = new HashMap();
/** Map of spatial types to sql representation */
private static Map spatial = new HashMap();
/** Map of logical types to sql representation */
private static Map logical = new HashMap();
/** Map of expression types to sql representation */
private static Map expressions = new HashMap();
static {
comparisions.put(new Integer(AbstractFilter.COMPARE_EQUALS),
"PropertyIsEqualTo");
comparisions.put(new Integer(AbstractFilter.COMPARE_GREATER_THAN),
"PropertyIsGreaterThan");
comparisions.put(new Integer(AbstractFilter.COMPARE_GREATER_THAN_EQUAL),
"PropertyIsGreaterThanOrEqualTo");
comparisions.put(new Integer(AbstractFilter.COMPARE_LESS_THAN),
"PropertyIsLessThan");
comparisions.put(new Integer(AbstractFilter.COMPARE_LESS_THAN_EQUAL),
"PropertyIsLessThanOrEqualTo");
comparisions.put(new Integer(AbstractFilter.LIKE), "PropertyIsLike");
comparisions.put(new Integer(AbstractFilter.NULL), "PropertyIsNull");
comparisions.put(new Integer(AbstractFilter.BETWEEN),
"PropertyIsBetween");
expressions.put(new Integer(DefaultExpression.MATH_ADD), "Add");
expressions.put(new Integer(DefaultExpression.MATH_DIVIDE), "Div");
expressions.put(new Integer(DefaultExpression.MATH_MULTIPLY), "Mul");
expressions.put(new Integer(DefaultExpression.MATH_SUBTRACT), "Sub");
expressions.put(new Integer(DefaultExpression.FUNCTION), "Function");
//more to come
spatial.put(new Integer(AbstractFilter.GEOMETRY_EQUALS), "Equals");
spatial.put(new Integer(AbstractFilter.GEOMETRY_DISJOINT), "Disjoint");
spatial.put(new Integer(AbstractFilter.GEOMETRY_INTERSECTS),
"Intersects");
spatial.put(new Integer(AbstractFilter.GEOMETRY_TOUCHES), "Touches");
spatial.put(new Integer(AbstractFilter.GEOMETRY_CROSSES), "Crosses");
spatial.put(new Integer(AbstractFilter.GEOMETRY_WITHIN), "Within");
spatial.put(new Integer(AbstractFilter.GEOMETRY_CONTAINS), "Contains");
spatial.put(new Integer(AbstractFilter.GEOMETRY_OVERLAPS), "Overlaps");
spatial.put(new Integer(AbstractFilter.GEOMETRY_BEYOND), "Beyond");
spatial.put(new Integer(AbstractFilter.GEOMETRY_BBOX), "BBOX");
logical.put(new Integer(AbstractFilter.LOGIC_AND), "And");
logical.put(new Integer(AbstractFilter.LOGIC_OR), "Or");
logical.put(new Integer(AbstractFilter.LOGIC_NOT), "Not");
}
=====================================================================
Found a 79 line (397 tokens) duplication in the following files:
Starting at line 66 of /home/tom/pmd/pmd-web/src/geotools2/geotools-src/postgis/tests/unit/org/geotools/filter/SQLEncoderPostgisTest.java
Starting at line 53 of /home/tom/pmd/pmd-web/src/geotools2/geotools-src/filter/tests/unit/org/geotools/filter/FilterTestSupport.java
}
protected void setUp() throws SchemaException, IllegalAttributeException {
if (setup) {
return;
} else {
prepareFeatures();
}
setup = true;
}
protected void prepareFeatures()
throws SchemaException, IllegalAttributeException {
//_log.getLoggerRepository().setThreshold(Level.INFO);
// Create the schema attributes
LOGGER.finer("creating flat feature...");
AttributeType geometryAttribute = attFactory.newAttributeType("testGeometry",
LineString.class);
LOGGER.finer("created geometry attribute");
AttributeType booleanAttribute = attFactory.newAttributeType("testBoolean",
Boolean.class);
LOGGER.finer("created boolean attribute");
AttributeType charAttribute = attFactory.newAttributeType("testCharacter",
Character.class);
AttributeType byteAttribute = attFactory.newAttributeType("testByte",
Byte.class);
AttributeType shortAttribute = attFactory.newAttributeType("testShort",
Short.class);
AttributeType intAttribute = attFactory.newAttributeType("testInteger",
Integer.class);
AttributeType longAttribute = attFactory.newAttributeType("testLong",
Long.class);
AttributeType floatAttribute = attFactory.newAttributeType("testFloat",
Float.class);
AttributeType doubleAttribute = attFactory.newAttributeType("testDouble",
Double.class);
AttributeType stringAttribute = attFactory.newAttributeType("testString",
String.class);
AttributeType[] types = {
geometryAttribute, booleanAttribute, charAttribute, byteAttribute,
shortAttribute, intAttribute, longAttribute, floatAttribute,
doubleAttribute, stringAttribute
};
// Builds the schema
testSchema = FeatureTypeFactory.newFeatureType(types,"testSchema");
GeometryFactory geomFac = new GeometryFactory();
// Creates coordinates for the linestring
Coordinate[] coords = new Coordinate[3];
coords[0] = new Coordinate(1, 2);
coords[1] = new Coordinate(3, 4);
coords[2] = new Coordinate(5, 6);
// Builds the test feature
Object[] attributes = new Object[10];
attributes[0] = geomFac.createLineString(coords);
attributes[1] = new Boolean(true);
attributes[2] = new Character('t');
attributes[3] = new Byte("10");
attributes[4] = new Short("101");
attributes[5] = new Integer(1002);
attributes[6] = new Long(10003);
attributes[7] = new Float(10000.4);
attributes[8] = new Double(100000.5);
attributes[9] = "test string data";
// Creates the feature itself
testFeature = testSchema.create(attributes);
LOGGER.finer("...flat feature created");
//_log.getLoggerRepository().setThreshold(Level.DEBUG);
}
=====================================================================
Found a 60 line (367 tokens) duplication in the following files:
Starting at line 63 of /home/tom/pmd/pmd-web/src/geotools2/geotools-src/filter/tests/unit/org/geotools/filter/MathTest.java
Starting at line 61 of /home/tom/pmd/pmd-web/src/geotools2/geotools-src/filter/tests/unit/org/geotools/filter/AttributeTest.java
}, "test");
Feature[] f = new Feature[3];
f[0] = schema.create(new Object[] {
new Integer(12), new GeometryCollection(null, null, -1),
"first"
});
f[1] = schema.create(new Object[] {
new Integer(3), new GeometryCollection(null, null, -1),
"second"
});
f[2] = schema.create(new Object[] {
new Integer(15), new GeometryCollection(null, null, -1),
"third"
});
return f;
}
public void testTypeMissmatch() throws Exception {
Feature[] f = sampleFeatures();
//the following are intentionaly backwards
AttributeExpressionImpl e1 = new AttributeExpressionImpl(schema, "value");
AttributeExpressionImpl e2 = new AttributeExpressionImpl(schema, "name");
boolean pass = false;
Object value = null;
value = e1.getValue(f[0]);
if (value instanceof Integer) {
pass = true;
}
assertTrue("String expresion returned an Integer", pass);
pass = false;
value = e2.getValue(f[0]);
if (value instanceof String) {
pass = true;
}
assertTrue("Integer expresion returned a String", pass);
}
public void testSetupAndExtraction() throws Exception {
//this should move out to a more configurable system run from scripts
//but we can start with a set of hard coded tests
Feature[] f = sampleFeatures();
AttributeExpressionImpl e1 = new AttributeExpressionImpl(schema, "value");
AttributeExpressionImpl e2 = new AttributeExpressionImpl(schema, "name");
assertEquals(12d, ((Integer) e1.getValue(f[0])).doubleValue(), 0);
assertEquals(3d, ((Integer) e1.getValue(f[1])).doubleValue(), 0);
assertEquals(15d, ((Integer) e1.getValue(f[2])).doubleValue(), 0);
assertEquals("first", (String) e2.getValue(f[0]));
assertEquals("second", (String) e2.getValue(f[1]));
}
}
=====================================================================
Found a 53 line (342 tokens) duplication in the following files:
Starting at line 2438 of /home/tom/pmd/pmd-web/src/geotools2/geotools-src/lite-rendering/src/org/geotools/renderer/lite/LiteRenderer.java
Starting at line 296 of /home/tom/pmd/pmd-web/src/geotools2/geotools-src/renderer/src/org/geotools/renderer/j2d/SLDRenderedGeometries.java
double[] first = new double[2];
double[] previous = new double[2];
type = pi.currentSegment(coords);
first[0] = coords[0];
first[1] = coords[1];
previous[0] = coords[0];
previous[1] = coords[1];
if (LOGGER.isLoggable(Level.FINEST)) {
LOGGER.finest("starting at " + first[0] + "," + first[1]);
}
pi.next();
while (!pi.isDone()) {
type = pi.currentSegment(coords);
switch (type) {
case PathIterator.SEG_MOVETO:
// nothing to do?
if (LOGGER.isLoggable(Level.FINEST)) {
LOGGER.finest("moving to " + coords[0] + "," + coords[1]);
}
break;
case PathIterator.SEG_CLOSE:
// draw back to first from previous
coords[0] = first[0];
coords[1] = first[1];
if (LOGGER.isLoggable(Level.FINEST)) {
LOGGER.finest("closing from " + previous[0] + "," + previous[1] + " to "
+ coords[0] + "," + coords[1]);
}
// no break here - fall through to next section
case PathIterator.SEG_LINETO:
// draw from previous to coords
if (LOGGER.isLoggable(Level.FINEST)) {
LOGGER.finest("drawing from " + previous[0] + "," + previous[1] + " to "
+ coords[0] + "," + coords[1]);
}
double dx = coords[0] - previous[0];
double dy = coords[1] - previous[1];
double len = Math.sqrt((dx * dx) + (dy * dy)); // - imageWidth;
double theta = Math.atan2(dx, dy);
dx = (Math.sin(theta) * imageSize);
=====================================================================
Found a 100 line (337 tokens) duplication in the following files:
Starting at line 95 of /home/tom/pmd/pmd-web/src/geotools2/geotools-src/validation/src/org/geotools/validation/relate/CrossesIntegrity.java
Starting at line 96 of /home/tom/pmd/pmd-web/src/geotools2/geotools-src/validation/src/org/geotools/validation/relate/OverlapsIntegrity.java
public OverlapsIntegrity()
{
super();
usedIDs = new HashSet(); //TODO: remove me later, memory inefficient
}
/* (non-Javadoc)
* @see org.geotools.validation.IntegrityValidation#validate(java.util.Map, com.vividsolutions.jts.geom.Envelope, org.geotools.validation.ValidationResults)
*/
public boolean validate(Map layers, Envelope envelope,
ValidationResults results) throws Exception
{
LOGGER.finer("Starting test "+getName()+" ("+getClass().getName()+")" );
String typeRef1 = getGeomTypeRefA();
LOGGER.finer( typeRef1 +": looking up FeatureSource " );
FeatureSource geomSource1 = (FeatureSource) layers.get( typeRef1 );
LOGGER.finer( typeRef1 +": found "+ geomSource1.getSchema().getTypeName() );
String typeRef2 = getGeomTypeRefB();
if (typeRef2 == EMPTY || typeRef1.equals(typeRef2))
return validateSingleLayer(geomSource1, isExpected(), results, envelope);
else
{
LOGGER.finer( typeRef2 +": looking up FeatureSource " );
FeatureSource geomSource2 = (FeatureSource) layers.get( typeRef2 );
LOGGER.finer( typeRef2 +": found "+ geomSource2.getSchema().getTypeName() );
return validateMultipleLayers(geomSource1, geomSource2, isExpected(), results, envelope);
}
}
/**
* validateMultipleLayers Purpose:
*
* This validation tests for a geometry overlaps another geometry. * Uses JTS' Geometry.overlaps(Geometry) and Geometry.contains(Geometry)method. * The DE-9IM intersection matrix for overlaps is: * T*T***T** (for two points or two surfaces) * 1*T***T** (for two curves) * Contains DE-9IM intersection matrix is T*F**F***. *
* * Description:* The function filters the FeatureSources using the given bounding box. * It creates iterators over both filtered FeatureSources. It calls overlaps() and contains()using the * geometries in the FeatureSource layers. Tests the results of the method call against * the given expected results. Returns true if the returned results and the expected results * are true, false otherwise. * *
* * Author: bowens* This validation tests for a geometry crosses another geometry. * Uses JTS' Geometry.crosses(Geometry) method. * *
* * Description:* The function filters the FeatureSources using the given bounding box. * It creates iterators over both filtered FeatureSources. It calls intersects() using the * geometries in the FeatureSource layers. Tests the results of the method call against * the given expected results. Returns true if the returned results and the expected results * are true, false otherwise. * *
* * Author: bowens* This validation tests for a geometry crosses another geometry. * Uses JTS' Geometry.crosses(Geometry) method. * *
* * Description:* The function filters the FeatureSources using the given bounding box. * It creates iterators over both filtered FeatureSources. It calls relate() using the * geometries in the FeatureSource layers. Tests the results of the method call against * the given expected results. Returns true if the returned results and the expected results * are true, false otherwise. * * The following is taken from JTS documentation for Geometry.relate(): * "Returns true if the elements in the DE-9IM intersection matrix for the two Geometrys match the elements in intersectionPattern , which may be: * 0 * 1 * 2 * T ( = 0, 1 or 2) * F ( = -1) * * ( = -1, 0, 1 or 2) * For more information on the DE-9IM, see the OpenGIS Simple Features Specification." * * *
* * Author: bowenstrue if this method is invoked
* for augmenting {@link #table}, or false if
* it is invoked for making the table smaller.
*/
private void rehash(final boolean augmentation)
{
assert Thread.holdsLock(this);
assert valid();
final long currentTime = System.currentTimeMillis();
final int capacity = Math.max(Math.round(count/(LOAD_FACTOR/2)), count+MIN_CAPACITY);
if (augmentation ? (capacity<=table.length) :
(capacity>=table.length || currentTime-lastRehashTime* This validation tests for a geometry crosses another geometry. * Uses JTS' Geometry.crosses(Geometry) method. * The DE-9IM intersection matrix for crosses is * T*T****** (for a point and a curve, a point and an area or a line and an area) * 0******** (for two curves) *
* * Description:* The function filters the FeatureSources using the given bounding box. * It creates iterators over both filtered FeatureSources. It calls overlaps() and contains()using the * geometries in the FeatureSource layers. Tests the results of the method call against * the given expected results. Returns true if the returned results and the expected results * are true, false otherwise. * *
* * Author: bowens* Sets the priority level of this validation. This is set by the * programmer and is a measure of the expense of this plugin *
* * @return A made up priority for this validation. * * @see org.geotools.validation.Validation#getPriority() */ public int getPriority() { return PRIORITY_COMPLEX; } /** * Override validate. * ** Tests to see if a geometry intersects itself. It does not detect if a * segment of a LineString doubles back on itself for one segment, then * terminates. A different validation is needed to test overlapping. Uses * JTS' intersect routine. *
* * @param feature The Feature to be validated. * @param type The FeatureTypeInfo of the feature. * @param results The storage for error messages. * * @return True if the feature does not self intersect. * * @see org.geotools.validation.FeatureValidation#validate(org.geotools.feature.Feature, * org.geotools.feature.FeatureTypeInfo, * org.geotools.validation.ValidationResults) */ public boolean validate(Feature feature, FeatureType type, ValidationResults results) { LOGGER.setLevel(Level.ALL); LineString line = null; try { line = getDefaultLineString( feature ); } catch( ClassCastException unLine ){ results.error(feature,"Geometry is required to be a LineString"); System.out.println( feature.getID()+" name: "+getName() ); System.out.println( feature.getID()+" ref: "+getTypeRef() ); System.out.println( feature.getID()+" ref: "+getTypeRefs() ); } if (line == null) { // Ignore null geometry (user can check with nullZero ) return true; } if (line.getNumPoints() < 2) { results.warning(feature,"LineString contains too few points"); return false; } GeometryFactory gf = new GeometryFactory(); int numPoints = line.getNumPoints(); // break up the LineString into line segments LineString[] segments = new LineString[numPoints - 1]; for (int i = 0; i < (numPoints - 1); i++) { Coordinate[] coords = new Coordinate[] { line.getCoordinateN(i), line.getCoordinateN(i + 1) }; segments[i] = gf.createLineString(coords); } // intersect all of the line segments with each other for (int i = 0; i < segments.length; i++) // for each line segment { for (int j = 0; j < segments.length; j++) // intersect with every other line segment { if ((i != j) && ((i - 1) != j) && ((i + 1) != j)) // if they aren't the same segment ===================================================================== Found a 84 line (263 tokens) duplication in the following files: Starting at line 88 of /home/tom/pmd/pmd-web/src/geotools2/geotools-src/validation/src/org/geotools/validation/relate/RelateIntegrity.java Starting at line 99 of /home/tom/pmd/pmd-web/src/geotools2/geotools-src/validation/src/org/geotools/validation/relate/CrossesIntegrity.java } /* (non-Javadoc) * @see org.geotools.validation.IntegrityValidation#validate(java.util.Map, com.vividsolutions.jts.geom.Envelope, org.geotools.validation.ValidationResults) */ public boolean validate(Map layers, Envelope envelope, ValidationResults results) throws Exception { LOGGER.finer("Starting test "+getName()+" ("+getClass().getName()+")" ); String typeRef1 = getGeomTypeRefA(); LOGGER.finer( typeRef1 +": looking up FeatureSource " ); FeatureSource geomSource1 = (FeatureSource) layers.get( typeRef1 ); LOGGER.finer( typeRef1 +": found "+ geomSource1.getSchema().getTypeName() ); String typeRef2 = getGeomTypeRefB(); if (typeRef2 == EMPTY || typeRef1.equals(typeRef2)) return validateSingleLayer(geomSource1, isExpected(), results, envelope); else { LOGGER.finer( typeRef2 +": looking up FeatureSource " ); FeatureSource geomSource2 = (FeatureSource) layers.get( typeRef2 ); LOGGER.finer( typeRef2 +": found "+ geomSource2.getSchema().getTypeName() ); return validateMultipleLayers(geomSource1, geomSource2, isExpected(), results, envelope); } } /** * validateMultipleLayers Purpose:* This validation tests for a geometry crosses another geometry. * Uses JTS' Geometry.crosses(Geometry) method. * The DE-9IM intersection matrix for crosses is * T*T****** (for a point and a curve, a point and an area or a line and an area) * 0******** (for two curves) *
* * Description:* The function filters the FeatureSources using the given bounding box. * It creates iterators over both filtered FeatureSources. It calls overlaps() and contains()using the * geometries in the FeatureSource layers. Tests the results of the method call against * the given expected results. Returns true if the returned results and the expected results * are true, false otherwise. * *
* * Author: bowens* This validation tests for a geometry that intersects with itself. * Uses JTS' Geometry.intersects(Geometry) method. *
* * Description:* The function filters the FeatureSource using the given bounding box. * It creates iterators over the filtered FeatureSource. It calls intersects() using the * geometries in the FeatureSource layer. Tests the results of the method call against * the given expected results. Returns true if the returned results and the expected results * are true, false otherwise. * *
* * Author: bowensnull for the default locale.
* @return Resources in the given locale.
* @throws MissingResourceException if resources can't be found.
*/
public static Resources getResources(Locale locale) throws MissingResourceException {
if (locale==null) {
locale = Locale.getDefault();
}
return (Resources) getBundle(Resources.class.getName(), locale);
/*
* We rely on cache capability of {@link java.util.ResourceBundle}.
*/
}
/**
* Gets a string for the given key from this resource bundle or one of its
* parents.
*
* @param key The key for the desired string.
* @return The string for the given key.
* @throws MissingResourceException If no object for the given key can be
* found.
*/
public static String format(final int key) throws MissingResourceException {
return getResources(null).getString(key);
}
/**
* Gets a string for the given key are replace all occurence of "{0}"
* with values of arg0.
*
* @param key The key for the desired string.
* @param arg0 Value to substitute to "{0}".
* @return The formatted string for the given key.
* @throws MissingResourceException If no object for the given key can be
* found.
*/
public static String format(final int key,
final Object arg0) throws MissingResourceException {
return getResources(null).getString(key, arg0);
}
/**
* Gets a string for the given key are replace all occurence of "{0}",
* "{1}", with values of arg0, arg1.
*
* @param key The key for the desired string.
* @param arg0 Value to substitute to "{0}".
* @param arg1 Value to substitute to "{1}".
* @return The formatted string for the given key.
* @throws MissingResourceException If no object for the given key can be
* found.
*/
public static String format(final int key,
final Object arg0,
final Object arg1) throws MissingResourceException {
return getResources(null).getString(key, arg0, arg1);
}
/**
* Gets a string for the given key are replace all occurence of "{0}",
* "{1}", with values of arg0, arg1, etc.
*
* @param key The key for the desired string.
* @param arg0 Value to substitute to "{0}".
* @param arg1 Value to substitute to "{1}".
* @param arg2 Value to substitute to "{2}".
* @return The formatted string for the given key.
* @throws MissingResourceException If no object for the given key can be found.
*/
public static String format(final int key,
final Object arg0,
final Object arg1,
final Object arg2) throws MissingResourceException {
return getResources(null).getString(key, arg0, arg1, arg2);
}
=====================================================================
Found a 29 line (209 tokens) duplication in the following files:
Starting at line 96 of /home/tom/pmd/pmd-web/src/geotools2/geotools-src/shapefile/src/org/geotools/data/shapefile/ShapefileDataStore.java
Starting at line 77 of /home/tom/pmd/pmd-web/src/geotools2/geotools-src/shapefile/src/org/geotools/data/shapefile/ShapefileDataSource.java
public ShapefileDataSource(URL url) throws java.net.MalformedURLException {
String filename = null;
if (url == null) {
throw new NullPointerException("Null URL for ShapefileDataSource");
}
try {
filename = java.net.URLDecoder.decode(url.toString(),"US-ASCII");
} catch (java.io.UnsupportedEncodingException use) {
throw new java.net.MalformedURLException(
"Unable to decode " + url + " cause " + use.getMessage()
);
}
String shpext = ".shp";
String dbfext = ".dbf";
String shxext = ".shx";
if(filename.endsWith(shpext) || filename.endsWith(dbfext) || filename.endsWith(shxext)) {
filename = filename.substring(0, filename.length() - 4);
} else if(filename.endsWith(".SHP") || filename.endsWith(".DBF") || filename.endsWith(".SHX")) {
filename = filename.substring(0, filename.length() - 4);
shpext = ".SHP";
dbfext = ".DBF";
shxext = ".SHX";
}
shpURL = new URL(filename + shpext);
dbfURL = new URL(filename + dbfext);
shxURL = new URL(filename + shxext);
=====================================================================
Found a 43 line (207 tokens) duplication in the following files:
Starting at line 62 of /home/tom/pmd/pmd-web/src/geotools2/geotools-src/validation/src/org/geotools/validation/spatial/LineCoveredByPolygonBoundaryValidation.java
Starting at line 81 of /home/tom/pmd/pmd-web/src/geotools2/geotools-src/validation/src/org/geotools/validation/spatial/LineCoveredByPolygonValidation.java
}
/**
* Check that lineTypeRef is convered by polygonTypeRef.
*
* * Detailed description... *
* * @param layers Map of FeatureSource by "dataStoreID:typeName" * @param envelope The bounding box that encloses the unvalidated data * @param results Used to coallate results information * * @returntrue if all the features pass this test.
*
* @throws Exception DOCUMENT ME!
*/
public boolean validate(Map layers, Envelope envelope,
ValidationResults results) throws Exception {
boolean r = true;
FeatureSource fsLine = (FeatureSource) layers.get(getLineTypeRef());
FeatureResults frLine = fsLine.getFeatures();
FeatureCollection fcLine = frLine.collection();
FeatureIterator fLine = fcLine.features();
FeatureSource fsPoly = (FeatureSource) layers.get(getRestrictedPolygonTypeRef());
FeatureResults frPoly = fsPoly.getFeatures();
FeatureCollection fcPoly = frPoly.collection();
while(fLine.hasNext()){
Feature line = fLine.next();
FeatureIterator fPoly = fcPoly.features();
Geometry lineGeom = line.getDefaultGeometry();
if(envelope.contains(lineGeom.getEnvelopeInternal())){
// check for valid comparison
if(LineString.class.isAssignableFrom(lineGeom.getClass())){
while(fPoly.hasNext()){
Feature poly = fPoly.next();
Geometry polyGeom = poly.getDefaultGeometry();
if(envelope.contains(polyGeom.getEnvelopeInternal())){
if(Polygon.class.isAssignableFrom(polyGeom.getClass())){
=====================================================================
Found a 42 line (207 tokens) duplication in the following files:
Starting at line 492 of /home/tom/pmd/pmd-web/src/geotools2/geotools-src/postgis/src/org/geotools/data/postgis/PostgisDataSource.java
Starting at line 661 of /home/tom/pmd/pmd-web/src/geotools2/geotools-src/postgis/src/org/geotools/data/postgis/PostgisFeatureStore.java
throws IOException {
//one to one relationship for now, so typeName is not used.
//String tableName = query.getTypeName();
tableName = this.tableName;
boolean useLimit = (unpacker.getUnSupported() == null);
Filter filter = unpacker.getSupported();
LOGGER.fine("Filter in making sql is " + filter);
StringBuffer sqlStatement = new StringBuffer("SELECT ");
sqlStatement.append(fidColumn);
AttributeType[] attributeTypes = getAttTypes(query);
int numAttributes = attributeTypes.length;
LOGGER.finer("making sql for " + numAttributes + " attributes");
for (int i = 0; i < numAttributes; i++) {
String curAttName = attributeTypes[i].getName();
if (Geometry.class.isAssignableFrom(attributeTypes[i].getType())) {
sqlStatement.append(", AsText(force_2d(\"" + curAttName
+ "\"))");
//REVISIT, see getIdColumn note.
} else if (fidColumn.equals(curAttName)) {
//do nothing, already covered by fid
} else {
sqlStatement.append(", \"" + curAttName + "\"");
}
}
String where = "";
if (filter != null) {
try {
where = encoder.encode(filter);
} catch (SQLEncoderException sqle) {
String message = "Encoder error" + sqle.getMessage();
LOGGER.warning(message);
throw new DataSourceException(message, sqle);
}
}
=====================================================================
Found a 44 line (205 tokens) duplication in the following files:
Starting at line 147 of /home/tom/pmd/pmd-web/src/geotools2/geotools-src/filter/src/org/geotools/filter/parser/ParseException.java
Starting at line 40 of /home/tom/pmd/pmd-web/src/geotools2/geotools-src/filter/src/org/geotools/filter/parser/TokenMgrError.java
protected static final String addEscapes(String str) {
StringBuffer retval = new StringBuffer();
char ch;
for (int i = 0; i < str.length(); i++) {
switch (str.charAt(i))
{
case 0 :
continue;
case '\b':
retval.append("\\b");
continue;
case '\t':
retval.append("\\t");
continue;
case '\n':
retval.append("\\n");
continue;
case '\f':
retval.append("\\f");
continue;
case '\r':
retval.append("\\r");
continue;
case '\"':
retval.append("\\\"");
continue;
case '\'':
retval.append("\\\'");
continue;
case '\\':
retval.append("\\\\");
continue;
default:
if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) {
String s = "0000" + Integer.toString(ch, 16);
retval.append("\\u" + s.substring(s.length() - 4, s.length()));
} else {
retval.append(ch);
}
continue;
}
}
return retval.toString();
}
=====================================================================
Found a 98 line (202 tokens) duplication in the following files:
Starting at line 49 of /home/tom/pmd/pmd-web/src/geotools2/geotools-src/gui/src/org/geotools/resources/gui/Resources.java
Starting at line 49 of /home/tom/pmd/pmd-web/src/geotools2/geotools-src/renderer/src/org/geotools/resources/renderer/Resources.java
public class Resources extends ResourceBundle {
/**
* Construct a resource bundle using english language.
* This is the default when no resource are available
* in user language.
*/
public Resources() {
super(Resources_en.FILEPATH);
}
/**
* Construct a resource bundle
* using the specified UTF8 file.
*/
Resources(final String filepath) {
super(filepath);
}
/**
* Returns resources in the given locale.
*
* @param local The locale, or null for the default locale.
* @return Resources in the given locale.
* @throws MissingResourceException if resources can't be found.
*/
public static Resources getResources(Locale locale) throws MissingResourceException {
if (locale==null) {
locale = Locale.getDefault();
}
return (Resources) getBundle(Resources.class.getName(), locale);
/*
* We rely on cache capability of {@link java.util.ResourceBundle}.
*/
}
/**
* Gets a string for the given key from this resource bundle or one of its
* parents.
*
* @param key The key for the desired string.
* @return The string for the given key.
* @throws MissingResourceException If no object for the given key can be
* found.
*/
public static String format(final int key) throws MissingResourceException {
return getResources(null).getString(key);
}
/**
* Gets a string for the given key are replace all occurence of "{0}"
* with values of arg0.
*
* @param key The key for the desired string.
* @param arg0 Value to substitute to "{0}".
* @return The formatted string for the given key.
* @throws MissingResourceException If no object for the given key can be
* found.
*/
public static String format(final int key,
final Object arg0) throws MissingResourceException {
return getResources(null).getString(key, arg0);
}
/**
* Gets a string for the given key are replace all occurence of "{0}",
* "{1}", with values of arg0, arg1.
*
* @param key The key for the desired string.
* @param arg0 Value to substitute to "{0}".
* @param arg1 Value to substitute to "{1}".
* @return The formatted string for the given key.
* @throws MissingResourceException If no object for the given key can be
* found.
*/
public static String format(final int key,
final Object arg0,
final Object arg1) throws MissingResourceException {
return getResources(null).getString(key, arg0, arg1);
}
/**
* Gets a string for the given key are replace all occurence of "{0}",
* "{1}", with values of arg0, arg1, etc.
*
* @param key The key for the desired string.
* @param arg0 Value to substitute to "{0}".
* @param arg1 Value to substitute to "{1}".
* @param arg2 Value to substitute to "{2}".
* @return The formatted string for the given key.
* @throws MissingResourceException If no object for the given key can be found.
*/
public static String format(final int key,
final Object arg0,
final Object arg1,
final Object arg2) throws MissingResourceException {
return getResources(null).getString(key, arg0, arg1, arg2);
}
}
=====================================================================
Found a 33 line (201 tokens) duplication in the following files:
Starting at line 396 of /home/tom/pmd/pmd-web/src/geotools2/geotools-src/rendering-styling/tests/unit/org/geotools/styling/RenderingGridCoverageTest.java
Starting at line 330 of /home/tom/pmd/pmd-web/src/geotools2/geotools-src/rendering-styling/tests/unit/org/geotools/styling/TextStyleTest.java
Raster data = image1.getData();
Raster data2 = image2.getData();
int[] pixel1 = null;
int[] pixel2 = null;
boolean isBlack = false;
for (int x = 0; x < data.getWidth(); x++) {
for (int y = 0; y < data.getHeight(); y++) {
pixel1 = data.getPixel(x, y, pixel1);
pixel2 = data2.getPixel(x, y, pixel2);
if ((notBlack(pixel1)) && (notBlack(pixel2))) { //Since text is black and fonts are not stable across platforms, ignore pixels where at least one is black.
for (int band = 0; band < data2.getNumBands(); band++) {
assertEquals("mismatch in image comparison at (x: " + x + " y: " + y
+ " band: " + band + ")", pixel1[band], pixel2[band]);
}
}
}
}
}
private boolean notBlack(int[] pixel) {
boolean isBlack = true;
int x = 0;
while (isBlack && (x < pixel.length)) {
isBlack = (pixel[x] == 0);
x++;
}
return !(isBlack);
}
=====================================================================
Found a 50 line (198 tokens) duplication in the following files:
Starting at line 56 of /home/tom/pmd/pmd-web/src/geotools2/geotools-src/validation/src/org/geotools/validation/spatial/PointCoveredByLineValidation.java
Starting at line 57 of /home/tom/pmd/pmd-web/src/geotools2/geotools-src/validation/src/org/geotools/validation/spatial/PointCoveredByEndPointOfLineValidation.java
public PointCoveredByEndPointOfLineValidation() {
super();
}
/**
* Ensure Point is covered by a Line end point.
*
*
*
* @param layers a HashMap of key="TypeName" value="FeatureSource"
* @param envelope The bounding box of modified features
* @param results Storage for the error and warning messages
*
* @return True if no features intersect. If they do then the validation
* failed.
*
* @throws Exception DOCUMENT ME!
*
* @see org.geotools.validation.IntegrityValidation#validate(java.util.Map,
* com.vividsolutions.jts.geom.Envelope,
* org.geotools.validation.ValidationResults)
*/
public boolean validate(Map layers, Envelope envelope,
ValidationResults results) throws Exception {
FeatureSource lineSource = (FeatureSource) layers.get(getRestrictedLineTypeRef());
FeatureSource pointSource = (FeatureSource) layers.get(getPointTypeRef());
Object[] points = pointSource.getFeatures().collection().toArray();
Object[] lines = lineSource.getFeatures().collection().toArray();
if (!envelope.contains(pointSource.getBounds())) {
results.error((Feature) points[0],
"Point Feature Source is not contained within the Envelope provided.");
return false;
}
if (!envelope.contains(lineSource.getBounds())) {
results.error((Feature) lines[0],
"Line Feature Source is not contained within the Envelope provided.");
return false;
}
for (int i = 0; i < lines.length; i++) {
Feature tmp = (Feature) lines[i];
Geometry gt = tmp.getDefaultGeometry();
if (gt instanceof LineString) {
LineString ls = (LineString) gt;
=====================================================================
Found a 28 line (197 tokens) duplication in the following files:
Starting at line 200 of /home/tom/pmd/pmd-web/src/geotools2/geotools-src/filter/tests/unit/org/geotools/filter/DOMParserTest.java
Starting at line 234 of /home/tom/pmd/pmd-web/src/geotools2/geotools-src/filter/tests/unit/org/geotools/filter/DOMParserTest.java
public Filter parseDocumentFirst(String uri) throws Exception {
Filter filter = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document dom = db.parse(uri);
LOGGER.fine("parsing " + uri);
// first grab a filter node
NodeList nodes = dom.getElementsByTagName("Filter");
for (int j = 0; j < nodes.getLength(); j++) {
Element filterNode = (Element) nodes.item(j);
NodeList list = filterNode.getChildNodes();
Node child = null;
for (int i = 0; i < list.getLength(); i++) {
child = list.item(i);
if ((child == null)
|| (child.getNodeType() != Node.ELEMENT_NODE)) {
continue;
}
filter = FilterDOMParser.parseFilter(child);
assertNotNull("Null filter returned", filter);
LOGGER.finer("filter: " + filter.getClass().toString());
LOGGER.fine("parsed: " + filter.toString());
LOGGER.finer("result " + filter.contains(testFeature));
=====================================================================
Found a 40 line (192 tokens) duplication in the following files:
Starting at line 446 of /home/tom/pmd/pmd-web/src/geotools2/geotools-src/wmsserver/src/org/geotools/wms/WMSServlet.java
Starting at line 667 of /home/tom/pmd/pmd-web/src/geotools2/geotools-src/wmsserver/src/org/geotools/wms/WMSServlet.java
} catch (WMSException wmsexp) {
doException(wmsexp.getCode(), wmsexp.getMessage(), request,
response, exceptions);
return;
} catch (Exception exp) {
doException(null,
"Unknown exception : " + exp + " : " + exp.getStackTrace()[0] +
exp.getMessage(), request, response, exceptions);
return;
}
// Write the response
response.setContentType(format);
OutputStream out = response.getOutputStream();
// avoid caching in browser
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
try {
formatImageOutputStream(format, image, out);
} catch (Exception exp) {
exp.printStackTrace();
LOGGER.severe(
"Unable to complete image generation after response started : " +
exp + exp.getMessage());
if (exp instanceof SecurityException) {
response.sendError(500,
"Image generation failed because of: " +
exp.getStackTrace()[0] +
" JAI may not have 'write' and 'delete' permissions in temp folder");
} else {
response.sendError(500,
"Image generation failed because of: " +
exp.getStackTrace()[0] + "Check JAI configuration");
}
}//finally{
=====================================================================
Found a 44 line (188 tokens) duplication in the following files:
Starting at line 644 of /home/tom/pmd/pmd-web/src/geotools2/geotools-src/resources/src/org/geotools/resources/NumberParser.java
Starting at line 702 of /home/tom/pmd/pmd-web/src/geotools2/geotools-src/resources/src/org/geotools/resources/NumberParser.java
low = (b < m );
high = (b+m > tens );
if ( q >= 10 ){
// bummer, dude
throw new RuntimeException( "Assertion botch: excessivly large digit "+q);
} else if ( (q == 0) && ! high ){
// oops. Usually ignore leading zero.
decExp--;
} else {
digits[ndigit++] = (char)('0' + q);
}
/*
* HACK! Java spec sez that we always have at least
* one digit after the . in either F- or E-form output.
* Thus we will need more than one digit if we're using
* E-form
*/
if ( decExp <= -3 || decExp >= 8 ){
high = low = false;
}
while( ! low && ! high ){
q = (int) ( b / s );
b = 10 * ( b % s );
m *= 10;
if ( q >= 10 ){
// bummer, dude
throw new RuntimeException( "Assertion botch: excessivly large digit "+q);
}
if ( m > 0L ){
low = (b < m );
high = (b+m > tens );
} else {
// hack -- m might overflow!
// in this case, it is certainly > b,
// which won't
// and b+m > tens, too, since that has overflowed
// either!
low = true;
high = true;
}
digits[ndigit++] = (char)('0' + q);
}
lowDigitDifference = (b<<1) - tens;
}
=====================================================================
Found a 32 line (186 tokens) duplication in the following files:
Starting at line 328 of /home/tom/pmd/pmd-web/src/geotools2/geotools-src/shapefile/tests/unit/org/geotools/data/shapefile/ShapefileDataStoreTest.java
Starting at line 217 of /home/tom/pmd/pmd-web/src/geotools2/geotools-src/shapefile/tests/unit/org/geotools/data/shapefile/ShapefileDataSourceTest.java
FeatureCollection fc = s.getFeatures();
FeatureIterator fci = fc.features();
// verify
while (fci.hasNext()) {
Feature f = fci.next();
Geometry fromShape = f.getDefaultGeometry();
if (fromShape instanceof GeometryCollection) {
if ( ! (geom instanceof GeometryCollection) ) {
fromShape = ((GeometryCollection)fromShape).getGeometryN(0);
}
}
try {
Coordinate[] c1 = geom.getCoordinates();
Coordinate[] c2 = fromShape.getCoordinates();
for (int cc = 0, ccc = c1.length; cc < ccc; cc++) {
//System.out.println(c1[cc] + "," + c2[cc]);
if (d3)
assertTrue(c1[cc].equals3D(c2[cc]));
else
assertTrue(c1[cc].equals2D(c2[cc]));
}
} catch (Throwable t) {
fail("Bogus : " + Arrays.asList(geom.getCoordinates()) + " : " + Arrays.asList(fromShape.getCoordinates()));
}
}
tmpFile.delete();
}
=====================================================================
Found a 91 line (186 tokens) duplication in the following files:
Starting at line 56 of /home/tom/pmd/pmd-web/src/geotools2/geotools-src/gui/src/org/geotools/resources/gui/Resources.java
Starting at line 59 of /home/tom/pmd/pmd-web/src/geotools2/geotools-src/resources/src/org/geotools/resources/rsc/Resources.java
null);
}
/**
* Construct a resource bundle
* using the specified UTF8 file.
*/
Resources(final String filepath) {
super(filepath);
}
/**
* Returns resources in the given locale.
*
* @param local The locale, or null for the default locale.
* @return Resources in the given locale.
* @throws MissingResourceException if resources can't be found.
*/
public static Resources getResources(Locale locale) throws MissingResourceException {
if (locale==null) {
locale = Locale.getDefault();
}
return (Resources) getBundle(Resources.class.getName(), locale);
/*
* We rely on cache capability of {@link java.util.ResourceBundle}.
*/
}
/**
* Gets a string for the given key from this resource bundle or one of its
* parents.
*
* @param key The key for the desired string.
* @return The string for the given key.
* @throws MissingResourceException If no object for the given key can be
* found.
*/
public static String format(final int key) throws MissingResourceException {
return getResources(null).getString(key);
}
/**
* Gets a string for the given key are replace all occurence of "{0}"
* with values of arg0.
*
* @param key The key for the desired string.
* @param arg0 Value to substitute to "{0}".
* @return The formatted string for the given key.
* @throws MissingResourceException If no object for the given key can be
* found.
*/
public static String format(final int key,
final Object arg0) throws MissingResourceException {
return getResources(null).getString(key, arg0);
}
/**
* Gets a string for the given key are replace all occurence of "{0}",
* "{1}", with values of arg0, arg1.
*
* @param key The key for the desired string.
* @param arg0 Value to substitute to "{0}".
* @param arg1 Value to substitute to "{1}".
* @return The formatted string for the given key.
* @throws MissingResourceException If no object for the given key can be
* found.
*/
public static String format(final int key,
final Object arg0,
final Object arg1) throws MissingResourceException {
return getResources(null).getString(key, arg0, arg1);
}
/**
* Gets a string for the given key are replace all occurence of "{0}",
* "{1}", with values of arg0, arg1, etc.
*
* @param key The key for the desired string.
* @param arg0 Value to substitute to "{0}".
* @param arg1 Value to substitute to "{1}".
* @param arg2 Value to substitute to "{2}".
* @return The formatted string for the given key.
* @throws MissingResourceException If no object for the given key can be found.
*/
public static String format(final int key,
final Object arg0,
final Object arg1,
final Object arg2) throws MissingResourceException {
return getResources(null).getString(key, arg0, arg1, arg2);
}
}
=====================================================================
Found a 14 line (186 tokens) duplication in the following files:
Starting at line 96 of /home/tom/pmd/pmd-web/src/geotools2/geotools-src/lite-rendering/tests/unit/org/geotools/renderer/lite/LiteShapeTest.java
Starting at line 549 of /home/tom/pmd/pmd-web/src/geotools2/geotools-src/rendering-styling/tests/unit/org/geotools/styling/RenderStyleTest.java
private Polygon makeSamplePolygon(final GeometryFactory geomFac, double xoff, double yoff) {
Coordinate[] polygonCoordinates = new Coordinate[10];
polygonCoordinates[0] = new Coordinate(70 + xoff, 70 + yoff);
polygonCoordinates[1] = new Coordinate(60 + xoff, 90 + yoff);
polygonCoordinates[2] = new Coordinate(60 + xoff, 110 + yoff);
polygonCoordinates[3] = new Coordinate(70 + xoff, 120 + yoff);
polygonCoordinates[4] = new Coordinate(90 + xoff, 110 + yoff);
polygonCoordinates[5] = new Coordinate(110 + xoff, 120 + yoff);
polygonCoordinates[6] = new Coordinate(130 + xoff, 110 + yoff);
polygonCoordinates[7] = new Coordinate(130 + xoff, 90 + yoff);
polygonCoordinates[8] = new Coordinate(110 + xoff, 70 + yoff);
polygonCoordinates[9] = new Coordinate(70 + xoff, 70 + yoff);
try {
=====================================================================
Found a 92 line (185 tokens) duplication in the following files:
Starting at line 56 of /home/tom/pmd/pmd-web/src/geotools2/geotools-src/gui/src/org/geotools/resources/gui/Resources.java
Starting at line 59 of /home/tom/pmd/pmd-web/src/geotools2/geotools-src/gcs-coverage/src/org/geotools/resources/gcs/Resources.java
null);
}
/**
* Construct a resource bundle
* using the specified UTF8 file.
*/
Resources(final String filepath) {
super(filepath);
}
/**
* Returns resources in the given locale.
*
* @param local The locale, or null for the default locale.
* @return Resources in the given locale.
* @throws MissingResourceException if resources can't be found.
*/
public static Resources getResources(Locale locale) throws MissingResourceException {
if (locale==null) {
locale = Locale.getDefault();
}
return (Resources) getBundle(Resources.class.getName(), locale);
/*
* We rely on cache capability of {@link java.util.ResourceBundle}.
*/
}
/**
* Gets a string for the given key from this resource bundle or one of its parents.
*
* @param key The key for the desired string.
* @return The string for the given key.
* @throws MissingResourceException If no object for the given key can be found.
*/
public static String format(final int key) throws MissingResourceException {
return getResources(null).getString(key);
}
/**
* Gets a string for the given key are replace all occurence of "{0}"
* with values of arg0.
*
* @param key The key for the desired string.
* @param arg0 Value to substitute to "{0}".
* @return The formatted string for the given key.
* @throws MissingResourceException If no object for the given key can be found.
*/
public static String format(final int key,
final Object arg0)
throws MissingResourceException
{
return getResources(null).getString(key, arg0);
}
/**
* Gets a string for the given key are replace all occurence of "{0}",
* "{1}", with values of arg0, arg1.
*
* @param key The key for the desired string.
* @param arg0 Value to substitute to "{0}".
* @param arg1 Value to substitute to "{1}".
* @return The formatted string for the given key.
* @throws MissingResourceException If no object for the given key can be found.
*/
public static String format(final int key,
final Object arg0,
final Object arg1)
throws MissingResourceException
{
return getResources(null).getString(key, arg0, arg1);
}
/**
* Gets a string for the given key are replace all occurence of "{0}",
* "{1}", with values of arg0, arg1, etc.
*
* @param key The key for the desired string.
* @param arg0 Value to substitute to "{0}".
* @param arg1 Value to substitute to "{1}".
* @param arg2 Value to substitute to "{2}".
* @return The formatted string for the given key.
* @throws MissingResourceException If no object for the given key can be found.
*/
public static String format(final int key,
final Object arg0,
final Object arg1,
final Object arg2)
throws MissingResourceException
{
return getResources(null).getString(key, arg0, arg1, arg2);
}
=====================================================================
Found a 39 line (177 tokens) duplication in the following files:
Starting at line 79 of /home/tom/pmd/pmd-web/src/geotools2/geotools-src/gmldatasource/src/org/geotools/gml/TestParser.java
Starting at line 46 of /home/tom/pmd/pmd-web/src/geotools2/geotools-src/validation/tests/unit/org/geotools/validation/LakesValidationTest.java
LakesTestHandler contentHandler = new LakesTestHandler();
GMLFilterGeometry geometryFilter = new GMLFilterGeometry(contentHandler);
GMLFilterDocument documentFilter = new GMLFilterDocument(geometryFilter);
XMLReader parser = XMLReaderFactory.createXMLReader(
"org.apache.xerces.parsers.SAXParser");
parser.setContentHandler(documentFilter);
parser.parse(uri);
} catch (IOException e) {
System.out.println("Error reading uri: " + uri);
} catch (SAXException e) {
System.out.println("Error in parsing: " + e.getMessage());
}
}
public static void parseFeatures(String uri) {
System.out.println("Parsing the flat feature collection in this GML "
+ "resource:" + uri);
try {
GMLDataSource data = new GMLDataSource(uri);
FeatureCollection featureCollection = data.getFeatures(Query.ALL);
Iterator i = featureCollection.iterator();
while (i.hasNext()) {
System.out.println("Parsed feature is ... " + i.next());
}
} catch (DataSourceException e) {
System.out.println(
"TestParser->parseFeatures DataSourceException: "
+ e.toString());
}
//parsedFeatures.
// chains all the appropriate filters together (in correct order)
// and initiates parsing
}
}
=====================================================================
Found a 20 line (168 tokens) duplication in the following files:
Starting at line 78 of /home/tom/pmd/pmd-web/src/geotools2/geotools-src/lite-rendering/tests/unit/org/geotools/renderer/lite/LiteShapeTest.java
Starting at line 530 of /home/tom/pmd/pmd-web/src/geotools2/geotools-src/rendering-styling/tests/unit/org/geotools/styling/RenderStyleTest.java
return !(isBlack);
}
private LineString makeSampleLineString(final GeometryFactory geomFac, double xoff, double yoff) {
Coordinate[] linestringCoordinates = new Coordinate[8];
linestringCoordinates[0] = new Coordinate(50.0d + xoff, 50.0d + yoff);
linestringCoordinates[1] = new Coordinate(60.0d + xoff, 50.0d + yoff);
linestringCoordinates[2] = new Coordinate(60.0d + xoff, 60.0d + yoff);
linestringCoordinates[3] = new Coordinate(70.0d + xoff, 60.0d + yoff);
linestringCoordinates[4] = new Coordinate(70.0d + xoff, 70.0d + yoff);
linestringCoordinates[5] = new Coordinate(80.0d + xoff, 70.0d + yoff);
linestringCoordinates[6] = new Coordinate(80.0d + xoff, 80.0d + yoff);
linestringCoordinates[7] = new Coordinate(130.0d + xoff, 300.0d + yoff);
LineString line = geomFac.createLineString(linestringCoordinates);
return line;
}
private Polygon makeSamplePolygon(final GeometryFactory geomFac, double xoff, double yoff) {
=====================================================================
Found a 24 line (165 tokens) duplication in the following files:
Starting at line 1544 of /home/tom/pmd/pmd-web/src/geotools2/geotools-src/lite-rendering/src/org/geotools/renderer/lite/LiteRenderer.java
Starting at line 1612 of /home/tom/pmd/pmd-web/src/geotools2/geotools-src/lite-rendering/src/org/geotools/renderer/lite/LiteRenderer.java
float radius = ((Number) halo.getRadius().getValue(feature)).floatValue();
Point2D mapCentre = new java.awt.geom.Point2D.Double(x, y);
Point2D graphicCentre = new java.awt.geom.Point2D.Double();
temp.transform(mapCentre, graphicCentre);
labelAT.translate(graphicCentre.getX(), graphicCentre.getY());
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.finer("rotation " + rotation);
}
double shearY = temp.getShearY();
double scaleY = temp.getScaleY();
double scaleX = temp.getScaleX();
double originalRotation = Math.atan(shearY / scaleY);
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.finer("originalRotation " + originalRotation);
}
labelAT.rotate(rotation - originalRotation);
double xToyRatio = Math.abs(scaleX / scaleY);
labelAT.scale(xToyRatio, 1.0 / xToyRatio);
=====================================================================
Found a 22 line (165 tokens) duplication in the following files:
Starting at line 1378 of /home/tom/pmd/pmd-web/src/geotools2/geotools-src/lite-rendering/src/org/geotools/renderer/lite/LiteRenderer.java
Starting at line 1409 of /home/tom/pmd/pmd-web/src/geotools2/geotools-src/lite-rendering/src/org/geotools/renderer/lite/LiteRenderer.java
String reqStyle = (String) fonts[k].getFontStyle().getValue(feature);
if (fontStyleLookup.containsKey(reqStyle)) {
styleCode = ((Integer) fontStyleLookup.get(reqStyle))
.intValue();
} else {
styleCode = java.awt.Font.PLAIN;
}
String reqWeight = (String) fonts[k].getFontWeight().getValue(feature);
if (reqWeight.equalsIgnoreCase("Bold")) {
styleCode = styleCode | java.awt.Font.BOLD;
}
if ((fonts[k].getFontSize() == null)
|| (fonts[k].getFontSize().getValue(feature) == null)) {
size = 10;
} else {
size = ((Number) fonts[k].getFontSize().getValue(feature))
.intValue();
}
=====================================================================
Found a 41 line (163 tokens) duplication in the following files:
Starting at line 254 of /home/tom/pmd/pmd-web/src/geotools2/geotools-src/shapefile/tests/unit/org/geotools/data/shapefile/ShapefileDataStoreTest.java
Starting at line 155 of /home/tom/pmd/pmd-web/src/geotools2/geotools-src/shapefile/tests/unit/org/geotools/data/shapefile/ShapefileDataSourceTest.java
tmpFile.delete();
}
public void testGeometriesWriting() throws Exception {
String[] wktResources = new String[] {
"point",
"multipoint",
"line",
"multiline",
"polygon",
"multipolygon"
};
PrecisionModel pm = new PrecisionModel();
for (int i = 0; i < wktResources.length; i++) {
Geometry geom = readGeometry(wktResources[i]);
String testName = wktResources[i];
try {
runWriteReadTest(geom,false);
make3D(geom);
testName += "3d";
runWriteReadTest(geom,true);
} catch (Throwable e) {
throw new Exception("Error in " + testName,e);
}
}
}
private void make3D(Geometry g) {
Coordinate[] c = g.getCoordinates();
for (int i = 0, ii = c.length; i < ii; i++) {
c[i].z = 42 + i;
}
}
private void runWriteReadTest(Geometry geom,boolean d3) throws Exception {
=====================================================================
Found a 24 line (160 tokens) duplication in the following files:
Starting at line 103 of /home/tom/pmd/pmd-web/src/geotools2/geotools-src/lite-rendering/tests/unit/org/geotools/renderer/lite/Rendering2DTest.java
Starting at line 97 of /home/tom/pmd/pmd-web/src/geotools2/geotools-src/wmsserver/tests/unit/org/geotools/renderer/LegendImageGeneratorTest.java
StyleFactory sFac = StyleFactory.createStyleFactory();
//The following is complex, and should be built from
//an SLD document and not by hand
PointSymbolizer pointsym = sFac.createPointSymbolizer();
pointsym.setGraphic(sFac.getDefaultGraphic());
LineSymbolizer linesym = sFac.createLineSymbolizer();
Stroke myStroke = sFac.getDefaultStroke();
myStroke.setColor(filterFactory.createLiteralExpression("#0000ff"));
myStroke.setWidth(filterFactory.createLiteralExpression(new Integer(5)));
LOGGER.info("got new Stroke " + myStroke);
linesym.setStroke(myStroke);
PolygonSymbolizer polysym = sFac.createPolygonSymbolizer();
Fill myFill = sFac.getDefaultFill();
myFill.setColor(filterFactory.createLiteralExpression("#ff0000"));
polysym.setFill(myFill);
polysym.setStroke(sFac.getDefaultStroke());
Rule rule = sFac.createRule();
rule.setSymbolizers(new Symbolizer[] { polysym });
FeatureTypeStyle fts = sFac.createFeatureTypeStyle(new Rule[] { rule });
=====================================================================
Found a 45 line (160 tokens) duplication in the following files:
Starting at line 113 of /home/tom/pmd/pmd-web/src/geotools2/geotools-src/lite-rendering/src/org/geotools/renderer/lite/Java2DMark.java
Starting at line 94 of /home/tom/pmd/pmd-web/src/geotools2/geotools-src/renderer/src/org/geotools/renderer/style/Java2DMark.java
}
public static Shape getWellKnownMark(String wellKnownName) {
LOGGER.finer("fetching mark of name " + wellKnownName);
if (wellKnownName.equalsIgnoreCase("cross")) {
LOGGER.finer("returning cross");
return cross;
}
if (wellKnownName.equalsIgnoreCase("circle")) {
LOGGER.finer("returning circle");
return new java.awt.geom.Ellipse2D.Double(-.5, -.5, 1., 1.);
}
if (wellKnownName.equalsIgnoreCase("triangle")) {
LOGGER.finer("returning triangle");
return triangle;
}
if (wellKnownName.equalsIgnoreCase("X")) {
LOGGER.finer("returning X");
return X;
}
if (wellKnownName.equalsIgnoreCase("star")) {
LOGGER.finer("returning star");
return star;
}
if (wellKnownName.equalsIgnoreCase("arrow")) {
LOGGER.finer("returning arrow");
return arrow;
}
// failing that return a square?
LOGGER.finer("returning square");
return new Rectangle2D.Double(-.5, -.5, 1., 1.);
=====================================================================
Found a 20 line (151 tokens) duplication in the following files:
Starting at line 63 of /home/tom/pmd/pmd-web/src/geotools2/geotools-src/shapefile/tests/unit/org/geotools/data/shapefile/ShapefileDataStoreTest.java
Starting at line 61 of /home/tom/pmd/pmd-web/src/geotools2/geotools-src/shapefile/tests/unit/org/geotools/data/shapefile/ShapefileDataSourceTest.java
assertEquals("Number of Attributes",253,types.length);
}
public void testEnvelope() throws Exception {
FeatureCollection features = loadFeatures(STATE_POP, null);
ShapefileDataSource s = new ShapefileDataSource(getTestResource(STATE_POP));
assertEquals(features.getBounds(), s.getBounds());
}
public void testLoadAndVerify() throws Exception {
FeatureCollection features = loadFeatures(STATE_POP,null);
assertEquals("Number of Features loaded",49,features.size());
FeatureType schema = firstFeature(features).getFeatureType();
assertNotNull(schema.getDefaultGeometry());
assertEquals("Number of Attributes",253,schema.getAttributeTypes().length);
assertEquals("Value of statename is wrong",firstFeature(features).getAttribute("STATE_NAME"),"Illinois");
assertEquals("Value of land area is wrong",((Double)firstFeature(features).getAttribute("LAND_KM")).doubleValue(),143986.61,0.001);
}
=====================================================================
Found a 15 line (150 tokens) duplication in the following files:
Starting at line 155 of /home/tom/pmd/pmd-web/src/geotools2/geotools-src/proj4j/src/org/geotools/proj4j/Transformer.java
Starting at line 193 of /home/tom/pmd/pmd-web/src/geotools2/geotools-src/proj4j/src/org/geotools/proj4j/Transformer.java
z[io] = z[io] - defn.datum.getParams()[2];
}
}
else if( defn.datum.datumType == Datum.PJD_7PARAM ) {
for(int i = 0; i < point_count; i++ ) {
io = i * point_offset;
double x_out, y_out, z_out;
double Dx_BF = defn.datum.getParams()[0];//not elegent!
double Dy_BF = defn.datum.getParams()[1];//and possibly expensive
double Dz_BF = defn.datum.getParams()[2];//sigh, no macros in Java
double Rx_BF = defn.datum.getParams()[3];//...
double Ry_BF = defn.datum.getParams()[4];//still, keeps it readable
double Rz_BF = defn.datum.getParams()[5];//if a little verbose
double M_BF = defn.datum.getParams()[6];//could do with a better solution though.
x_out = M_BF*( x[io] + Rz_BF*y[io] - Ry_BF*z[io]) - Dx_BF;
=====================================================================
Found a 23 line (149 tokens) duplication in the following files:
Starting at line 69 of /home/tom/pmd/pmd-web/src/geotools2/geotools-src/sldstyling/src/org/geotools/styling/SLDTransformer.java
Starting at line 292 of /home/tom/pmd/pmd-web/src/geotools2/geotools-src/sldstyling/src/org/geotools/styling/XMLEncoder.java
out.write("