code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
package lv.bond.science.nnstudio;
import lv.bond.science.nnstudio.ui.errorgraph.ErrorGraphView;
import lv.bond.science.nnstudio.ui.imageloader.ImageLoadView;
import lv.bond.science.nnstudio.ui.netsetup.NetSetupView;
import lv.bond.science.nnstudio.ui.testgraph.TestGraphView;
import lv.bond.science.nnstudio.ui.testresult.TestResultView;
import org.eclipse.ui.IFolderLayout;
import org.eclipse.ui.IPageLayout;
import org.eclipse.ui.IPerspectiveFactory;
public class Perspective implements IPerspectiveFactory {
public void createInitialLayout(IPageLayout layout) {
layout.addStandaloneView(
NetSetupView.ID,
true,
IPageLayout.LEFT,
0.22f,
IPageLayout.ID_EDITOR_AREA);
IFolderLayout right = layout.createFolder(
"right",
IPageLayout.RIGHT,
0.78f,
IPageLayout.ID_EDITOR_AREA);
right.addView(ErrorGraphView.ID);
right.addView(TestGraphView.ID);
right.addView(TestResultView.ID);
/*
IFolderLayout folder = layout.createFolder("messages", IPageLayout.TOP, 0.5f, editorArea);
folder.addPlaceholder(View.ID + ":*");
folder.addView(View.ID);
*/
layout.addView(
ImageLoadView.ID,
IPageLayout.BOTTOM,
0.78f,
"right");
layout.getViewLayout(NetSetupView.ID).setCloseable(false);
layout.getViewLayout(ErrorGraphView.ID).setCloseable(false);
layout.getViewLayout(TestGraphView.ID).setCloseable(false);
layout.getViewLayout(ImageLoadView.ID).setCloseable(false);
layout.addShowViewShortcut(NetSetupView.ID);
layout.addShowViewShortcut(ErrorGraphView.ID);
layout.addShowViewShortcut(TestGraphView.ID);
layout.addShowViewShortcut(ImageLoadView.ID);
layout.setEditorAreaVisible(false);
}
}
| Java |
package lv.bond.science.nnstudio;
import org.eclipse.core.runtime.IPlatformRunnable;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.PlatformUI;
/**
* This class controls all aspects of the application's execution
*/
public class NNStudioApplication implements IPlatformRunnable {
/* (non-Javadoc)
* @see org.eclipse.core.runtime.IPlatformRunnable#run(java.lang.Object)
*/
public Object run(Object args) throws Exception {
Display display = PlatformUI.createDisplay();
try {
int returnCode = PlatformUI.createAndRunWorkbench(display, new ApplicationWorkbenchAdvisor());
if (returnCode == PlatformUI.RETURN_RESTART) {
return IPlatformRunnable.EXIT_RESTART;
}
return IPlatformRunnable.EXIT_OK;
} finally {
display.dispose();
}
}
}
| Java |
package lv.bond.science.nnstudio.core;
public class NetworkParams {
private double learnRate = 0.0;
private double sigmoidStep = 0.0;
private double learnRateDecrease = 0.0;
private int inputDimX = 0;
private int inputDimY = 0;
private int hiddenDim = 0;
private int outputDim = 0;
private int epochsCount = 0;
public int getHiddenDim() {
return hiddenDim;
}
public void setHiddenDim(int hiddenDim) {
this.hiddenDim = hiddenDim;
}
public int getInputDimX() {
return inputDimX;
}
public void setInputDimX(int inputDimX) {
this.inputDimX = inputDimX;
}
public int getInputDimY() {
return inputDimY;
}
public void setInputDimY(int inputDimY) {
this.inputDimY = inputDimY;
}
public double getLearnRate() {
return learnRate;
}
public void setLearnRate(double learnRate) {
this.learnRate = learnRate;
}
public double getLearnRateDecrease() {
return learnRateDecrease;
}
public void setLearnRateDecrease(double learnRateDecrease) {
this.learnRateDecrease = learnRateDecrease;
}
public int getOutputDim() {
return outputDim;
}
public void setOutputDim(int outputDim) {
this.outputDim = outputDim;
}
public double getSigmoidStep() {
return sigmoidStep;
}
public void setSigmoidStep(double sigmoidStep) {
this.sigmoidStep = sigmoidStep;
}
public int getEpochsCount() {
return epochsCount;
}
public void setEpochsCount(int epochsCount) {
this.epochsCount = epochsCount;
}
}
| Java |
package lv.bond.science.nnstudio.core;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import lv.bond.ann.mlp.IActFunction;
import lv.bond.ann.mlp.IErrorCalculator;
import lv.bond.ann.mlp.MlpNet;
import lv.bond.ann.mlp.MlpNetFactory;
import lv.bond.ann.mlp.MlpNeuron;
import lv.bond.ann.mlp.MlpParamsContainer;
import lv.bond.ann.mlp.TargetValuesContainer;
import lv.bond.ann.mlp.impl.MlpNetFactoryImpl;
import lv.bond.ann.net.model.Layer;
import lv.bond.ann.net.model.NetFactory;
import lv.bond.ann.net.model.impl.NetFactoryImpl;
import lv.bond.science.nnstudio.model.ImagesBean;
import lv.bond.science.nnstudio.ui.errorgraph.ErrorGraphView;
import lv.bond.science.nnstudio.ui.testgraph.TestGraphView;
import lv.bond.science.nnstudio.ui.testresult.TestResultView;
public class MlpModel {
private MlpNetFactory mlpFactory = new MlpNetFactoryImpl();
private NetFactory netFactory = new NetFactoryImpl();
private MlpNet mlpNet = mlpFactory.createMlpNet();
private boolean isInitalized = false;
private int epochsCount = 0;
private ArrayList epochsErrors = new ArrayList();
public MlpModel() {
}
public void createMlpNet(NetworkParams params) {
this.epochsCount = params.getEpochsCount();
// Prepare network
// Each neurons IErrorCalculator must be conected to
// MlpNet -> TargetValuesContainer
// Create Target Values Container
TargetValuesContainer targetsContainer =
mlpFactory.createTargetValuesContainer();
mlpNet.setTargetValuesContainer( targetsContainer );
// Create Params Container
MlpParamsContainer paramsContainer =
mlpFactory.createMlpParamsContainer();
paramsContainer.setLearnRate(params.getLearnRate());
paramsContainer.setLearnRateDecreaseCoef(params.getLearnRateDecrease());
paramsContainer.setSigmoidStepCoef(params.getSigmoidStep());
mlpNet.setParamsContainer( paramsContainer );
// Error calculators
IErrorCalculator errCalculatorHidden =
mlpFactory.createHiddenErrorCalculator();
errCalculatorHidden.setCalculatorName( "hidden" );
errCalculatorHidden.setTargetValuesContainer( targetsContainer );
mlpNet.getErrorCalculators().put(
"hidden",
errCalculatorHidden);
IErrorCalculator errCalculatorOutput = mlpFactory.createOutputErrorCalculator();
errCalculatorOutput.setCalculatorName( "output" );
errCalculatorOutput.setTargetValuesContainer( targetsContainer );
mlpNet.getErrorCalculators().put(
"output",
errCalculatorOutput);
// ActFunctions
IActFunction actFunctionPlain =
mlpFactory.createPlainActFunction();
actFunctionPlain.setNameOfFunction("plain");
actFunctionPlain.setParamsContainer( paramsContainer );
mlpNet.getActFunctions().put(
"plain",
actFunctionPlain);
IActFunction actFunctionSigmoid =
mlpFactory.createSigmoidActFunction();
actFunctionSigmoid.setNameOfFunction("sigmoid");
actFunctionSigmoid.setParamsContainer( paramsContainer );
mlpNet.getActFunctions().put(
"sigmoid",
actFunctionSigmoid);
//Create & register Layers
Layer inputLayer = netFactory.createLayer();
inputLayer.setLayerName( "input" );
Layer biasLayer = netFactory.createLayer();
biasLayer.setLayerName( "bias" );
Layer hiddenLayer = netFactory.createLayer();
hiddenLayer.setLayerName( "hidden" );
Layer outputLayer = netFactory.createLayer();
outputLayer.setLayerName( "output" );
mlpNet.getLayers().put("input", inputLayer);
mlpNet.getLayers().put("bias", biasLayer);
mlpNet.getLayers().put("hidden", hiddenLayer);
mlpNet.getLayers().put("output", outputLayer);
// Neurons
mlpNet.addNeurons(
(params.getInputDimX() //63
*
params.getInputDimY()),
"plain",
"hidden",
inputLayer);
mlpNet.addNeurons(
1,
"plain",
"hidden",
biasLayer);
mlpNet.addNeurons(
params.getHiddenDim()-1, //63
"sigmoid",
"hidden",
hiddenLayer);
mlpNet.addNeurons(
params.getOutputDim(), //3
"sigmoid",
"output",
outputLayer);
mlpNet.connectLayers(inputLayer, hiddenLayer);
mlpNet.connectLayers(biasLayer, hiddenLayer);
mlpNet.connectLayers(biasLayer, outputLayer);
mlpNet.connectLayers(hiddenLayer, outputLayer);
// Network ready
this.isInitalized = true;
}
@SuppressWarnings("unchecked")
public void runMlp() {
if (this.mlpFactory == null) {
return;
}
//MlpNetFactory mlpFactory = new MlpNetFactoryImpl();
//NetFactory netFactory = new NetFactoryImpl();
//MlpNet mlpNet = mlpFactory.createMlpNet();
//this.createMlpNet( mlpNet );
ImagesBean bean = ImagesBean.getInstance();
HashMap<Integer, HashMap> inputsForEpoch =
this.setupMlpEpochInputs(bean.getFileNameTrainData());
HashMap<Integer, HashMap> targetsForEpoch =
this.setupMlpEpochTargets(bean.getFileNameTrainTargetData());
// Bias input is always 1.0
HashMap bias = new HashMap();
bias.put(0, 1.0);
mlpNet.loadLayerInputs(
(Layer) mlpNet.getLayers().get("bias"),
bias);
HashMap printOrderOfLayers = new HashMap();
printOrderOfLayers.put(0, "input");
printOrderOfLayers.put(1, "bias");
printOrderOfLayers.put(2, "hidden");
printOrderOfLayers.put(3, "output");
int errBufferSize = 5;
float[] errorsBuffer = new float[errBufferSize];
int bufferPosition = 0;
for (int epoch = 1; epoch <= this.epochsCount; epoch++ ) {
Double epochError = 0.0;
//Iterator iterKeys = inputsForEpoch.keySet().iterator();
//while (iterKeys.hasNext()) {
for (Integer keyInt = 0; keyInt < inputsForEpoch.keySet().size(); keyInt++) {
//Integer keyInt = (Integer) iterKeys.next();
mlpNet.loadLayerInputs(
(Layer) mlpNet.getLayers().get("input"),
(HashMap) inputsForEpoch.get(keyInt) );
TargetValuesContainer targetValuesContainer =
mlpNet.getTargetValuesContainer();
targetValuesContainer.setValues(
(Map) targetsForEpoch.get( keyInt ) );
//System.out.println("================= BEFORE RUN");
//printNet(mlpNet, printOrderOfLayers);
this.runMlpSignal( mlpNet );
//System.out.println("================= BEFORE ERROR");
//printNet(mlpNet, printOrderOfLayers);
this.runMlpError( mlpNet );
//System.out.println("================= BEFORE TEACHING");
//printNet(mlpNet, printOrderOfLayers);
this.runMlpTeach( mlpNet );
//double out = (Double) mlpNet.readLayerOutputs(
// (Layer) mlpNet.getLayers().get( "output" ) ).get( 0 );
//System.out.println("++++");
//System.out.println("out="+out+";");
double netError = mlpNet.calculateNetworkError();
epochError += netError;
//System.out.println("================= AFTER TEACHING");
//printNet(mlpNet, printOrderOfLayers);
}
//System.out.println();
String epochErrorText = "epoch Nr."+epoch+"; error = "+epochError+";" + "\n";
System.out.print(epochErrorText);
//view.trainLogTextArea.setText(
// view.trainLogTextArea.getText() +
// epochErrorText);
epochsErrors.add(epochError);
if (bufferPosition == errBufferSize) {
ErrorGraphView.appendToDataSet(errorsBuffer);
bufferPosition = 0;
errorsBuffer = new float[errBufferSize];
} else {
errorsBuffer[bufferPosition] =
epochError.floatValue();
bufferPosition++;
}
// at the end of each epoch - decrease learn rate
double newLearnRate =
mlpNet.getParamsContainer().getLearnRate() *
mlpNet.getParamsContainer().getLearnRateDecreaseCoef();
mlpNet.getParamsContainer().setLearnRate( newLearnRate );
}
// TODO - flush to graph error Buffer
float[] flushBuffer = new float[bufferPosition];
for (int i = 0; i < flushBuffer.length ; i++) {
flushBuffer[i] = errorsBuffer[i];
ErrorGraphView.appendToDataSet(flushBuffer);
}
}
public void runTesting() {
ImagesBean bean = ImagesBean.getInstance();
HashMap<Integer, HashMap> inputsForEpoch =
this.setupMlpEpochInputs(bean.getFileNameTestData());
HashMap<Integer, HashMap> targetsForEpoch =
this.setupMlpEpochTargets(bean.getFileNameTestTargetData());
// TESTING
System.out.println("Testing:");
//inputsForEpoch = this.setupMlpEpochInputsForTest();
for (Integer keyInt = 0; keyInt < inputsForEpoch.keySet().size(); keyInt++) {
//Integer keyInt = (Integer) iterKeys.next();
mlpNet.loadLayerInputs(
(Layer) mlpNet.getLayers().get("input"),
(HashMap) inputsForEpoch.get(keyInt) );
TargetValuesContainer targetValuesContainer =
mlpNet.getTargetValuesContainer();
targetValuesContainer.setValues(
(Map) targetsForEpoch.get( keyInt ) );
this.runMlpSignal( mlpNet );
Iterator iterNeurons =
((Layer) mlpNet.getLayers().get("output"))
.getNeurons().values().iterator();
while (iterNeurons.hasNext()) {
MlpNeuron neuron = (MlpNeuron) iterNeurons.next();
String testResultForIteration =
"neuron id="+neuron.getNeuronId()+"; out="+neuron.getOutput();
System.out.println(testResultForIteration);
//view.testsLogsTextArea.setText(
// view.testsLogsTextArea.getText() +
// testResultForIteration + "\t");
}
double netError = this.mlpNet.calculateNetworkError();
System.out.println("NET ERROR = "+netError);
double[] e = new double[1];
e[0] = netError;
TestGraphView.appendToDataSet( e , keyInt);
////// fill classification results
int winnerNeuronId =
this.getWinnerNeuronId();
int resultTargetVectorId =
this.getResultVectorId();
lv.bond.science.nnstudio.ui.testresult.TestResult tResult =
new lv.bond.science.nnstudio.ui.testresult.TestResult(
winnerNeuronId,
resultTargetVectorId);
TestResultView.addTestResult(tResult);
}
}
private int getResultVectorId() {
Map targetMap = this.mlpNet.getTargetValuesContainer().getValues();
return getKeyOfMaximumValue(targetMap);
}
private int getKeyOfMaximumValue(Map map) {
int keyOfMaxValue = -1;
double maxValue = Double.MIN_VALUE;
Iterator iter = map.keySet().iterator();
while (iter.hasNext()) {
Integer key = (Integer) iter.next();
Double value = (Double) map.get(key);
if (value > maxValue) {
keyOfMaxValue = key;
maxValue = value;
}
}
return keyOfMaxValue;
}
private int getWinnerNeuronId() {
HashMap outputMap = new HashMap();
outputMap = this.mlpNet.readLayerOutputs(
(Layer) this.mlpNet.getLayers().get("output") );
return getKeyOfMaximumValue(outputMap);
}
private double[] listToArray(ArrayList list) {
double[] result = new double[list.size()];
int i = 0;
for (Iterator iter = list.iterator(); iter.hasNext();) {
double d = (Double) iter.next();
result[i] = d;
i++;
}
return result;
}
private HashMap<Integer, HashMap> setupMlpEpochInputs(String path) {
HashMap<Integer, HashMap> inputsForEpoch =
new HashMap<Integer, HashMap>();
//ImagesBean bean = ImagesBean.getInstance();
Image trainImage = new Image(null, path);//bean.getFileNameTrainData());
ImageData trainImageData = trainImage.getImageData();
// height of one Image is equal to width
int height = trainImageData.height;
int width = trainImageData.width;
if (width % (height + 1) != 0) {
System.out.println("Wrong format of train data!");
return null;
}
int countOfImages = width / (height + 1);
for (int imageNo = 0; imageNo < countOfImages; imageNo++) {
HashMap inputValues = new HashMap();
// for all lines
for (int lineNo = 0; lineNo < height; lineNo ++) {
ArrayList imageRow = new ArrayList();
// for all columns in current image
for (int columnNo = 0; columnNo < height; columnNo++) {
int x =(imageNo*(height+1))+columnNo;
int y =lineNo;
int in = trainImage.getImageData().getPixel(x, y);
switch (in) {
case -1: in = 0; break;
case 255: in = 1; break;
};
System.out.println("x="+x+"; y="+y+"; in="+in+";");
imageRow.add(new Double(in));
}
//double[] inputRow = (Double[]) imageRow.toArray();
put(inputValues, listToArray(imageRow));
}
inputsForEpoch.put(imageNo, inputValues );
}
/*
// Setup inputs
HashMap inputValues = new HashMap();
put( inputValues, getDouble("0,0,0,1,0,0,0") );
put( inputValues, getDouble("0,0,0,1,0,0,0") );
put( inputValues, getDouble("0,0,0,1,0,0,0") );
put( inputValues, getDouble("0,0,1,0,1,0,0") );
put( inputValues, getDouble("0,0,1,0,1,0,0") );
put( inputValues, getDouble("0,1,0,0,0,1,0") );
put( inputValues, getDouble("0,1,1,1,1,1,0") );
put( inputValues, getDouble("0,1,0,0,0,1,0") );
put( inputValues, getDouble("0,1,0,0,0,1,0") );
inputsForEpoch.put(0, inputValues );
inputValues = new HashMap();
put( inputValues, getDouble("1,1,1,1,1,1,0") );
put( inputValues, getDouble("1,0,0,0,0,0,1") );
put( inputValues, getDouble("1,0,0,0,0,0,1") );
put( inputValues, getDouble("1,0,0,0,0,0,1") );
put( inputValues, getDouble("1,1,1,1,1,1,0") );
put( inputValues, getDouble("1,0,0,0,0,0,1") );
put( inputValues, getDouble("1,0,0,0,0,0,1") );
put( inputValues, getDouble("1,0,0,0,0,0,1") );
put( inputValues, getDouble("1,1,1,1,1,1,0") );
inputsForEpoch.put(1, inputValues );
inputValues = new HashMap();
put( inputValues, getDouble("0,0,1,1,1,0,0") );
put( inputValues, getDouble("0,1,0,0,0,1,0") );
put( inputValues, getDouble("1,0,0,0,0,0,1") );
put( inputValues, getDouble("1,0,0,0,0,0,0") );
put( inputValues, getDouble("1,0,0,0,0,0,0") );
put( inputValues, getDouble("1,0,0,0,0,0,0") );
put( inputValues, getDouble("1,0,0,0,0,0,1") );
put( inputValues, getDouble("0,1,0,0,0,1,0") );
put( inputValues, getDouble("0,0,1,1,1,0,0") );
inputsForEpoch.put(2, inputValues );
*/
return inputsForEpoch;
}
private HashMap<Integer, HashMap> setupMlpEpochInputsForTest() {
HashMap<Integer, HashMap> inputsForEpoch =
new HashMap<Integer, HashMap>();
// Setup inputs
HashMap inputValues = new HashMap();
put( inputValues, getDouble("0,0,0,1,0,0,0") );
put( inputValues, getDouble("0,0,0,1,0,0,0") );
put( inputValues, getDouble("0,0,1,0,1,0,0") );
put( inputValues, getDouble("0,1,0,0,0,1,0") );
put( inputValues, getDouble("1,0,0,0,0,0,1") );
put( inputValues, getDouble("1,0,0,0,0,0,1") );
put( inputValues, getDouble("1,1,1,1,1,1,1") );
put( inputValues, getDouble("1,0,0,0,0,0,1") );
put( inputValues, getDouble("1,0,0,0,0,0,1") );
inputsForEpoch.put(0, inputValues );
inputValues = new HashMap();
put( inputValues, getDouble("1,1,1,1,1,1,0") );
put( inputValues, getDouble("0,1,0,0,0,0,1") );
put( inputValues, getDouble("0,1,0,0,0,0,1") );
put( inputValues, getDouble("0,1,0,0,0,0,1") );
put( inputValues, getDouble("0,1,1,1,1,1,0") );
put( inputValues, getDouble("0,1,0,0,0,0,1") );
put( inputValues, getDouble("0,1,0,0,0,0,1") );
put( inputValues, getDouble("0,1,0,0,0,0,1") );
put( inputValues, getDouble("1,1,1,1,1,1,0") );
inputsForEpoch.put(1, inputValues );
inputValues = new HashMap();
put( inputValues, getDouble("0,1,1,1,1,0,0") );
put( inputValues, getDouble("1,0,0,0,0,1,0") );
put( inputValues, getDouble("1,0,0,0,0,0,0") );
put( inputValues, getDouble("1,0,0,0,0,0,0") );
put( inputValues, getDouble("1,0,0,0,0,0,0") );
put( inputValues, getDouble("1,0,0,0,0,0,0") );
put( inputValues, getDouble("1,0,0,0,0,0,0") );
put( inputValues, getDouble("1,0,0,0,0,1,0") );
put( inputValues, getDouble("0,1,1,1,1,0,0") );
inputsForEpoch.put(2, inputValues );
return inputsForEpoch;
}
@SuppressWarnings("unchecked")
private HashMap<Integer, HashMap> setupMlpEpochTargets(String pathToTargetsImage) {
HashMap<Integer, HashMap> targetsForEpoch =
new HashMap<Integer, HashMap>();
//ImagesBean bean = ImagesBean.getInstance();
Image trainImage = new Image(null, pathToTargetsImage);//bean.getFileNameTrainTargetData());
ImageData trainImageData = trainImage.getImageData();
// height of one Image is equal to width
int height = trainImageData.height;
int width = trainImageData.width;
//if (width % (height + 1) != 0) {
// System.out.println("Wrong format of train data!");
// return null;
//}
// each row is target vector
// for each row
for (int rowNo = 0; rowNo < height; rowNo++) {
HashMap targetValues = new HashMap();
//for all columns
for (int columnNo = 0; columnNo < width; columnNo++ ) {
int x = columnNo;
int y = rowNo;
int in = trainImage.getImageData().getPixel(x, y);
switch (in) {
case -1: in = 0; break;
case 255: in = 1; break;
};
System.out.println("x="+x+"; y="+y+"; in="+in+";");
targetValues.put( columnNo, new Double(in) );
}
targetsForEpoch.put( rowNo, targetValues);
}
/*
// Setup new target value(s)
HashMap targetValues = new HashMap();
targetValues.put( 0, 1.0d );
targetValues.put( 1, 0.0d );
targetValues.put( 2, 0.0d );
targetsForEpoch.put( 0, targetValues);
targetValues = new HashMap();
targetValues.put( 0, 0.0d );
targetValues.put( 1, 1.0d );
targetValues.put( 2, 0.0d );
targetsForEpoch.put( 1, targetValues);
targetValues = new HashMap();
targetValues.put( 0, 0.0d );
targetValues.put( 1, 0.0d );
targetValues.put( 2, 1.0d );
targetsForEpoch.put( 2, targetValues);
*/
return targetsForEpoch;
}
@SuppressWarnings("unchecked")
private void runMlpError( MlpNet mlpNet ) {
HashMap layersForErrorAndTeaching = new HashMap();
layersForErrorAndTeaching.put(new Integer( 0 ), "output" );
layersForErrorAndTeaching.put(new Integer( 1 ), "hidden" );
//layers.put(new Integer( 2 ), "input" );
mlpNet.propagateError( layersForErrorAndTeaching );
}
@SuppressWarnings("unchecked")
private void runMlpTeach( MlpNet mlpNet ) {
HashMap layersForErrorAndTeaching = new HashMap();
layersForErrorAndTeaching.put(new Integer( 0 ), "output" );
layersForErrorAndTeaching.put(new Integer( 1 ), "hidden" );
//layers.put(new Integer( 2 ), "input" );
//mlpNet.propagateError( layersForErrorAndTeaching );
mlpNet.teachLayers( layersForErrorAndTeaching );
}
@SuppressWarnings("unchecked")
private void runMlpSignal( MlpNet mlpNet ) {
HashMap signalRun = new HashMap();
signalRun.put(0, "hidden");
signalRun.put(1, "output");
mlpNet.runSignal( signalRun );
}
private double[] getDouble(String str) {
String[] strs = str.split(",");
double[] result = new double[strs.length];
for (int i = 0; i < strs.length; i++) {
result[i] = Double.valueOf(strs[i]);
}
return result;
}
@SuppressWarnings("unchecked")
private void put(Map map, double[] d) {
for (int count = 0; count < d.length; count++ ) {
map.put( map.size(), d[count] );
}
}
public boolean isInitalized() {
return isInitalized;
}
public MlpNet getMlpNet() {
return mlpNet;
}
public ArrayList getEpochsErrors() {
return epochsErrors;
}
}
| Java |
package lv.bond.science.nnstudio.ui.testresult;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.part.ViewPart;
public class TestResultView extends ViewPart {
public static final String ID =
"lv.bond.science.nnstudio.ui.testresult.TestResultView";
// Needs to be whatever is mentioned in plugin.xml
private Composite top = null;
private Table testResultTable = null;
private static TableViewer tableViewer = null;
private static List<TestResult> model = new ArrayList<TestResult>(); // @jve:decl-index=0:
private ArrayContentProvider contentProvider = null; // @jve:decl-index=0:
private Label errorPercentLabel = null;
private static Text errorPercentText = null;
@Override
public void createPartControl(Composite parent) {
GridData gridData2 = new GridData();
gridData2.grabExcessHorizontalSpace = true;
gridData2.verticalAlignment = GridData.CENTER;
gridData2.horizontalAlignment = GridData.BEGINNING;
GridData gridData1 = new GridData();
gridData1.horizontalAlignment = GridData.FILL;
gridData1.grabExcessHorizontalSpace = false;
gridData1.verticalAlignment = GridData.CENTER;
GridData gridData = new GridData();
gridData.widthHint = 220;
gridData.horizontalAlignment = GridData.FILL;
gridData.verticalAlignment = GridData.FILL;
gridData.grabExcessHorizontalSpace = true;
gridData.grabExcessVerticalSpace = true;
gridData.horizontalSpan = 2;
gridData.heightHint = 120;
GridLayout gridLayout = new GridLayout();
gridLayout.numColumns = 2;
top = new Composite(parent, SWT.NONE);
top.setLayout(gridLayout);
testResultTable = new Table(top, SWT.BORDER | SWT.MULTI);
testResultTable.setHeaderVisible(true);
testResultTable.setLayoutData(gridData);
testResultTable.setLinesVisible(true);
errorPercentLabel = new Label(top, SWT.RIGHT);
errorPercentLabel.setText("Errors %");
errorPercentLabel.setLayoutData(gridData1);
errorPercentText = new Text(top, SWT.BORDER);
errorPercentText.setEditable(false);
errorPercentText.setLayoutData(gridData2);
TableColumn tableColumn = new TableColumn(testResultTable, SWT.NONE);
tableColumn.setWidth(170);
tableColumn.setText("Classification - Winner Neuron");
TableColumn tableColumn1 = new TableColumn(testResultTable, SWT.NONE);
tableColumn1.setWidth(130);
tableColumn1.setText("Target Winner Neuron");
TableColumn tableColumn2 = new TableColumn(testResultTable, SWT.NONE);
tableColumn2.setWidth(60);
tableColumn2.setText("Match");
tableViewer = new TableViewer(testResultTable);
tableViewer.setLabelProvider(new TestResultLabelProvider());
contentProvider = new ArrayContentProvider();
tableViewer.setContentProvider(contentProvider);
//model = TestResult.example();
tableViewer.setInput(model);
}
public static void addToTableRow() {
int index = model.size()+1;
TestResult tr = new TestResult(index, (index%2 == 0) ? index: index+1);
addTestResult(tr);
}
public static void addTestResult(TestResult tr) {
model.add(tr);
tableViewer.add(tr);
errorPercentText.setText(getErrorsPercent()+"");
}
@Override
public void setFocus() {
testResultTable.setFocus();
}
private static double getErrorsPercent() {
int testsCount = model.size();
int errorsCount = 0;
for (Iterator iter = model.iterator(); iter.hasNext();) {
TestResult tr = (TestResult) iter.next();
if ( !tr.isMatching()) {
errorsCount++;
}
}
return ( (errorsCount * 100) / testsCount );
}
}
| Java |
package lv.bond.science.nnstudio.ui.testresult;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.swt.graphics.Image;
public class TestResultLabelProvider extends LabelProvider implements ITableLabelProvider {
public Image getColumnImage(Object element, int columnIndex) {
return null;
}
public String getColumnText(Object element, int columnIndex) {
if (element instanceof TestResult) {
TestResult result = (TestResult)element;
switch (columnIndex) {
case 0: return result.getNearestResultingVectorId()+"";
case 1: return result.getTargetVectorId()+"";
case 2: return (result.isMatching()) ? "Ok" : "ERROR";
default:
return "Unknown column index - "+columnIndex;
}
} else {
return "unknown data type";
}
}
}
| Java |
package lv.bond.science.nnstudio.ui.testresult;
import java.util.ArrayList;
import java.util.List;
public class TestResult {
private int nearestResultingVectorId;
private int targetVectorId;
public TestResult(int nearestResultingVectorId,
int targetVectorId)
{
this.nearestResultingVectorId = nearestResultingVectorId;
this.targetVectorId = targetVectorId;
}
public boolean isMatching() {
return (nearestResultingVectorId ==
targetVectorId);
}
public int getNearestResultingVectorId() {
return nearestResultingVectorId;
}
public void setNearestResultingVectorId(int nearestResultingVectorId) {
this.nearestResultingVectorId = nearestResultingVectorId;
}
public int getTargetVectorId() {
return targetVectorId;
}
public void setTargetVectorId(int targetVectorId) {
this.targetVectorId = targetVectorId;
}
public static List<TestResult> example() {
ArrayList<TestResult> result =
new ArrayList<TestResult>();
//TestResult[] exampleData = new TestResult[4];
TestResult tr1 = new TestResult(1, 1);
TestResult tr2 = new TestResult(1, 2);
TestResult tr3 = new TestResult(3, 3);
TestResult tr4 = new TestResult(4, 4);
result.add(tr1);
result.add(tr2);
result.add(tr3);
result.add(tr4);
//exampleData[0] = tr1;
//exampleData[1] = tr2;
//exampleData[2] = tr3;
//exampleData[3] = tr4;
return result;//exampleData;
}
}
| Java |
package lv.bond.science.nnstudio.ui.netsetup;
import lv.bond.science.nnstudio.core.MlpModel;
import lv.bond.science.nnstudio.core.NetworkParams;
import lv.bond.science.nnstudio.model.ImagesBean;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.part.ViewPart;
public class NetSetupView extends ViewPart {
public static final String ID = "lv.bond.science.nnstudio.ui.netsetup.NetSetupView";
// Needs to be whatever is mentioned in plugin.xml // @jve:decl-index=0:
private Composite top = null;
private Label xDimLabel = null;
private Text xDimText = null;
private Label yDimLabel = null;
private Text yDimText = null;
private Label hiddenDimLabel = null;
private Text hiddenText = null;
private Label outputDimLabel = null;
private Text outputDimText = null;
private Label leranRateLabel = null;
private Label learnDecreaseRateLabel = null;
private Label sigmoidStepCoefLabel = null;
private Text learnRateText = null;
private Text learnDecreaseCoefText = null;
private Text sigmoidStepCoefText = null;
private Button createAndTrainbutton = null;
private Button testButton = null;
private MlpModel mlpModel = null; // @jve:decl-index=0:
private Label epochsCountLabel = null;
private Text epochsCountText = null;
@Override
public void createPartControl(Composite parent) {
// TODO Auto-generated method stub
GridData gridData22 = new GridData();
gridData22.horizontalSpan = 3;
gridData22.verticalAlignment = GridData.CENTER;
gridData22.horizontalAlignment = GridData.FILL;
GridData gridData12 = new GridData();
gridData12.horizontalAlignment = GridData.END;
gridData12.verticalAlignment = GridData.CENTER;
GridData gridData15 = new GridData();
gridData15.verticalAlignment = GridData.CENTER;
gridData15.horizontalSpan = 3;
gridData15.horizontalAlignment = GridData.FILL;
GridData gridData111 = new GridData();
gridData111.horizontalSpan = 3;
gridData111.verticalAlignment = GridData.CENTER;
gridData111.horizontalAlignment = GridData.FILL;
GridData gridData10 = new GridData();
gridData10.horizontalSpan = 3;
gridData10.verticalAlignment = GridData.CENTER;
gridData10.horizontalAlignment = GridData.FILL;
GridData gridData9 = new GridData();
gridData9.horizontalSpan = 3;
gridData9.verticalAlignment = GridData.CENTER;
gridData9.horizontalAlignment = GridData.FILL;
GridData gridData8 = new GridData();
gridData8.horizontalSpan = 3;
gridData8.verticalAlignment = GridData.CENTER;
gridData8.horizontalAlignment = GridData.FILL;
GridData gridData7 = new GridData();
gridData7.horizontalAlignment = GridData.END;
gridData7.verticalAlignment = GridData.CENTER;
GridData gridData6 = new GridData();
gridData6.horizontalAlignment = GridData.END;
gridData6.verticalAlignment = GridData.CENTER;
GridData gridData5 = new GridData();
gridData5.horizontalAlignment = GridData.END;
gridData5.verticalAlignment = GridData.CENTER;
GridData gridData4 = new GridData();
gridData4.horizontalAlignment = GridData.END;
gridData4.verticalAlignment = GridData.CENTER;
GridData gridData31 = new GridData();
gridData31.horizontalAlignment = GridData.END;
gridData31.verticalAlignment = GridData.CENTER;
GridData gridData21 = new GridData();
gridData21.horizontalSpan = 3;
gridData21.verticalAlignment = GridData.CENTER;
gridData21.horizontalAlignment = GridData.FILL;
GridData gridData11 = new GridData();
gridData11.widthHint = 30;
GridData gridData3 = new GridData();
gridData3.horizontalSpan = 3;
gridData3.verticalAlignment = GridData.CENTER;
gridData3.horizontalAlignment = GridData.FILL;
GridData gridData2 = new GridData();
gridData2.horizontalIndent = 10;
gridData2.verticalAlignment = GridData.CENTER;
gridData2.horizontalAlignment = GridData.END;
GridData gridData1 = new GridData();
gridData1.horizontalIndent = 0;
gridData1.widthHint = 30;
GridData gridData = new GridData();
gridData.horizontalIndent = 10;
GridLayout gridLayout = new GridLayout();
gridLayout.numColumns = 4;
gridLayout.marginWidth = 5;
gridLayout.verticalSpacing = 5;
gridLayout.marginHeight = 5;
top = new Composite(parent, SWT.NONE);
top.setLayout(gridLayout);
xDimLabel = new Label(top, SWT.NONE);
xDimLabel.setText("X");
xDimLabel.setLayoutData(gridData2);
xDimText = new Text(top, SWT.BORDER);
xDimText.setEditable(false);
xDimText.setEnabled(false);
xDimText.setLayoutData(gridData1);
yDimLabel = new Label(top, SWT.NONE);
yDimLabel.setText("Y");
yDimLabel.setLayoutData(gridData);
yDimText = new Text(top, SWT.BORDER);
yDimText.setEditable(false);
yDimText.setEnabled(false);
yDimText.setLayoutData(gridData11);
hiddenDimLabel = new Label(top, SWT.NONE);
hiddenDimLabel.setText("Hidden Layer");
hiddenDimLabel.setLayoutData(gridData31);
hiddenText = new Text(top, SWT.BORDER);
hiddenText.setLayoutData(gridData3);
outputDimLabel = new Label(top, SWT.NONE);
outputDimLabel.setText("Output Layer");
outputDimLabel.setLayoutData(gridData4);
outputDimText = new Text(top, SWT.BORDER);
outputDimText.setEditable(false);
outputDimText.setEnabled(false);
outputDimText.setLayoutData(gridData21);
leranRateLabel = new Label(top, SWT.NONE);
leranRateLabel.setText("Learn Rate");
leranRateLabel.setLayoutData(gridData5);
learnRateText = new Text(top, SWT.BORDER);
learnRateText.setText("0.25");
learnRateText.setLayoutData(gridData8);
learnDecreaseRateLabel = new Label(top, SWT.NONE);
learnDecreaseRateLabel.setText("Learn Decrease");
learnDecreaseRateLabel.setLayoutData(gridData6);
learnDecreaseCoefText = new Text(top, SWT.BORDER);
learnDecreaseCoefText.setText("1.0");
learnDecreaseCoefText.setLayoutData(gridData9);
sigmoidStepCoefLabel = new Label(top, SWT.NONE);
sigmoidStepCoefLabel.setText("Sigmoid Step Coef");
sigmoidStepCoefLabel.setLayoutData(gridData7);
sigmoidStepCoefText = new Text(top, SWT.BORDER);
sigmoidStepCoefText.setText("1.0");
sigmoidStepCoefText.setLayoutData(gridData10);
epochsCountLabel = new Label(top, SWT.NONE);
epochsCountLabel.setText("Epochs Count");
epochsCountLabel.setLayoutData(gridData12);
epochsCountText = new Text(top, SWT.BORDER);
epochsCountText.setText("150");
epochsCountText.setLayoutData(gridData22);
Label filler12 = new Label(top, SWT.NONE);
createAndTrainbutton = new Button(top, SWT.NONE);
createAndTrainbutton.setText("Create and Train");
createAndTrainbutton.setLayoutData(gridData111);
createAndTrainbutton
.addSelectionListener(new org.eclipse.swt.events.SelectionAdapter() {
public void widgetSelected(org.eclipse.swt.events.SelectionEvent e) {
actionCreateAndRun();
}
});
Label filler13 = new Label(top, SWT.NONE);
testButton = new Button(top, SWT.NONE);
testButton.setText("Test");
testButton.setLayoutData(gridData15);
testButton.addSelectionListener(new org.eclipse.swt.events.SelectionAdapter() {
public void widgetSelected(org.eclipse.swt.events.SelectionEvent e) {
actionTest();
}
});
}
@Override
public void setFocus() {
this.hiddenText.setFocus();
}
private void actionCreateAndRun() {
this.mlpModel = new MlpModel();
NetworkParams params = new NetworkParams();
ImagesBean bean = ImagesBean.getInstance();
Image trainImage = new Image(null, bean.getFileNameTrainData());
ImageData trainImageData = trainImage.getImageData();
params.setInputDimX(trainImageData.height);
params.setInputDimY(trainImageData.height);
trainImage = new Image(null, bean.getFileNameTrainTargetData());
trainImageData = trainImage.getImageData();
params.setOutputDim(trainImageData.width);
params.setHiddenDim(
Integer.valueOf(this.hiddenText.getText()));
params.setLearnRate(
Double.valueOf(this.learnRateText.getText()));
params.setLearnRateDecrease(
Double.valueOf(this.learnDecreaseCoefText.getText()));
params.setSigmoidStep(
Double.valueOf(this.sigmoidStepCoefText.getText()));
params.setEpochsCount(
Integer.valueOf(this.epochsCountText.getText()));
this.mlpModel.createMlpNet(params);
this.mlpModel.runMlp();
}
private void actionTest() {
this.mlpModel.runTesting();
}
}
| Java |
package lv.bond.science.nnstudio.ui.imageloader;
import lv.bond.eclipse.imagecanvas.SWTImageCanvas;
import lv.bond.science.nnstudio.model.ImagesBean;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.part.ViewPart;
public class ImageLoadView extends ViewPart {
public static final String ID = "lv.bond.science.nnstudio.ui.imageloader.ImageLoadView";
// ID Needs to be whatever is mentioned in plugin.xml
private Composite top = null;
private Composite loadTrainDataComposite = null;
private Button loadTrainDataButton = null;
private Text trainDataPathText = null;
private Button loadTrainTargetsDataButton = null;
private Text trainTargetsDataPathText = null;
private Button clearTrainDataButton = null;
private Button clearTrainTargetDataButton = null;
private Button loadTestDataButton = null;
private Text testDataPathText = null;
private Button clearTestDataButton = null;
private Button loadTestTargetsDataButton = null;
private Text testTargetsDataPathText = null;
private Button clearTestTargetDataButton = null;
private SWTImageCanvas canvas = null;
public ImagesBean model = ImagesBean.getInstance(); // @jve:decl-index=0:
@Override
public void createPartControl(Composite parent) {
GridLayout gridLayout = new GridLayout();
gridLayout.numColumns = 2;
top = new Composite(parent, SWT.NONE);
top.setLayout(gridLayout);
createLoadTrainDataComposite();
createCanvas();
}
@Override
public void setFocus() {
loadTrainDataButton.setFocus();
}
/**
* This method initializes loadTrainDataComposite
*
*/
private void createLoadTrainDataComposite() {
GridData gridData11 = new GridData();
gridData11.horizontalAlignment = GridData.CENTER;
gridData11.verticalAlignment = GridData.BEGINNING;
GridData gridData7 = new GridData();
gridData7.horizontalAlignment = GridData.FILL;
gridData7.verticalAlignment = GridData.CENTER;
GridData gridData6 = new GridData();
gridData6.horizontalAlignment = GridData.FILL;
gridData6.verticalAlignment = GridData.CENTER;
GridData gridData3 = new GridData();
gridData3.horizontalAlignment = GridData.FILL;
gridData3.verticalAlignment = GridData.CENTER;
GridData gridData = new GridData();
gridData.horizontalAlignment = GridData.FILL;
gridData.verticalAlignment = GridData.CENTER;
GridData gridData5 = new GridData();
gridData5.horizontalAlignment = GridData.FILL;
gridData5.grabExcessHorizontalSpace = true;
gridData5.verticalAlignment = GridData.CENTER;
GridData gridData4 = new GridData();
gridData4.horizontalAlignment = GridData.FILL;
gridData4.widthHint = -1;
gridData4.verticalAlignment = GridData.CENTER;
GridData gridData2 = new GridData();
gridData2.horizontalAlignment = GridData.FILL;
gridData2.verticalAlignment = GridData.CENTER;
GridData gridData1 = new GridData();
gridData1.horizontalAlignment = GridData.FILL;
gridData1.grabExcessHorizontalSpace = true;
gridData1.widthHint = 120;
gridData1.verticalAlignment = GridData.CENTER;
GridLayout gridLayout1 = new GridLayout();
gridLayout1.numColumns = 3;
loadTrainDataComposite = new Composite(top, SWT.NONE);
loadTrainDataComposite.setLayout(gridLayout1);
loadTrainDataComposite.setLayoutData(gridData11);
loadTrainDataButton = new Button(loadTrainDataComposite, SWT.NONE);
loadTrainDataButton.setText("Load Train Data");
loadTrainDataButton.setLayoutData(gridData2);
loadTrainDataButton
.addSelectionListener(new org.eclipse.swt.events.SelectionAdapter() {
public void widgetSelected(org.eclipse.swt.events.SelectionEvent e) {
actionLoadTrainData();
}
});
trainDataPathText = new Text(loadTrainDataComposite, SWT.BORDER);
trainDataPathText.setEditable(false);
trainDataPathText.setEnabled(true);
trainDataPathText.setLayoutData(gridData1);
clearTrainDataButton = new Button(loadTrainDataComposite, SWT.NONE);
clearTrainDataButton.setText("X");
clearTrainDataButton
.addSelectionListener(new org.eclipse.swt.events.SelectionAdapter() {
public void widgetSelected(org.eclipse.swt.events.SelectionEvent e) {
System.out.println("trainData before clear -"+model.getFileNameTrainData());
actionClearTrainData();
System.out.println("trainData after clear -"+model.getFileNameTrainData());
}
});
loadTrainTargetsDataButton = new Button(loadTrainDataComposite, SWT.NONE);
loadTrainTargetsDataButton.setText("Load Target Data");
loadTrainTargetsDataButton.setLayoutData(gridData4);
loadTrainTargetsDataButton
.addSelectionListener(new org.eclipse.swt.events.SelectionAdapter() {
public void widgetSelected(org.eclipse.swt.events.SelectionEvent e) {
actionLoadTrainTargetsData();
}
});
trainTargetsDataPathText = new Text(loadTrainDataComposite, SWT.BORDER);
trainTargetsDataPathText.setEditable(false);
trainTargetsDataPathText.setEnabled(true);
trainTargetsDataPathText.setLayoutData(gridData5);
clearTrainTargetDataButton = new Button(loadTrainDataComposite, SWT.NONE);
clearTrainTargetDataButton.setText("X");
loadTestDataButton = new Button(loadTrainDataComposite, SWT.NONE);
loadTestDataButton.setText("Load Test Data");
loadTestDataButton.setLayoutData(gridData);
loadTestDataButton
.addSelectionListener(new org.eclipse.swt.events.SelectionAdapter() {
public void widgetSelected(org.eclipse.swt.events.SelectionEvent e) {
actionLoadTestData();
}
});
testDataPathText = new Text(loadTrainDataComposite, SWT.BORDER);
testDataPathText.setEditable(false);
testDataPathText.setEnabled(true);
testDataPathText.setLayoutData(gridData6);
clearTestDataButton = new Button(loadTrainDataComposite, SWT.NONE);
clearTestDataButton.setText("X");
clearTestDataButton
.addSelectionListener(new org.eclipse.swt.events.SelectionAdapter() {
public void widgetSelected(org.eclipse.swt.events.SelectionEvent e) {
actionClearTestData();
}
});
loadTestTargetsDataButton = new Button(loadTrainDataComposite, SWT.NONE);
loadTestTargetsDataButton.setText("Load Target Data");
loadTestTargetsDataButton.setLayoutData(gridData3);
loadTestTargetsDataButton
.addSelectionListener(new org.eclipse.swt.events.SelectionAdapter() {
public void widgetSelected(org.eclipse.swt.events.SelectionEvent e) {
actionLoadTestTargetsData();
}
});
testTargetsDataPathText = new Text(loadTrainDataComposite, SWT.BORDER);
testTargetsDataPathText.setEditable(false);
testTargetsDataPathText.setEnabled(true);
testTargetsDataPathText.setLayoutData(gridData7);
clearTestTargetDataButton = new Button(loadTrainDataComposite, SWT.NONE);
clearTestTargetDataButton.setText("X");
clearTestTargetDataButton
.addSelectionListener(new org.eclipse.swt.events.SelectionAdapter() {
public void widgetSelected(org.eclipse.swt.events.SelectionEvent e) {
actionClearTestTargetData();
}
});
clearTrainTargetDataButton
.addSelectionListener(new org.eclipse.swt.events.SelectionAdapter() {
public void widgetSelected(org.eclipse.swt.events.SelectionEvent e) {
actionClearTrainTargetData();
}
});
}
public void setTrainDataPathText(String pathName) {
this.trainDataPathText.setText(pathName);
}
public void clearTrainDataPathText() {
this.trainDataPathText.setText("");
}
public void setTrainTargetDataPathText(String pathName) {
this.trainTargetsDataPathText.setText(pathName);
}
public void clearTrainTargetDataPathText() {
this.trainTargetsDataPathText.setText("");
}
public void setTestDataPathText(String pathName) {
this.testDataPathText.setText(pathName);
}
public void clearTestDataPathText() {
this.testDataPathText.setText("");
}
public void setTestTargetDataPathText(String pathName) {
this.testTargetsDataPathText.setText(pathName);
}
public void clearTestTargetDataPathText() {
this.testTargetsDataPathText.setText("");
}
public void dispose() {
super.dispose();
canvas.dispose();
}
/**
* This method initializes canvas
*
*/
private void createCanvas() {
GridLayout gridLayout2 = new GridLayout();
gridLayout2.marginHeight = 5;
GridData gridData9 = new GridData();
gridData9.horizontalAlignment = GridData.FILL;
gridData9.grabExcessHorizontalSpace = true;
gridData9.grabExcessVerticalSpace = true;
gridData9.widthHint = 200;
gridData9.horizontalIndent = 0;
gridData9.verticalAlignment = GridData.FILL;
canvas = new SWTImageCanvas(top, SWT.NONE);
canvas.setLayoutData(gridData9);
canvas.setLayout(gridLayout2);
}
// Train
private void actionLoadTrainTargetsData() {
canvas.onFileOpen();
this.trainTargetsDataPathText.setText(
canvas.getSourceImageFileName() );
model.setFileNameTrainTargetData(canvas.getSourceImageFileName());
}
private void actionClearTrainTargetData() {
canvas.clearCanvas();
this.trainTargetsDataPathText.setText("");
model.setFileNameTrainTargetData("");
}
private void actionLoadTrainData() {
canvas.onFileOpen();
this.trainDataPathText.setText(
canvas.getSourceImageFileName() );
model.setFileNameTrainData(canvas.getSourceImageFileName());
}
private void actionClearTrainData() {
canvas.clearCanvas();
this.trainDataPathText.setText("");
model.setFileNameTrainData("");
}
// Test
private void actionLoadTestTargetsData() {
canvas.onFileOpen();
this.testTargetsDataPathText.setText(
canvas.getSourceImageFileName());
model.setFileNameTestTargetData(canvas.getSourceImageFileName());
}
private void actionClearTestTargetData() {
canvas.clearCanvas();
this.trainTargetsDataPathText.setText("");
model.setFileNameTestTargetData("");
}
private void actionLoadTestData() {
canvas.onFileOpen();
this.testDataPathText.setText(
canvas.getSourceImageFileName() );
model.setFileNameTestData(canvas.getSourceImageFileName());
}
private void actionClearTestData() {
canvas.clearCanvas();
this.testDataPathText.setText("");
model.setFileNameTestData("");
}
}
| Java |
package lv.bond.science.nnstudio.ui.errorgraph;
import java.awt.Dimension;
import java.awt.Font;
import java.util.Iterator;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import lv.bond.science.nnstudio.model.ImagesBean;
import org.eclipse.swt.SWT;
import org.eclipse.swt.awt.SWT_AWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.internal.activities.ws.ImageBindingRegistry;
import org.eclipse.ui.part.ViewPart;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.xy.XYDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
public class ErrorGraphView extends ViewPart {
public static final String ID = "lv.bond.science.nnstudio.ui.errorgraph.ErrorGraphView";
// Needs to be whatever is mentioned in plugin.xml
private Composite top = null;
private Composite composite = null;
private float[] testData = {0.2f, 0.3f, 0.4f};
private static XYSeriesCollection xySeriesCollection =
new XYSeriesCollection();
@Override
public void createPartControl(Composite parent) {
GridLayout gridLayout = new GridLayout();
gridLayout.numColumns = 1;
top = new Composite(parent, SWT.NONE);
top.setLayout(gridLayout);
createComposite();
}
@Override
public void setFocus() {
composite.setFocus();
}
/**
* This method initializes composite
*
*/
private void createComposite() {
GridData gridData = new GridData();
gridData.horizontalAlignment = GridData.FILL;
gridData.grabExcessHorizontalSpace = true;
gridData.grabExcessVerticalSpace = true;
gridData.verticalAlignment = GridData.FILL;
composite = new Composite(top, SWT.EMBEDDED);
composite.setLayout(new GridLayout());
composite.setLayoutData(gridData);
embedJPanelInto(composite);
}
private void embedJPanelInto(Composite container) {
java.awt.Frame graphFrame =
SWT_AWT.new_Frame(container);
java.awt.Panel panel =
new java.awt.Panel(new java.awt.BorderLayout());
graphFrame.add(panel);
JScrollPane scrollPane = new JScrollPane(
NormalDistributionDemo("Normal Distribution Demo"));
panel.add(scrollPane);
}
public JPanel NormalDistributionDemo(String s) {
JPanel jpanel = errorGraphPanel();
jpanel.setPreferredSize(new Dimension(500, 270));
return jpanel;
}
/*private static void fillDataset() {
Iterator iter = ErrorGraphView.xySeriesCollection.getSeries().iterator();
while (iter.hasNext()) {
XYSeries series = (XYSeries) iter.next();
Random rnd = new Random();
int seriesSize = series.getItemCount();
for(int i = seriesSize; i < seriesSize + 10; i++ ) {
float x = i;
float y = rnd.nextFloat();
series.add(x, y);
}
}
}*/
public static void clearDataset() {
Iterator iter = ErrorGraphView
.xySeriesCollection
.getSeries()
.iterator();
while (iter.hasNext()) {
XYSeries series = (XYSeries) iter.next();
series.clear();
}
}
public static void appendToDataSet(float[] data) {
XYSeries series =ErrorGraphView
.xySeriesCollection
.getSeries(0);
int seriesSize = series.getItemCount();
for (int i = seriesSize; i < seriesSize + data.length; i++) {
float x = i;
float y = data[i - seriesSize];
series.add(x, y);
}
}
public JPanel errorGraphPanel() {
XYSeriesCollection xyseriescollection = createDataset();
JFreeChart jfreechart = createChart(xyseriescollection);
ChartPanel chartpanel = new ChartPanel(jfreechart);
chartpanel.setPreferredSize(new Dimension(360, 500));
return chartpanel;
}
private static XYSeriesCollection createDataset()
{
XYSeriesCollection xyseriescollection = //new XYSeriesCollection();
ErrorGraphView.xySeriesCollection;
XYSeries xyseries = new XYSeries("Error", true, false);
//XYSeries xyseries1 = new XYSeries("D2", true, false);
/*Random rnd = new Random();
for(int i = 0; i < 10; i++ ) {
float x = i;
float y1 = rnd.nextFloat();
float y2 = rnd.nextFloat();
xyseries.add(x, y1);
xyseries1.add(x, y2);
}*/
xyseriescollection.addSeries(xyseries);
//xyseriescollection.addSeries(xyseries1);
return xyseriescollection;
}
private static JFreeChart createChart(XYDataset xydataset) {
JFreeChart jfreechart = ChartFactory.createXYLineChart(null, "Epochs", "Error", xydataset, PlotOrientation.VERTICAL, true, true, false);
TextTitle texttitle = new TextTitle("Network error", new Font("SansSerif", 1, 14));
jfreechart.addSubtitle(texttitle);
XYPlot xyplot = jfreechart.getXYPlot();
NumberAxis numberaxis = (NumberAxis)xyplot.getDomainAxis();
numberaxis.setUpperMargin(0.12D);
numberaxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
NumberAxis numberaxis1 = (NumberAxis)xyplot.getRangeAxis();
numberaxis1.setAutoRangeIncludesZero(false);
return jfreechart;
}
}
| Java |
package lv.bond.science.nnstudio.ui.testgraph;
import java.awt.Dimension;
import java.awt.Font;
import java.util.Iterator;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import org.eclipse.swt.SWT;
import org.eclipse.swt.awt.SWT_AWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.part.ViewPart;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
public class TestGraphView extends ViewPart {
public static final String ID =
"lv.bond.science.nnstudio.ui.errorgraph.TestGraphView";
// Needs to be whatever is mentioned in plugin.xml
private Composite top = null;
private Composite composite = null;
private Button button = null;
private float[] testData = {0.2f, 0.5f, 0.4f};
private static DefaultCategoryDataset defaultcategoryDataset =
new DefaultCategoryDataset(); // @jve:decl-index=0:
@Override
public void createPartControl(Composite parent) {
GridLayout gridLayout = new GridLayout();
gridLayout.numColumns = 1;
top = new Composite(parent, SWT.NONE);
top.setLayout(gridLayout);
createComposite();
button = new Button(top, SWT.NONE);
button.setText("Run");
button.addSelectionListener(new org.eclipse.swt.events.SelectionAdapter() {
public void widgetSelected(org.eclipse.swt.events.SelectionEvent e) {
//fillDataset();
//appendToDataSet(testData);
//ImagesBean beanWithPaths = ImagesBean.getInstance();
//System.out.println("path-"+beanWithPaths.getFileNameTestData()+";");
}
});
}
@Override
public void setFocus() {
composite.setFocus();
}
/**
* This method initializes composite
*
*/
private void createComposite() {
GridData gridData = new GridData();
gridData.horizontalAlignment = GridData.FILL;
gridData.grabExcessHorizontalSpace = true;
gridData.grabExcessVerticalSpace = true;
gridData.verticalAlignment = GridData.FILL;
composite = new Composite(top, SWT.EMBEDDED);
composite.setLayout(new GridLayout());
composite.setLayoutData(gridData);
embedJPanelInto(composite);
}
private void embedJPanelInto(Composite container) {
java.awt.Frame graphFrame =
SWT_AWT.new_Frame(container);
java.awt.Panel panel =
new java.awt.Panel(new java.awt.BorderLayout());
graphFrame.add(panel);
JScrollPane scrollPane = new JScrollPane(
TestNetwork("Normal Distribution Demo"));
panel.add(scrollPane);
}
public JPanel TestNetwork(String s) {
JPanel jpanel = errorGraphPanel();
jpanel.setPreferredSize(new Dimension(500, 270));
return jpanel;
}
public static void clearDataset() {
System.out.println("clearDataset for TestNet doesn`t mplemented yet!");
}
public static void appendToDataSet(double[] data, int key) {
for (int i = 0; i < data.length; i++) {
TestGraphView
.defaultcategoryDataset
.addValue(data[i], "Network Error", "Test "+key);
}
}
public JPanel errorGraphPanel() {
CategoryDataset categoryDataset = createDataset();
JFreeChart jfreechart = createChart(categoryDataset);
ChartPanel chartpanel = new ChartPanel(jfreechart);
chartpanel.setPreferredSize(new Dimension(360, 500));
return chartpanel;
}
private static CategoryDataset createDataset() {
/*
defaultcategoryDataset.addValue(1D, "Network Traffic", "Monday");
defaultcategoryDataset.addValue(0.003D, "Network Traffic", "Tuesday");
defaultcategoryDataset.addValue(0.02D, "Network Traffic", "Wednesday");
defaultcategoryDataset.addValue(0.00012D, "Network Traffic", "Thursday");
defaultcategoryDataset.addValue(0.0003D, "Network Traffic", "Friday");
*/
return defaultcategoryDataset;
}
private static JFreeChart createChart(CategoryDataset categoryDataset) {
JFreeChart jfreechart =
ChartFactory.createBarChart("Netwrok error on Tests", null, "NET Error", categoryDataset, PlotOrientation.VERTICAL, false, true, false);
//JFreeChart jfreechart = ChartFactory.createXYLineChart(null, "Epochs", "Error", xydataset, PlotOrientation.VERTICAL, true, true, false);
//TextTitle texttitle = new TextTitle("Network test", new Font("SansSerif", 1, 14));
//jfreechart.addSubtitle(texttitle);
//XYPlot xyplot = jfreechart.getXYPlot();
CategoryPlot categoryplot = (CategoryPlot)jfreechart.getPlot();
categoryplot.setDomainGridlinesVisible(true);
categoryplot.setRangeGridlinesVisible(true);
categoryplot.setNoDataMessage("NO DATA!");
NumberAxis numberaxis = (NumberAxis)categoryplot.getRangeAxis();
numberaxis.setUpperMargin(0.12D);
numberaxis.setStandardTickUnits(NumberAxis.createStandardTickUnits());
CategoryAxis numberaxis1 = (CategoryAxis)categoryplot.getDomainAxis();
//numberaxis1.
//numberaxis1.setAutoRangeIncludesZero(false);
return jfreechart;
}
}
| Java |
package lv.bond.science.nnstudio;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.actions.ActionFactory;
import org.eclipse.ui.actions.ActionFactory.IWorkbenchAction;
import org.eclipse.ui.application.ActionBarAdvisor;
import org.eclipse.ui.application.IActionBarConfigurer;
/**
* An action bar advisor is responsible for creating, adding, and disposing of
* the actions added to a workbench window. Each window will be populated with
* new actions.
*/
public class ApplicationActionBarAdvisor extends ActionBarAdvisor {
// Actions - important to allocate these only in makeActions, and then use
// them
// in the fill methods. This ensures that the actions aren't recreated
// when fillActionBars is called with FILL_PROXY.
private IWorkbenchAction exitAction;
public ApplicationActionBarAdvisor(IActionBarConfigurer configurer) {
super(configurer);
}
protected void makeActions(final IWorkbenchWindow window) {
// Creates the actions and registers them.
// Registering is needed to ensure that key bindings work.
// The corresponding commands keybindings are defined in the plugin.xml
// file.
// Registering also provides automatic disposal of the actions when
// the window is closed.
exitAction = ActionFactory.QUIT.create(window);
register(exitAction);
}
protected void fillMenuBar(IMenuManager menuBar) {
MenuManager fileMenu = new MenuManager("&File",
IWorkbenchActionConstants.M_FILE);
menuBar.add(fileMenu);
fileMenu.add(exitAction);
}
}
| Java |
package lv.bond.science.nnstudio;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.application.ActionBarAdvisor;
import org.eclipse.ui.application.IActionBarConfigurer;
import org.eclipse.ui.application.IWorkbenchWindowConfigurer;
import org.eclipse.ui.application.WorkbenchWindowAdvisor;
public class ApplicationWorkbenchWindowAdvisor extends WorkbenchWindowAdvisor {
public ApplicationWorkbenchWindowAdvisor(IWorkbenchWindowConfigurer configurer) {
super(configurer);
}
public ActionBarAdvisor createActionBarAdvisor(
IActionBarConfigurer configurer) {
return new ApplicationActionBarAdvisor(configurer);
}
public void preWindowOpen() {
IWorkbenchWindowConfigurer configurer = getWindowConfigurer();
configurer.setInitialSize(new Point(800, 600));
configurer.setShowCoolBar(false);
configurer.setShowPerspectiveBar(false);
configurer.setShowStatusLine(false);
configurer.setShowProgressIndicator(true);
configurer.setTitle("RCP NNStudio");
}
public void postWindowCreate() {
super.postWindowCreate();
IWorkbenchWindowConfigurer configurer = getWindowConfigurer();
Shell shell = configurer.getWindow().getShell();
shell.setMaximized(true);
shell.setMinimumSize(700, 500);
}
}
| Java |
package lv.bond.science.nnstudio.model;
public class ImagesBean {
private static String fileNameTrainData = "";
private static String fileNameTrainTargetData = "";
private static String fileNameTestData = "";
private static String fileNameTestTargetData = "";
private static ImagesBean instance = null;
public static ImagesBean getInstance() {
if (instance == null) {
instance = new ImagesBean();
}
return instance;
}
private ImagesBean() {
}
public String getFileNameTestData() {
return fileNameTestData;
}
public void setFileNameTestData(String fileNameTestData) {
this.fileNameTestData = fileNameTestData;
}
public String getFileNameTestTargetData() {
return fileNameTestTargetData;
}
public void setFileNameTestTargetData(String fileNameTestTargetData) {
this.fileNameTestTargetData = fileNameTestTargetData;
}
public String getFileNameTrainData() {
return fileNameTrainData;
}
public void setFileNameTrainData(String fileNameTrainData) {
this.fileNameTrainData = fileNameTrainData;
}
public String getFileNameTrainTargetData() {
return fileNameTrainTargetData;
}
public void setFileNameTrainTargetData(String fileNameTrainTargetData) {
this.fileNameTrainTargetData = fileNameTrainTargetData;
}
public String toString() {
String str = new String();
str = "Test"+this.getFileNameTestData()+"; ";
str += "TestTarget"+this.getFileNameTestTargetData()+"; ";
str += "Train"+this.getFileNameTrainData()+"; ";
str += "TrainTarget"+this.getFileNameTrainTargetData()+"; ";
return str;
}
}
| Java |
package lv.bond.eclipse.imagecanvas;
import java.awt.geom.AffineTransform;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ControlAdapter;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.ScrollBar;
/**
* A scrollable image canvas that extends org.eclipse.swt.graphics.Canvas.
* <p/>
* It requires Eclipse (version >= 2.1) on Win32/win32; Linux/gtk; MacOSX/carbon.
* <p/>
* This implementation using the pure SWT, no UI AWT package is used. For
* convenience, I put everything into one class. However, the best way to
* implement this is to use inheritance to create multiple hierarchies.
*
* @author Chengdong Li: cli4@uky.edu
*/
public class SWTImageCanvas extends Canvas {
/* zooming rates in x and y direction are equal.*/
final float ZOOMIN_RATE = 1.1f; /* zoomin rate */
final float ZOOMOUT_RATE = 0.9f; /* zoomout rate */
private Image sourceImage; /* original image */
private Image screenImage; /* screen image */
private AffineTransform transform = new AffineTransform();
private String currentDir=""; /* remembering file open directory */
private String sourceImageFileName="";
public SWTImageCanvas(final Composite parent) {
this(parent, SWT.NULL);
}
/**
* Constructor for ScrollableCanvas.
* @param parent the parent of this control.
* @param style the style of this control.
*/
public SWTImageCanvas(final Composite parent, int style) {
super( parent, style|SWT.BORDER|SWT.V_SCROLL|SWT.H_SCROLL
| SWT.NO_BACKGROUND);
addControlListener(new ControlAdapter() { /* resize listener. */
public void controlResized(ControlEvent event) {
syncScrollBars();
}
});
addPaintListener(new PaintListener() { /* paint listener. */
public void paintControl(final PaintEvent event) {
paint(event.gc);
}
});
initScrollBars();
}
/**
* Dispose the garbage here
*/
public void dispose() {
if (sourceImage != null && !sourceImage.isDisposed()) {
sourceImage.dispose();
}
if (screenImage != null && !screenImage.isDisposed()) {
screenImage.dispose();
}
}
/* Paint function */
private void paint(GC gc) {
Rectangle clientRect = getClientArea(); /* Canvas' painting area */
if (sourceImage != null) {
Rectangle imageRect =
SWT2Dutil.inverseTransformRect(transform, clientRect);
int gap = 2; /* find a better start point to render */
imageRect.x -= gap; imageRect.y -= gap;
imageRect.width += 2 * gap; imageRect.height += 2 * gap;
Rectangle imageBound = sourceImage.getBounds();
imageRect = imageRect.intersection(imageBound);
Rectangle destRect = SWT2Dutil.transformRect(transform, imageRect);
if (screenImage != null)
screenImage.dispose();
screenImage =
new Image(getDisplay(), clientRect.width, clientRect.height);
GC newGC = new GC(screenImage);
newGC.setClipping(clientRect);
newGC.drawImage(
sourceImage,
imageRect.x,
imageRect.y,
imageRect.width,
imageRect.height,
destRect.x,
destRect.y,
destRect.width,
destRect.height);
newGC.dispose();
gc.drawImage(screenImage, 0, 0);
} else {
gc.setClipping(clientRect);
gc.fillRectangle(clientRect);
initScrollBars();
}
}
/* Initalize the scrollbar and register listeners. */
private void initScrollBars() {
ScrollBar horizontal = getHorizontalBar();
horizontal.setEnabled(false);
horizontal.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
scrollHorizontally((ScrollBar) event.widget);
}
});
ScrollBar vertical = getVerticalBar();
vertical.setEnabled(false);
vertical.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
scrollVertically((ScrollBar) event.widget);
}
});
}
/* Scroll horizontally */
private void scrollHorizontally(ScrollBar scrollBar) {
if (sourceImage == null)
return;
AffineTransform af = transform;
double tx = af.getTranslateX();
double select = -scrollBar.getSelection();
af.preConcatenate(AffineTransform.getTranslateInstance(select - tx, 0));
transform = af;
syncScrollBars();
}
/* Scroll vertically */
private void scrollVertically(ScrollBar scrollBar) {
if (sourceImage == null)
return;
AffineTransform af = transform;
double ty = af.getTranslateY();
double select = -scrollBar.getSelection();
af.preConcatenate(AffineTransform.getTranslateInstance(0, select - ty));
transform = af;
syncScrollBars();
}
/**
* Source image getter.
* @return sourceImage.
*/
public Image getSourceImage() {
return sourceImage;
}
/**
* Synchronize the scrollbar with the image. If the transform is out
* of range, it will correct it. This function considers only following
* factors :<b> transform, image size, client area</b>.
*/
public void syncScrollBars() {
if (sourceImage == null) {
redraw();
return;
}
AffineTransform af = transform;
double sx = af.getScaleX(), sy = af.getScaleY();
double tx = af.getTranslateX(), ty = af.getTranslateY();
if (tx > 0) tx = 0;
if (ty > 0) ty = 0;
ScrollBar horizontal = getHorizontalBar();
horizontal.setIncrement((int) (getClientArea().width / 100));
horizontal.setPageIncrement(getClientArea().width);
Rectangle imageBound = sourceImage.getBounds();
int cw = getClientArea().width, ch = getClientArea().height;
if (imageBound.width * sx > cw) { /* image is wider than client area */
horizontal.setMaximum((int) (imageBound.width * sx));
horizontal.setEnabled(true);
if (((int) - tx) > horizontal.getMaximum() - cw)
tx = -horizontal.getMaximum() + cw;
} else { /* image is narrower than client area */
horizontal.setEnabled(false);
tx = (cw - imageBound.width * sx) / 2; //center if too small.
}
horizontal.setSelection((int) (-tx));
horizontal.setThumb((int) (getClientArea().width));
ScrollBar vertical = getVerticalBar();
vertical.setIncrement((int) (getClientArea().height / 100));
vertical.setPageIncrement((int) (getClientArea().height));
if (imageBound.height * sy > ch) { /* image is higher than client area */
vertical.setMaximum((int) (imageBound.height * sy));
vertical.setEnabled(true);
if (((int) - ty) > vertical.getMaximum() - ch)
ty = -vertical.getMaximum() + ch;
} else { /* image is less higher than client area */
vertical.setEnabled(false);
ty = (ch - imageBound.height * sy) / 2; //center if too small.
}
vertical.setSelection((int) (-ty));
vertical.setThumb((int) (getClientArea().height));
/* update transform. */
af = AffineTransform.getScaleInstance(sx, sy);
af.preConcatenate(AffineTransform.getTranslateInstance(tx, ty));
transform = af;
redraw();
}
/**
* Reload image from a file
* @param filename image file
* @return swt image created from image file
*/
public Image loadImage(String filename) {
if (sourceImage != null && !sourceImage.isDisposed()) {
sourceImage.dispose();
sourceImage = null;
}
sourceImage = new Image(getDisplay(), filename);
showOriginal();
return sourceImage;
}
/**
* Call back funtion of button "open". Will open a file dialog, and choose
* the image file. It supports image formats supported by Eclipse.
*/
public void onFileOpen() {
FileDialog fileChooser = new FileDialog(getShell(), SWT.OPEN);
fileChooser.setText("Open image file");
fileChooser.setFilterPath(currentDir);
fileChooser.setFilterExtensions(
new String[] { "*.gif; *.jpg; *.png; *.ico; *.bmp" });
fileChooser.setFilterNames(
new String[] { "SWT image" + " (gif, jpeg, png, ico, bmp)" });
String filename = fileChooser.open();
if (filename != null){
loadImage(filename);
this.sourceImageFileName = filename;
currentDir = fileChooser.getFilterPath();
}
}
/**
* Get the image data. (for future use only)
* @return image data of canvas
*/
public ImageData getImageData() {
return sourceImage.getImageData();
}
/**
* Reset the image data and update the image
* @param data image data to be set
*/
public void setImageData(ImageData data) {
if (sourceImage != null)
sourceImage.dispose();
if (data != null)
sourceImage = new Image(getDisplay(), data);
syncScrollBars();
}
/**
* Fit the image onto the canvas
*/
public void fitCanvas() {
if (sourceImage == null)
return;
Rectangle imageBound = sourceImage.getBounds();
Rectangle destRect = getClientArea();
double sx = (double) destRect.width / (double) imageBound.width;
double sy = (double) destRect.height / (double) imageBound.height;
double s = Math.min(sx, sy);
double dx = 0.5 * destRect.width;
double dy = 0.5 * destRect.height;
centerZoom(dx, dy, s, new AffineTransform());
}
/**
* Show the image with the original size
*/
public void showOriginal() {
if (sourceImage == null)
return;
transform = new AffineTransform();
syncScrollBars();
}
/**
* Perform a zooming operation centered on the given point
* (dx, dy) and using the given scale factor.
* The given AffineTransform instance is preconcatenated.
* @param dx center x
* @param dy center y
* @param scale zoom rate
* @param af original affinetransform
*/
public void centerZoom(
double dx,
double dy,
double scale,
AffineTransform af) {
af.preConcatenate(AffineTransform.getTranslateInstance(-dx, -dy));
af.preConcatenate(AffineTransform.getScaleInstance(scale, scale));
af.preConcatenate(AffineTransform.getTranslateInstance(dx, dy));
transform = af;
syncScrollBars();
}
/**
* Zoom in around the center of client Area.
*/
public void zoomIn() {
if (sourceImage == null)
return;
Rectangle rect = getClientArea();
int w = rect.width, h = rect.height;
double dx = ((double) w) / 2;
double dy = ((double) h) / 2;
centerZoom(dx, dy, ZOOMIN_RATE, transform);
}
/**
* Zoom out around the center of client Area.
*/
public void zoomOut() {
if (sourceImage == null)
return;
Rectangle rect = getClientArea();
int w = rect.width, h = rect.height;
double dx = ((double) w) / 2;
double dy = ((double) h) / 2;
centerZoom(dx, dy, ZOOMOUT_RATE, transform);
}
public void clearCanvas() {
this.sourceImage = null;
this.sourceImageFileName = "";
syncScrollBars();
}
public String getSourceImageFileName() {
return sourceImageFileName;
}
}
| Java |
/*******************************************************************************
* Copyright (c) 2004 Chengdong Li : cdli@ccs.uky.edu
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*******************************************************************************/
package lv.bond.eclipse.imagecanvas;
import java.awt.geom.AffineTransform;
import java.awt.geom.Point2D;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
/**
* Utility for Java2d transform
*
* @author Chengdong Li: cli4@uky.edu
*
*/
public class SWT2Dutil {
/**
* Given an arbitrary rectangle, get the rectangle with the given transform.
* The result rectangle is positive width and positive height.
* @param af AffineTransform
* @param src source rectangle
* @return rectangle after transform with positive width and height
*/
public static Rectangle transformRect(AffineTransform af, Rectangle src){
Rectangle dest= new Rectangle(0,0,0,0);
src=absRect(src);
Point p1=new Point(src.x,src.y);
p1=transformPoint(af,p1);
dest.x=p1.x; dest.y=p1.y;
dest.width=(int)(src.width*af.getScaleX());
dest.height=(int)(src.height*af.getScaleY());
return dest;
}
/**
* Given an arbitrary rectangle, get the rectangle with the inverse given transform.
* The result rectangle is positive width and positive height.
* @param af AffineTransform
* @param src source rectangle
* @return rectangle after transform with positive width and height
*/
public static Rectangle inverseTransformRect(AffineTransform af, Rectangle src){
Rectangle dest= new Rectangle(0,0,0,0);
src=absRect(src);
Point p1=new Point(src.x,src.y);
p1=inverseTransformPoint(af,p1);
dest.x=p1.x; dest.y=p1.y;
dest.width=(int)(src.width/af.getScaleX());
dest.height=(int)(src.height/af.getScaleY());
return dest;
}
/**
* Given an arbitrary point, get the point with the given transform.
* @param af affine transform
* @param pt point to be transformed
* @return point after tranform
*/
public static Point transformPoint(AffineTransform af, Point pt) {
Point2D src = new Point2D.Float(pt.x, pt.y);
Point2D dest= af.transform(src, null);
Point point=new Point((int)Math.floor(dest.getX()), (int)Math.floor(dest.getY()));
return point;
}
/**
* Given an arbitrary point, get the point with the inverse given transform.
* @param af AffineTransform
* @param pt source point
* @return point after transform
*/
public static Point inverseTransformPoint(AffineTransform af, Point pt){
Point2D src=new Point2D.Float(pt.x,pt.y);
try{
Point2D dest= af.inverseTransform(src, null);
return new Point((int)Math.floor(dest.getX()), (int)Math.floor(dest.getY()));
}catch (Exception e){
e.printStackTrace();
return new Point(0,0);
}
}
/**
* Given arbitrary rectangle, return a rectangle with upper-left
* start and positive width and height.
* @param src source rectangle
* @return result rectangle with positive width and height
*/
public static Rectangle absRect(Rectangle src){
Rectangle dest= new Rectangle(0,0,0,0);
if(src.width<0) { dest.x=src.x+src.width+1; dest.width=-src.width; }
else{ dest.x=src.x; dest.width=src.width; }
if(src.height<0) { dest.y=src.y+src.height+1; dest.height=-src.height; }
else{ dest.y=src.y; dest.height=src.height; }
return dest;
}
}
| Java |
package info.bond.labs.geftest1;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EObject;
import java.util.List;
/**
* @model abstract="true"
*/
public interface Shape extends EObject {
/**
* @model
*/
String getName();
/**
* Sets the value of the '{@link info.bond.labs.geftest1.Shape#getName <em>Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Name</em>' attribute.
* @see #getName()
* @generated
*/
void setName(String value);
/**
* @model containment="true"
*/
EList<Connection> getSourceConnections();
/**
* @model
*/
EList<Connection> getTargetConnections();
}
| Java |
package info.bond.labs.geftest1;
/**
* @model
*/
public interface RectangularShape extends Shape {
}
| Java |
package info.bond.labs.geftest1;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EObject;
/**
* @model
*/
public interface ShapesDiagram extends EObject {
/**
* @model containment="true"
*/
EList<Shape> getShapes();
}
| Java |
/**
* <copyright>
* </copyright>
*
* $Id$
*/
package info.bond.labs.geftest1.impl;
import info.bond.labs.geftest1.Connection;
import info.bond.labs.geftest1.Geftest1Package;
import info.bond.labs.geftest1.Shape;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.impl.EObjectImpl;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Connection</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link info.bond.labs.geftest1.impl.ConnectionImpl#getSource <em>Source</em>}</li>
* <li>{@link info.bond.labs.geftest1.impl.ConnectionImpl#getTarget <em>Target</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public class ConnectionImpl extends EObjectImpl implements Connection {
/**
* The cached value of the '{@link #getSource() <em>Source</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getSource()
* @generated
* @ordered
*/
protected Shape source;
/**
* The cached value of the '{@link #getTarget() <em>Target</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getTarget()
* @generated
* @ordered
*/
protected Shape target;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected ConnectionImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return Geftest1Package.Literals.CONNECTION;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Shape getSource() {
if (source != null && source.eIsProxy()) {
InternalEObject oldSource = (InternalEObject)source;
source = (Shape)eResolveProxy(oldSource);
if (source != oldSource) {
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE, Geftest1Package.CONNECTION__SOURCE, oldSource, source));
}
}
return source;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Shape basicGetSource() {
return source;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setSource(Shape newSource) {
Shape oldSource = source;
source = newSource;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, Geftest1Package.CONNECTION__SOURCE, oldSource, source));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Shape getTarget() {
if (target != null && target.eIsProxy()) {
InternalEObject oldTarget = (InternalEObject)target;
target = (Shape)eResolveProxy(oldTarget);
if (target != oldTarget) {
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE, Geftest1Package.CONNECTION__TARGET, oldTarget, target));
}
}
return target;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Shape basicGetTarget() {
return target;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setTarget(Shape newTarget) {
Shape oldTarget = target;
target = newTarget;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, Geftest1Package.CONNECTION__TARGET, oldTarget, target));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case Geftest1Package.CONNECTION__SOURCE:
if (resolve) return getSource();
return basicGetSource();
case Geftest1Package.CONNECTION__TARGET:
if (resolve) return getTarget();
return basicGetTarget();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case Geftest1Package.CONNECTION__SOURCE:
setSource((Shape)newValue);
return;
case Geftest1Package.CONNECTION__TARGET:
setTarget((Shape)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case Geftest1Package.CONNECTION__SOURCE:
setSource((Shape)null);
return;
case Geftest1Package.CONNECTION__TARGET:
setTarget((Shape)null);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case Geftest1Package.CONNECTION__SOURCE:
return source != null;
case Geftest1Package.CONNECTION__TARGET:
return target != null;
}
return super.eIsSet(featureID);
}
} //ConnectionImpl
| Java |
/**
* <copyright>
* </copyright>
*
* $Id$
*/
package info.bond.labs.geftest1.impl;
import info.bond.labs.geftest1.Connection;
import info.bond.labs.geftest1.EllipticalShape;
import info.bond.labs.geftest1.Geftest1Factory;
import info.bond.labs.geftest1.Geftest1Package;
import info.bond.labs.geftest1.RectangularShape;
import info.bond.labs.geftest1.Shape;
import info.bond.labs.geftest1.ShapesDiagram;
import org.eclipse.emf.ecore.EAttribute;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.EReference;
import org.eclipse.emf.ecore.impl.EPackageImpl;
/**
* <!-- begin-user-doc -->
* An implementation of the model <b>Package</b>.
* <!-- end-user-doc -->
* @generated
*/
public class Geftest1PackageImpl extends EPackageImpl implements Geftest1Package {
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private EClass connectionEClass = null;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private EClass ellipticalShapeEClass = null;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private EClass rectangularShapeEClass = null;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private EClass shapeEClass = null;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private EClass shapesDiagramEClass = null;
/**
* Creates an instance of the model <b>Package</b>, registered with
* {@link org.eclipse.emf.ecore.EPackage.Registry EPackage.Registry} by the package
* package URI value.
* <p>Note: the correct way to create the package is via the static
* factory method {@link #init init()}, which also performs
* initialization of the package, or returns the registered package,
* if one already exists.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see org.eclipse.emf.ecore.EPackage.Registry
* @see info.bond.labs.geftest1.Geftest1Package#eNS_URI
* @see #init()
* @generated
*/
private Geftest1PackageImpl() {
super(eNS_URI, Geftest1Factory.eINSTANCE);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private static boolean isInited = false;
/**
* Creates, registers, and initializes the <b>Package</b> for this
* model, and for any others upon which it depends. Simple
* dependencies are satisfied by calling this method on all
* dependent packages before doing anything else. This method drives
* initialization for interdependent packages directly, in parallel
* with this package, itself.
* <p>Of this package and its interdependencies, all packages which
* have not yet been registered by their URI values are first created
* and registered. The packages are then initialized in two steps:
* meta-model objects for all of the packages are created before any
* are initialized, since one package's meta-model objects may refer to
* those of another.
* <p>Invocation of this method will not affect any packages that have
* already been initialized.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #eNS_URI
* @see #createPackageContents()
* @see #initializePackageContents()
* @generated
*/
public static Geftest1Package init() {
if (isInited) return (Geftest1Package)EPackage.Registry.INSTANCE.getEPackage(Geftest1Package.eNS_URI);
// Obtain or create and register package
Geftest1PackageImpl theGeftest1Package = (Geftest1PackageImpl)(EPackage.Registry.INSTANCE.getEPackage(eNS_URI) instanceof Geftest1PackageImpl ? EPackage.Registry.INSTANCE.getEPackage(eNS_URI) : new Geftest1PackageImpl());
isInited = true;
// Create package meta-data objects
theGeftest1Package.createPackageContents();
// Initialize created meta-data
theGeftest1Package.initializePackageContents();
// Mark meta-data to indicate it can't be changed
theGeftest1Package.freeze();
return theGeftest1Package;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EClass getConnection() {
return connectionEClass;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EReference getConnection_Source() {
return (EReference)connectionEClass.getEStructuralFeatures().get(0);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EReference getConnection_Target() {
return (EReference)connectionEClass.getEStructuralFeatures().get(1);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EClass getEllipticalShape() {
return ellipticalShapeEClass;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EClass getRectangularShape() {
return rectangularShapeEClass;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EClass getShape() {
return shapeEClass;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EAttribute getShape_Name() {
return (EAttribute)shapeEClass.getEStructuralFeatures().get(0);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EReference getShape_SourceConnections() {
return (EReference)shapeEClass.getEStructuralFeatures().get(1);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EReference getShape_TargetConnections() {
return (EReference)shapeEClass.getEStructuralFeatures().get(2);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EClass getShapesDiagram() {
return shapesDiagramEClass;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EReference getShapesDiagram_Shapes() {
return (EReference)shapesDiagramEClass.getEStructuralFeatures().get(0);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Geftest1Factory getGeftest1Factory() {
return (Geftest1Factory)getEFactoryInstance();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private boolean isCreated = false;
/**
* Creates the meta-model objects for the package. This method is
* guarded to have no affect on any invocation but its first.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void createPackageContents() {
if (isCreated) return;
isCreated = true;
// Create classes and their features
connectionEClass = createEClass(CONNECTION);
createEReference(connectionEClass, CONNECTION__SOURCE);
createEReference(connectionEClass, CONNECTION__TARGET);
ellipticalShapeEClass = createEClass(ELLIPTICAL_SHAPE);
rectangularShapeEClass = createEClass(RECTANGULAR_SHAPE);
shapeEClass = createEClass(SHAPE);
createEAttribute(shapeEClass, SHAPE__NAME);
createEReference(shapeEClass, SHAPE__SOURCE_CONNECTIONS);
createEReference(shapeEClass, SHAPE__TARGET_CONNECTIONS);
shapesDiagramEClass = createEClass(SHAPES_DIAGRAM);
createEReference(shapesDiagramEClass, SHAPES_DIAGRAM__SHAPES);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private boolean isInitialized = false;
/**
* Complete the initialization of the package and its meta-model. This
* method is guarded to have no affect on any invocation but its first.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void initializePackageContents() {
if (isInitialized) return;
isInitialized = true;
// Initialize package
setName(eNAME);
setNsPrefix(eNS_PREFIX);
setNsURI(eNS_URI);
// Create type parameters
// Set bounds for type parameters
// Add supertypes to classes
ellipticalShapeEClass.getESuperTypes().add(this.getShape());
rectangularShapeEClass.getESuperTypes().add(this.getShape());
// Initialize classes and features; add operations and parameters
initEClass(connectionEClass, Connection.class, "Connection", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS);
initEReference(getConnection_Source(), this.getShape(), null, "source", null, 0, 1, Connection.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_COMPOSITE, IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEReference(getConnection_Target(), this.getShape(), null, "target", null, 0, 1, Connection.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_COMPOSITE, IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEClass(ellipticalShapeEClass, EllipticalShape.class, "EllipticalShape", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS);
initEClass(rectangularShapeEClass, RectangularShape.class, "RectangularShape", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS);
initEClass(shapeEClass, Shape.class, "Shape", IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS);
initEAttribute(getShape_Name(), ecorePackage.getEString(), "name", null, 0, 1, Shape.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEReference(getShape_SourceConnections(), this.getConnection(), null, "sourceConnections", null, 0, -1, Shape.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEReference(getShape_TargetConnections(), this.getConnection(), null, "targetConnections", null, 0, -1, Shape.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_COMPOSITE, IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEClass(shapesDiagramEClass, ShapesDiagram.class, "ShapesDiagram", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS);
initEReference(getShapesDiagram_Shapes(), this.getShape(), null, "shapes", null, 0, -1, ShapesDiagram.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
// Create resource
createResource(eNS_URI);
}
} //Geftest1PackageImpl
| Java |
/**
* <copyright>
* </copyright>
*
* $Id$
*/
package info.bond.labs.geftest1.impl;
import info.bond.labs.geftest1.Connection;
import info.bond.labs.geftest1.Geftest1Package;
import info.bond.labs.geftest1.Shape;
import java.util.Collection;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.impl.EObjectImpl;
import org.eclipse.emf.ecore.util.EObjectContainmentEList;
import org.eclipse.emf.ecore.util.EObjectResolvingEList;
import org.eclipse.emf.ecore.util.InternalEList;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Shape</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link info.bond.labs.geftest1.impl.ShapeImpl#getName <em>Name</em>}</li>
* <li>{@link info.bond.labs.geftest1.impl.ShapeImpl#getSourceConnections <em>Source Connections</em>}</li>
* <li>{@link info.bond.labs.geftest1.impl.ShapeImpl#getTargetConnections <em>Target Connections</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public abstract class ShapeImpl extends EObjectImpl implements Shape {
/**
* The default value of the '{@link #getName() <em>Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getName()
* @generated
* @ordered
*/
protected static final String NAME_EDEFAULT = null;
/**
* The cached value of the '{@link #getName() <em>Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getName()
* @generated
* @ordered
*/
protected String name = NAME_EDEFAULT;
/**
* The cached value of the '{@link #getSourceConnections() <em>Source Connections</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getSourceConnections()
* @generated
* @ordered
*/
protected EList<Connection> sourceConnections;
/**
* The cached value of the '{@link #getTargetConnections() <em>Target Connections</em>}' reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getTargetConnections()
* @generated
* @ordered
*/
protected EList<Connection> targetConnections;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected ShapeImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return Geftest1Package.Literals.SHAPE;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getName() {
return name;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setName(String newName) {
String oldName = name;
name = newName;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, Geftest1Package.SHAPE__NAME, oldName, name));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<Connection> getSourceConnections() {
if (sourceConnections == null) {
sourceConnections = new EObjectContainmentEList<Connection>(Connection.class, this, Geftest1Package.SHAPE__SOURCE_CONNECTIONS);
}
return sourceConnections;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<Connection> getTargetConnections() {
if (targetConnections == null) {
targetConnections = new EObjectResolvingEList<Connection>(Connection.class, this, Geftest1Package.SHAPE__TARGET_CONNECTIONS);
}
return targetConnections;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case Geftest1Package.SHAPE__SOURCE_CONNECTIONS:
return ((InternalEList<?>)getSourceConnections()).basicRemove(otherEnd, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case Geftest1Package.SHAPE__NAME:
return getName();
case Geftest1Package.SHAPE__SOURCE_CONNECTIONS:
return getSourceConnections();
case Geftest1Package.SHAPE__TARGET_CONNECTIONS:
return getTargetConnections();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case Geftest1Package.SHAPE__NAME:
setName((String)newValue);
return;
case Geftest1Package.SHAPE__SOURCE_CONNECTIONS:
getSourceConnections().clear();
getSourceConnections().addAll((Collection<? extends Connection>)newValue);
return;
case Geftest1Package.SHAPE__TARGET_CONNECTIONS:
getTargetConnections().clear();
getTargetConnections().addAll((Collection<? extends Connection>)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case Geftest1Package.SHAPE__NAME:
setName(NAME_EDEFAULT);
return;
case Geftest1Package.SHAPE__SOURCE_CONNECTIONS:
getSourceConnections().clear();
return;
case Geftest1Package.SHAPE__TARGET_CONNECTIONS:
getTargetConnections().clear();
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case Geftest1Package.SHAPE__NAME:
return NAME_EDEFAULT == null ? name != null : !NAME_EDEFAULT.equals(name);
case Geftest1Package.SHAPE__SOURCE_CONNECTIONS:
return sourceConnections != null && !sourceConnections.isEmpty();
case Geftest1Package.SHAPE__TARGET_CONNECTIONS:
return targetConnections != null && !targetConnections.isEmpty();
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
if (eIsProxy()) return super.toString();
StringBuffer result = new StringBuffer(super.toString());
result.append(" (name: ");
result.append(name);
result.append(')');
return result.toString();
}
} //ShapeImpl
| Java |
/**
* <copyright>
* </copyright>
*
* $Id$
*/
package info.bond.labs.geftest1.impl;
import info.bond.labs.geftest1.Geftest1Package;
import info.bond.labs.geftest1.Shape;
import info.bond.labs.geftest1.ShapesDiagram;
import java.util.Collection;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.EObjectImpl;
import org.eclipse.emf.ecore.util.EObjectContainmentEList;
import org.eclipse.emf.ecore.util.InternalEList;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Shapes Diagram</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link info.bond.labs.geftest1.impl.ShapesDiagramImpl#getShapes <em>Shapes</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public class ShapesDiagramImpl extends EObjectImpl implements ShapesDiagram {
/**
* The cached value of the '{@link #getShapes() <em>Shapes</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getShapes()
* @generated
* @ordered
*/
protected EList<Shape> shapes;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected ShapesDiagramImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return Geftest1Package.Literals.SHAPES_DIAGRAM;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<Shape> getShapes() {
if (shapes == null) {
shapes = new EObjectContainmentEList<Shape>(Shape.class, this, Geftest1Package.SHAPES_DIAGRAM__SHAPES);
}
return shapes;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case Geftest1Package.SHAPES_DIAGRAM__SHAPES:
return ((InternalEList<?>)getShapes()).basicRemove(otherEnd, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case Geftest1Package.SHAPES_DIAGRAM__SHAPES:
return getShapes();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case Geftest1Package.SHAPES_DIAGRAM__SHAPES:
getShapes().clear();
getShapes().addAll((Collection<? extends Shape>)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case Geftest1Package.SHAPES_DIAGRAM__SHAPES:
getShapes().clear();
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case Geftest1Package.SHAPES_DIAGRAM__SHAPES:
return shapes != null && !shapes.isEmpty();
}
return super.eIsSet(featureID);
}
} //ShapesDiagramImpl
| Java |
/**
* <copyright>
* </copyright>
*
* $Id$
*/
package info.bond.labs.geftest1;
import org.eclipse.emf.ecore.EAttribute;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.EReference;
/**
* <!-- begin-user-doc -->
* The <b>Package</b> for the model.
* It contains accessors for the meta objects to represent
* <ul>
* <li>each class,</li>
* <li>each feature of each class,</li>
* <li>each enum,</li>
* <li>and each data type</li>
* </ul>
* <!-- end-user-doc -->
* @see info.bond.labs.geftest1.Geftest1Factory
* @model kind="package"
* @generated
*/
public interface Geftest1Package extends EPackage {
/**
* The package name.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
String eNAME = "geftest1";
/**
* The package namespace URI.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
String eNS_URI = "http:///info/bond/labs/geftest1.ecore";
/**
* The package namespace name.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
String eNS_PREFIX = "info.bond.labs.geftest1";
/**
* The singleton instance of the package.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
Geftest1Package eINSTANCE = info.bond.labs.geftest1.impl.Geftest1PackageImpl.init();
/**
* The meta object id for the '{@link info.bond.labs.geftest1.impl.ConnectionImpl <em>Connection</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see info.bond.labs.geftest1.impl.ConnectionImpl
* @see info.bond.labs.geftest1.impl.Geftest1PackageImpl#getConnection()
* @generated
*/
int CONNECTION = 0;
/**
* The feature id for the '<em><b>Source</b></em>' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int CONNECTION__SOURCE = 0;
/**
* The feature id for the '<em><b>Target</b></em>' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int CONNECTION__TARGET = 1;
/**
* The number of structural features of the '<em>Connection</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int CONNECTION_FEATURE_COUNT = 2;
/**
* The meta object id for the '{@link info.bond.labs.geftest1.impl.ShapeImpl <em>Shape</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see info.bond.labs.geftest1.impl.ShapeImpl
* @see info.bond.labs.geftest1.impl.Geftest1PackageImpl#getShape()
* @generated
*/
int SHAPE = 3;
/**
* The feature id for the '<em><b>Name</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int SHAPE__NAME = 0;
/**
* The feature id for the '<em><b>Source Connections</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int SHAPE__SOURCE_CONNECTIONS = 1;
/**
* The feature id for the '<em><b>Target Connections</b></em>' reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int SHAPE__TARGET_CONNECTIONS = 2;
/**
* The number of structural features of the '<em>Shape</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int SHAPE_FEATURE_COUNT = 3;
/**
* The meta object id for the '{@link info.bond.labs.geftest1.impl.EllipticalShapeImpl <em>Elliptical Shape</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see info.bond.labs.geftest1.impl.EllipticalShapeImpl
* @see info.bond.labs.geftest1.impl.Geftest1PackageImpl#getEllipticalShape()
* @generated
*/
int ELLIPTICAL_SHAPE = 1;
/**
* The feature id for the '<em><b>Name</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ELLIPTICAL_SHAPE__NAME = SHAPE__NAME;
/**
* The feature id for the '<em><b>Source Connections</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ELLIPTICAL_SHAPE__SOURCE_CONNECTIONS = SHAPE__SOURCE_CONNECTIONS;
/**
* The feature id for the '<em><b>Target Connections</b></em>' reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ELLIPTICAL_SHAPE__TARGET_CONNECTIONS = SHAPE__TARGET_CONNECTIONS;
/**
* The number of structural features of the '<em>Elliptical Shape</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int ELLIPTICAL_SHAPE_FEATURE_COUNT = SHAPE_FEATURE_COUNT + 0;
/**
* The meta object id for the '{@link info.bond.labs.geftest1.impl.RectangularShapeImpl <em>Rectangular Shape</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see info.bond.labs.geftest1.impl.RectangularShapeImpl
* @see info.bond.labs.geftest1.impl.Geftest1PackageImpl#getRectangularShape()
* @generated
*/
int RECTANGULAR_SHAPE = 2;
/**
* The feature id for the '<em><b>Name</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int RECTANGULAR_SHAPE__NAME = SHAPE__NAME;
/**
* The feature id for the '<em><b>Source Connections</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int RECTANGULAR_SHAPE__SOURCE_CONNECTIONS = SHAPE__SOURCE_CONNECTIONS;
/**
* The feature id for the '<em><b>Target Connections</b></em>' reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int RECTANGULAR_SHAPE__TARGET_CONNECTIONS = SHAPE__TARGET_CONNECTIONS;
/**
* The number of structural features of the '<em>Rectangular Shape</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int RECTANGULAR_SHAPE_FEATURE_COUNT = SHAPE_FEATURE_COUNT + 0;
/**
* The meta object id for the '{@link info.bond.labs.geftest1.impl.ShapesDiagramImpl <em>Shapes Diagram</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see info.bond.labs.geftest1.impl.ShapesDiagramImpl
* @see info.bond.labs.geftest1.impl.Geftest1PackageImpl#getShapesDiagram()
* @generated
*/
int SHAPES_DIAGRAM = 4;
/**
* The feature id for the '<em><b>Shapes</b></em>' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int SHAPES_DIAGRAM__SHAPES = 0;
/**
* The number of structural features of the '<em>Shapes Diagram</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int SHAPES_DIAGRAM_FEATURE_COUNT = 1;
/**
* Returns the meta object for class '{@link info.bond.labs.geftest1.Connection <em>Connection</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Connection</em>'.
* @see info.bond.labs.geftest1.Connection
* @generated
*/
EClass getConnection();
/**
* Returns the meta object for the reference '{@link info.bond.labs.geftest1.Connection#getSource <em>Source</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the reference '<em>Source</em>'.
* @see info.bond.labs.geftest1.Connection#getSource()
* @see #getConnection()
* @generated
*/
EReference getConnection_Source();
/**
* Returns the meta object for the reference '{@link info.bond.labs.geftest1.Connection#getTarget <em>Target</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the reference '<em>Target</em>'.
* @see info.bond.labs.geftest1.Connection#getTarget()
* @see #getConnection()
* @generated
*/
EReference getConnection_Target();
/**
* Returns the meta object for class '{@link info.bond.labs.geftest1.EllipticalShape <em>Elliptical Shape</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Elliptical Shape</em>'.
* @see info.bond.labs.geftest1.EllipticalShape
* @generated
*/
EClass getEllipticalShape();
/**
* Returns the meta object for class '{@link info.bond.labs.geftest1.RectangularShape <em>Rectangular Shape</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Rectangular Shape</em>'.
* @see info.bond.labs.geftest1.RectangularShape
* @generated
*/
EClass getRectangularShape();
/**
* Returns the meta object for class '{@link info.bond.labs.geftest1.Shape <em>Shape</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Shape</em>'.
* @see info.bond.labs.geftest1.Shape
* @generated
*/
EClass getShape();
/**
* Returns the meta object for the attribute '{@link info.bond.labs.geftest1.Shape#getName <em>Name</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Name</em>'.
* @see info.bond.labs.geftest1.Shape#getName()
* @see #getShape()
* @generated
*/
EAttribute getShape_Name();
/**
* Returns the meta object for the containment reference list '{@link info.bond.labs.geftest1.Shape#getSourceConnections <em>Source Connections</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the containment reference list '<em>Source Connections</em>'.
* @see info.bond.labs.geftest1.Shape#getSourceConnections()
* @see #getShape()
* @generated
*/
EReference getShape_SourceConnections();
/**
* Returns the meta object for the reference list '{@link info.bond.labs.geftest1.Shape#getTargetConnections <em>Target Connections</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the reference list '<em>Target Connections</em>'.
* @see info.bond.labs.geftest1.Shape#getTargetConnections()
* @see #getShape()
* @generated
*/
EReference getShape_TargetConnections();
/**
* Returns the meta object for class '{@link info.bond.labs.geftest1.ShapesDiagram <em>Shapes Diagram</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Shapes Diagram</em>'.
* @see info.bond.labs.geftest1.ShapesDiagram
* @generated
*/
EClass getShapesDiagram();
/**
* Returns the meta object for the containment reference list '{@link info.bond.labs.geftest1.ShapesDiagram#getShapes <em>Shapes</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the containment reference list '<em>Shapes</em>'.
* @see info.bond.labs.geftest1.ShapesDiagram#getShapes()
* @see #getShapesDiagram()
* @generated
*/
EReference getShapesDiagram_Shapes();
/**
* Returns the factory that creates the instances of the model.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the factory that creates the instances of the model.
* @generated
*/
Geftest1Factory getGeftest1Factory();
/**
* <!-- begin-user-doc -->
* Defines literals for the meta objects that represent
* <ul>
* <li>each class,</li>
* <li>each feature of each class,</li>
* <li>each enum,</li>
* <li>and each data type</li>
* </ul>
* <!-- end-user-doc -->
* @generated
*/
interface Literals {
/**
* The meta object literal for the '{@link info.bond.labs.geftest1.impl.ConnectionImpl <em>Connection</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see info.bond.labs.geftest1.impl.ConnectionImpl
* @see info.bond.labs.geftest1.impl.Geftest1PackageImpl#getConnection()
* @generated
*/
EClass CONNECTION = eINSTANCE.getConnection();
/**
* The meta object literal for the '<em><b>Source</b></em>' reference feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EReference CONNECTION__SOURCE = eINSTANCE.getConnection_Source();
/**
* The meta object literal for the '<em><b>Target</b></em>' reference feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EReference CONNECTION__TARGET = eINSTANCE.getConnection_Target();
/**
* The meta object literal for the '{@link info.bond.labs.geftest1.impl.EllipticalShapeImpl <em>Elliptical Shape</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see info.bond.labs.geftest1.impl.EllipticalShapeImpl
* @see info.bond.labs.geftest1.impl.Geftest1PackageImpl#getEllipticalShape()
* @generated
*/
EClass ELLIPTICAL_SHAPE = eINSTANCE.getEllipticalShape();
/**
* The meta object literal for the '{@link info.bond.labs.geftest1.impl.RectangularShapeImpl <em>Rectangular Shape</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see info.bond.labs.geftest1.impl.RectangularShapeImpl
* @see info.bond.labs.geftest1.impl.Geftest1PackageImpl#getRectangularShape()
* @generated
*/
EClass RECTANGULAR_SHAPE = eINSTANCE.getRectangularShape();
/**
* The meta object literal for the '{@link info.bond.labs.geftest1.impl.ShapeImpl <em>Shape</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see info.bond.labs.geftest1.impl.ShapeImpl
* @see info.bond.labs.geftest1.impl.Geftest1PackageImpl#getShape()
* @generated
*/
EClass SHAPE = eINSTANCE.getShape();
/**
* The meta object literal for the '<em><b>Name</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute SHAPE__NAME = eINSTANCE.getShape_Name();
/**
* The meta object literal for the '<em><b>Source Connections</b></em>' containment reference list feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EReference SHAPE__SOURCE_CONNECTIONS = eINSTANCE.getShape_SourceConnections();
/**
* The meta object literal for the '<em><b>Target Connections</b></em>' reference list feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EReference SHAPE__TARGET_CONNECTIONS = eINSTANCE.getShape_TargetConnections();
/**
* The meta object literal for the '{@link info.bond.labs.geftest1.impl.ShapesDiagramImpl <em>Shapes Diagram</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see info.bond.labs.geftest1.impl.ShapesDiagramImpl
* @see info.bond.labs.geftest1.impl.Geftest1PackageImpl#getShapesDiagram()
* @generated
*/
EClass SHAPES_DIAGRAM = eINSTANCE.getShapesDiagram();
/**
* The meta object literal for the '<em><b>Shapes</b></em>' containment reference list feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EReference SHAPES_DIAGRAM__SHAPES = eINSTANCE.getShapesDiagram_Shapes();
}
} //Geftest1Package
| Java |
package info.bond.labs.geftest1;
/**
* @model
*/
public interface EllipticalShape extends Shape {
}
| Java |
/**
* <copyright>
* </copyright>
*
* $Id$
*/
package info.bond.labs.geftest1.util;
import info.bond.labs.geftest1.*;
import org.eclipse.emf.common.notify.Adapter;
import org.eclipse.emf.common.notify.Notifier;
import org.eclipse.emf.common.notify.impl.AdapterFactoryImpl;
import org.eclipse.emf.ecore.EObject;
/**
* <!-- begin-user-doc -->
* The <b>Adapter Factory</b> for the model.
* It provides an adapter <code>createXXX</code> method for each class of the model.
* <!-- end-user-doc -->
* @see info.bond.labs.geftest1.Geftest1Package
* @generated
*/
public class Geftest1AdapterFactory extends AdapterFactoryImpl {
/**
* The cached model package.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected static Geftest1Package modelPackage;
/**
* Creates an instance of the adapter factory.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Geftest1AdapterFactory() {
if (modelPackage == null) {
modelPackage = Geftest1Package.eINSTANCE;
}
}
/**
* Returns whether this factory is applicable for the type of the object.
* <!-- begin-user-doc -->
* This implementation returns <code>true</code> if the object is either the model's package or is an instance object of the model.
* <!-- end-user-doc -->
* @return whether this factory is applicable for the type of the object.
* @generated
*/
@Override
public boolean isFactoryForType(Object object) {
if (object == modelPackage) {
return true;
}
if (object instanceof EObject) {
return ((EObject)object).eClass().getEPackage() == modelPackage;
}
return false;
}
/**
* The switch that delegates to the <code>createXXX</code> methods.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected Geftest1Switch<Adapter> modelSwitch =
new Geftest1Switch<Adapter>() {
@Override
public Adapter caseConnection(Connection object) {
return createConnectionAdapter();
}
@Override
public Adapter caseEllipticalShape(EllipticalShape object) {
return createEllipticalShapeAdapter();
}
@Override
public Adapter caseRectangularShape(RectangularShape object) {
return createRectangularShapeAdapter();
}
@Override
public Adapter caseShape(Shape object) {
return createShapeAdapter();
}
@Override
public Adapter caseShapesDiagram(ShapesDiagram object) {
return createShapesDiagramAdapter();
}
@Override
public Adapter defaultCase(EObject object) {
return createEObjectAdapter();
}
};
/**
* Creates an adapter for the <code>target</code>.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param target the object to adapt.
* @return the adapter for the <code>target</code>.
* @generated
*/
@Override
public Adapter createAdapter(Notifier target) {
return modelSwitch.doSwitch((EObject)target);
}
/**
* Creates a new adapter for an object of class '{@link info.bond.labs.geftest1.Connection <em>Connection</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see info.bond.labs.geftest1.Connection
* @generated
*/
public Adapter createConnectionAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link info.bond.labs.geftest1.EllipticalShape <em>Elliptical Shape</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see info.bond.labs.geftest1.EllipticalShape
* @generated
*/
public Adapter createEllipticalShapeAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link info.bond.labs.geftest1.RectangularShape <em>Rectangular Shape</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see info.bond.labs.geftest1.RectangularShape
* @generated
*/
public Adapter createRectangularShapeAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link info.bond.labs.geftest1.Shape <em>Shape</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see info.bond.labs.geftest1.Shape
* @generated
*/
public Adapter createShapeAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link info.bond.labs.geftest1.ShapesDiagram <em>Shapes Diagram</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see info.bond.labs.geftest1.ShapesDiagram
* @generated
*/
public Adapter createShapesDiagramAdapter() {
return null;
}
/**
* Creates a new adapter for the default case.
* <!-- begin-user-doc -->
* This default implementation returns null.
* <!-- end-user-doc -->
* @return the new adapter.
* @generated
*/
public Adapter createEObjectAdapter() {
return null;
}
} //Geftest1AdapterFactory
| Java |
/**
* <copyright>
* </copyright>
*
* $Id$
*/
package info.bond.labs.geftest1.util;
import info.bond.labs.geftest1.*;
import java.util.List;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EObject;
/**
* <!-- begin-user-doc -->
* The <b>Switch</b> for the model's inheritance hierarchy.
* It supports the call {@link #doSwitch(EObject) doSwitch(object)}
* to invoke the <code>caseXXX</code> method for each class of the model,
* starting with the actual class of the object
* and proceeding up the inheritance hierarchy
* until a non-null result is returned,
* which is the result of the switch.
* <!-- end-user-doc -->
* @see info.bond.labs.geftest1.Geftest1Package
* @generated
*/
public class Geftest1Switch<T> {
/**
* The cached model package
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected static Geftest1Package modelPackage;
/**
* Creates an instance of the switch.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Geftest1Switch() {
if (modelPackage == null) {
modelPackage = Geftest1Package.eINSTANCE;
}
}
/**
* Calls <code>caseXXX</code> for each class of the model until one returns a non null result; it yields that result.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the first non-null result returned by a <code>caseXXX</code> call.
* @generated
*/
public T doSwitch(EObject theEObject) {
return doSwitch(theEObject.eClass(), theEObject);
}
/**
* Calls <code>caseXXX</code> for each class of the model until one returns a non null result; it yields that result.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the first non-null result returned by a <code>caseXXX</code> call.
* @generated
*/
protected T doSwitch(EClass theEClass, EObject theEObject) {
if (theEClass.eContainer() == modelPackage) {
return doSwitch(theEClass.getClassifierID(), theEObject);
}
else {
List<EClass> eSuperTypes = theEClass.getESuperTypes();
return
eSuperTypes.isEmpty() ?
defaultCase(theEObject) :
doSwitch(eSuperTypes.get(0), theEObject);
}
}
/**
* Calls <code>caseXXX</code> for each class of the model until one returns a non null result; it yields that result.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the first non-null result returned by a <code>caseXXX</code> call.
* @generated
*/
protected T doSwitch(int classifierID, EObject theEObject) {
switch (classifierID) {
case Geftest1Package.CONNECTION: {
Connection connection = (Connection)theEObject;
T result = caseConnection(connection);
if (result == null) result = defaultCase(theEObject);
return result;
}
case Geftest1Package.ELLIPTICAL_SHAPE: {
EllipticalShape ellipticalShape = (EllipticalShape)theEObject;
T result = caseEllipticalShape(ellipticalShape);
if (result == null) result = caseShape(ellipticalShape);
if (result == null) result = defaultCase(theEObject);
return result;
}
case Geftest1Package.RECTANGULAR_SHAPE: {
RectangularShape rectangularShape = (RectangularShape)theEObject;
T result = caseRectangularShape(rectangularShape);
if (result == null) result = caseShape(rectangularShape);
if (result == null) result = defaultCase(theEObject);
return result;
}
case Geftest1Package.SHAPE: {
Shape shape = (Shape)theEObject;
T result = caseShape(shape);
if (result == null) result = defaultCase(theEObject);
return result;
}
case Geftest1Package.SHAPES_DIAGRAM: {
ShapesDiagram shapesDiagram = (ShapesDiagram)theEObject;
T result = caseShapesDiagram(shapesDiagram);
if (result == null) result = defaultCase(theEObject);
return result;
}
default: return defaultCase(theEObject);
}
}
/**
* Returns the result of interpreting the object as an instance of '<em>Connection</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Connection</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseConnection(Connection object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Elliptical Shape</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Elliptical Shape</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseEllipticalShape(EllipticalShape object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Rectangular Shape</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Rectangular Shape</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseRectangularShape(RectangularShape object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Shape</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Shape</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseShape(Shape object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Shapes Diagram</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Shapes Diagram</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T caseShapesDiagram(ShapesDiagram object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>EObject</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch, but this is the last case anyway.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>EObject</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject)
* @generated
*/
public T defaultCase(EObject object) {
return null;
}
} //Geftest1Switch
| Java |
/**
* <copyright>
* </copyright>
*
* $Id$
*/
package info.bondtnt.labs.model.research;
import org.eclipse.emf.ecore.EAttribute;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EPackage;
/**
* <!-- begin-user-doc -->
* The <b>Package</b> for the model.
* It contains accessors for the meta objects to represent
* <ul>
* <li>each class,</li>
* <li>each feature of each class,</li>
* <li>each enum,</li>
* <li>and each data type</li>
* </ul>
* <!-- end-user-doc -->
* @see info.bondtnt.labs.model.research.ResearchFactory
* @model kind="package"
* @generated
*/
public interface ResearchPackage extends EPackage {
/**
* The package name.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
String eNAME = "research";
/**
* The package namespace URI.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
String eNS_URI = "http:///info/bondtnt/labs/model/research.ecore";
/**
* The package namespace name.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
String eNS_PREFIX = "info.bondtnt.labs.model.research";
/**
* The singleton instance of the package.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
ResearchPackage eINSTANCE = info.bondtnt.labs.model.research.impl.ResearchPackageImpl.init();
/**
* The meta object id for the '{@link info.bondtnt.labs.model.research.BoundedParameter <em>Bounded Parameter</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see info.bondtnt.labs.model.research.BoundedParameter
* @see info.bondtnt.labs.model.research.impl.ResearchPackageImpl#getBoundedParameter()
* @generated
*/
int BOUNDED_PARAMETER = 4;
/**
* The meta object id for the '{@link info.bondtnt.labs.model.research.impl.BoundedDoubleParameterImpl <em>Bounded Double Parameter</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see info.bondtnt.labs.model.research.impl.BoundedDoubleParameterImpl
* @see info.bondtnt.labs.model.research.impl.ResearchPackageImpl#getBoundedDoubleParameter()
* @generated
*/
int BOUNDED_DOUBLE_PARAMETER = 0;
/**
* The feature id for the '<em><b>First Value</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int BOUNDED_DOUBLE_PARAMETER__FIRST_VALUE = 0;
/**
* The feature id for the '<em><b>Last Value</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int BOUNDED_DOUBLE_PARAMETER__LAST_VALUE = 1;
/**
* The feature id for the '<em><b>All Values</b></em>' attribute list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int BOUNDED_DOUBLE_PARAMETER__ALL_VALUES = 2;
/**
* The feature id for the '<em><b>Step Value</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int BOUNDED_DOUBLE_PARAMETER__STEP_VALUE = 3;
/**
* The feature id for the '<em><b>Name</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int BOUNDED_DOUBLE_PARAMETER__NAME = 4;
/**
* The number of structural features of the '<em>Bounded Double Parameter</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int BOUNDED_DOUBLE_PARAMETER_FEATURE_COUNT = 5;
/**
* The meta object id for the '{@link info.bondtnt.labs.model.research.impl.NamedDoubleParameterImpl <em>Named Double Parameter</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see info.bondtnt.labs.model.research.impl.NamedDoubleParameterImpl
* @see info.bondtnt.labs.model.research.impl.ResearchPackageImpl#getNamedDoubleParameter()
* @generated
*/
int NAMED_DOUBLE_PARAMETER = 1;
/**
* The feature id for the '<em><b>Name</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int NAMED_DOUBLE_PARAMETER__NAME = 0;
/**
* The feature id for the '<em><b>Value</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int NAMED_DOUBLE_PARAMETER__VALUE = 1;
/**
* The number of structural features of the '<em>Named Double Parameter</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int NAMED_DOUBLE_PARAMETER_FEATURE_COUNT = 2;
/**
* The meta object id for the '{@link info.bondtnt.labs.model.research.impl.ParametersListImpl <em>Parameters List</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see info.bondtnt.labs.model.research.impl.ParametersListImpl
* @see info.bondtnt.labs.model.research.impl.ResearchPackageImpl#getParametersList()
* @generated
*/
int PARAMETERS_LIST = 2;
/**
* The feature id for the '<em><b>List</b></em>' attribute list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int PARAMETERS_LIST__LIST = 0;
/**
* The number of structural features of the '<em>Parameters List</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int PARAMETERS_LIST_FEATURE_COUNT = 1;
/**
* The meta object id for the '{@link info.bondtnt.labs.model.research.impl.BoundedTypedParameterImpl <em>Bounded Typed Parameter</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see info.bondtnt.labs.model.research.impl.BoundedTypedParameterImpl
* @see info.bondtnt.labs.model.research.impl.ResearchPackageImpl#getBoundedTypedParameter()
* @generated
*/
int BOUNDED_TYPED_PARAMETER = 3;
/**
* The feature id for the '<em><b>All Values</b></em>' attribute list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int BOUNDED_TYPED_PARAMETER__ALL_VALUES = 0;
/**
* The feature id for the '<em><b>Name</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int BOUNDED_TYPED_PARAMETER__NAME = 1;
/**
* The number of structural features of the '<em>Bounded Typed Parameter</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int BOUNDED_TYPED_PARAMETER_FEATURE_COUNT = 2;
/**
* The number of structural features of the '<em>Bounded Parameter</em>' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
int BOUNDED_PARAMETER_FEATURE_COUNT = 0;
/**
* Returns the meta object for class '{@link info.bondtnt.labs.model.research.BoundedDoubleParameter <em>Bounded Double Parameter</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Bounded Double Parameter</em>'.
* @see info.bondtnt.labs.model.research.BoundedDoubleParameter
* @generated
*/
EClass getBoundedDoubleParameter();
/**
* Returns the meta object for the attribute '{@link info.bondtnt.labs.model.research.BoundedDoubleParameter#getFirstValue <em>First Value</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>First Value</em>'.
* @see info.bondtnt.labs.model.research.BoundedDoubleParameter#getFirstValue()
* @see #getBoundedDoubleParameter()
* @generated
*/
EAttribute getBoundedDoubleParameter_FirstValue();
/**
* Returns the meta object for the attribute '{@link info.bondtnt.labs.model.research.BoundedDoubleParameter#getLastValue <em>Last Value</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Last Value</em>'.
* @see info.bondtnt.labs.model.research.BoundedDoubleParameter#getLastValue()
* @see #getBoundedDoubleParameter()
* @generated
*/
EAttribute getBoundedDoubleParameter_LastValue();
/**
* Returns the meta object for the attribute list '{@link info.bondtnt.labs.model.research.BoundedDoubleParameter#getAllValues <em>All Values</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute list '<em>All Values</em>'.
* @see info.bondtnt.labs.model.research.BoundedDoubleParameter#getAllValues()
* @see #getBoundedDoubleParameter()
* @generated
*/
EAttribute getBoundedDoubleParameter_AllValues();
/**
* Returns the meta object for the attribute '{@link info.bondtnt.labs.model.research.BoundedDoubleParameter#getStepValue <em>Step Value</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Step Value</em>'.
* @see info.bondtnt.labs.model.research.BoundedDoubleParameter#getStepValue()
* @see #getBoundedDoubleParameter()
* @generated
*/
EAttribute getBoundedDoubleParameter_StepValue();
/**
* Returns the meta object for the attribute '{@link info.bondtnt.labs.model.research.BoundedDoubleParameter#getName <em>Name</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Name</em>'.
* @see info.bondtnt.labs.model.research.BoundedDoubleParameter#getName()
* @see #getBoundedDoubleParameter()
* @generated
*/
EAttribute getBoundedDoubleParameter_Name();
/**
* Returns the meta object for class '{@link info.bondtnt.labs.model.research.NamedDoubleParameter <em>Named Double Parameter</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Named Double Parameter</em>'.
* @see info.bondtnt.labs.model.research.NamedDoubleParameter
* @generated
*/
EClass getNamedDoubleParameter();
/**
* Returns the meta object for the attribute '{@link info.bondtnt.labs.model.research.NamedDoubleParameter#getName <em>Name</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Name</em>'.
* @see info.bondtnt.labs.model.research.NamedDoubleParameter#getName()
* @see #getNamedDoubleParameter()
* @generated
*/
EAttribute getNamedDoubleParameter_Name();
/**
* Returns the meta object for the attribute '{@link info.bondtnt.labs.model.research.NamedDoubleParameter#getValue <em>Value</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Value</em>'.
* @see info.bondtnt.labs.model.research.NamedDoubleParameter#getValue()
* @see #getNamedDoubleParameter()
* @generated
*/
EAttribute getNamedDoubleParameter_Value();
/**
* Returns the meta object for class '{@link info.bondtnt.labs.model.research.ParametersList <em>Parameters List</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Parameters List</em>'.
* @see info.bondtnt.labs.model.research.ParametersList
* @generated
*/
EClass getParametersList();
/**
* Returns the meta object for the attribute list '{@link info.bondtnt.labs.model.research.ParametersList#getList <em>List</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute list '<em>List</em>'.
* @see info.bondtnt.labs.model.research.ParametersList#getList()
* @see #getParametersList()
* @generated
*/
EAttribute getParametersList_List();
/**
* Returns the meta object for class '{@link info.bondtnt.labs.model.research.BoundedTypedParameter <em>Bounded Typed Parameter</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Bounded Typed Parameter</em>'.
* @see info.bondtnt.labs.model.research.BoundedTypedParameter
* @generated
*/
EClass getBoundedTypedParameter();
/**
* Returns the meta object for the attribute list '{@link info.bondtnt.labs.model.research.BoundedTypedParameter#getAllValues <em>All Values</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute list '<em>All Values</em>'.
* @see info.bondtnt.labs.model.research.BoundedTypedParameter#getAllValues()
* @see #getBoundedTypedParameter()
* @generated
*/
EAttribute getBoundedTypedParameter_AllValues();
/**
* Returns the meta object for the attribute '{@link info.bondtnt.labs.model.research.BoundedTypedParameter#getName <em>Name</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Name</em>'.
* @see info.bondtnt.labs.model.research.BoundedTypedParameter#getName()
* @see #getBoundedTypedParameter()
* @generated
*/
EAttribute getBoundedTypedParameter_Name();
/**
* Returns the meta object for class '{@link info.bondtnt.labs.model.research.BoundedParameter <em>Bounded Parameter</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Bounded Parameter</em>'.
* @see info.bondtnt.labs.model.research.BoundedParameter
* @model instanceClass="info.bondtnt.labs.model.research.BoundedParameter" typeParameters="T"
* @generated
*/
EClass getBoundedParameter();
/**
* Returns the factory that creates the instances of the model.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the factory that creates the instances of the model.
* @generated
*/
ResearchFactory getResearchFactory();
/**
* <!-- begin-user-doc -->
* Defines literals for the meta objects that represent
* <ul>
* <li>each class,</li>
* <li>each feature of each class,</li>
* <li>each enum,</li>
* <li>and each data type</li>
* </ul>
* <!-- end-user-doc -->
* @generated
*/
interface Literals {
/**
* The meta object literal for the '{@link info.bondtnt.labs.model.research.impl.BoundedDoubleParameterImpl <em>Bounded Double Parameter</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see info.bondtnt.labs.model.research.impl.BoundedDoubleParameterImpl
* @see info.bondtnt.labs.model.research.impl.ResearchPackageImpl#getBoundedDoubleParameter()
* @generated
*/
EClass BOUNDED_DOUBLE_PARAMETER = eINSTANCE.getBoundedDoubleParameter();
/**
* The meta object literal for the '<em><b>First Value</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute BOUNDED_DOUBLE_PARAMETER__FIRST_VALUE = eINSTANCE.getBoundedDoubleParameter_FirstValue();
/**
* The meta object literal for the '<em><b>Last Value</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute BOUNDED_DOUBLE_PARAMETER__LAST_VALUE = eINSTANCE.getBoundedDoubleParameter_LastValue();
/**
* The meta object literal for the '<em><b>All Values</b></em>' attribute list feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute BOUNDED_DOUBLE_PARAMETER__ALL_VALUES = eINSTANCE.getBoundedDoubleParameter_AllValues();
/**
* The meta object literal for the '<em><b>Step Value</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute BOUNDED_DOUBLE_PARAMETER__STEP_VALUE = eINSTANCE.getBoundedDoubleParameter_StepValue();
/**
* The meta object literal for the '<em><b>Name</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute BOUNDED_DOUBLE_PARAMETER__NAME = eINSTANCE.getBoundedDoubleParameter_Name();
/**
* The meta object literal for the '{@link info.bondtnt.labs.model.research.impl.NamedDoubleParameterImpl <em>Named Double Parameter</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see info.bondtnt.labs.model.research.impl.NamedDoubleParameterImpl
* @see info.bondtnt.labs.model.research.impl.ResearchPackageImpl#getNamedDoubleParameter()
* @generated
*/
EClass NAMED_DOUBLE_PARAMETER = eINSTANCE.getNamedDoubleParameter();
/**
* The meta object literal for the '<em><b>Name</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute NAMED_DOUBLE_PARAMETER__NAME = eINSTANCE.getNamedDoubleParameter_Name();
/**
* The meta object literal for the '<em><b>Value</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute NAMED_DOUBLE_PARAMETER__VALUE = eINSTANCE.getNamedDoubleParameter_Value();
/**
* The meta object literal for the '{@link info.bondtnt.labs.model.research.impl.ParametersListImpl <em>Parameters List</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see info.bondtnt.labs.model.research.impl.ParametersListImpl
* @see info.bondtnt.labs.model.research.impl.ResearchPackageImpl#getParametersList()
* @generated
*/
EClass PARAMETERS_LIST = eINSTANCE.getParametersList();
/**
* The meta object literal for the '<em><b>List</b></em>' attribute list feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute PARAMETERS_LIST__LIST = eINSTANCE.getParametersList_List();
/**
* The meta object literal for the '{@link info.bondtnt.labs.model.research.impl.BoundedTypedParameterImpl <em>Bounded Typed Parameter</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see info.bondtnt.labs.model.research.impl.BoundedTypedParameterImpl
* @see info.bondtnt.labs.model.research.impl.ResearchPackageImpl#getBoundedTypedParameter()
* @generated
*/
EClass BOUNDED_TYPED_PARAMETER = eINSTANCE.getBoundedTypedParameter();
/**
* The meta object literal for the '<em><b>All Values</b></em>' attribute list feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute BOUNDED_TYPED_PARAMETER__ALL_VALUES = eINSTANCE.getBoundedTypedParameter_AllValues();
/**
* The meta object literal for the '<em><b>Name</b></em>' attribute feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
EAttribute BOUNDED_TYPED_PARAMETER__NAME = eINSTANCE.getBoundedTypedParameter_Name();
/**
* The meta object literal for the '{@link info.bondtnt.labs.model.research.BoundedParameter <em>Bounded Parameter</em>}' class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see info.bondtnt.labs.model.research.BoundedParameter
* @see info.bondtnt.labs.model.research.impl.ResearchPackageImpl#getBoundedParameter()
* @generated
*/
EClass BOUNDED_PARAMETER = eINSTANCE.getBoundedParameter();
}
} //ResearchPackage
| Java |
package info.bondtnt.labs.model.research;
import org.eclipse.emf.ecore.EObject;
/**
* @author <a href="mailto:bondtnt@gmail.com">Andrey Bondarenko</a>
* @model
*/
public interface NamedDoubleParameter extends EObject {
/**
* @model
*/
public String getName();
/**
* Sets the value of the '{@link info.bondtnt.labs.model.research.NamedDoubleParameter#getName <em>Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Name</em>' attribute.
* @see #getName()
* @generated
*/
void setName(String value);
/**
* @model
*/
public Double getValue();
/**
* Sets the value of the '{@link info.bondtnt.labs.model.research.NamedDoubleParameter#getValue <em>Value</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Value</em>' attribute.
* @see #getValue()
* @generated
*/
void setValue(Double value);
}
| Java |
package info.bondtnt.labs.model.research;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EObject;
/**
* @author <a href="mailto:bondtnt@gmail.com">Andrey Bondarenko</a>
* @model
*/
public interface BoundedTypedParameter<Type> extends EObject {
/**
* @model changeable="false"
*/
public EList<Type> getAllValues();
/**
* @model
*/
public void addValue(Type value);
/**
* @model
*/
public void removeAllValues();
/**
* @model
*/
public void removeValue(Type value);
/**
* @model
*/
public abstract String getName();
/**
* Sets the value of the '{@link info.bondtnt.labs.model.research.BoundedTypedParameter#getName <em>Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Name</em>' attribute.
* @see #getName()
* @generated
*/
void setName(String value);
/**
* @model changeable="false"
*/
public abstract Integer countOfValues();
/**
* Returns value according to its index.
* First index is 0; Last index is (countOfValues() - 1);
* First value usually is less than last;
*
* @model changeable="false"
*/
public abstract Type getValueByIndex(Integer index);
}
| Java |
package info.bondtnt.labs.model.research;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EObject;
/**
* @author <a href="mailto:bondtnt@gmail.com">Andrey Bondarenko</a>
* @model
*/
public interface ParametersList<Type> extends EObject {
/**
* @model containment=true
*/
public EList<Type> getList();
/**
* @model
*/
public void addParameter(Type namedParam);
}
| Java |
/**
* <copyright>
* </copyright>
*
* $Id$
*/
package info.bondtnt.labs.model.research.impl;
import info.bondtnt.labs.model.research.ParametersList;
import info.bondtnt.labs.model.research.ResearchPackage;
import java.util.Collection;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.impl.EObjectImpl;
import org.eclipse.emf.ecore.util.EDataTypeUniqueEList;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Parameters List</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link info.bondtnt.labs.model.research.impl.ParametersListImpl#getList <em>List</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public class ParametersListImpl<Type> extends EObjectImpl implements ParametersList<Type> {
/**
* The cached value of the '{@link #getList() <em>List</em>}' attribute list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getList()
* @generated
* @ordered
*/
protected EList<Type> list;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected ParametersListImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return ResearchPackage.Literals.PARAMETERS_LIST;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<Type> getList() {
if (list == null) {
list = new EDataTypeUniqueEList<Type>(Object.class, this, ResearchPackage.PARAMETERS_LIST__LIST);
}
return list;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void addParameter(Type namedParam) {
// TODO: implement this method
// Ensure that you remove @generated or mark it @generated NOT
throw new UnsupportedOperationException();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case ResearchPackage.PARAMETERS_LIST__LIST:
return getList();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case ResearchPackage.PARAMETERS_LIST__LIST:
getList().clear();
getList().addAll((Collection<? extends Type>)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case ResearchPackage.PARAMETERS_LIST__LIST:
getList().clear();
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case ResearchPackage.PARAMETERS_LIST__LIST:
return list != null && !list.isEmpty();
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
if (eIsProxy()) return super.toString();
StringBuffer result = new StringBuffer(super.toString());
result.append(" (list: ");
result.append(list);
result.append(')');
return result.toString();
}
} //ParametersListImpl
| Java |
/**
* <copyright>
* </copyright>
*
* $Id$
*/
package info.bondtnt.labs.model.research.impl;
import info.bondtnt.labs.model.research.NamedDoubleParameter;
import info.bondtnt.labs.model.research.ResearchPackage;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.impl.EObjectImpl;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Named Double Parameter</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link info.bondtnt.labs.model.research.impl.NamedDoubleParameterImpl#getName <em>Name</em>}</li>
* <li>{@link info.bondtnt.labs.model.research.impl.NamedDoubleParameterImpl#getValue <em>Value</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public class NamedDoubleParameterImpl extends EObjectImpl implements NamedDoubleParameter {
/**
* The default value of the '{@link #getName() <em>Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getName()
* @generated
* @ordered
*/
protected static final String NAME_EDEFAULT = null;
/**
* The cached value of the '{@link #getName() <em>Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getName()
* @generated
* @ordered
*/
protected String name = NAME_EDEFAULT;
/**
* The default value of the '{@link #getValue() <em>Value</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getValue()
* @generated
* @ordered
*/
protected static final Double VALUE_EDEFAULT = null;
/**
* The cached value of the '{@link #getValue() <em>Value</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getValue()
* @generated
* @ordered
*/
protected Double value = VALUE_EDEFAULT;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected NamedDoubleParameterImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return ResearchPackage.Literals.NAMED_DOUBLE_PARAMETER;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getName() {
return name;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setName(String newName) {
String oldName = name;
name = newName;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, ResearchPackage.NAMED_DOUBLE_PARAMETER__NAME, oldName, name));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Double getValue() {
return value;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setValue(Double newValue) {
Double oldValue = value;
value = newValue;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, ResearchPackage.NAMED_DOUBLE_PARAMETER__VALUE, oldValue, value));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case ResearchPackage.NAMED_DOUBLE_PARAMETER__NAME:
return getName();
case ResearchPackage.NAMED_DOUBLE_PARAMETER__VALUE:
return getValue();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case ResearchPackage.NAMED_DOUBLE_PARAMETER__NAME:
setName((String)newValue);
return;
case ResearchPackage.NAMED_DOUBLE_PARAMETER__VALUE:
setValue((Double)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case ResearchPackage.NAMED_DOUBLE_PARAMETER__NAME:
setName(NAME_EDEFAULT);
return;
case ResearchPackage.NAMED_DOUBLE_PARAMETER__VALUE:
setValue(VALUE_EDEFAULT);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case ResearchPackage.NAMED_DOUBLE_PARAMETER__NAME:
return NAME_EDEFAULT == null ? name != null : !NAME_EDEFAULT.equals(name);
case ResearchPackage.NAMED_DOUBLE_PARAMETER__VALUE:
return VALUE_EDEFAULT == null ? value != null : !VALUE_EDEFAULT.equals(value);
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
if (eIsProxy()) return super.toString();
StringBuffer result = new StringBuffer(super.toString());
result.append(" (name: ");
result.append(name);
result.append(", value: ");
result.append(value);
result.append(')');
return result.toString();
}
} //NamedDoubleParameterImpl
| Java |
/**
* <copyright>
* </copyright>
*
* $Id$
*/
package info.bondtnt.labs.model.research.impl;
import info.bondtnt.labs.model.research.BoundedDoubleParameter;
import info.bondtnt.labs.model.research.ResearchPackage;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.impl.EObjectImpl;
import org.eclipse.emf.ecore.util.EDataTypeUniqueEList;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Bounded Double Parameter</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link info.bondtnt.labs.model.research.impl.BoundedDoubleParameterImpl#getFirstValue <em>First Value</em>}</li>
* <li>{@link info.bondtnt.labs.model.research.impl.BoundedDoubleParameterImpl#getLastValue <em>Last Value</em>}</li>
* <li>{@link info.bondtnt.labs.model.research.impl.BoundedDoubleParameterImpl#getAllValues <em>All Values</em>}</li>
* <li>{@link info.bondtnt.labs.model.research.impl.BoundedDoubleParameterImpl#getStepValue <em>Step Value</em>}</li>
* <li>{@link info.bondtnt.labs.model.research.impl.BoundedDoubleParameterImpl#getName <em>Name</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public class BoundedDoubleParameterImpl extends EObjectImpl implements BoundedDoubleParameter {
private static final int PRECISION_ENCHASER = 1000;
/**
* The default value of the '{@link #getFirstValue() <em>First Value</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getFirstValue()
* @generated
* @ordered
*/
protected static final Double FIRST_VALUE_EDEFAULT = null;
/**
* The cached value of the '{@link #getFirstValue() <em>First Value</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getFirstValue()
* @generated
* @ordered
*/
protected Double firstValue = FIRST_VALUE_EDEFAULT;
/**
* The default value of the '{@link #getLastValue() <em>Last Value</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getLastValue()
* @generated
* @ordered
*/
protected static final Double LAST_VALUE_EDEFAULT = null;
/**
* The cached value of the '{@link #getLastValue() <em>Last Value</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getLastValue()
* @generated
* @ordered
*/
protected Double lastValue = LAST_VALUE_EDEFAULT;
/**
* The cached value of the '{@link #getAllValues() <em>All Values</em>}' attribute list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getAllValues()
* @generated
* @ordered
*/
protected EList<Double> allValues;
/**
* The default value of the '{@link #getStepValue() <em>Step Value</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getStepValue()
* @generated
* @ordered
*/
protected static final Double STEP_VALUE_EDEFAULT = null;
/**
* The cached value of the '{@link #getStepValue() <em>Step Value</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getStepValue()
* @generated
* @ordered
*/
protected Double stepValue = STEP_VALUE_EDEFAULT;
/**
* The default value of the '{@link #getName() <em>Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getName()
* @generated
* @ordered
*/
protected static final String NAME_EDEFAULT = null;
private Integer countOfValues = 0;
private String name;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected BoundedDoubleParameterImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return ResearchPackage.Literals.BOUNDED_DOUBLE_PARAMETER;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated NOT
*/
public Integer countOfValues() {
return countOfValues;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Double getFirstValue() {
return firstValue;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Double getLastValue() {
return lastValue;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<Double> getAllValues() {
if (allValues == null) {
allValues = new EDataTypeUniqueEList<Double>(Double.class, this, ResearchPackage.BOUNDED_DOUBLE_PARAMETER__ALL_VALUES);
}
return allValues;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Double getStepValue() {
return stepValue;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated NOT
*/
public Double getValueByIndex(Integer index) {
Double result = null;
if (index < this.countOfValues()) {
Double value = this.getFirstValue();
final Double stepVal = this.getStepValue();
value = value*PRECISION_ENCHASER + stepVal*PRECISION_ENCHASER*index;
result = value/PRECISION_ENCHASER;
} else {
throw new IllegalArgumentException("Parameter 'index' must be less than countOfvalues()!");
}
return result;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated NOT
*/
public void setBoundaries(double firstValue, double lastValue, double stepValue) {
if (firstValue > lastValue) {
throw new IllegalArgumentException("'lastValue' can't be greater than 'firstValue'");
}
this.firstValue = firstValue;
this.lastValue = lastValue;
this.stepValue = stepValue;
countOfValues = 0;
Double value = firstValue;
EList<Double> allValuesList = this.getAllValues();
do {
allValuesList.add(value);
countOfValues++;
value = value + stepValue;
} while (value.doubleValue() <= lastValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case ResearchPackage.BOUNDED_DOUBLE_PARAMETER__FIRST_VALUE:
return getFirstValue();
case ResearchPackage.BOUNDED_DOUBLE_PARAMETER__LAST_VALUE:
return getLastValue();
case ResearchPackage.BOUNDED_DOUBLE_PARAMETER__ALL_VALUES:
return getAllValues();
case ResearchPackage.BOUNDED_DOUBLE_PARAMETER__STEP_VALUE:
return getStepValue();
case ResearchPackage.BOUNDED_DOUBLE_PARAMETER__NAME:
return getName();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case ResearchPackage.BOUNDED_DOUBLE_PARAMETER__NAME:
setName((String)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case ResearchPackage.BOUNDED_DOUBLE_PARAMETER__NAME:
setName(NAME_EDEFAULT);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case ResearchPackage.BOUNDED_DOUBLE_PARAMETER__FIRST_VALUE:
return FIRST_VALUE_EDEFAULT == null ? firstValue != null : !FIRST_VALUE_EDEFAULT.equals(firstValue);
case ResearchPackage.BOUNDED_DOUBLE_PARAMETER__LAST_VALUE:
return LAST_VALUE_EDEFAULT == null ? lastValue != null : !LAST_VALUE_EDEFAULT.equals(lastValue);
case ResearchPackage.BOUNDED_DOUBLE_PARAMETER__ALL_VALUES:
return allValues != null && !allValues.isEmpty();
case ResearchPackage.BOUNDED_DOUBLE_PARAMETER__STEP_VALUE:
return STEP_VALUE_EDEFAULT == null ? stepValue != null : !STEP_VALUE_EDEFAULT.equals(stepValue);
case ResearchPackage.BOUNDED_DOUBLE_PARAMETER__NAME:
return NAME_EDEFAULT == null ? name != null : !NAME_EDEFAULT.equals(name);
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
if (eIsProxy()) return super.toString();
StringBuffer result = new StringBuffer(super.toString());
result.append(" (firstValue: ");
result.append(firstValue);
result.append(", lastValue: ");
result.append(lastValue);
result.append(", allValues: ");
result.append(allValues);
result.append(", stepValue: ");
result.append(stepValue);
result.append(", name: ");
result.append(name);
result.append(')');
return result.toString();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String getName() {
return name;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void setName(String newName) {
String oldName = name;
name = newName;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, ResearchPackage.BOUNDED_DOUBLE_PARAMETER__NAME, oldName, name));
}
} //BoundedDoubleParameterImpl
| Java |
/**
* <copyright>
* </copyright>
*
* $Id$
*/
package info.bondtnt.labs.model.research.impl;
import info.bondtnt.labs.model.research.BoundedDoubleParameter;
import info.bondtnt.labs.model.research.BoundedTypedParameter;
import info.bondtnt.labs.model.research.NamedDoubleParameter;
import info.bondtnt.labs.model.research.ParametersList;
import info.bondtnt.labs.model.research.ResearchFactory;
import info.bondtnt.labs.model.research.ResearchPackage;
import org.eclipse.emf.ecore.EAttribute;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EGenericType;
import org.eclipse.emf.ecore.EOperation;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.ETypeParameter;
import org.eclipse.emf.ecore.impl.EPackageImpl;
/**
* <!-- begin-user-doc -->
* An implementation of the model <b>Package</b>.
* <!-- end-user-doc -->
* @generated
*/
public class ResearchPackageImpl extends EPackageImpl implements ResearchPackage {
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private EClass boundedDoubleParameterEClass = null;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private EClass namedDoubleParameterEClass = null;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private EClass parametersListEClass = null;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private EClass boundedTypedParameterEClass = null;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private EClass boundedParameterEClass = null;
/**
* Creates an instance of the model <b>Package</b>, registered with
* {@link org.eclipse.emf.ecore.EPackage.Registry EPackage.Registry} by the package
* package URI value.
* <p>Note: the correct way to create the package is via the static
* factory method {@link #init init()}, which also performs
* initialization of the package, or returns the registered package,
* if one already exists.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see org.eclipse.emf.ecore.EPackage.Registry
* @see info.bondtnt.labs.model.research.ResearchPackage#eNS_URI
* @see #init()
* @generated
*/
private ResearchPackageImpl() {
super(eNS_URI, ResearchFactory.eINSTANCE);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private static boolean isInited = false;
/**
* Creates, registers, and initializes the <b>Package</b> for this
* model, and for any others upon which it depends. Simple
* dependencies are satisfied by calling this method on all
* dependent packages before doing anything else. This method drives
* initialization for interdependent packages directly, in parallel
* with this package, itself.
* <p>Of this package and its interdependencies, all packages which
* have not yet been registered by their URI values are first created
* and registered. The packages are then initialized in two steps:
* meta-model objects for all of the packages are created before any
* are initialized, since one package's meta-model objects may refer to
* those of another.
* <p>Invocation of this method will not affect any packages that have
* already been initialized.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #eNS_URI
* @see #createPackageContents()
* @see #initializePackageContents()
* @generated
*/
public static ResearchPackage init() {
if (isInited) return (ResearchPackage)EPackage.Registry.INSTANCE.getEPackage(ResearchPackage.eNS_URI);
// Obtain or create and register package
ResearchPackageImpl theResearchPackage = (ResearchPackageImpl)(EPackage.Registry.INSTANCE.getEPackage(eNS_URI) instanceof ResearchPackageImpl ? EPackage.Registry.INSTANCE.getEPackage(eNS_URI) : new ResearchPackageImpl());
isInited = true;
// Create package meta-data objects
theResearchPackage.createPackageContents();
// Initialize created meta-data
theResearchPackage.initializePackageContents();
// Mark meta-data to indicate it can't be changed
theResearchPackage.freeze();
return theResearchPackage;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EClass getBoundedDoubleParameter() {
return boundedDoubleParameterEClass;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EAttribute getBoundedDoubleParameter_FirstValue() {
return (EAttribute)boundedDoubleParameterEClass.getEStructuralFeatures().get(0);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EAttribute getBoundedDoubleParameter_LastValue() {
return (EAttribute)boundedDoubleParameterEClass.getEStructuralFeatures().get(1);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EAttribute getBoundedDoubleParameter_AllValues() {
return (EAttribute)boundedDoubleParameterEClass.getEStructuralFeatures().get(2);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EAttribute getBoundedDoubleParameter_StepValue() {
return (EAttribute)boundedDoubleParameterEClass.getEStructuralFeatures().get(3);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EAttribute getBoundedDoubleParameter_Name() {
return (EAttribute)boundedDoubleParameterEClass.getEStructuralFeatures().get(4);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EClass getNamedDoubleParameter() {
return namedDoubleParameterEClass;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EAttribute getNamedDoubleParameter_Name() {
return (EAttribute)namedDoubleParameterEClass.getEStructuralFeatures().get(0);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EAttribute getNamedDoubleParameter_Value() {
return (EAttribute)namedDoubleParameterEClass.getEStructuralFeatures().get(1);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EClass getParametersList() {
return parametersListEClass;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EAttribute getParametersList_List() {
return (EAttribute)parametersListEClass.getEStructuralFeatures().get(0);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EClass getBoundedTypedParameter() {
return boundedTypedParameterEClass;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EAttribute getBoundedTypedParameter_AllValues() {
return (EAttribute)boundedTypedParameterEClass.getEStructuralFeatures().get(0);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EAttribute getBoundedTypedParameter_Name() {
return (EAttribute)boundedTypedParameterEClass.getEStructuralFeatures().get(1);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EClass getBoundedParameter() {
return boundedParameterEClass;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ResearchFactory getResearchFactory() {
return (ResearchFactory)getEFactoryInstance();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private boolean isCreated = false;
/**
* Creates the meta-model objects for the package. This method is
* guarded to have no affect on any invocation but its first.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void createPackageContents() {
if (isCreated) return;
isCreated = true;
// Create classes and their features
boundedDoubleParameterEClass = createEClass(BOUNDED_DOUBLE_PARAMETER);
createEAttribute(boundedDoubleParameterEClass, BOUNDED_DOUBLE_PARAMETER__FIRST_VALUE);
createEAttribute(boundedDoubleParameterEClass, BOUNDED_DOUBLE_PARAMETER__LAST_VALUE);
createEAttribute(boundedDoubleParameterEClass, BOUNDED_DOUBLE_PARAMETER__ALL_VALUES);
createEAttribute(boundedDoubleParameterEClass, BOUNDED_DOUBLE_PARAMETER__STEP_VALUE);
createEAttribute(boundedDoubleParameterEClass, BOUNDED_DOUBLE_PARAMETER__NAME);
namedDoubleParameterEClass = createEClass(NAMED_DOUBLE_PARAMETER);
createEAttribute(namedDoubleParameterEClass, NAMED_DOUBLE_PARAMETER__NAME);
createEAttribute(namedDoubleParameterEClass, NAMED_DOUBLE_PARAMETER__VALUE);
parametersListEClass = createEClass(PARAMETERS_LIST);
createEAttribute(parametersListEClass, PARAMETERS_LIST__LIST);
boundedTypedParameterEClass = createEClass(BOUNDED_TYPED_PARAMETER);
createEAttribute(boundedTypedParameterEClass, BOUNDED_TYPED_PARAMETER__ALL_VALUES);
createEAttribute(boundedTypedParameterEClass, BOUNDED_TYPED_PARAMETER__NAME);
boundedParameterEClass = createEClass(BOUNDED_PARAMETER);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private boolean isInitialized = false;
/**
* Complete the initialization of the package and its meta-model. This
* method is guarded to have no affect on any invocation but its first.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void initializePackageContents() {
if (isInitialized) return;
isInitialized = true;
// Initialize package
setName(eNAME);
setNsPrefix(eNS_PREFIX);
setNsURI(eNS_URI);
// Create type parameters
ETypeParameter parametersListEClass_Type = addETypeParameter(parametersListEClass, "Type");
ETypeParameter boundedTypedParameterEClass_Type = addETypeParameter(boundedTypedParameterEClass, "Type");
addETypeParameter(boundedParameterEClass, "T");
// Set bounds for type parameters
// Add supertypes to classes
// Initialize classes and features; add operations and parameters
initEClass(boundedDoubleParameterEClass, BoundedDoubleParameter.class, "BoundedDoubleParameter", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS);
initEAttribute(getBoundedDoubleParameter_FirstValue(), ecorePackage.getEDoubleObject(), "firstValue", null, 0, 1, BoundedDoubleParameter.class, !IS_TRANSIENT, !IS_VOLATILE, !IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEAttribute(getBoundedDoubleParameter_LastValue(), ecorePackage.getEDoubleObject(), "lastValue", null, 0, 1, BoundedDoubleParameter.class, !IS_TRANSIENT, !IS_VOLATILE, !IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEAttribute(getBoundedDoubleParameter_AllValues(), ecorePackage.getEDoubleObject(), "allValues", null, 0, -1, BoundedDoubleParameter.class, !IS_TRANSIENT, !IS_VOLATILE, !IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEAttribute(getBoundedDoubleParameter_StepValue(), ecorePackage.getEDoubleObject(), "stepValue", null, 0, 1, BoundedDoubleParameter.class, !IS_TRANSIENT, !IS_VOLATILE, !IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEAttribute(getBoundedDoubleParameter_Name(), ecorePackage.getEString(), "name", null, 0, 1, BoundedDoubleParameter.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
EOperation op = addEOperation(boundedDoubleParameterEClass, null, "setBoundaries", 0, 1, IS_UNIQUE, IS_ORDERED);
addEParameter(op, ecorePackage.getEDouble(), "firstValue", 0, 1, IS_UNIQUE, IS_ORDERED);
addEParameter(op, ecorePackage.getEDouble(), "lastValue", 0, 1, IS_UNIQUE, IS_ORDERED);
addEParameter(op, ecorePackage.getEDouble(), "stepValue", 0, 1, IS_UNIQUE, IS_ORDERED);
addEOperation(boundedDoubleParameterEClass, ecorePackage.getEIntegerObject(), "countOfValues", 0, 1, IS_UNIQUE, IS_ORDERED);
op = addEOperation(boundedDoubleParameterEClass, ecorePackage.getEDoubleObject(), "getValueByIndex", 0, 1, IS_UNIQUE, IS_ORDERED);
addEParameter(op, ecorePackage.getEIntegerObject(), "index", 0, 1, IS_UNIQUE, IS_ORDERED);
initEClass(namedDoubleParameterEClass, NamedDoubleParameter.class, "NamedDoubleParameter", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS);
initEAttribute(getNamedDoubleParameter_Name(), ecorePackage.getEString(), "name", null, 0, 1, NamedDoubleParameter.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEAttribute(getNamedDoubleParameter_Value(), ecorePackage.getEDoubleObject(), "value", null, 0, 1, NamedDoubleParameter.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEClass(parametersListEClass, ParametersList.class, "ParametersList", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS);
EGenericType g1 = createEGenericType(parametersListEClass_Type);
initEAttribute(getParametersList_List(), g1, "list", null, 0, -1, ParametersList.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
op = addEOperation(parametersListEClass, null, "addParameter", 0, 1, IS_UNIQUE, IS_ORDERED);
g1 = createEGenericType(parametersListEClass_Type);
addEParameter(op, g1, "namedParam", 0, 1, IS_UNIQUE, IS_ORDERED);
initEClass(boundedTypedParameterEClass, BoundedTypedParameter.class, "BoundedTypedParameter", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS);
g1 = createEGenericType(boundedTypedParameterEClass_Type);
initEAttribute(getBoundedTypedParameter_AllValues(), g1, "allValues", null, 0, -1, BoundedTypedParameter.class, !IS_TRANSIENT, !IS_VOLATILE, !IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
initEAttribute(getBoundedTypedParameter_Name(), ecorePackage.getEString(), "name", null, 0, 1, BoundedTypedParameter.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED);
op = addEOperation(boundedTypedParameterEClass, null, "addValue", 0, 1, IS_UNIQUE, IS_ORDERED);
g1 = createEGenericType(boundedTypedParameterEClass_Type);
addEParameter(op, g1, "value", 0, 1, IS_UNIQUE, IS_ORDERED);
addEOperation(boundedTypedParameterEClass, null, "removeAllValues", 0, 1, IS_UNIQUE, IS_ORDERED);
op = addEOperation(boundedTypedParameterEClass, null, "removeValue", 0, 1, IS_UNIQUE, IS_ORDERED);
g1 = createEGenericType(boundedTypedParameterEClass_Type);
addEParameter(op, g1, "value", 0, 1, IS_UNIQUE, IS_ORDERED);
addEOperation(boundedTypedParameterEClass, ecorePackage.getEIntegerObject(), "countOfValues", 0, 1, IS_UNIQUE, IS_ORDERED);
op = addEOperation(boundedTypedParameterEClass, null, "getValueByIndex", 0, 1, IS_UNIQUE, IS_ORDERED);
addEParameter(op, ecorePackage.getEIntegerObject(), "index", 0, 1, IS_UNIQUE, IS_ORDERED);
g1 = createEGenericType(boundedTypedParameterEClass_Type);
initEOperation(op, g1);
// Create resource
createResource(eNS_URI);
}
} //ResearchPackageImpl
| Java |
/**
* <copyright>
* </copyright>
*
* $Id$
*/
package info.bondtnt.labs.model.research.impl;
import info.bondtnt.labs.model.research.BoundedTypedParameter;
import info.bondtnt.labs.model.research.ResearchPackage;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.common.util.UniqueEList;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.impl.EObjectImpl;
import org.eclipse.emf.ecore.util.EDataTypeUniqueEList;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Bounded Typed Parameter</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link info.bondtnt.labs.model.research.impl.BoundedTypedParameterImpl#getAllValues <em>All Values</em>}</li>
* <li>{@link info.bondtnt.labs.model.research.impl.BoundedTypedParameterImpl#getName <em>Name</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public class BoundedTypedParameterImpl<Type> extends EObjectImpl implements BoundedTypedParameter<Type> {
/**
* The cached value of the '{@link #getAllValues() <em>All Values</em>}' attribute list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getAllValues()
* @generated
* @ordered
*/
protected EList<Type> allValues;
/**
* The default value of the '{@link #getName() <em>Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getName()
* @generated
* @ordered
*/
protected static final String NAME_EDEFAULT = null;
/**
* The cached value of the '{@link #getName() <em>Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getName()
* @generated
* @ordered
*/
protected String name = NAME_EDEFAULT;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected BoundedTypedParameterImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return ResearchPackage.Literals.BOUNDED_TYPED_PARAMETER;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<Type> getAllValues() {
if (allValues == null) {
allValues = new EDataTypeUniqueEList<Type>(Object.class, this, ResearchPackage.BOUNDED_TYPED_PARAMETER__ALL_VALUES);
}
return allValues;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getName() {
return name;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setName(String newName) {
String oldName = name;
name = newName;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, ResearchPackage.BOUNDED_TYPED_PARAMETER__NAME, oldName, name));
}
private void checkAllValuesNotNull() {
if (allValues == null) {
allValues = new EDataTypeUniqueEList<Type>(Object.class, this, ResearchPackage.BOUNDED_TYPED_PARAMETER__ALL_VALUES);
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated NOT
*/
public Type getValueByIndex(Integer index) {
checkAllValuesNotNull();
return allValues.get(index);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated NOT
*/
public void addValue(Type value) {
checkAllValuesNotNull();
allValues.add(value);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated NOT
*/
public void removeAllValues() {
checkAllValuesNotNull();
allValues.clear();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated NOT
*/
public void removeValue(Type value) {
checkAllValuesNotNull();
allValues.remove(value);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case ResearchPackage.BOUNDED_TYPED_PARAMETER__ALL_VALUES:
return getAllValues();
case ResearchPackage.BOUNDED_TYPED_PARAMETER__NAME:
return getName();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case ResearchPackage.BOUNDED_TYPED_PARAMETER__NAME:
setName((String)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case ResearchPackage.BOUNDED_TYPED_PARAMETER__NAME:
setName(NAME_EDEFAULT);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case ResearchPackage.BOUNDED_TYPED_PARAMETER__ALL_VALUES:
return allValues != null && !allValues.isEmpty();
case ResearchPackage.BOUNDED_TYPED_PARAMETER__NAME:
return NAME_EDEFAULT == null ? name != null : !NAME_EDEFAULT.equals(name);
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
if (eIsProxy()) return super.toString();
StringBuffer result = new StringBuffer(super.toString());
result.append(" (allValues: ");
result.append(allValues);
result.append(", name: ");
result.append(name);
result.append(')');
return result.toString();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated NOT
*/
@Override
public Integer countOfValues() {
checkAllValuesNotNull();
return this.allValues.size();
}
} //BoundedTypedParameterImpl
| Java |
/**
* <copyright>
* </copyright>
*
* $Id$
*/
package info.bondtnt.labs.model.research.util;
import info.bondtnt.labs.model.research.*;
import org.eclipse.emf.common.notify.Adapter;
import org.eclipse.emf.common.notify.Notifier;
import org.eclipse.emf.common.notify.impl.AdapterFactoryImpl;
import org.eclipse.emf.ecore.EObject;
/**
* <!-- begin-user-doc -->
* The <b>Adapter Factory</b> for the model.
* It provides an adapter <code>createXXX</code> method for each class of the model.
* <!-- end-user-doc -->
* @see info.bondtnt.labs.model.research.ResearchPackage
* @generated
*/
public class ResearchAdapterFactory extends AdapterFactoryImpl {
/**
* The cached model package.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected static ResearchPackage modelPackage;
/**
* Creates an instance of the adapter factory.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ResearchAdapterFactory() {
if (modelPackage == null) {
modelPackage = ResearchPackage.eINSTANCE;
}
}
/**
* Returns whether this factory is applicable for the type of the object.
* <!-- begin-user-doc -->
* This implementation returns <code>true</code> if the object is either the model's package or is an instance object of the model.
* <!-- end-user-doc -->
* @return whether this factory is applicable for the type of the object.
* @generated
*/
@Override
public boolean isFactoryForType(Object object) {
if (object == modelPackage) {
return true;
}
if (object instanceof EObject) {
return ((EObject)object).eClass().getEPackage() == modelPackage;
}
return false;
}
/**
* The switch that delegates to the <code>createXXX</code> methods.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected ResearchSwitch<Adapter> modelSwitch =
new ResearchSwitch<Adapter>() {
@Override
public Adapter caseBoundedDoubleParameter(BoundedDoubleParameter object) {
return createBoundedDoubleParameterAdapter();
}
@Override
public Adapter caseNamedDoubleParameter(NamedDoubleParameter object) {
return createNamedDoubleParameterAdapter();
}
@Override
public <Type> Adapter caseParametersList(ParametersList<Type> object) {
return createParametersListAdapter();
}
@Override
public <Type> Adapter caseBoundedTypedParameter(BoundedTypedParameter<Type> object) {
return createBoundedTypedParameterAdapter();
}
@Override
public Adapter defaultCase(EObject object) {
return createEObjectAdapter();
}
};
/**
* Creates an adapter for the <code>target</code>.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param target the object to adapt.
* @return the adapter for the <code>target</code>.
* @generated
*/
@Override
public Adapter createAdapter(Notifier target) {
return modelSwitch.doSwitch((EObject)target);
}
/**
* Creates a new adapter for an object of class '{@link info.bondtnt.labs.model.research.BoundedDoubleParameter <em>Bounded Double Parameter</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see info.bondtnt.labs.model.research.BoundedDoubleParameter
* @generated
*/
public Adapter createBoundedDoubleParameterAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link info.bondtnt.labs.model.research.NamedDoubleParameter <em>Named Double Parameter</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see info.bondtnt.labs.model.research.NamedDoubleParameter
* @generated
*/
public Adapter createNamedDoubleParameterAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link info.bondtnt.labs.model.research.ParametersList <em>Parameters List</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see info.bondtnt.labs.model.research.ParametersList
* @generated
*/
public Adapter createParametersListAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link info.bondtnt.labs.model.research.BoundedTypedParameter <em>Bounded Typed Parameter</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see info.bondtnt.labs.model.research.BoundedTypedParameter
* @generated
*/
public Adapter createBoundedTypedParameterAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link info.bondtnt.labs.model.research.BoundedParameter <em>Bounded Parameter</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see info.bondtnt.labs.model.research.BoundedParameter
* @generated
*/
public Adapter createBoundedParameterAdapter() {
return null;
}
/**
* Creates a new adapter for the default case.
* <!-- begin-user-doc -->
* This default implementation returns null.
* <!-- end-user-doc -->
* @return the new adapter.
* @generated
*/
public Adapter createEObjectAdapter() {
return null;
}
} //ResearchAdapterFactory
| Java |
/**
* <copyright>
* </copyright>
*
* $Id$
*/
package info.bondtnt.labs.model.research.util;
import info.bondtnt.labs.model.research.*;
import java.util.List;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EObject;
/**
* <!-- begin-user-doc -->
* The <b>Switch</b> for the model's inheritance hierarchy.
* It supports the call {@link #doSwitch(EObject) doSwitch(object)}
* to invoke the <code>caseXXX</code> method for each class of the model,
* starting with the actual class of the object
* and proceeding up the inheritance hierarchy
* until a non-null result is returned,
* which is the result of the switch.
* <!-- end-user-doc -->
* @see info.bondtnt.labs.model.research.ResearchPackage
* @generated
*/
public class ResearchSwitch<T1> {
/**
* The cached model package
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected static ResearchPackage modelPackage;
/**
* Creates an instance of the switch.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ResearchSwitch() {
if (modelPackage == null) {
modelPackage = ResearchPackage.eINSTANCE;
}
}
/**
* Calls <code>caseXXX</code> for each class of the model until one returns a non null result; it yields that result.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the first non-null result returned by a <code>caseXXX</code> call.
* @generated
*/
public T1 doSwitch(EObject theEObject) {
return doSwitch(theEObject.eClass(), theEObject);
}
/**
* Calls <code>caseXXX</code> for each class of the model until one returns a non null result; it yields that result.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the first non-null result returned by a <code>caseXXX</code> call.
* @generated
*/
protected T1 doSwitch(EClass theEClass, EObject theEObject) {
if (theEClass.eContainer() == modelPackage) {
return doSwitch(theEClass.getClassifierID(), theEObject);
}
else {
List<EClass> eSuperTypes = theEClass.getESuperTypes();
return
eSuperTypes.isEmpty() ?
defaultCase(theEObject) :
doSwitch(eSuperTypes.get(0), theEObject);
}
}
/**
* Calls <code>caseXXX</code> for each class of the model until one returns a non null result; it yields that result.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the first non-null result returned by a <code>caseXXX</code> call.
* @generated
*/
protected T1 doSwitch(int classifierID, EObject theEObject) {
switch (classifierID) {
case ResearchPackage.BOUNDED_DOUBLE_PARAMETER: {
BoundedDoubleParameter boundedDoubleParameter = (BoundedDoubleParameter)theEObject;
T1 result = caseBoundedDoubleParameter(boundedDoubleParameter);
if (result == null) result = defaultCase(theEObject);
return result;
}
case ResearchPackage.NAMED_DOUBLE_PARAMETER: {
NamedDoubleParameter namedDoubleParameter = (NamedDoubleParameter)theEObject;
T1 result = caseNamedDoubleParameter(namedDoubleParameter);
if (result == null) result = defaultCase(theEObject);
return result;
}
case ResearchPackage.PARAMETERS_LIST: {
ParametersList<?> parametersList = (ParametersList<?>)theEObject;
T1 result = caseParametersList(parametersList);
if (result == null) result = defaultCase(theEObject);
return result;
}
case ResearchPackage.BOUNDED_TYPED_PARAMETER: {
BoundedTypedParameter<?> boundedTypedParameter = (BoundedTypedParameter<?>)theEObject;
T1 result = caseBoundedTypedParameter(boundedTypedParameter);
if (result == null) result = defaultCase(theEObject);
return result;
}
default: return defaultCase(theEObject);
}
}
/**
* Returns the result of interpreting the object as an instance of '<em>Bounded Double Parameter</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Bounded Double Parameter</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T1 caseBoundedDoubleParameter(BoundedDoubleParameter object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Named Double Parameter</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Named Double Parameter</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public T1 caseNamedDoubleParameter(NamedDoubleParameter object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Parameters List</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Parameters List</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public <Type> T1 caseParametersList(ParametersList<Type> object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>Bounded Typed Parameter</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>Bounded Typed Parameter</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
* @generated
*/
public <Type> T1 caseBoundedTypedParameter(BoundedTypedParameter<Type> object) {
return null;
}
/**
* Returns the result of interpreting the object as an instance of '<em>EObject</em>'.
* <!-- begin-user-doc -->
* This implementation returns null;
* returning a non-null result will terminate the switch, but this is the last case anyway.
* <!-- end-user-doc -->
* @param object the target of the switch.
* @return the result of interpreting the object as an instance of '<em>EObject</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject)
* @generated
*/
public T1 defaultCase(EObject object) {
return null;
}
} //ResearchSwitch
| Java |
package info.bondtnt.labs.model.research;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EObject;
/**
* @author <a href="mailto:bondtnt@gmail.com">Andrey Bondarenko</a>
* @model
*/
public interface BoundedDoubleParameter extends EObject {
/**
* @model changeable="false"
*/
public Double getFirstValue();
/**
* @model changeable="false"
*/
public Double getLastValue();
/**
* @model changeable="false"
*/
public EList<Double> getAllValues();
/**
* @model changeable="false"
*/
public Double getStepValue();
/**
* @model
*/
public void setBoundaries(double firstValue, double lastValue, double stepValue);
/**
* @model
*/
public abstract String getName();
/**
* Sets the value of the '{@link info.bondtnt.labs.model.research.BoundedDoubleParameter#getName <em>Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Name</em>' attribute.
* @see #getName()
* @generated
*/
void setName(String value);
/**
* @model changeable="false"
*/
public abstract Integer countOfValues();
/**
* Returns value according to its index.
* First index is 0; Last index is (countOfValues() - 1);
* First value usually is less than last;
*
* @model changeable="false"
*/
public abstract Double getValueByIndex(Integer index);
}
| Java |
package info.bond.rp.experiments;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;
/**
* The activator class controls the plug-in life cycle
*/
public class Activator extends AbstractUIPlugin {
// The plug-in ID
public static final String PLUGIN_ID = "info.bond.rp.experiments";
// The shared instance
private static Activator plugin;
/**
* The constructor
*/
public Activator() {
}
/*
* (non-Javadoc)
* @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
*/
public void start(BundleContext context) throws Exception {
super.start(context);
plugin = this;
}
/*
* (non-Javadoc)
* @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
*/
public void stop(BundleContext context) throws Exception {
plugin = null;
super.stop(context);
}
/**
* Returns the shared instance
*
* @return the shared instance
*/
public static Activator getDefault() {
return plugin;
}
}
| Java |
package info.bond.rp.experiments;
public class SpaceCoordinatesGenerator {
private DimensionSizeIndexPair[] dimensions;
/**
* @param dimensionsSizesArray - array contains lengths of every
* space dimension. E.g. if we have 3 parameters (dimensions) and
* each of dimensions (parameters) can be equal to any value
* from set {0, 1, ... , 8, 9}, then maxCountOfValuesArray should
* be equal to [10, 10, 10]; Thus generator will be able to generate
* all coordinates from this space.
* <p>
* Actually it will only return indexes of parameters from particular
* dimensions, as some of dimensions can be represented by non-numeric
* values (example used algorithm - different algorithms will be marked
* by different indexes )
*/
public SpaceCoordinatesGenerator(Integer[] dimensionsSizesArray) {
int dimensionsCount = dimensionsSizesArray.length;
this.dimensions = new DimensionSizeIndexPair[dimensionsCount];
for (int i = 0; i < dimensionsCount; i++) {
DimensionSizeIndexPair maxValueIndexPair = dimensions[i];
Integer dimensionSize = dimensionsSizesArray[i];
maxValueIndexPair.setDimensionParameterIndex(0);
maxValueIndexPair.setMaxDimensionParameterIndex(dimensionSize);
}
}
/**
* @return Integer[] - returns next indexes of parameters.
*/
public Integer[] getSpaceCoordinates() {
int dimensionsCount = dimensions.length;
Integer[] coordinates = new Integer[dimensionsCount];
for (int i = 0; i < dimensionsCount; i++) {
DimensionSizeIndexPair dimensionSizeIndexPair = dimensions[i];
Integer parameterIndex = dimensionSizeIndexPair.getDimensionParameterIndex();
coordinates[i] = parameterIndex;
}
return coordinates;
}
public void generateNextCombination() {
int dimensionsCount = dimensions.length;
int dimensionIndex = 0;
while (dimensionIndex < dimensionsCount) {
DimensionSizeIndexPair maxValueIndexPair = dimensions[dimensionIndex];
if (!maxValueIndexPair.isLastIndex()) {
maxValueIndexPair.increaseIndex();
break;
} else {
maxValueIndexPair.resetIndex();
}
}
}
/**
* Returns true when last combination is remaining
*
* @return
*/
public Boolean isLast() {
Boolean isLast = Boolean.FALSE;
int dimensionsCount = dimensions.length;
DimensionSizeIndexPair lastDimensionSizeIndexPair = dimensions[dimensionsCount-1];
Integer parameterIndex = lastDimensionSizeIndexPair.getDimensionParameterIndex();
Integer maxParameterIndex = lastDimensionSizeIndexPair.getMaxDimensionParameterIndex();
if (parameterIndex.equals(maxParameterIndex)) {
isLast = Boolean.TRUE;
}
return isLast;
}
} | Java |
package info.bond.rp.experiments;
import info.bondtnt.labs.model.research.BoundedDoubleParameter;
import info.bondtnt.labs.model.research.NamedDoubleParameter;
import info.bondtnt.labs.model.research.ParametersList;
import info.bondtnt.labs.model.research.ResearchFactory;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.emf.common.util.EList;
public class ExperimentsDataGeneratorImpl implements ExperimentsDataGenerator {
private List<BoundedDoubleParameter> boundedDoubleParameterList;
public ExperimentsDataGeneratorImpl() {
this.boundedDoubleParameterList = new ArrayList<BoundedDoubleParameter>();
}
@Override
public void add(BoundedDoubleParameter boundedParam) {
boundedDoubleParameterList.add(boundedParam);
}
@Override
public List<ParametersList<NamedDoubleParameter>> generateParametersList() {
List<ParametersList<NamedDoubleParameter>> resultingList = new ArrayList<ParametersList<NamedDoubleParameter>>();
List<EList<Double>> allValuesList = new ArrayList<EList<Double>>();
List<Integer> indexesList = new ArrayList<Integer>();
int totalCountOfParamsCombinations = 1;
for (BoundedDoubleParameter boundedDoubleParameter : boundedDoubleParameterList) {
Integer countOfValues = boundedDoubleParameter.countOfValues();
totalCountOfParamsCombinations = totalCountOfParamsCombinations * countOfValues;
EList<Double> allValues = boundedDoubleParameter.getAllValues();
allValuesList.add(allValues);
indexesList.add(0);
}
while (totalCountOfParamsCombinations > 0) {
totalCountOfParamsCombinations--;
// collect all param values to resultingList
ParametersList<NamedDoubleParameter> parametersList = ResearchFactory.eINSTANCE.createParametersList();
for (int i = 0; i < allValuesList.size(); i++) {
// for (Integer index : indexesList) {
EList<Double> list = allValuesList.get(i);
Integer index = indexesList.get(i);
Double value = list.get(index);
NamedDoubleParameter namedParam = ResearchFactory.eINSTANCE.createNamedDoubleParameter();
// namedParam.setName(name);
namedParam.setValue(value);
parametersList.addParameter(namedParam );
}
int indexOfParam = 0;
BoundedDoubleParameter boundedDoubleParameter = boundedDoubleParameterList.get(indexOfParam);
Integer countOfValues = boundedDoubleParameter.countOfValues();
totalCountOfParamsCombinations = totalCountOfParamsCombinations * countOfValues;
}
return null;
}
}
| Java |
package info.bond.rp.experiments;
/**
* @author Andrey Bondarenko
*
* Pair of values needed for generator - maximum possible index for dimension
* and current dimension index parameter.
*/
public class DimensionSizeIndexPair {
private Integer dimensionParameterIndex;
private Integer maxDimensionParameterIndex; // dimension size
// Constructor
public DimensionSizeIndexPair(Integer maxValueIndex, Integer valueIndex) {
super();
this.maxDimensionParameterIndex = maxValueIndex;
this.dimensionParameterIndex = valueIndex;
}
public DimensionSizeIndexPair(Integer maxValueIndex) {
this(maxValueIndex, 0);
}
// Business methods
public Boolean isLastIndex() {
return dimensionParameterIndex.equals(maxDimensionParameterIndex - 1);
}
public void increaseIndex() {
if (isLastIndex()) {
throw new IllegalArgumentException("Cannot increase index, because it is last!");
}
dimensionParameterIndex++;
}
/**
* Sets <code>dimensionParameterIndex</code> to <code>0</code>;
*/
public void resetIndex() {
dimensionParameterIndex = 0;
}
// Getters/Setters
public Integer getDimensionParameterIndex() {
return dimensionParameterIndex;
}
public void setDimensionParameterIndex(Integer index) {
this.dimensionParameterIndex = index;
}
public Integer getMaxDimensionParameterIndex() {
return maxDimensionParameterIndex;
}
public void setMaxDimensionParameterIndex(Integer maxDimensionParameterIndex) {
this.maxDimensionParameterIndex = maxDimensionParameterIndex;
}
}
| Java |
package info.bond.rp.experiments;
import info.bondtnt.labs.model.research.BoundedDoubleParameter;
import info.bondtnt.labs.model.research.NamedDoubleParameter;
import info.bondtnt.labs.model.research.ParametersList;
import java.util.List;
public interface ExperimentsDataGenerator {
void add(BoundedDoubleParameter boundedParam);
List<ParametersList<NamedDoubleParameter>> generateParametersList();
}
| Java |
package panda_codelab_soln;
public class ConstantSumPairInArray {
public static boolean existPairWithSum(int arr[], int sum) {
if (arr == null) {
return false;
}
int begin = 0;
int end = arr.length - 1;
while (begin != end) {
int current_sum = arr[begin] + arr[end];
if (current_sum < sum) {
begin++;
} else if (current_sum == sum) {
return true;
} else {
end--;
}
}
return false;
}
}
| Java |
package panda_codelab_soln;
public class MergeSort {
public static int[] sort(int[] arr) {
if (arr == null) {
return null;
}
if (arr.length < 2) {
return arr;
}
int middle = arr.length / 2;
int[] left = new int[middle];
System.arraycopy(arr, 0, left, 0, middle);
int[] sorted_left = sort(left);
int[] right = new int[arr.length - middle];
System.arraycopy(arr, middle, right, 0, right.length);
int[] sorted_right = sort(right);
return merge(sorted_left, sorted_right);
}
private static int[] merge(int[] a, int[] b) {
int[] c = new int[a.length + b.length];
int a_iter = 0;
int b_iter = 0;
int c_iter = 0;
while (a_iter < a.length && b_iter < b.length) {
if (a[a_iter] < b[b_iter]) {
c[c_iter++] = a[a_iter++];
} else {
c[c_iter++] = b[b_iter++];
}
}
while (a_iter < a.length) {
c[c_iter++] = a[a_iter++];
}
while (b_iter < b.length) {
c[c_iter++] = b[b_iter++];
}
return c;
}
}
| Java |
package panda_codelab_soln;
public class OddBeforeEvenInArrary {
public static void reorder(int[] arr) {
assert(arr != null);
int open_slot = 0;
int next = 0;
while (next < arr.length) {
if (arr[next] % 2 == 1) {
swap(arr, open_slot++, next);
}
next++;
}
}
private static void swap(int[] arr, int index1, int index2) {
assert(index1 < arr.length);
assert(index2 < arr.length);
int temp = arr[index1];
arr[index1] = arr[index2];
arr[index2] = temp;
}
}
| Java |
package panda_codelab;
/**
* Given a _sorted_ array of ints, and a value, _sum_, find a pair of ints in
* array that sum up to this number. Returns true if exists such pair, false
* otherwise.
*
* Running time requirements, O(n).
*/
public class ConstantSumPairInArray {
// 1. Test if there is a pair of ints with given sum.
public static boolean existPairWithSum(int arr[], int sum) {
return false;
}
// 2. Design a function that also returns the indices of the pair if exists.
}
| Java |
package panda_codelab;
public class MergeSort {
public static int[] sort(int[] arr) {
return null;
}
}
| Java |
package panda_codelab;
/**
* Given an array of ints, reorder its elements such that odd number are in
* front of even numbers.
*
* Running time requirement: O(n).
*/
public class OddBeforeEvenInArrary {
public static void reorder(int[] arr) {
}
}
| Java |
package panda_codelab_test;
import static org.junit.Assert.*;
import org.junit.Test;
import panda_codelab_soln.ConstantSumPairInArray;
public class ConstantSumPairInArrayTest {
@Test
public void TestWithSingleElemArray() {
int sum = 1;
int[] arr = { sum + sum };
assertFalse(ConstantSumPairInArray.existPairWithSum(arr, sum));
}
@Test
public void TestAllSameElemArrayWithoutSuchPair() {
int[] arr = { 1, 1, 1 };
int sum = 4;
assertFalse(ConstantSumPairInArray.existPairWithSum(arr, sum));
}
@Test
public void TestAllSameElemArrayWithSuchPair() {
int[] arr = { 1, 1, 1 };
int sum = 2;
assertTrue(ConstantSumPairInArray.existPairWithSum(arr, sum));
}
@Test
public void TestArrayWithoutSuchPair() {
int[] arr = { 1, 2, 3, 4, 5 };
int sum = 10;
assertFalse(ConstantSumPairInArray.existPairWithSum(arr, sum));
}
@Test
public void TestArrayWithSuchPair() {
int[] arr = { 1, 2, 3, 4, 5 };
int sum = 7;
assertTrue(ConstantSumPairInArray.existPairWithSum(arr, sum));
}
}
| Java |
package panda_codelab_test;
import static org.junit.Assert.*;
import org.junit.Test;
// import classes to be tested.
import panda_codelab_soln.MergeSort;
//import panda_codelab.MergeSort;
public class MergeSortTest {
@Test
public void NullInputIntArr() {
int[] arr = null;
int[] result = MergeSort.sort(arr);
assertNull(result);
}
@Test
public void EmptyInputIntArr() {
int[] arr = new int[0];
int[] result = MergeSort.sort(arr);
assertArrayEquals(arr, result);
}
@Test
public void SingleElemInputIntArr() {
int[] arr = new int[1];
int[] result = MergeSort.sort(arr);
assertArrayEquals(arr, result);
}
@Test
public void DistinctElemInputIntArr() {
int[] arr = { 5, 4, 3, 2, 1 };
int[] result = MergeSort.sort(arr);
int[] expected = { 1, 2, 3, 4, 5 };
assertArrayEquals(expected, result);
}
@Test
public void AllSameElemInputIntArr() {
int[] arr = { 1, 1, 1 };
int[] result = MergeSort.sort(arr);
assertArrayEquals(arr, result);
}
@Test
public void SortedInputIntArr() {
int[] arr = { 1, 2, 3, 4, 5 };
int[] result = MergeSort.sort(arr);
assertArrayEquals(arr, result);
}
}
| Java |
package panda_codelab_test;
import static org.junit.Assert.*;
import org.junit.Test;
import panda_codelab_soln.OddBeforeEvenInArrary;
public class OddBeforeEvenInArraryTest {
// helper function that for a given array of ints, it returns true if odd
// numbers are before even numbers, false otherwise.
private static boolean isOddBeforeEven(int arr[]) {
boolean passOdd = false;
for (int i = 0; i < arr.length; i++) {
if (!passOdd && arr[i] % 2 == 0) {
passOdd = true;
} else if (passOdd && arr[i] % 2 == 1) {
return false;
}
}
return true;
}
@Test
public void TestIsOddBeforeEvenHelper() {
int[] good = { 1, 1, 2 };
assertTrue(isOddBeforeEven(good));
int[] bad = { 1, 2, 1 };
assertFalse(isOddBeforeEven(bad));
// Test with single elem arrary.
int[] single = { 1 };
assertTrue(isOddBeforeEven(single));
single[0] = 2;
assertTrue(isOddBeforeEven(single));
}
@Test
public void TestWithAlternatingArray() {
int[] arr = { 1, 2, 3, 4, 5 };
assertFalse(isOddBeforeEven(arr));
OddBeforeEvenInArrary.reorder(arr);
assertTrue(isOddBeforeEven(arr));
}
}
| Java |
package com.jincheng.activity;
import android.os.Bundle;
import android.preference.PreferenceActivity;
public class SettingActivity extends PreferenceActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.setting);
}
}
| Java |
package com.jincheng.activity;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuItem;
public class BaseActivity extends Activity {
protected SharedPreferences sp;
protected String number;
private String wupeng;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sp = PreferenceManager.getDefaultSharedPreferences(this);
number = sp.getString("number", "8");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, 0, 0, R.string.setting);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == 0){
Intent setIntent = new Intent(this,SettingActivity.class);
startActivity(setIntent);
}
return super.onOptionsItemSelected(item);
}
}
| Java |
package com.jincheng.parser;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.xmlpull.v1.XmlPullParser;
import com.jincheng.model.Team;
import android.util.Xml;
public class XMLParser {
public static List<Team> XML2Object(String xmlStr) throws Exception {
InputStream in = new ByteArrayInputStream(xmlStr.getBytes("UTF-8"));
List<Team> teams = null;
Team team = null;
XmlPullParser parser = Xml.newPullParser();
parser.setInput(in, "UTF-8");
int type = parser.getEventType();
while (type != parser.END_DOCUMENT) {
switch (type) {
case XmlPullParser.START_TAG:
if ("teams".equals(parser.getName())) {
teams = new ArrayList<Team>();
} else if ("team".equals(parser.getName())) {
team = new Team();
} else if ("id".equals(parser.getName())) {
String id = parser.nextText();
team.setId(id);
} else if ("link".equals(parser.getName())) {
String link = parser.nextText();
team.setLink(link);
} else if ("large_image_url".equals(parser.getName())) {
String largeImageUrl = parser.nextText();
team.setLargeImageUrl(largeImageUrl);
} else if ("small_image_url".equals(parser.getName())) {
String smallImageUrl = parser.nextText();
team.setSmallImageUrl(smallImageUrl);
} else if ("title".equals(parser.getName())) {
String title = parser.nextText();
team.setTitle(title);
} else if ("product".equals(parser.getName())) {
String product = parser.nextText();
team.setProduct(product);
} else if ("team_price".equals(parser.getName())) {
String teamPrice = parser.nextText();
team.setTeamPrice(teamPrice);
} else if ("market_price".equals(parser.getName())) {
String marketPrice = parser.nextText();
team.setMarketPrice(marketPrice);
} else if ("rebate".equals(parser.getName())) {
String rebate = parser.nextText();
team.setRebate(rebate);
} else if ("start_date".equals(parser.getName())) {
String startDate = parser.nextText();
team.setStartDate(startDate);
} else if ("end_date".equals(parser.getName())) {
String endDate = parser.nextText();
team.setEndDate(endDate);
} else if ("state".equals(parser.getName())) {
String state = parser.nextText();
team.setState(state);
} else if ("tipped".equals(parser.getName())) {
String tipped = parser.nextText();
team.setTipped(tipped);
} else if ("tipping_point".equals(parser.getName())) {
String tippingPoint = parser.nextText();
team.setTippingPoint(tippingPoint);
} else if ("current_point".equals(parser.getName())) {
String currentPoint = parser.nextText();
team.setCurrentPoint(currentPoint);
} else if ("city".equals(parser.getName())) {
String city = parser.nextText();
team.setCity(city);
} else if ("group".equals(parser.getName())) {
String group = parser.nextText();
team.setGroup(group);
}
break;
case XmlPullParser.END_TAG:
if ("team".equals(parser.getName())) {
teams.add(team);
team = null;
}
break;
}
type = parser.next();
}
in.close();
return teams;
}
}
| Java |
package com.jincheng.utils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import android.os.Environment;
public class NetUtil {
private static String url = "http://www.ajjct.com/api/index.php";
public static String stream2File(String content) throws Exception {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
HttpResponse response = client.execute(post);
if (response.getStatusLine().getStatusCode() == 200) {
String result = EntityUtils.toString(response.getEntity(), "UTF-8");
System.out.println(result);
return result;
}else{
return "";
}
/*
* InputStream is = response.getEntity().getContent();
*
* File file = new
* File(Environment.getExternalStorageDirectory(),"/anjie.xml");
* FileOutputStream out = new FileOutputStream(file); int len = 0;
* byte[] buffer = new byte[1024]; while((len = is.read(buffer)) != -1){
* out.write(buffer, 0, len); } out.flush(); out.close(); is.close();
*/
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks;
import com.google.android.apps.mytracks.services.TrackRecordingService;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.test.AndroidTestCase;
import java.util.List;
/**
* Tests for the BootReceiver.
*
* @author Youtao Liu
*/
public class BootReceiverTest extends AndroidTestCase {
private static final String SERVICE_NAME = "com.google.android.apps.mytracks.services.TrackRecordingService";
/**
* Tests the behavior when receive notification which is the phone boot.
*/
public void testOnReceive_startService() {
// Make sure no TrackRecordingService
Intent stopIntent = new Intent(getContext(), TrackRecordingService.class);
getContext().stopService(stopIntent);
assertFalse(isServiceExisted(getContext(), SERVICE_NAME));
BootReceiver bootReceiver = new BootReceiver();
Intent intent = new Intent();
intent.setAction(Intent.ACTION_BOOT_COMPLETED);
bootReceiver.onReceive(getContext(), intent);
// Check if the service is started
assertTrue(isServiceExisted(getContext(), SERVICE_NAME));
}
/**
* Tests the behavior when receive notification which is not the phone boot.
*/
public void testOnReceive_noStartService() {
// Make sure no TrackRecordingService
Intent stopIntent = new Intent(getContext(), TrackRecordingService.class);
getContext().stopService(stopIntent);
assertFalse(isServiceExisted(getContext(), SERVICE_NAME));
BootReceiver bootReceiver = new BootReceiver();
Intent intent = new Intent();
intent.setAction(Intent.ACTION_BUG_REPORT);
bootReceiver.onReceive(getContext(), intent);
// Check if the service is not started
assertFalse(isServiceExisted(getContext(), SERVICE_NAME));
}
/**
* Checks if a service is started in a context.
*
* @param context the context for checking a service
* @param serviceName the service name to find if existed
*/
private boolean isServiceExisted(Context context, String serviceName) {
ActivityManager activityManager = (ActivityManager) context
.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningServiceInfo> serviceList = activityManager
.getRunningServices(Integer.MAX_VALUE);
for (int i = 0; i < serviceList.size(); i++) {
RunningServiceInfo serviceInfo = serviceList.get(i);
ComponentName componentName = serviceInfo.service;
if (componentName.getClassName().equals(serviceName)) {
return true;
}
}
return false;
}
} | Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks;
import com.google.android.maps.mytracks.R;
import android.test.AndroidTestCase;
/**
* Tests for the AntPreference.
*
* @author Youtao Liu
*/
public class AntPreferenceTest extends AndroidTestCase {
public void testNotPaired() {
AntPreference antPreference = new AntPreference(getContext()) {
@Override
protected int getPersistedInt(int defaultReturnValue) {
return 0;
}
};
assertEquals(getContext().getString(R.string.settings_sensor_ant_not_paired),
antPreference.getSummary());
}
public void testPaired() {
int persistInt = 1;
AntPreference antPreference = new AntPreference(getContext()) {
@Override
protected int getPersistedInt(int defaultReturnValue) {
return 1;
}
};
assertEquals(
getContext().getString(R.string.settings_sensor_ant_paired, persistInt),
antPreference.getSummary());
}
} | Java |
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks;
import com.google.android.apps.mytracks.content.Waypoint;
import com.google.android.apps.mytracks.maps.SingleColorTrackPathPainter;
import com.google.android.maps.MapView;
import android.graphics.Canvas;
import android.graphics.Path;
import android.location.Location;
import android.test.AndroidTestCase;
/**
* Tests for the MyTracks map overlay.
*
* @author Bartlomiej Niechwiej
* @author Vangelis S.
*/
public class MapOverlayTest extends AndroidTestCase {
private Canvas canvas;
private MockMyTracksOverlay myTracksOverlay;
private MapView mockView;
@Override
protected void setUp() throws Exception {
super.setUp();
canvas = new Canvas();
myTracksOverlay = new MockMyTracksOverlay(getContext());
// Enable drawing.
myTracksOverlay.setTrackDrawingEnabled(true);
// Set a TrackPathPainter with a MockPath.
myTracksOverlay.setTrackPathPainter(new SingleColorTrackPathPainter(getContext()) {
@Override
public Path newPath() {
return new MockPath();
}
});
mockView = null;
}
public void testAddLocation() throws Exception {
Location location = new Location("gps");
location.setLatitude(10);
location.setLongitude(20);
myTracksOverlay.addLocation(location);
assertEquals(1, myTracksOverlay.getNumLocations());
assertEquals(0, myTracksOverlay.getNumWaypoints());
location.setLatitude(20);
location.setLongitude(30);
myTracksOverlay.addLocation(location);
assertEquals(2, myTracksOverlay.getNumLocations());
assertEquals(0, myTracksOverlay.getNumWaypoints());
assertNull(myTracksOverlay.getTrackPathPainter().getLastPath());
// Draw and make sure that we don't lose any point.
myTracksOverlay.draw(canvas, mockView, false);
assertEquals(2, myTracksOverlay.getNumLocations());
assertEquals(0, myTracksOverlay.getNumWaypoints());
assertNotNull(myTracksOverlay.getTrackPathPainter().getLastPath());
assertTrue(myTracksOverlay.getTrackPathPainter().getLastPath() instanceof MockPath);
MockPath path = (MockPath) myTracksOverlay.getTrackPathPainter().getLastPath();
assertEquals(2, path.totalPoints);
myTracksOverlay.draw(canvas, mockView, true);
assertEquals(2, myTracksOverlay.getNumLocations());
assertEquals(0, myTracksOverlay.getNumWaypoints());
assertNotNull(myTracksOverlay.getTrackPathPainter().getLastPath());
}
public void testClearPoints() throws Exception {
Location location = new Location("gps");
location.setLatitude(10);
location.setLongitude(20);
myTracksOverlay.addLocation(location);
assertEquals(1, myTracksOverlay.getNumLocations());
myTracksOverlay.clearPoints();
assertEquals(0, myTracksOverlay.getNumLocations());
// Same after drawing on canvas.
final int locations = 100;
for (int i = 0; i < locations; ++i) {
myTracksOverlay.addLocation(location);
}
assertEquals(locations, myTracksOverlay.getNumLocations());
myTracksOverlay.draw(canvas, mockView, false);
myTracksOverlay.draw(canvas, mockView, true);
myTracksOverlay.clearPoints();
assertEquals(0, myTracksOverlay.getNumLocations());
}
public void testAddWaypoint() throws Exception {
Location location = new Location("gps");
location.setLatitude(10);
location.setLongitude(20);
Waypoint waypoint = new Waypoint();
waypoint.setLocation(location);
myTracksOverlay.addWaypoint(waypoint);
assertEquals(1, myTracksOverlay.getNumWaypoints());
assertEquals(0, myTracksOverlay.getNumLocations());
assertNull(myTracksOverlay.getTrackPathPainter().getLastPath());
final int waypoints = 10;
for (int i = 0; i < waypoints; ++i) {
waypoint = new Waypoint();
waypoint.setLocation(location);
myTracksOverlay.addWaypoint(waypoint);
}
assertEquals(1 + waypoints, myTracksOverlay.getNumWaypoints());
assertEquals(0, myTracksOverlay.getNumLocations());
assertNull(myTracksOverlay.getTrackPathPainter().getLastPath());
}
public void testClearWaypoints() throws Exception {
Location location = new Location("gps");
location.setLatitude(10);
location.setLongitude(20);
Waypoint waypoint = new Waypoint();
waypoint.setLocation(location);
myTracksOverlay.addWaypoint(waypoint);
assertEquals(1, myTracksOverlay.getNumWaypoints());
myTracksOverlay.clearWaypoints();
assertEquals(0, myTracksOverlay.getNumWaypoints());
}
public void testDrawing() {
Location location = new Location("gps");
location.setLatitude(10);
for (int i = 0; i < 40; ++i) {
location.setLongitude(20 + i);
Waypoint waypoint = new Waypoint();
waypoint.setLocation(location);
myTracksOverlay.addWaypoint(waypoint);
}
for (int i = 0; i < 100; ++i) {
location = new Location("gps");
location.setLatitude(20 + i / 2);
location.setLongitude(150 - i);
myTracksOverlay.addLocation(location);
}
// Shadow.
myTracksOverlay.draw(canvas, mockView, true);
// We don't expect to do anything if
assertNull(myTracksOverlay.getTrackPathPainter().getLastPath());
assertEquals(40, myTracksOverlay.getNumWaypoints());
assertEquals(100, myTracksOverlay.getNumLocations());
// No shadow.
myTracksOverlay.draw(canvas, mockView, false);
assertNotNull(myTracksOverlay.getTrackPathPainter().getLastPath());
assertTrue(myTracksOverlay.getTrackPathPainter().getLastPath() instanceof MockPath);
MockPath path = (MockPath) myTracksOverlay.getTrackPathPainter().getLastPath();
assertEquals(40, myTracksOverlay.getNumWaypoints());
assertEquals(100, myTracksOverlay.getNumLocations());
assertEquals(100, path.totalPoints);
// TODO: Check the points from the path (and the segments).
}
}
| Java |
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.services;
import com.google.android.apps.mytracks.util.StringUtils;
import com.google.android.maps.mytracks.R;
import android.test.AndroidTestCase;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Tests {@link DefaultTrackNameFactory}
*
* @author Matthew Simmons
*/
public class DefaultTrackNameFactoryTest extends AndroidTestCase {
private static final long TRACK_ID = 1L;
private static final long START_TIME = 1288213406000L;
public void testDefaultTrackName_date_local() {
DefaultTrackNameFactory defaultTrackNameFactory = new DefaultTrackNameFactory(getContext()) {
@Override
String getTrackNameSetting() {
return getContext().getString(R.string.settings_recording_track_name_date_local_value);
}
};
assertEquals(StringUtils.formatDateTime(getContext(), START_TIME),
defaultTrackNameFactory.getDefaultTrackName(TRACK_ID, START_TIME));
}
public void testDefaultTrackName_date_iso_8601() {
DefaultTrackNameFactory defaultTrackNameFactory = new DefaultTrackNameFactory(getContext()) {
@Override
String getTrackNameSetting() {
return getContext().getString(R.string.settings_recording_track_name_date_iso_8601_value);
}
};
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
DefaultTrackNameFactory.ISO_8601_FORMAT);
assertEquals(simpleDateFormat.format(new Date(START_TIME)),
defaultTrackNameFactory.getDefaultTrackName(TRACK_ID, START_TIME));
}
public void testDefaultTrackName_number() {
DefaultTrackNameFactory defaultTrackNameFactory = new DefaultTrackNameFactory(getContext()) {
@Override
String getTrackNameSetting() {
return getContext().getString(R.string.settings_recording_track_name_number_value);
}
};
assertEquals(
"Track " + TRACK_ID, defaultTrackNameFactory.getDefaultTrackName(TRACK_ID, START_TIME));
}
}
| Java |
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.services.tasks;
import static com.google.android.testing.mocking.AndroidMock.capture;
import static com.google.android.testing.mocking.AndroidMock.eq;
import static com.google.android.testing.mocking.AndroidMock.expect;
import static com.google.android.testing.mocking.AndroidMock.same;
import com.google.android.apps.mytracks.stats.TripStatistics;
import com.google.android.apps.mytracks.util.StringUtils;
import com.google.android.testing.mocking.AndroidMock;
import com.google.android.testing.mocking.UsesMocks;
import android.content.Context;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.speech.tts.TextToSpeech.OnUtteranceCompletedListener;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.test.AndroidTestCase;
import java.util.HashMap;
import java.util.Locale;
import java.util.concurrent.atomic.AtomicBoolean;
import org.easymock.Capture;
/**
* Tests for {@link StatusAnnouncerTask}.
* WARNING: I'm not responsible if your eyes start bleeding while reading this
* code. You have been warned. It's still better than no test, though.
*
* @author Rodrigo Damazio
*/
public class StatusAnnouncerTaskTest extends AndroidTestCase {
// Use something other than our hardcoded value
private static final Locale DEFAULT_LOCALE = Locale.KOREAN;
private static final String ANNOUNCEMENT = "I can haz cheeseburger?";
private Locale oldDefaultLocale;
private StatusAnnouncerTask task;
private StatusAnnouncerTask mockTask;
private Capture<OnInitListener> initListenerCapture;
private Capture<PhoneStateListener> phoneListenerCapture;
private TextToSpeechDelegate ttsDelegate;
private TextToSpeechInterface tts;
/**
* Mockable interface that we delegate TTS calls to.
*/
interface TextToSpeechInterface {
int addEarcon(String earcon, String packagename, int resourceId);
int addEarcon(String earcon, String filename);
int addSpeech(String text, String packagename, int resourceId);
int addSpeech(String text, String filename);
boolean areDefaultsEnforced();
String getDefaultEngine();
Locale getLanguage();
int isLanguageAvailable(Locale loc);
boolean isSpeaking();
int playEarcon(String earcon, int queueMode,
HashMap<String, String> params);
int playSilence(long durationInMs, int queueMode,
HashMap<String, String> params);
int setEngineByPackageName(String enginePackageName);
int setLanguage(Locale loc);
int setOnUtteranceCompletedListener(OnUtteranceCompletedListener listener);
int setPitch(float pitch);
int setSpeechRate(float speechRate);
void shutdown();
int speak(String text, int queueMode, HashMap<String, String> params);
int stop();
int synthesizeToFile(String text, HashMap<String, String> params,
String filename);
}
/**
* Subclass of {@link TextToSpeech} which delegates calls to the interface
* above.
* The logic here is stupid and the author is ashamed of having to write it
* like this, but basically the issue is that TextToSpeech cannot be mocked
* without running its constructor, its constructor runs async operations
* which call other methods (and then if the methods are part of a mock we'd
* have to set a behavior, but we can't 'cause the object hasn't been fully
* built yet).
* The logic is that calls made during the constructor (when tts is not yet
* set) will go up to the original class, but after tts is set we'll forward
* them all to the mock.
*/
private class TextToSpeechDelegate
extends TextToSpeech implements TextToSpeechInterface {
public TextToSpeechDelegate(Context context, OnInitListener listener) {
super(context, listener);
}
@Override
public int addEarcon(String earcon, String packagename, int resourceId) {
if (tts == null) {
return super.addEarcon(earcon, packagename, resourceId);
}
return tts.addEarcon(earcon, packagename, resourceId);
}
@Override
public int addEarcon(String earcon, String filename) {
if (tts == null) {
return super.addEarcon(earcon, filename);
}
return tts.addEarcon(earcon, filename);
}
@Override
public int addSpeech(String text, String packagename, int resourceId) {
if (tts == null) {
return super.addSpeech(text, packagename, resourceId);
}
return tts.addSpeech(text, packagename, resourceId);
}
@Override
public int addSpeech(String text, String filename) {
if (tts == null) {
return super.addSpeech(text, filename);
}
return tts.addSpeech(text, filename);
}
@Override
public Locale getLanguage() {
if (tts == null) {
return super.getLanguage();
}
return tts.getLanguage();
}
@Override
public int isLanguageAvailable(Locale loc) {
if (tts == null) {
return super.isLanguageAvailable(loc);
}
return tts.isLanguageAvailable(loc);
}
@Override
public boolean isSpeaking() {
if (tts == null) {
return super.isSpeaking();
}
return tts.isSpeaking();
}
@Override
public int playEarcon(String earcon, int queueMode,
HashMap<String, String> params) {
if (tts == null) {
return super.playEarcon(earcon, queueMode, params);
}
return tts.playEarcon(earcon, queueMode, params);
}
@Override
public int playSilence(long durationInMs, int queueMode,
HashMap<String, String> params) {
if (tts == null) {
return super.playSilence(durationInMs, queueMode, params);
}
return tts.playSilence(durationInMs, queueMode, params);
}
@Override
public int setLanguage(Locale loc) {
if (tts == null) {
return super.setLanguage(loc);
}
return tts.setLanguage(loc);
}
@Override
public int setOnUtteranceCompletedListener(
OnUtteranceCompletedListener listener) {
if (tts == null) {
return super.setOnUtteranceCompletedListener(listener);
}
return tts.setOnUtteranceCompletedListener(listener);
}
@Override
public int setPitch(float pitch) {
if (tts == null) {
return super.setPitch(pitch);
}
return tts.setPitch(pitch);
}
@Override
public int setSpeechRate(float speechRate) {
if (tts == null) {
return super.setSpeechRate(speechRate);
}
return tts.setSpeechRate(speechRate);
}
@Override
public void shutdown() {
if (tts == null) {
super.shutdown();
return;
}
tts.shutdown();
}
@Override
public int speak(
String text, int queueMode, HashMap<String, String> params) {
if (tts == null) {
return super.speak(text, queueMode, params);
}
return tts.speak(text, queueMode, params);
}
@Override
public int stop() {
if (tts == null) {
return super.stop();
}
return tts.stop();
}
@Override
public int synthesizeToFile(String text, HashMap<String, String> params,
String filename) {
if (tts == null) {
return super.synthesizeToFile(text, params, filename);
}
return tts.synthesizeToFile(text, params, filename);
}
}
@UsesMocks({
StatusAnnouncerTask.class,
StringUtils.class,
})
@Override
protected void setUp() throws Exception {
super.setUp();
oldDefaultLocale = Locale.getDefault();
Locale.setDefault(DEFAULT_LOCALE);
// Eww, the effort required just to mock TextToSpeech is insane
final AtomicBoolean listenerCalled = new AtomicBoolean();
OnInitListener blockingListener = new OnInitListener() {
@Override
public void onInit(int status) {
synchronized (this) {
listenerCalled.set(true);
notify();
}
}
};
ttsDelegate = new TextToSpeechDelegate(getContext(), blockingListener);
// Wait for all async operations done in the constructor to finish.
synchronized (blockingListener) {
while (!listenerCalled.get()) {
// Releases the synchronized lock until we're woken up.
blockingListener.wait();
}
}
// Phew, done, now we can start forwarding calls
tts = AndroidMock.createMock(TextToSpeechInterface.class);
initListenerCapture = new Capture<OnInitListener>();
phoneListenerCapture = new Capture<PhoneStateListener>();
// Create a partial forwarding mock
mockTask = AndroidMock.createMock(StatusAnnouncerTask.class, getContext());
task = new StatusAnnouncerTask(getContext()) {
@Override
protected TextToSpeech newTextToSpeech(Context ctx,
OnInitListener onInitListener) {
return mockTask.newTextToSpeech(ctx, onInitListener);
}
@Override
protected String getAnnouncement(TripStatistics stats) {
return mockTask.getAnnouncement(stats);
}
@Override
protected void listenToPhoneState(
PhoneStateListener listener, int events) {
mockTask.listenToPhoneState(listener, events);
}
};
}
@Override
protected void tearDown() {
Locale.setDefault(oldDefaultLocale);
}
public void testStart() {
doStart();
OnInitListener ttsInitListener = initListenerCapture.getValue();
assertNotNull(ttsInitListener);
expect(tts.isLanguageAvailable(DEFAULT_LOCALE))
.andStubReturn(TextToSpeech.LANG_AVAILABLE);
expect(tts.setLanguage(DEFAULT_LOCALE))
.andReturn(TextToSpeech.LANG_AVAILABLE);
expect(tts.setSpeechRate(StatusAnnouncerTask.TTS_SPEECH_RATE))
.andReturn(TextToSpeech.SUCCESS);
AndroidMock.replay(tts);
ttsInitListener.onInit(TextToSpeech.SUCCESS);
AndroidMock.verify(mockTask, tts);
}
public void testStart_languageNotSupported() {
doStart();
OnInitListener ttsInitListener = initListenerCapture.getValue();
assertNotNull(ttsInitListener);
expect(tts.isLanguageAvailable(DEFAULT_LOCALE))
.andStubReturn(TextToSpeech.LANG_NOT_SUPPORTED);
expect(tts.setLanguage(Locale.ENGLISH))
.andReturn(TextToSpeech.LANG_AVAILABLE);
expect(tts.setSpeechRate(StatusAnnouncerTask.TTS_SPEECH_RATE))
.andReturn(TextToSpeech.SUCCESS);
AndroidMock.replay(tts);
ttsInitListener.onInit(TextToSpeech.SUCCESS);
AndroidMock.verify(mockTask, tts);
}
public void testStart_notReady() {
doStart();
OnInitListener ttsInitListener = initListenerCapture.getValue();
assertNotNull(ttsInitListener);
AndroidMock.replay(tts);
ttsInitListener.onInit(TextToSpeech.ERROR);
AndroidMock.verify(mockTask, tts);
}
public void testShutdown() {
// First, start
doStart();
AndroidMock.verify(mockTask);
AndroidMock.reset(mockTask);
// Then, shut down
PhoneStateListener phoneListener = phoneListenerCapture.getValue();
mockTask.listenToPhoneState(
same(phoneListener), eq(PhoneStateListener.LISTEN_NONE));
tts.shutdown();
AndroidMock.replay(mockTask, tts);
task.shutdown();
AndroidMock.verify(mockTask, tts);
}
public void testRun() throws Exception {
// Expect service data calls
TripStatistics stats = new TripStatistics();
// Expect announcement building call
expect(mockTask.getAnnouncement(same(stats))).andStubReturn(ANNOUNCEMENT);
// Put task in "ready" state
startTask(TextToSpeech.SUCCESS);
// Expect actual announcement call
expect(tts.speak(
eq(ANNOUNCEMENT), eq(TextToSpeech.QUEUE_FLUSH),
AndroidMock.<HashMap<String, String>>isNull()))
.andReturn(TextToSpeech.SUCCESS);
// Run the announcement
AndroidMock.replay(tts);
task.runWithStatistics(stats);
AndroidMock.verify(mockTask, tts);
}
public void testRun_notReady() throws Exception {
// Put task in "not ready" state
startTask(TextToSpeech.ERROR);
// Run the announcement
AndroidMock.replay(tts);
task.runWithStatistics(null);
AndroidMock.verify(mockTask, tts);
}
public void testRun_duringCall() throws Exception {
startTask(TextToSpeech.SUCCESS);
expect(tts.isSpeaking()).andStubReturn(false);
// Run the announcement
AndroidMock.replay(tts);
PhoneStateListener phoneListener = phoneListenerCapture.getValue();
phoneListener.onCallStateChanged(TelephonyManager.CALL_STATE_OFFHOOK, null);
task.runWithStatistics(null);
AndroidMock.verify(mockTask, tts);
}
public void testRun_ringWhileSpeaking() throws Exception {
startTask(TextToSpeech.SUCCESS);
expect(tts.isSpeaking()).andStubReturn(true);
expect(tts.stop()).andReturn(TextToSpeech.SUCCESS);
AndroidMock.replay(tts);
// Update the state to ringing - this should stop the current announcement.
PhoneStateListener phoneListener = phoneListenerCapture.getValue();
phoneListener.onCallStateChanged(TelephonyManager.CALL_STATE_RINGING, null);
// Run the announcement - this should do nothing.
task.runWithStatistics(null);
AndroidMock.verify(mockTask, tts);
}
public void testRun_whileRinging() throws Exception {
startTask(TextToSpeech.SUCCESS);
expect(tts.isSpeaking()).andStubReturn(false);
// Run the announcement
AndroidMock.replay(tts);
PhoneStateListener phoneListener = phoneListenerCapture.getValue();
phoneListener.onCallStateChanged(TelephonyManager.CALL_STATE_RINGING, null);
task.runWithStatistics(null);
AndroidMock.verify(mockTask, tts);
}
public void testRun_noService() throws Exception {
startTask(TextToSpeech.SUCCESS);
// Run the announcement
AndroidMock.replay(tts);
task.run(null);
AndroidMock.verify(mockTask, tts);
}
public void testRun_noStats() throws Exception {
// Expect service data calls
startTask(TextToSpeech.SUCCESS);
// Run the announcement
AndroidMock.replay(tts);
task.runWithStatistics(null);
AndroidMock.verify(mockTask, tts);
}
/**
* Tests {@link StatusAnnouncerTask#getAnnounceTime(long)} with time zero.
*/
public void testGetAnnounceTime_time_zero() {
long time = 0; // 0 seconds
assertEquals("0 minutes 0 seconds", task.getAnnounceTime(time));
}
/**
* Tests {@link StatusAnnouncerTask#getAnnounceTime(long)} with time one.
*/
public void testGetAnnounceTime_time_one() {
long time = 1 * 1000; // 1 second
assertEquals("0 minutes 1 second", task.getAnnounceTime(time));
}
/**
* Tests {@link StatusAnnouncerTask#getAnnounceTime(long)} with singular
* numbers with the hour unit.
*/
public void testGetAnnounceTime_singular_has_hour() {
long time = (1 * 60 * 60 * 1000) + (1 * 60 * 1000) + (1 * 1000); // 1 hour 1 minute 1 second
assertEquals("1 hour 1 minute", task.getAnnounceTime(time));
}
/**
* Tests {@link StatusAnnouncerTask#getAnnounceTime(long)} with plural numbers
* with the hour unit.
*/
public void testGetAnnounceTime_plural_has_hour() {
long time = (2 * 60 * 60 * 1000) + (2 * 60 * 1000) + (2 * 1000); // 2 hours 2 minutes 2 seconds
assertEquals("2 hours 2 minutes", task.getAnnounceTime(time));
}
/**
* Tests {@link StatusAnnouncerTask#getAnnounceTime(long)} with singular
* numbers without the hour unit.
*/
public void testGetAnnounceTime_singular_no_hour() {
long time = (1 * 60 * 1000) + (1 * 1000); // 1 minute 1 second
assertEquals("1 minute 1 second", task.getAnnounceTime(time));
}
/**
* Tests {@link StatusAnnouncerTask#getAnnounceTime(long)} with plural numbers
* without the hour unit.
*/
public void testGetAnnounceTime_plural_no_hour() {
long time = (2 * 60 * 1000) + (2 * 1000); // 2 minutes 2 seconds
assertEquals("2 minutes 2 seconds", task.getAnnounceTime(time));
}
private void startTask(int state) {
AndroidMock.resetToNice(tts);
AndroidMock.replay(tts);
doStart();
OnInitListener ttsInitListener = initListenerCapture.getValue();
ttsInitListener.onInit(state);
AndroidMock.resetToDefault(tts);
}
private void doStart() {
mockTask.listenToPhoneState(capture(phoneListenerCapture),
eq(PhoneStateListener.LISTEN_CALL_STATE));
expect(mockTask.newTextToSpeech(
same(getContext()), capture(initListenerCapture)))
.andStubReturn(ttsDelegate);
AndroidMock.replay(mockTask);
task.start();
}
}
| Java |
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.services.tasks;
import android.test.AndroidTestCase;
/**
* Tests for {@link StatusAnnouncerFactory}.
* These tests require Donut+ to run.
*
* @author Rodrigo Damazio
*/
public class StatusAnnouncerFactoryTest extends AndroidTestCase {
public void testCreate() {
PeriodicTaskFactory factory = new StatusAnnouncerFactory();
PeriodicTask task = factory.create(getContext());
assertTrue(task instanceof StatusAnnouncerTask);
}
}
| Java |
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.services;
import static com.google.android.apps.mytracks.Constants.RESUME_TRACK_EXTRA_NAME;
import com.google.android.apps.mytracks.Constants;
import com.google.android.apps.mytracks.content.MyTracksProvider;
import com.google.android.apps.mytracks.content.MyTracksProviderUtils;
import com.google.android.apps.mytracks.content.Track;
import com.google.android.apps.mytracks.content.Waypoint;
import com.google.android.apps.mytracks.content.WaypointCreationRequest;
import com.google.android.apps.mytracks.stats.TripStatistics;
import com.google.android.maps.mytracks.R;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.location.Location;
import android.os.IBinder;
import android.test.RenamingDelegatingContext;
import android.test.ServiceTestCase;
import android.test.mock.MockContentResolver;
import android.test.suitebuilder.annotation.MediumTest;
import android.test.suitebuilder.annotation.SmallTest;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
/**
* Tests for the MyTracks track recording service.
*
* @author Bartlomiej Niechwiej
*
* TODO: The original class, ServiceTestCase, has a few limitations, e.g.
* it's not possible to properly shutdown the service, unless tearDown()
* is called, which prevents from testing multiple scenarios in a single
* test (see runFunctionTest for more details).
*/
public class TrackRecordingServiceTest extends ServiceTestCase<TestRecordingService> {
private Context context;
private MyTracksProviderUtils providerUtils;
private SharedPreferences sharedPreferences;
/*
* In order to support starting and binding to the service in the same
* unit test, we provide a workaround, as the original class doesn't allow
* to bind after the service has been previously started.
*/
private boolean bound;
private Intent serviceIntent;
public TrackRecordingServiceTest() {
super(TestRecordingService.class);
}
/**
* A context wrapper with the user provided {@link ContentResolver}.
*
* TODO: Move to test utils package.
*/
public static class MockContext extends ContextWrapper {
private final ContentResolver contentResolver;
public MockContext(ContentResolver contentResolver, Context base) {
super(base);
this.contentResolver = contentResolver;
}
@Override
public ContentResolver getContentResolver() {
return contentResolver;
}
}
@Override
protected IBinder bindService(Intent intent) {
if (getService() != null) {
if (bound) {
throw new IllegalStateException(
"Service: " + getService() + " is already bound");
}
bound = true;
serviceIntent = intent.cloneFilter();
return getService().onBind(intent);
} else {
return super.bindService(intent);
}
}
@Override
protected void shutdownService() {
if (bound) {
assertNotNull(getService());
getService().onUnbind(serviceIntent);
bound = false;
}
super.shutdownService();
}
@Override
protected void setUp() throws Exception {
super.setUp();
MockContentResolver mockContentResolver = new MockContentResolver();
RenamingDelegatingContext targetContext = new RenamingDelegatingContext(
getContext(), getContext(), "test.");
context = new MockContext(mockContentResolver, targetContext);
MyTracksProvider provider = new MyTracksProvider();
provider.attachInfo(context, null);
mockContentResolver.addProvider(MyTracksProviderUtils.AUTHORITY, provider);
setContext(context);
providerUtils = MyTracksProviderUtils.Factory.get(context);
sharedPreferences = context.getSharedPreferences(Constants.SETTINGS_NAME, Context.MODE_PRIVATE);
// Let's use default values.
sharedPreferences.edit().clear().apply();
// Disable auto resume by default.
updateAutoResumePrefs(0, -1);
// No recording track.
Editor editor = sharedPreferences.edit();
editor.putLong(context.getString(R.string.recording_track_key), -1);
editor.apply();
}
@SmallTest
public void testStartable() {
startService(createStartIntent());
assertNotNull(getService());
}
@MediumTest
public void testBindable() {
IBinder service = bindService(createStartIntent());
assertNotNull(service);
}
@MediumTest
public void testResumeAfterReboot_shouldResume() throws Exception {
// Insert a dummy track and mark it as recording track.
createDummyTrack(123, System.currentTimeMillis(), true);
// Clear the number of attempts and set the timeout to 10 min.
updateAutoResumePrefs(0, 10);
// Start the service in "resume" mode (simulates the on-reboot action).
Intent startIntent = createStartIntent();
startIntent.putExtra(RESUME_TRACK_EXTRA_NAME, true);
startService(startIntent);
assertNotNull(getService());
// We expect to resume the previous track.
assertTrue(getService().isRecording());
ITrackRecordingService service = bindAndGetService(createStartIntent());
assertEquals(123, service.getRecordingTrackId());
}
// TODO: shutdownService() has a bug and doesn't set mServiceCreated
// to false, thus preventing from a second call to onCreate().
// Report the bug to Android team. Until then, the following tests
// and checks must be commented out.
//
// TODO: If fixed, remove "disabled" prefix from the test name.
@MediumTest
public void disabledTestResumeAfterReboot_simulateReboot() throws Exception {
updateAutoResumePrefs(0, 10);
ITrackRecordingService service = bindAndGetService(createStartIntent());
assertFalse(service.isRecording());
// Simulate recording a track.
long id = service.startNewTrack();
assertTrue(service.isRecording());
assertEquals(id, service.getRecordingTrackId());
shutdownService();
assertEquals(id, sharedPreferences.getLong(
context.getString(R.string.recording_track_key), -1));
// Start the service in "resume" mode (simulates the on-reboot action).
Intent startIntent = createStartIntent();
startIntent.putExtra(RESUME_TRACK_EXTRA_NAME, true);
startService(startIntent);
assertNotNull(getService());
assertTrue(getService().isRecording());
}
@MediumTest
public void testResumeAfterReboot_noRecordingTrack() throws Exception {
// Insert a dummy track and mark it as recording track.
createDummyTrack(123, System.currentTimeMillis(), false);
// Clear the number of attempts and set the timeout to 10 min.
updateAutoResumePrefs(0, 10);
// Start the service in "resume" mode (simulates the on-reboot action).
Intent startIntent = createStartIntent();
startIntent.putExtra(RESUME_TRACK_EXTRA_NAME, true);
startService(startIntent);
assertNotNull(getService());
// We don't expect to resume the previous track, because it was stopped.
assertFalse(getService().isRecording());
ITrackRecordingService service = bindAndGetService(createStartIntent());
assertEquals(-1, service.getRecordingTrackId());
}
@MediumTest
public void testResumeAfterReboot_expiredTrack() throws Exception {
// Insert a dummy track last updated 20 min ago.
createDummyTrack(123, System.currentTimeMillis() - 20 * 60 * 1000, true);
// Clear the number of attempts and set the timeout to 10 min.
updateAutoResumePrefs(0, 10);
// Start the service in "resume" mode (simulates the on-reboot action).
Intent startIntent = createStartIntent();
startIntent.putExtra(RESUME_TRACK_EXTRA_NAME, true);
startService(startIntent);
assertNotNull(getService());
// We don't expect to resume the previous track, because it has expired.
assertFalse(getService().isRecording());
ITrackRecordingService service = bindAndGetService(createStartIntent());
assertEquals(-1, service.getRecordingTrackId());
}
@MediumTest
public void testResumeAfterReboot_tooManyAttempts() throws Exception {
// Insert a dummy track.
createDummyTrack(123, System.currentTimeMillis(), true);
// Set the number of attempts to max.
updateAutoResumePrefs(
TrackRecordingService.MAX_AUTO_RESUME_TRACK_RETRY_ATTEMPTS, 10);
// Start the service in "resume" mode (simulates the on-reboot action).
Intent startIntent = createStartIntent();
startIntent.putExtra(RESUME_TRACK_EXTRA_NAME, true);
startService(startIntent);
assertNotNull(getService());
// We don't expect to resume the previous track, because there were already
// too many attempts.
assertFalse(getService().isRecording());
ITrackRecordingService service = bindAndGetService(createStartIntent());
assertEquals(-1, service.getRecordingTrackId());
}
@MediumTest
public void testRecording_noTracks() throws Exception {
List<Track> tracks = providerUtils.getAllTracks();
assertTrue(tracks.isEmpty());
ITrackRecordingService service = bindAndGetService(createStartIntent());
// Test if we start in no-recording mode by default.
assertFalse(service.isRecording());
assertEquals(-1, service.getRecordingTrackId());
}
@MediumTest
public void testRecording_oldTracks() throws Exception {
createDummyTrack(123, -1, false);
ITrackRecordingService service = bindAndGetService(createStartIntent());
assertFalse(service.isRecording());
assertEquals(-1, service.getRecordingTrackId());
}
@MediumTest
public void testRecording_orphanedRecordingTrack() throws Exception {
// Just set recording track to a bogus value.
setRecordingTrack(256);
// Make sure that the service will not start recording and will clear
// the bogus track.
ITrackRecordingService service = bindAndGetService(createStartIntent());
assertFalse(service.isRecording());
assertEquals(-1, service.getRecordingTrackId());
}
/**
* Synchronous/waitable broadcast receiver to be used in testing.
*/
private class BlockingBroadcastReceiver extends BroadcastReceiver {
private static final long MAX_WAIT_TIME_MS = 10000;
private List<Intent> receivedIntents = new ArrayList<Intent>();
public List<Intent> getReceivedIntents() {
return receivedIntents;
}
@Override
public void onReceive(Context ctx, Intent intent) {
Log.d("MyTracksTest", "Got broadcast: " + intent);
synchronized (receivedIntents) {
receivedIntents.add(intent);
receivedIntents.notifyAll();
}
}
public boolean waitUntilReceived(int receiveCount) {
long deadline = System.currentTimeMillis() + MAX_WAIT_TIME_MS;
synchronized (receivedIntents) {
while (receivedIntents.size() < receiveCount) {
try {
// Wait releases synchronized lock until it returns
receivedIntents.wait(500);
} catch (InterruptedException e) {
// Do nothing
}
if (System.currentTimeMillis() > deadline) {
return false;
}
}
}
return true;
}
}
@MediumTest
public void testStartNewTrack_noRecording() throws Exception {
// NOTICE: due to the way Android permissions work, if this fails,
// uninstall the test apk then retry - the test must be installed *after*
// My Tracks (go figure).
// Reference: http://code.google.com/p/android/issues/detail?id=5521
BlockingBroadcastReceiver startReceiver = new BlockingBroadcastReceiver();
String startAction = context.getString(R.string.track_started_broadcast_action);
context.registerReceiver(startReceiver, new IntentFilter(startAction));
List<Track> tracks = providerUtils.getAllTracks();
assertTrue(tracks.isEmpty());
ITrackRecordingService service = bindAndGetService(createStartIntent());
assertFalse(service.isRecording());
long id = service.startNewTrack();
assertTrue(id >= 0);
assertTrue(service.isRecording());
Track track = providerUtils.getTrack(id);
assertNotNull(track);
assertEquals(id, track.getId());
assertEquals(sharedPreferences.getString(context.getString(R.string.default_activity_key), ""),
track.getCategory());
assertEquals(id, sharedPreferences.getLong(
context.getString(R.string.recording_track_key), -1));
assertEquals(id, service.getRecordingTrackId());
// Verify that the start broadcast was received.
assertTrue(startReceiver.waitUntilReceived(1));
List<Intent> receivedIntents = startReceiver.getReceivedIntents();
assertEquals(1, receivedIntents.size());
Intent broadcastIntent = receivedIntents.get(0);
assertEquals(startAction, broadcastIntent.getAction());
assertEquals(id, broadcastIntent.getLongExtra(
context.getString(R.string.track_id_broadcast_extra), -1));
context.unregisterReceiver(startReceiver);
}
@MediumTest
public void testStartNewTrack_alreadyRecording() throws Exception {
createDummyTrack(123, -1, true);
ITrackRecordingService service = bindAndGetService(createStartIntent());
assertTrue(service.isRecording());
// Starting a new track when there is a recording should just return -1L.
long newTrack = service.startNewTrack();
assertEquals(-1L, newTrack);
assertEquals(123, sharedPreferences.getLong(
context.getString(R.string.recording_track_key), 0));
assertEquals(123, service.getRecordingTrackId());
}
@MediumTest
public void testEndCurrentTrack_alreadyRecording() throws Exception {
// See comment above if this fails randomly.
BlockingBroadcastReceiver stopReceiver = new BlockingBroadcastReceiver();
String stopAction = context.getString(R.string.track_stopped_broadcast_action);
context.registerReceiver(stopReceiver, new IntentFilter(stopAction));
createDummyTrack(123, -1, true);
ITrackRecordingService service = bindAndGetService(createStartIntent());
assertTrue(service.isRecording());
// End the current track.
service.endCurrentTrack();
assertFalse(service.isRecording());
assertEquals(-1, sharedPreferences.getLong(
context.getString(R.string.recording_track_key), 0));
assertEquals(-1, service.getRecordingTrackId());
// Verify that the stop broadcast was received.
assertTrue(stopReceiver.waitUntilReceived(1));
List<Intent> receivedIntents = stopReceiver.getReceivedIntents();
assertEquals(1, receivedIntents.size());
Intent broadcastIntent = receivedIntents.get(0);
assertEquals(stopAction, broadcastIntent.getAction());
assertEquals(123, broadcastIntent.getLongExtra(
context.getString(R.string.track_id_broadcast_extra), -1));
context.unregisterReceiver(stopReceiver);
}
@MediumTest
public void testEndCurrentTrack_noRecording() throws Exception {
ITrackRecordingService service = bindAndGetService(createStartIntent());
assertFalse(service.isRecording());
// Ending the current track when there is no recording should not result in any error.
service.endCurrentTrack();
assertEquals(-1, sharedPreferences.getLong(
context.getString(R.string.recording_track_key), 0));
assertEquals(-1, service.getRecordingTrackId());
}
@MediumTest
public void testIntegration_completeRecordingSession() throws Exception {
List<Track> tracks = providerUtils.getAllTracks();
assertTrue(tracks.isEmpty());
fullRecordingSession();
}
@MediumTest
public void testInsertStatisticsMarker_noRecordingTrack() throws Exception {
ITrackRecordingService service = bindAndGetService(createStartIntent());
assertFalse(service.isRecording());
try {
service.insertWaypoint(WaypointCreationRequest.DEFAULT_STATISTICS);
fail("Expecting IllegalStateException");
} catch (IllegalStateException e) {
// Expected.
}
}
@MediumTest
public void testInsertStatisticsMarker_validLocation() throws Exception {
createDummyTrack(123, -1, true);
ITrackRecordingService service = bindAndGetService(createStartIntent());
assertTrue(service.isRecording());
assertEquals(1, service.insertWaypoint(WaypointCreationRequest.DEFAULT_STATISTICS));
assertEquals(2, service.insertWaypoint(WaypointCreationRequest.DEFAULT_STATISTICS));
Waypoint wpt = providerUtils.getWaypoint(1);
assertEquals(getContext().getString(R.string.marker_statistics_icon_url),
wpt.getIcon());
assertEquals(getContext().getString(R.string.marker_type_statistics),
wpt.getName());
assertEquals(Waypoint.TYPE_STATISTICS, wpt.getType());
assertEquals(123, wpt.getTrackId());
assertEquals(0.0, wpt.getLength());
assertNotNull(wpt.getLocation());
assertNotNull(wpt.getStatistics());
// TODO check the rest of the params.
// TODO: Check waypoint 2.
}
@MediumTest
public void testInsertWaypointMarker_noRecordingTrack() throws Exception {
ITrackRecordingService service = bindAndGetService(createStartIntent());
assertFalse(service.isRecording());
try {
service.insertWaypoint(WaypointCreationRequest.DEFAULT_MARKER);
fail("Expecting IllegalStateException");
} catch (IllegalStateException e) {
// Expected.
}
}
@MediumTest
public void testInsertWaypointMarker_validWaypoint() throws Exception {
createDummyTrack(123, -1, true);
ITrackRecordingService service = bindAndGetService(createStartIntent());
assertTrue(service.isRecording());
assertEquals(1, service.insertWaypoint(WaypointCreationRequest.DEFAULT_MARKER));
Waypoint wpt = providerUtils.getWaypoint(1);
assertEquals(getContext().getString(R.string.marker_waypoint_icon_url),
wpt.getIcon());
assertEquals(getContext().getString(R.string.marker_type_waypoint),
wpt.getName());
assertEquals(Waypoint.TYPE_WAYPOINT, wpt.getType());
assertEquals(123, wpt.getTrackId());
assertEquals(0.0, wpt.getLength());
assertNotNull(wpt.getLocation());
assertNull(wpt.getStatistics());
}
@MediumTest
public void testWithProperties_noAnnouncementFreq() throws Exception {
functionalTest(R.string.announcement_frequency_key, (Object) null);
}
@MediumTest
public void testWithProperties_defaultAnnouncementFreq() throws Exception {
functionalTest(R.string.announcement_frequency_key, 1);
}
@MediumTest
public void testWithProperties_noMaxRecordingDist() throws Exception {
functionalTest(R.string.max_recording_distance_key, (Object) null);
}
@MediumTest
public void testWithProperties_defaultMaxRecordingDist() throws Exception {
functionalTest(R.string.max_recording_distance_key, 5);
}
@MediumTest
public void testWithProperties_noMinRecordingDist() throws Exception {
functionalTest(R.string.min_recording_distance_key, (Object) null);
}
@MediumTest
public void testWithProperties_defaultMinRecordingDist() throws Exception {
functionalTest(R.string.min_recording_distance_key, 2);
}
@MediumTest
public void testWithProperties_noSplitFreq() throws Exception {
functionalTest(R.string.split_frequency_key, (Object) null);
}
@MediumTest
public void testWithProperties_defaultSplitFreqByDist() throws Exception {
functionalTest(R.string.split_frequency_key, 5);
}
@MediumTest
public void testWithProperties_defaultSplitFreqByTime() throws Exception {
functionalTest(R.string.split_frequency_key, -2);
}
@MediumTest
public void testWithProperties_noMetricUnits() throws Exception {
functionalTest(R.string.metric_units_key, (Object) null);
}
@MediumTest
public void testWithProperties_metricUnitsEnabled() throws Exception {
functionalTest(R.string.metric_units_key, true);
}
@MediumTest
public void testWithProperties_metricUnitsDisabled() throws Exception {
functionalTest(R.string.metric_units_key, false);
}
@MediumTest
public void testWithProperties_noMinRecordingInterval() throws Exception {
functionalTest(R.string.min_recording_interval_key, (Object) null);
}
@MediumTest
public void testWithProperties_defaultMinRecordingInterval()
throws Exception {
functionalTest(R.string.min_recording_interval_key, 3);
}
@MediumTest
public void testWithProperties_noMinRequiredAccuracy() throws Exception {
functionalTest(R.string.min_required_accuracy_key, (Object) null);
}
@MediumTest
public void testWithProperties_defaultMinRequiredAccuracy() throws Exception {
functionalTest(R.string.min_required_accuracy_key, 500);
}
@MediumTest
public void testWithProperties_noSensorType() throws Exception {
functionalTest(R.string.sensor_type_key, (Object) null);
}
@MediumTest
public void testWithProperties_zephyrSensorType() throws Exception {
functionalTest(R.string.sensor_type_key,
context.getString(R.string.sensor_type_value_zephyr));
}
private ITrackRecordingService bindAndGetService(Intent intent) {
ITrackRecordingService service = ITrackRecordingService.Stub.asInterface(
bindService(intent));
assertNotNull(service);
return service;
}
private Track createDummyTrack(long id, long stopTime, boolean isRecording) {
Track dummyTrack = new Track();
dummyTrack.setId(id);
dummyTrack.setName("Dummy Track");
TripStatistics tripStatistics = new TripStatistics();
tripStatistics.setStopTime(stopTime);
dummyTrack.setStatistics(tripStatistics);
addTrack(dummyTrack, isRecording);
return dummyTrack;
}
private void updateAutoResumePrefs(int attempts, int timeoutMins) {
Editor editor = sharedPreferences.edit();
editor.putInt(context.getString(
R.string.auto_resume_track_current_retry_key), attempts);
editor.putInt(context.getString(
R.string.auto_resume_track_timeout_key), timeoutMins);
editor.apply();
}
private Intent createStartIntent() {
Intent startIntent = new Intent();
startIntent.setClass(context, TrackRecordingService.class);
return startIntent;
}
private void addTrack(Track track, boolean isRecording) {
assertTrue(track.getId() >= 0);
providerUtils.insertTrack(track);
assertEquals(track.getId(), providerUtils.getTrack(track.getId()).getId());
setRecordingTrack(isRecording ? track.getId() : -1);
}
private void setRecordingTrack(long id) {
Editor editor = sharedPreferences.edit();
editor.putLong(context.getString(R.string.recording_track_key), id);
editor.apply();
}
// TODO: We support multiple values for readability, however this test's
// base class doesn't properly shutdown the service, so it's not possible
// to pass more than 1 value at a time.
private void functionalTest(int resourceId, Object ...values)
throws Exception {
final String key = context.getString(resourceId);
for (Object value : values) {
// Remove all properties and set the property for the given key.
Editor editor = sharedPreferences.edit();
editor.clear();
if (value instanceof String) {
editor.putString(key, (String) value);
} else if (value instanceof Long) {
editor.putLong(key, (Long) value);
} else if (value instanceof Integer) {
editor.putInt(key, (Integer) value);
} else if (value instanceof Boolean) {
editor.putBoolean(key, (Boolean) value);
} else if (value == null) {
// Do nothing, as clear above has already removed this property.
}
editor.apply();
fullRecordingSession();
}
}
private void fullRecordingSession() throws Exception {
ITrackRecordingService service = bindAndGetService(createStartIntent());
assertFalse(service.isRecording());
// Start a track.
long id = service.startNewTrack();
assertTrue(id >= 0);
assertTrue(service.isRecording());
Track track = providerUtils.getTrack(id);
assertNotNull(track);
assertEquals(id, track.getId());
assertEquals(id, sharedPreferences.getLong(
context.getString(R.string.recording_track_key), -1));
assertEquals(id, service.getRecordingTrackId());
// Insert a few points, markers and statistics.
long startTime = System.currentTimeMillis();
for (int i = 0; i < 30; i++) {
Location loc = new Location("gps");
loc.setLongitude(35.0f + i / 10.0f);
loc.setLatitude(45.0f - i / 5.0f);
loc.setAccuracy(5);
loc.setSpeed(10);
loc.setTime(startTime + i * 10000);
loc.setBearing(3.0f);
service.recordLocation(loc);
if (i % 10 == 0) {
service.insertWaypoint(WaypointCreationRequest.DEFAULT_STATISTICS);
} else if (i % 7 == 0) {
service.insertWaypoint(WaypointCreationRequest.DEFAULT_MARKER);
}
}
// Stop the track. Validate if it has correct data.
service.endCurrentTrack();
assertFalse(service.isRecording());
assertEquals(-1, service.getRecordingTrackId());
track = providerUtils.getTrack(id);
assertNotNull(track);
assertEquals(id, track.getId());
TripStatistics tripStatistics = track.getStatistics();
assertNotNull(tripStatistics);
assertTrue(tripStatistics.getStartTime() > 0);
assertTrue(tripStatistics.getStopTime() >= tripStatistics.getStartTime());
}
}
| Java |
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.services;
import static com.google.android.testing.mocking.AndroidMock.expect;
import com.google.android.testing.mocking.AndroidMock;
import com.google.android.testing.mocking.UsesMocks;
import android.test.AndroidTestCase;
import java.io.File;
/**
* Tests {@link RemoveTempFilesService}.
*
* @author Sandor Dornbush
*/
public class RemoveTempFilesServiceTest extends AndroidTestCase {
private static final String DIR_NAME = "/tmp";
private static final String FILE_NAME = "foo";
private RemoveTempFilesService service;
@UsesMocks({ File.class, })
protected void setUp() throws Exception {
service = new RemoveTempFilesService();
};
/**
* Tests when the directory doesn't exists.
*/
public void test_noDir() {
File dir = AndroidMock.createMock(File.class, DIR_NAME);
expect(dir.exists()).andStubReturn(false);
AndroidMock.replay(dir);
assertEquals(0, service.cleanTempDirectory(dir));
AndroidMock.verify(dir);
}
/**
* Tests when the directory is empty.
*/
public void test_emptyDir() {
File dir = AndroidMock.createMock(File.class, DIR_NAME);
expect(dir.exists()).andStubReturn(true);
expect(dir.listFiles()).andStubReturn(new File[0]);
AndroidMock.replay(dir);
assertEquals(0, service.cleanTempDirectory(dir));
AndroidMock.verify(dir);
}
/**
* Tests when there is a new file and it shouldn't get deleted.
*/
public void test_newFile() {
File file = AndroidMock.createMock(File.class, DIR_NAME + FILE_NAME);
expect(file.lastModified()).andStubReturn(System.currentTimeMillis());
File dir = AndroidMock.createMock(File.class, DIR_NAME);
expect(dir.exists()).andStubReturn(true);
expect(dir.listFiles()).andStubReturn(new File[] { file });
AndroidMock.replay(dir, file);
assertEquals(0, service.cleanTempDirectory(dir));
AndroidMock.verify(dir, file);
}
/**
* Tests when there is an old file and it should get deleted.
*/
public void test_oldFile() {
File file = AndroidMock.createMock(File.class, DIR_NAME + FILE_NAME);
// qSet to one hour and 1 millisecond later than the current time
expect(file.lastModified()).andStubReturn(System.currentTimeMillis() - 3600001);
expect(file.delete()).andStubReturn(true);
File dir = AndroidMock.createMock(File.class, DIR_NAME);
expect(dir.exists()).andStubReturn(true);
expect(dir.listFiles()).andStubReturn(new File[] { file });
AndroidMock.replay(dir, file);
assertEquals(1, service.cleanTempDirectory(dir));
AndroidMock.verify(dir, file);
}
}
| Java |
package com.google.android.apps.mytracks.services.sensors;
import com.google.android.apps.mytracks.Constants;
import com.google.android.apps.mytracks.services.sensors.ant.AntDirectSensorManager;
import com.google.android.apps.mytracks.services.sensors.ant.AntSrmBridgeSensorManager;
import com.google.android.maps.mytracks.R;
import android.content.Context;
import android.content.SharedPreferences;
import android.test.AndroidTestCase;
import android.test.suitebuilder.annotation.SmallTest;
public class SensorManagerFactoryTest extends AndroidTestCase {
private SharedPreferences sharedPreferences;
@Override
protected void setUp() throws Exception {
super.setUp();
sharedPreferences = getContext().getSharedPreferences(
Constants.SETTINGS_NAME, Context.MODE_PRIVATE);
// Let's use default values.
sharedPreferences.edit().clear().apply();
}
@SmallTest
public void testDefaultSettings() throws Exception {
assertNull(SensorManagerFactory.getInstance().getSensorManager(getContext()));
}
@SmallTest
public void testCreateZephyr() throws Exception {
assertClassForName(ZephyrSensorManager.class, R.string.sensor_type_value_zephyr);
}
@SmallTest
public void testCreateAnt() throws Exception {
assertClassForName(AntDirectSensorManager.class, R.string.sensor_type_value_ant);
}
@SmallTest
public void testCreateAntSRM() throws Exception {
assertClassForName(AntSrmBridgeSensorManager.class, R.string.sensor_type_value_srm_ant_bridge);
}
private void assertClassForName(Class<?> c, int i) {
sharedPreferences.edit()
.putString(getContext().getString(R.string.sensor_type_key),
getContext().getString(i))
.apply();
SensorManager sm = SensorManagerFactory.getInstance().getSensorManager(getContext());
assertNotNull(sm);
assertTrue(c.isInstance(sm));
SensorManagerFactory.getInstance().releaseSensorManager(sm);
}
}
| Java |
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.services.sensors.ant;
import android.test.AndroidTestCase;
public class AntStartupMessageTest extends AndroidTestCase {
public void testParse() {
byte[] rawMessage = {
0x12,
};
AntStartupMessage message = new AntStartupMessage(rawMessage);
assertEquals(0x12, message.getMessage());
}
}
| Java |
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.services.sensors.ant;
import com.dsi.ant.AntDefine;
import com.dsi.ant.AntMesg;
import android.test.AndroidTestCase;
public class AntChannelResponseMessageTest extends AndroidTestCase {
public void testParse() {
byte[] rawMessage = {
0,
AntMesg.MESG_EVENT_ID,
AntDefine.EVENT_RX_SEARCH_TIMEOUT
};
AntChannelResponseMessage message = new AntChannelResponseMessage(rawMessage);
assertEquals(0, message.getChannelNumber());
assertEquals(AntMesg.MESG_EVENT_ID, message.getMessageId());
assertEquals(AntDefine.EVENT_RX_SEARCH_TIMEOUT, message.getMessageCode());
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.services.sensors.ant;
import android.test.AndroidTestCase;
import android.test.suitebuilder.annotation.SmallTest;
/**
* @author Laszlo Molnar
*/
public class SensorEventCounterTest extends AndroidTestCase {
@SmallTest
public void testGetEventsPerMinute() {
SensorEventCounter sec = new SensorEventCounter();
assertEquals(0, sec.getEventsPerMinute(0, 0, 0));
assertEquals(0, sec.getEventsPerMinute(1, 1024, 1000));
assertEquals(60, sec.getEventsPerMinute(2, 1024 * 2, 2000));
assertEquals(60, sec.getEventsPerMinute(2, 1024 * 2, 2500));
assertTrue(60 > sec.getEventsPerMinute(2, 1024 * 2, 4000));
}
}
| Java |
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.services.sensors.ant;
import android.test.AndroidTestCase;
public class AntChannelIdMessageTest extends AndroidTestCase {
public void testParse() {
byte[] rawMessage = {
0, // channel number
0x34, 0x12, // device number
(byte) 0xaa, // device type id
(byte) 0xbb, // transmission type
};
AntChannelIdMessage message = new AntChannelIdMessage(rawMessage);
assertEquals(0, message.getChannelNumber());
assertEquals(0x1234, message.getDeviceNumber());
assertEquals((byte) 0xaa, message.getDeviceTypeId());
assertEquals((byte) 0xbb, message.getTransmissionType());
}
}
| Java |
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.services.sensors.ant;
import android.test.AndroidTestCase;
public class AntMessageTest extends AndroidTestCase {
private static class TestAntMessage extends AntMessage {
public static short decodeShort(byte low, byte high) {
return AntMessage.decodeShort(low, high);
}
}
public void testDecode() {
assertEquals(0x1234, TestAntMessage.decodeShort((byte) 0x34, (byte) 0x12));
}
}
| Java |
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.services.sensors.ant;
import android.content.Context;
import android.test.AndroidTestCase;
import android.test.MoreAsserts;
public class AntSensorManagerTest extends AndroidTestCase {
private class TestAntSensorManager extends AntSensorManager {
public TestAntSensorManager(Context context) {
super(context);
}
public byte messageId;
public byte[] messageData;
@Override
protected void setupAntSensorChannels() {}
@SuppressWarnings("deprecation")
@Override
public void handleMessage(byte[] rawMessage) {
super.handleMessage(rawMessage);
}
@SuppressWarnings("hiding")
@Override
public boolean handleMessage(byte messageId, byte[] messageData) {
this.messageId = messageId;
this.messageData = messageData;
return true;
}
}
private TestAntSensorManager sensorManager;
@Override
protected void setUp() throws Exception {
super.setUp();
sensorManager = new TestAntSensorManager(getContext());
}
public void testSimple() {
byte[] rawMessage = {
0x03, // length
0x12, // message id
0x11, 0x22, 0x33, // body
};
byte[] expectedBody = { 0x11, 0x22, 0x33 };
sensorManager.handleMessage(rawMessage);
assertEquals((byte) 0x12, sensorManager.messageId);
MoreAsserts.assertEquals(expectedBody, sensorManager.messageData);
}
public void testTooShort() {
byte[] rawMessage = {
0x53, // length
0x12 // message id
};
sensorManager.handleMessage(rawMessage);
assertEquals(0, sensorManager.messageId);
assertNull(sensorManager.messageData);
}
public void testLengthWrong() {
byte[] rawMessage = {
0x53, // length
0x12, // message id
0x34, // body
};
sensorManager.handleMessage(rawMessage);
assertEquals(0, sensorManager.messageId);
assertNull(sensorManager.messageData);
}
}
| Java |
/*
* Copyright 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.services.sensors.ant;
import com.dsi.ant.AntMesg;
import com.google.android.apps.mytracks.Constants;
import com.google.android.apps.mytracks.content.Sensor;
import com.google.android.maps.mytracks.R;
import android.content.Context;
import android.content.SharedPreferences;
import android.test.AndroidTestCase;
import android.test.suitebuilder.annotation.SmallTest;
public class AntDirectSensorManagerTest extends AndroidTestCase {
private SharedPreferences sharedPreferences;
private AntSensorBase heartRateSensor;
private static final byte HEART_RATE_CHANNEL = 0;
private class MockAntDirectSensorManager extends AntDirectSensorManager {
public MockAntDirectSensorManager(Context context) {
super(context);
}
@Override
protected boolean setupChannel(AntSensorBase sensor, byte channel) {
if (channel == HEART_RATE_CHANNEL) {
heartRateSensor = sensor;
return true;
}
return false;
}
}
private AntDirectSensorManager manager;
public void setUp() {
sharedPreferences = getContext().getSharedPreferences(
Constants.SETTINGS_NAME, Context.MODE_PRIVATE);
// Let's use default values.
sharedPreferences.edit().clear().apply();
manager = new MockAntDirectSensorManager(getContext());
}
@SmallTest
public void testBroadcastData() {
manager.setupAntSensorChannels();
assertNotNull(heartRateSensor);
heartRateSensor.setDeviceNumber((short) 42);
byte[] buff = new byte[9];
buff[0] = HEART_RATE_CHANNEL;
buff[8] = (byte) 220;
manager.handleMessage(AntMesg.MESG_BROADCAST_DATA_ID, buff);
Sensor.SensorDataSet sds = manager.getSensorDataSet();
assertNotNull(sds);
assertTrue(sds.hasHeartRate());
assertEquals(Sensor.SensorState.SENDING,
sds.getHeartRate().getState());
assertEquals(220, sds.getHeartRate().getValue());
assertFalse(sds.hasCadence());
assertFalse(sds.hasPower());
assertEquals(Sensor.SensorState.CONNECTED, manager.getSensorState());
}
@SmallTest
public void testChannelId() {
manager.setupAntSensorChannels();
assertNotNull(heartRateSensor);
byte[] buff = new byte[9];
buff[1] = 43;
manager.handleMessage(AntMesg.MESG_CHANNEL_ID_ID, buff);
assertEquals(43, heartRateSensor.getDeviceNumber());
assertEquals(43,
sharedPreferences.getInt(
getContext().getString(R.string.ant_heart_rate_sensor_id_key), -1));
assertNull(manager.getSensorDataSet());
}
@SmallTest
public void testResponseEvent() {
manager.setupAntSensorChannels();
assertNotNull(heartRateSensor);
manager.setHeartRate(210);
heartRateSensor.setDeviceNumber((short) 42);
assertEquals(Sensor.SensorState.CONNECTED, manager.getSensorState());
byte[] buff = new byte[3];
buff[0] = HEART_RATE_CHANNEL;
buff[1] = AntMesg.MESG_UNASSIGN_CHANNEL_ID;
buff[2] = 0; // code
manager.handleMessage(AntMesg.MESG_RESPONSE_EVENT_ID, buff);
assertEquals(Sensor.SensorState.CONNECTED, manager.getSensorState());
heartRateSensor.setDeviceNumber((short) 0);
manager.handleMessage(AntMesg.MESG_RESPONSE_EVENT_ID, buff);
assertEquals(Sensor.SensorState.DISCONNECTED, manager.getSensorState());
}
// TODO: Test timeout too.
}
| Java |
package com.google.android.apps.mytracks.services.sensors;
import java.util.Arrays;
import com.google.android.apps.mytracks.content.Sensor;
import junit.framework.TestCase;
public class PolarMessageParserTest extends TestCase {
PolarMessageParser parser = new PolarMessageParser();
// A complete and valid Polar HxM packet
// FE08F701D1001104FE08F702D1001104
private final byte[] originalBuf =
{(byte) 0xFE, 0x08, (byte) 0xF7, 0x01, (byte) 0xD1, 0x00, 0x11, 0x04, (byte) 0xFE, 0x08,
(byte) 0xF7, 0x02, (byte) 0xD1, 0x00, 0x11, 0x04};
private byte[] buf;
public void setUp() {
buf = Arrays.copyOf(originalBuf, originalBuf.length);
}
public void testIsValid() {
assertTrue(parser.isValid(buf));
}
public void testIsValid_invalidHeader() {
// Invalidate header.
buf[0] = 0x03;
assertFalse(parser.isValid(buf));
}
public void testIsValid_invalidCheckbyte() {
// Invalidate checkbyte.
buf[2] = 0x03;
assertFalse(parser.isValid(buf));
}
public void testIsValid_invalidSequence() {
// Invalidate sequence.
buf[3] = 0x11;
assertFalse(parser.isValid(buf));
}
public void testParseBuffer() {
buf[5] = 70;
Sensor.SensorDataSet sds = parser.parseBuffer(buf);
assertTrue(sds.hasHeartRate());
assertTrue(sds.getHeartRate().getState() == Sensor.SensorState.SENDING);
assertEquals(70, sds.getHeartRate().getValue());
}
public void testFindNextAlignment_offset() {
// The first 4 bytes are garbage
buf = new byte[originalBuf.length + 4];
buf[0] = 4;
buf[1] = 2;
buf[2] = 4;
buf[3] = 2;
// Then the valid message.
System.arraycopy(originalBuf, 0, buf, 4, originalBuf.length);
assertEquals(4, parser.findNextAlignment(buf));
}
public void testFindNextAlignment_invalid() {
buf[0] = 0;
assertEquals(-1, parser.findNextAlignment(buf));
}
}
| Java |
package com.google.android.apps.mytracks.services.sensors;
import com.google.android.apps.mytracks.content.Sensor;
import junit.framework.TestCase;
public class ZephyrMessageParserTest extends TestCase {
ZephyrMessageParser parser = new ZephyrMessageParser();
public void testIsValid() {
byte[] smallBuf = new byte[59];
assertFalse(parser.isValid(smallBuf));
// A complete and valid Zephyr HxM packet
byte[] buf = { 2,38,55,26,0,49,101,80,0,49,98,100,42,113,120,-53,-24,-60,-123,-61,117,-69,42,-75,74,-78,51,-79,27,-83,28,-88,28,-93,29,-98,25,-103,26,-108,26,-113,59,-118,0,0,0,0,0,0,-22,3,125,1,48,0,96,4,30,0 };
// Make buffer invalid
buf[0] = buf[58] = buf[59] = 0;
assertFalse(parser.isValid(buf));
buf[0] = 0x02;
assertFalse(parser.isValid(buf));
buf[58] = 0x1E;
assertFalse(parser.isValid(buf));
buf[59] = 0x03;
assertTrue(parser.isValid(buf));
}
public void testParseBuffer() {
byte[] buf = new byte[60];
// Heart Rate (-1 =^ 255 unsigned byte)
buf[12] = -1;
// Battery Level
buf[11] = 51;
// Cadence (=^ 255*16 strides/min)
buf[56] = -1;
buf[57] = 15;
Sensor.SensorDataSet sds = parser.parseBuffer(buf);
assertTrue(sds.hasHeartRate());
assertTrue(sds.getHeartRate().getState() == Sensor.SensorState.SENDING);
assertEquals(255, sds.getHeartRate().getValue());
assertTrue(sds.hasBatteryLevel());
assertTrue(sds.getBatteryLevel().getState() == Sensor.SensorState.SENDING);
assertEquals(51, sds.getBatteryLevel().getValue());
assertTrue(sds.hasCadence());
assertTrue(sds.getCadence().getState() == Sensor.SensorState.SENDING);
assertEquals(255, sds.getCadence().getValue());
}
public void testFindNextAlignment() {
byte[] buf = new byte[60];
assertEquals(-1, parser.findNextAlignment(buf));
buf[10] = 0x03;
buf[11] = 0x02;
assertEquals(10, parser.findNextAlignment(buf));
}
}
| Java |
// Copyright 2012 Google Inc. All Rights Reserved.
package com.google.android.apps.mytracks.services;
import android.app.Notification;
import android.app.Service;
import android.test.ServiceTestCase;
import android.util.Log;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* A {@link TrackRecordingService} that can be used with {@link ServiceTestCase}.
* {@link ServiceTestCase} throws a null pointer exception when the service
* calls {@link Service#startForeground(int, android.app.Notification)} and
* {@link Service#stopForeground(boolean)}.
* <p>
* See http://code.google.com/p/android/issues/detail?id=12122
* <p>
* Wrap these two methods in wrappers and override them.
*
* @author Jimmy Shih
*/
public class TestRecordingService extends TrackRecordingService {
private static final String TAG = TestRecordingService.class.getSimpleName();
@Override
protected void startForegroundService(Notification notification) {
try {
Method setForegroundMethod = Service.class.getMethod("setForeground", boolean.class);
setForegroundMethod.invoke(this, true);
} catch (SecurityException e) {
Log.e(TAG, "Unable to start a service in foreground", e);
} catch (NoSuchMethodException e) {
Log.e(TAG, "Unable to start a service in foreground", e);
} catch (IllegalArgumentException e) {
Log.e(TAG, "Unable to start a service in foreground", e);
} catch (IllegalAccessException e) {
Log.e(TAG, "Unable to start a service in foreground", e);
} catch (InvocationTargetException e) {
Log.e(TAG, "Unable to start a service in foreground", e);
}
}
@Override
protected void stopForegroundService() {
try {
Method setForegroundMethod = Service.class.getMethod("setForeground", boolean.class);
setForegroundMethod.invoke(this, false);
} catch (SecurityException e) {
Log.e(TAG, "Unable to start a service in foreground", e);
} catch (NoSuchMethodException e) {
Log.e(TAG, "Unable to start a service in foreground", e);
} catch (IllegalArgumentException e) {
Log.e(TAG, "Unable to start a service in foreground", e);
} catch (IllegalAccessException e) {
Log.e(TAG, "Unable to start a service in foreground", e);
} catch (InvocationTargetException e) {
Log.e(TAG, "Unable to start a service in foreground", e);
}
}
}
| Java |
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.content;
import com.google.android.apps.mytracks.content.WaypointCreationRequest.WaypointType;
import android.os.Parcel;
import android.test.AndroidTestCase;
/**
* Tests for the WaypointCreationRequest class.
* {@link WaypointCreationRequest}
*
* @author Sandor Dornbush
*/
public class WaypointCreationRequestTest extends AndroidTestCase {
public void testTypeParceling() {
WaypointCreationRequest original = WaypointCreationRequest.DEFAULT_MARKER;
Parcel p = Parcel.obtain();
original.writeToParcel(p, 0);
p.setDataPosition(0);
WaypointCreationRequest copy = WaypointCreationRequest.CREATOR.createFromParcel(p);
assertEquals(original.getType(), copy.getType());
assertNull(copy.getName());
assertNull(copy.getDescription());
assertNull(copy.getIconUrl());
}
public void testAllAttributesParceling() {
WaypointCreationRequest original =
new WaypointCreationRequest(WaypointType.MARKER, "name", "description", "img.png");
Parcel p = Parcel.obtain();
original.writeToParcel(p, 0);
p.setDataPosition(0);
WaypointCreationRequest copy = WaypointCreationRequest.CREATOR.createFromParcel(p);
assertEquals(original.getType(), copy.getType());
assertEquals("name", copy.getName());
assertEquals("description", copy.getDescription());
assertEquals("img.png", copy.getIconUrl());
}
}
| Java |
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.content;
import com.google.android.apps.mytracks.content.MyTracksProviderUtils.LocationFactory;
import com.google.android.apps.mytracks.content.MyTracksProviderUtils.LocationIterator;
import com.google.android.apps.mytracks.services.TrackRecordingServiceTest.MockContext;
import android.content.Context;
import android.location.Location;
import android.test.AndroidTestCase;
import android.test.RenamingDelegatingContext;
import android.test.mock.MockContentResolver;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
/**
* A unit test for {@link MyTracksProviderUtilsImpl}.
*
* @author Bartlomiej Niechwiej
*/
public class MyTracksProviderUtilsImplTest extends AndroidTestCase {
private Context context;
private MyTracksProviderUtils providerUtils;
@Override
protected void setUp() throws Exception {
super.setUp();
MockContentResolver mockContentResolver = new MockContentResolver();
RenamingDelegatingContext targetContext = new RenamingDelegatingContext(
getContext(), getContext(), "test.");
context = new MockContext(mockContentResolver, targetContext);
MyTracksProvider provider = new MyTracksProvider();
provider.attachInfo(context, null);
mockContentResolver.addProvider(MyTracksProviderUtils.AUTHORITY, provider);
setContext(context);
providerUtils = MyTracksProviderUtils.Factory.get(context);
}
public void testLocationIterator_noPoints() {
testIterator(1, 0, 1, false, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY);
}
public void testLocationIterator_customFactory() {
final Location location = new Location("test_location");
final AtomicInteger counter = new AtomicInteger();
testIterator(1, 15, 4, false, new LocationFactory() {
@Override
public Location createLocation() {
counter.incrementAndGet();
return location;
}
});
// Make sure we were called exactly as many times as we had track points.
assertEquals(15, counter.get());
}
public void testLocationIterator_nullFactory() {
try {
testIterator(1, 15, 4, false, null);
fail("Expecting IllegalArgumentException");
} catch (IllegalArgumentException e) {
// Expected.
}
}
public void testLocationIterator_noBatchAscending() {
testIterator(1, 50, 100, false, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY);
testIterator(2, 50, 50, false, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY);
}
public void testLocationIterator_noBatchDescending() {
testIterator(1, 50, 100, true, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY);
testIterator(2, 50, 50, true, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY);
}
public void testLocationIterator_batchAscending() {
testIterator(1, 50, 11, false, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY);
testIterator(2, 50, 25, false, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY);
}
public void testLocationIterator_batchDescending() {
testIterator(1, 50, 11, true, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY);
testIterator(2, 50, 25, true, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY);
}
public void testLocationIterator_largeTrack() {
testIterator(1, 20000, 2000, false, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY);
}
private List<Location> testIterator(long trackId, int numPoints, int batchSize,
boolean descending, LocationFactory locationFactory) {
long lastPointId = initializeTrack(trackId, numPoints);
((MyTracksProviderUtilsImpl) providerUtils).setDefaultCursorBatchSize(batchSize);
List<Location> locations = new ArrayList<Location>(numPoints);
LocationIterator it = providerUtils.getLocationIterator(trackId, -1, descending, locationFactory);
try {
while (it.hasNext()) {
Location loc = it.next();
assertNotNull(loc);
locations.add(loc);
// Make sure the IDs are returned in the right order.
assertEquals(descending ? lastPointId - locations.size() + 1
: lastPointId - numPoints + locations.size(), it.getLocationId());
}
assertEquals(numPoints, locations.size());
} finally {
it.close();
}
return locations;
}
private long initializeTrack(long id, int numPoints) {
Track track = new Track();
track.setId(id);
track.setName("Test: " + id);
track.setNumberOfPoints(numPoints);
providerUtils.insertTrack(track);
track = providerUtils.getTrack(id);
assertNotNull(track);
Location[] locations = new Location[numPoints];
for (int i = 0; i < numPoints; ++i) {
Location loc = new Location("test");
loc.setLatitude(37.0 + (double) i / 10000.0);
loc.setLongitude(57.0 - (double) i / 10000.0);
loc.setAccuracy((float) i / 100.0f);
loc.setAltitude(i * 2.5);
locations[i] = loc;
}
providerUtils.bulkInsertTrackPoints(locations, numPoints, id);
// Load all inserted locations.
long lastPointId = -1;
int counter = 0;
LocationIterator it = providerUtils.getLocationIterator(id, -1, false,
MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY);
try {
while (it.hasNext()) {
it.next();
lastPointId = it.getLocationId();
counter++;
}
} finally {
it.close();
}
assertTrue(numPoints == 0 || lastPointId > 0);
assertEquals(numPoints, track.getNumberOfPoints());
assertEquals(numPoints, counter);
return lastPointId;
}
}
| Java |
/**
*
*/
package com.google.android.apps.mytracks.content;
import com.google.android.apps.mytracks.content.SearchEngine.ScoredResult;
import com.google.android.apps.mytracks.content.SearchEngine.SearchQuery;
import com.google.android.apps.mytracks.services.TrackRecordingServiceTest.MockContext;
import com.google.android.apps.mytracks.stats.TripStatistics;
import android.content.ContentUris;
import android.location.Location;
import android.net.Uri;
import android.test.AndroidTestCase;
import android.test.RenamingDelegatingContext;
import android.test.mock.MockContentResolver;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Tests for {@link SearchEngine}.
* These are not meant to be quality tests, but instead feature-by-feature tests
* (in other words, they don't test the mixing of different score boostings, just
* each boosting separately)
*
* @author Rodrigo Damazio
*/
public class SearchEngineTest extends AndroidTestCase {
private static final Location HERE = new Location("gps");
private static final long NOW = 1234567890000L; // After OLDEST_ALLOWED_TIMESTAMP
private MyTracksProviderUtils providerUtils;
private SearchEngine engine;
@Override
protected void setUp() throws Exception {
super.setUp();
MockContentResolver mockContentResolver = new MockContentResolver();
RenamingDelegatingContext targetContext = new RenamingDelegatingContext(
getContext(), getContext(), "test.");
MockContext context = new MockContext(mockContentResolver, targetContext);
MyTracksProvider provider = new MyTracksProvider();
provider.attachInfo(context, null);
mockContentResolver.addProvider(MyTracksProviderUtils.AUTHORITY, provider);
setContext(context);
providerUtils = MyTracksProviderUtils.Factory.get(context);
engine = new SearchEngine(providerUtils);
}
@Override
protected void tearDown() throws Exception {
providerUtils.deleteAllTracks();
super.tearDown();
}
private long insertTrack(String title, String description, String category, double distance, long hoursAgo) {
Track track = new Track();
track.setName(title);
track.setDescription(description);
track.setCategory(category);
TripStatistics stats = track.getStatistics();
if (hoursAgo > 0) {
// Started twice hoursAgo, so the average time is hoursAgo.
stats.setStartTime(NOW - hoursAgo * 1000L * 60L * 60L * 2);
stats.setStopTime(NOW);
}
int latitude = (int) ((HERE.getLatitude() + distance) * 1E6);
int longitude = (int) ((HERE.getLongitude() + distance) * 1E6);
stats.setBounds(latitude, longitude, latitude, longitude);
Uri uri = providerUtils.insertTrack(track);
return ContentUris.parseId(uri);
}
private long insertTrack(String title, String description, String category) {
return insertTrack(title, description, category, 0, -1);
}
private long insertTrack(String title, double distance) {
return insertTrack(title, "", "", distance, -1);
}
private long insertTrack(String title, long hoursAgo) {
return insertTrack(title, "", "", 0.0, hoursAgo);
}
private long insertWaypoint(String title, String description, String category, double distance, long hoursAgo, long trackId) {
Waypoint waypoint = new Waypoint();
waypoint.setName(title);
waypoint.setDescription(description);
waypoint.setCategory(category);
waypoint.setTrackId(trackId);
Location location = new Location(HERE);
location.setLatitude(location.getLatitude() + distance);
location.setLongitude(location.getLongitude() + distance);
if (hoursAgo >= 0) {
location.setTime(NOW - hoursAgo * 1000L * 60L * 60L);
}
waypoint.setLocation(location);
Uri uri = providerUtils.insertWaypoint(waypoint);
return ContentUris.parseId(uri);
}
private long insertWaypoint(String title, String description, String category) {
return insertWaypoint(title, description, category, 0.0, -1, -1);
}
private long insertWaypoint(String title, double distance) {
return insertWaypoint(title, "", "", distance, -1, -1);
}
private long insertWaypoint(String title, long hoursAgo) {
return insertWaypoint(title, "", "", 0.0, hoursAgo, -1);
}
private long insertWaypoint(String title, long hoursAgo, long trackId) {
return insertWaypoint(title, "", "", 0.0, hoursAgo, trackId);
}
public void testSearchText() {
// Insert 7 tracks (purposefully out of result order):
// - one which won't match
// - one which will match the description
// - one which will match the category
// - one which will match the title
// - one which will match in title and category
// - one which will match in title and description
// - one which will match in all fields
insertTrack("bb", "cc", "dd");
long descriptionMatchId = insertTrack("bb", "aa", "cc");
long categoryMatchId = insertTrack("bb", "cc", "aa");
long titleMatchId = insertTrack("aa", "bb", "cc");
long titleCategoryMatchId = insertTrack("aa", "bb", "ca");
long titleDescriptionMatchId = insertTrack("aa", "ba", "cc");
long allMatchId = insertTrack("aa", "ba", "ca");
SearchQuery query = new SearchQuery("a", null, -1, NOW);
ArrayList<ScoredResult> results = new ArrayList<ScoredResult>(engine.search(query));
// Title > Description > Category.
assertTrackResults(results,
allMatchId, titleDescriptionMatchId, titleCategoryMatchId, titleMatchId, descriptionMatchId,
categoryMatchId);
}
public void testSearchWaypointText() {
// Insert 7 waypoints (purposefully out of result order):
// - one which won't match
// - one which will match the description
// - one which will match the category
// - one which will match the title
// - one which will match in title and category
// - one which will match in title and description
// - one which will match in all fields
insertWaypoint("bb", "cc", "dd");
long descriptionMatchId = insertWaypoint("bb", "aa", "cc");
long categoryMatchId = insertWaypoint("bb", "cc", "aa");
long titleMatchId = insertWaypoint("aa", "bb", "cc");
long titleCategoryMatchId = insertWaypoint("aa", "bb", "ca");
long titleDescriptionMatchId = insertWaypoint("aa", "ba", "cc");
long allMatchId = insertWaypoint("aa", "ba", "ca");
SearchQuery query = new SearchQuery("a", null, -1, NOW);
ArrayList<ScoredResult> results = new ArrayList<ScoredResult>(engine.search(query));
// Title > Description > Category.
assertWaypointResults(results,
allMatchId, titleDescriptionMatchId, titleCategoryMatchId, titleMatchId, descriptionMatchId,
categoryMatchId);
}
public void testSearchMixedText() {
// Insert 5 entries (purposefully out of result order):
// - one waypoint which will match by description
// - one waypoint which won't match
// - one waypoint which will match by title
// - one track which won't match
// - one track which will match by title
long descriptionWaypointId = insertWaypoint("bb", "aa", "cc");
insertWaypoint("bb", "cc", "dd");
long titleWaypointId = insertWaypoint("aa", "bb", "cc");
insertTrack("bb", "cc", "dd");
long trackId = insertTrack("aa", "bb", "cc");
SearchQuery query = new SearchQuery("a", null, -1, NOW);
ArrayList<ScoredResult> results = new ArrayList<ScoredResult>(engine.search(query));
// Title > Description > Category.
assertEquals(results.toString(), 3, results.size());
assertTrackResult(trackId, results.get(0));
assertWaypointResult(titleWaypointId, results.get(1));
assertWaypointResult(descriptionWaypointId, results.get(2));
}
public void testSearchTrackDistance() {
// All results match text, but they're at difference distances from the user.
long farFarAwayId = insertTrack("aa", 0.3);
long nearId = insertTrack("ab", 0.1);
long farId = insertTrack("ac", 0.2);
SearchQuery query = new SearchQuery("a", HERE, -1, NOW);
ArrayList<ScoredResult> results = new ArrayList<ScoredResult>(engine.search(query));
// Distance order.
assertTrackResults(results, nearId, farId, farFarAwayId);
}
public void testSearchWaypointDistance() {
// All results match text, but they're at difference distances from the user.
long farFarAwayId = insertWaypoint("aa", 0.3);
long nearId = insertWaypoint("ab", 0.1);
long farId = insertWaypoint("ac", 0.2);
SearchQuery query = new SearchQuery("a", HERE, -1, NOW);
ArrayList<ScoredResult> results = new ArrayList<ScoredResult>(engine.search(query));
// Distance order.
assertWaypointResults(results, nearId, farId, farFarAwayId);
}
public void testSearchTrackRecent() {
// All results match text, but they're were recorded at different times.
long oldestId = insertTrack("aa", 3);
long recentId = insertTrack("ab", 1);
long oldId = insertTrack("ac", 2);
SearchQuery query = new SearchQuery("a", null, -1, NOW);
ArrayList<ScoredResult> results = new ArrayList<ScoredResult>(engine.search(query));
// Reverse time order.
assertTrackResults(results, recentId, oldId, oldestId);
}
public void testSearchWaypointRecent() {
// All results match text, but they're were recorded at different times.
long oldestId = insertWaypoint("aa", 2);
long recentId = insertWaypoint("ab", 0);
long oldId = insertWaypoint("ac", 1);
SearchQuery query = new SearchQuery("a", null, -1, NOW);
ArrayList<ScoredResult> results = new ArrayList<ScoredResult>(engine.search(query));
// Reverse time order.
assertWaypointResults(results, recentId, oldId, oldestId);
}
public void testSearchCurrentTrack() {
// All results match text, but one of them is the current track.
long currentId = insertTrack("ab", 1);
long otherId = insertTrack("aa", 1);
SearchQuery query = new SearchQuery("a", null, currentId, NOW);
ArrayList<ScoredResult> results = new ArrayList<ScoredResult>(engine.search(query));
// Current track should be demoted.
assertTrackResults(results, otherId, currentId);
}
public void testSearchCurrentTrackWaypoint() {
// All results match text, but one of them is in the current track.
long otherId = insertWaypoint("aa", 1, 456);
long currentId = insertWaypoint("ab", 1, 123);
SearchQuery query = new SearchQuery("a", null, 123, NOW);
ArrayList<ScoredResult> results = new ArrayList<ScoredResult>(engine.search(query));
// Waypoint in current track should be promoted.
assertWaypointResults(results, currentId, otherId);
}
private void assertTrackResult(long trackId, ScoredResult result) {
assertNotNull("Not a track", result.track);
assertNull("Ambiguous result", result.waypoint);
assertEquals(trackId, result.track.getId());
}
private void assertTrackResults(List<ScoredResult> results, long... trackIds) {
String errMsg = "Expected IDs=" + Arrays.toString(trackIds) + "; results=" + results;
assertEquals(results.size(), trackIds.length);
for (int i = 0; i < results.size(); i++) {
ScoredResult result = results.get(i);
assertNotNull(errMsg, result.track);
assertNull(errMsg, result.waypoint);
assertEquals(errMsg, trackIds[i], result.track.getId());
}
}
private void assertWaypointResult(long waypointId, ScoredResult result) {
assertNotNull("Not a waypoint", result.waypoint);
assertNull("Ambiguous result", result.track);
assertEquals(waypointId, result.waypoint.getId());
}
private void assertWaypointResults(List<ScoredResult> results, long... waypointIds) {
String errMsg = "Expected IDs=" + Arrays.toString(waypointIds) + "; results=" + results;
assertEquals(results.size(), waypointIds.length);
for (int i = 0; i < results.size(); i++) {
ScoredResult result = results.get(i);
assertNotNull(errMsg, result.waypoint);
assertNull(errMsg, result.track);
assertEquals(errMsg, waypointIds[i], result.waypoint.getId());
}
}
}
| Java |
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.content;
import static com.google.android.testing.mocking.AndroidMock.anyInt;
import static com.google.android.testing.mocking.AndroidMock.capture;
import static com.google.android.testing.mocking.AndroidMock.eq;
import static com.google.android.testing.mocking.AndroidMock.expect;
import static com.google.android.testing.mocking.AndroidMock.isA;
import static com.google.android.testing.mocking.AndroidMock.leq;
import static com.google.android.testing.mocking.AndroidMock.same;
import com.google.android.apps.mytracks.Constants;
import com.google.android.apps.mytracks.content.MyTracksProviderUtils.LocationFactory;
import com.google.android.apps.mytracks.content.MyTracksProviderUtils.LocationIterator;
import com.google.android.apps.mytracks.content.TrackDataHub.ListenerDataType;
import com.google.android.apps.mytracks.content.TrackDataListener.ProviderState;
import com.google.android.apps.mytracks.services.TrackRecordingServiceTest.MockContext;
import com.google.android.maps.mytracks.R;
import com.google.android.testing.mocking.AndroidMock;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.database.ContentObserver;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.location.Location;
import android.location.LocationListener;
import android.provider.BaseColumns;
import android.test.AndroidTestCase;
import android.test.RenamingDelegatingContext;
import android.test.mock.MockContentResolver;
import java.lang.reflect.Constructor;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.Set;
import org.easymock.Capture;
import org.easymock.IAnswer;
/**
* Tests for {@link TrackDataHub}.
*
* @author Rodrigo Damazio
*/
public class TrackDataHubTest extends AndroidTestCase {
private static final long TRACK_ID = 42L;
private static final int TARGET_POINTS = 50;
private MyTracksProviderUtils providerUtils;
private TrackDataHub hub;
private TrackDataListeners listeners;
private DataSourcesWrapper dataSources;
private SharedPreferences prefs;
private TrackDataListener listener1;
private TrackDataListener listener2;
private Capture<OnSharedPreferenceChangeListener> preferenceListenerCapture =
new Capture<SharedPreferences.OnSharedPreferenceChangeListener>();
private MockContext context;
private float declination;
@Override
protected void setUp() throws Exception {
super.setUp();
MockContentResolver mockContentResolver = new MockContentResolver();
RenamingDelegatingContext targetContext = new RenamingDelegatingContext(
getContext(), getContext(), "test.");
context = new MockContext(mockContentResolver, targetContext);
prefs = context.getSharedPreferences(Constants.SETTINGS_NAME, Context.MODE_PRIVATE);
providerUtils = AndroidMock.createMock("providerUtils", MyTracksProviderUtils.class);
dataSources = AndroidMock.createNiceMock("dataSources", DataSourcesWrapper.class);
listeners = new TrackDataListeners();
hub = new TrackDataHub(context, listeners, prefs, providerUtils, TARGET_POINTS) {
@Override
protected DataSourcesWrapper newDataSources() {
return dataSources;
}
@Override
protected void runInListenerThread(Runnable runnable) {
// Run everything in the same thread.
runnable.run();
}
@Override
protected float getDeclinationFor(Location location, long timestamp) {
return declination;
}
};
listener1 = AndroidMock.createStrictMock("listener1", TrackDataListener.class);
listener2 = AndroidMock.createStrictMock("listener2", TrackDataListener.class);
}
@Override
protected void tearDown() throws Exception {
AndroidMock.reset(dataSources);
// Expect everything to be unregistered.
if (preferenceListenerCapture.hasCaptured()) {
dataSources.unregisterOnSharedPreferenceChangeListener(preferenceListenerCapture.getValue());
}
dataSources.removeLocationUpdates(isA(LocationListener.class));
dataSources.unregisterSensorListener(isA(SensorEventListener.class));
dataSources.unregisterContentObserver(isA(ContentObserver.class));
AndroidMock.expectLastCall().times(3);
AndroidMock.replay(dataSources);
hub.stop();
hub = null;
super.tearDown();
}
public void testTrackListen() {
Capture<ContentObserver> observerCapture = new Capture<ContentObserver>();
Track track = new Track();
prefs.edit().putLong("recordingTrack", TRACK_ID)
.putLong("selectedTrack", TRACK_ID).apply();
expect(providerUtils.getTrack(TRACK_ID)).andStubReturn(track);
expectStart();
dataSources.registerContentObserver(
eq(TracksColumns.CONTENT_URI), eq(false), capture(observerCapture));
// Expect the initial loading.
// Both listeners (registered before and after start) should get the same data.
listener1.onTrackUpdated(track);
listener2.onTrackUpdated(track);
replay();
hub.registerTrackDataListener(listener1, EnumSet.of(ListenerDataType.TRACK_UPDATES));
hub.start();
hub.registerTrackDataListener(listener2, EnumSet.of(ListenerDataType.TRACK_UPDATES));
verifyAndReset();
ContentObserver observer = observerCapture.getValue();
expect(providerUtils.getTrack(TRACK_ID)).andStubReturn(track);
// Now expect an update.
listener1.onTrackUpdated(track);
listener2.onTrackUpdated(track);
replay();
observer.onChange(false);
verifyAndReset();
// Unregister one, get another update.
expect(providerUtils.getTrack(TRACK_ID)).andStubReturn(track);
listener2.onTrackUpdated(track);
replay();
hub.unregisterTrackDataListener(listener1);
observer.onChange(false);
verifyAndReset();
// Unregister the other, expect internal unregistration
dataSources.unregisterContentObserver(observer);
replay();
hub.unregisterTrackDataListener(listener2);
observer.onChange(false);
verifyAndReset();
}
private static class FixedSizeCursorAnswer implements IAnswer<Cursor> {
private final int size;
public FixedSizeCursorAnswer(int size) {
this.size = size;
}
@Override
public Cursor answer() throws Throwable {
MatrixCursor cursor = new MatrixCursor(new String[] { BaseColumns._ID });
for (long i = 1; i <= size; i++) {
cursor.addRow(new Object[] { i });
}
return cursor;
}
}
private static class FixedSizeLocationIterator implements LocationIterator {
private final long startId;
private final Location[] locs;
private final Set<Integer> splitIndexSet = new HashSet<Integer>();
private int currentIdx = -1;
public FixedSizeLocationIterator(long startId, int size) {
this(startId, size, null);
}
public FixedSizeLocationIterator(long startId, int size, int... splitIndices) {
this.startId = startId;
this.locs = new Location[size];
for (int i = 0; i < size; i++) {
Location loc = new Location("gps");
loc.setLatitude(-15.0 + i / 1000.0);
loc.setLongitude(37 + i / 1000.0);
loc.setAltitude(i);
locs[i] = loc;
}
if (splitIndices != null) {
for (int splitIdx : splitIndices) {
splitIndexSet.add(splitIdx);
Location splitLoc = locs[splitIdx];
splitLoc.setLatitude(100.0);
splitLoc.setLongitude(200.0);
}
}
}
public void expectLocationsDelivered(TrackDataListener listener) {
for (int i = 0; i < locs.length; i++) {
if (splitIndexSet.contains(i)) {
listener.onSegmentSplit();
} else {
listener.onNewTrackPoint(locs[i]);
}
}
}
public void expectSampledLocationsDelivered(
TrackDataListener listener, int sampleFrequency, boolean includeSampledOut) {
for (int i = 0; i < locs.length; i++) {
if (splitIndexSet.contains(i)) {
listener.onSegmentSplit();
} else if (i % sampleFrequency == 0) {
listener.onNewTrackPoint(locs[i]);
} else if (includeSampledOut) {
listener.onSampledOutTrackPoint(locs[i]);
}
}
}
@Override
public boolean hasNext() {
return currentIdx < (locs.length - 1);
}
@Override
public Location next() {
currentIdx++;
return locs[currentIdx];
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
@Override
public long getLocationId() {
return startId + currentIdx;
}
@Override
public void close() {
// Do nothing
}
}
public void testWaypointListen() {
Capture<ContentObserver> observerCapture = new Capture<ContentObserver>();
prefs.edit().putLong("recordingTrack", TRACK_ID)
.putLong("selectedTrack", TRACK_ID).apply();
Waypoint wpt1 = new Waypoint(),
wpt2 = new Waypoint(),
wpt3 = new Waypoint(),
wpt4 = new Waypoint();
Location loc = new Location("gps");
loc.setLatitude(10.0);
loc.setLongitude(8.0);
wpt1.setLocation(loc);
wpt2.setLocation(loc);
wpt3.setLocation(loc);
wpt4.setLocation(loc);
expect(providerUtils.getWaypointsCursor(
eq(TRACK_ID), leq(0L), eq(Constants.MAX_DISPLAYED_WAYPOINTS_POINTS)))
.andStubAnswer(new FixedSizeCursorAnswer(2));
expect(providerUtils.createWaypoint(isA(Cursor.class)))
.andReturn(wpt1)
.andReturn(wpt2)
.andReturn(wpt1)
.andReturn(wpt2);
expectStart();
dataSources.registerContentObserver(
eq(WaypointsColumns.CONTENT_URI), eq(false), capture(observerCapture));
// Expect the initial loading.
// Both listeners (registered before and after start) should get the same data.
listener1.clearWaypoints();
listener1.onNewWaypoint(wpt1);
listener1.onNewWaypoint(wpt2);
listener1.onNewWaypointsDone();
listener2.clearWaypoints();
listener2.onNewWaypoint(wpt1);
listener2.onNewWaypoint(wpt2);
listener2.onNewWaypointsDone();
replay();
hub.registerTrackDataListener(listener1, EnumSet.of(ListenerDataType.WAYPOINT_UPDATES));
hub.start();
hub.registerTrackDataListener(listener2, EnumSet.of(ListenerDataType.WAYPOINT_UPDATES));
verifyAndReset();
ContentObserver observer = observerCapture.getValue();
expect(providerUtils.getWaypointsCursor(
eq(TRACK_ID), leq(0L), eq(Constants.MAX_DISPLAYED_WAYPOINTS_POINTS)))
.andStubAnswer(new FixedSizeCursorAnswer(3));
expect(providerUtils.createWaypoint(isA(Cursor.class)))
.andReturn(wpt1)
.andReturn(wpt2)
.andReturn(wpt3);
// Now expect an update.
listener1.clearWaypoints();
listener2.clearWaypoints();
listener1.onNewWaypoint(wpt1);
listener2.onNewWaypoint(wpt1);
listener1.onNewWaypoint(wpt2);
listener2.onNewWaypoint(wpt2);
listener1.onNewWaypoint(wpt3);
listener2.onNewWaypoint(wpt3);
listener1.onNewWaypointsDone();
listener2.onNewWaypointsDone();
replay();
observer.onChange(false);
verifyAndReset();
// Unregister one, get another update.
expect(providerUtils.getWaypointsCursor(
eq(TRACK_ID), leq(0L), eq(Constants.MAX_DISPLAYED_WAYPOINTS_POINTS)))
.andStubAnswer(new FixedSizeCursorAnswer(4));
expect(providerUtils.createWaypoint(isA(Cursor.class)))
.andReturn(wpt1)
.andReturn(wpt2)
.andReturn(wpt3)
.andReturn(wpt4);
// Now expect an update.
listener2.clearWaypoints();
listener2.onNewWaypoint(wpt1);
listener2.onNewWaypoint(wpt2);
listener2.onNewWaypoint(wpt3);
listener2.onNewWaypoint(wpt4);
listener2.onNewWaypointsDone();
replay();
hub.unregisterTrackDataListener(listener1);
observer.onChange(false);
verifyAndReset();
// Unregister the other, expect internal unregistration
dataSources.unregisterContentObserver(observer);
replay();
hub.unregisterTrackDataListener(listener2);
observer.onChange(false);
verifyAndReset();
}
public void testPointsListen() {
Capture<ContentObserver> observerCapture = new Capture<ContentObserver>();
prefs.edit().putLong("recordingTrack", TRACK_ID)
.putLong("selectedTrack", TRACK_ID).apply();
expectStart();
dataSources.registerContentObserver(
eq(TrackPointsColumns.CONTENT_URI), eq(false), capture(observerCapture));
FixedSizeLocationIterator locationIterator = new FixedSizeLocationIterator(1, 10, 5);
expect(providerUtils.getLocationIterator(
eq(TRACK_ID), eq(0L), eq(false), isA(LocationFactory.class)))
.andReturn(locationIterator);
expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(10L);
listener1.clearTrackPoints();
locationIterator.expectLocationsDelivered(listener1);
listener1.onNewTrackPointsDone();
replay();
hub.start();
hub.registerTrackDataListener(listener1, EnumSet.of(ListenerDataType.POINT_UPDATES));
verifyAndReset();
// Register a second listener - it will get the same points as the previous one
locationIterator = new FixedSizeLocationIterator(1, 10, 5);
expect(providerUtils.getLocationIterator(
eq(TRACK_ID), eq(0L), eq(false), isA(LocationFactory.class)))
.andReturn(locationIterator);
expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(10L);
listener2.clearTrackPoints();
locationIterator.expectLocationsDelivered(listener2);
listener2.onNewTrackPointsDone();
replay();
hub.start();
hub.registerTrackDataListener(listener2, EnumSet.of(ListenerDataType.POINT_UPDATES));
verifyAndReset();
// Deliver more points - should go to both listeners, without clearing.
ContentObserver observer = observerCapture.getValue();
locationIterator = new FixedSizeLocationIterator(11, 10, 1);
expect(providerUtils.getLocationIterator(
eq(TRACK_ID), eq(11L), eq(false), isA(LocationFactory.class)))
.andReturn(locationIterator);
expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(20L);
locationIterator.expectLocationsDelivered(listener1);
locationIterator.expectLocationsDelivered(listener2);
listener1.onNewTrackPointsDone();
listener2.onNewTrackPointsDone();
replay();
observer.onChange(false);
verifyAndReset();
// Unregister listener1, switch tracks to ensure data is cleared/reloaded.
locationIterator = new FixedSizeLocationIterator(101, 10);
expect(providerUtils.getLocationIterator(
eq(TRACK_ID + 1), eq(0L), eq(false), isA(LocationFactory.class)))
.andReturn(locationIterator);
expect(providerUtils.getLastLocationId(TRACK_ID + 1)).andReturn(110L);
listener2.clearTrackPoints();
locationIterator.expectLocationsDelivered(listener2);
listener2.onNewTrackPointsDone();
replay();
hub.unregisterTrackDataListener(listener1);
hub.loadTrack(TRACK_ID + 1);
verifyAndReset();
}
public void testPointsListen_beforeStart() {
}
public void testPointsListen_reRegister() {
Capture<ContentObserver> observerCapture = new Capture<ContentObserver>();
prefs.edit().putLong("recordingTrack", TRACK_ID)
.putLong("selectedTrack", TRACK_ID).apply();
expectStart();
dataSources.registerContentObserver(
eq(TrackPointsColumns.CONTENT_URI), eq(false), capture(observerCapture));
FixedSizeLocationIterator locationIterator = new FixedSizeLocationIterator(1, 10, 5);
expect(providerUtils.getLocationIterator(
eq(TRACK_ID), eq(0L), eq(false), isA(LocationFactory.class)))
.andReturn(locationIterator);
expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(10L);
listener1.clearTrackPoints();
locationIterator.expectLocationsDelivered(listener1);
listener1.onNewTrackPointsDone();
replay();
hub.start();
hub.registerTrackDataListener(listener1, EnumSet.of(ListenerDataType.POINT_UPDATES));
verifyAndReset();
// Unregister
ContentObserver observer = observerCapture.getValue();
dataSources.unregisterContentObserver(observer);
replay();
hub.unregisterTrackDataListener(listener1);
verifyAndReset();
// Register again, except only points since unregistered.
dataSources.registerContentObserver(
eq(TrackPointsColumns.CONTENT_URI), eq(false), capture(observerCapture));
locationIterator = new FixedSizeLocationIterator(11, 10);
expect(providerUtils.getLocationIterator(
eq(TRACK_ID), eq(11L), eq(false), isA(LocationFactory.class)))
.andReturn(locationIterator);
expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(20L);
locationIterator.expectLocationsDelivered(listener1);
listener1.onNewTrackPointsDone();
replay();
hub.registerTrackDataListener(listener1, EnumSet.of(ListenerDataType.POINT_UPDATES));
verifyAndReset();
// Deliver more points - should still be incremental.
locationIterator = new FixedSizeLocationIterator(21, 10, 1);
expect(providerUtils.getLocationIterator(
eq(TRACK_ID), eq(21L), eq(false), isA(LocationFactory.class)))
.andReturn(locationIterator);
expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(30L);
locationIterator.expectLocationsDelivered(listener1);
listener1.onNewTrackPointsDone();
replay();
observer.onChange(false);
verifyAndReset();
}
public void testPointsListen_reRegisterTrackChanged() {
Capture<ContentObserver> observerCapture = new Capture<ContentObserver>();
prefs.edit().putLong("recordingTrack", TRACK_ID)
.putLong("selectedTrack", TRACK_ID).apply();
expectStart();
dataSources.registerContentObserver(
eq(TrackPointsColumns.CONTENT_URI), eq(false), capture(observerCapture));
FixedSizeLocationIterator locationIterator = new FixedSizeLocationIterator(1, 10, 5);
expect(providerUtils.getLocationIterator(
eq(TRACK_ID), eq(0L), eq(false), isA(LocationFactory.class)))
.andReturn(locationIterator);
expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(10L);
listener1.clearTrackPoints();
locationIterator.expectLocationsDelivered(listener1);
listener1.onNewTrackPointsDone();
replay();
hub.start();
hub.registerTrackDataListener(listener1, EnumSet.of(ListenerDataType.POINT_UPDATES));
verifyAndReset();
// Unregister
ContentObserver observer = observerCapture.getValue();
dataSources.unregisterContentObserver(observer);
replay();
hub.unregisterTrackDataListener(listener1);
verifyAndReset();
// Register again after track changed, expect all points.
dataSources.registerContentObserver(
eq(TrackPointsColumns.CONTENT_URI), eq(false), capture(observerCapture));
locationIterator = new FixedSizeLocationIterator(1, 10);
expect(providerUtils.getLocationIterator(
eq(TRACK_ID + 1), eq(0L), eq(false), isA(LocationFactory.class)))
.andReturn(locationIterator);
expect(providerUtils.getLastLocationId(TRACK_ID + 1)).andReturn(10L);
listener1.clearTrackPoints();
locationIterator.expectLocationsDelivered(listener1);
listener1.onNewTrackPointsDone();
replay();
hub.loadTrack(TRACK_ID + 1);
hub.registerTrackDataListener(listener1, EnumSet.of(ListenerDataType.POINT_UPDATES));
verifyAndReset();
}
public void testPointsListen_largeTrackSampling() {
Capture<ContentObserver> observerCapture = new Capture<ContentObserver>();
prefs.edit().putLong("recordingTrack", TRACK_ID)
.putLong("selectedTrack", TRACK_ID).apply();
expectStart();
dataSources.registerContentObserver(
eq(TrackPointsColumns.CONTENT_URI), eq(false), capture(observerCapture));
FixedSizeLocationIterator locationIterator = new FixedSizeLocationIterator(1, 200, 4, 25, 71, 120);
expect(providerUtils.getLocationIterator(
eq(TRACK_ID), eq(0L), eq(false), isA(LocationFactory.class)))
.andReturn(locationIterator);
expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(200L);
listener1.clearTrackPoints();
listener2.clearTrackPoints();
locationIterator.expectSampledLocationsDelivered(listener1, 4, false);
locationIterator.expectSampledLocationsDelivered(listener2, 4, true);
listener1.onNewTrackPointsDone();
listener2.onNewTrackPointsDone();
replay();
hub.registerTrackDataListener(listener1,
EnumSet.of(ListenerDataType.POINT_UPDATES));
hub.registerTrackDataListener(listener2,
EnumSet.of(ListenerDataType.POINT_UPDATES, ListenerDataType.SAMPLED_OUT_POINT_UPDATES));
hub.start();
verifyAndReset();
}
public void testPointsListen_resampling() {
Capture<ContentObserver> observerCapture = new Capture<ContentObserver>();
prefs.edit().putLong("recordingTrack", TRACK_ID)
.putLong("selectedTrack", TRACK_ID).apply();
expectStart();
dataSources.registerContentObserver(
eq(TrackPointsColumns.CONTENT_URI), eq(false), capture(observerCapture));
// Deliver 30 points (no sampling happens)
FixedSizeLocationIterator locationIterator = new FixedSizeLocationIterator(1, 30, 5);
expect(providerUtils.getLocationIterator(
eq(TRACK_ID), eq(0L), eq(false), isA(LocationFactory.class)))
.andReturn(locationIterator);
expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(30L);
listener1.clearTrackPoints();
locationIterator.expectLocationsDelivered(listener1);
listener1.onNewTrackPointsDone();
replay();
hub.start();
hub.registerTrackDataListener(listener1, EnumSet.of(ListenerDataType.POINT_UPDATES));
verifyAndReset();
// Now deliver 30 more (incrementally sampled)
ContentObserver observer = observerCapture.getValue();
locationIterator = new FixedSizeLocationIterator(31, 30);
expect(providerUtils.getLocationIterator(
eq(TRACK_ID), eq(31L), eq(false), isA(LocationFactory.class)))
.andReturn(locationIterator);
expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(60L);
locationIterator.expectSampledLocationsDelivered(listener1, 2, false);
listener1.onNewTrackPointsDone();
replay();
observer.onChange(false);
verifyAndReset();
// Now another 30 (triggers resampling)
locationIterator = new FixedSizeLocationIterator(1, 90);
expect(providerUtils.getLocationIterator(
eq(TRACK_ID), eq(0L), eq(false), isA(LocationFactory.class)))
.andReturn(locationIterator);
expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(90L);
listener1.clearTrackPoints();
locationIterator.expectSampledLocationsDelivered(listener1, 2, false);
listener1.onNewTrackPointsDone();
replay();
observer.onChange(false);
verifyAndReset();
}
public void testLocationListen() {
// TODO
}
public void testCompassListen() throws Exception {
AndroidMock.resetToDefault(listener1);
Sensor compass = newSensor();
expect(dataSources.getSensor(Sensor.TYPE_ORIENTATION)).andReturn(compass);
Capture<SensorEventListener> listenerCapture = new Capture<SensorEventListener>();
dataSources.registerSensorListener(capture(listenerCapture), same(compass), anyInt());
Capture<LocationListener> locationListenerCapture = new Capture<LocationListener>();
dataSources.requestLocationUpdates(capture(locationListenerCapture));
SensorEvent event = newSensorEvent();
event.sensor = compass;
// First, get a dummy heading update.
listener1.onCurrentHeadingChanged(0.0);
// Then, get a heading update without a known location (thus can't calculate declination).
listener1.onCurrentHeadingChanged(42.0f);
// Also expect location updates which are not relevant to us.
listener1.onProviderStateChange(isA(ProviderState.class));
AndroidMock.expectLastCall().anyTimes();
replay();
hub.registerTrackDataListener(listener1,
EnumSet.of(ListenerDataType.COMPASS_UPDATES, ListenerDataType.LOCATION_UPDATES));
hub.start();
SensorEventListener sensorListener = listenerCapture.getValue();
LocationListener locationListener = locationListenerCapture.getValue();
event.values[0] = 42.0f;
sensorListener.onSensorChanged(event);
verifyAndReset();
// Expect the heading update to include declination.
listener1.onCurrentHeadingChanged(52.0);
// Also expect location updates which are not relevant to us.
listener1.onProviderStateChange(isA(ProviderState.class));
AndroidMock.expectLastCall().anyTimes();
listener1.onCurrentLocationChanged(isA(Location.class));
AndroidMock.expectLastCall().anyTimes();
replay();
// Now try injecting a location update, triggering a declination update.
Location location = new Location("gps");
location.setLatitude(10.0);
location.setLongitude(20.0);
location.setAltitude(30.0);
declination = 10.0f;
locationListener.onLocationChanged(location);
sensorListener.onSensorChanged(event);
verifyAndReset();
listener1.onCurrentHeadingChanged(52.0);
replay();
// Now try changing the known declination - it should still return the old declination, since
// updates only happen sparsely.
declination = 20.0f;
sensorListener.onSensorChanged(event);
verifyAndReset();
}
private Sensor newSensor() throws Exception {
Constructor<Sensor> constructor = Sensor.class.getDeclaredConstructor();
constructor.setAccessible(true);
return constructor.newInstance();
}
private SensorEvent newSensorEvent() throws Exception {
Constructor<SensorEvent> constructor = SensorEvent.class.getDeclaredConstructor(int.class);
constructor.setAccessible(true);
return constructor.newInstance(3);
}
public void testDisplayPreferencesListen() throws Exception {
String metricUnitsKey = context.getString(R.string.metric_units_key);
String speedKey = context.getString(R.string.report_speed_key);
prefs.edit()
.putBoolean(metricUnitsKey, true)
.putBoolean(speedKey, true)
.apply();
Capture<OnSharedPreferenceChangeListener> listenerCapture =
new Capture<OnSharedPreferenceChangeListener>();
dataSources.registerOnSharedPreferenceChangeListener(capture(listenerCapture));
expect(listener1.onUnitsChanged(true)).andReturn(false);
expect(listener2.onUnitsChanged(true)).andReturn(false);
expect(listener1.onReportSpeedChanged(true)).andReturn(false);
expect(listener2.onReportSpeedChanged(true)).andReturn(false);
replay();
hub.registerTrackDataListener(listener1, EnumSet.of(ListenerDataType.DISPLAY_PREFERENCES));
hub.start();
hub.registerTrackDataListener(listener2, EnumSet.of(ListenerDataType.DISPLAY_PREFERENCES));
verifyAndReset();
expect(listener1.onReportSpeedChanged(false)).andReturn(false);
expect(listener2.onReportSpeedChanged(false)).andReturn(false);
replay();
prefs.edit()
.putBoolean(speedKey, false)
.apply();
OnSharedPreferenceChangeListener listener = listenerCapture.getValue();
listener.onSharedPreferenceChanged(prefs, speedKey);
AndroidMock.verify(dataSources, providerUtils, listener1, listener2);
AndroidMock.reset(dataSources, providerUtils, listener1, listener2);
expect(listener1.onUnitsChanged(false)).andReturn(false);
expect(listener2.onUnitsChanged(false)).andReturn(false);
replay();
prefs.edit()
.putBoolean(metricUnitsKey, false)
.apply();
listener.onSharedPreferenceChanged(prefs, metricUnitsKey);
verifyAndReset();
}
private void expectStart() {
dataSources.registerOnSharedPreferenceChangeListener(capture(preferenceListenerCapture));
}
private void replay() {
AndroidMock.replay(dataSources, providerUtils, listener1, listener2);
}
private void verifyAndReset() {
AndroidMock.verify(listener1, listener2, dataSources, providerUtils);
AndroidMock.reset(listener1, listener2, dataSources, providerUtils);
}
}
| Java |
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks;
import android.graphics.Path;
import android.graphics.PointF;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import junit.framework.Assert;
/**
* Elements for Tests for the MyTracks map overlay.
*
* @author Bartlomiej Niechwiej
* @author Vangelis S.
*
* A mock class that intercepts {@code Path}'s and records calls to
* {@code #moveTo()} and {@code #lineTo()}.
*/
public class MockPath extends Path {
/** A list of disjoined path segments. */
public final List<List<PointF>> segments = new LinkedList<List<PointF>>();
/** The total number of points in this path. */
public int totalPoints;
private List<PointF> currentSegment;
@Override
public void lineTo(float x, float y) {
super.lineTo(x, y);
Assert.assertNotNull(currentSegment);
currentSegment.add(new PointF(x, y));
totalPoints++;
}
@Override
public void moveTo(float x, float y) {
super.moveTo(x, y);
segments.add(currentSegment =
new ArrayList<PointF>(Arrays.asList(new PointF(x, y))));
totalPoints++;
}
} | Java |
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.Projection;
import android.graphics.Point;
/**
* Elements for Tests for the MyTracks map overlay.
*
* @author Bartlomiej Niechwiej
* @author Vangelis S.
*
* A mock {@code Projection} that acts as the identity matrix.
*/
public class MockProjection implements Projection {
@Override
public Point toPixels(GeoPoint in, Point out) {
return out;
}
@Override
public float metersToEquatorPixels(float meters) {
return meters;
}
@Override
public GeoPoint fromPixels(int x, int y) {
return new GeoPoint(y, x);
}
} | Java |
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.maps;
import android.location.Location;
/**
* Tests for the MyTracks track path descriptors and painters.
*
* @author Vangelis S.
*/
public class TrackPathDescriptorDynamicSpeedTest extends TrackPathPainterTestCase {
public void testDynamicSpeedTrackPathDescriptor() throws Exception {
Location location = new Location("gps");
location.setLatitude(10);
for (int i = 0; i < 100; ++i) {
location = new Location("gps");
location.setLatitude(20 + i / 2);
location.setLongitude(150 - i);
myTracksOverlay.addLocation(location);
}
TrackPathPainter painter = new DynamicSpeedTrackPathPainter(
getContext(), new DynamicSpeedTrackPathDescriptor(getContext()));
myTracksOverlay.setTrackPathPainter(painter);
int startLocationIdx = 0;
Boolean alwaysVisible = true;
assertNotNull(painter);
painter.updatePath(myTracksOverlay.getMapProjection(mockView),
myTracksOverlay.getMapViewRect(mockView), startLocationIdx, alwaysVisible,
myTracksOverlay.getPoints());
assertNotNull(myTracksOverlay.getTrackPathPainter().getLastPath());
painter.drawTrack(canvas);
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.maps;
import com.google.android.apps.mytracks.Constants;
import com.google.android.maps.mytracks.R;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.test.AndroidTestCase;
/**
* Tests for the {@link DynamicSpeedTrackPathDescriptor}.
*
* @author Youtao Liu
*/
public class DynamicSpeedTrackPathDescriptorTest extends AndroidTestCase {
private Context context;
private SharedPreferences sharedPreferences;
private Editor sharedPreferencesEditor;
@Override
protected void setUp() throws Exception {
super.setUp();
context = getContext();
sharedPreferences = context.getSharedPreferences(Constants.SETTINGS_NAME, Context.MODE_PRIVATE);
sharedPreferencesEditor = sharedPreferences.edit();
}
/**
* Tests the method {@link DynamicSpeedTrackPathDescriptor#getSpeedMargin()}
* with zero, normal and illegal value.
*/
public void testGetSpeedMargin() {
String[] actuals = { "0", "50", "99", "" };
// The default value of speedMargin is 25.
int[] expectations = { 0, 50, 99, 25 };
// Test
for (int i = 0; i < expectations.length; i++) {
sharedPreferencesEditor.putString(
context.getString(R.string.track_color_mode_dynamic_speed_variation_key), actuals[i]);
sharedPreferencesEditor.commit();
DynamicSpeedTrackPathDescriptor dynamicSpeedTrackPathDescriptor = new DynamicSpeedTrackPathDescriptor(
context);
assertEquals(expectations[i],
dynamicSpeedTrackPathDescriptor.getSpeedMargin(sharedPreferences));
}
}
/**
* Tests {@link
* DynamicSpeedTrackPathDescriptor#onSharedPreferenceChanged(SharedPreferences,
* String)} when the key is null.
*/
public void testOnSharedPreferenceChanged_nullKey() {
DynamicSpeedTrackPathDescriptor dynamicSpeedTrackPathDescriptor = new DynamicSpeedTrackPathDescriptor(
context);
int speedMargin = dynamicSpeedTrackPathDescriptor.getSpeedMargin(sharedPreferences);
// Change value in shared preferences.
sharedPreferencesEditor.putString(
context.getString(R.string.track_color_mode_dynamic_speed_variation_key),
Integer.toString(speedMargin + 2));
sharedPreferencesEditor.commit();
dynamicSpeedTrackPathDescriptor.onSharedPreferenceChanged(sharedPreferences, null);
assertEquals(speedMargin, dynamicSpeedTrackPathDescriptor.getSpeedMargin());
}
/**
* Tests {@link
* DynamicSpeedTrackPathDescriptor#onSharedPreferenceChanged(SharedPreferences,
* String)} when the key is not null, and not trackColorModeDynamicVariation.
*/
public void testOnSharedPreferenceChanged_otherKey() {
DynamicSpeedTrackPathDescriptor dynamicSpeedTrackPathDescriptor = new DynamicSpeedTrackPathDescriptor(
context);
int speedMargin = dynamicSpeedTrackPathDescriptor.getSpeedMargin(sharedPreferences);
// Change value in shared preferences.
sharedPreferencesEditor.putString(
context.getString(R.string.track_color_mode_dynamic_speed_variation_key),
Integer.toString(speedMargin + 2));
sharedPreferencesEditor.commit();
dynamicSpeedTrackPathDescriptor.onSharedPreferenceChanged(sharedPreferences, "anyKey");
assertEquals(speedMargin, dynamicSpeedTrackPathDescriptor.getSpeedMargin());
}
/**
* Tests {@link
* DynamicSpeedTrackPathDescriptor#onSharedPreferenceChanged(SharedPreferences,
* String)} when the key is trackColorModeDynamicVariation.
*/
public void testOnSharedPreferenceChanged_trackColorModeDynamicVariationKey() {
DynamicSpeedTrackPathDescriptor dynamicSpeedTrackPathDescriptor = new DynamicSpeedTrackPathDescriptor(
context);
int speedMargin = dynamicSpeedTrackPathDescriptor.getSpeedMargin(sharedPreferences);
// Change value in shared preferences.
sharedPreferencesEditor.putString(
"trackColorModeDynamicVariation",
Integer.toString(speedMargin + 2));
sharedPreferencesEditor.commit();
dynamicSpeedTrackPathDescriptor.onSharedPreferenceChanged(sharedPreferences,
"trackColorModeDynamicVariation");
assertEquals(speedMargin + 2, dynamicSpeedTrackPathDescriptor.getSpeedMargin());
}
/**
* Tests {@link
* DynamicSpeedTrackPathDescriptor#onSharedPreferenceChanged(SharedPreferences,
* String)} when the values of speedMargin is "".
*/
public void testOnSharedPreferenceChanged_emptyValue() {
DynamicSpeedTrackPathDescriptor dynamicSpeedTrackPathDescriptor = new DynamicSpeedTrackPathDescriptor(
context);
// Change value in shared preferences
sharedPreferencesEditor.putString(
context.getString(R.string.track_color_mode_dynamic_speed_variation_key), "");
sharedPreferencesEditor.commit();
dynamicSpeedTrackPathDescriptor.onSharedPreferenceChanged(sharedPreferences,
context.getString(R.string.track_color_mode_dynamic_speed_variation_key));
// The default value of speedMargin is 25.
assertEquals(25, dynamicSpeedTrackPathDescriptor.getSpeedMargin());
}
/**
* Tests {@link DynamicSpeedTrackPathDescriptor#needsRedraw()} by wrong track
* id.
*/
public void testNeedsRedraw_WrongTrackId() {
long trackId = -1;
sharedPreferencesEditor.putLong(context.getString(R.string.selected_track_key), trackId);
sharedPreferencesEditor.commit();
DynamicSpeedTrackPathDescriptor dynamicSpeedTrackPathDescriptor = new DynamicSpeedTrackPathDescriptor(
context);
assertEquals(false, dynamicSpeedTrackPathDescriptor.needsRedraw());
}
/**
* Tests {@link DynamicSpeedTrackPathDescriptor#needsRedraw()} by different
* averageMovingSpeed.
*/
public void testIsDiffereceSignificant() {
DynamicSpeedTrackPathDescriptor dynamicSpeedTrackPathDescriptor = new DynamicSpeedTrackPathDescriptor(
context);
double[] averageMovingSpeeds = { 0, 30, 30, 30 };
double[] newAverageMovingSpeed = { 20, 30,
// Difference is less than CRITICAL_DIFFERENCE_PERCENTAGE
30 * (1 + (DynamicSpeedTrackPathDescriptor.CRITICAL_DIFFERENCE_PERCENTAGE / 100) / 2),
// Difference is more than CRITICAL_DIFFERENCE_PERCENTAGE
30 * (1 + (DynamicSpeedTrackPathDescriptor.CRITICAL_DIFFERENCE_PERCENTAGE / 100.00) * 2) };
boolean[] expectedValues = { true, false, false, true };
double[] expectedAverageMovingSpeed = { 20, 30, 30,
30 * (1 + (DynamicSpeedTrackPathDescriptor.CRITICAL_DIFFERENCE_PERCENTAGE / 100.00) * 2) };
// Test
for (int i = 0; i < newAverageMovingSpeed.length; i++) {
dynamicSpeedTrackPathDescriptor.setAverageMovingSpeed(averageMovingSpeeds[i]);
assertEquals(expectedValues[i], dynamicSpeedTrackPathDescriptor.isDifferenceSignificant(
averageMovingSpeeds[i], newAverageMovingSpeed[i]));
assertEquals(expectedAverageMovingSpeed[i],
dynamicSpeedTrackPathDescriptor.getAverageMovingSpeed());
}
}
} | Java |
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.maps;
import android.location.Location;
/**
* Tests for the MyTracks track path descriptors and painters.
*
* @author Vangelis S.
*/
public class TrackPathDescriptorFixedSpeedTest extends TrackPathPainterTestCase {
public void testFixedSpeedTrackPathDescriptor() throws Exception {
Location location = new Location("gps");
location.setLatitude(10);
for (int i = 0; i < 100; ++i) {
location = new Location("gps");
location.setLatitude(20 + i / 2);
location.setLongitude(150 - i);
myTracksOverlay.addLocation(location);
}
TrackPathPainter painter = new DynamicSpeedTrackPathPainter(
getContext(), new FixedSpeedTrackPathDescriptor(getContext()));
myTracksOverlay.setTrackPathPainter(painter);
int startLocationIdx = 0;
Boolean alwaysVisible = true;
assertNotNull(painter);
painter.updatePath(myTracksOverlay.getMapProjection(mockView),
myTracksOverlay.getMapViewRect(mockView), startLocationIdx, alwaysVisible,
myTracksOverlay.getPoints());
assertNotNull(myTracksOverlay.getTrackPathPainter().getLastPath());
painter.drawTrack(canvas);
}
}
| Java |
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.maps;
import android.location.Location;
/**
* Tests for the MyTracks track path descriptors and painters.
*
* @author Vangelis S.
*/
public class TrackPathPainterSingleColorTest extends TrackPathPainterTestCase {
public void testSimpeColorTrackPathPainter() throws Exception {
Location location = new Location("gps");
location.setLatitude(10);
for (int i = 0; i < 100; ++i) {
location = new Location("gps");
location.setLatitude(20 + i / 2);
location.setLongitude(150 - i);
myTracksOverlay.addLocation(location);
}
TrackPathPainter painter = new SingleColorTrackPathPainter(getContext());
myTracksOverlay.setTrackPathPainter(painter);
int startLocationIdx = 0;
Boolean alwaysVisible = true;
assertNotNull(painter);
painter.updatePath(myTracksOverlay.getMapProjection(mockView),
myTracksOverlay.getMapViewRect(mockView), startLocationIdx, alwaysVisible,
myTracksOverlay.getPoints());
assertNotNull(myTracksOverlay.getTrackPathPainter().getLastPath());
painter.drawTrack(canvas);
}
}
| Java |
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.maps;
import com.google.android.apps.mytracks.MockMyTracksOverlay;
import com.google.android.maps.MapView;
import android.graphics.Canvas;
import android.test.AndroidTestCase;
/**
* Tests for the MyTracks track path descriptors and painters.
*
* @author Vangelis S.
*/
public class TrackPathPainterTestCase extends AndroidTestCase {
protected Canvas canvas;
protected MockMyTracksOverlay myTracksOverlay;
protected MapView mockView;
@Override
protected void setUp() throws Exception {
super.setUp();
canvas = new Canvas();
myTracksOverlay = new MockMyTracksOverlay(getContext());
// Enable drawing.
myTracksOverlay.setTrackDrawingEnabled(true);
mockView = null;
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.maps;
import com.google.android.apps.mytracks.Constants;
import com.google.android.maps.mytracks.R;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.test.AndroidTestCase;
/**
* Tests for the {@link DynamicSpeedTrackPathDescriptor}.
*
* @author Youtao Liu
*/
public class FixedSpeedTrackPathDescriptorTest extends AndroidTestCase {
private Context context;
private SharedPreferences sharedPreferences;
private Editor sharedPreferencesEditor;
private int slowDefault;
private int normalDefault;
@Override
protected void setUp() throws Exception {
super.setUp();
context = getContext();
sharedPreferences = context.getSharedPreferences(Constants.SETTINGS_NAME, Context.MODE_PRIVATE);
sharedPreferencesEditor = sharedPreferences.edit();
// Get the default value
slowDefault = 9;
normalDefault = 15;
}
/**
* Tests the initialization of slowSpeed and normalSpeed in {@link
* DynamicSpeedTrackPathDescriptor#DynamicSpeedTrackPathDescriptor(Context)}.
*/
public void testConstructor() {
String[] slowSpeedsInShPre = { "0", "1", "99", "" };
int[] slowSpeedExpectations = { 0, 1, 99, slowDefault };
String[] normalSpeedsInShPre = { "0", "1", "99", "" };
int[] normalSpeedExpectations = { 0, 1, 99, normalDefault };
for (int i = 0; i < slowSpeedsInShPre.length; i++) {
sharedPreferencesEditor.putString(
context.getString(R.string.track_color_mode_fixed_speed_slow_key), slowSpeedsInShPre[i]);
sharedPreferencesEditor.putString(
context.getString(R.string.track_color_mode_fixed_speed_medium_key),
normalSpeedsInShPre[i]);
sharedPreferencesEditor.commit();
FixedSpeedTrackPathDescriptor fixedSpeedTrackPathDescriptor = new FixedSpeedTrackPathDescriptor(
context);
assertEquals(slowSpeedExpectations[i], fixedSpeedTrackPathDescriptor.getSlowSpeed());
assertEquals(normalSpeedExpectations[i], fixedSpeedTrackPathDescriptor.getNormalSpeed());
}
}
/**
* Tests {@link
* DynamicSpeedTrackPathDescriptor#onSharedPreferenceChanged(SharedPreferences,
* String)} when the key is null.
*/
public void testOnSharedPreferenceChanged_null_key() {
FixedSpeedTrackPathDescriptor fixedSpeedTrackPathDescriptor = new FixedSpeedTrackPathDescriptor(
context);
int slowSpeed = fixedSpeedTrackPathDescriptor.getSlowSpeed();
int normalSpeed = fixedSpeedTrackPathDescriptor.getNormalSpeed();
// Change value in shared preferences
sharedPreferencesEditor.putString(
context.getString(R.string.track_color_mode_fixed_speed_slow_key),
Integer.toString(slowSpeed + 2));
sharedPreferencesEditor.putString(
context.getString(R.string.track_color_mode_fixed_speed_medium_key),
Integer.toString(normalSpeed + 2));
sharedPreferencesEditor.commit();
fixedSpeedTrackPathDescriptor.onSharedPreferenceChanged(sharedPreferences, null);
assertEquals(slowSpeed, fixedSpeedTrackPathDescriptor.getSlowSpeed());
assertEquals(normalSpeed, fixedSpeedTrackPathDescriptor.getNormalSpeed());
}
/**
* Tests {@link
* DynamicSpeedTrackPathDescriptor#onSharedPreferenceChanged(SharedPreferences,
* String)} when the key is not null, and not slowSpeed and not normalSpeed.
*/
public void testOnSharedPreferenceChanged_other_key() {
FixedSpeedTrackPathDescriptor fixedSpeedTrackPathDescriptor = new FixedSpeedTrackPathDescriptor(
context);
int slowSpeed = fixedSpeedTrackPathDescriptor.getSlowSpeed();
int normalSpeed = fixedSpeedTrackPathDescriptor.getNormalSpeed();
// Change value in shared preferences
sharedPreferencesEditor.putString(
context.getString(R.string.track_color_mode_fixed_speed_slow_key),
Integer.toString(slowSpeed + 2));
sharedPreferencesEditor.putString(
context.getString(R.string.track_color_mode_fixed_speed_medium_key),
Integer.toString(normalSpeed + 2));
sharedPreferencesEditor.commit();
fixedSpeedTrackPathDescriptor.onSharedPreferenceChanged(sharedPreferences, "anyKey");
assertEquals(slowSpeed, fixedSpeedTrackPathDescriptor.getSlowSpeed());
assertEquals(normalSpeed, fixedSpeedTrackPathDescriptor.getNormalSpeed());
}
/**
* Tests {@link
* DynamicSpeedTrackPathDescriptor#onSharedPreferenceChanged(SharedPreferences,
* String)} when the key is slowSpeed.
*/
public void testOnSharedPreferenceChanged_slowSpeedKey() {
FixedSpeedTrackPathDescriptor fixedSpeedTrackPathDescriptor = new FixedSpeedTrackPathDescriptor(
context);
int slowSpeed = fixedSpeedTrackPathDescriptor.getSlowSpeed();
int normalSpeed = fixedSpeedTrackPathDescriptor.getNormalSpeed();
// Change value in shared preferences
sharedPreferencesEditor.putString(
context.getString(R.string.track_color_mode_fixed_speed_slow_key),
Integer.toString(slowSpeed + 2));
sharedPreferencesEditor.putString(
context.getString(R.string.track_color_mode_fixed_speed_medium_key),
Integer.toString(normalSpeed + 2));
sharedPreferencesEditor.commit();
fixedSpeedTrackPathDescriptor.onSharedPreferenceChanged(sharedPreferences,
context.getString(R.string.track_color_mode_fixed_speed_slow_key));
assertEquals(slowSpeed + 2, fixedSpeedTrackPathDescriptor.getSlowSpeed());
assertEquals(normalSpeed + 2, fixedSpeedTrackPathDescriptor.getNormalSpeed());
}
/**
* Tests {@link
* DynamicSpeedTrackPathDescriptor#onSharedPreferenceChanged(SharedPreferences,
* String)} when the key is normalSpeed.
*/
public void testOnSharedPreferenceChanged_normalSpeedKey() {
FixedSpeedTrackPathDescriptor fixedSpeedTrackPathDescriptor = new FixedSpeedTrackPathDescriptor(
context);
int slowSpeed = fixedSpeedTrackPathDescriptor.getSlowSpeed();
int normalSpeed = fixedSpeedTrackPathDescriptor.getNormalSpeed();
sharedPreferencesEditor.putString(
context.getString(R.string.track_color_mode_fixed_speed_slow_key),
Integer.toString(slowSpeed + 4));
sharedPreferencesEditor.putString(
context.getString(R.string.track_color_mode_fixed_speed_medium_key),
Integer.toString(normalSpeed + 4));
sharedPreferencesEditor.commit();
fixedSpeedTrackPathDescriptor.onSharedPreferenceChanged(sharedPreferences,
context.getString(R.string.track_color_mode_fixed_speed_medium_key));
assertEquals(slowSpeed + 4, fixedSpeedTrackPathDescriptor.getSlowSpeed());
assertEquals(normalSpeed + 4, fixedSpeedTrackPathDescriptor.getNormalSpeed());
}
/**
* Tests {@link
* DynamicSpeedTrackPathDescriptor#onSharedPreferenceChanged(SharedPreferences,
* String)} when the values of slowSpeed and normalSpeed in SharedPreference
* is "". In such situation, the default value should get returned.
*/
public void testOnSharedPreferenceChanged_emptyValue() {
FixedSpeedTrackPathDescriptor fixedSpeedTrackPathDescriptor = new FixedSpeedTrackPathDescriptor(
context);
sharedPreferencesEditor.putString(
context.getString(R.string.track_color_mode_fixed_speed_slow_key), "");
sharedPreferencesEditor.putString(
context.getString(R.string.track_color_mode_fixed_speed_medium_key), "");
sharedPreferencesEditor.commit();
fixedSpeedTrackPathDescriptor.onSharedPreferenceChanged(sharedPreferences,
context.getString(R.string.track_color_mode_fixed_speed_medium_key));
assertEquals(slowDefault, fixedSpeedTrackPathDescriptor.getSlowSpeed());
assertEquals(normalDefault, fixedSpeedTrackPathDescriptor.getNormalSpeed());
}
} | Java |
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.maps;
import com.google.android.apps.mytracks.Constants;
import com.google.android.maps.mytracks.R;
import android.content.Context;
import android.content.SharedPreferences;
import android.location.Location;
/**
* Tests for the MyTracks track path painter factory.
*
* @author Vangelis S.
*/
public class TrackPathPainterFactoryTest extends TrackPathPainterTestCase {
public void testTrackPathPainterFactory() throws Exception {
Location location = new Location("gps");
location.setLatitude(10);
for (int i = 0; i < 100; ++i) {
location = new Location("gps");
location.setLatitude(20 + i / 2);
location.setLongitude(150 - i);
myTracksOverlay.addLocation(location);
}
Context context = getContext();
SharedPreferences prefs = context.getSharedPreferences(
Constants.SETTINGS_NAME, Context.MODE_PRIVATE);
if (prefs == null) {
return;
}
testTrackPathPainterFactorySpecific(context, prefs, R.string.display_track_color_value_none,
SingleColorTrackPathPainter.class);
testTrackPathPainterFactorySpecific(context, prefs, R.string.display_track_color_value_fixed,
DynamicSpeedTrackPathPainter.class);
testTrackPathPainterFactorySpecific(context, prefs, R.string.display_track_color_value_dynamic,
DynamicSpeedTrackPathPainter.class);
}
private <T> void testTrackPathPainterFactorySpecific(Context context, SharedPreferences prefs,
int track_color_mode, Class <?> c) {
prefs.edit().putString(context.getString(R.string.track_color_mode_key),
context.getString(track_color_mode)).apply();
int startLocationIdx = 0;
Boolean alwaysVisible = true;
TrackPathPainter painter = TrackPathPainterFactory.getTrackPathPainter(context);
myTracksOverlay.setTrackPathPainter(painter);
assertNotNull(painter);
assertTrue(c.isInstance(painter));
painter.updatePath(myTracksOverlay.getMapProjection(mockView),
myTracksOverlay.getMapViewRect(mockView), startLocationIdx, alwaysVisible,
myTracksOverlay.getPoints());
assertNotNull(myTracksOverlay.getTrackPathPainter().getLastPath());
painter.drawTrack(canvas);
}
}
| Java |
// Copyright 2009 Google Inc. All Rights Reserved.
package com.google.android.apps.mytracks.stats;
import com.google.android.apps.mytracks.Constants;
import android.location.Location;
import junit.framework.TestCase;
/**
* Test the the function of the TripStatisticsBuilder class.
*
* @author Sandor Dornbush
*/
public class TripStatisticsBuilderTest extends TestCase {
private TripStatisticsBuilder builder = null;
@Override
protected void setUp() throws Exception {
super.setUp();
builder = new TripStatisticsBuilder(System.currentTimeMillis());
}
public void testAddLocationSimple() throws Exception {
builder = new TripStatisticsBuilder(1000);
TripStatistics stats = builder.getStatistics();
assertEquals(0.0, builder.getSmoothedElevation());
assertEquals(Double.POSITIVE_INFINITY, stats.getMinElevation());
assertEquals(Double.NEGATIVE_INFINITY, stats.getMaxElevation());
assertEquals(0.0, stats.getMaxSpeed());
assertEquals(Double.POSITIVE_INFINITY, stats.getMinGrade());
assertEquals(Double.NEGATIVE_INFINITY, stats.getMaxGrade());
assertEquals(0.0, stats.getTotalElevationGain());
assertEquals(0, stats.getMovingTime());
assertEquals(0.0, stats.getTotalDistance());
for (int i = 0; i < 100; i++) {
Location l = new Location("test");
l.setAccuracy(1.0f);
l.setLongitude(45.0);
// Going up by 5 meters each time.
l.setAltitude(i);
// Moving by .1% of a degree latitude.
l.setLatitude(i * .001);
l.setSpeed(11.1f);
// Each time slice is 10 seconds.
long time = 1000 + 10000 * i;
l.setTime(time);
boolean moving = builder.addLocation(l, time);
assertEquals((i != 0), moving);
stats = builder.getStatistics();
assertEquals(10000 * i, stats.getTotalTime());
assertEquals(10000 * i, stats.getMovingTime());
assertEquals(i, builder.getSmoothedElevation(),
Constants.ELEVATION_SMOOTHING_FACTOR / 2);
assertEquals(0.0, stats.getMinElevation());
assertEquals(i, stats.getMaxElevation(),
Constants.ELEVATION_SMOOTHING_FACTOR / 2);
assertEquals(i, stats.getTotalElevationGain(),
Constants.ELEVATION_SMOOTHING_FACTOR);
if (i > Constants.SPEED_SMOOTHING_FACTOR) {
assertEquals(11.1f, stats.getMaxSpeed(), 0.1);
}
if ((i > Constants.GRADE_SMOOTHING_FACTOR)
&& (i > Constants.ELEVATION_SMOOTHING_FACTOR)) {
assertEquals(0.009, stats.getMinGrade(), 0.0001);
assertEquals(0.009, stats.getMaxGrade(), 0.0001);
}
// 1 degree = 111 km
// 1 timeslice = 0.001 degree = 111 m
assertEquals(111.0 * i, stats.getTotalDistance(), 100);
}
}
/**
* Test that elevation works if the user is stable.
*/
public void testElevationSimple() throws Exception {
for (double elevation = 0; elevation < 1000; elevation += 10) {
builder = new TripStatisticsBuilder(System.currentTimeMillis());
for (int j = 0; j < 100; j++) {
assertEquals(0.0, builder.updateElevation(elevation));
assertEquals(elevation, builder.getSmoothedElevation());
TripStatistics data = builder.getStatistics();
assertEquals(elevation, data.getMinElevation());
assertEquals(elevation, data.getMaxElevation());
assertEquals(0.0, data.getTotalElevationGain());
}
}
}
public void testElevationGain() throws Exception {
for (double i = 0; i < 1000; i++) {
double expectedGain;
if (i < (Constants.ELEVATION_SMOOTHING_FACTOR - 1)) {
expectedGain = 0;
} else if (i < Constants.ELEVATION_SMOOTHING_FACTOR) {
expectedGain = 0.5;
} else {
expectedGain = 1.0;
}
assertEquals(expectedGain,
builder.updateElevation(i));
assertEquals(i, builder.getSmoothedElevation(), 20);
TripStatistics data = builder.getStatistics();
assertEquals(0.0, data.getMinElevation(), 0.0);
assertEquals(i, data.getMaxElevation(),
Constants.ELEVATION_SMOOTHING_FACTOR);
assertEquals(i, data.getTotalElevationGain(),
Constants.ELEVATION_SMOOTHING_FACTOR);
}
}
public void testGradeSimple() throws Exception {
for (double i = 0; i < 1000; i++) {
// The value of the elevation does not matter. This is just to fill the
// buffer.
builder.updateElevation(i);
builder.updateGrade(100, 100);
if ((i > Constants.GRADE_SMOOTHING_FACTOR)
&& (i > Constants.ELEVATION_SMOOTHING_FACTOR)) {
assertEquals(1.0, builder.getStatistics().getMaxGrade());
assertEquals(1.0, builder.getStatistics().getMinGrade());
}
}
for (double i = 0; i < 1000; i++) {
// The value of the elevation does not matter. This is just to fill the
// buffer.
builder.updateElevation(i);
builder.updateGrade(100, -100);
if ((i > Constants.GRADE_SMOOTHING_FACTOR)
&& (i > Constants.ELEVATION_SMOOTHING_FACTOR)) {
assertEquals(1.0, builder.getStatistics().getMaxGrade());
assertEquals(-1.0, builder.getStatistics().getMinGrade());
}
}
}
public void testGradeIgnoreShort() throws Exception {
for (double i = 0; i < 100; i++) {
// The value of the elevation does not matter. This is just to fill the
// buffer.
builder.updateElevation(i);
builder.updateGrade(1, 100);
assertEquals(Double.NEGATIVE_INFINITY, builder.getStatistics().getMaxGrade());
assertEquals(Double.POSITIVE_INFINITY, builder.getStatistics().getMinGrade());
}
}
public void testUpdateSpeedIncludeZero() {
for (int i = 0; i < 1000; i++) {
builder.updateSpeed(i + 1000, 0.0, i, 4.0);
assertEquals(0.0, builder.getStatistics().getMaxSpeed());
assertEquals((i + 1) * 1000, builder.getStatistics().getMovingTime());
}
}
public void testUpdateSpeedIngoreErrorCode() {
builder.updateSpeed(12345000, 128.0, 12344000, 0.0);
assertEquals(0.0, builder.getStatistics().getMaxSpeed());
assertEquals(1000, builder.getStatistics().getMovingTime());
}
public void testUpdateSpeedIngoreLargeAcceleration() {
builder.updateSpeed(12345000, 100.0, 12344000, 1.0);
assertEquals(0.0, builder.getStatistics().getMaxSpeed());
assertEquals(1000, builder.getStatistics().getMovingTime());
}
public void testUpdateSpeed() {
for (int i = 0; i < 1000; i++) {
builder.updateSpeed(i + 1000, 4.0, i, 4.0);
assertEquals((i + 1) * 1000, builder.getStatistics().getMovingTime());
if (i > Constants.SPEED_SMOOTHING_FACTOR) {
assertEquals(4.0, builder.getStatistics().getMaxSpeed());
}
}
}
}
| Java |
/*
* Copyright 2009 Google Inc. All Rights Reserved.
*/
package com.google.android.apps.mytracks.stats;
import junit.framework.TestCase;
/**
* Test for the DoubleBuffer class.
*
* @author Sandor Dornbush
*/
public class DoubleBufferTest extends TestCase {
/**
* Tests that the constructor leaves the buffer in a valid state.
*/
public void testConstructor() {
DoubleBuffer buffer = new DoubleBuffer(10);
assertFalse(buffer.isFull());
assertEquals(0.0, buffer.getAverage());
double[] averageAndVariance = buffer.getAverageAndVariance();
assertEquals(0.0, averageAndVariance[0]);
assertEquals(0.0, averageAndVariance[1]);
}
/**
* Simple test with 10 of the same values.
*/
public void testBasic() {
DoubleBuffer buffer = new DoubleBuffer(10);
for (int i = 0; i < 9; i++) {
buffer.setNext(1.0);
assertFalse(buffer.isFull());
assertEquals(1.0, buffer.getAverage());
double[] averageAndVariance = buffer.getAverageAndVariance();
assertEquals(1.0, averageAndVariance[0]);
assertEquals(0.0, averageAndVariance[1]);
}
buffer.setNext(1);
assertTrue(buffer.isFull());
assertEquals(1.0, buffer.getAverage());
double[] averageAndVariance = buffer.getAverageAndVariance();
assertEquals(1.0, averageAndVariance[0]);
assertEquals(0.0, averageAndVariance[1]);
}
/**
* Tests with 5 entries of -10 and 5 entries of 10.
*/
public void testSplit() {
DoubleBuffer buffer = new DoubleBuffer(10);
for (int i = 0; i < 5; i++) {
buffer.setNext(-10);
assertFalse(buffer.isFull());
assertEquals(-10.0, buffer.getAverage());
double[] averageAndVariance = buffer.getAverageAndVariance();
assertEquals(-10.0, averageAndVariance[0]);
assertEquals(0.0, averageAndVariance[1]);
}
for (int i = 1; i < 5; i++) {
buffer.setNext(10);
assertFalse(buffer.isFull());
double expectedAverage = ((i * 10.0) - 50.0) / (i + 5);
assertEquals(buffer.toString(),
expectedAverage, buffer.getAverage(), 0.01);
double[] averageAndVariance = buffer.getAverageAndVariance();
assertEquals(expectedAverage, averageAndVariance[0]);
}
buffer.setNext(10);
assertTrue(buffer.isFull());
assertEquals(0.0, buffer.getAverage());
double[] averageAndVariance = buffer.getAverageAndVariance();
assertEquals(0.0, averageAndVariance[0]);
assertEquals(100.0, averageAndVariance[1]);
}
/**
* Tests that reset leaves the buffer in a valid state.
*/
public void testReset() {
DoubleBuffer buffer = new DoubleBuffer(10);
for (int i = 0; i < 100; i++) {
buffer.setNext(i);
}
assertTrue(buffer.isFull());
buffer.reset();
assertFalse(buffer.isFull());
assertEquals(0.0, buffer.getAverage());
double[] averageAndVariance = buffer.getAverageAndVariance();
assertEquals(0.0, averageAndVariance[0]);
assertEquals(0.0, averageAndVariance[1]);
}
/**
* Tests that if a lot of items are inserted the smoothing and looping works.
*/
public void testLoop() {
DoubleBuffer buffer = new DoubleBuffer(10);
for (int i = 0; i < 1000; i++) {
buffer.setNext(i);
assertEquals(i >= 9, buffer.isFull());
if (i > 10) {
assertEquals(i - 4.5, buffer.getAverage());
}
}
}
}
| Java |
/**
* Copyright 2009 Google Inc. All Rights Reserved.
*/
package com.google.android.apps.mytracks.stats;
import junit.framework.TestCase;
import java.util.Random;
/**
* This class test the ExtremityMonitor class.
*
* @author Sandor Dornbush
*/
public class ExtremityMonitorTest extends TestCase {
public ExtremityMonitorTest(String name) {
super(name);
}
public void testInitialize() {
ExtremityMonitor monitor = new ExtremityMonitor();
assertEquals(Double.POSITIVE_INFINITY, monitor.getMin());
assertEquals(Double.NEGATIVE_INFINITY, monitor.getMax());
}
public void testSimple() {
ExtremityMonitor monitor = new ExtremityMonitor();
assertTrue(monitor.update(0));
assertTrue(monitor.update(1));
assertEquals(0.0, monitor.getMin());
assertEquals(1.0, monitor.getMax());
assertFalse(monitor.update(1));
assertFalse(monitor.update(0.5));
}
/**
* Throws a bunch of random numbers between [0,1] at the monitor.
*/
public void testRandom() {
ExtremityMonitor monitor = new ExtremityMonitor();
Random random = new Random(42);
for (int i = 0; i < 1000; i++) {
monitor.update(random.nextDouble());
}
assertTrue(monitor.getMin() < 0.1);
assertTrue(monitor.getMax() < 1.0);
assertTrue(monitor.getMin() >= 0.0);
assertTrue(monitor.getMax() > 0.9);
}
public void testReset() {
ExtremityMonitor monitor = new ExtremityMonitor();
assertTrue(monitor.update(0));
assertTrue(monitor.update(1));
monitor.reset();
assertEquals(Double.POSITIVE_INFINITY, monitor.getMin());
assertEquals(Double.NEGATIVE_INFINITY, monitor.getMax());
assertTrue(monitor.update(0));
assertTrue(monitor.update(1));
assertEquals(0.0, monitor.getMin());
assertEquals(1.0, monitor.getMax());
}
}
| Java |
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.stats;
import junit.framework.TestCase;
/**
* Tests for {@link TripStatistics}.
* This only tests non-trivial pieces of that class.
*
* @author Rodrigo Damazio
*/
public class TripStatisticsTest extends TestCase {
private TripStatistics statistics;
@Override
protected void setUp() throws Exception {
super.setUp();
statistics = new TripStatistics();
}
public void testSetBounds() {
// This is not a trivial setter, conversion happens in it
statistics.setBounds(12345, -34567, 56789, -98765);
assertEquals(12345, statistics.getLeft());
assertEquals(-34567, statistics.getTop());
assertEquals(56789, statistics.getRight());
assertEquals(-98765, statistics.getBottom());
}
public void testMerge() {
TripStatistics statistics2 = new TripStatistics();
statistics.setStartTime(1000L); // Resulting start time
statistics.setStopTime(2500L);
statistics2.setStartTime(3000L);
statistics2.setStopTime(4000L); // Resulting stop time
statistics.setTotalTime(1500L);
statistics2.setTotalTime(1000L); // Result: 1500+1000
statistics.setMovingTime(700L);
statistics2.setMovingTime(600L); // Result: 700+600
statistics.setTotalDistance(750.0);
statistics2.setTotalDistance(350.0); // Result: 750+350
statistics.setTotalElevationGain(50.0);
statistics2.setTotalElevationGain(850.0); // Result: 850+50
statistics.setMaxSpeed(60.0); // Resulting max speed
statistics2.setMaxSpeed(30.0);
statistics.setMaxElevation(1250.0);
statistics.setMinElevation(1200.0); // Resulting min elevation
statistics2.setMaxElevation(3575.0); // Resulting max elevation
statistics2.setMinElevation(2800.0);
statistics.setMaxGrade(15.0);
statistics.setMinGrade(-25.0); // Resulting min grade
statistics2.setMaxGrade(35.0); // Resulting max grade
statistics2.setMinGrade(0.0);
// Resulting bounds: -10000, 35000, 30000, -40000
statistics.setBounds(-10000, 20000, 30000, -40000);
statistics2.setBounds(-5000, 35000, 0, 20000);
statistics.merge(statistics2);
assertEquals(1000L, statistics.getStartTime());
assertEquals(4000L, statistics.getStopTime());
assertEquals(2500L, statistics.getTotalTime());
assertEquals(1300L, statistics.getMovingTime());
assertEquals(1100.0, statistics.getTotalDistance());
assertEquals(900.0, statistics.getTotalElevationGain());
assertEquals(60.0, statistics.getMaxSpeed());
assertEquals(-10000, statistics.getLeft());
assertEquals(30000, statistics.getRight());
assertEquals(35000, statistics.getTop());
assertEquals(-40000, statistics.getBottom());
assertEquals(1200.0, statistics.getMinElevation());
assertEquals(3575.0, statistics.getMaxElevation());
assertEquals(-25.0, statistics.getMinGrade());
assertEquals(35.0, statistics.getMaxGrade());
}
public void testGetAverageSpeed() {
statistics.setTotalDistance(1000.0);
statistics.setTotalTime(50000); // in milliseconds
assertEquals(20.0, statistics.getAverageSpeed());
}
public void testGetAverageMovingSpeed() {
statistics.setTotalDistance(1000.0);
statistics.setMovingTime(20000); // in milliseconds
assertEquals(50.0, statistics.getAverageMovingSpeed());
}
}
| Java |
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks;
import com.google.android.apps.mytracks.services.ServiceUtils;
import com.google.android.apps.mytracks.services.TrackRecordingServiceConnection;
import com.google.android.maps.mytracks.R;
import android.app.Activity;
import android.app.Instrumentation.ActivityMonitor;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.test.ActivityInstrumentationTestCase2;
import android.widget.Button;
import java.io.File;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* A unit test for {@link MyTracks} activity.
*
* @author Bartlomiej Niechwiej
*/
public class MyTracksTest extends ActivityInstrumentationTestCase2<MyTracks>{
private SharedPreferences sharedPreferences;
private TrackRecordingServiceConnection serviceConnection;
public MyTracksTest() {
super(MyTracks.class);
}
@Override
protected void tearDown() throws Exception {
clearSelectedAndRecordingTracks();
waitForIdle();
super.tearDown();
}
public void testInitialization_mainAction() {
// Make sure we can start MyTracks and the activity doesn't start recording.
assertInitialized();
// Check if not recording.
assertFalse(isRecording());
assertEquals(-1, getRecordingTrackId());
long selectedTrackId = getSharedPreferences().getLong(
getActivity().getString(R.string.selected_track_key), -1);
assertEquals(selectedTrackId, getActivity().getSelectedTrackId());
}
public void testInitialization_viewActionWithNoData() {
// Simulate start with ACTION_VIEW intent.
Intent startIntent = new Intent();
startIntent.setAction(Intent.ACTION_VIEW);
setActivityIntent(startIntent);
assertInitialized();
// Check if not recording.
assertFalse(isRecording());
assertEquals(-1, getRecordingTrackId());
long selectedTrackId = getSharedPreferences().getLong(
getActivity().getString(R.string.selected_track_key), -1);
assertEquals(selectedTrackId, getActivity().getSelectedTrackId());
}
public void testInitialization_viewActionWithValidData() throws Exception {
// Simulate start with ACTION_VIEW intent.
Intent startIntent = new Intent();
startIntent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(File.createTempFile("valid", ".gpx", getActivity().getFilesDir()));
// TODO: Add a valid GPX.
startIntent.setData(uri);
setActivityIntent(startIntent);
assertInitialized();
// Check if not recording.
assertFalse(isRecording());
assertEquals(-1, getRecordingTrackId());
long selectedTrackId = getSharedPreferences().getLong(
getActivity().getString(R.string.selected_track_key), -1);
assertEquals(selectedTrackId, getActivity().getSelectedTrackId());
// TODO: Finish this test.
}
public void testInitialization_viewActionWithInvalidData() throws Exception {
// Simulate start with ACTION_VIEW intent.
Intent startIntent = new Intent();
startIntent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(File.createTempFile("invalid", ".gpx", getActivity().getFilesDir()));
startIntent.setData(uri);
setActivityIntent(startIntent);
assertInitialized();
// Check if not recording.
assertFalse(isRecording());
assertEquals(-1, getRecordingTrackId());
long selectedTrackId = getSharedPreferences().getLong(
getActivity().getString(R.string.selected_track_key), -1);
assertEquals(selectedTrackId, getActivity().getSelectedTrackId());
// TODO: Finish this test.
}
public void testRecording_startAndStop() throws Exception {
assertInitialized();
// Check if not recording.
clearSelectedAndRecordingTracks();
waitForIdle();
assertFalse(isRecording());
assertEquals(-1, getRecordingTrackId());
long selectedTrackId = getSharedPreferences().getLong(
getActivity().getString(R.string.selected_track_key), -1);
assertEquals(selectedTrackId, getActivity().getSelectedTrackId());
// Start a new track.
getActivity().startRecording();
serviceConnection.bindIfRunning();
long recordingTrackId = awaitRecordingStatus(5000, true);
assertTrue(recordingTrackId >= 0);
// Wait until we are done and make sure that selectedTrack = recordingTrack.
waitForIdle();
assertEquals(recordingTrackId, getSharedPreferences().getLong(
getActivity().getString(R.string.recording_track_key), -1));
selectedTrackId = getSharedPreferences().getLong(
getActivity().getString(R.string.selected_track_key), -1);
assertEquals(recordingTrackId, selectedTrackId);
assertEquals(selectedTrackId, getActivity().getSelectedTrackId());
// Watch for MyTracksDetails activity.
ActivityMonitor monitor = getInstrumentation().addMonitor(
TrackDetail.class.getName(), null, false);
// Now, stop the track and make sure that it is still selected, but
// no longer recording.
getActivity().stopRecording();
// Check if we got back MyTracksDetails activity.
Activity activity = getInstrumentation().waitForMonitor(monitor);
assertTrue(activity instanceof TrackDetail);
// TODO: Update track name and other properties and test if they were
// properly saved.
// Simulate a click on Save button.
final Button save = (Button) activity.findViewById(R.id.track_detail_save);
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
save.performClick();
}
});
// Check the remaining properties.
recordingTrackId = awaitRecordingStatus(5000, false);
assertEquals(-1, recordingTrackId);
assertEquals(recordingTrackId, getRecordingTrackId());
assertEquals(recordingTrackId, getSharedPreferences().getLong(
getActivity().getString(R.string.recording_track_key), -1));
// Make sure this is the same track as the last recording track ID.
assertEquals(selectedTrackId, getActivity().getSelectedTrackId());
}
private void assertInitialized() {
assertNotNull(getActivity());
serviceConnection = new TrackRecordingServiceConnection(getActivity(), null);
}
/**
* Waits until the UI thread becomes idle.
*/
private void waitForIdle() throws InterruptedException {
// Note: We can't use getInstrumentation().waitForIdleSync() here.
final Object semaphore = new Object();
synchronized (semaphore) {
final AtomicBoolean isIdle = new AtomicBoolean();
getInstrumentation().waitForIdle(new Runnable() {
@Override
public void run() {
synchronized (semaphore) {
isIdle.set(true);
semaphore.notify();
}
}
});
while (!isIdle.get()) {
semaphore.wait();
}
}
}
/**
* Clears {selected,recording}TrackId in the {@link #getSharedPreferences()}.
*/
private void clearSelectedAndRecordingTracks() {
Editor editor = getSharedPreferences().edit();
editor.putLong(getActivity().getString(R.string.selected_track_key), -1);
editor.putLong(getActivity().getString(R.string.recording_track_key), -1);
editor.clear();
editor.apply();
}
/**
* Waits until the recording state changes to the given status.
*
* @param timeout the maximum time to wait, in milliseconds.
* @param isRecording the final status to await.
* @return the recording track ID.
*/
private long awaitRecordingStatus(long timeout, boolean isRecording)
throws TimeoutException, InterruptedException {
long startTime = System.nanoTime();
while (isRecording() != isRecording) {
if (System.nanoTime() - startTime > timeout * 1000000) {
throw new TimeoutException("Timeout while waiting for recording!");
}
Thread.sleep(20);
}
waitForIdle();
assertEquals(isRecording, isRecording());
return getRecordingTrackId();
}
private long getRecordingTrackId() {
return getSharedPreferences().getLong(getActivity().getString(R.string.recording_track_key), -1);
}
private SharedPreferences getSharedPreferences() {
if (sharedPreferences == null) {
sharedPreferences = getActivity().getSharedPreferences(
Constants.SETTINGS_NAME, Context.MODE_PRIVATE);
}
return sharedPreferences;
}
private boolean isRecording() {
return ServiceUtils.isRecording(getActivity(),
serviceConnection.getServiceIfBound(), getSharedPreferences());
}
}
| Java |
// Copyright 2010 Google Inc. All Rights Reserved.
package com.google.android.apps.mytracks.testing;
import com.google.android.apps.mytracks.content.MyTracksProviderUtils;
import com.google.android.apps.mytracks.content.MyTracksProviderUtils.Factory;
import android.content.Context;
/**
* A fake factory for {@link MyTracksProviderUtils} which always returns a
* predefined instance.
*
* @author Rodrigo Damazio
*/
public class TestingProviderUtilsFactory extends Factory {
private MyTracksProviderUtils instance;
public TestingProviderUtilsFactory(MyTracksProviderUtils instance) {
this.instance = instance;
}
@Override
protected MyTracksProviderUtils newForContext(Context context) {
return instance;
}
public static Factory installWithInstance(MyTracksProviderUtils instance) {
Factory oldFactory = Factory.getInstance();
Factory factory = new TestingProviderUtilsFactory(instance);
MyTracksProviderUtils.Factory.overrideInstance(factory);
return oldFactory;
}
public static void restoreOldFactory(Factory factory) {
MyTracksProviderUtils.Factory.overrideInstance(factory);
}
}
| Java |
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks;
import com.google.android.apps.mytracks.ChartValueSeries.ZoomSettings;
import com.google.android.maps.mytracks.R;
import android.graphics.Paint.Style;
import android.test.AndroidTestCase;
/**
* @author Sandor Dornbush
*/
public class ChartValueSeriesTest extends AndroidTestCase {
private ChartValueSeries series;
@Override
protected void setUp() throws Exception {
series = new ChartValueSeries(getContext(),
R.color.elevation_fill,
R.color.elevation_border,
new ZoomSettings(5, new int[] {100}),
R.string.stat_elevation);
}
public void testInitialConditions() {
assertEquals(0, series.getInterval());
assertEquals(1, series.getMaxLabelLength());
assertEquals(0, series.getMin());
assertEquals(0, series.getMax());
assertEquals(0.0, series.getSpread());
assertEquals(Style.STROKE, series.getPaint().getStyle());
assertEquals(getContext().getString(R.string.stat_elevation),
series.getTitle());
assertTrue(series.isEnabled());
}
public void testEnabled() {
series.setEnabled(false);
assertFalse(series.isEnabled());
}
public void testSmallUpdates() {
series.update(0);
series.update(10);
series.updateDimension();
assertEquals(100, series.getInterval());
assertEquals(3, series.getMaxLabelLength());
assertEquals(0, series.getMin());
assertEquals(100, series.getMax());
assertEquals(100.0, series.getSpread());
}
public void testBigUpdates() {
series.update(0);
series.update(901);
series.updateDimension();
assertEquals(100, series.getInterval());
assertEquals(5, series.getMaxLabelLength());
assertEquals(0, series.getMin());
assertEquals(1000, series.getMax());
assertEquals(1000.0, series.getSpread());
}
public void testNotZeroBasedUpdates() {
series.update(500);
series.update(1401);
series.updateDimension();
assertEquals(100, series.getInterval());
assertEquals(5, series.getMaxLabelLength());
assertEquals(500, series.getMin());
assertEquals(1500, series.getMax());
assertEquals(1000.0, series.getSpread());
}
public void testZoomSettings_invalidArgs() {
try {
new ZoomSettings(0, new int[] {10, 50, 100});
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
// OK.
}
try {
new ZoomSettings(1, null);
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
// OK.
}
try {
new ZoomSettings(1, new int[] {});
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
// OK.
}
try {
new ZoomSettings(1, new int[] {1, 3, 2});
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
// OK.
}
}
public void testZoomSettings_minAligned() {
ZoomSettings settings = new ZoomSettings(5, new int[] {10, 50, 100});
assertEquals(10, settings.calculateInterval(0, 15));
assertEquals(10, settings.calculateInterval(0, 50));
assertEquals(50, settings.calculateInterval(0, 111));
assertEquals(50, settings.calculateInterval(0, 250));
assertEquals(100, settings.calculateInterval(0, 251));
assertEquals(100, settings.calculateInterval(0, 10000));
}
public void testZoomSettings_minNotAligned() {
ZoomSettings settings = new ZoomSettings(5, new int[] {10, 50, 100});
assertEquals(50, settings.calculateInterval(5, 55));
assertEquals(10, settings.calculateInterval(10, 60));
assertEquals(50, settings.calculateInterval(7, 250));
assertEquals(100, settings.calculateInterval(7, 257));
assertEquals(100, settings.calculateInterval(11, 10000));
// A regression test.
settings = new ZoomSettings(5, new int[] {5, 10, 20});
assertEquals(10, settings.calculateInterval(-37.14, -11.89));
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks;
import com.google.android.apps.mytracks.content.MyTracksLocation;
import com.google.android.apps.mytracks.content.Sensor;
import com.google.android.apps.mytracks.content.Sensor.SensorDataSet;
import com.google.android.apps.mytracks.util.UnitConversions;
import com.google.android.maps.mytracks.R;
import com.jayway.android.robotium.solo.Solo;
import android.app.Instrumentation;
import android.location.Location;
import android.test.ActivityInstrumentationTestCase2;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ZoomControls;
/**
* Tests {@link ChartActivity}.
*
* @author Youtao Liu
*/
public class ChartActivityTest extends ActivityInstrumentationTestCase2<ChartActivity> {
private Instrumentation instrumentation;
private ChartActivity chartActivity;
private Solo solo;
private View zoomIn;
private View zoomOut;
private int currentZoomLevel;
private final String LOCATION_PROVIDER = "gps";
private final double INITIAL_LONGTITUDE = 22;
private final double INITIAL_LATITUDE = 22;
private final double INITIAL_ALTITUDE = 22;
private final float INITIAL_ACCURACY = 5;
private final float INITIAL_SPEED = 10;
private final float INITIAL_BEARING = 3.0f;
// 10 is same with the default value in ChartView
private final int MAX_ZOOM_LEVEL = 10;
private final int MIN_ZOOM_LEVEL = 1;
// The ratio from meter/second to kilometer/hour, the conversion is 60 * 60 /
// 1000 = 3.6.
private final double METER_PER_SECOND_TO_KILOMETER_PER_HOUR = 3.6;
private final double KILOMETER_TO_METER = 1000.0;
private final double HOURS_PER_UNIT = 60;
public ChartActivityTest() {
super(ChartActivity.class);
}
@Override
protected void setUp() throws Exception {
super.setUp();
instrumentation = getInstrumentation();
chartActivity = getActivity();
}
/**
* Tests {@link ChartActivity#zoomIn()} and {@link ChartActivity#zoomOut()}.
*/
public void testZoomInAndZoomOut() {
currentZoomLevel = chartActivity.getChartView().getZoomLevel();
chartActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
ZoomControls zoomControls = (ZoomControls) chartActivity.findViewById(R.id.elevation_zoom);
zoomIn = zoomControls.getChildAt(0);
zoomOut = zoomControls.getChildAt(1);
// Invoke following two methods method to initial the display of
// ZoomControls.
zoomControls.setIsZoomInEnabled(chartActivity.getChartView().canZoomIn());
zoomControls.setIsZoomOutEnabled(chartActivity.getChartView().canZoomOut());
// Click zoomIn button to disable.
for (int i = currentZoomLevel; i > MIN_ZOOM_LEVEL; i--) {
zoomIn.performClick();
}
}
});
instrumentation.waitForIdleSync();
assertEquals(false, zoomIn.isEnabled());
assertEquals(true, zoomOut.isEnabled());
chartActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
// Click to the second max zoom level
for (int i = MIN_ZOOM_LEVEL; i < MAX_ZOOM_LEVEL - 1; i++) {
zoomOut.performClick();
assertEquals(true, zoomIn.isEnabled());
assertEquals(true, zoomOut.isEnabled());
}
zoomOut.performClick();
}
});
instrumentation.waitForIdleSync();
assertEquals(true, zoomIn.isEnabled());
assertEquals(false, zoomOut.isEnabled());
}
/**
* There are two parts in this test. Tests
* {@link ChartActivity#OnCreateDialog()} which includes the logic to create
* {@link ChartSettingsDialog}.
*/
public void testCreateSettingDialog() {
solo = new Solo(instrumentation, chartActivity);
// Part1, tests {@link ChartActivity#onCreateOptionsMenu()}. Check if
// optional menu is created.
assertNull(chartActivity.getChartSettingsMenuItem());
sendKeys(KeyEvent.KEYCODE_MENU);
assertNotNull(chartActivity.getChartSettingsMenuItem());
// Part2, tests {@link ChartActivity#onOptionsItemSelected()}. Clicks on the
// "Chart settings", and then verify that the dialog contains the
// "By distance" text.
solo.clickOnText(chartActivity.getString(R.string.menu_chart_view_chart_settings));
instrumentation.waitForIdleSync();
assertTrue(solo.searchText(chartActivity.getString(R.string.chart_settings_by_distance)));
}
/**
* Tests the logic to get the incorrect values of sensor in {@link
* ChartActivity#fillDataPoint(Location location, double result[])}.
*/
public void testFillDataPoint_sensorIncorrect() {
MyTracksLocation myTracksLocation = getMyTracksLocation();
// No input.
double[] point = fillDataPointTestHelper(myTracksLocation, false);
assertEquals(Double.NaN, point[3]);
assertEquals(Double.NaN, point[4]);
assertEquals(Double.NaN, point[5]);
// Input incorrect state.
// Creates SensorData.
Sensor.SensorData.Builder powerData = Sensor.SensorData.newBuilder().setValue(20)
.setState(Sensor.SensorState.NONE);
Sensor.SensorData.Builder cadenceData = Sensor.SensorData.newBuilder().setValue(20)
.setState(Sensor.SensorState.NONE);
Sensor.SensorData.Builder heartRateData = Sensor.SensorData.newBuilder().setValue(20)
.setState(Sensor.SensorState.NONE);
// Creates SensorDataSet.
SensorDataSet sensorDataSet = myTracksLocation.getSensorDataSet();
sensorDataSet = sensorDataSet.toBuilder().setPower(powerData).setCadence(cadenceData)
.setHeartRate(heartRateData).build();
myTracksLocation.setSensorData(sensorDataSet);
// Test.
point = fillDataPointTestHelper(myTracksLocation, false);
assertEquals(Double.NaN, point[3]);
assertEquals(Double.NaN, point[4]);
assertEquals(Double.NaN, point[5]);
}
/**
* Tests the logic to get the correct values of sensor in {@link
* ChartActivity#fillDataPoint(Location location, double result[])}.
*/
public void testFillDataPoint_sensorCorrect() {
MyTracksLocation myTracksLocation = getMyTracksLocation();
// No input.
double[] point = fillDataPointTestHelper(myTracksLocation, false);
assertEquals(Double.NaN, point[3]);
assertEquals(Double.NaN, point[4]);
assertEquals(Double.NaN, point[5]);
// Creates SensorData.
Sensor.SensorData.Builder powerData = Sensor.SensorData.newBuilder().setValue(20)
.setState(Sensor.SensorState.SENDING);
Sensor.SensorData.Builder cadenceData = Sensor.SensorData.newBuilder().setValue(20)
.setState(Sensor.SensorState.SENDING);
Sensor.SensorData.Builder heartRateData = Sensor.SensorData.newBuilder().setValue(20)
.setState(Sensor.SensorState.SENDING);
// Creates SensorDataSet.
SensorDataSet sensorDataSet = myTracksLocation.getSensorDataSet();
sensorDataSet = sensorDataSet.toBuilder().setPower(powerData).setCadence(cadenceData)
.setHeartRate(heartRateData).build();
myTracksLocation.setSensorData(sensorDataSet);
// Test.
point = fillDataPointTestHelper(myTracksLocation, false);
assertEquals(20.0, point[3]);
assertEquals(20.0, point[4]);
assertEquals(20.0, point[5]);
}
/**
* Tests the logic to get the value of metric Distance in
* {@link #fillDataPoint}.
*/
public void testFillDataPoint_distanceMetric() {
// By distance.
chartActivity.getChartView().setMode(ChartView.Mode.BY_DISTANCE);
// Resets last location and writes first location.
MyTracksLocation myTracksLocation1 = getMyTracksLocation();
double[] point = fillDataPointTestHelper(myTracksLocation1, true);
assertEquals(0.0, point[0]);
// The second is a same location, just different time.
MyTracksLocation myTracksLocation2 = getMyTracksLocation();
point = fillDataPointTestHelper(myTracksLocation2, false);
assertEquals(0.0, point[0]);
// The third location is a new location, and use metric.
MyTracksLocation myTracksLocation3 = getMyTracksLocation();
myTracksLocation3.setLatitude(23);
point = fillDataPointTestHelper(myTracksLocation3, false);
// Computes the distance between Latitude 22 and 23.
float[] results = new float[4];
Location.distanceBetween(myTracksLocation2.getLatitude(), myTracksLocation2.getLongitude(),
myTracksLocation3.getLatitude(), myTracksLocation3.getLongitude(), results);
double distance1 = results[0];
assertEquals(distance1 / KILOMETER_TO_METER, point[0]);
// The fourth location is a new location, and use metric.
MyTracksLocation myTracksLocation4 = getMyTracksLocation();
myTracksLocation4.setLatitude(24);
point = fillDataPointTestHelper(myTracksLocation4, false);
// Computes the distance between Latitude 23 and 24.
Location.distanceBetween(myTracksLocation3.getLatitude(), myTracksLocation3.getLongitude(),
myTracksLocation4.getLatitude(), myTracksLocation4.getLongitude(), results);
double distance2 = results[0];
assertEquals((distance1 + distance2) / KILOMETER_TO_METER, point[0]);
}
/**
* Tests the logic to get the value of imperial Distance in
* {@link #fillDataPoint}.
*/
public void testFillDataPoint_distanceImperial() {
// Setups to use imperial.
chartActivity.onUnitsChanged(false);
// The first is a same location, just different time.
MyTracksLocation myTracksLocation1 = getMyTracksLocation();
double[] point = fillDataPointTestHelper(myTracksLocation1, true);
assertEquals(0.0, point[0]);
// The second location is a new location, and use imperial.
MyTracksLocation myTracksLocation2 = getMyTracksLocation();
myTracksLocation2.setLatitude(23);
point = fillDataPointTestHelper(myTracksLocation2, false);
/*
* Computes the distance between Latitude 22 and 23. And for we set using
* imperial, the distance should be multiplied by UnitConversions.KM_TO_MI.
*/
float[] results = new float[4];
Location.distanceBetween(myTracksLocation1.getLatitude(), myTracksLocation1.getLongitude(),
myTracksLocation2.getLatitude(), myTracksLocation2.getLongitude(), results);
double distance1 = results[0] * UnitConversions.KM_TO_MI;
assertEquals(distance1 / KILOMETER_TO_METER, point[0]);
// The third location is a new location, and use imperial.
MyTracksLocation myTracksLocation3 = getMyTracksLocation();
myTracksLocation3.setLatitude(24);
point = fillDataPointTestHelper(myTracksLocation3, false);
/*
* Computes the distance between Latitude 23 and 24. And for we set using
* imperial, the distance should be multiplied by UnitConversions.KM_TO_MI.
*/
Location.distanceBetween(myTracksLocation2.getLatitude(), myTracksLocation2.getLongitude(),
myTracksLocation3.getLatitude(), myTracksLocation3.getLongitude(), results);
double distance2 = results[0] * UnitConversions.KM_TO_MI;
assertEquals((distance1 + distance2) / KILOMETER_TO_METER, point[0]);
}
/**
* Tests the logic to get the values of time in {@link #fillDataPoint}.
*/
public void testFillDataPoint_time() {
// By time
chartActivity.getChartView().setMode(ChartView.Mode.BY_TIME);
MyTracksLocation myTracksLocation1 = getMyTracksLocation();
double[] point = fillDataPointTestHelper(myTracksLocation1, true);
assertEquals(0.0, point[0]);
long timeSpan = 222;
MyTracksLocation myTracksLocation2 = getMyTracksLocation();
myTracksLocation2.setTime(myTracksLocation1.getTime() + timeSpan);
point = fillDataPointTestHelper(myTracksLocation2, false);
assertEquals((double) timeSpan, point[0]);
}
/**
* Tests the logic to get the value of elevation in
* {@link ChartActivity#fillDataPoint} by one and two points.
*/
public void testFillDataPoint_elevation() {
MyTracksLocation myTracksLocation1 = getMyTracksLocation();
/*
* At first, clear old points of elevation, so give true to the second
* parameter. Then only one value INITIALLONGTITUDE in buffer.
*/
double[] point = fillDataPointTestHelper(myTracksLocation1, true);
assertEquals(INITIAL_ALTITUDE, point[1]);
/*
* Send another value to buffer, now there are two values, INITIALALTITUDE
* and INITIALALTITUDE * 2.
*/
MyTracksLocation myTracksLocation2 = getMyTracksLocation();
myTracksLocation2.setAltitude(INITIAL_ALTITUDE * 2);
point = fillDataPointTestHelper(myTracksLocation2, false);
assertEquals((INITIAL_ALTITUDE + INITIAL_ALTITUDE * 2) / 2.0, point[1]);
}
/**
* Tests the logic to get the value of speed in
* {@link ChartActivity#fillDataPoint}. In this test, firstly remove all
* points in memory, and then fill in two points one by one. The speed values
* of these points are 129, 130.
*/
public void testFillDataPoint_speed() {
// Set max speed to make the speed of points are valid.
chartActivity.setTrackMaxSpeed(200.0);
/*
* At first, clear old points of speed, so give true to the second
* parameter. It will not be filled in to the speed buffer.
*/
MyTracksLocation myTracksLocation1 = getMyTracksLocation();
myTracksLocation1.setSpeed(129);
double[] point = fillDataPointTestHelper(myTracksLocation1, true);
assertEquals(0.0, point[2]);
/*
* Tests the logic when both metricUnits and reportSpeed are true.This
* location will be filled into speed buffer.
*/
MyTracksLocation myTracksLocation2 = getMyTracksLocation();
// Add a time span here to make sure the second point is valid, the value
// 222 here is doesn't matter.
myTracksLocation2.setTime(myTracksLocation1.getTime() + 222);
myTracksLocation2.setSpeed(130);
point = fillDataPointTestHelper(myTracksLocation2, false);
assertEquals(130.0 * METER_PER_SECOND_TO_KILOMETER_PER_HOUR, point[2]);
}
/**
* Tests the logic to compute speed when use Imperial.
*/
public void testFillDataPoint_speedImperial() {
// Setups to use imperial.
chartActivity.onUnitsChanged(false);
MyTracksLocation myTracksLocation = getMyTracksLocation();
myTracksLocation.setSpeed(132);
double[] point = fillDataPointTestHelper(myTracksLocation, true);
assertEquals(132.0 * METER_PER_SECOND_TO_KILOMETER_PER_HOUR * UnitConversions.KM_TO_MI,
point[2]);
}
/**
* Tests the logic to get pace value when reportSpeed is false.
*/
public void testFillDataPoint_pace_nonZeroSpeed() {
// Setups reportSpeed to false.
chartActivity.onReportSpeedChanged(false);
MyTracksLocation myTracksLocation = getMyTracksLocation();
myTracksLocation.setSpeed(134);
double[] point = fillDataPointTestHelper(myTracksLocation, true);
assertEquals(HOURS_PER_UNIT / (134.0 * METER_PER_SECOND_TO_KILOMETER_PER_HOUR), point[2]);
}
/**
* Tests the logic to get pace value when reportSpeed is false and average
* speed is zero.
*/
public void testFillDataPoint_pace_zeroSpeed() {
// Setups reportSpeed to false.
chartActivity.onReportSpeedChanged(false);
MyTracksLocation myTracksLocation = getMyTracksLocation();
myTracksLocation.setSpeed(0);
double[] point = fillDataPointTestHelper(myTracksLocation, true);
assertEquals(Double.NaN, point[2]);
}
/**
* Simulates a MyTracksLocation for test.
*
* @return a simulated location.
*/
private MyTracksLocation getMyTracksLocation() {
// Initial Location
Location loc = new Location(LOCATION_PROVIDER);
loc.setLongitude(INITIAL_LONGTITUDE);
loc.setLatitude(INITIAL_LATITUDE);
loc.setAltitude(INITIAL_ALTITUDE);
loc.setAccuracy(INITIAL_ACCURACY);
loc.setSpeed(INITIAL_SPEED);
loc.setTime(System.currentTimeMillis());
loc.setBearing(INITIAL_BEARING);
SensorDataSet sd = SensorDataSet.newBuilder().build();
MyTracksLocation myTracksLocation = new MyTracksLocation(loc, sd);
return myTracksLocation;
}
/**
* Helper method to test fillDataPoint.
*
* @param location location to fill
* @param operation a flag to do some operations
* @return data of this location
*/
private double[] fillDataPointTestHelper(Location location, boolean isNeedClear) {
if (isNeedClear) {
chartActivity.clearTrackPoints();
}
double[] point = new double[6];
chartActivity.fillDataPoint(location, point);
return point;
}
}
| Java |
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks;
import com.google.android.maps.MapView;
import com.google.android.maps.Projection;
import android.content.Context;
import android.graphics.Rect;
/**
* Elements for Tests for the MyTracks map overlay.
*
* @author Bartlomiej Niechwiej
* @author Vangelis S.
*
* A mock version of {@code MapOverlay} that does not use
* {@class MapView}.
*/
public class MockMyTracksOverlay extends MapOverlay {
private Projection mockProjection;
public MockMyTracksOverlay(Context context) {
super(context);
mockProjection = new MockProjection();
}
@Override
public Projection getMapProjection(MapView mapView) {
return mockProjection;
}
@Override
public Rect getMapViewRect(MapView mapView) {
return new Rect(0, 0, 100, 100);
}
} | Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks;
import com.google.android.apps.mytracks.ChartView.Mode;
import com.google.android.maps.mytracks.R;
import android.test.ActivityInstrumentationTestCase2;
/**
* Tests the {@link ChartSettingsDialog}.
*
* @author Youtao Liu
*/
public class ChartSettingsDialogTest extends ActivityInstrumentationTestCase2<ChartActivity> {
private ChartSettingsDialog chartSettingsDialog;
public ChartSettingsDialogTest() {
super(ChartActivity.class);
}
@Override
protected void setUp() throws Exception {
super.setUp();
chartSettingsDialog = new ChartSettingsDialog(getActivity());
chartSettingsDialog.show();
}
/**
* Tests the {@link ChartSettingsDialog#setMode} and check the result by
* {@link ChartSettingsDialog#getMode}. Gets all modes of Mode, then set and
* get each mode.
*/
public void testSetMode() {
Mode[] modes = Mode.values();
for (Mode mode : modes) {
chartSettingsDialog.setMode(mode);
assertEquals(mode, chartSettingsDialog.getMode());
}
}
/**
* Tests the {@link ChartSettingsDialog#setDisplaySpeed}.
*/
public void testSetDisplaySpeed() {
chartSettingsDialog.setDisplaySpeed(true);
assertEquals(getActivity().getString(R.string.stat_speed),
chartSettingsDialog.getSeries()[ChartView.SPEED_SERIES].getText());
chartSettingsDialog.setDisplaySpeed(false);
assertEquals(getActivity().getString(R.string.stat_pace),
chartSettingsDialog.getSeries()[ChartView.SPEED_SERIES].getText());
}
/**
* Tests the {@link ChartSettingsDialog#setSeriesEnabled} and check the result
* by {@link ChartSettingsDialog#isSeriesEnabled}.
*/
public void testSetSeriesEnabled() {
for (int i = 0; i < ChartView.NUM_SERIES; i++) {
chartSettingsDialog.setSeriesEnabled(i, true);
assertEquals(true, chartSettingsDialog.getSeries()[i].isChecked());
assertEquals(true, chartSettingsDialog.isSeriesEnabled(i));
chartSettingsDialog.setSeriesEnabled(i, false);
assertEquals(false, chartSettingsDialog.getSeries()[i].isChecked());
assertEquals(false, chartSettingsDialog.isSeriesEnabled(i));
}
}
} | Java |
/*
* Copyright 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.util;
import com.google.android.apps.mytracks.content.Track;
import com.google.android.apps.mytracks.stats.TripStatistics;
import java.util.Vector;
import junit.framework.TestCase;
/**
* Tests for the Chart URL generator.
*
* @author Sandor Dornbush
*/
public class ChartURLGeneratorTest extends TestCase {
public void testgetChartUrl() {
Vector<Double> distances = new Vector<Double>();
Vector<Double> elevations = new Vector<Double>();
Track t = new Track();
TripStatistics stats = t.getStatistics();
stats.setMinElevation(0);
stats.setMaxElevation(2000);
stats.setTotalDistance(100);
distances.add(0.0);
elevations.add(10.0);
distances.add(10.0);
elevations.add(300.0);
distances.add(20.0);
elevations.add(800.0);
distances.add(50.0);
elevations.add(1900.0);
distances.add(75.0);
elevations.add(1200.0);
distances.add(90.0);
elevations.add(700.0);
distances.add(100.0);
elevations.add(70.0);
String chart = ChartURLGenerator.getChartUrl(distances,
elevations,
t,
"Title",
true);
assertEquals(
"http://chart.apis.google.com/chart?&chs=600x350&cht=lxy&"
+ "chtt=Title&chxt=x,y&chxr=0,0,0,0|1,0.0,2100.0,300&chco=009A00&"
+ "chm=B,00AA00,0,0,0&chg=100000,14.285714285714286,1,0&"
+ "chd=e:AAGZMzf.v.5l..,ATJJYY55kkVVCI",
chart);
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.