target
stringlengths 20
113k
| src_fm
stringlengths 11
86.3k
| src_fm_fc
stringlengths 21
86.4k
| src_fm_fc_co
stringlengths 30
86.4k
| src_fm_fc_ms
stringlengths 42
86.8k
| src_fm_fc_ms_ff
stringlengths 43
86.8k
|
---|---|---|---|---|---|
@Test public void testEvaluateAlgorithmsCommandWithSystemConfigWithUnknownEvaluationIdentifier() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { String inCorrectresult = String.format( TestUtils.getStringByReflection(EvaluateAlgorithmsCommand.class, REFLECTION_EVALUATION_IDENTIFIER_UNKNOWN_ERROR_MESSAGE), INCORRECT_EVALUATION_IDENTIFIER); runSystemConfigCommandWithFile(getTestRessourcePathFor(SYSTEM_CONFIG_COMPLETE_WITH_UNKNOWN_EVALUATION_IDENTIFIER)); currentCommand = new String[] { ECommand.EVALUATE_ALGORITHMS.getCommandIdentifier() }; String consoleOutput = TestUtils.simulateCommandLineInputAndReturnConsoleOutput(currentCommand); logger.debug(String.format(EVALUATIONS_CONSOLE_OUTPUT, consoleOutput)); Pair<ICommand, CommandResult> commandAndResult = TestUtils.getLatestPairOfCommandAndCommandResultInCommandHistory(); ICommand command = commandAndResult.getFirst(); CommandResult commandResult = commandAndResult.getSecond(); assertTrue(commandResult != null); assertTrue(command.canBeExecuted()); TestUtils.assertCorrectFailedEmptyCommandResult(commandResult, UnknownEvaluationIdentifierException.class); assertTrue(commandResult.getException().getMessage().equals(inCorrectresult)); } | @Override public boolean canBeExecuted() { try { checkInitialParametersForCommandExecution(); } catch (CommandCannotBeExecutedException commandCannotBeExecuted) { failureReason = String.format(COMMAND_CANNOT_BE_EXECUTED_ERROR_MESSAGE, commandCannotBeExecuted.getMessage()); logger.error(failureReason, commandCannotBeExecuted); } return canBeExecuted; } | EvaluateAlgorithmsCommand extends ACommand { @Override public boolean canBeExecuted() { try { checkInitialParametersForCommandExecution(); } catch (CommandCannotBeExecutedException commandCannotBeExecuted) { failureReason = String.format(COMMAND_CANNOT_BE_EXECUTED_ERROR_MESSAGE, commandCannotBeExecuted.getMessage()); logger.error(failureReason, commandCannotBeExecuted); } return canBeExecuted; } } | EvaluateAlgorithmsCommand extends ACommand { @Override public boolean canBeExecuted() { try { checkInitialParametersForCommandExecution(); } catch (CommandCannotBeExecutedException commandCannotBeExecuted) { failureReason = String.format(COMMAND_CANNOT_BE_EXECUTED_ERROR_MESSAGE, commandCannotBeExecuted.getMessage()); logger.error(failureReason, commandCannotBeExecuted); } return canBeExecuted; } EvaluateAlgorithmsCommand(String evaluationIdentifierHandler, List<String> metricIdentifierHandler); } | EvaluateAlgorithmsCommand extends ACommand { @Override public boolean canBeExecuted() { try { checkInitialParametersForCommandExecution(); } catch (CommandCannotBeExecutedException commandCannotBeExecuted) { failureReason = String.format(COMMAND_CANNOT_BE_EXECUTED_ERROR_MESSAGE, commandCannotBeExecuted.getMessage()); logger.error(failureReason, commandCannotBeExecuted); } return canBeExecuted; } EvaluateAlgorithmsCommand(String evaluationIdentifierHandler, List<String> metricIdentifierHandler); @Override boolean canBeExecuted(); @Override CommandResult executeCommand(); @Override String getFailureReason(); @Override void undo(); static JsonObject getEvalautionMetricJsonArray(List<EvaluationMetricJsonElement> evaluationMetricElementArray); IEvaluation getEvaluation(); } | EvaluateAlgorithmsCommand extends ACommand { @Override public boolean canBeExecuted() { try { checkInitialParametersForCommandExecution(); } catch (CommandCannotBeExecutedException commandCannotBeExecuted) { failureReason = String.format(COMMAND_CANNOT_BE_EXECUTED_ERROR_MESSAGE, commandCannotBeExecuted.getMessage()); logger.error(failureReason, commandCannotBeExecuted); } return canBeExecuted; } EvaluateAlgorithmsCommand(String evaluationIdentifierHandler, List<String> metricIdentifierHandler); @Override boolean canBeExecuted(); @Override CommandResult executeCommand(); @Override String getFailureReason(); @Override void undo(); static JsonObject getEvalautionMetricJsonArray(List<EvaluationMetricJsonElement> evaluationMetricElementArray); IEvaluation getEvaluation(); } |
@Test @Override public void testCorrectParameters() throws JsonParsingFailedException { List<JsonObject> listOfJsonObjects = getCorrectParameters(); for (int i = 0; i < listOfJsonObjects.size(); i++) { IDistribution<SPACE> distribution = getDistribution(); try { distribution.setParameters(listOfJsonObjects.get(i)); } catch (ParameterValidationFailedException e) { fail(String.format(ERROR_CORRECT_PARAMETER_NOT_ACCEPTED, listOfJsonObjects.get(i))); } } } | @Override public void setParameters(JsonObject jsonObject) throws ParameterValidationFailedException { getDistributionConfiguration().overrideConfiguration(jsonObject); } | ADistribution implements IDistribution<SPACE> { @Override public void setParameters(JsonObject jsonObject) throws ParameterValidationFailedException { getDistributionConfiguration().overrideConfiguration(jsonObject); } } | ADistribution implements IDistribution<SPACE> { @Override public void setParameters(JsonObject jsonObject) throws ParameterValidationFailedException { getDistributionConfiguration().overrideConfiguration(jsonObject); } ADistribution(); } | ADistribution implements IDistribution<SPACE> { @Override public void setParameters(JsonObject jsonObject) throws ParameterValidationFailedException { getDistributionConfiguration().overrideConfiguration(jsonObject); } ADistribution(); @Override List<SPACE> generateSamples(int numberOfSamples); abstract CONFIG createDefaultDistributionConfiguration(); @Override ADistributionConfiguration getDefaultDistributionConfiguration(); @Override @SuppressWarnings("unchecked") void setDistributionConfiguration(ADistributionConfiguration algorithmConfiguration); @Override @SuppressWarnings("unchecked") CONFIG getDistributionConfiguration(); @Override void setParameters(JsonObject jsonObject); @Override String toString(); } | ADistribution implements IDistribution<SPACE> { @Override public void setParameters(JsonObject jsonObject) throws ParameterValidationFailedException { getDistributionConfiguration().overrideConfiguration(jsonObject); } ADistribution(); @Override List<SPACE> generateSamples(int numberOfSamples); abstract CONFIG createDefaultDistributionConfiguration(); @Override ADistributionConfiguration getDefaultDistributionConfiguration(); @Override @SuppressWarnings("unchecked") void setDistributionConfiguration(ADistributionConfiguration algorithmConfiguration); @Override @SuppressWarnings("unchecked") CONFIG getDistributionConfiguration(); @Override void setParameters(JsonObject jsonObject); @Override String toString(); } |
@Test public void testEvaluateAlgorithmsCommandWithSystemConfigHaveNoEvaluation() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { String inCorrectresult = String.format( TestUtils.getStringByReflection(EvaluateAlgorithmsCommand.class, REFLECTION_EVALUATION_FOR_LEARNINGPROBLEM_NOT_EXIST_ERROR_MESSAGE), EvaluationsKeyValuePairs.EVALUATION_PERCENTAGE_SPLIT_IDENTIFIER, ELearningProblem.RANK_AGGREGATION.getLearningProblemIdentifier()); runSystemConfigCommandWithFileWithoutTrainingModels(getTestRessourcePathFor(SYSTEM_CONFIG_COMPLETE_WITH_NO_EVALUATION)); currentCommand = new String[] { ECommand.EVALUATE_ALGORITHMS.getCommandIdentifier() }; String consoleOutput = TestUtils.simulateCommandLineInputAndReturnConsoleOutput(currentCommand); logger.debug(String.format(EVALUATIONS_CONSOLE_OUTPUT, consoleOutput)); Pair<ICommand, CommandResult> commandAndResult = TestUtils.getLatestPairOfCommandAndCommandResultInCommandHistory(); ICommand command = commandAndResult.getFirst(); CommandResult commandResult = commandAndResult.getSecond(); assertTrue(commandResult != null); assertTrue(command.canBeExecuted()); TestUtils.assertCorrectFailedEmptyCommandResult(commandResult, EvaluationDoesnotExistForLearningProblemException.class); assertTrue(commandResult.getException().getMessage().equals(inCorrectresult)); } | @Override public boolean canBeExecuted() { try { checkInitialParametersForCommandExecution(); } catch (CommandCannotBeExecutedException commandCannotBeExecuted) { failureReason = String.format(COMMAND_CANNOT_BE_EXECUTED_ERROR_MESSAGE, commandCannotBeExecuted.getMessage()); logger.error(failureReason, commandCannotBeExecuted); } return canBeExecuted; } | EvaluateAlgorithmsCommand extends ACommand { @Override public boolean canBeExecuted() { try { checkInitialParametersForCommandExecution(); } catch (CommandCannotBeExecutedException commandCannotBeExecuted) { failureReason = String.format(COMMAND_CANNOT_BE_EXECUTED_ERROR_MESSAGE, commandCannotBeExecuted.getMessage()); logger.error(failureReason, commandCannotBeExecuted); } return canBeExecuted; } } | EvaluateAlgorithmsCommand extends ACommand { @Override public boolean canBeExecuted() { try { checkInitialParametersForCommandExecution(); } catch (CommandCannotBeExecutedException commandCannotBeExecuted) { failureReason = String.format(COMMAND_CANNOT_BE_EXECUTED_ERROR_MESSAGE, commandCannotBeExecuted.getMessage()); logger.error(failureReason, commandCannotBeExecuted); } return canBeExecuted; } EvaluateAlgorithmsCommand(String evaluationIdentifierHandler, List<String> metricIdentifierHandler); } | EvaluateAlgorithmsCommand extends ACommand { @Override public boolean canBeExecuted() { try { checkInitialParametersForCommandExecution(); } catch (CommandCannotBeExecutedException commandCannotBeExecuted) { failureReason = String.format(COMMAND_CANNOT_BE_EXECUTED_ERROR_MESSAGE, commandCannotBeExecuted.getMessage()); logger.error(failureReason, commandCannotBeExecuted); } return canBeExecuted; } EvaluateAlgorithmsCommand(String evaluationIdentifierHandler, List<String> metricIdentifierHandler); @Override boolean canBeExecuted(); @Override CommandResult executeCommand(); @Override String getFailureReason(); @Override void undo(); static JsonObject getEvalautionMetricJsonArray(List<EvaluationMetricJsonElement> evaluationMetricElementArray); IEvaluation getEvaluation(); } | EvaluateAlgorithmsCommand extends ACommand { @Override public boolean canBeExecuted() { try { checkInitialParametersForCommandExecution(); } catch (CommandCannotBeExecutedException commandCannotBeExecuted) { failureReason = String.format(COMMAND_CANNOT_BE_EXECUTED_ERROR_MESSAGE, commandCannotBeExecuted.getMessage()); logger.error(failureReason, commandCannotBeExecuted); } return canBeExecuted; } EvaluateAlgorithmsCommand(String evaluationIdentifierHandler, List<String> metricIdentifierHandler); @Override boolean canBeExecuted(); @Override CommandResult executeCommand(); @Override String getFailureReason(); @Override void undo(); static JsonObject getEvalautionMetricJsonArray(List<EvaluationMetricJsonElement> evaluationMetricElementArray); IEvaluation getEvaluation(); } |
@Test public void testEvaluateAlgorithmsCommandWithSystemConfigWithNoAlgorithmsSet() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { runSystemConfigCommandWithFileWithoutLoadingAlgorithms(getTestRessourcePathFor(SYSTEM_CONFIG_JSON_FILE)); currentCommand = new String[] { ECommand.EVALUATE_ALGORITHMS.getCommandIdentifier() }; String consoleOutput = TestUtils.simulateCommandLineInputAndReturnConsoleOutput(currentCommand); logger.debug(String.format(EVALUATIONS_CONSOLE_OUTPUT, consoleOutput)); Pair<ICommand, CommandResult> commandAndResult = TestUtils.getLatestPairOfCommandAndCommandResultInCommandHistory(); ICommand command = commandAndResult.getFirst(); CommandResult commandResult = commandAndResult.getSecond(); assertTrue(commandResult != null); assertTrue(command.canBeExecuted()); TestUtils.assertCorrectFailedEmptyCommandResult(commandResult, DatasetsOrLearningAlgorithmsNotSetForEvaluationException.class); String inCorrectresult = String.format( StringUtils.LINE_BREAK + TestUtils.getStringByReflection(EvaluateAlgorithmsCommand.class, REFLECTION_LEARNING_ALGORITHMS_ERROR_MESSAGE), EEvaluation.SUPPLIED_TEST_SET_RANK_AGGREGATION.getEvaluationIdentifier()); assertTrue(commandResult.getException().getMessage().equals(inCorrectresult)); } | @Override public boolean canBeExecuted() { try { checkInitialParametersForCommandExecution(); } catch (CommandCannotBeExecutedException commandCannotBeExecuted) { failureReason = String.format(COMMAND_CANNOT_BE_EXECUTED_ERROR_MESSAGE, commandCannotBeExecuted.getMessage()); logger.error(failureReason, commandCannotBeExecuted); } return canBeExecuted; } | EvaluateAlgorithmsCommand extends ACommand { @Override public boolean canBeExecuted() { try { checkInitialParametersForCommandExecution(); } catch (CommandCannotBeExecutedException commandCannotBeExecuted) { failureReason = String.format(COMMAND_CANNOT_BE_EXECUTED_ERROR_MESSAGE, commandCannotBeExecuted.getMessage()); logger.error(failureReason, commandCannotBeExecuted); } return canBeExecuted; } } | EvaluateAlgorithmsCommand extends ACommand { @Override public boolean canBeExecuted() { try { checkInitialParametersForCommandExecution(); } catch (CommandCannotBeExecutedException commandCannotBeExecuted) { failureReason = String.format(COMMAND_CANNOT_BE_EXECUTED_ERROR_MESSAGE, commandCannotBeExecuted.getMessage()); logger.error(failureReason, commandCannotBeExecuted); } return canBeExecuted; } EvaluateAlgorithmsCommand(String evaluationIdentifierHandler, List<String> metricIdentifierHandler); } | EvaluateAlgorithmsCommand extends ACommand { @Override public boolean canBeExecuted() { try { checkInitialParametersForCommandExecution(); } catch (CommandCannotBeExecutedException commandCannotBeExecuted) { failureReason = String.format(COMMAND_CANNOT_BE_EXECUTED_ERROR_MESSAGE, commandCannotBeExecuted.getMessage()); logger.error(failureReason, commandCannotBeExecuted); } return canBeExecuted; } EvaluateAlgorithmsCommand(String evaluationIdentifierHandler, List<String> metricIdentifierHandler); @Override boolean canBeExecuted(); @Override CommandResult executeCommand(); @Override String getFailureReason(); @Override void undo(); static JsonObject getEvalautionMetricJsonArray(List<EvaluationMetricJsonElement> evaluationMetricElementArray); IEvaluation getEvaluation(); } | EvaluateAlgorithmsCommand extends ACommand { @Override public boolean canBeExecuted() { try { checkInitialParametersForCommandExecution(); } catch (CommandCannotBeExecutedException commandCannotBeExecuted) { failureReason = String.format(COMMAND_CANNOT_BE_EXECUTED_ERROR_MESSAGE, commandCannotBeExecuted.getMessage()); logger.error(failureReason, commandCannotBeExecuted); } return canBeExecuted; } EvaluateAlgorithmsCommand(String evaluationIdentifierHandler, List<String> metricIdentifierHandler); @Override boolean canBeExecuted(); @Override CommandResult executeCommand(); @Override String getFailureReason(); @Override void undo(); static JsonObject getEvalautionMetricJsonArray(List<EvaluationMetricJsonElement> evaluationMetricElementArray); IEvaluation getEvaluation(); } |
@Test public void testEvaluateAlgorithmsCommandWithSystemConfigWithNoSetupForEvaluation() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { runSystemConfigCommandWithFileWithoutTrainingModels(getTestRessourcePathFor(SYSTEM_CONFIG_COMPLETE_WITH_SETUP_PROBLEM_IN_EVALUATION)); currentCommand = new String[] { ECommand.EVALUATE_ALGORITHMS.getCommandIdentifier() }; String consoleOutput = TestUtils.simulateCommandLineInputAndReturnConsoleOutput(currentCommand); logger.debug(String.format(EVALUATIONS_CONSOLE_OUTPUT, consoleOutput)); Pair<ICommand, CommandResult> commandAndResult = TestUtils.getLatestPairOfCommandAndCommandResultInCommandHistory(); ICommand command = commandAndResult.getFirst(); CommandResult commandResult = commandAndResult.getSecond(); assertTrue(commandResult != null); assertTrue(command.canBeExecuted()); TestUtils.assertCorrectFailedEmptyCommandResult(commandResult, CouldNotSetupEvaluationException.class); String inCorrectresult = String.format( TestUtils.getStringByReflection(EvaluateAlgorithmsCommand.class, REFLECTION_COULDNOT_SETUP_EVALUATION_ERROR_MESSAGE), EvaluationsKeyValuePairs.EVALUATION_USE_TRAINING_DATASET_IDENTIFIER); assertTrue(commandResult.getException().getMessage().equals(inCorrectresult)); } | @Override public boolean canBeExecuted() { try { checkInitialParametersForCommandExecution(); } catch (CommandCannotBeExecutedException commandCannotBeExecuted) { failureReason = String.format(COMMAND_CANNOT_BE_EXECUTED_ERROR_MESSAGE, commandCannotBeExecuted.getMessage()); logger.error(failureReason, commandCannotBeExecuted); } return canBeExecuted; } | EvaluateAlgorithmsCommand extends ACommand { @Override public boolean canBeExecuted() { try { checkInitialParametersForCommandExecution(); } catch (CommandCannotBeExecutedException commandCannotBeExecuted) { failureReason = String.format(COMMAND_CANNOT_BE_EXECUTED_ERROR_MESSAGE, commandCannotBeExecuted.getMessage()); logger.error(failureReason, commandCannotBeExecuted); } return canBeExecuted; } } | EvaluateAlgorithmsCommand extends ACommand { @Override public boolean canBeExecuted() { try { checkInitialParametersForCommandExecution(); } catch (CommandCannotBeExecutedException commandCannotBeExecuted) { failureReason = String.format(COMMAND_CANNOT_BE_EXECUTED_ERROR_MESSAGE, commandCannotBeExecuted.getMessage()); logger.error(failureReason, commandCannotBeExecuted); } return canBeExecuted; } EvaluateAlgorithmsCommand(String evaluationIdentifierHandler, List<String> metricIdentifierHandler); } | EvaluateAlgorithmsCommand extends ACommand { @Override public boolean canBeExecuted() { try { checkInitialParametersForCommandExecution(); } catch (CommandCannotBeExecutedException commandCannotBeExecuted) { failureReason = String.format(COMMAND_CANNOT_BE_EXECUTED_ERROR_MESSAGE, commandCannotBeExecuted.getMessage()); logger.error(failureReason, commandCannotBeExecuted); } return canBeExecuted; } EvaluateAlgorithmsCommand(String evaluationIdentifierHandler, List<String> metricIdentifierHandler); @Override boolean canBeExecuted(); @Override CommandResult executeCommand(); @Override String getFailureReason(); @Override void undo(); static JsonObject getEvalautionMetricJsonArray(List<EvaluationMetricJsonElement> evaluationMetricElementArray); IEvaluation getEvaluation(); } | EvaluateAlgorithmsCommand extends ACommand { @Override public boolean canBeExecuted() { try { checkInitialParametersForCommandExecution(); } catch (CommandCannotBeExecutedException commandCannotBeExecuted) { failureReason = String.format(COMMAND_CANNOT_BE_EXECUTED_ERROR_MESSAGE, commandCannotBeExecuted.getMessage()); logger.error(failureReason, commandCannotBeExecuted); } return canBeExecuted; } EvaluateAlgorithmsCommand(String evaluationIdentifierHandler, List<String> metricIdentifierHandler); @Override boolean canBeExecuted(); @Override CommandResult executeCommand(); @Override String getFailureReason(); @Override void undo(); static JsonObject getEvalautionMetricJsonArray(List<EvaluationMetricJsonElement> evaluationMetricElementArray); IEvaluation getEvaluation(); } |
@Test public void testRunCompleteToolChainCommand() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { String command[] = { ECommand.RUN_COMPLETE_TOOLCHAIN.getCommandIdentifier(), PARAMETER_CONFIG + getTestRessourcePathFor(CORRECT_SYSTEM_CONFIG_JSON) }; TestUtils.simulateCommandLineInput(command); assertCorrectCommandResultAsLatestInCommandHistory(); } | public RunCompleteToolChainCommand(RunCompleteToolChainCommandConfiguration commandConfiguration) { super(ECommand.RUN_COMPLETE_TOOLCHAIN.getCommandIdentifier()); this.commandConfiguration = commandConfiguration; toolChainCommands = new ArrayList<>(); commandExecutionSuccessPairs = new ArrayList<>(); inputControl = InputControl.getInputControl(); systemStatus = SystemStatus.getSystemStatus(); } | RunCompleteToolChainCommand extends ACommand { public RunCompleteToolChainCommand(RunCompleteToolChainCommandConfiguration commandConfiguration) { super(ECommand.RUN_COMPLETE_TOOLCHAIN.getCommandIdentifier()); this.commandConfiguration = commandConfiguration; toolChainCommands = new ArrayList<>(); commandExecutionSuccessPairs = new ArrayList<>(); inputControl = InputControl.getInputControl(); systemStatus = SystemStatus.getSystemStatus(); } } | RunCompleteToolChainCommand extends ACommand { public RunCompleteToolChainCommand(RunCompleteToolChainCommandConfiguration commandConfiguration) { super(ECommand.RUN_COMPLETE_TOOLCHAIN.getCommandIdentifier()); this.commandConfiguration = commandConfiguration; toolChainCommands = new ArrayList<>(); commandExecutionSuccessPairs = new ArrayList<>(); inputControl = InputControl.getInputControl(); systemStatus = SystemStatus.getSystemStatus(); } RunCompleteToolChainCommand(RunCompleteToolChainCommandConfiguration commandConfiguration); } | RunCompleteToolChainCommand extends ACommand { public RunCompleteToolChainCommand(RunCompleteToolChainCommandConfiguration commandConfiguration) { super(ECommand.RUN_COMPLETE_TOOLCHAIN.getCommandIdentifier()); this.commandConfiguration = commandConfiguration; toolChainCommands = new ArrayList<>(); commandExecutionSuccessPairs = new ArrayList<>(); inputControl = InputControl.getInputControl(); systemStatus = SystemStatus.getSystemStatus(); } RunCompleteToolChainCommand(RunCompleteToolChainCommandConfiguration commandConfiguration); @Override boolean canBeExecuted(); @Override CommandResult executeCommand(); @Override String getFailureReason(); @Override void undo(); } | RunCompleteToolChainCommand extends ACommand { public RunCompleteToolChainCommand(RunCompleteToolChainCommandConfiguration commandConfiguration) { super(ECommand.RUN_COMPLETE_TOOLCHAIN.getCommandIdentifier()); this.commandConfiguration = commandConfiguration; toolChainCommands = new ArrayList<>(); commandExecutionSuccessPairs = new ArrayList<>(); inputControl = InputControl.getInputControl(); systemStatus = SystemStatus.getSystemStatus(); } RunCompleteToolChainCommand(RunCompleteToolChainCommandConfiguration commandConfiguration); @Override boolean canBeExecuted(); @Override CommandResult executeCommand(); @Override String getFailureReason(); @Override void undo(); } |
@Test(expected = UnsupportedOperationException.class) public void testUpdateFailureWithWrongObservable() { inputControl.update(new DetermineApplicableAlgorithmsCommandHandler(), StringUtils.EMPTY_STRING); } | @Override public void update(Observable o, Object arg) { if (o instanceof CommandLineParserView && arg instanceof String[]) { String[] userInput = (String[]) arg; handleUserInput(userInput); } else { throw new UnsupportedOperationException(String.format(ERROR_UNSUPPORTED_UPDATE, o, arg)); } } | InputControl implements Observer { @Override public void update(Observable o, Object arg) { if (o instanceof CommandLineParserView && arg instanceof String[]) { String[] userInput = (String[]) arg; handleUserInput(userInput); } else { throw new UnsupportedOperationException(String.format(ERROR_UNSUPPORTED_UPDATE, o, arg)); } } } | InputControl implements Observer { @Override public void update(Observable o, Object arg) { if (o instanceof CommandLineParserView && arg instanceof String[]) { String[] userInput = (String[]) arg; handleUserInput(userInput); } else { throw new UnsupportedOperationException(String.format(ERROR_UNSUPPORTED_UPDATE, o, arg)); } } private InputControl(); } | InputControl implements Observer { @Override public void update(Observable o, Object arg) { if (o instanceof CommandLineParserView && arg instanceof String[]) { String[] userInput = (String[]) arg; handleUserInput(userInput); } else { throw new UnsupportedOperationException(String.format(ERROR_UNSUPPORTED_UPDATE, o, arg)); } } private InputControl(); static InputControl getInputControl(); @Override void update(Observable o, Object arg); void printUsage(); void simulateUserInput(String[] userInput); } | InputControl implements Observer { @Override public void update(Observable o, Object arg) { if (o instanceof CommandLineParserView && arg instanceof String[]) { String[] userInput = (String[]) arg; handleUserInput(userInput); } else { throw new UnsupportedOperationException(String.format(ERROR_UNSUPPORTED_UPDATE, o, arg)); } } private InputControl(); static InputControl getInputControl(); @Override void update(Observable o, Object arg); void printUsage(); void simulateUserInput(String[] userInput); } |
@Test(expected = UnsupportedOperationException.class) public void testUpdateFailureWithWrongArgument() { inputControl.update(CommandLineParserView.getCommandLineParserView(), new Exception()); } | @Override public void update(Observable o, Object arg) { if (o instanceof CommandLineParserView && arg instanceof String[]) { String[] userInput = (String[]) arg; handleUserInput(userInput); } else { throw new UnsupportedOperationException(String.format(ERROR_UNSUPPORTED_UPDATE, o, arg)); } } | InputControl implements Observer { @Override public void update(Observable o, Object arg) { if (o instanceof CommandLineParserView && arg instanceof String[]) { String[] userInput = (String[]) arg; handleUserInput(userInput); } else { throw new UnsupportedOperationException(String.format(ERROR_UNSUPPORTED_UPDATE, o, arg)); } } } | InputControl implements Observer { @Override public void update(Observable o, Object arg) { if (o instanceof CommandLineParserView && arg instanceof String[]) { String[] userInput = (String[]) arg; handleUserInput(userInput); } else { throw new UnsupportedOperationException(String.format(ERROR_UNSUPPORTED_UPDATE, o, arg)); } } private InputControl(); } | InputControl implements Observer { @Override public void update(Observable o, Object arg) { if (o instanceof CommandLineParserView && arg instanceof String[]) { String[] userInput = (String[]) arg; handleUserInput(userInput); } else { throw new UnsupportedOperationException(String.format(ERROR_UNSUPPORTED_UPDATE, o, arg)); } } private InputControl(); static InputControl getInputControl(); @Override void update(Observable o, Object arg); void printUsage(); void simulateUserInput(String[] userInput); } | InputControl implements Observer { @Override public void update(Observable o, Object arg) { if (o instanceof CommandLineParserView && arg instanceof String[]) { String[] userInput = (String[]) arg; handleUserInput(userInput); } else { throw new UnsupportedOperationException(String.format(ERROR_UNSUPPORTED_UPDATE, o, arg)); } } private InputControl(); static InputControl getInputControl(); @Override void update(Observable o, Object arg); void printUsage(); void simulateUserInput(String[] userInput); } |
@Test public void testParseInvalidDataset() { List<DatasetFile> datasets = getInvalidDatasets(); for (int i = 0; i < datasets.size(); i++) { try { DatasetFile datasetFile = datasets.get(i); getDatasetParser().parse(datasetFile); fail(PARSING_FAILED_EXCEPTION_EXPECTED_BUT_NOT_FOUND); } catch (ParsingFailedException e) { } } } | @Override public IDataset<?, ?, ?> parse(DatasetFile file) throws ParsingFailedException { return parsePartialOf(file, Integer.MAX_VALUE); } | ADatasetParser implements IDatasetParser { @Override public IDataset<?, ?, ?> parse(DatasetFile file) throws ParsingFailedException { return parsePartialOf(file, Integer.MAX_VALUE); } } | ADatasetParser implements IDatasetParser { @Override public IDataset<?, ?, ?> parse(DatasetFile file) throws ParsingFailedException { return parsePartialOf(file, Integer.MAX_VALUE); } } | ADatasetParser implements IDatasetParser { @Override public IDataset<?, ?, ?> parse(DatasetFile file) throws ParsingFailedException { return parsePartialOf(file, Integer.MAX_VALUE); } @Override IDataset<?, ?, ?> parse(DatasetFile file); @Override IDataset<?, ?, ?> parsePartialOf(DatasetFile file, int amountOfInstances); static Ranking parseRelativeRanking(String ranking); } | ADatasetParser implements IDatasetParser { @Override public IDataset<?, ?, ?> parse(DatasetFile file) throws ParsingFailedException { return parsePartialOf(file, Integer.MAX_VALUE); } @Override IDataset<?, ?, ?> parse(DatasetFile file); @Override IDataset<?, ?, ?> parsePartialOf(DatasetFile file, int amountOfInstances); static Ranking parseRelativeRanking(String ranking); static final String ITEM_MARKER; } |
@Test public void testParseValidDataset() throws ParsingFailedException { List<DatasetFile> datasets = getValidDatasets(); for (int i = 0; i < datasets.size(); i++) { DatasetFile datasetFile = datasets.get(i); IDatasetParser parser = getDatasetParser(); parser.parse(datasetFile); validateDataset(i, parser.getDataset()); } } | @Override public IDataset<?, ?, ?> parse(DatasetFile file) throws ParsingFailedException { return parsePartialOf(file, Integer.MAX_VALUE); } | ADatasetParser implements IDatasetParser { @Override public IDataset<?, ?, ?> parse(DatasetFile file) throws ParsingFailedException { return parsePartialOf(file, Integer.MAX_VALUE); } } | ADatasetParser implements IDatasetParser { @Override public IDataset<?, ?, ?> parse(DatasetFile file) throws ParsingFailedException { return parsePartialOf(file, Integer.MAX_VALUE); } } | ADatasetParser implements IDatasetParser { @Override public IDataset<?, ?, ?> parse(DatasetFile file) throws ParsingFailedException { return parsePartialOf(file, Integer.MAX_VALUE); } @Override IDataset<?, ?, ?> parse(DatasetFile file); @Override IDataset<?, ?, ?> parsePartialOf(DatasetFile file, int amountOfInstances); static Ranking parseRelativeRanking(String ranking); } | ADatasetParser implements IDatasetParser { @Override public IDataset<?, ?, ?> parse(DatasetFile file) throws ParsingFailedException { return parsePartialOf(file, Integer.MAX_VALUE); } @Override IDataset<?, ?, ?> parse(DatasetFile file); @Override IDataset<?, ?, ?> parsePartialOf(DatasetFile file, int amountOfInstances); static Ranking parseRelativeRanking(String ranking); static final String ITEM_MARKER; } |
@Override @Test public void testCorrectPredictions() { List<IDataset<double[], List<double[]>, IVector>> correctDatasetList = getCorrectDatasetList(); List<Pair<IDataset<double[], List<double[]>, IVector>, List<IVector>>> predictionDatasetList = getPredictionsForDatasetList(); Assert.assertEquals(ERROR_DIFFERENT_LIST_LENGTHS, correctDatasetList.size(), predictionDatasetList.size()); for (int i = 0; i < correctDatasetList.size(); i++) { IDataset<double[], List<double[]>, IVector> testDataset = correctDatasetList.get(i); IDataset<double[], List<double[]>, IVector> predictDataset = predictionDatasetList.get(i).getFirst(); List<IVector> expectedPredictedValueOfDataset = predictionDatasetList.get(i).getSecond(); try { ITrainableAlgorithm algorithm = getTrainableAlgorithm(); @SuppressWarnings("unchecked") ILearningModel<Double> trainedLearningModel = (ILearningModel<Double>) algorithm.train(testDataset); List<Double> predictedValueOfDataset = trainedLearningModel.predict(predictDataset); if (!areIVectorRatingListsEqual(predictedValueOfDataset, expectedPredictedValueOfDataset)) { fail(String.format(ERROR_WRONG_OUTPUT, expectedPredictedValueOfDataset, predictedValueOfDataset)); } } catch (TrainModelsFailedException e) { fail(String.format(ERROR_INCORRECT_DATASET, e.getMessage())); } catch (PredictionFailedException e) { fail(String.format(ERROR_PREDICTION_FAILED, e.getMessage())); } } } | @Override public CombinedRankingAndRegressionLearningModel train(IDataset<?, ?, ?> dataset) throws TrainModelsFailedException { return (CombinedRankingAndRegressionLearningModel) super.train(dataset); } | CombinedRankingAndRegressionLearningAlgorithm extends ALearningAlgorithm<CombinedRankingAndRegressionConfiguration> { @Override public CombinedRankingAndRegressionLearningModel train(IDataset<?, ?, ?> dataset) throws TrainModelsFailedException { return (CombinedRankingAndRegressionLearningModel) super.train(dataset); } } | CombinedRankingAndRegressionLearningAlgorithm extends ALearningAlgorithm<CombinedRankingAndRegressionConfiguration> { @Override public CombinedRankingAndRegressionLearningModel train(IDataset<?, ?, ?> dataset) throws TrainModelsFailedException { return (CombinedRankingAndRegressionLearningModel) super.train(dataset); } CombinedRankingAndRegressionLearningAlgorithm(); } | CombinedRankingAndRegressionLearningAlgorithm extends ALearningAlgorithm<CombinedRankingAndRegressionConfiguration> { @Override public CombinedRankingAndRegressionLearningModel train(IDataset<?, ?, ?> dataset) throws TrainModelsFailedException { return (CombinedRankingAndRegressionLearningModel) super.train(dataset); } CombinedRankingAndRegressionLearningAlgorithm(); @Override IDatasetParser getDatasetParser(); @Override void init(); @Override CombinedRankingAndRegressionLearningModel train(IDataset<?, ?, ?> dataset); @Override boolean equals(Object secondObject); @Override int hashCode(); } | CombinedRankingAndRegressionLearningAlgorithm extends ALearningAlgorithm<CombinedRankingAndRegressionConfiguration> { @Override public CombinedRankingAndRegressionLearningModel train(IDataset<?, ?, ?> dataset) throws TrainModelsFailedException { return (CombinedRankingAndRegressionLearningModel) super.train(dataset); } CombinedRankingAndRegressionLearningAlgorithm(); @Override IDatasetParser getDatasetParser(); @Override void init(); @Override CombinedRankingAndRegressionLearningModel train(IDataset<?, ?, ?> dataset); @Override boolean equals(Object secondObject); @Override int hashCode(); } |
@Test @Ignore public void pairwiseRankingAlgorithmTestCorrectInput() throws ParsingFailedException, TrainModelsFailedException, PredictionFailedException, LossException { File file = new File(getTestRessourcePathFor(OBJECT_RANKING_DATASET_B)); PairwiseRankingLearningAlgorithm algortihm = new PairwiseRankingLearningAlgorithm(); DatasetFile datasetFile = new DatasetFile(file); ObjectRankingDatasetParser objectRankingParser = (ObjectRankingDatasetParser) algortihm.getDatasetParser(); IDataset<?, ?, ?> objectRankingDataset = objectRankingParser.parse(datasetFile); IInstance<?, ?, ?> instance = objectRankingDataset.getInstance(505); IDataset<?, ?, ?> testSet = objectRankingDataset.getPartOfDataset(515, 518); objectRankingDataset = objectRankingDataset.getPartOfDataset(0, 10); ILearningModel<?> train = algortihm.train(objectRankingDataset); PairwiseRankingLearningModel castedLearningModel = (PairwiseRankingLearningModel) train; Ranking predict = null; List<Ranking> predictedRankingsOnTestSet = new ArrayList<>(); if (castedLearningModel != null) { predict = castedLearningModel.predict(instance); predictedRankingsOnTestSet = castedLearningModel.predict(testSet); } int[] objectList = new int[] { 0, 8, 21, 16, 7, 12, 30, 24, 59, 14 }; Ranking expectedResult = new Ranking(objectList, Ranking.createCompareOperatorArrayForLabels(objectList)); assertNotNull(predict); assertTrue(expectedResult.getObjectList().length == predict.getObjectList().length); assertTrue(expectedResult.getCompareOperators().length == predict.getCompareOperators().length); assertTrue(expectedResult.equals(predict)); List<Ranking> expected = ((ObjectRankingDataset) testSet).getRankings(); SpearmansCorrelation correlation = new SpearmansCorrelation(); double rho = correlation.getAggregatedLossForRatings(expected, predictedRankingsOnTestSet); Assert.assertEquals(0.5191919191919192, rho, 0.0001); } | @Override public PairwiseRankingLearningModel train(IDataset<?, ?, ?> dataset) throws TrainModelsFailedException { return (PairwiseRankingLearningModel) super.train(dataset); } | PairwiseRankingLearningAlgorithm extends AObjectRankingWithBaseLearner<PairwiseRankingConfiguration> { @Override public PairwiseRankingLearningModel train(IDataset<?, ?, ?> dataset) throws TrainModelsFailedException { return (PairwiseRankingLearningModel) super.train(dataset); } } | PairwiseRankingLearningAlgorithm extends AObjectRankingWithBaseLearner<PairwiseRankingConfiguration> { @Override public PairwiseRankingLearningModel train(IDataset<?, ?, ?> dataset) throws TrainModelsFailedException { return (PairwiseRankingLearningModel) super.train(dataset); } PairwiseRankingLearningAlgorithm(); } | PairwiseRankingLearningAlgorithm extends AObjectRankingWithBaseLearner<PairwiseRankingConfiguration> { @Override public PairwiseRankingLearningModel train(IDataset<?, ?, ?> dataset) throws TrainModelsFailedException { return (PairwiseRankingLearningModel) super.train(dataset); } PairwiseRankingLearningAlgorithm(); @Override PairwiseRankingLearningModel train(IDataset<?, ?, ?> dataset); } | PairwiseRankingLearningAlgorithm extends AObjectRankingWithBaseLearner<PairwiseRankingConfiguration> { @Override public PairwiseRankingLearningModel train(IDataset<?, ?, ?> dataset) throws TrainModelsFailedException { return (PairwiseRankingLearningModel) super.train(dataset); } PairwiseRankingLearningAlgorithm(); @Override PairwiseRankingLearningModel train(IDataset<?, ?, ?> dataset); } |
@Test public void expectedRankRegressionTestCorrectInput() throws ParsingFailedException, TrainModelsFailedException, PredictionFailedException, LossException { File file = new File(getTestRessourcePathFor(OBJECT_RANKING_DATASET_B)); ExpectedRankRegression expectedRankRegressionAlgorithm = new ExpectedRankRegression(); DatasetFile datasetFile = new DatasetFile(file); ObjectRankingDatasetParser expectedRankRegressionDatasetParser = (ObjectRankingDatasetParser) expectedRankRegressionAlgorithm .getDatasetParser(); IDataset<?, ?, ?> expectedRankRegressionDataset = expectedRankRegressionDatasetParser.parse(datasetFile); IInstance<?, ?, ?> instance = expectedRankRegressionDataset.getInstance(505); IDataset<?, ?, ?> testSet = expectedRankRegressionDataset.getPartOfDataset(500, expectedRankRegressionDataset.getNumberOfInstances()); expectedRankRegressionDataset = expectedRankRegressionDataset.getPartOfDataset(0, 500); ILearningModel<?> train = expectedRankRegressionAlgorithm.train(expectedRankRegressionDataset); ExpectedRankRegressionLearningModel expectedRankRegressionLearningModel = (ExpectedRankRegressionLearningModel) train; Ranking predict = null; List<Ranking> predictedRankingsOnTestSet = new ArrayList<>(); if (expectedRankRegressionLearningModel != null) { predict = expectedRankRegressionLearningModel.predict(instance); predictedRankingsOnTestSet = expectedRankRegressionLearningModel.predict(testSet); } int[] objectList = new int[] { 8, 0, 21, 12, 7, 14, 16, 24, 30, 59 }; Ranking expectedResult = new Ranking(objectList, Ranking.createCompareOperatorArrayForLabels(objectList)); assertNotNull(predict); assertTrue(expectedResult.getObjectList().length == predict.getObjectList().length); assertTrue(expectedResult.getCompareOperators().length == predict.getCompareOperators().length); assertTrue(expectedResult.equals(predict)); List<Ranking> expected = ((ObjectRankingDataset) testSet).getRankings(); SpearmansCorrelation correlation = new SpearmansCorrelation(); double rho = correlation.getAggregatedLossForRatings(expected, predictedRankingsOnTestSet); Assert.assertEquals(0.17740336700336695, rho, 0.0001); } | @Override public ExpectedRankRegressionLearningModel train(IDataset<?, ?, ?> dataset) throws TrainModelsFailedException { return (ExpectedRankRegressionLearningModel) super.train(dataset); } | ExpectedRankRegression extends AObjectRankingWithBaseLearner<ExpectedRankRegressionConfiguration> { @Override public ExpectedRankRegressionLearningModel train(IDataset<?, ?, ?> dataset) throws TrainModelsFailedException { return (ExpectedRankRegressionLearningModel) super.train(dataset); } } | ExpectedRankRegression extends AObjectRankingWithBaseLearner<ExpectedRankRegressionConfiguration> { @Override public ExpectedRankRegressionLearningModel train(IDataset<?, ?, ?> dataset) throws TrainModelsFailedException { return (ExpectedRankRegressionLearningModel) super.train(dataset); } ExpectedRankRegression(); } | ExpectedRankRegression extends AObjectRankingWithBaseLearner<ExpectedRankRegressionConfiguration> { @Override public ExpectedRankRegressionLearningModel train(IDataset<?, ?, ?> dataset) throws TrainModelsFailedException { return (ExpectedRankRegressionLearningModel) super.train(dataset); } ExpectedRankRegression(); @Override ExpectedRankRegressionLearningModel train(IDataset<?, ?, ?> dataset); } | ExpectedRankRegression extends AObjectRankingWithBaseLearner<ExpectedRankRegressionConfiguration> { @Override public ExpectedRankRegressionLearningModel train(IDataset<?, ?, ?> dataset) throws TrainModelsFailedException { return (ExpectedRankRegressionLearningModel) super.train(dataset); } ExpectedRankRegression(); @Override ExpectedRankRegressionLearningModel train(IDataset<?, ?, ?> dataset); } |
@Test @Override public void testCorrectParameters() throws JsonParsingFailedException { List<JsonObject> listOfJsonObjects = getCorrectParameters(); for (int i = 0; i < listOfJsonObjects.size(); i++) { IAlgorithm algorithm = getAlgorithm(); try { algorithm.setParameters(listOfJsonObjects.get(i)); } catch (ParameterValidationFailedException e) { fail(String.format(ERROR_CORRECT_PARAMETER_NOT_ACCEPTED, listOfJsonObjects.get(i))); } } } | @Override public void setParameters(JsonObject jsonObject) throws ParameterValidationFailedException { getAlgorithmConfiguration().overrideConfiguration(jsonObject); } | AAlgorithm implements IAlgorithm { @Override public void setParameters(JsonObject jsonObject) throws ParameterValidationFailedException { getAlgorithmConfiguration().overrideConfiguration(jsonObject); } } | AAlgorithm implements IAlgorithm { @Override public void setParameters(JsonObject jsonObject) throws ParameterValidationFailedException { getAlgorithmConfiguration().overrideConfiguration(jsonObject); } AAlgorithm(); AAlgorithm(String algorithmIdentifier); } | AAlgorithm implements IAlgorithm { @Override public void setParameters(JsonObject jsonObject) throws ParameterValidationFailedException { getAlgorithmConfiguration().overrideConfiguration(jsonObject); } AAlgorithm(); AAlgorithm(String algorithmIdentifier); @Override AAlgorithmConfiguration getDefaultAlgorithmConfiguration(); @Override @SuppressWarnings("unchecked") void setAlgorithmConfiguration(AAlgorithmConfiguration algorithmConfiguration); @Override @SuppressWarnings("unchecked") CONFIG getAlgorithmConfiguration(); @Override void setParameters(JsonObject jsonObject); @Override boolean equals(Object secondObject); @Override int hashCode(); @Override String toString(); } | AAlgorithm implements IAlgorithm { @Override public void setParameters(JsonObject jsonObject) throws ParameterValidationFailedException { getAlgorithmConfiguration().overrideConfiguration(jsonObject); } AAlgorithm(); AAlgorithm(String algorithmIdentifier); @Override AAlgorithmConfiguration getDefaultAlgorithmConfiguration(); @Override @SuppressWarnings("unchecked") void setAlgorithmConfiguration(AAlgorithmConfiguration algorithmConfiguration); @Override @SuppressWarnings("unchecked") CONFIG getAlgorithmConfiguration(); @Override void setParameters(JsonObject jsonObject); @Override boolean equals(Object secondObject); @Override int hashCode(); @Override String toString(); } |
@Test @Override public void testWrongParameters() throws JsonParsingFailedException { List<Pair<String, JsonObject>> listOfPairsOfStringAndJsonObjects = getWrongParameters(); for (int i = 0; i < listOfPairsOfStringAndJsonObjects.size(); i++) { IAlgorithm algorithm = getAlgorithm(); try { algorithm.setParameters(listOfPairsOfStringAndJsonObjects.get(i).getSecond()); fail(String.format(ERROR_INCORRECT_PARAMETER_ACCEPTED, listOfPairsOfStringAndJsonObjects.get(i).getSecond())); } catch (ParameterValidationFailedException e) { Assert.assertEquals(ERROR_WRONG_OUTPUT, e.getMessage(), listOfPairsOfStringAndJsonObjects.get(i).getFirst()); } } } | @Override public void setParameters(JsonObject jsonObject) throws ParameterValidationFailedException { getAlgorithmConfiguration().overrideConfiguration(jsonObject); } | AAlgorithm implements IAlgorithm { @Override public void setParameters(JsonObject jsonObject) throws ParameterValidationFailedException { getAlgorithmConfiguration().overrideConfiguration(jsonObject); } } | AAlgorithm implements IAlgorithm { @Override public void setParameters(JsonObject jsonObject) throws ParameterValidationFailedException { getAlgorithmConfiguration().overrideConfiguration(jsonObject); } AAlgorithm(); AAlgorithm(String algorithmIdentifier); } | AAlgorithm implements IAlgorithm { @Override public void setParameters(JsonObject jsonObject) throws ParameterValidationFailedException { getAlgorithmConfiguration().overrideConfiguration(jsonObject); } AAlgorithm(); AAlgorithm(String algorithmIdentifier); @Override AAlgorithmConfiguration getDefaultAlgorithmConfiguration(); @Override @SuppressWarnings("unchecked") void setAlgorithmConfiguration(AAlgorithmConfiguration algorithmConfiguration); @Override @SuppressWarnings("unchecked") CONFIG getAlgorithmConfiguration(); @Override void setParameters(JsonObject jsonObject); @Override boolean equals(Object secondObject); @Override int hashCode(); @Override String toString(); } | AAlgorithm implements IAlgorithm { @Override public void setParameters(JsonObject jsonObject) throws ParameterValidationFailedException { getAlgorithmConfiguration().overrideConfiguration(jsonObject); } AAlgorithm(); AAlgorithm(String algorithmIdentifier); @Override AAlgorithmConfiguration getDefaultAlgorithmConfiguration(); @Override @SuppressWarnings("unchecked") void setAlgorithmConfiguration(AAlgorithmConfiguration algorithmConfiguration); @Override @SuppressWarnings("unchecked") CONFIG getAlgorithmConfiguration(); @Override void setParameters(JsonObject jsonObject); @Override boolean equals(Object secondObject); @Override int hashCode(); @Override String toString(); } |
@Test public void testFitting() throws ParameterValidationFailedException, DistributionException, FittingDistributionFailedException { double[] expectedParameters = new double[] { 0.2, 0.1, 0.1, 0.1, 0.25, 0.25 }; int[] validItems = new int[] { 1, 2, 3, 4, 5, 6 }; PlackettLuceModel model = new PlackettLuceModel(expectedParameters, validItems); long startingTimeSampling = System.currentTimeMillis(); PlackettLuceModelSampleSet sampleSet = new PlackettLuceModelSampleSet(validItems); for (int i = 0; i < 2000; i++) { sampleSet.addSample(model.generateSample()); } long stoppingTimeSampling = System.currentTimeMillis(); logger.debug( "Stopped sampling at " + stoppingTimeSampling + " and took " + (stoppingTimeSampling - startingTimeSampling) / 1000.0 + " s."); PlackettLuceModelFittingAlgorithm fittingAlgorithm = new PlackettLuceModelFittingAlgorithm(); long startingTime = System.currentTimeMillis(); logger.debug("Started at " + startingTime); PlackettLuceModel fittedModel = fittingAlgorithm.fit(sampleSet); long stoppingTime = System.currentTimeMillis(); logger.debug("Stopped at " + stoppingTime + " and took " + (stoppingTime - startingTime) / 1000.0 + " s."); assertEquals(expectedParameters[0], fittedModel.getDistributionConfiguration().getParameterValueOfItem(1), GREATER_DOUBLE_DELTA); assertEquals(expectedParameters[1], fittedModel.getDistributionConfiguration().getParameterValueOfItem(2), GREATER_DOUBLE_DELTA); assertEquals(expectedParameters[2], fittedModel.getDistributionConfiguration().getParameterValueOfItem(3), GREATER_DOUBLE_DELTA); } | @Override public PlackettLuceModel fit(IDistributionSampleSet<Ranking> sampleSet) throws FittingDistributionFailedException { assertCorrectSampleSetType(sampleSet); initializeAlgorithm((PlackettLuceModelSampleSet) sampleSet); while (!shouldStop()) { updateParameters(); normalizeParameters(); updateDifferenceBetweenOldAndNewParameters(); updateNumberOfIterations(); oldParameters = Arrays.copyOf(parameters, parameters.length); } try { return new PlackettLuceModel(parameters, plackettLuceSampleSet.getValidItems()); } catch (ParameterValidationFailedException e) { throw new FittingDistributionFailedException(e); } } | PlackettLuceModelFittingAlgorithm extends ARankingDistributionFittingAlgorithm<PlackettLuceModelFittingAlgorithmConfiguration> { @Override public PlackettLuceModel fit(IDistributionSampleSet<Ranking> sampleSet) throws FittingDistributionFailedException { assertCorrectSampleSetType(sampleSet); initializeAlgorithm((PlackettLuceModelSampleSet) sampleSet); while (!shouldStop()) { updateParameters(); normalizeParameters(); updateDifferenceBetweenOldAndNewParameters(); updateNumberOfIterations(); oldParameters = Arrays.copyOf(parameters, parameters.length); } try { return new PlackettLuceModel(parameters, plackettLuceSampleSet.getValidItems()); } catch (ParameterValidationFailedException e) { throw new FittingDistributionFailedException(e); } } } | PlackettLuceModelFittingAlgorithm extends ARankingDistributionFittingAlgorithm<PlackettLuceModelFittingAlgorithmConfiguration> { @Override public PlackettLuceModel fit(IDistributionSampleSet<Ranking> sampleSet) throws FittingDistributionFailedException { assertCorrectSampleSetType(sampleSet); initializeAlgorithm((PlackettLuceModelSampleSet) sampleSet); while (!shouldStop()) { updateParameters(); normalizeParameters(); updateDifferenceBetweenOldAndNewParameters(); updateNumberOfIterations(); oldParameters = Arrays.copyOf(parameters, parameters.length); } try { return new PlackettLuceModel(parameters, plackettLuceSampleSet.getValidItems()); } catch (ParameterValidationFailedException e) { throw new FittingDistributionFailedException(e); } } PlackettLuceModelFittingAlgorithm(); PlackettLuceModelFittingAlgorithm(double minimumRequiredChangeOnUpdate, int iterationsSampleSetMultiplier); } | PlackettLuceModelFittingAlgorithm extends ARankingDistributionFittingAlgorithm<PlackettLuceModelFittingAlgorithmConfiguration> { @Override public PlackettLuceModel fit(IDistributionSampleSet<Ranking> sampleSet) throws FittingDistributionFailedException { assertCorrectSampleSetType(sampleSet); initializeAlgorithm((PlackettLuceModelSampleSet) sampleSet); while (!shouldStop()) { updateParameters(); normalizeParameters(); updateDifferenceBetweenOldAndNewParameters(); updateNumberOfIterations(); oldParameters = Arrays.copyOf(parameters, parameters.length); } try { return new PlackettLuceModel(parameters, plackettLuceSampleSet.getValidItems()); } catch (ParameterValidationFailedException e) { throw new FittingDistributionFailedException(e); } } PlackettLuceModelFittingAlgorithm(); PlackettLuceModelFittingAlgorithm(double minimumRequiredChangeOnUpdate, int iterationsSampleSetMultiplier); @Override PlackettLuceModel fit(IDistributionSampleSet<Ranking> sampleSet); @Override int hashCode(); @Override boolean equals(Object obj); } | PlackettLuceModelFittingAlgorithm extends ARankingDistributionFittingAlgorithm<PlackettLuceModelFittingAlgorithmConfiguration> { @Override public PlackettLuceModel fit(IDistributionSampleSet<Ranking> sampleSet) throws FittingDistributionFailedException { assertCorrectSampleSetType(sampleSet); initializeAlgorithm((PlackettLuceModelSampleSet) sampleSet); while (!shouldStop()) { updateParameters(); normalizeParameters(); updateDifferenceBetweenOldAndNewParameters(); updateNumberOfIterations(); oldParameters = Arrays.copyOf(parameters, parameters.length); } try { return new PlackettLuceModel(parameters, plackettLuceSampleSet.getValidItems()); } catch (ParameterValidationFailedException e) { throw new FittingDistributionFailedException(e); } } PlackettLuceModelFittingAlgorithm(); PlackettLuceModelFittingAlgorithm(double minimumRequiredChangeOnUpdate, int iterationsSampleSetMultiplier); @Override PlackettLuceModel fit(IDistributionSampleSet<Ranking> sampleSet); @Override int hashCode(); @Override boolean equals(Object obj); } |
@Test public void testGetSnippet() throws IOException { ResponseEntity<String> response = restTemplate.getForEntity(SNIPPET_ENDPOINT, String.class); Assert.assertEquals(HttpStatus.OK, response.getStatusCode()); Page<SnippetEntity> page = TestUtils.getObjectFromString(response.getBody(), new TypeReference<Page<SnippetEntity>>() { }); List<SnippetEntity> snippetsExpected = Arrays.asList(TestUtils.getObjectFromJson("snippet/content.json", SnippetEntity[].class)); Assert.assertEquals(2, page.getTotalElement()); Assert.assertEquals(1, page.getTotalPage()); } | @GetMapping(path = "/{id}") public SnippetEntity getSnippet(@PathVariable("id") String id) { return snippetService.getSnippet(id); } | Snippet { @GetMapping(path = "/{id}") public SnippetEntity getSnippet(@PathVariable("id") String id) { return snippetService.getSnippet(id); } } | Snippet { @GetMapping(path = "/{id}") public SnippetEntity getSnippet(@PathVariable("id") String id) { return snippetService.getSnippet(id); } } | Snippet { @GetMapping(path = "/{id}") public SnippetEntity getSnippet(@PathVariable("id") String id) { return snippetService.getSnippet(id); } @GetMapping() Page<SnippetEntity> getSnippets(@RequestParam(value = "from", defaultValue = "0") final int from,
@RequestParam(value = "size", defaultValue = "10") final int size,
@RequestParam(value = "query", required = false) final String query); @GetMapping(path = "/search", consumes = MediaType.APPLICATION_JSON) Page<SnippetEntity> search(@RequestParam(value = "from", defaultValue = "0") final int from,
@RequestParam(value = "size", defaultValue = "10") final int size,
@RequestBody SearchBody searchBody); @PostMapping() SnippetEntity create(@RequestBody SnippetEntity snippet); @GetMapping(path = "/{id}") SnippetEntity getSnippet(@PathVariable("id") String id); @PutMapping(path = "/{id}", consumes = MediaType.APPLICATION_JSON) @PreAuthorize("hasRole('" + Permission.ADMIN + "') or (hasRole('" + Permission.USER + "') and @snippetSecurityService.ownsSnippet(#id))") SnippetEntity updateSnippet(@PathVariable("id") String id, @RequestBody SnippetEntity snippet); @DeleteMapping(path = "/{id}") @PreAuthorize("hasRole('" + Permission.ADMIN + "') or (hasRole('" + Permission.USER + "') and @snippetSecurityService.ownsSnippet(#id))") @ResponseStatus(value = HttpStatus.NO_CONTENT) void delete(@PathVariable("id") String id); } | Snippet { @GetMapping(path = "/{id}") public SnippetEntity getSnippet(@PathVariable("id") String id) { return snippetService.getSnippet(id); } @GetMapping() Page<SnippetEntity> getSnippets(@RequestParam(value = "from", defaultValue = "0") final int from,
@RequestParam(value = "size", defaultValue = "10") final int size,
@RequestParam(value = "query", required = false) final String query); @GetMapping(path = "/search", consumes = MediaType.APPLICATION_JSON) Page<SnippetEntity> search(@RequestParam(value = "from", defaultValue = "0") final int from,
@RequestParam(value = "size", defaultValue = "10") final int size,
@RequestBody SearchBody searchBody); @PostMapping() SnippetEntity create(@RequestBody SnippetEntity snippet); @GetMapping(path = "/{id}") SnippetEntity getSnippet(@PathVariable("id") String id); @PutMapping(path = "/{id}", consumes = MediaType.APPLICATION_JSON) @PreAuthorize("hasRole('" + Permission.ADMIN + "') or (hasRole('" + Permission.USER + "') and @snippetSecurityService.ownsSnippet(#id))") SnippetEntity updateSnippet(@PathVariable("id") String id, @RequestBody SnippetEntity snippet); @DeleteMapping(path = "/{id}") @PreAuthorize("hasRole('" + Permission.ADMIN + "') or (hasRole('" + Permission.USER + "') and @snippetSecurityService.ownsSnippet(#id))") @ResponseStatus(value = HttpStatus.NO_CONTENT) void delete(@PathVariable("id") String id); } |
@Test public void should_select_startup_category() { long selectedCategoryId = categories.get("AA1").id; navigator.selectCategory(selectedCategoryId); assertEquals(selectedCategoryId, navigator.selectedCategoryId); assertSelected(selectedCategoryId, "A1", "AA1"); } | public void selectCategory(long selectedCategoryId) { Map<Long, Category> map = categories.asMap(); Category selectedCategory = map.get(selectedCategoryId); if (selectedCategory != null) { Stack<Long> path = new Stack<>(); Category parent = selectedCategory.parent; while (parent != null) { path.push(parent.id); parent = parent.parent; } while (!path.isEmpty()) { navigateTo(path.pop()); } this.selectedCategoryId = selectedCategoryId; } } | CategoryTreeNavigator { public void selectCategory(long selectedCategoryId) { Map<Long, Category> map = categories.asMap(); Category selectedCategory = map.get(selectedCategoryId); if (selectedCategory != null) { Stack<Long> path = new Stack<>(); Category parent = selectedCategory.parent; while (parent != null) { path.push(parent.id); parent = parent.parent; } while (!path.isEmpty()) { navigateTo(path.pop()); } this.selectedCategoryId = selectedCategoryId; } } } | CategoryTreeNavigator { public void selectCategory(long selectedCategoryId) { Map<Long, Category> map = categories.asMap(); Category selectedCategory = map.get(selectedCategoryId); if (selectedCategory != null) { Stack<Long> path = new Stack<>(); Category parent = selectedCategory.parent; while (parent != null) { path.push(parent.id); parent = parent.parent; } while (!path.isEmpty()) { navigateTo(path.pop()); } this.selectedCategoryId = selectedCategoryId; } } CategoryTreeNavigator(DatabaseAdapter db); CategoryTreeNavigator(DatabaseAdapter db, long excludedTreeId); } | CategoryTreeNavigator { public void selectCategory(long selectedCategoryId) { Map<Long, Category> map = categories.asMap(); Category selectedCategory = map.get(selectedCategoryId); if (selectedCategory != null) { Stack<Long> path = new Stack<>(); Category parent = selectedCategory.parent; while (parent != null) { path.push(parent.id); parent = parent.parent; } while (!path.isEmpty()) { navigateTo(path.pop()); } this.selectedCategoryId = selectedCategoryId; } } CategoryTreeNavigator(DatabaseAdapter db); CategoryTreeNavigator(DatabaseAdapter db, long excludedTreeId); void selectCategory(long selectedCategoryId); void tagCategories(Category parent); boolean goBack(); boolean canGoBack(); boolean navigateTo(long categoryId); boolean isSelected(long categoryId); List<Category> getSelectedRoots(); void addSplitCategoryToTheTop(); void separateIncomeAndExpense(); long getExcludedTreeId(); } | CategoryTreeNavigator { public void selectCategory(long selectedCategoryId) { Map<Long, Category> map = categories.asMap(); Category selectedCategory = map.get(selectedCategoryId); if (selectedCategory != null) { Stack<Long> path = new Stack<>(); Category parent = selectedCategory.parent; while (parent != null) { path.push(parent.id); parent = parent.parent; } while (!path.isEmpty()) { navigateTo(path.pop()); } this.selectedCategoryId = selectedCategoryId; } } CategoryTreeNavigator(DatabaseAdapter db); CategoryTreeNavigator(DatabaseAdapter db, long excludedTreeId); void selectCategory(long selectedCategoryId); void tagCategories(Category parent); boolean goBack(); boolean canGoBack(); boolean navigateTo(long categoryId); boolean isSelected(long categoryId); List<Category> getSelectedRoots(); void addSplitCategoryToTheTop(); void separateIncomeAndExpense(); long getExcludedTreeId(); static final long INCOME_CATEGORY_ID; static final long EXPENSE_CATEGORY_ID; public CategoryTree<Category> categories; public long selectedCategoryId; } |
@Test public void should_return_error_if_exchange_rate_not_available() { TransactionBuilder.withDb(db).account(a1).dateTime(DateTime.date(2012, 1, 10)).amount(1).create(); assertFalse(c.getAccountBalance(c1, a1.id).isError()); assertFalse(c.getAccountBalance(c3, a1.id).isError()); Total total = c.getAccountBalance(c2, a1.id); assertTrue(total.isError()); total = c.getAccountBalance(c4, a1.id); assertTrue(total.isError()); } | public Total getAccountBalance(Currency toCurrency, long accountId) { WhereFilter filter = selectedAccountOnly(this.filter, accountId); return getBalanceInHomeCurrency(V_BLOTTER_FOR_ACCOUNT_WITH_SPLITS, toCurrency, filter); } | TransactionsTotalCalculator { public Total getAccountBalance(Currency toCurrency, long accountId) { WhereFilter filter = selectedAccountOnly(this.filter, accountId); return getBalanceInHomeCurrency(V_BLOTTER_FOR_ACCOUNT_WITH_SPLITS, toCurrency, filter); } } | TransactionsTotalCalculator { public Total getAccountBalance(Currency toCurrency, long accountId) { WhereFilter filter = selectedAccountOnly(this.filter, accountId); return getBalanceInHomeCurrency(V_BLOTTER_FOR_ACCOUNT_WITH_SPLITS, toCurrency, filter); } TransactionsTotalCalculator(DatabaseAdapter db, WhereFilter filter); } | TransactionsTotalCalculator { public Total getAccountBalance(Currency toCurrency, long accountId) { WhereFilter filter = selectedAccountOnly(this.filter, accountId); return getBalanceInHomeCurrency(V_BLOTTER_FOR_ACCOUNT_WITH_SPLITS, toCurrency, filter); } TransactionsTotalCalculator(DatabaseAdapter db, WhereFilter filter); Total[] getTransactionsBalance(); Total getAccountTotal(); Total getBlotterBalanceInHomeCurrency(); Total getBlotterBalance(Currency toCurrency); Total getAccountBalance(Currency toCurrency, long accountId); static Total calculateTotalFromListInHomeCurrency(DatabaseAdapter db, List<TransactionInfo> list); static long[] calculateTotalFromList(DatabaseAdapter db, List<TransactionInfo> list, Currency toCurrency); static BigDecimal getAmountFromCursor(MyEntityManager em, Cursor c, Currency toCurrency, ExchangeRateProvider rates, int index); static BigDecimal getAmountFromTransaction(MyEntityManager em, TransactionInfo ti, Currency toCurrency, ExchangeRateProvider rates); } | TransactionsTotalCalculator { public Total getAccountBalance(Currency toCurrency, long accountId) { WhereFilter filter = selectedAccountOnly(this.filter, accountId); return getBalanceInHomeCurrency(V_BLOTTER_FOR_ACCOUNT_WITH_SPLITS, toCurrency, filter); } TransactionsTotalCalculator(DatabaseAdapter db, WhereFilter filter); Total[] getTransactionsBalance(); Total getAccountTotal(); Total getBlotterBalanceInHomeCurrency(); Total getBlotterBalance(Currency toCurrency); Total getAccountBalance(Currency toCurrency, long accountId); static Total calculateTotalFromListInHomeCurrency(DatabaseAdapter db, List<TransactionInfo> list); static long[] calculateTotalFromList(DatabaseAdapter db, List<TransactionInfo> list, Currency toCurrency); static BigDecimal getAmountFromCursor(MyEntityManager em, Cursor c, Currency toCurrency, ExchangeRateProvider rates, int index); static BigDecimal getAmountFromTransaction(MyEntityManager em, TransactionInfo ti, Currency toCurrency, ExchangeRateProvider rates); static final String[] BALANCE_PROJECTION; static final String BALANCE_GROUPBY; static final String[] HOME_CURRENCY_PROJECTION; } |
@Test public void should_calculate_blotter_total_in_multiple_currencies() { Total[] totals = c.getTransactionsBalance(); assertEquals(2, totals.length); assertEquals(-700, totals[0].balance); assertEquals(-230, totals[1].balance); } | public Total[] getTransactionsBalance() { WhereFilter filter = this.filter; if (filter.getAccountId() == -1) { filter = excludeAccountsNotIncludedInTotalsAndSplits(filter); } try (Cursor c = db.db().query(V_BLOTTER_FOR_ACCOUNT_WITH_SPLITS, BALANCE_PROJECTION, filter.getSelection(), filter.getSelectionArgs(), BALANCE_GROUPBY, null, null)) { int count = c.getCount(); List<Total> totals = new ArrayList<Total>(count); while (c.moveToNext()) { long currencyId = c.getLong(0); long balance = c.getLong(1); Currency currency = CurrencyCache.getCurrency(db, currencyId); Total total = new Total(currency); total.balance = balance; totals.add(total); } return totals.toArray(new Total[totals.size()]); } } | TransactionsTotalCalculator { public Total[] getTransactionsBalance() { WhereFilter filter = this.filter; if (filter.getAccountId() == -1) { filter = excludeAccountsNotIncludedInTotalsAndSplits(filter); } try (Cursor c = db.db().query(V_BLOTTER_FOR_ACCOUNT_WITH_SPLITS, BALANCE_PROJECTION, filter.getSelection(), filter.getSelectionArgs(), BALANCE_GROUPBY, null, null)) { int count = c.getCount(); List<Total> totals = new ArrayList<Total>(count); while (c.moveToNext()) { long currencyId = c.getLong(0); long balance = c.getLong(1); Currency currency = CurrencyCache.getCurrency(db, currencyId); Total total = new Total(currency); total.balance = balance; totals.add(total); } return totals.toArray(new Total[totals.size()]); } } } | TransactionsTotalCalculator { public Total[] getTransactionsBalance() { WhereFilter filter = this.filter; if (filter.getAccountId() == -1) { filter = excludeAccountsNotIncludedInTotalsAndSplits(filter); } try (Cursor c = db.db().query(V_BLOTTER_FOR_ACCOUNT_WITH_SPLITS, BALANCE_PROJECTION, filter.getSelection(), filter.getSelectionArgs(), BALANCE_GROUPBY, null, null)) { int count = c.getCount(); List<Total> totals = new ArrayList<Total>(count); while (c.moveToNext()) { long currencyId = c.getLong(0); long balance = c.getLong(1); Currency currency = CurrencyCache.getCurrency(db, currencyId); Total total = new Total(currency); total.balance = balance; totals.add(total); } return totals.toArray(new Total[totals.size()]); } } TransactionsTotalCalculator(DatabaseAdapter db, WhereFilter filter); } | TransactionsTotalCalculator { public Total[] getTransactionsBalance() { WhereFilter filter = this.filter; if (filter.getAccountId() == -1) { filter = excludeAccountsNotIncludedInTotalsAndSplits(filter); } try (Cursor c = db.db().query(V_BLOTTER_FOR_ACCOUNT_WITH_SPLITS, BALANCE_PROJECTION, filter.getSelection(), filter.getSelectionArgs(), BALANCE_GROUPBY, null, null)) { int count = c.getCount(); List<Total> totals = new ArrayList<Total>(count); while (c.moveToNext()) { long currencyId = c.getLong(0); long balance = c.getLong(1); Currency currency = CurrencyCache.getCurrency(db, currencyId); Total total = new Total(currency); total.balance = balance; totals.add(total); } return totals.toArray(new Total[totals.size()]); } } TransactionsTotalCalculator(DatabaseAdapter db, WhereFilter filter); Total[] getTransactionsBalance(); Total getAccountTotal(); Total getBlotterBalanceInHomeCurrency(); Total getBlotterBalance(Currency toCurrency); Total getAccountBalance(Currency toCurrency, long accountId); static Total calculateTotalFromListInHomeCurrency(DatabaseAdapter db, List<TransactionInfo> list); static long[] calculateTotalFromList(DatabaseAdapter db, List<TransactionInfo> list, Currency toCurrency); static BigDecimal getAmountFromCursor(MyEntityManager em, Cursor c, Currency toCurrency, ExchangeRateProvider rates, int index); static BigDecimal getAmountFromTransaction(MyEntityManager em, TransactionInfo ti, Currency toCurrency, ExchangeRateProvider rates); } | TransactionsTotalCalculator { public Total[] getTransactionsBalance() { WhereFilter filter = this.filter; if (filter.getAccountId() == -1) { filter = excludeAccountsNotIncludedInTotalsAndSplits(filter); } try (Cursor c = db.db().query(V_BLOTTER_FOR_ACCOUNT_WITH_SPLITS, BALANCE_PROJECTION, filter.getSelection(), filter.getSelectionArgs(), BALANCE_GROUPBY, null, null)) { int count = c.getCount(); List<Total> totals = new ArrayList<Total>(count); while (c.moveToNext()) { long currencyId = c.getLong(0); long balance = c.getLong(1); Currency currency = CurrencyCache.getCurrency(db, currencyId); Total total = new Total(currency); total.balance = balance; totals.add(total); } return totals.toArray(new Total[totals.size()]); } } TransactionsTotalCalculator(DatabaseAdapter db, WhereFilter filter); Total[] getTransactionsBalance(); Total getAccountTotal(); Total getBlotterBalanceInHomeCurrency(); Total getBlotterBalance(Currency toCurrency); Total getAccountBalance(Currency toCurrency, long accountId); static Total calculateTotalFromListInHomeCurrency(DatabaseAdapter db, List<TransactionInfo> list); static long[] calculateTotalFromList(DatabaseAdapter db, List<TransactionInfo> list, Currency toCurrency); static BigDecimal getAmountFromCursor(MyEntityManager em, Cursor c, Currency toCurrency, ExchangeRateProvider rates, int index); static BigDecimal getAmountFromTransaction(MyEntityManager em, TransactionInfo ti, Currency toCurrency, ExchangeRateProvider rates); static final String[] BALANCE_PROJECTION; static final String BALANCE_GROUPBY; static final String[] HOME_CURRENCY_PROJECTION; } |
@Test public void should_calculate_account_total_in_home_currency() { assertEquals(a1t1_09th.fromAmount + a1t2_17th.fromAmount + a1t3_20th.fromAmount + a1t4_22nd.fromAmount + a1t5_23rd.fromAmount, c.getAccountBalance(c1, a1.id).balance); assertEquals((long) (a1t1_09th.originalFromAmount + r_c1c2_17th * a1t2_17th.fromAmount - a1t3_20th.toAmount + r_c1c2_18th * a1t4_22nd.fromAmount + r_c1c2_18th * a1t5_23rd.fromAmount), c.getAccountBalance(c2, a1.id).balance); assertEquals(a2t1_17th.fromAmount + a2t2_18th.fromAmount + a1t3_20th.toAmount + a1t5_23rd_s2.toAmount, c.getAccountBalance(c2, a2.id).balance); assertEquals((long) (r_c2c1_17th * a2t1_17th.fromAmount + r_c2c1_18th * a2t2_18th.fromAmount - a1t3_20th.fromAmount - a1t5_23rd_s2.fromAmount), c.getAccountBalance(c1, a2.id).balance); assertEquals((long) (r_c1c3_5th * (a1t1_09th.fromAmount + a1t2_17th.fromAmount + a1t3_20th.fromAmount + a1t4_22nd.fromAmount + a1t5_23rd.fromAmount)), c.getAccountBalance(c3, a1.id).balance); assertEquals((long) (r_c2c3_5th * (a2t1_17th.fromAmount + a2t2_18th.fromAmount + a1t3_20th.toAmount + a1t5_23rd_s2.toAmount)), c.getAccountBalance(c3, a2.id).balance); } | public Total getAccountBalance(Currency toCurrency, long accountId) { WhereFilter filter = selectedAccountOnly(this.filter, accountId); return getBalanceInHomeCurrency(V_BLOTTER_FOR_ACCOUNT_WITH_SPLITS, toCurrency, filter); } | TransactionsTotalCalculator { public Total getAccountBalance(Currency toCurrency, long accountId) { WhereFilter filter = selectedAccountOnly(this.filter, accountId); return getBalanceInHomeCurrency(V_BLOTTER_FOR_ACCOUNT_WITH_SPLITS, toCurrency, filter); } } | TransactionsTotalCalculator { public Total getAccountBalance(Currency toCurrency, long accountId) { WhereFilter filter = selectedAccountOnly(this.filter, accountId); return getBalanceInHomeCurrency(V_BLOTTER_FOR_ACCOUNT_WITH_SPLITS, toCurrency, filter); } TransactionsTotalCalculator(DatabaseAdapter db, WhereFilter filter); } | TransactionsTotalCalculator { public Total getAccountBalance(Currency toCurrency, long accountId) { WhereFilter filter = selectedAccountOnly(this.filter, accountId); return getBalanceInHomeCurrency(V_BLOTTER_FOR_ACCOUNT_WITH_SPLITS, toCurrency, filter); } TransactionsTotalCalculator(DatabaseAdapter db, WhereFilter filter); Total[] getTransactionsBalance(); Total getAccountTotal(); Total getBlotterBalanceInHomeCurrency(); Total getBlotterBalance(Currency toCurrency); Total getAccountBalance(Currency toCurrency, long accountId); static Total calculateTotalFromListInHomeCurrency(DatabaseAdapter db, List<TransactionInfo> list); static long[] calculateTotalFromList(DatabaseAdapter db, List<TransactionInfo> list, Currency toCurrency); static BigDecimal getAmountFromCursor(MyEntityManager em, Cursor c, Currency toCurrency, ExchangeRateProvider rates, int index); static BigDecimal getAmountFromTransaction(MyEntityManager em, TransactionInfo ti, Currency toCurrency, ExchangeRateProvider rates); } | TransactionsTotalCalculator { public Total getAccountBalance(Currency toCurrency, long accountId) { WhereFilter filter = selectedAccountOnly(this.filter, accountId); return getBalanceInHomeCurrency(V_BLOTTER_FOR_ACCOUNT_WITH_SPLITS, toCurrency, filter); } TransactionsTotalCalculator(DatabaseAdapter db, WhereFilter filter); Total[] getTransactionsBalance(); Total getAccountTotal(); Total getBlotterBalanceInHomeCurrency(); Total getBlotterBalance(Currency toCurrency); Total getAccountBalance(Currency toCurrency, long accountId); static Total calculateTotalFromListInHomeCurrency(DatabaseAdapter db, List<TransactionInfo> list); static long[] calculateTotalFromList(DatabaseAdapter db, List<TransactionInfo> list, Currency toCurrency); static BigDecimal getAmountFromCursor(MyEntityManager em, Cursor c, Currency toCurrency, ExchangeRateProvider rates, int index); static BigDecimal getAmountFromTransaction(MyEntityManager em, TransactionInfo ti, Currency toCurrency, ExchangeRateProvider rates); static final String[] BALANCE_PROJECTION; static final String BALANCE_GROUPBY; static final String[] HOME_CURRENCY_PROJECTION; } |
@Test public void should_calculate_account_total_in_home_currency_with_big_amounts() { TransactionBuilder.withDb(db).account(a1).dateTime(DateTime.date(2012, 1, 10)).amount(45000000000L).create(); assertEquals(45000000000L + (long) (-100f + 100f - 50f - 450f - 50f - 150f), c.getAccountBalance(c1, a1.id).balance); } | public Total getAccountBalance(Currency toCurrency, long accountId) { WhereFilter filter = selectedAccountOnly(this.filter, accountId); return getBalanceInHomeCurrency(V_BLOTTER_FOR_ACCOUNT_WITH_SPLITS, toCurrency, filter); } | TransactionsTotalCalculator { public Total getAccountBalance(Currency toCurrency, long accountId) { WhereFilter filter = selectedAccountOnly(this.filter, accountId); return getBalanceInHomeCurrency(V_BLOTTER_FOR_ACCOUNT_WITH_SPLITS, toCurrency, filter); } } | TransactionsTotalCalculator { public Total getAccountBalance(Currency toCurrency, long accountId) { WhereFilter filter = selectedAccountOnly(this.filter, accountId); return getBalanceInHomeCurrency(V_BLOTTER_FOR_ACCOUNT_WITH_SPLITS, toCurrency, filter); } TransactionsTotalCalculator(DatabaseAdapter db, WhereFilter filter); } | TransactionsTotalCalculator { public Total getAccountBalance(Currency toCurrency, long accountId) { WhereFilter filter = selectedAccountOnly(this.filter, accountId); return getBalanceInHomeCurrency(V_BLOTTER_FOR_ACCOUNT_WITH_SPLITS, toCurrency, filter); } TransactionsTotalCalculator(DatabaseAdapter db, WhereFilter filter); Total[] getTransactionsBalance(); Total getAccountTotal(); Total getBlotterBalanceInHomeCurrency(); Total getBlotterBalance(Currency toCurrency); Total getAccountBalance(Currency toCurrency, long accountId); static Total calculateTotalFromListInHomeCurrency(DatabaseAdapter db, List<TransactionInfo> list); static long[] calculateTotalFromList(DatabaseAdapter db, List<TransactionInfo> list, Currency toCurrency); static BigDecimal getAmountFromCursor(MyEntityManager em, Cursor c, Currency toCurrency, ExchangeRateProvider rates, int index); static BigDecimal getAmountFromTransaction(MyEntityManager em, TransactionInfo ti, Currency toCurrency, ExchangeRateProvider rates); } | TransactionsTotalCalculator { public Total getAccountBalance(Currency toCurrency, long accountId) { WhereFilter filter = selectedAccountOnly(this.filter, accountId); return getBalanceInHomeCurrency(V_BLOTTER_FOR_ACCOUNT_WITH_SPLITS, toCurrency, filter); } TransactionsTotalCalculator(DatabaseAdapter db, WhereFilter filter); Total[] getTransactionsBalance(); Total getAccountTotal(); Total getBlotterBalanceInHomeCurrency(); Total getBlotterBalance(Currency toCurrency); Total getAccountBalance(Currency toCurrency, long accountId); static Total calculateTotalFromListInHomeCurrency(DatabaseAdapter db, List<TransactionInfo> list); static long[] calculateTotalFromList(DatabaseAdapter db, List<TransactionInfo> list, Currency toCurrency); static BigDecimal getAmountFromCursor(MyEntityManager em, Cursor c, Currency toCurrency, ExchangeRateProvider rates, int index); static BigDecimal getAmountFromTransaction(MyEntityManager em, TransactionInfo ti, Currency toCurrency, ExchangeRateProvider rates); static final String[] BALANCE_PROJECTION; static final String BALANCE_GROUPBY; static final String[] HOME_CURRENCY_PROJECTION; } |
@Test public void TemplatesWithDifferentLength() { String template1 = "*{{a}}. Summa {{p}} RUB. {{*}}, MOSCOW. {{d}}. Dostupno {{b}}"; String template2 = "*{{a}}. Summa {{p}} RUB. NOVYY PROEKT, MOSCOW. {{d}}. Dostupno {{b}}"; String template3 = "*{{a}}. Summa {{p}} RUB. NOVYY PROEKT, MOSCOW. {{d}}. Dostupno {{b}}"; String sms = "Pokupka. Karta *5631. Summa 250.77 RUB. NOVYY PROEKT, MOSCOW. 02.10.2017 14:19. Dostupno 34202.82 RUB. Tinkoff.ru"; SmsTemplateBuilder.withDb(db).title("Tinkoff").accountId(7).categoryId(8).template(template1).sortOrder(2).create(); SmsTemplateBuilder.withDb(db).title("Tinkoff").accountId(7).categoryId(88).template(template2).sortOrder(1).create(); SmsTemplateBuilder.withDb(db).title("Tinkoff").accountId(7).categoryId(89).template(template3).create(); Transaction transaction = smsProcessor.createTransactionBySms("Tinkoff", sms, status, true); assertEquals(7, transaction.fromAccountId); assertEquals(88, transaction.categoryId); assertEquals(-25077, transaction.fromAmount); assertEquals(sms, transaction.note); assertEquals(TransactionStatus.PN, transaction.status); } | public Transaction createTransactionBySms(String addr, String fullSmsBody, TransactionStatus status, boolean updateNote) { List<SmsTemplate> addrTemplates = db.getSmsTemplatesByNumber(addr); for (final SmsTemplate t : addrTemplates) { String[] match = findTemplateMatches(t.template, fullSmsBody); if (match != null) { Log.d(TAG, format("Found template`%s` with matches `%s`", t, Arrays.toString(match))); String account = match[ACCOUNT.ordinal()]; String parsedPrice = match[PRICE.ordinal()]; try { BigDecimal price = toBigDecimal(parsedPrice); return createNewTransaction(price, account, t, updateNote ? fullSmsBody : "", status); } catch (Exception e) { Log.e(TAG, format("Failed to parse price value: `%s`", parsedPrice), e); } } } return null; } | SmsTransactionProcessor { public Transaction createTransactionBySms(String addr, String fullSmsBody, TransactionStatus status, boolean updateNote) { List<SmsTemplate> addrTemplates = db.getSmsTemplatesByNumber(addr); for (final SmsTemplate t : addrTemplates) { String[] match = findTemplateMatches(t.template, fullSmsBody); if (match != null) { Log.d(TAG, format("Found template`%s` with matches `%s`", t, Arrays.toString(match))); String account = match[ACCOUNT.ordinal()]; String parsedPrice = match[PRICE.ordinal()]; try { BigDecimal price = toBigDecimal(parsedPrice); return createNewTransaction(price, account, t, updateNote ? fullSmsBody : "", status); } catch (Exception e) { Log.e(TAG, format("Failed to parse price value: `%s`", parsedPrice), e); } } } return null; } } | SmsTransactionProcessor { public Transaction createTransactionBySms(String addr, String fullSmsBody, TransactionStatus status, boolean updateNote) { List<SmsTemplate> addrTemplates = db.getSmsTemplatesByNumber(addr); for (final SmsTemplate t : addrTemplates) { String[] match = findTemplateMatches(t.template, fullSmsBody); if (match != null) { Log.d(TAG, format("Found template`%s` with matches `%s`", t, Arrays.toString(match))); String account = match[ACCOUNT.ordinal()]; String parsedPrice = match[PRICE.ordinal()]; try { BigDecimal price = toBigDecimal(parsedPrice); return createNewTransaction(price, account, t, updateNote ? fullSmsBody : "", status); } catch (Exception e) { Log.e(TAG, format("Failed to parse price value: `%s`", parsedPrice), e); } } } return null; } SmsTransactionProcessor(DatabaseAdapter db); } | SmsTransactionProcessor { public Transaction createTransactionBySms(String addr, String fullSmsBody, TransactionStatus status, boolean updateNote) { List<SmsTemplate> addrTemplates = db.getSmsTemplatesByNumber(addr); for (final SmsTemplate t : addrTemplates) { String[] match = findTemplateMatches(t.template, fullSmsBody); if (match != null) { Log.d(TAG, format("Found template`%s` with matches `%s`", t, Arrays.toString(match))); String account = match[ACCOUNT.ordinal()]; String parsedPrice = match[PRICE.ordinal()]; try { BigDecimal price = toBigDecimal(parsedPrice); return createNewTransaction(price, account, t, updateNote ? fullSmsBody : "", status); } catch (Exception e) { Log.e(TAG, format("Failed to parse price value: `%s`", parsedPrice), e); } } } return null; } SmsTransactionProcessor(DatabaseAdapter db); Transaction createTransactionBySms(String addr, String fullSmsBody, TransactionStatus status, boolean updateNote); static String[] findTemplateMatches(String template, final String sms); } | SmsTransactionProcessor { public Transaction createTransactionBySms(String addr, String fullSmsBody, TransactionStatus status, boolean updateNote) { List<SmsTemplate> addrTemplates = db.getSmsTemplatesByNumber(addr); for (final SmsTemplate t : addrTemplates) { String[] match = findTemplateMatches(t.template, fullSmsBody); if (match != null) { Log.d(TAG, format("Found template`%s` with matches `%s`", t, Arrays.toString(match))); String account = match[ACCOUNT.ordinal()]; String parsedPrice = match[PRICE.ordinal()]; try { BigDecimal price = toBigDecimal(parsedPrice); return createNewTransaction(price, account, t, updateNote ? fullSmsBody : "", status); } catch (Exception e) { Log.e(TAG, format("Failed to parse price value: `%s`", parsedPrice), e); } } } return null; } SmsTransactionProcessor(DatabaseAdapter db); Transaction createTransactionBySms(String addr, String fullSmsBody, TransactionStatus status, boolean updateNote); static String[] findTemplateMatches(String template, final String sms); } |
@Test public void MultilineSms() { String template = "*{{a}}. Summa {{p}} RUB. NOVYY PROEKT, MOSCOW. {{d}}. Dostupno {{b}}{{*}}"; String sms = "Pokupka. Karta *5631. Summa 1250,77 RUB. NOVYY PROEKT, MOSCOW. 02.10.2017 14:19. Dostupno 34 202.82 RUB.\nTinkoff\n.ru"; String[] matches = SmsTransactionProcessor.findTemplateMatches(template, sms); Assert.assertArrayEquals(new String[]{null, "5631", "34 202.82 ", "02.10.2017 14:19", "1250,77", null}, matches); } | public static String[] findTemplateMatches(String template, final String sms) { String[] results = null; template = preprocessPatterns(template); final int[] phIndexes = findPlaceholderIndexes(template); if (phIndexes != null) { template = template.replaceAll("([.\\[\\]{}()*+\\-?^$|])", "\\\\$1"); for (int i = 0; i < phIndexes.length; i++) { if (phIndexes[i] != -1) { Placeholder placeholder = Placeholder.values()[i]; template = template.replace(placeholder.code, placeholder.regexp); } } template = ANY.regexp + template.replace(ANY.code, ANY.regexp) + ANY.regexp; Matcher matcher = Pattern.compile(template, DOTALL).matcher(sms); if (matcher.matches()) { results = new String[Placeholder.values().length]; for (int i = 0; i < phIndexes.length; i++) { final int groupNum = phIndexes[i] + 1; if (groupNum > 0) { results[i] = matcher.group(groupNum); } } } } return results; } | SmsTransactionProcessor { public static String[] findTemplateMatches(String template, final String sms) { String[] results = null; template = preprocessPatterns(template); final int[] phIndexes = findPlaceholderIndexes(template); if (phIndexes != null) { template = template.replaceAll("([.\\[\\]{}()*+\\-?^$|])", "\\\\$1"); for (int i = 0; i < phIndexes.length; i++) { if (phIndexes[i] != -1) { Placeholder placeholder = Placeholder.values()[i]; template = template.replace(placeholder.code, placeholder.regexp); } } template = ANY.regexp + template.replace(ANY.code, ANY.regexp) + ANY.regexp; Matcher matcher = Pattern.compile(template, DOTALL).matcher(sms); if (matcher.matches()) { results = new String[Placeholder.values().length]; for (int i = 0; i < phIndexes.length; i++) { final int groupNum = phIndexes[i] + 1; if (groupNum > 0) { results[i] = matcher.group(groupNum); } } } } return results; } } | SmsTransactionProcessor { public static String[] findTemplateMatches(String template, final String sms) { String[] results = null; template = preprocessPatterns(template); final int[] phIndexes = findPlaceholderIndexes(template); if (phIndexes != null) { template = template.replaceAll("([.\\[\\]{}()*+\\-?^$|])", "\\\\$1"); for (int i = 0; i < phIndexes.length; i++) { if (phIndexes[i] != -1) { Placeholder placeholder = Placeholder.values()[i]; template = template.replace(placeholder.code, placeholder.regexp); } } template = ANY.regexp + template.replace(ANY.code, ANY.regexp) + ANY.regexp; Matcher matcher = Pattern.compile(template, DOTALL).matcher(sms); if (matcher.matches()) { results = new String[Placeholder.values().length]; for (int i = 0; i < phIndexes.length; i++) { final int groupNum = phIndexes[i] + 1; if (groupNum > 0) { results[i] = matcher.group(groupNum); } } } } return results; } SmsTransactionProcessor(DatabaseAdapter db); } | SmsTransactionProcessor { public static String[] findTemplateMatches(String template, final String sms) { String[] results = null; template = preprocessPatterns(template); final int[] phIndexes = findPlaceholderIndexes(template); if (phIndexes != null) { template = template.replaceAll("([.\\[\\]{}()*+\\-?^$|])", "\\\\$1"); for (int i = 0; i < phIndexes.length; i++) { if (phIndexes[i] != -1) { Placeholder placeholder = Placeholder.values()[i]; template = template.replace(placeholder.code, placeholder.regexp); } } template = ANY.regexp + template.replace(ANY.code, ANY.regexp) + ANY.regexp; Matcher matcher = Pattern.compile(template, DOTALL).matcher(sms); if (matcher.matches()) { results = new String[Placeholder.values().length]; for (int i = 0; i < phIndexes.length; i++) { final int groupNum = phIndexes[i] + 1; if (groupNum > 0) { results[i] = matcher.group(groupNum); } } } } return results; } SmsTransactionProcessor(DatabaseAdapter db); Transaction createTransactionBySms(String addr, String fullSmsBody, TransactionStatus status, boolean updateNote); static String[] findTemplateMatches(String template, final String sms); } | SmsTransactionProcessor { public static String[] findTemplateMatches(String template, final String sms) { String[] results = null; template = preprocessPatterns(template); final int[] phIndexes = findPlaceholderIndexes(template); if (phIndexes != null) { template = template.replaceAll("([.\\[\\]{}()*+\\-?^$|])", "\\\\$1"); for (int i = 0; i < phIndexes.length; i++) { if (phIndexes[i] != -1) { Placeholder placeholder = Placeholder.values()[i]; template = template.replace(placeholder.code, placeholder.regexp); } } template = ANY.regexp + template.replace(ANY.code, ANY.regexp) + ANY.regexp; Matcher matcher = Pattern.compile(template, DOTALL).matcher(sms); if (matcher.matches()) { results = new String[Placeholder.values().length]; for (int i = 0; i < phIndexes.length; i++) { final int groupNum = phIndexes[i] + 1; if (groupNum > 0) { results[i] = matcher.group(groupNum); } } } } return results; } SmsTransactionProcessor(DatabaseAdapter db); Transaction createTransactionBySms(String addr, String fullSmsBody, TransactionStatus status, boolean updateNote); static String[] findTemplateMatches(String template, final String sms); } |
@Test public void TemplateWithWrongSpaces() { String smsTpl = "ECMC{{a}}<:D:>покупка{{P}}р TEREMOK METROPOLIS Баланс:{{b}}р"; String sms = "ECMC5431 01.10.17 19:50 покупка 550р TEREMOK METROPOLIS Баланс: 49820.45р"; String[] matches = SmsTransactionProcessor.findTemplateMatches(smsTpl, sms); Assert.assertArrayEquals(new String[]{null, "5431", "49820.45", "01.10.17 19:50", "550", null}, matches); } | public static String[] findTemplateMatches(String template, final String sms) { String[] results = null; template = preprocessPatterns(template); final int[] phIndexes = findPlaceholderIndexes(template); if (phIndexes != null) { template = template.replaceAll("([.\\[\\]{}()*+\\-?^$|])", "\\\\$1"); for (int i = 0; i < phIndexes.length; i++) { if (phIndexes[i] != -1) { Placeholder placeholder = Placeholder.values()[i]; template = template.replace(placeholder.code, placeholder.regexp); } } template = ANY.regexp + template.replace(ANY.code, ANY.regexp) + ANY.regexp; Matcher matcher = Pattern.compile(template, DOTALL).matcher(sms); if (matcher.matches()) { results = new String[Placeholder.values().length]; for (int i = 0; i < phIndexes.length; i++) { final int groupNum = phIndexes[i] + 1; if (groupNum > 0) { results[i] = matcher.group(groupNum); } } } } return results; } | SmsTransactionProcessor { public static String[] findTemplateMatches(String template, final String sms) { String[] results = null; template = preprocessPatterns(template); final int[] phIndexes = findPlaceholderIndexes(template); if (phIndexes != null) { template = template.replaceAll("([.\\[\\]{}()*+\\-?^$|])", "\\\\$1"); for (int i = 0; i < phIndexes.length; i++) { if (phIndexes[i] != -1) { Placeholder placeholder = Placeholder.values()[i]; template = template.replace(placeholder.code, placeholder.regexp); } } template = ANY.regexp + template.replace(ANY.code, ANY.regexp) + ANY.regexp; Matcher matcher = Pattern.compile(template, DOTALL).matcher(sms); if (matcher.matches()) { results = new String[Placeholder.values().length]; for (int i = 0; i < phIndexes.length; i++) { final int groupNum = phIndexes[i] + 1; if (groupNum > 0) { results[i] = matcher.group(groupNum); } } } } return results; } } | SmsTransactionProcessor { public static String[] findTemplateMatches(String template, final String sms) { String[] results = null; template = preprocessPatterns(template); final int[] phIndexes = findPlaceholderIndexes(template); if (phIndexes != null) { template = template.replaceAll("([.\\[\\]{}()*+\\-?^$|])", "\\\\$1"); for (int i = 0; i < phIndexes.length; i++) { if (phIndexes[i] != -1) { Placeholder placeholder = Placeholder.values()[i]; template = template.replace(placeholder.code, placeholder.regexp); } } template = ANY.regexp + template.replace(ANY.code, ANY.regexp) + ANY.regexp; Matcher matcher = Pattern.compile(template, DOTALL).matcher(sms); if (matcher.matches()) { results = new String[Placeholder.values().length]; for (int i = 0; i < phIndexes.length; i++) { final int groupNum = phIndexes[i] + 1; if (groupNum > 0) { results[i] = matcher.group(groupNum); } } } } return results; } SmsTransactionProcessor(DatabaseAdapter db); } | SmsTransactionProcessor { public static String[] findTemplateMatches(String template, final String sms) { String[] results = null; template = preprocessPatterns(template); final int[] phIndexes = findPlaceholderIndexes(template); if (phIndexes != null) { template = template.replaceAll("([.\\[\\]{}()*+\\-?^$|])", "\\\\$1"); for (int i = 0; i < phIndexes.length; i++) { if (phIndexes[i] != -1) { Placeholder placeholder = Placeholder.values()[i]; template = template.replace(placeholder.code, placeholder.regexp); } } template = ANY.regexp + template.replace(ANY.code, ANY.regexp) + ANY.regexp; Matcher matcher = Pattern.compile(template, DOTALL).matcher(sms); if (matcher.matches()) { results = new String[Placeholder.values().length]; for (int i = 0; i < phIndexes.length; i++) { final int groupNum = phIndexes[i] + 1; if (groupNum > 0) { results[i] = matcher.group(groupNum); } } } } return results; } SmsTransactionProcessor(DatabaseAdapter db); Transaction createTransactionBySms(String addr, String fullSmsBody, TransactionStatus status, boolean updateNote); static String[] findTemplateMatches(String template, final String sms); } | SmsTransactionProcessor { public static String[] findTemplateMatches(String template, final String sms) { String[] results = null; template = preprocessPatterns(template); final int[] phIndexes = findPlaceholderIndexes(template); if (phIndexes != null) { template = template.replaceAll("([.\\[\\]{}()*+\\-?^$|])", "\\\\$1"); for (int i = 0; i < phIndexes.length; i++) { if (phIndexes[i] != -1) { Placeholder placeholder = Placeholder.values()[i]; template = template.replace(placeholder.code, placeholder.regexp); } } template = ANY.regexp + template.replace(ANY.code, ANY.regexp) + ANY.regexp; Matcher matcher = Pattern.compile(template, DOTALL).matcher(sms); if (matcher.matches()) { results = new String[Placeholder.values().length]; for (int i = 0; i < phIndexes.length; i++) { final int groupNum = phIndexes[i] + 1; if (groupNum > 0) { results[i] = matcher.group(groupNum); } } } } return results; } SmsTransactionProcessor(DatabaseAdapter db); Transaction createTransactionBySms(String addr, String fullSmsBody, TransactionStatus status, boolean updateNote); static String[] findTemplateMatches(String template, final String sms); } |
@Test public void TemplateWithAnyMatch() { String smsTpl = "ECMC{{A}}{{d}}покупка<:P:>р TEREMOK <::>Баланс:<:B:>р"; String sms = "ECMC5431 01.10.17 19:50 покупка 550р TEREMOK METROPOLIS Баланс: 49820.45р"; String[] matches = SmsTransactionProcessor.findTemplateMatches(smsTpl, sms); Assert.assertArrayEquals(new String[]{null, "5431", "49820.45", "01.10.17 19:50", "550", null}, matches); } | public static String[] findTemplateMatches(String template, final String sms) { String[] results = null; template = preprocessPatterns(template); final int[] phIndexes = findPlaceholderIndexes(template); if (phIndexes != null) { template = template.replaceAll("([.\\[\\]{}()*+\\-?^$|])", "\\\\$1"); for (int i = 0; i < phIndexes.length; i++) { if (phIndexes[i] != -1) { Placeholder placeholder = Placeholder.values()[i]; template = template.replace(placeholder.code, placeholder.regexp); } } template = ANY.regexp + template.replace(ANY.code, ANY.regexp) + ANY.regexp; Matcher matcher = Pattern.compile(template, DOTALL).matcher(sms); if (matcher.matches()) { results = new String[Placeholder.values().length]; for (int i = 0; i < phIndexes.length; i++) { final int groupNum = phIndexes[i] + 1; if (groupNum > 0) { results[i] = matcher.group(groupNum); } } } } return results; } | SmsTransactionProcessor { public static String[] findTemplateMatches(String template, final String sms) { String[] results = null; template = preprocessPatterns(template); final int[] phIndexes = findPlaceholderIndexes(template); if (phIndexes != null) { template = template.replaceAll("([.\\[\\]{}()*+\\-?^$|])", "\\\\$1"); for (int i = 0; i < phIndexes.length; i++) { if (phIndexes[i] != -1) { Placeholder placeholder = Placeholder.values()[i]; template = template.replace(placeholder.code, placeholder.regexp); } } template = ANY.regexp + template.replace(ANY.code, ANY.regexp) + ANY.regexp; Matcher matcher = Pattern.compile(template, DOTALL).matcher(sms); if (matcher.matches()) { results = new String[Placeholder.values().length]; for (int i = 0; i < phIndexes.length; i++) { final int groupNum = phIndexes[i] + 1; if (groupNum > 0) { results[i] = matcher.group(groupNum); } } } } return results; } } | SmsTransactionProcessor { public static String[] findTemplateMatches(String template, final String sms) { String[] results = null; template = preprocessPatterns(template); final int[] phIndexes = findPlaceholderIndexes(template); if (phIndexes != null) { template = template.replaceAll("([.\\[\\]{}()*+\\-?^$|])", "\\\\$1"); for (int i = 0; i < phIndexes.length; i++) { if (phIndexes[i] != -1) { Placeholder placeholder = Placeholder.values()[i]; template = template.replace(placeholder.code, placeholder.regexp); } } template = ANY.regexp + template.replace(ANY.code, ANY.regexp) + ANY.regexp; Matcher matcher = Pattern.compile(template, DOTALL).matcher(sms); if (matcher.matches()) { results = new String[Placeholder.values().length]; for (int i = 0; i < phIndexes.length; i++) { final int groupNum = phIndexes[i] + 1; if (groupNum > 0) { results[i] = matcher.group(groupNum); } } } } return results; } SmsTransactionProcessor(DatabaseAdapter db); } | SmsTransactionProcessor { public static String[] findTemplateMatches(String template, final String sms) { String[] results = null; template = preprocessPatterns(template); final int[] phIndexes = findPlaceholderIndexes(template); if (phIndexes != null) { template = template.replaceAll("([.\\[\\]{}()*+\\-?^$|])", "\\\\$1"); for (int i = 0; i < phIndexes.length; i++) { if (phIndexes[i] != -1) { Placeholder placeholder = Placeholder.values()[i]; template = template.replace(placeholder.code, placeholder.regexp); } } template = ANY.regexp + template.replace(ANY.code, ANY.regexp) + ANY.regexp; Matcher matcher = Pattern.compile(template, DOTALL).matcher(sms); if (matcher.matches()) { results = new String[Placeholder.values().length]; for (int i = 0; i < phIndexes.length; i++) { final int groupNum = phIndexes[i] + 1; if (groupNum > 0) { results[i] = matcher.group(groupNum); } } } } return results; } SmsTransactionProcessor(DatabaseAdapter db); Transaction createTransactionBySms(String addr, String fullSmsBody, TransactionStatus status, boolean updateNote); static String[] findTemplateMatches(String template, final String sms); } | SmsTransactionProcessor { public static String[] findTemplateMatches(String template, final String sms) { String[] results = null; template = preprocessPatterns(template); final int[] phIndexes = findPlaceholderIndexes(template); if (phIndexes != null) { template = template.replaceAll("([.\\[\\]{}()*+\\-?^$|])", "\\\\$1"); for (int i = 0; i < phIndexes.length; i++) { if (phIndexes[i] != -1) { Placeholder placeholder = Placeholder.values()[i]; template = template.replace(placeholder.code, placeholder.regexp); } } template = ANY.regexp + template.replace(ANY.code, ANY.regexp) + ANY.regexp; Matcher matcher = Pattern.compile(template, DOTALL).matcher(sms); if (matcher.matches()) { results = new String[Placeholder.values().length]; for (int i = 0; i < phIndexes.length; i++) { final int groupNum = phIndexes[i] + 1; if (groupNum > 0) { results[i] = matcher.group(groupNum); } } } } return results; } SmsTransactionProcessor(DatabaseAdapter db); Transaction createTransactionBySms(String addr, String fullSmsBody, TransactionStatus status, boolean updateNote); static String[] findTemplateMatches(String template, final String sms); } |
@Test public void TemplateWithMultipleAnyMatch() { String smsTpl = "ECMC<:A:> <:D:> {{*}} <:P:>р TEREMOK<::><:B:>р"; String sms = "ECMC5431 01.10.17 19:50 покупка 550р TEREMOK METROPOLIS Баланс: 49820.45р"; String[] matches = SmsTransactionProcessor.findTemplateMatches(smsTpl, sms); Assert.assertArrayEquals(new String[]{null, "5431", "49820.45", "01.10.17 19:50", "550", null}, matches); } | public static String[] findTemplateMatches(String template, final String sms) { String[] results = null; template = preprocessPatterns(template); final int[] phIndexes = findPlaceholderIndexes(template); if (phIndexes != null) { template = template.replaceAll("([.\\[\\]{}()*+\\-?^$|])", "\\\\$1"); for (int i = 0; i < phIndexes.length; i++) { if (phIndexes[i] != -1) { Placeholder placeholder = Placeholder.values()[i]; template = template.replace(placeholder.code, placeholder.regexp); } } template = ANY.regexp + template.replace(ANY.code, ANY.regexp) + ANY.regexp; Matcher matcher = Pattern.compile(template, DOTALL).matcher(sms); if (matcher.matches()) { results = new String[Placeholder.values().length]; for (int i = 0; i < phIndexes.length; i++) { final int groupNum = phIndexes[i] + 1; if (groupNum > 0) { results[i] = matcher.group(groupNum); } } } } return results; } | SmsTransactionProcessor { public static String[] findTemplateMatches(String template, final String sms) { String[] results = null; template = preprocessPatterns(template); final int[] phIndexes = findPlaceholderIndexes(template); if (phIndexes != null) { template = template.replaceAll("([.\\[\\]{}()*+\\-?^$|])", "\\\\$1"); for (int i = 0; i < phIndexes.length; i++) { if (phIndexes[i] != -1) { Placeholder placeholder = Placeholder.values()[i]; template = template.replace(placeholder.code, placeholder.regexp); } } template = ANY.regexp + template.replace(ANY.code, ANY.regexp) + ANY.regexp; Matcher matcher = Pattern.compile(template, DOTALL).matcher(sms); if (matcher.matches()) { results = new String[Placeholder.values().length]; for (int i = 0; i < phIndexes.length; i++) { final int groupNum = phIndexes[i] + 1; if (groupNum > 0) { results[i] = matcher.group(groupNum); } } } } return results; } } | SmsTransactionProcessor { public static String[] findTemplateMatches(String template, final String sms) { String[] results = null; template = preprocessPatterns(template); final int[] phIndexes = findPlaceholderIndexes(template); if (phIndexes != null) { template = template.replaceAll("([.\\[\\]{}()*+\\-?^$|])", "\\\\$1"); for (int i = 0; i < phIndexes.length; i++) { if (phIndexes[i] != -1) { Placeholder placeholder = Placeholder.values()[i]; template = template.replace(placeholder.code, placeholder.regexp); } } template = ANY.regexp + template.replace(ANY.code, ANY.regexp) + ANY.regexp; Matcher matcher = Pattern.compile(template, DOTALL).matcher(sms); if (matcher.matches()) { results = new String[Placeholder.values().length]; for (int i = 0; i < phIndexes.length; i++) { final int groupNum = phIndexes[i] + 1; if (groupNum > 0) { results[i] = matcher.group(groupNum); } } } } return results; } SmsTransactionProcessor(DatabaseAdapter db); } | SmsTransactionProcessor { public static String[] findTemplateMatches(String template, final String sms) { String[] results = null; template = preprocessPatterns(template); final int[] phIndexes = findPlaceholderIndexes(template); if (phIndexes != null) { template = template.replaceAll("([.\\[\\]{}()*+\\-?^$|])", "\\\\$1"); for (int i = 0; i < phIndexes.length; i++) { if (phIndexes[i] != -1) { Placeholder placeholder = Placeholder.values()[i]; template = template.replace(placeholder.code, placeholder.regexp); } } template = ANY.regexp + template.replace(ANY.code, ANY.regexp) + ANY.regexp; Matcher matcher = Pattern.compile(template, DOTALL).matcher(sms); if (matcher.matches()) { results = new String[Placeholder.values().length]; for (int i = 0; i < phIndexes.length; i++) { final int groupNum = phIndexes[i] + 1; if (groupNum > 0) { results[i] = matcher.group(groupNum); } } } } return results; } SmsTransactionProcessor(DatabaseAdapter db); Transaction createTransactionBySms(String addr, String fullSmsBody, TransactionStatus status, boolean updateNote); static String[] findTemplateMatches(String template, final String sms); } | SmsTransactionProcessor { public static String[] findTemplateMatches(String template, final String sms) { String[] results = null; template = preprocessPatterns(template); final int[] phIndexes = findPlaceholderIndexes(template); if (phIndexes != null) { template = template.replaceAll("([.\\[\\]{}()*+\\-?^$|])", "\\\\$1"); for (int i = 0; i < phIndexes.length; i++) { if (phIndexes[i] != -1) { Placeholder placeholder = Placeholder.values()[i]; template = template.replace(placeholder.code, placeholder.regexp); } } template = ANY.regexp + template.replace(ANY.code, ANY.regexp) + ANY.regexp; Matcher matcher = Pattern.compile(template, DOTALL).matcher(sms); if (matcher.matches()) { results = new String[Placeholder.values().length]; for (int i = 0; i < phIndexes.length; i++) { final int groupNum = phIndexes[i] + 1; if (groupNum > 0) { results[i] = matcher.group(groupNum); } } } } return results; } SmsTransactionProcessor(DatabaseAdapter db); Transaction createTransactionBySms(String addr, String fullSmsBody, TransactionStatus status, boolean updateNote); static String[] findTemplateMatches(String template, final String sms); } |
@Test public void TemplateWithMultipleAnyMatchWithoutAccount() { String smsTpl = "<::> <:D:> {{*}} <:P:>р TEREMOK<::><:B:>р"; String sms = "ECMC5431 01.10.17 19:50 покупка 550р TEREMOK METROPOLIS Баланс: 49820.45р"; String[] matches = SmsTransactionProcessor.findTemplateMatches(smsTpl, sms); Assert.assertArrayEquals(new String[]{null, null, "49820.45", "01.10.17 19:50", "550", null}, matches); } | public static String[] findTemplateMatches(String template, final String sms) { String[] results = null; template = preprocessPatterns(template); final int[] phIndexes = findPlaceholderIndexes(template); if (phIndexes != null) { template = template.replaceAll("([.\\[\\]{}()*+\\-?^$|])", "\\\\$1"); for (int i = 0; i < phIndexes.length; i++) { if (phIndexes[i] != -1) { Placeholder placeholder = Placeholder.values()[i]; template = template.replace(placeholder.code, placeholder.regexp); } } template = ANY.regexp + template.replace(ANY.code, ANY.regexp) + ANY.regexp; Matcher matcher = Pattern.compile(template, DOTALL).matcher(sms); if (matcher.matches()) { results = new String[Placeholder.values().length]; for (int i = 0; i < phIndexes.length; i++) { final int groupNum = phIndexes[i] + 1; if (groupNum > 0) { results[i] = matcher.group(groupNum); } } } } return results; } | SmsTransactionProcessor { public static String[] findTemplateMatches(String template, final String sms) { String[] results = null; template = preprocessPatterns(template); final int[] phIndexes = findPlaceholderIndexes(template); if (phIndexes != null) { template = template.replaceAll("([.\\[\\]{}()*+\\-?^$|])", "\\\\$1"); for (int i = 0; i < phIndexes.length; i++) { if (phIndexes[i] != -1) { Placeholder placeholder = Placeholder.values()[i]; template = template.replace(placeholder.code, placeholder.regexp); } } template = ANY.regexp + template.replace(ANY.code, ANY.regexp) + ANY.regexp; Matcher matcher = Pattern.compile(template, DOTALL).matcher(sms); if (matcher.matches()) { results = new String[Placeholder.values().length]; for (int i = 0; i < phIndexes.length; i++) { final int groupNum = phIndexes[i] + 1; if (groupNum > 0) { results[i] = matcher.group(groupNum); } } } } return results; } } | SmsTransactionProcessor { public static String[] findTemplateMatches(String template, final String sms) { String[] results = null; template = preprocessPatterns(template); final int[] phIndexes = findPlaceholderIndexes(template); if (phIndexes != null) { template = template.replaceAll("([.\\[\\]{}()*+\\-?^$|])", "\\\\$1"); for (int i = 0; i < phIndexes.length; i++) { if (phIndexes[i] != -1) { Placeholder placeholder = Placeholder.values()[i]; template = template.replace(placeholder.code, placeholder.regexp); } } template = ANY.regexp + template.replace(ANY.code, ANY.regexp) + ANY.regexp; Matcher matcher = Pattern.compile(template, DOTALL).matcher(sms); if (matcher.matches()) { results = new String[Placeholder.values().length]; for (int i = 0; i < phIndexes.length; i++) { final int groupNum = phIndexes[i] + 1; if (groupNum > 0) { results[i] = matcher.group(groupNum); } } } } return results; } SmsTransactionProcessor(DatabaseAdapter db); } | SmsTransactionProcessor { public static String[] findTemplateMatches(String template, final String sms) { String[] results = null; template = preprocessPatterns(template); final int[] phIndexes = findPlaceholderIndexes(template); if (phIndexes != null) { template = template.replaceAll("([.\\[\\]{}()*+\\-?^$|])", "\\\\$1"); for (int i = 0; i < phIndexes.length; i++) { if (phIndexes[i] != -1) { Placeholder placeholder = Placeholder.values()[i]; template = template.replace(placeholder.code, placeholder.regexp); } } template = ANY.regexp + template.replace(ANY.code, ANY.regexp) + ANY.regexp; Matcher matcher = Pattern.compile(template, DOTALL).matcher(sms); if (matcher.matches()) { results = new String[Placeholder.values().length]; for (int i = 0; i < phIndexes.length; i++) { final int groupNum = phIndexes[i] + 1; if (groupNum > 0) { results[i] = matcher.group(groupNum); } } } } return results; } SmsTransactionProcessor(DatabaseAdapter db); Transaction createTransactionBySms(String addr, String fullSmsBody, TransactionStatus status, boolean updateNote); static String[] findTemplateMatches(String template, final String sms); } | SmsTransactionProcessor { public static String[] findTemplateMatches(String template, final String sms) { String[] results = null; template = preprocessPatterns(template); final int[] phIndexes = findPlaceholderIndexes(template); if (phIndexes != null) { template = template.replaceAll("([.\\[\\]{}()*+\\-?^$|])", "\\\\$1"); for (int i = 0; i < phIndexes.length; i++) { if (phIndexes[i] != -1) { Placeholder placeholder = Placeholder.values()[i]; template = template.replace(placeholder.code, placeholder.regexp); } } template = ANY.regexp + template.replace(ANY.code, ANY.regexp) + ANY.regexp; Matcher matcher = Pattern.compile(template, DOTALL).matcher(sms); if (matcher.matches()) { results = new String[Placeholder.values().length]; for (int i = 0; i < phIndexes.length; i++) { final int groupNum = phIndexes[i] + 1; if (groupNum > 0) { results[i] = matcher.group(groupNum); } } } } return results; } SmsTransactionProcessor(DatabaseAdapter db); Transaction createTransactionBySms(String addr, String fullSmsBody, TransactionStatus status, boolean updateNote); static String[] findTemplateMatches(String template, final String sms); } |
@Test public void should_navigate_to_category() { long categoryId = categories.get("A").id; navigator.navigateTo(categoryId); assertSelected(categoryId, "A", "A1", "A2"); categoryId = categories.get("A1").id; navigator.navigateTo(categoryId); assertSelected(categoryId, "A1", "AA1"); categoryId = categories.get("AA1").id; navigator.navigateTo(categoryId); assertSelected(categoryId, "A1", "AA1"); } | public boolean navigateTo(long categoryId) { Category selectedCategory = findCategory(categoryId); if (selectedCategory != null) { selectedCategoryId = selectedCategory.id; if (selectedCategory.hasChildren()) { categoriesStack.push(categories); categories = selectedCategory.children; tagCategories(selectedCategory); return true; } } return false; } | CategoryTreeNavigator { public boolean navigateTo(long categoryId) { Category selectedCategory = findCategory(categoryId); if (selectedCategory != null) { selectedCategoryId = selectedCategory.id; if (selectedCategory.hasChildren()) { categoriesStack.push(categories); categories = selectedCategory.children; tagCategories(selectedCategory); return true; } } return false; } } | CategoryTreeNavigator { public boolean navigateTo(long categoryId) { Category selectedCategory = findCategory(categoryId); if (selectedCategory != null) { selectedCategoryId = selectedCategory.id; if (selectedCategory.hasChildren()) { categoriesStack.push(categories); categories = selectedCategory.children; tagCategories(selectedCategory); return true; } } return false; } CategoryTreeNavigator(DatabaseAdapter db); CategoryTreeNavigator(DatabaseAdapter db, long excludedTreeId); } | CategoryTreeNavigator { public boolean navigateTo(long categoryId) { Category selectedCategory = findCategory(categoryId); if (selectedCategory != null) { selectedCategoryId = selectedCategory.id; if (selectedCategory.hasChildren()) { categoriesStack.push(categories); categories = selectedCategory.children; tagCategories(selectedCategory); return true; } } return false; } CategoryTreeNavigator(DatabaseAdapter db); CategoryTreeNavigator(DatabaseAdapter db, long excludedTreeId); void selectCategory(long selectedCategoryId); void tagCategories(Category parent); boolean goBack(); boolean canGoBack(); boolean navigateTo(long categoryId); boolean isSelected(long categoryId); List<Category> getSelectedRoots(); void addSplitCategoryToTheTop(); void separateIncomeAndExpense(); long getExcludedTreeId(); } | CategoryTreeNavigator { public boolean navigateTo(long categoryId) { Category selectedCategory = findCategory(categoryId); if (selectedCategory != null) { selectedCategoryId = selectedCategory.id; if (selectedCategory.hasChildren()) { categoriesStack.push(categories); categories = selectedCategory.children; tagCategories(selectedCategory); return true; } } return false; } CategoryTreeNavigator(DatabaseAdapter db); CategoryTreeNavigator(DatabaseAdapter db, long excludedTreeId); void selectCategory(long selectedCategoryId); void tagCategories(Category parent); boolean goBack(); boolean canGoBack(); boolean navigateTo(long categoryId); boolean isSelected(long categoryId); List<Category> getSelectedRoots(); void addSplitCategoryToTheTop(); void separateIncomeAndExpense(); long getExcludedTreeId(); static final long INCOME_CATEGORY_ID; static final long EXPENSE_CATEGORY_ID; public CategoryTree<Category> categories; public long selectedCategoryId; } |
@Test public void TemplateWithSpecialChars() { String smsTpl = "{{*}} {{d}} {{*}} {{p}}р TE{{R}}E{{MOK ME}TROP<:P:OL?$()[]/\\.*IS{{*}}{{b}}р"; String sms = "ECMC5431 01.10.17 19:50 покупка 555р TE{{R}}E{{MOK ME}TROP<:P:OL?$()[]/\\.*IS Баланс: 49820.45р"; String[] matches = SmsTransactionProcessor.findTemplateMatches(smsTpl, sms); Assert.assertArrayEquals(new String[]{null, null, "49820.45", "01.10.17 19:50", "555", null}, matches); } | public static String[] findTemplateMatches(String template, final String sms) { String[] results = null; template = preprocessPatterns(template); final int[] phIndexes = findPlaceholderIndexes(template); if (phIndexes != null) { template = template.replaceAll("([.\\[\\]{}()*+\\-?^$|])", "\\\\$1"); for (int i = 0; i < phIndexes.length; i++) { if (phIndexes[i] != -1) { Placeholder placeholder = Placeholder.values()[i]; template = template.replace(placeholder.code, placeholder.regexp); } } template = ANY.regexp + template.replace(ANY.code, ANY.regexp) + ANY.regexp; Matcher matcher = Pattern.compile(template, DOTALL).matcher(sms); if (matcher.matches()) { results = new String[Placeholder.values().length]; for (int i = 0; i < phIndexes.length; i++) { final int groupNum = phIndexes[i] + 1; if (groupNum > 0) { results[i] = matcher.group(groupNum); } } } } return results; } | SmsTransactionProcessor { public static String[] findTemplateMatches(String template, final String sms) { String[] results = null; template = preprocessPatterns(template); final int[] phIndexes = findPlaceholderIndexes(template); if (phIndexes != null) { template = template.replaceAll("([.\\[\\]{}()*+\\-?^$|])", "\\\\$1"); for (int i = 0; i < phIndexes.length; i++) { if (phIndexes[i] != -1) { Placeholder placeholder = Placeholder.values()[i]; template = template.replace(placeholder.code, placeholder.regexp); } } template = ANY.regexp + template.replace(ANY.code, ANY.regexp) + ANY.regexp; Matcher matcher = Pattern.compile(template, DOTALL).matcher(sms); if (matcher.matches()) { results = new String[Placeholder.values().length]; for (int i = 0; i < phIndexes.length; i++) { final int groupNum = phIndexes[i] + 1; if (groupNum > 0) { results[i] = matcher.group(groupNum); } } } } return results; } } | SmsTransactionProcessor { public static String[] findTemplateMatches(String template, final String sms) { String[] results = null; template = preprocessPatterns(template); final int[] phIndexes = findPlaceholderIndexes(template); if (phIndexes != null) { template = template.replaceAll("([.\\[\\]{}()*+\\-?^$|])", "\\\\$1"); for (int i = 0; i < phIndexes.length; i++) { if (phIndexes[i] != -1) { Placeholder placeholder = Placeholder.values()[i]; template = template.replace(placeholder.code, placeholder.regexp); } } template = ANY.regexp + template.replace(ANY.code, ANY.regexp) + ANY.regexp; Matcher matcher = Pattern.compile(template, DOTALL).matcher(sms); if (matcher.matches()) { results = new String[Placeholder.values().length]; for (int i = 0; i < phIndexes.length; i++) { final int groupNum = phIndexes[i] + 1; if (groupNum > 0) { results[i] = matcher.group(groupNum); } } } } return results; } SmsTransactionProcessor(DatabaseAdapter db); } | SmsTransactionProcessor { public static String[] findTemplateMatches(String template, final String sms) { String[] results = null; template = preprocessPatterns(template); final int[] phIndexes = findPlaceholderIndexes(template); if (phIndexes != null) { template = template.replaceAll("([.\\[\\]{}()*+\\-?^$|])", "\\\\$1"); for (int i = 0; i < phIndexes.length; i++) { if (phIndexes[i] != -1) { Placeholder placeholder = Placeholder.values()[i]; template = template.replace(placeholder.code, placeholder.regexp); } } template = ANY.regexp + template.replace(ANY.code, ANY.regexp) + ANY.regexp; Matcher matcher = Pattern.compile(template, DOTALL).matcher(sms); if (matcher.matches()) { results = new String[Placeholder.values().length]; for (int i = 0; i < phIndexes.length; i++) { final int groupNum = phIndexes[i] + 1; if (groupNum > 0) { results[i] = matcher.group(groupNum); } } } } return results; } SmsTransactionProcessor(DatabaseAdapter db); Transaction createTransactionBySms(String addr, String fullSmsBody, TransactionStatus status, boolean updateNote); static String[] findTemplateMatches(String template, final String sms); } | SmsTransactionProcessor { public static String[] findTemplateMatches(String template, final String sms) { String[] results = null; template = preprocessPatterns(template); final int[] phIndexes = findPlaceholderIndexes(template); if (phIndexes != null) { template = template.replaceAll("([.\\[\\]{}()*+\\-?^$|])", "\\\\$1"); for (int i = 0; i < phIndexes.length; i++) { if (phIndexes[i] != -1) { Placeholder placeholder = Placeholder.values()[i]; template = template.replace(placeholder.code, placeholder.regexp); } } template = ANY.regexp + template.replace(ANY.code, ANY.regexp) + ANY.regexp; Matcher matcher = Pattern.compile(template, DOTALL).matcher(sms); if (matcher.matches()) { results = new String[Placeholder.values().length]; for (int i = 0; i < phIndexes.length; i++) { final int groupNum = phIndexes[i] + 1; if (groupNum > 0) { results[i] = matcher.group(groupNum); } } } } return results; } SmsTransactionProcessor(DatabaseAdapter db); Transaction createTransactionBySms(String addr, String fullSmsBody, TransactionStatus status, boolean updateNote); static String[] findTemplateMatches(String template, final String sms); } |
@Test public void MultipleAnyMatchWithoutAccountAndDate() { String smsTpl = "Pokupka{{*}}Summa {{p}} RUB. NOVYY PROEKT, MOSCOW{{*}}Dostupno {{b}} RUB.{{*}}"; String sms = "Pokupka. Karta *5631. Summa 250.00 RUB. NOVYY PROEKT, MOSCOW. 02.10.2017 14:19. Dostupno 34202.82 RUB. Tinkoff.ru"; String[] matches = SmsTransactionProcessor.findTemplateMatches(smsTpl, sms); Assert.assertArrayEquals(new String[]{null, null, "34202.82", null, "250.00", null}, matches); } | public static String[] findTemplateMatches(String template, final String sms) { String[] results = null; template = preprocessPatterns(template); final int[] phIndexes = findPlaceholderIndexes(template); if (phIndexes != null) { template = template.replaceAll("([.\\[\\]{}()*+\\-?^$|])", "\\\\$1"); for (int i = 0; i < phIndexes.length; i++) { if (phIndexes[i] != -1) { Placeholder placeholder = Placeholder.values()[i]; template = template.replace(placeholder.code, placeholder.regexp); } } template = ANY.regexp + template.replace(ANY.code, ANY.regexp) + ANY.regexp; Matcher matcher = Pattern.compile(template, DOTALL).matcher(sms); if (matcher.matches()) { results = new String[Placeholder.values().length]; for (int i = 0; i < phIndexes.length; i++) { final int groupNum = phIndexes[i] + 1; if (groupNum > 0) { results[i] = matcher.group(groupNum); } } } } return results; } | SmsTransactionProcessor { public static String[] findTemplateMatches(String template, final String sms) { String[] results = null; template = preprocessPatterns(template); final int[] phIndexes = findPlaceholderIndexes(template); if (phIndexes != null) { template = template.replaceAll("([.\\[\\]{}()*+\\-?^$|])", "\\\\$1"); for (int i = 0; i < phIndexes.length; i++) { if (phIndexes[i] != -1) { Placeholder placeholder = Placeholder.values()[i]; template = template.replace(placeholder.code, placeholder.regexp); } } template = ANY.regexp + template.replace(ANY.code, ANY.regexp) + ANY.regexp; Matcher matcher = Pattern.compile(template, DOTALL).matcher(sms); if (matcher.matches()) { results = new String[Placeholder.values().length]; for (int i = 0; i < phIndexes.length; i++) { final int groupNum = phIndexes[i] + 1; if (groupNum > 0) { results[i] = matcher.group(groupNum); } } } } return results; } } | SmsTransactionProcessor { public static String[] findTemplateMatches(String template, final String sms) { String[] results = null; template = preprocessPatterns(template); final int[] phIndexes = findPlaceholderIndexes(template); if (phIndexes != null) { template = template.replaceAll("([.\\[\\]{}()*+\\-?^$|])", "\\\\$1"); for (int i = 0; i < phIndexes.length; i++) { if (phIndexes[i] != -1) { Placeholder placeholder = Placeholder.values()[i]; template = template.replace(placeholder.code, placeholder.regexp); } } template = ANY.regexp + template.replace(ANY.code, ANY.regexp) + ANY.regexp; Matcher matcher = Pattern.compile(template, DOTALL).matcher(sms); if (matcher.matches()) { results = new String[Placeholder.values().length]; for (int i = 0; i < phIndexes.length; i++) { final int groupNum = phIndexes[i] + 1; if (groupNum > 0) { results[i] = matcher.group(groupNum); } } } } return results; } SmsTransactionProcessor(DatabaseAdapter db); } | SmsTransactionProcessor { public static String[] findTemplateMatches(String template, final String sms) { String[] results = null; template = preprocessPatterns(template); final int[] phIndexes = findPlaceholderIndexes(template); if (phIndexes != null) { template = template.replaceAll("([.\\[\\]{}()*+\\-?^$|])", "\\\\$1"); for (int i = 0; i < phIndexes.length; i++) { if (phIndexes[i] != -1) { Placeholder placeholder = Placeholder.values()[i]; template = template.replace(placeholder.code, placeholder.regexp); } } template = ANY.regexp + template.replace(ANY.code, ANY.regexp) + ANY.regexp; Matcher matcher = Pattern.compile(template, DOTALL).matcher(sms); if (matcher.matches()) { results = new String[Placeholder.values().length]; for (int i = 0; i < phIndexes.length; i++) { final int groupNum = phIndexes[i] + 1; if (groupNum > 0) { results[i] = matcher.group(groupNum); } } } } return results; } SmsTransactionProcessor(DatabaseAdapter db); Transaction createTransactionBySms(String addr, String fullSmsBody, TransactionStatus status, boolean updateNote); static String[] findTemplateMatches(String template, final String sms); } | SmsTransactionProcessor { public static String[] findTemplateMatches(String template, final String sms) { String[] results = null; template = preprocessPatterns(template); final int[] phIndexes = findPlaceholderIndexes(template); if (phIndexes != null) { template = template.replaceAll("([.\\[\\]{}()*+\\-?^$|])", "\\\\$1"); for (int i = 0; i < phIndexes.length; i++) { if (phIndexes[i] != -1) { Placeholder placeholder = Placeholder.values()[i]; template = template.replace(placeholder.code, placeholder.regexp); } } template = ANY.regexp + template.replace(ANY.code, ANY.regexp) + ANY.regexp; Matcher matcher = Pattern.compile(template, DOTALL).matcher(sms); if (matcher.matches()) { results = new String[Placeholder.values().length]; for (int i = 0; i < phIndexes.length; i++) { final int groupNum = phIndexes[i] + 1; if (groupNum > 0) { results[i] = matcher.group(groupNum); } } } } return results; } SmsTransactionProcessor(DatabaseAdapter db); Transaction createTransactionBySms(String addr, String fullSmsBody, TransactionStatus status, boolean updateNote); static String[] findTemplateMatches(String template, final String sms); } |
@Test public void FindingPlaceholderIndexes() { int[] indexes = SmsTransactionProcessor.findPlaceholderIndexes("Pokupka. Karta *<:A:>. Summa <:P:> RUB. NOVYY PROEKT, MOSCOW. <:D:>. Dostupno <:B:> RUB. Tinkoff.ru"); assertEquals(0, indexes[Placeholder.ACCOUNT.ordinal()]); assertEquals(1, indexes[Placeholder.PRICE.ordinal()]); assertEquals(2, indexes[Placeholder.DATE.ordinal()]); assertEquals(3, indexes[Placeholder.BALANCE.ordinal()]); indexes = SmsTransactionProcessor.findPlaceholderIndexes("ECMC<:A:> <:D:> покупка <:P:> TEREMOK METROPOLIS Баланс: <:B:>р"); assertEquals(0, indexes[Placeholder.ACCOUNT.ordinal()]); assertEquals(1, indexes[Placeholder.DATE.ordinal()]); assertEquals(2, indexes[Placeholder.PRICE.ordinal()]); assertEquals(3, indexes[Placeholder.BALANCE.ordinal()]); indexes = SmsTransactionProcessor.findPlaceholderIndexes("ECMC<:A:> <:D:> покупка <:P:> TEREMOK METROPOLIS Баланс:"); assertEquals(0, indexes[Placeholder.ACCOUNT.ordinal()]); assertEquals(1, indexes[Placeholder.DATE.ordinal()]); assertEquals(2, indexes[Placeholder.PRICE.ordinal()]); assertEquals(indexes[Placeholder.BALANCE.ordinal()], -1); indexes = SmsTransactionProcessor.findPlaceholderIndexes("ECMC<:A:> <:D:><::> <:P:> TEREMOK METROPOLIS Баланс:"); assertEquals(indexes[Placeholder.ANY.ordinal()], -1); assertEquals(0, indexes[Placeholder.ACCOUNT.ordinal()]); assertEquals(1, indexes[Placeholder.DATE.ordinal()]); assertEquals(2, indexes[Placeholder.PRICE.ordinal()]); assertEquals(indexes[Placeholder.BALANCE.ordinal()], -1); indexes = SmsTransactionProcessor.findPlaceholderIndexes("ECMC<:A:> <:D:><::> TEREMOK METROPOLIS Баланс:"); Assert.assertNull(indexes); } | static int[] findPlaceholderIndexes(String template) { Map<Integer, Placeholder> sorted = new TreeMap<>(); boolean foundPrice = false; for (Placeholder p : Placeholder.values()) { int i = template.indexOf(p.code); if (i >= 0) { if (p == PRICE) { foundPrice = true; } if (p != ANY) { sorted.put(i, p); } } } int[] result = null; if (foundPrice) { result = new int[Placeholder.values().length]; Arrays.fill(result, -1); int i = 0; for (Placeholder p : sorted.values()) { result[p.ordinal()] = i++; } } return result; } | SmsTransactionProcessor { static int[] findPlaceholderIndexes(String template) { Map<Integer, Placeholder> sorted = new TreeMap<>(); boolean foundPrice = false; for (Placeholder p : Placeholder.values()) { int i = template.indexOf(p.code); if (i >= 0) { if (p == PRICE) { foundPrice = true; } if (p != ANY) { sorted.put(i, p); } } } int[] result = null; if (foundPrice) { result = new int[Placeholder.values().length]; Arrays.fill(result, -1); int i = 0; for (Placeholder p : sorted.values()) { result[p.ordinal()] = i++; } } return result; } } | SmsTransactionProcessor { static int[] findPlaceholderIndexes(String template) { Map<Integer, Placeholder> sorted = new TreeMap<>(); boolean foundPrice = false; for (Placeholder p : Placeholder.values()) { int i = template.indexOf(p.code); if (i >= 0) { if (p == PRICE) { foundPrice = true; } if (p != ANY) { sorted.put(i, p); } } } int[] result = null; if (foundPrice) { result = new int[Placeholder.values().length]; Arrays.fill(result, -1); int i = 0; for (Placeholder p : sorted.values()) { result[p.ordinal()] = i++; } } return result; } SmsTransactionProcessor(DatabaseAdapter db); } | SmsTransactionProcessor { static int[] findPlaceholderIndexes(String template) { Map<Integer, Placeholder> sorted = new TreeMap<>(); boolean foundPrice = false; for (Placeholder p : Placeholder.values()) { int i = template.indexOf(p.code); if (i >= 0) { if (p == PRICE) { foundPrice = true; } if (p != ANY) { sorted.put(i, p); } } } int[] result = null; if (foundPrice) { result = new int[Placeholder.values().length]; Arrays.fill(result, -1); int i = 0; for (Placeholder p : sorted.values()) { result[p.ordinal()] = i++; } } return result; } SmsTransactionProcessor(DatabaseAdapter db); Transaction createTransactionBySms(String addr, String fullSmsBody, TransactionStatus status, boolean updateNote); static String[] findTemplateMatches(String template, final String sms); } | SmsTransactionProcessor { static int[] findPlaceholderIndexes(String template) { Map<Integer, Placeholder> sorted = new TreeMap<>(); boolean foundPrice = false; for (Placeholder p : Placeholder.values()) { int i = template.indexOf(p.code); if (i >= 0) { if (p == PRICE) { foundPrice = true; } if (p != ANY) { sorted.put(i, p); } } } int[] result = null; if (foundPrice) { result = new int[Placeholder.values().length]; Arrays.fill(result, -1); int i = 0; for (Placeholder p : sorted.values()) { result[p.ordinal()] = i++; } } return result; } SmsTransactionProcessor(DatabaseAdapter db); Transaction createTransactionBySms(String addr, String fullSmsBody, TransactionStatus status, boolean updateNote); static String[] findTemplateMatches(String template, final String sms); } |
@Test public void DifferentPrices() { Assert.assertEquals(new BigDecimal(5), toBigDecimal("5")); Assert.assertEquals(new BigDecimal("5.3"), toBigDecimal(" 5,3 ")); Assert.assertEquals(new BigDecimal("5.3"), toBigDecimal("5.3")); Assert.assertEquals(new BigDecimal("5000.3"), toBigDecimal("5.000,3")); Assert.assertEquals(new BigDecimal("5000000.3"), toBigDecimal("5.000.000,3")); Assert.assertEquals(new BigDecimal("5000000"), toBigDecimal("5.000.000")); Assert.assertEquals(new BigDecimal("5000.3"), toBigDecimal("5,000.3")); Assert.assertEquals(new BigDecimal("5000000.3"), toBigDecimal("5,000,000.3")); Assert.assertEquals(new BigDecimal("5000000"), toBigDecimal("5,000,000")); Assert.assertEquals(new BigDecimal("5"), toBigDecimal("+5")); Assert.assertEquals(new BigDecimal("5.3"), toBigDecimal("+5,3")); Assert.assertEquals(new BigDecimal("5.3"), toBigDecimal("+5.3")); Assert.assertEquals(new BigDecimal("5000.3"), toBigDecimal("+5.000,3")); Assert.assertEquals(new BigDecimal("5000000.3"), toBigDecimal("+5.000.000,3")); Assert.assertEquals(new BigDecimal("5000000"), toBigDecimal("+5.000.000")); Assert.assertEquals(new BigDecimal("5000.3"), toBigDecimal("+5,000.3")); Assert.assertEquals(new BigDecimal("5000000.3"), toBigDecimal("+5,000,000.3")); Assert.assertEquals(new BigDecimal("5000000"), toBigDecimal("+5,000,000")); Assert.assertEquals(new BigDecimal("-5"), toBigDecimal(" -5 ")); Assert.assertEquals(new BigDecimal("-5.3"), toBigDecimal("-5,3")); Assert.assertEquals(new BigDecimal("-5.3"), toBigDecimal("-5.3")); Assert.assertEquals(new BigDecimal("-5000.3"), toBigDecimal("-5.000,3")); Assert.assertEquals(new BigDecimal("-5000000.3"), toBigDecimal("-5.000.000,3")); Assert.assertEquals(new BigDecimal("-5000000"), toBigDecimal("-5.000.000")); Assert.assertEquals(new BigDecimal("-5000.3"), toBigDecimal("-5,000.3")); Assert.assertEquals(new BigDecimal("-5000000.3"), toBigDecimal("-5,000,000.3")); Assert.assertEquals(new BigDecimal("-5000000"), toBigDecimal("-5,000,000")); Assert.assertEquals(new BigDecimal("1234.56"), toBigDecimal("1 234.56")); Assert.assertEquals(new BigDecimal("1234.56"), toBigDecimal("1234.56")); Assert.assertEquals(new BigDecimal("1234.56"), toBigDecimal("1 234,56")); Assert.assertEquals(new BigDecimal("1234.56"), toBigDecimal("1 234,56")); Assert.assertEquals(new BigDecimal("1234.56"), toBigDecimal("1,234.56")); Assert.assertEquals(new BigDecimal("123456"), toBigDecimal("123456")); Assert.assertEquals(new BigDecimal("1234.5678"), toBigDecimal("1234,5678")); Assert.assertEquals(new BigDecimal("123456789"), toBigDecimal("123456789")); Assert.assertEquals(new BigDecimal("123456789"), toBigDecimal("123 456 789")); Assert.assertEquals(new BigDecimal("1234.56"), toBigDecimal("1'234.56")); } | static BigDecimal toBigDecimal(final String value) { if (value != null) { final String EMPTY = ""; final char COMMA = ','; final String POINT_AS_STRING = "."; final char POINT = '.'; final String COMMA_AS_STRING = ","; String trimmed = value.trim(); boolean negativeNumber = ((trimmed.contains("(") && trimmed.contains(")")) || trimmed.endsWith("-") || trimmed.startsWith("-")); String parsedValue = value.replaceAll("[^0-9,.]", EMPTY); if (negativeNumber) parsedValue = "-" + parsedValue; int lastPointPosition = parsedValue.lastIndexOf(POINT); int lastCommaPosition = parsedValue.lastIndexOf(COMMA); if (lastPointPosition == -1 && lastCommaPosition == -1) { return new BigDecimal(parsedValue); } if (lastPointPosition > -1 && lastCommaPosition == -1) { int firstPointPosition = parsedValue.indexOf(POINT); if (firstPointPosition != lastPointPosition) return new BigDecimal(parsedValue.replace(POINT_AS_STRING, EMPTY)); else return new BigDecimal(parsedValue); } if (lastPointPosition == -1 && lastCommaPosition > -1) { int firstCommaPosition = parsedValue.indexOf(COMMA); if (firstCommaPosition != lastCommaPosition) return new BigDecimal(parsedValue.replace(COMMA_AS_STRING, EMPTY)); else return new BigDecimal(parsedValue.replace(COMMA, POINT)); } if (lastPointPosition < lastCommaPosition) { parsedValue = parsedValue.replace(POINT_AS_STRING, EMPTY); return new BigDecimal(parsedValue.replace(COMMA, POINT)); } if (lastCommaPosition < lastPointPosition) { parsedValue = parsedValue.replace(COMMA_AS_STRING, EMPTY); return new BigDecimal(parsedValue); } } throw new NumberFormatException("Unexpected number format. Cannot convert '" + value + "' to BigDecimal."); } | SmsTransactionProcessor { static BigDecimal toBigDecimal(final String value) { if (value != null) { final String EMPTY = ""; final char COMMA = ','; final String POINT_AS_STRING = "."; final char POINT = '.'; final String COMMA_AS_STRING = ","; String trimmed = value.trim(); boolean negativeNumber = ((trimmed.contains("(") && trimmed.contains(")")) || trimmed.endsWith("-") || trimmed.startsWith("-")); String parsedValue = value.replaceAll("[^0-9,.]", EMPTY); if (negativeNumber) parsedValue = "-" + parsedValue; int lastPointPosition = parsedValue.lastIndexOf(POINT); int lastCommaPosition = parsedValue.lastIndexOf(COMMA); if (lastPointPosition == -1 && lastCommaPosition == -1) { return new BigDecimal(parsedValue); } if (lastPointPosition > -1 && lastCommaPosition == -1) { int firstPointPosition = parsedValue.indexOf(POINT); if (firstPointPosition != lastPointPosition) return new BigDecimal(parsedValue.replace(POINT_AS_STRING, EMPTY)); else return new BigDecimal(parsedValue); } if (lastPointPosition == -1 && lastCommaPosition > -1) { int firstCommaPosition = parsedValue.indexOf(COMMA); if (firstCommaPosition != lastCommaPosition) return new BigDecimal(parsedValue.replace(COMMA_AS_STRING, EMPTY)); else return new BigDecimal(parsedValue.replace(COMMA, POINT)); } if (lastPointPosition < lastCommaPosition) { parsedValue = parsedValue.replace(POINT_AS_STRING, EMPTY); return new BigDecimal(parsedValue.replace(COMMA, POINT)); } if (lastCommaPosition < lastPointPosition) { parsedValue = parsedValue.replace(COMMA_AS_STRING, EMPTY); return new BigDecimal(parsedValue); } } throw new NumberFormatException("Unexpected number format. Cannot convert '" + value + "' to BigDecimal."); } } | SmsTransactionProcessor { static BigDecimal toBigDecimal(final String value) { if (value != null) { final String EMPTY = ""; final char COMMA = ','; final String POINT_AS_STRING = "."; final char POINT = '.'; final String COMMA_AS_STRING = ","; String trimmed = value.trim(); boolean negativeNumber = ((trimmed.contains("(") && trimmed.contains(")")) || trimmed.endsWith("-") || trimmed.startsWith("-")); String parsedValue = value.replaceAll("[^0-9,.]", EMPTY); if (negativeNumber) parsedValue = "-" + parsedValue; int lastPointPosition = parsedValue.lastIndexOf(POINT); int lastCommaPosition = parsedValue.lastIndexOf(COMMA); if (lastPointPosition == -1 && lastCommaPosition == -1) { return new BigDecimal(parsedValue); } if (lastPointPosition > -1 && lastCommaPosition == -1) { int firstPointPosition = parsedValue.indexOf(POINT); if (firstPointPosition != lastPointPosition) return new BigDecimal(parsedValue.replace(POINT_AS_STRING, EMPTY)); else return new BigDecimal(parsedValue); } if (lastPointPosition == -1 && lastCommaPosition > -1) { int firstCommaPosition = parsedValue.indexOf(COMMA); if (firstCommaPosition != lastCommaPosition) return new BigDecimal(parsedValue.replace(COMMA_AS_STRING, EMPTY)); else return new BigDecimal(parsedValue.replace(COMMA, POINT)); } if (lastPointPosition < lastCommaPosition) { parsedValue = parsedValue.replace(POINT_AS_STRING, EMPTY); return new BigDecimal(parsedValue.replace(COMMA, POINT)); } if (lastCommaPosition < lastPointPosition) { parsedValue = parsedValue.replace(COMMA_AS_STRING, EMPTY); return new BigDecimal(parsedValue); } } throw new NumberFormatException("Unexpected number format. Cannot convert '" + value + "' to BigDecimal."); } SmsTransactionProcessor(DatabaseAdapter db); } | SmsTransactionProcessor { static BigDecimal toBigDecimal(final String value) { if (value != null) { final String EMPTY = ""; final char COMMA = ','; final String POINT_AS_STRING = "."; final char POINT = '.'; final String COMMA_AS_STRING = ","; String trimmed = value.trim(); boolean negativeNumber = ((trimmed.contains("(") && trimmed.contains(")")) || trimmed.endsWith("-") || trimmed.startsWith("-")); String parsedValue = value.replaceAll("[^0-9,.]", EMPTY); if (negativeNumber) parsedValue = "-" + parsedValue; int lastPointPosition = parsedValue.lastIndexOf(POINT); int lastCommaPosition = parsedValue.lastIndexOf(COMMA); if (lastPointPosition == -1 && lastCommaPosition == -1) { return new BigDecimal(parsedValue); } if (lastPointPosition > -1 && lastCommaPosition == -1) { int firstPointPosition = parsedValue.indexOf(POINT); if (firstPointPosition != lastPointPosition) return new BigDecimal(parsedValue.replace(POINT_AS_STRING, EMPTY)); else return new BigDecimal(parsedValue); } if (lastPointPosition == -1 && lastCommaPosition > -1) { int firstCommaPosition = parsedValue.indexOf(COMMA); if (firstCommaPosition != lastCommaPosition) return new BigDecimal(parsedValue.replace(COMMA_AS_STRING, EMPTY)); else return new BigDecimal(parsedValue.replace(COMMA, POINT)); } if (lastPointPosition < lastCommaPosition) { parsedValue = parsedValue.replace(POINT_AS_STRING, EMPTY); return new BigDecimal(parsedValue.replace(COMMA, POINT)); } if (lastCommaPosition < lastPointPosition) { parsedValue = parsedValue.replace(COMMA_AS_STRING, EMPTY); return new BigDecimal(parsedValue); } } throw new NumberFormatException("Unexpected number format. Cannot convert '" + value + "' to BigDecimal."); } SmsTransactionProcessor(DatabaseAdapter db); Transaction createTransactionBySms(String addr, String fullSmsBody, TransactionStatus status, boolean updateNote); static String[] findTemplateMatches(String template, final String sms); } | SmsTransactionProcessor { static BigDecimal toBigDecimal(final String value) { if (value != null) { final String EMPTY = ""; final char COMMA = ','; final String POINT_AS_STRING = "."; final char POINT = '.'; final String COMMA_AS_STRING = ","; String trimmed = value.trim(); boolean negativeNumber = ((trimmed.contains("(") && trimmed.contains(")")) || trimmed.endsWith("-") || trimmed.startsWith("-")); String parsedValue = value.replaceAll("[^0-9,.]", EMPTY); if (negativeNumber) parsedValue = "-" + parsedValue; int lastPointPosition = parsedValue.lastIndexOf(POINT); int lastCommaPosition = parsedValue.lastIndexOf(COMMA); if (lastPointPosition == -1 && lastCommaPosition == -1) { return new BigDecimal(parsedValue); } if (lastPointPosition > -1 && lastCommaPosition == -1) { int firstPointPosition = parsedValue.indexOf(POINT); if (firstPointPosition != lastPointPosition) return new BigDecimal(parsedValue.replace(POINT_AS_STRING, EMPTY)); else return new BigDecimal(parsedValue); } if (lastPointPosition == -1 && lastCommaPosition > -1) { int firstCommaPosition = parsedValue.indexOf(COMMA); if (firstCommaPosition != lastCommaPosition) return new BigDecimal(parsedValue.replace(COMMA_AS_STRING, EMPTY)); else return new BigDecimal(parsedValue.replace(COMMA, POINT)); } if (lastPointPosition < lastCommaPosition) { parsedValue = parsedValue.replace(POINT_AS_STRING, EMPTY); return new BigDecimal(parsedValue.replace(COMMA, POINT)); } if (lastCommaPosition < lastPointPosition) { parsedValue = parsedValue.replace(COMMA_AS_STRING, EMPTY); return new BigDecimal(parsedValue); } } throw new NumberFormatException("Unexpected number format. Cannot convert '" + value + "' to BigDecimal."); } SmsTransactionProcessor(DatabaseAdapter db); Transaction createTransactionBySms(String addr, String fullSmsBody, TransactionStatus status, boolean updateNote); static String[] findTemplateMatches(String template, final String sms); } |
@Test public void should_detect_that_running_balance_is_broken() { TransactionBuilder.withDb(db).account(a1).amount(1000).create(); TransactionBuilder.withDb(db).account(a1).amount(2000).create(); TransactionBuilder.withDb(db).account(a2).amount(-100).create(); assertEquals(IntegrityCheck.Level.OK, integrity.check().level); breakRunningBalanceForAccount(a1); assertEquals(IntegrityCheck.Level.ERROR, integrity.check().level); db.rebuildRunningBalanceForAccount(a1); assertEquals(IntegrityCheck.Level.OK, integrity.check().level); breakRunningBalance(); assertEquals(IntegrityCheck.Level.ERROR, integrity.check().level); db.rebuildRunningBalances(); assertEquals(IntegrityCheck.Level.OK, integrity.check().level); } | @Override public Result check() { if (isRunningBalanceBroken()) { return new Result(Level.ERROR, context.getString(R.string.integrity_error)); } else { return Result.OK; } } | IntegrityCheckRunningBalance implements IntegrityCheck { @Override public Result check() { if (isRunningBalanceBroken()) { return new Result(Level.ERROR, context.getString(R.string.integrity_error)); } else { return Result.OK; } } } | IntegrityCheckRunningBalance implements IntegrityCheck { @Override public Result check() { if (isRunningBalanceBroken()) { return new Result(Level.ERROR, context.getString(R.string.integrity_error)); } else { return Result.OK; } } IntegrityCheckRunningBalance(Context context, DatabaseAdapter db); } | IntegrityCheckRunningBalance implements IntegrityCheck { @Override public Result check() { if (isRunningBalanceBroken()) { return new Result(Level.ERROR, context.getString(R.string.integrity_error)); } else { return Result.OK; } } IntegrityCheckRunningBalance(Context context, DatabaseAdapter db); @Override Result check(); } | IntegrityCheckRunningBalance implements IntegrityCheck { @Override public Result check() { if (isRunningBalanceBroken()) { return new Result(Level.ERROR, context.getString(R.string.integrity_error)); } else { return Result.OK; } } IntegrityCheckRunningBalance(Context context, DatabaseAdapter db); @Override Result check(); } |
@Test public void should_check_if_autobackup_has_been_disabled() { givenAutobackupReminderEnabledIs(true); givenAutobackupEnabledIs(false); givenFirstRunAfterRelease(); assertEquals(IntegrityCheck.Level.OK, integrity.check().level); sleepMillis(50); assertEquals(IntegrityCheck.Level.OK, integrity.check().level); sleepMillis(51); assertEquals(IntegrityCheck.Level.INFO, integrity.check().level); assertEquals(IntegrityCheck.Level.OK, integrity.check().level); givenAutobackupEnabledIs(true); sleepMillis(101); assertEquals(IntegrityCheck.Level.OK, integrity.check().level); givenAutobackupReminderEnabledIs(false); givenAutobackupEnabledIs(false); sleepMillis(101); assertEquals(IntegrityCheck.Level.OK, integrity.check().level); } | @Override public Result check() { if (MyPreferences.isAutoBackupEnabled(context)) { if (MyPreferences.isAutoBackupWarningEnabled(context)) { MyPreferences.AutobackupStatus status = MyPreferences.getAutobackupStatus(context); if (status.notify) { MyPreferences.notifyAutobackupSucceeded(context); return new Result(Level.ERROR, context.getString(R.string.autobackup_failed_message, DateUtils.getTimeFormat(context).format(new Date(status.timestamp)), status.errorMessage)); } } } else { if (MyPreferences.isAutoBackupReminderEnabled(context)) { long lastCheck = MyPreferences.getLastAutobackupCheck(context); if (lastCheck == 0) { MyPreferences.updateLastAutobackupCheck(context); } else { long delta = System.currentTimeMillis() - lastCheck; if (delta > threshold) { MyPreferences.updateLastAutobackupCheck(context); return new Result(Level.INFO, context.getString(R.string.auto_backup_is_not_enabled)); } } } } return Result.OK; } | IntegrityCheckAutobackup implements IntegrityCheck { @Override public Result check() { if (MyPreferences.isAutoBackupEnabled(context)) { if (MyPreferences.isAutoBackupWarningEnabled(context)) { MyPreferences.AutobackupStatus status = MyPreferences.getAutobackupStatus(context); if (status.notify) { MyPreferences.notifyAutobackupSucceeded(context); return new Result(Level.ERROR, context.getString(R.string.autobackup_failed_message, DateUtils.getTimeFormat(context).format(new Date(status.timestamp)), status.errorMessage)); } } } else { if (MyPreferences.isAutoBackupReminderEnabled(context)) { long lastCheck = MyPreferences.getLastAutobackupCheck(context); if (lastCheck == 0) { MyPreferences.updateLastAutobackupCheck(context); } else { long delta = System.currentTimeMillis() - lastCheck; if (delta > threshold) { MyPreferences.updateLastAutobackupCheck(context); return new Result(Level.INFO, context.getString(R.string.auto_backup_is_not_enabled)); } } } } return Result.OK; } } | IntegrityCheckAutobackup implements IntegrityCheck { @Override public Result check() { if (MyPreferences.isAutoBackupEnabled(context)) { if (MyPreferences.isAutoBackupWarningEnabled(context)) { MyPreferences.AutobackupStatus status = MyPreferences.getAutobackupStatus(context); if (status.notify) { MyPreferences.notifyAutobackupSucceeded(context); return new Result(Level.ERROR, context.getString(R.string.autobackup_failed_message, DateUtils.getTimeFormat(context).format(new Date(status.timestamp)), status.errorMessage)); } } } else { if (MyPreferences.isAutoBackupReminderEnabled(context)) { long lastCheck = MyPreferences.getLastAutobackupCheck(context); if (lastCheck == 0) { MyPreferences.updateLastAutobackupCheck(context); } else { long delta = System.currentTimeMillis() - lastCheck; if (delta > threshold) { MyPreferences.updateLastAutobackupCheck(context); return new Result(Level.INFO, context.getString(R.string.auto_backup_is_not_enabled)); } } } } return Result.OK; } IntegrityCheckAutobackup(Context context, long threshold); } | IntegrityCheckAutobackup implements IntegrityCheck { @Override public Result check() { if (MyPreferences.isAutoBackupEnabled(context)) { if (MyPreferences.isAutoBackupWarningEnabled(context)) { MyPreferences.AutobackupStatus status = MyPreferences.getAutobackupStatus(context); if (status.notify) { MyPreferences.notifyAutobackupSucceeded(context); return new Result(Level.ERROR, context.getString(R.string.autobackup_failed_message, DateUtils.getTimeFormat(context).format(new Date(status.timestamp)), status.errorMessage)); } } } else { if (MyPreferences.isAutoBackupReminderEnabled(context)) { long lastCheck = MyPreferences.getLastAutobackupCheck(context); if (lastCheck == 0) { MyPreferences.updateLastAutobackupCheck(context); } else { long delta = System.currentTimeMillis() - lastCheck; if (delta > threshold) { MyPreferences.updateLastAutobackupCheck(context); return new Result(Level.INFO, context.getString(R.string.auto_backup_is_not_enabled)); } } } } return Result.OK; } IntegrityCheckAutobackup(Context context, long threshold); @Override Result check(); } | IntegrityCheckAutobackup implements IntegrityCheck { @Override public Result check() { if (MyPreferences.isAutoBackupEnabled(context)) { if (MyPreferences.isAutoBackupWarningEnabled(context)) { MyPreferences.AutobackupStatus status = MyPreferences.getAutobackupStatus(context); if (status.notify) { MyPreferences.notifyAutobackupSucceeded(context); return new Result(Level.ERROR, context.getString(R.string.autobackup_failed_message, DateUtils.getTimeFormat(context).format(new Date(status.timestamp)), status.errorMessage)); } } } else { if (MyPreferences.isAutoBackupReminderEnabled(context)) { long lastCheck = MyPreferences.getLastAutobackupCheck(context); if (lastCheck == 0) { MyPreferences.updateLastAutobackupCheck(context); } else { long delta = System.currentTimeMillis() - lastCheck; if (delta > threshold) { MyPreferences.updateLastAutobackupCheck(context); return new Result(Level.INFO, context.getString(R.string.auto_backup_is_not_enabled)); } } } } return Result.OK; } IntegrityCheckAutobackup(Context context, long threshold); @Override Result check(); } |
@Test public void should_check_if_the_last_autobackup_has_failed() { givenAutobackupWarningEnabledIs(true); givenAutobackupEnabledIs(true); givenFirstRunAfterRelease(); assertEquals(IntegrityCheck.Level.OK, integrity.check().level); givenTheLastAutobackupHasFailed(); assertEquals(IntegrityCheck.Level.ERROR, integrity.check().level); assertEquals(IntegrityCheck.Level.OK, integrity.check().level); givenTheLastAutobackupHasFailed(); givenTheLastAutobackupHasSucceeded(); assertEquals(IntegrityCheck.Level.OK, integrity.check().level); givenAutobackupWarningEnabledIs(false); givenTheLastAutobackupHasFailed(); assertEquals(IntegrityCheck.Level.OK, integrity.check().level); } | @Override public Result check() { if (MyPreferences.isAutoBackupEnabled(context)) { if (MyPreferences.isAutoBackupWarningEnabled(context)) { MyPreferences.AutobackupStatus status = MyPreferences.getAutobackupStatus(context); if (status.notify) { MyPreferences.notifyAutobackupSucceeded(context); return new Result(Level.ERROR, context.getString(R.string.autobackup_failed_message, DateUtils.getTimeFormat(context).format(new Date(status.timestamp)), status.errorMessage)); } } } else { if (MyPreferences.isAutoBackupReminderEnabled(context)) { long lastCheck = MyPreferences.getLastAutobackupCheck(context); if (lastCheck == 0) { MyPreferences.updateLastAutobackupCheck(context); } else { long delta = System.currentTimeMillis() - lastCheck; if (delta > threshold) { MyPreferences.updateLastAutobackupCheck(context); return new Result(Level.INFO, context.getString(R.string.auto_backup_is_not_enabled)); } } } } return Result.OK; } | IntegrityCheckAutobackup implements IntegrityCheck { @Override public Result check() { if (MyPreferences.isAutoBackupEnabled(context)) { if (MyPreferences.isAutoBackupWarningEnabled(context)) { MyPreferences.AutobackupStatus status = MyPreferences.getAutobackupStatus(context); if (status.notify) { MyPreferences.notifyAutobackupSucceeded(context); return new Result(Level.ERROR, context.getString(R.string.autobackup_failed_message, DateUtils.getTimeFormat(context).format(new Date(status.timestamp)), status.errorMessage)); } } } else { if (MyPreferences.isAutoBackupReminderEnabled(context)) { long lastCheck = MyPreferences.getLastAutobackupCheck(context); if (lastCheck == 0) { MyPreferences.updateLastAutobackupCheck(context); } else { long delta = System.currentTimeMillis() - lastCheck; if (delta > threshold) { MyPreferences.updateLastAutobackupCheck(context); return new Result(Level.INFO, context.getString(R.string.auto_backup_is_not_enabled)); } } } } return Result.OK; } } | IntegrityCheckAutobackup implements IntegrityCheck { @Override public Result check() { if (MyPreferences.isAutoBackupEnabled(context)) { if (MyPreferences.isAutoBackupWarningEnabled(context)) { MyPreferences.AutobackupStatus status = MyPreferences.getAutobackupStatus(context); if (status.notify) { MyPreferences.notifyAutobackupSucceeded(context); return new Result(Level.ERROR, context.getString(R.string.autobackup_failed_message, DateUtils.getTimeFormat(context).format(new Date(status.timestamp)), status.errorMessage)); } } } else { if (MyPreferences.isAutoBackupReminderEnabled(context)) { long lastCheck = MyPreferences.getLastAutobackupCheck(context); if (lastCheck == 0) { MyPreferences.updateLastAutobackupCheck(context); } else { long delta = System.currentTimeMillis() - lastCheck; if (delta > threshold) { MyPreferences.updateLastAutobackupCheck(context); return new Result(Level.INFO, context.getString(R.string.auto_backup_is_not_enabled)); } } } } return Result.OK; } IntegrityCheckAutobackup(Context context, long threshold); } | IntegrityCheckAutobackup implements IntegrityCheck { @Override public Result check() { if (MyPreferences.isAutoBackupEnabled(context)) { if (MyPreferences.isAutoBackupWarningEnabled(context)) { MyPreferences.AutobackupStatus status = MyPreferences.getAutobackupStatus(context); if (status.notify) { MyPreferences.notifyAutobackupSucceeded(context); return new Result(Level.ERROR, context.getString(R.string.autobackup_failed_message, DateUtils.getTimeFormat(context).format(new Date(status.timestamp)), status.errorMessage)); } } } else { if (MyPreferences.isAutoBackupReminderEnabled(context)) { long lastCheck = MyPreferences.getLastAutobackupCheck(context); if (lastCheck == 0) { MyPreferences.updateLastAutobackupCheck(context); } else { long delta = System.currentTimeMillis() - lastCheck; if (delta > threshold) { MyPreferences.updateLastAutobackupCheck(context); return new Result(Level.INFO, context.getString(R.string.auto_backup_is_not_enabled)); } } } } return Result.OK; } IntegrityCheckAutobackup(Context context, long threshold); @Override Result check(); } | IntegrityCheckAutobackup implements IntegrityCheck { @Override public Result check() { if (MyPreferences.isAutoBackupEnabled(context)) { if (MyPreferences.isAutoBackupWarningEnabled(context)) { MyPreferences.AutobackupStatus status = MyPreferences.getAutobackupStatus(context); if (status.notify) { MyPreferences.notifyAutobackupSucceeded(context); return new Result(Level.ERROR, context.getString(R.string.autobackup_failed_message, DateUtils.getTimeFormat(context).format(new Date(status.timestamp)), status.errorMessage)); } } } else { if (MyPreferences.isAutoBackupReminderEnabled(context)) { long lastCheck = MyPreferences.getLastAutobackupCheck(context); if (lastCheck == 0) { MyPreferences.updateLastAutobackupCheck(context); } else { long delta = System.currentTimeMillis() - lastCheck; if (delta > threshold) { MyPreferences.updateLastAutobackupCheck(context); return new Result(Level.INFO, context.getString(R.string.auto_backup_is_not_enabled)); } } } } return Result.OK; } IntegrityCheckAutobackup(Context context, long threshold); @Override Result check(); } |
@Test public void should_add_selected_currency_as_default_if_it_is_the_very_first_currency_added() { givenNoCurrenciesYetExist(); selector.addSelectedCurrency(1); Currency currency1 = db.load(Currency.class, currencyId); assertTrue(currency1.isDefault); selector.addSelectedCurrency(2); Currency currency2 = db.load(Currency.class, currencyId); assertTrue(currency1.isDefault); assertFalse(currency2.isDefault); } | public void addSelectedCurrency(int selectedCurrency) { if (selectedCurrency > 0 && selectedCurrency <= currencies.size()) { List<String> c = currencies.get(selectedCurrency-1); addSelectedCurrency(c); } else { listener.onCreated(0); } } | CurrencySelector { public void addSelectedCurrency(int selectedCurrency) { if (selectedCurrency > 0 && selectedCurrency <= currencies.size()) { List<String> c = currencies.get(selectedCurrency-1); addSelectedCurrency(c); } else { listener.onCreated(0); } } } | CurrencySelector { public void addSelectedCurrency(int selectedCurrency) { if (selectedCurrency > 0 && selectedCurrency <= currencies.size()) { List<String> c = currencies.get(selectedCurrency-1); addSelectedCurrency(c); } else { listener.onCreated(0); } } CurrencySelector(Context context, MyEntityManager em, OnCurrencyCreatedListener listener); } | CurrencySelector { public void addSelectedCurrency(int selectedCurrency) { if (selectedCurrency > 0 && selectedCurrency <= currencies.size()) { List<String> c = currencies.get(selectedCurrency-1); addSelectedCurrency(c); } else { listener.onCreated(0); } } CurrencySelector(Context context, MyEntityManager em, OnCurrencyCreatedListener listener); void show(); void addSelectedCurrency(int selectedCurrency); } | CurrencySelector { public void addSelectedCurrency(int selectedCurrency) { if (selectedCurrency > 0 && selectedCurrency <= currencies.size()) { List<String> c = currencies.get(selectedCurrency-1); addSelectedCurrency(c); } else { listener.onCreated(0); } } CurrencySelector(Context context, MyEntityManager em, OnCurrencyCreatedListener listener); void show(); void addSelectedCurrency(int selectedCurrency); } |
@Test public void should_split_category_name() { assertEquals("P1", extractCategoryName("P1")); assertEquals("P1:c1", extractCategoryName("P1:c1")); assertEquals("P1", extractCategoryName("P1/C2")); assertEquals("P1:c1", extractCategoryName("P1:c1/C2")); } | public static String extractCategoryName(String name) { int i = name.indexOf('/'); if (i != -1) { name = name.substring(0, i); } return name; } | CategoryCache { public static String extractCategoryName(String name) { int i = name.indexOf('/'); if (i != -1) { name = name.substring(0, i); } return name; } } | CategoryCache { public static String extractCategoryName(String name) { int i = name.indexOf('/'); if (i != -1) { name = name.substring(0, i); } return name; } } | CategoryCache { public static String extractCategoryName(String name) { int i = name.indexOf('/'); if (i != -1) { name = name.substring(0, i); } return name; } static String extractCategoryName(String name); void loadExistingCategories(DatabaseAdapter db); void insertCategories(DatabaseAdapter dbAdapter, Set<? extends CategoryInfo> categories); Category findCategory(String category); } | CategoryCache { public static String extractCategoryName(String name) { int i = name.indexOf('/'); if (i != -1) { name = name.substring(0, i); } return name; } static String extractCategoryName(String name); void loadExistingCategories(DatabaseAdapter db); void insertCategories(DatabaseAdapter dbAdapter, Set<? extends CategoryInfo> categories); Category findCategory(String category); public Map<String, Category> categoryNameToCategory; public CategoryTree<Category> categoryTree; } |
@Test public void should_detect_multiple_account_currencies() { assertTrue(db.singleCurrencyOnly()); AccountBuilder.withDb(db).currency(a1.currency).title("Account2").create(); assertTrue(db.singleCurrencyOnly()); Currency c2 = CurrencyBuilder.withDb(db).name("USD").title("Dollar").symbol("$").create(); AccountBuilder.withDb(db).currency(c2).title("Account3").doNotIncludeIntoTotals().create(); assertTrue(db.singleCurrencyOnly()); AccountBuilder.withDb(db).currency(c2).title("Account4").inactive().create(); assertTrue(db.singleCurrencyOnly()); AccountBuilder.withDb(db).currency(c2).title("Account5").create(); assertFalse(db.singleCurrencyOnly()); } | public boolean singleCurrencyOnly() { long currencyId = getSingleCurrencyId(); return currencyId > 0; } | DatabaseAdapter extends MyEntityManager { public boolean singleCurrencyOnly() { long currencyId = getSingleCurrencyId(); return currencyId > 0; } } | DatabaseAdapter extends MyEntityManager { public boolean singleCurrencyOnly() { long currencyId = getSingleCurrencyId(); return currencyId > 0; } DatabaseAdapter(Context context); } | DatabaseAdapter extends MyEntityManager { public boolean singleCurrencyOnly() { long currencyId = getSingleCurrencyId(); return currencyId > 0; } DatabaseAdapter(Context context); void open(); void close(); int deleteAccount(long id); Transaction getTransaction(long id); Cursor getBlotter(WhereFilter filter); Cursor getBlotterForAccount(WhereFilter filter); static WhereFilter enhanceFilterForAccountBlotter(WhereFilter filter); Cursor getBlotterForAccountWithSplits(WhereFilter filter); Cursor getAllTemplates(WhereFilter filter, String sortBy); Cursor getBlotterWithSplits(String where); long duplicateTransaction(long id); long duplicateTransactionWithMultiplier(long id, int multiplier); long duplicateTransactionAsTemplate(long id); long insertOrUpdate(Transaction transaction); long insertOrUpdate(Transaction transaction, List<TransactionAttribute> attributes); long insertOrUpdateInTransaction(Transaction transaction, List<TransactionAttribute> attributes); void insertWithoutUpdatingBalance(Transaction transaction); void updateTransactionStatus(long id, TransactionStatus status); void deleteTransaction(long id); void deleteTransactionNoDbTransaction(long id); long insertOrUpdate(Category category, List<Attribute> attributes); Category getCategoryWithParent(long id); List<Long> getCategoryIdsByLeftIds(List<String> leftIds); Category getCategoryByLeft(long left); CategoryTree<Category> getCategoriesTreeWithoutSubTree(long excludingTreeId, boolean includeNoCategory); CategoryTree<Category> getCategoriesTree(boolean includeNoCategory); CategoryTree<Category> getAllCategoriesTree(); Map<Long, Category> getAllCategoriesMap(); List<Category> getCategoriesList(boolean includeNoCategory); Cursor getAllCategories(); List<Category> getAllCategoriesList(); Cursor getCategories(boolean includeNoCategory); Cursor filterCategories(CharSequence titleFilter); Cursor getCategories(boolean includeNoCategory, CharSequence titleFilter); Cursor getCategoriesWithoutSubtree(long id, boolean includeNoCategory); List<Category> getCategoriesWithoutSubtreeAsList(long categoryId); long insertChildCategory(long parentId, Category category); long insertMateCategory(long categoryId, Category category); void deleteCategory(long categoryId); void insertCategoryTreeInTransaction(CategoryTree<Category> tree); void updateCategoryTree(CategoryTree<Category> tree); List<SmsTemplate> getSmsTemplatesForCategory(long categoryId); List<SmsTemplate> getSmsTemplatesByNumber(String smsNumber); Set<String> findAllSmsTemplateNumbers(); Cursor getAllSmsTemplates(); Cursor getSmsTemplatesWithFullInfo(); Cursor getSmsTemplatesWithFullInfo(final String filter); long duplicateSmsTemplateBelowOriginal(long id); ArrayList<Attribute> getAttributesForCategory(long categoryId); ArrayList<Attribute> getAllAttributesForCategory(long categoryId); Attribute getSystemAttribute(SystemAttribute a); Attribute getAttribute(long id); long insertOrUpdate(Attribute attribute); void deleteAttribute(long id); Cursor getAllAttributes(); Map<Long, String> getAllAttributesMap(); Map<Long, String> getAllAttributesForTransaction(long transactionId); EnumMap<SystemAttribute, String> getSystemAttributesForTransaction(long transactionId); void clearSelectedTransactions(long[] ids); void reconcileSelectedTransactions(long[] ids); void deleteSelectedTransactions(long[] ids); long[] storeMissedSchedules(List<RestoredTransaction> restored, long now); int getCustomClosingDay(long accountId, int period); void setCustomClosingDay(long accountId, int period, int closingDay); void deleteCustomClosingDay(long accountId, int period); void updateCustomClosingDay(long accountId, int period, int closingDay); void rebuildRunningBalances(); void rebuildRunningBalanceForAccount(Account account); long fetchBudgetBalance(Map<Long, Category> categories, Map<Long, Project> projects, Budget b); void recalculateAccountsBalances(); void saveRate(ExchangeRate r); void replaceRate(ExchangeRate rate, long originalDate); void saveDownloadedRates(List<ExchangeRate> downloadedRates); ExchangeRate findRate(Currency fromCurrency, Currency toCurrency, long date); List<ExchangeRate> findRates(Currency fromCurrency); List<ExchangeRate> findRates(Currency fromCurrency, Currency toCurrency); ExchangeRateProvider getLatestRates(); ExchangeRateProvider getHistoryRates(); void deleteRate(ExchangeRate rate); void deleteRate(long fromCurrencyId, long toCurrencyId, long date); Total getAccountsTotalInHomeCurrency(); Total[] getAccountsTotal(); Total getAccountsTotal(Currency homeCurrency); List<Long> findAccountsByNumber(String numberEnding); boolean singleCurrencyOnly(); void setDefaultHomeCurrency(); void purgeAccountAtDate(Account account, long date); void deleteOldTransactions(Account account, long date); long getAccountBalanceForTransaction(Account a, Transaction t); long findNearestOlderTransactionId(Account account, long date); long findLatestTransactionDate(long accountId); void updateAccountsLastTransactionDate(); void restoreSystemEntities(); long getLastRunningBalanceForAccount(Account account); } | DatabaseAdapter extends MyEntityManager { public boolean singleCurrencyOnly() { long currencyId = getSingleCurrencyId(); return currencyId > 0; } DatabaseAdapter(Context context); void open(); void close(); int deleteAccount(long id); Transaction getTransaction(long id); Cursor getBlotter(WhereFilter filter); Cursor getBlotterForAccount(WhereFilter filter); static WhereFilter enhanceFilterForAccountBlotter(WhereFilter filter); Cursor getBlotterForAccountWithSplits(WhereFilter filter); Cursor getAllTemplates(WhereFilter filter, String sortBy); Cursor getBlotterWithSplits(String where); long duplicateTransaction(long id); long duplicateTransactionWithMultiplier(long id, int multiplier); long duplicateTransactionAsTemplate(long id); long insertOrUpdate(Transaction transaction); long insertOrUpdate(Transaction transaction, List<TransactionAttribute> attributes); long insertOrUpdateInTransaction(Transaction transaction, List<TransactionAttribute> attributes); void insertWithoutUpdatingBalance(Transaction transaction); void updateTransactionStatus(long id, TransactionStatus status); void deleteTransaction(long id); void deleteTransactionNoDbTransaction(long id); long insertOrUpdate(Category category, List<Attribute> attributes); Category getCategoryWithParent(long id); List<Long> getCategoryIdsByLeftIds(List<String> leftIds); Category getCategoryByLeft(long left); CategoryTree<Category> getCategoriesTreeWithoutSubTree(long excludingTreeId, boolean includeNoCategory); CategoryTree<Category> getCategoriesTree(boolean includeNoCategory); CategoryTree<Category> getAllCategoriesTree(); Map<Long, Category> getAllCategoriesMap(); List<Category> getCategoriesList(boolean includeNoCategory); Cursor getAllCategories(); List<Category> getAllCategoriesList(); Cursor getCategories(boolean includeNoCategory); Cursor filterCategories(CharSequence titleFilter); Cursor getCategories(boolean includeNoCategory, CharSequence titleFilter); Cursor getCategoriesWithoutSubtree(long id, boolean includeNoCategory); List<Category> getCategoriesWithoutSubtreeAsList(long categoryId); long insertChildCategory(long parentId, Category category); long insertMateCategory(long categoryId, Category category); void deleteCategory(long categoryId); void insertCategoryTreeInTransaction(CategoryTree<Category> tree); void updateCategoryTree(CategoryTree<Category> tree); List<SmsTemplate> getSmsTemplatesForCategory(long categoryId); List<SmsTemplate> getSmsTemplatesByNumber(String smsNumber); Set<String> findAllSmsTemplateNumbers(); Cursor getAllSmsTemplates(); Cursor getSmsTemplatesWithFullInfo(); Cursor getSmsTemplatesWithFullInfo(final String filter); long duplicateSmsTemplateBelowOriginal(long id); ArrayList<Attribute> getAttributesForCategory(long categoryId); ArrayList<Attribute> getAllAttributesForCategory(long categoryId); Attribute getSystemAttribute(SystemAttribute a); Attribute getAttribute(long id); long insertOrUpdate(Attribute attribute); void deleteAttribute(long id); Cursor getAllAttributes(); Map<Long, String> getAllAttributesMap(); Map<Long, String> getAllAttributesForTransaction(long transactionId); EnumMap<SystemAttribute, String> getSystemAttributesForTransaction(long transactionId); void clearSelectedTransactions(long[] ids); void reconcileSelectedTransactions(long[] ids); void deleteSelectedTransactions(long[] ids); long[] storeMissedSchedules(List<RestoredTransaction> restored, long now); int getCustomClosingDay(long accountId, int period); void setCustomClosingDay(long accountId, int period, int closingDay); void deleteCustomClosingDay(long accountId, int period); void updateCustomClosingDay(long accountId, int period, int closingDay); void rebuildRunningBalances(); void rebuildRunningBalanceForAccount(Account account); long fetchBudgetBalance(Map<Long, Category> categories, Map<Long, Project> projects, Budget b); void recalculateAccountsBalances(); void saveRate(ExchangeRate r); void replaceRate(ExchangeRate rate, long originalDate); void saveDownloadedRates(List<ExchangeRate> downloadedRates); ExchangeRate findRate(Currency fromCurrency, Currency toCurrency, long date); List<ExchangeRate> findRates(Currency fromCurrency); List<ExchangeRate> findRates(Currency fromCurrency, Currency toCurrency); ExchangeRateProvider getLatestRates(); ExchangeRateProvider getHistoryRates(); void deleteRate(ExchangeRate rate); void deleteRate(long fromCurrencyId, long toCurrencyId, long date); Total getAccountsTotalInHomeCurrency(); Total[] getAccountsTotal(); Total getAccountsTotal(Currency homeCurrency); List<Long> findAccountsByNumber(String numberEnding); boolean singleCurrencyOnly(); void setDefaultHomeCurrency(); void purgeAccountAtDate(Account account, long date); void deleteOldTransactions(Account account, long date); long getAccountBalanceForTransaction(Account a, Transaction t); long findNearestOlderTransactionId(Account account, long date); long findLatestTransactionDate(long accountId); void updateAccountsLastTransactionDate(); void restoreSystemEntities(); long getLastRunningBalanceForAccount(Account account); } |
@Test public void should_not_return_split_category_as_parent_when_editing_a_category() { List<Category> list = db.getCategoriesWithoutSubtreeAsList(categoriesMap.get("A").id); for (Category category : list) { assertFalse("Should not be split", category.isSplit()); } } | public List<Category> getCategoriesWithoutSubtreeAsList(long categoryId) { List<Category> list = new ArrayList<>(); try (Cursor c = getCategoriesWithoutSubtree(categoryId, true)) { while (c.moveToNext()) { Category category = Category.formCursor(c); list.add(category); } return list; } } | DatabaseAdapter extends MyEntityManager { public List<Category> getCategoriesWithoutSubtreeAsList(long categoryId) { List<Category> list = new ArrayList<>(); try (Cursor c = getCategoriesWithoutSubtree(categoryId, true)) { while (c.moveToNext()) { Category category = Category.formCursor(c); list.add(category); } return list; } } } | DatabaseAdapter extends MyEntityManager { public List<Category> getCategoriesWithoutSubtreeAsList(long categoryId) { List<Category> list = new ArrayList<>(); try (Cursor c = getCategoriesWithoutSubtree(categoryId, true)) { while (c.moveToNext()) { Category category = Category.formCursor(c); list.add(category); } return list; } } DatabaseAdapter(Context context); } | DatabaseAdapter extends MyEntityManager { public List<Category> getCategoriesWithoutSubtreeAsList(long categoryId) { List<Category> list = new ArrayList<>(); try (Cursor c = getCategoriesWithoutSubtree(categoryId, true)) { while (c.moveToNext()) { Category category = Category.formCursor(c); list.add(category); } return list; } } DatabaseAdapter(Context context); void open(); void close(); int deleteAccount(long id); Transaction getTransaction(long id); Cursor getBlotter(WhereFilter filter); Cursor getBlotterForAccount(WhereFilter filter); static WhereFilter enhanceFilterForAccountBlotter(WhereFilter filter); Cursor getBlotterForAccountWithSplits(WhereFilter filter); Cursor getAllTemplates(WhereFilter filter, String sortBy); Cursor getBlotterWithSplits(String where); long duplicateTransaction(long id); long duplicateTransactionWithMultiplier(long id, int multiplier); long duplicateTransactionAsTemplate(long id); long insertOrUpdate(Transaction transaction); long insertOrUpdate(Transaction transaction, List<TransactionAttribute> attributes); long insertOrUpdateInTransaction(Transaction transaction, List<TransactionAttribute> attributes); void insertWithoutUpdatingBalance(Transaction transaction); void updateTransactionStatus(long id, TransactionStatus status); void deleteTransaction(long id); void deleteTransactionNoDbTransaction(long id); long insertOrUpdate(Category category, List<Attribute> attributes); Category getCategoryWithParent(long id); List<Long> getCategoryIdsByLeftIds(List<String> leftIds); Category getCategoryByLeft(long left); CategoryTree<Category> getCategoriesTreeWithoutSubTree(long excludingTreeId, boolean includeNoCategory); CategoryTree<Category> getCategoriesTree(boolean includeNoCategory); CategoryTree<Category> getAllCategoriesTree(); Map<Long, Category> getAllCategoriesMap(); List<Category> getCategoriesList(boolean includeNoCategory); Cursor getAllCategories(); List<Category> getAllCategoriesList(); Cursor getCategories(boolean includeNoCategory); Cursor filterCategories(CharSequence titleFilter); Cursor getCategories(boolean includeNoCategory, CharSequence titleFilter); Cursor getCategoriesWithoutSubtree(long id, boolean includeNoCategory); List<Category> getCategoriesWithoutSubtreeAsList(long categoryId); long insertChildCategory(long parentId, Category category); long insertMateCategory(long categoryId, Category category); void deleteCategory(long categoryId); void insertCategoryTreeInTransaction(CategoryTree<Category> tree); void updateCategoryTree(CategoryTree<Category> tree); List<SmsTemplate> getSmsTemplatesForCategory(long categoryId); List<SmsTemplate> getSmsTemplatesByNumber(String smsNumber); Set<String> findAllSmsTemplateNumbers(); Cursor getAllSmsTemplates(); Cursor getSmsTemplatesWithFullInfo(); Cursor getSmsTemplatesWithFullInfo(final String filter); long duplicateSmsTemplateBelowOriginal(long id); ArrayList<Attribute> getAttributesForCategory(long categoryId); ArrayList<Attribute> getAllAttributesForCategory(long categoryId); Attribute getSystemAttribute(SystemAttribute a); Attribute getAttribute(long id); long insertOrUpdate(Attribute attribute); void deleteAttribute(long id); Cursor getAllAttributes(); Map<Long, String> getAllAttributesMap(); Map<Long, String> getAllAttributesForTransaction(long transactionId); EnumMap<SystemAttribute, String> getSystemAttributesForTransaction(long transactionId); void clearSelectedTransactions(long[] ids); void reconcileSelectedTransactions(long[] ids); void deleteSelectedTransactions(long[] ids); long[] storeMissedSchedules(List<RestoredTransaction> restored, long now); int getCustomClosingDay(long accountId, int period); void setCustomClosingDay(long accountId, int period, int closingDay); void deleteCustomClosingDay(long accountId, int period); void updateCustomClosingDay(long accountId, int period, int closingDay); void rebuildRunningBalances(); void rebuildRunningBalanceForAccount(Account account); long fetchBudgetBalance(Map<Long, Category> categories, Map<Long, Project> projects, Budget b); void recalculateAccountsBalances(); void saveRate(ExchangeRate r); void replaceRate(ExchangeRate rate, long originalDate); void saveDownloadedRates(List<ExchangeRate> downloadedRates); ExchangeRate findRate(Currency fromCurrency, Currency toCurrency, long date); List<ExchangeRate> findRates(Currency fromCurrency); List<ExchangeRate> findRates(Currency fromCurrency, Currency toCurrency); ExchangeRateProvider getLatestRates(); ExchangeRateProvider getHistoryRates(); void deleteRate(ExchangeRate rate); void deleteRate(long fromCurrencyId, long toCurrencyId, long date); Total getAccountsTotalInHomeCurrency(); Total[] getAccountsTotal(); Total getAccountsTotal(Currency homeCurrency); List<Long> findAccountsByNumber(String numberEnding); boolean singleCurrencyOnly(); void setDefaultHomeCurrency(); void purgeAccountAtDate(Account account, long date); void deleteOldTransactions(Account account, long date); long getAccountBalanceForTransaction(Account a, Transaction t); long findNearestOlderTransactionId(Account account, long date); long findLatestTransactionDate(long accountId); void updateAccountsLastTransactionDate(); void restoreSystemEntities(); long getLastRunningBalanceForAccount(Account account); } | DatabaseAdapter extends MyEntityManager { public List<Category> getCategoriesWithoutSubtreeAsList(long categoryId) { List<Category> list = new ArrayList<>(); try (Cursor c = getCategoriesWithoutSubtree(categoryId, true)) { while (c.moveToNext()) { Category category = Category.formCursor(c); list.add(category); } return list; } } DatabaseAdapter(Context context); void open(); void close(); int deleteAccount(long id); Transaction getTransaction(long id); Cursor getBlotter(WhereFilter filter); Cursor getBlotterForAccount(WhereFilter filter); static WhereFilter enhanceFilterForAccountBlotter(WhereFilter filter); Cursor getBlotterForAccountWithSplits(WhereFilter filter); Cursor getAllTemplates(WhereFilter filter, String sortBy); Cursor getBlotterWithSplits(String where); long duplicateTransaction(long id); long duplicateTransactionWithMultiplier(long id, int multiplier); long duplicateTransactionAsTemplate(long id); long insertOrUpdate(Transaction transaction); long insertOrUpdate(Transaction transaction, List<TransactionAttribute> attributes); long insertOrUpdateInTransaction(Transaction transaction, List<TransactionAttribute> attributes); void insertWithoutUpdatingBalance(Transaction transaction); void updateTransactionStatus(long id, TransactionStatus status); void deleteTransaction(long id); void deleteTransactionNoDbTransaction(long id); long insertOrUpdate(Category category, List<Attribute> attributes); Category getCategoryWithParent(long id); List<Long> getCategoryIdsByLeftIds(List<String> leftIds); Category getCategoryByLeft(long left); CategoryTree<Category> getCategoriesTreeWithoutSubTree(long excludingTreeId, boolean includeNoCategory); CategoryTree<Category> getCategoriesTree(boolean includeNoCategory); CategoryTree<Category> getAllCategoriesTree(); Map<Long, Category> getAllCategoriesMap(); List<Category> getCategoriesList(boolean includeNoCategory); Cursor getAllCategories(); List<Category> getAllCategoriesList(); Cursor getCategories(boolean includeNoCategory); Cursor filterCategories(CharSequence titleFilter); Cursor getCategories(boolean includeNoCategory, CharSequence titleFilter); Cursor getCategoriesWithoutSubtree(long id, boolean includeNoCategory); List<Category> getCategoriesWithoutSubtreeAsList(long categoryId); long insertChildCategory(long parentId, Category category); long insertMateCategory(long categoryId, Category category); void deleteCategory(long categoryId); void insertCategoryTreeInTransaction(CategoryTree<Category> tree); void updateCategoryTree(CategoryTree<Category> tree); List<SmsTemplate> getSmsTemplatesForCategory(long categoryId); List<SmsTemplate> getSmsTemplatesByNumber(String smsNumber); Set<String> findAllSmsTemplateNumbers(); Cursor getAllSmsTemplates(); Cursor getSmsTemplatesWithFullInfo(); Cursor getSmsTemplatesWithFullInfo(final String filter); long duplicateSmsTemplateBelowOriginal(long id); ArrayList<Attribute> getAttributesForCategory(long categoryId); ArrayList<Attribute> getAllAttributesForCategory(long categoryId); Attribute getSystemAttribute(SystemAttribute a); Attribute getAttribute(long id); long insertOrUpdate(Attribute attribute); void deleteAttribute(long id); Cursor getAllAttributes(); Map<Long, String> getAllAttributesMap(); Map<Long, String> getAllAttributesForTransaction(long transactionId); EnumMap<SystemAttribute, String> getSystemAttributesForTransaction(long transactionId); void clearSelectedTransactions(long[] ids); void reconcileSelectedTransactions(long[] ids); void deleteSelectedTransactions(long[] ids); long[] storeMissedSchedules(List<RestoredTransaction> restored, long now); int getCustomClosingDay(long accountId, int period); void setCustomClosingDay(long accountId, int period, int closingDay); void deleteCustomClosingDay(long accountId, int period); void updateCustomClosingDay(long accountId, int period, int closingDay); void rebuildRunningBalances(); void rebuildRunningBalanceForAccount(Account account); long fetchBudgetBalance(Map<Long, Category> categories, Map<Long, Project> projects, Budget b); void recalculateAccountsBalances(); void saveRate(ExchangeRate r); void replaceRate(ExchangeRate rate, long originalDate); void saveDownloadedRates(List<ExchangeRate> downloadedRates); ExchangeRate findRate(Currency fromCurrency, Currency toCurrency, long date); List<ExchangeRate> findRates(Currency fromCurrency); List<ExchangeRate> findRates(Currency fromCurrency, Currency toCurrency); ExchangeRateProvider getLatestRates(); ExchangeRateProvider getHistoryRates(); void deleteRate(ExchangeRate rate); void deleteRate(long fromCurrencyId, long toCurrencyId, long date); Total getAccountsTotalInHomeCurrency(); Total[] getAccountsTotal(); Total getAccountsTotal(Currency homeCurrency); List<Long> findAccountsByNumber(String numberEnding); boolean singleCurrencyOnly(); void setDefaultHomeCurrency(); void purgeAccountAtDate(Account account, long date); void deleteOldTransactions(Account account, long date); long getAccountBalanceForTransaction(Account a, Transaction t); long findNearestOlderTransactionId(Account account, long date); long findLatestTransactionDate(long accountId); void updateAccountsLastTransactionDate(); void restoreSystemEntities(); long getLastRunningBalanceForAccount(Account account); } |
@Test public void should_return_only_valid_parent_categories_when_editing_a_category() { List<Category> list = db.getCategoriesWithoutSubtreeAsList(categoriesMap.get("A").id); assertEquals(2, list.size()); assertEquals(Category.NO_CATEGORY_ID, list.get(0).id); assertEquals(categoriesMap.get("B").id, list.get(1).id); } | public List<Category> getCategoriesWithoutSubtreeAsList(long categoryId) { List<Category> list = new ArrayList<>(); try (Cursor c = getCategoriesWithoutSubtree(categoryId, true)) { while (c.moveToNext()) { Category category = Category.formCursor(c); list.add(category); } return list; } } | DatabaseAdapter extends MyEntityManager { public List<Category> getCategoriesWithoutSubtreeAsList(long categoryId) { List<Category> list = new ArrayList<>(); try (Cursor c = getCategoriesWithoutSubtree(categoryId, true)) { while (c.moveToNext()) { Category category = Category.formCursor(c); list.add(category); } return list; } } } | DatabaseAdapter extends MyEntityManager { public List<Category> getCategoriesWithoutSubtreeAsList(long categoryId) { List<Category> list = new ArrayList<>(); try (Cursor c = getCategoriesWithoutSubtree(categoryId, true)) { while (c.moveToNext()) { Category category = Category.formCursor(c); list.add(category); } return list; } } DatabaseAdapter(Context context); } | DatabaseAdapter extends MyEntityManager { public List<Category> getCategoriesWithoutSubtreeAsList(long categoryId) { List<Category> list = new ArrayList<>(); try (Cursor c = getCategoriesWithoutSubtree(categoryId, true)) { while (c.moveToNext()) { Category category = Category.formCursor(c); list.add(category); } return list; } } DatabaseAdapter(Context context); void open(); void close(); int deleteAccount(long id); Transaction getTransaction(long id); Cursor getBlotter(WhereFilter filter); Cursor getBlotterForAccount(WhereFilter filter); static WhereFilter enhanceFilterForAccountBlotter(WhereFilter filter); Cursor getBlotterForAccountWithSplits(WhereFilter filter); Cursor getAllTemplates(WhereFilter filter, String sortBy); Cursor getBlotterWithSplits(String where); long duplicateTransaction(long id); long duplicateTransactionWithMultiplier(long id, int multiplier); long duplicateTransactionAsTemplate(long id); long insertOrUpdate(Transaction transaction); long insertOrUpdate(Transaction transaction, List<TransactionAttribute> attributes); long insertOrUpdateInTransaction(Transaction transaction, List<TransactionAttribute> attributes); void insertWithoutUpdatingBalance(Transaction transaction); void updateTransactionStatus(long id, TransactionStatus status); void deleteTransaction(long id); void deleteTransactionNoDbTransaction(long id); long insertOrUpdate(Category category, List<Attribute> attributes); Category getCategoryWithParent(long id); List<Long> getCategoryIdsByLeftIds(List<String> leftIds); Category getCategoryByLeft(long left); CategoryTree<Category> getCategoriesTreeWithoutSubTree(long excludingTreeId, boolean includeNoCategory); CategoryTree<Category> getCategoriesTree(boolean includeNoCategory); CategoryTree<Category> getAllCategoriesTree(); Map<Long, Category> getAllCategoriesMap(); List<Category> getCategoriesList(boolean includeNoCategory); Cursor getAllCategories(); List<Category> getAllCategoriesList(); Cursor getCategories(boolean includeNoCategory); Cursor filterCategories(CharSequence titleFilter); Cursor getCategories(boolean includeNoCategory, CharSequence titleFilter); Cursor getCategoriesWithoutSubtree(long id, boolean includeNoCategory); List<Category> getCategoriesWithoutSubtreeAsList(long categoryId); long insertChildCategory(long parentId, Category category); long insertMateCategory(long categoryId, Category category); void deleteCategory(long categoryId); void insertCategoryTreeInTransaction(CategoryTree<Category> tree); void updateCategoryTree(CategoryTree<Category> tree); List<SmsTemplate> getSmsTemplatesForCategory(long categoryId); List<SmsTemplate> getSmsTemplatesByNumber(String smsNumber); Set<String> findAllSmsTemplateNumbers(); Cursor getAllSmsTemplates(); Cursor getSmsTemplatesWithFullInfo(); Cursor getSmsTemplatesWithFullInfo(final String filter); long duplicateSmsTemplateBelowOriginal(long id); ArrayList<Attribute> getAttributesForCategory(long categoryId); ArrayList<Attribute> getAllAttributesForCategory(long categoryId); Attribute getSystemAttribute(SystemAttribute a); Attribute getAttribute(long id); long insertOrUpdate(Attribute attribute); void deleteAttribute(long id); Cursor getAllAttributes(); Map<Long, String> getAllAttributesMap(); Map<Long, String> getAllAttributesForTransaction(long transactionId); EnumMap<SystemAttribute, String> getSystemAttributesForTransaction(long transactionId); void clearSelectedTransactions(long[] ids); void reconcileSelectedTransactions(long[] ids); void deleteSelectedTransactions(long[] ids); long[] storeMissedSchedules(List<RestoredTransaction> restored, long now); int getCustomClosingDay(long accountId, int period); void setCustomClosingDay(long accountId, int period, int closingDay); void deleteCustomClosingDay(long accountId, int period); void updateCustomClosingDay(long accountId, int period, int closingDay); void rebuildRunningBalances(); void rebuildRunningBalanceForAccount(Account account); long fetchBudgetBalance(Map<Long, Category> categories, Map<Long, Project> projects, Budget b); void recalculateAccountsBalances(); void saveRate(ExchangeRate r); void replaceRate(ExchangeRate rate, long originalDate); void saveDownloadedRates(List<ExchangeRate> downloadedRates); ExchangeRate findRate(Currency fromCurrency, Currency toCurrency, long date); List<ExchangeRate> findRates(Currency fromCurrency); List<ExchangeRate> findRates(Currency fromCurrency, Currency toCurrency); ExchangeRateProvider getLatestRates(); ExchangeRateProvider getHistoryRates(); void deleteRate(ExchangeRate rate); void deleteRate(long fromCurrencyId, long toCurrencyId, long date); Total getAccountsTotalInHomeCurrency(); Total[] getAccountsTotal(); Total getAccountsTotal(Currency homeCurrency); List<Long> findAccountsByNumber(String numberEnding); boolean singleCurrencyOnly(); void setDefaultHomeCurrency(); void purgeAccountAtDate(Account account, long date); void deleteOldTransactions(Account account, long date); long getAccountBalanceForTransaction(Account a, Transaction t); long findNearestOlderTransactionId(Account account, long date); long findLatestTransactionDate(long accountId); void updateAccountsLastTransactionDate(); void restoreSystemEntities(); long getLastRunningBalanceForAccount(Account account); } | DatabaseAdapter extends MyEntityManager { public List<Category> getCategoriesWithoutSubtreeAsList(long categoryId) { List<Category> list = new ArrayList<>(); try (Cursor c = getCategoriesWithoutSubtree(categoryId, true)) { while (c.moveToNext()) { Category category = Category.formCursor(c); list.add(category); } return list; } } DatabaseAdapter(Context context); void open(); void close(); int deleteAccount(long id); Transaction getTransaction(long id); Cursor getBlotter(WhereFilter filter); Cursor getBlotterForAccount(WhereFilter filter); static WhereFilter enhanceFilterForAccountBlotter(WhereFilter filter); Cursor getBlotterForAccountWithSplits(WhereFilter filter); Cursor getAllTemplates(WhereFilter filter, String sortBy); Cursor getBlotterWithSplits(String where); long duplicateTransaction(long id); long duplicateTransactionWithMultiplier(long id, int multiplier); long duplicateTransactionAsTemplate(long id); long insertOrUpdate(Transaction transaction); long insertOrUpdate(Transaction transaction, List<TransactionAttribute> attributes); long insertOrUpdateInTransaction(Transaction transaction, List<TransactionAttribute> attributes); void insertWithoutUpdatingBalance(Transaction transaction); void updateTransactionStatus(long id, TransactionStatus status); void deleteTransaction(long id); void deleteTransactionNoDbTransaction(long id); long insertOrUpdate(Category category, List<Attribute> attributes); Category getCategoryWithParent(long id); List<Long> getCategoryIdsByLeftIds(List<String> leftIds); Category getCategoryByLeft(long left); CategoryTree<Category> getCategoriesTreeWithoutSubTree(long excludingTreeId, boolean includeNoCategory); CategoryTree<Category> getCategoriesTree(boolean includeNoCategory); CategoryTree<Category> getAllCategoriesTree(); Map<Long, Category> getAllCategoriesMap(); List<Category> getCategoriesList(boolean includeNoCategory); Cursor getAllCategories(); List<Category> getAllCategoriesList(); Cursor getCategories(boolean includeNoCategory); Cursor filterCategories(CharSequence titleFilter); Cursor getCategories(boolean includeNoCategory, CharSequence titleFilter); Cursor getCategoriesWithoutSubtree(long id, boolean includeNoCategory); List<Category> getCategoriesWithoutSubtreeAsList(long categoryId); long insertChildCategory(long parentId, Category category); long insertMateCategory(long categoryId, Category category); void deleteCategory(long categoryId); void insertCategoryTreeInTransaction(CategoryTree<Category> tree); void updateCategoryTree(CategoryTree<Category> tree); List<SmsTemplate> getSmsTemplatesForCategory(long categoryId); List<SmsTemplate> getSmsTemplatesByNumber(String smsNumber); Set<String> findAllSmsTemplateNumbers(); Cursor getAllSmsTemplates(); Cursor getSmsTemplatesWithFullInfo(); Cursor getSmsTemplatesWithFullInfo(final String filter); long duplicateSmsTemplateBelowOriginal(long id); ArrayList<Attribute> getAttributesForCategory(long categoryId); ArrayList<Attribute> getAllAttributesForCategory(long categoryId); Attribute getSystemAttribute(SystemAttribute a); Attribute getAttribute(long id); long insertOrUpdate(Attribute attribute); void deleteAttribute(long id); Cursor getAllAttributes(); Map<Long, String> getAllAttributesMap(); Map<Long, String> getAllAttributesForTransaction(long transactionId); EnumMap<SystemAttribute, String> getSystemAttributesForTransaction(long transactionId); void clearSelectedTransactions(long[] ids); void reconcileSelectedTransactions(long[] ids); void deleteSelectedTransactions(long[] ids); long[] storeMissedSchedules(List<RestoredTransaction> restored, long now); int getCustomClosingDay(long accountId, int period); void setCustomClosingDay(long accountId, int period, int closingDay); void deleteCustomClosingDay(long accountId, int period); void updateCustomClosingDay(long accountId, int period, int closingDay); void rebuildRunningBalances(); void rebuildRunningBalanceForAccount(Account account); long fetchBudgetBalance(Map<Long, Category> categories, Map<Long, Project> projects, Budget b); void recalculateAccountsBalances(); void saveRate(ExchangeRate r); void replaceRate(ExchangeRate rate, long originalDate); void saveDownloadedRates(List<ExchangeRate> downloadedRates); ExchangeRate findRate(Currency fromCurrency, Currency toCurrency, long date); List<ExchangeRate> findRates(Currency fromCurrency); List<ExchangeRate> findRates(Currency fromCurrency, Currency toCurrency); ExchangeRateProvider getLatestRates(); ExchangeRateProvider getHistoryRates(); void deleteRate(ExchangeRate rate); void deleteRate(long fromCurrencyId, long toCurrencyId, long date); Total getAccountsTotalInHomeCurrency(); Total[] getAccountsTotal(); Total getAccountsTotal(Currency homeCurrency); List<Long> findAccountsByNumber(String numberEnding); boolean singleCurrencyOnly(); void setDefaultHomeCurrency(); void purgeAccountAtDate(Account account, long date); void deleteOldTransactions(Account account, long date); long getAccountBalanceForTransaction(Account a, Transaction t); long findNearestOlderTransactionId(Account account, long date); long findLatestTransactionDate(long accountId); void updateAccountsLastTransactionDate(); void restoreSystemEntities(); long getLastRunningBalanceForAccount(Account account); } |
@Test public void should_return_id_of_the_nearest_transaction_which_is_older_than_specified_date() { a2 = AccountBuilder.createDefault(db); Transaction t8 = TransactionBuilder.withDb(db).dateTime(DateTime.date(2012, 5, 25).at(17, 30, 45, 0)).account(a2).amount(-234).create(); Transaction t7 = TransactionBuilder.withDb(db).dateTime(DateTime.date(2012, 5, 25).at(16, 30, 45, 0)).account(a1).amount(-234).create(); Transaction t6 = TransactionBuilder.withDb(db).dateTime(DateTime.date(2012, 5, 24).at(23, 59, 59, 999)).account(a1).amount(200).create(); Transaction t5 = TransactionBuilder.withDb(db).scheduleOnce(DateTime.date(2012, 5, 23).at(0, 0, 0, 45)).account(a1).amount(100).create(); Transaction t4 = TransactionBuilder.withDb(db).dateTime(DateTime.date(2012, 5, 23).at(0, 0, 0, 45)).account(a1).amount(100).create(); Transaction t3 = TransactionBuilder.withDb(db).dateTime(DateTime.date(2012, 5, 22).at(12, 0, 12, 345)).account(a1).amount(10).create(); Transaction t2 = TransactionBuilder.withDb(db).dateTime(DateTime.date(2012, 5, 22).at(12, 0, 12, 345)).account(a1).amount(10).makeTemplate().create(); Transaction t1 = TransactionBuilder.withDb(db).dateTime(DateTime.date(2012, 5, 21).at(0, 0, 0, 0)).account(a1).amount(-20).create(); assertEquals(-1, db.findNearestOlderTransactionId(a1, DateTime.date(2012, 5, 20).asLong())); assertEquals(t1.id, db.findNearestOlderTransactionId(a1, DateTime.date(2012, 5, 21).at(15, 30, 30, 456).asLong())); assertEquals(t3.id, db.findNearestOlderTransactionId(a1, DateTime.date(2012, 5, 22).asLong())); assertEquals(t4.id, db.findNearestOlderTransactionId(a1, DateTime.date(2012, 5, 23).asLong())); assertEquals(t6.id, db.findNearestOlderTransactionId(a1, DateTime.date(2012, 5, 24).asLong())); assertEquals(t7.id, db.findNearestOlderTransactionId(a1, DateTime.date(2012, 5, 25).asLong())); assertEquals(t7.id, db.findNearestOlderTransactionId(a1, DateTime.date(2012, 5, 26).asLong())); assertEquals(t8.id, db.findNearestOlderTransactionId(a2, DateTime.date(2012, 5, 26).asLong())); } | public long findNearestOlderTransactionId(Account account, long date) { return DatabaseUtils.rawFetchId(this, "select _id from v_blotter where from_account_id=? and datetime<=? order by datetime desc limit 1", new String[]{String.valueOf(account.id), String.valueOf(DateUtils.atDayEnd(date))}); } | DatabaseAdapter extends MyEntityManager { public long findNearestOlderTransactionId(Account account, long date) { return DatabaseUtils.rawFetchId(this, "select _id from v_blotter where from_account_id=? and datetime<=? order by datetime desc limit 1", new String[]{String.valueOf(account.id), String.valueOf(DateUtils.atDayEnd(date))}); } } | DatabaseAdapter extends MyEntityManager { public long findNearestOlderTransactionId(Account account, long date) { return DatabaseUtils.rawFetchId(this, "select _id from v_blotter where from_account_id=? and datetime<=? order by datetime desc limit 1", new String[]{String.valueOf(account.id), String.valueOf(DateUtils.atDayEnd(date))}); } DatabaseAdapter(Context context); } | DatabaseAdapter extends MyEntityManager { public long findNearestOlderTransactionId(Account account, long date) { return DatabaseUtils.rawFetchId(this, "select _id from v_blotter where from_account_id=? and datetime<=? order by datetime desc limit 1", new String[]{String.valueOf(account.id), String.valueOf(DateUtils.atDayEnd(date))}); } DatabaseAdapter(Context context); void open(); void close(); int deleteAccount(long id); Transaction getTransaction(long id); Cursor getBlotter(WhereFilter filter); Cursor getBlotterForAccount(WhereFilter filter); static WhereFilter enhanceFilterForAccountBlotter(WhereFilter filter); Cursor getBlotterForAccountWithSplits(WhereFilter filter); Cursor getAllTemplates(WhereFilter filter, String sortBy); Cursor getBlotterWithSplits(String where); long duplicateTransaction(long id); long duplicateTransactionWithMultiplier(long id, int multiplier); long duplicateTransactionAsTemplate(long id); long insertOrUpdate(Transaction transaction); long insertOrUpdate(Transaction transaction, List<TransactionAttribute> attributes); long insertOrUpdateInTransaction(Transaction transaction, List<TransactionAttribute> attributes); void insertWithoutUpdatingBalance(Transaction transaction); void updateTransactionStatus(long id, TransactionStatus status); void deleteTransaction(long id); void deleteTransactionNoDbTransaction(long id); long insertOrUpdate(Category category, List<Attribute> attributes); Category getCategoryWithParent(long id); List<Long> getCategoryIdsByLeftIds(List<String> leftIds); Category getCategoryByLeft(long left); CategoryTree<Category> getCategoriesTreeWithoutSubTree(long excludingTreeId, boolean includeNoCategory); CategoryTree<Category> getCategoriesTree(boolean includeNoCategory); CategoryTree<Category> getAllCategoriesTree(); Map<Long, Category> getAllCategoriesMap(); List<Category> getCategoriesList(boolean includeNoCategory); Cursor getAllCategories(); List<Category> getAllCategoriesList(); Cursor getCategories(boolean includeNoCategory); Cursor filterCategories(CharSequence titleFilter); Cursor getCategories(boolean includeNoCategory, CharSequence titleFilter); Cursor getCategoriesWithoutSubtree(long id, boolean includeNoCategory); List<Category> getCategoriesWithoutSubtreeAsList(long categoryId); long insertChildCategory(long parentId, Category category); long insertMateCategory(long categoryId, Category category); void deleteCategory(long categoryId); void insertCategoryTreeInTransaction(CategoryTree<Category> tree); void updateCategoryTree(CategoryTree<Category> tree); List<SmsTemplate> getSmsTemplatesForCategory(long categoryId); List<SmsTemplate> getSmsTemplatesByNumber(String smsNumber); Set<String> findAllSmsTemplateNumbers(); Cursor getAllSmsTemplates(); Cursor getSmsTemplatesWithFullInfo(); Cursor getSmsTemplatesWithFullInfo(final String filter); long duplicateSmsTemplateBelowOriginal(long id); ArrayList<Attribute> getAttributesForCategory(long categoryId); ArrayList<Attribute> getAllAttributesForCategory(long categoryId); Attribute getSystemAttribute(SystemAttribute a); Attribute getAttribute(long id); long insertOrUpdate(Attribute attribute); void deleteAttribute(long id); Cursor getAllAttributes(); Map<Long, String> getAllAttributesMap(); Map<Long, String> getAllAttributesForTransaction(long transactionId); EnumMap<SystemAttribute, String> getSystemAttributesForTransaction(long transactionId); void clearSelectedTransactions(long[] ids); void reconcileSelectedTransactions(long[] ids); void deleteSelectedTransactions(long[] ids); long[] storeMissedSchedules(List<RestoredTransaction> restored, long now); int getCustomClosingDay(long accountId, int period); void setCustomClosingDay(long accountId, int period, int closingDay); void deleteCustomClosingDay(long accountId, int period); void updateCustomClosingDay(long accountId, int period, int closingDay); void rebuildRunningBalances(); void rebuildRunningBalanceForAccount(Account account); long fetchBudgetBalance(Map<Long, Category> categories, Map<Long, Project> projects, Budget b); void recalculateAccountsBalances(); void saveRate(ExchangeRate r); void replaceRate(ExchangeRate rate, long originalDate); void saveDownloadedRates(List<ExchangeRate> downloadedRates); ExchangeRate findRate(Currency fromCurrency, Currency toCurrency, long date); List<ExchangeRate> findRates(Currency fromCurrency); List<ExchangeRate> findRates(Currency fromCurrency, Currency toCurrency); ExchangeRateProvider getLatestRates(); ExchangeRateProvider getHistoryRates(); void deleteRate(ExchangeRate rate); void deleteRate(long fromCurrencyId, long toCurrencyId, long date); Total getAccountsTotalInHomeCurrency(); Total[] getAccountsTotal(); Total getAccountsTotal(Currency homeCurrency); List<Long> findAccountsByNumber(String numberEnding); boolean singleCurrencyOnly(); void setDefaultHomeCurrency(); void purgeAccountAtDate(Account account, long date); void deleteOldTransactions(Account account, long date); long getAccountBalanceForTransaction(Account a, Transaction t); long findNearestOlderTransactionId(Account account, long date); long findLatestTransactionDate(long accountId); void updateAccountsLastTransactionDate(); void restoreSystemEntities(); long getLastRunningBalanceForAccount(Account account); } | DatabaseAdapter extends MyEntityManager { public long findNearestOlderTransactionId(Account account, long date) { return DatabaseUtils.rawFetchId(this, "select _id from v_blotter where from_account_id=? and datetime<=? order by datetime desc limit 1", new String[]{String.valueOf(account.id), String.valueOf(DateUtils.atDayEnd(date))}); } DatabaseAdapter(Context context); void open(); void close(); int deleteAccount(long id); Transaction getTransaction(long id); Cursor getBlotter(WhereFilter filter); Cursor getBlotterForAccount(WhereFilter filter); static WhereFilter enhanceFilterForAccountBlotter(WhereFilter filter); Cursor getBlotterForAccountWithSplits(WhereFilter filter); Cursor getAllTemplates(WhereFilter filter, String sortBy); Cursor getBlotterWithSplits(String where); long duplicateTransaction(long id); long duplicateTransactionWithMultiplier(long id, int multiplier); long duplicateTransactionAsTemplate(long id); long insertOrUpdate(Transaction transaction); long insertOrUpdate(Transaction transaction, List<TransactionAttribute> attributes); long insertOrUpdateInTransaction(Transaction transaction, List<TransactionAttribute> attributes); void insertWithoutUpdatingBalance(Transaction transaction); void updateTransactionStatus(long id, TransactionStatus status); void deleteTransaction(long id); void deleteTransactionNoDbTransaction(long id); long insertOrUpdate(Category category, List<Attribute> attributes); Category getCategoryWithParent(long id); List<Long> getCategoryIdsByLeftIds(List<String> leftIds); Category getCategoryByLeft(long left); CategoryTree<Category> getCategoriesTreeWithoutSubTree(long excludingTreeId, boolean includeNoCategory); CategoryTree<Category> getCategoriesTree(boolean includeNoCategory); CategoryTree<Category> getAllCategoriesTree(); Map<Long, Category> getAllCategoriesMap(); List<Category> getCategoriesList(boolean includeNoCategory); Cursor getAllCategories(); List<Category> getAllCategoriesList(); Cursor getCategories(boolean includeNoCategory); Cursor filterCategories(CharSequence titleFilter); Cursor getCategories(boolean includeNoCategory, CharSequence titleFilter); Cursor getCategoriesWithoutSubtree(long id, boolean includeNoCategory); List<Category> getCategoriesWithoutSubtreeAsList(long categoryId); long insertChildCategory(long parentId, Category category); long insertMateCategory(long categoryId, Category category); void deleteCategory(long categoryId); void insertCategoryTreeInTransaction(CategoryTree<Category> tree); void updateCategoryTree(CategoryTree<Category> tree); List<SmsTemplate> getSmsTemplatesForCategory(long categoryId); List<SmsTemplate> getSmsTemplatesByNumber(String smsNumber); Set<String> findAllSmsTemplateNumbers(); Cursor getAllSmsTemplates(); Cursor getSmsTemplatesWithFullInfo(); Cursor getSmsTemplatesWithFullInfo(final String filter); long duplicateSmsTemplateBelowOriginal(long id); ArrayList<Attribute> getAttributesForCategory(long categoryId); ArrayList<Attribute> getAllAttributesForCategory(long categoryId); Attribute getSystemAttribute(SystemAttribute a); Attribute getAttribute(long id); long insertOrUpdate(Attribute attribute); void deleteAttribute(long id); Cursor getAllAttributes(); Map<Long, String> getAllAttributesMap(); Map<Long, String> getAllAttributesForTransaction(long transactionId); EnumMap<SystemAttribute, String> getSystemAttributesForTransaction(long transactionId); void clearSelectedTransactions(long[] ids); void reconcileSelectedTransactions(long[] ids); void deleteSelectedTransactions(long[] ids); long[] storeMissedSchedules(List<RestoredTransaction> restored, long now); int getCustomClosingDay(long accountId, int period); void setCustomClosingDay(long accountId, int period, int closingDay); void deleteCustomClosingDay(long accountId, int period); void updateCustomClosingDay(long accountId, int period, int closingDay); void rebuildRunningBalances(); void rebuildRunningBalanceForAccount(Account account); long fetchBudgetBalance(Map<Long, Category> categories, Map<Long, Project> projects, Budget b); void recalculateAccountsBalances(); void saveRate(ExchangeRate r); void replaceRate(ExchangeRate rate, long originalDate); void saveDownloadedRates(List<ExchangeRate> downloadedRates); ExchangeRate findRate(Currency fromCurrency, Currency toCurrency, long date); List<ExchangeRate> findRates(Currency fromCurrency); List<ExchangeRate> findRates(Currency fromCurrency, Currency toCurrency); ExchangeRateProvider getLatestRates(); ExchangeRateProvider getHistoryRates(); void deleteRate(ExchangeRate rate); void deleteRate(long fromCurrencyId, long toCurrencyId, long date); Total getAccountsTotalInHomeCurrency(); Total[] getAccountsTotal(); Total getAccountsTotal(Currency homeCurrency); List<Long> findAccountsByNumber(String numberEnding); boolean singleCurrencyOnly(); void setDefaultHomeCurrency(); void purgeAccountAtDate(Account account, long date); void deleteOldTransactions(Account account, long date); long getAccountBalanceForTransaction(Account a, Transaction t); long findNearestOlderTransactionId(Account account, long date); long findLatestTransactionDate(long accountId); void updateAccountsLastTransactionDate(); void restoreSystemEntities(); long getLastRunningBalanceForAccount(Account account); } |
@Test public void should_delete_old_transactions() { a2 = AccountBuilder.createDefault(db); TransactionBuilder.withDb(db).dateTime(DateTime.date(2012, 5, 25).at(17, 30, 45, 0)).account(a2).amount(-234).create(); TransactionBuilder.withDb(db).dateTime(DateTime.date(2012, 5, 24).at(12, 30, 0, 0)).account(a1).amount(-100) .withSplit(categoriesMap.get("A1"), -50) .withTransferSplit(a2, -50, 50) .create(); TransactionBuilder.withDb(db).scheduleOnce(DateTime.date(2012, 5, 23).at(0, 0, 0, 45)).account(a1).amount(100).create(); TransactionBuilder.withDb(db).dateTime(DateTime.date(2012, 5, 23).at(23, 59, 59, 999)).account(a1).amount(10).create(); TransferBuilder.withDb(db).dateTime(DateTime.date(2012, 5, 22).at(22, 0, 0, 0)) .fromAccount(a1).fromAmount(10) .toAccount(a2).toAmount(10).create(); TransactionBuilder.withDb(db).dateTime(DateTime.date(2012, 5, 22).at(12, 0, 12, 345)).account(a1).amount(10).makeTemplate().create(); TransactionBuilder.withDb(db).dateTime(DateTime.date(2012, 5, 21).at(0, 0, 0, 0)).account(a1).amount(-20).create(); assertTransactionsCount(a1, 8); assertTransactionsCount(a2, 1); db.deleteOldTransactions(a1, DateTime.date(2012, 5, 20).asLong()); assertTransactionsCount(a1, 8); assertTransactionsCount(a2, 1); db.deleteOldTransactions(a1, DateTime.date(2012, 5, 21).asLong()); assertTransactionsCount(a1, 7); assertTransactionsCount(a2, 1); db.deleteOldTransactions(a1, DateTime.date(2012, 5, 22).asLong()); assertTransactionsCount(a1, 6); assertTransactionsCount(a2, 1); db.deleteOldTransactions(a1, DateTime.date(2012, 5, 23).asLong()); assertTransactionsCount(a1, 5); assertTransactionsCount(a2, 1); db.deleteOldTransactions(a1, DateTime.date(2012, 5, 25).asLong()); assertTransactionsCount(a1, 2); assertTransactionsCount(a2, 1); db.deleteOldTransactions(a2, DateTime.date(2012, 5, 25).asLong()); assertTransactionsCount(a1, 2); assertTransactionsCount(a2, 0); } | public void deleteOldTransactions(Account account, long date) { SQLiteDatabase db = db(); long dayEnd = DateUtils.atDayEnd(date); db.delete("transactions", "from_account_id=? and datetime<=? and is_template=0", new String[]{String.valueOf(account.id), String.valueOf(dayEnd)}); db.delete("running_balance", "account_id=? and datetime<=?", new String[]{String.valueOf(account.id), String.valueOf(dayEnd)}); } | DatabaseAdapter extends MyEntityManager { public void deleteOldTransactions(Account account, long date) { SQLiteDatabase db = db(); long dayEnd = DateUtils.atDayEnd(date); db.delete("transactions", "from_account_id=? and datetime<=? and is_template=0", new String[]{String.valueOf(account.id), String.valueOf(dayEnd)}); db.delete("running_balance", "account_id=? and datetime<=?", new String[]{String.valueOf(account.id), String.valueOf(dayEnd)}); } } | DatabaseAdapter extends MyEntityManager { public void deleteOldTransactions(Account account, long date) { SQLiteDatabase db = db(); long dayEnd = DateUtils.atDayEnd(date); db.delete("transactions", "from_account_id=? and datetime<=? and is_template=0", new String[]{String.valueOf(account.id), String.valueOf(dayEnd)}); db.delete("running_balance", "account_id=? and datetime<=?", new String[]{String.valueOf(account.id), String.valueOf(dayEnd)}); } DatabaseAdapter(Context context); } | DatabaseAdapter extends MyEntityManager { public void deleteOldTransactions(Account account, long date) { SQLiteDatabase db = db(); long dayEnd = DateUtils.atDayEnd(date); db.delete("transactions", "from_account_id=? and datetime<=? and is_template=0", new String[]{String.valueOf(account.id), String.valueOf(dayEnd)}); db.delete("running_balance", "account_id=? and datetime<=?", new String[]{String.valueOf(account.id), String.valueOf(dayEnd)}); } DatabaseAdapter(Context context); void open(); void close(); int deleteAccount(long id); Transaction getTransaction(long id); Cursor getBlotter(WhereFilter filter); Cursor getBlotterForAccount(WhereFilter filter); static WhereFilter enhanceFilterForAccountBlotter(WhereFilter filter); Cursor getBlotterForAccountWithSplits(WhereFilter filter); Cursor getAllTemplates(WhereFilter filter, String sortBy); Cursor getBlotterWithSplits(String where); long duplicateTransaction(long id); long duplicateTransactionWithMultiplier(long id, int multiplier); long duplicateTransactionAsTemplate(long id); long insertOrUpdate(Transaction transaction); long insertOrUpdate(Transaction transaction, List<TransactionAttribute> attributes); long insertOrUpdateInTransaction(Transaction transaction, List<TransactionAttribute> attributes); void insertWithoutUpdatingBalance(Transaction transaction); void updateTransactionStatus(long id, TransactionStatus status); void deleteTransaction(long id); void deleteTransactionNoDbTransaction(long id); long insertOrUpdate(Category category, List<Attribute> attributes); Category getCategoryWithParent(long id); List<Long> getCategoryIdsByLeftIds(List<String> leftIds); Category getCategoryByLeft(long left); CategoryTree<Category> getCategoriesTreeWithoutSubTree(long excludingTreeId, boolean includeNoCategory); CategoryTree<Category> getCategoriesTree(boolean includeNoCategory); CategoryTree<Category> getAllCategoriesTree(); Map<Long, Category> getAllCategoriesMap(); List<Category> getCategoriesList(boolean includeNoCategory); Cursor getAllCategories(); List<Category> getAllCategoriesList(); Cursor getCategories(boolean includeNoCategory); Cursor filterCategories(CharSequence titleFilter); Cursor getCategories(boolean includeNoCategory, CharSequence titleFilter); Cursor getCategoriesWithoutSubtree(long id, boolean includeNoCategory); List<Category> getCategoriesWithoutSubtreeAsList(long categoryId); long insertChildCategory(long parentId, Category category); long insertMateCategory(long categoryId, Category category); void deleteCategory(long categoryId); void insertCategoryTreeInTransaction(CategoryTree<Category> tree); void updateCategoryTree(CategoryTree<Category> tree); List<SmsTemplate> getSmsTemplatesForCategory(long categoryId); List<SmsTemplate> getSmsTemplatesByNumber(String smsNumber); Set<String> findAllSmsTemplateNumbers(); Cursor getAllSmsTemplates(); Cursor getSmsTemplatesWithFullInfo(); Cursor getSmsTemplatesWithFullInfo(final String filter); long duplicateSmsTemplateBelowOriginal(long id); ArrayList<Attribute> getAttributesForCategory(long categoryId); ArrayList<Attribute> getAllAttributesForCategory(long categoryId); Attribute getSystemAttribute(SystemAttribute a); Attribute getAttribute(long id); long insertOrUpdate(Attribute attribute); void deleteAttribute(long id); Cursor getAllAttributes(); Map<Long, String> getAllAttributesMap(); Map<Long, String> getAllAttributesForTransaction(long transactionId); EnumMap<SystemAttribute, String> getSystemAttributesForTransaction(long transactionId); void clearSelectedTransactions(long[] ids); void reconcileSelectedTransactions(long[] ids); void deleteSelectedTransactions(long[] ids); long[] storeMissedSchedules(List<RestoredTransaction> restored, long now); int getCustomClosingDay(long accountId, int period); void setCustomClosingDay(long accountId, int period, int closingDay); void deleteCustomClosingDay(long accountId, int period); void updateCustomClosingDay(long accountId, int period, int closingDay); void rebuildRunningBalances(); void rebuildRunningBalanceForAccount(Account account); long fetchBudgetBalance(Map<Long, Category> categories, Map<Long, Project> projects, Budget b); void recalculateAccountsBalances(); void saveRate(ExchangeRate r); void replaceRate(ExchangeRate rate, long originalDate); void saveDownloadedRates(List<ExchangeRate> downloadedRates); ExchangeRate findRate(Currency fromCurrency, Currency toCurrency, long date); List<ExchangeRate> findRates(Currency fromCurrency); List<ExchangeRate> findRates(Currency fromCurrency, Currency toCurrency); ExchangeRateProvider getLatestRates(); ExchangeRateProvider getHistoryRates(); void deleteRate(ExchangeRate rate); void deleteRate(long fromCurrencyId, long toCurrencyId, long date); Total getAccountsTotalInHomeCurrency(); Total[] getAccountsTotal(); Total getAccountsTotal(Currency homeCurrency); List<Long> findAccountsByNumber(String numberEnding); boolean singleCurrencyOnly(); void setDefaultHomeCurrency(); void purgeAccountAtDate(Account account, long date); void deleteOldTransactions(Account account, long date); long getAccountBalanceForTransaction(Account a, Transaction t); long findNearestOlderTransactionId(Account account, long date); long findLatestTransactionDate(long accountId); void updateAccountsLastTransactionDate(); void restoreSystemEntities(); long getLastRunningBalanceForAccount(Account account); } | DatabaseAdapter extends MyEntityManager { public void deleteOldTransactions(Account account, long date) { SQLiteDatabase db = db(); long dayEnd = DateUtils.atDayEnd(date); db.delete("transactions", "from_account_id=? and datetime<=? and is_template=0", new String[]{String.valueOf(account.id), String.valueOf(dayEnd)}); db.delete("running_balance", "account_id=? and datetime<=?", new String[]{String.valueOf(account.id), String.valueOf(dayEnd)}); } DatabaseAdapter(Context context); void open(); void close(); int deleteAccount(long id); Transaction getTransaction(long id); Cursor getBlotter(WhereFilter filter); Cursor getBlotterForAccount(WhereFilter filter); static WhereFilter enhanceFilterForAccountBlotter(WhereFilter filter); Cursor getBlotterForAccountWithSplits(WhereFilter filter); Cursor getAllTemplates(WhereFilter filter, String sortBy); Cursor getBlotterWithSplits(String where); long duplicateTransaction(long id); long duplicateTransactionWithMultiplier(long id, int multiplier); long duplicateTransactionAsTemplate(long id); long insertOrUpdate(Transaction transaction); long insertOrUpdate(Transaction transaction, List<TransactionAttribute> attributes); long insertOrUpdateInTransaction(Transaction transaction, List<TransactionAttribute> attributes); void insertWithoutUpdatingBalance(Transaction transaction); void updateTransactionStatus(long id, TransactionStatus status); void deleteTransaction(long id); void deleteTransactionNoDbTransaction(long id); long insertOrUpdate(Category category, List<Attribute> attributes); Category getCategoryWithParent(long id); List<Long> getCategoryIdsByLeftIds(List<String> leftIds); Category getCategoryByLeft(long left); CategoryTree<Category> getCategoriesTreeWithoutSubTree(long excludingTreeId, boolean includeNoCategory); CategoryTree<Category> getCategoriesTree(boolean includeNoCategory); CategoryTree<Category> getAllCategoriesTree(); Map<Long, Category> getAllCategoriesMap(); List<Category> getCategoriesList(boolean includeNoCategory); Cursor getAllCategories(); List<Category> getAllCategoriesList(); Cursor getCategories(boolean includeNoCategory); Cursor filterCategories(CharSequence titleFilter); Cursor getCategories(boolean includeNoCategory, CharSequence titleFilter); Cursor getCategoriesWithoutSubtree(long id, boolean includeNoCategory); List<Category> getCategoriesWithoutSubtreeAsList(long categoryId); long insertChildCategory(long parentId, Category category); long insertMateCategory(long categoryId, Category category); void deleteCategory(long categoryId); void insertCategoryTreeInTransaction(CategoryTree<Category> tree); void updateCategoryTree(CategoryTree<Category> tree); List<SmsTemplate> getSmsTemplatesForCategory(long categoryId); List<SmsTemplate> getSmsTemplatesByNumber(String smsNumber); Set<String> findAllSmsTemplateNumbers(); Cursor getAllSmsTemplates(); Cursor getSmsTemplatesWithFullInfo(); Cursor getSmsTemplatesWithFullInfo(final String filter); long duplicateSmsTemplateBelowOriginal(long id); ArrayList<Attribute> getAttributesForCategory(long categoryId); ArrayList<Attribute> getAllAttributesForCategory(long categoryId); Attribute getSystemAttribute(SystemAttribute a); Attribute getAttribute(long id); long insertOrUpdate(Attribute attribute); void deleteAttribute(long id); Cursor getAllAttributes(); Map<Long, String> getAllAttributesMap(); Map<Long, String> getAllAttributesForTransaction(long transactionId); EnumMap<SystemAttribute, String> getSystemAttributesForTransaction(long transactionId); void clearSelectedTransactions(long[] ids); void reconcileSelectedTransactions(long[] ids); void deleteSelectedTransactions(long[] ids); long[] storeMissedSchedules(List<RestoredTransaction> restored, long now); int getCustomClosingDay(long accountId, int period); void setCustomClosingDay(long accountId, int period, int closingDay); void deleteCustomClosingDay(long accountId, int period); void updateCustomClosingDay(long accountId, int period, int closingDay); void rebuildRunningBalances(); void rebuildRunningBalanceForAccount(Account account); long fetchBudgetBalance(Map<Long, Category> categories, Map<Long, Project> projects, Budget b); void recalculateAccountsBalances(); void saveRate(ExchangeRate r); void replaceRate(ExchangeRate rate, long originalDate); void saveDownloadedRates(List<ExchangeRate> downloadedRates); ExchangeRate findRate(Currency fromCurrency, Currency toCurrency, long date); List<ExchangeRate> findRates(Currency fromCurrency); List<ExchangeRate> findRates(Currency fromCurrency, Currency toCurrency); ExchangeRateProvider getLatestRates(); ExchangeRateProvider getHistoryRates(); void deleteRate(ExchangeRate rate); void deleteRate(long fromCurrencyId, long toCurrencyId, long date); Total getAccountsTotalInHomeCurrency(); Total[] getAccountsTotal(); Total getAccountsTotal(Currency homeCurrency); List<Long> findAccountsByNumber(String numberEnding); boolean singleCurrencyOnly(); void setDefaultHomeCurrency(); void purgeAccountAtDate(Account account, long date); void deleteOldTransactions(Account account, long date); long getAccountBalanceForTransaction(Account a, Transaction t); long findNearestOlderTransactionId(Account account, long date); long findLatestTransactionDate(long accountId); void updateAccountsLastTransactionDate(); void restoreSystemEntities(); long getLastRunningBalanceForAccount(Account account); } |
@Test public void should_find_latest_transaction_date_for_an_account() { Account a2 = AccountBuilder.createDefault(db); Account a3 = AccountBuilder.createDefault(db); Account a4 = AccountBuilder.createDefault(db); TransactionBuilder.withDb(db).dateTime(DateTime.date(2012, 5, 25).at(17, 30, 45, 0)).account(a2).amount(-234).create(); TransactionBuilder.withDb(db).scheduleOnce(DateTime.date(2012, 5, 23).at(0, 0, 0, 45)).account(a1).amount(100).create(); TransactionBuilder.withDb(db).dateTime(DateTime.date(2012, 5, 23).at(23, 59, 59, 999)).account(a1).amount(10).create(); TransactionBuilder.withDb(db).dateTime(DateTime.date(2012, 5, 22).at(12, 30, 0, 0)).account(a1).amount(-100) .withSplit(categoriesMap.get("A1"), -50) .withTransferSplit(a3, -50, 50) .create(); TransactionBuilder.withDb(db).dateTime(DateTime.date(2012, 5, 21).at(12, 0, 12, 345)).account(a2).amount(10).makeTemplate().create(); TransactionBuilder.withDb(db).dateTime(DateTime.date(2012, 5, 20).at(0, 0, 0, 0)).account(a2).amount(-20).create(); assertEquals(DateTime.date(2012, 5, 23).at(23, 59, 59, 999).asLong(), db.findLatestTransactionDate(a1.id)); assertEquals(DateTime.date(2012, 5, 25).at(17, 30, 45, 0).asLong(), db.findLatestTransactionDate(a2.id)); assertEquals(DateTime.date(2012, 5, 22).at(12, 30, 0, 0).asLong(), db.findLatestTransactionDate(a3.id)); assertEquals(0, db.findLatestTransactionDate(a4.id)); } | public long findLatestTransactionDate(long accountId) { return DatabaseUtils.rawFetchLongValue(this, "select datetime from running_balance where account_id=? order by datetime desc limit 1", new String[]{String.valueOf(accountId)}); } | DatabaseAdapter extends MyEntityManager { public long findLatestTransactionDate(long accountId) { return DatabaseUtils.rawFetchLongValue(this, "select datetime from running_balance where account_id=? order by datetime desc limit 1", new String[]{String.valueOf(accountId)}); } } | DatabaseAdapter extends MyEntityManager { public long findLatestTransactionDate(long accountId) { return DatabaseUtils.rawFetchLongValue(this, "select datetime from running_balance where account_id=? order by datetime desc limit 1", new String[]{String.valueOf(accountId)}); } DatabaseAdapter(Context context); } | DatabaseAdapter extends MyEntityManager { public long findLatestTransactionDate(long accountId) { return DatabaseUtils.rawFetchLongValue(this, "select datetime from running_balance where account_id=? order by datetime desc limit 1", new String[]{String.valueOf(accountId)}); } DatabaseAdapter(Context context); void open(); void close(); int deleteAccount(long id); Transaction getTransaction(long id); Cursor getBlotter(WhereFilter filter); Cursor getBlotterForAccount(WhereFilter filter); static WhereFilter enhanceFilterForAccountBlotter(WhereFilter filter); Cursor getBlotterForAccountWithSplits(WhereFilter filter); Cursor getAllTemplates(WhereFilter filter, String sortBy); Cursor getBlotterWithSplits(String where); long duplicateTransaction(long id); long duplicateTransactionWithMultiplier(long id, int multiplier); long duplicateTransactionAsTemplate(long id); long insertOrUpdate(Transaction transaction); long insertOrUpdate(Transaction transaction, List<TransactionAttribute> attributes); long insertOrUpdateInTransaction(Transaction transaction, List<TransactionAttribute> attributes); void insertWithoutUpdatingBalance(Transaction transaction); void updateTransactionStatus(long id, TransactionStatus status); void deleteTransaction(long id); void deleteTransactionNoDbTransaction(long id); long insertOrUpdate(Category category, List<Attribute> attributes); Category getCategoryWithParent(long id); List<Long> getCategoryIdsByLeftIds(List<String> leftIds); Category getCategoryByLeft(long left); CategoryTree<Category> getCategoriesTreeWithoutSubTree(long excludingTreeId, boolean includeNoCategory); CategoryTree<Category> getCategoriesTree(boolean includeNoCategory); CategoryTree<Category> getAllCategoriesTree(); Map<Long, Category> getAllCategoriesMap(); List<Category> getCategoriesList(boolean includeNoCategory); Cursor getAllCategories(); List<Category> getAllCategoriesList(); Cursor getCategories(boolean includeNoCategory); Cursor filterCategories(CharSequence titleFilter); Cursor getCategories(boolean includeNoCategory, CharSequence titleFilter); Cursor getCategoriesWithoutSubtree(long id, boolean includeNoCategory); List<Category> getCategoriesWithoutSubtreeAsList(long categoryId); long insertChildCategory(long parentId, Category category); long insertMateCategory(long categoryId, Category category); void deleteCategory(long categoryId); void insertCategoryTreeInTransaction(CategoryTree<Category> tree); void updateCategoryTree(CategoryTree<Category> tree); List<SmsTemplate> getSmsTemplatesForCategory(long categoryId); List<SmsTemplate> getSmsTemplatesByNumber(String smsNumber); Set<String> findAllSmsTemplateNumbers(); Cursor getAllSmsTemplates(); Cursor getSmsTemplatesWithFullInfo(); Cursor getSmsTemplatesWithFullInfo(final String filter); long duplicateSmsTemplateBelowOriginal(long id); ArrayList<Attribute> getAttributesForCategory(long categoryId); ArrayList<Attribute> getAllAttributesForCategory(long categoryId); Attribute getSystemAttribute(SystemAttribute a); Attribute getAttribute(long id); long insertOrUpdate(Attribute attribute); void deleteAttribute(long id); Cursor getAllAttributes(); Map<Long, String> getAllAttributesMap(); Map<Long, String> getAllAttributesForTransaction(long transactionId); EnumMap<SystemAttribute, String> getSystemAttributesForTransaction(long transactionId); void clearSelectedTransactions(long[] ids); void reconcileSelectedTransactions(long[] ids); void deleteSelectedTransactions(long[] ids); long[] storeMissedSchedules(List<RestoredTransaction> restored, long now); int getCustomClosingDay(long accountId, int period); void setCustomClosingDay(long accountId, int period, int closingDay); void deleteCustomClosingDay(long accountId, int period); void updateCustomClosingDay(long accountId, int period, int closingDay); void rebuildRunningBalances(); void rebuildRunningBalanceForAccount(Account account); long fetchBudgetBalance(Map<Long, Category> categories, Map<Long, Project> projects, Budget b); void recalculateAccountsBalances(); void saveRate(ExchangeRate r); void replaceRate(ExchangeRate rate, long originalDate); void saveDownloadedRates(List<ExchangeRate> downloadedRates); ExchangeRate findRate(Currency fromCurrency, Currency toCurrency, long date); List<ExchangeRate> findRates(Currency fromCurrency); List<ExchangeRate> findRates(Currency fromCurrency, Currency toCurrency); ExchangeRateProvider getLatestRates(); ExchangeRateProvider getHistoryRates(); void deleteRate(ExchangeRate rate); void deleteRate(long fromCurrencyId, long toCurrencyId, long date); Total getAccountsTotalInHomeCurrency(); Total[] getAccountsTotal(); Total getAccountsTotal(Currency homeCurrency); List<Long> findAccountsByNumber(String numberEnding); boolean singleCurrencyOnly(); void setDefaultHomeCurrency(); void purgeAccountAtDate(Account account, long date); void deleteOldTransactions(Account account, long date); long getAccountBalanceForTransaction(Account a, Transaction t); long findNearestOlderTransactionId(Account account, long date); long findLatestTransactionDate(long accountId); void updateAccountsLastTransactionDate(); void restoreSystemEntities(); long getLastRunningBalanceForAccount(Account account); } | DatabaseAdapter extends MyEntityManager { public long findLatestTransactionDate(long accountId) { return DatabaseUtils.rawFetchLongValue(this, "select datetime from running_balance where account_id=? order by datetime desc limit 1", new String[]{String.valueOf(accountId)}); } DatabaseAdapter(Context context); void open(); void close(); int deleteAccount(long id); Transaction getTransaction(long id); Cursor getBlotter(WhereFilter filter); Cursor getBlotterForAccount(WhereFilter filter); static WhereFilter enhanceFilterForAccountBlotter(WhereFilter filter); Cursor getBlotterForAccountWithSplits(WhereFilter filter); Cursor getAllTemplates(WhereFilter filter, String sortBy); Cursor getBlotterWithSplits(String where); long duplicateTransaction(long id); long duplicateTransactionWithMultiplier(long id, int multiplier); long duplicateTransactionAsTemplate(long id); long insertOrUpdate(Transaction transaction); long insertOrUpdate(Transaction transaction, List<TransactionAttribute> attributes); long insertOrUpdateInTransaction(Transaction transaction, List<TransactionAttribute> attributes); void insertWithoutUpdatingBalance(Transaction transaction); void updateTransactionStatus(long id, TransactionStatus status); void deleteTransaction(long id); void deleteTransactionNoDbTransaction(long id); long insertOrUpdate(Category category, List<Attribute> attributes); Category getCategoryWithParent(long id); List<Long> getCategoryIdsByLeftIds(List<String> leftIds); Category getCategoryByLeft(long left); CategoryTree<Category> getCategoriesTreeWithoutSubTree(long excludingTreeId, boolean includeNoCategory); CategoryTree<Category> getCategoriesTree(boolean includeNoCategory); CategoryTree<Category> getAllCategoriesTree(); Map<Long, Category> getAllCategoriesMap(); List<Category> getCategoriesList(boolean includeNoCategory); Cursor getAllCategories(); List<Category> getAllCategoriesList(); Cursor getCategories(boolean includeNoCategory); Cursor filterCategories(CharSequence titleFilter); Cursor getCategories(boolean includeNoCategory, CharSequence titleFilter); Cursor getCategoriesWithoutSubtree(long id, boolean includeNoCategory); List<Category> getCategoriesWithoutSubtreeAsList(long categoryId); long insertChildCategory(long parentId, Category category); long insertMateCategory(long categoryId, Category category); void deleteCategory(long categoryId); void insertCategoryTreeInTransaction(CategoryTree<Category> tree); void updateCategoryTree(CategoryTree<Category> tree); List<SmsTemplate> getSmsTemplatesForCategory(long categoryId); List<SmsTemplate> getSmsTemplatesByNumber(String smsNumber); Set<String> findAllSmsTemplateNumbers(); Cursor getAllSmsTemplates(); Cursor getSmsTemplatesWithFullInfo(); Cursor getSmsTemplatesWithFullInfo(final String filter); long duplicateSmsTemplateBelowOriginal(long id); ArrayList<Attribute> getAttributesForCategory(long categoryId); ArrayList<Attribute> getAllAttributesForCategory(long categoryId); Attribute getSystemAttribute(SystemAttribute a); Attribute getAttribute(long id); long insertOrUpdate(Attribute attribute); void deleteAttribute(long id); Cursor getAllAttributes(); Map<Long, String> getAllAttributesMap(); Map<Long, String> getAllAttributesForTransaction(long transactionId); EnumMap<SystemAttribute, String> getSystemAttributesForTransaction(long transactionId); void clearSelectedTransactions(long[] ids); void reconcileSelectedTransactions(long[] ids); void deleteSelectedTransactions(long[] ids); long[] storeMissedSchedules(List<RestoredTransaction> restored, long now); int getCustomClosingDay(long accountId, int period); void setCustomClosingDay(long accountId, int period, int closingDay); void deleteCustomClosingDay(long accountId, int period); void updateCustomClosingDay(long accountId, int period, int closingDay); void rebuildRunningBalances(); void rebuildRunningBalanceForAccount(Account account); long fetchBudgetBalance(Map<Long, Category> categories, Map<Long, Project> projects, Budget b); void recalculateAccountsBalances(); void saveRate(ExchangeRate r); void replaceRate(ExchangeRate rate, long originalDate); void saveDownloadedRates(List<ExchangeRate> downloadedRates); ExchangeRate findRate(Currency fromCurrency, Currency toCurrency, long date); List<ExchangeRate> findRates(Currency fromCurrency); List<ExchangeRate> findRates(Currency fromCurrency, Currency toCurrency); ExchangeRateProvider getLatestRates(); ExchangeRateProvider getHistoryRates(); void deleteRate(ExchangeRate rate); void deleteRate(long fromCurrencyId, long toCurrencyId, long date); Total getAccountsTotalInHomeCurrency(); Total[] getAccountsTotal(); Total getAccountsTotal(Currency homeCurrency); List<Long> findAccountsByNumber(String numberEnding); boolean singleCurrencyOnly(); void setDefaultHomeCurrency(); void purgeAccountAtDate(Account account, long date); void deleteOldTransactions(Account account, long date); long getAccountBalanceForTransaction(Account a, Transaction t); long findNearestOlderTransactionId(Account account, long date); long findLatestTransactionDate(long accountId); void updateAccountsLastTransactionDate(); void restoreSystemEntities(); long getLastRunningBalanceForAccount(Account account); } |
@Test public void should_restore_system_entities() { givenSystemEntitiesHaveBeenDeleted(); db.restoreSystemEntities(); for (MyEntity e : systemEntities) { MyEntity myEntity = db.get(e.getClass(), e.id); assertNotNull(e.getClass() + ":" + e.getTitle(), myEntity); } Category c = db.get(Category.class, Category.NO_CATEGORY_ID); assertNotNull(c); assertEquals("<NO_CATEGORY>", c.title); } | public void restoreSystemEntities() { SQLiteDatabase db = db(); db.beginTransaction(); try { restoreCategories(); restoreAttributes(); restoreProjects(); restoreLocations(); db.setTransactionSuccessful(); } catch (Exception e) { Log.e("Financisto", "Unable to restore system entities", e); } finally { db.endTransaction(); } } | DatabaseAdapter extends MyEntityManager { public void restoreSystemEntities() { SQLiteDatabase db = db(); db.beginTransaction(); try { restoreCategories(); restoreAttributes(); restoreProjects(); restoreLocations(); db.setTransactionSuccessful(); } catch (Exception e) { Log.e("Financisto", "Unable to restore system entities", e); } finally { db.endTransaction(); } } } | DatabaseAdapter extends MyEntityManager { public void restoreSystemEntities() { SQLiteDatabase db = db(); db.beginTransaction(); try { restoreCategories(); restoreAttributes(); restoreProjects(); restoreLocations(); db.setTransactionSuccessful(); } catch (Exception e) { Log.e("Financisto", "Unable to restore system entities", e); } finally { db.endTransaction(); } } DatabaseAdapter(Context context); } | DatabaseAdapter extends MyEntityManager { public void restoreSystemEntities() { SQLiteDatabase db = db(); db.beginTransaction(); try { restoreCategories(); restoreAttributes(); restoreProjects(); restoreLocations(); db.setTransactionSuccessful(); } catch (Exception e) { Log.e("Financisto", "Unable to restore system entities", e); } finally { db.endTransaction(); } } DatabaseAdapter(Context context); void open(); void close(); int deleteAccount(long id); Transaction getTransaction(long id); Cursor getBlotter(WhereFilter filter); Cursor getBlotterForAccount(WhereFilter filter); static WhereFilter enhanceFilterForAccountBlotter(WhereFilter filter); Cursor getBlotterForAccountWithSplits(WhereFilter filter); Cursor getAllTemplates(WhereFilter filter, String sortBy); Cursor getBlotterWithSplits(String where); long duplicateTransaction(long id); long duplicateTransactionWithMultiplier(long id, int multiplier); long duplicateTransactionAsTemplate(long id); long insertOrUpdate(Transaction transaction); long insertOrUpdate(Transaction transaction, List<TransactionAttribute> attributes); long insertOrUpdateInTransaction(Transaction transaction, List<TransactionAttribute> attributes); void insertWithoutUpdatingBalance(Transaction transaction); void updateTransactionStatus(long id, TransactionStatus status); void deleteTransaction(long id); void deleteTransactionNoDbTransaction(long id); long insertOrUpdate(Category category, List<Attribute> attributes); Category getCategoryWithParent(long id); List<Long> getCategoryIdsByLeftIds(List<String> leftIds); Category getCategoryByLeft(long left); CategoryTree<Category> getCategoriesTreeWithoutSubTree(long excludingTreeId, boolean includeNoCategory); CategoryTree<Category> getCategoriesTree(boolean includeNoCategory); CategoryTree<Category> getAllCategoriesTree(); Map<Long, Category> getAllCategoriesMap(); List<Category> getCategoriesList(boolean includeNoCategory); Cursor getAllCategories(); List<Category> getAllCategoriesList(); Cursor getCategories(boolean includeNoCategory); Cursor filterCategories(CharSequence titleFilter); Cursor getCategories(boolean includeNoCategory, CharSequence titleFilter); Cursor getCategoriesWithoutSubtree(long id, boolean includeNoCategory); List<Category> getCategoriesWithoutSubtreeAsList(long categoryId); long insertChildCategory(long parentId, Category category); long insertMateCategory(long categoryId, Category category); void deleteCategory(long categoryId); void insertCategoryTreeInTransaction(CategoryTree<Category> tree); void updateCategoryTree(CategoryTree<Category> tree); List<SmsTemplate> getSmsTemplatesForCategory(long categoryId); List<SmsTemplate> getSmsTemplatesByNumber(String smsNumber); Set<String> findAllSmsTemplateNumbers(); Cursor getAllSmsTemplates(); Cursor getSmsTemplatesWithFullInfo(); Cursor getSmsTemplatesWithFullInfo(final String filter); long duplicateSmsTemplateBelowOriginal(long id); ArrayList<Attribute> getAttributesForCategory(long categoryId); ArrayList<Attribute> getAllAttributesForCategory(long categoryId); Attribute getSystemAttribute(SystemAttribute a); Attribute getAttribute(long id); long insertOrUpdate(Attribute attribute); void deleteAttribute(long id); Cursor getAllAttributes(); Map<Long, String> getAllAttributesMap(); Map<Long, String> getAllAttributesForTransaction(long transactionId); EnumMap<SystemAttribute, String> getSystemAttributesForTransaction(long transactionId); void clearSelectedTransactions(long[] ids); void reconcileSelectedTransactions(long[] ids); void deleteSelectedTransactions(long[] ids); long[] storeMissedSchedules(List<RestoredTransaction> restored, long now); int getCustomClosingDay(long accountId, int period); void setCustomClosingDay(long accountId, int period, int closingDay); void deleteCustomClosingDay(long accountId, int period); void updateCustomClosingDay(long accountId, int period, int closingDay); void rebuildRunningBalances(); void rebuildRunningBalanceForAccount(Account account); long fetchBudgetBalance(Map<Long, Category> categories, Map<Long, Project> projects, Budget b); void recalculateAccountsBalances(); void saveRate(ExchangeRate r); void replaceRate(ExchangeRate rate, long originalDate); void saveDownloadedRates(List<ExchangeRate> downloadedRates); ExchangeRate findRate(Currency fromCurrency, Currency toCurrency, long date); List<ExchangeRate> findRates(Currency fromCurrency); List<ExchangeRate> findRates(Currency fromCurrency, Currency toCurrency); ExchangeRateProvider getLatestRates(); ExchangeRateProvider getHistoryRates(); void deleteRate(ExchangeRate rate); void deleteRate(long fromCurrencyId, long toCurrencyId, long date); Total getAccountsTotalInHomeCurrency(); Total[] getAccountsTotal(); Total getAccountsTotal(Currency homeCurrency); List<Long> findAccountsByNumber(String numberEnding); boolean singleCurrencyOnly(); void setDefaultHomeCurrency(); void purgeAccountAtDate(Account account, long date); void deleteOldTransactions(Account account, long date); long getAccountBalanceForTransaction(Account a, Transaction t); long findNearestOlderTransactionId(Account account, long date); long findLatestTransactionDate(long accountId); void updateAccountsLastTransactionDate(); void restoreSystemEntities(); long getLastRunningBalanceForAccount(Account account); } | DatabaseAdapter extends MyEntityManager { public void restoreSystemEntities() { SQLiteDatabase db = db(); db.beginTransaction(); try { restoreCategories(); restoreAttributes(); restoreProjects(); restoreLocations(); db.setTransactionSuccessful(); } catch (Exception e) { Log.e("Financisto", "Unable to restore system entities", e); } finally { db.endTransaction(); } } DatabaseAdapter(Context context); void open(); void close(); int deleteAccount(long id); Transaction getTransaction(long id); Cursor getBlotter(WhereFilter filter); Cursor getBlotterForAccount(WhereFilter filter); static WhereFilter enhanceFilterForAccountBlotter(WhereFilter filter); Cursor getBlotterForAccountWithSplits(WhereFilter filter); Cursor getAllTemplates(WhereFilter filter, String sortBy); Cursor getBlotterWithSplits(String where); long duplicateTransaction(long id); long duplicateTransactionWithMultiplier(long id, int multiplier); long duplicateTransactionAsTemplate(long id); long insertOrUpdate(Transaction transaction); long insertOrUpdate(Transaction transaction, List<TransactionAttribute> attributes); long insertOrUpdateInTransaction(Transaction transaction, List<TransactionAttribute> attributes); void insertWithoutUpdatingBalance(Transaction transaction); void updateTransactionStatus(long id, TransactionStatus status); void deleteTransaction(long id); void deleteTransactionNoDbTransaction(long id); long insertOrUpdate(Category category, List<Attribute> attributes); Category getCategoryWithParent(long id); List<Long> getCategoryIdsByLeftIds(List<String> leftIds); Category getCategoryByLeft(long left); CategoryTree<Category> getCategoriesTreeWithoutSubTree(long excludingTreeId, boolean includeNoCategory); CategoryTree<Category> getCategoriesTree(boolean includeNoCategory); CategoryTree<Category> getAllCategoriesTree(); Map<Long, Category> getAllCategoriesMap(); List<Category> getCategoriesList(boolean includeNoCategory); Cursor getAllCategories(); List<Category> getAllCategoriesList(); Cursor getCategories(boolean includeNoCategory); Cursor filterCategories(CharSequence titleFilter); Cursor getCategories(boolean includeNoCategory, CharSequence titleFilter); Cursor getCategoriesWithoutSubtree(long id, boolean includeNoCategory); List<Category> getCategoriesWithoutSubtreeAsList(long categoryId); long insertChildCategory(long parentId, Category category); long insertMateCategory(long categoryId, Category category); void deleteCategory(long categoryId); void insertCategoryTreeInTransaction(CategoryTree<Category> tree); void updateCategoryTree(CategoryTree<Category> tree); List<SmsTemplate> getSmsTemplatesForCategory(long categoryId); List<SmsTemplate> getSmsTemplatesByNumber(String smsNumber); Set<String> findAllSmsTemplateNumbers(); Cursor getAllSmsTemplates(); Cursor getSmsTemplatesWithFullInfo(); Cursor getSmsTemplatesWithFullInfo(final String filter); long duplicateSmsTemplateBelowOriginal(long id); ArrayList<Attribute> getAttributesForCategory(long categoryId); ArrayList<Attribute> getAllAttributesForCategory(long categoryId); Attribute getSystemAttribute(SystemAttribute a); Attribute getAttribute(long id); long insertOrUpdate(Attribute attribute); void deleteAttribute(long id); Cursor getAllAttributes(); Map<Long, String> getAllAttributesMap(); Map<Long, String> getAllAttributesForTransaction(long transactionId); EnumMap<SystemAttribute, String> getSystemAttributesForTransaction(long transactionId); void clearSelectedTransactions(long[] ids); void reconcileSelectedTransactions(long[] ids); void deleteSelectedTransactions(long[] ids); long[] storeMissedSchedules(List<RestoredTransaction> restored, long now); int getCustomClosingDay(long accountId, int period); void setCustomClosingDay(long accountId, int period, int closingDay); void deleteCustomClosingDay(long accountId, int period); void updateCustomClosingDay(long accountId, int period, int closingDay); void rebuildRunningBalances(); void rebuildRunningBalanceForAccount(Account account); long fetchBudgetBalance(Map<Long, Category> categories, Map<Long, Project> projects, Budget b); void recalculateAccountsBalances(); void saveRate(ExchangeRate r); void replaceRate(ExchangeRate rate, long originalDate); void saveDownloadedRates(List<ExchangeRate> downloadedRates); ExchangeRate findRate(Currency fromCurrency, Currency toCurrency, long date); List<ExchangeRate> findRates(Currency fromCurrency); List<ExchangeRate> findRates(Currency fromCurrency, Currency toCurrency); ExchangeRateProvider getLatestRates(); ExchangeRateProvider getHistoryRates(); void deleteRate(ExchangeRate rate); void deleteRate(long fromCurrencyId, long toCurrencyId, long date); Total getAccountsTotalInHomeCurrency(); Total[] getAccountsTotal(); Total getAccountsTotal(Currency homeCurrency); List<Long> findAccountsByNumber(String numberEnding); boolean singleCurrencyOnly(); void setDefaultHomeCurrency(); void purgeAccountAtDate(Account account, long date); void deleteOldTransactions(Account account, long date); long getAccountBalanceForTransaction(Account a, Transaction t); long findNearestOlderTransactionId(Account account, long date); long findLatestTransactionDate(long accountId); void updateAccountsLastTransactionDate(); void restoreSystemEntities(); long getLastRunningBalanceForAccount(Account account); } |
@Test public void account_number_lookup() { Account account = AccountBuilder.withDb(db) .currency(CurrencyBuilder.createDefault(db)) .title("SB").issuer("Sber").number("1111-2222-3333-5431").create(); final List<Long> res = db.findAccountsByNumber("5431"); assertEquals(1, res.size()); assertEquals((Long) account.id, res.get(0)); } | public List<Long> findAccountsByNumber(String numberEnding) { try (Cursor c = db().rawQuery( "select " + AccountColumns.ID + " from " + ACCOUNT_TABLE + " where " + AccountColumns.NUMBER + " like ?", new String[]{"%" + numberEnding})) { List<Long> res = new ArrayList<>(c.getCount()); while (c.moveToNext()) { res.add(c.getLong(0)); } return res; } } | DatabaseAdapter extends MyEntityManager { public List<Long> findAccountsByNumber(String numberEnding) { try (Cursor c = db().rawQuery( "select " + AccountColumns.ID + " from " + ACCOUNT_TABLE + " where " + AccountColumns.NUMBER + " like ?", new String[]{"%" + numberEnding})) { List<Long> res = new ArrayList<>(c.getCount()); while (c.moveToNext()) { res.add(c.getLong(0)); } return res; } } } | DatabaseAdapter extends MyEntityManager { public List<Long> findAccountsByNumber(String numberEnding) { try (Cursor c = db().rawQuery( "select " + AccountColumns.ID + " from " + ACCOUNT_TABLE + " where " + AccountColumns.NUMBER + " like ?", new String[]{"%" + numberEnding})) { List<Long> res = new ArrayList<>(c.getCount()); while (c.moveToNext()) { res.add(c.getLong(0)); } return res; } } DatabaseAdapter(Context context); } | DatabaseAdapter extends MyEntityManager { public List<Long> findAccountsByNumber(String numberEnding) { try (Cursor c = db().rawQuery( "select " + AccountColumns.ID + " from " + ACCOUNT_TABLE + " where " + AccountColumns.NUMBER + " like ?", new String[]{"%" + numberEnding})) { List<Long> res = new ArrayList<>(c.getCount()); while (c.moveToNext()) { res.add(c.getLong(0)); } return res; } } DatabaseAdapter(Context context); void open(); void close(); int deleteAccount(long id); Transaction getTransaction(long id); Cursor getBlotter(WhereFilter filter); Cursor getBlotterForAccount(WhereFilter filter); static WhereFilter enhanceFilterForAccountBlotter(WhereFilter filter); Cursor getBlotterForAccountWithSplits(WhereFilter filter); Cursor getAllTemplates(WhereFilter filter, String sortBy); Cursor getBlotterWithSplits(String where); long duplicateTransaction(long id); long duplicateTransactionWithMultiplier(long id, int multiplier); long duplicateTransactionAsTemplate(long id); long insertOrUpdate(Transaction transaction); long insertOrUpdate(Transaction transaction, List<TransactionAttribute> attributes); long insertOrUpdateInTransaction(Transaction transaction, List<TransactionAttribute> attributes); void insertWithoutUpdatingBalance(Transaction transaction); void updateTransactionStatus(long id, TransactionStatus status); void deleteTransaction(long id); void deleteTransactionNoDbTransaction(long id); long insertOrUpdate(Category category, List<Attribute> attributes); Category getCategoryWithParent(long id); List<Long> getCategoryIdsByLeftIds(List<String> leftIds); Category getCategoryByLeft(long left); CategoryTree<Category> getCategoriesTreeWithoutSubTree(long excludingTreeId, boolean includeNoCategory); CategoryTree<Category> getCategoriesTree(boolean includeNoCategory); CategoryTree<Category> getAllCategoriesTree(); Map<Long, Category> getAllCategoriesMap(); List<Category> getCategoriesList(boolean includeNoCategory); Cursor getAllCategories(); List<Category> getAllCategoriesList(); Cursor getCategories(boolean includeNoCategory); Cursor filterCategories(CharSequence titleFilter); Cursor getCategories(boolean includeNoCategory, CharSequence titleFilter); Cursor getCategoriesWithoutSubtree(long id, boolean includeNoCategory); List<Category> getCategoriesWithoutSubtreeAsList(long categoryId); long insertChildCategory(long parentId, Category category); long insertMateCategory(long categoryId, Category category); void deleteCategory(long categoryId); void insertCategoryTreeInTransaction(CategoryTree<Category> tree); void updateCategoryTree(CategoryTree<Category> tree); List<SmsTemplate> getSmsTemplatesForCategory(long categoryId); List<SmsTemplate> getSmsTemplatesByNumber(String smsNumber); Set<String> findAllSmsTemplateNumbers(); Cursor getAllSmsTemplates(); Cursor getSmsTemplatesWithFullInfo(); Cursor getSmsTemplatesWithFullInfo(final String filter); long duplicateSmsTemplateBelowOriginal(long id); ArrayList<Attribute> getAttributesForCategory(long categoryId); ArrayList<Attribute> getAllAttributesForCategory(long categoryId); Attribute getSystemAttribute(SystemAttribute a); Attribute getAttribute(long id); long insertOrUpdate(Attribute attribute); void deleteAttribute(long id); Cursor getAllAttributes(); Map<Long, String> getAllAttributesMap(); Map<Long, String> getAllAttributesForTransaction(long transactionId); EnumMap<SystemAttribute, String> getSystemAttributesForTransaction(long transactionId); void clearSelectedTransactions(long[] ids); void reconcileSelectedTransactions(long[] ids); void deleteSelectedTransactions(long[] ids); long[] storeMissedSchedules(List<RestoredTransaction> restored, long now); int getCustomClosingDay(long accountId, int period); void setCustomClosingDay(long accountId, int period, int closingDay); void deleteCustomClosingDay(long accountId, int period); void updateCustomClosingDay(long accountId, int period, int closingDay); void rebuildRunningBalances(); void rebuildRunningBalanceForAccount(Account account); long fetchBudgetBalance(Map<Long, Category> categories, Map<Long, Project> projects, Budget b); void recalculateAccountsBalances(); void saveRate(ExchangeRate r); void replaceRate(ExchangeRate rate, long originalDate); void saveDownloadedRates(List<ExchangeRate> downloadedRates); ExchangeRate findRate(Currency fromCurrency, Currency toCurrency, long date); List<ExchangeRate> findRates(Currency fromCurrency); List<ExchangeRate> findRates(Currency fromCurrency, Currency toCurrency); ExchangeRateProvider getLatestRates(); ExchangeRateProvider getHistoryRates(); void deleteRate(ExchangeRate rate); void deleteRate(long fromCurrencyId, long toCurrencyId, long date); Total getAccountsTotalInHomeCurrency(); Total[] getAccountsTotal(); Total getAccountsTotal(Currency homeCurrency); List<Long> findAccountsByNumber(String numberEnding); boolean singleCurrencyOnly(); void setDefaultHomeCurrency(); void purgeAccountAtDate(Account account, long date); void deleteOldTransactions(Account account, long date); long getAccountBalanceForTransaction(Account a, Transaction t); long findNearestOlderTransactionId(Account account, long date); long findLatestTransactionDate(long accountId); void updateAccountsLastTransactionDate(); void restoreSystemEntities(); long getLastRunningBalanceForAccount(Account account); } | DatabaseAdapter extends MyEntityManager { public List<Long> findAccountsByNumber(String numberEnding) { try (Cursor c = db().rawQuery( "select " + AccountColumns.ID + " from " + ACCOUNT_TABLE + " where " + AccountColumns.NUMBER + " like ?", new String[]{"%" + numberEnding})) { List<Long> res = new ArrayList<>(c.getCount()); while (c.moveToNext()) { res.add(c.getLong(0)); } return res; } } DatabaseAdapter(Context context); void open(); void close(); int deleteAccount(long id); Transaction getTransaction(long id); Cursor getBlotter(WhereFilter filter); Cursor getBlotterForAccount(WhereFilter filter); static WhereFilter enhanceFilterForAccountBlotter(WhereFilter filter); Cursor getBlotterForAccountWithSplits(WhereFilter filter); Cursor getAllTemplates(WhereFilter filter, String sortBy); Cursor getBlotterWithSplits(String where); long duplicateTransaction(long id); long duplicateTransactionWithMultiplier(long id, int multiplier); long duplicateTransactionAsTemplate(long id); long insertOrUpdate(Transaction transaction); long insertOrUpdate(Transaction transaction, List<TransactionAttribute> attributes); long insertOrUpdateInTransaction(Transaction transaction, List<TransactionAttribute> attributes); void insertWithoutUpdatingBalance(Transaction transaction); void updateTransactionStatus(long id, TransactionStatus status); void deleteTransaction(long id); void deleteTransactionNoDbTransaction(long id); long insertOrUpdate(Category category, List<Attribute> attributes); Category getCategoryWithParent(long id); List<Long> getCategoryIdsByLeftIds(List<String> leftIds); Category getCategoryByLeft(long left); CategoryTree<Category> getCategoriesTreeWithoutSubTree(long excludingTreeId, boolean includeNoCategory); CategoryTree<Category> getCategoriesTree(boolean includeNoCategory); CategoryTree<Category> getAllCategoriesTree(); Map<Long, Category> getAllCategoriesMap(); List<Category> getCategoriesList(boolean includeNoCategory); Cursor getAllCategories(); List<Category> getAllCategoriesList(); Cursor getCategories(boolean includeNoCategory); Cursor filterCategories(CharSequence titleFilter); Cursor getCategories(boolean includeNoCategory, CharSequence titleFilter); Cursor getCategoriesWithoutSubtree(long id, boolean includeNoCategory); List<Category> getCategoriesWithoutSubtreeAsList(long categoryId); long insertChildCategory(long parentId, Category category); long insertMateCategory(long categoryId, Category category); void deleteCategory(long categoryId); void insertCategoryTreeInTransaction(CategoryTree<Category> tree); void updateCategoryTree(CategoryTree<Category> tree); List<SmsTemplate> getSmsTemplatesForCategory(long categoryId); List<SmsTemplate> getSmsTemplatesByNumber(String smsNumber); Set<String> findAllSmsTemplateNumbers(); Cursor getAllSmsTemplates(); Cursor getSmsTemplatesWithFullInfo(); Cursor getSmsTemplatesWithFullInfo(final String filter); long duplicateSmsTemplateBelowOriginal(long id); ArrayList<Attribute> getAttributesForCategory(long categoryId); ArrayList<Attribute> getAllAttributesForCategory(long categoryId); Attribute getSystemAttribute(SystemAttribute a); Attribute getAttribute(long id); long insertOrUpdate(Attribute attribute); void deleteAttribute(long id); Cursor getAllAttributes(); Map<Long, String> getAllAttributesMap(); Map<Long, String> getAllAttributesForTransaction(long transactionId); EnumMap<SystemAttribute, String> getSystemAttributesForTransaction(long transactionId); void clearSelectedTransactions(long[] ids); void reconcileSelectedTransactions(long[] ids); void deleteSelectedTransactions(long[] ids); long[] storeMissedSchedules(List<RestoredTransaction> restored, long now); int getCustomClosingDay(long accountId, int period); void setCustomClosingDay(long accountId, int period, int closingDay); void deleteCustomClosingDay(long accountId, int period); void updateCustomClosingDay(long accountId, int period, int closingDay); void rebuildRunningBalances(); void rebuildRunningBalanceForAccount(Account account); long fetchBudgetBalance(Map<Long, Category> categories, Map<Long, Project> projects, Budget b); void recalculateAccountsBalances(); void saveRate(ExchangeRate r); void replaceRate(ExchangeRate rate, long originalDate); void saveDownloadedRates(List<ExchangeRate> downloadedRates); ExchangeRate findRate(Currency fromCurrency, Currency toCurrency, long date); List<ExchangeRate> findRates(Currency fromCurrency); List<ExchangeRate> findRates(Currency fromCurrency, Currency toCurrency); ExchangeRateProvider getLatestRates(); ExchangeRateProvider getHistoryRates(); void deleteRate(ExchangeRate rate); void deleteRate(long fromCurrencyId, long toCurrencyId, long date); Total getAccountsTotalInHomeCurrency(); Total[] getAccountsTotal(); Total getAccountsTotal(Currency homeCurrency); List<Long> findAccountsByNumber(String numberEnding); boolean singleCurrencyOnly(); void setDefaultHomeCurrency(); void purgeAccountAtDate(Account account, long date); void deleteOldTransactions(Account account, long date); long getAccountBalanceForTransaction(Account a, Transaction t); long findNearestOlderTransactionId(Account account, long date); long findLatestTransactionDate(long accountId); void updateAccountsLastTransactionDate(); void restoreSystemEntities(); long getLastRunningBalanceForAccount(Account account); } |
@Test public void should_pay_1_when_buy_espresso() { Espresso espresso = new Espresso(false, false); assertTrue(espresso.cost() == 4.0); } | public abstract double cost(); | Beverage { public abstract double cost(); } | Beverage { public abstract double cost(); protected Beverage(boolean milk, boolean mocha); } | Beverage { public abstract double cost(); protected Beverage(boolean milk, boolean mocha); boolean isMilk(); boolean isMocha(); String getDescription(); abstract double cost(); } | Beverage { public abstract double cost(); protected Beverage(boolean milk, boolean mocha); boolean isMilk(); boolean isMocha(); String getDescription(); abstract double cost(); } |
@Test public void should_turn_off_stereo_when_press_third_off_button() { Stereo stereo = new Stereo(); RemoteControl remoteControl = new RemoteControl(null, null, stereo); remoteControl.off(3); assertFalse(stereo.getCdStatus()); assertFalse(stereo.getCdStatus()); assertEquals(0, stereo.getVolume()); } | public void off(int slot) { if (slot == 1) light.off(); if (slot == 2) ceiling.off(); if (slot == 3) stereo.off(); } | RemoteControl { public void off(int slot) { if (slot == 1) light.off(); if (slot == 2) ceiling.off(); if (slot == 3) stereo.off(); } } | RemoteControl { public void off(int slot) { if (slot == 1) light.off(); if (slot == 2) ceiling.off(); if (slot == 3) stereo.off(); } RemoteControl(Light light, Ceiling ceiling, Stereo stereo); } | RemoteControl { public void off(int slot) { if (slot == 1) light.off(); if (slot == 2) ceiling.off(); if (slot == 3) stereo.off(); } RemoteControl(Light light, Ceiling ceiling, Stereo stereo); void on(int slot); void off(int slot); } | RemoteControl { public void off(int slot) { if (slot == 1) light.off(); if (slot == 2) ceiling.off(); if (slot == 3) stereo.off(); } RemoteControl(Light light, Ceiling ceiling, Stereo stereo); void on(int slot); void off(int slot); } |
@Test public void gumball_machine_status_should_be_no_quarter_at_start() { GumballMachine gumballMachine = new GumballMachine(10, MachineStatus.NO_QUARTER); assertEquals(MachineStatus.NO_QUARTER, gumballMachine.getState()); } | public MachineStatus getState() { return State; } | GumballMachine { public MachineStatus getState() { return State; } } | GumballMachine { public MachineStatus getState() { return State; } GumballMachine(int gumballNum, MachineStatus machineStatus); } | GumballMachine { public MachineStatus getState() { return State; } GumballMachine(int gumballNum, MachineStatus machineStatus); int getGumballNum(); void setGumballNum(int gumballNum); MachineStatus getState(); void setState(MachineStatus state); String insertQuarter(); String turnCrank(); String dispense(); String ejectQuarter(); } | GumballMachine { public MachineStatus getState() { return State; } GumballMachine(int gumballNum, MachineStatus machineStatus); int getGumballNum(); void setGumballNum(int gumballNum); MachineStatus getState(); void setState(MachineStatus state); String insertQuarter(); String turnCrank(); String dispense(); String ejectQuarter(); final String insertedQuarterMessage; } |
@Test public void seeding_machine_should_start_if_temperature_over_5_degree() { weatherData.measurementsChanged(10, 0, 0); assertTrue(seedingMachine.getStatus()); } | public void measurementsChanged(int temp, int humidity, int windPower) { if (temp > 5) { seedingMachine.start(); if (humidity > 65) reapingMachine.start(); } if (temp > 10 && humidity < 55 && windPower < 4) wateringMachine.start(); } | WeatherData { public void measurementsChanged(int temp, int humidity, int windPower) { if (temp > 5) { seedingMachine.start(); if (humidity > 65) reapingMachine.start(); } if (temp > 10 && humidity < 55 && windPower < 4) wateringMachine.start(); } } | WeatherData { public void measurementsChanged(int temp, int humidity, int windPower) { if (temp > 5) { seedingMachine.start(); if (humidity > 65) reapingMachine.start(); } if (temp > 10 && humidity < 55 && windPower < 4) wateringMachine.start(); } WeatherData(SeedingMachine seedingMachine, ReapingMachine reapingMachine, WateringMachine wateringMachine); } | WeatherData { public void measurementsChanged(int temp, int humidity, int windPower) { if (temp > 5) { seedingMachine.start(); if (humidity > 65) reapingMachine.start(); } if (temp > 10 && humidity < 55 && windPower < 4) wateringMachine.start(); } WeatherData(SeedingMachine seedingMachine, ReapingMachine reapingMachine, WateringMachine wateringMachine); void measurementsChanged(int temp, int humidity, int windPower); } | WeatherData { public void measurementsChanged(int temp, int humidity, int windPower) { if (temp > 5) { seedingMachine.start(); if (humidity > 65) reapingMachine.start(); } if (temp > 10 && humidity < 55 && windPower < 4) wateringMachine.start(); } WeatherData(SeedingMachine seedingMachine, ReapingMachine reapingMachine, WateringMachine wateringMachine); void measurementsChanged(int temp, int humidity, int windPower); } |
@Test public void reaping_machine_should_start_if_temperature_over_5_degree_and_humidity_over_65() { weatherData.measurementsChanged(10, 70, 0); assertTrue(reapingMachine.getStatus()); } | public void measurementsChanged(int temp, int humidity, int windPower) { if (temp > 5) { seedingMachine.start(); if (humidity > 65) reapingMachine.start(); } if (temp > 10 && humidity < 55 && windPower < 4) wateringMachine.start(); } | WeatherData { public void measurementsChanged(int temp, int humidity, int windPower) { if (temp > 5) { seedingMachine.start(); if (humidity > 65) reapingMachine.start(); } if (temp > 10 && humidity < 55 && windPower < 4) wateringMachine.start(); } } | WeatherData { public void measurementsChanged(int temp, int humidity, int windPower) { if (temp > 5) { seedingMachine.start(); if (humidity > 65) reapingMachine.start(); } if (temp > 10 && humidity < 55 && windPower < 4) wateringMachine.start(); } WeatherData(SeedingMachine seedingMachine, ReapingMachine reapingMachine, WateringMachine wateringMachine); } | WeatherData { public void measurementsChanged(int temp, int humidity, int windPower) { if (temp > 5) { seedingMachine.start(); if (humidity > 65) reapingMachine.start(); } if (temp > 10 && humidity < 55 && windPower < 4) wateringMachine.start(); } WeatherData(SeedingMachine seedingMachine, ReapingMachine reapingMachine, WateringMachine wateringMachine); void measurementsChanged(int temp, int humidity, int windPower); } | WeatherData { public void measurementsChanged(int temp, int humidity, int windPower) { if (temp > 5) { seedingMachine.start(); if (humidity > 65) reapingMachine.start(); } if (temp > 10 && humidity < 55 && windPower < 4) wateringMachine.start(); } WeatherData(SeedingMachine seedingMachine, ReapingMachine reapingMachine, WateringMachine wateringMachine); void measurementsChanged(int temp, int humidity, int windPower); } |
@Test public void water_machine_should_start_if_temperature_over_10_degree_and_humidity_less_than_55_and_wind_power_less_than_4() { weatherData.measurementsChanged(12, 50, 2); assertTrue(wateringMachine.getStatus()); } | public void measurementsChanged(int temp, int humidity, int windPower) { if (temp > 5) { seedingMachine.start(); if (humidity > 65) reapingMachine.start(); } if (temp > 10 && humidity < 55 && windPower < 4) wateringMachine.start(); } | WeatherData { public void measurementsChanged(int temp, int humidity, int windPower) { if (temp > 5) { seedingMachine.start(); if (humidity > 65) reapingMachine.start(); } if (temp > 10 && humidity < 55 && windPower < 4) wateringMachine.start(); } } | WeatherData { public void measurementsChanged(int temp, int humidity, int windPower) { if (temp > 5) { seedingMachine.start(); if (humidity > 65) reapingMachine.start(); } if (temp > 10 && humidity < 55 && windPower < 4) wateringMachine.start(); } WeatherData(SeedingMachine seedingMachine, ReapingMachine reapingMachine, WateringMachine wateringMachine); } | WeatherData { public void measurementsChanged(int temp, int humidity, int windPower) { if (temp > 5) { seedingMachine.start(); if (humidity > 65) reapingMachine.start(); } if (temp > 10 && humidity < 55 && windPower < 4) wateringMachine.start(); } WeatherData(SeedingMachine seedingMachine, ReapingMachine reapingMachine, WateringMachine wateringMachine); void measurementsChanged(int temp, int humidity, int windPower); } | WeatherData { public void measurementsChanged(int temp, int humidity, int windPower) { if (temp > 5) { seedingMachine.start(); if (humidity > 65) reapingMachine.start(); } if (temp > 10 && humidity < 55 && windPower < 4) wateringMachine.start(); } WeatherData(SeedingMachine seedingMachine, ReapingMachine reapingMachine, WateringMachine wateringMachine); void measurementsChanged(int temp, int humidity, int windPower); } |
@Test public void should_calc_health_rating_Ingredient() { assertEquals(1, flour.getHealthRating()); } | public List<Integer> getHealthRating() { return ingredients.stream() .map(Ingredient::getHealthRating) .collect(Collectors.toList()); } | MenuItem { public List<Integer> getHealthRating() { return ingredients.stream() .map(Ingredient::getHealthRating) .collect(Collectors.toList()); } } | MenuItem { public List<Integer> getHealthRating() { return ingredients.stream() .map(Ingredient::getHealthRating) .collect(Collectors.toList()); } MenuItem(List<Ingredient> ingredients); } | MenuItem { public List<Integer> getHealthRating() { return ingredients.stream() .map(Ingredient::getHealthRating) .collect(Collectors.toList()); } MenuItem(List<Ingredient> ingredients); void AddToPot(); void AddWater(); void AddOil(); void Smell(); void Taste(); void Cook(); List<Integer> getHealthRating(); List<String> getProtein(); List<String> getCalory(); } | MenuItem { public List<Integer> getHealthRating() { return ingredients.stream() .map(Ingredient::getHealthRating) .collect(Collectors.toList()); } MenuItem(List<Ingredient> ingredients); void AddToPot(); void AddWater(); void AddOil(); void Smell(); void Taste(); void Cook(); List<Integer> getHealthRating(); List<String> getProtein(); List<String> getCalory(); } |
@Test public void should_calc_protein_for_Ingredient() { assertEquals("100.0 g", flour.getProtein()); } | public List<String> getProtein() { return ingredients.stream() .map(Ingredient::getProtein) .collect(Collectors.toList()); } | MenuItem { public List<String> getProtein() { return ingredients.stream() .map(Ingredient::getProtein) .collect(Collectors.toList()); } } | MenuItem { public List<String> getProtein() { return ingredients.stream() .map(Ingredient::getProtein) .collect(Collectors.toList()); } MenuItem(List<Ingredient> ingredients); } | MenuItem { public List<String> getProtein() { return ingredients.stream() .map(Ingredient::getProtein) .collect(Collectors.toList()); } MenuItem(List<Ingredient> ingredients); void AddToPot(); void AddWater(); void AddOil(); void Smell(); void Taste(); void Cook(); List<Integer> getHealthRating(); List<String> getProtein(); List<String> getCalory(); } | MenuItem { public List<String> getProtein() { return ingredients.stream() .map(Ingredient::getProtein) .collect(Collectors.toList()); } MenuItem(List<Ingredient> ingredients); void AddToPot(); void AddWater(); void AddOil(); void Smell(); void Taste(); void Cook(); List<Integer> getHealthRating(); List<String> getProtein(); List<String> getCalory(); } |
@Test public void should_calc_calory_for_Ingredient() { assertEquals("10 J", flour.getCalory()); } | public List<String> getCalory() { List<String> calories = ingredients.stream() .map(Ingredient::getCalory) .collect(Collectors.toList()); calories.add("Cooking will double calories!!!"); return calories; } | MenuItem { public List<String> getCalory() { List<String> calories = ingredients.stream() .map(Ingredient::getCalory) .collect(Collectors.toList()); calories.add("Cooking will double calories!!!"); return calories; } } | MenuItem { public List<String> getCalory() { List<String> calories = ingredients.stream() .map(Ingredient::getCalory) .collect(Collectors.toList()); calories.add("Cooking will double calories!!!"); return calories; } MenuItem(List<Ingredient> ingredients); } | MenuItem { public List<String> getCalory() { List<String> calories = ingredients.stream() .map(Ingredient::getCalory) .collect(Collectors.toList()); calories.add("Cooking will double calories!!!"); return calories; } MenuItem(List<Ingredient> ingredients); void AddToPot(); void AddWater(); void AddOil(); void Smell(); void Taste(); void Cook(); List<Integer> getHealthRating(); List<String> getProtein(); List<String> getCalory(); } | MenuItem { public List<String> getCalory() { List<String> calories = ingredients.stream() .map(Ingredient::getCalory) .collect(Collectors.toList()); calories.add("Cooking will double calories!!!"); return calories; } MenuItem(List<Ingredient> ingredients); void AddToPot(); void AddWater(); void AddOil(); void Smell(); void Taste(); void Cook(); List<Integer> getHealthRating(); List<String> getProtein(); List<String> getCalory(); } |
@Test public void should_calc_health_rating_for_MenuItem() { assertEquals(2, moonCake.getHealthRating().size()); assertTrue(moonCake.getHealthRating().contains(1)); assertTrue(moonCake.getHealthRating().contains(2)); } | public List<Integer> getHealthRating() { return ingredients.stream() .map(Ingredient::getHealthRating) .collect(Collectors.toList()); } | MenuItem { public List<Integer> getHealthRating() { return ingredients.stream() .map(Ingredient::getHealthRating) .collect(Collectors.toList()); } } | MenuItem { public List<Integer> getHealthRating() { return ingredients.stream() .map(Ingredient::getHealthRating) .collect(Collectors.toList()); } MenuItem(List<Ingredient> ingredients); } | MenuItem { public List<Integer> getHealthRating() { return ingredients.stream() .map(Ingredient::getHealthRating) .collect(Collectors.toList()); } MenuItem(List<Ingredient> ingredients); void AddToPot(); void AddWater(); void AddOil(); void Smell(); void Taste(); void Cook(); List<Integer> getHealthRating(); List<String> getProtein(); List<String> getCalory(); } | MenuItem { public List<Integer> getHealthRating() { return ingredients.stream() .map(Ingredient::getHealthRating) .collect(Collectors.toList()); } MenuItem(List<Ingredient> ingredients); void AddToPot(); void AddWater(); void AddOil(); void Smell(); void Taste(); void Cook(); List<Integer> getHealthRating(); List<String> getProtein(); List<String> getCalory(); } |
@Test public void should_calc_protein_for_MenuItem() { assertEquals(2, moonCake.getProtein().size()); assertTrue(moonCake.getProtein().contains("100.0 g")); assertTrue(moonCake.getProtein().contains("200.0 g")); } | public List<String> getProtein() { return ingredients.stream() .map(Ingredient::getProtein) .collect(Collectors.toList()); } | MenuItem { public List<String> getProtein() { return ingredients.stream() .map(Ingredient::getProtein) .collect(Collectors.toList()); } } | MenuItem { public List<String> getProtein() { return ingredients.stream() .map(Ingredient::getProtein) .collect(Collectors.toList()); } MenuItem(List<Ingredient> ingredients); } | MenuItem { public List<String> getProtein() { return ingredients.stream() .map(Ingredient::getProtein) .collect(Collectors.toList()); } MenuItem(List<Ingredient> ingredients); void AddToPot(); void AddWater(); void AddOil(); void Smell(); void Taste(); void Cook(); List<Integer> getHealthRating(); List<String> getProtein(); List<String> getCalory(); } | MenuItem { public List<String> getProtein() { return ingredients.stream() .map(Ingredient::getProtein) .collect(Collectors.toList()); } MenuItem(List<Ingredient> ingredients); void AddToPot(); void AddWater(); void AddOil(); void Smell(); void Taste(); void Cook(); List<Integer> getHealthRating(); List<String> getProtein(); List<String> getCalory(); } |
@Test public void should_pay_5_when_buy_espresso_with_milk() { Espresso espresso = new Espresso(true, false); assertTrue(espresso.cost() == 5.0); } | public abstract double cost(); | Beverage { public abstract double cost(); } | Beverage { public abstract double cost(); protected Beverage(boolean milk, boolean mocha); } | Beverage { public abstract double cost(); protected Beverage(boolean milk, boolean mocha); boolean isMilk(); boolean isMocha(); String getDescription(); abstract double cost(); } | Beverage { public abstract double cost(); protected Beverage(boolean milk, boolean mocha); boolean isMilk(); boolean isMocha(); String getDescription(); abstract double cost(); } |
@Test public void should_calc_calory_for_MenuItem() { assertEquals(3, moonCake.getCalory().size()); assertTrue(moonCake.getCalory().contains("10 J")); assertTrue(moonCake.getCalory().contains("20 J")); assertTrue(moonCake.getCalory().contains("Cooking will double calories!!!")); } | public List<String> getCalory() { List<String> calories = ingredients.stream() .map(Ingredient::getCalory) .collect(Collectors.toList()); calories.add("Cooking will double calories!!!"); return calories; } | MenuItem { public List<String> getCalory() { List<String> calories = ingredients.stream() .map(Ingredient::getCalory) .collect(Collectors.toList()); calories.add("Cooking will double calories!!!"); return calories; } } | MenuItem { public List<String> getCalory() { List<String> calories = ingredients.stream() .map(Ingredient::getCalory) .collect(Collectors.toList()); calories.add("Cooking will double calories!!!"); return calories; } MenuItem(List<Ingredient> ingredients); } | MenuItem { public List<String> getCalory() { List<String> calories = ingredients.stream() .map(Ingredient::getCalory) .collect(Collectors.toList()); calories.add("Cooking will double calories!!!"); return calories; } MenuItem(List<Ingredient> ingredients); void AddToPot(); void AddWater(); void AddOil(); void Smell(); void Taste(); void Cook(); List<Integer> getHealthRating(); List<String> getProtein(); List<String> getCalory(); } | MenuItem { public List<String> getCalory() { List<String> calories = ingredients.stream() .map(Ingredient::getCalory) .collect(Collectors.toList()); calories.add("Cooking will double calories!!!"); return calories; } MenuItem(List<Ingredient> ingredients); void AddToPot(); void AddWater(); void AddOil(); void Smell(); void Taste(); void Cook(); List<Integer> getHealthRating(); List<String> getProtein(); List<String> getCalory(); } |
@Test public void should_get_alert_message_if_people_names_include_don() { List<String> peopleNames = Arrays.asList("Don", "Kent"); UsingReturn usingReturn = new UsingReturn(); String alertMessage = usingReturn.checkSecurity(peopleNames); assertEquals("AlertDon", alertMessage); } | public String checkSecurity(List<String> people) { String found = ""; for (String name : people) { if (found == "") { if (name.equals("Don")) { sendAlert(); found = "Don"; } if (name.equals("John")) { sendAlert(); found = "John"; } } } return someLaterCode(found); } | UsingReturn { public String checkSecurity(List<String> people) { String found = ""; for (String name : people) { if (found == "") { if (name.equals("Don")) { sendAlert(); found = "Don"; } if (name.equals("John")) { sendAlert(); found = "John"; } } } return someLaterCode(found); } } | UsingReturn { public String checkSecurity(List<String> people) { String found = ""; for (String name : people) { if (found == "") { if (name.equals("Don")) { sendAlert(); found = "Don"; } if (name.equals("John")) { sendAlert(); found = "John"; } } } return someLaterCode(found); } } | UsingReturn { public String checkSecurity(List<String> people) { String found = ""; for (String name : people) { if (found == "") { if (name.equals("Don")) { sendAlert(); found = "Don"; } if (name.equals("John")) { sendAlert(); found = "John"; } } } return someLaterCode(found); } String checkSecurity(List<String> people); } | UsingReturn { public String checkSecurity(List<String> people) { String found = ""; for (String name : people) { if (found == "") { if (name.equals("Don")) { sendAlert(); found = "Don"; } if (name.equals("John")) { sendAlert(); found = "John"; } } } return someLaterCode(found); } String checkSecurity(List<String> people); } |
@Test public void should_get_alert_message_if_people_names_include_john() { List<String> peopleNames = Arrays.asList("John", "Kent"); UsingReturn usingReturn = new UsingReturn(); String alertMessage = usingReturn.checkSecurity(peopleNames); assertEquals("AlertJohn", alertMessage); } | public String checkSecurity(List<String> people) { String found = ""; for (String name : people) { if (found == "") { if (name.equals("Don")) { sendAlert(); found = "Don"; } if (name.equals("John")) { sendAlert(); found = "John"; } } } return someLaterCode(found); } | UsingReturn { public String checkSecurity(List<String> people) { String found = ""; for (String name : people) { if (found == "") { if (name.equals("Don")) { sendAlert(); found = "Don"; } if (name.equals("John")) { sendAlert(); found = "John"; } } } return someLaterCode(found); } } | UsingReturn { public String checkSecurity(List<String> people) { String found = ""; for (String name : people) { if (found == "") { if (name.equals("Don")) { sendAlert(); found = "Don"; } if (name.equals("John")) { sendAlert(); found = "John"; } } } return someLaterCode(found); } } | UsingReturn { public String checkSecurity(List<String> people) { String found = ""; for (String name : people) { if (found == "") { if (name.equals("Don")) { sendAlert(); found = "Don"; } if (name.equals("John")) { sendAlert(); found = "John"; } } } return someLaterCode(found); } String checkSecurity(List<String> people); } | UsingReturn { public String checkSecurity(List<String> people) { String found = ""; for (String name : people) { if (found == "") { if (name.equals("Don")) { sendAlert(); found = "Don"; } if (name.equals("John")) { sendAlert(); found = "John"; } } } return someLaterCode(found); } String checkSecurity(List<String> people); } |
@Test public void should_alert_first_matched_people() { List<String> peopleNames = Arrays.asList("John", "Don"); UsingReturn usingReturn = new UsingReturn(); String alertMessage = usingReturn.checkSecurity(peopleNames); assertEquals("AlertJohn", alertMessage); } | public String checkSecurity(List<String> people) { String found = ""; for (String name : people) { if (found == "") { if (name.equals("Don")) { sendAlert(); found = "Don"; } if (name.equals("John")) { sendAlert(); found = "John"; } } } return someLaterCode(found); } | UsingReturn { public String checkSecurity(List<String> people) { String found = ""; for (String name : people) { if (found == "") { if (name.equals("Don")) { sendAlert(); found = "Don"; } if (name.equals("John")) { sendAlert(); found = "John"; } } } return someLaterCode(found); } } | UsingReturn { public String checkSecurity(List<String> people) { String found = ""; for (String name : people) { if (found == "") { if (name.equals("Don")) { sendAlert(); found = "Don"; } if (name.equals("John")) { sendAlert(); found = "John"; } } } return someLaterCode(found); } } | UsingReturn { public String checkSecurity(List<String> people) { String found = ""; for (String name : people) { if (found == "") { if (name.equals("Don")) { sendAlert(); found = "Don"; } if (name.equals("John")) { sendAlert(); found = "John"; } } } return someLaterCode(found); } String checkSecurity(List<String> people); } | UsingReturn { public String checkSecurity(List<String> people) { String found = ""; for (String name : people) { if (found == "") { if (name.equals("Don")) { sendAlert(); found = "Don"; } if (name.equals("John")) { sendAlert(); found = "John"; } } } return someLaterCode(found); } String checkSecurity(List<String> people); } |
@Test public void should_not_get_alert_message_if_people_names_does_include_don_and_john() { List<String> peopleNames = Arrays.asList("Martin", "Kent"); UsingReturn usingReturn = new UsingReturn(); String alertMessage = usingReturn.checkSecurity(peopleNames); assertEquals("", alertMessage); } | public String checkSecurity(List<String> people) { String found = ""; for (String name : people) { if (found == "") { if (name.equals("Don")) { sendAlert(); found = "Don"; } if (name.equals("John")) { sendAlert(); found = "John"; } } } return someLaterCode(found); } | UsingReturn { public String checkSecurity(List<String> people) { String found = ""; for (String name : people) { if (found == "") { if (name.equals("Don")) { sendAlert(); found = "Don"; } if (name.equals("John")) { sendAlert(); found = "John"; } } } return someLaterCode(found); } } | UsingReturn { public String checkSecurity(List<String> people) { String found = ""; for (String name : people) { if (found == "") { if (name.equals("Don")) { sendAlert(); found = "Don"; } if (name.equals("John")) { sendAlert(); found = "John"; } } } return someLaterCode(found); } } | UsingReturn { public String checkSecurity(List<String> people) { String found = ""; for (String name : people) { if (found == "") { if (name.equals("Don")) { sendAlert(); found = "Don"; } if (name.equals("John")) { sendAlert(); found = "John"; } } } return someLaterCode(found); } String checkSecurity(List<String> people); } | UsingReturn { public String checkSecurity(List<String> people) { String found = ""; for (String name : people) { if (found == "") { if (name.equals("Don")) { sendAlert(); found = "Don"; } if (name.equals("John")) { sendAlert(); found = "John"; } } } return someLaterCode(found); } String checkSecurity(List<String> people); } |
@Test public void should_get_zero_disability_amount_given_seniority_less_than_two() { OrsExample consolidateConditionalExpression = new OrsExample(1, 0, false); assertEquals(0, consolidateConditionalExpression.disabilityAmount(), 0); } | public double disabilityAmount() { if (seniority < 2) return 0; if (monthsDisabled > 12) return 0; if (isPartTime) return 0; return disabilityAmount; } | OrsExample { public double disabilityAmount() { if (seniority < 2) return 0; if (monthsDisabled > 12) return 0; if (isPartTime) return 0; return disabilityAmount; } } | OrsExample { public double disabilityAmount() { if (seniority < 2) return 0; if (monthsDisabled > 12) return 0; if (isPartTime) return 0; return disabilityAmount; } OrsExample(double seniority, double monthsDisabled, boolean isPartTime); } | OrsExample { public double disabilityAmount() { if (seniority < 2) return 0; if (monthsDisabled > 12) return 0; if (isPartTime) return 0; return disabilityAmount; } OrsExample(double seniority, double monthsDisabled, boolean isPartTime); double disabilityAmount(); } | OrsExample { public double disabilityAmount() { if (seniority < 2) return 0; if (monthsDisabled > 12) return 0; if (isPartTime) return 0; return disabilityAmount; } OrsExample(double seniority, double monthsDisabled, boolean isPartTime); double disabilityAmount(); } |
@Test public void should_get_zero_disability_amount_given_month_disabled_more_than_12() { OrsExample consolidateConditionalExpression = new OrsExample(2, 13, false); assertEquals(0, consolidateConditionalExpression.disabilityAmount(), 0); } | public double disabilityAmount() { if (seniority < 2) return 0; if (monthsDisabled > 12) return 0; if (isPartTime) return 0; return disabilityAmount; } | OrsExample { public double disabilityAmount() { if (seniority < 2) return 0; if (monthsDisabled > 12) return 0; if (isPartTime) return 0; return disabilityAmount; } } | OrsExample { public double disabilityAmount() { if (seniority < 2) return 0; if (monthsDisabled > 12) return 0; if (isPartTime) return 0; return disabilityAmount; } OrsExample(double seniority, double monthsDisabled, boolean isPartTime); } | OrsExample { public double disabilityAmount() { if (seniority < 2) return 0; if (monthsDisabled > 12) return 0; if (isPartTime) return 0; return disabilityAmount; } OrsExample(double seniority, double monthsDisabled, boolean isPartTime); double disabilityAmount(); } | OrsExample { public double disabilityAmount() { if (seniority < 2) return 0; if (monthsDisabled > 12) return 0; if (isPartTime) return 0; return disabilityAmount; } OrsExample(double seniority, double monthsDisabled, boolean isPartTime); double disabilityAmount(); } |
@Test public void should_get_zero_disability_amount_given_is_part_time() { OrsExample consolidateConditionalExpression = new OrsExample(2, 1, true); assertEquals(0, consolidateConditionalExpression.disabilityAmount(), 0); } | public double disabilityAmount() { if (seniority < 2) return 0; if (monthsDisabled > 12) return 0; if (isPartTime) return 0; return disabilityAmount; } | OrsExample { public double disabilityAmount() { if (seniority < 2) return 0; if (monthsDisabled > 12) return 0; if (isPartTime) return 0; return disabilityAmount; } } | OrsExample { public double disabilityAmount() { if (seniority < 2) return 0; if (monthsDisabled > 12) return 0; if (isPartTime) return 0; return disabilityAmount; } OrsExample(double seniority, double monthsDisabled, boolean isPartTime); } | OrsExample { public double disabilityAmount() { if (seniority < 2) return 0; if (monthsDisabled > 12) return 0; if (isPartTime) return 0; return disabilityAmount; } OrsExample(double seniority, double monthsDisabled, boolean isPartTime); double disabilityAmount(); } | OrsExample { public double disabilityAmount() { if (seniority < 2) return 0; if (monthsDisabled > 12) return 0; if (isPartTime) return 0; return disabilityAmount; } OrsExample(double seniority, double monthsDisabled, boolean isPartTime); double disabilityAmount(); } |
@Test public void should_get_ten_disability_amount_given_seniority_greater_than_one_and_disabled_less_than_13_and_is_not_part_time() { OrsExample consolidateConditionalExpression = new OrsExample(2, 1, false); assertEquals(10, consolidateConditionalExpression.disabilityAmount(), 0); } | public double disabilityAmount() { if (seniority < 2) return 0; if (monthsDisabled > 12) return 0; if (isPartTime) return 0; return disabilityAmount; } | OrsExample { public double disabilityAmount() { if (seniority < 2) return 0; if (monthsDisabled > 12) return 0; if (isPartTime) return 0; return disabilityAmount; } } | OrsExample { public double disabilityAmount() { if (seniority < 2) return 0; if (monthsDisabled > 12) return 0; if (isPartTime) return 0; return disabilityAmount; } OrsExample(double seniority, double monthsDisabled, boolean isPartTime); } | OrsExample { public double disabilityAmount() { if (seniority < 2) return 0; if (monthsDisabled > 12) return 0; if (isPartTime) return 0; return disabilityAmount; } OrsExample(double seniority, double monthsDisabled, boolean isPartTime); double disabilityAmount(); } | OrsExample { public double disabilityAmount() { if (seniority < 2) return 0; if (monthsDisabled > 12) return 0; if (isPartTime) return 0; return disabilityAmount; } OrsExample(double seniority, double monthsDisabled, boolean isPartTime); double disabilityAmount(); } |
@Test public void should_get_1_given_is_on_vacation_and_length_of_service_greater_than_10() { AndsExample andsExample = new AndsExample(11, true); assertEquals(1, andsExample.getCharge(), 0); } | public double getCharge() { if (onVacation()) if (lengthOfService() > 10) return 1; return 0.5; } | AndsExample { public double getCharge() { if (onVacation()) if (lengthOfService() > 10) return 1; return 0.5; } } | AndsExample { public double getCharge() { if (onVacation()) if (lengthOfService() > 10) return 1; return 0.5; } AndsExample(double lengthOfService, boolean onVacation); } | AndsExample { public double getCharge() { if (onVacation()) if (lengthOfService() > 10) return 1; return 0.5; } AndsExample(double lengthOfService, boolean onVacation); double getCharge(); } | AndsExample { public double getCharge() { if (onVacation()) if (lengthOfService() > 10) return 1; return 0.5; } AndsExample(double lengthOfService, boolean onVacation); double getCharge(); } |
@Test public void should_pay_7_when_buy_espresso_with_mocha() { Espresso espresso = new Espresso(false, true); assertTrue(espresso.cost() == 7.0); } | public abstract double cost(); | Beverage { public abstract double cost(); } | Beverage { public abstract double cost(); protected Beverage(boolean milk, boolean mocha); } | Beverage { public abstract double cost(); protected Beverage(boolean milk, boolean mocha); boolean isMilk(); boolean isMocha(); String getDescription(); abstract double cost(); } | Beverage { public abstract double cost(); protected Beverage(boolean milk, boolean mocha); boolean isMilk(); boolean isMocha(); String getDescription(); abstract double cost(); } |
@Test public void should_get_point_5_given_is_not_on_vacation() { AndsExample andsExample = new AndsExample(11, false); assertEquals(0.5, andsExample.getCharge(), 0); } | public double getCharge() { if (onVacation()) if (lengthOfService() > 10) return 1; return 0.5; } | AndsExample { public double getCharge() { if (onVacation()) if (lengthOfService() > 10) return 1; return 0.5; } } | AndsExample { public double getCharge() { if (onVacation()) if (lengthOfService() > 10) return 1; return 0.5; } AndsExample(double lengthOfService, boolean onVacation); } | AndsExample { public double getCharge() { if (onVacation()) if (lengthOfService() > 10) return 1; return 0.5; } AndsExample(double lengthOfService, boolean onVacation); double getCharge(); } | AndsExample { public double getCharge() { if (onVacation()) if (lengthOfService() > 10) return 1; return 0.5; } AndsExample(double lengthOfService, boolean onVacation); double getCharge(); } |
@Test public void should_get_point_5_given_length_of_service_not_greater_than_10() { AndsExample andsExample = new AndsExample(5, true); assertEquals(0.5, andsExample.getCharge(), 0); } | public double getCharge() { if (onVacation()) if (lengthOfService() > 10) return 1; return 0.5; } | AndsExample { public double getCharge() { if (onVacation()) if (lengthOfService() > 10) return 1; return 0.5; } } | AndsExample { public double getCharge() { if (onVacation()) if (lengthOfService() > 10) return 1; return 0.5; } AndsExample(double lengthOfService, boolean onVacation); } | AndsExample { public double getCharge() { if (onVacation()) if (lengthOfService() > 10) return 1; return 0.5; } AndsExample(double lengthOfService, boolean onVacation); double getCharge(); } | AndsExample { public double getCharge() { if (onVacation()) if (lengthOfService() > 10) return 1; return 0.5; } AndsExample(double lengthOfService, boolean onVacation); double getCharge(); } |
@Test public void should_get_disability_amount_given_is_special_deal() { ConsolidateDuplicateConditionalFragments consolidateDuplicateConditionalFragments = new ConsolidateDuplicateConditionalFragments(true, 10); assertEquals(10.5, consolidateDuplicateConditionalFragments.disabilityAmount(), 0); } | public double disabilityAmount() { if (isSpecialDeal()) { total = price * 0.95; send(); } else { total = price * 0.98; send(); } return total; } | ConsolidateDuplicateConditionalFragments { public double disabilityAmount() { if (isSpecialDeal()) { total = price * 0.95; send(); } else { total = price * 0.98; send(); } return total; } } | ConsolidateDuplicateConditionalFragments { public double disabilityAmount() { if (isSpecialDeal()) { total = price * 0.95; send(); } else { total = price * 0.98; send(); } return total; } ConsolidateDuplicateConditionalFragments(boolean isSpecialDeal, double price); } | ConsolidateDuplicateConditionalFragments { public double disabilityAmount() { if (isSpecialDeal()) { total = price * 0.95; send(); } else { total = price * 0.98; send(); } return total; } ConsolidateDuplicateConditionalFragments(boolean isSpecialDeal, double price); double disabilityAmount(); } | ConsolidateDuplicateConditionalFragments { public double disabilityAmount() { if (isSpecialDeal()) { total = price * 0.95; send(); } else { total = price * 0.98; send(); } return total; } ConsolidateDuplicateConditionalFragments(boolean isSpecialDeal, double price); double disabilityAmount(); } |
@Test public void should_get_zero_disability_amount_given_month_disabled_more_than_12() { ConsolidateDuplicateConditionalFragments consolidateDuplicateConditionalFragments = new ConsolidateDuplicateConditionalFragments(false, 10); assertEquals(10.8, consolidateDuplicateConditionalFragments.disabilityAmount(), 0); } | public double disabilityAmount() { if (isSpecialDeal()) { total = price * 0.95; send(); } else { total = price * 0.98; send(); } return total; } | ConsolidateDuplicateConditionalFragments { public double disabilityAmount() { if (isSpecialDeal()) { total = price * 0.95; send(); } else { total = price * 0.98; send(); } return total; } } | ConsolidateDuplicateConditionalFragments { public double disabilityAmount() { if (isSpecialDeal()) { total = price * 0.95; send(); } else { total = price * 0.98; send(); } return total; } ConsolidateDuplicateConditionalFragments(boolean isSpecialDeal, double price); } | ConsolidateDuplicateConditionalFragments { public double disabilityAmount() { if (isSpecialDeal()) { total = price * 0.95; send(); } else { total = price * 0.98; send(); } return total; } ConsolidateDuplicateConditionalFragments(boolean isSpecialDeal, double price); double disabilityAmount(); } | ConsolidateDuplicateConditionalFragments { public double disabilityAmount() { if (isSpecialDeal()) { total = price * 0.95; send(); } else { total = price * 0.98; send(); } return total; } ConsolidateDuplicateConditionalFragments(boolean isSpecialDeal, double price); double disabilityAmount(); } |
@Test public void should_get_summer_charge_given_date_is_in_summer() { ChargeCalculator chargeCalculator = new ChargeCalculator(); double charge = chargeCalculator.getCharge(new Date(2011, 7, 1), 100); assertEquals(200, charge, 0); } | public double getCharge(Date date, double quantity) { double charge; if (date.before(SUMMER_START) || date.after(SUMMER_END)) charge = quantity * winterRate + winterServiceCharge; else charge = quantity * summerRate; return charge; } | ChargeCalculator { public double getCharge(Date date, double quantity) { double charge; if (date.before(SUMMER_START) || date.after(SUMMER_END)) charge = quantity * winterRate + winterServiceCharge; else charge = quantity * summerRate; return charge; } } | ChargeCalculator { public double getCharge(Date date, double quantity) { double charge; if (date.before(SUMMER_START) || date.after(SUMMER_END)) charge = quantity * winterRate + winterServiceCharge; else charge = quantity * summerRate; return charge; } } | ChargeCalculator { public double getCharge(Date date, double quantity) { double charge; if (date.before(SUMMER_START) || date.after(SUMMER_END)) charge = quantity * winterRate + winterServiceCharge; else charge = quantity * summerRate; return charge; } double getCharge(Date date, double quantity); } | ChargeCalculator { public double getCharge(Date date, double quantity) { double charge; if (date.before(SUMMER_START) || date.after(SUMMER_END)) charge = quantity * winterRate + winterServiceCharge; else charge = quantity * summerRate; return charge; } double getCharge(Date date, double quantity); } |
@Test public void should_get_winter_charge_given_date_is_not_in_summer() { ChargeCalculator chargeCalculator = new ChargeCalculator(); double charge = chargeCalculator.getCharge(new Date(2011, 11, 1), 100); assertEquals(400, charge, 0); } | public double getCharge(Date date, double quantity) { double charge; if (date.before(SUMMER_START) || date.after(SUMMER_END)) charge = quantity * winterRate + winterServiceCharge; else charge = quantity * summerRate; return charge; } | ChargeCalculator { public double getCharge(Date date, double quantity) { double charge; if (date.before(SUMMER_START) || date.after(SUMMER_END)) charge = quantity * winterRate + winterServiceCharge; else charge = quantity * summerRate; return charge; } } | ChargeCalculator { public double getCharge(Date date, double quantity) { double charge; if (date.before(SUMMER_START) || date.after(SUMMER_END)) charge = quantity * winterRate + winterServiceCharge; else charge = quantity * summerRate; return charge; } } | ChargeCalculator { public double getCharge(Date date, double quantity) { double charge; if (date.before(SUMMER_START) || date.after(SUMMER_END)) charge = quantity * winterRate + winterServiceCharge; else charge = quantity * summerRate; return charge; } double getCharge(Date date, double quantity); } | ChargeCalculator { public double getCharge(Date date, double quantity) { double charge; if (date.before(SUMMER_START) || date.after(SUMMER_END)) charge = quantity * winterRate + winterServiceCharge; else charge = quantity * summerRate; return charge; } double getCharge(Date date, double quantity); } |
@Test public void should_get_basic_statement_given_does_not_have_customer() { Site site = new Site(null); Client client = new Client(site); assertEquals("Basic Plan occupant 0", client.getStatement()); } | public String getStatement() { String plan = customer() == null ? "Basic Plan" : customer().getPlan(); String customerName = customer() == null ? "occupant" : customer().getName(); int weeksDelinquent = customer() == null ? 0 : customer().getWeeksDelinquentInLastYear(); return plan + " " + customerName + " " + weeksDelinquent; } | Client { public String getStatement() { String plan = customer() == null ? "Basic Plan" : customer().getPlan(); String customerName = customer() == null ? "occupant" : customer().getName(); int weeksDelinquent = customer() == null ? 0 : customer().getWeeksDelinquentInLastYear(); return plan + " " + customerName + " " + weeksDelinquent; } } | Client { public String getStatement() { String plan = customer() == null ? "Basic Plan" : customer().getPlan(); String customerName = customer() == null ? "occupant" : customer().getName(); int weeksDelinquent = customer() == null ? 0 : customer().getWeeksDelinquentInLastYear(); return plan + " " + customerName + " " + weeksDelinquent; } Client(Site site); } | Client { public String getStatement() { String plan = customer() == null ? "Basic Plan" : customer().getPlan(); String customerName = customer() == null ? "occupant" : customer().getName(); int weeksDelinquent = customer() == null ? 0 : customer().getWeeksDelinquentInLastYear(); return plan + " " + customerName + " " + weeksDelinquent; } Client(Site site); String getStatement(); } | Client { public String getStatement() { String plan = customer() == null ? "Basic Plan" : customer().getPlan(); String customerName = customer() == null ? "occupant" : customer().getName(); int weeksDelinquent = customer() == null ? 0 : customer().getWeeksDelinquentInLastYear(); return plan + " " + customerName + " " + weeksDelinquent; } Client(Site site); String getStatement(); } |
@Test public void should_get_customer_statement_given_has_customer() { Site site = new Site(new Customer()); Client client = new Client(site); assertEquals("Real Plan Name 100", client.getStatement()); } | public String getStatement() { String plan = customer() == null ? "Basic Plan" : customer().getPlan(); String customerName = customer() == null ? "occupant" : customer().getName(); int weeksDelinquent = customer() == null ? 0 : customer().getWeeksDelinquentInLastYear(); return plan + " " + customerName + " " + weeksDelinquent; } | Client { public String getStatement() { String plan = customer() == null ? "Basic Plan" : customer().getPlan(); String customerName = customer() == null ? "occupant" : customer().getName(); int weeksDelinquent = customer() == null ? 0 : customer().getWeeksDelinquentInLastYear(); return plan + " " + customerName + " " + weeksDelinquent; } } | Client { public String getStatement() { String plan = customer() == null ? "Basic Plan" : customer().getPlan(); String customerName = customer() == null ? "occupant" : customer().getName(); int weeksDelinquent = customer() == null ? 0 : customer().getWeeksDelinquentInLastYear(); return plan + " " + customerName + " " + weeksDelinquent; } Client(Site site); } | Client { public String getStatement() { String plan = customer() == null ? "Basic Plan" : customer().getPlan(); String customerName = customer() == null ? "occupant" : customer().getName(); int weeksDelinquent = customer() == null ? 0 : customer().getWeeksDelinquentInLastYear(); return plan + " " + customerName + " " + weeksDelinquent; } Client(Site site); String getStatement(); } | Client { public String getStatement() { String plan = customer() == null ? "Basic Plan" : customer().getPlan(); String customerName = customer() == null ? "occupant" : customer().getName(); int weeksDelinquent = customer() == null ? 0 : customer().getWeeksDelinquentInLastYear(); return plan + " " + customerName + " " + weeksDelinquent; } Client(Site site); String getStatement(); } |
@Test public void should_get_pay_amount_for_engineer_given_type_is_engineer() throws Exception { Employee employee = new Employee(EmployeeType.ENGINEER); assertEquals(100, employee.payAmount()); } | public int payAmount() throws Exception { switch (employeeType.getEmployeeCode()) { case EmployeeType.ENGINEER: return MonthlySalary; case EmployeeType.SALESMAN: return MonthlySalary + Commission; case EmployeeType.MANAGER: return MonthlySalary + Bonus; default: throw new Exception(); } } | Employee { public int payAmount() throws Exception { switch (employeeType.getEmployeeCode()) { case EmployeeType.ENGINEER: return MonthlySalary; case EmployeeType.SALESMAN: return MonthlySalary + Commission; case EmployeeType.MANAGER: return MonthlySalary + Bonus; default: throw new Exception(); } } } | Employee { public int payAmount() throws Exception { switch (employeeType.getEmployeeCode()) { case EmployeeType.ENGINEER: return MonthlySalary; case EmployeeType.SALESMAN: return MonthlySalary + Commission; case EmployeeType.MANAGER: return MonthlySalary + Bonus; default: throw new Exception(); } } Employee(int type); } | Employee { public int payAmount() throws Exception { switch (employeeType.getEmployeeCode()) { case EmployeeType.ENGINEER: return MonthlySalary; case EmployeeType.SALESMAN: return MonthlySalary + Commission; case EmployeeType.MANAGER: return MonthlySalary + Bonus; default: throw new Exception(); } } Employee(int type); int payAmount(); } | Employee { public int payAmount() throws Exception { switch (employeeType.getEmployeeCode()) { case EmployeeType.ENGINEER: return MonthlySalary; case EmployeeType.SALESMAN: return MonthlySalary + Commission; case EmployeeType.MANAGER: return MonthlySalary + Bonus; default: throw new Exception(); } } Employee(int type); int payAmount(); } |
@Test public void should_get_pay_amount_for_sales_man_given_type_is_sales_man() throws Exception { Employee employee = new Employee(EmployeeType.SALESMAN); assertEquals(120, employee.payAmount()); } | public int payAmount() throws Exception { switch (employeeType.getEmployeeCode()) { case EmployeeType.ENGINEER: return MonthlySalary; case EmployeeType.SALESMAN: return MonthlySalary + Commission; case EmployeeType.MANAGER: return MonthlySalary + Bonus; default: throw new Exception(); } } | Employee { public int payAmount() throws Exception { switch (employeeType.getEmployeeCode()) { case EmployeeType.ENGINEER: return MonthlySalary; case EmployeeType.SALESMAN: return MonthlySalary + Commission; case EmployeeType.MANAGER: return MonthlySalary + Bonus; default: throw new Exception(); } } } | Employee { public int payAmount() throws Exception { switch (employeeType.getEmployeeCode()) { case EmployeeType.ENGINEER: return MonthlySalary; case EmployeeType.SALESMAN: return MonthlySalary + Commission; case EmployeeType.MANAGER: return MonthlySalary + Bonus; default: throw new Exception(); } } Employee(int type); } | Employee { public int payAmount() throws Exception { switch (employeeType.getEmployeeCode()) { case EmployeeType.ENGINEER: return MonthlySalary; case EmployeeType.SALESMAN: return MonthlySalary + Commission; case EmployeeType.MANAGER: return MonthlySalary + Bonus; default: throw new Exception(); } } Employee(int type); int payAmount(); } | Employee { public int payAmount() throws Exception { switch (employeeType.getEmployeeCode()) { case EmployeeType.ENGINEER: return MonthlySalary; case EmployeeType.SALESMAN: return MonthlySalary + Commission; case EmployeeType.MANAGER: return MonthlySalary + Bonus; default: throw new Exception(); } } Employee(int type); int payAmount(); } |
@Test public void should_pay_8_when_buy_espresso_with_milk_and_mocha() { Espresso espresso = new Espresso(true, true); assertTrue(espresso.cost() == 8.0); } | public abstract double cost(); | Beverage { public abstract double cost(); } | Beverage { public abstract double cost(); protected Beverage(boolean milk, boolean mocha); } | Beverage { public abstract double cost(); protected Beverage(boolean milk, boolean mocha); boolean isMilk(); boolean isMocha(); String getDescription(); abstract double cost(); } | Beverage { public abstract double cost(); protected Beverage(boolean milk, boolean mocha); boolean isMilk(); boolean isMocha(); String getDescription(); abstract double cost(); } |
@Test public void should_get_pay_amount_for_manager_given_type_is_manager() throws Exception { Employee employee = new Employee(EmployeeType.MANAGER); assertEquals(150, employee.payAmount()); } | public int payAmount() throws Exception { switch (employeeType.getEmployeeCode()) { case EmployeeType.ENGINEER: return MonthlySalary; case EmployeeType.SALESMAN: return MonthlySalary + Commission; case EmployeeType.MANAGER: return MonthlySalary + Bonus; default: throw new Exception(); } } | Employee { public int payAmount() throws Exception { switch (employeeType.getEmployeeCode()) { case EmployeeType.ENGINEER: return MonthlySalary; case EmployeeType.SALESMAN: return MonthlySalary + Commission; case EmployeeType.MANAGER: return MonthlySalary + Bonus; default: throw new Exception(); } } } | Employee { public int payAmount() throws Exception { switch (employeeType.getEmployeeCode()) { case EmployeeType.ENGINEER: return MonthlySalary; case EmployeeType.SALESMAN: return MonthlySalary + Commission; case EmployeeType.MANAGER: return MonthlySalary + Bonus; default: throw new Exception(); } } Employee(int type); } | Employee { public int payAmount() throws Exception { switch (employeeType.getEmployeeCode()) { case EmployeeType.ENGINEER: return MonthlySalary; case EmployeeType.SALESMAN: return MonthlySalary + Commission; case EmployeeType.MANAGER: return MonthlySalary + Bonus; default: throw new Exception(); } } Employee(int type); int payAmount(); } | Employee { public int payAmount() throws Exception { switch (employeeType.getEmployeeCode()) { case EmployeeType.ENGINEER: return MonthlySalary; case EmployeeType.SALESMAN: return MonthlySalary + Commission; case EmployeeType.MANAGER: return MonthlySalary + Bonus; default: throw new Exception(); } } Employee(int type); int payAmount(); } |
@Test public void should_get_dead_amount_pay_given_is_dead() { ReplaceNestedConditionalWithGuardClauses replaceNestedConditionalWithGuardClauses = new ReplaceNestedConditionalWithGuardClauses(true, false, false); assertEquals(400, replaceNestedConditionalWithGuardClauses.getPayAmount(), 0); } | public double getPayAmount() { double result; if (isDead) result = deadAmount(); else { if (isSeparated) result = separatedAmount(); else { if (isRetired) result = retiredAmount(); else result = normalPayAmount(); } } return result; } | ReplaceNestedConditionalWithGuardClauses { public double getPayAmount() { double result; if (isDead) result = deadAmount(); else { if (isSeparated) result = separatedAmount(); else { if (isRetired) result = retiredAmount(); else result = normalPayAmount(); } } return result; } } | ReplaceNestedConditionalWithGuardClauses { public double getPayAmount() { double result; if (isDead) result = deadAmount(); else { if (isSeparated) result = separatedAmount(); else { if (isRetired) result = retiredAmount(); else result = normalPayAmount(); } } return result; } ReplaceNestedConditionalWithGuardClauses(boolean isDead, boolean isSeparated, boolean isRetired); } | ReplaceNestedConditionalWithGuardClauses { public double getPayAmount() { double result; if (isDead) result = deadAmount(); else { if (isSeparated) result = separatedAmount(); else { if (isRetired) result = retiredAmount(); else result = normalPayAmount(); } } return result; } ReplaceNestedConditionalWithGuardClauses(boolean isDead, boolean isSeparated, boolean isRetired); double getPayAmount(); } | ReplaceNestedConditionalWithGuardClauses { public double getPayAmount() { double result; if (isDead) result = deadAmount(); else { if (isSeparated) result = separatedAmount(); else { if (isRetired) result = retiredAmount(); else result = normalPayAmount(); } } return result; } ReplaceNestedConditionalWithGuardClauses(boolean isDead, boolean isSeparated, boolean isRetired); double getPayAmount(); } |
@Test public void should_get_separated_amount_pay_given_is_separated_and_not_dead() { ReplaceNestedConditionalWithGuardClauses replaceNestedConditionalWithGuardClauses = new ReplaceNestedConditionalWithGuardClauses(false, true, false); assertEquals(300, replaceNestedConditionalWithGuardClauses.getPayAmount(), 0); } | public double getPayAmount() { double result; if (isDead) result = deadAmount(); else { if (isSeparated) result = separatedAmount(); else { if (isRetired) result = retiredAmount(); else result = normalPayAmount(); } } return result; } | ReplaceNestedConditionalWithGuardClauses { public double getPayAmount() { double result; if (isDead) result = deadAmount(); else { if (isSeparated) result = separatedAmount(); else { if (isRetired) result = retiredAmount(); else result = normalPayAmount(); } } return result; } } | ReplaceNestedConditionalWithGuardClauses { public double getPayAmount() { double result; if (isDead) result = deadAmount(); else { if (isSeparated) result = separatedAmount(); else { if (isRetired) result = retiredAmount(); else result = normalPayAmount(); } } return result; } ReplaceNestedConditionalWithGuardClauses(boolean isDead, boolean isSeparated, boolean isRetired); } | ReplaceNestedConditionalWithGuardClauses { public double getPayAmount() { double result; if (isDead) result = deadAmount(); else { if (isSeparated) result = separatedAmount(); else { if (isRetired) result = retiredAmount(); else result = normalPayAmount(); } } return result; } ReplaceNestedConditionalWithGuardClauses(boolean isDead, boolean isSeparated, boolean isRetired); double getPayAmount(); } | ReplaceNestedConditionalWithGuardClauses { public double getPayAmount() { double result; if (isDead) result = deadAmount(); else { if (isSeparated) result = separatedAmount(); else { if (isRetired) result = retiredAmount(); else result = normalPayAmount(); } } return result; } ReplaceNestedConditionalWithGuardClauses(boolean isDead, boolean isSeparated, boolean isRetired); double getPayAmount(); } |
@Test public void should_get_separated_amount_pay_given_is_retired_and_not_dead_and_not_seperated() { ReplaceNestedConditionalWithGuardClauses replaceNestedConditionalWithGuardClauses = new ReplaceNestedConditionalWithGuardClauses(false, false, true); assertEquals(200, replaceNestedConditionalWithGuardClauses.getPayAmount(), 0); } | public double getPayAmount() { double result; if (isDead) result = deadAmount(); else { if (isSeparated) result = separatedAmount(); else { if (isRetired) result = retiredAmount(); else result = normalPayAmount(); } } return result; } | ReplaceNestedConditionalWithGuardClauses { public double getPayAmount() { double result; if (isDead) result = deadAmount(); else { if (isSeparated) result = separatedAmount(); else { if (isRetired) result = retiredAmount(); else result = normalPayAmount(); } } return result; } } | ReplaceNestedConditionalWithGuardClauses { public double getPayAmount() { double result; if (isDead) result = deadAmount(); else { if (isSeparated) result = separatedAmount(); else { if (isRetired) result = retiredAmount(); else result = normalPayAmount(); } } return result; } ReplaceNestedConditionalWithGuardClauses(boolean isDead, boolean isSeparated, boolean isRetired); } | ReplaceNestedConditionalWithGuardClauses { public double getPayAmount() { double result; if (isDead) result = deadAmount(); else { if (isSeparated) result = separatedAmount(); else { if (isRetired) result = retiredAmount(); else result = normalPayAmount(); } } return result; } ReplaceNestedConditionalWithGuardClauses(boolean isDead, boolean isSeparated, boolean isRetired); double getPayAmount(); } | ReplaceNestedConditionalWithGuardClauses { public double getPayAmount() { double result; if (isDead) result = deadAmount(); else { if (isSeparated) result = separatedAmount(); else { if (isRetired) result = retiredAmount(); else result = normalPayAmount(); } } return result; } ReplaceNestedConditionalWithGuardClauses(boolean isDead, boolean isSeparated, boolean isRetired); double getPayAmount(); } |
@Test public void should_get_normal_amount_pay_given_is_not_retired_and_not_dead_and_not_seperated() { ReplaceNestedConditionalWithGuardClauses replaceNestedConditionalWithGuardClauses = new ReplaceNestedConditionalWithGuardClauses(false, false, false); assertEquals(100, replaceNestedConditionalWithGuardClauses.getPayAmount(), 0); } | public double getPayAmount() { double result; if (isDead) result = deadAmount(); else { if (isSeparated) result = separatedAmount(); else { if (isRetired) result = retiredAmount(); else result = normalPayAmount(); } } return result; } | ReplaceNestedConditionalWithGuardClauses { public double getPayAmount() { double result; if (isDead) result = deadAmount(); else { if (isSeparated) result = separatedAmount(); else { if (isRetired) result = retiredAmount(); else result = normalPayAmount(); } } return result; } } | ReplaceNestedConditionalWithGuardClauses { public double getPayAmount() { double result; if (isDead) result = deadAmount(); else { if (isSeparated) result = separatedAmount(); else { if (isRetired) result = retiredAmount(); else result = normalPayAmount(); } } return result; } ReplaceNestedConditionalWithGuardClauses(boolean isDead, boolean isSeparated, boolean isRetired); } | ReplaceNestedConditionalWithGuardClauses { public double getPayAmount() { double result; if (isDead) result = deadAmount(); else { if (isSeparated) result = separatedAmount(); else { if (isRetired) result = retiredAmount(); else result = normalPayAmount(); } } return result; } ReplaceNestedConditionalWithGuardClauses(boolean isDead, boolean isSeparated, boolean isRetired); double getPayAmount(); } | ReplaceNestedConditionalWithGuardClauses { public double getPayAmount() { double result; if (isDead) result = deadAmount(); else { if (isSeparated) result = separatedAmount(); else { if (isRetired) result = retiredAmount(); else result = normalPayAmount(); } } return result; } ReplaceNestedConditionalWithGuardClauses(boolean isDead, boolean isSeparated, boolean isRetired); double getPayAmount(); } |
@Test public void should_get_zero_adjusted_capital_given_capital_is_less_than_zero() { ReversingTheConditions reversingTheConditions = new ReversingTheConditions(-1, 10, 10, 10); assertEquals(0, reversingTheConditions.getAdjustedCapital(), 0); } | public double getAdjustedCapital() { double result = 0.0; if (capital > 0.0) { if (intRate > 0.0 && duration > 0.0) { result = (income / duration) * AdjFactor; } } return result; } | ReversingTheConditions { public double getAdjustedCapital() { double result = 0.0; if (capital > 0.0) { if (intRate > 0.0 && duration > 0.0) { result = (income / duration) * AdjFactor; } } return result; } } | ReversingTheConditions { public double getAdjustedCapital() { double result = 0.0; if (capital > 0.0) { if (intRate > 0.0 && duration > 0.0) { result = (income / duration) * AdjFactor; } } return result; } ReversingTheConditions(double capital, double intRate, double duration, double income); } | ReversingTheConditions { public double getAdjustedCapital() { double result = 0.0; if (capital > 0.0) { if (intRate > 0.0 && duration > 0.0) { result = (income / duration) * AdjFactor; } } return result; } ReversingTheConditions(double capital, double intRate, double duration, double income); double getAdjustedCapital(); } | ReversingTheConditions { public double getAdjustedCapital() { double result = 0.0; if (capital > 0.0) { if (intRate > 0.0 && duration > 0.0) { result = (income / duration) * AdjFactor; } } return result; } ReversingTheConditions(double capital, double intRate, double duration, double income); double getAdjustedCapital(); } |
@Test public void should_get_zero_adjusted_capital_given_init_rate_is_less_than_zero() { ReversingTheConditions reversingTheConditions = new ReversingTheConditions(10, -1, 10, 10); assertEquals(0, reversingTheConditions.getAdjustedCapital(), 0); } | public double getAdjustedCapital() { double result = 0.0; if (capital > 0.0) { if (intRate > 0.0 && duration > 0.0) { result = (income / duration) * AdjFactor; } } return result; } | ReversingTheConditions { public double getAdjustedCapital() { double result = 0.0; if (capital > 0.0) { if (intRate > 0.0 && duration > 0.0) { result = (income / duration) * AdjFactor; } } return result; } } | ReversingTheConditions { public double getAdjustedCapital() { double result = 0.0; if (capital > 0.0) { if (intRate > 0.0 && duration > 0.0) { result = (income / duration) * AdjFactor; } } return result; } ReversingTheConditions(double capital, double intRate, double duration, double income); } | ReversingTheConditions { public double getAdjustedCapital() { double result = 0.0; if (capital > 0.0) { if (intRate > 0.0 && duration > 0.0) { result = (income / duration) * AdjFactor; } } return result; } ReversingTheConditions(double capital, double intRate, double duration, double income); double getAdjustedCapital(); } | ReversingTheConditions { public double getAdjustedCapital() { double result = 0.0; if (capital > 0.0) { if (intRate > 0.0 && duration > 0.0) { result = (income / duration) * AdjFactor; } } return result; } ReversingTheConditions(double capital, double intRate, double duration, double income); double getAdjustedCapital(); } |
@Test public void should_get_zero_adjusted_capital_given_duration_is_less_than_zero() { ReversingTheConditions reversingTheConditions = new ReversingTheConditions(10, 10, -1, 10); assertEquals(0, reversingTheConditions.getAdjustedCapital(), 0); } | public double getAdjustedCapital() { double result = 0.0; if (capital > 0.0) { if (intRate > 0.0 && duration > 0.0) { result = (income / duration) * AdjFactor; } } return result; } | ReversingTheConditions { public double getAdjustedCapital() { double result = 0.0; if (capital > 0.0) { if (intRate > 0.0 && duration > 0.0) { result = (income / duration) * AdjFactor; } } return result; } } | ReversingTheConditions { public double getAdjustedCapital() { double result = 0.0; if (capital > 0.0) { if (intRate > 0.0 && duration > 0.0) { result = (income / duration) * AdjFactor; } } return result; } ReversingTheConditions(double capital, double intRate, double duration, double income); } | ReversingTheConditions { public double getAdjustedCapital() { double result = 0.0; if (capital > 0.0) { if (intRate > 0.0 && duration > 0.0) { result = (income / duration) * AdjFactor; } } return result; } ReversingTheConditions(double capital, double intRate, double duration, double income); double getAdjustedCapital(); } | ReversingTheConditions { public double getAdjustedCapital() { double result = 0.0; if (capital > 0.0) { if (intRate > 0.0 && duration > 0.0) { result = (income / duration) * AdjFactor; } } return result; } ReversingTheConditions(double capital, double intRate, double duration, double income); double getAdjustedCapital(); } |
@Test public void should_get_adjusted_capital_given_duration_and_capital_and_init_rate_all_are_greater_than_zero() { ReversingTheConditions reversingTheConditions = new ReversingTheConditions(10, 10, 5, 10); assertEquals(4, reversingTheConditions.getAdjustedCapital(), 0); } | public double getAdjustedCapital() { double result = 0.0; if (capital > 0.0) { if (intRate > 0.0 && duration > 0.0) { result = (income / duration) * AdjFactor; } } return result; } | ReversingTheConditions { public double getAdjustedCapital() { double result = 0.0; if (capital > 0.0) { if (intRate > 0.0 && duration > 0.0) { result = (income / duration) * AdjFactor; } } return result; } } | ReversingTheConditions { public double getAdjustedCapital() { double result = 0.0; if (capital > 0.0) { if (intRate > 0.0 && duration > 0.0) { result = (income / duration) * AdjFactor; } } return result; } ReversingTheConditions(double capital, double intRate, double duration, double income); } | ReversingTheConditions { public double getAdjustedCapital() { double result = 0.0; if (capital > 0.0) { if (intRate > 0.0 && duration > 0.0) { result = (income / duration) * AdjFactor; } } return result; } ReversingTheConditions(double capital, double intRate, double duration, double income); double getAdjustedCapital(); } | ReversingTheConditions { public double getAdjustedCapital() { double result = 0.0; if (capital > 0.0) { if (intRate > 0.0 && duration > 0.0) { result = (income / duration) * AdjFactor; } } return result; } ReversingTheConditions(double capital, double intRate, double duration, double income); double getAdjustedCapital(); } |
@Test public void should_get_true_given_amount_over_1000() { InlineTemp inlineTemp = new InlineTemp(2000); assertTrue(inlineTemp.isAmountOver1000()); } | public boolean isAmountOver1000() { double amount = order.getAmount(); return amount > 1000; } | InlineTemp { public boolean isAmountOver1000() { double amount = order.getAmount(); return amount > 1000; } } | InlineTemp { public boolean isAmountOver1000() { double amount = order.getAmount(); return amount > 1000; } InlineTemp(int amount); } | InlineTemp { public boolean isAmountOver1000() { double amount = order.getAmount(); return amount > 1000; } InlineTemp(int amount); boolean isAmountOver1000(); } | InlineTemp { public boolean isAmountOver1000() { double amount = order.getAmount(); return amount > 1000; } InlineTemp(int amount); boolean isAmountOver1000(); } |
@Test public void should_return_espresso_when_get_espresso_description() { Espresso espresso = new Espresso(false, false); assertTrue(Objects.equals(espresso.getDescription(), "Espresso")); } | public String getDescription() { return ""; } | Beverage { public String getDescription() { return ""; } } | Beverage { public String getDescription() { return ""; } protected Beverage(boolean milk, boolean mocha); } | Beverage { public String getDescription() { return ""; } protected Beverage(boolean milk, boolean mocha); boolean isMilk(); boolean isMocha(); String getDescription(); abstract double cost(); } | Beverage { public String getDescription() { return ""; } protected Beverage(boolean milk, boolean mocha); boolean isMilk(); boolean isMocha(); String getDescription(); abstract double cost(); } |
@Test public void should_get_false_given_amount_less_than_1000() { InlineTemp inlineTemp = new InlineTemp(500); assertFalse(inlineTemp.isAmountOver1000()); } | public boolean isAmountOver1000() { double amount = order.getAmount(); return amount > 1000; } | InlineTemp { public boolean isAmountOver1000() { double amount = order.getAmount(); return amount > 1000; } } | InlineTemp { public boolean isAmountOver1000() { double amount = order.getAmount(); return amount > 1000; } InlineTemp(int amount); } | InlineTemp { public boolean isAmountOver1000() { double amount = order.getAmount(); return amount > 1000; } InlineTemp(int amount); boolean isAmountOver1000(); } | InlineTemp { public boolean isAmountOver1000() { double amount = order.getAmount(); return amount > 1000; } InlineTemp(int amount); boolean isAmountOver1000(); } |
@Test public void should_get_rating_2_given_more_than_five_late_deliveries() { final int numberOfLateDeliveries = 6; InlineMethod inlineMethod = new InlineMethod(numberOfLateDeliveries); assertEquals(2, inlineMethod.getRating()); } | public int getRating() { return (moreThanFiveLateDeliveries()) ? 2 : 1; } | InlineMethod { public int getRating() { return (moreThanFiveLateDeliveries()) ? 2 : 1; } } | InlineMethod { public int getRating() { return (moreThanFiveLateDeliveries()) ? 2 : 1; } InlineMethod(double numberOfLateDeliveries); } | InlineMethod { public int getRating() { return (moreThanFiveLateDeliveries()) ? 2 : 1; } InlineMethod(double numberOfLateDeliveries); int getRating(); } | InlineMethod { public int getRating() { return (moreThanFiveLateDeliveries()) ? 2 : 1; } InlineMethod(double numberOfLateDeliveries); int getRating(); } |
@Test public void should_get_rating_1_given_less_than_five_late_deliveries() { final int numberOfLateDeliveries = 4; InlineMethod inlineMethod = new InlineMethod(numberOfLateDeliveries); assertEquals(1, inlineMethod.getRating()); } | public int getRating() { return (moreThanFiveLateDeliveries()) ? 2 : 1; } | InlineMethod { public int getRating() { return (moreThanFiveLateDeliveries()) ? 2 : 1; } } | InlineMethod { public int getRating() { return (moreThanFiveLateDeliveries()) ? 2 : 1; } InlineMethod(double numberOfLateDeliveries); } | InlineMethod { public int getRating() { return (moreThanFiveLateDeliveries()) ? 2 : 1; } InlineMethod(double numberOfLateDeliveries); int getRating(); } | InlineMethod { public int getRating() { return (moreThanFiveLateDeliveries()) ? 2 : 1; } InlineMethod(double numberOfLateDeliveries); int getRating(); } |
@Test public void should_get_right_customer_owns() { String expectedCustomerOwns = "****/n**Customer Owns**/n****/nname:ExtractMethod/namount:140.0"; List<Order> orders = Arrays.asList(new Order(10), new Order(20)); ExtractMethod extractMethod = new ExtractMethod(orders); String owns = extractMethod.printOwning("ExtractMethod", 100); assertEquals(expectedCustomerOwns, owns); } | public String printOwning(String name, int previousAmount) { String customerOwns = ""; double outstanding = 10 + previousAmount; customerOwns += "****/n"; customerOwns += "**Customer Owns**/n"; customerOwns += "****/n"; for (Order order : orders) { outstanding += order.getAmount(); } customerOwns += "name:" + name + "/n"; customerOwns += "amount:" + outstanding; return customerOwns; } | ExtractMethod { public String printOwning(String name, int previousAmount) { String customerOwns = ""; double outstanding = 10 + previousAmount; customerOwns += "****/n"; customerOwns += "**Customer Owns**/n"; customerOwns += "****/n"; for (Order order : orders) { outstanding += order.getAmount(); } customerOwns += "name:" + name + "/n"; customerOwns += "amount:" + outstanding; return customerOwns; } } | ExtractMethod { public String printOwning(String name, int previousAmount) { String customerOwns = ""; double outstanding = 10 + previousAmount; customerOwns += "****/n"; customerOwns += "**Customer Owns**/n"; customerOwns += "****/n"; for (Order order : orders) { outstanding += order.getAmount(); } customerOwns += "name:" + name + "/n"; customerOwns += "amount:" + outstanding; return customerOwns; } ExtractMethod(List<Order> orders); } | ExtractMethod { public String printOwning(String name, int previousAmount) { String customerOwns = ""; double outstanding = 10 + previousAmount; customerOwns += "****/n"; customerOwns += "**Customer Owns**/n"; customerOwns += "****/n"; for (Order order : orders) { outstanding += order.getAmount(); } customerOwns += "name:" + name + "/n"; customerOwns += "amount:" + outstanding; return customerOwns; } ExtractMethod(List<Order> orders); String printOwning(String name, int previousAmount); } | ExtractMethod { public String printOwning(String name, int previousAmount) { String customerOwns = ""; double outstanding = 10 + previousAmount; customerOwns += "****/n"; customerOwns += "**Customer Owns**/n"; customerOwns += "****/n"; for (Order order : orders) { outstanding += order.getAmount(); } customerOwns += "name:" + name + "/n"; customerOwns += "amount:" + outstanding; return customerOwns; } ExtractMethod(List<Order> orders); String printOwning(String name, int previousAmount); } |
@Test public void should_get_discount_7_given_value_is_over_50_and_quantity_is_over_100_and_yearToEnd_is_over_10000() { RemoveAssignmentsToParameters removeAssignmentsToParameters = new RemoveAssignmentsToParameters(); assertEquals(53, removeAssignmentsToParameters.discount(60, 200, 20000)); } | public int discount(int inputVal, int quantity, int yearToDate) { if (inputVal > 50) inputVal -= 2; if (quantity > 100) inputVal -= 1; if (yearToDate > 10000) inputVal -= 4; return inputVal; } | RemoveAssignmentsToParameters { public int discount(int inputVal, int quantity, int yearToDate) { if (inputVal > 50) inputVal -= 2; if (quantity > 100) inputVal -= 1; if (yearToDate > 10000) inputVal -= 4; return inputVal; } } | RemoveAssignmentsToParameters { public int discount(int inputVal, int quantity, int yearToDate) { if (inputVal > 50) inputVal -= 2; if (quantity > 100) inputVal -= 1; if (yearToDate > 10000) inputVal -= 4; return inputVal; } } | RemoveAssignmentsToParameters { public int discount(int inputVal, int quantity, int yearToDate) { if (inputVal > 50) inputVal -= 2; if (quantity > 100) inputVal -= 1; if (yearToDate > 10000) inputVal -= 4; return inputVal; } int discount(int inputVal, int quantity, int yearToDate); } | RemoveAssignmentsToParameters { public int discount(int inputVal, int quantity, int yearToDate) { if (inputVal > 50) inputVal -= 2; if (quantity > 100) inputVal -= 1; if (yearToDate > 10000) inputVal -= 4; return inputVal; } int discount(int inputVal, int quantity, int yearToDate); } |
@Test public void should_get_discount_5_given_value_is_less_than_50_and_quantity_is_over_100_and_yearToEnd_is_over_10000() { RemoveAssignmentsToParameters removeAssignmentsToParameters = new RemoveAssignmentsToParameters(); assertEquals(35, removeAssignmentsToParameters.discount(40, 200, 20000)); } | public int discount(int inputVal, int quantity, int yearToDate) { if (inputVal > 50) inputVal -= 2; if (quantity > 100) inputVal -= 1; if (yearToDate > 10000) inputVal -= 4; return inputVal; } | RemoveAssignmentsToParameters { public int discount(int inputVal, int quantity, int yearToDate) { if (inputVal > 50) inputVal -= 2; if (quantity > 100) inputVal -= 1; if (yearToDate > 10000) inputVal -= 4; return inputVal; } } | RemoveAssignmentsToParameters { public int discount(int inputVal, int quantity, int yearToDate) { if (inputVal > 50) inputVal -= 2; if (quantity > 100) inputVal -= 1; if (yearToDate > 10000) inputVal -= 4; return inputVal; } } | RemoveAssignmentsToParameters { public int discount(int inputVal, int quantity, int yearToDate) { if (inputVal > 50) inputVal -= 2; if (quantity > 100) inputVal -= 1; if (yearToDate > 10000) inputVal -= 4; return inputVal; } int discount(int inputVal, int quantity, int yearToDate); } | RemoveAssignmentsToParameters { public int discount(int inputVal, int quantity, int yearToDate) { if (inputVal > 50) inputVal -= 2; if (quantity > 100) inputVal -= 1; if (yearToDate > 10000) inputVal -= 4; return inputVal; } int discount(int inputVal, int quantity, int yearToDate); } |
@Test public void should_get_right_discount_given_base_price_is_over_1000() { ReplaceTempWithQuery replaceTempWithQuery = new ReplaceTempWithQuery(1000, 2); assertEquals(1900, replaceTempWithQuery.getPrice(), 2); } | public double getPrice() { double basePrice = quantity * itemPrice; double discountFactor; if (basePrice > 1000) discountFactor = 0.95; else discountFactor = 0.98; return basePrice * discountFactor; } | ReplaceTempWithQuery { public double getPrice() { double basePrice = quantity * itemPrice; double discountFactor; if (basePrice > 1000) discountFactor = 0.95; else discountFactor = 0.98; return basePrice * discountFactor; } } | ReplaceTempWithQuery { public double getPrice() { double basePrice = quantity * itemPrice; double discountFactor; if (basePrice > 1000) discountFactor = 0.95; else discountFactor = 0.98; return basePrice * discountFactor; } ReplaceTempWithQuery(double quantity, double itemPrice); } | ReplaceTempWithQuery { public double getPrice() { double basePrice = quantity * itemPrice; double discountFactor; if (basePrice > 1000) discountFactor = 0.95; else discountFactor = 0.98; return basePrice * discountFactor; } ReplaceTempWithQuery(double quantity, double itemPrice); double getPrice(); } | ReplaceTempWithQuery { public double getPrice() { double basePrice = quantity * itemPrice; double discountFactor; if (basePrice > 1000) discountFactor = 0.95; else discountFactor = 0.98; return basePrice * discountFactor; } ReplaceTempWithQuery(double quantity, double itemPrice); double getPrice(); } |
@Test public void should_get_right_discount_given_base_price_is_less_than_1000() { ReplaceTempWithQuery replaceTempWithQuery = new ReplaceTempWithQuery(400, 2); assertEquals(784, replaceTempWithQuery.getPrice(), 2); } | public double getPrice() { double basePrice = quantity * itemPrice; double discountFactor; if (basePrice > 1000) discountFactor = 0.95; else discountFactor = 0.98; return basePrice * discountFactor; } | ReplaceTempWithQuery { public double getPrice() { double basePrice = quantity * itemPrice; double discountFactor; if (basePrice > 1000) discountFactor = 0.95; else discountFactor = 0.98; return basePrice * discountFactor; } } | ReplaceTempWithQuery { public double getPrice() { double basePrice = quantity * itemPrice; double discountFactor; if (basePrice > 1000) discountFactor = 0.95; else discountFactor = 0.98; return basePrice * discountFactor; } ReplaceTempWithQuery(double quantity, double itemPrice); } | ReplaceTempWithQuery { public double getPrice() { double basePrice = quantity * itemPrice; double discountFactor; if (basePrice > 1000) discountFactor = 0.95; else discountFactor = 0.98; return basePrice * discountFactor; } ReplaceTempWithQuery(double quantity, double itemPrice); double getPrice(); } | ReplaceTempWithQuery { public double getPrice() { double basePrice = quantity * itemPrice; double discountFactor; if (basePrice > 1000) discountFactor = 0.95; else discountFactor = 0.98; return basePrice * discountFactor; } ReplaceTempWithQuery(double quantity, double itemPrice); double getPrice(); } |
@Test public void should_get_right_gamma_given() { ReplaceMethodWithMethodObject replaceMethodWithMethodObject = new ReplaceMethodWithMethodObject(); int gamma = replaceMethodWithMethodObject.gamma(10, 5, 100); assertEquals(7600, gamma); } | public int gamma(int inputVal, int quantity, int yearToDate) { int importantValue1 = inputVal * quantity; int importantValue2 = inputVal * yearToDate + 100; if ((yearToDate - importantValue1) > 100) importantValue2 -= 20; int importantValue3 = importantValue2 * 7; return importantValue3 - 2 * importantValue1; } | ReplaceMethodWithMethodObject { public int gamma(int inputVal, int quantity, int yearToDate) { int importantValue1 = inputVal * quantity; int importantValue2 = inputVal * yearToDate + 100; if ((yearToDate - importantValue1) > 100) importantValue2 -= 20; int importantValue3 = importantValue2 * 7; return importantValue3 - 2 * importantValue1; } } | ReplaceMethodWithMethodObject { public int gamma(int inputVal, int quantity, int yearToDate) { int importantValue1 = inputVal * quantity; int importantValue2 = inputVal * yearToDate + 100; if ((yearToDate - importantValue1) > 100) importantValue2 -= 20; int importantValue3 = importantValue2 * 7; return importantValue3 - 2 * importantValue1; } } | ReplaceMethodWithMethodObject { public int gamma(int inputVal, int quantity, int yearToDate) { int importantValue1 = inputVal * quantity; int importantValue2 = inputVal * yearToDate + 100; if ((yearToDate - importantValue1) > 100) importantValue2 -= 20; int importantValue3 = importantValue2 * 7; return importantValue3 - 2 * importantValue1; } int gamma(int inputVal, int quantity, int yearToDate); } | ReplaceMethodWithMethodObject { public int gamma(int inputVal, int quantity, int yearToDate) { int importantValue1 = inputVal * quantity; int importantValue2 = inputVal * yearToDate + 100; if ((yearToDate - importantValue1) > 100) importantValue2 -= 20; int importantValue3 = importantValue2 * 7; return importantValue3 - 2 * importantValue1; } int gamma(int inputVal, int quantity, int yearToDate); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.