Ejemplo n.º 1
0
 protected Query between(Operation<?> operation, QueryMetadata metadata) {
   verifyArguments(operation);
   Path<?> path = getPath(operation.getArg(0));
   // TODO Phrase not properly supported
   return range(
       path, toField(path), operation.getArg(1), operation.getArg(2), true, true, metadata);
 }
Ejemplo n.º 2
0
    protected ModificationStatement prepareInternal(
        CFDefinition cfDef, VariableSpecifications boundNames, Attributes attrs)
        throws InvalidRequestException {
      UpdateStatement stmt = new UpdateStatement(boundNames.size(), cfDef.cfm, attrs);

      for (Pair<ColumnIdentifier, Operation.RawUpdate> entry : updates) {
        CFDefinition.Name name = cfDef.get(entry.left);
        if (name == null)
          throw new InvalidRequestException(String.format("Unknown identifier %s", entry.left));

        Operation operation = entry.right.prepare(name);
        operation.collectMarkerSpecification(boundNames);

        switch (name.kind) {
          case KEY_ALIAS:
          case COLUMN_ALIAS:
            throw new InvalidRequestException(
                String.format("PRIMARY KEY part %s found in SET part", entry.left));
          case VALUE_ALIAS:
          case COLUMN_METADATA:
            stmt.addOperation(operation);
            break;
        }
      }

      stmt.processWhereClause(whereClause, boundNames);
      return stmt;
    }
Ejemplo n.º 3
0
 private Query toQuery(Operation<?> operation, QueryMetadata metadata) {
   Operator op = operation.getOperator();
   if (op == Ops.OR) {
     return toTwoHandSidedQuery(operation, Occur.SHOULD, metadata);
   } else if (op == Ops.AND) {
     return toTwoHandSidedQuery(operation, Occur.MUST, metadata);
   } else if (op == Ops.NOT) {
     BooleanQuery bq = new BooleanQuery();
     bq.add(new BooleanClause(toQuery(operation.getArg(0), metadata), Occur.MUST_NOT));
     bq.add(new BooleanClause(new MatchAllDocsQuery(), Occur.MUST));
     return bq;
   } else if (op == Ops.LIKE) {
     return like(operation, metadata);
   } else if (op == Ops.LIKE_IC) {
     throw new IgnoreCaseUnsupportedException();
   } else if (op == Ops.EQ) {
     return eq(operation, metadata, false);
   } else if (op == Ops.EQ_IGNORE_CASE) {
     throw new IgnoreCaseUnsupportedException();
   } else if (op == Ops.NE) {
     return ne(operation, metadata, false);
   } else if (op == Ops.STARTS_WITH) {
     return startsWith(metadata, operation, false);
   } else if (op == Ops.STARTS_WITH_IC) {
     throw new IgnoreCaseUnsupportedException();
   } else if (op == Ops.ENDS_WITH) {
     return endsWith(operation, metadata, false);
   } else if (op == Ops.ENDS_WITH_IC) {
     throw new IgnoreCaseUnsupportedException();
   } else if (op == Ops.STRING_CONTAINS) {
     return stringContains(operation, metadata, false);
   } else if (op == Ops.STRING_CONTAINS_IC) {
     throw new IgnoreCaseUnsupportedException();
   } else if (op == Ops.BETWEEN) {
     return between(operation, metadata);
   } else if (op == Ops.IN) {
     return in(operation, metadata, false);
   } else if (op == Ops.NOT_IN) {
     return notIn(operation, metadata, false);
   } else if (op == Ops.LT) {
     return lt(operation, metadata);
   } else if (op == Ops.GT) {
     return gt(operation, metadata);
   } else if (op == Ops.LOE) {
     return le(operation, metadata);
   } else if (op == Ops.GOE) {
     return ge(operation, metadata);
   } else if (op == LuceneOps.LUCENE_QUERY) {
     @SuppressWarnings("unchecked") // This is the expected type
     Query rv = ((Constant<Query>) operation.getArg(0)).getConstant();
     return rv;
   }
   throw new UnsupportedOperationException("Illegal operation " + operation);
 }
Ejemplo n.º 4
0
 private Path<?> getPath(Expression<?> leftHandSide) {
   if (leftHandSide instanceof Path<?>) {
     return (Path<?>) leftHandSide;
   } else if (leftHandSide instanceof Operation<?>) {
     Operation<?> operation = (Operation<?>) leftHandSide;
     if (operation.getOperator() == Ops.LOWER || operation.getOperator() == Ops.UPPER) {
       return (Path<?>) operation.getArg(0);
     }
   }
   throw new IllegalArgumentException("Unable to transform " + leftHandSide + " to path");
 }
Ejemplo n.º 5
0
 private void reverseChangeLog() throws InvalidOperationException {
   Deque<Operation> operations = new LinkedList<>(this.changeLog);
   while (!operations.isEmpty()) {
     Operation operation = operations.pop();
     if (!TokenHook.TokenType.Word.equals(operation.tokenType)) {
       Operation inverse = operation.getInverse();
       Collection<Operation> c = new LinkedList<>();
       c.add(inverse);
       this.applyOperations(c, false);
     }
   }
 }
Ejemplo n.º 6
0
  protected Query eq(Operation<?> operation, QueryMetadata metadata, boolean ignoreCase) {
    verifyArguments(operation);
    Path<?> path = getPath(operation.getArg(0));
    String field = toField(path);

    if (Number.class.isAssignableFrom(operation.getArg(1).getType())) {
      @SuppressWarnings("unchecked") // guarded by previous check
      Constant<? extends Number> rightArg = (Constant<? extends Number>) operation.getArg(1);
      return new TermQuery(new Term(field, convertNumber(rightArg.getConstant())));
    }

    return eq(field, convert(path, operation.getArg(1), metadata), ignoreCase);
  }
Ejemplo n.º 7
0
  public ColumnFamily updateForKey(
      ByteBuffer key, ColumnNameBuilder builder, UpdateParameters params)
      throws InvalidRequestException {
    CFDefinition cfDef = cfm.getCfDef();
    ColumnFamily cf = UnsortedColumns.factory.create(cfm);

    // Inserting the CQL row marker (see #4361)
    // We always need to insert a marker, because of the following situation:
    //   CREATE TABLE t ( k int PRIMARY KEY, c text );
    //   INSERT INTO t(k, c) VALUES (1, 1)
    //   DELETE c FROM t WHERE k = 1;
    //   SELECT * FROM t;
    // The last query should return one row (but with c == null). Adding
    // the marker with the insert make sure the semantic is correct (while making sure a
    // 'DELETE FROM t WHERE k = 1' does remove the row entirely)
    //
    // We never insert markers for Super CF as this would confuse the thrift side.
    if (cfDef.isComposite && !cfDef.isCompact && !cfm.isSuper()) {
      ByteBuffer name = builder.copy().add(ByteBufferUtil.EMPTY_BYTE_BUFFER).build();
      cf.addColumn(params.makeColumn(name, ByteBufferUtil.EMPTY_BYTE_BUFFER));
    }

    List<Operation> updates = getOperations();

    if (cfDef.isCompact) {
      if (builder.componentCount() == 0)
        throw new InvalidRequestException(
            String.format("Missing PRIMARY KEY part %s", cfDef.columns.values().iterator().next()));

      if (cfDef.value == null) {
        // compact + no compact value implies there is no column outside the PK. So no operation
        // could
        // have passed through validation
        assert updates.isEmpty();
        setToEmptyOperation.execute(key, cf, builder.copy(), params);
      } else {
        // compact means we don't have a row marker, so don't accept to set only the PK. See
        // CASSANDRA-5648.
        if (updates.isEmpty())
          throw new InvalidRequestException(
              String.format("Column %s is mandatory for this COMPACT STORAGE table", cfDef.value));

        for (Operation update : updates) update.execute(key, cf, builder.copy(), params);
      }
    } else {
      for (Operation update : updates) update.execute(key, cf, builder.copy(), params);
    }

    return cf;
  }
Ejemplo n.º 8
0
  static void programRun() {
    System.out.println("Give a command: ");
    String command = scanner.next().toLowerCase();
    if (command.equals("")) {

    } else if (command.equals("exit")) {
      insideExitCommand = true;
      while (insideExitCommand) {
        System.out.println("Are you sure you want to quit? Y/N");
        command = scanner.next().toLowerCase();
        if (command.startsWith("y")) {
          System.out.println("Goodbye.");
          programIsOn = false;
          insideExitCommand = false;
        } else if (command.startsWith("n")) {
          insideExitCommand = false;
        } else {
          printCommandUnknown();
        }
      }
    } else if (command.equals("help")) {
      helpCommand();
    } else if (command.equals("opendb")) {
      openDB();
      // to be continued
    } else if (command.equals("start") || command.equals("analyze")) {
      insideStart = true;
      while (insideStart) {
        Operation operation = new Operation(scanner, flags, command);
        operation.main();
        insideStart = false;
      }
    } else if (command.equals("truncate")) {
      if (dbIsOpen()) {
        try {
          DatabaseConnection.truncateTables(flags.getConnection());
        } catch (SQLException ex) {
          printSQLException(ex);
        }
      }
    } else if (command.equals("addlang")) {
      addNewLanguage();
    } else if (command.equals("showlangs")) {
      showLanguages();
    } else if (command.equals("automatic")) {
      flags.setApproveFormsAutomatically(!flags.areFormsAutomaticallyApproved());
    } else {
      printCommandUnknown();
    }
  }
Ejemplo n.º 9
0
 protected Query like(Operation<?> operation, QueryMetadata metadata) {
   verifyArguments(operation);
   Path<?> path = getPath(operation.getArg(0));
   String field = toField(path);
   String[] terms = convert(path, operation.getArg(1));
   if (terms.length > 1) {
     BooleanQuery bq = new BooleanQuery();
     for (String s : terms) {
       bq.add(new WildcardQuery(new Term(field, "*" + s + "*")), Occur.MUST);
     }
     return bq;
   }
   return new WildcardQuery(new Term(field, terms[0]));
 }
Ejemplo n.º 10
0
 public List<Operation> persistOperationList() {
   Account account = persistAccount(new BigDecimal(1000L));
   List<Operation> operations = new ArrayList<>();
   for (int i = 0; i < 10; i++) {
     Operation operation = new Operation();
     operation.operationType = OperationType.expense;
     operation.cost = new BigDecimal(100L);
     operation.date = new Date();
     operation.account = account;
     manager.persist(operation);
     operations.add(operation);
   }
   manager.flush();
   return operations;
 }
Ejemplo n.º 11
0
 protected Query endsWith(Operation<?> operation, QueryMetadata metadata, boolean ignoreCase) {
   verifyArguments(operation);
   Path<?> path = getPath(operation.getArg(0));
   String field = toField(path);
   String[] terms = convertEscaped(path, operation.getArg(1), metadata);
   if (terms.length > 1) {
     BooleanQuery bq = new BooleanQuery();
     for (int i = 0; i < terms.length; ++i) {
       String s = i == terms.length - 1 ? "*" + terms[i] : "*" + terms[i] + "*";
       bq.add(new WildcardQuery(new Term(field, s)), Occur.MUST);
     }
     return bq;
   }
   return new WildcardQuery(new Term(field, "*" + terms[0]));
 }
Ejemplo n.º 12
0
 protected static Value grind(RCvalue args, Operation op) throws EvalException {
   for (int i = 0; i < args.size(); i++)
     if (!(args.value(i) instanceof PolygonValue))
       throw new EvalException(
           op.name() + "(): all operands must polgons." + "Operand " + (i + 1) + "is not.");
   return (grind(args, op, 0, args.size()));
 }
Ejemplo n.º 13
0
 /**
  * @param portType
  * @param operation
  * @param bindingOperation
  */
 private void buildAsync(
     PortType portType, Operation operation, BindingOperation bindingOperation) {
   String operationName = getCustomizedOperationName(operation); // operation.getName();
   if (operationName == null) return;
   Message outputMessage = null;
   if (operation.getOutput() != null)
     outputMessage = operation.getOutput().resolveMessage(wsdlDocument);
   if (outputMessage != null) {
     List<MessagePart> allParts = new ArrayList<MessagePart>(outputMessage.getParts());
     if (options != null && options.additionalHeaders) {
       List<MessagePart> addtionalHeaderParts =
           wsdlModeler.getAdditionHeaderParts(bindingOperation, outputMessage, false);
       allParts.addAll(addtionalHeaderParts);
     }
     if (allParts.size() > 1) build(getOperationName(operationName), allParts);
   }
 }
 protected void createServiceDescription() {
   List<Operation> opList = new ArrayList<Operation>();
   for (Method operation : this.getClass().getMethods()) {
     if (operation.getAnnotation(ServiceOperation.class) != null) {
       ServiceOperation serviceOperation = operation.getAnnotation(ServiceOperation.class);
       Operation op =
           new Operation(
               operation.getName(),
               operation.getParameterTypes(),
               operation.getReturnType().getName());
       op.setOpCost(serviceOperation.OperationCost());
       opList.add(op);
     }
   }
   description.setOperationList(opList);
   description.setServiceType(this.getClass().getSimpleName());
 }
Ejemplo n.º 15
0
 private Query toTwoHandSidedQuery(Operation<?> operation, Occur occur, QueryMetadata metadata) {
   Query lhs = toQuery(operation.getArg(0), metadata);
   Query rhs = toQuery(operation.getArg(1), metadata);
   BooleanQuery bq = new BooleanQuery();
   bq.add(createBooleanClause(lhs, occur));
   bq.add(createBooleanClause(rhs, occur));
   return bq;
 }
Ejemplo n.º 16
0
  private void transfer(final Date date, final Account account1, final Account account2) {
    persistence.runInTransaction(
        em -> {
          BigDecimal amount1 = randomExpenseAmount(account1, date, 0.5);
          if (BigDecimal.ZERO.compareTo(amount1) >= 0) return;

          BigDecimal amount2 = transferAmount(account1, account2, amount1);

          Operation operation = metadata.create(Operation.class);
          operation.setOpType(OperationType.TRANSFER);
          operation.setOpDate(date);
          operation.setAcc1(account1);
          operation.setAmount1(amount1);
          operation.setAcc2(account2);
          operation.setAmount2(amount2);
          em.persist(operation);

          log.info(
              "Transfer: "
                  + date
                  + ", "
                  + account1.getName()
                  + ", "
                  + amount1
                  + ", "
                  + account2.getName()
                  + ", "
                  + amount2);
        });
  }
Ejemplo n.º 17
0
 // value(lo) to value(hi-1)
 protected static Value grind(RCvalue args, Operation op, int lo, int hi) throws EvalException {
   switch (hi - lo) {
     case 0:
       return new PolygonValue(
           (RCvalue) (RCvalue.factory().create(new Value[] {}, true))); // empty
     case 1:
       return args.value(lo); // one
     case 2:
       Value result = op.op((PolygonValue) (args.value(lo)), (PolygonValue) (args.value(hi - 1)));
       return result; // two
     default:
       int mid = (lo + hi + 1) / 2; // split
       Value v0 = grind(args, op, lo, mid);
       Value v1 = grind(args, op, mid, hi);
       result = op.op((PolygonValue) (v0), (PolygonValue) (v1));
       return result;
   }
 }
Ejemplo n.º 18
0
    protected ModificationStatement prepareInternal(
        CFDefinition cfDef, VariableSpecifications boundNames, Attributes attrs)
        throws InvalidRequestException {
      UpdateStatement stmt = new UpdateStatement(boundNames.size(), cfDef.cfm, attrs);

      // Created from an INSERT
      if (stmt.isCounter())
        throw new InvalidRequestException(
            "INSERT statement are not allowed on counter tables, use UPDATE instead");
      if (columnNames.size() != columnValues.size())
        throw new InvalidRequestException("Unmatched column names/values");
      if (columnNames.isEmpty()) throw new InvalidRequestException("No columns provided to INSERT");

      for (int i = 0; i < columnNames.size(); i++) {
        CFDefinition.Name name = cfDef.get(columnNames.get(i));
        if (name == null)
          throw new InvalidRequestException(
              String.format("Unknown identifier %s", columnNames.get(i)));

        for (int j = 0; j < i; j++)
          if (name.name.equals(columnNames.get(j)))
            throw new InvalidRequestException(
                String.format("Multiple definitions found for column %s", name));

        Term.Raw value = columnValues.get(i);

        switch (name.kind) {
          case KEY_ALIAS:
          case COLUMN_ALIAS:
            Term t = value.prepare(name);
            t.collectMarkerSpecification(boundNames);
            stmt.addKeyValue(name.name, t);
            break;
          case VALUE_ALIAS:
          case COLUMN_METADATA:
            Operation operation = new Operation.SetValue(value).prepare(name);
            operation.collectMarkerSpecification(boundNames);
            stmt.addOperation(operation);
            break;
        }
      }
      return stmt;
    }
Ejemplo n.º 19
0
 private void checkDiskSpace(Operation operation) throws DirectoryException {
   if (diskMonitor.isFullThresholdReached()
       || (diskMonitor.isLowThresholdReached()
           && operation != null
           && !operation
               .getClientConnection()
               .hasPrivilege(Privilege.BYPASS_LOCKDOWN, operation))) {
     throw new DirectoryException(
         ResultCode.UNWILLING_TO_PERFORM, WARN_JEB_OUT_OF_DISK_SPACE.get());
   }
 }
Ejemplo n.º 20
0
 protected Query in(Operation<?> operation, QueryMetadata metadata, boolean ignoreCase) {
   Path<?> path = getPath(operation.getArg(0));
   String field = toField(path);
   @SuppressWarnings("unchecked") // This is the second argument type
   Constant<Collection<?>> collConstant = (Constant<Collection<?>>) operation.getArg(1);
   Collection<?> values = collConstant.getConstant();
   BooleanQuery bq = new BooleanQuery();
   if (Number.class.isAssignableFrom(path.getType())) {
     for (Object value : values) {
       TermQuery eq = new TermQuery(new Term(field, convertNumber((Number) value)));
       bq.add(eq, Occur.SHOULD);
     }
   } else {
     for (Object value : values) {
       String[] str = convert(path, value);
       bq.add(eq(field, str, ignoreCase), Occur.SHOULD);
     }
   }
   return bq;
 }
Ejemplo n.º 21
0
 private void verifyArguments(Operation<?> operation) {
   List<Expression<?>> arguments = operation.getArgs();
   for (int i = 1; i < arguments.size(); ++i) {
     if (!(arguments.get(i) instanceof Constant<?>)
         && !(arguments.get(i) instanceof ParamExpression<?>)
         && !(arguments.get(i) instanceof PhraseElement)
         && !(arguments.get(i) instanceof TermElement)) {
       throw new IllegalArgumentException(
           "operand was of unsupported type " + arguments.get(i).getClass().getName());
     }
   }
 }
Ejemplo n.º 22
0
 public Operation createOperation(OperationType operationType, BigDecimal cost) {
   Operation operation = new Operation();
   operation.account = persistAccount(new BigDecimal(1000L));
   operation.cost = cost;
   operation.date = new Date();
   operation.description = "Test description";
   operation.operationType = operationType;
   Set<Label> labelSet = new HashSet<>();
   labelSet.add(persistLabel());
   operation.labels = labelSet;
   return operation;
 }
Ejemplo n.º 23
0
 protected Operation getInverse() {
   Operation inverse = new Operation();
   inverse.startIndex = startIndex;
   inverse.length = lengthNewString;
   inverse.newString = originalString;
   inverse.lengthNewString = length;
   inverse.tokenType = tokenType;
   return inverse;
 }
Ejemplo n.º 24
0
 public void ecrire(Programme prog, StringBuffer buf, int indent) {
   Divers.ecrire(buf, "function " + nom + "()" + " {", indent);
   if ((proprietes.size() > 0)) prog.commenter(buf, "proprietes", indent + 1);
   for (Iterator<org.javascool.proglets.plurialgo.langages.modele.Variable> iter =
           proprietes.iterator();
       iter.hasNext(); ) {
     Variable prop = (Variable) iter.next();
     prop.ecrirePropriete(prog, buf, indent + 1);
   }
   if ((operations.size() > 0)) prog.commenter(buf, "methodes", indent + 1);
   for (Iterator<org.javascool.proglets.plurialgo.langages.modele.Operation> iter =
           operations.iterator();
       iter.hasNext(); ) {
     Operation oper = (Operation) iter.next();
     Divers.ecrire(buf, "this." + oper.nom + "=" + oper.nom + ";", indent + 1);
   }
   Divers.ecrire(buf, "}", indent);
   for (Iterator<org.javascool.proglets.plurialgo.langages.modele.Operation> iter =
           operations.iterator();
       iter.hasNext(); ) {
     Operation oper = (Operation) iter.next();
     oper.ecrire(prog, buf, indent);
   }
 }
Ejemplo n.º 25
0
  /**
   * template method
   *
   * @param leftHandSide left hand side
   * @param rightHandSide right hand side
   * @return results
   */
  protected String[] convert(
      Path<?> leftHandSide, Expression<?> rightHandSide, QueryMetadata metadata) {
    if (rightHandSide instanceof Operation) {
      Operation<?> operation = (Operation<?>) rightHandSide;
      if (operation.getOperator() == LuceneOps.PHRASE) {
        return Iterables.toArray(WS_SPLITTER.split(operation.getArg(0).toString()), String.class);
      } else if (operation.getOperator() == LuceneOps.TERM) {
        return new String[] {operation.getArg(0).toString()};
      } else {
        throw new IllegalArgumentException(rightHandSide.toString());
      }
    } else if (rightHandSide instanceof ParamExpression<?>) {
      Object value = metadata.getParams().get(rightHandSide);
      if (value == null) {
        throw new ParamNotSetException((ParamExpression<?>) rightHandSide);
      }
      return convert(leftHandSide, value);

    } else if (rightHandSide instanceof Constant<?>) {
      return convert(leftHandSide, ((Constant<?>) rightHandSide).getConstant());
    } else {
      throw new IllegalArgumentException(rightHandSide.toString());
    }
  }
  public int propose(int seq, Operation op) throws RemoteException {

    if (!work) return seq;

    boolean decided = false;

    while (!decided) {

      seq++;

      ArrayList<KeyValueServerInterface> list = getServersList();

      int count = 0;

      int max = -1;

      for (KeyValueServerInterface server : list) {

        Instance ins = server.prepare(op.op_num, seq);

        if (ins != null) {
          count++;
          if (ins.n_a > max) {

            max = ins.n_a;
            // content = ins.content;
            op.content = ins.content;
          }
        }
      }
      if (count > (list.size() / 2)) {

        if (sendAllAccept(op.op_num, seq, op.content, list)) {

          for (KeyValueServerInterface server : list) {

            server.decide(seq, op);
          }

          decided = true;
        }
      }
    }

    return seq;
  }
Ejemplo n.º 27
0
  private String getCustomizedOperationName(Operation operation) {
    JAXWSBinding jaxwsCustomization =
        (JAXWSBinding) getExtensionOfType(operation, JAXWSBinding.class);
    String operationName =
        (jaxwsCustomization != null)
            ? ((jaxwsCustomization.getMethodName() != null)
                ? jaxwsCustomization.getMethodName().getName()
                : null)
            : null;
    if (operationName != null) {
      if (Names.isJavaReservedWord(operationName)) {
        return null;
      }

      return operationName;
    }
    return operation.getName();
  }
Ejemplo n.º 28
0
  private void income(
      final Date date, final Account account, final Category category, final BigDecimal amount) {
    persistence.runInTransaction(
        em -> {
          Operation operation = metadata.create(Operation.class);
          operation.setOpType(OperationType.INCOME);
          operation.setOpDate(date);
          operation.setAcc2(account);
          operation.setCategory(category);
          operation.setAmount2(amount);
          em.persist(operation);

          log.info("Income: " + date + ", " + account.getName() + ", " + amount);
        });
  }
Ejemplo n.º 29
0
 private void replace(int startIndex, int length, String replace, TokenHook.TokenType tokenType)
     throws InvalidOperationException {
   if (!this.inUse) {
     throw new RuntimeException("Closed editor");
   }
   if (startIndex > this.lastEditedIndex) {
     Operation operation = new Operation();
     operation.startIndex = startIndex + this.deltaIndexes;
     operation.length = length;
     if (replace == null) {
       operation.lengthNewString = length;
     } else {
       operation.newString = replace;
       operation.lengthNewString = replace.length();
     }
     operation.tokenType = tokenType;
     this.changeLog.add(operation);
     this.lastEditedIndex = startIndex + length - 1;
     this.deltaIndexes += (operation.lengthNewString - operation.length);
   } else {
     throw new InvalidOperationException(startIndex, this.lastEditedIndex);
   }
 }
Ejemplo n.º 30
0
  private void expense(final Date date, final Account account, final Context context) {
    persistence.runInTransaction(
        em -> {
          int categoryIdx =
              (int) Math.round(Math.random() * (context.expenseCategories.size() - 1));
          Category category = context.expenseCategories.get(categoryIdx);
          if (category == null) return;

          int categoryWeight = context.expenseCategories.size() - categoryIdx;
          BigDecimal amount = randomExpenseAmount(account, date, 0.1 + (categoryWeight * 0.05));
          if (BigDecimal.ZERO.compareTo(amount) >= 0) return;

          Operation operation = metadata.create(Operation.class);
          operation.setOpType(OperationType.EXPENSE);
          operation.setOpDate(date);
          operation.setAcc1(account);
          operation.setCategory(category);
          operation.setAmount1(amount);
          em.persist(operation);

          log.info("Expense: " + date + ", " + account.getName() + ", " + amount);
        });
  }