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/nuget-tests/src/jetbrains/buildServer/nuget/tests/util/BuildProcessTestCase.java b/nuget-tests/src/jetbrains/buildServer/nuget/tests/util/BuildProcessTestCase.java
index a959135e..490bcd4f 100644
--- a/nuget-tests/src/jetbrains/buildServer/nuget/tests/util/BuildProcessTestCase.java
+++ b/nuget-tests/src/jetbrains/buildServer/nuget/tests/util/BuildProcessTestCase.java
@@ -1,124 +1,124 @@
/*
* Copyright 2000-2011 JetBrains s.r.o.
*
* 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 jetbrains.buildServer.nuget.tests.util;
import jetbrains.buildServer.RunBuildException;
import jetbrains.buildServer.agent.BuildFinishedStatus;
import jetbrains.buildServer.agent.BuildProcess;
import jetbrains.buildServer.nuget.tests.LoggingTestCase;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Eugene Petrenko ([email protected])
* Date: 07.07.11 20:08
*/
public class BuildProcessTestCase extends LoggingTestCase {
@DataProvider(name = "buildFinishStatuses")
public Object[][] buildStatuses() {
List<Object[]> list = new ArrayList<Object[]>();
for (BuildFinishedStatus val : BuildFinishedStatus.values()) {
list.add(new Object[]{val});
}
return list.toArray(new Object[list.size()][]);
}
protected void assertRunSuccessfully(@NotNull BuildProcess proc, @NotNull BuildFinishedStatus result) {
BuildFinishedStatus status = null;
try {
proc.start();
status = proc.waitFor();
} catch (RunBuildException e) {
Assert.fail("Failed with exception " + e);
}
- Assert.assertEquals(result, status);
+ Assert.assertEquals(status, result);
}
protected void assertRunException(@NotNull BuildProcess proc, @NotNull String message) {
try {
proc.start();
proc.waitFor();
Assert.fail("Exception expected");
} catch (RunBuildException e) {
Assert.assertTrue(e.getMessage().contains(message), e.toString());
}
}
/**
* Created by Eugene Petrenko ([email protected])
* Date: 07.07.11 20:07
*/
protected class RecordingBuildProcess implements BuildProcess {
private final String myId;
private final BuildFinishedStatus myResultStatus;
private Throwable myStartException;
private Throwable myFinishException;
RecordingBuildProcess(@NotNull String id,
@Nullable final BuildFinishedStatus resultStatus) {
myId = id;
myResultStatus = resultStatus;
}
public void setStartException(Exception startException) {
myStartException = startException;
}
public void setFinishException(Exception finishException) {
myFinishException = finishException;
}
public void start() throws RunBuildException {
log("start-" + myId);
throwExceptionIfPossible(myStartException);
}
private void throwExceptionIfPossible(Throwable ex) throws RunBuildException {
if (ex != null) {
if (ex instanceof RunBuildException) throw (RunBuildException) ex;
if (ex instanceof RuntimeException) throw (RuntimeException) ex;
throw (Error) ex;
}
}
public boolean isInterrupted() {
return false;
}
public boolean isFinished() {
return false;
}
public void interrupt() {
log("interrupt-" + myId);
}
@NotNull
public BuildFinishedStatus waitFor() throws RunBuildException {
log("waitFor-" + myId);
throwExceptionIfPossible(myFinishException);
return myResultStatus;
}
}
}
| true | true | protected void assertRunSuccessfully(@NotNull BuildProcess proc, @NotNull BuildFinishedStatus result) {
BuildFinishedStatus status = null;
try {
proc.start();
status = proc.waitFor();
} catch (RunBuildException e) {
Assert.fail("Failed with exception " + e);
}
Assert.assertEquals(result, status);
}
| protected void assertRunSuccessfully(@NotNull BuildProcess proc, @NotNull BuildFinishedStatus result) {
BuildFinishedStatus status = null;
try {
proc.start();
status = proc.waitFor();
} catch (RunBuildException e) {
Assert.fail("Failed with exception " + e);
}
Assert.assertEquals(status, result);
}
|
diff --git a/wms/src/main/java/org/vfny/geoserver/wms/responses/featureInfo/AbstractFeatureInfoResponse.java b/wms/src/main/java/org/vfny/geoserver/wms/responses/featureInfo/AbstractFeatureInfoResponse.java
index ca5a851234..ccc534bfb4 100644
--- a/wms/src/main/java/org/vfny/geoserver/wms/responses/featureInfo/AbstractFeatureInfoResponse.java
+++ b/wms/src/main/java/org/vfny/geoserver/wms/responses/featureInfo/AbstractFeatureInfoResponse.java
@@ -1,314 +1,314 @@
/* Copyright (c) 2001, 2003 TOPP - www.openplans.org. All rights reserved.
* This code is licensed under the GPL 2.0 license, availible at the root
* application directory.
*/
package org.vfny.geoserver.wms.responses.featureInfo;
import java.awt.geom.AffineTransform;
import java.awt.geom.NoninvertibleTransformException;
import java.awt.geom.Point2D;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import org.geotools.data.DefaultQuery;
import org.geotools.data.FeatureResults;
import org.geotools.data.Query;
import org.geotools.filter.AbstractFilter;
import org.geotools.filter.FilterFactory;
import org.geotools.filter.FilterFactoryFinder;
import org.geotools.filter.GeometryFilter;
import org.geotools.filter.IllegalFilterException;
import org.geotools.geometry.jts.JTS;
import org.geotools.geometry.jts.ReferencedEnvelope;
import org.geotools.referencing.CRS;
import org.opengis.referencing.FactoryException;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.opengis.referencing.operation.MathTransform;
import org.opengis.referencing.operation.TransformException;
import org.opengis.spatialschema.geometry.MismatchedDimensionException;
import org.vfny.geoserver.ServiceException;
import org.vfny.geoserver.global.FeatureTypeInfo;
import org.vfny.geoserver.global.GeoServer;
import org.vfny.geoserver.wms.WmsException;
import org.vfny.geoserver.wms.requests.GetFeatureInfoRequest;
import org.vfny.geoserver.wms.requests.GetMapRequest;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Envelope;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.LinearRing;
import com.vividsolutions.jts.geom.Polygon;
/**
* Abstract class to do the common work of the FeatureInfoResponse subclasses.
* Subclasses should just need to implement writeTo(), to write the actual
* response, the executions are handled here, figuring out where on the map
* the pixel is located.
*
* <p>
* Would be nice to have some greater control over the pixels that are
* selected. Ideally we would be able to detect things like the size of the
* mark, so that users need not click on the exact center, or the exact pixel.
* This is not a big deal for polygons, but is for lines and points. One
* half solution to make things a bit nicer would be a global parameter to set
* a wider pixel range.
* </p>
*
* @author James Macgill, PSU
* @author Gabriel Roldan, Axios
* @author Chris Holmes, TOPP
* @author Brent Owens, TOPP
*/
public abstract class AbstractFeatureInfoResponse extends GetFeatureInfoDelegate {
/** A logger for this class. */
protected static final Logger LOGGER = Logger.getLogger(
"org.vfny.geoserver.responses.wms.featureinfo");
/** The formats supported by this map delegate. */
protected List supportedFormats = null;
protected List results;
protected List metas;
/**
* setted in execute() from the requested output format, it's holded just
* to be sure that method has been called before getContentType() thus
* supporting the workflow contract of the request processing
*/
protected String format = null;
/**
* Creates a new GetMapDelegate object.
*/
/**
* Autogenerated proxy constructor.
*/
public AbstractFeatureInfoResponse() {
super();
}
/**
* Returns the content encoding for the output data.
*
* <p>
* Note that this reffers to an encoding applied to the response stream
* (such as GZIP or DEFLATE), and not to the MIME response type, wich is
* returned by <code>getContentType()</code>
* </p>
*
* @return <code>null</code> since no special encoding is performed while
* wrtting to the output stream.
*/
public String getContentEncoding() {
return null;
}
/**
* Writes the image to the client.
*
* @param out The output stream to write to.
*
* @throws ServiceException DOCUMENT ME!
* @throws IOException DOCUMENT ME!
*/
public abstract void writeTo(OutputStream out)
throws ServiceException, IOException;
/**
* The formats this delegate supports.
*
* @return The list of the supported formats
*/
public List getSupportedFormats() {
return supportedFormats;
}
/**
* DOCUMENT ME!
*
* @param gs app context
*
* @task TODO: implement
*/
public void abort(GeoServer gs) {
}
/**
* Gets the content type. This is set by the request, should only be
* called after execute. GetMapResponse should handle this though.
*
* @param gs server configuration
*
* @return The mime type that this response will generate.
*
* @throws IllegalStateException if<code>execute()</code> has not been
* previously called
*/
public String getContentType(GeoServer gs) {
if (format == null) {
throw new IllegalStateException(
"Content type unknown since execute() has not been called yet");
}
return format;
}
/**
* Performs the execute request using geotools rendering.
*
* @param requestedLayers The information on the types requested.
* @param queries The results of the queries to generate maps with.
* @param x DOCUMENT ME!
* @param y DOCUMENT ME!
*
* @throws WmsException For any problems.
*/
protected void execute(FeatureTypeInfo[] requestedLayers, Query[] queries,
int x, int y) throws WmsException {
GetFeatureInfoRequest request = getRequest();
this.format = request.getInfoFormat();
GetMapRequest getMapReq = request.getGetMapRequest();
- CoordinateReferenceSystem requestedCRS = getMapReq.getCrs();
+ CoordinateReferenceSystem requestedCRS = getMapReq.getCrs(); // optional, may be null
int width = getMapReq.getWidth();
int height = getMapReq.getHeight();
Envelope bbox = getMapReq.getBbox();
Coordinate upperLeft = pixelToWorld(x - 2, y - 2, bbox, width, height);
Coordinate lowerRight = pixelToWorld(x + 2, y + 2, bbox, width, height);
Coordinate[] coords = new Coordinate[5];
coords[0] = upperLeft;
coords[1] = new Coordinate(lowerRight.x, upperLeft.y);
coords[2] = lowerRight;
coords[3] = new Coordinate(upperLeft.x, lowerRight.y);
coords[4] = coords[0];
//DJB:
//TODO: this should probably put a max features restriction on the query
// unforunately, this queryies by filter not by query, so this is a slightly more difficult problem
// Its not a big deal not to do this because the writer will ensure that the correct # of items
// are actually printed out.
//DJB: DONE - see "q", below
// NOTE: you can ask for results from multiple layers at once. So, if max features is 2 (after you add max features query to above) and you
// query 10 layers, you could still get 20 features being sent on.
// Thats why max features is handled at the query portion!
GeometryFactory geomFac = new GeometryFactory();
LinearRing boundary = geomFac.createLinearRing(coords); // this needs to be done with each FT so it can be reprojected
Polygon pixelRect = geomFac.createPolygon(boundary, null);
FilterFactory filterFac = FilterFactoryFinder.createFilterFactory();
GeometryFilter getFInfoFilter = null;
int layerCount = requestedLayers.length;
results = new ArrayList(layerCount);
metas = new ArrayList(layerCount);
try {
for (int i = 0; i < layerCount; i++) {
FeatureTypeInfo finfo = requestedLayers[i];
CoordinateReferenceSystem dataCRS = finfo.getFeatureType().getDefaultGeometry().getCoordinateSystem();
// reproject the bounding box
- if (!CRS.equalsIgnoreMetadata(dataCRS, requestedCRS)) {
+ if (requestedCRS != null && !CRS.equalsIgnoreMetadata(dataCRS, requestedCRS)) {
try {
MathTransform transform = CRS.transform(requestedCRS, dataCRS, true);
pixelRect = (Polygon) JTS.transform(pixelRect, transform); // reprojected
} catch (MismatchedDimensionException e) {
LOGGER.severe( e.getLocalizedMessage() );
} catch (TransformException e) {
LOGGER.severe( e.getLocalizedMessage() );
} catch (FactoryException e) {
LOGGER.severe( e.getLocalizedMessage() );
}
}
try {
getFInfoFilter = filterFac.createGeometryFilter(AbstractFilter.GEOMETRY_INTERSECTS);
getFInfoFilter.addLeftGeometry(filterFac.createLiteralExpression(pixelRect));
} catch (IllegalFilterException e) {
e.printStackTrace();
throw new WmsException(null, "Internal error : " + e.getMessage());
}
Query q = new DefaultQuery( finfo.getTypeName(), null, getFInfoFilter,request.getFeatureCount(), Query.ALL_NAMES, null );
FeatureResults match = finfo.getFeatureSource().getFeatures(q);
//this was crashing Gml2FeatureResponseDelegate due to not setting
//the featureresults, thus not being able of querying the SRS
//if (match.getCount() > 0) {
results.add(match);
metas.add(finfo);
//}
}
} catch (IOException ioe) {
ioe.printStackTrace();
throw new WmsException(null, "Internal error : " + ioe.getMessage());
}
}
/**
* Converts a coordinate expressed on the device space back to real world
* coordinates. Stolen from LiteRenderer but without the need of a
* Graphics object
*
* @param x horizontal coordinate on device space
* @param y vertical coordinate on device space
* @param map The map extent
* @param width image width
* @param height image height
*
* @return The correspondent real world coordinate
*
* @throws RuntimeException DOCUMENT ME!
*/
private Coordinate pixelToWorld(int x, int y, Envelope map, int width,
int height) {
//set up the affine transform and calculate scale values
AffineTransform at = worldToScreenTransform(map, width, height);
Point2D result = null;
try {
result = at.inverseTransform(new java.awt.geom.Point2D.Double(x, y),
new java.awt.geom.Point2D.Double());
} catch (NoninvertibleTransformException e) {
throw new RuntimeException(e);
}
Coordinate c = new Coordinate(result.getX(), result.getY());
return c;
}
/**
* Sets up the affine transform. Stolen from liteRenderer code.
*
* @param mapExtent the map extent
* @param width the screen size
* @param height DOCUMENT ME!
*
* @return a transform that maps from real world coordinates to the screen
*/
private AffineTransform worldToScreenTransform(Envelope mapExtent,
int width, int height) {
double scaleX = (double) width / mapExtent.getWidth();
double scaleY = (double) height / mapExtent.getHeight();
double tx = -mapExtent.getMinX() * scaleX;
double ty = (mapExtent.getMinY() * scaleY) + height;
AffineTransform at = new AffineTransform(scaleX, 0.0d, 0.0d, -scaleY,
tx, ty);
return at;
}
}
| false | true | protected void execute(FeatureTypeInfo[] requestedLayers, Query[] queries,
int x, int y) throws WmsException {
GetFeatureInfoRequest request = getRequest();
this.format = request.getInfoFormat();
GetMapRequest getMapReq = request.getGetMapRequest();
CoordinateReferenceSystem requestedCRS = getMapReq.getCrs();
int width = getMapReq.getWidth();
int height = getMapReq.getHeight();
Envelope bbox = getMapReq.getBbox();
Coordinate upperLeft = pixelToWorld(x - 2, y - 2, bbox, width, height);
Coordinate lowerRight = pixelToWorld(x + 2, y + 2, bbox, width, height);
Coordinate[] coords = new Coordinate[5];
coords[0] = upperLeft;
coords[1] = new Coordinate(lowerRight.x, upperLeft.y);
coords[2] = lowerRight;
coords[3] = new Coordinate(upperLeft.x, lowerRight.y);
coords[4] = coords[0];
//DJB:
//TODO: this should probably put a max features restriction on the query
// unforunately, this queryies by filter not by query, so this is a slightly more difficult problem
// Its not a big deal not to do this because the writer will ensure that the correct # of items
// are actually printed out.
//DJB: DONE - see "q", below
// NOTE: you can ask for results from multiple layers at once. So, if max features is 2 (after you add max features query to above) and you
// query 10 layers, you could still get 20 features being sent on.
// Thats why max features is handled at the query portion!
GeometryFactory geomFac = new GeometryFactory();
LinearRing boundary = geomFac.createLinearRing(coords); // this needs to be done with each FT so it can be reprojected
Polygon pixelRect = geomFac.createPolygon(boundary, null);
FilterFactory filterFac = FilterFactoryFinder.createFilterFactory();
GeometryFilter getFInfoFilter = null;
int layerCount = requestedLayers.length;
results = new ArrayList(layerCount);
metas = new ArrayList(layerCount);
try {
for (int i = 0; i < layerCount; i++) {
FeatureTypeInfo finfo = requestedLayers[i];
CoordinateReferenceSystem dataCRS = finfo.getFeatureType().getDefaultGeometry().getCoordinateSystem();
// reproject the bounding box
if (!CRS.equalsIgnoreMetadata(dataCRS, requestedCRS)) {
try {
MathTransform transform = CRS.transform(requestedCRS, dataCRS, true);
pixelRect = (Polygon) JTS.transform(pixelRect, transform); // reprojected
} catch (MismatchedDimensionException e) {
LOGGER.severe( e.getLocalizedMessage() );
} catch (TransformException e) {
LOGGER.severe( e.getLocalizedMessage() );
} catch (FactoryException e) {
LOGGER.severe( e.getLocalizedMessage() );
}
}
try {
getFInfoFilter = filterFac.createGeometryFilter(AbstractFilter.GEOMETRY_INTERSECTS);
getFInfoFilter.addLeftGeometry(filterFac.createLiteralExpression(pixelRect));
} catch (IllegalFilterException e) {
e.printStackTrace();
throw new WmsException(null, "Internal error : " + e.getMessage());
}
Query q = new DefaultQuery( finfo.getTypeName(), null, getFInfoFilter,request.getFeatureCount(), Query.ALL_NAMES, null );
FeatureResults match = finfo.getFeatureSource().getFeatures(q);
//this was crashing Gml2FeatureResponseDelegate due to not setting
//the featureresults, thus not being able of querying the SRS
//if (match.getCount() > 0) {
results.add(match);
metas.add(finfo);
//}
}
} catch (IOException ioe) {
ioe.printStackTrace();
throw new WmsException(null, "Internal error : " + ioe.getMessage());
}
}
| protected void execute(FeatureTypeInfo[] requestedLayers, Query[] queries,
int x, int y) throws WmsException {
GetFeatureInfoRequest request = getRequest();
this.format = request.getInfoFormat();
GetMapRequest getMapReq = request.getGetMapRequest();
CoordinateReferenceSystem requestedCRS = getMapReq.getCrs(); // optional, may be null
int width = getMapReq.getWidth();
int height = getMapReq.getHeight();
Envelope bbox = getMapReq.getBbox();
Coordinate upperLeft = pixelToWorld(x - 2, y - 2, bbox, width, height);
Coordinate lowerRight = pixelToWorld(x + 2, y + 2, bbox, width, height);
Coordinate[] coords = new Coordinate[5];
coords[0] = upperLeft;
coords[1] = new Coordinate(lowerRight.x, upperLeft.y);
coords[2] = lowerRight;
coords[3] = new Coordinate(upperLeft.x, lowerRight.y);
coords[4] = coords[0];
//DJB:
//TODO: this should probably put a max features restriction on the query
// unforunately, this queryies by filter not by query, so this is a slightly more difficult problem
// Its not a big deal not to do this because the writer will ensure that the correct # of items
// are actually printed out.
//DJB: DONE - see "q", below
// NOTE: you can ask for results from multiple layers at once. So, if max features is 2 (after you add max features query to above) and you
// query 10 layers, you could still get 20 features being sent on.
// Thats why max features is handled at the query portion!
GeometryFactory geomFac = new GeometryFactory();
LinearRing boundary = geomFac.createLinearRing(coords); // this needs to be done with each FT so it can be reprojected
Polygon pixelRect = geomFac.createPolygon(boundary, null);
FilterFactory filterFac = FilterFactoryFinder.createFilterFactory();
GeometryFilter getFInfoFilter = null;
int layerCount = requestedLayers.length;
results = new ArrayList(layerCount);
metas = new ArrayList(layerCount);
try {
for (int i = 0; i < layerCount; i++) {
FeatureTypeInfo finfo = requestedLayers[i];
CoordinateReferenceSystem dataCRS = finfo.getFeatureType().getDefaultGeometry().getCoordinateSystem();
// reproject the bounding box
if (requestedCRS != null && !CRS.equalsIgnoreMetadata(dataCRS, requestedCRS)) {
try {
MathTransform transform = CRS.transform(requestedCRS, dataCRS, true);
pixelRect = (Polygon) JTS.transform(pixelRect, transform); // reprojected
} catch (MismatchedDimensionException e) {
LOGGER.severe( e.getLocalizedMessage() );
} catch (TransformException e) {
LOGGER.severe( e.getLocalizedMessage() );
} catch (FactoryException e) {
LOGGER.severe( e.getLocalizedMessage() );
}
}
try {
getFInfoFilter = filterFac.createGeometryFilter(AbstractFilter.GEOMETRY_INTERSECTS);
getFInfoFilter.addLeftGeometry(filterFac.createLiteralExpression(pixelRect));
} catch (IllegalFilterException e) {
e.printStackTrace();
throw new WmsException(null, "Internal error : " + e.getMessage());
}
Query q = new DefaultQuery( finfo.getTypeName(), null, getFInfoFilter,request.getFeatureCount(), Query.ALL_NAMES, null );
FeatureResults match = finfo.getFeatureSource().getFeatures(q);
//this was crashing Gml2FeatureResponseDelegate due to not setting
//the featureresults, thus not being able of querying the SRS
//if (match.getCount() > 0) {
results.add(match);
metas.add(finfo);
//}
}
} catch (IOException ioe) {
ioe.printStackTrace();
throw new WmsException(null, "Internal error : " + ioe.getMessage());
}
}
|
diff --git a/java/test/org/broadinstitute/sting/alignment/AlignerIntegrationTest.java b/java/test/org/broadinstitute/sting/alignment/AlignerIntegrationTest.java
index 374e5ee51..3e0c3774e 100644
--- a/java/test/org/broadinstitute/sting/alignment/AlignerIntegrationTest.java
+++ b/java/test/org/broadinstitute/sting/alignment/AlignerIntegrationTest.java
@@ -1,29 +1,30 @@
package org.broadinstitute.sting.alignment;
import org.junit.Test;
import org.broadinstitute.sting.WalkerTest;
import java.util.Arrays;
import java.util.List;
import java.io.File;
/**
* Integration tests for the aligner.
*
* @author mhanna
* @version 0.1
*/
public class AlignerIntegrationTest extends WalkerTest {
@Test
public void testBasicAlignment() {
String md5 = "c6d95d8ae707e78fefdaa7375f130995";
WalkerTest.WalkerTestSpec spec = new WalkerTest.WalkerTestSpec(
"-R /humgen/gsa-scr1/GATK_Data/bwa/human_b36_both.fasta" +
" -T Align" +
" -I " + validationDataLocation + "NA12878_Pilot1_20.trimmed.unmapped.bam" +
" -ob %s",
1, // just one output file
Arrays.asList(md5));
- executeTest("testBasicAlignment", spec);
+ //executeTest("testBasicAlignment", spec);
+ System.err.println("Test disabled until we get more memory on the build machine.");
}
}
| true | true | public void testBasicAlignment() {
String md5 = "c6d95d8ae707e78fefdaa7375f130995";
WalkerTest.WalkerTestSpec spec = new WalkerTest.WalkerTestSpec(
"-R /humgen/gsa-scr1/GATK_Data/bwa/human_b36_both.fasta" +
" -T Align" +
" -I " + validationDataLocation + "NA12878_Pilot1_20.trimmed.unmapped.bam" +
" -ob %s",
1, // just one output file
Arrays.asList(md5));
executeTest("testBasicAlignment", spec);
}
| public void testBasicAlignment() {
String md5 = "c6d95d8ae707e78fefdaa7375f130995";
WalkerTest.WalkerTestSpec spec = new WalkerTest.WalkerTestSpec(
"-R /humgen/gsa-scr1/GATK_Data/bwa/human_b36_both.fasta" +
" -T Align" +
" -I " + validationDataLocation + "NA12878_Pilot1_20.trimmed.unmapped.bam" +
" -ob %s",
1, // just one output file
Arrays.asList(md5));
//executeTest("testBasicAlignment", spec);
System.err.println("Test disabled until we get more memory on the build machine.");
}
|
diff --git a/src/main/java/de/cismet/cismap/cids/geometryeditor/FeatureComboBoxRenderer.java b/src/main/java/de/cismet/cismap/cids/geometryeditor/FeatureComboBoxRenderer.java
index cdb820a..1b22228 100644
--- a/src/main/java/de/cismet/cismap/cids/geometryeditor/FeatureComboBoxRenderer.java
+++ b/src/main/java/de/cismet/cismap/cids/geometryeditor/FeatureComboBoxRenderer.java
@@ -1,104 +1,104 @@
/*
* FeatureComboBoxRenderer.java
* Copyright (C) 2005 by:
*
*----------------------------
* cismet GmbH
* Goebenstrasse 40
* 66117 Saarbruecken
* http://www.cismet.de
*----------------------------
*
* 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
* General Public License for more details.
*
* You should have received a copy of the GNU 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
*
*----------------------------
* Author:
* [email protected]
*----------------------------
*
* Created on 31. Mai 2006, 16:32
*
*/
package de.cismet.cismap.cids.geometryeditor;
import com.vividsolutions.jts.geom.Point;
import de.cismet.cismap.commons.features.Feature;
import de.cismet.cismap.commons.features.XStyledFeature;
import de.cismet.cismap.commons.gui.piccolo.PFeature;
import de.cismet.cismap.commons.interaction.CismapBroker;
import de.cismet.cismap.navigatorplugin.CidsFeature;
import java.awt.Color;
import java.awt.Component;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JList;
import javax.swing.ListCellRenderer;
import javax.swing.UIManager;
/**
*
* @author [email protected]
*/
public class FeatureComboBoxRenderer extends DefaultListCellRenderer implements ListCellRenderer{
private final org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(this.getClass());
Color background=UIManager.getDefaults().getColor("ComboBox.background");
Color selectedBackground=UIManager.getDefaults().getColor("ComboBox.selectionBackground");
/** Creates a new instance of FeatureComboBoxRenderer */
public FeatureComboBoxRenderer() {
}
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
super.getListCellRendererComponent(list,value,index,isSelected,cellHasFocus);
try {
if (value!=null) {
if (value instanceof CidsFeature&&((CidsFeature)value).getGeometry()!=null) {
setText("momentan zugeordnete Geometrie ("+((CidsFeature)value).getGeometry().getGeometryType()+")");
}
else if (value instanceof XStyledFeature&&((XStyledFeature)value).getGeometry()!=null) {
setText(((XStyledFeature)value).getName());
setIcon(((XStyledFeature)value).getIconImage());
- log.fatal("xxxlala "+CismapBroker.getInstance().getMappingComponent().getPFeatureHM());
+ //log.fatal("xxxlala "+CismapBroker.getInstance().getMappingComponent().getPFeatureHM());
PFeature pf=(PFeature)CismapBroker.getInstance().getMappingComponent().getPFeatureHM().get(value);
PFeature clonePf=(PFeature)pf.clone();
if (clonePf.getFeature().getGeometry() instanceof Point) {
clonePf.getChild(0).removeAllChildren();
} else {
clonePf.removeAllChildren();
}
setToolTipText("@@@@"+getText());
//i=clonePf.toImage(100,55,null);
} else {
setText(value.getClass()+":"+value.toString());
setIcon(null);
}
} else {
setText("keine Geometrie zugeordnet");
}
} catch (Throwable t) {
log.error("Fehler im Renderer der ComboBox",t);
setText("--->value:"+((Feature)value).getGeometry());
}
return this;
}
}
| true | true | public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
super.getListCellRendererComponent(list,value,index,isSelected,cellHasFocus);
try {
if (value!=null) {
if (value instanceof CidsFeature&&((CidsFeature)value).getGeometry()!=null) {
setText("momentan zugeordnete Geometrie ("+((CidsFeature)value).getGeometry().getGeometryType()+")");
}
else if (value instanceof XStyledFeature&&((XStyledFeature)value).getGeometry()!=null) {
setText(((XStyledFeature)value).getName());
setIcon(((XStyledFeature)value).getIconImage());
log.fatal("xxxlala "+CismapBroker.getInstance().getMappingComponent().getPFeatureHM());
PFeature pf=(PFeature)CismapBroker.getInstance().getMappingComponent().getPFeatureHM().get(value);
PFeature clonePf=(PFeature)pf.clone();
if (clonePf.getFeature().getGeometry() instanceof Point) {
clonePf.getChild(0).removeAllChildren();
} else {
clonePf.removeAllChildren();
}
setToolTipText("@@@@"+getText());
//i=clonePf.toImage(100,55,null);
} else {
setText(value.getClass()+":"+value.toString());
setIcon(null);
}
} else {
setText("keine Geometrie zugeordnet");
}
} catch (Throwable t) {
log.error("Fehler im Renderer der ComboBox",t);
setText("--->value:"+((Feature)value).getGeometry());
}
return this;
}
| public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
super.getListCellRendererComponent(list,value,index,isSelected,cellHasFocus);
try {
if (value!=null) {
if (value instanceof CidsFeature&&((CidsFeature)value).getGeometry()!=null) {
setText("momentan zugeordnete Geometrie ("+((CidsFeature)value).getGeometry().getGeometryType()+")");
}
else if (value instanceof XStyledFeature&&((XStyledFeature)value).getGeometry()!=null) {
setText(((XStyledFeature)value).getName());
setIcon(((XStyledFeature)value).getIconImage());
//log.fatal("xxxlala "+CismapBroker.getInstance().getMappingComponent().getPFeatureHM());
PFeature pf=(PFeature)CismapBroker.getInstance().getMappingComponent().getPFeatureHM().get(value);
PFeature clonePf=(PFeature)pf.clone();
if (clonePf.getFeature().getGeometry() instanceof Point) {
clonePf.getChild(0).removeAllChildren();
} else {
clonePf.removeAllChildren();
}
setToolTipText("@@@@"+getText());
//i=clonePf.toImage(100,55,null);
} else {
setText(value.getClass()+":"+value.toString());
setIcon(null);
}
} else {
setText("keine Geometrie zugeordnet");
}
} catch (Throwable t) {
log.error("Fehler im Renderer der ComboBox",t);
setText("--->value:"+((Feature)value).getGeometry());
}
return this;
}
|
diff --git a/demos/rtm/src/com/badlogic/rtm/LevelRenderer.java b/demos/rtm/src/com/badlogic/rtm/LevelRenderer.java
index ed8e92d20..f8ea5dd46 100644
--- a/demos/rtm/src/com/badlogic/rtm/LevelRenderer.java
+++ b/demos/rtm/src/com/badlogic/rtm/LevelRenderer.java
@@ -1,251 +1,251 @@
package com.badlogic.rtm;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Files.FileType;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.backends.jogl.JoglApplication;
import com.badlogic.gdx.graphics.BitmapFont;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.ImmediateModeRenderer;
import com.badlogic.gdx.graphics.Mesh;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.SpriteBatch;
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.TextureAtlas;
import com.badlogic.gdx.graphics.TextureRegion;
import com.badlogic.gdx.graphics.VertexAttribute;
import com.badlogic.gdx.graphics.VertexAttributes;
import com.badlogic.gdx.utils.GdxRuntimeException;
public class LevelRenderer implements ApplicationListener {
PerspectiveCamera camera;
Texture tiles;
Mesh floorMesh;
Mesh wallMesh;
SpriteBatch batch;
BitmapFont font;
ImmediateModeRenderer renderer;
float angle = -90;
@Override public void create () {
camera = new PerspectiveCamera();
camera.setNear(1);
camera.setFar(2000);
camera.setFov(67);
camera.getDirection().set(0, 0, -1);
batch = new SpriteBatch();
font = new BitmapFont();
load();
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
}
private void load () {
try {
tiles = Gdx.graphics.newTexture( Gdx.files.getFileHandle("data/tiles-3.png", FileType.Internal),
TextureFilter.MipMapLinearNearest, TextureFilter.Nearest,
TextureWrap.ClampToEdge, TextureWrap.ClampToEdge );
TextureAtlas atlas = new TextureAtlas(tiles);
for( int i = 0; i < 12; i++ ) {
TextureRegion region = new TextureRegion(tiles, i % 4 * 64 + 1, i / 4 * 64 + 1, 64, 64);
atlas.addRegion("" + i, region);
}
float uSize = 62.0f / 256.0f;
float vSize = 62.0f / 256.0f;
- BufferedReader reader = new BufferedReader(new InputStreamReader(Gdx.files.readFile("data/level.map", FileType.Internal)));
+ BufferedReader reader = new BufferedReader(new InputStreamReader(Gdx.files.internal("data/level.map").read()));
String line = reader.readLine();
String tokens[] = line.split(",");
camera.getPosition().set(Float.parseFloat(tokens[0]), 0, Float.parseFloat(tokens[1]));
int floors = Integer.parseInt(reader.readLine());
int walls = Integer.parseInt(reader.readLine());
float[] floorVertices = new float[floors*20];
float[] wallVertices = new float[walls*20];
short[] floorIndices = new short[floors*6];
short[] wallIndices = new short[walls*6];
int idx = 0;
for(int i = 0, j = 0; i < floors; i++ ) {
for( int k = 0; k < 4; k++) {
tokens = reader.readLine().split(",");
floorVertices[j++] = Float.parseFloat(tokens[0]);
floorVertices[j++] = Float.parseFloat(tokens[1]);
floorVertices[j++] = Float.parseFloat(tokens[2]);
floorVertices[j++] = 0;
floorVertices[j++] = 0;
}
short startIndex = (short)(i * 4);
floorIndices[idx++] = startIndex;
floorIndices[idx++] = (short)(startIndex + 1);
floorIndices[idx++] = (short)(startIndex + 2);
floorIndices[idx++] = (short)(startIndex + 2);
floorIndices[idx++] = (short)(startIndex + 3);
floorIndices[idx++] = startIndex;
int type = Integer.parseInt(reader.readLine());
String textureId = reader.readLine();
TextureRegion region = atlas.getRegion(textureId);
float u = region.x / 256.0f;
float v = region.y / 256.0f;
floorVertices[j-2] = u + uSize;
floorVertices[j-1] = v;
floorVertices[j-2-5] = u + uSize;
floorVertices[j-1-5] = v + vSize;
floorVertices[j-2-10] = u;
floorVertices[j-1-10] = v + vSize;
floorVertices[j-2-15] = u;
floorVertices[j-1-15] = v;
}
idx = 0;
short startIndex = 0;
for(int i = 0, j = 0; i < walls; i++ ) {
tokens = reader.readLine().split(",");
if( !tokens[1].equals("0") ) {
for( int k = 0; k < 4; k++) {
wallVertices[j++] = Float.parseFloat(tokens[0]);
wallVertices[j++] = Float.parseFloat(tokens[1]);
wallVertices[j++] = Float.parseFloat(tokens[2]);
wallVertices[j++] = 0;
wallVertices[j++] = 0;
if(k < 3)
tokens = reader.readLine().split(",");
}
wallIndices[idx++] = startIndex;
wallIndices[idx++] = (short)(startIndex + 1);
wallIndices[idx++] = (short)(startIndex + 2);
wallIndices[idx++] = (short)(startIndex + 2);
wallIndices[idx++] = (short)(startIndex + 3);
wallIndices[idx++] = startIndex;
startIndex+=4;
int type = Integer.parseInt(reader.readLine());
String textureId = reader.readLine();
TextureRegion region = atlas.getRegion(textureId);
float u = region.x / 256.0f;
float v = region.y / 256.0f;
wallVertices[j-2] = u + uSize;
wallVertices[j-1] = v;
wallVertices[j-2-5] = u + vSize;
wallVertices[j-1-5] = v + vSize;
wallVertices[j-2-10] = u;
wallVertices[j-1-10] = v + vSize;
wallVertices[j-2-15] = u;
wallVertices[j-1-15] = v;
}
else {
reader.readLine();
reader.readLine();
reader.readLine();
int type = Integer.parseInt(reader.readLine());
int textureId = Integer.parseInt(reader.readLine());
}
}
floorMesh = new Mesh(true, floors * 4, floors * 6,
new VertexAttribute(VertexAttributes.Usage.Position, 3, "a_position"),
new VertexAttribute(VertexAttributes.Usage.TextureCoordinates, 2, "a_texCoord" ));
floorMesh.setVertices(floorVertices);
floorMesh.setIndices(floorIndices);
wallMesh = new Mesh(true, walls * 4, walls * 6,
new VertexAttribute(VertexAttributes.Usage.Position, 3, "a_position"),
new VertexAttribute(VertexAttributes.Usage.TextureCoordinates, 2, "a_texCoord" ));
wallMesh.setVertices(wallVertices);
wallMesh.setIndices(wallIndices);
reader.close();
}
catch(IOException ex) {
throw new GdxRuntimeException(ex);
}
}
@Override public void resume () {
// TODO Auto-generated method stub
}
@Override public void render () {
GL10 gl = Gdx.gl10;
gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
gl.glEnable(GL10.GL_DEPTH_TEST);
gl.glEnable(GL10.GL_TEXTURE_2D);
camera.setViewport(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
camera.setMatrices();
tiles.bind();
gl.glColor4f(1, 1, 1, 1);
floorMesh.render(GL10.GL_TRIANGLES);
wallMesh.render(GL10.GL_TRIANGLES);
batch.begin();
font.draw(batch, "fps: " + Gdx.graphics.getFramesPerSecond() + ", delta:" + Gdx.graphics.getDeltaTime(), 10, 10, Color.WHITE);
batch.end();
processInput();
}
private void processInput() {
float delta = Gdx.graphics.getDeltaTime();
//
// if (Gdx.input.isKeyPressed(Keys.ANY_KEY)==false)
// Gdx.app.log("RTM", "No key pressed");
if( Gdx.input.isKeyPressed(Keys.KEYCODE_W) )
camera.getPosition().add(camera.getDirection().tmp().mul(80*delta));
if( Gdx.input.isKeyPressed(Keys.KEYCODE_S) )
camera.getPosition().add(camera.getDirection().tmp().mul(-80*delta));
if( Gdx.input.isKeyPressed(Keys.KEYCODE_A) )
angle -= 90 * delta;
if( Gdx.input.isKeyPressed(Keys.KEYCODE_D))
angle += 90 * delta;
if( Gdx.input.isTouched() ) {
float x = Gdx.input.getX();
float y = Gdx.input.getY();
if( x > Gdx.graphics.getWidth() / 2 + Gdx.graphics.getWidth() / 4 )
angle += 90 * delta;
if( x < Gdx.graphics.getWidth() / 2 - Gdx.graphics.getWidth() / 4 )
angle -= 90 * delta;
if( y > Gdx.graphics.getHeight() / 2 + Gdx.graphics.getHeight() / 4 )
camera.getPosition().add(camera.getDirection().tmp().mul(80*delta));
if( y < Gdx.graphics.getHeight() / 2 - Gdx.graphics.getHeight() / 4 )
camera.getPosition().add(camera.getDirection().tmp().mul(-80*delta));
}
camera.getDirection().set((float)Math.cos(Math.toRadians(angle)), 0, (float)Math.sin(Math.toRadians(angle)));
}
@Override public void resize (int width, int height) {
}
@Override public void pause () {
}
@Override
public void dispose() {
}
}
| true | true | private void load () {
try {
tiles = Gdx.graphics.newTexture( Gdx.files.getFileHandle("data/tiles-3.png", FileType.Internal),
TextureFilter.MipMapLinearNearest, TextureFilter.Nearest,
TextureWrap.ClampToEdge, TextureWrap.ClampToEdge );
TextureAtlas atlas = new TextureAtlas(tiles);
for( int i = 0; i < 12; i++ ) {
TextureRegion region = new TextureRegion(tiles, i % 4 * 64 + 1, i / 4 * 64 + 1, 64, 64);
atlas.addRegion("" + i, region);
}
float uSize = 62.0f / 256.0f;
float vSize = 62.0f / 256.0f;
BufferedReader reader = new BufferedReader(new InputStreamReader(Gdx.files.readFile("data/level.map", FileType.Internal)));
String line = reader.readLine();
String tokens[] = line.split(",");
camera.getPosition().set(Float.parseFloat(tokens[0]), 0, Float.parseFloat(tokens[1]));
int floors = Integer.parseInt(reader.readLine());
int walls = Integer.parseInt(reader.readLine());
float[] floorVertices = new float[floors*20];
float[] wallVertices = new float[walls*20];
short[] floorIndices = new short[floors*6];
short[] wallIndices = new short[walls*6];
int idx = 0;
for(int i = 0, j = 0; i < floors; i++ ) {
for( int k = 0; k < 4; k++) {
tokens = reader.readLine().split(",");
floorVertices[j++] = Float.parseFloat(tokens[0]);
floorVertices[j++] = Float.parseFloat(tokens[1]);
floorVertices[j++] = Float.parseFloat(tokens[2]);
floorVertices[j++] = 0;
floorVertices[j++] = 0;
}
short startIndex = (short)(i * 4);
floorIndices[idx++] = startIndex;
floorIndices[idx++] = (short)(startIndex + 1);
floorIndices[idx++] = (short)(startIndex + 2);
floorIndices[idx++] = (short)(startIndex + 2);
floorIndices[idx++] = (short)(startIndex + 3);
floorIndices[idx++] = startIndex;
int type = Integer.parseInt(reader.readLine());
String textureId = reader.readLine();
TextureRegion region = atlas.getRegion(textureId);
float u = region.x / 256.0f;
float v = region.y / 256.0f;
floorVertices[j-2] = u + uSize;
floorVertices[j-1] = v;
floorVertices[j-2-5] = u + uSize;
floorVertices[j-1-5] = v + vSize;
floorVertices[j-2-10] = u;
floorVertices[j-1-10] = v + vSize;
floorVertices[j-2-15] = u;
floorVertices[j-1-15] = v;
}
idx = 0;
short startIndex = 0;
for(int i = 0, j = 0; i < walls; i++ ) {
tokens = reader.readLine().split(",");
if( !tokens[1].equals("0") ) {
for( int k = 0; k < 4; k++) {
wallVertices[j++] = Float.parseFloat(tokens[0]);
wallVertices[j++] = Float.parseFloat(tokens[1]);
wallVertices[j++] = Float.parseFloat(tokens[2]);
wallVertices[j++] = 0;
wallVertices[j++] = 0;
if(k < 3)
tokens = reader.readLine().split(",");
}
wallIndices[idx++] = startIndex;
wallIndices[idx++] = (short)(startIndex + 1);
wallIndices[idx++] = (short)(startIndex + 2);
wallIndices[idx++] = (short)(startIndex + 2);
wallIndices[idx++] = (short)(startIndex + 3);
wallIndices[idx++] = startIndex;
startIndex+=4;
int type = Integer.parseInt(reader.readLine());
String textureId = reader.readLine();
TextureRegion region = atlas.getRegion(textureId);
float u = region.x / 256.0f;
float v = region.y / 256.0f;
wallVertices[j-2] = u + uSize;
wallVertices[j-1] = v;
wallVertices[j-2-5] = u + vSize;
wallVertices[j-1-5] = v + vSize;
wallVertices[j-2-10] = u;
wallVertices[j-1-10] = v + vSize;
wallVertices[j-2-15] = u;
wallVertices[j-1-15] = v;
}
else {
reader.readLine();
reader.readLine();
reader.readLine();
int type = Integer.parseInt(reader.readLine());
int textureId = Integer.parseInt(reader.readLine());
}
}
floorMesh = new Mesh(true, floors * 4, floors * 6,
new VertexAttribute(VertexAttributes.Usage.Position, 3, "a_position"),
new VertexAttribute(VertexAttributes.Usage.TextureCoordinates, 2, "a_texCoord" ));
floorMesh.setVertices(floorVertices);
floorMesh.setIndices(floorIndices);
wallMesh = new Mesh(true, walls * 4, walls * 6,
new VertexAttribute(VertexAttributes.Usage.Position, 3, "a_position"),
new VertexAttribute(VertexAttributes.Usage.TextureCoordinates, 2, "a_texCoord" ));
wallMesh.setVertices(wallVertices);
wallMesh.setIndices(wallIndices);
reader.close();
}
catch(IOException ex) {
throw new GdxRuntimeException(ex);
}
}
| private void load () {
try {
tiles = Gdx.graphics.newTexture( Gdx.files.getFileHandle("data/tiles-3.png", FileType.Internal),
TextureFilter.MipMapLinearNearest, TextureFilter.Nearest,
TextureWrap.ClampToEdge, TextureWrap.ClampToEdge );
TextureAtlas atlas = new TextureAtlas(tiles);
for( int i = 0; i < 12; i++ ) {
TextureRegion region = new TextureRegion(tiles, i % 4 * 64 + 1, i / 4 * 64 + 1, 64, 64);
atlas.addRegion("" + i, region);
}
float uSize = 62.0f / 256.0f;
float vSize = 62.0f / 256.0f;
BufferedReader reader = new BufferedReader(new InputStreamReader(Gdx.files.internal("data/level.map").read()));
String line = reader.readLine();
String tokens[] = line.split(",");
camera.getPosition().set(Float.parseFloat(tokens[0]), 0, Float.parseFloat(tokens[1]));
int floors = Integer.parseInt(reader.readLine());
int walls = Integer.parseInt(reader.readLine());
float[] floorVertices = new float[floors*20];
float[] wallVertices = new float[walls*20];
short[] floorIndices = new short[floors*6];
short[] wallIndices = new short[walls*6];
int idx = 0;
for(int i = 0, j = 0; i < floors; i++ ) {
for( int k = 0; k < 4; k++) {
tokens = reader.readLine().split(",");
floorVertices[j++] = Float.parseFloat(tokens[0]);
floorVertices[j++] = Float.parseFloat(tokens[1]);
floorVertices[j++] = Float.parseFloat(tokens[2]);
floorVertices[j++] = 0;
floorVertices[j++] = 0;
}
short startIndex = (short)(i * 4);
floorIndices[idx++] = startIndex;
floorIndices[idx++] = (short)(startIndex + 1);
floorIndices[idx++] = (short)(startIndex + 2);
floorIndices[idx++] = (short)(startIndex + 2);
floorIndices[idx++] = (short)(startIndex + 3);
floorIndices[idx++] = startIndex;
int type = Integer.parseInt(reader.readLine());
String textureId = reader.readLine();
TextureRegion region = atlas.getRegion(textureId);
float u = region.x / 256.0f;
float v = region.y / 256.0f;
floorVertices[j-2] = u + uSize;
floorVertices[j-1] = v;
floorVertices[j-2-5] = u + uSize;
floorVertices[j-1-5] = v + vSize;
floorVertices[j-2-10] = u;
floorVertices[j-1-10] = v + vSize;
floorVertices[j-2-15] = u;
floorVertices[j-1-15] = v;
}
idx = 0;
short startIndex = 0;
for(int i = 0, j = 0; i < walls; i++ ) {
tokens = reader.readLine().split(",");
if( !tokens[1].equals("0") ) {
for( int k = 0; k < 4; k++) {
wallVertices[j++] = Float.parseFloat(tokens[0]);
wallVertices[j++] = Float.parseFloat(tokens[1]);
wallVertices[j++] = Float.parseFloat(tokens[2]);
wallVertices[j++] = 0;
wallVertices[j++] = 0;
if(k < 3)
tokens = reader.readLine().split(",");
}
wallIndices[idx++] = startIndex;
wallIndices[idx++] = (short)(startIndex + 1);
wallIndices[idx++] = (short)(startIndex + 2);
wallIndices[idx++] = (short)(startIndex + 2);
wallIndices[idx++] = (short)(startIndex + 3);
wallIndices[idx++] = startIndex;
startIndex+=4;
int type = Integer.parseInt(reader.readLine());
String textureId = reader.readLine();
TextureRegion region = atlas.getRegion(textureId);
float u = region.x / 256.0f;
float v = region.y / 256.0f;
wallVertices[j-2] = u + uSize;
wallVertices[j-1] = v;
wallVertices[j-2-5] = u + vSize;
wallVertices[j-1-5] = v + vSize;
wallVertices[j-2-10] = u;
wallVertices[j-1-10] = v + vSize;
wallVertices[j-2-15] = u;
wallVertices[j-1-15] = v;
}
else {
reader.readLine();
reader.readLine();
reader.readLine();
int type = Integer.parseInt(reader.readLine());
int textureId = Integer.parseInt(reader.readLine());
}
}
floorMesh = new Mesh(true, floors * 4, floors * 6,
new VertexAttribute(VertexAttributes.Usage.Position, 3, "a_position"),
new VertexAttribute(VertexAttributes.Usage.TextureCoordinates, 2, "a_texCoord" ));
floorMesh.setVertices(floorVertices);
floorMesh.setIndices(floorIndices);
wallMesh = new Mesh(true, walls * 4, walls * 6,
new VertexAttribute(VertexAttributes.Usage.Position, 3, "a_position"),
new VertexAttribute(VertexAttributes.Usage.TextureCoordinates, 2, "a_texCoord" ));
wallMesh.setVertices(wallVertices);
wallMesh.setIndices(wallIndices);
reader.close();
}
catch(IOException ex) {
throw new GdxRuntimeException(ex);
}
}
|
diff --git a/runner/src/com/zutubi/android/junitreport/JUnitListener.java b/runner/src/com/zutubi/android/junitreport/JUnitListener.java
index f0d7c89..b3a3707 100644
--- a/runner/src/com/zutubi/android/junitreport/JUnitListener.java
+++ b/runner/src/com/zutubi/android/junitreport/JUnitListener.java
@@ -1,468 +1,469 @@
/*
* Copyright (C) 2010-2011 Zutubi Pty Ltd
*
* 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.zutubi.android.junitreport;
import android.content.Context;
import android.os.Environment;
import android.util.Log;
import android.util.Xml;
import junit.framework.AssertionFailedError;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestListener;
import org.imaginea.botbot.common.DataDrivenTestCase;
import org.xmlpull.v1.XmlSerializer;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Locale;
/**
* Custom test listener that outputs test results to XML files. The files
* use a similar format to the Ant JUnit task XML formatter, with a few of
* caveats:
* <ul>
* <li>
* By default, multiple suites are all placed in a single file under a root
* <testsuites> element. In multiFile mode a separate file is
* created for each suite, which may be more compatible with existing
* tools.
* </li>
* <li>
* Redundant information about the number of nested cases within a suite is
* omitted.
* </li>
* <li>
* Durations are omitted from suites.
* </li>
* <li>
* Neither standard output nor system properties are included.
* </li>
* </ul>
* The differences mainly revolve around making this reporting as lightweight as
* possible. The report is streamed as the tests run, making it impossible to,
* e.g. include the case count in a <testsuite> element.
*/
public class JUnitListener implements TestListener {
private static final String LOG_TAG = "JUnitReportListener";
private static final String ENCODING_UTF_8 = "utf-8";
private static final String TAG_SUITES = "testsuites";
private static final String TAG_SUITE = "testsuite";
private static final String TAG_CASE = "testcase";
private static final String TAG_ERROR = "error";
private static final String TAG_FAILURE = "failure";
private static final String ATTRIBUTE_NAME = "name";
private static final String ATTRIBUTE_CLASS = "classname";
private static final String ATTRIBUTE_TYPE = "type";
private static final String ATTRIBUTE_MESSAGE = "message";
private static final String ATTRIBUTE_TIME = "time";
private static final String ATTRIBUTE_ERRORS = "errors";
private static final String ATTRIBUTE_FAILURES = "failures";
private static final String ATTRIBUTE_TESTS = "tests";
// With thanks to org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner.
// Trimmed some entries, added others for Android.
private static final String[] DEFAULT_TRACE_FILTERS = new String[] {
"junit.framework.TestCase", "junit.framework.TestResult",
"junit.framework.TestSuite",
"junit.framework.Assert.", // don't filter AssertionFailure
"java.lang.reflect.Method.invoke(", "sun.reflect.",
// JUnit 4 support:
"org.junit.", "junit.framework.JUnit4TestAdapter", " more",
// Added for Android
"android.test.", "android.app.Instrumentation",
"java.lang.reflect.Method.invokeNative",
};
private Context mContext;
private Context mTargetContext;
private String mReportFile;
private String mReportDir;
private boolean mFilterTraces;
private boolean mMultiFile;
private FileOutputStream mOutputStream;
private XmlSerializer mSerializer;
private String mCurrentSuite;
private HashMap<String, HashMap<String, TestKeeper>> suiteMap=new HashMap<String, HashMap<String,TestKeeper>>();
private HashMap<String,SuiteKeeper> suiteDetails= new HashMap<String, SuiteKeeper>();
// simple time tracking
private boolean mTimeAlreadyWritten = false;
private long mTestStartTime;
/**
* Creates a new listener.
*
* @param context context of the test application
* @param targetContext context of the application under test
* @param reportFile name of the report file(s) to create
* @param reportDir path of the directory under which to write files
* (may be null in which case files are written under
* the context using {@link Context#openFileOutput(String, int)}).
* @param filterTraces if true, stack traces will have common noise (e.g.
* framework methods) omitted for clarity
* @param multiFile if true, use a separate file for each test suite
*/
public JUnitListener(Context context, Context targetContext, String reportFile, String reportDir, boolean filterTraces, boolean multiFile) {
this.mContext = context;
this.mTargetContext = targetContext;
this.mReportFile = reportFile;
this.mReportDir = reportDir;
this.mFilterTraces = filterTraces;
this.mMultiFile = multiFile;
}
@Override
public void startTest(Test test) {
if (test instanceof TestCase) {
TestCase testCase = (TestCase) test;
TestKeeper testKeeper= new TestKeeper();
String testName=getTestName(test);
testKeeper.setTestname(testName);
mTimeAlreadyWritten = false;
mTestStartTime = System.currentTimeMillis();
testKeeper.setStartTime(mTestStartTime);
testKeeper.setTest(testCase);
checkSuiteDetails(test);
addToSuite(test, testKeeper);
}
}
private void addToSuite(Test test,TestKeeper testKeeper){
TestCase testcase=(TestCase)test;
String suiteName=testcase.getClass().getName();
HashMap<String, TestKeeper> suiteTests;
if(suiteMap.containsKey(suiteName)){
suiteTests=suiteMap.get(suiteName);
}else{
suiteTests=new HashMap<String, TestKeeper>();
}
if(suiteDetails.containsKey(suiteName)){
SuiteKeeper sKeeper= suiteDetails.get(suiteName);
sKeeper.setEndTime(testKeeper.getEndTime());
suiteDetails.put(suiteName, sKeeper);
}
suiteTests.put(getTestName(test), testKeeper);
suiteMap.put(suiteName, suiteTests);
}
private void checkSuiteDetails(Test test){
TestCase testcase=(TestCase)test;
String suiteName=testcase.getClass().getName();
if(!suiteDetails.containsKey(suiteName)){
SuiteKeeper sKeeper= new SuiteKeeper();
sKeeper.setStartTime(System.currentTimeMillis());
suiteDetails.put(suiteName, sKeeper);
}
}
private void updateSuiteDetails(Test test,String tag){
checkSuiteDetails(test);
TestCase testcase=(TestCase)test;
String suiteName=testcase.getClass().getName();
SuiteKeeper suiteKeeper=suiteDetails.get(suiteName);
if(tag.contentEquals(TAG_ERROR)){
suiteKeeper.setErrorCount();
}else if(tag.contentEquals(TAG_FAILURE)){
suiteKeeper.setFailureCount();
}
}
private String getTestName(Test test) {
String testName="";
if (test instanceof TestCase) {
TestCase testCase = (TestCase) test;
if (DataDrivenTestCase.class.isAssignableFrom(test.getClass())) {
testName = ((DataDrivenTestCase) testCase).getCustomTestName();
} else {
testName=testCase.getName();
}
}
return testName;
}
private void checkForNewSuite(String suiteName) throws IOException {
if (mCurrentSuite == null || !mCurrentSuite.equals(suiteName)) {
if (mCurrentSuite != null) {
System.out.println(mCurrentSuite.toString());
if (mMultiFile) {
closeSuite();
} else if(mSerializer!=null){
mSerializer.endTag("", TAG_SUITE);
}
}
openIfRequired(suiteName);
mSerializer.startTag("", TAG_SUITE);
mSerializer.attribute("", ATTRIBUTE_NAME, suiteName);
mCurrentSuite = suiteName;
}
}
private boolean deleteDir(File dir) {
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i=0; i<children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
// The directory is now empty so delete it
return dir.delete();
}
private void openIfRequired(String suiteName) throws IOException {
String state = Environment.getExternalStorageState();
if (mSerializer == null) {
String fileName = mReportFile;
if (mMultiFile) {
fileName = fileName.replace("$(suite)", suiteName);
}
if (mReportDir == null) {
if(Environment.MEDIA_MOUNTED.equals(state)&&!Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)){
File f = mContext.getExternalFilesDir("junit");
mOutputStream=new FileOutputStream(new File(f,fileName));
}else {
mOutputStream = mTargetContext.openFileOutput(fileName, 0);
}
} else {
mOutputStream = new FileOutputStream(new File(mReportDir, fileName));
}
mSerializer = Xml.newSerializer();
mSerializer.setOutput(mOutputStream, ENCODING_UTF_8);
mSerializer.startDocument(ENCODING_UTF_8, true);
if (!mMultiFile) {
mSerializer.startTag("", TAG_SUITES);
}
}
}
@Override
public void addError(Test test, Throwable error) {
addProblem(test,TAG_ERROR, error);
}
@Override
public void addFailure(Test test, AssertionFailedError error) {
addProblem(test,TAG_FAILURE, error);
}
private void addProblem(Test test,String tag, Throwable error) {
recordTestTime(test);
TestKeeper testKeeper= getTestKeeper(test);
testKeeper.setError(error);
testKeeper.setTag(tag);
addToSuite(test, testKeeper);
updateSuiteDetails(test, tag);
}
private TestKeeper getTestKeeper(Test test){
TestCase testcase = (TestCase) test;
String suiteName = testcase.getClass().getName();
HashMap<String, TestKeeper> suiteTests;
if (suiteMap.containsKey(suiteName)) {
suiteTests = suiteMap.get(suiteName);
if (suiteTests.containsKey(getTestName(test))) {
return suiteTests.get(getTestName(test));
}
}
TestKeeper testKeeper = new TestKeeper();
String testName = getTestName(test);
testKeeper.setTestname(testName);
mTestStartTime = System.currentTimeMillis();
testKeeper.setStartTime(mTestStartTime);
testKeeper.setTest(testcase);
return testKeeper;
}
private void recordTestTime(Test test) {
if (!mTimeAlreadyWritten) {
mTimeAlreadyWritten = true;
TestKeeper testKeeper= getTestKeeper(test);
testKeeper.setEndTime(System.currentTimeMillis());
addToSuite(test, testKeeper);
}
}
@Override
public void endTest(Test test) {
if (test instanceof TestCase) {
recordTestTime(test);
}
}
private void addAttribute(String tag,String value) throws IOException{
mSerializer.attribute("", tag, value);
}
public void close(){
Iterator<String> suiteIterator = suiteMap.keySet().iterator();
String state = Environment.getExternalStorageState();
if(Environment.MEDIA_MOUNTED.equals(state)&&!Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)){
File f = mContext.getExternalFilesDir("junit");
if(f.exists()){
deleteDir(f);
f.mkdirs();
}
}
while (suiteIterator.hasNext()) {
try {
String suiteName = suiteIterator.next();
SuiteKeeper suiteKeeper = suiteDetails.get(suiteName);
HashMap<String, TestKeeper> suiteTests=suiteMap.get(suiteName);
checkForNewSuite(suiteName);
addAttribute(ATTRIBUTE_ERRORS, suiteKeeper.getErrorCount());
addAttribute(ATTRIBUTE_FAILURES, suiteKeeper.getFailureCount());
addAttribute(ATTRIBUTE_TESTS, String.valueOf(suiteTests.size()));
- addAttribute(ATTRIBUTE_TIME, String.valueOf(suiteKeeper.getEndTime()-suiteKeeper.getStartTime()));
+ String suiteTime = String.format(Locale.ENGLISH, "%.3f",(suiteKeeper.getEndTime()- suiteKeeper.getStartTime()) / 1000.);
+ addAttribute(ATTRIBUTE_TIME, suiteTime);
Iterator<String> testIterator=suiteTests.keySet().iterator();
while(testIterator.hasNext()){
String testName=testIterator.next();
TestKeeper testKeeper=suiteTests.get(testName);
mSerializer.startTag("",TAG_CASE);
addAttribute(ATTRIBUTE_CLASS, suiteName);
addAttribute(ATTRIBUTE_NAME, testName);
String timeTaken = String.format(Locale.ENGLISH, "%.3f",(testKeeper.getEndTime()- testKeeper.getStartTime()) / 1000.);
addAttribute(ATTRIBUTE_TIME, timeTaken);
if(testKeeper.isFailed()){
String tag = testKeeper.getTag();
Throwable error = testKeeper.getError();
mSerializer.startTag("", tag);
mSerializer.attribute("", ATTRIBUTE_MESSAGE,
safeMessage(error));
mSerializer.attribute("", ATTRIBUTE_TYPE, error
.getClass().getName());
StringWriter w = new StringWriter();
error.printStackTrace(mFilterTraces ? new FilteringWriterTest(
w) : new PrintWriter(w));
mSerializer.text(w.toString());
mSerializer.endTag("", tag);
}
mSerializer.endTag("", TAG_CASE);
}
} catch (IOException e) {
Log.e(LOG_TAG, safeMessage(e));
}
}
closeSuite();
}
/**
* Releases all resources associated with this listener. Must be called
* when the listener is finished with.
*/
public void closeSuite() {
if (mSerializer != null) {
try {
if (mCurrentSuite != null) {
mSerializer.endTag("", TAG_SUITE);
}
if (!mMultiFile) {
mSerializer.endTag("", TAG_SUITES);
}
mSerializer.endDocument();
mSerializer = null;
} catch (IOException e) {
Log.e(LOG_TAG, safeMessage(e));
}
}
if (mOutputStream != null) {
try {
mOutputStream.close();
mOutputStream = null;
} catch (IOException e) {
Log.e(LOG_TAG, safeMessage(e));
}
}
}
private String safeMessage(Throwable error) {
String message = error.getMessage();
return error.getClass().getName() + ": " + (message == null ? "<null>" : message);
}
/**
* Wrapper around a print writer that filters out common noise from stack
* traces, making it easier to see the actual failure.
*/
private static class FilteringWriterTest extends PrintWriter {
public FilteringWriterTest(Writer out) {
super(out);
}
@Override
public void println(String s) {
for (String filtered : DEFAULT_TRACE_FILTERS) {
if (s.contains(filtered)) {
return;
}
}
super.println(s);
}
}
private class SuiteKeeper{
private int failureCount=0;
private int errorCount=0;
private long startTime=0;
private long endTime=0;
public long getStartTime() {
return startTime;
}
public void setStartTime(long startTime) {
this.startTime = startTime;
}
public long getEndTime() {
return endTime;
}
public void setEndTime(long endTime) {
if(this.endTime<endTime){
this.endTime = endTime;
}
}
public String getFailureCount() {
return String.valueOf(failureCount);
}
public void setFailureCount() {
failureCount++;
}
public String getErrorCount() {
return String.valueOf(errorCount);
}
public void setErrorCount() {
errorCount++;
}
}
}
| true | true | public void close(){
Iterator<String> suiteIterator = suiteMap.keySet().iterator();
String state = Environment.getExternalStorageState();
if(Environment.MEDIA_MOUNTED.equals(state)&&!Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)){
File f = mContext.getExternalFilesDir("junit");
if(f.exists()){
deleteDir(f);
f.mkdirs();
}
}
while (suiteIterator.hasNext()) {
try {
String suiteName = suiteIterator.next();
SuiteKeeper suiteKeeper = suiteDetails.get(suiteName);
HashMap<String, TestKeeper> suiteTests=suiteMap.get(suiteName);
checkForNewSuite(suiteName);
addAttribute(ATTRIBUTE_ERRORS, suiteKeeper.getErrorCount());
addAttribute(ATTRIBUTE_FAILURES, suiteKeeper.getFailureCount());
addAttribute(ATTRIBUTE_TESTS, String.valueOf(suiteTests.size()));
addAttribute(ATTRIBUTE_TIME, String.valueOf(suiteKeeper.getEndTime()-suiteKeeper.getStartTime()));
Iterator<String> testIterator=suiteTests.keySet().iterator();
while(testIterator.hasNext()){
String testName=testIterator.next();
TestKeeper testKeeper=suiteTests.get(testName);
mSerializer.startTag("",TAG_CASE);
addAttribute(ATTRIBUTE_CLASS, suiteName);
addAttribute(ATTRIBUTE_NAME, testName);
String timeTaken = String.format(Locale.ENGLISH, "%.3f",(testKeeper.getEndTime()- testKeeper.getStartTime()) / 1000.);
addAttribute(ATTRIBUTE_TIME, timeTaken);
if(testKeeper.isFailed()){
String tag = testKeeper.getTag();
Throwable error = testKeeper.getError();
mSerializer.startTag("", tag);
mSerializer.attribute("", ATTRIBUTE_MESSAGE,
safeMessage(error));
mSerializer.attribute("", ATTRIBUTE_TYPE, error
.getClass().getName());
StringWriter w = new StringWriter();
error.printStackTrace(mFilterTraces ? new FilteringWriterTest(
w) : new PrintWriter(w));
mSerializer.text(w.toString());
mSerializer.endTag("", tag);
}
mSerializer.endTag("", TAG_CASE);
}
} catch (IOException e) {
Log.e(LOG_TAG, safeMessage(e));
}
}
closeSuite();
}
| public void close(){
Iterator<String> suiteIterator = suiteMap.keySet().iterator();
String state = Environment.getExternalStorageState();
if(Environment.MEDIA_MOUNTED.equals(state)&&!Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)){
File f = mContext.getExternalFilesDir("junit");
if(f.exists()){
deleteDir(f);
f.mkdirs();
}
}
while (suiteIterator.hasNext()) {
try {
String suiteName = suiteIterator.next();
SuiteKeeper suiteKeeper = suiteDetails.get(suiteName);
HashMap<String, TestKeeper> suiteTests=suiteMap.get(suiteName);
checkForNewSuite(suiteName);
addAttribute(ATTRIBUTE_ERRORS, suiteKeeper.getErrorCount());
addAttribute(ATTRIBUTE_FAILURES, suiteKeeper.getFailureCount());
addAttribute(ATTRIBUTE_TESTS, String.valueOf(suiteTests.size()));
String suiteTime = String.format(Locale.ENGLISH, "%.3f",(suiteKeeper.getEndTime()- suiteKeeper.getStartTime()) / 1000.);
addAttribute(ATTRIBUTE_TIME, suiteTime);
Iterator<String> testIterator=suiteTests.keySet().iterator();
while(testIterator.hasNext()){
String testName=testIterator.next();
TestKeeper testKeeper=suiteTests.get(testName);
mSerializer.startTag("",TAG_CASE);
addAttribute(ATTRIBUTE_CLASS, suiteName);
addAttribute(ATTRIBUTE_NAME, testName);
String timeTaken = String.format(Locale.ENGLISH, "%.3f",(testKeeper.getEndTime()- testKeeper.getStartTime()) / 1000.);
addAttribute(ATTRIBUTE_TIME, timeTaken);
if(testKeeper.isFailed()){
String tag = testKeeper.getTag();
Throwable error = testKeeper.getError();
mSerializer.startTag("", tag);
mSerializer.attribute("", ATTRIBUTE_MESSAGE,
safeMessage(error));
mSerializer.attribute("", ATTRIBUTE_TYPE, error
.getClass().getName());
StringWriter w = new StringWriter();
error.printStackTrace(mFilterTraces ? new FilteringWriterTest(
w) : new PrintWriter(w));
mSerializer.text(w.toString());
mSerializer.endTag("", tag);
}
mSerializer.endTag("", TAG_CASE);
}
} catch (IOException e) {
Log.e(LOG_TAG, safeMessage(e));
}
}
closeSuite();
}
|
diff --git a/test/models/BaseDataUnitTest.java b/test/models/BaseDataUnitTest.java
index 0a749fd..3f29703 100644
--- a/test/models/BaseDataUnitTest.java
+++ b/test/models/BaseDataUnitTest.java
@@ -1,25 +1,27 @@
package models;
import org.junit.After;
import org.junit.Before;
import play.test.Fixtures;
import play.test.UnitTest;
/**
* Base class for all unit tests using default data in DB.
* @author Sryl <[email protected]>
*/
public abstract class BaseDataUnitTest extends UnitTest {
@Before
public void setUp() {
- Fixtures.deleteAllModels();
+ // CLA 10/04/2012 : Fix https://play.lighthouseapp.com/projects/57987/tickets/425-error-in-reloading-a-yml-file before Play! 1.2.5 release.
+ // cf. http://stackoverflow.com/questions/6266684/cannot-load-fixture-because-of-wrong-duplicate-id-detection
+ Fixtures.deleteDatabase();
Fixtures.loadModels("data.yml");
}
@After
public void tearDown() {
Fixtures.deleteAllModels();
}
}
| true | true | public void setUp() {
Fixtures.deleteAllModels();
Fixtures.loadModels("data.yml");
}
| public void setUp() {
// CLA 10/04/2012 : Fix https://play.lighthouseapp.com/projects/57987/tickets/425-error-in-reloading-a-yml-file before Play! 1.2.5 release.
// cf. http://stackoverflow.com/questions/6266684/cannot-load-fixture-because-of-wrong-duplicate-id-detection
Fixtures.deleteDatabase();
Fixtures.loadModels("data.yml");
}
|
diff --git a/atlas-loader/src/main/java/uk/ac/ebi/gxa/loader/service/AtlasNetCDFUpdaterService.java b/atlas-loader/src/main/java/uk/ac/ebi/gxa/loader/service/AtlasNetCDFUpdaterService.java
index 6fffb4beb..f9f12ab52 100644
--- a/atlas-loader/src/main/java/uk/ac/ebi/gxa/loader/service/AtlasNetCDFUpdaterService.java
+++ b/atlas-loader/src/main/java/uk/ac/ebi/gxa/loader/service/AtlasNetCDFUpdaterService.java
@@ -1,285 +1,285 @@
package uk.ac.ebi.gxa.loader.service;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Iterators;
import com.google.common.collect.ListMultimap;
import uk.ac.ebi.gxa.loader.AtlasLoaderException;
import uk.ac.ebi.gxa.loader.DefaultAtlasLoader;
import uk.ac.ebi.gxa.loader.UpdateNetCDFForExperimentCommand;
import uk.ac.ebi.gxa.loader.datamatrix.DataMatrixStorage;
import uk.ac.ebi.gxa.netcdf.generator.NetCDFCreator;
import uk.ac.ebi.gxa.netcdf.generator.NetCDFCreatorException;
import uk.ac.ebi.gxa.netcdf.reader.NetCDFProxy;
import uk.ac.ebi.gxa.utils.EfvTree;
import uk.ac.ebi.gxa.utils.Maker;
import uk.ac.ebi.gxa.utils.Pair;
import uk.ac.ebi.microarray.atlas.model.*;
import javax.annotation.Nonnull;
import java.io.File;
import java.io.IOException;
import java.util.*;
import static com.google.common.collect.Iterators.concat;
import static com.google.common.collect.Iterators.filter;
import static com.google.common.io.Closeables.closeQuietly;
import static com.google.common.primitives.Floats.asList;
import static uk.ac.ebi.gxa.netcdf.reader.AtlasNetCDFDAO.getNetCDFLocation;
import static uk.ac.ebi.gxa.utils.CountIterator.zeroTo;
/**
* NetCDF updater service which preserves expression values information, but updates all properties
*
* @author pashky
*/
public class AtlasNetCDFUpdaterService extends AtlasLoaderService {
public AtlasNetCDFUpdaterService(DefaultAtlasLoader atlasLoader) {
super(atlasLoader);
}
private static class CBitSet extends BitSet implements Comparable<CBitSet> {
private CBitSet(int nbits) {
super(nbits);
}
public int compareTo(CBitSet o) {
for (int i = 0; i < Math.max(size(), o.size()); ++i) {
boolean b1 = get(i);
boolean b2 = o.get(i);
if (b1 != b2)
return b1 ? 1 : -1;
}
return 0;
}
}
private static class CPair<T1 extends Comparable<T1>, T2 extends Comparable<T2>> extends Pair<T1, T2> implements Comparable<CPair<T1, T2>> {
private CPair(T1 first, T2 second) {
super(first, second);
}
public int compareTo(CPair<T1, T2> o) {
int d = getFirst().compareTo(o.getFirst());
return d != 0 ? d : getSecond().compareTo(o.getSecond());
}
}
private EfvTree<CPair<String, String>> matchEfvs(EfvTree<CBitSet> from, EfvTree<CBitSet> to) {
final List<EfvTree.Ef<CBitSet>> fromTree = matchEfvsSort(from);
final List<EfvTree.Ef<CBitSet>> toTree = matchEfvsSort(to);
EfvTree<CPair<String, String>> result = new EfvTree<CPair<String, String>>();
for (EfvTree.Ef<CBitSet> toEf : toTree) {
boolean matched = false;
for (EfvTree.Ef<CBitSet> fromEf : fromTree)
if (fromEf.getEfvs().size() == toEf.getEfvs().size()) {
int i;
for (i = 0; i < fromEf.getEfvs().size(); ++i)
if (!fromEf.getEfvs().get(i).getPayload().equals(toEf.getEfvs().get(i).getPayload()))
break;
if (i == fromEf.getEfvs().size()) {
for (i = 0; i < fromEf.getEfvs().size(); ++i)
result.put(toEf.getEf(), toEf.getEfvs().get(i).getEfv(),
new CPair<String, String>(fromEf.getEf(), fromEf.getEfvs().get(i).getEfv()));
matched = true;
}
}
if (!matched)
return null;
}
return result;
}
private List<EfvTree.Ef<CBitSet>> matchEfvsSort(EfvTree<CBitSet> from) {
final List<EfvTree.Ef<CBitSet>> fromTree = from.getNameSortedTree();
for (EfvTree.Ef<CBitSet> ef : fromTree) {
Collections.sort(ef.getEfvs(), new Comparator<EfvTree.Efv<CBitSet>>() {
public int compare(EfvTree.Efv<CBitSet> o1, EfvTree.Efv<CBitSet> o2) {
return o1.getPayload().compareTo(o2.getPayload());
}
});
}
return fromTree;
}
private EfvTree<CBitSet> getEfvPatternsFromAssays(final List<Assay> assays) {
Set<String> efs = new HashSet<String>();
for (Assay assay : assays)
for (Property prop : assay.getProperties())
efs.add(prop.getName());
EfvTree<CBitSet> efvTree = new EfvTree<CBitSet>();
int i = 0;
for (Assay assay : assays) {
for (final String propName : efs) {
String value = assay.getPropertySummary(propName);
efvTree.getOrCreate(propName, value, new Maker<CBitSet>() {
public CBitSet make() {
return new CBitSet(assays.size());
}
}).set(i, true);
}
++i;
}
return efvTree;
}
public void process(UpdateNetCDFForExperimentCommand cmd, AtlasLoaderServiceListener listener) throws AtlasLoaderException {
String experimentAccession = cmd.getAccession();
listener.setAccession(experimentAccession);
List<Assay> assays = getAtlasDAO().getAssaysByExperimentAccession(experimentAccession);
ListMultimap<String, Assay> assaysByArrayDesign = ArrayListMultimap.create();
for (Assay assay : assays) {
String adAcc = assay.getArrayDesignAccession();
if (null != adAcc)
assaysByArrayDesign.put(adAcc, assay);
}
Experiment experiment = getAtlasDAO().getExperimentByAccession(experimentAccession);
final String version = "NetCDF Updater";
for (String arrayDesignAccession : assaysByArrayDesign.keySet()) {
ArrayDesign arrayDesign = getAtlasDAO().getArrayDesignByAccession(arrayDesignAccession);
final File netCDFLocation = getNetCDFLocation(getAtlasNetCDFDirectory(experimentAccession), experiment, arrayDesign);
listener.setProgress("Reading existing NetCDF");
final List<Assay> arrayDesignAssays = assaysByArrayDesign.get(arrayDesignAccession);
getLog().info("Starting NetCDF for " + experimentAccession +
" and " + arrayDesignAccession + " (" + arrayDesignAssays.size() + " assays)");
// TODO: create an entity encapsulating the following values: it is what we read from NetCDF
EfvTree<CPair<String, String>> matchedEfvs = null;
final List<Assay> leaveAssays;
DataMatrixStorage storage;
String[] uEFVs;
NetCDFProxy reader = null;
try {
reader = new NetCDFProxy(netCDFLocation);
leaveAssays = new ArrayList<Assay>(arrayDesignAssays.size());
final long[] oldAssays = reader.getAssays();
for (int i = 0; i < oldAssays.length; ++i) {
for (Assay assay : arrayDesignAssays)
if (assay.getAssayID() == oldAssays[i]) {
leaveAssays.add(assay);
oldAssays[i] = -1; // mark it as used for later filtering
break;
}
}
if (oldAssays.length == leaveAssays.size()) {
EfvTree<CBitSet> oldEfvPats = new EfvTree<CBitSet>();
for (String ef : reader.getFactors()) {
String[] efvs = reader.getFactorValues(ef);
for (String efv : new HashSet<String>(Arrays.asList(efvs))) {
CBitSet pattern = new CBitSet(efvs.length);
for (int i = 0; i < efvs.length; ++i)
pattern.set(i, efvs[i].equals(efv));
oldEfvPats.put(ef, efv, pattern);
}
}
EfvTree<CBitSet> newEfvPats = getEfvPatternsFromAssays(leaveAssays);
matchedEfvs = matchEfvs(oldEfvPats, newEfvPats);
}
uEFVs = reader.getUniqueFactorValues();
String[] deAccessions = reader.getDesignElementAccessions();
storage = new DataMatrixStorage(
leaveAssays.size() + (matchedEfvs != null ? uEFVs.length * 2 : 0), // expressions + pvals + tstats
deAccessions.length, 1);
for (int i = 0; i < deAccessions.length; ++i) {
final float[] values = reader.getExpressionDataForDesignElementAtIndex(i);
final float[] pval = reader.getPValuesForDesignElement(i);
final float[] tstat = reader.getTStatisticsForDesignElement(i);
storage.add(deAccessions[i], concat(
Iterators.transform(
filter(
zeroTo(values.length),
new Predicate<Integer>() {
public boolean apply(@Nonnull Integer j) {
return oldAssays[j] == -1; // skips deleted assays
}
}),
new Function<Integer, Float>() {
public Float apply(@Nonnull Integer j) {
return values[j];
}
}),
asList(pval).iterator(),
asList(tstat).iterator()));
}
} catch (IOException e) {
getLog().error("Error reading NetCDF for " + experimentAccession +
" and " + arrayDesignAccession);
throw new AtlasLoaderException(e);
} finally {
closeQuietly(reader);
}
try {
listener.setProgress("Writing new NetCDF");
NetCDFCreator netCdfCreator = new NetCDFCreator();
netCdfCreator.setAssays(leaveAssays);
for (Assay assay : leaveAssays)
for (Sample sample : getAtlasDAO().getSamplesByAssayAccession(experimentAccession, assay.getAccession()))
netCdfCreator.setSample(assay, sample);
Map<String, DataMatrixStorage.ColumnRef> dataMap = new HashMap<String, DataMatrixStorage.ColumnRef>();
for (int i = 0; i < leaveAssays.size(); ++i)
dataMap.put(leaveAssays.get(i).getAccession(), new DataMatrixStorage.ColumnRef(storage, i));
netCdfCreator.setAssayDataMap(dataMap);
if (matchedEfvs != null) {
Map<Pair<String, String>, DataMatrixStorage.ColumnRef> pvalMap = new HashMap<Pair<String, String>, DataMatrixStorage.ColumnRef>();
Map<Pair<String, String>, DataMatrixStorage.ColumnRef> tstatMap = new HashMap<Pair<String, String>, DataMatrixStorage.ColumnRef>();
for (EfvTree.EfEfv<CPair<String, String>> efEfv : matchedEfvs.getNameSortedList()) {
final int oldPos = Arrays.asList(uEFVs).indexOf(efEfv.getPayload().getFirst() + "||" + efEfv.getPayload().getSecond());
pvalMap.put(Pair.create(efEfv.getEf(), efEfv.getEfv()),
new DataMatrixStorage.ColumnRef(storage, leaveAssays.size() + oldPos));
tstatMap.put(Pair.create(efEfv.getEf(), efEfv.getEfv()),
new DataMatrixStorage.ColumnRef(storage, leaveAssays.size() + uEFVs.length + oldPos));
}
netCdfCreator.setPvalDataMap(pvalMap);
netCdfCreator.setTstatDataMap(tstatMap);
}
netCdfCreator.setArrayDesign(arrayDesign);
netCdfCreator.setExperiment(experiment);
netCdfCreator.setVersion(version);
final File tempFile = File.createTempFile(experimentAccession, ".nc.tmp");
netCdfCreator.createNetCdf(tempFile);
- if (!netCDFLocation.delete() && !tempFile.renameTo(netCDFLocation))
+ if (!netCDFLocation.delete() || !tempFile.renameTo(netCDFLocation))
throw new AtlasLoaderException("Can't update original NetCDF file " + netCDFLocation);
getLog().info("Successfully finished NetCDF for " + experimentAccession +
" and " + arrayDesignAccession);
if (matchedEfvs != null)
listener.setRecomputeAnalytics(false);
} catch (NetCDFCreatorException e) {
getLog().error("Error writing NetCDF for " + experimentAccession +
" and " + arrayDesignAccession);
throw new AtlasLoaderException(e);
} catch (IOException e) {
getLog().error("Error writing NetCDF for " + experimentAccession +
" and " + arrayDesignAccession);
throw new AtlasLoaderException(e);
}
}
}
}
| true | true | public void process(UpdateNetCDFForExperimentCommand cmd, AtlasLoaderServiceListener listener) throws AtlasLoaderException {
String experimentAccession = cmd.getAccession();
listener.setAccession(experimentAccession);
List<Assay> assays = getAtlasDAO().getAssaysByExperimentAccession(experimentAccession);
ListMultimap<String, Assay> assaysByArrayDesign = ArrayListMultimap.create();
for (Assay assay : assays) {
String adAcc = assay.getArrayDesignAccession();
if (null != adAcc)
assaysByArrayDesign.put(adAcc, assay);
}
Experiment experiment = getAtlasDAO().getExperimentByAccession(experimentAccession);
final String version = "NetCDF Updater";
for (String arrayDesignAccession : assaysByArrayDesign.keySet()) {
ArrayDesign arrayDesign = getAtlasDAO().getArrayDesignByAccession(arrayDesignAccession);
final File netCDFLocation = getNetCDFLocation(getAtlasNetCDFDirectory(experimentAccession), experiment, arrayDesign);
listener.setProgress("Reading existing NetCDF");
final List<Assay> arrayDesignAssays = assaysByArrayDesign.get(arrayDesignAccession);
getLog().info("Starting NetCDF for " + experimentAccession +
" and " + arrayDesignAccession + " (" + arrayDesignAssays.size() + " assays)");
// TODO: create an entity encapsulating the following values: it is what we read from NetCDF
EfvTree<CPair<String, String>> matchedEfvs = null;
final List<Assay> leaveAssays;
DataMatrixStorage storage;
String[] uEFVs;
NetCDFProxy reader = null;
try {
reader = new NetCDFProxy(netCDFLocation);
leaveAssays = new ArrayList<Assay>(arrayDesignAssays.size());
final long[] oldAssays = reader.getAssays();
for (int i = 0; i < oldAssays.length; ++i) {
for (Assay assay : arrayDesignAssays)
if (assay.getAssayID() == oldAssays[i]) {
leaveAssays.add(assay);
oldAssays[i] = -1; // mark it as used for later filtering
break;
}
}
if (oldAssays.length == leaveAssays.size()) {
EfvTree<CBitSet> oldEfvPats = new EfvTree<CBitSet>();
for (String ef : reader.getFactors()) {
String[] efvs = reader.getFactorValues(ef);
for (String efv : new HashSet<String>(Arrays.asList(efvs))) {
CBitSet pattern = new CBitSet(efvs.length);
for (int i = 0; i < efvs.length; ++i)
pattern.set(i, efvs[i].equals(efv));
oldEfvPats.put(ef, efv, pattern);
}
}
EfvTree<CBitSet> newEfvPats = getEfvPatternsFromAssays(leaveAssays);
matchedEfvs = matchEfvs(oldEfvPats, newEfvPats);
}
uEFVs = reader.getUniqueFactorValues();
String[] deAccessions = reader.getDesignElementAccessions();
storage = new DataMatrixStorage(
leaveAssays.size() + (matchedEfvs != null ? uEFVs.length * 2 : 0), // expressions + pvals + tstats
deAccessions.length, 1);
for (int i = 0; i < deAccessions.length; ++i) {
final float[] values = reader.getExpressionDataForDesignElementAtIndex(i);
final float[] pval = reader.getPValuesForDesignElement(i);
final float[] tstat = reader.getTStatisticsForDesignElement(i);
storage.add(deAccessions[i], concat(
Iterators.transform(
filter(
zeroTo(values.length),
new Predicate<Integer>() {
public boolean apply(@Nonnull Integer j) {
return oldAssays[j] == -1; // skips deleted assays
}
}),
new Function<Integer, Float>() {
public Float apply(@Nonnull Integer j) {
return values[j];
}
}),
asList(pval).iterator(),
asList(tstat).iterator()));
}
} catch (IOException e) {
getLog().error("Error reading NetCDF for " + experimentAccession +
" and " + arrayDesignAccession);
throw new AtlasLoaderException(e);
} finally {
closeQuietly(reader);
}
try {
listener.setProgress("Writing new NetCDF");
NetCDFCreator netCdfCreator = new NetCDFCreator();
netCdfCreator.setAssays(leaveAssays);
for (Assay assay : leaveAssays)
for (Sample sample : getAtlasDAO().getSamplesByAssayAccession(experimentAccession, assay.getAccession()))
netCdfCreator.setSample(assay, sample);
Map<String, DataMatrixStorage.ColumnRef> dataMap = new HashMap<String, DataMatrixStorage.ColumnRef>();
for (int i = 0; i < leaveAssays.size(); ++i)
dataMap.put(leaveAssays.get(i).getAccession(), new DataMatrixStorage.ColumnRef(storage, i));
netCdfCreator.setAssayDataMap(dataMap);
if (matchedEfvs != null) {
Map<Pair<String, String>, DataMatrixStorage.ColumnRef> pvalMap = new HashMap<Pair<String, String>, DataMatrixStorage.ColumnRef>();
Map<Pair<String, String>, DataMatrixStorage.ColumnRef> tstatMap = new HashMap<Pair<String, String>, DataMatrixStorage.ColumnRef>();
for (EfvTree.EfEfv<CPair<String, String>> efEfv : matchedEfvs.getNameSortedList()) {
final int oldPos = Arrays.asList(uEFVs).indexOf(efEfv.getPayload().getFirst() + "||" + efEfv.getPayload().getSecond());
pvalMap.put(Pair.create(efEfv.getEf(), efEfv.getEfv()),
new DataMatrixStorage.ColumnRef(storage, leaveAssays.size() + oldPos));
tstatMap.put(Pair.create(efEfv.getEf(), efEfv.getEfv()),
new DataMatrixStorage.ColumnRef(storage, leaveAssays.size() + uEFVs.length + oldPos));
}
netCdfCreator.setPvalDataMap(pvalMap);
netCdfCreator.setTstatDataMap(tstatMap);
}
netCdfCreator.setArrayDesign(arrayDesign);
netCdfCreator.setExperiment(experiment);
netCdfCreator.setVersion(version);
final File tempFile = File.createTempFile(experimentAccession, ".nc.tmp");
netCdfCreator.createNetCdf(tempFile);
if (!netCDFLocation.delete() && !tempFile.renameTo(netCDFLocation))
throw new AtlasLoaderException("Can't update original NetCDF file " + netCDFLocation);
getLog().info("Successfully finished NetCDF for " + experimentAccession +
" and " + arrayDesignAccession);
if (matchedEfvs != null)
listener.setRecomputeAnalytics(false);
} catch (NetCDFCreatorException e) {
getLog().error("Error writing NetCDF for " + experimentAccession +
" and " + arrayDesignAccession);
throw new AtlasLoaderException(e);
} catch (IOException e) {
getLog().error("Error writing NetCDF for " + experimentAccession +
" and " + arrayDesignAccession);
throw new AtlasLoaderException(e);
}
}
}
| public void process(UpdateNetCDFForExperimentCommand cmd, AtlasLoaderServiceListener listener) throws AtlasLoaderException {
String experimentAccession = cmd.getAccession();
listener.setAccession(experimentAccession);
List<Assay> assays = getAtlasDAO().getAssaysByExperimentAccession(experimentAccession);
ListMultimap<String, Assay> assaysByArrayDesign = ArrayListMultimap.create();
for (Assay assay : assays) {
String adAcc = assay.getArrayDesignAccession();
if (null != adAcc)
assaysByArrayDesign.put(adAcc, assay);
}
Experiment experiment = getAtlasDAO().getExperimentByAccession(experimentAccession);
final String version = "NetCDF Updater";
for (String arrayDesignAccession : assaysByArrayDesign.keySet()) {
ArrayDesign arrayDesign = getAtlasDAO().getArrayDesignByAccession(arrayDesignAccession);
final File netCDFLocation = getNetCDFLocation(getAtlasNetCDFDirectory(experimentAccession), experiment, arrayDesign);
listener.setProgress("Reading existing NetCDF");
final List<Assay> arrayDesignAssays = assaysByArrayDesign.get(arrayDesignAccession);
getLog().info("Starting NetCDF for " + experimentAccession +
" and " + arrayDesignAccession + " (" + arrayDesignAssays.size() + " assays)");
// TODO: create an entity encapsulating the following values: it is what we read from NetCDF
EfvTree<CPair<String, String>> matchedEfvs = null;
final List<Assay> leaveAssays;
DataMatrixStorage storage;
String[] uEFVs;
NetCDFProxy reader = null;
try {
reader = new NetCDFProxy(netCDFLocation);
leaveAssays = new ArrayList<Assay>(arrayDesignAssays.size());
final long[] oldAssays = reader.getAssays();
for (int i = 0; i < oldAssays.length; ++i) {
for (Assay assay : arrayDesignAssays)
if (assay.getAssayID() == oldAssays[i]) {
leaveAssays.add(assay);
oldAssays[i] = -1; // mark it as used for later filtering
break;
}
}
if (oldAssays.length == leaveAssays.size()) {
EfvTree<CBitSet> oldEfvPats = new EfvTree<CBitSet>();
for (String ef : reader.getFactors()) {
String[] efvs = reader.getFactorValues(ef);
for (String efv : new HashSet<String>(Arrays.asList(efvs))) {
CBitSet pattern = new CBitSet(efvs.length);
for (int i = 0; i < efvs.length; ++i)
pattern.set(i, efvs[i].equals(efv));
oldEfvPats.put(ef, efv, pattern);
}
}
EfvTree<CBitSet> newEfvPats = getEfvPatternsFromAssays(leaveAssays);
matchedEfvs = matchEfvs(oldEfvPats, newEfvPats);
}
uEFVs = reader.getUniqueFactorValues();
String[] deAccessions = reader.getDesignElementAccessions();
storage = new DataMatrixStorage(
leaveAssays.size() + (matchedEfvs != null ? uEFVs.length * 2 : 0), // expressions + pvals + tstats
deAccessions.length, 1);
for (int i = 0; i < deAccessions.length; ++i) {
final float[] values = reader.getExpressionDataForDesignElementAtIndex(i);
final float[] pval = reader.getPValuesForDesignElement(i);
final float[] tstat = reader.getTStatisticsForDesignElement(i);
storage.add(deAccessions[i], concat(
Iterators.transform(
filter(
zeroTo(values.length),
new Predicate<Integer>() {
public boolean apply(@Nonnull Integer j) {
return oldAssays[j] == -1; // skips deleted assays
}
}),
new Function<Integer, Float>() {
public Float apply(@Nonnull Integer j) {
return values[j];
}
}),
asList(pval).iterator(),
asList(tstat).iterator()));
}
} catch (IOException e) {
getLog().error("Error reading NetCDF for " + experimentAccession +
" and " + arrayDesignAccession);
throw new AtlasLoaderException(e);
} finally {
closeQuietly(reader);
}
try {
listener.setProgress("Writing new NetCDF");
NetCDFCreator netCdfCreator = new NetCDFCreator();
netCdfCreator.setAssays(leaveAssays);
for (Assay assay : leaveAssays)
for (Sample sample : getAtlasDAO().getSamplesByAssayAccession(experimentAccession, assay.getAccession()))
netCdfCreator.setSample(assay, sample);
Map<String, DataMatrixStorage.ColumnRef> dataMap = new HashMap<String, DataMatrixStorage.ColumnRef>();
for (int i = 0; i < leaveAssays.size(); ++i)
dataMap.put(leaveAssays.get(i).getAccession(), new DataMatrixStorage.ColumnRef(storage, i));
netCdfCreator.setAssayDataMap(dataMap);
if (matchedEfvs != null) {
Map<Pair<String, String>, DataMatrixStorage.ColumnRef> pvalMap = new HashMap<Pair<String, String>, DataMatrixStorage.ColumnRef>();
Map<Pair<String, String>, DataMatrixStorage.ColumnRef> tstatMap = new HashMap<Pair<String, String>, DataMatrixStorage.ColumnRef>();
for (EfvTree.EfEfv<CPair<String, String>> efEfv : matchedEfvs.getNameSortedList()) {
final int oldPos = Arrays.asList(uEFVs).indexOf(efEfv.getPayload().getFirst() + "||" + efEfv.getPayload().getSecond());
pvalMap.put(Pair.create(efEfv.getEf(), efEfv.getEfv()),
new DataMatrixStorage.ColumnRef(storage, leaveAssays.size() + oldPos));
tstatMap.put(Pair.create(efEfv.getEf(), efEfv.getEfv()),
new DataMatrixStorage.ColumnRef(storage, leaveAssays.size() + uEFVs.length + oldPos));
}
netCdfCreator.setPvalDataMap(pvalMap);
netCdfCreator.setTstatDataMap(tstatMap);
}
netCdfCreator.setArrayDesign(arrayDesign);
netCdfCreator.setExperiment(experiment);
netCdfCreator.setVersion(version);
final File tempFile = File.createTempFile(experimentAccession, ".nc.tmp");
netCdfCreator.createNetCdf(tempFile);
if (!netCDFLocation.delete() || !tempFile.renameTo(netCDFLocation))
throw new AtlasLoaderException("Can't update original NetCDF file " + netCDFLocation);
getLog().info("Successfully finished NetCDF for " + experimentAccession +
" and " + arrayDesignAccession);
if (matchedEfvs != null)
listener.setRecomputeAnalytics(false);
} catch (NetCDFCreatorException e) {
getLog().error("Error writing NetCDF for " + experimentAccession +
" and " + arrayDesignAccession);
throw new AtlasLoaderException(e);
} catch (IOException e) {
getLog().error("Error writing NetCDF for " + experimentAccession +
" and " + arrayDesignAccession);
throw new AtlasLoaderException(e);
}
}
}
|
diff --git a/loci/formats/out/AVIWriter.java b/loci/formats/out/AVIWriter.java
index d358a5529..6c18c42a1 100644
--- a/loci/formats/out/AVIWriter.java
+++ b/loci/formats/out/AVIWriter.java
@@ -1,543 +1,543 @@
//
// AVIWriter.java
//
/*
LOCI Bio-Formats package for reading and converting biological file formats.
Copyright (C) 2005-@year@ Melissa Linkert, Curtis Rueden, Chris Allan,
Eric Kjellman and Brian Loranger.
This program 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 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 Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package loci.formats.out;
import java.awt.Image;
import java.awt.image.*;
import java.io.*;
import java.util.Vector;
import loci.formats.*;
/**
* AVIWriter is the file format writer for AVI files.
*
* Much of this writer's code was adapted from Wayne Rasband's
* AVI Movie Writer plugin for ImageJ
* (available at http://rsb.info.nih.gov/ij/).
*/
public class AVIWriter extends FormatWriter {
// -- Fields --
private RandomAccessFile raFile;
private int planesWritten = 0;
private int bytesPerPixel;
private File file;
private int xDim, yDim, zDim, tDim, xPad;
private int microSecPerFrame;
// location of file size in bytes not counting first 8 bytes
private long saveFileSize;
// location of length of CHUNK with first LIST - not including first 8
// bytes with LIST and size. JUNK follows the end of this CHUNK
private long saveLIST1Size;
// location of length of CHUNK with second LIST - not including first 8
// bytes with LIST and size. Note that saveLIST1subSize = saveLIST1Size +
// 76, and that the length size written to saveLIST2Size is 76 less than
// that written to saveLIST1Size. JUNK follows the end of this CHUNK.
private long saveLIST1subSize;
// location of length of strf CHUNK - not including the first 8 bytes with
// strf and size. strn follows the end of this CHUNK.
private long savestrfSize;
private byte[] text;
private long savestrnPos;
private long saveJUNKsignature;
private int paddingBytes;
private long saveLIST2Size;
private byte[] dataSignature;
private Vector savedbLength;
private long idx1Pos;
private long endPos;
private long saveidx1Length;
private int z;
private long savemovi;
private int xMod;
private long frameOffset;
private long frameOffset2;
private int savePlaneNum;
// -- Constructor --
public AVIWriter() { super("Audio Video Interleave", "avi"); }
// -- IFormatWriter API methods --
/**
* Saves the given image to the specified (possibly already open) file.
* If this image is the last one in the file, the last flag must be set.
*/
public void save(String id, Image image, boolean last)
throws FormatException, IOException
{
if (image == null) {
throw new FormatException("Image is null");
}
BufferedImage img = null;
if (cm != null) img = ImageTools.makeBuffered(image, cm);
else img = ImageTools.makeBuffered(image);
byte[][] byteData = ImageTools.getBytes(img);
if (!id.equals(currentId)) {
planesWritten = 0;
currentId = id;
bytesPerPixel = byteData.length;
file = new File(id);
raFile = new RandomAccessFile(file, "rw");
raFile.seek(raFile.length());
saveFileSize = 4;
saveLIST1Size = 16;
saveLIST1subSize = 23 * 4;
frameOffset = 48;
frameOffset2 = 35 * 4;
savestrfSize = 42 * 4;
savestrnPos = savestrfSize + 44 + (bytesPerPixel == 1 ? 4 * 256 : 0);
- saveJUNKsignature = savestrnPos + 16;
+ saveJUNKsignature = savestrnPos + 24;
saveLIST2Size = 4088;
savemovi = 4092;
savedbLength = new Vector();
dataSignature = new byte[4];
dataSignature[0] = 48; // 0
dataSignature[1] = 48; // 0
dataSignature[2] = 100; // d
dataSignature[3] = 98; // b
tDim = 1;
zDim = 1;
yDim = img.getHeight();
xDim = img.getWidth();
xPad = 0;
xMod = xDim % 4;
if (xMod != 0) {
xPad = 4 - xMod;
xDim += xPad;
}
if (raFile.length() == 0) {
DataTools.writeString(raFile, "RIFF"); // signature
// Bytes 4 thru 7 contain the length of the file. This length does
// not include bytes 0 thru 7.
DataTools.writeInt(raFile, 0, true); // for now write 0 for size
DataTools.writeString(raFile, "AVI "); // RIFF type
// Write the first LIST chunk, which contains
// information on data decoding
DataTools.writeString(raFile, "LIST"); // CHUNK signature
// Write the length of the LIST CHUNK not including the first 8 bytes
// with LIST and size. Note that the end of the LIST CHUNK is followed
// by JUNK.
DataTools.writeInt(raFile, (bytesPerPixel == 1) ? 1240 : 216, true);
DataTools.writeString(raFile, "hdrl"); // CHUNK type
DataTools.writeString(raFile, "avih"); // Write the avih sub-CHUNK
// Write the length of the avih sub-CHUNK (38H) not including the
// the first 8 bytes for avihSignature and the length
DataTools.writeInt(raFile, 0x38, true);
// dwMicroSecPerFrame - Write the microseconds per frame
microSecPerFrame = (int) (1.0 / fps * 1.0e6);
DataTools.writeInt(raFile, microSecPerFrame, true);
// Write the maximum data rate of the file in bytes per second
DataTools.writeInt(raFile, 0, true); // dwMaxBytesPerSec
DataTools.writeInt(raFile, 0, true); // dwReserved1 - set to 0
// dwFlags - just set the bit for AVIF_HASINDEX
savePlaneNum = (int) raFile.getFilePointer();
DataTools.writeInt(raFile, 0x10, true);
// 10H AVIF_HASINDEX: The AVI file has an idx1 chunk containing
// an index at the end of the file. For good performance, all
// AVI files should contain an index.
// 20H AVIF_MUSTUSEINDEX: Index CHUNK, rather than the physical
// ordering of the chunks in the file, must be used to determine the
// order of the frames.
// 100H AVIF_ISINTERLEAVED: Indicates that the AVI file is interleaved.
// This is used to read data from a CD-ROM more efficiently.
// 800H AVIF_TRUSTCKTYPE: USE CKType to find key frames
// 10000H AVIF_WASCAPTUREFILE: The AVI file is used for capturing
// real-time video. Applications should warn the user before
// writing over a file with this fla set because the user
// probably defragmented this file.
// 20000H AVIF_COPYRIGHTED: The AVI file contains copyrighted data
// and software. When, this flag is used, software should not
// permit the data to be duplicated.
// dwTotalFrames - total frame number
DataTools.writeInt(raFile, zDim * tDim, true);
// dwInitialFrames -Initial frame for interleaved files.
// Noninterleaved files should specify 0.
DataTools.writeInt(raFile, 0, true);
// dwStreams - number of streams in the file - here 1 video and
// zero audio.
DataTools.writeInt(raFile, 1, true);
// dwSuggestedBufferSize - Suggested buffer size for reading the file.
// Generally, this size should be large enough to contain the largest
// chunk in the file.
DataTools.writeInt(raFile, 0, true);
// dwWidth - image width in pixels
DataTools.writeInt(raFile, xDim - xPad, true);
DataTools.writeInt(raFile, yDim, true); // dwHeight - height in pixels
// dwReserved[4] - Microsoft says to set the following 4 values to 0.
DataTools.writeInt(raFile, 0, true);
DataTools.writeInt(raFile, 0, true);
DataTools.writeInt(raFile, 0, true);
DataTools.writeInt(raFile, 0, true);
// Write the Stream line header CHUNK
DataTools.writeString(raFile, "LIST");
// Write the size of the first LIST subCHUNK not including the first 8
// bytes with LIST and size. Note that saveLIST1subSize = saveLIST1Size
// + 76, and that the length written to saveLIST1subSize is 76 less than
// the length written to saveLIST1Size. The end of the first LIST
// subCHUNK is followed by JUNK.
DataTools.writeInt(raFile, (bytesPerPixel == 1) ? 1164 : 140 , true);
DataTools.writeString(raFile, "strl"); // Write the chunk type
DataTools.writeString(raFile, "strh"); // Write the strh sub-CHUNK
DataTools.writeInt(raFile, 56, true); // Write length of strh sub-CHUNK
// fccType - Write the type of data stream - here vids for video stream
DataTools.writeString(raFile, "vids");
// Write DIB for Microsoft Device Independent Bitmap.
// Note: Unfortunately, at least 3 other four character codes are
// sometimes used for uncompressed AVI videos: 'RGB ', 'RAW ',
// 0x00000000
DataTools.writeString(raFile, "DIB ");
DataTools.writeInt(raFile, 0, true); // dwFlags
// 0x00000001 AVISF_DISABLED The stram data should be rendered only when
// explicitly enabled.
// 0x00010000 AVISF_VIDEO_PALCHANGES Indicates that a palette change is
// included in the AVI file. This flag warns the playback software that
// it will need to animate the palette.
// dwPriority - priority of a stream type. For example, in a file with
// multiple audio streams, the one with the highest priority might be
// the default one.
DataTools.writeInt(raFile, 0, true);
// dwInitialFrames - Specifies how far audio data is skewed ahead of
// video frames in interleaved files. Typically, this is about 0.75
// seconds. In interleaved files specify the number of frames in the
// file prior to the initial frame of the AVI sequence.
// Noninterleaved files should use zero.
DataTools.writeInt(raFile, 0, true);
// rate/scale = samples/second
DataTools.writeInt(raFile, 1, true); // dwScale
// dwRate - frame rate for video streams
DataTools.writeInt(raFile, fps, true);
// dwStart - this field is usually set to zero
DataTools.writeInt(raFile, 0, true);
// dwLength - playing time of AVI file as defined by scale and rate
// Set equal to the number of frames
DataTools.writeInt(raFile, tDim * zDim, true);
// dwSuggestedBufferSize - Suggested buffer size for reading the stream.
// Typically, this contains a value corresponding to the largest chunk
// in a stream.
DataTools.writeInt(raFile, 0, true);
// dwQuality - encoding quality given by an integer between 0 and
// 10,000. If set to -1, drivers use the default quality value.
DataTools.writeInt(raFile, -1, true);
// dwSampleSize #
// 0 if the video frames may or may not vary in size
// If 0, each sample of data(such as a video frame) must be in a
// separate chunk. If nonzero, then multiple samples of data can be
// grouped into a single chunk within the file.
DataTools.writeInt(raFile, 0, true);
// rcFrame - Specifies the destination rectangle for a text or video
// stream within the movie rectangle specified by the dwWidth and
// dwHeight members of the AVI main header structure. The rcFrame member
// is typically used in support of multiple video streams. Set this
// rectangle to the coordinates corresponding to the movie rectangle to
// update the whole movie rectangle. Units for this member are pixels.
// The upper-left corner of the destination rectangle is relative to the
// upper-left corner of the movie rectangle.
DataTools.writeShort(raFile, (short) 0, true); // left
DataTools.writeShort(raFile, (short) 0, true); // top
DataTools.writeShort(raFile, (short) 0, true); // right
DataTools.writeShort(raFile, (short) 0, true); // bottom
// Write the size of the stream format CHUNK not including the first 8
// bytes for strf and the size. Note that the end of the stream format
// CHUNK is followed by strn.
DataTools.writeString(raFile, "strf"); // Write the stream format chunk
// write the strf CHUNK size
DataTools.writeInt(raFile, (bytesPerPixel == 1) ? 1068 : 44, true);
// Applications should use this size to determine which BITMAPINFO
// header structure is being used. This size includes this biSize field.
// biSize- Write header size of BITMAPINFO header structure
DataTools.writeInt(raFile, 40, true);
// biWidth - image width in pixels
DataTools.writeInt(raFile, xDim, true);
// biHeight - image height in pixels. If height is positive, the bitmap
// is a bottom up DIB and its origin is in the lower left corner. If
// height is negative, the bitmap is a top-down DIB and its origin is
// the upper left corner. This negative sign feature is supported by the
// Windows Media Player, but it is not supported by PowerPoint.
DataTools.writeInt(raFile, yDim, true);
// biPlanes - number of color planes in which the data is stored
// This must be set to 1.
DataTools.writeShort(raFile, 1, true);
int bitsPerPixel = (bytesPerPixel == 3) ? 24 : 8;
// biBitCount - number of bits per pixel #
// 0L for BI_RGB, uncompressed data as bitmap
DataTools.writeShort(raFile, (short) bitsPerPixel, true);
//writeInt(bytesPerPixel * xDim * yDim * zDim * tDim); // biSizeImage #
DataTools.writeInt(raFile, 0, true); // biSizeImage #
DataTools.writeInt(raFile, 0, true); // biCompression - compression type
// biXPelsPerMeter - horizontal resolution in pixels
DataTools.writeInt(raFile, 0, true);
// biYPelsPerMeter - vertical resolution in pixels per meter
DataTools.writeInt(raFile, 0, true);
if (bitsPerPixel == 8) DataTools.writeInt(raFile, 256, true);
else DataTools.writeInt(raFile, 0, true); // biClrUsed
// biClrImportant - specifies that the first x colors of the color table
// are important to the DIB. If the rest of the colors are not
// available, the image still retains its meaning in an acceptable
// manner. When this field is set to zero, all the colors are important,
// or, rather, their relative importance has not been computed.
DataTools.writeInt(raFile, 0, true);
// Write the LUTa.getExtents()[1] color table entries here. They are
// written: blue byte, green byte, red byte, 0 byte
if (bytesPerPixel == 1) {
byte[] lutWrite = new byte[4 * 256];
for (int i=0; i<256; i++) {
lutWrite[4*i] = (byte) i; // blue
lutWrite[4*i+1] = (byte) i; // green
lutWrite[4*i+2] = (byte) i; // red
lutWrite[4*i+3] = 0;
}
raFile.write(lutWrite);
}
raFile.seek(savestrfSize);
DataTools.writeInt(raFile,
(int) (savestrnPos - (savestrfSize + 4)), true);
raFile.seek(savestrnPos);
// Use strn to provide zero terminated text string describing the stream
DataTools.writeString(raFile, "strn");
DataTools.writeInt(raFile, 16, true); // Write length of strn sub-CHUNK
text = new byte[16];
text[0] = 70; // F
text[1] = 105; // i
text[2] = 108; // l
text[3] = 101; // e
text[4] = 65; // A
text[5] = 86; // V
text[6] = 73; // I
text[7] = 32; // space
text[8] = 119; // w
text[9] = 114; // r
text[10] = 105; // i
text[11] = 116; // t
text[12] = 101; // e
text[13] = 32; // space
text[14] = 32; // space
text[15] = 0; // termination byte
raFile.write(text);
raFile.seek(saveLIST1Size);
DataTools.writeInt(raFile,
(int) (saveJUNKsignature - (saveLIST1Size + 4)), true);
raFile.seek(saveLIST1subSize);
DataTools.writeInt(raFile,
(int) (saveJUNKsignature - (saveLIST1subSize + 4)), true);
raFile.seek(saveJUNKsignature);
// write a JUNK CHUNK for padding
DataTools.writeString(raFile, "JUNK");
paddingBytes = (int) (4084 - (saveJUNKsignature + 8));
DataTools.writeInt(raFile, paddingBytes, true);
for (int i=0; i<paddingBytes/2; i++) {
DataTools.writeShort(raFile, (short) 0, true);
}
// Write the second LIST chunk, which contains the actual data
DataTools.writeString(raFile, "LIST");
// Write the length of the LIST CHUNK not including the first 8 bytes
// with LIST and size. The end of the second LIST CHUNK is followed by
// idx1.
saveLIST2Size = raFile.getFilePointer();
DataTools.writeInt(raFile, 0, true); // For now write 0
DataTools.writeString(raFile, "movi"); // Write CHUNK type 'movi'
}
}
// Write the data. Each 3-byte triplet in the bitmap array represents the
// relative intensities of blue, green, and red, respectively, for a pixel.
// The color bytes are in reverse order from the Windows convention.
int width = xDim - xPad;
int height = byteData[0].length / width;
raFile.write(dataSignature);
savedbLength.add(new Long(raFile.getFilePointer()));
// Write the data length
DataTools.writeInt(raFile, bytesPerPixel * xDim * yDim, true);
if (bytesPerPixel == 1) {
for (int i=(height-1); i>=0; i--) {
raFile.write(byteData[0], i*width, width);
for (int j=0; j<xPad; j++) raFile.write(0);
}
}
else {
byte[] buf = new byte[bytesPerPixel * xDim * yDim];
int offset = 0;
int next = 0;
for (int i=(height-1); i>=0; i--) {
for (int j=0; j<width; j++) {
offset = i*width + j;
for (int k=(byteData.length - 1); k>=0; k--) {
buf[next] = byteData[k][offset];
next++;
}
}
next += xPad * byteData.length;
}
raFile.write(buf);
buf = null;
}
planesWritten++;
if (last) {
// Write the idx1 CHUNK
// Write the 'idx1' signature
idx1Pos = raFile.getFilePointer();
raFile.seek(saveLIST2Size);
DataTools.writeInt(raFile, (int) (idx1Pos - (saveLIST2Size + 4)), true);
raFile.seek(idx1Pos);
DataTools.writeString(raFile, "idx1");
saveidx1Length = raFile.getFilePointer();
// Write the length of the idx1 CHUNK not including the idx1 signature
DataTools.writeInt(raFile, 4 + (planesWritten*16), true);
for (z=0; z<planesWritten; z++) {
// In the ckid field write the 4 character code to identify the chunk
// 00db or 00dc
raFile.write(dataSignature);
// Write the flags - select AVIIF_KEYFRAME
if (z == 0) DataTools.writeInt(raFile, 0x10, true);
else DataTools.writeInt(raFile, 0x00, true);
// AVIIF_KEYFRAME 0x00000010L
// The flag indicates key frames in the video sequence.
// Key frames do not need previous video information to be
// decompressed.
// AVIIF_NOTIME 0x00000100L The CHUNK does not influence video timing
// (for example a palette change CHUNK).
// AVIIF_LIST 0x00000001L Marks a LIST CHUNK.
// AVIIF_TWOCC 2L
// AVIIF_COMPUSE 0x0FFF0000L These bits are for compressor use.
DataTools.writeInt(raFile, (int) (((Long)
savedbLength.get(z)).longValue() - 4 - savemovi), true);
// Write the offset (relative to the 'movi' field) to the relevant
// CHUNK. Write the length of the relevant CHUNK. Note that this length
// is also written at savedbLength
DataTools.writeInt(raFile, bytesPerPixel*xDim*yDim, true);
}
endPos = raFile.getFilePointer();
raFile.seek(saveFileSize);
DataTools.writeInt(raFile, (int) (endPos - (saveFileSize + 4)), true);
raFile.seek(saveidx1Length);
DataTools.writeInt(raFile, (int) (endPos - (saveidx1Length + 4)), true);
// write the total number of planes
raFile.seek(frameOffset);
DataTools.writeInt(raFile, planesWritten, true);
raFile.seek(frameOffset2);
DataTools.writeInt(raFile, planesWritten, true);
raFile.close();
}
}
/* @see loci.formats.IFormatWriter#close() */
public void close() throws FormatException, IOException {
if (raFile != null) raFile.close();
raFile = null;
currentId = null;
}
/** Reports whether the writer can save multiple images to a single file. */
public boolean canDoStacks(String id) { return true; }
/* @see loci.formats.IFormatWriter#getPixelTypes(String) */
public int[] getPixelTypes(String id) throws FormatException, IOException {
return new int[] {FormatTools.UINT8};
}
// -- Main method --
public static void main(String[] args) throws IOException, FormatException {
new AVIWriter().testConvert(args);
}
}
| true | true | public void save(String id, Image image, boolean last)
throws FormatException, IOException
{
if (image == null) {
throw new FormatException("Image is null");
}
BufferedImage img = null;
if (cm != null) img = ImageTools.makeBuffered(image, cm);
else img = ImageTools.makeBuffered(image);
byte[][] byteData = ImageTools.getBytes(img);
if (!id.equals(currentId)) {
planesWritten = 0;
currentId = id;
bytesPerPixel = byteData.length;
file = new File(id);
raFile = new RandomAccessFile(file, "rw");
raFile.seek(raFile.length());
saveFileSize = 4;
saveLIST1Size = 16;
saveLIST1subSize = 23 * 4;
frameOffset = 48;
frameOffset2 = 35 * 4;
savestrfSize = 42 * 4;
savestrnPos = savestrfSize + 44 + (bytesPerPixel == 1 ? 4 * 256 : 0);
saveJUNKsignature = savestrnPos + 16;
saveLIST2Size = 4088;
savemovi = 4092;
savedbLength = new Vector();
dataSignature = new byte[4];
dataSignature[0] = 48; // 0
dataSignature[1] = 48; // 0
dataSignature[2] = 100; // d
dataSignature[3] = 98; // b
tDim = 1;
zDim = 1;
yDim = img.getHeight();
xDim = img.getWidth();
xPad = 0;
xMod = xDim % 4;
if (xMod != 0) {
xPad = 4 - xMod;
xDim += xPad;
}
if (raFile.length() == 0) {
DataTools.writeString(raFile, "RIFF"); // signature
// Bytes 4 thru 7 contain the length of the file. This length does
// not include bytes 0 thru 7.
DataTools.writeInt(raFile, 0, true); // for now write 0 for size
DataTools.writeString(raFile, "AVI "); // RIFF type
// Write the first LIST chunk, which contains
// information on data decoding
DataTools.writeString(raFile, "LIST"); // CHUNK signature
// Write the length of the LIST CHUNK not including the first 8 bytes
// with LIST and size. Note that the end of the LIST CHUNK is followed
// by JUNK.
DataTools.writeInt(raFile, (bytesPerPixel == 1) ? 1240 : 216, true);
DataTools.writeString(raFile, "hdrl"); // CHUNK type
DataTools.writeString(raFile, "avih"); // Write the avih sub-CHUNK
// Write the length of the avih sub-CHUNK (38H) not including the
// the first 8 bytes for avihSignature and the length
DataTools.writeInt(raFile, 0x38, true);
// dwMicroSecPerFrame - Write the microseconds per frame
microSecPerFrame = (int) (1.0 / fps * 1.0e6);
DataTools.writeInt(raFile, microSecPerFrame, true);
// Write the maximum data rate of the file in bytes per second
DataTools.writeInt(raFile, 0, true); // dwMaxBytesPerSec
DataTools.writeInt(raFile, 0, true); // dwReserved1 - set to 0
// dwFlags - just set the bit for AVIF_HASINDEX
savePlaneNum = (int) raFile.getFilePointer();
DataTools.writeInt(raFile, 0x10, true);
// 10H AVIF_HASINDEX: The AVI file has an idx1 chunk containing
// an index at the end of the file. For good performance, all
// AVI files should contain an index.
// 20H AVIF_MUSTUSEINDEX: Index CHUNK, rather than the physical
// ordering of the chunks in the file, must be used to determine the
// order of the frames.
// 100H AVIF_ISINTERLEAVED: Indicates that the AVI file is interleaved.
// This is used to read data from a CD-ROM more efficiently.
// 800H AVIF_TRUSTCKTYPE: USE CKType to find key frames
// 10000H AVIF_WASCAPTUREFILE: The AVI file is used for capturing
// real-time video. Applications should warn the user before
// writing over a file with this fla set because the user
// probably defragmented this file.
// 20000H AVIF_COPYRIGHTED: The AVI file contains copyrighted data
// and software. When, this flag is used, software should not
// permit the data to be duplicated.
// dwTotalFrames - total frame number
DataTools.writeInt(raFile, zDim * tDim, true);
// dwInitialFrames -Initial frame for interleaved files.
// Noninterleaved files should specify 0.
DataTools.writeInt(raFile, 0, true);
// dwStreams - number of streams in the file - here 1 video and
// zero audio.
DataTools.writeInt(raFile, 1, true);
// dwSuggestedBufferSize - Suggested buffer size for reading the file.
// Generally, this size should be large enough to contain the largest
// chunk in the file.
DataTools.writeInt(raFile, 0, true);
// dwWidth - image width in pixels
DataTools.writeInt(raFile, xDim - xPad, true);
DataTools.writeInt(raFile, yDim, true); // dwHeight - height in pixels
// dwReserved[4] - Microsoft says to set the following 4 values to 0.
DataTools.writeInt(raFile, 0, true);
DataTools.writeInt(raFile, 0, true);
DataTools.writeInt(raFile, 0, true);
DataTools.writeInt(raFile, 0, true);
// Write the Stream line header CHUNK
DataTools.writeString(raFile, "LIST");
// Write the size of the first LIST subCHUNK not including the first 8
// bytes with LIST and size. Note that saveLIST1subSize = saveLIST1Size
// + 76, and that the length written to saveLIST1subSize is 76 less than
// the length written to saveLIST1Size. The end of the first LIST
// subCHUNK is followed by JUNK.
DataTools.writeInt(raFile, (bytesPerPixel == 1) ? 1164 : 140 , true);
DataTools.writeString(raFile, "strl"); // Write the chunk type
DataTools.writeString(raFile, "strh"); // Write the strh sub-CHUNK
DataTools.writeInt(raFile, 56, true); // Write length of strh sub-CHUNK
// fccType - Write the type of data stream - here vids for video stream
DataTools.writeString(raFile, "vids");
// Write DIB for Microsoft Device Independent Bitmap.
// Note: Unfortunately, at least 3 other four character codes are
// sometimes used for uncompressed AVI videos: 'RGB ', 'RAW ',
// 0x00000000
DataTools.writeString(raFile, "DIB ");
DataTools.writeInt(raFile, 0, true); // dwFlags
// 0x00000001 AVISF_DISABLED The stram data should be rendered only when
// explicitly enabled.
// 0x00010000 AVISF_VIDEO_PALCHANGES Indicates that a palette change is
// included in the AVI file. This flag warns the playback software that
// it will need to animate the palette.
// dwPriority - priority of a stream type. For example, in a file with
// multiple audio streams, the one with the highest priority might be
// the default one.
DataTools.writeInt(raFile, 0, true);
// dwInitialFrames - Specifies how far audio data is skewed ahead of
// video frames in interleaved files. Typically, this is about 0.75
// seconds. In interleaved files specify the number of frames in the
// file prior to the initial frame of the AVI sequence.
// Noninterleaved files should use zero.
DataTools.writeInt(raFile, 0, true);
// rate/scale = samples/second
DataTools.writeInt(raFile, 1, true); // dwScale
// dwRate - frame rate for video streams
DataTools.writeInt(raFile, fps, true);
// dwStart - this field is usually set to zero
DataTools.writeInt(raFile, 0, true);
// dwLength - playing time of AVI file as defined by scale and rate
// Set equal to the number of frames
DataTools.writeInt(raFile, tDim * zDim, true);
// dwSuggestedBufferSize - Suggested buffer size for reading the stream.
// Typically, this contains a value corresponding to the largest chunk
// in a stream.
DataTools.writeInt(raFile, 0, true);
// dwQuality - encoding quality given by an integer between 0 and
// 10,000. If set to -1, drivers use the default quality value.
DataTools.writeInt(raFile, -1, true);
// dwSampleSize #
// 0 if the video frames may or may not vary in size
// If 0, each sample of data(such as a video frame) must be in a
// separate chunk. If nonzero, then multiple samples of data can be
// grouped into a single chunk within the file.
DataTools.writeInt(raFile, 0, true);
// rcFrame - Specifies the destination rectangle for a text or video
// stream within the movie rectangle specified by the dwWidth and
// dwHeight members of the AVI main header structure. The rcFrame member
// is typically used in support of multiple video streams. Set this
// rectangle to the coordinates corresponding to the movie rectangle to
// update the whole movie rectangle. Units for this member are pixels.
// The upper-left corner of the destination rectangle is relative to the
// upper-left corner of the movie rectangle.
DataTools.writeShort(raFile, (short) 0, true); // left
DataTools.writeShort(raFile, (short) 0, true); // top
DataTools.writeShort(raFile, (short) 0, true); // right
DataTools.writeShort(raFile, (short) 0, true); // bottom
// Write the size of the stream format CHUNK not including the first 8
// bytes for strf and the size. Note that the end of the stream format
// CHUNK is followed by strn.
DataTools.writeString(raFile, "strf"); // Write the stream format chunk
// write the strf CHUNK size
DataTools.writeInt(raFile, (bytesPerPixel == 1) ? 1068 : 44, true);
// Applications should use this size to determine which BITMAPINFO
// header structure is being used. This size includes this biSize field.
// biSize- Write header size of BITMAPINFO header structure
DataTools.writeInt(raFile, 40, true);
// biWidth - image width in pixels
DataTools.writeInt(raFile, xDim, true);
// biHeight - image height in pixels. If height is positive, the bitmap
// is a bottom up DIB and its origin is in the lower left corner. If
// height is negative, the bitmap is a top-down DIB and its origin is
// the upper left corner. This negative sign feature is supported by the
// Windows Media Player, but it is not supported by PowerPoint.
DataTools.writeInt(raFile, yDim, true);
// biPlanes - number of color planes in which the data is stored
// This must be set to 1.
DataTools.writeShort(raFile, 1, true);
int bitsPerPixel = (bytesPerPixel == 3) ? 24 : 8;
// biBitCount - number of bits per pixel #
// 0L for BI_RGB, uncompressed data as bitmap
DataTools.writeShort(raFile, (short) bitsPerPixel, true);
//writeInt(bytesPerPixel * xDim * yDim * zDim * tDim); // biSizeImage #
DataTools.writeInt(raFile, 0, true); // biSizeImage #
DataTools.writeInt(raFile, 0, true); // biCompression - compression type
// biXPelsPerMeter - horizontal resolution in pixels
DataTools.writeInt(raFile, 0, true);
// biYPelsPerMeter - vertical resolution in pixels per meter
DataTools.writeInt(raFile, 0, true);
if (bitsPerPixel == 8) DataTools.writeInt(raFile, 256, true);
else DataTools.writeInt(raFile, 0, true); // biClrUsed
// biClrImportant - specifies that the first x colors of the color table
// are important to the DIB. If the rest of the colors are not
// available, the image still retains its meaning in an acceptable
// manner. When this field is set to zero, all the colors are important,
// or, rather, their relative importance has not been computed.
DataTools.writeInt(raFile, 0, true);
// Write the LUTa.getExtents()[1] color table entries here. They are
// written: blue byte, green byte, red byte, 0 byte
if (bytesPerPixel == 1) {
byte[] lutWrite = new byte[4 * 256];
for (int i=0; i<256; i++) {
lutWrite[4*i] = (byte) i; // blue
lutWrite[4*i+1] = (byte) i; // green
lutWrite[4*i+2] = (byte) i; // red
lutWrite[4*i+3] = 0;
}
raFile.write(lutWrite);
}
raFile.seek(savestrfSize);
DataTools.writeInt(raFile,
(int) (savestrnPos - (savestrfSize + 4)), true);
raFile.seek(savestrnPos);
// Use strn to provide zero terminated text string describing the stream
DataTools.writeString(raFile, "strn");
DataTools.writeInt(raFile, 16, true); // Write length of strn sub-CHUNK
text = new byte[16];
text[0] = 70; // F
text[1] = 105; // i
text[2] = 108; // l
text[3] = 101; // e
text[4] = 65; // A
text[5] = 86; // V
text[6] = 73; // I
text[7] = 32; // space
text[8] = 119; // w
text[9] = 114; // r
text[10] = 105; // i
text[11] = 116; // t
text[12] = 101; // e
text[13] = 32; // space
text[14] = 32; // space
text[15] = 0; // termination byte
raFile.write(text);
raFile.seek(saveLIST1Size);
DataTools.writeInt(raFile,
(int) (saveJUNKsignature - (saveLIST1Size + 4)), true);
raFile.seek(saveLIST1subSize);
DataTools.writeInt(raFile,
(int) (saveJUNKsignature - (saveLIST1subSize + 4)), true);
raFile.seek(saveJUNKsignature);
// write a JUNK CHUNK for padding
DataTools.writeString(raFile, "JUNK");
paddingBytes = (int) (4084 - (saveJUNKsignature + 8));
DataTools.writeInt(raFile, paddingBytes, true);
for (int i=0; i<paddingBytes/2; i++) {
DataTools.writeShort(raFile, (short) 0, true);
}
// Write the second LIST chunk, which contains the actual data
DataTools.writeString(raFile, "LIST");
// Write the length of the LIST CHUNK not including the first 8 bytes
// with LIST and size. The end of the second LIST CHUNK is followed by
// idx1.
saveLIST2Size = raFile.getFilePointer();
DataTools.writeInt(raFile, 0, true); // For now write 0
DataTools.writeString(raFile, "movi"); // Write CHUNK type 'movi'
}
}
// Write the data. Each 3-byte triplet in the bitmap array represents the
// relative intensities of blue, green, and red, respectively, for a pixel.
// The color bytes are in reverse order from the Windows convention.
int width = xDim - xPad;
int height = byteData[0].length / width;
raFile.write(dataSignature);
savedbLength.add(new Long(raFile.getFilePointer()));
// Write the data length
DataTools.writeInt(raFile, bytesPerPixel * xDim * yDim, true);
if (bytesPerPixel == 1) {
for (int i=(height-1); i>=0; i--) {
raFile.write(byteData[0], i*width, width);
for (int j=0; j<xPad; j++) raFile.write(0);
}
}
else {
byte[] buf = new byte[bytesPerPixel * xDim * yDim];
int offset = 0;
int next = 0;
for (int i=(height-1); i>=0; i--) {
for (int j=0; j<width; j++) {
offset = i*width + j;
for (int k=(byteData.length - 1); k>=0; k--) {
buf[next] = byteData[k][offset];
next++;
}
}
next += xPad * byteData.length;
}
raFile.write(buf);
buf = null;
}
planesWritten++;
if (last) {
// Write the idx1 CHUNK
// Write the 'idx1' signature
idx1Pos = raFile.getFilePointer();
raFile.seek(saveLIST2Size);
DataTools.writeInt(raFile, (int) (idx1Pos - (saveLIST2Size + 4)), true);
raFile.seek(idx1Pos);
DataTools.writeString(raFile, "idx1");
saveidx1Length = raFile.getFilePointer();
// Write the length of the idx1 CHUNK not including the idx1 signature
DataTools.writeInt(raFile, 4 + (planesWritten*16), true);
for (z=0; z<planesWritten; z++) {
// In the ckid field write the 4 character code to identify the chunk
// 00db or 00dc
raFile.write(dataSignature);
// Write the flags - select AVIIF_KEYFRAME
if (z == 0) DataTools.writeInt(raFile, 0x10, true);
else DataTools.writeInt(raFile, 0x00, true);
// AVIIF_KEYFRAME 0x00000010L
// The flag indicates key frames in the video sequence.
// Key frames do not need previous video information to be
// decompressed.
// AVIIF_NOTIME 0x00000100L The CHUNK does not influence video timing
// (for example a palette change CHUNK).
// AVIIF_LIST 0x00000001L Marks a LIST CHUNK.
// AVIIF_TWOCC 2L
// AVIIF_COMPUSE 0x0FFF0000L These bits are for compressor use.
DataTools.writeInt(raFile, (int) (((Long)
savedbLength.get(z)).longValue() - 4 - savemovi), true);
// Write the offset (relative to the 'movi' field) to the relevant
// CHUNK. Write the length of the relevant CHUNK. Note that this length
// is also written at savedbLength
DataTools.writeInt(raFile, bytesPerPixel*xDim*yDim, true);
}
endPos = raFile.getFilePointer();
raFile.seek(saveFileSize);
DataTools.writeInt(raFile, (int) (endPos - (saveFileSize + 4)), true);
raFile.seek(saveidx1Length);
DataTools.writeInt(raFile, (int) (endPos - (saveidx1Length + 4)), true);
// write the total number of planes
raFile.seek(frameOffset);
DataTools.writeInt(raFile, planesWritten, true);
raFile.seek(frameOffset2);
DataTools.writeInt(raFile, planesWritten, true);
raFile.close();
}
}
| public void save(String id, Image image, boolean last)
throws FormatException, IOException
{
if (image == null) {
throw new FormatException("Image is null");
}
BufferedImage img = null;
if (cm != null) img = ImageTools.makeBuffered(image, cm);
else img = ImageTools.makeBuffered(image);
byte[][] byteData = ImageTools.getBytes(img);
if (!id.equals(currentId)) {
planesWritten = 0;
currentId = id;
bytesPerPixel = byteData.length;
file = new File(id);
raFile = new RandomAccessFile(file, "rw");
raFile.seek(raFile.length());
saveFileSize = 4;
saveLIST1Size = 16;
saveLIST1subSize = 23 * 4;
frameOffset = 48;
frameOffset2 = 35 * 4;
savestrfSize = 42 * 4;
savestrnPos = savestrfSize + 44 + (bytesPerPixel == 1 ? 4 * 256 : 0);
saveJUNKsignature = savestrnPos + 24;
saveLIST2Size = 4088;
savemovi = 4092;
savedbLength = new Vector();
dataSignature = new byte[4];
dataSignature[0] = 48; // 0
dataSignature[1] = 48; // 0
dataSignature[2] = 100; // d
dataSignature[3] = 98; // b
tDim = 1;
zDim = 1;
yDim = img.getHeight();
xDim = img.getWidth();
xPad = 0;
xMod = xDim % 4;
if (xMod != 0) {
xPad = 4 - xMod;
xDim += xPad;
}
if (raFile.length() == 0) {
DataTools.writeString(raFile, "RIFF"); // signature
// Bytes 4 thru 7 contain the length of the file. This length does
// not include bytes 0 thru 7.
DataTools.writeInt(raFile, 0, true); // for now write 0 for size
DataTools.writeString(raFile, "AVI "); // RIFF type
// Write the first LIST chunk, which contains
// information on data decoding
DataTools.writeString(raFile, "LIST"); // CHUNK signature
// Write the length of the LIST CHUNK not including the first 8 bytes
// with LIST and size. Note that the end of the LIST CHUNK is followed
// by JUNK.
DataTools.writeInt(raFile, (bytesPerPixel == 1) ? 1240 : 216, true);
DataTools.writeString(raFile, "hdrl"); // CHUNK type
DataTools.writeString(raFile, "avih"); // Write the avih sub-CHUNK
// Write the length of the avih sub-CHUNK (38H) not including the
// the first 8 bytes for avihSignature and the length
DataTools.writeInt(raFile, 0x38, true);
// dwMicroSecPerFrame - Write the microseconds per frame
microSecPerFrame = (int) (1.0 / fps * 1.0e6);
DataTools.writeInt(raFile, microSecPerFrame, true);
// Write the maximum data rate of the file in bytes per second
DataTools.writeInt(raFile, 0, true); // dwMaxBytesPerSec
DataTools.writeInt(raFile, 0, true); // dwReserved1 - set to 0
// dwFlags - just set the bit for AVIF_HASINDEX
savePlaneNum = (int) raFile.getFilePointer();
DataTools.writeInt(raFile, 0x10, true);
// 10H AVIF_HASINDEX: The AVI file has an idx1 chunk containing
// an index at the end of the file. For good performance, all
// AVI files should contain an index.
// 20H AVIF_MUSTUSEINDEX: Index CHUNK, rather than the physical
// ordering of the chunks in the file, must be used to determine the
// order of the frames.
// 100H AVIF_ISINTERLEAVED: Indicates that the AVI file is interleaved.
// This is used to read data from a CD-ROM more efficiently.
// 800H AVIF_TRUSTCKTYPE: USE CKType to find key frames
// 10000H AVIF_WASCAPTUREFILE: The AVI file is used for capturing
// real-time video. Applications should warn the user before
// writing over a file with this fla set because the user
// probably defragmented this file.
// 20000H AVIF_COPYRIGHTED: The AVI file contains copyrighted data
// and software. When, this flag is used, software should not
// permit the data to be duplicated.
// dwTotalFrames - total frame number
DataTools.writeInt(raFile, zDim * tDim, true);
// dwInitialFrames -Initial frame for interleaved files.
// Noninterleaved files should specify 0.
DataTools.writeInt(raFile, 0, true);
// dwStreams - number of streams in the file - here 1 video and
// zero audio.
DataTools.writeInt(raFile, 1, true);
// dwSuggestedBufferSize - Suggested buffer size for reading the file.
// Generally, this size should be large enough to contain the largest
// chunk in the file.
DataTools.writeInt(raFile, 0, true);
// dwWidth - image width in pixels
DataTools.writeInt(raFile, xDim - xPad, true);
DataTools.writeInt(raFile, yDim, true); // dwHeight - height in pixels
// dwReserved[4] - Microsoft says to set the following 4 values to 0.
DataTools.writeInt(raFile, 0, true);
DataTools.writeInt(raFile, 0, true);
DataTools.writeInt(raFile, 0, true);
DataTools.writeInt(raFile, 0, true);
// Write the Stream line header CHUNK
DataTools.writeString(raFile, "LIST");
// Write the size of the first LIST subCHUNK not including the first 8
// bytes with LIST and size. Note that saveLIST1subSize = saveLIST1Size
// + 76, and that the length written to saveLIST1subSize is 76 less than
// the length written to saveLIST1Size. The end of the first LIST
// subCHUNK is followed by JUNK.
DataTools.writeInt(raFile, (bytesPerPixel == 1) ? 1164 : 140 , true);
DataTools.writeString(raFile, "strl"); // Write the chunk type
DataTools.writeString(raFile, "strh"); // Write the strh sub-CHUNK
DataTools.writeInt(raFile, 56, true); // Write length of strh sub-CHUNK
// fccType - Write the type of data stream - here vids for video stream
DataTools.writeString(raFile, "vids");
// Write DIB for Microsoft Device Independent Bitmap.
// Note: Unfortunately, at least 3 other four character codes are
// sometimes used for uncompressed AVI videos: 'RGB ', 'RAW ',
// 0x00000000
DataTools.writeString(raFile, "DIB ");
DataTools.writeInt(raFile, 0, true); // dwFlags
// 0x00000001 AVISF_DISABLED The stram data should be rendered only when
// explicitly enabled.
// 0x00010000 AVISF_VIDEO_PALCHANGES Indicates that a palette change is
// included in the AVI file. This flag warns the playback software that
// it will need to animate the palette.
// dwPriority - priority of a stream type. For example, in a file with
// multiple audio streams, the one with the highest priority might be
// the default one.
DataTools.writeInt(raFile, 0, true);
// dwInitialFrames - Specifies how far audio data is skewed ahead of
// video frames in interleaved files. Typically, this is about 0.75
// seconds. In interleaved files specify the number of frames in the
// file prior to the initial frame of the AVI sequence.
// Noninterleaved files should use zero.
DataTools.writeInt(raFile, 0, true);
// rate/scale = samples/second
DataTools.writeInt(raFile, 1, true); // dwScale
// dwRate - frame rate for video streams
DataTools.writeInt(raFile, fps, true);
// dwStart - this field is usually set to zero
DataTools.writeInt(raFile, 0, true);
// dwLength - playing time of AVI file as defined by scale and rate
// Set equal to the number of frames
DataTools.writeInt(raFile, tDim * zDim, true);
// dwSuggestedBufferSize - Suggested buffer size for reading the stream.
// Typically, this contains a value corresponding to the largest chunk
// in a stream.
DataTools.writeInt(raFile, 0, true);
// dwQuality - encoding quality given by an integer between 0 and
// 10,000. If set to -1, drivers use the default quality value.
DataTools.writeInt(raFile, -1, true);
// dwSampleSize #
// 0 if the video frames may or may not vary in size
// If 0, each sample of data(such as a video frame) must be in a
// separate chunk. If nonzero, then multiple samples of data can be
// grouped into a single chunk within the file.
DataTools.writeInt(raFile, 0, true);
// rcFrame - Specifies the destination rectangle for a text or video
// stream within the movie rectangle specified by the dwWidth and
// dwHeight members of the AVI main header structure. The rcFrame member
// is typically used in support of multiple video streams. Set this
// rectangle to the coordinates corresponding to the movie rectangle to
// update the whole movie rectangle. Units for this member are pixels.
// The upper-left corner of the destination rectangle is relative to the
// upper-left corner of the movie rectangle.
DataTools.writeShort(raFile, (short) 0, true); // left
DataTools.writeShort(raFile, (short) 0, true); // top
DataTools.writeShort(raFile, (short) 0, true); // right
DataTools.writeShort(raFile, (short) 0, true); // bottom
// Write the size of the stream format CHUNK not including the first 8
// bytes for strf and the size. Note that the end of the stream format
// CHUNK is followed by strn.
DataTools.writeString(raFile, "strf"); // Write the stream format chunk
// write the strf CHUNK size
DataTools.writeInt(raFile, (bytesPerPixel == 1) ? 1068 : 44, true);
// Applications should use this size to determine which BITMAPINFO
// header structure is being used. This size includes this biSize field.
// biSize- Write header size of BITMAPINFO header structure
DataTools.writeInt(raFile, 40, true);
// biWidth - image width in pixels
DataTools.writeInt(raFile, xDim, true);
// biHeight - image height in pixels. If height is positive, the bitmap
// is a bottom up DIB and its origin is in the lower left corner. If
// height is negative, the bitmap is a top-down DIB and its origin is
// the upper left corner. This negative sign feature is supported by the
// Windows Media Player, but it is not supported by PowerPoint.
DataTools.writeInt(raFile, yDim, true);
// biPlanes - number of color planes in which the data is stored
// This must be set to 1.
DataTools.writeShort(raFile, 1, true);
int bitsPerPixel = (bytesPerPixel == 3) ? 24 : 8;
// biBitCount - number of bits per pixel #
// 0L for BI_RGB, uncompressed data as bitmap
DataTools.writeShort(raFile, (short) bitsPerPixel, true);
//writeInt(bytesPerPixel * xDim * yDim * zDim * tDim); // biSizeImage #
DataTools.writeInt(raFile, 0, true); // biSizeImage #
DataTools.writeInt(raFile, 0, true); // biCompression - compression type
// biXPelsPerMeter - horizontal resolution in pixels
DataTools.writeInt(raFile, 0, true);
// biYPelsPerMeter - vertical resolution in pixels per meter
DataTools.writeInt(raFile, 0, true);
if (bitsPerPixel == 8) DataTools.writeInt(raFile, 256, true);
else DataTools.writeInt(raFile, 0, true); // biClrUsed
// biClrImportant - specifies that the first x colors of the color table
// are important to the DIB. If the rest of the colors are not
// available, the image still retains its meaning in an acceptable
// manner. When this field is set to zero, all the colors are important,
// or, rather, their relative importance has not been computed.
DataTools.writeInt(raFile, 0, true);
// Write the LUTa.getExtents()[1] color table entries here. They are
// written: blue byte, green byte, red byte, 0 byte
if (bytesPerPixel == 1) {
byte[] lutWrite = new byte[4 * 256];
for (int i=0; i<256; i++) {
lutWrite[4*i] = (byte) i; // blue
lutWrite[4*i+1] = (byte) i; // green
lutWrite[4*i+2] = (byte) i; // red
lutWrite[4*i+3] = 0;
}
raFile.write(lutWrite);
}
raFile.seek(savestrfSize);
DataTools.writeInt(raFile,
(int) (savestrnPos - (savestrfSize + 4)), true);
raFile.seek(savestrnPos);
// Use strn to provide zero terminated text string describing the stream
DataTools.writeString(raFile, "strn");
DataTools.writeInt(raFile, 16, true); // Write length of strn sub-CHUNK
text = new byte[16];
text[0] = 70; // F
text[1] = 105; // i
text[2] = 108; // l
text[3] = 101; // e
text[4] = 65; // A
text[5] = 86; // V
text[6] = 73; // I
text[7] = 32; // space
text[8] = 119; // w
text[9] = 114; // r
text[10] = 105; // i
text[11] = 116; // t
text[12] = 101; // e
text[13] = 32; // space
text[14] = 32; // space
text[15] = 0; // termination byte
raFile.write(text);
raFile.seek(saveLIST1Size);
DataTools.writeInt(raFile,
(int) (saveJUNKsignature - (saveLIST1Size + 4)), true);
raFile.seek(saveLIST1subSize);
DataTools.writeInt(raFile,
(int) (saveJUNKsignature - (saveLIST1subSize + 4)), true);
raFile.seek(saveJUNKsignature);
// write a JUNK CHUNK for padding
DataTools.writeString(raFile, "JUNK");
paddingBytes = (int) (4084 - (saveJUNKsignature + 8));
DataTools.writeInt(raFile, paddingBytes, true);
for (int i=0; i<paddingBytes/2; i++) {
DataTools.writeShort(raFile, (short) 0, true);
}
// Write the second LIST chunk, which contains the actual data
DataTools.writeString(raFile, "LIST");
// Write the length of the LIST CHUNK not including the first 8 bytes
// with LIST and size. The end of the second LIST CHUNK is followed by
// idx1.
saveLIST2Size = raFile.getFilePointer();
DataTools.writeInt(raFile, 0, true); // For now write 0
DataTools.writeString(raFile, "movi"); // Write CHUNK type 'movi'
}
}
// Write the data. Each 3-byte triplet in the bitmap array represents the
// relative intensities of blue, green, and red, respectively, for a pixel.
// The color bytes are in reverse order from the Windows convention.
int width = xDim - xPad;
int height = byteData[0].length / width;
raFile.write(dataSignature);
savedbLength.add(new Long(raFile.getFilePointer()));
// Write the data length
DataTools.writeInt(raFile, bytesPerPixel * xDim * yDim, true);
if (bytesPerPixel == 1) {
for (int i=(height-1); i>=0; i--) {
raFile.write(byteData[0], i*width, width);
for (int j=0; j<xPad; j++) raFile.write(0);
}
}
else {
byte[] buf = new byte[bytesPerPixel * xDim * yDim];
int offset = 0;
int next = 0;
for (int i=(height-1); i>=0; i--) {
for (int j=0; j<width; j++) {
offset = i*width + j;
for (int k=(byteData.length - 1); k>=0; k--) {
buf[next] = byteData[k][offset];
next++;
}
}
next += xPad * byteData.length;
}
raFile.write(buf);
buf = null;
}
planesWritten++;
if (last) {
// Write the idx1 CHUNK
// Write the 'idx1' signature
idx1Pos = raFile.getFilePointer();
raFile.seek(saveLIST2Size);
DataTools.writeInt(raFile, (int) (idx1Pos - (saveLIST2Size + 4)), true);
raFile.seek(idx1Pos);
DataTools.writeString(raFile, "idx1");
saveidx1Length = raFile.getFilePointer();
// Write the length of the idx1 CHUNK not including the idx1 signature
DataTools.writeInt(raFile, 4 + (planesWritten*16), true);
for (z=0; z<planesWritten; z++) {
// In the ckid field write the 4 character code to identify the chunk
// 00db or 00dc
raFile.write(dataSignature);
// Write the flags - select AVIIF_KEYFRAME
if (z == 0) DataTools.writeInt(raFile, 0x10, true);
else DataTools.writeInt(raFile, 0x00, true);
// AVIIF_KEYFRAME 0x00000010L
// The flag indicates key frames in the video sequence.
// Key frames do not need previous video information to be
// decompressed.
// AVIIF_NOTIME 0x00000100L The CHUNK does not influence video timing
// (for example a palette change CHUNK).
// AVIIF_LIST 0x00000001L Marks a LIST CHUNK.
// AVIIF_TWOCC 2L
// AVIIF_COMPUSE 0x0FFF0000L These bits are for compressor use.
DataTools.writeInt(raFile, (int) (((Long)
savedbLength.get(z)).longValue() - 4 - savemovi), true);
// Write the offset (relative to the 'movi' field) to the relevant
// CHUNK. Write the length of the relevant CHUNK. Note that this length
// is also written at savedbLength
DataTools.writeInt(raFile, bytesPerPixel*xDim*yDim, true);
}
endPos = raFile.getFilePointer();
raFile.seek(saveFileSize);
DataTools.writeInt(raFile, (int) (endPos - (saveFileSize + 4)), true);
raFile.seek(saveidx1Length);
DataTools.writeInt(raFile, (int) (endPos - (saveidx1Length + 4)), true);
// write the total number of planes
raFile.seek(frameOffset);
DataTools.writeInt(raFile, planesWritten, true);
raFile.seek(frameOffset2);
DataTools.writeInt(raFile, planesWritten, true);
raFile.close();
}
}
|
diff --git a/javafx.editor/src/org/netbeans/modules/javafx/editor/hints/MarkOverriddenTaskFactory.java b/javafx.editor/src/org/netbeans/modules/javafx/editor/hints/MarkOverriddenTaskFactory.java
index f915ff7c..7aeed9d5 100644
--- a/javafx.editor/src/org/netbeans/modules/javafx/editor/hints/MarkOverriddenTaskFactory.java
+++ b/javafx.editor/src/org/netbeans/modules/javafx/editor/hints/MarkOverriddenTaskFactory.java
@@ -1,238 +1,241 @@
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2009 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2008 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.modules.javafx.editor.hints;
import com.sun.javafx.api.tree.JavaFXTreePathScanner;
import com.sun.javafx.api.tree.SourcePositions;
import com.sun.javafx.api.tree.Tree;
import com.sun.tools.mjavac.code.Symbol;
import com.sun.tools.mjavac.code.Symbol.ClassSymbol;
import com.sun.tools.mjavac.code.Symbol.MethodSymbol;
import com.sun.tools.mjavac.code.Type;
import org.netbeans.api.javafx.source.CancellableTask;
import org.netbeans.api.javafx.source.support.EditorAwareJavaFXSourceTaskFactory;
import org.netbeans.api.javafx.source.JavaFXSource;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.lang.model.element.Element;
import javax.swing.SwingUtilities;
import javax.swing.text.*;
import javax.tools.Diagnostic;
import org.netbeans.api.javafx.source.CompilationInfo;
import org.openide.filesystems.FileObject;
import org.openide.text.Annotation;
import org.openide.text.NbDocument;
import org.openide.util.NbBundle;
/**
*
* @author karol harezlak
*/
public final class MarkOverriddenTaskFactory extends EditorAwareJavaFXSourceTaskFactory {
private static final String ANNOTATION_TYPE = "org.netbeans.modules.javafx.editor.hints"; //NOI18N
private final Map<Document, Collection<OverriddeAnnotation>> annotations = new WeakHashMap<Document, Collection<OverriddeAnnotation>>();
private final AtomicBoolean cancel = new AtomicBoolean();
public MarkOverriddenTaskFactory() {
super(JavaFXSource.Phase.ANALYZED, JavaFXSource.Priority.LOW);
}
@Override
protected CancellableTask<CompilationInfo> createTask(final FileObject file) {
final Collection<Element> classes = new HashSet<Element>();
final Map<Element, List<MethodSymbol>> overriddenMethods = new HashMap<Element, List<MethodSymbol>>();
final Collection<OverriddeAnnotation> addedAnotations = new HashSet<OverriddeAnnotation>();
return new CancellableTask<CompilationInfo>() {
public void cancel() {
cancel.set(true);
}
@SuppressWarnings("element-type-mismatch") //NOI18N
public void run(final CompilationInfo compilationInfo) throws Exception {
cancel.set(false);
final JavaFXTreePathScanner<Void, Void> visitor = new OverrideVisitor(compilationInfo, classes, overriddenMethods);
visitor.scan(compilationInfo.getCompilationUnit(), null);
SourcePositions sourcePositions = compilationInfo.getTrees().getSourcePositions();
for (Element currentClass : classes) {
if (overriddenMethods.get(currentClass) == null || overriddenMethods.get(currentClass).isEmpty()) {
continue;
}
ClassSymbol classSymbol = (ClassSymbol) currentClass;
for (Element element : overriddenMethods.get(currentClass)) {
if (element instanceof MethodSymbol) {
String fqnString = null;
if (classSymbol.getInterfaces().size() == 1) {
fqnString = classSymbol.getInterfaces().iterator().next().toString();
} else {
for (Type classType : classSymbol.getInterfaces()) {
- fqnString = getOwnerClass(classType.asElement().enclClass(), (MethodSymbol) element);
+ fqnString = getOwnerClassName(classType.asElement().enclClass(), (MethodSymbol) element);
if (fqnString != null) {
break;
}
}
}
if (fqnString != null) {
Tree tree = compilationInfo.getTrees().getTree(element);
int start = (int) sourcePositions.getStartPosition(compilationInfo.getCompilationUnit(), tree);
boolean isInErrorZone = false;
for (Diagnostic diagnostic : compilationInfo.getDiagnostics()) {
if (diagnostic.getStartPosition() <= start && diagnostic.getEndPosition() >= start) {
isInErrorZone = true;
}
}
if (start > 0 && !isInErrorZone) {
addedAnotations.add(new OverriddeAnnotation(start, fqnString));
}
}
}
}
}
updateAnnotationsOverridden(compilationInfo, addedAnotations);
clear();
}
- private String getOwnerClass(ClassSymbol classSymbol, MethodSymbol methodSymbol) {
+ private String getOwnerClassName(ClassSymbol classSymbol, MethodSymbol methodSymbol) {
String fqnType = null;
+ if (classSymbol == null || classSymbol.getEnclosedElements() == null) {
+ return null;
+ }
for (Symbol symbol : classSymbol.getEnclosedElements()) {
if (symbol instanceof MethodSymbol) {
MethodSymbol method = (MethodSymbol) symbol;
if (!method.name.toString().equals(methodSymbol.name.toString())) {
continue;
}
if (method.getReturnType() != methodSymbol.getReturnType()) {
continue;
}
if (method.getParameters().size() != methodSymbol.getParameters().size()) {
continue;
}
return classSymbol.className();
}
}
if (fqnType != null) {
return fqnType;
}
for (Type classType : classSymbol.getInterfaces()) {
- fqnType = getOwnerClass(classType.asElement().enclClass(), methodSymbol);
+ fqnType = getOwnerClassName(classType.asElement().enclClass(), methodSymbol);
}
return fqnType;
}
private void updateAnnotationsOverridden(CompilationInfo compilationInfo, Collection<OverriddeAnnotation> addedAnnotations) {
final StyledDocument document = (StyledDocument) compilationInfo.getDocument();
final Collection<OverriddeAnnotation> annotationsToRemoveCopy = annotations.get(document) == null ? null : new HashSet<OverriddeAnnotation>(annotations.get(document));
final Collection<OverriddeAnnotation> addedAnnotationsCopy = new HashSet<OverriddeAnnotation>(addedAnnotations);
Runnable update = new Runnable() {
public void run() {
if (document == null) {
return;
}
if (annotationsToRemoveCopy != null) {
for (Annotation annotation : annotationsToRemoveCopy) {
NbDocument.removeAnnotation(document, annotation);
}
}
for (OverriddeAnnotation annotation : addedAnnotationsCopy) {
Position position = null;
try {
position = document.createPosition(annotation.getPosition());
} catch (BadLocationException ex) {
ex.printStackTrace();
}
if (document != null && position != null) {
NbDocument.addAnnotation(document, position, annotation.getPosition(), annotation);
}
}
annotations.put(document, addedAnnotationsCopy);
}
};
runRunnable(update);
}
private void runRunnable(Runnable task) {
if (SwingUtilities.isEventDispatchThread()) {
task.run();
} else {
SwingUtilities.invokeLater(task);
}
}
private void clear() {
addedAnotations.clear();
classes.clear();
overriddenMethods.clear();
}
};
}
private static class OverriddeAnnotation extends Annotation {
private int positon;
private String superClassFQN;
public OverriddeAnnotation(int position, String superClassFQN) {
this.positon = position;
this.superClassFQN = superClassFQN;
}
@Override
public String getAnnotationType() {
return ANNOTATION_TYPE;
}
@Override
public String getShortDescription() {
return NbBundle.getMessage(MarkOverriddenTaskFactory.class, "LABEL_OVERRIDES") + superClassFQN; //NOI18N
}
int getPosition() {
return positon;
}
}
}
| false | true | protected CancellableTask<CompilationInfo> createTask(final FileObject file) {
final Collection<Element> classes = new HashSet<Element>();
final Map<Element, List<MethodSymbol>> overriddenMethods = new HashMap<Element, List<MethodSymbol>>();
final Collection<OverriddeAnnotation> addedAnotations = new HashSet<OverriddeAnnotation>();
return new CancellableTask<CompilationInfo>() {
public void cancel() {
cancel.set(true);
}
@SuppressWarnings("element-type-mismatch") //NOI18N
public void run(final CompilationInfo compilationInfo) throws Exception {
cancel.set(false);
final JavaFXTreePathScanner<Void, Void> visitor = new OverrideVisitor(compilationInfo, classes, overriddenMethods);
visitor.scan(compilationInfo.getCompilationUnit(), null);
SourcePositions sourcePositions = compilationInfo.getTrees().getSourcePositions();
for (Element currentClass : classes) {
if (overriddenMethods.get(currentClass) == null || overriddenMethods.get(currentClass).isEmpty()) {
continue;
}
ClassSymbol classSymbol = (ClassSymbol) currentClass;
for (Element element : overriddenMethods.get(currentClass)) {
if (element instanceof MethodSymbol) {
String fqnString = null;
if (classSymbol.getInterfaces().size() == 1) {
fqnString = classSymbol.getInterfaces().iterator().next().toString();
} else {
for (Type classType : classSymbol.getInterfaces()) {
fqnString = getOwnerClass(classType.asElement().enclClass(), (MethodSymbol) element);
if (fqnString != null) {
break;
}
}
}
if (fqnString != null) {
Tree tree = compilationInfo.getTrees().getTree(element);
int start = (int) sourcePositions.getStartPosition(compilationInfo.getCompilationUnit(), tree);
boolean isInErrorZone = false;
for (Diagnostic diagnostic : compilationInfo.getDiagnostics()) {
if (diagnostic.getStartPosition() <= start && diagnostic.getEndPosition() >= start) {
isInErrorZone = true;
}
}
if (start > 0 && !isInErrorZone) {
addedAnotations.add(new OverriddeAnnotation(start, fqnString));
}
}
}
}
}
updateAnnotationsOverridden(compilationInfo, addedAnotations);
clear();
}
private String getOwnerClass(ClassSymbol classSymbol, MethodSymbol methodSymbol) {
String fqnType = null;
for (Symbol symbol : classSymbol.getEnclosedElements()) {
if (symbol instanceof MethodSymbol) {
MethodSymbol method = (MethodSymbol) symbol;
if (!method.name.toString().equals(methodSymbol.name.toString())) {
continue;
}
if (method.getReturnType() != methodSymbol.getReturnType()) {
continue;
}
if (method.getParameters().size() != methodSymbol.getParameters().size()) {
continue;
}
return classSymbol.className();
}
}
if (fqnType != null) {
return fqnType;
}
for (Type classType : classSymbol.getInterfaces()) {
fqnType = getOwnerClass(classType.asElement().enclClass(), methodSymbol);
}
return fqnType;
}
private void updateAnnotationsOverridden(CompilationInfo compilationInfo, Collection<OverriddeAnnotation> addedAnnotations) {
final StyledDocument document = (StyledDocument) compilationInfo.getDocument();
final Collection<OverriddeAnnotation> annotationsToRemoveCopy = annotations.get(document) == null ? null : new HashSet<OverriddeAnnotation>(annotations.get(document));
final Collection<OverriddeAnnotation> addedAnnotationsCopy = new HashSet<OverriddeAnnotation>(addedAnnotations);
Runnable update = new Runnable() {
public void run() {
if (document == null) {
return;
}
if (annotationsToRemoveCopy != null) {
for (Annotation annotation : annotationsToRemoveCopy) {
NbDocument.removeAnnotation(document, annotation);
}
}
for (OverriddeAnnotation annotation : addedAnnotationsCopy) {
Position position = null;
try {
position = document.createPosition(annotation.getPosition());
} catch (BadLocationException ex) {
ex.printStackTrace();
}
if (document != null && position != null) {
NbDocument.addAnnotation(document, position, annotation.getPosition(), annotation);
}
}
annotations.put(document, addedAnnotationsCopy);
}
};
runRunnable(update);
}
private void runRunnable(Runnable task) {
if (SwingUtilities.isEventDispatchThread()) {
task.run();
} else {
SwingUtilities.invokeLater(task);
}
}
private void clear() {
addedAnotations.clear();
classes.clear();
overriddenMethods.clear();
}
};
}
| protected CancellableTask<CompilationInfo> createTask(final FileObject file) {
final Collection<Element> classes = new HashSet<Element>();
final Map<Element, List<MethodSymbol>> overriddenMethods = new HashMap<Element, List<MethodSymbol>>();
final Collection<OverriddeAnnotation> addedAnotations = new HashSet<OverriddeAnnotation>();
return new CancellableTask<CompilationInfo>() {
public void cancel() {
cancel.set(true);
}
@SuppressWarnings("element-type-mismatch") //NOI18N
public void run(final CompilationInfo compilationInfo) throws Exception {
cancel.set(false);
final JavaFXTreePathScanner<Void, Void> visitor = new OverrideVisitor(compilationInfo, classes, overriddenMethods);
visitor.scan(compilationInfo.getCompilationUnit(), null);
SourcePositions sourcePositions = compilationInfo.getTrees().getSourcePositions();
for (Element currentClass : classes) {
if (overriddenMethods.get(currentClass) == null || overriddenMethods.get(currentClass).isEmpty()) {
continue;
}
ClassSymbol classSymbol = (ClassSymbol) currentClass;
for (Element element : overriddenMethods.get(currentClass)) {
if (element instanceof MethodSymbol) {
String fqnString = null;
if (classSymbol.getInterfaces().size() == 1) {
fqnString = classSymbol.getInterfaces().iterator().next().toString();
} else {
for (Type classType : classSymbol.getInterfaces()) {
fqnString = getOwnerClassName(classType.asElement().enclClass(), (MethodSymbol) element);
if (fqnString != null) {
break;
}
}
}
if (fqnString != null) {
Tree tree = compilationInfo.getTrees().getTree(element);
int start = (int) sourcePositions.getStartPosition(compilationInfo.getCompilationUnit(), tree);
boolean isInErrorZone = false;
for (Diagnostic diagnostic : compilationInfo.getDiagnostics()) {
if (diagnostic.getStartPosition() <= start && diagnostic.getEndPosition() >= start) {
isInErrorZone = true;
}
}
if (start > 0 && !isInErrorZone) {
addedAnotations.add(new OverriddeAnnotation(start, fqnString));
}
}
}
}
}
updateAnnotationsOverridden(compilationInfo, addedAnotations);
clear();
}
private String getOwnerClassName(ClassSymbol classSymbol, MethodSymbol methodSymbol) {
String fqnType = null;
if (classSymbol == null || classSymbol.getEnclosedElements() == null) {
return null;
}
for (Symbol symbol : classSymbol.getEnclosedElements()) {
if (symbol instanceof MethodSymbol) {
MethodSymbol method = (MethodSymbol) symbol;
if (!method.name.toString().equals(methodSymbol.name.toString())) {
continue;
}
if (method.getReturnType() != methodSymbol.getReturnType()) {
continue;
}
if (method.getParameters().size() != methodSymbol.getParameters().size()) {
continue;
}
return classSymbol.className();
}
}
if (fqnType != null) {
return fqnType;
}
for (Type classType : classSymbol.getInterfaces()) {
fqnType = getOwnerClassName(classType.asElement().enclClass(), methodSymbol);
}
return fqnType;
}
private void updateAnnotationsOverridden(CompilationInfo compilationInfo, Collection<OverriddeAnnotation> addedAnnotations) {
final StyledDocument document = (StyledDocument) compilationInfo.getDocument();
final Collection<OverriddeAnnotation> annotationsToRemoveCopy = annotations.get(document) == null ? null : new HashSet<OverriddeAnnotation>(annotations.get(document));
final Collection<OverriddeAnnotation> addedAnnotationsCopy = new HashSet<OverriddeAnnotation>(addedAnnotations);
Runnable update = new Runnable() {
public void run() {
if (document == null) {
return;
}
if (annotationsToRemoveCopy != null) {
for (Annotation annotation : annotationsToRemoveCopy) {
NbDocument.removeAnnotation(document, annotation);
}
}
for (OverriddeAnnotation annotation : addedAnnotationsCopy) {
Position position = null;
try {
position = document.createPosition(annotation.getPosition());
} catch (BadLocationException ex) {
ex.printStackTrace();
}
if (document != null && position != null) {
NbDocument.addAnnotation(document, position, annotation.getPosition(), annotation);
}
}
annotations.put(document, addedAnnotationsCopy);
}
};
runRunnable(update);
}
private void runRunnable(Runnable task) {
if (SwingUtilities.isEventDispatchThread()) {
task.run();
} else {
SwingUtilities.invokeLater(task);
}
}
private void clear() {
addedAnotations.clear();
classes.clear();
overriddenMethods.clear();
}
};
}
|
diff --git a/src/org/fox/ttrss/ApiRequest.java b/src/org/fox/ttrss/ApiRequest.java
index d1b832c..bea5ce5 100644
--- a/src/org/fox/ttrss/ApiRequest.java
+++ b/src/org/fox/ttrss/ApiRequest.java
@@ -1,250 +1,250 @@
package org.fox.ttrss;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.util.Log;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class ApiRequest extends AsyncTask<HashMap<String,String>, Integer, JsonElement> {
private final String TAG = this.getClass().getSimpleName();
public enum ApiError { NO_ERROR, HTTP_UNAUTHORIZED, HTTP_FORBIDDEN, HTTP_NOT_FOUND,
HTTP_SERVER_ERROR, HTTP_OTHER_ERROR, SSL_REJECTED, PARSE_ERROR, IO_ERROR, OTHER_ERROR, API_DISABLED, API_UNKNOWN, LOGIN_FAILED, INVALID_URL, INCORRECT_USAGE };
public static final int API_STATUS_OK = 0;
public static final int API_STATUS_ERR = 1;
private String m_api;
private boolean m_trustAny = false;
private boolean m_transportDebugging = false;
protected int m_httpStatusCode = 0;
protected int m_apiStatusCode = 0;
protected Context m_context;
private SharedPreferences m_prefs;
protected ApiError m_lastError;
public ApiRequest(Context context) {
m_context = context;
m_prefs = PreferenceManager.getDefaultSharedPreferences(m_context);
m_api = m_prefs.getString("ttrss_url", null).trim();
m_trustAny = m_prefs.getBoolean("ssl_trust_any", false);
m_transportDebugging = m_prefs.getBoolean("transport_debugging", false);
m_lastError = ApiError.NO_ERROR;
}
protected int getErrorMessage() {
switch (m_lastError) {
case NO_ERROR:
return R.string.error_unknown;
case HTTP_UNAUTHORIZED:
return R.string.error_http_unauthorized;
case HTTP_FORBIDDEN:
return R.string.error_http_forbidden;
case HTTP_NOT_FOUND:
return R.string.error_http_not_found;
case HTTP_SERVER_ERROR:
return R.string.error_http_server_error;
case HTTP_OTHER_ERROR:
return R.string.error_http_other_error;
case SSL_REJECTED:
return R.string.error_ssl_rejected;
case PARSE_ERROR:
return R.string.error_parse_error;
case IO_ERROR:
return R.string.error_io_error;
case OTHER_ERROR:
return R.string.error_other_error;
case API_DISABLED:
return R.string.error_api_disabled;
case API_UNKNOWN:
return R.string.error_api_unknown;
case LOGIN_FAILED:
return R.string.error_login_failed;
case INVALID_URL:
return R.string.error_invalid_api_url;
case INCORRECT_USAGE:
return R.string.error_api_incorrect_usage;
default:
Log.d(TAG, "getErrorMessage: unknown error code=" + m_lastError);
return R.string.error_unknown;
}
}
@Override
protected JsonElement doInBackground(HashMap<String, String>... params) {
Gson gson = new Gson();
String requestStr = gson.toJson(new HashMap<String,String>(params[0]));
if (m_transportDebugging) Log.d(TAG, ">>> (" + requestStr + ") " + m_api);
DefaultHttpClient client;
if (m_trustAny) {
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
schemeRegistry.register(new Scheme("https", new EasySSLSocketFactory(), 443));
HttpParams httpParams = new BasicHttpParams();
client = new DefaultHttpClient(new ThreadSafeClientConnManager(httpParams, schemeRegistry), httpParams);
} else {
client = new DefaultHttpClient();
}
try {
HttpPost httpPost;
try {
httpPost = new HttpPost(m_api + "/api/");
} catch (IllegalArgumentException e) {
m_lastError = ApiError.INVALID_URL;
e.printStackTrace();
return null;
} catch (Exception e) {
m_lastError = ApiError.OTHER_ERROR;
e.printStackTrace();
return null;
}
String httpLogin = m_prefs.getString("http_login", "").trim();
String httpPassword = m_prefs.getString("http_password", "").trim();
if (httpLogin.length() > 0) {
if (m_transportDebugging) Log.d(TAG, "Using HTTP Basic authentication.");
URL targetUrl;
try {
targetUrl = new URL(m_api);
} catch (MalformedURLException e) {
m_lastError = ApiError.INVALID_URL;
e.printStackTrace();
return null;
}
HttpHost targetHost = new HttpHost(targetUrl.getHost(), targetUrl.getPort(), targetUrl.getProtocol());
client.getCredentialsProvider().setCredentials(
new AuthScope(targetHost.getHostName(), targetHost.getPort()),
new UsernamePasswordCredentials(httpLogin, httpPassword));
}
httpPost.setEntity(new StringEntity(requestStr, "utf-8"));
HttpResponse execute = client.execute(httpPost);
m_httpStatusCode = execute.getStatusLine().getStatusCode();
switch (m_httpStatusCode) {
case 200:
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(
new InputStreamReader(content), 8192);
String s = "";
String response = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
if (m_transportDebugging) Log.d(TAG, "<<< " + response);
JsonParser parser = new JsonParser();
JsonElement result = parser.parse(response);
JsonObject resultObj = result.getAsJsonObject();
m_apiStatusCode = resultObj.get("status").getAsInt();
switch (m_apiStatusCode) {
case API_STATUS_OK:
return result.getAsJsonObject().get("content");
case API_STATUS_ERR:
JsonObject contentObj = resultObj.get("content").getAsJsonObject();
String error = contentObj.get("error").getAsString();
if (error.equals("LOGIN_ERROR")) {
m_lastError = ApiError.LOGIN_FAILED;
} else if (error.equals("API_DISABLED")) {
- m_lastError = ApiError.LOGIN_FAILED;
+ m_lastError = ApiError.API_DISABLED;
} else if (error.equals("NOT_LOGGED_IN")) {
m_lastError = ApiError.LOGIN_FAILED;
} else if (error.equals("INCORRECT_USAGE")) {
m_lastError = ApiError.INCORRECT_USAGE;
} else {
Log.d(TAG, "Unknown API error: " + error);
m_lastError = ApiError.API_UNKNOWN;
}
}
return null;
case 401:
m_lastError = ApiError.HTTP_UNAUTHORIZED;
break;
case 403:
m_lastError = ApiError.HTTP_FORBIDDEN;
break;
case 404:
m_lastError = ApiError.HTTP_NOT_FOUND;
break;
case 500:
m_lastError = ApiError.HTTP_SERVER_ERROR;
break;
default:
m_lastError = ApiError.HTTP_OTHER_ERROR;
break;
}
return null;
} catch (javax.net.ssl.SSLPeerUnverifiedException e) {
m_lastError = ApiError.SSL_REJECTED;
e.printStackTrace();
} catch (IOException e) {
m_lastError = ApiError.IO_ERROR;
e.printStackTrace();
} catch (com.google.gson.JsonSyntaxException e) {
m_lastError = ApiError.PARSE_ERROR;
e.printStackTrace();
} catch (Exception e) {
m_lastError = ApiError.OTHER_ERROR;
e.printStackTrace();
}
return null;
}
}
| true | true | protected JsonElement doInBackground(HashMap<String, String>... params) {
Gson gson = new Gson();
String requestStr = gson.toJson(new HashMap<String,String>(params[0]));
if (m_transportDebugging) Log.d(TAG, ">>> (" + requestStr + ") " + m_api);
DefaultHttpClient client;
if (m_trustAny) {
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
schemeRegistry.register(new Scheme("https", new EasySSLSocketFactory(), 443));
HttpParams httpParams = new BasicHttpParams();
client = new DefaultHttpClient(new ThreadSafeClientConnManager(httpParams, schemeRegistry), httpParams);
} else {
client = new DefaultHttpClient();
}
try {
HttpPost httpPost;
try {
httpPost = new HttpPost(m_api + "/api/");
} catch (IllegalArgumentException e) {
m_lastError = ApiError.INVALID_URL;
e.printStackTrace();
return null;
} catch (Exception e) {
m_lastError = ApiError.OTHER_ERROR;
e.printStackTrace();
return null;
}
String httpLogin = m_prefs.getString("http_login", "").trim();
String httpPassword = m_prefs.getString("http_password", "").trim();
if (httpLogin.length() > 0) {
if (m_transportDebugging) Log.d(TAG, "Using HTTP Basic authentication.");
URL targetUrl;
try {
targetUrl = new URL(m_api);
} catch (MalformedURLException e) {
m_lastError = ApiError.INVALID_URL;
e.printStackTrace();
return null;
}
HttpHost targetHost = new HttpHost(targetUrl.getHost(), targetUrl.getPort(), targetUrl.getProtocol());
client.getCredentialsProvider().setCredentials(
new AuthScope(targetHost.getHostName(), targetHost.getPort()),
new UsernamePasswordCredentials(httpLogin, httpPassword));
}
httpPost.setEntity(new StringEntity(requestStr, "utf-8"));
HttpResponse execute = client.execute(httpPost);
m_httpStatusCode = execute.getStatusLine().getStatusCode();
switch (m_httpStatusCode) {
case 200:
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(
new InputStreamReader(content), 8192);
String s = "";
String response = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
if (m_transportDebugging) Log.d(TAG, "<<< " + response);
JsonParser parser = new JsonParser();
JsonElement result = parser.parse(response);
JsonObject resultObj = result.getAsJsonObject();
m_apiStatusCode = resultObj.get("status").getAsInt();
switch (m_apiStatusCode) {
case API_STATUS_OK:
return result.getAsJsonObject().get("content");
case API_STATUS_ERR:
JsonObject contentObj = resultObj.get("content").getAsJsonObject();
String error = contentObj.get("error").getAsString();
if (error.equals("LOGIN_ERROR")) {
m_lastError = ApiError.LOGIN_FAILED;
} else if (error.equals("API_DISABLED")) {
m_lastError = ApiError.LOGIN_FAILED;
} else if (error.equals("NOT_LOGGED_IN")) {
m_lastError = ApiError.LOGIN_FAILED;
} else if (error.equals("INCORRECT_USAGE")) {
m_lastError = ApiError.INCORRECT_USAGE;
} else {
Log.d(TAG, "Unknown API error: " + error);
m_lastError = ApiError.API_UNKNOWN;
}
}
return null;
case 401:
m_lastError = ApiError.HTTP_UNAUTHORIZED;
break;
case 403:
m_lastError = ApiError.HTTP_FORBIDDEN;
break;
case 404:
m_lastError = ApiError.HTTP_NOT_FOUND;
break;
case 500:
m_lastError = ApiError.HTTP_SERVER_ERROR;
break;
default:
m_lastError = ApiError.HTTP_OTHER_ERROR;
break;
}
return null;
} catch (javax.net.ssl.SSLPeerUnverifiedException e) {
m_lastError = ApiError.SSL_REJECTED;
e.printStackTrace();
} catch (IOException e) {
m_lastError = ApiError.IO_ERROR;
e.printStackTrace();
} catch (com.google.gson.JsonSyntaxException e) {
m_lastError = ApiError.PARSE_ERROR;
e.printStackTrace();
} catch (Exception e) {
m_lastError = ApiError.OTHER_ERROR;
e.printStackTrace();
}
return null;
}
| protected JsonElement doInBackground(HashMap<String, String>... params) {
Gson gson = new Gson();
String requestStr = gson.toJson(new HashMap<String,String>(params[0]));
if (m_transportDebugging) Log.d(TAG, ">>> (" + requestStr + ") " + m_api);
DefaultHttpClient client;
if (m_trustAny) {
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
schemeRegistry.register(new Scheme("https", new EasySSLSocketFactory(), 443));
HttpParams httpParams = new BasicHttpParams();
client = new DefaultHttpClient(new ThreadSafeClientConnManager(httpParams, schemeRegistry), httpParams);
} else {
client = new DefaultHttpClient();
}
try {
HttpPost httpPost;
try {
httpPost = new HttpPost(m_api + "/api/");
} catch (IllegalArgumentException e) {
m_lastError = ApiError.INVALID_URL;
e.printStackTrace();
return null;
} catch (Exception e) {
m_lastError = ApiError.OTHER_ERROR;
e.printStackTrace();
return null;
}
String httpLogin = m_prefs.getString("http_login", "").trim();
String httpPassword = m_prefs.getString("http_password", "").trim();
if (httpLogin.length() > 0) {
if (m_transportDebugging) Log.d(TAG, "Using HTTP Basic authentication.");
URL targetUrl;
try {
targetUrl = new URL(m_api);
} catch (MalformedURLException e) {
m_lastError = ApiError.INVALID_URL;
e.printStackTrace();
return null;
}
HttpHost targetHost = new HttpHost(targetUrl.getHost(), targetUrl.getPort(), targetUrl.getProtocol());
client.getCredentialsProvider().setCredentials(
new AuthScope(targetHost.getHostName(), targetHost.getPort()),
new UsernamePasswordCredentials(httpLogin, httpPassword));
}
httpPost.setEntity(new StringEntity(requestStr, "utf-8"));
HttpResponse execute = client.execute(httpPost);
m_httpStatusCode = execute.getStatusLine().getStatusCode();
switch (m_httpStatusCode) {
case 200:
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(
new InputStreamReader(content), 8192);
String s = "";
String response = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
if (m_transportDebugging) Log.d(TAG, "<<< " + response);
JsonParser parser = new JsonParser();
JsonElement result = parser.parse(response);
JsonObject resultObj = result.getAsJsonObject();
m_apiStatusCode = resultObj.get("status").getAsInt();
switch (m_apiStatusCode) {
case API_STATUS_OK:
return result.getAsJsonObject().get("content");
case API_STATUS_ERR:
JsonObject contentObj = resultObj.get("content").getAsJsonObject();
String error = contentObj.get("error").getAsString();
if (error.equals("LOGIN_ERROR")) {
m_lastError = ApiError.LOGIN_FAILED;
} else if (error.equals("API_DISABLED")) {
m_lastError = ApiError.API_DISABLED;
} else if (error.equals("NOT_LOGGED_IN")) {
m_lastError = ApiError.LOGIN_FAILED;
} else if (error.equals("INCORRECT_USAGE")) {
m_lastError = ApiError.INCORRECT_USAGE;
} else {
Log.d(TAG, "Unknown API error: " + error);
m_lastError = ApiError.API_UNKNOWN;
}
}
return null;
case 401:
m_lastError = ApiError.HTTP_UNAUTHORIZED;
break;
case 403:
m_lastError = ApiError.HTTP_FORBIDDEN;
break;
case 404:
m_lastError = ApiError.HTTP_NOT_FOUND;
break;
case 500:
m_lastError = ApiError.HTTP_SERVER_ERROR;
break;
default:
m_lastError = ApiError.HTTP_OTHER_ERROR;
break;
}
return null;
} catch (javax.net.ssl.SSLPeerUnverifiedException e) {
m_lastError = ApiError.SSL_REJECTED;
e.printStackTrace();
} catch (IOException e) {
m_lastError = ApiError.IO_ERROR;
e.printStackTrace();
} catch (com.google.gson.JsonSyntaxException e) {
m_lastError = ApiError.PARSE_ERROR;
e.printStackTrace();
} catch (Exception e) {
m_lastError = ApiError.OTHER_ERROR;
e.printStackTrace();
}
return null;
}
|
diff --git a/javasrc/src/org/ccnx/ccn/profiles/security/access/KeyCache.java b/javasrc/src/org/ccnx/ccn/profiles/security/access/KeyCache.java
index 2f7e6d5f2..474cc4e9e 100644
--- a/javasrc/src/org/ccnx/ccn/profiles/security/access/KeyCache.java
+++ b/javasrc/src/org/ccnx/ccn/profiles/security/access/KeyCache.java
@@ -1,241 +1,241 @@
/**
* Part of the CCNx Java Library.
*
* Copyright (C) 2008, 2009 Palo Alto Research Center, Inc.
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version 2.1
* as published by the Free Software Foundation.
* 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., 51 Franklin Street,
* Fifth Floor, Boston, MA 02110-1301 USA.
*/
package org.ccnx.ccn.profiles.security.access;
import java.security.Key;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.UnrecoverableEntryException;
import java.security.cert.X509Certificate;
import java.util.Collection;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.TreeMap;
import org.ccnx.ccn.KeyManager;
import org.ccnx.ccn.impl.security.crypto.CCNDigestHelper;
import org.ccnx.ccn.impl.security.keys.KeyRepository;
import org.ccnx.ccn.impl.security.keys.BasicKeyManager.KeyStoreInfo;
import org.ccnx.ccn.impl.support.ByteArrayCompare;
import org.ccnx.ccn.impl.support.Log;
import org.ccnx.ccn.protocol.ContentName;
import org.ccnx.ccn.protocol.PublisherPublicKeyDigest;
/**
* A cache for decrypted symmetric keys for access control.
*
*/
public class KeyCache {
static Comparator<byte[]> byteArrayComparator = new ByteArrayCompare();
/** Map the digest of a key to the key. */
private TreeMap<byte [], Key> _keyMap = new TreeMap<byte [], Key>(byteArrayComparator);
/** Map the digest of a public key to <I>my</I> corresponding private key. */
private TreeMap<byte [], PrivateKey> _myKeyMap = new TreeMap<byte [], PrivateKey>(byteArrayComparator);
/** Map the digest of a public key to the corresponding private key */
private TreeMap<byte [], PrivateKey> _privateKeyMap = new TreeMap<byte [], PrivateKey>(byteArrayComparator);
/** Map the digest of a private key to the digest of the corresponding public key. */
private TreeMap<byte [], byte []> _privateKeyIdentifierMap = new TreeMap<byte [], byte[]>(byteArrayComparator);
/** Map the digest of a key to its name */
private TreeMap<byte [], ContentName> _keyNameMap = new TreeMap<byte [], ContentName>(byteArrayComparator);
public KeyCache() {
}
/**
* Constructor that loads keys from a KeyManager
* @param keyManagerToLoadFrom the key manager
*/
public KeyCache(KeyManager keyManagerToLoadFrom) {
PrivateKey [] pks = keyManagerToLoadFrom.getSigningKeys();
for (PrivateKey pk : pks) {
addMyPrivateKey(keyManagerToLoadFrom.getPublisherKeyID(pk).digest(), pk);
}
}
/**
* Load the private keys from a KeyStore.
* @param keystore
* @throws KeyStoreException
*/
public void loadKeyStore(KeyStoreInfo keyStoreInfo, char [] password, KeyRepository publicKeyCache) throws KeyStoreException {
Enumeration<String> aliases = keyStoreInfo.getKeyStore().aliases();
String alias;
KeyStore.PrivateKeyEntry entry = null;
KeyStore.PasswordProtection passwordProtection = new KeyStore.PasswordProtection(password);
while (aliases.hasMoreElements()) {
alias = aliases.nextElement();
if (keyStoreInfo.getKeyStore().isKeyEntry(alias)) {
try {
entry = (KeyStore.PrivateKeyEntry)keyStoreInfo.getKeyStore().getEntry(alias, passwordProtection);
} catch (NoSuchAlgorithmException e) {
throw new KeyStoreException("Unexpected NoSuchAlgorithm retrieving key for alias : " + alias, e);
} catch (UnrecoverableEntryException e) {
throw new KeyStoreException("Unexpected UnrecoverableEntryException retrieving key for alias : " + alias, e);
}
if (null == entry) {
Log.warning("Cannot get private key entry for alias: " + alias);
} else {
PrivateKey pk = entry.getPrivateKey();
if (null != pk) {
- if (keyStoreInfo.getKeyStore().isCertificateEntry(alias)) {
- X509Certificate certificate = (X509Certificate)entry.getCertificate();
+ X509Certificate certificate = (X509Certificate)entry.getCertificate();
+ if (null != certificate) {
PublisherPublicKeyDigest ppkd = new PublisherPublicKeyDigest(certificate.getPublicKey());
if (null != ppkd) {
addMyPrivateKey(ppkd.digest(), pk);
publicKeyCache.remember(certificate, keyStoreInfo.getVersion());
} else {
Log.warning("Certificate has null public key for alias " + alias + "!");
}
} else {
Log.warning("Private key for alias: " + alias + " has no certificate entry. No way to get public key. Not caching.");
}
} else {
Log.warning("Cannot retrieve private key for key entry alias " + alias);
}
}
}
}
}
/**
* Retrieve a key specified by its digest
* To restrict access to keys, store key cache in a private variable, and don't
* allow references to it from untrusted code.
* @param desiredKeyIdentifier the digest
* @return the key
*/
public Key getKey(byte [] desiredKeyIdentifier) {
Key theKey = _keyMap.get(desiredKeyIdentifier);
if (null == theKey) {
theKey = _privateKeyMap.get(desiredKeyIdentifier);
}
if (null == theKey) {
theKey = _myKeyMap.get(desiredKeyIdentifier);
}
return theKey;
}
/**
* Checks whether we have a record of a key specified by its digest.
* @param keyIdentifier the key digest.
* @return
*/
public boolean containsKey(byte [] keyIdentifier) {
if ((_keyMap.containsKey(keyIdentifier)) || (_myKeyMap.containsKey(keyIdentifier)) ||
(_privateKeyMap.containsKey(keyIdentifier))) {
return true;
}
return false;
}
/**
* Returns the name of a key specified by its digest
* @param keyIdentifier the digest of the key.
* @return the name of the key.
*/
public ContentName getKeyName(byte [] keyIdentifier) {
return _keyNameMap.get(keyIdentifier);
}
/**
* Get the name of a specified key
* @param key the key
* @return the name
*/
public ContentName getKeyName(Key key) {
return getKeyName(getKeyIdentifier(key));
}
/**
* Returns the private key corresponding to a public key specified by its digest.
* To restrict access to keys, store key cache in a private variable, and don't
* allow references to it from untrusted code.
* @param desiredPublicKeyIdentifier the digest of the public key.
* @return the corresponding private key.
*/
public PrivateKey getPrivateKey(byte [] desiredPublicKeyIdentifier) {
PrivateKey key = _myKeyMap.get(desiredPublicKeyIdentifier);
if (null == key) {
key = _privateKeyMap.get(desiredPublicKeyIdentifier);
}
return key;
}
public PrivateKey [] getPrivateKeys() {
Collection<PrivateKey> myKeys = _myKeyMap.values();
myKeys.addAll(_privateKeyMap.values());
PrivateKey [] pkarray = new PrivateKey[myKeys.size()];
return myKeys.toArray(pkarray);
}
/**
* Records a private key and the name and digest of the corresponding public key.
* @param keyName the name of the public key
* @param publicKeyIdentifier the digest of the public key
* @param pk the private key
*/
public void addPrivateKey(ContentName keyName, byte [] publicKeyIdentifier, PrivateKey pk) {
_privateKeyMap.put(publicKeyIdentifier, pk);
_privateKeyIdentifierMap.put(getKeyIdentifier(pk), publicKeyIdentifier);
if (null != keyName)
_keyNameMap.put(publicKeyIdentifier, keyName);
}
/**
* Records one of my private keys and the digest of the corresponding public key.
* @param publicKeyIdentifier the digest of the public key.
* @param pk the corresponding private key.
*/
public void addMyPrivateKey(byte [] publicKeyIdentifier, PrivateKey pk) {
_privateKeyIdentifierMap.put(getKeyIdentifier(pk), publicKeyIdentifier);
_myKeyMap.put(publicKeyIdentifier, pk);
}
/**
* Make a record of a key by its name and digest.
* @param name the name of the key.
* @param key the key.
*/
public void addKey(ContentName name, Key key) {
byte [] id = getKeyIdentifier(key);
_keyMap.put(id, key);
if (null != name) {
_keyNameMap.put(id, name);
}
}
public PublisherPublicKeyDigest getPublicKeyIdentifier(PrivateKey pk) {
// TODO make map store PPKD's directly
return new PublisherPublicKeyDigest(_privateKeyIdentifierMap.get(getKeyIdentifier(pk)));
}
/**
* Returns the digest of a specified key.
* @param key the key.
* @return the digest.
*/
public static byte [] getKeyIdentifier(Key key) {
// Works on symmetric and public.
return CCNDigestHelper.digest(key.getEncoded());
}
}
| true | true | public void loadKeyStore(KeyStoreInfo keyStoreInfo, char [] password, KeyRepository publicKeyCache) throws KeyStoreException {
Enumeration<String> aliases = keyStoreInfo.getKeyStore().aliases();
String alias;
KeyStore.PrivateKeyEntry entry = null;
KeyStore.PasswordProtection passwordProtection = new KeyStore.PasswordProtection(password);
while (aliases.hasMoreElements()) {
alias = aliases.nextElement();
if (keyStoreInfo.getKeyStore().isKeyEntry(alias)) {
try {
entry = (KeyStore.PrivateKeyEntry)keyStoreInfo.getKeyStore().getEntry(alias, passwordProtection);
} catch (NoSuchAlgorithmException e) {
throw new KeyStoreException("Unexpected NoSuchAlgorithm retrieving key for alias : " + alias, e);
} catch (UnrecoverableEntryException e) {
throw new KeyStoreException("Unexpected UnrecoverableEntryException retrieving key for alias : " + alias, e);
}
if (null == entry) {
Log.warning("Cannot get private key entry for alias: " + alias);
} else {
PrivateKey pk = entry.getPrivateKey();
if (null != pk) {
if (keyStoreInfo.getKeyStore().isCertificateEntry(alias)) {
X509Certificate certificate = (X509Certificate)entry.getCertificate();
PublisherPublicKeyDigest ppkd = new PublisherPublicKeyDigest(certificate.getPublicKey());
if (null != ppkd) {
addMyPrivateKey(ppkd.digest(), pk);
publicKeyCache.remember(certificate, keyStoreInfo.getVersion());
} else {
Log.warning("Certificate has null public key for alias " + alias + "!");
}
} else {
Log.warning("Private key for alias: " + alias + " has no certificate entry. No way to get public key. Not caching.");
}
} else {
Log.warning("Cannot retrieve private key for key entry alias " + alias);
}
}
}
}
}
| public void loadKeyStore(KeyStoreInfo keyStoreInfo, char [] password, KeyRepository publicKeyCache) throws KeyStoreException {
Enumeration<String> aliases = keyStoreInfo.getKeyStore().aliases();
String alias;
KeyStore.PrivateKeyEntry entry = null;
KeyStore.PasswordProtection passwordProtection = new KeyStore.PasswordProtection(password);
while (aliases.hasMoreElements()) {
alias = aliases.nextElement();
if (keyStoreInfo.getKeyStore().isKeyEntry(alias)) {
try {
entry = (KeyStore.PrivateKeyEntry)keyStoreInfo.getKeyStore().getEntry(alias, passwordProtection);
} catch (NoSuchAlgorithmException e) {
throw new KeyStoreException("Unexpected NoSuchAlgorithm retrieving key for alias : " + alias, e);
} catch (UnrecoverableEntryException e) {
throw new KeyStoreException("Unexpected UnrecoverableEntryException retrieving key for alias : " + alias, e);
}
if (null == entry) {
Log.warning("Cannot get private key entry for alias: " + alias);
} else {
PrivateKey pk = entry.getPrivateKey();
if (null != pk) {
X509Certificate certificate = (X509Certificate)entry.getCertificate();
if (null != certificate) {
PublisherPublicKeyDigest ppkd = new PublisherPublicKeyDigest(certificate.getPublicKey());
if (null != ppkd) {
addMyPrivateKey(ppkd.digest(), pk);
publicKeyCache.remember(certificate, keyStoreInfo.getVersion());
} else {
Log.warning("Certificate has null public key for alias " + alias + "!");
}
} else {
Log.warning("Private key for alias: " + alias + " has no certificate entry. No way to get public key. Not caching.");
}
} else {
Log.warning("Cannot retrieve private key for key entry alias " + alias);
}
}
}
}
}
|
diff --git a/src/main/java/net/daboross/bukkitdev/fixstrength/FixStrength.java b/src/main/java/net/daboross/bukkitdev/fixstrength/FixStrength.java
index 4ff6429..48842a3 100644
--- a/src/main/java/net/daboross/bukkitdev/fixstrength/FixStrength.java
+++ b/src/main/java/net/daboross/bukkitdev/fixstrength/FixStrength.java
@@ -1,89 +1,89 @@
/*
* Copyright (C) 2013 Dabo Ross <http://www.daboross.net/>
*
* 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 net.daboross.bukkitdev.fixstrength;
import java.util.Map;
import java.util.Random;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
/**
*
* @author daboross
*/
public class FixStrength extends JavaPlugin implements Listener {
private static final double CONSTANT_TIMES = 10;
private static final double CONSTANT_DIVIDE = 13;
private static final double CONSTANT_PLUS = 1.5;
private static final double CONSTANT_PLUS_2 = 0.5;
@Override
public void onEnable() {
PluginManager pm = getServer().getPluginManager();
pm.registerEvents(this, this);
}
@Override
public void onDisable() {
}
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
sender.sendMessage("FixStrength doesn't know about the command /" + cmd);
return true;
}
@EventHandler
public void onHit(EntityDamageByEntityEvent evt) {
if (!evt.isCancelled()) {
if (evt.getDamager() instanceof Player) {
double addition = 0;
double multiplication = 1;
Player player = (Player) evt.getDamager();
for (PotionEffect potionEffect : player.getActivePotionEffects()) {
if (potionEffect.getType() == PotionEffectType.INCREASE_DAMAGE) {
multiplication *= CONSTANT_TIMES / (CONSTANT_DIVIDE * potionEffect.getAmplifier());
- addition += CONSTANT_PLUS + (CONSTANT_PLUS_2 * potionEffect.getAmplifier());
+ addition += CONSTANT_PLUS + (CONSTANT_PLUS_2 * (potionEffect.getAmplifier() + 1));
}
}
for (Map.Entry<Enchantment, Integer> enchant : player.getItemInHand().getEnchantments().entrySet()) {
if (enchant.getKey() == Enchantment.DAMAGE_ALL) {
multiplication *= 1 / (enchant.getValue());
for (int i = 0; i < enchant.getValue(); i++) {
addition += getRandomEnchant();
}
}
}
evt.setDamage((evt.getDamage() * multiplication) + addition);
}
}
}
private double getRandomEnchant() {
return 0.5 + (Math.random() * 0.75);
}
}
| true | true | public void onHit(EntityDamageByEntityEvent evt) {
if (!evt.isCancelled()) {
if (evt.getDamager() instanceof Player) {
double addition = 0;
double multiplication = 1;
Player player = (Player) evt.getDamager();
for (PotionEffect potionEffect : player.getActivePotionEffects()) {
if (potionEffect.getType() == PotionEffectType.INCREASE_DAMAGE) {
multiplication *= CONSTANT_TIMES / (CONSTANT_DIVIDE * potionEffect.getAmplifier());
addition += CONSTANT_PLUS + (CONSTANT_PLUS_2 * potionEffect.getAmplifier());
}
}
for (Map.Entry<Enchantment, Integer> enchant : player.getItemInHand().getEnchantments().entrySet()) {
if (enchant.getKey() == Enchantment.DAMAGE_ALL) {
multiplication *= 1 / (enchant.getValue());
for (int i = 0; i < enchant.getValue(); i++) {
addition += getRandomEnchant();
}
}
}
evt.setDamage((evt.getDamage() * multiplication) + addition);
}
}
}
| public void onHit(EntityDamageByEntityEvent evt) {
if (!evt.isCancelled()) {
if (evt.getDamager() instanceof Player) {
double addition = 0;
double multiplication = 1;
Player player = (Player) evt.getDamager();
for (PotionEffect potionEffect : player.getActivePotionEffects()) {
if (potionEffect.getType() == PotionEffectType.INCREASE_DAMAGE) {
multiplication *= CONSTANT_TIMES / (CONSTANT_DIVIDE * potionEffect.getAmplifier());
addition += CONSTANT_PLUS + (CONSTANT_PLUS_2 * (potionEffect.getAmplifier() + 1));
}
}
for (Map.Entry<Enchantment, Integer> enchant : player.getItemInHand().getEnchantments().entrySet()) {
if (enchant.getKey() == Enchantment.DAMAGE_ALL) {
multiplication *= 1 / (enchant.getValue());
for (int i = 0; i < enchant.getValue(); i++) {
addition += getRandomEnchant();
}
}
}
evt.setDamage((evt.getDamage() * multiplication) + addition);
}
}
}
|
diff --git a/fabric/fabric-core/src/main/scala/org/fusesource/fabric/service/FabricServiceImpl.java b/fabric/fabric-core/src/main/scala/org/fusesource/fabric/service/FabricServiceImpl.java
index eec6332b7..e45054604 100644
--- a/fabric/fabric-core/src/main/scala/org/fusesource/fabric/service/FabricServiceImpl.java
+++ b/fabric/fabric-core/src/main/scala/org/fusesource/fabric/service/FabricServiceImpl.java
@@ -1,534 +1,539 @@
/**
* Copyright (C) FuseSource, Inc.
* http://fusesource.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.fusesource.fabric.service;
import java.net.URI;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.karaf.admin.management.AdminServiceMBean;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs;
import org.fusesource.fabric.api.*;
import org.fusesource.fabric.internal.ContainerImpl;
import org.fusesource.fabric.internal.ProfileImpl;
import org.fusesource.fabric.internal.VersionImpl;
import org.fusesource.fabric.internal.ZooKeeperUtils;
import org.fusesource.fabric.zookeeper.ZkDefs;
import org.fusesource.fabric.zookeeper.ZkPath;
import org.linkedin.zookeeper.client.IZKClient;
import org.osgi.service.cm.Configuration;
import org.osgi.service.cm.ConfigurationAdmin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectInstance;
import javax.management.ObjectName;
import static org.fusesource.fabric.zookeeper.ZkPath.CONTAINER_PARENT;
public class FabricServiceImpl implements FabricService, FabricServiceImplMBean {
private transient Logger logger = LoggerFactory.getLogger(FabricServiceImpl.class);
private IZKClient zooKeeper;
private Map<String, ContainerProvider> providers;
private ConfigurationAdmin configurationAdmin;
private String profile = ZkDefs.DEFAULT_PROFILE;
private ObjectName mbeanName;
private String userName = "admin";
private String password = "admin";
public FabricServiceImpl() {
providers = new ConcurrentHashMap<String, ContainerProvider>();
providers.put("child", new ChildContainerProvider(this));
}
public IZKClient getZooKeeper() {
return zooKeeper;
}
public void setZooKeeper(IZKClient zooKeeper) {
this.zooKeeper = zooKeeper;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
@Override
public Container getCurrentContainer() {
String name = getCurrentContainerName();
return getContainer(name);
}
@Override
public String getCurrentContainerName() {
// TODO is there any other way to find this?
return System.getProperty("karaf.name");
}
public ObjectName getMbeanName() throws MalformedObjectNameException {
if (mbeanName == null) {
mbeanName = new ObjectName("org.fusesource.fabric:type=FabricService");
}
return mbeanName;
}
public void setMbeanName(ObjectName mbeanName) {
this.mbeanName = mbeanName;
}
public ConfigurationAdmin getConfigurationAdmin() {
return configurationAdmin;
}
public void setConfigurationAdmin(ConfigurationAdmin configurationAdmin) {
this.configurationAdmin = configurationAdmin;
}
public Container[] getContainers() {
try {
Map<String, Container> containers = new HashMap<String, Container>();
List<String> configs = zooKeeper.getChildren(ZkPath.CONFIGS_CONTAINERS.getPath());
for (String name : configs) {
String parentId = getParentOf(name);
if (parentId.isEmpty()) {
if (!containers.containsKey(name)) {
Container container = new ContainerImpl(null, name, this);
containers.put(name, container);
}
} else {
Container parent = containers.get(parentId);
if (parent == null) {
parent = new ContainerImpl(null, parentId, this);
containers.put(parentId, parent);
}
Container container = new ContainerImpl(parent, name, this);
containers.put(name, container);
}
}
return containers.values().toArray(new Container[containers.size()]);
} catch (Exception e) {
throw new FabricException(e);
}
}
private String getParentOf(String name) throws InterruptedException, KeeperException {
if (zooKeeper != null) {
try {
return zooKeeper.getStringData(ZkPath.CONTAINER_PARENT.getPath(name)).trim();
} catch (KeeperException.NoNodeException e) {
// Ignore
} catch (Throwable e) {
logger.warn("Failed to find parent " + name + ". This exception will be ignored.", e);
}
}
return "";
}
public Container getContainer(String name) {
if (name == null) {
return null;
}
try {
Container parent = null;
String parentId = getParentOf(name);
if (parentId != null && !parentId.isEmpty()) {
parent = getContainer(parentId);
}
return new ContainerImpl(parent, name, this);
} catch (FabricException e) {
throw e;
} catch (Exception e) {
throw new FabricException(e);
}
}
public void startContainer(final Container container) {
if (container.isRoot()) {
throw new IllegalArgumentException("Cannot start root containers");
}
getContainerTemplate(container.getParent()).execute(new ContainerTemplate.AdminServiceCallback<Object>() {
public Object doWithAdminService(AdminServiceMBean adminService) throws Exception {
adminService.startInstance(container.getId(), null);
return null;
}
});
}
public void stopContainer(final Container container) {
if (container.isRoot()) {
throw new IllegalArgumentException("Cannot stop root containers");
}
getContainerTemplate(container.getParent()).execute(new ContainerTemplate.AdminServiceCallback<Object>() {
public Object doWithAdminService(AdminServiceMBean adminService) throws Exception {
adminService.stopInstance(container.getId());
return null;
}
});
}
public static String getParentFromURI(URI uri) {
String parent = uri.getHost();
if (parent == null) {
parent = uri.getSchemeSpecificPart();
}
return parent;
}
public Container[] createContainers(final CreateContainerOptions options) {
Container[] containers = new Container[options.getNumber()];
if (options.getZookeeperUrl() == null && !options.isDebugContainer()) {
options.setZookeeperUrl(getZookeeperUrl());
}
if (options.getProxyUri() == null) {
options.setProxyUri(getMavenRepoURI());
}
try {
ContainerProvider provider = getProvider(options.getProviderType());
if (provider == null) {
throw new FabricException("Unable to find an container provider type '" + options.getProviderType() + "'");
}
Set<? extends CreateContainerMetadata> createMetadata = new LinkedHashSet<CreateContainerMetadata>();
String parent = options.getParent() != null ? options.getParent() : "";
Container parentContainer = null;
- if (provider instanceof ChildContainerProvider && !getCurrentContainer().getId().equals(parent)) {
- createMetadata = createChildContainer((CreateContainerChildOptions) options);
+ String currentID = "";
+ Container currentContainer = getCurrentContainer();
+ if (currentContainer != null) {
+ currentID = currentContainer.getId();
+ }
+ if (provider instanceof ChildContainerProvider && !parent.equals(currentID)) {
+ createMetadata = createChildContainer(options);
} else {
createMetadata = provider.create(options);
}
containers = new Container[createMetadata.size()];
int container = 0;
for(CreateContainerMetadata metadata : createMetadata) {
//An ensemble server can be created without an existing ensemble.
//In this case container config will be created by the newly created container.
if (!options.isEnsembleServer()) {
createContainerConfig(parent, metadata.getContainerName());
}
containers[container] = new ContainerImpl(parentContainer, metadata.getContainerName(), FabricServiceImpl.this);
containers[container++].setCreateContainerMetadata(metadata);
}
} catch (FabricException e) {
throw e;
} catch (Exception e) {
throw new FabricException(e);
}
return containers;
}
private Set<CreateContainerMetadata> createChildContainer(final CreateContainerOptions options) throws Exception {
Set<CreateContainerMetadata> result = new LinkedHashSet<CreateContainerMetadata>();
String parent = getParentFromURI(options.getProviderURI());
Container parentContainer = getContainer(parent);
if (!getCurrentContainer().getId().equals(parent)) {
ContainerTemplate containerTemplate = getContainerTemplate(parentContainer);
result = containerTemplate.execute(new ContainerTemplate.FabricServiceCallback<Set<CreateContainerMetadata>>() {
public Set<CreateContainerMetadata> doWithFabricService(FabricServiceImplMBean fabricService) throws Exception {
return (Set<CreateContainerMetadata>) fabricService.createRemoteContainer(options);
}
});
} else {
result = getProvider("child").create(options);
}
return result;
}
@Override
public Set<CreateContainerMetadata> createRemoteContainer(CreateContainerOptions args) {
Set<CreateContainerMetadata> result = new LinkedHashSet<CreateContainerMetadata>();
try {
Container[] containers = createContainers(args);
for (Container container: containers) {
result.add(container.getCreateContainerMetadata());
}
} catch (FabricException e) {
throw e;
} catch (Exception e) {
throw new FabricException(e);
}
return result;
}
public ContainerProvider getProvider(final String scheme) {
return providers.get(scheme);
}
public Map<String, ContainerProvider> getProviders() {
return Collections.unmodifiableMap(providers);
}
@Override
public URI getMavenRepoURI() {
URI uri = null;
try {
uri = new URI(DEFAULT_REPO_URI);
if (zooKeeper.exists(ZkPath.CONFIGS_MAVEN_REPO.getPath()) != null) {
String mavenRepo = zooKeeper.getStringData(ZkPath.CONFIGS_MAVEN_REPO.getPath());
if(mavenRepo != null && !mavenRepo.endsWith("/")) {
mavenRepo+="/";
}
uri = new URI(mavenRepo);
}
} catch (Exception e) {
//On exception just return uri.
}
return uri;
}
public void registerProvider(String scheme, ContainerProvider provider) {
providers.put(scheme, provider);
}
public void registerProvider(ContainerProvider provider, Map<String, Object> properties) {
String scheme = (String) properties.get(ContainerProvider.PROTOCOL);
registerProvider(scheme, provider);
}
public void unregisterProvider(String scheme) {
if (providers != null && scheme != null) {
providers.remove(scheme);
}
}
public void unregisterProvider(ContainerProvider provider, Map<String, Object> properties) {
String scheme = (String) properties.get(ContainerProvider.PROTOCOL);
unregisterProvider(scheme);
}
public void registerMBeanServer(MBeanServer mbeanServer) {
try {
ObjectName name = getMbeanName();
ObjectInstance objectInstance = mbeanServer.registerMBean(this, name);
} catch (Exception e) {
logger.warn("An error occurred during mbean server registration. This exception will be ignored.", e);
}
}
public void unregisterMBeanServer(MBeanServer mbeanServer) {
if (mbeanServer != null) {
try {
mbeanServer.unregisterMBean(getMbeanName());
} catch (Exception e) {
logger.warn("An error occurred during mbean server un-registration. This exception will be ignored.", e);
}
}
}
public void destroy(Container container) {
if (container.getParent() != null) {
destroyChild(container.getParent(), container.getId());
} else {
throw new UnsupportedOperationException();
}
}
private void destroyChild(final Container parent, final String name) {
getContainerTemplate(parent).execute(new ContainerTemplate.AdminServiceCallback<Object>() {
public Object doWithAdminService(AdminServiceMBean adminService) throws Exception {
adminService.stopInstance(name);
adminService.destroyInstance(name);
zooKeeper.deleteWithChildren(ZkPath.CONFIG_CONTAINER.getPath(name));
return null;
}
});
}
public String getZookeeperUrl() {
String zooKeeperUrl = null;
try {
Configuration config = configurationAdmin.getConfiguration("org.fusesource.fabric.zookeeper", null);
zooKeeperUrl = (String) config.getProperties().get("zookeeper.url");
} catch (Exception e) {
//Ignore it.
}
return zooKeeperUrl;
}
private void createContainerConfig(String parent, String name) {
try {
String configVersion = getDefaultVersion().getName();
ZooKeeperUtils.createDefault(zooKeeper, ZkPath.CONFIG_CONTAINER.getPath(name), configVersion);
ZooKeeperUtils.createDefault(zooKeeper, ZkPath.CONFIG_VERSIONS_CONTAINER.getPath(configVersion, name), profile);
zooKeeper.createOrSetWithParents(CONTAINER_PARENT.getPath(name), parent, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
} catch (FabricException e) {
throw e;
} catch (Exception e) {
throw new FabricException(e);
}
}
@Override
public Version getDefaultVersion() {
try {
String version = null;
if (zooKeeper.exists(ZkPath.CONFIG_DEFAULT_VERSION.getPath()) != null) {
version = zooKeeper.getStringData(ZkPath.CONFIG_DEFAULT_VERSION.getPath());
}
if (version == null || version.isEmpty()) {
version = ZkDefs.DEFAULT_VERSION;
ZooKeeperUtils.createDefault(zooKeeper, ZkPath.CONFIG_DEFAULT_VERSION.getPath(), version);
ZooKeeperUtils.createDefault(zooKeeper, ZkPath.CONFIG_VERSION.getPath(version), null);
}
return new VersionImpl(version, this);
} catch (Exception e) {
throw new FabricException(e);
}
}
@Override
public void setDefaultVersion(Version version) {
try {
ZooKeeperUtils.set(zooKeeper, ZkPath.CONFIG_DEFAULT_VERSION.getPath(), version.getName());
} catch (Exception e) {
throw new FabricException(e);
}
}
public Version createVersion(String version) {
try {
zooKeeper.createWithParents(ZkPath.CONFIG_VERSION.getPath(version), null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
zooKeeper.createWithParents(ZkPath.CONFIG_VERSIONS_PROFILES.getPath(version), null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
return new VersionImpl(version, this);
} catch (Exception e) {
throw new FabricException(e);
}
}
public Version createVersion(Version parent, String toVersion) {
try {
ZooKeeperUtils.copy(zooKeeper, ZkPath.CONFIG_VERSION.getPath(parent.getName()), ZkPath.CONFIG_VERSION.getPath(toVersion));
return new VersionImpl(toVersion, this);
} catch (Exception e) {
throw new FabricException(e);
}
}
public void deleteVersion(String version) {
try {
zooKeeper.deleteWithChildren(ZkPath.CONFIG_VERSION.getPath(version));
} catch (Exception e) {
throw new FabricException(e);
}
}
public Version[] getVersions() {
try {
List<Version> versions = new ArrayList<Version>();
List<String> children = zooKeeper.getChildren(ZkPath.CONFIG_VERSIONS.getPath());
for (String child : children) {
versions.add(new VersionImpl(child, this));
}
Collections.sort(versions);
return versions.toArray(new Version[versions.size()]);
} catch (Exception e) {
throw new FabricException(e);
}
}
public Version getVersion(String name) {
try {
if (zooKeeper != null && zooKeeper.isConnected() && zooKeeper.exists(ZkPath.CONFIG_VERSION.getPath(name)) == null) {
throw new FabricException("Version '" + name + "' does not exist!");
}
return new VersionImpl(name, this);
} catch (FabricException e) {
throw e;
} catch (Exception e) {
throw new FabricException(e);
}
}
@Override
public Profile[] getProfiles(String version) {
try {
List<String> names = zooKeeper.getChildren(ZkPath.CONFIG_VERSIONS_PROFILES.getPath(version));
List<Profile> profiles = new ArrayList<Profile>();
for (String name : names) {
profiles.add(new ProfileImpl(name, version, this));
}
return profiles.toArray(new Profile[profiles.size()]);
} catch (Exception e) {
throw new FabricException(e);
}
}
@Override
public Profile getProfile(String version, String name) {
try {
String path = ZkPath.CONFIG_VERSIONS_PROFILE.getPath(version, name);
if (zooKeeper.exists(path) == null) {
return null;
}
return new ProfileImpl(name, version, this);
} catch (Exception e) {
throw new FabricException(e);
}
}
@Override
public Profile createProfile(String version, String name) {
try {
ZooKeeperUtils.create(zooKeeper, ZkPath.CONFIG_VERSIONS_PROFILE.getPath(version, name));
return new ProfileImpl(name, version, this);
} catch (Exception e) {
throw new FabricException(e);
}
}
@Override
public void deleteProfile(Profile profile) {
try {
zooKeeper.deleteWithChildren(ZkPath.CONFIG_VERSIONS_PROFILE.getPath(profile.getVersion(), profile.getId()));
} catch (Exception e) {
throw new FabricException(e);
}
}
protected ContainerTemplate getContainerTemplate(Container container) {
// there's no point caching the JMX Connector as we are unsure if we'll communicate again with the same container any time soon
// though in the future we could possibly pool them
boolean cacheJmx = false;
return new ContainerTemplate(container, cacheJmx, userName, password);
}
}
| true | true | public Container[] createContainers(final CreateContainerOptions options) {
Container[] containers = new Container[options.getNumber()];
if (options.getZookeeperUrl() == null && !options.isDebugContainer()) {
options.setZookeeperUrl(getZookeeperUrl());
}
if (options.getProxyUri() == null) {
options.setProxyUri(getMavenRepoURI());
}
try {
ContainerProvider provider = getProvider(options.getProviderType());
if (provider == null) {
throw new FabricException("Unable to find an container provider type '" + options.getProviderType() + "'");
}
Set<? extends CreateContainerMetadata> createMetadata = new LinkedHashSet<CreateContainerMetadata>();
String parent = options.getParent() != null ? options.getParent() : "";
Container parentContainer = null;
if (provider instanceof ChildContainerProvider && !getCurrentContainer().getId().equals(parent)) {
createMetadata = createChildContainer((CreateContainerChildOptions) options);
} else {
createMetadata = provider.create(options);
}
containers = new Container[createMetadata.size()];
int container = 0;
for(CreateContainerMetadata metadata : createMetadata) {
//An ensemble server can be created without an existing ensemble.
//In this case container config will be created by the newly created container.
if (!options.isEnsembleServer()) {
createContainerConfig(parent, metadata.getContainerName());
}
containers[container] = new ContainerImpl(parentContainer, metadata.getContainerName(), FabricServiceImpl.this);
containers[container++].setCreateContainerMetadata(metadata);
}
} catch (FabricException e) {
throw e;
} catch (Exception e) {
throw new FabricException(e);
}
return containers;
}
| public Container[] createContainers(final CreateContainerOptions options) {
Container[] containers = new Container[options.getNumber()];
if (options.getZookeeperUrl() == null && !options.isDebugContainer()) {
options.setZookeeperUrl(getZookeeperUrl());
}
if (options.getProxyUri() == null) {
options.setProxyUri(getMavenRepoURI());
}
try {
ContainerProvider provider = getProvider(options.getProviderType());
if (provider == null) {
throw new FabricException("Unable to find an container provider type '" + options.getProviderType() + "'");
}
Set<? extends CreateContainerMetadata> createMetadata = new LinkedHashSet<CreateContainerMetadata>();
String parent = options.getParent() != null ? options.getParent() : "";
Container parentContainer = null;
String currentID = "";
Container currentContainer = getCurrentContainer();
if (currentContainer != null) {
currentID = currentContainer.getId();
}
if (provider instanceof ChildContainerProvider && !parent.equals(currentID)) {
createMetadata = createChildContainer(options);
} else {
createMetadata = provider.create(options);
}
containers = new Container[createMetadata.size()];
int container = 0;
for(CreateContainerMetadata metadata : createMetadata) {
//An ensemble server can be created without an existing ensemble.
//In this case container config will be created by the newly created container.
if (!options.isEnsembleServer()) {
createContainerConfig(parent, metadata.getContainerName());
}
containers[container] = new ContainerImpl(parentContainer, metadata.getContainerName(), FabricServiceImpl.this);
containers[container++].setCreateContainerMetadata(metadata);
}
} catch (FabricException e) {
throw e;
} catch (Exception e) {
throw new FabricException(e);
}
return containers;
}
|
diff --git a/client/ui/src/main/java/de/objectcode/time4u/client/ui/preferences/UIPreferencesPage.java b/client/ui/src/main/java/de/objectcode/time4u/client/ui/preferences/UIPreferencesPage.java
index aa2b3327..1f1946b1 100644
--- a/client/ui/src/main/java/de/objectcode/time4u/client/ui/preferences/UIPreferencesPage.java
+++ b/client/ui/src/main/java/de/objectcode/time4u/client/ui/preferences/UIPreferencesPage.java
@@ -1,29 +1,29 @@
package de.objectcode.time4u.client.ui.preferences;
import org.eclipse.jface.preference.BooleanFieldEditor;
import org.eclipse.jface.preference.FieldEditorPreferencePage;
import org.eclipse.jface.preference.IntegerFieldEditor;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
import de.objectcode.time4u.client.ui.UIPlugin;
public class UIPreferencesPage extends FieldEditorPreferencePage implements IWorkbenchPreferencePage
{
public void init(final IWorkbench workbench)
{
setPreferenceStore(UIPlugin.getDefault().getPreferenceStore());
}
@Override
protected void createFieldEditors()
{
addField(new BooleanFieldEditor(PreferenceConstants.UI_SHOW_TRAY_ICON, "Show &Tray icon", getFieldEditorParent()));
final IntegerFieldEditor taskHistory = new IntegerFieldEditor(PreferenceConstants.UI_TASK_HISTORY_SIZE,
- "&Task histroy size", getFieldEditorParent());
+ "&Task history size", getFieldEditorParent());
taskHistory.setValidRange(0, 30);
addField(taskHistory);
}
}
| true | true | protected void createFieldEditors()
{
addField(new BooleanFieldEditor(PreferenceConstants.UI_SHOW_TRAY_ICON, "Show &Tray icon", getFieldEditorParent()));
final IntegerFieldEditor taskHistory = new IntegerFieldEditor(PreferenceConstants.UI_TASK_HISTORY_SIZE,
"&Task histroy size", getFieldEditorParent());
taskHistory.setValidRange(0, 30);
addField(taskHistory);
}
| protected void createFieldEditors()
{
addField(new BooleanFieldEditor(PreferenceConstants.UI_SHOW_TRAY_ICON, "Show &Tray icon", getFieldEditorParent()));
final IntegerFieldEditor taskHistory = new IntegerFieldEditor(PreferenceConstants.UI_TASK_HISTORY_SIZE,
"&Task history size", getFieldEditorParent());
taskHistory.setValidRange(0, 30);
addField(taskHistory);
}
|
diff --git a/biz.aQute.bndlib/src/aQute/lib/osgi/CommandResource.java b/biz.aQute.bndlib/src/aQute/lib/osgi/CommandResource.java
index 3c30308ee..c9e3c8a4f 100644
--- a/biz.aQute.bndlib/src/aQute/lib/osgi/CommandResource.java
+++ b/biz.aQute.bndlib/src/aQute/lib/osgi/CommandResource.java
@@ -1,67 +1,69 @@
/*
* Copyright (c) OSGi Alliance (2012). All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package aQute.lib.osgi;
import java.io.*;
import aQute.libg.command.*;
public class CommandResource extends WriteResource {
final long lastModified;
final Builder domain;
final String command;
public CommandResource(String command, Builder domain, long lastModified) {
this.lastModified = lastModified;
this.domain = domain;
this.command = command;
}
@Override
public void write(OutputStream out) throws IOException, Exception {
StringBuilder errors = new StringBuilder();
StringBuilder stdout = new StringBuilder();
try {
+ domain.trace("executing command %s", command);
Command cmd = new Command("sh -l");
cmd.inherit();
String oldpath = cmd.var("PATH");
- String path = domain.getProperty("PATH");
+ String path = domain.getProperty("-PATH");
if (path != null) {
path = path.replaceAll("\\s*,\\s*",File.pathSeparator);
- path.replaceAll("\\$\\{@\\}", oldpath);
+ path = path.replaceAll("\\$\\{@\\}", oldpath);
cmd.var("PATH", path);
+ domain.trace("PATH: %s", path);
}
OutputStreamWriter osw = new OutputStreamWriter(out);
int result = cmd.execute(command,stdout, errors);
osw.append(stdout);
osw.flush();
if ( result != 0) {
- domain.error("Failed to create resource from system command %s, error %s: %s", command, result, errors);
+ domain.error("executing command failed %s %s", command, stdout + "\n" + errors);
}
} catch( Exception e) {
- domain.error("Failed to create resource from system command %s, error %s: %s", command, e.getMessage(), errors);
+ domain.error("executing command failed %s %s", command, e.getMessage());
}
}
@Override
public long lastModified() {
return lastModified;
}
}
| false | true | public void write(OutputStream out) throws IOException, Exception {
StringBuilder errors = new StringBuilder();
StringBuilder stdout = new StringBuilder();
try {
Command cmd = new Command("sh -l");
cmd.inherit();
String oldpath = cmd.var("PATH");
String path = domain.getProperty("PATH");
if (path != null) {
path = path.replaceAll("\\s*,\\s*",File.pathSeparator);
path.replaceAll("\\$\\{@\\}", oldpath);
cmd.var("PATH", path);
}
OutputStreamWriter osw = new OutputStreamWriter(out);
int result = cmd.execute(command,stdout, errors);
osw.append(stdout);
osw.flush();
if ( result != 0) {
domain.error("Failed to create resource from system command %s, error %s: %s", command, result, errors);
}
} catch( Exception e) {
domain.error("Failed to create resource from system command %s, error %s: %s", command, e.getMessage(), errors);
}
}
| public void write(OutputStream out) throws IOException, Exception {
StringBuilder errors = new StringBuilder();
StringBuilder stdout = new StringBuilder();
try {
domain.trace("executing command %s", command);
Command cmd = new Command("sh -l");
cmd.inherit();
String oldpath = cmd.var("PATH");
String path = domain.getProperty("-PATH");
if (path != null) {
path = path.replaceAll("\\s*,\\s*",File.pathSeparator);
path = path.replaceAll("\\$\\{@\\}", oldpath);
cmd.var("PATH", path);
domain.trace("PATH: %s", path);
}
OutputStreamWriter osw = new OutputStreamWriter(out);
int result = cmd.execute(command,stdout, errors);
osw.append(stdout);
osw.flush();
if ( result != 0) {
domain.error("executing command failed %s %s", command, stdout + "\n" + errors);
}
} catch( Exception e) {
domain.error("executing command failed %s %s", command, e.getMessage());
}
}
|
diff --git a/maven-core-integration-tests/src/test/java/org/apache/maven/integrationtests/MavenIT0079Test.java b/maven-core-integration-tests/src/test/java/org/apache/maven/integrationtests/MavenIT0079Test.java
index 7c7233752..2fd8bf82b 100644
--- a/maven-core-integration-tests/src/test/java/org/apache/maven/integrationtests/MavenIT0079Test.java
+++ b/maven-core-integration-tests/src/test/java/org/apache/maven/integrationtests/MavenIT0079Test.java
@@ -1,30 +1,30 @@
package org.apache.maven.integrationtests;
import junit.framework.TestCase;
import org.apache.maven.it.Verifier;
import org.apache.maven.it.util.ResourceExtractor;
import java.io.File;
public class MavenIT0079Test
extends TestCase /*extends AbstractMavenIntegrationTest*/
{
/**
* Test that source attachments have the same build number as the main
* artifact when deployed.
*/
public void testit0079()
throws Exception
{
File testDir = ResourceExtractor.simpleExtractResources( getClass(), "/it0079" );
Verifier verifier = new Verifier( testDir.getAbsolutePath() );
verifier.executeGoal( "deploy" );
- verifier.assertFilePresent( "target/test-repo/org/apache/maven/it/maven-it-it0079/SNAPSHOT/maven-it-it0079-*-1.jar" );
- verifier.assertFilePresent( "target/test-repo/org/apache/maven/it/maven-it-it0079/SNAPSHOT/maven-it-it0079-*-1-sources.jar" );
+ verifier.assertFilePresent( "target/test-repo/org/apache/maven/its/it0079/maven-it-it0079/SNAPSHOT/maven-it-it0079-*-1.jar" );
+ verifier.assertFilePresent( "target/test-repo/org/apache/maven/its/it0079/maven-it-it0079/SNAPSHOT/maven-it-it0079-*-1-sources.jar" );
verifier.verifyErrorFreeLog();
verifier.resetStreams();
System.out.println( "it0079 PASS" );
}
}
| true | true | public void testit0079()
throws Exception
{
File testDir = ResourceExtractor.simpleExtractResources( getClass(), "/it0079" );
Verifier verifier = new Verifier( testDir.getAbsolutePath() );
verifier.executeGoal( "deploy" );
verifier.assertFilePresent( "target/test-repo/org/apache/maven/it/maven-it-it0079/SNAPSHOT/maven-it-it0079-*-1.jar" );
verifier.assertFilePresent( "target/test-repo/org/apache/maven/it/maven-it-it0079/SNAPSHOT/maven-it-it0079-*-1-sources.jar" );
verifier.verifyErrorFreeLog();
verifier.resetStreams();
System.out.println( "it0079 PASS" );
}
| public void testit0079()
throws Exception
{
File testDir = ResourceExtractor.simpleExtractResources( getClass(), "/it0079" );
Verifier verifier = new Verifier( testDir.getAbsolutePath() );
verifier.executeGoal( "deploy" );
verifier.assertFilePresent( "target/test-repo/org/apache/maven/its/it0079/maven-it-it0079/SNAPSHOT/maven-it-it0079-*-1.jar" );
verifier.assertFilePresent( "target/test-repo/org/apache/maven/its/it0079/maven-it-it0079/SNAPSHOT/maven-it-it0079-*-1-sources.jar" );
verifier.verifyErrorFreeLog();
verifier.resetStreams();
System.out.println( "it0079 PASS" );
}
|
diff --git a/test/src/org/bouncycastle/jce/provider/test/AlgorithmParametersTest.java b/test/src/org/bouncycastle/jce/provider/test/AlgorithmParametersTest.java
index c616c3e8..72f38854 100644
--- a/test/src/org/bouncycastle/jce/provider/test/AlgorithmParametersTest.java
+++ b/test/src/org/bouncycastle/jce/provider/test/AlgorithmParametersTest.java
@@ -1,110 +1,110 @@
package org.bouncycastle.jce.provider.test;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Base64;
import org.bouncycastle.util.test.SimpleTest;
import java.io.IOException;
import java.security.AlgorithmParameters;
import java.security.Security;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.DSAParameterSpec;
import java.security.spec.InvalidParameterSpecException;
public class AlgorithmParametersTest
extends SimpleTest
{
private byte[] dsaParams = Base64.decode(
"MIGcAkEAjfKklEkidqo9JXWbsGhpy+rA2Dr7jQz3y7gyTw14guXQdi/FtyEOr8Lprawyq3qsSWk9+/g3J"
+ "MLsBzbuMcgCkQIVAMdzIYxzfsjumTtPLe0w9I7azpFfAkBP3Z9K7oNeZMXEXYpqvrMUgVdFjq4lnWJoV8"
+ "Rwe+TERStHTkqSO7sp0lq7EEggVMcuXtarKNsxaJ+qyYv/n1t6");
private void basicTest(String algorithm, Class algorithmParameterSpec, byte[] asn1Encoded)
throws Exception
{
AlgorithmParameters alg = AlgorithmParameters.getInstance(algorithm, "BC");
alg.init(asn1Encoded);
try
{
alg.init(asn1Encoded);
fail("encoded re-initialization not detected");
}
catch (IOException e)
{
// expected already initialized
}
AlgorithmParameterSpec spec = alg.getParameterSpec(algorithmParameterSpec);
try
{
alg.init(spec);
fail("spec re-initialization not detected");
}
catch (InvalidParameterSpecException e)
{
// expected already initialized
}
try
{
spec = alg.getParameterSpec(AlgorithmParameterSpec.class);
fail("wrong spec not detected");
}
catch (InvalidParameterSpecException e)
{
// expected unknown object
}
try
{
spec = alg.getParameterSpec(null);
fail("null spec not detected");
}
- catch (InvalidParameterSpecException e)
+ catch (NullPointerException e)
{
// expected unknown object
}
alg = AlgorithmParameters.getInstance(algorithm, "BC");
alg.init(asn1Encoded, "ASN.1");
alg = AlgorithmParameters.getInstance(algorithm, "BC");
alg.init(asn1Encoded, null);
alg = AlgorithmParameters.getInstance(algorithm, "BC");
try
{
alg.init(asn1Encoded, "FRED");
fail("unknown spec not detected");
}
catch (IOException e)
{
// expected already initialized
}
}
public void performTest()
throws Exception
{
basicTest("DSA", DSAParameterSpec.class, dsaParams);
}
public String getName()
{
return "AlgorithmParameters";
}
public static void main(
String[] args)
{
Security.addProvider(new BouncyCastleProvider());
runTest(new AlgorithmParametersTest());
}
}
| true | true | private void basicTest(String algorithm, Class algorithmParameterSpec, byte[] asn1Encoded)
throws Exception
{
AlgorithmParameters alg = AlgorithmParameters.getInstance(algorithm, "BC");
alg.init(asn1Encoded);
try
{
alg.init(asn1Encoded);
fail("encoded re-initialization not detected");
}
catch (IOException e)
{
// expected already initialized
}
AlgorithmParameterSpec spec = alg.getParameterSpec(algorithmParameterSpec);
try
{
alg.init(spec);
fail("spec re-initialization not detected");
}
catch (InvalidParameterSpecException e)
{
// expected already initialized
}
try
{
spec = alg.getParameterSpec(AlgorithmParameterSpec.class);
fail("wrong spec not detected");
}
catch (InvalidParameterSpecException e)
{
// expected unknown object
}
try
{
spec = alg.getParameterSpec(null);
fail("null spec not detected");
}
catch (InvalidParameterSpecException e)
{
// expected unknown object
}
alg = AlgorithmParameters.getInstance(algorithm, "BC");
alg.init(asn1Encoded, "ASN.1");
alg = AlgorithmParameters.getInstance(algorithm, "BC");
alg.init(asn1Encoded, null);
alg = AlgorithmParameters.getInstance(algorithm, "BC");
try
{
alg.init(asn1Encoded, "FRED");
fail("unknown spec not detected");
}
catch (IOException e)
{
// expected already initialized
}
}
| private void basicTest(String algorithm, Class algorithmParameterSpec, byte[] asn1Encoded)
throws Exception
{
AlgorithmParameters alg = AlgorithmParameters.getInstance(algorithm, "BC");
alg.init(asn1Encoded);
try
{
alg.init(asn1Encoded);
fail("encoded re-initialization not detected");
}
catch (IOException e)
{
// expected already initialized
}
AlgorithmParameterSpec spec = alg.getParameterSpec(algorithmParameterSpec);
try
{
alg.init(spec);
fail("spec re-initialization not detected");
}
catch (InvalidParameterSpecException e)
{
// expected already initialized
}
try
{
spec = alg.getParameterSpec(AlgorithmParameterSpec.class);
fail("wrong spec not detected");
}
catch (InvalidParameterSpecException e)
{
// expected unknown object
}
try
{
spec = alg.getParameterSpec(null);
fail("null spec not detected");
}
catch (NullPointerException e)
{
// expected unknown object
}
alg = AlgorithmParameters.getInstance(algorithm, "BC");
alg.init(asn1Encoded, "ASN.1");
alg = AlgorithmParameters.getInstance(algorithm, "BC");
alg.init(asn1Encoded, null);
alg = AlgorithmParameters.getInstance(algorithm, "BC");
try
{
alg.init(asn1Encoded, "FRED");
fail("unknown spec not detected");
}
catch (IOException e)
{
// expected already initialized
}
}
|
diff --git a/src/main/javassist/bytecode/CodeAttribute.java b/src/main/javassist/bytecode/CodeAttribute.java
index 5a423ef..35ab7dd 100644
--- a/src/main/javassist/bytecode/CodeAttribute.java
+++ b/src/main/javassist/bytecode/CodeAttribute.java
@@ -1,417 +1,419 @@
/*
* Javassist, a Java-bytecode translator toolkit.
* Copyright (C) 1999-2007 Shigeru Chiba. All Rights Reserved.
*
* 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. Alternatively, the contents of this file may be used under
* the terms of the GNU Lesser General Public License Version 2.1 or later.
*
* 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.
*/
package javassist.bytecode;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.LinkedList;
import java.util.Map;
/**
* <code>Code_attribute</code>.
*
* <p>To browse the <code>code</code> field of
* a <code>Code_attribute</code> structure,
* use <code>CodeIterator</code>.
*
* @see CodeIterator
*/
public class CodeAttribute extends AttributeInfo implements Opcode {
/**
* The name of this attribute <code>"Code"</code>.
*/
public static final String tag = "Code";
// code[] is stored in AttributeInfo.info.
private int maxStack;
private int maxLocals;
private ExceptionTable exceptions;
private LinkedList attributes;
/**
* Constructs a <code>Code_attribute</code>.
*
* @param cp constant pool table
* @param stack <code>max_stack</code>
* @param locals <code>max_locals</code>
* @param code <code>code[]</code>
* @param etable <code>exception_table[]</code>
*/
public CodeAttribute(ConstPool cp, int stack, int locals, byte[] code,
ExceptionTable etable)
{
super(cp, tag);
maxStack = stack;
maxLocals = locals;
info = code;
exceptions = etable;
attributes = new LinkedList();
}
/**
* Constructs a copy of <code>Code_attribute</code>.
* Specified class names are replaced during the copy.
*
* @param cp constant pool table.
* @param src source Code attribute.
* @param classnames pairs of replaced and substituted
* class names.
*/
private CodeAttribute(ConstPool cp, CodeAttribute src, Map classnames)
throws BadBytecode
{
super(cp, tag);
maxStack = src.getMaxStack();
maxLocals = src.getMaxLocals();
exceptions = src.getExceptionTable().copy(cp, classnames);
info = src.copyCode(cp, classnames, exceptions, this);
attributes = new LinkedList();
List src_attr = src.getAttributes();
int num = src_attr.size();
for (int i = 0; i < num; ++i) {
AttributeInfo ai = (AttributeInfo)src_attr.get(i);
attributes.add(ai.copy(cp, classnames));
}
}
CodeAttribute(ConstPool cp, int name_id, DataInputStream in)
throws IOException
{
super(cp, name_id, (byte[])null);
int attr_len = in.readInt();
maxStack = in.readUnsignedShort();
maxLocals = in.readUnsignedShort();
int code_len = in.readInt();
info = new byte[code_len];
in.readFully(info);
exceptions = new ExceptionTable(cp, in);
attributes = new LinkedList();
int num = in.readUnsignedShort();
for (int i = 0; i < num; ++i)
attributes.add(AttributeInfo.read(cp, in));
}
/**
* Makes a copy. Class names are replaced according to the
* given <code>Map</code> object.
*
* @param newCp the constant pool table used by the new copy.
* @param classnames pairs of replaced and substituted
* class names.
* @exception RuntimeCopyException if a <code>BadBytecode</code>
* exception is thrown, it is
* converted into
* <code>RuntimeCopyException</code>.
*
* @return <code>CodeAttribute</code> object.
*/
public AttributeInfo copy(ConstPool newCp, Map classnames)
throws RuntimeCopyException
{
try {
return new CodeAttribute(newCp, this, classnames);
}
catch (BadBytecode e) {
throw new RuntimeCopyException("bad bytecode. fatal?");
}
}
/**
* An exception that may be thrown by <code>copy()</code>
* in <code>CodeAttribute</code>.
*/
public static class RuntimeCopyException extends RuntimeException {
/**
* Constructs an exception.
*/
public RuntimeCopyException(String s) {
super(s);
}
}
/**
* Returns the length of this <code>attribute_info</code>
* structure.
* The returned value is <code>attribute_length + 6</code>.
*/
public int length() {
return 18 + info.length + exceptions.size() * 8
+ AttributeInfo.getLength(attributes);
}
void write(DataOutputStream out) throws IOException {
out.writeShort(name); // attribute_name_index
out.writeInt(length() - 6); // attribute_length
out.writeShort(maxStack); // max_stack
out.writeShort(maxLocals); // max_locals
out.writeInt(info.length); // code_length
out.write(info); // code
exceptions.write(out);
out.writeShort(attributes.size()); // attributes_count
AttributeInfo.writeAll(attributes, out); // attributes
}
/**
* This method is not available.
*
* @throws java.lang.UnsupportedOperationException always thrown.
*/
public byte[] get() {
throw new UnsupportedOperationException("CodeAttribute.get()");
}
/**
* This method is not available.
*
* @throws java.lang.UnsupportedOperationException always thrown.
*/
public void set(byte[] newinfo) {
throw new UnsupportedOperationException("CodeAttribute.set()");
}
/**
* Returns the name of the class declaring the method including
* this code attribute.
*/
public String getDeclaringClass() {
ConstPool cp = getConstPool();
return cp.getClassName();
}
/**
* Returns <code>max_stack</code>.
*/
public int getMaxStack() {
return maxStack;
}
/**
* Sets <code>max_stack</code>.
*/
public void setMaxStack(int value) {
maxStack = value;
}
/**
* Computes the maximum stack size and sets <code>max_stack</code>
* to the computed size.
*
* @throws BadBytecode if this method fails in computing.
* @return the newly computed value of <code>max_stack</code>
*/
public int computeMaxStack() throws BadBytecode {
maxStack = new CodeAnalyzer(this).computeMaxStack();
return maxStack;
}
/**
* Returns <code>max_locals</code>.
*/
public int getMaxLocals() {
return maxLocals;
}
/**
* Sets <code>max_locals</code>.
*/
public void setMaxLocals(int value) {
maxLocals = value;
}
/**
* Returns <code>code_length</code>.
*/
public int getCodeLength() {
return info.length;
}
/**
* Returns <code>code[]</code>.
*/
public byte[] getCode() {
return info;
}
/**
* Sets <code>code[]</code>.
*/
void setCode(byte[] newinfo) { super.set(newinfo); }
/**
* Makes a new iterator for reading this code attribute.
*/
public CodeIterator iterator() {
return new CodeIterator(this);
}
/**
* Returns <code>exception_table[]</code>.
*/
public ExceptionTable getExceptionTable() { return exceptions; }
/**
* Returns <code>attributes[]</code>.
* It returns a list of <code>AttributeInfo</code>.
* A new element can be added to the returned list
* and an existing element can be removed from the list.
*
* @see AttributeInfo
*/
public List getAttributes() { return attributes; }
/**
* Returns the attribute with the specified name.
* If it is not found, this method returns null.
*
* @param name attribute name
* @return an <code>AttributeInfo</code> object or null.
*/
public AttributeInfo getAttribute(String name) {
return AttributeInfo.lookup(attributes, name);
}
/**
* Adds a stack map table. If another copy of stack map table
* is already contained, the old one is removed.
*
* @param smt the stack map table added to this code attribute.
* If it is null, a new stack map is not added.
* Only the old stack map is removed.
*/
public void setAttribute(StackMapTable smt) {
AttributeInfo.remove(attributes, StackMapTable.tag);
if (smt != null)
attributes.add(smt);
}
/**
* Copies code.
*/
private byte[] copyCode(ConstPool destCp, Map classnames,
ExceptionTable etable, CodeAttribute destCa)
throws BadBytecode
{
int len = getCodeLength();
byte[] newCode = new byte[len];
LdcEntry ldc = copyCode(this.info, 0, len, this.getConstPool(),
newCode, destCp, classnames);
return LdcEntry.doit(newCode, ldc, etable, destCa);
}
private static LdcEntry copyCode(byte[] code, int beginPos, int endPos,
ConstPool srcCp, byte[] newcode,
ConstPool destCp, Map classnameMap)
throws BadBytecode
{
int i2, index;
LdcEntry ldcEntry = null;
for (int i = beginPos; i < endPos; i = i2) {
i2 = CodeIterator.nextOpcode(code, i);
byte c = code[i];
newcode[i] = c;
switch (c & 0xff) {
case LDC_W :
case LDC2_W :
case GETSTATIC :
case PUTSTATIC :
case GETFIELD :
case PUTFIELD :
case INVOKEVIRTUAL :
case INVOKESPECIAL :
case INVOKESTATIC :
case NEW :
case ANEWARRAY :
case CHECKCAST :
case INSTANCEOF :
copyConstPoolInfo(i + 1, code, srcCp, newcode, destCp,
classnameMap);
break;
case LDC :
index = code[i + 1] & 0xff;
index = srcCp.copy(index, destCp, classnameMap);
if (index < 0x100)
newcode[i + 1] = (byte)index;
else {
+ newcode[i] = NOP;
+ newcode[i + 1] = NOP;
LdcEntry ldc = new LdcEntry();
ldc.where = i;
ldc.index = index;
ldc.next = ldcEntry;
ldcEntry = ldc;
}
break;
case INVOKEINTERFACE :
copyConstPoolInfo(i + 1, code, srcCp, newcode, destCp,
classnameMap);
newcode[i + 3] = code[i + 3];
newcode[i + 4] = code[i + 4];
break;
case MULTIANEWARRAY :
copyConstPoolInfo(i + 1, code, srcCp, newcode, destCp,
classnameMap);
newcode[i + 3] = code[i + 3];
break;
default :
while (++i < i2)
newcode[i] = code[i];
break;
}
}
return ldcEntry;
}
private static void copyConstPoolInfo(int i, byte[] code, ConstPool srcCp,
byte[] newcode, ConstPool destCp,
Map classnameMap) {
int index = ((code[i] & 0xff) << 8) | (code[i + 1] & 0xff);
index = srcCp.copy(index, destCp, classnameMap);
newcode[i] = (byte)(index >> 8);
newcode[i + 1] = (byte)index;
}
}
final class LdcEntry {
LdcEntry next;
int where;
int index;
static byte[] doit(byte[] code, LdcEntry ldc, ExceptionTable etable,
CodeAttribute ca)
throws BadBytecode
{
while (ldc != null) {
int where = ldc.where;
code = CodeIterator.insertGap(code, where, 1, false, etable, ca);
code[where] = (byte)Opcode.LDC_W;
ByteArray.write16bit(ldc.index, code, where + 1);
ldc = ldc.next;
}
return code;
}
}
| true | true | private static LdcEntry copyCode(byte[] code, int beginPos, int endPos,
ConstPool srcCp, byte[] newcode,
ConstPool destCp, Map classnameMap)
throws BadBytecode
{
int i2, index;
LdcEntry ldcEntry = null;
for (int i = beginPos; i < endPos; i = i2) {
i2 = CodeIterator.nextOpcode(code, i);
byte c = code[i];
newcode[i] = c;
switch (c & 0xff) {
case LDC_W :
case LDC2_W :
case GETSTATIC :
case PUTSTATIC :
case GETFIELD :
case PUTFIELD :
case INVOKEVIRTUAL :
case INVOKESPECIAL :
case INVOKESTATIC :
case NEW :
case ANEWARRAY :
case CHECKCAST :
case INSTANCEOF :
copyConstPoolInfo(i + 1, code, srcCp, newcode, destCp,
classnameMap);
break;
case LDC :
index = code[i + 1] & 0xff;
index = srcCp.copy(index, destCp, classnameMap);
if (index < 0x100)
newcode[i + 1] = (byte)index;
else {
LdcEntry ldc = new LdcEntry();
ldc.where = i;
ldc.index = index;
ldc.next = ldcEntry;
ldcEntry = ldc;
}
break;
case INVOKEINTERFACE :
copyConstPoolInfo(i + 1, code, srcCp, newcode, destCp,
classnameMap);
newcode[i + 3] = code[i + 3];
newcode[i + 4] = code[i + 4];
break;
case MULTIANEWARRAY :
copyConstPoolInfo(i + 1, code, srcCp, newcode, destCp,
classnameMap);
newcode[i + 3] = code[i + 3];
break;
default :
while (++i < i2)
newcode[i] = code[i];
break;
}
}
return ldcEntry;
}
| private static LdcEntry copyCode(byte[] code, int beginPos, int endPos,
ConstPool srcCp, byte[] newcode,
ConstPool destCp, Map classnameMap)
throws BadBytecode
{
int i2, index;
LdcEntry ldcEntry = null;
for (int i = beginPos; i < endPos; i = i2) {
i2 = CodeIterator.nextOpcode(code, i);
byte c = code[i];
newcode[i] = c;
switch (c & 0xff) {
case LDC_W :
case LDC2_W :
case GETSTATIC :
case PUTSTATIC :
case GETFIELD :
case PUTFIELD :
case INVOKEVIRTUAL :
case INVOKESPECIAL :
case INVOKESTATIC :
case NEW :
case ANEWARRAY :
case CHECKCAST :
case INSTANCEOF :
copyConstPoolInfo(i + 1, code, srcCp, newcode, destCp,
classnameMap);
break;
case LDC :
index = code[i + 1] & 0xff;
index = srcCp.copy(index, destCp, classnameMap);
if (index < 0x100)
newcode[i + 1] = (byte)index;
else {
newcode[i] = NOP;
newcode[i + 1] = NOP;
LdcEntry ldc = new LdcEntry();
ldc.where = i;
ldc.index = index;
ldc.next = ldcEntry;
ldcEntry = ldc;
}
break;
case INVOKEINTERFACE :
copyConstPoolInfo(i + 1, code, srcCp, newcode, destCp,
classnameMap);
newcode[i + 3] = code[i + 3];
newcode[i + 4] = code[i + 4];
break;
case MULTIANEWARRAY :
copyConstPoolInfo(i + 1, code, srcCp, newcode, destCp,
classnameMap);
newcode[i + 3] = code[i + 3];
break;
default :
while (++i < i2)
newcode[i] = code[i];
break;
}
}
return ldcEntry;
}
|
diff --git a/ttools/src/main/uk/ac/starlink/ttools/taplint/VotLintTapRunner.java b/ttools/src/main/uk/ac/starlink/ttools/taplint/VotLintTapRunner.java
index aef13e207..eaadda64a 100644
--- a/ttools/src/main/uk/ac/starlink/ttools/taplint/VotLintTapRunner.java
+++ b/ttools/src/main/uk/ac/starlink/ttools/taplint/VotLintTapRunner.java
@@ -1,543 +1,543 @@
package uk.ac.starlink.ttools.taplint;
import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.ContentHandler;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;
import org.w3c.dom.Node;
import uk.ac.starlink.table.DefaultValueInfo;
import uk.ac.starlink.table.DescribedValue;
import uk.ac.starlink.table.StarTable;
import uk.ac.starlink.table.StoragePolicy;
import uk.ac.starlink.table.ValueInfo;
import uk.ac.starlink.ttools.votlint.VotableVersion;
import uk.ac.starlink.ttools.votlint.VotLintContentHandler;
import uk.ac.starlink.ttools.votlint.VotLintContext;
import uk.ac.starlink.ttools.votlint.VotLintEntityResolver;
import uk.ac.starlink.util.Compression;
import uk.ac.starlink.util.DOMUtils;
import uk.ac.starlink.util.MultiplexInvocationHandler;
import uk.ac.starlink.util.StarEntityResolver;
import uk.ac.starlink.vo.TapQuery;
import uk.ac.starlink.vo.UwsJob;
import uk.ac.starlink.votable.TableElement;
import uk.ac.starlink.votable.VODocument;
import uk.ac.starlink.votable.VOElement;
import uk.ac.starlink.votable.VOStarTable;
import uk.ac.starlink.votable.VOTableDOMBuilder;
/**
* TapRunner implementation which uses the VotLint validation classes
* to check the query's result VOTable.
*
* @author Mark Taylor
* @since 10 Jun 2011
*/
public abstract class VotLintTapRunner extends TapRunner {
private final boolean doChecks_;
/** Result table parameter set if table was marked overflowed. */
public static ValueInfo OVERFLOW_INFO =
new DefaultValueInfo( "OVERFLOW", Boolean.class,
"Is TAP result overflow status set?" );
/**
* Constructor.
*
* @param name name for this instance
* @param doChecks true to perform various checks on the result VOTable
* (including linting) and report them, false to be
* mostly silent and only report serious errors
*/
protected VotLintTapRunner( String name, boolean doChecks ) {
super( name );
doChecks_ = doChecks;
}
/**
* Execute a TAP query and return a URL connection giving its result.
*
* @param reporter validation message destination
* @param tq query
* @return result data source
*/
protected abstract URLConnection getResultConnection( Reporter reporter,
TapQuery tq )
throws IOException;
@Override
protected StarTable executeQuery( Reporter reporter, TapQuery tq )
throws IOException, SAXException {
URLConnection conn = getResultConnection( reporter, tq );
conn = TapQuery.followRedirects( conn );
conn.connect();
String ctype = conn.getContentType();
if ( doChecks_ ) {
if ( ctype == null || ctype.trim().length() == 0 ) {
reporter.report( ReportType.WARNING, "NOCT",
"No Content-Type header for "
+ conn.getURL() );
}
else if ( ! ( ctype.startsWith( "text/xml" ) ||
ctype.startsWith( "application/xml" ) ||
ctype.startsWith( "application/x-votable+xml" ) ||
ctype.startsWith( "text/x-votable+xml" ) ) ) {
String msg = new StringBuilder()
.append( "Bad content type " )
.append( ctype )
.append( " for HTTP response which should contain " )
.append( "VOTable result or error document" )
.append( " (" )
.append( conn.getURL() )
.append( ")" )
.toString();
reporter.report( ReportType.ERROR, "VOCT", msg );
}
}
/* RFC2616 sec 3.5. */
String cCoding = conn.getContentEncoding();
final Compression compression;
if ( cCoding == null || cCoding.trim().length() == 0
|| "identity".equals( cCoding ) ) {
compression = Compression.NONE;
}
else if ( "gzip".equals( cCoding ) || "x-gzip".equals( cCoding ) ) {
compression = Compression.GZIP;
}
else if ( "compress".equals( cCoding ) ||
"x-compress".equals( cCoding ) ) {
compression = Compression.COMPRESS;
}
else {
reporter.report( ReportType.WARNING, "CEUK",
"Unknown Content-Encoding " + cCoding
+ " for " + conn.getURL() );
compression = Compression.NONE;
}
if ( doChecks_ && compression != Compression.NONE ) {
reporter.report( ReportType.WARNING, "CEZZ",
"Compression with Content-Encoding " + cCoding
+ " for " + conn.getURL() );
}
InputStream in = null;
try {
in = compression.decompress( conn.getInputStream() );
}
catch ( IOException e ) {
if ( conn instanceof HttpURLConnection ) {
in = ((HttpURLConnection) conn).getErrorStream();
}
if ( in == null ) {
throw e;
}
}
return readResultVOTable( reporter, in );
}
/**
* Indicates if the given table, which must have been retrieved from
* this object's {@link #readResultVOTable} method, was marked as
* an overflow result.
*
* @param table TAP result table read by this object
* @return true iff overflow
*/
public boolean isOverflow( StarTable table ) {
DescribedValue ovParam =
table.getParameterByName( OVERFLOW_INFO.getName() );
if ( ovParam != null && ovParam.getValue() instanceof Boolean ) {
return ((Boolean) ovParam.getValue()).booleanValue();
}
else {
throw new IllegalArgumentException( "Not produced by me!" );
}
}
/**
* Reads a TAP result VOTable from an input stream, checking it and
* reporting messages as appropriate.
* The resulting table will have the {@link #OVERFLOW_INFO} parameter
* present and set/unset appropriately.
*
* @param reporter validation message destination
* @param in VOTable input stream
*/
protected StarTable readResultVOTable( Reporter reporter, InputStream in )
throws IOException, SAXException {
/* Set up a SAX event handler to create a DOM. */
VOTableDOMBuilder domHandler =
new VOTableDOMBuilder( StoragePolicy.getDefaultPolicy(), true );
/* Set up a parser which will feed SAX events to the dom builder,
* and may or may not generate logging messages through the
* reporter as it progresses. */
final XMLReader parser;
if ( doChecks_ ) {
ReporterVotLintContext vlContext =
new ReporterVotLintContext( reporter );
vlContext.setVersion( VotableVersion.V12 );
vlContext.setValidating( true );
vlContext.setDebug( false );
vlContext.setOutput( null );
parser = createParser( reporter, vlContext );
ContentHandler vcHandler =
new MultiplexInvocationHandler<ContentHandler>(
new ContentHandler[] {
new VotLintContentHandler( vlContext ),
domHandler } )
.createMultiplexer( ContentHandler.class );
parser.setErrorHandler( new ReporterErrorHandler( reporter ) );
parser.setContentHandler( vcHandler );
}
else {
parser = createParser( reporter );
parser.setEntityResolver( StarEntityResolver.getInstance() );
parser.setErrorHandler( new ErrorHandler() {
public void warning( SAXParseException err ) {}
public void error( SAXParseException err ) {}
public void fatalError( SAXParseException err ) {}
} );
parser.setContentHandler( domHandler );
}
/* Perform the parse and retrieve the resulting DOM. */
parser.parse( new InputSource( in ) );
VODocument doc = domHandler.getDocument();
/* Check the top-level element. */
VOElement voEl = (VOElement) doc.getDocumentElement();
if ( ! "VOTABLE".equals( voEl.getVOTagName() ) ) {
String msg = new StringBuffer()
.append( "Top-level element of result document is " )
.append( voEl.getTagName() )
.append( " not VOTABLE" )
.toString();
throw new IOException( msg );
}
/* Attempt to find the results element. */
VOElement[] resourceEls = voEl.getChildrenByName( "RESOURCE" );
VOElement resultsEl = null;
for ( int ie = 0; ie < resourceEls.length; ie++ ) {
VOElement el = resourceEls[ ie ];
if ( "results".equals( el.getAttribute( "type" ) ) ) {
resultsEl = el;
}
}
if ( resultsEl == null ) {
if ( resourceEls.length == 1 ) {
resultsEl = resourceEls[ 0 ];
if ( doChecks_ ) {
reporter.report( ReportType.ERROR, "RRES",
"TAP response document RESOURCE element "
+ "is not marked type='results'" );
}
}
else {
throw new IOException( "No RESOURCE with type='results'" );
}
}
/* Look for preceding and possible trailing QUERY_STATUS INFOs
* and the TABLE. */
VOElement preStatusInfo = null;
VOElement postStatusInfo = null;
TableElement tableEl = null;
for ( Node node = resultsEl.getFirstChild(); node != null;
node = node.getNextSibling() ) {
if ( node instanceof VOElement ) {
VOElement el = (VOElement) node;
String name = el.getVOTagName();
boolean isStatusInfo =
"INFO".equals( name ) &&
"QUERY_STATUS".equals( el.getAttribute( "name" ) );
boolean isTable =
"TABLE".equals( name );
if ( isStatusInfo ) {
if ( tableEl == null ) {
if ( preStatusInfo == null ) {
preStatusInfo = el;
}
else if ( doChecks_ ) {
reporter.report( ReportType.ERROR, "QST1",
"Multiple pre-table INFOs with "
+ "name='QUERY_STATUS'" );
}
}
else {
if ( postStatusInfo == null ) {
postStatusInfo = el;
}
else if ( doChecks_ ) {
reporter.report( ReportType.ERROR, "QST2",
"Multiple post-table INFOs with "
+ "name='QUERY_STATUS'" );
}
}
}
if ( isTable ) {
if ( tableEl == null ) {
tableEl = (TableElement) el;
}
else {
reporter.report( ReportType.ERROR, "TTOO",
"Multiple TABLEs in results "
+ "RESOURCE" );
}
}
}
}
/* Check pre-table status INFO. */
if ( preStatusInfo == null ) {
if ( doChecks_ ) {
reporter.report( ReportType.ERROR, "NOST",
"Missing <INFO name='QUERY_STATUS'> element "
+ "before TABLE" );
}
}
else {
String preStatus = preStatusInfo.getAttribute( "value" );
if ( "ERROR".equals( preStatus ) ) {
String err = DOMUtils.getTextContent( preStatusInfo );
if ( err == null || err.trim().length() == 0 ) {
if ( doChecks_ ) {
reporter.report( ReportType.WARNING, "NOER",
"<INFO name='QUERY_STATUS' "
+ "value='ERROR'> "
+ "element has no message content" );
}
err = "Unknown TAP result error";
}
- throw new IOException( err );
+ throw new IOException( "Service error: \"" + err + "\"" );
}
else if ( "OK".equals( preStatus ) ) {
// ok
}
else {
if ( doChecks_ ) {
String msg = new StringBuffer()
.append( "Pre-table QUERY_STATUS INFO " )
.append( "has unknown value " )
.append( preStatus )
.append( " is not OK/ERROR" )
.toString();
reporter.report( ReportType.ERROR, "QST1", msg );
}
}
}
/* Check post-table status INFO. */
boolean overflow = false;
if ( postStatusInfo != null ) {
String postStatus = postStatusInfo.getAttribute( "value" );
if ( "ERROR".equals( postStatus ) ) {
String err = DOMUtils.getTextContent( postStatusInfo );
if ( err == null || err.trim().length() == 0 ) {
if ( doChecks_ ) {
reporter.report( ReportType.WARNING, "NOER",
"<INFO name='QUERY_STATUS' "
+ "value='ERROR'> "
+ "element has no message content" );
}
err = "Unknown TAP result error";
}
throw new IOException( err );
}
else if ( "OVERFLOW".equals( postStatus ) ) {
overflow = true;
}
else {
if ( doChecks_ ) {
String msg = new StringBuffer()
.append( "Post-table QUERY_STATUS INFO " )
.append( "has unknown value " )
.append( postStatus )
.append( " is not ERROR/OVERFLOW" )
.toString();
reporter.report( ReportType.ERROR, "QST2", msg );
}
}
}
/* Return table if present. */
if ( tableEl == null ) {
throw new IOException( "No TABLE element in results RESOURCE" );
}
StarTable table = new VOStarTable( tableEl );
table.setParameter( new DescribedValue( OVERFLOW_INFO,
Boolean.valueOf( overflow ) ) );
return table;
}
/**
* Returns a basic SAX parser. If it fails, the error will be reported
* and an exception will be thrown.
*
* @param reporter validation message destination
* @return basically configured SAX parser
*/
private XMLReader createParser( Reporter reporter ) throws SAXException {
try {
SAXParserFactory spfact = SAXParserFactory.newInstance();
spfact.setValidating( false );
spfact.setNamespaceAware( true );
return spfact.newSAXParser().getXMLReader();
}
catch ( ParserConfigurationException e ) {
reporter.report( ReportType.FAILURE, "PRSR",
"Trouble setting up XML parse", e );
throw (SAXException) new SAXException( e.getMessage() )
.initCause( e );
}
}
/**
* Returns a SAX parser suitable for VOTable checking.
* Its handlers are not set.
*
* @param reporter validation message destination
* @param vlContext information about votlint config
*/
private XMLReader createParser( Reporter reporter,
VotLintContext vlContext )
throws SAXException {
XMLReader parser = createParser( reporter );
/* Install a custom entity resolver. This is also installed as
* a lexical handler, to guarantee that whatever is named in the
* DOCTYPE declaration is actually interpreted as the VOTable DTD. */
VotLintEntityResolver entityResolver =
new VotLintEntityResolver( vlContext );
try {
parser.setProperty( "http://xml.org/sax/properties/lexical-handler",
entityResolver );
parser.setEntityResolver( entityResolver );
}
catch ( SAXException e ) {
parser.setEntityResolver( StarEntityResolver.getInstance() );
reporter.report( ReportType.FAILURE, "XENT",
"Entity trouble - DTD validation may not be " +
"done properly", e );
}
/* Return. */
return parser;
}
/**
* Returns a new instance which uses HTTP POST to make synchronous queries.
*
* @param doChecks true for detailed VOTable checking
* @return new TapRunner
*/
public static VotLintTapRunner createPostSyncRunner( boolean doChecks ) {
return new VotLintTapRunner( "sync POST", doChecks ) {
@Override
protected URLConnection getResultConnection( Reporter reporter,
TapQuery tq )
throws IOException {
return UwsJob.postForm( new URL( tq.getServiceUrl() + "/sync" ),
tq.getStringParams(),
tq.getStreamParams() );
}
};
}
/**
* Returns a new instance which uses HTTP GET to make synchronous queries.
*
* @param doChecks true for detailed VOTable checking
* @return new TapRunner
*/
public static VotLintTapRunner
createGetSyncRunner( final boolean doChecks ) {
return new VotLintTapRunner( "sync GET", doChecks ) {
@Override
protected URLConnection getResultConnection( Reporter reporter,
TapQuery tq )
throws IOException {
if ( tq.getStreamParams() == null ||
tq.getStreamParams().isEmpty() ) {
String ptxt =
new String( UwsJob
.toPostedBytes( tq.getStringParams() ),
"utf-8" );
URL qurl = new URL( tq.getServiceUrl() + "/sync?" + ptxt );
if ( doChecks ) {
reporter.report( ReportType.INFO, "QGET",
"Query GET URL: " + qurl );
}
return qurl.openConnection();
}
else {
return UwsJob
.postForm( new URL( tq.getServiceUrl() + "/sync" ),
tq.getStringParams(),
tq.getStreamParams() );
}
}
};
}
/**
* Returns a new instance which makes asynchronous queries.
* This instance does not do exhaustive validation.
*
* @param pollMillis polling interval in milliseconds
* @param doChecks true for detailed VOTable checking
* @return new TapRunner
*/
public static VotLintTapRunner createAsyncRunner( final long pollMillis,
boolean doChecks ) {
return new VotLintTapRunner( "async", doChecks ) {
@Override
protected URLConnection getResultConnection( Reporter reporter,
TapQuery tq )
throws IOException {
UwsJob uwsJob =
UwsJob.createJob( tq.getServiceUrl()+ "/async",
tq.getStringParams(),
tq.getStreamParams() );
URL jobUrl = uwsJob.getJobUrl();
reporter.report( ReportType.INFO, "QJOB",
"Submitted query at " + jobUrl );
uwsJob.start();
String phase;
try {
phase = uwsJob.waitForFinish( pollMillis );
}
catch ( InterruptedException e ) {
throw (IOException)
new InterruptedIOException( "interrupted" )
.initCause( e );
}
if ( "COMPLETED".equals( phase ) ) {
uwsJob.setDeleteOnExit( true );
return new URL( jobUrl + "/results/result" )
.openConnection();
}
else if ( "ERROR".equals( phase ) ) {
return new URL( jobUrl + "/error" ).openConnection();
}
else {
throw new IOException( "Unexpected UWS phase " + phase );
}
}
};
}
}
| true | true | protected StarTable readResultVOTable( Reporter reporter, InputStream in )
throws IOException, SAXException {
/* Set up a SAX event handler to create a DOM. */
VOTableDOMBuilder domHandler =
new VOTableDOMBuilder( StoragePolicy.getDefaultPolicy(), true );
/* Set up a parser which will feed SAX events to the dom builder,
* and may or may not generate logging messages through the
* reporter as it progresses. */
final XMLReader parser;
if ( doChecks_ ) {
ReporterVotLintContext vlContext =
new ReporterVotLintContext( reporter );
vlContext.setVersion( VotableVersion.V12 );
vlContext.setValidating( true );
vlContext.setDebug( false );
vlContext.setOutput( null );
parser = createParser( reporter, vlContext );
ContentHandler vcHandler =
new MultiplexInvocationHandler<ContentHandler>(
new ContentHandler[] {
new VotLintContentHandler( vlContext ),
domHandler } )
.createMultiplexer( ContentHandler.class );
parser.setErrorHandler( new ReporterErrorHandler( reporter ) );
parser.setContentHandler( vcHandler );
}
else {
parser = createParser( reporter );
parser.setEntityResolver( StarEntityResolver.getInstance() );
parser.setErrorHandler( new ErrorHandler() {
public void warning( SAXParseException err ) {}
public void error( SAXParseException err ) {}
public void fatalError( SAXParseException err ) {}
} );
parser.setContentHandler( domHandler );
}
/* Perform the parse and retrieve the resulting DOM. */
parser.parse( new InputSource( in ) );
VODocument doc = domHandler.getDocument();
/* Check the top-level element. */
VOElement voEl = (VOElement) doc.getDocumentElement();
if ( ! "VOTABLE".equals( voEl.getVOTagName() ) ) {
String msg = new StringBuffer()
.append( "Top-level element of result document is " )
.append( voEl.getTagName() )
.append( " not VOTABLE" )
.toString();
throw new IOException( msg );
}
/* Attempt to find the results element. */
VOElement[] resourceEls = voEl.getChildrenByName( "RESOURCE" );
VOElement resultsEl = null;
for ( int ie = 0; ie < resourceEls.length; ie++ ) {
VOElement el = resourceEls[ ie ];
if ( "results".equals( el.getAttribute( "type" ) ) ) {
resultsEl = el;
}
}
if ( resultsEl == null ) {
if ( resourceEls.length == 1 ) {
resultsEl = resourceEls[ 0 ];
if ( doChecks_ ) {
reporter.report( ReportType.ERROR, "RRES",
"TAP response document RESOURCE element "
+ "is not marked type='results'" );
}
}
else {
throw new IOException( "No RESOURCE with type='results'" );
}
}
/* Look for preceding and possible trailing QUERY_STATUS INFOs
* and the TABLE. */
VOElement preStatusInfo = null;
VOElement postStatusInfo = null;
TableElement tableEl = null;
for ( Node node = resultsEl.getFirstChild(); node != null;
node = node.getNextSibling() ) {
if ( node instanceof VOElement ) {
VOElement el = (VOElement) node;
String name = el.getVOTagName();
boolean isStatusInfo =
"INFO".equals( name ) &&
"QUERY_STATUS".equals( el.getAttribute( "name" ) );
boolean isTable =
"TABLE".equals( name );
if ( isStatusInfo ) {
if ( tableEl == null ) {
if ( preStatusInfo == null ) {
preStatusInfo = el;
}
else if ( doChecks_ ) {
reporter.report( ReportType.ERROR, "QST1",
"Multiple pre-table INFOs with "
+ "name='QUERY_STATUS'" );
}
}
else {
if ( postStatusInfo == null ) {
postStatusInfo = el;
}
else if ( doChecks_ ) {
reporter.report( ReportType.ERROR, "QST2",
"Multiple post-table INFOs with "
+ "name='QUERY_STATUS'" );
}
}
}
if ( isTable ) {
if ( tableEl == null ) {
tableEl = (TableElement) el;
}
else {
reporter.report( ReportType.ERROR, "TTOO",
"Multiple TABLEs in results "
+ "RESOURCE" );
}
}
}
}
/* Check pre-table status INFO. */
if ( preStatusInfo == null ) {
if ( doChecks_ ) {
reporter.report( ReportType.ERROR, "NOST",
"Missing <INFO name='QUERY_STATUS'> element "
+ "before TABLE" );
}
}
else {
String preStatus = preStatusInfo.getAttribute( "value" );
if ( "ERROR".equals( preStatus ) ) {
String err = DOMUtils.getTextContent( preStatusInfo );
if ( err == null || err.trim().length() == 0 ) {
if ( doChecks_ ) {
reporter.report( ReportType.WARNING, "NOER",
"<INFO name='QUERY_STATUS' "
+ "value='ERROR'> "
+ "element has no message content" );
}
err = "Unknown TAP result error";
}
throw new IOException( err );
}
else if ( "OK".equals( preStatus ) ) {
// ok
}
else {
if ( doChecks_ ) {
String msg = new StringBuffer()
.append( "Pre-table QUERY_STATUS INFO " )
.append( "has unknown value " )
.append( preStatus )
.append( " is not OK/ERROR" )
.toString();
reporter.report( ReportType.ERROR, "QST1", msg );
}
}
}
/* Check post-table status INFO. */
boolean overflow = false;
if ( postStatusInfo != null ) {
String postStatus = postStatusInfo.getAttribute( "value" );
if ( "ERROR".equals( postStatus ) ) {
String err = DOMUtils.getTextContent( postStatusInfo );
if ( err == null || err.trim().length() == 0 ) {
if ( doChecks_ ) {
reporter.report( ReportType.WARNING, "NOER",
"<INFO name='QUERY_STATUS' "
+ "value='ERROR'> "
+ "element has no message content" );
}
err = "Unknown TAP result error";
}
throw new IOException( err );
}
else if ( "OVERFLOW".equals( postStatus ) ) {
overflow = true;
}
else {
if ( doChecks_ ) {
String msg = new StringBuffer()
.append( "Post-table QUERY_STATUS INFO " )
.append( "has unknown value " )
.append( postStatus )
.append( " is not ERROR/OVERFLOW" )
.toString();
reporter.report( ReportType.ERROR, "QST2", msg );
}
}
}
/* Return table if present. */
if ( tableEl == null ) {
throw new IOException( "No TABLE element in results RESOURCE" );
}
StarTable table = new VOStarTable( tableEl );
table.setParameter( new DescribedValue( OVERFLOW_INFO,
Boolean.valueOf( overflow ) ) );
return table;
}
| protected StarTable readResultVOTable( Reporter reporter, InputStream in )
throws IOException, SAXException {
/* Set up a SAX event handler to create a DOM. */
VOTableDOMBuilder domHandler =
new VOTableDOMBuilder( StoragePolicy.getDefaultPolicy(), true );
/* Set up a parser which will feed SAX events to the dom builder,
* and may or may not generate logging messages through the
* reporter as it progresses. */
final XMLReader parser;
if ( doChecks_ ) {
ReporterVotLintContext vlContext =
new ReporterVotLintContext( reporter );
vlContext.setVersion( VotableVersion.V12 );
vlContext.setValidating( true );
vlContext.setDebug( false );
vlContext.setOutput( null );
parser = createParser( reporter, vlContext );
ContentHandler vcHandler =
new MultiplexInvocationHandler<ContentHandler>(
new ContentHandler[] {
new VotLintContentHandler( vlContext ),
domHandler } )
.createMultiplexer( ContentHandler.class );
parser.setErrorHandler( new ReporterErrorHandler( reporter ) );
parser.setContentHandler( vcHandler );
}
else {
parser = createParser( reporter );
parser.setEntityResolver( StarEntityResolver.getInstance() );
parser.setErrorHandler( new ErrorHandler() {
public void warning( SAXParseException err ) {}
public void error( SAXParseException err ) {}
public void fatalError( SAXParseException err ) {}
} );
parser.setContentHandler( domHandler );
}
/* Perform the parse and retrieve the resulting DOM. */
parser.parse( new InputSource( in ) );
VODocument doc = domHandler.getDocument();
/* Check the top-level element. */
VOElement voEl = (VOElement) doc.getDocumentElement();
if ( ! "VOTABLE".equals( voEl.getVOTagName() ) ) {
String msg = new StringBuffer()
.append( "Top-level element of result document is " )
.append( voEl.getTagName() )
.append( " not VOTABLE" )
.toString();
throw new IOException( msg );
}
/* Attempt to find the results element. */
VOElement[] resourceEls = voEl.getChildrenByName( "RESOURCE" );
VOElement resultsEl = null;
for ( int ie = 0; ie < resourceEls.length; ie++ ) {
VOElement el = resourceEls[ ie ];
if ( "results".equals( el.getAttribute( "type" ) ) ) {
resultsEl = el;
}
}
if ( resultsEl == null ) {
if ( resourceEls.length == 1 ) {
resultsEl = resourceEls[ 0 ];
if ( doChecks_ ) {
reporter.report( ReportType.ERROR, "RRES",
"TAP response document RESOURCE element "
+ "is not marked type='results'" );
}
}
else {
throw new IOException( "No RESOURCE with type='results'" );
}
}
/* Look for preceding and possible trailing QUERY_STATUS INFOs
* and the TABLE. */
VOElement preStatusInfo = null;
VOElement postStatusInfo = null;
TableElement tableEl = null;
for ( Node node = resultsEl.getFirstChild(); node != null;
node = node.getNextSibling() ) {
if ( node instanceof VOElement ) {
VOElement el = (VOElement) node;
String name = el.getVOTagName();
boolean isStatusInfo =
"INFO".equals( name ) &&
"QUERY_STATUS".equals( el.getAttribute( "name" ) );
boolean isTable =
"TABLE".equals( name );
if ( isStatusInfo ) {
if ( tableEl == null ) {
if ( preStatusInfo == null ) {
preStatusInfo = el;
}
else if ( doChecks_ ) {
reporter.report( ReportType.ERROR, "QST1",
"Multiple pre-table INFOs with "
+ "name='QUERY_STATUS'" );
}
}
else {
if ( postStatusInfo == null ) {
postStatusInfo = el;
}
else if ( doChecks_ ) {
reporter.report( ReportType.ERROR, "QST2",
"Multiple post-table INFOs with "
+ "name='QUERY_STATUS'" );
}
}
}
if ( isTable ) {
if ( tableEl == null ) {
tableEl = (TableElement) el;
}
else {
reporter.report( ReportType.ERROR, "TTOO",
"Multiple TABLEs in results "
+ "RESOURCE" );
}
}
}
}
/* Check pre-table status INFO. */
if ( preStatusInfo == null ) {
if ( doChecks_ ) {
reporter.report( ReportType.ERROR, "NOST",
"Missing <INFO name='QUERY_STATUS'> element "
+ "before TABLE" );
}
}
else {
String preStatus = preStatusInfo.getAttribute( "value" );
if ( "ERROR".equals( preStatus ) ) {
String err = DOMUtils.getTextContent( preStatusInfo );
if ( err == null || err.trim().length() == 0 ) {
if ( doChecks_ ) {
reporter.report( ReportType.WARNING, "NOER",
"<INFO name='QUERY_STATUS' "
+ "value='ERROR'> "
+ "element has no message content" );
}
err = "Unknown TAP result error";
}
throw new IOException( "Service error: \"" + err + "\"" );
}
else if ( "OK".equals( preStatus ) ) {
// ok
}
else {
if ( doChecks_ ) {
String msg = new StringBuffer()
.append( "Pre-table QUERY_STATUS INFO " )
.append( "has unknown value " )
.append( preStatus )
.append( " is not OK/ERROR" )
.toString();
reporter.report( ReportType.ERROR, "QST1", msg );
}
}
}
/* Check post-table status INFO. */
boolean overflow = false;
if ( postStatusInfo != null ) {
String postStatus = postStatusInfo.getAttribute( "value" );
if ( "ERROR".equals( postStatus ) ) {
String err = DOMUtils.getTextContent( postStatusInfo );
if ( err == null || err.trim().length() == 0 ) {
if ( doChecks_ ) {
reporter.report( ReportType.WARNING, "NOER",
"<INFO name='QUERY_STATUS' "
+ "value='ERROR'> "
+ "element has no message content" );
}
err = "Unknown TAP result error";
}
throw new IOException( err );
}
else if ( "OVERFLOW".equals( postStatus ) ) {
overflow = true;
}
else {
if ( doChecks_ ) {
String msg = new StringBuffer()
.append( "Post-table QUERY_STATUS INFO " )
.append( "has unknown value " )
.append( postStatus )
.append( " is not ERROR/OVERFLOW" )
.toString();
reporter.report( ReportType.ERROR, "QST2", msg );
}
}
}
/* Return table if present. */
if ( tableEl == null ) {
throw new IOException( "No TABLE element in results RESOURCE" );
}
StarTable table = new VOStarTable( tableEl );
table.setParameter( new DescribedValue( OVERFLOW_INFO,
Boolean.valueOf( overflow ) ) );
return table;
}
|
diff --git a/src/edu/cmu/hcii/novo/kadarbra/ProcedureFactory.java b/src/edu/cmu/hcii/novo/kadarbra/ProcedureFactory.java
index 1fff3fb..fb6c71f 100644
--- a/src/edu/cmu/hcii/novo/kadarbra/ProcedureFactory.java
+++ b/src/edu/cmu/hcii/novo/kadarbra/ProcedureFactory.java
@@ -1,842 +1,842 @@
package edu.cmu.hcii.novo.kadarbra;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import android.content.Context;
import android.content.res.AssetManager;
import android.util.Log;
import android.util.Xml;
import edu.cmu.hcii.novo.kadarbra.structure.Callout;
import edu.cmu.hcii.novo.kadarbra.structure.Callout.CType;
import edu.cmu.hcii.novo.kadarbra.structure.Cycle;
import edu.cmu.hcii.novo.kadarbra.structure.CycleNote;
import edu.cmu.hcii.novo.kadarbra.structure.ExecNote;
import edu.cmu.hcii.novo.kadarbra.structure.Procedure;
import edu.cmu.hcii.novo.kadarbra.structure.ProcedureItem;
import edu.cmu.hcii.novo.kadarbra.structure.Reference;
import edu.cmu.hcii.novo.kadarbra.structure.Reference.RType;
import edu.cmu.hcii.novo.kadarbra.structure.Step;
import edu.cmu.hcii.novo.kadarbra.structure.StowageItem;
public class ProcedureFactory {
private static final String TAG = "ProcedureFactory";
// We don't use namespaces
private static final String ns = null;
/**
* Generate a list of procedure objects based off of the
* xml definitions in the ___ directory.
*
* @return a list of procedure objects
*/
public static List<Procedure> getProcedures(Context ctx) {
Log.d(TAG, "Getting procedures from xml");
List<Procedure> results = new ArrayList<Procedure>();
try {
//yup
AssetManager assMan = ctx.getAssets();
String[] procs = assMan.list("procedures");
Log.v(TAG, procs.length + " file(s) to parse");
for (String proc : procs) {
if (proc.endsWith(".xml")) {
try {
Log.d(TAG, "Parsing " + proc);
InputStream in = assMan.open("procedures/" + proc);
results.add(getProcedure(in));
} catch (Exception e) {
Log.e(TAG, "Error parsing procedure", e);
}
}
}
} catch (IOException e) {
Log.e(TAG, "Error gathering asset files", e);
}
return results;
}
/**
* Get a procedure object based off of the given input stream.
* Sets up the parser then calls a different parse method.
*
* @param in the input stream to parse
* @return a procedure object
* @throws XmlPullParserException
* @throws IOException
*/
public static Procedure getProcedure(InputStream in) throws XmlPullParserException, IOException {
Log.v(TAG, "Initializing parser");
try {
XmlPullParser parser = Xml.newPullParser();
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
parser.setInput(in, null);
parser.nextTag();
return readProcedure(parser);
} finally {
in.close();
}
}
/**
* Parse an xml document to create a procedure object.
*
* TODO: these methods could definitely be more flexible, maybe keep a
* map of the corresponding tags?
*
* @param parser the xml to parse
* @return the resulting procedure object
* @throws XmlPullParserException
* @throws IOException
*/
private static Procedure readProcedure(XmlPullParser parser) throws XmlPullParserException, IOException {
Log.d(TAG, "Parsing procedure");
String section = null;
String title = null;
String objective = null;
String duration = null;
List<ExecNote> execNotes = null;
Map<String, List<StowageItem>> stowageItems = null;
List<ProcedureItem> children = null;
//This is the tag we are looking for
parser.require(XmlPullParser.START_TAG, ns, "procedure");
//Until we get to the closing tag
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.getEventType() != XmlPullParser.START_TAG) {
continue;
}
String tag = parser.getName();
//Get the attributes
if (tag.equals("section")) {
section = readTag(parser, tag);
} else if (tag.equals("subsection")) {
section += "." + readTag(parser, tag);
} else if (tag.equals("sub_subsection")) {
section += "." + readTag(parser, tag);
} else if (tag.equals("title")) {
title = readTag(parser, tag);
} else if (tag.equals("objective")) {
objective = readTag(parser, tag);
} else if (tag.equals("duration")) {
duration = readTag(parser, tag);
} else if (tag.equals("execution_notes")) {
execNotes = readExecNotes(parser);
} else if (tag.equals("stowage_notes")) {
stowageItems = readStowageNotes(parser);
} else if (tag.equals("steps")) {
children = readSteps(parser);
} else {
skip(parser);
}
}
return new Procedure(section, title, objective, duration, execNotes, stowageItems, children);
}
/**
* Parse the xml for a list of overall execution notes
*
* @param parser the xml to parse
* @return the resulting list of execution notes
* @throws XmlPullParserException
* @throws IOException
*/
private static List<ExecNote> readExecNotes(XmlPullParser parser) throws XmlPullParserException, IOException {
Log.d(TAG, "Parsing execution notes");
List<ExecNote> execNotes = new ArrayList<ExecNote>();
//This is the tag we are looking for
parser.require(XmlPullParser.START_TAG, ns, "execution_notes");
//Until we get to the closing tag
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.getEventType() != XmlPullParser.START_TAG) {
continue;
}
String tag = parser.getName();
//Get the attributes
if (tag.equals("note")) {
execNotes.add(readExecNote(parser));
} else {
skip(parser);
}
}
return execNotes;
}
/**
* Parse xml for an execution note
*
* @param parser the xml to parse
* @return the resulting execution note
* @throws XmlPullParserException
* @throws IOException
*/
private static ExecNote readExecNote(XmlPullParser parser) throws XmlPullParserException, IOException {
Log.d(TAG, "Parsing execution note");
String step = null;
String text = null;
//This is the tag we are looking for
parser.require(XmlPullParser.START_TAG, ns, "note");
//Until we get to the closing tag
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.getEventType() != XmlPullParser.START_TAG) {
continue;
}
String tag = parser.getName();
//Get the attributes
if (tag.equals("step")) {
step = readTag(parser, tag);
} else if (tag.equals("substep")) {
step += "." + readTag(parser, tag);
} else if (tag.equals("text")) {
text = readTag(parser, tag);
} else {
skip(parser);
}
}
return new ExecNote(step, text);
}
/**
* Parse the xml for a list of overall stowage items
*
* @param parser the xml to parse
* @return the resulting list of stowage items
* @throws XmlPullParserException
* @throws IOException
*/
private static Map<String, List<StowageItem>> readStowageNotes(XmlPullParser parser) throws XmlPullParserException, IOException {
Log.d(TAG, "Parsing stowage notes");
Map<String, List<StowageItem>> stowageItems = new HashMap<String, List<StowageItem>>();
//This is the tag we are looking for
parser.require(XmlPullParser.START_TAG, ns, "stowage_notes");
//Until we get to the closing tag
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.getEventType() != XmlPullParser.START_TAG) {
continue;
}
String tag = parser.getName();
//Get the attributes
if (tag.equals("item")) {
StowageItem newItem = readStowageItem(parser);
String module = newItem.getModule();
if (!stowageItems.containsKey(module)) {
stowageItems.put(module, new ArrayList<StowageItem>());
}
stowageItems.get(module).add(newItem);
} else {
skip(parser);
}
}
return stowageItems;
}
/**
* Parse xml for an execution note
*
* @param parser the xml to parse
* @return the resultin execution note
* @throws XmlPullParserException
* @throws IOException
*/
private static StowageItem readStowageItem(XmlPullParser parser) throws XmlPullParserException, IOException {
Log.v(TAG, "Parsing stowage item");
String module = null;
String name = null;
int quantity = 0;
String itemCode = null;
String binCode = null;
String text = null;
String url = null;
//This is the tag we are looking for
parser.require(XmlPullParser.START_TAG, ns, "item");
//Until we get to the closing tag
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.getEventType() != XmlPullParser.START_TAG) {
continue;
}
String tag = parser.getName();
//Get the attributes
if (tag.equals("module")) {
module = readTag(parser, tag);
} else if (tag.equals("name")) {
name = readTag(parser, tag);
} else if (tag.equals("quantity")) {
quantity = Integer.parseInt(readTag(parser, tag));
} else if (tag.equals("item_code")) {
itemCode = readTag(parser, tag);
} else if (tag.equals("bin_code")) {
binCode = readTag(parser, tag);
} else if (tag.equals("text")) {
text = readTag(parser, tag);
} else if (tag.equals("url")) {
url = readTag(parser, tag);
} else {
skip(parser);
}
}
return new StowageItem(module, name, quantity, itemCode, binCode, text, url);
}
/**
* Parse the xml for the list of overall procedure steps.
*
*
* @param parser the xml to parse
* @return a list of steps
* @throws XmlPullParserException
* @throws IOException
*/
private static List<ProcedureItem> readSteps(XmlPullParser parser) throws XmlPullParserException, IOException {
Log.d(TAG, "Parsing steps");
List<ProcedureItem> steps = new ArrayList<ProcedureItem>();
//This is the tag we are looking for
parser.require(XmlPullParser.START_TAG, ns, "steps");
//Until we get to the closing tag
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.getEventType() != XmlPullParser.START_TAG) {
continue;
}
String tag = parser.getName();
//Get the attributes
if (tag.equals("step")) {
steps.add(readStep(parser));
} else if (tag.equals("cycle")) {
steps.add(readCycle(parser));
} else {
skip(parser);
}
}
return steps;
}
/**
* Parse an xml document to create a parent step.
*
* @param parser the xml to parse
* @return a step object
* @throws XmlPullParserException
* @throws IOException
*/
private static Step readStep(XmlPullParser parser) throws XmlPullParserException, IOException {
Log.d(TAG, "Parsing step");
String number = null;
String text = null;
String consequent = null;
List<Callout> callouts = new ArrayList<Callout>();
List<ProcedureItem> children = new ArrayList<ProcedureItem>();
List<Reference> references = new ArrayList<Reference>();
boolean timer = false;
boolean inputAllowed = false;
//This is the tag we are looking for
parser.require(XmlPullParser.START_TAG, ns, "step");
//Until we get to the closing tag
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.getEventType() != XmlPullParser.START_TAG) {
continue;
}
String tag = parser.getName();
//Get the attributes
if (tag.equals("number")) {
number = readTag(parser, tag);
} else if (tag.equals("consequent")) {
consequent = readTag(parser, tag);
} else if (tag.equals("text")) {
text = readTag(parser, tag);
} else if (tag.equals("callout")) {
callouts.add(readCallout(parser));
} else if (tag.equals("reference")) {
references.add(readReference(parser));
} else if (tag.equals("step")) {
children.add(readStep(parser));
} else if (tag.equals("cycle")) {
children.add(readCycle(parser));
} else if (tag.equals("timer")){
- timer = true;
+ timer = Boolean.parseBoolean(readTag(parser, tag));
} else if (tag.equals("input")) {
inputAllowed = Boolean.parseBoolean(readTag(parser, tag));
} else {
skip(parser);
}
}
Step result = new Step(number, text, callouts, references, children, timer, inputAllowed);
if (consequent != null) result.setConsequent(consequent);
return result;
}
/**
* Parse and xml document to create a new Callout object.
*
* @param parser the xml to parse
* @return the resulting Callout object
* @throws XmlPullParserException
* @throws IOException
*/
private static Callout readCallout(XmlPullParser parser) throws XmlPullParserException, IOException {
Log.d(TAG, "Parsing callout");
CType type = null;
String text = null;
//This is the tag we are looking for
parser.require(XmlPullParser.START_TAG, ns, "callout");
//Until we get to the closing tag
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.getEventType() != XmlPullParser.START_TAG) {
continue;
}
String tag = parser.getName();
//Get the attributes
if (tag.equals("type")) {
String t = readTag(parser, tag);
if (t.equals("note")) {
type = CType.NOTE;
} else if (t.equals("warning")) {
type = CType.WARNING;
} else if (t.equals("caution")) {
type = CType.CAUTION;
}
} else if (tag.equals("text")) {
text = readTag(parser, tag);
} else {
skip(parser);
}
}
return new Callout(type, text);
}
/**
* Parse and xml document to create a new Callout object.
*
* @param parser the xml to parse
* @return the resulting Callout object
* @throws XmlPullParserException
* @throws IOException
*/
private static Reference readReference(XmlPullParser parser) throws XmlPullParserException, IOException {
Log.d(TAG, "Parsing reference");
RType type = null;
String name = null;
String description = null;
String url = null;
List<List<String>> table = new ArrayList<List<String>>();
//This is the tag we are looking for
parser.require(XmlPullParser.START_TAG, ns, "reference");
//Until we get to the closing tag
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.getEventType() != XmlPullParser.START_TAG) {
continue;
}
String tag = parser.getName();
//Get the attributes
if (tag.equals("type")) {
String t = readTag(parser, tag);
if (t.equals("image")) {
type = RType.IMAGE;
} else if (t.equals("video")) {
type = RType.VIDEO;
} else if (t.equals("audio")) {
type = RType.AUDIO;
} else if (t.equals("table")) {
type = RType.TABLE;
}
} else if (tag.equals("name")) {
name = readTag(parser, tag);
} else if (tag.equals("description")) {
description = readTag(parser, tag);
} else if (tag.equals("url")) {
url = readTag(parser, tag);
} else if (tag.equals("table")) {
table = readTable(parser);
} else {
skip(parser);
}
}
return new Reference(type, name, description, url, table);
}
/**
* Parse and xml document to create a new cycle of steps. A cycle is
* really just a linear list of the same steps being repeated.
*
* @param parser the xml to parse
* @return the resulting list of steps
* @throws XmlPullParserException
* @throws IOException
*/
private static Cycle readCycle(XmlPullParser parser) throws XmlPullParserException, IOException {
Log.d(TAG, "Parsing cycle");
int repetitions = 0;
List<CycleNote> notes = new ArrayList<CycleNote>();
List<ProcedureItem> children = new ArrayList<ProcedureItem>();
//This is the tag we are looking for
parser.require(XmlPullParser.START_TAG, ns, "cycle");
//Until we get to the closing tag
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.getEventType() != XmlPullParser.START_TAG) {
continue;
}
String tag = parser.getName();
//Get the attributes
if (tag.equals("repetitions")) {
repetitions = Integer.parseInt(readTag(parser, tag));
} else if (tag.equals("step")) {
children.add(readStep(parser));
} else if (tag.equals("cycle")) {
children.add(readCycle(parser));
} else if (tag.equals("cycle_notes")) {
notes = readCycleNotes(parser);
} else {
skip(parser);
}
}
return new Cycle(repetitions, notes, children);
}
/**
* Parse xml to produce a list of cycle notes
*
* @param parser
* @return
* @throws XmlPullParserException
* @throws IOException
*/
private static List<CycleNote> readCycleNotes(XmlPullParser parser) throws XmlPullParserException, IOException {
Log.d(TAG, "Parsing cycle notes");
List<CycleNote> notes = new ArrayList<CycleNote>();
//This is the tag we are looking for
parser.require(XmlPullParser.START_TAG, ns, "cycle_notes");
//Until we get to the closing tag
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.getEventType() != XmlPullParser.START_TAG) {
continue;
}
String tag = parser.getName();
//Get the attributes
if (tag.equals("note")) {
notes.add(readCycleNote(parser));
} else {
skip(parser);
}
}
return notes;
}
/**
* Parse xml to produce a cycle note object
* @param parser
* @return
* @throws XmlPullParserException
* @throws IOException
*/
private static CycleNote readCycleNote(XmlPullParser parser) throws XmlPullParserException, IOException {
Log.v(TAG, "Parsing cycle note");
String text = null;
Reference ref = null;
//This is the tag we are looking for
parser.require(XmlPullParser.START_TAG, ns, "note");
//Until we get to the closing tag
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.getEventType() != XmlPullParser.START_TAG) {
continue;
}
String tag = parser.getName();
//Get the attributes
if (tag.equals("text")) {
text = readTag(parser, tag);
} else if (tag.equals("reference")) {
ref = readReference(parser);
} else {
skip(parser);
}
}
return new CycleNote(text, ref);
}
/**
* Read the xml to produce a table object. Its a list of lists of strings
* defining rows and columns.
*
* TODO this really should be a 2d array
*
* @param parser
* @return
* @throws XmlPullParserException
* @throws IOException
*/
private static List<List<String>> readTable(XmlPullParser parser) throws XmlPullParserException, IOException {
Log.d(TAG, "Parsing table");
List<List<String>> cells = new ArrayList<List<String>>();
//This is the tag we are looking for
parser.require(XmlPullParser.START_TAG, ns, "table");
//Until we get to the closing tag
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.getEventType() != XmlPullParser.START_TAG) {
continue;
}
String tag = parser.getName();
//Get the attributes
if (tag.equals("row")) {
cells.add(readRow(parser));
} else {
skip(parser);
}
}
return cells;
}
private static List<String> readRow(XmlPullParser parser) throws XmlPullParserException, IOException {
Log.d(TAG, "Parsing row");
List<String> row = new ArrayList<String>();
//This is the tag we are looking for
parser.require(XmlPullParser.START_TAG, ns, "row");
//Until we get to the closing tag
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.getEventType() != XmlPullParser.START_TAG) {
continue;
}
String tag = parser.getName();
//Get the attributes
if (tag.equals("cell")) {
row.add(readTag(parser, tag));
} else {
skip(parser);
}
}
//row.toArray(new String[row.size()]);
return row;
}
/**
* Read the text value of the given tag from the xml.
*
* @param parser the xml to parse
* @param tag the tag to look for
* @return the string value of the tag
* @throws XmlPullParserException
* @throws IOException
*/
private static String readTag(XmlPullParser parser, String tag) throws XmlPullParserException, IOException {
Log.v(TAG, "Reading tag " + tag);
parser.require(XmlPullParser.START_TAG, ns, tag);
String result = readTextValue(parser);
parser.require(XmlPullParser.END_TAG, ns, tag);
return result;
}
/**
* Extracts a tag's textual value.
*
* @param parser the xml to parse
* @return the string value contained within a tag
* @throws IOException
* @throws XmlPullParserException
*/
private static String readTextValue(XmlPullParser parser) throws IOException, XmlPullParserException {
String result = "";
if (parser.next() == XmlPullParser.TEXT) {
result = parser.getText();
parser.nextTag();
}
return result;
}
/**
* Skip the tag currently pointed to by the parser. This lets us
* ignore any tags we don't currently care about.
*
* @param parser the xml to parse
* @throws XmlPullParserException
* @throws IOException
*/
private static void skip(XmlPullParser parser) throws XmlPullParserException, IOException {
if (parser.getEventType() != XmlPullParser.START_TAG) {
throw new IllegalStateException();
}
//Move through the xml until we get to the close
//of the current tag.
int depth = 1;
while (depth != 0) {
switch (parser.next()) {
case XmlPullParser.END_TAG:
depth--;
break;
case XmlPullParser.START_TAG:
depth++;
break;
}
}
}
}
| true | true | private static Step readStep(XmlPullParser parser) throws XmlPullParserException, IOException {
Log.d(TAG, "Parsing step");
String number = null;
String text = null;
String consequent = null;
List<Callout> callouts = new ArrayList<Callout>();
List<ProcedureItem> children = new ArrayList<ProcedureItem>();
List<Reference> references = new ArrayList<Reference>();
boolean timer = false;
boolean inputAllowed = false;
//This is the tag we are looking for
parser.require(XmlPullParser.START_TAG, ns, "step");
//Until we get to the closing tag
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.getEventType() != XmlPullParser.START_TAG) {
continue;
}
String tag = parser.getName();
//Get the attributes
if (tag.equals("number")) {
number = readTag(parser, tag);
} else if (tag.equals("consequent")) {
consequent = readTag(parser, tag);
} else if (tag.equals("text")) {
text = readTag(parser, tag);
} else if (tag.equals("callout")) {
callouts.add(readCallout(parser));
} else if (tag.equals("reference")) {
references.add(readReference(parser));
} else if (tag.equals("step")) {
children.add(readStep(parser));
} else if (tag.equals("cycle")) {
children.add(readCycle(parser));
} else if (tag.equals("timer")){
timer = true;
} else if (tag.equals("input")) {
inputAllowed = Boolean.parseBoolean(readTag(parser, tag));
} else {
skip(parser);
}
}
Step result = new Step(number, text, callouts, references, children, timer, inputAllowed);
if (consequent != null) result.setConsequent(consequent);
return result;
}
| private static Step readStep(XmlPullParser parser) throws XmlPullParserException, IOException {
Log.d(TAG, "Parsing step");
String number = null;
String text = null;
String consequent = null;
List<Callout> callouts = new ArrayList<Callout>();
List<ProcedureItem> children = new ArrayList<ProcedureItem>();
List<Reference> references = new ArrayList<Reference>();
boolean timer = false;
boolean inputAllowed = false;
//This is the tag we are looking for
parser.require(XmlPullParser.START_TAG, ns, "step");
//Until we get to the closing tag
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.getEventType() != XmlPullParser.START_TAG) {
continue;
}
String tag = parser.getName();
//Get the attributes
if (tag.equals("number")) {
number = readTag(parser, tag);
} else if (tag.equals("consequent")) {
consequent = readTag(parser, tag);
} else if (tag.equals("text")) {
text = readTag(parser, tag);
} else if (tag.equals("callout")) {
callouts.add(readCallout(parser));
} else if (tag.equals("reference")) {
references.add(readReference(parser));
} else if (tag.equals("step")) {
children.add(readStep(parser));
} else if (tag.equals("cycle")) {
children.add(readCycle(parser));
} else if (tag.equals("timer")){
timer = Boolean.parseBoolean(readTag(parser, tag));
} else if (tag.equals("input")) {
inputAllowed = Boolean.parseBoolean(readTag(parser, tag));
} else {
skip(parser);
}
}
Step result = new Step(number, text, callouts, references, children, timer, inputAllowed);
if (consequent != null) result.setConsequent(consequent);
return result;
}
|
diff --git a/km/com/hifiremote/jp1/DeviceUpgrade.java b/km/com/hifiremote/jp1/DeviceUpgrade.java
index 79de4ea..a3dc28b 100644
--- a/km/com/hifiremote/jp1/DeviceUpgrade.java
+++ b/km/com/hifiremote/jp1/DeviceUpgrade.java
@@ -1,1535 +1,1536 @@
package com.hifiremote.jp1;
import java.util.*;
import java.io.*;
import java.text.*;
import javax.swing.*;
import java.awt.*;
public class DeviceUpgrade
{
public DeviceUpgrade()
{
devTypeAliasName = deviceTypeAliasNames[ 0 ];
initFunctions();
}
public void reset()
{
description = null;
setupCode = 0;
// remove all currently assigned functions
remote.clearButtonAssignments();
Remote[] remotes = RemoteManager.getRemoteManager().getRemotes();
if ( remote == null )
remote = remotes[ 0 ];
devTypeAliasName = deviceTypeAliasNames[ 0 ];
ProtocolManager pm = ProtocolManager.getProtocolManager();
Vector names = pm.getNames();
Protocol tentative = null;
for ( Enumeration e = names.elements(); e.hasMoreElements(); )
{
String protocolName = ( String )e.nextElement();
Protocol p = pm.findProtocolForRemote( remote, protocolName );
if ( p != null )
{
protocol = p;
break;
}
}
DeviceParameter[] devParms = protocol.getDeviceParameters();
for ( int i = 0; i < devParms.length; i++ )
devParms[ i ].setValue( null );
setProtocol( protocol );
notes = null;
file = null;
functions.clear();
initFunctions();
extFunctions.clear();
}
private void initFunctions()
{
String[] names = KeyMapMaster.getCustomNames();
if ( names == null )
names = defaultFunctionNames;
for ( int i = 0; i < names.length; i++ )
functions.add( new Function( names[ i ]));
}
public void setDescription( String text )
{
description = text;
}
public String getDescription()
{
return description;
}
public void setSetupCode( int setupCode )
{
this.setupCode = setupCode;
}
public int getSetupCode()
{
return setupCode;
}
public void setRemote( Remote newRemote )
{
Protocol p = protocol;
ProtocolManager pm = ProtocolManager.getProtocolManager();
Vector protocols = pm.getProtocolsForRemote( newRemote, false );
if ( !protocols.contains( p ))
{
System.err.println( "DeviceUpgrade.setRemote(), protocol " + p.getDiagnosticName() +
" is not built into remote " + newRemote.getName());
Protocol newp = pm.findProtocolForRemote( newRemote, p.getName() );
if ( newp != null )
{
System.err.println( "protocol " + newp.getDiagnosticName() + " will be used." );
if ( newp != p )
{
System.err.println( "\tChecking for matching dev. parms" );
DeviceParameter[] parms = p.getDeviceParameters();
DeviceParameter[] parms2 = newp.getDeviceParameters();
int[] map = new int[ parms.length ];
boolean parmsMatch = true;
for ( int i = 0; i < parms.length; i++ )
{
String name = parms[ i ].getName();
System.err.print( "\tchecking " + name );
boolean nameMatch = false;
for ( int j = 0; j < parms2.length; j++ )
{
if ( name.equals( parms2[ j ].getName()))
{
map[ i ] = j;
nameMatch = true;
System.err.print( " has a match!" );
break;
}
}
if ( !nameMatch )
{
Object v = parms[ i ].getValue();
Object d = parms[ i ].getDefaultValue();
if ( d != null )
d = (( DefaultValue )d ).value();
System.err.print( " no match!" );
if (( v == null ) ||
( v.equals( d )))
{
nameMatch = true;
map[ i ] = -1;
System.err.print( " But there's no value anyway! " );
}
}
System.err.println();
parmsMatch = nameMatch;
if ( !parmsMatch )
break;
}
if ( parmsMatch )
{
// copy parameters from p to p2!
System.err.println( "\tCopying dev. parms" );
for ( int i = 0; i < map.length; i++ )
{
if ( map[ i ] == -1 )
continue;
System.err.println( "\tfrom index " + i + " to index " + map[ i ]);
parms2[ map[ i ]].setValue( parms[ i ].getValue());
}
System.err.println();
System.err.println( "Setting new protocol" );
p.convertFunctions( functions, newp );
protocol = newp;
}
}
}
else
JOptionPane.showMessageDialog( KeyMapMaster.getKeyMapMaster(),
"The selected protocol " + p.getDiagnosticName() +
"\nis not compatible with the selected remote.\n" +
"This upgrade will NOT function correctly.\n" +
"Please choose a different protocol.",
"Error", JOptionPane.ERROR_MESSAGE );
}
if (( remote != null ) && ( remote != newRemote ))
{
Button[] buttons = remote.getUpgradeButtons();
Button[] newButtons = newRemote.getUpgradeButtons();
Vector unassigned = new Vector();
for ( int i = 0; i < buttons.length; i++ )
{
Button b = buttons[ i ];
Function f = b.getFunction();
Function sf = b.getShiftedFunction();
Function xf = b.getXShiftedFunction();
if (( f != null ) || ( sf != null ) || ( xf != null ))
{
if ( f != null )
b.setFunction( null );
if ( sf != null )
b.setShiftedFunction( null );
if ( xf != null )
b.setXShiftedFunction( null );
Button newB = newRemote.findByStandardName( b );
if ( newB != null )
{
if ( f != null )
newB.setFunction( f );
if ( sf != null )
newB.setShiftedFunction( sf );
if ( xf != null )
newB.setXShiftedFunction( xf );
}
else // keep track of lost assignments
{
Vector temp = null;
if ( f != null )
{
temp = new Vector();
temp.add( f.getName());
temp.add( b.getName());
unassigned.add( temp );
}
if ( sf != null )
{
temp = new Vector();
temp.add( sf.getName());
temp.add( b.getShiftedName());
unassigned.add( temp );
}
if ( xf != null )
{
temp = new Vector();
temp.add( xf.getName());
temp.add( b.getXShiftedName());
unassigned.add( temp );
}
}
}
}
if ( !unassigned.isEmpty())
{
String message = "Some of the functions defined in the device upgrade " +
"were assigned to buttons that do not match buttons on the newly selected remote. " +
"The functions and the corresponding button names from the original remote are listed below." +
"\n\nUse the Button or Layout panel to assign those functions properly.";
JFrame frame = new JFrame( "Lost Function Assignments" );
Container container = frame.getContentPane();
JTextArea text = new JTextArea( message );
text.setEditable( false );
text.setLineWrap( true );
text.setWrapStyleWord( true );
text.setBackground( container.getBackground() );
text.setBorder( BorderFactory.createEmptyBorder( 5, 5, 5, 5 ));
container.add( text, BorderLayout.NORTH );
Vector titles = new Vector();
titles.add( "Function name" );
titles.add( "Button name" );
JTable table = new JTable( unassigned, titles );
Dimension d = table.getPreferredScrollableViewportSize();
d.height = d.height / 4;
table.setPreferredScrollableViewportSize( d );
container.add( new JScrollPane( table ), BorderLayout.CENTER );
frame.pack();
frame.setLocationRelativeTo( KeyMapMaster.getKeyMapMaster());
frame.show();
}
}
remote = newRemote;
}
public Remote getRemote()
{
return remote;
}
public void setDeviceTypeAliasName( String name )
{
if ( name != null )
{
if ( remote.getDeviceTypeByAliasName( name ) != null )
{
devTypeAliasName = name;
return;
}
System.err.println( "Unable to find device type with alias name " + name );
}
devTypeAliasName = deviceTypeAliasNames[ 0 ];
}
public String getDeviceTypeAliasName()
{
return devTypeAliasName;
}
public DeviceType getDeviceType()
{
return remote.getDeviceTypeByAliasName( devTypeAliasName );
}
public void setProtocol( Protocol protocol )
{
this.protocol = protocol;
parmValues = protocol.getDeviceParmValues();
}
public Protocol getProtocol()
{
return protocol;
}
public void setNotes( String notes )
{
this.notes = notes;
}
public String getNotes()
{
return notes;
}
public Vector getFunctions()
{
return functions;
}
public Function getFunction( String name )
{
Function rc = getFunction( name, functions );
if ( rc == null )
rc = getFunction( name, extFunctions );
return rc;
}
public Function getFunction( String name, Vector funcs )
{
Function rc = null;
for ( Enumeration e = funcs.elements(); e.hasMoreElements(); )
{
Function func = ( Function )e.nextElement();
String funcName = func.getName();
if (( funcName != null ) && funcName.equalsIgnoreCase( name ))
{
rc = func;
break;
}
}
return rc;
}
public Vector getExternalFunctions()
{
return extFunctions;
}
public Vector getKeyMoves()
{
return keymoves;
}
public void setFile( File file )
{
this.file = file;
}
public File getFile(){ return file; }
private int findDigitMapIndex()
{
Button[] buttons = remote.getUpgradeButtons();
int[] digitMaps = remote.getDigitMaps();
if (( digitMaps != null ) && ( protocol.getDefaultCmd().length() == 1 ))
{
for ( int i = 0; i < digitMaps.length; i++ )
{
int mapNum = digitMaps[ i ];
if ( mapNum == 999 )
continue;
int[] codes = DigitMaps.data[ mapNum ];
int rc = -1;
for ( int j = 0; ; j++ )
{
Function f = buttons[ j ].getFunction();
if (( f != null ) && !f.isExternal())
{
if (( f.getHex().getData()[ 0 ] & 0xFF ) == codes[ j ])
rc = i + 1;
else
break;
}
if ( j == 9 )
{
return rc;
}
}
}
}
return -1;
}
public String getUpgradeText( boolean includeNotes )
{
StringBuffer buff = new StringBuffer( 400 );
buff.append( "Upgrade code 0 = " );
DeviceType devType = remote.getDeviceTypeByAliasName( devTypeAliasName );
int[] id = protocol.getID( remote ).getData();
int temp = devType.getNumber() * 0x1000 +
( id[ 0 ] & 1 ) * 0x0800 +
setupCode - remote.getDeviceCodeOffset();
int[] deviceCode = new int[2];
deviceCode[ 0 ] = (temp >> 8 );
deviceCode[ 1 ] = temp;
buff.append( Hex.toString( deviceCode ));
buff.append( " (" );
buff.append( devTypeAliasName );
buff.append( '/' );
DecimalFormat df = new DecimalFormat( "0000" );
buff.append( df.format( setupCode ));
buff.append( ")" );
if ( includeNotes )
{
String descr = "";
if ( description != null )
descr = description.trim();
if ( descr.length() != 0 )
{
buff.append( ' ' );
buff.append( descr );
}
buff.append( " (RM " );
buff.append( KeyMapMaster.version );
buff.append( ')' );
}
buff.append( "\n " );
buff.append( Hex.asString( id[ 1 ]));
int digitMapIndex = -1;
if ( !remote.getOmitDigitMapByte())
{
buff.append( ' ' );
digitMapIndex = findDigitMapIndex();
if ( digitMapIndex == -1 )
buff.append( "00" );
else
{
buff.append( Hex.asString( digitMapIndex ));
}
}
ButtonMap map = devType.getButtonMap();
if ( map != null )
{
buff.append( ' ' );
buff.append( Hex.toString( map.toBitMap( digitMapIndex != -1 )));
}
buff.append( ' ' );
buff.append( protocol.getFixedData( parmValues ).toString());
if ( map != null )
{
int[] data = map.toCommandList( digitMapIndex != -1 );
if (( data != null ) && ( data.length != 0 ))
{
buff.append( "\n " );
buff.append( Hex.toString( data, 16 ));
}
}
Button[] buttons = remote.getUpgradeButtons();
boolean hasKeyMoves = false;
int startingButton = 0;
int i;
for ( i = 0; i < buttons.length; i++ )
{
Button b = buttons[ i ];
Function f = b.getFunction();
Function sf = b.getShiftedFunction();
if ( b.getShiftedButton() != null )
sf = null;
Function xf = b.getXShiftedFunction();
if ( b.getXShiftedButton() != null )
xf = null;
if ((( f != null ) && (( map == null ) || !map.isPresent( b ) || f.isExternal())) ||
(( sf != null ) && ( sf.getHex() != null )) || (( xf != null) && ( xf.getHex() != null )))
{
hasKeyMoves = true;
break;
}
}
if ( hasKeyMoves )
{
deviceCode[ 0 ] = ( deviceCode[ 0 ] & 0xF7 );
buff.append( "\nKeyMoves" );
boolean first = true;
for ( ; i < buttons.length; i++ )
{
Button button = buttons[ i ];
Function f = button.getFunction();
first = appendKeyMove( buff, button.getKeyMove( f, 0, deviceCode, devType, remote ),
f, includeNotes, first );
f = button.getShiftedFunction();
if ( button.getShiftedButton() != null )
f = null;
first = appendKeyMove( buff, button.getKeyMove( f, remote.getShiftMask(), deviceCode, devType, remote ),
f, includeNotes, first );
f = button.getXShiftedFunction();
if ( button.getXShiftedButton() != null )
f = null;
first = appendKeyMove( buff, button.getKeyMove( f, remote.getXShiftMask(), deviceCode, devType, remote ),
f, includeNotes, first );
}
}
buff.append( "\nEnd" );
return buff.toString();
}
private boolean appendKeyMove( StringBuffer buff, int[] keyMove,Function f, boolean includeNotes, boolean first )
{
if (( keyMove == null ) || ( keyMove.length == 0 ))
return first;
if ( includeNotes && !first )
buff.append( '\u00a6' );
buff.append( "\n " );
buff.append( Hex.toString( keyMove ));
if ( includeNotes )
{
buff.append( '\u00ab' );
buff.append( f.getName());
String notes = f.getNotes();
if (( notes != null ) && ( notes.length() != 0 ))
{
buff.append( ": " );
buff.append( notes );
}
buff.append( '\u00bb' );
}
return false;
}
public void store()
throws IOException
{
store( file );
}
public static String valueArrayToString( Value[] parms )
{
StringBuffer buff = new StringBuffer( 200 );
for ( int i = 0; i < parms.length; i++ )
{
if ( i > 0 )
buff.append( ' ' );
buff.append( parms[ i ].getUserValue());
}
return buff.toString();
}
public static Value[] stringToValueArray( String str )
{
StringTokenizer st = new StringTokenizer( str );
Value[] parms = new Value[ st.countTokens()];
for ( int i = 0; i < parms.length; i++ )
{
String token = st.nextToken();
Object val = null;
if ( !token.equals( "null" ))
{
if ( token.equals( "true" ))
val = new Integer( 1 );
else if ( token.equals( "false" ))
val = new Integer( 0 );
else
val = new Integer( token );
}
parms[ i ] = new Value( val, null );
}
return parms;
}
public void store( File file )
throws IOException
{
this.file = file;
PropertyWriter out =
new PropertyWriter( new PrintWriter( new FileWriter( file )));
if ( description != null )
out.print( "Description", description );
out.print( "Remote.name", remote.getName());
out.print( "Remote.signature", remote.getSignature());
out.print( "DeviceType", devTypeAliasName );
DeviceType devType = remote.getDeviceTypeByAliasName( devTypeAliasName );
out.print( "DeviceIndex", Integer.toHexString( devType.getNumber()));
out.print( "SetupCode", Integer.toString( setupCode ));
// protocol.setDeviceParms( parmValues );
protocol.store( out, parmValues );
if ( notes != null )
out.print( "Notes", notes );
int i = 0;
for ( Enumeration e = functions.elements(); e.hasMoreElements(); i++ )
{
Function func = ( Function )e.nextElement();
func.store( out, "Function." + i );
}
i = 0;
for ( Enumeration e = extFunctions.elements(); e.hasMoreElements(); i++ )
{
ExternalFunction func = ( ExternalFunction )e.nextElement();
func.store( out, "ExtFunction." + i );
}
Button[] buttons = remote.getUpgradeButtons();
String regex = "\\|";
String replace = "\\\\u007c";
for ( i = 0; i < buttons.length; i++ )
{
Button b = buttons[ i ];
Function f = b.getFunction();
String fstr;
if ( f == null )
fstr = "null";
else
fstr = f.getName().replaceAll( regex, replace );
Function sf = b.getShiftedFunction();
String sstr;
if ( sf == null )
sstr = "null";
else
sstr = sf.getName().replaceAll( regex, replace );
Function xf = b.getXShiftedFunction();
String xstr;
if ( xf == null )
xstr = null;
else
xstr = xf.getName().replaceAll( regex, replace );
if (( f != null ) || ( sf != null ) || ( xf != null ))
{
out.print( "Button." + Integer.toHexString( b.getKeyCode()),
fstr + '|' + sstr + '|' + xstr );
}
}
out.flush();
out.close();
}
public void load( File file )
throws Exception
{
load( file, true );
}
public void load( File file, boolean loadButtons )
throws Exception
{
if ( file.getName().toLowerCase().endsWith( ".rmdu" ))
this.file = file;
BufferedReader reader = new BufferedReader( new FileReader( file ));
load( reader, loadButtons );
}
public void load( BufferedReader reader )
throws Exception
{
load( reader, true );
}
public void load( BufferedReader reader, boolean loadButtons )
throws Exception
{
reader.mark( 160 );
String line = reader.readLine();
reader.reset();
if ( line.startsWith( "Name:" ))
{
importUpgrade( reader, loadButtons );
return;
}
Properties props = new Properties();
Property property = new Property();
PropertyReader pr = new PropertyReader( reader );
while (( property = pr.nextProperty( property )) != null )
{
props.put( property.name, property.value );
}
reader.close();
String str = props.getProperty( "Description" );
if ( str != null )
description = str;
str = props.getProperty( "Remote.name" );
if ( str == null )
{
JOptionPane.showMessageDialog( KeyMapMaster.getKeyMapMaster(),
"The upgrade you are trying to import is not valid! It does not contain a value for Remote.name",
"Import Failure", JOptionPane.ERROR_MESSAGE );
return;
}
String sig = props.getProperty( "Remote.signature" );
remote = RemoteManager.getRemoteManager().findRemoteByName( str );
remote.load();
int index = -1;
str = props.getProperty( "DeviceIndex" );
if ( str != null )
index = Integer.parseInt( str, 16 );
setDeviceTypeAliasName( props.getProperty( "DeviceType" ) );
setupCode = Integer.parseInt( props.getProperty( "SetupCode" ));
Hex pid = new Hex( props.getProperty( "Protocol", "0200" ));
String name = props.getProperty( "Protocol.name", "" );
String variantName = props.getProperty( "Protocol.variantName", "" );
ProtocolManager pm = ProtocolManager.getProtocolManager();
if ( name.equals( "Manual Settings" ) ||
name.equals( "Manual" ) ||
name.equals( "PID " + pid.toString()))
{
protocol = new ManualProtocol( pid, props );
pm.add( protocol );
}
else
{
protocol = pm.findNearestProtocol( name, pid, variantName );
if ( protocol == null )
{
JOptionPane.showMessageDialog( KeyMapMaster.getKeyMapMaster(),
"No protocol found with name=\"" + name +
"\", ID=" + pid.toString() +
", and variantName=\"" + variantName + "\"",
"File Load Error", JOptionPane.ERROR_MESSAGE );
return;
}
}
str = props.getProperty( "ProtocolParms" );
System.err.println( "ProtocolParms='" + str + "'" );
if (( str != null ) && ( str.length() != 0 ))
{
protocol.setDeviceParms( stringToValueArray( str ));
parmValues = protocol.getDeviceParmValues();
}
protocol.setProperties( props );
notes = props.getProperty( "Notes" );
functions.clear();
int i = 0;
while ( true )
{
Function f = new Function();
f.load( props, "Function." + i );
if ( f.isEmpty())
{
break;
}
functions.add( f );
i++;
}
extFunctions.clear();
i = 0;
while ( true )
{
ExternalFunction f = new ExternalFunction();
f.load( props, "ExtFunction." + i, remote );
if ( f.isEmpty())
{
break;
}
extFunctions.add( f );
i++;
}
if ( loadButtons )
{
Button[] buttons = remote.getUpgradeButtons();
String regex = "\\\\u007c";
String replace = "|";
for ( i = 0; i < buttons.length; i++ )
{
Button b = buttons[ i ];
str = props.getProperty( "Button." + Integer.toHexString( b.getKeyCode()));
if ( str == null )
{
continue;
}
StringTokenizer st = new StringTokenizer( str, "|" );
str = st.nextToken();
Function func = null;
if ( !str.equals( "null" ))
{
func = getFunction( str.replaceAll( regex, replace ));
b.setFunction( func );
}
str = st.nextToken();
if ( !str.equals( "null" ))
{
func = getFunction( str.replaceAll( regex, replace ));
b.setShiftedFunction( func );
}
if ( st.hasMoreTokens())
{
str = st.nextToken();
if ( !str.equals( "null" ))
{
func = getFunction( str.replaceAll( regex, replace ));
b.setXShiftedFunction( func );
}
}
}
}
}
private String getNextField( StringTokenizer st, String delim )
{
String rc = null;
if ( st.hasMoreTokens())
{
rc = st.nextToken();
if ( rc.equals( delim ))
rc = null;
else
{
if ( rc.startsWith( "\"" ))
{
if ( rc.endsWith( "\"" ))
{
rc = rc.substring( 1, rc.length() - 1 ).replaceAll( "\"\"", "\"" );
}
else
{
StringBuffer buff = new StringBuffer( 200 );
buff.append( rc.substring( 1 ));
while ( true )
{
String token = st.nextToken(); // skip delim
buff.append( delim );
token = st.nextToken();
if ( token.endsWith( "\"" ))
{
buff.append( token.substring( 0, token.length() - 1 ));
break;
}
else
buff.append( token );
}
rc = buff.toString().replaceAll( "\"\"", "\"" );
}
}
if ( st.hasMoreTokens())
st.nextToken(); // skip delim
}
}
return rc;
}
public void importUpgrade( BufferedReader in )
throws Exception
{
importUpgrade( in, true );
}
public void importUpgrade( BufferedReader in, boolean loadButtons )
throws Exception
{
String line = in.readLine(); // line 1
String token = line.substring( 0, 5 );
if ( !token.equals( "Name:" ))
{
JOptionPane.showMessageDialog( KeyMapMaster.getKeyMapMaster(),
"The upgrade you are trying to import is not valid!",
"Import Failure", JOptionPane.ERROR_MESSAGE );
return;
}
String delim = line.substring( 5, 6 );
StringTokenizer st = new StringTokenizer( line, delim, true );
getNextField( st, delim );
description = getNextField( st, delim );
String protocolLine = in.readLine(); // line 3
String manualLine = in.readLine(); // line 4
line = in.readLine(); // line 5
st = new StringTokenizer( line, delim );
st.nextToken();
token = st.nextToken();
setupCode = Integer.parseInt( token );
token = st.nextToken();
String str = token.substring( 5 );
remote = RemoteManager.getRemoteManager().findRemoteByName( str );
Hex pid = null;
while ( true )
{
line = in.readLine();
if (( line != null ) && ( line.length() > 0 ) && ( line.charAt( 0 ) == '\"' ))
line = line.substring( 1 );
int equals = line.indexOf( '=' );
if (( equals != -1 ) && line.substring( 0, equals ).toLowerCase().startsWith( "upgrade code " ))
{
int[] id = new int[ 2 ];
int temp = Integer.parseInt( line.substring( equals + 2, equals + 4 ), 16 );
if (( temp & 8 ) != 0 )
id[ 0 ] = 1;
line = in.readLine();
temp = Integer.parseInt( line.substring( 0, 2 ), 16 );
id[ 1 ] = temp;
pid = new Hex( id );
break;
}
}
remote.load();
token = st.nextToken();
str = token.substring( 5 );
if ( remote.getDeviceTypeByAliasName( str ) == null )
{
String rc = null;
String msg = "Remote \"" + remote.getName() + "\" does not support the device type " +
str + ". Please select one of the supported device types below to use instead.\n";
while ( rc == null )
{
rc = ( String )JOptionPane.showInputDialog( KeyMapMaster.getKeyMapMaster(),
msg,
"Unsupported Device Type",
JOptionPane.ERROR_MESSAGE,
null,
remote.getDeviceTypeAliasNames(),
null );
}
str = rc;
}
setDeviceTypeAliasName( str );
String buttonStyle = st.nextToken();
st = new StringTokenizer( protocolLine, delim, true );
getNextField( st, delim ); // skip header
String protocolName = getNextField( st, delim ); // protocol name
ProtocolManager protocolManager = ProtocolManager.getProtocolManager();
if ( protocolName.equals( "Manual Settings" ))
{
System.err.println( "protocolName=" + protocolName );
System.err.println( "manualLine=" + manualLine );
StringTokenizer manual = new StringTokenizer( manualLine, delim, true );
System.err.println( "skipping " + getNextField( manual, delim )); // skip header
String pidStr = getNextField( manual, delim );
System.err.println( "pid=" + pidStr );
if ( pidStr != null )
{
int space = pidStr.indexOf( ' ' );
if ( space != -1 )
{
pid = new Hex( pidStr );
}
else
{
int pidInt = Integer.parseInt( pidStr, 16 );
int[] data = new int[ 2 ];
data[ 0 ] = ( pidInt & 0xFF00 ) >> 8;
data[ 1 ] = pidInt & 0xFF;
pid = new Hex( data );
}
}
int byte2 = Integer.parseInt( getNextField( manual, delim ).substring( 0, 1 ));
System.err.println( "byte2=" + byte2 );
String signalStyle = getNextField( manual, delim );
System.err.println( "SignalStyle=" + signalStyle );
String bitsStr = getNextField( manual, delim );
int devBits = Integer.parseInt( bitsStr.substring( 0, 1 ), 16);
int cmdBits = Integer.parseInt( bitsStr.substring( 1 ), 16 );
System.err.println( "devBits=" + devBits + " and cmdBits=" + cmdBits );
Vector values = new Vector();
str = getNextField( st, delim ); // Device 1
if ( str != null )
values.add( new Integer( str ));
str = getNextField( st, delim ); // Device 2
if ( str != null )
values.add( new Integer( str ));
str = getNextField( st, delim ); // Device 3
if ( str != null )
values.add( new Integer( str ));
str = getNextField( st, delim ); // Raw Fixed Data
if ( str == null )
str = "";
int[] rawHex = Hex.parseHex( str );
protocol = new ManualProtocol( protocolName, pid, byte2, signalStyle, devBits, values, rawHex, cmdBits );
protocolName = protocol.getName();
setParmValues( protocol.getDeviceParmValues());
protocolManager.add( protocol );
}
else
{
// protocol = protocolManager.findProtocolForRemote( remote, protocolName );
Protocol p = protocolManager.findNearestProtocol( protocolName, pid, null );
if ( p == null )
{
p = protocolManager.findProtocolByOldName( remote, protocolName, pid );
if ( p == null )
{
JOptionPane.showMessageDialog( KeyMapMaster.getKeyMapMaster(),
"No protocol found with name=\"" + protocolName +
"\" for remote \"" + remote.getName() + "\".",
"Import Failure", JOptionPane.ERROR_MESSAGE );
reset();
return;
}
}
protocol = p;
Value[] importParms = new Value[ 4 ];
for ( int i = 0; i < importParms.length; i++ )
{
token = getNextField( st, delim );
Object val = null;
if ( token == null )
val = null;
else
{
if ( token.equals( "true" ))
val = new Integer( 1 );
else if ( token.equals( "false" ))
val = new Integer( 0 );
else
val = token;
// val = new Integer( token );
}
importParms[ i ] = new Value( val );
}
protocol.importDeviceParms( importParms );
parmValues = protocol.getDeviceParmValues();
}
// compute cmdIndex
boolean useOBC = false;
boolean useEFC = false;
if ( buttonStyle.equals( "OBC" ))
useOBC = true;
else if ( buttonStyle.equals( "EFC" ))
useEFC = true;
int obcIndex = -1;
CmdParameter[] cmdParms = protocol.getCommandParameters();
for ( obcIndex = 0; obcIndex < cmdParms.length; obcIndex++ )
{
if ( cmdParms[ obcIndex ].getName().equals( "OBC" ))
break;
}
String match1 = "fFunctions" + delim;
String match2 = "Functions" + delim;
if ( useOBC )
{
match1 = match1 + "fOBC" + delim;
match2 = match2 + "OBC" + delim;
}
else
{
match1 = match1 + "fEFC" + delim;
match2 = match2 + "EFC" + delim;
}
while ( true )
{
line = in.readLine();
if ( line.startsWith( match1 ) || line.startsWith( match2 ))
break;
}
functions.clear();
DeviceCombiner combiner = null;
if ( protocol.getClass() == DeviceCombiner.class )
combiner = ( DeviceCombiner )protocol;
Vector unassigned = new Vector();
Vector usedFunctions = new Vector();
for ( int i = 0; i < 128; i++ )
{
line = in.readLine();
st = new StringTokenizer( line, delim, true );
token = getNextField( st, delim ); // get the name (field 1)
if (( token != null ) && ( token.length() == 5 ) &&
token.startsWith( "num " ) && Character.isDigit( token.charAt( 4 )))
token = token.substring( 4 );
System.err.println( "Looking for function " + token );
Function f = getFunction( token, usedFunctions );
if ( f == null )
{
System.err.println( "Had to create a new one!" );
if (( token != null ) && ( token.charAt( 0 ) == '=' ) && ( token.indexOf( '/' ) != -1 ))
f = new ExternalFunction();
else
f = new Function();
f.setName( token );
}
else
System.err.println( "Found it!" );
token = getNextField( st, delim ); // get the function code (field 2)
if ( token != null )
{
Hex hex = null;
if ( f.isExternal())
{
ExternalFunction ef = ( ExternalFunction )f;
String name = ef.getName();
int slash = name.indexOf( '/' );
String devName = name.substring( 1, slash );
ef.setDeviceTypeAliasName( devName );
int space = name.indexOf( ' ', slash + 1 );
String codeString = null;
if ( space == -1 )
codeString = name.substring( slash + 1 );
else
codeString = name.substring( slash + 1, space );
ef.setSetupCode( Integer.parseInt( codeString ));
- if ( token.startsWith( "h") || token.endsWith( "h") || (token.indexOf( ' ' ) != -1 ))
+ if (( token.indexOf( 'h' ) != -1 ) || ( token.indexOf( '$') != -1 ) || (token.indexOf( ' ' ) != -1 ))
{
hex = new Hex( token );
ef.setType( ExternalFunction.HexType );
}
else
{
hex = new Hex( 1 );
protocol.efc2hex( new EFC( token ), hex, 0 );
ef.setType( ExternalFunction.EFCType );
}
+ getNextField( st, delim ); // skip byte2 (field 3)
}
else
{
hex = protocol.getDefaultCmd();
protocol.importCommand( hex, token, useOBC, obcIndex, useEFC );
token = getNextField( st, delim ); // get byte2 (field 3)
if ( token != null )
protocol.importCommandParms( hex, token );
}
f.setHex( hex );
}
else
{
token = getNextField( st, delim ); // skip field 3
}
String actualName = getNextField( st, delim ); // get assigned button name (field 4)
System.err.println( "actualName='" + actualName + "'" );
if (( actualName != null ) && actualName.length() == 0 )
actualName = null;
String buttonName = null;
if ( actualName != null )
{
if ( i < genericButtonNames.length )
buttonName = genericButtonNames[ i ];
else
{
System.err.println( "No generic name available!" );
Button b = remote.getButton( actualName );
if ( b == null )
b = remote.getButton( actualName.replace( ' ', '_' ));
if ( b != null )
buttonName = b.getStandardName();
}
}
Button b = null;
if ( buttonName != null )
{
System.err.println( "Searching for button w/ name " + buttonName );
b = remote.findByStandardName( new Button( buttonName, null, ( byte )0, remote ));
System.err.println( "Found button " + b );
}
else
System.err.println( "No buttonName for actualName=" + actualName + " and i=" + i );
token = getNextField( st, delim ); // get normal function (field 5)
if (( buttonName != null ) && ( token != null ) &&
Character.isDigit( token.charAt( 0 )) &&
Character.isDigit( token.charAt( 1 )) &&
( token.charAt( 2 ) == ' ' ) &&
( token.charAt( 3 ) == '-' ) &&
( token.charAt( 4 ) == ' ' ))
{
String name = token.substring( 5 );
if (( name.length() == 5 ) && name.startsWith( "num " ) &&
Character.isDigit( name.charAt( 4 )))
name = name.substring( 4 );
Function func = null;
if (( f.getName() != null ) && f.getName().equalsIgnoreCase( name ))
func = f;
else
{
func = getFunction( name, functions );
if ( func == null )
func = getFunction( name, usedFunctions );
}
if ( func == null )
{
System.err.println( "Creating new function " + name );
if (( name.charAt( 0 ) == '=' ) && ( name.indexOf( '/' ) != -1 ))
func = new ExternalFunction();
else
func = new Function();
func.setName( name );
if ( b != null )
usedFunctions.add( func );
}
else
System.err.println( "Found function " + name );
if ( b == null )
{
Vector temp = new Vector( 2 );
temp.add( name );
temp.add( actualName );
unassigned.add( temp );
System.err.println( "Couldn't find button " + buttonName + " to assign function " + name );
}
else if ( loadButtons )
{
System.err.println( "Setting function " + name + " on button " + b );
b.setFunction( func );
}
}
token = getNextField( st, delim ); // get notes (field 6)
if ( token != null )
f.setNotes( token );
if ( !f.isEmpty())
{
if ( f.isExternal())
extFunctions.add( f );
else
functions.add( f );
}
String pidStr = getNextField( st, delim ); // field 7
String fixedDataStr = getNextField( st, delim ); // field 8
if (( combiner != null ) && ( pidStr != null ) && // ( fixedDataStr != null ) &&
!pidStr.equals( "Protocol ID" )) // && !fixedDataStr.equals( "Fixed Data" )
{
Hex fixedData = new Hex();
if ( fixedDataStr != null )
fixedData = new Hex( fixedDataStr );
Hex newPid = new Hex( pidStr );
Vector protocols = protocolManager.findByPID( newPid );
boolean foundMatch = false;
for ( Enumeration e = protocols.elements(); e.hasMoreElements(); )
{
Protocol p = ( Protocol )e.nextElement();
if ( !remote.supportsVariant( newPid, p.getVariantName()))
continue;
CombinerDevice dev = new CombinerDevice( p, fixedData );
Hex calculatedFixedData = dev.getFixedData();
if ( !calculatedFixedData.equals( fixedData ))
continue;
combiner.add( dev );
foundMatch = true;
break;
}
if ( !foundMatch )
{
ManualProtocol p = new ManualProtocol( newPid, new Properties());
p.setRawHex( fixedData );
combiner.add( new CombinerDevice( p, null, null ));
}
}
// skip to field 13
for ( int j = 8; j < 13; j++ )
token = getNextField( st, delim );
if ( token != null )
{
String name = token.substring( 5 );
if (( name.length() == 5 ) && name.startsWith( "num " ) &&
Character.isDigit( token.charAt( 4 )))
name = name.substring( 4 );
Function func = getFunction( name, functions );
if ( func == null )
func = getFunction( name, extFunctions );
if ( func == null )
{
if (( name.charAt( 0 ) == '=' ) && ( name.indexOf( '/' ) != -1 ))
func = new ExternalFunction();
else
func = new Function();
func.setName( name );
usedFunctions.add( func );
}
if ( b == null )
{
Vector temp = new Vector( 2 );
temp.add( name );
temp.add( "shift-" + buttonName );
unassigned.add( temp );
}
else if ( loadButtons )
b.setShiftedFunction( func );
}
}
while (( line = in.readLine()) != null )
{
st = new StringTokenizer( line, delim );
token = getNextField( st, delim );
if ( token != null )
{
if ( token.equals( "Line Notes:" ) || token.equals( "Notes:" ))
{
StringBuffer buff = new StringBuffer();
boolean first = true;
String tempDelim = null;
while (( line = in.readLine()) != null )
{
if ( line.charAt( 0 ) == '"' )
tempDelim = "\"";
else
tempDelim = delim;
st = new StringTokenizer( line, tempDelim );
if ( st.hasMoreTokens())
{
token = st.nextToken();
if ( token.startsWith( "EOF Marker" ))
break;
if ( first )
first = false;
else
buff.append( "\n" );
buff.append( token.trim());
}
else
buff.append( "\n" );
}
notes = buff.toString().trim();
if ( protocol.getClass() == ManualProtocol.class )
protocol.importUpgradeCode( notes );
}
}
}
if ( !unassigned.isEmpty())
{
System.err.println( "Removing undefined functions from usedFunctions" );
for( ListIterator i = unassigned.listIterator(); i.hasNext(); )
{
Vector temp = ( Vector )i.next();
String funcName = ( String )temp.elementAt( 0 );
System.err.print( "Checking '" + funcName + "'" );
Function f = getFunction( funcName, usedFunctions );
if (( f == null ) || ( f.getHex() == null ) || ( f.getHex().length() == 0 ))
{
System.err.println( "Removing function " + f + ", which has name '" + funcName + "'" );
i.remove();
}
}
}
if ( !unassigned.isEmpty())
{
String message = "Some of the functions defined in the imported device upgrade " +
"were assigned to buttons that could not be matched by name. " +
"The functions and the corresponding button names are listed below." +
"\n\nPlease post this information in the \"JP1 - Software\" section of the " +
"JP1 Forums at www.hifi-remote.com" +
"\n\nUse the Button or Layout panel to assign those functions properly.";
JFrame frame = new JFrame( "Import Failure" );
Container container = frame.getContentPane();
JTextArea text = new JTextArea( message );
text.setEditable( false );
text.setLineWrap( true );
text.setWrapStyleWord( true );
text.setBackground( container.getBackground() );
text.setBorder( BorderFactory.createEmptyBorder( 5, 5, 5, 5 ));
container.add( text, BorderLayout.NORTH );
Vector titles = new Vector();
titles.add( "Function name" );
titles.add( "Button name" );
JTable table = new JTable( unassigned, titles );
Dimension d = table.getPreferredScrollableViewportSize();
d.height = d.height / 4;
table.setPreferredScrollableViewportSize( d );
container.add( new JScrollPane( table ), BorderLayout.CENTER );
frame.pack();
frame.setLocationRelativeTo( KeyMapMaster.getKeyMapMaster());
frame.show();
}
Button[] buttons = remote.getUpgradeButtons();
System.err.println( "Removing assigned functions with no hex!" );
for ( int i = 0; i < buttons.length; i++ )
{
Button b = buttons[ i ];
Function f = b.getFunction();
if (( f != null ) && ( f.getHex() == null ))
b.setFunction( null );
f = b.getShiftedFunction();
if (( f != null ) && ( f.getHex() == null ))
b.setShiftedFunction( null );
f = b.getXShiftedFunction();
if (( f != null ) && ( f.getHex() == null ))
b.setXShiftedFunction( null );
}
System.err.println( "Done!" );
}
public Value[] getParmValues()
{
return parmValues;
}
public void setParmValues( Value[] parmValues )
{
this.parmValues = parmValues;
}
public static final String[] getDeviceTypeAliasNames()
{
return deviceTypeAliasNames;
}
public void autoAssignFunctions()
{
autoAssignFunctions( functions );
autoAssignFunctions( extFunctions );
}
private void autoAssignFunctions( Vector funcs )
{
Button[] buttons = remote.getUpgradeButtons();
for ( Enumeration e = funcs.elements(); e.hasMoreElements(); )
{
Function func = ( Function )e.nextElement();
if ( func.getHex() != null )
{
for ( int i = 0; i < buttons.length; i++ )
{
Button b = buttons[ i ];
if ( b.getFunction() == null )
{
if ( b.getName().equalsIgnoreCase( func.getName()) ||
b.getStandardName().equalsIgnoreCase( func.getName()))
{
b.setFunction( func );
break;
}
}
}
}
}
}
private String description = null;
private int setupCode = 0;
private Remote remote = null;
private String devTypeAliasName = null;
private Protocol protocol = null;
private Value[] parmValues = new Value[ 0 ];
private String notes = null;
private Vector functions = new Vector();
private Vector extFunctions = new Vector();
private Vector keymoves = new Vector();
private File file = null;
private static final String[] deviceTypeAliasNames =
{
"Cable", "TV", "VCR", "CD", "Tuner", "DVD", "SAT", "Tape", "Laserdisc",
"DAT", "Home Auto", "Misc Audio", "Phono", "Video Acc", "Amp", "PVR", "OEM Mode"
};
private static final String[] defaultFunctionNames =
{
"0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
"vol up", "vol down", "mute",
"channel up", "channel down",
"power", "enter", "tv/vcr",
"last (prev ch)", "menu", "program guide", "up arrow", "down arrow",
"left arrow", "right arrow", "select", "sleep", "pip on/off", "display",
"pip swap", "pip move", "play", "pause", "rewind", "fast fwd", "stop",
"record", "exit", "surround", "input toggle", "+100", "fav/scan",
"device button", "next track", "prev track", "shift-left", "shift-right",
"pip freeze", "slow", "eject", "slow+", "slow-", "X2", "center", "rear"
};
private final static String[] genericButtonNames =
{
"0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
"vol up", "vol down", "mute",
"channel up", "channel down",
"power", "enter", "tv/vcr", "prev ch", "menu", "guide",
"up arrow", "down arrow", "left arrow", "right arrow", "select",
"sleep", "pip on/off", "display", "pip swap", "pip move",
"play", "pause", "rewind", "fast fwd", "stop", "record",
"exit", "surround", "input", "+100", "fav/scan",
"device button", "next track", "prev track", "shift-left", "shift-right",
"pip freeze", "slow", "eject", "slow+", "slow-", "x2", "center", "rear",
"phantom1", "phantom2", "phantom3", "phantom4", "phantom5", "phantom6",
"phantom7", "phantom8", "phantom9", "phantom10",
"setup", "light", "theater",
"macro1", "macro2", "macro3", "macro4",
"learn1", "learn2", "learn3", "learn4" // ,
// "button85", "button86", "button87", "button88", "button89", "button90",
// "button91", "button92", "button93", "button94", "button95", "button96",
// "button97", "button98", "button99", "button100", "button101", "button102",
// "button103", "button104", "button105", "button106", "button107", "button108",
// "button109", "button110", "button112", "button113", "button114", "button115",
// "button116", "button117", "button118", "button119", "button120", "button121",
// "button122", "button123", "button124", "button125", "button126", "button127",
// "button128", "button129", "button130", "button131", "button132", "button133",
// "button134", "button135", "button136"
};
}
| false | true | public void importUpgrade( BufferedReader in, boolean loadButtons )
throws Exception
{
String line = in.readLine(); // line 1
String token = line.substring( 0, 5 );
if ( !token.equals( "Name:" ))
{
JOptionPane.showMessageDialog( KeyMapMaster.getKeyMapMaster(),
"The upgrade you are trying to import is not valid!",
"Import Failure", JOptionPane.ERROR_MESSAGE );
return;
}
String delim = line.substring( 5, 6 );
StringTokenizer st = new StringTokenizer( line, delim, true );
getNextField( st, delim );
description = getNextField( st, delim );
String protocolLine = in.readLine(); // line 3
String manualLine = in.readLine(); // line 4
line = in.readLine(); // line 5
st = new StringTokenizer( line, delim );
st.nextToken();
token = st.nextToken();
setupCode = Integer.parseInt( token );
token = st.nextToken();
String str = token.substring( 5 );
remote = RemoteManager.getRemoteManager().findRemoteByName( str );
Hex pid = null;
while ( true )
{
line = in.readLine();
if (( line != null ) && ( line.length() > 0 ) && ( line.charAt( 0 ) == '\"' ))
line = line.substring( 1 );
int equals = line.indexOf( '=' );
if (( equals != -1 ) && line.substring( 0, equals ).toLowerCase().startsWith( "upgrade code " ))
{
int[] id = new int[ 2 ];
int temp = Integer.parseInt( line.substring( equals + 2, equals + 4 ), 16 );
if (( temp & 8 ) != 0 )
id[ 0 ] = 1;
line = in.readLine();
temp = Integer.parseInt( line.substring( 0, 2 ), 16 );
id[ 1 ] = temp;
pid = new Hex( id );
break;
}
}
remote.load();
token = st.nextToken();
str = token.substring( 5 );
if ( remote.getDeviceTypeByAliasName( str ) == null )
{
String rc = null;
String msg = "Remote \"" + remote.getName() + "\" does not support the device type " +
str + ". Please select one of the supported device types below to use instead.\n";
while ( rc == null )
{
rc = ( String )JOptionPane.showInputDialog( KeyMapMaster.getKeyMapMaster(),
msg,
"Unsupported Device Type",
JOptionPane.ERROR_MESSAGE,
null,
remote.getDeviceTypeAliasNames(),
null );
}
str = rc;
}
setDeviceTypeAliasName( str );
String buttonStyle = st.nextToken();
st = new StringTokenizer( protocolLine, delim, true );
getNextField( st, delim ); // skip header
String protocolName = getNextField( st, delim ); // protocol name
ProtocolManager protocolManager = ProtocolManager.getProtocolManager();
if ( protocolName.equals( "Manual Settings" ))
{
System.err.println( "protocolName=" + protocolName );
System.err.println( "manualLine=" + manualLine );
StringTokenizer manual = new StringTokenizer( manualLine, delim, true );
System.err.println( "skipping " + getNextField( manual, delim )); // skip header
String pidStr = getNextField( manual, delim );
System.err.println( "pid=" + pidStr );
if ( pidStr != null )
{
int space = pidStr.indexOf( ' ' );
if ( space != -1 )
{
pid = new Hex( pidStr );
}
else
{
int pidInt = Integer.parseInt( pidStr, 16 );
int[] data = new int[ 2 ];
data[ 0 ] = ( pidInt & 0xFF00 ) >> 8;
data[ 1 ] = pidInt & 0xFF;
pid = new Hex( data );
}
}
int byte2 = Integer.parseInt( getNextField( manual, delim ).substring( 0, 1 ));
System.err.println( "byte2=" + byte2 );
String signalStyle = getNextField( manual, delim );
System.err.println( "SignalStyle=" + signalStyle );
String bitsStr = getNextField( manual, delim );
int devBits = Integer.parseInt( bitsStr.substring( 0, 1 ), 16);
int cmdBits = Integer.parseInt( bitsStr.substring( 1 ), 16 );
System.err.println( "devBits=" + devBits + " and cmdBits=" + cmdBits );
Vector values = new Vector();
str = getNextField( st, delim ); // Device 1
if ( str != null )
values.add( new Integer( str ));
str = getNextField( st, delim ); // Device 2
if ( str != null )
values.add( new Integer( str ));
str = getNextField( st, delim ); // Device 3
if ( str != null )
values.add( new Integer( str ));
str = getNextField( st, delim ); // Raw Fixed Data
if ( str == null )
str = "";
int[] rawHex = Hex.parseHex( str );
protocol = new ManualProtocol( protocolName, pid, byte2, signalStyle, devBits, values, rawHex, cmdBits );
protocolName = protocol.getName();
setParmValues( protocol.getDeviceParmValues());
protocolManager.add( protocol );
}
else
{
// protocol = protocolManager.findProtocolForRemote( remote, protocolName );
Protocol p = protocolManager.findNearestProtocol( protocolName, pid, null );
if ( p == null )
{
p = protocolManager.findProtocolByOldName( remote, protocolName, pid );
if ( p == null )
{
JOptionPane.showMessageDialog( KeyMapMaster.getKeyMapMaster(),
"No protocol found with name=\"" + protocolName +
"\" for remote \"" + remote.getName() + "\".",
"Import Failure", JOptionPane.ERROR_MESSAGE );
reset();
return;
}
}
protocol = p;
Value[] importParms = new Value[ 4 ];
for ( int i = 0; i < importParms.length; i++ )
{
token = getNextField( st, delim );
Object val = null;
if ( token == null )
val = null;
else
{
if ( token.equals( "true" ))
val = new Integer( 1 );
else if ( token.equals( "false" ))
val = new Integer( 0 );
else
val = token;
// val = new Integer( token );
}
importParms[ i ] = new Value( val );
}
protocol.importDeviceParms( importParms );
parmValues = protocol.getDeviceParmValues();
}
// compute cmdIndex
boolean useOBC = false;
boolean useEFC = false;
if ( buttonStyle.equals( "OBC" ))
useOBC = true;
else if ( buttonStyle.equals( "EFC" ))
useEFC = true;
int obcIndex = -1;
CmdParameter[] cmdParms = protocol.getCommandParameters();
for ( obcIndex = 0; obcIndex < cmdParms.length; obcIndex++ )
{
if ( cmdParms[ obcIndex ].getName().equals( "OBC" ))
break;
}
String match1 = "fFunctions" + delim;
String match2 = "Functions" + delim;
if ( useOBC )
{
match1 = match1 + "fOBC" + delim;
match2 = match2 + "OBC" + delim;
}
else
{
match1 = match1 + "fEFC" + delim;
match2 = match2 + "EFC" + delim;
}
while ( true )
{
line = in.readLine();
if ( line.startsWith( match1 ) || line.startsWith( match2 ))
break;
}
functions.clear();
DeviceCombiner combiner = null;
if ( protocol.getClass() == DeviceCombiner.class )
combiner = ( DeviceCombiner )protocol;
Vector unassigned = new Vector();
Vector usedFunctions = new Vector();
for ( int i = 0; i < 128; i++ )
{
line = in.readLine();
st = new StringTokenizer( line, delim, true );
token = getNextField( st, delim ); // get the name (field 1)
if (( token != null ) && ( token.length() == 5 ) &&
token.startsWith( "num " ) && Character.isDigit( token.charAt( 4 )))
token = token.substring( 4 );
System.err.println( "Looking for function " + token );
Function f = getFunction( token, usedFunctions );
if ( f == null )
{
System.err.println( "Had to create a new one!" );
if (( token != null ) && ( token.charAt( 0 ) == '=' ) && ( token.indexOf( '/' ) != -1 ))
f = new ExternalFunction();
else
f = new Function();
f.setName( token );
}
else
System.err.println( "Found it!" );
token = getNextField( st, delim ); // get the function code (field 2)
if ( token != null )
{
Hex hex = null;
if ( f.isExternal())
{
ExternalFunction ef = ( ExternalFunction )f;
String name = ef.getName();
int slash = name.indexOf( '/' );
String devName = name.substring( 1, slash );
ef.setDeviceTypeAliasName( devName );
int space = name.indexOf( ' ', slash + 1 );
String codeString = null;
if ( space == -1 )
codeString = name.substring( slash + 1 );
else
codeString = name.substring( slash + 1, space );
ef.setSetupCode( Integer.parseInt( codeString ));
if ( token.startsWith( "h") || token.endsWith( "h") || (token.indexOf( ' ' ) != -1 ))
{
hex = new Hex( token );
ef.setType( ExternalFunction.HexType );
}
else
{
hex = new Hex( 1 );
protocol.efc2hex( new EFC( token ), hex, 0 );
ef.setType( ExternalFunction.EFCType );
}
}
else
{
hex = protocol.getDefaultCmd();
protocol.importCommand( hex, token, useOBC, obcIndex, useEFC );
token = getNextField( st, delim ); // get byte2 (field 3)
if ( token != null )
protocol.importCommandParms( hex, token );
}
f.setHex( hex );
}
else
{
token = getNextField( st, delim ); // skip field 3
}
String actualName = getNextField( st, delim ); // get assigned button name (field 4)
System.err.println( "actualName='" + actualName + "'" );
if (( actualName != null ) && actualName.length() == 0 )
actualName = null;
String buttonName = null;
if ( actualName != null )
{
if ( i < genericButtonNames.length )
buttonName = genericButtonNames[ i ];
else
{
System.err.println( "No generic name available!" );
Button b = remote.getButton( actualName );
if ( b == null )
b = remote.getButton( actualName.replace( ' ', '_' ));
if ( b != null )
buttonName = b.getStandardName();
}
}
Button b = null;
if ( buttonName != null )
{
System.err.println( "Searching for button w/ name " + buttonName );
b = remote.findByStandardName( new Button( buttonName, null, ( byte )0, remote ));
System.err.println( "Found button " + b );
}
else
System.err.println( "No buttonName for actualName=" + actualName + " and i=" + i );
token = getNextField( st, delim ); // get normal function (field 5)
if (( buttonName != null ) && ( token != null ) &&
Character.isDigit( token.charAt( 0 )) &&
Character.isDigit( token.charAt( 1 )) &&
( token.charAt( 2 ) == ' ' ) &&
( token.charAt( 3 ) == '-' ) &&
( token.charAt( 4 ) == ' ' ))
{
String name = token.substring( 5 );
if (( name.length() == 5 ) && name.startsWith( "num " ) &&
Character.isDigit( name.charAt( 4 )))
name = name.substring( 4 );
Function func = null;
if (( f.getName() != null ) && f.getName().equalsIgnoreCase( name ))
func = f;
else
{
func = getFunction( name, functions );
if ( func == null )
func = getFunction( name, usedFunctions );
}
if ( func == null )
{
System.err.println( "Creating new function " + name );
if (( name.charAt( 0 ) == '=' ) && ( name.indexOf( '/' ) != -1 ))
func = new ExternalFunction();
else
func = new Function();
func.setName( name );
if ( b != null )
usedFunctions.add( func );
}
else
System.err.println( "Found function " + name );
if ( b == null )
{
Vector temp = new Vector( 2 );
temp.add( name );
temp.add( actualName );
unassigned.add( temp );
System.err.println( "Couldn't find button " + buttonName + " to assign function " + name );
}
else if ( loadButtons )
{
System.err.println( "Setting function " + name + " on button " + b );
b.setFunction( func );
}
}
token = getNextField( st, delim ); // get notes (field 6)
if ( token != null )
f.setNotes( token );
if ( !f.isEmpty())
{
if ( f.isExternal())
extFunctions.add( f );
else
functions.add( f );
}
String pidStr = getNextField( st, delim ); // field 7
String fixedDataStr = getNextField( st, delim ); // field 8
if (( combiner != null ) && ( pidStr != null ) && // ( fixedDataStr != null ) &&
!pidStr.equals( "Protocol ID" )) // && !fixedDataStr.equals( "Fixed Data" )
{
Hex fixedData = new Hex();
if ( fixedDataStr != null )
fixedData = new Hex( fixedDataStr );
Hex newPid = new Hex( pidStr );
Vector protocols = protocolManager.findByPID( newPid );
boolean foundMatch = false;
for ( Enumeration e = protocols.elements(); e.hasMoreElements(); )
{
Protocol p = ( Protocol )e.nextElement();
if ( !remote.supportsVariant( newPid, p.getVariantName()))
continue;
CombinerDevice dev = new CombinerDevice( p, fixedData );
Hex calculatedFixedData = dev.getFixedData();
if ( !calculatedFixedData.equals( fixedData ))
continue;
combiner.add( dev );
foundMatch = true;
break;
}
if ( !foundMatch )
{
ManualProtocol p = new ManualProtocol( newPid, new Properties());
p.setRawHex( fixedData );
combiner.add( new CombinerDevice( p, null, null ));
}
}
// skip to field 13
for ( int j = 8; j < 13; j++ )
token = getNextField( st, delim );
if ( token != null )
{
String name = token.substring( 5 );
if (( name.length() == 5 ) && name.startsWith( "num " ) &&
Character.isDigit( token.charAt( 4 )))
name = name.substring( 4 );
Function func = getFunction( name, functions );
if ( func == null )
func = getFunction( name, extFunctions );
if ( func == null )
{
if (( name.charAt( 0 ) == '=' ) && ( name.indexOf( '/' ) != -1 ))
func = new ExternalFunction();
else
func = new Function();
func.setName( name );
usedFunctions.add( func );
}
if ( b == null )
{
Vector temp = new Vector( 2 );
temp.add( name );
temp.add( "shift-" + buttonName );
unassigned.add( temp );
}
else if ( loadButtons )
b.setShiftedFunction( func );
}
}
while (( line = in.readLine()) != null )
{
st = new StringTokenizer( line, delim );
token = getNextField( st, delim );
if ( token != null )
{
if ( token.equals( "Line Notes:" ) || token.equals( "Notes:" ))
{
StringBuffer buff = new StringBuffer();
boolean first = true;
String tempDelim = null;
while (( line = in.readLine()) != null )
{
if ( line.charAt( 0 ) == '"' )
tempDelim = "\"";
else
tempDelim = delim;
st = new StringTokenizer( line, tempDelim );
if ( st.hasMoreTokens())
{
token = st.nextToken();
if ( token.startsWith( "EOF Marker" ))
break;
if ( first )
first = false;
else
buff.append( "\n" );
buff.append( token.trim());
}
else
buff.append( "\n" );
}
notes = buff.toString().trim();
if ( protocol.getClass() == ManualProtocol.class )
protocol.importUpgradeCode( notes );
}
}
}
if ( !unassigned.isEmpty())
{
System.err.println( "Removing undefined functions from usedFunctions" );
for( ListIterator i = unassigned.listIterator(); i.hasNext(); )
{
Vector temp = ( Vector )i.next();
String funcName = ( String )temp.elementAt( 0 );
System.err.print( "Checking '" + funcName + "'" );
Function f = getFunction( funcName, usedFunctions );
if (( f == null ) || ( f.getHex() == null ) || ( f.getHex().length() == 0 ))
{
System.err.println( "Removing function " + f + ", which has name '" + funcName + "'" );
i.remove();
}
}
}
if ( !unassigned.isEmpty())
{
String message = "Some of the functions defined in the imported device upgrade " +
"were assigned to buttons that could not be matched by name. " +
"The functions and the corresponding button names are listed below." +
"\n\nPlease post this information in the \"JP1 - Software\" section of the " +
"JP1 Forums at www.hifi-remote.com" +
"\n\nUse the Button or Layout panel to assign those functions properly.";
JFrame frame = new JFrame( "Import Failure" );
Container container = frame.getContentPane();
JTextArea text = new JTextArea( message );
text.setEditable( false );
text.setLineWrap( true );
text.setWrapStyleWord( true );
text.setBackground( container.getBackground() );
text.setBorder( BorderFactory.createEmptyBorder( 5, 5, 5, 5 ));
container.add( text, BorderLayout.NORTH );
Vector titles = new Vector();
titles.add( "Function name" );
titles.add( "Button name" );
JTable table = new JTable( unassigned, titles );
Dimension d = table.getPreferredScrollableViewportSize();
d.height = d.height / 4;
table.setPreferredScrollableViewportSize( d );
container.add( new JScrollPane( table ), BorderLayout.CENTER );
frame.pack();
frame.setLocationRelativeTo( KeyMapMaster.getKeyMapMaster());
frame.show();
}
Button[] buttons = remote.getUpgradeButtons();
System.err.println( "Removing assigned functions with no hex!" );
for ( int i = 0; i < buttons.length; i++ )
{
Button b = buttons[ i ];
Function f = b.getFunction();
if (( f != null ) && ( f.getHex() == null ))
b.setFunction( null );
f = b.getShiftedFunction();
if (( f != null ) && ( f.getHex() == null ))
b.setShiftedFunction( null );
f = b.getXShiftedFunction();
if (( f != null ) && ( f.getHex() == null ))
b.setXShiftedFunction( null );
}
System.err.println( "Done!" );
}
| public void importUpgrade( BufferedReader in, boolean loadButtons )
throws Exception
{
String line = in.readLine(); // line 1
String token = line.substring( 0, 5 );
if ( !token.equals( "Name:" ))
{
JOptionPane.showMessageDialog( KeyMapMaster.getKeyMapMaster(),
"The upgrade you are trying to import is not valid!",
"Import Failure", JOptionPane.ERROR_MESSAGE );
return;
}
String delim = line.substring( 5, 6 );
StringTokenizer st = new StringTokenizer( line, delim, true );
getNextField( st, delim );
description = getNextField( st, delim );
String protocolLine = in.readLine(); // line 3
String manualLine = in.readLine(); // line 4
line = in.readLine(); // line 5
st = new StringTokenizer( line, delim );
st.nextToken();
token = st.nextToken();
setupCode = Integer.parseInt( token );
token = st.nextToken();
String str = token.substring( 5 );
remote = RemoteManager.getRemoteManager().findRemoteByName( str );
Hex pid = null;
while ( true )
{
line = in.readLine();
if (( line != null ) && ( line.length() > 0 ) && ( line.charAt( 0 ) == '\"' ))
line = line.substring( 1 );
int equals = line.indexOf( '=' );
if (( equals != -1 ) && line.substring( 0, equals ).toLowerCase().startsWith( "upgrade code " ))
{
int[] id = new int[ 2 ];
int temp = Integer.parseInt( line.substring( equals + 2, equals + 4 ), 16 );
if (( temp & 8 ) != 0 )
id[ 0 ] = 1;
line = in.readLine();
temp = Integer.parseInt( line.substring( 0, 2 ), 16 );
id[ 1 ] = temp;
pid = new Hex( id );
break;
}
}
remote.load();
token = st.nextToken();
str = token.substring( 5 );
if ( remote.getDeviceTypeByAliasName( str ) == null )
{
String rc = null;
String msg = "Remote \"" + remote.getName() + "\" does not support the device type " +
str + ". Please select one of the supported device types below to use instead.\n";
while ( rc == null )
{
rc = ( String )JOptionPane.showInputDialog( KeyMapMaster.getKeyMapMaster(),
msg,
"Unsupported Device Type",
JOptionPane.ERROR_MESSAGE,
null,
remote.getDeviceTypeAliasNames(),
null );
}
str = rc;
}
setDeviceTypeAliasName( str );
String buttonStyle = st.nextToken();
st = new StringTokenizer( protocolLine, delim, true );
getNextField( st, delim ); // skip header
String protocolName = getNextField( st, delim ); // protocol name
ProtocolManager protocolManager = ProtocolManager.getProtocolManager();
if ( protocolName.equals( "Manual Settings" ))
{
System.err.println( "protocolName=" + protocolName );
System.err.println( "manualLine=" + manualLine );
StringTokenizer manual = new StringTokenizer( manualLine, delim, true );
System.err.println( "skipping " + getNextField( manual, delim )); // skip header
String pidStr = getNextField( manual, delim );
System.err.println( "pid=" + pidStr );
if ( pidStr != null )
{
int space = pidStr.indexOf( ' ' );
if ( space != -1 )
{
pid = new Hex( pidStr );
}
else
{
int pidInt = Integer.parseInt( pidStr, 16 );
int[] data = new int[ 2 ];
data[ 0 ] = ( pidInt & 0xFF00 ) >> 8;
data[ 1 ] = pidInt & 0xFF;
pid = new Hex( data );
}
}
int byte2 = Integer.parseInt( getNextField( manual, delim ).substring( 0, 1 ));
System.err.println( "byte2=" + byte2 );
String signalStyle = getNextField( manual, delim );
System.err.println( "SignalStyle=" + signalStyle );
String bitsStr = getNextField( manual, delim );
int devBits = Integer.parseInt( bitsStr.substring( 0, 1 ), 16);
int cmdBits = Integer.parseInt( bitsStr.substring( 1 ), 16 );
System.err.println( "devBits=" + devBits + " and cmdBits=" + cmdBits );
Vector values = new Vector();
str = getNextField( st, delim ); // Device 1
if ( str != null )
values.add( new Integer( str ));
str = getNextField( st, delim ); // Device 2
if ( str != null )
values.add( new Integer( str ));
str = getNextField( st, delim ); // Device 3
if ( str != null )
values.add( new Integer( str ));
str = getNextField( st, delim ); // Raw Fixed Data
if ( str == null )
str = "";
int[] rawHex = Hex.parseHex( str );
protocol = new ManualProtocol( protocolName, pid, byte2, signalStyle, devBits, values, rawHex, cmdBits );
protocolName = protocol.getName();
setParmValues( protocol.getDeviceParmValues());
protocolManager.add( protocol );
}
else
{
// protocol = protocolManager.findProtocolForRemote( remote, protocolName );
Protocol p = protocolManager.findNearestProtocol( protocolName, pid, null );
if ( p == null )
{
p = protocolManager.findProtocolByOldName( remote, protocolName, pid );
if ( p == null )
{
JOptionPane.showMessageDialog( KeyMapMaster.getKeyMapMaster(),
"No protocol found with name=\"" + protocolName +
"\" for remote \"" + remote.getName() + "\".",
"Import Failure", JOptionPane.ERROR_MESSAGE );
reset();
return;
}
}
protocol = p;
Value[] importParms = new Value[ 4 ];
for ( int i = 0; i < importParms.length; i++ )
{
token = getNextField( st, delim );
Object val = null;
if ( token == null )
val = null;
else
{
if ( token.equals( "true" ))
val = new Integer( 1 );
else if ( token.equals( "false" ))
val = new Integer( 0 );
else
val = token;
// val = new Integer( token );
}
importParms[ i ] = new Value( val );
}
protocol.importDeviceParms( importParms );
parmValues = protocol.getDeviceParmValues();
}
// compute cmdIndex
boolean useOBC = false;
boolean useEFC = false;
if ( buttonStyle.equals( "OBC" ))
useOBC = true;
else if ( buttonStyle.equals( "EFC" ))
useEFC = true;
int obcIndex = -1;
CmdParameter[] cmdParms = protocol.getCommandParameters();
for ( obcIndex = 0; obcIndex < cmdParms.length; obcIndex++ )
{
if ( cmdParms[ obcIndex ].getName().equals( "OBC" ))
break;
}
String match1 = "fFunctions" + delim;
String match2 = "Functions" + delim;
if ( useOBC )
{
match1 = match1 + "fOBC" + delim;
match2 = match2 + "OBC" + delim;
}
else
{
match1 = match1 + "fEFC" + delim;
match2 = match2 + "EFC" + delim;
}
while ( true )
{
line = in.readLine();
if ( line.startsWith( match1 ) || line.startsWith( match2 ))
break;
}
functions.clear();
DeviceCombiner combiner = null;
if ( protocol.getClass() == DeviceCombiner.class )
combiner = ( DeviceCombiner )protocol;
Vector unassigned = new Vector();
Vector usedFunctions = new Vector();
for ( int i = 0; i < 128; i++ )
{
line = in.readLine();
st = new StringTokenizer( line, delim, true );
token = getNextField( st, delim ); // get the name (field 1)
if (( token != null ) && ( token.length() == 5 ) &&
token.startsWith( "num " ) && Character.isDigit( token.charAt( 4 )))
token = token.substring( 4 );
System.err.println( "Looking for function " + token );
Function f = getFunction( token, usedFunctions );
if ( f == null )
{
System.err.println( "Had to create a new one!" );
if (( token != null ) && ( token.charAt( 0 ) == '=' ) && ( token.indexOf( '/' ) != -1 ))
f = new ExternalFunction();
else
f = new Function();
f.setName( token );
}
else
System.err.println( "Found it!" );
token = getNextField( st, delim ); // get the function code (field 2)
if ( token != null )
{
Hex hex = null;
if ( f.isExternal())
{
ExternalFunction ef = ( ExternalFunction )f;
String name = ef.getName();
int slash = name.indexOf( '/' );
String devName = name.substring( 1, slash );
ef.setDeviceTypeAliasName( devName );
int space = name.indexOf( ' ', slash + 1 );
String codeString = null;
if ( space == -1 )
codeString = name.substring( slash + 1 );
else
codeString = name.substring( slash + 1, space );
ef.setSetupCode( Integer.parseInt( codeString ));
if (( token.indexOf( 'h' ) != -1 ) || ( token.indexOf( '$') != -1 ) || (token.indexOf( ' ' ) != -1 ))
{
hex = new Hex( token );
ef.setType( ExternalFunction.HexType );
}
else
{
hex = new Hex( 1 );
protocol.efc2hex( new EFC( token ), hex, 0 );
ef.setType( ExternalFunction.EFCType );
}
getNextField( st, delim ); // skip byte2 (field 3)
}
else
{
hex = protocol.getDefaultCmd();
protocol.importCommand( hex, token, useOBC, obcIndex, useEFC );
token = getNextField( st, delim ); // get byte2 (field 3)
if ( token != null )
protocol.importCommandParms( hex, token );
}
f.setHex( hex );
}
else
{
token = getNextField( st, delim ); // skip field 3
}
String actualName = getNextField( st, delim ); // get assigned button name (field 4)
System.err.println( "actualName='" + actualName + "'" );
if (( actualName != null ) && actualName.length() == 0 )
actualName = null;
String buttonName = null;
if ( actualName != null )
{
if ( i < genericButtonNames.length )
buttonName = genericButtonNames[ i ];
else
{
System.err.println( "No generic name available!" );
Button b = remote.getButton( actualName );
if ( b == null )
b = remote.getButton( actualName.replace( ' ', '_' ));
if ( b != null )
buttonName = b.getStandardName();
}
}
Button b = null;
if ( buttonName != null )
{
System.err.println( "Searching for button w/ name " + buttonName );
b = remote.findByStandardName( new Button( buttonName, null, ( byte )0, remote ));
System.err.println( "Found button " + b );
}
else
System.err.println( "No buttonName for actualName=" + actualName + " and i=" + i );
token = getNextField( st, delim ); // get normal function (field 5)
if (( buttonName != null ) && ( token != null ) &&
Character.isDigit( token.charAt( 0 )) &&
Character.isDigit( token.charAt( 1 )) &&
( token.charAt( 2 ) == ' ' ) &&
( token.charAt( 3 ) == '-' ) &&
( token.charAt( 4 ) == ' ' ))
{
String name = token.substring( 5 );
if (( name.length() == 5 ) && name.startsWith( "num " ) &&
Character.isDigit( name.charAt( 4 )))
name = name.substring( 4 );
Function func = null;
if (( f.getName() != null ) && f.getName().equalsIgnoreCase( name ))
func = f;
else
{
func = getFunction( name, functions );
if ( func == null )
func = getFunction( name, usedFunctions );
}
if ( func == null )
{
System.err.println( "Creating new function " + name );
if (( name.charAt( 0 ) == '=' ) && ( name.indexOf( '/' ) != -1 ))
func = new ExternalFunction();
else
func = new Function();
func.setName( name );
if ( b != null )
usedFunctions.add( func );
}
else
System.err.println( "Found function " + name );
if ( b == null )
{
Vector temp = new Vector( 2 );
temp.add( name );
temp.add( actualName );
unassigned.add( temp );
System.err.println( "Couldn't find button " + buttonName + " to assign function " + name );
}
else if ( loadButtons )
{
System.err.println( "Setting function " + name + " on button " + b );
b.setFunction( func );
}
}
token = getNextField( st, delim ); // get notes (field 6)
if ( token != null )
f.setNotes( token );
if ( !f.isEmpty())
{
if ( f.isExternal())
extFunctions.add( f );
else
functions.add( f );
}
String pidStr = getNextField( st, delim ); // field 7
String fixedDataStr = getNextField( st, delim ); // field 8
if (( combiner != null ) && ( pidStr != null ) && // ( fixedDataStr != null ) &&
!pidStr.equals( "Protocol ID" )) // && !fixedDataStr.equals( "Fixed Data" )
{
Hex fixedData = new Hex();
if ( fixedDataStr != null )
fixedData = new Hex( fixedDataStr );
Hex newPid = new Hex( pidStr );
Vector protocols = protocolManager.findByPID( newPid );
boolean foundMatch = false;
for ( Enumeration e = protocols.elements(); e.hasMoreElements(); )
{
Protocol p = ( Protocol )e.nextElement();
if ( !remote.supportsVariant( newPid, p.getVariantName()))
continue;
CombinerDevice dev = new CombinerDevice( p, fixedData );
Hex calculatedFixedData = dev.getFixedData();
if ( !calculatedFixedData.equals( fixedData ))
continue;
combiner.add( dev );
foundMatch = true;
break;
}
if ( !foundMatch )
{
ManualProtocol p = new ManualProtocol( newPid, new Properties());
p.setRawHex( fixedData );
combiner.add( new CombinerDevice( p, null, null ));
}
}
// skip to field 13
for ( int j = 8; j < 13; j++ )
token = getNextField( st, delim );
if ( token != null )
{
String name = token.substring( 5 );
if (( name.length() == 5 ) && name.startsWith( "num " ) &&
Character.isDigit( token.charAt( 4 )))
name = name.substring( 4 );
Function func = getFunction( name, functions );
if ( func == null )
func = getFunction( name, extFunctions );
if ( func == null )
{
if (( name.charAt( 0 ) == '=' ) && ( name.indexOf( '/' ) != -1 ))
func = new ExternalFunction();
else
func = new Function();
func.setName( name );
usedFunctions.add( func );
}
if ( b == null )
{
Vector temp = new Vector( 2 );
temp.add( name );
temp.add( "shift-" + buttonName );
unassigned.add( temp );
}
else if ( loadButtons )
b.setShiftedFunction( func );
}
}
while (( line = in.readLine()) != null )
{
st = new StringTokenizer( line, delim );
token = getNextField( st, delim );
if ( token != null )
{
if ( token.equals( "Line Notes:" ) || token.equals( "Notes:" ))
{
StringBuffer buff = new StringBuffer();
boolean first = true;
String tempDelim = null;
while (( line = in.readLine()) != null )
{
if ( line.charAt( 0 ) == '"' )
tempDelim = "\"";
else
tempDelim = delim;
st = new StringTokenizer( line, tempDelim );
if ( st.hasMoreTokens())
{
token = st.nextToken();
if ( token.startsWith( "EOF Marker" ))
break;
if ( first )
first = false;
else
buff.append( "\n" );
buff.append( token.trim());
}
else
buff.append( "\n" );
}
notes = buff.toString().trim();
if ( protocol.getClass() == ManualProtocol.class )
protocol.importUpgradeCode( notes );
}
}
}
if ( !unassigned.isEmpty())
{
System.err.println( "Removing undefined functions from usedFunctions" );
for( ListIterator i = unassigned.listIterator(); i.hasNext(); )
{
Vector temp = ( Vector )i.next();
String funcName = ( String )temp.elementAt( 0 );
System.err.print( "Checking '" + funcName + "'" );
Function f = getFunction( funcName, usedFunctions );
if (( f == null ) || ( f.getHex() == null ) || ( f.getHex().length() == 0 ))
{
System.err.println( "Removing function " + f + ", which has name '" + funcName + "'" );
i.remove();
}
}
}
if ( !unassigned.isEmpty())
{
String message = "Some of the functions defined in the imported device upgrade " +
"were assigned to buttons that could not be matched by name. " +
"The functions and the corresponding button names are listed below." +
"\n\nPlease post this information in the \"JP1 - Software\" section of the " +
"JP1 Forums at www.hifi-remote.com" +
"\n\nUse the Button or Layout panel to assign those functions properly.";
JFrame frame = new JFrame( "Import Failure" );
Container container = frame.getContentPane();
JTextArea text = new JTextArea( message );
text.setEditable( false );
text.setLineWrap( true );
text.setWrapStyleWord( true );
text.setBackground( container.getBackground() );
text.setBorder( BorderFactory.createEmptyBorder( 5, 5, 5, 5 ));
container.add( text, BorderLayout.NORTH );
Vector titles = new Vector();
titles.add( "Function name" );
titles.add( "Button name" );
JTable table = new JTable( unassigned, titles );
Dimension d = table.getPreferredScrollableViewportSize();
d.height = d.height / 4;
table.setPreferredScrollableViewportSize( d );
container.add( new JScrollPane( table ), BorderLayout.CENTER );
frame.pack();
frame.setLocationRelativeTo( KeyMapMaster.getKeyMapMaster());
frame.show();
}
Button[] buttons = remote.getUpgradeButtons();
System.err.println( "Removing assigned functions with no hex!" );
for ( int i = 0; i < buttons.length; i++ )
{
Button b = buttons[ i ];
Function f = b.getFunction();
if (( f != null ) && ( f.getHex() == null ))
b.setFunction( null );
f = b.getShiftedFunction();
if (( f != null ) && ( f.getHex() == null ))
b.setShiftedFunction( null );
f = b.getXShiftedFunction();
if (( f != null ) && ( f.getHex() == null ))
b.setXShiftedFunction( null );
}
System.err.println( "Done!" );
}
|
diff --git a/src/ArithmeticOperatorNode.java b/src/ArithmeticOperatorNode.java
index fd2c278..30883c0 100644
--- a/src/ArithmeticOperatorNode.java
+++ b/src/ArithmeticOperatorNode.java
@@ -1,190 +1,190 @@
/*
* Implements Semantic checking and code output generation for
* Addition and Subtraction.
*
* Example - a + 3
* a - 3
* a * 3
* a / 3
*/
/**
* The Class ArithmeticOperatorNode.
* @author Parth and Kshitij
*/
public class ArithmeticOperatorNode extends ASTNode{
/** The arith type. */
private String arithType="";
/*
* Instantiates ArithmeticOperator invoked by this grammar:
* relational_operand '+' term
* relational_operand '-' term
* relational_operand '/' term
* relational_operand '*' term
* relational_operand '%' term
*
* Example:
* a + 3
* a - 3
* a * 3
* a / 3
* a % 3
*
* @param str specifies whether the expression was addition or subtraction
* @param expr represents a relational operand
* @param stmt represents terms
*/
/**
* Instantiates a new arithmetic operator node.
*
* @param str the str
* @param relOp the rel op
* @param terms the terms
* @param yyline the yyline
* @param yycolumn the yycolumn
*/
public ArithmeticOperatorNode(String str, ASTNode relOp, ASTNode terms, int yyline, int yycolumn) {
super(yyline, yycolumn);
addChild(relOp);
addChild(terms);
this.setArithType(str);
// TODO Auto-generated constructor stub
}
/*
*
* Instantiates ArithmeticOperator invoked by this grammar:
*
* Example:
* -a
*
* @param str specifies whether the expression was addition or subtraction
* @param expr represents a relational operand
* @param stmt represents terms
*/
/**
* Instantiates a new arithmetic operator node.
*
* @param str the str
* @param lcNode the lc node
* @param yyline the yyline
* @param yycolumn the yycolumn
*/
public ArithmeticOperatorNode(String str, ASTNode lcNode, int yyline, int yycolumn) {
super(yyline, yycolumn);
this.addChild(lcNode);
this.setArithType(str);
}
/*
* Checks the semantics to make sure that integer is being operated with an integer.
* Implicit conversions are not allowed
* Throw an exception otherwise.
* (non-Javadoc)
* @see ASTNode#checkSemantics()
*/
@Override
public void checkSemantics() throws Exception {
// TODO Auto-generated method stub
this.getChildAt(0).checkSemantics();
if (this.getChildCount() > 1)
this.getChildAt(1).checkSemantics();
/*
* The grammar should look into that only boolean expressions or relational expressions are executed.
*/
//for unary minus
if(this.getChildCount() == 1)
{
if (!(this.getChildAt(0).getType().equalsIgnoreCase("int")
|| this.getChildAt(0).getType().equalsIgnoreCase("double")))
{
- throw new Exception("Type mismatch: statement at Line " + this.getYyline() + ":" +
- this.getYycolumn()+"should be of the same type. Unary");
+ throw new Exception("Invalid operand on line " + this.getYyline() + ":" +
+ this.getYycolumn()+ " cannot compute unary minus on type " + this.getChildAt(0).getType());
}
if(this.getChildAt(0).getType().equals("double"))
this.setType("double");
else
this.setType("int");
}
else
{
if(!((this.getChildAt(0).getType().equals("double") || this.getChildAt(0).getType().equals("int"))
&& (this.getChildAt(1).getType().equals("double") || this.getChildAt(1).getType().equals("int"))))
{
throw new Exception("Cannot do Arithmetic operation on "+this.getChildAt(0).getType()+ " & " +
this.getChildAt(1).getType()+" on line "+ this.getYyline() + ":" +
this.getYycolumn());
}
if(this.getChildAt(0).getType().equals("double") || this.getChildAt(1).getType().equals("double"))
this.setType("double");
else
this.setType("int");
}
}
/* (non-Javadoc)
* @see ASTNode#generateCode()
*/
@Override
public StringBuffer generateCode() {
// TODO Auto-generated method stub
// Should use arithType
StringBuffer output = new StringBuffer();
if(this.getChildCount() > 1)
{
output.append(this.getChildAt(0).generateCode());
if ("multiplication".equalsIgnoreCase(getArithType()))
{
output.append(" * ");
}
else if ("division".equalsIgnoreCase(getArithType()))
{
output.append(" / ");
}
else if ("addition".equalsIgnoreCase(getArithType()))
{
output.append(" + ");
}
else if ("subtraction".equalsIgnoreCase(getArithType()))
{
output.append(" - ");
}
else if ("modulus".equalsIgnoreCase(getArithType()))
{
output.append(" % ");
}
output.append(this.getChildAt(1).generateCode());
}
else
{
output.append(" - ");
output.append(this.getChildAt(0).generateCode());
}
return output;
}
/**
* @return the arithType
*/
public String getArithType() {
return arithType;
}
/**
* @param arithType the arithType to set
*/
public void setArithType(String arithType) {
this.arithType = arithType;
}
}
| true | true | public void checkSemantics() throws Exception {
// TODO Auto-generated method stub
this.getChildAt(0).checkSemantics();
if (this.getChildCount() > 1)
this.getChildAt(1).checkSemantics();
/*
* The grammar should look into that only boolean expressions or relational expressions are executed.
*/
//for unary minus
if(this.getChildCount() == 1)
{
if (!(this.getChildAt(0).getType().equalsIgnoreCase("int")
|| this.getChildAt(0).getType().equalsIgnoreCase("double")))
{
throw new Exception("Type mismatch: statement at Line " + this.getYyline() + ":" +
this.getYycolumn()+"should be of the same type. Unary");
}
if(this.getChildAt(0).getType().equals("double"))
this.setType("double");
else
this.setType("int");
}
else
{
if(!((this.getChildAt(0).getType().equals("double") || this.getChildAt(0).getType().equals("int"))
&& (this.getChildAt(1).getType().equals("double") || this.getChildAt(1).getType().equals("int"))))
{
throw new Exception("Cannot do Arithmetic operation on "+this.getChildAt(0).getType()+ " & " +
this.getChildAt(1).getType()+" on line "+ this.getYyline() + ":" +
this.getYycolumn());
}
if(this.getChildAt(0).getType().equals("double") || this.getChildAt(1).getType().equals("double"))
this.setType("double");
else
this.setType("int");
}
}
| public void checkSemantics() throws Exception {
// TODO Auto-generated method stub
this.getChildAt(0).checkSemantics();
if (this.getChildCount() > 1)
this.getChildAt(1).checkSemantics();
/*
* The grammar should look into that only boolean expressions or relational expressions are executed.
*/
//for unary minus
if(this.getChildCount() == 1)
{
if (!(this.getChildAt(0).getType().equalsIgnoreCase("int")
|| this.getChildAt(0).getType().equalsIgnoreCase("double")))
{
throw new Exception("Invalid operand on line " + this.getYyline() + ":" +
this.getYycolumn()+ " cannot compute unary minus on type " + this.getChildAt(0).getType());
}
if(this.getChildAt(0).getType().equals("double"))
this.setType("double");
else
this.setType("int");
}
else
{
if(!((this.getChildAt(0).getType().equals("double") || this.getChildAt(0).getType().equals("int"))
&& (this.getChildAt(1).getType().equals("double") || this.getChildAt(1).getType().equals("int"))))
{
throw new Exception("Cannot do Arithmetic operation on "+this.getChildAt(0).getType()+ " & " +
this.getChildAt(1).getType()+" on line "+ this.getYyline() + ":" +
this.getYycolumn());
}
if(this.getChildAt(0).getType().equals("double") || this.getChildAt(1).getType().equals("double"))
this.setType("double");
else
this.setType("int");
}
}
|
diff --git a/src/main/java/me/m0r13/maptools/MarkerUpdateTask.java b/src/main/java/me/m0r13/maptools/MarkerUpdateTask.java
index fa6beea..bc2ae1e 100644
--- a/src/main/java/me/m0r13/maptools/MarkerUpdateTask.java
+++ b/src/main/java/me/m0r13/maptools/MarkerUpdateTask.java
@@ -1,77 +1,78 @@
/*
* Copyright 2013 Moritz Hilscher
*
* This file is part of MapTools.
*
* MapTools 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.
*
* MapTools 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 MapTools. If not, see <http://www.gnu.org/licenses/>.
*/
package me.m0r13.maptools;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.World.Environment;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
public class MarkerUpdateTask extends BukkitRunnable {
private MapToolsPlugin plugin;
public MarkerUpdateTask(MapToolsPlugin plugin) {
this.plugin = plugin;
}
@Override
public void run() {
writePlayers(plugin.getServer().getOnlinePlayers());
}
public void writePlayers(Player[] players) {
JSONArray playersJson = new JSONArray();
for (Player player : players) {
JSONObject json = new JSONObject();
Location pos = player.getLocation();
+ World world = player.getWorld();
json.put("username", player.getName());
json.put("x", pos.getX());
json.put("y", pos.getY());
json.put("z", pos.getZ());
json.put("world", world.getName());
json.put("dimension", world.getEnvironment().toString());
json.put("health", player.getHealth());
json.put("saturation", player.getSaturation());
playersJson.add(json);
}
JSONObject json = new JSONObject();
json.put("players", playersJson);
try {
File file = new File(plugin.getConfig().getString("markerFile"));
BufferedWriter output = new BufferedWriter(new FileWriter(file));
output.write(json.toJSONString());
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| true | true | public void writePlayers(Player[] players) {
JSONArray playersJson = new JSONArray();
for (Player player : players) {
JSONObject json = new JSONObject();
Location pos = player.getLocation();
json.put("username", player.getName());
json.put("x", pos.getX());
json.put("y", pos.getY());
json.put("z", pos.getZ());
json.put("world", world.getName());
json.put("dimension", world.getEnvironment().toString());
json.put("health", player.getHealth());
json.put("saturation", player.getSaturation());
playersJson.add(json);
}
JSONObject json = new JSONObject();
json.put("players", playersJson);
try {
File file = new File(plugin.getConfig().getString("markerFile"));
BufferedWriter output = new BufferedWriter(new FileWriter(file));
output.write(json.toJSONString());
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
| public void writePlayers(Player[] players) {
JSONArray playersJson = new JSONArray();
for (Player player : players) {
JSONObject json = new JSONObject();
Location pos = player.getLocation();
World world = player.getWorld();
json.put("username", player.getName());
json.put("x", pos.getX());
json.put("y", pos.getY());
json.put("z", pos.getZ());
json.put("world", world.getName());
json.put("dimension", world.getEnvironment().toString());
json.put("health", player.getHealth());
json.put("saturation", player.getSaturation());
playersJson.add(json);
}
JSONObject json = new JSONObject();
json.put("players", playersJson);
try {
File file = new File(plugin.getConfig().getString("markerFile"));
BufferedWriter output = new BufferedWriter(new FileWriter(file));
output.write(json.toJSONString());
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
|
diff --git a/maven-amps-plugin/src/main/java/com/atlassian/maven/plugins/amps/product/BambooProductHandler.java b/maven-amps-plugin/src/main/java/com/atlassian/maven/plugins/amps/product/BambooProductHandler.java
index aebf4f84..d12da512 100644
--- a/maven-amps-plugin/src/main/java/com/atlassian/maven/plugins/amps/product/BambooProductHandler.java
+++ b/maven-amps-plugin/src/main/java/com/atlassian/maven/plugins/amps/product/BambooProductHandler.java
@@ -1,99 +1,99 @@
package com.atlassian.maven.plugins.amps.product;
import com.atlassian.maven.plugins.amps.MavenGoals;
import com.atlassian.maven.plugins.amps.Product;
import com.atlassian.maven.plugins.amps.ProductArtifact;
import com.atlassian.maven.plugins.amps.util.ConfigFileUtils;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.project.MavenProject;
import java.io.File;
import java.util.*;
public class BambooProductHandler extends AbstractWebappProductHandler
{
public BambooProductHandler(MavenProject project, MavenGoals goals)
{
super(project, goals, new BambooPluginProvider());
}
public String getId()
{
return "bamboo";
}
public ProductArtifact getArtifact()
{
return new ProductArtifact("com.atlassian.bamboo", "atlassian-bamboo-web-app", "RELEASE");
}
protected Collection<ProductArtifact> getSalArtifacts(String salVersion)
{
return Arrays.asList(
new ProductArtifact("com.atlassian.sal", "sal-api", salVersion),
new ProductArtifact("com.atlassian.sal", "sal-bamboo-plugin", salVersion));
}
public ProductArtifact getTestResourcesArtifact()
{
return new ProductArtifact("com.atlassian.bamboo.plugins", "bamboo-plugin-test-resources", "LATEST");
}
public int getDefaultHttpPort()
{
return 6990;
}
public Map<String, String> getSystemProperties(Product ctx)
{
return Collections.singletonMap("bamboo.home", getHomeDirectory(ctx).getPath());
}
@Override
public File getUserInstalledPluginsDirectory(final File webappDir, final File homeDir)
{
return new File(homeDir, "plugins");
}
public List<ProductArtifact> getExtraContainerDependencies()
{
return Collections.emptyList();
}
public String getBundledPluginPath(Product ctx)
{
return "WEB-INF/classes/atlassian-bundled-plugins.zip";
}
public void processHomeDirectory(final Product ctx, final File homeDir) throws MojoExecutionException
{
ConfigFileUtils.replace(new File(homeDir, "bamboo.cfg.xml"), "@project-dir@", homeDir.getParent());
ConfigFileUtils.replace(new File(homeDir, "bamboo.cfg.xml"), "/bamboo-home/", "/home/");
ConfigFileUtils.replace(new File(homeDir, "bamboo.cfg.xml"), "${bambooHome}", homeDir.getAbsolutePath());
ConfigFileUtils.replaceAll(new File(homeDir, "/xml-data/configuration/administration.xml"),
- "http://[^:]+:8085", "http://" + ctx.getServer() + ":" + ctx.getHttpPort() + "/" + ctx.getContextPath().replaceAll("^/|/$", ""));
+ "http://(?:[^:]|\\[.+])+:8085", "http://" + ctx.getServer() + ":" + ctx.getHttpPort() + "/" + ctx.getContextPath().replaceAll("^/|/$", ""));
}
public List<ProductArtifact> getDefaultLibPlugins()
{
return Collections.emptyList();
}
public List<ProductArtifact> getDefaultBundledPlugins()
{
return Collections.emptyList();
}
private static class BambooPluginProvider extends AbstractPluginProvider
{
@Override
protected Collection<ProductArtifact> getSalArtifacts(String salVersion)
{
return Arrays.asList(
new ProductArtifact("com.atlassian.sal", "sal-api", salVersion),
new ProductArtifact("com.atlassian.sal", "sal-bamboo-plugin", salVersion));
}
}
}
| true | true | public void processHomeDirectory(final Product ctx, final File homeDir) throws MojoExecutionException
{
ConfigFileUtils.replace(new File(homeDir, "bamboo.cfg.xml"), "@project-dir@", homeDir.getParent());
ConfigFileUtils.replace(new File(homeDir, "bamboo.cfg.xml"), "/bamboo-home/", "/home/");
ConfigFileUtils.replace(new File(homeDir, "bamboo.cfg.xml"), "${bambooHome}", homeDir.getAbsolutePath());
ConfigFileUtils.replaceAll(new File(homeDir, "/xml-data/configuration/administration.xml"),
"http://[^:]+:8085", "http://" + ctx.getServer() + ":" + ctx.getHttpPort() + "/" + ctx.getContextPath().replaceAll("^/|/$", ""));
}
| public void processHomeDirectory(final Product ctx, final File homeDir) throws MojoExecutionException
{
ConfigFileUtils.replace(new File(homeDir, "bamboo.cfg.xml"), "@project-dir@", homeDir.getParent());
ConfigFileUtils.replace(new File(homeDir, "bamboo.cfg.xml"), "/bamboo-home/", "/home/");
ConfigFileUtils.replace(new File(homeDir, "bamboo.cfg.xml"), "${bambooHome}", homeDir.getAbsolutePath());
ConfigFileUtils.replaceAll(new File(homeDir, "/xml-data/configuration/administration.xml"),
"http://(?:[^:]|\\[.+])+:8085", "http://" + ctx.getServer() + ":" + ctx.getHttpPort() + "/" + ctx.getContextPath().replaceAll("^/|/$", ""));
}
|
diff --git a/src/de/dhbw/wbs/Seminarplanung.java b/src/de/dhbw/wbs/Seminarplanung.java
index e5267ba..383638c 100644
--- a/src/de/dhbw/wbs/Seminarplanung.java
+++ b/src/de/dhbw/wbs/Seminarplanung.java
@@ -1,162 +1,162 @@
package de.dhbw.wbs;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
public final class Seminarplanung {
private static final SimpleDateFormat lectureTimeFormat = new SimpleDateFormat("hh:mm");
/**
* @param args
*/
public static void main(String[] args) {
HashMap<Integer, Lecture> lectures = new HashMap<Integer, Lecture>();
HashMap<Integer, Group> groups = new HashMap<Integer, Group>();
if (args.length != 3) {
System.err.println("Expecting three file names as arguments.");
System.exit(1);
}
String lectureFileName = args[0];
String depFileName = args[1];
String timeFileName = args[2];
// 1. Parsen
try {
/*
* Parse 1st file - lectures
*
* Lecture No;subject;lecturer;group number;duration;room
*/
BufferedReader lectureReader = new BufferedReader(new FileReader(lectureFileName));
// Skip the header line
lectureReader.readLine();
CSVParser lectureParser = new CSVParser(lectureReader);
for (String[] elems : lectureParser.parse()) {
Lecture lecture = new Lecture();
Group group = groups.get(new Integer(elems[3]));
if (group == null)
group = new Group(Integer.parseInt(elems[3]));
lecture.setNumber(Integer.parseInt(elems[0]));
lecture.setName(elems[1]);
lecture.setLecturer(new Lecturer(elems[2]));
lecture.setGroup(group);
lecture.setDuration(Integer.parseInt(elems[4]));
lecture.setRoom(new Room(Integer.parseInt(elems[5])));
lectures.put(new Integer(lecture.getNumber()), lecture);
}
/*
* Parse 2nd file - lecture dependencies
*
* basic lecture;required lecture;;;;
*/
BufferedReader depReader = new BufferedReader(new FileReader(depFileName));
// Skip the header line
depReader.readLine();
CSVParser depParser = new CSVParser(depReader);
for (String[] elems : depParser.parse()) {
Lecture basicLecture = lectures.get(new Integer(elems[0]));
Lecture dependentLecture = lectures.get(new Integer(elems[1]));
dependentLecture.addRequiredLecture(basicLecture);
}
/*
* Parse 3rd file - time information
* group number;lecture number;start time
*/
BufferedReader timeReader = new BufferedReader(new FileReader(timeFileName));
// Skip the header line
timeReader.readLine();
CSVParser timeParser = new CSVParser(timeReader);
for (String[] elems : timeParser.parse()) {
Lecture lecture = lectures.get(new Integer(elems[0]));
Group group = groups.get(new Integer(elems[1]));
if (group != lecture.getGroup()) {
System.err.println("Error: The group number for lecture " + elems[1] +
- " as supplied in file " + timeFileName + " does not match the group " +
+ "(" + lecture.getName() + ") as supplied in file " + timeFileName + " does not match the group " +
"number from file " + lectureFileName);
System.exit(1);
}
Date startTime = null;
try {
startTime = lectureTimeFormat.parse(elems[2]);
} catch (ParseException exc) {
System.err.println("Error: Invalid time format " + elems[2] +
" in file " + args[2] + ". Expect hh:mm notation.");
System.exit(1);
}
Calendar cal = Calendar.getInstance();
cal.setTime(startTime);
lecture.setStartTime(cal);
}
}
catch (FileNotFoundException e) {
System.err.println("File not found: " + e.getMessage());
System.exit(1);
} catch (IOException e) {
e.printStackTrace();
System.exit(2);
}
// 2. Check consistency
/*
* 2.1 A lecture may only take place of the group has already heard all lectures that this
* lecture depends on
*/
for (Lecture dependentLecture : lectures.values()) {
for (Lecture requiredLecture : dependentLecture.getRequiredLectures()) {
assertTrue(dependentLecture.getGroup() == requiredLecture.getGroup(),
"Lecture " + dependentLecture.getName() + "depends on lecture " +
requiredLecture.getName() +
", but the two lectures are held in different groups.");
// TODO
assertTrue(true, "Lecture " + dependentLecture.getName() + "depends on lecture " +
requiredLecture + ", but this lecture is not taught before the other lecture.");
}
}
/*
* 2.2 Lectures of the same group or the same lecturer may not overlap.
* One room can be used for only one lecture at a given point of time.
*/
// TODO
/*
* 2.3 There has to be a break between two lectures of length two for both the lecturerers and the
* seminar group.
*/
// TODO
}
private static void assertTrue(boolean assertion, String errMsg) {
if (!assertion) {
System.err.println(errMsg);
System.exit(1);
}
}
}
| true | true | public static void main(String[] args) {
HashMap<Integer, Lecture> lectures = new HashMap<Integer, Lecture>();
HashMap<Integer, Group> groups = new HashMap<Integer, Group>();
if (args.length != 3) {
System.err.println("Expecting three file names as arguments.");
System.exit(1);
}
String lectureFileName = args[0];
String depFileName = args[1];
String timeFileName = args[2];
// 1. Parsen
try {
/*
* Parse 1st file - lectures
*
* Lecture No;subject;lecturer;group number;duration;room
*/
BufferedReader lectureReader = new BufferedReader(new FileReader(lectureFileName));
// Skip the header line
lectureReader.readLine();
CSVParser lectureParser = new CSVParser(lectureReader);
for (String[] elems : lectureParser.parse()) {
Lecture lecture = new Lecture();
Group group = groups.get(new Integer(elems[3]));
if (group == null)
group = new Group(Integer.parseInt(elems[3]));
lecture.setNumber(Integer.parseInt(elems[0]));
lecture.setName(elems[1]);
lecture.setLecturer(new Lecturer(elems[2]));
lecture.setGroup(group);
lecture.setDuration(Integer.parseInt(elems[4]));
lecture.setRoom(new Room(Integer.parseInt(elems[5])));
lectures.put(new Integer(lecture.getNumber()), lecture);
}
/*
* Parse 2nd file - lecture dependencies
*
* basic lecture;required lecture;;;;
*/
BufferedReader depReader = new BufferedReader(new FileReader(depFileName));
// Skip the header line
depReader.readLine();
CSVParser depParser = new CSVParser(depReader);
for (String[] elems : depParser.parse()) {
Lecture basicLecture = lectures.get(new Integer(elems[0]));
Lecture dependentLecture = lectures.get(new Integer(elems[1]));
dependentLecture.addRequiredLecture(basicLecture);
}
/*
* Parse 3rd file - time information
* group number;lecture number;start time
*/
BufferedReader timeReader = new BufferedReader(new FileReader(timeFileName));
// Skip the header line
timeReader.readLine();
CSVParser timeParser = new CSVParser(timeReader);
for (String[] elems : timeParser.parse()) {
Lecture lecture = lectures.get(new Integer(elems[0]));
Group group = groups.get(new Integer(elems[1]));
if (group != lecture.getGroup()) {
System.err.println("Error: The group number for lecture " + elems[1] +
" as supplied in file " + timeFileName + " does not match the group " +
"number from file " + lectureFileName);
System.exit(1);
}
Date startTime = null;
try {
startTime = lectureTimeFormat.parse(elems[2]);
} catch (ParseException exc) {
System.err.println("Error: Invalid time format " + elems[2] +
" in file " + args[2] + ". Expect hh:mm notation.");
System.exit(1);
}
Calendar cal = Calendar.getInstance();
cal.setTime(startTime);
lecture.setStartTime(cal);
}
}
catch (FileNotFoundException e) {
System.err.println("File not found: " + e.getMessage());
System.exit(1);
} catch (IOException e) {
e.printStackTrace();
System.exit(2);
}
// 2. Check consistency
/*
* 2.1 A lecture may only take place of the group has already heard all lectures that this
* lecture depends on
*/
for (Lecture dependentLecture : lectures.values()) {
for (Lecture requiredLecture : dependentLecture.getRequiredLectures()) {
assertTrue(dependentLecture.getGroup() == requiredLecture.getGroup(),
"Lecture " + dependentLecture.getName() + "depends on lecture " +
requiredLecture.getName() +
", but the two lectures are held in different groups.");
// TODO
assertTrue(true, "Lecture " + dependentLecture.getName() + "depends on lecture " +
requiredLecture + ", but this lecture is not taught before the other lecture.");
}
}
/*
* 2.2 Lectures of the same group or the same lecturer may not overlap.
* One room can be used for only one lecture at a given point of time.
*/
// TODO
/*
* 2.3 There has to be a break between two lectures of length two for both the lecturerers and the
* seminar group.
*/
// TODO
}
| public static void main(String[] args) {
HashMap<Integer, Lecture> lectures = new HashMap<Integer, Lecture>();
HashMap<Integer, Group> groups = new HashMap<Integer, Group>();
if (args.length != 3) {
System.err.println("Expecting three file names as arguments.");
System.exit(1);
}
String lectureFileName = args[0];
String depFileName = args[1];
String timeFileName = args[2];
// 1. Parsen
try {
/*
* Parse 1st file - lectures
*
* Lecture No;subject;lecturer;group number;duration;room
*/
BufferedReader lectureReader = new BufferedReader(new FileReader(lectureFileName));
// Skip the header line
lectureReader.readLine();
CSVParser lectureParser = new CSVParser(lectureReader);
for (String[] elems : lectureParser.parse()) {
Lecture lecture = new Lecture();
Group group = groups.get(new Integer(elems[3]));
if (group == null)
group = new Group(Integer.parseInt(elems[3]));
lecture.setNumber(Integer.parseInt(elems[0]));
lecture.setName(elems[1]);
lecture.setLecturer(new Lecturer(elems[2]));
lecture.setGroup(group);
lecture.setDuration(Integer.parseInt(elems[4]));
lecture.setRoom(new Room(Integer.parseInt(elems[5])));
lectures.put(new Integer(lecture.getNumber()), lecture);
}
/*
* Parse 2nd file - lecture dependencies
*
* basic lecture;required lecture;;;;
*/
BufferedReader depReader = new BufferedReader(new FileReader(depFileName));
// Skip the header line
depReader.readLine();
CSVParser depParser = new CSVParser(depReader);
for (String[] elems : depParser.parse()) {
Lecture basicLecture = lectures.get(new Integer(elems[0]));
Lecture dependentLecture = lectures.get(new Integer(elems[1]));
dependentLecture.addRequiredLecture(basicLecture);
}
/*
* Parse 3rd file - time information
* group number;lecture number;start time
*/
BufferedReader timeReader = new BufferedReader(new FileReader(timeFileName));
// Skip the header line
timeReader.readLine();
CSVParser timeParser = new CSVParser(timeReader);
for (String[] elems : timeParser.parse()) {
Lecture lecture = lectures.get(new Integer(elems[0]));
Group group = groups.get(new Integer(elems[1]));
if (group != lecture.getGroup()) {
System.err.println("Error: The group number for lecture " + elems[1] +
"(" + lecture.getName() + ") as supplied in file " + timeFileName + " does not match the group " +
"number from file " + lectureFileName);
System.exit(1);
}
Date startTime = null;
try {
startTime = lectureTimeFormat.parse(elems[2]);
} catch (ParseException exc) {
System.err.println("Error: Invalid time format " + elems[2] +
" in file " + args[2] + ". Expect hh:mm notation.");
System.exit(1);
}
Calendar cal = Calendar.getInstance();
cal.setTime(startTime);
lecture.setStartTime(cal);
}
}
catch (FileNotFoundException e) {
System.err.println("File not found: " + e.getMessage());
System.exit(1);
} catch (IOException e) {
e.printStackTrace();
System.exit(2);
}
// 2. Check consistency
/*
* 2.1 A lecture may only take place of the group has already heard all lectures that this
* lecture depends on
*/
for (Lecture dependentLecture : lectures.values()) {
for (Lecture requiredLecture : dependentLecture.getRequiredLectures()) {
assertTrue(dependentLecture.getGroup() == requiredLecture.getGroup(),
"Lecture " + dependentLecture.getName() + "depends on lecture " +
requiredLecture.getName() +
", but the two lectures are held in different groups.");
// TODO
assertTrue(true, "Lecture " + dependentLecture.getName() + "depends on lecture " +
requiredLecture + ", but this lecture is not taught before the other lecture.");
}
}
/*
* 2.2 Lectures of the same group or the same lecturer may not overlap.
* One room can be used for only one lecture at a given point of time.
*/
// TODO
/*
* 2.3 There has to be a break between two lectures of length two for both the lecturerers and the
* seminar group.
*/
// TODO
}
|
diff --git a/deegree-services/deegree-services-commons/src/main/java/org/deegree/services/ows/OWS110ExceptionReportSerializer.java b/deegree-services/deegree-services-commons/src/main/java/org/deegree/services/ows/OWS110ExceptionReportSerializer.java
index c40e92905e..40081eadbb 100644
--- a/deegree-services/deegree-services-commons/src/main/java/org/deegree/services/ows/OWS110ExceptionReportSerializer.java
+++ b/deegree-services/deegree-services-commons/src/main/java/org/deegree/services/ows/OWS110ExceptionReportSerializer.java
@@ -1,117 +1,120 @@
//$HeadURL$
/*----------------------------------------------------------------------------
This file is part of deegree, http://deegree.org/
Copyright (C) 2001-2009 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.services.ows;
import static org.deegree.commons.ows.exception.OWSException.NO_APPLICABLE_CODE;
import static org.deegree.commons.ows.exception.OWSException.OPERATION_PROCESSING_FAILED;
import static org.deegree.commons.xml.CommonNamespaces.XSINS;
import java.io.IOException;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import org.deegree.commons.ows.exception.OWSException;
import org.deegree.commons.tom.ows.Version;
import org.deegree.services.controller.exception.serializer.XMLExceptionSerializer;
import org.deegree.services.controller.utils.HttpResponseBuffer;
/**
* {@link XMLExceptionSerializer} for OWS Commons 1.1.0 <code>ExceptionReport</code> documents.
*
* @author <a href="mailto:[email protected]">Oliver Tonnhofer</a>
* @author last edited by: $Author$
*
* @version $Revision$, $Date$
*/
public class OWS110ExceptionReportSerializer extends XMLExceptionSerializer {
private static final String OWS_NS = "http://www.opengis.net/ows/1.1";
private static final String OWS_SCHEMA = "http://schemas.opengis.net/ows/1.1.0/owsExceptionReport.xsd";
private final Version version;
/**
* Creates a new {@link OWS110ExceptionReportSerializer} instance.
*
* @param version
* version attribute, must not be <code>null</code>
*/
public OWS110ExceptionReportSerializer( Version version ) {
this.version = version;
}
@Override
public void serializeException( HttpResponseBuffer response, OWSException exception )
throws IOException, XMLStreamException {
response.reset();
response.setCharacterEncoding( "UTF-8" );
response.setContentType( "application/xml" );
if ( NO_APPLICABLE_CODE.equals( exception.getExceptionCode() ) ) {
response.setStatus( 500 );
} else if ( OPERATION_PROCESSING_FAILED.equals( exception.getExceptionCode() ) ) {
response.setStatus( 403 );
} else {
response.setStatus( 400 );
}
serializeExceptionToXML( response.getXMLWriter(), exception );
}
@Override
public void serializeExceptionToXML( XMLStreamWriter writer, OWSException ex )
throws XMLStreamException {
if ( ex == null || writer == null ) {
return;
}
writer.writeStartElement( "ows", "ExceptionReport", OWS_NS );
writer.writeNamespace( "ows", OWS_NS );
writer.writeNamespace( "xsi", XSINS );
writer.writeAttribute( XSINS, "schemaLocation", OWS_NS + " " + OWS_SCHEMA );
writer.writeAttribute( "version", "" + version );
writer.writeStartElement( OWS_NS, "Exception" );
writer.writeAttribute( "exceptionCode", ex.getExceptionCode() );
if ( ex.getLocator() != null && !"".equals( ex.getLocator().trim() ) ) {
writer.writeAttribute( "locator", ex.getLocator() );
}
- writer.writeStartElement( OWS_NS, "ExceptionText" );
- writer.writeCharacters( ex.getMessage() );
- writer.writeEndElement();
+ String message = ex.getMessage();
+ if ( message != null ) {
+ writer.writeStartElement( OWS_NS, "ExceptionText" );
+ writer.writeCharacters( message );
+ writer.writeEndElement();
+ }
writer.writeEndElement(); // Exception
writer.writeEndElement(); // ExceptionReport
}
}
| true | true | public void serializeExceptionToXML( XMLStreamWriter writer, OWSException ex )
throws XMLStreamException {
if ( ex == null || writer == null ) {
return;
}
writer.writeStartElement( "ows", "ExceptionReport", OWS_NS );
writer.writeNamespace( "ows", OWS_NS );
writer.writeNamespace( "xsi", XSINS );
writer.writeAttribute( XSINS, "schemaLocation", OWS_NS + " " + OWS_SCHEMA );
writer.writeAttribute( "version", "" + version );
writer.writeStartElement( OWS_NS, "Exception" );
writer.writeAttribute( "exceptionCode", ex.getExceptionCode() );
if ( ex.getLocator() != null && !"".equals( ex.getLocator().trim() ) ) {
writer.writeAttribute( "locator", ex.getLocator() );
}
writer.writeStartElement( OWS_NS, "ExceptionText" );
writer.writeCharacters( ex.getMessage() );
writer.writeEndElement();
writer.writeEndElement(); // Exception
writer.writeEndElement(); // ExceptionReport
}
| public void serializeExceptionToXML( XMLStreamWriter writer, OWSException ex )
throws XMLStreamException {
if ( ex == null || writer == null ) {
return;
}
writer.writeStartElement( "ows", "ExceptionReport", OWS_NS );
writer.writeNamespace( "ows", OWS_NS );
writer.writeNamespace( "xsi", XSINS );
writer.writeAttribute( XSINS, "schemaLocation", OWS_NS + " " + OWS_SCHEMA );
writer.writeAttribute( "version", "" + version );
writer.writeStartElement( OWS_NS, "Exception" );
writer.writeAttribute( "exceptionCode", ex.getExceptionCode() );
if ( ex.getLocator() != null && !"".equals( ex.getLocator().trim() ) ) {
writer.writeAttribute( "locator", ex.getLocator() );
}
String message = ex.getMessage();
if ( message != null ) {
writer.writeStartElement( OWS_NS, "ExceptionText" );
writer.writeCharacters( message );
writer.writeEndElement();
}
writer.writeEndElement(); // Exception
writer.writeEndElement(); // ExceptionReport
}
|
diff --git a/src/org/joni/Matcher.java b/src/org/joni/Matcher.java
index 215f0da..b55b0b4 100644
--- a/src/org/joni/Matcher.java
+++ b/src/org/joni/Matcher.java
@@ -1,581 +1,581 @@
/*
* 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 org.joni;
import static org.joni.Option.isFindLongest;
import org.jcodings.Encoding;
import org.jcodings.IntHolder;
import org.joni.constants.AnchorType;
public abstract class Matcher extends IntHolder {
protected final Regex regex;
protected final Encoding enc;
protected final byte[]bytes;
protected final int str;
protected final int end;
protected int msaStart;
protected int msaOptions;
protected final Region msaRegion;
protected int msaBestLen;
protected int msaBestS;
protected int msaBegin;
protected int msaEnd;
// cached values
protected final int option;
protected final int caseFoldFlag;
public Matcher(Regex regex, byte[]bytes) {
this(regex, bytes, 0, bytes.length);
}
public Matcher(Regex regex, byte[]bytes, int p, int end) {
this.regex = regex;
this.enc = regex.enc;
this.bytes = bytes;
this.str = p;
this.end = end;
this.msaRegion = regex.numMem == 0 ? null : new Region(regex.numMem + 1);
this.option = regex.options;
this.caseFoldFlag = regex.caseFoldFlag;
}
// main matching method
protected abstract int matchAt(int range, int sstart, int sprev);
protected abstract void stateCheckBuffInit(int strLength, int offset, int stateNum);
protected abstract void stateCheckBuffClear();
public final Region getRegion() {
return msaRegion;
}
public final Region getEagerRegion() {
return msaRegion != null ? msaRegion : new Region(msaBegin, msaEnd);
}
public final int getBegin() {
return msaBegin;
}
public final int getEnd() {
return msaEnd;
}
protected final void msaInit(int option, int start) {
msaOptions = option;
msaStart = start;
if (Config.USE_FIND_LONGEST_SEARCH_ALL_OF_RANGE) msaBestLen = -1;
}
public final int match(int at, int range, int option) {
msaInit(option, at);
if (Config.USE_COMBINATION_EXPLOSION_CHECK) {
int offset = at = str;
stateCheckBuffInit(end - str, offset, regex.numCombExpCheck); // move it to construction?
} // USE_COMBINATION_EXPLOSION_CHECK
int prev = enc.prevCharHead(bytes, str, at, end);
if (Config.USE_MATCH_RANGE_MUST_BE_INSIDE_OF_SPECIFIED_RANGE) {
return matchAt(end /*range*/, at, prev);
} else {
return matchAt(range /*range*/, at, prev);
}
}
int low, high; // these are the return values
private boolean forwardSearchRange(byte[]bytes, int str, int end, int s, int range, IntHolder lowPrev) {
int pprev = -1;
int p = s;
if (Config.DEBUG_SEARCH) {
Config.log.println("forward_search_range: "+
"str: " + str +
", end: " + end +
", s: " + s +
", range: " + range);
}
if (regex.dMin > 0) {
if (enc.isSingleByte()) {
p += regex.dMin;
} else {
int q = p + regex.dMin;
while (p < q) p += enc.length(bytes, p, end);
}
}
retry:while (true) {
p = regex.searchAlgorithm.search(regex, bytes, p, end, range);
if (p != -1 && p < range) {
if (p - regex.dMin < s) {
// retry_gate:
pprev = p;
p += enc.length(bytes, p, end);
continue retry;
}
if (regex.subAnchor != 0) {
switch (regex.subAnchor) {
case AnchorType.BEGIN_LINE:
if (p != str) {
int prev = enc.prevCharHead(bytes, (pprev != -1) ? pprev : str, p, end);
if (!enc.isNewLine(bytes, prev, end)) {
// goto retry_gate;
pprev = p;
p += enc.length(bytes, p, end);
continue retry;
}
}
break;
case AnchorType.END_LINE:
if (p == end) {
if (!Config.USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE) {
int prev = enc.prevCharHead(bytes, (pprev != -1) ? pprev : str, p, end);
if (prev != -1 && enc.isNewLine(bytes, prev, end)) {
// goto retry_gate;
pprev = p;
p += enc.length(bytes, p, end);
continue retry;
}
}
} else if (!enc.isNewLine(bytes, p, end) && (!Config.USE_CRNL_AS_LINE_TERMINATOR || !enc.isMbcCrnl(bytes, p, end))) {
//if () break;
// goto retry_gate;
pprev = p;
p += enc.length(bytes, p, end);
continue retry;
}
break;
} // switch
}
if (regex.dMax == 0) {
low = p;
if (lowPrev != null) { // ??? // remove null checks
if (low > s) {
lowPrev.value = enc.prevCharHead(bytes, s, p, end);
} else {
lowPrev.value = enc.prevCharHead(bytes, (pprev != -1) ? pprev : str, p, end);
}
}
} else {
if (regex.dMax != MinMaxLen.INFINITE_DISTANCE) {
low = p - regex.dMax;
if (low > s) {
low = enc.rightAdjustCharHeadWithPrev(bytes, s, low, end, lowPrev);
if (lowPrev != null && lowPrev.value == -1) {
lowPrev.value = enc.prevCharHead(bytes, (pprev != -1) ? pprev : s, low, end);
}
} else {
if (lowPrev != null) {
lowPrev.value = enc.prevCharHead(bytes, (pprev != -1) ? pprev : str, low, end);
}
}
}
}
/* no needs to adjust *high, *high is used as range check only */
high = p - regex.dMin;
if (Config.DEBUG_SEARCH) {
Config.log.println("forward_search_range success: "+
"low: " + (low - str) +
", high: " + (high - str) +
", dmin: " + regex.dMin +
", dmax: " + regex.dMax);
}
return true; /* success */
}
return false; /* fail */
} //while
}
// low, high
private boolean backwardSearchRange(byte[]bytes, int str, int end, int s, int range, int adjrange) {
range += regex.dMin;
int p = s;
retry:while (true) {
p = regex.searchAlgorithm.searchBackward(regex, bytes, range, adjrange, end, p, s, range);
if (p != -1) {
if (regex.subAnchor != 0) {
switch (regex.subAnchor) {
case AnchorType.BEGIN_LINE:
if (p != str) {
int prev = enc.prevCharHead(bytes, str, p, end);
if (!enc.isNewLine(bytes, prev, end)) {
p = prev;
continue retry;
}
}
break;
case AnchorType.END_LINE:
if (p == end) {
if (!Config.USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE) {
int prev = enc.prevCharHead(bytes, adjrange, p, end);
if (prev == -1) return false;
if (enc.isNewLine(bytes, prev, end)) {
p = prev;
continue retry;
}
}
} else if (!enc.isNewLine(bytes, p, end) && (!Config.USE_CRNL_AS_LINE_TERMINATOR || !enc.isMbcCrnl(bytes, p, end))) {
p = enc.prevCharHead(bytes, adjrange, p, end);
if (p == -1) return false;
continue retry;
}
break;
} // switch
}
/* no needs to adjust *high, *high is used as range check only */
if (regex.dMax != MinMaxLen.INFINITE_DISTANCE) {
low = p - regex.dMax;
high = p - regex.dMin;
high = enc.rightAdjustCharHead(bytes, adjrange, high, end);
}
if (Config.DEBUG_SEARCH) {
Config.log.println("backward_search_range: "+
"low: " + (low - str) +
", high: " + (high - str));
}
return true;
}
if (Config.DEBUG_SEARCH) Config.log.println("backward_search_range: fail.");
return false;
} // while
}
// MATCH_AND_RETURN_CHECK
private boolean matchCheck(int upperRange, int s, int prev) {
if (Config.USE_MATCH_RANGE_MUST_BE_INSIDE_OF_SPECIFIED_RANGE) {
if (Config.USE_FIND_LONGEST_SEARCH_ALL_OF_RANGE) {
//range = upperRange;
if (matchAt(upperRange, s, prev) != -1) {
if (!isFindLongest(option)) return true;
}
} else {
//range = upperRange;
if (matchAt(upperRange, s, prev) != -1) return true;
}
} else {
if (Config.USE_FIND_LONGEST_SEARCH_ALL_OF_RANGE) {
if (matchAt(end, s, prev) != -1) {
//range = upperRange;
if (!isFindLongest(option)) return true;
}
} else {
//range = upperRange;
if (matchAt(end, s, prev) != -1) return true;
}
}
return false;
}
public final int search(int start, int range, int option) {
int s, prev;
int origStart = start;
int origRange = range;
if (Config.DEBUG_SEARCH) {
Config.log.println("onig_search (entry point): "+
"str: " + str +
", end: " + (end - str) +
", start: " + (start - str) +
", range " + (range - str));
}
if (start > end || start < str) return -1;
/* anchor optimize: resume search range */
if (regex.anchor != 0 && str < end) {
int minSemiEnd, maxSemiEnd;
if ((regex.anchor & AnchorType.BEGIN_POSITION) != 0) {
/* search start-position only */
// !begin_position:!
if (range > start) {
range = start + 1;
} else {
range = start;
}
} else if ((regex.anchor & AnchorType.BEGIN_BUF) != 0) {
/* search str-position only */
if (range > start) {
if (start != str) return -1; // mismatch_no_msa;
range = str + 1;
} else {
if (range <= str) {
start = str;
range = str;
} else {
return -1; // mismatch_no_msa;
}
}
} else if ((regex.anchor & AnchorType.END_BUF) != 0) {
minSemiEnd = maxSemiEnd = end;
// !end_buf:!
if (endBuf(start, range, minSemiEnd, maxSemiEnd)) return -1; // mismatch_no_msa;
} else if ((regex.anchor & AnchorType.SEMI_END_BUF) != 0) {
int preEnd = enc.stepBack(bytes, str, end, end, 1);
maxSemiEnd = end;
if (enc.isNewLine(bytes, preEnd, end)) {
minSemiEnd = preEnd;
if (Config.USE_CRNL_AS_LINE_TERMINATOR) {
preEnd = enc.stepBack(bytes, str, preEnd, end, 1);
if (preEnd != -1 && enc.isMbcCrnl(bytes, preEnd, end)) {
minSemiEnd = preEnd;
}
}
if (minSemiEnd > str && start <= minSemiEnd) {
// !goto end_buf;!
if (endBuf(start, range, minSemiEnd, maxSemiEnd)) return -1; // mismatch_no_msa;
}
} else {
minSemiEnd = end;
// !goto end_buf;!
if (endBuf(start, range, minSemiEnd, maxSemiEnd)) return -1; // mismatch_no_msa;
}
} else if ((regex.anchor & AnchorType.ANYCHAR_STAR_ML) != 0) {
// goto !begin_position;!
if (range > start) {
range = start + 1;
} else {
range = start;
}
}
} else if (str == end) { /* empty string */
// empty address ?
if (Config.DEBUG_SEARCH) {
Config.log.println("onig_search: empty string.");
}
if (regex.thresholdLength == 0) {
s = start = str;
prev = -1;
msaInit(option, start);
if (Config.USE_COMBINATION_EXPLOSION_CHECK) stateCheckBuffClear();
if (matchCheck(end, s, prev)) return match(s);
return mismatch();
}
return -1; // goto mismatch_no_msa;
}
if (Config.DEBUG_SEARCH) {
Config.log.println("onig_search(apply anchor): " +
"end: " + (end - str) +
", start " + (start - str) +
", range " + (range - str));
}
msaInit(option, origStart);
if (Config.USE_COMBINATION_EXPLOSION_CHECK) {
int offset = Math.min(start, range) - str;
stateCheckBuffInit(end - str, offset, regex.numCombExpCheck);
}
s = start;
if (range > start) { /* forward search */
if (s > str) {
prev = enc.prevCharHead(bytes, str, s, end);
} else {
prev = 0; // -1
}
if (regex.searchAlgorithm != SearchAlgorithm.NONE) {
int schRange = range;
if (regex.dMax != 0) {
if (regex.dMax == MinMaxLen.INFINITE_DISTANCE) {
schRange = end;
} else {
schRange += regex.dMax;
if (schRange > end) schRange = end;
}
}
if ((end - start) < regex.thresholdLength) return mismatch();
if (regex.dMax != MinMaxLen.INFINITE_DISTANCE) {
do {
if (!forwardSearchRange(bytes, str, end, s, schRange, this)) return mismatch(); // low, high, lowPrev
if (s < low) {
s = low;
prev = value;
}
while (s <= high) {
if (matchCheck(origRange, s, prev)) return match(s); // ???
prev = s;
s += enc.length(bytes, s, end);
}
} while (s < range);
return mismatch();
} else { /* check only. */
if (!forwardSearchRange(bytes, str, end, s, schRange, null)) return mismatch();
if ((regex.anchor & AnchorType.ANYCHAR_STAR) != 0) {
do {
if (matchCheck(origRange, s, prev)) return match(s);
prev = s;
s += enc.length(bytes, s, end);
while (!enc.isNewLine(bytes, prev, end) && s < range) {
prev = s;
s += enc.length(bytes, s, end);
}
} while (s < range);
return mismatch();
}
}
}
do {
if (matchCheck(origRange, s, prev)) return match(s);
prev = s;
s += enc.length(bytes, s, end);
} while (s < range);
if (s == range) { /* because empty match with /$/. */
if (matchCheck(origRange, s, prev)) return match(s);
}
} else { /* backward search */
if (Config.USE_MATCH_RANGE_MUST_BE_INSIDE_OF_SPECIFIED_RANGE) {
if (origStart < end) {
origStart += enc.length(bytes, origStart, end); // /* is upper range */
}
}
if (regex.searchAlgorithm != SearchAlgorithm.NONE) {
int adjrange;
if (range < end) {
adjrange = enc.leftAdjustCharHead(bytes, str, range, end);
} else {
adjrange = end;
}
if (regex.dMax != MinMaxLen.INFINITE_DISTANCE && (end - range) >= regex.thresholdLength) {
do {
int schStart = s + regex.dMax;
if (schStart > end) schStart = end;
if (!backwardSearchRange(bytes, str, end, schStart, range, adjrange)) return mismatch(); // low, high
if (s > high) s = high;
- while (s >= low) {
+ while (s != -1 && s >= low) {
prev = enc.prevCharHead(bytes, str, s, end);
if (matchCheck(origStart, s, prev)) return match(s);
s = prev;
}
} while (s >= range);
return mismatch();
} else { /* check only. */
if ((end - range) < regex.thresholdLength) return mismatch();
int schStart = s;
if (regex.dMax != 0) {
if (regex.dMax == MinMaxLen.INFINITE_DISTANCE) {
schStart = end;
} else {
schStart += regex.dMax;
if (schStart > end) {
schStart = end;
} else {
schStart = enc.leftAdjustCharHead(bytes, start, schStart, end);
}
}
}
if (!backwardSearchRange(bytes, str, end, schStart, range, adjrange)) return mismatch();
}
}
do {
prev = enc.prevCharHead(bytes, str, s, end);
if (matchCheck(origStart, s, prev)) return match(s);
s = prev;
} while (s >= range);
}
return mismatch();
}
private boolean endBuf(int start, int range, int minSemiEnd, int maxSemiEnd) {
if ((maxSemiEnd - str) < regex.anchorDmin) return true; // mismatch_no_msa;
if (range > start) {
if ((minSemiEnd - start) > regex.anchorDmax) {
start = minSemiEnd - regex.anchorDmax;
if (start < end) {
start = enc.rightAdjustCharHead(bytes, str, start, end);
} else { /* match with empty at end */
start = enc.prevCharHead(bytes, str, end, end);
}
}
if ((maxSemiEnd - (range - 1)) < regex.anchorDmin) {
range = maxSemiEnd - regex.anchorDmin + 1;
}
if (start >= range) return true; // mismatch_no_msa;
} else {
if ((minSemiEnd - range) > regex.anchorDmax) {
range = minSemiEnd - regex.anchorDmax;
}
if ((maxSemiEnd - start) < regex.anchorDmin) {
start = maxSemiEnd - regex.anchorDmin;
start = enc.leftAdjustCharHead(bytes, str, start, end);
}
if (range > start) return true; // mismatch_no_msa;
}
return false;
}
private int match(int s) {
return s - str; // sstart ???
}
private int mismatch() {
if (Config.USE_FIND_LONGEST_SEARCH_ALL_OF_RANGE) {
if (msaBestLen >= 0) {
int s = msaBestS;
return match(s);
}
}
// falls through finish:
return -1;
}
}
| true | true | public final int search(int start, int range, int option) {
int s, prev;
int origStart = start;
int origRange = range;
if (Config.DEBUG_SEARCH) {
Config.log.println("onig_search (entry point): "+
"str: " + str +
", end: " + (end - str) +
", start: " + (start - str) +
", range " + (range - str));
}
if (start > end || start < str) return -1;
/* anchor optimize: resume search range */
if (regex.anchor != 0 && str < end) {
int minSemiEnd, maxSemiEnd;
if ((regex.anchor & AnchorType.BEGIN_POSITION) != 0) {
/* search start-position only */
// !begin_position:!
if (range > start) {
range = start + 1;
} else {
range = start;
}
} else if ((regex.anchor & AnchorType.BEGIN_BUF) != 0) {
/* search str-position only */
if (range > start) {
if (start != str) return -1; // mismatch_no_msa;
range = str + 1;
} else {
if (range <= str) {
start = str;
range = str;
} else {
return -1; // mismatch_no_msa;
}
}
} else if ((regex.anchor & AnchorType.END_BUF) != 0) {
minSemiEnd = maxSemiEnd = end;
// !end_buf:!
if (endBuf(start, range, minSemiEnd, maxSemiEnd)) return -1; // mismatch_no_msa;
} else if ((regex.anchor & AnchorType.SEMI_END_BUF) != 0) {
int preEnd = enc.stepBack(bytes, str, end, end, 1);
maxSemiEnd = end;
if (enc.isNewLine(bytes, preEnd, end)) {
minSemiEnd = preEnd;
if (Config.USE_CRNL_AS_LINE_TERMINATOR) {
preEnd = enc.stepBack(bytes, str, preEnd, end, 1);
if (preEnd != -1 && enc.isMbcCrnl(bytes, preEnd, end)) {
minSemiEnd = preEnd;
}
}
if (minSemiEnd > str && start <= minSemiEnd) {
// !goto end_buf;!
if (endBuf(start, range, minSemiEnd, maxSemiEnd)) return -1; // mismatch_no_msa;
}
} else {
minSemiEnd = end;
// !goto end_buf;!
if (endBuf(start, range, minSemiEnd, maxSemiEnd)) return -1; // mismatch_no_msa;
}
} else if ((regex.anchor & AnchorType.ANYCHAR_STAR_ML) != 0) {
// goto !begin_position;!
if (range > start) {
range = start + 1;
} else {
range = start;
}
}
} else if (str == end) { /* empty string */
// empty address ?
if (Config.DEBUG_SEARCH) {
Config.log.println("onig_search: empty string.");
}
if (regex.thresholdLength == 0) {
s = start = str;
prev = -1;
msaInit(option, start);
if (Config.USE_COMBINATION_EXPLOSION_CHECK) stateCheckBuffClear();
if (matchCheck(end, s, prev)) return match(s);
return mismatch();
}
return -1; // goto mismatch_no_msa;
}
if (Config.DEBUG_SEARCH) {
Config.log.println("onig_search(apply anchor): " +
"end: " + (end - str) +
", start " + (start - str) +
", range " + (range - str));
}
msaInit(option, origStart);
if (Config.USE_COMBINATION_EXPLOSION_CHECK) {
int offset = Math.min(start, range) - str;
stateCheckBuffInit(end - str, offset, regex.numCombExpCheck);
}
s = start;
if (range > start) { /* forward search */
if (s > str) {
prev = enc.prevCharHead(bytes, str, s, end);
} else {
prev = 0; // -1
}
if (regex.searchAlgorithm != SearchAlgorithm.NONE) {
int schRange = range;
if (regex.dMax != 0) {
if (regex.dMax == MinMaxLen.INFINITE_DISTANCE) {
schRange = end;
} else {
schRange += regex.dMax;
if (schRange > end) schRange = end;
}
}
if ((end - start) < regex.thresholdLength) return mismatch();
if (regex.dMax != MinMaxLen.INFINITE_DISTANCE) {
do {
if (!forwardSearchRange(bytes, str, end, s, schRange, this)) return mismatch(); // low, high, lowPrev
if (s < low) {
s = low;
prev = value;
}
while (s <= high) {
if (matchCheck(origRange, s, prev)) return match(s); // ???
prev = s;
s += enc.length(bytes, s, end);
}
} while (s < range);
return mismatch();
} else { /* check only. */
if (!forwardSearchRange(bytes, str, end, s, schRange, null)) return mismatch();
if ((regex.anchor & AnchorType.ANYCHAR_STAR) != 0) {
do {
if (matchCheck(origRange, s, prev)) return match(s);
prev = s;
s += enc.length(bytes, s, end);
while (!enc.isNewLine(bytes, prev, end) && s < range) {
prev = s;
s += enc.length(bytes, s, end);
}
} while (s < range);
return mismatch();
}
}
}
do {
if (matchCheck(origRange, s, prev)) return match(s);
prev = s;
s += enc.length(bytes, s, end);
} while (s < range);
if (s == range) { /* because empty match with /$/. */
if (matchCheck(origRange, s, prev)) return match(s);
}
} else { /* backward search */
if (Config.USE_MATCH_RANGE_MUST_BE_INSIDE_OF_SPECIFIED_RANGE) {
if (origStart < end) {
origStart += enc.length(bytes, origStart, end); // /* is upper range */
}
}
if (regex.searchAlgorithm != SearchAlgorithm.NONE) {
int adjrange;
if (range < end) {
adjrange = enc.leftAdjustCharHead(bytes, str, range, end);
} else {
adjrange = end;
}
if (regex.dMax != MinMaxLen.INFINITE_DISTANCE && (end - range) >= regex.thresholdLength) {
do {
int schStart = s + regex.dMax;
if (schStart > end) schStart = end;
if (!backwardSearchRange(bytes, str, end, schStart, range, adjrange)) return mismatch(); // low, high
if (s > high) s = high;
while (s >= low) {
prev = enc.prevCharHead(bytes, str, s, end);
if (matchCheck(origStart, s, prev)) return match(s);
s = prev;
}
} while (s >= range);
return mismatch();
} else { /* check only. */
if ((end - range) < regex.thresholdLength) return mismatch();
int schStart = s;
if (regex.dMax != 0) {
if (regex.dMax == MinMaxLen.INFINITE_DISTANCE) {
schStart = end;
} else {
schStart += regex.dMax;
if (schStart > end) {
schStart = end;
} else {
schStart = enc.leftAdjustCharHead(bytes, start, schStart, end);
}
}
}
if (!backwardSearchRange(bytes, str, end, schStart, range, adjrange)) return mismatch();
}
}
do {
prev = enc.prevCharHead(bytes, str, s, end);
if (matchCheck(origStart, s, prev)) return match(s);
s = prev;
} while (s >= range);
}
return mismatch();
}
| public final int search(int start, int range, int option) {
int s, prev;
int origStart = start;
int origRange = range;
if (Config.DEBUG_SEARCH) {
Config.log.println("onig_search (entry point): "+
"str: " + str +
", end: " + (end - str) +
", start: " + (start - str) +
", range " + (range - str));
}
if (start > end || start < str) return -1;
/* anchor optimize: resume search range */
if (regex.anchor != 0 && str < end) {
int minSemiEnd, maxSemiEnd;
if ((regex.anchor & AnchorType.BEGIN_POSITION) != 0) {
/* search start-position only */
// !begin_position:!
if (range > start) {
range = start + 1;
} else {
range = start;
}
} else if ((regex.anchor & AnchorType.BEGIN_BUF) != 0) {
/* search str-position only */
if (range > start) {
if (start != str) return -1; // mismatch_no_msa;
range = str + 1;
} else {
if (range <= str) {
start = str;
range = str;
} else {
return -1; // mismatch_no_msa;
}
}
} else if ((regex.anchor & AnchorType.END_BUF) != 0) {
minSemiEnd = maxSemiEnd = end;
// !end_buf:!
if (endBuf(start, range, minSemiEnd, maxSemiEnd)) return -1; // mismatch_no_msa;
} else if ((regex.anchor & AnchorType.SEMI_END_BUF) != 0) {
int preEnd = enc.stepBack(bytes, str, end, end, 1);
maxSemiEnd = end;
if (enc.isNewLine(bytes, preEnd, end)) {
minSemiEnd = preEnd;
if (Config.USE_CRNL_AS_LINE_TERMINATOR) {
preEnd = enc.stepBack(bytes, str, preEnd, end, 1);
if (preEnd != -1 && enc.isMbcCrnl(bytes, preEnd, end)) {
minSemiEnd = preEnd;
}
}
if (minSemiEnd > str && start <= minSemiEnd) {
// !goto end_buf;!
if (endBuf(start, range, minSemiEnd, maxSemiEnd)) return -1; // mismatch_no_msa;
}
} else {
minSemiEnd = end;
// !goto end_buf;!
if (endBuf(start, range, minSemiEnd, maxSemiEnd)) return -1; // mismatch_no_msa;
}
} else if ((regex.anchor & AnchorType.ANYCHAR_STAR_ML) != 0) {
// goto !begin_position;!
if (range > start) {
range = start + 1;
} else {
range = start;
}
}
} else if (str == end) { /* empty string */
// empty address ?
if (Config.DEBUG_SEARCH) {
Config.log.println("onig_search: empty string.");
}
if (regex.thresholdLength == 0) {
s = start = str;
prev = -1;
msaInit(option, start);
if (Config.USE_COMBINATION_EXPLOSION_CHECK) stateCheckBuffClear();
if (matchCheck(end, s, prev)) return match(s);
return mismatch();
}
return -1; // goto mismatch_no_msa;
}
if (Config.DEBUG_SEARCH) {
Config.log.println("onig_search(apply anchor): " +
"end: " + (end - str) +
", start " + (start - str) +
", range " + (range - str));
}
msaInit(option, origStart);
if (Config.USE_COMBINATION_EXPLOSION_CHECK) {
int offset = Math.min(start, range) - str;
stateCheckBuffInit(end - str, offset, regex.numCombExpCheck);
}
s = start;
if (range > start) { /* forward search */
if (s > str) {
prev = enc.prevCharHead(bytes, str, s, end);
} else {
prev = 0; // -1
}
if (regex.searchAlgorithm != SearchAlgorithm.NONE) {
int schRange = range;
if (regex.dMax != 0) {
if (regex.dMax == MinMaxLen.INFINITE_DISTANCE) {
schRange = end;
} else {
schRange += regex.dMax;
if (schRange > end) schRange = end;
}
}
if ((end - start) < regex.thresholdLength) return mismatch();
if (regex.dMax != MinMaxLen.INFINITE_DISTANCE) {
do {
if (!forwardSearchRange(bytes, str, end, s, schRange, this)) return mismatch(); // low, high, lowPrev
if (s < low) {
s = low;
prev = value;
}
while (s <= high) {
if (matchCheck(origRange, s, prev)) return match(s); // ???
prev = s;
s += enc.length(bytes, s, end);
}
} while (s < range);
return mismatch();
} else { /* check only. */
if (!forwardSearchRange(bytes, str, end, s, schRange, null)) return mismatch();
if ((regex.anchor & AnchorType.ANYCHAR_STAR) != 0) {
do {
if (matchCheck(origRange, s, prev)) return match(s);
prev = s;
s += enc.length(bytes, s, end);
while (!enc.isNewLine(bytes, prev, end) && s < range) {
prev = s;
s += enc.length(bytes, s, end);
}
} while (s < range);
return mismatch();
}
}
}
do {
if (matchCheck(origRange, s, prev)) return match(s);
prev = s;
s += enc.length(bytes, s, end);
} while (s < range);
if (s == range) { /* because empty match with /$/. */
if (matchCheck(origRange, s, prev)) return match(s);
}
} else { /* backward search */
if (Config.USE_MATCH_RANGE_MUST_BE_INSIDE_OF_SPECIFIED_RANGE) {
if (origStart < end) {
origStart += enc.length(bytes, origStart, end); // /* is upper range */
}
}
if (regex.searchAlgorithm != SearchAlgorithm.NONE) {
int adjrange;
if (range < end) {
adjrange = enc.leftAdjustCharHead(bytes, str, range, end);
} else {
adjrange = end;
}
if (regex.dMax != MinMaxLen.INFINITE_DISTANCE && (end - range) >= regex.thresholdLength) {
do {
int schStart = s + regex.dMax;
if (schStart > end) schStart = end;
if (!backwardSearchRange(bytes, str, end, schStart, range, adjrange)) return mismatch(); // low, high
if (s > high) s = high;
while (s != -1 && s >= low) {
prev = enc.prevCharHead(bytes, str, s, end);
if (matchCheck(origStart, s, prev)) return match(s);
s = prev;
}
} while (s >= range);
return mismatch();
} else { /* check only. */
if ((end - range) < regex.thresholdLength) return mismatch();
int schStart = s;
if (regex.dMax != 0) {
if (regex.dMax == MinMaxLen.INFINITE_DISTANCE) {
schStart = end;
} else {
schStart += regex.dMax;
if (schStart > end) {
schStart = end;
} else {
schStart = enc.leftAdjustCharHead(bytes, start, schStart, end);
}
}
}
if (!backwardSearchRange(bytes, str, end, schStart, range, adjrange)) return mismatch();
}
}
do {
prev = enc.prevCharHead(bytes, str, s, end);
if (matchCheck(origStart, s, prev)) return match(s);
s = prev;
} while (s >= range);
}
return mismatch();
}
|
diff --git a/src/com/jcope/vnc/server/screen/Monitor.java b/src/com/jcope/vnc/server/screen/Monitor.java
index 8fe2ad1..40ad308 100644
--- a/src/com/jcope/vnc/server/screen/Monitor.java
+++ b/src/com/jcope/vnc/server/screen/Monitor.java
@@ -1,301 +1,301 @@
package com.jcope.vnc.server.screen;
import java.awt.Rectangle;
import java.util.ArrayList;
import com.jcope.debug.LLog;
import com.jcope.util.SegmentationInfo;
import com.jcope.vnc.server.ClientHandler;
import com.jcope.vnc.server.DirectRobot;
import com.jcope.vnc.server.StateMachine;
import com.jcope.vnc.shared.StateMachine.SERVER_EVENT;
/**
*
* @author Joseph Copenhaver
*
* This class will contain registered listener interfaces that
* get notified when a particular screen changes graphically.
*
* For each ScreenMonitor there is exactly one screen device
* being sampled for which there can be one or more listening
* components.
*
* Components will be notified when a segment of a screen changes.
* It is then the responsibility of the listening component to fetch
* from this class the data segment of interest.
*
* Should all listeners be terminated, then the Screen Monitor shall
* terminate and be ready for garbage collection.
*
* Let each screen be broken up into segmentWidth by segmentHeight pixel segments.
*
* Let each segment be assigned an ID from left to right, top down where the first tile is ID 0
* Let segment ID -1 indicate the collection of segments as a whole (The entire screen)
*
*/
public class Monitor extends Thread
{
public static final long refreshMS = 1000;
int screenX, screenY;
SegmentationInfo segInfo = new SegmentationInfo();
private Integer screenWidth = null, screenHeight;
private ArrayList<ClientHandler> clients;
private DirectRobot dirbot;
private int[][] segments;
private boolean[] changedSegments;
private volatile boolean stopped = Boolean.FALSE;
private volatile boolean joined = Boolean.FALSE;
public Monitor(int segmentWidth, int segmentHeight, DirectRobot dirbot, ArrayList<ClientHandler> clients)
{
super(String.format("Monitor: %s", dirbot.toString()));
segInfo.segmentWidth = segmentWidth;
segInfo.segmentHeight = segmentHeight;
this.dirbot = dirbot;
this.clients = clients;
syncBounds();
}
private void syncBounds()
{
Integer lastWidth = screenWidth;
Integer lastHeight = screenHeight;
Rectangle bounds = getScreenBounds();
screenX = bounds.x;
screenY = bounds.y;
screenWidth = bounds.width;
screenHeight = bounds.height;
if (lastWidth == null || lastWidth != screenWidth || lastHeight != screenHeight)
{
segInfo.loadConfig(screenWidth, screenHeight, segInfo.segmentWidth, segInfo.segmentHeight);
segments = new int[segInfo.numSegments][];
changedSegments = new boolean[segInfo.numSegments];
for (int i=0; i<segInfo.numSegments; i++)
{
segments[i] = new int[getSegmentPixelCount(i)];
changedSegments[i] = Boolean.FALSE;
}
if (lastWidth != null)
{
// TODO: provide ability to lock a set of clients
for (ClientHandler client : clients)
{
StateMachine.handleServerEvent(client, SERVER_EVENT.SCREEN_RESIZED, screenWidth, screenHeight);
}
}
}
}
public void run()
{
// detect change in a segment of the configured screen
// notify all listeners of the changed segment
boolean changed;
int[] buffer = new int[segInfo.maxSegmentNumPixels];
int[] segmentDim = new int[2];
int x, y;
long startAt, timeConsumed;
ArrayList<ClientHandler> newClients = new ArrayList<ClientHandler>();
try
{
while (!stopped)
{
startAt = System.currentTimeMillis();
changed = Boolean.FALSE;
dirbot.markRGBCacheDirty();
for (int i=0; i<=segInfo.maxSegmentID; i++)
{
getSegmentPos(i, segmentDim);
x = segmentDim[0];
y = segmentDim[1];
getSegmentDim(i, segmentDim);
dirbot.getRGBPixels(x, y, segmentDim[0], segmentDim[1], buffer);
if (copyIntArray(segments[i], buffer, segments[i].length))
{
changed = Boolean.TRUE;
changedSegments[i] = Boolean.TRUE;
}
}
for (ClientHandler client : clients)
{
- if (!client.getIsNewFlag())
+ if (client.getIsNewFlag())
{
newClients.add(client);
}
}
if (changed)
{
for (ClientHandler client : clients)
{
- if (!client.getIsNewFlag())
+ if (client.getIsNewFlag())
{
continue;
}
ScreenListener l = client.getScreenListener(dirbot);
for (int i=0; i<changedSegments.length; i++)
{
if (changedSegments[i])
{
l.onScreenChange(i);
}
}
}
for (int i=0; i<changedSegments.length; i++)
{
changedSegments[i] = Boolean.FALSE;
}
}
if (newClients.size() > 0)
{
for (ClientHandler client : newClients)
{
client.setIsNewFlag(Boolean.FALSE);
ScreenListener l = client.getScreenListener(dirbot);
for (int i=0; i<segInfo.numSegments; i++)
{
l.onScreenChange(i);
}
}
newClients.clear();
}
timeConsumed = System.currentTimeMillis() - startAt;
if (timeConsumed < refreshMS)
{
try
{
sleep(refreshMS - timeConsumed);
}
catch (InterruptedException e)
{
LLog.e(e);
}
}
}
}
finally {
stopped = Boolean.TRUE;
joined = Boolean.TRUE;
}
}
public void sendDisplayInitEvents(ClientHandler client)
{
Rectangle bounds = getScreenBounds();
client.sendEvent(SERVER_EVENT.SCREEN_RESIZED, bounds.width, bounds.height);
client.sendEvent(SERVER_EVENT.SCREEN_SEGMENT_SIZE_UPDATE, segInfo.segmentWidth, segInfo.segmentHeight);
}
private boolean copyIntArray(int[] dst, int[] src, int length)
{
boolean rval = Boolean.FALSE;
for (int i=0; i<length; i++)
{
if (dst[i] != src[i])
{
dst[i] = src[i];
rval = Boolean.TRUE;
}
}
return rval;
}
public int getSegmentID(int x, int y)
{
int rval = segInfo.getSegmentID(x, y);
return rval;
}
public void getSegmentDim(int segmentID, int[] dim)
{
segInfo.getDim(segmentID, dim);
}
public void getSegmentPos(int segmentID, int[] absPos)
{
segInfo.getPos(segmentID, absPos);
absPos[0] += screenX;
absPos[1] += screenY;
}
public void getSegmentIdxPos(int segmentID, int[] pos)
{
segInfo.getIdxPos(segmentID, pos);
}
public int getSegmentPixelCount(int segmentID)
{
int rval = segInfo.getSegmentPixelCount(segmentID);
return rval;
}
public int getMaxSegmentPixelCount()
{
return segInfo.maxSegmentNumPixels;
}
public int getSegmentWidth()
{
return segInfo.segmentWidth;
}
public int getSegmentHeight()
{
return segInfo.segmentHeight;
}
public Rectangle getScreenBounds()
{
return dirbot.getScreenBounds();
}
public int getSegmentCount()
{
return segInfo.numSegments;
}
private void signalStop()
{
stopped = true;
}
public boolean isRunning()
{
return !stopped;
}
public boolean isJoined()
{
return joined;
}
public void kill()
{
signalStop();
}
public int[] getSegment(int segmentID)
{
int[] rval = (segmentID == -1) ? dirbot.getRGBPixels() : segments[segmentID];
return rval;
}
}
| false | true | public void run()
{
// detect change in a segment of the configured screen
// notify all listeners of the changed segment
boolean changed;
int[] buffer = new int[segInfo.maxSegmentNumPixels];
int[] segmentDim = new int[2];
int x, y;
long startAt, timeConsumed;
ArrayList<ClientHandler> newClients = new ArrayList<ClientHandler>();
try
{
while (!stopped)
{
startAt = System.currentTimeMillis();
changed = Boolean.FALSE;
dirbot.markRGBCacheDirty();
for (int i=0; i<=segInfo.maxSegmentID; i++)
{
getSegmentPos(i, segmentDim);
x = segmentDim[0];
y = segmentDim[1];
getSegmentDim(i, segmentDim);
dirbot.getRGBPixels(x, y, segmentDim[0], segmentDim[1], buffer);
if (copyIntArray(segments[i], buffer, segments[i].length))
{
changed = Boolean.TRUE;
changedSegments[i] = Boolean.TRUE;
}
}
for (ClientHandler client : clients)
{
if (!client.getIsNewFlag())
{
newClients.add(client);
}
}
if (changed)
{
for (ClientHandler client : clients)
{
if (!client.getIsNewFlag())
{
continue;
}
ScreenListener l = client.getScreenListener(dirbot);
for (int i=0; i<changedSegments.length; i++)
{
if (changedSegments[i])
{
l.onScreenChange(i);
}
}
}
for (int i=0; i<changedSegments.length; i++)
{
changedSegments[i] = Boolean.FALSE;
}
}
if (newClients.size() > 0)
{
for (ClientHandler client : newClients)
{
client.setIsNewFlag(Boolean.FALSE);
ScreenListener l = client.getScreenListener(dirbot);
for (int i=0; i<segInfo.numSegments; i++)
{
l.onScreenChange(i);
}
}
newClients.clear();
}
timeConsumed = System.currentTimeMillis() - startAt;
if (timeConsumed < refreshMS)
{
try
{
sleep(refreshMS - timeConsumed);
}
catch (InterruptedException e)
{
LLog.e(e);
}
}
}
}
finally {
stopped = Boolean.TRUE;
joined = Boolean.TRUE;
}
}
| public void run()
{
// detect change in a segment of the configured screen
// notify all listeners of the changed segment
boolean changed;
int[] buffer = new int[segInfo.maxSegmentNumPixels];
int[] segmentDim = new int[2];
int x, y;
long startAt, timeConsumed;
ArrayList<ClientHandler> newClients = new ArrayList<ClientHandler>();
try
{
while (!stopped)
{
startAt = System.currentTimeMillis();
changed = Boolean.FALSE;
dirbot.markRGBCacheDirty();
for (int i=0; i<=segInfo.maxSegmentID; i++)
{
getSegmentPos(i, segmentDim);
x = segmentDim[0];
y = segmentDim[1];
getSegmentDim(i, segmentDim);
dirbot.getRGBPixels(x, y, segmentDim[0], segmentDim[1], buffer);
if (copyIntArray(segments[i], buffer, segments[i].length))
{
changed = Boolean.TRUE;
changedSegments[i] = Boolean.TRUE;
}
}
for (ClientHandler client : clients)
{
if (client.getIsNewFlag())
{
newClients.add(client);
}
}
if (changed)
{
for (ClientHandler client : clients)
{
if (client.getIsNewFlag())
{
continue;
}
ScreenListener l = client.getScreenListener(dirbot);
for (int i=0; i<changedSegments.length; i++)
{
if (changedSegments[i])
{
l.onScreenChange(i);
}
}
}
for (int i=0; i<changedSegments.length; i++)
{
changedSegments[i] = Boolean.FALSE;
}
}
if (newClients.size() > 0)
{
for (ClientHandler client : newClients)
{
client.setIsNewFlag(Boolean.FALSE);
ScreenListener l = client.getScreenListener(dirbot);
for (int i=0; i<segInfo.numSegments; i++)
{
l.onScreenChange(i);
}
}
newClients.clear();
}
timeConsumed = System.currentTimeMillis() - startAt;
if (timeConsumed < refreshMS)
{
try
{
sleep(refreshMS - timeConsumed);
}
catch (InterruptedException e)
{
LLog.e(e);
}
}
}
}
finally {
stopped = Boolean.TRUE;
joined = Boolean.TRUE;
}
}
|
diff --git a/gsf-facades/src/main/java/com/fatwire/gst/foundation/facade/runtag/TagRunnerRuntimeException.java b/gsf-facades/src/main/java/com/fatwire/gst/foundation/facade/runtag/TagRunnerRuntimeException.java
index 910b11cf..b2cce3b7 100644
--- a/gsf-facades/src/main/java/com/fatwire/gst/foundation/facade/runtag/TagRunnerRuntimeException.java
+++ b/gsf-facades/src/main/java/com/fatwire/gst/foundation/facade/runtag/TagRunnerRuntimeException.java
@@ -1,98 +1,84 @@
/*
* Copyright 2008 FatWire Corporation. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.fatwire.gst.foundation.facade.runtag;
import COM.FutureTense.Interfaces.FTValList;
import COM.FutureTense.Util.ftErrors;
import com.fatwire.gst.foundation.CSRuntimeException;
/**
* Exception that is thrown when a TagRunner is invoked and the
*
* @author Dolf.Dijkstra
*/
public class TagRunnerRuntimeException extends CSRuntimeException {
private final String pageName;
private final String elementName;
private final FTValList arguments;
private static final long serialVersionUID = 5392042951880858120L;
/**
* @param msg
* @param errno
*/
public TagRunnerRuntimeException(String msg, int errno, final FTValList arguments) {
this(msg, errno, arguments, null, null, null);
}
public TagRunnerRuntimeException(String msg, int errno, final FTValList arguments, ftErrors complexError,
String pagename, String elementname) {
super(msg, complexError, errno);
this.arguments = arguments;
this.pageName = pagename;
this.elementName = elementname;
}
/**
* @return the pagename that generated this exception or null if this was
* not provided
*/
public String getPageName() {
return pageName;
}
/**
* @return the name of the element that generated this exception or null if
* this was not provided
*/
public String getElementName() {
return elementName;
}
public FTValList getArguments() {
return arguments;
}
@Override
public String getMessage() {
StringBuilder builder = new StringBuilder();
builder.append(super.getMessage());
builder.append("|");
builder.append(arguments);
builder.append("|");
builder.append(getPageName());
builder.append("|");
builder.append(getElementName());
- if (getComplexError() != null) {
- builder.append("|");
- builder.append("reason: ").append(getComplexError().getReason());
- builder.append("|message: ");
- builder.append(getComplexError().getMessage());
- int details = getComplexError().details();
- if (details > 0) {
- builder.append("|");
- }
- for (int i = 0; i < details; i++) {
- builder.append(" ");
- builder.append(getComplexError().detail(i));
- }
- }
return builder.toString();
}
}
| false | true | public String getMessage() {
StringBuilder builder = new StringBuilder();
builder.append(super.getMessage());
builder.append("|");
builder.append(arguments);
builder.append("|");
builder.append(getPageName());
builder.append("|");
builder.append(getElementName());
if (getComplexError() != null) {
builder.append("|");
builder.append("reason: ").append(getComplexError().getReason());
builder.append("|message: ");
builder.append(getComplexError().getMessage());
int details = getComplexError().details();
if (details > 0) {
builder.append("|");
}
for (int i = 0; i < details; i++) {
builder.append(" ");
builder.append(getComplexError().detail(i));
}
}
return builder.toString();
}
| public String getMessage() {
StringBuilder builder = new StringBuilder();
builder.append(super.getMessage());
builder.append("|");
builder.append(arguments);
builder.append("|");
builder.append(getPageName());
builder.append("|");
builder.append(getElementName());
return builder.toString();
}
|
diff --git a/sahi/src/main/java/com/redhat/qe/jon/sahi/tests/plugins/eap6/domain/DeploymentTest.java b/sahi/src/main/java/com/redhat/qe/jon/sahi/tests/plugins/eap6/domain/DeploymentTest.java
index d47f6336..6fbfb83c 100644
--- a/sahi/src/main/java/com/redhat/qe/jon/sahi/tests/plugins/eap6/domain/DeploymentTest.java
+++ b/sahi/src/main/java/com/redhat/qe/jon/sahi/tests/plugins/eap6/domain/DeploymentTest.java
@@ -1,147 +1,147 @@
package com.redhat.qe.jon.sahi.tests.plugins.eap6.domain;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import com.redhat.qe.Assert;
import com.redhat.qe.jon.sahi.base.inventory.Inventory;
import com.redhat.qe.jon.sahi.base.inventory.Inventory.ChildResources;
import com.redhat.qe.jon.sahi.base.inventory.Inventory.NewChildWizard;
import com.redhat.qe.jon.sahi.base.inventory.Operations;
import com.redhat.qe.jon.sahi.base.inventory.Operations.Operation;
import com.redhat.qe.jon.sahi.base.inventory.Resource;
import com.redhat.qe.jon.sahi.tasks.Timing;
import com.redhat.qe.jon.sahi.tests.plugins.eap6.AS7PluginSahiTasks;
/**
* @author Libor Zoubek ([email protected])
* @since 20.01.2011
* see TCMS cases
*/
public class DeploymentTest extends AS7DomainTest {
private static final int waitTime = Timing.WAIT_TIME;
private static final String war = "hello.war";
Resource serverGroup;
@BeforeClass(groups = "deployment")
protected void setupAS7Plugin() {
as7SahiTasks = new AS7PluginSahiTasks(sahiTasks);
as7SahiTasks.importResource(controller);
serverGroup = controller.child("main-server-group");
}
@Test(groups = "deployment")
public void createDomainDeploymentWAR() {
if (mgmtDomain.existsResource("", "deployment", war)) {
removeDeployment(war);
log.fine("Deployment removed using API, we have perform manual discovery for deployment to disappear from RHQ UI");
controller.performManualAutodiscovery();
}
Inventory inventory = controller.inventory();
ChildResources childResources = inventory.childResources();
NewChildWizard newChild = childResources.newChild("DomainDeployment");
newChild.next();
newChild.upload("/deploy/original/"+war);
//wait for upload to finish
sahiTasks.waitFor(2*waitTime);
newChild.next();
newChild.finish();
mgmtClient.assertResourcePresence("", "deployment", war, true);
controller.child(war).assertExists(true);
}
//@Test(groups = "deployment", dependsOnMethods="createDomainDeploymentWAR")
public void createDomainDeploymentWARv2() {
Inventory inventory = controller.inventory();
ChildResources childResources = inventory.childResources();
NewChildWizard newChild = childResources.newChild("DomainDeployment");
newChild.next();
newChild.upload("/deploy/modified/"+war);
//wait for upload to finish
sahiTasks.waitFor(2*waitTime);
newChild.next();
newChild.finish();
mgmtClient.assertResourcePresence("", "deployment", war, true);
controller.child(war).assertExists(true);
}
@Test(groups = "deployment", dependsOnMethods="createDomainDeploymentWAR")
public void deployToServerGroup() {
Operations operations = controller.child(war).operations();
- Operation op = operations.newOperation("Deploy to Server-Group");
+ Operation op = operations.newOperation("Assign to Server-Group");
sahiTasks.radio(serverGroup.getName()).check();
sahiTasks.waitFor(waitTime);
op.assertRequiredInputs();
op.schedule();
operations.assertOperationResult(op, true);
mgmtClient.assertResourcePresence("/server-group="+serverGroup.getName(), "deployment", war, true);
// deployments on server group are not recognized automatically, we need to run manual discovery
controller.performManualAutodiscovery();
log.fine("Waiting "+Timing.toString(waitTime*10)+" after manual autodiscovery..");
sahiTasks.waitFor(waitTime*10);
serverGroup.child(war).assertExists(true);
// we KNOW that managed servers server-one, server-two belong to main-server-group and are UP
// deployment should be on both of them
httpDomainOne.assertDeploymentContent(war, "Original", "Check whether original version of WAR has been deployed to "+httpDomainOne.getServerAddress());
httpDomainTwo.assertDeploymentContent(war, "Original", "Check whether original version of WAR has been deployed to "+httpDomainTwo.getServerAddress());
}
@Test(groups = "deployment", dependsOnMethods="deployToServerGroup")
public void undeployFromServerGroup() {
serverGroup.inventory().childResources().deleteChild(war);
mgmtClient.assertResourcePresence("/server-group="+serverGroup.getName(), "deployment", war, false);
serverGroup.child(war).assertExists(false);
Assert.assertTrue(!httpDomainOne.isDeploymentAvailable(war),"Deployment is no longer reachable on "+httpDomainOne.getServerAddress());
Assert.assertTrue(!httpDomainTwo.isDeploymentAvailable(war),"Deployment is no longer reachable on "+httpDomainTwo.getServerAddress());
//serverOne.child(war).assertExists(false);
//serverTwo.child(war).assertExists(false);
}
@Test(groups = "deployment", dependsOnMethods="undeployFromServerGroup")
public void removeDomainDeployment() {
controller.inventory().childResources().deleteChild(war);
mgmtDomain.assertResourcePresence("", "deployment", war, false);
controller.child(war).assertExists(false);
//serverOne.child(war).assertExists(false);
//serverTwo.child(war).assertExists(false);
}
@Test(groups = {"deployment","blockedByBug-815965"}, dependsOnMethods="removeDomainDeployment")
public void createWARChildOnServerGroup() {
Inventory inventory = serverGroup.inventory();
ChildResources childResources = inventory.childResources();
NewChildWizard newChild = childResources.newChild("Deployment");
newChild.next();
newChild.upload("/deploy/original/"+war);
//wait for upload to finish
sahiTasks.waitFor(2*waitTime);
newChild.next();
newChild.finish();
inventory.childHistory().assertLastResourceChange(true);
mgmtClient.assertResourcePresence("/server-group="+serverGroup.getName(), "deployment", war, true);
serverGroup.child(war).assertExists(true);
// we KNOW that managed servers server-one, server-two belong to main-server-group and are UP
// deployment should be on both of them
httpDomainOne.assertDeploymentContent(war, "Original", "Check whether original version of WAR has been deployed to "+httpDomainOne.getServerAddress());
httpDomainTwo.assertDeploymentContent(war, "Original", "Check whether original version of WAR has been deployed to "+httpDomainTwo.getServerAddress());
}
@Test(groups = {"deployment"}, dependsOnMethods="createWARChildOnServerGroup")
public void removeWARChildFromServerGroup() {
serverGroup.inventory().childResources().deleteChild(war);
mgmtClient.assertResourcePresence("/server-group="+serverGroup.getName(), "deployment", war, false);
serverGroup.child(war).assertExists(false);
Assert.assertTrue(!httpDomainOne.isDeploymentAvailable(war),"Deployment is no longer reachable on "+httpDomainOne.getServerAddress());
Assert.assertTrue(!httpDomainTwo.isDeploymentAvailable(war),"Deployment is no longer reachable on "+httpDomainTwo.getServerAddress());
//serverOne.child(war).assertExists(false);
//serverTwo.child(war).assertExists(false);
}
/**
* removes deployment
* @param name
*/
private void removeDeployment(String name) {
log.info("Removing deployment using DMR API");
if (mgmtDomain.executeOperationVoid("/deployment="+name, "remove", new String[]{})) {
log.info("[mgmt API] Deployment was removed");
}
}
}
| true | true | public void deployToServerGroup() {
Operations operations = controller.child(war).operations();
Operation op = operations.newOperation("Deploy to Server-Group");
sahiTasks.radio(serverGroup.getName()).check();
sahiTasks.waitFor(waitTime);
op.assertRequiredInputs();
op.schedule();
operations.assertOperationResult(op, true);
mgmtClient.assertResourcePresence("/server-group="+serverGroup.getName(), "deployment", war, true);
// deployments on server group are not recognized automatically, we need to run manual discovery
controller.performManualAutodiscovery();
log.fine("Waiting "+Timing.toString(waitTime*10)+" after manual autodiscovery..");
sahiTasks.waitFor(waitTime*10);
serverGroup.child(war).assertExists(true);
// we KNOW that managed servers server-one, server-two belong to main-server-group and are UP
// deployment should be on both of them
httpDomainOne.assertDeploymentContent(war, "Original", "Check whether original version of WAR has been deployed to "+httpDomainOne.getServerAddress());
httpDomainTwo.assertDeploymentContent(war, "Original", "Check whether original version of WAR has been deployed to "+httpDomainTwo.getServerAddress());
}
| public void deployToServerGroup() {
Operations operations = controller.child(war).operations();
Operation op = operations.newOperation("Assign to Server-Group");
sahiTasks.radio(serverGroup.getName()).check();
sahiTasks.waitFor(waitTime);
op.assertRequiredInputs();
op.schedule();
operations.assertOperationResult(op, true);
mgmtClient.assertResourcePresence("/server-group="+serverGroup.getName(), "deployment", war, true);
// deployments on server group are not recognized automatically, we need to run manual discovery
controller.performManualAutodiscovery();
log.fine("Waiting "+Timing.toString(waitTime*10)+" after manual autodiscovery..");
sahiTasks.waitFor(waitTime*10);
serverGroup.child(war).assertExists(true);
// we KNOW that managed servers server-one, server-two belong to main-server-group and are UP
// deployment should be on both of them
httpDomainOne.assertDeploymentContent(war, "Original", "Check whether original version of WAR has been deployed to "+httpDomainOne.getServerAddress());
httpDomainTwo.assertDeploymentContent(war, "Original", "Check whether original version of WAR has been deployed to "+httpDomainTwo.getServerAddress());
}
|
diff --git a/src/main/java/org/train/state/GameState.java b/src/main/java/org/train/state/GameState.java
index 412584e..f515405 100644
--- a/src/main/java/org/train/state/GameState.java
+++ b/src/main/java/org/train/state/GameState.java
@@ -1,268 +1,263 @@
package org.train.state;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import org.newdawn.slick.Color;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Input;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.StateBasedGame;
import org.train.app.Game;
import org.train.entity.Level;
import org.train.entity.Menu;
import org.train.entity.MenuItem;
import org.train.entity.MessageBox;
import org.train.factory.EffectFactory;
import org.train.helper.LevelHelper;
import org.train.other.LevelController;
import org.train.other.ResourceManager;
import org.train.other.Translator;
public class GameState extends BasicGameState {
private int stateId;
private Level level = null;
private Menu menu = null;
private Menu gameOverMenu = null;
private Translator translator;
private LevelController levelController;
private MessageBox messageBox;
private boolean wasFinished = false;
public GameState(int stateId) {
this.stateId = stateId;
}
@Override
public void init(final GameContainer container, final StateBasedGame game)
throws SlickException {
this.levelController = this.container.getComponent(LevelController.class);
this.translator = this.container.getComponent(Translator.class);
this.messageBox = this.container.getComponent(MessageBox.class);
this.messageBox.setBackgroundColor(Color.lightGray);
this.initMenuItems(container, game);
this.initGameOverMenuItems(container, game);
this.initLevel(container, game);
this.menu.close();
this.gameOverMenu.close();
}
private void initMenuItems(final GameContainer container, final StateBasedGame game) {
MenuItem continueItem = new MenuItem(this.translator.translate("Game.Menu.Continue"),
new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
GameState.this.menu.close();
GameState.this.gameOverMenu.close();
}
});
MenuItem repeatLevel = new MenuItem(this.translator.translate("Game.Menu.RepeatLevel"),
new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
GameState.this.initLevel(container, game);
GameState.this.menu.close();
GameState.this.gameOverMenu.close();
}
});
MenuItem subMenu = new MenuItem(this.translator.translate("Game.Menu.Menu"),
new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
GameState.this.menu.close();
GameState.this.gameOverMenu.close();
game.enterState(Game.MENU_FOR_GAME_STATE);
}
});
MenuItem mainMenu = new MenuItem(this.translator.translate("Game.Menu.MainMenu"),
new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
GameState.this.menu.close();
GameState.this.gameOverMenu.close();
game.enterState(Game.MENU_STATE);
}
});
List<MenuItem> menuItems = new ArrayList<MenuItem>();
menuItems.add(continueItem);
menuItems.add(repeatLevel);
menuItems.add(subMenu);
menuItems.add(mainMenu);
for (MenuItem item : menuItems) {
item.setMargin(30);
}
this.menu = new Menu(menuItems, container,
this.container.getComponent(ResourceManager.class),
this.container.getComponent(EffectFactory.class));
this.menu.setBackgroundColor(Color.lightGray);
}
private void initGameOverMenuItems(final GameContainer container, final StateBasedGame game) {
MenuItem repeatLevel = new MenuItem(this.translator.translate("Game.Menu.RepeatLevel"),
new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
GameState.this.initLevel(container, game);
GameState.this.menu.close();
GameState.this.gameOverMenu.close();
}
});
MenuItem subMenu = new MenuItem(this.translator.translate("Game.Menu.Menu"),
new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
GameState.this.menu.close();
GameState.this.gameOverMenu.close();
game.enterState(Game.MENU_FOR_GAME_STATE);
}
});
MenuItem mainMenu = new MenuItem(this.translator.translate("Game.Menu.MainMenu"),
new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
GameState.this.menu.close();
GameState.this.gameOverMenu.close();
game.enterState(Game.MENU_STATE);
}
});
List<MenuItem> gameOverMenuItems = new ArrayList<MenuItem>();
gameOverMenuItems.add(repeatLevel);
gameOverMenuItems.add(subMenu);
gameOverMenuItems.add(mainMenu);
for (MenuItem item : gameOverMenuItems) {
item.setMargin(30);
}
this.gameOverMenu = new Menu(gameOverMenuItems, container,
this.container.getComponent(ResourceManager.class),
this.container.getComponent(EffectFactory.class));
this.gameOverMenu.setBackgroundColor(Color.lightGray);
}
private void initLevel(GameContainer container, final StateBasedGame game) {
try {
this.wasFinished = false;
this.level = this.levelController.getCurrentLevel();
int itemSize = this.level.getOriginalImageSize();
LevelHelper levelHelper = this.container.getComponent(LevelHelper.class);
float scale = levelHelper.computeScale(container, this.level.getOriginalImageSize(),
new Dimension(this.level.getWidth(), this.level.getHeight()));
this.level.setScale(scale);
int width = this.level.getWidth() * (int) (itemSize * scale);
int height = this.level.getHeight() * (int) (itemSize * scale);
this.level.setMarginLeft((container.getWidth() - width) / 2);
this.level.setMarginTop((container.getHeight() - height) / 2);
if (!this.level.isValid()) {
this.messageBox.showConfirm(this.translator.translate("Game.LevelIsInvalid"),
new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
game.enterState(Game.EDITOR_STATE);
}
}, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
game.enterState(Game.MENU_FOR_GAME_STATE);
}
});
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void render(GameContainer container, StateBasedGame game, Graphics g)
throws SlickException {
this.level.render(container, game, g);
this.menu.render(container, game, g);
this.gameOverMenu.render(container, game, g);
this.messageBox.render(container, game, g);
}
@Override
public void update(final GameContainer container, final StateBasedGame game, int delta)
throws SlickException {
Input input = container.getInput();
if (!this.menu.isShowed() && input.isKeyPressed(Input.KEY_ESCAPE)
&& !this.level.isFinished() && !this.level.isOver()) {
this.menu.show();
}
if (this.level.isOver()) {
this.gameOverMenu.show();
- if (input.isKeyPressed(Input.KEY_ENTER) || input.isKeyPressed(Input.KEY_NUMPADENTER)) {
- this.initLevel(container, game);
- this.menu.close();
- this.gameOverMenu.show();
- }
}
if (this.level.isFinished()) {
if (this.levelController.nextLevelExist()) {
if (!this.wasFinished) {
this.wasFinished = true;
this.levelController.updateProgress();
}
this.messageBox.showConfirm(this.translator.translate("Game.LevelFinished"),
new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
GameState.this.levelController.loadNextLevel();
GameState.this.initLevel(container, game);
}
}, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
game.enterState(Game.MENU_STATE);
}
});
if (input.isKeyPressed(Input.KEY_ENTER)
|| input.isKeyPressed(Input.KEY_NUMPADENTER)) {
this.levelController.loadNextLevel();
this.initLevel(container, game);
this.messageBox.close();
}
} else {
this.messageBox.showConfirm(this.translator.translate("Game.Congratulation"),
new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
game.enterState(Game.MENU_FOR_GAME_STATE);
}
}, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
game.enterState(Game.MENU_STATE);
}
});
}
}
this.menu.update(container, game, delta);
this.gameOverMenu.update(container, game, delta);
if (this.menu.isShowed()) {
if (input.isKeyPressed(Input.KEY_ESCAPE)) {
this.menu.close();
}
} else if (!this.gameOverMenu.isShowed()) {
this.level.update(container, game, delta);
}
this.messageBox.update(container, game, delta);
input.clearKeyPressedRecord();
}
@Override
public int getID() {
return this.stateId;
}
}
| true | true | public void update(final GameContainer container, final StateBasedGame game, int delta)
throws SlickException {
Input input = container.getInput();
if (!this.menu.isShowed() && input.isKeyPressed(Input.KEY_ESCAPE)
&& !this.level.isFinished() && !this.level.isOver()) {
this.menu.show();
}
if (this.level.isOver()) {
this.gameOverMenu.show();
if (input.isKeyPressed(Input.KEY_ENTER) || input.isKeyPressed(Input.KEY_NUMPADENTER)) {
this.initLevel(container, game);
this.menu.close();
this.gameOverMenu.show();
}
}
if (this.level.isFinished()) {
if (this.levelController.nextLevelExist()) {
if (!this.wasFinished) {
this.wasFinished = true;
this.levelController.updateProgress();
}
this.messageBox.showConfirm(this.translator.translate("Game.LevelFinished"),
new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
GameState.this.levelController.loadNextLevel();
GameState.this.initLevel(container, game);
}
}, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
game.enterState(Game.MENU_STATE);
}
});
if (input.isKeyPressed(Input.KEY_ENTER)
|| input.isKeyPressed(Input.KEY_NUMPADENTER)) {
this.levelController.loadNextLevel();
this.initLevel(container, game);
this.messageBox.close();
}
} else {
this.messageBox.showConfirm(this.translator.translate("Game.Congratulation"),
new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
game.enterState(Game.MENU_FOR_GAME_STATE);
}
}, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
game.enterState(Game.MENU_STATE);
}
});
}
}
this.menu.update(container, game, delta);
this.gameOverMenu.update(container, game, delta);
if (this.menu.isShowed()) {
if (input.isKeyPressed(Input.KEY_ESCAPE)) {
this.menu.close();
}
} else if (!this.gameOverMenu.isShowed()) {
this.level.update(container, game, delta);
}
this.messageBox.update(container, game, delta);
input.clearKeyPressedRecord();
}
| public void update(final GameContainer container, final StateBasedGame game, int delta)
throws SlickException {
Input input = container.getInput();
if (!this.menu.isShowed() && input.isKeyPressed(Input.KEY_ESCAPE)
&& !this.level.isFinished() && !this.level.isOver()) {
this.menu.show();
}
if (this.level.isOver()) {
this.gameOverMenu.show();
}
if (this.level.isFinished()) {
if (this.levelController.nextLevelExist()) {
if (!this.wasFinished) {
this.wasFinished = true;
this.levelController.updateProgress();
}
this.messageBox.showConfirm(this.translator.translate("Game.LevelFinished"),
new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
GameState.this.levelController.loadNextLevel();
GameState.this.initLevel(container, game);
}
}, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
game.enterState(Game.MENU_STATE);
}
});
if (input.isKeyPressed(Input.KEY_ENTER)
|| input.isKeyPressed(Input.KEY_NUMPADENTER)) {
this.levelController.loadNextLevel();
this.initLevel(container, game);
this.messageBox.close();
}
} else {
this.messageBox.showConfirm(this.translator.translate("Game.Congratulation"),
new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
game.enterState(Game.MENU_FOR_GAME_STATE);
}
}, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
game.enterState(Game.MENU_STATE);
}
});
}
}
this.menu.update(container, game, delta);
this.gameOverMenu.update(container, game, delta);
if (this.menu.isShowed()) {
if (input.isKeyPressed(Input.KEY_ESCAPE)) {
this.menu.close();
}
} else if (!this.gameOverMenu.isShowed()) {
this.level.update(container, game, delta);
}
this.messageBox.update(container, game, delta);
input.clearKeyPressedRecord();
}
|
diff --git a/signserver/src/java/org/signserver/ejb/WorkerSessionBean.java b/signserver/src/java/org/signserver/ejb/WorkerSessionBean.java
index 40cbbfedf..8b3afa953 100644
--- a/signserver/src/java/org/signserver/ejb/WorkerSessionBean.java
+++ b/signserver/src/java/org/signserver/ejb/WorkerSessionBean.java
@@ -1,433 +1,433 @@
/*************************************************************************
* *
* SignServer: The OpenSource Automated Signing Server *
* *
* This software 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 any later version. *
* *
* See terms of license at gnu.org. *
* *
*************************************************************************/
package org.signserver.ejb;
import java.math.BigInteger;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.apache.log4j.Logger;
import org.ejbca.util.CertTools;
import org.signserver.common.ArchiveDataVO;
import org.signserver.common.AuthorizedClient;
import org.signserver.common.CryptoTokenAuthenticationFailureException;
import org.signserver.common.CryptoTokenOfflineException;
import org.signserver.common.GlobalConfiguration;
import org.signserver.common.IArchivableProcessResponse;
import org.signserver.common.ICertReqData;
import org.signserver.common.ISignResponse;
import org.signserver.common.ISignerCertReqInfo;
import org.signserver.common.IllegalRequestException;
import org.signserver.common.InvalidWorkerIdException;
import org.signserver.common.ProcessRequest;
import org.signserver.common.ProcessResponse;
import org.signserver.common.ProcessableConfig;
import org.signserver.common.RequestContext;
import org.signserver.common.SignServerConstants;
import org.signserver.common.SignServerException;
import org.signserver.common.WorkerConfig;
import org.signserver.common.WorkerStatus;
import org.signserver.ejb.interfaces.IGlobalConfigurationSession;
import org.signserver.ejb.interfaces.IServiceTimerSession;
import org.signserver.ejb.interfaces.IWorkerSession;
import org.signserver.server.IAuthorizer;
import org.signserver.server.IProcessable;
import org.signserver.server.IWorker;
import org.signserver.server.SignServerContext;
import org.signserver.server.WorkerFactory;
import org.signserver.server.statistics.Event;
import org.signserver.server.statistics.StatisticsManager;
/**
* The main worker session bean
*
*/
@Stateless
public class WorkerSessionBean implements IWorkerSession.ILocal, IWorkerSession.IRemote {
@PersistenceContext(unitName="SignServerJPA")
EntityManager em;
private static final long serialVersionUID = 1L;
@EJB
private IGlobalConfigurationSession.ILocal globalConfigurationSession;
@EJB
private IServiceTimerSession.ILocal serviceTimerSession;
/** Log4j instance for actual implementation class */
private static final Logger log = Logger.getLogger(WorkerSessionBean.class);
/** The local home interface of Worker Config entity bean. */
private WorkerConfigDataService workerConfigService = null;
/** The local home interface of archive entity bean. */
private ArchiveDataService archiveDataService = null;
@PostConstruct
public void create() {
workerConfigService = new WorkerConfigDataService(em);
archiveDataService = new ArchiveDataService(em);
}
/**
* @see org.signserver.ejb.interfaces.IWorkerSession#process(int, org.signserver.common.ISignRequest, java.security.cert.X509Certificate, java.lang.String)
*/
public ProcessResponse process(int workerId, ProcessRequest request, RequestContext requestContext) throws IllegalRequestException,
CryptoTokenOfflineException, SignServerException {
log.debug(">process: "+workerId);
IWorker worker = WorkerFactory.getInstance().getWorker(workerId, workerConfigService, globalConfigurationSession,new SignServerContext(em));
if(worker == null){
- throw new IllegalRequestException("Non-existing signerId");
+ throw new IllegalRequestException("Non-existing workerId");
}
if(!(worker instanceof IProcessable)){
throw new IllegalRequestException("Worker exists but isn't a processable.");
}
IProcessable processable = (IProcessable) worker;
IAuthorizer auth = WorkerFactory.getInstance().getAuthenticator(workerId, processable.getAuthenticationType(), worker.getStatus().getActiveSignerConfig(), em);
auth.isAuthorized(request, requestContext);
if(processable.getStatus().getActiveSignerConfig().getProperties().getProperty(SignServerConstants.DISABLED,"FALSE").equalsIgnoreCase("TRUE")){
throw new CryptoTokenOfflineException("Error Signer : " + workerId + " is disabled and cannot perform any signature operations");
}
WorkerConfig awc = processable.getStatus().getActiveSignerConfig();
Event event = StatisticsManager.startEvent(workerId, awc, em);
requestContext.put(RequestContext.STATISTICS_EVENT, event);
ProcessResponse res = null;
try {
res = processable.processData(request, requestContext);
if(res instanceof IArchivableProcessResponse){
IArchivableProcessResponse arres = (IArchivableProcessResponse) res;
if(processable.getStatus().getActiveSignerConfig().getProperties().getProperty(SignServerConstants.ARCHIVE,"FALSE").equalsIgnoreCase("TRUE")){
if(arres.getArchiveData() != null){
String requestIP = (String) requestContext.get(RequestContext.REMOTE_IP);
X509Certificate clientCert = (X509Certificate) requestContext.get(RequestContext.CLIENT_CERTIFICATE);
archiveDataService.create(ArchiveDataVO.TYPE_RESPONSE,workerId, arres.getArchiveId(), clientCert, requestIP, arres.getArchiveData());
}else{
log.error("Error archiving response generated of signer " + workerId + ", archiving is not supported by signer.");
}
}
}
StatisticsManager.endEvent(workerId, awc, em, event);
if(res instanceof ISignResponse){
log.info("Worker " + workerId + " Processed request " + ((ISignResponse) res).getRequestID() + " successfully");
}else{
log.info("Worker " + workerId + " Processed request successfully");
}
} catch (SignServerException e) {
log.error("SignServerException calling signer with id " + workerId + " : " +e.getMessage(),e);
throw e;
}
log.debug("<process " );
return res;
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#getStatus(int)
*/
public WorkerStatus getStatus(int workerId) throws InvalidWorkerIdException{
IWorker worker = WorkerFactory.getInstance().getWorker(workerId, workerConfigService, globalConfigurationSession,new SignServerContext(em));
if(worker == null){
throw new InvalidWorkerIdException("Given SignerId " + workerId + " doesn't exist");
}
return worker.getStatus();
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#getWorkerId(java.lang.String)
*/
public int getWorkerId(String signerName) {
return WorkerFactory.getInstance().getWorkerIdFromName(signerName.toUpperCase(), workerConfigService, globalConfigurationSession,new SignServerContext(em));
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#reloadConfiguration(int)
*/
public void reloadConfiguration(int workerId) {
if(workerId == 0){
globalConfigurationSession.reload();
}else{
WorkerFactory.getInstance().reloadWorker(workerId, workerConfigService, globalConfigurationSession,new SignServerContext(em));
}
if(workerId == 0 || globalConfigurationSession.getWorkers(GlobalConfiguration.WORKERTYPE_SERVICES).contains(new Integer(workerId))){
serviceTimerSession.unload(workerId);
serviceTimerSession.load(workerId);
}
StatisticsManager.flush(workerId);
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#activateSigner(int, java.lang.String)
*/
public void activateSigner(int signerId, String authenticationCode)
throws CryptoTokenAuthenticationFailureException,
CryptoTokenOfflineException, InvalidWorkerIdException {
IWorker worker = WorkerFactory.getInstance().getWorker(signerId, workerConfigService,globalConfigurationSession,new SignServerContext(em));
if(worker == null){
throw new InvalidWorkerIdException("Given SignerId " + signerId + " doesn't exist");
}
if(!(worker instanceof IProcessable)){
throw new InvalidWorkerIdException("Worker exists but isn't a signer.");
}
IProcessable signer = (IProcessable) worker;
signer.activateSigner(authenticationCode);
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#deactivateSigner(int)
*/
public boolean deactivateSigner(int signerId)
throws CryptoTokenOfflineException, InvalidWorkerIdException {
IWorker worker = WorkerFactory.getInstance().getWorker(signerId, workerConfigService,globalConfigurationSession,new SignServerContext(em));
if(worker == null){
throw new InvalidWorkerIdException("Given SignerId " + signerId + " doesn't exist");
}
if(!(worker instanceof IProcessable)){
throw new InvalidWorkerIdException("Worker exists but isn't a signer.");
}
IProcessable signer = (IProcessable) worker;
return signer.deactivateSigner();
}
/* (non-Javadoc)
* @see org.signserver.ejb.IWorkerSession#getCurrentSignerConfig(int)
*/
public WorkerConfig getCurrentWorkerConfig(int signerId){
return getWorkerConfig(signerId);
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#setWorkerProperty(int, java.lang.String, java.lang.String)
*/
public void setWorkerProperty(int workerId, String key, String value){
WorkerConfig config = getWorkerConfig(workerId);
config.setProperty(key.toUpperCase(),value);
workerConfigService.setWorkerConfig(workerId, config);
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#removeWorkerProperty(int, java.lang.String)
*/
public boolean removeWorkerProperty(int workerId, String key){
boolean result = false;
WorkerConfig config = getWorkerConfig(workerId);
result = config.removeProperty(key.toUpperCase());
if(config.getProperties().size() == 0){
workerConfigService.removeWorkerConfig(workerId);
log.debug("WorkerConfig is empty and therefore removed.");
}else{
workerConfigService.setWorkerConfig(workerId,config);
}
return result;
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#getAuthorizedClients(int)
*/
public Collection<AuthorizedClient> getAuthorizedClients(int signerId){
return new ProcessableConfig( getWorkerConfig(signerId)).getAuthorizedClients();
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#addAuthorizedClient(int, org.signserver.common.AuthorizedClient)
*/
public void addAuthorizedClient(int signerId, AuthorizedClient authClient){
WorkerConfig config = getWorkerConfig(signerId);
(new ProcessableConfig(config)).addAuthorizedClient(authClient);
workerConfigService.setWorkerConfig(signerId, config);
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#removeAuthorizedClient(int, org.signserver.common.AuthorizedClient)
*/
public boolean removeAuthorizedClient(int signerId, AuthorizedClient authClient){
boolean result = false;
WorkerConfig config = getWorkerConfig(signerId);
result = (new ProcessableConfig(config)).removeAuthorizedClient(authClient);
workerConfigService.setWorkerConfig(signerId, config);
return result;
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#getCertificateRequest(int, org.signserver.common.ISignerCertReqInfo)
*/
public ICertReqData getCertificateRequest(int signerId, ISignerCertReqInfo certReqInfo) throws
CryptoTokenOfflineException, InvalidWorkerIdException {
IWorker worker = WorkerFactory.getInstance().getWorker(signerId, workerConfigService,globalConfigurationSession,new SignServerContext(em));
if(worker == null){
throw new InvalidWorkerIdException("Given SignerId " + signerId + " doesn't exist");
}
if(!(worker instanceof IProcessable)){
throw new InvalidWorkerIdException("Worker exists but isn't a signer.");
}
IProcessable processable = (IProcessable) worker;
return processable.genCertificateRequest(certReqInfo);
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#destroyKey(int, int)
*/
public boolean destroyKey(int signerId, int purpose) throws InvalidWorkerIdException {
IWorker worker = WorkerFactory.getInstance().getWorker(signerId, workerConfigService,globalConfigurationSession,new SignServerContext(em));
if(worker == null){
throw new InvalidWorkerIdException("Given SignerId " + signerId + " doesn't exist");
}
if(!(worker instanceof IProcessable)){
throw new InvalidWorkerIdException("Worker exists but isn't a signer.");
}
IProcessable signer = (IProcessable) worker;
return signer.destroyKey(purpose);
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#uploadSignerCertificate(int, java.security.cert.X509Certificate, java.lang.String)
*/
public void uploadSignerCertificate(int signerId, X509Certificate signerCert, String scope){
WorkerConfig config = getWorkerConfig(signerId);
( new ProcessableConfig(config)).setSignerCertificate(signerCert,scope);
workerConfigService.setWorkerConfig(signerId, config);
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#uploadSignerCertificateChain(int, java.util.Collection, java.lang.String)
*/
public void uploadSignerCertificateChain(int signerId, Collection<Certificate> signerCerts, String scope){
WorkerConfig config = getWorkerConfig(signerId);
(new ProcessableConfig( config)).setSignerCertificateChain(signerCerts, scope);
workerConfigService.setWorkerConfig(signerId, config);
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#genFreeWorkerId()
*/
public int genFreeWorkerId(){
Collection<Integer> ids = globalConfigurationSession.getWorkers(GlobalConfiguration.WORKERTYPE_ALL);
int max = 0;
Iterator<Integer> iter = ids.iterator();
while(iter.hasNext()){
Integer id = iter.next();
if(id.intValue() > max){
max = id.intValue();
}
}
return max+1;
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#findArchiveDataFromArchiveId(int, java.lang.String)
*/
public ArchiveDataVO findArchiveDataFromArchiveId(int signerId, String archiveId){
ArchiveDataVO retval = null;
ArchiveDataBean adb = archiveDataService.findByArchiveId(ArchiveDataVO.TYPE_RESPONSE,signerId,archiveId);
if(adb != null){
retval = adb.getArchiveDataVO();
}
return retval;
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#findArchiveDatasFromRequestIP(int, java.lang.String)
*/
public List<ArchiveDataVO> findArchiveDatasFromRequestIP(int signerId, String requestIP){
ArrayList<ArchiveDataVO> retval = new ArrayList<ArchiveDataVO>();
Collection<ArchiveDataBean> result = archiveDataService.findByRequestIP(ArchiveDataVO.TYPE_RESPONSE,signerId,requestIP);
Iterator<ArchiveDataBean> iter = result.iterator();
while(iter.hasNext()){
ArchiveDataBean next = iter.next();
retval.add(next.getArchiveDataVO());
}
return retval;
}
/* (non-Javadoc)
* @see org.signserver.ejb.interfaces.IWorkerSession#findArchiveDatasFromRequestCertificate(int, java.math.BigInteger, java.lang.String)
*/
public List<ArchiveDataVO> findArchiveDatasFromRequestCertificate(int signerId, BigInteger requestCertSerialnumber, String requestCertIssuerDN){
ArrayList<ArchiveDataVO> retval = new ArrayList<ArchiveDataVO>();
Collection<ArchiveDataBean> result = archiveDataService.findByRequestCertificate(ArchiveDataVO.TYPE_RESPONSE,signerId,CertTools.stringToBCDNString(requestCertIssuerDN),requestCertSerialnumber.toString(16));
Iterator<ArchiveDataBean> iter = result.iterator();
while(iter.hasNext()){
ArchiveDataBean next = iter.next();
retval.add(next.getArchiveDataVO());
}
return retval;
}
private WorkerConfig getWorkerConfig(int workerId){
WorkerConfig workerConfig = workerConfigService.getWorkerConfig(workerId);
if(workerConfig == null){
workerConfigService.create(workerId, WorkerConfig.class.getName());
workerConfig = workerConfigService.getWorkerConfig(workerId);
}
return workerConfig;
}
}
| true | true | public ProcessResponse process(int workerId, ProcessRequest request, RequestContext requestContext) throws IllegalRequestException,
CryptoTokenOfflineException, SignServerException {
log.debug(">process: "+workerId);
IWorker worker = WorkerFactory.getInstance().getWorker(workerId, workerConfigService, globalConfigurationSession,new SignServerContext(em));
if(worker == null){
throw new IllegalRequestException("Non-existing signerId");
}
if(!(worker instanceof IProcessable)){
throw new IllegalRequestException("Worker exists but isn't a processable.");
}
IProcessable processable = (IProcessable) worker;
IAuthorizer auth = WorkerFactory.getInstance().getAuthenticator(workerId, processable.getAuthenticationType(), worker.getStatus().getActiveSignerConfig(), em);
auth.isAuthorized(request, requestContext);
if(processable.getStatus().getActiveSignerConfig().getProperties().getProperty(SignServerConstants.DISABLED,"FALSE").equalsIgnoreCase("TRUE")){
throw new CryptoTokenOfflineException("Error Signer : " + workerId + " is disabled and cannot perform any signature operations");
}
WorkerConfig awc = processable.getStatus().getActiveSignerConfig();
Event event = StatisticsManager.startEvent(workerId, awc, em);
requestContext.put(RequestContext.STATISTICS_EVENT, event);
ProcessResponse res = null;
try {
res = processable.processData(request, requestContext);
if(res instanceof IArchivableProcessResponse){
IArchivableProcessResponse arres = (IArchivableProcessResponse) res;
if(processable.getStatus().getActiveSignerConfig().getProperties().getProperty(SignServerConstants.ARCHIVE,"FALSE").equalsIgnoreCase("TRUE")){
if(arres.getArchiveData() != null){
String requestIP = (String) requestContext.get(RequestContext.REMOTE_IP);
X509Certificate clientCert = (X509Certificate) requestContext.get(RequestContext.CLIENT_CERTIFICATE);
archiveDataService.create(ArchiveDataVO.TYPE_RESPONSE,workerId, arres.getArchiveId(), clientCert, requestIP, arres.getArchiveData());
}else{
log.error("Error archiving response generated of signer " + workerId + ", archiving is not supported by signer.");
}
}
}
StatisticsManager.endEvent(workerId, awc, em, event);
if(res instanceof ISignResponse){
log.info("Worker " + workerId + " Processed request " + ((ISignResponse) res).getRequestID() + " successfully");
}else{
log.info("Worker " + workerId + " Processed request successfully");
}
} catch (SignServerException e) {
log.error("SignServerException calling signer with id " + workerId + " : " +e.getMessage(),e);
throw e;
}
log.debug("<process " );
return res;
}
| public ProcessResponse process(int workerId, ProcessRequest request, RequestContext requestContext) throws IllegalRequestException,
CryptoTokenOfflineException, SignServerException {
log.debug(">process: "+workerId);
IWorker worker = WorkerFactory.getInstance().getWorker(workerId, workerConfigService, globalConfigurationSession,new SignServerContext(em));
if(worker == null){
throw new IllegalRequestException("Non-existing workerId");
}
if(!(worker instanceof IProcessable)){
throw new IllegalRequestException("Worker exists but isn't a processable.");
}
IProcessable processable = (IProcessable) worker;
IAuthorizer auth = WorkerFactory.getInstance().getAuthenticator(workerId, processable.getAuthenticationType(), worker.getStatus().getActiveSignerConfig(), em);
auth.isAuthorized(request, requestContext);
if(processable.getStatus().getActiveSignerConfig().getProperties().getProperty(SignServerConstants.DISABLED,"FALSE").equalsIgnoreCase("TRUE")){
throw new CryptoTokenOfflineException("Error Signer : " + workerId + " is disabled and cannot perform any signature operations");
}
WorkerConfig awc = processable.getStatus().getActiveSignerConfig();
Event event = StatisticsManager.startEvent(workerId, awc, em);
requestContext.put(RequestContext.STATISTICS_EVENT, event);
ProcessResponse res = null;
try {
res = processable.processData(request, requestContext);
if(res instanceof IArchivableProcessResponse){
IArchivableProcessResponse arres = (IArchivableProcessResponse) res;
if(processable.getStatus().getActiveSignerConfig().getProperties().getProperty(SignServerConstants.ARCHIVE,"FALSE").equalsIgnoreCase("TRUE")){
if(arres.getArchiveData() != null){
String requestIP = (String) requestContext.get(RequestContext.REMOTE_IP);
X509Certificate clientCert = (X509Certificate) requestContext.get(RequestContext.CLIENT_CERTIFICATE);
archiveDataService.create(ArchiveDataVO.TYPE_RESPONSE,workerId, arres.getArchiveId(), clientCert, requestIP, arres.getArchiveData());
}else{
log.error("Error archiving response generated of signer " + workerId + ", archiving is not supported by signer.");
}
}
}
StatisticsManager.endEvent(workerId, awc, em, event);
if(res instanceof ISignResponse){
log.info("Worker " + workerId + " Processed request " + ((ISignResponse) res).getRequestID() + " successfully");
}else{
log.info("Worker " + workerId + " Processed request successfully");
}
} catch (SignServerException e) {
log.error("SignServerException calling signer with id " + workerId + " : " +e.getMessage(),e);
throw e;
}
log.debug("<process " );
return res;
}
|
diff --git a/src/uk/ac/cam/db538/dexter/dex/method/DexMethodWithCode.java b/src/uk/ac/cam/db538/dexter/dex/method/DexMethodWithCode.java
index 6a3954a3..80401677 100644
--- a/src/uk/ac/cam/db538/dexter/dex/method/DexMethodWithCode.java
+++ b/src/uk/ac/cam/db538/dexter/dex/method/DexMethodWithCode.java
@@ -1,219 +1,223 @@
package uk.ac.cam.db538.dexter.dex.method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import lombok.Getter;
import lombok.val;
import org.jf.dexlib.AnnotationSetItem;
import org.jf.dexlib.AnnotationVisibility;
import org.jf.dexlib.ClassDataItem.EncodedMethod;
import org.jf.dexlib.CodeItem;
import org.jf.dexlib.DebugInfoItem;
import org.jf.dexlib.DexFile;
import org.jf.dexlib.Util.AccessFlags;
import uk.ac.cam.db538.dexter.analysis.coloring.GraphColoring;
import uk.ac.cam.db538.dexter.dex.DexAnnotation;
import uk.ac.cam.db538.dexter.dex.DexAssemblingCache;
import uk.ac.cam.db538.dexter.dex.DexClass;
import uk.ac.cam.db538.dexter.dex.DexInstrumentationCache;
import uk.ac.cam.db538.dexter.dex.code.DexCode;
import uk.ac.cam.db538.dexter.dex.code.DexRegister;
import uk.ac.cam.db538.dexter.dex.code.insn.DexInstruction_Move;
import uk.ac.cam.db538.dexter.dex.code.insn.DexInstruction_MoveWide;
import uk.ac.cam.db538.dexter.dex.type.DexReferenceType;
import uk.ac.cam.db538.dexter.utils.NoDuplicatesList;
public abstract class DexMethodWithCode extends DexMethod {
@Getter protected DexCode code;
@Getter private final boolean direct;
private final NoDuplicatesList<DexRegister> parameterRegisters;
private final Map<DexRegister, DexRegister> parameterRegistersMappings;
public DexMethodWithCode(DexClass parent, String name, Set<AccessFlags> accessFlags,
DexPrototype prototype, DexCode code,
Set<DexAnnotation> annotations,
boolean direct) {
super(parent, name, accessFlags, prototype, annotations);
this.code = code;
this.direct = direct;
this.parameterRegisters = this.getPrototype().generateParameterRegisters(this.isStatic());
this.parameterRegistersMappings = new HashMap<DexRegister, DexRegister>();
if (this.code != null)
this.code.setParentMethod(this);
}
public DexMethodWithCode(DexClass parent, EncodedMethod methodInfo, AnnotationSetItem encodedAnnotations, boolean parseInstructions) {
super(parent, methodInfo, encodedAnnotations);
this.direct = methodInfo.isDirect();
this.parameterRegisters = this.getPrototype().generateParameterRegisters(this.isStatic());
this.parameterRegistersMappings = new HashMap<DexRegister, DexRegister>();
if (parseInstructions) {
this.code = new DexCode(methodInfo.codeItem, this, parent.getParentFile().getParsingCache());
val prototype = this.getPrototype();
val isStatic = this.isStatic();
val clazz = this.getParentClass();
// create the parameter-register mappings
val regCount = methodInfo.codeItem.getRegisterCount();
val paramCount = prototype.getParameterCount(isStatic);
for (int i = 0; i < paramCount; ++i) {
val paramRegId = prototype.getParameterRegisterId(i, regCount, isStatic);
val paramType = prototype.getParameterType(i, isStatic, clazz);
switch (paramType.getTypeSize()) {
case SINGLE:
val regSingle = code.getRegisterByOriginalNumber(paramRegId);
addParameterMapping_Single(i, regSingle);
break;
case WIDE:
val regWide1 = code.getRegisterByOriginalNumber(paramRegId);
val regWide2 = code.getRegisterByOriginalNumber(paramRegId + 1);
addParameterMapping_Wide(i, regWide1, regWide2);
break;
}
}
} else
this.code = null;
}
private void addParameterMapping_Single(int paramIndex, DexRegister codeReg) {
// if (!code.getUsedRegisters().contains(codeReg))
// return;
val paramType = this.getPrototype().getParameterType(paramIndex, this.isStatic(), this.getParentClass());
val regIndex = this.getPrototype().getFirstParameterRegisterIndex(paramIndex, isStatic());
val paramReg = parameterRegisters.get(regIndex);
val moveInsn = new DexInstruction_Move(code, codeReg, paramReg, paramType instanceof DexReferenceType);
moveInsn.setAuxiliaryElement(true);
code.insertBefore(moveInsn, code.getStartingLabel());
if (parameterRegistersMappings.containsKey(paramReg))
throw new RuntimeException("Multiple mappings of the same parameter");
else
parameterRegistersMappings.put(paramReg, codeReg);
}
private void addParameterMapping_Wide(int paramIndex, DexRegister codeReg1, DexRegister codeReg2) {
// if (!code.getUsedRegisters().contains(codeReg1) && !code.getUsedRegisters().contains(codeReg2))
// return;
val firstRegIndex = this.getPrototype().getFirstParameterRegisterIndex(paramIndex, isStatic());
val paramReg1 = parameterRegisters.get(firstRegIndex);
val paramReg2 = parameterRegisters.get(firstRegIndex + 1);
val moveInsn = new DexInstruction_MoveWide(code, codeReg1, codeReg2, paramReg1, paramReg2);
moveInsn.setAuxiliaryElement(true);
code.insertBefore(moveInsn, code.getStartingLabel());
if (parameterRegistersMappings.containsKey(paramReg1) || parameterRegistersMappings.containsKey(paramReg2))
throw new RuntimeException("Multiple mappings of the same parameter");
else {
parameterRegistersMappings.put(paramReg1, codeReg1);
parameterRegistersMappings.put(paramReg2, codeReg2);
}
}
public List<DexRegister> getParameterMappedRegisters() {
val list = new ArrayList<DexRegister>(parameterRegisters.size());
for (val paramReg : parameterRegisters) {
val codeReg = parameterRegistersMappings.get(paramReg);
// if (codeReg == null)
// throw new RuntimeException("Missing parameter register mapping (" + getParentClass().getType().getPrettyName() + "." + getName() + ")");
list.add(codeReg);
}
return list;
}
@Override
public boolean isVirtual() {
return !direct;
}
@Override
public void instrument(DexInstrumentationCache cache) {
code.instrument(cache);
if (isVirtual())
this.addAnnotation(
new DexAnnotation(getParentFile().getInternalMethodAnnotation_Type(),
AnnotationVisibility.RUNTIME));
}
@Override
protected CodeItem generateCodeItem(DexFile outFile, DexAssemblingCache cache) {
// do register allocation
// note that this changes the code itself
// (adds temporaries, inserts move instructions)
val codeColoring = new GraphColoring(code); // changes the code itself (potentially)
// add parameter registers to the register allocation
val registerAllocation = new HashMap<DexRegister, Integer>(codeColoring.getColoring());
int registerCount = codeColoring.getColorsUsed();
val inWords = this.getPrototype().countParamWords(this.isStatic());
- if (registerCount >= inWords) {
- int startReg = registerCount - inWords;
- for (int i = 0; i < inWords; ++i)
- registerAllocation.put(parameterRegisters.get(i), startReg + i);
- } else {
- for (int i = 0; i < inWords; ++i)
- registerAllocation.put(parameterRegisters.get(i), i);
- registerCount = inWords;
- }
+// if (registerCount >= inWords) {
+// int startReg = registerCount - inWords;
+// for (int i = 0; i < inWords; ++i)
+// registerAllocation.put(parameterRegisters.get(i), startReg + i);
+// } else {
+// for (int i = 0; i < inWords; ++i)
+// registerAllocation.put(parameterRegisters.get(i), i);
+// registerCount = inWords;
+// }
+ if (registerCount + inWords >= (1 << 16))
+ throw new RuntimeException("Cannot allocate paramter registers");
+ for (int i = 0; i < inWords; ++i)
+ registerAllocation.put(parameterRegisters.get(i), registerCount++);
// sometimes a register is not used in the code
// and thus would not get allocated...
// but if it's mapped to a parameter, assembling
// the move instruction would fail...
// so add these into the register allocation...
// the color doesn't matter
for (val reg : parameterRegistersMappings.values())
if (!registerAllocation.containsKey(reg))
registerAllocation.put(reg, 0);
// val assembledMoveInstructions = parameterMoveInstructions.assembleBytecode(registerAllocation, cache, 0);
// val assembledCode = code.assembleBytecode(registerAllocation, cache, assembledMoveInstructions.getTotalCodeLength());
val assembledCode = code.assembleBytecode(registerAllocation, cache, 0);
// List<Instruction> instructions = new ArrayList<Instruction>();
// instructions.addAll(assembledMoveInstructions.getInstructions());
// instructions.addAll(assembledCode.getInstructions());
val instructions = assembledCode.getInstructions();
// List<TryItem> tries = new ArrayList<TryItem>();
// tries.addAll(assembledMoveInstructions.getTries());
// tries.addAll(assembledCode.getTries());
val tries = assembledCode.getTries();
// List<EncodedCatchHandler> catchHandlers = new ArrayList<EncodedCatchHandler>();
// catchHandlers.addAll(assembledMoveInstructions.getCatchHandlers());
// catchHandlers.addAll(assembledCode.getCatchHandlers());
val catchHandlers = assembledCode.getCatchHandlers();
int outWords = code.getOutWords();
DebugInfoItem debugInfo = null;
return CodeItem.internCodeItem(outFile, registerCount, inWords, outWords, debugInfo, instructions, tries, catchHandlers);
}
@Override
public void markMethodOriginal() {
if (code != null)
code.markAllInstructionsOriginal();
}
}
| true | true | protected CodeItem generateCodeItem(DexFile outFile, DexAssemblingCache cache) {
// do register allocation
// note that this changes the code itself
// (adds temporaries, inserts move instructions)
val codeColoring = new GraphColoring(code); // changes the code itself (potentially)
// add parameter registers to the register allocation
val registerAllocation = new HashMap<DexRegister, Integer>(codeColoring.getColoring());
int registerCount = codeColoring.getColorsUsed();
val inWords = this.getPrototype().countParamWords(this.isStatic());
if (registerCount >= inWords) {
int startReg = registerCount - inWords;
for (int i = 0; i < inWords; ++i)
registerAllocation.put(parameterRegisters.get(i), startReg + i);
} else {
for (int i = 0; i < inWords; ++i)
registerAllocation.put(parameterRegisters.get(i), i);
registerCount = inWords;
}
// sometimes a register is not used in the code
// and thus would not get allocated...
// but if it's mapped to a parameter, assembling
// the move instruction would fail...
// so add these into the register allocation...
// the color doesn't matter
for (val reg : parameterRegistersMappings.values())
if (!registerAllocation.containsKey(reg))
registerAllocation.put(reg, 0);
// val assembledMoveInstructions = parameterMoveInstructions.assembleBytecode(registerAllocation, cache, 0);
// val assembledCode = code.assembleBytecode(registerAllocation, cache, assembledMoveInstructions.getTotalCodeLength());
val assembledCode = code.assembleBytecode(registerAllocation, cache, 0);
// List<Instruction> instructions = new ArrayList<Instruction>();
// instructions.addAll(assembledMoveInstructions.getInstructions());
// instructions.addAll(assembledCode.getInstructions());
val instructions = assembledCode.getInstructions();
// List<TryItem> tries = new ArrayList<TryItem>();
// tries.addAll(assembledMoveInstructions.getTries());
// tries.addAll(assembledCode.getTries());
val tries = assembledCode.getTries();
// List<EncodedCatchHandler> catchHandlers = new ArrayList<EncodedCatchHandler>();
// catchHandlers.addAll(assembledMoveInstructions.getCatchHandlers());
// catchHandlers.addAll(assembledCode.getCatchHandlers());
val catchHandlers = assembledCode.getCatchHandlers();
int outWords = code.getOutWords();
DebugInfoItem debugInfo = null;
return CodeItem.internCodeItem(outFile, registerCount, inWords, outWords, debugInfo, instructions, tries, catchHandlers);
}
| protected CodeItem generateCodeItem(DexFile outFile, DexAssemblingCache cache) {
// do register allocation
// note that this changes the code itself
// (adds temporaries, inserts move instructions)
val codeColoring = new GraphColoring(code); // changes the code itself (potentially)
// add parameter registers to the register allocation
val registerAllocation = new HashMap<DexRegister, Integer>(codeColoring.getColoring());
int registerCount = codeColoring.getColorsUsed();
val inWords = this.getPrototype().countParamWords(this.isStatic());
// if (registerCount >= inWords) {
// int startReg = registerCount - inWords;
// for (int i = 0; i < inWords; ++i)
// registerAllocation.put(parameterRegisters.get(i), startReg + i);
// } else {
// for (int i = 0; i < inWords; ++i)
// registerAllocation.put(parameterRegisters.get(i), i);
// registerCount = inWords;
// }
if (registerCount + inWords >= (1 << 16))
throw new RuntimeException("Cannot allocate paramter registers");
for (int i = 0; i < inWords; ++i)
registerAllocation.put(parameterRegisters.get(i), registerCount++);
// sometimes a register is not used in the code
// and thus would not get allocated...
// but if it's mapped to a parameter, assembling
// the move instruction would fail...
// so add these into the register allocation...
// the color doesn't matter
for (val reg : parameterRegistersMappings.values())
if (!registerAllocation.containsKey(reg))
registerAllocation.put(reg, 0);
// val assembledMoveInstructions = parameterMoveInstructions.assembleBytecode(registerAllocation, cache, 0);
// val assembledCode = code.assembleBytecode(registerAllocation, cache, assembledMoveInstructions.getTotalCodeLength());
val assembledCode = code.assembleBytecode(registerAllocation, cache, 0);
// List<Instruction> instructions = new ArrayList<Instruction>();
// instructions.addAll(assembledMoveInstructions.getInstructions());
// instructions.addAll(assembledCode.getInstructions());
val instructions = assembledCode.getInstructions();
// List<TryItem> tries = new ArrayList<TryItem>();
// tries.addAll(assembledMoveInstructions.getTries());
// tries.addAll(assembledCode.getTries());
val tries = assembledCode.getTries();
// List<EncodedCatchHandler> catchHandlers = new ArrayList<EncodedCatchHandler>();
// catchHandlers.addAll(assembledMoveInstructions.getCatchHandlers());
// catchHandlers.addAll(assembledCode.getCatchHandlers());
val catchHandlers = assembledCode.getCatchHandlers();
int outWords = code.getOutWords();
DebugInfoItem debugInfo = null;
return CodeItem.internCodeItem(outFile, registerCount, inWords, outWords, debugInfo, instructions, tries, catchHandlers);
}
|
diff --git a/bundles/org.eclipse.orion.server.git/src/org/eclipse/orion/server/git/servlets/GitJob.java b/bundles/org.eclipse.orion.server.git/src/org/eclipse/orion/server/git/servlets/GitJob.java
index 601a674e..38613b15 100644
--- a/bundles/org.eclipse.orion.server.git/src/org/eclipse/orion/server/git/servlets/GitJob.java
+++ b/bundles/org.eclipse.orion.server.git/src/org/eclipse/orion/server/git/servlets/GitJob.java
@@ -1,57 +1,57 @@
/*******************************************************************************
* Copyright (c) 2011 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.orion.server.git.servlets;
import com.jcraft.jsch.JSchException;
import java.util.Locale;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jgit.api.errors.JGitInternalException;
import org.eclipse.orion.server.core.ServerStatus;
import org.eclipse.orion.server.git.GitActivator;
import org.eclipse.orion.server.jsch.HostFingerprintException;
/**
* Base class for all Git jobs.
*
*/
public abstract class GitJob extends Job {
private static JSchException getJSchException(Throwable e) {
if (e instanceof JSchException) {
return (JSchException) e;
}
if (e.getCause() != null) {
return getJSchException(e.getCause());
}
return null;
}
public static IStatus getJGitInternalExceptionStatus(JGitInternalException e, String message) {
JSchException jschEx = getJSchException(e);
if (jschEx != null && jschEx instanceof HostFingerprintException) {
HostFingerprintException cause = (HostFingerprintException) jschEx;
return new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_FORBIDDEN, cause.getMessage(), cause.formJson(), cause);
}
//JSch handles auth fail by exception message
- if (jschEx.getMessage() != null && jschEx.getMessage().toLowerCase(Locale.ENGLISH).contains("auth fail")) {
+ if (jschEx != null && jschEx.getMessage() != null && jschEx.getMessage().toLowerCase(Locale.ENGLISH).contains("auth fail")) {
return new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_UNAUTHORIZED, jschEx.getMessage(), null, jschEx);
}
return new Status(IStatus.ERROR, GitActivator.PI_GIT, message, e);
}
public GitJob(String name) {
super(name);
}
}
| true | true | public static IStatus getJGitInternalExceptionStatus(JGitInternalException e, String message) {
JSchException jschEx = getJSchException(e);
if (jschEx != null && jschEx instanceof HostFingerprintException) {
HostFingerprintException cause = (HostFingerprintException) jschEx;
return new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_FORBIDDEN, cause.getMessage(), cause.formJson(), cause);
}
//JSch handles auth fail by exception message
if (jschEx.getMessage() != null && jschEx.getMessage().toLowerCase(Locale.ENGLISH).contains("auth fail")) {
return new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_UNAUTHORIZED, jschEx.getMessage(), null, jschEx);
}
return new Status(IStatus.ERROR, GitActivator.PI_GIT, message, e);
}
| public static IStatus getJGitInternalExceptionStatus(JGitInternalException e, String message) {
JSchException jschEx = getJSchException(e);
if (jschEx != null && jschEx instanceof HostFingerprintException) {
HostFingerprintException cause = (HostFingerprintException) jschEx;
return new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_FORBIDDEN, cause.getMessage(), cause.formJson(), cause);
}
//JSch handles auth fail by exception message
if (jschEx != null && jschEx.getMessage() != null && jschEx.getMessage().toLowerCase(Locale.ENGLISH).contains("auth fail")) {
return new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_UNAUTHORIZED, jschEx.getMessage(), null, jschEx);
}
return new Status(IStatus.ERROR, GitActivator.PI_GIT, message, e);
}
|
diff --git a/ext/java/nokogiri/XmlNode.java b/ext/java/nokogiri/XmlNode.java
index 8eab2596..263fdbd8 100644
--- a/ext/java/nokogiri/XmlNode.java
+++ b/ext/java/nokogiri/XmlNode.java
@@ -1,801 +1,813 @@
package nokogiri;
import nokogiri.internals.NokogiriHelpers;
import nokogiri.internals.XmlNodeImpl;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import nokogiri.internals.NokogiriNamespaceCache;
import nokogiri.internals.NokogiriUserDataHandler;
import nokogiri.internals.ParseOptions;
import nokogiri.internals.SaveContext;
import org.jruby.Ruby;
import org.jruby.RubyArray;
import org.jruby.RubyClass;
import org.jruby.RubyFixnum;
import org.jruby.RubyHash;
import org.jruby.RubyNil;
import org.jruby.RubyObject;
import org.jruby.RubyString;
import org.jruby.anno.JRubyMethod;
import org.jruby.exceptions.RaiseException;
import org.jruby.javasupport.util.RuntimeHelpers;
import org.jruby.runtime.Arity;
import org.jruby.runtime.Block;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.Visibility;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.util.ByteList;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import static java.lang.Math.max;
public class XmlNode extends RubyObject {
protected XmlNodeImpl internalNode;
protected NokogiriNamespaceCache nsCache;
/*
* Taken from http://ejohn.org/blog/comparing-document-position/
* Used for compareDocumentPosition.
* <ironic>Thanks to both java api and w3 doc for its helpful documentation</ironic>
*/
protected static final int IDENTICAL_ELEMENTS = 0;
protected static final int IN_DIFFERENT_DOCUMENTS = 1;
protected static final int SECOND_PRECEDES_FIRST = 2;
protected static final int FIRST_PRECEDES_SECOND = 4;
protected static final int SECOND_CONTAINS_FIRST = 8;
protected static final int FIRST_CONTAINS_SECOND = 16;
public XmlNode(Ruby ruby, RubyClass cls){
this(ruby,cls,null);
}
public XmlNode(Ruby ruby, RubyClass cls, Node node) {
super(ruby, cls);
this.nsCache = new NokogiriNamespaceCache();
this.internalNode = XmlNodeImpl.getImplForNode(ruby, node);
if(node != null && node.getNodeType() != Node.DOCUMENT_NODE) {
XmlDocument ownerXml = (XmlDocument) this.document(ruby.getCurrentContext());
// Don't touch this. Some nodes has no document
if(ownerXml == null) return;
RuntimeHelpers.invoke(ruby.getCurrentContext(), ownerXml, "decorate", this);
node.setUserData(NokogiriUserDataHandler.CACHED_NODE, this,
new NokogiriUserDataHandler(ruby));
}
}
protected void assimilateXmlNode(ThreadContext context, IRubyObject otherNode) {
XmlNode toAssimilate = asXmlNode(context, otherNode);
this.internalNode = toAssimilate.internalNode;
}
private static XmlNode asXmlNode(ThreadContext context, IRubyObject node) {
if (!(node instanceof XmlNode)) {
throw context.getRuntime().newTypeError(node, (RubyClass) context.getRuntime().getClassFromPath("Nokogiri::XML::Node"));
}
return (XmlNode) node;
}
/**
* Coalesce to adjacent TextNodes.
* @param context
* @param prev Previous node to cur.
* @param cur Next node to prev.
*/
public static void coalesceTextNodes(ThreadContext context, IRubyObject prev, IRubyObject cur) {
XmlNode p = asXmlNode(context, prev);
XmlNode c = asXmlNode(context, cur);
Node pNode = p.node();
Node cNode = c.node();
pNode.setNodeValue(pNode.getNodeValue()+cNode.getNodeValue());
p.internalNode.resetContent();
c.assimilateXmlNode(context, p);
}
/**
* Given three nodes such that firstNode is previousSibling of secondNode
* and secondNode is previousSibling of third node, this method coalesces
* two subsequent TextNodes.
* @param context
* @param firstNode
* @param secondNode
* @param thirdNode
*/
protected static void coalesceTextNodesInteligently(ThreadContext context, IRubyObject firstNode,
IRubyObject secondNode, IRubyObject thirdNode) {
Node first = (firstNode.isNil()) ? null : asXmlNode(context, firstNode).node();
Node second = asXmlNode(context, secondNode).node();
Node third = (thirdNode.isNil()) ? null : asXmlNode(context, thirdNode).node();
if(second.getNodeType() == Node.TEXT_NODE) {
if(first != null && first.getNodeType() == Node.TEXT_NODE) {
coalesceTextNodes(context, firstNode, secondNode);
} else if(third != null && third.getNodeType() == Node.TEXT_NODE) {
coalesceTextNodes(context, secondNode, thirdNode);
}
}
}
public static IRubyObject constructNode(Ruby ruby, Node node) {
if (node == null) return ruby.getNil();
// this is slow; need a way to cache nokogiri classes/modules somewhere
switch (node.getNodeType()) {
case Node.ATTRIBUTE_NODE:
return new XmlAttr(ruby, node);
case Node.TEXT_NODE:
return new XmlText(ruby, (RubyClass)ruby.getClassFromPath("Nokogiri::XML::Text"), node);
case Node.COMMENT_NODE:
return new XmlComment(ruby, (RubyClass)ruby.getClassFromPath("Nokogiri::XML::Comment"), node);
case Node.ELEMENT_NODE:
return new XmlElement(ruby, (RubyClass)ruby.getClassFromPath("Nokogiri::XML::Element"), node);
case Node.ENTITY_NODE:
return new XmlNode(ruby, (RubyClass)ruby.getClassFromPath("Nokogiri::XML::EntityDeclaration"), node);
case Node.CDATA_SECTION_NODE:
return new XmlCdata(ruby, (RubyClass)ruby.getClassFromPath("Nokogiri::XML::CDATA"), node);
case Node.DOCUMENT_NODE:
return new XmlDocument(ruby, (Document) node);
case Node.DOCUMENT_TYPE_NODE:
return new XmlDtd(ruby, (RubyClass)ruby.getClassFromPath("Nokogiri::XML::DTD"), node);
default:
return new XmlNode(ruby, (RubyClass)ruby.getClassFromPath("Nokogiri::XML::Node"), node);
}
}
protected RubyArray getNsDefinitions(Ruby ruby) {
return this.internalNode.getNsDefinitions(ruby);
}
public Node getNode() {
return this.internalNode.getNode();
}
public static Node getNodeFromXmlNode(ThreadContext context, IRubyObject xmlNode) {
return asXmlNode(context, xmlNode).node();
}
protected Node getNodeToCompare() {
return this.getNode();
}
protected String indentString(IRubyObject indentStringObject, String xml) {
String[] lines = xml.split("\n");
if(lines.length <= 1) return xml;
String[] resultLines = new String[lines.length];
String curLine;
boolean closingTag = false;
String indentString = indentStringObject.convertToString().asJavaString();
int lengthInd = indentString.length();
StringBuffer curInd = new StringBuffer();
resultLines[0] = lines[0];
for(int i = 1; i < lines.length; i++) {
curLine = lines[i].trim();
if(curLine.length() == 0) continue;
if(curLine.startsWith("</")) {
closingTag = true;
curInd.setLength(max(0,curInd.length() - lengthInd));
}
resultLines[i] = curInd.toString() + curLine;
if(!curLine.endsWith("/>") && !closingTag) {
curInd.append(indentString);
}
closingTag = false;
}
StringBuffer result = new StringBuffer();
for(int i = 0; i < resultLines.length; i++) {
result.append(resultLines[i]);
result.append("\n");
}
return result.toString();
}
@JRubyMethod
public IRubyObject internal_node(ThreadContext context) {
return context.getRuntime().newData(this.getType(), this.getNode());
}
public boolean isComment() { return this.internalNode.methods().isComment(); }
public boolean isElement() { return this.internalNode.methods().isElement(); }
public boolean isProcessingInstruction() { return this.internalNode.methods().isProcessingInstruction(); }
/*
* A more rubyist way to get the internal node.
*/
public Node node() {
return this.getNode();
}
protected IRubyObject parseRubyString(Ruby ruby, RubyString content) {
try {
Document document;
ByteList byteList = content.getByteList();
ByteArrayInputStream bais = new ByteArrayInputStream(byteList.unsafeBytes(), byteList.begin(), byteList.length());
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
dbf.setIgnoringElementContentWhitespace(false);
DocumentBuilder db = dbf.newDocumentBuilder();
db.setEntityResolver(new EntityResolver() {
public InputSource resolveEntity(String arg0, String arg1) throws SAXException, IOException {
return new InputSource(new ByteArrayInputStream(new byte[0]));
}
});
document = db.parse(bais);
return constructNode(ruby, document.getFirstChild());
} catch (ParserConfigurationException pce) {
throw RaiseException.createNativeRaiseException(ruby, pce);
} catch (SAXException saxe) {
throw RaiseException.createNativeRaiseException(ruby, saxe);
} catch (IOException ioe) {
throw RaiseException.createNativeRaiseException(ruby, ioe);
}
}
public void post_add_child(ThreadContext context, XmlNode current, XmlNode child) {
this.internalNode.post_add_child(context, current, child);
}
public void relink_namespace(ThreadContext context) {
this.internalNode.methods().relink_namespace(context, this);
((XmlNodeSet) this.children(context)).relink_namespace(context);
}
public void resetDocumentCache() {
this.internalNode.resetDocument();
}
public void resetDueToRenaming() {
this.internalNode.resetName();
}
public void saveContent(ThreadContext context, SaveContext ctx) {
this.internalNode.methods().saveContent(context, this, ctx);
}
public void saveContentAsHtml(ThreadContext context, SaveContext ctx) {
this.internalNode.saveContentAsHtml(context, this, ctx);
}
public void setDocument(IRubyObject doc) {
this.internalNode.setDocument(doc);
}
public void setInternalNode(XmlNodeImpl impl) {
this.internalNode = impl;
}
public void setName(IRubyObject name) {
this.internalNode.setName(name);
}
protected void setNode(Ruby ruby, Node node) {
this.internalNode = XmlNodeImpl.getImplForNode(ruby, node);
}
public void updateNodeNamespaceIfNecessary(ThreadContext context, XmlNamespace ns) {
String oldPrefix = this.node().getPrefix();
String uri = ns.href(context).convertToString().asJavaString();
/*
* Update if both prefixes are null or equal
*/
boolean update = (oldPrefix == null && ns.prefix(context).isNil()) ||
(oldPrefix != null && !ns.prefix(context).isNil()
&& oldPrefix.equals(ns.prefix(context).convertToString().asJavaString()));
if(update) {
this.node().getOwnerDocument().renameNode(this.node(), uri, this.node().getNodeName());
this.internalNode.setNamespace(ns);
}
}
@JRubyMethod(name = "new", meta = true)
public static IRubyObject rbNew(ThreadContext context, IRubyObject cls, IRubyObject name, IRubyObject doc, Block block) {
Ruby ruby = context.getRuntime();
if(!(doc instanceof XmlDocument)) {
throw ruby.newArgumentError("document must be an instance of Nokogiri::XML::Document");
}
XmlDocument xmlDoc = (XmlDocument)doc;
Document document = xmlDoc.getDocument();
Element element = document.createElementNS(null, name.convertToString().asJavaString());
RubyClass klazz = (RubyClass) cls;
if(cls.equals(ruby.getClassFromPath("Nokogiri::XML::Node"))) {
klazz = (RubyClass) ruby.getClassFromPath("Nokogiri::XML::Element");
}
XmlElement node = new XmlElement(ruby,
klazz,
element);
node.internalNode.setDocument(doc);
RuntimeHelpers.invoke(context, xmlDoc, "decorate", node);
element.setUserData(NokogiriUserDataHandler.CACHED_NODE,
node, new NokogiriUserDataHandler(ruby));
if(block.isGiven()) block.call(context, node);
return node;
}
@JRubyMethod
public IRubyObject add_child(ThreadContext context, IRubyObject child) {
XmlNode childNode = asXmlNode(context, child);
childNode.internalNode.methods().add_child(context, this, childNode);
return child;
}
@JRubyMethod
public IRubyObject add_child_node(ThreadContext context, IRubyObject child) {
return add_child(context, child);
}
@JRubyMethod
public IRubyObject add_namespace_definition(ThreadContext context, IRubyObject prefix, IRubyObject href) {
String prefixString = prefix.isNil() ? "" : prefix.convertToString().asJavaString();
String hrefString = href.convertToString().asJavaString();
XmlNamespace ns = this.nsCache.get(context, this, prefixString, hrefString);
this.internalNode.methods().add_namespace_definitions(context, this, ns,
(prefix.isNil()) ? "xmlns" : "xmlns:"+prefixString, hrefString);
this.internalNode.resetNamespaceDefinitions();
return ns;
}
@JRubyMethod
public IRubyObject add_next_sibling(ThreadContext context, IRubyObject appendNode) {
IRubyObject nextSibling = this.next_sibling(context);
XmlNode otherNode = asXmlNode(context, appendNode);
Node next = this.node().getNextSibling();
if (next != null) {
this.node().getParentNode().insertBefore(otherNode.node(), next);
} else {
this.node().getParentNode().appendChild(otherNode.node());
}
RuntimeHelpers.invoke(context, otherNode, "decorate!");
coalesceTextNodesInteligently(context, this, appendNode, nextSibling);
return otherNode;
}
@JRubyMethod
public IRubyObject add_previous_sibling(ThreadContext context, IRubyObject node) {
IRubyObject previousSibling = this.previous_sibling(context);
XmlNode otherNode = asXmlNode(context, node);
try{
this.node().getParentNode().insertBefore(otherNode.node(), this.node());
} catch (DOMException ex) {
throw context.getRuntime().newRuntimeError("This should not happen: "+ex.getMessage());
}
RuntimeHelpers.invoke(context , otherNode, "decorate!");
coalesceTextNodesInteligently(context, previousSibling, otherNode, this);
return node;
}
@JRubyMethod
public IRubyObject attribute(ThreadContext context, IRubyObject name){
NamedNodeMap attrs = this.node().getAttributes();
Node attr = attrs.getNamedItem(name.convertToString().asJavaString());
if(attr == null) {
return context.getRuntime().newString(ERR_INSECURE_SET_INST_VAR);
}
return constructNode(context.getRuntime(), attr);
}
@JRubyMethod
public IRubyObject attribute_nodes(ThreadContext context) {
NamedNodeMap nodeMap = this.node().getAttributes();
Ruby ruby = context.getRuntime();
if(nodeMap == null){
return ruby.newEmptyArray();
}
RubyArray attr = ruby.newArray();
for(int i = 0; i < nodeMap.getLength(); i++) {
attr.append(NokogiriHelpers.getCachedNodeOrCreate(ruby, nodeMap.item(i)));
}
return attr;
}
@JRubyMethod
public IRubyObject attribute_with_ns(ThreadContext context, IRubyObject name, IRubyObject namespace) {
String namej = name.convertToString().asJavaString();
String nsj = (namespace.isNil()) ? null : namespace.convertToString().asJavaString();
Node el = this.node().getAttributes().getNamedItemNS(nsj, namej);
if(el == null) {
return context.getRuntime().getNil();
}
return NokogiriHelpers.getCachedNodeOrCreate(context.getRuntime(), el);
}
@JRubyMethod
public IRubyObject attributes(ThreadContext context) {
Ruby ruby = context.getRuntime();
RubyHash hash = RubyHash.newHash(ruby);
NamedNodeMap attrs = node().getAttributes();
for (int i = 0; i < attrs.getLength(); i++) {
Node attr = attrs.item(i);
hash.op_aset(context, RubyString.newString(ruby, attr.getNodeName()), RubyString.newString(ruby, attr.getNodeValue()));
}
return hash;
}
@JRubyMethod(name = "blank?")
public IRubyObject blank_p(ThreadContext context) {
return this.internalNode.methods().blank_p(context, this);
}
@JRubyMethod
public IRubyObject child(ThreadContext context) {
return constructNode(context.getRuntime(), node().getFirstChild());
}
@JRubyMethod
public IRubyObject children(ThreadContext context) {
return this.internalNode.children(context, this);
}
@JRubyMethod
public IRubyObject compare(ThreadContext context, IRubyObject otherNode) {
if(!(otherNode instanceof XmlNode)) {
return context.getRuntime().newFixnum(-2);
}
Node on = ((XmlNode) otherNode).getNodeToCompare();
// Do not touch this if, if it's not for a good reason.
if(getNodeToCompare().getNodeType() == Node.DOCUMENT_NODE ||
on.getNodeType() == Node.DOCUMENT_NODE) {
return context.getRuntime().newFixnum(-1);
}
try{
int res = getNodeToCompare().compareDocumentPosition(on);
if( (res & FIRST_PRECEDES_SECOND) == FIRST_PRECEDES_SECOND) {
return context.getRuntime().newFixnum(-1);
} else if ( (res & SECOND_PRECEDES_FIRST) == SECOND_PRECEDES_FIRST) {
return context.getRuntime().newFixnum(1);
} else if ( res == IDENTICAL_ELEMENTS) {
return context.getRuntime().newFixnum(0);
}
return context.getRuntime().newFixnum(-2);
} catch (Exception ex) {
return context.getRuntime().newFixnum(-2);
}
}
@JRubyMethod
public IRubyObject content(ThreadContext context) {
return this.internalNode.getContent(context);
}
@JRubyMethod
public IRubyObject document(ThreadContext context) {
return this.internalNode.getDocument(context);
}
@JRubyMethod
public IRubyObject dup(ThreadContext context) {
return this.dup_implementation(context, true);
}
@JRubyMethod
public IRubyObject dup(ThreadContext context, IRubyObject depth) {
boolean deep = depth.convertToInteger().getLongValue() != 0;
return this.dup_implementation(context, deep);
}
protected IRubyObject dup_implementation(ThreadContext context, boolean deep) {
Node newNode = this.internalNode.cloneNode(context, this, deep);
return new XmlNode(context.getRuntime(), this.getType(), newNode);
}
@JRubyMethod
public IRubyObject encode_special_chars(ThreadContext context, IRubyObject string) {
String s = string.convertToString().asJavaString();
return RubyString.newString(context.getRuntime(),
NokogiriHelpers.encodeJavaString(s));
}
@JRubyMethod(visibility = Visibility.PRIVATE)
public IRubyObject get(ThreadContext context, IRubyObject attribute) {
return this.internalNode.methods().get(context, this, attribute);
}
@JRubyMethod
public IRubyObject internal_subset(ThreadContext context) {
if(this.node().getOwnerDocument() == null) {
return context.getRuntime().getNil();
}
return XmlNode.constructNode(context.getRuntime(), this.node().getOwnerDocument().getDoctype());
}
@JRubyMethod(name = "key?")
public IRubyObject key_p(ThreadContext context, IRubyObject k) {
return this.internalNode.methods().key_p(context, this, k);
}
@JRubyMethod
public IRubyObject namespace(ThreadContext context){
return this.internalNode.getNamespace(context);
}
@JRubyMethod
public IRubyObject namespace_definitions(ThreadContext context) {
return this.getNsDefinitions(context.getRuntime());
}
@JRubyMethod(name="namespaced_key?")
public IRubyObject namespaced_key_p(ThreadContext context, IRubyObject elementLName, IRubyObject namespaceUri) {
return this.attribute_with_ns(context, elementLName, namespaceUri).isNil() ?
context.getRuntime().getFalse() : context.getRuntime().getTrue();
}
@JRubyMethod
public IRubyObject namespaces(ThreadContext context) {
Ruby ruby = context.getRuntime();
RubyHash hash = RubyHash.newHash(ruby);
NamedNodeMap attrs = node().getAttributes();
for (int i = 0; i < attrs.getLength(); i++) {
Node attr = attrs.item(i);
hash.op_aset(context, RubyString.newString(ruby, attr.getNodeName()), RubyString.newString(ruby, attr.getNodeValue()));
}
return hash;
}
@JRubyMethod(name = "native_content=", visibility = Visibility.PRIVATE)
public IRubyObject native_content_set(ThreadContext context, IRubyObject content) {
RubyString newContent = content.convertToString();
this.internalNode.setContent(newContent);
this.node().setTextContent(newContent.asJavaString());
return content;
}
@JRubyMethod(required=4, visibility=Visibility.PRIVATE)
public IRubyObject native_write_to(ThreadContext context, IRubyObject[] args) {//IRubyObject io, IRubyObject encoding, IRubyObject indentString, IRubyObject options) {
IRubyObject io = args[0];
IRubyObject encoding = args[1];
IRubyObject indentString = args[2];
IRubyObject options = args[3];
String encString = encoding.isNil() ? null : encoding.convertToString().asJavaString();
int opt = (int) options.convertToInteger().getLongValue();
SaveContext ctx = new SaveContext(opt,
indentString.convertToString().asJavaString(),
encString);
if(ctx.asHtml()){
this.saveContentAsHtml(context, ctx);
} else {
this.saveContent(context, ctx);
}
RuntimeHelpers.invoke(context, io, "write", context.getRuntime().newString(ctx.toString()));
return io;
}
@JRubyMethod
public IRubyObject next_sibling(ThreadContext context) {
return constructNode(context.getRuntime(), node().getNextSibling());
}
@JRubyMethod(meta = true, rest = true)
public static IRubyObject new_from_str(ThreadContext context, IRubyObject cls, IRubyObject[] args) {
// TODO: duplicating code from Document.read_memory
Ruby ruby = context.getRuntime();
Arity.checkArgumentCount(ruby, args, 4, 4);
ParseOptions options = new ParseOptions(args[3]);
try {
Document document;
RubyString content = args[0].convertToString();
ByteList byteList = content.getByteList();
ByteArrayInputStream bais = new ByteArrayInputStream(byteList.unsafeBytes(), byteList.begin(), byteList.length());
document = options.getDocumentBuilder().parse(bais);
return constructNode(ruby, document.getFirstChild());
} catch (ParserConfigurationException pce) {
throw RaiseException.createNativeRaiseException(ruby, pce);
} catch (SAXException saxe) {
throw RaiseException.createNativeRaiseException(ruby, saxe);
} catch (IOException ioe) {
throw RaiseException.createNativeRaiseException(ruby, ioe);
}
}
@JRubyMethod
public IRubyObject node_name(ThreadContext context) {
return this.internalNode.getNodeName(context);
}
@JRubyMethod(name = "node_name=")
public IRubyObject node_name_set(ThreadContext context, IRubyObject nodeName) {
this.internalNode.methods().node_name_set(context, this, nodeName);
return nodeName;
}
@JRubyMethod(name = "[]=")
public IRubyObject op_aset(ThreadContext context, IRubyObject index, IRubyObject val) {
this.internalNode.methods().op_aset(context, this, index, val);
return val;
}
@JRubyMethod
public IRubyObject parent(ThreadContext context) {
/*
* Check if this node is the root node of the document.
* If so, parent is the document.
*/
if(node().getOwnerDocument().getDocumentElement() == node()) {
return document(context);
} else {
return NokogiriHelpers.getCachedNodeOrCreate(context.getRuntime(), node().getParentNode());
}
}
@JRubyMethod(name = "parent=")
public IRubyObject parent_set(ThreadContext context, IRubyObject parent) {
Node otherNode = getNodeFromXmlNode(context, parent);
otherNode.appendChild(node());
return parent;
}
@JRubyMethod
public IRubyObject path(ThreadContext context) {
return RubyString.newString(context.getRuntime(), NokogiriHelpers.getNodeCompletePath(this.node()));
}
@JRubyMethod
public IRubyObject pointer_id(ThreadContext context) {
return RubyFixnum.newFixnum(context.getRuntime(), this.node().hashCode());
}
@JRubyMethod
public IRubyObject previous_sibling(ThreadContext context) {
return constructNode(context.getRuntime(), node().getPreviousSibling());
}
@JRubyMethod
public IRubyObject remove_attribute(ThreadContext context, IRubyObject name) {
this.internalNode.methods().remove_attribute(context, this, name);
return context.getRuntime().getNil();
}
@JRubyMethod(name="replace_with_node", visibility=Visibility.PROTECTED)
public IRubyObject replace(ThreadContext context, IRubyObject newNode) {
Node otherNode = getNodeFromXmlNode(context, newNode);
if(!otherNode.getOwnerDocument().equals(node().getOwnerDocument())) {
node().getOwnerDocument().adoptNode(otherNode);
}
node().getParentNode().replaceChild(otherNode, node());
((XmlNode) newNode).relink_namespace(context);
return this;
}
@JRubyMethod(visibility=Visibility.PRIVATE)
public IRubyObject set_namespace(ThreadContext context, IRubyObject namespace) {
this.internalNode.setNamespace(namespace);
this.internalNode.resetNamespaceDefinitions();
XmlNamespace ns = (XmlNamespace) namespace;
String prefix = ns.prefix(context).convertToString().asJavaString();
String href = ns.href(context).convertToString().asJavaString();
this.node().getOwnerDocument().renameNode(node(), href, NokogiriHelpers.newQName(prefix, node()));
return this;
}
@JRubyMethod
public IRubyObject unlink(ThreadContext context) {
this.internalNode.methods().unlink(context, this);
return this;
}
@JRubyMethod(name = "node_type")
public IRubyObject xmlType(ThreadContext context) {
return this.internalNode.methods().getNokogiriNodeType(context);
}
@JRubyMethod
public IRubyObject line(ThreadContext context) {
Node root = internalNode.getDocument(context).getDocument();
int[] counter = new int[1];
count(root, counter);
return RubyFixnum.newFixnum(context.getRuntime(), counter[0]+1);
}
private boolean count(Node node, int[] counter) {
if (node == this.getNode()) {
return true;
}
NodeList list = node.getChildNodes();
for (int i=0; i<list.getLength(); i++) {
Node n = list.item(i);
if (n instanceof Text
&& ((Text)n).getData().contains("\n")) {
counter[0] += 1;
}
if (count(n, counter)) return true;
}
return false;
}
@JRubyMethod
public IRubyObject next_element(ThreadContext context) {
Node node = this.getNode().getNextSibling();
- if (node == null) return context.getRuntime().getNil();
Ruby ruby = context.getRuntime();
+ if (node == null) return ruby.getNil();
if (node instanceof Element) {
return new XmlElement(ruby, (RubyClass)ruby.getClassFromPath("Nokogiri::XML::Element"), node);
}
Node deeper = node.getNextSibling();
- if (deeper == null) return context.getRuntime().getNil();
+ if (deeper == null) return ruby.getNil();
return new XmlElement(ruby, (RubyClass)ruby.getClassFromPath("Nokogiri::XML::Element"), deeper);
}
+ @JRubyMethod
+ public IRubyObject previous_element(ThreadContext context) {
+ Node node = this.getNode().getPreviousSibling();
+ Ruby ruby = context.getRuntime();
+ if (node == null) return ruby.getNil();
+ if (node instanceof Element) {
+ return new XmlElement(ruby, (RubyClass)ruby.getClassFromPath("Nokogiri::XML::Element"), node);
+ }
+ Node shallower = node.getPreviousSibling();
+ if (shallower == null) return ruby.getNil();
+ return new XmlElement(ruby, (RubyClass)ruby.getClassFromPath("Nokogiri::XML::Element"), shallower);
+ }
}
| false | true | public IRubyObject native_write_to(ThreadContext context, IRubyObject[] args) {//IRubyObject io, IRubyObject encoding, IRubyObject indentString, IRubyObject options) {
IRubyObject io = args[0];
IRubyObject encoding = args[1];
IRubyObject indentString = args[2];
IRubyObject options = args[3];
String encString = encoding.isNil() ? null : encoding.convertToString().asJavaString();
int opt = (int) options.convertToInteger().getLongValue();
SaveContext ctx = new SaveContext(opt,
indentString.convertToString().asJavaString(),
encString);
if(ctx.asHtml()){
this.saveContentAsHtml(context, ctx);
} else {
this.saveContent(context, ctx);
}
RuntimeHelpers.invoke(context, io, "write", context.getRuntime().newString(ctx.toString()));
return io;
}
@JRubyMethod
public IRubyObject next_sibling(ThreadContext context) {
return constructNode(context.getRuntime(), node().getNextSibling());
}
@JRubyMethod(meta = true, rest = true)
public static IRubyObject new_from_str(ThreadContext context, IRubyObject cls, IRubyObject[] args) {
// TODO: duplicating code from Document.read_memory
Ruby ruby = context.getRuntime();
Arity.checkArgumentCount(ruby, args, 4, 4);
ParseOptions options = new ParseOptions(args[3]);
try {
Document document;
RubyString content = args[0].convertToString();
ByteList byteList = content.getByteList();
ByteArrayInputStream bais = new ByteArrayInputStream(byteList.unsafeBytes(), byteList.begin(), byteList.length());
document = options.getDocumentBuilder().parse(bais);
return constructNode(ruby, document.getFirstChild());
} catch (ParserConfigurationException pce) {
throw RaiseException.createNativeRaiseException(ruby, pce);
} catch (SAXException saxe) {
throw RaiseException.createNativeRaiseException(ruby, saxe);
} catch (IOException ioe) {
throw RaiseException.createNativeRaiseException(ruby, ioe);
}
}
@JRubyMethod
public IRubyObject node_name(ThreadContext context) {
return this.internalNode.getNodeName(context);
}
@JRubyMethod(name = "node_name=")
public IRubyObject node_name_set(ThreadContext context, IRubyObject nodeName) {
this.internalNode.methods().node_name_set(context, this, nodeName);
return nodeName;
}
@JRubyMethod(name = "[]=")
public IRubyObject op_aset(ThreadContext context, IRubyObject index, IRubyObject val) {
this.internalNode.methods().op_aset(context, this, index, val);
return val;
}
@JRubyMethod
public IRubyObject parent(ThreadContext context) {
/*
* Check if this node is the root node of the document.
* If so, parent is the document.
*/
if(node().getOwnerDocument().getDocumentElement() == node()) {
return document(context);
} else {
return NokogiriHelpers.getCachedNodeOrCreate(context.getRuntime(), node().getParentNode());
}
}
@JRubyMethod(name = "parent=")
public IRubyObject parent_set(ThreadContext context, IRubyObject parent) {
Node otherNode = getNodeFromXmlNode(context, parent);
otherNode.appendChild(node());
return parent;
}
@JRubyMethod
public IRubyObject path(ThreadContext context) {
return RubyString.newString(context.getRuntime(), NokogiriHelpers.getNodeCompletePath(this.node()));
}
@JRubyMethod
public IRubyObject pointer_id(ThreadContext context) {
return RubyFixnum.newFixnum(context.getRuntime(), this.node().hashCode());
}
@JRubyMethod
public IRubyObject previous_sibling(ThreadContext context) {
return constructNode(context.getRuntime(), node().getPreviousSibling());
}
@JRubyMethod
public IRubyObject remove_attribute(ThreadContext context, IRubyObject name) {
this.internalNode.methods().remove_attribute(context, this, name);
return context.getRuntime().getNil();
}
@JRubyMethod(name="replace_with_node", visibility=Visibility.PROTECTED)
public IRubyObject replace(ThreadContext context, IRubyObject newNode) {
Node otherNode = getNodeFromXmlNode(context, newNode);
if(!otherNode.getOwnerDocument().equals(node().getOwnerDocument())) {
node().getOwnerDocument().adoptNode(otherNode);
}
node().getParentNode().replaceChild(otherNode, node());
((XmlNode) newNode).relink_namespace(context);
return this;
}
@JRubyMethod(visibility=Visibility.PRIVATE)
public IRubyObject set_namespace(ThreadContext context, IRubyObject namespace) {
this.internalNode.setNamespace(namespace);
this.internalNode.resetNamespaceDefinitions();
XmlNamespace ns = (XmlNamespace) namespace;
String prefix = ns.prefix(context).convertToString().asJavaString();
String href = ns.href(context).convertToString().asJavaString();
this.node().getOwnerDocument().renameNode(node(), href, NokogiriHelpers.newQName(prefix, node()));
return this;
}
@JRubyMethod
public IRubyObject unlink(ThreadContext context) {
this.internalNode.methods().unlink(context, this);
return this;
}
@JRubyMethod(name = "node_type")
public IRubyObject xmlType(ThreadContext context) {
return this.internalNode.methods().getNokogiriNodeType(context);
}
@JRubyMethod
public IRubyObject line(ThreadContext context) {
Node root = internalNode.getDocument(context).getDocument();
int[] counter = new int[1];
count(root, counter);
return RubyFixnum.newFixnum(context.getRuntime(), counter[0]+1);
}
private boolean count(Node node, int[] counter) {
if (node == this.getNode()) {
return true;
}
NodeList list = node.getChildNodes();
for (int i=0; i<list.getLength(); i++) {
Node n = list.item(i);
if (n instanceof Text
&& ((Text)n).getData().contains("\n")) {
counter[0] += 1;
}
if (count(n, counter)) return true;
}
return false;
}
@JRubyMethod
public IRubyObject next_element(ThreadContext context) {
Node node = this.getNode().getNextSibling();
if (node == null) return context.getRuntime().getNil();
Ruby ruby = context.getRuntime();
if (node instanceof Element) {
return new XmlElement(ruby, (RubyClass)ruby.getClassFromPath("Nokogiri::XML::Element"), node);
}
Node deeper = node.getNextSibling();
if (deeper == null) return context.getRuntime().getNil();
return new XmlElement(ruby, (RubyClass)ruby.getClassFromPath("Nokogiri::XML::Element"), deeper);
}
}
| public IRubyObject native_write_to(ThreadContext context, IRubyObject[] args) {//IRubyObject io, IRubyObject encoding, IRubyObject indentString, IRubyObject options) {
IRubyObject io = args[0];
IRubyObject encoding = args[1];
IRubyObject indentString = args[2];
IRubyObject options = args[3];
String encString = encoding.isNil() ? null : encoding.convertToString().asJavaString();
int opt = (int) options.convertToInteger().getLongValue();
SaveContext ctx = new SaveContext(opt,
indentString.convertToString().asJavaString(),
encString);
if(ctx.asHtml()){
this.saveContentAsHtml(context, ctx);
} else {
this.saveContent(context, ctx);
}
RuntimeHelpers.invoke(context, io, "write", context.getRuntime().newString(ctx.toString()));
return io;
}
@JRubyMethod
public IRubyObject next_sibling(ThreadContext context) {
return constructNode(context.getRuntime(), node().getNextSibling());
}
@JRubyMethod(meta = true, rest = true)
public static IRubyObject new_from_str(ThreadContext context, IRubyObject cls, IRubyObject[] args) {
// TODO: duplicating code from Document.read_memory
Ruby ruby = context.getRuntime();
Arity.checkArgumentCount(ruby, args, 4, 4);
ParseOptions options = new ParseOptions(args[3]);
try {
Document document;
RubyString content = args[0].convertToString();
ByteList byteList = content.getByteList();
ByteArrayInputStream bais = new ByteArrayInputStream(byteList.unsafeBytes(), byteList.begin(), byteList.length());
document = options.getDocumentBuilder().parse(bais);
return constructNode(ruby, document.getFirstChild());
} catch (ParserConfigurationException pce) {
throw RaiseException.createNativeRaiseException(ruby, pce);
} catch (SAXException saxe) {
throw RaiseException.createNativeRaiseException(ruby, saxe);
} catch (IOException ioe) {
throw RaiseException.createNativeRaiseException(ruby, ioe);
}
}
@JRubyMethod
public IRubyObject node_name(ThreadContext context) {
return this.internalNode.getNodeName(context);
}
@JRubyMethod(name = "node_name=")
public IRubyObject node_name_set(ThreadContext context, IRubyObject nodeName) {
this.internalNode.methods().node_name_set(context, this, nodeName);
return nodeName;
}
@JRubyMethod(name = "[]=")
public IRubyObject op_aset(ThreadContext context, IRubyObject index, IRubyObject val) {
this.internalNode.methods().op_aset(context, this, index, val);
return val;
}
@JRubyMethod
public IRubyObject parent(ThreadContext context) {
/*
* Check if this node is the root node of the document.
* If so, parent is the document.
*/
if(node().getOwnerDocument().getDocumentElement() == node()) {
return document(context);
} else {
return NokogiriHelpers.getCachedNodeOrCreate(context.getRuntime(), node().getParentNode());
}
}
@JRubyMethod(name = "parent=")
public IRubyObject parent_set(ThreadContext context, IRubyObject parent) {
Node otherNode = getNodeFromXmlNode(context, parent);
otherNode.appendChild(node());
return parent;
}
@JRubyMethod
public IRubyObject path(ThreadContext context) {
return RubyString.newString(context.getRuntime(), NokogiriHelpers.getNodeCompletePath(this.node()));
}
@JRubyMethod
public IRubyObject pointer_id(ThreadContext context) {
return RubyFixnum.newFixnum(context.getRuntime(), this.node().hashCode());
}
@JRubyMethod
public IRubyObject previous_sibling(ThreadContext context) {
return constructNode(context.getRuntime(), node().getPreviousSibling());
}
@JRubyMethod
public IRubyObject remove_attribute(ThreadContext context, IRubyObject name) {
this.internalNode.methods().remove_attribute(context, this, name);
return context.getRuntime().getNil();
}
@JRubyMethod(name="replace_with_node", visibility=Visibility.PROTECTED)
public IRubyObject replace(ThreadContext context, IRubyObject newNode) {
Node otherNode = getNodeFromXmlNode(context, newNode);
if(!otherNode.getOwnerDocument().equals(node().getOwnerDocument())) {
node().getOwnerDocument().adoptNode(otherNode);
}
node().getParentNode().replaceChild(otherNode, node());
((XmlNode) newNode).relink_namespace(context);
return this;
}
@JRubyMethod(visibility=Visibility.PRIVATE)
public IRubyObject set_namespace(ThreadContext context, IRubyObject namespace) {
this.internalNode.setNamespace(namespace);
this.internalNode.resetNamespaceDefinitions();
XmlNamespace ns = (XmlNamespace) namespace;
String prefix = ns.prefix(context).convertToString().asJavaString();
String href = ns.href(context).convertToString().asJavaString();
this.node().getOwnerDocument().renameNode(node(), href, NokogiriHelpers.newQName(prefix, node()));
return this;
}
@JRubyMethod
public IRubyObject unlink(ThreadContext context) {
this.internalNode.methods().unlink(context, this);
return this;
}
@JRubyMethod(name = "node_type")
public IRubyObject xmlType(ThreadContext context) {
return this.internalNode.methods().getNokogiriNodeType(context);
}
@JRubyMethod
public IRubyObject line(ThreadContext context) {
Node root = internalNode.getDocument(context).getDocument();
int[] counter = new int[1];
count(root, counter);
return RubyFixnum.newFixnum(context.getRuntime(), counter[0]+1);
}
private boolean count(Node node, int[] counter) {
if (node == this.getNode()) {
return true;
}
NodeList list = node.getChildNodes();
for (int i=0; i<list.getLength(); i++) {
Node n = list.item(i);
if (n instanceof Text
&& ((Text)n).getData().contains("\n")) {
counter[0] += 1;
}
if (count(n, counter)) return true;
}
return false;
}
@JRubyMethod
public IRubyObject next_element(ThreadContext context) {
Node node = this.getNode().getNextSibling();
Ruby ruby = context.getRuntime();
if (node == null) return ruby.getNil();
if (node instanceof Element) {
return new XmlElement(ruby, (RubyClass)ruby.getClassFromPath("Nokogiri::XML::Element"), node);
}
Node deeper = node.getNextSibling();
if (deeper == null) return ruby.getNil();
return new XmlElement(ruby, (RubyClass)ruby.getClassFromPath("Nokogiri::XML::Element"), deeper);
}
@JRubyMethod
public IRubyObject previous_element(ThreadContext context) {
Node node = this.getNode().getPreviousSibling();
Ruby ruby = context.getRuntime();
if (node == null) return ruby.getNil();
if (node instanceof Element) {
return new XmlElement(ruby, (RubyClass)ruby.getClassFromPath("Nokogiri::XML::Element"), node);
}
Node shallower = node.getPreviousSibling();
if (shallower == null) return ruby.getNil();
return new XmlElement(ruby, (RubyClass)ruby.getClassFromPath("Nokogiri::XML::Element"), shallower);
}
}
|
diff --git a/src/test/java/net/codjo/tools/github/GithubCommandToolTest.java b/src/test/java/net/codjo/tools/github/GithubCommandToolTest.java
index 7df839e..13409ea 100644
--- a/src/test/java/net/codjo/tools/github/GithubCommandToolTest.java
+++ b/src/test/java/net/codjo/tools/github/GithubCommandToolTest.java
@@ -1,279 +1,279 @@
package net.codjo.tools.github;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.io.PrintStream;
import net.codjo.test.common.LogString;
import net.codjo.util.file.FileUtil;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static net.codjo.test.common.matcher.JUnitMatchers.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
public class GithubCommandToolTest {
private static final String endOfLine = System.getProperty("line.separator");
private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
private final ByteArrayOutputStream errContent = new ByteArrayOutputStream();
private GithubCommandTool githubCommandTool;
private GithubUtilService mockGithubService;
private LogString logString = new LogString();
private String proxyMessage;
@Before
public void setUpStreams() {
githubCommandTool = new GithubCommandTool();
logString.clear();
mockGithubService = new GithubUtilMockService(logString);
//TODO Testing System.out could be yeald to codjo-test ?
System.setOut(new PrintStream(outContent));
System.setErr(new PrintStream(errContent));
GitConfigUtil gitConfigUtil = GithubCommandTool.tryToLoadProxyConfig();
if (gitConfigUtil == null || gitConfigUtil.getProxyHost() != null) {
proxyMessage = "";
}
else {
proxyMessage = GithubCommandTool.PROXY_CONFIG_MESSAGE;
}
}
@After
public void cleanUpStreams() {
System.setOut(null);
System.setErr(null);
}
@Test
public void test_badMethodPrintsHelp() {
String[] args = new String[]{"badMethod", "githubUser", "githubPassword"};
githubCommandTool.localMain(mockGithubService, args);
assertThat(outContent.toString(), is(helpInConsole(true)));
assertNoError();
}
@Test
public void test_listDefaultRepositories() {
String[] args = new String[]{"list", "githubUser", "githubPassword"};
githubCommandTool.localMain(mockGithubService, args);
assertThat(outContent.toString(), is(repositoryListInConsole("githubUser")));
assertNoError();
}
@Test
public void test_listRepositoriesFromOtherUser() {
String[] args = new String[]{"list", "githubUser", "githubPassword", "codjo-sandbox"};
githubCommandTool.localMain(mockGithubService, args);
assertThat(outContent.toString(), is(repositoryListInConsole("githubUser")));
assertNoError();
}
@Test
public void test_forkRepository() {
String[] args = new String[]{"fork", "githubUser", "githubPassword", "codjo-github-tools"};
githubCommandTool.localMain(mockGithubService, args);
logString.assertContent(
"initGithubClient(githubUser, githubPassword), forkRepo(githubUser, githubPassword, codjo-github-tools)");
assertThat(outContent.toString(), is(forkRepositoryInConsole()));
assertNoError();
}
@Test
public void test_deleteRepository() {
String[] args = new String[]{"delete", "githubUser", "githubPassword", "codjo-github-tools"};
String data = "Yes" + endOfLine;
InputStream stdin = System.in;
try {
System.setIn(new ByteArrayInputStream(data.getBytes()));
githubCommandTool.localMain(mockGithubService, args);
logString.assertContent(
"initGithubClient(githubUser, githubPassword), deleteRepo(githubUser, githubPassword, codjo-github-tools)");
assertThat(outContent.toString(), is(deleteRepositoryInConsole("githubUser")));
assertNoError();
}
finally {
System.setIn(stdin);
}
}
@Test
public void test_deleteRepositoryCanceledByUser() {
String[] args = new String[]{"delete", "githubUser", "githubPassword", "codjo-github-tools"};
String data = "No" + endOfLine;
InputStream stdin = System.in;
try {
System.setIn(new ByteArrayInputStream(data.getBytes()));
githubCommandTool.localMain(mockGithubService, args);
logString.assertContent(
"initGithubClient(githubUser, githubPassword)");
assertThat(outContent.toString(), is(deleteRepositoryCanceledByUserInConsole()));
assertNoError();
}
finally {
System.setIn(stdin);
}
}
@Test
public void test_deleteWithCodjoAccount() {
String[] args = new String[]{"delete", "codjo", "githubPassword", "codjo-github-tools"};
String data = "Yes" + endOfLine;
InputStream stdin = System.in;
try {
System.setIn(new ByteArrayInputStream(data.getBytes()));
githubCommandTool.localMain(mockGithubService, args);
logString.assertContent(
"initGithubClient(codjo, githubPassword)");
assertThat(outContent.toString(), is(deleteRepositoryWithCodjoAccountInConsole()));
assertNoError();
}
finally {
System.setIn(stdin);
}
}
@Test
public void test_postIssue() throws Exception {
final String issueTitle = "myFirstIssue";
File issueContentFile = new File(getClass().getResource("/" + issueTitle).toURI());
String[] args = new String[]{"postIssue", "codjo", "password", "monRepo", issueTitle, "closed",
issueContentFile.getCanonicalPath(), "label_1", "label_2"};
InputStream stdin = System.in;
try {
githubCommandTool.localMain(mockGithubService, args);
logString.assertContent(
"initGithubClient(codjo, password), "
- + "postIssue(codjo, password, monRepo, myFirstIssue, " + issueContentFile.getPath() + ", closed), "
+ + "postIssue(codjo, password, monRepo, myFirstIssue, " + issueContentFile.getCanonicalPath() + ", closed), "
+ "addLabels(codjo, password, monRepo, myFirstIssue, [label_1, label_2])");
assertThat(outContent.toString(),
is(postIssueWithCodjoAccountInConsole(issueTitle, FileUtil.loadContent(issueContentFile))));
assertNoError();
}
finally {
System.setIn(stdin);
}
}
@Test
public void test_noParameterPrintsHelp
() {
String[] args = new String[]{};
githubCommandTool.localMain(mockGithubService, args);
assertEquals(helpInConsole(false), outContent.toString());
assertNoError();
}
@Test
public void test_listOpenedPullRequest() {
String[] args = new String[]{"events", "codjo", "githubPassword"};
githubCommandTool.localMain(mockGithubService, args);
logString.assertContent("initGithubClient(codjo, githubPassword)");
assertThat(outContent.toString(), equalTo(listEventsSinceLastStabilisationInConsole()));
assertNoError();
}
private String helpInConsole(boolean wihtQuotas) {
String result = ConsoleManager.OCTOPUS + endOfLine
+ proxyMessage +
" Did you mean :" + endOfLine +
" - gh list [ACCOUNT_NAME] : list all repositories from ACCOUNT_NAME" + endOfLine +
" - gh fork REPO_NAME : fork a repository from codjo" + endOfLine +
" - gh delete REPO_NAME : delete a repository if exists" + endOfLine +
" - gh postIssue REPO_NAME ISSUE_TITLE STATE ISSUE_CONTENT_FILE_PATH : add a new issue in repository"
+ endOfLine +
" - gh events [ACCOUNT_NAME] [ACCOUNT_PASSWORD] : list all events since last stabilisation (last pull request with 'For Release' title"
+ endOfLine;
if (wihtQuotas) {
result += printApiQuota();
}
return result;
}
private String repositoryListInConsole(String githubUser) {
return ConsoleManager.OCTOPUS + endOfLine + "\n"
+ "Here are the repositories from " + githubUser + endOfLine
+ "\tLast push\t\t\t\tName" + endOfLine
+ "\t19/07/2012 00:00\t\tcodjo-repoOne" + endOfLine
+ "\t05/07/2012 00:00\t\tcodjo-repoTwo" + endOfLine
+ printApiQuota();
}
private String forkRepositoryInConsole() {
return ConsoleManager.OCTOPUS + "" + endOfLine
+ "\tRepository codjo-github-tools has been forked from codjo." + endOfLine
+ printApiQuota();
}
private String deleteRepositoryInConsole(String githubUser) {
return ConsoleManager.OCTOPUS + "" + endOfLine
+ "Do you really want to delete the repository codjo-github-tools on githubUser account ? (y = yes / n = no/) : \n"
+ "\tRepository codjo-github-tools has been removed from " + githubUser + " account" + endOfLine
+ printApiQuota();
}
private String deleteRepositoryCanceledByUserInConsole() {
return ConsoleManager.OCTOPUS + "" + endOfLine
+ "Do you really want to delete the repository codjo-github-tools on githubUser account ? (y = yes / n = no/) : "
+ printApiQuota();
}
private String deleteRepositoryWithCodjoAccountInConsole() {
return ConsoleManager.OCTOPUS + "" + endOfLine
+ "\tRepositoy deletion with codjo account is not allowed." + endOfLine
+ "\t--> Please, use web interface instead." + endOfLine
+ printApiQuota();
}
private String postIssueWithCodjoAccountInConsole(String title, String content) {
return ConsoleManager.OCTOPUS + "" + endOfLine
+ "\tIssue " + title + " has been created with codjo account" + endOfLine
+ "\twith the following content:" + endOfLine
+ content + endOfLine
+ printApiQuota();
}
private String listEventsSinceLastStabilisationInConsole() {
return ConsoleManager.OCTOPUS + "" + endOfLine
+ "\tHere are the last events on codjo"
+ endOfLine
+ "\tUser\t\t\t\t\tName\t\t\t\tUrl" + endOfLine
+ "\tcodjo-sandbox\t\tfirst pullRequest\t\thttp://urlr/pullRequest/1" + endOfLine
+ "\tgonnot\t\tSecond pullRequest\t\thttp://urlr/pullRequest/2/other " + endOfLine
+ printApiQuota();
}
private String printApiQuota() {
return ConsoleManager.printApiQuota(5) + endOfLine;
}
private void assertNoError() {
assertEquals("", errContent.toString());
}
}
| true | true | public void test_postIssue() throws Exception {
final String issueTitle = "myFirstIssue";
File issueContentFile = new File(getClass().getResource("/" + issueTitle).toURI());
String[] args = new String[]{"postIssue", "codjo", "password", "monRepo", issueTitle, "closed",
issueContentFile.getCanonicalPath(), "label_1", "label_2"};
InputStream stdin = System.in;
try {
githubCommandTool.localMain(mockGithubService, args);
logString.assertContent(
"initGithubClient(codjo, password), "
+ "postIssue(codjo, password, monRepo, myFirstIssue, " + issueContentFile.getPath() + ", closed), "
+ "addLabels(codjo, password, monRepo, myFirstIssue, [label_1, label_2])");
assertThat(outContent.toString(),
is(postIssueWithCodjoAccountInConsole(issueTitle, FileUtil.loadContent(issueContentFile))));
assertNoError();
}
finally {
System.setIn(stdin);
}
}
| public void test_postIssue() throws Exception {
final String issueTitle = "myFirstIssue";
File issueContentFile = new File(getClass().getResource("/" + issueTitle).toURI());
String[] args = new String[]{"postIssue", "codjo", "password", "monRepo", issueTitle, "closed",
issueContentFile.getCanonicalPath(), "label_1", "label_2"};
InputStream stdin = System.in;
try {
githubCommandTool.localMain(mockGithubService, args);
logString.assertContent(
"initGithubClient(codjo, password), "
+ "postIssue(codjo, password, monRepo, myFirstIssue, " + issueContentFile.getCanonicalPath() + ", closed), "
+ "addLabels(codjo, password, monRepo, myFirstIssue, [label_1, label_2])");
assertThat(outContent.toString(),
is(postIssueWithCodjoAccountInConsole(issueTitle, FileUtil.loadContent(issueContentFile))));
assertNoError();
}
finally {
System.setIn(stdin);
}
}
|
diff --git a/HelloWorld/src/com/Rally/demo/Start.java b/HelloWorld/src/com/Rally/demo/Start.java
index 038f459..3a2a14e 100644
--- a/HelloWorld/src/com/Rally/demo/Start.java
+++ b/HelloWorld/src/com/Rally/demo/Start.java
@@ -1,14 +1,14 @@
package com.Rally.demo;
public class Start {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
// This is java
- System.out.println("Hello...");
+ System.out.println("Hello.");
}
}
| true | true | public static void main(String[] args) {
// TODO Auto-generated method stub
// This is java
System.out.println("Hello...");
}
| public static void main(String[] args) {
// TODO Auto-generated method stub
// This is java
System.out.println("Hello.");
}
|
diff --git a/reactor-spring/src/main/java/reactor/spring/context/ConsumerBeanPostProcessor.java b/reactor-spring/src/main/java/reactor/spring/context/ConsumerBeanPostProcessor.java
index 91ca16ad..25a7b1e0 100644
--- a/reactor-spring/src/main/java/reactor/spring/context/ConsumerBeanPostProcessor.java
+++ b/reactor-spring/src/main/java/reactor/spring/context/ConsumerBeanPostProcessor.java
@@ -1,264 +1,264 @@
/*
* Copyright (c) 2011-2013 GoPivotal, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package reactor.spring.context;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.expression.BeanFactoryResolver;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.expression.AccessException;
import org.springframework.expression.BeanResolver;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.EvaluationException;
import org.springframework.expression.Expression;
import org.springframework.expression.MethodExecutor;
import org.springframework.expression.MethodResolver;
import org.springframework.expression.TypedValue;
import org.springframework.expression.common.TemplateAwareExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.util.Assert;
import org.springframework.util.ReflectionUtils;
import reactor.event.Event;
import reactor.event.selector.Selector;
import reactor.event.selector.Selectors;
import reactor.function.Consumer;
import reactor.function.Observable;
import reactor.spring.context.annotation.On;
import reactor.util.StringUtils;
/**
* @author Jon Brisbin
*/
public class ConsumerBeanPostProcessor implements BeanPostProcessor,
BeanFactoryAware,
Ordered {
private static final Logger LOG = LoggerFactory.getLogger(ConsumerBeanPostProcessor.class);
private static final List<MethodResolver> METHOD_RESOLVERS = Arrays.<MethodResolver>asList(new ReactorsMethodResolver());
private BeanResolver beanResolver;
private TemplateAwareExpressionParser expressionParser = new SpelExpressionParser();
private final ConversionService conversionService;
@Autowired(required = false)
public ConsumerBeanPostProcessor(ConversionService conversionService) {
this.conversionService = conversionService;
}
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
beanResolver = new BeanFactoryResolver(beanFactory);
}
@Override public int getOrder() {
return Ordered.LOWEST_PRECEDENCE;
}
@Override
public Object postProcessBeforeInitialization(final Object bean,
String beanName) throws BeansException {
ReflectionUtils.doWithMethods(
bean.getClass(),
new ReflectionUtils.MethodCallback() {
@Override
public void doWith(final Method method) throws IllegalArgumentException,
IllegalAccessException {
StandardEvaluationContext evalCtx = new StandardEvaluationContext();
evalCtx.setRootObject(bean);
evalCtx.setBeanResolver(beanResolver);
evalCtx.setMethodResolvers(METHOD_RESOLVERS);
On onAnno = AnnotationUtils.findAnnotation(method, On.class);
Observable reactor = (Observable)expressionParser.parseExpression(onAnno.reactor()).getValue(evalCtx);
Assert.notNull(reactor, "Reactor cannot be null");
Selector selector = null;
if(StringUtils.hasText(onAnno.value())) {
try {
Expression selectorExpr = expressionParser.parseExpression(onAnno.value());
Object selObj = selectorExpr.getValue(evalCtx);
switch(onAnno.type()) {
case OBJECT:
selector = Selectors.object(selObj);
break;
case REGEX:
selector = Selectors.regex(selObj.toString());
break;
case URI:
selector = Selectors.uri(selObj.toString());
break;
case TYPE:
if(selObj instanceof Class) {
selector = Selectors.type((Class<?>)selObj);
} else {
try {
selector = Selectors.type(Class.forName(selObj.toString()));
} catch(ClassNotFoundException e) {
throw new IllegalArgumentException(e.getMessage(), e);
}
}
break;
}
} catch(EvaluationException e) {
- if(LOG.isWarnEnabled()) {
- LOG.warn("Creating ObjectSelector for '" + onAnno.value() + "' due to " + e.getMessage(), e);
+ if(LOG.isTraceEnabled()) {
+ LOG.trace("Creating ObjectSelector for '" + onAnno.value() + "' due to " + e.getMessage(), e);
}
selector = Selectors.object(onAnno.value());
}
}
Consumer<Event<Object>> handler = new Consumer<Event<Object>>() {
Class<?>[] argTypes = method.getParameterTypes();
@Override
public void accept(Event<Object> ev) {
if(argTypes.length == 0) {
if(LOG.isDebugEnabled()) {
LOG.debug("Invoking method[" + method + "] on " + bean + " using " + ev);
}
ReflectionUtils.invokeMethod(method, bean);
return;
}
if(argTypes.length > 1) {
// TODO: handle more than one parameter
throw new IllegalStateException("Multiple parameters not yet supported.");
}
if(null == ev.getData() || argTypes[0].isAssignableFrom(ev.getData().getClass())) {
if(LOG.isDebugEnabled()) {
LOG.debug("Invoking method[" + method + "] on " + bean + " using " + ev.getData());
}
ReflectionUtils.invokeMethod(method, bean, ev.getData());
return;
}
if(!argTypes[0].isAssignableFrom(ev.getClass())
&& conversionService.canConvert(ev.getClass(), argTypes[0])) {
ReflectionUtils.invokeMethod(method, bean, conversionService.convert(ev, argTypes[0]));
}
if(conversionService.canConvert(ev.getData().getClass(), argTypes[0])) {
Object convertedObj = conversionService.convert(ev.getData(), argTypes[0]);
if(LOG.isDebugEnabled()) {
LOG.debug("Invoking method[" + method + "] on " + bean + " using " + convertedObj);
}
ReflectionUtils.invokeMethod(method, bean, convertedObj);
return;
}
throw new IllegalArgumentException("Cannot invoke method " + method + " passing parameter " + ev.getData());
}
};
if(LOG.isDebugEnabled()) {
LOG.debug("Attaching Selector[" + selector + "] to Reactor[" + reactor + "] using Consumer[" + handler + "]");
}
if(null == selector) {
reactor.on(handler);
} else {
reactor.on(selector, handler);
}
}
},
new ReflectionUtils.MethodFilter() {
@Override public boolean matches(Method method) {
return null != AnnotationUtils.findAnnotation(method, On.class);
}
}
);
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean,
String beanName)
throws BeansException {
return bean;
}
private static class ReactorsMethodResolver implements MethodResolver {
@Override
public MethodExecutor resolve(EvaluationContext context,
Object targetObject,
String name,
List<TypeDescriptor> argumentTypes) throws AccessException {
if("$".equals(name)) {
return new MethodExecutor() {
@Override
public TypedValue execute(EvaluationContext context,
Object target,
Object... arguments) throws AccessException {
if(arguments.length != 1
|| null == arguments[0]
|| !Serializable.class.isAssignableFrom(arguments[0].getClass())) {
return null;
}
Selector sel = Selectors.$(arguments[0]);
return new TypedValue(sel, TypeDescriptor.valueOf(sel.getClass()));
}
};
} else if("R".equals(name)) {
return new MethodExecutor() {
@Override
public TypedValue execute(EvaluationContext context,
Object target,
Object... arguments) throws AccessException {
if(arguments.length != 1 || null == arguments[0]) {
return null;
}
Selector sel = Selectors.R(arguments[0].toString());
return new TypedValue(sel, TypeDescriptor.valueOf(sel.getClass()));
}
};
} else if("T".equals(name)) {
return new MethodExecutor() {
@Override
public TypedValue execute(EvaluationContext context,
Object target,
Object... arguments) throws AccessException {
if(arguments.length != 1
|| null == arguments[0]
|| !Class.class.isAssignableFrom(arguments[0].getClass())) {
return null;
}
Selector sel = Selectors.T((Class<?>)arguments[0]);
return new TypedValue(sel, TypeDescriptor.valueOf(sel.getClass()));
}
};
}
return null;
}
}
}
| true | true | public Object postProcessBeforeInitialization(final Object bean,
String beanName) throws BeansException {
ReflectionUtils.doWithMethods(
bean.getClass(),
new ReflectionUtils.MethodCallback() {
@Override
public void doWith(final Method method) throws IllegalArgumentException,
IllegalAccessException {
StandardEvaluationContext evalCtx = new StandardEvaluationContext();
evalCtx.setRootObject(bean);
evalCtx.setBeanResolver(beanResolver);
evalCtx.setMethodResolvers(METHOD_RESOLVERS);
On onAnno = AnnotationUtils.findAnnotation(method, On.class);
Observable reactor = (Observable)expressionParser.parseExpression(onAnno.reactor()).getValue(evalCtx);
Assert.notNull(reactor, "Reactor cannot be null");
Selector selector = null;
if(StringUtils.hasText(onAnno.value())) {
try {
Expression selectorExpr = expressionParser.parseExpression(onAnno.value());
Object selObj = selectorExpr.getValue(evalCtx);
switch(onAnno.type()) {
case OBJECT:
selector = Selectors.object(selObj);
break;
case REGEX:
selector = Selectors.regex(selObj.toString());
break;
case URI:
selector = Selectors.uri(selObj.toString());
break;
case TYPE:
if(selObj instanceof Class) {
selector = Selectors.type((Class<?>)selObj);
} else {
try {
selector = Selectors.type(Class.forName(selObj.toString()));
} catch(ClassNotFoundException e) {
throw new IllegalArgumentException(e.getMessage(), e);
}
}
break;
}
} catch(EvaluationException e) {
if(LOG.isWarnEnabled()) {
LOG.warn("Creating ObjectSelector for '" + onAnno.value() + "' due to " + e.getMessage(), e);
}
selector = Selectors.object(onAnno.value());
}
}
Consumer<Event<Object>> handler = new Consumer<Event<Object>>() {
Class<?>[] argTypes = method.getParameterTypes();
@Override
public void accept(Event<Object> ev) {
if(argTypes.length == 0) {
if(LOG.isDebugEnabled()) {
LOG.debug("Invoking method[" + method + "] on " + bean + " using " + ev);
}
ReflectionUtils.invokeMethod(method, bean);
return;
}
if(argTypes.length > 1) {
// TODO: handle more than one parameter
throw new IllegalStateException("Multiple parameters not yet supported.");
}
if(null == ev.getData() || argTypes[0].isAssignableFrom(ev.getData().getClass())) {
if(LOG.isDebugEnabled()) {
LOG.debug("Invoking method[" + method + "] on " + bean + " using " + ev.getData());
}
ReflectionUtils.invokeMethod(method, bean, ev.getData());
return;
}
if(!argTypes[0].isAssignableFrom(ev.getClass())
&& conversionService.canConvert(ev.getClass(), argTypes[0])) {
ReflectionUtils.invokeMethod(method, bean, conversionService.convert(ev, argTypes[0]));
}
if(conversionService.canConvert(ev.getData().getClass(), argTypes[0])) {
Object convertedObj = conversionService.convert(ev.getData(), argTypes[0]);
if(LOG.isDebugEnabled()) {
LOG.debug("Invoking method[" + method + "] on " + bean + " using " + convertedObj);
}
ReflectionUtils.invokeMethod(method, bean, convertedObj);
return;
}
throw new IllegalArgumentException("Cannot invoke method " + method + " passing parameter " + ev.getData());
}
};
if(LOG.isDebugEnabled()) {
LOG.debug("Attaching Selector[" + selector + "] to Reactor[" + reactor + "] using Consumer[" + handler + "]");
}
if(null == selector) {
reactor.on(handler);
} else {
reactor.on(selector, handler);
}
}
},
new ReflectionUtils.MethodFilter() {
@Override public boolean matches(Method method) {
return null != AnnotationUtils.findAnnotation(method, On.class);
}
}
);
return bean;
}
| public Object postProcessBeforeInitialization(final Object bean,
String beanName) throws BeansException {
ReflectionUtils.doWithMethods(
bean.getClass(),
new ReflectionUtils.MethodCallback() {
@Override
public void doWith(final Method method) throws IllegalArgumentException,
IllegalAccessException {
StandardEvaluationContext evalCtx = new StandardEvaluationContext();
evalCtx.setRootObject(bean);
evalCtx.setBeanResolver(beanResolver);
evalCtx.setMethodResolvers(METHOD_RESOLVERS);
On onAnno = AnnotationUtils.findAnnotation(method, On.class);
Observable reactor = (Observable)expressionParser.parseExpression(onAnno.reactor()).getValue(evalCtx);
Assert.notNull(reactor, "Reactor cannot be null");
Selector selector = null;
if(StringUtils.hasText(onAnno.value())) {
try {
Expression selectorExpr = expressionParser.parseExpression(onAnno.value());
Object selObj = selectorExpr.getValue(evalCtx);
switch(onAnno.type()) {
case OBJECT:
selector = Selectors.object(selObj);
break;
case REGEX:
selector = Selectors.regex(selObj.toString());
break;
case URI:
selector = Selectors.uri(selObj.toString());
break;
case TYPE:
if(selObj instanceof Class) {
selector = Selectors.type((Class<?>)selObj);
} else {
try {
selector = Selectors.type(Class.forName(selObj.toString()));
} catch(ClassNotFoundException e) {
throw new IllegalArgumentException(e.getMessage(), e);
}
}
break;
}
} catch(EvaluationException e) {
if(LOG.isTraceEnabled()) {
LOG.trace("Creating ObjectSelector for '" + onAnno.value() + "' due to " + e.getMessage(), e);
}
selector = Selectors.object(onAnno.value());
}
}
Consumer<Event<Object>> handler = new Consumer<Event<Object>>() {
Class<?>[] argTypes = method.getParameterTypes();
@Override
public void accept(Event<Object> ev) {
if(argTypes.length == 0) {
if(LOG.isDebugEnabled()) {
LOG.debug("Invoking method[" + method + "] on " + bean + " using " + ev);
}
ReflectionUtils.invokeMethod(method, bean);
return;
}
if(argTypes.length > 1) {
// TODO: handle more than one parameter
throw new IllegalStateException("Multiple parameters not yet supported.");
}
if(null == ev.getData() || argTypes[0].isAssignableFrom(ev.getData().getClass())) {
if(LOG.isDebugEnabled()) {
LOG.debug("Invoking method[" + method + "] on " + bean + " using " + ev.getData());
}
ReflectionUtils.invokeMethod(method, bean, ev.getData());
return;
}
if(!argTypes[0].isAssignableFrom(ev.getClass())
&& conversionService.canConvert(ev.getClass(), argTypes[0])) {
ReflectionUtils.invokeMethod(method, bean, conversionService.convert(ev, argTypes[0]));
}
if(conversionService.canConvert(ev.getData().getClass(), argTypes[0])) {
Object convertedObj = conversionService.convert(ev.getData(), argTypes[0]);
if(LOG.isDebugEnabled()) {
LOG.debug("Invoking method[" + method + "] on " + bean + " using " + convertedObj);
}
ReflectionUtils.invokeMethod(method, bean, convertedObj);
return;
}
throw new IllegalArgumentException("Cannot invoke method " + method + " passing parameter " + ev.getData());
}
};
if(LOG.isDebugEnabled()) {
LOG.debug("Attaching Selector[" + selector + "] to Reactor[" + reactor + "] using Consumer[" + handler + "]");
}
if(null == selector) {
reactor.on(handler);
} else {
reactor.on(selector, handler);
}
}
},
new ReflectionUtils.MethodFilter() {
@Override public boolean matches(Method method) {
return null != AnnotationUtils.findAnnotation(method, On.class);
}
}
);
return bean;
}
|
diff --git a/src/main/java/net/krinsoft/privileges/commands/ListCommand.java b/src/main/java/net/krinsoft/privileges/commands/ListCommand.java
index 536b8bf..c60bae0 100644
--- a/src/main/java/net/krinsoft/privileges/commands/ListCommand.java
+++ b/src/main/java/net/krinsoft/privileges/commands/ListCommand.java
@@ -1,102 +1,102 @@
package net.krinsoft.privileges.commands;
import net.krinsoft.privileges.FancyPage;
import net.krinsoft.privileges.Privileges;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.permissions.PermissionAttachmentInfo;
import org.bukkit.permissions.PermissionDefault;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
*
* @author krinsdeath
*/
public class ListCommand extends PrivilegesCommand {
public ListCommand(Privileges plugin) {
super(plugin);
setName("Privileges: List");
setCommandUsage("/privileges list ([player] [page])");
setArgRange(0, 2);
addKey("privileges list");
addKey("priv list");
addKey("plist");
setPermission("privileges.list", "Lists the specified user's permissions nodes.", PermissionDefault.TRUE);
}
@Override
public void runCommand(CommandSender sender, List<String> args) {
CommandSender target = sender;
String name = "Console";
int pageNum = 0;
List<String> list = new ArrayList<String>();
if (args.size() == 1) {
try {
pageNum = Integer.parseInt(args.get(0));
} catch (NumberFormatException e) {
pageNum = 0;
CommandSender test = plugin.getServer().getPlayer(args.get(0));
if (test != null) {
target = test;
name = test.getName();
} else {
sender.sendMessage("No player named '" + args.get(0) + "' is online.");
return;
}
}
} else if (args.size() == 2) {
try {
- pageNum = Integer.parseInt(args.get(1));
CommandSender test = plugin.getServer().getPlayer(args.get(0));
if (test != null) {
target = test;
name = test.getName();
} else {
sender.sendMessage("No player named '" + args.get(0) + "' is online.");
return;
}
+ pageNum = Integer.parseInt(args.get(1));
} catch (NumberFormatException e) {
pageNum = 0;
}
}
if (!target.equals(sender) && !sender.hasPermission("privileges.list.other")) {
sender.sendMessage(ChatColor.RED + "You do not have permission to view other peoples' nodes.");
return;
}
List<PermissionAttachmentInfo> attInfo = new ArrayList<PermissionAttachmentInfo>(target.getEffectivePermissions());
Collections.sort(attInfo, new Comparator<PermissionAttachmentInfo>() {
public int compare(PermissionAttachmentInfo a, PermissionAttachmentInfo b) {
return a.getPermission().compareTo(b.getPermission());
}
}); // thanks SpaceManiac!
for (PermissionAttachmentInfo att : attInfo) {
String node = att.getPermission();
StringBuilder msg = new StringBuilder();
msg.append("&B").append(node).append("&A - &B").append(att.getValue()).append("&A ");
msg.append("&A(").append(att.getAttachment() != null ? "set: &6" + att.getAttachment().getPlugin().getDescription().getName() + "&A" : "&3default&A").append(")");
list.add(ChatColor.translateAlternateColorCodes('&', msg.toString()));
}
FancyPage page = new FancyPage(list);
String header;
if (sender instanceof ConsoleCommandSender) {
header = ChatColor.GREEN + "=== " + ChatColor.WHITE + "Permissions list for " + ChatColor.AQUA + name + ChatColor.GREEN + " ===";
sender.sendMessage(ChatColor.translateAlternateColorCodes('&', header));
for (String line : list) {
sender.sendMessage(ChatColor.stripColor(line));
}
} else {
header = ChatColor.GREEN + "=== " + ChatColor.WHITE + " [Page " + pageNum + "/" + page.getPages() + "] " + ChatColor.GREEN + "===";
sender.sendMessage(ChatColor.translateAlternateColorCodes('&', header));
for (String line : page.getPage(pageNum)) {
sender.sendMessage(line);
}
}
}
}
| false | true | public void runCommand(CommandSender sender, List<String> args) {
CommandSender target = sender;
String name = "Console";
int pageNum = 0;
List<String> list = new ArrayList<String>();
if (args.size() == 1) {
try {
pageNum = Integer.parseInt(args.get(0));
} catch (NumberFormatException e) {
pageNum = 0;
CommandSender test = plugin.getServer().getPlayer(args.get(0));
if (test != null) {
target = test;
name = test.getName();
} else {
sender.sendMessage("No player named '" + args.get(0) + "' is online.");
return;
}
}
} else if (args.size() == 2) {
try {
pageNum = Integer.parseInt(args.get(1));
CommandSender test = plugin.getServer().getPlayer(args.get(0));
if (test != null) {
target = test;
name = test.getName();
} else {
sender.sendMessage("No player named '" + args.get(0) + "' is online.");
return;
}
} catch (NumberFormatException e) {
pageNum = 0;
}
}
if (!target.equals(sender) && !sender.hasPermission("privileges.list.other")) {
sender.sendMessage(ChatColor.RED + "You do not have permission to view other peoples' nodes.");
return;
}
List<PermissionAttachmentInfo> attInfo = new ArrayList<PermissionAttachmentInfo>(target.getEffectivePermissions());
Collections.sort(attInfo, new Comparator<PermissionAttachmentInfo>() {
public int compare(PermissionAttachmentInfo a, PermissionAttachmentInfo b) {
return a.getPermission().compareTo(b.getPermission());
}
}); // thanks SpaceManiac!
for (PermissionAttachmentInfo att : attInfo) {
String node = att.getPermission();
StringBuilder msg = new StringBuilder();
msg.append("&B").append(node).append("&A - &B").append(att.getValue()).append("&A ");
msg.append("&A(").append(att.getAttachment() != null ? "set: &6" + att.getAttachment().getPlugin().getDescription().getName() + "&A" : "&3default&A").append(")");
list.add(ChatColor.translateAlternateColorCodes('&', msg.toString()));
}
FancyPage page = new FancyPage(list);
String header;
if (sender instanceof ConsoleCommandSender) {
header = ChatColor.GREEN + "=== " + ChatColor.WHITE + "Permissions list for " + ChatColor.AQUA + name + ChatColor.GREEN + " ===";
sender.sendMessage(ChatColor.translateAlternateColorCodes('&', header));
for (String line : list) {
sender.sendMessage(ChatColor.stripColor(line));
}
} else {
header = ChatColor.GREEN + "=== " + ChatColor.WHITE + " [Page " + pageNum + "/" + page.getPages() + "] " + ChatColor.GREEN + "===";
sender.sendMessage(ChatColor.translateAlternateColorCodes('&', header));
for (String line : page.getPage(pageNum)) {
sender.sendMessage(line);
}
}
}
| public void runCommand(CommandSender sender, List<String> args) {
CommandSender target = sender;
String name = "Console";
int pageNum = 0;
List<String> list = new ArrayList<String>();
if (args.size() == 1) {
try {
pageNum = Integer.parseInt(args.get(0));
} catch (NumberFormatException e) {
pageNum = 0;
CommandSender test = plugin.getServer().getPlayer(args.get(0));
if (test != null) {
target = test;
name = test.getName();
} else {
sender.sendMessage("No player named '" + args.get(0) + "' is online.");
return;
}
}
} else if (args.size() == 2) {
try {
CommandSender test = plugin.getServer().getPlayer(args.get(0));
if (test != null) {
target = test;
name = test.getName();
} else {
sender.sendMessage("No player named '" + args.get(0) + "' is online.");
return;
}
pageNum = Integer.parseInt(args.get(1));
} catch (NumberFormatException e) {
pageNum = 0;
}
}
if (!target.equals(sender) && !sender.hasPermission("privileges.list.other")) {
sender.sendMessage(ChatColor.RED + "You do not have permission to view other peoples' nodes.");
return;
}
List<PermissionAttachmentInfo> attInfo = new ArrayList<PermissionAttachmentInfo>(target.getEffectivePermissions());
Collections.sort(attInfo, new Comparator<PermissionAttachmentInfo>() {
public int compare(PermissionAttachmentInfo a, PermissionAttachmentInfo b) {
return a.getPermission().compareTo(b.getPermission());
}
}); // thanks SpaceManiac!
for (PermissionAttachmentInfo att : attInfo) {
String node = att.getPermission();
StringBuilder msg = new StringBuilder();
msg.append("&B").append(node).append("&A - &B").append(att.getValue()).append("&A ");
msg.append("&A(").append(att.getAttachment() != null ? "set: &6" + att.getAttachment().getPlugin().getDescription().getName() + "&A" : "&3default&A").append(")");
list.add(ChatColor.translateAlternateColorCodes('&', msg.toString()));
}
FancyPage page = new FancyPage(list);
String header;
if (sender instanceof ConsoleCommandSender) {
header = ChatColor.GREEN + "=== " + ChatColor.WHITE + "Permissions list for " + ChatColor.AQUA + name + ChatColor.GREEN + " ===";
sender.sendMessage(ChatColor.translateAlternateColorCodes('&', header));
for (String line : list) {
sender.sendMessage(ChatColor.stripColor(line));
}
} else {
header = ChatColor.GREEN + "=== " + ChatColor.WHITE + " [Page " + pageNum + "/" + page.getPages() + "] " + ChatColor.GREEN + "===";
sender.sendMessage(ChatColor.translateAlternateColorCodes('&', header));
for (String line : page.getPage(pageNum)) {
sender.sendMessage(line);
}
}
}
|
diff --git a/src/main/edu/iastate/music/marching/attendance/servlets/FormsServlet.java b/src/main/edu/iastate/music/marching/attendance/servlets/FormsServlet.java
index 9a329fe2..6258bd55 100644
--- a/src/main/edu/iastate/music/marching/attendance/servlets/FormsServlet.java
+++ b/src/main/edu/iastate/music/marching/attendance/servlets/FormsServlet.java
@@ -1,762 +1,764 @@
package edu.iastate.music.marching.attendance.servlets;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.TimeZone;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import edu.iastate.music.marching.attendance.App;
import edu.iastate.music.marching.attendance.controllers.DataTrain;
import edu.iastate.music.marching.attendance.controllers.FormController;
import edu.iastate.music.marching.attendance.model.Absence;
import edu.iastate.music.marching.attendance.model.Form;
import edu.iastate.music.marching.attendance.model.User;
import edu.iastate.music.marching.attendance.util.PageBuilder;
import edu.iastate.music.marching.attendance.util.Util;
import edu.iastate.music.marching.attendance.util.ValidationUtil;
public class FormsServlet extends AbstractBaseServlet {
/**
*
*/
private static final long serialVersionUID = -4738485557840953301L;
private static final Logger log = Logger.getLogger(FormsServlet.class
.getName());
private enum Page {
forma, formb, formc, formd, index, view, remove, messages;
}
private static final String SERVLET_PATH = "form";
private static final String SUCCESS_FORMA = "Submitted new Form A";
private static final String SUCCESS_FORMB = "Submitted new Form B";
private static final String SUCCESS_FORMC = "Submitted new Form C";
private static final String SUCCESS_FORMD = "Submitted new Form D";
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
if (!isLoggedIn(req, resp)) {
resp.sendRedirect(AuthServlet.getLoginUrl(req));
return;
} else if (!isLoggedIn(req, resp, getServletUserTypes())) {
resp.sendRedirect(ErrorServlet.getLoginFailedUrl(req));
return;
}
Page page = parsePathInfo(req.getPathInfo(), Page.class);
if (page == null) {
show404(req, resp);
return;
}
switch (page) {
case forma:
postFormA(req, resp);
break;
case formb:
handleFormB(req, resp);
break;
case formc:
handleFormC(req, resp);
break;
case formd:
handleFormD(req, resp);
break;
case index:
showIndex(req, resp);
break;
case view:
viewForm(req, resp, new LinkedList<String>(), "");
break;
// case remove:
// removeForm(req, resp);
// break;
case messages:
break;
default:
ErrorServlet.showError(req, resp, 404);
}
}
private void viewForm(HttpServletRequest req, HttpServletResponse resp,
List<String> errors, String success_message)
throws ServletException, IOException {
DataTrain train = DataTrain.getAndStartTrain();
User currentUser = train.getAuthController().getCurrentUser(
req.getSession());
Form form = null;
try {
long id = Long.parseLong(req.getParameter("id"));
form = train.getFormsController().get(id);
PageBuilder page = new PageBuilder(Page.view, SERVLET_PATH);
if(form == null)
{
log.warning("Could not find form number " + id + ".");
errors.add("Could not find form number " + id + ".");
page.setAttribute("error_messages", errors);
} else {
page.setPageTitle("Form " + form.getType());
page.setAttribute("form", form);
page.setAttribute("day", form.getDayAsString());
page.setAttribute("isDirector", currentUser.getType().isDirector());
page.setAttribute("error_messages", errors);
page.setAttribute("success_message", success_message);
}
page.passOffToJsp(req, resp);
} catch (NumberFormatException nfe) {
log.warning("Could not parse view form id: " + req.getParameter("id"));
ErrorServlet.showError(req, resp, 500);
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
if (!isLoggedIn(req, resp)) {
resp.sendRedirect(AuthServlet.getLoginUrl());
return;
} else if (!isLoggedIn(req, resp, getServletUserTypes())) {
resp.sendRedirect(ErrorServlet.getLoginFailedUrl(req));
return;
}
Page page = parsePathInfo(req.getPathInfo(), Page.class);
if (page == null)
ErrorServlet.showError(req, resp, 404);
else
switch (page) {
case index:
showIndex(req, resp);
break;
case forma:
postFormA(req, resp);
break;
case formb:
handleFormB(req, resp);
break;
case formc:
handleFormC(req, resp);
break;
case formd:
handleFormD(req, resp);
break;
case messages:
break;
case view:
updateStatus(req, resp);
break;
default:
ErrorServlet.showError(req, resp, 404);
}
}
private void updateStatus(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
DataTrain train = DataTrain.getAndStartTrain();
FormController fc = train.getFormsController();
List<String> errors = new LinkedList<String>();
String success_message = "";
boolean validForm = true;
Form f = null;
Form.Status status = null;
long id = 0;
if (!ValidationUtil.isPost(req)) {
validForm = false;
}
if (validForm) {
try {
id = Long.parseLong(req.getParameter("id"));
f = fc.get(id);
String strStat = req.getParameter("status");
if (strStat.equalsIgnoreCase("Approved"))
status = Form.Status.Approved;
else if (strStat.equalsIgnoreCase("Pending"))
status = Form.Status.Pending;
else if (strStat.equalsIgnoreCase("Denied"))
status = Form.Status.Denied;
else {
validForm = false;
errors.add("Invalid form status.");
}
} catch (NumberFormatException e) {
errors.add("Unable to find form.");
validForm = false;
} catch (NullPointerException e) {
errors.add("Unable to find form.");
validForm = false;
}
}
if (validForm) {
// Send them back to their Form page
f.setStatus(status);
fc.update(f);
success_message = "Successfully updated form.";
}
viewForm(req, resp, errors, success_message);
}
private void postFormA(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String reason = null;
Date date = null;
DataTrain train = DataTrain.getAndStartTrain();
// Parse out all data from form and validate
boolean validForm = true;
List<String> errors = new LinkedList<String>();
if (!ValidationUtil.isPost(req)) {
// This is not a post request to create a new form, no need to
// validate
validForm = false;
} else {
// Extract all basic parameters
reason = req.getParameter("Reason");
try {
date = Util.parseDate(req.getParameter("StartMonth"),
req.getParameter("StartDay"),
req.getParameter("StartYear"), "0", "AM", "0", train
.getAppDataController().get().getTimeZone());
} catch (IllegalArgumentException e) {
validForm = false;
errors.add("Invalid Input: The input date is invalid.");
}
}
if (validForm) {
// Store our new form to the data store
User student = train.getAuthController().getCurrentUser(
req.getSession());
Form form = null;
try {
form = train.getFormsController().createFormA(student, date,
reason);
} catch (IllegalArgumentException e) {
validForm = false;
errors.add(e.getMessage());
}
if (form == null) {
validForm = false;
errors.add("Fix any errors above and try to resubmit. If you're still having issues, submit a bug report using the form at the bottom of the page.");
}
}
if (validForm) {
String url = getIndexURL() + "?success_message="
+ URLEncoder.encode(SUCCESS_FORMA, "UTF-8");
// url = resp.encodeRedirectURL(url);
resp.sendRedirect(url);
} else {
// Show form
PageBuilder page = new PageBuilder(Page.forma, SERVLET_PATH);
page.setPageTitle("Form A");
page.setAttribute("error_messages", errors);
page.setAttribute("cutoff", train.getAppDataController().get()
.getFormSubmissionCutoff());
page.setAttribute("Reason", reason);
setStartDate(date, page, train.getAppDataController().get()
.getTimeZone());
page.passOffToJsp(req, resp);
}
}
private void handleFormB(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String department = null;
String course = null;
String section = null;
String building = null;
Date startDate = null;
Date endDate = null;
Date fromTime = null;
Date toTime = null;
int day = -1;
int minutesToOrFrom = 0;
String comments = null;
Absence.Type absenceType = null;
DataTrain train = DataTrain.getAndStartTrain();
// Parse out all data from form and validate
boolean validForm = true;
List<String> errors = new LinkedList<String>();
if (!ValidationUtil.isPost(req)) {
// This is not a post request to create a new form, no need to
// validate
validForm = false;
} else {
// Extract all basic parameters
department = req.getParameter("Department");
course = req.getParameter("Course");
section = req.getParameter("Section");
building = req.getParameter("Building");
comments = req.getParameter("Comments");
String minutestmp = req.getParameter("MinutesToOrFrom");
try {
minutesToOrFrom = Integer.parseInt(minutestmp);
} catch (NumberFormatException nfe) {
errors.add("Minutes to or from must be a whole number.");
}
String stype = req.getParameter("Type");
if (stype != null && !stype.equals("")) {
if (stype.equals(Absence.Type.Absence.getValue())) {
absenceType = Absence.Type.Absence;
} else if (stype.equals(Absence.Type.Tardy.getValue())) {
absenceType = Absence.Type.Tardy;
} else if (stype.equals(Absence.Type.EarlyCheckOut.getValue())) {
absenceType = Absence.Type.EarlyCheckOut;
}
} else {
errors.add("Invalid type.");
}
// this is one-based! Starting on Sunday.
try {
day = Integer.parseInt(req.getParameter("DayOfWeek"));
} catch (NumberFormatException nfe) {
errors.add("Weekday was invalid.");
}
if (day < 1 || day > 7) {
errors.add("Value of " + day + " for day was not valid.");
}
try {
startDate = Util.parseDate(req.getParameter("StartMonth"),
req.getParameter("StartDay"),
req.getParameter("StartYear"), "0", "AM", "0", train
.getAppDataController().get().getTimeZone());
} catch (IllegalArgumentException e) {
validForm = false;
errors.add("The start date is invalid.");
}
try {
endDate = Util.parseDate(req.getParameter("EndMonth"),
req.getParameter("EndDay"),
req.getParameter("EndYear"), "0", "AM", "0", train
.getAppDataController().get().getTimeZone());
} catch (IllegalArgumentException e) {
validForm = false;
errors.add("The end date is invalid.");
}
try {
fromTime = Util.parseDate("1", "1", "1000",
req.getParameter("FromHour"),
req.getParameter("FromAMPM"),
req.getParameter("FromMinute"), train
.getAppDataController().get().getTimeZone());
} catch (IllegalArgumentException e) {
validForm = false;
errors.add("The start time is invalid.");
}
try {
toTime = Util.parseDate("1", "1", "1000",
req.getParameter("ToHour"), req.getParameter("ToAMPM"),
req.getParameter("ToMinute"), train
.getAppDataController().get().getTimeZone());
} catch (IllegalArgumentException e) {
validForm = false;
errors.add("The end time is invalid.");
}
}
if (validForm) {
// Store our new form to the datastore
User student = train.getAuthController().getCurrentUser(
req.getSession());
Form form = null;
try {
form = train.getFormsController().createFormB(student,
department, course, section, building, startDate,
endDate, day, fromTime, toTime, comments,
minutesToOrFrom, absenceType);
} catch (IllegalArgumentException e) {
validForm = false;
errors.add(e.getMessage());
}
if (form == null) {
validForm = false;
errors.add("Fix any errors above and try to resubmit. If you're still having issues, submit a bug report using the form at the bottom of the page.");
}
}
if (validForm) {
String url = getIndexURL() + "?success_message="
+ URLEncoder.encode(SUCCESS_FORMB, "UTF-8");
url = resp.encodeRedirectURL(url);
resp.sendRedirect(url);
} else {
// Show form
PageBuilder page = new PageBuilder(Page.formb, SERVLET_PATH);
page.setPageTitle("Form B");
page.setAttribute("daysOfWeek", App.getDaysOfTheWeek());
page.setAttribute("error_messages", errors);
page.setAttribute("Department", department);
page.setAttribute("Course", course);
page.setAttribute("Section", section);
page.setAttribute("Building", building);
setStartDate(startDate, page, train.getAppDataController().get()
.getTimeZone());
setEndDate(endDate, page, train.getAppDataController().get()
.getTimeZone());
page.setAttribute("Type", Form.Type.B);
page.setAttribute("Comments", comments);
page.setAttribute("MinutesToOrFrom", minutesToOrFrom);
page.setAttribute("Type", absenceType);
page.setAttribute("types", Absence.Type.values());
if (fromTime != null) {
- Calendar from = Calendar.getInstance();
+ Calendar from = Calendar.getInstance(train.getAppDataController().get()
+ .getTimeZone());
from.setTime(fromTime);
page.setAttribute("FromHour", from.get(Calendar.HOUR));
page.setAttribute("FromMinute", from.get(Calendar.MINUTE));
page.setAttribute("FromAMPM", from.get(Calendar.AM_PM) == 0 ? "AM" : "PM");
}
if (toTime != null) {
- Calendar to = Calendar.getInstance();
+ Calendar to = Calendar.getInstance(train.getAppDataController().get()
+ .getTimeZone());
to.setTime(toTime);
page.setAttribute("ToHour", to.get(Calendar.HOUR));
page.setAttribute("ToMinute", to.get(Calendar.MINUTE));
page.setAttribute("ToAMPM", to.get(Calendar.AM_PM) == 0 ? "AM" : "PM");
}
page.passOffToJsp(req, resp);
}
}
private void handleFormC(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
Date date = null;
String reason = null;
Absence.Type type = null;
DataTrain train = DataTrain.getAndStartTrain();
// Parse out all data from form and validate
boolean validForm = true;
List<String> errors = new LinkedList<String>();
if (!ValidationUtil.isPost(req)) {
// This is not a post request to create a new form, no need to
// validate
validForm = false;
} else {
// Extract all basic parameters
reason = req.getParameter("Reason");
String stype = req.getParameter("Type");
if (stype != null && !stype.equals("")) {
if (stype.equals(Absence.Type.Absence.getValue())) {
type = Absence.Type.Absence;
} else if (stype.equals(Absence.Type.Tardy.getValue())) {
type = Absence.Type.Tardy;
} else if (stype.equals(Absence.Type.EarlyCheckOut.getValue())) {
type = Absence.Type.EarlyCheckOut;
}
} else {
errors.add("Invalid type.");
}
try {
if (type == Absence.Type.Absence) {
date = Util.parseDate(req.getParameter("Month"),
req.getParameter("Day"), req.getParameter("Year"),
"0", "AM", "0", train.getAppDataController().get()
.getTimeZone());
} else {
date = Util
.parseDate(req.getParameter("Month"),
req.getParameter("Day"),
req.getParameter("Year"),
req.getParameter("Hour"),
req.getParameter("AMPM"),
req.getParameter("Minute"), train
.getAppDataController().get()
.getTimeZone());
}
} catch (IllegalArgumentException e) {
validForm = false;
errors.add("The date is invalid.");
}
}
if (validForm) {
// Store our new form to the data store
User student = train.getAuthController().getCurrentUser(
req.getSession());
Form form = null;
try {
form = train.getFormsController().createFormC(student, date,
type, reason);
} catch (IllegalArgumentException e) {
validForm = false;
errors.add(e.getMessage());
}
if (form == null) {
validForm = false;
errors.add("Fix any errors above and try to resubmit. If you're still having issues, submit a bug report using the form at the bottom of the page.");
}
}
if (validForm) {
String url = getIndexURL() + "?success_message="
+ URLEncoder.encode(SUCCESS_FORMC, "UTF-8");
url = resp.encodeRedirectURL(url);
resp.sendRedirect(url);
} else {
// Show form
PageBuilder page = new PageBuilder(Page.formc, SERVLET_PATH);
page.setPageTitle("Form C");
page.setAttribute("error_messages", errors);
page.setAttribute("types", Absence.Type.values());
setStartDate(date, page, train.getAppDataController().get()
.getTimeZone());
page.setAttribute("Reason", reason);
page.passOffToJsp(req, resp);
}
}
private void handleFormD(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String email = null;
int minutes = 0;
Date date = null;
String details = null;
DataTrain train = DataTrain.getAndStartTrain();
// Parse out all data from form and validate
boolean validForm = true;
List<String> errors = new LinkedList<String>();
if (!ValidationUtil.isPost(req)) {
// This is not a post request to create a new form, no need to
// validate
validForm = false;
} else {
// Extract all basic parameters
email = req.getParameter("Email");
details = req.getParameter("Details");
try {
minutes = Integer.parseInt(req.getParameter("AmountWorked"));
} catch (NumberFormatException e) {
validForm = false;
errors.add("Invalid amount of time worked: " + e.getMessage());
}
try {
date = Util.parseDate(req.getParameter("StartMonth"),
req.getParameter("StartDay"),
req.getParameter("StartYear"), "0", "AM", "0", train
.getAppDataController().get().getTimeZone());
} catch (IllegalArgumentException e) {
validForm = false;
errors.add("Invalid Input: The input date is invalid.");
}
}
User student = train.getAuthController().getCurrentUser(
req.getSession());
if (validForm) {
// Store our new form to the data store
Form form = null;
try {
// hash the id for use in the accepting and declining forms
form = train.getFormsController().createFormD(student, email,
date, minutes, details);
} catch (IllegalArgumentException e) {
validForm = false;
errors.add(e.getMessage());
}
if (form == null) {
validForm = false;
errors.add("Fix any errors above and try to resubmit. If you're still having issues, submit a bug report using the form at the bottom of the page.");
}
}
if (validForm) {
String url = getIndexURL() + "?success_message="
+ URLEncoder.encode(SUCCESS_FORMD, "UTF-8");
url = resp.encodeRedirectURL(url);
resp.sendRedirect(url);
} else {
// Show form
PageBuilder page = new PageBuilder(Page.formd, SERVLET_PATH);
page.setPageTitle("Form D");
page.setAttribute("error_messages", errors);
page.setAttribute("verifiers", train.getAppDataController().get()
.getTimeWorkedEmails());
page.setAttribute("Email", email);
page.setAttribute("AmountWorked", minutes);
setStartDate(date, page, train.getAppDataController().get()
.getTimeZone());
page.setAttribute("Details", details);
page.passOffToJsp(req, resp);
}
}
private void setEndDate(Date date, PageBuilder page, TimeZone timezone) {
if (date == null)
return;
Calendar c = Calendar.getInstance(timezone);
c.setTime(date);
page.setAttribute("EndYear", c.get(Calendar.YEAR));
page.setAttribute("EndMonth", c.get(Calendar.MONTH));
page.setAttribute("EndDay", c.get(Calendar.DATE));
}
private void setStartDate(Date date, PageBuilder page, TimeZone timezone) {
if (date == null)
return;
Calendar c = Calendar.getInstance(timezone);
c.setTime(date);
page.setAttribute("StartYear", c.get(Calendar.YEAR));
page.setAttribute("StartMonth", c.get(Calendar.MONTH));
page.setAttribute("StartDay", c.get(Calendar.DATE));
page.setAttribute("StartHour", c.get(Calendar.HOUR));
page.setAttribute("StartMinute", c.get(Calendar.MINUTE));
page.setAttribute("StartPeriod", c.get(Calendar.AM_PM));
}
private void showIndex(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
DataTrain train = DataTrain.getAndStartTrain();
FormController fc = train.getFormsController();
PageBuilder page = new PageBuilder(Page.index, SERVLET_PATH);
// Pass through any success message in the url parameters sent from a
// new form being created or deleted
page.setAttribute("success_message",
req.getParameter("success_message"));
User currentUser = train.getAuthController().getCurrentUser(
req.getSession());
String removeid = req.getParameter("removeid");
if (removeid != null && removeid != "") {
try {
long id = Long.parseLong(removeid);
if (currentUser.getType() == User.Type.Student
&& fc.get(id).getStatus() != Form.Status.Pending) {
page.setAttribute("error_messages",
"Students cannot delete any non-pending form.");
} else {
if (fc.removeForm(id)) {
page.setAttribute("success_message",
"Form successfully deleted");
} else {
page.setAttribute("error_messages",
"Form not deleted. If the form was already approved then you can't delete it.");
}
}
} catch (NullPointerException e) {
page.setAttribute("error_messages", "The form does not exist.");
}
}
// Handle students and director differently
List<Form> forms = null;
if (getServletUserType() == User.Type.Student)
forms = fc.get(currentUser);
else if (getServletUserType() == User.Type.Director)
forms = fc.getAll();
page.setAttribute("forms", forms);
page.passOffToJsp(req, resp);
}
/**
* This servlet can be used for multiple user types, this grabs the type of
* user this specific servlet instance is for
*
* @return
*/
private User.Type getServletUserType() {
String value = getInitParameter("userType");
return User.Type.valueOf(value);
}
/**
* This servlet can be used for multiple user types, this grabs the type of
* user this specific servlet instance can be accessed by
*
* @return
*/
private User.Type[] getServletUserTypes() {
User.Type userType = getServletUserType();
// Since a TA is also a student, we also allow them access to their
// student forms
if (userType == User.Type.Student)
return new User.Type[] { User.Type.Student, User.Type.TA };
else
return new User.Type[] { userType };
}
/**
* Have to use a method since this servlet can be mapped from different
* paths
*/
private String getIndexURL() {
return pageToUrl(Page.index, getInitParameter("path"));
}
}
| false | true | private void handleFormB(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String department = null;
String course = null;
String section = null;
String building = null;
Date startDate = null;
Date endDate = null;
Date fromTime = null;
Date toTime = null;
int day = -1;
int minutesToOrFrom = 0;
String comments = null;
Absence.Type absenceType = null;
DataTrain train = DataTrain.getAndStartTrain();
// Parse out all data from form and validate
boolean validForm = true;
List<String> errors = new LinkedList<String>();
if (!ValidationUtil.isPost(req)) {
// This is not a post request to create a new form, no need to
// validate
validForm = false;
} else {
// Extract all basic parameters
department = req.getParameter("Department");
course = req.getParameter("Course");
section = req.getParameter("Section");
building = req.getParameter("Building");
comments = req.getParameter("Comments");
String minutestmp = req.getParameter("MinutesToOrFrom");
try {
minutesToOrFrom = Integer.parseInt(minutestmp);
} catch (NumberFormatException nfe) {
errors.add("Minutes to or from must be a whole number.");
}
String stype = req.getParameter("Type");
if (stype != null && !stype.equals("")) {
if (stype.equals(Absence.Type.Absence.getValue())) {
absenceType = Absence.Type.Absence;
} else if (stype.equals(Absence.Type.Tardy.getValue())) {
absenceType = Absence.Type.Tardy;
} else if (stype.equals(Absence.Type.EarlyCheckOut.getValue())) {
absenceType = Absence.Type.EarlyCheckOut;
}
} else {
errors.add("Invalid type.");
}
// this is one-based! Starting on Sunday.
try {
day = Integer.parseInt(req.getParameter("DayOfWeek"));
} catch (NumberFormatException nfe) {
errors.add("Weekday was invalid.");
}
if (day < 1 || day > 7) {
errors.add("Value of " + day + " for day was not valid.");
}
try {
startDate = Util.parseDate(req.getParameter("StartMonth"),
req.getParameter("StartDay"),
req.getParameter("StartYear"), "0", "AM", "0", train
.getAppDataController().get().getTimeZone());
} catch (IllegalArgumentException e) {
validForm = false;
errors.add("The start date is invalid.");
}
try {
endDate = Util.parseDate(req.getParameter("EndMonth"),
req.getParameter("EndDay"),
req.getParameter("EndYear"), "0", "AM", "0", train
.getAppDataController().get().getTimeZone());
} catch (IllegalArgumentException e) {
validForm = false;
errors.add("The end date is invalid.");
}
try {
fromTime = Util.parseDate("1", "1", "1000",
req.getParameter("FromHour"),
req.getParameter("FromAMPM"),
req.getParameter("FromMinute"), train
.getAppDataController().get().getTimeZone());
} catch (IllegalArgumentException e) {
validForm = false;
errors.add("The start time is invalid.");
}
try {
toTime = Util.parseDate("1", "1", "1000",
req.getParameter("ToHour"), req.getParameter("ToAMPM"),
req.getParameter("ToMinute"), train
.getAppDataController().get().getTimeZone());
} catch (IllegalArgumentException e) {
validForm = false;
errors.add("The end time is invalid.");
}
}
if (validForm) {
// Store our new form to the datastore
User student = train.getAuthController().getCurrentUser(
req.getSession());
Form form = null;
try {
form = train.getFormsController().createFormB(student,
department, course, section, building, startDate,
endDate, day, fromTime, toTime, comments,
minutesToOrFrom, absenceType);
} catch (IllegalArgumentException e) {
validForm = false;
errors.add(e.getMessage());
}
if (form == null) {
validForm = false;
errors.add("Fix any errors above and try to resubmit. If you're still having issues, submit a bug report using the form at the bottom of the page.");
}
}
if (validForm) {
String url = getIndexURL() + "?success_message="
+ URLEncoder.encode(SUCCESS_FORMB, "UTF-8");
url = resp.encodeRedirectURL(url);
resp.sendRedirect(url);
} else {
// Show form
PageBuilder page = new PageBuilder(Page.formb, SERVLET_PATH);
page.setPageTitle("Form B");
page.setAttribute("daysOfWeek", App.getDaysOfTheWeek());
page.setAttribute("error_messages", errors);
page.setAttribute("Department", department);
page.setAttribute("Course", course);
page.setAttribute("Section", section);
page.setAttribute("Building", building);
setStartDate(startDate, page, train.getAppDataController().get()
.getTimeZone());
setEndDate(endDate, page, train.getAppDataController().get()
.getTimeZone());
page.setAttribute("Type", Form.Type.B);
page.setAttribute("Comments", comments);
page.setAttribute("MinutesToOrFrom", minutesToOrFrom);
page.setAttribute("Type", absenceType);
page.setAttribute("types", Absence.Type.values());
if (fromTime != null) {
Calendar from = Calendar.getInstance();
from.setTime(fromTime);
page.setAttribute("FromHour", from.get(Calendar.HOUR));
page.setAttribute("FromMinute", from.get(Calendar.MINUTE));
page.setAttribute("FromAMPM", from.get(Calendar.AM_PM) == 0 ? "AM" : "PM");
}
if (toTime != null) {
Calendar to = Calendar.getInstance();
to.setTime(toTime);
page.setAttribute("ToHour", to.get(Calendar.HOUR));
page.setAttribute("ToMinute", to.get(Calendar.MINUTE));
page.setAttribute("ToAMPM", to.get(Calendar.AM_PM) == 0 ? "AM" : "PM");
}
page.passOffToJsp(req, resp);
}
}
| private void handleFormB(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String department = null;
String course = null;
String section = null;
String building = null;
Date startDate = null;
Date endDate = null;
Date fromTime = null;
Date toTime = null;
int day = -1;
int minutesToOrFrom = 0;
String comments = null;
Absence.Type absenceType = null;
DataTrain train = DataTrain.getAndStartTrain();
// Parse out all data from form and validate
boolean validForm = true;
List<String> errors = new LinkedList<String>();
if (!ValidationUtil.isPost(req)) {
// This is not a post request to create a new form, no need to
// validate
validForm = false;
} else {
// Extract all basic parameters
department = req.getParameter("Department");
course = req.getParameter("Course");
section = req.getParameter("Section");
building = req.getParameter("Building");
comments = req.getParameter("Comments");
String minutestmp = req.getParameter("MinutesToOrFrom");
try {
minutesToOrFrom = Integer.parseInt(minutestmp);
} catch (NumberFormatException nfe) {
errors.add("Minutes to or from must be a whole number.");
}
String stype = req.getParameter("Type");
if (stype != null && !stype.equals("")) {
if (stype.equals(Absence.Type.Absence.getValue())) {
absenceType = Absence.Type.Absence;
} else if (stype.equals(Absence.Type.Tardy.getValue())) {
absenceType = Absence.Type.Tardy;
} else if (stype.equals(Absence.Type.EarlyCheckOut.getValue())) {
absenceType = Absence.Type.EarlyCheckOut;
}
} else {
errors.add("Invalid type.");
}
// this is one-based! Starting on Sunday.
try {
day = Integer.parseInt(req.getParameter("DayOfWeek"));
} catch (NumberFormatException nfe) {
errors.add("Weekday was invalid.");
}
if (day < 1 || day > 7) {
errors.add("Value of " + day + " for day was not valid.");
}
try {
startDate = Util.parseDate(req.getParameter("StartMonth"),
req.getParameter("StartDay"),
req.getParameter("StartYear"), "0", "AM", "0", train
.getAppDataController().get().getTimeZone());
} catch (IllegalArgumentException e) {
validForm = false;
errors.add("The start date is invalid.");
}
try {
endDate = Util.parseDate(req.getParameter("EndMonth"),
req.getParameter("EndDay"),
req.getParameter("EndYear"), "0", "AM", "0", train
.getAppDataController().get().getTimeZone());
} catch (IllegalArgumentException e) {
validForm = false;
errors.add("The end date is invalid.");
}
try {
fromTime = Util.parseDate("1", "1", "1000",
req.getParameter("FromHour"),
req.getParameter("FromAMPM"),
req.getParameter("FromMinute"), train
.getAppDataController().get().getTimeZone());
} catch (IllegalArgumentException e) {
validForm = false;
errors.add("The start time is invalid.");
}
try {
toTime = Util.parseDate("1", "1", "1000",
req.getParameter("ToHour"), req.getParameter("ToAMPM"),
req.getParameter("ToMinute"), train
.getAppDataController().get().getTimeZone());
} catch (IllegalArgumentException e) {
validForm = false;
errors.add("The end time is invalid.");
}
}
if (validForm) {
// Store our new form to the datastore
User student = train.getAuthController().getCurrentUser(
req.getSession());
Form form = null;
try {
form = train.getFormsController().createFormB(student,
department, course, section, building, startDate,
endDate, day, fromTime, toTime, comments,
minutesToOrFrom, absenceType);
} catch (IllegalArgumentException e) {
validForm = false;
errors.add(e.getMessage());
}
if (form == null) {
validForm = false;
errors.add("Fix any errors above and try to resubmit. If you're still having issues, submit a bug report using the form at the bottom of the page.");
}
}
if (validForm) {
String url = getIndexURL() + "?success_message="
+ URLEncoder.encode(SUCCESS_FORMB, "UTF-8");
url = resp.encodeRedirectURL(url);
resp.sendRedirect(url);
} else {
// Show form
PageBuilder page = new PageBuilder(Page.formb, SERVLET_PATH);
page.setPageTitle("Form B");
page.setAttribute("daysOfWeek", App.getDaysOfTheWeek());
page.setAttribute("error_messages", errors);
page.setAttribute("Department", department);
page.setAttribute("Course", course);
page.setAttribute("Section", section);
page.setAttribute("Building", building);
setStartDate(startDate, page, train.getAppDataController().get()
.getTimeZone());
setEndDate(endDate, page, train.getAppDataController().get()
.getTimeZone());
page.setAttribute("Type", Form.Type.B);
page.setAttribute("Comments", comments);
page.setAttribute("MinutesToOrFrom", minutesToOrFrom);
page.setAttribute("Type", absenceType);
page.setAttribute("types", Absence.Type.values());
if (fromTime != null) {
Calendar from = Calendar.getInstance(train.getAppDataController().get()
.getTimeZone());
from.setTime(fromTime);
page.setAttribute("FromHour", from.get(Calendar.HOUR));
page.setAttribute("FromMinute", from.get(Calendar.MINUTE));
page.setAttribute("FromAMPM", from.get(Calendar.AM_PM) == 0 ? "AM" : "PM");
}
if (toTime != null) {
Calendar to = Calendar.getInstance(train.getAppDataController().get()
.getTimeZone());
to.setTime(toTime);
page.setAttribute("ToHour", to.get(Calendar.HOUR));
page.setAttribute("ToMinute", to.get(Calendar.MINUTE));
page.setAttribute("ToAMPM", to.get(Calendar.AM_PM) == 0 ? "AM" : "PM");
}
page.passOffToJsp(req, resp);
}
}
|
diff --git a/src/info/guardianproject/otr/app/im/ui/AccountWizardActivity.java b/src/info/guardianproject/otr/app/im/ui/AccountWizardActivity.java
index ab491374..6fedc47f 100644
--- a/src/info/guardianproject/otr/app/im/ui/AccountWizardActivity.java
+++ b/src/info/guardianproject/otr/app/im/ui/AccountWizardActivity.java
@@ -1,412 +1,413 @@
package info.guardianproject.otr.app.im.ui;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.InputType;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import info.guardianproject.otr.app.im.R;
public class AccountWizardActivity extends Activity implements OnClickListener
{
private String accountId = "";
private String username = "";
private String hostname = "";
private String port = "5222";
private EditText editAccountId1;
private EditText editAccountId2;
private int title[] = {
R.string.account_wizard_setup_title,
R.string.account_wizard_account_title,
R.string.account_wizard_host_title,
R.string.account_wizard_ready_title
};
private int msg[] = {
R.string.account_wizard_setup_body,
R.string.account_wizard_account_body,
R.string.account_wizard_host_body,
R.string.account_wizard_ready_body,
};
private String fields[][] =
{
{null,null},
{"Account ID",null},
{"Hostname","Port Number"},
{null, null},
};
private String buttons[][] =
{
{null,"Next"},
{null,"Next"},
{"Back","Save"},
{"Back","Let's Go!"},
};
private View.OnClickListener listener[][] =
{
{
null,
new View.OnClickListener() {
@Override
public void onClick(View v) {
nextContent();
editAccountId1.setText(accountId);
}
}
},
{
new View.OnClickListener() {
@Override
public void onClick(View v) {
prevContent();
}
},
new View.OnClickListener() {
@Override
public void onClick(View v) {
parseAccount ();
hideKeyboard ();
}
}
},
{
new View.OnClickListener() {
@Override
public void onClick(View v) {
prevContent();
editAccountId1.setText(accountId);
}
},
new View.OnClickListener() {
@Override
public void onClick(View v) {
saveHostValues();
nextContent();
hideKeyboard();
}
}
},
{
new View.OnClickListener() {
@Override
public void onClick(View v) {
prevContent();
}
},
new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getBaseContext(), MainActivity.class);
intent.putExtra("doSignIn",true);
startActivityForResult(intent, 1);
}
}
},
};
private void hideKeyboard ()
{
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(editAccountId1.getWindowToken(), 0);
}
private int contentIdx = -1;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
if (savedInstanceState != null)
{
if (savedInstanceState.containsKey("contentIdx"))
contentIdx = savedInstanceState.getInt("contentIdx");
if (savedInstanceState.containsKey("accountId"))
contentIdx = savedInstanceState.getInt("accountId");
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("contentIdx", contentIdx);
outState.putString("accountId", accountId);
}
@Override
protected void onPause() {
super.onPause();
}
@Override
protected void onStart() {
super.onStart();
setContentView(R.layout.fields_buttons_view);
if (contentIdx == -1)
{
nextContent ();
}
else
{
showContent(contentIdx);
}
}
private void prevContent ()
{
contentIdx--;
showContent(contentIdx);
}
private void nextContent ()
{
contentIdx++;
showContent(contentIdx);
}
private void showContent (int contentIdx)
{
TextView txtTitle = ((TextView)findViewById(R.id.WizardTextTitle));
txtTitle.setText(getString(title[contentIdx]));
TextView txtBody = ((TextView)findViewById(R.id.WizardTextBody));
txtBody.setText(getString(msg[contentIdx]));
editAccountId1 = ((EditText)findViewById(R.id.edit1));
editAccountId1.setInputType(InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS);
editAccountId2 = ((EditText)findViewById(R.id.edit2));
if (fields[contentIdx][0] != null)
{
editAccountId1.setHint(fields[contentIdx][0]);
editAccountId1.setVisibility(TextView.VISIBLE);
}
else
{
editAccountId1.setVisibility(TextView.GONE);
}
if (fields[contentIdx][1] != null)
{
editAccountId2.setHint(fields[contentIdx][1]);
editAccountId2.setVisibility(TextView.VISIBLE);
}
else
{
editAccountId2.setVisibility(TextView.GONE);
}
Button btn1 = ((Button)findViewById(R.id.btnWizard1));
if (buttons[contentIdx][0] != null)
{
btn1.setText(buttons[contentIdx][0]);
btn1.setOnClickListener(listener[contentIdx][0]);
btn1.setVisibility(Button.VISIBLE);
}
else
{
btn1.setVisibility(Button.INVISIBLE);
}
Button btn2 = ((Button)findViewById(R.id.btnWizard2));
if (buttons[contentIdx][1] != null)
{
btn2.setText(buttons[contentIdx][1]);
btn2.setOnClickListener(listener[contentIdx][1]);
btn2.setVisibility(Button.VISIBLE);
}
else
{
btn2.setVisibility(Button.INVISIBLE);
}
}
@Override
protected void onResume() {
super.onResume();
}
@Override
public void onClick(DialogInterface arg0, int arg1) {
}
private void parseAccount ()
{
boolean isGood = false;
EditText editAccountId = ((EditText)findViewById(R.id.edit1));
- editAccountId.setInputType(InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS);// | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
+ // InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS would also be nice but Android 2.x only
+ editAccountId.setInputType(InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS);
accountId = editAccountId.getText().toString();
String[] split = accountId.split("@");
username = split[0];
hostname = null;
port = "5222";
if (split.length > 1)
{
hostname = split[1];
split = hostname.split(":");
hostname = split[0];
if(split.length > 1)
port = split[1];
}
String errMsg = "";
if (hostname == null)
{
isGood = false;
errMsg = "You didn't enter an @hostname.com part for your account ID. Try again!";
}
else if (hostname.indexOf(".")==-1)
{
isGood = false;
errMsg = "Your server hostname didn't have a .com, .net or similar appendix. Try again!";
}
else
{
isGood = true;
}
if (!isGood)
{
Toast.makeText(this, errMsg, Toast.LENGTH_LONG).show();
}
else
{
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplication());
Editor edit = prefs.edit();
edit.putString("pref_account_user", username);
edit.remove("pref_account_pass");
edit.putString("pref_account_host", hostname.toLowerCase());
edit.putString("pref_account_port", port);
edit.commit();
nextContent();
EditText editAccountId1 = ((EditText)findViewById(R.id.edit1));
EditText editAccountId2 = ((EditText)findViewById(R.id.edit2));
editAccountId1.setText(hostname);
editAccountId2.setText(port);
if (hostname.equals("gmail.com") || hostname.equals("jabber.org"))
{
nextContent();
}
}
}
private void saveHostValues ()
{
EditText editAccountId1 = ((EditText)findViewById(R.id.edit1));
EditText editAccountId2 = ((EditText)findViewById(R.id.edit2));
hostname = editAccountId1.getText().toString();
port = editAccountId2.getText().toString();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplication());
Editor edit = prefs.edit();
edit.putString("pref_account_host", hostname.toLowerCase());
edit.putString("pref_account_port", port);
edit.commit();
}
}
| true | true | private void parseAccount ()
{
boolean isGood = false;
EditText editAccountId = ((EditText)findViewById(R.id.edit1));
editAccountId.setInputType(InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS);// | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
accountId = editAccountId.getText().toString();
String[] split = accountId.split("@");
username = split[0];
hostname = null;
port = "5222";
if (split.length > 1)
{
hostname = split[1];
split = hostname.split(":");
hostname = split[0];
if(split.length > 1)
port = split[1];
}
String errMsg = "";
if (hostname == null)
{
isGood = false;
errMsg = "You didn't enter an @hostname.com part for your account ID. Try again!";
}
else if (hostname.indexOf(".")==-1)
{
isGood = false;
errMsg = "Your server hostname didn't have a .com, .net or similar appendix. Try again!";
}
else
{
isGood = true;
}
if (!isGood)
{
Toast.makeText(this, errMsg, Toast.LENGTH_LONG).show();
}
else
{
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplication());
Editor edit = prefs.edit();
edit.putString("pref_account_user", username);
edit.remove("pref_account_pass");
edit.putString("pref_account_host", hostname.toLowerCase());
edit.putString("pref_account_port", port);
edit.commit();
nextContent();
EditText editAccountId1 = ((EditText)findViewById(R.id.edit1));
EditText editAccountId2 = ((EditText)findViewById(R.id.edit2));
editAccountId1.setText(hostname);
editAccountId2.setText(port);
if (hostname.equals("gmail.com") || hostname.equals("jabber.org"))
{
nextContent();
}
}
}
| private void parseAccount ()
{
boolean isGood = false;
EditText editAccountId = ((EditText)findViewById(R.id.edit1));
// InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS would also be nice but Android 2.x only
editAccountId.setInputType(InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS);
accountId = editAccountId.getText().toString();
String[] split = accountId.split("@");
username = split[0];
hostname = null;
port = "5222";
if (split.length > 1)
{
hostname = split[1];
split = hostname.split(":");
hostname = split[0];
if(split.length > 1)
port = split[1];
}
String errMsg = "";
if (hostname == null)
{
isGood = false;
errMsg = "You didn't enter an @hostname.com part for your account ID. Try again!";
}
else if (hostname.indexOf(".")==-1)
{
isGood = false;
errMsg = "Your server hostname didn't have a .com, .net or similar appendix. Try again!";
}
else
{
isGood = true;
}
if (!isGood)
{
Toast.makeText(this, errMsg, Toast.LENGTH_LONG).show();
}
else
{
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplication());
Editor edit = prefs.edit();
edit.putString("pref_account_user", username);
edit.remove("pref_account_pass");
edit.putString("pref_account_host", hostname.toLowerCase());
edit.putString("pref_account_port", port);
edit.commit();
nextContent();
EditText editAccountId1 = ((EditText)findViewById(R.id.edit1));
EditText editAccountId2 = ((EditText)findViewById(R.id.edit2));
editAccountId1.setText(hostname);
editAccountId2.setText(port);
if (hostname.equals("gmail.com") || hostname.equals("jabber.org"))
{
nextContent();
}
}
}
|
diff --git a/src/main/java/javax/time/period/field/PeriodField.java b/src/main/java/javax/time/period/field/PeriodField.java
index 27d9995a..b1dd191f 100644
--- a/src/main/java/javax/time/period/field/PeriodField.java
+++ b/src/main/java/javax/time/period/field/PeriodField.java
@@ -1,233 +1,233 @@
/*
* Copyright (c) 2007, Stephen Colebourne & Michael Nascimento Santos
*
* 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 JSR-310 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 javax.time.period.field;
import javax.time.MathUtils;
import javax.time.period.PeriodUnit;
import javax.time.period.PeriodView;
/**
* A period measured in terms of a single field, such as days or seconds.
* <p>
* Years is an immutable period that can only store years.
* It is a type-safe way of representing a number of years in an application.
* <p>
* Static factory methods allow you to constuct instances.
* The number of years may be queried using getYears().
* Basic mathematical operations are provided - plus(), minus(), multipliedBy(),
* dividedBy() and negated(), all of which return a new instance
* <p>
* PeriodField is an abstract class and must be implemented with care to ensure
* other classes in the framework operate correctly.
* All instantiable subclasses must be final, immutable and thread-safe.
*
* @author Stephen Colebourne
*/
public abstract class PeriodField implements PeriodView {
//-----------------------------------------------------------------------
/**
* Constructs a new instance.
*/
protected PeriodField() {
super();
}
//-----------------------------------------------------------------------
/**
* Gets the amount of time in this period field.
*
* @return the amount of time of this period field
*/
public abstract int getAmount();
/**
* Returns a new instance of the subclass with a different amount of time.
*
* @param amount the amount of time to set in the new period field, may be negative
* @return a new period field, never null
*/
public abstract PeriodField withAmount(int amount);
//-----------------------------------------------------------------------
/**
* Gets the unit defining the amount of time.
*
* @return the period unit, never null
*/
public abstract PeriodUnit getUnit();
//-----------------------------------------------------------------------
/**
* Returns a new instance with the specified amount of time added.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param amount the amount of time to add, may be negative
* @return the new period field plus the specified amount of time, never null
* @throws ArithmeticException if the result overflows an int
*/
public PeriodField plus(int amount) {
if (amount == 0) {
return this;
}
return withAmount(MathUtils.safeAdd(getAmount(), amount));
}
//-----------------------------------------------------------------------
/**
* Returns a new instance with the specified amount of time taken away.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param amount the amount of time to take away, may be negative
* @return the new period minus the specified amount of time, never null
* @throws ArithmeticException if the result overflows an int
*/
public PeriodField minus(int amount) {
return withAmount(MathUtils.safeSubtract(getAmount(), amount));
}
//-----------------------------------------------------------------------
/**
* Returns a new instance with the amount multiplied by the specified scalar.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param scalar the amount to multiply by, may be negative
* @return the new period multiplied by the specified scalar, never null
* @throws ArithmeticException if the result overflows an int
*/
public PeriodField multipliedBy(int scalar) {
return withAmount(MathUtils.safeMultiply(getAmount(), scalar));
}
/**
* Returns a new instance with the amount divided by the specified divisor.
* The calculation uses integer division, thus 3 divided by 2 is 1.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param divisor the amount to divide by, may be negative
* @return the new period divided by the specified divisor, never null
* @throws ArithmeticException if the divisor is zero
*/
public PeriodField dividedBy(int divisor) {
if (divisor == 1) {
return this;
}
return withAmount(getAmount() / divisor);
}
//-----------------------------------------------------------------------
/**
* Returns a new instance with the amount negated.
*
* @return the new period with a negated amount, never null
* @throws ArithmeticException if the result overflows an int
*/
public PeriodField negated() {
return withAmount(MathUtils.safeNegate(getAmount()));
}
// //-----------------------------------------------------------------------
// /**
// * Converts this instance to another type of period.
// * <p>
// * This instance is immutable and unaffected by this method call.
// *
// * @param <T> the type to be converted to
// * @param periodType the period type to convert to, not null
// * @return the new converted period field, never null
// * @throws IllegalArgumentException if the conversion is not possible
// * @throws ArithmeticException if the result overflows an int
// */
// public <T extends PeriodField> T convertTo(Class<T> periodType) {
// PeriodUnit unit = null;
// try {
// Field field = periodType.getField("UNIT");
// unit = (PeriodUnit) field.get(null);
// } catch (NoSuchFieldException ex) {
// throw new IllegalArgumentException("UNIT field missing on " + periodType, ex);
// } catch (SecurityException ex) {
// throw new IllegalArgumentException("UNIT field not public on " + periodType, ex);
// } catch (IllegalArgumentException ex) {
// throw new IllegalArgumentException("UNIT field access error on " + periodType, ex);
// } catch (IllegalAccessException ex) {
// throw new IllegalArgumentException("UNIT field not public on " + periodType, ex);
// } catch (NullPointerException ex) {
// throw new IllegalArgumentException("UNIT field not static on " + periodType, ex);
// } catch (ClassCastException ex) {
// throw new IllegalArgumentException("UNIT field not a PeriodUnit on " + periodType, ex);
// }
// return null; //getUnit().convert(this);
// }
//-----------------------------------------------------------------------
/**
* Is this instance equal to that specified, as defined by <code>Periodal</code>.
*
* @param other the other amount of time, null returns false
* @return true if this amount of time is the same as that specified
*/
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (other instanceof PeriodView) {
PeriodView otherPeriod = (PeriodView) other;
- return getPeriodViewMap().equals(otherPeriod);
+ return getPeriodViewMap().equals(otherPeriod.getPeriodViewMap());
}
return false;
}
/**
* Returns the hash code for this period.
*
* @return the hash code defined by <code>Periodal</code>
*/
@Override
public int hashCode() {
return getPeriodViewMap().hashCode();
}
//-----------------------------------------------------------------------
/**
* Returns a string representation of the amount of time.
*
* @return the amount of time in ISO8601 string format
*/
@Override
public abstract String toString();
}
| true | true | public boolean equals(Object other) {
if (this == other) {
return true;
}
if (other instanceof PeriodView) {
PeriodView otherPeriod = (PeriodView) other;
return getPeriodViewMap().equals(otherPeriod);
}
return false;
}
| public boolean equals(Object other) {
if (this == other) {
return true;
}
if (other instanceof PeriodView) {
PeriodView otherPeriod = (PeriodView) other;
return getPeriodViewMap().equals(otherPeriod.getPeriodViewMap());
}
return false;
}
|
diff --git a/src/main/java/com/haakenstad/potwater/scheduler/PotwaterScheduler.java b/src/main/java/com/haakenstad/potwater/scheduler/PotwaterScheduler.java
index f25deae..bfcd1fe 100644
--- a/src/main/java/com/haakenstad/potwater/scheduler/PotwaterScheduler.java
+++ b/src/main/java/com/haakenstad/potwater/scheduler/PotwaterScheduler.java
@@ -1,84 +1,84 @@
package com.haakenstad.potwater.scheduler;
import org.apache.commons.lang3.StringUtils;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Date;
import static org.quartz.CronScheduleBuilder.cronSchedule;
import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;
/**
* Created with IntelliJ IDEA.
* User: bjornhaa
* Date: 04.07.13
* Time: 22:26
* To change this template use File | Settings | File Templates.
*/
public class PotwaterScheduler {
private static final Integer VALVE_1 = 7;
private static final Integer VALVE_2 = 6;
private static final Integer VALVE_3 = 5;
private static final Integer VALVE_4 = 4;
private static final Integer DURATION_VALVE_1 = 10;
private static final Integer DURATION_VALVE_2 = 10;
private static final Integer DURATION_VALVE_3 = 10;
private static final Integer DURATION_VALVE_4 = 25;
private static final Integer PUMP = 2;
public static void main(String[] args) throws Exception {
System.out.println("*********** Starting PotWater ****************");
System.out.println("Args:" + StringUtils.join(args));
boolean debug = false;
if (args.length > 0) {
if ("debug".equalsIgnoreCase(args[0])) {
debug = true;
}
}
Logger log = LoggerFactory.getLogger(PotwaterScheduler.class);
SchedulerFactory sf = new StdSchedulerFactory();
Scheduler sched = sf.getScheduler();
JobDetail job = newJob(PotWaterJob.class)
.withIdentity("wetjob")
.usingJobData("debug", debug)
.usingJobData("pump", PUMP)
.usingJobData(VALVE_1.toString(), DURATION_VALVE_1)
.usingJobData(VALVE_2.toString(), DURATION_VALVE_2)
.usingJobData(VALVE_3.toString(), DURATION_VALVE_3)
.usingJobData(VALVE_4.toString(), DURATION_VALVE_4)
.build();
CronTrigger trigger = newTrigger()
.withIdentity("trigger1")
.withSchedule(cronSchedule("0 0 20 * * ?"))
.build();
Trigger testTrigger = newTrigger()
.startNow()
.build();
Date ft = null;
- //ft = sched.scheduleJob(job, trigger);
- ft = sched.scheduleJob(job, testTrigger);
+ ft = sched.scheduleJob(job, trigger);
+ //ft = sched.scheduleJob(job, testTrigger);
log.info(job.getKey() + " has been scheduled to run at: " + ft
+ " and repeat based on expression: "
+ trigger.getCronExpression());
sched.start();
log.info("------- Started Scheduler -----------------");
while (true) ;
}
}
| true | true | public static void main(String[] args) throws Exception {
System.out.println("*********** Starting PotWater ****************");
System.out.println("Args:" + StringUtils.join(args));
boolean debug = false;
if (args.length > 0) {
if ("debug".equalsIgnoreCase(args[0])) {
debug = true;
}
}
Logger log = LoggerFactory.getLogger(PotwaterScheduler.class);
SchedulerFactory sf = new StdSchedulerFactory();
Scheduler sched = sf.getScheduler();
JobDetail job = newJob(PotWaterJob.class)
.withIdentity("wetjob")
.usingJobData("debug", debug)
.usingJobData("pump", PUMP)
.usingJobData(VALVE_1.toString(), DURATION_VALVE_1)
.usingJobData(VALVE_2.toString(), DURATION_VALVE_2)
.usingJobData(VALVE_3.toString(), DURATION_VALVE_3)
.usingJobData(VALVE_4.toString(), DURATION_VALVE_4)
.build();
CronTrigger trigger = newTrigger()
.withIdentity("trigger1")
.withSchedule(cronSchedule("0 0 20 * * ?"))
.build();
Trigger testTrigger = newTrigger()
.startNow()
.build();
Date ft = null;
//ft = sched.scheduleJob(job, trigger);
ft = sched.scheduleJob(job, testTrigger);
log.info(job.getKey() + " has been scheduled to run at: " + ft
+ " and repeat based on expression: "
+ trigger.getCronExpression());
sched.start();
log.info("------- Started Scheduler -----------------");
while (true) ;
}
| public static void main(String[] args) throws Exception {
System.out.println("*********** Starting PotWater ****************");
System.out.println("Args:" + StringUtils.join(args));
boolean debug = false;
if (args.length > 0) {
if ("debug".equalsIgnoreCase(args[0])) {
debug = true;
}
}
Logger log = LoggerFactory.getLogger(PotwaterScheduler.class);
SchedulerFactory sf = new StdSchedulerFactory();
Scheduler sched = sf.getScheduler();
JobDetail job = newJob(PotWaterJob.class)
.withIdentity("wetjob")
.usingJobData("debug", debug)
.usingJobData("pump", PUMP)
.usingJobData(VALVE_1.toString(), DURATION_VALVE_1)
.usingJobData(VALVE_2.toString(), DURATION_VALVE_2)
.usingJobData(VALVE_3.toString(), DURATION_VALVE_3)
.usingJobData(VALVE_4.toString(), DURATION_VALVE_4)
.build();
CronTrigger trigger = newTrigger()
.withIdentity("trigger1")
.withSchedule(cronSchedule("0 0 20 * * ?"))
.build();
Trigger testTrigger = newTrigger()
.startNow()
.build();
Date ft = null;
ft = sched.scheduleJob(job, trigger);
//ft = sched.scheduleJob(job, testTrigger);
log.info(job.getKey() + " has been scheduled to run at: " + ft
+ " and repeat based on expression: "
+ trigger.getCronExpression());
sched.start();
log.info("------- Started Scheduler -----------------");
while (true) ;
}
|
diff --git a/src/main/java/hudson/ivy/IvyModuleSet.java b/src/main/java/hudson/ivy/IvyModuleSet.java
index 36352f8..c58f1aa 100644
--- a/src/main/java/hudson/ivy/IvyModuleSet.java
+++ b/src/main/java/hudson/ivy/IvyModuleSet.java
@@ -1,733 +1,733 @@
/*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Jorg Heymans, Peter Hayes, Red Hat, Inc., Stephen Connolly, id:cactusman
*
* 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 hudson.ivy;
import static hudson.Util.fixEmpty;
import static hudson.model.ItemGroupMixIn.loadChildren;
import hudson.CopyOnWrite;
import hudson.Extension;
import hudson.FilePath;
import hudson.Util;
import hudson.model.AbstractProject;
import hudson.model.Action;
import hudson.model.BuildableItemWithBuildWrappers;
import hudson.model.DependencyGraph;
import hudson.model.Descriptor;
import hudson.model.Executor;
import hudson.model.Hudson;
import hudson.model.Item;
import hudson.model.ItemGroup;
import hudson.model.Job;
import hudson.model.Queue;
import hudson.model.ResourceActivity;
import hudson.model.SCMedItem;
import hudson.model.Saveable;
import hudson.model.TopLevelItem;
import hudson.model.TopLevelItemDescriptor;
import hudson.model.Descriptor.FormException;
import hudson.model.Queue.Task;
import hudson.search.CollectionSearchIndex;
import hudson.search.SearchIndexBuilder;
import hudson.tasks.Ant;
import hudson.tasks.BuildStep;
import hudson.tasks.BuildStepDescriptor;
import hudson.tasks.BuildWrapper;
import hudson.tasks.BuildWrappers;
import hudson.tasks.Publisher;
import hudson.tasks.Ant.AntInstallation;
import hudson.util.CopyOnWriteMap;
import hudson.util.DescribableList;
import hudson.util.FormValidation;
import hudson.util.Function1;
import java.io.File;
import java.io.IOException;
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.Properties;
import java.util.Set;
import javax.servlet.ServletException;
import net.sf.json.JSONObject;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.export.Exported;
/**
* Group of {@link IvyModule}s.
*
* <p>
* This corresponds to the group of Ivy module descriptors that constitute a single
* branch of projects.
*
* @author Timothy Bingaman
*/
public final class IvyModuleSet extends AbstractIvyProject<IvyModuleSet,IvyModuleSetBuild> implements TopLevelItem, ItemGroup<IvyModule>, SCMedItem, Saveable, BuildableItemWithBuildWrappers {
/**
* All {@link IvyModule}s, keyed by their {@link IvyModule#getModuleName()} module name}s.
*/
transient /*final*/ Map<ModuleName,IvyModule> modules = new CopyOnWriteMap.Tree<ModuleName,IvyModule>();
/**
* Topologically sorted list of modules. This only includes live modules,
* since archived ones usually don't have consistent history.
*/
@CopyOnWrite
transient List<IvyModule> sortedActiveModules;
private String ivyFilePattern;
private String ivyFileExcludesPattern;
private String targets;
private String ivyBranch;
private String relativePathToDescriptorFromModuleRoot;
/**
* Identifies {@link AntInstallation} to be used.
*/
private String antName;
/**
* ANT_OPTS if not null.
*/
private String antOpts;
/**
* Optional build script path relative to the workspace.
* Used for the Ant '-f' option.
*/
private String buildFile;
/**
* Optional properties to be passed to Ant. Follows {@link Properties} syntax.
*/
private String antProperties;
/**
* If true, the build will be aggregator style, meaning all the modules are
* executed in a single Ant invocation, as in CLI. False otherwise, meaning
* each module is built separately and possibly in parallel.
*/
private boolean aggregatorStyleBuild = true;
/**
* If true, and if aggregatorStyleBuild is false, the build will check the
* changeset before building, and if there are changes, only those modules
* which have changes or those modules which failed or were unstable in the
* previous build will be built directly. Any modules depending on the
* directly built modules will also be built.
*/
private boolean incrementalBuild = false;
/**
* The name of the property used to pass the names of the changed modules
* to the build when both incremental build and aggregated build options are
* selected.
*/
private String changedModulesProperty;
/**
* If true, do not automatically schedule a build when one of the project
* dependencies is built.
*/
private boolean ignoreUpstreamChanges = false;
/**
* If true, do not archive artifacts to the master.
*/
private boolean archivingDisabled = false;
/**
* List of active {@link Publisher}s configured for this project.
*/
private DescribableList<Publisher,Descriptor<Publisher>> publishers =
new DescribableList<Publisher,Descriptor<Publisher>>(this);
/**
* List of active {@link BuildWrapper}s configured for this project.
*/
private DescribableList<BuildWrapper,Descriptor<BuildWrapper>> buildWrappers =
new DescribableList<BuildWrapper, Descriptor<BuildWrapper>>(this);
public IvyModuleSet(String name) {
super(Hudson.getInstance(),name);
}
public String getUrlChildPrefix() {
// seemingly redundant "./" is used to make sure that ':' is not interpreted as the scheme identifier
return ".";
}
@Override
public Hudson getParent() {
return Hudson.getInstance();
}
public Collection<IvyModule> getItems() {
return modules.values();
}
@Exported
public Collection<IvyModule> getModules() {
return getItems();
}
public IvyModule getItem(String name) {
return modules.get(ModuleName.fromString(name));
}
public IvyModule getModule(String name) {
return getItem(name);
}
@Override
protected void updateTransientActions() {
super.updateTransientActions();
for (IvyModule module: modules.values()) {
module.updateTransientActions();
}
if(publishers!=null) // this method can be loaded from within the onLoad method, where this might be null
for (BuildStep step : publishers) {
Collection<? extends Action> a = step.getProjectActions(this);
if(a!=null)
transientActions.addAll(a);
}
if (buildWrappers!=null)
for (BuildWrapper step : buildWrappers) {
Collection<? extends Action> a = step.getProjectActions(this);
if(a!=null)
transientActions.addAll(a);
}
}
@Override
protected void addTransientActionsFromBuild(IvyModuleSetBuild build, Set<Class> added) {
if(build==null) return;
for (Action a : build.getActions())
if(a instanceof IvyAggregatedReport)
if(added.add(a.getClass()))
transientActions.add(((IvyAggregatedReport)a).getProjectAction(this));
List<IvyReporter> list = build.projectActionReporters;
if(list==null) return;
for (IvyReporter step : list) {
if(!added.add(step.getClass())) continue; // already added
Action a = step.getAggregatedProjectAction(this);
if(a!=null)
transientActions.add(a);
}
}
/**
* Called by {@link IvyModule#doDoDelete(StaplerRequest, StaplerResponse)}.
* Real deletion is done by the caller, and this method only adjusts the
* data structure the parent maintains.
*/
/*package*/ void onModuleDeleted(IvyModule module) {
modules.remove(module.getModuleName());
}
/**
* Returns true if there's any disabled module.
*/
public boolean hasDisabledModule() {
for (IvyModule m : modules.values()) {
if(m.isDisabled())
return true;
}
return false;
}
/**
* Possibly empty list of all disabled modules (if disabled==true)
* or all enabeld modules (if disabled==false)
*/
public List<IvyModule> getDisabledModules(boolean disabled) {
if(!disabled && sortedActiveModules!=null)
return sortedActiveModules;
List<IvyModule> r = new ArrayList<IvyModule>();
for (IvyModule m : modules.values()) {
if(m.isDisabled()==disabled)
r.add(m);
}
return r;
}
public boolean isIncrementalBuild() {
return incrementalBuild;
}
public String getChangedModulesProperty() {
return changedModulesProperty;
}
public boolean isAggregatorStyleBuild() {
return aggregatorStyleBuild;
}
public boolean ignoreUpstreamChanges() {
return ignoreUpstreamChanges;
}
public boolean isArchivingDisabled() {
return archivingDisabled;
}
public void setIncrementalBuild(boolean incrementalBuild) {
this.incrementalBuild = incrementalBuild;
}
public String getIvyFilePattern() {
return ivyFilePattern;
}
public void setIvyFilePattern(String ivyFilePattern) {
this.ivyFilePattern = ivyFilePattern;
}
public String getIvyFileExcludesPattern() {
return ivyFileExcludesPattern;
}
public void setIvyFileExcludesPattern(String ivyFileExcludesPattern) {
this.ivyFileExcludesPattern = ivyFileExcludesPattern;
}
public String getIvyBranch() {
return ivyBranch;
}
public void setIvyBranch(String ivyBranch) {
this.ivyBranch = ivyBranch;
}
public void setAggregatorStyleBuild(boolean aggregatorStyleBuild) {
this.aggregatorStyleBuild = aggregatorStyleBuild;
}
public void setIgnoreUpstremChanges(boolean ignoreUpstremChanges) {
this.ignoreUpstreamChanges = ignoreUpstremChanges;
}
public void setIsArchivingDisabled(boolean archivingDisabled) {
this.archivingDisabled = archivingDisabled;
}
/**
* List of active {@link Publisher}s that should be applied to all module builds.
*/
public DescribableList<Publisher, Descriptor<Publisher>> getModulePublishers() {
return aggregatorStyleBuild ? new DescribableList<Publisher, Descriptor<Publisher>>(this) : publishers;
}
/**
* List of active {@link Publisher}s. Can be empty but never null.
*/
public DescribableList<Publisher, Descriptor<Publisher>> getPublishers() {
return publishers;
}
@Override
public DescribableList<Publisher, Descriptor<Publisher>> getPublishersList() {
return publishers;
}
public DescribableList<BuildWrapper, Descriptor<BuildWrapper>> getBuildWrappersList() {
return buildWrappers;
}
/**
* List of active {@link BuildWrapper}s. Can be empty but never null.
*
* @deprecated as of 1.335
* Use {@link #getBuildWrappersList()} to be consistent with other subtypes of {@link AbstractProject}.
*/
@Deprecated
public DescribableList<BuildWrapper, Descriptor<BuildWrapper>> getBuildWrappers() {
return buildWrappers;
}
@Override
public Object getDynamic(String token, StaplerRequest req, StaplerResponse rsp) {
if (ModuleName.isValid(token))
return getModule(token);
return super.getDynamic(token,req,rsp);
}
public File getRootDirFor(IvyModule child) {
return new File(getModulesDir(),child.getModuleName().toFileSystemName());
}
@Override
public Collection<Job> getAllJobs() {
Set<Job> jobs = new HashSet<Job>(getItems());
jobs.add(this);
return jobs;
}
@Override
protected Class<IvyModuleSetBuild> getBuildClass() {
return IvyModuleSetBuild.class;
}
@Override
protected SearchIndexBuilder makeSearchIndex() {
return super.makeSearchIndex()
.add(new CollectionSearchIndex<IvyModule>() {// for computers
@Override
protected IvyModule get(String key) {
for (IvyModule m : modules.values()) {
if(m.getDisplayName().equals(key))
return m;
}
return null;
}
@Override
protected Collection<IvyModule> all() {
return modules.values();
}
@Override
protected String getName(IvyModule o) {
return o.getName();
}
});
}
@Override
public boolean isFingerprintConfigured() {
return true;
}
@Override
public void onLoad(ItemGroup<? extends Item> parent, String name) throws IOException {
modules = Collections.emptyMap(); // needed during load
super.onLoad(parent, name);
modules = loadChildren(this, getModulesDir(),new Function1<ModuleName,IvyModule>() {
public ModuleName call(IvyModule module) {
return module.getModuleName();
}
});
if(publishers==null)
publishers = new DescribableList<Publisher,Descriptor<Publisher>>(this);
publishers.setOwner(this);
if(buildWrappers==null)
buildWrappers = new DescribableList<BuildWrapper, Descriptor<BuildWrapper>>(this);
buildWrappers.setOwner(this);
updateTransientActions();
}
private File getModulesDir() {
return new File(getRootDir(),"modules");
}
/**
* To make it easy to grasp relationship among modules
* and the module set, we'll align the build numbers of
* all the modules.
*
* <p>
* This method is invoked from {@link Executor#run()},
* and because of the mutual exclusion among {@link IvyModuleSetBuild}
* and {@link IvyBuild}, we can safely touch all the modules.
*/
@Override
public synchronized int assignBuildNumber() throws IOException {
// determine the next value
updateNextBuildNumber();
return super.assignBuildNumber();
}
@Override
public void logRotate() throws IOException, InterruptedException {
super.logRotate();
// perform the log rotation of modules
for (IvyModule m : modules.values())
m.logRotate();
}
/**
* The next build of {@link IvyModuleSet} must have
* the build number newer than any of the current module build.
*/
/*package*/ void updateNextBuildNumber() throws IOException {
int next = this.nextBuildNumber;
for (IvyModule m : modules.values())
next = Math.max(next,m.getNextBuildNumber());
if(this.nextBuildNumber!=next) {
this.nextBuildNumber=next;
this.saveNextBuildNumber();
}
}
@Override
protected void buildDependencyGraph(DependencyGraph graph) {
publishers.buildDependencyGraph(this,graph);
buildWrappers.buildDependencyGraph(this,graph);
}
public AntInstallation inferAntInstallation() {
return getAnt();
}
@Override
protected Set<ResourceActivity> getResourceActivities() {
final Set<ResourceActivity> activities = new HashSet<ResourceActivity>();
activities.addAll(super.getResourceActivities());
activities.addAll(Util.filter(publishers,ResourceActivity.class));
activities.addAll(Util.filter(buildWrappers,ResourceActivity.class));
return activities;
}
public AbstractProject<?,?> asProject() {
return this;
}
/**
* Gets the list of targets to execute.
*/
public String getTargets() {
return targets;
}
public void setTargets(String targets) {
this.targets = targets;
}
public String getRelativePathToDescriptorFromModuleRoot() {
return relativePathToDescriptorFromModuleRoot;
}
public void setRelativePathToDescriptorFromModuleRoot(String relativePathToDescriptorFromModuleRoot) {
this.relativePathToDescriptorFromModuleRoot = relativePathToDescriptorFromModuleRoot;
}
/**
* Possibly null, whitespace-separated (including TAB, NL, etc) VM options
* to be used to launch Ant process.
*
* If antOpts is null or empty, we'll return the globally-defined ANT_OPTS.
*/
public String getAntOpts() {
if ((antOpts!=null) && (antOpts.trim().length()>0)) {
return antOpts;
}
else {
return DESCRIPTOR.getGlobalAntOpts();
}
}
/**
* Set ANT_OPTS.
*/
public void setAntOpts(String antOpts) {
this.antOpts = antOpts;
}
public String getBuildFile() {
return buildFile;
}
public String getAntProperties() {
return antProperties;
}
/**
* Gets the Ant to invoke.
* If null, we pick any random Ant installation.
*/
public AntInstallation getAnt() {
for( AntInstallation i : DESCRIPTOR.getAntDescriptor().getInstallations() ) {
if(antName==null || i.getName().equals(antName))
return i;
}
return null;
}
public void setAnt(String antName) {
this.antName = antName;
}
/**
* Returns the {@link IvyModule}s that are in the queue.
*/
public List<Queue.Item> getQueueItems() {
List<Queue.Item> r = new ArrayList<hudson.model.Queue.Item>();
for( Queue.Item item : Hudson.getInstance().getQueue().getItems() ) {
Task t = item.task;
if((t instanceof IvyModule && ((IvyModule)t).getParent()==this) || t ==this)
r.add(item);
}
return r;
}
/**
* Gets the list of targets specified by the user,
* without taking inheritance into account.
*
* <p>
* This is only used to present the UI screen, and in
* all the other cases {@link #getTargets()} should be used.
*/
public String getUserConfiguredTargets() {
return targets;
}
//
//
// Web methods
//
//
@Override
protected void submit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, FormException {
super.submit(req,rsp);
JSONObject json = req.getSubmittedForm();
ignoreUpstreamChanges = !json.has("triggerByDependency");
ivyFilePattern = Util.fixEmptyAndTrim(json.getString("ivyFilePattern"));
ivyFileExcludesPattern = Util.fixEmptyAndTrim(json.getString("ivyFileExcludesPattern"));
- targets = Util.fixEmptyAndTrim(json.getString("targets"));
+ targets = json.getString("targets").trim();
ivyBranch = Util.fixEmptyAndTrim(json.getString("ivyBranch"));
relativePathToDescriptorFromModuleRoot = Util.fixEmptyAndTrim(json.getString("relativePathToDescriptorFromModuleRoot"));
antName = Util.fixEmptyAndTrim(json.getString("antName"));
buildFile = Util.fixEmptyAndTrim(json.getString("buildFile"));
antOpts = Util.fixEmptyAndTrim(json.getString("antOpts"));
antProperties = Util.fixEmptyAndTrim(json.getString("antProperties"));
aggregatorStyleBuild = !req.hasParameter("perModuleBuild");
incrementalBuild = req.hasParameter("incrementalBuild");
if (incrementalBuild)
changedModulesProperty = Util.fixEmptyAndTrim(json.getJSONObject("incrementalBuild").getString("changedModulesProperty"));
publishers.rebuild(req,json,BuildStepDescriptor.filter(Publisher.all(),this.getClass()));
buildWrappers.rebuild(req,json,BuildWrappers.getFor(this));
updateTransientActions(); // to pick up transient actions from builder, publisher, etc.
}
public Class<? extends AbstractProject> getModuleClass() {
return IvyModule.class;
}
/**
* Delete all disabled modules.
*/
public void doDoDeleteAllDisabledModules(StaplerResponse rsp) throws IOException, InterruptedException {
checkPermission(DELETE);
for( IvyModule m : getDisabledModules(true))
m.delete();
rsp.sendRedirect2(".");
}
/**
* Check the location of the ivy descriptor file, alternate settings file, etc - any file.
*/
public FormValidation doCheckFileInWorkspace(@QueryParameter String value) throws IOException, ServletException {
IvyModuleSetBuild lb = getLastBuild();
if (lb!=null) {
FilePath ws = lb.getModuleRoot();
if(ws!=null)
return ws.validateRelativePath(value,true,true);
}
return FormValidation.ok();
}
/**
* Check that the provided file is a relative path. And check that it exists, just in case.
*/
public FormValidation doCheckFileRelative(@QueryParameter String value) throws IOException, ServletException {
String v = fixEmpty(value);
if ((v == null) || (v.length() == 0)) {
// Null values are allowed.
return FormValidation.ok();
}
if ((v.startsWith("/")) || (v.startsWith("\\")) || (v.matches("^\\w\\:\\\\.*"))) {
return FormValidation.error("Alternate settings file must be a relative path.");
}
IvyModuleSetBuild lb = getLastBuild();
if (lb!=null) {
FilePath ws = lb.getModuleRoot();
if(ws!=null)
return ws.validateRelativePath(value,true,true);
}
return FormValidation.ok();
}
public TopLevelItemDescriptor getDescriptor() {
return DESCRIPTOR;
}
@Extension(ordinal=900)
public static final DescriptorImpl DESCRIPTOR = new DescriptorImpl();
public static final class DescriptorImpl extends AbstractProjectDescriptor {
/**
* Globally-defined ANT_OPTS.
*/
private String globalAntOpts;
public String getGlobalAntOpts() {
return globalAntOpts;
}
public void setGlobalAntOpts(String globalAntOpts) {
this.globalAntOpts = globalAntOpts;
save();
}
@Override
public String getDisplayName() {
return Messages.IvyModuleSet_DiplayName();
}
@Override
public IvyModuleSet newInstance(String name) {
return new IvyModuleSet(name);
}
public Ant.DescriptorImpl getAntDescriptor() {
return Hudson.getInstance().getDescriptorByType(Ant.DescriptorImpl.class);
}
}
}
| true | true | protected void submit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, FormException {
super.submit(req,rsp);
JSONObject json = req.getSubmittedForm();
ignoreUpstreamChanges = !json.has("triggerByDependency");
ivyFilePattern = Util.fixEmptyAndTrim(json.getString("ivyFilePattern"));
ivyFileExcludesPattern = Util.fixEmptyAndTrim(json.getString("ivyFileExcludesPattern"));
targets = Util.fixEmptyAndTrim(json.getString("targets"));
ivyBranch = Util.fixEmptyAndTrim(json.getString("ivyBranch"));
relativePathToDescriptorFromModuleRoot = Util.fixEmptyAndTrim(json.getString("relativePathToDescriptorFromModuleRoot"));
antName = Util.fixEmptyAndTrim(json.getString("antName"));
buildFile = Util.fixEmptyAndTrim(json.getString("buildFile"));
antOpts = Util.fixEmptyAndTrim(json.getString("antOpts"));
antProperties = Util.fixEmptyAndTrim(json.getString("antProperties"));
aggregatorStyleBuild = !req.hasParameter("perModuleBuild");
incrementalBuild = req.hasParameter("incrementalBuild");
if (incrementalBuild)
changedModulesProperty = Util.fixEmptyAndTrim(json.getJSONObject("incrementalBuild").getString("changedModulesProperty"));
publishers.rebuild(req,json,BuildStepDescriptor.filter(Publisher.all(),this.getClass()));
buildWrappers.rebuild(req,json,BuildWrappers.getFor(this));
updateTransientActions(); // to pick up transient actions from builder, publisher, etc.
}
| protected void submit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, FormException {
super.submit(req,rsp);
JSONObject json = req.getSubmittedForm();
ignoreUpstreamChanges = !json.has("triggerByDependency");
ivyFilePattern = Util.fixEmptyAndTrim(json.getString("ivyFilePattern"));
ivyFileExcludesPattern = Util.fixEmptyAndTrim(json.getString("ivyFileExcludesPattern"));
targets = json.getString("targets").trim();
ivyBranch = Util.fixEmptyAndTrim(json.getString("ivyBranch"));
relativePathToDescriptorFromModuleRoot = Util.fixEmptyAndTrim(json.getString("relativePathToDescriptorFromModuleRoot"));
antName = Util.fixEmptyAndTrim(json.getString("antName"));
buildFile = Util.fixEmptyAndTrim(json.getString("buildFile"));
antOpts = Util.fixEmptyAndTrim(json.getString("antOpts"));
antProperties = Util.fixEmptyAndTrim(json.getString("antProperties"));
aggregatorStyleBuild = !req.hasParameter("perModuleBuild");
incrementalBuild = req.hasParameter("incrementalBuild");
if (incrementalBuild)
changedModulesProperty = Util.fixEmptyAndTrim(json.getJSONObject("incrementalBuild").getString("changedModulesProperty"));
publishers.rebuild(req,json,BuildStepDescriptor.filter(Publisher.all(),this.getClass()));
buildWrappers.rebuild(req,json,BuildWrappers.getFor(this));
updateTransientActions(); // to pick up transient actions from builder, publisher, etc.
}
|
diff --git a/src/main/java/de/lemo/dms/processing/questions/QPerformanceHistogram.java b/src/main/java/de/lemo/dms/processing/questions/QPerformanceHistogram.java
index 93cfc6b3..b37c3a99 100644
--- a/src/main/java/de/lemo/dms/processing/questions/QPerformanceHistogram.java
+++ b/src/main/java/de/lemo/dms/processing/questions/QPerformanceHistogram.java
@@ -1,138 +1,137 @@
package de.lemo.dms.processing.questions;
import static de.lemo.dms.processing.MetaParam.COURSE_IDS;
import static de.lemo.dms.processing.MetaParam.END_TIME;
import static de.lemo.dms.processing.MetaParam.START_TIME;
import static de.lemo.dms.processing.MetaParam.USER_IDS;
import static de.lemo.dms.processing.MetaParam.QUIZ_IDS;
import static de.lemo.dms.processing.MetaParam.RESOLUTION;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import de.lemo.dms.core.ServerConfigurationHardCoded;
import de.lemo.dms.db.IDBHandler;
import de.lemo.dms.db.miningDBclass.abstractions.IRatedLogObject;
import de.lemo.dms.db.miningDBclass.abstractions.IRatedObject;
import de.lemo.dms.processing.Question;
import de.lemo.dms.processing.resulttype.ResultListLongObject;
@Path("performanceHistogram")
public class QPerformanceHistogram extends Question{
/**
*
* @param courses (optional) List of course-ids that shall be included
* @param users (optional) List of user-ids
* @param quizzes (mandatory) List of learning object ids (the ids have to start with the type specific prefix (11 for "assignment", 14 for "quiz", 17 for "scorm"))
* @param resolution (mandatory)
* @param startTime (mandatory)
* @param endTime (mandatory)
* @return
*/
@POST
public ResultListLongObject compute(
@FormParam(COURSE_IDS) List<Long> courses,
@FormParam(USER_IDS) List<Long> users,
@FormParam(QUIZ_IDS) List<Long> quizzes,
@FormParam(RESOLUTION) int resolution,
@FormParam(START_TIME) Long startTime,
@FormParam(END_TIME) Long endTime) {
if(courses!=null && courses.size() > 0)
{
System.out.print("Parameter list: Courses: " + courses.get(0));
for(int i = 1; i < courses.size(); i++)
System.out.print(", " + courses.get(i));
System.out.println();
}
if(users!=null && users.size() > 0)
{
System.out.print("Parameter list: Users: " + users.get(0));
for(int i = 1; i < users.size(); i++)
System.out.print(", " + users.get(i));
System.out.println();
}
System.out.println("Parameter list: Resolution: : " + resolution);
System.out.println("Parameter list: Start time: : " + startTime);
System.out.println("Parameter list: End time: : " + endTime);
- if(quizzes == null || quizzes.size() < 1 || quizzes.size() % 2 != 0 || resolution <= 0 || startTime == null || endTime == null)
+ if(quizzes == null || quizzes.size() < 1 || resolution <= 0 || startTime == null || endTime == null)
{
System.out.println("Calculation aborted. At least one of the mandatory parameters is not set properly.");
return new ResultListLongObject();
}
//Determine length of result array
int objects = resolution * quizzes.size();
Long[] results = new Long[objects];
//Initialize result array
for(int i = 0; i < results.length; i++)
results[i] = 0L;
try
{
HashMap<Long, Integer> obj = new HashMap<Long, Integer>();
IDBHandler dbHandler = ServerConfigurationHardCoded.getInstance().getDBHandler();
Session session = dbHandler.getMiningSession();
Criteria criteria;
for(int i = 0; i < quizzes.size(); i++)
{
obj.put(quizzes.get(i), i);
}
criteria = session.createCriteria(IRatedLogObject.class, "log");
criteria.add(Restrictions.between("log.timestamp", startTime, endTime));
if(courses != null && courses.size() > 0)
criteria.add(Restrictions.in("log.course.id", courses));
if(users != null && users.size() > 0)
criteria.add(Restrictions.in("log.user.id", users));
- boolean getAll = (quizzes == null || quizzes.size() == 0);
ArrayList<IRatedLogObject> list = (ArrayList<IRatedLogObject>) criteria.list();
for(IRatedLogObject log : list)
{
- if((getAll || obj.get(Long.valueOf(log.getPrefix() + "" + log.getLearnObjId())) != null ) && log.getFinalgrade() != null &&
+ if(obj.get(Long.valueOf(log.getPrefix() + "" + log.getLearnObjId())) != null && log.getFinalgrade() != null &&
log.getMaxgrade() != null && log.getMaxgrade() > 0)
{
//Determine size of each interval
Double step = log.getMaxgrade() / resolution;
if(step > 0d)
{
//Determine interval for specific grade
int pos = (int) (log.getFinalgrade() / step);
if(pos > resolution - 1)
pos = resolution - 1;
//Increase count of specified interval
results[(resolution * obj.get(Long.valueOf(log.getPrefix() + "" + log.getLearnObjId()))) + pos] = results[(resolution * obj.get(Long.valueOf(log.getPrefix() + "" + log.getLearnObjId()))) + pos] + 1;
}
}
}
}catch(Exception e)
{
e.printStackTrace();
}
return new ResultListLongObject(Arrays.asList(results));
}
}
| false | true | public ResultListLongObject compute(
@FormParam(COURSE_IDS) List<Long> courses,
@FormParam(USER_IDS) List<Long> users,
@FormParam(QUIZ_IDS) List<Long> quizzes,
@FormParam(RESOLUTION) int resolution,
@FormParam(START_TIME) Long startTime,
@FormParam(END_TIME) Long endTime) {
if(courses!=null && courses.size() > 0)
{
System.out.print("Parameter list: Courses: " + courses.get(0));
for(int i = 1; i < courses.size(); i++)
System.out.print(", " + courses.get(i));
System.out.println();
}
if(users!=null && users.size() > 0)
{
System.out.print("Parameter list: Users: " + users.get(0));
for(int i = 1; i < users.size(); i++)
System.out.print(", " + users.get(i));
System.out.println();
}
System.out.println("Parameter list: Resolution: : " + resolution);
System.out.println("Parameter list: Start time: : " + startTime);
System.out.println("Parameter list: End time: : " + endTime);
if(quizzes == null || quizzes.size() < 1 || quizzes.size() % 2 != 0 || resolution <= 0 || startTime == null || endTime == null)
{
System.out.println("Calculation aborted. At least one of the mandatory parameters is not set properly.");
return new ResultListLongObject();
}
//Determine length of result array
int objects = resolution * quizzes.size();
Long[] results = new Long[objects];
//Initialize result array
for(int i = 0; i < results.length; i++)
results[i] = 0L;
try
{
HashMap<Long, Integer> obj = new HashMap<Long, Integer>();
IDBHandler dbHandler = ServerConfigurationHardCoded.getInstance().getDBHandler();
Session session = dbHandler.getMiningSession();
Criteria criteria;
for(int i = 0; i < quizzes.size(); i++)
{
obj.put(quizzes.get(i), i);
}
criteria = session.createCriteria(IRatedLogObject.class, "log");
criteria.add(Restrictions.between("log.timestamp", startTime, endTime));
if(courses != null && courses.size() > 0)
criteria.add(Restrictions.in("log.course.id", courses));
if(users != null && users.size() > 0)
criteria.add(Restrictions.in("log.user.id", users));
boolean getAll = (quizzes == null || quizzes.size() == 0);
ArrayList<IRatedLogObject> list = (ArrayList<IRatedLogObject>) criteria.list();
for(IRatedLogObject log : list)
{
if((getAll || obj.get(Long.valueOf(log.getPrefix() + "" + log.getLearnObjId())) != null ) && log.getFinalgrade() != null &&
log.getMaxgrade() != null && log.getMaxgrade() > 0)
{
//Determine size of each interval
Double step = log.getMaxgrade() / resolution;
if(step > 0d)
{
//Determine interval for specific grade
int pos = (int) (log.getFinalgrade() / step);
if(pos > resolution - 1)
pos = resolution - 1;
//Increase count of specified interval
results[(resolution * obj.get(Long.valueOf(log.getPrefix() + "" + log.getLearnObjId()))) + pos] = results[(resolution * obj.get(Long.valueOf(log.getPrefix() + "" + log.getLearnObjId()))) + pos] + 1;
}
}
}
}catch(Exception e)
{
e.printStackTrace();
}
return new ResultListLongObject(Arrays.asList(results));
}
| public ResultListLongObject compute(
@FormParam(COURSE_IDS) List<Long> courses,
@FormParam(USER_IDS) List<Long> users,
@FormParam(QUIZ_IDS) List<Long> quizzes,
@FormParam(RESOLUTION) int resolution,
@FormParam(START_TIME) Long startTime,
@FormParam(END_TIME) Long endTime) {
if(courses!=null && courses.size() > 0)
{
System.out.print("Parameter list: Courses: " + courses.get(0));
for(int i = 1; i < courses.size(); i++)
System.out.print(", " + courses.get(i));
System.out.println();
}
if(users!=null && users.size() > 0)
{
System.out.print("Parameter list: Users: " + users.get(0));
for(int i = 1; i < users.size(); i++)
System.out.print(", " + users.get(i));
System.out.println();
}
System.out.println("Parameter list: Resolution: : " + resolution);
System.out.println("Parameter list: Start time: : " + startTime);
System.out.println("Parameter list: End time: : " + endTime);
if(quizzes == null || quizzes.size() < 1 || resolution <= 0 || startTime == null || endTime == null)
{
System.out.println("Calculation aborted. At least one of the mandatory parameters is not set properly.");
return new ResultListLongObject();
}
//Determine length of result array
int objects = resolution * quizzes.size();
Long[] results = new Long[objects];
//Initialize result array
for(int i = 0; i < results.length; i++)
results[i] = 0L;
try
{
HashMap<Long, Integer> obj = new HashMap<Long, Integer>();
IDBHandler dbHandler = ServerConfigurationHardCoded.getInstance().getDBHandler();
Session session = dbHandler.getMiningSession();
Criteria criteria;
for(int i = 0; i < quizzes.size(); i++)
{
obj.put(quizzes.get(i), i);
}
criteria = session.createCriteria(IRatedLogObject.class, "log");
criteria.add(Restrictions.between("log.timestamp", startTime, endTime));
if(courses != null && courses.size() > 0)
criteria.add(Restrictions.in("log.course.id", courses));
if(users != null && users.size() > 0)
criteria.add(Restrictions.in("log.user.id", users));
ArrayList<IRatedLogObject> list = (ArrayList<IRatedLogObject>) criteria.list();
for(IRatedLogObject log : list)
{
if(obj.get(Long.valueOf(log.getPrefix() + "" + log.getLearnObjId())) != null && log.getFinalgrade() != null &&
log.getMaxgrade() != null && log.getMaxgrade() > 0)
{
//Determine size of each interval
Double step = log.getMaxgrade() / resolution;
if(step > 0d)
{
//Determine interval for specific grade
int pos = (int) (log.getFinalgrade() / step);
if(pos > resolution - 1)
pos = resolution - 1;
//Increase count of specified interval
results[(resolution * obj.get(Long.valueOf(log.getPrefix() + "" + log.getLearnObjId()))) + pos] = results[(resolution * obj.get(Long.valueOf(log.getPrefix() + "" + log.getLearnObjId()))) + pos] + 1;
}
}
}
}catch(Exception e)
{
e.printStackTrace();
}
return new ResultListLongObject(Arrays.asList(results));
}
|
diff --git a/src/org/openstreetmap/josm/gui/layer/markerlayer/Marker.java b/src/org/openstreetmap/josm/gui/layer/markerlayer/Marker.java
index d6493443..617c32cd 100644
--- a/src/org/openstreetmap/josm/gui/layer/markerlayer/Marker.java
+++ b/src/org/openstreetmap/josm/gui/layer/markerlayer/Marker.java
@@ -1,217 +1,217 @@
// License: GPL. Copyright 2008 by Immanuel Scholz and others
package org.openstreetmap.josm.gui.layer.markerlayer;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import javax.swing.Icon;
import org.openstreetmap.josm.Main;
import org.openstreetmap.josm.data.coor.EastNorth;
import org.openstreetmap.josm.data.coor.LatLon;
import org.openstreetmap.josm.data.gpx.GpxLink;
import org.openstreetmap.josm.data.gpx.WayPoint;
import org.openstreetmap.josm.gui.MapView;
import org.openstreetmap.josm.gui.layer.Layer;
import org.openstreetmap.josm.tools.ImageProvider;
/**
* Basic marker class. Requires a position, and supports
* a custom icon and a name.
*
* This class is also used to create appropriate Marker-type objects
* when waypoints are imported.
*
* It hosts a public list object, named makers, containing implementations of
* the MarkerMaker interface. Whenever a Marker needs to be created, each
* object in makers is called with the waypoint parameters (Lat/Lon and tag
* data), and the first one to return a Marker object wins.
*
* By default, one the list contains one default "Maker" implementation that
* will create AudioMarkers for .wav files, ImageMarkers for .png/.jpg/.jpeg
* files, and WebMarkers for everything else. (The creation of a WebMarker will
* fail if there's no vaild URL in the <link> tag, so it might still make sense
* to add Makers for such waypoints at the end of the list.)
*
* The default implementation only looks at the value of the <link> tag inside
* the <wpt> tag of the GPX file.
*
* <h2>HowTo implement a new Marker</h2>
* <ul>
* <li> Subclass Marker or ButtonMarker and override <code>containsPoint</code>
* if you like to respond to user clicks</li>
* <li> Override paint, if you want a custom marker look (not "a label and a symbol")</li>
* <li> Implement MarkerCreator to return a new instance of your marker class</li>
* <li> In you plugin constructor, add an instance of your MarkerCreator
* implementation either on top or bottom of Marker.markerProducers.
* Add at top, if your marker should overwrite an current marker or at bottom
* if you only add a new marker style.</li>
* </ul>
*
* @author Frederik Ramm <[email protected]>
*/
public class Marker implements ActionListener {
public EastNorth eastNorth;
public final String text;
public final Icon symbol;
public final MarkerLayer parentLayer;
public double time; /* avbsolute time of marker since epocj */
public double offset; /* time offset in seconds from the gpx point from which it was derived,
may be adjusted later to sync with other data, so not final */
/**
* Plugins can add their Marker creation stuff at the bottom or top of this list
* (depending on whether they want to override default behaviour or just add new
* stuff).
*/
public static LinkedList<MarkerProducers> markerProducers = new LinkedList<MarkerProducers>();
// Add one Maker specifying the default behaviour.
static {
Marker.markerProducers.add(new MarkerProducers() {
public Marker createMarker(WayPoint wpt, File relativePath) {
return createMarker(wpt, relativePath, null, 0.0, 0.0);
}
public Marker createMarker(WayPoint wpt, File relativePath, MarkerLayer parentLayer, double time, double offset) {
String uri = null;
// cheapest way to check whether "link" object exists and is a non-empty
// collection of GpxLink objects...
try {
for (GpxLink oneLink : (Collection<GpxLink>) wpt.attr.get("link")) {
uri = oneLink.uri;
break;
}
} catch (Exception ex) {};
// Try a relative file:// url, if the link is not in an URL-compatible form
if (relativePath != null && uri != null && !isWellFormedAddress(uri))
- uri = new File(relativePath, uri).toURI().toString();
+ uri = new File(relativePath.getParentFile(), uri).toURI().toString();
String name_desc = "";
if (wpt.attr.containsKey("name")) {
name_desc = wpt.getString("name");
} else if (wpt.attr.containsKey("desc")) {
name_desc = wpt.getString("desc");
}
if (uri == null)
return new Marker(wpt.latlon, name_desc, wpt.getString("symbol"), parentLayer, time, offset);
else if (uri.endsWith(".wav"))
return AudioMarker.create(wpt.latlon, name_desc, uri, parentLayer, time, offset);
else if (uri.endsWith(".png") || uri.endsWith(".jpg") || uri.endsWith(".jpeg") || uri.endsWith(".gif"))
return ImageMarker.create(wpt.latlon, uri, parentLayer, time, offset);
else
return WebMarker.create(wpt.latlon, uri, parentLayer, time, offset);
}
private boolean isWellFormedAddress(String link) {
try {
new URL(link);
return true;
} catch (MalformedURLException x) {
return false;
}
}
});
}
public Marker(LatLon ll, String text, String iconName, MarkerLayer parentLayer, double time, double offset) {
eastNorth = Main.proj.latlon2eastNorth(ll);
this.text = text;
this.offset = offset;
this.time = time;
Icon symbol = ImageProvider.getIfAvailable("markers",iconName);
if (symbol == null)
symbol = ImageProvider.getIfAvailable("symbols",iconName);
if (symbol == null)
symbol = ImageProvider.getIfAvailable("nodes",iconName);
this.symbol = symbol;
this.parentLayer = parentLayer;
}
/**
* Checks whether the marker display area contains the given point.
* Markers not interested in mouse clicks may always return false.
*
* @param p The point to check
* @return <code>true</code> if the marker "hotspot" contains the point.
*/
public boolean containsPoint(Point p) {
return false;
}
/**
* Called when the mouse is clicked in the marker's hotspot. Never
* called for markers which always return false from containsPoint.
*
* @param ev A dummy ActionEvent
*/
public void actionPerformed(ActionEvent ev) {
}
/**
* Paints the marker.
* @param g graphics context
* @param mv map view
* @param mousePressed true if the left mouse button is pressed
*/
public void paint(Graphics g, MapView mv, boolean mousePressed, String show) {
Point screen = mv.getPoint(eastNorth);
if (symbol != null && show.equalsIgnoreCase("show")) {
symbol.paintIcon(mv, g, screen.x-symbol.getIconWidth()/2, screen.y-symbol.getIconHeight()/2);
} else {
g.drawLine(screen.x-2, screen.y-2, screen.x+2, screen.y+2);
g.drawLine(screen.x+2, screen.y-2, screen.x-2, screen.y+2);
}
if ((text != null) && (show.equalsIgnoreCase("show")))
g.drawString(text, screen.x+4, screen.y+2);
}
/**
* Returns an object of class Marker or one of its subclasses
* created from the parameters given.
*
* @param ll lat/lon for marker
* @param data hash containing keys and values from the GPX waypoint structure
* @param relativePath An path to use for constructing relative URLs or
* <code>null</code> for no relative URLs
* @param offset double in seconds as the time offset of this marker from
* the GPX file from which it was derived (if any).
* @return a new Marker object
*/
public static Marker createMarker(WayPoint wpt, File relativePath, MarkerLayer parentLayer, double time, double offset) {
for (MarkerProducers maker : Marker.markerProducers) {
Marker marker = maker.createMarker(wpt, relativePath, parentLayer, time, offset);
if (marker != null)
return marker;
}
return null;
}
/**
* Returns an AudioMarker derived from this Marker and the provided uri
* Subclasses of specific marker types override this to return null as they can't
* be turned into AudioMarkers. This includes AudioMarkers themselves, as they
* already have audio.
*
* @param uri uri of wave file
* @return AudioMarker
*/
public AudioMarker audioMarkerFromMarker(String uri) {
AudioMarker audioMarker = AudioMarker.create(Main.proj.eastNorth2latlon(this.eastNorth), this.text, uri, this.parentLayer, this.time, this.offset);
return audioMarker;
}
}
| true | true | public Marker createMarker(WayPoint wpt, File relativePath, MarkerLayer parentLayer, double time, double offset) {
String uri = null;
// cheapest way to check whether "link" object exists and is a non-empty
// collection of GpxLink objects...
try {
for (GpxLink oneLink : (Collection<GpxLink>) wpt.attr.get("link")) {
uri = oneLink.uri;
break;
}
} catch (Exception ex) {};
// Try a relative file:// url, if the link is not in an URL-compatible form
if (relativePath != null && uri != null && !isWellFormedAddress(uri))
uri = new File(relativePath, uri).toURI().toString();
String name_desc = "";
if (wpt.attr.containsKey("name")) {
name_desc = wpt.getString("name");
} else if (wpt.attr.containsKey("desc")) {
name_desc = wpt.getString("desc");
}
if (uri == null)
return new Marker(wpt.latlon, name_desc, wpt.getString("symbol"), parentLayer, time, offset);
else if (uri.endsWith(".wav"))
return AudioMarker.create(wpt.latlon, name_desc, uri, parentLayer, time, offset);
else if (uri.endsWith(".png") || uri.endsWith(".jpg") || uri.endsWith(".jpeg") || uri.endsWith(".gif"))
return ImageMarker.create(wpt.latlon, uri, parentLayer, time, offset);
else
return WebMarker.create(wpt.latlon, uri, parentLayer, time, offset);
}
| public Marker createMarker(WayPoint wpt, File relativePath, MarkerLayer parentLayer, double time, double offset) {
String uri = null;
// cheapest way to check whether "link" object exists and is a non-empty
// collection of GpxLink objects...
try {
for (GpxLink oneLink : (Collection<GpxLink>) wpt.attr.get("link")) {
uri = oneLink.uri;
break;
}
} catch (Exception ex) {};
// Try a relative file:// url, if the link is not in an URL-compatible form
if (relativePath != null && uri != null && !isWellFormedAddress(uri))
uri = new File(relativePath.getParentFile(), uri).toURI().toString();
String name_desc = "";
if (wpt.attr.containsKey("name")) {
name_desc = wpt.getString("name");
} else if (wpt.attr.containsKey("desc")) {
name_desc = wpt.getString("desc");
}
if (uri == null)
return new Marker(wpt.latlon, name_desc, wpt.getString("symbol"), parentLayer, time, offset);
else if (uri.endsWith(".wav"))
return AudioMarker.create(wpt.latlon, name_desc, uri, parentLayer, time, offset);
else if (uri.endsWith(".png") || uri.endsWith(".jpg") || uri.endsWith(".jpeg") || uri.endsWith(".gif"))
return ImageMarker.create(wpt.latlon, uri, parentLayer, time, offset);
else
return WebMarker.create(wpt.latlon, uri, parentLayer, time, offset);
}
|
diff --git a/src/ca/uwaterloo/joos/weeder/IntegerChecker.java b/src/ca/uwaterloo/joos/weeder/IntegerChecker.java
index c2b9f63..01abd07 100644
--- a/src/ca/uwaterloo/joos/weeder/IntegerChecker.java
+++ b/src/ca/uwaterloo/joos/weeder/IntegerChecker.java
@@ -1,56 +1,59 @@
/**
*
*/
package ca.uwaterloo.joos.weeder;
import ca.uwaterloo.joos.ast.ASTNode;
import ca.uwaterloo.joos.ast.expr.primary.LiteralPrimary;
import ca.uwaterloo.joos.ast.visitor.IntegerVisitor;
/**
* @author wenzhuman
*
*/
public class IntegerChecker extends IntegerVisitor {
/**
* @throws Exception
*
*/
@Override
public void willVisit(ASTNode node) {
}
@Override
public void didVisit(ASTNode node) {
}
@Override
protected void visitInteger(LiteralPrimary node) throws Exception {
String intPositiveThreshold = "2147483647";
String intNegThreshold = "2147483648";
if (node.getParent().getClass().getSimpleName().equals("UnaryExpression")) {
checkIntRange(node.getValue(), intNegThreshold);
} else {
checkIntRange(node.getValue(), intPositiveThreshold);
}
}
private void checkIntRange(String intString, String intergerThreshold) throws Exception {
if (intString.length() == intergerThreshold.length()) {
for (int i = 0; i < intergerThreshold.length(); i++) {
if ((int) intString.charAt(i) > (int) intergerThreshold.charAt(i)) {
- throw new Exception("Interger out of Range");
+ throw new Exception(intString + "AT" + i + "1:Interger out of Range");
+ }
+ if ((int) intString.charAt(i) < (int) intergerThreshold.charAt(i)) {
+ break;
}
}
}
if (intString.length() > intergerThreshold.length()) {
- throw new Exception("Interger out of Range");
+ throw new Exception("2:Interger out of Range");
}
}
}
| false | true | private void checkIntRange(String intString, String intergerThreshold) throws Exception {
if (intString.length() == intergerThreshold.length()) {
for (int i = 0; i < intergerThreshold.length(); i++) {
if ((int) intString.charAt(i) > (int) intergerThreshold.charAt(i)) {
throw new Exception("Interger out of Range");
}
}
}
if (intString.length() > intergerThreshold.length()) {
throw new Exception("Interger out of Range");
}
}
| private void checkIntRange(String intString, String intergerThreshold) throws Exception {
if (intString.length() == intergerThreshold.length()) {
for (int i = 0; i < intergerThreshold.length(); i++) {
if ((int) intString.charAt(i) > (int) intergerThreshold.charAt(i)) {
throw new Exception(intString + "AT" + i + "1:Interger out of Range");
}
if ((int) intString.charAt(i) < (int) intergerThreshold.charAt(i)) {
break;
}
}
}
if (intString.length() > intergerThreshold.length()) {
throw new Exception("2:Interger out of Range");
}
}
|
diff --git a/src/org/ojim/client/ai/valuation/Valuator.java b/src/org/ojim/client/ai/valuation/Valuator.java
index e37534b..df72465 100644
--- a/src/org/ojim/client/ai/valuation/Valuator.java
+++ b/src/org/ojim/client/ai/valuation/Valuator.java
@@ -1,411 +1,412 @@
/* Copyright (C) 2010 - 2011 Fabian Neundorf, Philip Caroli,
* Maximilian Madlung, Usman Ghani Ahmed, Jeremias Mechler
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ojim.client.ai.valuation;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.ojim.client.SimpleClient;
import org.ojim.client.ai.commands.AcceptCommand;
import org.ojim.client.ai.commands.AuctionBidCommand;
import org.ojim.client.ai.commands.BuildHouseCommand;
import org.ojim.client.ai.commands.Command;
import org.ojim.client.ai.commands.DeclineCommand;
import org.ojim.client.ai.commands.EndTurnCommand;
import org.ojim.client.ai.commands.NullCommand;
import org.ojim.client.ai.commands.OutOfPrisonCommand;
import org.ojim.client.ai.commands.SellCommand;
import org.ojim.log.OJIMLogger;
import org.ojim.logic.Logic;
import org.ojim.logic.state.Player;
import org.ojim.logic.state.fields.BuyableField;
import org.ojim.logic.state.fields.Field;
import org.ojim.logic.state.fields.Jail;
import org.ojim.logic.state.fields.Street;
import org.ojim.logic.state.fields.StreetFieldGroup;
import edu.kit.iti.pse.iface.IServer;
/**
* Valuator - returns the best command
*
* @author Jeremias Mechler
*
*/
public class Valuator extends SimpleClient {
private double[] weights;
private ValuationFunction[] valuationFunctions;
private Logic logic;
private int playerID;
private IServer server;
private Logger logger;
private int auctionBid;
// private PriorityQueue<Property> properties;
private int auctionSteps = 11;
private int currentStep = 2;
// private LinkedList<Property> list;
private int[] toSell;
private boolean endTurn = false;
/**
* Constructor
*
* @param state
* reference to state
* @param logic
* reference to logic
* @param server
* reference to server
* @param playerID
* The player's ID
*/
public Valuator(Logic logic, IServer server, int playerID) {
super(logic, playerID, server);
assert (logic != null);
assert (server != null);
this.logic = logic;
this.server = server;
this.playerID = playerID;
weights = new double[ValuationFunction.COUNT];
for (int i = 0; i < weights.length; i++) {
weights[i] = 1;
}
weights[0] = 100000;
this.logger = OJIMLogger.getLogger(this.getClass().toString());
valuationFunctions = new ValuationFunction[6];
valuationFunctions[0] = CapitalValuator.getInstance();
valuationFunctions[1] = PropertyValuator.getInstance();
valuationFunctions[2] = PrisonValuator.getInstance();
valuationFunctions[3] = MortgageValuator.getInstance();
valuationFunctions[4] = PropertyGroupValuator.getInstance();
valuationFunctions[5] = BuildingOnPropertyValuator.getInstance();
for (int i = 0; i < ValuationFunction.COUNT; i++) {
assert (valuationFunctions[i] != null);
}
ValuationParameters.init(logic);
}
/**
* Returns the best command
*
* @param position
* current position
* @return command
*/
public Command returnBestCommand(int position) {
assert(this.getNumberOfGetOutOfJailCards(playerID) == 0);
assert (position >= 0);
Field field = getGameState().getFieldAt(Math.abs(position));
for (ValuationFunction function : valuationFunctions) {
assert (function != null);
function.setParameters(logic);
function.setServer(server);
}
// OJIMLogger.changeGlobalLevel(Level.WARNING);
// OJIMLogger.changeLogLevel(logger, Level.FINE);
// Feld potenziell kaufbar
if (field instanceof BuyableField && !endTurn) {
logger.log(Level.FINE, "BuyableField!");
Player owner = ((BuyableField) field).getOwner();
double realValue = getResults(position, 0);
// Feld gehört mir (noch) nicht
if (owner != getMe()) {
int price = ((BuyableField) field).getPrice();
double valuation = getResults(position, price);
// double realValue = getResults(position, 0);
// Feld gehört der Bank
if (owner == null) {
if (valuation > 0) {
logger.log(Level.FINE, "Granted");
assert (logic != null);
assert (server != null);
logger.log(Level.FINE, "Accept");
return new AcceptCommand(logic, server, playerID);
// nicht ausreichend, ab wann verkaufen oder handeln?
} else if (realValue > 0 && false) {
// preis?
// getPropertiesToSell();
// sell();
// return new DeclineCommand(logic, server, playerID);
} else {
// Ablehnen
logger.log(Level.FINE, "Decline");
endTurn = true;
return new DeclineCommand(logic, server, playerID);
}
} else {
// Trade!
logger.log(Level.FINE, "Soon trade");
// return new NullCommand(logic, server, playerID);
}
}
// Feld potentiell bebaubar
if (field instanceof Street) {
Street street = (Street) field;
// Feld bebaubar
// if (allOfGroupOwned(street)) {
// assert(false);
// }
if (allOfGroupOwned(street) && this.getNumberOfHousesLeft() > 0) {
logger.log(Level.FINE, "Owning everything in group " + street.getColorGroup());
// assert(false);
double valuation = getResults(position, this.getEstateHousePrice(street.getPosition()));
// houses, hotels, real price?
// if (valuation > 0) {
if (true) {
// int oldLevel = street.getNumberOfHouse();
System.out.println(this.getEstateHouses(street.getPosition()));
System.out.println(this.getNumberOfHousesLeft());
// construct(street);
// this.
// street.upgrade(street.getNumberOfHouse() + 1);
// assert (street.getNumberOfHouse() == oldLevel + 1);
if (this.getEstateHouses(street.getPosition()) == 1) {
assert (false);
logger.log(Level.FINE, "All houses owned on " + street.getPosition());
}
// assert(false);
+ endTurn = true;
return new BuildHouseCommand(logic, server, playerID, street);
// assert(false);
} else {
// assert(false);
}
}
}
}
// reicht das?
else if (field instanceof Jail) {
double valuation = getResults(position, 0);
// To be tested!
if (valuation > 0 && position == -10) {
return new OutOfPrisonCommand(logic, server, playerID);
} else {
// null command?
System.out.println(valuation);
// assert (false);
endTurn = false;
return new EndTurnCommand(logic, server, playerID);
}
}
endTurn = false;
return new EndTurnCommand(logic, server, playerID);
}
/**
*
* @return
*/
public Command actOnTradeOffer() {
System.out.println("Trade!");
assert (getTradeState() == 1);
boolean restricted = false;
if (getRequiredEstates() != null) {
for (int position : getRequiredEstates()) {
BuyableField field = (BuyableField) getGameState().getFieldAt(position);
if (field.isMortgaged()) {
restricted = true;
}
if (field instanceof Street && ((Street) field).getBuiltLevel() > 0) {
restricted = false;
}
}
}
if (!restricted) {
double value = getOfferedCash();
double minus = tradeValuateRequestedEstates();
value += tradeValuateJailCards();
value += tradeValuateOfferedEstates();
minus += valuationFunctions[0].returnValuation(this.getRequiredCash());
// missing: out of jail cards!
if (value + minus > 0) {
return new AcceptCommand(logic, server, playerID);
}
}
return new DeclineCommand(logic, server, playerID);
}
public Command actOnAuction() {
int auctionState = getAuctionState();
assert (auctionState >= 0);
int realValue = (int) getResults(getAuctionedEstate(), 0);
getAuctionState();
getBidder();
getHighestBid();
logger.log(Level.FINE, "state = " + getAuctionState() + " bidder = " + getBidder() + " highesBid = " + getHighestBid() + " value = " + realValue);
if ((auctionState = getAuctionState()) < 3 && getBidder() != playerID && getHighestBid() < realValue
&& currentStep < auctionSteps) {
logger.log(Level.FINE, "Highest bid = " + getHighestBid());
if (getHighestBid() < realValue) {
logger.log(Level.FINE, "Valuation " + realValue);
double factor = Math.log(currentStep++)/Math.log(auctionSteps);
auctionBid = (int)(factor * realValue);
logger.log(Level.FINE, "Bidding " + auctionBid);
if (getResults(getAuctionedEstate(), auctionBid) > 0) {
System.out.println("THere!");
// assert(false);
return new AuctionBidCommand(logic, server, playerID, auctionBid);
} else {
assert (false);
}
}
}
if (getAuctionState() == 3) {
currentStep = 2;
}
return new NullCommand(logic, server, playerID);
}
private double getResults(int position, int amount) {
double result = weights[0] * valuationFunctions[0].returnValuation(amount);
for (int i = 1; i < valuationFunctions.length; i++) {
result += weights[i] * valuationFunctions[i].returnValuation(position);
}
return result;
}
private double tradeValuateJailCards() {
int offeredCards = getNumberOfOfferedGetOutOfJailCards();
int difference = ValuationParameters.desiredNumberOfOutOfOjailCards - getNumberOfGetOutOfJailCards(playerID);
if (difference > 0) {
if (offeredCards >= difference) {
return ((Jail) getGameState().getFieldAt(10)).getMoneyToPay() * difference;
} else {
return ((Jail) getGameState().getFieldAt(10)).getMoneyToPay() * offeredCards;
}
} else {
return 0;
}
}
private double tradeValuateEstates(int[] estates) {
double result = 0;
for (int estate : estates) {
result += getResults(estate, 0);
}
return result;
}
private double tradeValuateRequestedEstates() {
return (-1) * tradeValuateEstates(getRequiredEstates());
}
private double tradeValuateOfferedEstates() {
return tradeValuateEstates(getOfferedEstates());
}
private boolean decideWhetherToSell(int buyPosition, int sellPosition) {
return (getResults(buyPosition, 0) > getResults(sellPosition, 0));
}
private void getPropertiesToSell(int requiredCash, boolean mortgage) {
int cash = 0;
ArrayList<BuyableField> list = new ArrayList<BuyableField>();
PriorityQueue<BuyableField> queue = getMe().getQueue();
// TODO better condition?
while (cash < requiredCash && !queue.isEmpty()) {
BuyableField temp = queue.poll();
cash += temp.getPrice() / 2;
list.add(temp);
revaluate(queue);
}
int[] result = new int[list.size()];
int i = 0;
for (BuyableField field : list) {
result[i++] = field.getPosition();
}
toSell = result;
}
// beim Hinzufügen alle neu validieren?
private void revaluate(PriorityQueue<BuyableField> queue) {
BuyableField[] fields = new BuyableField[queue.size()];
int i = 0;
while (!queue.isEmpty()) {
BuyableField field = queue.poll();
field.setValuation(getResults(field.getPosition(), 0));
fields[i++] = field;
}
for (BuyableField field : fields) {
queue.add(field);
}
assert (queue.size() == fields.length);
}
private void sell(int requiredCash) {
int initialCash = getLogic().getGameState().getActivePlayer().getBalance();
int newCash = 0;
// Property[] toBeSold = new Property[list.size()];
// toBeSold = list.toArray(new Property[0]);
// Iterator-Zugriffsfehler?
for (BuyableField field : this.getMe().getQueue()) {
if (newCash < requiredCash) {
int faceValue = field.getPrice();
new SellCommand(logic, server, playerID, field.getPosition(), (int) Math.max(faceValue,
field.getValuation()), faceValue / 2).execute();
newCash = logic.getGameState().getActivePlayer().getBalance() - initialCash;
assert (newCash != initialCash);
// property = null; // field.setSelected(true);
} else {
field.setSelected(false);
}
}
revaluate(getMe().getQueue());
}
private int getPrice(int position) {
Field field = logic.getGameState().getFieldAt(position);
assert (field instanceof BuyableField);
return ((BuyableField) field).getPrice();
}
private boolean allOfGroupOwned(Street street) {
StreetFieldGroup group = street.getFieldGroup();
if (group.getFields().length > 1) {
int count = 0;
for (Field field : group.getFields()) {
if (((BuyableField) field).getOwner() == getMe()) {
count++;
}
}
return (count == group.getFields().length);
} else {
System.out.println(street.getFieldGroup().getName());
return false;
}
}
// private boolean
}
| true | true | public Command returnBestCommand(int position) {
assert(this.getNumberOfGetOutOfJailCards(playerID) == 0);
assert (position >= 0);
Field field = getGameState().getFieldAt(Math.abs(position));
for (ValuationFunction function : valuationFunctions) {
assert (function != null);
function.setParameters(logic);
function.setServer(server);
}
// OJIMLogger.changeGlobalLevel(Level.WARNING);
// OJIMLogger.changeLogLevel(logger, Level.FINE);
// Feld potenziell kaufbar
if (field instanceof BuyableField && !endTurn) {
logger.log(Level.FINE, "BuyableField!");
Player owner = ((BuyableField) field).getOwner();
double realValue = getResults(position, 0);
// Feld gehört mir (noch) nicht
if (owner != getMe()) {
int price = ((BuyableField) field).getPrice();
double valuation = getResults(position, price);
// double realValue = getResults(position, 0);
// Feld gehört der Bank
if (owner == null) {
if (valuation > 0) {
logger.log(Level.FINE, "Granted");
assert (logic != null);
assert (server != null);
logger.log(Level.FINE, "Accept");
return new AcceptCommand(logic, server, playerID);
// nicht ausreichend, ab wann verkaufen oder handeln?
} else if (realValue > 0 && false) {
// preis?
// getPropertiesToSell();
// sell();
// return new DeclineCommand(logic, server, playerID);
} else {
// Ablehnen
logger.log(Level.FINE, "Decline");
endTurn = true;
return new DeclineCommand(logic, server, playerID);
}
} else {
// Trade!
logger.log(Level.FINE, "Soon trade");
// return new NullCommand(logic, server, playerID);
}
}
// Feld potentiell bebaubar
if (field instanceof Street) {
Street street = (Street) field;
// Feld bebaubar
// if (allOfGroupOwned(street)) {
// assert(false);
// }
if (allOfGroupOwned(street) && this.getNumberOfHousesLeft() > 0) {
logger.log(Level.FINE, "Owning everything in group " + street.getColorGroup());
// assert(false);
double valuation = getResults(position, this.getEstateHousePrice(street.getPosition()));
// houses, hotels, real price?
// if (valuation > 0) {
if (true) {
// int oldLevel = street.getNumberOfHouse();
System.out.println(this.getEstateHouses(street.getPosition()));
System.out.println(this.getNumberOfHousesLeft());
// construct(street);
// this.
// street.upgrade(street.getNumberOfHouse() + 1);
// assert (street.getNumberOfHouse() == oldLevel + 1);
if (this.getEstateHouses(street.getPosition()) == 1) {
assert (false);
logger.log(Level.FINE, "All houses owned on " + street.getPosition());
}
// assert(false);
return new BuildHouseCommand(logic, server, playerID, street);
// assert(false);
} else {
// assert(false);
}
}
}
}
// reicht das?
else if (field instanceof Jail) {
double valuation = getResults(position, 0);
// To be tested!
if (valuation > 0 && position == -10) {
return new OutOfPrisonCommand(logic, server, playerID);
} else {
// null command?
System.out.println(valuation);
// assert (false);
endTurn = false;
return new EndTurnCommand(logic, server, playerID);
}
}
endTurn = false;
return new EndTurnCommand(logic, server, playerID);
}
| public Command returnBestCommand(int position) {
assert(this.getNumberOfGetOutOfJailCards(playerID) == 0);
assert (position >= 0);
Field field = getGameState().getFieldAt(Math.abs(position));
for (ValuationFunction function : valuationFunctions) {
assert (function != null);
function.setParameters(logic);
function.setServer(server);
}
// OJIMLogger.changeGlobalLevel(Level.WARNING);
// OJIMLogger.changeLogLevel(logger, Level.FINE);
// Feld potenziell kaufbar
if (field instanceof BuyableField && !endTurn) {
logger.log(Level.FINE, "BuyableField!");
Player owner = ((BuyableField) field).getOwner();
double realValue = getResults(position, 0);
// Feld gehört mir (noch) nicht
if (owner != getMe()) {
int price = ((BuyableField) field).getPrice();
double valuation = getResults(position, price);
// double realValue = getResults(position, 0);
// Feld gehört der Bank
if (owner == null) {
if (valuation > 0) {
logger.log(Level.FINE, "Granted");
assert (logic != null);
assert (server != null);
logger.log(Level.FINE, "Accept");
return new AcceptCommand(logic, server, playerID);
// nicht ausreichend, ab wann verkaufen oder handeln?
} else if (realValue > 0 && false) {
// preis?
// getPropertiesToSell();
// sell();
// return new DeclineCommand(logic, server, playerID);
} else {
// Ablehnen
logger.log(Level.FINE, "Decline");
endTurn = true;
return new DeclineCommand(logic, server, playerID);
}
} else {
// Trade!
logger.log(Level.FINE, "Soon trade");
// return new NullCommand(logic, server, playerID);
}
}
// Feld potentiell bebaubar
if (field instanceof Street) {
Street street = (Street) field;
// Feld bebaubar
// if (allOfGroupOwned(street)) {
// assert(false);
// }
if (allOfGroupOwned(street) && this.getNumberOfHousesLeft() > 0) {
logger.log(Level.FINE, "Owning everything in group " + street.getColorGroup());
// assert(false);
double valuation = getResults(position, this.getEstateHousePrice(street.getPosition()));
// houses, hotels, real price?
// if (valuation > 0) {
if (true) {
// int oldLevel = street.getNumberOfHouse();
System.out.println(this.getEstateHouses(street.getPosition()));
System.out.println(this.getNumberOfHousesLeft());
// construct(street);
// this.
// street.upgrade(street.getNumberOfHouse() + 1);
// assert (street.getNumberOfHouse() == oldLevel + 1);
if (this.getEstateHouses(street.getPosition()) == 1) {
assert (false);
logger.log(Level.FINE, "All houses owned on " + street.getPosition());
}
// assert(false);
endTurn = true;
return new BuildHouseCommand(logic, server, playerID, street);
// assert(false);
} else {
// assert(false);
}
}
}
}
// reicht das?
else if (field instanceof Jail) {
double valuation = getResults(position, 0);
// To be tested!
if (valuation > 0 && position == -10) {
return new OutOfPrisonCommand(logic, server, playerID);
} else {
// null command?
System.out.println(valuation);
// assert (false);
endTurn = false;
return new EndTurnCommand(logic, server, playerID);
}
}
endTurn = false;
return new EndTurnCommand(logic, server, playerID);
}
|
diff --git a/editor/tools/plugins/com.google.dart.tools.core/src/com/google/dart/tools/core/refresh/DartPackagesFolderMatcher.java b/editor/tools/plugins/com.google.dart.tools.core/src/com/google/dart/tools/core/refresh/DartPackagesFolderMatcher.java
index 1228cd15..46d6de62 100644
--- a/editor/tools/plugins/com.google.dart.tools.core/src/com/google/dart/tools/core/refresh/DartPackagesFolderMatcher.java
+++ b/editor/tools/plugins/com.google.dart.tools.core/src/com/google/dart/tools/core/refresh/DartPackagesFolderMatcher.java
@@ -1,90 +1,93 @@
/*
* Copyright 2012 Dart project authors.
*
* Licensed under the Eclipse License v1.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.eclipse.org/legal/epl-v10.html
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.dart.tools.core.refresh;
import com.google.dart.tools.core.DartCore;
import com.google.dart.tools.core.utilities.io.FileUtilities;
import org.eclipse.core.filesystem.IFileInfo;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.filtermatchers.AbstractFileInfoMatcher;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
/**
* Filter out the children of symlinked 'packages' directories. This does not filter the main
* 'packages' directory.
*/
public class DartPackagesFolderMatcher extends AbstractFileInfoMatcher {
public static final String MATCHER_ID = "com.google.dart.tools.core.packagesFolderMatcher";
public DartPackagesFolderMatcher() {
}
@Override
public void initialize(IProject project, Object arguments) throws CoreException {
}
@Override
public boolean matches(IContainer parent, IFileInfo fileInfo) throws CoreException {
- // suppress self link
+ // suppress self link - test for self link only in pacakges that is next to pubspec.yaml
// TODO(keertip): this does not work on Windows, replace it.
- if (!DartCore.isWindows() && parent.getParent() != null
- && parent.getParent().getName().equals(DartCore.PACKAGES_DIRECTORY_NAME)) {
- if (DartCore.isSelfLinkedResource(parent.getProject(), parent)) {
- return true;
+ if (!DartCore.isWindows() && parent.getParent() != null) {
+ IContainer gparent = parent.getParent();
+ if (gparent.getName().equals(DartCore.PACKAGES_DIRECTORY_NAME) && gparent.getParent() != null) {
+ IContainer appDir = gparent.getParent();
+ if (appDir.findMember(DartCore.PUBSPEC_FILE_NAME) != null) {
+ if (DartCore.isSelfLinkedResource(parent.getProject(), parent)) {
+ return true;
+ }
+ }
}
return false;
}
// Check that the folder's name is "packages"
if (!parent.getName().equals(DartCore.PACKAGES_DIRECTORY_NAME)) {
return false;
}
// Don't filter out the top-level packages reference.
if (parent.getParent() instanceof IProject) {
return false;
}
// If it's a system symlink, filter it out.
- // TODO(keertip): this does not filter symlinks in web/packages etc on Windows. For now we
- // need the resources to be shown in editor for debugging. Fix when debugging is fixed.
if (isSymLinked(parent)) {
return true;
}
return false;
}
private boolean isSymLinked(IContainer parent) {
IPath location = parent.getLocation();
if (location != null) {
try {
return FileUtilities.isLinkedFile(location.toFile());
} catch (CoreException e) {
}
}
return false;
}
}
| false | true | public boolean matches(IContainer parent, IFileInfo fileInfo) throws CoreException {
// suppress self link
// TODO(keertip): this does not work on Windows, replace it.
if (!DartCore.isWindows() && parent.getParent() != null
&& parent.getParent().getName().equals(DartCore.PACKAGES_DIRECTORY_NAME)) {
if (DartCore.isSelfLinkedResource(parent.getProject(), parent)) {
return true;
}
return false;
}
// Check that the folder's name is "packages"
if (!parent.getName().equals(DartCore.PACKAGES_DIRECTORY_NAME)) {
return false;
}
// Don't filter out the top-level packages reference.
if (parent.getParent() instanceof IProject) {
return false;
}
// If it's a system symlink, filter it out.
// TODO(keertip): this does not filter symlinks in web/packages etc on Windows. For now we
// need the resources to be shown in editor for debugging. Fix when debugging is fixed.
if (isSymLinked(parent)) {
return true;
}
return false;
}
| public boolean matches(IContainer parent, IFileInfo fileInfo) throws CoreException {
// suppress self link - test for self link only in pacakges that is next to pubspec.yaml
// TODO(keertip): this does not work on Windows, replace it.
if (!DartCore.isWindows() && parent.getParent() != null) {
IContainer gparent = parent.getParent();
if (gparent.getName().equals(DartCore.PACKAGES_DIRECTORY_NAME) && gparent.getParent() != null) {
IContainer appDir = gparent.getParent();
if (appDir.findMember(DartCore.PUBSPEC_FILE_NAME) != null) {
if (DartCore.isSelfLinkedResource(parent.getProject(), parent)) {
return true;
}
}
}
return false;
}
// Check that the folder's name is "packages"
if (!parent.getName().equals(DartCore.PACKAGES_DIRECTORY_NAME)) {
return false;
}
// Don't filter out the top-level packages reference.
if (parent.getParent() instanceof IProject) {
return false;
}
// If it's a system symlink, filter it out.
if (isSymLinked(parent)) {
return true;
}
return false;
}
|
diff --git a/src/main/java/com/xebialabs/overthere/cifs/winrm/WinRmClient.java b/src/main/java/com/xebialabs/overthere/cifs/winrm/WinRmClient.java
index 7f5a977..e7b75a2 100644
--- a/src/main/java/com/xebialabs/overthere/cifs/winrm/WinRmClient.java
+++ b/src/main/java/com/xebialabs/overthere/cifs/winrm/WinRmClient.java
@@ -1,318 +1,323 @@
/**
* Copyright (c) 2008, 2012, XebiaLabs B.V., All rights reserved.
*
*
* Overthere is licensed under the terms of the GPLv2
* <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most XebiaLabs Libraries.
* There are special exceptions to the terms and conditions of the GPLv2 as it is applied to
* this software, see the FLOSS License Exception
* <http://github.com/xebialabs/overthere/blob/master/LICENSE>.
*
* 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; version 2
* of the License.
*
* 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 St, Fifth
* Floor, Boston, MA 02110-1301 USA
*/
package com.xebialabs.overthere.cifs.winrm;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
import com.xebialabs.overthere.cifs.winrm.soap.*;
import org.apache.commons.codec.binary.Base64;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.QName;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.xebialabs.overthere.OverthereProcessOutputHandler;
import com.xebialabs.overthere.RuntimeIOException;
import com.xebialabs.overthere.cifs.winrm.exception.WinRMRuntimeIOException;
import static com.xebialabs.overthere.cifs.winrm.Namespaces.NS_WIN_SHELL;
public class WinRmClient {
private final URL targetURL;
private final HttpConnector connector;
private String timeout;
private int envelopSize;
private String locale;
private String exitCode;
private String shellId;
private String commandId;
private int chunk = 0;
public WinRmClient(HttpConnector connector, URL targetURL) {
this.connector = connector;
this.targetURL = targetURL;
}
public void runCmd(String command, OverthereProcessOutputHandler handler) {
try {
shellId = openShell();
commandId = runCommand(command);
getCommandOutput(handler);
} finally {
cleanUp();
closeShell();
}
}
private void closeShell() {
if (shellId == null)
return;
logger.debug("closeShell shellId {}", shellId);
final Document requestDocument = getRequestDocument(Action.WS_DELETE, ResourceURI.RESOURCE_URI_CMD, null, shellId, null);
sendMessage(requestDocument, null);
}
private void cleanUp() {
if (commandId == null)
return;
logger.debug("cleanUp shellId {} commandId {} ", shellId, commandId);
final Element bodyContent = DocumentHelper.createElement(QName.get("Signal", NS_WIN_SHELL)).addAttribute("CommandId", commandId);
bodyContent.addElement(QName.get("Code", NS_WIN_SHELL)).addText("http://schemas.microsoft.com/wbem/wsman/1/windows/shell/signal/terminate");
final Document requestDocument = getRequestDocument(Action.WS_SIGNAL, ResourceURI.RESOURCE_URI_CMD, null, shellId, bodyContent);
sendMessage(requestDocument, SoapAction.SIGNAL);
}
private void getCommandOutput(OverthereProcessOutputHandler handler) {
logger.debug("getCommandOutput shellId {} commandId {} ", shellId, commandId);
final Element bodyContent = DocumentHelper.createElement(QName.get("Receive", NS_WIN_SHELL));
bodyContent.addElement(QName.get("DesiredStream", NS_WIN_SHELL)).addAttribute("CommandId", commandId).addText("stdout stderr");
final Document requestDocument = getRequestDocument(Action.WS_RECEIVE, ResourceURI.RESOURCE_URI_CMD, null, shellId, bodyContent);
for (;;) {
Document responseDocument = sendMessage(requestDocument, SoapAction.RECEIVE);
String stdout = handleStream(responseDocument, ResponseExtractor.STDOUT);
BufferedReader stdoutReader = new BufferedReader(new StringReader(stdout));
try {
for (;;) {
String line = stdoutReader.readLine();
if (line == null) {
break;
}
+ for(int i = 0; i < line.length(); i++) {
+ handler.handleOutput(line.charAt(i));
+ }
+ handler.handleOutput('\r');
+ handler.handleOutput('\n');
handler.handleOutputLine(line);
}
} catch (IOException exc) {
throw new RuntimeIOException("Unexpected I/O exception while reading stdout", exc);
}
String stderr = handleStream(responseDocument, ResponseExtractor.STDERR);
BufferedReader stderrReader = new BufferedReader(new StringReader(stderr));
try {
for (;;) {
String line = stderrReader.readLine();
if (line == null) {
break;
}
handler.handleErrorLine(line);
}
} catch (IOException exc) {
throw new RuntimeIOException("Unexpected I/O exception while reading stderr", exc);
}
if (chunk == 0) {
try {
exitCode = getFirstElement(responseDocument, ResponseExtractor.EXIT_CODE);
logger.debug("exit code {}", exitCode);
} catch (Exception e) {
logger.debug("not found");
}
}
chunk++;
/*
* We may need to get additional output if the stream has not finished. The CommandState will change from
* Running to Done like so:
*
* @example
*
* from... <rsp:CommandState CommandId="..."
* State="http://schemas.microsoft.com/wbem/wsman/1/windows/shell/CommandState/Running"/> to...
* <rsp:CommandState CommandId="..."
* State="http://schemas.microsoft.com/wbem/wsman/1/windows/shell/CommandState/Done">
* <rsp:ExitCode>0</rsp:ExitCode> </rsp:CommandState>
*/
final List<?> list = ResponseExtractor.STREAM_DONE.getXPath().selectNodes(responseDocument);
if (!list.isEmpty()) {
exitCode = getFirstElement(responseDocument, ResponseExtractor.EXIT_CODE);
logger.info("exit code {}", exitCode);
break;
}
}
logger.debug("all the command output has been fetched (chunk={})", chunk);
}
private static String handleStream(Document responseDocument, ResponseExtractor stream) {
StringBuffer buffer = new StringBuffer();
@SuppressWarnings("unchecked") final List<Element> streams = stream.getXPath().selectNodes(responseDocument);
if (!streams.isEmpty()) {
final Base64 base64 = new Base64();
Iterator<Element> itStreams = streams.iterator();
while (itStreams.hasNext()) {
Element e = itStreams.next();
// TODO check performance with http://www.iharder.net/current/java/base64/
final byte[] decode = base64.decode(e.getText());
buffer.append(new String(decode));
}
}
logger.debug("handleStream {} buffer {}", stream, buffer);
return buffer.toString();
}
private String runCommand(String command) {
logger.debug("runCommand shellId {} command {}", shellId, command);
final Element bodyContent = DocumentHelper.createElement(QName.get("CommandLine", NS_WIN_SHELL));
String encoded = command;
encoded = "\"" + encoded + "\"";
logger.info("Encoded command is {}", encoded);
bodyContent.addElement(QName.get("Command", NS_WIN_SHELL)).addText(encoded);
final Document requestDocument = getRequestDocument(Action.WS_COMMAND, ResourceURI.RESOURCE_URI_CMD, OptionSet.RUN_COMMAND, shellId, bodyContent);
Document responseDocument = sendMessage(requestDocument, SoapAction.COMMAND_LINE);
return getFirstElement(responseDocument, ResponseExtractor.COMMAND_ID);
}
private static String getFirstElement(Document doc, ResponseExtractor extractor) {
@SuppressWarnings("unchecked") final List<Element> nodes = extractor.getXPath().selectNodes(doc);
if (nodes.isEmpty())
throw new RuntimeException("Cannot find " + extractor.getXPath() + " in " + toString(doc));
final Element next = nodes.iterator().next();
return next.getText();
}
private String openShell() {
logger.debug("openShell");
final Element bodyContent = DocumentHelper.createElement(QName.get("Shell", NS_WIN_SHELL));
bodyContent.addElement(QName.get("InputStreams", NS_WIN_SHELL)).addText("stdin");
bodyContent.addElement(QName.get("OutputStreams", NS_WIN_SHELL)).addText("stdout stderr");
final Document requestDocument = getRequestDocument(Action.WS_ACTION, ResourceURI.RESOURCE_URI_CMD, OptionSet.OPEN_SHELL, null, bodyContent);
Document responseDocument = sendMessage(requestDocument, SoapAction.SHELL);
return getFirstElement(responseDocument, ResponseExtractor.SHELL_ID);
}
private Document sendMessage(Document requestDocument, SoapAction soapAction) {
return connector.sendMessage(requestDocument, soapAction);
}
private Document getRequestDocument(Action action, ResourceURI resourceURI, OptionSet optionSet, String shelId, Element bodyContent) {
SoapMessageBuilder message = Soapy.newMessage();
SoapMessageBuilder.EnvelopeBuilder envelope = message.envelope();
try {
addHeaders(envelope, action, resourceURI, optionSet, shelId);
} catch (URISyntaxException e) {
throw new IllegalArgumentException(e);
}
BodyBuilder body = envelope.body();
if (bodyContent != null)
body.setContent(bodyContent);
return message.getDocument();
}
private void addHeaders(SoapMessageBuilder.EnvelopeBuilder envelope, Action action, ResourceURI resourceURI, OptionSet optionSet, String shelId)
throws URISyntaxException {
HeaderBuilder header = envelope.header();
header.to(targetURL.toURI()).replyTo(new URI("http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous"));
header.maxEnvelopeSize(envelopSize);
header.withId(getUUID());
header.withLocale(locale);
header.withTimeout(timeout);
header.withAction(action.getUri());
if (shelId != null) {
header.withShellId(shellId);
}
header.withResourceURI(resourceURI.getUri());
if (optionSet != null) {
header.withOptionSet(optionSet.getKeyValuePairs());
}
}
private static String toString(Document doc) {
StringWriter stringWriter = new StringWriter();
XMLWriter xmlWriter = new XMLWriter(stringWriter, OutputFormat.createPrettyPrint());
try {
xmlWriter.write(doc);
xmlWriter.close();
} catch (IOException e) {
throw new WinRMRuntimeIOException("error ", e);
}
return stringWriter.toString();
}
private static String getUUID() {
return "uuid:" + UUID.randomUUID().toString().toUpperCase();
}
public int getExitCode() {
return Integer.parseInt(exitCode);
}
public String getTimeout() {
return timeout;
}
public void setTimeout(String timeout) {
this.timeout = timeout;
}
public int getEnvelopSize() {
return envelopSize;
}
public void setEnvelopSize(int envelopSize) {
this.envelopSize = envelopSize;
}
public String getLocale() {
return locale;
}
public void setLocale(String locale) {
this.locale = locale;
}
public URL getTargetURL() {
return targetURL;
}
private static Logger logger = LoggerFactory.getLogger(WinRmClient.class);
}
| true | true | private void getCommandOutput(OverthereProcessOutputHandler handler) {
logger.debug("getCommandOutput shellId {} commandId {} ", shellId, commandId);
final Element bodyContent = DocumentHelper.createElement(QName.get("Receive", NS_WIN_SHELL));
bodyContent.addElement(QName.get("DesiredStream", NS_WIN_SHELL)).addAttribute("CommandId", commandId).addText("stdout stderr");
final Document requestDocument = getRequestDocument(Action.WS_RECEIVE, ResourceURI.RESOURCE_URI_CMD, null, shellId, bodyContent);
for (;;) {
Document responseDocument = sendMessage(requestDocument, SoapAction.RECEIVE);
String stdout = handleStream(responseDocument, ResponseExtractor.STDOUT);
BufferedReader stdoutReader = new BufferedReader(new StringReader(stdout));
try {
for (;;) {
String line = stdoutReader.readLine();
if (line == null) {
break;
}
handler.handleOutputLine(line);
}
} catch (IOException exc) {
throw new RuntimeIOException("Unexpected I/O exception while reading stdout", exc);
}
String stderr = handleStream(responseDocument, ResponseExtractor.STDERR);
BufferedReader stderrReader = new BufferedReader(new StringReader(stderr));
try {
for (;;) {
String line = stderrReader.readLine();
if (line == null) {
break;
}
handler.handleErrorLine(line);
}
} catch (IOException exc) {
throw new RuntimeIOException("Unexpected I/O exception while reading stderr", exc);
}
if (chunk == 0) {
try {
exitCode = getFirstElement(responseDocument, ResponseExtractor.EXIT_CODE);
logger.debug("exit code {}", exitCode);
} catch (Exception e) {
logger.debug("not found");
}
}
chunk++;
/*
* We may need to get additional output if the stream has not finished. The CommandState will change from
* Running to Done like so:
*
* @example
*
* from... <rsp:CommandState CommandId="..."
* State="http://schemas.microsoft.com/wbem/wsman/1/windows/shell/CommandState/Running"/> to...
* <rsp:CommandState CommandId="..."
* State="http://schemas.microsoft.com/wbem/wsman/1/windows/shell/CommandState/Done">
* <rsp:ExitCode>0</rsp:ExitCode> </rsp:CommandState>
*/
final List<?> list = ResponseExtractor.STREAM_DONE.getXPath().selectNodes(responseDocument);
if (!list.isEmpty()) {
exitCode = getFirstElement(responseDocument, ResponseExtractor.EXIT_CODE);
logger.info("exit code {}", exitCode);
break;
}
}
logger.debug("all the command output has been fetched (chunk={})", chunk);
}
| private void getCommandOutput(OverthereProcessOutputHandler handler) {
logger.debug("getCommandOutput shellId {} commandId {} ", shellId, commandId);
final Element bodyContent = DocumentHelper.createElement(QName.get("Receive", NS_WIN_SHELL));
bodyContent.addElement(QName.get("DesiredStream", NS_WIN_SHELL)).addAttribute("CommandId", commandId).addText("stdout stderr");
final Document requestDocument = getRequestDocument(Action.WS_RECEIVE, ResourceURI.RESOURCE_URI_CMD, null, shellId, bodyContent);
for (;;) {
Document responseDocument = sendMessage(requestDocument, SoapAction.RECEIVE);
String stdout = handleStream(responseDocument, ResponseExtractor.STDOUT);
BufferedReader stdoutReader = new BufferedReader(new StringReader(stdout));
try {
for (;;) {
String line = stdoutReader.readLine();
if (line == null) {
break;
}
for(int i = 0; i < line.length(); i++) {
handler.handleOutput(line.charAt(i));
}
handler.handleOutput('\r');
handler.handleOutput('\n');
handler.handleOutputLine(line);
}
} catch (IOException exc) {
throw new RuntimeIOException("Unexpected I/O exception while reading stdout", exc);
}
String stderr = handleStream(responseDocument, ResponseExtractor.STDERR);
BufferedReader stderrReader = new BufferedReader(new StringReader(stderr));
try {
for (;;) {
String line = stderrReader.readLine();
if (line == null) {
break;
}
handler.handleErrorLine(line);
}
} catch (IOException exc) {
throw new RuntimeIOException("Unexpected I/O exception while reading stderr", exc);
}
if (chunk == 0) {
try {
exitCode = getFirstElement(responseDocument, ResponseExtractor.EXIT_CODE);
logger.debug("exit code {}", exitCode);
} catch (Exception e) {
logger.debug("not found");
}
}
chunk++;
/*
* We may need to get additional output if the stream has not finished. The CommandState will change from
* Running to Done like so:
*
* @example
*
* from... <rsp:CommandState CommandId="..."
* State="http://schemas.microsoft.com/wbem/wsman/1/windows/shell/CommandState/Running"/> to...
* <rsp:CommandState CommandId="..."
* State="http://schemas.microsoft.com/wbem/wsman/1/windows/shell/CommandState/Done">
* <rsp:ExitCode>0</rsp:ExitCode> </rsp:CommandState>
*/
final List<?> list = ResponseExtractor.STREAM_DONE.getXPath().selectNodes(responseDocument);
if (!list.isEmpty()) {
exitCode = getFirstElement(responseDocument, ResponseExtractor.EXIT_CODE);
logger.info("exit code {}", exitCode);
break;
}
}
logger.debug("all the command output has been fetched (chunk={})", chunk);
}
|
diff --git a/src/com/bretth/osmosis/core/TaskRegistrar.java b/src/com/bretth/osmosis/core/TaskRegistrar.java
index 9755bf9d..9a843e61 100644
--- a/src/com/bretth/osmosis/core/TaskRegistrar.java
+++ b/src/com/bretth/osmosis/core/TaskRegistrar.java
@@ -1,185 +1,185 @@
// License: GPL. Copyright 2007-2008 by Brett Henderson and other contributors.
package com.bretth.osmosis.core;
import com.bretth.osmosis.core.bdb.v0_5.BdbReaderFactory;
import com.bretth.osmosis.core.bdb.v0_5.BdbWriterFactory;
import com.bretth.osmosis.core.buffer.v0_5.ChangeBufferFactory;
import com.bretth.osmosis.core.buffer.v0_5.EntityBufferFactory;
import com.bretth.osmosis.core.change.v0_5.ChangeApplierFactory;
import com.bretth.osmosis.core.change.v0_5.ChangeDeriverFactory;
import com.bretth.osmosis.core.customdb.v0_5.DumpDatasetFactory;
import com.bretth.osmosis.core.customdb.v0_5.ReadDatasetFactory;
import com.bretth.osmosis.core.customdb.v0_5.WriteDatasetFactory;
import com.bretth.osmosis.core.filter.v0_5.BoundingBoxFilterFactory;
import com.bretth.osmosis.core.filter.v0_5.DatasetBoundingBoxFilterFactory;
import com.bretth.osmosis.core.filter.v0_5.PolygonFilterFactory;
import com.bretth.osmosis.core.merge.v0_5.ChangeMergerFactory;
import com.bretth.osmosis.core.merge.v0_5.EntityMergerFactory;
import com.bretth.osmosis.core.misc.v0_5.NullChangeWriterFactory;
import com.bretth.osmosis.core.misc.v0_5.NullWriterFactory;
import com.bretth.osmosis.core.mysql.v0_5.MySqlCurrentReaderFactory;
import com.bretth.osmosis.core.mysql.v0_5.MysqlChangeReaderFactory;
import com.bretth.osmosis.core.mysql.v0_5.MysqlChangeWriterFactory;
import com.bretth.osmosis.core.mysql.v0_5.MysqlReaderFactory;
import com.bretth.osmosis.core.mysql.v0_5.MysqlTruncatorFactory;
import com.bretth.osmosis.core.mysql.v0_5.MysqlWriterFactory;
import com.bretth.osmosis.core.pgsql.common.v0_5.PostgreSqlDumpWriterFactory;
import com.bretth.osmosis.core.pgsql.common.v0_5.PostgreSqlTruncatorFactory;
import com.bretth.osmosis.core.pgsql.common.v0_5.PostgreSqlWriterFactory;
import com.bretth.osmosis.core.pipeline.common.TaskManagerFactory;
import com.bretth.osmosis.core.progress.v0_5.ChangeProgressLoggerFactory;
import com.bretth.osmosis.core.progress.v0_5.EntityProgressLoggerFactory;
import com.bretth.osmosis.core.report.v0_5.EntityReporterFactory;
import com.bretth.osmosis.core.report.v0_5.IntegrityReporterFactory;
import com.bretth.osmosis.core.sort.v0_5.ChangeForSeekableApplierComparator;
import com.bretth.osmosis.core.sort.v0_5.ChangeForStreamableApplierComparator;
import com.bretth.osmosis.core.sort.v0_5.ChangeSorterFactory;
import com.bretth.osmosis.core.sort.v0_5.EntityByTypeThenIdComparator;
import com.bretth.osmosis.core.sort.v0_5.EntitySorterFactory;
import com.bretth.osmosis.core.tee.v0_5.ChangeTeeFactory;
import com.bretth.osmosis.core.tee.v0_5.EntityTeeFactory;
import com.bretth.osmosis.core.xml.v0_5.XmlChangeReaderFactory;
import com.bretth.osmosis.core.xml.v0_5.XmlChangeWriterFactory;
import com.bretth.osmosis.core.xml.v0_5.XmlDownloaderFactory;
import com.bretth.osmosis.core.xml.v0_5.XmlReaderFactory;
import com.bretth.osmosis.core.xml.v0_5.XmlWriterFactory;
/**
* Provides the initialisation logic for registering all task factories.
*
* @author Brett Henderson
*/
public class TaskRegistrar {
/**
* Initialises factories for all tasks.
*/
public static void initialize() {
EntitySorterFactory entitySorterFactory05;
ChangeSorterFactory changeSorterFactory05;
// Configure factories that require additional information.
entitySorterFactory05 = new EntitySorterFactory();
entitySorterFactory05.registerComparator("TypeThenId", new EntityByTypeThenIdComparator(), true);
changeSorterFactory05 = new ChangeSorterFactory();
changeSorterFactory05.registerComparator("streamable", new ChangeForStreamableApplierComparator(), true);
changeSorterFactory05.registerComparator("seekable", new ChangeForSeekableApplierComparator(), false);
// Register factories.
TaskManagerFactory.register("apply-change", new ChangeApplierFactory());
TaskManagerFactory.register("ac", new ChangeApplierFactory());
TaskManagerFactory.register("bounding-box", new BoundingBoxFilterFactory());
TaskManagerFactory.register("bb", new BoundingBoxFilterFactory());
TaskManagerFactory.register("derive-change", new ChangeDeriverFactory());
TaskManagerFactory.register("dc", new ChangeDeriverFactory());
TaskManagerFactory.register("read-mysql", new MysqlReaderFactory());
TaskManagerFactory.register("rm", new MysqlReaderFactory());
TaskManagerFactory.register("read-mysql-change", new MysqlChangeReaderFactory());
TaskManagerFactory.register("rmc", new MysqlChangeReaderFactory());
TaskManagerFactory.register("read-mysql-current", new MySqlCurrentReaderFactory());
TaskManagerFactory.register("rmcur", new MySqlCurrentReaderFactory());
TaskManagerFactory.register("read-xml", new XmlReaderFactory());
TaskManagerFactory.register("rx", new XmlReaderFactory());
TaskManagerFactory.register("read-xml-change", new XmlChangeReaderFactory());
TaskManagerFactory.register("rxc", new XmlChangeReaderFactory());
TaskManagerFactory.register("sort", entitySorterFactory05);
TaskManagerFactory.register("s", entitySorterFactory05);
TaskManagerFactory.register("sort-change", changeSorterFactory05);
TaskManagerFactory.register("sc", changeSorterFactory05);
TaskManagerFactory.register("write-mysql", new MysqlWriterFactory());
TaskManagerFactory.register("wm", new MysqlWriterFactory());
TaskManagerFactory.register("write-mysql-change", new MysqlChangeWriterFactory());
TaskManagerFactory.register("wmc", new MysqlChangeWriterFactory());
TaskManagerFactory.register("truncate-mysql", new MysqlTruncatorFactory());
TaskManagerFactory.register("tm", new MysqlTruncatorFactory());
TaskManagerFactory.register("write-xml", new XmlWriterFactory());
TaskManagerFactory.register("wx", new XmlWriterFactory());
TaskManagerFactory.register("write-xml-change", new XmlChangeWriterFactory());
TaskManagerFactory.register("wxc", new XmlChangeWriterFactory());
TaskManagerFactory.register("write-null", new NullWriterFactory());
TaskManagerFactory.register("wn", new NullWriterFactory());
TaskManagerFactory.register("write-null-change", new NullChangeWriterFactory());
TaskManagerFactory.register("wnc", new NullChangeWriterFactory());
TaskManagerFactory.register("buffer", new EntityBufferFactory());
TaskManagerFactory.register("b", new EntityBufferFactory());
TaskManagerFactory.register("buffer-change", new ChangeBufferFactory());
TaskManagerFactory.register("bc", new ChangeBufferFactory());
TaskManagerFactory.register("merge", new EntityMergerFactory());
TaskManagerFactory.register("m", new EntityMergerFactory());
TaskManagerFactory.register("merge-change", new ChangeMergerFactory());
TaskManagerFactory.register("mc", new ChangeMergerFactory());
TaskManagerFactory.register("read-api", new XmlDownloaderFactory());
- TaskManagerFactory.register("wa", new XmlDownloaderFactory());
+ TaskManagerFactory.register("ra", new XmlDownloaderFactory());
TaskManagerFactory.register("bounding-polygon", new PolygonFilterFactory());
TaskManagerFactory.register("bp", new PolygonFilterFactory());
TaskManagerFactory.register("report-entity", new EntityReporterFactory());
TaskManagerFactory.register("re", new EntityReporterFactory());
TaskManagerFactory.register("report-integrity", new IntegrityReporterFactory());
TaskManagerFactory.register("ri", new IntegrityReporterFactory());
TaskManagerFactory.register("write-pgsql", new PostgreSqlWriterFactory());
TaskManagerFactory.register("wp", new PostgreSqlWriterFactory());
TaskManagerFactory.register("truncate-pgsql", new PostgreSqlTruncatorFactory());
TaskManagerFactory.register("tp", new PostgreSqlTruncatorFactory());
TaskManagerFactory.register("log-progress", new EntityProgressLoggerFactory());
TaskManagerFactory.register("lp", new EntityProgressLoggerFactory());
TaskManagerFactory.register("log-progress-change", new ChangeProgressLoggerFactory());
TaskManagerFactory.register("lpc", new ChangeProgressLoggerFactory());
TaskManagerFactory.register("tee", new EntityTeeFactory());
TaskManagerFactory.register("t", new EntityTeeFactory());
TaskManagerFactory.register("tee-change", new ChangeTeeFactory());
TaskManagerFactory.register("tc", new ChangeTeeFactory());
TaskManagerFactory.register("write-pgsql-dump", new PostgreSqlDumpWriterFactory());
TaskManagerFactory.register("wpd", new PostgreSqlDumpWriterFactory());
TaskManagerFactory.register("write-customdb", new WriteDatasetFactory());
TaskManagerFactory.register("wc", new WriteDatasetFactory());
TaskManagerFactory.register("dataset-bounding-box", new DatasetBoundingBoxFilterFactory());
TaskManagerFactory.register("dbb", new DatasetBoundingBoxFilterFactory());
TaskManagerFactory.register("dataset-dump", new DumpDatasetFactory());
TaskManagerFactory.register("dd", new DumpDatasetFactory());
TaskManagerFactory.register("write-bdb", new BdbWriterFactory());
TaskManagerFactory.register("wb", new BdbWriterFactory());
TaskManagerFactory.register("read-bdb", new BdbReaderFactory());
TaskManagerFactory.register("rb", new BdbReaderFactory());
TaskManagerFactory.register("read-customdb", new ReadDatasetFactory());
TaskManagerFactory.register("rc", new ReadDatasetFactory());
TaskManagerFactory.register("apply-change-0.5", new ChangeApplierFactory());
TaskManagerFactory.register("bounding-box-0.5", new BoundingBoxFilterFactory());
TaskManagerFactory.register("derive-change-0.5", new ChangeDeriverFactory());
TaskManagerFactory.register("read-mysql-0.5", new MysqlReaderFactory());
TaskManagerFactory.register("read-mysql-change-0.5", new MysqlChangeReaderFactory());
TaskManagerFactory.register("read-mysql-current-0.5", new MySqlCurrentReaderFactory());
TaskManagerFactory.register("read-xml-0.5", new XmlReaderFactory());
TaskManagerFactory.register("read-xml-change-0.5", new XmlChangeReaderFactory());
TaskManagerFactory.register("sort-0.5", entitySorterFactory05);
TaskManagerFactory.register("sort-change-0.5", changeSorterFactory05);
TaskManagerFactory.register("write-mysql-0.5", new MysqlWriterFactory());
TaskManagerFactory.register("write-mysql-change-0.5", new MysqlChangeWriterFactory());
TaskManagerFactory.register("truncate-mysql-0.5", new MysqlTruncatorFactory());
TaskManagerFactory.register("write-xml-0.5", new XmlWriterFactory());
TaskManagerFactory.register("write-xml-change-0.5", new XmlChangeWriterFactory());
TaskManagerFactory.register("write-null-0.5", new NullWriterFactory());
TaskManagerFactory.register("write-null-change-0.5", new NullChangeWriterFactory());
TaskManagerFactory.register("buffer-0.5", new EntityBufferFactory());
TaskManagerFactory.register("buffer-change-0.5", new ChangeBufferFactory());
TaskManagerFactory.register("merge-0.5", new EntityMergerFactory());
TaskManagerFactory.register("merge-change-0.5", new ChangeMergerFactory());
TaskManagerFactory.register("read-api-0.5", new XmlDownloaderFactory());
TaskManagerFactory.register("bounding-polygon-0.5", new PolygonFilterFactory());
TaskManagerFactory.register("report-entity-0.5", new EntityReporterFactory());
TaskManagerFactory.register("report-integrity-0.5", new IntegrityReporterFactory());
TaskManagerFactory.register("write-pgsql-0.5", new PostgreSqlWriterFactory());
TaskManagerFactory.register("truncate-pgsql-0.5", new PostgreSqlTruncatorFactory());
TaskManagerFactory.register("log-progress-0.5", new EntityProgressLoggerFactory());
TaskManagerFactory.register("log-change-progress-0.5", new ChangeProgressLoggerFactory());
TaskManagerFactory.register("tee-0.5", new EntityTeeFactory());
TaskManagerFactory.register("tee-change-0.5", new ChangeTeeFactory());
TaskManagerFactory.register("write-pgsql-dump-0.5", new PostgreSqlDumpWriterFactory());
TaskManagerFactory.register("write-customdb-0.5", new WriteDatasetFactory());
TaskManagerFactory.register("dataset-bounding-box-0.5", new DatasetBoundingBoxFilterFactory());
TaskManagerFactory.register("dataset-dump-0.5", new DumpDatasetFactory());
TaskManagerFactory.register("write-bdb-0.5", new BdbWriterFactory());
TaskManagerFactory.register("read-bdb-0.5", new BdbReaderFactory());
TaskManagerFactory.register("read-customdb-0.5", new ReadDatasetFactory());
}
}
| true | true | public static void initialize() {
EntitySorterFactory entitySorterFactory05;
ChangeSorterFactory changeSorterFactory05;
// Configure factories that require additional information.
entitySorterFactory05 = new EntitySorterFactory();
entitySorterFactory05.registerComparator("TypeThenId", new EntityByTypeThenIdComparator(), true);
changeSorterFactory05 = new ChangeSorterFactory();
changeSorterFactory05.registerComparator("streamable", new ChangeForStreamableApplierComparator(), true);
changeSorterFactory05.registerComparator("seekable", new ChangeForSeekableApplierComparator(), false);
// Register factories.
TaskManagerFactory.register("apply-change", new ChangeApplierFactory());
TaskManagerFactory.register("ac", new ChangeApplierFactory());
TaskManagerFactory.register("bounding-box", new BoundingBoxFilterFactory());
TaskManagerFactory.register("bb", new BoundingBoxFilterFactory());
TaskManagerFactory.register("derive-change", new ChangeDeriverFactory());
TaskManagerFactory.register("dc", new ChangeDeriverFactory());
TaskManagerFactory.register("read-mysql", new MysqlReaderFactory());
TaskManagerFactory.register("rm", new MysqlReaderFactory());
TaskManagerFactory.register("read-mysql-change", new MysqlChangeReaderFactory());
TaskManagerFactory.register("rmc", new MysqlChangeReaderFactory());
TaskManagerFactory.register("read-mysql-current", new MySqlCurrentReaderFactory());
TaskManagerFactory.register("rmcur", new MySqlCurrentReaderFactory());
TaskManagerFactory.register("read-xml", new XmlReaderFactory());
TaskManagerFactory.register("rx", new XmlReaderFactory());
TaskManagerFactory.register("read-xml-change", new XmlChangeReaderFactory());
TaskManagerFactory.register("rxc", new XmlChangeReaderFactory());
TaskManagerFactory.register("sort", entitySorterFactory05);
TaskManagerFactory.register("s", entitySorterFactory05);
TaskManagerFactory.register("sort-change", changeSorterFactory05);
TaskManagerFactory.register("sc", changeSorterFactory05);
TaskManagerFactory.register("write-mysql", new MysqlWriterFactory());
TaskManagerFactory.register("wm", new MysqlWriterFactory());
TaskManagerFactory.register("write-mysql-change", new MysqlChangeWriterFactory());
TaskManagerFactory.register("wmc", new MysqlChangeWriterFactory());
TaskManagerFactory.register("truncate-mysql", new MysqlTruncatorFactory());
TaskManagerFactory.register("tm", new MysqlTruncatorFactory());
TaskManagerFactory.register("write-xml", new XmlWriterFactory());
TaskManagerFactory.register("wx", new XmlWriterFactory());
TaskManagerFactory.register("write-xml-change", new XmlChangeWriterFactory());
TaskManagerFactory.register("wxc", new XmlChangeWriterFactory());
TaskManagerFactory.register("write-null", new NullWriterFactory());
TaskManagerFactory.register("wn", new NullWriterFactory());
TaskManagerFactory.register("write-null-change", new NullChangeWriterFactory());
TaskManagerFactory.register("wnc", new NullChangeWriterFactory());
TaskManagerFactory.register("buffer", new EntityBufferFactory());
TaskManagerFactory.register("b", new EntityBufferFactory());
TaskManagerFactory.register("buffer-change", new ChangeBufferFactory());
TaskManagerFactory.register("bc", new ChangeBufferFactory());
TaskManagerFactory.register("merge", new EntityMergerFactory());
TaskManagerFactory.register("m", new EntityMergerFactory());
TaskManagerFactory.register("merge-change", new ChangeMergerFactory());
TaskManagerFactory.register("mc", new ChangeMergerFactory());
TaskManagerFactory.register("read-api", new XmlDownloaderFactory());
TaskManagerFactory.register("wa", new XmlDownloaderFactory());
TaskManagerFactory.register("bounding-polygon", new PolygonFilterFactory());
TaskManagerFactory.register("bp", new PolygonFilterFactory());
TaskManagerFactory.register("report-entity", new EntityReporterFactory());
TaskManagerFactory.register("re", new EntityReporterFactory());
TaskManagerFactory.register("report-integrity", new IntegrityReporterFactory());
TaskManagerFactory.register("ri", new IntegrityReporterFactory());
TaskManagerFactory.register("write-pgsql", new PostgreSqlWriterFactory());
TaskManagerFactory.register("wp", new PostgreSqlWriterFactory());
TaskManagerFactory.register("truncate-pgsql", new PostgreSqlTruncatorFactory());
TaskManagerFactory.register("tp", new PostgreSqlTruncatorFactory());
TaskManagerFactory.register("log-progress", new EntityProgressLoggerFactory());
TaskManagerFactory.register("lp", new EntityProgressLoggerFactory());
TaskManagerFactory.register("log-progress-change", new ChangeProgressLoggerFactory());
TaskManagerFactory.register("lpc", new ChangeProgressLoggerFactory());
TaskManagerFactory.register("tee", new EntityTeeFactory());
TaskManagerFactory.register("t", new EntityTeeFactory());
TaskManagerFactory.register("tee-change", new ChangeTeeFactory());
TaskManagerFactory.register("tc", new ChangeTeeFactory());
TaskManagerFactory.register("write-pgsql-dump", new PostgreSqlDumpWriterFactory());
TaskManagerFactory.register("wpd", new PostgreSqlDumpWriterFactory());
TaskManagerFactory.register("write-customdb", new WriteDatasetFactory());
TaskManagerFactory.register("wc", new WriteDatasetFactory());
TaskManagerFactory.register("dataset-bounding-box", new DatasetBoundingBoxFilterFactory());
TaskManagerFactory.register("dbb", new DatasetBoundingBoxFilterFactory());
TaskManagerFactory.register("dataset-dump", new DumpDatasetFactory());
TaskManagerFactory.register("dd", new DumpDatasetFactory());
TaskManagerFactory.register("write-bdb", new BdbWriterFactory());
TaskManagerFactory.register("wb", new BdbWriterFactory());
TaskManagerFactory.register("read-bdb", new BdbReaderFactory());
TaskManagerFactory.register("rb", new BdbReaderFactory());
TaskManagerFactory.register("read-customdb", new ReadDatasetFactory());
TaskManagerFactory.register("rc", new ReadDatasetFactory());
TaskManagerFactory.register("apply-change-0.5", new ChangeApplierFactory());
TaskManagerFactory.register("bounding-box-0.5", new BoundingBoxFilterFactory());
TaskManagerFactory.register("derive-change-0.5", new ChangeDeriverFactory());
TaskManagerFactory.register("read-mysql-0.5", new MysqlReaderFactory());
TaskManagerFactory.register("read-mysql-change-0.5", new MysqlChangeReaderFactory());
TaskManagerFactory.register("read-mysql-current-0.5", new MySqlCurrentReaderFactory());
TaskManagerFactory.register("read-xml-0.5", new XmlReaderFactory());
TaskManagerFactory.register("read-xml-change-0.5", new XmlChangeReaderFactory());
TaskManagerFactory.register("sort-0.5", entitySorterFactory05);
TaskManagerFactory.register("sort-change-0.5", changeSorterFactory05);
TaskManagerFactory.register("write-mysql-0.5", new MysqlWriterFactory());
TaskManagerFactory.register("write-mysql-change-0.5", new MysqlChangeWriterFactory());
TaskManagerFactory.register("truncate-mysql-0.5", new MysqlTruncatorFactory());
TaskManagerFactory.register("write-xml-0.5", new XmlWriterFactory());
TaskManagerFactory.register("write-xml-change-0.5", new XmlChangeWriterFactory());
TaskManagerFactory.register("write-null-0.5", new NullWriterFactory());
TaskManagerFactory.register("write-null-change-0.5", new NullChangeWriterFactory());
TaskManagerFactory.register("buffer-0.5", new EntityBufferFactory());
TaskManagerFactory.register("buffer-change-0.5", new ChangeBufferFactory());
TaskManagerFactory.register("merge-0.5", new EntityMergerFactory());
TaskManagerFactory.register("merge-change-0.5", new ChangeMergerFactory());
TaskManagerFactory.register("read-api-0.5", new XmlDownloaderFactory());
TaskManagerFactory.register("bounding-polygon-0.5", new PolygonFilterFactory());
TaskManagerFactory.register("report-entity-0.5", new EntityReporterFactory());
TaskManagerFactory.register("report-integrity-0.5", new IntegrityReporterFactory());
TaskManagerFactory.register("write-pgsql-0.5", new PostgreSqlWriterFactory());
TaskManagerFactory.register("truncate-pgsql-0.5", new PostgreSqlTruncatorFactory());
TaskManagerFactory.register("log-progress-0.5", new EntityProgressLoggerFactory());
TaskManagerFactory.register("log-change-progress-0.5", new ChangeProgressLoggerFactory());
TaskManagerFactory.register("tee-0.5", new EntityTeeFactory());
TaskManagerFactory.register("tee-change-0.5", new ChangeTeeFactory());
TaskManagerFactory.register("write-pgsql-dump-0.5", new PostgreSqlDumpWriterFactory());
TaskManagerFactory.register("write-customdb-0.5", new WriteDatasetFactory());
TaskManagerFactory.register("dataset-bounding-box-0.5", new DatasetBoundingBoxFilterFactory());
TaskManagerFactory.register("dataset-dump-0.5", new DumpDatasetFactory());
TaskManagerFactory.register("write-bdb-0.5", new BdbWriterFactory());
TaskManagerFactory.register("read-bdb-0.5", new BdbReaderFactory());
TaskManagerFactory.register("read-customdb-0.5", new ReadDatasetFactory());
}
| public static void initialize() {
EntitySorterFactory entitySorterFactory05;
ChangeSorterFactory changeSorterFactory05;
// Configure factories that require additional information.
entitySorterFactory05 = new EntitySorterFactory();
entitySorterFactory05.registerComparator("TypeThenId", new EntityByTypeThenIdComparator(), true);
changeSorterFactory05 = new ChangeSorterFactory();
changeSorterFactory05.registerComparator("streamable", new ChangeForStreamableApplierComparator(), true);
changeSorterFactory05.registerComparator("seekable", new ChangeForSeekableApplierComparator(), false);
// Register factories.
TaskManagerFactory.register("apply-change", new ChangeApplierFactory());
TaskManagerFactory.register("ac", new ChangeApplierFactory());
TaskManagerFactory.register("bounding-box", new BoundingBoxFilterFactory());
TaskManagerFactory.register("bb", new BoundingBoxFilterFactory());
TaskManagerFactory.register("derive-change", new ChangeDeriverFactory());
TaskManagerFactory.register("dc", new ChangeDeriverFactory());
TaskManagerFactory.register("read-mysql", new MysqlReaderFactory());
TaskManagerFactory.register("rm", new MysqlReaderFactory());
TaskManagerFactory.register("read-mysql-change", new MysqlChangeReaderFactory());
TaskManagerFactory.register("rmc", new MysqlChangeReaderFactory());
TaskManagerFactory.register("read-mysql-current", new MySqlCurrentReaderFactory());
TaskManagerFactory.register("rmcur", new MySqlCurrentReaderFactory());
TaskManagerFactory.register("read-xml", new XmlReaderFactory());
TaskManagerFactory.register("rx", new XmlReaderFactory());
TaskManagerFactory.register("read-xml-change", new XmlChangeReaderFactory());
TaskManagerFactory.register("rxc", new XmlChangeReaderFactory());
TaskManagerFactory.register("sort", entitySorterFactory05);
TaskManagerFactory.register("s", entitySorterFactory05);
TaskManagerFactory.register("sort-change", changeSorterFactory05);
TaskManagerFactory.register("sc", changeSorterFactory05);
TaskManagerFactory.register("write-mysql", new MysqlWriterFactory());
TaskManagerFactory.register("wm", new MysqlWriterFactory());
TaskManagerFactory.register("write-mysql-change", new MysqlChangeWriterFactory());
TaskManagerFactory.register("wmc", new MysqlChangeWriterFactory());
TaskManagerFactory.register("truncate-mysql", new MysqlTruncatorFactory());
TaskManagerFactory.register("tm", new MysqlTruncatorFactory());
TaskManagerFactory.register("write-xml", new XmlWriterFactory());
TaskManagerFactory.register("wx", new XmlWriterFactory());
TaskManagerFactory.register("write-xml-change", new XmlChangeWriterFactory());
TaskManagerFactory.register("wxc", new XmlChangeWriterFactory());
TaskManagerFactory.register("write-null", new NullWriterFactory());
TaskManagerFactory.register("wn", new NullWriterFactory());
TaskManagerFactory.register("write-null-change", new NullChangeWriterFactory());
TaskManagerFactory.register("wnc", new NullChangeWriterFactory());
TaskManagerFactory.register("buffer", new EntityBufferFactory());
TaskManagerFactory.register("b", new EntityBufferFactory());
TaskManagerFactory.register("buffer-change", new ChangeBufferFactory());
TaskManagerFactory.register("bc", new ChangeBufferFactory());
TaskManagerFactory.register("merge", new EntityMergerFactory());
TaskManagerFactory.register("m", new EntityMergerFactory());
TaskManagerFactory.register("merge-change", new ChangeMergerFactory());
TaskManagerFactory.register("mc", new ChangeMergerFactory());
TaskManagerFactory.register("read-api", new XmlDownloaderFactory());
TaskManagerFactory.register("ra", new XmlDownloaderFactory());
TaskManagerFactory.register("bounding-polygon", new PolygonFilterFactory());
TaskManagerFactory.register("bp", new PolygonFilterFactory());
TaskManagerFactory.register("report-entity", new EntityReporterFactory());
TaskManagerFactory.register("re", new EntityReporterFactory());
TaskManagerFactory.register("report-integrity", new IntegrityReporterFactory());
TaskManagerFactory.register("ri", new IntegrityReporterFactory());
TaskManagerFactory.register("write-pgsql", new PostgreSqlWriterFactory());
TaskManagerFactory.register("wp", new PostgreSqlWriterFactory());
TaskManagerFactory.register("truncate-pgsql", new PostgreSqlTruncatorFactory());
TaskManagerFactory.register("tp", new PostgreSqlTruncatorFactory());
TaskManagerFactory.register("log-progress", new EntityProgressLoggerFactory());
TaskManagerFactory.register("lp", new EntityProgressLoggerFactory());
TaskManagerFactory.register("log-progress-change", new ChangeProgressLoggerFactory());
TaskManagerFactory.register("lpc", new ChangeProgressLoggerFactory());
TaskManagerFactory.register("tee", new EntityTeeFactory());
TaskManagerFactory.register("t", new EntityTeeFactory());
TaskManagerFactory.register("tee-change", new ChangeTeeFactory());
TaskManagerFactory.register("tc", new ChangeTeeFactory());
TaskManagerFactory.register("write-pgsql-dump", new PostgreSqlDumpWriterFactory());
TaskManagerFactory.register("wpd", new PostgreSqlDumpWriterFactory());
TaskManagerFactory.register("write-customdb", new WriteDatasetFactory());
TaskManagerFactory.register("wc", new WriteDatasetFactory());
TaskManagerFactory.register("dataset-bounding-box", new DatasetBoundingBoxFilterFactory());
TaskManagerFactory.register("dbb", new DatasetBoundingBoxFilterFactory());
TaskManagerFactory.register("dataset-dump", new DumpDatasetFactory());
TaskManagerFactory.register("dd", new DumpDatasetFactory());
TaskManagerFactory.register("write-bdb", new BdbWriterFactory());
TaskManagerFactory.register("wb", new BdbWriterFactory());
TaskManagerFactory.register("read-bdb", new BdbReaderFactory());
TaskManagerFactory.register("rb", new BdbReaderFactory());
TaskManagerFactory.register("read-customdb", new ReadDatasetFactory());
TaskManagerFactory.register("rc", new ReadDatasetFactory());
TaskManagerFactory.register("apply-change-0.5", new ChangeApplierFactory());
TaskManagerFactory.register("bounding-box-0.5", new BoundingBoxFilterFactory());
TaskManagerFactory.register("derive-change-0.5", new ChangeDeriverFactory());
TaskManagerFactory.register("read-mysql-0.5", new MysqlReaderFactory());
TaskManagerFactory.register("read-mysql-change-0.5", new MysqlChangeReaderFactory());
TaskManagerFactory.register("read-mysql-current-0.5", new MySqlCurrentReaderFactory());
TaskManagerFactory.register("read-xml-0.5", new XmlReaderFactory());
TaskManagerFactory.register("read-xml-change-0.5", new XmlChangeReaderFactory());
TaskManagerFactory.register("sort-0.5", entitySorterFactory05);
TaskManagerFactory.register("sort-change-0.5", changeSorterFactory05);
TaskManagerFactory.register("write-mysql-0.5", new MysqlWriterFactory());
TaskManagerFactory.register("write-mysql-change-0.5", new MysqlChangeWriterFactory());
TaskManagerFactory.register("truncate-mysql-0.5", new MysqlTruncatorFactory());
TaskManagerFactory.register("write-xml-0.5", new XmlWriterFactory());
TaskManagerFactory.register("write-xml-change-0.5", new XmlChangeWriterFactory());
TaskManagerFactory.register("write-null-0.5", new NullWriterFactory());
TaskManagerFactory.register("write-null-change-0.5", new NullChangeWriterFactory());
TaskManagerFactory.register("buffer-0.5", new EntityBufferFactory());
TaskManagerFactory.register("buffer-change-0.5", new ChangeBufferFactory());
TaskManagerFactory.register("merge-0.5", new EntityMergerFactory());
TaskManagerFactory.register("merge-change-0.5", new ChangeMergerFactory());
TaskManagerFactory.register("read-api-0.5", new XmlDownloaderFactory());
TaskManagerFactory.register("bounding-polygon-0.5", new PolygonFilterFactory());
TaskManagerFactory.register("report-entity-0.5", new EntityReporterFactory());
TaskManagerFactory.register("report-integrity-0.5", new IntegrityReporterFactory());
TaskManagerFactory.register("write-pgsql-0.5", new PostgreSqlWriterFactory());
TaskManagerFactory.register("truncate-pgsql-0.5", new PostgreSqlTruncatorFactory());
TaskManagerFactory.register("log-progress-0.5", new EntityProgressLoggerFactory());
TaskManagerFactory.register("log-change-progress-0.5", new ChangeProgressLoggerFactory());
TaskManagerFactory.register("tee-0.5", new EntityTeeFactory());
TaskManagerFactory.register("tee-change-0.5", new ChangeTeeFactory());
TaskManagerFactory.register("write-pgsql-dump-0.5", new PostgreSqlDumpWriterFactory());
TaskManagerFactory.register("write-customdb-0.5", new WriteDatasetFactory());
TaskManagerFactory.register("dataset-bounding-box-0.5", new DatasetBoundingBoxFilterFactory());
TaskManagerFactory.register("dataset-dump-0.5", new DumpDatasetFactory());
TaskManagerFactory.register("write-bdb-0.5", new BdbWriterFactory());
TaskManagerFactory.register("read-bdb-0.5", new BdbReaderFactory());
TaskManagerFactory.register("read-customdb-0.5", new ReadDatasetFactory());
}
|
diff --git a/src/com/cole2sworld/ColeBans/GlobalConf.java b/src/com/cole2sworld/ColeBans/GlobalConf.java
index 3729821..e387292 100644
--- a/src/com/cole2sworld/ColeBans/GlobalConf.java
+++ b/src/com/cole2sworld/ColeBans/GlobalConf.java
@@ -1,273 +1,273 @@
package com.cole2sworld.ColeBans;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.logging.Logger;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.FileConfiguration;
/**
* Configuration for ColeBans. Loaded from file on startup.
*
*/
//LOWPRI Check if there is a better way to do this
public final class GlobalConf {
/**
* Configuration we are using.
*/
public static FileConfiguration conf;
/**
* The main ConfigurationSection.
*/
public static ConfigurationSection settings;
/**
* Do we allow tempbans to be made?
*/
public static boolean allowTempBans = true;
/**
* Message when somebody tries to log in but is banned.
*/
public static String banMessage = "You are banned for %reason!";
/**
* Message when somebody tries to log in but is tempbanned.
*/
public static String tempBanMessage = "You are tempbanned! %time seconds remaining!";
/**
* Show fancy effects?
*/
public static boolean fancyEffects = true;
/**
* Color of the disconnect message when banned.
*/
public static String banColor = "DARK_RED";
/**
* Color of the disconnect message when kicked.
*/
public static String kickColor = "YELLOW";
/**
* Color of the disconnect message when tempbanned.
*/
public static String tempBanColor = "RED";
/**
* Announce when somebody is banned/kicked to the entire server?
*/
public static boolean announceBansAndKicks = true;
/**
* Prefix to use in the console.
*/
public static String logPrefix = "[ColeBans] ";
/**
* Which banhandler?
*/
public static String banHandlerConf = "MySQL";
/**
* Configuration section for SQL.
*
*/
public static class Sql {
/**
* The raw section.
*/
public static ConfigurationSection section;
/**
* Username for the database.
*/
public static String user = "minecraft";
/**
* Password for the database.
*/
public static String pass = "password";
/**
* Host for the database.
*/
public static String host = "localhost";
/**
* Port for the database.
*/
public static String port = "3306";
/**
* Database name.
*/
public static String db = "minecraft";
/**
* Table prefix.
*/
public static String prefix = "cb_";
}
/**
* Configuration section for MCBans.
*
*/
public static class MCBans {
/**
* The raw section.
*/
public static ConfigurationSection section;
/**
* The MCBans API key.
*/
public static String apiKey = "yourAPIKeyHere";
/**
* Whether or not to make full dumps of the banlist, including reasons.
*/
public static boolean fullBackups = false;
/**
* Lowest rep you can have and still be able to join.
*/
public static double minRep = 10;
}
/**
* Configuration section for YAML.
*
*/
public static class Yaml {
/**
* The raw section.
*/
public static ConfigurationSection section;
/**
* The file to use.
*/
public static String file;
}
/**
* Configuration section for YAML.
*
*/
public static class Json {
/**
* The raw section.
*/
public static ConfigurationSection section;
/**
* The file to use.
*/
public static String file;
}
/**
* Stuff the user shouldn't touch unless they know what they are doing.
* @author cole2
*
*/
public static class Advanced {
/**
* The raw section.
*/
public static ConfigurationSection section;
/**
* Which package do we get the banhandlers?
*/
public static String pkg;
/**
* What is the suffix on the banhandlers?
*/
public static String suffix;
}
/**
* Loads up the config from disk, or creates it if it does not exist.
*/
public static void loadConfig() throws RuntimeException {
File confFile = new File("./plugins/ColeBans/config.yml");
try {
if (confFile.exists()) {
conf.load(confFile);
try {
settings = conf.getConfigurationSection("settings");
allowTempBans = settings.getBoolean("allowTempBans");
banMessage = settings.getString("banMessage");
tempBanMessage = settings.getString("tempBanMessage");
fancyEffects = settings.getBoolean("fancyEffects");
banColor = settings.getString("banColor");
kickColor = settings.getString("kickColor");
tempBanColor = settings.getString("tempBanColor");
announceBansAndKicks = settings.getBoolean("announceBansAndKicks");
logPrefix = settings.getString("logPrefix")+" ";
Sql.section = settings.getConfigurationSection("mysql");
Sql.user = Sql.section.getString("user");
Sql.pass = Sql.section.getString("pass");
Sql.host = Sql.section.getString("host");
Sql.port = Sql.section.getString("port");
Sql.db = Sql.section.getString("db");
Sql.prefix = Sql.section.getString("prefix");
MCBans.section = settings.getConfigurationSection("mcbans");
MCBans.apiKey = MCBans.section.getString("apiKey");
MCBans.fullBackups = MCBans.section.getBoolean("fullBackups");
MCBans.minRep = MCBans.section.getDouble("minRep");
Advanced.section = settings.getConfigurationSection("advanced");
Advanced.pkg = Advanced.section.getString("package");
Advanced.suffix = Advanced.section.getString("suffix");
}
catch (NullPointerException e) {
Logger.getLogger("Minecraft").severe("[ColeBans] Your config file is outdated! Please delete it to regenerate it!");
Logger.getLogger("Minecraft").severe("[ColeBans] COULD NOT LOAD WORKING CONFIG FILE. Aborting operation.");
Main.instance.onFatal();
}
}
else {
File dir = new File("./plugins/ColeBans");
dir.mkdir();
if (confFile.createNewFile()) {
if (confFile.canWrite()) {
System.out.println("[ColeBans] No config file exists, generating.");
FileOutputStream fos = new FileOutputStream(confFile);
String defaultConfig = ""+
"# For information on how to configure ColeBans, go to http://c2wr.com/cbconf"+
"settings:\n"+
" allowTempBans: true\n"+
" banMessage: You are banned for %reason!\n"+
" tempBanMessage: You are tempbanned! %time minute%plural remaining!\n"+
" fancyEffects: true\n"+
" banColor: DARK_RED\n"+
" kickColor: YELLOW\n"+
" tempBanColor: RED\n"+
" announceBansAndKicks: true\n"+
" logPrefix: [ColeBans]\n"+
" #banHandler can be MySQL, MCBans, YAML, or JSON.\n"+
" banHandler: YAML\n"+
" mysql:\n"+
" user: root\n"+
" pass: pass\n"+
" host: localhost\n"+
" port: 3306\n"+
" db: minecraft\n"+
" prefix: cb_\n"+
" mcbans:\n"+
" ###### THIS LINE IS VERY VERY IMPORTANT IF YOU CHOSE MCBANS FOR THE BAN HANDLER ######\n"+
" apiKey: yourAPIKeyHere\n"+
" # Set this to the BanHandler you want to use for the backups, or \"None\" to turn off backups.\n"+
" backup: true\n"+
" fullBackups: false\n"+
- " #The minimum rep a player can have to join your server."+
- " minRep: 10"+
+ " #The minimum rep a player can have to join your server.\n"+
+ " minRep: 10\n"+
" yaml:\n"+
" fileName: banlist.yml\n"+
" json:\n"+
" fileName: banlist.json\n"+
" advanced:\n" +
" # The package is where to get the ban handlers. Only change this line if you know what you are doing.\n" +
- " package: com.cole2sworld.ColeBans.handlers" +
+ " package: com.cole2sworld.ColeBans.handlers\n" +
" #The suffix is what is at the end of all the ban handlers. Only change this line if you know what you are doing.\n" +
" suffix: BanHandler";
fos.write(defaultConfig.getBytes("utf-8"));
loadConfig();
fos.close();
}
return;
}
else {
Logger.getLogger("Minecraft").severe("[ColeBans] COULD NOT LOAD WORKING CONFIG FILE. Aborting operation.");
Main.instance.onFatal();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InvalidConfigurationException e) {
e.printStackTrace();
}
}
}
| false | true | public static void loadConfig() throws RuntimeException {
File confFile = new File("./plugins/ColeBans/config.yml");
try {
if (confFile.exists()) {
conf.load(confFile);
try {
settings = conf.getConfigurationSection("settings");
allowTempBans = settings.getBoolean("allowTempBans");
banMessage = settings.getString("banMessage");
tempBanMessage = settings.getString("tempBanMessage");
fancyEffects = settings.getBoolean("fancyEffects");
banColor = settings.getString("banColor");
kickColor = settings.getString("kickColor");
tempBanColor = settings.getString("tempBanColor");
announceBansAndKicks = settings.getBoolean("announceBansAndKicks");
logPrefix = settings.getString("logPrefix")+" ";
Sql.section = settings.getConfigurationSection("mysql");
Sql.user = Sql.section.getString("user");
Sql.pass = Sql.section.getString("pass");
Sql.host = Sql.section.getString("host");
Sql.port = Sql.section.getString("port");
Sql.db = Sql.section.getString("db");
Sql.prefix = Sql.section.getString("prefix");
MCBans.section = settings.getConfigurationSection("mcbans");
MCBans.apiKey = MCBans.section.getString("apiKey");
MCBans.fullBackups = MCBans.section.getBoolean("fullBackups");
MCBans.minRep = MCBans.section.getDouble("minRep");
Advanced.section = settings.getConfigurationSection("advanced");
Advanced.pkg = Advanced.section.getString("package");
Advanced.suffix = Advanced.section.getString("suffix");
}
catch (NullPointerException e) {
Logger.getLogger("Minecraft").severe("[ColeBans] Your config file is outdated! Please delete it to regenerate it!");
Logger.getLogger("Minecraft").severe("[ColeBans] COULD NOT LOAD WORKING CONFIG FILE. Aborting operation.");
Main.instance.onFatal();
}
}
else {
File dir = new File("./plugins/ColeBans");
dir.mkdir();
if (confFile.createNewFile()) {
if (confFile.canWrite()) {
System.out.println("[ColeBans] No config file exists, generating.");
FileOutputStream fos = new FileOutputStream(confFile);
String defaultConfig = ""+
"# For information on how to configure ColeBans, go to http://c2wr.com/cbconf"+
"settings:\n"+
" allowTempBans: true\n"+
" banMessage: You are banned for %reason!\n"+
" tempBanMessage: You are tempbanned! %time minute%plural remaining!\n"+
" fancyEffects: true\n"+
" banColor: DARK_RED\n"+
" kickColor: YELLOW\n"+
" tempBanColor: RED\n"+
" announceBansAndKicks: true\n"+
" logPrefix: [ColeBans]\n"+
" #banHandler can be MySQL, MCBans, YAML, or JSON.\n"+
" banHandler: YAML\n"+
" mysql:\n"+
" user: root\n"+
" pass: pass\n"+
" host: localhost\n"+
" port: 3306\n"+
" db: minecraft\n"+
" prefix: cb_\n"+
" mcbans:\n"+
" ###### THIS LINE IS VERY VERY IMPORTANT IF YOU CHOSE MCBANS FOR THE BAN HANDLER ######\n"+
" apiKey: yourAPIKeyHere\n"+
" # Set this to the BanHandler you want to use for the backups, or \"None\" to turn off backups.\n"+
" backup: true\n"+
" fullBackups: false\n"+
" #The minimum rep a player can have to join your server."+
" minRep: 10"+
" yaml:\n"+
" fileName: banlist.yml\n"+
" json:\n"+
" fileName: banlist.json\n"+
" advanced:\n" +
" # The package is where to get the ban handlers. Only change this line if you know what you are doing.\n" +
" package: com.cole2sworld.ColeBans.handlers" +
" #The suffix is what is at the end of all the ban handlers. Only change this line if you know what you are doing.\n" +
" suffix: BanHandler";
fos.write(defaultConfig.getBytes("utf-8"));
loadConfig();
fos.close();
}
return;
}
else {
Logger.getLogger("Minecraft").severe("[ColeBans] COULD NOT LOAD WORKING CONFIG FILE. Aborting operation.");
Main.instance.onFatal();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InvalidConfigurationException e) {
e.printStackTrace();
}
}
| public static void loadConfig() throws RuntimeException {
File confFile = new File("./plugins/ColeBans/config.yml");
try {
if (confFile.exists()) {
conf.load(confFile);
try {
settings = conf.getConfigurationSection("settings");
allowTempBans = settings.getBoolean("allowTempBans");
banMessage = settings.getString("banMessage");
tempBanMessage = settings.getString("tempBanMessage");
fancyEffects = settings.getBoolean("fancyEffects");
banColor = settings.getString("banColor");
kickColor = settings.getString("kickColor");
tempBanColor = settings.getString("tempBanColor");
announceBansAndKicks = settings.getBoolean("announceBansAndKicks");
logPrefix = settings.getString("logPrefix")+" ";
Sql.section = settings.getConfigurationSection("mysql");
Sql.user = Sql.section.getString("user");
Sql.pass = Sql.section.getString("pass");
Sql.host = Sql.section.getString("host");
Sql.port = Sql.section.getString("port");
Sql.db = Sql.section.getString("db");
Sql.prefix = Sql.section.getString("prefix");
MCBans.section = settings.getConfigurationSection("mcbans");
MCBans.apiKey = MCBans.section.getString("apiKey");
MCBans.fullBackups = MCBans.section.getBoolean("fullBackups");
MCBans.minRep = MCBans.section.getDouble("minRep");
Advanced.section = settings.getConfigurationSection("advanced");
Advanced.pkg = Advanced.section.getString("package");
Advanced.suffix = Advanced.section.getString("suffix");
}
catch (NullPointerException e) {
Logger.getLogger("Minecraft").severe("[ColeBans] Your config file is outdated! Please delete it to regenerate it!");
Logger.getLogger("Minecraft").severe("[ColeBans] COULD NOT LOAD WORKING CONFIG FILE. Aborting operation.");
Main.instance.onFatal();
}
}
else {
File dir = new File("./plugins/ColeBans");
dir.mkdir();
if (confFile.createNewFile()) {
if (confFile.canWrite()) {
System.out.println("[ColeBans] No config file exists, generating.");
FileOutputStream fos = new FileOutputStream(confFile);
String defaultConfig = ""+
"# For information on how to configure ColeBans, go to http://c2wr.com/cbconf"+
"settings:\n"+
" allowTempBans: true\n"+
" banMessage: You are banned for %reason!\n"+
" tempBanMessage: You are tempbanned! %time minute%plural remaining!\n"+
" fancyEffects: true\n"+
" banColor: DARK_RED\n"+
" kickColor: YELLOW\n"+
" tempBanColor: RED\n"+
" announceBansAndKicks: true\n"+
" logPrefix: [ColeBans]\n"+
" #banHandler can be MySQL, MCBans, YAML, or JSON.\n"+
" banHandler: YAML\n"+
" mysql:\n"+
" user: root\n"+
" pass: pass\n"+
" host: localhost\n"+
" port: 3306\n"+
" db: minecraft\n"+
" prefix: cb_\n"+
" mcbans:\n"+
" ###### THIS LINE IS VERY VERY IMPORTANT IF YOU CHOSE MCBANS FOR THE BAN HANDLER ######\n"+
" apiKey: yourAPIKeyHere\n"+
" # Set this to the BanHandler you want to use for the backups, or \"None\" to turn off backups.\n"+
" backup: true\n"+
" fullBackups: false\n"+
" #The minimum rep a player can have to join your server.\n"+
" minRep: 10\n"+
" yaml:\n"+
" fileName: banlist.yml\n"+
" json:\n"+
" fileName: banlist.json\n"+
" advanced:\n" +
" # The package is where to get the ban handlers. Only change this line if you know what you are doing.\n" +
" package: com.cole2sworld.ColeBans.handlers\n" +
" #The suffix is what is at the end of all the ban handlers. Only change this line if you know what you are doing.\n" +
" suffix: BanHandler";
fos.write(defaultConfig.getBytes("utf-8"));
loadConfig();
fos.close();
}
return;
}
else {
Logger.getLogger("Minecraft").severe("[ColeBans] COULD NOT LOAD WORKING CONFIG FILE. Aborting operation.");
Main.instance.onFatal();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InvalidConfigurationException e) {
e.printStackTrace();
}
}
|
diff --git a/framework/src/play/i18n/Lang.java b/framework/src/play/i18n/Lang.java
index bf79156c..bb99aca5 100644
--- a/framework/src/play/i18n/Lang.java
+++ b/framework/src/play/i18n/Lang.java
@@ -1,157 +1,157 @@
package play.i18n;
import java.util.Locale;
import play.Logger;
import play.Play;
import play.mvc.Http;
import play.mvc.Http.Request;
import play.mvc.Http.Response;
/**
* Language support
*/
public class Lang {
public static ThreadLocal<String> current = new ThreadLocal<String>();
/**
* Retrieve the current language or null
* @return The current language (fr, ja, it ...) or null
*/
public static String get() {
String locale = current.get();
if (locale == null) {
// don't have current locale for this request - must try to resolve it
Http.Request currentRequest = Http.Request.current();
if (currentRequest!=null) {
// we have a current request - lets try to resolve language from it
resolvefrom( currentRequest );
} else {
// don't have current request - just use default
setDefaultLocale();
}
// get the picked locale
locale = current.get();
}
return locale;
}
/**
* Force the current language
* @param locale (fr, ja, it ...)
* @return false if the language is not supported by the application
*/
public static boolean set(String locale) {
if (locale.equals("") || Play.langs.contains(locale)) {
current.set(locale);
return true;
} else {
Logger.warn("Locale %s is not defined in your application.conf", locale);
return false;
}
}
/**
* Clears the current language - This wil trigger resolving language from request
* if not manually set.
*/
public static void clear() {
current.remove();
}
/**
* Change language for next requests
* @param locale (fr, ja, it ...)
*/
public static void change(String locale) {
if (set(locale)) {
Response.current().setCookie(Play.configuration.getProperty("application.lang.cookie", "PLAY_LANG"), locale);
}
}
/**
* Guess the language for current request in the following order:
* <ol>
* <li>if a <b>PLAY_LANG</b> cookie is set, use this value</li>
* <li>if <b>Accept-Language</b> header is set, use it only if the Play! application allows it.<br/>supported language may be defined in application configuration, eg : <em>play.langs=fr,en,de)</em></li>
* <li>otherwise, server's locale language is assumed
* </ol>
* @param request
*/
private static void resolvefrom(Request request) {
// Check a cookie
String cn = Play.configuration.getProperty("application.lang.cookie", "PLAY_LANG");
if (request.cookies.containsKey(cn)) {
String localeFromCookie = request.cookies.get(cn).value;
if (localeFromCookie != null && localeFromCookie.trim().length()>0) {
if (set(localeFromCookie)) {
// we're using locale from cookie
return;
}
// could not use locale from cookie - clear the locale-cookie
Response.current().setCookie(cn, "");
}
}
// Try from accept-language - look for an exact match
for (String a: request.acceptLanguage()) {
a = a.replace("-", "_").toLowerCase();
for (String locale: Play.langs) {
if (locale.toLowerCase().equals(a)) {
set(locale);
return;
}
}
}
- // now see if we have a country-only match
+ // now see if we have a language-only match
for (String a: request.acceptLanguage()) {
if (a.indexOf("-") > 0) {
a = a.substring(0, a.indexOf("-"));
}
for (String locale: Play.langs) {
if (locale.equals(a)) {
set(locale);
return;
}
}
}
// Use default
setDefaultLocale();
}
public static void setDefaultLocale() {
if (Play.langs.isEmpty()) {
set("");
} else {
set(Play.langs.get(0));
}
}
/**
*
* @return the default locale if the Locale cannot be found otherwise the locale
* associated to the current Lang.
*/
public static Locale getLocale() {
String lang = get();
Locale locale = getLocale(lang);
if (locale != null) {
return locale;
}
return Locale.getDefault();
}
public static Locale getLocale(String lang) {
for (Locale locale : Locale.getAvailableLocales()) {
if (locale.getLanguage().equals(lang)) {
return locale;
}
}
return null;
}
}
| true | true | private static void resolvefrom(Request request) {
// Check a cookie
String cn = Play.configuration.getProperty("application.lang.cookie", "PLAY_LANG");
if (request.cookies.containsKey(cn)) {
String localeFromCookie = request.cookies.get(cn).value;
if (localeFromCookie != null && localeFromCookie.trim().length()>0) {
if (set(localeFromCookie)) {
// we're using locale from cookie
return;
}
// could not use locale from cookie - clear the locale-cookie
Response.current().setCookie(cn, "");
}
}
// Try from accept-language - look for an exact match
for (String a: request.acceptLanguage()) {
a = a.replace("-", "_").toLowerCase();
for (String locale: Play.langs) {
if (locale.toLowerCase().equals(a)) {
set(locale);
return;
}
}
}
// now see if we have a country-only match
for (String a: request.acceptLanguage()) {
if (a.indexOf("-") > 0) {
a = a.substring(0, a.indexOf("-"));
}
for (String locale: Play.langs) {
if (locale.equals(a)) {
set(locale);
return;
}
}
}
// Use default
setDefaultLocale();
}
| private static void resolvefrom(Request request) {
// Check a cookie
String cn = Play.configuration.getProperty("application.lang.cookie", "PLAY_LANG");
if (request.cookies.containsKey(cn)) {
String localeFromCookie = request.cookies.get(cn).value;
if (localeFromCookie != null && localeFromCookie.trim().length()>0) {
if (set(localeFromCookie)) {
// we're using locale from cookie
return;
}
// could not use locale from cookie - clear the locale-cookie
Response.current().setCookie(cn, "");
}
}
// Try from accept-language - look for an exact match
for (String a: request.acceptLanguage()) {
a = a.replace("-", "_").toLowerCase();
for (String locale: Play.langs) {
if (locale.toLowerCase().equals(a)) {
set(locale);
return;
}
}
}
// now see if we have a language-only match
for (String a: request.acceptLanguage()) {
if (a.indexOf("-") > 0) {
a = a.substring(0, a.indexOf("-"));
}
for (String locale: Play.langs) {
if (locale.equals(a)) {
set(locale);
return;
}
}
}
// Use default
setDefaultLocale();
}
|
diff --git a/src/ch06/pp6_11/LinesPanel.java b/src/ch06/pp6_11/LinesPanel.java
index e748bce..4333f34 100644
--- a/src/ch06/pp6_11/LinesPanel.java
+++ b/src/ch06/pp6_11/LinesPanel.java
@@ -1,61 +1,61 @@
/* Copyright (C) 2013 Travis Mosley <[email protected]>
*
* PP 6.11 Design and implement a program that draws 20 horizontal,
* evenly spaced parallel lines of random length.
*
* Page 298
*/
package ch06.pp6_11;
import javax.swing.JPanel;
import java.awt.*;
import java.util.Random;
public class LinesPanel extends JPanel
{
private final int MAX_LENGTH = 100;
private final int MAX_NUM_LINES = 20;
private final int SPACING = 40;
private int window_dim_x; // The window's width in pixels
private int window_dim_y; // The window's height in pixels
private Random gen;
public LinesPanel()
{
gen = new Random();
window_dim_x = 400;
window_dim_y = 300;
setBackground(Color.black);
setPreferredSize(new Dimension(window_dim_x, window_dim_y));
}
public LinesPanel(int win_dim_x, int win_dim_y)
{
gen = new Random();
window_dim_x = win_dim_x;
window_dim_y = win_dim_y;
setBackground(Color.black);
setPreferredSize(new Dimension(window_dim_x, window_dim_y));
}
// Draws MAX_NUM_LINES evenly spaced horizontal lines parallel
// lines of random length.
public void paintComponent(Graphics page) {
super.paintComponent(page);
int lines_drawn = 0;
int x = 0;
int line_height;
page.setColor(Color.white);
while(lines_drawn < 20)
{
- goddamn_solution = gen.nextInt(MAX_LENGTH+2) + 2;
+ line_height = gen.nextInt(MAX_LENGTH+2) + 2;
page.fillRect(x, window_dim_y+line_height, 2, line_height);
x += SPACING;
lines_drawn++;
}
}
}
| true | true | public void paintComponent(Graphics page) {
super.paintComponent(page);
int lines_drawn = 0;
int x = 0;
int line_height;
page.setColor(Color.white);
while(lines_drawn < 20)
{
goddamn_solution = gen.nextInt(MAX_LENGTH+2) + 2;
page.fillRect(x, window_dim_y+line_height, 2, line_height);
x += SPACING;
lines_drawn++;
}
}
| public void paintComponent(Graphics page) {
super.paintComponent(page);
int lines_drawn = 0;
int x = 0;
int line_height;
page.setColor(Color.white);
while(lines_drawn < 20)
{
line_height = gen.nextInt(MAX_LENGTH+2) + 2;
page.fillRect(x, window_dim_y+line_height, 2, line_height);
x += SPACING;
lines_drawn++;
}
}
|
diff --git a/AI.java b/AI.java
index fa3b0e2..e536f24 100644
--- a/AI.java
+++ b/AI.java
@@ -1,287 +1,287 @@
import java.awt.Point;
import java.util.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class AI {
AI() {}
static private final int BLACKPIECE = -1;
static private final int WHITEPIECE = 1;
static private final int EMPTYSPOT = 0;
static public int MAX_GRID_WIDTH_INDEX;
static public int MAX_GRID_HEIGHT_INDEX;
static Boolean gameOver(int[][] gameState){
int blackPieces = 0;
int whitePieces = 0;
for (int x = 0; x < MAX_GRID_WIDTH_INDEX+1; x++){
for (int y = 0; y < MAX_GRID_HEIGHT_INDEX+1; y++){
if(gameState[x][y] == 1) whitePieces++;
if(gameState[x][y] == -1) blackPieces++;
}
}
if( (whitePieces == 0) || (blackPieces == 0) ) return true;
return false;
}
static void setBounds(int rowSize, int columnSize){
MAX_GRID_WIDTH_INDEX = rowSize;
MAX_GRID_HEIGHT_INDEX = columnSize;
}
static int evaluateBoard(int[][] gameState){
int value = 0;
for (int x = 0; x < MAX_GRID_WIDTH_INDEX+1; x++){
for (int y = 0; y < MAX_GRID_HEIGHT_INDEX+1; y++){
if(gameState[x][y] == 1) value++;
if(gameState[x][y] == -1) value--;
}
}
return value;
}
static public Boolean aiIsOnGrid(Point move) {
if(move.x < 1 || move.x > MAX_GRID_WIDTH_INDEX+1) return false;
if(move.y < 1 || move.y > MAX_GRID_HEIGHT_INDEX+1) return false;
return true;
}
static ArrayList<Move> getValidMoves(int[][] gameState) {//{{{
int movingColor = 0;
int fwdColor = 0;
int bkwdColor = 0;
ArrayList<Point> blackPawnLocations = new ArrayList<Point>();
ArrayList<Move> validMoves = new ArrayList<Move>();
//For our current board, we want to find all of the black pawns on the board.
for (int x = 0; x < MAX_GRID_WIDTH_INDEX+1; x++){
for (int y = 0; y < MAX_GRID_HEIGHT_INDEX+1; y++){
if(gameState[x][y] == BLACKPIECE){
blackPawnLocations.add(new Point(x + 1,y + 1));
}
}
}
System.out.println("Number of black pawns: " + blackPawnLocations.size());
for (Point startLocation: blackPawnLocations){
List<Point> adjacentMoves = Grid.getAdjacentPoints(startLocation);
for(Point adjacentMove: adjacentMoves){
if(aiIsOnGrid(adjacentMove) && (gameState[adjacentMove.x-1][adjacentMove.y-1] == EMPTYSPOT) ){
Point fwdMove = Vector.subtract(adjacentMove,startLocation);
Point fwdTarPt = Vector.add(adjacentMove,fwdMove);
Point bkwdMove = Vector.subtract(startLocation,adjacentMove);
Point bkwdTarPt = Vector.add(startLocation,bkwdMove);
movingColor = gameState[startLocation.x-1][startLocation.y-1];
if(aiIsOnGrid(fwdTarPt)){
fwdColor = gameState[fwdTarPt.x-1][fwdTarPt.y-1];
if( (movingColor != fwdColor) && (fwdColor != EMPTYSPOT) )
validMoves.add(new Move(startLocation.x, startLocation.y, adjacentMove.x, adjacentMove.y) );
}
else if(aiIsOnGrid(bkwdTarPt)){
bkwdColor = gameState[bkwdTarPt.x-1][bkwdTarPt.y-1];
if( (movingColor != bkwdColor) && (bkwdColor != EMPTYSPOT) )
validMoves.add(new Move(startLocation.x, startLocation.y, adjacentMove.x, adjacentMove.y) );
}
}
}
}
return validMoves;
}
static ArrayList<Move> getValidPaikaMoves(int[][] gameState) {//{{{
ArrayList<Point> blackPawnLocations = new ArrayList<Point>();
ArrayList<Move> validMoves = new ArrayList<Move>();
for (int x = 0; x < MAX_GRID_WIDTH_INDEX+1; x++){
for (int y = 0; y < MAX_GRID_HEIGHT_INDEX+1; y++){
if(gameState[x][y] == BLACKPIECE){
blackPawnLocations.add(new Point(x + 1,y + 1));
}
}
}
for (Point startLocation: blackPawnLocations){
List<Point> adjacentMoves = Grid.getAdjacentPoints(startLocation);
for(Point adjacentMove: adjacentMoves){
if(aiIsOnGrid(adjacentMove) && (gameState[adjacentMove.x-1][adjacentMove.y-1] == EMPTYSPOT) )
validMoves.add(new Move(startLocation.x, startLocation.y, adjacentMove.x, adjacentMove.y) );
}
}
return validMoves;
}
static public Move minimax (int[][] gameBoard){
int[][] nextBoard;
int value, maxValue = Integer.MIN_VALUE;
Move bestMove = new Move();
ArrayList<Move> possibleMoveList = getValidMoves(gameBoard);
if(possibleMoveList.size() != 0) bestMove = new Move(possibleMoveList.get(0));
for (Move possibleMove: possibleMoveList){
nextBoard = (int[][]) gameBoard.clone();
nextBoard = possibleMove.makeMove(gameBoard);
value = minMove(nextBoard, 5, maxValue, Integer.MAX_VALUE);
if (value > maxValue) {
System.out.println ("Max value : " + value + " at depth : 0");
maxValue = value;
bestMove = new Move(possibleMove);
}
}
System.out.println ("Move value selected : " + maxValue + " at depth : 0");
return bestMove;
}
static public int maxMove (int[][] gameBoard, int depth, int alpha, int beta){
if ( gameOver(gameBoard) || depth <= 0 ) return evaluateBoard(gameBoard);
int[][] nextBoard;
int value;
ArrayList<Move> possibleMoveList = getValidMoves(gameBoard);
System.out.println ("Max node at depth : " + depth + " with alpha : " + alpha +
" beta : " + beta);
for (Move possibleMove: possibleMoveList){
nextBoard = (int[][]) gameBoard.clone();
nextBoard = possibleMove.makeMove(gameBoard);
value = minMove (nextBoard, depth - 1, alpha, beta);
if (value > alpha) {
alpha = value;
System.out.println ("Max value : " + value + " at depth : " + depth);
}
if (alpha > beta) {
- System.out.println ("Max value with prunning : " + beta + " at depth : " + depth);
+ System.out.println ("Max value with pruning : " + beta + " at depth : " + depth);
return beta;
}
}
System.out.println ("Max value selected : " + alpha + " at depth : " + depth);
return alpha;
}
static public int minMove (int[][] gameBoard, int depth, int alpha, int beta){
if ( gameOver(gameBoard) || depth <= 0 ) return evaluateBoard(gameBoard);
int[][] nextBoard;
int value;
ArrayList<Move> possibleMoveList = getValidMoves(gameBoard);
System.out.println ("Min node at depth : " + depth + " with alpha : " + alpha +
" beta : " + beta);
for (Move possibleMove: possibleMoveList){
nextBoard = (int[][]) gameBoard.clone();
nextBoard = possibleMove.makeMove(gameBoard);
value = maxMove (nextBoard, depth - 1, alpha, beta);
if (value < beta) {
beta = value;
System.out.println ("Min value : " + value + " at depth : " + depth);
}
if (beta < alpha) {
- System.out.println ("Min value with prunning : " + alpha + " at depth : " + depth);
+ System.out.println ("Min value with pruning : " + alpha + " at depth : " + depth);
return alpha;
}
}
System.out.println ("Min value selected : " + beta + " at depth : " + depth);
return beta;
}
static public Move getMove(int[][] gridState) {
//returns a Move which is 2 pts: start & end
Random rand = new Random();
int min = 0;
int max = 0;
int randomNum = 0;
ArrayList<Move> captureMoves = getValidMoves(gridState);
if( captureMoves.size() != 0){
return minimax(gridState);
}
else{
ArrayList<Move> paikaMoves = getValidPaikaMoves(gridState);
max = paikaMoves.size() - 1;
randomNum = rand.nextInt(max - min + 1) + min;
Move bestMove = paikaMoves.get(randomNum);
return bestMove;
}
}
static public Move getDoubleMove(int[][] gridState, Point selectedPiece, List<Point> validEndPts) {
Random rand = new Random();
int min = 0;
int max = validEndPts.size() - 1;
int randomNum = rand.nextInt(max - min + 1) + min;
Point endPoint = validEndPts.get(randomNum);
Move bestMove = new Move(selectedPiece.x, selectedPiece.y, endPoint.x, endPoint.y);
return bestMove;
}
}
| false | true | static ArrayList<Move> getValidMoves(int[][] gameState) {//{{{
int movingColor = 0;
int fwdColor = 0;
int bkwdColor = 0;
ArrayList<Point> blackPawnLocations = new ArrayList<Point>();
ArrayList<Move> validMoves = new ArrayList<Move>();
//For our current board, we want to find all of the black pawns on the board.
for (int x = 0; x < MAX_GRID_WIDTH_INDEX+1; x++){
for (int y = 0; y < MAX_GRID_HEIGHT_INDEX+1; y++){
if(gameState[x][y] == BLACKPIECE){
blackPawnLocations.add(new Point(x + 1,y + 1));
}
}
}
System.out.println("Number of black pawns: " + blackPawnLocations.size());
for (Point startLocation: blackPawnLocations){
List<Point> adjacentMoves = Grid.getAdjacentPoints(startLocation);
for(Point adjacentMove: adjacentMoves){
if(aiIsOnGrid(adjacentMove) && (gameState[adjacentMove.x-1][adjacentMove.y-1] == EMPTYSPOT) ){
Point fwdMove = Vector.subtract(adjacentMove,startLocation);
Point fwdTarPt = Vector.add(adjacentMove,fwdMove);
Point bkwdMove = Vector.subtract(startLocation,adjacentMove);
Point bkwdTarPt = Vector.add(startLocation,bkwdMove);
movingColor = gameState[startLocation.x-1][startLocation.y-1];
if(aiIsOnGrid(fwdTarPt)){
fwdColor = gameState[fwdTarPt.x-1][fwdTarPt.y-1];
if( (movingColor != fwdColor) && (fwdColor != EMPTYSPOT) )
validMoves.add(new Move(startLocation.x, startLocation.y, adjacentMove.x, adjacentMove.y) );
}
else if(aiIsOnGrid(bkwdTarPt)){
bkwdColor = gameState[bkwdTarPt.x-1][bkwdTarPt.y-1];
if( (movingColor != bkwdColor) && (bkwdColor != EMPTYSPOT) )
validMoves.add(new Move(startLocation.x, startLocation.y, adjacentMove.x, adjacentMove.y) );
}
}
}
}
return validMoves;
}
static ArrayList<Move> getValidPaikaMoves(int[][] gameState) {//{{{
ArrayList<Point> blackPawnLocations = new ArrayList<Point>();
ArrayList<Move> validMoves = new ArrayList<Move>();
for (int x = 0; x < MAX_GRID_WIDTH_INDEX+1; x++){
for (int y = 0; y < MAX_GRID_HEIGHT_INDEX+1; y++){
if(gameState[x][y] == BLACKPIECE){
blackPawnLocations.add(new Point(x + 1,y + 1));
}
}
}
for (Point startLocation: blackPawnLocations){
List<Point> adjacentMoves = Grid.getAdjacentPoints(startLocation);
for(Point adjacentMove: adjacentMoves){
if(aiIsOnGrid(adjacentMove) && (gameState[adjacentMove.x-1][adjacentMove.y-1] == EMPTYSPOT) )
validMoves.add(new Move(startLocation.x, startLocation.y, adjacentMove.x, adjacentMove.y) );
}
}
return validMoves;
}
static public Move minimax (int[][] gameBoard){
int[][] nextBoard;
int value, maxValue = Integer.MIN_VALUE;
Move bestMove = new Move();
ArrayList<Move> possibleMoveList = getValidMoves(gameBoard);
if(possibleMoveList.size() != 0) bestMove = new Move(possibleMoveList.get(0));
for (Move possibleMove: possibleMoveList){
nextBoard = (int[][]) gameBoard.clone();
nextBoard = possibleMove.makeMove(gameBoard);
value = minMove(nextBoard, 5, maxValue, Integer.MAX_VALUE);
if (value > maxValue) {
System.out.println ("Max value : " + value + " at depth : 0");
maxValue = value;
bestMove = new Move(possibleMove);
}
}
System.out.println ("Move value selected : " + maxValue + " at depth : 0");
return bestMove;
}
static public int maxMove (int[][] gameBoard, int depth, int alpha, int beta){
if ( gameOver(gameBoard) || depth <= 0 ) return evaluateBoard(gameBoard);
int[][] nextBoard;
int value;
ArrayList<Move> possibleMoveList = getValidMoves(gameBoard);
System.out.println ("Max node at depth : " + depth + " with alpha : " + alpha +
" beta : " + beta);
for (Move possibleMove: possibleMoveList){
nextBoard = (int[][]) gameBoard.clone();
nextBoard = possibleMove.makeMove(gameBoard);
value = minMove (nextBoard, depth - 1, alpha, beta);
if (value > alpha) {
alpha = value;
System.out.println ("Max value : " + value + " at depth : " + depth);
}
if (alpha > beta) {
System.out.println ("Max value with prunning : " + beta + " at depth : " + depth);
return beta;
}
}
System.out.println ("Max value selected : " + alpha + " at depth : " + depth);
return alpha;
}
static public int minMove (int[][] gameBoard, int depth, int alpha, int beta){
if ( gameOver(gameBoard) || depth <= 0 ) return evaluateBoard(gameBoard);
int[][] nextBoard;
int value;
ArrayList<Move> possibleMoveList = getValidMoves(gameBoard);
System.out.println ("Min node at depth : " + depth + " with alpha : " + alpha +
" beta : " + beta);
for (Move possibleMove: possibleMoveList){
nextBoard = (int[][]) gameBoard.clone();
nextBoard = possibleMove.makeMove(gameBoard);
value = maxMove (nextBoard, depth - 1, alpha, beta);
if (value < beta) {
beta = value;
System.out.println ("Min value : " + value + " at depth : " + depth);
}
if (beta < alpha) {
System.out.println ("Min value with prunning : " + alpha + " at depth : " + depth);
return alpha;
}
}
System.out.println ("Min value selected : " + beta + " at depth : " + depth);
return beta;
}
static public Move getMove(int[][] gridState) {
//returns a Move which is 2 pts: start & end
Random rand = new Random();
int min = 0;
int max = 0;
int randomNum = 0;
ArrayList<Move> captureMoves = getValidMoves(gridState);
if( captureMoves.size() != 0){
return minimax(gridState);
}
else{
ArrayList<Move> paikaMoves = getValidPaikaMoves(gridState);
max = paikaMoves.size() - 1;
randomNum = rand.nextInt(max - min + 1) + min;
Move bestMove = paikaMoves.get(randomNum);
return bestMove;
}
}
static public Move getDoubleMove(int[][] gridState, Point selectedPiece, List<Point> validEndPts) {
Random rand = new Random();
int min = 0;
int max = validEndPts.size() - 1;
int randomNum = rand.nextInt(max - min + 1) + min;
Point endPoint = validEndPts.get(randomNum);
Move bestMove = new Move(selectedPiece.x, selectedPiece.y, endPoint.x, endPoint.y);
return bestMove;
}
}
| static ArrayList<Move> getValidMoves(int[][] gameState) {//{{{
int movingColor = 0;
int fwdColor = 0;
int bkwdColor = 0;
ArrayList<Point> blackPawnLocations = new ArrayList<Point>();
ArrayList<Move> validMoves = new ArrayList<Move>();
//For our current board, we want to find all of the black pawns on the board.
for (int x = 0; x < MAX_GRID_WIDTH_INDEX+1; x++){
for (int y = 0; y < MAX_GRID_HEIGHT_INDEX+1; y++){
if(gameState[x][y] == BLACKPIECE){
blackPawnLocations.add(new Point(x + 1,y + 1));
}
}
}
System.out.println("Number of black pawns: " + blackPawnLocations.size());
for (Point startLocation: blackPawnLocations){
List<Point> adjacentMoves = Grid.getAdjacentPoints(startLocation);
for(Point adjacentMove: adjacentMoves){
if(aiIsOnGrid(adjacentMove) && (gameState[adjacentMove.x-1][adjacentMove.y-1] == EMPTYSPOT) ){
Point fwdMove = Vector.subtract(adjacentMove,startLocation);
Point fwdTarPt = Vector.add(adjacentMove,fwdMove);
Point bkwdMove = Vector.subtract(startLocation,adjacentMove);
Point bkwdTarPt = Vector.add(startLocation,bkwdMove);
movingColor = gameState[startLocation.x-1][startLocation.y-1];
if(aiIsOnGrid(fwdTarPt)){
fwdColor = gameState[fwdTarPt.x-1][fwdTarPt.y-1];
if( (movingColor != fwdColor) && (fwdColor != EMPTYSPOT) )
validMoves.add(new Move(startLocation.x, startLocation.y, adjacentMove.x, adjacentMove.y) );
}
else if(aiIsOnGrid(bkwdTarPt)){
bkwdColor = gameState[bkwdTarPt.x-1][bkwdTarPt.y-1];
if( (movingColor != bkwdColor) && (bkwdColor != EMPTYSPOT) )
validMoves.add(new Move(startLocation.x, startLocation.y, adjacentMove.x, adjacentMove.y) );
}
}
}
}
return validMoves;
}
static ArrayList<Move> getValidPaikaMoves(int[][] gameState) {//{{{
ArrayList<Point> blackPawnLocations = new ArrayList<Point>();
ArrayList<Move> validMoves = new ArrayList<Move>();
for (int x = 0; x < MAX_GRID_WIDTH_INDEX+1; x++){
for (int y = 0; y < MAX_GRID_HEIGHT_INDEX+1; y++){
if(gameState[x][y] == BLACKPIECE){
blackPawnLocations.add(new Point(x + 1,y + 1));
}
}
}
for (Point startLocation: blackPawnLocations){
List<Point> adjacentMoves = Grid.getAdjacentPoints(startLocation);
for(Point adjacentMove: adjacentMoves){
if(aiIsOnGrid(adjacentMove) && (gameState[adjacentMove.x-1][adjacentMove.y-1] == EMPTYSPOT) )
validMoves.add(new Move(startLocation.x, startLocation.y, adjacentMove.x, adjacentMove.y) );
}
}
return validMoves;
}
static public Move minimax (int[][] gameBoard){
int[][] nextBoard;
int value, maxValue = Integer.MIN_VALUE;
Move bestMove = new Move();
ArrayList<Move> possibleMoveList = getValidMoves(gameBoard);
if(possibleMoveList.size() != 0) bestMove = new Move(possibleMoveList.get(0));
for (Move possibleMove: possibleMoveList){
nextBoard = (int[][]) gameBoard.clone();
nextBoard = possibleMove.makeMove(gameBoard);
value = minMove(nextBoard, 5, maxValue, Integer.MAX_VALUE);
if (value > maxValue) {
System.out.println ("Max value : " + value + " at depth : 0");
maxValue = value;
bestMove = new Move(possibleMove);
}
}
System.out.println ("Move value selected : " + maxValue + " at depth : 0");
return bestMove;
}
static public int maxMove (int[][] gameBoard, int depth, int alpha, int beta){
if ( gameOver(gameBoard) || depth <= 0 ) return evaluateBoard(gameBoard);
int[][] nextBoard;
int value;
ArrayList<Move> possibleMoveList = getValidMoves(gameBoard);
System.out.println ("Max node at depth : " + depth + " with alpha : " + alpha +
" beta : " + beta);
for (Move possibleMove: possibleMoveList){
nextBoard = (int[][]) gameBoard.clone();
nextBoard = possibleMove.makeMove(gameBoard);
value = minMove (nextBoard, depth - 1, alpha, beta);
if (value > alpha) {
alpha = value;
System.out.println ("Max value : " + value + " at depth : " + depth);
}
if (alpha > beta) {
System.out.println ("Max value with pruning : " + beta + " at depth : " + depth);
return beta;
}
}
System.out.println ("Max value selected : " + alpha + " at depth : " + depth);
return alpha;
}
static public int minMove (int[][] gameBoard, int depth, int alpha, int beta){
if ( gameOver(gameBoard) || depth <= 0 ) return evaluateBoard(gameBoard);
int[][] nextBoard;
int value;
ArrayList<Move> possibleMoveList = getValidMoves(gameBoard);
System.out.println ("Min node at depth : " + depth + " with alpha : " + alpha +
" beta : " + beta);
for (Move possibleMove: possibleMoveList){
nextBoard = (int[][]) gameBoard.clone();
nextBoard = possibleMove.makeMove(gameBoard);
value = maxMove (nextBoard, depth - 1, alpha, beta);
if (value < beta) {
beta = value;
System.out.println ("Min value : " + value + " at depth : " + depth);
}
if (beta < alpha) {
System.out.println ("Min value with pruning : " + alpha + " at depth : " + depth);
return alpha;
}
}
System.out.println ("Min value selected : " + beta + " at depth : " + depth);
return beta;
}
static public Move getMove(int[][] gridState) {
//returns a Move which is 2 pts: start & end
Random rand = new Random();
int min = 0;
int max = 0;
int randomNum = 0;
ArrayList<Move> captureMoves = getValidMoves(gridState);
if( captureMoves.size() != 0){
return minimax(gridState);
}
else{
ArrayList<Move> paikaMoves = getValidPaikaMoves(gridState);
max = paikaMoves.size() - 1;
randomNum = rand.nextInt(max - min + 1) + min;
Move bestMove = paikaMoves.get(randomNum);
return bestMove;
}
}
static public Move getDoubleMove(int[][] gridState, Point selectedPiece, List<Point> validEndPts) {
Random rand = new Random();
int min = 0;
int max = validEndPts.size() - 1;
int randomNum = rand.nextInt(max - min + 1) + min;
Point endPoint = validEndPts.get(randomNum);
Move bestMove = new Move(selectedPiece.x, selectedPiece.y, endPoint.x, endPoint.y);
return bestMove;
}
}
|
diff --git a/src/Quote.java b/src/Quote.java
index 19b7035..e6d363d 100644
--- a/src/Quote.java
+++ b/src/Quote.java
@@ -1,121 +1,121 @@
import java.sql.Date;
import java.sql.SQLException;
import plugin.PluginTemp;
import program.Database;
import program.IRC;
public class Quote implements PluginTemp
{
@Override
public void onCreate(String in_str)
{
// TODO Auto-generated method stub
}
@Override
public void onTime(String in_str)
{
// TODO Auto-generated method stub
}
@Override
public void onMessage(String in_str)
{
String temp[] = in_str.split(":"),
message, host, user, channel;
message = temp[2];
temp = temp[1].split("!");
user = temp[0];
temp = temp[1].split(" ");
host = temp[0];
channel = temp[2];
try
{
if (message.matches("^[A-Za-z0-9]+([\\+]){2,2}"))
{
Database.updateRep(message.substring(0, message.length()-2), +1);
IRC.sendServer("PRIVMSG " + channel + " " + message.substring(0, message.length()-2) + ": Rep = " + Database.getUserRep(message.substring(0, message.length()-2)) + "!");
}
else if (message.matches("^[A-Za-z0-9]+([\\-]){2,2}"))
{
Database.updateRep(message.substring(0, message.length()-2), -1);
IRC.sendServer("PRIVMSG " + channel + " " + message.substring(0, message.length()-2) + ": Rep = " + Database.getUserRep(message.substring(0, message.length()-2)) + "!");
}
else if (message.matches("^.rep")||message.matches("^.rep [A-Za-z0-9#]+$"))
{
String[] t = message.split(" ");
if (t.length <= 0||t[1] == null)
IRC.sendServer("PRIVMSG " + channel + " " + user + ": Rep = " + Database.getUserRep(user) + "!");
else
IRC.sendServer("PRIVMSG " + channel + " " + t[1] + ": Rep = " + Database.getUserRep(t[1]) + "!");
}
- else if (message.matches("^.msgsent")||message.matches("^.msgsent [A-Za-z0-9#]+$"))
+ else if (message.matches("^.msgsent [A-Za-z0-9#]+$"))
{
String[] t = message.split(" ");
if (t.length <= 0||t[1] == null)
IRC.sendServer("PRIVMSG " + channel + " " + user + ": Messages Sent = " + Database.getMessagesSent(user) + "!");
else
IRC.sendServer("PRIVMSG " + channel + " " + t[1] + ": Messages Sent = " + Database.getMessagesSent(t[1]) + "!");
}
else if (message.matches("^.lastonline [A-Za-z0-9#]+$"))
{
String[] t = message.split(" ");
if (t.length > 0||t[1] != null)
IRC.sendServer("PRIVMSG " + channel + " " + t[1] + ": Last Online = " + Database.getLastOnline(t[1]) + "!");
}
else if (message.matches("\\.remind .* \".*\"")||message.matches("\\.remind .* '.*'"))
{
String[] t = message.split("'");
if (message.matches("\\.remind .* \".*\""))
t = message.split("\"");
String[] tt = t[0].split(" ");
Database.addReminder(user, tt[1], t[1]);
IRC.sendServer("PRIVMSG " + channel + " " + user + ": I will remind them next time they are round master!");
}
else
{
String[] reminders = Database.getReminders(user);
if (reminders.length > 0)
{
for (int i = 0; i < reminders.length;i++)
{
IRC.sendServer("PRIVMSG " + channel + " " + reminders[i]);
Database.delReminder(user);
}
}
Database.updateUser(user);
}
}
catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (ClassNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void onJoin(String in_str)
{
// TODO Auto-generated method stub
}
@Override
public void onQuit(String in_str)
{
// TODO Auto-generated method stub
}
}
| true | true | public void onMessage(String in_str)
{
String temp[] = in_str.split(":"),
message, host, user, channel;
message = temp[2];
temp = temp[1].split("!");
user = temp[0];
temp = temp[1].split(" ");
host = temp[0];
channel = temp[2];
try
{
if (message.matches("^[A-Za-z0-9]+([\\+]){2,2}"))
{
Database.updateRep(message.substring(0, message.length()-2), +1);
IRC.sendServer("PRIVMSG " + channel + " " + message.substring(0, message.length()-2) + ": Rep = " + Database.getUserRep(message.substring(0, message.length()-2)) + "!");
}
else if (message.matches("^[A-Za-z0-9]+([\\-]){2,2}"))
{
Database.updateRep(message.substring(0, message.length()-2), -1);
IRC.sendServer("PRIVMSG " + channel + " " + message.substring(0, message.length()-2) + ": Rep = " + Database.getUserRep(message.substring(0, message.length()-2)) + "!");
}
else if (message.matches("^.rep")||message.matches("^.rep [A-Za-z0-9#]+$"))
{
String[] t = message.split(" ");
if (t.length <= 0||t[1] == null)
IRC.sendServer("PRIVMSG " + channel + " " + user + ": Rep = " + Database.getUserRep(user) + "!");
else
IRC.sendServer("PRIVMSG " + channel + " " + t[1] + ": Rep = " + Database.getUserRep(t[1]) + "!");
}
else if (message.matches("^.msgsent")||message.matches("^.msgsent [A-Za-z0-9#]+$"))
{
String[] t = message.split(" ");
if (t.length <= 0||t[1] == null)
IRC.sendServer("PRIVMSG " + channel + " " + user + ": Messages Sent = " + Database.getMessagesSent(user) + "!");
else
IRC.sendServer("PRIVMSG " + channel + " " + t[1] + ": Messages Sent = " + Database.getMessagesSent(t[1]) + "!");
}
else if (message.matches("^.lastonline [A-Za-z0-9#]+$"))
{
String[] t = message.split(" ");
if (t.length > 0||t[1] != null)
IRC.sendServer("PRIVMSG " + channel + " " + t[1] + ": Last Online = " + Database.getLastOnline(t[1]) + "!");
}
else if (message.matches("\\.remind .* \".*\"")||message.matches("\\.remind .* '.*'"))
{
String[] t = message.split("'");
if (message.matches("\\.remind .* \".*\""))
t = message.split("\"");
String[] tt = t[0].split(" ");
Database.addReminder(user, tt[1], t[1]);
IRC.sendServer("PRIVMSG " + channel + " " + user + ": I will remind them next time they are round master!");
}
else
{
String[] reminders = Database.getReminders(user);
if (reminders.length > 0)
{
for (int i = 0; i < reminders.length;i++)
{
IRC.sendServer("PRIVMSG " + channel + " " + reminders[i]);
Database.delReminder(user);
}
}
Database.updateUser(user);
}
}
catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (ClassNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
| public void onMessage(String in_str)
{
String temp[] = in_str.split(":"),
message, host, user, channel;
message = temp[2];
temp = temp[1].split("!");
user = temp[0];
temp = temp[1].split(" ");
host = temp[0];
channel = temp[2];
try
{
if (message.matches("^[A-Za-z0-9]+([\\+]){2,2}"))
{
Database.updateRep(message.substring(0, message.length()-2), +1);
IRC.sendServer("PRIVMSG " + channel + " " + message.substring(0, message.length()-2) + ": Rep = " + Database.getUserRep(message.substring(0, message.length()-2)) + "!");
}
else if (message.matches("^[A-Za-z0-9]+([\\-]){2,2}"))
{
Database.updateRep(message.substring(0, message.length()-2), -1);
IRC.sendServer("PRIVMSG " + channel + " " + message.substring(0, message.length()-2) + ": Rep = " + Database.getUserRep(message.substring(0, message.length()-2)) + "!");
}
else if (message.matches("^.rep")||message.matches("^.rep [A-Za-z0-9#]+$"))
{
String[] t = message.split(" ");
if (t.length <= 0||t[1] == null)
IRC.sendServer("PRIVMSG " + channel + " " + user + ": Rep = " + Database.getUserRep(user) + "!");
else
IRC.sendServer("PRIVMSG " + channel + " " + t[1] + ": Rep = " + Database.getUserRep(t[1]) + "!");
}
else if (message.matches("^.msgsent [A-Za-z0-9#]+$"))
{
String[] t = message.split(" ");
if (t.length <= 0||t[1] == null)
IRC.sendServer("PRIVMSG " + channel + " " + user + ": Messages Sent = " + Database.getMessagesSent(user) + "!");
else
IRC.sendServer("PRIVMSG " + channel + " " + t[1] + ": Messages Sent = " + Database.getMessagesSent(t[1]) + "!");
}
else if (message.matches("^.lastonline [A-Za-z0-9#]+$"))
{
String[] t = message.split(" ");
if (t.length > 0||t[1] != null)
IRC.sendServer("PRIVMSG " + channel + " " + t[1] + ": Last Online = " + Database.getLastOnline(t[1]) + "!");
}
else if (message.matches("\\.remind .* \".*\"")||message.matches("\\.remind .* '.*'"))
{
String[] t = message.split("'");
if (message.matches("\\.remind .* \".*\""))
t = message.split("\"");
String[] tt = t[0].split(" ");
Database.addReminder(user, tt[1], t[1]);
IRC.sendServer("PRIVMSG " + channel + " " + user + ": I will remind them next time they are round master!");
}
else
{
String[] reminders = Database.getReminders(user);
if (reminders.length > 0)
{
for (int i = 0; i < reminders.length;i++)
{
IRC.sendServer("PRIVMSG " + channel + " " + reminders[i]);
Database.delReminder(user);
}
}
Database.updateUser(user);
}
}
catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (ClassNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
|
diff --git a/src/gwt/src/org/rstudio/studio/client/workbench/views/vcs/common/ConsoleProgressDialog.java b/src/gwt/src/org/rstudio/studio/client/workbench/views/vcs/common/ConsoleProgressDialog.java
index f1fb608b7d..5b775470e9 100644
--- a/src/gwt/src/org/rstudio/studio/client/workbench/views/vcs/common/ConsoleProgressDialog.java
+++ b/src/gwt/src/org/rstudio/studio/client/workbench/views/vcs/common/ConsoleProgressDialog.java
@@ -1,410 +1,411 @@
/*
* ConsoleProgressDialog.java
*
* Copyright (C) 2009-11 by RStudio, Inc.
*
* This program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
package org.rstudio.studio.client.workbench.views.vcs.common;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Style;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.dom.client.Style.Visibility;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.logical.shared.CloseEvent;
import com.google.gwt.event.logical.shared.CloseHandler;
import com.google.gwt.resources.client.ClientBundle;
import com.google.gwt.resources.client.CssResource;
import com.google.gwt.resources.client.ImageResource;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.Event.NativePreviewEvent;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.*;
import org.rstudio.core.client.BrowseCap;
import org.rstudio.core.client.CommandWithArg;
import org.rstudio.core.client.HandlerRegistrations;
import org.rstudio.core.client.StringUtil;
import org.rstudio.core.client.command.KeyboardShortcut;
import org.rstudio.core.client.widget.*;
import org.rstudio.studio.client.common.SimpleRequestCallback;
import org.rstudio.studio.client.common.console.ConsoleOutputEvent;
import org.rstudio.studio.client.common.console.ConsolePromptEvent;
import org.rstudio.studio.client.common.console.ConsoleProcess;
import org.rstudio.studio.client.common.console.ConsoleProcessInfo;
import org.rstudio.studio.client.common.console.ProcessExitEvent;
import org.rstudio.studio.client.common.crypto.CryptoServerOperations;
import org.rstudio.studio.client.common.shell.ShellInput;
import org.rstudio.studio.client.common.shell.ShellInteractionManager;
import org.rstudio.studio.client.common.shell.ShellOutputWriter;
import org.rstudio.studio.client.server.ServerError;
import org.rstudio.studio.client.server.Void;
import org.rstudio.studio.client.server.VoidServerRequestCallback;
public class ConsoleProgressDialog extends ModalDialogBase
implements ConsoleOutputEvent.Handler,
ConsolePromptEvent.Handler,
ProcessExitEvent.Handler,
ClickHandler
{
interface Resources extends ClientBundle
{
ImageResource progress();
@Source("ConsoleProgressDialog.css")
Styles styles();
}
interface Styles extends CssResource
{
String consoleProgressDialog();
String labelCell();
String progressCell();
String buttonCell();
String shellDisplay();
}
interface Binder extends UiBinder<Widget, ConsoleProgressDialog>
{}
public static void ensureStylesInjected()
{
resources_.styles().ensureInjected();
}
public ConsoleProgressDialog(ConsoleProcess consoleProcess,
CryptoServerOperations server)
{
this(consoleProcess.getProcessInfo().getCaption(),
consoleProcess,
"",
null,
server);
}
public ConsoleProgressDialog(String title,
String output,
int exitCode)
{
this(title, null, output, exitCode, null);
}
public ConsoleProgressDialog(String title,
ConsoleProcess consoleProcess,
String initialOutput,
Integer exitCode,
CryptoServerOperations server)
{
if (consoleProcess == null && exitCode == null)
{
throw new IllegalArgumentException(
"Invalid combination of arguments to ConsoleProgressDialog");
}
addStyleName(resources_.styles().consoleProgressDialog());
consoleProcess_ = consoleProcess;
setText(title);
display_ = new ConsoleProgressWidget();
+ display_.addStyleName(resources_.styles().shellDisplay());
Style style = display_.getElement().getStyle();
double skewFactor = (12 + BrowseCap.getFontSkew()) / 12.0;
int width = Math.min((int)(skewFactor * 660),
Window.getClientWidth() - 100);
style.setWidth(width, Unit.PX);
display_.setMaxOutputLines(getMaxOutputLines());
display_.setSuppressPendingInput(true);
if (getInteractionMode() != ConsoleProcessInfo.INTERACTION_NEVER)
{
ShellInteractionManager shellInteractionManager =
new ShellInteractionManager(display_, server, inputHandler_);
if (getInteractionMode() != ConsoleProcessInfo.INTERACTION_ALWAYS)
shellInteractionManager.setHistoryEnabled(false);
outputWriter_ = shellInteractionManager;
}
else
{
display_.setReadOnly(true);
outputWriter_ = display_;
}
progressAnim_ = new Image(resources_.progress().getSafeUri());
stopButton_ = new ThemedButton("Stop", this);
centralWidget_ = GWT.<Binder>create(Binder.class).createAndBindUi(this);
label_.setText(title);
if (!StringUtil.isNullOrEmpty(initialOutput))
{
outputWriter_.consoleWriteOutput(initialOutput);
}
registrations_ = new HandlerRegistrations();
if (consoleProcess != null)
{
registrations_.add(consoleProcess.addConsolePromptHandler(this));
registrations_.add(consoleProcess.addConsoleOutputHandler(this));
registrations_.add(consoleProcess.addProcessExitHandler(this));
consoleProcess.start(new SimpleRequestCallback<Void>()
{
@Override
public void onError(ServerError error)
{
// Show error and stop
super.onError(error);
// if this is showOnOutput_ then we will never get
// a ProcessExitEvent or an onUnload so we should unsubscribe
// from events here
registrations_.removeHandler();
closeDialog();
}
});
}
addCloseHandler(new CloseHandler<PopupPanel>()
{
@Override
public void onClose(CloseEvent<PopupPanel> popupPanelCloseEvent)
{
if (consoleProcess_ != null)
consoleProcess_.reap(new VoidServerRequestCallback());
}
});
if (exitCode != null)
setExitCode(exitCode);
// interaction-always mode is a shell -- customize ui accordingly
if (getInteractionMode() == ConsoleProcessInfo.INTERACTION_ALWAYS)
{
stopButton_.setText("Close");
hideProgress();
int height = Window.getClientHeight() - 150;
display_.getElement().getStyle().setHeight(height, Unit.PX);
}
}
public void showOnOutput()
{
showOnOutput_ = true;
}
@Override
protected Widget createMainWidget()
{
return centralWidget_;
}
@Override
protected void onUnload()
{
super.onUnload();
registrations_.removeHandler();
}
@Override
public void onPreviewNativeEvent(NativePreviewEvent event)
{
if (event.getTypeInt() == Event.ONKEYDOWN
&& KeyboardShortcut.getModifierValue(event.getNativeEvent()) == KeyboardShortcut.NONE)
{
if (event.getNativeEvent().getKeyCode() == KeyCodes.KEY_ESCAPE)
{
stopButton_.click();
event.cancel();
return;
}
else if (event.getNativeEvent().getKeyCode() == KeyCodes.KEY_ENTER)
{
if (!running_)
{
stopButton_.click();
event.cancel();
return;
}
}
}
super.onPreviewNativeEvent(event);
}
@Override
public void onConsoleOutput(ConsoleOutputEvent event)
{
maybeShowOnOutput(event.getOutput());
outputWriter_.consoleWriteOutput(event.getOutput());
}
@Override
public void onConsolePrompt(ConsolePromptEvent event)
{
maybeShowOnOutput(event.getPrompt());
outputWriter_.consoleWritePrompt(event.getPrompt());
}
@Override
public void onProcessExit(ProcessExitEvent event)
{
setExitCode(event.getExitCode());
if (isShowing())
{
display_.setReadOnly(true);
stopButton_.setFocus(true);
// when a shell exits we close the dialog
if (getInteractionMode() == ConsoleProcessInfo.INTERACTION_ALWAYS)
stopButton_.click();
// when we were showOnOutput and the process succeeded then
// we also auto-close
else if (showOnOutput_ && (event.getExitCode() == 0))
stopButton_.click();
}
// the dialog was showOnOutput_ but was never shown so just tear
// down registrations and reap the process
else if (showOnOutput_)
{
registrations_.removeHandler();
if (consoleProcess_ != null)
consoleProcess_.reap(new VoidServerRequestCallback());
}
}
private void setExitCode(int exitCode)
{
running_ = false;
stopButton_.setText("Close");
stopButton_.setDefault(true);
hideProgress();
}
@Override
public void onClick(ClickEvent event)
{
if (running_)
{
consoleProcess_.interrupt(new SimpleRequestCallback<Void>() {
@Override
public void onResponseReceived(Void response)
{
closeDialog();
}
@Override
public void onError(ServerError error)
{
stopButton_.setEnabled(true);
super.onError(error);
}
});
stopButton_.setEnabled(false);
}
else
{
closeDialog();
}
// Whether success or failure, we don't want to interrupt again
running_ = false;
}
private CommandWithArg<ShellInput> inputHandler_ =
new CommandWithArg<ShellInput>()
{
@Override
public void execute(ShellInput input)
{
consoleProcess_.writeStandardInput(
input,
new VoidServerRequestCallback() {
@Override
public void onError(ServerError error)
{
outputWriter_.consoleWriteError(error.getUserMessage());
}
});
}
};
private void hideProgress()
{
progressAnim_.getElement().getStyle().setVisibility(Visibility.HIDDEN);
}
private int getInteractionMode()
{
if (consoleProcess_ != null)
return consoleProcess_.getProcessInfo().getInteractionMode();
else
return ConsoleProcessInfo.INTERACTION_NEVER;
}
private int getMaxOutputLines()
{
if (consoleProcess_ != null)
return consoleProcess_.getProcessInfo().getMaxOutputLines();
else
return 1000;
}
private void maybeShowOnOutput(String output)
{
// NOTE: we have to trim the output because when the password
// manager provides a password non-interactively the back-end
// process sometimes echos a newline back to us
if (!isShowing() && showOnOutput_ && (output.trim().length() > 0))
showModal();
}
private boolean running_ = true;
private boolean showOnOutput_ = false;
private final ConsoleProcess consoleProcess_;
private HandlerRegistrations registrations_;
private final ShellOutputWriter outputWriter_;
@UiField(provided = true)
ConsoleProgressWidget display_;
@UiField(provided = true)
Image progressAnim_;
@UiField
Label label_;
@UiField(provided = true)
ThemedButton stopButton_;
private Widget centralWidget_;
private static final Resources resources_ = GWT.<Resources>create(Resources.class);
}
| true | true | public ConsoleProgressDialog(String title,
ConsoleProcess consoleProcess,
String initialOutput,
Integer exitCode,
CryptoServerOperations server)
{
if (consoleProcess == null && exitCode == null)
{
throw new IllegalArgumentException(
"Invalid combination of arguments to ConsoleProgressDialog");
}
addStyleName(resources_.styles().consoleProgressDialog());
consoleProcess_ = consoleProcess;
setText(title);
display_ = new ConsoleProgressWidget();
Style style = display_.getElement().getStyle();
double skewFactor = (12 + BrowseCap.getFontSkew()) / 12.0;
int width = Math.min((int)(skewFactor * 660),
Window.getClientWidth() - 100);
style.setWidth(width, Unit.PX);
display_.setMaxOutputLines(getMaxOutputLines());
display_.setSuppressPendingInput(true);
if (getInteractionMode() != ConsoleProcessInfo.INTERACTION_NEVER)
{
ShellInteractionManager shellInteractionManager =
new ShellInteractionManager(display_, server, inputHandler_);
if (getInteractionMode() != ConsoleProcessInfo.INTERACTION_ALWAYS)
shellInteractionManager.setHistoryEnabled(false);
outputWriter_ = shellInteractionManager;
}
else
{
display_.setReadOnly(true);
outputWriter_ = display_;
}
progressAnim_ = new Image(resources_.progress().getSafeUri());
stopButton_ = new ThemedButton("Stop", this);
centralWidget_ = GWT.<Binder>create(Binder.class).createAndBindUi(this);
label_.setText(title);
if (!StringUtil.isNullOrEmpty(initialOutput))
{
outputWriter_.consoleWriteOutput(initialOutput);
}
registrations_ = new HandlerRegistrations();
if (consoleProcess != null)
{
registrations_.add(consoleProcess.addConsolePromptHandler(this));
registrations_.add(consoleProcess.addConsoleOutputHandler(this));
registrations_.add(consoleProcess.addProcessExitHandler(this));
consoleProcess.start(new SimpleRequestCallback<Void>()
{
@Override
public void onError(ServerError error)
{
// Show error and stop
super.onError(error);
// if this is showOnOutput_ then we will never get
// a ProcessExitEvent or an onUnload so we should unsubscribe
// from events here
registrations_.removeHandler();
closeDialog();
}
});
}
addCloseHandler(new CloseHandler<PopupPanel>()
{
@Override
public void onClose(CloseEvent<PopupPanel> popupPanelCloseEvent)
{
if (consoleProcess_ != null)
consoleProcess_.reap(new VoidServerRequestCallback());
}
});
if (exitCode != null)
setExitCode(exitCode);
// interaction-always mode is a shell -- customize ui accordingly
if (getInteractionMode() == ConsoleProcessInfo.INTERACTION_ALWAYS)
{
stopButton_.setText("Close");
hideProgress();
int height = Window.getClientHeight() - 150;
display_.getElement().getStyle().setHeight(height, Unit.PX);
}
}
| public ConsoleProgressDialog(String title,
ConsoleProcess consoleProcess,
String initialOutput,
Integer exitCode,
CryptoServerOperations server)
{
if (consoleProcess == null && exitCode == null)
{
throw new IllegalArgumentException(
"Invalid combination of arguments to ConsoleProgressDialog");
}
addStyleName(resources_.styles().consoleProgressDialog());
consoleProcess_ = consoleProcess;
setText(title);
display_ = new ConsoleProgressWidget();
display_.addStyleName(resources_.styles().shellDisplay());
Style style = display_.getElement().getStyle();
double skewFactor = (12 + BrowseCap.getFontSkew()) / 12.0;
int width = Math.min((int)(skewFactor * 660),
Window.getClientWidth() - 100);
style.setWidth(width, Unit.PX);
display_.setMaxOutputLines(getMaxOutputLines());
display_.setSuppressPendingInput(true);
if (getInteractionMode() != ConsoleProcessInfo.INTERACTION_NEVER)
{
ShellInteractionManager shellInteractionManager =
new ShellInteractionManager(display_, server, inputHandler_);
if (getInteractionMode() != ConsoleProcessInfo.INTERACTION_ALWAYS)
shellInteractionManager.setHistoryEnabled(false);
outputWriter_ = shellInteractionManager;
}
else
{
display_.setReadOnly(true);
outputWriter_ = display_;
}
progressAnim_ = new Image(resources_.progress().getSafeUri());
stopButton_ = new ThemedButton("Stop", this);
centralWidget_ = GWT.<Binder>create(Binder.class).createAndBindUi(this);
label_.setText(title);
if (!StringUtil.isNullOrEmpty(initialOutput))
{
outputWriter_.consoleWriteOutput(initialOutput);
}
registrations_ = new HandlerRegistrations();
if (consoleProcess != null)
{
registrations_.add(consoleProcess.addConsolePromptHandler(this));
registrations_.add(consoleProcess.addConsoleOutputHandler(this));
registrations_.add(consoleProcess.addProcessExitHandler(this));
consoleProcess.start(new SimpleRequestCallback<Void>()
{
@Override
public void onError(ServerError error)
{
// Show error and stop
super.onError(error);
// if this is showOnOutput_ then we will never get
// a ProcessExitEvent or an onUnload so we should unsubscribe
// from events here
registrations_.removeHandler();
closeDialog();
}
});
}
addCloseHandler(new CloseHandler<PopupPanel>()
{
@Override
public void onClose(CloseEvent<PopupPanel> popupPanelCloseEvent)
{
if (consoleProcess_ != null)
consoleProcess_.reap(new VoidServerRequestCallback());
}
});
if (exitCode != null)
setExitCode(exitCode);
// interaction-always mode is a shell -- customize ui accordingly
if (getInteractionMode() == ConsoleProcessInfo.INTERACTION_ALWAYS)
{
stopButton_.setText("Close");
hideProgress();
int height = Window.getClientHeight() - 150;
display_.getElement().getStyle().setHeight(height, Unit.PX);
}
}
|
diff --git a/src/java/org/rapidcontext/core/data/DynamicObject.java b/src/java/org/rapidcontext/core/data/DynamicObject.java
index 6f79ae3..6970012 100644
--- a/src/java/org/rapidcontext/core/data/DynamicObject.java
+++ b/src/java/org/rapidcontext/core/data/DynamicObject.java
@@ -1,61 +1,61 @@
/*
* RapidContext <http://www.rapidcontext.com/>
* Copyright (c) 2007-2010 Per Cederberg. All rights reserved.
*
* This program is free software: you can redistribute it and/or
* modify it under the terms of the BSD license.
*
* 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 RapidContext LICENSE.txt file for more details.
*/
package org.rapidcontext.core.data;
/**
* A dynamic object base class. This class provides a basic dynamic
* data container (a dictionary) that can be used for simple
* serialization of the object. It also enables containers and others
* to store additional data in this object, breaking the concept of
* encapsulation (for improved utility).
*
* @author Per Cederberg
* @version 1.0
*/
public abstract class DynamicObject {
/**
* The dictionary key for the object type. The value stored is a
* string and should be descriptive outside of the Java world.
*/
public static final String KEY_TYPE = "type";
/**
* The dictionary containing the serializable data for this
* object.
*/
public Dict dict = new Dict();
/**
* Creates a new dynamic object. This constructor is used to
* enforce that subclasses set the type key properly.
*
* @param type the type name
*/
- public DynamicObject(String type) {
+ protected DynamicObject(String type) {
dict.add(KEY_TYPE, type);
}
/**
* Returns a serialized representation of this object. Used when
* accessing the object from outside pure Java. By default this
* method will return the contained dictionary.
*
* @return the serialized representation of this object
*/
public Dict serialize() {
return dict;
}
}
| true | true | public DynamicObject(String type) {
dict.add(KEY_TYPE, type);
}
| protected DynamicObject(String type) {
dict.add(KEY_TYPE, type);
}
|
diff --git a/Tools/org.jcryptool.doc.tools/src/org/jcryptool/algorithms/AlgorithmParser.java b/Tools/org.jcryptool.doc.tools/src/org/jcryptool/algorithms/AlgorithmParser.java
index 1b8f1c2..1f2b947 100644
--- a/Tools/org.jcryptool.doc.tools/src/org/jcryptool/algorithms/AlgorithmParser.java
+++ b/Tools/org.jcryptool.doc.tools/src/org/jcryptool/algorithms/AlgorithmParser.java
@@ -1,71 +1,71 @@
package org.jcryptool.algorithms;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.SortedSet;
import java.util.TreeSet;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.PosixParser;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class AlgorithmParser {
public static void main(String[] args) throws XPathExpressionException, SAXException, IOException, ParseException, ParserConfigurationException{
CommandLineParser cmdParser = new PosixParser();
Options options = new Options();
options.addOption("help", false, "prints this message");
options.addOption("in", true, "path to algorithms.xml");
options.addOption("out", true, "path to algorithms.txt");
CommandLine cmd = cmdParser.parse(options, args);
if(cmd.hasOption("help"))
{
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("AlgorithmXmlParser extracts algorithm names from algorithms.xml file to algorithms.txt", options );
return;
}
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
builder = factory.newDocumentBuilder();
Document doc = builder.parse(cmd.getOptionValue("in"));
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile("//Names");
NodeList result = (NodeList)expr.evaluate(doc, XPathConstants.NODESET);
SortedSet<String> algorithmNames = new TreeSet<String>();
for(int i = 0; i < result.getLength(); i++)
{
algorithmNames.addAll(Arrays.asList((result.item(i).getTextContent().split(","))));
}
String algorithms = "";
for(String name : algorithmNames)
{
- algorithms += name + "\n";
+ algorithms += name + System.getProperty("line.separator");
}
PrintWriter out = new PrintWriter(cmd.getOptionValue("out"));
- out.println(algorithms);
+ out.print(algorithms);
out.close();
}
}
| false | true | public static void main(String[] args) throws XPathExpressionException, SAXException, IOException, ParseException, ParserConfigurationException{
CommandLineParser cmdParser = new PosixParser();
Options options = new Options();
options.addOption("help", false, "prints this message");
options.addOption("in", true, "path to algorithms.xml");
options.addOption("out", true, "path to algorithms.txt");
CommandLine cmd = cmdParser.parse(options, args);
if(cmd.hasOption("help"))
{
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("AlgorithmXmlParser extracts algorithm names from algorithms.xml file to algorithms.txt", options );
return;
}
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
builder = factory.newDocumentBuilder();
Document doc = builder.parse(cmd.getOptionValue("in"));
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile("//Names");
NodeList result = (NodeList)expr.evaluate(doc, XPathConstants.NODESET);
SortedSet<String> algorithmNames = new TreeSet<String>();
for(int i = 0; i < result.getLength(); i++)
{
algorithmNames.addAll(Arrays.asList((result.item(i).getTextContent().split(","))));
}
String algorithms = "";
for(String name : algorithmNames)
{
algorithms += name + "\n";
}
PrintWriter out = new PrintWriter(cmd.getOptionValue("out"));
out.println(algorithms);
out.close();
}
| public static void main(String[] args) throws XPathExpressionException, SAXException, IOException, ParseException, ParserConfigurationException{
CommandLineParser cmdParser = new PosixParser();
Options options = new Options();
options.addOption("help", false, "prints this message");
options.addOption("in", true, "path to algorithms.xml");
options.addOption("out", true, "path to algorithms.txt");
CommandLine cmd = cmdParser.parse(options, args);
if(cmd.hasOption("help"))
{
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("AlgorithmXmlParser extracts algorithm names from algorithms.xml file to algorithms.txt", options );
return;
}
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
builder = factory.newDocumentBuilder();
Document doc = builder.parse(cmd.getOptionValue("in"));
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile("//Names");
NodeList result = (NodeList)expr.evaluate(doc, XPathConstants.NODESET);
SortedSet<String> algorithmNames = new TreeSet<String>();
for(int i = 0; i < result.getLength(); i++)
{
algorithmNames.addAll(Arrays.asList((result.item(i).getTextContent().split(","))));
}
String algorithms = "";
for(String name : algorithmNames)
{
algorithms += name + System.getProperty("line.separator");
}
PrintWriter out = new PrintWriter(cmd.getOptionValue("out"));
out.print(algorithms);
out.close();
}
|
diff --git a/src/main/java/com/impetus/kundera/cassandra/ColumnFamilyDataAccessor.java b/src/main/java/com/impetus/kundera/cassandra/ColumnFamilyDataAccessor.java
index 06f4a919e..f0eeffb1f 100644
--- a/src/main/java/com/impetus/kundera/cassandra/ColumnFamilyDataAccessor.java
+++ b/src/main/java/com/impetus/kundera/cassandra/ColumnFamilyDataAccessor.java
@@ -1,340 +1,345 @@
/*******************************************************************************
* * Copyright 2011 Impetus Infotech.
* *
* * 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.impetus.kundera.cassandra;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.cassandra.thrift.Column;
import org.apache.cassandra.thrift.SuperColumn;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.scale7.cassandra.pelops.Bytes;
import com.impetus.kundera.Client;
import com.impetus.kundera.Constants;
import com.impetus.kundera.cassandra.client.CassandraClient;
import com.impetus.kundera.cassandra.client.pelops.PelopsDataHandler;
import com.impetus.kundera.db.accessor.BaseDataAccessor;
import com.impetus.kundera.ejb.EntityManagerImpl;
import com.impetus.kundera.loader.DBType;
import com.impetus.kundera.metadata.EntityMetadata;
import com.impetus.kundera.property.PropertyAccessException;
import com.impetus.kundera.property.PropertyAccessorFactory;
import com.impetus.kundera.property.PropertyAccessorHelper;
import com.impetus.kundera.proxy.EnhancedEntity;
/**
* DataAccessor implementation for Cassandra's ColumnFamily.
*
* @author animesh.kumar
* @since 0.1
*/
public final class ColumnFamilyDataAccessor extends BaseDataAccessor
{
/** log for this class. */
private static final Log log = LogFactory.getLog(ColumnFamilyDataAccessor.class);
/** The Constant TO_ONE_SUPER_COL_NAME. */
private static final String TO_ONE_SUPER_COL_NAME = "FKey-TO";
/**
* Instantiates a new column family data accessor.
*
* @param em
* the em
*/
public ColumnFamilyDataAccessor(EntityManagerImpl em)
{
super(em);
}
/*
* @see com.impetus.kundera.db.DataAccessor#read(java.lang.Class,
* com.impetus.kundera.metadata.EntityMetadata, java.lang.String)
*/
@Override
public <E> E read(Class<E> clazz, EntityMetadata m, String id) throws Exception
{
log.debug("Column Family >> Read >> " + clazz.getName() + "_" + id);
String keyspace = m.getSchema();
String family = m.getTableName();
return getEntityManager().getClient().loadColumns(getEntityManager(), clazz, keyspace, family, id, m);
}
/*
* @see com.impetus.kundera.db.DataAccessor#read(java.lang.Class,
* com.impetus.kundera.metadata.EntityMetadata, java.lang.String[])
*/
@Override
public <E> List<E> read(Class<E> clazz, EntityMetadata m, String... ids) throws Exception
{
Client client =null;
log.debug("Cassandra >> Read >> " + clazz.getName() + "_(" + Arrays.asList(ids) + ")");
String keyspace = m.getSchema();
String family = m.getTableName();
return m.getSuperColumnsAsList().isEmpty()?getEntityManager().getClient().loadColumns(getEntityManager(), clazz, keyspace, family, m, ids):
readSuperColumn(clazz, m, keyspace, family, ids);
}
private <E> List<E> readSuperColumn(Class<E> clazz, EntityMetadata m, String keyspace, String family, String... ids)
throws Exception
{
List<E> entities = new ArrayList<E>();
Map<Bytes, List<SuperColumn>> map = ((CassandraClient)getEntityManager().getClient()).loadSuperColumns(keyspace, family,ids);
for (Map.Entry<Bytes, List<SuperColumn>> entry : map.entrySet())
{
String entityId = PropertyAccessorFactory.STRING.fromBytes(entry.getKey().toByteArray());
List<SuperColumn> superColumn = entry.getValue();
E e = fromThriftRow(clazz, m, this.new ThriftRow<SuperColumn>(entityId, family, superColumn));
entities.add(e);
}
return entities;
}
/*
* @seecom.impetus.kundera.db.DataAccessor#write(com.impetus.kundera.proxy.
* EnhancedEntity, com.impetus.kundera.metadata.EntityMetadata)
*/
@Override
public void write(EnhancedEntity e, EntityMetadata m) throws Exception
{
String entityName = e.getEntity().getClass().getName();
String id = e.getId();
log.debug("Column Family >> Write >> " + entityName + "_" + id);
getEntityManager().getClient().writeColumns(getEntityManager(), e, m);
}
@Override
public <E> List<E> read(Class<E> clazz, EntityMetadata m, Map<String, String> col) throws Exception
{
String keyspace = m.getSchema();
String family = m.getTableName();
List<E> entities = new ArrayList<E>();
for (String superColName : col.keySet())
{
String entityId = col.get(superColName);
List<SuperColumn> map = ((CassandraClient) getEntityManager().getClient()).loadSuperColumns(keyspace,
family, entityId, new String[] { superColName });
E e = fromThriftRow(clazz, m, this.new ThriftRow<SuperColumn>(entityId, family, map));
entities.add(e);
}
return entities;
}
/**
* From thrift row.
*
* @param <E>
* the element type
* @param clazz
* the clazz
* @param m
* the m
* @param cr
* the cr
* @return the e
* @throws Exception
* the exception
*/
// TODO: this is a duplicate code snippet and we need to refactor this.(Same
// is with PelopsDataHandler)
private <E> E fromThriftRow(Class<E> clazz, EntityMetadata m, BaseDataAccessor.ThriftRow<SuperColumn> cr)
throws Exception
{
// Instantiate a new instance
E e = clazz.newInstance();
// Set row-key. Note: @Id is always String.
PropertyAccessorHelper.set(e, m.getIdProperty(), cr.getId());
// Get a name->field map for super-columns
Map<String, Field> columnNameToFieldMap = new HashMap<String, Field>();
for (Map.Entry<String, EntityMetadata.SuperColumn> entry : m.getSuperColumnsMap().entrySet())
{
for (EntityMetadata.Column cMetadata : entry.getValue().getColumns())
{
columnNameToFieldMap.put(cMetadata.getName(), cMetadata.getField());
}
}
for (SuperColumn sc : cr.getColumns())
{
String scName = PropertyAccessorFactory.STRING.fromBytes(sc.getName());
if (scName.indexOf(Constants.SUPER_COLUMN_NAME_DELIMITER) != -1)
{
String scFieldName = scName.substring(0,scName.indexOf(Constants.SUPER_COLUMN_NAME_DELIMITER));
Field superColumnField = e.getClass().getDeclaredField(scFieldName);
+ if(!superColumnField.isAccessible())
+ {
+ superColumnField.setAccessible(true);
+ }
Collection embeddedCollection = null;
if(superColumnField.getType().equals(List.class))
{
embeddedCollection = new ArrayList();
}else if(superColumnField.getType().equals(Set.class))
{
embeddedCollection = new HashSet();
}
PelopsDataHandler handler = new PelopsDataHandler();
Object embeddedObject = handler.populateEmbeddedObject(sc, m);
embeddedCollection.add(embeddedObject);
+ superColumnField.set(e, embeddedCollection);
}
else
{
boolean intoRelations = false;
if (scName.equals(TO_ONE_SUPER_COL_NAME))
{
intoRelations = true;
}
for (Column column : sc.getColumns())
{
String name = PropertyAccessorFactory.STRING.fromBytes(column.getName());
byte[] value = column.getValue();
if (value == null)
{
continue;
}
if (intoRelations)
{
EntityMetadata.Relation relation = m.getRelation(name);
String foreignKeys = PropertyAccessorFactory.STRING.fromBytes(value);
Set<String> keys = deserializeKeys(foreignKeys);
getEntityManager().getEntityResolver().populateForeignEntities(e, cr.getId(), relation,
keys.toArray(new String[0]));
}
else
{
// set value of the field in the bean
Field field = columnNameToFieldMap.get(name);
Object embeddedObject = PropertyAccessorHelper.getObject(e, scName);
PropertyAccessorHelper.set(embeddedObject, field, value);
}
}
}
}
return e;
}
// Helper method to convert @Entity to ThriftRow
/**
* To thrift row.
*
* @param e
* the e
* @param m
* the m
* @return the base data accessor. thrift row
* @throws Exception
* the exception
*/
private BaseDataAccessor.ThriftRow<SuperColumn> toThriftRow(EnhancedEntity e, EntityMetadata m) throws Exception
{
// timestamp to use in thrift column objects
long timestamp = System.currentTimeMillis();
BaseDataAccessor.ThriftRow<SuperColumn> cr = this.new ThriftRow<SuperColumn>();
// column-family name
cr.setColumnFamilyName(m.getTableName());
// Set row key
cr.setId(e.getId());
for (EntityMetadata.SuperColumn superColumn : m.getSuperColumnsAsList())
{
String superColumnName = superColumn.getName();
List<Column> columns = new ArrayList<Column>();
for (EntityMetadata.Column column : superColumn.getColumns())
{
Field field = column.getField();
String name = column.getName();
try
{
byte[] value = PropertyAccessorHelper.get(e.getEntity(), field);
if (null != value)
{
Column col = new Column();
col.setName(PropertyAccessorFactory.STRING.toBytes(name));
col.setValue(value);
col.setTimestamp(timestamp);
columns.add(col);
}
}
catch (PropertyAccessException exp)
{
log.warn(exp.getMessage());
}
}
SuperColumn superCol = new SuperColumn();
superCol.setName(PropertyAccessorFactory.STRING.toBytes(superColumnName));
superCol.setColumns(columns);
cr.addColumn(superCol);
}
// add toOne relations
List<Column> columns = new ArrayList<Column>();
for (Map.Entry<String, Set<String>> entry : e.getForeignKeysMap().entrySet())
{
String property = entry.getKey();
Set<String> foreignKeys = entry.getValue();
String keys = serializeKeys(foreignKeys);
if (null != keys)
{
Column col = new Column();
col.setName(PropertyAccessorFactory.STRING.toBytes(property));
col.setValue(PropertyAccessorFactory.STRING.toBytes(keys));
col.setTimestamp(timestamp);
columns.add(col);
}
}
if (!columns.isEmpty())
{
SuperColumn superCol = new SuperColumn();
superCol.setName(PropertyAccessorFactory.STRING.toBytes(TO_ONE_SUPER_COL_NAME));
superCol.setColumns(columns);
cr.addColumn(superCol);
}
return cr;
}
}
| false | true | private <E> E fromThriftRow(Class<E> clazz, EntityMetadata m, BaseDataAccessor.ThriftRow<SuperColumn> cr)
throws Exception
{
// Instantiate a new instance
E e = clazz.newInstance();
// Set row-key. Note: @Id is always String.
PropertyAccessorHelper.set(e, m.getIdProperty(), cr.getId());
// Get a name->field map for super-columns
Map<String, Field> columnNameToFieldMap = new HashMap<String, Field>();
for (Map.Entry<String, EntityMetadata.SuperColumn> entry : m.getSuperColumnsMap().entrySet())
{
for (EntityMetadata.Column cMetadata : entry.getValue().getColumns())
{
columnNameToFieldMap.put(cMetadata.getName(), cMetadata.getField());
}
}
for (SuperColumn sc : cr.getColumns())
{
String scName = PropertyAccessorFactory.STRING.fromBytes(sc.getName());
if (scName.indexOf(Constants.SUPER_COLUMN_NAME_DELIMITER) != -1)
{
String scFieldName = scName.substring(0,scName.indexOf(Constants.SUPER_COLUMN_NAME_DELIMITER));
Field superColumnField = e.getClass().getDeclaredField(scFieldName);
Collection embeddedCollection = null;
if(superColumnField.getType().equals(List.class))
{
embeddedCollection = new ArrayList();
}else if(superColumnField.getType().equals(Set.class))
{
embeddedCollection = new HashSet();
}
PelopsDataHandler handler = new PelopsDataHandler();
Object embeddedObject = handler.populateEmbeddedObject(sc, m);
embeddedCollection.add(embeddedObject);
}
else
{
boolean intoRelations = false;
if (scName.equals(TO_ONE_SUPER_COL_NAME))
{
intoRelations = true;
}
for (Column column : sc.getColumns())
{
String name = PropertyAccessorFactory.STRING.fromBytes(column.getName());
byte[] value = column.getValue();
if (value == null)
{
continue;
}
if (intoRelations)
{
EntityMetadata.Relation relation = m.getRelation(name);
String foreignKeys = PropertyAccessorFactory.STRING.fromBytes(value);
Set<String> keys = deserializeKeys(foreignKeys);
getEntityManager().getEntityResolver().populateForeignEntities(e, cr.getId(), relation,
keys.toArray(new String[0]));
}
else
{
// set value of the field in the bean
Field field = columnNameToFieldMap.get(name);
Object embeddedObject = PropertyAccessorHelper.getObject(e, scName);
PropertyAccessorHelper.set(embeddedObject, field, value);
}
}
}
}
return e;
}
| private <E> E fromThriftRow(Class<E> clazz, EntityMetadata m, BaseDataAccessor.ThriftRow<SuperColumn> cr)
throws Exception
{
// Instantiate a new instance
E e = clazz.newInstance();
// Set row-key. Note: @Id is always String.
PropertyAccessorHelper.set(e, m.getIdProperty(), cr.getId());
// Get a name->field map for super-columns
Map<String, Field> columnNameToFieldMap = new HashMap<String, Field>();
for (Map.Entry<String, EntityMetadata.SuperColumn> entry : m.getSuperColumnsMap().entrySet())
{
for (EntityMetadata.Column cMetadata : entry.getValue().getColumns())
{
columnNameToFieldMap.put(cMetadata.getName(), cMetadata.getField());
}
}
for (SuperColumn sc : cr.getColumns())
{
String scName = PropertyAccessorFactory.STRING.fromBytes(sc.getName());
if (scName.indexOf(Constants.SUPER_COLUMN_NAME_DELIMITER) != -1)
{
String scFieldName = scName.substring(0,scName.indexOf(Constants.SUPER_COLUMN_NAME_DELIMITER));
Field superColumnField = e.getClass().getDeclaredField(scFieldName);
if(!superColumnField.isAccessible())
{
superColumnField.setAccessible(true);
}
Collection embeddedCollection = null;
if(superColumnField.getType().equals(List.class))
{
embeddedCollection = new ArrayList();
}else if(superColumnField.getType().equals(Set.class))
{
embeddedCollection = new HashSet();
}
PelopsDataHandler handler = new PelopsDataHandler();
Object embeddedObject = handler.populateEmbeddedObject(sc, m);
embeddedCollection.add(embeddedObject);
superColumnField.set(e, embeddedCollection);
}
else
{
boolean intoRelations = false;
if (scName.equals(TO_ONE_SUPER_COL_NAME))
{
intoRelations = true;
}
for (Column column : sc.getColumns())
{
String name = PropertyAccessorFactory.STRING.fromBytes(column.getName());
byte[] value = column.getValue();
if (value == null)
{
continue;
}
if (intoRelations)
{
EntityMetadata.Relation relation = m.getRelation(name);
String foreignKeys = PropertyAccessorFactory.STRING.fromBytes(value);
Set<String> keys = deserializeKeys(foreignKeys);
getEntityManager().getEntityResolver().populateForeignEntities(e, cr.getId(), relation,
keys.toArray(new String[0]));
}
else
{
// set value of the field in the bean
Field field = columnNameToFieldMap.get(name);
Object embeddedObject = PropertyAccessorHelper.getObject(e, scName);
PropertyAccessorHelper.set(embeddedObject, field, value);
}
}
}
}
return e;
}
|
diff --git a/java/src/com/android/inputmethod/latin/Suggest.java b/java/src/com/android/inputmethod/latin/Suggest.java
index 29b62957..93933f1b 100644
--- a/java/src/com/android/inputmethod/latin/Suggest.java
+++ b/java/src/com/android/inputmethod/latin/Suggest.java
@@ -1,585 +1,575 @@
/*
* 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.inputmethod.latin;
import android.content.Context;
import android.text.AutoText;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import com.android.inputmethod.keyboard.ProximityInfo;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
/**
* This class loads a dictionary and provides a list of suggestions for a given sequence of
* characters. This includes corrections and completions.
*/
public class Suggest implements Dictionary.WordCallback {
public static final String TAG = Suggest.class.getSimpleName();
public static final int APPROX_MAX_WORD_LENGTH = 32;
public static final int CORRECTION_NONE = 0;
public static final int CORRECTION_BASIC = 1;
public static final int CORRECTION_FULL = 2;
public static final int CORRECTION_FULL_BIGRAM = 3;
/**
* Words that appear in both bigram and unigram data gets multiplier ranging from
* BIGRAM_MULTIPLIER_MIN to BIGRAM_MULTIPLIER_MAX depending on the score from
* bigram data.
*/
public static final double BIGRAM_MULTIPLIER_MIN = 1.2;
public static final double BIGRAM_MULTIPLIER_MAX = 1.5;
/**
* Maximum possible bigram frequency. Will depend on how many bits are being used in data
* structure. Maximum bigram frequency will get the BIGRAM_MULTIPLIER_MAX as the multiplier.
*/
public static final int MAXIMUM_BIGRAM_FREQUENCY = 127;
// It seems the following values are only used for logging.
public static final int DIC_USER_TYPED = 0;
public static final int DIC_MAIN = 1;
public static final int DIC_USER = 2;
public static final int DIC_USER_UNIGRAM = 3;
public static final int DIC_CONTACTS = 4;
public static final int DIC_USER_BIGRAM = 5;
// If you add a type of dictionary, increment DIC_TYPE_LAST_ID
// TODO: this value seems unused. Remove it?
public static final int DIC_TYPE_LAST_ID = 5;
public static final String DICT_KEY_MAIN = "main";
public static final String DICT_KEY_CONTACTS = "contacts";
// User dictionary, the system-managed one.
public static final String DICT_KEY_USER = "user";
// User unigram dictionary, internal to LatinIME
public static final String DICT_KEY_USER_UNIGRAM = "user_unigram";
// User bigram dictionary, internal to LatinIME
public static final String DICT_KEY_USER_BIGRAM = "user_bigram";
public static final String DICT_KEY_WHITELIST ="whitelist";
private static final boolean DBG = LatinImeLogger.sDBG;
private AutoCorrection mAutoCorrection;
private Dictionary mMainDict;
private ContactsDictionary mContactsDict;
private WhitelistDictionary mWhiteListDictionary;
private final Map<String, Dictionary> mUnigramDictionaries = new HashMap<String, Dictionary>();
private final Map<String, Dictionary> mBigramDictionaries = new HashMap<String, Dictionary>();
private int mPrefMaxSuggestions = 18;
private static final int PREF_MAX_BIGRAMS = 60;
private boolean mQuickFixesEnabled;
private double mAutoCorrectionThreshold;
private int[] mScores = new int[mPrefMaxSuggestions];
private int[] mBigramScores = new int[PREF_MAX_BIGRAMS];
private ArrayList<CharSequence> mSuggestions = new ArrayList<CharSequence>();
ArrayList<CharSequence> mBigramSuggestions = new ArrayList<CharSequence>();
private CharSequence mTypedWord;
// TODO: Remove these member variables by passing more context to addWord() callback method
private boolean mIsFirstCharCapitalized;
private boolean mIsAllUpperCase;
private int mCorrectionMode = CORRECTION_BASIC;
public Suggest(final Context context, final int dictionaryResId, final Locale locale) {
initAsynchronously(context, dictionaryResId, locale);
}
/* package for test */ Suggest(Context context, File dictionary, long startOffset, long length,
Flag[] flagArray) {
initSynchronously(null, DictionaryFactory.createDictionaryForTest(context, dictionary,
startOffset, length, flagArray));
}
private void initWhitelistAndAutocorrectAndPool(final Context context) {
mWhiteListDictionary = WhitelistDictionary.init(context);
addOrReplaceDictionary(mUnigramDictionaries, DICT_KEY_WHITELIST, mWhiteListDictionary);
mAutoCorrection = new AutoCorrection();
StringBuilderPool.ensureCapacity(mPrefMaxSuggestions, getApproxMaxWordLength());
}
private void initAsynchronously(final Context context, final int dictionaryResId,
final Locale locale) {
resetMainDict(context, dictionaryResId, locale);
// TODO: read the whitelist and init the pool asynchronously too.
// initPool should be done asynchronously now that the pool is thread-safe.
initWhitelistAndAutocorrectAndPool(context);
}
private void initSynchronously(Context context, Dictionary mainDict) {
mMainDict = mainDict;
addOrReplaceDictionary(mUnigramDictionaries, DICT_KEY_MAIN, mainDict);
addOrReplaceDictionary(mBigramDictionaries, DICT_KEY_MAIN, mainDict);
initWhitelistAndAutocorrectAndPool(context);
}
private void addOrReplaceDictionary(Map<String, Dictionary> dictionaries, String key,
Dictionary dict) {
final Dictionary oldDict = (dict == null)
? dictionaries.remove(key)
: dictionaries.put(key, dict);
if (oldDict != null && dict != oldDict) {
oldDict.close();
}
}
public void resetMainDict(final Context context, final int dictionaryResId,
final Locale locale) {
mMainDict = null;
new Thread("InitializeBinaryDictionary") {
public void run() {
final Dictionary newMainDict = DictionaryFactory.createDictionaryFromManager(
context, locale, dictionaryResId);
mMainDict = newMainDict;
addOrReplaceDictionary(mUnigramDictionaries, DICT_KEY_MAIN, newMainDict);
addOrReplaceDictionary(mBigramDictionaries, DICT_KEY_MAIN, newMainDict);
}
}.start();
}
public void setQuickFixesEnabled(boolean enabled) {
mQuickFixesEnabled = enabled;
}
public int getCorrectionMode() {
return mCorrectionMode;
}
public void setCorrectionMode(int mode) {
mCorrectionMode = mode;
}
// The main dictionary could have been loaded asynchronously. Don't cache the return value
// of this method.
public boolean hasMainDictionary() {
return mMainDict != null;
}
public ContactsDictionary getContactsDictionary() {
return mContactsDict;
}
public Map<String, Dictionary> getUnigramDictionaries() {
return mUnigramDictionaries;
}
public int getApproxMaxWordLength() {
return APPROX_MAX_WORD_LENGTH;
}
/**
* Sets an optional user dictionary resource to be loaded. The user dictionary is consulted
* before the main dictionary, if set. This refers to the system-managed user dictionary.
*/
public void setUserDictionary(Dictionary userDictionary) {
addOrReplaceDictionary(mUnigramDictionaries, DICT_KEY_USER, userDictionary);
}
/**
* Sets an optional contacts dictionary resource to be loaded. It is also possible to remove
* the contacts dictionary by passing null to this method. In this case no contacts dictionary
* won't be used.
*/
public void setContactsDictionary(ContactsDictionary contactsDictionary) {
mContactsDict = contactsDictionary;
addOrReplaceDictionary(mUnigramDictionaries, DICT_KEY_CONTACTS, contactsDictionary);
addOrReplaceDictionary(mBigramDictionaries, DICT_KEY_CONTACTS, contactsDictionary);
}
public void setUserUnigramDictionary(Dictionary userUnigramDictionary) {
addOrReplaceDictionary(mUnigramDictionaries, DICT_KEY_USER_UNIGRAM, userUnigramDictionary);
}
public void setUserBigramDictionary(Dictionary userBigramDictionary) {
addOrReplaceDictionary(mBigramDictionaries, DICT_KEY_USER_BIGRAM, userBigramDictionary);
}
public void setAutoCorrectionThreshold(double threshold) {
mAutoCorrectionThreshold = threshold;
}
public boolean isAggressiveAutoCorrectionMode() {
return (mAutoCorrectionThreshold == 0);
}
/**
* Number of suggestions to generate from the input key sequence. This has
* to be a number between 1 and 100 (inclusive).
* @param maxSuggestions
* @throws IllegalArgumentException if the number is out of range
*/
public void setMaxSuggestions(int maxSuggestions) {
if (maxSuggestions < 1 || maxSuggestions > 100) {
throw new IllegalArgumentException("maxSuggestions must be between 1 and 100");
}
mPrefMaxSuggestions = maxSuggestions;
mScores = new int[mPrefMaxSuggestions];
mBigramScores = new int[PREF_MAX_BIGRAMS];
collectGarbage(mSuggestions, mPrefMaxSuggestions);
StringBuilderPool.ensureCapacity(mPrefMaxSuggestions, getApproxMaxWordLength());
}
/**
* Returns a object which represents suggested words that match the list of character codes
* passed in. This object contents will be overwritten the next time this function is called.
* @param view a view for retrieving the context for AutoText
* @param wordComposer contains what is currently being typed
* @param prevWordForBigram previous word (used only for bigram)
* @return suggested words object.
*/
public SuggestedWords getSuggestions(final View view, final WordComposer wordComposer,
final CharSequence prevWordForBigram, final ProximityInfo proximityInfo) {
return getSuggestedWordBuilder(view, wordComposer, prevWordForBigram,
proximityInfo).build();
}
private CharSequence capitalizeWord(boolean all, boolean first, CharSequence word) {
if (TextUtils.isEmpty(word) || !(all || first)) return word;
final int wordLength = word.length();
final StringBuilder sb = StringBuilderPool.getStringBuilder(getApproxMaxWordLength());
// TODO: Must pay attention to locale when changing case.
if (all) {
sb.append(word.toString().toUpperCase());
} else if (first) {
sb.append(Character.toUpperCase(word.charAt(0)));
if (wordLength > 1) {
sb.append(word.subSequence(1, wordLength));
}
}
return sb;
}
protected void addBigramToSuggestions(CharSequence bigram) {
// TODO: Try to be a little more shrewd with resource allocation.
// At the moment we copy this object because the StringBuilders are pooled (see
// StringBuilderPool.java) and when we are finished using mSuggestions and
// mBigramSuggestions we will take everything from both and insert them back in the
// pool, so we can't allow the same object to be in both lists at the same time.
final StringBuilder sb = StringBuilderPool.getStringBuilder(getApproxMaxWordLength());
sb.append(bigram);
mSuggestions.add(sb);
}
// TODO: cleanup dictionaries looking up and suggestions building with SuggestedWords.Builder
public SuggestedWords.Builder getSuggestedWordBuilder(final View view,
final WordComposer wordComposer, CharSequence prevWordForBigram,
final ProximityInfo proximityInfo) {
LatinImeLogger.onStartSuggestion(prevWordForBigram);
mAutoCorrection.init();
mIsFirstCharCapitalized = wordComposer.isFirstCharCapitalized();
mIsAllUpperCase = wordComposer.isAllUpperCase();
collectGarbage(mSuggestions, mPrefMaxSuggestions);
Arrays.fill(mScores, 0);
// Save a lowercase version of the original word
CharSequence typedWord = wordComposer.getTypedWord();
if (typedWord != null) {
final String typedWordString = typedWord.toString();
typedWord = typedWordString;
// Treating USER_TYPED as UNIGRAM suggestion for logging now.
LatinImeLogger.onAddSuggestedWord(typedWordString, Suggest.DIC_USER_TYPED,
Dictionary.DataType.UNIGRAM);
}
mTypedWord = typedWord;
if (wordComposer.size() <= 1 && (mCorrectionMode == CORRECTION_FULL_BIGRAM
|| mCorrectionMode == CORRECTION_BASIC)) {
// At first character typed, search only the bigrams
Arrays.fill(mBigramScores, 0);
collectGarbage(mBigramSuggestions, PREF_MAX_BIGRAMS);
if (!TextUtils.isEmpty(prevWordForBigram)) {
CharSequence lowerPrevWord = prevWordForBigram.toString().toLowerCase();
if (mMainDict != null && mMainDict.isValidWord(lowerPrevWord)) {
prevWordForBigram = lowerPrevWord;
}
for (final Dictionary dictionary : mBigramDictionaries.values()) {
dictionary.getBigrams(wordComposer, prevWordForBigram, this);
}
if (TextUtils.isEmpty(typedWord)) {
// Nothing entered: return all bigrams for the previous word
int insertCount = Math.min(mBigramSuggestions.size(), mPrefMaxSuggestions);
for (int i = 0; i < insertCount; ++i) {
addBigramToSuggestions(mBigramSuggestions.get(i));
}
} else {
// Word entered: return only bigrams that match the first char of the typed word
final char currentChar = typedWord.charAt(0);
// TODO: Must pay attention to locale when changing case.
final char currentCharUpper = Character.toUpperCase(currentChar);
int count = 0;
final int bigramSuggestionSize = mBigramSuggestions.size();
for (int i = 0; i < bigramSuggestionSize; i++) {
final CharSequence bigramSuggestion = mBigramSuggestions.get(i);
final char bigramSuggestionFirstChar = bigramSuggestion.charAt(0);
if (bigramSuggestionFirstChar == currentChar
|| bigramSuggestionFirstChar == currentCharUpper) {
addBigramToSuggestions(bigramSuggestion);
if (++count > mPrefMaxSuggestions) break;
}
}
}
}
} else if (wordComposer.size() > 1) {
// At second character typed, search the unigrams (scores being affected by bigrams)
for (final String key : mUnigramDictionaries.keySet()) {
// Skip UserUnigramDictionary and WhitelistDictionary to lookup
if (key.equals(DICT_KEY_USER_UNIGRAM) || key.equals(DICT_KEY_WHITELIST))
continue;
final Dictionary dictionary = mUnigramDictionaries.get(key);
dictionary.getWords(wordComposer, this, proximityInfo);
}
}
CharSequence autoText = null;
final String typedWordString = typedWord == null ? null : typedWord.toString();
if (typedWord != null) {
// Apply quick fix only for the typed word.
if (mQuickFixesEnabled) {
final String lowerCaseTypedWord = typedWordString.toLowerCase();
- CharSequence tempAutoText = capitalizeWord(
- mIsAllUpperCase, mIsFirstCharCapitalized, AutoText.get(
- lowerCaseTypedWord, 0, lowerCaseTypedWord.length(), view));
- // TODO: cleanup canAdd
// Is there an AutoText (also known as Quick Fixes) correction?
// Capitalize as needed
- boolean canAdd = tempAutoText != null;
- // Is that correction already the current prediction (or original word)?
- canAdd &= !TextUtils.equals(tempAutoText, typedWord);
- // Is that correction already the next predicted word?
- if (canAdd && mSuggestions.size() > 0 && mCorrectionMode != CORRECTION_BASIC) {
- canAdd &= !TextUtils.equals(tempAutoText, mSuggestions.get(0));
- }
- if (canAdd) {
- if (DBG) {
- Log.d(TAG, "Auto corrected by AUTOTEXT.");
+ autoText = capitalizeWord(mIsAllUpperCase, mIsFirstCharCapitalized, AutoText.get(
+ lowerCaseTypedWord, 0, lowerCaseTypedWord.length(), view));
+ if (DBG) {
+ if (autoText != null) {
+ Log.d(TAG, "Auto corrected by AUTOTEXT: " + typedWord + " -> " + autoText);
}
- autoText = tempAutoText;
}
}
}
CharSequence whitelistedWord = capitalizeWord(mIsAllUpperCase, mIsFirstCharCapitalized,
mWhiteListDictionary.getWhiteListedWord(typedWordString));
mAutoCorrection.updateAutoCorrectionStatus(mUnigramDictionaries, wordComposer,
mSuggestions, mScores, typedWord, mAutoCorrectionThreshold, mCorrectionMode,
autoText, whitelistedWord);
if (autoText != null) {
mSuggestions.add(0, autoText);
}
if (whitelistedWord != null) {
mSuggestions.add(0, whitelistedWord);
}
if (typedWord != null) {
mSuggestions.add(0, typedWordString);
}
Utils.removeDupes(mSuggestions);
if (DBG) {
double normalizedScore = mAutoCorrection.getNormalizedScore();
ArrayList<SuggestedWords.SuggestedWordInfo> scoreInfoList =
new ArrayList<SuggestedWords.SuggestedWordInfo>();
scoreInfoList.add(new SuggestedWords.SuggestedWordInfo("+", false));
for (int i = 0; i < mScores.length; ++i) {
if (normalizedScore > 0) {
final String scoreThreshold = String.format("%d (%4.2f)", mScores[i],
normalizedScore);
scoreInfoList.add(
new SuggestedWords.SuggestedWordInfo(scoreThreshold, false));
normalizedScore = 0.0;
} else {
final String score = Integer.toString(mScores[i]);
scoreInfoList.add(new SuggestedWords.SuggestedWordInfo(score, false));
}
}
for (int i = mScores.length; i < mSuggestions.size(); ++i) {
scoreInfoList.add(new SuggestedWords.SuggestedWordInfo("--", false));
}
return new SuggestedWords.Builder().addWords(mSuggestions, scoreInfoList);
}
return new SuggestedWords.Builder().addWords(mSuggestions, null);
}
public boolean hasAutoCorrection() {
return mAutoCorrection.hasAutoCorrection();
}
@Override
public boolean addWord(final char[] word, final int offset, final int length, int score,
final int dicTypeId, final Dictionary.DataType dataType) {
Dictionary.DataType dataTypeForLog = dataType;
final ArrayList<CharSequence> suggestions;
final int[] sortedScores;
final int prefMaxSuggestions;
if(dataType == Dictionary.DataType.BIGRAM) {
suggestions = mBigramSuggestions;
sortedScores = mBigramScores;
prefMaxSuggestions = PREF_MAX_BIGRAMS;
} else {
suggestions = mSuggestions;
sortedScores = mScores;
prefMaxSuggestions = mPrefMaxSuggestions;
}
int pos = 0;
// Check if it's the same word, only caps are different
if (Utils.equalsIgnoreCase(mTypedWord, word, offset, length)) {
// TODO: remove this surrounding if clause and move this logic to
// getSuggestedWordBuilder.
if (suggestions.size() > 0) {
final String currentHighestWord = suggestions.get(0).toString();
// If the current highest word is also equal to typed word, we need to compare
// frequency to determine the insertion position. This does not ensure strictly
// correct ordering, but ensures the top score is on top which is enough for
// removing duplicates correctly.
if (Utils.equalsIgnoreCase(currentHighestWord, word, offset, length)
&& score <= sortedScores[0]) {
pos = 1;
}
}
} else {
if (dataType == Dictionary.DataType.UNIGRAM) {
// Check if the word was already added before (by bigram data)
int bigramSuggestion = searchBigramSuggestion(word,offset,length);
if(bigramSuggestion >= 0) {
dataTypeForLog = Dictionary.DataType.BIGRAM;
// turn freq from bigram into multiplier specified above
double multiplier = (((double) mBigramScores[bigramSuggestion])
/ MAXIMUM_BIGRAM_FREQUENCY)
* (BIGRAM_MULTIPLIER_MAX - BIGRAM_MULTIPLIER_MIN)
+ BIGRAM_MULTIPLIER_MIN;
/* Log.d(TAG,"bigram num: " + bigramSuggestion
+ " wordB: " + mBigramSuggestions.get(bigramSuggestion).toString()
+ " currentScore: " + score + " bigramScore: "
+ mBigramScores[bigramSuggestion]
+ " multiplier: " + multiplier); */
score = (int)Math.round((score * multiplier));
}
}
// Check the last one's score and bail
if (sortedScores[prefMaxSuggestions - 1] >= score) return true;
while (pos < prefMaxSuggestions) {
if (sortedScores[pos] < score
|| (sortedScores[pos] == score && length < suggestions.get(pos).length())) {
break;
}
pos++;
}
}
if (pos >= prefMaxSuggestions) {
return true;
}
System.arraycopy(sortedScores, pos, sortedScores, pos + 1, prefMaxSuggestions - pos - 1);
sortedScores[pos] = score;
final StringBuilder sb = StringBuilderPool.getStringBuilder(getApproxMaxWordLength());
// TODO: Must pay attention to locale when changing case.
if (mIsAllUpperCase) {
sb.append(new String(word, offset, length).toUpperCase());
} else if (mIsFirstCharCapitalized) {
sb.append(Character.toUpperCase(word[offset]));
if (length > 1) {
sb.append(word, offset + 1, length - 1);
}
} else {
sb.append(word, offset, length);
}
suggestions.add(pos, sb);
if (suggestions.size() > prefMaxSuggestions) {
final CharSequence garbage = suggestions.remove(prefMaxSuggestions);
if (garbage instanceof StringBuilder) {
StringBuilderPool.recycle((StringBuilder)garbage);
}
} else {
LatinImeLogger.onAddSuggestedWord(sb.toString(), dicTypeId, dataTypeForLog);
}
return true;
}
private int searchBigramSuggestion(final char[] word, final int offset, final int length) {
// TODO This is almost O(n^2). Might need fix.
// search whether the word appeared in bigram data
int bigramSuggestSize = mBigramSuggestions.size();
for(int i = 0; i < bigramSuggestSize; i++) {
if(mBigramSuggestions.get(i).length() == length) {
boolean chk = true;
for(int j = 0; j < length; j++) {
if(mBigramSuggestions.get(i).charAt(j) != word[offset+j]) {
chk = false;
break;
}
}
if(chk) return i;
}
}
return -1;
}
private void collectGarbage(ArrayList<CharSequence> suggestions, int prefMaxSuggestions) {
int poolSize = StringBuilderPool.getSize();
int garbageSize = suggestions.size();
while (poolSize < prefMaxSuggestions && garbageSize > 0) {
final CharSequence garbage = suggestions.get(garbageSize - 1);
if (garbage instanceof StringBuilder) {
StringBuilderPool.recycle((StringBuilder)garbage);
poolSize++;
}
garbageSize--;
}
if (poolSize == prefMaxSuggestions + 1) {
Log.w("Suggest", "String pool got too big: " + poolSize);
}
suggestions.clear();
}
public void close() {
final Set<Dictionary> dictionaries = new HashSet<Dictionary>();
dictionaries.addAll(mUnigramDictionaries.values());
dictionaries.addAll(mBigramDictionaries.values());
for (final Dictionary dictionary : dictionaries) {
dictionary.close();
}
mMainDict = null;
}
}
| false | true | public SuggestedWords.Builder getSuggestedWordBuilder(final View view,
final WordComposer wordComposer, CharSequence prevWordForBigram,
final ProximityInfo proximityInfo) {
LatinImeLogger.onStartSuggestion(prevWordForBigram);
mAutoCorrection.init();
mIsFirstCharCapitalized = wordComposer.isFirstCharCapitalized();
mIsAllUpperCase = wordComposer.isAllUpperCase();
collectGarbage(mSuggestions, mPrefMaxSuggestions);
Arrays.fill(mScores, 0);
// Save a lowercase version of the original word
CharSequence typedWord = wordComposer.getTypedWord();
if (typedWord != null) {
final String typedWordString = typedWord.toString();
typedWord = typedWordString;
// Treating USER_TYPED as UNIGRAM suggestion for logging now.
LatinImeLogger.onAddSuggestedWord(typedWordString, Suggest.DIC_USER_TYPED,
Dictionary.DataType.UNIGRAM);
}
mTypedWord = typedWord;
if (wordComposer.size() <= 1 && (mCorrectionMode == CORRECTION_FULL_BIGRAM
|| mCorrectionMode == CORRECTION_BASIC)) {
// At first character typed, search only the bigrams
Arrays.fill(mBigramScores, 0);
collectGarbage(mBigramSuggestions, PREF_MAX_BIGRAMS);
if (!TextUtils.isEmpty(prevWordForBigram)) {
CharSequence lowerPrevWord = prevWordForBigram.toString().toLowerCase();
if (mMainDict != null && mMainDict.isValidWord(lowerPrevWord)) {
prevWordForBigram = lowerPrevWord;
}
for (final Dictionary dictionary : mBigramDictionaries.values()) {
dictionary.getBigrams(wordComposer, prevWordForBigram, this);
}
if (TextUtils.isEmpty(typedWord)) {
// Nothing entered: return all bigrams for the previous word
int insertCount = Math.min(mBigramSuggestions.size(), mPrefMaxSuggestions);
for (int i = 0; i < insertCount; ++i) {
addBigramToSuggestions(mBigramSuggestions.get(i));
}
} else {
// Word entered: return only bigrams that match the first char of the typed word
final char currentChar = typedWord.charAt(0);
// TODO: Must pay attention to locale when changing case.
final char currentCharUpper = Character.toUpperCase(currentChar);
int count = 0;
final int bigramSuggestionSize = mBigramSuggestions.size();
for (int i = 0; i < bigramSuggestionSize; i++) {
final CharSequence bigramSuggestion = mBigramSuggestions.get(i);
final char bigramSuggestionFirstChar = bigramSuggestion.charAt(0);
if (bigramSuggestionFirstChar == currentChar
|| bigramSuggestionFirstChar == currentCharUpper) {
addBigramToSuggestions(bigramSuggestion);
if (++count > mPrefMaxSuggestions) break;
}
}
}
}
} else if (wordComposer.size() > 1) {
// At second character typed, search the unigrams (scores being affected by bigrams)
for (final String key : mUnigramDictionaries.keySet()) {
// Skip UserUnigramDictionary and WhitelistDictionary to lookup
if (key.equals(DICT_KEY_USER_UNIGRAM) || key.equals(DICT_KEY_WHITELIST))
continue;
final Dictionary dictionary = mUnigramDictionaries.get(key);
dictionary.getWords(wordComposer, this, proximityInfo);
}
}
CharSequence autoText = null;
final String typedWordString = typedWord == null ? null : typedWord.toString();
if (typedWord != null) {
// Apply quick fix only for the typed word.
if (mQuickFixesEnabled) {
final String lowerCaseTypedWord = typedWordString.toLowerCase();
CharSequence tempAutoText = capitalizeWord(
mIsAllUpperCase, mIsFirstCharCapitalized, AutoText.get(
lowerCaseTypedWord, 0, lowerCaseTypedWord.length(), view));
// TODO: cleanup canAdd
// Is there an AutoText (also known as Quick Fixes) correction?
// Capitalize as needed
boolean canAdd = tempAutoText != null;
// Is that correction already the current prediction (or original word)?
canAdd &= !TextUtils.equals(tempAutoText, typedWord);
// Is that correction already the next predicted word?
if (canAdd && mSuggestions.size() > 0 && mCorrectionMode != CORRECTION_BASIC) {
canAdd &= !TextUtils.equals(tempAutoText, mSuggestions.get(0));
}
if (canAdd) {
if (DBG) {
Log.d(TAG, "Auto corrected by AUTOTEXT.");
}
autoText = tempAutoText;
}
}
}
CharSequence whitelistedWord = capitalizeWord(mIsAllUpperCase, mIsFirstCharCapitalized,
mWhiteListDictionary.getWhiteListedWord(typedWordString));
mAutoCorrection.updateAutoCorrectionStatus(mUnigramDictionaries, wordComposer,
mSuggestions, mScores, typedWord, mAutoCorrectionThreshold, mCorrectionMode,
autoText, whitelistedWord);
if (autoText != null) {
mSuggestions.add(0, autoText);
}
if (whitelistedWord != null) {
mSuggestions.add(0, whitelistedWord);
}
if (typedWord != null) {
mSuggestions.add(0, typedWordString);
}
Utils.removeDupes(mSuggestions);
if (DBG) {
double normalizedScore = mAutoCorrection.getNormalizedScore();
ArrayList<SuggestedWords.SuggestedWordInfo> scoreInfoList =
new ArrayList<SuggestedWords.SuggestedWordInfo>();
scoreInfoList.add(new SuggestedWords.SuggestedWordInfo("+", false));
for (int i = 0; i < mScores.length; ++i) {
if (normalizedScore > 0) {
final String scoreThreshold = String.format("%d (%4.2f)", mScores[i],
normalizedScore);
scoreInfoList.add(
new SuggestedWords.SuggestedWordInfo(scoreThreshold, false));
normalizedScore = 0.0;
} else {
final String score = Integer.toString(mScores[i]);
scoreInfoList.add(new SuggestedWords.SuggestedWordInfo(score, false));
}
}
for (int i = mScores.length; i < mSuggestions.size(); ++i) {
scoreInfoList.add(new SuggestedWords.SuggestedWordInfo("--", false));
}
return new SuggestedWords.Builder().addWords(mSuggestions, scoreInfoList);
}
return new SuggestedWords.Builder().addWords(mSuggestions, null);
}
| public SuggestedWords.Builder getSuggestedWordBuilder(final View view,
final WordComposer wordComposer, CharSequence prevWordForBigram,
final ProximityInfo proximityInfo) {
LatinImeLogger.onStartSuggestion(prevWordForBigram);
mAutoCorrection.init();
mIsFirstCharCapitalized = wordComposer.isFirstCharCapitalized();
mIsAllUpperCase = wordComposer.isAllUpperCase();
collectGarbage(mSuggestions, mPrefMaxSuggestions);
Arrays.fill(mScores, 0);
// Save a lowercase version of the original word
CharSequence typedWord = wordComposer.getTypedWord();
if (typedWord != null) {
final String typedWordString = typedWord.toString();
typedWord = typedWordString;
// Treating USER_TYPED as UNIGRAM suggestion for logging now.
LatinImeLogger.onAddSuggestedWord(typedWordString, Suggest.DIC_USER_TYPED,
Dictionary.DataType.UNIGRAM);
}
mTypedWord = typedWord;
if (wordComposer.size() <= 1 && (mCorrectionMode == CORRECTION_FULL_BIGRAM
|| mCorrectionMode == CORRECTION_BASIC)) {
// At first character typed, search only the bigrams
Arrays.fill(mBigramScores, 0);
collectGarbage(mBigramSuggestions, PREF_MAX_BIGRAMS);
if (!TextUtils.isEmpty(prevWordForBigram)) {
CharSequence lowerPrevWord = prevWordForBigram.toString().toLowerCase();
if (mMainDict != null && mMainDict.isValidWord(lowerPrevWord)) {
prevWordForBigram = lowerPrevWord;
}
for (final Dictionary dictionary : mBigramDictionaries.values()) {
dictionary.getBigrams(wordComposer, prevWordForBigram, this);
}
if (TextUtils.isEmpty(typedWord)) {
// Nothing entered: return all bigrams for the previous word
int insertCount = Math.min(mBigramSuggestions.size(), mPrefMaxSuggestions);
for (int i = 0; i < insertCount; ++i) {
addBigramToSuggestions(mBigramSuggestions.get(i));
}
} else {
// Word entered: return only bigrams that match the first char of the typed word
final char currentChar = typedWord.charAt(0);
// TODO: Must pay attention to locale when changing case.
final char currentCharUpper = Character.toUpperCase(currentChar);
int count = 0;
final int bigramSuggestionSize = mBigramSuggestions.size();
for (int i = 0; i < bigramSuggestionSize; i++) {
final CharSequence bigramSuggestion = mBigramSuggestions.get(i);
final char bigramSuggestionFirstChar = bigramSuggestion.charAt(0);
if (bigramSuggestionFirstChar == currentChar
|| bigramSuggestionFirstChar == currentCharUpper) {
addBigramToSuggestions(bigramSuggestion);
if (++count > mPrefMaxSuggestions) break;
}
}
}
}
} else if (wordComposer.size() > 1) {
// At second character typed, search the unigrams (scores being affected by bigrams)
for (final String key : mUnigramDictionaries.keySet()) {
// Skip UserUnigramDictionary and WhitelistDictionary to lookup
if (key.equals(DICT_KEY_USER_UNIGRAM) || key.equals(DICT_KEY_WHITELIST))
continue;
final Dictionary dictionary = mUnigramDictionaries.get(key);
dictionary.getWords(wordComposer, this, proximityInfo);
}
}
CharSequence autoText = null;
final String typedWordString = typedWord == null ? null : typedWord.toString();
if (typedWord != null) {
// Apply quick fix only for the typed word.
if (mQuickFixesEnabled) {
final String lowerCaseTypedWord = typedWordString.toLowerCase();
// Is there an AutoText (also known as Quick Fixes) correction?
// Capitalize as needed
autoText = capitalizeWord(mIsAllUpperCase, mIsFirstCharCapitalized, AutoText.get(
lowerCaseTypedWord, 0, lowerCaseTypedWord.length(), view));
if (DBG) {
if (autoText != null) {
Log.d(TAG, "Auto corrected by AUTOTEXT: " + typedWord + " -> " + autoText);
}
}
}
}
CharSequence whitelistedWord = capitalizeWord(mIsAllUpperCase, mIsFirstCharCapitalized,
mWhiteListDictionary.getWhiteListedWord(typedWordString));
mAutoCorrection.updateAutoCorrectionStatus(mUnigramDictionaries, wordComposer,
mSuggestions, mScores, typedWord, mAutoCorrectionThreshold, mCorrectionMode,
autoText, whitelistedWord);
if (autoText != null) {
mSuggestions.add(0, autoText);
}
if (whitelistedWord != null) {
mSuggestions.add(0, whitelistedWord);
}
if (typedWord != null) {
mSuggestions.add(0, typedWordString);
}
Utils.removeDupes(mSuggestions);
if (DBG) {
double normalizedScore = mAutoCorrection.getNormalizedScore();
ArrayList<SuggestedWords.SuggestedWordInfo> scoreInfoList =
new ArrayList<SuggestedWords.SuggestedWordInfo>();
scoreInfoList.add(new SuggestedWords.SuggestedWordInfo("+", false));
for (int i = 0; i < mScores.length; ++i) {
if (normalizedScore > 0) {
final String scoreThreshold = String.format("%d (%4.2f)", mScores[i],
normalizedScore);
scoreInfoList.add(
new SuggestedWords.SuggestedWordInfo(scoreThreshold, false));
normalizedScore = 0.0;
} else {
final String score = Integer.toString(mScores[i]);
scoreInfoList.add(new SuggestedWords.SuggestedWordInfo(score, false));
}
}
for (int i = mScores.length; i < mSuggestions.size(); ++i) {
scoreInfoList.add(new SuggestedWords.SuggestedWordInfo("--", false));
}
return new SuggestedWords.Builder().addWords(mSuggestions, scoreInfoList);
}
return new SuggestedWords.Builder().addWords(mSuggestions, null);
}
|
diff --git a/TargetClassification/src/featureselection/BackwardsElimination.java b/TargetClassification/src/featureselection/BackwardsElimination.java
index fc3d2ae..ca6cf56 100644
--- a/TargetClassification/src/featureselection/BackwardsElimination.java
+++ b/TargetClassification/src/featureselection/BackwardsElimination.java
@@ -1,673 +1,673 @@
package featureselection;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import datasetgeneration.BootstrapGeneration;
import datasetgeneration.CrossValidationFoldGenerationMultiClass;
import tree.Forest;
import tree.ImmutableThreeValues;
import tree.ImmutableTwoValues;
import tree.ProcessDataForGrowing;
import tree.TreeGrowthControl;
public class BackwardsElimination
{
/**
* @param args
*/
public static void main(String[] args)
{
// Required inputs.
String inputLocation = args[0]; // The location of the file containing the dataset to use in the feature selection.
File inputFile = new File(inputLocation);
if (!inputFile.isFile())
{
System.out.println("The first argument must be a valid file location, and must contain the dataset for feature selection.");
System.exit(0);
}
String outputLocation = args[1]; // The location to store any and all results.
File outputDirectory = new File(outputLocation);
if (!outputDirectory.exists())
{
boolean isDirCreated = outputDirectory.mkdirs();
if (!isDirCreated)
{
System.out.println("The output directory could not be created.");
System.exit(0);
}
}
else if (!outputDirectory.isDirectory())
{
// Exists and is not a directory.
System.out.println("The second argument must be a valid directory location or location where a directory can be created.");
System.exit(0);
}
String entireDatasetVarImpLocation = args[2]; // The location for the repetitions of the variable importance calculations for the entire dtaset.
File varImpFile = new File(entireDatasetVarImpLocation);
if (!varImpFile.isFile())
{
System.out.println("The third argument must be a valid file location, and must contain the variable importances calculated for the entire dataset.");
System.exit(0);
}
//===================================================================
//==================== CONTROL PARAMETER SETTING ====================
//===================================================================
int externalSubsamplesToGenerate = 100;
- double fractionToReserveAsValidation = 0.1;
+ double fractionToReserveAsValidation = 0.2;
int internalSubsamplesToGenerate = 10;
- int validationIterations = 1;
+ int validationIterations = 10;
double fractionToElim = 0.02; // Eliminating a fraction allows you to remove lots of variables when there are lots remaining, and get better resolution when there are few remaining.
boolean continueRun = false; // Whether or not you want to continue a run in progress or restart the whole process.
Integer[] trainingObsToUse = {};
TreeGrowthControl ctrl = new TreeGrowthControl();
ctrl.isReplacementUsed = true;
ctrl.numberOfTreesToGrow = 500;
ctrl.mtry = 10;
ctrl.isStratifiedBootstrapUsed = true;
ctrl.isCalculateOOB = false;
ctrl.minNodeSize = 1;
ctrl.trainingObservations = Arrays.asList(trainingObsToUse);
TreeGrowthControl varImpCtrl = new TreeGrowthControl(ctrl);
- varImpCtrl.numberOfTreesToGrow = 500;
+ varImpCtrl.numberOfTreesToGrow = 5000;
varImpCtrl.trainingObservations = Arrays.asList(trainingObsToUse);
Map<String, Double> weights = new HashMap<String, Double>();
weights.put("Unlabelled", 1.0);
weights.put("Positive", 1.0);
//===================================================================
//==================== CONTROL PARAMETER SETTING ====================
//===================================================================
// Get the names and types of the features (the types are so that you know which features are the response and which aren't used).
String featureNames[] = null;
String featureTypes[] = null;
try (BufferedReader reader = Files.newBufferedReader(Paths.get(inputLocation), StandardCharsets.UTF_8))
{
String line = reader.readLine();
line = line.replaceAll("\n", "");
featureNames = line.split("\t");
line = reader.readLine();
line = line.toLowerCase();
line = line.replaceAll("\n", "");
featureTypes = line.split("\t");
}
catch (Exception e)
{
e.printStackTrace();
System.exit(0);
}
// Determine the features that are used in growing the trees.
List<String> featuresUsed = new ArrayList<String>();
for (int i = 0; i < featureNames.length; i++)
{
if (featureTypes[i].equals("x") || featureTypes[i].equals("r"))
{
// If the feature is a response variable or is to be skipped.
continue;
}
featuresUsed.add(featureNames[i]);
}
// Determine whether bootstrap samples need to be generated.
String resultsOutputLoc = outputLocation + "/Results.txt";
String parameterLocation = outputLocation + "/Parameters.txt";
String subsetSizeErrorRates = outputLocation + "/ErrorRates.txt";
String subsetSizeGMeans = outputLocation + "/GMeans.txt";
if (!continueRun)
{
// Generate bootstraps and recreate the results file.
removeDirectoryContent(outputDirectory);
BootstrapGeneration.main(inputLocation, outputLocation, externalSubsamplesToGenerate, false, 1 - fractionToReserveAsValidation);
try
{
FileWriter featureFractionsOutputFile = new FileWriter(resultsOutputLoc);
BufferedWriter featureFractionsOutputWriter = new BufferedWriter(featureFractionsOutputFile);
for (String s : featuresUsed)
{
featureFractionsOutputWriter.write(s + "\t");
}
featureFractionsOutputWriter.write("GMean\tErrorRate");
featureFractionsOutputWriter.newLine();
featureFractionsOutputWriter.close();
FileWriter parameterOutputFile = new FileWriter(parameterLocation);
BufferedWriter parameterOutputWriter = new BufferedWriter(parameterOutputFile);
parameterOutputWriter.write("External subsamples generated - " + Integer.toString(externalSubsamplesToGenerate));
parameterOutputWriter.newLine();
parameterOutputWriter.write("Fraction to reserve as validation - " + Double.toString(fractionToReserveAsValidation));
parameterOutputWriter.newLine();
parameterOutputWriter.write("Internal subsamples generated - " + Integer.toString(internalSubsamplesToGenerate));
parameterOutputWriter.newLine();
parameterOutputWriter.write("Validation iterations performed - " + Integer.toString(validationIterations));
parameterOutputWriter.newLine();
parameterOutputWriter.write("Fraction of features to eliminate each round - " + Double.toString(fractionToElim));
parameterOutputWriter.newLine();
parameterOutputWriter.write("Trees used in training - " + Integer.toString(ctrl.numberOfTreesToGrow));
parameterOutputWriter.newLine();
parameterOutputWriter.write("Trees used for variable importance - " + Integer.toString(varImpCtrl.numberOfTreesToGrow));
parameterOutputWriter.newLine();
parameterOutputWriter.write("Weights used - " + weights.toString());
parameterOutputWriter.newLine();
parameterOutputWriter.close();
FileWriter errorRateOutputFile = new FileWriter(subsetSizeErrorRates);
BufferedWriter errorRateOutputWriter = new BufferedWriter(errorRateOutputFile);
int numberOfFeaturesRemaining = featuresUsed.size();
String featureNumberHeader = "";
double featuresToEliminate;
while (numberOfFeaturesRemaining > 0)
{
featureNumberHeader += Integer.toString(numberOfFeaturesRemaining) + "\t";
featuresToEliminate = (int) Math.ceil(numberOfFeaturesRemaining * fractionToElim);
numberOfFeaturesRemaining -= featuresToEliminate;
}
featureNumberHeader = featureNumberHeader.substring(0, featureNumberHeader.length() - 1);
errorRateOutputWriter.write(featureNumberHeader);
errorRateOutputWriter.newLine();
errorRateOutputWriter.close();
FileWriter gMeanOutputFile = new FileWriter(subsetSizeGMeans);
BufferedWriter gMeanOutputWriter = new BufferedWriter(gMeanOutputFile);
gMeanOutputWriter.write(featureNumberHeader);
gMeanOutputWriter.newLine();
gMeanOutputWriter.close();
ctrl.save(outputLocation + "/RegularCtrl.txt");
varImpCtrl.save(outputLocation + "/VariableImportanceCtrl.txt");
}
catch (Exception e)
{
e.printStackTrace();
System.exit(0);
}
}
for (int i = 0; i < externalSubsamplesToGenerate; i++)
{
String subsampleDirectory = outputLocation + "/" + Integer.toString(i);
if ((new File(subsampleDirectory + "/ErrorForThisSubsample.txt")).exists())
{
continue;
}
Date currentTime = new Date();
DateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String strDate = sdfDate.format(currentTime);
System.out.format("Now working on subsample %d at %s.\n", i, strDate);
String subsampleTrainingSet = subsampleDirectory + "/Train.txt";
String subsampleTestingSet = subsampleDirectory + "/Test.txt";
String internalFoldDirLoc = subsampleDirectory + "/Folds";
ImmutableThreeValues<Integer, Map<Integer, Double>, Map<Integer, Double>> internalSelectionResults = internalSelection(subsampleTrainingSet,
internalFoldDirLoc, internalSubsamplesToGenerate, weights, ctrl, varImpCtrl, featuresUsed, fractionToElim);
int bestNumberOfFeatures = internalSelectionResults.first;
Map<Integer, Double> averageErrorRates = internalSelectionResults.second;
Map<Integer, Double> averageGMeans = internalSelectionResults.third;
// Determine and validate best feature subset.
currentTime = new Date();
sdfDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
strDate = sdfDate.format(currentTime);
System.out.format("\tNow validating the feature set at %s.\n", strDate);
ImmutableThreeValues<List<String>, Double, Double> validationResults = validateSubset(subsampleTrainingSet, subsampleTestingSet,
bestNumberOfFeatures, weights, new TreeGrowthControl(varImpCtrl), featuresUsed, validationIterations);
List<String> bestFeatureSet = validationResults.first;
double validatedError = validationResults.second;
double validatedGMean = validationResults.third;
// Write out the results for this external subsample.
try
{
FileWriter featureFractionsOutputFile = new FileWriter(resultsOutputLoc, true);
BufferedWriter featureFractionsOutputWriter = new BufferedWriter(featureFractionsOutputFile);
for (String s : featuresUsed)
{
if (bestFeatureSet.contains(s))
{
featureFractionsOutputWriter.write("1\t");
}
else
{
featureFractionsOutputWriter.write("0\t");
}
}
featureFractionsOutputWriter.write(Double.toString(validatedGMean));
featureFractionsOutputWriter.write("\t");
featureFractionsOutputWriter.write(Double.toString(validatedError));
featureFractionsOutputWriter.newLine();
featureFractionsOutputWriter.close();
FileWriter subsampleOutputFile = new FileWriter(subsampleDirectory + "/ErrorForThisSubsample.txt");
BufferedWriter subsampleOutputWriter = new BufferedWriter(subsampleOutputFile);
subsampleOutputWriter.write("ErrorRate = ");
subsampleOutputWriter.write(Double.toString(validatedError));
subsampleOutputWriter.close();
List<Integer> featureSetSizes = new ArrayList<Integer>(averageErrorRates.keySet());
Collections.sort(featureSetSizes, Collections.reverseOrder());
FileWriter errorRateOutputFile = new FileWriter(subsetSizeErrorRates, true);
BufferedWriter errorRateOutputWriter = new BufferedWriter(errorRateOutputFile);
FileWriter gMeanOutputFile = new FileWriter(subsetSizeGMeans, true);
BufferedWriter gMeanOutputWriter = new BufferedWriter(gMeanOutputFile);
String errorOutput = "";
String gMeanOutput = "";
for (Integer j : featureSetSizes)
{
errorOutput += Double.toString(averageErrorRates.get(j)) + "\t";
gMeanOutput += Double.toString(averageGMeans.get(j)) + "\t";
}
errorOutput.substring(0, errorOutput.length() - 1);
errorRateOutputWriter.write(errorOutput);
errorRateOutputWriter.newLine();
errorRateOutputWriter.close();
gMeanOutput.substring(0, gMeanOutput.length() - 1);
gMeanOutputWriter.write(gMeanOutput);
gMeanOutputWriter.newLine();
gMeanOutputWriter.close();
}
catch (Exception e)
{
e.printStackTrace();
System.exit(0);
}
}
//---------------------------------------------//
// Perform the whole dataset feature selection //
//---------------------------------------------//
Date currentTime = new Date();
DateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String strDate = sdfDate.format(currentTime);
System.out.format("Now working on the full feature set selection at %s.\n", strDate);
String finalSelectionOutputLoc = outputLocation + "/FinalSelection";
String finalSelectionErrorRates = finalSelectionOutputLoc + "/ErrorRates.txt";
String finalSelectionGMeans = finalSelectionOutputLoc + "/GMeans.txt";
String finalSelectionResults = finalSelectionOutputLoc + "/Results.txt";
ImmutableThreeValues<Integer, Map<Integer, Double>, Map<Integer, Double>> internalSelectionResults = internalSelection(inputLocation,
finalSelectionOutputLoc, internalSubsamplesToGenerate, weights, ctrl, varImpCtrl, featuresUsed, 0.0001); // Use 0.0001 as the feature elimination fraction to ensure that only one feature is eliminated per iteraton.
int bestNumberOfFeatures = internalSelectionResults.first;
Map<Integer, Double> averageErrorRates = internalSelectionResults.second;
Map<Integer, Double> averageGMeans = internalSelectionResults.third;
// Determine and validate best feature subset.
currentTime = new Date();
sdfDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
strDate = sdfDate.format(currentTime);
System.out.format("\tNow validating the feature set at %s.\n", strDate);
List<StringsSortedByDoubles> sortedVariables = new ArrayList<StringsSortedByDoubles>();
try (BufferedReader reader = Files.newBufferedReader(Paths.get(entireDatasetVarImpLocation), StandardCharsets.UTF_8))
{
- String line;
+ String line = reader.readLine(); // Strip off the first line header.
while ((line = reader.readLine()) != null)
{
line = line.replaceAll("\n", "");
String[] chunks = line.split("\t");
double averageRank = 0.0;
- for (int i = 1; i < chunks.length; i++)
+ for (int i = 0; i < chunks.length; i++)
{
averageRank += Integer.parseInt(chunks[i]);
}
averageRank /= (chunks.length - 1);
sortedVariables.add(new StringsSortedByDoubles(averageRank, chunks[0]));
}
}
catch (Exception e)
{
e.printStackTrace();
System.exit(0);
}
Collections.sort(sortedVariables); // Smaller ranks first.
List<String> orderedFeaturesByImportance = new ArrayList<String>();
for (StringsSortedByDoubles ssbd : sortedVariables)
{
orderedFeaturesByImportance.add(ssbd.getId());
}
List<String> bestFeatureSet = new ArrayList<String>();
for (int i = 0; i < bestNumberOfFeatures; i++)
{
bestFeatureSet.add(orderedFeaturesByImportance.get(i));
}
// Write out the results for the whole dataset selection.
try
{
FileWriter resultsOutputFile = new FileWriter(finalSelectionResults);
BufferedWriter resultsOutputWriter = new BufferedWriter(resultsOutputFile);
for (String s : featuresUsed)
{
if (bestFeatureSet.contains(s))
{
resultsOutputWriter.write(s);
resultsOutputWriter.newLine();
}
}
resultsOutputWriter.close();
List<Integer> featureSetSizes = new ArrayList<Integer>(averageErrorRates.keySet());
Collections.sort(featureSetSizes, Collections.reverseOrder());
FileWriter errorRateOutputFile = new FileWriter(finalSelectionErrorRates, true);
BufferedWriter errorRateOutputWriter = new BufferedWriter(errorRateOutputFile);
String errorOutput = "";
String errorRateHeader = "";
for (Integer j : featureSetSizes)
{
errorRateHeader += Integer.toString(j) + "\t";
errorOutput += Double.toString(averageErrorRates.get(j)) + "\t";
}
errorRateHeader = errorRateHeader.substring(0, errorRateHeader.length() - 1);
errorOutput.substring(0, errorOutput.length() - 1);
errorRateOutputWriter.write(errorRateHeader);
errorRateOutputWriter.newLine();
errorRateOutputWriter.write(errorOutput);
errorRateOutputWriter.close();
featureSetSizes = new ArrayList<Integer>(averageGMeans.keySet());
Collections.sort(featureSetSizes, Collections.reverseOrder());
FileWriter gMeanOutputFile = new FileWriter(finalSelectionGMeans, true);
BufferedWriter gMeanOutputWriter = new BufferedWriter(gMeanOutputFile);
String gMeanOutput = "";
for (Integer j : featureSetSizes)
{
gMeanOutput += Double.toString(averageGMeans.get(j)) + "\t";
}
gMeanOutput.substring(0, gMeanOutput.length() - 1);
gMeanOutputWriter.write(gMeanOutput);
gMeanOutputWriter.newLine();
gMeanOutputWriter.close();
}
catch (Exception e)
{
e.printStackTrace();
System.exit(0);
}
}
static ImmutableTwoValues<Map<Integer, Double>, Map<Integer, Double>> internalEvaluation(String internalSubsampleTrainingSet,
String internalSubsampleTestingSet, long internalSubsampleSeed, Map<String, Double> weights, TreeGrowthControl eliminationControl,
TreeGrowthControl variableImportanceControl, List<String> fullFeatureSet, double fractionToElim)
{
ProcessDataForGrowing processedInputData = new ProcessDataForGrowing(internalSubsampleTestingSet, eliminationControl);
Map<String, Integer> classCounts = new HashMap<String, Integer>();
for (String s : new HashSet<String>(processedInputData.responseData))
{
classCounts.put(s, Collections.frequency(processedInputData.responseData, s));
}
//--------------------------------------------------------------------//
// Determine the order of the features by feature importance ranking. //
//--------------------------------------------------------------------//
Forest forest = new Forest(internalSubsampleTrainingSet, variableImportanceControl, internalSubsampleSeed);
forest.setWeightsByClass(weights);
forest.growForest();
Map<String, Double> varImp = forest.variableImportance().second;
// Rank the variables by importance.
List<StringsSortedByDoubles> sortedVariables = new ArrayList<StringsSortedByDoubles>();
for (String s : varImp.keySet())
{
sortedVariables.add(new StringsSortedByDoubles(varImp.get(s), s));
}
Collections.sort(sortedVariables, Collections.reverseOrder()); // Larger importance first.
List<String> orderedFeaturesByImportance = new ArrayList<String>();
for (StringsSortedByDoubles ssbd : sortedVariables)
{
orderedFeaturesByImportance.add(ssbd.getId());
}
//--------------------------//
// Perform the elimination. //
//--------------------------//
Map<Integer, Double> errorRates = new HashMap<Integer, Double>();
Map<Integer, Double> gMeans = new HashMap<Integer, Double>();
int featuresToEliminate;
while (!orderedFeaturesByImportance.isEmpty())
{
List<String> variablesToIgnore = new ArrayList<String>(fullFeatureSet);
variablesToIgnore.removeAll(orderedFeaturesByImportance);
eliminationControl.variablesToIgnore = variablesToIgnore;
forest = new Forest(internalSubsampleTrainingSet, eliminationControl, internalSubsampleSeed);
forest.setWeightsByClass(weights);
forest.growForest();
ImmutableTwoValues<Double, Map<String, Map<String, Double>>> predictionResults = forest.predict(new ProcessDataForGrowing(internalSubsampleTestingSet, eliminationControl));
errorRates.put(orderedFeaturesByImportance.size(), predictionResults.first);
Map<String, Map<String, Double>> confusionMatrix = predictionResults.second;
// Determine the macro G mean.
double macroGMean = 1.0;
for (String s : confusionMatrix.keySet())
{
double TP = confusionMatrix.get(s).get("TruePositive");
double FN = classCounts.get(s) - TP; // The number of false positives is the number of observations from the class in the test set - the number of true positives.
double recall = TP / (TP + FN);
macroGMean *= recall;
}
gMeans.put(orderedFeaturesByImportance.size(), Math.pow(macroGMean, (1.0 / classCounts.size())));
featuresToEliminate = (int) Math.ceil(orderedFeaturesByImportance.size() * fractionToElim);
for (int j = 0; j < featuresToEliminate; j++)
{
orderedFeaturesByImportance.remove(orderedFeaturesByImportance.size() - 1);
}
}
return new ImmutableTwoValues<Map<Integer, Double>, Map<Integer, Double>>(errorRates, gMeans);
}
static ImmutableThreeValues<Integer, Map<Integer, Double>, Map<Integer, Double>> internalSelection(String entireTrainingSet,
String locatonForInternalFolds, int internalSubsamplesToGenerate, Map<String, Double> weights, TreeGrowthControl ctrl,
TreeGrowthControl varImpCtrl, List<String> featuresUsed, double fractionToElim)
{
ctrl.variablesToIgnore = new ArrayList<String>();
CrossValidationFoldGenerationMultiClass.main(entireTrainingSet, locatonForInternalFolds, internalSubsamplesToGenerate);
List<Map<Integer, Double>> errorRates = new ArrayList<Map<Integer, Double>>();
List<Map<Integer, Double>> gMeans = new ArrayList<Map<Integer, Double>>();
List<Long> usedSeeds = new ArrayList<Long>();
Random seedGenerator = new Random();
for (int j = 0; j < internalSubsamplesToGenerate; j++)
{
Date currentTime = new Date();
DateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String strDate = sdfDate.format(currentTime);
System.out.format("\tNow performing elimination for CV fold %d at %s.\n", j, strDate);
long seedToUse = seedGenerator.nextLong(); // Determine the seed to use for the feature selection process on this bootstrap sample.
while (usedSeeds.contains(seedToUse))
{
seedToUse = seedGenerator.nextLong();
}
usedSeeds.add(seedToUse);
String internalFoldTrainingSet = locatonForInternalFolds + "/" + Integer.toString(j) + "/Train.txt";
String internalFoldTestingSet = locatonForInternalFolds + "/" + Integer.toString(j) + "/Test.txt";
ImmutableTwoValues<Map<Integer, Double>, Map<Integer, Double>> internalEvalResults = internalEvaluation(internalFoldTrainingSet,
internalFoldTestingSet, seedToUse, weights, new TreeGrowthControl(ctrl), varImpCtrl, featuresUsed, fractionToElim);
errorRates.add(internalEvalResults.first);
gMeans.add(internalEvalResults.second);
}
// Determine the average error rate and gMean for each size of feature subset, and the best feature set size.
Map<Integer, Double> averageErrorRates = new HashMap<Integer, Double>();
Map<Integer, Double> averageGMeans = new HashMap<Integer, Double>();
int bestNumberOfFeatures = featuresUsed.size();
double bestGMean = 0.0;
List<Integer> featureSetSizes = new ArrayList<Integer>(errorRates.get(0).keySet());
Collections.sort(featureSetSizes, Collections.reverseOrder());
for (Integer j : featureSetSizes)
{
double averageError = 0.0;
double averageGMean = 0.0;
for (int k = 0; k < internalSubsamplesToGenerate; k++)
{
averageError += errorRates.get(k).get(j);
averageGMean += gMeans.get(k).get(j);
}
averageError /= internalSubsamplesToGenerate;
averageErrorRates.put(j, averageError);
averageGMean /= internalSubsamplesToGenerate;
averageGMeans.put(j, averageGMean);
if (averageGMean > bestGMean)
{
bestNumberOfFeatures = j;
bestGMean = averageGMean;
}
}
return new ImmutableThreeValues<Integer, Map<Integer, Double>, Map<Integer, Double>>(bestNumberOfFeatures, averageErrorRates, averageGMeans);
}
static ImmutableThreeValues<List<String>, Double, Double> validateSubset(String externalSubsampleTrainingSet, String externalSubsampleTestingSet,
int numberOfFeatures, Map<String, Double> weights, TreeGrowthControl variableImportanceControl,
List<String> fullFeatureSet, int validationIterations)
{
Random seedGenerator = new Random();
List<Long> seedsToUse = new ArrayList<Long>();
for (int i = 0; i < validationIterations; i++)
{
long newSeed = seedGenerator.nextLong();
while (seedsToUse.contains(newSeed))
{
newSeed = seedGenerator.nextLong();
}
seedsToUse.add(newSeed);
}
ProcessDataForGrowing processedInputData = new ProcessDataForGrowing(externalSubsampleTestingSet, variableImportanceControl);
Map<String, Integer> classCounts = new HashMap<String, Integer>();
for (String s : new HashSet<String>(processedInputData.responseData))
{
classCounts.put(s, Collections.frequency(processedInputData.responseData, s));
}
//--------------------------------------------------------------------//
// Determine the order of the features by feature importance ranking. //
//--------------------------------------------------------------------//
Map<String, List<Integer>> importanceRanking = new HashMap<String, List<Integer>>();
for (String s : fullFeatureSet)
{
importanceRanking.put(s, new ArrayList<Integer>());
}
for (int i = 0; i < validationIterations; i++)
{
Forest forest = new Forest(externalSubsampleTrainingSet, variableImportanceControl, seedsToUse.get(i));
forest.setWeightsByClass(weights);
forest.growForest();
Map<String, Double> varImp = forest.variableImportance().second;
List<StringsSortedByDoubles> sortedVariables = new ArrayList<StringsSortedByDoubles>();
for (String s : varImp.keySet())
{
sortedVariables.add(new StringsSortedByDoubles(varImp.get(s), s));
}
Collections.sort(sortedVariables, Collections.reverseOrder()); // Larger importance first.
for (int j = 0; j < varImp.size(); j++)
{
String feature = sortedVariables.get(j).getId();
importanceRanking.get(feature).add(j + 1);
}
}
// Rank the variables by importance.
List<StringsSortedByDoubles> sortedVariables = new ArrayList<StringsSortedByDoubles>();
for (String s : importanceRanking.keySet())
{
double averageRank = 0.0;
for (Integer i : importanceRanking.get(s))
{
averageRank += i;
}
averageRank /= validationIterations;
sortedVariables.add(new StringsSortedByDoubles(averageRank, s));
}
Collections.sort(sortedVariables); // Smaller ranks first.
List<String> orderedFeaturesByImportance = new ArrayList<String>();
for (StringsSortedByDoubles ssbd : sortedVariables)
{
orderedFeaturesByImportance.add(ssbd.getId());
}
//---------------------------//
// Select the best features. //
//---------------------------//
List<String> bestFeatures = new ArrayList<String>();
for (int i = 0; i < numberOfFeatures; i++)
{
bestFeatures.add(orderedFeaturesByImportance.get(i));
}
List<String> variablesToIgnore = new ArrayList<String>(fullFeatureSet);
variablesToIgnore.removeAll(bestFeatures);
variableImportanceControl.variablesToIgnore = variablesToIgnore;
double validatedErrorRate = 0.0;
double validatedGMean = 0.0;
for (int i = 0; i < validationIterations; i++)
{
Forest forest = new Forest(externalSubsampleTrainingSet, variableImportanceControl, seedsToUse.get(i));
forest.setWeightsByClass(weights);
forest.growForest();
ImmutableTwoValues<Double, Map<String, Map<String, Double>>> validationResults = forest.predict(new ProcessDataForGrowing(externalSubsampleTestingSet, variableImportanceControl));
validatedErrorRate += validationResults.first;
// Determine the macro G mean.
Map<String, Map<String, Double>> confusionMatrix = validationResults.second;
double macroGMean = 1.0;
for (String s : confusionMatrix.keySet())
{
double TP = confusionMatrix.get(s).get("TruePositive");
double FN = classCounts.get(s) - TP; // The number of false positives is the number of observaitons from the class - the number of true positives.
double recall = TP / (TP + FN);
macroGMean *= recall;
}
validatedGMean += Math.pow(macroGMean, (1.0 / classCounts.size()));
}
validatedErrorRate /= validationIterations;
validatedGMean /= validationIterations;
return new ImmutableThreeValues<List<String>, Double, Double>(bestFeatures, validatedErrorRate, validatedGMean);
}
static void removeDirectoryContent(File directory)
{
String directoryLocation = directory.getAbsolutePath();
if (directory.isDirectory())
{
String dirFiles[] = directory.list();
for (String s : dirFiles)
{
File subFile = new File(directoryLocation + "/" + s);
if (subFile.isDirectory())
{
removeDirectoryContent(subFile);
}
else
{
subFile.delete();
}
}
}
directory.delete();
}
}
| false | true | public static void main(String[] args)
{
// Required inputs.
String inputLocation = args[0]; // The location of the file containing the dataset to use in the feature selection.
File inputFile = new File(inputLocation);
if (!inputFile.isFile())
{
System.out.println("The first argument must be a valid file location, and must contain the dataset for feature selection.");
System.exit(0);
}
String outputLocation = args[1]; // The location to store any and all results.
File outputDirectory = new File(outputLocation);
if (!outputDirectory.exists())
{
boolean isDirCreated = outputDirectory.mkdirs();
if (!isDirCreated)
{
System.out.println("The output directory could not be created.");
System.exit(0);
}
}
else if (!outputDirectory.isDirectory())
{
// Exists and is not a directory.
System.out.println("The second argument must be a valid directory location or location where a directory can be created.");
System.exit(0);
}
String entireDatasetVarImpLocation = args[2]; // The location for the repetitions of the variable importance calculations for the entire dtaset.
File varImpFile = new File(entireDatasetVarImpLocation);
if (!varImpFile.isFile())
{
System.out.println("The third argument must be a valid file location, and must contain the variable importances calculated for the entire dataset.");
System.exit(0);
}
//===================================================================
//==================== CONTROL PARAMETER SETTING ====================
//===================================================================
int externalSubsamplesToGenerate = 100;
double fractionToReserveAsValidation = 0.1;
int internalSubsamplesToGenerate = 10;
int validationIterations = 1;
double fractionToElim = 0.02; // Eliminating a fraction allows you to remove lots of variables when there are lots remaining, and get better resolution when there are few remaining.
boolean continueRun = false; // Whether or not you want to continue a run in progress or restart the whole process.
Integer[] trainingObsToUse = {};
TreeGrowthControl ctrl = new TreeGrowthControl();
ctrl.isReplacementUsed = true;
ctrl.numberOfTreesToGrow = 500;
ctrl.mtry = 10;
ctrl.isStratifiedBootstrapUsed = true;
ctrl.isCalculateOOB = false;
ctrl.minNodeSize = 1;
ctrl.trainingObservations = Arrays.asList(trainingObsToUse);
TreeGrowthControl varImpCtrl = new TreeGrowthControl(ctrl);
varImpCtrl.numberOfTreesToGrow = 500;
varImpCtrl.trainingObservations = Arrays.asList(trainingObsToUse);
Map<String, Double> weights = new HashMap<String, Double>();
weights.put("Unlabelled", 1.0);
weights.put("Positive", 1.0);
//===================================================================
//==================== CONTROL PARAMETER SETTING ====================
//===================================================================
// Get the names and types of the features (the types are so that you know which features are the response and which aren't used).
String featureNames[] = null;
String featureTypes[] = null;
try (BufferedReader reader = Files.newBufferedReader(Paths.get(inputLocation), StandardCharsets.UTF_8))
{
String line = reader.readLine();
line = line.replaceAll("\n", "");
featureNames = line.split("\t");
line = reader.readLine();
line = line.toLowerCase();
line = line.replaceAll("\n", "");
featureTypes = line.split("\t");
}
catch (Exception e)
{
e.printStackTrace();
System.exit(0);
}
// Determine the features that are used in growing the trees.
List<String> featuresUsed = new ArrayList<String>();
for (int i = 0; i < featureNames.length; i++)
{
if (featureTypes[i].equals("x") || featureTypes[i].equals("r"))
{
// If the feature is a response variable or is to be skipped.
continue;
}
featuresUsed.add(featureNames[i]);
}
// Determine whether bootstrap samples need to be generated.
String resultsOutputLoc = outputLocation + "/Results.txt";
String parameterLocation = outputLocation + "/Parameters.txt";
String subsetSizeErrorRates = outputLocation + "/ErrorRates.txt";
String subsetSizeGMeans = outputLocation + "/GMeans.txt";
if (!continueRun)
{
// Generate bootstraps and recreate the results file.
removeDirectoryContent(outputDirectory);
BootstrapGeneration.main(inputLocation, outputLocation, externalSubsamplesToGenerate, false, 1 - fractionToReserveAsValidation);
try
{
FileWriter featureFractionsOutputFile = new FileWriter(resultsOutputLoc);
BufferedWriter featureFractionsOutputWriter = new BufferedWriter(featureFractionsOutputFile);
for (String s : featuresUsed)
{
featureFractionsOutputWriter.write(s + "\t");
}
featureFractionsOutputWriter.write("GMean\tErrorRate");
featureFractionsOutputWriter.newLine();
featureFractionsOutputWriter.close();
FileWriter parameterOutputFile = new FileWriter(parameterLocation);
BufferedWriter parameterOutputWriter = new BufferedWriter(parameterOutputFile);
parameterOutputWriter.write("External subsamples generated - " + Integer.toString(externalSubsamplesToGenerate));
parameterOutputWriter.newLine();
parameterOutputWriter.write("Fraction to reserve as validation - " + Double.toString(fractionToReserveAsValidation));
parameterOutputWriter.newLine();
parameterOutputWriter.write("Internal subsamples generated - " + Integer.toString(internalSubsamplesToGenerate));
parameterOutputWriter.newLine();
parameterOutputWriter.write("Validation iterations performed - " + Integer.toString(validationIterations));
parameterOutputWriter.newLine();
parameterOutputWriter.write("Fraction of features to eliminate each round - " + Double.toString(fractionToElim));
parameterOutputWriter.newLine();
parameterOutputWriter.write("Trees used in training - " + Integer.toString(ctrl.numberOfTreesToGrow));
parameterOutputWriter.newLine();
parameterOutputWriter.write("Trees used for variable importance - " + Integer.toString(varImpCtrl.numberOfTreesToGrow));
parameterOutputWriter.newLine();
parameterOutputWriter.write("Weights used - " + weights.toString());
parameterOutputWriter.newLine();
parameterOutputWriter.close();
FileWriter errorRateOutputFile = new FileWriter(subsetSizeErrorRates);
BufferedWriter errorRateOutputWriter = new BufferedWriter(errorRateOutputFile);
int numberOfFeaturesRemaining = featuresUsed.size();
String featureNumberHeader = "";
double featuresToEliminate;
while (numberOfFeaturesRemaining > 0)
{
featureNumberHeader += Integer.toString(numberOfFeaturesRemaining) + "\t";
featuresToEliminate = (int) Math.ceil(numberOfFeaturesRemaining * fractionToElim);
numberOfFeaturesRemaining -= featuresToEliminate;
}
featureNumberHeader = featureNumberHeader.substring(0, featureNumberHeader.length() - 1);
errorRateOutputWriter.write(featureNumberHeader);
errorRateOutputWriter.newLine();
errorRateOutputWriter.close();
FileWriter gMeanOutputFile = new FileWriter(subsetSizeGMeans);
BufferedWriter gMeanOutputWriter = new BufferedWriter(gMeanOutputFile);
gMeanOutputWriter.write(featureNumberHeader);
gMeanOutputWriter.newLine();
gMeanOutputWriter.close();
ctrl.save(outputLocation + "/RegularCtrl.txt");
varImpCtrl.save(outputLocation + "/VariableImportanceCtrl.txt");
}
catch (Exception e)
{
e.printStackTrace();
System.exit(0);
}
}
for (int i = 0; i < externalSubsamplesToGenerate; i++)
{
String subsampleDirectory = outputLocation + "/" + Integer.toString(i);
if ((new File(subsampleDirectory + "/ErrorForThisSubsample.txt")).exists())
{
continue;
}
Date currentTime = new Date();
DateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String strDate = sdfDate.format(currentTime);
System.out.format("Now working on subsample %d at %s.\n", i, strDate);
String subsampleTrainingSet = subsampleDirectory + "/Train.txt";
String subsampleTestingSet = subsampleDirectory + "/Test.txt";
String internalFoldDirLoc = subsampleDirectory + "/Folds";
ImmutableThreeValues<Integer, Map<Integer, Double>, Map<Integer, Double>> internalSelectionResults = internalSelection(subsampleTrainingSet,
internalFoldDirLoc, internalSubsamplesToGenerate, weights, ctrl, varImpCtrl, featuresUsed, fractionToElim);
int bestNumberOfFeatures = internalSelectionResults.first;
Map<Integer, Double> averageErrorRates = internalSelectionResults.second;
Map<Integer, Double> averageGMeans = internalSelectionResults.third;
// Determine and validate best feature subset.
currentTime = new Date();
sdfDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
strDate = sdfDate.format(currentTime);
System.out.format("\tNow validating the feature set at %s.\n", strDate);
ImmutableThreeValues<List<String>, Double, Double> validationResults = validateSubset(subsampleTrainingSet, subsampleTestingSet,
bestNumberOfFeatures, weights, new TreeGrowthControl(varImpCtrl), featuresUsed, validationIterations);
List<String> bestFeatureSet = validationResults.first;
double validatedError = validationResults.second;
double validatedGMean = validationResults.third;
// Write out the results for this external subsample.
try
{
FileWriter featureFractionsOutputFile = new FileWriter(resultsOutputLoc, true);
BufferedWriter featureFractionsOutputWriter = new BufferedWriter(featureFractionsOutputFile);
for (String s : featuresUsed)
{
if (bestFeatureSet.contains(s))
{
featureFractionsOutputWriter.write("1\t");
}
else
{
featureFractionsOutputWriter.write("0\t");
}
}
featureFractionsOutputWriter.write(Double.toString(validatedGMean));
featureFractionsOutputWriter.write("\t");
featureFractionsOutputWriter.write(Double.toString(validatedError));
featureFractionsOutputWriter.newLine();
featureFractionsOutputWriter.close();
FileWriter subsampleOutputFile = new FileWriter(subsampleDirectory + "/ErrorForThisSubsample.txt");
BufferedWriter subsampleOutputWriter = new BufferedWriter(subsampleOutputFile);
subsampleOutputWriter.write("ErrorRate = ");
subsampleOutputWriter.write(Double.toString(validatedError));
subsampleOutputWriter.close();
List<Integer> featureSetSizes = new ArrayList<Integer>(averageErrorRates.keySet());
Collections.sort(featureSetSizes, Collections.reverseOrder());
FileWriter errorRateOutputFile = new FileWriter(subsetSizeErrorRates, true);
BufferedWriter errorRateOutputWriter = new BufferedWriter(errorRateOutputFile);
FileWriter gMeanOutputFile = new FileWriter(subsetSizeGMeans, true);
BufferedWriter gMeanOutputWriter = new BufferedWriter(gMeanOutputFile);
String errorOutput = "";
String gMeanOutput = "";
for (Integer j : featureSetSizes)
{
errorOutput += Double.toString(averageErrorRates.get(j)) + "\t";
gMeanOutput += Double.toString(averageGMeans.get(j)) + "\t";
}
errorOutput.substring(0, errorOutput.length() - 1);
errorRateOutputWriter.write(errorOutput);
errorRateOutputWriter.newLine();
errorRateOutputWriter.close();
gMeanOutput.substring(0, gMeanOutput.length() - 1);
gMeanOutputWriter.write(gMeanOutput);
gMeanOutputWriter.newLine();
gMeanOutputWriter.close();
}
catch (Exception e)
{
e.printStackTrace();
System.exit(0);
}
}
//---------------------------------------------//
// Perform the whole dataset feature selection //
//---------------------------------------------//
Date currentTime = new Date();
DateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String strDate = sdfDate.format(currentTime);
System.out.format("Now working on the full feature set selection at %s.\n", strDate);
String finalSelectionOutputLoc = outputLocation + "/FinalSelection";
String finalSelectionErrorRates = finalSelectionOutputLoc + "/ErrorRates.txt";
String finalSelectionGMeans = finalSelectionOutputLoc + "/GMeans.txt";
String finalSelectionResults = finalSelectionOutputLoc + "/Results.txt";
ImmutableThreeValues<Integer, Map<Integer, Double>, Map<Integer, Double>> internalSelectionResults = internalSelection(inputLocation,
finalSelectionOutputLoc, internalSubsamplesToGenerate, weights, ctrl, varImpCtrl, featuresUsed, 0.0001); // Use 0.0001 as the feature elimination fraction to ensure that only one feature is eliminated per iteraton.
int bestNumberOfFeatures = internalSelectionResults.first;
Map<Integer, Double> averageErrorRates = internalSelectionResults.second;
Map<Integer, Double> averageGMeans = internalSelectionResults.third;
// Determine and validate best feature subset.
currentTime = new Date();
sdfDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
strDate = sdfDate.format(currentTime);
System.out.format("\tNow validating the feature set at %s.\n", strDate);
List<StringsSortedByDoubles> sortedVariables = new ArrayList<StringsSortedByDoubles>();
try (BufferedReader reader = Files.newBufferedReader(Paths.get(entireDatasetVarImpLocation), StandardCharsets.UTF_8))
{
String line;
while ((line = reader.readLine()) != null)
{
line = line.replaceAll("\n", "");
String[] chunks = line.split("\t");
double averageRank = 0.0;
for (int i = 1; i < chunks.length; i++)
{
averageRank += Integer.parseInt(chunks[i]);
}
averageRank /= (chunks.length - 1);
sortedVariables.add(new StringsSortedByDoubles(averageRank, chunks[0]));
}
}
catch (Exception e)
{
e.printStackTrace();
System.exit(0);
}
Collections.sort(sortedVariables); // Smaller ranks first.
List<String> orderedFeaturesByImportance = new ArrayList<String>();
for (StringsSortedByDoubles ssbd : sortedVariables)
{
orderedFeaturesByImportance.add(ssbd.getId());
}
List<String> bestFeatureSet = new ArrayList<String>();
for (int i = 0; i < bestNumberOfFeatures; i++)
{
bestFeatureSet.add(orderedFeaturesByImportance.get(i));
}
// Write out the results for the whole dataset selection.
try
{
FileWriter resultsOutputFile = new FileWriter(finalSelectionResults);
BufferedWriter resultsOutputWriter = new BufferedWriter(resultsOutputFile);
for (String s : featuresUsed)
{
if (bestFeatureSet.contains(s))
{
resultsOutputWriter.write(s);
resultsOutputWriter.newLine();
}
}
resultsOutputWriter.close();
List<Integer> featureSetSizes = new ArrayList<Integer>(averageErrorRates.keySet());
Collections.sort(featureSetSizes, Collections.reverseOrder());
FileWriter errorRateOutputFile = new FileWriter(finalSelectionErrorRates, true);
BufferedWriter errorRateOutputWriter = new BufferedWriter(errorRateOutputFile);
String errorOutput = "";
String errorRateHeader = "";
for (Integer j : featureSetSizes)
{
errorRateHeader += Integer.toString(j) + "\t";
errorOutput += Double.toString(averageErrorRates.get(j)) + "\t";
}
errorRateHeader = errorRateHeader.substring(0, errorRateHeader.length() - 1);
errorOutput.substring(0, errorOutput.length() - 1);
errorRateOutputWriter.write(errorRateHeader);
errorRateOutputWriter.newLine();
errorRateOutputWriter.write(errorOutput);
errorRateOutputWriter.close();
featureSetSizes = new ArrayList<Integer>(averageGMeans.keySet());
Collections.sort(featureSetSizes, Collections.reverseOrder());
FileWriter gMeanOutputFile = new FileWriter(finalSelectionGMeans, true);
BufferedWriter gMeanOutputWriter = new BufferedWriter(gMeanOutputFile);
String gMeanOutput = "";
for (Integer j : featureSetSizes)
{
gMeanOutput += Double.toString(averageGMeans.get(j)) + "\t";
}
gMeanOutput.substring(0, gMeanOutput.length() - 1);
gMeanOutputWriter.write(gMeanOutput);
gMeanOutputWriter.newLine();
gMeanOutputWriter.close();
}
catch (Exception e)
{
e.printStackTrace();
System.exit(0);
}
}
| public static void main(String[] args)
{
// Required inputs.
String inputLocation = args[0]; // The location of the file containing the dataset to use in the feature selection.
File inputFile = new File(inputLocation);
if (!inputFile.isFile())
{
System.out.println("The first argument must be a valid file location, and must contain the dataset for feature selection.");
System.exit(0);
}
String outputLocation = args[1]; // The location to store any and all results.
File outputDirectory = new File(outputLocation);
if (!outputDirectory.exists())
{
boolean isDirCreated = outputDirectory.mkdirs();
if (!isDirCreated)
{
System.out.println("The output directory could not be created.");
System.exit(0);
}
}
else if (!outputDirectory.isDirectory())
{
// Exists and is not a directory.
System.out.println("The second argument must be a valid directory location or location where a directory can be created.");
System.exit(0);
}
String entireDatasetVarImpLocation = args[2]; // The location for the repetitions of the variable importance calculations for the entire dtaset.
File varImpFile = new File(entireDatasetVarImpLocation);
if (!varImpFile.isFile())
{
System.out.println("The third argument must be a valid file location, and must contain the variable importances calculated for the entire dataset.");
System.exit(0);
}
//===================================================================
//==================== CONTROL PARAMETER SETTING ====================
//===================================================================
int externalSubsamplesToGenerate = 100;
double fractionToReserveAsValidation = 0.2;
int internalSubsamplesToGenerate = 10;
int validationIterations = 10;
double fractionToElim = 0.02; // Eliminating a fraction allows you to remove lots of variables when there are lots remaining, and get better resolution when there are few remaining.
boolean continueRun = false; // Whether or not you want to continue a run in progress or restart the whole process.
Integer[] trainingObsToUse = {};
TreeGrowthControl ctrl = new TreeGrowthControl();
ctrl.isReplacementUsed = true;
ctrl.numberOfTreesToGrow = 500;
ctrl.mtry = 10;
ctrl.isStratifiedBootstrapUsed = true;
ctrl.isCalculateOOB = false;
ctrl.minNodeSize = 1;
ctrl.trainingObservations = Arrays.asList(trainingObsToUse);
TreeGrowthControl varImpCtrl = new TreeGrowthControl(ctrl);
varImpCtrl.numberOfTreesToGrow = 5000;
varImpCtrl.trainingObservations = Arrays.asList(trainingObsToUse);
Map<String, Double> weights = new HashMap<String, Double>();
weights.put("Unlabelled", 1.0);
weights.put("Positive", 1.0);
//===================================================================
//==================== CONTROL PARAMETER SETTING ====================
//===================================================================
// Get the names and types of the features (the types are so that you know which features are the response and which aren't used).
String featureNames[] = null;
String featureTypes[] = null;
try (BufferedReader reader = Files.newBufferedReader(Paths.get(inputLocation), StandardCharsets.UTF_8))
{
String line = reader.readLine();
line = line.replaceAll("\n", "");
featureNames = line.split("\t");
line = reader.readLine();
line = line.toLowerCase();
line = line.replaceAll("\n", "");
featureTypes = line.split("\t");
}
catch (Exception e)
{
e.printStackTrace();
System.exit(0);
}
// Determine the features that are used in growing the trees.
List<String> featuresUsed = new ArrayList<String>();
for (int i = 0; i < featureNames.length; i++)
{
if (featureTypes[i].equals("x") || featureTypes[i].equals("r"))
{
// If the feature is a response variable or is to be skipped.
continue;
}
featuresUsed.add(featureNames[i]);
}
// Determine whether bootstrap samples need to be generated.
String resultsOutputLoc = outputLocation + "/Results.txt";
String parameterLocation = outputLocation + "/Parameters.txt";
String subsetSizeErrorRates = outputLocation + "/ErrorRates.txt";
String subsetSizeGMeans = outputLocation + "/GMeans.txt";
if (!continueRun)
{
// Generate bootstraps and recreate the results file.
removeDirectoryContent(outputDirectory);
BootstrapGeneration.main(inputLocation, outputLocation, externalSubsamplesToGenerate, false, 1 - fractionToReserveAsValidation);
try
{
FileWriter featureFractionsOutputFile = new FileWriter(resultsOutputLoc);
BufferedWriter featureFractionsOutputWriter = new BufferedWriter(featureFractionsOutputFile);
for (String s : featuresUsed)
{
featureFractionsOutputWriter.write(s + "\t");
}
featureFractionsOutputWriter.write("GMean\tErrorRate");
featureFractionsOutputWriter.newLine();
featureFractionsOutputWriter.close();
FileWriter parameterOutputFile = new FileWriter(parameterLocation);
BufferedWriter parameterOutputWriter = new BufferedWriter(parameterOutputFile);
parameterOutputWriter.write("External subsamples generated - " + Integer.toString(externalSubsamplesToGenerate));
parameterOutputWriter.newLine();
parameterOutputWriter.write("Fraction to reserve as validation - " + Double.toString(fractionToReserveAsValidation));
parameterOutputWriter.newLine();
parameterOutputWriter.write("Internal subsamples generated - " + Integer.toString(internalSubsamplesToGenerate));
parameterOutputWriter.newLine();
parameterOutputWriter.write("Validation iterations performed - " + Integer.toString(validationIterations));
parameterOutputWriter.newLine();
parameterOutputWriter.write("Fraction of features to eliminate each round - " + Double.toString(fractionToElim));
parameterOutputWriter.newLine();
parameterOutputWriter.write("Trees used in training - " + Integer.toString(ctrl.numberOfTreesToGrow));
parameterOutputWriter.newLine();
parameterOutputWriter.write("Trees used for variable importance - " + Integer.toString(varImpCtrl.numberOfTreesToGrow));
parameterOutputWriter.newLine();
parameterOutputWriter.write("Weights used - " + weights.toString());
parameterOutputWriter.newLine();
parameterOutputWriter.close();
FileWriter errorRateOutputFile = new FileWriter(subsetSizeErrorRates);
BufferedWriter errorRateOutputWriter = new BufferedWriter(errorRateOutputFile);
int numberOfFeaturesRemaining = featuresUsed.size();
String featureNumberHeader = "";
double featuresToEliminate;
while (numberOfFeaturesRemaining > 0)
{
featureNumberHeader += Integer.toString(numberOfFeaturesRemaining) + "\t";
featuresToEliminate = (int) Math.ceil(numberOfFeaturesRemaining * fractionToElim);
numberOfFeaturesRemaining -= featuresToEliminate;
}
featureNumberHeader = featureNumberHeader.substring(0, featureNumberHeader.length() - 1);
errorRateOutputWriter.write(featureNumberHeader);
errorRateOutputWriter.newLine();
errorRateOutputWriter.close();
FileWriter gMeanOutputFile = new FileWriter(subsetSizeGMeans);
BufferedWriter gMeanOutputWriter = new BufferedWriter(gMeanOutputFile);
gMeanOutputWriter.write(featureNumberHeader);
gMeanOutputWriter.newLine();
gMeanOutputWriter.close();
ctrl.save(outputLocation + "/RegularCtrl.txt");
varImpCtrl.save(outputLocation + "/VariableImportanceCtrl.txt");
}
catch (Exception e)
{
e.printStackTrace();
System.exit(0);
}
}
for (int i = 0; i < externalSubsamplesToGenerate; i++)
{
String subsampleDirectory = outputLocation + "/" + Integer.toString(i);
if ((new File(subsampleDirectory + "/ErrorForThisSubsample.txt")).exists())
{
continue;
}
Date currentTime = new Date();
DateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String strDate = sdfDate.format(currentTime);
System.out.format("Now working on subsample %d at %s.\n", i, strDate);
String subsampleTrainingSet = subsampleDirectory + "/Train.txt";
String subsampleTestingSet = subsampleDirectory + "/Test.txt";
String internalFoldDirLoc = subsampleDirectory + "/Folds";
ImmutableThreeValues<Integer, Map<Integer, Double>, Map<Integer, Double>> internalSelectionResults = internalSelection(subsampleTrainingSet,
internalFoldDirLoc, internalSubsamplesToGenerate, weights, ctrl, varImpCtrl, featuresUsed, fractionToElim);
int bestNumberOfFeatures = internalSelectionResults.first;
Map<Integer, Double> averageErrorRates = internalSelectionResults.second;
Map<Integer, Double> averageGMeans = internalSelectionResults.third;
// Determine and validate best feature subset.
currentTime = new Date();
sdfDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
strDate = sdfDate.format(currentTime);
System.out.format("\tNow validating the feature set at %s.\n", strDate);
ImmutableThreeValues<List<String>, Double, Double> validationResults = validateSubset(subsampleTrainingSet, subsampleTestingSet,
bestNumberOfFeatures, weights, new TreeGrowthControl(varImpCtrl), featuresUsed, validationIterations);
List<String> bestFeatureSet = validationResults.first;
double validatedError = validationResults.second;
double validatedGMean = validationResults.third;
// Write out the results for this external subsample.
try
{
FileWriter featureFractionsOutputFile = new FileWriter(resultsOutputLoc, true);
BufferedWriter featureFractionsOutputWriter = new BufferedWriter(featureFractionsOutputFile);
for (String s : featuresUsed)
{
if (bestFeatureSet.contains(s))
{
featureFractionsOutputWriter.write("1\t");
}
else
{
featureFractionsOutputWriter.write("0\t");
}
}
featureFractionsOutputWriter.write(Double.toString(validatedGMean));
featureFractionsOutputWriter.write("\t");
featureFractionsOutputWriter.write(Double.toString(validatedError));
featureFractionsOutputWriter.newLine();
featureFractionsOutputWriter.close();
FileWriter subsampleOutputFile = new FileWriter(subsampleDirectory + "/ErrorForThisSubsample.txt");
BufferedWriter subsampleOutputWriter = new BufferedWriter(subsampleOutputFile);
subsampleOutputWriter.write("ErrorRate = ");
subsampleOutputWriter.write(Double.toString(validatedError));
subsampleOutputWriter.close();
List<Integer> featureSetSizes = new ArrayList<Integer>(averageErrorRates.keySet());
Collections.sort(featureSetSizes, Collections.reverseOrder());
FileWriter errorRateOutputFile = new FileWriter(subsetSizeErrorRates, true);
BufferedWriter errorRateOutputWriter = new BufferedWriter(errorRateOutputFile);
FileWriter gMeanOutputFile = new FileWriter(subsetSizeGMeans, true);
BufferedWriter gMeanOutputWriter = new BufferedWriter(gMeanOutputFile);
String errorOutput = "";
String gMeanOutput = "";
for (Integer j : featureSetSizes)
{
errorOutput += Double.toString(averageErrorRates.get(j)) + "\t";
gMeanOutput += Double.toString(averageGMeans.get(j)) + "\t";
}
errorOutput.substring(0, errorOutput.length() - 1);
errorRateOutputWriter.write(errorOutput);
errorRateOutputWriter.newLine();
errorRateOutputWriter.close();
gMeanOutput.substring(0, gMeanOutput.length() - 1);
gMeanOutputWriter.write(gMeanOutput);
gMeanOutputWriter.newLine();
gMeanOutputWriter.close();
}
catch (Exception e)
{
e.printStackTrace();
System.exit(0);
}
}
//---------------------------------------------//
// Perform the whole dataset feature selection //
//---------------------------------------------//
Date currentTime = new Date();
DateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String strDate = sdfDate.format(currentTime);
System.out.format("Now working on the full feature set selection at %s.\n", strDate);
String finalSelectionOutputLoc = outputLocation + "/FinalSelection";
String finalSelectionErrorRates = finalSelectionOutputLoc + "/ErrorRates.txt";
String finalSelectionGMeans = finalSelectionOutputLoc + "/GMeans.txt";
String finalSelectionResults = finalSelectionOutputLoc + "/Results.txt";
ImmutableThreeValues<Integer, Map<Integer, Double>, Map<Integer, Double>> internalSelectionResults = internalSelection(inputLocation,
finalSelectionOutputLoc, internalSubsamplesToGenerate, weights, ctrl, varImpCtrl, featuresUsed, 0.0001); // Use 0.0001 as the feature elimination fraction to ensure that only one feature is eliminated per iteraton.
int bestNumberOfFeatures = internalSelectionResults.first;
Map<Integer, Double> averageErrorRates = internalSelectionResults.second;
Map<Integer, Double> averageGMeans = internalSelectionResults.third;
// Determine and validate best feature subset.
currentTime = new Date();
sdfDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
strDate = sdfDate.format(currentTime);
System.out.format("\tNow validating the feature set at %s.\n", strDate);
List<StringsSortedByDoubles> sortedVariables = new ArrayList<StringsSortedByDoubles>();
try (BufferedReader reader = Files.newBufferedReader(Paths.get(entireDatasetVarImpLocation), StandardCharsets.UTF_8))
{
String line = reader.readLine(); // Strip off the first line header.
while ((line = reader.readLine()) != null)
{
line = line.replaceAll("\n", "");
String[] chunks = line.split("\t");
double averageRank = 0.0;
for (int i = 0; i < chunks.length; i++)
{
averageRank += Integer.parseInt(chunks[i]);
}
averageRank /= (chunks.length - 1);
sortedVariables.add(new StringsSortedByDoubles(averageRank, chunks[0]));
}
}
catch (Exception e)
{
e.printStackTrace();
System.exit(0);
}
Collections.sort(sortedVariables); // Smaller ranks first.
List<String> orderedFeaturesByImportance = new ArrayList<String>();
for (StringsSortedByDoubles ssbd : sortedVariables)
{
orderedFeaturesByImportance.add(ssbd.getId());
}
List<String> bestFeatureSet = new ArrayList<String>();
for (int i = 0; i < bestNumberOfFeatures; i++)
{
bestFeatureSet.add(orderedFeaturesByImportance.get(i));
}
// Write out the results for the whole dataset selection.
try
{
FileWriter resultsOutputFile = new FileWriter(finalSelectionResults);
BufferedWriter resultsOutputWriter = new BufferedWriter(resultsOutputFile);
for (String s : featuresUsed)
{
if (bestFeatureSet.contains(s))
{
resultsOutputWriter.write(s);
resultsOutputWriter.newLine();
}
}
resultsOutputWriter.close();
List<Integer> featureSetSizes = new ArrayList<Integer>(averageErrorRates.keySet());
Collections.sort(featureSetSizes, Collections.reverseOrder());
FileWriter errorRateOutputFile = new FileWriter(finalSelectionErrorRates, true);
BufferedWriter errorRateOutputWriter = new BufferedWriter(errorRateOutputFile);
String errorOutput = "";
String errorRateHeader = "";
for (Integer j : featureSetSizes)
{
errorRateHeader += Integer.toString(j) + "\t";
errorOutput += Double.toString(averageErrorRates.get(j)) + "\t";
}
errorRateHeader = errorRateHeader.substring(0, errorRateHeader.length() - 1);
errorOutput.substring(0, errorOutput.length() - 1);
errorRateOutputWriter.write(errorRateHeader);
errorRateOutputWriter.newLine();
errorRateOutputWriter.write(errorOutput);
errorRateOutputWriter.close();
featureSetSizes = new ArrayList<Integer>(averageGMeans.keySet());
Collections.sort(featureSetSizes, Collections.reverseOrder());
FileWriter gMeanOutputFile = new FileWriter(finalSelectionGMeans, true);
BufferedWriter gMeanOutputWriter = new BufferedWriter(gMeanOutputFile);
String gMeanOutput = "";
for (Integer j : featureSetSizes)
{
gMeanOutput += Double.toString(averageGMeans.get(j)) + "\t";
}
gMeanOutput.substring(0, gMeanOutput.length() - 1);
gMeanOutputWriter.write(gMeanOutput);
gMeanOutputWriter.newLine();
gMeanOutputWriter.close();
}
catch (Exception e)
{
e.printStackTrace();
System.exit(0);
}
}
|
diff --git a/src/com/hdweiss/codemap/view/CodeMapView.java b/src/com/hdweiss/codemap/view/CodeMapView.java
index 054772e..0d31197 100644
--- a/src/com/hdweiss/codemap/view/CodeMapView.java
+++ b/src/com/hdweiss/codemap/view/CodeMapView.java
@@ -1,195 +1,196 @@
package com.hdweiss.codemap.view;
import java.util.ArrayList;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.text.SpannableString;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.widget.LinearLayout;
import android.widget.Scroller;
import com.hdweiss.codemap.data.Project;
import com.hdweiss.codemap.util.CodeMapCursorPoint;
import com.hdweiss.codemap.util.CodeMapPoint;
import com.hdweiss.codemap.util.MyAbsoluteLayout;
import com.hdweiss.codemap.view.CodeMapListeners.CodeMapGestureListener;
import com.hdweiss.codemap.view.CodeMapListeners.CodeMapScaleListener;
import com.hdweiss.codemap.view.fragments.CodeMapFunction;
public class CodeMapView extends MyAbsoluteLayout {
private GestureDetector gestureDetector;
private ScaleGestureDetector scaleDetector;
private Scroller scroller;
private float zoom = 1;
private ArrayList<CodeMapFunction> views = new ArrayList<CodeMapFunction>();
private Project project;
public CodeMapView(Context context, AttributeSet attrs) {
super(context, attrs);
this.scroller = new Scroller(getContext());
this.gestureDetector = new GestureDetector(getContext(), new CodeMapGestureListener(this, scroller));
this.scaleDetector = new ScaleGestureDetector(getContext(), new CodeMapScaleListener(this));
setFocusable(false);
}
private void initState() {
createFunctionFragment("addTotals", new CodeMapPoint(200, 200));
createFunctionFragment("createTagsFromFileInput", new CodeMapPoint(300, 500));
}
public void setProject(Project project) {
this.project = project;
initState();
}
public float getZoom() {
return this.zoom;
}
public void setZoom(float zoom, CodeMapPoint pivot) {
this.zoom = zoom;
invalidate();
}
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
event.setLocation(event.getX() * zoom, event.getY() * zoom);
return super.dispatchTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
super.onTouchEvent(event);
scaleDetector.onTouchEvent(event);
gestureDetector.onTouchEvent(event);
updateScroll();
return true;
}
private void updateScroll() {
if(scroller.computeScrollOffset()) {
float dx = (scroller.getStartX() - scroller.getFinalX());
float dy = (scroller.getStartY() - scroller.getFinalY());
scrollBy(-(int)dx, -(int)dy);
}
}
@Override
public void dispatchDraw(Canvas canvas) {
canvas.scale(zoom, zoom);
canvas.save(Canvas.MATRIX_SAVE_FLAG);
// canvas.translate(getScrollX() * zoom, getScrollY() * zoom);
super.dispatchDraw(canvas);
canvas.restore();
}
public CodeMapFunction createFileFragment(String fileName) {
CodeMapPoint position = new CodeMapCursorPoint(100, 100).getCodeMapPoint(this);
final SpannableString content = project.getFileSource(fileName);
CodeMapFunction functionView = new CodeMapFunction(getContext(),
position, fileName, content, this);
addMapFragment(functionView);
return functionView;
}
public CodeMapFunction createFunctionFragment(String functionName) {
CodeMapPoint position = new CodeMapCursorPoint(100, 100).getCodeMapPoint(this);
return createFunctionFragment(functionName, position);
}
public CodeMapFunction createFunctionFragment(String functionName, CodeMapPoint position) {
final SpannableString content = project.getFunctionSource(functionName);
CodeMapFunction functionView = new CodeMapFunction(getContext(),
position, functionName, content, this);
addMapFragment(functionView);
return functionView;
}
public CodeMapFunction openFragmentFromUrl(String url, CodeMapFunction codeMapFunction) {
CodeMapPoint position = new CodeMapPoint();
position.x = codeMapFunction.getX() + codeMapFunction.getWidth() + 30;
position.y = codeMapFunction.getY() + 20;
return createFunctionFragment(url, position);
}
public void addMapFragment(CodeMapFunction function) {
addView(function);
views.add(function);
moveMapFragmentToEmptyPosition(function);
}
public boolean moveMapFragmentToEmptyPosition(CodeMapFunction function) {
- Rect rect = new Rect();
- function.getDrawingRect(rect);
+ Rect rect = function.getBounds();
+ rect.bottom += 1;
+ rect.right += 1;
final int offset = 5;
boolean foundEmpty = false;
while (foundEmpty == false) {
foundEmpty = true;
for (CodeMapFunction view : views) {
Log.d("CodeMap", "Comparing " + function.getBounds().toString() + " " + view.getBounds().toString());
if (view != function && Rect.intersects(view.getBounds(), rect)) {
Log.d("CodeMap", function.getName() + " collieded with " + view.getName());
int height = rect.bottom - rect.top;
rect.top = view.getBounds().bottom + offset;
rect.bottom = rect.top + height;
foundEmpty = false;
break;
}
}
}
function.setX(rect.left);
function.setY(rect.top);
return true;
}
public CodeMapFunction getMapFragmentAtPoint(CodeMapCursorPoint cursorPoint) {
CodeMapPoint point = cursorPoint.getCodeMapPoint(this);
for (CodeMapFunction view : views) {
if (view.contains(point))
return view;
}
return null;
}
public void refresh() {
invalidate();
}
public void remove(LinearLayout view) {
removeView(view);
views.remove(view);
}
public void clear() {
removeAllViews();
views.clear();
}
}
| true | true | public boolean moveMapFragmentToEmptyPosition(CodeMapFunction function) {
Rect rect = new Rect();
function.getDrawingRect(rect);
final int offset = 5;
boolean foundEmpty = false;
while (foundEmpty == false) {
foundEmpty = true;
for (CodeMapFunction view : views) {
Log.d("CodeMap", "Comparing " + function.getBounds().toString() + " " + view.getBounds().toString());
if (view != function && Rect.intersects(view.getBounds(), rect)) {
Log.d("CodeMap", function.getName() + " collieded with " + view.getName());
int height = rect.bottom - rect.top;
rect.top = view.getBounds().bottom + offset;
rect.bottom = rect.top + height;
foundEmpty = false;
break;
}
}
}
function.setX(rect.left);
function.setY(rect.top);
return true;
}
| public boolean moveMapFragmentToEmptyPosition(CodeMapFunction function) {
Rect rect = function.getBounds();
rect.bottom += 1;
rect.right += 1;
final int offset = 5;
boolean foundEmpty = false;
while (foundEmpty == false) {
foundEmpty = true;
for (CodeMapFunction view : views) {
Log.d("CodeMap", "Comparing " + function.getBounds().toString() + " " + view.getBounds().toString());
if (view != function && Rect.intersects(view.getBounds(), rect)) {
Log.d("CodeMap", function.getName() + " collieded with " + view.getName());
int height = rect.bottom - rect.top;
rect.top = view.getBounds().bottom + offset;
rect.bottom = rect.top + height;
foundEmpty = false;
break;
}
}
}
function.setX(rect.left);
function.setY(rect.top);
return true;
}
|
diff --git a/src/main/java/com/authdb/scripts/forum/MyBB.java b/src/main/java/com/authdb/scripts/forum/MyBB.java
index 0026fe2..5eeaadd 100644
--- a/src/main/java/com/authdb/scripts/forum/MyBB.java
+++ b/src/main/java/com/authdb/scripts/forum/MyBB.java
@@ -1,102 +1,103 @@
/**
(C) Copyright 2011 CraftFire <[email protected]>
Contex <[email protected]>, Wulfspider <[email protected]>
This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License.
To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/3.0/
or send a letter to Creative Commons, 171 Second Street, Suite 300, San Francisco, California, 94105, USA.
**/
package com.authdb.scripts.forum;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import com.authdb.util.Config;
import com.authdb.util.encryption.Encryption;
import com.authdb.util.Util;
import com.authdb.util.databases.MySQL;
import com.authdb.util.databases.EBean;
public class MyBB {
public static String VersionRange = "1.6-1.6";
public static String LatestVersionRange = VersionRange;
public static String Name = "mybb";
public static String ShortName = "mybb";
public static void adduser(int checkid, String player, String email, String password, String ipAddress) throws SQLException {
if (checkid == 1) {
long timestamp = System.currentTimeMillis()/1000;
String salt = Encryption.hash(8, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", 0, 0);
String hash = hash("create", player, password, salt);
//
PreparedStatement ps;
//
+ Util.logging.mySQL("INSERT INTO `" + Config.script_tableprefix + "users" + "` (`username`, `password`, `salt`, `email`, `regdate`, `lastactive`, `lastvisit`, `regip`, `longregip`, `signature`, `buddylist`, `ignorelist`, `pmfolders`, `notepad`, `usernotes`, `usergroup`) VALUES (" + player + ", " + hash + ", " + salt + ", " + email + ", " + timestamp + ", " + timestamp + ", " + timestamp + ", " + ipAddress + ", " + Util.ip2Long(ipAddress) + ", '', '', '', '', '', '', '')");
ps = MySQL.mysql.prepareStatement("INSERT INTO `" + Config.script_tableprefix + "users" + "` (`username`, `password`, `salt`, `email`, `regdate`, `lastactive`, `lastvisit`, `regip`, `longregip`, `signature`, `buddylist`, `ignorelist`, `pmfolders`, `notepad`, `usernotes`, `usergroup`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", 1);
ps.setString(1, player); //username
ps.setString(2, hash); // password
ps.setString(3, salt); //salt
ps.setString(4, email); //email
ps.setLong(5, timestamp); //regdate
ps.setLong(6, timestamp); //lastactive
ps.setLong(7, timestamp); //lastvisit
ps.setString(8, ipAddress); //regip
ps.setLong(9, Util.ip2Long(ipAddress));
//need to add these, it's complaining about not default is set.
ps.setString(10, ""); //signature
ps.setString(11, ""); //buddylist
ps.setString(12, ""); //ignorelist
ps.setString(13, ""); //pmfolders
ps.setString(14, ""); //notepad
ps.setString(15, ""); //usernotes
ps.setString(16, "5");//usergroup
ps.executeUpdate();
ps.close();
int userid = MySQL.countitall(Config.script_tableprefix + "users");
String oldcache = MySQL.getfromtable(Config.script_tableprefix + "datastore", "`data`", "title", "userstats");
String newcache = Util.forumCache(oldcache, player, userid, "numusers", null, "lastusername", "lastuid", null);
ps = MySQL.mysql.prepareStatement("UPDATE `" + Config.script_tableprefix + "datacache" + "` SET `cache` = '" + newcache + "' WHERE `title` = 'stats'");
ps.executeUpdate();
ps.close();
}
}
public static String hash(String action, String player, String password, String thesalt) throws SQLException {
if (action.equalsIgnoreCase("find")) {
try {
EBean eBeanClass = EBean.checkPlayer(player, true);
String StoredSalt = eBeanClass.getSalt();
return passwordHash(password, StoredSalt);
} catch (NoSuchAlgorithmException e) {
Util.logging.StackTrace(e.getStackTrace(), Thread.currentThread().getStackTrace()[1].getMethodName(), Thread.currentThread().getStackTrace()[1].getLineNumber(), Thread.currentThread().getStackTrace()[1].getClassName(), Thread.currentThread().getStackTrace()[1].getFileName());
} catch (UnsupportedEncodingException e) {
Util.logging.StackTrace(e.getStackTrace(), Thread.currentThread().getStackTrace()[1].getMethodName(), Thread.currentThread().getStackTrace()[1].getLineNumber(), Thread.currentThread().getStackTrace()[1].getClassName(), Thread.currentThread().getStackTrace()[1].getFileName());
}
} else if (action.equalsIgnoreCase("create")) {
try {
return passwordHash(password, thesalt);
} catch (NoSuchAlgorithmException e) {
Util.logging.StackTrace(e.getStackTrace(), Thread.currentThread().getStackTrace()[1].getMethodName(), Thread.currentThread().getStackTrace()[1].getLineNumber(), Thread.currentThread().getStackTrace()[1].getClassName(), Thread.currentThread().getStackTrace()[1].getFileName());
} catch (UnsupportedEncodingException e) {
Util.logging.StackTrace(e.getStackTrace(), Thread.currentThread().getStackTrace()[1].getMethodName(), Thread.currentThread().getStackTrace()[1].getLineNumber(), Thread.currentThread().getStackTrace()[1].getClassName(), Thread.currentThread().getStackTrace()[1].getFileName());
}
}
return "fail";
}
public static boolean check_hash(String passwordhash, String hash) {
if (passwordhash.equals(hash)) {
return true;
} else {
return false;
}
}
public static String passwordHash(String password, String salt) throws NoSuchAlgorithmException, UnsupportedEncodingException {
return Encryption.md5(Encryption.md5(salt) + Encryption.md5(password));
}
}
| true | true | public static void adduser(int checkid, String player, String email, String password, String ipAddress) throws SQLException {
if (checkid == 1) {
long timestamp = System.currentTimeMillis()/1000;
String salt = Encryption.hash(8, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", 0, 0);
String hash = hash("create", player, password, salt);
//
PreparedStatement ps;
//
ps = MySQL.mysql.prepareStatement("INSERT INTO `" + Config.script_tableprefix + "users" + "` (`username`, `password`, `salt`, `email`, `regdate`, `lastactive`, `lastvisit`, `regip`, `longregip`, `signature`, `buddylist`, `ignorelist`, `pmfolders`, `notepad`, `usernotes`, `usergroup`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", 1);
ps.setString(1, player); //username
ps.setString(2, hash); // password
ps.setString(3, salt); //salt
ps.setString(4, email); //email
ps.setLong(5, timestamp); //regdate
ps.setLong(6, timestamp); //lastactive
ps.setLong(7, timestamp); //lastvisit
ps.setString(8, ipAddress); //regip
ps.setLong(9, Util.ip2Long(ipAddress));
//need to add these, it's complaining about not default is set.
ps.setString(10, ""); //signature
ps.setString(11, ""); //buddylist
ps.setString(12, ""); //ignorelist
ps.setString(13, ""); //pmfolders
ps.setString(14, ""); //notepad
ps.setString(15, ""); //usernotes
ps.setString(16, "5");//usergroup
ps.executeUpdate();
ps.close();
int userid = MySQL.countitall(Config.script_tableprefix + "users");
String oldcache = MySQL.getfromtable(Config.script_tableprefix + "datastore", "`data`", "title", "userstats");
String newcache = Util.forumCache(oldcache, player, userid, "numusers", null, "lastusername", "lastuid", null);
ps = MySQL.mysql.prepareStatement("UPDATE `" + Config.script_tableprefix + "datacache" + "` SET `cache` = '" + newcache + "' WHERE `title` = 'stats'");
ps.executeUpdate();
ps.close();
}
}
| public static void adduser(int checkid, String player, String email, String password, String ipAddress) throws SQLException {
if (checkid == 1) {
long timestamp = System.currentTimeMillis()/1000;
String salt = Encryption.hash(8, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", 0, 0);
String hash = hash("create", player, password, salt);
//
PreparedStatement ps;
//
Util.logging.mySQL("INSERT INTO `" + Config.script_tableprefix + "users" + "` (`username`, `password`, `salt`, `email`, `regdate`, `lastactive`, `lastvisit`, `regip`, `longregip`, `signature`, `buddylist`, `ignorelist`, `pmfolders`, `notepad`, `usernotes`, `usergroup`) VALUES (" + player + ", " + hash + ", " + salt + ", " + email + ", " + timestamp + ", " + timestamp + ", " + timestamp + ", " + ipAddress + ", " + Util.ip2Long(ipAddress) + ", '', '', '', '', '', '', '')");
ps = MySQL.mysql.prepareStatement("INSERT INTO `" + Config.script_tableprefix + "users" + "` (`username`, `password`, `salt`, `email`, `regdate`, `lastactive`, `lastvisit`, `regip`, `longregip`, `signature`, `buddylist`, `ignorelist`, `pmfolders`, `notepad`, `usernotes`, `usergroup`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", 1);
ps.setString(1, player); //username
ps.setString(2, hash); // password
ps.setString(3, salt); //salt
ps.setString(4, email); //email
ps.setLong(5, timestamp); //regdate
ps.setLong(6, timestamp); //lastactive
ps.setLong(7, timestamp); //lastvisit
ps.setString(8, ipAddress); //regip
ps.setLong(9, Util.ip2Long(ipAddress));
//need to add these, it's complaining about not default is set.
ps.setString(10, ""); //signature
ps.setString(11, ""); //buddylist
ps.setString(12, ""); //ignorelist
ps.setString(13, ""); //pmfolders
ps.setString(14, ""); //notepad
ps.setString(15, ""); //usernotes
ps.setString(16, "5");//usergroup
ps.executeUpdate();
ps.close();
int userid = MySQL.countitall(Config.script_tableprefix + "users");
String oldcache = MySQL.getfromtable(Config.script_tableprefix + "datastore", "`data`", "title", "userstats");
String newcache = Util.forumCache(oldcache, player, userid, "numusers", null, "lastusername", "lastuid", null);
ps = MySQL.mysql.prepareStatement("UPDATE `" + Config.script_tableprefix + "datacache" + "` SET `cache` = '" + newcache + "' WHERE `title` = 'stats'");
ps.executeUpdate();
ps.close();
}
}
|
diff --git a/activiti-engine/src/test/java/org/activiti/engine/test/bpmn/mail/EmailTestCase.java b/activiti-engine/src/test/java/org/activiti/engine/test/bpmn/mail/EmailTestCase.java
index 3bcd15b80..72c03e1e7 100644
--- a/activiti-engine/src/test/java/org/activiti/engine/test/bpmn/mail/EmailTestCase.java
+++ b/activiti-engine/src/test/java/org/activiti/engine/test/bpmn/mail/EmailTestCase.java
@@ -1,47 +1,45 @@
/* 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.test.bpmn.mail;
import org.activiti.engine.impl.test.PluggableActivitiTestCase;
import org.subethamail.wiser.Wiser;
/**
* @author Joram Barrez
*/
public class EmailTestCase extends PluggableActivitiTestCase {
protected Wiser wiser;
@Override
protected void setUp() throws Exception {
super.setUp();
wiser = new Wiser();
wiser.setPort(5025);
wiser.start();
}
@Override
protected void tearDown() throws Exception {
wiser.stop();
// Fix for slow Jenkins
- while (wiser.getServer().isRunning()) {
- Thread.sleep(100L);
- }
+ Thread.sleep(250L);
super.tearDown();
}
}
| true | true | protected void tearDown() throws Exception {
wiser.stop();
// Fix for slow Jenkins
while (wiser.getServer().isRunning()) {
Thread.sleep(100L);
}
super.tearDown();
}
| protected void tearDown() throws Exception {
wiser.stop();
// Fix for slow Jenkins
Thread.sleep(250L);
super.tearDown();
}
|
diff --git a/DbstarDVB/src/com/dbstar/DbstarDVB/VideoPlayer/alert/NormalState.java b/DbstarDVB/src/com/dbstar/DbstarDVB/VideoPlayer/alert/NormalState.java
index 732262e5..99216c61 100644
--- a/DbstarDVB/src/com/dbstar/DbstarDVB/VideoPlayer/alert/NormalState.java
+++ b/DbstarDVB/src/com/dbstar/DbstarDVB/VideoPlayer/alert/NormalState.java
@@ -1,213 +1,213 @@
package com.dbstar.DbstarDVB.VideoPlayer.alert;
import com.dbstar.DbstarDVB.R;
import android.app.Dialog;
import android.content.res.Resources;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class NormalState extends TimerViewState {
private static final String TAG = "NormalState";
public static final String ID = "Normal";
private static final int TIMEOUT_IN_MILLIONSECONDS = 5000;
private static final int UpdatePeriodInMills = 1000;
TextView mMovieTitle;
TextView mMovieDescription;
TextView mMovieDirector;
TextView mMovieActors;
TextView mCodeformat;
TextView mBitrate;
TextView mResolution;
Button mCloseButton, mReplayButton, mAddFavouriteButton, mDeleteButton;
MediaData mMediaData;
public NormalState(Dialog dlg, ViewStateManager manager) {
super(ID, dlg, manager);
mTimeoutTotal = TIMEOUT_IN_MILLIONSECONDS;
mTimeoutUpdateInterval = UpdatePeriodInMills;
mDelay = UpdatePeriodInMills;
}
public void enter(Object args) {
mMediaData = (MediaData) args;
mDialog.setContentView(R.layout.movie_info_view);
initializeView(mDialog);
mActionHandler = new ActionHandler(mDialog.getContext(), mMediaData);
}
protected void start() {
updateView(mDialog);
resetTimer();
}
protected void stop() {
stopTimer();
}
public void exit() {
stopTimer();
}
protected void keyEvent(int KeyCode, KeyEvent event) {
if (mDialog != null && mDialog.isShowing()) {
resetTimer();
}
}
public void initializeView(Dialog dlg) {
mTimeoutView = (TextView) dlg.findViewById(R.id.timeout_view);
mMovieTitle = (TextView) dlg.findViewById(R.id.title_view);
mMovieDescription = (TextView) dlg.findViewById(R.id.description_view);
mMovieDirector = (TextView) dlg.findViewById(R.id.director_view);
mMovieActors = (TextView) dlg.findViewById(R.id.actors_view);
mCodeformat = (TextView) dlg.findViewById(R.id.codeformat_view);
mBitrate = (TextView) dlg.findViewById(R.id.bitrate_view);
mResolution = (TextView) dlg.findViewById(R.id.resolution_view);
mCloseButton = (Button) dlg.findViewById(R.id.close_button);
mReplayButton = (Button) dlg.findViewById(R.id.replay_button);
mAddFavouriteButton = (Button) dlg
.findViewById(R.id.add_favourite_button);
mDeleteButton = (Button) dlg.findViewById(R.id.delete_button);
mCloseButton.setOnClickListener(mClickListener);
mReplayButton.setOnClickListener(mClickListener);
mAddFavouriteButton.setOnClickListener(mClickListener);
mDeleteButton.setOnClickListener(mClickListener);
mCloseButton.requestFocus();
}
View.OnClickListener mClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG, "button clicked");
buttonClicked((Button) v);
}
};
private void buttonClicked(Button button) {
Log.d(TAG, "buttonClicked clicked " + button);
if (button == mCloseButton) {
closedButtonClicked();
} else if (button == mReplayButton) {
replayButtonClicked();
closePopupView();
} else if (button == mAddFavouriteButton) {
addFavoriteClicked();
} else if (button == mDeleteButton) {
deleteButtonClicked();
} else {
}
}
public void onTimeout() {
closePopupView();
}
void closePopupView() {
Log.d(TAG, "+++++++++ close popus dialog");
mDialog.dismiss();
}
void closedButtonClicked() {
Log.d(TAG, "closedButtonClicked");
closePopupView();
}
void replayButtonClicked() {
Log.d(TAG, "replayButtonClicked");
mActionHandler.sendCommnd(ActionHandler.COMMAND_REPLAY);
}
void addFavoriteClicked() {
Log.d(TAG, "addFavoriteClicked");
mActionHandler.sendCommnd(ActionHandler.COMMAND_ADDTOFAVOURITE);
ViewState state = null;
state = mManager.getState(FavouriteState.ID);
if (state == null) {
state = new FavouriteState(mDialog, mManager);
}
mManager.changeToState(state, null);
}
void deleteButtonClicked() {
Log.d(TAG, "deleteButtonClicked");
ViewState state = null;
state = mManager.getState(DeleteState.ID);
if (state == null) {
state = new DeleteState(mDialog, mManager);
}
mManager.changeToState(state, mMediaData);
}
public void updateView(Dialog dlg) {
if (mMediaData != null) {
if (mMediaData.Title != null) {
mMovieTitle.setText(mMediaData.Title);
}
if (mMediaData.Description != null) {
mMovieDescription.setText(mMediaData.Description);
}
Resources res = dlg.getContext().getResources();
String director = res
.getString(R.string.property_director);
if (mMediaData.Director != null) {
director += mMediaData.Director;
}
mMovieDirector.setText(director);
String actors = res
.getString(R.string.property_actors);
if (mMediaData.Actors != null) {
actors += mMediaData.Actors;
}
mMovieActors.setText(actors);
String videoFormat = res.getString(R.string.property_codeformat);
if (mMediaData.CodeFormat != null) {
videoFormat += mMediaData.CodeFormat;
}
mCodeformat.setText(videoFormat);
String bitrate = res.getString(R.string.property_bitrate);
if (mMediaData.Bitrate != null) {
bitrate += mMediaData.Bitrate;
}
- mCodeformat.setText(bitrate);
+ mBitrate.setText(bitrate);
String resolution = res.getString(R.string.property_resolution);
if (mMediaData.Resolution != null) {
resolution += mMediaData.Resolution;
}
- mCodeformat.setText(resolution);
+ mResolution.setText(resolution);
}
}
}
| false | true | public void updateView(Dialog dlg) {
if (mMediaData != null) {
if (mMediaData.Title != null) {
mMovieTitle.setText(mMediaData.Title);
}
if (mMediaData.Description != null) {
mMovieDescription.setText(mMediaData.Description);
}
Resources res = dlg.getContext().getResources();
String director = res
.getString(R.string.property_director);
if (mMediaData.Director != null) {
director += mMediaData.Director;
}
mMovieDirector.setText(director);
String actors = res
.getString(R.string.property_actors);
if (mMediaData.Actors != null) {
actors += mMediaData.Actors;
}
mMovieActors.setText(actors);
String videoFormat = res.getString(R.string.property_codeformat);
if (mMediaData.CodeFormat != null) {
videoFormat += mMediaData.CodeFormat;
}
mCodeformat.setText(videoFormat);
String bitrate = res.getString(R.string.property_bitrate);
if (mMediaData.Bitrate != null) {
bitrate += mMediaData.Bitrate;
}
mCodeformat.setText(bitrate);
String resolution = res.getString(R.string.property_resolution);
if (mMediaData.Resolution != null) {
resolution += mMediaData.Resolution;
}
mCodeformat.setText(resolution);
}
}
| public void updateView(Dialog dlg) {
if (mMediaData != null) {
if (mMediaData.Title != null) {
mMovieTitle.setText(mMediaData.Title);
}
if (mMediaData.Description != null) {
mMovieDescription.setText(mMediaData.Description);
}
Resources res = dlg.getContext().getResources();
String director = res
.getString(R.string.property_director);
if (mMediaData.Director != null) {
director += mMediaData.Director;
}
mMovieDirector.setText(director);
String actors = res
.getString(R.string.property_actors);
if (mMediaData.Actors != null) {
actors += mMediaData.Actors;
}
mMovieActors.setText(actors);
String videoFormat = res.getString(R.string.property_codeformat);
if (mMediaData.CodeFormat != null) {
videoFormat += mMediaData.CodeFormat;
}
mCodeformat.setText(videoFormat);
String bitrate = res.getString(R.string.property_bitrate);
if (mMediaData.Bitrate != null) {
bitrate += mMediaData.Bitrate;
}
mBitrate.setText(bitrate);
String resolution = res.getString(R.string.property_resolution);
if (mMediaData.Resolution != null) {
resolution += mMediaData.Resolution;
}
mResolution.setText(resolution);
}
}
|
diff --git a/src/cwcore/ComplexAgent.java b/src/cwcore/ComplexAgent.java
index ec123f6..ff23436 100644
--- a/src/cwcore/ComplexAgent.java
+++ b/src/cwcore/ComplexAgent.java
@@ -1,1185 +1,1184 @@
package cwcore;
import java.awt.Color;
import java.io.Serializable;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import cobweb.ColorLookup;
import cobweb.Direction;
import cobweb.DrawingHandler;
import cobweb.Environment;
import cobweb.Environment.Location;
import cobweb.Point2D;
import cobweb.TypeColorEnumeration;
import cwcore.ComplexEnvironment.CommManager;
import cwcore.ComplexEnvironment.CommPacket;
import cwcore.complexParams.AgentMutator;
import cwcore.complexParams.ComplexAgentParams;
import cwcore.complexParams.ContactMutator;
import cwcore.complexParams.SpawnMutator;
import cwcore.complexParams.StepMutator;
import driver.ControllerFactory;
public class ComplexAgent extends cobweb.Agent implements cobweb.TickScheduler.Client, Serializable{
static class SeeInfo {
private int dist;
private int type;
public SeeInfo(int d, int t) {
dist = d;
type = t;
}
public int getDist() {
return dist;
}
public int getType() {
return type;
}
}
/**
*
*/
private static final long serialVersionUID = -5310096345506441368L;
/** Default mutable parameters of each agent type. */
private static ComplexAgentParams defaulParams[];
private static AgentSimilarityCalculator simCalc;
public static Collection<String> logDataAgent(int i) {
List<String> blah = new LinkedList<String>();
for (SpawnMutator mut : spawnMutators) {
for (String s : mut.logDataAgent(i))
blah.add(s);
}
return blah;
}
public static Iterable<String> logDataTotal() {
List<String> blah = new LinkedList<String>();
for (SpawnMutator mut : spawnMutators) {
for (String s : mut.logDataTotal())
blah.add(s);
}
return blah;
}
public static Collection<String> logHederAgent() {
List<String> blah = new LinkedList<String>();
for (SpawnMutator mut : spawnMutators) {
for (String s : mut.logHeadersAgent())
blah.add(s);
}
return blah;
}
public static Iterable<String> logHederTotal() {
List<String> blah = new LinkedList<String>();
for (SpawnMutator mut : spawnMutators) {
for (String s : mut.logHeaderTotal())
blah.add(s);
}
return blah;
}
/** Sets the default mutable parameters of each agent type. */
public static void setDefaultMutableParams(ComplexAgentParams[] params) {
defaulParams = params.clone();
for (int i = 0; i < params.length; i++) {
defaulParams[i] = (ComplexAgentParams) params[i].clone();
}
}
public static void setSimularityCalc(AgentSimilarityCalculator calc) {
simCalc = calc;
}
private int agentType = 0;
public ComplexAgentParams params;
/* energy gauge */
private int energy;
/* Prisoner's Dilemma */
private int agentPDStrategy; // tit-for-tat or probability
private int pdCheater; // The agent's action; 1 == cheater, else
// cooperator
private int lastPDMove; // Remember the opponent's move in the last game
private int commInbox;
private int commOutbox;
// memory size is the maximum capacity of the number of cheaters an agent
// can remember
private long photo_memory[];
private int photo_num = 0;
private boolean want2meet = false;
boolean cooperate;
private long birthTick = 0;
private long age = 0;
/* Waste variables */
private int wasteCounterGain;
private int wasteCounterLoss;
private int memoryBuffer;
private ComplexAgent breedPartner;
private Color color = Color.lightGray;
private boolean asexFlag;
private ComplexAgentInfo info;
// pregnancyPeriod is set value while pregPeriod constantly changes
private int pregPeriod;
private boolean pregnant = false;
private static boolean tracked = false;
// static-izing the writer. Doesn't seem feasible to have a writer for each
// agent.
// main issue is speed and also the need to find a graceful way to produce
// the output
// (dumping 200 .txt files != graceful).
private static java.io.Writer writer;
public static final int LOOK_DISTANCE = 4;
public static void clearData() {
if (tracked)
ComplexAgentInfo.resetGroupData();
}
public static void dumpData(long tick) {
if (tracked)
ComplexAgentInfo.dumpGroupData(tick, writer);
}
public static void setPrintWriter(java.io.Writer w) {
writer = w;
}
// static-izing this too. see the comment above
public static void tracked() {
tracked = true;
}
/** The current tick we are in (or the last tick this agent was notified */
private long currTick = 0;
private static ColorLookup colorMap = TypeColorEnumeration.getInstance();
private static Set<ContactMutator> contactMutators = new LinkedHashSet<ContactMutator>();
private static Set<StepMutator> stepMutators = new LinkedHashSet<StepMutator>();
private static final cobweb.Direction[] dirList = { cobweb.Environment.DIRECTION_NORTH,
cobweb.Environment.DIRECTION_SOUTH, cobweb.Environment.DIRECTION_WEST, cobweb.Environment.DIRECTION_EAST,
cobweb.Environment.DIRECTION_NORTHEAST, cobweb.Environment.DIRECTION_SOUTHEAST,
cobweb.Environment.DIRECTION_NORTHWEST, cobweb.Environment.DIRECTION_SOUTHWEST };
public static void addMutator(AgentMutator mutator) {
if (mutator instanceof SpawnMutator)
spawnMutators.add((SpawnMutator) mutator);
if (mutator instanceof ContactMutator)
contactMutators.add((ContactMutator) mutator);
if (mutator instanceof StepMutator)
stepMutators.add((StepMutator) mutator);
}
public static void clearMutators() {
spawnMutators.clear();
contactMutators.clear();
stepMutators.clear();
}
private cobweb.Direction facing = cobweb.Environment.DIRECTION_NORTH;
private static Set<SpawnMutator> spawnMutators = new LinkedHashSet<SpawnMutator>();
boolean mustFlip = false;
/**
* Constructor with two parents
*
* @param pos spawn position
* @param parent1 first parent
* @param parent2 second parent
* @param strat PD strategy
*/
protected ComplexAgent(cobweb.Environment.Location pos, ComplexAgent parent1, ComplexAgent parent2, int strat) {
super(ControllerFactory.createFromParents(parent1.getController(), parent2.getController(),
parent1.params.mutationRate));
InitFacing();
copyConstants(parent1);
info = ((ComplexEnvironment) (pos.getEnvironment())).addAgentInfo(agentType, parent1.info, parent2.info, strat);
move(pos);
pos.getEnvironment().getScheduler().addSchedulerClient(this);
for (SpawnMutator mutator : spawnMutators)
mutator.onSpawn(this, parent1, parent2);
}
/**
* Constructor with a parent; standard asexual copy
*
* @param pos spawn position
* @param parent parent
* @param strat PD strategy
*/
protected ComplexAgent(cobweb.Environment.Location pos, ComplexAgent parent, int strat) {
super(ControllerFactory.createFromParent(parent.getController(), parent.params.mutationRate));
InitFacing();
copyConstants(parent);
info = ((ComplexEnvironment) (pos.getEnvironment())).addAgentInfo(agentType, parent.info, strat);
move(pos);
pos.getEnvironment().getScheduler().addSchedulerClient(this);
for (SpawnMutator mutator : spawnMutators)
mutator.onSpawn(this, parent);
}
/** */
public ComplexAgent(int agentT, int doCheat, ComplexAgentParams agentData, Direction facingDirection, Location pos) {
super(ControllerFactory.createNew(agentData.memoryBits, agentData.communicationBits));
setConstants(doCheat, agentData);
this.facing = facingDirection;
info = ((ComplexEnvironment) (pos.getEnvironment())).addAgentInfo(agentT, doCheat);
move(pos);
pos.getEnvironment().getScheduler().addSchedulerClient(this);
for (SpawnMutator mutator : spawnMutators)
mutator.onSpawn(this);
}
/**
* Constructor with no parent agent; creates an agent using "immaculate conception" technique
*
* @param agentType agent type
* @param pos spawn position
* @param doCheat start PD off cheating?
* @param agentData agent parameters
*/
public ComplexAgent(int agentType, Location pos, int doCheat, ComplexAgentParams agentData) {
super(ControllerFactory.createNew(agentData.memoryBits, agentData.communicationBits));
setConstants(doCheat, agentData);
InitFacing();
params = agentData;
info = ((ComplexEnvironment) (pos.getEnvironment())).addAgentInfo(agentType, doCheat);
this.agentType = agentType;
move(pos);
pos.getEnvironment().getScheduler().addSchedulerClient(this);
for (SpawnMutator mutator : spawnMutators)
mutator.onSpawn(this);
}
private void afterTurnAction() {
energy -= energyPenalty(true);
if (energy <= 0)
die();
if (!pregnant)
tryAsexBreed();
if (pregnant) {
pregPeriod--;
}
}
@Override
public long birthday() {
return birthTick;
}
void broadcastCheating(cobweb.Environment.Location loc) { // []SK
// String message = "Cheater encountered (" + loc.v[0] + " , " + loc.v[1] + ")";
String message = Long.toString(((ComplexAgent) loc.getAgent()).id);
new CommPacket(CommPacket.CHEATER, id, message, energy, params.broadcastEnergyBased, params.broadcastFixedRange);
// new CommPacket sent
energy -= params.broadcastEnergyCost; // Deduct broadcasting cost from energy
}
void broadcastFood(cobweb.Environment.Location loc) { // []SK
String message = loc.toString();
new CommPacket(CommPacket.FOOD, id, message, energy, params.broadcastEnergyBased, params.broadcastFixedRange);
// new CommPacket sent
energy -= params.broadcastEnergyCost; // Deduct broadcasting cost from energy
}
private boolean canBroadcast() {
return energy > params.broadcastEnergyMin;
}
public boolean canEat(cobweb.Environment.Location destPos) {
return params.foodweb.canEatFood[ComplexEnvironment.getFoodType(destPos)];
}
private boolean canEat(ComplexAgent adjacentAgent) {
boolean caneat = false;
caneat = params.foodweb.canEatAgent[adjacentAgent.getAgentType()];
if (this.energy > params.breedEnergy)
caneat = false;
return caneat;
}
boolean canStep(Location destPos) {
// The position must be valid...
if (destPos == null)
return false;
// and the destination must be clear of stones
if (destPos.testFlag(ComplexEnvironment.FLAG_STONE))
return false;
// and clear of wastes
if (destPos.testFlag(ComplexEnvironment.FLAG_WASTE))
return false;
// as well as other agents...
if (destPos.getAgent() != null)
return false;
return true;
}
boolean checkCredibility(long agentId) {
// check if dispatcherId is in list
// if (agentId != null) {
for (int i = 0; i < params.pdMemory; i++) {
if (photo_memory[i] == agentId) {
return false;
}
}
// }
return true;
}
int checkforBroadcasts() {
CommManager commManager = new CommManager();
CommPacket commPacket = null;
for (int i = 0; i < ComplexEnvironment.currentPackets.size(); i++) {
commPacket = ComplexEnvironment.currentPackets.get(i);
if (commManager.packetInRange(commPacket.getRadius(), getPosition(), getPosition()))
return i;
}
return -1;
}
//@Override
// public Object clone() {
// ComplexAgent cp = new ComplexAgent(getAgentType(), pdCheater, params, facing);
// //cp.hibernate();
// return cp;
// }
void communicate(ComplexAgent target) {
target.setCommInbox(commOutbox);
}
public void copyConstants(ComplexAgent p) {
setConstants(p.pdCheater, (ComplexAgentParams) defaulParams[p.getAgentType()].clone());
}
@Override
public void die() {
super.die();
for (SpawnMutator mutator : spawnMutators) {
mutator.onDeath(this);
}
info.setDeath(((ComplexEnvironment) position.getEnvironment()).getTickCount());
}
public SeeInfo distanceLook() {
Direction d = facing;
cobweb.Environment.Location destPos = getPosition().getAdjacent(d);
if (getPosition().checkFlip(d))
d = d.flip();
for (int dist = 1; dist <= LOOK_DISTANCE; ++dist) {
// We are looking at the wall
if (destPos == null)
return new SeeInfo(dist, ComplexEnvironment.FLAG_STONE);
// Check for stone...
if (destPos.testFlag(ComplexEnvironment.FLAG_STONE))
return new SeeInfo(dist, ComplexEnvironment.FLAG_STONE);
// If there's another agent there, then return that it's a stone...
if (destPos.getAgent() != null && destPos.getAgent() != this)
return new SeeInfo(dist, ComplexEnvironment.FLAG_AGENT);
// If there's food there, return the food...
if (destPos.testFlag(ComplexEnvironment.FLAG_FOOD))
return new SeeInfo(dist, ComplexEnvironment.FLAG_FOOD);
if (destPos.testFlag(ComplexEnvironment.FLAG_WASTE))
return new SeeInfo(dist, ComplexEnvironment.FLAG_WASTE);
destPos = destPos.getAdjacent(d);
if (getPosition().checkFlip(d))
d = d.flip();
}
return new SeeInfo(LOOK_DISTANCE, 0);
}
public void eat(cobweb.Environment.Location destPos) {
// Eat first before we can produce waste, of course.
destPos.setFlag(ComplexEnvironment.FLAG_FOOD, false);
// Gain Energy according to the food type.
if (ComplexEnvironment.getFoodType(destPos) == agentType) {
energy += params.foodEnergy;
wasteCounterGain -= params.foodEnergy;
info.addFoodEnergy(params.foodEnergy);
} else {
energy += params.otherFoodEnergy;
wasteCounterGain -= params.otherFoodEnergy;
info.addOthers(params.otherFoodEnergy);
}
}
private void eat(ComplexAgent adjacentAgent) {
int gain = (int) (adjacentAgent.energy * params.agentFoodEnergy);
energy += gain;
wasteCounterGain -= gain;
info.addCannibalism(gain);
adjacentAgent.die();
}
private double energyPenalty(boolean log) {
if (!params.agingMode)
return 0.0;
double tempAge = currTick - birthTick;
assert(tempAge == age);
int penaltyValue = Math.min(Math.max(0, energy), (int)(params.agingRate
* (Math.tan(((tempAge / params.agingLimit) * 89.99) * Math.PI / 180))));
if (tracked && log) {
info.useExtraEnergy(penaltyValue);
}
return penaltyValue;
}
cobweb.Agent getAdjacentAgent() {
cobweb.Environment.Location destPos = getPosition().getAdjacent(facing);
if (destPos == null) {
return null;
}
return destPos.getAgent();
}
public long getAge() {
return age;
}
@Override
public int getAgentPDAction() {
return pdCheater;
}
@Override
public int getAgentPDStrategy() {
return agentPDStrategy;
}
public int getAgentType() {
return params.type;
}
@Override
public Color getColor() {
return color;
}
public int getCommInbox() {
return commInbox;
}
public int getCommOutbox() {
return commOutbox;
}
// get agent's drawing information given the UI
@Override
public void getDrawInfo(DrawingHandler theUI) {
Color stratColor;
// is agents action is 1, it's a cheater therefore it's
// graphical representation will a have red boundary
if (pdCheater == 1) {
stratColor = Color.red;
} else {
// cooperator, black boundary
stratColor = Color.black;
}
// based on agent type
theUI.newAgent(getColor(), colorMap.getColor(agentType, 1), stratColor, new Point2D(getPosition().v[0],
getPosition().v[1]), new Point2D(facing.v[0], facing.v[1]));
}
// return agent's energy
@Override
public int getEnergy() {
return energy;
}
public ComplexAgentInfo getInfo() {
return info;
}
public int getIntFacing() {
if (facing.equals(cobweb.Environment.DIRECTION_NORTH))
return 0;
if (facing.equals(cobweb.Environment.DIRECTION_EAST))
return 1;
if (facing.equals(cobweb.Environment.DIRECTION_SOUTH))
return 2;
if (facing.equals(cobweb.Environment.DIRECTION_WEST))
return 3;
return 0;
}
public int getMemoryBuffer() {
return memoryBuffer;
}
// Provide a random facing for the agent.
private void InitFacing() {
double f = cobweb.globals.random.nextFloat();
if (f < 0.25)
facing = cobweb.Environment.DIRECTION_NORTH;
else if (f < 0.5)
facing = cobweb.Environment.DIRECTION_SOUTH;
else if (f < 0.75)
facing = cobweb.Environment.DIRECTION_EAST;
else
facing = cobweb.Environment.DIRECTION_WEST;
}
public boolean isAsexFlag() {
return asexFlag;
}
private void iveBeenCheated(int othersID) {
if (params.pdMemory > 0) {
photo_memory[photo_num++] = othersID;
if (photo_num >= params.pdMemory) {
photo_num = 0;
}
}
broadcastCheating(getPosition());
}
public long look() {
cobweb.Environment.Location destPos = getPosition().getAdjacent(facing);
// If the position is invalid, then we're looking at a stone...
if (destPos == null)
return ComplexEnvironment.FLAG_STONE;
// Check for stone...
if (destPos.testFlag(ComplexEnvironment.FLAG_STONE))
return ComplexEnvironment.FLAG_STONE;
// If there's another agent there, then return that it's a stone...
if (destPos.getAgent() != null)
return ComplexEnvironment.FLAG_STONE;
// If there's food there, return the food...
if (destPos.testFlag(ComplexEnvironment.FLAG_FOOD))
return ComplexEnvironment.FLAG_FOOD;
// waste check
if (destPos.testFlag(ComplexEnvironment.FLAG_WASTE))
return ComplexEnvironment.FLAG_WASTE;
// Return an empty tile
return 0;
}
public Node makeNode(Document doc) {
Node agent = doc.createElement("Agent");
Element agentTypeElement = doc.createElement("agentType");
agentTypeElement.appendChild(doc.createTextNode(agentType +""));
agent.appendChild(agentTypeElement);
Element doCheatElement = doc.createElement("doCheat");
doCheatElement.appendChild(doc.createTextNode(pdCheater +""));
agent.appendChild(doCheatElement);
Element paramsElement = doc.createElement("params");
params.saveConfig(paramsElement, doc);
agent.appendChild(paramsElement);
Element directionElement = doc.createElement("direction");
facing.saveAsANode(directionElement, doc);
agent.appendChild(directionElement);
return agent;
}
@Override
public void move(Location newPos) {
super.move(newPos);
info.addPathStep(newPos);
if (mustFlip) {
if (facing.equals(Environment.DIRECTION_NORTH))
facing = Environment.DIRECTION_SOUTH;
else if (facing.equals(Environment.DIRECTION_SOUTH))
facing = Environment.DIRECTION_NORTH;
else if (facing.equals(Environment.DIRECTION_EAST))
facing = Environment.DIRECTION_WEST;
else if (facing.equals(Environment.DIRECTION_WEST))
facing = Environment.DIRECTION_EAST;
}
}
/**
* This method determines the action of the agent in a PD game
*/
public void playPD() {
double coopProb = params.pdCoopProb / 100.0d; // static value for now
if (params.pdTitForTat) { // if true then agent is playing TitForTat
agentPDStrategy = 1; // set Strategy to 1 i.e. TitForTat
if (lastPDMove == -1)// if this is the first move
lastPDMove = 0; // start by cooperating
// might include probability bias within TitForTat strategy...not
// currently implemented
pdCheater = lastPDMove;
} else {
agentPDStrategy = 0; // $$$$$$ added to ensure Strategy is set to
// 0, i.e. probability. Apr 22
pdCheater = 0; // agent is assumed to cooperate
float rnd = cobweb.globals.random.nextFloat();
if (rnd > coopProb)
pdCheater = 1; // agent defects depending on
// probability
}
info.setStrategy(pdCheater);
return;
}
private void playPDonStep(ComplexAgent adjacentAgent, int othersID) {
playPD();
adjacentAgent.playPD();
lastPDMove = adjacentAgent.pdCheater; // Adjacent Agent's action is assigned to the last move memory of the
// agent
adjacentAgent.lastPDMove = pdCheater; // Agent's action is assigned to the last move memory of the adjacent
// agent
/*
* TODO: The ability for the PD game to contend for the Get the food tiles immediately around each agents
*/
/* 0 = cooperate. 1 = defect */
/*
* Payoff Matrix: 0 0 => 5 5 0 1 => 2 8 1 0 => 8 2 1 1 => 3 3
*/
final int PD_COOPERATE = 0;
final int PD_DEFECT = 1;
if (pdCheater == PD_COOPERATE && adjacentAgent.pdCheater == PD_COOPERATE) {
/* REWARD */
energy += ComplexEnvironment.PD_PAYOFF_REWARD;
adjacentAgent.energy += ComplexEnvironment.PD_PAYOFF_REWARD;
} else if (pdCheater == PD_COOPERATE && adjacentAgent.pdCheater == PD_DEFECT) {
/* SUCKER */
energy += ComplexEnvironment.PD_PAYOFF_SUCKER;
adjacentAgent.energy += ComplexEnvironment.PD_PAYOFF_TEMPTATION;
iveBeenCheated(othersID);
} else if (pdCheater == PD_DEFECT && adjacentAgent.pdCheater == PD_COOPERATE) {
/* TEMPTATION */
energy += ComplexEnvironment.PD_PAYOFF_TEMPTATION;
adjacentAgent.energy += ComplexEnvironment.PD_PAYOFF_SUCKER;
} else if (pdCheater == PD_DEFECT && adjacentAgent.pdCheater == PD_DEFECT) {
/* PUNISHMENT */
energy += ComplexEnvironment.PD_PAYOFF_PUNISHMENT;
adjacentAgent.energy += ComplexEnvironment.PD_PAYOFF_PUNISHMENT; // $$$$$$
iveBeenCheated(othersID);
}
}
/*
* Record the state here for logging. Can also be treated as a "setup" function before doing any activities. Might
* be useful in the future. This is only run when tracking is enabled.
*/
private void poll() {
info.addEnergy(energy);
info.alive();
}
void receiveBroadcast() {
CommPacket commPacket = null;
commPacket = ComplexEnvironment.currentPackets.get(checkforBroadcasts());
// check if dispatcherId is in list
// TODO what does this do?
checkCredibility(commPacket.getDispatcherId());
int type = commPacket.getType();
switch (type) {
case CommPacket.FOOD:
receiveFoodBroadcast(commPacket);
break;
case CommPacket.CHEATER:
receiveCheatingBroadcast(commPacket);
break;
default:
Logger myLogger = Logger.getLogger("COBWEB2");
myLogger.log(Level.WARNING, "Unrecognised broadcast type");
}
}
void receiveCheatingBroadcast(CommPacket commPacket) {
String message = commPacket.getContent();
long cheaterId = 0;
cheaterId = Long.parseLong(message);
photo_memory[photo_num] = cheaterId;
}
void receiveFoodBroadcast(CommPacket commPacket) {
String message = commPacket.getContent();
String[] xy = message.substring(1, message.length() - 1).split(",");
int x = Integer.parseInt(xy[0]);
int y = Integer.parseInt(xy[1]);
thinkAboutFoodLocation(x, y);
}
public void setAsexFlag(boolean asexFlag) {
this.asexFlag = asexFlag;
}
@Override
public void setColor(Color c) {
color = c;
}
public void setCommInbox(int commInbox) {
this.commInbox = commInbox;
}
public void setCommOutbox(int commOutbox) {
this.commOutbox = commOutbox;
}
public void setConstants(int pdCheat, ComplexAgentParams agentData) {
this.params = agentData;
this.agentType = agentData.type;
this.pdCheater = pdCheat;
energy = agentData.initEnergy;
wasteCounterGain = params.wasteLimitGain;
wasteCounterLoss = params.wasteLimitLoss;
photo_memory = new long[params.pdMemory];
// $$$$$$ Modified the following block. we are not talking about RESET
// here. Apr 18
/*
* agentPDStrategy = 1; // Tit-for-tat or probability based agentPDAction = -1; // The agent's action; 1 =
* cheater, else cooperator $$$$$ this parameter seems useless, there is another PDaction parameter above
* already. Apr 18 lastPDMove = -1; // Remember the opponent's move in the last game
*/
this.agentPDStrategy = 0; // FIXME agentData.agentPDStrategy;
// above all, sometimes a new
// agent need copy PDStrategy
// from its parent. See
// copyConstants( ComplexAgent p
// )
this.lastPDMove = 0; // FIXME agentData.lastPDMove;
// "KeepOldAgents" need pass this
// parameter. (as a reasonable side
// effect, the parameter of a parent
// would also pass to its child)
// See ComplexEnvironment.load(cobweb.Scheduler s, Parser p/*
// java.io.Reader r */) @ if (keepOldAgents[0]) {...
}
public void setMemoryBuffer(int memoryBuffer) {
this.memoryBuffer = memoryBuffer;
}
/*
* return the measure of similiarity between this agent and the 'other' ranging from 0.0 to 1.0 (identical)
*/
@Override
public double similarity(cobweb.Agent other) {
if (!(other instanceof ComplexAgent))
return 0.0;
return // ((GeneticController) controller)
// .similarity((GeneticController) ((ComplexAgent) other)
// .getController());
((LinearWeightsController) controller).similarity((LinearWeightsController) other.getController());
}
@Override
public double similarity(int other) {
return 0.5; // ((GeneticController) controller).similarity(other);
}
public void step() {
cobweb.Agent adjAgent;
mustFlip = getPosition().checkFlip(facing);
cobweb.Environment.Location destPos = getPosition().getAdjacent(facing);
if (canStep(destPos)) {
// Check for food...
cobweb.Environment.Location breedPos = null;
if (destPos.testFlag(ComplexEnvironment.FLAG_FOOD)) {
if (params.broadcastMode & canBroadcast()) {
broadcastFood(destPos);
}
if (canEat(destPos)) {
eat(destPos);
}
if (pregnant && energy >= params.breedEnergy && pregPeriod <= 0) {
breedPos = getPosition();
energy -= params.initEnergy;
energy -= energyPenalty(true);
wasteCounterLoss -= params.initEnergy;
info.useOthers(params.initEnergy);
} else {
if (!pregnant)
tryAsexBreed();
}
}
for (StepMutator m : stepMutators)
m.onStep(this, getPosition(), destPos);
move(destPos);
if (breedPos != null) {
if (breedPartner == null) {
info.addDirectChild();
new ComplexAgent(breedPos, this, this.pdCheater);
} else {
// child's strategy is determined by its parents, it has a
// 50% chance to get either parent's strategy
int childStrategy = -1;
if (this.pdCheater != -1) {
boolean choose = cobweb.globals.random.nextBoolean();
if (choose) {
childStrategy = this.pdCheater;
} else {
childStrategy = breedPartner.pdCheater;
}
}
info.addDirectChild();
breedPartner.info.addDirectChild();
new ComplexAgent(breedPos, this, breedPartner, childStrategy);
info.addSexPreg();
}
breedPartner = null;
pregnant = false;
}
energy -= params.stepEnergy;
wasteCounterLoss -= params.stepEnergy;
info.useStepEnergy(params.stepEnergy);
info.addStep();
- info.addPathStep(this.getPosition());
} else if ((adjAgent = getAdjacentAgent()) != null && adjAgent instanceof ComplexAgent
&& ((ComplexAgent) adjAgent).info != null) {
// two agents meet
ComplexAgent adjacentAgent = (ComplexAgent) adjAgent;
for (ContactMutator mut : contactMutators) {
mut.onContact(this, adjacentAgent);
}
if (canEat(adjacentAgent)) {
eat(adjacentAgent);
}
if (this.pdCheater != -1) {// $$$$$ if playing Prisoner's
// Dilemma. Please refer to ComplexEnvironment.load, "// spawn new random agents for each type"
want2meet = true;
}
int othersID = adjacentAgent.info.getAgentNumber();
// scan the memory array, is the 'other' agents ID is found in the array,
// then choose not to have a transaction with him.
for (int i = 0; i < params.pdMemory; i++) {
if (photo_memory[i] == othersID) {
want2meet = false;
}
}
// if the agents are of the same type, check if they have enough
// resources to breed
if (adjacentAgent.agentType == agentType) {
double sim = 0.0;
boolean canBreed = !pregnant && energy >= params.breedEnergy && params.sexualBreedChance != 0.0
&& cobweb.globals.random.nextFloat() < params.sexualBreedChance;
// Generate genetic similarity number
sim = simCalc.similarity(this, adjacentAgent);
if (sim >= params.commSimMin) {
communicate(adjacentAgent);
}
if (canBreed && sim >= params.breedSimMin
&& ((want2meet && adjacentAgent.want2meet) || (pdCheater == -1))) {
pregnant = true;
pregPeriod = params.sexualPregnancyPeriod;
breedPartner = adjacentAgent;
}
}
// perform the transaction only if non-pregnant and both agents want to meet
if (!pregnant && want2meet && adjacentAgent.want2meet) {
playPDonStep(adjacentAgent, othersID);
}
energy -= params.stepAgentEnergy;
wasteCounterLoss -= params.stepAgentEnergy;
info.useAgentBumpEnergy(params.stepAgentEnergy);
info.addAgentBump();
} // end of two agents meet
else if (destPos != null && destPos.testFlag(ComplexEnvironment.FLAG_WASTE)) {
// Bumps into waste
energy -= params.wastePen;
wasteCounterLoss -= params.wastePen;
info.useRockBumpEnergy(params.wastePen);
info.addRockBump();
} else {
// Rock bump
energy -= params.stepRockEnergy;
wasteCounterLoss -= params.stepRockEnergy;
info.useRockBumpEnergy(params.stepRockEnergy);
info.addRockBump();
}
energy -= energyPenalty(true);
if (energy <= 0)
die();
if (energy < params.breedEnergy) {
pregnant = false;
breedPartner = null;
}
if (pregnant) {
pregPeriod--;
}
}
private void thinkAboutFoodLocation(int x, int y) {
Location target = this.getPosition().getEnvironment().getLocation(x, y);
double closeness = 1;
if (!target.equals(getPosition()))
closeness = 1 / target.distance(this.getPosition());
int o =(int)Math.round(closeness * (1 << this.params.communicationBits - 1));
setCommInbox(o);
}
public void tickNotification(long tick) {
if (!isAlive())
return;
/* The current tick */
currTick = tick;
/* Hack to find the birth tick... */
if (birthTick == 0)
birthTick = currTick;
age++;
/* Time to die, Agent Bond */
if (params.agingMode) {
if ((currTick - birthTick) >= params.agingLimit) {
die();
return;
}
}
/* Move/eat/reproduce/etc */
controller.controlAgent(this);
/* track me */
if (tracked)
poll();
/* Produce waste if able */
if (params.wasteMode)
tryPoop();
/* Check if broadcasting is enabled */
if (params.broadcastMode & !ComplexEnvironment.currentPackets.isEmpty())
receiveBroadcast();// []SK
}
public void tickZero() {
// nothing
}
private void tryAsexBreed() {
if (asexFlag && energy >= params.breedEnergy && params.asexualBreedChance != 0.0
&& cobweb.globals.random.nextFloat() < params.asexualBreedChance) {
pregPeriod = params.asexPregnancyPeriod;
pregnant = true;
}
}
/**
* Produce waste
*/
private void tryPoop() {
boolean produce = false;
if (wasteCounterGain <= 0 && params.wasteLimitGain > 0) {
produce = true;
wasteCounterGain += params.wasteLimitGain;
} else if (wasteCounterLoss <= 0 && params.wasteLimitLoss > 0) {
produce = true;
wasteCounterLoss += params.wasteLimitLoss;
}
if (!produce)
return;
boolean wasteAdded = false;
/* Output a waste somewhere "close" (rad 1 from currentPosition) */
for (int i = 0; i < dirList.length; i++) {
cobweb.Environment.Location foo = getPosition().getAdjacent(dirList[i]);
if (foo == null)
continue;
if (foo.getAgent() == null && !foo.testFlag(ComplexEnvironment.FLAG_STONE)
&& !foo.testFlag(ComplexEnvironment.FLAG_WASTE) && !foo.testFlag(ComplexEnvironment.FLAG_FOOD)) {
foo.setFlag(ComplexEnvironment.FLAG_FOOD, false);
foo.setFlag(ComplexEnvironment.FLAG_STONE, false);
foo.setFlag(ComplexEnvironment.FLAG_WASTE, true);
ComplexEnvironment.addWaste(currTick, foo.v[0], foo.v[1], params.wasteInit, params.wasteDecay);
wasteAdded = true;
i = dirList.length + 100;
break;
}
}
/*
* Crowded! IF there is no empty tile in which to drop the waste, we can replace a food tile with a waste
* tile... / This function is assumed to add a waste tile! That is, this function assumes an existence of at
* least one food tile that it will be able to replace with a waste tile. Nothing happens otherwise.
*/
if (!wasteAdded) {
for (int i = 0; i < dirList.length; i++) {
cobweb.Environment.Location foo = getPosition().getAdjacent(dirList[i]);
if (foo == null)
continue;
if (foo.getAgent() == null && foo.testFlag(ComplexEnvironment.FLAG_FOOD)) {
/* Hack: don't put a waste tile on top of an agent */
/* Nuke a food pile */
foo.setFlag(ComplexEnvironment.FLAG_FOOD, false);
foo.setFlag(ComplexEnvironment.FLAG_WASTE, true);
ComplexEnvironment.addWaste(currTick, foo.v[0], foo.v[1], params.wasteInit, params.wasteDecay);
wasteAdded = true;
i = dirList.length + 100;
break;
}
}
}
}
public void turnLeft() {
cobweb.Direction newFacing = new cobweb.Direction(2);
newFacing.v[0] = facing.v[1];
newFacing.v[1] = -facing.v[0];
facing = newFacing;
energy -= params.turnLeftEnergy;
wasteCounterLoss -= params.turnLeftEnergy;
info.useTurning(params.turnLeftEnergy);
info.addTurn();
afterTurnAction();
}
public void turnRight() {
cobweb.Direction newFacing = new cobweb.Direction(2);
newFacing.v[0] = -facing.v[1];
newFacing.v[1] = facing.v[0];
facing = newFacing;
energy -= params.turnRightEnergy;
wasteCounterLoss -= params.turnRightEnergy;
info.useTurning(params.turnRightEnergy);
info.addTurn();
afterTurnAction();
}
@Override
public int type() {
return agentType;
}
}
| true | true | public void step() {
cobweb.Agent adjAgent;
mustFlip = getPosition().checkFlip(facing);
cobweb.Environment.Location destPos = getPosition().getAdjacent(facing);
if (canStep(destPos)) {
// Check for food...
cobweb.Environment.Location breedPos = null;
if (destPos.testFlag(ComplexEnvironment.FLAG_FOOD)) {
if (params.broadcastMode & canBroadcast()) {
broadcastFood(destPos);
}
if (canEat(destPos)) {
eat(destPos);
}
if (pregnant && energy >= params.breedEnergy && pregPeriod <= 0) {
breedPos = getPosition();
energy -= params.initEnergy;
energy -= energyPenalty(true);
wasteCounterLoss -= params.initEnergy;
info.useOthers(params.initEnergy);
} else {
if (!pregnant)
tryAsexBreed();
}
}
for (StepMutator m : stepMutators)
m.onStep(this, getPosition(), destPos);
move(destPos);
if (breedPos != null) {
if (breedPartner == null) {
info.addDirectChild();
new ComplexAgent(breedPos, this, this.pdCheater);
} else {
// child's strategy is determined by its parents, it has a
// 50% chance to get either parent's strategy
int childStrategy = -1;
if (this.pdCheater != -1) {
boolean choose = cobweb.globals.random.nextBoolean();
if (choose) {
childStrategy = this.pdCheater;
} else {
childStrategy = breedPartner.pdCheater;
}
}
info.addDirectChild();
breedPartner.info.addDirectChild();
new ComplexAgent(breedPos, this, breedPartner, childStrategy);
info.addSexPreg();
}
breedPartner = null;
pregnant = false;
}
energy -= params.stepEnergy;
wasteCounterLoss -= params.stepEnergy;
info.useStepEnergy(params.stepEnergy);
info.addStep();
info.addPathStep(this.getPosition());
} else if ((adjAgent = getAdjacentAgent()) != null && adjAgent instanceof ComplexAgent
&& ((ComplexAgent) adjAgent).info != null) {
// two agents meet
ComplexAgent adjacentAgent = (ComplexAgent) adjAgent;
for (ContactMutator mut : contactMutators) {
mut.onContact(this, adjacentAgent);
}
if (canEat(adjacentAgent)) {
eat(adjacentAgent);
}
if (this.pdCheater != -1) {// $$$$$ if playing Prisoner's
// Dilemma. Please refer to ComplexEnvironment.load, "// spawn new random agents for each type"
want2meet = true;
}
int othersID = adjacentAgent.info.getAgentNumber();
// scan the memory array, is the 'other' agents ID is found in the array,
// then choose not to have a transaction with him.
for (int i = 0; i < params.pdMemory; i++) {
if (photo_memory[i] == othersID) {
want2meet = false;
}
}
// if the agents are of the same type, check if they have enough
// resources to breed
if (adjacentAgent.agentType == agentType) {
double sim = 0.0;
boolean canBreed = !pregnant && energy >= params.breedEnergy && params.sexualBreedChance != 0.0
&& cobweb.globals.random.nextFloat() < params.sexualBreedChance;
// Generate genetic similarity number
sim = simCalc.similarity(this, adjacentAgent);
if (sim >= params.commSimMin) {
communicate(adjacentAgent);
}
if (canBreed && sim >= params.breedSimMin
&& ((want2meet && adjacentAgent.want2meet) || (pdCheater == -1))) {
pregnant = true;
pregPeriod = params.sexualPregnancyPeriod;
breedPartner = adjacentAgent;
}
}
// perform the transaction only if non-pregnant and both agents want to meet
if (!pregnant && want2meet && adjacentAgent.want2meet) {
playPDonStep(adjacentAgent, othersID);
}
energy -= params.stepAgentEnergy;
wasteCounterLoss -= params.stepAgentEnergy;
info.useAgentBumpEnergy(params.stepAgentEnergy);
info.addAgentBump();
} // end of two agents meet
else if (destPos != null && destPos.testFlag(ComplexEnvironment.FLAG_WASTE)) {
// Bumps into waste
energy -= params.wastePen;
wasteCounterLoss -= params.wastePen;
info.useRockBumpEnergy(params.wastePen);
info.addRockBump();
} else {
// Rock bump
energy -= params.stepRockEnergy;
wasteCounterLoss -= params.stepRockEnergy;
info.useRockBumpEnergy(params.stepRockEnergy);
info.addRockBump();
}
energy -= energyPenalty(true);
if (energy <= 0)
die();
if (energy < params.breedEnergy) {
pregnant = false;
breedPartner = null;
}
if (pregnant) {
pregPeriod--;
}
}
| public void step() {
cobweb.Agent adjAgent;
mustFlip = getPosition().checkFlip(facing);
cobweb.Environment.Location destPos = getPosition().getAdjacent(facing);
if (canStep(destPos)) {
// Check for food...
cobweb.Environment.Location breedPos = null;
if (destPos.testFlag(ComplexEnvironment.FLAG_FOOD)) {
if (params.broadcastMode & canBroadcast()) {
broadcastFood(destPos);
}
if (canEat(destPos)) {
eat(destPos);
}
if (pregnant && energy >= params.breedEnergy && pregPeriod <= 0) {
breedPos = getPosition();
energy -= params.initEnergy;
energy -= energyPenalty(true);
wasteCounterLoss -= params.initEnergy;
info.useOthers(params.initEnergy);
} else {
if (!pregnant)
tryAsexBreed();
}
}
for (StepMutator m : stepMutators)
m.onStep(this, getPosition(), destPos);
move(destPos);
if (breedPos != null) {
if (breedPartner == null) {
info.addDirectChild();
new ComplexAgent(breedPos, this, this.pdCheater);
} else {
// child's strategy is determined by its parents, it has a
// 50% chance to get either parent's strategy
int childStrategy = -1;
if (this.pdCheater != -1) {
boolean choose = cobweb.globals.random.nextBoolean();
if (choose) {
childStrategy = this.pdCheater;
} else {
childStrategy = breedPartner.pdCheater;
}
}
info.addDirectChild();
breedPartner.info.addDirectChild();
new ComplexAgent(breedPos, this, breedPartner, childStrategy);
info.addSexPreg();
}
breedPartner = null;
pregnant = false;
}
energy -= params.stepEnergy;
wasteCounterLoss -= params.stepEnergy;
info.useStepEnergy(params.stepEnergy);
info.addStep();
} else if ((adjAgent = getAdjacentAgent()) != null && adjAgent instanceof ComplexAgent
&& ((ComplexAgent) adjAgent).info != null) {
// two agents meet
ComplexAgent adjacentAgent = (ComplexAgent) adjAgent;
for (ContactMutator mut : contactMutators) {
mut.onContact(this, adjacentAgent);
}
if (canEat(adjacentAgent)) {
eat(adjacentAgent);
}
if (this.pdCheater != -1) {// $$$$$ if playing Prisoner's
// Dilemma. Please refer to ComplexEnvironment.load, "// spawn new random agents for each type"
want2meet = true;
}
int othersID = adjacentAgent.info.getAgentNumber();
// scan the memory array, is the 'other' agents ID is found in the array,
// then choose not to have a transaction with him.
for (int i = 0; i < params.pdMemory; i++) {
if (photo_memory[i] == othersID) {
want2meet = false;
}
}
// if the agents are of the same type, check if they have enough
// resources to breed
if (adjacentAgent.agentType == agentType) {
double sim = 0.0;
boolean canBreed = !pregnant && energy >= params.breedEnergy && params.sexualBreedChance != 0.0
&& cobweb.globals.random.nextFloat() < params.sexualBreedChance;
// Generate genetic similarity number
sim = simCalc.similarity(this, adjacentAgent);
if (sim >= params.commSimMin) {
communicate(adjacentAgent);
}
if (canBreed && sim >= params.breedSimMin
&& ((want2meet && adjacentAgent.want2meet) || (pdCheater == -1))) {
pregnant = true;
pregPeriod = params.sexualPregnancyPeriod;
breedPartner = adjacentAgent;
}
}
// perform the transaction only if non-pregnant and both agents want to meet
if (!pregnant && want2meet && adjacentAgent.want2meet) {
playPDonStep(adjacentAgent, othersID);
}
energy -= params.stepAgentEnergy;
wasteCounterLoss -= params.stepAgentEnergy;
info.useAgentBumpEnergy(params.stepAgentEnergy);
info.addAgentBump();
} // end of two agents meet
else if (destPos != null && destPos.testFlag(ComplexEnvironment.FLAG_WASTE)) {
// Bumps into waste
energy -= params.wastePen;
wasteCounterLoss -= params.wastePen;
info.useRockBumpEnergy(params.wastePen);
info.addRockBump();
} else {
// Rock bump
energy -= params.stepRockEnergy;
wasteCounterLoss -= params.stepRockEnergy;
info.useRockBumpEnergy(params.stepRockEnergy);
info.addRockBump();
}
energy -= energyPenalty(true);
if (energy <= 0)
die();
if (energy < params.breedEnergy) {
pregnant = false;
breedPartner = null;
}
if (pregnant) {
pregPeriod--;
}
}
|
diff --git a/rwiki-tool/tool/src/java/uk/ac/cam/caret/sakai/rwiki/tool/RWikiServlet.java b/rwiki-tool/tool/src/java/uk/ac/cam/caret/sakai/rwiki/tool/RWikiServlet.java
index 44e6ad5c..79e30149 100644
--- a/rwiki-tool/tool/src/java/uk/ac/cam/caret/sakai/rwiki/tool/RWikiServlet.java
+++ b/rwiki-tool/tool/src/java/uk/ac/cam/caret/sakai/rwiki/tool/RWikiServlet.java
@@ -1,299 +1,302 @@
/**********************************************************************************
* $URL$
* $Id$
***********************************************************************************
*
* Copyright (c) 2003, 2004, 2005, 2006 The Sakai Foundation.
*
* Licensed under the Educational Community License, Version 1.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.opensource.org/licenses/ecl1.php
*
* 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 uk.ac.cam.caret.sakai.rwiki.tool;
import java.io.IOException;
import java.util.Enumeration;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sakaiproject.tool.api.Tool;
import org.sakaiproject.tool.api.ToolSession;
import org.sakaiproject.tool.cover.SessionManager;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import uk.ac.cam.caret.sakai.rwiki.tool.api.HttpCommand;
import uk.ac.cam.caret.sakai.rwiki.tool.bean.PrePopulateBean;
import uk.ac.cam.caret.sakai.rwiki.tool.bean.ViewBean;
import uk.ac.cam.caret.sakai.rwiki.tool.command.Dispatcher;
import uk.ac.cam.caret.sakai.rwiki.tool.command.SaveCommand;
import uk.ac.cam.caret.sakai.rwiki.tool.util.WikiPageAction;
import uk.ac.cam.caret.sakai.rwiki.utils.TimeLogger;
/**
* @author andrew
*/
public class RWikiServlet extends HttpServlet
{
private static Log log = LogFactory.getLog(RWikiServlet.class);
/**
* Required for serialization... also to stop eclipse from giving me a
* warning!
*/
private static final long serialVersionUID = 676743152200357706L;
public static final String SAVED_REQUEST_URL = "uk.ac.cam.caret.sakai.rwiki.tool.RWikiServlet.last-request-url";
private WebApplicationContext wac;
private String headerPreContent;
private String headerScriptSource;
private String footerScript;
private Dispatcher dispatcher = null;
public void init(ServletConfig servletConfig) throws ServletException
{
super.init(servletConfig);
ServletContext sc = servletConfig.getServletContext();
wac = WebApplicationContextUtils.getWebApplicationContext(sc);
headerPreContent = servletConfig.getInitParameter("headerPreContent");
headerScriptSource = servletConfig
.getInitParameter("headerScriptSource");
footerScript = servletConfig.getInitParameter("footerScript");
try
{
boolean logResponse = "true".equalsIgnoreCase(servletConfig
.getInitParameter("log-response"));
TimeLogger.setLogResponse(logResponse);
}
catch (Exception ex)
{
}
try
{
boolean logFullResponse = "true".equalsIgnoreCase(servletConfig
.getInitParameter("log-full-response"));
TimeLogger.setLogFullResponse(logFullResponse);
}
catch (Exception ex)
{
}
String basePath = servletConfig.getServletContext().getRealPath("/");
dispatcher = new MapDispatcher(sc);
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
try {
execute(request, response);
} finally {
RequestScopeSuperBean.clearInstance();
}
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
try {
execute(request, response);
} finally {
RequestScopeSuperBean.clearInstance();
}
}
public void execute(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
if (wac == null)
{
wac = WebApplicationContextUtils
.getRequiredWebApplicationContext(this.getServletContext());
if (wac == null)
{
response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE,
"Cannot get WebApplicationContext");
return;
}
}
log.debug("========================Page Start==========");
request.setAttribute(Tool.NATIVE_URL, Tool.NATIVE_URL);
String targetURL = persistState(request);
if (targetURL != null && targetURL.trim().length() > 0)
{
response.sendRedirect(targetURL);
return;
}
// Must be done on every request
prePopulateRealm(request);
addWikiStylesheet(request);
request.setAttribute("footerScript", footerScript);
- request.setAttribute("headerScriptSource", headerScriptSource);
+ if ( headerScriptSource != null && headerScriptSource.length() > 0 )
+ {
+ request.setAttribute("headerScriptSource", headerScriptSource);
+ }
RequestHelper helper = (RequestHelper) wac.getBean(RequestHelper.class
.getName());
HttpCommand command = helper.getCommandForRequest(request);
// fix for IE6's poor cache capabilities
String userAgent = request.getHeader("User-Agent");
if ( userAgent != null && userAgent.indexOf("MSIE 6") >= 0 ) {
response.addHeader("Expires","0");
response.addHeader("Pragma","cache");
response.addHeader("Cache-Control","private");
}
command.execute(dispatcher,request, response);
request.removeAttribute(Tool.NATIVE_URL);
log.debug("=====================Page End=============");
}
public void prePopulateRealm(HttpServletRequest request)
{
RequestScopeSuperBean rssb = RequestScopeSuperBean.createAndAttach(
request, wac);
PrePopulateBean ppBean = rssb.getPrePopulateBean();
ppBean.doPrepopulate();
}
public void addWikiStylesheet(HttpServletRequest request)
{
String sakaiHeader = (String) request.getAttribute("sakai.html.head");
request.setAttribute("sakai.html.head", headerPreContent + sakaiHeader);
}
/**
* returns the request state for the tool. If the state is restored, we set
* the request attribute RWikiServlet.REQUEST_STATE_RESTORED to Boolean.TRUE
* and a Thread local named RWikiServlet.REQUEST_STATE_RESTORED to
* Boolean.TRUE. These MUST be checked by anything that modifies state, to
* ensure that a reinitialisation of Tool state does not result in a repost
* of data.
*
* @param request
* @return
*/
private String persistState(HttpServletRequest request)
{
ToolSession ts = SessionManager.getCurrentToolSession();
if (isPageToolDefault(request))
{
if (log.isDebugEnabled())
{
log.debug("Incomming URL is " + request.getRequestURL().toString() + "?" + request.getQueryString());
log.debug("Restore " + ts.getAttribute(SAVED_REQUEST_URL));
}
return (String) ts.getAttribute(SAVED_REQUEST_URL);
}
if (isPageRestorable(request))
{
ts.setAttribute(SAVED_REQUEST_URL, request.getRequestURL()
.toString()
+ "?" + request.getQueryString());
if (log.isDebugEnabled())
{
log.debug("Saved " + ts.getAttribute(SAVED_REQUEST_URL));
}
}
return null;
}
/**
* Check to see if the reques represents the Tool default page. This is not
* the same as the view Home. It is the same as first entry into a Tool or
* when the page is refreshed
*
* @param request
* @return true if the page is the Tool default page
*/
// XXX this should not be here!! The RequestHelper should perform this
// functionality.
private boolean isPageToolDefault(HttpServletRequest request)
{
if (RequestHelper.TITLE_PANEL.equals(request
.getParameter(RequestHelper.PANEL))) return false;
if ( request.getPathInfo() != null && request.getPathInfo().startsWith("/helper/") ) {
return false;
}
String action = request.getParameter(RequestHelper.ACTION);
if (action != null && action.length() > 0) {
return false;
}
String pageName = request.getParameter(ViewBean.PAGE_NAME_PARAM);
if (pageName == null || pageName.trim().length() == 0) {
return true;
} else {
return false;
}
}
/**
* Check to see if the request represents a page that can act as a restor
* point.
*
* @param request
* @return true if it is possible to restore to this point.
*/
private boolean isPageRestorable(HttpServletRequest request)
{
if (RequestHelper.TITLE_PANEL.equals(request
.getParameter(RequestHelper.PANEL))) return false;
if (WikiPageAction.PUBLICVIEW_ACTION.getName().equals(
request.getParameter(RequestHelper.ACTION))) return false;
if (WikiPageAction.PRINTVIEW_ACTION.getName().equals(
request.getParameter(RequestHelper.ACTION))) return false;
if ("GET".equalsIgnoreCase(request.getMethod())) return true;
return false;
}
}
| true | true | public void execute(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
if (wac == null)
{
wac = WebApplicationContextUtils
.getRequiredWebApplicationContext(this.getServletContext());
if (wac == null)
{
response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE,
"Cannot get WebApplicationContext");
return;
}
}
log.debug("========================Page Start==========");
request.setAttribute(Tool.NATIVE_URL, Tool.NATIVE_URL);
String targetURL = persistState(request);
if (targetURL != null && targetURL.trim().length() > 0)
{
response.sendRedirect(targetURL);
return;
}
// Must be done on every request
prePopulateRealm(request);
addWikiStylesheet(request);
request.setAttribute("footerScript", footerScript);
request.setAttribute("headerScriptSource", headerScriptSource);
RequestHelper helper = (RequestHelper) wac.getBean(RequestHelper.class
.getName());
HttpCommand command = helper.getCommandForRequest(request);
// fix for IE6's poor cache capabilities
String userAgent = request.getHeader("User-Agent");
if ( userAgent != null && userAgent.indexOf("MSIE 6") >= 0 ) {
response.addHeader("Expires","0");
response.addHeader("Pragma","cache");
response.addHeader("Cache-Control","private");
}
command.execute(dispatcher,request, response);
request.removeAttribute(Tool.NATIVE_URL);
log.debug("=====================Page End=============");
}
| public void execute(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
if (wac == null)
{
wac = WebApplicationContextUtils
.getRequiredWebApplicationContext(this.getServletContext());
if (wac == null)
{
response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE,
"Cannot get WebApplicationContext");
return;
}
}
log.debug("========================Page Start==========");
request.setAttribute(Tool.NATIVE_URL, Tool.NATIVE_URL);
String targetURL = persistState(request);
if (targetURL != null && targetURL.trim().length() > 0)
{
response.sendRedirect(targetURL);
return;
}
// Must be done on every request
prePopulateRealm(request);
addWikiStylesheet(request);
request.setAttribute("footerScript", footerScript);
if ( headerScriptSource != null && headerScriptSource.length() > 0 )
{
request.setAttribute("headerScriptSource", headerScriptSource);
}
RequestHelper helper = (RequestHelper) wac.getBean(RequestHelper.class
.getName());
HttpCommand command = helper.getCommandForRequest(request);
// fix for IE6's poor cache capabilities
String userAgent = request.getHeader("User-Agent");
if ( userAgent != null && userAgent.indexOf("MSIE 6") >= 0 ) {
response.addHeader("Expires","0");
response.addHeader("Pragma","cache");
response.addHeader("Cache-Control","private");
}
command.execute(dispatcher,request, response);
request.removeAttribute(Tool.NATIVE_URL);
log.debug("=====================Page End=============");
}
|
diff --git a/common/src/main/java/org/jboss/capedwarf/common/servlet/ServletUtils.java b/common/src/main/java/org/jboss/capedwarf/common/servlet/ServletUtils.java
index 43fa2d83..4cc85d7b 100644
--- a/common/src/main/java/org/jboss/capedwarf/common/servlet/ServletUtils.java
+++ b/common/src/main/java/org/jboss/capedwarf/common/servlet/ServletUtils.java
@@ -1,50 +1,53 @@
/*
*
* * JBoss, Home of Professional Open Source.
* * Copyright 2011, 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.capedwarf.common.servlet;
import javax.servlet.http.Part;
/**
* @author <a href="mailto:[email protected]">Marko Luksa</a>
*/
public class ServletUtils {
public static boolean isFile(Part part) {
return getFileName(part) != null;
}
public static String getFileName(Part part) {
// TODO: surely, there is an existing servlet api method that does this. Googled it, but found nothing (!?)
String contentDisposition = part.getHeader("content-disposition");
for (String token : contentDisposition.split(";")) {
if (token.trim().startsWith("filename")) {
- return token.substring(token.indexOf('=') + 1).trim().replace("\"", "");
+ String filename = token.substring(token.indexOf('=') + 1).trim().replace("\"", "");
+ if (filename.length() > 0) {
+ return filename;
+ }
}
}
return null;
}
}
| true | true | public static String getFileName(Part part) {
// TODO: surely, there is an existing servlet api method that does this. Googled it, but found nothing (!?)
String contentDisposition = part.getHeader("content-disposition");
for (String token : contentDisposition.split(";")) {
if (token.trim().startsWith("filename")) {
return token.substring(token.indexOf('=') + 1).trim().replace("\"", "");
}
}
return null;
}
| public static String getFileName(Part part) {
// TODO: surely, there is an existing servlet api method that does this. Googled it, but found nothing (!?)
String contentDisposition = part.getHeader("content-disposition");
for (String token : contentDisposition.split(";")) {
if (token.trim().startsWith("filename")) {
String filename = token.substring(token.indexOf('=') + 1).trim().replace("\"", "");
if (filename.length() > 0) {
return filename;
}
}
}
return null;
}
|
diff --git a/src/org/dancres/paxos/Leader.java b/src/org/dancres/paxos/Leader.java
index 9be0b2a..bdfd1b2 100644
--- a/src/org/dancres/paxos/Leader.java
+++ b/src/org/dancres/paxos/Leader.java
@@ -1,636 +1,638 @@
package org.dancres.paxos;
import org.dancres.paxos.messages.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.InetSocketAddress;
import java.util.List;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Timer;
import java.util.TimerTask;
/**
* Implements the leader state machine.
*
* @todo State recovery - basic model will be to resolve memory state from the last checkpoint and then replay the log
* to bring that memory state up-to-date (possibly by re-announcing completions via the AcceptorLearner). Once that
* is done, we could become the leader.
* @todo If some other leader failed, we need to resolve any previous slots outstanding. It's possible the old leader
* secured a slot and declared a value but didn't report back to the client. In that case, the client would see it's
* leader fail to respond and have to either submit an operation to determine whether it's previous attempt succeeded
* or submit an idempotent operation that could be retried safely multiple times. Other cases include the leader
* reserving a slot but not filling in a value in which case we need to fill it with a null value (which AcceptorLearner
* would need to drop silently rather than deliver it to a listener). It's also possible the leader proposed a value
* but didn't reach a majority due to network issues and then died. In such a case, the new leader will have to settle
* that round with the partially agreed value. It's likely that will be done with the originating client absent so
* as per the leader failed to report case, the client will need to retry with the appropriate protocol.
* @todo Add a test for validating multiple sequence number recovery.
* @todo Add a test for validating retries on dropped packets in later leader states.
*
* @author dan
*/
public class Leader implements MembershipListener {
private static final Logger _logger = LoggerFactory.getLogger(Leader.class);
private static final long GRACE_PERIOD = 500;
private static final long MAX_TRIES = 3;
/*
* Internal states
*/
/**
* Leader reaches this state after SUBMITTED. If already leader, a transition to BEGIN will be immediate.
* If not leader and recovery is not active, move to state RECOVER otherwise leader is in recovery and must now
* settle low to high watermark (as set by RECOVER) before processing any submitted value by repeatedly executing
* full instances of paxos (including a COLLECT to recover any previous value that was proposed).
*/
private static final int COLLECT = 0;
/**
* Attempt to reserve a slot in the sequence of operations. Transition to SUCCESS after emitting begin to see
* if the slot was granted.
*/
private static final int BEGIN = 1;
/**
* Leader has sent a BEGIN and now determines if it has secured the slot associated with the sequence number.
* If the slot was secured, a value will be sent to all members of the current instance after which there will
* be a transition to COMMITTED.
*/
private static final int SUCCESS = 2;
/**
* A paxos instance was completed successfully, clean up is all that remains.
*/
private static final int EXIT = 3;
/**
* A paxos isntance failed for some reason (which will be found in </code>_completion</code>).
*/
private static final int ABORT = 4;
/**
* Leader has completed the necessary steps to secure an entry in storage for a particular sequence number
* and is now processing ACKs to ensure enough nodes have seen the committed value.
*/
private static final int COMMITTED = 6;
/**
* Leader has been given a value and should attempt to complete a paxos instance.
*/
private static final int SUBMITTED = 7;
private final Timer _watchdog = new Timer("Leader timers");
private final FailureDetector _detector;
private final Transport _transport;
private final AcceptorLearner _al;
private long _seqNum = AcceptorLearner.UNKNOWN_SEQ;
/**
* Tracks the round number this leader used last. This cannot be stored in the acceptor/learner's version without
* risking breaking the collect protocol (the al could suddenly believe it's seen a collect it hasn't and become
* noisy when it should be silent). This field can be updated as the result of OldRound messages.
*/
private long _rndNumber = 0;
private long _tries = 0;
/**
* This alarm is used to limit the amount of time the leader will wait for responses from all apparently live
* members in a round of communication.
*/
private TimerTask _interactionAlarm;
/**
* This alarm is used to ensure the leader sends regular heartbeats in the face of inactivity so as to extend
* its lease with AcceptorLearners.
*/
private TimerTask _heartbeatAlarm;
/**
* Tracks membership for an entire paxos instance.
*/
private Membership _membership;
private int _state = EXIT;
/**
* In cases of ABORT, indicates the reason
*/
private Event _event;
private List<PaxosMessage> _messages = new ArrayList<PaxosMessage>();
private List<ConsolidatedValue> _queue = new LinkedList<ConsolidatedValue>();
public Leader(FailureDetector aDetector, Transport aTransport, AcceptorLearner anAcceptorLearner) {
_detector = aDetector;
_transport = aTransport;
_al = anAcceptorLearner;
}
public void shutdown() {
_watchdog.cancel();
}
private long calculateLeaderRefresh() {
long myExpiry = _al.getLeaderLeaseDuration();
return myExpiry - (myExpiry * 20 / 100);
}
private long calculateInteractionTimeout() {
return GRACE_PERIOD;
}
public long getCurrentRound() {
synchronized(this) {
return _rndNumber;
}
}
public boolean isReady() {
synchronized(this) {
return (_state == EXIT) || (_state == ABORT);
}
}
/**
* Do actions for the state we are now in. Essentially, we're always one state ahead of the participants thus we
* process the result of a Collect in the BEGIN state which means we expect Last or OldRound and in SUCCESS state
* we expect ACCEPT or OLDROUND
*
* @todo Increment round number via heartbeats every so often - see note below about jittering collects.
*/
private void process() {
switch(_state) {
case ABORT : {
assert (_queue.size() != 0);
_logger.info(this + ": ABORT " + _event, new RuntimeException());
_messages.clear();
if (_membership != null)
_membership.dispose();
/*
* We must fail all queued operations - use the same completion code...
*/
while (_queue.size() > 0) {
_al.signal(new Event(_event.getResult(), _event.getSeqNum(),
_queue.remove(0)));
}
return;
}
case EXIT : {
assert (_queue.size() != 0);
_logger.info(this + ": EXIT " + _event);
_messages.clear();
// Remove the just processed item
//
_queue.remove(0);
if (_membership != null)
_membership.dispose();
if (_queue.size() > 0) {
_logger.info(this + ": processing op from queue: " + _queue.get(0));
_state = SUBMITTED;
process();
} else {
// If we got here, we're leader, setup for a heartbeat if there's no other activity
//
_heartbeatAlarm = new TimerTask() {
public void run() {
_logger.info(this + ": sending heartbeat: " + System.currentTimeMillis());
submit(AcceptorLearner.HEARTBEAT);
}
};
_watchdog.schedule(_heartbeatAlarm, calculateLeaderRefresh());
}
return;
}
case SUBMITTED : {
assert (_queue.size() != 0);
_tries = 0;
_membership = _detector.getMembers(this);
_logger.info(this + ": got membership: (" +
_membership.getSize() + ")");
// Collect will decide if it can skip straight to a begin
//
_state = COLLECT;
process();
break;
}
/*
* It's possible an AL will have seen a success that no others saw such that a previous value is
* not fully committed. That's okay as a lagging leader will propose a new client value for that sequence
* number and find that AL tells it about this value which will cause the leader to finish off that
* round and any others after which it can propose the client value for a sequence number. Should that AL
* die the record is lost and the client needs to re-propose the value.
*
* Other AL's may have missed other values, that's also okay as they will separately deduce they have
* missing instances to catch-up and recover that state from those around them.
*/
case COLLECT : {
assert (_queue.size() != 0);
// We've got activity, cancel heartbeat until we're done. Note this may be a heartbeat, that's okay.
//
if (_heartbeatAlarm != null)
_heartbeatAlarm.cancel();
Collect myLastCollect = _al.getLastCollect();
// Collect is INITIAL means no leader known so try to become leader
//
if (myLastCollect.isInitial()) {
_logger.info(this + ": collect is initial");
_rndNumber = myLastCollect.getRndNumber() + 1;
} else {
InetSocketAddress myOtherLeader = myLastCollect.getNodeId();
boolean isUs = myOtherLeader.equals(_transport.getLocalAddress());
/*
* If the leader is us we needn't update our round number and we can proceed, otherwise
* we ascertain liveness of last known leader and proceed if it appears dead.
*
* This potential leader and its associated AL may be unaware of the active leader or indeed
* it may appear dead. Under such circumstances this potential leader will attempt to
* become anointed but could fail on an existing leader lease which would lead to a vote
* timeout. The client would thus re-submit or similar rather than swap to the active leader node.
* This is okay as eventually this potential leader will decide the active leader is alive and
* immediately reject the client with an other leader message resulting in the necessary re-routing.
*
* The above behaviour has another benefit which is a client can connect to any member of the
* paxos co-operative and be re-directed to the leader node. This means clients don't have to
* perform any specialised behaviours for selecting a leader.
*/
if (! isUs) {
_logger.info(this + ": leader is not us");
if (_detector.isLive(myOtherLeader)) {
_logger.info(this + ": other leader is alive");
error(Event.Reason.OTHER_LEADER, myOtherLeader);
return;
} else {
_logger.info(this + ": other leader not alive");
/*
* If we're going for leadership, make sure we have a credible round number. If this
* round number isn't good enough, we'll find out via OldRound messages and update
* the round number accordingly.
*/
if (_rndNumber <= myLastCollect.getRndNumber())
_rndNumber = myLastCollect.getRndNumber() + 1;
}
}
}
// Possibility we're starting from scratch
//
if (_seqNum == AcceptorLearner.UNKNOWN_SEQ)
_seqNum = 0;
else
_seqNum = _seqNum + 1;
_state = BEGIN;
emit(new Collect(_seqNum, _rndNumber, _transport.getLocalAddress()));
break;
}
case BEGIN : {
assert (_queue.size() != 0);
long myMaxProposal = -1;
ConsolidatedValue myValue = null;
for(PaxosMessage m : _messages) {
Last myLast = (Last) m;
if (!myLast.getConsolidatedValue().equals(LogStorage.NO_VALUE)) {
- if (myLast.getRndNumber() > myMaxProposal)
+ if (myLast.getRndNumber() > myMaxProposal) {
myValue = myLast.getConsolidatedValue();
+ myMaxProposal = myLast.getRndNumber();
+ }
}
}
/*
* If we have a value from a LAST message and it's not the same as the one we want to propose,
* we've hit an outstanding paxos instance and must now drive it to completion. Put it at the head of
* the queue ready for the BEGIN. Note we must compare the consolidated value we want to propose
* as the one in the LAST message will be a consolidated value.
*/
if ((myValue != null) && (! myValue.equals(_queue.get(0))))
_queue.add(myValue);
_state = SUCCESS;
emit(new Begin(_seqNum, _rndNumber, _queue.get(0),
_transport.getLocalAddress()));
break;
}
case SUCCESS : {
assert (_queue.size() != 0);
if (_messages.size() >= _detector.getMajority()) {
// Send success, wait for acks
//
_state = COMMITTED;
emit(new Success(_seqNum, _rndNumber,
_queue.get(0), _transport.getLocalAddress()));
} else {
// Need another try, didn't get enough accepts but didn't get leader conflict
//
emit(new Begin(_seqNum, _rndNumber, _queue.get(0),
_transport.getLocalAddress()));
}
break;
}
case COMMITTED : {
assert (_queue.size() != 0);
/*
* If ACK messages total more than majority we're happy otherwise try again.
*/
if (_messages.size() >= _detector.getMajority()) {
successful(Event.Reason.DECISION, null);
} else {
// Need another try, didn't get enough accepts but didn't get leader conflict
//
emit(new Success(_seqNum, _rndNumber,
_queue.get(0), _transport.getLocalAddress()));
}
break;
}
default : throw new RuntimeException("Invalid state: " + _state);
}
}
private boolean canRetry() {
return (_state == SUCCESS) || (_state == COMMITTED);
}
/**
* @param aMessage is an OldRound message received from some other node
*/
private void oldRound(PaxosMessage aMessage) {
OldRound myOldRound = (OldRound) aMessage;
InetSocketAddress myCompetingNodeId = myOldRound.getLeaderNodeId();
/*
* If we're getting an OldRound, the other leader's lease has expired. We may be about to become leader
* but if we're proposing against an already settled sequence number we need to get up to date. If we were
* about to become leader but our sequence number is out of date, the response we'll get from an AL is an
* OldRound where the round number is less than ours but the sequence number is greater. Note that updating
* our _seqNum will drive our own AL to recover missing state should that be necessary.
*/
if (myOldRound.getLastRound() < _rndNumber) {
if (myOldRound.getSeqNum() > _seqNum) {
_logger.info(this + ": This leader is out of date: " + _seqNum + " < " + myOldRound.getSeqNum());
_seqNum = myOldRound.getSeqNum();
_state = COLLECT;
process();
}
} else {
_logger.info(this + ": Another leader is active, backing down: " + myCompetingNodeId + " (" +
myOldRound.getLastRound() + ", " + _rndNumber + ")");
_rndNumber = myOldRound.getLastRound() + 1;
error(Event.Reason.OTHER_LEADER, myCompetingNodeId);
}
}
private void successful(int aReason, Object aContext) {
_state = EXIT;
_event = new Event(aReason, _seqNum, _queue.get(0), aContext);
process();
}
private void error(int aReason, Object aContext) {
_state = ABORT;
_event = new Event(aReason, _seqNum, _queue.get(0), aContext);
process();
}
private void emit(PaxosMessage aMessage) {
_messages.clear();
if (startInteraction()) {
_logger.info(this + ": sending: " + aMessage);
_transport.send(aMessage, _transport.getBroadcastAddress());
}
}
private boolean startInteraction() {
_interactionAlarm = new TimerTask() {
public void run() {
expired();
}
};
_watchdog.schedule(_interactionAlarm, calculateInteractionTimeout());
return _membership.startInteraction();
}
/**
* @todo If we get ABORT, we could try a new round from scratch or make the client re-submit or .....
*/
public void abort() {
_logger.info(this + ": Membership requested abort");
_interactionAlarm.cancel();
synchronized(this) {
error(Event.Reason.BAD_MEMBERSHIP, null);
}
}
private void expired() {
// _interactionAlarm will be cancelled automatically
//
_logger.info(this + ": Watchdog requested abort: ");
synchronized(this) {
if (canRetry()) {
++_tries;
if (_tries < MAX_TRIES) {
process();
return;
}
}
error(Event.Reason.VOTE_TIMEOUT, null);
}
}
public void allReceived() {
_interactionAlarm.cancel();
synchronized(this) {
_tries = 0;
process();
}
}
public void submit(byte[] aValue, byte[] aHandback) {
submit(new ConsolidatedValue(aValue, aHandback));
}
/**
* Request a vote on a value.
*
* @param aValue is the value to attempt to agree upon
*/
private void submit(ConsolidatedValue aValue) {
synchronized (this) {
_queue.add(aValue);
if (! isReady()) {
_logger.info(this + ": Queued operation (already active): " + aValue);
} else {
_logger.info(this + ": Queued operation (initialising leader)");
_state = SUBMITTED;
process();
}
}
}
/**
* Used to process all core paxos protocol messages.
*
* We optimise by counting messages and transitioning as soon as we have enough and detecting failure
* immediately. But what if we miss an oldRound? If we miss an OldRound it can only be because a minority is seeing
* another leader and when it runs into our majority, it will be forced to resync seqNum/learnedValues etc. In
* essence if we've progressed through enough phases to get a majority commit we can go ahead and set the value as
* any future leader wading in will pick up our value. NOTE: This optimisation requires the membership impl to
* understand the concept of minimum acceptable majority.
*
* @param aMessage is a message from some acceptor/learner
*/
public void messageReceived(PaxosMessage aMessage) {
assert (aMessage.getClassification() != PaxosMessage.CLIENT): "Got a client message and shouldn't have done";
_logger.info(this + " received message: " + aMessage);
synchronized (this) {
if ((aMessage.getSeqNum() == _seqNum) && MessageValidator.getValidator(_state).acceptable(aMessage)) {
if (MessageValidator.getValidator(_state).fail(aMessage)) {
// Can only be an oldRound right now...
//
oldRound(aMessage);
} else {
_messages.add(aMessage);
_membership.receivedResponse(aMessage.getNodeId());
}
} else {
_logger.warn(this + ": Unexpected message received: " + aMessage);
}
}
}
public String toString() {
int myState;
synchronized(this) {
myState = _state;
}
return "Leader: " + _transport.getLocalAddress() +
": (" + Long.toHexString(_seqNum) + ", " + Long.toHexString(_rndNumber) + ")" + " in state: " + myState +
" tries: " + _tries + "/" + MAX_TRIES;
}
private static abstract class MessageValidator {
private static final MessageValidator _commitValidator =
new MessageValidator(new Class[]{Ack.class}, new Class[]{}) {};
private static final MessageValidator _beginValidator =
new MessageValidator(new Class[]{OldRound.class, Last.class}, new Class[]{OldRound.class}) {};
private static final MessageValidator _successValidator =
new MessageValidator(new Class[]{OldRound.class, Accept.class}, new Class[]{OldRound.class}){};
private static final MessageValidator _nullValidator =
new MessageValidator(new Class[]{}, new Class[]{}) {};
static MessageValidator getValidator(int aLeaderState) {
switch(aLeaderState) {
case BEGIN : return _beginValidator;
case COMMITTED : return _commitValidator;
case SUCCESS : return _successValidator;
default : throw new RuntimeException("No validator for state: " + aLeaderState);
}
}
private Class[] _acceptable;
private Class[] _fail;
private MessageValidator(Class[] acceptable, Class[] fail) {
_acceptable = acceptable;
_fail = fail;
}
boolean acceptable(PaxosMessage aMessage) {
for (Class c: _acceptable) {
if (aMessage.getClass().equals(c))
return true;
}
return false;
}
boolean fail(PaxosMessage aMessage) {
for (Class c: _fail) {
if (aMessage.getClass().equals(c))
return true;
}
return false;
}
}
}
| false | true | private void process() {
switch(_state) {
case ABORT : {
assert (_queue.size() != 0);
_logger.info(this + ": ABORT " + _event, new RuntimeException());
_messages.clear();
if (_membership != null)
_membership.dispose();
/*
* We must fail all queued operations - use the same completion code...
*/
while (_queue.size() > 0) {
_al.signal(new Event(_event.getResult(), _event.getSeqNum(),
_queue.remove(0)));
}
return;
}
case EXIT : {
assert (_queue.size() != 0);
_logger.info(this + ": EXIT " + _event);
_messages.clear();
// Remove the just processed item
//
_queue.remove(0);
if (_membership != null)
_membership.dispose();
if (_queue.size() > 0) {
_logger.info(this + ": processing op from queue: " + _queue.get(0));
_state = SUBMITTED;
process();
} else {
// If we got here, we're leader, setup for a heartbeat if there's no other activity
//
_heartbeatAlarm = new TimerTask() {
public void run() {
_logger.info(this + ": sending heartbeat: " + System.currentTimeMillis());
submit(AcceptorLearner.HEARTBEAT);
}
};
_watchdog.schedule(_heartbeatAlarm, calculateLeaderRefresh());
}
return;
}
case SUBMITTED : {
assert (_queue.size() != 0);
_tries = 0;
_membership = _detector.getMembers(this);
_logger.info(this + ": got membership: (" +
_membership.getSize() + ")");
// Collect will decide if it can skip straight to a begin
//
_state = COLLECT;
process();
break;
}
/*
* It's possible an AL will have seen a success that no others saw such that a previous value is
* not fully committed. That's okay as a lagging leader will propose a new client value for that sequence
* number and find that AL tells it about this value which will cause the leader to finish off that
* round and any others after which it can propose the client value for a sequence number. Should that AL
* die the record is lost and the client needs to re-propose the value.
*
* Other AL's may have missed other values, that's also okay as they will separately deduce they have
* missing instances to catch-up and recover that state from those around them.
*/
case COLLECT : {
assert (_queue.size() != 0);
// We've got activity, cancel heartbeat until we're done. Note this may be a heartbeat, that's okay.
//
if (_heartbeatAlarm != null)
_heartbeatAlarm.cancel();
Collect myLastCollect = _al.getLastCollect();
// Collect is INITIAL means no leader known so try to become leader
//
if (myLastCollect.isInitial()) {
_logger.info(this + ": collect is initial");
_rndNumber = myLastCollect.getRndNumber() + 1;
} else {
InetSocketAddress myOtherLeader = myLastCollect.getNodeId();
boolean isUs = myOtherLeader.equals(_transport.getLocalAddress());
/*
* If the leader is us we needn't update our round number and we can proceed, otherwise
* we ascertain liveness of last known leader and proceed if it appears dead.
*
* This potential leader and its associated AL may be unaware of the active leader or indeed
* it may appear dead. Under such circumstances this potential leader will attempt to
* become anointed but could fail on an existing leader lease which would lead to a vote
* timeout. The client would thus re-submit or similar rather than swap to the active leader node.
* This is okay as eventually this potential leader will decide the active leader is alive and
* immediately reject the client with an other leader message resulting in the necessary re-routing.
*
* The above behaviour has another benefit which is a client can connect to any member of the
* paxos co-operative and be re-directed to the leader node. This means clients don't have to
* perform any specialised behaviours for selecting a leader.
*/
if (! isUs) {
_logger.info(this + ": leader is not us");
if (_detector.isLive(myOtherLeader)) {
_logger.info(this + ": other leader is alive");
error(Event.Reason.OTHER_LEADER, myOtherLeader);
return;
} else {
_logger.info(this + ": other leader not alive");
/*
* If we're going for leadership, make sure we have a credible round number. If this
* round number isn't good enough, we'll find out via OldRound messages and update
* the round number accordingly.
*/
if (_rndNumber <= myLastCollect.getRndNumber())
_rndNumber = myLastCollect.getRndNumber() + 1;
}
}
}
// Possibility we're starting from scratch
//
if (_seqNum == AcceptorLearner.UNKNOWN_SEQ)
_seqNum = 0;
else
_seqNum = _seqNum + 1;
_state = BEGIN;
emit(new Collect(_seqNum, _rndNumber, _transport.getLocalAddress()));
break;
}
case BEGIN : {
assert (_queue.size() != 0);
long myMaxProposal = -1;
ConsolidatedValue myValue = null;
for(PaxosMessage m : _messages) {
Last myLast = (Last) m;
if (!myLast.getConsolidatedValue().equals(LogStorage.NO_VALUE)) {
if (myLast.getRndNumber() > myMaxProposal)
myValue = myLast.getConsolidatedValue();
}
}
/*
* If we have a value from a LAST message and it's not the same as the one we want to propose,
* we've hit an outstanding paxos instance and must now drive it to completion. Put it at the head of
* the queue ready for the BEGIN. Note we must compare the consolidated value we want to propose
* as the one in the LAST message will be a consolidated value.
*/
if ((myValue != null) && (! myValue.equals(_queue.get(0))))
_queue.add(myValue);
_state = SUCCESS;
emit(new Begin(_seqNum, _rndNumber, _queue.get(0),
_transport.getLocalAddress()));
break;
}
case SUCCESS : {
assert (_queue.size() != 0);
if (_messages.size() >= _detector.getMajority()) {
// Send success, wait for acks
//
_state = COMMITTED;
emit(new Success(_seqNum, _rndNumber,
_queue.get(0), _transport.getLocalAddress()));
} else {
// Need another try, didn't get enough accepts but didn't get leader conflict
//
emit(new Begin(_seqNum, _rndNumber, _queue.get(0),
_transport.getLocalAddress()));
}
break;
}
case COMMITTED : {
assert (_queue.size() != 0);
/*
* If ACK messages total more than majority we're happy otherwise try again.
*/
if (_messages.size() >= _detector.getMajority()) {
successful(Event.Reason.DECISION, null);
} else {
// Need another try, didn't get enough accepts but didn't get leader conflict
//
emit(new Success(_seqNum, _rndNumber,
_queue.get(0), _transport.getLocalAddress()));
}
break;
}
default : throw new RuntimeException("Invalid state: " + _state);
}
}
| private void process() {
switch(_state) {
case ABORT : {
assert (_queue.size() != 0);
_logger.info(this + ": ABORT " + _event, new RuntimeException());
_messages.clear();
if (_membership != null)
_membership.dispose();
/*
* We must fail all queued operations - use the same completion code...
*/
while (_queue.size() > 0) {
_al.signal(new Event(_event.getResult(), _event.getSeqNum(),
_queue.remove(0)));
}
return;
}
case EXIT : {
assert (_queue.size() != 0);
_logger.info(this + ": EXIT " + _event);
_messages.clear();
// Remove the just processed item
//
_queue.remove(0);
if (_membership != null)
_membership.dispose();
if (_queue.size() > 0) {
_logger.info(this + ": processing op from queue: " + _queue.get(0));
_state = SUBMITTED;
process();
} else {
// If we got here, we're leader, setup for a heartbeat if there's no other activity
//
_heartbeatAlarm = new TimerTask() {
public void run() {
_logger.info(this + ": sending heartbeat: " + System.currentTimeMillis());
submit(AcceptorLearner.HEARTBEAT);
}
};
_watchdog.schedule(_heartbeatAlarm, calculateLeaderRefresh());
}
return;
}
case SUBMITTED : {
assert (_queue.size() != 0);
_tries = 0;
_membership = _detector.getMembers(this);
_logger.info(this + ": got membership: (" +
_membership.getSize() + ")");
// Collect will decide if it can skip straight to a begin
//
_state = COLLECT;
process();
break;
}
/*
* It's possible an AL will have seen a success that no others saw such that a previous value is
* not fully committed. That's okay as a lagging leader will propose a new client value for that sequence
* number and find that AL tells it about this value which will cause the leader to finish off that
* round and any others after which it can propose the client value for a sequence number. Should that AL
* die the record is lost and the client needs to re-propose the value.
*
* Other AL's may have missed other values, that's also okay as they will separately deduce they have
* missing instances to catch-up and recover that state from those around them.
*/
case COLLECT : {
assert (_queue.size() != 0);
// We've got activity, cancel heartbeat until we're done. Note this may be a heartbeat, that's okay.
//
if (_heartbeatAlarm != null)
_heartbeatAlarm.cancel();
Collect myLastCollect = _al.getLastCollect();
// Collect is INITIAL means no leader known so try to become leader
//
if (myLastCollect.isInitial()) {
_logger.info(this + ": collect is initial");
_rndNumber = myLastCollect.getRndNumber() + 1;
} else {
InetSocketAddress myOtherLeader = myLastCollect.getNodeId();
boolean isUs = myOtherLeader.equals(_transport.getLocalAddress());
/*
* If the leader is us we needn't update our round number and we can proceed, otherwise
* we ascertain liveness of last known leader and proceed if it appears dead.
*
* This potential leader and its associated AL may be unaware of the active leader or indeed
* it may appear dead. Under such circumstances this potential leader will attempt to
* become anointed but could fail on an existing leader lease which would lead to a vote
* timeout. The client would thus re-submit or similar rather than swap to the active leader node.
* This is okay as eventually this potential leader will decide the active leader is alive and
* immediately reject the client with an other leader message resulting in the necessary re-routing.
*
* The above behaviour has another benefit which is a client can connect to any member of the
* paxos co-operative and be re-directed to the leader node. This means clients don't have to
* perform any specialised behaviours for selecting a leader.
*/
if (! isUs) {
_logger.info(this + ": leader is not us");
if (_detector.isLive(myOtherLeader)) {
_logger.info(this + ": other leader is alive");
error(Event.Reason.OTHER_LEADER, myOtherLeader);
return;
} else {
_logger.info(this + ": other leader not alive");
/*
* If we're going for leadership, make sure we have a credible round number. If this
* round number isn't good enough, we'll find out via OldRound messages and update
* the round number accordingly.
*/
if (_rndNumber <= myLastCollect.getRndNumber())
_rndNumber = myLastCollect.getRndNumber() + 1;
}
}
}
// Possibility we're starting from scratch
//
if (_seqNum == AcceptorLearner.UNKNOWN_SEQ)
_seqNum = 0;
else
_seqNum = _seqNum + 1;
_state = BEGIN;
emit(new Collect(_seqNum, _rndNumber, _transport.getLocalAddress()));
break;
}
case BEGIN : {
assert (_queue.size() != 0);
long myMaxProposal = -1;
ConsolidatedValue myValue = null;
for(PaxosMessage m : _messages) {
Last myLast = (Last) m;
if (!myLast.getConsolidatedValue().equals(LogStorage.NO_VALUE)) {
if (myLast.getRndNumber() > myMaxProposal) {
myValue = myLast.getConsolidatedValue();
myMaxProposal = myLast.getRndNumber();
}
}
}
/*
* If we have a value from a LAST message and it's not the same as the one we want to propose,
* we've hit an outstanding paxos instance and must now drive it to completion. Put it at the head of
* the queue ready for the BEGIN. Note we must compare the consolidated value we want to propose
* as the one in the LAST message will be a consolidated value.
*/
if ((myValue != null) && (! myValue.equals(_queue.get(0))))
_queue.add(myValue);
_state = SUCCESS;
emit(new Begin(_seqNum, _rndNumber, _queue.get(0),
_transport.getLocalAddress()));
break;
}
case SUCCESS : {
assert (_queue.size() != 0);
if (_messages.size() >= _detector.getMajority()) {
// Send success, wait for acks
//
_state = COMMITTED;
emit(new Success(_seqNum, _rndNumber,
_queue.get(0), _transport.getLocalAddress()));
} else {
// Need another try, didn't get enough accepts but didn't get leader conflict
//
emit(new Begin(_seqNum, _rndNumber, _queue.get(0),
_transport.getLocalAddress()));
}
break;
}
case COMMITTED : {
assert (_queue.size() != 0);
/*
* If ACK messages total more than majority we're happy otherwise try again.
*/
if (_messages.size() >= _detector.getMajority()) {
successful(Event.Reason.DECISION, null);
} else {
// Need another try, didn't get enough accepts but didn't get leader conflict
//
emit(new Success(_seqNum, _rndNumber,
_queue.get(0), _transport.getLocalAddress()));
}
break;
}
default : throw new RuntimeException("Invalid state: " + _state);
}
}
|
diff --git a/FinProj/src/tw/edu/ntu/fortour/LocMap.java b/FinProj/src/tw/edu/ntu/fortour/LocMap.java
index 6481709..59bbb64 100644
--- a/FinProj/src/tw/edu/ntu/fortour/LocMap.java
+++ b/FinProj/src/tw/edu/ntu/fortour/LocMap.java
@@ -1,458 +1,458 @@
package tw.edu.ntu.fortour;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
public class LocMap extends MapActivity {
private ProgressDialog mProgressDialog;
private Button mButtonLMOk, mButtonLMLocation, mButtonLMCancel, mButtonLMBack, mButtonLMHelp;
private TextView mTextViewLMLocation;
private MapView mMapView;
private Spinner mSpinner;
private MapController mMapController;
private GeoPoint mGeoPoint, mManualGeoPoint;
private MyLocationOverlay mMyLocationOverlay;
private String locLongitude, locLatitude, locName;
private List<Overlay> mMapOverlays;
private boolean hasLocation = false;
private boolean updateMode = false;
private boolean manualMode = false;
protected static String KEY_LATITUDE = "KEY_LATITUDE";
protected static String KEY_LONGITUDE = "KEY_LONGITUDE";
protected static String KEY_LOCNAME = "KEY_LOCNAME";
protected static String KEY_UPDMODE = "KEY_UPDMODE";
private final int ADDRESS_LIMIT = 5;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.loc_map);
/* check Internet first */
if( !Util.isOnline( getSystemService( Context.CONNECTIVITY_SERVICE ) ) ) {
Toast.makeText( LocMap.this, getString( R.string.stringNoInternetConnection ), Toast.LENGTH_LONG ).show();
}
Bundle b = this.getIntent().getExtras();
if( b != null ) {
locLatitude = b.getString( KEY_LATITUDE );
locLongitude = b.getString( KEY_LONGITUDE );
locName = b.getString( KEY_LOCNAME );
updateMode = b.getString( KEY_UPDMODE ) != null ? true : false;
if( locLatitude != null && locLongitude != null ) hasLocation = true;
}
mButtonLMHelp = (Button) findViewById( R.id.buttonLMHelp );
mButtonLMOk = (Button) findViewById( R.id.buttonLMOk );
mButtonLMLocation = (Button) findViewById( R.id.buttonLMDetermine );
mButtonLMCancel = (Button) findViewById( R.id.buttonLMCancel );
mButtonLMBack = (Button) findViewById( R.id.buttonLMBack );
mTextViewLMLocation= (TextView) findViewById( R.id.textViewLMLocation );
mMapView = (MapView) findViewById( R.id.mapView );
mSpinner = (Spinner) findViewById( R.id.spinnerLMList );
mProgressDialog = new ProgressDialog( LocMap.this );
mProgressDialog.setTitle( getString( R.string.stringLoading ) );
mProgressDialog.setMessage( getString( R.string.stringPleaseWait ) );
mProgressDialog.setCancelable( true );
mProgressDialog.setOnCancelListener( new OnCancelListener() {
@Override
public void onCancel(DialogInterface arg0) {
Toast.makeText( LocMap.this, getString( R.string.stringUnableToRetrieveLocationNow ), Toast.LENGTH_LONG ).show();
}
} );
mProgressDialog.show();
/* NOTE: DO NOT USE 'setStreetView( true )' or it may be a strange layout. */
mMapView.setClickable( true );
mMapView.setBuiltInZoomControls( true );
mMapView.displayZoomControls( true );
mMapOverlays = mMapView.getOverlays();
mMapOverlays.clear();
mMapController = mMapView.getController();
mMapController.setZoom( 17 );
mMyLocationOverlay = new MyLocationOverlay( LocMap.this, mMapView );
if( !hasLocation ) {
mMyLocationOverlay.enableCompass();
mMyLocationOverlay.enableMyLocation();
mMyLocationOverlay.runOnFirstFix( determinLocation );
}
else {
if( !updateMode ) {
mButtonLMHelp.setVisibility( View.GONE );
mButtonLMOk.setVisibility( View.GONE );
mButtonLMLocation.setVisibility( View.GONE );
mButtonLMCancel.setVisibility( View.GONE );
mButtonLMBack.setVisibility( View.VISIBLE );
if( !"".equals( locName ) ) {
mSpinner.setVisibility( View.GONE );
mTextViewLMLocation.setText( locName );
mTextViewLMLocation.setVisibility( View.VISIBLE );
}
}
determinLocation.run();
}
mMapOverlays.add( mMyLocationOverlay );
/* should after all variable initial */
setButtonListener();
}
Runnable addMarker = new Runnable() {
@Override
public void run() {
markerOverlay mLMOverlay = new markerOverlay( getResources().getDrawable( R.drawable.locate ) );
OverlayItem mOverlayItem = new OverlayItem( mGeoPoint, getString( R.string.stringLocation ), locName );
mLMOverlay.addMarker( mOverlayItem );
mMapOverlays.add( mLMOverlay );
}
};
Runnable determinLocation = new Runnable() {
@Override
public void run() {
if( !hasLocation ) mGeoPoint = mMyLocationOverlay.getMyLocation();
else mGeoPoint = new GeoPoint( Integer.valueOf( locLatitude ) , Integer.valueOf( locLongitude ) );
mMapController.animateTo( mGeoPoint, addMarker );
if( mProgressDialog != null ) mProgressDialog.dismiss();
// Translate location to location name
if( !hasLocation || ( hasLocation && updateMode ) ) runOnUiThread( getAddressList );
}
};
Runnable getAddressList = new Runnable() {
private ArrayAdapter<String> mArrayAdapter;
@Override
public void run() {
Geocoder mGeocoder = new Geocoder( LocMap.this, Locale.getDefault() );
mSpinner.setOnItemSelectedListener( new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> view, View arg1, int arg2, long arg3) {
locName = view.getSelectedItem().toString().trim();
}
@Override
public void onNothingSelected(AdapterView<?> arg0) { }
});
try {
List<Address> addressesList = null;
if( !manualMode ) addressesList = mGeocoder.getFromLocation( mGeoPoint.getLatitudeE6()/1E6, mGeoPoint.getLongitudeE6()/1E6, ADDRESS_LIMIT );
else addressesList = mGeocoder.getFromLocation( mManualGeoPoint.getLatitudeE6()/1E6, mManualGeoPoint.getLongitudeE6()/1E6, ADDRESS_LIMIT );
if( addressesList != null ) {
int selectPos = 0;
ArrayList<String> mArrayList = new ArrayList<String>();
for( int i = 0; i < addressesList.size(); i++ ) {
String addr = addressesList.get(i).getAddressLine(0).trim();
mArrayList.add( addr );
if( !manualMode && locName != null && addr.equals( locName ) ) selectPos = i;
}
mArrayAdapter = new ArrayAdapter<String>( LocMap.this, android.R.layout.simple_spinner_item, mArrayList );
mArrayAdapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item );
mSpinner.setAdapter( mArrayAdapter );
mSpinner.setSelection( selectPos );
if( !mSpinner.isEnabled() ) mSpinner.setEnabled( true );
}
}
catch( Exception e ) {
if( mArrayAdapter != null ) mArrayAdapter.clear();
mSpinner.setEnabled( false );
Toast.makeText( LocMap.this, getString( R.string.stringLocationList ) + ": " + e.getLocalizedMessage(), Toast.LENGTH_SHORT ).show();
}
}
};
private void setButtonListener() {
mButtonLMHelp.setOnClickListener( new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setClass( LocMap.this, LocMapInfo.class );
startActivity( intent );
overridePendingTransition( android.R.anim.fade_in, android.R.anim.fade_out );
}
} );
mButtonLMLocation.setOnClickListener( new OnClickListener() {
@Override
public void onClick(View v) {
manualMode = false;
mProgressDialog.show();
mMapOverlays.clear();
if( !hasLocation ) mMyLocationOverlay.runOnFirstFix( determinLocation );
else determinLocation.run();
mMapOverlays.add( mMyLocationOverlay );
}
} );
mButtonLMOk.setOnClickListener( new OnClickListener() {
@Override
public void onClick(View v) {
if( updateMode ) {
AlertDialog.Builder builder = new AlertDialog.Builder( LocMap.this );
builder.setTitle( R.string.stringSaveChanges );
builder.setMessage( R.string.stringDoYouWantToReplaceIt );
builder.setPositiveButton( android.R.string.yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
update();
}
} );
builder.setNegativeButton( android.R.string.no, null );
builder.show();
}
else update();
}
private void update() {
Intent i = new Intent();
Bundle b = new Bundle();
if( !hasLocation ) mGeoPoint = mMyLocationOverlay.getMyLocation();
else mGeoPoint = new GeoPoint( Integer.valueOf( locLatitude ) , Integer.valueOf( locLongitude ) );
if( manualMode && mManualGeoPoint != null ) mGeoPoint = mManualGeoPoint;
if( mGeoPoint != null ) {
b.putString( KEY_LATITUDE, Integer.toString( mGeoPoint.getLatitudeE6() ) );
b.putString( KEY_LONGITUDE, Integer.toString( mGeoPoint.getLongitudeE6() ) );
}
- if( !"".equals( locName ) ) b.putString( KEY_LOCNAME, locName.trim() );
+ if( locName!=null && !"".equals( locName ) ) b.putString( KEY_LOCNAME, locName.trim() );
i.putExtras( b );
setResult( Activity.RESULT_OK, i );
LocMap.this.finish();
}
} );
mButtonLMCancel.setOnClickListener( new OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder( LocMap.this );
builder.setTitle( R.string.stringDiscardChanges );
builder.setMessage( R.string.stringDoYouWantToDiscardIt );
builder.setPositiveButton( android.R.string.yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
LocMap.this.finish();
}
} );
builder.setNegativeButton( android.R.string.no, null );
builder.show();
}
} );
mButtonLMBack.setOnClickListener( new OnClickListener() {
@Override
public void onClick(View arg0) {
LocMap.this.finish();
}
} );
}
@Override
public void onBackPressed() {
/* NOTE: We don't allow user use back button in map view */
if( hasLocation && !updateMode ) super.onBackPressed();
}
@Override
protected void onResume() {
super.onResume();
if( !hasLocation && !mMyLocationOverlay.isMyLocationEnabled() ) mMyLocationOverlay.enableMyLocation();
}
@Override
protected void onPause() {
super.onPause();
if( !hasLocation && mMyLocationOverlay.isMyLocationEnabled() ) mMyLocationOverlay.disableMyLocation();
}
@Override
protected boolean isRouteDisplayed() {
return false;
}
class markerOverlay extends ItemizedOverlay<OverlayItem> {
private ArrayList<OverlayItem> mOverlayList = new ArrayList<OverlayItem>();
private OverlayItem mOverlayitemInDrag = null;
private Drawable mDrawableMarker = null;
private ImageView mImageViewDragImage = null;
private int xDragImageOffset = 0;
private int yDragImageOffset = 0;
private int xDragTouchOffset = 0;
private int yDragTouchOffset = 0;
public markerOverlay( Drawable defaultMarker ) {
super( boundCenterBottom( defaultMarker ) );
mDrawableMarker = defaultMarker;
mImageViewDragImage = (ImageView) findViewById( R.id.imageViewLMDrag );
xDragImageOffset = mImageViewDragImage.getDrawable().getIntrinsicWidth() / 2;
yDragImageOffset = mImageViewDragImage.getDrawable().getIntrinsicHeight();
}
private void addMarker( OverlayItem item ) {
mOverlayList.add( item );
populate();
}
@Override
protected OverlayItem createItem( int i ) {
return mOverlayList.get( i );
}
@Override
public int size() {
return mOverlayList.size();
}
@Override
public boolean onTouchEvent(MotionEvent event, MapView mapView) {
final int x = (int) event.getX();
final int y = (int) event.getY();
boolean result = false;
switch( event.getAction() ) {
case MotionEvent.ACTION_DOWN:
for( OverlayItem item : mOverlayList ) {
Point p = new Point(0,0);
mMapView.getProjection().toPixels( item.getPoint(), p );
if( ( !hasLocation || updateMode ) && hitTest( item, mDrawableMarker, x - p.x , y - p.y ) ) {
manualMode = true;
result = true;
mOverlayitemInDrag = item;
mOverlayList.remove( mOverlayitemInDrag );
populate();
xDragTouchOffset = 0;
yDragTouchOffset = 0;
setDragImagePosition( p.x, p.y );
mImageViewDragImage.setVisibility( View.VISIBLE );
xDragTouchOffset = x - p.x;
yDragTouchOffset = y - p.y;
break;
}
}
break;
case MotionEvent.ACTION_MOVE:
if( mOverlayitemInDrag != null ) {
setDragImagePosition( x, y );
result = true;
}
break;
case MotionEvent.ACTION_UP:
if( mOverlayitemInDrag != null ) {
mImageViewDragImage.setVisibility( View.GONE );
mManualGeoPoint = mMapView.getProjection().fromPixels( x - xDragTouchOffset, y - yDragTouchOffset );
mOverlayList.add( new OverlayItem( mManualGeoPoint,
mOverlayitemInDrag.getTitle(),
mOverlayitemInDrag.getSnippet() )
);
populate();
mOverlayitemInDrag = null;
result = true;
mMapController.animateTo( mManualGeoPoint, getAddressList );
}
break;
default:
break;
}
return ( result || super.onTouchEvent( event, mapView ) );
}
private void setDragImagePosition( int x, int y ) {
RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) mImageViewDragImage.getLayoutParams();
lp.setMargins( x - xDragImageOffset - xDragTouchOffset, y - yDragImageOffset - yDragTouchOffset, 0, 0 );
mImageViewDragImage.setLayoutParams( lp );
}
}
}
| true | true | private void setButtonListener() {
mButtonLMHelp.setOnClickListener( new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setClass( LocMap.this, LocMapInfo.class );
startActivity( intent );
overridePendingTransition( android.R.anim.fade_in, android.R.anim.fade_out );
}
} );
mButtonLMLocation.setOnClickListener( new OnClickListener() {
@Override
public void onClick(View v) {
manualMode = false;
mProgressDialog.show();
mMapOverlays.clear();
if( !hasLocation ) mMyLocationOverlay.runOnFirstFix( determinLocation );
else determinLocation.run();
mMapOverlays.add( mMyLocationOverlay );
}
} );
mButtonLMOk.setOnClickListener( new OnClickListener() {
@Override
public void onClick(View v) {
if( updateMode ) {
AlertDialog.Builder builder = new AlertDialog.Builder( LocMap.this );
builder.setTitle( R.string.stringSaveChanges );
builder.setMessage( R.string.stringDoYouWantToReplaceIt );
builder.setPositiveButton( android.R.string.yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
update();
}
} );
builder.setNegativeButton( android.R.string.no, null );
builder.show();
}
else update();
}
private void update() {
Intent i = new Intent();
Bundle b = new Bundle();
if( !hasLocation ) mGeoPoint = mMyLocationOverlay.getMyLocation();
else mGeoPoint = new GeoPoint( Integer.valueOf( locLatitude ) , Integer.valueOf( locLongitude ) );
if( manualMode && mManualGeoPoint != null ) mGeoPoint = mManualGeoPoint;
if( mGeoPoint != null ) {
b.putString( KEY_LATITUDE, Integer.toString( mGeoPoint.getLatitudeE6() ) );
b.putString( KEY_LONGITUDE, Integer.toString( mGeoPoint.getLongitudeE6() ) );
}
if( !"".equals( locName ) ) b.putString( KEY_LOCNAME, locName.trim() );
i.putExtras( b );
setResult( Activity.RESULT_OK, i );
LocMap.this.finish();
}
} );
mButtonLMCancel.setOnClickListener( new OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder( LocMap.this );
builder.setTitle( R.string.stringDiscardChanges );
builder.setMessage( R.string.stringDoYouWantToDiscardIt );
builder.setPositiveButton( android.R.string.yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
LocMap.this.finish();
}
} );
builder.setNegativeButton( android.R.string.no, null );
builder.show();
}
} );
mButtonLMBack.setOnClickListener( new OnClickListener() {
@Override
public void onClick(View arg0) {
LocMap.this.finish();
}
} );
}
| private void setButtonListener() {
mButtonLMHelp.setOnClickListener( new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setClass( LocMap.this, LocMapInfo.class );
startActivity( intent );
overridePendingTransition( android.R.anim.fade_in, android.R.anim.fade_out );
}
} );
mButtonLMLocation.setOnClickListener( new OnClickListener() {
@Override
public void onClick(View v) {
manualMode = false;
mProgressDialog.show();
mMapOverlays.clear();
if( !hasLocation ) mMyLocationOverlay.runOnFirstFix( determinLocation );
else determinLocation.run();
mMapOverlays.add( mMyLocationOverlay );
}
} );
mButtonLMOk.setOnClickListener( new OnClickListener() {
@Override
public void onClick(View v) {
if( updateMode ) {
AlertDialog.Builder builder = new AlertDialog.Builder( LocMap.this );
builder.setTitle( R.string.stringSaveChanges );
builder.setMessage( R.string.stringDoYouWantToReplaceIt );
builder.setPositiveButton( android.R.string.yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
update();
}
} );
builder.setNegativeButton( android.R.string.no, null );
builder.show();
}
else update();
}
private void update() {
Intent i = new Intent();
Bundle b = new Bundle();
if( !hasLocation ) mGeoPoint = mMyLocationOverlay.getMyLocation();
else mGeoPoint = new GeoPoint( Integer.valueOf( locLatitude ) , Integer.valueOf( locLongitude ) );
if( manualMode && mManualGeoPoint != null ) mGeoPoint = mManualGeoPoint;
if( mGeoPoint != null ) {
b.putString( KEY_LATITUDE, Integer.toString( mGeoPoint.getLatitudeE6() ) );
b.putString( KEY_LONGITUDE, Integer.toString( mGeoPoint.getLongitudeE6() ) );
}
if( locName!=null && !"".equals( locName ) ) b.putString( KEY_LOCNAME, locName.trim() );
i.putExtras( b );
setResult( Activity.RESULT_OK, i );
LocMap.this.finish();
}
} );
mButtonLMCancel.setOnClickListener( new OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder( LocMap.this );
builder.setTitle( R.string.stringDiscardChanges );
builder.setMessage( R.string.stringDoYouWantToDiscardIt );
builder.setPositiveButton( android.R.string.yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
LocMap.this.finish();
}
} );
builder.setNegativeButton( android.R.string.no, null );
builder.show();
}
} );
mButtonLMBack.setOnClickListener( new OnClickListener() {
@Override
public void onClick(View arg0) {
LocMap.this.finish();
}
} );
}
|
diff --git a/src/plugins/android.win32.x86/src/com/motorola/studio/android/nativeos/NativeUI.java b/src/plugins/android.win32.x86/src/com/motorola/studio/android/nativeos/NativeUI.java
index c70f3a5..f1780b9 100644
--- a/src/plugins/android.win32.x86/src/com/motorola/studio/android/nativeos/NativeUI.java
+++ b/src/plugins/android.win32.x86/src/com/motorola/studio/android/nativeos/NativeUI.java
@@ -1,200 +1,200 @@
/*
* Copyright (C) 2012 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.motorola.studio.android.nativeos;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.internal.win32.OS;
import org.eclipse.swt.internal.win32.RECT;
import org.eclipse.swt.internal.win32.TCHAR;
import org.eclipse.swt.widgets.Composite;
import com.motorola.studio.android.common.log.StudioLogger;
/***
* This class is responsible for provide WIN32 X86 specific constants values
* and implementation of INativeUI interface
*/
@SuppressWarnings("restriction")
public class NativeUI implements INativeUI
{
private static final int SWP_SHOWWINDOW = 0x0040;
String DEFAULT_COMMANDLINE = "";
String DEFAULT_USEVNC = "false";
/*
* (non-Javadoc)
* @see com.motorola.studio.android.nativeos.INativeUI#getDefaultCommandLine()
*/
public String getDefaultCommandLine()
{
return DEFAULT_COMMANDLINE;
}
/*
* (non-Javadoc)
* @see com.motorola.studio.android.nativeos.INativeUI#getDefaultUseVnc()
*/
public String getDefaultUseVnc()
{
return DEFAULT_USEVNC;
}
/*
* (non-Javadoc)
* @see com.motorola.studio.android.nativeos.INativeUI#getWindowHandle(java.lang.String)
*/
public long getWindowHandle(String windowName)
{
StudioLogger.debug(this, "Get native window handler for: " + windowName);
- int windowHandle = 0;
+ long windowHandle = 0;
try
{
TCHAR className = null;
TCHAR tChrTitle = new TCHAR(0, windowName, true);
windowHandle = OS.FindWindow(className, tChrTitle);
}
catch (Throwable t)
{
StudioLogger.error(this.getClass(), "Failed to retrieve window handler for window "
+ windowName, t);
}
return windowHandle;
}
/*
* (non-Javadoc)
* @see com.motorola.studio.android.nativeos.INativeUI#getWindowProperties(long)
*/
public long getWindowProperties(long windowHandle)
{
long windowLong = OS.GetWindowLong((int) windowHandle, OS.GWL_STYLE);
return windowLong;
}
/*
* (non-Javadoc)
* @see com.motorola.studio.android.nativeos.INativeUI#setWindowProperties(long, long)
*/
public void setWindowProperties(long windowHandle, long originalProperties)
{
OS.SetWindowLong((int) windowHandle, OS.GWL_STYLE, (int) originalProperties);
}
/*
* (non-Javadoc)
* @see com.motorola.studio.android.nativeos.INativeUI#embedWindow(long, org.eclipse.swt.widgets.Composite)
*/
public long embedWindow(long windowHandle, Composite composite)
{
// Set the position to fix an odd behavior in the Windows Classic Theme - the window goes off-screen and Emulator View stops working
OS.SetWindowPos((int) windowHandle, OS.HWND_TOP, 0, 0, 0, 0, SWP_SHOWWINDOW);
long originalParent = OS.SetParent((int) windowHandle, composite.handle);
return originalParent;
}
/*
* (non-Javadoc)
* @see com.motorola.studio.android.nativeos.INativeUI#unembedWindow(long, long)
*/
public void unembedWindow(long windowHandle, long originalParent)
{
OS.SetParent((int) windowHandle, (int) originalParent);
}
/*
* (non-Javadoc)
* @see com.motorola.studio.android.nativeos.INativeUI#getWindowSize(long, long)
*/
public Point getWindowSize(long originalParentHandle, long windowHandle)
{
RECT rect = new RECT();
OS.GetClientRect((int) windowHandle, rect);
return new Point(rect.right, rect.bottom);
}
/*
* (non-Javadoc)
* @see com.motorola.studio.android.nativeos.INativeUI#setWindowStyle(long)
*/
public void setWindowStyle(long windowHandle)
{
OS.SetWindowLong((int) windowHandle, OS.GWL_STYLE, OS.WS_VISIBLE | OS.WS_CLIPCHILDREN
| OS.WS_CLIPSIBLINGS);
}
/*
* (non-Javadoc)
* @see com.motorola.studio.android.nativeos.INativeUI#hideWindow(long)
*/
public void hideWindow(long windowHandle)
{
OS.ShowWindow((int) windowHandle, OS.SW_HIDE);
}
/*
* (non-Javadoc)
* @see com.motorola.studio.android.nativeos.INativeUI#showWindow(long)
*/
public void showWindow(long windowHandle)
{
OS.ShowWindow((int) windowHandle, OS.SW_SHOW);
}
/*
* (non-Javadoc)
* @see com.motorola.studio.android.nativeos.INativeUI#restoreWindow(long)
*/
public void restoreWindow(long windowHandle)
{
OS.ShowWindow((int) windowHandle, OS.SW_SHOWMINIMIZED);
OS.ShowWindow((int) windowHandle, OS.SW_RESTORE);
}
/*
* (non-Javadoc)
* @see com.motorola.studio.android.nativeos.INativeUI#sendNextLayoutCommand(long, long)
*/
public void sendNextLayoutCommand(long originalParent, long windowHandle)
{
OS.SendMessage((int) windowHandle, OS.WM_KEYDOWN, OS.VK_CONTROL, 0);
OS.SendMessage((int) windowHandle, OS.WM_KEYDOWN, OS.VK_F12, 0);
OS.SendMessage((int) windowHandle, OS.WM_KEYUP, OS.VK_CONTROL, 0);
OS.SendMessage((int) windowHandle, OS.WM_KEYUP, OS.VK_F12, 0);
}
/*
* (non-Javadoc)
* @see com.motorola.studio.android.nativeos.INativeUI#isWindowEnabled(long)
*/
public boolean isWindowEnabled(long windowHandle)
{
long getFocus = OS.GetForegroundWindow();
return windowHandle == getFocus;
}
/*
* (non-Javadoc)
* @see com.motorola.studio.android.nativeos.INativeUI#setWindowFocus(long)
*/
public void setWindowFocus(long windowHandle)
{
OS.SetForegroundWindow((int) windowHandle);
}
}
| true | true | public long getWindowHandle(String windowName)
{
StudioLogger.debug(this, "Get native window handler for: " + windowName);
int windowHandle = 0;
try
{
TCHAR className = null;
TCHAR tChrTitle = new TCHAR(0, windowName, true);
windowHandle = OS.FindWindow(className, tChrTitle);
}
catch (Throwable t)
{
StudioLogger.error(this.getClass(), "Failed to retrieve window handler for window "
+ windowName, t);
}
return windowHandle;
}
| public long getWindowHandle(String windowName)
{
StudioLogger.debug(this, "Get native window handler for: " + windowName);
long windowHandle = 0;
try
{
TCHAR className = null;
TCHAR tChrTitle = new TCHAR(0, windowName, true);
windowHandle = OS.FindWindow(className, tChrTitle);
}
catch (Throwable t)
{
StudioLogger.error(this.getClass(), "Failed to retrieve window handler for window "
+ windowName, t);
}
return windowHandle;
}
|
diff --git a/src/uk/co/ipodling/skeuosc/MainActivity.java b/src/uk/co/ipodling/skeuosc/MainActivity.java
index 852a103..4f0fdef 100644
--- a/src/uk/co/ipodling/skeuosc/MainActivity.java
+++ b/src/uk/co/ipodling/skeuosc/MainActivity.java
@@ -1,277 +1,277 @@
package uk.co.ipodling.skeuosc;
import java.net.SocketException;
import uk.co.ipodling.skeuosc.R;
import android.widget.Toast;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.util.Log;
import android.view.GestureDetector;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.Window;
/*
* Bugs:
* Moving slider is a bit hoopy
* firstX position for grid returns as 0 instead of 90, causes snapping to left of screen
* */
public class MainActivity extends Activity{
//this is so badly coded it's nearly funny, one does not simply
private GestureDetector gestureDetector;
Networking network;
DrawableView drawableView;
int index = 0;
private final static int START_DRAGGING = 0;
private final static int STOP_DRAGGING = 1;
private int status;
SkeuOSCPrefs prefs;//
GridSystem grid;
float width;
@Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE); //kinda not good way to do it if it takes a second to load but gets the job done
final java.lang.Object[] args = {"hello"};
prefs = new SkeuOSCPrefs(getApplicationContext());
grid = new GridSystem(getApplicationContext());
width = grid.getGridSize();
drawableView = new DrawableView(this);
drawableView.setBackgroundColor(Color.WHITE);
setContentView(drawableView);
super.onCreate(savedInstanceState);
try {
networkSetup(); // try to create socket
} catch (SocketException e1) {
Toast.makeText(MainActivity.this, "Network Error", Toast.LENGTH_SHORT).show();
e1.printStackTrace();
}
gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() { // crazy gesture detector of crazy
@Override
public boolean onDoubleTap(MotionEvent e) {
for(int i = 0; i < DrawableView.myButtonArray.size(); i++){ //tests is event was near position of a button or toggle in their arrays
if (e.getX() <= DrawableView.myButtonArray.get(i).getX()+width/2 && e.getX() >= DrawableView.myButtonArray.get(i).getX()-width/2 &&
e.getY()-150 <= DrawableView.myButtonArray.get(i).getY()+width/2 && e.getY()-150 >= DrawableView.myButtonArray.get(i).getY()-width/2){
Toast.makeText(MainActivity.this, "/button"+Integer.toString(i), Toast.LENGTH_LONG).show();
}
}
for(int i = 0; i < DrawableView.myToggleArray.size(); i++){
if (e.getX() <= DrawableView.myToggleArray.get(i).getX()+width/2 && e.getX() >= DrawableView.myToggleArray.get(i).getX()-width/2 &&
e.getY()-150 <= DrawableView.myToggleArray.get(i).getY()+width/2 && e.getY()-150 >= DrawableView.myToggleArray.get(i).getY()-width/2){
DrawableView.myToggleArray.get(i).setXY(0, 20);
Toast.makeText(MainActivity.this, "/toggle"+Integer.toString(i), Toast.LENGTH_LONG).show();
}
}
return true;
}
@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
if (e.getX() > DrawableView.screenWidth - 200 && e.getY()-150 < 100){
Intent i = new Intent(getApplicationContext(), MainMenu.class);
startActivity(i);
}
for(int i = 0; i < DrawableView.myButtonArray.size(); i++){
if (e.getX() <= DrawableView.myButtonArray.get(i).getX()+width/2 && e.getX() >= DrawableView.myButtonArray.get(i).getX()-width/2 &&
e.getY() <= DrawableView.myButtonArray.get(i).getY()+width/2 && e.getY() >= DrawableView.myButtonArray.get(i).getY()-width/2){
Log.d("event:", "button");
index = i;
try{
String host = prefs.getHost();
int port = prefs.getPort();
if(host.matches("") || port == 0){
Toast.makeText(MainActivity.this, "Please set host and port in settings", Toast.LENGTH_SHORT).show();// toasty
}else{
network.sendOSCMessage("/button"+Integer.toString(i), DrawableView.myButtonArray.get(i).getMessage()); //here send button message
}
}catch(Exception ex){
Log.d("Exception:", ex.toString());
}
}
}
for(int i = 0; i < DrawableView.myToggleArray.size(); i++){
if (e.getX() <= DrawableView.myToggleArray.get(i).getX()+width/2 && e.getX() >= DrawableView.myToggleArray.get(i).getX()-width/2 &&
e.getY() <= DrawableView.myToggleArray.get(i).getY()+width/2 && e.getY() >= DrawableView.myToggleArray.get(i).getY()-width/2){
Log.d("event:", "toggle");
index = i;
try{
String host = prefs.getHost();
int port = prefs.getPort();
if(host.matches("") || port == 0){
Toast.makeText(MainActivity.this, "Please set host and port in settings", Toast.LENGTH_SHORT).show();// toasty
}else{
network.sendOSCMessage("/toggle"+Integer.toString(i), DrawableView.myToggleArray.get(i).getMessage());
drawableView.invalidate();
}
}catch(Exception ex){
Log.d("Exception:", ex.toString());
}
}
}
drawableView.invalidate();
return true;
}
public void onLongPress(MotionEvent e) {
boolean button = false;
boolean toggle = false;
boolean slider = false;
for(int i = 0; i < DrawableView.myButtonArray.size(); i++){ //tests is event was near position of a button or toggle in their arrays
- if (e.getX() <= DrawableView.myButtonArray.get(i).getX()+50 && e.getX() >= DrawableView.myButtonArray.get(i).getX()-50 &&
- e.getY()-150 <= DrawableView.myButtonArray.get(i).getY()+50 && e.getY()-150 >= DrawableView.myButtonArray.get(i).getY()-50){
+ if (e.getX() <= DrawableView.myButtonArray.get(i).getX()+width && e.getX() >= DrawableView.myButtonArray.get(i).getX()-width &&
+ e.getY()-150 <= DrawableView.myButtonArray.get(i).getY()+width && e.getY()-150 >= DrawableView.myButtonArray.get(i).getY()-width){
button = true;
// Intent j = new Intent(getApplicationContext(), Inspector.class);
// startActivity(j);
}
}
for(int i = 0; i < DrawableView.myToggleArray.size(); i++){
- if (e.getX() <= DrawableView.myToggleArray.get(i).getX()+50 && e.getX() >= DrawableView.myToggleArray.get(i).getX()-50 &&
- e.getY()-150 <= DrawableView.myToggleArray.get(i).getY()+50 && e.getY()-150 >= DrawableView.myToggleArray.get(i).getY()-50){
+ if (e.getX() <= DrawableView.myToggleArray.get(i).getX()+width && e.getX() >= DrawableView.myToggleArray.get(i).getX()-width &&
+ e.getY()-150 <= DrawableView.myToggleArray.get(i).getY()+width && e.getY()-150 >= DrawableView.myToggleArray.get(i).getY()-width){
toggle = true;
// Intent j = new Intent(getApplicationContext(), Inspector.class);
// startActivity(j);
}
}
for(int i = 0; i < DrawableView.mySliderArray.size(); i++){
- if (e.getX() <= DrawableView.mySliderArray.get(i).getX()+50 && e.getX() >= DrawableView.mySliderArray.get(i).getX()-50 &&
- e.getY()-150 <= DrawableView.mySliderArray.get(i).getY()+75 && e.getY()-150 >= DrawableView.mySliderArray.get(i).getY()-75){
+ if (e.getX() <= DrawableView.mySliderArray.get(i).getX()+width*2 && e.getX() >= DrawableView.mySliderArray.get(i).getX()-width*2 &&
+ e.getY()-150 <= DrawableView.mySliderArray.get(i).getY()+width*2+width && e.getY()-150 >= DrawableView.mySliderArray.get(i).getY()-width*2+width){
slider = true;
// Intent j = new Intent(getApplicationContext(), Inspector.class);
// startActivity(j);
}
}
- if (button == false && toggle == false && slider == false) {
+ if (button == false && toggle == false) {
Intent j = new Intent(getApplicationContext(), AddItem.class);
startActivityForResult(j, 0);
}
drawableView.invalidate();
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onDown(MotionEvent e) {
drawableView.invalidate();
return false;
}
});
}//end of method brace
@Override
public boolean onTouchEvent(MotionEvent me){
if (me.getAction() == MotionEvent.ACTION_DOWN) {
status = START_DRAGGING;
}
if (me.getAction() == MotionEvent.ACTION_UP) {
status = STOP_DRAGGING;
for(int i = 0; i < DrawableView.myButtonArray.size(); i++){
if(DrawableView.myButtonArray.get(i).isMoving()){
DrawableView.myButtonArray.get(i).placeWithCoords(me.getX(), me.getY());
}
}
for(int i = 0; i < DrawableView.myToggleArray.size(); i++){
if(DrawableView.myToggleArray.get(i).isMoving()){
DrawableView.myToggleArray.get(i).placeWithCoords(me.getX(), me.getY());
}
}
for(int i = 0; i < DrawableView.mySliderArray.size(); i++){
if(DrawableView.mySliderArray.get(i).isMoving()){
DrawableView.mySliderArray.get(i).placeWithCoords(me.getX(), me.getY());
}
}
Log.i("Drag", "Stopped Dragging");
} else if (me.getAction() == MotionEvent.ACTION_MOVE) {
if (status == START_DRAGGING) {
for(int i = 0; i < DrawableView.myButtonArray.size(); i++){
if (me.getX() <= DrawableView.myButtonArray.get(i).getX()+width/2 && me.getX() >= DrawableView.myButtonArray.get(i).getX()-width/2 &&(
me.getY() <= DrawableView.myButtonArray.get(i).getY()+width/2 && me.getY() >= DrawableView.myButtonArray.get(i).getY()-width/2))
{
DrawableView.myButtonArray.get(i).move(me.getX(), me.getY(), true); //move stuff
}
}
for(int i = 0; i < DrawableView.myToggleArray.size(); i++){
if (me.getX() <= DrawableView.myToggleArray.get(i).getX()+width/2 && me.getX() >= DrawableView.myToggleArray.get(i).getX()-width/2 &&
me.getY() <= DrawableView.myToggleArray.get(i).getY()+width/2 && me.getY() >= DrawableView.myToggleArray.get(i).getY()-width/2){
DrawableView.myToggleArray.get(i).move(me.getX(), me.getY(), true);
}
}
for(int i = 0; i < DrawableView.mySliderArray.size(); i++){
if (me.getX() <= DrawableView.mySliderArray.get(i).getX()+width/2 && me.getX() >= DrawableView.mySliderArray.get(i).getX()-width/2 &&
(me.getY() <= DrawableView.mySliderArray.get(i).getY()+width && me.getY() >= DrawableView.mySliderArray.get(i).getY()-width)){
if(me.getX()>= DrawableView.mySliderArray.get(i).getX()-width/2+30 && me.getX()<= DrawableView.mySliderArray.get(i).getX()+width/2-30){
DrawableView.mySliderArray.get(i).setY(me.getX(), me.getY());
try{
String host = prefs.getHost();
int port = prefs.getPort();
if(host.matches("") || port == 0){
Toast.makeText(MainActivity.this, "Please set host and port in settings", Toast.LENGTH_SHORT).show();// toasty
}else{
network.sendOSCMessage("/slider"+Integer.toString(i), DrawableView.mySliderArray.get(i).getMessage());
drawableView.invalidate();
}
}catch(Exception ex){
Log.d("Exception:", ex.toString());
}
}else{
DrawableView.mySliderArray.get(i).move(me.getX(), me.getY(), true);
}
}
}
drawableView.invalidate();
}
}
if (!gestureDetector.onTouchEvent(me))
return super.onTouchEvent(me);
return true;
// return gestureScanner.onTouchEvent(me);
} // here be gesture stuff
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void networkSetup() throws SocketException{
network = new Networking(getApplicationContext());
if(prefs.isItThere("host") == true && prefs.isItThere("port") == true){
network.updateHost(prefs.getHost(), prefs.getPort());
}else{
Toast.makeText(MainActivity.this, "Please open setup and specify host and port", Toast.LENGTH_SHORT).show();
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 0) {
if(resultCode == RESULT_OK){
if(prefs.isItThere("button") == true){
if(prefs.getBoolean("button") == true){
DrawableView.myButtonArray.add(new MyButton(getApplicationContext(), width-30));
prefs.putBoolean("button", false);
}
}
if(prefs.isItThere("toggle") == true){
if(prefs.getBoolean("toggle") == true){
DrawableView.myToggleArray.add(new MyToggle(getApplicationContext(), width-30));
prefs.putBoolean("toggle", false);
}
}
if(prefs.isItThere("slider") == true){
if(prefs.getBoolean("slider") == true){
DrawableView.mySliderArray.add(new MySlider(getApplicationContext(), width-30));
prefs.putBoolean("slider", false);
}
}
}
}
}
}
| false | true | protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE); //kinda not good way to do it if it takes a second to load but gets the job done
final java.lang.Object[] args = {"hello"};
prefs = new SkeuOSCPrefs(getApplicationContext());
grid = new GridSystem(getApplicationContext());
width = grid.getGridSize();
drawableView = new DrawableView(this);
drawableView.setBackgroundColor(Color.WHITE);
setContentView(drawableView);
super.onCreate(savedInstanceState);
try {
networkSetup(); // try to create socket
} catch (SocketException e1) {
Toast.makeText(MainActivity.this, "Network Error", Toast.LENGTH_SHORT).show();
e1.printStackTrace();
}
gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() { // crazy gesture detector of crazy
@Override
public boolean onDoubleTap(MotionEvent e) {
for(int i = 0; i < DrawableView.myButtonArray.size(); i++){ //tests is event was near position of a button or toggle in their arrays
if (e.getX() <= DrawableView.myButtonArray.get(i).getX()+width/2 && e.getX() >= DrawableView.myButtonArray.get(i).getX()-width/2 &&
e.getY()-150 <= DrawableView.myButtonArray.get(i).getY()+width/2 && e.getY()-150 >= DrawableView.myButtonArray.get(i).getY()-width/2){
Toast.makeText(MainActivity.this, "/button"+Integer.toString(i), Toast.LENGTH_LONG).show();
}
}
for(int i = 0; i < DrawableView.myToggleArray.size(); i++){
if (e.getX() <= DrawableView.myToggleArray.get(i).getX()+width/2 && e.getX() >= DrawableView.myToggleArray.get(i).getX()-width/2 &&
e.getY()-150 <= DrawableView.myToggleArray.get(i).getY()+width/2 && e.getY()-150 >= DrawableView.myToggleArray.get(i).getY()-width/2){
DrawableView.myToggleArray.get(i).setXY(0, 20);
Toast.makeText(MainActivity.this, "/toggle"+Integer.toString(i), Toast.LENGTH_LONG).show();
}
}
return true;
}
@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
if (e.getX() > DrawableView.screenWidth - 200 && e.getY()-150 < 100){
Intent i = new Intent(getApplicationContext(), MainMenu.class);
startActivity(i);
}
for(int i = 0; i < DrawableView.myButtonArray.size(); i++){
if (e.getX() <= DrawableView.myButtonArray.get(i).getX()+width/2 && e.getX() >= DrawableView.myButtonArray.get(i).getX()-width/2 &&
e.getY() <= DrawableView.myButtonArray.get(i).getY()+width/2 && e.getY() >= DrawableView.myButtonArray.get(i).getY()-width/2){
Log.d("event:", "button");
index = i;
try{
String host = prefs.getHost();
int port = prefs.getPort();
if(host.matches("") || port == 0){
Toast.makeText(MainActivity.this, "Please set host and port in settings", Toast.LENGTH_SHORT).show();// toasty
}else{
network.sendOSCMessage("/button"+Integer.toString(i), DrawableView.myButtonArray.get(i).getMessage()); //here send button message
}
}catch(Exception ex){
Log.d("Exception:", ex.toString());
}
}
}
for(int i = 0; i < DrawableView.myToggleArray.size(); i++){
if (e.getX() <= DrawableView.myToggleArray.get(i).getX()+width/2 && e.getX() >= DrawableView.myToggleArray.get(i).getX()-width/2 &&
e.getY() <= DrawableView.myToggleArray.get(i).getY()+width/2 && e.getY() >= DrawableView.myToggleArray.get(i).getY()-width/2){
Log.d("event:", "toggle");
index = i;
try{
String host = prefs.getHost();
int port = prefs.getPort();
if(host.matches("") || port == 0){
Toast.makeText(MainActivity.this, "Please set host and port in settings", Toast.LENGTH_SHORT).show();// toasty
}else{
network.sendOSCMessage("/toggle"+Integer.toString(i), DrawableView.myToggleArray.get(i).getMessage());
drawableView.invalidate();
}
}catch(Exception ex){
Log.d("Exception:", ex.toString());
}
}
}
drawableView.invalidate();
return true;
}
public void onLongPress(MotionEvent e) {
boolean button = false;
boolean toggle = false;
boolean slider = false;
for(int i = 0; i < DrawableView.myButtonArray.size(); i++){ //tests is event was near position of a button or toggle in their arrays
if (e.getX() <= DrawableView.myButtonArray.get(i).getX()+50 && e.getX() >= DrawableView.myButtonArray.get(i).getX()-50 &&
e.getY()-150 <= DrawableView.myButtonArray.get(i).getY()+50 && e.getY()-150 >= DrawableView.myButtonArray.get(i).getY()-50){
button = true;
// Intent j = new Intent(getApplicationContext(), Inspector.class);
// startActivity(j);
}
}
for(int i = 0; i < DrawableView.myToggleArray.size(); i++){
if (e.getX() <= DrawableView.myToggleArray.get(i).getX()+50 && e.getX() >= DrawableView.myToggleArray.get(i).getX()-50 &&
e.getY()-150 <= DrawableView.myToggleArray.get(i).getY()+50 && e.getY()-150 >= DrawableView.myToggleArray.get(i).getY()-50){
toggle = true;
// Intent j = new Intent(getApplicationContext(), Inspector.class);
// startActivity(j);
}
}
for(int i = 0; i < DrawableView.mySliderArray.size(); i++){
if (e.getX() <= DrawableView.mySliderArray.get(i).getX()+50 && e.getX() >= DrawableView.mySliderArray.get(i).getX()-50 &&
e.getY()-150 <= DrawableView.mySliderArray.get(i).getY()+75 && e.getY()-150 >= DrawableView.mySliderArray.get(i).getY()-75){
slider = true;
// Intent j = new Intent(getApplicationContext(), Inspector.class);
// startActivity(j);
}
}
if (button == false && toggle == false && slider == false) {
Intent j = new Intent(getApplicationContext(), AddItem.class);
startActivityForResult(j, 0);
}
drawableView.invalidate();
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onDown(MotionEvent e) {
drawableView.invalidate();
return false;
}
});
}//end of method brace
| protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE); //kinda not good way to do it if it takes a second to load but gets the job done
final java.lang.Object[] args = {"hello"};
prefs = new SkeuOSCPrefs(getApplicationContext());
grid = new GridSystem(getApplicationContext());
width = grid.getGridSize();
drawableView = new DrawableView(this);
drawableView.setBackgroundColor(Color.WHITE);
setContentView(drawableView);
super.onCreate(savedInstanceState);
try {
networkSetup(); // try to create socket
} catch (SocketException e1) {
Toast.makeText(MainActivity.this, "Network Error", Toast.LENGTH_SHORT).show();
e1.printStackTrace();
}
gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() { // crazy gesture detector of crazy
@Override
public boolean onDoubleTap(MotionEvent e) {
for(int i = 0; i < DrawableView.myButtonArray.size(); i++){ //tests is event was near position of a button or toggle in their arrays
if (e.getX() <= DrawableView.myButtonArray.get(i).getX()+width/2 && e.getX() >= DrawableView.myButtonArray.get(i).getX()-width/2 &&
e.getY()-150 <= DrawableView.myButtonArray.get(i).getY()+width/2 && e.getY()-150 >= DrawableView.myButtonArray.get(i).getY()-width/2){
Toast.makeText(MainActivity.this, "/button"+Integer.toString(i), Toast.LENGTH_LONG).show();
}
}
for(int i = 0; i < DrawableView.myToggleArray.size(); i++){
if (e.getX() <= DrawableView.myToggleArray.get(i).getX()+width/2 && e.getX() >= DrawableView.myToggleArray.get(i).getX()-width/2 &&
e.getY()-150 <= DrawableView.myToggleArray.get(i).getY()+width/2 && e.getY()-150 >= DrawableView.myToggleArray.get(i).getY()-width/2){
DrawableView.myToggleArray.get(i).setXY(0, 20);
Toast.makeText(MainActivity.this, "/toggle"+Integer.toString(i), Toast.LENGTH_LONG).show();
}
}
return true;
}
@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
if (e.getX() > DrawableView.screenWidth - 200 && e.getY()-150 < 100){
Intent i = new Intent(getApplicationContext(), MainMenu.class);
startActivity(i);
}
for(int i = 0; i < DrawableView.myButtonArray.size(); i++){
if (e.getX() <= DrawableView.myButtonArray.get(i).getX()+width/2 && e.getX() >= DrawableView.myButtonArray.get(i).getX()-width/2 &&
e.getY() <= DrawableView.myButtonArray.get(i).getY()+width/2 && e.getY() >= DrawableView.myButtonArray.get(i).getY()-width/2){
Log.d("event:", "button");
index = i;
try{
String host = prefs.getHost();
int port = prefs.getPort();
if(host.matches("") || port == 0){
Toast.makeText(MainActivity.this, "Please set host and port in settings", Toast.LENGTH_SHORT).show();// toasty
}else{
network.sendOSCMessage("/button"+Integer.toString(i), DrawableView.myButtonArray.get(i).getMessage()); //here send button message
}
}catch(Exception ex){
Log.d("Exception:", ex.toString());
}
}
}
for(int i = 0; i < DrawableView.myToggleArray.size(); i++){
if (e.getX() <= DrawableView.myToggleArray.get(i).getX()+width/2 && e.getX() >= DrawableView.myToggleArray.get(i).getX()-width/2 &&
e.getY() <= DrawableView.myToggleArray.get(i).getY()+width/2 && e.getY() >= DrawableView.myToggleArray.get(i).getY()-width/2){
Log.d("event:", "toggle");
index = i;
try{
String host = prefs.getHost();
int port = prefs.getPort();
if(host.matches("") || port == 0){
Toast.makeText(MainActivity.this, "Please set host and port in settings", Toast.LENGTH_SHORT).show();// toasty
}else{
network.sendOSCMessage("/toggle"+Integer.toString(i), DrawableView.myToggleArray.get(i).getMessage());
drawableView.invalidate();
}
}catch(Exception ex){
Log.d("Exception:", ex.toString());
}
}
}
drawableView.invalidate();
return true;
}
public void onLongPress(MotionEvent e) {
boolean button = false;
boolean toggle = false;
boolean slider = false;
for(int i = 0; i < DrawableView.myButtonArray.size(); i++){ //tests is event was near position of a button or toggle in their arrays
if (e.getX() <= DrawableView.myButtonArray.get(i).getX()+width && e.getX() >= DrawableView.myButtonArray.get(i).getX()-width &&
e.getY()-150 <= DrawableView.myButtonArray.get(i).getY()+width && e.getY()-150 >= DrawableView.myButtonArray.get(i).getY()-width){
button = true;
// Intent j = new Intent(getApplicationContext(), Inspector.class);
// startActivity(j);
}
}
for(int i = 0; i < DrawableView.myToggleArray.size(); i++){
if (e.getX() <= DrawableView.myToggleArray.get(i).getX()+width && e.getX() >= DrawableView.myToggleArray.get(i).getX()-width &&
e.getY()-150 <= DrawableView.myToggleArray.get(i).getY()+width && e.getY()-150 >= DrawableView.myToggleArray.get(i).getY()-width){
toggle = true;
// Intent j = new Intent(getApplicationContext(), Inspector.class);
// startActivity(j);
}
}
for(int i = 0; i < DrawableView.mySliderArray.size(); i++){
if (e.getX() <= DrawableView.mySliderArray.get(i).getX()+width*2 && e.getX() >= DrawableView.mySliderArray.get(i).getX()-width*2 &&
e.getY()-150 <= DrawableView.mySliderArray.get(i).getY()+width*2+width && e.getY()-150 >= DrawableView.mySliderArray.get(i).getY()-width*2+width){
slider = true;
// Intent j = new Intent(getApplicationContext(), Inspector.class);
// startActivity(j);
}
}
if (button == false && toggle == false) {
Intent j = new Intent(getApplicationContext(), AddItem.class);
startActivityForResult(j, 0);
}
drawableView.invalidate();
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onDown(MotionEvent e) {
drawableView.invalidate();
return false;
}
});
}//end of method brace
|
diff --git a/sahi/src/main/java/com/redhat/qe/jon/sahi/base/inventory/Operations.java b/sahi/src/main/java/com/redhat/qe/jon/sahi/base/inventory/Operations.java
index cc0f54fd..dc9320fd 100644
--- a/sahi/src/main/java/com/redhat/qe/jon/sahi/base/inventory/Operations.java
+++ b/sahi/src/main/java/com/redhat/qe/jon/sahi/base/inventory/Operations.java
@@ -1,198 +1,198 @@
package com.redhat.qe.jon.sahi.base.inventory;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import net.sf.sahi.client.ElementStub;
import org.testng.Assert;
import com.redhat.qe.jon.sahi.base.editor.Editor;
import com.redhat.qe.jon.sahi.tasks.SahiTasks;
import com.redhat.qe.jon.sahi.tasks.Timing;
/**
* represents <b>Operations</b> Tab of given resource.
* Creating instance of this class will navigate to resource and select <b>Operations</b> Tab
*
* @author lzoubek
*/
public class Operations extends ResourceTab {
public Operations(SahiTasks tasks, Resource resource) {
super(tasks, resource);
}
@Override
protected void navigate() {
navigateUnderResource("Operations/Schedules");
raiseErrorIfCellDoesNotExist("Operations");
}
/**
* Creates new Operation of given name, also selects it in <b>Operation:</b> combo
*
* @param name of new Operation
* @return new operation
*/
public Operation newOperation(String name) {
tasks.cell("New").click();
return new Operation(tasks, name);
}
/**
* asserts operation result, waits until operation is either success or failure.
*
* @param op operation
* @param success if true, success is expected, otherwise failure is expected
* @return result map returned by this operation if operation succeeded, otherwise null.
* In this map, keys are result properties and values are result values
*/
public Map<String, String> assertOperationResult(Operation op, boolean success) {
String opName = op.name;
String resultImage = "Operation_failed_16.png";
String succ = "Failed";
if (success) {
resultImage = "Operation_ok_16.png";
succ = "Success";
}
log.fine("Asserting operation [" + opName + "] result, expecting " + succ);
getResource().summary();
int timeout = 20 * Timing.TIME_1M;
int time = 0;
while (time < timeout && tasks.image("Operation_inprogress_16.png").in(tasks.div(opName + "[0]").parentNode("tr")).exists()) {
time += Timing.TIME_10S;
log.fine("Operation [" + opName + "] in progress, waiting " + Timing.toString(Timing.TIME_10S));
tasks.waitFor(Timing.TIME_10S);
getResource().summary();
}
if (tasks.image("Operation_inprogress_16.png").in(tasks.div(opName + "[0]").parentNode("tr")).exists()) {
log.info("Operation [" + opName + "] did NOT finish after " + Timing.toString(time) + "!!!");
Assert.assertEquals(!success, success, "Operation [" + opName + "] result: " + succ);
} else {
log.info("Operation [" + opName + "] finished after " + Timing.toString(time));
}
boolean existsImage = tasks.image(resultImage).in(tasks.div(opName + "[0]").parentNode("tr")).exists();
// when operation failed and success was expected, let's get operation error message
if (!existsImage && success) {
log.info("Retrieving the error message as it was expected that operation ends successfully but it didn't");
String message = null;
tasks.xy(tasks.image("Operation_failed_16.png").in(tasks.div(opName + "[0]").parentNode("tr")), 3, 3).click();
if (tasks.preformatted("").exists()) {
message = tasks.preformatted("").getText();
}
tasks.waitFor(Timing.WAIT_TIME);
int buttons = tasks.image("close.png").countSimilar();
tasks.xy(tasks.image("close.png[" + (buttons - 1) + "]"), 3, 3).click();
if (message != null) {
Assert.assertTrue(existsImage, "Operation [" + opName + "] result: " + succ + " errorMessage:\n" + message);
return null;
}
}
Assert.assertTrue(existsImage, "Operation [" + opName + "] result: " + succ);
log.fine("Getting operation result");
- tasks.image(resultImage).in(tasks.div(opName + "[0]").parentNode("tr")).doubleClick();
+ tasks.xy(tasks.image(resultImage).in(tasks.div(opName + "[0]").parentNode("tr")), 3, 3).doubleClick();
log.finer("Waiting " + Timing.toString(Timing.WAIT_TIME) + " for loading results of the operation");
tasks.waitFor(Timing.WAIT_TIME);
log.finest("The property element: " + tasks.cell("Property").fetch());
List<ElementStub> headerCells = tasks.cell("Property").collectSimilar();
for (ElementStub el : headerCells) {
log.finest(el.fetch());
}
if (headerCells.size() > 1) {
Map<String, String> result = new HashMap<String, String>();
ElementStub table = headerCells.get(headerCells.size() - 1).parentNode("table");
log.finer("Table element is " + table.toString());
List<ElementStub> rows = tasks.row("").in(table).collectSimilar();
// starting with 3rd row, because 1st some shit and 2nd is table header
// we also ignore last because sahi was failing
log.fine("Have " + (rows.size() - 3) + " result rows");
log.finest("The rows are: " + rows.toString());
for (int i = 2; i < rows.size(); i++) {
ElementStub row = rows.get(i);
ElementStub key = tasks.cell(0).in(row);
ElementStub value = tasks.cell(2).in(row);
if (key.exists() && value.exists()) {
log.fine("Found result property [" + key.getText() + "]");
result.put(key.getText(), value.getText());
} else {
log.warning("Missing key or value column in the results table - probably caused by nonstandard result output");
}
}
return result;
}
log.fine("Result table not found");
return null;
}
public static class Operation {
private final SahiTasks tasks;
private final String name;
private final Editor editor;
private final Logger log = Logger.getLogger(this.getClass().getName());
public Operation(SahiTasks tasks, String name) {
this.tasks = tasks;
this.name = name;
this.editor = new Editor(tasks);
tasks.waitFor(Timing.WAIT_TIME);
selectOperation(this.name);
}
public void selectOperation(String op) {
List<ElementStub> pickers = tasks.image("comboBoxPicker.png").collectSimilar();
log.fine("Found " + pickers.size() + " comboboxes");
for (ElementStub picker : pickers) {
if (picker.isVisible()) {
log.fine("Clicking on " + picker.parentNode().fetch("innerHTML"));
tasks.xy(picker.parentNode(), 3, 3).click();
ElementStub operation = tasks.row(op);
if (operation.exists()) {
tasks.xy(operation, 3, 3).click();
log.fine("Selected operation [" + op + "].");
return;
} else {
log.fine("Trying workaround with focused picker");
ElementStub focused = tasks.image("comboBoxPicker_Over.png");
if (focused.isVisible()) {
log.fine("Focused picker was visible, clicking...");
tasks.xy(focused, 3, 3).click();
operation = tasks.row(op);
if (operation.exists()) {
tasks.xy(operation, 3, 3).click();
log.fine("Selected operation [" + op + "].");
return;
}
}
}
}
}
throw new RuntimeException("Unable to select operation [" + op + "] clicked on each visible combo, but operation did NOT pop up");
}
/**
* asserts all required input fields have been filled
*/
public void assertRequiredInputs() {
getEditor().assertRequiredInputs();
}
public Editor getEditor() {
return editor;
}
/**
* clicks <b>Schedule</b> button to start operation
*/
public void schedule() {
tasks.cell("Schedule").click();
tasks.waitFor(Timing.WAIT_TIME);
}
}
}
| true | true | public Map<String, String> assertOperationResult(Operation op, boolean success) {
String opName = op.name;
String resultImage = "Operation_failed_16.png";
String succ = "Failed";
if (success) {
resultImage = "Operation_ok_16.png";
succ = "Success";
}
log.fine("Asserting operation [" + opName + "] result, expecting " + succ);
getResource().summary();
int timeout = 20 * Timing.TIME_1M;
int time = 0;
while (time < timeout && tasks.image("Operation_inprogress_16.png").in(tasks.div(opName + "[0]").parentNode("tr")).exists()) {
time += Timing.TIME_10S;
log.fine("Operation [" + opName + "] in progress, waiting " + Timing.toString(Timing.TIME_10S));
tasks.waitFor(Timing.TIME_10S);
getResource().summary();
}
if (tasks.image("Operation_inprogress_16.png").in(tasks.div(opName + "[0]").parentNode("tr")).exists()) {
log.info("Operation [" + opName + "] did NOT finish after " + Timing.toString(time) + "!!!");
Assert.assertEquals(!success, success, "Operation [" + opName + "] result: " + succ);
} else {
log.info("Operation [" + opName + "] finished after " + Timing.toString(time));
}
boolean existsImage = tasks.image(resultImage).in(tasks.div(opName + "[0]").parentNode("tr")).exists();
// when operation failed and success was expected, let's get operation error message
if (!existsImage && success) {
log.info("Retrieving the error message as it was expected that operation ends successfully but it didn't");
String message = null;
tasks.xy(tasks.image("Operation_failed_16.png").in(tasks.div(opName + "[0]").parentNode("tr")), 3, 3).click();
if (tasks.preformatted("").exists()) {
message = tasks.preformatted("").getText();
}
tasks.waitFor(Timing.WAIT_TIME);
int buttons = tasks.image("close.png").countSimilar();
tasks.xy(tasks.image("close.png[" + (buttons - 1) + "]"), 3, 3).click();
if (message != null) {
Assert.assertTrue(existsImage, "Operation [" + opName + "] result: " + succ + " errorMessage:\n" + message);
return null;
}
}
Assert.assertTrue(existsImage, "Operation [" + opName + "] result: " + succ);
log.fine("Getting operation result");
tasks.image(resultImage).in(tasks.div(opName + "[0]").parentNode("tr")).doubleClick();
log.finer("Waiting " + Timing.toString(Timing.WAIT_TIME) + " for loading results of the operation");
tasks.waitFor(Timing.WAIT_TIME);
log.finest("The property element: " + tasks.cell("Property").fetch());
List<ElementStub> headerCells = tasks.cell("Property").collectSimilar();
for (ElementStub el : headerCells) {
log.finest(el.fetch());
}
if (headerCells.size() > 1) {
Map<String, String> result = new HashMap<String, String>();
ElementStub table = headerCells.get(headerCells.size() - 1).parentNode("table");
log.finer("Table element is " + table.toString());
List<ElementStub> rows = tasks.row("").in(table).collectSimilar();
// starting with 3rd row, because 1st some shit and 2nd is table header
// we also ignore last because sahi was failing
log.fine("Have " + (rows.size() - 3) + " result rows");
log.finest("The rows are: " + rows.toString());
for (int i = 2; i < rows.size(); i++) {
ElementStub row = rows.get(i);
ElementStub key = tasks.cell(0).in(row);
ElementStub value = tasks.cell(2).in(row);
if (key.exists() && value.exists()) {
log.fine("Found result property [" + key.getText() + "]");
result.put(key.getText(), value.getText());
} else {
log.warning("Missing key or value column in the results table - probably caused by nonstandard result output");
}
}
return result;
}
log.fine("Result table not found");
return null;
}
| public Map<String, String> assertOperationResult(Operation op, boolean success) {
String opName = op.name;
String resultImage = "Operation_failed_16.png";
String succ = "Failed";
if (success) {
resultImage = "Operation_ok_16.png";
succ = "Success";
}
log.fine("Asserting operation [" + opName + "] result, expecting " + succ);
getResource().summary();
int timeout = 20 * Timing.TIME_1M;
int time = 0;
while (time < timeout && tasks.image("Operation_inprogress_16.png").in(tasks.div(opName + "[0]").parentNode("tr")).exists()) {
time += Timing.TIME_10S;
log.fine("Operation [" + opName + "] in progress, waiting " + Timing.toString(Timing.TIME_10S));
tasks.waitFor(Timing.TIME_10S);
getResource().summary();
}
if (tasks.image("Operation_inprogress_16.png").in(tasks.div(opName + "[0]").parentNode("tr")).exists()) {
log.info("Operation [" + opName + "] did NOT finish after " + Timing.toString(time) + "!!!");
Assert.assertEquals(!success, success, "Operation [" + opName + "] result: " + succ);
} else {
log.info("Operation [" + opName + "] finished after " + Timing.toString(time));
}
boolean existsImage = tasks.image(resultImage).in(tasks.div(opName + "[0]").parentNode("tr")).exists();
// when operation failed and success was expected, let's get operation error message
if (!existsImage && success) {
log.info("Retrieving the error message as it was expected that operation ends successfully but it didn't");
String message = null;
tasks.xy(tasks.image("Operation_failed_16.png").in(tasks.div(opName + "[0]").parentNode("tr")), 3, 3).click();
if (tasks.preformatted("").exists()) {
message = tasks.preformatted("").getText();
}
tasks.waitFor(Timing.WAIT_TIME);
int buttons = tasks.image("close.png").countSimilar();
tasks.xy(tasks.image("close.png[" + (buttons - 1) + "]"), 3, 3).click();
if (message != null) {
Assert.assertTrue(existsImage, "Operation [" + opName + "] result: " + succ + " errorMessage:\n" + message);
return null;
}
}
Assert.assertTrue(existsImage, "Operation [" + opName + "] result: " + succ);
log.fine("Getting operation result");
tasks.xy(tasks.image(resultImage).in(tasks.div(opName + "[0]").parentNode("tr")), 3, 3).doubleClick();
log.finer("Waiting " + Timing.toString(Timing.WAIT_TIME) + " for loading results of the operation");
tasks.waitFor(Timing.WAIT_TIME);
log.finest("The property element: " + tasks.cell("Property").fetch());
List<ElementStub> headerCells = tasks.cell("Property").collectSimilar();
for (ElementStub el : headerCells) {
log.finest(el.fetch());
}
if (headerCells.size() > 1) {
Map<String, String> result = new HashMap<String, String>();
ElementStub table = headerCells.get(headerCells.size() - 1).parentNode("table");
log.finer("Table element is " + table.toString());
List<ElementStub> rows = tasks.row("").in(table).collectSimilar();
// starting with 3rd row, because 1st some shit and 2nd is table header
// we also ignore last because sahi was failing
log.fine("Have " + (rows.size() - 3) + " result rows");
log.finest("The rows are: " + rows.toString());
for (int i = 2; i < rows.size(); i++) {
ElementStub row = rows.get(i);
ElementStub key = tasks.cell(0).in(row);
ElementStub value = tasks.cell(2).in(row);
if (key.exists() && value.exists()) {
log.fine("Found result property [" + key.getText() + "]");
result.put(key.getText(), value.getText());
} else {
log.warning("Missing key or value column in the results table - probably caused by nonstandard result output");
}
}
return result;
}
log.fine("Result table not found");
return null;
}
|
diff --git a/org.osate.imv.aadldiagram/src/org/osate/imv/aadldiagram/util/ErrorUtil.java b/org.osate.imv.aadldiagram/src/org/osate/imv/aadldiagram/util/ErrorUtil.java
index a8b985e..9faaf2b 100644
--- a/org.osate.imv.aadldiagram/src/org/osate/imv/aadldiagram/util/ErrorUtil.java
+++ b/org.osate.imv.aadldiagram/src/org/osate/imv/aadldiagram/util/ErrorUtil.java
@@ -1,47 +1,47 @@
package org.osate.imv.aadldiagram.util;
import java.util.List;
import org.osate.aadl2.instance.ComponentInstance;
import org.osate.aadl2.ComponentCategory;
import org.osate.xtext.aadl2.properties.util.GetProperties;
public class ErrorUtil {
/*
* returns a factor between 0 and 100 which indicates
* the potential impact of a fault ocuring from the selected
* component.
*/
public static int getFactor (ComponentInstance source, ComponentInstance dest)
{
ComponentInstance boundProcessor;
List<ComponentInstance> boundProcessors;
- System.out.println("source=" + source);
- System.out.println("dest =" + dest);
+ //System.out.println("source=" + source);
+ //System.out.println("dest =" + dest);
if ( (source == null) || (dest == null))
{
return -1;
}
if (source == dest)
{
return 99;
}
if ( (dest.getCategory() == ComponentCategory.DEVICE) && (source.getCategory() == ComponentCategory.PROCESSOR))
{
boundProcessors = GetProperties.getActualProcessorBinding(dest);
if (boundProcessors.size() > 0)
{
boundProcessor = boundProcessors.get(0);
if (boundProcessor == source)
{
return 50;
}
}
}
return -1;
}
}
| true | true | public static int getFactor (ComponentInstance source, ComponentInstance dest)
{
ComponentInstance boundProcessor;
List<ComponentInstance> boundProcessors;
System.out.println("source=" + source);
System.out.println("dest =" + dest);
if ( (source == null) || (dest == null))
{
return -1;
}
if (source == dest)
{
return 99;
}
if ( (dest.getCategory() == ComponentCategory.DEVICE) && (source.getCategory() == ComponentCategory.PROCESSOR))
{
boundProcessors = GetProperties.getActualProcessorBinding(dest);
if (boundProcessors.size() > 0)
{
boundProcessor = boundProcessors.get(0);
if (boundProcessor == source)
{
return 50;
}
}
}
return -1;
}
| public static int getFactor (ComponentInstance source, ComponentInstance dest)
{
ComponentInstance boundProcessor;
List<ComponentInstance> boundProcessors;
//System.out.println("source=" + source);
//System.out.println("dest =" + dest);
if ( (source == null) || (dest == null))
{
return -1;
}
if (source == dest)
{
return 99;
}
if ( (dest.getCategory() == ComponentCategory.DEVICE) && (source.getCategory() == ComponentCategory.PROCESSOR))
{
boundProcessors = GetProperties.getActualProcessorBinding(dest);
if (boundProcessors.size() > 0)
{
boundProcessor = boundProcessors.get(0);
if (boundProcessor == source)
{
return 50;
}
}
}
return -1;
}
|
diff --git a/commons/src/main/java/org/soluvas/commons/NameUtils.java b/commons/src/main/java/org/soluvas/commons/NameUtils.java
index 9404ad7f..e67e93d8 100644
--- a/commons/src/main/java/org/soluvas/commons/NameUtils.java
+++ b/commons/src/main/java/org/soluvas/commons/NameUtils.java
@@ -1,81 +1,85 @@
package org.soluvas.commons;
import java.util.List;
import org.fusesource.jansi.Ansi;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
/**
* @author ceefour
*
*/
public class NameUtils {
/**
* Shorten a class name by abbreviating package prefixes, then replacing with ellipsis
* as last resort.
* @param name
* @param targetLength
* @return
*/
public static String shortenClass(final String name, final int targetLength) {
String current = name;
if (current.length() <= targetLength)
return current;
// Split into segments
final List<String> split = Lists.newArrayList(Splitter.on('.').split(name));
// get rid of first to third-from-last segment
for (int i = 0; i < split.size() - 2; i++) {
split.set(i, split.get(i).substring(0, 1));
current = Joiner.on('.').join(split);
if (current.length() <= targetLength)
return current;
}
// last resort, force cut then replace with ellipsis
return "…" + current.substring(current.length() - targetLength + 1);
}
/**
* Shorten a class name by abbreviating package prefixes, then replacing with ellipsis
* as last resort.
*
* The result is right-padded with space and contain {@link Ansi}-style color instructions.
*
* @param name
* @param targetLength
* @return
*/
public static String shortenClassAnsi(final String name, final int targetLength) {
final String shortened = shortenClass(name, targetLength);
final String padding = Strings.repeat(" ", targetLength - shortened.length());
return formatClassAnsi(shortened) + padding;
}
/**
* Format a class name as {@link Ansi}-style color codes.
* @param name
* @return
*/
public static String formatClassAnsi(final String name) {
// Split into segments
final List<String> split = Lists.newArrayList(Splitter.on('.').split(name));
- split.set(split.size() - 1, "@|bold " + split.get(split.size() - 1) + "|@");
+ final String lastSegment = split.get(split.size() - 1);
+ final String boldedLastSegment = "…".equals(lastSegment.substring(0, 1))
+ ? "…" + "@|bold " + lastSegment.substring(1) + "|@"
+ : "@|bold " + lastSegment + "|@";
+ split.set(split.size() - 1, boldedLastSegment);
// final List<String> highlight = Lists.transform(split, new Function<String, String>() {
// @Override
// @Nullable
// public String apply(@Nullable String input) {
// if (input.substring(0, 1).equals("…")) {
// return "@|bold,black …|@@|bold " + input.substring(1) + "|@";
// } else {
// return "@|bold " + input + "|@";
// }
// }
// });
return Joiner.on("@|bold,black .|@").join(split).replaceFirst("…", "@|bold,black …|@");
}
}
| true | true | public static String formatClassAnsi(final String name) {
// Split into segments
final List<String> split = Lists.newArrayList(Splitter.on('.').split(name));
split.set(split.size() - 1, "@|bold " + split.get(split.size() - 1) + "|@");
// final List<String> highlight = Lists.transform(split, new Function<String, String>() {
// @Override
// @Nullable
// public String apply(@Nullable String input) {
// if (input.substring(0, 1).equals("…")) {
// return "@|bold,black …|@@|bold " + input.substring(1) + "|@";
// } else {
// return "@|bold " + input + "|@";
// }
// }
// });
return Joiner.on("@|bold,black .|@").join(split).replaceFirst("…", "@|bold,black …|@");
}
| public static String formatClassAnsi(final String name) {
// Split into segments
final List<String> split = Lists.newArrayList(Splitter.on('.').split(name));
final String lastSegment = split.get(split.size() - 1);
final String boldedLastSegment = "…".equals(lastSegment.substring(0, 1))
? "…" + "@|bold " + lastSegment.substring(1) + "|@"
: "@|bold " + lastSegment + "|@";
split.set(split.size() - 1, boldedLastSegment);
// final List<String> highlight = Lists.transform(split, new Function<String, String>() {
// @Override
// @Nullable
// public String apply(@Nullable String input) {
// if (input.substring(0, 1).equals("…")) {
// return "@|bold,black …|@@|bold " + input.substring(1) + "|@";
// } else {
// return "@|bold " + input + "|@";
// }
// }
// });
return Joiner.on("@|bold,black .|@").join(split).replaceFirst("…", "@|bold,black …|@");
}
|
diff --git a/src/se/kth/ssvl/tslab/wsn/general/servlib/contacts/interfaces/InterfaceTable.java b/src/se/kth/ssvl/tslab/wsn/general/servlib/contacts/interfaces/InterfaceTable.java
index 2842f33..61f008b 100644
--- a/src/se/kth/ssvl/tslab/wsn/general/servlib/contacts/interfaces/InterfaceTable.java
+++ b/src/se/kth/ssvl/tslab/wsn/general/servlib/contacts/interfaces/InterfaceTable.java
@@ -1,215 +1,213 @@
/*
* This file is part of the Bytewalla Project
* More information can be found at "http://www.tslab.ssvl.kth.se/csd/projects/092106/".
*
* Copyright 2009 Telecommunication Systems Laboratory (TSLab), Royal Institute of Technology, Sweden.
*
* 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 se.kth.ssvl.tslab.wsn.general.servlib.contacts.interfaces;
import java.util.Iterator;
import se.kth.ssvl.tslab.wsn.general.bpf.BPF;
import se.kth.ssvl.tslab.wsn.general.servlib.config.settings.InterfacesSetting.InterfaceEntry;
import se.kth.ssvl.tslab.wsn.general.servlib.conv_layers.ConvergenceLayer;
import se.kth.ssvl.tslab.wsn.general.servlib.conv_layers.connection.TCPConvergenceLayer;
import se.kth.ssvl.tslab.wsn.general.systemlib.util.List;
/**
* The list of interfaces
*
* @author Maria Jose Peroza Marval ([email protected])
*/
public class InterfaceTable {
/**
* TAG for Android Logging mechanism
*/
private static final String TAG = "InterfaceTable";
/**
* Singleton pattern for InterfaceTable
*/
private static InterfaceTable instance_ = null;
public static InterfaceTable getInstance() {
if (instance_ == null) {
instance_ = new InterfaceTable();
}
return instance_;
}
/**
* Parsing the interface's parameters specified in the configuration file
* (config). Create he interfaces and add them to the InterfaceTable.
*/
public static void init() {
List<InterfaceEntry> EntriesList = BPF.getInstance().getConfig()
.interfaces_setting().interface_entries();
Iterator<InterfaceEntry> i = EntriesList.iterator();
Interface.set_iface_counter(0);
while (i.hasNext()) {
InterfaceEntry element = i.next();
String conv_layer_type_ = element.conv_layer_type().getCaption();
- BPF.getInstance().getBPFLogger().debug(TAG, conv_layer_type_);
String id = element.id();
- BPF.getInstance().getBPFLogger().debug(TAG, id);
short local_port = element.local_port();
- BPF.getInstance().getBPFLogger().debug(TAG, "" + local_port);
boolean fixed_local_port_ = element.fixed_local_port();
+ BPF.getInstance().getBPFLogger().debug(TAG, conv_layer_type_ + " - " + id + " - " + local_port);
if (!fixed_local_port_) {
local_port = TCPConvergenceLayer.TCPCL_DEFAULT_PORT;
}
ConvergenceLayer cl = ConvergenceLayer
.find_clayer(conv_layer_type_);
if (cl == null) {
BPF.getInstance().getBPFLogger()
.error(TAG, "can't find convergence layer for " + id);
}
cl.set_local_port(local_port);
if (!InterfaceTable.getInstance().add(id, cl, conv_layer_type_)) {
BPF.getInstance().getBPFLogger()
.debug(TAG, "error adding interface %s" + id);
}
}
}
/**
* Constructor
*/
public InterfaceTable() {
iflist_ = new InterfaceList();
}
/**
* "Add a new interface to the table. Returns true if the interface is
* successfully added, false if the interface specification is invalid (or
* it already exists)"[DTN2].
*/
public boolean add(String name, ConvergenceLayer cl, String proto) {
Iterator<Interface> iter = iflist_.iterator();
if (find(name, iter)) {
String text = String.format("Interface %s already exists", name);
BPF.getInstance().getBPFLogger().error(TAG, text);
return false;
}
String text = String.format("adding interface " + name, proto);
BPF.getInstance().getBPFLogger().info(TAG, text);
Interface iface = new Interface(name, proto, cl);
if (!cl.interface_up(iface)) {
BPF.getInstance()
.getBPFLogger()
.error(TAG,
"convergence layer error adding interface" + name);
return false;
}
iflist_.add(iface);
return true;
}
/**
* "Remove the specified interface"[DTN2].
*/
public void shutdown() {
Iterator<Interface> iter = iflist_.iterator();
Interface iface;
BPF.getInstance().getBPFLogger().info(TAG, "removing interfaces");
while (iter.hasNext()) {
iface = iter.next();
iter.remove();
if (iface.clayer().interface_down(iface)) {
BPF.getInstance().getBPFLogger()
.info(TAG, "shutdown interface " + iface.name());
} else {
BPF.getInstance()
.getBPFLogger()
.error(TAG,
"error deleting interfaces from the convergence layer");
}
}
instance_ = null;
}
/**
* "List the current interfaces" [DTN2].
*/
public void list(StringBuffer buf) {
Iterator<Interface> iter = iflist_.iterator();
Interface iface;
while (iter.hasNext()) {
iface = iter.next();
String text = String.format("%s: Convergence Layer: %s\n",
iface.name(), iface.proto());
buf.append(text);
iface.clayer().dump_interface(iface, buf);
}
}
/**
* "All interfaces are tabled in-memory in a flat list. It's non-obvious
* what else would be better since we need to do a prefix match on demux
* strings in matching_interfaces" [DTN2].
*/
protected List<Interface> iflist_;
/**
* "Internal method to find the location of the given interface in the list"
* [DTN2].
*/
protected boolean find(String name, Iterator<Interface> iter) {
Interface iface;
while (iter.hasNext()) {
iface = iter.next();
if (iface.name() == name) {
return true;
}
}
return false;
}
}
| false | true | public static void init() {
List<InterfaceEntry> EntriesList = BPF.getInstance().getConfig()
.interfaces_setting().interface_entries();
Iterator<InterfaceEntry> i = EntriesList.iterator();
Interface.set_iface_counter(0);
while (i.hasNext()) {
InterfaceEntry element = i.next();
String conv_layer_type_ = element.conv_layer_type().getCaption();
BPF.getInstance().getBPFLogger().debug(TAG, conv_layer_type_);
String id = element.id();
BPF.getInstance().getBPFLogger().debug(TAG, id);
short local_port = element.local_port();
BPF.getInstance().getBPFLogger().debug(TAG, "" + local_port);
boolean fixed_local_port_ = element.fixed_local_port();
if (!fixed_local_port_) {
local_port = TCPConvergenceLayer.TCPCL_DEFAULT_PORT;
}
ConvergenceLayer cl = ConvergenceLayer
.find_clayer(conv_layer_type_);
if (cl == null) {
BPF.getInstance().getBPFLogger()
.error(TAG, "can't find convergence layer for " + id);
}
cl.set_local_port(local_port);
if (!InterfaceTable.getInstance().add(id, cl, conv_layer_type_)) {
BPF.getInstance().getBPFLogger()
.debug(TAG, "error adding interface %s" + id);
}
}
}
| public static void init() {
List<InterfaceEntry> EntriesList = BPF.getInstance().getConfig()
.interfaces_setting().interface_entries();
Iterator<InterfaceEntry> i = EntriesList.iterator();
Interface.set_iface_counter(0);
while (i.hasNext()) {
InterfaceEntry element = i.next();
String conv_layer_type_ = element.conv_layer_type().getCaption();
String id = element.id();
short local_port = element.local_port();
boolean fixed_local_port_ = element.fixed_local_port();
BPF.getInstance().getBPFLogger().debug(TAG, conv_layer_type_ + " - " + id + " - " + local_port);
if (!fixed_local_port_) {
local_port = TCPConvergenceLayer.TCPCL_DEFAULT_PORT;
}
ConvergenceLayer cl = ConvergenceLayer
.find_clayer(conv_layer_type_);
if (cl == null) {
BPF.getInstance().getBPFLogger()
.error(TAG, "can't find convergence layer for " + id);
}
cl.set_local_port(local_port);
if (!InterfaceTable.getInstance().add(id, cl, conv_layer_type_)) {
BPF.getInstance().getBPFLogger()
.debug(TAG, "error adding interface %s" + id);
}
}
}
|
diff --git a/org.eclipse.mylyn.team.ui/src/org/eclipse/mylyn/internal/team/ui/actions/OpenCorrespondingTaskAction.java b/org.eclipse.mylyn.team.ui/src/org/eclipse/mylyn/internal/team/ui/actions/OpenCorrespondingTaskAction.java
index 23f2aaf76..4b082afff 100644
--- a/org.eclipse.mylyn.team.ui/src/org/eclipse/mylyn/internal/team/ui/actions/OpenCorrespondingTaskAction.java
+++ b/org.eclipse.mylyn.team.ui/src/org/eclipse/mylyn/internal/team/ui/actions/OpenCorrespondingTaskAction.java
@@ -1,265 +1,265 @@
/*******************************************************************************
* Copyright (c) 2004 - 2006 University Of British Columbia 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:
* University Of British Columbia - initial API and implementation
*******************************************************************************/
package org.eclipse.mylar.internal.team.ui.actions;
import org.eclipse.compare.structuremergeviewer.IDiffElement;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.Path;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.mylar.internal.tasks.ui.TaskListImages;
import org.eclipse.mylar.internal.tasks.ui.TaskUiUtil;
import org.eclipse.mylar.internal.team.ContextChangeSet;
import org.eclipse.mylar.tasks.core.AbstractRepositoryConnector;
import org.eclipse.mylar.tasks.core.AbstractRepositoryTask;
import org.eclipse.mylar.tasks.core.ITask;
import org.eclipse.mylar.tasks.core.TaskRepository;
import org.eclipse.mylar.tasks.ui.AbstractRepositoryConnectorUi;
import org.eclipse.mylar.tasks.ui.TasksUiPlugin;
import org.eclipse.mylar.team.MylarTeamPlugin;
import org.eclipse.team.core.history.IFileRevision;
import org.eclipse.team.core.variants.IResourceVariant;
import org.eclipse.team.internal.ccvs.core.client.listeners.LogEntry;
import org.eclipse.team.internal.ccvs.core.mapping.CVSCheckedInChangeSet;
import org.eclipse.team.internal.ccvs.core.resources.RemoteResource;
import org.eclipse.team.internal.core.subscribers.DiffChangeSet;
import org.eclipse.team.internal.ui.synchronize.ChangeSetDiffNode;
import org.eclipse.team.internal.ui.synchronize.SynchronizeModelElement;
import org.eclipse.ui.IViewActionDelegate;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.internal.ObjectPluginAction;
/**
* @author Mik Kersten
*/
public class OpenCorrespondingTaskAction extends Action implements IViewActionDelegate {
private static final String LABEL = "Open Corresponding Task";
private ISelection selection;
private static final String PREFIX_HTTP = "http://";
private static final String PREFIX_HTTPS = "https://";
public OpenCorrespondingTaskAction() {
setText(LABEL);
setToolTipText(LABEL);
setImageDescriptor(TaskListImages.TASK_REPOSITORY);
}
public void init(IViewPart view) {
// ignore
}
public void run() {
if (selection instanceof StructuredSelection) {
run((StructuredSelection) selection);
}
}
public void run(IAction action) {
if (action instanceof ObjectPluginAction) {
ObjectPluginAction objectAction = (ObjectPluginAction) action;
if (objectAction.getSelection() instanceof StructuredSelection) {
StructuredSelection selection = (StructuredSelection) objectAction.getSelection();
run(selection);
}
}
}
private void run(StructuredSelection selection) {
Object element = selection.getFirstElement();
boolean opened = false;
if (element instanceof ChangeSetDiffNode) {
ChangeSetDiffNode diffNode = (ChangeSetDiffNode) element;
if (diffNode.getSet() instanceof ContextChangeSet) {
ITask task = ((ContextChangeSet) diffNode.getSet()).getTask();
TaskUiUtil.openEditor(task, false);
opened = true;
}
} else if (element instanceof ContextChangeSet) {
ITask task = ((ContextChangeSet) element).getTask();
if (task != null) {
TaskUiUtil.openEditor(task, false);
opened = true;
}
}
if (!opened) {
IProject project = findCorrespondingProject(element);
String comment = getCommentFromSelection(element);
if (comment != null) {
String id = MylarTeamPlugin.getDefault().getCommitTemplateManager()
.getTaskIdFromCommentOrLabel(comment);
if (id == null) {
id = getTaskIdFromLegacy07Label(comment);
}
if (project != null) {
TaskRepository repository = TasksUiPlugin.getDefault().getRepositoryForResource(project, false);
if (repository != null) {
AbstractRepositoryConnectorUi connectorUi = TasksUiPlugin.getRepositoryUi(repository.getKind());
if (connectorUi != null && id != null) {
opened = TaskUiUtil.openRepositoryTask(repository, id);
}
}
}
// try opening via URL if present
if (!opened) {
String fullUrl = getUrlFromComment(comment);
String repositoryUrl = null;
if (fullUrl != null) {
AbstractRepositoryConnector connector = TasksUiPlugin.getRepositoryManager()
- .getRepositoryForTaskUrl(fullUrl);
+ .getConnectorForRepositoryTaskUrl(fullUrl);
if (connector != null) {
repositoryUrl = connector.getRepositoryUrlFromTaskUrl(fullUrl);
}
} else {
ITask task = TasksUiPlugin.getTaskListManager().getTaskList().getActiveTask();
if (task instanceof AbstractRepositoryTask) {
repositoryUrl = ((AbstractRepositoryTask) task).getRepositoryUrl();
} else if (TasksUiPlugin.getRepositoryManager().getAllRepositories().size() == 1) {
repositoryUrl = TasksUiPlugin.getRepositoryManager().getAllRepositories().get(0).getUrl();
}
}
opened = TaskUiUtil.openRepositoryTask(repositoryUrl, id, fullUrl);
if (!opened) {
TaskUiUtil.openUrl(fullUrl);
}
}
}
}
}
private String getCommentFromSelection(Object element) {
if (element instanceof DiffChangeSet) {
return ((CVSCheckedInChangeSet) element).getComment();
} else if (element instanceof ChangeSetDiffNode) {
return ((ChangeSetDiffNode) element).getName();
} else if (element instanceof LogEntry) {
return ((LogEntry) element).getComment();
} else if (element instanceof IFileRevision) {
return ((IFileRevision) element).getComment();
}
return null;
}
private IProject findCorrespondingProject(Object element) {
if (element instanceof DiffChangeSet) {
IResource[] resources = ((DiffChangeSet) element).getResources();
if (resources.length > 0) {
// TODO: only checks first resource
return resources[0].getProject();
}
} else if (element instanceof SynchronizeModelElement) {
SynchronizeModelElement modelElement = (SynchronizeModelElement)element;
IResource resource = modelElement.getResource();
if (resource != null) {
return resource.getProject();
} else {
IDiffElement[] elements = modelElement.getChildren();
if (elements.length > 0) {
// TODO: only checks first diff
if (elements[0] instanceof SynchronizeModelElement) {
return ((SynchronizeModelElement)elements[0]).getResource().getProject();
}
}
}
} else if (element instanceof IAdaptable) {
// TODO: there must be a better way to get at the local resource
IResourceVariant resourceVariant = (IResourceVariant) ((IAdaptable) element)
.getAdapter(IResourceVariant.class);
if (resourceVariant != null && resourceVariant instanceof RemoteResource) {
RemoteResource remoteResource = (RemoteResource) resourceVariant;
String path = remoteResource.getRepositoryRelativePath();
IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
return root.getProject(new Path(path).removeFirstSegments(1).uptoSegment(1).toString());
}
} else {
}
return null;
}
public static String getUrlFromComment(String comment) {
int httpIndex = comment.indexOf(PREFIX_HTTP);
int httpsIndex = comment.indexOf(PREFIX_HTTPS);
int idStart = -1;
if (httpIndex != -1) {
idStart = httpIndex;
} else if (httpsIndex != -1) {
idStart = httpsIndex;
}
if (idStart != -1) {
int idEnd = comment.indexOf(' ', idStart);
if (idEnd == -1) {
return comment.substring(idStart);
} else if (idEnd != -1 && idStart < idEnd) {
return comment.substring(idStart, idEnd);
}
}
return null;
}
public static String getTaskIdFromLegacy07Label(String comment) {
String PREFIX_DELIM = ":";
String PREFIX_START_1 = "Progress on:";
String PREFIX_START_2 = "Completed:";
String usedPrefix = PREFIX_START_1;
int firstDelimIndex = comment.indexOf(PREFIX_START_1);
if (firstDelimIndex == -1) {
firstDelimIndex = comment.indexOf(PREFIX_START_2);
usedPrefix = PREFIX_START_2;
}
if (firstDelimIndex != -1) {
int idStart = firstDelimIndex + usedPrefix.length();
int idEnd = comment.indexOf(PREFIX_DELIM, firstDelimIndex + usedPrefix.length());// comment.indexOf(PREFIX_DELIM);
if (idEnd != -1 && idStart < idEnd) {
String id = comment.substring(idStart, idEnd);
if (id != null) {
return id.trim();
}
} else {
return comment.substring(0, firstDelimIndex);
}
}
return null;
}
// private Object findParent(ISynchronizeModelElement element) {
// if (element instanceof ChangeSetDiffNode) {
// return element;
// } else if (element.getParent() instanceof ISynchronizeModelElement) {
// return findParent((ISynchronizeModelElement) element.getParent());
// }
// return null;
// }
public void selectionChanged(IAction action, ISelection selection) {
this.selection = selection;
}
}
| true | true | private void run(StructuredSelection selection) {
Object element = selection.getFirstElement();
boolean opened = false;
if (element instanceof ChangeSetDiffNode) {
ChangeSetDiffNode diffNode = (ChangeSetDiffNode) element;
if (diffNode.getSet() instanceof ContextChangeSet) {
ITask task = ((ContextChangeSet) diffNode.getSet()).getTask();
TaskUiUtil.openEditor(task, false);
opened = true;
}
} else if (element instanceof ContextChangeSet) {
ITask task = ((ContextChangeSet) element).getTask();
if (task != null) {
TaskUiUtil.openEditor(task, false);
opened = true;
}
}
if (!opened) {
IProject project = findCorrespondingProject(element);
String comment = getCommentFromSelection(element);
if (comment != null) {
String id = MylarTeamPlugin.getDefault().getCommitTemplateManager()
.getTaskIdFromCommentOrLabel(comment);
if (id == null) {
id = getTaskIdFromLegacy07Label(comment);
}
if (project != null) {
TaskRepository repository = TasksUiPlugin.getDefault().getRepositoryForResource(project, false);
if (repository != null) {
AbstractRepositoryConnectorUi connectorUi = TasksUiPlugin.getRepositoryUi(repository.getKind());
if (connectorUi != null && id != null) {
opened = TaskUiUtil.openRepositoryTask(repository, id);
}
}
}
// try opening via URL if present
if (!opened) {
String fullUrl = getUrlFromComment(comment);
String repositoryUrl = null;
if (fullUrl != null) {
AbstractRepositoryConnector connector = TasksUiPlugin.getRepositoryManager()
.getRepositoryForTaskUrl(fullUrl);
if (connector != null) {
repositoryUrl = connector.getRepositoryUrlFromTaskUrl(fullUrl);
}
} else {
ITask task = TasksUiPlugin.getTaskListManager().getTaskList().getActiveTask();
if (task instanceof AbstractRepositoryTask) {
repositoryUrl = ((AbstractRepositoryTask) task).getRepositoryUrl();
} else if (TasksUiPlugin.getRepositoryManager().getAllRepositories().size() == 1) {
repositoryUrl = TasksUiPlugin.getRepositoryManager().getAllRepositories().get(0).getUrl();
}
}
opened = TaskUiUtil.openRepositoryTask(repositoryUrl, id, fullUrl);
if (!opened) {
TaskUiUtil.openUrl(fullUrl);
}
}
}
}
}
| private void run(StructuredSelection selection) {
Object element = selection.getFirstElement();
boolean opened = false;
if (element instanceof ChangeSetDiffNode) {
ChangeSetDiffNode diffNode = (ChangeSetDiffNode) element;
if (diffNode.getSet() instanceof ContextChangeSet) {
ITask task = ((ContextChangeSet) diffNode.getSet()).getTask();
TaskUiUtil.openEditor(task, false);
opened = true;
}
} else if (element instanceof ContextChangeSet) {
ITask task = ((ContextChangeSet) element).getTask();
if (task != null) {
TaskUiUtil.openEditor(task, false);
opened = true;
}
}
if (!opened) {
IProject project = findCorrespondingProject(element);
String comment = getCommentFromSelection(element);
if (comment != null) {
String id = MylarTeamPlugin.getDefault().getCommitTemplateManager()
.getTaskIdFromCommentOrLabel(comment);
if (id == null) {
id = getTaskIdFromLegacy07Label(comment);
}
if (project != null) {
TaskRepository repository = TasksUiPlugin.getDefault().getRepositoryForResource(project, false);
if (repository != null) {
AbstractRepositoryConnectorUi connectorUi = TasksUiPlugin.getRepositoryUi(repository.getKind());
if (connectorUi != null && id != null) {
opened = TaskUiUtil.openRepositoryTask(repository, id);
}
}
}
// try opening via URL if present
if (!opened) {
String fullUrl = getUrlFromComment(comment);
String repositoryUrl = null;
if (fullUrl != null) {
AbstractRepositoryConnector connector = TasksUiPlugin.getRepositoryManager()
.getConnectorForRepositoryTaskUrl(fullUrl);
if (connector != null) {
repositoryUrl = connector.getRepositoryUrlFromTaskUrl(fullUrl);
}
} else {
ITask task = TasksUiPlugin.getTaskListManager().getTaskList().getActiveTask();
if (task instanceof AbstractRepositoryTask) {
repositoryUrl = ((AbstractRepositoryTask) task).getRepositoryUrl();
} else if (TasksUiPlugin.getRepositoryManager().getAllRepositories().size() == 1) {
repositoryUrl = TasksUiPlugin.getRepositoryManager().getAllRepositories().get(0).getUrl();
}
}
opened = TaskUiUtil.openRepositoryTask(repositoryUrl, id, fullUrl);
if (!opened) {
TaskUiUtil.openUrl(fullUrl);
}
}
}
}
}
|
diff --git a/twitter-adapter/src/main/java/com/esri/geoevent/adapter/twitter/TweetStatusAdapter.java b/twitter-adapter/src/main/java/com/esri/geoevent/adapter/twitter/TweetStatusAdapter.java
index 02203b5..916b5a0 100644
--- a/twitter-adapter/src/main/java/com/esri/geoevent/adapter/twitter/TweetStatusAdapter.java
+++ b/twitter-adapter/src/main/java/com/esri/geoevent/adapter/twitter/TweetStatusAdapter.java
@@ -1,283 +1,283 @@
/*
Copyright 1995-2013 Esri
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.
For additional information, contact:
Environmental Systems Research Institute, Inc.
Attn: Contracts Dept
380 New York Street
Redlands, California, USA 92373
email: [email protected]
*/
package com.esri.geoevent.adapter.twitter;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.jackson.map.ObjectMapper;
import com.esri.geoevent.adapter.twitter.Tweet.BoundingBox;
import com.esri.geoevent.adapter.twitter.Tweet.Coordinates;
import com.esri.geoevent.adapter.twitter.Tweet.Place;
import com.esri.geoevent.adapter.twitter.Tweet.User;
import com.esri.ges.adapter.AdapterDefinition;
import com.esri.ges.adapter.InboundAdapterBase;
import com.esri.ges.core.component.ComponentException;
import com.esri.ges.core.geoevent.FieldGroup;
import com.esri.ges.core.geoevent.GeoEvent;
import com.esri.ges.core.geoevent.GeoEventDefinition;
import com.esri.ges.messaging.MessagingException;
import com.esri.ges.spatial.Point;
public class TweetStatusAdapter extends InboundAdapterBase
{
private static final Log LOG = LogFactory.getLog(TweetStatusAdapter.class);
private ObjectMapper mapper = new ObjectMapper();
private SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy");
private Charset charset;
private CharsetDecoder decoder;
public TweetStatusAdapter(AdapterDefinition definition) throws ComponentException
{
super(definition);
LOG.debug("Tweet Status Adapter created");
charset = Charset.forName("UTF-8");
decoder = charset.newDecoder();
}
private class TweetEventBuilder implements Runnable
{
private StringBuilder sb;
TweetEventBuilder(String text)
{
this.sb = new StringBuilder(text);
}
private GeoEvent buildGeoEvent() throws Exception
{
// 3 lines below are not necessary I think. These were added when I
// was having problems with encoding
// //byte[] strBytes = sb.toString().getBytes("UTF-8");
// //String s = new String(strBytes,"UTF-8");
// //Tweet jsonTweet = mapper.readValue(s, Tweet.class);
// atempt to parse string to Tweet
Tweet jsonTweet = mapper.readValue(sb.toString(), Tweet.class);
// consoleDebugPrintLn(sb.toString());
if (jsonTweet == null)
{
consoleDebugPrintLn("jsonTweet is null");
return null;
}
// consoleDebugPrintLn(jsonTweet.getText());
// Create an instance of the message using the guid that we
// generated when we started up.
GeoEvent msg;
try
{
AdapterDefinition def = (AdapterDefinition) definition;
// XmlAdapterDefinition tweetDef = (XmlAdapterDefinition) definition;
// String name = tweetDef.getName();
GeoEventDefinition geoDef = def.getGeoEventDefinition("TweetStatus");
if (geoEventCreator.getGeoEventDefinitionManager().searchGeoEventDefinition(geoDef.getName(), geoDef.getOwner()) == null)
{
geoEventCreator.getGeoEventDefinitionManager().addGeoEventDefinition(geoDef);
}
msg = geoEventCreator.create(geoDef.getName(), geoDef.getOwner());
LOG.debug("Created new TweetStatusMessage");
}
catch (MessagingException e)
{
LOG.error("Message Creation error in TweetStatusAdapter: " + e.getMessage());
return null;
}
catch (Exception ex)
{
LOG.error("Error creating initial tweet message: " + ex.getMessage());
return null;
}
// Populate the message with all the attribute values.
// first is geometry - get from tweet coordinates or place
double x = Double.NaN;
double y = Double.NaN;
int wkid = 4326;
Coordinates coords = jsonTweet.getCoordinates();
Place place = jsonTweet.getPlace();
User user = jsonTweet.getUser();
if (coords != null)
{
x = coords.getCoordinates().get(0);
y = coords.getCoordinates().get(1);
}
if (place != null)
{
// if still need coordinates0..
// get bounding box of place and figure center
if (Double.isNaN(x) && Double.isNaN(y))
{
BoundingBox bbox = place.getBounding_box();
if (bbox != null)
{
ArrayList<Double> ll = bbox.getCoordinates().get(0).get(0);
ArrayList<Double> ur = bbox.getCoordinates().get(0).get(2);
Double xmin = ll.get(0);
Double xmax = ur.get(0);
Double ymin = ll.get(1);
Double ymax = ur.get(1);
x = xmin + ((xmax - xmin) / 2);
y = ymin + ((ymax - ymin) / 2);
}
}
// set attributes in message associated with place
FieldGroup placeGrp = msg.createFieldGroup("place");
placeGrp.setField(0, place.getId());
placeGrp.setField(1, place.getFull_name());
placeGrp.setField(2, place.getUrl());
msg.setField(13, placeGrp);
}
// set geometry in message if an xy coordinate was found
// and set geolocated attribute to true or false
if (!Double.isNaN(x) && !Double.isNaN(y))
{
Point pt = spatial.createPoint(x, y, wkid);
msg.setField(5, pt);
msg.setField(15, true);
LOG.debug("Generated tweet with location");
// consoleDebugPrintLn("tweet with location");
}
else
{
msg.setField(15, false);
}
// set rest of attributes in message
msg.setField(0, jsonTweet.getPossibly_sensitive_editable());
msg.setField(1, jsonTweet.getText());
String createdAt = jsonTweet.getCreated_at();
try
{
if (createdAt != null)
msg.setField(2, sdf.parse(jsonTweet.getCreated_at()));
}
catch (Exception e)
{
- LOG.warn("Parse date exception in TweetStatusAdapter: " + e.getMessage());
+ LOG.warn("Parse date exception in TweetStatusAdapter (" + jsonTweet.getCreated_at() + "): " + e.getMessage());
LOG.debug(e.getMessage(), e);
}
msg.setField(3, jsonTweet.getRetweeted());
msg.setField(4, jsonTweet.getRetweet_count());
msg.setField(6, jsonTweet.getId_str());
msg.setField(7, jsonTweet.getIn_reply_to_screen_name());
msg.setField(8, jsonTweet.getIn_reply_to_status_id_str());
msg.setField(9, jsonTweet.getFavorited());
msg.setField(10, jsonTweet.getTruncated());
msg.setField(11, jsonTweet.getPossibly_sensitive());
msg.setField(12, jsonTweet.getIn_reply_to_user_id_str());
if (user != null)
{
FieldGroup userGrp = msg.createFieldGroup("user");
userGrp.setField(0, user.getId_str());
userGrp.setField(1, user.getName());
userGrp.setField(2, user.getFollowers_count());
userGrp.setField(3, user.getLocation());
userGrp.setField(4, user.getScreen_name());
msg.setField(14, userGrp);
}
return msg;
}
@Override
public void run()
{
try
{
GeoEvent event = buildGeoEvent();
if (event != null)
{
geoEventListener.receive(event);
}
}
catch (Throwable t)
{
LOG.error("Unexpected error", t);
}
}
}
@Override
public void receive(ByteBuffer buffer, String channelId)
{
if (!buffer.hasRemaining())
return;
try
{
CharBuffer charBuffer = decoder.decode(buffer);
String text = charBuffer.toString();
TweetEventBuilder builder = new TweetEventBuilder(text);
Thread t = new Thread(builder);
t.setName("Twitter Event Builder " + System.identityHashCode(buffer));
t.start();
}
catch (CharacterCodingException e)
{
LOG.warn("Could not decode the incoming buffer - " + e);
buffer.clear();
return;
}
}
@Override
protected GeoEvent adapt(ByteBuffer buffer, String channelId)
{
return null;
}
public static void consoleDebugPrintLn(String msg)
{
String consoleOut = System.getenv("GEP_CONSOLE_OUTPUT");
if (consoleOut != null && "1".equals(consoleOut))
{
System.out.println(msg);
LOG.debug(msg);
}
}
public static void consoleDebugPrint(String msg)
{
String consoleOut = System.getenv("GEP_CONSOLE_OUTPUT");
if (consoleOut != null && "1".equals(consoleOut))
{
System.out.print(msg);
LOG.debug(msg);
}
}
}
| true | true | private GeoEvent buildGeoEvent() throws Exception
{
// 3 lines below are not necessary I think. These were added when I
// was having problems with encoding
// //byte[] strBytes = sb.toString().getBytes("UTF-8");
// //String s = new String(strBytes,"UTF-8");
// //Tweet jsonTweet = mapper.readValue(s, Tweet.class);
// atempt to parse string to Tweet
Tweet jsonTweet = mapper.readValue(sb.toString(), Tweet.class);
// consoleDebugPrintLn(sb.toString());
if (jsonTweet == null)
{
consoleDebugPrintLn("jsonTweet is null");
return null;
}
// consoleDebugPrintLn(jsonTweet.getText());
// Create an instance of the message using the guid that we
// generated when we started up.
GeoEvent msg;
try
{
AdapterDefinition def = (AdapterDefinition) definition;
// XmlAdapterDefinition tweetDef = (XmlAdapterDefinition) definition;
// String name = tweetDef.getName();
GeoEventDefinition geoDef = def.getGeoEventDefinition("TweetStatus");
if (geoEventCreator.getGeoEventDefinitionManager().searchGeoEventDefinition(geoDef.getName(), geoDef.getOwner()) == null)
{
geoEventCreator.getGeoEventDefinitionManager().addGeoEventDefinition(geoDef);
}
msg = geoEventCreator.create(geoDef.getName(), geoDef.getOwner());
LOG.debug("Created new TweetStatusMessage");
}
catch (MessagingException e)
{
LOG.error("Message Creation error in TweetStatusAdapter: " + e.getMessage());
return null;
}
catch (Exception ex)
{
LOG.error("Error creating initial tweet message: " + ex.getMessage());
return null;
}
// Populate the message with all the attribute values.
// first is geometry - get from tweet coordinates or place
double x = Double.NaN;
double y = Double.NaN;
int wkid = 4326;
Coordinates coords = jsonTweet.getCoordinates();
Place place = jsonTweet.getPlace();
User user = jsonTweet.getUser();
if (coords != null)
{
x = coords.getCoordinates().get(0);
y = coords.getCoordinates().get(1);
}
if (place != null)
{
// if still need coordinates0..
// get bounding box of place and figure center
if (Double.isNaN(x) && Double.isNaN(y))
{
BoundingBox bbox = place.getBounding_box();
if (bbox != null)
{
ArrayList<Double> ll = bbox.getCoordinates().get(0).get(0);
ArrayList<Double> ur = bbox.getCoordinates().get(0).get(2);
Double xmin = ll.get(0);
Double xmax = ur.get(0);
Double ymin = ll.get(1);
Double ymax = ur.get(1);
x = xmin + ((xmax - xmin) / 2);
y = ymin + ((ymax - ymin) / 2);
}
}
// set attributes in message associated with place
FieldGroup placeGrp = msg.createFieldGroup("place");
placeGrp.setField(0, place.getId());
placeGrp.setField(1, place.getFull_name());
placeGrp.setField(2, place.getUrl());
msg.setField(13, placeGrp);
}
// set geometry in message if an xy coordinate was found
// and set geolocated attribute to true or false
if (!Double.isNaN(x) && !Double.isNaN(y))
{
Point pt = spatial.createPoint(x, y, wkid);
msg.setField(5, pt);
msg.setField(15, true);
LOG.debug("Generated tweet with location");
// consoleDebugPrintLn("tweet with location");
}
else
{
msg.setField(15, false);
}
// set rest of attributes in message
msg.setField(0, jsonTweet.getPossibly_sensitive_editable());
msg.setField(1, jsonTweet.getText());
String createdAt = jsonTweet.getCreated_at();
try
{
if (createdAt != null)
msg.setField(2, sdf.parse(jsonTweet.getCreated_at()));
}
catch (Exception e)
{
LOG.warn("Parse date exception in TweetStatusAdapter: " + e.getMessage());
LOG.debug(e.getMessage(), e);
}
msg.setField(3, jsonTweet.getRetweeted());
msg.setField(4, jsonTweet.getRetweet_count());
msg.setField(6, jsonTweet.getId_str());
msg.setField(7, jsonTweet.getIn_reply_to_screen_name());
msg.setField(8, jsonTweet.getIn_reply_to_status_id_str());
msg.setField(9, jsonTweet.getFavorited());
msg.setField(10, jsonTweet.getTruncated());
msg.setField(11, jsonTweet.getPossibly_sensitive());
msg.setField(12, jsonTweet.getIn_reply_to_user_id_str());
if (user != null)
{
FieldGroup userGrp = msg.createFieldGroup("user");
userGrp.setField(0, user.getId_str());
userGrp.setField(1, user.getName());
userGrp.setField(2, user.getFollowers_count());
userGrp.setField(3, user.getLocation());
userGrp.setField(4, user.getScreen_name());
msg.setField(14, userGrp);
}
return msg;
}
| private GeoEvent buildGeoEvent() throws Exception
{
// 3 lines below are not necessary I think. These were added when I
// was having problems with encoding
// //byte[] strBytes = sb.toString().getBytes("UTF-8");
// //String s = new String(strBytes,"UTF-8");
// //Tweet jsonTweet = mapper.readValue(s, Tweet.class);
// atempt to parse string to Tweet
Tweet jsonTweet = mapper.readValue(sb.toString(), Tweet.class);
// consoleDebugPrintLn(sb.toString());
if (jsonTweet == null)
{
consoleDebugPrintLn("jsonTweet is null");
return null;
}
// consoleDebugPrintLn(jsonTweet.getText());
// Create an instance of the message using the guid that we
// generated when we started up.
GeoEvent msg;
try
{
AdapterDefinition def = (AdapterDefinition) definition;
// XmlAdapterDefinition tweetDef = (XmlAdapterDefinition) definition;
// String name = tweetDef.getName();
GeoEventDefinition geoDef = def.getGeoEventDefinition("TweetStatus");
if (geoEventCreator.getGeoEventDefinitionManager().searchGeoEventDefinition(geoDef.getName(), geoDef.getOwner()) == null)
{
geoEventCreator.getGeoEventDefinitionManager().addGeoEventDefinition(geoDef);
}
msg = geoEventCreator.create(geoDef.getName(), geoDef.getOwner());
LOG.debug("Created new TweetStatusMessage");
}
catch (MessagingException e)
{
LOG.error("Message Creation error in TweetStatusAdapter: " + e.getMessage());
return null;
}
catch (Exception ex)
{
LOG.error("Error creating initial tweet message: " + ex.getMessage());
return null;
}
// Populate the message with all the attribute values.
// first is geometry - get from tweet coordinates or place
double x = Double.NaN;
double y = Double.NaN;
int wkid = 4326;
Coordinates coords = jsonTweet.getCoordinates();
Place place = jsonTweet.getPlace();
User user = jsonTweet.getUser();
if (coords != null)
{
x = coords.getCoordinates().get(0);
y = coords.getCoordinates().get(1);
}
if (place != null)
{
// if still need coordinates0..
// get bounding box of place and figure center
if (Double.isNaN(x) && Double.isNaN(y))
{
BoundingBox bbox = place.getBounding_box();
if (bbox != null)
{
ArrayList<Double> ll = bbox.getCoordinates().get(0).get(0);
ArrayList<Double> ur = bbox.getCoordinates().get(0).get(2);
Double xmin = ll.get(0);
Double xmax = ur.get(0);
Double ymin = ll.get(1);
Double ymax = ur.get(1);
x = xmin + ((xmax - xmin) / 2);
y = ymin + ((ymax - ymin) / 2);
}
}
// set attributes in message associated with place
FieldGroup placeGrp = msg.createFieldGroup("place");
placeGrp.setField(0, place.getId());
placeGrp.setField(1, place.getFull_name());
placeGrp.setField(2, place.getUrl());
msg.setField(13, placeGrp);
}
// set geometry in message if an xy coordinate was found
// and set geolocated attribute to true or false
if (!Double.isNaN(x) && !Double.isNaN(y))
{
Point pt = spatial.createPoint(x, y, wkid);
msg.setField(5, pt);
msg.setField(15, true);
LOG.debug("Generated tweet with location");
// consoleDebugPrintLn("tweet with location");
}
else
{
msg.setField(15, false);
}
// set rest of attributes in message
msg.setField(0, jsonTweet.getPossibly_sensitive_editable());
msg.setField(1, jsonTweet.getText());
String createdAt = jsonTweet.getCreated_at();
try
{
if (createdAt != null)
msg.setField(2, sdf.parse(jsonTweet.getCreated_at()));
}
catch (Exception e)
{
LOG.warn("Parse date exception in TweetStatusAdapter (" + jsonTweet.getCreated_at() + "): " + e.getMessage());
LOG.debug(e.getMessage(), e);
}
msg.setField(3, jsonTweet.getRetweeted());
msg.setField(4, jsonTweet.getRetweet_count());
msg.setField(6, jsonTweet.getId_str());
msg.setField(7, jsonTweet.getIn_reply_to_screen_name());
msg.setField(8, jsonTweet.getIn_reply_to_status_id_str());
msg.setField(9, jsonTweet.getFavorited());
msg.setField(10, jsonTweet.getTruncated());
msg.setField(11, jsonTweet.getPossibly_sensitive());
msg.setField(12, jsonTweet.getIn_reply_to_user_id_str());
if (user != null)
{
FieldGroup userGrp = msg.createFieldGroup("user");
userGrp.setField(0, user.getId_str());
userGrp.setField(1, user.getName());
userGrp.setField(2, user.getFollowers_count());
userGrp.setField(3, user.getLocation());
userGrp.setField(4, user.getScreen_name());
msg.setField(14, userGrp);
}
return msg;
}
|
diff --git a/src/com/omartech/tdg/service/ItemService.java b/src/com/omartech/tdg/service/ItemService.java
index cb8a347..2201c6e 100644
--- a/src/com/omartech/tdg/service/ItemService.java
+++ b/src/com/omartech/tdg/service/ItemService.java
@@ -1,116 +1,120 @@
package com.omartech.tdg.service;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.omartech.tdg.mapper.ItemMapper;
import com.omartech.tdg.model.Coinage;
import com.omartech.tdg.model.Item;
import com.omartech.tdg.utils.ProductStatus;
@Service
public class ItemService {
@Autowired
private ItemMapper itemMapper;
@Autowired
private ProductService productService;
@Transactional
public void insertItem(Item item) {
if(item.getAvailableQuantity() < item.getSafeStock()){
item.setActive(0);
}else{
item.setActive(1);
}
item.setStatus(ProductStatus.OK);
itemMapper.insertItem(item);
}
/**
* 根据itemId和数量来返回对应的价格,是单价,不是乘上数量之后的价格
*/
public float getPriceByItemId(int id, int count){
Item item = getItemById(id);
Date now = new Date(System.currentTimeMillis());
Date begin = item.getPromotionTime();
Date end = item.getPromotionEnd();
int min = item.getMinimumQuantity();
int max = item.getMaximumAcceptQuantity();
float result = 0f;
if(count < max && count > min){//优先批发价
float pifa = item.getWholePrice();
if(pifa - 0.0 < 0.01)
result = item.getRetailPrice();
else
result = item.getWholePrice();
}
if(begin != null && end !=null){//如果在优惠期就用优惠价
if(now.after(begin) && end.after(now)){
float pro = item.getPromotionPrice();
if(pro - 0.0 < 0.001){
pro = item.getRetailPrice();
}
- if(pro < result){
+ if(result > 0){
+ if(pro < result){
+ result = pro;
+ }
+ }else{
result = pro;
}
}else{
result = item.getRetailPrice();
}
}else{
result = item.getRetailPrice();
}
return result;
}
public Item getItemBySku(String sku) {//for 卖家
Item item = itemMapper.getItemBySku(sku);
return item;
}
public Item getItemById(int id){//for 系统
Item item = itemMapper.getItemById(id);
return item;
}
public List<Item> getItemsByProductId(int productId) {
List<Item> items = itemMapper.getItemsByProductIdAndStatus(productId, ProductStatus.OK);
return items;
}
public List<Item> getItemsByProductIdAndStatus(int productId, int statusId){
List<Item> items = itemMapper.getItemsByProductIdAndStatus(productId, statusId);
return items;
}
public void updateItem(Item item){
itemMapper.updateItem(item);
}
public void updateItemStatus(int itemId, int statusId){
Item item = getItemById(itemId);
item.setStatus(statusId);
updateItem(item);
}
public void deleteItem(int itemId){
updateItemStatus(itemId, ProductStatus.Deleted);
// Item item = getItemById(itemId);
// int productId = item.getProductId();
// List<Item> items = getItemsByProductIdAndStatus(productId, ProductStatus.OK);
// if(items.size() == 0){
// productService.updateProductStatus(productId, ProductStatus.NoChildren);
// }
}
public ItemMapper getItemMapper() {
return itemMapper;
}
public void setItemMapper(ItemMapper itemMapper) {
this.itemMapper = itemMapper;
}
}
| true | true | public float getPriceByItemId(int id, int count){
Item item = getItemById(id);
Date now = new Date(System.currentTimeMillis());
Date begin = item.getPromotionTime();
Date end = item.getPromotionEnd();
int min = item.getMinimumQuantity();
int max = item.getMaximumAcceptQuantity();
float result = 0f;
if(count < max && count > min){//优先批发价
float pifa = item.getWholePrice();
if(pifa - 0.0 < 0.01)
result = item.getRetailPrice();
else
result = item.getWholePrice();
}
if(begin != null && end !=null){//如果在优惠期就用优惠价
if(now.after(begin) && end.after(now)){
float pro = item.getPromotionPrice();
if(pro - 0.0 < 0.001){
pro = item.getRetailPrice();
}
if(pro < result){
result = pro;
}
}else{
result = item.getRetailPrice();
}
}else{
result = item.getRetailPrice();
}
return result;
}
| public float getPriceByItemId(int id, int count){
Item item = getItemById(id);
Date now = new Date(System.currentTimeMillis());
Date begin = item.getPromotionTime();
Date end = item.getPromotionEnd();
int min = item.getMinimumQuantity();
int max = item.getMaximumAcceptQuantity();
float result = 0f;
if(count < max && count > min){//优先批发价
float pifa = item.getWholePrice();
if(pifa - 0.0 < 0.01)
result = item.getRetailPrice();
else
result = item.getWholePrice();
}
if(begin != null && end !=null){//如果在优惠期就用优惠价
if(now.after(begin) && end.after(now)){
float pro = item.getPromotionPrice();
if(pro - 0.0 < 0.001){
pro = item.getRetailPrice();
}
if(result > 0){
if(pro < result){
result = pro;
}
}else{
result = pro;
}
}else{
result = item.getRetailPrice();
}
}else{
result = item.getRetailPrice();
}
return result;
}
|
diff --git a/src/com/joshuawise/dumload/Uploader.java b/src/com/joshuawise/dumload/Uploader.java
index e7725e9..d81441a 100644
--- a/src/com/joshuawise/dumload/Uploader.java
+++ b/src/com/joshuawise/dumload/Uploader.java
@@ -1,406 +1,410 @@
package com.joshuawise.dumload;
import java.io.InputStream;
import java.io.OutputStream;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.Messenger;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.UIKeyboardInteractive;
import com.jcraft.jsch.UserInfo;
public class Uploader extends Service implements Runnable, UserInfo, UIKeyboardInteractive {
private Uri uri;
private String homedir;
private Thread me;
private static final int HELPME_ID = 1;
private RemoteViews remote;
private int thenotifid;
private Notification thenotif;
private String headline;
private String dest;
private InputStream is;
public Object _theObject;
private void sayNullNotification(final String scroller, final String headline, final String description)
{
int bogon = (int)SystemClock.elapsedRealtime();
NotificationManager mNotificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.icon, scroller, System.currentTimeMillis());
Intent intent = new Intent(this, NotifSlave.class);
intent.setAction("com.joshuawise.dumload.NotifSlave");
/* no extras to make the notifslave die */
intent.setData((Uri.parse("suckit://"+SystemClock.elapsedRealtime())));
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, 0);
notification.defaults |= Notification.DEFAULT_VIBRATE;
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.setLatestEventInfo(getApplicationContext(), headline, description, contentIntent);
mNotificationManager.notify(bogon, notification);
}
private Object /* pick one type, and fixate on it */ dance(final String type, final String text) /* for inside the thread */
{
final Uploader thisupl = this;
final Message msg = Message.obtain();
/* t(*A*t) */
Thread t = new Thread() {
public void run() {
Looper.prepare();
int bogon = (int)SystemClock.elapsedRealtime();
NotificationManager mNotificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.icon, "Dumload prompt", System.currentTimeMillis());
Handler h = new Handler() {
public void handleMessage(Message M) {
msg.copyFrom(M);
Looper.myLooper().quit();
}
};
Messenger m = new Messenger(h);
Intent intent = new Intent(thisupl, NotifSlave.class);
intent.setAction("com.joshuawise.dumload.NotifSlave");
intent.putExtra("com.joshuawise.dumload.returnmessenger", m);
intent.putExtra("com.joshuawise.dumload.reqtype", type);
intent.putExtra("com.joshuawise.dumload.prompt", text);
intent.setData((Uri.parse("suckit://"+SystemClock.elapsedRealtime())));
PendingIntent contentIntent = PendingIntent.getActivity(thisupl, 0, intent, 0);
notification.defaults |= Notification.DEFAULT_VIBRATE;
notification.flags |= Notification.FLAG_ONGOING_EVENT | Notification.FLAG_NO_CLEAR;
notification.setLatestEventInfo(getApplicationContext(), "I've been had!", "Dumload needs your input.", contentIntent);
Log.e("Dumload.Uploader[thread]", "Notifying...");
mNotificationManager.notify(bogon, notification);
Log.e("Dumload.Uploader[thread]", "About to go to 'sleep'...");
Looper.loop();
Log.e("Dumload.Uploader[thread]", "And we're alive!");
Log.e("Dumload.Uploader[thread]", "result was: "+(Integer.toString(msg.arg1)));
mNotificationManager.cancel(bogon);
}
};
t.start();
try {
t.join();
} catch (Exception e) {
return null;
}
if (type.equals("yesno"))
return new Boolean(msg.arg1 == 1);
else if (type.equals("message"))
return null;
else if (type.equals("password")) {
if (msg.arg1 == 0)
return null;
Bundle b = msg.getData();
return b.getString("response");
} else
return null;
}
/* UserInfo bits */
String _password = null;
public String getPassword()
{
return _password;
}
public boolean promptPassword(String message)
{
_password = (String)dance("password", message);
return (_password != null);
}
String _passphrase = null;
public String getPassphrase()
{
return _passphrase;
}
public boolean promptPassphrase(String message)
{
_passphrase = (String)dance("password", message);
return (_passphrase != null);
}
public boolean promptYesNo(String str)
{
return ((Boolean)dance("yesno", str)).booleanValue();
}
public void showMessage(String str)
{
dance("message", str);
}
public String[] promptKeyboardInteractive(String dest, String name, String instr, String[] prompt, boolean[] echo)
{
int i;
String [] responses = new String[prompt.length];
Log.e("Dumload.Uploader", "dest: "+dest);
Log.e("Dumload.Uploader", "name: "+name);
Log.e("Dumload.Uploader", "instr: "+instr);
for (i = 0; i < prompt.length; i++)
{
responses[i] = (String) dance("password", "[" + dest + "]\n" + prompt[i]);
if (responses[i] == null)
return null;
}
return responses;
}
private void expect_ack(InputStream in) throws Exception, java.io.IOException
{
int b = in.read();
if (b == -1)
{
throw new Exception("unexpected EOF from remote end");
}
if (b == 1 /* error */ || b == 2 /* fatal error */)
{
StringBuffer sb = new StringBuffer();
int c = 0;
while ((c = in.read()) != '\n')
sb.append((char)c);
throw new Exception("error from remote end: " + sb.toString());
}
}
private void set_up_notif(final String _headline)
{
NotificationManager mNotificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
thenotif = new Notification(R.drawable.icon, headline, System.currentTimeMillis());
thenotifid = (int)SystemClock.elapsedRealtime();
Intent intent = new Intent(this, NotifSlave.class);
headline = _headline;
intent.setAction("com.joshuawise.dumload.NotifSlave");
/* no extras to make the notifslave die */
intent.setData((Uri.parse("suckit://"+SystemClock.elapsedRealtime())));
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, 0);
thenotif.defaults |= 0;
thenotif.flags |= Notification.FLAG_ONGOING_EVENT | Notification.FLAG_NO_CLEAR;
remote = new RemoteViews(getPackageName(), R.layout.textnotif);
remote.setImageViewResource(R.id.image, R.drawable.icon);
remote.setTextViewText(R.id.headline, headline);
remote.setTextViewText(R.id.status, "Beginning upload...");
thenotif.contentView = remote;
thenotif.contentIntent = contentIntent;
mNotificationManager.notify(thenotifid, thenotif);
}
private void destroy_notif()
{
NotificationManager mNotificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.cancel(thenotifid);
}
private void update_notif(String text)
{
NotificationManager mNotificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
remote = new RemoteViews(getPackageName(), R.layout.textnotif);
remote.setImageViewResource(R.id.image, R.drawable.icon);
remote.setTextViewText(R.id.headline, headline);
remote.setTextViewText(R.id.status, text);
thenotif.contentView = remote;
mNotificationManager.notify(thenotifid, thenotif);
}
private void update_notif(int n, int total)
{
NotificationManager mNotificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
remote = new RemoteViews(getPackageName(), R.layout.progressnotif);
remote.setImageViewResource(R.id.image, R.drawable.icon);
remote.setTextViewText(R.id.headline, headline);
remote.setProgressBar(R.id.status, total, n, false);
thenotif.contentView = remote;
mNotificationManager.notify(thenotifid, thenotif);
}
public void run()
{
Looper.prepare();
Log.e("Dumload.Uploader[thread]", "This brought to you from the new thread.");
set_up_notif("Dumload upload: " + dest);
try {
say("Uploading "+(Integer.toString(is.available()))+" bytes");
update_notif("Connecting...");
JSch jsch = new JSch();
jsch.setKnownHosts(homedir + "/known_hosts");
try {
jsch.addIdentity(homedir + "/id_dsa");
} catch (java.lang.Exception e) {
}
+ try {
+ jsch.addIdentity(homedir + "/id_dsa_generated");
+ } catch (java.lang.Exception e) {
+ }
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String server = prefs.getString("server", "").trim();
String userName = prefs.getString("userName", "").trim();
- Integer port = prefs.getInt("serverPort", 22);
+ Integer port = Integer.valueOf(prefs.getString("port", "22"));
Log.d("dbg", userName + "@" + server + ":" + port);
Session s = jsch.getSession(userName, server, port);
s.setUserInfo(this);
s.connect();
Channel channel = s.openChannel("exec");
((ChannelExec)channel).setCommand("scp -t "+dest);
channel.connect();
OutputStream scp_out = channel.getOutputStream();
InputStream scp_in = channel.getInputStream();
update_notif("Starting send...");
/* Okay, BS out of the way. Now go send the file. */
expect_ack(scp_in);
String stfu;
if (dest.lastIndexOf("/") > 0)
stfu = dest.substring(dest.lastIndexOf("/") + 1);
else
stfu = dest;
scp_out.write(("C0644 " + (Integer.toString(is.available())) + " "+stfu+"\n").getBytes());
scp_out.flush();
expect_ack(scp_in);
int total, nbytes;
total = is.available();
nbytes = 0;
int len;
byte[] buf = new byte[4096];
while ((len = is.read(buf, 0, buf.length)) > 0)
{
scp_out.write(buf, 0, len);
nbytes += len;
update_notif(nbytes, total);
}
is.close();
update_notif("Finishing file transfer...");
scp_out.write("\0".getBytes());
scp_out.flush();
expect_ack(scp_in);
channel.disconnect();
update_notif("Preparing to resize image...");
channel = s.openChannel("exec");
((ChannelExec)channel).setCommand("pscale "+dest);
channel.connect();
scp_in = channel.getInputStream();
update_notif("Resizing image...");
while ((len = scp_in.read(buf, 0, buf.length)) > 0)
;
channel.disconnect();
update_notif("Upload complete.");
sayNullNotification("Dumload upload complete: " + dest, "Upload complete", "Uploaded: " + dest);
s.disconnect();
} catch (Exception e) {
Log.e("Dumload.uploader[thread]", "JSchException: "+(e.toString()));
sayNullNotification("Dumload upload failed", "Upload failed", e.toString());
}
destroy_notif();
Log.e("Dumload.uploader[thread]", "And now I'm back to life!");
}
private void say(String s) {
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
}
@Override
public void onStart(Intent i, int startId)
{
uri = i.getData();
dest = i.getStringExtra("com.joshuawise.dumload.dest");
homedir = getApplicationContext().getFilesDir().getAbsolutePath();
int shits = 0;
int giggles = 1;
super.onStart(i, startId);
Log.e("Dumload.Uploader", "Started.");
Log.e("Dumload.Uploader", "My path is "+homedir);
try {
is = getContentResolver().openInputStream(uri);
} catch (Exception e) {
say("Failed to open input file.");
return;
}
me = new Thread(this, "Uploader thread");
me.start();
}
@Override
public IBinder onBind(Intent i) {
Log.e("Dumload.Uploader", "bound");
return null;
}
}
| false | true | public void run()
{
Looper.prepare();
Log.e("Dumload.Uploader[thread]", "This brought to you from the new thread.");
set_up_notif("Dumload upload: " + dest);
try {
say("Uploading "+(Integer.toString(is.available()))+" bytes");
update_notif("Connecting...");
JSch jsch = new JSch();
jsch.setKnownHosts(homedir + "/known_hosts");
try {
jsch.addIdentity(homedir + "/id_dsa");
} catch (java.lang.Exception e) {
}
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String server = prefs.getString("server", "").trim();
String userName = prefs.getString("userName", "").trim();
Integer port = prefs.getInt("serverPort", 22);
Log.d("dbg", userName + "@" + server + ":" + port);
Session s = jsch.getSession(userName, server, port);
s.setUserInfo(this);
s.connect();
Channel channel = s.openChannel("exec");
((ChannelExec)channel).setCommand("scp -t "+dest);
channel.connect();
OutputStream scp_out = channel.getOutputStream();
InputStream scp_in = channel.getInputStream();
update_notif("Starting send...");
/* Okay, BS out of the way. Now go send the file. */
expect_ack(scp_in);
String stfu;
if (dest.lastIndexOf("/") > 0)
stfu = dest.substring(dest.lastIndexOf("/") + 1);
else
stfu = dest;
scp_out.write(("C0644 " + (Integer.toString(is.available())) + " "+stfu+"\n").getBytes());
scp_out.flush();
expect_ack(scp_in);
int total, nbytes;
total = is.available();
nbytes = 0;
int len;
byte[] buf = new byte[4096];
while ((len = is.read(buf, 0, buf.length)) > 0)
{
scp_out.write(buf, 0, len);
nbytes += len;
update_notif(nbytes, total);
}
is.close();
update_notif("Finishing file transfer...");
scp_out.write("\0".getBytes());
scp_out.flush();
expect_ack(scp_in);
channel.disconnect();
update_notif("Preparing to resize image...");
channel = s.openChannel("exec");
((ChannelExec)channel).setCommand("pscale "+dest);
channel.connect();
scp_in = channel.getInputStream();
update_notif("Resizing image...");
while ((len = scp_in.read(buf, 0, buf.length)) > 0)
;
channel.disconnect();
update_notif("Upload complete.");
sayNullNotification("Dumload upload complete: " + dest, "Upload complete", "Uploaded: " + dest);
s.disconnect();
} catch (Exception e) {
Log.e("Dumload.uploader[thread]", "JSchException: "+(e.toString()));
sayNullNotification("Dumload upload failed", "Upload failed", e.toString());
}
destroy_notif();
Log.e("Dumload.uploader[thread]", "And now I'm back to life!");
}
| public void run()
{
Looper.prepare();
Log.e("Dumload.Uploader[thread]", "This brought to you from the new thread.");
set_up_notif("Dumload upload: " + dest);
try {
say("Uploading "+(Integer.toString(is.available()))+" bytes");
update_notif("Connecting...");
JSch jsch = new JSch();
jsch.setKnownHosts(homedir + "/known_hosts");
try {
jsch.addIdentity(homedir + "/id_dsa");
} catch (java.lang.Exception e) {
}
try {
jsch.addIdentity(homedir + "/id_dsa_generated");
} catch (java.lang.Exception e) {
}
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String server = prefs.getString("server", "").trim();
String userName = prefs.getString("userName", "").trim();
Integer port = Integer.valueOf(prefs.getString("port", "22"));
Log.d("dbg", userName + "@" + server + ":" + port);
Session s = jsch.getSession(userName, server, port);
s.setUserInfo(this);
s.connect();
Channel channel = s.openChannel("exec");
((ChannelExec)channel).setCommand("scp -t "+dest);
channel.connect();
OutputStream scp_out = channel.getOutputStream();
InputStream scp_in = channel.getInputStream();
update_notif("Starting send...");
/* Okay, BS out of the way. Now go send the file. */
expect_ack(scp_in);
String stfu;
if (dest.lastIndexOf("/") > 0)
stfu = dest.substring(dest.lastIndexOf("/") + 1);
else
stfu = dest;
scp_out.write(("C0644 " + (Integer.toString(is.available())) + " "+stfu+"\n").getBytes());
scp_out.flush();
expect_ack(scp_in);
int total, nbytes;
total = is.available();
nbytes = 0;
int len;
byte[] buf = new byte[4096];
while ((len = is.read(buf, 0, buf.length)) > 0)
{
scp_out.write(buf, 0, len);
nbytes += len;
update_notif(nbytes, total);
}
is.close();
update_notif("Finishing file transfer...");
scp_out.write("\0".getBytes());
scp_out.flush();
expect_ack(scp_in);
channel.disconnect();
update_notif("Preparing to resize image...");
channel = s.openChannel("exec");
((ChannelExec)channel).setCommand("pscale "+dest);
channel.connect();
scp_in = channel.getInputStream();
update_notif("Resizing image...");
while ((len = scp_in.read(buf, 0, buf.length)) > 0)
;
channel.disconnect();
update_notif("Upload complete.");
sayNullNotification("Dumload upload complete: " + dest, "Upload complete", "Uploaded: " + dest);
s.disconnect();
} catch (Exception e) {
Log.e("Dumload.uploader[thread]", "JSchException: "+(e.toString()));
sayNullNotification("Dumload upload failed", "Upload failed", e.toString());
}
destroy_notif();
Log.e("Dumload.uploader[thread]", "And now I'm back to life!");
}
|
diff --git a/sos/sos-platform/src/main/java/sorcer/core/dispatch/ProvisionManager.java b/sos/sos-platform/src/main/java/sorcer/core/dispatch/ProvisionManager.java
index b5b2f7ec..6d24465a 100755
--- a/sos/sos-platform/src/main/java/sorcer/core/dispatch/ProvisionManager.java
+++ b/sos/sos-platform/src/main/java/sorcer/core/dispatch/ProvisionManager.java
@@ -1,260 +1,260 @@
/*
* Copyright 2012 the original author or authors.
* Copyright 2012 SorcerSoft.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 sorcer.core.dispatch;
import net.jini.core.lease.Lease;
import net.jini.space.JavaSpace05;
import sorcer.core.exertion.ExertionEnvelop;
import sorcer.core.provider.Spacer;
import sorcer.core.signature.NetSignature;
import sorcer.ext.Provisioner;
import sorcer.ext.ProvisioningException;
import sorcer.service.*;
import sorcer.service.space.SpaceAccessor;
import java.rmi.RemoteException;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.logging.Logger;
/**
* @author Pawel Rubach
*/
public class ProvisionManager {
private static final Logger logger = Logger.getLogger(ProvisionManager.class.getName());
protected final Set<SignatureElement> servicesToProvision = new LinkedHashSet<SignatureElement>();
private static ProvisionManager instance = null;
private static final int MAX_ATTEMPTS = 2;
public static ProvisionManager getInstance() {
if (instance==null)
instance = new ProvisionManager();
return instance;
}
protected ProvisionManager() {
ThreadGroup provGroup = new ThreadGroup("spacer-provisioning");
provGroup.setDaemon(true);
provGroup.setMaxPriority(Thread.NORM_PRIORITY - 1);
Thread pThread = new Thread(provGroup, new ProvisionThread(), "Provisioner");
pThread.start();
}
public void add(Exertion exertion, SpaceExertDispatcher spaceExertDispatcher) {
NetSignature sig = (NetSignature) exertion.getProcessSignature();
Service service = (Service) Accessor.getService(sig);
// A hack to disable provisioning spacer itself
if (service==null && !sig.getServiceType().getName().equals(Spacer.class.getName())) {
synchronized (servicesToProvision) {
servicesToProvision.add(
new SignatureElement(sig.getServiceType().getName(), sig.getProviderName(),
sig.getVersion(), sig, exertion, spaceExertDispatcher));
}
}
}
protected class ProvisionThread implements Runnable {
public void run() {
Provisioner provisioner = Accessor.getService(Provisioner.class);
while (true) {
if (!servicesToProvision.isEmpty()) {
LinkedHashSet<SignatureElement> copy ;
synchronized (servicesToProvision){
copy = new LinkedHashSet<SignatureElement>(servicesToProvision);
}
Iterator<SignatureElement> it = copy.iterator();
Set<SignatureElement> sigsToRemove = new LinkedHashSet<SignatureElement>();
logger.fine("Services to provision from Spacer/Jobber: "+ servicesToProvision.size());
while (it.hasNext()) {
SignatureElement sigEl = it.next();
// Catalog lookup or use Lookup Service for the particular
// service
Service service = (Service) Accessor.getService(sigEl.getSignature());
if (service == null ) {
+ sigEl.incrementProvisionAttempts();
if (provisioner != null) {
try {
logger.info("Provisioning: "+ sigEl.getSignature());
- sigEl.incrementProvisionAttempts();
service = provisioner.provision(sigEl.getServiceType(), sigEl.getProviderName(), sigEl.getVersion());
if (service!=null) sigsToRemove.add(sigEl);
} catch (ProvisioningException pe) {
logger.severe("Problem provisioning: " +pe.getMessage());
} catch (RemoteException re) {
provisioner = Accessor.getService(Provisioner.class);
String msg = "Problem provisioning "+sigEl.getSignature().getServiceType()
+ " (" + sigEl.getSignature().getProviderName() + ")"
+ " " +re.getMessage();
logger.severe(msg);
}
} else
provisioner = Accessor.getService(Provisioner.class);
if (service == null && sigEl.getProvisionAttempts() > MAX_ATTEMPTS) {
String logMsg = "Provisioning for " + sigEl.getServiceType() + "(" + sigEl.getProviderName()
+ ") tried: " + sigEl.getProvisionAttempts() +" times, provisioning will not be reattempted";
logger.severe(logMsg);
try {
failExertionInSpace(sigEl, new ProvisioningException(logMsg));
sigsToRemove.add(sigEl);
} catch (ExertionException ile) {
logger.severe("Problem trying to remove exception after reattempting to provision");
}
}
} else
sigsToRemove.add(sigEl);
}
if (!sigsToRemove.isEmpty()) {
synchronized (servicesToProvision) {
servicesToProvision.removeAll(sigsToRemove);
}
}
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
}
}
}
}
private void failExertionInSpace(SignatureElement sigEl, Exception exc) throws ExertionException {
logger.info("Setting Failed state for service type: " + sigEl.getServiceType() + " exertion ID: " +
"" + sigEl.getExertion().getId());
ExertionEnvelop ee = ExertionEnvelop.getTemplate(sigEl.getExertion());
ExertionEnvelop result = null;
result = sigEl.getSpaceExertDispatcher().takeEnvelop(ee);
if (result!=null) {
result.state = ExecState.FAILED;
((ServiceExertion)result.exertion).setStatus(ExecState.FAILED);
((ServiceExertion)result.exertion).reportException(exc);
try {
JavaSpace05 space = SpaceAccessor.getSpace();
if (space == null) {
throw new ExertionException("NO exertion space available!");
}
space.write(result, null, Lease.FOREVER);
logger.finer("===========================> written failure envelop: "
+ ee.describe() + "\n to: " + space);
} catch (Exception e) {
e.printStackTrace();
logger.throwing(this.getClass().getName(), "faileExertionInSpace", e);
throw new ExertionException("Problem writing exertion back to space");
}
}
}
private class SignatureElement {
String serviceType;
String providerName;
String version;
Signature signature;
int provisionAttempts=0;
Exertion exertion;
SpaceExertDispatcher spaceExertDispatcher;
private String getServiceType() {
return serviceType;
}
private void setServiceType(String serviceType) {
this.serviceType = serviceType;
}
private String getProviderName() {
return providerName;
}
private void setProviderName(String providerName) {
this.providerName = providerName;
}
private String getVersion() {
return version;
}
private void setVersion(String version) {
this.version = version;
}
private Signature getSignature() {
return signature;
}
private void setSignature(Signature signature) {
this.signature = signature;
}
public int getProvisionAttempts() {
return provisionAttempts;
}
public void incrementProvisionAttempts() {
this.provisionAttempts++;
}
public Exertion getExertion() {
return exertion;
}
public SpaceExertDispatcher getSpaceExertDispatcher() {
return spaceExertDispatcher;
}
private SignatureElement(String serviceType, String providerName, String version, Signature signature,
Exertion exertion, SpaceExertDispatcher spaceExertDispatcher) {
this.serviceType = serviceType;
this.providerName = providerName;
this.version = version;
this.signature = signature;
this.exertion = exertion;
this.spaceExertDispatcher = spaceExertDispatcher;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SignatureElement that = (SignatureElement) o;
if (!providerName.equals(that.providerName)) return false;
if (!serviceType.equals(that.serviceType)) return false;
if (!exertion.equals(that.exertion)) return false;
if (version != null ? !version.equals(that.version) : that.version != null) return false;
return true;
}
@Override
public int hashCode() {
int result = serviceType.hashCode();
result = 31 * result + providerName.hashCode();
result = 31 * result + (version != null ? version.hashCode() : 0);
return result;
}
}
}
| false | true | public void run() {
Provisioner provisioner = Accessor.getService(Provisioner.class);
while (true) {
if (!servicesToProvision.isEmpty()) {
LinkedHashSet<SignatureElement> copy ;
synchronized (servicesToProvision){
copy = new LinkedHashSet<SignatureElement>(servicesToProvision);
}
Iterator<SignatureElement> it = copy.iterator();
Set<SignatureElement> sigsToRemove = new LinkedHashSet<SignatureElement>();
logger.fine("Services to provision from Spacer/Jobber: "+ servicesToProvision.size());
while (it.hasNext()) {
SignatureElement sigEl = it.next();
// Catalog lookup or use Lookup Service for the particular
// service
Service service = (Service) Accessor.getService(sigEl.getSignature());
if (service == null ) {
if (provisioner != null) {
try {
logger.info("Provisioning: "+ sigEl.getSignature());
sigEl.incrementProvisionAttempts();
service = provisioner.provision(sigEl.getServiceType(), sigEl.getProviderName(), sigEl.getVersion());
if (service!=null) sigsToRemove.add(sigEl);
} catch (ProvisioningException pe) {
logger.severe("Problem provisioning: " +pe.getMessage());
} catch (RemoteException re) {
provisioner = Accessor.getService(Provisioner.class);
String msg = "Problem provisioning "+sigEl.getSignature().getServiceType()
+ " (" + sigEl.getSignature().getProviderName() + ")"
+ " " +re.getMessage();
logger.severe(msg);
}
} else
provisioner = Accessor.getService(Provisioner.class);
if (service == null && sigEl.getProvisionAttempts() > MAX_ATTEMPTS) {
String logMsg = "Provisioning for " + sigEl.getServiceType() + "(" + sigEl.getProviderName()
+ ") tried: " + sigEl.getProvisionAttempts() +" times, provisioning will not be reattempted";
logger.severe(logMsg);
try {
failExertionInSpace(sigEl, new ProvisioningException(logMsg));
sigsToRemove.add(sigEl);
} catch (ExertionException ile) {
logger.severe("Problem trying to remove exception after reattempting to provision");
}
}
} else
sigsToRemove.add(sigEl);
}
if (!sigsToRemove.isEmpty()) {
synchronized (servicesToProvision) {
servicesToProvision.removeAll(sigsToRemove);
}
}
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
}
}
}
| public void run() {
Provisioner provisioner = Accessor.getService(Provisioner.class);
while (true) {
if (!servicesToProvision.isEmpty()) {
LinkedHashSet<SignatureElement> copy ;
synchronized (servicesToProvision){
copy = new LinkedHashSet<SignatureElement>(servicesToProvision);
}
Iterator<SignatureElement> it = copy.iterator();
Set<SignatureElement> sigsToRemove = new LinkedHashSet<SignatureElement>();
logger.fine("Services to provision from Spacer/Jobber: "+ servicesToProvision.size());
while (it.hasNext()) {
SignatureElement sigEl = it.next();
// Catalog lookup or use Lookup Service for the particular
// service
Service service = (Service) Accessor.getService(sigEl.getSignature());
if (service == null ) {
sigEl.incrementProvisionAttempts();
if (provisioner != null) {
try {
logger.info("Provisioning: "+ sigEl.getSignature());
service = provisioner.provision(sigEl.getServiceType(), sigEl.getProviderName(), sigEl.getVersion());
if (service!=null) sigsToRemove.add(sigEl);
} catch (ProvisioningException pe) {
logger.severe("Problem provisioning: " +pe.getMessage());
} catch (RemoteException re) {
provisioner = Accessor.getService(Provisioner.class);
String msg = "Problem provisioning "+sigEl.getSignature().getServiceType()
+ " (" + sigEl.getSignature().getProviderName() + ")"
+ " " +re.getMessage();
logger.severe(msg);
}
} else
provisioner = Accessor.getService(Provisioner.class);
if (service == null && sigEl.getProvisionAttempts() > MAX_ATTEMPTS) {
String logMsg = "Provisioning for " + sigEl.getServiceType() + "(" + sigEl.getProviderName()
+ ") tried: " + sigEl.getProvisionAttempts() +" times, provisioning will not be reattempted";
logger.severe(logMsg);
try {
failExertionInSpace(sigEl, new ProvisioningException(logMsg));
sigsToRemove.add(sigEl);
} catch (ExertionException ile) {
logger.severe("Problem trying to remove exception after reattempting to provision");
}
}
} else
sigsToRemove.add(sigEl);
}
if (!sigsToRemove.isEmpty()) {
synchronized (servicesToProvision) {
servicesToProvision.removeAll(sigsToRemove);
}
}
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
}
}
}
|
diff --git a/src/main/java/crowdtrust/BinaryAccuracy.java b/src/main/java/crowdtrust/BinaryAccuracy.java
index db69a92..c810ee6 100644
--- a/src/main/java/crowdtrust/BinaryAccuracy.java
+++ b/src/main/java/crowdtrust/BinaryAccuracy.java
@@ -1,101 +1,101 @@
package crowdtrust;
import java.util.ArrayList;
import java.util.Collection;
import org.apache.commons.math3.distribution.BetaDistribution;
import org.apache.commons.math3.distribution.NormalDistribution;
import be.ac.ulg.montefiore.run.jahmm.ObservationReal;
import be.ac.ulg.montefiore.run.jahmm.OpdfGaussian;
public class BinaryAccuracy extends Accuracy {
private double truePositive;
private double trueNegative;
private int negativeN;
private int positiveN;
public BinaryAccuracy(double pos, double neg, int numpos, int numneg){
truePositive = pos;
trueNegative = neg;
negativeN = numneg;
positiveN = numpos;
}
boolean expert(double threshold){
NormalDistribution n = new NormalDistribution();
double d = (n.inverseCumulativeProbability(trueNegative) +
n.inverseCumulativeProbability(1 - truePositive))/2;
return d > threshold;
}
public int getPositiveN(){
return this.positiveN;
}
public int getNegativeN(){
return this.negativeN;
}
public double getTruePositive() {
return this.truePositive;
}
public double getTrueNegative() {
return this.trueNegative;
}
public void setTruePositive(double n) {
this.truePositive = n;
}
public void setTrueNegative(double n) {
this.trueNegative = n;
}
void incrementPositiveN(){
positiveN++;
n++;
}
void incrementNegativeN(){
negativeN++;
n++;
}
@Override
Byte[] serialise() {
// TODO Auto-generated method stub
return null;
}
@Override
protected double variance() {
double alphaPos = truePositive * positiveN + 1;
double betaPos = positiveN - alphaPos + 1;
double alphaNeg = trueNegative * negativeN + 1;
double betaNeg = negativeN - alphaNeg + 1;
BetaDistribution posCurve = new BetaDistribution(alphaPos, betaPos);
BetaDistribution negCurve = new BetaDistribution(alphaNeg, betaNeg);
double maxP = alphaPos/positiveN;
double maxN = alphaNeg/negativeN;
Collection <ObservationReal> peak = new ArrayList <ObservationReal>();
- for (double p = -0.1; p < 0.2; p+=0.1){
- for (double n = -0.1; n < 0.2; n+=0.1){
+ for (double p = -0.5; p < 0.6; p+=0.5){
+ for (double n = -0.5; n < 0.6; n+=0.5){
peak.add(new ObservationReal(
posCurve.density(maxP+p)*negCurve.density(maxN+n)
)
);
}
}
OpdfGaussian estimate = new OpdfGaussian();
estimate.fit(peak);
return estimate.variance();
}
}
| true | true | protected double variance() {
double alphaPos = truePositive * positiveN + 1;
double betaPos = positiveN - alphaPos + 1;
double alphaNeg = trueNegative * negativeN + 1;
double betaNeg = negativeN - alphaNeg + 1;
BetaDistribution posCurve = new BetaDistribution(alphaPos, betaPos);
BetaDistribution negCurve = new BetaDistribution(alphaNeg, betaNeg);
double maxP = alphaPos/positiveN;
double maxN = alphaNeg/negativeN;
Collection <ObservationReal> peak = new ArrayList <ObservationReal>();
for (double p = -0.1; p < 0.2; p+=0.1){
for (double n = -0.1; n < 0.2; n+=0.1){
peak.add(new ObservationReal(
posCurve.density(maxP+p)*negCurve.density(maxN+n)
)
);
}
}
OpdfGaussian estimate = new OpdfGaussian();
estimate.fit(peak);
return estimate.variance();
}
| protected double variance() {
double alphaPos = truePositive * positiveN + 1;
double betaPos = positiveN - alphaPos + 1;
double alphaNeg = trueNegative * negativeN + 1;
double betaNeg = negativeN - alphaNeg + 1;
BetaDistribution posCurve = new BetaDistribution(alphaPos, betaPos);
BetaDistribution negCurve = new BetaDistribution(alphaNeg, betaNeg);
double maxP = alphaPos/positiveN;
double maxN = alphaNeg/negativeN;
Collection <ObservationReal> peak = new ArrayList <ObservationReal>();
for (double p = -0.5; p < 0.6; p+=0.5){
for (double n = -0.5; n < 0.6; n+=0.5){
peak.add(new ObservationReal(
posCurve.density(maxP+p)*negCurve.density(maxN+n)
)
);
}
}
OpdfGaussian estimate = new OpdfGaussian();
estimate.fit(peak);
return estimate.variance();
}
|
diff --git a/src/com/vesalaakso/rbb/model/TileMapObject.java b/src/com/vesalaakso/rbb/model/TileMapObject.java
index 0b0f007..7cbe14b 100644
--- a/src/com/vesalaakso/rbb/model/TileMapObject.java
+++ b/src/com/vesalaakso/rbb/model/TileMapObject.java
@@ -1,112 +1,112 @@
package com.vesalaakso.rbb.model;
import java.util.Properties;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.geom.Polygon;
import org.newdawn.slick.tiled.GroupObject;
import com.vesalaakso.rbb.model.exceptions.MapException;
/**
* Represents a single GroupObject, in an easier-to-digest way.
*
* @author Vesa Laakso
*/
public class TileMapObject {
/** The index of this object */
public final int index;
/** The name of this object */
public final String name;
/** The type of this object */
public final TileMapObjectType type;
/** The object type of this object */
public final GroupObject.ObjectType objectType;
/** The x-coordinate of this object */
public final int x;
/** The y-coordinate of this object */
public final int y;
/** The width of this object */
public final int width;
/** The height of this object */
public final int height;
/** the properties of this object */
public final Properties props;
/** The underlying GroupObject */
private final GroupObject groupObject;
/**
* Constructs a new object based on the given <code>GroupObject</code>.
*
* @param obj
* the GroupObject to base this new object on
* @throws MapException
* if the type of this object was unknown.
*/
public TileMapObject(GroupObject obj) throws MapException {
groupObject = obj;
index = obj.index;
name = obj.name;
try {
- type = TileMapObjectType.valueOf(obj.name.toUpperCase());
+ type = TileMapObjectType.valueOf(obj.type.toUpperCase());
}
catch (IllegalArgumentException e) {
throw new MapException("Unknown object type: " + obj.type, e);
}
objectType = obj.getObjectType();
x = obj.x;
y = obj.y;
width = obj.width;
height = obj.height;
props = obj.props;
}
/**
* Returns the <code>Polygon</code> used to construct a polygon shape, if
* this shape is indeed a polygon.
*
* @return <code>Polygon</code> constructing this object
* @throws MapException
* if the shape was not a polygon
*/
public Polygon getPolygon() throws MapException {
if (objectType != GroupObject.ObjectType.POLYGON) {
String str = String.format(
"The object \"%s\" at (%d, %d) was not a polygon!",
name, x, y);
throw new MapException(str);
}
try {
return groupObject.getPolygon();
}
catch (SlickException e) {
throw new MapException(String.format(
"Couldn't get polygon for the object \"%s\" at (%d, %d)",
name, x, y), e);
}
}
/**
* Gets the <code>String</code> representation of this
* <code>TileMapObject</code>.
*/
@Override
public String toString() {
String str = "TileMapObject={"
+ "index:" + index
+ ",name:" + name
+ ",type:" + type
+ ",objectType:" + objectType
+ ",x:" + x
+ ",y:" + y
+ ",width:" + width
+ ",height:" + height
+ ",props:" + props
+ "}";
return str;
}
}
| true | true | public TileMapObject(GroupObject obj) throws MapException {
groupObject = obj;
index = obj.index;
name = obj.name;
try {
type = TileMapObjectType.valueOf(obj.name.toUpperCase());
}
catch (IllegalArgumentException e) {
throw new MapException("Unknown object type: " + obj.type, e);
}
objectType = obj.getObjectType();
x = obj.x;
y = obj.y;
width = obj.width;
height = obj.height;
props = obj.props;
}
| public TileMapObject(GroupObject obj) throws MapException {
groupObject = obj;
index = obj.index;
name = obj.name;
try {
type = TileMapObjectType.valueOf(obj.type.toUpperCase());
}
catch (IllegalArgumentException e) {
throw new MapException("Unknown object type: " + obj.type, e);
}
objectType = obj.getObjectType();
x = obj.x;
y = obj.y;
width = obj.width;
height = obj.height;
props = obj.props;
}
|
diff --git a/src/org/pit/fetegeo/importer/processors/TagProcessor.java b/src/org/pit/fetegeo/importer/processors/TagProcessor.java
index 0a5a1e9..8f9018c 100644
--- a/src/org/pit/fetegeo/importer/processors/TagProcessor.java
+++ b/src/org/pit/fetegeo/importer/processors/TagProcessor.java
@@ -1,196 +1,207 @@
package org.pit.fetegeo.importer.processors;
import org.openstreetmap.osmosis.core.domain.v0_6.Entity;
import org.openstreetmap.osmosis.core.domain.v0_6.EntityType;
import org.openstreetmap.osmosis.core.domain.v0_6.Tag;
import org.pit.fetegeo.importer.objects.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* Author: Pit Apps
* Date: 10/26/12
* Time: 3:48 PM
*/
public class TagProcessor {
private List<GenericTag> tags;
public List<GenericTag> process(Entity entity) {
String key, value;
tags = new ArrayList<GenericTag>();
for (Tag tag : entity.getTags()) {
key = tag.getKey();
value = tag.getValue();
if (key.equalsIgnoreCase("place") || (key.equalsIgnoreCase("boundary") && value.equalsIgnoreCase("administrative"))) {
processPlace(entity);
break;
} else if (key.equalsIgnoreCase("highway")) {
// TODO: limit this to only a couple values?
processHighway(entity);
break;
} else if (key.startsWith("addr")) {
processAddress(entity); // TODO: IGNORE THIS TAG?
break;
}
}
return tags;
}
private void addToTypeList(String type) {
Map<String, Long> typeMap = GenericTag.getTypeMap();
if (!typeMap.containsKey(type)) {
typeMap.put(type, (long) typeMap.size());
}
}
private void processPlace(Entity entity) {
Place place = new Place();
List<Name> nameList = new ArrayList<Name>();
String key, value;
boolean isCountry = false, isBoundary = false;
place.setId(entity.getId());
place.setOriginEntity(entity.getType());
for (Tag tag : entity.getTags()) {
key = tag.getKey();
value = tag.getValue();
if (key.equalsIgnoreCase("place")) {
if (place.getType() == null || place.getType().isEmpty()) { // don't overwrite boundary type
place.setType(value);
if (value.equalsIgnoreCase("country")) { // we're dealing with a country here
isCountry = true;
}
}
} else if (key.equalsIgnoreCase("boundary") && value.equalsIgnoreCase("administrative")) {
place.setType("boundary");
} else if (key.startsWith("name:") || key.endsWith("name") || key.equalsIgnoreCase("place_name")) {
nameList.add(new Name(value, key));
} else if (key.equalsIgnoreCase("population")) {
- place.setPopulation(Long.valueOf(value));
+ try {
+ place.setPopulation(Long.valueOf(value));
+ }
+ // Some population numbers are given as '#### (YYYY)'...
+ catch (NumberFormatException nfe) {
+ value = value.replaceAll("\\([^\\(]*\\)", "");
+ try {
+ place.setPopulation(Long.valueOf(value));
+ } catch (NumberFormatException nfe2) {
+ // Not a number?
+ }
+ }
} else if (key.equalsIgnoreCase("postal_code")) {
processPostalCode(entity, tag, place);
}
// find the boundaries of a country. Not all admin_level=2 relations are countries though.
else if (key.equalsIgnoreCase("admin_level") && value.equalsIgnoreCase("2")) {
if (entity.getType().equals(EntityType.Relation)) {
isBoundary = true;
}
}
}
place.setNameList(nameList);
// Set the country id if it's a country (we're using english names)
if (isCountry || isBoundary) {
Long enISOCode = LanguageProcessor.findLanguageId("en");
for (Name name : nameList) {
// If the name is in english, proceed
if (!name.isLocalised() || (name.getLanguageId() != null && name.getLanguageId().equals(enISOCode))) {
Long countryId = CountryCodeProcessor.findCountryId(name.getName());
if (countryId != null) {
place.setCountryId(countryId);
break;
}
}
}
}
// If this tag has a new type, add it to our list
addToTypeList(place.getType());
// Add all tags to the list
tags.add(place);
}
private void processHighway(Entity entity) {
Highway highway = new Highway();
List<Name> nameList = new ArrayList<Name>();
String key, value;
highway.setId(entity.getId());
highway.setOriginEntity(entity.getType());
for (Tag tag : entity.getTags()) {
key = tag.getKey();
value = tag.getValue();
if (key.equalsIgnoreCase("highway")) {
highway.setType(value);
} else if (key.startsWith("name:") || key.endsWith("name")) {
nameList.add(new Name(value, key));
} else if (key.equalsIgnoreCase("ref")) {
highway.setRef(value);
} else if (key.equalsIgnoreCase("postal_code")) {
processPostalCode(entity, tag, highway);
}
}
// We don't want highways without names
if (nameList.isEmpty() && highway.getRef() == null) {
return;
}
highway.setNameList(nameList);
addToTypeList(highway.getType());
tags.add(highway);
}
private void processAddress(Entity entity) {
Address address = new Address();
List<Name> nameList = new ArrayList<Name>();
String key, value;
address.setId(entity.getId());
address.setOriginEntity(entity.getType());
address.setType("addr");
for (Tag tag : entity.getTags()) {
key = tag.getKey();
value = tag.getValue();
if (key.startsWith("addr:")) {
String addressType = key.split(":")[1];
if (addressType.equalsIgnoreCase("housenumber")) {
address.setHouseNumber(value);
} else if (addressType.equalsIgnoreCase("street")) {
address.setStreetName(value);
}
} else if (key.startsWith("name:") || key.endsWith("name")) {
nameList.add(new Name(value, key));
}
if (key.equalsIgnoreCase("postal_code") || key.equalsIgnoreCase("addr:postcode")) { // TODO: do we really need these? probably not! (too specific)
processPostalCode(entity, tag, address);
}
}
// We don't want addresses without names AND refs
if (nameList.isEmpty() || address.getRef() == null) {
return;
}
address.setNameList(nameList);
tags.add(address);
}
// We allow for duplicate postcodes so that we can then store all locations for a given post_code (and combine the area using PostGIS)
private void processPostalCode(Entity entity, Tag tag, GenericTag genericTag) {
String[] values = tag.getValue().split(",|;"); // sometimes we have more than one postcode separated by a comma or semi-colon
for (String code : values) {
PostalCode postalCode = new PostalCode(code.trim()); // trim whitespace as some postcodes are badly formatted
postalCode.setId(entity.getId());
postalCode.setType(entity.getType().toString());
postalCode.setOriginEntity(entity.getType());
tags.add(postalCode);
genericTag.setPostCodeId(postalCode.getPostCodeId());
}
}
}
| true | true | private void processPlace(Entity entity) {
Place place = new Place();
List<Name> nameList = new ArrayList<Name>();
String key, value;
boolean isCountry = false, isBoundary = false;
place.setId(entity.getId());
place.setOriginEntity(entity.getType());
for (Tag tag : entity.getTags()) {
key = tag.getKey();
value = tag.getValue();
if (key.equalsIgnoreCase("place")) {
if (place.getType() == null || place.getType().isEmpty()) { // don't overwrite boundary type
place.setType(value);
if (value.equalsIgnoreCase("country")) { // we're dealing with a country here
isCountry = true;
}
}
} else if (key.equalsIgnoreCase("boundary") && value.equalsIgnoreCase("administrative")) {
place.setType("boundary");
} else if (key.startsWith("name:") || key.endsWith("name") || key.equalsIgnoreCase("place_name")) {
nameList.add(new Name(value, key));
} else if (key.equalsIgnoreCase("population")) {
place.setPopulation(Long.valueOf(value));
} else if (key.equalsIgnoreCase("postal_code")) {
processPostalCode(entity, tag, place);
}
// find the boundaries of a country. Not all admin_level=2 relations are countries though.
else if (key.equalsIgnoreCase("admin_level") && value.equalsIgnoreCase("2")) {
if (entity.getType().equals(EntityType.Relation)) {
isBoundary = true;
}
}
}
place.setNameList(nameList);
// Set the country id if it's a country (we're using english names)
if (isCountry || isBoundary) {
Long enISOCode = LanguageProcessor.findLanguageId("en");
for (Name name : nameList) {
// If the name is in english, proceed
if (!name.isLocalised() || (name.getLanguageId() != null && name.getLanguageId().equals(enISOCode))) {
Long countryId = CountryCodeProcessor.findCountryId(name.getName());
if (countryId != null) {
place.setCountryId(countryId);
break;
}
}
}
}
// If this tag has a new type, add it to our list
addToTypeList(place.getType());
// Add all tags to the list
tags.add(place);
}
| private void processPlace(Entity entity) {
Place place = new Place();
List<Name> nameList = new ArrayList<Name>();
String key, value;
boolean isCountry = false, isBoundary = false;
place.setId(entity.getId());
place.setOriginEntity(entity.getType());
for (Tag tag : entity.getTags()) {
key = tag.getKey();
value = tag.getValue();
if (key.equalsIgnoreCase("place")) {
if (place.getType() == null || place.getType().isEmpty()) { // don't overwrite boundary type
place.setType(value);
if (value.equalsIgnoreCase("country")) { // we're dealing with a country here
isCountry = true;
}
}
} else if (key.equalsIgnoreCase("boundary") && value.equalsIgnoreCase("administrative")) {
place.setType("boundary");
} else if (key.startsWith("name:") || key.endsWith("name") || key.equalsIgnoreCase("place_name")) {
nameList.add(new Name(value, key));
} else if (key.equalsIgnoreCase("population")) {
try {
place.setPopulation(Long.valueOf(value));
}
// Some population numbers are given as '#### (YYYY)'...
catch (NumberFormatException nfe) {
value = value.replaceAll("\\([^\\(]*\\)", "");
try {
place.setPopulation(Long.valueOf(value));
} catch (NumberFormatException nfe2) {
// Not a number?
}
}
} else if (key.equalsIgnoreCase("postal_code")) {
processPostalCode(entity, tag, place);
}
// find the boundaries of a country. Not all admin_level=2 relations are countries though.
else if (key.equalsIgnoreCase("admin_level") && value.equalsIgnoreCase("2")) {
if (entity.getType().equals(EntityType.Relation)) {
isBoundary = true;
}
}
}
place.setNameList(nameList);
// Set the country id if it's a country (we're using english names)
if (isCountry || isBoundary) {
Long enISOCode = LanguageProcessor.findLanguageId("en");
for (Name name : nameList) {
// If the name is in english, proceed
if (!name.isLocalised() || (name.getLanguageId() != null && name.getLanguageId().equals(enISOCode))) {
Long countryId = CountryCodeProcessor.findCountryId(name.getName());
if (countryId != null) {
place.setCountryId(countryId);
break;
}
}
}
}
// If this tag has a new type, add it to our list
addToTypeList(place.getType());
// Add all tags to the list
tags.add(place);
}
|
diff --git a/src/java/org/jivesoftware/sparkimpl/plugin/gateways/transports/TransportUtils.java b/src/java/org/jivesoftware/sparkimpl/plugin/gateways/transports/TransportUtils.java
index 00bbbfe6..5ef3f21b 100644
--- a/src/java/org/jivesoftware/sparkimpl/plugin/gateways/transports/TransportUtils.java
+++ b/src/java/org/jivesoftware/sparkimpl/plugin/gateways/transports/TransportUtils.java
@@ -1,217 +1,217 @@
/**
* $Revision: $
* $Date: $
*
* Copyright (C) 2006 Jive Software. All rights reserved.
*
* This software is published under the terms of the GNU Lesser Public License (LGPL),
* a copy of which is included in this distribution.
*/
package org.jivesoftware.sparkimpl.plugin.gateways.transports;
import org.jivesoftware.smack.PacketCollector;
import org.jivesoftware.smack.SmackConfiguration;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.PacketIDFilter;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.PacketExtension;
import org.jivesoftware.smack.packet.Registration;
import org.jivesoftware.smack.util.StringUtils;
import org.jivesoftware.smackx.PrivateDataManager;
import org.jivesoftware.smackx.ServiceDiscoveryManager;
import org.jivesoftware.smackx.packet.DiscoverInfo;
import org.jivesoftware.spark.SparkManager;
import org.jivesoftware.spark.util.TaskEngine;
import org.jivesoftware.spark.util.log.Log;
import org.jivesoftware.sparkimpl.plugin.gateways.GatewayPrivateData;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
/**
* Handles some basic handling of
*/
public class TransportUtils {
private static Map<String, Transport> transports = new HashMap<String, Transport>();
private static GatewayPrivateData gatewayPreferences;
private TransportUtils() {
}
static {
PrivateDataManager.addPrivateDataProvider(GatewayPrivateData.ELEMENT, GatewayPrivateData.NAMESPACE, new GatewayPrivateData.ConferencePrivateDataProvider());
final Runnable loadGateways = new Runnable() {
public void run() {
try {
PrivateDataManager pdm = SparkManager.getSessionManager().getPersonalDataManager();
gatewayPreferences = (GatewayPrivateData)pdm.getPrivateData(GatewayPrivateData.ELEMENT, GatewayPrivateData.NAMESPACE);
}
catch (XMPPException e) {
Log.error("Unable to load private data for Gateways", e);
}
}
};
TaskEngine.getInstance().submit(loadGateways);
}
public static boolean autoJoinService(String serviceName) {
return gatewayPreferences.autoLogin(serviceName);
}
public static void setAutoJoin(String serviceName, boolean autoJoin) {
gatewayPreferences.addService(serviceName, autoJoin);
PrivateDataManager pdm = SparkManager.getSessionManager().getPersonalDataManager();
try {
pdm.setPrivateData(gatewayPreferences);
}
catch (XMPPException e) {
Log.error(e);
}
}
public static Transport getTransport(String serviceName) {
// Return transport.
if (transports.containsKey(serviceName)) {
return transports.get(serviceName);
}
return null;
}
/**
* Returns true if the jid is from a gateway.
* @param jid the jid.
* @return true if the jid is from a gateway.
*/
public static boolean isFromGateway(String jid) {
jid = StringUtils.parseBareAddress(jid);
String serviceName = StringUtils.parseServer(jid);
return transports.containsKey(serviceName);
}
public static void addTransport(String serviceName, Transport transport) {
transports.put(serviceName, transport);
}
public static Collection<Transport> getTransports() {
return transports.values();
}
/**
* Checks if the user is registered with a gateway.
*
* @param con the XMPPConnection.
* @param transport the transport.
* @return true if the user is registered with the transport.
*/
public static boolean isRegistered(XMPPConnection con, Transport transport) {
if (!con.isConnected()) {
return false;
}
ServiceDiscoveryManager discoveryManager = ServiceDiscoveryManager.getInstanceFor(con);
try {
DiscoverInfo info = discoveryManager.discoverInfo(transport.getServiceName());
return info.containsFeature("jabber:iq:registered");
}
catch (XMPPException e) {
Log.error(e);
}
return false;
}
/**
* Registers a user with a gateway.
*
* @param con the XMPPConnection.
* @param gatewayDomain the domain of the gateway (service name)
* @param username the username.
* @param password the password.
* @param nickname the nickname.
* @throws XMPPException thrown if there was an issue registering with the gateway.
*/
public static void registerUser(XMPPConnection con, String gatewayDomain, String username, String password, String nickname) throws XMPPException {
Registration registration = new Registration();
registration.setType(IQ.Type.SET);
registration.setTo(gatewayDomain);
registration.addExtension(new GatewayRegisterExtension());
Map<String, String> attributes = new HashMap<String, String>();
if (username != null) {
attributes.put("username", username);
}
if (password != null) {
attributes.put("password", password);
}
if (nickname != null) {
- attributes.put("nickname", nickname);
+ attributes.put("nick", nickname);
}
registration.setAttributes(attributes);
PacketCollector collector = con.createPacketCollector(new PacketIDFilter(registration.getPacketID()));
con.sendPacket(registration);
IQ response = (IQ)collector.nextResult(SmackConfiguration.getPacketReplyTimeout());
collector.cancel();
if (response == null) {
throw new XMPPException("Server timed out");
}
if (response.getType() == IQ.Type.ERROR) {
throw new XMPPException("Error registering user", response.getError());
}
}
/**
* @param con the XMPPConnection.
* @param gatewayDomain the domain of the gateway (service name)
* @throws XMPPException thrown if there was an issue unregistering with the gateway.
*/
public static void unregister(XMPPConnection con, String gatewayDomain) throws XMPPException {
Registration registration = new Registration();
registration.setType(IQ.Type.SET);
registration.setTo(gatewayDomain);
Map<String,String> map = new HashMap<String,String>();
map.put("remove", "");
registration.setAttributes(map);
PacketCollector collector = con.createPacketCollector(new PacketIDFilter(registration.getPacketID()));
con.sendPacket(registration);
IQ response = (IQ)collector.nextResult(SmackConfiguration.getPacketReplyTimeout());
collector.cancel();
if (response == null) {
throw new XMPPException("Server timed out");
}
if (response.getType() == IQ.Type.ERROR) {
throw new XMPPException("Error registering user", response.getError());
}
}
static class GatewayRegisterExtension implements PacketExtension {
public String getElementName() {
return "x";
}
public String getNamespace() {
return "jabber:iq:gateway:register";
}
public String toXML() {
StringBuilder builder = new StringBuilder();
builder.append("<").append(getElementName()).append(" xmlns=\"").append(getNamespace()).append(
"\"/>");
return builder.toString();
}
}
}
| true | true | public static void registerUser(XMPPConnection con, String gatewayDomain, String username, String password, String nickname) throws XMPPException {
Registration registration = new Registration();
registration.setType(IQ.Type.SET);
registration.setTo(gatewayDomain);
registration.addExtension(new GatewayRegisterExtension());
Map<String, String> attributes = new HashMap<String, String>();
if (username != null) {
attributes.put("username", username);
}
if (password != null) {
attributes.put("password", password);
}
if (nickname != null) {
attributes.put("nickname", nickname);
}
registration.setAttributes(attributes);
PacketCollector collector = con.createPacketCollector(new PacketIDFilter(registration.getPacketID()));
con.sendPacket(registration);
IQ response = (IQ)collector.nextResult(SmackConfiguration.getPacketReplyTimeout());
collector.cancel();
if (response == null) {
throw new XMPPException("Server timed out");
}
if (response.getType() == IQ.Type.ERROR) {
throw new XMPPException("Error registering user", response.getError());
}
}
| public static void registerUser(XMPPConnection con, String gatewayDomain, String username, String password, String nickname) throws XMPPException {
Registration registration = new Registration();
registration.setType(IQ.Type.SET);
registration.setTo(gatewayDomain);
registration.addExtension(new GatewayRegisterExtension());
Map<String, String> attributes = new HashMap<String, String>();
if (username != null) {
attributes.put("username", username);
}
if (password != null) {
attributes.put("password", password);
}
if (nickname != null) {
attributes.put("nick", nickname);
}
registration.setAttributes(attributes);
PacketCollector collector = con.createPacketCollector(new PacketIDFilter(registration.getPacketID()));
con.sendPacket(registration);
IQ response = (IQ)collector.nextResult(SmackConfiguration.getPacketReplyTimeout());
collector.cancel();
if (response == null) {
throw new XMPPException("Server timed out");
}
if (response.getType() == IQ.Type.ERROR) {
throw new XMPPException("Error registering user", response.getError());
}
}
|
diff --git a/src/java/drbd/utilities/Tools.java b/src/java/drbd/utilities/Tools.java
index 743decca..4eb8578d 100644
--- a/src/java/drbd/utilities/Tools.java
+++ b/src/java/drbd/utilities/Tools.java
@@ -1,2658 +1,2660 @@
/*
* This file is part of DRBD Management Console by LINBIT HA-Solutions GmbH
* written by Rasto Levrinc.
*
* Copyright (C) 2009, LINBIT HA-Solutions GmbH.
*
* DRBD Management Console 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, or (at your option)
* any later version.
*
* DRBD Management Console 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 drbd; see the file COPYING. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package drbd.utilities;
import drbd.data.ConfigData;
import drbd.data.Host;
import drbd.data.Cluster;
import drbd.data.Clusters;
import drbd.data.DrbdGuiXML;
import drbd.configs.DistResource;
import drbd.gui.resources.DrbdResourceInfo;
import drbd.gui.resources.Info;
import drbd.gui.resources.ServiceInfo;
import drbd.gui.ClusterBrowser;
import drbd.gui.GUIData;
import drbd.gui.dialog.ConfirmDialog;
import drbd.Exceptions;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.util.regex.PatternSyntaxException;
import java.util.List;
import java.util.ArrayList;
import java.util.ResourceBundle;
import java.util.Properties;
import java.util.Locale;
import java.util.Enumeration;
import java.util.Map;
import java.util.HashMap;
import java.util.Random;
import java.util.Set;
import java.util.Collection;
import java.util.TreeSet;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.io.File;
import java.io.InputStream;
import java.io.FileNotFoundException;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.JEditorPane;
import javax.swing.JScrollPane;
import javax.swing.border.TitledBorder;
import javax.swing.BorderFactory;
import javax.swing.JTextArea;
import javax.swing.DefaultListModel;
import javax.swing.text.html.HTMLDocument;
import javax.swing.UIManager;
import javax.swing.JTable;
import javax.swing.JCheckBox;
import javax.swing.SwingUtilities;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.DefaultTableColumnModel;
import javax.swing.JComponent;
import javax.swing.JPopupMenu;
import java.awt.Component;
import java.awt.Color;
import java.awt.Font;
import java.awt.Dimension;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.Cursor;
import java.awt.image.MemoryImageSource;
import java.awt.Image;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.GraphicsConfiguration;
import java.awt.Insets;
import java.awt.event.KeyEvent;
import java.awt.event.KeyAdapter;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.FileReader;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URI;
import java.net.InetAddress;
import java.lang.reflect.InvocationTargetException;
import java.net.URLClassLoader;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
/**
* This class provides tools, that are not classified.
*
* @author Rasto Levrinc
* @version $Id$
*
*/
public final class Tools {
/** Singleton. */
private static Tools instance = null;
/** Release version. */
private static String release = null;
/** Debug level. */
private static int debugLevel = -1;
/** Whether the warnings should be shown. */
private static boolean appWarning;
/** Whether application errors should show a dialog. */
private static boolean appError;
/** Map with all warnings, so that they don't appear more than once. */
private static Set<String> appWarningHash = new HashSet<String>();
/** Map with all errors, so that they don't appear more than once. */
private static Set<String> appErrorHash = new HashSet<String>();
/** Image icon cache. */
private static Map<String, ImageIcon> imageIcons =
new HashMap<String, ImageIcon>();
/** Locales. */
private static String localeLang = ""; //TODO: not needed?
/** Locales. */
private static String localeCountry = ""; //TODO: not needed?
/** Resource bundle. */
private static ResourceBundle resource = null;
/** Application defaults bundle. */
private static ResourceBundle resourceAppDefaults = null;
/** Config data object. */
private static ConfigData configData;
/** Gui data object. */
private static GUIData guiData;
/** Drbd gui xml object. */
private static DrbdGuiXML drbdGuiXML = new DrbdGuiXML();
/** String that starts error messages. */
private static final String ERROR_STRING = "ERROR: ";
/** String that starts info messages. */
private static final String INFO_STRING = "INFO: ";
/** String that starts debug messages. */
private static final String DEBUG_STRING = "DEBUG: ";
/** string that starts application warnings. */
private static final String APPWARNING_STRING = "APPWARNING: ";
/** String that starts application errors. */
private static final String APPERROR_STRING = "APPERROR: ";
/** Default dialog panel width. */
private static final int DIALOG_PANEL_WIDTH = 400;
/** Default dialog panel height. */
private static final int DIALOG_PANEL_HEIGHT = 300;
/** Default dialog panel size. */
private static final Dimension DIALOG_PANEL_SIZE = new Dimension(
DIALOG_PANEL_WIDTH,
DIALOG_PANEL_HEIGHT);
/** Previous index in the scrolling menu. */
private static volatile int prevScrollingMenuIndex = -1;
/** Text/html mime type. */
public static final String MIME_TYPE_TEXT_HTML = "text/html";
/** Text/plain mime type. */
public static final String MIME_TYPE_TEXT_PLAIN = "text/plain";
/** Pattern that matches a number and unit. */
private static final Pattern UNIT_PATTERN = Pattern.compile("(\\d*)(\\D*)");
/** Random number generator. */
private static final Random RANDOM = new Random();
/** Hash mit classes from plugin. */
private static final Map<String, RemotePlugin> PLUGIN_OBJECTS =
new HashMap<String, RemotePlugin>();
/** Local plugin directory. */
private static final String PLUGIN_DIR = System.getProperty("user.home")
+ "/.drbd-mc/plugins/";
/** Remote plugin location. */
private static final String PLUGIN_LOCATION =
"oss.linbit.com/drbd-mc/drbd-mc-plugins/";
/** Private constructor. */
private Tools() {
/* no instantiation possible. */
}
/** This is to make this class a singleton. */
public static Tools getInstance() {
synchronized (Tools.class) {
if (instance == null) {
instance = new Tools();
}
}
return instance;
}
/** Inits this class. */
public static void init() {
setDefaults();
configData = new ConfigData();
guiData = new GUIData();
}
/**
* Returns an ImageIcon, or null if the path was invalid.
*
* return image icon object.
*/
public static ImageIcon createImageIcon(final String imageFilename) {
final ImageIcon imageIcon = imageIcons.get(imageFilename);
if (imageIcon != null) {
return imageIcon;
}
final java.net.URL imgURL =
Tools.class.getResource("/images/" + imageFilename);
if (imgURL == null) {
Tools.appWarning("Couldn't find image: " + imageFilename);
return null;
} else {
final ImageIcon newIcon = new ImageIcon(imgURL);
imageIcons.put(imageFilename, newIcon);
return newIcon;
}
}
/** Returns the drbd gui release version. */
public static String getRelease() {
if (release != null) {
return release;
}
final Properties p = new Properties();
try {
p.load(Tools.class.getResourceAsStream("/drbd/release.properties"));
release = p.getProperty("release");
return release;
} catch (IOException e) {
appError("cannot open release file", "", e);
return "unknown";
}
}
/** Prints info message to the stdout. */
public static void info(final String msg) {
System.out.println(INFO_STRING + msg);
}
/** Sets defaults from AppDefaults bundle. */
public static void setDefaults() {
debugLevel = getDefaultInt("DebugLevel");
if (getDefault("AppWarning").equals("y")) {
appWarning = true;
}
if (getDefault("AppError").equals("y")) {
appError = true;
}
localeLang = getDefault("Locale.Lang");
localeCountry = getDefault("Locale.Country");
}
/** Increments the debug level. */
public static void incrementDebugLevel() {
debugLevel++;
info("debug level: " + debugLevel);
}
/** Decrements the debug level. */
public static void decrementDebugLevel() {
debugLevel--;
info("debug level: " + debugLevel);
}
/**
* Sets debug level.
*
* @param level
* debug level usually from 0 to 2. 0 means no debug output.
*/
public static void setDebugLevel(final int level) {
debugLevel = level;
}
/**
* Prints debug message to the stdout.
*
* @param msg
* debug message
*/
private static void debug(final String msg) {
if (debugLevel > 0) {
System.out.println(DEBUG_STRING + msg + " (drbd.utilities.Tools)");
}
}
/**
* Prints debug message to the stdout. Only messages with level smaller
* or equal than debug level will be printed.
*
* @param msg
* debug message
*
* @param level
* level of this message.
*/
private static void debug(final String msg, final int level) {
if (level <= debugLevel) {
System.out.println(DEBUG_STRING
+ "(" + level + ") "
+ msg + " (drbd.utilities.Tools)");
}
}
/**
* Prints debug message to the stdout.
*
* @param object
* object from which this message originated. Use "this" by
* caller for this.
* @param msg
* debug message
*/
public static void debug(final Object object, final String msg) {
if (debugLevel > -1) {
if (object == null) {
System.out.println(DEBUG_STRING + msg);
} else {
System.out.println(DEBUG_STRING + msg
+ " (" + object.getClass().getName() + ")");
}
}
}
/**
* Prints debug message to the stdout. Only messages with level smaller
* or equal than debug level will be printed.
*
* @param object
* object from which this message originated. Use "this" by
* caller for this.
* @param msg
* debug message
* @param level
* level of this message.
*/
public static void debug(final Object object,
final String msg,
final int level) {
if (level <= debugLevel) {
String from = "";
if (object != null) {
from = " (" + object.getClass().getName() + ")";
}
System.out.println(DEBUG_STRING
+ "(" + level + ") "
+ msg
+ from);
}
}
/**
* Shows error message dialog and prints error to the stdout.
*
* @param msg
* error message
*/
public static void error(final String msg) {
System.out.println(ERROR_STRING + getErrorString(msg));
SwingUtilities.invokeLater(new Runnable() {
@Override public void run() {
JOptionPane.showMessageDialog(
guiData.getMainFrame(),
new JScrollPane(new JTextArea(getErrorString(msg),
20,
60)),
Tools.getString("Error.Title"),
JOptionPane.ERROR_MESSAGE);
}
});
}
/** Show an ssh error message. */
public static void sshError(final Host host,
final String command,
final String ans,
final String stacktrace,
final int exitCode) {
final StringBuilder onHost = new StringBuilder("");
if (host != null) {
onHost.append(" on host ");
final Cluster cluster = host.getCluster();
if (cluster != null) {
onHost.append(cluster.getName());
onHost.append(" / ");
}
onHost.append(host.getName());
}
Tools.appWarning(Tools.getString("Tools.sshError.command")
+ " '" + command + "'" + onHost.toString() + "\n"
+ Tools.getString("Tools.sshError.returned")
+ " " + exitCode + "\n"
+ ans + "\n"
+ stacktrace);
}
/**
* Shows confirm dialog with yes and no options and returns true if yes
* button was pressed.
*/
public static boolean confirmDialog(final String title,
final String desc,
final String yesButton,
final String noButton) {
final ConfirmDialog cd = new ConfirmDialog(title,
desc,
yesButton,
noButton);
cd.showDialog();
return cd.isPressedYesButton();
}
/** Executes a command with progress indicator. */
public static SSH.SSHOutput execCommandProgressIndicator(
final Host host,
final String command,
final ExecCallback execCallback,
final boolean outputVisible,
final String text,
final int commandTimeout) {
ExecCallback ec;
final String hostName = host.getName();
Tools.startProgressIndicator(hostName, text);
final StringBuilder output = new StringBuilder("");
final Integer[] exitCodeHolder = new Integer[]{0};
if (execCallback == null) {
final String stacktrace = getStackTrace();
ec = new ExecCallback() {
@Override public void done(final String ans) {
output.append(ans);
}
@Override public void doneError(
final String ans,
final int exitCode) {
Tools.appWarning(ERROR_STRING
+ command
+ " "
+ ans + " rc: "
+ exitCode);
if (outputVisible) {
Tools.sshError(host,
command,
ans,
stacktrace,
exitCode);
}
exitCodeHolder[0] = exitCode;
output.append(ans);
}
};
} else {
ec = execCallback;
}
final Thread commandThread = host.execCommandRaw(command,
ec,
outputVisible,
true,
commandTimeout);
try {
if (commandThread != null) {
commandThread.join(0);
}
} catch (java.lang.InterruptedException e) {
Thread.currentThread().interrupt();
}
Tools.stopProgressIndicator(hostName, text);
return new SSH.SSHOutput(output.toString(), exitCodeHolder[0]);
}
/** Executes a command. */
public static SSH.SSHOutput execCommand(final Host host,
final String command,
final ExecCallback execCallback,
final boolean outputVisible,
final int commandTimeout) {
ExecCallback ec;
final StringBuilder output = new StringBuilder("");
final Integer[] exitCodeHolder = new Integer[]{0};
if (execCallback == null) {
final String stacktrace = getStackTrace();
ec = new ExecCallback() {
@Override public void done(final String ans) {
output.append(ans);
}
@Override public void doneError(
final String ans,
final int exitCode) {
if (outputVisible) {
Tools.sshError(host,
command,
ans,
stacktrace,
exitCode);
}
exitCodeHolder[0] = exitCode;
output.append(ans);
}
};
} else {
ec = execCallback;
}
final Thread commandThread = host.execCommandRaw(command,
ec,
outputVisible,
true,
commandTimeout);
try {
if (commandThread != null) {
commandThread.join(0);
}
} catch (java.lang.InterruptedException e) {
Thread.currentThread().interrupt();
}
return new SSH.SSHOutput(output.toString(), exitCodeHolder[0]);
}
/**
* Shows application warning message dialog if application warning messages
* are enabled.
*
* @param msg
* warning message
*/
public static void appWarning(final String msg) {
if (!appWarningHash.contains(msg)) {
appWarningHash.add(msg);
if (appWarning) {
System.out.println(APPWARNING_STRING + msg);
} else {
debug(APPWARNING_STRING + msg, 2);
}
}
}
/** Warning with exception error message. */
public static void appWarning(final String msg, final Exception e) {
if (!appWarningHash.contains(msg)) {
appWarningHash.add(msg);
if (appWarning) {
System.out.println(APPWARNING_STRING + msg + ": "
+ e.getMessage());
} else {
debug(APPWARNING_STRING + msg, 2);
}
}
}
/**
* Shows application error message dialog if application error messages
* are enabled.
*
* @param msg
* error message
*/
public static void appError(final String msg) {
appError(msg, "", null);
}
/**
* Shows application error message dialog if application error messages
* are enabled.
*
* @param msg
* error message
* @param msg2
* second error message in a new line.
*/
public static void appError(final String msg, final String msg2) {
appError(msg, msg2, null);
}
/** Shows application error message dialog, with a stacktrace. */
public static void appError(final String msg, final Exception e) {
appError(msg, "", e);
}
/**
* Shows application error message dialog with stack trace if
* application error messages are enabled.
*
* @param msg
* error message
* @param msg2
* second error message in a new line.
*
* @param e
* Exception object.
*/
public static void appError(final String msg,
final String msg2,
final Exception e) {
if (appErrorHash.contains(msg + msg2)) {
return;
}
appErrorHash.add(msg + msg2);
final StringBuilder errorString = new StringBuilder(300);
errorString.append(getErrorString("AppError.Text"));
errorString.append("\nrelease: ");
errorString.append(getRelease());
errorString.append("\njava: ");
errorString.append(System.getProperty("java.vendor"));
errorString.append(' ');
errorString.append(System.getProperty("java.version"));
errorString.append("\n\n");
errorString.append(getErrorString(msg));
errorString.append('\n');
errorString.append(msg2);
if (e != null) {
errorString.append('\n');
errorString.append(e.getMessage());
final StackTraceElement[] st = e.getStackTrace();
for (int i = 0; i < st.length; i++) {
errorString.append('\n');
errorString.append(e.getStackTrace()[i].toString());
}
}
if (e == null) {
/* stack trace */
final Throwable th = new Throwable();
final StringWriter sw = new StringWriter();
final PrintWriter pw = new PrintWriter(sw);
th.printStackTrace(pw);
pw.close();
errorString.append('\n');
errorString.append(sw.toString());
}
System.out.println(APPERROR_STRING + errorString);
if (!appError) {
return;
}
final JEditorPane errorPane = new JEditorPane(MIME_TYPE_TEXT_PLAIN,
errorString.toString());
errorPane.setEditable(false);
errorPane.setMinimumSize(DIALOG_PANEL_SIZE);
errorPane.setMaximumSize(DIALOG_PANEL_SIZE);
errorPane.setPreferredSize(DIALOG_PANEL_SIZE);
SwingUtilities.invokeLater(new Runnable() {
@Override public void run() {
JOptionPane.showMessageDialog(guiData.getMainFrame(),
new JScrollPane(errorPane),
getErrorString("AppError.Title"),
JOptionPane.ERROR_MESSAGE);
}
});
}
/** Dialog that informs a user about something with ok button. */
public static void infoDialog(final String title,
final String info1,
final String info2) {
final JEditorPane infoPane = new JEditorPane(MIME_TYPE_TEXT_PLAIN,
info1 + "\n" + info2);
infoPane.setEditable(false);
infoPane.setMinimumSize(DIALOG_PANEL_SIZE);
infoPane.setMaximumSize(DIALOG_PANEL_SIZE);
infoPane.setPreferredSize(DIALOG_PANEL_SIZE);
SwingUtilities.invokeLater(new Runnable() {
@Override public void run() {
JOptionPane.showMessageDialog(guiData.getMainFrame(),
new JScrollPane(infoPane),
getErrorString(title),
JOptionPane.ERROR_MESSAGE);
}
});
}
/**
* Checks string if it is an ip.
*
* @param ipString
* Ip string to be checked.
*
* @return whether string is ip or not.
*/
public static boolean isIp(final String ipString) {
boolean wasValid = true;
// Inet4Address ip;
Pattern pattern = null;
final String ipPattern =
"([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})";
if ("".equals(ipString)) {
wasValid = false;
} else {
try {
pattern = Pattern.compile(ipPattern);
} catch (PatternSyntaxException exception) {
return true;
}
final Matcher myMatcher = pattern.matcher(ipString);
if (myMatcher.matches()) {
for (int i = 1; i < 5; i++) {
if (Integer.parseInt(myMatcher.group(i)) > 255) {
wasValid = false;
break;
}
}
} else {
wasValid = false;
}
}
return wasValid;
}
/** Prints stack trace with text. */
public static void printStackTrace(final String text) {
System.out.println(text);
printStackTrace();
}
/** Prints stack trace. */
public static void printStackTrace() {
System.out.println(getStackTrace());
}
/** Returns stack trace. */
public static String getStackTrace() {
final Throwable th = new Throwable();
final StringWriter sw = new StringWriter();
final PrintWriter pw = new PrintWriter(sw);
th.printStackTrace(pw);
pw.close();
return sw.toString();
}
/**
* Loads the save file and returns its content as string. Return null, if
* nothing was loaded.
*/
public static String loadFile(final String filename,
final boolean showError) {
BufferedReader in = null;
final StringBuilder content = new StringBuilder("");
//Tools.startProgressIndicator(Tools.getString("Tools.Loading"));
try {
in = new BufferedReader(new FileReader(filename));
String line = "";
while ((line = in.readLine()) != null) {
content.append(line);
}
} catch (Exception ex) {
if (showError) {
infoDialog("Load Error",
"The file " + filename + " failed to load",
ex.getMessage());
}
return null;
}
if (in != null) {
try {
in.close();
} catch (IOException ex) {
Tools.appError("Could not close: " + filename, ex);
}
}
return content.toString();
}
/** Loads config data from the specified file. */
public static void loadConfigData(final String filename) {
debug("load", 0);
final String xml = loadFile(filename, true);
if (xml == null) {
return;
}
drbdGuiXML.startClusters(null);
Tools.getGUIData().allHostsUpdate();
}
/**
* Starts the specified clusters and connects to the hosts of these
* clusters.
*/
public static void startClusters(final List<Cluster> selectedClusters) {
drbdGuiXML.startClusters(selectedClusters);
}
/** Stops the specified clusters in the gui. */
public static void stopClusters(final List<Cluster> selectedClusters) {
for (final Cluster cluster : selectedClusters) {
cluster.removeCluster();
for (final Host host : cluster.getHosts()) {
// TODO: can be run concurrently.
host.disconnect();
}
getGUIData().getClustersPanel().removeTab(cluster);
}
}
/** Removes the specified clusters from the gui. */
public static void removeClusters(final List<Cluster> selectedClusters) {
for (final Cluster cluster : selectedClusters) {
getConfigData().removeClusterFromClusters(cluster);
for (final Host host : cluster.getHosts()) {
host.setCluster(null);
}
}
}
/** Returns cluster names from the parsed save file. */
public static void loadXML(final String xml) {
drbdGuiXML.loadXML(xml);
}
/** Removes all the hosts and clusters from all the panels and data. */
public static void removeEverything() {
Tools.startProgressIndicator("Removing Everything");
Tools.getConfigData().disconnectAllHosts();
getGUIData().getClustersPanel().removeAllTabs();
Tools.stopProgressIndicator("Removing Everything");
}
/**
* Saves config data.
*
* @param filename
* filename where are the data stored.
*/
public static void save(final String filename) {
debug("save");
final String text =
Tools.getString("Tools.Saving").replaceAll("@FILENAME@", filename);
startProgressIndicator(text);
try {
final FileOutputStream fileOut = new FileOutputStream(filename);
drbdGuiXML.saveXML(fileOut);
debug("saved: " + filename, 0);
} catch (IOException e) {
appError("error saving: " + filename, "", e);
} finally {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
final Clusters clusters = Tools.getConfigData().getClusters();
if (clusters != null) {
for (final Cluster cluster : clusters.getClusterSet()) {
final ClusterBrowser cb = cluster.getBrowser();
if (cb != null) {
cb.saveGraphPositions();
}
}
}
stopProgressIndicator(text);
}
}
/**
* Gets config data object.
*
* @return config data object.
*/
public static ConfigData getConfigData() {
return configData;
}
/**
* Gets gui data object.
*
* @return gui data object.
*/
public static GUIData getGUIData() {
return guiData;
}
/**
* Returns default value for option from AppDefaults resource bundle.
*
* @param option
* String that holds option.
*
* @return string with default value.
*/
public static String getDefault(final String option) {
synchronized (Tools.class) {
if (resourceAppDefaults == null) {
resourceAppDefaults =
ResourceBundle.getBundle("drbd.configs.AppDefaults");
}
}
try {
return resourceAppDefaults.getString(option);
} catch (Exception e) {
appError("unresolved config resource", option, e);
return option;
}
}
/**
* Returns default color for option from AppDefaults resource bundle.
*
* @param option
* String that holds option.
*
* @return default color.
*/
public static Color getDefaultColor(final String option) {
synchronized (Tools.class) {
if (resourceAppDefaults == null) {
resourceAppDefaults =
ResourceBundle.getBundle("drbd.configs.AppDefaults");
}
}
try {
return (Color) resourceAppDefaults.getObject(option);
} catch (Exception e) {
appError("unresolved config resource", option, e);
return Color.WHITE;
}
}
/**
* Returns default value for integer option from AppDefaults resource
* bundle.
*
* @param option
* String that holds option.
*
* @return integer with default value.
*/
public static int getDefaultInt(final String option) {
synchronized (Tools.class) {
if (resourceAppDefaults == null) {
resourceAppDefaults =
ResourceBundle.getBundle("drbd.configs.AppDefaults");
}
}
try {
return (Integer) resourceAppDefaults.getObject(option);
} catch (Exception e) {
appError("AppError.getInt.Exception",
option + ": " + getDefault(option),
e);
return 0;
}
/*
try {
return Integer.parseInt(getDefault(option));
} catch (Exception e) {
appError("AppError.getInt.Exception",
option + ": " + getDefault(option),
e);
return 0;
}
*/
}
/**
* Returns localized string from TextResource resource bundle.
*
* @param text
* String that holds text.
*
* @return localized string.
*/
public static String getString(final String text) {
synchronized (Tools.class) {
if (resource == null) {
/* set locale */
final Locale currentLocale = Locale.getDefault();
resource =
ResourceBundle.getBundle("drbd.configs.TextResource",
currentLocale);
}
}
try {
return resource.getString(text);
} catch (Exception e) {
appError("unresolved resource: " + text);
return text;
}
}
/**
* Returns converted error string. TODO: at the moment there is no
* conversion.
* TODO: ?
*/
public static String getErrorString(final String text) {
return text;
}
/** Returns string that is specific to a distribution and version. */
public static String getDistString(final String text,
String dist,
String version,
final String arch) {
if (dist == null) {
dist = "";
}
if (version == null) {
version = "";
}
final Locale locale = new Locale(dist, version);
debug("getDistString text: "
+ text
+ " dist: "
+ dist
+ " version: "
+ version, 2);
final ResourceBundle resourceString =
ResourceBundle.getBundle("drbd.configs.DistResource", locale);
String ret;
try {
ret = resourceString.getString(text + "." + arch);
} catch (Exception e) {
ret = null;
}
if (ret == null) {
try {
if (ret == null) {
ret = resourceString.getString(text);
}
debug("ret: " + ret, 2);
return ret;
} catch (Exception e) {
return null;
}
}
return ret;
}
/**
* Returns command from DistResource resource bundle for specific
* distribution and version.
*
* @param text
* text that should be found.
* @param dist
* distribution
* @param version
* version of this distribution.
*
* @return command.
*/
public static String getDistCommand(
final String text,
final String dist,
final String version,
final String arch,
final ConvertCmdCallback convertCmdCallback,
final boolean inBash) {
if (text == null) {
return null;
}
final String[] texts = text.split(";;;");
final List<String> results = new ArrayList<String>();
int i = 0;
for (final String t : texts) {
String distString = getDistString(t, dist, version, arch);
if (distString == null) {
Tools.appWarning("unknown command: " + t);
distString = t;
}
if (inBash && i == 0) {
results.add(DistResource.SUDO + "bash -c \""
+ Tools.escapeQuotes(distString, 1)
+ "\"");
} else {
results.add(distString);
}
i++;
}
String ret;
if (results.isEmpty()) {
ret = text;
} else {
ret = Tools.join(";;;",
results.toArray(new String[results.size()]));
}
if (convertCmdCallback != null && ret != null) {
ret = convertCmdCallback.convert(ret);
}
return ret;
}
/**
* Returns service definiton from ServiceDefinitions resource bundle.
*
* @param service
* service name.
*
* @return service definition as array of strings.
*/
public static String[] getServiceDefinition(final String service) {
final ResourceBundle resourceSD =
ResourceBundle.getBundle("drbd.configs.ServiceDefinitions");
try {
return resourceSD.getStringArray(service);
} catch (Exception e) {
Tools.appWarning("cannot get service definition for service: "
+ service, e);
return new String[]{};
}
}
/**
* Converts kernelVersion as parsed from uname to a version that is used
* in the download area on the website.
*/
public static String getKernelDownloadDir(final String kernelVersion,
final String dist,
final String version,
final String arch) {
final String regexp = getDistString("kerneldir", dist, version, arch);
if (regexp != null && kernelVersion != null) {
final Pattern p = Pattern.compile(regexp);
final Matcher m = p.matcher(kernelVersion);
if (m.matches()) {
return m.group(1);
}
}
return null;
}
/**
* Gets compact representation of distribution and version. Distribution
* and version are joined with "_" and all spaces and '.' are replaced by
* "_" as well.
*
* @param dist
* distribution
* @param version
* version of this distribution
* @return string that represents distribution and version.
*/
public static String getDistVersionString(String dist,
final String version) {
if (dist == null) {
dist = "";
}
debug("dist: " + dist + ", version: " + version, 2);
final Locale locale = new Locale(dist, "");
final ResourceBundle resourceCommand =
ResourceBundle.getBundle("drbd.configs.DistResource", locale);
String distVersion = null;
try {
distVersion = resourceCommand.getString("version:" + version);
} catch (Exception e) {
/* with wildcard */
final StringBuilder buf = new StringBuilder(version);
for (int i = version.length() - 1; i >= 0; i--) {
try {
distVersion = resourceCommand.getString("version:"
+ buf.toString()
+ "*");
} catch (Exception e2) {
distVersion = null;
}
if (distVersion != null) {
break;
}
buf.setLength(i);
}
if (distVersion == null) {
distVersion = version;
}
}
debug("dist version: " + distVersion, 2);
return distVersion;
}
/**
* Joins String array into one string with specified delimiter.
*
* @param delim
* delimiter
* @param strings
* array of strings
*
* @return
* joined string from array
*/
public static String join(final String delim, final String[] strings) {
if (strings == null || strings.length == 0) {
return "";
}
if (strings.length == 1 && strings[0] == null) {
return "";
}
final StringBuilder ret = new StringBuilder("");
for (int i = 0; i < strings.length - 1; i++) {
ret.append(strings[i]);
if (delim != null) {
ret.append(delim);
}
}
ret.append(strings[strings.length - 1]);
return ret.toString();
}
/** Joins String list into one string with specified delimiter. */
public static String join(final String delim,
final Collection<String> strings) {
if (strings == null) {
return "";
}
return join(delim, strings.toArray(new String[strings.size()]));
}
/**
* Joins String array into one string with specified delimiter.
*
* @param delim
* delimiter
* @param strings
* array of strings
* @param length
* length of the string array
*
* @return
* joined string from array
*/
public static String join(final String delim,
final String[] strings,
final int length) {
if (strings == null || strings.length == 0 || length <= 0) {
return "";
}
final StringBuilder ret = new StringBuilder("");
int i;
for (i = 0; i < length - 1 && i < strings.length - 1; i++) {
ret.append(strings[i]);
if (delim != null) {
ret.append(delim);
}
}
i++;
ret.append(strings[i - 1]);
return ret.toString();
}
/** Uppercases the first character. */
public static String ucfirst(final String s) {
if (s == null || s.length() == 0) {
return s;
}
final String f = s.substring(0, 1);
return s.replaceFirst(".", f.toUpperCase(Locale.US));
}
/**
* Converts enumeration to the string array.
*
* @param e
* enumeration
* @return string array
*/
public static String[] enumToStringArray(final Enumeration<String> e) {
if (e == null) {
return null;
}
final List<String> list = new ArrayList<String>();
while (e.hasMoreElements()) {
list.add(e.nextElement());
}
return list.toArray(new String[list.size()]);
}
/**
* returns intersection of two string lists as List of string.
*
* @param setA
* set A
* @param setB
* set B
* @return
* intersection of set A and B.
*/
public static Set<String> getIntersection(final Set<String> setA,
final Set<String> setB) {
final Set<String> resultSet = new TreeSet<String>();
if (setB == null) {
return setA;
}
if (setA == null) {
return setB;
}
for (final String item : setA) {
if (setB.contains(item)) {
resultSet.add(item);
}
}
return resultSet;
}
/**
* Convert text to html.
*
* @param text
* text to convert
*
* @return html
*/
public static String html(final String text) {
if (text == null) {
return "<html>\n</html>";
}
return "<html><p>" + text.replaceAll("\n", "<br>") + "\n</html>";
}
/**
* Checks if object is of the string class. Returns true if object is null.
*
* @param o
* object to be checked
* @return true if object is of string class
*/
public static boolean isStringClass(final Object o) {
if (o == null || o instanceof String) {
return true;
}
return false;
}
/** Returns thrue if object is in StringInfo class. */
public static boolean isStringInfoClass(final Object o) {
if (o != null
&& o.getClass().getName().equals("drbd.gui.resources.StringInfo")) {
return true;
}
return false;
}
/** Escapes for config file. */
public static String escapeConfig(final String value) {
if (value == null) {
return null;
}
if (value.indexOf(' ') > -1 || value.indexOf('"') > -1) {
return "\"" + value.replaceAll("\"", "\\\\\"") + "\"";
}
return value;
}
/** Starts progress indicator with specified text. */
public static void startProgressIndicator(final String text) {
final boolean rightMovement = RANDOM.nextBoolean();
getGUIData().getMainGlassPane().start(text, null, rightMovement);
}
/** Starts progress indicator for host or cluster command. */
public static void startProgressIndicator(final String name,
final String text) {
startProgressIndicator(name + ": " + text);
}
/** Stops progress indicator with specified text. */
public static void stopProgressIndicator(final String text) {
getGUIData().getMainGlassPane().stop(text);
}
/** Stops progress indicator for host or cluster command. */
public static void stopProgressIndicator(final String name,
final String text) {
stopProgressIndicator(name + ": " + text);
}
/** Progress indicator with failure message. */
public static void progressIndicatorFailed(final String text) {
getGUIData().getMainGlassPane().failure(text);
}
/** Progress indicator with failure message for host or cluster command. */
public static void progressIndicatorFailed(final String name,
final String text) {
progressIndicatorFailed(name + ": " + text);
}
/** Progress indicator with failure message that shows for n seconds. */
public static void progressIndicatorFailed(final String text, final int n) {
getGUIData().getMainGlassPane().failure(text, n);
}
/**
* Progress indicator with failure message for host or cluster command,
* that shows for n seconds.
*/
public static void progressIndicatorFailed(final String name,
final String text,
final int n) {
progressIndicatorFailed(name + ": " + text, n);
}
/** Sets fixed size for component. */
public static void setSize(final Component c,
final int width,
final int height) {
final Dimension d = new Dimension(width, height);
c.setMaximumSize(d);
c.setMinimumSize(d);
c.setPreferredSize(d);
}
/**
* Returns -1 if version1 is smaller that version2, 0 if version1 equals
* version2 and 1 if version1 is bigger than version2.
* @Throws Exceptions.IllegalVersionException
*/
public static int compareVersions(final String version1,
final String version2)
throws Exceptions.IllegalVersionException {
if (version1 == null || version2 == null) {
throw new Exceptions.IllegalVersionException(version1, version2);
}
final Pattern p = Pattern.compile("(.*\\d+)rc(\\d+)$");
final Matcher m1 = p.matcher(version1);
String version1a;
int rc1 = Integer.MAX_VALUE;
if (m1.matches()) {
version1a = m1.group(1);
try {
rc1 = Integer.parseInt(m1.group(2));
} catch (java.lang.NumberFormatException e) {
e.printStackTrace();
}
} else {
version1a = version1;
}
final Matcher m2 = p.matcher(version2);
String version2a;
int rc2 = Integer.MAX_VALUE;
if (m2.matches()) {
version2a = m2.group(1);
try {
rc2 = Integer.parseInt(m2.group(2));
} catch (java.lang.NumberFormatException e) {
e.printStackTrace();
}
} else {
version2a = version2;
}
final String[] v1a = version1a.split("\\.");
final String[] v2a = version2a.split("\\.");
if (v1a.length < 1 || v2a.length < 1) {
throw new Exceptions.IllegalVersionException(version1, version2);
}
int i = 0;
while (true) {
if (i >= v1a.length && i >= v2a.length) {
break;
} else if (i >= v1a.length || i >= v2a.length) {
return 0;
}
int v1i = 0;
if (i < v1a.length) {
final String v1 = v1a[i];
try {
v1i = Integer.parseInt(v1);
} catch (java.lang.NumberFormatException e) {
throw new Exceptions.IllegalVersionException(version1);
}
}
int v2i = 0;
if (i < v2a.length) {
final String v2 = v2a[i];
try {
v2i = Integer.parseInt(v2);
} catch (java.lang.NumberFormatException e) {
throw new Exceptions.IllegalVersionException(version2);
}
}
if (v1i < v2i) {
return -1;
} else if (v1i > v2i) {
return 1;
}
i++;
}
if (rc1 < rc2) {
return -1;
} else if (rc1 > rc2) {
return 1;
}
return 0;
}
/** Returns number of characters 'c' in a string 's'. */
public static int charCount(final String s, final char c) {
if (s == null) {
return 0;
}
int count = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == c) {
count++;
}
}
return count;
}
/**
* Creates config on all hosts with specified name in the specified
* directory.
*
* @param config
* config content as a string
* @param fileName
* file name of the config
* @param dir
* directory where the config should be stored
* @param mode
* mode, e.g. "0700"
* @param makeBackup
* whether to make backup or not
*/
public static void createConfigOnAllHosts(final Host[] hosts,
final String config,
final String fileName,
final String dir,
final String mode,
final boolean makeBackup) {
for (Host host : hosts) {
host.getSSH().createConfig(config,
fileName,
dir,
mode,
makeBackup,
null,
null);
}
}
/** Returns border with title. */
public static TitledBorder getBorder(final String text) {
final TitledBorder titledBorder = new TitledBorder(
BorderFactory.createLineBorder(Color.BLACK, 1), text);
titledBorder.setTitleJustification(TitledBorder.LEFT);
return titledBorder;
}
/** Returns a popup in a scrolling pane. */
public static JScrollPane getScrollingMenu(
final MyMenu menu,
final DefaultListModel dlm,
final MyList list,
final Map<MyMenuItem, ButtonCallback> callbackHash) {
prevScrollingMenuIndex = -1;
list.setFixedCellHeight(25);
final int maxSize = dlm.getSize();
if (maxSize <= 0) {
return null;
}
if (maxSize > 20) {
list.setVisibleRowCount(20);
} else {
list.setVisibleRowCount(maxSize);
}
list.addMouseListener(new MouseAdapter() {
@Override public void mouseExited(final MouseEvent evt) {
prevScrollingMenuIndex = -1;
if (callbackHash != null) {
for (final MyMenuItem item : callbackHash.keySet()) {
callbackHash.get(item).mouseOut();
list.clearSelection();
}
}
}
@Override public void mouseEntered(final MouseEvent evt) {
- list.requestFocus();
+ /* request focus here causes the applet making all
+ textfields to be not editable. */
+ /* list.requestFocus(); */
}
@Override public void mousePressed(final MouseEvent evt) {
prevScrollingMenuIndex = -1;
if (callbackHash != null) {
for (final MyMenuItem item : callbackHash.keySet()) {
callbackHash.get(item).mouseOut();
}
}
final Thread thread = new Thread(new Runnable() {
@Override public void run() {
final int index = list.locationToIndex(evt.getPoint());
SwingUtilities.invokeLater(new Runnable() {
@Override public void run() {
list.setSelectedIndex(index);
//TODO: some submenus stay visible, during
//ptest, but this breaks group popup menu
//setMenuVisible(menu, false);
menu.setSelected(false);
}
});
final MyMenuItem item =
(MyMenuItem) dlm.elementAt(index);
item.action();
}
});
thread.start();
}
});
list.addMouseMotionListener(new MouseMotionAdapter() {
@Override public void mouseMoved(final MouseEvent evt) {
final Thread thread = new Thread(new Runnable() {
@Override public void run() {
int pIndex = list.locationToIndex(evt.getPoint());
if (!list.getCellBounds(pIndex, pIndex).contains(
evt.getPoint())) {
pIndex = -1;
}
final int index = pIndex;
final int lastIndex = prevScrollingMenuIndex;
if (index == lastIndex) {
return;
}
prevScrollingMenuIndex = index;
SwingUtilities.invokeLater(new Runnable() {
@Override public void run() {
list.setSelectedIndex(index);
}
});
if (callbackHash != null) {
if (lastIndex >= 0) {
final MyMenuItem lastItem =
(MyMenuItem) dlm.elementAt(lastIndex);
callbackHash.get(lastItem).mouseOut();
}
if (index >= 0) {
final MyMenuItem item =
(MyMenuItem) dlm.elementAt(index);
callbackHash.get(item).mouseOver();
}
}
}
});
thread.start();
}
});
final JScrollPane sp = new JScrollPane(list);
sp.setViewportBorder(null);
sp.setBorder(null);
list.addKeyListener(new KeyAdapter() {
@Override public void keyTyped(final KeyEvent e) {
final char ch = e.getKeyChar();
if (ch == ' ' || ch == '\n') {
final MyMenuItem item =
(MyMenuItem) list.getSelectedValue();
//SwingUtilities.invokeLater(new Runnable() {
// @Override public void run() {
// //menu.setPopupMenuVisible(false);
// setMenuVisible(menu, false);
// }
//});
if (item != null) {
item.action();
}
} else {
if (Character.isLetterOrDigit(ch)) {
final Thread t = new Thread(new Runnable() {
@Override public void run() {
getGUIData().getMainGlassPane().start("" + ch,
null,
true);
stopProgressIndicator("" + ch);
}
});
t.start();
}
}
}
});
return sp;
}
/** Returns whether the computer, where this program is run, is Linux. */
public static boolean isLinux() {
return "Linux".equals(System.getProperty("os.name"));
}
/** Returns whether the computer, where this program is run, is Windows. */
public static boolean isWindows() {
return System.getProperty("os.name").indexOf("Windows") == 0;
}
/** Sets the html font of the editor pane to be the default font. */
public static void setEditorFont(final JEditorPane ep) {
final Font font = UIManager.getFont("Label.font");
final String bodyRule = "body { font-family: " + font.getFamily()
+ "; "
+ "font-size: " + font.getSize() + "pt; }";
((HTMLDocument) ep.getDocument()).getStyleSheet().addRule(bodyRule);
}
/** Reads and returns a content of a text file. */
public static String getFile(final String fileName) {
if (fileName == null) {
return null;
}
final URL url = Tools.class.getResource(fileName);
if (url == null) {
return null;
}
try {
final BufferedReader br =
new BufferedReader(
new InputStreamReader(url.openStream()));
final StringBuilder content = new StringBuilder("");
while (br.ready()) {
content.append(br.readLine());
content.append('\n');
}
return content.toString();
} catch (IOException e) {
Tools.appError("could not read: " + fileName, "", e);
return null;
}
}
/**
* Parses arguments from --auto command line option, it makes some
* automatical gui actions, that help to test the gui and can find some
* other uses later.
* To find out which options are available, you'd have to grep for
* getAutoOptionHost and getAutoOptionCluster
*/
public static void parseAutoArgs(final String line) {
if (line == null) {
return;
}
final String[] args = line.split(",");
String host = null;
String cluster = null;
boolean global = false;
for (final String arg : args) {
final String[] pair = arg.split(":");
if (pair == null || pair.length != 2) {
appWarning("cannot parse: " + line);
return;
}
final String option = pair[0];
final String value = pair[1];
if ("host".equals(option)) {
cluster = null;
host = value;
Tools.getConfigData().addAutoHost(host);
continue;
} else if ("cluster".equals(option)) {
host = null;
cluster = value;
Tools.getConfigData().addAutoCluster(cluster);
continue;
} else if ("global".equals(option)) {
host = null;
cluster = null;
global = true;
continue;
}
if (host != null) {
Tools.getConfigData().addAutoOption(host, option, value);
} else if (cluster != null) {
Tools.getConfigData().addAutoOption(cluster, option, value);
} else if (global) {
Tools.getConfigData().addAutoOption("global", option, value);
} else {
appWarning("cannot parse: " + line);
return;
}
}
}
/** Convenience sleep wrapper. */
public static void sleep(final int ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
/** Convenience sleep wrapper with float argument. */
public static void sleep(final float ms) {
sleep((int) ms);
}
/** Returns the latest version of this application. */
public static String getLatestVersion() {
String version = null;
final Pattern vp = Pattern.compile(
".*<a\\s+href=\"drbd-mc-([0-9.]*?)\\.tar\\..*");
try {
final String url = "http://oss.linbit.com/drbd-mc/?drbd-mc-check-"
+ getRelease();
final BufferedReader reader = new BufferedReader(
new InputStreamReader(new URL(url).openStream()));
String line;
do {
line = reader.readLine();
if (line == null) {
break;
}
final Matcher m = vp.matcher(line);
if (m.matches()) {
final String v = m.group(1);
try {
if (version == null
|| compareVersions(v, version) > 0) {
version = v;
}
} catch (Exceptions.IllegalVersionException e) {
Tools.appWarning(e.getMessage(), e);
}
}
} while (true);
} catch (MalformedURLException mue) {
return null;
} catch (IOException ioe) {
return version;
}
return version;
}
/** Opens default browser. */
public static void openBrowser(final String url) {
try {
java.awt.Desktop.getDesktop().browse(new URI(url));
} catch (java.io.IOException e) {
Tools.appError("wrong uri", e);
} catch (java.net.URISyntaxException e) {
Tools.appError("error opening browser", e);
}
}
/**
* Prepares vnc viewer, gets the port and creates ssh tunnel. Returns true
* if ssh tunnel was created.
*/
private static int prepareVncViewer(final Host host,
final int remotePort) {
if (remotePort < 0 || host == null) {
return -1;
}
if (Tools.isLocalIp(host.getIp())) {
return remotePort;
}
final int localPort = remotePort + getConfigData().getVncPortOffset();
debug("start port forwarding " + remotePort + " -> " + localPort);
try {
host.getSSH().startVncPortForwarding(host.getIp(), remotePort);
} catch (final java.io.IOException e) {
Tools.appError("unable to create tunnel", e);
return -1;
}
return localPort;
}
/** Cleans up after vnc viewer. It stops ssh tunnel. */
private static void cleanupVncViewer(final Host host,
final int localPort) {
if (Tools.isLocalIp(host.getIp())) {
return;
}
final int remotePort = localPort - getConfigData().getVncPortOffset();
debug("stop port forwarding " + remotePort);
try {
host.getSSH().stopVncPortForwarding(remotePort);
} catch (final java.io.IOException e) {
Tools.appError("unable to close tunnel", e);
}
}
/** Starts Tight VNC viewer. */
public static void startTightVncViewer(final Host host,
final int remotePort) {
final int localPort = prepareVncViewer(host, remotePort);
if (localPort < 0) {
return;
}
final tightvnc.VncViewer v = new tightvnc.VncViewer(
new String[]{"HOST",
"127.0.0.1",
"PORT",
Integer.toString(localPort)},
false,
true);
v.init();
v.start();
v.join();
cleanupVncViewer(host, localPort);
}
/** Starts Ultra VNC viewer. */
public static void startUltraVncViewer(final Host host,
final int remotePort) {
final int localPort = prepareVncViewer(host, remotePort);
if (localPort < 0) {
return;
}
final JavaViewer.VncViewer v = new JavaViewer.VncViewer(
new String[]{"HOST",
"127.0.0.1",
"PORT",
Integer.toString(localPort)},
false,
true);
v.init();
v.start();
v.join();
cleanupVncViewer(host, localPort);
}
/** Starts Real VNC viewer. */
public static void startRealVncViewer(final Host host,
final int remotePort) {
final int localPort = prepareVncViewer(host, remotePort);
if (localPort < 0) {
return;
}
final vncviewer.VNCViewer v = new vncviewer.VNCViewer(
new String[]{"127.0.0.1:"
+ (Integer.toString(localPort - 5900))});
v.start();
v.join();
cleanupVncViewer(host, localPort);
}
/** Hides mouse pointer. */
public static void hideMousePointer(final Component c) {
final int[] pixels = new int[16 * 16];
final Image image = Toolkit.getDefaultToolkit().createImage(
new MemoryImageSource(16, 16, pixels, 0, 16));
final Cursor transparentCursor =
Toolkit.getDefaultToolkit().createCustomCursor(image,
new Point(0, 0),
"invisibleCursor");
c.setCursor(transparentCursor);
}
/** Check whether the string is number. */
public static boolean isNumber(final String s) {
try {
Long.parseLong(s);
return true;
} catch (final NumberFormatException nfe) {
return false;
}
}
/** Returns list that is expandable by shell. {'a','b'...} */
public static String shellList(final String[] items) {
final StringBuilder list = new StringBuilder("");
if (items == null || items.length == 0) {
return null;
} else if (items.length == 1) {
list.append(items[0]);
} else {
list.append('{');
for (int i = 0; i < items.length - 1; i++) {
list.append('\'');
list.append(items[i]);
list.append("',");
}
if (items.length != 0) {
list.append('\'');
list.append(items[items.length - 1]);
list.append('\'');
}
list.append('}');
}
return list.toString();
}
/**
* Returns whether two objects are equal. Special handling for Units and
* StringInfo objects.
*/
public static boolean areEqual(final Object o1, final Object o2) {
if (o1 == null && o2 == null) {
return true;
} else if (o1 != null && o1 instanceof DrbdResourceInfo) {
/* this is special case, because this object represents devices in
* filesystem ra and also after field in drbd.conf. */
final String device = ((DrbdResourceInfo) o1).getStringValue();
if (device.equals(o2)) {
return true;
}
final String res = ((DrbdResourceInfo) o1).getName();
if (res == null) {
return res == o2;
}
if (res.equals(o2)) {
return true;
}
return false;
} else if (o1 != null && o1 instanceof Info) {
final String s1 = ((Info) o1).getStringValue();
if (s1 == null) {
return o2 == null;
}
if (o2 == null) {
return false;
}
if (o2 instanceof Info) {
return s1.equals(((Info) o2).getStringValue());
} else {
return s1.equals(o2) || o1.toString().equals(o2);
}
} else if (o2 != null && o2 instanceof Info) {
final String s2 = ((Info) o2).getStringValue();
if (s2 == null) {
return o1 == null;
}
if (o1 == null) {
return false;
}
if (o1 instanceof Info) {
return s2.equals(((Info) o1).getStringValue());
} else {
return s2.equals(o1) || o2.toString().equals(o1);
}
} else if (o1 == null && o2 != null) {
return o2.toString().equals("");
} else if (o2 == null && o1 != null) {
return o1.toString().equals("");
} else if (o1 instanceof Object[]
&& o2 instanceof Object[]) {
final Object[] array1 = (Object[]) o1;
final Object[] array2 = (Object[]) o2;
for (int i = 0; i < array1.length; i++) {
if (!areEqual(array1[i], array2[i])) {
return false;
}
}
return true;
} else if (o1 instanceof Unit) {
return ((Unit) o1).equals(o2);
} else if (o2 instanceof Unit) {
return ((Unit) o2).equals(o1);
} else if (o1 instanceof ComboInfo) {
return ((ComboInfo) o1).equals(o2);
} else if (o2 instanceof ComboInfo) {
return ((ComboInfo) o2).equals(o1);
} else {
return o1.equals(o2);
}
}
/**
* Returns value unit pair extracting from string. E.g. "10min" becomes 10
* and "min" pair.
*/
public static Object[] extractUnit(final String time) {
final Object[] o = new Object[]{null, null};
if (time == null) {
return o;
}
final Matcher m = UNIT_PATTERN.matcher(time);
if (m.matches()) {
o[0] = m.group(1);
o[1] = m.group(2);
}
return o;
}
/** Returns random secret of the specified lenght. */
public static String getRandomSecret(final int len) {
final Random rand = new Random();
final ArrayList<Character> charsL = new ArrayList<Character>();
for (int a = 'a'; a <= 'z'; a++) {
charsL.add((char) a);
charsL.add(Character.toUpperCase((char) a));
}
for (int a = '0'; a <= '9'; a++) {
charsL.add((char) a);
}
final Character[] chars = charsL.toArray(new Character[charsL.size()]);
final StringBuilder s = new StringBuilder(len + 1);
for (int i = 0; i < len; i++) {
s.append(chars[rand.nextInt(chars.length)]);
}
return s.toString();
}
/** Returns whether the ip is localhost. */
public static boolean isLocalIp(final String ip) {
if (ip == null
|| "127.0.0.1".equals(ip)
|| "127.0.1.1".equals(ip)) {
return true;
}
try {
final String localIp = InetAddress.getLocalHost().getHostAddress();
return ip.equals(localIp);
} catch (java.net.UnknownHostException e) {
return false;
}
}
/** Converts value in kilobytes. */
public static String convertKilobytes(final String kb) {
if (!isNumber(kb)) {
return kb;
}
final double k = Long.parseLong(kb);
if (k == 0) {
return "0K";
}
if (k / 1024 != (long) (k / 1024)) {
return kb + "K";
}
final double m = k / 1024;
if (m / 1024 != (long) (m / 1024)) {
return Long.toString((long) m) + "M";
}
final double g = m / 1024;
if (g / 1024 != (long) (g / 1024)) {
return Long.toString((long) g) + "G";
}
final double t = g / 1024;
if (t / 1024 != (long) (t / 1024)) {
return Long.toString((long) t) + "T";
}
return Long.toString((long) (t / 1024)) + "P";
}
/** Converts value with unit to kilobites. */
public static long convertToKilobytes(final String value) {
final Object[] v = Tools.extractUnit(value);
if (v.length == 2 && Tools.isNumber((String) v[0])) {
long num = Long.parseLong((String) v[0]);
final String unit = (String) v[1];
if ("P".equalsIgnoreCase(unit)) {
num = num * 1024 * 1024 * 1024 * 1024;
} else if ("T".equalsIgnoreCase(unit)) {
num = num * 1024 * 1024 * 1024;
} else if ("G".equalsIgnoreCase(unit)) {
num = num * 1024 * 1024;
} else if ("M".equalsIgnoreCase(unit)) {
num = num * 1024;
} else if ("K".equalsIgnoreCase(unit)) {
} else {
return -1;
}
return num;
}
return -1;
}
/** Resize table. */
public static void resizeTable(final JTable table,
final Map<Integer, Integer> defaultWidths) {
final int margin = 3;
for (int i = 0; i < table.getColumnCount(); i++) {
final int vColIndex = i;
final DefaultTableColumnModel colModel =
(DefaultTableColumnModel) table.getColumnModel();
final TableColumn col = colModel.getColumn(vColIndex);
int width = 0;
TableCellRenderer renderer = col.getHeaderRenderer();
if (renderer == null) {
renderer = table.getTableHeader().getDefaultRenderer();
}
if (renderer == null) {
continue;
}
Component comp = renderer.getTableCellRendererComponent(
table,
col.getHeaderValue(),
false,
false,
0,
0);
Integer dw = null;
if (defaultWidths != null) {
dw = defaultWidths.get(i);
}
if (dw == null) {
width = comp.getPreferredSize().width;
for (int r = 0; r < table.getRowCount(); r++) {
renderer = table.getCellRenderer(r, vColIndex);
if (renderer == null) {
continue;
}
comp = renderer.getTableCellRendererComponent(
table,
table.getValueAt(r, vColIndex),
false,
false,
r, vColIndex);
width = Math.max(width, comp.getPreferredSize().width);
}
} else {
width = dw;
col.setMaxWidth(width);
}
width += 2 * margin;
col.setPreferredWidth(width);
}
((DefaultTableCellRenderer) table.getTableHeader().getDefaultRenderer())
.setHorizontalAlignment(SwingConstants.CENTER);
}
/** Sets the menu and all its parents visible, not visible. */
public static void setMenuVisible(final JComponent menu,
final boolean visible) {
JComponent parent = (JComponent) menu.getParent();
if (parent instanceof javax.swing.JViewport) {
/* MyList */
parent = (JComponent) parent.getParent();
parent = (JComponent) parent.getParent();
}
if (parent instanceof JPopupMenu) {
JComponent inv = (JComponent) ((JPopupMenu) parent).getInvoker();
while (inv != null) {
final JComponent invP = (JComponent) inv.getParent();
if (!(invP instanceof JPopupMenu)) {
break;
}
invP.setVisible(visible);
for (final java.awt.Component c : invP.getComponents()) {
((JComponent) c).setVisible(visible);
}
final JComponent pp = (JComponent) invP.getParent();
if (pp != null) {
pp.setVisible(visible);
}
inv = (JComponent) ((JPopupMenu) invP).getInvoker();
}
menu.setVisible(visible);
parent.setVisible(visible);
final JComponent pp = (JComponent) parent.getParent();
if (pp != null) {
pp.setVisible(visible);
}
for (final java.awt.Component c : parent.getComponents()) {
((JComponent) c).setVisible(visible);
}
parent.repaint();
}
}
/** Sets the menu and all its parents opaque, not opaque. */
public static void setMenuOpaque(final JComponent menu,
final boolean opaque) {
JComponent parent = (JComponent) menu.getParent();
if (parent instanceof javax.swing.JViewport) {
/* MyList */
parent = (JComponent) parent.getParent();
parent = (JComponent) parent.getParent();
}
if (parent instanceof JPopupMenu) {
JComponent inv = (JComponent) ((JPopupMenu) parent).getInvoker();
while (inv != null) {
final JComponent invP = (JComponent) inv.getParent();
if (!(invP instanceof JPopupMenu)) {
break;
}
invP.setOpaque(opaque);
for (final java.awt.Component c : invP.getComponents()) {
((JComponent) c).setOpaque(opaque);
}
final JComponent pp = (JComponent) invP.getParent();
if (pp != null) {
pp.setOpaque(opaque);
}
inv = (JComponent) ((JPopupMenu) invP).getInvoker();
}
menu.setOpaque(opaque);
parent.setOpaque(opaque);
final JComponent pp = (JComponent) parent.getParent();
if (pp != null) {
pp.setOpaque(opaque);
}
for (final java.awt.Component c : parent.getComponents()) {
((JComponent) c).setOpaque(opaque);
}
parent.repaint();
}
}
/** Converts windows path to unix path. */
public static String getUnixPath(final String dir) {
if (dir == null) {
return null;
}
String unixPath;
if (isWindows()) {
unixPath = dir.replaceAll("\\\\", "/");
if (unixPath.length() >= 2
&& ":".equalsIgnoreCase(unixPath.substring(1, 2))) {
unixPath = unixPath.substring(2);
}
} else {
unixPath = dir;
}
return unixPath;
}
/** Returns bounds of the whole screen. */
public static Rectangle getScreenBounds(final JComponent component) {
final GraphicsConfiguration gc = component.getGraphicsConfiguration();
final Rectangle sBounds = gc.getBounds();
final Insets screenInsets =
Toolkit.getDefaultToolkit().getScreenInsets(gc);
/* Take into account screen insets, decrease viewport */
sBounds.x += screenInsets.left;
sBounds.y += screenInsets.top;
sBounds.width -= (screenInsets.left + screenInsets.right);
sBounds.height -= (screenInsets.top + screenInsets.bottom);
return sBounds;
}
/** Compares two Lists with services if thery are equal. The order does not
* matter. */
public static boolean serviceInfoListEquals(final Set<ServiceInfo> l1,
final Set<ServiceInfo> l2) {
if (l1 == l2) {
return true;
}
if (l1 == null || l2 == null) {
return false;
}
if (l1.size() != l2.size()) {
return false;
}
for (final ServiceInfo s1 : l1) {
if (!l2.contains(s1)) {
return false;
}
}
return true;
}
/** Trims text to have displayable width. */
public static String trimText(final String text) {
final int width = 80;
if (text == null || text.length() <= width) {
return text;
}
final StringBuilder out = new StringBuilder(text.length() + 10);
/* find next space */
String t = text;
while (true) {
final int pos = t.indexOf(' ', width);
if (pos > 0) {
out.append(t.substring(0, pos));
out.append('\n');
t = t.substring(pos + 1);
} else {
break;
}
}
out.append(t);
return out.toString();
}
/** Wait for next swing threads to finish. It's used for synchronization */
public static void waitForSwing() {
try {
SwingUtilities.invokeAndWait(new Runnable() {
@Override public void run() {
/* just wait */
}
});
} catch (final InterruptedException ix) {
Thread.currentThread().interrupt();
} catch (final InvocationTargetException x) {
Tools.printStackTrace();
}
}
/** Convenience invoke and wait function. */
public static void invokeAndWait(final Runnable runnable) {
try {
SwingUtilities.invokeAndWait(runnable);
} catch (final InterruptedException ix) {
Thread.currentThread().interrupt();
} catch (final InvocationTargetException x) {
Tools.printStackTrace();
}
}
/** Return directory part (to the /) of the filename. */
public static String getDirectoryPart(final String filename) {
if (filename == null) {
return null;
}
final int i = filename.lastIndexOf('/');
if (i < 0) {
return filename;
}
return filename.substring(0, i + 1);
}
/** Returns list of plugins. */
public static Set<String> getPluginList() {
final Pattern p = Pattern.compile(
".*<img src=\"/icons/folder.gif\" alt=\"\\[DIR\\]\">"
+ "</td><td><a href=\".*?/\">(.*?)/</a>.*");
final Set<String> pluginList = new LinkedHashSet<String>();
try {
final String url = "http://" + PLUGIN_LOCATION
+ "/?drbd-mc-plugin-check-" + getRelease();
final BufferedReader reader = new BufferedReader(
new InputStreamReader(new URL(url).openStream()));
do {
final String line = reader.readLine();
if (line == null) {
break;
}
final Matcher m = p.matcher(line);
if (m.matches()) {
final String pluginName = m.group(1);
final String checkURL = "http://" + PLUGIN_LOCATION
+ pluginName + "/" + getRelease()
+ "/?drbd-mc-plugin-check-" + getRelease();
try {
new URL(checkURL).openStream();
pluginList.add(pluginName);
} catch (MalformedURLException mue) {
Tools.appWarning("malformed URL");
} catch (IOException ioe) {
/* don't show this in the menu */
}
}
} while (true);
} catch (MalformedURLException mue) {
Tools.appWarning("malformed URL");
} catch (IOException ioe) {
}
final File dir = new File(PLUGIN_DIR);
final String[] l = dir.list();
if (dir != null && l != null) {
for (final String fn : l) {
pluginList.add(fn);
}
}
return pluginList;
}
/** Loads one plugin. */
private static Class loadPlugin(final String pluginName,
final String url) {
final String user = getConfigData().getPluginUser();
final String passwd = getConfigData().getPluginPassword();
if (user != null && passwd != null) {
Authenticator.setDefault(new java.net.Authenticator() {
protected PasswordAuthentication
getPasswordAuthentication() {
return new PasswordAuthentication(user,
passwd.toCharArray());
}
});
}
URLClassLoader loader;
final String[] dirs = pluginName.split(":");
try {
loader = new URLClassLoader(new URL[] {
new URL(url + pluginName + "/" + getRelease() + "/")
});
} catch (java.net.MalformedURLException e) {
Tools.appWarning("could not get: " + url, e);
return null;
}
Class c = null;
final String className = "plugins." + dirs[dirs.length - 1];
try {
c = loader.loadClass(className);
} catch (java.lang.ClassNotFoundException e) {
Tools.debug("could not load " + url + " " + className, 1);
return null;
}
return c;
}
/** Saves the class. */
private static void savePluginClass(final String pluginName,
final Class c) {
for (final Class sc : c.getDeclaredClasses()) {
savePluginClass(pluginName, sc);
}
try {
final String className = c.getName();
final String classAsPath = className.replace('.', '/') + ".class";
final String dirToCreate = PLUGIN_DIR
+ pluginName
+ "/"
+ getRelease()
+ "/";
(new File(dirToCreate + "plugins/")).mkdirs();
final FileOutputStream fileOut = new FileOutputStream(
dirToCreate
+ classAsPath);
final InputStream stream =
c.getClassLoader().getResourceAsStream(classAsPath);
final byte[] buff = new byte[512];
while (stream.available() > 0) {
final int l = stream.read(buff);
fileOut.write(buff, 0, l);
}
fileOut.close();
} catch (FileNotFoundException e) {
Tools.appWarning("plugin not found", e);
return;
} catch (IOException e) {
Tools.appWarning("could not save plugin", e);
return;
}
}
/** Load all plugins. */
public static void loadPlugins() {
final Set<String> pluginList = getPluginList();
getGUIData().getMainMenu().reloadPluginsMenu(pluginList);
for (final String pluginName : pluginList) {
Class c = loadPlugin(pluginName, "http://" + PLUGIN_LOCATION);
if (c == null) {
c = loadPlugin(pluginName, "file://" + PLUGIN_DIR);
if (c == null) {
continue;
}
} else {
savePluginClass(pluginName, c);
/* cache it. */
}
final Class pluginClass = c;
RemotePlugin remotePlugin = null;
try {
remotePlugin = (RemotePlugin) pluginClass.newInstance();
} catch (java.lang.InstantiationException e) {
Tools.appWarning("could not instantiate plugin: " + pluginName,
e);
continue;
} catch (java.lang.IllegalAccessException e) {
Tools.appWarning("could not access plugin: " + pluginName, e);
continue;
}
remotePlugin.init();
PLUGIN_OBJECTS.put(pluginName, remotePlugin);
SwingUtilities.invokeLater(new Runnable() {
@Override public void run() {
getGUIData().getMainMenu().enablePluginMenu(
pluginName,
pluginClass != null);
if (pluginClass != null) {
Tools.info(pluginName + " was enabled");
}
}
});
}
}
/** Show plugin description. */
public static void showPluginDescription(final String pluginName) {
final RemotePlugin remotePlugin = PLUGIN_OBJECTS.get(pluginName);
if (remotePlugin != null) {
remotePlugin.showDescription();
}
}
/** Adds menu items from plugins. */
public static void addPluginMenuItems(final Info info,
final List<UpdatableItem> items) {
for (final String pluginName : PLUGIN_OBJECTS.keySet()) {
PLUGIN_OBJECTS.get(pluginName).addPluginMenuItems(info, items);
}
}
/** Escapes the quotes for the stacked ssh commands. */
public static String escapeQuotes(final String s, final int count) {
if (s == null) {
return null;
}
if (count <= 0) {
return s;
}
final StringBuilder sb = new StringBuilder("");
for (int i = 0; i < s.length(); i++) {
final char c = s.charAt(i);
if (c == '\\') {
sb.append("\\\\");
} else if (c == '"' || c == '$' || c == '`') {
sb.append('\\');
sb.append(c);
} else {
sb.append(c);
}
}
return escapeQuotes(sb.toString(), count - 1);
}
/** Returns array of host checkboxes in the specified cluster. */
public static Map<Host, JCheckBox> getHostCheckboxes(
final Cluster cluster) {
final Map<Host, JCheckBox> components =
new LinkedHashMap<Host, JCheckBox>();
for (final Host host : cluster.getHosts()) {
final JCheckBox button = new JCheckBox(host.getName());
button.setBackground(
Tools.getDefaultColor("ConfigDialog.Background.Light"));
components.put(host, button);
}
return components;
}
/**
* Returns true if the hb version on the host is smaller or equal
* Heartbeat 2.1.4.
*/
public static boolean versionBeforePacemaker(final Host host) {
final String hbV = host.getHeartbeatVersion();
final String pcmkV = host.getPacemakerVersion();
try {
return pcmkV == null
&& hbV != null
&& Tools.compareVersions(hbV, "2.99.0") < 0;
} catch (Exceptions.IllegalVersionException e) {
Tools.appWarning(e.getMessage(), e);
return false;
}
}
}
| true | true | public static JScrollPane getScrollingMenu(
final MyMenu menu,
final DefaultListModel dlm,
final MyList list,
final Map<MyMenuItem, ButtonCallback> callbackHash) {
prevScrollingMenuIndex = -1;
list.setFixedCellHeight(25);
final int maxSize = dlm.getSize();
if (maxSize <= 0) {
return null;
}
if (maxSize > 20) {
list.setVisibleRowCount(20);
} else {
list.setVisibleRowCount(maxSize);
}
list.addMouseListener(new MouseAdapter() {
@Override public void mouseExited(final MouseEvent evt) {
prevScrollingMenuIndex = -1;
if (callbackHash != null) {
for (final MyMenuItem item : callbackHash.keySet()) {
callbackHash.get(item).mouseOut();
list.clearSelection();
}
}
}
@Override public void mouseEntered(final MouseEvent evt) {
list.requestFocus();
}
@Override public void mousePressed(final MouseEvent evt) {
prevScrollingMenuIndex = -1;
if (callbackHash != null) {
for (final MyMenuItem item : callbackHash.keySet()) {
callbackHash.get(item).mouseOut();
}
}
final Thread thread = new Thread(new Runnable() {
@Override public void run() {
final int index = list.locationToIndex(evt.getPoint());
SwingUtilities.invokeLater(new Runnable() {
@Override public void run() {
list.setSelectedIndex(index);
//TODO: some submenus stay visible, during
//ptest, but this breaks group popup menu
//setMenuVisible(menu, false);
menu.setSelected(false);
}
});
final MyMenuItem item =
(MyMenuItem) dlm.elementAt(index);
item.action();
}
});
thread.start();
}
});
list.addMouseMotionListener(new MouseMotionAdapter() {
@Override public void mouseMoved(final MouseEvent evt) {
final Thread thread = new Thread(new Runnable() {
@Override public void run() {
int pIndex = list.locationToIndex(evt.getPoint());
if (!list.getCellBounds(pIndex, pIndex).contains(
evt.getPoint())) {
pIndex = -1;
}
final int index = pIndex;
final int lastIndex = prevScrollingMenuIndex;
if (index == lastIndex) {
return;
}
prevScrollingMenuIndex = index;
SwingUtilities.invokeLater(new Runnable() {
@Override public void run() {
list.setSelectedIndex(index);
}
});
if (callbackHash != null) {
if (lastIndex >= 0) {
final MyMenuItem lastItem =
(MyMenuItem) dlm.elementAt(lastIndex);
callbackHash.get(lastItem).mouseOut();
}
if (index >= 0) {
final MyMenuItem item =
(MyMenuItem) dlm.elementAt(index);
callbackHash.get(item).mouseOver();
}
}
}
});
thread.start();
}
});
final JScrollPane sp = new JScrollPane(list);
sp.setViewportBorder(null);
sp.setBorder(null);
list.addKeyListener(new KeyAdapter() {
@Override public void keyTyped(final KeyEvent e) {
final char ch = e.getKeyChar();
if (ch == ' ' || ch == '\n') {
final MyMenuItem item =
(MyMenuItem) list.getSelectedValue();
//SwingUtilities.invokeLater(new Runnable() {
// @Override public void run() {
// //menu.setPopupMenuVisible(false);
// setMenuVisible(menu, false);
// }
//});
if (item != null) {
item.action();
}
} else {
if (Character.isLetterOrDigit(ch)) {
final Thread t = new Thread(new Runnable() {
@Override public void run() {
getGUIData().getMainGlassPane().start("" + ch,
null,
true);
stopProgressIndicator("" + ch);
}
});
t.start();
}
}
}
});
return sp;
}
| public static JScrollPane getScrollingMenu(
final MyMenu menu,
final DefaultListModel dlm,
final MyList list,
final Map<MyMenuItem, ButtonCallback> callbackHash) {
prevScrollingMenuIndex = -1;
list.setFixedCellHeight(25);
final int maxSize = dlm.getSize();
if (maxSize <= 0) {
return null;
}
if (maxSize > 20) {
list.setVisibleRowCount(20);
} else {
list.setVisibleRowCount(maxSize);
}
list.addMouseListener(new MouseAdapter() {
@Override public void mouseExited(final MouseEvent evt) {
prevScrollingMenuIndex = -1;
if (callbackHash != null) {
for (final MyMenuItem item : callbackHash.keySet()) {
callbackHash.get(item).mouseOut();
list.clearSelection();
}
}
}
@Override public void mouseEntered(final MouseEvent evt) {
/* request focus here causes the applet making all
textfields to be not editable. */
/* list.requestFocus(); */
}
@Override public void mousePressed(final MouseEvent evt) {
prevScrollingMenuIndex = -1;
if (callbackHash != null) {
for (final MyMenuItem item : callbackHash.keySet()) {
callbackHash.get(item).mouseOut();
}
}
final Thread thread = new Thread(new Runnable() {
@Override public void run() {
final int index = list.locationToIndex(evt.getPoint());
SwingUtilities.invokeLater(new Runnable() {
@Override public void run() {
list.setSelectedIndex(index);
//TODO: some submenus stay visible, during
//ptest, but this breaks group popup menu
//setMenuVisible(menu, false);
menu.setSelected(false);
}
});
final MyMenuItem item =
(MyMenuItem) dlm.elementAt(index);
item.action();
}
});
thread.start();
}
});
list.addMouseMotionListener(new MouseMotionAdapter() {
@Override public void mouseMoved(final MouseEvent evt) {
final Thread thread = new Thread(new Runnable() {
@Override public void run() {
int pIndex = list.locationToIndex(evt.getPoint());
if (!list.getCellBounds(pIndex, pIndex).contains(
evt.getPoint())) {
pIndex = -1;
}
final int index = pIndex;
final int lastIndex = prevScrollingMenuIndex;
if (index == lastIndex) {
return;
}
prevScrollingMenuIndex = index;
SwingUtilities.invokeLater(new Runnable() {
@Override public void run() {
list.setSelectedIndex(index);
}
});
if (callbackHash != null) {
if (lastIndex >= 0) {
final MyMenuItem lastItem =
(MyMenuItem) dlm.elementAt(lastIndex);
callbackHash.get(lastItem).mouseOut();
}
if (index >= 0) {
final MyMenuItem item =
(MyMenuItem) dlm.elementAt(index);
callbackHash.get(item).mouseOver();
}
}
}
});
thread.start();
}
});
final JScrollPane sp = new JScrollPane(list);
sp.setViewportBorder(null);
sp.setBorder(null);
list.addKeyListener(new KeyAdapter() {
@Override public void keyTyped(final KeyEvent e) {
final char ch = e.getKeyChar();
if (ch == ' ' || ch == '\n') {
final MyMenuItem item =
(MyMenuItem) list.getSelectedValue();
//SwingUtilities.invokeLater(new Runnable() {
// @Override public void run() {
// //menu.setPopupMenuVisible(false);
// setMenuVisible(menu, false);
// }
//});
if (item != null) {
item.action();
}
} else {
if (Character.isLetterOrDigit(ch)) {
final Thread t = new Thread(new Runnable() {
@Override public void run() {
getGUIData().getMainGlassPane().start("" + ch,
null,
true);
stopProgressIndicator("" + ch);
}
});
t.start();
}
}
}
});
return sp;
}
|
diff --git a/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/p2/director/SimplePlanner.java b/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/p2/director/SimplePlanner.java
index bb5e854cb..eb86b3296 100644
--- a/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/p2/director/SimplePlanner.java
+++ b/bundles/org.eclipse.equinox.p2.director/src/org/eclipse/equinox/internal/p2/director/SimplePlanner.java
@@ -1,446 +1,446 @@
/*******************************************************************************
* Copyright (c) 2007, 2008 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
* Genuitec - bug fixes
******************************************************************************/
package org.eclipse.equinox.internal.p2.director;
import java.net.URI;
import java.util.*;
import org.eclipse.core.runtime.*;
import org.eclipse.equinox.internal.p2.core.helpers.*;
import org.eclipse.equinox.internal.p2.resolution.ResolutionHelper;
import org.eclipse.equinox.internal.p2.rollback.FormerState;
import org.eclipse.equinox.internal.provisional.p2.core.*;
import org.eclipse.equinox.internal.provisional.p2.core.repository.IRepositoryManager;
import org.eclipse.equinox.internal.provisional.p2.director.*;
import org.eclipse.equinox.internal.provisional.p2.engine.*;
import org.eclipse.equinox.internal.provisional.p2.metadata.*;
import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory.InstallableUnitDescription;
import org.eclipse.equinox.internal.provisional.p2.metadata.query.InstallableUnitQuery;
import org.eclipse.equinox.internal.provisional.p2.metadata.query.UpdateQuery;
import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository;
import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepositoryManager;
import org.eclipse.equinox.internal.provisional.p2.query.*;
public class SimplePlanner implements IPlanner {
private static boolean DEBUG = Tracing.DEBUG_PLANNER_OPERANDS;
private static final int ExpandWork = 12;
private static final String PLANNER_MARKER = "private.org.eclipse.equinox.p2.planner.installed"; //$NON-NLS-1$
private static final String INCLUDE_PROFILE_IUS = "org.eclipse.equinox.p2.internal.profileius"; //$NON-NLS-1$
public static final String INCLUSION_RULES = "org.eclipse.equinox.p2.internal.inclusion.rules"; //$NON-NLS-1$
private static final String EXPLANATION = "org.eclipse.equinox.p2.director.explain"; //$NON-NLS-1$
private ProvisioningPlan generateProvisioningPlan(IStatus status, Collection fromState, Collection toState, ProfileChangeRequest changeRequest) {
InstallableUnitOperand[] iuOperands = generateOperations(fromState, toState);
PropertyOperand[] propertyOperands = generatePropertyOperations(changeRequest);
Operand[] operands = new Operand[iuOperands.length + propertyOperands.length];
System.arraycopy(iuOperands, 0, operands, 0, iuOperands.length);
System.arraycopy(propertyOperands, 0, operands, iuOperands.length, propertyOperands.length);
if (status == null)
status = Status.OK_STATUS;
if (DEBUG) {
for (int i = 0; i < operands.length; i++) {
Tracing.debug(operands[i].toString());
}
}
return new ProvisioningPlan(status, operands, computeActualChangeRequest(toState, changeRequest), null);
}
private Map[] buildDetailedErrors(ProfileChangeRequest changeRequest) {
IInstallableUnit[] added = changeRequest.getAddedInstallableUnits();
IInstallableUnit[] removed = changeRequest.getRemovedInstallableUnits();
Map requestStatus = new HashMap(added.length + removed.length);
for (int i = 0; i < added.length; i++) {
requestStatus.put(added[i], new RequestStatus(added[i], RequestStatus.ADDED, IStatus.ERROR, null));
}
for (int i = 0; i < removed.length; i++) {
requestStatus.put(removed[i], new RequestStatus(removed[i], RequestStatus.REMOVED, IStatus.ERROR, null));
}
return new Map[] {requestStatus, null};
}
private Map[] computeActualChangeRequest(Collection toState, ProfileChangeRequest changeRequest) {
IInstallableUnit[] added = changeRequest.getAddedInstallableUnits();
IInstallableUnit[] removed = changeRequest.getRemovedInstallableUnits();
Map requestStatus = new HashMap(added.length + removed.length);
for (int i = 0; i < added.length; i++) {
if (toState.contains(added[i]))
requestStatus.put(added[i], new RequestStatus(added[i], RequestStatus.ADDED, IStatus.OK, null));
else
requestStatus.put(added[i], new RequestStatus(added[i], RequestStatus.ADDED, IStatus.ERROR, null));
}
for (int i = 0; i < removed.length; i++) {
if (!toState.contains(removed[i]))
requestStatus.put(removed[i], new RequestStatus(removed[i], RequestStatus.REMOVED, IStatus.OK, null));
else
requestStatus.put(removed[i], new RequestStatus(removed[i], RequestStatus.REMOVED, IStatus.ERROR, null));
}
//Compute the side effect changes (e.g. things installed optionally going away)
Collection includedIUs = new HashSet(changeRequest.getProfile().query(new IUProfilePropertyQuery(changeRequest.getProfile(), INCLUSION_RULES, null), new Collector(), null).toCollection());
Map sideEffectStatus = new HashMap(includedIUs.size());
includedIUs.removeAll(toState);
for (Iterator iterator = includedIUs.iterator(); iterator.hasNext();) {
IInstallableUnit removal = (IInstallableUnit) iterator.next();
if (!requestStatus.containsKey(removal))
sideEffectStatus.put(removal, new RequestStatus(removal, RequestStatus.REMOVED, IStatus.INFO, null));
}
return new Map[] {requestStatus, sideEffectStatus};
}
private PropertyOperand[] generatePropertyOperations(ProfileChangeRequest profileChangeRequest) {
IProfile profile = profileChangeRequest.getProfile();
List operands = new ArrayList();
// First deal with profile properties to remove. Only generate an operand if the property was there in the first place
String[] toRemove = profileChangeRequest.getPropertiesToRemove();
Map existingProperties = profile.getProperties();
for (int i = 0; i < toRemove.length; i++) {
if (existingProperties.containsKey(toRemove[i]))
operands.add(new PropertyOperand(toRemove[i], existingProperties.get(toRemove[i]), null));
}
// Now deal with profile property changes/additions
Map propertyChanges = profileChangeRequest.getPropertiesToAdd();
Iterator iter = propertyChanges.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
operands.add(new PropertyOperand((String) entry.getKey(), existingProperties.get(entry.getKey()), entry.getValue()));
}
// Now deal with iu property changes/additions.
// TODO we aren't yet checking that the IU will exist in the final profile, will the engine do this?
Map allIUPropertyChanges = profileChangeRequest.getInstallableUnitProfilePropertiesToAdd();
iter = allIUPropertyChanges.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
IInstallableUnit iu = (IInstallableUnit) entry.getKey();
Map iuPropertyChanges = (Map) entry.getValue();
Iterator iuPropIter = iuPropertyChanges.entrySet().iterator();
while (iuPropIter.hasNext()) {
Map.Entry entry2 = (Map.Entry) iuPropIter.next();
Object oldValue = profile.getInstallableUnitProperty(iu, (String) entry2.getKey());
operands.add(new InstallableUnitPropertyOperand(iu, (String) entry2.getKey(), oldValue, entry2.getValue()));
}
}
// Now deal with iu property removals.
// TODO we could optimize by not generating property removals for IU's that aren't there or won't be there.
Map allIUPropertyDeletions = profileChangeRequest.getInstallableUnitProfilePropertiesToRemove();
iter = allIUPropertyDeletions.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
IInstallableUnit iu = (IInstallableUnit) entry.getKey();
Map existingIUProperties = profile.getInstallableUnitProperties(iu);
List iuPropertyRemovals = (List) entry.getValue();
for (Iterator it = iuPropertyRemovals.iterator(); it.hasNext();) {
String key = (String) it.next();
if (existingIUProperties.containsKey(key))
operands.add(new InstallableUnitPropertyOperand(iu, key, existingIUProperties.get(key), null));
}
}
return (PropertyOperand[]) operands.toArray(new PropertyOperand[operands.size()]);
}
private InstallableUnitOperand[] generateOperations(Collection fromState, Collection toState) {
return new OperationGenerator().generateOperation(fromState, toState);
}
public ProvisioningPlan getRevertPlan(IProfile currentProfile, IProfile revertProfile, ProvisioningContext context, IProgressMonitor monitor) {
SubMonitor sub = SubMonitor.convert(monitor, ExpandWork);
sub.setTaskName(Messages.Director_Task_Resolving_Dependencies);
try {
ProfileChangeRequest profileChangeRequest = FormerState.generateProfileDeltaChangeRequest(currentProfile, revertProfile);
if (context == null)
context = new ProvisioningContext();
if (context.getProperty(INCLUDE_PROFILE_IUS) == null)
context.setProperty(INCLUDE_PROFILE_IUS, Boolean.FALSE.toString());
context.setExtraIUs(new ArrayList(revertProfile.available(InstallableUnitQuery.ANY, new Collector(), null).toCollection()));
return getProvisioningPlan(profileChangeRequest, context, sub.newChild(ExpandWork / 2));
} finally {
sub.done();
}
}
public static IInstallableUnit[] findPlannerMarkedIUs(final IProfile profile) {
Query markerQuery = new MatchQuery() {
public boolean isMatch(Object candidate) {
if (!(candidate instanceof IInstallableUnit))
return false;
IInstallableUnit iu = (IInstallableUnit) candidate;
// TODO: remove marker -- temporary backwards compatibility only
String marker = profile.getInstallableUnitProperty(iu, PLANNER_MARKER);
if (marker != null && Boolean.valueOf(marker).booleanValue())
return true;
String inclusion = profile.getInstallableUnitProperty(iu, INCLUSION_RULES);
return (inclusion != null);
}
};
return (IInstallableUnit[]) profile.query(markerQuery, new Collector(), null).toArray(IInstallableUnit.class);
}
public static Dictionary createSelectionContext(Map properties) {
Hashtable result = new Hashtable(properties);
String environments = (String) properties.get(IProfile.PROP_ENVIRONMENTS);
if (environments == null)
return result;
for (StringTokenizer tokenizer = new StringTokenizer(environments, ","); tokenizer.hasMoreElements();) { //$NON-NLS-1$
String entry = tokenizer.nextToken();
int i = entry.indexOf('=');
String key = entry.substring(0, i).trim();
String value = entry.substring(i + 1).trim();
result.put(key, value);
}
return result;
}
public static IInstallableUnit[] gatherAvailableInstallableUnits(IInstallableUnit[] additionalSource, URI[] repositories, ProvisioningContext context, IProgressMonitor monitor) {
Map resultsMap = new HashMap();
if (additionalSource != null) {
for (int i = 0; i < additionalSource.length; i++) {
String key = additionalSource[i].getId() + "_" + additionalSource[i].getVersion().toString(); //$NON-NLS-1$
resultsMap.put(key, additionalSource[i]);
}
}
if (context != null) {
for (Iterator iter = context.getExtraIUs().iterator(); iter.hasNext();) {
IInstallableUnit iu = (IInstallableUnit) iter.next();
String key = iu.getId() + '_' + iu.getVersion().toString();
resultsMap.put(key, iu);
}
}
IMetadataRepositoryManager repoMgr = (IMetadataRepositoryManager) ServiceHelper.getService(DirectorActivator.context, IMetadataRepositoryManager.class.getName());
if (repositories == null)
repositories = repoMgr.getKnownRepositories(IRepositoryManager.REPOSITORIES_ALL);
SubMonitor sub = SubMonitor.convert(monitor, repositories.length * 200);
for (int i = 0; i < repositories.length; i++) {
try {
if (sub.isCanceled())
throw new OperationCanceledException();
IMetadataRepository repository = repoMgr.loadRepository(repositories[i], sub.newChild(100));
Collector matches = repository.query(new InstallableUnitQuery(null, VersionRange.emptyRange), new Collector(), sub.newChild(100));
for (Iterator it = matches.iterator(); it.hasNext();) {
IInstallableUnit iu = (IInstallableUnit) it.next();
String key = iu.getId() + "_" + iu.getVersion().toString(); //$NON-NLS-1$
IInstallableUnit currentIU = (IInstallableUnit) resultsMap.get(key);
if (currentIU == null || hasHigherFidelity(iu, currentIU))
resultsMap.put(key, iu);
}
} catch (ProvisionException e) {
//skip unreadable repositories
}
}
sub.done();
Collection results = resultsMap.values();
return (IInstallableUnit[]) results.toArray(new IInstallableUnit[results.size()]);
}
private static boolean hasHigherFidelity(IInstallableUnit iu, IInstallableUnit currentIU) {
if (Boolean.valueOf(currentIU.getProperty(IInstallableUnit.PROP_PARTIAL_IU)).booleanValue() && !Boolean.valueOf(iu.getProperty(IInstallableUnit.PROP_PARTIAL_IU)).booleanValue())
return true;
return false;
}
public ProvisioningPlan getProvisioningPlan(ProfileChangeRequest profileChangeRequest, ProvisioningContext context, IProgressMonitor monitor) {
SubMonitor sub = SubMonitor.convert(monitor, ExpandWork);
sub.setTaskName(Messages.Director_Task_Resolving_Dependencies);
try {
IProfile profile = profileChangeRequest.getProfile();
Object[] updatedPlan = updatePlannerInfo(profileChangeRequest);
URI[] metadataRepositories = (context != null) ? context.getMetadataRepositories() : null;
Dictionary newSelectionContext = createSelectionContext(profileChangeRequest.getProfileProperties());
List extraIUs = new ArrayList(Arrays.asList(profileChangeRequest.getAddedInstallableUnits()));
extraIUs.addAll(Arrays.asList(profileChangeRequest.getRemovedInstallableUnits()));
if (context == null || context.getProperty(INCLUDE_PROFILE_IUS) == null || context.getProperty(INCLUDE_PROFILE_IUS).equalsIgnoreCase(Boolean.TRUE.toString()))
extraIUs.addAll(profile.available(InstallableUnitQuery.ANY, new Collector(), null).toCollection());
IInstallableUnit[] availableIUs = gatherAvailableInstallableUnits((IInstallableUnit[]) extraIUs.toArray(new IInstallableUnit[extraIUs.size()]), metadataRepositories, context, sub.newChild(ExpandWork / 4));
Slicer slicer = new Slicer(new QueryableArray(availableIUs), newSelectionContext);
IQueryable slice = slicer.slice(new IInstallableUnit[] {(IInstallableUnit) updatedPlan[0]}, sub.newChild(ExpandWork / 4));
if (slice == null)
return new ProvisioningPlan(slicer.getStatus());
Projector projector = new Projector(slice, newSelectionContext);
projector.encode((IInstallableUnit) updatedPlan[0], (IInstallableUnit[]) updatedPlan[1], profileChangeRequest.getAddedInstallableUnits(), sub.newChild(ExpandWork / 4));
IStatus s = projector.invokeSolver(sub.newChild(ExpandWork / 4));
if (s.getSeverity() == IStatus.CANCEL)
return new ProvisioningPlan(s);
if (s.getSeverity() == IStatus.ERROR) {
sub.setTaskName(Messages.Planner_NoSolution);
- if (!(context.getProperty(EXPLANATION) == null || Boolean.TRUE.toString().equalsIgnoreCase(context.getProperty(EXPLANATION))))
+ LogHelper.log(s);
+ if (context != null && !(context.getProperty(EXPLANATION) == null || Boolean.TRUE.toString().equalsIgnoreCase(context.getProperty(EXPLANATION))))
return new ProvisioningPlan(s);
boolean newExplanation = Boolean.getBoolean("p2.new.explanation"); //$NON-NLS-1$
- LogHelper.log(s);
if (!newExplanation) {
//We invoke the old resolver to get explanations for now
IStatus oldResolverStatus = new NewDependencyExpander(new IInstallableUnit[] {(IInstallableUnit) updatedPlan[0]}, null, availableIUs, newSelectionContext, false).expand(sub.newChild(ExpandWork / 4));
if (!oldResolverStatus.isOK())
s = oldResolverStatus;
return new ProvisioningPlan(oldResolverStatus, new Operand[0], buildDetailedErrors(profileChangeRequest), new RequestStatus(null, RequestStatus.REMOVED, IStatus.ERROR, null));
}
//Invoke the new resolver
Set explanation = projector.getExplanation();
IStatus explanationStatus = new Status(IStatus.ERROR, DirectorActivator.PI_DIRECTOR, explanation.toString(), null);
return new ProvisioningPlan(explanationStatus, new Operand[0], buildDetailedErrors(profileChangeRequest), new RequestStatus(null, RequestStatus.REMOVED, IStatus.ERROR, explanation));
}
//The resolution succeeded. We can forget about the warnings since there is a solution.
if (Tracing.DEBUG && s.getSeverity() != IStatus.OK)
LogHelper.log(s);
s = Status.OK_STATUS;
Collection newState = projector.extractSolution();
newState.remove(updatedPlan[0]);
ResolutionHelper newStateHelper = new ResolutionHelper(newSelectionContext, null);
newState = newStateHelper.attachCUs(newState);
ResolutionHelper oldStateHelper = new ResolutionHelper(createSelectionContext(profile.getProperties()), null);
Collection oldState = oldStateHelper.attachCUs(profile.query(InstallableUnitQuery.ANY, new Collector(), null).toCollection());
return generateProvisioningPlan(s, oldState, newState, profileChangeRequest);
} catch (OperationCanceledException e) {
return new ProvisioningPlan(Status.CANCEL_STATUS);
} finally {
sub.done();
}
}
private IInstallableUnit createIURepresentingTheProfile(ArrayList allRequirements) {
InstallableUnitDescription iud = new MetadataFactory.InstallableUnitDescription();
String time = Long.toString(System.currentTimeMillis());
iud.setId(time);
iud.setVersion(new Version(0, 0, 0, time));
iud.setRequiredCapabilities((IRequiredCapability[]) allRequirements.toArray(new IRequiredCapability[allRequirements.size()]));
return MetadataFactory.createInstallableUnit(iud);
}
//The planner uses installable unit properties to keep track of what it has been asked to install. This updates this information
//It returns at index 0 a meta IU representing everything that needs to be installed
//It returns at index 1 all the IUs that are in the profile after the removal have been done, but before the addition have been done
private Object[] updatePlannerInfo(ProfileChangeRequest profileChangeRequest) {
Collection includedIUs = profileChangeRequest.getProfile().query(new IUProfilePropertyQuery(profileChangeRequest.getProfile(), INCLUSION_RULES, null), new Collector(), null).toCollection();
Collection alreadyInstalled = new HashSet(includedIUs);
IInstallableUnit[] added = profileChangeRequest.getAddedInstallableUnits();
IInstallableUnit[] removed = profileChangeRequest.getRemovedInstallableUnits();
for (Iterator iterator = profileChangeRequest.getInstallableUnitProfilePropertiesToRemove().entrySet().iterator(); iterator.hasNext();) {
Map.Entry object = (Map.Entry) iterator.next();
if (((List) object.getValue()).contains(INCLUSION_RULES))
profileChangeRequest.setInstallableUnitProfileProperty((IInstallableUnit) object.getKey(), INCLUSION_RULES, PlannerHelper.createStrictInclusionRule((IInstallableUnit) object.getKey()));
}
//Remove the iu properties associated to the ius removed and the iu properties being removed as well
for (Iterator iterator = alreadyInstalled.iterator(); iterator.hasNext();) {
IInstallableUnit iu = (IInstallableUnit) iterator.next();
for (int i = 0; i < removed.length; i++) {
if (iu.equals(removed[i])) {
profileChangeRequest.removeInstallableUnitProfileProperty(removed[i], INCLUSION_RULES);
iterator.remove();
break;
}
}
}
ArrayList gatheredRequirements = new ArrayList();
//Process all the IUs being added
Map iuPropertiesToAdd = profileChangeRequest.getInstallableUnitProfilePropertiesToAdd();
for (int i = 0; i < added.length; i++) {
Map propertiesForIU = (Map) iuPropertiesToAdd.get(added[i]);
IRequiredCapability profileRequirement = null;
if (propertiesForIU != null) {
profileRequirement = createRequirement(added[i], (String) propertiesForIU.get(INCLUSION_RULES));
}
if (profileRequirement == null) {
profileChangeRequest.setInstallableUnitProfileProperty(added[i], INCLUSION_RULES, PlannerHelper.createStrictInclusionRule(added[i]));
profileRequirement = createStrictRequirement(added[i]);
}
gatheredRequirements.add(profileRequirement);
}
//Process the IUs that were already there
for (Iterator iterator = alreadyInstalled.iterator(); iterator.hasNext();) {
IInstallableUnit iu = (IInstallableUnit) iterator.next();
Map propertiesForIU = (Map) iuPropertiesToAdd.get(iu);
IRequiredCapability profileRequirement = null;
//Test if the value has changed
if (propertiesForIU != null) {
profileRequirement = createRequirement(iu, (String) propertiesForIU.get(INCLUSION_RULES));
}
if (profileRequirement == null) {
profileRequirement = createRequirement(iu, profileChangeRequest.getProfile().getInstallableUnitProperty(iu, INCLUSION_RULES));
}
gatheredRequirements.add(profileRequirement);
}
return new Object[] {createIURepresentingTheProfile(gatheredRequirements), (IInstallableUnit[]) alreadyInstalled.toArray(new IInstallableUnit[alreadyInstalled.size()])};
}
private IRequiredCapability createRequirement(IInstallableUnit iu, String rule) {
if (rule == null)
return null;
if (rule.equals(PlannerHelper.createStrictInclusionRule(iu))) {
return createStrictRequirement(iu);
}
if (rule.equals(PlannerHelper.createOptionalInclusionRule(iu))) {
return createOptionalRequirement(iu);
}
return null;
}
private IRequiredCapability createOptionalRequirement(IInstallableUnit iu) {
return MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, iu.getId(), new VersionRange(iu.getVersion(), true, iu.getVersion(), true), null, true, false, true);
}
private IRequiredCapability createStrictRequirement(IInstallableUnit iu) {
return MetadataFactory.createRequiredCapability(IInstallableUnit.NAMESPACE_IU_ID, iu.getId(), new VersionRange(iu.getVersion(), true, iu.getVersion(), true), null, false, false, true);
}
public IInstallableUnit[] updatesFor(IInstallableUnit toUpdate, ProvisioningContext context, IProgressMonitor monitor) {
Map resultsMap = new HashMap();
IMetadataRepositoryManager repoMgr = (IMetadataRepositoryManager) ServiceHelper.getService(DirectorActivator.context, IMetadataRepositoryManager.class.getName());
URI[] repositories = context.getMetadataRepositories();
if (repositories == null)
repositories = repoMgr.getKnownRepositories(IRepositoryManager.REPOSITORIES_ALL);
SubMonitor sub = SubMonitor.convert(monitor, repositories.length * 200);
for (int i = 0; i < repositories.length; i++) {
try {
if (sub.isCanceled())
throw new OperationCanceledException();
IMetadataRepository repository = repoMgr.loadRepository(repositories[i], sub.newChild(100));
Collector matches = repository.query(new UpdateQuery(toUpdate), new Collector(), sub.newChild(100));
for (Iterator it = matches.iterator(); it.hasNext();) {
IInstallableUnit iu = (IInstallableUnit) it.next();
String key = iu.getId() + "_" + iu.getVersion().toString(); //$NON-NLS-1$
IInstallableUnit currentIU = (IInstallableUnit) resultsMap.get(key);
if (currentIU == null || hasHigherFidelity(iu, currentIU))
resultsMap.put(key, iu);
}
} catch (ProvisionException e) {
//skip unreadable repositories
}
}
sub.done();
Collection results = resultsMap.values();
return (IInstallableUnit[]) results.toArray(new IInstallableUnit[results.size()]);
}
}
| false | true | public ProvisioningPlan getProvisioningPlan(ProfileChangeRequest profileChangeRequest, ProvisioningContext context, IProgressMonitor monitor) {
SubMonitor sub = SubMonitor.convert(monitor, ExpandWork);
sub.setTaskName(Messages.Director_Task_Resolving_Dependencies);
try {
IProfile profile = profileChangeRequest.getProfile();
Object[] updatedPlan = updatePlannerInfo(profileChangeRequest);
URI[] metadataRepositories = (context != null) ? context.getMetadataRepositories() : null;
Dictionary newSelectionContext = createSelectionContext(profileChangeRequest.getProfileProperties());
List extraIUs = new ArrayList(Arrays.asList(profileChangeRequest.getAddedInstallableUnits()));
extraIUs.addAll(Arrays.asList(profileChangeRequest.getRemovedInstallableUnits()));
if (context == null || context.getProperty(INCLUDE_PROFILE_IUS) == null || context.getProperty(INCLUDE_PROFILE_IUS).equalsIgnoreCase(Boolean.TRUE.toString()))
extraIUs.addAll(profile.available(InstallableUnitQuery.ANY, new Collector(), null).toCollection());
IInstallableUnit[] availableIUs = gatherAvailableInstallableUnits((IInstallableUnit[]) extraIUs.toArray(new IInstallableUnit[extraIUs.size()]), metadataRepositories, context, sub.newChild(ExpandWork / 4));
Slicer slicer = new Slicer(new QueryableArray(availableIUs), newSelectionContext);
IQueryable slice = slicer.slice(new IInstallableUnit[] {(IInstallableUnit) updatedPlan[0]}, sub.newChild(ExpandWork / 4));
if (slice == null)
return new ProvisioningPlan(slicer.getStatus());
Projector projector = new Projector(slice, newSelectionContext);
projector.encode((IInstallableUnit) updatedPlan[0], (IInstallableUnit[]) updatedPlan[1], profileChangeRequest.getAddedInstallableUnits(), sub.newChild(ExpandWork / 4));
IStatus s = projector.invokeSolver(sub.newChild(ExpandWork / 4));
if (s.getSeverity() == IStatus.CANCEL)
return new ProvisioningPlan(s);
if (s.getSeverity() == IStatus.ERROR) {
sub.setTaskName(Messages.Planner_NoSolution);
if (!(context.getProperty(EXPLANATION) == null || Boolean.TRUE.toString().equalsIgnoreCase(context.getProperty(EXPLANATION))))
return new ProvisioningPlan(s);
boolean newExplanation = Boolean.getBoolean("p2.new.explanation"); //$NON-NLS-1$
LogHelper.log(s);
if (!newExplanation) {
//We invoke the old resolver to get explanations for now
IStatus oldResolverStatus = new NewDependencyExpander(new IInstallableUnit[] {(IInstallableUnit) updatedPlan[0]}, null, availableIUs, newSelectionContext, false).expand(sub.newChild(ExpandWork / 4));
if (!oldResolverStatus.isOK())
s = oldResolverStatus;
return new ProvisioningPlan(oldResolverStatus, new Operand[0], buildDetailedErrors(profileChangeRequest), new RequestStatus(null, RequestStatus.REMOVED, IStatus.ERROR, null));
}
//Invoke the new resolver
Set explanation = projector.getExplanation();
IStatus explanationStatus = new Status(IStatus.ERROR, DirectorActivator.PI_DIRECTOR, explanation.toString(), null);
return new ProvisioningPlan(explanationStatus, new Operand[0], buildDetailedErrors(profileChangeRequest), new RequestStatus(null, RequestStatus.REMOVED, IStatus.ERROR, explanation));
}
//The resolution succeeded. We can forget about the warnings since there is a solution.
if (Tracing.DEBUG && s.getSeverity() != IStatus.OK)
LogHelper.log(s);
s = Status.OK_STATUS;
Collection newState = projector.extractSolution();
newState.remove(updatedPlan[0]);
ResolutionHelper newStateHelper = new ResolutionHelper(newSelectionContext, null);
newState = newStateHelper.attachCUs(newState);
ResolutionHelper oldStateHelper = new ResolutionHelper(createSelectionContext(profile.getProperties()), null);
Collection oldState = oldStateHelper.attachCUs(profile.query(InstallableUnitQuery.ANY, new Collector(), null).toCollection());
return generateProvisioningPlan(s, oldState, newState, profileChangeRequest);
} catch (OperationCanceledException e) {
return new ProvisioningPlan(Status.CANCEL_STATUS);
} finally {
sub.done();
}
}
| public ProvisioningPlan getProvisioningPlan(ProfileChangeRequest profileChangeRequest, ProvisioningContext context, IProgressMonitor monitor) {
SubMonitor sub = SubMonitor.convert(monitor, ExpandWork);
sub.setTaskName(Messages.Director_Task_Resolving_Dependencies);
try {
IProfile profile = profileChangeRequest.getProfile();
Object[] updatedPlan = updatePlannerInfo(profileChangeRequest);
URI[] metadataRepositories = (context != null) ? context.getMetadataRepositories() : null;
Dictionary newSelectionContext = createSelectionContext(profileChangeRequest.getProfileProperties());
List extraIUs = new ArrayList(Arrays.asList(profileChangeRequest.getAddedInstallableUnits()));
extraIUs.addAll(Arrays.asList(profileChangeRequest.getRemovedInstallableUnits()));
if (context == null || context.getProperty(INCLUDE_PROFILE_IUS) == null || context.getProperty(INCLUDE_PROFILE_IUS).equalsIgnoreCase(Boolean.TRUE.toString()))
extraIUs.addAll(profile.available(InstallableUnitQuery.ANY, new Collector(), null).toCollection());
IInstallableUnit[] availableIUs = gatherAvailableInstallableUnits((IInstallableUnit[]) extraIUs.toArray(new IInstallableUnit[extraIUs.size()]), metadataRepositories, context, sub.newChild(ExpandWork / 4));
Slicer slicer = new Slicer(new QueryableArray(availableIUs), newSelectionContext);
IQueryable slice = slicer.slice(new IInstallableUnit[] {(IInstallableUnit) updatedPlan[0]}, sub.newChild(ExpandWork / 4));
if (slice == null)
return new ProvisioningPlan(slicer.getStatus());
Projector projector = new Projector(slice, newSelectionContext);
projector.encode((IInstallableUnit) updatedPlan[0], (IInstallableUnit[]) updatedPlan[1], profileChangeRequest.getAddedInstallableUnits(), sub.newChild(ExpandWork / 4));
IStatus s = projector.invokeSolver(sub.newChild(ExpandWork / 4));
if (s.getSeverity() == IStatus.CANCEL)
return new ProvisioningPlan(s);
if (s.getSeverity() == IStatus.ERROR) {
sub.setTaskName(Messages.Planner_NoSolution);
LogHelper.log(s);
if (context != null && !(context.getProperty(EXPLANATION) == null || Boolean.TRUE.toString().equalsIgnoreCase(context.getProperty(EXPLANATION))))
return new ProvisioningPlan(s);
boolean newExplanation = Boolean.getBoolean("p2.new.explanation"); //$NON-NLS-1$
if (!newExplanation) {
//We invoke the old resolver to get explanations for now
IStatus oldResolverStatus = new NewDependencyExpander(new IInstallableUnit[] {(IInstallableUnit) updatedPlan[0]}, null, availableIUs, newSelectionContext, false).expand(sub.newChild(ExpandWork / 4));
if (!oldResolverStatus.isOK())
s = oldResolverStatus;
return new ProvisioningPlan(oldResolverStatus, new Operand[0], buildDetailedErrors(profileChangeRequest), new RequestStatus(null, RequestStatus.REMOVED, IStatus.ERROR, null));
}
//Invoke the new resolver
Set explanation = projector.getExplanation();
IStatus explanationStatus = new Status(IStatus.ERROR, DirectorActivator.PI_DIRECTOR, explanation.toString(), null);
return new ProvisioningPlan(explanationStatus, new Operand[0], buildDetailedErrors(profileChangeRequest), new RequestStatus(null, RequestStatus.REMOVED, IStatus.ERROR, explanation));
}
//The resolution succeeded. We can forget about the warnings since there is a solution.
if (Tracing.DEBUG && s.getSeverity() != IStatus.OK)
LogHelper.log(s);
s = Status.OK_STATUS;
Collection newState = projector.extractSolution();
newState.remove(updatedPlan[0]);
ResolutionHelper newStateHelper = new ResolutionHelper(newSelectionContext, null);
newState = newStateHelper.attachCUs(newState);
ResolutionHelper oldStateHelper = new ResolutionHelper(createSelectionContext(profile.getProperties()), null);
Collection oldState = oldStateHelper.attachCUs(profile.query(InstallableUnitQuery.ANY, new Collector(), null).toCollection());
return generateProvisioningPlan(s, oldState, newState, profileChangeRequest);
} catch (OperationCanceledException e) {
return new ProvisioningPlan(Status.CANCEL_STATUS);
} finally {
sub.done();
}
}
|
diff --git a/src/main/java/com/mozilla/bagheera/consumer/KafkaReplayConsumer.java b/src/main/java/com/mozilla/bagheera/consumer/KafkaReplayConsumer.java
index 7cb5c1d..7e3d059 100644
--- a/src/main/java/com/mozilla/bagheera/consumer/KafkaReplayConsumer.java
+++ b/src/main/java/com/mozilla/bagheera/consumer/KafkaReplayConsumer.java
@@ -1,87 +1,87 @@
/*
* Copyright 2013 Mozilla Foundation
*
* 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 com.mozilla.bagheera.consumer;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.log4j.Logger;
import com.mozilla.bagheera.cli.App;
import com.mozilla.bagheera.cli.OptionFactory;
import com.mozilla.bagheera.sink.KeyValueSinkFactory;
import com.mozilla.bagheera.sink.ReplaySink;
import com.mozilla.bagheera.sink.SinkConfiguration;
import com.mozilla.bagheera.util.ShutdownHook;
/**
* Kafka consumer which reads from one kafka queue and re-creates requests to send elsewhere.
*/
public final class KafkaReplayConsumer extends App {
private static final Logger LOG = Logger.getLogger(KafkaReplayConsumer.class);
public static void main(String[] args) {
OptionFactory optFactory = OptionFactory.getInstance();
Options options = KafkaConsumer.getOptions();
- options.addOption(optFactory.create("k", "copy-keys", true, "Whether or not to copy keys from the source data").required());
- options.addOption(optFactory.create("d", "dest", true, "Destination host / url pattern (include '" + ReplaySink.KEY_PLACEHOLDER + "' for key placeholder)"));
+ options.addOption(optFactory.create("k", "copy-keys", true, "Whether or not to copy keys from the source data"));
+ options.addOption(optFactory.create("d", "dest", true, "Destination host / url pattern (include '" + ReplaySink.KEY_PLACEHOLDER + "' for key placeholder)").required());
options.addOption(optFactory.create("s", "sample", true, "Rate at which to sample the source data (defaults to using all data)"));
options.addOption(optFactory.create("D", "delete", true, "Also replay deletes (using the source keys by necessity)"));
CommandLineParser parser = new GnuParser();
ShutdownHook sh = ShutdownHook.getInstance();
try {
// Parse command line options
CommandLine cmd = parser.parse(options, args);
final KafkaConsumer consumer = KafkaConsumer.fromOptions(cmd);
sh.addFirst(consumer);
// Create a sink for storing data
SinkConfiguration sinkConfig = new SinkConfiguration();
if (cmd.hasOption("numthreads")) {
sinkConfig.setInt("hbasesink.hbase.numthreads", Integer.parseInt(cmd.getOptionValue("numthreads")));
}
sinkConfig.setString("replaysink.keys", cmd.getOptionValue("copy-keys", "true"));
sinkConfig.setString("replaysink.dest", cmd.getOptionValue("dest", "http://bogus:8080/submit/endpoint/" + ReplaySink.KEY_PLACEHOLDER));
sinkConfig.setString("replaysink.sample", cmd.getOptionValue("sample", "1"));
sinkConfig.setString("replaysink.delete", cmd.getOptionValue("delete", "true"));
KeyValueSinkFactory sinkFactory = KeyValueSinkFactory.getInstance(ReplaySink.class, sinkConfig);
sh.addLast(sinkFactory);
// Set the sink factory for consumer storage
consumer.setSinkFactory(sinkFactory);
prepareHealthChecks();
// Begin polling
consumer.poll();
} catch (ParseException e) {
LOG.error("Error parsing command line options", e);
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp(KafkaReplayConsumer.class.getName(), options);
}
}
}
| true | true | public static void main(String[] args) {
OptionFactory optFactory = OptionFactory.getInstance();
Options options = KafkaConsumer.getOptions();
options.addOption(optFactory.create("k", "copy-keys", true, "Whether or not to copy keys from the source data").required());
options.addOption(optFactory.create("d", "dest", true, "Destination host / url pattern (include '" + ReplaySink.KEY_PLACEHOLDER + "' for key placeholder)"));
options.addOption(optFactory.create("s", "sample", true, "Rate at which to sample the source data (defaults to using all data)"));
options.addOption(optFactory.create("D", "delete", true, "Also replay deletes (using the source keys by necessity)"));
CommandLineParser parser = new GnuParser();
ShutdownHook sh = ShutdownHook.getInstance();
try {
// Parse command line options
CommandLine cmd = parser.parse(options, args);
final KafkaConsumer consumer = KafkaConsumer.fromOptions(cmd);
sh.addFirst(consumer);
// Create a sink for storing data
SinkConfiguration sinkConfig = new SinkConfiguration();
if (cmd.hasOption("numthreads")) {
sinkConfig.setInt("hbasesink.hbase.numthreads", Integer.parseInt(cmd.getOptionValue("numthreads")));
}
sinkConfig.setString("replaysink.keys", cmd.getOptionValue("copy-keys", "true"));
sinkConfig.setString("replaysink.dest", cmd.getOptionValue("dest", "http://bogus:8080/submit/endpoint/" + ReplaySink.KEY_PLACEHOLDER));
sinkConfig.setString("replaysink.sample", cmd.getOptionValue("sample", "1"));
sinkConfig.setString("replaysink.delete", cmd.getOptionValue("delete", "true"));
KeyValueSinkFactory sinkFactory = KeyValueSinkFactory.getInstance(ReplaySink.class, sinkConfig);
sh.addLast(sinkFactory);
// Set the sink factory for consumer storage
consumer.setSinkFactory(sinkFactory);
prepareHealthChecks();
// Begin polling
consumer.poll();
} catch (ParseException e) {
LOG.error("Error parsing command line options", e);
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp(KafkaReplayConsumer.class.getName(), options);
}
}
| public static void main(String[] args) {
OptionFactory optFactory = OptionFactory.getInstance();
Options options = KafkaConsumer.getOptions();
options.addOption(optFactory.create("k", "copy-keys", true, "Whether or not to copy keys from the source data"));
options.addOption(optFactory.create("d", "dest", true, "Destination host / url pattern (include '" + ReplaySink.KEY_PLACEHOLDER + "' for key placeholder)").required());
options.addOption(optFactory.create("s", "sample", true, "Rate at which to sample the source data (defaults to using all data)"));
options.addOption(optFactory.create("D", "delete", true, "Also replay deletes (using the source keys by necessity)"));
CommandLineParser parser = new GnuParser();
ShutdownHook sh = ShutdownHook.getInstance();
try {
// Parse command line options
CommandLine cmd = parser.parse(options, args);
final KafkaConsumer consumer = KafkaConsumer.fromOptions(cmd);
sh.addFirst(consumer);
// Create a sink for storing data
SinkConfiguration sinkConfig = new SinkConfiguration();
if (cmd.hasOption("numthreads")) {
sinkConfig.setInt("hbasesink.hbase.numthreads", Integer.parseInt(cmd.getOptionValue("numthreads")));
}
sinkConfig.setString("replaysink.keys", cmd.getOptionValue("copy-keys", "true"));
sinkConfig.setString("replaysink.dest", cmd.getOptionValue("dest", "http://bogus:8080/submit/endpoint/" + ReplaySink.KEY_PLACEHOLDER));
sinkConfig.setString("replaysink.sample", cmd.getOptionValue("sample", "1"));
sinkConfig.setString("replaysink.delete", cmd.getOptionValue("delete", "true"));
KeyValueSinkFactory sinkFactory = KeyValueSinkFactory.getInstance(ReplaySink.class, sinkConfig);
sh.addLast(sinkFactory);
// Set the sink factory for consumer storage
consumer.setSinkFactory(sinkFactory);
prepareHealthChecks();
// Begin polling
consumer.poll();
} catch (ParseException e) {
LOG.error("Error parsing command line options", e);
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp(KafkaReplayConsumer.class.getName(), options);
}
}
|
diff --git a/ide/eclipse/esb/org.wso2.developerstudio.eclipse.gmf.esb.persistence/src/org/wso2/developerstudio/eclipse/gmf/esb/internal/persistence/MessageStoreTransformer.java b/ide/eclipse/esb/org.wso2.developerstudio.eclipse.gmf.esb.persistence/src/org/wso2/developerstudio/eclipse/gmf/esb/internal/persistence/MessageStoreTransformer.java
index 6946e1658..3c13a0d31 100755
--- a/ide/eclipse/esb/org.wso2.developerstudio.eclipse.gmf.esb.persistence/src/org/wso2/developerstudio/eclipse/gmf/esb/internal/persistence/MessageStoreTransformer.java
+++ b/ide/eclipse/esb/org.wso2.developerstudio.eclipse.gmf.esb.persistence/src/org/wso2/developerstudio/eclipse/gmf/esb/internal/persistence/MessageStoreTransformer.java
@@ -1,108 +1,108 @@
/*
* Copyright (c) WSO2, Inc. (http://wso2.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.developerstudio.eclipse.gmf.esb.internal.persistence;
import java.util.HashMap;
import java.util.Map;
import javax.xml.namespace.QName;
import org.apache.axiom.om.OMAttribute;
import org.apache.axiom.om.OMElement;
import org.apache.commons.lang.StringUtils;
import org.apache.synapse.config.xml.MessageStoreSerializer;
import org.eclipse.emf.common.util.EList;
import org.wso2.developerstudio.eclipse.gmf.esb.MessageStore;
import org.wso2.developerstudio.eclipse.gmf.esb.MessageStoreParameter;
import org.wso2.developerstudio.eclipse.gmf.esb.MessageStoreType;
import org.apache.synapse.message.store.impl.memory.InMemoryStore;
public class MessageStoreTransformer {
public static OMElement createMessageStore(MessageStore model) throws Exception {
Map<String, Object> parameters = new HashMap<String, Object>();
// Fixing TOOLS-2026.
//String className = "org.apache.synapse.message.store.InMemoryMessageStore";
//String className = "org.apache.synapse.message.store.impl.memory.InMemoryStore";
String className = null;
org.apache.synapse.message.store.MessageStore messageStore = new InMemoryStore();
messageStore.setName(model.getStoreName());
if (model.getStoreType() == MessageStoreType.CUSTOM) {
className = model.getProviderClass();
EList<MessageStoreParameter> parameters2 = model.getParameters();
for (MessageStoreParameter param : parameters2) {
if (!StringUtils.isBlank(param.getParameterName())
&& !StringUtils.isBlank(param.getParameterValue())) {
parameters.put(param.getParameterName(), param.getParameterValue());
}
}
} else if (model.getStoreType() == MessageStoreType.JMS) {
// Fixing TOOLS-2026.
//className = "org.wso2.carbon.message.store.persistence.jms.JMSMessageStore";
className = "org.apache.synapse.message.store.impl.jms.JmsStore";
if (!StringUtils.isBlank(model.getInitialContextFactory())) {
parameters.put("java.naming.factory.initial",
model.getInitialContextFactory());
}
if (!StringUtils.isBlank(model.getProviderURL())) {
parameters.put("java.naming.provider.url", model.getProviderURL());
}
if (!StringUtils.isBlank(model.getJndiQueueName())) {
parameters.put("store.jms.destination", model.getJndiQueueName());
}
- if (!StringUtils.isBlank(model.getInitialContextFactory())) {
+ if (!StringUtils.isBlank(model.getConnectionFactory())) {
parameters.put("store.jms.connection.factory",
- model.getInitialContextFactory());
+ model.getConnectionFactory());
}
if (!StringUtils.isBlank(model.getUserName())) {
parameters.put("store.jms.username", model.getUserName());
}
if (!StringUtils.isBlank(model.getPassword())) {
parameters.put("store.jms.password", model.getPassword());
}
parameters.put("store.jms.JMSSpecVersion", model.getJmsSpecVersion().getLiteral());
parameters.put("store.jms.cache.connection",
((Boolean) model.isEnableCaching()).toString());
parameters.put("store.jms.ConsumerReceiveTimeOut",
((Long) model.getTimeout()).toString());
}
messageStore.setParameters(parameters);
OMElement messageStoreElement = MessageStoreSerializer.serializeMessageStore(null,
messageStore);
OMAttribute classAttr = messageStoreElement.getAttribute(new QName("class"));
if (classAttr != null) {
classAttr.setAttributeValue(className);
} else if (!StringUtils.isBlank(className)) {
messageStoreElement.addAttribute("class", className, null);
} else {
/*
* Class attribute is optional for In-Memory Store. If class attribute is
* not defined it will be considered as an In-Memory Store.
*/
//messageStoreElement.addAttribute("class", className, null);
}
return messageStoreElement;
}
}
| false | true | public static OMElement createMessageStore(MessageStore model) throws Exception {
Map<String, Object> parameters = new HashMap<String, Object>();
// Fixing TOOLS-2026.
//String className = "org.apache.synapse.message.store.InMemoryMessageStore";
//String className = "org.apache.synapse.message.store.impl.memory.InMemoryStore";
String className = null;
org.apache.synapse.message.store.MessageStore messageStore = new InMemoryStore();
messageStore.setName(model.getStoreName());
if (model.getStoreType() == MessageStoreType.CUSTOM) {
className = model.getProviderClass();
EList<MessageStoreParameter> parameters2 = model.getParameters();
for (MessageStoreParameter param : parameters2) {
if (!StringUtils.isBlank(param.getParameterName())
&& !StringUtils.isBlank(param.getParameterValue())) {
parameters.put(param.getParameterName(), param.getParameterValue());
}
}
} else if (model.getStoreType() == MessageStoreType.JMS) {
// Fixing TOOLS-2026.
//className = "org.wso2.carbon.message.store.persistence.jms.JMSMessageStore";
className = "org.apache.synapse.message.store.impl.jms.JmsStore";
if (!StringUtils.isBlank(model.getInitialContextFactory())) {
parameters.put("java.naming.factory.initial",
model.getInitialContextFactory());
}
if (!StringUtils.isBlank(model.getProviderURL())) {
parameters.put("java.naming.provider.url", model.getProviderURL());
}
if (!StringUtils.isBlank(model.getJndiQueueName())) {
parameters.put("store.jms.destination", model.getJndiQueueName());
}
if (!StringUtils.isBlank(model.getInitialContextFactory())) {
parameters.put("store.jms.connection.factory",
model.getInitialContextFactory());
}
if (!StringUtils.isBlank(model.getUserName())) {
parameters.put("store.jms.username", model.getUserName());
}
if (!StringUtils.isBlank(model.getPassword())) {
parameters.put("store.jms.password", model.getPassword());
}
parameters.put("store.jms.JMSSpecVersion", model.getJmsSpecVersion().getLiteral());
parameters.put("store.jms.cache.connection",
((Boolean) model.isEnableCaching()).toString());
parameters.put("store.jms.ConsumerReceiveTimeOut",
((Long) model.getTimeout()).toString());
}
messageStore.setParameters(parameters);
OMElement messageStoreElement = MessageStoreSerializer.serializeMessageStore(null,
messageStore);
OMAttribute classAttr = messageStoreElement.getAttribute(new QName("class"));
if (classAttr != null) {
classAttr.setAttributeValue(className);
} else if (!StringUtils.isBlank(className)) {
messageStoreElement.addAttribute("class", className, null);
} else {
/*
* Class attribute is optional for In-Memory Store. If class attribute is
* not defined it will be considered as an In-Memory Store.
*/
//messageStoreElement.addAttribute("class", className, null);
}
return messageStoreElement;
}
| public static OMElement createMessageStore(MessageStore model) throws Exception {
Map<String, Object> parameters = new HashMap<String, Object>();
// Fixing TOOLS-2026.
//String className = "org.apache.synapse.message.store.InMemoryMessageStore";
//String className = "org.apache.synapse.message.store.impl.memory.InMemoryStore";
String className = null;
org.apache.synapse.message.store.MessageStore messageStore = new InMemoryStore();
messageStore.setName(model.getStoreName());
if (model.getStoreType() == MessageStoreType.CUSTOM) {
className = model.getProviderClass();
EList<MessageStoreParameter> parameters2 = model.getParameters();
for (MessageStoreParameter param : parameters2) {
if (!StringUtils.isBlank(param.getParameterName())
&& !StringUtils.isBlank(param.getParameterValue())) {
parameters.put(param.getParameterName(), param.getParameterValue());
}
}
} else if (model.getStoreType() == MessageStoreType.JMS) {
// Fixing TOOLS-2026.
//className = "org.wso2.carbon.message.store.persistence.jms.JMSMessageStore";
className = "org.apache.synapse.message.store.impl.jms.JmsStore";
if (!StringUtils.isBlank(model.getInitialContextFactory())) {
parameters.put("java.naming.factory.initial",
model.getInitialContextFactory());
}
if (!StringUtils.isBlank(model.getProviderURL())) {
parameters.put("java.naming.provider.url", model.getProviderURL());
}
if (!StringUtils.isBlank(model.getJndiQueueName())) {
parameters.put("store.jms.destination", model.getJndiQueueName());
}
if (!StringUtils.isBlank(model.getConnectionFactory())) {
parameters.put("store.jms.connection.factory",
model.getConnectionFactory());
}
if (!StringUtils.isBlank(model.getUserName())) {
parameters.put("store.jms.username", model.getUserName());
}
if (!StringUtils.isBlank(model.getPassword())) {
parameters.put("store.jms.password", model.getPassword());
}
parameters.put("store.jms.JMSSpecVersion", model.getJmsSpecVersion().getLiteral());
parameters.put("store.jms.cache.connection",
((Boolean) model.isEnableCaching()).toString());
parameters.put("store.jms.ConsumerReceiveTimeOut",
((Long) model.getTimeout()).toString());
}
messageStore.setParameters(parameters);
OMElement messageStoreElement = MessageStoreSerializer.serializeMessageStore(null,
messageStore);
OMAttribute classAttr = messageStoreElement.getAttribute(new QName("class"));
if (classAttr != null) {
classAttr.setAttributeValue(className);
} else if (!StringUtils.isBlank(className)) {
messageStoreElement.addAttribute("class", className, null);
} else {
/*
* Class attribute is optional for In-Memory Store. If class attribute is
* not defined it will be considered as an In-Memory Store.
*/
//messageStoreElement.addAttribute("class", className, null);
}
return messageStoreElement;
}
|
diff --git a/opentripplanner-routing/src/main/java/org/opentripplanner/routing/impl/StreetVertexIndexServiceImpl.java b/opentripplanner-routing/src/main/java/org/opentripplanner/routing/impl/StreetVertexIndexServiceImpl.java
index d888753af..b5cb4ad36 100644
--- a/opentripplanner-routing/src/main/java/org/opentripplanner/routing/impl/StreetVertexIndexServiceImpl.java
+++ b/opentripplanner-routing/src/main/java/org/opentripplanner/routing/impl/StreetVertexIndexServiceImpl.java
@@ -1,548 +1,544 @@
/* 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 3 of
the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
package org.opentripplanner.routing.impl;
import static org.opentripplanner.common.IterableLibrary.filter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.opentripplanner.common.IterableLibrary;
import org.opentripplanner.common.geometry.DistanceLibrary;
import org.opentripplanner.common.geometry.SphericalDistanceLibrary;
import org.opentripplanner.common.geometry.GeometryUtils;
import org.opentripplanner.common.model.NamedPlace;
import org.opentripplanner.common.model.P2;
import org.opentripplanner.routing.core.RoutingRequest;
import org.opentripplanner.routing.edgetype.FreeEdge;
import org.opentripplanner.routing.edgetype.OutEdge;
import org.opentripplanner.routing.edgetype.StreetEdge;
import org.opentripplanner.routing.edgetype.StreetTraversalPermission;
import org.opentripplanner.routing.graph.Edge;
import org.opentripplanner.routing.graph.Graph;
import org.opentripplanner.routing.graph.Vertex;
import org.opentripplanner.routing.location.StreetLocation;
import org.opentripplanner.routing.services.StreetVertexIndexService;
import org.opentripplanner.routing.vertextype.IntersectionVertex;
import org.opentripplanner.routing.vertextype.StreetVertex;
import org.opentripplanner.routing.vertextype.TransitStop;
import org.opentripplanner.routing.vertextype.TurnVertex;
import org.opentripplanner.util.JoinedList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Envelope;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.Point;
import com.vividsolutions.jts.index.SpatialIndex;
import com.vividsolutions.jts.index.quadtree.Quadtree;
import com.vividsolutions.jts.index.strtree.STRtree;
import com.vividsolutions.jts.operation.distance.DistanceOp;
import com.vividsolutions.jts.operation.distance.GeometryLocation;
/**
* Indexes all edges and transit vertices of the graph spatially. Has a variety of query methods
* used during network linking and trip planning.
*
* Creates a StreetLocation representing a location on a street that's not at an intersection, based
* on input latitude and longitude. Instantiating this class is expensive, because it creates a
* spatial index of all of the intersections in the graph.
*/
//@Component
public class StreetVertexIndexServiceImpl implements StreetVertexIndexService {
private Graph graph;
/**
* Contains only instances of {@link StreetEdge}
*/
private SpatialIndex edgeTree;
private STRtree transitStopTree;
private STRtree intersectionTree;
private DistanceLibrary distanceLibrary = SphericalDistanceLibrary.getInstance();
// private static final double SEARCH_RADIUS_M = 100; // meters
// private static final double SEARCH_RADIUS_DEG = DistanceLibrary.metersToDegrees(SEARCH_RADIUS_M);
/* all distance constants here are plate-carée Euclidean, 0.001 ~= 100m at equator */
// edges will only be found if they are closer than this distance
public static final double MAX_DISTANCE_FROM_STREET = 0.01000;
// maximum difference in distance for two geometries to be considered coincident
public static final double DISTANCE_ERROR = 0.000001;
//if a point is within MAX_CORNER_DISTANCE, it is treated as at the corner
private static final double MAX_CORNER_DISTANCE = 0.0001;
private static final double DIRECTION_ERROR = 0.05;
private static final Logger _log = LoggerFactory.getLogger(StreetVertexIndexServiceImpl.class);
public StreetVertexIndexServiceImpl(Graph graph) {
this.graph = graph;
setup();
}
public StreetVertexIndexServiceImpl(Graph graph, DistanceLibrary distanceLibrary) {
this.graph = graph;
this.distanceLibrary = distanceLibrary;
setup();
}
public void setup_modifiable() {
edgeTree = new Quadtree();
postSetup();
}
public void setup() {
edgeTree = new STRtree();
postSetup();
((STRtree) edgeTree).build();
}
private void postSetup() {
transitStopTree = new STRtree();
intersectionTree = new STRtree();
for (Vertex gv : graph.getVertices()) {
Vertex v = gv;
// We only care about StreetEdges
for (StreetEdge e : filter(gv.getOutgoing(), StreetEdge.class)) {
if (e.getGeometry() == null) {
continue;
}
Envelope env = e.getGeometry().getEnvelopeInternal();
edgeTree.insert(env, e);
}
if (v instanceof TransitStop) {
// only index transit stops that (a) are entrances, or (b) have no associated
// entrances
TransitStop ts = (TransitStop) v;
if (!ts.isEntrance() && ts.hasEntrances()) {
continue;
}
Envelope env = new Envelope(v.getCoordinate());
transitStopTree.insert(env, v);
}
if (v instanceof TurnVertex || v instanceof IntersectionVertex) {
Envelope env = new Envelope(v.getCoordinate());
intersectionTree.insert(env, v);
}
}
transitStopTree.build();
}
/**
* Get all transit stops within a given distance of a coordinate
*
* @param distance in meters
*/
@SuppressWarnings("unchecked")
public List<Vertex> getLocalTransitStops(Coordinate c, double distance) {
Envelope env = new Envelope(c);
env.expandBy(SphericalDistanceLibrary.metersToDegrees(distance));
List<Vertex> nearby = transitStopTree.query(env);
List<Vertex> results = new ArrayList<Vertex>();
for (Vertex v : nearby) {
if (distanceLibrary.distance(v.getCoordinate(), c) <= distance) {
results.add(v);
}
}
return results;
}
/**
* Gets the closest vertex to a coordinate. If necessary, this vertex will be created by
* splitting nearby edges (non-permanently).
*/
public Vertex getClosestVertex(final Coordinate coordinate, String name, RoutingRequest options) {
return getClosestVertex(coordinate, name, options, null);
}
public Vertex getClosestVertex(final Coordinate coordinate, String name, RoutingRequest options, List<Edge> extraEdges) {
_log.debug("Looking for/making a vertex near {}", coordinate);
// first, check for intersections very close by
List<StreetVertex> vertices = getIntersectionAt(coordinate, MAX_CORNER_DISTANCE);
if (vertices != null && !vertices.isEmpty()) {
// coordinate is at a street corner or endpoint
if (name == null) {
// generate names for corners when no name was given
// TODO: internationalize
Set<String> uniqueNameSet = new HashSet<String>();
// filter to avoid using OSM node ids for dead ends
for (StreetVertex v : IterableLibrary.filter(vertices, StreetVertex.class))
uniqueNameSet.add(v.getName());
List<String> uniqueNames = new ArrayList<String>(uniqueNameSet);
if (uniqueNames.size() > 1)
name = String.format("corner of %s and %s", uniqueNames.get(0), uniqueNames.get(1));
else if (uniqueNames.size() == 1)
name = uniqueNames.get(0);
else
name = "unnamed street";
}
StreetLocation closest = new StreetLocation(graph, "corner " + Math.random(), coordinate, name);
for (Vertex v : vertices) {
FreeEdge e = new FreeEdge(closest, v);
closest.getExtra().add(e);
e = new FreeEdge(v, closest);
closest.getExtra().add(e);
if (v instanceof TurnVertex && ((TurnVertex) v).isWheelchairAccessible()) {
closest.setWheelchairAccessible(true);
}
}
return closest;
}
// if no intersection vertices were found, then find the closest transit stop
// (we can return stops here because this method is not used when street-transit linking)
double closest_stop_distance = Double.POSITIVE_INFINITY;
Vertex closest_stop = null;
// elsewhere options=null means no restrictions, find anything.
// here we skip examining stops, as they are really only relevant when transit is being used
if (options != null && options.getModes().isTransit()) {
for (Vertex v : getLocalTransitStops(coordinate, 1000)) {
double d = distanceLibrary.distance(v.getCoordinate(), coordinate);
if (d < closest_stop_distance) {
closest_stop_distance = d;
closest_stop = v;
}
}
}
_log.debug(" best stop: {} distance: {}", closest_stop, closest_stop_distance);
// then find closest walkable street
StreetLocation closest_street = null;
CandidateEdgeBundle bundle = getClosestEdges(coordinate, options, extraEdges, null);
CandidateEdge candidate = bundle.best;
double closest_street_distance = Double.POSITIVE_INFINITY;
if (candidate != null) {
StreetEdge bestStreet = candidate.edge;
Coordinate nearestPoint = candidate.nearestPointOnEdge;
closest_street_distance = distanceLibrary.distance(coordinate, nearestPoint);
_log.debug("best street: {} dist: {}", bestStreet.toString(), closest_street_distance);
if (name == null) {
name = bestStreet.getName();
}
closest_street = StreetLocation.createStreetLocation(graph, bestStreet.getName() + "_"
+ coordinate.toString(), name, bundle.toEdgeList(), nearestPoint);
}
- // decide whether to return stop, street, or street + stop
+ // decide whether to return street, or street + stop
if (closest_street == null) {
// no street found, return closest stop or null
_log.debug("returning only transit stop (no street found)");
return closest_stop; // which will be null if none was found
} else {
// street found
if (closest_stop != null) {
// both street and stop found
double relativeStopDistance = closest_stop_distance / closest_street_distance;
- if (relativeStopDistance < 0.1) {
- _log.debug("returning only transit stop (stop much closer than street)");
- return closest_stop;
- }
if (relativeStopDistance < 1.5) {
_log.debug("linking transit stop to street (distances are comparable)");
closest_street.addExtraEdgeTo(closest_stop);
}
}
_log.debug("returning split street");
return closest_street;
}
}
@SuppressWarnings("unchecked")
public Collection<Vertex> getVerticesForEnvelope(Envelope envelope) {
return intersectionTree.query(envelope);
}
public static class CandidateEdge {
private static final double PLATFORM_PREFERENCE = 2.0;
private static final double SIDEWALK_PREFERENCE = 1.5;
public final DistanceOp op;
public final StreetEdge edge;
public final Vertex endwiseVertex;
private double score;
public final Coordinate nearestPointOnEdge;
public final double directionToEdge;
public final double directionOfEdge;
public final double directionDifference;
public final double distance;
public CandidateEdge(StreetEdge e, Point p, double preference) {
edge = e;
Geometry edgeGeom = edge.getGeometry();
op = new DistanceOp(p, edgeGeom);
distance = op.distance();
// location on second geometry (edge)
GeometryLocation edgeLocation = op.nearestLocations()[1];
nearestPointOnEdge = edgeLocation.getCoordinate();
Coordinate[] edgeCoords = edgeGeom.getCoordinates();
if (nearestPointOnEdge.equals(edgeCoords[0]))
endwiseVertex = edge.getFromVertex();
else if (nearestPointOnEdge.equals(edgeCoords[edgeCoords.length - 1]))
endwiseVertex = edge.getToVertex();
else
endwiseVertex = null;
score = distance;
if (endwise()) {
score *= 1.5;
}
score /= preference;
if (e.getName().contains("platform")) {
//this is kind of a hack, but there's not really a better way to do it
score /= PLATFORM_PREFERENCE;
}
if (e.getName().contains("sidewalk") || !e.getPermission().allows(StreetTraversalPermission.CAR)) {
//this is kind of a hack, but there's not really a better way to do it
score /= SIDEWALK_PREFERENCE;
}
//break ties by choosing shorter edges; this should cause split streets to be preferred
score += edge.getLength() / 1000000;
double xd = nearestPointOnEdge.x - p.getX();
double yd = nearestPointOnEdge.y - p.getY();
directionToEdge = Math.atan2(yd, xd);
int edgeSegmentIndex = edgeLocation.getSegmentIndex();
Coordinate c0 = edgeCoords[edgeSegmentIndex];
Coordinate c1 = edgeCoords[edgeSegmentIndex + 1];
xd = c1.x - c1.y;
yd = c1.y - c0.y;
directionOfEdge = Math.atan2(yd, xd);
double absDiff = Math.abs(directionToEdge - directionOfEdge);
directionDifference = Math.min(2*Math.PI - absDiff, absDiff);
if (Double.isNaN(directionToEdge) ||
Double.isNaN(directionOfEdge) ||
Double.isNaN(directionDifference)) {
_log.warn("direction to/of edge is NaN (0 length?): {}", edge);
}
}
public boolean endwise() { return endwiseVertex != null; }
public boolean parallel() { return directionDifference < Math.PI / 2; }
public boolean perpendicular() { return !parallel(); }
public double getScore() {
return score;
}
}
public static class CandidateEdgeBundle extends ArrayList<CandidateEdge> {
private static final long serialVersionUID = 20120222L;
public Vertex endwiseVertex = null;
public CandidateEdge best = null;
public boolean add(CandidateEdge ce) {
if (ce.endwiseVertex != null)
this.endwiseVertex = ce.endwiseVertex;
if (best == null || ce.score < best.score)
best = ce;
return super.add(ce);
}
public List<StreetEdge> toEdgeList() {
List<StreetEdge> ret = new ArrayList<StreetEdge>();
for (CandidateEdge ce : this)
ret.add(ce.edge);
return ret;
}
public Collection<CandidateEdgeBundle> binByDistanceAndAngle() {
Map<P2<Double>, CandidateEdgeBundle> bins =
new HashMap<P2<Double>, CandidateEdgeBundle>(); // (r, theta)
CANDIDATE : for (CandidateEdge ce : this) {
for (Entry<P2<Double>, CandidateEdgeBundle> bin : bins.entrySet()) {
double distance = bin.getKey().getFirst();
double direction = bin.getKey().getSecond();
if (Math.abs(direction - ce.directionToEdge) < DIRECTION_ERROR &&
Math.abs(distance - ce.distance) < DISTANCE_ERROR ) {
bin.getValue().add(ce);
continue CANDIDATE;
}
}
P2<Double> rTheta = new P2<Double>(ce.distance, ce.directionToEdge);
CandidateEdgeBundle bundle = new CandidateEdgeBundle();
bundle.add(ce);
bins.put(rTheta, bundle);
}
return bins.values();
}
public boolean endwise() { return endwiseVertex != null; }
public double getScore() {
return best.score;
}
}
@SuppressWarnings("unchecked")
public CandidateEdgeBundle getClosestEdges(Coordinate coordinate, RoutingRequest options, List<Edge> extraEdges, Collection<Edge> routeEdges) {
ArrayList<StreetEdge> extraStreets = new ArrayList<StreetEdge> ();
if (extraEdges != null)
for (StreetEdge se : IterableLibrary.filter(extraEdges, StreetEdge.class))
extraStreets.add(se);
for (StreetEdge se : IterableLibrary.filter(graph.getTemporaryEdges(), StreetEdge.class))
extraStreets.add(se);
Envelope envelope = new Envelope(coordinate);
Point p = GeometryUtils.getGeometryFactory().createPoint(coordinate);
RoutingRequest walkingOptions = null;
if (options != null) {
walkingOptions = options.getWalkingOptions();
}
double envelopeGrowthAmount = 0.001; // ~= 100 meters
double radius = 0;
CandidateEdgeBundle candidateEdges = new CandidateEdgeBundle();
while (candidateEdges.size() == 0) {
// expand envelope -- assumes many close searches and occasional far ones
envelope.expandBy(envelopeGrowthAmount);
radius += envelopeGrowthAmount;
if (radius > MAX_DISTANCE_FROM_STREET)
return candidateEdges; // empty list
// envelopeGrowthAmount *= 2;
List<StreetEdge> nearbyEdges = edgeTree.query(envelope);
if (nearbyEdges != null) {
nearbyEdges = new JoinedList<StreetEdge>(nearbyEdges, extraStreets);
}
for (StreetEdge e : nearbyEdges) {
if (e == null || e instanceof OutEdge || e.getFromVertex() == null)
continue;
if (options != null &&
(!(e.canTraverse(options) || e.canTraverse(walkingOptions))))
continue;
double preferrence = 1;
if (routeEdges != null && routeEdges.contains(e)) {
preferrence = 3.0;
}
CandidateEdge ce = new CandidateEdge(e, p, preferrence);
// Even if an edge is outside the query envelope, bounding boxes can
// still intersect. In this case, distance to the edge is greater
// than the query envelope size.
if (ce.distance < radius)
candidateEdges.add(ce);
}
}
Collection<CandidateEdgeBundle> bundles = candidateEdges.binByDistanceAndAngle();
// initially set best bundle to the closest bundle
CandidateEdgeBundle best = null;
for (CandidateEdgeBundle bundle : bundles) {
if (best == null || bundle.best.score < best.best.score)
best = bundle;
}
return best;
}
public List<StreetVertex> getIntersectionAt(Coordinate coordinate) {
return getIntersectionAt(coordinate, MAX_CORNER_DISTANCE);
}
@SuppressWarnings("unchecked")
public List<StreetVertex> getIntersectionAt(Coordinate coordinate, double distanceError) {
Envelope envelope = new Envelope(coordinate);
envelope.expandBy(distanceError * 2);
List<StreetVertex> nearby = intersectionTree.query(envelope);
List<StreetVertex> atIntersection = new ArrayList<StreetVertex>(nearby.size());
for (StreetVertex v : nearby) {
if (coordinate.distance(v.getCoordinate()) < distanceError) {
atIntersection.add(v);
}
}
if (atIntersection.isEmpty()) {
return null;
}
return atIntersection;
}
@Override
/** radius is meters */
public List<TransitStop> getNearbyTransitStops(Coordinate coordinate, double radius) {
Envelope envelope = new Envelope(coordinate);
envelope.expandBy(SphericalDistanceLibrary.metersToDegrees(radius));
List<?> stops = transitStopTree.query(envelope);
ArrayList<TransitStop> out = new ArrayList<TransitStop>();
for (Object o : stops) {
TransitStop stop = (TransitStop) o;
if (distanceLibrary.distance(stop.getCoordinate(), coordinate) < radius) {
out.add(stop);
}
}
return out;
}
/* EX-GENERICPATHSERVICE */
private static final String _doublePattern = "-{0,1}\\d+(\\.\\d+){0,1}";
private static final Pattern _latLonPattern = Pattern.compile("^\\s*(" + _doublePattern
+ ")(\\s*,\\s*|\\s+)(" + _doublePattern + ")\\s*$");
@Override
public Vertex getVertexForPlace(NamedPlace place, RoutingRequest options) {
return getVertexForPlace(place, options, null);
}
@Override
public Vertex getVertexForPlace(NamedPlace place, RoutingRequest options, Vertex other) {
if (place == null || place.place == null)
return null;
Matcher matcher = _latLonPattern.matcher(place.place);
if (matcher.matches()) {
double lat = Double.parseDouble(matcher.group(1));
double lon = Double.parseDouble(matcher.group(4));
Coordinate location = new Coordinate(lon, lat);
if (other instanceof StreetLocation) {
return getClosestVertex(location, place.name, options, ((StreetLocation) other).getExtra());
} else {
return getClosestVertex(location, place.name, options);
}
}
// did not match lat/lon, interpret place as a vertex label.
// this should probably only be used in tests.
return graph.getVertex(place.place);
}
@Override
public boolean isAccessible(NamedPlace place, RoutingRequest options) {
/* fixme: take into account slope for wheelchair accessibility */
Vertex vertex = getVertexForPlace(place, options);
if (vertex instanceof TransitStop) {
TransitStop ts = (TransitStop) vertex;
return ts.hasWheelchairEntrance();
} else if (vertex instanceof StreetLocation) {
StreetLocation sl = (StreetLocation) vertex;
return sl.isWheelchairAccessible();
}
return true;
}
public DistanceLibrary getDistanceLibrary() {
return distanceLibrary;
}
public void setDistanceLibrary(DistanceLibrary distanceLibrary) {
this.distanceLibrary = distanceLibrary;
}
}
| false | true | public Vertex getClosestVertex(final Coordinate coordinate, String name, RoutingRequest options, List<Edge> extraEdges) {
_log.debug("Looking for/making a vertex near {}", coordinate);
// first, check for intersections very close by
List<StreetVertex> vertices = getIntersectionAt(coordinate, MAX_CORNER_DISTANCE);
if (vertices != null && !vertices.isEmpty()) {
// coordinate is at a street corner or endpoint
if (name == null) {
// generate names for corners when no name was given
// TODO: internationalize
Set<String> uniqueNameSet = new HashSet<String>();
// filter to avoid using OSM node ids for dead ends
for (StreetVertex v : IterableLibrary.filter(vertices, StreetVertex.class))
uniqueNameSet.add(v.getName());
List<String> uniqueNames = new ArrayList<String>(uniqueNameSet);
if (uniqueNames.size() > 1)
name = String.format("corner of %s and %s", uniqueNames.get(0), uniqueNames.get(1));
else if (uniqueNames.size() == 1)
name = uniqueNames.get(0);
else
name = "unnamed street";
}
StreetLocation closest = new StreetLocation(graph, "corner " + Math.random(), coordinate, name);
for (Vertex v : vertices) {
FreeEdge e = new FreeEdge(closest, v);
closest.getExtra().add(e);
e = new FreeEdge(v, closest);
closest.getExtra().add(e);
if (v instanceof TurnVertex && ((TurnVertex) v).isWheelchairAccessible()) {
closest.setWheelchairAccessible(true);
}
}
return closest;
}
// if no intersection vertices were found, then find the closest transit stop
// (we can return stops here because this method is not used when street-transit linking)
double closest_stop_distance = Double.POSITIVE_INFINITY;
Vertex closest_stop = null;
// elsewhere options=null means no restrictions, find anything.
// here we skip examining stops, as they are really only relevant when transit is being used
if (options != null && options.getModes().isTransit()) {
for (Vertex v : getLocalTransitStops(coordinate, 1000)) {
double d = distanceLibrary.distance(v.getCoordinate(), coordinate);
if (d < closest_stop_distance) {
closest_stop_distance = d;
closest_stop = v;
}
}
}
_log.debug(" best stop: {} distance: {}", closest_stop, closest_stop_distance);
// then find closest walkable street
StreetLocation closest_street = null;
CandidateEdgeBundle bundle = getClosestEdges(coordinate, options, extraEdges, null);
CandidateEdge candidate = bundle.best;
double closest_street_distance = Double.POSITIVE_INFINITY;
if (candidate != null) {
StreetEdge bestStreet = candidate.edge;
Coordinate nearestPoint = candidate.nearestPointOnEdge;
closest_street_distance = distanceLibrary.distance(coordinate, nearestPoint);
_log.debug("best street: {} dist: {}", bestStreet.toString(), closest_street_distance);
if (name == null) {
name = bestStreet.getName();
}
closest_street = StreetLocation.createStreetLocation(graph, bestStreet.getName() + "_"
+ coordinate.toString(), name, bundle.toEdgeList(), nearestPoint);
}
// decide whether to return stop, street, or street + stop
if (closest_street == null) {
// no street found, return closest stop or null
_log.debug("returning only transit stop (no street found)");
return closest_stop; // which will be null if none was found
} else {
// street found
if (closest_stop != null) {
// both street and stop found
double relativeStopDistance = closest_stop_distance / closest_street_distance;
if (relativeStopDistance < 0.1) {
_log.debug("returning only transit stop (stop much closer than street)");
return closest_stop;
}
if (relativeStopDistance < 1.5) {
_log.debug("linking transit stop to street (distances are comparable)");
closest_street.addExtraEdgeTo(closest_stop);
}
}
_log.debug("returning split street");
return closest_street;
}
}
| public Vertex getClosestVertex(final Coordinate coordinate, String name, RoutingRequest options, List<Edge> extraEdges) {
_log.debug("Looking for/making a vertex near {}", coordinate);
// first, check for intersections very close by
List<StreetVertex> vertices = getIntersectionAt(coordinate, MAX_CORNER_DISTANCE);
if (vertices != null && !vertices.isEmpty()) {
// coordinate is at a street corner or endpoint
if (name == null) {
// generate names for corners when no name was given
// TODO: internationalize
Set<String> uniqueNameSet = new HashSet<String>();
// filter to avoid using OSM node ids for dead ends
for (StreetVertex v : IterableLibrary.filter(vertices, StreetVertex.class))
uniqueNameSet.add(v.getName());
List<String> uniqueNames = new ArrayList<String>(uniqueNameSet);
if (uniqueNames.size() > 1)
name = String.format("corner of %s and %s", uniqueNames.get(0), uniqueNames.get(1));
else if (uniqueNames.size() == 1)
name = uniqueNames.get(0);
else
name = "unnamed street";
}
StreetLocation closest = new StreetLocation(graph, "corner " + Math.random(), coordinate, name);
for (Vertex v : vertices) {
FreeEdge e = new FreeEdge(closest, v);
closest.getExtra().add(e);
e = new FreeEdge(v, closest);
closest.getExtra().add(e);
if (v instanceof TurnVertex && ((TurnVertex) v).isWheelchairAccessible()) {
closest.setWheelchairAccessible(true);
}
}
return closest;
}
// if no intersection vertices were found, then find the closest transit stop
// (we can return stops here because this method is not used when street-transit linking)
double closest_stop_distance = Double.POSITIVE_INFINITY;
Vertex closest_stop = null;
// elsewhere options=null means no restrictions, find anything.
// here we skip examining stops, as they are really only relevant when transit is being used
if (options != null && options.getModes().isTransit()) {
for (Vertex v : getLocalTransitStops(coordinate, 1000)) {
double d = distanceLibrary.distance(v.getCoordinate(), coordinate);
if (d < closest_stop_distance) {
closest_stop_distance = d;
closest_stop = v;
}
}
}
_log.debug(" best stop: {} distance: {}", closest_stop, closest_stop_distance);
// then find closest walkable street
StreetLocation closest_street = null;
CandidateEdgeBundle bundle = getClosestEdges(coordinate, options, extraEdges, null);
CandidateEdge candidate = bundle.best;
double closest_street_distance = Double.POSITIVE_INFINITY;
if (candidate != null) {
StreetEdge bestStreet = candidate.edge;
Coordinate nearestPoint = candidate.nearestPointOnEdge;
closest_street_distance = distanceLibrary.distance(coordinate, nearestPoint);
_log.debug("best street: {} dist: {}", bestStreet.toString(), closest_street_distance);
if (name == null) {
name = bestStreet.getName();
}
closest_street = StreetLocation.createStreetLocation(graph, bestStreet.getName() + "_"
+ coordinate.toString(), name, bundle.toEdgeList(), nearestPoint);
}
// decide whether to return street, or street + stop
if (closest_street == null) {
// no street found, return closest stop or null
_log.debug("returning only transit stop (no street found)");
return closest_stop; // which will be null if none was found
} else {
// street found
if (closest_stop != null) {
// both street and stop found
double relativeStopDistance = closest_stop_distance / closest_street_distance;
if (relativeStopDistance < 1.5) {
_log.debug("linking transit stop to street (distances are comparable)");
closest_street.addExtraEdgeTo(closest_stop);
}
}
_log.debug("returning split street");
return closest_street;
}
}
|
diff --git a/src/php/runtime/memory/support/MemoryUtils.java b/src/php/runtime/memory/support/MemoryUtils.java
index 951bc2f7..fb247f7a 100644
--- a/src/php/runtime/memory/support/MemoryUtils.java
+++ b/src/php/runtime/memory/support/MemoryUtils.java
@@ -1,341 +1,341 @@
package php.runtime.memory.support;
import php.runtime.Memory;
import php.runtime.common.HintType;
import php.runtime.env.Environment;
import php.runtime.ext.java.JavaObject;
import php.runtime.memory.*;
import java.util.*;
public class MemoryUtils {
protected final static Map<Class<?>, Unconverter> UNCONVERTERS = new HashMap<Class<?>, Unconverter>(){{
put(Double.class, new Unconverter<Double>() {
@Override
public Memory run(Double value) {
return new DoubleMemory(value);
}
});
put(Double.TYPE, get(Double.class));
put(Float.class, new Unconverter<Float>() {
@Override
public Memory run(Float value) {
return new DoubleMemory(value);
}
});
put(Float.TYPE, get(Float.class));
put(Long.class, new Unconverter<Long>() {
@Override
public Memory run(Long value) {
return LongMemory.valueOf(value);
}
});
put(Long.TYPE, get(Long.class));
put(Integer.class, new Unconverter<Integer>() {
@Override
public Memory run(Integer value) {
return LongMemory.valueOf(value);
}
});
put(Integer.TYPE, get(Integer.class));
put(Short.class, new Unconverter<Short>() {
@Override
public Memory run(Short value) {
return LongMemory.valueOf(value);
}
});
put(Short.TYPE, get(Short.class));
put(Short.class, new Unconverter<Byte>() {
@Override
public Memory run(Byte value) {
return LongMemory.valueOf(value);
}
});
put(Byte.TYPE, get(Byte.class));
put(Character.class, new Unconverter<Character>() {
@Override
public Memory run(Character value) {
return new StringMemory(value);
}
});
put(Character.TYPE, get(Character.class));
put(Boolean.class, new Unconverter<Boolean>() {
@Override
public Memory run(Boolean value) {
return value ? Memory.TRUE : Memory.FALSE;
}
});
put(Boolean.TYPE, get(Boolean.class));
put(String.class, new Unconverter<String>() {
@Override
public Memory run(String value) {
return new StringMemory(value);
}
});
put(Memory.class, new Unconverter<Memory>() {
@Override
public Memory run(Memory value) {
return value;
}
});
put(Memory[].class, new Unconverter<Memory[]>() {
@Override
public Memory run(Memory[] value) {
return new ArrayMemory(value);
}
});
}};
protected final static Map<Class<?>, Converter> CONVERTERS = new HashMap<Class<?>, Converter>(){{
// double
put(Double.class, new Converter<Double>() {
@Override
public Double run(Memory value) {
return value.toDouble();
}
});
put(Double.TYPE, get(Double.class));
// float
put(Float.class, new Converter<Float>() {
@Override
public Float run(Memory value) {
return (float)value.toDouble();
}
});
put(Float.TYPE, get(Float.class));
// long
put(Long.class, new Converter<Long>() {
@Override
public Long run(Memory value) {
return value.toLong();
}
});
put(Long.TYPE, get(Long.class));
// int
put(Integer.class, new Converter<Integer>() {
@Override
public Integer run(Memory value) {
return (int)value.toLong();
}
});
put(Integer.TYPE, get(Integer.class));
// short
put(Short.class, new Converter<Short>() {
@Override
public Short run(Memory value) {
return (short)value.toLong();
}
});
put(Short.TYPE, get(Short.class));
// byte
put(Byte.class, new Converter<Byte>() {
@Override
public Byte run(Memory value) {
return (byte)value.toLong();
}
});
put(Byte.TYPE, get(Byte.class));
// char
put(Character.class, new Converter<Character>() {
@Override
public Character run(Memory value) {
return value.toChar();
}
});
put(Character.TYPE, get(Character.class));
// bool
put(Boolean.class, new Converter<Boolean>() {
@Override
public Boolean run(Memory value) {
return value.toBoolean();
}
});
put(Boolean.TYPE, get(Boolean.class));
// string
put(String.class, new Converter<String>() {
@Override
public String run(Memory value) {
return value.toString();
}
});
put(Memory.class, new Converter<Memory>() {
@Override
public Memory run(Memory value) {
return value;
}
});
put(Memory[].class, new Converter<Memory[]>() {
@Override
public Memory[] run(Memory value) {
if (value.isArray()){
List<Memory> result = new ArrayList<Memory>();
for(Memory one : (ArrayMemory)value){
result.add(one.toImmutable());
}
return result.toArray(new Memory[]{});
} else {
return null;
}
}
});
}};
public static Converter<?> getConverter(Class<?> type){
return CONVERTERS.get(type);
}
public static Converter<?>[] getConverters(Class<?>[] types){
Converter<?>[] result = new Converter[types.length];
for(int i = 0; i < types.length; i++){
result[i] = getConverter(types[i]);
}
return result;
}
public static Unconverter getUnconverter(Class<?> type){
return UNCONVERTERS.get(type);
}
public static Object fromMemory(Memory value, Class<?> type){
if (value.instanceOf("php\\lang\\JavaObject"))
return ((JavaObject)value.toValue(ObjectMemory.class).value).getObject();
Converter converter = getConverter(type);
if (converter != null)
return converter.run(value);
else
return value;
}
public static Object toValue(Memory value, Class<?> type){
if (type == Double.TYPE || type == Double.class)
return value.toDouble();
if (type == Float.TYPE || type == Float.class)
return (float)value.toDouble();
if (type == Long.TYPE || type == Long.class)
return value.toLong();
if (type == Integer.TYPE || type == Integer.class)
return (int)value.toLong();
if (type == Short.TYPE || type == Short.class)
return (short)value.toLong();
if (type == Byte.TYPE || type == Byte.class)
return (byte)value.toLong();
if (type == Character.TYPE || type == Character.class)
return value.toChar();
if (type == String.class)
return value.toString();
if (type == Boolean.TYPE || type == Boolean.class)
return value.toBoolean();
if (type == Memory.class)
return value;
if (type == Memory[].class){
if (value.isArray()){
List<Memory> result = new ArrayList<Memory>();
for(Memory one : (ArrayMemory)value){
result.add(one.toImmutable());
}
return result.toArray(new Memory[]{});
} else {
return null;
}
}
throw new IllegalArgumentException("Unexpected class type: " + type.getName());
}
public static Memory valueOf(Object value){
return valueOf(null, value);
}
public static Memory valueOf(Environment env, Object value){
if (value == null)
return Memory.NULL;
Unconverter unconverter = getUnconverter(value.getClass());
if (unconverter != null) {
return unconverter.run(value);
} else {
if (value instanceof Memory)
return (Memory)value;
if (env == null)
if (value instanceof Collection){
ArrayMemory result = new ArrayMemory();
for (Object el : (Collection)value)
- result.add(valueOf(value));
+ result.add(valueOf(el));
return result;
} else if (value instanceof Map){
ArrayMemory result = new ArrayMemory();
for (Map.Entry el : ((Map<?, ?>)value).entrySet())
result.refOfIndex(valueOf(el.getKey())).assign(valueOf(el.getValue()));
return result;
} else if (value.getClass().isArray()){
ArrayMemory result = new ArrayMemory();
for (Object el : (Object[])value)
- result.add(valueOf(value));
+ result.add(valueOf(el));
return result;
}
if (env != null)
return new ObjectMemory(JavaObject.of(env, value));
else
return null;
//}
}
}
public static Memory valueOf(String value, HintType type){
switch (type){
case STRING: return new StringMemory(value);
case ANY: return value.equals("NULL") ? Memory.NULL : new StringMemory(value);
case INT: {
try {
return new DoubleMemory(Double.parseDouble(value));
} catch (NumberFormatException e){
return LongMemory.valueOf(Long.parseLong(value));
}
}
case ARRAY:
return new ArrayMemory();
case BOOLEAN:
return new StringMemory(value).toBoolean() ? Memory.TRUE : Memory.FALSE;
case CALLABLE:
return new StringMemory(value);
default:
throw new IllegalArgumentException("Unsupported type - " + type);
}
}
public static interface Converter<T> {
T run(Memory value);
}
public static interface Unconverter<T> {
Memory run(T value);
}
}
| false | true | public static Memory valueOf(Environment env, Object value){
if (value == null)
return Memory.NULL;
Unconverter unconverter = getUnconverter(value.getClass());
if (unconverter != null) {
return unconverter.run(value);
} else {
if (value instanceof Memory)
return (Memory)value;
if (env == null)
if (value instanceof Collection){
ArrayMemory result = new ArrayMemory();
for (Object el : (Collection)value)
result.add(valueOf(value));
return result;
} else if (value instanceof Map){
ArrayMemory result = new ArrayMemory();
for (Map.Entry el : ((Map<?, ?>)value).entrySet())
result.refOfIndex(valueOf(el.getKey())).assign(valueOf(el.getValue()));
return result;
} else if (value.getClass().isArray()){
ArrayMemory result = new ArrayMemory();
for (Object el : (Object[])value)
result.add(valueOf(value));
return result;
}
if (env != null)
return new ObjectMemory(JavaObject.of(env, value));
else
return null;
//}
}
}
| public static Memory valueOf(Environment env, Object value){
if (value == null)
return Memory.NULL;
Unconverter unconverter = getUnconverter(value.getClass());
if (unconverter != null) {
return unconverter.run(value);
} else {
if (value instanceof Memory)
return (Memory)value;
if (env == null)
if (value instanceof Collection){
ArrayMemory result = new ArrayMemory();
for (Object el : (Collection)value)
result.add(valueOf(el));
return result;
} else if (value instanceof Map){
ArrayMemory result = new ArrayMemory();
for (Map.Entry el : ((Map<?, ?>)value).entrySet())
result.refOfIndex(valueOf(el.getKey())).assign(valueOf(el.getValue()));
return result;
} else if (value.getClass().isArray()){
ArrayMemory result = new ArrayMemory();
for (Object el : (Object[])value)
result.add(valueOf(el));
return result;
}
if (env != null)
return new ObjectMemory(JavaObject.of(env, value));
else
return null;
//}
}
}
|
diff --git a/src/dit/DEIDGUI.java b/src/dit/DEIDGUI.java
index 2d580fb..424c5fe 100644
--- a/src/dit/DEIDGUI.java
+++ b/src/dit/DEIDGUI.java
@@ -1,653 +1,654 @@
package dit;
import dit.panels.UserPanel;
import dit.panels.WizardPanel;
import java.awt.Toolkit;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.*;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JPanel;
import java.util.zip.*;
import java.util.Iterator;
/**
*
* @author christianprescott
*/
public class DEIDGUI extends javax.swing.JFrame {
public static enum LOG_LEVEL {INFO, ERROR, WARNING};
private static FileWriter logWriter;
private static ErrorFrame errWindow;
private static HelpManualFrame help;
private static misHelpFrame mhf;
public static String title = "User Information";
/**
* Creates new form DEIDGUI
*/
public DEIDGUI() {
initComponents();
// this.setTitle("Deidentification Tool- " + title);
// Set DeID's platform-dependent output location
jButtonMisHelp.setVisible(false);
if(FileUtils.OS.isMac() || FileUtils.OS.isUnix()){
DeidData.outputPath = "/tmp/deid_output/";
} else if(FileUtils.OS.isWindows()){
DeidData.outputPath = "E:\\Temp\\deid_output\\";
} else if(FileUtils.OS.isUnix()){
DeidData.outputPath = "/tmp/deid_output/";
} else {
DEIDGUI.log("Couldn't identify platform in \"" + FileUtils.OS.getOS()
+ "\", local output directory will be used.", LOG_LEVEL.WARNING);
DeidData.outputPath = "deid_output/";
}
//TODO: remove these
// DeidData.UserFullName = "Christian james precott";
// DeidData.UserInstitution = "Clemson U";
// DeidData.inputFiles = new Vector<File>(Arrays.asList(new File[]{new File("/Users/christianprescott/Desktop/dataset/152T1.nii")}));
File logFile = new File(DeidData.outputPath + "deid.log");
errWindow = new ErrorFrame(logFile);
InitLogFile(logFile);
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
DEIDGUI.log("Exiting");
// TODO: Delete files in the temporary output folder
dispose();
try {
DEIDGUI.logWriter.close();
} catch (IOException ex) {
Logger.getLogger(DEIDGUI.class.getName()).log(Level.SEVERE, null, ex);
}
System.exit(0);
}
});
// Copy tools to the tmp directory
unpackTools();
pagePanel.setLayout(new java.awt.BorderLayout());
pagePanel.add(new UserPanel());
log("Deidentification tool GUI initialized");
// TODO: File move does not work on linux
// TODO: Mac, linux, windows(.bat) shell scripts
// TODO: sharing mode in data file for each image?
// TODO: Linux compatibility
// TODO: Manual image-ID matching
// TODO: Update progress bar for image montage and tar creation
// TODO: VM option -Xdock:name=DeID sets the name displayed in the Apple menu bar.
// TODO: use -Xmx256m VM option to ensure DeID is allowed the memory
// it needs to display images. Even more memory needed in some cases.
// TODO: Link to help page with overview of functions and errors
// Warn in documentation about lots of free space needed on disk for
// converted files
// Attributions for dcm4che, fsl, dcm2nii, niftijlib, jtar, jsch, and ftp4j
// The fsl tools don't play nice with files on secondary drives, they
// Just throw a file read error (which DeID will display to the user)
// TODO: default FTP server credentials for MUSC's server
// TODO: Ability to cancel deface and tar and FTP procedures
// (See conversion tasks for example implementation)
// TODO: file cleanup on start or exit/completion? The temp folder is cleared
// on shutdown anyway, but it could grow to be very large. Simply
// delete all files in /tmp/deid_output except log file
// TODO: fslchfiletype and bet will have to have Windows/Unix specific
// builds because they need to know the absolute path of the tools
// TODO: It would be nice to refactor the fields in DeidData into a nice
// DeidImage class, with data about each image's source and result of
// conversions or deface.
// TODO: Error frame sometimes displays blank list panel, possible thread-related error?
}
/* public static void settheTitle(){
* this.setTitle("Deidentification Tool- " + title);
*
* }*/
private static String newline = "\n";
private void InitLogFile(File logFile) {
newline = System.getProperty("line.separator");
File outputDir = new File(DeidData.outputPath);
if(!outputDir.exists()){
outputDir.mkdirs();
}
try {
logFile.createNewFile();
logWriter = new FileWriter(logFile, false);
} catch (IOException ex) {
Logger.getLogger(DEIDGUI.class.getName()).log(Level.SEVERE, null, ex);
}
log("########################################");
log("# Deidentification Tool log #");
String dateStr = new Date().toString();
String dateLine = "# " + dateStr;
for (int ndx = 0; ndx < 40 - (dateStr.length() + 3); ndx++) {
dateLine += " ";
}
log(dateLine + "#");
log("########################################");
}
public static void log(String line){
log(line, LOG_LEVEL.INFO);
}
public static void log(String line, LOG_LEVEL level) {
if(line.isEmpty()){
return;
}
String writerLine = line.trim();
if(level == LOG_LEVEL.ERROR){
errWindow.addError(line, ErrorFrame.ERROR_TYPE.ERROR);
writerLine = "ERROR: " + writerLine;
} else if (level == LOG_LEVEL.WARNING){
errWindow.addError(line, ErrorFrame.ERROR_TYPE.WARNING);
writerLine = "WARNING: " + writerLine;
}
if (logWriter != null) {
try {
logWriter.write(writerLine + newline);
logWriter.flush();
} catch (IOException ex) {
Logger.getLogger(DEIDGUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
private void unpackTools() {
String[] toolNames = new String[]{
"bet",
"bet2",
"dcm2nii",
"mricron",
"mricron_64",
"fslchfiletype",
"fslchfiletype_exe",
"imtest",
"remove_ext",
"fslview",
"libbint.so",
"libcprob.so",
"libfslio.so",
"libggmix.so",
"libhfunc.so",
"libmeshclass.so",
"libmiscmaths.so",
"libmiscpic.so",
"libmiscplot.so",
"libmm.so",
"libnewimage.so",
"libprob.so",
"libshapeModel.so",
"libutils.so",
"libnewmat.so.10.0.0",
"libniftiio.so.2.0.0",
"libstdc++.so.6.0.14",
"libz.so.1.2.3.4",
"libznz.so.2.0.0",
"libnewmat.so.10.gz",
"libniftiio.so.2.gz",
"libstdc++.so.6.gz",
"libz.so.1.gz",
"libznz.so.2.gz",
"default.ini"
};
/* String[] toolNames = new String[]{
* "bet",
* "bet2",
* "dcm2nii",
* "fslchfiletype",
* "fslchfiletype_exe",
* "imtest",
* "remove_ext",};*/
// Extract only the tools for this platform
File outputDir;
String osPrefix, outputPath;
if(FileUtils.OS.isMac()){
outputPath = "/tmp/";
osPrefix = "osx";
} else if(FileUtils.OS.isWindows()){
outputPath = "E:\\Temp\\";
osPrefix = "win";
toolNames = new String[]{"robex.zip"};
// Windows executables work fine without the .exe extension, no
// need to concatenate it to unpacked files.
} else if(FileUtils.OS.isUnix()){
outputPath = "/tmp/";
osPrefix = "nix";
} else {
DEIDGUI.log("Couldn't identify platform in \"" + FileUtils.OS.getOS()
+ "\", unix tools will be used.", LOG_LEVEL.WARNING);
outputPath = "/tmp/";
osPrefix = "nix";
}
outputDir = new File(outputPath + "dit_tools");
log("Unpacking " + toolNames.length + " " + osPrefix +
" tools to " + outputDir);
if (!outputDir.exists()) {
outputDir.mkdirs();
}
int unpackCount = 0, existCount = 0;
for (String toolName : toolNames) {
File oFile = new File(outputDir.getAbsolutePath() + File.separator + toolName);
if (!oFile.exists()) {
// Get the resource from the jar
InputStream rStream = getClass().getResourceAsStream(
"tools/" + osPrefix + "_" + toolName);
FileOutputStream oStream = null;
if (rStream == null) {
DEIDGUI.log("Unable to get ResourceStream for " + "tools/" +
osPrefix + "_" + toolName + ", some deidentificati"
+ "on tasks may fail", DEIDGUI.LOG_LEVEL.ERROR);
} else {
try {
oFile.createNewFile();
oStream = new FileOutputStream(oFile);
// Copy the file from resources to a temp location
int size;
byte[] buf = new byte[1024];
while ((size = rStream.read(buf, 0, 1024)) != -1) {
oStream.write(buf, 0, size);
}
oFile.setExecutable(true);
// Save locations of critical tools on successful unzip
DeidData.unpackedFileLocation.put(toolName, oFile);
unpackCount++;
} catch (FileNotFoundException ex) {
DEIDGUI.log("An unpacked file "
+ "was not found, some deidentification tasks "
+ "may fail: " + ex.getMessage(), DEIDGUI.LOG_LEVEL.ERROR);
} catch (IOException ex) {
DEIDGUI.log("Unpacking " + toolName + " failed, some "
+ "deidentification tasks may fail: " +
ex.getMessage(), DEIDGUI.LOG_LEVEL.WARNING);
} finally {
if (oStream != null) {
try {
oStream.close();
} catch (IOException ex) {
}
}
try {
rStream.close();
} catch (IOException ex) {
}
}
}
} else {
// Save locations of critical tools
DeidData.unpackedFileLocation.put(toolName, oFile);
existCount++;
}
}
if(unpackCount > 0){
log(unpackCount + " tools were successfully unpacked");
}
if(existCount > 0){
log(existCount + " tools were already in place");
}
String gzfiles[] = new String[]{"/tmp/dit_tools/libnewmat.so.10", "/tmp/dit_tools/libniftiio.so.2","/tmp/dit_tools/libstdc++.so.6", "/tmp/dit_tools/libz.so.1",
"/tmp/dit_tools/libznz.so.2"};
- String zipfiles[]= new String[]{DeidData.unpackedFileLocation.get("robex.zip").getParentFile().getAbsolutePath()+"\\robex"};
+ String zipfiles[]= new String[]{};
if(FileUtils.OS.isWindows())
{
gzfiles=new String[]{};
+ zipfiles= new String[]{DeidData.unpackedFileLocation.get("robex.zip").getParentFile().getAbsolutePath()+"\\robex"};
}
else
{
zipfiles=new String[]{};
}
for(String gzfile:gzfiles){
try{
FileInputStream instream= new FileInputStream(gzfile+".gz");
FileOutputStream outstream;
try (GZIPInputStream ginstream = new GZIPInputStream(instream)) {
outstream = new FileOutputStream(gzfile);
byte[] buf = new byte[1024];
int len;
while ((len = ginstream.read(buf)) > 0)
{
outstream.write(buf, 0, len);
}
}
outstream.close();
} catch(IOException e){
System.out.println("failed:"+e);
}
}
for(String gzfile:zipfiles){
try {
String destinationname = DeidData.unpackedFileLocation.get("robex.zip").getParentFile().getAbsolutePath()+"\\";
byte[] buf = new byte[1024];
ZipInputStream zipinputstream = null;
ZipEntry zipentry;
zipinputstream = new ZipInputStream(
new FileInputStream(gzfile+".zip"));
zipentry = zipinputstream.getNextEntry();
while (zipentry != null) {
//for each entry to be extracted
String entryName = destinationname + zipentry.getName();
entryName = entryName.replace('/', File.separatorChar);
entryName = entryName.replace('\\', File.separatorChar);
System.out.println("entryname " + entryName);
int n;
FileOutputStream fileoutputstream;
File newFile = new File(entryName);
if (zipentry.isDirectory()) {
if (!newFile.mkdirs()) {
break;
}
zipentry = zipinputstream.getNextEntry();
continue;
}
fileoutputstream = new FileOutputStream(entryName);
while ((n = zipinputstream.read(buf, 0, 1024)) > -1) {
fileoutputstream.write(buf, 0, n);
}
fileoutputstream.close();
zipinputstream.closeEntry();
zipentry = zipinputstream.getNextEntry();
}//while
zipinputstream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 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() {
buttonPanel = new javax.swing.JPanel();
jSeparator5 = new javax.swing.JSeparator();
continueButton = new javax.swing.JButton();
backButton = new javax.swing.JButton();
cancelButton = new javax.swing.JButton();
helpButton = new javax.swing.JButton();
errlogButton = new javax.swing.JButton();
jButtonMisHelp = new javax.swing.JButton();
pagePanel = new javax.swing.JPanel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("DeIDentification Tool");
setMinimumSize(new java.awt.Dimension(512, 512));
continueButton.setText("Continue >");
continueButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
continueButtonActionPerformed(evt);
}
});
backButton.setText("< Back");
backButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
backButtonActionPerformed(evt);
}
});
cancelButton.setText("Cancel");
cancelButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cancelButtonActionPerformed(evt);
}
});
helpButton.setText("Help");
helpButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
helpButtonActionPerformed(evt);
}
});
errlogButton.setText("See Error Log");
errlogButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
errlogButtonActionPerformed(evt);
}
});
jButtonMisHelp.setText("Mismatch Help");
jButtonMisHelp.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonMisHelpActionPerformed(evt);
}
});
org.jdesktop.layout.GroupLayout buttonPanelLayout = new org.jdesktop.layout.GroupLayout(buttonPanel);
buttonPanel.setLayout(buttonPanelLayout);
buttonPanelLayout.setHorizontalGroup(
buttonPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(buttonPanelLayout.createSequentialGroup()
.addContainerGap()
.add(buttonPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(buttonPanelLayout.createSequentialGroup()
.add(cancelButton)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
.add(helpButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 61, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
.add(errlogButton)
.add(18, 18, 18)
.add(jButtonMisHelp)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.add(backButton)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(continueButton))
.add(jSeparator5))
.addContainerGap())
);
buttonPanelLayout.setVerticalGroup(
buttonPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(org.jdesktop.layout.GroupLayout.TRAILING, buttonPanelLayout.createSequentialGroup()
.addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.add(jSeparator5, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 10, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(buttonPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(continueButton)
.add(backButton)
.add(cancelButton)
.add(helpButton)
.add(errlogButton)
.add(jButtonMisHelp))
.addContainerGap())
);
org.jdesktop.layout.GroupLayout pagePanelLayout = new org.jdesktop.layout.GroupLayout(pagePanel);
pagePanel.setLayout(pagePanelLayout);
pagePanelLayout.setHorizontalGroup(
pagePanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 652, Short.MAX_VALUE)
);
pagePanelLayout.setVerticalGroup(
pagePanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 428, Short.MAX_VALUE)
);
org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(buttonPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.add(pagePanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
.add(pagePanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(buttonPanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
public static void advance() {
continueButton.setEnabled(true);
backButton.setEnabled(true);
try{
WizardPanel nextPanel = ((WizardPanel) pagePanel.getComponent(0)).getNextPanel();
pagePanel.remove(0);
pagePanel.add((JPanel) nextPanel);
pagePanel.revalidate();
log(">>> Advanced to " + nextPanel.getClass().getSimpleName());
} catch (Exception e){
e.printStackTrace();
log("Failed to advance: " + e.getMessage(), LOG_LEVEL.ERROR);
}
}
public static void previous() {
continueButton.setEnabled(true);
backButton.setEnabled(true);
try{
WizardPanel prevPanel = ((WizardPanel) pagePanel.getComponent(0)).getPreviousPanel();
pagePanel.remove(0);
pagePanel.add((JPanel) prevPanel);
pagePanel.revalidate();
log("<<< Back to " + prevPanel.getClass().getSimpleName());
} catch (Exception e){
log("Failed to go back: " + e.getMessage(), LOG_LEVEL.ERROR);
}
}
private void continueButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_continueButtonActionPerformed
advance();
}//GEN-LAST:event_continueButtonActionPerformed
private void backButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_backButtonActionPerformed
previous();
}//GEN-LAST:event_backButtonActionPerformed
private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(
new WindowEvent(this, WindowEvent.WINDOW_CLOSING));
}//GEN-LAST:event_cancelButtonActionPerformed
private void helpButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_helpButtonActionPerformed
// TODO add your handling code here:
help = new HelpManualFrame(title);
help.pack();
help.setVisible(true);
}//GEN-LAST:event_helpButtonActionPerformed
private void errlogButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_errlogButtonActionPerformed
// TODO add your handling code here:
if (!DeidData.errorlog.isEmpty()){
Iterator vItr = DeidData.errorlog.iterator();
while(vItr.hasNext())
{
log(vItr.next().toString(), LOG_LEVEL.WARNING);
}
}
}//GEN-LAST:event_errlogButtonActionPerformed
private void jButtonMisHelpActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonMisHelpActionPerformed
// TODO add your handling code here:
mhf = new misHelpFrame();
mhf.pack();
mhf.setVisible(true);
}//GEN-LAST:event_jButtonMisHelpActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
if(FileUtils.OS.isMac()){
// Use the Mac OS X Menu bar instead of the JFrame one
System.setProperty("apple.laf.useScreenMenuBar", "true");
// This name setting does not work
System.setProperty("com.apple.mrj.application.apple.menu.about.name", "DeID");
}
/*
* Set the OS look and feel
*/
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
// Use the System look and feel
try {
javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(DEIDGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(DEIDGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(DEIDGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(DEIDGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/*
* Create and display the form
*/
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new DEIDGUI().setVisible(true);
// DEIDGUI.log("This is a super long warning, it's just so warnful"
// + " file /Users/christian/Desktop/image.jpeg",
// LOG_LEVEL.WARNING);
// DEIDGUI.log("This is a super long error, it is similar in its "
// + "longfulness to the previous warning file "
// + "/Users/christian/Desktop/image.jpeg",
// LOG_LEVEL.ERROR);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
public static javax.swing.JButton backButton;
private javax.swing.JPanel buttonPanel;
public static javax.swing.JButton cancelButton;
public static javax.swing.JButton continueButton;
public static javax.swing.JButton errlogButton;
public static javax.swing.JButton helpButton;
public static javax.swing.JButton jButtonMisHelp;
private javax.swing.JSeparator jSeparator5;
private static javax.swing.JPanel pagePanel;
// End of variables declaration//GEN-END:variables
}
| false | true | private void unpackTools() {
String[] toolNames = new String[]{
"bet",
"bet2",
"dcm2nii",
"mricron",
"mricron_64",
"fslchfiletype",
"fslchfiletype_exe",
"imtest",
"remove_ext",
"fslview",
"libbint.so",
"libcprob.so",
"libfslio.so",
"libggmix.so",
"libhfunc.so",
"libmeshclass.so",
"libmiscmaths.so",
"libmiscpic.so",
"libmiscplot.so",
"libmm.so",
"libnewimage.so",
"libprob.so",
"libshapeModel.so",
"libutils.so",
"libnewmat.so.10.0.0",
"libniftiio.so.2.0.0",
"libstdc++.so.6.0.14",
"libz.so.1.2.3.4",
"libznz.so.2.0.0",
"libnewmat.so.10.gz",
"libniftiio.so.2.gz",
"libstdc++.so.6.gz",
"libz.so.1.gz",
"libznz.so.2.gz",
"default.ini"
};
/* String[] toolNames = new String[]{
* "bet",
* "bet2",
* "dcm2nii",
* "fslchfiletype",
* "fslchfiletype_exe",
* "imtest",
* "remove_ext",};*/
// Extract only the tools for this platform
File outputDir;
String osPrefix, outputPath;
if(FileUtils.OS.isMac()){
outputPath = "/tmp/";
osPrefix = "osx";
} else if(FileUtils.OS.isWindows()){
outputPath = "E:\\Temp\\";
osPrefix = "win";
toolNames = new String[]{"robex.zip"};
// Windows executables work fine without the .exe extension, no
// need to concatenate it to unpacked files.
} else if(FileUtils.OS.isUnix()){
outputPath = "/tmp/";
osPrefix = "nix";
} else {
DEIDGUI.log("Couldn't identify platform in \"" + FileUtils.OS.getOS()
+ "\", unix tools will be used.", LOG_LEVEL.WARNING);
outputPath = "/tmp/";
osPrefix = "nix";
}
outputDir = new File(outputPath + "dit_tools");
log("Unpacking " + toolNames.length + " " + osPrefix +
" tools to " + outputDir);
if (!outputDir.exists()) {
outputDir.mkdirs();
}
int unpackCount = 0, existCount = 0;
for (String toolName : toolNames) {
File oFile = new File(outputDir.getAbsolutePath() + File.separator + toolName);
if (!oFile.exists()) {
// Get the resource from the jar
InputStream rStream = getClass().getResourceAsStream(
"tools/" + osPrefix + "_" + toolName);
FileOutputStream oStream = null;
if (rStream == null) {
DEIDGUI.log("Unable to get ResourceStream for " + "tools/" +
osPrefix + "_" + toolName + ", some deidentificati"
+ "on tasks may fail", DEIDGUI.LOG_LEVEL.ERROR);
} else {
try {
oFile.createNewFile();
oStream = new FileOutputStream(oFile);
// Copy the file from resources to a temp location
int size;
byte[] buf = new byte[1024];
while ((size = rStream.read(buf, 0, 1024)) != -1) {
oStream.write(buf, 0, size);
}
oFile.setExecutable(true);
// Save locations of critical tools on successful unzip
DeidData.unpackedFileLocation.put(toolName, oFile);
unpackCount++;
} catch (FileNotFoundException ex) {
DEIDGUI.log("An unpacked file "
+ "was not found, some deidentification tasks "
+ "may fail: " + ex.getMessage(), DEIDGUI.LOG_LEVEL.ERROR);
} catch (IOException ex) {
DEIDGUI.log("Unpacking " + toolName + " failed, some "
+ "deidentification tasks may fail: " +
ex.getMessage(), DEIDGUI.LOG_LEVEL.WARNING);
} finally {
if (oStream != null) {
try {
oStream.close();
} catch (IOException ex) {
}
}
try {
rStream.close();
} catch (IOException ex) {
}
}
}
} else {
// Save locations of critical tools
DeidData.unpackedFileLocation.put(toolName, oFile);
existCount++;
}
}
if(unpackCount > 0){
log(unpackCount + " tools were successfully unpacked");
}
if(existCount > 0){
log(existCount + " tools were already in place");
}
String gzfiles[] = new String[]{"/tmp/dit_tools/libnewmat.so.10", "/tmp/dit_tools/libniftiio.so.2","/tmp/dit_tools/libstdc++.so.6", "/tmp/dit_tools/libz.so.1",
"/tmp/dit_tools/libznz.so.2"};
String zipfiles[]= new String[]{DeidData.unpackedFileLocation.get("robex.zip").getParentFile().getAbsolutePath()+"\\robex"};
if(FileUtils.OS.isWindows())
{
gzfiles=new String[]{};
}
else
{
zipfiles=new String[]{};
}
for(String gzfile:gzfiles){
try{
FileInputStream instream= new FileInputStream(gzfile+".gz");
FileOutputStream outstream;
try (GZIPInputStream ginstream = new GZIPInputStream(instream)) {
outstream = new FileOutputStream(gzfile);
byte[] buf = new byte[1024];
int len;
while ((len = ginstream.read(buf)) > 0)
{
outstream.write(buf, 0, len);
}
}
outstream.close();
} catch(IOException e){
System.out.println("failed:"+e);
}
}
for(String gzfile:zipfiles){
try {
String destinationname = DeidData.unpackedFileLocation.get("robex.zip").getParentFile().getAbsolutePath()+"\\";
byte[] buf = new byte[1024];
ZipInputStream zipinputstream = null;
ZipEntry zipentry;
zipinputstream = new ZipInputStream(
new FileInputStream(gzfile+".zip"));
zipentry = zipinputstream.getNextEntry();
while (zipentry != null) {
//for each entry to be extracted
String entryName = destinationname + zipentry.getName();
entryName = entryName.replace('/', File.separatorChar);
entryName = entryName.replace('\\', File.separatorChar);
System.out.println("entryname " + entryName);
int n;
FileOutputStream fileoutputstream;
File newFile = new File(entryName);
if (zipentry.isDirectory()) {
if (!newFile.mkdirs()) {
break;
}
zipentry = zipinputstream.getNextEntry();
continue;
}
fileoutputstream = new FileOutputStream(entryName);
while ((n = zipinputstream.read(buf, 0, 1024)) > -1) {
fileoutputstream.write(buf, 0, n);
}
fileoutputstream.close();
zipinputstream.closeEntry();
zipentry = zipinputstream.getNextEntry();
}//while
zipinputstream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
| private void unpackTools() {
String[] toolNames = new String[]{
"bet",
"bet2",
"dcm2nii",
"mricron",
"mricron_64",
"fslchfiletype",
"fslchfiletype_exe",
"imtest",
"remove_ext",
"fslview",
"libbint.so",
"libcprob.so",
"libfslio.so",
"libggmix.so",
"libhfunc.so",
"libmeshclass.so",
"libmiscmaths.so",
"libmiscpic.so",
"libmiscplot.so",
"libmm.so",
"libnewimage.so",
"libprob.so",
"libshapeModel.so",
"libutils.so",
"libnewmat.so.10.0.0",
"libniftiio.so.2.0.0",
"libstdc++.so.6.0.14",
"libz.so.1.2.3.4",
"libznz.so.2.0.0",
"libnewmat.so.10.gz",
"libniftiio.so.2.gz",
"libstdc++.so.6.gz",
"libz.so.1.gz",
"libznz.so.2.gz",
"default.ini"
};
/* String[] toolNames = new String[]{
* "bet",
* "bet2",
* "dcm2nii",
* "fslchfiletype",
* "fslchfiletype_exe",
* "imtest",
* "remove_ext",};*/
// Extract only the tools for this platform
File outputDir;
String osPrefix, outputPath;
if(FileUtils.OS.isMac()){
outputPath = "/tmp/";
osPrefix = "osx";
} else if(FileUtils.OS.isWindows()){
outputPath = "E:\\Temp\\";
osPrefix = "win";
toolNames = new String[]{"robex.zip"};
// Windows executables work fine without the .exe extension, no
// need to concatenate it to unpacked files.
} else if(FileUtils.OS.isUnix()){
outputPath = "/tmp/";
osPrefix = "nix";
} else {
DEIDGUI.log("Couldn't identify platform in \"" + FileUtils.OS.getOS()
+ "\", unix tools will be used.", LOG_LEVEL.WARNING);
outputPath = "/tmp/";
osPrefix = "nix";
}
outputDir = new File(outputPath + "dit_tools");
log("Unpacking " + toolNames.length + " " + osPrefix +
" tools to " + outputDir);
if (!outputDir.exists()) {
outputDir.mkdirs();
}
int unpackCount = 0, existCount = 0;
for (String toolName : toolNames) {
File oFile = new File(outputDir.getAbsolutePath() + File.separator + toolName);
if (!oFile.exists()) {
// Get the resource from the jar
InputStream rStream = getClass().getResourceAsStream(
"tools/" + osPrefix + "_" + toolName);
FileOutputStream oStream = null;
if (rStream == null) {
DEIDGUI.log("Unable to get ResourceStream for " + "tools/" +
osPrefix + "_" + toolName + ", some deidentificati"
+ "on tasks may fail", DEIDGUI.LOG_LEVEL.ERROR);
} else {
try {
oFile.createNewFile();
oStream = new FileOutputStream(oFile);
// Copy the file from resources to a temp location
int size;
byte[] buf = new byte[1024];
while ((size = rStream.read(buf, 0, 1024)) != -1) {
oStream.write(buf, 0, size);
}
oFile.setExecutable(true);
// Save locations of critical tools on successful unzip
DeidData.unpackedFileLocation.put(toolName, oFile);
unpackCount++;
} catch (FileNotFoundException ex) {
DEIDGUI.log("An unpacked file "
+ "was not found, some deidentification tasks "
+ "may fail: " + ex.getMessage(), DEIDGUI.LOG_LEVEL.ERROR);
} catch (IOException ex) {
DEIDGUI.log("Unpacking " + toolName + " failed, some "
+ "deidentification tasks may fail: " +
ex.getMessage(), DEIDGUI.LOG_LEVEL.WARNING);
} finally {
if (oStream != null) {
try {
oStream.close();
} catch (IOException ex) {
}
}
try {
rStream.close();
} catch (IOException ex) {
}
}
}
} else {
// Save locations of critical tools
DeidData.unpackedFileLocation.put(toolName, oFile);
existCount++;
}
}
if(unpackCount > 0){
log(unpackCount + " tools were successfully unpacked");
}
if(existCount > 0){
log(existCount + " tools were already in place");
}
String gzfiles[] = new String[]{"/tmp/dit_tools/libnewmat.so.10", "/tmp/dit_tools/libniftiio.so.2","/tmp/dit_tools/libstdc++.so.6", "/tmp/dit_tools/libz.so.1",
"/tmp/dit_tools/libznz.so.2"};
String zipfiles[]= new String[]{};
if(FileUtils.OS.isWindows())
{
gzfiles=new String[]{};
zipfiles= new String[]{DeidData.unpackedFileLocation.get("robex.zip").getParentFile().getAbsolutePath()+"\\robex"};
}
else
{
zipfiles=new String[]{};
}
for(String gzfile:gzfiles){
try{
FileInputStream instream= new FileInputStream(gzfile+".gz");
FileOutputStream outstream;
try (GZIPInputStream ginstream = new GZIPInputStream(instream)) {
outstream = new FileOutputStream(gzfile);
byte[] buf = new byte[1024];
int len;
while ((len = ginstream.read(buf)) > 0)
{
outstream.write(buf, 0, len);
}
}
outstream.close();
} catch(IOException e){
System.out.println("failed:"+e);
}
}
for(String gzfile:zipfiles){
try {
String destinationname = DeidData.unpackedFileLocation.get("robex.zip").getParentFile().getAbsolutePath()+"\\";
byte[] buf = new byte[1024];
ZipInputStream zipinputstream = null;
ZipEntry zipentry;
zipinputstream = new ZipInputStream(
new FileInputStream(gzfile+".zip"));
zipentry = zipinputstream.getNextEntry();
while (zipentry != null) {
//for each entry to be extracted
String entryName = destinationname + zipentry.getName();
entryName = entryName.replace('/', File.separatorChar);
entryName = entryName.replace('\\', File.separatorChar);
System.out.println("entryname " + entryName);
int n;
FileOutputStream fileoutputstream;
File newFile = new File(entryName);
if (zipentry.isDirectory()) {
if (!newFile.mkdirs()) {
break;
}
zipentry = zipinputstream.getNextEntry();
continue;
}
fileoutputstream = new FileOutputStream(entryName);
while ((n = zipinputstream.read(buf, 0, 1024)) > -1) {
fileoutputstream.write(buf, 0, n);
}
fileoutputstream.close();
zipinputstream.closeEntry();
zipentry = zipinputstream.getNextEntry();
}//while
zipinputstream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
diff --git a/android/src/org/thinkfree/NFC/TagViewer.java b/android/src/org/thinkfree/NFC/TagViewer.java
index e4d1bda..31d3e21 100755
--- a/android/src/org/thinkfree/NFC/TagViewer.java
+++ b/android/src/org/thinkfree/NFC/TagViewer.java
@@ -1,224 +1,224 @@
/*
* 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 org.thinkfree.NFC;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Parcelable;
import android.util.Log;
import org.thinkfree.NFC.record.ParsedNdefRecord;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
import java.util.Properties;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
/**
* An {@link Activity} which handles a broadcast of a new tag that the device
* just discovered.
*/
public class TagViewer extends Activity {
static final String TAG = "NFC";
Activity mAct;
/**
* This activity will finish itself in this amount of time if the user
* doesn't do anything.
*/
static final int ACTIVITY_TIMEOUT_MS = 1 * 1000;
@Override
protected void onCreate(Bundle savedInstanceState) {
//StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
//StrictMode.setThreadPolicy(policy);
super.onCreate(savedInstanceState);
resolveIntent(getIntent());
mAct = this;
}
void resolveIntent(Intent intent) {
Log.e(TAG, "Tag detected");
String action = intent.getAction();
Log.e(TAG, action);
if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
NdefMessage[] msgs;
if (rawMsgs != null) {
msgs = new NdefMessage[rawMsgs.length];
for (int i = 0; i < rawMsgs.length; i++) {
msgs[i] = (NdefMessage) rawMsgs[i];
}
} else {
// Unknown tag type
Log.e(TAG, "Unknown tag type");
byte[] empty = new byte[] {};
NdefRecord record = new NdefRecord(NdefRecord.TNF_UNKNOWN, empty, empty, empty);
NdefMessage msg = new NdefMessage(new NdefRecord[] {record});
msgs = new NdefMessage[] {msg};
}
// Setup the views
processMessage(msgs);
}
else {
Log.e(TAG, "Unknown intent " + intent);
finish();
return;
}
}
void processMessage(NdefMessage[] msgs) {
Log.e(TAG, "Processing message");
if (msgs == null || msgs.length == 0) {
finish();
return;
}
List<ParsedNdefRecord> records = NdefMessageParser.parse(msgs[0]);
final int size = records.size();
for (int i = 0; i < size; i++) {
ParsedNdefRecord record = records.get(i);
String str = record.getText();
String key = str.split("=")[0];
Log.e(TAG, "Key : " + key);
if ( key.equals("Scene")){
String value = str.split("=")[1];
Log.e(TAG,"Making a request to : " + value);
new MakeDomoLoadSceneRestRequest().execute(value);
}
}
return;
}
@Override
public void onNewIntent(Intent intent) {
setIntent(intent);
resolveIntent(intent);
}
class MakeDomoLoadSceneRestRequest extends AsyncTask<String, Object, Object> {
@Override
protected Object doInBackground(String... params) {
Properties prop = new Properties();
try {
- prop.load(new FileInputStream(Environment.getExternalStorageDirectory().toString() + "/.on-domo-qt/config.ini"));
+ prop.load(new FileInputStream(Environment.getExternalStorageDirectory().toString() + "/.axihome/config.ini"));
}
catch (FileNotFoundException e1) {
e1.printStackTrace();
}
catch (IOException e1) {
e1.printStackTrace();
}
String url = prop.getProperty("sceneUrl") + params[0];
Log.e(TAG, "Requesting to url : " + url);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = null;
try {
HttpGet get = new HttpGet(url);
response = httpclient.execute(get);
}
catch (ClientProtocolException e) {
Log.e(TAG, "Error 1");
e.printStackTrace();
}
catch (IOException e) {
Log.e(TAG, "Error 2");
e.printStackTrace();
}
catch(Exception e){
Log.e(TAG, "Exception executing request");
e.printStackTrace();
}
try{
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
Log.e(TAG,"Request ok");
}
else{
Log.e(TAG,"Request failed");
}
}
catch(Exception e){
Log.e(TAG, "Exception getting status");
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Object result) {
Log.e(TAG, "Closing activity");
mAct.finish();
}
}
}
| true | true | protected Object doInBackground(String... params) {
Properties prop = new Properties();
try {
prop.load(new FileInputStream(Environment.getExternalStorageDirectory().toString() + "/.on-domo-qt/config.ini"));
}
catch (FileNotFoundException e1) {
e1.printStackTrace();
}
catch (IOException e1) {
e1.printStackTrace();
}
String url = prop.getProperty("sceneUrl") + params[0];
Log.e(TAG, "Requesting to url : " + url);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = null;
try {
HttpGet get = new HttpGet(url);
response = httpclient.execute(get);
}
catch (ClientProtocolException e) {
Log.e(TAG, "Error 1");
e.printStackTrace();
}
catch (IOException e) {
Log.e(TAG, "Error 2");
e.printStackTrace();
}
catch(Exception e){
Log.e(TAG, "Exception executing request");
e.printStackTrace();
}
try{
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
Log.e(TAG,"Request ok");
}
else{
Log.e(TAG,"Request failed");
}
}
catch(Exception e){
Log.e(TAG, "Exception getting status");
e.printStackTrace();
}
return null;
}
| protected Object doInBackground(String... params) {
Properties prop = new Properties();
try {
prop.load(new FileInputStream(Environment.getExternalStorageDirectory().toString() + "/.axihome/config.ini"));
}
catch (FileNotFoundException e1) {
e1.printStackTrace();
}
catch (IOException e1) {
e1.printStackTrace();
}
String url = prop.getProperty("sceneUrl") + params[0];
Log.e(TAG, "Requesting to url : " + url);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = null;
try {
HttpGet get = new HttpGet(url);
response = httpclient.execute(get);
}
catch (ClientProtocolException e) {
Log.e(TAG, "Error 1");
e.printStackTrace();
}
catch (IOException e) {
Log.e(TAG, "Error 2");
e.printStackTrace();
}
catch(Exception e){
Log.e(TAG, "Exception executing request");
e.printStackTrace();
}
try{
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
Log.e(TAG,"Request ok");
}
else{
Log.e(TAG,"Request failed");
}
}
catch(Exception e){
Log.e(TAG, "Exception getting status");
e.printStackTrace();
}
return null;
}
|
diff --git a/luni/src/main/java/java/util/Random.java b/luni/src/main/java/java/util/Random.java
index 7ce74cc95..cc9de5883 100644
--- a/luni/src/main/java/java/util/Random.java
+++ b/luni/src/main/java/java/util/Random.java
@@ -1,205 +1,201 @@
/*
* 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 java.util;
import java.io.Serializable;
/**
* This class provides methods that return pseudo-random values.
*
* <p>It is dangerous to seed {@code Random} with the current time because
* that value is more predictable to an attacker than the default seed.
*
* <p>This class is thread-safe.
*
* @see java.security.SecureRandom
*/
public class Random implements Serializable {
private static final long serialVersionUID = 3905348978240129619L;
private static final long multiplier = 0x5deece66dL;
/**
* The boolean value indicating if the second Gaussian number is available.
*
* @serial
*/
private boolean haveNextNextGaussian;
/**
* @serial It is associated with the internal state of this generator.
*/
private long seed;
/**
* The second Gaussian generated number.
*
* @serial
*/
private double nextNextGaussian;
/**
* Constructs a random generator with an initial state that is
* unlikely to be duplicated by a subsequent instantiation.
*
* <p>The initial state (that is, the seed) is <i>partially</i> based
* on the current time of day in milliseconds.
*/
public Random() {
// Note: Using identityHashCode() to be hermetic wrt subclasses.
setSeed(System.currentTimeMillis() + System.identityHashCode(this));
}
/**
* Construct a random generator with the given {@code seed} as the
* initial state. Equivalent to {@code Random r = new Random(); r.setSeed(seed);}.
*
* <p>This constructor is mainly useful for <i>predictability</i> in tests.
* The default constructor is likely to provide better randomness.
*/
public Random(long seed) {
setSeed(seed);
}
/**
* Returns a pseudo-random uniformly distributed {@code int} value of
* the number of bits specified by the argument {@code bits} as
* described by Donald E. Knuth in <i>The Art of Computer Programming,
* Volume 2: Seminumerical Algorithms</i>, section 3.2.1.
*
* <p>Most applications will want to use one of this class' convenience methods instead.
*/
protected synchronized int next(int bits) {
seed = (seed * multiplier + 0xbL) & ((1L << 48) - 1);
return (int) (seed >>> (48 - bits));
}
/**
* Returns a pseudo-random uniformly distributed {@code boolean}.
*/
public boolean nextBoolean() {
return next(1) != 0;
}
/**
* Fills {@code buf} with random bytes.
*/
public void nextBytes(byte[] buf) {
int rand = 0, count = 0, loop = 0;
while (count < buf.length) {
if (loop == 0) {
rand = nextInt();
loop = 3;
} else {
loop--;
}
buf[count++] = (byte) rand;
rand >>= 8;
}
}
/**
* Returns a pseudo-random uniformly distributed {@code double}
* in the half-open range [0.0, 1.0).
*/
public double nextDouble() {
return ((((long) next(26) << 27) + next(27)) / (double) (1L << 53));
}
/**
* Returns a pseudo-random uniformly distributed {@code float}
* in the half-open range [0.0, 1.0).
*/
public float nextFloat() {
return (next(24) / 16777216f);
}
/**
* Returns a pseudo-random (approximately) normally distributed
* {@code double} with mean 0.0 and standard deviation 1.0.
* This method uses the <i>polar method</i> of G. E. P. Box, M.
* E. Muller, and G. Marsaglia, as described by Donald E. Knuth in <i>The
* Art of Computer Programming, Volume 2: Seminumerical Algorithms</i>,
* section 3.4.1, subsection C, algorithm P.
*/
public synchronized double nextGaussian() {
- if (haveNextNextGaussian) { // if X1 has been returned, return the
- // second Gaussian
+ if (haveNextNextGaussian) {
haveNextNextGaussian = false;
return nextNextGaussian;
}
double v1, v2, s;
do {
- v1 = 2 * nextDouble() - 1; // Generates two independent random
- // variables U1, U2
+ v1 = 2 * nextDouble() - 1;
v2 = 2 * nextDouble() - 1;
s = v1 * v1 + v2 * v2;
- } while (s >= 1);
- double norm = Math.sqrt(-2 * Math.log(s) / s);
- nextNextGaussian = v2 * norm; // should that not be norm instead
- // of multiplier ?
+ } while (s >= 1 || s == 0);
+ double multiplier = StrictMath.sqrt(-2 * StrictMath.log(s) / s);
+ nextNextGaussian = v2 * multiplier;
haveNextNextGaussian = true;
- return v1 * norm; // should that not be norm instead of multiplier
- // ?
+ return v1 * multiplier;
}
/**
* Returns a pseudo-random uniformly distributed {@code int}.
*/
public int nextInt() {
return next(32);
}
/**
* Returns a pseudo-random uniformly distributed {@code int}
* in the half-open range [0, n).
*/
public int nextInt(int n) {
if (n > 0) {
if ((n & -n) == n) {
return (int) ((n * (long) next(31)) >> 31);
}
int bits, val;
do {
bits = next(31);
val = bits % n;
} while (bits - val + (n - 1) < 0);
return val;
}
throw new IllegalArgumentException();
}
/**
* Returns a pseudo-random uniformly distributed {@code long}.
*/
public long nextLong() {
return ((long) next(32) << 32) + next(32);
}
/**
* Modifies the seed using a linear congruential formula presented in <i>The
* Art of Computer Programming, Volume 2</i>, Section 3.2.1.
*/
public synchronized void setSeed(long seed) {
this.seed = (seed ^ multiplier) & ((1L << 48) - 1);
haveNextNextGaussian = false;
}
}
| false | true | public synchronized double nextGaussian() {
if (haveNextNextGaussian) { // if X1 has been returned, return the
// second Gaussian
haveNextNextGaussian = false;
return nextNextGaussian;
}
double v1, v2, s;
do {
v1 = 2 * nextDouble() - 1; // Generates two independent random
// variables U1, U2
v2 = 2 * nextDouble() - 1;
s = v1 * v1 + v2 * v2;
} while (s >= 1);
double norm = Math.sqrt(-2 * Math.log(s) / s);
nextNextGaussian = v2 * norm; // should that not be norm instead
// of multiplier ?
haveNextNextGaussian = true;
return v1 * norm; // should that not be norm instead of multiplier
// ?
}
| public synchronized double nextGaussian() {
if (haveNextNextGaussian) {
haveNextNextGaussian = false;
return nextNextGaussian;
}
double v1, v2, s;
do {
v1 = 2 * nextDouble() - 1;
v2 = 2 * nextDouble() - 1;
s = v1 * v1 + v2 * v2;
} while (s >= 1 || s == 0);
double multiplier = StrictMath.sqrt(-2 * StrictMath.log(s) / s);
nextNextGaussian = v2 * multiplier;
haveNextNextGaussian = true;
return v1 * multiplier;
}
|
diff --git a/source/de/anomic/htmlFilter/htmlFilterInputStream.java b/source/de/anomic/htmlFilter/htmlFilterInputStream.java
index 5f3c55439..5d28f6537 100644
--- a/source/de/anomic/htmlFilter/htmlFilterInputStream.java
+++ b/source/de/anomic/htmlFilter/htmlFilterInputStream.java
@@ -1,169 +1,169 @@
// htmlFilterInputStream.java
// (C) 2005, 2006 by Michael Peter Christen; [email protected], Frankfurt a. M., Germany
// first published 2005 on http://www.anomic.de
//
// This is a part of YaCy, a peer-to-peer based web search engine
//
// $LastChangedDate: 2006-04-02 22:40:07 +0200 (So, 02 Apr 2006) $
// $LastChangedRevision: 1986 $
// $LastChangedBy: orbiter $
//
// LICENSE
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package de.anomic.htmlFilter;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.Properties;
import de.anomic.yacy.yacyURL;
public class htmlFilterInputStream extends InputStream implements htmlFilterEventListener {
private static final int MODE_PRESCAN = 0;
private static final int MODE_PRESCAN_FINISHED = 1;
private int mode = 1;
private static final long preBufferSize = 2048;
private long preRead = 0;
private final BufferedInputStream bufferedIn;
private String detectedCharset;
private boolean charsetChanged = false;
private boolean endOfHead = false;
private Reader reader;
private Writer writer;
public htmlFilterInputStream(
final InputStream inStream,
final String inputStreamCharset,
final yacyURL rooturl,
final htmlFilterTransformer transformer,
final boolean passbyIfBinarySuspect
) {
// create a input stream for buffereing
this.bufferedIn = new BufferedInputStream(inStream,(int) preBufferSize);
this.bufferedIn.mark((int) preBufferSize);
final htmlFilterContentScraper scraper = new htmlFilterContentScraper(rooturl);
- //scraper.registerHtmlFilterEventListener(this);
+ scraper.registerHtmlFilterEventListener(this);
try {
this.reader = new InputStreamReader(this,inputStreamCharset);
} catch (UnsupportedEncodingException e) {
try {
this.reader = new InputStreamReader(this, "UTF-8");
} catch (UnsupportedEncodingException e1) {
// how is that possible?
this.reader = new InputStreamReader(this);
}
}
this.writer = new htmlFilterWriter(null,null,scraper,transformer,passbyIfBinarySuspect);
}
private static String extractCharsetFromMimetypeHeader(final String mimeType) {
if (mimeType == null) return null;
final String[] parts = mimeType.split(";");
if (parts == null || parts.length <= 1) return null;
for (int i=1; i < parts.length; i++) {
final String param = parts[i].trim();
if (param.startsWith("charset=")) {
String charset = param.substring("charset=".length()).trim();
if (charset.startsWith("\"") || charset.startsWith("'")) charset = charset.substring(1);
if (charset.endsWith("\"") || charset.endsWith("'")) charset = charset.substring(0,charset.length()-1);
return charset.trim();
}
}
return null;
}
public void scrapeTag0(final String tagname, final Properties tagopts) {
if (tagname == null || tagname.length() == 0) return;
if (tagname.equalsIgnoreCase("meta")) {
if (tagopts.containsKey("http-equiv")) {
final String value = tagopts.getProperty("http-equiv");
if (value.equalsIgnoreCase("Content-Type")) {
// parse lines like <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
final String contentType = tagopts.getProperty("content","");
this.detectedCharset = extractCharsetFromMimetypeHeader(contentType);
if (this.detectedCharset != null && this.detectedCharset.length() > 0) {
this.charsetChanged = true;
} else if (tagopts.containsKey("charset")) {
// sometimes the charset property is configured as extra attribut. try it ...
this.detectedCharset = tagopts.getProperty("charset");
this.charsetChanged = true;
}
}
}
}
}
public void scrapeTag1(final String tagname, final Properties tagopts, final char[] text) {
if (tagname == null || tagname.length() == 0) return;
if (tagname.equalsIgnoreCase("head")) {
this.endOfHead = true;
}
}
public String detectCharset() throws IOException {
this.mode = MODE_PRESCAN;
// loop until we have detected the header element or the charset data
int c;
while ((c = this.reader.read())!= -1) {
this.writer.write(c);
if (this.charsetChanged) break; // thats enough
}
// free writer
this.writer = null;
// don't close writer here, otherwise it will shutdown our source stream
// reset the buffer if not already done
if (this.mode != MODE_PRESCAN_FINISHED) {
this.mode++;
this.bufferedIn.reset();
}
// return scanning result
return (this.charsetChanged) ? this.detectedCharset : null;
}
public int read() throws IOException {
// mode 0 is called from within the detectCharset function
if (this.mode == MODE_PRESCAN) {
if (this.endOfHead || this.charsetChanged || this.preRead >= preBufferSize - 1) {
return -1;
}
this.preRead++;
}
return this.bufferedIn.read();
}
}
| true | true | public htmlFilterInputStream(
final InputStream inStream,
final String inputStreamCharset,
final yacyURL rooturl,
final htmlFilterTransformer transformer,
final boolean passbyIfBinarySuspect
) {
// create a input stream for buffereing
this.bufferedIn = new BufferedInputStream(inStream,(int) preBufferSize);
this.bufferedIn.mark((int) preBufferSize);
final htmlFilterContentScraper scraper = new htmlFilterContentScraper(rooturl);
//scraper.registerHtmlFilterEventListener(this);
try {
this.reader = new InputStreamReader(this,inputStreamCharset);
} catch (UnsupportedEncodingException e) {
try {
this.reader = new InputStreamReader(this, "UTF-8");
} catch (UnsupportedEncodingException e1) {
// how is that possible?
this.reader = new InputStreamReader(this);
}
}
this.writer = new htmlFilterWriter(null,null,scraper,transformer,passbyIfBinarySuspect);
}
| public htmlFilterInputStream(
final InputStream inStream,
final String inputStreamCharset,
final yacyURL rooturl,
final htmlFilterTransformer transformer,
final boolean passbyIfBinarySuspect
) {
// create a input stream for buffereing
this.bufferedIn = new BufferedInputStream(inStream,(int) preBufferSize);
this.bufferedIn.mark((int) preBufferSize);
final htmlFilterContentScraper scraper = new htmlFilterContentScraper(rooturl);
scraper.registerHtmlFilterEventListener(this);
try {
this.reader = new InputStreamReader(this,inputStreamCharset);
} catch (UnsupportedEncodingException e) {
try {
this.reader = new InputStreamReader(this, "UTF-8");
} catch (UnsupportedEncodingException e1) {
// how is that possible?
this.reader = new InputStreamReader(this);
}
}
this.writer = new htmlFilterWriter(null,null,scraper,transformer,passbyIfBinarySuspect);
}
|
diff --git a/src/org/netbeans/modules/php/wordpress/WordPressPhpModuleExtender.java b/src/org/netbeans/modules/php/wordpress/WordPressPhpModuleExtender.java
index 8cd89b4..58a53f7 100644
--- a/src/org/netbeans/modules/php/wordpress/WordPressPhpModuleExtender.java
+++ b/src/org/netbeans/modules/php/wordpress/WordPressPhpModuleExtender.java
@@ -1,447 +1,449 @@
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2013 Oracle and/or its affiliates. All rights reserved.
*
* Oracle and Java are registered trademarks of Oracle and/or its affiliates.
* Other names may be trademarks of their respective owners.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*
* Contributor(s):
*
* Portions Copyrighted 2013 Sun Microsystems, Inc.
*/
package org.netbeans.modules.php.wordpress;
import java.awt.Component;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import javax.net.ssl.HttpsURLConnection;
import javax.swing.JComponent;
import javax.swing.event.ChangeListener;
import org.netbeans.modules.php.api.executable.InvalidPhpExecutableException;
import org.netbeans.modules.php.api.phpmodule.PhpModule;
import org.netbeans.modules.php.api.util.FileUtils;
import org.netbeans.modules.php.api.util.FileUtils.ZipEntryFilter;
import org.netbeans.modules.php.api.util.StringUtils;
import org.netbeans.modules.php.spi.framework.PhpModuleExtender;
import org.netbeans.modules.php.wordpress.commands.WordPressCli;
import org.netbeans.modules.php.wordpress.preferences.WordPressPreferences;
import org.netbeans.modules.php.wordpress.ui.options.WordPressOptions;
import org.netbeans.modules.php.wordpress.ui.wizards.NewProjectConfigurationPanel;
import org.netbeans.modules.php.wordpress.util.Charset;
import org.netbeans.modules.php.wordpress.util.NetUtils;
import org.netbeans.modules.php.wordpress.util.WPFileUtils;
import org.netbeans.modules.php.wordpress.util.WPZipEntryFilter;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileUtil;
import org.openide.util.Exceptions;
import org.openide.util.HelpCtx;
/**
*
* @author junichi11
*/
public class WordPressPhpModuleExtender extends PhpModuleExtender {
private static final String HTTPS_API_WORDPRESS_ORG_SECRET_KEY = "https://api.wordpress.org/secret-key/1.1/salt/"; // NOI18N
private static final String DEFINE_PATTERN = "^define\\('(.*)', *.*\\);$"; // NOI18N
private static final String DEFINE_FORMAT_PATTERN = "define('%s', '%s');"; // NOI18N
private static final String WP_CONFIG_PHP = "wp-config.php"; // NOI18N
private NewProjectConfigurationPanel panel;
private static final String WORDPRESS = "wordpress"; // NOI18N
private static final String WP_DL_URL_DEFAULT = "http://wordpress.org/latest.zip"; // NOI18N
private static final String WP_DL_URL_FORMAT = "http://%s.wordpress.org/latest-%s.zip"; // NOI18N
private static final String DB_NAME = "DB_NAME"; // NOI18N
private static final String DB_USER = "DB_USER"; // NOI18N
private static final String DB_PASSWORD = "DB_PASSWORD"; // NOI18N
private static final String DB_HOST = "DB_HOST"; // NOI18N
private static final String DB_CHARSET = "DB_CHARSET"; // NOI18N
private static final String DB_COLLATE = "DB_COLLATE"; // NOI18N
private static final Set<String> SECRET_KEYS = new HashSet<String>();
private static final Set<String> CONFIG_KEYS = new HashSet<String>();
private static final Map<String, String> CONFIG_MAP = new HashMap<String, String>();
private boolean isInternetReachable = true;
private static final Logger LOGGER = Logger.getLogger(WordPressPhpModuleExtender.class.getName());
static {
SECRET_KEYS.add("AUTH_KEY"); // NOI18N
SECRET_KEYS.add("SECURE_AUTH_KEY"); // NOI18N
SECRET_KEYS.add("LOGGED_IN_KEY"); // NOI18N
SECRET_KEYS.add("NONCE_KEY"); // NOI18N
SECRET_KEYS.add("AUTH_SALT"); // NOI18N
SECRET_KEYS.add("SECURE_AUTH_SALT"); // NOI18N
SECRET_KEYS.add("LOGGED_IN_SALT"); // NOI18N
SECRET_KEYS.add("NONCE_SALT"); // NOI18N
CONFIG_KEYS.add(DB_NAME);
CONFIG_KEYS.add(DB_USER);
CONFIG_KEYS.add(DB_PASSWORD);
CONFIG_KEYS.add(DB_HOST);
CONFIG_KEYS.add(DB_CHARSET);
CONFIG_KEYS.add(DB_COLLATE);
}
@Override
public void addChangeListener(ChangeListener cl) {
}
@Override
public void removeChangeListener(ChangeListener cl) {
}
@Override
public JComponent getComponent() {
return getPanel();
}
@Override
public HelpCtx getHelp() {
return null;
}
@Override
public boolean isValid() {
String url = panel.getUrlLabel();
String localFile = panel.getLocalFileLabel();
if (!isInternetReachable || url.isEmpty()) {
if (localFile.isEmpty()) {
Component[] components = panel.getComponents();
for (Component component : components) {
component.setEnabled(false);
}
return false;
}
}
return true;
}
@Override
public String getErrorMessage() {
return null;
}
@Override
public String getWarningMessage() {
return null;
}
/**
* Unzip from url. In case of default, download from
* http://wordpress.org/latest.zip.
*
* @see <a href="http://wordpress.org/">WordPress</a>
* @param pm
* @return file set
* @throws
* org.netbeans.modules.php.spi.framework.PhpModuleExtender.ExtendingException
*/
@Override
public Set<FileObject> extend(PhpModule pm) throws ExtendingException {
panel.setAllEnabled(panel, false);
panel.setAllEnabled(panel.getWpConfigPanel(), false);
FileObject sourceDirectory = pm.getSourceDirectory();
if (panel.useUrl()) {
// url
String urlPath = panel.getUrlLabel();
try {
// unzip
WPFileUtils.unzip(urlPath, FileUtil.toFile(sourceDirectory), new WPZipEntryFilter(panel.getUnzipStatusTextField()));
} catch (MalformedURLException ex) {
Exceptions.printStackTrace(ex);
} catch (IOException ex) {
throw new ExtendingException(ex.getLocalizedMessage());
}
} else if (panel.useLocalFile()) {
// local file
String path = panel.getLocalFileLabel();
try {
FileUtils.unzip(path, FileUtil.toFile(sourceDirectory), new ZipEntryFilterImpl());
} catch (IOException ex) {
throw new ExtendingException(ex.getLocalizedMessage());
}
} else if (panel.useWpCli()) {
try {
// params
ArrayList<String> params = new ArrayList<String>(2);
WordPressOptions options = WordPressOptions.getInstance();
String locale = options.getWpCliDownloadLocale();
if (!StringUtils.isEmpty(locale)) {
params.add(String.format(WordPressCli.LOCALE_PARAM, locale));
}
String version = options.getWpCliDownloadVersion();
if (!StringUtils.isEmpty(version)) {
params.add(String.format(WordPressCli.VERSION_PARAM, version));
}
// run
WordPressCli wpCli = WordPressCli.getDefault(false);
Future<Integer> result = wpCli.download(pm, params);
if (result != null) {
result.get();
}
} catch (InvalidPhpExecutableException ex) {
throw new ExtendingException(ex.getLocalizedMessage());
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
} catch (ExecutionException ex) {
throw new ExtendingException(ex.getLocalizedMessage());
}
+ // #18
+ sourceDirectory.refresh(true);
} else {
// do nothing
return Collections.emptySet();
}
// set format
if (panel.useFormatOption()) {
WordPressPreferences.setWordPressFormat(pm);
}
Set<FileObject> files = new HashSet<FileObject>();
if (sourceDirectory != null) {
// create wp-config.php
if (panel.isSelectedCreateConfig()) {
setConfigMap();
createWpConfig(sourceDirectory.getFileObject("wp-config-sample.php")); // NOI18N
}
// set files to open
FileObject config = sourceDirectory.getFileObject(WP_CONFIG_PHP); // NOI18N
if (config != null) {
files.add(config);
}
FileObject index = sourceDirectory.getFileObject("index.php"); // NOI18N
if (index != null) {
files.add(index);
}
}
return files;
}
/**
* Get download url. If url is set to option panel or found url of user
* language, return it. Otherwise return default url.
*
* @see <a href="http://wordpress.org/latest.zip">WordPress Download</a>
* @return download url
*/
private String getDownloadUrl() {
String downloadUrl = WordPressOptions.getInstance().getDownloadUrl();
if (downloadUrl != null && !downloadUrl.isEmpty()) {
return downloadUrl;
}
Locale locale = Locale.getDefault();
String language = locale.getLanguage();
String urlPath = WP_DL_URL_DEFAULT;
if (language != null && !language.isEmpty()) {
if (!language.equals("en")) { // NOI18N
urlPath = String.format(WP_DL_URL_FORMAT, language, language);
}
}
try {
URL check = new URL(urlPath);
URLConnection connection = check.openConnection();
connection.connect();
} catch (MalformedURLException ex) {
Exceptions.printStackTrace(ex);
} catch (IOException ex) {
urlPath = WP_DL_URL_DEFAULT;
}
return urlPath;
}
private void createWpConfig(FileObject sample) {
if (sample == null) {
return;
}
PrintWriter pw = null;
List<String> lines = null;
try {
lines = sample.asLines(Charset.UTF8);
FileObject parent = sample.getParent();
OutputStream outpuStream = parent.createAndOpen(WP_CONFIG_PHP);
pw = new PrintWriter(new OutputStreamWriter(outpuStream, Charset.UTF8));
} catch (IOException ex) {
Exceptions.printStackTrace(ex);
}
if (pw == null) {
return;
}
// write
try {
Pattern pattern = Pattern.compile(DEFINE_PATTERN);
boolean isSecret = false;
for (String line : lines) {
Matcher matcher = pattern.matcher(line);
if (matcher.find()) {
String group = matcher.group(1);
if (CONFIG_KEYS.contains(group)) {
pw.println(String.format(DEFINE_FORMAT_PATTERN, group, CONFIG_MAP.get(group)));
continue;
}
if (SECRET_KEYS.contains(group) && isInternetReachable) {
isSecret = true;
continue;
}
}
if (isSecret) {
for (String key : getSecretKey()) {
pw.println(key);
}
isSecret = false;
}
pw.println(line);
}
} finally {
pw.close();
}
}
/**
* Get local file. can set only zip file.
*
* @return local zip file
*/
private String getLocalFile() {
return WordPressOptions.getInstance().getLocalFilePath();
}
/**
* Get secret keys with wordpress api.
*
* @see <a href="https://api.wordpress.org/secret-key/1.1/salt/">WordPress
* API</a>
* @return
*/
private List<String> getSecretKey() {
List<String> keys = new ArrayList<String>();
try {
URL url = new URL(HTTPS_API_WORDPRESS_ORG_SECRET_KEY);
URLConnection connection = url.openConnection();
if (connection instanceof HttpsURLConnection) {
HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;
BufferedReader reader = new BufferedReader(new InputStreamReader(httpsConnection.getInputStream(), Charset.UTF8)); // NOI18N
try {
String line = null;
while ((line = reader.readLine()) != null) {
keys.add(line);
}
} finally {
reader.close();
}
}
} catch (MalformedURLException ex) {
Exceptions.printStackTrace(ex);
} catch (IOException ex) {
LOGGER.log(Level.WARNING, null, ex);
}
return keys;
}
private synchronized void setConfigMap() {
CONFIG_MAP.put(DB_NAME, panel.getDbName());
CONFIG_MAP.put(DB_USER, panel.getDbUser());
CONFIG_MAP.put(DB_PASSWORD, panel.getDbPassword());
CONFIG_MAP.put(DB_HOST, panel.getDbHost());
CONFIG_MAP.put(DB_CHARSET, panel.getDbCharset());
CONFIG_MAP.put(DB_COLLATE, panel.getDbCollate());
}
/**
* Get panel
*
* @return
*/
private synchronized NewProjectConfigurationPanel getPanel() {
if (panel == null) {
panel = new NewProjectConfigurationPanel();
String url = getDownloadUrl();
if (!NetUtils.isInternetReachable(url)) {
isInternetReachable = false;
panel.setEnabledUrl(false);
}
panel.setUrlLabel(url);
panel.setLocalFileLabel(getLocalFile());
}
return panel;
}
private static class ZipEntryFilterImpl implements ZipEntryFilter {
public ZipEntryFilterImpl() {
}
@Override
public boolean accept(ZipEntry ze) {
if (ze.isDirectory() && ze.getName().equals(WORDPRESS)) {
return false;
}
return true;
}
@Override
public String getName(ZipEntry ze) {
String name = ze.getName();
if (name.startsWith(WORDPRESS)) {
name = name.replaceFirst(WORDPRESS, ""); // NOI18N
}
return name;
}
}
}
| true | true | public Set<FileObject> extend(PhpModule pm) throws ExtendingException {
panel.setAllEnabled(panel, false);
panel.setAllEnabled(panel.getWpConfigPanel(), false);
FileObject sourceDirectory = pm.getSourceDirectory();
if (panel.useUrl()) {
// url
String urlPath = panel.getUrlLabel();
try {
// unzip
WPFileUtils.unzip(urlPath, FileUtil.toFile(sourceDirectory), new WPZipEntryFilter(panel.getUnzipStatusTextField()));
} catch (MalformedURLException ex) {
Exceptions.printStackTrace(ex);
} catch (IOException ex) {
throw new ExtendingException(ex.getLocalizedMessage());
}
} else if (panel.useLocalFile()) {
// local file
String path = panel.getLocalFileLabel();
try {
FileUtils.unzip(path, FileUtil.toFile(sourceDirectory), new ZipEntryFilterImpl());
} catch (IOException ex) {
throw new ExtendingException(ex.getLocalizedMessage());
}
} else if (panel.useWpCli()) {
try {
// params
ArrayList<String> params = new ArrayList<String>(2);
WordPressOptions options = WordPressOptions.getInstance();
String locale = options.getWpCliDownloadLocale();
if (!StringUtils.isEmpty(locale)) {
params.add(String.format(WordPressCli.LOCALE_PARAM, locale));
}
String version = options.getWpCliDownloadVersion();
if (!StringUtils.isEmpty(version)) {
params.add(String.format(WordPressCli.VERSION_PARAM, version));
}
// run
WordPressCli wpCli = WordPressCli.getDefault(false);
Future<Integer> result = wpCli.download(pm, params);
if (result != null) {
result.get();
}
} catch (InvalidPhpExecutableException ex) {
throw new ExtendingException(ex.getLocalizedMessage());
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
} catch (ExecutionException ex) {
throw new ExtendingException(ex.getLocalizedMessage());
}
} else {
// do nothing
return Collections.emptySet();
}
// set format
if (panel.useFormatOption()) {
WordPressPreferences.setWordPressFormat(pm);
}
Set<FileObject> files = new HashSet<FileObject>();
if (sourceDirectory != null) {
// create wp-config.php
if (panel.isSelectedCreateConfig()) {
setConfigMap();
createWpConfig(sourceDirectory.getFileObject("wp-config-sample.php")); // NOI18N
}
// set files to open
FileObject config = sourceDirectory.getFileObject(WP_CONFIG_PHP); // NOI18N
if (config != null) {
files.add(config);
}
FileObject index = sourceDirectory.getFileObject("index.php"); // NOI18N
if (index != null) {
files.add(index);
}
}
return files;
}
| public Set<FileObject> extend(PhpModule pm) throws ExtendingException {
panel.setAllEnabled(panel, false);
panel.setAllEnabled(panel.getWpConfigPanel(), false);
FileObject sourceDirectory = pm.getSourceDirectory();
if (panel.useUrl()) {
// url
String urlPath = panel.getUrlLabel();
try {
// unzip
WPFileUtils.unzip(urlPath, FileUtil.toFile(sourceDirectory), new WPZipEntryFilter(panel.getUnzipStatusTextField()));
} catch (MalformedURLException ex) {
Exceptions.printStackTrace(ex);
} catch (IOException ex) {
throw new ExtendingException(ex.getLocalizedMessage());
}
} else if (panel.useLocalFile()) {
// local file
String path = panel.getLocalFileLabel();
try {
FileUtils.unzip(path, FileUtil.toFile(sourceDirectory), new ZipEntryFilterImpl());
} catch (IOException ex) {
throw new ExtendingException(ex.getLocalizedMessage());
}
} else if (panel.useWpCli()) {
try {
// params
ArrayList<String> params = new ArrayList<String>(2);
WordPressOptions options = WordPressOptions.getInstance();
String locale = options.getWpCliDownloadLocale();
if (!StringUtils.isEmpty(locale)) {
params.add(String.format(WordPressCli.LOCALE_PARAM, locale));
}
String version = options.getWpCliDownloadVersion();
if (!StringUtils.isEmpty(version)) {
params.add(String.format(WordPressCli.VERSION_PARAM, version));
}
// run
WordPressCli wpCli = WordPressCli.getDefault(false);
Future<Integer> result = wpCli.download(pm, params);
if (result != null) {
result.get();
}
} catch (InvalidPhpExecutableException ex) {
throw new ExtendingException(ex.getLocalizedMessage());
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
} catch (ExecutionException ex) {
throw new ExtendingException(ex.getLocalizedMessage());
}
// #18
sourceDirectory.refresh(true);
} else {
// do nothing
return Collections.emptySet();
}
// set format
if (panel.useFormatOption()) {
WordPressPreferences.setWordPressFormat(pm);
}
Set<FileObject> files = new HashSet<FileObject>();
if (sourceDirectory != null) {
// create wp-config.php
if (panel.isSelectedCreateConfig()) {
setConfigMap();
createWpConfig(sourceDirectory.getFileObject("wp-config-sample.php")); // NOI18N
}
// set files to open
FileObject config = sourceDirectory.getFileObject(WP_CONFIG_PHP); // NOI18N
if (config != null) {
files.add(config);
}
FileObject index = sourceDirectory.getFileObject("index.php"); // NOI18N
if (index != null) {
files.add(index);
}
}
return files;
}
|
diff --git a/bundles/org.eclipse.team.core/src/org/eclipse/team/core/mapping/provider/SynchronizationContext.java b/bundles/org.eclipse.team.core/src/org/eclipse/team/core/mapping/provider/SynchronizationContext.java
index b511ea1b8..586804cdb 100644
--- a/bundles/org.eclipse.team.core/src/org/eclipse/team/core/mapping/provider/SynchronizationContext.java
+++ b/bundles/org.eclipse.team.core/src/org/eclipse/team/core/mapping/provider/SynchronizationContext.java
@@ -1,115 +1,115 @@
/*******************************************************************************
* Copyright (c) 2000, 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
*******************************************************************************/
package org.eclipse.team.core.mapping.provider;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.mapping.ResourceMapping;
import org.eclipse.core.resources.mapping.ResourceTraversal;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.team.core.ICache;
import org.eclipse.team.core.mapping.*;
import org.eclipse.team.internal.core.Cache;
import org.eclipse.team.internal.core.Policy;
/**
* Abstract implementation of the {@link ISynchronizationContext} interface.
* This class can be subclassed by clients.
*
* @see ISynchronizationContext
* @since 3.2
*/
public abstract class SynchronizationContext implements ISynchronizationContext {
private final int type;
private final IResourceDiffTree diffTree;
private Cache cache;
private final ISynchronizationScopeManager manager;
/**
* Create a synchronization context.
* @param manager the manager that defines the scope of the synchronization
* @param type the type of synchronization (ONE_WAY or TWO_WAY)
* @param diffTree the sync info tree that contains all out-of-sync resources
*/
protected SynchronizationContext(ISynchronizationScopeManager manager, int type, IResourceDiffTree diffTree) {
this.manager = manager;
this.type = type;
this.diffTree = diffTree;
}
/**
* {@inheritDoc}
*/
public ISynchronizationScope getScope() {
return getScopeManager().getScope();
}
/**
* Return the scope manager for the scope of this context.
* @return the scope manager for the scope of this context
*/
public ISynchronizationScopeManager getScopeManager() {
return manager;
}
/**
* {@inheritDoc}
*/
public int getType() {
return type;
}
/**
* {@inheritDoc}
*/
public void dispose() {
if (cache != null) {
cache.dispose();
}
manager.dispose();
}
/**
* {@inheritDoc}
*/
public synchronized ICache getCache() {
if (cache == null) {
cache = new Cache();
}
return cache;
}
/**
* {@inheritDoc}
*/
public IResourceDiffTree getDiffTree() {
return diffTree;
}
/**
* {@inheritDoc}
*/
public void refresh(ResourceMapping[] mappings, IProgressMonitor monitor) throws CoreException {
monitor.beginTask(null, 100);
- SynchronizationScopeManager manager = null; //getScopeManager();
+ ISynchronizationScopeManager manager = getScopeManager();
if (manager == null) {
// The scope manager is missing so just refresh everything
refresh(getScope().getTraversals(), IResource.NONE, Policy.subMonitorFor(monitor, 50));
} else {
ResourceTraversal[] traversals = manager.refresh(mappings, Policy.subMonitorFor(monitor, 50));
if (traversals.length > 0)
refresh(traversals, IResource.NONE, Policy.subMonitorFor(monitor, 50));
}
monitor.done();
}
}
| true | true | public void refresh(ResourceMapping[] mappings, IProgressMonitor monitor) throws CoreException {
monitor.beginTask(null, 100);
SynchronizationScopeManager manager = null; //getScopeManager();
if (manager == null) {
// The scope manager is missing so just refresh everything
refresh(getScope().getTraversals(), IResource.NONE, Policy.subMonitorFor(monitor, 50));
} else {
ResourceTraversal[] traversals = manager.refresh(mappings, Policy.subMonitorFor(monitor, 50));
if (traversals.length > 0)
refresh(traversals, IResource.NONE, Policy.subMonitorFor(monitor, 50));
}
monitor.done();
}
| public void refresh(ResourceMapping[] mappings, IProgressMonitor monitor) throws CoreException {
monitor.beginTask(null, 100);
ISynchronizationScopeManager manager = getScopeManager();
if (manager == null) {
// The scope manager is missing so just refresh everything
refresh(getScope().getTraversals(), IResource.NONE, Policy.subMonitorFor(monitor, 50));
} else {
ResourceTraversal[] traversals = manager.refresh(mappings, Policy.subMonitorFor(monitor, 50));
if (traversals.length > 0)
refresh(traversals, IResource.NONE, Policy.subMonitorFor(monitor, 50));
}
monitor.done();
}
|
diff --git a/src/me/ellbristow/greylistVote/greylistVote.java b/src/me/ellbristow/greylistVote/greylistVote.java
index 0f76dde..02a603c 100644
--- a/src/me/ellbristow/greylistVote/greylistVote.java
+++ b/src/me/ellbristow/greylistVote/greylistVote.java
@@ -1,704 +1,704 @@
package me.ellbristow.greylistVote;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import org.bukkit.ChatColor;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.permissions.PermissionAttachment;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
public class greylistVote extends JavaPlugin {
public static greylistVote plugin;
public final greyBlockListener blockListener = new greyBlockListener(this);
public final greyPlayerListener loginListener = new greyPlayerListener(this);
protected FileConfiguration config;
public FileConfiguration usersConfig = null;
private File usersFile = null;
protected int approvalVotes;
protected boolean noPVP;
private boolean allowApprovedVote;
@Override
public void onDisable() {
}
@Override
public void onEnable() {
PluginManager pm = getServer().getPluginManager();
pm.registerEvents(blockListener, this);
pm.registerEvents(loginListener, this);
this.config = this.getConfig();
approvalVotes = this.config.getInt("required_votes", 2);
this.config.set("required_votes", approvalVotes);
noPVP = this.config.getBoolean("no_pvp", true);
this.config.set("no_pvp", noPVP);
allowApprovedVote = this.config.getBoolean("allow_all_approved_to_vote", false);
this.config.set("allow_all_approved_to_vote", allowApprovedVote);
this.saveConfig();
this.usersConfig = this.getUsersConfig();
}
@Override
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
if (commandLabel.equalsIgnoreCase("glv")) {
if (args.length == 0) {
PluginDescriptionFile pdfFile = this.getDescription();
sender.sendMessage(ChatColor.GOLD + pdfFile.getName() + " version " + pdfFile.getVersion() + " by " + pdfFile.getAuthors());
sender.sendMessage(ChatColor.GOLD + "Commands: {optional} [required]");
sender.sendMessage(ChatColor.GOLD + " /glv " + ChatColor.GRAY + ": View all GreylistVote commands");
sender.sendMessage(ChatColor.GOLD + " /greylist [player] || /gl [player] || /trust Player " + ChatColor.GRAY + ":");
sender.sendMessage(ChatColor.GRAY + " Increase player's reputation");
sender.sendMessage(ChatColor.GOLD + " /griefer [player] " + ChatColor.GRAY + ":");
sender.sendMessage(ChatColor.GRAY + " Reduce player's reputation");
sender.sendMessage(ChatColor.GOLD + " /votelist {player} || /glvlist {player} " + ChatColor.GRAY + ":");
sender.sendMessage(ChatColor.GRAY + " View your (or player's) reputation");
if (sender.hasPermission("greylistvote.admin")) {
sender.sendMessage(ChatColor.RED + "Admin Commands:");
sender.sendMessage(ChatColor.GOLD + " /glv setrep [req. rep] " + ChatColor.GRAY + ": Set required reputation");
sender.sendMessage(ChatColor.GOLD + " /glv toggle [pvp|approvedvote] " + ChatColor.GRAY + ": Toggle true/false config options");
sender.sendMessage(ChatColor.GOLD + " /glv clearserver [player] " + ChatColor.GRAY + ": Remove player's Server votes");
sender.sendMessage(ChatColor.GOLD + " /glv clearall [player] " + ChatColor.GRAY + ": Remove all player's votes");
}
return true;
}
else if (args.length == 2) {
if (!sender.hasPermission("greylistvote.admin")) {
sender.sendMessage(ChatColor.RED + "You do not have permission to do that!");
return false;
}
if (args[0].equalsIgnoreCase("setrep")) {
try {
approvalVotes = Integer.parseInt(args[1]);
}
catch(NumberFormatException nfe) {
// Failed. Number not an integer
sender.sendMessage(ChatColor.RED + "[req. votes] must be a number!" );
return false;
}
this.config.set("required_votes", approvalVotes);
this.saveConfig();
sender.sendMessage(ChatColor.GOLD + "Reputation requirement now set to " + ChatColor.WHITE + args[1]);
sender.sendMessage(ChatColor.GOLD + "Player approval will be updated on next login.");
return true;
}
else if (args[0].equalsIgnoreCase("clearserver")) {
OfflinePlayer target = getServer().getOfflinePlayer(args[1]);
if (!target.hasPlayedBefore()) {
sender.sendMessage(ChatColor.RED + "Player " + ChatColor.WHITE + args[0] + ChatColor.RED + "not found!");
return true;
}
String griefList = this.usersConfig.getString(target.getName().toLowerCase() + ".griefer", null);
String voteList = this.usersConfig.getString(target.getName().toLowerCase() + ".votes", null);
String[] voteArray;
String[] griefArray;
if (griefList == null && voteList == null) {
sender.sendMessage(ChatColor.RED + "Player " + ChatColor.WHITE + target.getName() + ChatColor.RED + " does not have any votes!");
return true;
}
String newVoteList = null;
String[] newVoteArray = null;
if (voteList != null) {
voteArray = voteList.split(",");
for (String vote : voteArray) {
if (!vote.equals("Server")) {
if (newVoteList != null) {
newVoteList += "," + vote;
} else {
newVoteList = vote;
}
}
}
if (newVoteList != null) {
newVoteArray = newVoteList.split(",");
}
usersConfig.set(target.getName().toLowerCase() + ".votes", newVoteList);
}
String newGriefList = null;
String[] newGriefArray = null;
if (griefList != null) {
griefArray = griefList.split(",");
for (String vote : griefArray) {
if (!vote.equals("Server")) {
if (newGriefList != null) {
newGriefList += "," + vote;
} else {
newGriefList = vote;
}
}
}
if (newGriefList != null) {
newGriefArray = newGriefList.split(",");
}
usersConfig.set(target.getName().toLowerCase() + ".griefer", newGriefList);
}
saveUsersConfig();
int rep = 0;
if (newVoteList != null) {
rep += newVoteArray.length;
}
if (newGriefList != null) {
rep -= newGriefArray.length;
}
sender.sendMessage(ChatColor.GOLD + "'Server' votes removed from " + ChatColor.WHITE + target.getName());
if (target.isOnline()) {
target.getPlayer().sendMessage(ChatColor.GOLD + "Your Server Approval/Black-Ball votes were removed!");
if (rep >= approvalVotes && !target.getPlayer().hasPermission("greylistvote.build") && !target.getPlayer().hasPermission("greylistvote.approved")) {
setApproved(target.getPlayer());
}
else if (rep < approvalVotes && target.getPlayer().hasPermission("greylistvote.build") && !target.getPlayer().hasPermission("greylistvote.approved")) {
setGriefer(target.getPlayer());
}
} else {
Player[] onlinePlayers = getServer().getOnlinePlayers();
for (Player chatPlayer : onlinePlayers) {
if (!chatPlayer.getName().equals(sender.getName())) {
chatPlayer.sendMessage(target.getName() + ChatColor.GOLD + "'s reputation has been reset to 0!");
}
}
}
this.saveUsersConfig();
return true;
}
else if (args[0].equalsIgnoreCase("clearall")) {
OfflinePlayer target = getServer().getOfflinePlayer(args[1]);
if (!target.hasPlayedBefore()) {
sender.sendMessage(ChatColor.RED + "Player " + ChatColor.WHITE + args[0] + ChatColor.RED + "not found!");
return true;
}
String griefList = this.usersConfig.getString(target.getName().toLowerCase() + ".griefer", null);
String voteList = this.usersConfig.getString(target.getName().toLowerCase() + ".votes", null);
if (griefList == null && voteList == null) {
sender.sendMessage(ChatColor.RED + "Player " + ChatColor.WHITE + target.getName() + ChatColor.RED + " does not have any votes!");
return true;
}
usersConfig.set(target.getName().toLowerCase() + ".votes", null);
usersConfig.set(target.getName().toLowerCase() + ".griefer", null);
sender.sendMessage(ChatColor.GOLD + "ALL votes removed from " + ChatColor.WHITE + target.getName());
if (target.isOnline()) {
target.getPlayer().sendMessage(ChatColor.RED + "Your reputation was reset to 0!");
if (0 >= approvalVotes && !target.getPlayer().hasPermission("greylistvote.build") && !target.getPlayer().hasPermission("greylistvote.approved")) {
setApproved(target.getPlayer());
}
else if (0 < approvalVotes && target.getPlayer().hasPermission("greylistvote.build") && !target.getPlayer().hasPermission("greylistvote.approved")) {
setGriefer(target.getPlayer());
}
} else {
Player[] onlinePlayers = getServer().getOnlinePlayers();
for (Player chatPlayer : onlinePlayers) {
if (!chatPlayer.getName().equals(sender.getName())) {
chatPlayer.sendMessage(target.getName() + ChatColor.GOLD + "'s reputation has been reset to 0!");
}
}
}
this.saveUsersConfig();
return true;
} else if (args[0].equalsIgnoreCase("toggle")) {
if (args[1].equalsIgnoreCase("pvp")) {
if (noPVP) {
noPVP = false;
sender.sendMessage(ChatColor.GOLD + "Unapproved players are no longer protected against PVP.");
} else {
noPVP = true;
sender.sendMessage(ChatColor.GOLD + "Unapproved players are now protected against PVP.");
}
config.set("no_pvp", noPVP);
saveConfig();
} else if (args[1].equalsIgnoreCase("approvedvote")) {
if (allowApprovedVote) {
allowApprovedVote = false;
sender.sendMessage(ChatColor.GOLD + "Only player with permission may now vote!");
} else {
allowApprovedVote = true;
sender.sendMessage(ChatColor.GOLD + "All approved players may now vote!");
}
config.set("allow_all_approved_to_vote", allowApprovedVote);
saveConfig();
} else {
sender.sendMessage(ChatColor.RED + "Toggle option not recognised!");
sender.sendMessage(ChatColor.RED + "Allowed toggles: pvp, approvedvote");
return false;
}
}
else {
sender.sendMessage(ChatColor.RED + "Command not recognised!");
return false;
}
}
sender.sendMessage(ChatColor.RED + "Command not recognised!");
return false;
}
else if (commandLabel.equalsIgnoreCase("greylist") || commandLabel.equalsIgnoreCase("gl") || commandLabel.equalsIgnoreCase("trust")) {
if (args.length != 1) {
// No player specified or too many arguments
return false;
}
else {
- if (!sender.hasPermission("greylistvote.vote") && !(allowApprovedVote && sender.hasPermission("greylistvote.approved"))) {
+ if (!sender.hasPermission("greylistvote.vote") && !(allowApprovedVote && sender.hasPermission("greylistvote.build"))) {
sender.sendMessage(ChatColor.RED + "You do not have permission to vote!");
return true;
}
OfflinePlayer target = getServer().getOfflinePlayer(args[0]);
if (!target.hasPlayedBefore() && !target.isOnline()) {
// Player not online
sender.sendMessage(args[0] + ChatColor.RED + " not found!");
return false;
}
if (!(sender instanceof Player)) {
// Voter is the console
this.usersConfig.set(target.getName().toLowerCase() + ".votes", "Server");
this.usersConfig.set(target.getName().toLowerCase() + ".griefer", null);
sender.sendMessage(target.getName() + ChatColor.GOLD + "'s reputation was set to " + approvalVotes + "!");
Player[] onlinePlayers = getServer().getOnlinePlayers();
for (Player chatPlayer : onlinePlayers) {
if (!chatPlayer.getName().equals(target.getName())) {
chatPlayer.sendMessage(target.getName() + ChatColor.GOLD + "'s reputation was set to " + approvalVotes + " by the Server!");
}
else {
target.getPlayer().sendMessage(ChatColor.GOLD + "Your reputation was set to " + approvalVotes + " by the Server!");
}
}
if (target.isOnline() && !target.getPlayer().hasPermission("greylistvote.build") && !target.getPlayer().hasPermission("greylistvote.approved")) {
this.setApproved(target.getPlayer());
}
this.saveUsersConfig();
return true;
}
if (sender.getName().equalsIgnoreCase(target.getName())) {
// Player voting for self
sender.sendMessage(ChatColor.RED + "You cannot vote for yourself!");
return true;
}
String griefList = this.usersConfig.getString(target.getName().toLowerCase() + ".griefer", null);
String voteList = this.usersConfig.getString(target.getName().toLowerCase() + ".votes", null);
String[] voteArray = null;
String[] griefArray = null;
if (voteList != null) {
voteArray = voteList.split(",");
}
else {
voteList = "";
}
if (griefList != null) {
griefArray = griefList.split(",");
}
boolean found = false;
if (voteArray != null) {
for (String vote : voteArray) {
if (vote.equalsIgnoreCase(sender.getName())) {
found = true;
}
}
}
if (found) {
// Voter has already voted for this target player
sender.sendMessage(ChatColor.RED + "You have already voted for " + ChatColor.WHITE + target.getName());
return true;
}
if (griefArray != null) {
String newGriefList = null;
for (String vote : griefArray) {
if (!vote.equalsIgnoreCase(sender.getName())) {
if (newGriefList != null) {
newGriefList += "," + vote;
} else {
newGriefList = vote;
}
}
}
if (newGriefList != null) {
newGriefList = newGriefList.replaceFirst(",", "");
usersConfig.set(target.getName().toLowerCase() + ".griefer", newGriefList);
griefArray = newGriefList.split(",");
}
else {
griefArray = null;
usersConfig.set(target.getName().toLowerCase() + ".griefer", null);
}
}
sender.sendMessage(ChatColor.GOLD + "You have increased " + ChatColor.WHITE + target.getName() + ChatColor.GOLD + "'s reputation!");
Player[] onlinePlayers = getServer().getOnlinePlayers();
// Tell everyone about the reputation change
for (Player chatPlayer : onlinePlayers) {
if (!chatPlayer.getName().equals(target.getName()) && !chatPlayer.getName().equals(sender.getName())) {
chatPlayer.sendMessage(sender.getName() + ChatColor.GOLD + " increased " + ChatColor.WHITE + target.getName() + ChatColor.GOLD + "'s reputation!");
}
else if (!chatPlayer.getName().equals(sender.getName())) {
chatPlayer.sendMessage(sender.getName() + ChatColor.GREEN + " increased your reputation!");
chatPlayer.sendMessage(ChatColor.GOLD + "Type " + ChatColor.WHITE + "/votelist" + ChatColor.GOLD + " to check your reputation.");
}
}
if (voteList.equals("")) {
voteList = sender.getName();
}
else {
voteList = voteList + "," + sender.getName();
}
this.usersConfig.set(target.getName().toLowerCase() + ".votes", voteList);
voteArray = voteList.split(",");
int rep = 0;
if (voteArray.length != 0) {
rep += voteArray.length;
}
if (griefArray != null) {
if (griefArray.length != 0) {
rep -= griefArray.length;
}
}
if (target.isOnline() && rep >= approvalVotes && !target.getPlayer().hasPermission("greylistvote.build") && !target.getPlayer().hasPermission("greylistvote.approved")) {
// Enough votes received
this.setApproved(target.getPlayer());
}
else if (!target.isOnline() && rep >= approvalVotes) {
for (Player chatPlayer : onlinePlayers) {
if (!chatPlayer.getName().equals(target.getName())) {
chatPlayer.sendMessage(target.getName() + ChatColor.GOLD + "'s reputation has reached " + approvalVotes + "!");
chatPlayer.sendMessage(target.getName() + ChatColor.GOLD + " can now build!");
}
}
}
this.saveUsersConfig();
return true;
}
}
else if (commandLabel.equalsIgnoreCase("griefer") || commandLabel.equalsIgnoreCase("distrust")) {
- if (!sender.hasPermission("greylistvote.griefer") && !(allowApprovedVote && sender.hasPermission("greylistvote.approved"))) {
+ if (!sender.hasPermission("greylistvote.griefer") && !(allowApprovedVote && sender.hasPermission("greylistvote.build"))) {
sender.sendMessage(ChatColor.RED + "You do not have permission to vote!");
return true;
}
if (args.length != 1) {
// No player specified or too many arguments
return false;
}
else {
OfflinePlayer target = getServer().getOfflinePlayer(args[0]);
if (!target.hasPlayedBefore()) {
// Player not online
sender.sendMessage(args[0] + ChatColor.RED + " not found!");
return false;
}
String griefList = this.usersConfig.getString(target.getName().toLowerCase() + ".griefer", null);
String voteList = this.usersConfig.getString(target.getName().toLowerCase() + ".votes", null);
String[] voteArray = null;
String[] griefArray = null;
if (voteList != null) {
voteArray = voteList.split(",");
}
if (griefList != null) {
griefArray = griefList.split(",");
}
else {
griefList = "";
}
if (!(sender instanceof Player)) {
// Voter is the console
this.usersConfig.set(target.getName().toLowerCase() + ".griefer", "Server");
this.usersConfig.set(target.getName().toLowerCase() + ".votes", null);
sender.sendMessage(target.getName() + ChatColor.GOLD + "'s reputation was set to -1!");
Player[] onlinePlayers = getServer().getOnlinePlayers();
for (Player chatPlayer : onlinePlayers) {
if (!chatPlayer.getName().equals(target.getName())) {
chatPlayer.sendMessage(target.getName() + ChatColor.GOLD + "'s reputation was set to -1 by the Server!");
}
else {
target.getPlayer().sendMessage(ChatColor.GOLD + "Your reputation was set to -1 by the Server!");
}
}
if (target.getPlayer().hasPermission("greylistvote.build") && !target.getPlayer().hasPermission("greylistvote.approved")) {
this.setGriefer(target.getPlayer());
}
this.saveUsersConfig();
return true;
}
if (!sender.getName().equals(target.getName())) {
// Player voting for self
sender.sendMessage(ChatColor.RED + "You cannot vote for yourself!");
return true;
}
boolean found = false;
if (griefArray != null) {
for (String vote : griefArray) {
if (vote.equalsIgnoreCase(sender.getName())) {
found = true;
}
}
}
if (found) {
// Voter has already voted for this target player
sender.sendMessage(ChatColor.RED + "You have already voted for " + ChatColor.WHITE + target.getName());
return true;
}
if (voteArray != null) {
String newVoteList = null;
for (String vote : voteArray) {
if (!vote.equalsIgnoreCase(sender.getName())) {
if (newVoteList != null) {
newVoteList += "," + vote;
} else {
newVoteList = vote;
}
}
}
if (newVoteList != null) {
newVoteList = newVoteList.replaceFirst(",", "");
usersConfig.set(target.getName().toLowerCase() + ".votes", newVoteList);
voteArray = newVoteList.split(",");
}
else {
voteArray = null;
usersConfig.set(target.getName().toLowerCase() + ".votes", null);
}
}
sender.sendMessage(ChatColor.GOLD + "You have reduced " + ChatColor.WHITE + target.getName() + ChatColor.GOLD + "'s reputation!");
Player[] onlinePlayers = getServer().getOnlinePlayers();
for (Player chatPlayer : onlinePlayers) {
if (!chatPlayer.getName().equals(target.getName()) && !chatPlayer.getName().equals(sender.getName())) {
chatPlayer.sendMessage(sender.getName() + ChatColor.GOLD + " reduced " + ChatColor.WHITE + target.getName() + ChatColor.GOLD + "'s reputation!");
}
else if (!chatPlayer.getName().equals(sender.getName())) {
chatPlayer.sendMessage(sender.getName() + ChatColor.RED + " reduced your reputation!");
chatPlayer.sendMessage(ChatColor.GOLD + "Type " + ChatColor.WHITE + "/votelist" + ChatColor.GOLD + " to check your reputation.");
}
}
if (griefList.equals("")) {
griefList = sender.getName();
}
else {
griefList = griefList + "," + sender.getName();
}
this.usersConfig.set(target.getName().toLowerCase() + ".griefer", griefList);
griefArray = griefList.split(",");
int rep = 0;
if (voteArray != null) {
rep += voteArray.length;
}
if (griefArray != null) {
rep -= griefArray.length;
}
if (target.isOnline() && rep < approvalVotes && target.getPlayer().hasPermission("greylistvote.build") && !target.getPlayer().hasPermission("greylistvote.approved")) {
// Enough votes received
this.setGriefer(target.getPlayer());
}
else if (!target.isOnline() && rep < approvalVotes) {
for (Player chatPlayer : onlinePlayers) {
if (!chatPlayer.getName().equals(target.getName())) {
chatPlayer.sendMessage(target.getName() + ChatColor.GOLD + "'s reputation has dropped below " + approvalVotes + "!");
}
}
}
this.saveUsersConfig();
return true;
}
}
else if (commandLabel.equalsIgnoreCase("votelist") || commandLabel.equalsIgnoreCase("glvlist") || commandLabel.equalsIgnoreCase("rep")) {
if (args == null || args.length == 0) {
String voteList = this.usersConfig.getString(sender.getName().toLowerCase() + ".votes", null);
String griefList = this.usersConfig.getString(sender.getName().toLowerCase() + ".griefer", null);
if (voteList == null && griefList == null) {
sender.sendMessage(ChatColor.GOLD + "You have not received any votes.");
sender.sendMessage(ChatColor.GOLD + "Current Reputation: " + ChatColor.WHITE + "0");
sender.sendMessage(ChatColor.GOLD + "Required Reputation: " + ChatColor.WHITE + approvalVotes);
}
else {
sender.sendMessage(ChatColor.GOLD + "You have received votes from:");
int reputation = 0;
boolean serverVote = false;
String[] voteArray;
String[] griefArray;
if (voteList != null) {
voteArray = voteList.split(",");
if (voteArray.length != 0) {
String votes = ChatColor.GREEN + " Approvals: " + ChatColor.GOLD;
for (String vote : voteArray) {
votes = votes + vote + " ";
if (vote.equals("Server")) {
serverVote = true;
}
reputation ++;
}
if (serverVote) {
reputation = approvalVotes;
}
sender.sendMessage(votes);
}
}
if (griefList != null) {
griefArray = griefList.split(",");
if (griefArray.length != 0) {
String votes = ChatColor.DARK_GRAY + " Black-Balls: " + ChatColor.GOLD;
serverVote = false;
for (String vote : griefArray) {
votes = votes + vote + " ";
if (vote.equals("Server")) {
serverVote = true;
}
reputation--;
}
if (serverVote) {
reputation = -1;
}
sender.sendMessage(votes);
}
}
String repText;
if (reputation >= approvalVotes) {
repText = " " + ChatColor.GREEN + reputation;
}
else {
repText = " " + ChatColor.RED + reputation;
}
sender.sendMessage(ChatColor.GOLD + "Current Reputation:" + repText);
sender.sendMessage(ChatColor.GOLD + "Required Reputation: " + ChatColor.WHITE + approvalVotes);
}
return true;
}
else {
OfflinePlayer checktarget = getServer().getOfflinePlayer(args[0]);
String DN = null;
String target = null;
if (checktarget.isOnline()) {
target = checktarget.getPlayer().getName();
DN = checktarget.getPlayer().getDisplayName();
}
else {
if (checktarget != null) {
target = checktarget.getName();
DN = checktarget.getName();
}
}
if (target == null) {
// Player not found
sender.sendMessage(args[0] + ChatColor.RED + " not found!");
return false;
}
String voteList = this.usersConfig.getString(target.toLowerCase() + ".votes", null);
String griefList = this.usersConfig.getString(target.toLowerCase() + ".griefer", null);
if (voteList == null && griefList == null) {
sender.sendMessage(DN + ChatColor.GOLD + " has not received any votes.");
sender.sendMessage(ChatColor.GOLD + "Current Reputation: " + ChatColor.WHITE + "0");
sender.sendMessage(ChatColor.GOLD + "Required Reputation: " + ChatColor.WHITE + approvalVotes);
}
else {
sender.sendMessage(DN + ChatColor.GOLD + " has received votes from:");
int reputation = 0;
boolean serverVote = false;
String[] voteArray;
String[] griefArray;
if (voteList != null) {
voteArray = voteList.split(",");
if (voteArray.length != 0) {
String votes = ChatColor.GREEN + " Approvals: " + ChatColor.GOLD;
for (String vote : voteArray) {
votes = votes + vote + " ";
if (vote.equals("Server")) {
serverVote = true;
}
reputation ++;
}
if (serverVote) {
reputation = approvalVotes;
}
sender.sendMessage(votes);
}
}
if (griefList != null) {
griefArray = griefList.split(",");
if (griefArray.length != 0) {
String votes = ChatColor.DARK_GRAY + " Black-Balls: " + ChatColor.GOLD;
serverVote = false;
for (String vote : griefArray) {
votes = votes + vote + " ";
if (vote.equals("Server")) {
serverVote = true;
}
reputation--;
}
if (serverVote) {
reputation = -1;
}
sender.sendMessage(votes);
}
}
String repText;
if (reputation >= approvalVotes) {
repText = " " + ChatColor.GREEN + reputation;
}
else {
repText = " " + ChatColor.RED + reputation;
}
sender.sendMessage(ChatColor.GOLD + "Current Reputation:" + repText);
sender.sendMessage(ChatColor.GOLD + "Required Reputation: " + ChatColor.WHITE + approvalVotes);
}
return true;
}
}
return false;
}
public void setApproved(Player target) {
PermissionAttachment attachment = target.addAttachment(this);
attachment.setPermission("greylistvote.build", true);
Player[] onlinePlayers = getServer().getOnlinePlayers();
for (Player chatPlayer : onlinePlayers) {
if (!chatPlayer.getName().equals(target.getName())) {
chatPlayer.sendMessage(target.getName() + ChatColor.GOLD + "'s reputation has reached " + approvalVotes + "!");
chatPlayer.sendMessage(target.getName() + ChatColor.GOLD + " can now build!");
}
else {
chatPlayer.sendMessage(ChatColor.GREEN + "Your reputation has reached " + approvalVotes + "!");
chatPlayer.sendMessage(ChatColor.GREEN + "You can now build!");
}
}
}
public void setGriefer(Player target) {
PermissionAttachment attachment = target.addAttachment(this);
attachment.setPermission("greylistvote.build", false);
Player[] onlinePlayers = getServer().getOnlinePlayers();
for (Player chatPlayer : onlinePlayers) {
if (!chatPlayer.getName().equals(target.getName())) {
chatPlayer.sendMessage(target.getName() + ChatColor.GOLD + "'s reputation has dropped below " + approvalVotes + "!");
chatPlayer.sendMessage(target.getName() + ChatColor.GOLD + " can no longer build!");
}
else {
chatPlayer.sendMessage(ChatColor.RED + "Your reputation has dropped below " + approvalVotes + "!");
chatPlayer.sendMessage(ChatColor.RED + "Your build rights have been revoked!");
}
}
}
public void loadUsersConfig() {
if (this.usersFile == null) {
this.usersFile = new File(getDataFolder(),"users.yml");
}
this.usersConfig = YamlConfiguration.loadConfiguration(this.usersFile);
}
public FileConfiguration getUsersConfig() {
if (this.usersConfig == null) {
this.loadUsersConfig();
}
return this.usersConfig;
}
public void saveUsersConfig() {
if (this.usersConfig == null || this.usersFile == null) {
return;
}
try {
this.usersConfig.save(this.usersFile);
} catch (IOException ex) {
getLogger().log(Level.SEVERE, "Could not save " + this.usersFile, ex );
}
}
}
| false | true | public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
if (commandLabel.equalsIgnoreCase("glv")) {
if (args.length == 0) {
PluginDescriptionFile pdfFile = this.getDescription();
sender.sendMessage(ChatColor.GOLD + pdfFile.getName() + " version " + pdfFile.getVersion() + " by " + pdfFile.getAuthors());
sender.sendMessage(ChatColor.GOLD + "Commands: {optional} [required]");
sender.sendMessage(ChatColor.GOLD + " /glv " + ChatColor.GRAY + ": View all GreylistVote commands");
sender.sendMessage(ChatColor.GOLD + " /greylist [player] || /gl [player] || /trust Player " + ChatColor.GRAY + ":");
sender.sendMessage(ChatColor.GRAY + " Increase player's reputation");
sender.sendMessage(ChatColor.GOLD + " /griefer [player] " + ChatColor.GRAY + ":");
sender.sendMessage(ChatColor.GRAY + " Reduce player's reputation");
sender.sendMessage(ChatColor.GOLD + " /votelist {player} || /glvlist {player} " + ChatColor.GRAY + ":");
sender.sendMessage(ChatColor.GRAY + " View your (or player's) reputation");
if (sender.hasPermission("greylistvote.admin")) {
sender.sendMessage(ChatColor.RED + "Admin Commands:");
sender.sendMessage(ChatColor.GOLD + " /glv setrep [req. rep] " + ChatColor.GRAY + ": Set required reputation");
sender.sendMessage(ChatColor.GOLD + " /glv toggle [pvp|approvedvote] " + ChatColor.GRAY + ": Toggle true/false config options");
sender.sendMessage(ChatColor.GOLD + " /glv clearserver [player] " + ChatColor.GRAY + ": Remove player's Server votes");
sender.sendMessage(ChatColor.GOLD + " /glv clearall [player] " + ChatColor.GRAY + ": Remove all player's votes");
}
return true;
}
else if (args.length == 2) {
if (!sender.hasPermission("greylistvote.admin")) {
sender.sendMessage(ChatColor.RED + "You do not have permission to do that!");
return false;
}
if (args[0].equalsIgnoreCase("setrep")) {
try {
approvalVotes = Integer.parseInt(args[1]);
}
catch(NumberFormatException nfe) {
// Failed. Number not an integer
sender.sendMessage(ChatColor.RED + "[req. votes] must be a number!" );
return false;
}
this.config.set("required_votes", approvalVotes);
this.saveConfig();
sender.sendMessage(ChatColor.GOLD + "Reputation requirement now set to " + ChatColor.WHITE + args[1]);
sender.sendMessage(ChatColor.GOLD + "Player approval will be updated on next login.");
return true;
}
else if (args[0].equalsIgnoreCase("clearserver")) {
OfflinePlayer target = getServer().getOfflinePlayer(args[1]);
if (!target.hasPlayedBefore()) {
sender.sendMessage(ChatColor.RED + "Player " + ChatColor.WHITE + args[0] + ChatColor.RED + "not found!");
return true;
}
String griefList = this.usersConfig.getString(target.getName().toLowerCase() + ".griefer", null);
String voteList = this.usersConfig.getString(target.getName().toLowerCase() + ".votes", null);
String[] voteArray;
String[] griefArray;
if (griefList == null && voteList == null) {
sender.sendMessage(ChatColor.RED + "Player " + ChatColor.WHITE + target.getName() + ChatColor.RED + " does not have any votes!");
return true;
}
String newVoteList = null;
String[] newVoteArray = null;
if (voteList != null) {
voteArray = voteList.split(",");
for (String vote : voteArray) {
if (!vote.equals("Server")) {
if (newVoteList != null) {
newVoteList += "," + vote;
} else {
newVoteList = vote;
}
}
}
if (newVoteList != null) {
newVoteArray = newVoteList.split(",");
}
usersConfig.set(target.getName().toLowerCase() + ".votes", newVoteList);
}
String newGriefList = null;
String[] newGriefArray = null;
if (griefList != null) {
griefArray = griefList.split(",");
for (String vote : griefArray) {
if (!vote.equals("Server")) {
if (newGriefList != null) {
newGriefList += "," + vote;
} else {
newGriefList = vote;
}
}
}
if (newGriefList != null) {
newGriefArray = newGriefList.split(",");
}
usersConfig.set(target.getName().toLowerCase() + ".griefer", newGriefList);
}
saveUsersConfig();
int rep = 0;
if (newVoteList != null) {
rep += newVoteArray.length;
}
if (newGriefList != null) {
rep -= newGriefArray.length;
}
sender.sendMessage(ChatColor.GOLD + "'Server' votes removed from " + ChatColor.WHITE + target.getName());
if (target.isOnline()) {
target.getPlayer().sendMessage(ChatColor.GOLD + "Your Server Approval/Black-Ball votes were removed!");
if (rep >= approvalVotes && !target.getPlayer().hasPermission("greylistvote.build") && !target.getPlayer().hasPermission("greylistvote.approved")) {
setApproved(target.getPlayer());
}
else if (rep < approvalVotes && target.getPlayer().hasPermission("greylistvote.build") && !target.getPlayer().hasPermission("greylistvote.approved")) {
setGriefer(target.getPlayer());
}
} else {
Player[] onlinePlayers = getServer().getOnlinePlayers();
for (Player chatPlayer : onlinePlayers) {
if (!chatPlayer.getName().equals(sender.getName())) {
chatPlayer.sendMessage(target.getName() + ChatColor.GOLD + "'s reputation has been reset to 0!");
}
}
}
this.saveUsersConfig();
return true;
}
else if (args[0].equalsIgnoreCase("clearall")) {
OfflinePlayer target = getServer().getOfflinePlayer(args[1]);
if (!target.hasPlayedBefore()) {
sender.sendMessage(ChatColor.RED + "Player " + ChatColor.WHITE + args[0] + ChatColor.RED + "not found!");
return true;
}
String griefList = this.usersConfig.getString(target.getName().toLowerCase() + ".griefer", null);
String voteList = this.usersConfig.getString(target.getName().toLowerCase() + ".votes", null);
if (griefList == null && voteList == null) {
sender.sendMessage(ChatColor.RED + "Player " + ChatColor.WHITE + target.getName() + ChatColor.RED + " does not have any votes!");
return true;
}
usersConfig.set(target.getName().toLowerCase() + ".votes", null);
usersConfig.set(target.getName().toLowerCase() + ".griefer", null);
sender.sendMessage(ChatColor.GOLD + "ALL votes removed from " + ChatColor.WHITE + target.getName());
if (target.isOnline()) {
target.getPlayer().sendMessage(ChatColor.RED + "Your reputation was reset to 0!");
if (0 >= approvalVotes && !target.getPlayer().hasPermission("greylistvote.build") && !target.getPlayer().hasPermission("greylistvote.approved")) {
setApproved(target.getPlayer());
}
else if (0 < approvalVotes && target.getPlayer().hasPermission("greylistvote.build") && !target.getPlayer().hasPermission("greylistvote.approved")) {
setGriefer(target.getPlayer());
}
} else {
Player[] onlinePlayers = getServer().getOnlinePlayers();
for (Player chatPlayer : onlinePlayers) {
if (!chatPlayer.getName().equals(sender.getName())) {
chatPlayer.sendMessage(target.getName() + ChatColor.GOLD + "'s reputation has been reset to 0!");
}
}
}
this.saveUsersConfig();
return true;
} else if (args[0].equalsIgnoreCase("toggle")) {
if (args[1].equalsIgnoreCase("pvp")) {
if (noPVP) {
noPVP = false;
sender.sendMessage(ChatColor.GOLD + "Unapproved players are no longer protected against PVP.");
} else {
noPVP = true;
sender.sendMessage(ChatColor.GOLD + "Unapproved players are now protected against PVP.");
}
config.set("no_pvp", noPVP);
saveConfig();
} else if (args[1].equalsIgnoreCase("approvedvote")) {
if (allowApprovedVote) {
allowApprovedVote = false;
sender.sendMessage(ChatColor.GOLD + "Only player with permission may now vote!");
} else {
allowApprovedVote = true;
sender.sendMessage(ChatColor.GOLD + "All approved players may now vote!");
}
config.set("allow_all_approved_to_vote", allowApprovedVote);
saveConfig();
} else {
sender.sendMessage(ChatColor.RED + "Toggle option not recognised!");
sender.sendMessage(ChatColor.RED + "Allowed toggles: pvp, approvedvote");
return false;
}
}
else {
sender.sendMessage(ChatColor.RED + "Command not recognised!");
return false;
}
}
sender.sendMessage(ChatColor.RED + "Command not recognised!");
return false;
}
else if (commandLabel.equalsIgnoreCase("greylist") || commandLabel.equalsIgnoreCase("gl") || commandLabel.equalsIgnoreCase("trust")) {
if (args.length != 1) {
// No player specified or too many arguments
return false;
}
else {
if (!sender.hasPermission("greylistvote.vote") && !(allowApprovedVote && sender.hasPermission("greylistvote.approved"))) {
sender.sendMessage(ChatColor.RED + "You do not have permission to vote!");
return true;
}
OfflinePlayer target = getServer().getOfflinePlayer(args[0]);
if (!target.hasPlayedBefore() && !target.isOnline()) {
// Player not online
sender.sendMessage(args[0] + ChatColor.RED + " not found!");
return false;
}
if (!(sender instanceof Player)) {
// Voter is the console
this.usersConfig.set(target.getName().toLowerCase() + ".votes", "Server");
this.usersConfig.set(target.getName().toLowerCase() + ".griefer", null);
sender.sendMessage(target.getName() + ChatColor.GOLD + "'s reputation was set to " + approvalVotes + "!");
Player[] onlinePlayers = getServer().getOnlinePlayers();
for (Player chatPlayer : onlinePlayers) {
if (!chatPlayer.getName().equals(target.getName())) {
chatPlayer.sendMessage(target.getName() + ChatColor.GOLD + "'s reputation was set to " + approvalVotes + " by the Server!");
}
else {
target.getPlayer().sendMessage(ChatColor.GOLD + "Your reputation was set to " + approvalVotes + " by the Server!");
}
}
if (target.isOnline() && !target.getPlayer().hasPermission("greylistvote.build") && !target.getPlayer().hasPermission("greylistvote.approved")) {
this.setApproved(target.getPlayer());
}
this.saveUsersConfig();
return true;
}
if (sender.getName().equalsIgnoreCase(target.getName())) {
// Player voting for self
sender.sendMessage(ChatColor.RED + "You cannot vote for yourself!");
return true;
}
String griefList = this.usersConfig.getString(target.getName().toLowerCase() + ".griefer", null);
String voteList = this.usersConfig.getString(target.getName().toLowerCase() + ".votes", null);
String[] voteArray = null;
String[] griefArray = null;
if (voteList != null) {
voteArray = voteList.split(",");
}
else {
voteList = "";
}
if (griefList != null) {
griefArray = griefList.split(",");
}
boolean found = false;
if (voteArray != null) {
for (String vote : voteArray) {
if (vote.equalsIgnoreCase(sender.getName())) {
found = true;
}
}
}
if (found) {
// Voter has already voted for this target player
sender.sendMessage(ChatColor.RED + "You have already voted for " + ChatColor.WHITE + target.getName());
return true;
}
if (griefArray != null) {
String newGriefList = null;
for (String vote : griefArray) {
if (!vote.equalsIgnoreCase(sender.getName())) {
if (newGriefList != null) {
newGriefList += "," + vote;
} else {
newGriefList = vote;
}
}
}
if (newGriefList != null) {
newGriefList = newGriefList.replaceFirst(",", "");
usersConfig.set(target.getName().toLowerCase() + ".griefer", newGriefList);
griefArray = newGriefList.split(",");
}
else {
griefArray = null;
usersConfig.set(target.getName().toLowerCase() + ".griefer", null);
}
}
sender.sendMessage(ChatColor.GOLD + "You have increased " + ChatColor.WHITE + target.getName() + ChatColor.GOLD + "'s reputation!");
Player[] onlinePlayers = getServer().getOnlinePlayers();
// Tell everyone about the reputation change
for (Player chatPlayer : onlinePlayers) {
if (!chatPlayer.getName().equals(target.getName()) && !chatPlayer.getName().equals(sender.getName())) {
chatPlayer.sendMessage(sender.getName() + ChatColor.GOLD + " increased " + ChatColor.WHITE + target.getName() + ChatColor.GOLD + "'s reputation!");
}
else if (!chatPlayer.getName().equals(sender.getName())) {
chatPlayer.sendMessage(sender.getName() + ChatColor.GREEN + " increased your reputation!");
chatPlayer.sendMessage(ChatColor.GOLD + "Type " + ChatColor.WHITE + "/votelist" + ChatColor.GOLD + " to check your reputation.");
}
}
if (voteList.equals("")) {
voteList = sender.getName();
}
else {
voteList = voteList + "," + sender.getName();
}
this.usersConfig.set(target.getName().toLowerCase() + ".votes", voteList);
voteArray = voteList.split(",");
int rep = 0;
if (voteArray.length != 0) {
rep += voteArray.length;
}
if (griefArray != null) {
if (griefArray.length != 0) {
rep -= griefArray.length;
}
}
if (target.isOnline() && rep >= approvalVotes && !target.getPlayer().hasPermission("greylistvote.build") && !target.getPlayer().hasPermission("greylistvote.approved")) {
// Enough votes received
this.setApproved(target.getPlayer());
}
else if (!target.isOnline() && rep >= approvalVotes) {
for (Player chatPlayer : onlinePlayers) {
if (!chatPlayer.getName().equals(target.getName())) {
chatPlayer.sendMessage(target.getName() + ChatColor.GOLD + "'s reputation has reached " + approvalVotes + "!");
chatPlayer.sendMessage(target.getName() + ChatColor.GOLD + " can now build!");
}
}
}
this.saveUsersConfig();
return true;
}
}
else if (commandLabel.equalsIgnoreCase("griefer") || commandLabel.equalsIgnoreCase("distrust")) {
if (!sender.hasPermission("greylistvote.griefer") && !(allowApprovedVote && sender.hasPermission("greylistvote.approved"))) {
sender.sendMessage(ChatColor.RED + "You do not have permission to vote!");
return true;
}
if (args.length != 1) {
// No player specified or too many arguments
return false;
}
else {
OfflinePlayer target = getServer().getOfflinePlayer(args[0]);
if (!target.hasPlayedBefore()) {
// Player not online
sender.sendMessage(args[0] + ChatColor.RED + " not found!");
return false;
}
String griefList = this.usersConfig.getString(target.getName().toLowerCase() + ".griefer", null);
String voteList = this.usersConfig.getString(target.getName().toLowerCase() + ".votes", null);
String[] voteArray = null;
String[] griefArray = null;
if (voteList != null) {
voteArray = voteList.split(",");
}
if (griefList != null) {
griefArray = griefList.split(",");
}
else {
griefList = "";
}
if (!(sender instanceof Player)) {
// Voter is the console
this.usersConfig.set(target.getName().toLowerCase() + ".griefer", "Server");
this.usersConfig.set(target.getName().toLowerCase() + ".votes", null);
sender.sendMessage(target.getName() + ChatColor.GOLD + "'s reputation was set to -1!");
Player[] onlinePlayers = getServer().getOnlinePlayers();
for (Player chatPlayer : onlinePlayers) {
if (!chatPlayer.getName().equals(target.getName())) {
chatPlayer.sendMessage(target.getName() + ChatColor.GOLD + "'s reputation was set to -1 by the Server!");
}
else {
target.getPlayer().sendMessage(ChatColor.GOLD + "Your reputation was set to -1 by the Server!");
}
}
if (target.getPlayer().hasPermission("greylistvote.build") && !target.getPlayer().hasPermission("greylistvote.approved")) {
this.setGriefer(target.getPlayer());
}
this.saveUsersConfig();
return true;
}
if (!sender.getName().equals(target.getName())) {
// Player voting for self
sender.sendMessage(ChatColor.RED + "You cannot vote for yourself!");
return true;
}
boolean found = false;
if (griefArray != null) {
for (String vote : griefArray) {
if (vote.equalsIgnoreCase(sender.getName())) {
found = true;
}
}
}
if (found) {
// Voter has already voted for this target player
sender.sendMessage(ChatColor.RED + "You have already voted for " + ChatColor.WHITE + target.getName());
return true;
}
if (voteArray != null) {
String newVoteList = null;
for (String vote : voteArray) {
if (!vote.equalsIgnoreCase(sender.getName())) {
if (newVoteList != null) {
newVoteList += "," + vote;
} else {
newVoteList = vote;
}
}
}
if (newVoteList != null) {
newVoteList = newVoteList.replaceFirst(",", "");
usersConfig.set(target.getName().toLowerCase() + ".votes", newVoteList);
voteArray = newVoteList.split(",");
}
else {
voteArray = null;
usersConfig.set(target.getName().toLowerCase() + ".votes", null);
}
}
sender.sendMessage(ChatColor.GOLD + "You have reduced " + ChatColor.WHITE + target.getName() + ChatColor.GOLD + "'s reputation!");
Player[] onlinePlayers = getServer().getOnlinePlayers();
for (Player chatPlayer : onlinePlayers) {
if (!chatPlayer.getName().equals(target.getName()) && !chatPlayer.getName().equals(sender.getName())) {
chatPlayer.sendMessage(sender.getName() + ChatColor.GOLD + " reduced " + ChatColor.WHITE + target.getName() + ChatColor.GOLD + "'s reputation!");
}
else if (!chatPlayer.getName().equals(sender.getName())) {
chatPlayer.sendMessage(sender.getName() + ChatColor.RED + " reduced your reputation!");
chatPlayer.sendMessage(ChatColor.GOLD + "Type " + ChatColor.WHITE + "/votelist" + ChatColor.GOLD + " to check your reputation.");
}
}
if (griefList.equals("")) {
griefList = sender.getName();
}
else {
griefList = griefList + "," + sender.getName();
}
this.usersConfig.set(target.getName().toLowerCase() + ".griefer", griefList);
griefArray = griefList.split(",");
int rep = 0;
if (voteArray != null) {
rep += voteArray.length;
}
if (griefArray != null) {
rep -= griefArray.length;
}
if (target.isOnline() && rep < approvalVotes && target.getPlayer().hasPermission("greylistvote.build") && !target.getPlayer().hasPermission("greylistvote.approved")) {
// Enough votes received
this.setGriefer(target.getPlayer());
}
else if (!target.isOnline() && rep < approvalVotes) {
for (Player chatPlayer : onlinePlayers) {
if (!chatPlayer.getName().equals(target.getName())) {
chatPlayer.sendMessage(target.getName() + ChatColor.GOLD + "'s reputation has dropped below " + approvalVotes + "!");
}
}
}
this.saveUsersConfig();
return true;
}
}
else if (commandLabel.equalsIgnoreCase("votelist") || commandLabel.equalsIgnoreCase("glvlist") || commandLabel.equalsIgnoreCase("rep")) {
if (args == null || args.length == 0) {
String voteList = this.usersConfig.getString(sender.getName().toLowerCase() + ".votes", null);
String griefList = this.usersConfig.getString(sender.getName().toLowerCase() + ".griefer", null);
if (voteList == null && griefList == null) {
sender.sendMessage(ChatColor.GOLD + "You have not received any votes.");
sender.sendMessage(ChatColor.GOLD + "Current Reputation: " + ChatColor.WHITE + "0");
sender.sendMessage(ChatColor.GOLD + "Required Reputation: " + ChatColor.WHITE + approvalVotes);
}
else {
sender.sendMessage(ChatColor.GOLD + "You have received votes from:");
int reputation = 0;
boolean serverVote = false;
String[] voteArray;
String[] griefArray;
if (voteList != null) {
voteArray = voteList.split(",");
if (voteArray.length != 0) {
String votes = ChatColor.GREEN + " Approvals: " + ChatColor.GOLD;
for (String vote : voteArray) {
votes = votes + vote + " ";
if (vote.equals("Server")) {
serverVote = true;
}
reputation ++;
}
if (serverVote) {
reputation = approvalVotes;
}
sender.sendMessage(votes);
}
}
if (griefList != null) {
griefArray = griefList.split(",");
if (griefArray.length != 0) {
String votes = ChatColor.DARK_GRAY + " Black-Balls: " + ChatColor.GOLD;
serverVote = false;
for (String vote : griefArray) {
votes = votes + vote + " ";
if (vote.equals("Server")) {
serverVote = true;
}
reputation--;
}
if (serverVote) {
reputation = -1;
}
sender.sendMessage(votes);
}
}
String repText;
if (reputation >= approvalVotes) {
repText = " " + ChatColor.GREEN + reputation;
}
else {
repText = " " + ChatColor.RED + reputation;
}
sender.sendMessage(ChatColor.GOLD + "Current Reputation:" + repText);
sender.sendMessage(ChatColor.GOLD + "Required Reputation: " + ChatColor.WHITE + approvalVotes);
}
return true;
}
else {
OfflinePlayer checktarget = getServer().getOfflinePlayer(args[0]);
String DN = null;
String target = null;
if (checktarget.isOnline()) {
target = checktarget.getPlayer().getName();
DN = checktarget.getPlayer().getDisplayName();
}
else {
if (checktarget != null) {
target = checktarget.getName();
DN = checktarget.getName();
}
}
if (target == null) {
// Player not found
sender.sendMessage(args[0] + ChatColor.RED + " not found!");
return false;
}
String voteList = this.usersConfig.getString(target.toLowerCase() + ".votes", null);
String griefList = this.usersConfig.getString(target.toLowerCase() + ".griefer", null);
if (voteList == null && griefList == null) {
sender.sendMessage(DN + ChatColor.GOLD + " has not received any votes.");
sender.sendMessage(ChatColor.GOLD + "Current Reputation: " + ChatColor.WHITE + "0");
sender.sendMessage(ChatColor.GOLD + "Required Reputation: " + ChatColor.WHITE + approvalVotes);
}
else {
sender.sendMessage(DN + ChatColor.GOLD + " has received votes from:");
int reputation = 0;
boolean serverVote = false;
String[] voteArray;
String[] griefArray;
if (voteList != null) {
voteArray = voteList.split(",");
if (voteArray.length != 0) {
String votes = ChatColor.GREEN + " Approvals: " + ChatColor.GOLD;
for (String vote : voteArray) {
votes = votes + vote + " ";
if (vote.equals("Server")) {
serverVote = true;
}
reputation ++;
}
if (serverVote) {
reputation = approvalVotes;
}
sender.sendMessage(votes);
}
}
if (griefList != null) {
griefArray = griefList.split(",");
if (griefArray.length != 0) {
String votes = ChatColor.DARK_GRAY + " Black-Balls: " + ChatColor.GOLD;
serverVote = false;
for (String vote : griefArray) {
votes = votes + vote + " ";
if (vote.equals("Server")) {
serverVote = true;
}
reputation--;
}
if (serverVote) {
reputation = -1;
}
sender.sendMessage(votes);
}
}
String repText;
if (reputation >= approvalVotes) {
repText = " " + ChatColor.GREEN + reputation;
}
else {
repText = " " + ChatColor.RED + reputation;
}
sender.sendMessage(ChatColor.GOLD + "Current Reputation:" + repText);
sender.sendMessage(ChatColor.GOLD + "Required Reputation: " + ChatColor.WHITE + approvalVotes);
}
return true;
}
}
return false;
}
| public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
if (commandLabel.equalsIgnoreCase("glv")) {
if (args.length == 0) {
PluginDescriptionFile pdfFile = this.getDescription();
sender.sendMessage(ChatColor.GOLD + pdfFile.getName() + " version " + pdfFile.getVersion() + " by " + pdfFile.getAuthors());
sender.sendMessage(ChatColor.GOLD + "Commands: {optional} [required]");
sender.sendMessage(ChatColor.GOLD + " /glv " + ChatColor.GRAY + ": View all GreylistVote commands");
sender.sendMessage(ChatColor.GOLD + " /greylist [player] || /gl [player] || /trust Player " + ChatColor.GRAY + ":");
sender.sendMessage(ChatColor.GRAY + " Increase player's reputation");
sender.sendMessage(ChatColor.GOLD + " /griefer [player] " + ChatColor.GRAY + ":");
sender.sendMessage(ChatColor.GRAY + " Reduce player's reputation");
sender.sendMessage(ChatColor.GOLD + " /votelist {player} || /glvlist {player} " + ChatColor.GRAY + ":");
sender.sendMessage(ChatColor.GRAY + " View your (or player's) reputation");
if (sender.hasPermission("greylistvote.admin")) {
sender.sendMessage(ChatColor.RED + "Admin Commands:");
sender.sendMessage(ChatColor.GOLD + " /glv setrep [req. rep] " + ChatColor.GRAY + ": Set required reputation");
sender.sendMessage(ChatColor.GOLD + " /glv toggle [pvp|approvedvote] " + ChatColor.GRAY + ": Toggle true/false config options");
sender.sendMessage(ChatColor.GOLD + " /glv clearserver [player] " + ChatColor.GRAY + ": Remove player's Server votes");
sender.sendMessage(ChatColor.GOLD + " /glv clearall [player] " + ChatColor.GRAY + ": Remove all player's votes");
}
return true;
}
else if (args.length == 2) {
if (!sender.hasPermission("greylistvote.admin")) {
sender.sendMessage(ChatColor.RED + "You do not have permission to do that!");
return false;
}
if (args[0].equalsIgnoreCase("setrep")) {
try {
approvalVotes = Integer.parseInt(args[1]);
}
catch(NumberFormatException nfe) {
// Failed. Number not an integer
sender.sendMessage(ChatColor.RED + "[req. votes] must be a number!" );
return false;
}
this.config.set("required_votes", approvalVotes);
this.saveConfig();
sender.sendMessage(ChatColor.GOLD + "Reputation requirement now set to " + ChatColor.WHITE + args[1]);
sender.sendMessage(ChatColor.GOLD + "Player approval will be updated on next login.");
return true;
}
else if (args[0].equalsIgnoreCase("clearserver")) {
OfflinePlayer target = getServer().getOfflinePlayer(args[1]);
if (!target.hasPlayedBefore()) {
sender.sendMessage(ChatColor.RED + "Player " + ChatColor.WHITE + args[0] + ChatColor.RED + "not found!");
return true;
}
String griefList = this.usersConfig.getString(target.getName().toLowerCase() + ".griefer", null);
String voteList = this.usersConfig.getString(target.getName().toLowerCase() + ".votes", null);
String[] voteArray;
String[] griefArray;
if (griefList == null && voteList == null) {
sender.sendMessage(ChatColor.RED + "Player " + ChatColor.WHITE + target.getName() + ChatColor.RED + " does not have any votes!");
return true;
}
String newVoteList = null;
String[] newVoteArray = null;
if (voteList != null) {
voteArray = voteList.split(",");
for (String vote : voteArray) {
if (!vote.equals("Server")) {
if (newVoteList != null) {
newVoteList += "," + vote;
} else {
newVoteList = vote;
}
}
}
if (newVoteList != null) {
newVoteArray = newVoteList.split(",");
}
usersConfig.set(target.getName().toLowerCase() + ".votes", newVoteList);
}
String newGriefList = null;
String[] newGriefArray = null;
if (griefList != null) {
griefArray = griefList.split(",");
for (String vote : griefArray) {
if (!vote.equals("Server")) {
if (newGriefList != null) {
newGriefList += "," + vote;
} else {
newGriefList = vote;
}
}
}
if (newGriefList != null) {
newGriefArray = newGriefList.split(",");
}
usersConfig.set(target.getName().toLowerCase() + ".griefer", newGriefList);
}
saveUsersConfig();
int rep = 0;
if (newVoteList != null) {
rep += newVoteArray.length;
}
if (newGriefList != null) {
rep -= newGriefArray.length;
}
sender.sendMessage(ChatColor.GOLD + "'Server' votes removed from " + ChatColor.WHITE + target.getName());
if (target.isOnline()) {
target.getPlayer().sendMessage(ChatColor.GOLD + "Your Server Approval/Black-Ball votes were removed!");
if (rep >= approvalVotes && !target.getPlayer().hasPermission("greylistvote.build") && !target.getPlayer().hasPermission("greylistvote.approved")) {
setApproved(target.getPlayer());
}
else if (rep < approvalVotes && target.getPlayer().hasPermission("greylistvote.build") && !target.getPlayer().hasPermission("greylistvote.approved")) {
setGriefer(target.getPlayer());
}
} else {
Player[] onlinePlayers = getServer().getOnlinePlayers();
for (Player chatPlayer : onlinePlayers) {
if (!chatPlayer.getName().equals(sender.getName())) {
chatPlayer.sendMessage(target.getName() + ChatColor.GOLD + "'s reputation has been reset to 0!");
}
}
}
this.saveUsersConfig();
return true;
}
else if (args[0].equalsIgnoreCase("clearall")) {
OfflinePlayer target = getServer().getOfflinePlayer(args[1]);
if (!target.hasPlayedBefore()) {
sender.sendMessage(ChatColor.RED + "Player " + ChatColor.WHITE + args[0] + ChatColor.RED + "not found!");
return true;
}
String griefList = this.usersConfig.getString(target.getName().toLowerCase() + ".griefer", null);
String voteList = this.usersConfig.getString(target.getName().toLowerCase() + ".votes", null);
if (griefList == null && voteList == null) {
sender.sendMessage(ChatColor.RED + "Player " + ChatColor.WHITE + target.getName() + ChatColor.RED + " does not have any votes!");
return true;
}
usersConfig.set(target.getName().toLowerCase() + ".votes", null);
usersConfig.set(target.getName().toLowerCase() + ".griefer", null);
sender.sendMessage(ChatColor.GOLD + "ALL votes removed from " + ChatColor.WHITE + target.getName());
if (target.isOnline()) {
target.getPlayer().sendMessage(ChatColor.RED + "Your reputation was reset to 0!");
if (0 >= approvalVotes && !target.getPlayer().hasPermission("greylistvote.build") && !target.getPlayer().hasPermission("greylistvote.approved")) {
setApproved(target.getPlayer());
}
else if (0 < approvalVotes && target.getPlayer().hasPermission("greylistvote.build") && !target.getPlayer().hasPermission("greylistvote.approved")) {
setGriefer(target.getPlayer());
}
} else {
Player[] onlinePlayers = getServer().getOnlinePlayers();
for (Player chatPlayer : onlinePlayers) {
if (!chatPlayer.getName().equals(sender.getName())) {
chatPlayer.sendMessage(target.getName() + ChatColor.GOLD + "'s reputation has been reset to 0!");
}
}
}
this.saveUsersConfig();
return true;
} else if (args[0].equalsIgnoreCase("toggle")) {
if (args[1].equalsIgnoreCase("pvp")) {
if (noPVP) {
noPVP = false;
sender.sendMessage(ChatColor.GOLD + "Unapproved players are no longer protected against PVP.");
} else {
noPVP = true;
sender.sendMessage(ChatColor.GOLD + "Unapproved players are now protected against PVP.");
}
config.set("no_pvp", noPVP);
saveConfig();
} else if (args[1].equalsIgnoreCase("approvedvote")) {
if (allowApprovedVote) {
allowApprovedVote = false;
sender.sendMessage(ChatColor.GOLD + "Only player with permission may now vote!");
} else {
allowApprovedVote = true;
sender.sendMessage(ChatColor.GOLD + "All approved players may now vote!");
}
config.set("allow_all_approved_to_vote", allowApprovedVote);
saveConfig();
} else {
sender.sendMessage(ChatColor.RED + "Toggle option not recognised!");
sender.sendMessage(ChatColor.RED + "Allowed toggles: pvp, approvedvote");
return false;
}
}
else {
sender.sendMessage(ChatColor.RED + "Command not recognised!");
return false;
}
}
sender.sendMessage(ChatColor.RED + "Command not recognised!");
return false;
}
else if (commandLabel.equalsIgnoreCase("greylist") || commandLabel.equalsIgnoreCase("gl") || commandLabel.equalsIgnoreCase("trust")) {
if (args.length != 1) {
// No player specified or too many arguments
return false;
}
else {
if (!sender.hasPermission("greylistvote.vote") && !(allowApprovedVote && sender.hasPermission("greylistvote.build"))) {
sender.sendMessage(ChatColor.RED + "You do not have permission to vote!");
return true;
}
OfflinePlayer target = getServer().getOfflinePlayer(args[0]);
if (!target.hasPlayedBefore() && !target.isOnline()) {
// Player not online
sender.sendMessage(args[0] + ChatColor.RED + " not found!");
return false;
}
if (!(sender instanceof Player)) {
// Voter is the console
this.usersConfig.set(target.getName().toLowerCase() + ".votes", "Server");
this.usersConfig.set(target.getName().toLowerCase() + ".griefer", null);
sender.sendMessage(target.getName() + ChatColor.GOLD + "'s reputation was set to " + approvalVotes + "!");
Player[] onlinePlayers = getServer().getOnlinePlayers();
for (Player chatPlayer : onlinePlayers) {
if (!chatPlayer.getName().equals(target.getName())) {
chatPlayer.sendMessage(target.getName() + ChatColor.GOLD + "'s reputation was set to " + approvalVotes + " by the Server!");
}
else {
target.getPlayer().sendMessage(ChatColor.GOLD + "Your reputation was set to " + approvalVotes + " by the Server!");
}
}
if (target.isOnline() && !target.getPlayer().hasPermission("greylistvote.build") && !target.getPlayer().hasPermission("greylistvote.approved")) {
this.setApproved(target.getPlayer());
}
this.saveUsersConfig();
return true;
}
if (sender.getName().equalsIgnoreCase(target.getName())) {
// Player voting for self
sender.sendMessage(ChatColor.RED + "You cannot vote for yourself!");
return true;
}
String griefList = this.usersConfig.getString(target.getName().toLowerCase() + ".griefer", null);
String voteList = this.usersConfig.getString(target.getName().toLowerCase() + ".votes", null);
String[] voteArray = null;
String[] griefArray = null;
if (voteList != null) {
voteArray = voteList.split(",");
}
else {
voteList = "";
}
if (griefList != null) {
griefArray = griefList.split(",");
}
boolean found = false;
if (voteArray != null) {
for (String vote : voteArray) {
if (vote.equalsIgnoreCase(sender.getName())) {
found = true;
}
}
}
if (found) {
// Voter has already voted for this target player
sender.sendMessage(ChatColor.RED + "You have already voted for " + ChatColor.WHITE + target.getName());
return true;
}
if (griefArray != null) {
String newGriefList = null;
for (String vote : griefArray) {
if (!vote.equalsIgnoreCase(sender.getName())) {
if (newGriefList != null) {
newGriefList += "," + vote;
} else {
newGriefList = vote;
}
}
}
if (newGriefList != null) {
newGriefList = newGriefList.replaceFirst(",", "");
usersConfig.set(target.getName().toLowerCase() + ".griefer", newGriefList);
griefArray = newGriefList.split(",");
}
else {
griefArray = null;
usersConfig.set(target.getName().toLowerCase() + ".griefer", null);
}
}
sender.sendMessage(ChatColor.GOLD + "You have increased " + ChatColor.WHITE + target.getName() + ChatColor.GOLD + "'s reputation!");
Player[] onlinePlayers = getServer().getOnlinePlayers();
// Tell everyone about the reputation change
for (Player chatPlayer : onlinePlayers) {
if (!chatPlayer.getName().equals(target.getName()) && !chatPlayer.getName().equals(sender.getName())) {
chatPlayer.sendMessage(sender.getName() + ChatColor.GOLD + " increased " + ChatColor.WHITE + target.getName() + ChatColor.GOLD + "'s reputation!");
}
else if (!chatPlayer.getName().equals(sender.getName())) {
chatPlayer.sendMessage(sender.getName() + ChatColor.GREEN + " increased your reputation!");
chatPlayer.sendMessage(ChatColor.GOLD + "Type " + ChatColor.WHITE + "/votelist" + ChatColor.GOLD + " to check your reputation.");
}
}
if (voteList.equals("")) {
voteList = sender.getName();
}
else {
voteList = voteList + "," + sender.getName();
}
this.usersConfig.set(target.getName().toLowerCase() + ".votes", voteList);
voteArray = voteList.split(",");
int rep = 0;
if (voteArray.length != 0) {
rep += voteArray.length;
}
if (griefArray != null) {
if (griefArray.length != 0) {
rep -= griefArray.length;
}
}
if (target.isOnline() && rep >= approvalVotes && !target.getPlayer().hasPermission("greylistvote.build") && !target.getPlayer().hasPermission("greylistvote.approved")) {
// Enough votes received
this.setApproved(target.getPlayer());
}
else if (!target.isOnline() && rep >= approvalVotes) {
for (Player chatPlayer : onlinePlayers) {
if (!chatPlayer.getName().equals(target.getName())) {
chatPlayer.sendMessage(target.getName() + ChatColor.GOLD + "'s reputation has reached " + approvalVotes + "!");
chatPlayer.sendMessage(target.getName() + ChatColor.GOLD + " can now build!");
}
}
}
this.saveUsersConfig();
return true;
}
}
else if (commandLabel.equalsIgnoreCase("griefer") || commandLabel.equalsIgnoreCase("distrust")) {
if (!sender.hasPermission("greylistvote.griefer") && !(allowApprovedVote && sender.hasPermission("greylistvote.build"))) {
sender.sendMessage(ChatColor.RED + "You do not have permission to vote!");
return true;
}
if (args.length != 1) {
// No player specified or too many arguments
return false;
}
else {
OfflinePlayer target = getServer().getOfflinePlayer(args[0]);
if (!target.hasPlayedBefore()) {
// Player not online
sender.sendMessage(args[0] + ChatColor.RED + " not found!");
return false;
}
String griefList = this.usersConfig.getString(target.getName().toLowerCase() + ".griefer", null);
String voteList = this.usersConfig.getString(target.getName().toLowerCase() + ".votes", null);
String[] voteArray = null;
String[] griefArray = null;
if (voteList != null) {
voteArray = voteList.split(",");
}
if (griefList != null) {
griefArray = griefList.split(",");
}
else {
griefList = "";
}
if (!(sender instanceof Player)) {
// Voter is the console
this.usersConfig.set(target.getName().toLowerCase() + ".griefer", "Server");
this.usersConfig.set(target.getName().toLowerCase() + ".votes", null);
sender.sendMessage(target.getName() + ChatColor.GOLD + "'s reputation was set to -1!");
Player[] onlinePlayers = getServer().getOnlinePlayers();
for (Player chatPlayer : onlinePlayers) {
if (!chatPlayer.getName().equals(target.getName())) {
chatPlayer.sendMessage(target.getName() + ChatColor.GOLD + "'s reputation was set to -1 by the Server!");
}
else {
target.getPlayer().sendMessage(ChatColor.GOLD + "Your reputation was set to -1 by the Server!");
}
}
if (target.getPlayer().hasPermission("greylistvote.build") && !target.getPlayer().hasPermission("greylistvote.approved")) {
this.setGriefer(target.getPlayer());
}
this.saveUsersConfig();
return true;
}
if (!sender.getName().equals(target.getName())) {
// Player voting for self
sender.sendMessage(ChatColor.RED + "You cannot vote for yourself!");
return true;
}
boolean found = false;
if (griefArray != null) {
for (String vote : griefArray) {
if (vote.equalsIgnoreCase(sender.getName())) {
found = true;
}
}
}
if (found) {
// Voter has already voted for this target player
sender.sendMessage(ChatColor.RED + "You have already voted for " + ChatColor.WHITE + target.getName());
return true;
}
if (voteArray != null) {
String newVoteList = null;
for (String vote : voteArray) {
if (!vote.equalsIgnoreCase(sender.getName())) {
if (newVoteList != null) {
newVoteList += "," + vote;
} else {
newVoteList = vote;
}
}
}
if (newVoteList != null) {
newVoteList = newVoteList.replaceFirst(",", "");
usersConfig.set(target.getName().toLowerCase() + ".votes", newVoteList);
voteArray = newVoteList.split(",");
}
else {
voteArray = null;
usersConfig.set(target.getName().toLowerCase() + ".votes", null);
}
}
sender.sendMessage(ChatColor.GOLD + "You have reduced " + ChatColor.WHITE + target.getName() + ChatColor.GOLD + "'s reputation!");
Player[] onlinePlayers = getServer().getOnlinePlayers();
for (Player chatPlayer : onlinePlayers) {
if (!chatPlayer.getName().equals(target.getName()) && !chatPlayer.getName().equals(sender.getName())) {
chatPlayer.sendMessage(sender.getName() + ChatColor.GOLD + " reduced " + ChatColor.WHITE + target.getName() + ChatColor.GOLD + "'s reputation!");
}
else if (!chatPlayer.getName().equals(sender.getName())) {
chatPlayer.sendMessage(sender.getName() + ChatColor.RED + " reduced your reputation!");
chatPlayer.sendMessage(ChatColor.GOLD + "Type " + ChatColor.WHITE + "/votelist" + ChatColor.GOLD + " to check your reputation.");
}
}
if (griefList.equals("")) {
griefList = sender.getName();
}
else {
griefList = griefList + "," + sender.getName();
}
this.usersConfig.set(target.getName().toLowerCase() + ".griefer", griefList);
griefArray = griefList.split(",");
int rep = 0;
if (voteArray != null) {
rep += voteArray.length;
}
if (griefArray != null) {
rep -= griefArray.length;
}
if (target.isOnline() && rep < approvalVotes && target.getPlayer().hasPermission("greylistvote.build") && !target.getPlayer().hasPermission("greylistvote.approved")) {
// Enough votes received
this.setGriefer(target.getPlayer());
}
else if (!target.isOnline() && rep < approvalVotes) {
for (Player chatPlayer : onlinePlayers) {
if (!chatPlayer.getName().equals(target.getName())) {
chatPlayer.sendMessage(target.getName() + ChatColor.GOLD + "'s reputation has dropped below " + approvalVotes + "!");
}
}
}
this.saveUsersConfig();
return true;
}
}
else if (commandLabel.equalsIgnoreCase("votelist") || commandLabel.equalsIgnoreCase("glvlist") || commandLabel.equalsIgnoreCase("rep")) {
if (args == null || args.length == 0) {
String voteList = this.usersConfig.getString(sender.getName().toLowerCase() + ".votes", null);
String griefList = this.usersConfig.getString(sender.getName().toLowerCase() + ".griefer", null);
if (voteList == null && griefList == null) {
sender.sendMessage(ChatColor.GOLD + "You have not received any votes.");
sender.sendMessage(ChatColor.GOLD + "Current Reputation: " + ChatColor.WHITE + "0");
sender.sendMessage(ChatColor.GOLD + "Required Reputation: " + ChatColor.WHITE + approvalVotes);
}
else {
sender.sendMessage(ChatColor.GOLD + "You have received votes from:");
int reputation = 0;
boolean serverVote = false;
String[] voteArray;
String[] griefArray;
if (voteList != null) {
voteArray = voteList.split(",");
if (voteArray.length != 0) {
String votes = ChatColor.GREEN + " Approvals: " + ChatColor.GOLD;
for (String vote : voteArray) {
votes = votes + vote + " ";
if (vote.equals("Server")) {
serverVote = true;
}
reputation ++;
}
if (serverVote) {
reputation = approvalVotes;
}
sender.sendMessage(votes);
}
}
if (griefList != null) {
griefArray = griefList.split(",");
if (griefArray.length != 0) {
String votes = ChatColor.DARK_GRAY + " Black-Balls: " + ChatColor.GOLD;
serverVote = false;
for (String vote : griefArray) {
votes = votes + vote + " ";
if (vote.equals("Server")) {
serverVote = true;
}
reputation--;
}
if (serverVote) {
reputation = -1;
}
sender.sendMessage(votes);
}
}
String repText;
if (reputation >= approvalVotes) {
repText = " " + ChatColor.GREEN + reputation;
}
else {
repText = " " + ChatColor.RED + reputation;
}
sender.sendMessage(ChatColor.GOLD + "Current Reputation:" + repText);
sender.sendMessage(ChatColor.GOLD + "Required Reputation: " + ChatColor.WHITE + approvalVotes);
}
return true;
}
else {
OfflinePlayer checktarget = getServer().getOfflinePlayer(args[0]);
String DN = null;
String target = null;
if (checktarget.isOnline()) {
target = checktarget.getPlayer().getName();
DN = checktarget.getPlayer().getDisplayName();
}
else {
if (checktarget != null) {
target = checktarget.getName();
DN = checktarget.getName();
}
}
if (target == null) {
// Player not found
sender.sendMessage(args[0] + ChatColor.RED + " not found!");
return false;
}
String voteList = this.usersConfig.getString(target.toLowerCase() + ".votes", null);
String griefList = this.usersConfig.getString(target.toLowerCase() + ".griefer", null);
if (voteList == null && griefList == null) {
sender.sendMessage(DN + ChatColor.GOLD + " has not received any votes.");
sender.sendMessage(ChatColor.GOLD + "Current Reputation: " + ChatColor.WHITE + "0");
sender.sendMessage(ChatColor.GOLD + "Required Reputation: " + ChatColor.WHITE + approvalVotes);
}
else {
sender.sendMessage(DN + ChatColor.GOLD + " has received votes from:");
int reputation = 0;
boolean serverVote = false;
String[] voteArray;
String[] griefArray;
if (voteList != null) {
voteArray = voteList.split(",");
if (voteArray.length != 0) {
String votes = ChatColor.GREEN + " Approvals: " + ChatColor.GOLD;
for (String vote : voteArray) {
votes = votes + vote + " ";
if (vote.equals("Server")) {
serverVote = true;
}
reputation ++;
}
if (serverVote) {
reputation = approvalVotes;
}
sender.sendMessage(votes);
}
}
if (griefList != null) {
griefArray = griefList.split(",");
if (griefArray.length != 0) {
String votes = ChatColor.DARK_GRAY + " Black-Balls: " + ChatColor.GOLD;
serverVote = false;
for (String vote : griefArray) {
votes = votes + vote + " ";
if (vote.equals("Server")) {
serverVote = true;
}
reputation--;
}
if (serverVote) {
reputation = -1;
}
sender.sendMessage(votes);
}
}
String repText;
if (reputation >= approvalVotes) {
repText = " " + ChatColor.GREEN + reputation;
}
else {
repText = " " + ChatColor.RED + reputation;
}
sender.sendMessage(ChatColor.GOLD + "Current Reputation:" + repText);
sender.sendMessage(ChatColor.GOLD + "Required Reputation: " + ChatColor.WHITE + approvalVotes);
}
return true;
}
}
return false;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.