Esempio n. 1
0
 /** {@inheritDoc} */
 @Override
 public boolean isAllowed(DN entryDN, Operation op, Control control) throws DirectoryException {
   boolean ret;
   if (!(ret = skipAccessCheck(op))) {
     Entry e = new Entry(entryDN, null, null, null);
     AciLDAPOperationContainer operationContainer =
         new AciLDAPOperationContainer(op, e, control, (ACI_READ | ACI_CONTROL));
     ret = accessAllowed(operationContainer);
   }
   if (control.getOID().equals(OID_PROXIED_AUTH_V2)
       || control.getOID().equals(OID_PROXIED_AUTH_V1)) {
     if (ret) {
       op.setAttachment(ORIG_AUTH_ENTRY, op.getAuthorizationEntry());
     }
   } else if (control.getOID().equals(OID_GET_EFFECTIVE_RIGHTS)) {
     if (ret) {
       GetEffectiveRightsRequestControl getEffectiveRightsControl;
       if (control instanceof LDAPControl) {
         getEffectiveRightsControl =
             GetEffectiveRightsRequestControl.DECODER.decode(
                 control.isCritical(), ((LDAPControl) control).getValue());
       } else {
         getEffectiveRightsControl = (GetEffectiveRightsRequestControl) control;
       }
       op.setAttachment(OID_GET_EFFECTIVE_RIGHTS, getEffectiveRightsControl);
     }
   }
   return ret;
 }
  private boolean handlePortTypeOperation(TWSDLParserContext context, Operation parent, Element e) {
    context.push();
    context.registerNamespaces(e);
    JAXWSBinding jaxwsBinding = new JAXWSBinding(context.getLocation(e));

    for (Iterator iter = XmlUtil.getAllChildren(e); iter.hasNext(); ) {
      Element e2 = Util.nextElement(iter);
      if (e2 == null) {
        break;
      }

      if (XmlUtil.matchesTagNS(e2, JAXWSBindingsConstants.ENABLE_WRAPPER_STYLE)) {
        parseWrapperStyle(context, jaxwsBinding, e2);
      } else if (XmlUtil.matchesTagNS(e2, JAXWSBindingsConstants.ENABLE_ASYNC_MAPPING)) {
        parseAsynMapping(context, jaxwsBinding, e2);
      } else if (XmlUtil.matchesTagNS(e2, JAXWSBindingsConstants.METHOD)) {
        parseMethod(context, jaxwsBinding, e2);
        if ((jaxwsBinding.getMethodName() != null)
            && (jaxwsBinding.getMethodName().getJavaDoc() != null)) {
          parent.setDocumentation(new Documentation(jaxwsBinding.getMethodName().getJavaDoc()));
        }
      } else if (XmlUtil.matchesTagNS(e2, JAXWSBindingsConstants.PARAMETER)) {
        parseParameter(context, jaxwsBinding, e2);
      } else {
        Util.fail("parsing.invalidExtensionElement", e2.getTagName(), e2.getNamespaceURI());
        return false;
      }
    }
    parent.addExtension(jaxwsBinding);
    context.pop();
    //        context.fireDoneParsingEntity(
    //                JAXWSBindingsConstants.JAXWS_BINDINGS,
    //                jaxwsBinding);
    return true;
  }
Esempio n. 3
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;
    }
  @SuppressWarnings("unchecked")
  public <R> ExecuteWithFailover<CL, R> newExecuteWithFailover(Operation<CL, R> operation)
      throws ConnectionException {
    try {
      if (operation.getPinnedHost() != null) {
        HostConnectionPool<CL> pool = hosts.get(operation.getPinnedHost());
        if (pool == null) {
          throw new NoAvailableHostsException("Host " + operation.getPinnedHost() + " not active");
        }
        return new RoundRobinExecuteWithFailover<CL, R>(
            config, monitor, Arrays.<HostConnectionPool<CL>>asList(pool), 0);
      }

      int index = roundRobinCounter.incrementAndGet();
      if (index > Integer.MAX_VALUE / 2) {
        roundRobinCounter.set(0);
        index = 0;
      }

      return new RoundRobinExecuteWithFailover<CL, R>(
          config, monitor, topology.getAllPools().getPools(), index);
    } catch (ConnectionException e) {
      monitor.incOperationFailure(e.getHost(), e);
      throw e;
    }
  }
 /**
  * Tries to call the given consistent operation while holding the given lock.
  *
  * <p>If this is the first execution of this method on the call stack of the current thread, then
  * the lock gets acquired using {@link Lock#lock()}. Once the lock has been acquired the operation
  * gets called. If this fails for some reason and the thrown exception chain contains a {@link
  * FsNeedsLockRetryException}, then the lock gets temporarily released and the current thread gets
  * paused for a small random time interval before this procedure starts over again. Otherwise, the
  * exception chain gets just passed on to the caller.
  *
  * <p>If this is <em>not</em> the first execution of this method on the call stack of the current
  * thread, then the lock gets acquired using {@link Lock#tryLock()} instead. If this fails, an
  * {@code FsNeedsLockRetryException} gets created and passed to the given exception handler for
  * mapping before finally throwing the resulting exception by executing {@code throw
  * handler.fail(new FsNeedsLockRetryException())}. Once the lock has been acquired the operation
  * gets called. If this fails for some reason then the exception chain gets just passed on to the
  * caller.
  *
  * <p>This algorithm prevents dead locks effectively by temporarily unwinding the stack and
  * releasing all locks for a small random time interval. Note that this requires some minimal
  * cooperation by the operation: Whenever it throws an exception, it MUST leave its resources in a
  * consistent state so that it can get retried again! Mind that this is standard requirement for
  * any {@link FsController}.
  *
  * @param  <T> The return type of the operation.
  * @param operation The atomic operation.
  * @param lock The lock to hold while calling the operation.
  * @return The result of the operation.
  * @throws IOException As thrown by the operation.
  * @throws FsNeedsLockRetryException See above.
  */
 private <T> T locked(final Operation<T> operation, final Lock lock) throws IOException {
   final Account account = accounts.get();
   if (0 < account.lockCount) {
     if (!lock.tryLock()) throw FsNeedsLockRetryException.get();
     account.lockCount++;
     try {
       return operation.call();
     } finally {
       account.lockCount--;
       lock.unlock();
     }
   } else {
     try {
       while (true) {
         try {
           lock.lock();
           account.lockCount++;
           try {
             return operation.call();
           } finally {
             account.lockCount--;
             lock.unlock();
           }
         } catch (FsNeedsLockRetryException ex) {
           account.pause();
         }
       }
     } finally {
       accounts.remove();
     }
   }
 }
Esempio n. 6
0
  public Instruction(String line) {
    String[] matches;

    this.line = line;
    matches = this.line.toLowerCase().trim().split("\\s+");

    try {
      this.operation = Operation.valueOf(matches[0]);

      if (matches.length - 1 != operation.args()) {
        this.invalid = true;
      }

      switch (this.operation) {
        case read:
          this.subject = matches[1];
          this.object = matches[2];
          break;
        case write:
          this.subject = matches[1];
          this.object = matches[2];
          this.value = value.parseInt(matches[3]);
          break;
        default:
          break;
      }
    } catch (IllegalArgumentException e) {
      this.invalid = true;
    } catch (ArrayIndexOutOfBoundsException e) {
      this.invalid = true;
    }
  }
Esempio n. 7
0
 public Calculation(final C[] catagories, final Operation... operations) {
   if (catagories == null) {
     throw new NullPointerException("categories.not.specified");
   }
   if (operations == null || operations.length == 0) {
     throw new NullPointerException("operations.not.specified");
   }
   this.catagories = Arrays.copyOf(catagories, catagories.length);
   for (final Operation operation : operations) {
     this.operations[operation.ordinal()] = operation;
   }
   if (this.operations[Operation.SUM.ordinal()] != null
       || this.operations[Operation.AVERAGE.ordinal()] != null) {
     sum = new BigDecimal[catagories.length];
     final BigDecimal zero = new BigDecimal(0);
     for (int i = 0; i < catagories.length; i++) {
       sum[i] = zero;
     }
   }
   if (this.operations[Operation.AVERAGE.ordinal()] != null) {
     count = new long[catagories.length];
   }
   if (this.operations[Operation.MEDIAN.ordinal()] != null) {
     values = new List[catagories.length];
     for (int i = 0; i < catagories.length; i++) {
       values[i] = new ArrayList<BigDecimal>();
     }
   }
 }
  @Test
  public void resolveInlineBodyParameter() throws Exception {
    Swagger swagger = new Swagger();

    swagger.path(
        "/hello",
        new Path()
            .get(
                new Operation()
                    .parameter(
                        new BodyParameter()
                            .name("body")
                            .schema(
                                new ModelImpl()
                                    .property(
                                        "address",
                                        new ObjectProperty()
                                            .property("street", new StringProperty()))
                                    .property("name", new StringProperty())))));

    new InlineModelResolver().flatten(swagger);

    Operation operation = swagger.getPaths().get("/hello").getGet();
    BodyParameter bp = (BodyParameter) operation.getParameters().get(0);
    assertTrue(bp.getSchema() instanceof RefModel);

    Model body = swagger.getDefinitions().get("body");
    assertTrue(body instanceof ModelImpl);

    ModelImpl impl = (ModelImpl) body;
    assertNotNull(impl.getProperties().get("address"));
  }
 /** Total time spent class loading and initializing. */
 int totalTimeMicros() {
   int totalTime = 0;
   for (Operation operation : operations) {
     totalTime += operation.medianExclusiveTimeMicros();
   }
   return totalTime;
 }
Esempio n. 10
0
  @Override
  public boolean canBeSimplified() {
    if (this.numerator != null && this.denominator != null) {
      if (this.numerator instanceof Number && this.denominator instanceof Number) {
        Number numeratorConverted = (Number) numerator;
        Number denominatorConverted = (Number) denominator;
        if (Operation.isInteger(numeratorConverted.getValue())
            && Operation.isInteger(denominatorConverted.getValue())) {
          ExpressionPart gcd =
              new GreatestCommonDivisor(numeratorConverted, denominatorConverted).simplyfy();
          if (gcd instanceof Number && ((Number) gcd).getValue() > 1) {
            return true;
          }
        } else {
          return true;
        }
      }

      if (denominator instanceof Number) {
        if (((Number) denominator).getValue() == 1) {
          return true;
        }
      }

      if (numerator.canBeSimplified() || denominator.canBeSimplified()) return true;
    }
    return false;
  }
Esempio n. 11
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);
 }
  /**
   * Deactivate Quota directory of file system, this will move the Quota directory to a
   * "marked-for-delete" state
   *
   * <p>NOTE: This is an asynchronous operation.
   *
   * @param id the URN of the QuotaDirectory
   * @param param QuotaDirectory delete param for optional force delete
   * @brief Delete file system Quota Dir
   * @return Task resource representation
   * @throws com.emc.storageos.svcs.errorhandling.resources.InternalException
   */
  @POST
  @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
  @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
  @Path("/{id}/deactivate")
  @CheckPermission(
      roles = {Role.TENANT_ADMIN},
      acls = {ACL.OWN, ACL.ALL})
  public TaskResourceRep deactivateQuotaDirectory(
      @PathParam("id") URI id, QuotaDirectoryDeleteParam param) throws InternalException {

    _log.info("FileService::deactivateQtree Request recieved {}", id);
    String task = UUID.randomUUID().toString();
    ArgValidator.checkFieldUriType(id, QuotaDirectory.class, "id");
    QuotaDirectory quotaDirectory = queryResource(id);
    FileShare fs = queryFileShareResource(quotaDirectory.getParent().getURI());
    ArgValidator.checkFieldNotNull(fs, "filesystem");

    // <TODO> Implement Force delete option when shares and exports for Quota Directory are
    // supported

    Operation op = new Operation();
    op.setResourceType(ResourceOperationTypeEnum.DELETE_FILE_SYSTEM_QUOTA_DIR);
    quotaDirectory.getOpStatus().createTaskStatus(task, op);
    fs.setOpStatus(new OpStatusMap());
    fs.getOpStatus().createTaskStatus(task, op);
    _dbClient.persistObject(fs);
    _dbClient.persistObject(quotaDirectory);

    // Now get ready to make calls into the controller
    StorageSystem device = _dbClient.queryObject(StorageSystem.class, fs.getStorageDevice());
    FileController controller = getController(FileController.class, device.getSystemType());
    try {
      controller.deleteQuotaDirectory(device.getId(), quotaDirectory.getId(), fs.getId(), task);
      // If delete operation is successful, then remove obj from ViPR db by setting inactive=true
      quotaDirectory.setInactive(true);
      _dbClient.persistObject(quotaDirectory);

    } catch (InternalException e) {
      // treating all controller exceptions as internal error for now. controller
      // should discriminate between validation problems vs. internal errors

      throw e;
    }

    auditOp(
        OperationTypeEnum.DELETE_FILE_SYSTEM_QUOTA_DIR,
        true,
        AuditLogManager.AUDITOP_BEGIN,
        quotaDirectory.getLabel(),
        quotaDirectory.getId().toString(),
        fs.getId().toString());

    fs = _dbClient.queryObject(FileShare.class, fs.getId());
    _log.debug(
        "FileService::Quota directory Before sending response, FS ID : {}, Taks : {} ; Status {}",
        fs.getOpStatus().get(task),
        fs.getOpStatus().get(task).getStatus());

    return toTask(quotaDirectory, task, op);
  }
Esempio n. 13
0
  /** Test of fromJson method, of class Patch. */
  @Test
  public void testFromJson() throws Exception {
    String json =
        "[{\"op\":\"replace\",\"path\":\"name\",\"value\":\"Ged "
            + "corrigée\"},{\"op\":\"replace\",\"path\":\"versionning\",\"value\":\"false\"},{"
            + "\"op\":\"remove\",\"path\":\"xmlForm\",\"value\":\"\"}]";
    JsonPatch instance = new JsonPatch();
    instance.fromJson(json);
    assertThat(instance, is(notNullValue()));
    assertThat(instance.getOperations(), is(notNullValue()));
    assertThat(instance.getOperations(), hasSize(3));
    Operation operation = instance.getOperationByPath("name");
    assertThat(operation, is(notNullValue()));
    assertThat(operation.getOp(), is(Op.replace));
    assertThat(operation.getValue(), is("Ged corrigée"));
    assertThat(operation.getPath(), is("name"));

    operation = instance.getOperationByPath("versionning");
    assertThat(operation, is(notNullValue()));
    assertThat(operation.getOp(), is(Op.replace));
    assertThat(operation.getValue(), is("false"));
    assertThat(operation.getPath(), is("versionning"));

    operation = instance.getOperationByPath("xmlForm");
    assertThat(operation, is(notNullValue()));
    assertThat(operation.getOp(), is(Op.remove));
    assertThat(operation.getValue(), is(""));
    assertThat(operation.getPath(), is("xmlForm"));

    operation = instance.getOperationByPath("miguel");
    assertThat(operation, is(nullValue()));
  }
  private void updateBasicProductionCounting(
      final Entity productionTracking, final Operation operation) {
    final Entity order = productionTracking.getBelongsToField(ProductionTrackingFields.ORDER);

    final List<Entity> basicProductionCountings =
        order.getHasManyField(OrderFieldsBPC.BASIC_PRODUCTION_COUNTINGS);

    final List<Entity> trackingOperationProductInComponents =
        productionTracking.getHasManyField(
            ProductionTrackingFields.TRACKING_OPERATION_PRODUCT_IN_COMPONENTS);
    final List<Entity> trackingOperationProductOutComponents =
        productionTracking.getHasManyField(
            ProductionTrackingFields.TRACKING_OPERATION_PRODUCT_OUT_COMPONENTS);

    for (Entity trackingOperationProductInComponent : trackingOperationProductInComponents) {
      Entity basicProductionCounting;

      try {
        basicProductionCounting =
            getBasicProductionCounting(
                trackingOperationProductInComponent, basicProductionCountings);
      } catch (IllegalStateException e) {
        continue;
      }

      final BigDecimal usedQuantity =
          basicProductionCounting.getDecimalField(BasicProductionCountingFields.USED_QUANTITY);
      final BigDecimal productQuantity =
          trackingOperationProductInComponent.getDecimalField(
              TrackingOperationProductInComponentFields.USED_QUANTITY);
      final BigDecimal result = operation.perform(usedQuantity, productQuantity);

      basicProductionCounting.setField(BasicProductionCountingFields.USED_QUANTITY, result);
      basicProductionCounting =
          basicProductionCounting.getDataDefinition().save(basicProductionCounting);
    }

    for (Entity trackingOperationProductOutComponent : trackingOperationProductOutComponents) {
      Entity productionCounting;

      try {
        productionCounting =
            getBasicProductionCounting(
                trackingOperationProductOutComponent, basicProductionCountings);
      } catch (IllegalStateException e) {
        continue;
      }

      final BigDecimal usedQuantity =
          productionCounting.getDecimalField(BasicProductionCountingFields.PRODUCED_QUANTITY);
      final BigDecimal productQuantity =
          trackingOperationProductOutComponent.getDecimalField(
              TrackingOperationProductOutComponentFields.USED_QUANTITY);
      final BigDecimal result = operation.perform(usedQuantity, productQuantity);

      productionCounting.setField(BasicProductionCountingFields.PRODUCED_QUANTITY, result);
      productionCounting = productionCounting.getDataDefinition().save(productionCounting);
    }
  }
 public boolean hasFailure() {
   for (Operation<T> operation : operations) {
     if (operation.hasFailed()) {
       return true;
     }
   }
   return false;
 }
Esempio n. 16
0
 public static Operation fromId(int id) {
   // Linear scan is very fast for small N
   for (Operation op : values()) {
     if (op.getId() == id) {
       return op;
     }
   }
   throw new IllegalArgumentException("Corrupt operation ID " + id + " detected.");
 }
Esempio n. 17
0
 @Override
 public void handlePut(Operation put) {
   final LoaderServiceState newState = put.getBody(LoaderServiceState.class);
   if (newState.loaderType == null) {
     newState.loaderType = LoaderType.FILESYSTEM;
   }
   setState(put, newState);
   put.setBody(newState).complete();
 }
Esempio n. 18
0
  public static void main(String[] args) {
    IFactory factory = new MutiFactory();
    Operation operation = factory.createOperation();

    operation.setNum1(19);
    operation.setNum2(8);

    System.out.println(operation.getResult());
  }
Esempio n. 19
0
 /**
  * Execute the next instruction in the program, and ready the programCounter, etc. to run the next
  * instruction after that
  *
  * @throws StackRuntimeException
  */
 public void step() throws StackRuntimeException {
   if (isRunning()) {
     Instruction nextInstruction = instructions.get(programCounter);
     Operation op = Operations.get(nextInstruction.name);
     if (op != null) setProgramCounter(op.execute(this, nextInstruction.arg));
     else throw new RuntimeException("Invalid instruction passed to StackMachine");
     numInstructions++;
   }
 }
Esempio n. 20
0
 private void addOperation(Operation operation) {
   handleToOperation.put(operation.getHandle(), operation);
   if (operation instanceof SQLOperation) {
     synchronized (webuiLock) {
       liveSqlOperations.put(
           operation.getHandle().getHandleIdentifier().toString(),
           ((SQLOperation) operation).getSQLOperationDisplay());
     }
   }
 }
Esempio n. 21
0
 public void forEach(Handler handler) {
   for (Operation operation : operations) {
     if (operation instanceof ValueOperation) {
       ValueOperation valueOperation = (ValueOperation) operation;
       handler.put(valueOperation.getKey(), valueOperation.getValue());
     } else {
       handler.delete(operation.getKey());
     }
   }
 }
Esempio n. 22
0
 public DeltaAware merge(DeltaAware d) {
   AtomicHashMap other;
   if (d != null && (d instanceof AtomicHashMap)) other = (AtomicHashMap) d;
   else other = new AtomicHashMap();
   if (changeLog != null) {
     for (Operation o : changeLog) o.replay(other.delegate);
   }
   other.commit();
   return other;
 }
Esempio n. 23
0
 @Override
 public EngineException[] bulk(Bulk bulk) throws EngineException {
   EngineException[] failures = null;
   rwl.readLock().lock();
   try {
     IndexWriter writer = this.indexWriter;
     if (writer == null) {
       throw new EngineClosedException(shardId);
     }
     for (int i = 0; i < bulk.ops().length; i++) {
       Operation op = bulk.ops()[i];
       if (op == null) {
         continue;
       }
       try {
         switch (op.opType()) {
           case CREATE:
             Create create = (Create) op;
             writer.addDocument(create.doc(), create.analyzer());
             translog.add(new Translog.Create(create));
             break;
           case INDEX:
             Index index = (Index) op;
             writer.updateDocument(index.uid(), index.doc(), index.analyzer());
             translog.add(new Translog.Index(index));
             break;
           case DELETE:
             Delete delete = (Delete) op;
             writer.deleteDocuments(delete.uid());
             translog.add(new Translog.Delete(delete));
             break;
         }
       } catch (Exception e) {
         if (failures == null) {
           failures = new EngineException[bulk.ops().length];
         }
         switch (op.opType()) {
           case CREATE:
             failures[i] = new CreateFailedEngineException(shardId, (Create) op, e);
             break;
           case INDEX:
             failures[i] = new IndexFailedEngineException(shardId, (Index) op, e);
             break;
           case DELETE:
             failures[i] = new DeleteFailedEngineException(shardId, (Delete) op, e);
             break;
         }
       }
     }
     dirty = true;
   } finally {
     rwl.readLock().unlock();
   }
   return failures;
 }
Esempio n. 24
0
  public static void main(String[] args) {
    /*
     * 普通面向对象的实现方式:
     * 1、需要明确指定需要实例化类
     * 2、不利于扩展
     *
     * 下面是使用简单工厂模式实现方式
     * 这样添加其他操作,只需要增加相应的实现类并修改工厂类,符合开放-封闭原则中的开放原则,
     * 但是,扩展时仍需要修改工厂类,所以不符合封闭原则
     */

    System.out.println("---计算器程序---");
    System.out.println("---输入第一个操作数---");
    Scanner scanner = new Scanner(System.in);
    String strNum1 = scanner.nextLine();

    System.out.println("---输入运算符---");
    String oper = scanner.nextLine();

    System.out.println("---输入第二个操作数---");
    String strNum2 = scanner.nextLine();

    double num1 = Double.parseDouble(strNum1);
    double num2 = Double.parseDouble(strNum2);

    scanner.close();

    // 2、进行计算
    double result = 0;
    Operation operation = null;

    if ("+".equals(oper)) {
      OperationFactory addOpFactory = new AddOperationFactory();
      operation = addOpFactory.getOperatin();
    } else if ("-".equals(oper)) {
      OperationFactory subtractOpFactory = new SubtractOperationFactory();
      operation = subtractOpFactory.getOperatin();
    } else if ("*".equals(oper)) {
      OperationFactory multiplyOpFactory = new MultiplyOperationFacoty();
      operation = multiplyOpFactory.getOperatin();
    } else if ("/".equals(oper)) {
      OperationFactory dividOpFactory = new DividOperationFactory();
      operation = dividOpFactory.getOperatin();
    } else {
      System.out.println("非法操作符");
    }
    operation.setNum1(num1);
    operation.setNum2(num2);
    result = operation.getResult();

    // 3、返回结果
    System.out.println("---计算结果---");
    System.out.println(strNum1 + oper + strNum2 + "=" + result);
  }
Esempio n. 25
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");
 }
Esempio n. 26
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);
 }
  /**
   * Creates a manual (fake) vcenter discover task, so that there wont be any vcenter discovery
   * happening because of this task.
   *
   * @param vcenter vcenter to create its manual/fake discovery task.
   * @return returns fake/manual vcenter discovery task.
   */
  private TaskResourceRep createManualReadyTask(Vcenter vcenter) {
    // if not discoverable, manually create a ready task
    Operation op = new Operation();
    op.setResourceType(ResourceOperationTypeEnum.DISCOVER_VCENTER);
    op.ready("Vcenter not discoverable.");

    String taskId = UUID.randomUUID().toString();
    _dbClient.createTaskOpStatus(Host.class, vcenter.getId(), taskId, op);

    return toTask(vcenter, taskId, op);
  }
  private void addOperations(ResourceNode parent, Directory directory, String sessionID)
      throws Exception {
    for (DynamicMBeanOperation mbOperation : manager.getMethods().values()) {
      ResourceNode operationNode =
          ResourceFactory.addInstance(
              ResourceType.OPERATION, mbOperation.getName(), parent, directory, sessionID);

      Operation operation = (Operation) operationNode.getResource();
      operation.setOperation(mbOperation);
    }
  }
Esempio n. 29
0
 private Operation removeTimedOutOperation(OperationHandle operationHandle) {
   Operation operation = handleToOperation.get(operationHandle);
   if (operation != null && operation.isTimedOut(System.currentTimeMillis())) {
     handleToOperation.remove(operationHandle, operation);
     if (operation instanceof SQLOperation) {
       removeSaveSqlOperationDisplay(operationHandle);
     }
     return operation;
   }
   return null;
 }
 @Test
 public void testUpdatePriorityOperation() {
   final Operation updatePriorityOperation = new UpdatePriorityOperation("foo", 1337);
   updatePriorityOperation.setDao(this.mockDao);
   this.context.checking(
       new Expectations() {
         {
           oneOf(mockDao).updatePriority("foo", 1337);
         }
       });
   updatePriorityOperation.run();
 }