Exemple #1
12
  public String toXMLString(java.util.HashMap domMap) {
    StringBuffer sb = new StringBuffer();
    sb.append("<class type=\"" + this.getClass().getName() + "\" ");
    sb.append(" id=\"" + this.getId() + "\"");
    sb.append(
        " source=\"" + ims.configuration.EnvironmentConfig.getImportExportSourceName() + "\" ");
    sb.append(" classVersion=\"" + this.getClassVersion() + "\" ");
    sb.append(" component=\"" + this.getIsComponentClass() + "\" >");

    if (domMap.get(this) == null) {
      domMap.put(this, this);
      sb.append(this.fieldsToXMLString(domMap));
    }
    sb.append("</class>");

    String keyClassName = "Summary";
    String externalSource = ims.configuration.EnvironmentConfig.getImportExportSourceName();
    ims.configuration.ImportedObject impObj =
        (ims.configuration.ImportedObject)
            domMap.get(keyClassName + "_" + externalSource + "_" + this.getId());
    if (impObj == null) {
      impObj = new ims.configuration.ImportedObject();
      impObj.setExternalId(this.getId());
      impObj.setExternalSource(externalSource);
      impObj.setDomainObject(this);
      impObj.setLocalId(this.getId());
      impObj.setClassName(keyClassName);
      domMap.put(keyClassName + "_" + externalSource + "_" + this.getId(), impObj);
    }

    return sb.toString();
  }
Exemple #2
1
  /**
   * Load Default FontStylesCollection, singleton 1) if no citation style is given, return default
   * {@link FontStylesCollection} 2) if citation style is given, check citation style directory. If
   * there is a citation style specific {@link FontStylesCollection} in the citation style directory
   * FontStylesCollection, get it; if not - get default FontStylesCollection
   *
   * @param cs - citation style
   * @return {@link FontStylesCollection}
   * @throws CitationStyleManagerException
   */
  public static FontStylesCollection loadFontStylesCollection(String cs) {
    // get default FontStyleCollection from __Default__ element for empty cs
    if (cs == null || "".equals(cs.trim())) return loadFontStylesCollection("__Default__");

    if (fsc.containsKey(cs)) return fsc.get(cs);

    try {
      // load __Default__ collection
      if ("__Default__".equalsIgnoreCase(cs)) {
        fsc.put(
            cs,
            FontStylesCollection.loadFromXml(
                CitationUtil.getPathToCitationStyles() + FONT_STYLES_COLLECTION_FILE));
      } else {
        InputStream inputStream =
            ResourceUtil.getResourceAsStream(
                CitationUtil.getPathToCitationStyle(cs) + FONT_STYLES_COLLECTION_FILE,
                XmlHelper.class.getClassLoader());
        // get specific FontStyleCollection for citation style if exists
        if (inputStream != null) {
          fsc.put(cs, FontStylesCollection.loadFromXml(inputStream));
        }
        // otherwise: get __Default_ one
        else {
          fsc.put(cs, loadFontStylesCollection());
        }
      }
      return fsc.get(cs);
    } catch (Exception e) {
      // TODO Auto-generated catch block
      throw new RuntimeException("Cannot loadFontStylesCollection: ", e);
    }
  }
  public int totalMatches(String[] ngrams) {
    ArrayList<int[]> list = new ArrayList<int[]>(); // list to change letters into numbers
    HashMap calc = new HashMap(); // map to calculate sum of Cn2
    for (int i = 0; i < ngrams.length; i++) {
      int[] nowInts = stringToInts(ngrams[i]);
      list.add(nowInts); // loop every string,change into int[],store in arraylist
    }

    for (int j = 0; j < list.size() - 1; j++) {
      int[] first = list.get(j);
      calc.put(first, 1); // this one must be different from previous ones
      for (int k = j + 1; k < list.size(); k++) {
        int[] second = list.get(k);
        if (check(first, second)) {
          int p = calc.get(first).hashCode();
          calc.replace(first, p, p + 1); // increment of counting in the same int[]
          list.remove(second);
          k--;
          // list is shorted by removal,k should stay at the same position for next test
        }
        if (k == list.size() - 1 && check(first, second) == false) {
          calc.put(second, 1); // if the last one is not the same as last-1,set it as 1
        }
      }
    }
    int totalMatches = calculation(calc);
    return totalMatches;
  }
Exemple #4
0
  /** @param getFailureId */
  public void alarmStat(String getFailureId, boolean callBackFlag) {

    String failureId = null;
    String loseMailId = null;
    for (String tempId : getFailureId.split(",+")) {
      if (hashMap.containsKey(tempId)) {
        if (hashMap.get(tempId) + 1 >= Integer.parseInt(SenderConfig.getProp("sendFailureTimes"))) {
          loseMailId = loseMailId == null ? tempId : loseMailId + "," + tempId;
          hashMap.remove(tempId);
          if (callBackFlag) {
            FailureNotifier.notifier(tempId);
            log.error("[lose mailID]" + " [" + tempId + "]");
          }
        } else {
          failureId = failureId == null ? tempId : failureId + "," + tempId;
          hashMap.put(tempId, hashMap.get(tempId) + 1);
        }
      } else {
        failureId = failureId == null ? tempId : failureId + "," + tempId;
        hashMap.put(tempId, 1);
      }
    }
    if (failureId != null && callBackFlag) {
      log.info("[wait for sending again]" + " [" + failureId + "]");
      callBack(failureId);
    }
    if (loseMailId != null) {
      alarm(loseMailId);
    }
  }
  /**
   * A method to build four coordinates representing a bounding box given a start coordinate and a
   * distance
   *
   * @param latitude a latitude coordinate in decimal notation
   * @param longitude a longitude coordinate in decimal notation
   * @param distance the distance to add in metres
   * @return a hashMap representing the bounding box (NE,SE,SW,NW)
   */
  public static java.util.HashMap<String, Coordinate> getBoundingBox(
      float latitude, float longitude, int distance) {

    // check on the parameters
    if (isValidLatitude(latitude) == false
        || isValidLongitude(longitude) == false
        || distance <= 0) {
      throw new IllegalArgumentException("All parameters are required and must be valid");
    }

    // convert the distance from metres to kilometers
    float kilometers = distance / 1000;

    // declare helper variables
    java.util.HashMap<String, Coordinate> boundingBox = new java.util.HashMap<String, Coordinate>();

    // calculate the coordinates
    Coordinate north = addDistanceNorth(latitude, longitude, distance);
    Coordinate south = addDistanceSouth(latitude, longitude, distance);
    Coordinate east = addDistanceEast(latitude, longitude, distance);
    Coordinate west = addDistanceWest(latitude, longitude, distance);

    // build the bounding box object
    boundingBox.put("NE", new Coordinate(north.getLatitude(), east.getLongitude()));
    boundingBox.put("SE", new Coordinate(south.getLatitude(), east.getLongitude()));
    boundingBox.put("SW", new Coordinate(south.getLatitude(), west.getLongitude()));
    boundingBox.put("NW", new Coordinate(north.getLatitude(), west.getLongitude()));

    // return the bounding box object
    return boundingBox;
  }
  @Test
  public void testNoApiLimitOnRootAdmin() throws Exception {
    // issue list Accounts calls
    final HashMap<String, String> params = new HashMap<String, String>();
    params.put("response", "json");
    params.put("listAll", "true");
    params.put("sessionkey", sessionKey);
    // assuming ApiRateLimitService set api.throttling.max = 25
    int clientCount = 26;
    Runnable[] clients = new Runnable[clientCount];
    final boolean[] isUsable = new boolean[clientCount];

    final CountDownLatch startGate = new CountDownLatch(1);

    final CountDownLatch endGate = new CountDownLatch(clientCount);

    for (int i = 0; i < isUsable.length; ++i) {
      final int j = i;
      clients[j] =
          new Runnable() {

            /** {@inheritDoc} */
            @Override
            public void run() {
              try {
                startGate.await();

                sendRequest("listAccounts", params);

                isUsable[j] = true;

              } catch (CloudRuntimeException e) {
                isUsable[j] = false;
                e.printStackTrace();
              } catch (InterruptedException e) {
                e.printStackTrace();
              } finally {
                endGate.countDown();
              }
            }
          };
    }

    ExecutorService executor = Executors.newFixedThreadPool(clientCount);

    for (Runnable runnable : clients) {
      executor.execute(runnable);
    }

    startGate.countDown();

    endGate.await();

    int rejectCount = 0;
    for (int i = 0; i < isUsable.length; ++i) {
      if (!isUsable[i]) rejectCount++;
    }

    assertEquals("No request should be rejected!", 0, rejectCount);
  }
  public ActionForward updateAppointmentReason(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {
    HashMap<String, Object> hashMap = new HashMap<String, Object>();

    OscarAppointmentDao appointmentDao =
        (OscarAppointmentDao) SpringUtils.getBean("oscarAppointmentDao");

    Appointment appointment =
        appointmentDao.find(Integer.parseInt(request.getParameter("appointmentNo")));

    if (appointment != null) {
      appointment.setReason(request.getParameter("reason"));
      appointmentDao.merge(appointment);

      hashMap.put("success", true);
      hashMap.put("appointmentNo", appointment.getId());
    }

    JsonConfig config = new JsonConfig();
    config.registerJsonBeanProcessor(java.sql.Date.class, new JsDateJsonBeanProcessor());

    JSONObject json = JSONObject.fromObject(hashMap, config);
    response.getOutputStream().write(json.toString().getBytes());

    return null;
  }
Exemple #8
0
  public static List<String> findTopKWinner(int time, Vector<LogEntry> logs, int k) {
    List<String> result = new ArrayList<String>();

    HashMap<String, Integer> map = new HashMap<String, Integer>();
    for (LogEntry log : logs) {
      if (log.time <= time) {
        if (map.containsKey(log.candidate)) map.put(log.candidate, map.get(log.candidate) + 1);
        else map.put(log.candidate, 1);
      }
    }

    ArrayList<Integer> a = new ArrayList<Integer>();
    for (String str : map.keySet()) a.add(map.get(str));

    // find top K in a

    // method1: Using PriorityQuene.  time complexity: (nlgn+k)

    // method2: Using quick select

    quickSelect(a, 0, a.size() - 1, a.size() - k + 1);
    System.out.println(a);

    for (int i = a.size() - k; i < a.size(); i++) {
      int value = a.get(i);
      for (String str : map.keySet()) {
        if (map.get(str) == value) result.add(str);
      }
    }

    return result;
  }
 public void assertAll(Iterable<Diagnostic> asserted, DiagnosticPredicate predicates[]) {
   HashMap<DiagnosticPredicate, Boolean> consumed = new HashMap<DiagnosticPredicate, Boolean>();
   for (DiagnosticPredicate p : predicates) consumed.put(p, Boolean.FALSE);
   for (Diagnostic d : asserted) {
     boolean found = false;
     for (Entry<DiagnosticPredicate, Boolean> e : consumed.entrySet())
       if ((!e.getValue() || e.getKey().isGreedy()) && e.getKey().apply(d)) {
         consumed.put(e.getKey(), Boolean.TRUE);
         found = true;
         break;
       }
     if (!found) {
       if (predicates.length == 1)
         throw new ComparisonFailure(
             "Predicate does not match", predicates[0].toString(), diagnosticsToString(d));
       throw new ComparisonFailure(
           "No predicate in expected matches",
           Arrays.toString(predicates),
           diagnosticsToString(d));
     }
   }
   ArrayList<DiagnosticPredicate> unconsumed = new ArrayList<DiagnosticPredicate>();
   for (Entry<DiagnosticPredicate, Boolean> e : consumed.entrySet())
     if (!e.getValue() && e.getKey().isRequired()) unconsumed.add(e.getKey());
   if (unconsumed.size() != 0)
     throw new ComparisonFailure(
         "Missing diagnostics for required predicates",
         Arrays.toString(unconsumed.toArray()),
         diagnosticsToString(asserted));
 }
  @Test
  public void testDocumentationExample() throws Exception {

    initTestData();

    String script =
        "term = _index['float_payload_field'].get('b',"
            + includeAllFlag
            + "); payloadSum=0; for (pos in term) {payloadSum = pos.payloadAsInt(0)}; payloadSum";

    // non existing field: sum should be 0
    HashMap<String, Object> zeroArray = new HashMap<>();
    zeroArray.put("1", 0);
    zeroArray.put("2", 0);
    zeroArray.put("3", 0);
    checkValueInEachDoc(script, zeroArray, 3);

    script =
        "term = _index['int_payload_field'].get('b',"
            + includeAllFlag
            + "); payloadSum=0; for (pos in term) {payloadSum = payloadSum + pos.payloadAsInt(0)}; payloadSum";

    // existing field: sums should be as here:
    zeroArray.put("1", 5);
    zeroArray.put("2", 3);
    zeroArray.put("3", 1);
    checkValueInEachDoc(script, zeroArray, 3);
  }
  /**
   * Constructor. The first time an RJavaClassLoader is created, it is cached as the primary loader.
   *
   * @param path path of the rJava package
   * @param libpath lib sub directory of the rJava package
   */
  public RJavaClassLoader(String path, String libpath) {
    super(new URL[] {});
    // respect rJava.debug level
    String rjd = System.getProperty("rJava.debug");
    if (rjd != null && rjd.length() > 0 && !rjd.equals("0")) verbose = true;
    if (verbose) System.out.println("RJavaClassLoader(\"" + path + "\",\"" + libpath + "\")");
    if (primaryLoader == null) {
      primaryLoader = this;
      if (verbose) System.out.println(" - primary loader");
    } else {
      if (verbose)
        System.out.println(" - NOT primrary (this=" + this + ", primary=" + primaryLoader + ")");
    }
    libMap = new HashMap /*<String,UnixFile>*/();

    classPath = new Vector /*<UnixFile>*/();
    classPath.add(new UnixDirectory(path + "/java"));

    rJavaPath = path;
    rJavaLibPath = libpath;

    /* load the rJava library */
    UnixFile so = new UnixFile(rJavaLibPath + "/rJava.so");
    if (!so.exists()) so = new UnixFile(rJavaLibPath + "/rJava.dll");
    if (so.exists()) libMap.put("rJava", so);

    /* load the jri library */
    UnixFile jri = new UnixFile(path + "/jri/libjri.so");
    String rarch = System.getProperty("r.arch");
    if (rarch != null && rarch.length() > 0) {
      UnixFile af = new UnixFile(path + "/jri" + rarch + "/libjri.so");
      if (af.exists()) jri = af;
      else {
        af = new UnixFile(path + "/jri" + rarch + "/jri.dll");
        if (af.exists()) jri = af;
      }
    }
    if (!jri.exists()) jri = new UnixFile(path + "/jri/libjri.jnilib");
    if (!jri.exists()) jri = new UnixFile(path + "/jri/jri.dll");
    if (jri.exists()) {
      libMap.put("jri", jri);
      if (verbose) System.out.println(" - registered JRI: " + jri);
    }

    /* if we are the primary loader, make us the context loader so
    projects that rely on the context loader pick us */
    if (primaryLoader == this) Thread.currentThread().setContextClassLoader(this);

    if (verbose) {
      System.out.println("RJavaClassLoader initialized.\n\nRegistered libraries:");
      for (Iterator entries = libMap.keySet().iterator(); entries.hasNext(); ) {
        Object key = entries.next();
        System.out.println("  " + key + ": '" + libMap.get(key) + "'");
      }
      System.out.println("\nRegistered class paths:");
      for (Enumeration e = classPath.elements(); e.hasMoreElements(); )
        System.out.println("  '" + e.nextElement() + "'");
      System.out.println("\n-- end of class loader report --");
    }
  }
Exemple #12
0
 public int lengthOfLongestSubstring(String s) {
   if (s == null || s.length() <= 0) return 0;
   HashMap<Character, Integer> map = new HashMap<Character, Integer>();
   int result = 1;
   int setSize = 1; // 窗口[i,j]中字符种类数
   int i = 0;
   int j = 0;
   map.put(s.charAt(i), 1);
   while (j < s.length()) {
     System.out.println(i + " " + j + " " + setSize + " " + (setSize == j - i + 1));
     if (j - i + 1 == setSize) { // substring without repeating characters
       if (j - i + 1 > result) result = j - i + 1;
       if (++j >= s.length()) break;
       Integer t = map.get(s.charAt(j));
       if (t == null || t == 0) setSize++;
       map.put(s.charAt(j), t == null ? 1 : t + 1);
     } else { // substring with repeating characters
       Integer t = map.get(s.charAt(i));
       if (t == 1) setSize--;
       map.put(s.charAt(i), t - 1);
       i++;
     }
   }
   return result;
 }
  /** Tests partition operations */
  @Test
  public void testPartitionOps()
      throws MetaException, InvalidObjectException, NoSuchObjectException, InvalidInputException {
    Database db1 = new Database(DB1, "description", "locationurl", null);
    objectStore.createDatabase(db1);
    StorageDescriptor sd =
        new StorageDescriptor(
            null,
            "location",
            null,
            null,
            false,
            0,
            new SerDeInfo("SerDeName", "serializationLib", null),
            null,
            null,
            null);
    HashMap<String, String> tableParams = new HashMap<String, String>();
    tableParams.put("EXTERNAL", "false");
    FieldSchema partitionKey1 = new FieldSchema("Country", "String", "");
    FieldSchema partitionKey2 = new FieldSchema("State", "String", "");
    Table tbl1 =
        new Table(
            TABLE1,
            DB1,
            "owner",
            1,
            2,
            3,
            sd,
            Arrays.asList(partitionKey1, partitionKey2),
            tableParams,
            "viewOriginalText",
            "viewExpandedText",
            "MANAGED_TABLE");
    objectStore.createTable(tbl1);
    HashMap<String, String> partitionParams = new HashMap<String, String>();
    partitionParams.put("PARTITION_LEVEL_PRIVILEGE", "true");
    List<String> value1 = Arrays.asList("US", "CA");
    Partition part1 = new Partition(value1, DB1, TABLE1, 111, 111, sd, partitionParams);
    objectStore.addPartition(part1);
    List<String> value2 = Arrays.asList("US", "MA");
    Partition part2 = new Partition(value2, DB1, TABLE1, 222, 222, sd, partitionParams);
    objectStore.addPartition(part2);

    Deadline.startTimer("getPartition");
    List<Partition> partitions = objectStore.getPartitions(DB1, TABLE1, 10);
    Assert.assertEquals(2, partitions.size());
    Assert.assertEquals(111, partitions.get(0).getCreateTime());
    Assert.assertEquals(222, partitions.get(1).getCreateTime());

    objectStore.dropPartition(DB1, TABLE1, value1);
    partitions = objectStore.getPartitions(DB1, TABLE1, 10);
    Assert.assertEquals(1, partitions.size());
    Assert.assertEquals(222, partitions.get(0).getCreateTime());

    objectStore.dropPartition(DB1, TABLE1, value2);
    objectStore.dropTable(DB1, TABLE1);
    objectStore.dropDatabase(DB1);
  }
Exemple #14
0
  public void execute(final Context context, boolean force) {
    if (this.enabled(context) && this._action != null) {
      final Trigger me = this;

      Runnable r =
          new Runnable() {
            public void run() {
              try {
                BaseScriptEngine.runScript(context, me._action);
              } catch (Exception e) {
                LogManager.getInstance(context).logException(e);

                HashMap<String, Object> payload = new HashMap<String, Object>();
                payload.put("script", me._action);

                LogManager.getInstance(context).log("failed_trigger_script", payload);
              }
            }
          };

      Thread t = new Thread(new ThreadGroup("Triggers"), r, this.name(), 32768);
      t.start();

      HashMap<String, Object> payload = new HashMap<String, Object>();
      payload.put("name", this.name());
      payload.put("identifier", this.identifier());
      payload.put("action", this._action);

      LogManager.getInstance(context).log("pr_trigger_fired", payload);
    }
  }
  public static void readRatingData(String fileName, String split) throws IOException {
    BufferedReader br = new BufferedReader(new FileReader(fileName));
    HashMap<String, Float> hashUserRating;
    Set<String> setMovies;
    String s = "";

    while ((s = br.readLine()) != null) {
      String[] temp = s.split(split);
      String userid = temp[0];
      String movieid = temp[1];
      float rating = Float.parseFloat(temp[2]);

      if (hashUserMovie.containsKey(userid)) {
        setMovies = hashUserMovie.get(userid);
        setMovies.add(movieid);
        hashUserMovie.put(userid, setMovies);
      } else {
        setMovies = new HashSet<String>();
        setMovies.add(movieid);
        hashUserMovie.put(userid, setMovies);
      }

      if (hashMovieUserRating.containsKey(movieid)) {
        hashUserRating = hashMovieUserRating.get(movieid);
        hashUserRating.put(userid, rating);
        hashMovieUserRating.put(movieid, hashUserRating);
      } else {
        hashUserRating = new HashMap<String, Float>();
        hashUserRating.put(userid, rating);
        hashMovieUserRating.put(movieid, hashUserRating);
      }
    }

    br.close();
  }
 /**
  * AUTOR Y FECHA CREACION: JCHAVEZ / 26-08-2013 OBTENER MONTOS TOTALES POR EMPRESA-DESCUENTA Y
  * PERIODO (ESTADO DE CUENTA - TAB TERCEROS)
  */
 public List<Descuento> getMontoTotalPorNomCptoYPeriodo(
     String strDsteCpto,
     String strNomCpto,
     Integer intPeriodo,
     Integer intMes,
     Integer intParaModalidadCod,
     String strLibEle)
     throws BusinessException {
   List<Descuento> lista = null;
   try {
     HashMap<String, Object> mapa = new HashMap<String, Object>();
     mapa.put("strDsteCpto", strDsteCpto);
     mapa.put("strNomCpto", strNomCpto);
     mapa.put("intPeriodo", intPeriodo);
     mapa.put("intMes", intMes);
     mapa.put("intParaModalidadCod", intParaModalidadCod);
     mapa.put("strLibEle", strLibEle);
     lista = dao.getMontoTotalPorNomCptoYPeriodo(mapa);
   } catch (DAOException e) {
     throw new BusinessException(e);
   } catch (Exception e) {
     throw new BusinessException(e);
   }
   return lista;
 }
  public void testRangeValidation() {
    HashMap<String, String> params = new HashMap<String, String>();
    params.put("longFoo", "200");

    HashMap<String, Object> extraContext = new HashMap<String, Object>();
    extraContext.put(ActionContext.PARAMETERS, params);

    try {
      ActionProxy proxy =
          actionProxyFactory.createActionProxy(
              "", MockConfigurationProvider.VALIDATION_ACTION_NAME, extraContext);
      proxy.execute();
      assertTrue(((ValidationAware) proxy.getAction()).hasFieldErrors());

      Map errors = ((ValidationAware) proxy.getAction()).getFieldErrors();
      List errorMessages = (List) errors.get("longFoo");
      assertEquals(1, errorMessages.size());

      String errorMessage = (String) errorMessages.get(0);
      assertNotNull(errorMessage);
    } catch (Exception e) {
      e.printStackTrace();
      fail();
    }
  }
Exemple #18
0
  public static void main(String[] args) {
    buckets = new HashMap<String, Integer>();

    String dict = "ia mbn";

    String word = "Four score and seven years ago";

    for (int i = 0; i < dict.length(); i++) {
      char x = dict.charAt(i);
      buckets.put(String.valueOf(x), new Integer(0));
    }
    StringBuilder output = new StringBuilder("");

    for (int i = 0; i < word.length(); i++) {
      String c = String.valueOf(word.charAt(i));
      if (buckets.containsKey(c)) {
        Integer bucket = buckets.get(c);
        bucket++;
        buckets.put(c, bucket);
      } else {
        output.append(c);
      }
    }
    for (int i = 0; i < dict.length(); i++) {
      String c = String.valueOf(dict.charAt(i));
      Integer k = buckets.get(c);
      for (int j = 0; j < k; j++) {
        output.append(c);
      }
    }
    System.out.println(output);
  }
  public static HashMap<String, Integer> getAnimeSearchedMAL(
      String username, String password, String anime) {
    HashMap<String, Integer> map = new HashMap<String, Integer>();

    JSONObject xmlJSONObj;
    String json = "";
    String xml = "";
    try {
      xml = searchAnimeMAL(username, password, anime);
      xmlJSONObj = XML.toJSONObject(xml);
      json = xmlJSONObj.toString(4);
    } catch (Exception e) {
      MAMUtil.writeLog(e);
      e.printStackTrace();
    }
    JsonParser parser = new JsonParser();
    JsonObject root = parser.parse(json).getAsJsonObject();
    if (root.has("anime") && root.get("anime").getAsJsonObject().get("entry").isJsonArray()) {
      JsonArray searchedAnime = root.get("anime").getAsJsonObject().get("entry").getAsJsonArray();
      for (JsonElement obj : searchedAnime) {
        String name = obj.getAsJsonObject().get("title").getAsString();
        int id = obj.getAsJsonObject().get("id").getAsInt();
        map.put(name, id);
      }
    } else if (root.has("anime")) {
      JsonObject obj = root.get("anime").getAsJsonObject().get("entry").getAsJsonObject();
      int id = obj.getAsJsonObject().get("id").getAsInt();
      map.put(anime, id);
    }
    return map;
  }
 /** Add a value with a weight to the set. */
 public void add(double value, double weight) {
   if (valueMap.containsKey(value)) {
     valueMap.put(value, valueMap.get(value) + weight);
   } else {
     valueMap.put(value, weight);
   }
 }
  @Test
  public void testGetApiLimitOnUser() throws Exception {
    // log in using normal user
    login("demo", "password");

    // issue an api call
    HashMap<String, String> params = new HashMap<String, String>();
    params.put("response", "json");
    params.put("listAll", "true");
    params.put("sessionkey", sessionKey);
    sendRequest("listAccounts", params);

    // issue get api limit calls
    final HashMap<String, String> params2 = new HashMap<String, String>();
    params2.put("response", "json");
    params2.put("sessionkey", sessionKey);
    String getResult = sendRequest("getApiLimit", params2);
    ApiLimitResponse getLimitResp =
        (ApiLimitResponse) fromSerializedString(getResult, ApiLimitResponse.class);
    assertEquals(
        "Issued api count is incorrect!",
        2,
        getLimitResp.getApiIssued()); // should be 2 apis issues plus this getlimit api
    assertEquals("Allowed api count is incorrect!", apiMax - 2, getLimitResp.getApiAllowed());
  }
  @Override
  public Long getUniqueDevicesSupportingBluetooth(
      Company company, Date eventDate, Campaign campaign, Device device) {
    String query =
        "SELECT COUNT(DISTINCT b.macAddress) FROM BluetoothSend b WHERE b.eventDate BETWEEN ?1 AND ?2 AND b.company = ?3 AND b.sendStatus in (1, 2, 3, 4, 5, 7) ";
    int paramCount = 3;
    HashMap<Integer, Object> params = new HashMap<Integer, Object>();
    if (campaign != null) {
      paramCount++;
      query += " AND b.campaign = ?" + paramCount + " ";
      params.put(paramCount, campaign);
    }
    if (device != null) {
      paramCount++;
      query += " AND b.device = ?" + paramCount + " ";
      params.put(paramCount, device);
    }
    Query q = em.createQuery(query);

    q.setParameter(1, eventDate);
    q.setParameter(2, DateUtil.getEndOfDay(eventDate));
    q.setParameter(3, company);

    for (Map.Entry<Integer, Object> entry : params.entrySet()) {
      Integer paramId = entry.getKey();
      Object object = entry.getValue();
      q.setParameter(paramId, object);
    }

    Long countResult = (Long) q.getSingleResult();
    return countResult;
  }
 static {
   sHistoryProjectionMap = new HashMap<String, String>();
   sHistoryProjectionMap.put(ChatHistoryTable._ID, ChatHistoryTable._ID);
   sHistoryProjectionMap.put(ChatHistoryTable.CHAT_ASK, ChatHistoryTable.CHAT_ASK);
   sHistoryProjectionMap.put(ChatHistoryTable.CHAT_ANSWER, ChatHistoryTable.CHAT_ANSWER);
   sHistoryProjectionMap.put(ChatHistoryTable.CHAT_TIME, ChatHistoryTable.CHAT_TIME);
 }
  @Override
  public Long getUniqueDevicesAcceptingPush(
      Company company, Date eventDate, Campaign campaign, Device device) {
    String query =
        "SELECT COUNT(DISTINCT b.macAddress) FROM BluetoothSend b WHERE (b.acceptStatus = ?1 OR b.sendStatus = ?2) AND b.eventDate BETWEEN ?3 AND ?4 AND b.company = ?5 ";
    int paramCount = 5;
    HashMap<Integer, Object> params = new HashMap<Integer, Object>();
    if (campaign != null) {
      paramCount++;
      query += " AND b.campaign = ?" + paramCount + " ";
      params.put(paramCount, campaign);
    }
    if (device != null) {
      paramCount++;
      query += " AND b.device = ?" + paramCount + " ";
      params.put(paramCount, device);
    }
    Query q = em.createQuery(query);

    q.setParameter(1, 1);
    q.setParameter(2, BluetoothSend.STATUS_ACCEPTED);
    q.setParameter(3, eventDate);
    q.setParameter(4, DateUtil.getEndOfDay(eventDate));
    q.setParameter(5, company);

    for (Map.Entry<Integer, Object> entry : params.entrySet()) {
      Integer paramId = entry.getKey();
      Object object = entry.getValue();
      q.setParameter(paramId, object);
    }

    Long countResult = (Long) q.getSingleResult();
    return countResult;
  }
Exemple #25
0
 public HashMap getAllRateCodes() {
   /**
    * Requires - Modifies - Effects -
    *
    * @throws -
    */
   Criteria objCriteria = null;
   Session objSession = null;
   Integer totRecordCount = null;
   List objList = null;
   HashMap hmResult = new HashMap();
   try {
     logger.info("GETTING ALL RATE CODES");
     objSession = HibernateUtil.getSession();
     objCriteria = objSession.createCriteria(RateCodesVO.class);
     totRecordCount = new Integer(objCriteria.list().size());
     objList = objCriteria.list();
     hmResult.put("TotalRecordCount", totRecordCount);
     hmResult.put("Records", objList);
     logger.info("GOT ALL RATE CODES");
   } catch (HibernateException e) {
     logger.error("HIBERNATE EXCEPTION DURING GET ALL RATE CODES", e);
     e.printStackTrace();
   } finally {
     if (objSession != null) {
       objSession.close();
     }
   }
   return hmResult;
 }
  @Override
  public Long getTotalContentDownloads(
      Company company, Date eventDate, Campaign campaign, Device device) {
    String query =
        "SELECT COUNT(b.id) FROM BluetoothSend b WHERE b.sendStatus = ?1 AND b.eventDate BETWEEN ?2 AND ?3 AND b.company = ?4 ";
    int paramCount = 4;
    HashMap<Integer, Object> params = new HashMap<Integer, Object>();
    if (campaign != null) {
      paramCount++;
      query += " AND b.campaign = ?" + paramCount + " ";
      params.put(paramCount, campaign);
    }
    if (device != null) {
      paramCount++;
      query += " AND b.device = ?" + paramCount + " ";
      params.put(paramCount, device);
    }

    Query q = em.createQuery(query);
    q.setParameter(1, BluetoothSend.STATUS_SENT);
    q.setParameter(2, eventDate);
    q.setParameter(3, DateUtil.getEndOfDay(eventDate));
    q.setParameter(4, company);

    for (Map.Entry<Integer, Object> entry : params.entrySet()) {
      Integer paramId = entry.getKey();
      Object object = entry.getValue();
      q.setParameter(paramId, object);
    }

    Long countResult = (Long) q.getSingleResult();
    return countResult;
  }
  /**
   * fills the list with stops from the local database
   *
   * @param db the database adapter to use
   */
  private void fillList(BusDbAdapter db) {
    Cursor c;
    if (listType == FAVORITES) {
      c = db.getFavoriteDest(NUM_ENTRIES_TO_FETCH);
    } else { // listType == MAJOR
      c = db.getMajorDest(NUM_ENTRIES_TO_FETCH);
    }
    int stopIDIndex = c.getColumnIndex("stop_id");
    int stopDescIndex = c.getColumnIndex("stop_desc");
    int routeIDIndex = c.getColumnIndex("route_id");
    int routeDescIndex = c.getColumnIndex("route_desc");
    if (c != null) {
      for (int i = 0; i < c.getCount(); i++) {
        HashMap<String, String> item = new HashMap<String, String>();

        String stopID = c.getString(stopIDIndex);
        String stopName = c.getString(stopDescIndex);
        String route = c.getString(routeIDIndex);
        String routeDesc = c.getString(routeDescIndex);
        Log.v(TAG, "PUT");
        Log.v(TAG, "stopID " + stopID + " stopName " + stopName);
        Log.v(TAG, "routeID " + route + " routeDesc" + routeDesc);
        item.put("stopID", stopID);
        item.put("stopName", stopName);
        item.put("routeID", route);
        item.put("routeDesc", routeDesc);
        c.moveToNext();
        locationList.add(item);
      }
      listAdapter.notifyDataSetChanged();
    }
  }
  @Override
  public List<BluetoothFileSendSummary> fetchBluetoothFileSendSummaries(
      Date eventDate, Company company, Campaign campaign, Device device) {
    String query =
        "SELECT b FROM BluetoothFileSendSummary b WHERE b.eventDate BETWEEN ?1 AND ?2 AND b.company = ?3 ";
    int paramCount = 3;
    HashMap<Integer, Object> params = new HashMap<Integer, Object>();
    if (campaign != null) {
      paramCount++;
      query += " AND b.campaign = ?" + paramCount + " ";
      params.put(paramCount, campaign);
    }
    if (device != null) {
      paramCount++;
      query += " AND b.device = ?" + paramCount + " ";
      params.put(paramCount, device);
    }

    Query q = em.createQuery(query);
    q.setParameter(1, eventDate);
    q.setParameter(2, DateUtil.getEndOfDay(eventDate));
    q.setParameter(3, company);

    for (Map.Entry<Integer, Object> entry : params.entrySet()) {
      Integer paramId = entry.getKey();
      Object object = entry.getValue();
      q.setParameter(paramId, object);
    }

    List<BluetoothFileSendSummary> results = (List<BluetoothFileSendSummary>) q.getResultList();
    return results;
  }
  @GET
  @Path("/{reviewId}")
  @Timed(name = "view-book-by-reviewId")
  public Response viewBookReview(
      @PathParam("isbn") LongParam isbn, @PathParam("reviewId") IntParam reviewId) {

    Book book = bookRepository.getBookByISBN(isbn.get());

    ReviewDto reviewResponse = null;
    List<Review> reviewList = book.getReview();

    List<Review> tempList = new ArrayList<Review>();
    for (Review reviewObj : reviewList) {

      if (reviewObj.getId() == reviewId.get()) tempList.add(reviewObj);
    }
    reviewResponse = new ReviewDto(tempList);
    String location = "/books/" + book.getIsbn() + "/reviews/";

    HashMap<String, Object> map = new HashMap<String, Object>();

    Review review = reviewResponse.getReviewList().get(0);
    map.put("review", review);
    reviewResponse.addLink(new LinkDto("view-review", location + reviewId.get(), "GET"));
    map.put("links", reviewResponse.getLinks());
    return Response.status(200).entity(map).build();
  }
  public static void NIOReadTest() {
    long st = System.currentTimeMillis();
    String fileName = "/data/glassfish/bak/CS_AIU_MM/CITY_86020/combine.dat";
    int rNum = 700;
    HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();
    for (int i = 0; i < rNum; i++) hm.put(i, 0);
    int cc = 0;
    try {
      List<String> lines = Files.readAllLines(Paths.get(fileName), Charset.defaultCharset());
      for (String line : lines) {
        String r[] = StrUtils.split(line, ",");
        int salt = generatetRowKeySalt(r, 14, rNum);
        if (salt != -1) {
          int counter = hm.get(salt);
          counter++;
          hm.put(salt, counter);
        } else cc++;
      }

      long et = System.currentTimeMillis();
      System.out.println("UsedTime:" + (et - st));
    } catch (IOException e) {
      e.printStackTrace();
    }
  }