/**
   * Create the validate Netconf operation.
   *
   * @param session The active session.
   * @param source The source Container.
   * @throws CapabilityException Throw this exception if the server does not have the :validate:1.0
   *     capability. Throw this exception if the server does not have the :candidate:1.0 capability
   *     and the source container is 'candidate'.. Throw this exception if the server does not have
   *     the :startup:1.0 capability and the source container is 'startup'.
   */
  public Validate(Session session, Datastore source) throws CapabilityException {
    super(session);
    if (!Session.VALIDATE_1_0.isPresentOnServer(session))
      throw new CapabilityException(
          "This capability is not supported by server: "
              + Session.VALIDATE_1_0
              + "; Please don't use this class with any operation.");

    if (source.equals(Datastore.candidate) && !Session.CANDIDATE_1_0.isPresentOnServer(session))
      throw new CapabilityException(
          "This capability is not supported by server: "
              + Session.CANDIDATE_1_0
              + "; Please don't specific a <candidate> container as target or source in any operation.");

    if (source.equals(Datastore.startup) && !Session.STARTUP_1_0.isPresentOnServer(session))
      throw new CapabilityException(
          "This capability is not supported by server: "
              + Session.STARTUP_1_0
              + "; Please don't specific a <startup> container as target or source in any operation.");

    operation = new Rpc(Session.VALIDATE_1_0, "validate");

    Container sou;
    sou = operation.getInput().linkContainer(operation.createContainer("source"));
    Leaf s = sou.linkLeaf(operation.createLeaf(source.getName()));
    sou.assignLeaf(s, "");
  }
    void assertInstance(MyRelation rel, CallingContext cc)
        throws ODKEntityPersistException, ODKOverQuotaException {
      Datastore ds = cc.getDatastore();
      User user = cc.getCurrentUser();

      for (int i = 0; i < SET_SIZE; ++i) {
        MyRelation element = ds.createEntityUsingRelation(rel, user);
        element.setStringField(MyRelation.fieldStr, str);
        element.setLongField(MyRelation.fieldInt, Long.valueOf(i));
        element.setNumericField(MyRelation.fieldDbl, bd);
        element.setDateField(MyRelation.fieldDate, d);
        element.setBooleanField(MyRelation.fieldBool, b);

        ds.putEntity(element, user);
      }

      for (int i = 0; i < SET_SIZE; ++i) {
        MyRelation element = ds.createEntityUsingRelation(rel, user);
        element.setStringField(MyRelation.fieldStr, str);
        element.setLongField(MyRelation.fieldInt, Long.valueOf(i));
        element.setNumericField(MyRelation.fieldDbl, BigDecimal.valueOf(i));
        element.setDateField(MyRelation.fieldDate, d);
        element.setBooleanField(MyRelation.fieldBool, b);

        ds.putEntity(element, user);
      }
    }
 static final synchronized MyRelation assertRelation(CallingContext cc)
     throws ODKDatastoreException {
   MyRelation relationPrototype;
   Datastore ds = cc.getDatastore();
   User user = cc.getUserService().getDaemonAccountUser();
   relationPrototype = new MyRelation(ds.getDefaultSchemaName());
   ds.assertRelation(relationPrototype, user); // may throw exception...
   // at this point, the prototype has become fully populated
   return relationPrototype; // set static variable only upon success...
 }
Example #4
0
  public void completeInfo(final MachineDto dto) {
    HyperVisor h = new HyperVisor();
    h.setIp(dto.getIp());
    h.setIpService(dto.getIpService());
    if (dto.getType() != null) {
      h.setType(new HyperVisorType(dto.getType()));
    }
    h.setUser(dto.getUser());
    h.setPassword(dto.getPassword());
    if (dto.getPort() != null) {
      h.setPort(dto.getPort());
    }
    h.setId(dto.getId());
    h.setName(dto.getName());
    this.setHypervisor(h);

    if (dto.getDatastores() != null && !dto.getDatastores().getCollection().isEmpty()) {
      this.setDatastores(new HashSet<Datastore>());

      for (DatastoreDto dataDto : dto.getDatastores().getCollection()) {
        Datastore datastore = new Datastore();
        datastore.setDatastoreUUID(dataDto.getDatastoreUUID());
        datastore.setDirectory(dataDto.getDirectory());
        datastore.setEnabled(dataDto.isEnabled());
        datastore.setId(dataDto.getId());
        datastore.setName(dataDto.getName());
        datastore.setSize(dataDto.getSize());
        datastore.setUsedSize(dataDto.getUsedSize());
        datastore.setUUID(dataDto.getRootPath());

        this.getDatastores().add(datastore);
      }
    }
  }
Example #5
0
 /** @throws Exception */
 @Test(expected = EntityNotFoundRuntimeException.class)
 public void entityMapToModelListWhenNoEntityIsFound() throws Exception {
   Key key = Datastore.createKey("Hoge", 1);
   Key key2 = Datastore.createKey("Hoge", 2);
   Key key3 = Datastore.createKey("Hoge", 3);
   Entity entity = new Entity(key);
   Entity entity2 = new Entity(key2);
   Map<Key, Entity> map = new HashMap<Key, Entity>();
   map.put(key2, entity2);
   map.put(key, entity);
   DatastoreUtil.entityMapToModelList(meta, Arrays.asList(key, key2, key3), map);
 }
  @Test
  public void testCase1int() throws ODKDatastoreException {

    CallingContext cc = TestContextFactory.getCallingContext();
    Datastore ds = cc.getDatastore();
    User user = cc.getCurrentUser();
    MyRelation rel = MyRelation.assertRelation(cc);

    Query query = ds.createQuery(rel, "QueryResultTest.testCase1int", user);

    List<?> values = query.executeDistinctValueForDataField(MyRelation.fieldInt);
    assertEquals(SET_SIZE, values.size());
  }
  /** Displays the existing messages and offer the option to send a new one. */
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    resp.setContentType("text/html");
    resp.setCharacterEncoding("utf-8");
    PrintWriter out = resp.getWriter();

    out.print("<html><body>");
    out.print("<head>");
    out.print("  <title>Agnes Backdoor</title>");
    out.print("  <link rel='icon' href='/favicon.ico'/>");
    out.print("  <meta charset='utf-8' />");
    out.print("</head>");
    out.print(
        "<body style=\"background-image:url('matrix.png'); color:white;text-align:center\"><div style=\"display:inline-block;background-color: rgba(0%, 0%, 0%, 0.7)\">");
    String status = (String) req.getAttribute(ATTRIBUTE_STATUS);
    if (status != null) {
      out.print(status);
    }
    int total = Datastore.getTotalDevices();
    if (total == 0) {
      out.print("<h2>No slaves registered!</h2>");
    } else {
      out.print("<h3>" + total + " slave devices active!</h3>");
      out.print("<h2>Override AI behavior (Version code >= 15):</h2>");
      out.print(
          "<p>Last message: <span style='color: #E00; font-size: 20;'>"
              + Datastore.readLastMessage()
              + "</span></p>");
      out.print("<form name='form' method='POST' action='sendAll'>");
      out.print("<textarea name='message' cols='40' rows='4'></textarea><br />");
      out.print(
          "<input type='checkbox' name='notify' value='true' /> Flood their notifications<br />");
      out.print(
          "<input type='checkbox' name='vibrate' value='true' /> Vibrate-shock their pockets<br />");
      out.print(
          "<input type='checkbox' name='append' value='false' /> Append message to dialog<br />");
      out.print("<br />Choose the UI<br />");
      out.print("Agnes <input type='radio' name='ui_name' value='Agnes'>");
      out.print("Eddie <input type='radio' name='ui_name' value='Eddie' checked='checked'><br />");
      out.print("<input type='submit' value='Push to all humans' />");
      out.print("</form>");
      out.print("<h2>Update hard-wired personality files:</h2>");
      out.print("<form name='form' method='POST' action='sendAll'>");
      out.print("<input type='hidden' name='update' value='true' />");
      out.print("<input type=\"submit\" value=\"Let's hope she won't notice\" />");
      out.print("</form>");
    }
    out.print("</div></body></html>");
    resp.setStatus(HttpServletResponse.SC_OK);
  }
Example #8
0
  /** Displays the existing messages and offer the option to send a new one. */
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    resp.setContentType("text/html");
    PrintWriter out = resp.getWriter();

    out.print("<html><body>");
    out.print("<head>");
    out.print("  <title>GCM</title>");
    out.print("  <meta charset='utf-8' />");
    out.print("  <link rel='icon'/>");
    out.print("</head>");
    String status = (String) req.getAttribute(ATTRIBUTE_STATUS);
    if (status != null) {
      out.print(status);
    }
    List<String> devices = Datastore.getDevices();
    if (devices.isEmpty()) {
      out.print("<h2>No devices registered!</h2>");
    } else {
      out.print("<h2>" + devices.size() + " device(s) registered!</h2>");
      out.print("<form name='form' method='POST' action='sendAll'>");
      out.print("<input type='test' name='message' />");
      out.print("<input type='submit' value='Send Message' />");
      out.print("</form>");
    }
    out.print("</body></html>");
    resp.setStatus(HttpServletResponse.SC_OK);
  }
Example #9
0
  /** Displays the existing messages and offer the option to send a new one. */
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    resp.setContentType("text/html");
    PrintWriter out = resp.getWriter();

    out.print("<html><body>");
    out.print("<head>");
    out.print("  <title>GCM Demo</title>");
    out.print("  <link rel='icon' href='favicon.png'/>");
    out.print("</head>");
    String status = (String) req.getAttribute(ATTRIBUTE_STATUS);
    if (status != null) {
      out.print(status);
    }
    int total = Datastore.getTotalDevices();
    if (total == 0) {
      out.print("<h2>No devices registered!</h2>");
    } else {
      out.print("<h2>" + total + " device(s) registered!</h2>");
      out.print("<form name='form' method='POST' action='sendAll'>");
      out.print("<input type='submit' value='Send Message' />");
      out.print("</form>");
    }
    out.print("</body></html>");
    resp.setStatus(HttpServletResponse.SC_OK);
  }
Example #10
0
 /** @throws Exception */
 @SuppressWarnings("unchecked")
 @Test
 public void getModelMeta() throws Exception {
   ModelMeta<Hoge> modelMeta = DatastoreUtil.getModelMeta(Hoge.class);
   assertThat(modelMeta, is(notNullValue()));
   assertThat(modelMeta, is(sameInstance((ModelMeta) Datastore.getModelMeta(Hoge.class))));
 }
Example #11
0
  /**
   * Searches for {@link Dish}es belonging to a {@link Restauarnt} using the supplied search terms
   *
   * @param queryWords terms to search with
   * @param restKey {@link Key} to the {@link Restaurant} to search within
   * @param maxResults maximum number of results to return
   * @return {@link Collection} of {@link Dish}es
   */
  @SuppressWarnings("unchecked")
  public static Set<Dish> searchDishesByRestaurant(
      String[] queryWords, Key restKey, int maxResults) {
    List<Object> paramList = null;
    String paramS = "";
    String queryS = "";
    final String queryString = "SELECT key FROM " + Dish.class.getName();
    final Query q = PMF.get().getPersistenceManager().newQuery(queryString);

    if (queryWords.length > 0) {
      paramList = new ArrayList<Object>();
      queryS += "restaurant == restParam";
      paramS = Key.class.getName() + " restParam";
      paramList.add(restKey);

      for (int i = 0; i < queryWords.length; i++) {
        queryS += " && searchTerms.contains(s" + i + ")";
        paramS += ", String s" + i;
        paramList.add(queryWords[i]);
      }

      q.setFilter(queryS);
      q.declareParameters(paramS);

      return Datastore.get(new HashSet<Key>((List<Key>) q.executeWithArray(paramList.toArray())));
    }

    return new HashSet<Dish>();
  }
Example #12
0
  /**
   * Returns whether user is allowed to edit the entity if he created the entity
   *
   * @param <T> any object that extends TDPersistable
   * @param tdUser logged in user
   * @param t instance of T
   * @return
   */
  @SuppressWarnings("unchecked")
  public static <T extends TDPersistable> boolean isAccessible(Long id, T t) {
    boolean isAccessAllowed = true;
    try {
      TDUser tdUser = TDUserService.getUser();
      if (id != null && null != tdUser && tdUser.getRole() == TDUserRole.ROLE_STANDARD) {
        try {
          T returnValT = (T) Datastore.get(KeyFactory.createKey(t.getClass().getSimpleName(), id));
          if (returnValT != null) {
            if (returnValT.getCreator().getId() != Long.valueOf(tdUser.getKey().getId())) {
              isAccessAllowed = false;
            }
          }
        } catch (JDOObjectNotFoundException jdoe) {
          isAccessAllowed = false;
        } catch (Exception e) {
          isAccessAllowed = false;
        }
      }
      return isAccessAllowed;

    } catch (UserNotLoggedInException e) {
      return false;
    } catch (UserNotFoundException e) {
      return false;
    }
  }
Example #13
0
 /** @throws Exception */
 @Test
 public void bytesToEntity() throws Exception {
   Entity entity = new Entity(Datastore.createKey("Hoge", 1));
   byte[] bytes = DatastoreUtil.entityToBytes(entity);
   Entity entity2 = DatastoreUtil.bytesToEntity(bytes);
   assertThat(entity2, is(notNullValue()));
   assertThat(entity2, is(entity));
 }
Example #14
0
 /**
  * Gets the latest {@link Review} submitted by a {@link TDUser}
  *
  * @param userKey {@link Key} of the {@link TDUser}
  * @return the {@link Review}
  */
 public static Review getLatestReviewByUser(Key userKey) {
   final Key reviewKey = getLatestReviewKeyByUser(userKey);
   if (null != reviewKey) {
     return Datastore.get(reviewKey);
   } else {
     return null;
   }
 }
Example #15
0
 /**
  * Get the latest {@link Review} written for a {@link Dish}.
  *
  * @param dishKey {@link Key} of the {@link Dish}
  * @return the {@link Review}
  */
 public static Review getLatestReviewByDish(Key dishKey) {
   final Key reviewKey = getLatestReviewKeyByDish(dishKey);
   if (null != reviewKey) {
     return Datastore.get(getLatestReviewKeyByDish(dishKey));
   } else {
     return null;
   }
 }
Example #16
0
 /**
  * Get the first review written about a dish.
  *
  * @param dishKey {@link Key} of the {@link Dish}
  * @return the {@link Review}
  */
 public static Review getFirstReviewByDish(Key dishKey) {
   final Key reviewKey = getFirstReviewKeyByDish(dishKey);
   if (null != reviewKey) {
     return (Review) Datastore.get(reviewKey);
   } else {
     return null;
   }
 }
  @Test
  public void testCase2() throws ODKDatastoreException {

    CallingContext cc = TestContextFactory.getCallingContext();
    Datastore ds = cc.getDatastore();
    User user = cc.getCurrentUser();
    MyRelation rel = MyRelation.assertRelation(cc);

    Query query = ds.createQuery(rel, "QueryResultTest.testCase2", user);
    query.addFilter(MyRelation.fieldInt, FilterOperation.GREATER_THAN, SET_SIZE - 2);
    query.addSort(MyRelation.fieldDate, Direction.ASCENDING);
    query.addSort(MyRelation.fieldDbl, Direction.DESCENDING);

    Set<String> pkSet = new HashSet<String>();

    int len = 0;
    QueryResult result = query.executeQuery(null, 10);
    len += result.getResultList().size();
    assertEquals(true, result.hasMoreResults());
    assertEquals(10, result.getResultList().size());

    for (CommonFieldsBase cb : result.getResultList()) {
      assertEquals(false, pkSet.contains(cb.getUri()));
      pkSet.add(cb.getUri());
      ((MyRelation) cb).print();
    }
    boolean done = false;
    QueryResumePoint startCursor = result.getResumeCursor();
    while (!done) {
      System.out.println("Issuing follow-up query");
      result = query.executeQuery(startCursor, 20);
      len += result.getResultList().size();
      startCursor = result.getResumeCursor();
      done = !result.hasMoreResults();

      for (CommonFieldsBase cb : result.getResultList()) {
        assertEquals(false, pkSet.contains(cb.getUri()));
        pkSet.add(cb.getUri());
        ((MyRelation) cb).print();
      }
    }

    assertEquals(false, result.hasMoreResults());
    assertEquals(2 * values.length, len);
    System.out.println("done with testCase2");
  }
Example #18
0
  @Override
  public PhysicalmachineHB toPojoHB() {
    PhysicalmachineHB physicalMachineHB = new PhysicalmachineHB();

    physicalMachineHB.setDataCenter(getDataCenter().toPojoHB());

    physicalMachineHB.setIdPhysicalMachine(getId());
    physicalMachineHB.setName(StringUtils.substring(getName(), 0, 255)); // a fully qualified
    // domain name (FQDN)
    // is 255 octets -
    // where any one label
    // can be 63 octets
    // long at most (RFC
    // 2181)
    physicalMachineHB.setDescription(getDescription());
    physicalMachineHB.setCpu(getCpu());
    physicalMachineHB.setCpuUsed(getCpuUsed());
    physicalMachineHB.setRam(getRam());
    physicalMachineHB.setRamUsed(getRamUsed());
    Rack rack = (Rack) getAssignedTo();
    physicalMachineHB.setRack(rack.toPojoHB());
    physicalMachineHB.setIdState(getIdState());
    physicalMachineHB.setVswitchName(vswitchName);
    physicalMachineHB.setInitiatorIQN(initiatorIQN);
    physicalMachineHB.setIpmiIp(ipmiIp);
    physicalMachineHB.setIpmiPort(ipmiPort);
    physicalMachineHB.setIpmiUser(ipmiUser);
    physicalMachineHB.setIpmiPassword(ipmiPassword);
    Set<DatastoreHB> datastoresHB = new HashSet<DatastoreHB>();
    if (datastores != null) {
      for (Datastore datastore : datastores) {
        datastoresHB.add(datastore.toPojoHB());
      }
    }
    physicalMachineHB.setDatastoresHB(datastoresHB);
    if (idEnterprise != null) {
      physicalMachineHB.setIdEnterprise(idEnterprise.intValue() != 0 ? idEnterprise : null);
    }

    if (hypervisor != null) {
      physicalMachineHB.setHypervisor(hypervisor.toPojoHB(physicalMachineHB));
    }

    return physicalMachineHB;
  }
Example #19
0
  /**
   * Returns the most recent <code>numDishes</code> {@link Dish}es added
   *
   * @param numDishes number of {@link Dish}es to return
   * @return {@link List} of {@link Dish}es ordered from newest to oldest
   */
  @SuppressWarnings("unchecked")
  public static Set<Dish> getNewestDishes(int numDishes) {
    final String query = "SELECT key FROM " + Dish.class.getName();
    Query q = PMF.get().getPersistenceManager().newQuery(query);
    q.setOrdering("dateCreated desc");
    q.setRange("0, " + numDishes);

    return Datastore.get((Collection<Key>) q.execute());
  }
Example #20
0
 /** @throws Exception */
 @Test
 public void entityMapToModelMap() throws Exception {
   Key key = Datastore.createKey("Hoge", 1);
   Key key2 = Datastore.createKey("Hoge", 2);
   Key key3 = Datastore.createKey("Hoge", 3);
   Entity entity = new Entity(key);
   Entity entity2 = new Entity(key2);
   Entity entity3 = new Entity(key3);
   Map<Key, Entity> map = new HashMap<Key, Entity>();
   map.put(key3, entity3);
   map.put(key2, entity2);
   map.put(key, entity);
   Map<Key, Hoge> map2 = DatastoreUtil.entityMapToModelMap(meta, map);
   assertThat(map2.size(), is(3));
   assertThat(map2.get(key).getKey(), is(key));
   assertThat(map2.get(key2).getKey(), is(key2));
   assertThat(map2.get(key3).getKey(), is(key3));
 }
Example #21
0
 /** @throws Exception */
 @Test
 public void entityMapToModelList() throws Exception {
   Key key = Datastore.createKey("Hoge", 1);
   Key key2 = Datastore.createKey("Hoge", 2);
   Key key3 = Datastore.createKey("Hoge", 3);
   Entity entity = new Entity(key);
   Entity entity2 = new Entity(key2);
   Entity entity3 = new Entity(key3);
   Map<Key, Entity> map = new HashMap<Key, Entity>();
   map.put(key3, entity3);
   map.put(key2, entity2);
   map.put(key, entity);
   List<Hoge> list = DatastoreUtil.entityMapToModelList(meta, Arrays.asList(key, key2, key3), map);
   assertThat(list.size(), is(3));
   assertThat(list.get(0).getKey(), is(key));
   assertThat(list.get(1).getKey(), is(key2));
   assertThat(list.get(2).getKey(), is(key3));
 }
Example #22
0
  /**
   * Find {@link Source}s by name with a limit
   *
   * @param name - the source's name
   * @param limit - limit results
   * @return a {@link Set} of related {@link Source}s
   */
  @SuppressWarnings("unchecked")
  public static Set<Source> searchSourcebyName(String name, int limit) {

    final String queryString = "SELECT key FROM " + Source.class.getName();
    final Query q = PMF.get().getPersistenceManager().newQuery(queryString);
    q.setFilter("name == :p");
    q.setRange("0, " + limit);

    return Datastore.get(new HashSet<Key>((List<Key>) q.execute(name.toLowerCase())));
  }
Example #23
0
  /**
   * Search tags by name and types
   *
   * @param stringTag name of a single tag
   * @param types {@link Set} of tag types
   * @param limit maximum number of results
   * @return {@link Set} of {@link Tag}s
   */
  @SuppressWarnings("unchecked")
  public static Set<Tag> searchTagsByNameType(String stringTag, Set<Integer> types, int limit) {

    final String queryString = "SELECT key FROM " + Tag.class.getName();
    final Query q = PMF.get().getPersistenceManager().newQuery(queryString);
    q.setFilter("searchTerms.contains(:searchTerm) && :typeParam.contains(type)");
    q.setRange("0, " + limit);

    return Datastore.get(
        new HashSet<Key>((Collection<Key>) q.execute(stringTag.toLowerCase(), types)));
  }
Example #24
0
  /**
   * Gets the top <code>numDishes</code> {@link Dish}es ranked from most to least positive reviews
   *
   * @param numDishes number of {@link Dish}es to return
   * @return {@link List} of {@link Dish}es
   */
  @SuppressWarnings("unchecked")
  public static List<Dish> getTopDishes(int numDishes) {
    final String query = "SELECT key FROM " + Dish.class.getName();
    Query q = PMF.get().getPersistenceManager().newQuery(query);
    q.setOrdering("posReviews desc");
    q.setRange("0," + numDishes);

    final Set<Dish> results = Datastore.get((Collection<Key>) q.execute());
    final List<Dish> toReturn = new ArrayList<Dish>(results);
    Collections.sort(toReturn, new DishPosReviewsComparator());

    return toReturn;
  }
Example #25
0
  /**
   * Gets the top <code>numUsers</code> sorted by most to least ratings.
   *
   * @param numUsers number of {@link TDUser}s to return
   * @return {@link List} of {@link TDUser}s
   */
  @SuppressWarnings("unchecked")
  public static List<TDUser> getTopUsers(int numUsers) {
    final String query = "SELECT key FROM " + TDUser.class.getName();
    Query q = PMF.get().getPersistenceManager().newQuery(query);
    q.setOrdering("numReviews desc");
    q.setRange("0, " + numUsers);

    final Set<TDUser> results = Datastore.get((Collection<Key>) q.execute());
    final List<TDUser> toReturn = new ArrayList<TDUser>(results);
    // Collections.sort(toReturn, )

    return toReturn;
  }
Example #26
0
 /**
  * Gets the direction of the latest {@link Review} by a given {@link TDUser} for a given {@link
  * Dish}.
  *
  * @param userKey {@link Key} of the {@link TDUser}
  * @param dishKey {@link Key} of the {@link Dish}
  * @return {@link Review#POSITIVE_DIRECTION}, {@link Review#NEGATIVE_DIRECTION}, or 0 if none
  *     found
  */
 public static int getLatestUserVoteByDish(Key userKey, Key dishKey) {
   final Key revKey = getLatestReviewKeyByUserDish(userKey, dishKey);
   if (null != revKey) {
     final Review review = Datastore.get(revKey);
     if (null != review) {
       return review.getDirection();
     } else {
       return 0;
     }
   } else {
     return 0;
   }
 }
Example #27
0
  /**
   * Gets the top <code>numRestaurantss</code> {@link Restaurant}s ranked from most to least
   * positive reviews <br>
   * <b>Note: this does not actually return the top X restaurants, just a random X restaurants!</b>
   *
   * @param numRestaurants number of {@link Restaurant}s to return
   * @return {@link List} of {@link Restaurant}s
   */
  @SuppressWarnings("unchecked")
  public static List<Restaurant> getTopRestaurants(int numRestaurants) {
    final String query = "SELECT key FROM " + Restaurant.class.getName();
    Query q = PMF.get().getPersistenceManager().newQuery(query);
    // TODO: return a query that actually chooses the X highest rated
    // restaurants
    // q.setOrdering("posReviews desc");
    q.setRange("0," + numRestaurants);

    final Set<Restaurant> results = Datastore.get((Collection<Key>) q.execute());
    final List<Restaurant> toReturn = new ArrayList<Restaurant>(results);
    Collections.sort(toReturn, new RestaurantPosReviewsComparator());

    return toReturn;
  }
Example #28
0
  /**
   * Search through all {@link Tag}s given an array of {@link String} search terms
   *
   * @param queryWords array of {@link String} terms to search with
   * @param maxResults maximum number of results
   * @return list of Tags matching the search terms
   */
  @SuppressWarnings("unchecked")
  public static Set<Tag> searchTags(String[] queryWords, int maxResults) {
    // TODO: can this be replaced by a generic searchItems somehow?
    // Using a TDSearchable Interface would work

    final String queryString = "SELECT key FROM " + Tag.class.getName();
    final Query query = PMF.get().getPersistenceManager().newQuery(queryString);
    query.setFilter("searchTerms.contains(:searchParam)");
    query.setRange(0, maxResults);

    if (queryWords.length > 0) {
      return Datastore.get((Collection<Key>) query.execute(Arrays.asList(queryWords)));
    }

    return new HashSet<Tag>();
  }
Example #29
0
  /** Processes the request to add a new message. */
  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws IOException, ServletException {

    List<String> devices = Datastore.getDevices();

    String status;
    if (devices.isEmpty()) {
      status = "Message ignored as there is no device registered!";
    } else {
      // NOTE: check below is for demonstration purposes; a real application
      // could always send a multicast, even for just one recipient
      if (devices.size() == 1) {
        // send a single message using plain post

        String registrationId = devices.get(0);

        Message message = new Message.Builder().build();
        Result result = sender.send(message, registrationId, 5);

        status = "Sent message to one device: " + result;
      } else {
        // send a multicast message using JSON
        // must split in chunks of 1000 devices (GCM limit)
        int total = devices.size();
        List<String> partialDevices = new ArrayList<String>(total);
        int counter = 0;
        int tasks = 0;
        for (String device : devices) {
          counter++;
          partialDevices.add(device);
          int partialSize = partialDevices.size();
          if (partialSize == MULTICAST_SIZE || counter == total) {
            asyncSend(partialDevices);
            partialDevices.clear();
            tasks++;
          }
        }
        status = "Asynchronously sending " + tasks + " multicast messages to " + total + " devices";
      }
    }
    req.setAttribute(HomeServlet.ATTRIBUTE_STATUS, status.toString());
    getServletContext().getRequestDispatcher("/home").forward(req, resp);
  }
  @Test
  public void testCase3() throws ODKDatastoreException {

    CallingContext cc = TestContextFactory.getCallingContext();
    Datastore ds = cc.getDatastore();
    User user = cc.getCurrentUser();
    MyRelation rel = MyRelation.assertRelation(cc);
    System.out.println("start testCase3");

    Query query = ds.createQuery(rel, "QueryResultTest.testCase3(1st)", user);
    query.addFilter(MyRelation.fieldDbl, FilterOperation.EQUAL, new BigDecimal("0.9"));
    query.addFilter(MyRelation.fieldBool, FilterOperation.EQUAL, true);
    query.addSort(MyRelation.fieldInt, Direction.ASCENDING);
    query.addSort(MyRelation.fieldDate, Direction.DESCENDING);

    Query backquery = ds.createQuery(rel, "QueryResultTest.testCase3(2nd)", user);
    backquery.addFilter(MyRelation.fieldDbl, FilterOperation.EQUAL, new BigDecimal("0.9"));
    backquery.addFilter(MyRelation.fieldBool, FilterOperation.EQUAL, true);
    backquery.addSort(MyRelation.fieldInt, Direction.DESCENDING);
    backquery.addSort(MyRelation.fieldDate, Direction.ASCENDING);

    Set<String> pkTotalSet = new HashSet<String>();

    List<String> pkOrdering = new ArrayList<String>();

    int TOTAL_SIZE = 3 * SET_SIZE;
    int fetchSizes[] = {1, 2, 1021, 303, 101, 2831};
    int idxFetch = 4;
    int len = 0;
    QueryResult result = query.executeQuery(null, fetchSizes[idxFetch]);
    len += result.getResultList().size();
    assertEquals(true, result.hasMoreResults());
    assertEquals(fetchSizes[idxFetch], result.getResultList().size());

    System.out.println("Accumulating forward query results");
    for (CommonFieldsBase cb : result.getResultList()) {
      assertEquals(false, pkOrdering.contains(cb.getUri()));
      assertEquals(false, pkTotalSet.contains(cb.getUri()));
      pkOrdering.add(cb.getUri());
      pkTotalSet.add(cb.getUri());
      ((MyRelation) cb).print();
    }

    System.out.println("Verifying initial backward query is empty");
    QueryResult backResult = backquery.executeQuery(result.getBackwardCursor(), pkOrdering.size());
    assertEquals(false, backResult.hasMoreResults());
    assertEquals(0, backResult.getResultList().size());

    boolean notFirst = false;
    boolean done = false;
    QueryResumePoint startCursor = result.getResumeCursor();
    while (!done) {
      idxFetch = (idxFetch + 1) % fetchSizes.length;
      System.out.println("Issuing follow-up query");
      result = query.executeQuery(startCursor, fetchSizes[idxFetch]);
      len += result.getResultList().size();
      startCursor = result.getResumeCursor();
      done = !result.hasMoreResults();

      System.out.println("Verifying backward query against ordering of earlier result");
      backResult = backquery.executeQuery(result.getBackwardCursor(), pkOrdering.size());
      assertEquals(notFirst, backResult.hasMoreResults());
      notFirst = true;
      assertEquals(pkOrdering.size(), backResult.getResultList().size());
      for (int i = 0; i < pkOrdering.size(); ++i) {
        CommonFieldsBase cb = backResult.getResultList().get(i);
        ((MyRelation) cb).print();
        assertEquals(pkOrdering.get(pkOrdering.size() - i - 1), cb.getUri());
      }

      System.out.println("Accumulating forward query results");
      pkOrdering.clear();
      for (CommonFieldsBase cb : result.getResultList()) {
        assertEquals(false, pkOrdering.contains(cb.getUri()));
        assertEquals(false, pkTotalSet.contains(cb.getUri()));
        pkOrdering.add(cb.getUri());
        pkTotalSet.add(cb.getUri());
        ((MyRelation) cb).print();
      }
    }

    idxFetch = (idxFetch + 1) % fetchSizes.length;
    System.out.println("Before Issuing (what should be empty) follow-up query");
    result = query.executeQuery(startCursor, fetchSizes[idxFetch]);
    len += result.getResultList().size();
    startCursor = result.getResumeCursor();
    done = !result.hasMoreResults();

    System.out.println("Verifying backward query against ordering of earlier result");
    // backquery should match existing data
    backResult = backquery.executeQuery(result.getBackwardCursor(), pkOrdering.size());
    assertEquals(true, backResult.hasMoreResults());
    assertEquals(pkOrdering.size(), backResult.getResultList().size());
    for (int i = 0; i < pkOrdering.size(); ++i) {
      CommonFieldsBase cb = backResult.getResultList().get(i);
      ((MyRelation) cb).print();
      assertEquals(pkOrdering.get(pkOrdering.size() - i - 1), cb.getUri());
    }

    assertEquals(false, result.hasMoreResults());
    assertEquals(0, result.getResultList().size());

    idxFetch = (idxFetch + 1) % fetchSizes.length;
    System.out.println("Before Re-Issuing (what should be empty) follow-up query");
    // this should be an empty list
    result = query.executeQuery(startCursor, fetchSizes[idxFetch]);
    assertEquals(false, result.hasMoreResults());
    assertEquals(0, result.getResultList().size());

    System.out.println("Verifying backward query (again) against ordering of earlier result");
    // backquery should match existing data
    backResult = backquery.executeQuery(result.getBackwardCursor(), pkOrdering.size());
    assertEquals(true, backResult.hasMoreResults());
    assertEquals(pkOrdering.size(), backResult.getResultList().size());
    for (int i = 0; i < pkOrdering.size(); ++i) {
      CommonFieldsBase cb = backResult.getResultList().get(i);
      ((MyRelation) cb).print();
      assertEquals(pkOrdering.get(pkOrdering.size() - i - 1), cb.getUri());
    }

    assertEquals(TOTAL_SIZE, len);
  }