Example #1
0
  public static void bind(
      final BoundStatement statement,
      final TableScheme scheme,
      final ColumnDefinitions meta,
      final Value<?> value) {
    final String name = value.getColumn().getName();
    if (statement.isSet(name)) {
      throw new IllegalStateException(); // FIXME: descriptive
    }

    if (value.getType() != Value.Type.BOUND) {
      throw new IllegalStateException(); // FIXME: descriptive
    }

    final DataType tableType = meta.getType(name);
    final DataType valueType = value.getColumn().getCassandraType().getDataType();

    if (!typesEquals(tableType, valueType)) {
      throw new IllegalArgumentException(
          MessageFormat.format("Unexpected types: {0} != {1}", tableType, valueType));
    }

    final Object converted = value.asCassandraValue();
    statement.setBytesUnsafe(
        name, tableType.serialize(converted, ProtocolVersion.NEWEST_SUPPORTED));
  }
Example #2
0
  /**
   * Computes the number of results.
   *
   * @param qc query context (may be @code null)
   * @return number of results
   */
  private long size(final QueryContext qc) {
    final Value rt = initial(qc);
    // skip computation if value is not a document node
    if (rt == null || rt.type != NodeType.DOC) return -1;
    final Data data = rt.data();
    // skip computation if no database instance is available, is out-of-date or
    // if context does not contain all database nodes
    if (data == null || !data.meta.uptodate || data.resources.docs().size() != rt.size()) return -1;

    ArrayList<PathNode> nodes = data.paths.root();
    long m = 1;
    final int sl = steps.length;
    for (int s = 0; s < sl; s++) {
      final Step curr = axisStep(s);
      if (curr != null) {
        nodes = curr.nodes(nodes, data);
        if (nodes == null) return -1;
      } else if (s + 1 == sl) {
        m = steps[s].size();
      } else {
        // stop if a non-axis step is not placed last
        return -1;
      }
    }

    long sz = 0;
    for (final PathNode pn : nodes) sz += pn.stats.count;
    return sz * m;
  }
Example #3
0
 // Received an ACK
 @Override
 public void onAck() {
   // remove local cache but NOT in case it is already on disk
   // (ie memory can be reclaimed and we assume we have plenty of disk space)
   if (_dontCache && !_xval.isPersisted()) H2O.putIfMatch(_xkey, null, _xval);
   if (_xval != null) _xval.completeRemotePut();
 }
 /**
  * Returns the values owned by this {@link PropertyRepresentation}, represented by a string
  *
  * @return the values owned by this {@link PropertyRepresentation}, represented by a string
  */
 public ArrayList<String> getStringValue() {
   ArrayList<String> stringValues = new ArrayList<String>();
   for (Value val : values) {
     stringValues.add(val.getValue());
   }
   return stringValues;
 }
Example #5
0
  @Override
  public final Expr compile(final QueryContext qc, final VarScope scp) throws QueryException {
    if (root != null) root = root.compile(qc, scp);
    // no steps
    if (steps.length == 0) return root == null ? new Context(info) : root;

    final Value init = qc.value, cv = initial(qc);
    final boolean doc = cv != null && cv.type == NodeType.DOC;
    qc.value = cv;
    try {
      final int sl = steps.length;
      for (int s = 0; s < sl; s++) {
        Expr e = steps[s];

        // axis step: if input is a document, its type is temporarily generalized
        final boolean as = e instanceof Step;
        if (as && s == 0 && doc) cv.type = NodeType.NOD;

        e = e.compile(qc, scp);
        if (e.isEmpty()) return optPre(qc);
        steps[s] = e;

        // no axis step: invalidate context value
        if (!as) qc.value = null;
      }
    } finally {
      if (doc) cv.type = NodeType.DOC;
      qc.value = init;
    }
    // optimize path
    return optimize(qc, scp);
  }
Example #6
0
  public void exceptionEvent(ExceptionEvent event) {
    ObjectReference or = event.exception();
    ReferenceType rt = or.referenceType();
    String exceptionName = rt.name();
    // Field messageField = Throwable.class.getField("detailMessage");
    Field messageField = rt.fieldByName("detailMessage");
    //    System.out.println("field " + messageField);
    Value messageValue = or.getValue(messageField);
    //    System.out.println("mess val " + messageValue);

    // "java.lang.ArrayIndexOutOfBoundsException"
    int last = exceptionName.lastIndexOf('.');
    String message = exceptionName.substring(last + 1);
    if (messageValue != null) {
      String messageStr = messageValue.toString();
      if (messageStr.startsWith("\"")) {
        messageStr = messageStr.substring(1, messageStr.length() - 1);
      }
      message += ": " + messageStr;
    }
    //    System.out.println("mess type " + messageValue.type());
    // StringReference messageReference = (StringReference) messageValue.type();

    // First just report the exception and its placement
    reportException(message, or, event.thread());
    // Then try to pretty it up with a better message
    handleCommonErrors(exceptionName, message, listener);

    if (editor != null) {
      editor.deactivateRun();
    }
  }
  public static OsgiManifest read(List<String> lines) {

    // parse lines
    OsgiManifest manifest = new OsgiManifest();
    for (int i = 0; i < lines.size(); i++) {
      String line = lines.get(i);
      for (int j = i + 1; j < lines.size() && lines.get(j).startsWith(" "); j++, i++) {
        line = line + lines.get(j);
      }
      int index = line.indexOf(':');
      if (index > 0) {
        String attributeName = line.substring(0, index).trim();
        List<String> valueTokens = tokenize(line.substring(index + 1), ',');
        Attribute values = manifest.getAttribute(attributeName);
        for (String valueToken : valueTokens) {
          if (valueToken.trim().isEmpty()) continue;
          Value value = new Value();
          values.add(value);
          List<String> annotationTokens = tokenize(valueToken, ';');
          value.setValue(annotationTokens.get(0));
          for (int k = 1; k < annotationTokens.size(); k++) {
            String annotationToken = annotationTokens.get(k);
            index = annotationToken.indexOf('=');
            if (index > 0) {
              value.setAnnotation(
                  annotationToken.substring(0, index), annotationToken.substring(index + 1));
            }
          }
        }
      }
    }
    return manifest;
  }
 public String getProperty(String name) {
   Value val = getFile(name, Value.class);
   if (val != null) {
     return val.getString();
   }
   return null;
 }
Example #9
0
  @Override
  public Value value(final QueryContext ctx) throws QueryException {
    final int o = (int) ctx.resources.output.size();
    final Updates updates = ctx.resources.updates();
    final ContextModifier tmp = updates.mod;
    final TransformModifier pu = new TransformModifier();
    updates.mod = pu;

    try {
      for (final Let fo : copies) {
        final Iter ir = ctx.iter(fo.expr);
        Item i = ir.next();
        if (!(i instanceof ANode) || ir.next() != null) throw UPCOPYMULT.get(fo.info, fo.var.name);

        // copy node to main memory data instance
        i = ((ANode) i).dbCopy(ctx.context.options);
        // add resulting node to variable
        ctx.set(fo.var, i, info);
        pu.addData(i.data());
      }
      final Value v = ctx.value(expr[0]);
      if (!v.isEmpty()) throw BASEX_MOD.get(info);

      updates.prepare();
      updates.apply();
      return ctx.value(expr[1]);
    } finally {
      ctx.resources.output.size(o);
      updates.mod = tmp;
    }
  }
Example #10
0
 @Override
 public String toString() {
   StringBuilder sb = new StringBuilder();
   if (result != null) {
     sb.append(result.toString());
     sb.append(" = ");
   }
   sb.append(name);
   sb.append(' ');
   FunctionType ftype = (FunctionType) function.getType();
   sb.append(ftype.isVarargs() ? ftype.getDefinition() : ftype.getReturnType().toString());
   sb.append(" ");
   sb.append(function.toString());
   sb.append('(');
   for (int i = 0; i < args.length; i++) {
     if (i > 0) {
       sb.append(", ");
     }
     sb.append(args[i].getType());
     sb.append(' ');
     sb.append(args[i]);
   }
   sb.append(')');
   return sb.toString();
 }
Example #11
0
 // Write-lock & delete 'k'.  Will fail if 'k' is locked by anybody other than 'job_key'
 public static void delete(Key k, Key job_key) {
   if (k == null) return;
   Value val = DKV.get(k);
   if (val == null) return; // Or just nothing there to delete
   if (!val.isLockable()) UKV.remove(k); // Simple things being deleted
   else ((Lockable) val.get()).delete(job_key, 0.0f); // Lockable being deleted
 }
Example #12
0
  private Object getValueOrValueVector() {
    Pair<Expression, Expression> pair;
    ValueVector currVector;
    Value currValue = getRootValue();
    int index;

    for (int i = 0; i < path.length; i++) {
      pair = path[i];
      currVector = currValue.getChildren(pair.key().evaluate().strValue());
      if (pair.value() == null) {
        if ((i + 1) < path.length) {
          currValue = currVector.get(0);
        } else { // We're finished
          return currVector;
        }
      } else {
        index = pair.value().evaluate().intValue();
        if ((i + 1) < path.length) {
          currValue = currVector.get(index);
        } else {
          return currVector.get(index);
        }
      }
    }

    return currValue;
  }
Example #13
0
  public final void makePointer(VariablePath rightPath) {
    Pair<Expression, Expression> pair;
    ValueVector currVector;
    Value currValue = getRootValue();
    int index;
    String keyStr;

    for (int i = 0; i < path.length; i++) {
      pair = path[i];
      keyStr = pair.key().evaluate().strValue();
      currVector = currValue.getChildren(keyStr);
      if (pair.value() == null) {
        if ((i + 1) < path.length) {
          currValue = currVector.get(0);
        } else { // We're finished
          currValue.children().put(keyStr, ValueVector.createLink(rightPath));
        }
      } else {
        index = pair.value().evaluate().intValue();
        if ((i + 1) < path.length) {
          currValue = currVector.get(index);
        } else {
          currVector.set(index, Value.createLink(rightPath));
        }
      }
    }
  }
Example #14
0
  @Override
  @Secured
  public void removeTestExecution(TestExecution testExecution) throws ServiceException {
    TestExecution freshTestExecution = testExecutionDAO.get(testExecution.getId());
    if (freshTestExecution == null) {
      throw new ServiceException("serviceException.testExecutionNotFound", testExecution.getName());
    }
    for (TestExecutionParameter testExecutionParameter : freshTestExecution.getParameters()) {
      testExecutionParameterDAO.remove(testExecutionParameter);
    }
    for (Value value : freshTestExecution.getValues()) {
      for (ValueParameter valueParameter : value.getParameters()) {
        valueParameterDAO.remove(valueParameter);
      }
      valueDAO.remove(value);
    }

    Iterator<TestExecutionAttachment> allTestExecutionAttachments =
        freshTestExecution.getAttachments().iterator();
    while (allTestExecutionAttachments.hasNext()) {
      testExecutionAttachmentDAO.remove(allTestExecutionAttachments.next());
      allTestExecutionAttachments.remove();
    }
    testExecutionDAO.remove(freshTestExecution);
  }
Example #15
0
 @Override
 public Value lazyArrayChunk(final Key key) {
   final Key arykey = ValueArray.getArrayKey(key); // From the base file key
   final long off = (_iceRoot != null) ? 0 : ValueArray.getChunkOffset(key); // The offset
   final Path p =
       (_iceRoot != null)
           ? new Path(_iceRoot, getIceName(key, (byte) 'V'))
           : new Path(arykey.toString());
   final Size sz = new Size();
   run(
       new Callable() {
         @Override
         public Object call() throws Exception {
           FileSystem fs = FileSystem.get(p.toUri(), CONF);
           long rem = fs.getFileStatus(p).getLen() - off;
           sz._value = (rem > ValueArray.CHUNK_SZ * 2) ? (int) ValueArray.CHUNK_SZ : (int) rem;
           return null;
         }
       },
       true,
       0);
   Value val = new Value(key, sz._value, Value.HDFS);
   val.setdsk(); // But its already on disk.
   return val;
 }
Example #16
0
  /**
   * Constructs a new more operator with the specified two argument values.
   *
   * @param value1 the left side argument value
   * @param value2 the right side argument value
   * @throws ExpressionException if any of the two argument values are not numeric
   */
  public MoreOperator(Value value1, Value value2) throws ExpressionException {
    super(value1, value2);

    if (value1.getType() == Type.STRING || value2.getType() == Type.STRING) {
      throw new ExpressionException("Can't use more than operator with strings");
    }
  }
Example #17
0
  public LinkedList<String> getValueNames() {
    LinkedList<String> valueNames = new LinkedList<String>();

    for (Value v : values) valueNames.add(v.getContent());

    return valueNames;
  }
  public static void main(String[] args) {

    // create a graph with type inferencing
    SimpleSesameGraph g = new SimpleSesameGraph(true);

    //        //load the film schema and the example data
    //        g.addFile("../roadstead_ontologies/film-ontology.owl", SimpleSesameGraph.RDFXML);

    // try loading the geopolitical ontology
    g.addURI("http://aims.fao.org/aos/geopolitical.owl");

    //        List<HashMap<Object, Value>> solutions = g.runSPARQL("SELECT ?who WHERE  { " +
    //                "?who <http://www.w3.org/1999/02/22-rdf-syntax-ns#type>
    // <http://roadstead.org/film#Person> ." +
    //                "}");

    /*
    Here we are looking for the names of all the things with a name
     */
    List<HashMap<Object, Value>> solutions =
        g.runSPARQL(
            "SELECT ?name WHERE  { "
                + "?what <http://aims.fao.org/aos/geopolitical.owl#territory> ?name ."
                + "?what <http://aims.fao.org/aos/geopolitical.owl#nameListEN> ?name ."
                + "}");
    for (HashMap<Object, Value> object : solutions) {
      for (Value value : object.values()) {
        System.out.println("country: " + value.stringValue());
      }
    }
  }
Example #19
0
  @Override
  public List<FeedValue> getFeed(final int count, final String relationshipEntityKey)
      throws NimbitsException {

    final User loggedInUser = getUser();
    final User feedUser = getFeedUser(relationshipEntityKey, loggedInUser);

    if (feedUser != null) {

      final Point point = getFeedPoint(feedUser);
      if (point == null) {
        return new ArrayList<FeedValue>(0);
      } else {
        final List<Value> values =
            RecordedValueServiceFactory.getInstance().getTopDataSeries(point, count, new Date());
        final List<FeedValue> retObj = new ArrayList<FeedValue>(values.size());

        for (final Value v : values) {
          if (!Utils.isEmptyString(v.getData())) {
            try {
              retObj.add(GsonFactory.getInstance().fromJson(v.getData(), FeedValueModel.class));
            } catch (JsonSyntaxException ignored) {

            }
          }
        }
        return retObj;
      }
    } else {
      return new ArrayList<FeedValue>(0);
    }
  }
Example #20
0
  private static void putRequestMap(
      Env env,
      ArrayValue post,
      ArrayValue files,
      HttpServletRequest request,
      boolean addSlashesToValues,
      boolean isAllowUploads) {
    // this call consumes the inputstream
    Map<String, String[]> map = request.getParameterMap();

    if (map == null) return;

    long maxFileSize = Long.MAX_VALUE;

    Value maxFileSizeV = post.get(MAX_FILE_SIZE);
    if (maxFileSizeV.isNull()) maxFileSize = maxFileSizeV.toLong();

    if (isAllowUploads) {
      for (Map.Entry<String, String[]> entry : map.entrySet()) {
        String key = entry.getKey();

        int len = key.length();

        if (len < 10 || !key.endsWith(".filename")) continue;

        String name = key.substring(0, len - 9);

        String[] fileNames = request.getParameterValues(name + ".filename");
        String[] tmpNames = request.getParameterValues(name + ".file");
        String[] mimeTypes = request.getParameterValues(name + ".content-type");

        for (int i = 0; i < fileNames.length; i++) {
          long fileLength = new FilePath(tmpNames[i]).getLength();

          addFormFile(
              env,
              files,
              name,
              fileNames[i],
              tmpNames[i],
              mimeTypes[i],
              fileLength,
              addSlashesToValues,
              maxFileSize);
        }
      }
    }

    ArrayList<String> keys = new ArrayList<String>();

    keys.addAll(request.getParameterMap().keySet());

    Collections.sort(keys);

    for (String key : keys) {
      String[] value = request.getParameterValues(key);

      Post.addFormValue(env, post, key, value, addSlashesToValues);
    }
  }
 public List<String> write() {
   List<String> lines = new ArrayList<String>();
   StringBuilder out = new StringBuilder();
   for (Entry<String, Attribute> attribute : attributes.entrySet()) {
     out.append(attribute.getKey()).append(": ");
     Attribute attributeValue = attribute.getValue();
     if (attributeValue.size() > 1) {
       lines.add(out.toString());
       out.setLength(0);
       for (int i = 0; i < attributeValue.size(); i++) {
         Value value = attributeValue.get(i);
         out.append(" ");
         value.toString(out);
         if (i + 1 < attributeValue.size()) {
           out.append(",");
         }
         lines.add(out.toString());
         out.setLength(0);
       }
     } else {
       attributeValue.toString("", out);
       lines.add(out.toString());
       out.setLength(0);
     }
   }
   return lines;
 }
Example #22
0
  /** Evaluate collect expressions. */
  protected final Value evalCollectNested(EvalContext ctx) {
    // evaluate range
    Value v = fRangeExp.eval(ctx);
    if (v.isUndefined()) return UndefinedValue.instance;
    CollectionValue rangeVal = (CollectionValue) v;

    // prepare result value
    ArrayList<Value> resValues = new ArrayList<Value>();

    // loop over range elements
    for (Value elemVal : rangeVal) {

      // bind element variable to range element, if variable was
      // declared
      if (!fElemVarDecls.isEmpty()) ctx.pushVarBinding(fElemVarDecls.varDecl(0).name(), elemVal);

      // evaluate collect expression
      Value val = fQueryExp.eval(ctx);

      // add element to result
      resValues.add(val);

      if (!fElemVarDecls.isEmpty()) ctx.popVarBinding();
    }

    // result is collection with mapped values
    if (fRangeExp.type().isSequence() || fRangeExp.type().isOrderedSet())
      return new SequenceValue(fQueryExp.type(), resValues);
    else return new BagValue(fQueryExp.type(), resValues);
  }
Example #23
0
  @Override
  public Value visitMULT_DIV_MOD(Verilog2001Parser.MULT_DIV_MODContext ctx) {
    // System.out.println("*/%");
    Value left = visit(ctx.expression(0));
    Value right = visit(ctx.expression(1));
    int mask1 = (1 << left.getSize()) - 1;
    int mask2 = (1 << right.getSize()) - 1;

    switch (ctx.op.getType()) {
      case (Verilog2001Parser.MULT):
        {
          return new Value(
              Integer.valueOf(left.asInt() * right.asInt()),
              (mask1 >= mask2) ? 2 * mask1 : 2 * mask2);
        }
      case (Verilog2001Parser.DIV):
        {
          return new Value(
              Integer.valueOf(left.asInt() / right.asInt()), (mask1 >= mask2) ? mask1 : mask2);
        }
      case (Verilog2001Parser.MOD):
        {
          return new Value(
              Integer.valueOf(left.asInt() % right.asInt()), (mask1 >= mask2) ? mask1 : mask2);
        }
      default:
        {
          System.out.println("Error: Not ADD SUB called: " + ctx.getText());
        }
    }

    return null;
  }
Example #24
0
  /** Evaluate isUnique expression. */
  protected final Value evalIsUnique(EvalContext ctx) {
    // evaluate range
    Value v = fRangeExp.eval(ctx);
    if (v.isUndefined()) return UndefinedValue.instance;
    CollectionValue rangeVal = (CollectionValue) v;

    // collect values for finding duplicates
    Set<Value> values = new HashSet<Value>();

    // loop over range elements
    for (Value elemVal : rangeVal) {

      // bind element variable to range element, if variable was
      // declared
      if (!fElemVarDecls.isEmpty()) ctx.pushVarBinding(fElemVarDecls.varDecl(0).name(), elemVal);

      // evaluate collect expression
      Value val = fQueryExp.eval(ctx);

      if (!fElemVarDecls.isEmpty()) ctx.popVarBinding();

      // stop if duplicate element is found
      if (values.contains(val)) return BooleanValue.FALSE;
      else values.add(val);
    }

    // result is true if no duplicates where found
    return BooleanValue.TRUE;
  }
Example #25
0
  @Override
  public final Expr optimize(final QueryContext qc, final VarScope scp) throws QueryException {
    final Value v = initial(qc);
    if (v != null && v.isEmpty() || emptyPath(v)) return optPre(qc);

    // merge descendant steps
    Expr e = mergeSteps(qc);
    if (e == this && v != null && v.type == NodeType.DOC) {
      // check index access
      e = index(qc, v);
      // rewrite descendant to child steps
      if (e == this) e = children(qc, v);
    }
    // recompile path if it has changed
    if (e != this) return e.compile(qc, scp);

    // set atomic type for single attribute steps to speed up predicate tests
    if (root == null && steps.length == 1 && steps[0] instanceof Step) {
      final Step curr = (Step) steps[0];
      if (curr.axis == ATTR && curr.test.kind == Kind.URI_NAME) curr.seqType(SeqType.NOD_ZO);
    }

    // choose best path implementation and set type information
    final Path path = get(info, root, steps);
    path.size = path.size(qc);
    path.seqType = SeqType.get(steps[steps.length - 1].seqType().type, size);
    return path;
  }
Example #26
0
 @Test
 public void shouldPerformsActionOnEachElement() {
   final int[] consumer = new int[1];
   final Value<Integer> value = of(1, 2, 3);
   value.forEach(i -> consumer[0] += i);
   assertThat(consumer[0]).isEqualTo(value.isSingleValued() ? 1 : 6);
 }
Example #27
0
  /** Test of removeHandlerForEvent method, of class HexEventRegister. */
  @Test
  public void testRemoveHandlerForEvent() {
    Class type = HexEvent.class;

    final Value v = new Value();
    v.value = "fix";

    HexEventHandler handler =
        new HexEventHandler() {
          @Override
          public void handle(HexEvent event) throws Exception {
            v.value = "changed";
          }
        };

    String[] names = null;
    HexEventRegister instance = HexEventRegister.getInstance();

    instance.registerHandlerForEvent(type, handler, names);

    instance.triggerEvent(new HexEvent("one"));

    assertEquals(v.value, "changed");

    v.value = "fix";

    instance.removeHandlerForEvent(type, handler.getID());

    instance.triggerEvent(new HexEvent("one"));

    assertEquals(v.value, "fix");
  }
Example #28
0
 @Test
 public void shouldConvertNonEmptyValueToMatchValue() {
   final Value<Integer> value = of(1);
   final String actual =
       value.match().when((Value<Integer> v) -> v.getOrElse(-1) == 1).then("ok").getOrElse("nok");
   assertThat(actual).isEqualTo("ok");
 }
Example #29
0
  /**
   * Test sending of HTTP GET requests.
   *
   * @throws Exception exception
   */
  @Test
  public void postGet() throws Exception {
    // GET1 - just send a GET request
    try (final QueryProcessor qp =
        new QueryProcessor(
            _HTTP_SEND_REQUEST.args("<http:request method='get' href='" + REST_ROOT + "'/>"),
            ctx)) {
      final Value v = qp.value();
      checkResponse(v, 2, HttpURLConnection.HTTP_OK);

      assertEquals(NodeType.DOC, v.itemAt(1).type);
    }

    // GET2 - with override-media-type='text/plain'
    try (final QueryProcessor qp =
        new QueryProcessor(
            _HTTP_SEND_REQUEST.args(
                "<http:request method='get' override-media-type='text/plain'/>", REST_ROOT),
            ctx)) {
      final Value v = qp.value();
      checkResponse(v, 2, HttpURLConnection.HTTP_OK);

      assertEquals(AtomType.STR, v.itemAt(1).type);
    }

    // Get3 - with status-only='true'
    try (final QueryProcessor qp =
        new QueryProcessor(
            _HTTP_SEND_REQUEST.args("<http:request method='get' status-only='true'/>", REST_ROOT),
            ctx)) {
      checkResponse(qp.value(), 1, HttpURLConnection.HTTP_OK);
    }
  }
 public void caseCastExpr(CastExpr arg0) {
   Type cast_type = arg0.getCastType();
   OpenCLType ocl_type = new OpenCLType(cast_type);
   m_output.append("(" + ocl_type.getCudaTypeString() + ") ");
   Value rhs = arg0.getOp();
   rhs.apply(this);
 }