Custom function support + refactor of vars registry

This commit is contained in:
Sergey Solovyev 2011-12-22 18:54:16 +04:00
parent 5233ba9e18
commit 08e3f7cef1
28 changed files with 634 additions and 448 deletions

View File

@ -78,15 +78,15 @@
<string name="c_var.already.exists">¡Ya existe una variable con el mismo nombre!</string>
<string name="c_name.is.not.valid">El nombre de la Constante no es válido: el nombre debe comenzar con una letra,puede contener letras, dígitos y líneas.</string>
<string name="c_sys.var.cannot.be.changed">¡Una Variable de Sistema no puede ser cambiada!</string>
<string name="c_pi_description">Ratio de la circunferencia del círculo a su diámetro</string>
<string name="c_e_description">Número real único como el valor de la derivada (pendiente de la línea tangente) de la función f(x) = e^x en el punto x = 0 es igual a 1</string>
<string name="c_i_description">Unidad imaginaria, definida como i^2 = 1</string>
<string name="c_c_description">Velocidad de la luz en vacío, m·s^-1</string>
<string name="c_g_description">La constante gravitatoria es una constante física empírica consistente en el cálculo de la atracción gravitatoria entre objetos con masa, m^3·kg^1·s^2</string>
<string name="c_h_description">Constante física que refleja los tamaños de energía cuántica en mecánica cuántica, J·s</string>
<string name="c_h_reduced_description">Constante Planck reducida, J·s</string>
<string name="c_nan_description">No es un número</string>
<string name="c_infinity_description">Infinito</string>
<string name="c_var_description_pi">Ratio de la circunferencia del círculo a su diámetro</string>
<string name="c_var_description_e">Número real único como el valor de la derivada (pendiente de la línea tangente) de la función f(x) = e^x en el punto x = 0 es igual a 1</string>
<string name="c_var_description_i">Unidad imaginaria, definida como i^2 = 1</string>
<string name="c_var_description_c">Velocidad de la luz en vacío, m·s^-1</string>
<string name="c_var_description_G">La constante gravitatoria es una constante física empírica consistente en el cálculo de la atracción gravitatoria entre objetos con masa, m^3·kg^1·s^2</string>
<string name="c_var_description_h">Constante física que refleja los tamaños de energía cuántica en mecánica cuántica, J·s</string>
<string name="c_var_description_h_reduced">Constante Planck reducida, J·s</string>
<string name="c_var_description_nan">No es un número</string>
<string name="c_var_description_inf">Infinito</string>
<string name="c_calc_editor_hint">Introducir nuevo cálculo</string>
<string name="c_press_to_copy">Pulsar para copiar</string>
<string name="c_continue">Continuar</string>

View File

@ -72,15 +72,15 @@
<string name="c_name.is.not.valid">Il nome della costante non è valido: il nome deve iniziare con una lettera, può contenere lettere, cifre e underscore.</string>
<string name="c_sys.var.cannot.be.changed">La variabile di sistema non può essere cambiata!</string>
<string name="c_pi_description">Rapporto tra la circonferenza di qualsiasi cerchio col suo diametro</string>
<string name="c_e_description">Unico numero reale tale che il valore della derivata (pendenza della retta tangente) della funzione f(x) = e^x nel punto x = 0 che è uguale a 1</string>
<string name="c_i_description">Unità immaginaria, definita come i^2 = -1</string>
<string name="c_c_description">Velocità della luce nel vuoto, m·s^-1</string>
<string name="c_g_description">La costante gravitazionale è una costante fisica empirica coinvolta nel calcolo dell\' attrazione gravitazionale tra gli oggetti con massa, m^3·kg^1·s^2</string>
<string name="c_h_description">Costante fisica che riflette la dimensione dei quanti di energia in meccanica quantistica, J·s</string>
<string name="c_h_reduced_description">Costante di riduzione di Planck, J·s</string>
<string name="c_nan_description">Non è un numero</string>
<string name="c_infinity_description">Infinito</string>
<string name="c_var_description_pi">Rapporto tra la circonferenza di qualsiasi cerchio col suo diametro</string>
<string name="c_var_description_e">Unico numero reale tale che il valore della derivata (pendenza della retta tangente) della funzione f(x) = e^x nel punto x = 0 che è uguale a 1</string>
<string name="c_var_description_i">Unità immaginaria, definita come i^2 = -1</string>
<string name="c_var_description_c">Velocità della luce nel vuoto, m·s^-1</string>
<string name="c_var_description_G">La costante gravitazionale è una costante fisica empirica coinvolta nel calcolo dell\' attrazione gravitazionale tra gli oggetti con massa, m^3·kg^1·s^2</string>
<string name="c_var_description_h">Costante fisica che riflette la dimensione dei quanti di energia in meccanica quantistica, J·s</string>
<string name="c_var_description_h_reduced">Costante di riduzione di Planck, J·s</string>
<string name="c_var_description_nan">Non è un numero</string>
<string name="c_var_description_inf">Infinito</string>
<string name="c_calc_editor_hint">Inserisci una nuova espressione</string>
<string name="c_press_to_copy">Premi per copiare</string>

View File

@ -71,15 +71,16 @@
<string name="c_name.is.not.valid">Имя переменной не валидно: им ядолжно начинаться с буквы, может содержать буквы, цифры и знак подчёркивания.</string>
<string name="c_sys.var.cannot.be.changed">Системная переменная не может быть изменена!</string>
<string name="c_pi_description">Отношение длины окружности к диаметру</string>
<string name="c_e_description">Вещественное число, такое что производная функции f(x) = e^x в точке x = 0 равно 1</string>
<string name="c_i_description">Мнимая единица, определённая как i^2 = 1</string>
<string name="c_c_description">Скорость света в вакууме, м·с^-1</string>
<string name="c_g_description">Гравитационная постоянная, с^3·кг^с^2</string>
<string name="c_h_description">Постоянная Планка - коэффициент, связывающий величину энергии электромагнитного излучения с его частотой, Дж·с</string>
<string name="c_h_reduced_description">Приведённая постоянная Планка, Дж·с</string>
<string name="c_nan_description">Не число</string>
<string name="c_infinity_description">Бесконечность</string>
<string name="c_var_description_pi">Отношение длины окружности к диаметру. Внимание: эта постоянная зависит от единиц измерения углов => rad: 3.14, deg: 180.0</string>
<string name="c_var_description_PI">Отношение длины окружности к диаметру. Внимание: эта постоянная не зависит от единиц измерения углов => rad: 3.14, rad: 3.14</string>
<string name="c_var_description_e">Вещественное число, такое что производная функции f(x) = e^x в точке x = 0 равно 1</string>
<string name="c_var_description_i">Мнимая единица, определённая как i^2 = 1</string>
<string name="c_var_description_c">Скорость света в вакууме, м·с^-1</string>
<string name="c_var_description_G">Гравитационная постоянная, с^3·кг^с^2</string>
<string name="c_var_description_h">Постоянная Планка - коэффициент, связывающий величину энергии электромагнитного излучения с его частотой, Дж·с</string>
<string name="c_var_description_h_reduced">Приведённая постоянная Планка, Дж·с</string>
<string name="c_var_description_nan">Не число</string>
<string name="c_var_description_inf">Бесконечность</string>
<string name="c_calc_editor_hint">Введите новое выражение</string>
<string name="c_continue">Продолжить</string>
<string name="c_press_to_copy">Нажмите для копирования</string>

View File

@ -27,6 +27,7 @@
<string name="p_calc_round_result_key">org.solovyev.android.calculator.CalculatorModel_round_result</string>
<string name="p_calc_round_result">true</string>
<string name="p_calc_functions">org.solovyev.android.calculator.CalculatorModel_functions</string>
<string name="p_calc_vars">org.solovyev.android.calculator.CalculatorModel_vars</string>
<string name="p_calc_history">org.solovyev.android.calculator.CalculatorModel_history</string>

View File

@ -74,15 +74,16 @@
<string name="c_name.is.not.valid">Name of constant is not valid: name must start with letter, can contain letters, digits and underscore.</string>
<string name="c_sys.var.cannot.be.changed">System variable cannot be changed!</string>
<string name="c_pi_description">Ratio of any circle\'s circumference to its diameter</string>
<string name="c_e_description">Unique real number such that the value of the derivative (slope of the tangent line) of the function f(x) = e^x at the point x = 0 is equal to 1</string>
<string name="c_i_description">Imaginary unit, defined such that i^2 = 1</string>
<string name="c_c_description">Speed of light in vacuum, m·s^-1</string>
<string name="c_g_description">The gravitational constant is an empirical physical constant involved in the calculation of the gravitational attraction between objects with mass, m^3·kg^1·s^2</string>
<string name="c_h_description">Physical constant reflecting the sizes of energy quanta in quantum mechanics, J·s</string>
<string name="c_h_reduced_description">Reduced Planck constant, J·s</string>
<string name="c_nan_description">Not a number</string>
<string name="c_infinity_description">Infinity</string>
<string name="c_var_description_pi">Ratio of any circle\'s circumference to its diameter. Note: this constant is degree unit dependent => rad: 3.14, deg: 180.0</string>
<string name="c_var_description_PI">Ratio of any circle\'s circumference to its diameter. Note: this constant is degree unit independent => rad: 3.14, rad: 3.14</string>
<string name="c_var_description_e">Unique real number such that the value of the derivative (slope of the tangent line) of the function f(x) = e^x at the point x = 0 is equal to 1</string>
<string name="c_var_description_i">Imaginary unit, defined such that i^2 = 1</string>
<string name="c_var_description_c">Speed of light in vacuum, m·s^-1</string>
<string name="c_var_description_G">The gravitational constant is an empirical physical constant involved in the calculation of the gravitational attraction between objects with mass, m^3·kg^1·s^2</string>
<string name="c_var_description_h">Physical constant reflecting the sizes of energy quanta in quantum mechanics, J·s</string>
<string name="c_var_description_h_reduced">Reduced Planck constant, J·s</string>
<string name="c_var_description_nan">Not a number</string>
<string name="c_var_description_inf">Infinity</string>
<string name="c_calc_editor_hint">Enter new expression</string>
<string name="c_press_to_copy">Press to copy</string>

View File

@ -20,6 +20,7 @@ import android.widget.TextView;
import android.widget.Toast;
import jscl.math.Generic;
import jscl.math.function.Constant;
import jscl.math.function.IConstant;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.solovyev.android.calculator.history.CalculatorHistory;
@ -389,8 +390,8 @@ public enum CalculatorModel implements CursorControl, HistoryControl<CalculatorH
if ( genericResult != null ) {
final Set<Constant> notSystemConstants = new HashSet<Constant>();
for (Constant constant : genericResult.getConstants()) {
Var var = CalculatorEngine.instance.getVarsRegister().get(constant.getName());
if (var != null && !var.isSystem()) {
IConstant var = CalculatorEngine.instance.getVarsRegister().get(constant.getName());
if (var != null && !var.isSystem() && !var.isDefined()) {
notSystemConstants.add(constant);
}
}
@ -410,6 +411,8 @@ public enum CalculatorModel implements CursorControl, HistoryControl<CalculatorH
}
break;
case elementary:
copyResult(activity, cd);
break;
case numeric:
copyResult(activity, cd);
break;

View File

@ -10,7 +10,7 @@ import android.app.TabActivity;
import android.os.Bundle;
import android.widget.TabHost;
import org.jetbrains.annotations.Nullable;
import org.solovyev.android.calculator.model.AndroidVarsRegistry;
import org.solovyev.android.calculator.model.VarCategory;
import org.solovyev.android.view.prefs.AndroidUtils;
/**
@ -28,8 +28,8 @@ public class CalculatorVarsActivity extends TabActivity {
final TabHost tabHost = getTabHost();
for (AndroidVarsRegistry.Category category : AndroidVarsRegistry.Category.getCategoriesByTabOrder()) {
if (category == AndroidVarsRegistry.Category.my) {
for (VarCategory category : VarCategory.getCategoriesByTabOrder()) {
if (category == VarCategory.my) {
AbstractMathEntityListActivity.createTab(this, tabHost, category.name(), category.name(), category.getCaptionId(), CalculatorVarsTabActivity.class, getIntent());
} else {
AbstractMathEntityListActivity.createTab(this, tabHost, category.name(), category.name(), category.getCaptionId(), CalculatorVarsTabActivity.class, null);

View File

@ -17,6 +17,7 @@ import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import jscl.math.function.IConstant;
import jscl.text.Identifier;
import jscl.text.MutableInt;
import jscl.text.ParseException;
@ -24,7 +25,7 @@ import jscl.text.Parser;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.solovyev.android.calculator.math.MathType;
import org.solovyev.android.calculator.model.AndroidVarsRegistry;
import org.solovyev.android.calculator.model.AndroidMathRegistry;
import org.solovyev.android.calculator.model.CalculatorEngine;
import org.solovyev.android.calculator.model.Var;
import org.solovyev.common.utils.CollectionsUtils;
@ -40,7 +41,7 @@ import java.util.List;
* Date: 9/28/11
* Time: 10:55 PM
*/
public class CalculatorVarsTabActivity extends AbstractMathEntityListActivity<Var> {
public class CalculatorVarsTabActivity extends AbstractMathEntityListActivity<IConstant> {
public static final String CREATE_VAR_EXTRA_STRING = "org.solovyev.android.calculator.CalculatorVarsActivity_create_var";
@ -89,12 +90,12 @@ public class CalculatorVarsTabActivity extends AbstractMathEntityListActivity<Va
@NotNull
@Override
protected List<Var> getMathEntities() {
final List<Var> result = new ArrayList<Var>(CalculatorEngine.instance.getVarsRegister().getEntities());
protected List<IConstant> getMathEntities() {
final List<IConstant> result = new ArrayList<IConstant>(CalculatorEngine.instance.getVarsRegister().getEntities());
CollectionsUtils.removeAll(result, new Finder<Var>() {
CollectionsUtils.removeAll(result, new Finder<IConstant>() {
@Override
public boolean isFound(@Nullable Var var) {
public boolean isFound(@Nullable IConstant var) {
return var != null && CollectionsUtils.contains(var.getName(), MathType.INFINITY_JSCL, MathType.NAN);
}
});
@ -103,7 +104,7 @@ public class CalculatorVarsTabActivity extends AbstractMathEntityListActivity<Va
}
@Override
protected String getMathEntityCategory(@NotNull Var var) {
protected String getMathEntityCategory(@NotNull IConstant var) {
return CalculatorEngine.instance.getVarsRegister().getCategory(var);
}
@ -214,12 +215,12 @@ public class CalculatorVarsTabActivity extends AbstractMathEntityListActivity<Va
String description = editDescription.getText().toString();
final AndroidVarsRegistry varsRegistry = CalculatorEngine.instance.getVarsRegister();
final AndroidMathRegistry<IConstant> varsRegistry = CalculatorEngine.instance.getVarsRegister();
if (isValidName(name)) {
boolean canBeSaved = false;
final Var varFromRegister = varsRegistry.get(name);
final IConstant varFromRegister = varsRegistry.get(name);
if ( varFromRegister == null ) {
canBeSaved = true;
} else if ( editedInstance != null && varFromRegister.getId().equals(editedInstance.getId()) ) {
@ -264,7 +265,7 @@ public class CalculatorVarsTabActivity extends AbstractMathEntityListActivity<Va
Toast.makeText(CalculatorVarsTabActivity.this, getString(error), Toast.LENGTH_LONG).show();
createEditVariableDialog(editedInstance, name, value, description);
} else {
final Var addedVar = varsRegistry.add(varBuilder);
final IConstant addedVar = varsRegistry.add(varBuilder);
if (isInCategory(addedVar)) {
if ( editedInstance != null ) {
CalculatorVarsTabActivity.this.getAdapter().remove(editedInstance);
@ -363,7 +364,7 @@ public class CalculatorVarsTabActivity extends AbstractMathEntityListActivity<Va
if (isInCategory(var)) {
getAdapter().remove(var);
}
final AndroidVarsRegistry varsRegistry = CalculatorEngine.instance.getVarsRegister();
final AndroidMathRegistry<IConstant> varsRegistry = CalculatorEngine.instance.getVarsRegister();
varsRegistry.remove(var);
varsRegistry.save(CalculatorVarsTabActivity.this);
if (isInCategory(var)) {

View File

@ -331,7 +331,6 @@ public enum MathType {
public final static String INFINITY = "";
public final static String INFINITY_JSCL = "Infinity";
public static final List<String> constants = Arrays.asList(E, PI, C, G, H_REDUCED, IMAGINARY_NUMBER, NAN, INFINITY);
/**
* Method determines mathematical entity type for text substring starting from ith index

View File

@ -0,0 +1,71 @@
package org.solovyev.android.calculator.model;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;
import org.solovyev.common.utils.CollectionsUtils;
import org.solovyev.common.utils.StringMapper;
import java.util.List;
/**
* User: serso
* Date: 12/22/11
* Time: 5:25 PM
*/
@Root
public class AFunction implements MathPersistenceEntity {
@Element
@NotNull
private String name;
@Element
@NotNull
private String content;
@Element(required = false)
@Nullable
private String parameterNames;
@NotNull
public String getName() {
return name;
}
public void setName(@NotNull String name) {
this.name = name;
}
@NotNull
public String getContent() {
return content;
}
public void setContent(@NotNull String content) {
this.content = content;
}
@Nullable
public String getParameterNames() {
return parameterNames;
}
public void setParameterNames(@Nullable String[] parameterNames) {
this.parameterNames = CollectionsUtils.formatValue(CollectionsUtils.asList(parameterNames), ";", new StringMapper());
}
public void setParameterNames(@Nullable String parameterNames) {
this.parameterNames = parameterNames;
}
@NotNull
public String[] getParameterNamesAsArray() {
final List<String> parameterNamesAsList = CollectionsUtils.split(parameterNames, ";");
return parameterNamesAsList.toArray(new String[parameterNamesAsList.size()]);
}
}

View File

@ -0,0 +1,180 @@
/*
* Copyright (c) 2009-2011. Created by serso aka se.solovyev.
* For more information, please, contact se.solovyev@gmail.com
* or visit http://se.solovyev.org
*/
package org.solovyev.android.calculator.model;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;
import org.solovyev.android.view.prefs.ResourceCache;
import org.solovyev.common.definitions.IBuilder;
import org.solovyev.common.math.MathEntity;
import org.solovyev.common.math.MathRegistry;
import java.io.StringWriter;
import java.util.List;
import java.util.Map;
/**
* User: serso
* Date: 10/30/11
* Time: 1:03 AM
*/
public abstract class AbstractAndroidMathRegistry<T extends MathEntity, P extends MathPersistenceEntity> implements AndroidMathRegistry<T> {
@NotNull
private final MathRegistry<T> mathRegistry;
@NotNull
private final String prefix;
protected AbstractAndroidMathRegistry(@NotNull MathRegistry<T> mathRegistry, @NotNull String prefix) {
this.mathRegistry = mathRegistry;
this.prefix = prefix;
}
@NotNull
protected abstract Map<String, String> getSubstitutes();
@Nullable
@Override
public String getDescription(@NotNull Context context, @NotNull String mathEntityName) {
final String stringName;
final Map<String, String> substitutes = getSubstitutes();
final String substitute = substitutes.get(mathEntityName);
if (substitute == null) {
stringName = prefix + mathEntityName;
} else {
stringName = prefix + substitute;
}
return ResourceCache.instance.getCaption(stringName);
}
public synchronized void load(@Nullable Context context, @Nullable SharedPreferences preferences) {
if (context != null && preferences != null) {
final Integer preferenceStringId = getPreferenceStringId();
if (preferenceStringId != null) {
final String value = preferences.getString(context.getString(preferenceStringId), null);
if (value != null) {
final Serializer serializer = new Persister();
try {
final MathEntityPersistenceContainer<P> persistenceContainer = serializer.read(getPersistenceContainerClass(), value);
for (P entity : persistenceContainer.getEntities()) {
if (!contains(entity.getName())) {
add(createBuilder(entity));
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
}
/*Log.d(AndroidVarsRegistry.class.getName(), vars.size() + " variables registered!");
for (Var var : vars) {
Log.d(AndroidVarsRegistry.class.getName(), var.toString());
}*/
}
@NotNull
protected abstract IBuilder<? extends T> createBuilder(@NotNull P entity);
@NotNull
protected abstract Class<? extends MathEntityPersistenceContainer<P>> getPersistenceContainerClass();
@Nullable
protected abstract Integer getPreferenceStringId();
@Override
public synchronized void save(@NotNull Context context) {
final Integer preferenceStringId = getPreferenceStringId();
if (preferenceStringId != null) {
final SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
final SharedPreferences.Editor editor = settings.edit();
final MathEntityPersistenceContainer<P> container = createPersistenceContainer();
for (T entity : this.getEntities()) {
if (!entity.isSystem()) {
final P persistenceEntity = transform(entity);
if (persistenceEntity != null) {
container.getEntities().add(persistenceEntity);
}
}
}
final StringWriter sw = new StringWriter();
final Serializer serializer = new Persister();
try {
serializer.write(container, sw);
} catch (Exception e) {
throw new RuntimeException(e);
}
editor.putString(context.getString(preferenceStringId), sw.toString());
editor.commit();
}
}
@Nullable
protected abstract P transform(@NotNull T entity);
@NotNull
protected abstract MathEntityPersistenceContainer<P> createPersistenceContainer();
@NotNull
@Override
public List<T> getEntities() {
return mathRegistry.getEntities();
}
@NotNull
@Override
public List<T> getSystemEntities() {
return mathRegistry.getSystemEntities();
}
@Override
public T add(@NotNull IBuilder<? extends T> IBuilder) {
return mathRegistry.add(IBuilder);
}
@Override
public void remove(@NotNull T var) {
mathRegistry.remove(var);
}
@NotNull
@Override
public List<String> getNames() {
return mathRegistry.getNames();
}
@Override
public boolean contains(@NotNull String name) {
return mathRegistry.contains(name);
}
@Override
public T get(@NotNull String name) {
return mathRegistry.get(name);
}
@Override
public T getById(@NotNull Integer id) {
return mathRegistry.getById(id);
}
}

View File

@ -6,12 +6,13 @@
package org.solovyev.android.calculator.model;
import jscl.math.function.ArcTrigonometric;
import jscl.math.function.Comparison;
import jscl.math.function.Function;
import jscl.math.function.Trigonometric;
import android.content.Context;
import android.content.SharedPreferences;
import jscl.math.function.*;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.solovyev.android.calculator.R;
import org.solovyev.common.definitions.IBuilder;
import org.solovyev.common.math.MathRegistry;
import org.solovyev.common.utils.CollectionsUtils;
@ -22,7 +23,7 @@ import java.util.*;
* Date: 11/17/11
* Time: 11:28 PM
*/
public class AndroidFunctionsMathRegistry extends AndroidMathRegistryImpl<jscl.math.function.Function> {
public class AndroidFunctionsMathRegistry extends AbstractAndroidMathRegistry<Function, AFunction> {
public static enum Category {
@ -124,4 +125,40 @@ public class AndroidFunctionsMathRegistry extends AndroidMathRegistryImpl<jscl.m
return null;
}
@NotNull
@Override
protected IBuilder<? extends Function> createBuilder(@NotNull AFunction entity) {
return new CustomFunction.Builder(entity.getName(), entity.getParameterNamesAsArray(), entity.getContent());
}
@NotNull
@Override
protected Class<? extends MathEntityPersistenceContainer<AFunction>> getPersistenceContainerClass() {
return Functions.class;
}
@Override
protected Integer getPreferenceStringId() {
return R.string.p_calc_functions;
}
@Override
protected AFunction transform(@NotNull Function entity) {
if (entity instanceof CustomFunction) {
final AFunction result = new AFunction();
result.setName(entity.getName());
result.setContent(((CustomFunction) entity).getContent());
result.setParameterNames(((CustomFunction) entity).getParameterNames());
return result;
} else {
return null;
}
}
@NotNull
@Override
protected MathEntityPersistenceContainer<AFunction> createPersistenceContainer() {
return new Functions();
}
}

View File

@ -7,6 +7,7 @@
package org.solovyev.android.calculator.model;
import android.content.Context;
import android.content.SharedPreferences;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.solovyev.common.math.MathEntity;
@ -24,4 +25,8 @@ public interface AndroidMathRegistry<T extends MathEntity> extends MathRegistry<
@Nullable
String getCategory(@NotNull T mathEntity);
void load(@Nullable Context context, @Nullable SharedPreferences preferences);
void save(@NotNull Context context);
}

View File

@ -1,99 +0,0 @@
/*
* Copyright (c) 2009-2011. Created by serso aka se.solovyev.
* For more information, please, contact se.solovyev@gmail.com
* or visit http://se.solovyev.org
*/
package org.solovyev.android.calculator.model;
import android.content.Context;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.solovyev.android.view.prefs.ResourceCache;
import org.solovyev.common.definitions.IBuilder;
import org.solovyev.common.math.MathEntity;
import org.solovyev.common.math.MathRegistry;
import java.util.List;
import java.util.Map;
/**
* User: serso
* Date: 10/30/11
* Time: 1:03 AM
*/
public abstract class AndroidMathRegistryImpl<T extends MathEntity> implements AndroidMathRegistry<T> {
@NotNull
private final MathRegistry<T> functionsRegistry;
@NotNull
private final String prefix;
protected AndroidMathRegistryImpl(@NotNull MathRegistry<T> functionsRegistry, @NotNull String prefix) {
this.functionsRegistry = functionsRegistry;
this.prefix = prefix;
}
@NotNull
protected abstract Map<String, String> getSubstitutes();
@Nullable
@Override
public String getDescription(@NotNull Context context, @NotNull String mathEntityName) {
final String stringName;
final Map<String, String> substitutes = getSubstitutes();
final String substitute = substitutes.get(mathEntityName);
if (substitute == null) {
stringName = prefix + mathEntityName;
} else {
stringName = prefix + substitute;
}
return ResourceCache.instance.getCaption(stringName);
}
@NotNull
@Override
public List<T> getEntities() {
return functionsRegistry.getEntities();
}
@NotNull
@Override
public List<T> getSystemEntities() {
return functionsRegistry.getSystemEntities();
}
@Override
public T add(@NotNull IBuilder<? extends T> IBuilder) {
return functionsRegistry.add(IBuilder);
}
@Override
public void remove(@NotNull T var) {
functionsRegistry.remove(var);
}
@NotNull
@Override
public List<String> getNames() {
return functionsRegistry.getNames();
}
@Override
public boolean contains(@NotNull String name) {
return functionsRegistry.contains(name);
}
@Override
public T get(@NotNull String name) {
return functionsRegistry.get(name);
}
@Override
public T getById(@NotNull Integer id) {
return functionsRegistry.getById(id);
}
}

View File

@ -6,8 +6,12 @@
package org.solovyev.android.calculator.model;
import android.content.Context;
import android.content.SharedPreferences;
import jscl.math.operator.Operator;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.solovyev.common.definitions.IBuilder;
import org.solovyev.common.math.MathRegistry;
import java.util.HashMap;
@ -18,7 +22,7 @@ import java.util.Map;
* Date: 11/17/11
* Time: 11:29 PM
*/
public class AndroidOperatorsMathRegistry extends AndroidMathRegistryImpl<Operator> {
public class AndroidOperatorsMathRegistry extends AbstractAndroidMathRegistry<Operator, MathPersistenceEntity> {
@NotNull
private static final Map<String, String> substitutes = new HashMap<String, String>();
@ -48,4 +52,42 @@ public class AndroidOperatorsMathRegistry extends AndroidMathRegistryImpl<Operat
public String getCategory(@NotNull Operator mathEntity) {
return null;
}
@Override
public void load(@Nullable Context context, @Nullable SharedPreferences preferences) {
// not supported yet
}
@NotNull
@Override
protected IBuilder<? extends Operator> createBuilder(@NotNull MathPersistenceEntity entity) {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@NotNull
@Override
protected Class<? extends MathEntityPersistenceContainer<MathPersistenceEntity>> getPersistenceContainerClass() {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
protected Integer getPreferenceStringId() {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public void save(@NotNull Context context) {
// not supported yet
}
@Override
protected MathPersistenceEntity transform(@NotNull Operator entity) {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@NotNull
@Override
protected MathEntityPersistenceContainer<MathPersistenceEntity> createPersistenceContainer() {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
}

View File

@ -6,8 +6,12 @@
package org.solovyev.android.calculator.model;
import android.content.Context;
import android.content.SharedPreferences;
import jscl.math.operator.Operator;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.solovyev.common.definitions.IBuilder;
import org.solovyev.common.math.MathRegistry;
import java.util.HashMap;
@ -18,7 +22,7 @@ import java.util.Map;
* Date: 11/19/11
* Time: 1:48 PM
*/
public class AndroidPostfixFunctionsRegistry extends AndroidMathRegistryImpl<Operator> {
public class AndroidPostfixFunctionsRegistry extends AbstractAndroidMathRegistry<Operator, MathPersistenceEntity> {
@NotNull
private static final Map<String, String> substitutes = new HashMap<String, String>();
@ -47,4 +51,42 @@ public class AndroidPostfixFunctionsRegistry extends AndroidMathRegistryImpl<Ope
public String getCategory(@NotNull Operator mathEntity) {
return null;
}
@Override
public void load(@Nullable Context context, @Nullable SharedPreferences preferences) {
// not supported yet
}
@NotNull
@Override
protected IBuilder<? extends Operator> createBuilder(@NotNull MathPersistenceEntity entity) {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@NotNull
@Override
protected Class<? extends MathEntityPersistenceContainer<MathPersistenceEntity>> getPersistenceContainerClass() {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
protected Integer getPreferenceStringId() {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public void save(@NotNull Context context) {
// not supported yet
}
@Override
protected MathPersistenceEntity transform(@NotNull Operator entity) {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@NotNull
@Override
protected MathEntityPersistenceContainer<MathPersistenceEntity> createPersistenceContainer() {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
}

View File

@ -1,76 +0,0 @@
/*
* Copyright (c) 2009-2011. Created by serso aka se.solovyev.
* For more information, please, contact se.solovyev@gmail.com
* or visit http://se.solovyev.org
*/
package org.solovyev.android.calculator.model;
import android.content.Context;
import android.content.SharedPreferences;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.solovyev.android.calculator.R;
import org.solovyev.common.utils.CollectionsUtils;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* User: serso
* Date: 10/6/11
* Time: 9:31 PM
*/
public interface AndroidVarsRegistry extends AndroidMathRegistry<Var>{
public static enum Category {
system(R.string.c_var_system, 100){
@Override
boolean isInCategory(@NotNull Var var) {
return var.isSystem();
}
},
my(R.string.c_var_my, 0) {
@Override
boolean isInCategory(@NotNull Var var) {
return !var.isSystem();
}
};
private final int captionId;
private final int tabOrder;
Category(int captionId, int tabOrder) {
this.captionId = captionId;
this.tabOrder = tabOrder;
}
public int getCaptionId() {
return captionId;
}
abstract boolean isInCategory(@NotNull Var var);
@NotNull
public static List<Category> getCategoriesByTabOrder() {
final List<Category> result = CollectionsUtils.asList(Category.values());
Collections.sort(result, new Comparator<Category>() {
@Override
public int compare(Category category, Category category1) {
return category.tabOrder - category1.tabOrder;
}
});
return result;
}
}
void load(@Nullable Context context, @Nullable SharedPreferences preferences);
void save(@NotNull Context context);
}

View File

@ -15,92 +15,41 @@ import org.jetbrains.annotations.Nullable;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;
import org.solovyev.android.calculator.R;
import org.solovyev.android.calculator.math.MathType;
import org.solovyev.common.definitions.IBuilder;
import org.solovyev.common.math.MathRegistry;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import java.util.Map;
/**
* User: serso
* Date: 9/29/11
* Time: 4:57 PM
*/
class AndroidVarsRegistryImpl implements AndroidVarsRegistry {
class AndroidVarsRegistryImpl extends AbstractAndroidMathRegistry<IConstant, Var> {
@NotNull
private final MathRegistry<IConstant> mathRegistry;
private static final Map<String, String> substitutes = new HashMap<String, String>();
static {
substitutes.put("π", "pi");
substitutes.put("", "inf");
substitutes.put("h", "h_reduced");
substitutes.put("NaN", "nan");
}
protected AndroidVarsRegistryImpl(@NotNull MathRegistry<IConstant> mathRegistry) {
this.mathRegistry = mathRegistry;
super(mathRegistry, "c_var_description_");
}
@NotNull
@Override
protected Map<String, String> getSubstitutes() {
return substitutes;
}
public synchronized void load(@Nullable Context context, @Nullable SharedPreferences preferences) {
if (context != null && preferences != null) {
final String value = preferences.getString(context.getString(R.string.p_calc_vars), null);
if (value != null) {
final Serializer serializer = new Persister();
try {
final Vars vars = serializer.read(Vars.class, value);
for (Var var : vars.getVars()) {
if (!contains(var.getName())) {
add(new Var.Builder(var));
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
for (String systemVarName : MathType.constants) {
final Var.Builder builder;
final Integer varDescription;
if (systemVarName.equals(MathType.E)) {
builder = createBuilder(systemVarName, String.valueOf(Math.E));
varDescription = R.string.c_e_description;
} else if (systemVarName.equals(MathType.PI)) {
builder = createBuilder(systemVarName, String.valueOf(Math.PI));
varDescription = R.string.c_pi_description;
} else if (systemVarName.equals(MathType.C)) {
builder = createBuilder(systemVarName, String.valueOf(MathType.C_VALUE));
varDescription = R.string.c_c_description;
} else if (systemVarName.equals(MathType.G)) {
builder = createBuilder(systemVarName, String.valueOf(MathType.G_VALUE));
varDescription = R.string.c_g_description;
/* } else if (systemVarName.equals(MathType.H)) {
builder = new Var.Builder(systemVarName, MathType.H_VALUE);
varDescription = R.string.c_h_description;*/
} else if (systemVarName.equals(MathType.H_REDUCED)) {
builder = createBuilder(systemVarName, String.valueOf(MathType.H_REDUCED_VALUE));
varDescription = R.string.c_h_reduced_description;
} else if (systemVarName.equals(MathType.IMAGINARY_NUMBER)) {
builder = createBuilder(systemVarName, MathType.IMAGINARY_NUMBER_JSCL);
varDescription = R.string.c_i_description;
} else if (systemVarName.equals(MathType.NAN)) {
builder = createBuilder(systemVarName, MathType.NAN);
varDescription = R.string.c_nan_description;
} else if (systemVarName.equals(MathType.INFINITY)) {
builder = createBuilder(systemVarName, MathType.INFINITY_JSCL);
varDescription = R.string.c_infinity_description;
} else {
throw new IllegalArgumentException(systemVarName + " is not supported yet!");
}
builder.setSystem(true);
if (context != null) {
builder.setDescription(context.getString(varDescription));
}
add(builder);
}
super.load(context, preferences);
tryToAddAuxVar("x");
tryToAddAuxVar("y");
@ -114,140 +63,59 @@ class AndroidVarsRegistryImpl implements AndroidVarsRegistry {
}*/
}
@NotNull
@Override
protected IBuilder<? extends IConstant> createBuilder(@NotNull Var entity) {
return new Var.Builder(entity);
}
@NotNull
@Override
protected Class<? extends MathEntityPersistenceContainer<Var>> getPersistenceContainerClass() {
return Vars.class;
}
@NotNull
@Override
protected MathEntityPersistenceContainer<Var> createPersistenceContainer() {
return new Vars();
}
@NotNull
protected Integer getPreferenceStringId() {
return R.string.p_calc_vars;
}
private void tryToAddAuxVar(@NotNull String name) {
if ( !contains(name) ) {
add(new Var.Builder(name, (String)null));
}
}
private Var.Builder createBuilder(@NotNull String varName, @NotNull String varValue) {
final Var.Builder result;
final IConstant varFromRegistry = mathRegistry.get(varName);
if (varFromRegistry == null) {
result = new Var.Builder(varName, varValue);
} else {
result = new Var.Builder(varFromRegistry);
}
return result;
}
@Override
public synchronized void save(@NotNull Context context) {
final SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
final SharedPreferences.Editor editor = settings.edit();
final Vars vars = new Vars();
for (Var var : this.getEntities()) {
if (!var.isSystem()) {
vars.getVars().add(var);
}
}
final StringWriter sw = new StringWriter();
final Serializer serializer = new Persister();
try {
serializer.write(vars, sw);
} catch (Exception e) {
throw new RuntimeException(e);
}
editor.putString(context.getString(R.string.p_calc_vars), sw.toString());
editor.commit();
}
@NotNull
@Override
public List<Var> getEntities() {
final List<Var> result = new ArrayList<Var>();
for (IConstant iConstant : mathRegistry.getEntities()) {
result.add(transform(iConstant));
}
return result;
}
@NotNull
@Override
public List<Var> getSystemEntities() {
final List<Var> result = new ArrayList<Var>();
for (IConstant iConstant : mathRegistry.getSystemEntities()) {
result.add(transform(iConstant));
}
return result;
}
@Override
public Var add(@NotNull IBuilder<? extends Var> IBuilder) {
IConstant result = mathRegistry.add(IBuilder);
if (result instanceof Var) {
return (Var) result;
} else if (result != null) {
return transform(result);
protected Var transform(@NotNull IConstant entity) {
if (entity instanceof Var) {
return (Var) entity;
} else {
return null;
}
}
@NotNull
private Var transform(@NotNull IConstant result) {
return new Var.Builder(result).create();
}
@Override
public void remove(@NotNull Var var) {
mathRegistry.remove(var);
}
@NotNull
@Override
public List<String> getNames() {
return mathRegistry.getNames();
}
@Override
public boolean contains(@NotNull String name) {
return mathRegistry.contains(name);
}
@Override
public Var get(@NotNull String name) {
IConstant result = mathRegistry.get(name);
if (result instanceof Var) {
return (Var) result;
} else if (result != null) {
return transform(result);
} else {
return null;
return new Var.Builder(entity).create();
}
}
@Override
public Var getById(@NotNull Integer id) {
final IConstant result = mathRegistry.getById(id);
if (result instanceof Var) {
return (Var) result;
} else if (result != null) {
return transform(result);
} else {
return null;
}
}
@Override
public String getDescription(@NotNull Context context, @NotNull String mathEntityName) {
final Var var = get(mathEntityName);
if (var != null) {
final IConstant var = get(mathEntityName);
if (var != null && !var.isSystem()) {
return var.getDescription();
} else {
return null;
return super.getDescription(context, mathEntityName);
}
}
@Override
public String getCategory(@NotNull Var var) {
for (Category category : Category.values()) {
public String getCategory(@NotNull IConstant var) {
for (VarCategory category : VarCategory.values()) {
if ( category.isInCategory(var) ) {
return category.name();
}

View File

@ -10,6 +10,7 @@ import android.content.SharedPreferences;
import jscl.*;
import jscl.math.Generic;
import jscl.math.function.Function;
import jscl.math.function.IConstant;
import jscl.math.operator.Operator;
import jscl.text.ParseInterruptedException;
import org.jetbrains.annotations.NotNull;
@ -64,7 +65,7 @@ public enum CalculatorEngine {
public final TextProcessor<PreparedExpression, String> preprocessor = new ToJsclTextProcessor();
@NotNull
private final AndroidVarsRegistry varsRegister = new AndroidVarsRegistryImpl(engine.getConstantsRegistry());
private final AndroidMathRegistry<IConstant> varsRegister = new AndroidVarsRegistryImpl(engine.getConstantsRegistry());
@NotNull
private final AndroidMathRegistry<jscl.math.function.Function> functionsRegistry = new AndroidFunctionsMathRegistry(engine.getFunctionsRegistry());
@ -304,7 +305,7 @@ public enum CalculatorEngine {
}
@NotNull
public AndroidVarsRegistry getVarsRegister() {
public AndroidMathRegistry<IConstant> getVarsRegister() {
return varsRegister;
}

View File

@ -0,0 +1,29 @@
package org.solovyev.android.calculator.model;
import jscl.math.function.CustomFunction;
import jscl.math.function.Function;
import jscl.math.function.IConstant;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;
import java.util.ArrayList;
import java.util.List;
/**
* User: serso
* Date: 12/22/11
* Time: 5:15 PM
*/
@Root
public class Functions implements MathEntityPersistenceContainer<AFunction> {
@ElementList(type = CustomFunction.class)
private List<AFunction> functions = new ArrayList<AFunction>();
public Functions() {
}
public List<AFunction> getEntities() {
return functions;
}
}

View File

@ -0,0 +1,12 @@
package org.solovyev.android.calculator.model;
import java.util.List;
/**
* User: serso
* Date: 12/22/11
* Time: 5:03 PM
*/
public interface MathEntityPersistenceContainer<T extends MathPersistenceEntity> {
public List<T> getEntities();
}

View File

@ -0,0 +1,14 @@
package org.solovyev.android.calculator.model;
import org.jetbrains.annotations.NotNull;
/**
* User: serso
* Date: 12/22/11
* Time: 5:27 PM
*/
public interface MathPersistenceEntity {
@NotNull
String getName();
}

View File

@ -6,6 +6,7 @@
package org.solovyev.android.calculator.model;
import jscl.math.function.IConstant;
import org.jetbrains.annotations.NotNull;
import java.util.List;
@ -21,9 +22,9 @@ public class PreparedExpression implements CharSequence{
private String expression;
@NotNull
private List<Var> undefinedVars;
private List<IConstant> undefinedVars;
public PreparedExpression(@NotNull String expression, @NotNull List<Var> undefinedVars) {
public PreparedExpression(@NotNull String expression, @NotNull List<IConstant> undefinedVars) {
this.expression = expression;
this.undefinedVars = undefinedVars;
}
@ -38,7 +39,7 @@ public class PreparedExpression implements CharSequence{
}
@NotNull
public List<Var> getUndefinedVars() {
public List<IConstant> getUndefinedVars() {
return undefinedVars;
}

View File

@ -6,6 +6,7 @@
package org.solovyev.android.calculator.model;
import jscl.math.function.IConstant;
import org.jetbrains.annotations.NotNull;
import org.solovyev.android.calculator.StartsWithFinder;
import org.solovyev.android.calculator.math.MathType;
@ -22,10 +23,10 @@ class ToJsclTextProcessor implements TextProcessor<PreparedExpression, String> {
@Override
@NotNull
public PreparedExpression process(@NotNull String s) throws CalculatorParseException {
return processWithDepth(s, 0, new ArrayList<Var>());
return processWithDepth(s, 0, new ArrayList<IConstant>());
}
private static PreparedExpression processWithDepth(@NotNull String s, int depth, @NotNull List<Var> undefinedVars) throws CalculatorParseException {
private static PreparedExpression processWithDepth(@NotNull String s, int depth, @NotNull List<IConstant> undefinedVars) throws CalculatorParseException {
return replaceVariables(processExpression(s).toString(), depth, undefinedVars);
}
@ -69,7 +70,7 @@ class ToJsclTextProcessor implements TextProcessor<PreparedExpression, String> {
}
@NotNull
private static PreparedExpression replaceVariables(@NotNull final String s, int depth, @NotNull List<Var> undefinedVars) throws CalculatorParseException {
private static PreparedExpression replaceVariables(@NotNull final String s, int depth, @NotNull List<IConstant> undefinedVars) throws CalculatorParseException {
if (depth >= MAX_DEPTH) {
throw new CalculatorParseException(Messages.msg_6, s);
} else {
@ -89,7 +90,7 @@ class ToJsclTextProcessor implements TextProcessor<PreparedExpression, String> {
if (operatorName == null) {
String varName = CollectionsUtils.find(CalculatorEngine.instance.getVarsRegister().getNames(), startsWithFinder);
if (varName != null) {
final Var var = CalculatorEngine.instance.getVarsRegister().get(varName);
final IConstant var = CalculatorEngine.instance.getVarsRegister().get(varName);
if (var != null) {
if (!var.isDefined()) {
undefinedVars.add(var);

View File

@ -25,7 +25,7 @@ import org.solovyev.common.utils.StringUtils;
*/
@Root
public class Var implements IConstant {
public class Var implements IConstant, MathPersistenceEntity {
@Transient
private Integer id;
@ -225,17 +225,7 @@ public class Var implements IConstant {
@Override
public String toString() {
final Double doubleValue = getDoubleValue();
if (doubleValue == null) {
final String stringValue = getValue();
if (!StringUtils.isEmpty(stringValue)) {
return getName() + " = " + stringValue;
} else {
return getName();
}
} else {
return getName() + " = " + doubleValue;
}
return ExtendedConstant.toString(this);
}
@Override

View File

@ -0,0 +1,61 @@
package org.solovyev.android.calculator.model;
import jscl.math.function.IConstant;
import org.jetbrains.annotations.NotNull;
import org.solovyev.android.calculator.R;
import org.solovyev.common.utils.CollectionsUtils;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* User: serso
* Date: 12/22/11
* Time: 4:25 PM
*/
public enum VarCategory {
system(R.string.c_var_system, 100){
@Override
boolean isInCategory(@NotNull IConstant var) {
return var.isSystem();
}
},
my(R.string.c_var_my, 0) {
@Override
boolean isInCategory(@NotNull IConstant var) {
return !var.isSystem();
}
};
private final int captionId;
private final int tabOrder;
VarCategory(int captionId, int tabOrder) {
this.captionId = captionId;
this.tabOrder = tabOrder;
}
public int getCaptionId() {
return captionId;
}
abstract boolean isInCategory(@NotNull IConstant var);
@NotNull
public static List<VarCategory> getCategoriesByTabOrder() {
final List<VarCategory> result = CollectionsUtils.asList(VarCategory.values());
Collections.sort(result, new Comparator<VarCategory>() {
@Override
public int compare(VarCategory category, VarCategory category1) {
return category.tabOrder - category1.tabOrder;
}
});
return result;
}
}

View File

@ -1,5 +1,6 @@
package org.solovyev.android.calculator.model;
import jscl.math.function.IConstant;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;
@ -13,15 +14,15 @@ import java.util.List;
*/
@Root
public class Vars {
public class Vars implements MathEntityPersistenceContainer<Var> {
@ElementList
@ElementList(type = Var.class)
private List<Var> vars = new ArrayList<Var>();
public Vars() {
}
public List<Var> getVars() {
public List<Var> getEntities() {
return vars;
}
}

View File

@ -6,6 +6,7 @@
package org.solovyev.android.calculator.model;
import jscl.math.function.IConstant;
import junit.framework.Assert;
import org.junit.Test;
import org.simpleframework.xml.Serializer;
@ -40,9 +41,9 @@ public class VarTest {
public void testXml() throws Exception {
final Vars vars = new Vars();
Var first = new Var.Builder("e", Math.E).setDescription("description").setSystem(true).create();
vars.getVars().add(first);
vars.getEntities().add(first);
Var second = new Var.Builder(";", 3d).setSystem(true).create();
vars.getVars().add(second);
vars.getEntities().add(second);
final StringWriter sw = new StringWriter();
final Serializer serializer = new Persister();
@ -50,17 +51,16 @@ public class VarTest {
Assert.assertEquals(xml, sw.toString());
final Vars result = serializer.read(Vars.class, xml);
final Var actualFirst = result.getVars().get(0);
final Var actualSecond = result.getVars().get(1);
final IConstant actualFirst = result.getEntities().get(0);
final IConstant actualSecond = result.getEntities().get(1);
areEqual(first, actualFirst);
areEqual(second, actualSecond);
}
private void areEqual(Var expected, Var actual) {
private void areEqual(IConstant expected, IConstant actual) {
Assert.assertEquals(expected.getName(), actual.getName());
Assert.assertEquals(expected.getDescription(), actual.getDescription());
Assert.assertEquals(expected.getValue(), actual.getValue());