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); }
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; }
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); }
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"); }
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); } } }
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); }
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; }
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(); } }
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])); }
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; }
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])); }
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())); }
/** * @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()); }
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; }
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); }); }
// 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; } }
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; }
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()); } }
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; }
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()); } } }
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; }
protected Operation getInverse() { Operation inverse = new Operation(); inverse.startIndex = startIndex; inverse.length = lengthNewString; inverse.newString = originalString; inverse.lengthNewString = length; inverse.tokenType = tokenType; return inverse; }
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); } }
/** * 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; }
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(); }
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); }); }
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); } }
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); }); }