First remote-client
[dynamic-remote.git] / remote-server / src / main / java / test / remote / server / service / impl / CalculatorImpl.java
blob458a92ae28702e2a25b2ad053013b84e1cba4b3e
1 package test.remote.server.service.impl;
3 import java.util.ArrayList;
4 import java.util.HashMap;
5 import java.util.List;
6 import java.util.Map;
8 import org.springframework.stereotype.Service;
10 import test.remote.server.domain.Op;
11 import test.remote.server.domain.OpBinary;
12 import test.remote.server.domain.OpConstant;
13 import test.remote.server.domain.OpType;
14 import test.remote.server.service.Calculator;
16 @Service
17 public class CalculatorImpl implements Calculator {
19 private List<Long> stack = new ArrayList<Long>();
21 public CalculatorImpl() {
24 @Override
25 public void push(String atom) {
26 final Map<String,OpType> str2Type = new HashMap<String,OpType>();
27 for (OpType t: OpType.findAllOpTypes()) {
28 str2Type.put(t.getName(), t);
31 if (atom == null) {
32 throw new NullPointerException();
34 if (atom.equals("+") || atom.equals("-") || atom.equals("*")) {
35 final int size = stack.size();
36 final OpBinary op = new OpBinary();
37 op.setType(str2Type.get(atom));
38 op.setLeft(Op.findOp(stack.get(size - 1)));
39 op.setRight(Op.findOp(stack.get(size - 2)));
40 op.persist();
41 stack.add(op.getId());
43 else {
44 Double v = Double.parseDouble(atom);
45 final OpConstant op = new OpConstant();
46 op.setType(str2Type.get("CONST"));
47 op.setValue(v);
48 op.persist();
49 stack.add(op.getId());
53 @Override
54 public Double eval() {
55 final Apply apply = new ApplyImpl();
56 for (Long id: stack) {
57 final Op op = Op.findOp(id);
58 op.visit(apply);
60 final OpConstant result = new OpConstant();
61 result.setValue(apply.pop());
62 return result.getValue();
65 @Override
66 public void clear() {
67 for (Long l: stack) {
68 Op.findOp(l).remove();